mirror of https://github.com/vladmandic/human
4342 lines
1.0 MiB
4342 lines
1.0 MiB
|
|
/*
|
|
Human library
|
|
homepage: <https://github.com/vladmandic/human>
|
|
author: <https://github.com/vladmandic>'
|
|
*/
|
|
|
|
var F3=Object.create,Mh=Object.defineProperty,O3=Object.getPrototypeOf,P3=Object.prototype.hasOwnProperty,M3=Object.getOwnPropertyNames,L3=Object.getOwnPropertyDescriptor;var z3=r=>Mh(r,"__esModule",{value:!0});var Wr=(r,e)=>()=>(e||(e={exports:{}},r(e.exports,e)),e.exports),Ke=(r,e)=>{for(var t in e)Mh(r,t,{get:e[t],enumerable:!0})},B3=(r,e,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of M3(e))!P3.call(r,o)&&o!=="default"&&Mh(r,o,{get:()=>e[o],enumerable:!(t=L3(e,o))||t.enumerable});return r},Tc=r=>B3(z3(Mh(r!=null?F3(O3(r)):{},"default",r&&r.__esModule&&"default"in r?{get:()=>r.default,enumerable:!0}:{value:r,enumerable:!0})),r);var U0=Wr(()=>{});var IN=Wr((CN,Lw)=>{(function(r,e,t){function o(i){var l=this,u=a();l.next=function(){var c=2091639*l.s0+l.c*23283064365386963e-26;return l.s0=l.s1,l.s1=l.s2,l.s2=c-(l.c=c|0)},l.c=1,l.s0=u(" "),l.s1=u(" "),l.s2=u(" "),l.s0-=u(i),l.s0<0&&(l.s0+=1),l.s1-=u(i),l.s1<0&&(l.s1+=1),l.s2-=u(i),l.s2<0&&(l.s2+=1),u=null}function n(i,l){return l.c=i.c,l.s0=i.s0,l.s1=i.s1,l.s2=i.s2,l}function s(i,l){var u=new o(i),c=l&&l.state,p=u.next;return p.int32=function(){return u.next()*4294967296|0},p.double=function(){return p()+(p()*2097152|0)*11102230246251565e-32},p.quick=p,c&&(typeof c=="object"&&n(c,u),p.state=function(){return n(u,{})}),p}function a(){var i=4022871197,l=function(u){u=u.toString();for(var c=0;c<u.length;c++){i+=u.charCodeAt(c);var p=.02519603282416938*i;i=p>>>0,p-=i,p*=i,i=p>>>0,p-=i,i+=p*4294967296}return(i>>>0)*23283064365386963e-26};return l}e&&e.exports?e.exports=s:t&&t.amd?t(function(){return s}):this.alea=s})(CN,typeof Lw=="object"&&Lw,typeof define=="function"&&define)});var SN=Wr((NN,zw)=>{(function(r,e,t){function o(a){var i=this,l="";i.x=0,i.y=0,i.z=0,i.w=0,i.next=function(){var c=i.x^i.x<<11;return i.x=i.y,i.y=i.z,i.z=i.w,i.w^=i.w>>>19^c^c>>>8},a===(a|0)?i.x=a:l+=a;for(var u=0;u<l.length+64;u++)i.x^=l.charCodeAt(u)|0,i.next()}function n(a,i){return i.x=a.x,i.y=a.y,i.z=a.z,i.w=a.w,i}function s(a,i){var l=new o(a),u=i&&i.state,c=function(){return(l.next()>>>0)/4294967296};return c.double=function(){do var p=l.next()>>>11,m=(l.next()>>>0)/4294967296,f=(p+m)/(1<<21);while(f===0);return f},c.int32=l.next,c.quick=c,u&&(typeof u=="object"&&n(u,l),c.state=function(){return n(l,{})}),c}e&&e.exports?e.exports=s:t&&t.amd?t(function(){return s}):this.xor128=s})(NN,typeof zw=="object"&&zw,typeof define=="function"&&define)});var AN=Wr((TN,Bw)=>{(function(r,e,t){function o(a){var i=this,l="";i.next=function(){var c=i.x^i.x>>>2;return i.x=i.y,i.y=i.z,i.z=i.w,i.w=i.v,(i.d=i.d+362437|0)+(i.v=i.v^i.v<<4^(c^c<<1))|0},i.x=0,i.y=0,i.z=0,i.w=0,i.v=0,a===(a|0)?i.x=a:l+=a;for(var u=0;u<l.length+64;u++)i.x^=l.charCodeAt(u)|0,u==l.length&&(i.d=i.x<<10^i.x>>>4),i.next()}function n(a,i){return i.x=a.x,i.y=a.y,i.z=a.z,i.w=a.w,i.v=a.v,i.d=a.d,i}function s(a,i){var l=new o(a),u=i&&i.state,c=function(){return(l.next()>>>0)/4294967296};return c.double=function(){do var p=l.next()>>>11,m=(l.next()>>>0)/4294967296,f=(p+m)/(1<<21);while(f===0);return f},c.int32=l.next,c.quick=c,u&&(typeof u=="object"&&n(u,l),c.state=function(){return n(l,{})}),c}e&&e.exports?e.exports=s:t&&t.amd?t(function(){return s}):this.xorwow=s})(TN,typeof Bw=="object"&&Bw,typeof define=="function"&&define)});var DN=Wr((EN,Vw)=>{(function(r,e,t){function o(a){var i=this;i.next=function(){var u=i.x,c=i.i,p,m,f;return p=u[c],p^=p>>>7,m=p^p<<24,p=u[c+1&7],m^=p^p>>>10,p=u[c+3&7],m^=p^p>>>3,p=u[c+4&7],m^=p^p<<7,p=u[c+7&7],p=p^p<<13,m^=p^p<<9,u[c]=m,i.i=c+1&7,m};function l(u,c){var p,m,f=[];if(c===(c|0))m=f[0]=c;else for(c=""+c,p=0;p<c.length;++p)f[p&7]=f[p&7]<<15^c.charCodeAt(p)+f[p+1&7]<<13;for(;f.length<8;)f.push(0);for(p=0;p<8&&f[p]===0;++p);for(p==8?m=f[7]=-1:m=f[p],u.x=f,u.i=0,p=256;p>0;--p)u.next()}l(i,a)}function n(a,i){return i.x=a.x.slice(),i.i=a.i,i}function s(a,i){a==null&&(a=+new Date);var l=new o(a),u=i&&i.state,c=function(){return(l.next()>>>0)/4294967296};return c.double=function(){do var p=l.next()>>>11,m=(l.next()>>>0)/4294967296,f=(p+m)/(1<<21);while(f===0);return f},c.int32=l.next,c.quick=c,u&&(u.x&&n(u,l),c.state=function(){return n(l,{})}),c}e&&e.exports?e.exports=s:t&&t.amd?t(function(){return s}):this.xorshift7=s})(EN,typeof Vw=="object"&&Vw,typeof define=="function"&&define)});var RN=Wr(($N,Gw)=>{(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<y;++d)c&&(m^=c.charCodeAt((d+32)%c.length)),d===0&&(h=m),m^=m<<10,m^=m>>>15,m^=m<<4,m^=m>>>13,d>=0&&(h=h+1640531527|0,p=g[d&127]^=m+h,f=p==0?f+1:0);for(f>=128&&(g[(c&&c.length||0)&127]=-1),f=127,d=4*128;d>0;--d)m=g[f+34&127],p=g[f=f+1&127],m^=m<<13,p^=p<<17,m^=m>>>15,p^=p>>>12,g[f]=m^p;u.w=h,u.X=g,u.i=f}l(i,a)}function n(a,i){return i.i=a.i,i.w=a.w,i.X=a.X.slice(),i}function s(a,i){a==null&&(a=+new Date);var l=new o(a),u=i&&i.state,c=function(){return(l.next()>>>0)/4294967296};return c.double=function(){do var p=l.next()>>>11,m=(l.next()>>>0)/4294967296,f=(p+m)/(1<<21);while(f===0);return f},c.int32=l.next,c.quick=c,u&&(u.X&&n(u,l),c.state=function(){return n(l,{})}),c}e&&e.exports?e.exports=s:t&&t.amd?t(function(){return s}):this.xor4096=s})($N,typeof Gw=="object"&&Gw,typeof define=="function"&&define)});var ON=Wr((FN,Ww)=>{(function(r,e,t){function o(a){var i=this,l="";i.next=function(){var c=i.b,p=i.c,m=i.d,f=i.a;return c=c<<25^c>>>7^p,p=p-m|0,m=m<<24^m>>>8^f,f=f-c|0,i.b=c=c<<20^c>>>12^p,i.c=p=p-m|0,i.d=m<<16^p>>>16^f,i.a=f-c|0},i.a=0,i.b=0,i.c=2654435769|0,i.d=1367130551,a===Math.floor(a)?(i.a=a/4294967296|0,i.b=a|0):l+=a;for(var u=0;u<l.length+20;u++)i.b^=l.charCodeAt(u)|0,i.next()}function n(a,i){return i.a=a.a,i.b=a.b,i.c=a.c,i.d=a.d,i}function s(a,i){var l=new o(a),u=i&&i.state,c=function(){return(l.next()>>>0)/4294967296};return c.double=function(){do var p=l.next()>>>11,m=(l.next()>>>0)/4294967296,f=(p+m)/(1<<21);while(f===0);return f},c.int32=l.next,c.quick=c,u&&(typeof u=="object"&&n(u,l),c.state=function(){return n(l,{})}),c}e&&e.exports?e.exports=s:t&&t.amd?t(function(){return s}):this.tychei=s})(FN,typeof Ww=="object"&&Ww,typeof define=="function"&&define)});var PN=Wr(()=>{});var MN=Wr((Qxe,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,v){var D=[];k=k==!0?{entropy:!0}:k||{};var A=g(h(k.entropy?[w,b(r)]:w==null?y():w,3),D),R=new f(D),P=function(){for(var L=R.g(n),G=i,j=0;L<l;)L=(L+j)*o,G*=o,j=R.g(1);for(;L>=u;)L/=2,G/=2,j>>>=1;return(L+j)/G};return P.int32=function(){return R.g(4)|0},P.quick=function(){return R.g(4)/4294967296},P.double=P,g(b(R.S),r),(k.pass||v||function(L,G,j,U){return U&&(U.S&&d(U,R),L.state=function(){return d(R,{})}),j?(e[a]=L,G):L})(P,A,"global"in k?k.global:this==e,k.state)}e["seed"+a]=m;function f(w){var k,v=w.length,D=this,A=0,R=D.i=D.j=0,P=D.S=[];for(v||(w=[v++]);A<o;)P[A]=A++;for(A=0;A<o;A++)P[A]=P[R=c&R+w[A%v]+(k=P[A])],P[R]=k;(D.g=function(L){for(var G,j=0,U=D.i,H=D.j,q=D.S;L--;)G=q[U=c&U+1],j=j*o+q[c&(q[U]=q[H=c&H+G])+(q[H]=G)];return D.i=U,D.j=H,j})(o)}function d(w,k){return k.i=w.i,k.j=w.j,k.S=w.S.slice(),k}function h(w,k){var v=[],D=typeof w,A;if(k&&D=="object")for(A in w)try{v.push(h(w[A],k-1))}catch(R){}return v.length?v:D=="string"?w:w+"\0"}function g(w,k){for(var v=w+"",D,A=0;A<v.length;)k[c&A]=c&(D^=k[c&A]*19)+v.charCodeAt(A++);return b(k)}function y(){try{var w;return p&&(w=p.randomBytes)?w=w(o):(w=new Uint8Array(o),(t.crypto||t.msCrypto).getRandomValues(w)),b(w)}catch(D){var k=t.navigator,v=k&&k.plugins;return[+new Date,t,v,t.screen,b(r)]}}function b(w){return String.fromCharCode.apply(0,w)}if(g(e.random(),r),typeof ig=="object"&&ig.exports){ig.exports=m;try{p=PN()}catch(w){}}else typeof define=="function"&&define.amd&&define(function(){return m})})([],Math)});var Gm=Wr((eye,LN)=>{var hj=IN(),gj=SN(),xj=AN(),yj=DN(),bj=RN(),wj=ON(),$u=MN();$u.alea=hj;$u.xor128=gj;$u.xorwow=xj;$u.xorshift7=yj;$u.xor4096=bj;$u.tychei=wj;LN.exports=$u});var vp=Wr(()=>{});var mO=Wr(()=>{});var fO=Wr(()=>{});var dO=Wr((ex,tC)=>{var rC=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 J.buffer!=je&&rr(J.buffer),ut}function o(){return J.buffer!=je&&rr(J.buffer),mt}function n(){return J.buffer!=je&&rr(J.buffer),Kt}function s(){return J.buffer!=je&&rr(J.buffer),to}function a(){return J.buffer!=je&&rr(J.buffer),jo}var i=typeof e!="undefined"?e:{},l,u;i.ready=new Promise(function(I,$){l=I,u=$});var c={},p;for(p in i)i.hasOwnProperty(p)&&(c[p]=i[p]);var m=[],f="./this.program",d=function(I,$){throw $},h=!1,g=!1,y=!1,b=!1;h=typeof window=="object",g=typeof importScripts=="function",y=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",b=!h&&!y&&!g;var w=i.ENVIRONMENT_IS_PTHREAD||!1;w&&(je=i.buffer);var k="";function v(I){return i.locateFile?i.locateFile(I,k):k+I}var D,A,R,P,L,G;if(y){g?k=vp().dirname(k)+"/":k=__dirname+"/",D=function($,B){return L||(L=require("fs")),G||(G=vp()),$=G.normalize($),L.readFileSync($,B?null:"utf8")},R=function($){var B=D($,!0);return B.buffer||(B=new Uint8Array(B)),fe(B.buffer),B},process.argv.length>1&&(f=process.argv[1].replace(/\\/g,"/")),m=process.argv.slice(2),process.on("uncaughtException",function(I){if(!(I instanceof lm))throw I}),process.on("unhandledRejection",Zi),d=function(I){process.exit(I)},i.inspect=function(){return"[Emscripten Module object]"};var j;try{j=mO()}catch(I){throw console.error('The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?'),I}global.Worker=j.Worker}else b?(typeof read!="undefined"&&(D=function($){return read($)}),R=function($){var B;return typeof readbuffer=="function"?new Uint8Array(readbuffer($)):(B=read($,"binary"),fe(typeof B=="object"),B)},typeof scriptArgs!="undefined"?m=scriptArgs:typeof arguments!="undefined"&&(m=arguments),typeof quit=="function"&&(d=function(I){quit(I)}),typeof print!="undefined"&&(typeof console=="undefined"&&(console={}),console.log=print,console.warn=console.error=typeof printErr!="undefined"?printErr:print)):(h||g)&&(g?k=self.location.href:typeof document!="undefined"&&document.currentScript&&(k=document.currentScript.src),typeof r!="undefined"&&r&&(k=r),k.indexOf("blob:")!==0?k=k.substr(0,k.lastIndexOf("/")+1):k="",y?(D=function($,B){return L||(L=require("fs")),G||(G=vp()),$=G.normalize($),L.readFileSync($,B?null:"utf8")},R=function($){var B=D($,!0);return B.buffer||(B=new Uint8Array(B)),fe(B.buffer),B}):(D=function(I){var $=new XMLHttpRequest;return $.open("GET",I,!1),$.send(null),$.responseText},g&&(R=function(I){var $=new XMLHttpRequest;return $.open("GET",I,!1),$.responseType="arraybuffer",$.send(null),new Uint8Array($.response)}),A=function(I,$,B){var K=new XMLHttpRequest;K.open("GET",I,!0),K.responseType="arraybuffer",K.onload=function(){if(K.status==200||K.status==0&&K.response){$(K.response);return}B()},K.onerror=B,K.send(null)}),P=function(I){document.title=I});y&&typeof performance=="undefined"&&(global.performance=fO().performance);var U=i.print||console.log.bind(console),H=i.printErr||console.warn.bind(console);for(p in c)c.hasOwnProperty(p)&&(i[p]=c[p]);c=null,i.arguments&&(m=i.arguments),i.thisProgram&&(f=i.thisProgram),i.quit&&(d=i.quit);var q=Atomics.load,X=Atomics.store,oe=Atomics.compareExchange,Y;i.wasmBinary&&(Y=i.wasmBinary);var re=i.noExitRuntime||!0;typeof WebAssembly!="object"&&Zi("no native wasm support detected");var J,ie,ue=!1,ae;function fe(I,$){I||Zi("Assertion failed: "+$)}function de(I){var $=i["_"+I];return fe($,"Cannot call unknown function "+I+", make sure it is exported"),$}function xe(I,$,B,K,be){var he={string:function(Gr){var Sc=0;if(Gr!=null&&Gr!==0){var t0=(Gr.length<<2)+1;Sc=Cc(t0),qe(Gr,Sc,t0)}return Sc},array:function(Gr){var Sc=Cc(Gr.length);return Tt(Gr,Sc),Sc}};function ye(Gr){return $==="string"?Ne(Gr):$==="boolean"?Boolean(Gr):Gr}var Te=de(I),wt=[],br=0;if(K)for(var mr=0;mr<K.length;mr++){var Ya=he[B[mr]];Ya?(br===0&&(br=am()),wt[mr]=Ya(K[mr])):wt[mr]=K[mr]}var Nc=Te.apply(null,wt);return Nc=ye(Nc),br!==0&&vc(br),Nc}function we(I,$,B,K){B=B||[];var be=B.every(function(ye){return ye==="number"}),he=$!=="string";return he&&be&&!K?de(I):function(){return xe(I,$,B,arguments,K)}}function De(I,$,B){for(var K=$+B,be="";!($>=K);){var he=I[$++];if(!he)return be;if(!(he&128)){be+=String.fromCharCode(he);continue}var ye=I[$++]&63;if((he&224)==192){be+=String.fromCharCode((he&31)<<6|ye);continue}var Te=I[$++]&63;if((he&240)==224?he=(he&15)<<12|ye<<6|Te:he=(he&7)<<18|ye<<12|Te<<6|I[$++]&63,he<65536)be+=String.fromCharCode(he);else{var wt=he-65536;be+=String.fromCharCode(55296|wt>>10,56320|wt&1023)}}return be}function Ne(I,$){return I?De(o(),I,$):""}function ze(I,$,B,K){if(!(K>0))return 0;for(var be=B,he=B+K-1,ye=0;ye<I.length;++ye){var Te=I.charCodeAt(ye);if(Te>=55296&&Te<=57343){var wt=I.charCodeAt(++ye);Te=65536+((Te&1023)<<10)|wt&1023}if(Te<=127){if(B>=he)break;$[B++]=Te}else if(Te<=2047){if(B+1>=he)break;$[B++]=192|Te>>6,$[B++]=128|Te&63}else if(Te<=65535){if(B+2>=he)break;$[B++]=224|Te>>12,$[B++]=128|Te>>6&63,$[B++]=128|Te&63}else{if(B+3>=he)break;$[B++]=240|Te>>18,$[B++]=128|Te>>12&63,$[B++]=128|Te>>6&63,$[B++]=128|Te&63}}return $[B]=0,B-be}function qe(I,$,B){return ze(I,o(),$,B)}function it(I){for(var $=0,B=0;B<I.length;++B){var K=I.charCodeAt(B);K>=55296&&K<=57343&&(K=65536+((K&1023)<<10)|I.charCodeAt(++B)&1023),K<=127?++$:K<=2047?$+=2:K<=65535?$+=3:$+=4}return $}function Tt(I,$){t().set(I,$)}function At(I,$){return I%$>0&&(I+=$-I%$),I}var je,ut,mt,Pt,xo,Kt,to,Dr,jo;function rr(I){je=I,i.HEAP8=ut=new Int8Array(I),i.HEAP16=Pt=new Int16Array(I),i.HEAP32=Kt=new Int32Array(I),i.HEAPU8=mt=new Uint8Array(I),i.HEAPU16=xo=new Uint16Array(I),i.HEAPU32=to=new Uint32Array(I),i.HEAPF32=Dr=new Float32Array(I),i.HEAPF64=jo=new Float64Array(I)}var yo=i.INITIAL_MEMORY||16777216;if(w)J=i.wasmMemory,je=i.buffer;else if(i.wasmMemory)J=i.wasmMemory;else if(J=new WebAssembly.Memory({initial:yo/65536,maximum:2147483648/65536,shared:!0}),!(J.buffer instanceof SharedArrayBuffer))throw H("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"),y&&console.log("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and also use a recent version)"),Error("bad memory");J&&(je=J.buffer),yo=je.byteLength,rr(je);var Vr,yr=[],ro=[],Eo=[],Dl=[],Ua=[],ns=!1,Xi=!1;w||ro.push({func:function(){Eh()}}),w&&(ns=!0);function Qp(){if(!w){if(i.preRun)for(typeof i.preRun=="function"&&(i.preRun=[i.preRun]);i.preRun.length;)xh(i.preRun.shift());yc(yr)}}function gc(){ns=!0,yc(ro)}function ly(){w||yc(Eo)}function gh(){w||(Xi=!0)}function oo(){if(!w){if(i.postRun)for(typeof i.postRun=="function"&&(i.postRun=[i.postRun]);i.postRun.length;)uy(i.postRun.shift());yc(Ua)}}function xh(I){yr.unshift(I)}function uy(I){Ua.unshift(I)}var Yi=0,Ha=null,$l=null;function cy(I){fe(!w,"addRunDependency cannot be used in a pthread worker"),Yi++,i.monitorRunDependencies&&i.monitorRunDependencies(Yi)}function py(I){if(Yi--,i.monitorRunDependencies&&i.monitorRunDependencies(Yi),Yi==0&&(Ha!==null&&(clearInterval(Ha),Ha=null),$l)){var $=$l;$l=null,$()}}i.preloadedImages={},i.preloadedAudios={};function Zi(I){i.onAbort&&i.onAbort(I),w&&console.error("Pthread aborting at "+new Error().stack),I+="",H(I),ue=!0,ae=1,I="abort("+I+"). Build with -s ASSERTIONS=1 for more info.";var $=new WebAssembly.RuntimeError(I);throw u($),$}function yh(I,$){return String.prototype.startsWith?I.startsWith($):I.indexOf($)===0}var xc="data:application/octet-stream;base64,";function bh(I){return yh(I,xc)}var my="file://";function wh(I){return yh(I,my)}var no="tfjs-backend-wasm-threaded-simd.wasm";bh(no)||(no=v(no));function fy(I){try{if(I==no&&Y)return new Uint8Array(Y);if(R)return R(I);throw"both async and sync fetching of the wasm failed"}catch($){Zi($)}}function kh(){if(!Y&&(h||g)){if(typeof fetch=="function"&&!wh(no))return fetch(no,{credentials:"same-origin"}).then(function(I){if(!I.ok)throw"failed to load wasm binary file at '"+no+"'";return I.arrayBuffer()}).catch(function(){return fy(no)});if(A)return new Promise(function(I,$){A(no,function(B){I(new Uint8Array(B))},$)})}return Promise.resolve().then(function(){return fy(no)})}function dy(){var I={a:nb};function $(ye,Te){var wt=ye.exports;if(i.asm=wt,Vr=i.asm.F,ie=Te,!w){var br=Ee.unusedWorkers.length;Ee.unusedWorkers.forEach(function(mr){Ee.loadWasmModuleToWorker(mr,function(){--br||py("wasm-instantiate")})})}}w||cy("wasm-instantiate");function B(ye){$(ye.instance,ye.module)}function K(ye){return kh().then(function(Te){return WebAssembly.instantiate(Te,I)}).then(ye,function(Te){H("failed to asynchronously prepare wasm: "+Te),Zi(Te)})}function be(){return!Y&&typeof WebAssembly.instantiateStreaming=="function"&&!bh(no)&&!wh(no)&&typeof fetch=="function"?fetch(no,{credentials:"same-origin"}).then(function(ye){var Te=WebAssembly.instantiateStreaming(ye,I);return Te.then(B,function(wt){return H("wasm streaming compile failed: "+wt),H("falling back to ArrayBuffer instantiation"),K(B)})}):K(B)}if(i.instantiateWasm)try{var he=i.instantiateWasm(I,$);return he}catch(ye){return H("Module.instantiateWasm callback failed with error: "+ye),!1}return be().catch(u),{}}var _h={8991:function(I,$){setTimeout(function(){XI(I,$)},0)}};function hy(){Ee.initRuntime()}function yc(I){for(;I.length>0;){var $=I.shift();if(typeof $=="function"){$(i);continue}var B=$.func;typeof B=="number"?$.arg===void 0?Vr.get(B)():Vr.get(B)($.arg):B($.arg===void 0?null:$.arg)}}function bc(I,$){if(I<=0||I>t().length||I&!0||$<0)return-28;if($==0)return 0;$>=2147483647&&($=Infinity);var B=Atomics.load(n(),Ic>>2),K=0;if(B==I){var be=Atomics.compareExchange(n(),Ic>>2,B,0);if(be==B&&(--$,K=1,$<=0))return 1}var he=Atomics.notify(n(),I>>2,$);if(he>=0)return he+K;throw"Atomics.notify returned an unexpected value "+he}i._emscripten_futex_wake=bc;function gy(I){if(w)throw"Internal Error! killThread() can only ever be called from main application thread!";if(!I)throw"Internal Error! Null pthread_ptr in killThread!";n()[I+12>>2]=0;var $=Ee.pthreads[I];$.worker.terminate(),Ee.freeThreadData($),Ee.runningWorkers.splice(Ee.runningWorkers.indexOf($.worker),1),$.worker.pthread=void 0}function xy(I){if(w)throw"Internal Error! cancelThread() can only ever be called from main application thread!";if(!I)throw"Internal Error! Null pthread_ptr in cancelThread!";var $=Ee.pthreads[I];$.worker.postMessage({cmd:"cancel"})}function yy(I){if(w)throw"Internal Error! cleanupThread() can only ever be called from main application thread!";if(!I)throw"Internal Error! Null pthread_ptr in cleanupThread!";n()[I+12>>2]=0;var $=Ee.pthreads[I];if($){var B=$.worker;Ee.returnWorkerToPool(B)}}var Ee={unusedWorkers:[],runningWorkers:[],initMainThreadBlock:function(){for(var I=8,$=0;$<I;++$)Ee.allocateUnusedWorker()},initRuntime:function(){for(var I=Fl(228),$=0;$<228/4;++$)s()[I/4+$]=0;n()[I+12>>2]=I;var B=I+152;n()[B>>2]=B;for(var K=Fl(512),$=0;$<128;++$)s()[K/4+$]=0;Atomics.store(s(),I+100>>2,K),Atomics.store(s(),I+40>>2,I),Oh(I,!g,1),KI(I)},initWorker:function(){},pthreads:{},threadExitHandlers:[],setThreadStatus:function(){},runExitHandlers:function(){for(;Ee.threadExitHandlers.length>0;)Ee.threadExitHandlers.pop()();w&&_c()&&qI()},threadExit:function(I){var $=_c();$&&(Atomics.store(s(),$+4>>2,I),Atomics.store(s(),$+0>>2,1),Atomics.store(s(),$+56>>2,1),Atomics.store(s(),$+60>>2,0),Ee.runExitHandlers(),bc($+0,2147483647),Oh(0,0,0),w&&postMessage({cmd:"exit"}))},threadCancel:function(){Ee.runExitHandlers();var I=_c();Atomics.store(s(),I+4>>2,-1),Atomics.store(s(),I+0>>2,1),bc(I+0,2147483647),Oh(0,0,0),postMessage({cmd:"cancelDone"})},terminateAllThreads:function(){for(var I in Ee.pthreads){var $=Ee.pthreads[I];$&&$.worker&&Ee.returnWorkerToPool($.worker)}Ee.pthreads={};for(var B=0;B<Ee.unusedWorkers.length;++B){var K=Ee.unusedWorkers[B];K.terminate()}Ee.unusedWorkers=[];for(var B=0;B<Ee.runningWorkers.length;++B){var K=Ee.runningWorkers[B],$=K.pthread;Ee.freeThreadData($),K.terminate()}Ee.runningWorkers=[]},freeThreadData:function(I){if(!!I){if(I.threadInfoStruct){var $=n()[I.threadInfoStruct+100>>2];n()[I.threadInfoStruct+100>>2]=0,im($),im(I.threadInfoStruct)}I.threadInfoStruct=0,I.allocatedOwnStack&&I.stackBase&&im(I.stackBase),I.stackBase=0,I.worker&&(I.worker.pthread=null)}},returnWorkerToPool:function(I){Ee.runWithoutMainThreadQueuedCalls(function(){delete Ee.pthreads[I.pthread.threadInfoStruct],Ee.unusedWorkers.push(I),Ee.runningWorkers.splice(Ee.runningWorkers.indexOf(I),1),Ee.freeThreadData(I.pthread),I.pthread=void 0})},runWithoutMainThreadQueuedCalls:function(I){n()[e0>>2]=0;try{I()}finally{n()[e0>>2]=1}},receiveObjectTransfer:function(I){},loadWasmModuleToWorker:function(I,$){I.onmessage=function(B){var K=B.data,be=K.cmd;if(I.pthread&&(Ee.currentProxiedOperationCallerThread=I.pthread.threadInfoStruct),K.targetThread&&K.targetThread!=_c()){var he=Ee.pthreads[K.targetThread];he?he.worker.postMessage(B.data,K.transferList):console.error('Internal error! Worker sent a message "'+be+'" to target pthread '+K.targetThread+", but that thread no longer exists!"),Ee.currentProxiedOperationCallerThread=void 0;return}if(be==="processQueuedMainThreadWork")bb();else if(be==="spawnThread")Th(B.data);else if(be==="cleanupThread")yy(K.thread);else if(be==="killThread")gy(K.thread);else if(be==="cancelThread")xy(K.thread);else if(be==="loaded")I.loaded=!0,$&&$(I),I.runPthread&&(I.runPthread(),delete I.runPthread);else if(be==="print")U("Thread "+K.threadId+": "+K.text);else if(be==="printErr")H("Thread "+K.threadId+": "+K.text);else if(be==="alert")alert("Thread "+K.threadId+": "+K.text);else if(be==="exit"){var ye=I.pthread&&Atomics.load(s(),I.pthread.threadInfoStruct+64>>2);ye&&Ee.returnWorkerToPool(I)}else if(be==="exitProcess")try{R3(K.returnCode)}catch(Te){if(Te instanceof lm)return;throw Te}else be==="cancelDone"?Ee.returnWorkerToPool(I):be==="objectTransfer"?Ee.receiveObjectTransfer(B.data):B.data.target==="setimmediate"?I.postMessage(B.data):H("worker sent an unknown command "+be);Ee.currentProxiedOperationCallerThread=void 0},I.onerror=function(B){H("pthread sent an error! "+B.filename+":"+B.lineno+": "+B.message)},y&&(I.on("message",function(B){I.onmessage({data:B})}),I.on("error",function(B){I.onerror(B)}),I.on("exit",function(B){})),I.postMessage({cmd:"load",urlOrBlob:i.mainScriptUrlOrBlob||r,wasmMemory:J,wasmModule:ie})},allocateUnusedWorker:function(){var I=v("tfjs-backend-wasm-threaded-simd.worker.js");Ee.unusedWorkers.push(new Worker(I))},getNewWorker:function(){return Ee.unusedWorkers.length==0&&(Ee.allocateUnusedWorker(),Ee.loadWasmModuleToWorker(Ee.unusedWorkers[0])),Ee.unusedWorkers.length>0?Ee.unusedWorkers.pop():null},busySpinWait:function(I){for(var $=performance.now()+I;performance.now()<$;);}};function by(I,$){JI(I,$),vc(I)}i.establishStackSpace=by;function wy(){return re}i.getNoExitRuntime=wy;function ky(I,$){return Vr.get(I)($)}i.invokeEntryPoint=ky;function _y(I,$,B,K){Zi("Assertion failed: "+Ne(I)+", at: "+[$?Ne($):"unknown filename",B,K?Ne(K):"unknown function"])}function vy(I,$){var B=_main(I,$)}var Rl;y?Rl=function(){var I=process.hrtime();return I[0]*1e3+I[1]/1e6}:w?Rl=function(){return performance.now()-i.__performance_now_clock_drift}:typeof dateNow!="undefined"?Rl=dateNow:Rl=function(){return performance.now()};function Cy(I){return n()[UI()>>2]=I,I}function Iy(I,$){if(w)return qa(1,1,I,$)}function Ny(I,$){if(I==$)postMessage({cmd:"processQueuedMainThreadWork"});else if(w)postMessage({targetThread:I,cmd:"processThreadQueue"});else{var B=Ee.pthreads[I],K=B&&B.worker;if(!K)return;K.postMessage({cmd:"processThreadQueue"})}return 1}function Sy(){Zi()}function Ty(I,$,B){var K=Ry($,B);return _h[I].apply(null,K)}function Ay(I,$){}function Ey(I,$,B){if(I<=0||I>t().length||I&!0)return-28;if(h){if(Atomics.load(n(),I>>2)!=$)return-6;for(var be=performance.now(),he=be+B,ye=Atomics.exchange(n(),Ic>>2,I);;){if(be=performance.now(),be>he)return ye=Atomics.exchange(n(),Ic>>2,0),-73;if(ye=Atomics.exchange(n(),Ic>>2,0),ye==0)break;if(bb(),Atomics.load(n(),I>>2)!=$)return-6;ye=Atomics.exchange(n(),Ic>>2,I)}return 0}else{var K=Atomics.wait(n(),I>>2,$,B);if(K==="timed-out")return-73;if(K==="not-equal")return-6;if(K==="ok")return 0;throw"Atomics.wait returned an unexpected value "+K}}function Dy(I,$,B){o().copyWithin(I,$,$+B)}function $y(){return y?require("os").cpus().length:navigator.hardwareConcurrency}function qa(I,$){for(var B=arguments.length-2,K=am(),be=B,he=Cc(be*8),ye=he>>3,Te=0;Te<B;Te++){var wt=arguments[2+Te];a()[ye+Te]=wt}var br=ZI(I,be,he,$);return vc(K),br}var em=[],tm=[];function Ry(I,$){tm.length=0;var B;for($>>=2;B=o()[I++];){var K=B<105;K&&$&1&&$++,tm.push(K?a()[$++>>1]:n()[$]),++$}return tm}function Fy(I,$,B){em.length=$;for(var K=B>>3,be=0;be<$;be++)em[be]=a()[K+be];var he=I<0,ye=he?_h[-I-1]:ob[I];return ye.apply(null,em)}function Oy(){return o().length}function Py(I){try{return J.grow(I-je.byteLength+65535>>>16),rr(J.buffer),1}catch($){}}function My(I){var $=Oy();if(I<=$)return!1;var B=2147483648;if(I>B)return!1;for(var K=1;K<=4;K*=2){var be=$*(1+.2/K);be=Math.min(be,I+100663296);var he=Math.min(B,At(Math.max(I,be),65536)),ye=Py(he);if(ye)return!0}return!1}var Ye={inEventHandler:0,removeAllEventListeners:function(){for(var I=Ye.eventHandlers.length-1;I>=0;--I)Ye._removeHandler(I);Ye.eventHandlers=[],Ye.deferredCalls=[]},registerRemoveEventListeners:function(){Ye.removeEventListenersRegistered||(Dl.push(Ye.removeAllEventListeners),Ye.removeEventListenersRegistered=!0)},deferredCalls:[],deferCall:function(I,$,B){function K(ye,Te){if(ye.length!=Te.length)return!1;for(var wt in ye)if(ye[wt]!=Te[wt])return!1;return!0}for(var be in Ye.deferredCalls){var he=Ye.deferredCalls[be];if(he.targetFunction==I&&K(he.argsList,B))return}Ye.deferredCalls.push({targetFunction:I,precedence:$,argsList:B}),Ye.deferredCalls.sort(function(ye,Te){return ye.precedence<Te.precedence})},removeDeferredCalls:function(I){for(var $=0;$<Ye.deferredCalls.length;++$)Ye.deferredCalls[$].targetFunction==I&&(Ye.deferredCalls.splice($,1),--$)},canPerformEventHandlerRequests:function(){return Ye.inEventHandler&&Ye.currentEventHandler.allowsDeferredCalls},runDeferredCalls:function(){if(!!Ye.canPerformEventHandlerRequests())for(var I=0;I<Ye.deferredCalls.length;++I){var $=Ye.deferredCalls[I];Ye.deferredCalls.splice(I,1),--I,$.targetFunction.apply(null,$.argsList)}},eventHandlers:[],removeAllHandlersOnTarget:function(I,$){for(var B=0;B<Ye.eventHandlers.length;++B)Ye.eventHandlers[B].target==I&&(!$||$==Ye.eventHandlers[B].eventTypeString)&&Ye._removeHandler(B--)},_removeHandler:function(I){var $=Ye.eventHandlers[I];$.target.removeEventListener($.eventTypeString,$.eventListenerFunc,$.useCapture),Ye.eventHandlers.splice(I,1)},registerOrRemoveHandler:function(I){var $=function(be){++Ye.inEventHandler,Ye.currentEventHandler=I,Ye.runDeferredCalls(),I.handlerFunc(be),Ye.runDeferredCalls(),--Ye.inEventHandler};if(I.callbackfunc)I.eventListenerFunc=$,I.target.addEventListener(I.eventTypeString,$,I.useCapture),Ye.eventHandlers.push(I),Ye.registerRemoveEventListeners();else for(var B=0;B<Ye.eventHandlers.length;++B)Ye.eventHandlers[B].target==I.target&&Ye.eventHandlers[B].eventTypeString==I.eventTypeString&&Ye._removeHandler(B--)},queueEventHandlerOnThread_iiii:function(I,$,B,K,be){var he=am(),ye=Cc(12);n()[ye>>2]=B,n()[ye+4>>2]=K,n()[ye+8>>2]=be,wb(0,I,637534208,$,K,ye),vc(he)},getTargetThreadForEventCallback:function(I){switch(I){case 1:return 0;case 2:return Ee.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 Ly(I){var $=it(I)+1,B=Fl($);return qe(I,B,$),B}function zy(I,$,B,K){var be=am(),he=Cc(12),ye=0;$&&(ye=Ly($)),n()[he>>2]=ye,n()[he+4>>2]=B,n()[he+8>>2]=K,wb(0,I,657457152,0,ye,he),vc(be)}function By(I,$,B,K){$=$?Ne($):"",zy(I,$,B,K)}function Vy(I){return I>2?Ne(I):I}var Gy=[0,typeof document!="undefined"?document:0,typeof window!="undefined"?window:0];function Wy(I){I=Vy(I);var $=Gy[I]||(typeof document!="undefined"?document.querySelector(I):void 0);return $}function rm(I){return Wy(I)}function vh(I,$,B){var K=rm(I);if(!K)return-4;if(K.canvasSharedPtr&&(n()[K.canvasSharedPtr>>2]=$,n()[K.canvasSharedPtr+4>>2]=B),K.offscreenCanvas||!K.controlTransferredOffscreen){K.offscreenCanvas&&(K=K.offscreenCanvas);var be=!1;if(K.GLctxObject&&K.GLctxObject.GLctx){var he=K.GLctxObject.GLctx.getParameter(2978);be=he[0]===0&&he[1]===0&&he[2]===K.width&&he[3]===K.height}K.width=$,K.height=B,be&&K.GLctxObject.GLctx.viewport(0,0,$,B)}else if(K.canvasSharedPtr){var ye=n()[K.canvasSharedPtr+8>>2];return By(ye,I,$,B),1}else return-4;return 0}function Ch(I,$,B){return w?qa(2,1,I,$,B):vh(I,$,B)}function jy(I,$,B){var K=rm(I);return K?vh(I,$,B):Ch(I,$,B)}function Uy(I){}function Hy(I,$){}function qy(I){var $=I.getExtension("ANGLE_instanced_arrays");if($)return I.vertexAttribDivisor=function(B,K){$.vertexAttribDivisorANGLE(B,K)},I.drawArraysInstanced=function(B,K,be,he){$.drawArraysInstancedANGLE(B,K,be,he)},I.drawElementsInstanced=function(B,K,be,he,ye){$.drawElementsInstancedANGLE(B,K,be,he,ye)},1}function Ky(I){var $=I.getExtension("OES_vertex_array_object");if($)return I.createVertexArray=function(){return $.createVertexArrayOES()},I.deleteVertexArray=function(B){$.deleteVertexArrayOES(B)},I.bindVertexArray=function(B){$.bindVertexArrayOES(B)},I.isVertexArray=function(B){return $.isVertexArrayOES(B)},1}function Xy(I){var $=I.getExtension("WEBGL_draw_buffers");if($)return I.drawBuffers=function(B,K){$.drawBuffersWEBGL(B,K)},1}function Yy(I){return!!(I.multiDrawWebgl=I.getExtension("WEBGL_multi_draw"))}var ft={counter:1,buffers:[],programs:[],framebuffers:[],renderbuffers:[],textures:[],uniforms:[],shaders:[],vaos:[],contexts:{},offscreenCanvases:{},timerQueriesEXT:[],programInfos:{},stringCache:{},unpackAlignment:4,recordError:function($){ft.lastError||(ft.lastError=$)},getNewId:function(I){for(var $=ft.counter++,B=I.length;B<$;B++)I[B]=null;return $},getSource:function(I,$,B,K){for(var be="",he=0;he<$;++he){var ye=K?n()[K+he*4>>2]:-1;be+=Ne(n()[B+he*4>>2],ye<0?void 0:ye)}return be},createContext:function(I,$){var B=I.getContext("webgl",$);if(!B)return 0;var K=ft.registerContext(B,$);return K},registerContext:function(I,$){var B=Fl(8);n()[B+4>>2]=_c();var K={handle:B,attributes:$,version:$.majorVersion,GLctx:I};return I.canvas&&(I.canvas.GLctxObject=K),ft.contexts[B]=K,(typeof $.enableExtensionsByDefault=="undefined"||$.enableExtensionsByDefault)&&ft.initExtensions(K),B},makeContextCurrent:function(I){return ft.currentContext=ft.contexts[I],i.ctx=Ka=ft.currentContext&&ft.currentContext.GLctx,!(I&&!Ka)},getContext:function(I){return ft.contexts[I]},deleteContext:function(I){ft.currentContext===ft.contexts[I]&&(ft.currentContext=null),typeof Ye=="object"&&Ye.removeAllHandlersOnTarget(ft.contexts[I].GLctx.canvas),ft.contexts[I]&&ft.contexts[I].GLctx.canvas&&(ft.contexts[I].GLctx.canvas.GLctxObject=void 0),im(ft.contexts[I].handle),ft.contexts[I]=null},initExtensions:function(I){if(I||(I=ft.currentContext),!I.initExtensionsDone){I.initExtensionsDone=!0;var $=I.GLctx;qy($),Ky($),Xy($),$.disjointTimerQueryExt=$.getExtension("EXT_disjoint_timer_query"),Yy($);var B=$.getSupportedExtensions()||[];B.forEach(function(K){K.indexOf("lose_context")<0&&K.indexOf("debug")<0&&$.getExtension(K)})}},populateUniformTable:function(I){for(var $=ft.programs[I],B=ft.programInfos[I]={uniforms:{},maxUniformLength:0,maxAttributeLength:-1,maxUniformBlockNameLength:-1},K=B.uniforms,be=Ka.getProgramParameter($,35718),he=0;he<be;++he){var ye=Ka.getActiveUniform($,he),Te=ye.name;B.maxUniformLength=Math.max(B.maxUniformLength,Te.length+1),Te.slice(-1)=="]"&&(Te=Te.slice(0,Te.lastIndexOf("[")));var wt=Ka.getUniformLocation($,Te);if(wt){var br=ft.getNewId(ft.uniforms);K[Te]=[ye.size,br],ft.uniforms[br]=wt;for(var mr=1;mr<ye.size;++mr){var Ya=Te+"["+mr+"]";wt=Ka.getUniformLocation($,Ya),br=ft.getNewId(ft.uniforms),ft.uniforms[br]=wt}}}}},Zy=["default","low-power","high-performance"];function Jy(I,$){var B=$>>2,K=n()[B+(24>>2)],be={alpha:!!n()[B+(0>>2)],depth:!!n()[B+(4>>2)],stencil:!!n()[B+(8>>2)],antialias:!!n()[B+(12>>2)],premultipliedAlpha:!!n()[B+(16>>2)],preserveDrawingBuffer:!!n()[B+(20>>2)],powerPreference:Zy[K],failIfMajorPerformanceCaveat:!!n()[B+(28>>2)],majorVersion:n()[B+(32>>2)],minorVersion:n()[B+(36>>2)],enableExtensionsByDefault:n()[B+(40>>2)],explicitSwapControl:n()[B+(44>>2)],proxyContextToMainThread:n()[B+(48>>2)],renderViaOffscreenBackBuffer:n()[B+(52>>2)]},he=rm(I);if(!he||be.explicitSwapControl)return 0;var ye=ft.createContext(he,be);return ye}function Qy(I,$){return Jy(I,$)}var wc={mappings:{},buffers:[null,[],[]],printChar:function(I,$){var B=wc.buffers[I];$===0||$===10?((I===1?U:H)(De(B,0)),B.length=0):B.push($)},varargs:void 0,get:function(){wc.varargs+=4;var I=n()[wc.varargs-4>>2];return I},getStr:function(I){var $=Ne(I);return $},get64:function(I,$){return I}};function Ih(I){return w?qa(3,1,I):0}function Nh(I,$,B,K,be){if(w)return qa(4,1,I,$,B,K,be)}function Sh(I,$,B,K){if(w)return qa(5,1,I,$,B,K);for(var be=0,he=0;he<B;he++){for(var ye=n()[$+he*8>>2],Te=n()[$+(he*8+4)>>2],wt=0;wt<Te;wt++)wc.printChar(I,o()[ye+wt]);be+=Te}return n()[K>>2]=be,0}function eb(I){var $=Ee.threadExitHandlers.pop();I&&$()}function tb(I,$){Ee.threadExitHandlers.push(function(){Vr.get(I)($)})}function Th(I){if(w)throw"Internal Error! spawnThread() can only ever be called from main application thread!";var $=Ee.getNewWorker();if($.pthread!==void 0)throw"Internal error!";if(!I.pthread_ptr)throw"Internal error, no pthread ptr!";Ee.runningWorkers.push($);for(var B=Fl(128*4),K=0;K<128;++K)n()[B+K*4>>2]=0;var be=I.stackBase+I.stackSize,he=Ee.pthreads[I.pthread_ptr]={worker:$,stackBase:I.stackBase,stackSize:I.stackSize,allocatedOwnStack:I.allocatedOwnStack,threadInfoStruct:I.pthread_ptr},ye=he.threadInfoStruct>>2;Atomics.store(s(),ye+(64>>2),I.detached),Atomics.store(s(),ye+(100>>2),B),Atomics.store(s(),ye+(40>>2),he.threadInfoStruct),Atomics.store(s(),ye+(80>>2),I.stackSize),Atomics.store(s(),ye+(76>>2),be),Atomics.store(s(),ye+(104>>2),I.stackSize),Atomics.store(s(),ye+(104+8>>2),be),Atomics.store(s(),ye+(104+12>>2),I.detached);var Te=HI(),wt=Te+40;Atomics.store(s(),ye+(172>>2),wt),$.pthread=he;var br={cmd:"run",start_routine:I.startRoutine,arg:I.arg,threadInfoStruct:I.pthread_ptr,stackBase:I.stackBase,stackSize:I.stackSize};$.runPthread=function(){br.time=performance.now(),$.postMessage(br,I.transferList)},$.loaded&&($.runPthread(),delete $.runPthread)}function rb(I,$,B,K){if(typeof SharedArrayBuffer=="undefined")return H("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;if(!I)return H("pthread_create called with a null thread pointer!"),28;var be=[],he=0;if(w&&(be.length===0||he))return YI(687865856,I,$,B,K);if(he)return he;var ye=0,Te=0,wt=0;$&&$!=-1?(ye=n()[$>>2],ye+=81920,Te=n()[$+8>>2],wt=n()[$+12>>2]!==0):ye=2097152;var br=Te==0;br?Te=QI(16,ye):(Te-=ye,fe(Te>0));for(var mr=Fl(228),Ya=0;Ya<228>>2;++Ya)s()[(mr>>2)+Ya]=0;n()[I>>2]=mr,n()[mr+12>>2]=mr;var Nc=mr+152;n()[Nc>>2]=Nc;var Gr={stackBase:Te,stackSize:ye,allocatedOwnStack:br,detached:wt,startRoutine:B,pthread_ptr:mr,arg:K,transferList:be};return w?(Gr.cmd="spawnThread",postMessage(Gr,be)):Th(Gr),0}function Ah(I){if(w)return qa(6,1,I);switch(I){case 30:return 16384;case 85:var $=2147483648;return $/16384;case 132:case 133:case 12:case 137:case 138:case 15:case 235:case 16:case 17:case 18:case 19:case 20:case 149:case 13:case 10:case 236:case 153:case 9:case 21:case 22:case 159:case 154:case 14:case 77:case 78:case 139:case 82:case 68:case 67:case 164:case 11:case 29:case 47:case 48:case 95:case 52:case 51:case 46:return 200809;case 27:case 246:case 127:case 128:case 23:case 24:case 160:case 161:case 181:case 182:case 242:case 183:case 184:case 243:case 244:case 245:case 165:case 178:case 179:case 49:case 50:case 168:case 169:case 175:case 170:case 171:case 172:case 97:case 76:case 32:case 173:case 35:case 80:case 81:case 79:return-1;case 176:case 177:case 7:case 155:case 8:case 157:case 125:case 126:case 92:case 93:case 129:case 130:case 131:case 94:case 91:return 1;case 74:case 60:case 69:case 70:case 4:return 1024;case 31:case 42:case 72:return 32;case 87:case 26:case 33:return 2147483647;case 34:case 1:return 47839;case 38:case 36:return 99;case 43:case 37:return 2048;case 0:return 2097152;case 3:return 65536;case 28:return 32768;case 44:return 32767;case 75:return 16384;case 39:return 1e3;case 89:return 700;case 71:return 256;case 40:return 255;case 2:return 100;case 180:return 64;case 25:return 20;case 5:return 16;case 6:return 6;case 73:return 4;case 84:return typeof navigator=="object"&&navigator.hardwareConcurrency||1}return Cy(28),-1}w||Ee.initMainThreadBlock();var Ka,ob=[null,Iy,Ch,Ih,Nh,Sh,Ah],nb={e:_y,r:vy,x:Ny,b:Sy,y:Ty,j:Ay,c:Ey,d:bc,f:Rl,p:Dy,z:$y,u:Fy,q:My,v:jy,i:Uy,t:Hy,w:Qy,m:Ih,n:Nh,g:Sh,o:hy,a:J||i.wasmMemory,k:eb,l:tb,h:rb,s:Ah},jI=dy(),Eh=i.___wasm_call_ctors=function(){return(Eh=i.___wasm_call_ctors=i.asm.A).apply(null,arguments)},sb=i._init=function(){return(sb=i._init=i.asm.B).apply(null,arguments)},ib=i._register_tensor=function(){return(ib=i._register_tensor=i.asm.C).apply(null,arguments)},ab=i._dispose_data=function(){return(ab=i._dispose_data=i.asm.D).apply(null,arguments)},lb=i._dispose=function(){return(lb=i._dispose=i.asm.E).apply(null,arguments)},ub=i._Abs=function(){return(ub=i._Abs=i.asm.G).apply(null,arguments)},cb=i._Add=function(){return(cb=i._Add=i.asm.H).apply(null,arguments)},pb=i._AddN=function(){return(pb=i._AddN=i.asm.I).apply(null,arguments)},mb=i._ArgMax=function(){return(mb=i._ArgMax=i.asm.J).apply(null,arguments)},fb=i._AvgPool=function(){return(fb=i._AvgPool=i.asm.K).apply(null,arguments)},db=i._BatchMatMul=function(){return(db=i._BatchMatMul=i.asm.L).apply(null,arguments)},hb=i._Ceil=function(){return(hb=i._Ceil=i.asm.M).apply(null,arguments)},gb=i._ClipByValue=function(){return(gb=i._ClipByValue=i.asm.N).apply(null,arguments)},xb=i._Conv2D=function(){return(xb=i._Conv2D=i.asm.O).apply(null,arguments)},Dh=i._Conv2DBackpropInput=function(){return(Dh=i._Conv2DBackpropInput=i.asm.P).apply(null,arguments)},$h=i._Cos=function(){return($h=i._Cos=i.asm.Q).apply(null,arguments)},om=i._CropAndResize=function(){return(om=i._CropAndResize=i.asm.R).apply(null,arguments)},kc=i._Cumsum=function(){return(kc=i._Cumsum=i.asm.S).apply(null,arguments)},yb=i._DepthToSpace=function(){return(yb=i._DepthToSpace=i.asm.T).apply(null,arguments)},nm=i._DepthwiseConv2dNative=function(){return(nm=i._DepthwiseConv2dNative=i.asm.U).apply(null,arguments)},Z=i._Equal=function(){return(Z=i._Equal=i.asm.V).apply(null,arguments)},se=i._Exp=function(){return(se=i._Exp=i.asm.W).apply(null,arguments)},_e=i._FlipLeftRight=function(){return(_e=i._FlipLeftRight=i.asm.X).apply(null,arguments)},at=i._Floor=function(){return(at=i._Floor=i.asm.Y).apply(null,arguments)},Xt=i._FloorDiv=function(){return(Xt=i._FloorDiv=i.asm.Z).apply(null,arguments)},zt=i._FusedBatchNorm=function(){return(zt=i._FusedBatchNorm=i.asm._).apply(null,arguments)},tt=i._FusedConv2D=function(){return(tt=i._FusedConv2D=i.asm.$).apply(null,arguments)},rt=i._FusedDepthwiseConv2D=function(){return(rt=i._FusedDepthwiseConv2D=i.asm.aa).apply(null,arguments)},_r=i._Gather=function(){return(_r=i._Gather=i.asm.ba).apply(null,arguments)},Ji=i._GatherNd=function(){return(Ji=i._GatherNd=i.asm.ca).apply(null,arguments)},Qi=i._Greater=function(){return(Qi=i._Greater=i.asm.da).apply(null,arguments)},Rh=i._GreaterEqual=function(){return(Rh=i._GreaterEqual=i.asm.ea).apply(null,arguments)},sm=i._LeakyRelu=function(){return(sm=i._LeakyRelu=i.asm.fa).apply(null,arguments)},bo=i._Less=function(){return(bo=i._Less=i.asm.ga).apply(null,arguments)},Xa=i._LessEqual=function(){return(Xa=i._LessEqual=i.asm.ha).apply(null,arguments)},Fh=i._Log=function(){return(Fh=i._Log=i.asm.ia).apply(null,arguments)},Gz=i._LogicalAnd=function(){return(Gz=i._LogicalAnd=i.asm.ja).apply(null,arguments)},Wz=i._Max=function(){return(Wz=i._Max=i.asm.ka).apply(null,arguments)},jz=i._MaxPool=function(){return(jz=i._MaxPool=i.asm.la).apply(null,arguments)},Uz=i._Maximum=function(){return(Uz=i._Maximum=i.asm.ma).apply(null,arguments)},Hz=i._Mean=function(){return(Hz=i._Mean=i.asm.na).apply(null,arguments)},qz=i._Min=function(){return(qz=i._Min=i.asm.oa).apply(null,arguments)},Kz=i._Minimum=function(){return(Kz=i._Minimum=i.asm.pa).apply(null,arguments)},Xz=i._Multiply=function(){return(Xz=i._Multiply=i.asm.qa).apply(null,arguments)},Yz=i._Neg=function(){return(Yz=i._Neg=i.asm.ra).apply(null,arguments)},Zz=i._NonMaxSuppressionV3=function(){return(Zz=i._NonMaxSuppressionV3=i.asm.sa).apply(null,arguments)},Jz=i._NonMaxSuppressionV4=function(){return(Jz=i._NonMaxSuppressionV4=i.asm.ta).apply(null,arguments)},Qz=i._NonMaxSuppressionV5=function(){return(Qz=i._NonMaxSuppressionV5=i.asm.ua).apply(null,arguments)},e3=i._NotEqual=function(){return(e3=i._NotEqual=i.asm.va).apply(null,arguments)},t3=i._OneHot=function(){return(t3=i._OneHot=i.asm.wa).apply(null,arguments)},r3=i._PadV2=function(){return(r3=i._PadV2=i.asm.xa).apply(null,arguments)},o3=i._Pow=function(){return(o3=i._Pow=i.asm.ya).apply(null,arguments)},n3=i._Prelu=function(){return(n3=i._Prelu=i.asm.za).apply(null,arguments)},s3=i._Prod=function(){return(s3=i._Prod=i.asm.Aa).apply(null,arguments)},i3=i._RealDiv=function(){return(i3=i._RealDiv=i.asm.Ba).apply(null,arguments)},a3=i._Relu=function(){return(a3=i._Relu=i.asm.Ca).apply(null,arguments)},l3=i._Relu6=function(){return(l3=i._Relu6=i.asm.Da).apply(null,arguments)},u3=i._ResizeBilinear=function(){return(u3=i._ResizeBilinear=i.asm.Ea).apply(null,arguments)},c3=i._Reverse=function(){return(c3=i._Reverse=i.asm.Fa).apply(null,arguments)},p3=i._RotateWithOffset=function(){return(p3=i._RotateWithOffset=i.asm.Ga).apply(null,arguments)},m3=i._Round=function(){return(m3=i._Round=i.asm.Ha).apply(null,arguments)},f3=i._Rsqrt=function(){return(f3=i._Rsqrt=i.asm.Ia).apply(null,arguments)},d3=i._ScatterNd=function(){return(d3=i._ScatterNd=i.asm.Ja).apply(null,arguments)},h3=i._SelectV2=function(){return(h3=i._SelectV2=i.asm.Ka).apply(null,arguments)},g3=i._Sigmoid=function(){return(g3=i._Sigmoid=i.asm.La).apply(null,arguments)},x3=i._Sin=function(){return(x3=i._Sin=i.asm.Ma).apply(null,arguments)},y3=i._Softmax=function(){return(y3=i._Softmax=i.asm.Na).apply(null,arguments)},b3=i._Sqrt=function(){return(b3=i._Sqrt=i.asm.Oa).apply(null,arguments)},w3=i._Square=function(){return(w3=i._Square=i.asm.Pa).apply(null,arguments)},k3=i._SquaredDifference=function(){return(k3=i._SquaredDifference=i.asm.Qa).apply(null,arguments)},_3=i._Step=function(){return(_3=i._Step=i.asm.Ra).apply(null,arguments)},v3=i._StridedSlice=function(){return(v3=i._StridedSlice=i.asm.Sa).apply(null,arguments)},C3=i._Sub=function(){return(C3=i._Sub=i.asm.Ta).apply(null,arguments)},I3=i._Sum=function(){return(I3=i._Sum=i.asm.Ua).apply(null,arguments)},N3=i._Tanh=function(){return(N3=i._Tanh=i.asm.Va).apply(null,arguments)},S3=i._Tile=function(){return(S3=i._Tile=i.asm.Wa).apply(null,arguments)},T3=i._TopK=function(){return(T3=i._TopK=i.asm.Xa).apply(null,arguments)},A3=i._Transpose=function(){return(A3=i._Transpose=i.asm.Ya).apply(null,arguments)},E3=i.__FusedMatMul=function(){return(E3=i.__FusedMatMul=i.asm.Za).apply(null,arguments)},Fl=i._malloc=function(){return(Fl=i._malloc=i.asm._a).apply(null,arguments)},im=i._free=function(){return(im=i._free=i.asm.$a).apply(null,arguments)},UI=i.___errno_location=function(){return(UI=i.___errno_location=i.asm.ab).apply(null,arguments)},HI=i._emscripten_get_global_libc=function(){return(HI=i._emscripten_get_global_libc=i.asm.bb).apply(null,arguments)},_c=i._pthread_self=function(){return(_c=i._pthread_self=i.asm.cb).apply(null,arguments)},qI=i.___pthread_tsd_run_dtors=function(){return(qI=i.___pthread_tsd_run_dtors=i.asm.db).apply(null,arguments)},bb=i._emscripten_main_thread_process_queued_calls=function(){return(bb=i._emscripten_main_thread_process_queued_calls=i.asm.eb).apply(null,arguments)},D3=i._emscripten_current_thread_process_queued_calls=function(){return(D3=i._emscripten_current_thread_process_queued_calls=i.asm.fb).apply(null,arguments)},KI=i._emscripten_register_main_browser_thread_id=function(){return(KI=i._emscripten_register_main_browser_thread_id=i.asm.gb).apply(null,arguments)},XI=i.__emscripten_do_dispatch_to_thread=function(){return(XI=i.__emscripten_do_dispatch_to_thread=i.asm.hb).apply(null,arguments)},YI=i._emscripten_sync_run_in_main_thread_4=function(){return(YI=i._emscripten_sync_run_in_main_thread_4=i.asm.ib).apply(null,arguments)},ZI=i._emscripten_run_in_main_runtime_thread_js=function(){return(ZI=i._emscripten_run_in_main_runtime_thread_js=i.asm.jb).apply(null,arguments)},wb=i.__emscripten_call_on_thread=function(){return(wb=i.__emscripten_call_on_thread=i.asm.kb).apply(null,arguments)},$3=i._emscripten_tls_init=function(){return($3=i._emscripten_tls_init=i.asm.lb).apply(null,arguments)},Oh=i.__emscripten_thread_init=function(){return(Oh=i.__emscripten_thread_init=i.asm.mb).apply(null,arguments)},am=i.stackSave=function(){return(am=i.stackSave=i.asm.nb).apply(null,arguments)},vc=i.stackRestore=function(){return(vc=i.stackRestore=i.asm.ob).apply(null,arguments)},Cc=i.stackAlloc=function(){return(Cc=i.stackAlloc=i.asm.pb).apply(null,arguments)},JI=i._emscripten_stack_set_limits=function(){return(JI=i._emscripten_stack_set_limits=i.asm.qb).apply(null,arguments)},QI=i._memalign=function(){return(QI=i._memalign=i.asm.rb).apply(null,arguments)},e0=i.__emscripten_allow_main_runtime_queued_calls=9880,Ic=i.__emscripten_main_thread_futex=11368;i.cwrap=we,i.PThread=Ee,i.PThread=Ee,i.wasmMemory=J,i.ExitStatus=lm;var Ph;function lm(I){this.name="ExitStatus",this.message="Program terminated with exit("+I+")",this.status=I}$l=function I(){Ph||kb(),Ph||($l=I)};function kb(I){if(I=I||m,Yi>0)return;if(w){l(i),postMessage({cmd:"loaded"});return}if(Qp(),Yi>0)return;function $(){Ph||(Ph=!0,i.calledRun=!0,!ue&&(gc(),ly(),l(i),i.onRuntimeInitialized&&i.onRuntimeInitialized(),oo()))}i.setStatus?(i.setStatus("Running..."),setTimeout(function(){setTimeout(function(){i.setStatus("")},1),$()},1)):$()}i.run=kb;function R3(I,$){if(!($&&re&&I===0)){if(!$&&w)throw postMessage({cmd:"exitProcess",returnCode:I}),new lm(I);re||(Ee.terminateAllThreads(),ae=I,gh(),i.onExit&&i.onExit(I),ue=!0),d(I,new lm(I))}}if(i.preInit)for(typeof i.preInit=="function"&&(i.preInit=[i.preInit]);i.preInit.length>0;)i.preInit.pop()();return w&&(re=!1,Ee.initWorker()),kb(),e.ready}}();typeof ex=="object"&&typeof tC=="object"?tC.exports=rC:typeof define=="function"&&define.amd?define([],function(){return rC}):typeof ex=="object"&&(ex.WasmBackendModuleThreadedSimd=rC)});var gO=Wr((tx,oC)=>{var nC=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;t.ready=new Promise(function(Z,se){o=Z,n=se});var s={},a;for(a in t)t.hasOwnProperty(a)&&(s[a]=t[a]);var i=[],l="./this.program",u=function(Z,se){throw se},c=!1,p=!1,m=!1,f=!1;c=typeof window=="object",p=typeof importScripts=="function",m=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",f=!c&&!m&&!p;var d="";function h(Z){return t.locateFile?t.locateFile(Z,d):d+Z}var g,y,b,w,k,v;m?(p?d=vp().dirname(d)+"/":d=__dirname+"/",g=function(se,_e){return k||(k=require("fs")),v||(v=vp()),se=v.normalize(se),k.readFileSync(se,_e?null:"utf8")},b=function(se){var _e=g(se,!0);return _e.buffer||(_e=new Uint8Array(_e)),U(_e.buffer),_e},process.argv.length>1&&(l=process.argv[1].replace(/\\/g,"/")),i=process.argv.slice(2),process.on("uncaughtException",function(Z){if(!(Z instanceof yb))throw Z}),process.on("unhandledRejection",ns),u=function(Z){process.exit(Z)},t.inspect=function(){return"[Emscripten Module object]"}):f?(typeof read!="undefined"&&(g=function(se){return read(se)}),b=function(se){var _e;return typeof readbuffer=="function"?new Uint8Array(readbuffer(se)):(_e=read(se,"binary"),U(typeof _e=="object"),_e)},typeof scriptArgs!="undefined"?i=scriptArgs:typeof arguments!="undefined"&&(i=arguments),typeof quit=="function"&&(u=function(Z){quit(Z)}),typeof print!="undefined"&&(typeof console=="undefined"&&(console={}),console.log=print,console.warn=console.error=typeof printErr!="undefined"?printErr:print)):(c||p)&&(p?d=self.location.href:typeof document!="undefined"&&document.currentScript&&(d=document.currentScript.src),r&&(d=r),d.indexOf("blob:")!==0?d=d.substr(0,d.lastIndexOf("/")+1):d="",g=function(Z){var se=new XMLHttpRequest;return se.open("GET",Z,!1),se.send(null),se.responseText},p&&(b=function(Z){var se=new XMLHttpRequest;return se.open("GET",Z,!1),se.responseType="arraybuffer",se.send(null),new Uint8Array(se.response)}),y=function(Z,se,_e){var at=new XMLHttpRequest;at.open("GET",Z,!0),at.responseType="arraybuffer",at.onload=function(){if(at.status==200||at.status==0&&at.response){se(at.response);return}_e()},at.onerror=_e,at.send(null)},w=function(Z){document.title=Z});var D=t.print||console.log.bind(console),A=t.printErr||console.warn.bind(console);for(a in s)s.hasOwnProperty(a)&&(t[a]=s[a]);s=null,t.arguments&&(i=t.arguments),t.thisProgram&&(l=t.thisProgram),t.quit&&(u=t.quit);var R;t.wasmBinary&&(R=t.wasmBinary);var P=t.noExitRuntime||!0;typeof WebAssembly!="object"&&ns("no native wasm support detected");var L,G=!1,j;function U(Z,se){Z||ns("Assertion failed: "+se)}function H(Z){var se=t["_"+Z];return U(se,"Cannot call unknown function "+Z+", make sure it is exported"),se}function q(Z,se,_e,at,Xt){var zt={string:function(bo){var Xa=0;if(bo!=null&&bo!==0){var Fh=(bo.length<<2)+1;Xa=om(Fh),ie(bo,Xa,Fh)}return Xa},array:function(bo){var Xa=om(bo.length);return ue(bo,Xa),Xa}};function tt(bo){return se==="string"?re(bo):se==="boolean"?Boolean(bo):bo}var rt=H(Z),_r=[],Ji=0;if(at)for(var Qi=0;Qi<at.length;Qi++){var Rh=zt[_e[Qi]];Rh?(Ji===0&&(Ji=Dh()),_r[Qi]=Rh(at[Qi])):_r[Qi]=at[Qi]}var sm=rt.apply(null,_r);return sm=tt(sm),Ji!==0&&$h(Ji),sm}function X(Z,se,_e,at){_e=_e||[];var Xt=_e.every(function(tt){return tt==="number"}),zt=se!=="string";return zt&&Xt&&!at?H(Z):function(){return q(Z,se,_e,arguments,at)}}var oe=typeof TextDecoder!="undefined"?new TextDecoder("utf8"):void 0;function Y(Z,se,_e){for(var at=se+_e,Xt=se;Z[Xt]&&!(Xt>=at);)++Xt;if(Xt-se>16&&Z.subarray&&oe)return oe.decode(Z.subarray(se,Xt));for(var zt="";se<Xt;){var tt=Z[se++];if(!(tt&128)){zt+=String.fromCharCode(tt);continue}var rt=Z[se++]&63;if((tt&224)==192){zt+=String.fromCharCode((tt&31)<<6|rt);continue}var _r=Z[se++]&63;if((tt&240)==224?tt=(tt&15)<<12|rt<<6|_r:tt=(tt&7)<<18|rt<<12|_r<<6|Z[se++]&63,tt<65536)zt+=String.fromCharCode(tt);else{var Ji=tt-65536;zt+=String.fromCharCode(55296|Ji>>10,56320|Ji&1023)}}return zt}function re(Z,se){return Z?Y(xe,Z,se):""}function J(Z,se,_e,at){if(!(at>0))return 0;for(var Xt=_e,zt=_e+at-1,tt=0;tt<Z.length;++tt){var rt=Z.charCodeAt(tt);if(rt>=55296&&rt<=57343){var _r=Z.charCodeAt(++tt);rt=65536+((rt&1023)<<10)|_r&1023}if(rt<=127){if(_e>=zt)break;se[_e++]=rt}else if(rt<=2047){if(_e+1>=zt)break;se[_e++]=192|rt>>6,se[_e++]=128|rt&63}else if(rt<=65535){if(_e+2>=zt)break;se[_e++]=224|rt>>12,se[_e++]=128|rt>>6&63,se[_e++]=128|rt&63}else{if(_e+3>=zt)break;se[_e++]=240|rt>>18,se[_e++]=128|rt>>12&63,se[_e++]=128|rt>>6&63,se[_e++]=128|rt&63}}return se[_e]=0,_e-Xt}function ie(Z,se,_e){return J(Z,xe,se,_e)}function ue(Z,se){de.set(Z,se)}function ae(Z,se){return Z%se>0&&(Z+=se-Z%se),Z}var fe,de,xe,we,De,Ne,ze,qe,it;function Tt(Z){fe=Z,t.HEAP8=de=new Int8Array(Z),t.HEAP16=we=new Int16Array(Z),t.HEAP32=Ne=new Int32Array(Z),t.HEAPU8=xe=new Uint8Array(Z),t.HEAPU16=De=new Uint16Array(Z),t.HEAPU32=ze=new Uint32Array(Z),t.HEAPF32=qe=new Float32Array(Z),t.HEAPF64=it=new Float64Array(Z)}var At=t.INITIAL_MEMORY||16777216,je,ut=[],mt=[],Pt=[],xo=[],Kt=!1;mt.push({func:function(){kh()}});function to(){if(t.preRun)for(typeof t.preRun=="function"&&(t.preRun=[t.preRun]);t.preRun.length;)yo(t.preRun.shift());Ha(ut)}function Dr(){Kt=!0,Ha(mt)}function jo(){Ha(Pt)}function rr(){if(t.postRun)for(typeof t.postRun=="function"&&(t.postRun=[t.postRun]);t.postRun.length;)Vr(t.postRun.shift());Ha(xo)}function yo(Z){ut.unshift(Z)}function Vr(Z){xo.unshift(Z)}var yr=0,ro=null,Eo=null;function Dl(Z){yr++,t.monitorRunDependencies&&t.monitorRunDependencies(yr)}function Ua(Z){if(yr--,t.monitorRunDependencies&&t.monitorRunDependencies(yr),yr==0&&(ro!==null&&(clearInterval(ro),ro=null),Eo)){var se=Eo;Eo=null,se()}}t.preloadedImages={},t.preloadedAudios={};function ns(Z){t.onAbort&&t.onAbort(Z),Z+="",A(Z),G=!0,j=1,Z="abort("+Z+"). Build with -s ASSERTIONS=1 for more info.";var se=new WebAssembly.RuntimeError(Z);throw n(se),se}function Xi(Z,se){return String.prototype.startsWith?Z.startsWith(se):Z.indexOf(se)===0}var Qp="data:application/octet-stream;base64,";function gc(Z){return Xi(Z,Qp)}var ly="file://";function gh(Z){return Xi(Z,ly)}var oo="tfjs-backend-wasm.wasm";gc(oo)||(oo=h(oo));function xh(Z){try{if(Z==oo&&R)return new Uint8Array(R);if(b)return b(Z);throw"both async and sync fetching of the wasm failed"}catch(se){ns(se)}}function uy(){if(!R&&(c||p)){if(typeof fetch=="function"&&!gh(oo))return fetch(oo,{credentials:"same-origin"}).then(function(Z){if(!Z.ok)throw"failed to load wasm binary file at '"+oo+"'";return Z.arrayBuffer()}).catch(function(){return xh(oo)});if(y)return new Promise(function(Z,se){y(oo,function(_e){Z(new Uint8Array(_e))},se)})}return Promise.resolve().then(function(){return xh(oo)})}function Yi(){var Z={a:no};function se(tt,rt){var _r=tt.exports;t.asm=_r,L=t.asm.g,Tt(L.buffer),je=t.asm.m,Ua("wasm-instantiate")}Dl("wasm-instantiate");function _e(tt){se(tt.instance)}function at(tt){return uy().then(function(rt){return WebAssembly.instantiate(rt,Z)}).then(tt,function(rt){A("failed to asynchronously prepare wasm: "+rt),ns(rt)})}function Xt(){return!R&&typeof WebAssembly.instantiateStreaming=="function"&&!gc(oo)&&!gh(oo)&&typeof fetch=="function"?fetch(oo,{credentials:"same-origin"}).then(function(tt){var rt=WebAssembly.instantiateStreaming(tt,Z);return rt.then(_e,function(_r){return A("wasm streaming compile failed: "+_r),A("falling back to ArrayBuffer instantiation"),at(_e)})}):at(_e)}if(t.instantiateWasm)try{var zt=t.instantiateWasm(Z,se);return zt}catch(tt){return A("Module.instantiateWasm callback failed with error: "+tt),!1}return Xt().catch(n),{}}function Ha(Z){for(;Z.length>0;){var se=Z.shift();if(typeof se=="function"){se(t);continue}var _e=se.func;typeof _e=="number"?se.arg===void 0?je.get(_e)():je.get(_e)(se.arg):_e(se.arg===void 0?null:se.arg)}}function $l(){ns()}function cy(Z,se,_e){xe.copyWithin(Z,se,se+_e)}function py(){return xe.length}function Zi(Z){try{return L.grow(Z-fe.byteLength+65535>>>16),Tt(L.buffer),1}catch(se){}}function yh(Z){var se=py(),_e=2147483648;if(Z>_e)return!1;for(var at=1;at<=4;at*=2){var Xt=se*(1+.2/at);Xt=Math.min(Xt,Z+100663296);var zt=Math.min(_e,ae(Math.max(Z,Xt),65536)),tt=Zi(zt);if(tt)return!0}return!1}var xc={mappings:{},buffers:[null,[],[]],printChar:function(Z,se){var _e=xc.buffers[Z];se===0||se===10?((Z===1?D:A)(Y(_e,0)),_e.length=0):_e.push(se)},varargs:void 0,get:function(){xc.varargs+=4;var Z=Ne[xc.varargs-4>>2];return Z},getStr:function(Z){var se=re(Z);return se},get64:function(Z,se){return Z}};function bh(Z){return 0}function my(Z,se,_e,at,Xt){}function wh(Z,se,_e,at){for(var Xt=0,zt=0;zt<_e;zt++){for(var tt=Ne[se+zt*8>>2],rt=Ne[se+(zt*8+4)>>2],_r=0;_r<rt;_r++)xc.printChar(Z,xe[tt+_r]);Xt+=rt}return Ne[at>>2]=Xt,0}var no={a:$l,d:cy,e:yh,f:bh,c:my,b:wh},fy=Yi(),kh=t.___wasm_call_ctors=function(){return(kh=t.___wasm_call_ctors=t.asm.h).apply(null,arguments)},dy=t._init=function(){return(dy=t._init=t.asm.i).apply(null,arguments)},_h=t._register_tensor=function(){return(_h=t._register_tensor=t.asm.j).apply(null,arguments)},hy=t._dispose_data=function(){return(hy=t._dispose_data=t.asm.k).apply(null,arguments)},yc=t._dispose=function(){return(yc=t._dispose=t.asm.l).apply(null,arguments)},bc=t._Abs=function(){return(bc=t._Abs=t.asm.n).apply(null,arguments)},gy=t._Add=function(){return(gy=t._Add=t.asm.o).apply(null,arguments)},xy=t._AddN=function(){return(xy=t._AddN=t.asm.p).apply(null,arguments)},yy=t._ArgMax=function(){return(yy=t._ArgMax=t.asm.q).apply(null,arguments)},Ee=t._AvgPool=function(){return(Ee=t._AvgPool=t.asm.r).apply(null,arguments)},by=t._BatchMatMul=function(){return(by=t._BatchMatMul=t.asm.s).apply(null,arguments)},wy=t._Ceil=function(){return(wy=t._Ceil=t.asm.t).apply(null,arguments)},ky=t._ClipByValue=function(){return(ky=t._ClipByValue=t.asm.u).apply(null,arguments)},_y=t._Conv2D=function(){return(_y=t._Conv2D=t.asm.v).apply(null,arguments)},vy=t._Conv2DBackpropInput=function(){return(vy=t._Conv2DBackpropInput=t.asm.w).apply(null,arguments)},Rl=t._Cos=function(){return(Rl=t._Cos=t.asm.x).apply(null,arguments)},Cy=t._CropAndResize=function(){return(Cy=t._CropAndResize=t.asm.y).apply(null,arguments)},Iy=t._Cumsum=function(){return(Iy=t._Cumsum=t.asm.z).apply(null,arguments)},Ny=t._DepthToSpace=function(){return(Ny=t._DepthToSpace=t.asm.A).apply(null,arguments)},Sy=t._DepthwiseConv2dNative=function(){return(Sy=t._DepthwiseConv2dNative=t.asm.B).apply(null,arguments)},Ty=t._Equal=function(){return(Ty=t._Equal=t.asm.C).apply(null,arguments)},Ay=t._Exp=function(){return(Ay=t._Exp=t.asm.D).apply(null,arguments)},Ey=t._FlipLeftRight=function(){return(Ey=t._FlipLeftRight=t.asm.E).apply(null,arguments)},Dy=t._Floor=function(){return(Dy=t._Floor=t.asm.F).apply(null,arguments)},$y=t._FloorDiv=function(){return($y=t._FloorDiv=t.asm.G).apply(null,arguments)},qa=t._FusedBatchNorm=function(){return(qa=t._FusedBatchNorm=t.asm.H).apply(null,arguments)},em=t._FusedConv2D=function(){return(em=t._FusedConv2D=t.asm.I).apply(null,arguments)},tm=t._FusedDepthwiseConv2D=function(){return(tm=t._FusedDepthwiseConv2D=t.asm.J).apply(null,arguments)},Ry=t._Gather=function(){return(Ry=t._Gather=t.asm.K).apply(null,arguments)},Fy=t._GatherNd=function(){return(Fy=t._GatherNd=t.asm.L).apply(null,arguments)},Oy=t._Greater=function(){return(Oy=t._Greater=t.asm.M).apply(null,arguments)},Py=t._GreaterEqual=function(){return(Py=t._GreaterEqual=t.asm.N).apply(null,arguments)},My=t._LeakyRelu=function(){return(My=t._LeakyRelu=t.asm.O).apply(null,arguments)},Ye=t._Less=function(){return(Ye=t._Less=t.asm.P).apply(null,arguments)},Ly=t._LessEqual=function(){return(Ly=t._LessEqual=t.asm.Q).apply(null,arguments)},zy=t._Log=function(){return(zy=t._Log=t.asm.R).apply(null,arguments)},By=t._LogicalAnd=function(){return(By=t._LogicalAnd=t.asm.S).apply(null,arguments)},Vy=t._Max=function(){return(Vy=t._Max=t.asm.T).apply(null,arguments)},Gy=t._MaxPool=function(){return(Gy=t._MaxPool=t.asm.U).apply(null,arguments)},Wy=t._Maximum=function(){return(Wy=t._Maximum=t.asm.V).apply(null,arguments)},rm=t._Mean=function(){return(rm=t._Mean=t.asm.W).apply(null,arguments)},vh=t._Min=function(){return(vh=t._Min=t.asm.X).apply(null,arguments)},Ch=t._Minimum=function(){return(Ch=t._Minimum=t.asm.Y).apply(null,arguments)},jy=t._Multiply=function(){return(jy=t._Multiply=t.asm.Z).apply(null,arguments)},Uy=t._Neg=function(){return(Uy=t._Neg=t.asm._).apply(null,arguments)},Hy=t._NonMaxSuppressionV3=function(){return(Hy=t._NonMaxSuppressionV3=t.asm.$).apply(null,arguments)},qy=t._NonMaxSuppressionV4=function(){return(qy=t._NonMaxSuppressionV4=t.asm.aa).apply(null,arguments)},Ky=t._NonMaxSuppressionV5=function(){return(Ky=t._NonMaxSuppressionV5=t.asm.ba).apply(null,arguments)},Xy=t._NotEqual=function(){return(Xy=t._NotEqual=t.asm.ca).apply(null,arguments)},Yy=t._OneHot=function(){return(Yy=t._OneHot=t.asm.da).apply(null,arguments)},ft=t._PadV2=function(){return(ft=t._PadV2=t.asm.ea).apply(null,arguments)},Zy=t._Pow=function(){return(Zy=t._Pow=t.asm.fa).apply(null,arguments)},Jy=t._Prelu=function(){return(Jy=t._Prelu=t.asm.ga).apply(null,arguments)},Qy=t._Prod=function(){return(Qy=t._Prod=t.asm.ha).apply(null,arguments)},wc=t._RealDiv=function(){return(wc=t._RealDiv=t.asm.ia).apply(null,arguments)},Ih=t._Relu=function(){return(Ih=t._Relu=t.asm.ja).apply(null,arguments)},Nh=t._Relu6=function(){return(Nh=t._Relu6=t.asm.ka).apply(null,arguments)},Sh=t._ResizeBilinear=function(){return(Sh=t._ResizeBilinear=t.asm.la).apply(null,arguments)},eb=t._Reverse=function(){return(eb=t._Reverse=t.asm.ma).apply(null,arguments)},tb=t._RotateWithOffset=function(){return(tb=t._RotateWithOffset=t.asm.na).apply(null,arguments)},Th=t._Round=function(){return(Th=t._Round=t.asm.oa).apply(null,arguments)},rb=t._Rsqrt=function(){return(rb=t._Rsqrt=t.asm.pa).apply(null,arguments)},Ah=t._ScatterNd=function(){return(Ah=t._ScatterNd=t.asm.qa).apply(null,arguments)},Ka=t._SelectV2=function(){return(Ka=t._SelectV2=t.asm.ra).apply(null,arguments)},ob=t._Sigmoid=function(){return(ob=t._Sigmoid=t.asm.sa).apply(null,arguments)},nb=t._Sin=function(){return(nb=t._Sin=t.asm.ta).apply(null,arguments)},jI=t._Softmax=function(){return(jI=t._Softmax=t.asm.ua).apply(null,arguments)},Eh=t._Sqrt=function(){return(Eh=t._Sqrt=t.asm.va).apply(null,arguments)},sb=t._Square=function(){return(sb=t._Square=t.asm.wa).apply(null,arguments)},ib=t._SquaredDifference=function(){return(ib=t._SquaredDifference=t.asm.xa).apply(null,arguments)},ab=t._Step=function(){return(ab=t._Step=t.asm.ya).apply(null,arguments)},lb=t._StridedSlice=function(){return(lb=t._StridedSlice=t.asm.za).apply(null,arguments)},ub=t._Sub=function(){return(ub=t._Sub=t.asm.Aa).apply(null,arguments)},cb=t._Sum=function(){return(cb=t._Sum=t.asm.Ba).apply(null,arguments)},pb=t._Tanh=function(){return(pb=t._Tanh=t.asm.Ca).apply(null,arguments)},mb=t._Tile=function(){return(mb=t._Tile=t.asm.Da).apply(null,arguments)},fb=t._TopK=function(){return(fb=t._TopK=t.asm.Ea).apply(null,arguments)},db=t._Transpose=function(){return(db=t._Transpose=t.asm.Fa).apply(null,arguments)},hb=t.__FusedMatMul=function(){return(hb=t.__FusedMatMul=t.asm.Ga).apply(null,arguments)},gb=t._malloc=function(){return(gb=t._malloc=t.asm.Ha).apply(null,arguments)},xb=t._free=function(){return(xb=t._free=t.asm.Ia).apply(null,arguments)},Dh=t.stackSave=function(){return(Dh=t.stackSave=t.asm.Ja).apply(null,arguments)},$h=t.stackRestore=function(){return($h=t.stackRestore=t.asm.Ka).apply(null,arguments)},om=t.stackAlloc=function(){return(om=t.stackAlloc=t.asm.La).apply(null,arguments)};t.cwrap=X;var kc;function yb(Z){this.name="ExitStatus",this.message="Program terminated with exit("+Z+")",this.status=Z}Eo=function Z(){kc||nm(),kc||(Eo=Z)};function nm(Z){if(Z=Z||i,yr>0||(to(),yr>0))return;function se(){kc||(kc=!0,t.calledRun=!0,!G&&(Dr(),jo(),o(t),t.onRuntimeInitialized&&t.onRuntimeInitialized(),rr()))}t.setStatus?(t.setStatus("Running..."),setTimeout(function(){setTimeout(function(){t.setStatus("")},1),se()},1)):se()}if(t.run=nm,t.preInit)for(typeof t.preInit=="function"&&(t.preInit=[t.preInit]);t.preInit.length>0;)t.preInit.pop()();return nm(),e.ready}}();typeof tx=="object"&&typeof oC=="object"?oC.exports=nC:typeof define=="function"&&define.amd?define([],function(){return nC}):typeof tx=="object"&&(tx.WasmBackendModule=nC)});var $z=Wr(()=>{});var r0="3.3.0";var o0="3.3.0";var n0="3.3.0";var s0="3.3.0";var i0="3.3.0";var V3=1e-7,G3=1e-4,Za=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}},js=class{refCount(e){return Uo("refCount")}incRef(e){return Uo("incRef")}timerAvailable(){return!0}time(e){return Uo("time")}read(e){return Uo("read")}readSync(e){return Uo("readSync")}numDataIds(){return Uo("numDataIds")}disposeData(e,t){return Uo("disposeData")}write(e,t,o){return Uo("write")}move(e,t,o,n,s){return Uo("move")}memory(){return Uo("memory")}floatPrecision(){return Uo("floatPrecision")}epsilon(){return this.floatPrecision()===32?V3:G3}dispose(){return Uo("dispose")}};function Uo(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 a0(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 W3(r,e){if(r.length!==e.length)throw new Error(`Array sizes must match to be shuffled together First array length was ${r.length}Second array length was ${e.length}`);let t=r.length,o,n,s=0;for(;t>0;)s=Math.random()*t|0,t--,o=r[t],n=e[t],r[t]=r[s],e[t]=e[s],r[s]=o,e[s]=n}function Ac(r,e,t){return Math.max(r,Math.min(e,t))}function j3(r){return r%2==0?r:r+1}function U3(r){let e=0;for(let t=0;t<r.length;t++)e+=r[t];return e}function H3(r,e){let t=Math.random();return e*t+(1-t)*r}function q3(r,e){let t=0;for(let o=0;o<r.length;o++){let n=Number(r[o])-Number(e[o]);t+=n*n}return t}function T(r,e){if(!r)throw new Error(typeof e=="string"?e:e())}function vt(r,e,t=""){T(jr(r,e),()=>t+` Shapes ${r} and ${e} must match`)}function Do(r){T(r!=null,()=>"The input to the tensor constructor must be a non-null value.")}function ss(r,e=[],t=!1){if(e==null&&(e=[]),Array.isArray(r)||or(r)&&!t)for(let o=0;o<r.length;++o)ss(r[o],e,t);else e.push(r);return e}function ct(r){if(r.length===0)return 1;let e=r[0];for(let t=1;t<r.length;t++)e*=r[t];return e}function K3(r){return r.length===0}function jr(r,e){if(r===e)return!0;if(r==null||e==null||r.length!==e.length)return!1;for(let t=0;t<r.length;t++)if(r[t]!==e[t])return!1;return!0}function ot(r){return r%1==0}function X3(r){if(Math.tanh!=null)return Math.tanh(r);if(r===Infinity)return 1;if(r===-Infinity)return-1;{let e=Math.exp(2*r);return(e-1)/(e+1)}}function Y3(r){let e=Math.ceil(Math.sqrt(r));return[e,Math.ceil(r/e)]}function Z3(r){let e=new Uint32Array(r);for(let t=0;t<r;++t)e[t]=t;return a0(e),e}function Ol(r,e){return e<=r.length?r:r+" ".repeat(e-r.length)}function J3(r,e=o=>0,t){return new Promise((o,n)=>{let s=0,a=()=>{if(r()){o();return}s++;let i=e(s);if(t!=null&&s>=t){n();return}setTimeout(a,i)};a()})}function Q3(r,e){let t=1,o=-1;for(let s=0;s<r.length;++s)if(r[s]>=0)t*=r[s];else if(r[s]===-1){if(o!==-1)throw Error(`Shapes can only have 1 implicit size. Found -1 at dim ${o} and dim ${s}`);o=s}else if(r[s]<0)throw Error(`Shapes can not be < 0. Found ${r[s]} at dim ${s}`);if(o===-1){if(e>0&&e!==t)throw Error(`Size(${e}) must match the product of shape ${r}`);return r}if(t===0)throw Error(`Cannot infer the missing size in [${r}] when there are 0 elements`);if(e%t!=0)throw Error(`The implicit shape can't be a fractional number. Got ${e} / ${t}`);let n=r.slice();return n[o]=e/t,n}function Jt(r,e){let t=e.length;return r=r==null?e.map((o,n)=>n):[].concat(r),T(r.every(o=>o>=-t&&o<t),()=>`All values in axis param must be in range [-${t}, ${t}) but got axis ${r}`),T(r.every(o=>ot(o)),()=>`All values in axis param must be integers but got axis ${r}`),r.map(o=>o<0?t+o:o)}function _b(r,e){let t=[],o=[],n=e!=null&&Array.isArray(e)&&e.length===0,s=e==null||n?null:Jt(e,r).sort(),a=0;for(let i=0;i<r.length;++i){if(s!=null){if(s[a]===i&&r[i]!==1)throw new Error(`Can't squeeze axis ${i} since its dim '${r[i]}' is not 1`);(s[a]==null||s[a]>i)&&r[i]===1&&(t.push(r[i]),o.push(i)),s[a]<=i&&a++}r[i]!==1&&(t.push(r[i]),o.push(i))}return{newShape:t,keptDims:o}}function vb(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 Cb(r,e){let t=null;if(r==null||r==="float32")t=new Float32Array(e);else if(r==="int32")t=new Int32Array(e);else if(r==="bool")t=new Uint8Array(e);else if(r==="string")t=new Array(e);else throw new Error(`Unknown data type ${r}`);return t}function Ib(r,e){for(let t=0;t<r.length;t++){let o=r[t];if(isNaN(o)||!isFinite(o))throw Error(`A tensor of type ${e} being uploaded contains ${o}.`)}}function Nb(r){return r==="bool"||r==="complex64"||r==="float32"||r==="int32"||r==="string"}function eB(r,e){return!(e==="complex64"||e==="float32"&&r!=="complex64"||e==="int32"&&r!=="float32"&&r!=="complex64"||e==="bool"&&r==="bool")}function or(r){return r instanceof Float32Array||r instanceof Int32Array||r instanceof Uint8Array}function Lh(r){if(r==="float32"||r==="int32")return 4;if(r==="complex64")return 8;if(r==="bool")return 1;throw new Error(`Unknown dtype ${r}`)}function Sb(r){if(r==null)return 0;let e=0;return r.forEach(t=>e+=t.length),e}function is(r){return typeof r=="string"||r instanceof String}function l0(r){return typeof r=="boolean"}function u0(r){return typeof r=="number"}function Ec(r){return Array.isArray(r)?Ec(r[0]):r instanceof Float32Array?"float32":r instanceof Int32Array||r instanceof Uint8Array?"int32":u0(r)?"float32":is(r)?"string":l0(r)?"bool":"float32"}function Us(r){return!!(r&&r.constructor&&r.call&&r.apply)}function Dc(r,e){for(let t=e;t<r;++t)if(r%t==0)return t;return r}function Hs(r){let e=r.length;if(e<2)return[];let t=new Array(e-1);t[e-2]=r[e-1];for(let o=e-3;o>=0;--o)t[o]=t[o+1]*r[o+1];return t}function c0(r,e,t){let o=new Array;if(e.length===1){let n=e[0];for(let s=0;s<n;s++)o[s]=t[r+s]}else{let n=e[0],s=e.slice(1),a=s.reduce((i,l)=>i*l);for(let i=0;i<n;i++)o[i]=c0(r+i*a,s,t)}return o}function Pl(r,e){if(r.length===0)return e[0];let t=r.reduce((o,n)=>o*n);if(t===0)return[];if(t!==e.length)throw new Error(`[${r}] does not match the input size ${e.length}.`);return c0(0,r,e)}function um(r,e){let t=$c(r,e);for(let o=0;o<t.length;o++)t[o]=1;return t}function $c(r,e){if(e==null||e==="float32"||e==="complex64")return new Float32Array(r);if(e==="int32")return new Int32Array(r);if(e==="bool")return new Uint8Array(r);throw new Error(`Unknown data type ${e}`)}function tB(r,e){let t=r.reduce((o,n)=>o*n,1);if(e==null||e==="float32")return Pl(r,new Float32Array(t));if(e==="int32")return Pl(r,new Int32Array(t));if(e==="bool")return Pl(r,new Uint8Array(t));throw new Error(`Unknown data type ${e}`)}function cm(r){r.forEach(e=>{T(Number.isInteger(e)&&e>=0,()=>`Tensor must have a shape comprised of positive integers but got shape [${r}].`)})}function rB(r,e,t){if(e===0)return 0;if(e===1)return r[0];let o=r[r.length-1];for(let n=0;n<r.length-1;++n)o+=t[n]*r[n];return o}function oB(r,e,t){if(e===0)return[];if(e===1)return[r];let o=new Array(e);for(let n=0;n<o.length-1;++n)o[n]=Math.floor(r/t[n]),r-=o[n]*t[n];return o[o.length-1]=r,o}function pm(r){return r&&r.then&&typeof r.then=="function"}var p0="tfjsflags",zh=class{constructor(e){this.global=e,this.flags={},this.flagRegistry={},this.urlFlags={},this.populateURLFlags()}setPlatform(e,t){this.platform!=null&&console.warn(`Platform ${this.platformName} has already been set. Overwriting the platform with ${t}.`),this.platformName=e,this.platform=t}registerFlag(e,t,o){if(this.flagRegistry[e]={evaluationFn:t,setHook:o},this.urlFlags[e]!=null){let n=this.urlFlags[e];console.warn(`Setting feature override from URL ${e}: ${n}.`),this.set(e,n)}}async getAsync(e){return e in this.flags?this.flags[e]:(this.flags[e]=await this.evaluateFlag(e),this.flags[e])}get(e){if(e in this.flags)return this.flags[e];let t=this.evaluateFlag(e);if(pm(t))throw new Error(`Flag ${e} cannot be synchronously evaluated. Please use getAsync() instead.`);return this.flags[e]=t,this.flags[e]}getNumber(e){return this.get(e)}getBool(e){return this.get(e)}getFlags(){return this.flags}get features(){return this.flags}set(e,t){if(this.flagRegistry[e]==null)throw new Error(`Cannot set flag ${e} as it has not been registered.`);this.flags[e]=t,this.flagRegistry[e].setHook!=null&&this.flagRegistry[e].setHook(t)}evaluateFlag(e){if(this.flagRegistry[e]==null)throw new Error(`Cannot evaluate flag '${e}': no evaluation function found.`);return this.flagRegistry[e].evaluationFn()}setFlags(e){this.flags=Object.assign({},e)}reset(){this.flags={},this.urlFlags={},this.populateURLFlags()}populateURLFlags(){if(typeof this.global=="undefined"||typeof this.global.location=="undefined"||typeof this.global.location.search=="undefined")return;let e=nB(this.global.location.search);p0 in e&&e[p0].split(",").forEach(o=>{let[n,s]=o.split(":");this.urlFlags[n]=sB(n,s)})}};function nB(r){let e={};return r.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,(t,...o)=>(iB(e,o[0],o[1]),o.join("="))),e}function iB(r,e,t){r[decodeURIComponent(e)]=decodeURIComponent(t||"")}function sB(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 Tb}var Tb=null;function m0(r){Tb=r}var Ab;function Eb(){if(Ab==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");Ab=r}return Ab}function aB(){let r=Eb();return r._tfGlobals==null&&(r._tfGlobals=new Map),r._tfGlobals}function mm(r,e){let t=aB();if(t.has(r))return t.get(r);{let o=e();return t.set(r,o),t.get(r)}}var as="Abs",qs="Acos",Ks="Acosh",wo="Add",Ho="AddN",Ml="All",Ll="Any",qo="ArgMax",ea="ArgMin",Xs="Asin",Ys="Asinh",Zs="Atan",Js="Atanh",Qs="Atan2",Ko="AvgPool",zl="AvgPoolGrad",ta="AvgPool3D",Bl="AvgPool3DGrad",Xo="BatchMatMul",ra="BatchToSpaceND",Vl="Bincount",Db="BroadcastTo",$o="Cast",Yo="Ceil",Ro="ClipByValue",Gl="Complex",oa="ComplexAbs",ls="Concat",Zo="Conv2D",Wl="Conv2DBackpropFilter",Jo="Conv2DBackpropInput",na="Conv3D",jl="Conv3DBackpropFilterV2",Ul="Conv3DBackpropInputV2",Qo="Cos",ei="Cosh",en="Cumsum",ti="CropAndResize",Hl="DenseBincount",ri="DepthToSpace",tn="DepthwiseConv2dNative",ql="DepthwiseConv2dNativeBackpropFilter",Kl="DepthwiseConv2dNativeBackpropInput",Xl="Diag",sa="Dilation2D",Rc="Dilation2DBackpropInput",Fc="Dilation2DBackpropFilter",rn="RealDiv",oi="Elu",Yl="EluGrad",ni="Erf",si="Equal",on="Exp",us="ExpandDims",ii="Expm1",Zl="FFT",ia="Fill",ai="FlipLeftRight",nn="Floor",sn="FloorDiv",an="FusedBatchNorm",cs="GatherV2",li="GatherNd",ui="Greater",ln="GreaterEqual",Fo="Identity",Jl="IFFT",Ql="Imag",ci="IsFinite",pi="IsInf",mi="IsNan",un="LeakyRelu",fi="Less",di="LessEqual",eu="LinSpace",cn="Log",hi="Log1p",gi="LogicalAnd",Ja="LogicalNot",Qa="LogicalOr",$b="LogSoftmax",aa="LRN",tu="LRNGrad",pn="Max",mn="Maximum",fn="MaxPool",ru="MaxPoolGrad",la="MaxPool3D",ou="MaxPool3DGrad",nu="MaxPoolWithArgmax",dn="Mean",hn="Min",gn="Minimum",ua="MirrorPad",xi="Mod",su="Multinomial",xn="Multiply",ps="Neg",yi="NotEqual",bi="NonMaxSuppressionV3",wi="NonMaxSuppressionV4",ki="NonMaxSuppressionV5",ms="OnesLike",yn="OneHot",fs="Pack",bn="PadV2",lB="Pool",wn="Pow",kn="Prelu",_i="Prod",ca="Range",iu="Real",vi="Reciprocal",_n="Relu",ds="Reshape",pa="ResizeNearestNeighbor",au="ResizeNearestNeighborGrad",vn="ResizeBilinear",lu="ResizeBilinearGrad",Cn="Relu6",In="Reverse",Nn="Round",Sn="Rsqrt",Ci="ScatterNd",hs="Select",Ii="Selu",gs="Slice",Tn="Sin",Ni="Sinh",Si="Sign",An="Sigmoid",Ti="Softplus",En="Sqrt",Dn="Sum",ma="SpaceToBatchND",xs="SplitV",$n="Softmax",Rn="SquaredDifference",fa="Square",Fn="Sub",uu="SparseToDense",Ai="StridedSlice",Ei="Tan",On="Tanh",ko="Tile",Di="TopK",cu="Transform",Pn="Transpose",pu="Unique",ys="Unpack",da="UnsortedSegmentSum",bs="ZerosLike",Oo="Step",Oc="FromPixels",$i="RotateWithOffset",ws="_FusedMatMul",ks="FusedConv2D",_s="FusedDepthwiseConv2D";var Pc=mm("kernelRegistry",()=>new Map),fm=mm("gradRegistry",()=>new Map);function Mc(r,e){let t=Rb(r,e);return Pc.get(t)}function Bh(r){return fm.get(r)}function dm(r){let e=Pc.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 el(r){let{kernelName:e,backendName:t}=r,o=Rb(e,t);Pc.has(o)&&console.warn(`The kernel '${e}' for backend '${t}' is already registered`),Pc.set(o,r)}function Fb(r){let{kernelName:e}=r;fm.has(e)&&W().getBool("DEBUG")&&console.warn(`Overriding the gradient for '${e}'`),fm.set(e,r)}function uB(r,e){let t=Rb(r,e);if(!Pc.has(t))throw new Error(`The kernel '${r}' for backend '${e}' is not registered`);Pc.delete(t)}function cB(r){if(!fm.has(r))throw new Error(`The gradient '${r}' for backend is not registered`);fm.delete(r)}function pB(r,e){dm(r).forEach(o=>{let n=Object.assign({},o,{backendName:e});el(n)})}function Rb(r,e){return`${e}_${r}`}var x={};Ke(x,{arraysEqual:()=>jr,assert:()=>T,assertNonNegativeIntegerDimensions:()=>cm,assertNonNull:()=>Do,assertShapesMatch:()=>vt,bytesFromStringArray:()=>Sb,bytesPerElement:()=>Lh,checkConversionForErrors:()=>Ib,clamp:()=>Ac,computeStrides:()=>Hs,createScalarValue:()=>mB,createShuffledIndices:()=>Z3,decodeString:()=>zc,distSquared:()=>q3,encodeString:()=>tl,fetch:()=>dB,flatten:()=>ss,getArrayFromDType:()=>Cb,getTypedArrayFromDType:()=>vb,hasEncodingLoss:()=>eB,indexToLoc:()=>oB,inferDtype:()=>Ec,inferFromImplicitShape:()=>Q3,isBoolean:()=>l0,isFunction:()=>Us,isInt:()=>ot,isNumber:()=>u0,isPromise:()=>pm,isScalarShape:()=>K3,isString:()=>is,isTypedArray:()=>or,isValidDtype:()=>Nb,locToIndex:()=>rB,makeOnesTypedArray:()=>um,makeZerosNestedTypedArray:()=>tB,makeZerosTypedArray:()=>$c,nearestDivisor:()=>Dc,nearestLargerEven:()=>j3,now:()=>mu,parseAxisParam:()=>Jt,randUniform:()=>H3,repeatedTry:()=>J3,rightPad:()=>Ol,shuffle:()=>a0,shuffleCombo:()=>W3,sizeFromShape:()=>ct,sizeToSquarishShape:()=>Y3,squeezeShape:()=>_b,sum:()=>U3,tanh:()=>X3,toNestedArray:()=>Pl,toTypedArray:()=>Lc});function mB(r,e){return e==="string"?tl(r):Lc([r],e)}function fB(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=ss(r)),W().getBool("DEBUG")&&Ib(r,e),fB(r,e))return r;if(e==null||e==="float32"||e==="complex64")return new Float32Array(r);if(e==="int32")return new Int32Array(r);if(e==="bool"){let t=new Uint8Array(r.length);for(let o=0;o<t.length;++o)Math.round(r[o])!==0&&(t[o]=1);return t}else throw new Error(`Unknown data type ${e}`)}function mu(){return W().platform.now()}function dB(r,e){return W().platform.fetch(r,e)}function tl(r,e="utf-8"){return e=e||"utf-8",W().platform.encode(r,e)}function zc(r,e="utf-8"){return e=e||"utf-8",W().platform.decode(r,e)}var Ob=class{constructor(e,t){this.backendTimer=e,this.logger=t,t==null&&(this.logger=new f0)}profileKernel(e,t,o){let n,s=()=>{n=o()},a,i=mu();if(this.backendTimer.timerAvailable())a=this.backendTimer.time(s);else{s();for(let u of n)u.dataSync();a=Promise.resolve({kernelMs:mu()-i})}if(W().getBool("CHECK_COMPUTATION_FOR_ERRORS"))for(let u=0;u<n.length;u++){let c=n[u];c.data().then(p=>{hB(p,c.dtype,e)})}return{kernelName:e,outputs:n,inputs:t,timeMs:a.then(u=>u.kernelMs),extraInfo:a.then(u=>u.getExtraProfileInfo!=null?u.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 hB(r,e,t){if(e!=="float32")return!1;for(let o=0;o<r.length;o++){let n=r[o];if(isNaN(n)||!isFinite(n))return console.warn(`Found ${n} in the result of '${t}'`),!0}return!1}var f0=class{logKernelProfile(e,t,o,n,s,a){let i=typeof n=="number"?Ol(`${n}ms`,9):n.error,l=Ol(e,25),u=t.rank,c=t.size,p=Ol(t.shape.toString(),14),m="";for(let f in s){let d=s[f];if(d!=null){let h=d.shape||t.shape,g=h.length;m+=`${f}: ${g}D ${g>0?h:""} `}}console.log(`%c${l} %c${i} %c${u}D ${p} %c${c} %c${m} %c${a}`,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")}};function d0(r,e,t){let o={},n={};for(let l=0;l<e.length;l++)o[e[l].id]=!0;for(let l=0;l<r.length;l++){let u=r[l],c=u.inputs;for(let p in c){let m=c[p],f=!1;for(let d=0;d<e.length;d++)if(o[m.id]){u.outputs.forEach(h=>o[h.id]=!0),f=!0,n[u.id]=!0;break}if(f)break}}let s={};s[t.id]=!0;let a={};for(let l=r.length-1;l>=0;l--){let u=r[l],c=u.inputs;for(let p=0;p<u.outputs.length;p++)if(s[u.outputs[p].id]){for(let m in c)s[c[m].id]=!0,a[u.id]=!0;break}}let i=[];for(let l=0;l<r.length;l++){let u=r[l];if(n[u.id]&&a[u.id]){let c={};for(let m in u.inputs){let f=u.inputs[m];o[f.id]&&(c[m]=f)}let p=Object.assign({},u);p.inputs=c,p.outputs=u.outputs,i.push(p)}}return i}function h0(r,e,t,o){for(let n=e.length-1;n>=0;n--){let s=e[n],a=[];if(s.outputs.forEach(l=>{let u=r[l.id];u!=null?a.push(u):a.push(null)}),s.gradient==null)throw new Error(`Cannot compute gradient: gradient function not found for ${s.kernelName}.`);let i=s.gradient(a);for(let l in s.inputs){if(!(l in i))throw new Error(`Cannot backprop through input ${l}. Available gradients found: ${Object.keys(i)}.`);let u=t(()=>i[l]());if(u.dtype!=="float32")throw new Error(`Error in gradient for op ${s.kernelName}. The gradient of input ${l} must have 'float32' dtype, but has '${u.dtype}'`);let c=s.inputs[l];if(!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 g0=20,hm=3,Pb=7;function x0(r,e,t,o){let n=Hs(e),s=gB(r,e,t,n),a=e.length,i=Vh(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 gB(r,e,t,o){let n=ct(e),s=o[o.length-1],a=new Array(s).fill(0),i=e.length,l=t==="complex64"?xm(r):r;if(i>1)for(let u=0;u<n/s;u++){let c=u*s;for(let p=0;p<s;p++)a[p]=Math.max(a[p],gm(l[c+p],0,t).length)}return a}function gm(r,e,t){let o;return Array.isArray(r)?o=`${parseFloat(r[0].toFixed(Pb))} + ${parseFloat(r[1].toFixed(Pb))}j`:is(r)?o=`'${r}'`:t==="bool"?o=y0(r):o=parseFloat(r.toFixed(Pb)).toString(),Ol(o,e)}function y0(r){return r===0?"false":"true"}function Vh(r,e,t,o,n,s=!0){let a=t==="complex64"?2:1,i=e[0],l=e.length;if(l===0){if(t==="complex64"){let h=xm(r);return[gm(h[0],0,t)]}return t==="bool"?[y0(r[0])]:[r[0].toString()]}if(l===1){if(i>g0){let g=hm*a,y=Array.from(r.slice(0,g)),b=Array.from(r.slice((i-hm)*a,i*a));return t==="complex64"&&(y=xm(y),b=xm(b)),["["+y.map((w,k)=>gm(w,n[k],t)).join(", ")+", ..., "+b.map((w,k)=>gm(w,n[i-hm+k],t)).join(", ")+"]"]}let h=t==="complex64"?xm(r):Array.from(r);return["["+h.map((g,y)=>gm(g,n[y],t)).join(", ")+"]"]}let u=e.slice(1),c=o.slice(1),p=o[0]*a,m=[];if(i>g0){for(let h=0;h<hm;h++){let g=h*p,y=g+p;m.push(...Vh(r.slice(g,y),u,t,c,n,!1))}m.push("...");for(let h=i-hm;h<i;h++){let g=h*p,y=g+p;m.push(...Vh(r.slice(g,y),u,t,c,n,h===i-1))}}else for(let h=0;h<i;h++){let g=h*p,y=g+p;m.push(...Vh(r.slice(g,y),u,t,c,n,h===i-1))}let f=l===2?",":"";m[0]="["+m[0]+f;for(let h=1;h<m.length-1;h++)m[h]=" "+m[h]+f;let d=`,
|
|
`;for(let h=2;h<l;h++)d+=`
|
|
`;return m[m.length-1]=" "+m[m.length-1]+"]"+(s?"":d),m}function xm(r){let e=[];for(let t=0;t<r.length;t+=2)e.push([r[t],r[t+1]]);return e}var lt=class{constructor(e,t,o){if(this.dtype=t,this.shape=e.slice(),this.size=ct(e),o!=null){let n=o.length;T(n===this.size,()=>`Length of values '${n}' does not match the size inferred by the shape '${this.size}'.`)}if(t==="complex64")throw new Error("complex64 dtype TensorBuffers are not supported. Please create a TensorBuffer for the real and imaginary parts separately and call tf.complex(real, imag).");this.values=o||Cb(t,this.size),this.strides=Hs(e)}set(e,...t){t.length===0&&(t=[0]),T(t.length===this.rank,()=>`The number of provided coordinates (${t.length}) must match the rank (${this.rank})`);let o=this.locToIndex(t);this.values[o]=e}get(...e){e.length===0&&(e=[0]);let t=0;for(let n of e){if(n<0||n>=this.shape[t]){let s=`Requested out of range element at ${e}. Buffer shape=${this.shape}`;throw new Error(s)}t++}let o=e[e.length-1];for(let n=0;n<e.length-1;++n)o+=this.strides[n]*e[n];return this.values[o]}locToIndex(e){if(this.rank===0)return 0;if(this.rank===1)return e[0];let t=e[e.length-1];for(let o=0;o<e.length-1;++o)t+=this.strides[o]*e[o];return t}indexToLoc(e){if(this.rank===0)return[];if(this.rank===1)return[e];let t=new Array(this.shape.length);for(let o=0;o<t.length-1;++o)t[o]=Math.floor(e/this.strides[o]),e-=t[o]*this.strides[o];return t[t.length-1]=e,t}get rank(){return this.shape.length}toTensor(){return Ri().makeTensor(this.values,this.shape,this.dtype)}},Ri=null,Bc=null,xB=null;function b0(r){Ri=r}function w0(r){Bc=r}function k0(r){xB=r}var Ve=class{constructor(e,t,o,n){this.kept=!1,this.isDisposedInternal=!1,this.shape=e.slice(),this.dtype=t||"float32",this.size=ct(e),this.strides=Hs(e),this.dataId=o,this.id=n,this.rankType=this.rank<5?this.rank.toString():"higher"}get rank(){return this.shape.length}async buffer(){let e=await this.data();return Bc.buffer(this.shape,this.dtype,e)}bufferSync(){return Bc.buffer(this.shape,this.dtype,this.dataSync())}async array(){let e=await this.data();return Pl(this.shape,e)}arraySync(){return Pl(this.shape,this.dataSync())}async data(){this.throwIfDisposed();let e=Ri().read(this.dataId);if(this.dtype==="string"){let t=await e;try{return t.map(o=>zc(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 x0(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(Ve,Symbol.hasInstance,{value:r=>!!r&&r.data!=null&&r.dataSync!=null&&r.throwIfDisposed!=null});function F(){return mm("Tensor",()=>Ve)}F();var rl=class extends Ve{constructor(e,t,o,n){super(e.shape,e.dtype,e.dataId,n);this.trainable=t,this.name=o}assign(e){if(e.dtype!==this.dtype)throw new Error(`dtype of the new value (${e.dtype}) and previous value (${this.dtype}) must match`);if(!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(rl,Symbol.hasInstance,{value:r=>r instanceof Ve&&r.assign!=null&&r.assign instanceof Function});var Mn={};Ke(Mn,{assertTypesMatch:()=>Gb,getTensorsInContainer:()=>ym,isTensorInList:()=>bB,makeTypesMatch:()=>Ge});var Mb;(function(r){r.R0="R0",r.R1="R1",r.R2="R2",r.R3="R3",r.R4="R4",r.R5="R5",r.R6="R6"})(Mb||(Mb={}));var Lb;(function(r){r.float32="float32",r.int32="int32",r.bool="int32",r.complex64="complex64"})(Lb||(Lb={}));var zb;(function(r){r.float32="float32",r.int32="int32",r.bool="bool",r.complex64="complex64"})(zb||(zb={}));var Bb;(function(r){r.float32="float32",r.int32="float32",r.bool="float32",r.complex64="complex64"})(Bb||(Bb={}));var Vb;(function(r){r.float32="complex64",r.int32="complex64",r.bool="complex64",r.complex64="complex64"})(Vb||(Vb={}));var yB={float32:Bb,int32:Lb,bool:zb,complex64:Vb};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 yB[r][e]}function fu(r){return fr(r,"int32")}function Ge(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 Gb(r,e){T(r.dtype===e.dtype,()=>`The dtypes of the first(${r.dtype}) and second(${e.dtype}) input must match`)}function bB(r,e){return e.some(t=>t.id===r.id)}function ym(r){let e=[],t=new Set;return _0(r,e,t),e}function _0(r,e,t){if(r==null)return;if(r instanceof Ve){e.push(r);return}if(!wB(r))return;let o=r;for(let n in o){let s=o[n];t.has(s)||(t.add(s),_0(s,e,t))}}function wB(r){return Array.isArray(r)||typeof r=="object"}function Wb(r){return r.kernelName!=null}var jb=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()}},du=class{constructor(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new jb}async ready(){if(this.pendingBackendInit!=null)return this.pendingBackendInit.then(()=>{});if(this.backendInstance!=null)return;let e=this.getSortedBackends();for(let t=0;t<e.length;t++){let o=e[t];if(await this.initializeBackend(o).success){await this.setBackend(o);return}}throw new Error("Could not initialize any backends, all backend initializations failed.")}get backend(){if(this.pendingBackendInit!=null)throw new Error(`Backend '${this.backendName}' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`);if(this.backendInstance==null){let{name:e,asyncInit:t}=this.initializeBackendsAndReturnBest();if(t)throw new Error(`The highest priority backend '${e}' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`);this.setBackend(e)}return this.backendInstance}backendNames(){return Object.keys(this.registryFactory)}findBackend(e){if(!(e in this.registry))if(e in this.registryFactory){let{asyncInit:t}=this.initializeBackend(e);if(t)return null}else return null;return this.registry[e]}findBackendFactory(e){return e in this.registryFactory?this.registryFactory[e].factory:null}registerBackend(e,t,o=1){return e in this.registryFactory?(console.warn(`${e} backend was already registered. Reusing existing backend factory.`),!1):(this.registryFactory[e]={factory:t,priority:o},!0)}async setBackend(e){if(this.registryFactory[e]==null)throw new Error(`Backend name '${e}' not found in registry`);if(this.backendName=e,this.registry[e]==null){this.backendInstance=null;let{success:t,asyncInit:o}=this.initializeBackend(e);if(!(o?await t:t))return!1}return this.backendInstance=this.registry[e],this.setupRegisteredKernels(),this.profiler=new Ob(this.backendInstance),!0}setupRegisteredKernels(){dm(this.backendName).forEach(t=>{t.setupFunc!=null&&t.setupFunc(this.backendInstance)})}disposeRegisteredKernels(e){dm(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 js)&&typeof o.then=="function"){let n=++this.pendingBackendInitId,s=o.then(a=>n<this.pendingBackendInitId?!1:(this.registry[e]=a,this.pendingBackendInit=null,!0)).catch(a=>(n<this.pendingBackendInitId||(this.pendingBackendInit=null,console.warn(`Initialization of backend ${e} failed`),console.warn(a.stack||a.message)),!1));return this.pendingBackendInit=s,{success:s,asyncInit:!0}}else return this.registry[e]=o,{success:!0,asyncInit:!1}}catch(o){return console.warn(`Initialization of backend ${e} failed`),console.warn(o.stack||o.message),{success:!1,asyncInit:!1}}}removeBackend(e){if(!(e in this.registryFactory))throw new Error(`${e} backend not found in registry`);this.backendName===e&&this.pendingBackendInit!=null&&this.pendingBackendInitId++,e in this.registry&&(this.disposeRegisteredKernels(e),this.registry[e].dispose(),delete this.registry[e]),delete this.registryFactory[e],this.backendName===e&&(this.pendingBackendInit=null,this.backendName=null,this.backendInstance=null)}getSortedBackends(){if(Object.keys(this.registryFactory).length===0)throw new Error("No backend found in registry.");return Object.keys(this.registryFactory).sort((e,t)=>this.registryFactory[t].priority-this.registryFactory[e].priority)}initializeBackendsAndReturnBest(){let e=this.getSortedBackends();for(let t=0;t<e.length;t++){let o=e[t],{success:n,asyncInit:s}=this.initializeBackend(o);if(s||n)return{name:o,asyncInit:s}}throw new Error("Could not initialize any backends, all backend initializations failed.")}moveData(e,t){let o=this.state.tensorInfo.get(t),n=o.backend,s=this.readSync(t),a=n.refCount(t);n.disposeData(t,!0),o.backend=e,e.move(t,s,o.shape,o.dtype,a),this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack[this.state.numDataMovesStack.length-1]++}tidy(e,t){let o=null;if(t==null){if(typeof e!="function")throw new Error("Please provide a function to tidy()");t=e}else{if(typeof e!="string"&&!(e instanceof String))throw new Error("When calling with two arguments, the first argument to tidy() must be a string");if(typeof t!="function")throw new Error("When calling with two arguments, the 2nd argument to tidy() must be a function");o=e}let n;return this.scopedRun(()=>this.startScope(o),()=>this.endScope(n),()=>(n=t(),n instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),n))}scopedRun(e,t,o){e();try{let n=o();return t(),n}catch(n){throw t(),n}}nextTensorId(){return du.nextTensorId++}nextVariableId(){return du.nextVariableId++}clone(e){let t=E.runKernel(Fo,{x:e}),o={x:e},n=a=>({x:()=>{let i="float32",l={x:a},u={dtype:i};return E.runKernel($o,l,u)}}),s=[];return this.addTapeNode(this.state.activeScope.name,o,[t],n,s,{}),t}runKernel(e,t,o){if(!(Mc(e,this.backendName)!=null))throw new Error(`Kernel '${e}' not registered for backend '${this.backendName}'`);return this.runKernelFunc({kernelName:e,inputs:t,attrs:o})}shouldCheckForMemLeaks(){return this.ENV.getBool("IS_TEST")}checkKernelForMemLeak(e,t,o){let n=this.backend.numDataIds(),s=0;o.forEach(l=>{s+=l.dtype==="complex64"?3:1});let a=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],i=n-t-s-a;if(i>0)throw new Error(`Backend '${this.backendName}' has an internal memory leak (${i} data ids) after running '${e}'`)}runKernelFunc(e){let t,o=[],n=this.isTapeOn(),s=this.state.numBytes,a=this.state.numTensors;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0);let i;this.backendName==null&&this.backend;let l,u=Wb(e)?e.kernelName:this.state.activeScope!=null?this.state.activeScope.name:"";if(Wb(e)){let{kernelName:d,inputs:h,attrs:g}=e;this.backendName==null&&this.backend;let y=Mc(d,this.backendName);T(y!=null,()=>`Cannot find registered kernel '${d}' for backend '${this.backendName}'`),i=()=>{let b=this.backend.numDataIds();l=y.kernelFunc({inputs:h,attrs:g,backend:this.backend});let w=Array.isArray(l)?l:[l];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(d,b,w);let k=w.map(v=>{if(v.rank!=null)return v;let{dataId:D,shape:A,dtype:R}=v;return this.makeTensorFromDataId(D,A,R)});if(n){let v=this.getTensorsForGradient(d,h,k);o=this.saveTensorsForBackwardMode(v)}return k}}else{let{forwardFunc:d}=e,h=g=>{!n||(o=g.map(y=>this.keep(this.clone(y))))};i=()=>{let g=this.backend.numDataIds();l=this.tidy(()=>d(this.backend,h));let y=Array.isArray(l)?l:[l];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(u,g,y),y}}let{inputs:c,attrs:p}=e,m=Wb(e)?null:e.backwardsFunc,f;return this.scopedRun(()=>this.state.kernelDepth++,()=>this.state.kernelDepth--,()=>{!this.ENV.getBool("DEBUG")&&!this.state.profiling?t=i():(f=this.profiler.profileKernel(u,c,()=>i()),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(f),t=f.outputs)}),n&&this.addTapeNode(u,c,t,m,o,p),this.state.profiling&&this.state.activeProfile.kernels.push({name:u,bytesAdded:this.state.numBytes-s,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-a,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(c).map(d=>c[d]!=null?c[d].shape:null),outputShapes:t.map(d=>d.shape),kernelTimeMs:f.timeMs,extraInfo:f.extraInfo}),Array.isArray(l)?t:t[0]}saveTensorsForBackwardMode(e){return e.map(o=>this.keep(this.clone(o)))}getTensorsForGradient(e,t,o){let n=Bh(e);if(n!=null){let s=n.inputsToSave||[],a=n.outputsToSave||[],i;n.saveAllInputs?(T(Array.isArray(t),()=>"saveAllInputs is true, expected inputs to be an array."),i=Object.keys(t).map(u=>t[u])):i=s.map(u=>t[u]);let l=o.filter((u,c)=>a[c]);return i.concat(l)}return[]}makeTensor(e,t,o,n){if(e==null)throw new Error("Values passed to engine.makeTensor() are null");o=o||"float32",n=n||this.backend;let s=e;o==="string"&&is(e[0])&&(s=e.map(l=>tl(l)));let a=n.write(s,t,o),i=new Ve(t,o,a,this.nextTensorId());if(this.trackTensor(i,n),o==="string"){let l=this.state.tensorInfo.get(a),u=Sb(s);this.state.numBytes+=u-l.bytes,l.bytes=u}return i}makeTensorFromDataId(e,t,o,n){o=o||"float32";let s=new Ve(t,o,e,this.nextTensorId());return this.trackTensor(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 rl(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}trackTensor(e,t){this.state.numTensors++,e.dtype==="string"&&this.state.numStringTensors++;let o=0;e.dtype!=="complex64"&&e.dtype!=="string"&&(o=e.size*Lh(e.dtype)),this.state.numBytes+=o,this.state.tensorInfo.has(e.dataId)||(this.state.numDataBuffers++,this.state.tensorInfo.set(e.dataId,{backend:t||this.backend,dtype:e.dtype,shape:e.shape,bytes:o})),e instanceof rl||this.track(e)}incRef(e,t){this.trackTensor(e,t),this.backend.incRef(e.dataId)}removeDataId(e,t){this.state.tensorInfo.has(e)&&this.state.tensorInfo.get(e).backend===t&&(this.state.tensorInfo.delete(e),this.state.numDataBuffers--)}disposeTensor(e){if(!this.state.tensorInfo.has(e.dataId))return;let t=this.state.tensorInfo.get(e.dataId);if(this.state.numTensors--,e.dtype==="string"&&(this.state.numStringTensors--,this.state.numBytes-=t.bytes),e.dtype!=="complex64"&&e.dtype!=="string"){let o=e.size*Lh(e.dtype);this.state.numBytes-=o}t.backend.disposeData(e.dataId)&&this.removeDataId(e.dataId,t.backend)}disposeVariables(){for(let e in this.state.registeredVariables){let t=this.state.registeredVariables[e];this.disposeVariable(t)}}disposeVariable(e){this.disposeTensor(e),this.state.registeredVariables[e.name]!=null&&delete this.state.registeredVariables[e.name]}memory(){let e=this.backend.memory();return e.numTensors=this.state.numTensors,e.numDataBuffers=this.state.numDataBuffers,e.numBytes=this.state.numBytes,this.state.numStringTensors>0&&(e.unreliable=!0,e.reasons==null&&(e.reasons=[]),e.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)")),e}async profile(e){this.state.profiling=!0;let t=this.state.numBytes,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=$c(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=ym(e),o=new Set(t.map(s=>s.id));for(let s=0;s<this.state.activeScope.track.length;s++){let a=this.state.activeScope.track[s];!a.kept&&!o.has(a.id)&&a.dispose()}let n=this.state.scopeStack.pop();this.state.activeScope=this.state.scopeStack.length===0?null:this.state.scopeStack[this.state.scopeStack.length-1],t.forEach(s=>{!s.kept&&s.scopeId===n.id&&this.track(s)})}gradients(e,t,o,n=!1){if(T(t.length>0,()=>"gradients() received an empty list of xs."),o!=null&&o.dtype!=="float32")throw new Error(`dy must have 'float32' dtype, but has '${o.dtype}'`);let s=this.scopedRun(()=>this.startTape(),()=>this.endTape(),()=>this.tidy("forward",e));T(s instanceof Ve,()=>"The result y returned by f() must be a tensor.");let a=d0(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?kB(s.shape):o,h0(i,a,u=>this.tidy(u),_B);let l=t.map(u=>i[u.id]);return this.state.gradientDepth===0&&(this.state.activeTape.forEach(u=>{for(let c of u.saved)c.dispose()}),this.state.activeTape=null),{value:s,grads:l}})}customGrad(e){return T(Us(e),()=>"The f passed in customGrad(f) must be a function."),(...t)=>{T(t.every(i=>i instanceof Ve),()=>"The args passed in customGrad(f)(x1, x2,...) must all be tensors");let o,n={};t.forEach((i,l)=>{n[l]=i});let s=(i,l)=>(o=e(...t,l),T(o.value instanceof Ve,()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"),T(Us(o.gradFunc),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function."),o.value),a=(i,l)=>{let u=o.gradFunc(i,l),c=Array.isArray(u)?u:[u];T(c.length===t.length,()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns the same number of tensors as inputs passed to f(...)."),T(c.every(m=>m instanceof Ve),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns a list of only tensors.");let p={};return c.forEach((m,f)=>{p[f]=()=>m}),p};return this.runKernelFunc({forwardFunc:s,backwardsFunc:a,inputs:n})}}readSync(e){return this.state.tensorInfo.get(e).backend.readSync(e)}read(e){return this.state.tensorInfo.get(e).backend.read(e)}async time(e){let t=mu(),o=await this.backend.time(e);return o.wallMs=mu()-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 jb;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}};du.nextTensorId=0;du.nextVariableId=0;function kB(r){let e=um(ct(r),"float32");return E.makeTensor(e,r,"float32")}function Ub(){let r=Eb();if(r._tfengine==null){let e=new zh(r);r._tfengine=new du(e)}return m0(r._tfengine.ENV),b0(()=>r._tfengine),r._tfengine}var E=Ub();function _B(r,e){let t={a:r,b:e};return E.runKernel(wo,t)}var hu={};Ke(hu,{isBrowser:()=>Hb,isMobile:()=>CB});function vB(){return typeof navigator!="undefined"&&navigator!=null}function CB(){if(vB()){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 Hb(){return typeof window!="undefined"&&window.document!=null||typeof WorkerGlobalScope!="undefined"}var vs=W();vs.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.")});vs.registerFlag("IS_BROWSER",()=>Hb());vs.registerFlag("IS_NODE",()=>typeof process!="undefined"&&typeof process.versions!="undefined"&&typeof process.versions.node!="undefined");vs.registerFlag("IS_CHROME",()=>typeof navigator!="undefined"&&navigator!=null&&navigator.userAgent!=null&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor));vs.registerFlag("PROD",()=>!1);vs.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",()=>vs.getBool("DEBUG"));vs.registerFlag("DEPRECATION_WARNINGS_ENABLED",()=>!0);vs.registerFlag("IS_TEST",()=>!1);vs.registerFlag("CHECK_COMPUTATION_FOR_ERRORS",()=>!0);vs.registerFlag("WRAP_TO_IMAGEBITMAP",()=>!1);function vr(r,e){let t=r;if(or(r))return e==="string"?[]:[r.length];if(!Array.isArray(r))return[];let o=[];for(;Array.isArray(t)||or(t)&&e!=="string";)o.push(t.length),t=t[0];return Array.isArray(r)&&W().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&v0(r,o,[]),o}function v0(r,e,t){if(t=t||[],!Array.isArray(r)&&!or(r)){T(e.length===0,()=>`Element arr[${t.join("][")}] is a primitive, but should be an array/TypedArray of ${e[0]} elements`);return}T(e.length>0,()=>`Element arr[${t.join("][")}] should be a primitive, but is an array of ${r.length} elements`),T(r.length===e[0],()=>`Element arr[${t.join("][")}] should have ${e[0]} elements, but has ${r.length} elements`);let o=e.slice(1);for(let n=0;n<r.length;++n)v0(r[n],o,t.concat(n))}function C0(r,e,t,o){if(r!=="string_or_numeric"){if(r==null)throw new Error("Expected dtype cannot be null.");if(r!=="numeric"&&r!==e||r==="numeric"&&e==="string")throw new Error(`Argument '${t}' passed to '${o}' must be ${r} tensor, but got ${e} tensor`)}}function _(r,e,t,o="numeric"){if(r instanceof Ve)return C0(o,r.dtype,e,t),r;let n=Ec(r);if(n!=="string"&&["bool","int32","float32"].indexOf(o)>=0&&(n=o),C0(o,n,e,t),r==null||!or(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=vr(r,n);!or(r)&&!Array.isArray(r)&&(r=[r]);let i=n!=="string"?Lc(r,n):ss(r,[],!0);return E.makeTensor(i,s,n)}function ha(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)=>_(s,`${e}[${a}]`,t,o))}var I0="__op";function S(r){let e=Object.keys(r);if(e.length!==1)throw new Error(`Please provide an object with a single key (operation name) mapping to a function. Got an object with ${e.length} keys.`);let t=e[0],o=r[t];t.endsWith("_")&&(t=t.substring(0,t.length-1)),t=t+I0;let n=(...s)=>{E.startScope(t);try{let a=o(...s);return pm(a)&&console.error("Cannot return a Promise inside of tidy."),E.endScope(a),a}catch(a){throw E.endScope(null),a}};return Object.defineProperty(n,"name",{value:t,configurable:!0}),n}function IB(r,e){let t=_(r,"real","complex"),o=_(e,"imag","complex");vt(t.shape,o.shape,`real and imag shapes, ${t.shape} and ${o.shape}, must match in call to tf.complex().`);let n={real:t,imag:o};return E.runKernel(Gl,n)}var _o=S({complex_:IB});function Ur(r,e,t,o){if(o==null&&(o=Ec(r)),o==="complex64")throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(!or(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){cm(e);let n=ct(e),s=ct(t);T(n===s,()=>`Based on the provided shape, [${e}], the tensor should have ${n} values but has ${s}`);for(let a=0;a<t.length;++a){let i=t[a],l=a===t.length-1?i!==ct(e.slice(a)):!0;T(t[a]===e[a]||!l,()=>`Error creating a new Tensor. Inferred shape (${t}) does not match the provided shape (${e}). `)}}return!or(r)&&!Array.isArray(r)&&(r=[r]),e=e||t,r=o!=="string"?Lc(r,o):ss(r,[],!0),E.makeTensor(r,e,o)}function $r(r,e,t){let o=vr(r,t);return Ur(r,e,o,t)}var bm={float32:4,float16:2,int32:4,uint16:2,uint8:1,bool:1,complex64:8};var Gh=4;async function N0(r,e){let t=[],o=[],n=Array.isArray(r)?r.map(a=>a.name):Object.keys(r);for(let a=0;a<n.length;++a){let i=n[a],l=Array.isArray(r)?r[a].tensor:r[i];if(l.dtype!=="float32"&&l.dtype!=="int32"&&l.dtype!=="bool"&&l.dtype!=="string"&&l.dtype!=="complex64")throw new Error(`Unsupported dtype in weight '${i}': ${l.dtype}`);let u={name:i,shape:l.shape,dtype:l.dtype};if(l.dtype==="string"){let c=new Promise(async p=>{let m=await l.bytes(),f=m.reduce((g,y)=>g+y.length,0)+Gh*m.length,d=new Uint8Array(f),h=0;for(let g=0;g<m.length;g++){let y=m[g],b=new Uint8Array(new Uint32Array([y.length]).buffer);d.set(b,h),h+=Gh,d.set(y,h),h+=y.length}p(d)});o.push(c)}else o.push(l.data());e!=null&&(u.group=e),t.push(u)}let s=await Promise.all(o);return{data:NB(s),specs:t}}function Wh(r,e){let t={},o,n=0;for(let s of e){let a=s.name,i=s.dtype,l=s.shape,u=ct(l),c;if("quantization"in s){let p=s.quantization;if(p.dtype==="uint8"||p.dtype==="uint16"){if(!("min"in p&&"scale"in p))throw new Error(`Weight ${s.name} with quantization ${p.dtype} doesn't have corresponding metadata min and scale.`)}else if(p.dtype==="float16"){if(i!=="float32")throw new Error(`Weight ${s.name} is quantized with ${p.dtype} which only supports weights of type float32 not ${i}.`)}else throw new Error(`Weight ${s.name} has unknown quantization dtype ${p.dtype}. Supported quantization dtypes are: 'uint8', 'uint16', and 'float16'.`);let m=bm[p.dtype],f=r.slice(n,n+u*m),d=p.dtype==="uint8"?new Uint8Array(f):new Uint16Array(f);if(i==="float32")if(p.dtype==="uint8"||p.dtype==="uint16"){c=new Float32Array(d.length);for(let h=0;h<d.length;h++){let g=d[h];c[h]=g*p.scale+p.min}}else if(p.dtype==="float16")o===void 0&&(o=SB()),c=o(d);else throw new Error(`Unsupported quantization type ${p.dtype} for weight type float32.`);else if(i==="int32"){if(p.dtype!=="uint8"&&p.dtype!=="uint16")throw new Error(`Unsupported quantization type ${p.dtype} for weight type int32.`);c=new Int32Array(d.length);for(let h=0;h<d.length;h++){let g=d[h];c[h]=Math.round(g*p.scale+p.min)}}else throw new Error(`Unsupported dtype in weight '${a}': ${i}`);n+=u*m}else if(i==="string"){let p=ct(s.shape);c=[];for(let m=0;m<p;m++){let f=new Uint32Array(r.slice(n,n+Gh))[0];n+=Gh;let d=new Uint8Array(r.slice(n,n+f));c.push(d),n+=f}}else{let p=bm[i],m=r.slice(n,n+u*p);if(i==="float32")c=new Float32Array(m);else if(i==="int32")c=new Int32Array(m);else if(i==="bool")c=new Uint8Array(m);else if(i==="complex64"){c=new Float32Array(m);let f=new Float32Array(c.length/2),d=new Float32Array(c.length/2);for(let y=0;y<f.length;y++)f[y]=c[y*2],d[y]=c[y*2+1];let h=$r(f,l,"float32"),g=$r(d,l,"float32");t[a]=_o(h,g),h.dispose(),g.dispose()}else throw new Error(`Unsupported dtype in weight '${a}': ${i}`);n+=u*p}i!=="complex64"&&(t[a]=$r(c,l,i))}return t}function NB(r){if(r===null)throw new Error(`Invalid input value: ${JSON.stringify(r)}`);let e=0,t=[];r.forEach(s=>{if(e+=s.byteLength,t.push(s.byteLength===s.buffer.byteLength?s:new s.constructor(s)),!(s instanceof Float32Array||s instanceof Int32Array||s instanceof Uint8Array))throw new Error(`Unsupported TypedArray subtype: ${s.constructor.name}`)});let o=new Uint8Array(e),n=0;return t.forEach(s=>{o.set(new Uint8Array(s.buffer),n),n+=s.byteLength}),o.buffer}var qb=typeof Buffer!="undefined"&&(typeof Blob=="undefined"||typeof atob=="undefined"||typeof btoa=="undefined");function S0(r){return qb?Buffer.byteLength(r):new Blob([r]).size}function T0(r){if(qb)return Buffer.from(r).toString("base64");let e=new Uint8Array(r),t="";for(let o=0,n=e.length;o<n;o++)t+=String.fromCharCode(e[o]);return btoa(t)}function A0(r){if(qb){let o=Buffer.from(r,"base64");return o.buffer.slice(o.byteOffset,o.byteOffset+o.byteLength)}let e=atob(r),t=new Uint8Array(e.length);for(let o=0;o<e.length;++o)t.set([e.charCodeAt(o)],o);return t.buffer}function Vc(r){if(r.length===1)return r[0];let e=0;r.forEach(n=>{e+=n.byteLength});let t=new Uint8Array(e),o=0;return r.forEach(n=>{t.set(new Uint8Array(n),o),o+=n.byteLength}),t.buffer}function Kb(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 Fi(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:S0(JSON.stringify(r.modelTopology)),weightSpecsBytes:r.weightSpecs==null?0:S0(JSON.stringify(r.weightSpecs)),weightDataBytes:r.weightData==null?0:r.weightData.byteLength}}function TB(){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 AB(){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 EB(){let r=new Uint32Array(64);for(let e=0;e<64;e++)r[e]=1024;return r[0]=r[32]=0,r}function SB(){let r=TB(),e=AB(),t=EB();return o=>{let n=new ArrayBuffer(4*o.length),s=new Uint32Array(n);for(let a=0;a<o.length;a++){let i=o[a],l=r[t[i>>10]+(i&1023)]+e[i>>10];s[a]=l}return new Float32Array(n)}}var Ct=class{constructor(){this.saveRouters=[],this.loadRouters=[]}static getInstance(){return Ct.instance==null&&(Ct.instance=new Ct),Ct.instance}static registerSaveRouter(e){Ct.getInstance().saveRouters.push(e)}static registerLoadRouter(e){Ct.getInstance().loadRouters.push(e)}static getSaveHandlers(e){return Ct.getHandlers(e,"save")}static getLoadHandlers(e,t){return Ct.getHandlers(e,"load",t)}static getHandlers(e,t,o){let n=[];return(t==="load"?Ct.getInstance().loadRouters:Ct.getInstance().saveRouters).forEach(a=>{let i=a(e,o);i!==null&&n.push(i)}),n}},E0=r=>Ct.registerSaveRouter(r),D0=r=>Ct.registerLoadRouter(r),$0=r=>Ct.getSaveHandlers(r),R0=(r,e)=>Ct.getLoadHandlers(r,e);var Xb="tensorflowjs",Yb=1,gu="models_store",ol="model_info_store";function F0(){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 Zb(r){let e=r.result;e.createObjectStore(gu,{keyPath:"modelPath"}),e.createObjectStore(ol,{keyPath:"modelPath"})}var ga=class{constructor(e){if(this.indexedDB=F0(),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(Xb,Yb);s.onupgradeneeded=()=>Zb(s),s.onsuccess=()=>{let a=s.result;if(t==null){let i=a.transaction(gu,"readonly"),u=i.objectStore(gu).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=Fi(t),l=a.transaction(ol,"readwrite"),u=l.objectStore(ol),c=u.put({modelPath:this.modelPath,modelArtifactsInfo:i}),p;c.onsuccess=()=>{p=a.transaction(gu,"readwrite");let f=p.objectStore(gu).put({modelPath:this.modelPath,modelArtifacts:t,modelArtifactsInfo:i});f.onsuccess=()=>o({modelArtifactsInfo:i}),f.onerror=d=>{u=l.objectStore(ol);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)})}};ga.URL_SCHEME="indexeddb://";var O0=r=>W().getBool("IS_BROWSER")&&!Array.isArray(r)&&r.startsWith(ga.URL_SCHEME)?DB(r.slice(ga.URL_SCHEME.length)):null;Ct.registerSaveRouter(O0);Ct.registerLoadRouter(O0);function DB(r){return new ga(r)}function $B(r){return r.startsWith(ga.URL_SCHEME)?r.slice(ga.URL_SCHEME.length):r}var Jb=class{constructor(){this.indexedDB=F0()}async listModels(){return new Promise((e,t)=>{let o=this.indexedDB.open(Xb,Yb);o.onupgradeneeded=()=>Zb(o),o.onsuccess=()=>{let n=o.result,s=n.transaction(ol,"readonly"),i=s.objectStore(ol).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=$B(e),new Promise((t,o)=>{let n=this.indexedDB.open(Xb,Yb);n.onupgradeneeded=()=>Zb(n),n.onsuccess=()=>{let s=n.result,a=s.transaction(ol,"readwrite"),i=a.objectStore(ol),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(gu,"readwrite");let f=u.objectStore(gu).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 xa="/",Gc="tensorflowjs_models",P0="info",RB="model_topology",FB="weight_specs",OB="weight_data",PB="model_metadata";function M0(r){return{info:[Gc,r,P0].join(xa),topology:[Gc,r,RB].join(xa),weightSpecs:[Gc,r,FB].join(xa),weightData:[Gc,r,OB].join(xa),modelMetadata:[Gc,r,PB].join(xa)}}function MB(r){let e=r.split(xa);if(e.length<3)throw new Error(`Invalid key format: ${r}`);return e.slice(1,e.length-1).join(xa)}function LB(r){return r.startsWith(ya.URL_SCHEME)?r.slice(ya.URL_SCHEME.length):r}var ya=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=M0(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=Fi(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,T0(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=A0(a),t}};ya.URL_SCHEME="localstorage://";var L0=r=>W().getBool("IS_BROWSER")&&!Array.isArray(r)&&r.startsWith(ya.URL_SCHEME)?zB(r.slice(ya.URL_SCHEME.length)):null;Ct.registerSaveRouter(L0);Ct.registerLoadRouter(L0);function zB(r){return new ya(r)}var Qb=class{constructor(){T(W().getBool("IS_BROWSER"),()=>"Current environment is not a web browser"),T(typeof window=="undefined"||typeof window.localStorage!="undefined",()=>"Current browser does not appear to support localStorage"),this.LS=window.localStorage}async listModels(){let e={},t=Gc+xa,o=xa+P0;for(let n=0;n<this.LS.length;++n){let s=this.LS.key(n);if(s.startsWith(t)&&s.endsWith(o)){let a=MB(s);e[a]=JSON.parse(this.LS.getItem(s))}}return e}async removeModel(e){e=LB(e);let t=M0(e);if(this.LS.getItem(t.info)==null)throw new Error(`Cannot find model at path '${e}'`);let o=JSON.parse(this.LS.getItem(t.info));return this.LS.removeItem(t.info),this.LS.removeItem(t.topology),this.LS.removeItem(t.weightSpecs),this.LS.removeItem(t.weightData),o}};var Wc="://",Hr=class{constructor(){this.managers={}}static getInstance(){return Hr.instance==null&&(Hr.instance=new Hr),Hr.instance}static registerManager(e,t){T(e!=null,()=>"scheme must not be undefined or null."),e.endsWith(Wc)&&(e=e.slice(0,e.indexOf(Wc))),T(e.length>0,()=>"scheme must not be an empty string.");let o=Hr.getInstance();T(o.managers[e]==null,()=>`A model store manager is already registered for scheme '${e}'.`),o.managers[e]=t}static getManager(e){let t=this.getInstance().managers[e];if(t==null)throw new Error(`Cannot find model manager for scheme '${e}'`);return t}static getSchemes(){return Object.keys(this.getInstance().managers)}};function jh(r){if(r.indexOf(Wc)===-1)throw new Error(`The url string provided does not contain a scheme. Supported schemes are: ${Hr.getSchemes().join(",")}`);return{scheme:r.split(Wc)[0],path:r.split(Wc)[1]}}async function z0(r,e,t=!1){T(r!==e,()=>`Old path and new path are the same: '${r}'`);let o=Ct.getLoadHandlers(r);T(o.length>0,()=>`Copying failed because no load handler is found for source URL ${r}.`),T(o.length<2,()=>`Copying failed because more than one (${o.length}) load handlers for source URL ${r}.`);let n=o[0],s=Ct.getSaveHandlers(e);T(s.length>0,()=>`Copying failed because no save handler is found for destination URL ${e}.`),T(s.length<2,()=>`Copying failed because more than one (${o.length}) save handlers for destination URL ${e}.`);let a=s[0],i=jh(r).scheme,l=jh(r).path,u=i===jh(r).scheme,c=await n.load();t&&u&&await Hr.getManager(i).removeModel(l);let p=await a.save(c);return t&&!u&&await Hr.getManager(i).removeModel(l),p.modelArtifactsInfo}async function B0(){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+Wc+n;e[s]=o[n]}}return e}async function V0(r){let e=jh(r);return Hr.getManager(e.scheme).removeModel(e.path)}async function G0(r,e){return z0(r,e,!1)}async function W0(r,e){return z0(r,e,!0)}var j0=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 j0);try{Hr.registerManager(ya.URL_SCHEME,new Qb)}catch(r){}try{Hr.registerManager(ga.URL_SCHEME,new Jb)}catch(r){}}var BB={importFetch:()=>U0()},ew;var H0=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):(ew==null&&(ew=BB.importFetch()),ew(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 H0);function ve(r,e="float32",t){return e=e||"float32",cm(r),new lt(r,e,t)}function VB(r,e){let t=_(r,"x","cast");if(!Nb(e))throw new Error(`Failed to cast to unknown dtype ${e}`);if(e==="string"&&t.dtype!=="string"||e!=="string"&&t.dtype==="string")throw new Error("Only strings can be casted to strings");let o={x:t},n={dtype:e};return E.runKernel($o,o,n)}var ne=S({cast_:VB});function GB(r){let t={x:_(r,"x","clone","string_or_numeric")};return E.runKernel(Fo,t)}var Po=S({clone_:GB});function tw(r,e=!1){console.log(r.toString(e))}Ub();var WB={buffer:ve,cast:ne,clone:Po,print:tw};w0(WB);var Cr={};Ke(Cr,{browserFiles:()=>X0,browserHTTPRequest:()=>J0,concatenateArrayBuffers:()=>Vc,copyModel:()=>G0,decodeWeights:()=>Wh,encodeWeights:()=>N0,fromMemory:()=>eN,getLoadHandlers:()=>R0,getModelArtifactsInfoForJSON:()=>Fi,getSaveHandlers:()=>$0,http:()=>qh,isHTTPScheme:()=>Hh,listModels:()=>B0,loadWeights:()=>Y0,moveModel:()=>W0,registerLoadRouter:()=>D0,registerSaveRouter:()=>E0,removeModel:()=>V0,weightsLoaderFactory:()=>nw,withSaveHandler:()=>tN});var jB="model",UB=".json",HB=".weights.bin";function q0(r){return new Promise(e=>setTimeout(e)).then(r)}var nl=class{constructor(e){if(!W().getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");e.startsWith(nl.URL_SCHEME)&&(e=e.slice(nl.URL_SCHEME.length)),(e==null||e.length===0)&&(e=jB),this.modelTopologyFileName=e+UB,this.weightDataFileName=e+HB}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 q0(()=>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 q0(()=>i.dispatchEvent(new MouseEvent("click")))}return{modelArtifactsInfo:Fi(e)}}}};nl.URL_SCHEME="downloads://";var K0=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,w=m.indexOf(h);if(f[w]=b,f.indexOf(null)===-1){let k={modelTopology:l,weightSpecs:p,weightData:Vc(f),format:i.format,generatedBy:i.generatedBy,convertedBy:i.convertedBy};i.signature!=null&&(k.signature=i.signature),i.userDefinedMetadata!=null&&(k.userDefinedMetadata=i.userDefinedMetadata),i.modelInitializer!=null&&(k.modelInitializer=i.modelInitializer),o(k)}},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=>Kb(a.name)),s={};for(let a of e)a.paths.forEach(i=>{let l=Kb(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}},KB=r=>W().getBool("IS_BROWSER")&&!Array.isArray(r)&&r.startsWith(nl.URL_SCHEME)?qB(r.slice(nl.URL_SCHEME.length)):null;Ct.registerSaveRouter(KB);function qB(r="model"){return new nl(r)}function X0(r){return new K0(r)}function rw(r,e,t,o){a(r),t=t==null?0:t,o=o==null?1:o,i(t,o);let n=0,s=l=>(l.then(u=>{let c=t+ ++n/r.length*(o-t);return e(c),u}),l);function a(l){T(l!=null&&Array.isArray(l)&&l.length>0,()=>"promises must be a none empty array")}function i(l,u){T(l>=0&&l<=1,()=>`Progress fraction must be in range [0, 1], but got startFraction ${l}`),T(u>=0&&u<=1,()=>`Progress fraction must be in range [0, 1], but got endFraction ${u}`),T(u>=l,()=>`startFraction must be no more than endFraction, but got startFraction ${l} and endFraction ${u}`)}return Promise.all(r.map(s))}async function ow(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 rw(o,e.onProgress,n,s)).map(p=>p.arrayBuffer()),l=.5,u=1;return e.onProgress==null?await Promise.all(i):await rw(i,e.onProgress,l,u)}async function Y0(r,e="",t,o){return nw(a=>ow(a,{requestInit:o}))(r,e,t)}function nw(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=bm[y]*ct(g.shape),w=()=>{n[d]=!0,s[d]==null&&(s[d]=[]),s[d].push({manifestEntry:g,groupOffset:h,sizeBytes:b})};o!=null?o.forEach((k,v)=>{k===g.name&&(w(),a[v]=!0)}):w(),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 k=0;k<d;k++)h+=c[m+k].byteLength;let g=new ArrayBuffer(h),y=new Uint8Array(g),b=0;for(let k=0;k<d;k++){let v=new Uint8Array(c[m+k]);y.set(v,b),b+=v.byteLength}s[f].forEach(k=>{let v=g.slice(k.groupOffset,k.groupOffset+k.sizeBytes),D=Wh(v,[k.manifestEntry]);for(let A in D)p[A]=D[A]}),m+=d}),p}}var XB="application/octet-stream",YB="application/json",Uh=class{constructor(e,t){if(this.DEFAULT_METHOD="POST",t==null&&(t={}),this.weightPathPrefix=t.weightPathPrefix,this.onProgress=t.onProgress,this.weightUrlConverter=t.weightUrlConverter,t.fetchFunc!=null?(T(typeof t.fetchFunc=="function",()=>"Must pass a function that matches the signature of `fetch` (see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)"),this.fetch=t.fetchFunc):this.fetch=W().platform.fetch,T(e!=null&&e.length>0,()=>"URL path for http must not be null, undefined or empty."),Array.isArray(e)&&T(e.length===2,()=>`URL paths for http must have a length of 2, (actual length is ${e.length}).`),this.path=e,t.requestInit!=null&&t.requestInit.body!=null)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=t.requestInit||{}}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");let t=Object.assign({method:this.DEFAULT_METHOD},this.requestInit);t.body=new FormData;let o=[{paths:["./model.weights.bin"],weights:e.weightSpecs}],n={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,weightsManifest:o};e.signature!=null&&(n.signature=e.signature),e.userDefinedMetadata!=null&&(n.userDefinedMetadata=e.userDefinedMetadata),e.modelInitializer!=null&&(n.modelInitializer=e.modelInitializer),t.body.append("model.json",new Blob([JSON.stringify(n)],{type:YB}),"model.json"),e.weightData!=null&&t.body.append("model.weights.bin",new Blob([e.weightData],{type:XB}),"model.weights.bin");let s=await this.fetch(this.path,t);if(s.ok)return{modelArtifactsInfo:Fi(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]=ZB(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 ow(i,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress});return[a,Vc(u)]}};Uh.URL_SCHEME_REGEX=/^https?:\/\//;function ZB(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(Uh.URL_SCHEME_REGEX)!=null}var Z0=(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 qh(r,e)}return null};Ct.registerSaveRouter(Z0);Ct.registerLoadRouter(Z0);function qh(r,e){return new Uh(r,e)}function J0(r,e){return qh(r,e)}var Kh=class{constructor(e){this.modelArtifacts=e}async load(){return this.modelArtifacts}},Q0=class{constructor(e){this.saveHandler=e}async save(e){return this.saveHandler(e)}};function eN(r,e,t,o){return arguments.length===1?r.modelTopology!=null||r.weightSpecs!=null?new Kh(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 Kh({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 Kh({modelTopology:r,weightSpecs:e,weightData:t,trainingConfig:o}))}function tN(r){return new Q0(r)}var rN={};Ke(rN,{confusionMatrix:()=>rV});function JB(r,e,t=!1,o=!1){let n=_(r,"a","matMul"),s=_(e,"b","matMul");[n,s]=Ge(n,s);let a={a:n,b:s},i={transposeA:t,transposeB:o};return E.runKernel(Xo,a,i)}var We=S({matMul_:JB});function QB(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:_(r,"indices","oneHot","int32")},a={depth:e,onValue:t,offValue:o};return E.runKernel(yn,s,a)}var Cs=S({oneHot_:QB});function eV(r,e){let t=_(r,"x","transpose");if(e==null&&(e=t.shape.map((s,a)=>a).reverse()),T(t.rank===e.length,()=>`Error in transpose: rank of input ${t.rank} must match length of perm ${e}.`),e.forEach(s=>{T(s>=0&&s<t.rank,()=>`All entries in 'perm' must be between 0 and ${t.rank-1} but got ${e}`)}),t.rank<=1)return t.clone();let o={x:t},n={perm:e};return E.runKernel(Pn,o,n)}var Ue=S({transpose_:eV});function tV(r,e,t){let o=_(r,"labels","confusionMatrix"),n=_(e,"predictions","confusionMatrix");T(t==null||t>0&&Number.isInteger(t),()=>`If provided, numClasses must be a positive integer, but got ${t}`),T(o.rank===1,()=>`Expected the rank of labels to be 1, but got ${o.rank}`),T(n.rank===1,()=>`Expected the rank of predictions to be 1, but got ${n.rank}`),T(o.shape[0]===n.shape[0],()=>`Mismatch in the number of examples: ${o.shape[0]} vs. ${n.shape[0]}. Labels and predictions should have the same number of elements.`),T(t>0&&Number.isInteger(t),()=>`numClasses is required to be a positive integer, but got ${t}`);let s=Cs(ne(o,"int32"),t),a=Cs(ne(n,"int32"),t),i=Ue(s),l=We(i,a);return ne(l,"int32")}var rV=S({confusionMatrix_:tV});var Xh={};Ke(Xh,{fromPixels:()=>uV,fromPixelsAsync:()=>aV,toPixels:()=>lV});function sw(r,e,t){if(Do(r),e!=null&&e.length!==3)throw new Error("tensor3d() requires shape to have three numbers");let o=vr(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 Ur(r,e,o,t)}var jc;function oN(r,e=3){if(e>4)throw new Error("Cannot construct Tensor with more than 4 channels from pixels.");if(r==null)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");let t=!1,o=!1,n=!1,s=!1,a=!1,i=!1;if(r.data instanceof Uint8Array)t=!0;else if(typeof ImageData!="undefined"&&r instanceof ImageData)o=!0;else if(typeof HTMLVideoElement!="undefined"&&r instanceof HTMLVideoElement)n=!0;else if(typeof HTMLImageElement!="undefined"&&r instanceof HTMLImageElement)s=!0;else if(r.getContext!=null)a=!0;else if(typeof ImageBitmap!="undefined"&&r instanceof ImageBitmap)i=!0;else throw new Error(`pixels passed to tf.browser.fromPixels() must be either an HTMLVideoElement, HTMLImageElement, HTMLCanvasElement, ImageData in browser, or OffscreenCanvas, ImageData in webworker or {data: Uint32Array, width: number, height: number}, but was ${r.constructor.name}`);if(n){let d=2;if(n&&r.readyState<d)throw new Error("The video element has not loaded data yet. Please wait for `loadeddata` event on the <video> element.")}if(Mc(Oc,E.backendName)!=null){let d={pixels:r},h={numChannels:e};return E.runKernel(Oc,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;h<d;h++)for(let g=0;g<e;++g)m[h*e+g]=p[h*4+g]}return sw(m,[c,u,e],"int32")}function oV(r){return r!=null&&r.data instanceof Uint8Array}function nV(){return typeof window!="undefined"&&typeof ImageBitmap!="undefined"&&window.hasOwnProperty("createImageBitmap")}function sV(r){return r!=null&&r.width!==0&&r.height!==0}function iV(r){return nV()&&!(r instanceof ImageBitmap)&&sV(r)&&!oV(r)}async function aV(r,e=3){let t=null;if(W().getBool("WRAP_TO_IMAGEBITMAP")&&iV(r)){let o;try{o=await createImageBitmap(r,{premultiplyAlpha:"none"})}catch(n){o=null}o!=null&&o.width===r.width&&o.height===r.height?t=o:t=r}else t=r;return oN(t,e)}async function lV(r,e){let t=_(r,"img","toPixels");if(!(r instanceof Ve)){let u=t;t=ne(u,"int32"),u.dispose()}if(t.rank!==2&&t.rank!==3)throw new Error(`toPixels only supports rank 2 or 3 tensors, got rank ${t.rank}.`);let[o,n]=t.shape.slice(0,2),s=t.rank===2?1:t.shape[2];if(s>4||s===2)throw new Error(`toPixels only supports depth of size 1, 3 or 4 but got ${s}`);if(t.dtype!=="float32"&&t.dtype!=="int32")throw new Error(`Unsupported type for toPixels: ${t.dtype}. Please use float32 or int32 tensors.`);let a=await t.data(),i=t.dtype==="float32"?255:1,l=new Uint8ClampedArray(n*o*4);for(let u=0;u<o*n;++u){let c=[0,0,0,255];for(let m=0;m<s;m++){let f=a[u*s+m];if(t.dtype==="float32"){if(f<0||f>1)throw new Error(`Tensor values for a float32 Tensor must be in the range [0 - 1] but encountered ${f}.`)}else if(t.dtype==="int32"&&(f<0||f>255))throw new Error(`Tensor values for a int32 Tensor must be in the range [0 - 255] but encountered ${f}.`);s===1?(c[0]=f*i,c[1]=f*i,c[2]=f*i):c[m]=f*i}let p=u*4;l[p+0]=Math.round(c[0]),l[p+1]=Math.round(c[1]),l[p+2]=Math.round(c[2]),l[p+3]=Math.round(c[3])}if(e!=null){e.width=n,e.height=o;let u=e.getContext("2d"),c=new ImageData(l,n,o);u.putImageData(c,0,0)}return t!==r&&t.dispose(),l}var uV=S({fromPixels_:oN});var Yh={};Ke(Yh,{prepareAndValidate:()=>nN});function nN(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(ct(r.shape)===0)throw new Error(`Requested more than 0 entries, but input is empty. Input shape: ${r.shape}.`);let n=e.shape,s=n[n.length-1],a=1;for(let p=0;p<n.length-1;++p)a*=n[p];let i=r.shape,l=n.slice();l.pop();let u=1;for(let p=s;p<t;++p)u*=i[p],l.push(i[p]);let c=[...Hs(r.shape).map(p=>p/u),1].slice(0,s);return[l,a,u,c]}var Zh={};Ke(Zh,{calculateShapes:()=>sN,validateInput:()=>Jh,validateUpdateShape:()=>iw});function iw(r,e,t){let o=e.rank>1?e.shape[e.rank-1]:1,n=e.rank>1?e.rank-1:1,s=`Must have updates.shape = indices.shape[:batchDim] + shape[sliceDim:], got updates.shape: ${t.shape}, indices.shape: ${e.shape}, shape: ${r}, sliceDim: ${o}, and batchDim: ${n}.`;if(t.rank<n)throw new Error(s+` update.rank < ${n}. `);if(r.length<o+(t.rank-n))throw new Error(s+` Output shape length < ${o+(t.rank-n)}`);if(t.rank!==n+r.length-o)throw new Error(s+` update.rank != ${n+r.length-o}`);for(let a=0;a<n;++a)if(t.shape[a]!==e.shape[a])throw new Error(s+` updates.shape[${a}] (${t.shape[a]}) != indices.shape[${a}] (${e.shape[a]}).`);for(let a=0;a<t.rank-n;++a)if(t.shape[a+n]!==r[a+o])throw new Error(s+` updates.shape[${a+n}] (${t.shape[a+n]}) != shape[${a+n}] (${r[a+n]})`)}function Jh(r,e,t){if(e.rank<1)throw new Error(`tf.scatterND() expects the indices to be rank 1 or higher, but the rank was ${e.rank}.`);if(r.rank<1)throw new Error(`tf.scatterND() expects the updates to be rank 1 or higher, but the rank was ${r.rank}.`);if(e.dtype!=="int32")throw new Error(`The dtype of 'indices' should be int32, but got dtype: ${e.dtype}`);if(t.length<1)throw new Error(`Output rank must be greater or equal to 1, but got shape: ${t}`);if(t.length===0){if(e.size===0)throw new Error(`Indices specified for empty output. indices shape: ${e.shape}`);if(r.size===0)throw new Error(`Updates specified for empty output. updates shape: ${r.shape}`)}iw(t,e,r)}function sN(r,e,t){let o=e.shape.length,n=o>1?e.shape[o-1]:1,s=t.length,a=1;for(let p=n;p<s;++p)a*=t[p];let i=n<1?1:n,l=ct(e.shape)/i,u=[...Hs(t.slice(0,n)),1],c=ct(t);return{sliceRank:n,numUpdates:l,sliceSize:a,strides:u,outputSize:c}}var nr={};Ke(nr,{assertParamsValid:()=>cV,computeFlatOffset:()=>mV,computeOutShape:()=>iN,getNormalizedAxes:()=>hN,isSliceContinous:()=>pV,maskToAxes:()=>Qh,parseSliceParams:()=>aw,sliceInfo:()=>fV,startForAxis:()=>fN,startIndicesWithElidedDims:()=>cN,stopForAxis:()=>dN,stopIndicesWithElidedDims:()=>pN,stridesForAxis:()=>mN,stridesWithElidedDims:()=>aN});function cV(r,e,t){let o=r.shape.length;T(o===e.length,()=>`Error in slice${o}D: Length of begin ${e} must match the rank of the array (${o}).`),T(o===t.length,()=>`Error in slice${o}D: Length of size ${t} must match the rank of the array (${o}).`);for(let n=0;n<o;++n)T(e[n]+t[n]<=r.shape[n],()=>`Error in slice${o}D: begin[${n}] + size[${n}] (${e[n]+t[n]}) would overflow input.shape[${n}] (${r.shape[n]})`)}function Qh(r){let e=[],t=0;for(;r>0;)r&1&&e.push(t),r/=2,t++;return e}function iN(r,e,t){let o=[];for(let n=0;n<r.length;n++)o[n]=Math.ceil((e[n]-r[n])/t[n]);return o}function aN(r,e,t,o){let n=[...r];for(let s=n.length;s<o.length;s++)n.push(1);for(let s=0;s<t;s++)s===0?n[e]=1:(n.splice(e,0,1),n.pop());return n}function lN(r,e,t){return t<=r?t:t-(e-1)}function uN(r,e){let t=[];for(let o=0;o<r;o++)t.push(e+o);return t}function hN(r,e,t,o,n,s,a,i,l){let u=r.length,c=new Array(u),p=new Array(u),m=new Array(u);if(e.length&&t>0){let f=e[0],d=t+1;c=cN(a,f,d,o,r),p=pN(i,f,d,n,r),m=aN(s,f,d,r)}else for(let f=0;f<u;f++)c[f]=fN(a,o,s,r,f,l),p[f]=dN(i,n,s,r,f,l),m[f]=mN(s,f,l);return{begin:c,end:p,strides:m}}function cN(r,e,t,o,n){let s=[...n],a=uN(t,e);for(let i=0;i<s.length;i++)if(a.indexOf(i)>-1)s[i]=0;else{let l=lN(e,t,i),u=o[l];r&1<<l&&(u=0),s[i]=u}return s}function pN(r,e,t,o,n){let s=[...n],a=uN(t,e);for(let i=0;i<s.length;i++)if(a.indexOf(i)>-1)s[i]=Number.MAX_SAFE_INTEGER;else{let l=lN(e,t,i),u=o[l];r&1<<l&&(u=Number.MAX_SAFE_INTEGER),s[i]=u}for(let i=0;i<s.length;i++){let l=n[i];s[i]<0&&(s[i]+=l),s[i]=Ac(0,s[i],n[i])}return s}function mN(r,e,t){let o=r[e];return(t&1<<e||o==null)&&(o=1),o}function fN(r,e,t,o,n,s){let a=e[n],i=t[n]||1;(r&1<<n||s&1<<n||a==null)&&(i>0?a=Number.MIN_SAFE_INTEGER:a=Number.MAX_SAFE_INTEGER);let l=o[n];return a<0&&(a+=l),a=Ac(0,a,l-1),a}function dN(r,e,t,o,n,s){let a=e[n],i=t[n]||1;(r&1<<n||s&1<<n||a==null)&&(i>0?a=Number.MAX_SAFE_INTEGER:a=Number.MIN_SAFE_INTEGER);let l=o[n];return a<0&&(a+=l),i>0?a=Ac(0,a,l):a=Ac(-1,a,l-1),a}function pV(r,e,t){let o=t.length;for(let n=0;n<t.length;n++)if(t[n]>1){o=n;break}for(let n=o+1;n<t.length;n++)if(e[n]>0||t[n]!==r[n])return!1;return!0}function mV(r,e){let t=r.length>0?r[r.length-1]:1;for(let o=0;o<r.length-1;o++)t+=r[o]*e[o];return t}function aw(r,e,t){let o,n=r.shape.length;typeof e=="number"?o=[e,...new Array(n-1).fill(0)]:e.length<n?o=e.concat(new Array(n-e.length).fill(0)):o=e.slice(),o.forEach(a=>{T(a!==-1,()=>"slice() does not support negative begin indexing.")});let s;return t==null?s=new Array(n).fill(-1):typeof t=="number"?s=[t,...new Array(n-1).fill(-1)]:t.length<n?s=t.concat(new Array(n-t.length).fill(-1)):s=t,s=s.map((a,i)=>a>=0?a:(T(a===-1,()=>`Negative size values should be exactly -1 but got ${a} for the slice() size at index ${i}.`),r.shape[i]-o[i])),[o,s]}function fV(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=Qh(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=Qh(i),h=r.slice();d.forEach(A=>{u[A]=0,c[A]=1,h.splice(A,0,1)});let{begin:g,end:y,strides:b}=hN(h,m,f,u,c,p,n,s,a);u=g,c=y,p=b;let w=Qh(l);w.forEach(A=>{c[A]=u[A]+1,p[A]=1});let k=iN(u,c,p),v=k.filter((A,R)=>w.indexOf(R)===-1);return{nonStrided:p.every(A=>A===1),$begin:u,$end:c,$strides:p,size:k,newShape:h,outShape:v}}var Q={};Ke(Q,{Serializable:()=>eg,SerializationMap:()=>ba,registerClass:()=>so});var eg=class{getClassName(){return this.constructor.className}static fromConfig(e,t){return new e(t)}},ba=class{constructor(){this.classNameMap={}}static getMap(){return ba.instance==null&&(ba.instance=new ba),ba.instance}static register(e){ba.getMap().classNameMap[e.className]=[e,e.fromConfig]}};function so(r){T(r.className!=null,()=>"Class being registered does not have the static className property defined."),T(typeof r.className=="string",()=>"className is required to be a string, but got type "+typeof r.className),T(r.className.length>0,()=>"Class being registered has an empty-string as its className, which is disallowed."),ba.register(r)}var gN={};Ke(gN,{TEST_EPSILON_FLOAT16:()=>xN,encodeStrings:()=>yN,expectArrayBuffersEqual:()=>wV,expectArraysClose:()=>hV,expectArraysEqual:()=>xV,expectNumbersClose:()=>yV,expectPromiseToFail:()=>gV,expectValuesInRange:()=>bV,testEpsilon:()=>lw});var dV=.001,xN=.1;function hV(r,e,t){return t==null&&(t=lw()),uw(r,e,(o,n)=>cw(o,n,t))}function lw(){return E.backend.floatPrecision()===32?dV:xN}function uw(r,e,t){let o=!0;if((or(r)||or(e))&&(o=!1),or(r)&&or(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=vr(r),i=vr(e);if(!jr(a,i))throw new Error(`Arrays have different shapes. Actual: [${a}]. Expected: [${i}]`)}let n=or(r)?r:ss(r),s=or(e)?e:ss(e);if(n.length!==s.length)throw new Error(`Arrays have different lengths actual: ${n.length} vs expected: ${s.length}.
|
|
Actual: ${n}.
|
|
Expected: ${s}.`);for(let a=0;a<s.length;++a){let i=n[a],l=s[a];if(!t(i,l))throw new Error(`Arrays differ: actual[${a}] = ${i}, expected[${a}] = ${l}.
|
|
Actual: ${n}.
|
|
Expected: ${s}.`)}}function gV(r,e){r().then(()=>e.fail(),()=>e())}function xV(r,e){let t=typeof e=="string"||typeof e=="number"||typeof e=="boolean"?[e]:e;return is(r)||is(r[0])||is(e)||is(e[0])?uw(r,t,(o,n)=>o==n):uw(r,e,(o,n)=>cw(o,n,0))}function yV(r,e,t){if(t==null&&(t=lw()),!cw(r,e,t))throw new Error(`Numbers differ: actual === ${r}, expected === ${e}`)}function cw(r,e,t){return!isFinite(r)&&!isFinite(e)?!0:!(isNaN(r)||isNaN(e)||Math.abs(r-e)>t)}function bV(r,e,t){for(let o=0;o<r.length;o++)if(r[o]<e||r[o]>t)throw new Error(`Value out of range:${r[o]} low: ${e}, high: ${t}`)}function wV(r,e){expect(new Float32Array(r)).toEqual(new Float32Array(e))}function yN(r){for(let e=0;e<r.length;e++){let t=r[e];Array.isArray(t)?yN(t):r[e]=tl(t)}return r}var kV="3.3.0";function _V(){W().set("PROD",!0)}function vV(){W().set("DEBUG",!0)}function CV(){W().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")}function tg(r){W().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(r+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}k0(tg);function IV(){E.disposeVariables()}function Mo(){return E}function Uc(){return E.memory()}function NV(r){return E.profile(r)}function V(r,e){return E.tidy(r,e)}function Ae(r){ym(r).forEach(t=>t.dispose())}function Et(r){return E.keep(r)}function SV(r){return E.time(r)}function bN(r){return E.setBackend(r)}function TV(){return E.ready()}function AV(){return E.backendName}function EV(r){E.removeBackend(r)}function DV(r){return E.findBackend(r)}function $V(r){return E.findBackendFactory(r)}function xu(r,e,t=1){return E.registerBackend(r,e,t)}function pw(){return E.backend}function RV(r,e){W().setPlatform(r,e)}function FV(r,e){let t=_(r,"a","add"),o=_(e,"b","add");[t,o]=Ge(t,o);let n={a:t,b:o};return E.runKernel(wo,n)}var ee=S({add_:FV});function OV(r,e){let t=_(r,"a","floorDiv"),o=_(e,"b","floorDiv");[t,o]=Ge(t,o);let n={a:t,b:o};return E.runKernel(sn,n)}var yu=S({floorDiv_:OV});function PV(r,e){let t=_(r,"a","div"),o=_(e,"b","div");if([t,o]=Ge(t,o),t.dtype==="int32"&&o.dtype==="int32")return yu(t,o);let n={a:t,b:o},s={};return E.runKernel(rn,n,s)}var me=S({div_:PV});function MV(r,e){let t=_(r,"a","mul"),o=_(e,"b","mul");[t,o]=Ge(t,o);let n={a:t,b:o};return E.runKernel(xn,n)}var O=S({mul_:MV});function LV(r){let e=_(r,"x","abs");if(e.dtype==="complex64"){let t={x:e};return E.runKernel(oa,t)}else{let t={x:e};return E.runKernel(as,t)}}var It=S({abs_:LV});function zV(r){let t={x:_(r,"x","acos")};return E.runKernel(qs,t)}var wm=S({acos_:zV});function BV(r){let t={x:_(r,"x","acosh")};return E.runKernel(Ks,t)}var km=S({acosh_:BV});function VV(r){T(Array.isArray(r),()=>"The argument passed to tf.addN() must be a list of tensors"),T(r.length>=1,()=>`Must pass at least one tensor to tf.addN(), but got ${r.length}`);let e=r.map((n,s)=>_(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 E.runKernel(Ho,o)}var mw=S({addN_:VV});function GV(r,e=null,t=!1){let n={x:_(r,"x","all","bool")},s={axis:e,keepDims:t};return E.runKernel(Ml,n,s)}var bu=S({all_:GV});function WV(r,e=null,t=!1){let n={x:_(r,"x","any","bool")},s={axis:e,keepDims:t};return E.runKernel(Ll,n,s)}var sl=S({any_:WV});function jV(r,e=0){let o={x:_(r,"x","argMax")},n={axis:e};return E.runKernel(qo,o,n)}var il=S({argMax_:jV});function UV(r,e=0){let o={x:_(r,"x","argMin")},n={axis:e};return E.runKernel(ea,o,n)}var _m=S({argMin_:UV});function HV(r){let t={x:_(r,"x","asin")};return E.runKernel(Xs,t)}var vm=S({asin_:HV});function qV(r){let t={x:_(r,"x","asinh")};return E.runKernel(Ys,t)}var Cm=S({asinh_:qV});function KV(r){let t={x:_(r,"x","atan")};return E.runKernel(Zs,t)}var Im=S({atan_:KV});function XV(r,e){let t=_(r,"a","atan2"),o=_(e,"b","atan2");[t,o]=Ge(t,o);let n={a:t,b:o};return E.runKernel(Qs,n)}var Nm=S({atan2_:XV});function YV(r){let t={x:_(r,"x","atanh")};return E.runKernel(Js,t)}var Sm=S({atanh_:YV});function ZV(r,e,t,o,n="NHWC",s){let a=r[3],i=[...e,a],l=wN(n);return wu(r,i,t,s,o,null,null,l)}function fw(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 wu(r,u,t,o,n,s,!1,a)}function JV(r,e,t,o,n,s,a="NDHWC"){let[i,l,u]=dw(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 kN(r,c,t,o,n,!1,p,s)}function wu(r,e,t,o,n,s,a=!1,i="channelsLast"){let[l,u,c,p]=[-1,-1,-1,-1];if(i==="channelsLast")[l,u,c,p]=r;else if(i==="channelsFirst")[l,p,u,c]=r;else throw new Error(`Unknown dataFormat ${i}`);let[m,f,,d]=e,[h,g]=rg(t),[y,b]=rg(o),w=Hc(m,y),k=Hc(f,b),{padInfo:v,outHeight:D,outWidth:A}=QV(n,u,c,h,g,w,k,s,i),R=a?d*p:d,P;return i==="channelsFirst"?P=[l,R,D,A]:i==="channelsLast"&&(P=[l,D,A,R]),{batchSize:l,dataFormat:i,inHeight:u,inWidth:c,inChannels:p,outHeight:D,outWidth:A,outChannels:R,padInfo:v,strideHeight:h,strideWidth:g,filterHeight:m,filterWidth:f,effectiveFilterHeight:w,effectiveFilterWidth:k,dilationHeight:y,dilationWidth:b,inShape:r,outShape:P,filterShape:e}}function kN(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,w]=dw(t),[k,v,D]=dw(o),A=Hc(f,k),R=Hc(d,v),P=Hc(h,D),{padInfo:L,outDepth:G,outHeight:j,outWidth:U}=eG(n,u,c,p,y,b,w,A,R,P,i),H=s?g*m:g,q;return a==="channelsFirst"?q=[l,H,G,j,U]:a==="channelsLast"&&(q=[l,G,j,U,H]),{batchSize:l,dataFormat:a,inDepth:u,inHeight:c,inWidth:p,inChannels:m,outDepth:G,outHeight:j,outWidth:U,outChannels:H,padInfo:L,strideDepth:y,strideHeight:b,strideWidth:w,filterDepth:f,filterHeight:d,filterWidth:h,effectiveFilterDepth:A,effectiveFilterHeight:R,effectiveFilterWidth:P,dilationDepth:k,dilationHeight:v,dilationWidth:D,inShape:r,outShape:q,filterShape:e}}function tG(r,e,t,o,n){o==null&&(o=hw(r,e,t));let s=r[0],a=r[1],i=ku((s-e+2*o)/t+1,n),l=ku((a-e+2*o)/t+1,n);return[i,l]}function rG(r,e,t,o,n,s){n==null&&(n=hw(r,e,o));let a=r[0],i=r[1],l=r[2],u=ku((a-e+2*n)/o+1,s),c=ku((i-e+2*n)/o+1,s),p=ku((l-e+2*n)/o+1,s);return[u,c,p,t]}function hw(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 dw(r){return typeof r=="number"?[r,r,r]:r}function Hc(r,e){return e<=1?r:r+(r-1)*(e-1)}function QV(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=tG([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=ku((e-s+m+f)/o+1,i),p=ku((t-a+d+h)/n+1,i)}else throw Error(`Unknown padding parameter: ${r}`);return{padInfo:u,outHeight:c,outWidth:p}}function eG(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=rG([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),w=h-b,k=Math.floor(g/2),v=g-k,D=Math.floor(y/2),A=y-D;p={top:k,bottom:v,left:D,right:A,front:b,back:w,type:"SAME"}}else if(r==="valid")p={top:0,bottom:0,left:0,right:0,front:0,back:0,type:"VALID"},m=Math.ceil((e-i+1)/n),f=Math.ceil((t-l+1)/s),d=Math.ceil((o-u+1)/a);else throw Error(`Unknown padding parameter: ${r}`);return{padInfo:p,outDepth:m,outHeight:f,outWidth:d}}function ku(r,e){if(!e)return Math.trunc(r);switch(e){case"round":return Math.round(r);case"ceil":return Math.ceil(r);case"floor":return Math.floor(r);default:throw new Error(`Unknown roundingMode ${e}`)}}function Lo(r){let[e,t,o]=rg(r);return e===1&&t===1&&o===1}function wr(r,e){return Lo(r)||Lo(e)}function wN(r){if(r==="NHWC")return"channelsLast";if(r==="NCHW")return"channelsFirst";throw new Error(`Unknown dataFormat ${r}`)}function oG(r,e){let o={x:_(r,"x","reshape","string_or_numeric")},n={shape:e};return E.runKernel(ds,o,n)}var M=S({reshape_:oG});function nG(r,e,t,o,n){let s=_(r,"x","avgPool","float32"),a=1;T(wr(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=M(s,[1,s.shape[0],s.shape[1],s.shape[2]])),T(i.rank===4,()=>`Error in avgPool: x must be rank 4 but got rank ${i.rank}.`),n!=null&&T(ot(o),()=>`Error in avgPool: pad must be an integer when using, dimRoundingMode ${n} but got pad ${o}.`);let u={x:i},c={filterSize:e,strides:t,pad:o,dimRoundingMode:n},p=E.runKernel(Ko,u,c);return p=ne(p,s.dtype),l?M(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var wa=S({avgPool_:nG});function sG(r,e,t,o,n,s="NDHWC"){let a=_(r,"x","avgPool3d","float32"),i=a,l=!1;a.rank===4&&(l=!0,i=M(a,[1,a.shape[0],a.shape[1],a.shape[2],a.shape[3]])),T(i.rank===5,()=>`Error in avgPool3d: x must be rank 5 but got rank ${i.rank}.`),T(s==="NDHWC",()=>`Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of ${s}`),n!=null&&T(ot(o),()=>`Error in avgPool3d: pad must be an integer when using, dimRoundingMode ${n} but got pad ${o}.`);let u={x:i},c={filterSize:e,strides:t,pad:o,dimRoundingMode:n,dataFormat:s},p=E.runKernel(ta,u,c);return p=ne(p,i.dtype),l?M(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}var Tm=S({avgPool3d_:sG});function iG(r,e=0){T(r.length>=1,()=>"Pass at least one tensor to concat");let t=ha(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 E.runKernel(ls,o,n)}var Ze=S({concat_:iG});function aG(r){let t={x:_(r,"x","sigmoid")};return E.runKernel(An,t)}var qr=S({sigmoid_:aG});function lG(r,e,t){let o=_(r,"x","slice","string_or_numeric");if(o.rank===0)throw new Error("Slicing scalar is not possible");let n={x:o},s={begin:e,size:t};return E.runKernel(gs,n,s)}var Re=S({slice_:lG});function uG(r){let t={x:_(r,"x","tanh")};return E.runKernel(On,t)}var Oi=S({tanh_:uG});function cG(r,e,t,o,n,s){let a=_(r,"forgetBias","basicLSTMCell"),i=_(e,"lstmKernel","basicLSTMCell"),l=_(t,"lstmBias","basicLSTMCell"),u=_(o,"data","basicLSTMCell"),c=_(n,"c","basicLSTMCell"),p=_(s,"h","basicLSTMCell"),m=Ze([u,p],1),f=We(m,i),d=ee(f,l),h=d.shape[0],g=d.shape[1]/4,y=[h,g],b=Re(d,[0,0],y),w=Re(d,[0,g],y),k=Re(d,[0,g*2],y),v=Re(d,[0,g*3],y),D=ee(O(qr(b),Oi(w)),O(c,qr(ee(a,k)))),A=O(Oi(D),qr(v));return[D,A]}var pG=S({basicLSTMCell_:cG});function mG(r,e,t){let o=_(r,"x","batchToSpaceND"),n=e.reduce((i,l)=>i*l);T(o.rank>=1+e.length,()=>`input rank is ${o.rank} but should be > than blockShape.length ${e.length}`),T(t.length===e.length,()=>`crops.length is ${t.length} but should be equal to blockShape.length ${e.length}`),T(o.shape[0]%n==0,()=>`input tensor batch is ${o.shape[0]} but is not divisible by the product of the elements of blockShape ${e.join(" * ")} === ${n}`);let s={x:o},a={blockShape:e,crops:t};return E.runKernel(ra,s,a)}var ka=S({batchToSpaceND_:mG});function _N(r){let e;return r.rank===0||r.rank===1?e=M(r,[1,1,1,r.size]):r.rank===2?e=M(r,[1,1,r.shape[0],r.shape[1]]):r.rank===3?e=M(r,[1,r.shape[0],r.shape[1],r.shape[2]]):e=r,e}function fG(r,e,t,o,n,s){s==null&&(s=.001);let a=_(r,"x","batchNorm"),i=_(e,"mean","batchNorm"),l=_(t,"variance","batchNorm"),u;n!=null&&(u=_(n,"scale","batchNorm"));let c;o!=null&&(c=_(o,"offset","batchNorm")),T(i.rank===l.rank,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),T(c==null||i.rank===c.rank,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),T(u==null||i.rank===u.rank,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let m={x:_N(a),scale:u,offset:c,mean:i,variance:l},f={varianceEpsilon:s},d=E.runKernel(an,m,f);return M(d,a.shape)}var Ln=S({batchNorm_:fG});function dG(r,e,t,o,n,s){let a=_(r,"x","batchNorm"),i=_(e,"mean","batchNorm"),l=_(t,"variance","batchNorm"),u;n!=null&&(u=_(n,"scale","batchNorm"));let c;return o!=null&&(c=_(o,"offset","batchNorm")),T(a.rank===2,()=>`Error in batchNorm2D: x must be rank 2 but got rank ${a.rank}.`),T(i.rank===2||i.rank===1,()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${i.rank}.`),T(l.rank===2||l.rank===1,()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${l.rank}.`),u!=null&&T(u.rank===2||u.rank===1,()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${u.rank}.`),c!=null&&T(c.rank===2||c.rank===1,()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${c.rank}.`),Ln(a,i,l,c,u,s)}var gw=S({batchNorm2d_:dG});function hG(r,e,t,o,n,s){let a=_(r,"x","batchNorm"),i=_(e,"mean","batchNorm"),l=_(t,"variance","batchNorm"),u;n!=null&&(u=_(n,"scale","batchNorm"));let c;return o!=null&&(c=_(o,"offset","batchNorm")),T(a.rank===3,()=>`Error in batchNorm3D: x must be rank 3 but got rank ${a.rank}.`),T(i.rank===3||i.rank===1,()=>`Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank ${i.rank}.`),T(l.rank===3||l.rank===1,()=>`Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank ${l.rank}.`),u!=null&&T(u.rank===3||u.rank===1,()=>`Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank ${u.rank}.`),c!=null&&T(c.rank===3||c.rank===1,()=>`Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank ${c.rank}.`),Ln(a,i,l,c,u,s)}var xw=S({batchNorm3d_:hG});function gG(r,e,t,o,n,s){let a=_(r,"x","batchNorm"),i=_(e,"mean","batchNorm"),l=_(t,"variance","batchNorm"),u;n!=null&&(u=_(n,"scale","batchNorm"));let c;return o!=null&&(c=_(o,"offset","batchNorm")),T(a.rank===4,()=>`Error in batchNorm4D: x must be rank 4 but got rank ${a.rank}.`),T(i.rank===4||i.rank===1,()=>`Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank ${i.rank}.`),T(l.rank===4||l.rank===1,()=>`Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank ${l.rank}.`),u!=null&&T(u.rank===4||u.rank===1,()=>`Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank ${u.rank}.`),c!=null&&T(c.rank===4||c.rank===1,()=>`Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank ${c.rank}.`),Ln(a,i,l,c,u,s)}var yw=S({batchNorm4d_:gG});function xG(r,e,t){let o=_(r,"x","bincount"),n=_(e,"weights","bincount");T(o.dtype==="int32",()=>`Error in bincount: input dtype must be int32, but got ${o.dtype}`),T(t>=0,()=>`size must be non-negative, but got ${t}.`),T(n.size===o.size||n.size===0,()=>`Error in bincount: weights must have the same size as input or0-length, but got input shape: ${o.shape}, weights shape: ${n.shape}.`);let s={x:o,weights:n},a={size:t};return E.runKernel(Vl,s,a)}var bw=S({bincount_:xG});function yG(r,e){let t=_(r,"broadcastTo","x"),o=t.shape;if(e.some(u=>!(u>0)||u%1!=0))throw new Error(`broadcastTo(): Invalid broadcast shape [${e}].`);if(e.length<t.rank)throw new Error(`broadcastTo(): shape.length=${e.length} < input.rank=${t.rank}.`);if(e.length>t.rank){let u=t.shape.slice();for(;u.length<e.length;)u.unshift(1);t=M(t,u)}let n=t.shape,s=Array.from(e);for(let u=e.length-1;u>=0;u--)if(n[u]===e[u])s[u]=1;else if(t.shape[u]!==1)throw new Error(`broadcastTo(): [${o}] cannot be broadcast to [${e}].`);if(s.map((u,c)=>u>1?c:-1).filter(u=>u>=0).length===0)return Po(t);let i={x:t},l={reps:s};return E.runKernel(ko,i,l)}var al=S({broadcastTo_:yG});function bG(r){let t={x:_(r,"x","ceil")};return E.runKernel(Yo,t)}var Am=S({ceil_:bG});function wG(r,e,t){let o=_(r,"x","clipByValue");T(e<=t,()=>`Error in clip: min (${e}) must be less than or equal to max (${t}).`);let n={x:o},s={clipValueMin:e,clipValueMax:t};return E.runKernel(Ro,n,s)}var sr=S({clipByValue_:wG});function kG(r){return Ze(r,0)}var ww=S({concat1d_:kG});function _G(r,e){return Ze(r,e)}var kw=S({concat2d_:_G});function vG(r,e){return Ze(r,e)}var _w=S({concat3d_:vG});function CG(r,e){return Ze(r,e)}var vw=S({concat4d_:CG});function IG(r,e,t,o,n="NHWC",s=[1,1],a){let i=_(r,"x","conv2d"),l=_(e,"filter","conv2d"),u=i,c=!1;i.rank===3&&(c=!0,u=M(i,[1,i.shape[0],i.shape[1],i.shape[2]])),T(u.rank===4,()=>`Error in conv2d: input must be rank 4, but got rank ${u.rank}.`),T(l.rank===4,()=>`Error in conv2d: filter must be rank 4, but got rank ${l.rank}.`),a!=null&&T(ot(o),()=>`Error in conv2d: pad must be an integer when using, dimRoundingMode ${a} but got pad ${o}.`);let p=n==="NHWC"?u.shape[3]:u.shape[1];T(p===l.shape[2],()=>`Error in conv2d: depth of input (${p}) must match input depth for filter ${l.shape[2]}.`),T(wr(t,s),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${t} and dilations '${s}'`);let m={x:u,filter:l},f={strides:t,pad:o,dataFormat:n,dilations:s,dimRoundingMode:a},d=E.runKernel(Zo,m,f);return c?M(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var Kr=S({conv2d_:IG});function NG(r,e,t,o,n="NWC",s=1,a){let i=_(r,"x","conv1d"),l=_(e,"filter","conv1d"),u=i,c=!1;i.rank===2&&(c=!0,u=M(i,[1,i.shape[0],i.shape[1]])),T(u.rank===3,()=>`Error in conv1d: input must be rank 3, but got rank ${u.rank}.`),T(l.rank===3,()=>`Error in conv1d: filter must be rank 3, but got rank ${l.rank}.`),a!=null&&T(ot(o),()=>`Error in conv1d: pad must be an integer when using, dimRoundingMode ${a} but got pad ${o}.`),T(u.shape[2]===l.shape[1],()=>`Error in conv1d: depth of input (${u.shape[2]}) must match input depth for filter ${l.shape[1]}.`),T(wr(t,s),()=>`Error in conv1D: Either stride or dilation must be 1. Got stride ${t} and dilation '${s}'`),T(n==="NWC",()=>`Error in conv1d: got dataFormat of ${n} but only NWC is currently supported.`);let p=M(l,[1,l.shape[0],l.shape[1],l.shape[2]]),m=M(u,[u.shape[0],1,u.shape[1],u.shape[2]]),g=Kr(m,p,[1,t],o,"NHWC",[1,s],a);return c?M(g,[g.shape[2],g.shape[3]]):M(g,[g.shape[0],g.shape[2],g.shape[3]])}var _u=S({conv1d_:NG});function SG(r,e,t,o,n,s="NHWC",a){T(r.length===e.rank,()=>`Length of inShape (${r.length}) and rank of dy (${e.rank}) must match`);let i=r,l=e,u=!1;e.rank===3&&(u=!0,l=M(e,[1,e.shape[0],e.shape[1],e.shape[2]]),i=[1,r[0],r[1],r[2]]),T(i.length===4,()=>`Error in conv2dDerInput: inShape must be length 4, but got length ${i.length}.`),T(l.rank===4,()=>`Error in conv2dDerInput: dy must be rank 4, but got rank ${l.rank}`),T(t.rank===4,()=>`Error in conv2dDerInput: filter must be rank 4, but got rank ${t.rank}`);let c=s==="NHWC"?i[3]:i[1],p=s==="NHWC"?l.shape[3]:l.shape[1];T(c===t.shape[2],()=>`Error in conv2dDerInput: depth of input (${c}) must match input depth for filter ${t.shape[2]}.`),T(p===t.shape[3],()=>`Error in conv2dDerInput: depth of output (${p}) must match output depth for filter ${t.shape[3]}.`),a!=null&&T(ot(n),()=>`Error in conv2dDerInput: pad must be an integer when using, dimRoundingMode ${a} but got pad ${n}.`);let m={dy:l,filter:t},f={strides:o,pad:n,dataFormat:s,dimRoundingMode:a,inputShape:i},d=E.runKernel(Jo,m,f);return u?M(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var qc=S({conv2DBackpropInput_:SG});function TG(r,e,t,o,n,s){let a=_(r,"x","conv2dTranspose"),i=_(e,"filter","conv2dTranspose");return qc(t,a,i,o,n,"NHWC",s)}var vu=S({conv2dTranspose_:TG});function AG(r,e,t,o,n="NDHWC",s=[1,1,1]){let a=_(r,"x","conv3d"),i=_(e,"filter","conv3d"),l=a,u=!1;a.rank===4&&(u=!0,l=M(a,[1,a.shape[0],a.shape[1],a.shape[2],a.shape[3]])),T(l.rank===5,()=>`Error in conv3d: input must be rank 5, but got rank ${l.rank}.`),T(i.rank===5,()=>`Error in conv3d: filter must be rank 5, but got rank ${i.rank}.`),T(l.shape[4]===i.shape[3],()=>`Error in conv3d: depth of input (${l.shape[4]}) must match input depth for filter ${i.shape[3]}.`),T(wr(t,s),()=>`Error in conv3D: Either strides or dilations must be 1. Got strides ${t} and dilations '${s}'`),T(n==="NDHWC",()=>`Error in conv3d: got dataFormat of ${n} but only NDHWC is currently supported.`);let c={x:l,filter:i},p={strides:t,pad:o,dataFormat:n,dilations:s},m=E.runKernel(na,c,p);return u?M(m,[m.shape[1],m.shape[2],m.shape[3],m.shape[4]]):m}var Em=S({conv3d_:AG});function EG(r,e,t,o,n){T(r.length===e.rank,()=>`Length of inShape (${r.length}) and rank of dy (${e.rank}) must match`);let s=r,a=e,i=!1;e.rank===4&&(i=!0,a=M(e,[1,e.shape[0],e.shape[1],e.shape[2],e.shape[3]]),s=[1,r[0],r[1],r[2],r[3]]);let l=s[4],u=a.shape[4];T(s.length===5,()=>`Error in conv3dDerInput: inShape must be length 5, but got length ${s.length}.`),T(a.rank===5,()=>`Error in conv3dDerInput: dy must be rank 5, but got rank ${a.rank}`),T(t.rank===5,()=>`Error in conv3dDerInput: filter must be rank 5, but got rank ${t.rank}`),T(l===t.shape[3],()=>`Error in conv3dDerInput: depth of input (${l}) must match input depth for filter ${t.shape[3]}.`),T(u===t.shape[4],()=>`Error in conv3dDerInput: depth of output (${u}) must match output depth for filter ${t.shape[4]}.`);let c={dy:a,filter:t},p={pad:n,strides:o,inputShape:s},m=E.runKernel(Ul,c,p);return i?M(m,[m.shape[1],m.shape[2],m.shape[3],m.shape[4]]):m}var og=S({conv3DBackpropInput_:EG});function DG(r,e,t,o,n){let s=_(r,"x","conv3dTranspose"),a=_(e,"filter","conv3dTranspose");return og(t,s,a,o,n)}var $G=S({conv3dTranspose_:DG});function RG(r){let t={x:_(r,"x","cos")};return E.runKernel(Qo,t)}var _a=S({cos_:RG});function FG(r){let t={x:_(r,"x","cosh")};return E.runKernel(ei,t)}var Cu=S({cosh_:FG});function OG(r,e=0,t=!1,o=!1){let s={x:_(r,"x","cumsum")},a={axis:e,exclusive:t,reverse:o};return E.runKernel(en,s,a)}var Iu=S({cumsum_:OG});function PG(r,e,t,o=!1){let n=_(r,"x","denseBincount"),s=_(e,"weights","denseBincount");T(n.dtype==="int32",()=>`Error in denseBincount: input dtype must be int32, but got ${n.dtype}`),T(n.rank<=2,()=>`Error in denseBincount: input must be at most rank 2, but got rank ${n.rank}.`),T(t>=0,()=>`size must be non-negative, but got ${t}.`),T(s.size===n.size||s.size===0,()=>`Error in denseBincount: weights must have the same shape as x or 0-length, but got x shape: ${n.shape}, weights shape: ${s.shape}.`);let a={x:n,weights:s},i={size:t,binaryOutput:o};return E.runKernel(Hl,a,i)}var Cw=S({denseBincount_:PG});function MG(r,e,t="NHWC"){let o=_(r,"x","depthToSpace"),n=t==="NHWC"?o.shape[1]:o.shape[2],s=t==="NHWC"?o.shape[2]:o.shape[3],a=t==="NHWC"?o.shape[3]:o.shape[1];T(n*e>=0,()=>`Negative dimension size caused by overflow when multiplying
|
|
${n} and ${e} for depthToSpace with input shape
|
|
${o.shape}`),T(s*e>=0,()=>`Negative dimension size caused by overflow when multiplying
|
|
${s} and ${e} for depthToSpace with input shape
|
|
${o.shape}`),T(a%(e*e)==0,()=>`Dimension size must be evenly divisible by ${e*e} but is ${a} for depthToSpace with input shape ${o.shape}`);let i={x:o},l={blockSize:e,dataFormat:t};return E.runKernel(ri,i,l)}var Dm=S({depthToSpace_:MG});function LG(r,e,t,o,n="NHWC",s=[1,1],a){let i=_(r,"x","depthwiseConv2d"),l=_(e,"filter","depthwiseConv2d"),u=i,c=!1;i.rank===3&&(c=!0,u=M(i,[1,i.shape[0],i.shape[1],i.shape[2]])),T(u.rank===4,()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${u.rank}.`),T(l.rank===4,()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${l.rank}.`),T(u.shape[3]===l.shape[2],()=>`Error in depthwiseConv2d: number of input channels (${u.shape[3]}) must match the inChannels dimension in filter ${l.shape[2]}.`),a!=null&&T(ot(o),()=>`Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode ${a} but got pad ${o}.`);let p={x:u,filter:l},m={strides:t,pad:o,dataFormat:n,dilations:s,dimRoundingMode:a},f=E.runKernel(tn,p,m);return c?M(f,[f.shape[1],f.shape[2],f.shape[3]]):f}var Is=S({depthwiseConv2d_:LG});function zG(r){let t={x:_(r,"x","diag")};return E.runKernel(Xl,t)}var BG=S({diag_:zG});function VG(r,e,t,o,n=[1,1],s="NHWC"){let a=_(r,"x","dilation2d"),i=_(e,"filter","dilation2d");T(a.rank===3||a.rank===4,()=>`Error in dilation2d: input must be rank 3 or 4, but got rank ${a.rank}.`),T(i.rank===3,()=>`Error in dilation2d: filter must be rank 3, but got rank ${i.rank}.`),T(s==="NHWC",()=>`Error in dilation2d: Only NHWC is currently supported, but got dataFormat of ${s}`);let l=a,u=!1;a.rank===3&&(l=M(a,[1,a.shape[0],a.shape[1],a.shape[2]]),u=!0);let c={x:l,filter:i},p={strides:t,pad:o,dilations:n},m=E.runKernel(sa,c,p);return u?M(m,[m.shape[1],m.shape[2],m.shape[3]]):m}var $m=S({dilation2d_:VG});function GG(r,e){let t=r.length,o=[];for(let n=0;n<t;n++){let s=t-1-n,a=r[s]||1;(e[e.length-1-n]||1)>1&&a===1&&o.unshift(s)}return o}function kt(r,e){let t=[];for(let o=0;o<e.length;o++){let n=r[r.length-o-1],s=e.length-o-1,a=e[s];(n==null||n===1&&a>1)&&t.unshift(s)}return t}function Be(r,e){let t=[],o=Math.max(r.length,e.length);for(let n=0;n<o;n++){let s=r[r.length-n-1];s==null&&(s=1);let a=e[e.length-n-1];if(a==null&&(a=1),s===1)t.unshift(a);else if(a===1)t.unshift(s);else if(s!==a){let i=`Operands could not be broadcast together with shapes ${r} and ${e}.`;throw Error(i)}else t.unshift(s)}return t}function WG(r,e){let t=_(r,"a","equal"),o=_(e,"b","equal");[t,o]=Ge(t,o),Be(t.shape,o.shape);let n={a:t,b:o};return E.runKernel(si,n)}var vo=S({equal_:WG});function jG(r,e,t){let o=_(e,"a","where"),n=_(t,"b","where"),s=_(r,"condition","where","bool"),a=Be(o.shape,n.shape),i=al(o,a),l=al(n,a);s.rank===1&&T(s.shape[0]===o.shape[0],()=>"The first dimension of `a` must match the size of `condition`."),s.rank!==1&&vt(s.shape,l.shape,"Error in where: ");let u={condition:s,t:i,e:l};return E.runKernel(hs,u)}var Dt=S({where_:jG});function UG(r){let t={x:_(r,"x","zerosLike")};return E.runKernel(bs,t)}var Ce=S({zerosLike_:UG});function HG(r,e){let t=_(r,"a","div"),o=_(e,"b","div");[t,o]=Ge(t,o);let n=me(t,o),s=Ce(n),a=vo(o,s);return Dt(a,s,n)}var Rm=S({divNoNan_:HG});function qG(r,e){let t=_(r,"t1","dot"),o=_(e,"t2","dot");T((t.rank===1||t.rank===2)&&(o.rank===1||o.rank===2),()=>`Error in dot: inputs must all be rank 1 or 2, but got ranks ${t.rank} and ${o.rank}.`);let n=t.rank===1?t.size:t.shape[1],s=o.rank===1?o.size:o.shape[0];if(T(n===s,()=>`Error in dot: inner dimensions of inputs must match, but got ${n} and ${s}.`),t.rank===1&&o.rank===1){let a=M(t,[1,-1]),i=M(o,[-1,1]),l=We(a,i);return M(l,[])}else if(t.rank===1&&o.rank===2){let a=M(t,[1,-1]),i=M(o,[o.shape[0],o.shape[1]]),l=We(a,i);return M(l,[l.size])}else if(t.rank===2&&o.rank===1){let a=M(o,[-1,1]),i=We(t,a);return M(i,[i.size])}else{let a=M(o,[o.shape[0],o.shape[1]]);return We(t,a)}}var Iw=S({dot_:qG});function KG(r){let t={x:_(r,"x","elu")};return E.runKernel(oi,t)}var Ns=S({elu_:KG});function XG(r){let e=_(r,"x","erf");T(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 E.runKernel(ni,t)}var Fm=S({erf_:XG});function YG(r){let t={x:_(r,"x","exp")};return E.runKernel(on,t)}var Yt=S({exp_:YG});function ZG(r,e=0){let t=_(r,"x","expandDims","string_or_numeric");T(e<=t.rank,()=>"Axis must be <= rank of the tensor");let o={input:t},n={dim:e};return E.runKernel(us,o,n)}var ir=S({expandDims_:ZG});function JG(r){let t={x:_(r,"x","expm1")};return E.runKernel(ii,t)}var Om=S({expm1_:JG});function QG(r,e){let t=_(r,"x","tile","string_or_numeric");T(t.rank===e.length,()=>`Error in transpose: rank of input ${t.rank} must match length of reps ${e}.`);let o={x:t},n={reps:e};return E.runKernel(ko,o,n)}var zo=S({tile_:QG});function eW(r,e,t,o="float32"){e==null&&(e=r);let n=ve([r,e],o),s=r<=e?r:e;for(let i=0;i<s;++i)n.set(1,i,i);let a=M(n.toTensor(),[r,e]);if(t==null)return a;if(t.length===1)return zo(ir(a,0),[t[0],1,1]);if(t.length===2)return zo(ir(ir(a,0),0),[t[0],t[1],1,1]);if(t.length===3)return zo(ir(ir(ir(a,0),0),0),[t[0],t[1],t[2],1,1]);throw new Error(`eye() currently supports only 1D and 2D batchShapes, but received ${t.length}D.`)}var Kc=S({eye_:eW});function va(r,e,t){let o={shape:r,value:e,dtype:t};return E.runKernel(ia,{},o)}function tW(r){let t={x:_(r,"x","floor")};return E.runKernel(nn,t)}var Ss=S({floor_:tW});function rW(r,e,t=0,o=0){let n=_(r,"x","gather"),s=_(e,"indices","gather","int32"),a={x:n,indices:s},i={axis:t,batchDims:o};return E.runKernel(cs,a,i)}var zn=S({gather_:rW});function oW(r,e){let t=_(r,"a","greater"),o=_(e,"b","greater");[t,o]=Ge(t,o),Be(t.shape,o.shape);let n={a:t,b:o};return E.runKernel(ui,n)}var Qt=S({greater_:oW});function nW(r,e){let t=_(r,"a","greaterEqual"),o=_(e,"b","greaterEqual");[t,o]=Ge(t,o),Be(t.shape,o.shape);let n={a:t,b:o};return E.runKernel(ln,n)}var io=S({greaterEqual_:nW});function sW(r){let t={input:_(r,"input","imag")};return E.runKernel(Ql,t)}var Nu=S({imag_:sW});function iW(r){let t={x:_(r,"x","isFinite")};return E.runKernel(ci,t)}var Nw=S({isFinite_:iW});function aW(r){let t={x:_(r,"x","isInf")};return E.runKernel(pi,t)}var Sw=S({isInf_:aW});function lW(r){let t={x:_(r,"x","isNaN")};return E.runKernel(mi,t)}var Tw=S({isNaN_:lW});function uW(r,e=.2){let o={x:_(r,"x","leakyRelu")},n={alpha:e};return E.runKernel(un,o,n)}var Ca=S({leakyRelu_:uW});function cW(r,e){let t=_(r,"a","less"),o=_(e,"b","less");[t,o]=Ge(t,o),Be(t.shape,o.shape);let n={a:t,b:o};return E.runKernel(fi,n)}var Su=S({less_:cW});function pW(r,e){let t=_(r,"a","lessEqual"),o=_(e,"b","lessEqual");[t,o]=Ge(t,o),Be(t.shape,o.shape);let n={a:t,b:o};return E.runKernel(di,n)}var Bo=S({lessEqual_:pW});function Aw(r,e,t){if(t<=0)throw new Error("The number of values should be positive.");let o={start:r,stop:e,num:t};return E.runKernel(eu,{},o)}function mW(r,e=5,t=1,o=1,n=.5){let s=_(r,"x","localResponseNormalization");T(s.rank===4||s.rank===3,()=>`Error in localResponseNormalization: x must be rank 3 or 4 but got
|
|
rank ${s.rank}.`),T(ot(e),()=>`Error in localResponseNormalization: depthRadius must be an integer but got depthRadius ${e}.`);let a=s,i=!1;s.rank===3&&(i=!0,a=M(s,[1,s.shape[0],s.shape[1],s.shape[2]]));let l={x:a},u={depthRadius:e,bias:t,alpha:o,beta:n},c=E.runKernel(aa,l,u);return i?M(c,[c.shape[1],c.shape[2],c.shape[3]]):c}var Pm=S({localResponseNormalization_:mW});function fW(r){let t={x:_(r,"x","log")};return E.runKernel(cn,t)}var ar=S({log_:fW});function dW(r){let t={x:_(r,"x","log1p")};return E.runKernel(hi,t)}var Tu=S({log1p_:dW});function hW(r){return T(Us(r),()=>"The f passed in grad(f) must be a function"),(e,t)=>{let o=_(e,"x","tf.grad","string_or_numeric"),n=t!=null?_(t,"dy","tf.grad"):null;return E.tidy(()=>{let{value:s,grads:a}=E.gradients(()=>r(o),[o],n);return n!=null&&vt(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 gW(r){return T(Us(r),()=>"The f passed in grads(f) must be a function"),(e,t)=>{T(Array.isArray(e),()=>"The args passed in grads(f)(args) must be an array of `Tensor`s or `TensorLike`s");let o=ha(e,"args","tf.grads","string_or_numeric"),n=t!=null?_(t,"dy","tf.grads"):null;return E.tidy(()=>{let{value:s,grads:a}=E.gradients(()=>r(...o),o,n);return n!=null&&vt(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 xW(r){return T(Us(r),()=>"The f passed in valueAndGrad(f) must be a function"),(e,t)=>{T(e instanceof Ve,()=>"The x passed in valueAndGrad(f)(x) must be a tensor"),T(t==null||t instanceof Ve,()=>"The dy passed in valueAndGrad(f)(x, dy) must be a tensor");let{grads:o,value:n}=E.gradients(()=>r(e),[e],t);return ng(o),{grad:o[0],value:n}}}function yW(r){return T(Us(r),()=>"The f passed in valueAndGrads(f) must be a function"),(e,t)=>{T(Array.isArray(e)&&e.every(n=>n instanceof Ve),()=>"The args passed in valueAndGrads(f)(args) must be array of tensors"),T(t==null||t instanceof Ve,()=>"The dy passed in valueAndGrads(f)(args, dy) must be a tensor");let o=E.gradients(()=>r(...e),e,t);return t!=null&&vt(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){T(Us(r),()=>"The f passed in variableGrads(f) must be a function"),T(e==null||Array.isArray(e)&&e.every(u=>u instanceof rl),()=>"The varList passed in variableGrads(f, varList) must be an array of variables");let t=e!=null;if(!t){e=[];for(let u in E.registeredVariables)e.push(E.registeredVariables[u])}let o=t?e.filter(u=>!u.trainable):null,n=e.length;e=e.filter(u=>u.trainable),T(e.length>0,()=>`variableGrads() expects at least one of the input variables to be trainable, but none of the ${n} variables is trainable.`);let s=!0,{value:a,grads:i}=E.gradients(r,e,null,s);T(i.some(u=>u!=null),()=>"Cannot find a connection between any variable and the result of the loss function y=f(x). Please make sure the operations that use variables are inside the function f passed to minimize()."),T(a.rank===0,()=>`The f passed in variableGrads(f) must return a scalar, but it returned a rank-${a.rank} tensor`);let l={};return e.forEach((u,c)=>{i[c]!=null&&(l[u.name]=i[c])}),o!=null&&o.forEach(u=>l[u.name]=null),{value:a,grads:l}}function Xr(r){return E.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 bW(r){let t={x:_(r,"x","neg")};return E.runKernel(ps,t)}var He=S({neg_:bW});function wW(r){let t={x:_(r,"x","softplus")};return E.runKernel(Ti,t)}var Ts=S({softplus_:wW});function kW(r){let e=_(r,"x","logSigmoid");return Xr(o=>({value:He(Ts(He(o))),gradFunc:a=>O(a,qr(He(o)))}))(e)}var Ew=S({logSigmoid_:kW});function _W(r,e=null,t=!1){let n={x:_(r,"x","max")},s={reductionIndices:e,keepDims:t};return E.runKernel(pn,n,s)}var lr=S({max_:_W});function vW(r,e){let t=_(r,"a","sub"),o=_(e,"b","sub");[t,o]=Ge(t,o);let n={a:t,b:o};return E.runKernel(Fn,n)}var ce=S({sub_:vW});function CW(r,e=null,t=!1){let o=_(r,"x","sum");o.dtype==="bool"&&(o=ne(o,"int32"));let n={x:o},s={axis:e,keepDims:t};return E.runKernel(Dn,n,s)}var ge=S({sum_:CW});function IW(r,e=-1){let t=_(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 Xr((n,s)=>{let a=!0,i=lr(n,e,!0),l=ce(n,i),u=ce(ne(l,"float32"),ar(ge(Yt(l),e,a)));return s([u]),{value:u,gradFunc:(p,m)=>{let[f]=m,d=!0,h=Yt(f);return ce(p,O(ge(p,e,d),h))}}})(t)}var Au=S({logSoftmax_:IW});function Dw(r,e){for(let t=0;t<r.length;++t)if(r[r.length-t-1]!==e-1-t)return!1;return!0}function vN(r,e,t){let o=r.length+e.length,n=[],s=0,a=0;for(let i=0;i<o;i++)t.indexOf(i)===-1?n.push(r[s++]):n.push(e[a++]);return n}function $w(r,e){let t=[],o=r.length;for(let s=0;s<o;s++)e.indexOf(s)===-1&&t.push(r[s]);let n=e.map(s=>r[s]);return[t,n]}function Bn(r,e){let t=e.map(o=>1);return vN(r,t,e)}function NW(r,e,t){T(Dw(e,t),()=>`${r} supports only inner-most axes for now. Got axes ${e} and rank-${t} input.`)}function Rw(r,e){if(Dw(r,e))return null;let t=[];for(let o=0;o<e;++o)r.indexOf(o)===-1&&t.push(o);return r.forEach(o=>t.push(o)),t}function Mm(r){return r.map((e,t)=>[t,e]).sort((e,t)=>e[1]-t[1]).map(e=>e[0])}function SW(r,e){let t=[];for(let o=e-r;o<e;++o)t.push(o);return t}function TW(r,e=null,t=!1){let o=_(r,"x","logSumExp"),n=Jt(e,o.shape),s=lr(o,n,!0),a=ce(o,s),i=Yt(a),l=ge(i,n),u=ar(l),c=ee(M(s,u.shape),u);if(t){let p=Bn(c.shape,n);return M(c,p)}return c}var Lm=S({logSumExp_:TW});function AW(r,e){let t=_(r,"a","logicalAnd","bool"),o=_(e,"b","logicalAnd","bool");Be(t.shape,o.shape);let n={a:t,b:o};return E.runKernel(gi,n)}var dr=S({logicalAnd_:AW});function EW(r){let t={x:_(r,"x","logicalNot","bool")};return E.runKernel(Ja,t)}var Ia=S({logicalNot_:EW});function DW(r,e){let t=_(r,"a","logicalOr","bool"),o=_(e,"b","logicalOr","bool");Be(t.shape,o.shape);let n={a:t,b:o};return E.runKernel(Qa,n)}var Eu=S({logicalOr_:DW});function $W(r,e){let t=_(r,"a","logicalXor","bool"),o=_(e,"b","logicalXor","bool");return Be(t.shape,o.shape),dr(Eu(r,e),Ia(dr(r,e)))}var Fw=S({logicalXor_:$W});function RW(r,e,t,o,n){let s=_(r,"x","maxPool"),a=1,i=s,l=!1;s.rank===3&&(l=!0,i=M(s,[1,s.shape[0],s.shape[1],s.shape[2]])),T(i.rank===4,()=>`Error in maxPool: input must be rank 4 but got rank ${i.rank}.`),T(wr(t,a),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${t} and dilations '${a}'`),n!=null&&T(ot(o),()=>`Error in maxPool: pad must be an integer when using, dimRoundingMode ${n} but got pad ${o}.`);let u={x:i},c={filterSize:e,strides:t,pad:o,dimRoundingMode:n},p=E.runKernel(fn,u,c);return l?M(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var Na=S({maxPool_:RW});function FW(r,e=[1,1,1],t,o,n,s="NDHWC"){let a=_(r,"x","maxPool3d"),i=a,l=!1;a.rank===4&&(l=!0,i=M(a,[1,a.shape[0],a.shape[1],a.shape[2],a.shape[3]])),T(i.rank===5,()=>`Error in maxPool3d: x must be rank 5 but got rank ${i.rank}.`),T(s==="NDHWC",()=>`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${s}`),n!=null&&T(ot(o),()=>`Error in maxPool3d: pad must be an integer when using, dimRoundingMode ${n} but got pad ${o}.`);let u={x:i},c={filterSize:e,strides:t,pad:o,dimRoundingMode:n,dataFormat:s},p=E.runKernel(la,u,c);return l?M(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}var zm=S({maxPool3d_:FW});function OW(r,e,t,o,n=!1){let a={x:_(r,"x","maxPoolWithArgmax")},i={filterSize:e,strides:t,pad:o,includeBatchInIndex:n},l=E.runKernel(nu,a,i);return{result:l[0],indexes:l[1]}}var Ow=S({maxPoolWithArgmax_:OW});function PW(r,e){let t=_(r,"a","maximum"),o=_(e,"b","maximum");[t,o]=Ge(t,o),t.dtype==="bool"&&(t=ne(t,"int32"),o=ne(o,"int32")),Be(t.shape,o.shape);let n={a:t,b:o};return E.runKernel(mn,n)}var Yr=S({maximum_:PW});function MW(r,e=null,t=!1){let n={x:_(r,"x","mean")},s={axis:e,keepDims:t};return E.runKernel(dn,n,s)}var dt=S({mean_:MW});function LW(r,e=null,t=!1){let n={x:_(r,"x","min")},s={axis:e,keepDims:t};return E.runKernel(hn,n,s)}var Pi=S({min_:LW});function zW(r,e){let t=_(r,"a","minimum"),o=_(e,"b","minimum");[t,o]=Ge(t,o),t.dtype==="bool"&&(t=ne(t,"int32"),o=ne(o,"int32")),Be(t.shape,o.shape);let n={a:t,b:o};return E.runKernel(gn,n)}var As=S({minimum_:zW});function BW(r,e,t){T(t==="reflect"||t==="symmetric",()=>`Invalid mode. Mode must be either reflect or symmetric. Got ${t}.`);let o=_(r,"x","mirrorPad");if(o.rank===0)throw new Error("mirrorPad(scalar) is not defined. Pass non-scalar to mirrorPad");T(e.length===o.rank,()=>`Padding doesn't match input. Must be ${o.rank}. Got ${e.length}.`);let n=t==="reflect"?1:0;for(let i=0;i<o.rank;i++)T(e[i].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),T(e[i][0]>=0&&e[i][0]<=o.shape[i]-n&&e[i][1]>=0&&e[i][1]<=o.shape[i]-n,()=>`Padding in dimension ${i} cannot be greater than or equal to ${o.shape[i]-n} or less than 0 for input of shape ${o.shape}`);let s={paddings:e,mode:t},a={x:o};return E.runKernel(ua,a,s)}var Bm=S({mirrorPad_:BW});function VW(r,e){let t=_(r,"a","mod"),o=_(e,"b","mod");[t,o]=Ge(t,o);let n={a:t,b:o};return E.runKernel(xi,n)}var Vm=S({mod_:VW});function GW(r){let e=_(r,"x","square"),t={};return E.runKernel("Square",{x:e},t)}var Oe=S({square_:GW});function WW(r,e=null,t=!1){r=_(r,"x","moments");let o=Jt(e,r.shape),n=dt(r,o,t),s=n.shape;t||(s=Bn(n.shape,o));let a=Oe(ce(ne(r,"float32"),M(n,s))),i=dt(a,o,t);return{mean:n,variance:i}}var Xc=S({moments_:WW});function jW(r,e,t,o){let n=_(e,"data","multiRNNCell"),s=ha(t,"c","multiRNNCell"),a=ha(o,"h","multiRNNCell"),i=n,l=[];for(let p=0;p<r.length;p++){let m=r[p](i,s[p],a[p]);l.push(m[0]),l.push(m[1]),i=m[1]}let u=[],c=[];for(let p=0;p<l.length;p+=2)u.push(l[p]),c.push(l[p+1]);return[u,c]}var UW=S({multiRNNCell_:jW});function HW(r,e,t,o=!1){let n=_(r,"logits","multinomial"),s=n.size,a=n.rank;if(s<2)throw new Error(`Error in multinomial: you need at least 2 outcomes, but got ${s}.`);if(a>2)throw new Error(`Rank of probabilities must be 1 or 2, but is ${a}`);t=t||Math.random();let l={logits:a===1?M(n,[1,-1]):n},u={numSamples:e,seed:t,normalized:o},c=E.runKernel(su,l,u);return a===1?M(c,[c.size]):c}var Pw=S({multinomial_:HW});function qW(r,e){let t=_(r,"a","notEqual"),o=_(e,"b","notEqual");[t,o]=Ge(t,o),Be(t.shape,o.shape);let n={a:t,b:o};return E.runKernel(yi,n)}var Vn=S({notEqual_:qW});function ht(r,e="float32"){if(e==="complex64"){let o=ht(r,"float32"),n=ht(r,"float32");return _o(o,n)}let t=$c(ct(r),e);return E.makeTensor(t,r,e)}function Ir(r,e="float32"){if(e==="complex64"){let o=Ir(r,"float32"),n=ht(r,"float32");return _o(o,n)}let t=um(ct(r),e);return E.makeTensor(t,r,e)}function KW(r){let t={x:_(r,"x","onesLike")};return E.runKernel(ms,t)}var er=S({onesLike_:KW});function XW(r,e){let t=_(r,"v1","outerProduct"),o=_(e,"v2","outerProduct");T(t.rank===1&&o.rank===1,()=>`Error in outerProduct: inputs must be rank 1, but got ranks ${t.rank} and ${o.rank}.`);let n=M(t,[-1,1]),s=M(o,[1,-1]);return We(n,s)}var YW=S({outerProduct_:XW});function ZW(r,e,t=0){let o=_(r,"x","pad");if(o.rank===0)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");let n={paddings:e,constantValue:t},s={x:o};return E.runKernel(bn,s,n)}var Rr=S({pad_:ZW});function JW(r,e,t=0){return T(e.length===2,()=>"Invalid number of paddings. Must be length of 2."),Rr(r,[e],t)}var QW=S({pad1d_:JW});function ej(r,e,t=0){return T(e.length===2&&e[0].length===2&&e[1].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),Rr(r,e,t)}var tj=S({pad2d_:ej});function rj(r,e,t=0){return T(e.length===3&&e[0].length===2&&e[1].length===2&&e[2].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),Rr(r,e,t)}var oj=S({pad3d_:rj});function nj(r,e,t=0){return T(e.length===4&&e[0].length===2&&e[1].length===2&&e[2].length===2&&e[3].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),Rr(r,e,t)}var sj=S({pad4d_:nj});function ij(r,e,t){let o=_(r,"x","spaceToBatchND");T(o.rank>=1+e.length,()=>`input rank ${o.rank} should be > than [blockShape] ${e.length}`),T(t.length===e.length,()=>`paddings.shape[0] ${t.length} must be equal to [blockShape] ${e.length}`),T(o.shape.reduce((a,i,l)=>l>0&&l<=e.length?a&&(i+t[l-1][0]+t[l-1][1])%e[l-1]==0:a,!0),()=>`input spatial dimensions ${o.shape.slice(1)} with paddings ${t.toString()} must be divisible by blockShapes ${e.toString()}`);let n={x:o},s={blockShape:e,paddings:t};return E.runKernel(ma,n,s)}var Sa=S({spaceToBatchND_:ij});function uj(r,e,t,o,n,s){n==null&&(n=[1,1]),s==null&&(s=1),o===0&&(o="valid");let a=_(r,"x","maxPool"),i=a,l=!1;a.rank===3&&(l=!0,i=M(a,[1,a.shape[0],a.shape[1],a.shape[2]])),T(wr(s,n),()=>`Error in pool: Either strides or dilations must be 1. Got strides ${s} and dilations '${n}'`);let u=fw(i.shape,e,s,n,o),c=[u.dilationHeight,u.dilationWidth],p;o==="same"?p=lj([u.filterHeight,u.filterWidth],c):p=[[0,0],[0,0]];let m=c[0]===1&&c[1]===1,[f,d]=aj([u.inHeight,u.inWidth],c,p),h=m?o:"valid",g=m?i:Sa(i,c,f),b=(t==="avg"?()=>wa(g,e,s,h):()=>Na(g,e,s,h))(),w=m?b:ka(b,c,d);return l?M(w,[w.shape[1],w.shape[2],w.shape[3]]):w}function aj(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 lj(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 Mw=S({pool_:uj});function cj(r,e){let t=_(r,"base","pow"),o=_(e,"exp","pow");[t,o]=Ge(t,o);let n={a:t,b:o};return E.runKernel(wn,n)}var Fr=S({pow_:cj});function pj(r,e){let t=_(r,"x","prelu"),o=_(e,"alpha","prelu"),n={x:t,alpha:o};return E.runKernel(kn,n)}var Ta=S({prelu_:pj});function mj(r,e=null,t=!1){let o=_(r,"x","prod");o.dtype==="bool"&&(o=ne(o,"int32"));let n={x:o},s={axis:e,keepDims:t};return E.runKernel(_i,n,s)}var Du=S({prod_:mj});function fj(r,e,t){let o=ct(r),n=null;if(t==null||t==="float32")n=new Float32Array(o);else if(t==="int32")n=new Int32Array(o);else if(t==="bool")n=new Uint8Array(o);else throw new Error(`Unknown data type ${t}`);for(let s=0;s<o;s++)n[s]=e();return E.makeTensor(n,r,t)}var dj=S({rand_:fj});var ag=Tc(Gm());var Yc=class{constructor(e,t,o,n,s){this.mean=e,this.stdDev=t,this.dtype=o,this.nextVal=NaN,this.truncated=n,this.truncated&&(this.upper=this.mean+this.stdDev*2,this.lower=this.mean-this.stdDev*2);let a=s||Math.random();this.random=ag.alea(a.toString())}nextValue(){if(!isNaN(this.nextVal)){let n=this.nextVal;return this.nextVal=NaN,n}let e,t,o=!1;for(;!o;){let n,s,a;do n=2*this.random()-1,s=2*this.random()-1,a=n*n+s*s;while(a>=1||a===0);let i=Math.sqrt(-2*Math.log(a)/a);e=this.mean+this.stdDev*n*i,t=this.mean+this.stdDev*s*i,(!this.truncated||this.isValidTruncated(e))&&(o=!0)}return(!this.truncated||this.isValidTruncated(t))&&(this.nextVal=this.convertValue(t)),this.convertValue(e)}convertValue(e){return this.dtype==null||this.dtype==="float32"?e:Math.round(e)}isValidTruncated(e){return e<=this.upper&&e>=this.lower}},jw=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 Yc(0,1,o,!1,this.randu()),e<1?this.d=e+2/3:this.d=e-1/3,this.c=1/Math.sqrt(9*this.d)}nextValue(){let e,t,o,n,s,a;for(;;){do n=this.randn.nextValue(),a=1+this.c*n;while(a<=0);if(a*=a*a,e=n*n,t=1-.331*e*e,o=.5*e+this.d*(1-a+Math.log(a)),s=this.randu(),s<t||Math.log(s)<o)break}return a=1/this.beta*this.d*a,this.alpha<1&&(a*=Math.pow(this.randu(),1/this.alpha)),this.convertValue(a)}convertValue(e){return this.dtype==="float32"?e:Math.round(e)}},Uw=class{constructor(e=0,t=1,o,n){if(this.canReturnFloat=()=>this.dtype==null||this.dtype==="float32",this.min=e,this.range=t-e,this.dtype=o,n==null&&(n=Math.random()),typeof n=="number"&&(n=n.toString()),!this.canReturnFloat()&&this.range<=1)throw new Error(`The difference between ${e} - ${t} <= 1 and dtype is not float`);this.random=ag.alea(n)}convertValue(e){return this.canReturnFloat()?e:Math.round(e)}nextValue(){return this.convertValue(this.min+this.range*this.random())}};function kj(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 jw(e,t,o,n),a=ve(r,o);for(let i=0;i<a.values.length;i++)a.values[i]=s.nextValue();return a.toTensor()}var _j=S({randomGamma_:kj});function vj(r,e=0,t=1,o,n){if(o!=null&&o==="bool")throw new Error(`Unsupported data type ${o}`);let s=new Yc(e,t,o,!1,n),a=ve(r,o);for(let i=0;i<a.values.length;i++)a.values[i]=s.nextValue();return a.toTensor()}var lg=S({randomNormal_:vj});function Cj(r,e=0,t=1,o="float32",n){let s=ve(r,o),a=new Uw(e,t,null,n);for(let i=0;i<s.values.length;i++)s.values[i]=a.nextValue();return s.toTensor()}var Es=S({randomUniform_:Cj});function Zc(r,e,t=1,o="float32"){if(t===0)throw new Error("Cannot have a step of zero");let n={start:r,stop:e,step:t,dtype:o};return E.runKernel(ca,{},n)}function Ij(r){let t={input:_(r,"input","real")};return E.runKernel(iu,t)}var ll=S({real_:Ij});function Nj(r){let t={x:_(r,"x","reciprocal")};return E.runKernel(vi,t)}var Wm=S({reciprocal_:Nj});function Sj(r){let t={x:_(r,"x","relu")};return E.runKernel(_n,t)}var Nr=S({relu_:Sj});function Tj(r){let t={x:_(r,"x","relu6")};return E.runKernel(Cn,t)}var Ru=S({relu6_:Tj});function Aj(r,e){let o={x:_(r,"x","reverse")},n={dims:e};return E.runKernel(In,o,n)}var Ht=S({reverse_:Aj});function Ej(r){let e=_(r,"x","reverse");return T(e.rank===1,()=>`Error in reverse1D: x must be rank 1 but got rank ${e.rank}.`),Ht(e,0)}var Dj=S({reverse1d_:Ej});function $j(r,e){let t=_(r,"x","reverse");return T(t.rank===2,()=>`Error in reverse2D: x must be rank 2 but got rank ${t.rank}.`),Ht(t,e)}var Rj=S({reverse2d_:$j});function Fj(r,e){let t=_(r,"x","reverse");return T(t.rank===3,()=>`Error in reverse3D: x must be rank 3 but got rank ${t.rank}.`),Ht(t,e)}var Oj=S({reverse3d_:Fj});function Pj(r,e){let t=_(r,"x","reverse");return T(t.rank===4,()=>`Error in reverse4D: x must be rank 4 but got rank ${t.rank}.`),Ht(t,e)}var Mj=S({reverse4d_:Pj});function Lj(r){let t={x:_(r,"x","round")};return E.runKernel(Nn,t)}var jm=S({round_:Lj});function zj(r){let t={x:_(r,"x","rsqrt")};return E.runKernel(Sn,t)}var Fu=S({rsqrt_:zj});function le(r,e){if((or(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"&&or(r)&&!(r instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");return Ur(r,[],[],e)}function Bj(r){let t={x:_(r,"x","selu")};return E.runKernel(Ii,t)}var Ou=S({selu_:Bj});function Vj(r,e,t,o,n,s=[1,1],a="NHWC"){let i=_(r,"x","separableConv2d"),l=_(e,"depthwiseFilter","separableConv2d"),u=_(t,"pointwiseFilter","separableConv2d"),c=i,p=!1;if(i.rank===3&&(p=!0,c=M(i,[1,i.shape[0],i.shape[1],i.shape[2]])),a==="NCHW")throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");T(c.rank===4,()=>`Error in separableConv2d: input must be rank 4, but got rank ${c.rank}.`),T(l.rank===4,()=>`Error in separableConv2d: depthwise filter must be rank 4, but got rank ${l.rank}.`),T(u.rank===4,()=>`Error in separableConv2d: pointwise filter must be rank 4, but got rank ${l.rank}.`),T(u.shape[0]===1,()=>`Error in separableConv2d: the first dimension of pointwise filter must be 1, but got ${u.shape[0]}.`),T(u.shape[1]===1,()=>`Error in separableConv2d: the second dimension of pointwise filter must be 1, but got ${u.shape[1]}.`);let m=l.shape[2],f=l.shape[3];T(u.shape[2]===m*f,()=>`Error in separableConv2d: the third dimension of pointwise filter must be ${m*f}, but got ${u.shape[2]}.`);let d=Is(c,l,o,n,a,s),g=Kr(d,u,1,"valid",a);return p?M(g,[g.shape[1],g.shape[2],g.shape[3]]):g}var Um=S({separableConv2d_:Vj});async function Gj(r,e){let t=_(r,"x","setdiff1d"),o=_(e,"y","setdiff1d");T(t.dtype===o.dtype,()=>`x and y should have the same dtype, but got x (${t.dtype}) and y (${o.dtype}).`),T(t.rank===1,()=>`x should be 1D tensor, but got x (${t.shape}).`),T(o.rank===1,()=>`y should be 1D tensor, but got y (${o.shape}).`);let n=await t.data(),s=await o.data(),a=new Set(s),i=0;for(let c=0;c<n.length;c++)a.has(n[c])||i++;let l=new lt([i],t.dtype),u=new lt([i],"int32");for(let c=0,p=0;c<n.length;c++)a.has(n[c])||(l.values[p]=n[c],u.values[p]=c,p++);return[l.toTensor(),u.toTensor()]}var Hw=Gj;function Wj(r){let t={x:_(r,"x","sign")};return E.runKernel(Si,t)}var Hm=S({sign_:Wj});function jj(r){let t={x:_(r,"x","sin")};return E.runKernel(Tn,t)}var Pu=S({sin_:jj});function Uj(r){let t={x:_(r,"x","sinh")};return E.runKernel(Ni,t)}var Mu=S({sinh_:Uj});function Hj(r,e,t){let o=_(r,"x","slice1d");return T(o.rank===1,()=>`slice1d expects a rank-1 tensor, but got a rank-${o.rank} tensor`),Re(o,[e],[t])}var qm=S({slice1d_:Hj});function qj(r,e,t){let o=_(r,"x","slice2d");return T(o.rank===2,()=>`slice2d expects a rank-2 tensor, but got a rank-${o.rank} tensor`),Re(o,e,t)}var ug=S({slice2d_:qj});function Kj(r,e,t){let o=_(r,"x","slice3d");return T(o.rank===3,()=>`slice3d expects a rank-3 tensor, but got a rank-${o.rank} tensor`),Re(o,e,t)}var Km=S({slice3d_:Kj});function Xj(r,e,t){let o=_(r,"x","slice4d");return T(o.rank===4,()=>`slice4d expects a rank-4 tensor, but got a rank-${o.rank} tensor`),Re(o,e,t)}var Jc=S({slice4d_:Xj});function Yj(r,e=-1){let t=_(r,"logits","softmax","float32");if(e===-1&&(e=t.rank-1),e!==t.rank-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${t.rank} and dim was ${e}`);let o={logits:t},n={dim:e};return E.runKernel($n,o,n)}var Aa=S({softmax_:Yj});function Zj(r){T(r.dtype==="complex64",()=>`The dtype for tf.spectral.fft() must be complex64 but got ${r.dtype}.`);let e={input:r};return E.runKernel(Zl,e)}var Ea=S({fft_:Zj});function Jj(r){T(r.dtype==="complex64",()=>`The dtype for tf.spectral.ifft() must be complex64 but got ${r.dtype}.`);let e={input:r};return E.runKernel(Jl,e)}var Mi=S({ifft_:Jj});function Qj(r){let e=r.shape[r.shape.length-1],t=r.size/e,o;if(e<=2){let n=M(r,[t,e]);o=Mi(n)}else{let n=[t,2*(e-1)],s=M(ll(r),[t,e]),a=M(Nu(r),[t,e]),i=Ht(Re(s,[0,1],[t,e-2]),1),l=O(Ht(Re(a,[0,1],[t,e-2]),1),le(-1)),u=Ze([s,i],1),c=Ze([a,l],1),p=M(_o(u,c),[n[0],n[1]]);o=Mi(p)}if(o=ll(o),r.rank===3&&r.shape[0]!==0){let n=o,s=r.shape[0];o=M(o,[s,o.shape[0]/s,o.shape[1]]),n.dispose()}return o}var Lu=S({irfft_:Qj});function e4(r,e,t=0){let n={x:_(r,"x","split")},s={numOrSizeSplits:e,axis:t};return E.runKernel(xs,n,s)}var ur=S({split_:e4});function t4(r,e){T(r.dtype==="float32",()=>`The dtype for rfft() must be real value but got ${r.dtype}`);let t=r.shape[r.shape.length-1],o=r.size/t,n;if(e!=null&&e<t){let d=r.shape.map(g=>0),h=r.shape.map(g=>g);h[r.shape.length-1]=e,n=Re(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=Ze([r,ht(d)],r.shape.length-1),t=e}else n=r;let s=Ce(n),a=M(_o(n,s),[o,t]),i=Ea(a),l=Math.floor(t/2)+1,u=ll(i),c=Nu(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,M(_o(p[0],m[0]),f)}var Da=S({rfft_:t4});function r4(r){let t={x:_(r,"x","sqrt")};return E.runKernel(En,t)}var gt=S({sqrt_:r4});function o4(r,e){let t=_(r,"a","squaredDifference"),o=_(e,"b","squaredDifference");[t,o]=Ge(t,o),Be(t.shape,o.shape);let n={a:t,b:o},s={};return E.runKernel(Rn,n,s)}var zu=S({squaredDifference_:o4});function n4(r,e){let t=_(r,"x","squeeze");return M(t,_b(t.shape,e).newShape)}var Co=S({squeeze_:n4});function s4(r,e=0){let t=ha(r,"tensors","stack","string_or_numeric");T(t.length>=1,()=>"Pass at least one tensor to tf.stack"),t.length>0&&T(e<=t[0].rank,()=>"Axis must be <= rank of the tensor");let o=t,n={axis:e};return E.runKernel(fs,o,n)}var Bt=S({stack_:s4});function i4(r,e=0){let o={x:_(r,"x","step")},n={alpha:e};return E.runKernel(Oo,o,n)}var Ds=S({step_:i4});function a4(r,e,t,o,n=0,s=0,a=0,i=0,l=0){let c={x:_(r,"x","stridedSlice")},p={begin:e,end:t,strides:o,beginMask:n,endMask:s,ellipsisMask:a,newAxisMask:i,shrinkAxisMask:l};return E.runKernel(Ai,c,p)}var Xm=S({stridedSlice_:a4});function l4(r){let t={x:_(r,"x","tan")};return E.runKernel(Ei,t)}var Ym=S({tan_:l4});function Vt(r,e){Do(r);let t=vr(r,e);if(t.length!==1)throw new Error("tensor1d() requires values to be a flat/TypedArray");return Ur(r,null,t,e)}function Li(r,e,t){if(Do(r),e!=null&&e.length!==2)throw new Error("tensor2d() requires shape to have two numbers");let o=vr(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 Ur(r,e,o,t)}function u4(r,e,t){if(Do(r),e!=null&&e.length!==4)throw new Error("tensor4d() requires shape to have four numbers");let o=vr(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 Ur(r,e,o,t)}function c4(r,e,t){if(Do(r),e!=null&&e.length!==5)throw new Error("tensor5d() requires shape to have five numbers");let o=vr(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 Ur(r,e,o,t)}function p4(r,e,t){if(Do(r),e!=null&&e.length!==6)throw new Error("tensor6d() requires shape to have six numbers");let o=vr(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,Ur(r,e,o,t)}function m4(r,e=1,t=!0){let o=_(r,"x","topk");if(o.rank===0)throw new Error("topk() expects the input to be of rank 1 or higher");let n=o.shape[o.shape.length-1];if(e>n)throw new Error(`'k' passed to topk() must be <= the last dimension (${n}) but got ${e}`);let s={x:o},a={k:e,sorted:t},[i,l]=E.runKernel(Di,s,a);return{values:i,indices:l}}var Zm=S({topk_:m4});function f4(r,e=0,t=1,o,n){if(o!=null&&o==="bool")throw new Error("Unsupported data type $ { dtype }");let s=new Yc(e,t,o,!0,n),a=ve(r,o);for(let i=0;i<a.values.length;i++)a.values[i]=s.nextValue();return a.toTensor()}var Bu=S({truncatedNormal_:f4});function d4(r,e=0){let t=_(r,"x","unique","string_or_numeric");T(t.rank>0,()=>"The input tensor must be at least 1D");let o={x:t},n={axis:e},[s,a]=E.runKernel(pu,o,n);return{values:s,indices:a}}var Qc=S({unique_:d4});function h4(r,e,t){let o=_(r,"x","unsortedSegmentSum"),n=_(e,"segmentIds","unsortedSegmentSum","int32");T(ot(t),()=>"numSegments must be of dtype int");let s={x:o,segmentIds:n},a={numSegments:t};return E.runKernel(da,s,a)}var Jm=S({unsortedSegmentSum_:h4});function g4(r,e=0){let t=_(r,"x","unstack","string_or_numeric");T(e>=-t.shape.length&&e<t.shape.length,()=>`Axis = ${e} is not in [-${t.shape.length}, ${t.shape.length})`);let o={value:t},n={axis:e};return E.runKernel(ys,o,n)}var cr=S({unstack_:g4});function qw(r,e=!0,t,o){return E.makeVariable(r,e,t,o)}function Kw(r,e){let t=[];for(let s=0;s<e.length;s++)e[s]&&t.push(s);let o=ve(r,"int32"),n=ve([t.length,r.length],"int32");for(let s=0;s<t.length;s++){let a=o.indexToLoc(t[s]),i=s*r.length;n.values.set(a,i)}return n.toTensor()}async function x4(r){let e=_(r,"condition","whereAsync","bool"),t=await e.data(),o=Kw(e.shape,t);return r!==e&&e.dispose(),o}var Qm=x4;async function y4(r,e,t){let o=_(r,"tensor","boolMask"),n=_(e,"mask","boolMask","bool"),s=t==null?0:t,a=n.rank,i=o.shape;T(a>0,()=>"mask cannot be scalar"),vt(i.slice(s,s+a),n.shape,"mask's shape must match the first K dimensions of tensor's shape,");let l=1;for(let h=s;h<s+a;h++)l*=i[h];let u=i.slice(0,s).concat([l],i.slice(s+a)),c=M(o,u),p=M(n,[-1]),m=await Qm(p),f=Co(m,[1]),d=zn(c,f,s);return r!==o&&o.dispose(),e!==n&&n.dispose(),f.dispose(),c.dispose(),p.dispose(),m.dispose(),d}var b4=y4;function w4(r,e="euclidean",t=null,o=!1){r=_(r,"x","norm");let n=zN(r,e,t),s=n.shape;if(o){let a=Jt(t,r.shape);s=Bn(n.shape,a)}return M(n,s)}function zN(r,e,t=null){if(r.rank===0)return It(r);if(r.rank!==1&&t===null)return zN(M(r,[-1]),e,t);if(r.rank===1||typeof t=="number"||Array.isArray(t)&&t.length===1){if(e===1)return ge(It(r),t);if(e===Infinity)return lr(It(r),t);if(e===-Infinity)return Pi(It(r),t);if(e==="euclidean"||e===2)return gt(ge(Fr(It(r),le(2,"int32")),t));throw new Error(`Error in norm: invalid ord value: ${e}`)}if(Array.isArray(t)&&t.length===2){if(e===1)return lr(ge(It(r),t[0]),t[1]-1);if(e===Infinity)return lr(ge(It(r),t[1]),t[0]);if(e===-Infinity)return Pi(ge(It(r),t[1]),t[0]);if(e==="fro"||e==="euclidean")return gt(ge(Oe(r),t));throw new Error(`Error in norm: invalid ord value: ${e}`)}throw new Error(`Error in norm: invalid axis: ${t}`)}var Vu=S({norm_:w4});function k4(r,e,t,o,n=!0){let s=_(r,"v","movingAverage"),a=_(e,"x","movingAverage"),i=_(t,"decay","movingAverage");Gb(s,a),T(jr(s.shape,a.shape),()=>"Shape mismatch in v and x");let l=le(1),u=ce(l,i),c=O(ce(a,s),u);if(n){T(o!=null,()=>"When using zeroDebias: true, step is required.");let p=_(o,"step","movingAverage");c=me(c,ce(l,Fr(i,p)))}return ee(s,c)}var _4=S({movingAverage_:k4});function v4(r,e,t){let o=_(r,"indices","scatterND","int32"),n=_(e,"updates","scatterND");Jh(n,o,t);let s={indices:o,updates:n},a={shape:t};return E.runKernel(Ci,s,a)}var Xw=S({scatterND_:v4});function BN(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 C4(r,e,t,o=0){let n=_(r,"sparseIndices","sparseToDense","int32"),s=_(e,"sparseValues","sparseToDense"),a=_(o,"defaultValue","sparseToDense",s.dtype);BN(n,s,t,a);let i={sparseIndices:n,sparseValues:s,defaultValue:a},l={outputShape:t};return E.runKernel(uu,i,l)}var ef=S({sparseToDense_:C4});function I4(r,e){let t=_(e,"indices","gatherND","int32"),n={params:_(r,"x","gatherND"),indices:t};return E.runKernel(li,n)}var Yw=S({gatherND_:I4});function VN(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<r.shape.length;o++)e[o]==null&&r.shape[o]!=null?t.push(r.shape[o]):t.push(e[o]);return t}return e}function N4(r,e,t,o){let n=_(r,"x","dropout");if(T(n.dtype==="float32",()=>`x has to be a floating point tensor since it's going to be scaled, but got a ${n.dtype} tensor instead.`),T(e>=0&&e<1,()=>`rate must be a float in the range [0, 1), but got ${e}.`),e===0)return r instanceof Ve?n.clone():n;let s=VN(n,t),a=1-e,i=me(Ss(ee(Es(s,0,1,"float32",o),a)),a);return O(n,i)}var Zw=S({dropout_:N4});function Jw(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;s<r;++s){let a=2*Math.PI*s/(r+o-1);n[s]=e-t*Math.cos(a)}return Vt(n,"float32")}async function S4(r,e,t=1){let o=_(r,"predictions","inTopK"),n=_(e,"targets","inTopK");T(o.rank>1,()=>`inTopK() expects the predictions to be of rank 2 or higher, but got ${o.rank}`),T(o.rank-1===n.rank,()=>`predictions rank should be 1 larger than targets rank, but got predictions rank ${o.rank} and targets rank ${n.rank}`),vt(o.shape.slice(0,o.shape.length-1),n.shape,"predictions's shape should be align with the targets' shape, except the last dimension.");let s=o.shape[o.shape.length-1];T(t>0&&t<=s,()=>`'k' passed to inTopK() must be > 0 && <= the predictions last dimension (${s}), but got ${t}`);let a=await o.data(),i=await n.data(),[l,u]=[a.length/s,s],c=vb("bool",l);for(let p=0;p<l;p++){let m=p*u,f=a.subarray(m,m+u),d=[];for(let h=0;h<f.length;h++)d.push({value:f[h],index:h});d.sort((h,g)=>g.value-h.value),c[p]=0;for(let h=0;h<t;h++)if(d[h].index===i[p]){c[p]=1;break}}return r!==o&&o.dispose(),e!==n&&n.dispose(),$r(c,n.shape,"bool")}var T4=S4;var Gn={};Ke(Gn,{conv2d:()=>D4,depthwiseConv2d:()=>O4,matMul:()=>M4});function A4(r,e,t,o,n,s="NHWC",a){let i=r;r.rank===3&&(i=M(r,[1,r.shape[0],r.shape[1],r.shape[2]]));let l=e;l.rank===3&&(l=M(e,[1,e.shape[0],e.shape[1],e.shape[2]])),T(i.rank===4,()=>`Error in conv2dDerFilter: input must be rank 4, but got shape ${i.shape}.`),T(l.rank===4,()=>`Error in conv2dDerFilter: dy must be rank 4, but got shape ${l.shape}.`),T(t.length===4,()=>`Error in conv2dDerFilter: filterShape must be length 4, but got ${t}.`);let u=s==="NHWC"?i.shape[3]:i.shape[1],c=s==="NHWC"?l.shape[3]:l.shape[1];T(u===t[2],()=>`Error in conv2dDerFilter: depth of input ${u}) must match input depth in filter (${t[2]}.`),T(c===t[3],()=>`Error in conv2dDerFilter: depth of dy (${c}) must match output depth for filter (${t[3]}).`),a!=null&&T(ot(n),()=>`Error in conv2dDerFilter: pad must be an integer when using, dimRoundingMode ${a} but got pad ${n}.`);let p={x:i,dy:l},m={strides:o,pad:n,dataFormat:s,dimRoundingMode:a,filterShape:t};return E.runKernel(Wl,p,m)}var ep=S({conv2DBackpropFilter_:A4});function Gu(r,e,t){if(t==null||t==="linear")return r;if(t==="relu")return O(r,Ds(e));throw new Error(`Cannot compute gradient for fused activation ${t}.`)}function Wu(r,e){let t=e,o=kt(r.shape,e.shape);return o.length>0&&(t=ge(t,o)),M(t,r.shape)}function ju(r,e,t,o){if(e==="linear")return r;if(e==="relu")return Nr(r);if(e==="elu")return Ns(r);if(e==="relu6")return Ru(r);if(e==="prelu")return Ta(r,t);if(e==="leakyrelu")return Ca(r,o);throw new Error(`Unknown fused activation ${e}.`)}var Uu=(r,e)=>!(r>0)||e==="linear";function E4({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",Uu(E.state.gradientDepth,l)===!1){let v=Kr(r,e,t,o,n,s,a);return i!=null&&(v=ee(v,i)),ju(v,l,u,c)}let p=_(r,"x","conv2d"),m=_(e,"filter","conv2d"),f=p,d=!1;p.rank===3&&(d=!0,f=M(p,[1,p.shape[0],p.shape[1],p.shape[2]])),T(f.rank===4,()=>`Error in fused conv2d: input must be rank 4, but got rank ${f.rank}.`),T(m.rank===4,()=>`Error in fused conv2d: filter must be rank 4, but got rank ${m.rank}.`),a!=null&&T(ot(o),()=>`Error in fused conv2d: pad must be an integer when using, dimRoundingMode ${a} but got pad ${o}.`),T(f.shape[3]===m.shape[2],()=>`Error in conv2d: depth of input (${f.shape[3]}) must match input depth for filter ${m.shape[2]}.`),T(wr(t,s),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${t} and dilations '${s}'`),T(n==="NHWC",()=>`Error in conv2d: got dataFormat of ${n} but only NHWC is currently supported.`);let h=wu(f.shape,m.shape,t,s,o,a),g;i!=null&&(g=_(i,"bias","fused conv2d"),[g]=Ge(g,p),Be(h.outShape,g.shape));let y;u!=null&&(y=_(u,"prelu weights","fused conv2d"));let b=(v,D)=>{let[A,R,P,L]=D,G=Gu(v,P,l);T(Lo(s),()=>`Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${s}'`);let j=qc(R.shape,G,A,t,o),U=ep(R,G,A.shape,t,o),H=[j,U];if(L!=null){let q=Wu(L,G);H.push(q)}return H},w={x:f,filter:m,bias:g,preluActivationWeights:y},k={strides:t,pad:o,dataFormat:n,dilations:s,dimRoundingMode:a,activation:l,leakyreluAlpha:c};return i==null?Xr((D,A,R)=>{let P=E.runKernel(ks,w,k);return R([A,D,P]),d&&(P=M(P,[P.shape[1],P.shape[2],P.shape[3]])),{value:P,gradFunc:b}})(f,m):Xr((D,A,R,P)=>{let L=E.runKernel(ks,w,k);return P([A,D,L,R]),d&&(L=M(L,[L.shape[1],L.shape[2],L.shape[3]])),{value:L,gradFunc:b}})(f,m,g)}var D4=S({fusedConv2d_:E4});function $4(r,e,t,o,n,s=[1,1],a){let i=r;r.rank===3&&(i=M(r,[1,r.shape[0],r.shape[1],r.shape[2]]));let l=e;l.rank===3&&(l=M(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let u={x:i,dy:l},c={strides:o,pad:n,dimRoundingMode:a,dilations:s,filterShape:t};return E.runKernel(ql,u,c)}var cg=S({depthwiseConv2dNativeBackpropFilter_:$4});function R4(r,e,t,o,n,s=[1,1],a){let i=e,l=!1;e.rank===3&&(l=!0,i=M(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let u={dy:i,filter:t},c={strides:o,pad:n,dimRoundingMode:a,dilations:s,inputShape:r},p=E.runKernel(Kl,u,c);return l?M(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var pg=S({depthwiseConv2dNativeBackpropInput_:R4});function F4({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(Uu(E.state.gradientDepth,l)===!1){let v=Is(r,e,t,o,n,s,a);return i!=null&&(v=ee(v,i)),ju(v,l,u,c)}let p=_(r,"x","depthwiseConv2d"),m=_(e,"filter","depthwiseConv2d"),f=p,d=!1;p.rank===3&&(d=!0,f=M(p,[1,p.shape[0],p.shape[1],p.shape[2]])),T(f.rank===4,()=>`Error in fused depthwiseConv2d: input must be rank 4, but got rank ${f.rank}.`),T(m.rank===4,()=>`Error in fused depthwiseConv2d: filter must be rank 4, but got rank ${m.rank}.`),T(f.shape[3]===m.shape[2],()=>`Error in fused depthwiseConv2d: number of input channels (${f.shape[3]}) must match the inChannels dimension in filter ${m.shape[2]}.`),s==null&&(s=[1,1]),T(wr(t,s),()=>`Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides ${t} and dilations '${s}'`),a!=null&&T(ot(o),()=>`Error in fused depthwiseConv2d: pad must be an integer when using dimRoundingMode ${a} but got pad ${o}.`);let h=wu(f.shape,m.shape,t,s,o,a,!0),g;i!=null&&(g=_(i,"bias","fused conv2d"),[g]=Ge(g,p),Be(h.outShape,g.shape));let y;u!=null&&(y=_(u,"prelu weights","fused depthwiseConv2d"));let b=(v,D)=>{T(Lo(s),()=>`Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '${s}'`);let[A,R,P,L]=D,G=Gu(v,P,l),j=pg(R.shape,G,A,t,o,s,a),U=cg(R,G,A.shape,t,o,s,a);if(L!=null){let H=Wu(g,G);return[j,U,H]}return[j,U]},w={x:f,filter:m,bias:g,preluActivationWeights:y},k={strides:t,pad:o,dataFormat:n,dilations:s,dimRoundingMode:a,activation:l,leakyreluAlpha:c};return i==null?Xr((D,A,R)=>{let P=E.runKernel(_s,w,k);return R([A,D,P]),d&&(P=M(P,[P.shape[1],P.shape[2],P.shape[3]])),{value:P,gradFunc:b}})(f,m):Xr((D,A,R,P)=>{let L=E.runKernel(_s,w,k);return P([A,D,L,R]),d&&(L=M(L,[L.shape[1],L.shape[2],L.shape[3]])),{value:L,gradFunc:b}})(f,m,g)}var O4=S({fusedDepthwiseConv2d_:F4});function P4({a:r,b:e,transposeA:t=!1,transposeB:o=!1,bias:n,activation:s="linear",preluActivationWeights:a,leakyreluAlpha:i}){if(Uu(E.state.gradientDepth,s)===!1){let L=We(r,e,t,o);return n!=null&&(L=ee(L,n)),ju(L,s,a,i)}let l=_(r,"a","fused matMul"),u=_(e,"b","fused matMul");[l,u]=Ge(l,u);let c=t?l.shape[l.rank-2]:l.shape[l.rank-1],p=o?u.shape[u.rank-1]:u.shape[u.rank-2],m=t?l.shape[l.rank-1]:l.shape[l.rank-2],f=o?u.shape[u.rank-2]:u.shape[u.rank-1],d=l.shape.slice(0,-2),h=u.shape.slice(0,-2),g=ct(d),y=ct(h);T(l.rank>=2&&u.rank>=2&&l.rank===u.rank,()=>`Error in fused matMul: inputs must have the same rank of at least 2, got ranks ${l.rank} and ${u.rank}.`),T(jr(d,h),()=>`Error in fused matMul: outer dimensions (${d}) and (${h}) of Tensors with shapes ${l.shape} and ${u.shape} must match.`),T(c===p,()=>`Error in fused matMul: inner shapes (${c}) and (${p}) of Tensors with shapes ${l.shape} and ${u.shape} and transposeA=${t} and transposeB=${o} must match.`);let b=l.shape.slice(0,-2).concat([m,f]),w=t?M(l,[g,c,m]):M(l,[g,m,c]),k=o?M(u,[y,f,p]):M(u,[y,p,f]),v;n!=null&&(v=_(n,"bias","fused matMul"),[v]=Ge(v,l),Be(b,v.shape));let D;a!=null&&(D=_(a,"prelu weights","fused matMul"));let A=(L,G)=>{let[j,U,H,q]=G,X=Gu(M(L,H.shape),H,s),oe,Y;if(!t&&!o?(oe=We(X,U,!1,!0),Y=We(j,X,!0,!1)):!t&&o?(oe=We(X,U,!1,!1),Y=We(X,j,!0,!1)):t&&!o?(oe=We(U,X,!1,!0),Y=We(j,X,!1,!1)):(oe=We(U,X,!0,!0),Y=We(X,j,!0,!0)),n!=null){let re=Wu(q,X);return[oe,Y,re]}else return[oe,Y]},R={a:w,b:k,bias:v,preluActivationWeights:D},P={transposeA:t,transposeB:o,activation:s,leakyreluAlpha:i};return n==null?Xr((G,j,U)=>{let H=E.runKernel(ws,R,P);return U([G,j,H]),{value:M(H,b),gradFunc:A}})(w,k):Xr((G,j,U,H)=>{let q=E.runKernel(ws,R,P);return H([G,j,q,U]),{value:M(q,b),gradFunc:A}})(w,k,v)}var M4=S({fusedMatMul_:P4});function L4(r){return tf(r,.54,.46)}var GN=S({hammingWindow_:L4});function z4(r){return tf(r,.5,.5)}var mg=S({hannWindow_:z4});function B4(r,e,t,o=!1,n=0){let s=0,a=[];for(;s+e<=r.size;)a.push(Re(r,s,e)),s+=t;if(o)for(;s<r.size;){let i=s+e-r.size,l=Ze([Re(r,s,e-i),va([i],n)]);a.push(l),s+=t}return a.length===0?Li([],[0,e]):M(Ze(a),[a.length,e])}var fg=S({frame_:B4});function V4(r,e,t,o,n=mg){o==null&&(o=Jw(e));let s=fg(r,e,t),a=O(s,n(e)),i=[];for(let l=0;l<s.shape[0];l++)i.push(Da(Re(a,[l,0],[1,e]),o));return Ze(i)}var WN=S({stft_:V4});function G4(r,e,t,o,n="bilinear",s=0){let a=_(r,"image","cropAndResize"),i=_(e,"boxes","cropAndResize","float32"),l=_(t,"boxInd","cropAndResize","int32"),u=i.shape[0];T(a.rank===4,()=>`Error in cropAndResize: image must be rank 4,but got rank ${a.rank}.`),T(i.rank===2&&i.shape[1]===4,()=>`Error in cropAndResize: boxes must be have size [${u},4] but had shape ${i.shape}.`),T(l.rank===1&&l.shape[0]===u,()=>`Error in cropAndResize: boxInd must be have size [${u}] but had shape ${i.shape}.`),T(o.length===2,()=>`Error in cropAndResize: cropSize must be of length 2, but got length ${o.length}.`),T(o[0]>=1&&o[1]>=1,()=>`cropSize must be atleast [1,1], but was ${o}`),T(n==="bilinear"||n==="nearest",()=>`method must be bilinear or nearest, but was ${n}`);let c={image:a,boxes:i,boxInd:l},p={method:n,extrapolationValue:s,cropSize:o};return E.runKernel(ti,c,p)}var jN=S({cropAndResize_:G4});function W4(r){let e=_(r,"image","flipLeftRight","float32");T(e.rank===4,()=>`Error in flipLeftRight: image must be rank 4,but got rank ${e.rank}.`);let t={image:e};return E.runKernel(ai,t,{})}var UN=S({flipLeftRight_:W4});function j4(r,e,t=0,o=.5){let n=_(r,"image","rotateWithOffset","float32");T(n.rank===4,()=>`Error in rotateWithOffset: image must be rank 4,but got rank ${n.rank}.`);let s={image:n},a={radians:e,fillValue:t,center:o};return E.runKernel($i,s,a)}var HN=S({rotateWithOffset_:j4});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),T(0<=o&&o<=1,()=>`iouThreshold must be in [0, 1], but was '${o}'`),T(r.rank===2,()=>`boxes must be a 2D tensor, but was of rank '${r.rank}'`),T(r.shape[1]===4,()=>`boxes must have 4 columns, but 2nd dimension was ${r.shape[1]}`),T(e.rank===1,()=>"scores must be a 1D tensor"),T(e.shape[0]===a,()=>`scores has incompatible shape with boxes. Expected ${a}, but was ${e.shape[0]}`),T(0<=s&&s<=1,()=>`softNmsSigma must be in [0, 1], but was '${s}'`),{maxOutputSize:t,iouThreshold:o,scoreThreshold:n,softNmsSigma:s}}function U4(r,e,t,o=.5,n=Number.NEGATIVE_INFINITY){let s=_(r,"boxes","nonMaxSuppression"),a=_(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 E.runKernel(bi,{boxes:s,scores:a},l)}var qN=S({nonMaxSuppression_:U4});function KN(r,e,t){let o=H4(r,e,t),n=o<0?-(o+1):o;r.splice(n,0,e)}function H4(r,e,t){return K4(r,e,t||q4)}function q4(r,e){return r>e?1:r<e?-1:0}function K4(r,e,t){let o=0,n=r.length,s=0,a=!1;for(;o<n;){s=o+(n-o>>>1);let i=t(e,r[s]);i>0?o=s+1:(n=s,a=!i)}return a?o:-o-1}function ek(r,e,t,o,n){return Qw(r,e,t,o,n,0)}function tk(r,e,t,o,n,s){return Qw(r,e,t,o,n,0,!1,s,!0)}function rk(r,e,t,o,n,s){return Qw(r,e,t,o,n,s,!0)}function Qw(r,e,t,o,n,s,a=!1,i=!1,l=!1){let u=[];for(let g=0;g<e.length;g++)e[g]>n&&u.push({score:e[g],boxIndex:g,suppressBeginIndex:0});u.sort(XN);let c=s>0?-.5/s:0,p=[],m=[];for(;p.length<t&&u.length>0;){let g=u.pop(),{score:y,boxIndex:b,suppressBeginIndex:w}=g;if(y<n)break;let k=!1;for(let v=p.length-1;v>=w;--v){let D=X4(r,b,p[v]);if(D>=o){k=!0;break}if(g.score=g.score*Y4(o,c,D),g.score<=n)break}g.suppressBeginIndex=p.length,k||(g.score===y?(p.push(b),m.push(g.score)):g.score>n&&KN(u,g,XN))}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 X4(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),w=Math.max(y-h,0)*Math.max(b-g,0);return w/(f+d-w)}function Y4(r,e,t){let o=Math.exp(e*t*t);return t<=r?o:0}function XN(r,e){return r.score-e.score||r.score===e.score&&e.boxIndex-r.boxIndex}async function Z4(r,e,t,o=.5,n=Number.NEGATIVE_INFINITY){let s=_(r,"boxes","nonMaxSuppressionAsync"),a=_(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}=ek(u,c,t,o,n);return s!==r&&s.dispose(),a!==e&&a.dispose(),Vt(p,"int32")}var YN=Z4;function J4(r,e,t,o=.5,n=Number.NEGATIVE_INFINITY,s=0){let a=_(r,"boxes","nonMaxSuppression"),i=_(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=E.runKernel(ki,u,c);return{selectedIndices:p[0],selectedScores:p[1]}}var ZN=S({nonMaxSuppressionWithScore_:J4});async function Q4(r,e,t,o=.5,n=Number.NEGATIVE_INFINITY,s=0){let a=_(r,"boxes","nonMaxSuppressionAsync"),i=_(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}=rk(c,p,t,o,n,s);return a!==r&&a.dispose(),i!==e&&i.dispose(),{selectedIndices:Vt(m,"int32"),selectedScores:Vt(f)}}var JN=Q4;function eU(r,e,t,o=.5,n=Number.NEGATIVE_INFINITY,s=!1){let a=_(r,"boxes","nonMaxSuppression"),i=_(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=E.runKernel(wi,m,f);return{selectedIndices:d[0],validOutputs:d[1]}}var QN=S({nonMaxSuppressionPadded_:eU});async function tU(r,e,t,o=.5,n=Number.NEGATIVE_INFINITY,s=!1){let a=_(r,"boxes","nonMaxSuppressionAsync"),i=_(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}=tk(m,f,u,c,p,s);return a!==r&&a.dispose(),i!==e&&i.dispose(),{selectedIndices:Vt(d,"int32"),validOutputs:le(h,"int32")}}var eS=tU;function rU(r,e,t=!1,o=!1){let n=_(r,"images","resizeBilinear");T(n.rank===3||n.rank===4,()=>`Error in resizeBilinear: x must be rank 3 or 4, but got rank ${n.rank}.`),T(e.length===2,()=>`Error in resizeBilinear: new shape must 2D, but got shape ${e}.`),T(o===!1||t===!1,()=>"Error in resizeBilinear: If halfPixelCenters is true, alignCorners must be false.");let s=n,a=!1;n.rank===3&&(a=!0,s=M(n,[1,n.shape[0],n.shape[1],n.shape[2]]));let[]=e,i={images:s},l={alignCorners:t,halfPixelCenters:o,size:e},u=E.runKernel(vn,i,l);return a?M(u,[u.shape[1],u.shape[2],u.shape[3]]):u}var dg=S({resizeBilinear_:rU});function oU(r,e,t=!1,o=!1){let n=_(r,"images","resizeNearestNeighbor");T(n.rank===3||n.rank===4,()=>`Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank ${n.rank}.`),T(e.length===2,()=>`Error in resizeNearestNeighbor: new shape must 2D, but got shape ${e}.`),T(n.dtype==="float32"||n.dtype==="int32",()=>"`images` must have `int32` or `float32` as dtype"),T(o===!1||t===!1,()=>"Error in resizeNearestNeighbor: If halfPixelCenters is true, alignCorners must be false.");let s=n,a=!1;n.rank===3&&(a=!0,s=M(n,[1,n.shape[0],n.shape[1],n.shape[2]]));let[]=e,i={images:s},l={alignCorners:t,halfPixelCenters:o,size:e},u=E.runKernel(pa,i,l);return a?M(u,[u.shape[1],u.shape[2],u.shape[3]]):u}var hg=S({resizeNearestNeighbor_:oU});function nU(r,e,t="nearest",o="constant",n=0,s){let a=_(r,"image","transform","float32"),i=_(e,"transforms","transform","float32");T(a.rank===4,()=>`Error in transform: image must be rank 4,but got rank ${a.rank}.`),T(i.rank===2&&(i.shape[0]===a.shape[0]||i.shape[0]===1)&&i.shape[1]===8,()=>"Error in transform: Input transform should be batch x 8 or 1 x 8"),T(s==null||s.length===2,()=>`Error in transform: outputShape must be [height, width] or null, but got ${s}.`);let l={image:a,transforms:i},u={interpolation:t,fillMode:o,fillValue:n,outputShape:s};return E.runKernel(cu,l,u)}var tS=S({transform_:nU});function sU(r,e,t){T(e%1==0,()=>`bandPart(): numLower must be an integer, got ${e}.`),T(t%1==0,()=>`bandPart(): numUpper must be an integer, got ${t}.`);let o=_(r,"a","bandPart");T(o.rank>=2,()=>`bandPart(): Rank must be at least 2, got ${o.rank}.`);let n=o.shape,[s,a]=o.shape.slice(-2);if(!(e<=s))throw new Error(`bandPart(): numLower (${e}) must not be greater than the number of rows (${s}).`);if(!(t<=a))throw new Error(`bandPart(): numUpper (${t}) must not be greater than the number of columns (${a}).`);e<0&&(e=s),t<0&&(t=a);let i=M(Zc(0,s,1,"int32"),[-1,1]),l=Zc(0,a,1,"int32"),u=ce(i,l),c=dr(Bo(u,le(+e,"int32")),io(u,le(-t,"int32"))),p=ht([s,a],o.dtype);return M(Bt(cr(M(o,[-1,s,a])).map(m=>Dt(c,m,p))),n)}var rS=S({bandPart_:sU});function iU(r){let e;if(Array.isArray(r)){e=!1,T(r!=null&&r.length>0,()=>"Gram-Schmidt process: input must not be null, undefined, or empty");let n=r[0].shape[0];for(let s=1;s<r.length;++s)T(r[s].shape[0]===n,()=>`Gram-Schmidt: Non-unique lengths found in the input vectors: (${r[s].shape[0]} vs. ${n})`)}else e=!0,r=ur(r,r.shape[0],0).map(n=>Co(n,[0]));T(r.length<=r[0].shape[0],()=>`Gram-Schmidt: Number of vectors (${r.length}) exceeds number of dimensions (${r[0].shape[0]}).`);let t=[],o=r;for(let n=0;n<r.length;++n)t.push(E.tidy(()=>{let s=o[n];if(n>0)for(let a=0;a<n;++a){let i=O(ge(O(t[a],s)),t[a]);s=ce(s,i)}return me(s,Vu(s,"euclidean"))}));return e?Bt(t,0):t}var oS=S({gramSchmidt_:iU});function aU(r,e=!1){if(T(r.rank>=2,()=>`qr() requires input tensor to have a rank >= 2, but got rank ${r.rank}`),r.rank===2)return nS(r,e);{let t=r.shape.slice(0,r.shape.length-2).reduce((l,u)=>l*u),o=cr(M(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=M(Bt(n,0),r.shape),i=M(Bt(s,0),r.shape);return[a,i]}}function nS(r,e=!1){return E.tidy(()=>{T(r.shape.length===2,()=>`qr2d() requires a 2D Tensor, but got a ${r.shape.length}D Tensor.`);let t=r.shape[0],o=r.shape[1],n=Kc(t),s=Po(r),a=Li([[1]],[1,1]),i=Po(a),l=t>=o?o:t;for(let u=0;u<l;++u){let c=s,p=i,m=n;[i,s,n]=E.tidy(()=>{let f=Re(s,[u,u],[t-u,1]),d=Vu(f),h=Re(s,[u,u],[1,1]),g=Dt(Qt(h,0),Li([[-1]]),Li([[1]])),y=ce(h,O(g,d)),b=me(f,y);b.shape[0]===1?i=Po(a):i=Ze([a,Re(b,[1,0],[b.shape[0]-1,b.shape[1]])],0);let w=He(me(We(g,y),d)),k=Re(s,[u,0],[t-u,o]),v=O(w,i),D=Ue(i);if(u===0)s=ce(k,We(v,We(D,k)));else{let P=ce(k,We(v,We(D,k)));s=Ze([Re(s,[0,0],[u,o]),P],0)}let A=Ue(v),R=Re(n,[0,u],[t,n.shape[1]-u]);if(u===0)n=ce(R,We(We(R,i),A));else{let P=ce(R,We(We(R,i),A));n=Ze([Re(n,[0,0],[t,u]),P],1)}return[i,s,n]}),Ae([c,p,m])}return!e&&t>o&&(n=Re(n,[0,0],[t,o]),s=Re(s,[0,0],[o,o])),[n,s]})}var sS=S({qr_:aU});var Gt;(function(r){r[r.NONE=0]="NONE",r[r.MEAN=1]="MEAN",r[r.SUM=2]="SUM",r[r.SUM_BY_NONZERO_WEIGHTS=3]="SUM_BY_NONZERO_WEIGHTS"})(Gt||(Gt={}));function lU(r,e,t=Gt.SUM_BY_NONZERO_WEIGHTS){let o=_(r,"losses","computeWeightedLoss"),n=null;e!=null&&(n=_(e,"weights","computeWeightedLoss"));let s=n==null?o:O(o,n);if(t===Gt.NONE)return s;if(t===Gt.SUM)return ge(s);if(t===Gt.MEAN){if(n==null)return dt(s);{let a=o.size/n.size,i=me(ge(s),ge(n));return a>1?me(i,le(a)):i}}if(t===Gt.SUM_BY_NONZERO_WEIGHTS){if(n==null)return me(ge(s),le(o.size));{let a=O(n,Ir(o.shape)),i=ne(ge(Vn(a,le(0))),"float32");return me(ge(s),i)}}throw Error(`Unknown reduction: ${t}`)}var Sr=S({computeWeightedLoss_:lU});function uU(r,e,t,o=Gt.SUM_BY_NONZERO_WEIGHTS){let n=_(r,"labels","absoluteDifference"),s=_(e,"predictions","absoluteDifference"),a=null;t!=null&&(a=_(t,"weights","absoluteDifference")),vt(n.shape,s.shape,"Error in absoluteDifference: ");let i=It(ce(n,s));return Sr(i,a,o)}var iS=S({absoluteDifference_:uU});function cU(r,e,t,o,n=Gt.SUM_BY_NONZERO_WEIGHTS){let s=_(r,"labels","cosineDistance"),a=_(e,"predictions","cosineDistance"),i=null;o!=null&&(i=_(o,"weights","cosineDistance")),vt(s.shape,a.shape,"Error in cosineDistance: ");let l=le(1),u=ce(l,ge(O(s,a),t,!0));return Sr(u,i,n)}var aS=S({cosineDistance_:cU});function pU(r,e,t,o=Gt.SUM_BY_NONZERO_WEIGHTS){let n=_(r,"labels","hingeLoss"),s=_(e,"predictions","hingeLoss"),a=null;t!=null&&(a=_(t,"weights","hingeLoss")),vt(n.shape,s.shape,"Error in hingeLoss: ");let i=le(1);n=ce(O(le(2),n),i);let l=Nr(ce(i,O(n,s)));return Sr(l,a,o)}var lS=S({hingeLoss_:pU});function mU(r,e,t,o=1,n=Gt.SUM_BY_NONZERO_WEIGHTS){let s=_(r,"labels","huberLoss"),a=_(e,"predictions","huberLoss"),i=null;t!=null&&(i=_(t,"weights","huberLoss")),vt(s.shape,a.shape,"Error in huberLoss: ");let l=le(o),u=It(ce(a,s)),c=As(u,l),p=ce(u,c),m=ee(O(le(.5),Oe(c)),O(l,p));return Sr(m,i,n)}var uS=S({huberLoss_:mU});function fU(r,e,t,o=1e-7,n=Gt.SUM_BY_NONZERO_WEIGHTS){let s=_(r,"labels","logLoss"),a=_(e,"predictions","logLoss"),i=null;t!=null&&(i=_(t,"weights","logLoss")),vt(s.shape,a.shape,"Error in logLoss: ");let l=le(1),u=le(o),c=He(O(s,ar(ee(a,u)))),p=O(ce(l,s),ar(ee(ce(l,a),u))),m=ce(c,p);return Sr(m,i,n)}var cS=S({logLoss_:fU});function dU(r,e,t,o=Gt.SUM_BY_NONZERO_WEIGHTS){let n=_(r,"labels","meanSquaredError"),s=_(e,"predictions","meanSquaredError"),a=null;t!=null&&(a=_(t,"weights","meanSquaredError")),vt(n.shape,s.shape,"Error in meanSquaredError: ");let i=zu(n,s);return Sr(i,a,o)}var pS=S({meanSquaredError_:dU});function hU(r,e){let t=_(r,"labels","sigmoidCrossEntropyWithLogits"),o=_(e,"logits","sigmoidCrossEntropyWithLogits");vt(t.shape,o.shape,"Error in sigmoidCrossEntropyWithLogits: ");let n=Nr(o),s=O(o,t),a=Tu(Yt(He(It(o))));return ee(ce(n,s),a)}function gU(r,e,t,o=0,n=Gt.SUM_BY_NONZERO_WEIGHTS){let s=_(r,"multiClassLabels","sigmoidCrossEntropy"),a=_(e,"logits","sigmoidCrossEntropy"),i=null;if(t!=null&&(i=_(t,"weights","sigmoidCrossEntropy")),vt(s.shape,a.shape,"Error in sigmoidCrossEntropy: "),o>0){let u=le(o),c=le(1),p=le(.5);s=ee(O(s,ce(c,u)),O(p,u))}let l=hU(s,a);return Sr(l,i,n)}var mS=S({sigmoidCrossEntropy_:gU});function xU(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 Xr((n,s,a)=>{let l=Lm(s,[t],!0),u=ce(ne(s,"float32"),l);a([n,u]);let c=He(O(u,n));return{value:ge(c,[t]),gradFunc:(f,d)=>{let[h,g]=d,y=Bn(f.shape,[t]);return[O(M(f,y),ce(ne(h,"float32"),Yt(g))),O(M(f,y),ce(Yt(g),ne(h,"float32")))]}}})(r,e)}function yU(r,e,t,o=0,n=Gt.SUM_BY_NONZERO_WEIGHTS){let s=_(r,"onehotLabels","softmaxCrossEntropy"),a=_(e,"logits","softmaxCrossEntropy"),i=null;if(t!=null&&(i=_(t,"weights","softmaxCrossEntropy")),vt(s.shape,a.shape,"Error in softmaxCrossEntropy: "),o>0){let u=le(o),c=le(1),p=le(s.shape[1]);s=ee(O(s,ce(c,u)),me(u,p))}let l=xU(s,a);return Sr(l,i,n)}var fS=S({softmaxCrossEntropy_:yU});var bU={fft:Ea,ifft:Mi,rfft:Da,irfft:Lu},wU={hammingWindow:GN,hannWindow:mg,frame:fg,stft:WN},$s={flipLeftRight:UN,resizeNearestNeighbor:hg,resizeBilinear:dg,rotateWithOffset:HN,cropAndResize:jN,nonMaxSuppression:qN,nonMaxSuppressionAsync:YN,nonMaxSuppressionWithScore:ZN,nonMaxSuppressionWithScoreAsync:JN,nonMaxSuppressionPadded:QN,nonMaxSuppressionPaddedAsync:eS,transform:tS},ok={bandPart:rS,gramSchmidt:oS,qr:sS},kU={absoluteDifference:iS,computeWeightedLoss:Sr,cosineDistance:aS,hingeLoss:lS,huberLoss:uS,logLoss:cS,meanSquaredError:pS,sigmoidCrossEntropy:mS,softmaxCrossEntropy:fS};var Or=class extends eg{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:le(this.iterations_,"int32")}}async getWeights(){throw new Error("getWeights() is not implemented for this optimizer yet.")}async setWeights(e){throw new Error(`setWeights() is not implemented for this optimizer class ${this.getClassName()}`)}async extractIterations(e){return this.iterations_=(await e[0].tensor.data())[0],e.slice(1)}};Object.defineProperty(Or,Symbol.hasInstance,{value:r=>r.minimize!=null&&r.computeGradients!=null&&r.applyGradients!=null});var tp=class extends Or{constructor(e,t,o=null){super();this.learningRate=e,this.rho=t,this.epsilon=o,this.accumulatedGrads=[],this.accumulatedUpdates=[],o==null&&(this.epsilon=E.backend.epsilon())}applyGradients(e){(Array.isArray(e)?e.map(o=>o.name):Object.keys(e)).forEach((o,n)=>{let s=E.registeredVariables[o],a=!1;this.accumulatedGrads[n]==null&&(this.accumulatedGrads[n]={originalName:`${o}/accum_grad`,variable:V(()=>Ce(s).variable(a))}),this.accumulatedUpdates[n]==null&&(this.accumulatedUpdates[n]={originalName:`${o}/accum_var`,variable:V(()=>Ce(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(Oe(i),1-this.rho)),p=O(me(gt(ee(u,this.epsilon)),gt(ee(l,this.epsilon))),i),m=ee(O(u,this.rho),O(Oe(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)}};tp.className="Adadelta";so(tp);var rp=class extends Or{constructor(e,t=.1){super();this.learningRate=e,this.initialAccumulatorValue=t,this.accumulatedGrads=[]}applyGradients(e){(Array.isArray(e)?e.map(o=>o.name):Object.keys(e)).forEach((o,n)=>{let s=E.registeredVariables[o];if(this.accumulatedGrads[n]==null){let l=!1;this.accumulatedGrads[n]={originalName:`${o}/accumulator`,variable:V(()=>va(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,Oe(a));i.assign(l);let u=ee(O(me(a,gt(ee(l,E.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)}};rp.className="Adagrad";so(rp);var op=class extends Or{constructor(e,t,o,n=null){super();this.learningRate=e,this.beta1=t,this.beta2=o,this.epsilon=n,this.accumulatedFirstMoment=[],this.accumulatedSecondMoment=[],V(()=>{this.accBeta1=le(t).variable(),this.accBeta2=le(o).variable()}),n==null&&(this.epsilon=E.backend.epsilon())}applyGradients(e){let t=Array.isArray(e)?e.map(o=>o.name):Object.keys(e);V(()=>{let o=ce(1,this.accBeta1),n=ce(1,this.accBeta2);t.forEach((s,a)=>{let i=E.registeredVariables[s],l=!1;this.accumulatedFirstMoment[a]==null&&(this.accumulatedFirstMoment[a]={originalName:`${s}/m`,variable:V(()=>Ce(i).variable(l))}),this.accumulatedSecondMoment[a]==null&&(this.accumulatedSecondMoment[a]={originalName:`${s}/v`,variable:V(()=>Ce(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(Oe(u),1-this.beta2)),d=me(m,o),h=me(f,n);c.assign(m),p.assign(f);let g=ee(O(me(d,ee(gt(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(Fr(this.beta1,this.iterations_+1)),this.accBeta2.assign(Fr(this.beta2,this.iterations_+1))});let t=e.length/2,o=!1;this.accumulatedFirstMoment=e.slice(0,t).map(n=>({originalName:n.name,variable:n.tensor.variable(o)})),this.accumulatedSecondMoment=e.slice(t,t*2).map(n=>({originalName:n.name,variable:n.tensor.variable(o)}))}getConfig(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon}}static fromConfig(e,t){return new e(t.learningRate,t.beta1,t.beta2,t.epsilon)}};op.className="Adam";so(op);var np=class extends Or{constructor(e,t,o,n=null,s=0){super();this.learningRate=e,this.beta1=t,this.beta2=o,this.epsilon=n,this.decay=s,this.accumulatedFirstMoment=[],this.accumulatedWeightedInfNorm=[],V(()=>{this.iteration=le(0).variable(),this.accBeta1=le(t).variable()}),n==null&&(this.epsilon=E.backend.epsilon())}applyGradients(e){let t=Array.isArray(e)?e.map(o=>o.name):Object.keys(e);V(()=>{let o=ce(1,this.accBeta1),n=me(-this.learningRate,ee(O(this.iteration,this.decay),1));t.forEach((s,a)=>{let i=E.registeredVariables[s],l=!1;this.accumulatedFirstMoment[a]==null&&(this.accumulatedFirstMoment[a]={originalName:`${s}/m`,variable:Ce(i).variable(l)}),this.accumulatedWeightedInfNorm[a]==null&&(this.accumulatedWeightedInfNorm[a]={originalName:`${s}/v`,variable:Ce(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=It(u),h=Yr(f,d);c.assign(m),p.assign(h);let g=ee(O(me(n,o),me(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)}};np.className="Adamax";so(np);var ul=class extends Or{constructor(e){super();this.learningRate=e,this.setLearningRate(e)}applyGradients(e){(Array.isArray(e)?e.map(o=>o.name):Object.keys(e)).forEach((o,n)=>{let s=Array.isArray(e)?e[n].tensor:e[o];if(s==null)return;let a=E.registeredVariables[o];V(()=>{let i=ee(O(this.c,s),a);a.assign(i)})}),this.incrementIterations()}setLearningRate(e){this.learningRate=e,this.c!=null&&this.c.dispose(),this.c=Et(le(-e))}dispose(){this.c.dispose()}async getWeights(){return[await this.saveIterations()]}async setWeights(e){if(e=await this.extractIterations(e),e.length!==0)throw new Error("SGD optimizer does not have settable weights.")}getConfig(){return{learningRate:this.learningRate}}static fromConfig(e,t){return new e(t.learningRate)}};ul.className="SGD";so(ul);var sp=class extends ul{constructor(e,t,o=!1){super(e);this.learningRate=e,this.momentum=t,this.useNesterov=o,this.accumulations=[],this.m=le(this.momentum)}applyGradients(e){(Array.isArray(e)?e.map(o=>o.name):Object.keys(e)).forEach((o,n)=>{let s=E.registeredVariables[o];if(this.accumulations[n]==null){let l=!1;this.accumulations[n]={originalName:`${o}/momentum`,variable:V(()=>Ce(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)}};sp.className="Momentum";so(sp);var ip=class extends Or{constructor(e,t=.9,o=0,n=null,s=!1){super();if(this.learningRate=e,this.decay=t,this.momentum=o,this.epsilon=n,this.accumulatedMeanSquares=[],this.accumulatedMoments=[],this.accumulatedMeanGrads=[],this.centered=s,n==null&&(this.epsilon=E.backend.epsilon()),e==null)throw new Error("learningRate for RMSPropOptimizer must be defined.")}applyGradients(e){(Array.isArray(e)?e.map(o=>o.name):Object.keys(e)).forEach((o,n)=>{let s=E.registeredVariables[o],a=!1;this.accumulatedMeanSquares[n]==null&&(this.accumulatedMeanSquares[n]={originalName:`${o}/rms`,variable:V(()=>Ce(s).variable(a))}),this.accumulatedMoments[n]==null&&(this.accumulatedMoments[n]={originalName:`${o}/momentum`,variable:V(()=>Ce(s).variable(a))}),this.accumulatedMeanGrads[n]==null&&this.centered&&(this.accumulatedMeanGrads[n]={originalName:`${o}/mg`,variable:V(()=>Ce(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(Oe(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=me(O(i,this.learningRate),gt(ce(c,ee(Oe(m),this.epsilon)))),d=ee(O(u,this.momentum),f);l.assign(c),p.assign(m),u.assign(d);let h=ce(s,d);s.assign(h)}else{let p=ee(O(l,this.decay),O(Oe(i),1-this.decay)),m=ee(O(u,this.momentum),me(O(i,this.learningRate),gt(ee(p,this.epsilon))));l.assign(p),u.assign(m);let f=ce(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)}};ip.className="RMSProp";so(ip);var $a=class{static sgd(e){return new ul(e)}static momentum(e,t,o=!1){return new sp(e,t,o)}static rmsprop(e,t=.9,o=0,n=null,s=!1){return new ip(e,t,o,n,s)}static adam(e=.001,t=.9,o=.999,n=null){return new op(e,t,o,n)}static adadelta(e=.001,t=.95,o=null){return new tp(e,t,o)}static adamax(e=.002,t=.9,o=.999,n=null,s=0){return new np(e,t,o,n,s)}static adagrad(e,t=.1){return new rp(e,t)}};var cl={sgd:$a.sgd,momentum:$a.momentum,adadelta:$a.adadelta,adagrad:$a.adagrad,rmsprop:$a.rmsprop,adamax:$a.adamax,adam:$a.adam};var _U=(()=>typeof requestAnimationFrame!="undefined"?requestAnimationFrame:typeof setImmediate!="undefined"?setImmediate:r=>r())();function rf(){return new Promise(r=>_U(()=>r()))}var N={};Ke(N,{ERF_A1:()=>RU,ERF_A2:()=>FU,ERF_A3:()=>OU,ERF_A4:()=>PU,ERF_A5:()=>MU,ERF_P:()=>$U,PARALLELIZE_THRESHOLD:()=>gg,SELU_SCALE:()=>sk,SELU_SCALEALPHA:()=>nk,applyActivation:()=>ju,assertAndGetBroadcastShape:()=>Be,assertAxesAreInnerMostDims:()=>NW,assertParamsConsistent:()=>vU,assignToTypedArray:()=>UU,axesAreInnerMostDims:()=>Dw,calculateShapes:()=>sN,combineLocations:()=>vN,complexWithEvenIndex:()=>GU,complexWithOddIndex:()=>WU,computeConv2DInfo:()=>wu,computeConv3DInfo:()=>kN,computeDefaultPad:()=>hw,computeDilation2DInfo:()=>ZV,computeOptimalWindowSize:()=>IU,computeOutAndReduceShapes:()=>$w,computeOutShape:()=>CU,computePool2DInfo:()=>fw,computePool3DInfo:()=>JV,convertConv2DDataFormat:()=>wN,eitherStridesOrDilationsAreOne:()=>wr,expandShapeToKeepDim:()=>Bn,exponent:()=>qU,exponents:()=>HU,fromStringArrayToUint8:()=>QU,fromUint8ToStringArray:()=>JU,getAxesPermutation:()=>Rw,getBroadcastDims:()=>GG,getComplexWithIndex:()=>jU,getFusedBiasGradient:()=>Wu,getFusedDyActivation:()=>Gu,getImageCenter:()=>NU,getInnerMostAxes:()=>SW,getPermuted:()=>TU,getReductionAxes:()=>kt,getReshaped:()=>SU,getReshapedPermuted:()=>AU,getSliceBeginCoords:()=>EU,getSliceSize:()=>DU,getUndoAxesPermutation:()=>Mm,log:()=>zU,mergeRealAndImagArrays:()=>BU,prepareAndValidate:()=>nN,prepareSplitSize:()=>KU,segment_util:()=>dS,shouldFuse:()=>Uu,slice_util:()=>nr,splitRealAndImagArrays:()=>VU,tupleValuesAreOne:()=>Lo,upcastType:()=>fr,validateInput:()=>Jh,validateUpdateShape:()=>iw,warn:()=>LU});function vU(r,e){let t=r[0].length;r.forEach((n,s)=>{T(n.length===t,()=>`Error in concat${t}D: rank of tensors[${s}] must be the same as the rank of the rest (${t})`)}),T(e>=0&&e<t,()=>`Error in concat${t}D: axis must be between 0 and ${t-1}.`);let o=r[0];r.forEach((n,s)=>{for(let a=0;a<t;a++)T(a===e||n[a]===o[a],()=>`Error in concat${t}D: Shape of tensors[${s}] (${n}) does not match the shape of the rest (${o}) along the non-concatenated axis ${s}.`)})}function CU(r,e){let t=r[0].slice();for(let o=1;o<r.length;o++)t[e]+=r[o][e];return t}var gg=30;function IU(r){return r<=gg?r:Dc(r,Math.floor(Math.sqrt(r)))}function NU(r,e,t){let o=t*(typeof r=="number"?r:r[0]),n=e*(typeof r=="number"?r:r[1]);return[o,n]}function SU(r,e,t,o=!0){let n=[];if(o)n=n.concat(e.slice(0)),n.push(r[0]/t),n=n.concat(r.slice(1));else{n=n.concat(r[0]);let s=e.length;for(let a=0;a<s;++a)n=n.concat([r[a+1]/e[a],e[a]]);n=n.concat(r.slice(s+1))}return n}function TU(r,e,t=!0){let o=[];if(t){o.push(e);for(let n=e+1;n<r;++n)n<=2*e?(o.push(n),o.push(n-(e+1))):o.push(n)}else{let n=[],s=[];for(let a=1;a<r;++a)a>=e*2+1||a%2==1?s.push(a):n.push(a);o.push(...n),o.push(0),o.push(...s)}return o}function AU(r,e,t,o=!0){let n=[];o?n.push(r[0]/t):n.push(r[0]*t);for(let s=1;s<r.length;++s)s<=e.length?o?n.push(e[s-1]*r[s]):n.push(r[s]/e[s-1]):n.push(r[s]);return n}function EU(r,e){let t=[0];for(let o=0;o<e;++o)t.push(r[o][0]);return t}function DU(r,e,t){let o=r.slice(0,1);for(let n=0;n<t;++n)o.push(r[n+1]-e[n][0]-e[n][1]);return o}var nk=1.7580993408473768,sk=1.0507009873554805;var $U=.3275911,RU=.254829592,FU=-.284496736,OU=1.421413741,PU=-1.453152027,MU=1.061405429;function LU(...r){W().getBool("IS_TEST")||console.warn(...r)}function zU(...r){W().getBool("IS_TEST")||console.log(...r)}function BU(r,e){if(r.length!==e.length)throw new Error(`Cannot merge real and imag arrays of different lengths. real:${r.length}, imag: ${e.length}.`);let t=new Float32Array(r.length*2);for(let o=0;o<t.length;o+=2)t[o]=r[o/2],t[o+1]=e[o/2];return t}function VU(r){let e=new Float32Array(r.length/2),t=new Float32Array(r.length/2);for(let o=0;o<r.length;o+=2)e[o/2]=r[o],t[o/2]=r[o+1];return{real:e,imag:t}}function GU(r){let e=Math.ceil(r.length/4),t=new Float32Array(e),o=new Float32Array(e);for(let n=0;n<r.length;n+=4)t[Math.floor(n/4)]=r[n],o[Math.floor(n/4)]=r[n+1];return{real:t,imag:o}}function WU(r){let e=Math.floor(r.length/4),t=new Float32Array(e),o=new Float32Array(e);for(let n=2;n<r.length;n+=4)t[Math.floor(n/4)]=r[n],o[Math.floor(n/4)]=r[n+1];return{real:t,imag:o}}function jU(r,e){let t=r[e*2],o=r[e*2+1];return{real:t,imag:o}}function UU(r,e,t,o){r[o*2]=e,r[o*2+1]=t}function HU(r,e){let t=new Float32Array(r/2),o=new Float32Array(r/2);for(let n=0;n<Math.ceil(r/2);n++){let s=(e?2:-2)*Math.PI*(n/r);t[n]=Math.cos(s),o[n]=Math.sin(s)}return{real:t,imag:o}}function qU(r,e,t){let o=(t?2:-2)*Math.PI*(r/e),n=Math.cos(o),s=Math.sin(o);return{real:n,imag:s}}function KU(r,e,t=0){let o=[];if(typeof e=="number")T(r.shape[t]%e==0,()=>"Number of splits must evenly divide the axis."),o=new Array(e).fill(r.shape[t]/e);else{let n=e.reduce((a,i)=>(i===-1&&(a+=1),a),0);T(n<=1,()=>"There should be only one negative value in split array.");let s=e.indexOf(-1);if(s!==-1){let a=e.reduce((i,l)=>l>0?i+l:i);e[s]=r.shape[t]-a}T(r.shape[t]===e.reduce((a,i)=>a+i),()=>"The sum of sizes must match the size of the axis dimension."),o=e}return o}var dS={};Ke(dS,{collectGatherOpShapeInfo:()=>ZU,computeOutShape:()=>YU,segOpComputeOptimalWindowSize:()=>XU});function XU(r,e){let t=!1,o;for(r<=gg?(o=r,t=!0):o=Dc(r,Math.floor(Math.sqrt(r)));!t;)o>e||o===r?t=!0:o=Dc(r,o+1);return o}function YU(r,e,t){let o=[],n=r.length;for(let s=0;s<n;s++)s!==e?o.push(r[s]):o.push(t);return o}function ZU(r,e,t,o){let n=e.shape.length,s=r.shape.length;if(o!==0&&(o<-n||o>n))throw new Error(`Expect batchDims in the range of [-${n}, ${n}], but got ${o}`);if(o<0&&(o+=n),o>s)throw new Error(`batchDims (${o}) must be less than rank(x) (
|
|
${s}).`);if(t<o)throw new Error(`batchDims (${o}) must be less than or equal to axis (${t}).`);for(let p=0;p<o;++p)if(r.shape[p]!==e.shape[p])throw new Error(`x.shape[${p}]: ${r.shape[p]} should be equal to indices.shape[${p}]: ${e.shape[p]}.`);let a=r.shape[t],i=[],l=1,u=1,c=1;for(let p=0;p<o;++p)i.push(r.shape[p]),l*=r.shape[p];for(let p=o;p<t;p++)i.push(r.shape[p]),u*=r.shape[p];for(let p=o;p<n;p++)i.push(e.shape[p]);for(let p=t+1;p<s;p++)i.push(r.shape[p]),c*=r.shape[p];return{batchSize:l,sliceSize:c,outerSize:u,dimSize:a,outputShape:i}}function JU(r){try{return r.map(e=>zc(e))}catch(e){throw new Error(`Failed to decode encoded string bytes into utf-8, error: ${e}`)}}function QU(r){return r.map(e=>tl(e))}var Tr={};Ke(Tr,{nonMaxSuppressionV3Impl:()=>ek,nonMaxSuppressionV4Impl:()=>tk,nonMaxSuppressionV5Impl:()=>rk,whereImpl:()=>Kw});function te(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 eH=Tr.whereImpl,Hu=class extends js{constructor(){super();this.blockSize=48,this.firstUse=!0,this.data=new Za(this,Mo())}nextDataId(){return Hu.nextDataId++}write(e,t,o){this.firstUse&&(this.firstUse=!1,W().get("IS_NODE")&&N.warn(`
|
|
============================
|
|
Hi there \u{1F44B}. Looks like you are running TensorFlow.js in Node.js. To speed things up dramatically, install our node backend, which binds to TensorFlow C++, by running npm i @tensorflow/tfjs-node, or npm i @tensorflow/tfjs-node-gpu if you have CUDA. Then call require('@tensorflow/tfjs-node'); (-gpu suffix for CUDA) at the start of your program. Visit https://github.com/tensorflow/tfjs-node for more details.
|
|
============================`));let n={id:this.nextDataId()};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}}refCount(e){return this.data.has(e)?this.data.get(e).refCount:0}incRef(e){let t=this.data.get(e);t.refCount++}decRef(e){if(this.data.has(e)){let t=this.data.get(e);t.refCount--}}move(e,t,o,n,s){this.data.set(e,{values:t,dtype:n,refCount:s})}numDataIds(){return this.data.numDataIds()}async read(e){return this.readSync(e)}readSync(e){let{dtype:t,complexTensorInfos:o}=this.data.get(e);if(t==="complex64"){let n=this.readSync(o.real.dataId),s=this.readSync(o.imag.dataId);return N.mergeRealAndImagArrays(n,s)}return this.data.get(e).values}bufferSync(e){let t=this.readSync(e.dataId),o=t;if(e.dtype==="string")try{o=t.map(n=>x.decodeString(n))}catch(n){throw new Error("Failed to decode encoded string bytes into utf-8")}return ve(e.shape,e.dtype,o)}makeOutput(e,t,o){let n=this.write(e,t,o);return Mo().makeTensorFromDataId(n,t,o,this)}disposeData(e,t=!1){if(this.data.has(e)){if(this.data.get(e).refCount--,!t&&this.data.get(e).refCount>0)return!1;let{complexTensorInfos:o}=this.data.get(e);o!=null&&(this.disposeData(o.real.dataId,!0),this.disposeData(o.imag.dataId,!0)),this.data.delete(e)}return!0}disposeIntermediateTensorInfo(e){this.disposeData(e.dataId)}async time(e){let t=x.now();return e(),{kernelMs:x.now()-t}}memory(){return{unreliable:!0,reasons:["The reported memory is an upper bound. Due to automatic garbage collection, the true allocated memory may be less."]}}where(e){te([e],"where");let t=this.readSync(e.dataId);return eH(e.shape,t)}dispose(){}floatPrecision(){return 32}epsilon(){return super.epsilon()}};Hu.nextDataId=0;var yg={};Ke(yg,{addImpl:()=>kS,bincountImpl:()=>of,bincountReduceImpl:()=>ik,ceilImpl:()=>vS,concatImpl:()=>nf,expImpl:()=>IS,expm1Impl:()=>SS,floorImpl:()=>AS,gatherV2Impl:()=>lk,greaterImpl:()=>DS,lessImpl:()=>RS,linSpaceImpl:()=>uk,logImpl:()=>OS,maxImpl:()=>ck,maximumImpl:()=>MS,minimumImpl:()=>zS,multiplyImpl:()=>xg,negImpl:()=>GS,notEqualImpl:()=>jS,prodImpl:()=>qS,rangeImpl:()=>lf,rsqrtImpl:()=>XS,simpleAbsImpl:()=>hS,sliceImpl:()=>uf,squaredDifferenceImpl:()=>JS,stridedSliceImpl:()=>pk,subImpl:()=>eT,tileImpl:()=>mk,topKImpl:()=>fk,transposeImpl:()=>af,uniqueImpl:()=>dk});function hS(r){let e=new Float32Array(r.length);for(let t=0;t<r.length;++t)e[t]=Math.abs(r[t]);return e}var tH=r=>{let{x:e}=r.inputs,t=r.backend;te(e,"abs");let o=new Float32Array(x.sizeFromShape(e.shape)),n=t.data.get(e.dataId).values;return o=hS(n),t.makeOutput(o,e.shape,"float32")},gS={kernelName:as,backendName:"cpu",kernelFunc:tH};function Xe(r){return(e,t,o,n,s)=>{let a=N.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=N.getBroadcastDims(e,a),g=N.getBroadcastDims(t,a);if(h.length+g.length===0)for(let y=0;y<c.length;++y)c[y]=r(o[y%o.length],n[y%n.length]);else for(let y=0;y<c.length;++y){let b=x.indexToLoc(y,i,l),w=b.slice(-p);h.forEach(A=>w[A]=0);let k=x.locToIndex(w,p,f),v=b.slice(-m);g.forEach(A=>v[A]=0);let D=x.locToIndex(v,m,d);c[y]=r(o[k],n[D])}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 xS={kernelName:Gl,backendName:"cpu",kernelFunc:pr};function ap(r,e,t="float32"){if(t==="complex64"){let n=ap(r,e,"float32"),s=ap(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 yS={kernelName:Fo,backendName:"cpu",kernelFunc:Ar};function jn(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 bS={kernelName:iu,backendName:"cpu",kernelFunc:jn};function Un(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=ap(t,n.shape,n.dtype),i=Un({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=jn({inputs:{input:n},backend:t}),i=Un({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]=Xe((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 wS={kernelName:$o,backendName:"cpu",kernelFunc:Un};function et(r,e,t,o){return t==null?({inputs:n,backend:s})=>{let{a,b:i}=n,l=s;te([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=Un({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=Un({inputs:{x:i},backend:l,attrs:{dtype:"complex64"}}),g=l.data.get(h.dataId),y=g.complexTensorInfos.real,b=g.complexTensorInfos.imag,w=l.data.get(y.dataId).values,k=l.data.get(b.dataId).values,[v,D,A]=t(a.shape,i.shape,f,d,w,k),R=l.makeTensorInfo(A,"float32",v),P=l.makeTensorInfo(A,"float32",D),L=pr({inputs:{real:R,imag:P},backend:l});return l.disposeIntermediateTensorInfo(u),l.disposeIntermediateTensorInfo(h),l.disposeIntermediateTensorInfo(R),l.disposeIntermediateTensorInfo(P),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 lp(r){return(e,t,o,n,s,a)=>{let i=N.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=N.getBroadcastDims(e,i),d=N.getBroadcastDims(t,i),h=N.mergeRealAndImagArrays(o,n),g=N.mergeRealAndImagArrays(s,a),y=e.length,b=x.computeStrides(e),w=t.length,k=x.computeStrides(t);if(f.length+d.length===0)for(let v=0;v<p.length;v++){let D=v%h.length,A=v%g.length,R=r(h[D*2],h[D*2+1],g[A*2],g[A*2+1]);p[v]=R.real,m[v]=R.imag}else for(let v=0;v<p.length;v++){let D=x.indexToLoc(v,u,c),A=D.slice(-y);f.forEach(j=>A[j]=0);let R=x.locToIndex(A,y,b),P=D.slice(-w);d.forEach(j=>P[j]=0);let L=x.locToIndex(P,w,k),G=r(h[R*2],h[R*2+1],g[L*2],g[L*2+1]);p[v]=G.real,m[v]=G.imag}return[p,m,i]}}var kS=Xe((r,e)=>r+e),rH=lp((r,e,t,o)=>({real:r+t,imag:e+o})),Ra=et(wo,kS,rH),_S={kernelName:wo,backendName:"cpu",kernelFunc:Ra};function of(r,e,t,o,n){let s=x.sizeFromShape(o),a=x.makeZerosTypedArray(n,t);for(let i=0;i<r.length;i++){let l=r[i];if(l<0)throw new Error("Input x must be non-negative!");l>=n||(s>0?a[l]+=e[i]:a[l]+=1)}return a}function ik(r,e,t,o=!1){let n=r.shape[0],s=r.shape[1],a=ve([n,t],e.dtype);for(let i=0;i<n;i++)for(let l=0;l<s;l++){let u=r.get(i,l);if(u<0)throw new Error("Input x must be non-negative!");u>=t||(o?a.set(1,i,u):e.size>0?a.set(a.get(i,u)+e.get(i,l),i,u):a.set(a.get(i,u)+1,i,u))}return a}function Hn(r){return(e,t,o)=>{let n=x.getTypedArrayFromDType(t,e.length);for(let s=0;s<e.length;++s)n[s]=r(e[s],o);return n}}function $e(r,e,t){return({inputs:o,attrs:n,backend:s})=>{let{x:a}=o;if(te(a,r),a.dtype==="string"||t==="string")throw new Error("unaryKernelFunc does not support string input/output");let i=s,l=i.data.get(a.dataId).values,u=x.sizeFromShape(a.shape),c=t||a.dtype,p=x.getArrayFromDType(c,u);for(let m=0;m<u;++m)p[m]=e(l[m],n);return i.makeTensorInfo(a.shape,c,p)}}function qn(r,e,t){return({inputs:o,attrs:n,backend:s})=>{let{x:a}=o;if(te(a,r),a.dtype==="string"||t==="string")throw new Error("unaryKernelFunc does not support string input/output");let i=s,l=i.data.get(a.dataId).values,u=t||a.dtype,c=e(l,u,n);return i.makeTensorInfo(a.shape,u,c)}}var vS=Hn(r=>Math.ceil(r)),oH=qn(Yo,vS),CS={kernelName:Yo,backendName:"cpu",kernelFunc:oH};function nf(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"?N.fromUint8ToStringArray(a.vals):a.vals,l=0;for(let u=0;u<a.shape[0];++u){let c=u*e[1]+s;for(let p=0;p<a.shape[1];++p)n[c+p]=i[l++]}s+=a.shape[1]})}return n}var IS=Hn(r=>Math.exp(r)),ak=qn(on,IS),NS={kernelName:on,backendName:"cpu",kernelFunc:ak};var SS=Hn(r=>Math.expm1(r)),nH=qn(ii,SS),TS={kernelName:ii,backendName:"cpu",kernelFunc:nH};var AS=Hn(r=>Math.floor(r)),sH=qn(nn,AS),ES={kernelName:nn,backendName:"cpu",kernelFunc:sH};function lk(r,e,t){let o=ve(t,r.dtype);for(let n=0;n<o.size;++n){let a=o.indexToLoc(n).slice(),i=a[0],l=a[2],u=e.locToIndex([i,l]);a[2]=e.values[u];let c=r.locToIndex(a);o.values[n]=r.values[c]}return o}var DS=Xe((r,e)=>r>e?1:0),iH=et(ui,DS,null,"bool"),$S={kernelName:ui,backendName:"cpu",kernelFunc:iH};var RS=Xe((r,e)=>r<e?1:0),aH=et(fi,RS,null,"bool"),FS={kernelName:fi,backendName:"cpu",kernelFunc:aH};function uk(r,e,t){let o=(e-r)/(t-1),n=x.makeZerosTypedArray(t,"float32");n[0]=r;for(let s=1;s<n.length;s++)n[s]=n[s-1]+o;return n}var OS=Hn(r=>Math.log(r)),lH=qn(cn,OS),PS={kernelName:cn,backendName:"cpu",kernelFunc:lH};function ck(r,e,t,o){let n=x.getTypedArrayFromDType(o,x.sizeFromShape(t));for(let s=0;s<n.length;++s){let a=s*e,i=r[a];for(let l=0;l<e;++l){let u=r[a+l];u>i&&(i=u)}n[s]=i}return n}var MS=Xe((r,e)=>Math.max(r,e)),uH=et(mn,MS),LS={kernelName:mn,backendName:"cpu",kernelFunc:uH};var zS=Xe((r,e)=>Math.min(r,e)),cH=et(gn,zS),BS={kernelName:gn,backendName:"cpu",kernelFunc:cH};var xg=Xe((r,e)=>r*e),pH=lp((r,e,t,o)=>({real:r*t-e*o,imag:r*o+e*t})),sf=et(xn,xg,pH),VS={kernelName:xn,backendName:"cpu",kernelFunc:sf};function GS(r,e,t){let o=x.createScalarValue(-1,t);return xg([],e,o,r,t)}function mH(r){let{inputs:e,backend:t}=r,{x:o}=e;te(o,"neg");let n=t.data.get(o.dataId).values,[s,a]=GS(n,o.shape,o.dtype);return t.makeTensorInfo(a,o.dtype,s)}var WS={kernelName:ps,backendName:"cpu",kernelFunc:mH};var jS=Xe((r,e)=>r!==e?1:0),fH=et(yi,jS,null,"bool"),US={kernelName:yi,backendName:"cpu",kernelFunc:fH};function af(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;c<a;++c){let p=x.indexToLoc(c,s,i),m=new Array(p.length);for(let d=0;d<m.length;d++)m[d]=p[o[d]];let f=x.locToIndex(m,s,l);u[f]=r[c]}return u}function tr(r){let{inputs:e,attrs:t,backend:o}=r,{x:n}=e,{perm:s}=t;te(n,"transpose");let a=n.shape.length,i=new Array(a);for(let p=0;p<i.length;p++)i[p]=n.shape[s[p]];let l=o.data.get(n.dataId).values,u=af(l,n.shape,n.dtype,s,i);return{dataId:o.write(u,i,n.dtype),shape:i,dtype:n.dtype}}var HS={kernelName:Pn,backendName:"cpu",kernelFunc:tr};function qS(r,e,t,o){let[n,s]=N.computeOutAndReduceShapes(r,o),a=fr(e,"int32"),i=x.makeZerosTypedArray(x.sizeFromShape(n),a),l=x.sizeFromShape(s);for(let u=0;u<i.length;++u){let c=u*l,p=1;for(let m=0;m<l;++m)p*=t[c+m];i[u]=p}return{outVals:i,outShape:n,outDtype:a}}function dH(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{axis:s,keepDims:a}=o;te(n,"prod");let i=n.shape.length,l=x.parseAxisParam(s,n.shape),u=N.getAxesPermutation(l,i),c=l,p=n,m=[];u!=null&&(p=tr({inputs:{x:n},backend:t,attrs:{perm:u}}),m.push(p),c=N.getInnerMostAxes(c.length,i));let f=t.data.get(p.dataId).values,{outVals:d,outShape:h,outDtype:g}=qS(p.shape,p.dtype,f,c),y=h;return a&&(y=N.expandShapeToKeepDim(h,l)),m.forEach(b=>t.disposeIntermediateTensorInfo(b)),t.makeTensorInfo(y,g,d)}var KS={kernelName:_i,backendName:"cpu",kernelFunc:dH};function lf(r,e,t,o){let n=r===e,s=r<e&&t<0,a=e<r&&t>1;if(n||s||a)return x.makeZerosTypedArray(0,o);let i=Math.abs(Math.ceil((e-r)/t)),l=x.makeZerosTypedArray(i,o);e<r&&t===1&&(t=-1),l[0]=r;for(let u=1;u<l.length;u++)l[u]=l[u-1]+t;return l}var XS=Hn(r=>1/Math.sqrt(r)),hH=qn(Sn,XS),YS={kernelName:Sn,backendName:"cpu",kernelFunc:hH};function uf(r,e,t,o,n){let s=nr.isSliceContinous(o,e,t),a=x.sizeFromShape(t),i=x.computeStrides(o);if(s){let p=nr.computeFlatOffset(e,i);return n==="string"?r.slice(p,p+a):r.subarray(p,p+a)}let l=n==="string"?N.fromUint8ToStringArray(r):r,u=ve(o,n,l),c=ve(t,n);for(let p=0;p<c.size;++p){let m=c.indexToLoc(p),f=m.map((d,h)=>d+e[h]);c.set(u.get(...f),...m)}return n==="string"?N.fromStringArrayToUint8(c.values):c.values}function Kn(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{begin:s,size:a}=o;te(n,"slice");let[i,l]=nr.parseSliceParams(n,s,a);nr.assertParamsValid(n,i,l);let u=t.data.get(n.dataId).values,c=uf(u,i,l,n.shape,n.dtype);return t.makeTensorInfo(l,n.dtype,c)}var ZS={kernelName:gs,backendName:"cpu",kernelFunc:Kn};var JS=Xe((r,e)=>{let t=r-e;return t*t}),gH=et(Rn,JS),QS={kernelName:Rn,backendName:"cpu",kernelFunc:gH};function pk(r,e,t,o){let n=ve(r,e.dtype);for(let s=0;s<n.size;s++){let a=n.indexToLoc(s),i=new Array(a.length);for(let l=0;l<i.length;l++)i[l]=a[l]*t[l]+o[l];n.set(e.get(...i),...a)}return n}var eT=Xe((r,e)=>r-e),xH=lp((r,e,t,o)=>({real:r-t,imag:e-o})),cf=et(Fn,eT,xH),tT={kernelName:Fn,backendName:"cpu",kernelFunc:cf};function mk(r,e){let t=new Array(r.rank);for(let n=0;n<t.length;n++)t[n]=r.shape[n]*e[n];let o=ve(t,r.dtype);for(let n=0;n<o.values.length;++n){let s=o.indexToLoc(n),a=new Array(r.rank);for(let l=0;l<a.length;l++)a[l]=s[l]%r.shape[l];let i=r.locToIndex(a);o.values[n]=r.values[i]}return o}function fk(r,e,t,o,n){let s=e[e.length-1],[a,i]=[r.length/s,s],l=x.getTypedArrayFromDType(t,a*o),u=x.getTypedArrayFromDType("int32",a*o);for(let p=0;p<a;p++){let m=p*i,f=r.subarray(m,m+i),d=[];for(let b=0;b<f.length;b++)d.push({value:f[b],index:b});d.sort((b,w)=>w.value-b.value);let h=p*o,g=l.subarray(h,h+o),y=u.subarray(h,h+o);for(let b=0;b<o;b++)g[b]=d[b].value,y[b]=d[b].index}let c=e.slice();return c[c.length-1]=o,[ve(c,t,l),ve(c,"int32",u)]}function dk(r,e,t,o){let n=x.parseAxisParam(e,t)[0],s=[1,t[0],1];for(let d=0;d<n;d++)s[0]*=t[d];s[1]=t[n];for(let d=n+1;d<t.length;d++)s[2]*=t[d];let a={},i=new Int32Array(t[n]),l=new lt(s,o,r),u=[],c=s[0]===1&&s[2]===1;for(let d=0;d<t[n];d++){let h;if(c)h=r[d].toString();else{let g=[];for(let y=0;y<s[0];y++)for(let b=0;b<s[2];b++)g.push(l.get(y,d,b));h=g.join(",")}if(a[h]!==void 0)i[d]=a[h];else{let g=Object.keys(a).length;a[h]=g,i[d]=g,u.push(d)}}let p=s.slice();p[1]=Object.keys(a).length;let m=new lt(p,o);u.forEach((d,h)=>{for(let g=0;g<s[0];g++)for(let y=0;y<s[2];y++)m.set(l.get(g,d,y),g,h,y)});let f=t.slice();return f[n]=p[1],{outputValues:m.values,outputShape:f,indices:i}}var hk="3.3.0";xu("cpu",()=>new Hu,1);var gk=$e(oi,r=>r>=0?r:Math.exp(r)-1),rT={kernelName:oi,backendName:"cpu",kernelFunc:gk};function xk(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{alpha:s}=o;te([n],"leakyRelu");let a=x.sizeFromShape(n.shape),i=t.data.get(n.dataId).values,l=x.getTypedArrayFromDType("float32",a);for(let u=0;u<i.length;u++)l[u]=i[u]<0?s*i[u]:i[u];return t.makeTensorInfo(n.shape,"float32",l)}var oT={kernelName:un,backendName:"cpu",kernelFunc:xk};var yH=Xe((r,e)=>r<0?e*r:r);function yk(r){let{inputs:e,backend:t}=r,{x:o,alpha:n}=e;te([o,n],"prelu");let s=t.data.get(o.dataId).values,a=t.data.get(n.dataId).values,[i,l]=yH(o.shape,n.shape,s,a,o.dtype);return t.makeTensorInfo(l,o.dtype,i)}var nT={kernelName:kn,backendName:"cpu",kernelFunc:yk};var bk=$e(_n,r=>Math.max(0,r)),sT={kernelName:_n,backendName:"cpu",kernelFunc:bk};var wk=$e(Cn,r=>Math.min(Math.max(0,r),6)),iT={kernelName:Cn,backendName:"cpu",kernelFunc:wk};function up(r,e,t,o,n){if(t==="linear")return Ar({inputs:{x:e},backend:r});if(t==="relu")return bk({inputs:{x:e},backend:r});if(t==="elu")return gk({inputs:{x:e},backend:r});if(t==="relu6")return wk({inputs:{x:e},backend:r});if(t==="prelu")return yk({inputs:{x:e,alpha:o},backend:r});if(t==="leakyrelu")return xk({inputs:{x:e},backend:r,attrs:{alpha:n}});throw new Error(`Activation ${t} has not been implemented for the CPU backend.`)}function Qe(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 aT={kernelName:ds,backendName:"cpu",kernelFunc:Qe};function kk(r){let{inputs:e,backend:t,attrs:o}=r,{a:n,b:s}=e,{transposeA:a,transposeB:i}=o;te([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 k=(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 v=a?[g,c,m]:[g,m,c],D=i?[y,f,p]:[y,p,f],A=Qe({inputs:{x:n},backend:t,attrs:{shape:v}}),R=Qe({inputs:{x:s},backend:t,attrs:{shape:D}}),P=a?A.shape[1]:A.shape[2],L=a?A.shape[2]:A.shape[1],G=i?R.shape[1]:R.shape[2],j=Math.max(g,y),U=t.data.get(A.dataId).values,H=t.data.get(R.dataId).values,q=x.computeStrides(A.shape),X=x.computeStrides(R.shape),[oe,Y,re]=a?[q[0],1,q[1]]:[q[0],q[1],1],[J,ie,ue]=i?[1,X[1],X[0]]:[X[1],1,X[0]],ae=L*G,fe=ve([j,L,G],A.dtype),de=fe.values,xe=t.blockSize;for(let we=0;we<j;we++)for(let De=0;De<L;De+=xe)for(let Ne=0;Ne<G;Ne+=xe)for(let ze=0;ze<P;ze+=xe){let qe=Math.min(De+xe,L),it=Math.min(Ne+xe,G),Tt=Math.min(ze+xe,P);for(let At=De;At<qe;At++)for(let je=Ne;je<it;je++){let ut=0;for(let mt=ze;mt<Tt;mt++){let Pt=Math.min(we,g-1)*oe,xo=Math.min(we,y-1)*ue,Kt=U[Pt+At*Y+mt*re],to=H[mt*J+je*ie+xo];ut+=Kt*to}de[we*ae+(At*G+je)]+=ut}}return t.disposeIntermediateTensorInfo(A),t.disposeIntermediateTensorInfo(R),t.makeTensorInfo(k,fe.dtype,fe.values)}var lT={kernelName:Xo,backendName:"cpu",kernelFunc:kk};function bH(r){let{inputs:e,backend:t,attrs:o}=r,{a:n,b:s,bias:a,preluActivationWeights:i}=e,{transposeA:l,transposeB:u,activation:c,leakyreluAlpha:p}=o,m,f,d,h=[];m=kk({inputs:{a:n,b:s},attrs:{transposeA:l,transposeB:u},backend:t}),a&&(f=Ra({inputs:{a:m,b:a},backend:t}),h.push(m),m=f),c&&(d=up(t,m,c,i,p),h.push(m),m=d);for(let y of h)t.disposeIntermediateTensorInfo(y);return m}var uT={kernelName:ws,backendName:"cpu",kernelFunc:bH};var wH=$e(qs,r=>Math.acos(r)),cT={kernelName:qs,backendName:"cpu",kernelFunc:wH};var kH=$e(Ks,r=>Math.acosh(r)),pT={kernelName:Ks,backendName:"cpu",kernelFunc:kH};function _H(r){let{inputs:e,backend:t}=r,o=e;te(e,"addN");let n=o.map(i=>t.data.get(i.dataId).values),s=ve(o[0].shape,o[0].dtype),a=s.values;for(let i=0;i<o.length;i++){let l=n[i];for(let u=0;u<a.length;u++)a[u]+=l[u]}return t.makeTensorInfo(s.shape,s.dtype,s.values)}var mT={kernelName:Ho,backendName:"cpu",kernelFunc:_H};function vH(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{axis:s,keepDims:a}=o;te(n,"all");let i=x.parseAxisParam(s,n.shape),l=i,u=N.getAxesPermutation(l,n.shape.length),c=n;u!=null&&(c=tr({inputs:{x:n},backend:t,attrs:{perm:u}}),l=N.getInnerMostAxes(l.length,n.shape.length)),N.assertAxesAreInnerMostDims("all",l,c.shape.length);let[p,m]=N.computeOutAndReduceShapes(c.shape,l),f=x.sizeFromShape(m),d=x.makeZerosTypedArray(x.sizeFromShape(p),c.dtype),h=t.data.get(c.dataId).values;for(let y=0;y<d.length;++y){let b=y*f,w=h[b];for(let k=0;k<f;++k){let v=h[b+k];w=w&&v}d[y]=w}u!=null&&t.disposeIntermediateTensorInfo(c);let g=t.makeTensorInfo(p,c.dtype,d);if(a){let y=N.expandShapeToKeepDim(p,i),b=Qe({inputs:{x:g},backend:t,attrs:{shape:y}});return t.disposeIntermediateTensorInfo(g),b}return g}var fT={kernelName:Ml,backendName:"cpu",kernelFunc:vH};function CH(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{axis:s,keepDims:a}=o;te(n,"any");let i=x.parseAxisParam(s,n.shape),l=i,u=N.getAxesPermutation(l,n.shape.length),c=n;u!=null&&(c=tr({inputs:{x:n},backend:t,attrs:{perm:u}}),l=N.getInnerMostAxes(l.length,n.shape.length)),N.assertAxesAreInnerMostDims("any",l,c.shape.length);let[p,m]=N.computeOutAndReduceShapes(c.shape,l),f=x.sizeFromShape(m),d=x.makeZerosTypedArray(x.sizeFromShape(p),c.dtype),h=t.data.get(c.dataId).values;for(let y=0;y<d.length;++y){let b=y*f,w=h[b];for(let k=0;k<f;++k){let v=h[b+k];w=w||v}d[y]=w}u!=null&&t.disposeIntermediateTensorInfo(c);let g=t.makeTensorInfo(p,c.dtype,d);if(a){let y=N.expandShapeToKeepDim(p,i),b=Qe({inputs:{x:g},backend:t,attrs:{shape:y}});return t.disposeIntermediateTensorInfo(g),b}return g}var dT={kernelName:Ll,backendName:"cpu",kernelFunc:CH};function IH(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{axis:s}=o;te(n,"argMax");let a=x.parseAxisParam(s,n.shape),i=N.getAxesPermutation(a,n.shape.length),l=n,u=[];i!=null&&(l=tr({inputs:{x:n},backend:t,attrs:{perm:i}}),u.push(l),a=N.getInnerMostAxes(a.length,l.shape.length)),a=[a[0]],N.assertAxesAreInnerMostDims("argMax",a,l.shape.length);let[c,p]=N.computeOutAndReduceShapes(l.shape,a),m=x.sizeFromShape(c),f=x.makeZerosTypedArray(m,"int32"),d=x.sizeFromShape(p),h=t.data.get(l.dataId).values;for(let g=0;g<f.length;++g){let y=g*d,b=h[y],w=0;for(let k=0;k<d;++k){let v=h[y+k];v>b&&(b=v,w=k)}f[g]=w}return u.forEach(g=>t.disposeIntermediateTensorInfo(g)),t.makeTensorInfo(c,"int32",f)}var hT={kernelName:qo,backendName:"cpu",kernelFunc:IH};function NH(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{axis:s}=o;te(n,"argMin");let a=x.parseAxisParam(s,n.shape),i=N.getAxesPermutation(a,n.shape.length),l=n,u=[];i!=null&&(l=tr({inputs:{x:n},backend:t,attrs:{perm:i}}),u.push(l),a=N.getInnerMostAxes(a.length,l.shape.length)),a=[a[0]],N.assertAxesAreInnerMostDims("argMin",a,l.shape.length);let[c,p]=N.computeOutAndReduceShapes(l.shape,a),m=x.sizeFromShape(c),f=x.makeZerosTypedArray(m,"int32"),d=x.sizeFromShape(p),h=t.data.get(l.dataId).values;for(let g=0;g<f.length;++g){let y=g*d,b=h[y],w=0;for(let k=0;k<d;++k){let v=h[y+k];v<b&&(b=v,w=k)}f[g]=w}return u.forEach(g=>t.disposeIntermediateTensorInfo(g)),t.makeTensorInfo(c,"int32",f)}var gT={kernelName:ea,backendName:"cpu",kernelFunc:NH};var SH=$e(Xs,r=>Math.asin(r)),xT={kernelName:Xs,backendName:"cpu",kernelFunc:SH};var TH=$e(Ys,r=>Math.asinh(r)),yT={kernelName:Ys,backendName:"cpu",kernelFunc:TH};var AH=$e(Zs,r=>Math.atan(r)),bT={kernelName:Zs,backendName:"cpu",kernelFunc:AH};var EH=Xe((r,e)=>Math.atan2(r,e)),DH=et(Qs,EH),wT={kernelName:Qs,backendName:"cpu",kernelFunc:DH};var $H=$e(Js,r=>Math.atanh(r)),kT={kernelName:Js,backendName:"cpu",kernelFunc:$H};function cp(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=ve(n.outShape,t),g=h.values,y=n.outShape[1]*n.outShape[2]*n.outShape[3],b=n.outShape[2]*n.outShape[3],w=n.outShape[3];for(let k=0;k<n.batchSize;++k){let v=k*y,D=k*o[0];for(let A=0;A<n.inChannels;++A)for(let R=0;R<n.outHeight;++R){let P=R*a-m,L=Math.max(0,P),G=Math.min(n.inHeight,c+P),j=v+R*b;for(let U=0;U<n.outWidth;++U){let H=U*i-f,q=Math.max(0,H),X=Math.min(n.inWidth,p+H),oe=d,Y=0,re=0;for(let ie=L;ie<G;ie+=l){let ue=D+ie*o[1];for(let ae=q;ae<X;ae+=u){let fe=ue+ae*o[2],de=r[fe+A];s==="max"&&de>oe?oe=de:s==="avg"&&(Y+=de,re++)}if(isNaN(oe))break}let J=j+U*w+A;g[J]=s==="avg"?Y/re:oe}}}return h}function bg(r,e,t,o,n=!1,s=!1){let a=ve(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=ve(e,t,r);for(let g=0;g<o.batchSize;++g)for(let y=0;y<o.inChannels;++y)for(let b=0;b<o.outHeight;++b){let w=b*i-f,k=w;for(;k<0;)k+=u;let v=Math.min(o.inHeight,p+w);for(let D=0;D<o.outWidth;++D){let A=D*l-d,R=A;for(;R<0;)R+=c;let P=Math.min(o.inWidth,m+A),L=Number.NEGATIVE_INFINITY,G=-1;for(let j=k;j<v;j+=u){let U=j-w;for(let H=R;H<P;H+=c){let q=H-A,X=h.get(g,j,H,y);X>L&&(L=X,n?G=s?((g*o.inHeight+j)*o.inWidth+H)*o.inChannels+y:(j*o.inWidth+H)*o.inChannels+y:G=U*m+q)}}a.set(G,g,b,D,y)}}return a}function wg(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,w=ve(n.outShape,t),k=w.values,v=n.outShape[1]*n.outShape[2]*n.outShape[3]*n.outShape[4],D=n.outShape[2]*n.outShape[3]*n.outShape[4],A=n.outShape[3]*n.outShape[4],R=n.outShape[4];for(let P=0;P<n.batchSize;++P){let L=P*v,G=P*o[0];for(let j=0;j<n.inChannels;++j)for(let U=0;U<n.outDepth;++U){let H=U*a-h,q=H;for(;q<0;)q+=u;let X=Math.min(n.inDepth,m+H),oe=L+U*D;for(let Y=0;Y<n.outHeight;++Y){let re=Y*i-g,J=re;for(;J<0;)J+=c;let ie=Math.min(n.inHeight,f+re),ue=oe+Y*A;for(let ae=0;ae<n.outWidth;++ae){let fe=ae*l-y,de=fe;for(;de<0;)de+=p;let xe=Math.min(n.inWidth,d+fe),we=ue+ae*R,De=b,Ne=0,ze=0;for(let it=q;it<X;it+=u){let Tt=G+it*o[1];for(let At=J;At<ie;At+=c){let je=Tt+At*o[2];for(let ut=de;ut<xe;ut+=p){let mt=je+ut*o[3],Pt=r[mt+j];if(s==="max"&&Pt>De?De=Pt:s==="avg"&&(Ne+=Pt,ze++),isNaN(De))break}if(isNaN(De))break}if(isNaN(De))break}let qe=we+j;k[qe]=s==="avg"?Ne/ze:De}}}}return w}function _T(r,e){let t=ve(e.outShape,"int32"),o=e.strideDepth,n=e.strideHeight,s=e.strideWidth,a=e.dilationDepth,i=e.dilationHeight,l=e.dilationWidth,u=e.effectiveFilterDepth,c=e.effectiveFilterHeight,p=e.effectiveFilterWidth,m=e.padInfo.front,f=e.padInfo.top,d=e.padInfo.left;for(let h=0;h<e.batchSize;++h)for(let g=0;g<e.inChannels;++g)for(let y=0;y<e.outDepth;++y){let b=y*o-m,w=b;for(;w<0;)w+=a;let k=Math.min(e.inDepth,u+b);for(let v=0;v<e.outHeight;++v){let D=v*n-f,A=D;for(;A<0;)A+=i;let R=Math.min(e.inHeight,c+D);for(let P=0;P<e.outWidth;++P){let L=P*s-d,G=L;for(;G<0;)G+=l;let j=Math.min(e.inWidth,p+L),U=Number.NEGATIVE_INFINITY,H=-1;for(let q=w;q<k;q+=a){let X=q-b;for(let oe=A;oe<R;oe+=i){let Y=oe-D;for(let re=G;re<j;re+=l){let J=re-L,ie=r.get(h,q,oe,re,g);ie>=U&&(U=ie,H=X*c*p+Y*c+J)}}}t.set(H,h,y,v,P,g)}}}return t}function RH(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e;te(n,"avgPool");let{filterSize:s,strides:a,pad:i,dimRoundingMode:l}=o,u=1;x.assert(N.eitherStridesOrDilationsAreOne(a,u),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${u}'`);let c=N.computePool2DInfo(n.shape,s,a,u,i,l),p;if(c.filterWidth===1&&c.filterHeight===1&&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=cp(m,n.shape,n.dtype,f,c,"avg");p=t.makeTensorInfo(c.outShape,n.dtype,d.values)}return p}var vT={kernelName:Ko,backendName:"cpu",kernelFunc:RH};function FH(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{filterSize:s,strides:a,pad:i,dimRoundingMode:l,dataFormat:u}=o;te(n,"avgPool3d");let c=N.computePool3DInfo(n.shape,s,a,1,i,l,u),p=t.data.get(n.dataId).values,m=wg(p,n.shape,n.dtype,x.computeStrides(n.shape),c,"avg");return t.makeTensorInfo(m.shape,"float32",m.values)}var CT={kernelName:ta,backendName:"cpu",kernelFunc:FH};function OH(r){let{inputs:e,backend:t,attrs:o}=r,{dy:n,input:s}=e,{filterSize:a,strides:i,pad:l,dimRoundingMode:u}=o;te([n,s],"avgPool3DGrad");let c=N.computePool3DInfo(s.shape,a,i,1,l,u),p=c.strideDepth,m=c.strideHeight,f=c.strideWidth,d=c.filterDepth,h=c.filterHeight,g=c.filterWidth,y=c.dilationDepth,b=c.dilationHeight,w=c.dilationWidth,k=c.effectiveFilterDepth,v=c.effectiveFilterHeight,D=c.effectiveFilterWidth,A=k-1-c.padInfo.front,R=D-1-c.padInfo.left,P=v-1-c.padInfo.top,L=ve(s.shape,"float32"),G=1/(d*h*g),j=t.bufferSync(n);for(let U=0;U<c.batchSize;++U)for(let H=0;H<c.inChannels;++H)for(let q=0;q<c.inDepth;++q)for(let X=0;X<c.inHeight;++X)for(let oe=0;oe<c.inWidth;++oe){let Y=q-A,re=X-P,J=oe-R,ie=0;for(let ue=0;ue<k;ue+=y){let ae=(Y+ue)/p;if(!(ae<0||ae>=c.outDepth||Math.floor(ae)!==ae))for(let fe=0;fe<v;fe+=b){let de=(re+fe)/m;if(!(de<0||de>=c.outHeight||Math.floor(de)!==de))for(let xe=0;xe<D;xe+=w){let we=(J+xe)/f;if(we<0||we>=c.outWidth||Math.floor(we)!==we)continue;ie+=j.get(U,ae,de,we,H)}}}L.set(ie*G,U,q,X,oe,H)}return t.makeTensorInfo(L.shape,L.dtype,L.values)}var IT={kernelName:Bl,backendName:"cpu",kernelFunc:OH};function PH(r){let{inputs:e,backend:t,attrs:o}=r,{dy:n,input:s}=e,a=s;te([n,s],"avgPoolGrad");let{filterSize:i,strides:l,pad:u}=o,c=N.computePool2DInfo(a.shape,i,l,1,u),p=c.strideHeight,m=c.strideWidth,f=c.filterHeight,d=c.filterWidth,h=c.dilationHeight,g=c.dilationWidth,y=c.effectiveFilterHeight,b=c.effectiveFilterWidth,w=b-1-c.padInfo.left,k=y-1-c.padInfo.top,v=ve(a.shape,"float32"),D=1/(f*d),A=t.data.get(n.dataId).values,R=ve(n.shape,"float32",A);for(let P=0;P<c.batchSize;++P)for(let L=0;L<c.inChannels;++L)for(let G=0;G<c.inHeight;++G)for(let j=0;j<c.inWidth;++j){let U=G-k,H=j-w,q=0;for(let X=0;X<y;X+=h){let oe=(U+X)/p;if(!(oe<0||oe>=c.outHeight||Math.floor(oe)!==oe))for(let Y=0;Y<b;Y+=g){let re=(H+Y)/m;if(re<0||re>=c.outWidth||Math.floor(re)!==re)continue;q+=R.get(P,oe,re,L)}}v.set(q*D,P,G,j,L)}return t.makeTensorInfo(v.shape,v.dtype,v.values)}var NT={kernelName:zl,backendName:"cpu",kernelFunc:PH};function MH(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."),te([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,w=p.length,k=0,v=0,D=0,A=0;for(let R=0;R<c.length;++R)h[R]=d[k++]+(c[R]-p[v++])*f[D++]/Math.sqrt(m[A++]+u),k>=g&&(k=0),v>=w&&(v=0),D>=y&&(D=0),A>=b&&(A=0);return t.makeTensorInfo(n.shape,n.dtype,h)}var ST={kernelName:an,backendName:"cpu",kernelFunc:MH};function LH(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{blockShape:s,crops:a}=o;te([n],"batchToSpaceND");let i=s.reduce((y,b)=>y*b),l=N.getReshaped(n.shape,s,i),u=N.getPermuted(l.length,s.length),c=N.getReshapedPermuted(n.shape,s,i),p=N.getSliceBeginCoords(a,s.length),m=N.getSliceSize(c,a,s.length),f=Qe({inputs:{x:n},backend:t,attrs:{shape:l}}),d=tr({inputs:{x:f},backend:t,attrs:{perm:u}}),h=Qe({inputs:{x:d},backend:t,attrs:{shape:c}}),g=Kn({inputs:{x:h},backend:t,attrs:{begin:p,size:m}});return t.disposeIntermediateTensorInfo(f),t.disposeIntermediateTensorInfo(d),t.disposeIntermediateTensorInfo(h),g}var TT={kernelName:ra,backendName:"cpu",kernelFunc:LH};function zH(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=of(i,l,s.dtype,s.shape,a);return t.makeTensorInfo([a],s.dtype,u)}var AT={kernelName:Vl,backendName:"cpu",kernelFunc:zH};var BH=$e(Ro,(r,e)=>{let t=e;return r>t.clipValueMax?t.clipValueMax:r<t.clipValueMin?t.clipValueMin:r}),ET={kernelName:Ro,backendName:"cpu",kernelFunc:BH};var VH=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;u<i.length;u++){let c=i[u],p=l[u];o[u]=Math.hypot(c,p)}return t.makeOutput(o,e.shape,"float32")},DT={kernelName:oa,backendName:"cpu",kernelFunc:VH};function zi(r){let{inputs:e,backend:t}=r,{input:o}=e,n=t.data.get(o.dataId).complexTensorInfos.imag,s=t.data.get(n.dataId).values;return t.makeTensorInfo(n.shape,n.dtype,s)}var $T={kernelName:Ql,backendName:"cpu",kernelFunc:zi};function pl(r){let{inputs:e,backend:t,attrs:o}=r,{axis:n}=o,s=x.parseAxisParam(n,e[0].shape)[0],a=N.computeOutShape(e.map(h=>h.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(N.assertParamsConsistent(l,s),i[0].dtype==="complex64"){let h=i.map(k=>jn({inputs:{input:k},backend:t})),g=i.map(k=>zi({inputs:{input:k},backend:t})),y=pl({inputs:h,backend:t,attrs:{axis:s}}),b=pl({inputs:g,backend:t,attrs:{axis:s}}),w=pr({inputs:{real:y,imag:b},backend:t});return h.forEach(k=>t.disposeIntermediateTensorInfo(k)),g.forEach(k=>t.disposeIntermediateTensorInfo(k)),t.disposeIntermediateTensorInfo(y),t.disposeIntermediateTensorInfo(b),w}let u=i.map(h=>{let g=x.sizeFromShape(h.shape.slice(s));return Qe({inputs:{x:h},backend:t,attrs:{shape:[-1,g]}})}),c=u.map(h=>({vals:t.data.get(h.dataId).values,shape:h.shape}));a=N.computeOutShape(u.map(h=>h.shape),1);let p=u[0].shape[0]===1,m=nf(c,a,e[0].dtype,p),f=N.computeOutShape(i.map(h=>h.shape),s),d=t.makeTensorInfo(f,e[0].dtype,m);return u.forEach(h=>t.disposeIntermediateTensorInfo(h)),d}var RT={kernelName:ls,backendName:"cpu",kernelFunc:pl};function _k(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;te([n,s],"conv2d");let p=N.convertConv2DDataFormat(l),m=N.computeConv2DInfo(n.shape,s.shape,a,u,i,c,!1,p),f=m.filterHeight,d=m.filterWidth,h=m.dilationHeight,g=m.dilationWidth,y=m.padInfo.left,b=m.padInfo.top,w=m.dataFormat==="channelsLast",k=new lt(m.outShape,n.dtype),v=x.computeStrides(n.shape),D=x.computeStrides(s.shape),A=v[0],R=w?v[1]:v[2],P=w?v[2]:1,L=w?1:v[1],G=k.strides[0],j=w?k.strides[1]:k.strides[2],U=w?k.strides[2]:1,H=w?1:k.strides[1],q=t.data.get(n.dataId).values,X=t.data.get(s.dataId).values,oe=k.values;for(let Y=0;Y<m.batchSize;++Y){let re=Y*A,J=Y*G;for(let ie=0;ie<m.outHeight;++ie){let ue=J+ie*j,ae=ie*m.strideHeight-b;for(let fe=0;fe<f;++fe){let de=ae+fe*h;if(de<0||de>=m.inHeight)continue;let xe=fe*D[0],we=re+de*R;for(let De=0;De<m.outWidth;++De){let Ne=ue+De*U,ze=De*m.strideWidth-y;for(let qe=0;qe<d;++qe){let it=ze+qe*g;if(it<0||it>=m.inWidth)continue;let Tt=xe+qe*D[1],At=we+it*P,je=Tt;for(let ut=0;ut<m.inChannels;++ut){let mt=q[At+ut*L];for(let Pt=0;Pt<m.outChannels;++Pt)oe[Ne+Pt*H]+=mt*X[je+Pt];je+=m.outChannels}}}}}}return t.makeTensorInfo(k.shape,k.dtype,oe)}var FT={kernelName:Zo,backendName:"cpu",kernelFunc:_k};function GH(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;te([n,s],"conv2dBackpropFilter");let p=N.convertConv2DDataFormat(l),m=N.computeConv2DInfo(n.shape,c,a,1,i,u,!1,p),{strideHeight:f,strideWidth:d,filterHeight:h,filterWidth:g}=m,y=m.dataFormat==="channelsLast",b=new lt(m.filterShape,"float32"),w=m.padInfo.left,k=m.padInfo.top,v=t.data.get(n.dataId).values,D=t.data.get(s.dataId).values,A=new lt(n.shape,n.dtype,v),R=new lt(s.shape,s.dtype,D);for(let P=0;P<h;++P){let L=Math.max(0,Math.ceil((k-P)/f)),G=Math.min(m.outHeight,(m.inHeight+k-P)/f);for(let j=0;j<g;++j){let U=Math.max(0,Math.ceil((w-j)/d)),H=Math.min(m.outWidth,(m.inWidth+w-j)/d);for(let q=0;q<m.inChannels;++q)for(let X=0;X<m.outChannels;++X){let oe=0;for(let Y=0;Y<m.batchSize;++Y)for(let re=L;re<G;++re){let J=P+re*f-k;for(let ie=U;ie<H;++ie){let ue=j+ie*d-w;y?oe+=A.get(Y,J,ue,q)*R.get(Y,re,ie,X):oe+=A.get(Y,q,J,ue)*R.get(Y,X,re,ie)}}b.set(oe,P,j,q,X)}}}return t.makeTensorInfo(b.shape,b.dtype,b.values)}var OT={kernelName:Wl,backendName:"cpu",kernelFunc:GH};function WH(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;te([n,s],"conv2dBackpropInput");let p=x.computeStrides(s.shape),m=x.computeStrides(n.shape),f=N.convertConv2DDataFormat(u),d=N.computeConv2DInfo(a,s.shape,i,1,l,c,!1,f),h=new lt(d.inShape,"float32"),g=h.values,y=t.data.get(n.dataId).values,b=t.data.get(s.dataId).values,[w,k,v]=p,{batchSize:D,filterHeight:A,filterWidth:R,inChannels:P,inHeight:L,inWidth:G,outChannels:j,outHeight:U,outWidth:H,strideHeight:q,strideWidth:X}=d;f=d.dataFormat;let oe=A-1-d.padInfo.top,Y=R-1-d.padInfo.left,re=f==="channelsLast",J=h.strides[0],ie=re?h.strides[1]:h.strides[2],ue=re?h.strides[2]:1,ae=re?1:h.strides[1],fe=m[0],de=re?m[1]:m[2],xe=re?m[2]:1,we=re?1:m[1];for(let De=0;De<D;++De)for(let Ne=0;Ne<P;++Ne)for(let ze=0;ze<L;++ze){let qe=ze-oe,it=Math.max(0,Math.ceil(qe/q)),Tt=Math.min(U,(A+qe)/q);for(let At=0;At<G;++At){let je=At-Y,ut=Math.max(0,Math.ceil(je/X)),mt=Math.min(H,(R+je)/X),Pt=0;for(let Kt=it;Kt<Tt;++Kt){let to=Kt*q-qe;for(let Dr=ut;Dr<mt;++Dr){let jo=Dr*X-je,rr=fe*De+de*Kt+xe*Dr,yo=w*(A-1-to)+k*(R-1-jo)+v*Ne;for(let Vr=0;Vr<j;++Vr){let yr=y[rr+we*Vr],ro=b[yo+Vr];Pt+=yr*ro}}}let xo=J*De+ie*ze+ue*At+ae*Ne;g[xo]=Pt}}return t.makeTensorInfo(h.shape,h.dtype,h.values)}var PT={kernelName:Jo,backendName:"cpu",kernelFunc:WH};function jH(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,filter:s}=e,{strides:a,pad:i,dilations:l}=o;te([n,s],"conv3d");let u=N.computeConv3DInfo(n.shape,s.shape,a,l,i),{filterDepth:c,filterHeight:p,filterWidth:m,dilationDepth:f,dilationHeight:d,dilationWidth:h,padInfo:g}=u,y=g.front,b=g.left,w=g.top,k=new lt(u.outShape,n.dtype),v=t.data.get(n.dataId).values,D=t.data.get(s.dataId).values,A=k.values,R=x.computeStrides(n.shape),P=x.computeStrides(s.shape);for(let L=0;L<u.batchSize;++L){let G=L*R[0],j=L*k.strides[0];for(let U=0;U<u.outDepth;++U){let H=j+U*k.strides[1],q=U*u.strideDepth-y;for(let X=0;X<c;++X){let oe=q+X*f;if(oe<0||oe>=u.inDepth)continue;let Y=X*P[0],re=G+oe*R[1];for(let J=0;J<u.outHeight;++J){let ie=H+J*k.strides[2],ue=J*u.strideHeight-w;for(let ae=0;ae<p;++ae){let fe=ue+ae*d;if(fe<0||fe>=u.inHeight)continue;let de=Y+ae*P[1],xe=re+fe*R[2];for(let we=0;we<u.outWidth;++we){let De=ie+we*u.outChannels,Ne=we*u.strideWidth-b;for(let ze=0;ze<m;++ze){let qe=Ne+ze*h;if(qe<0||qe>=u.inWidth)continue;let it=de+ze*P[2],Tt=xe+qe*u.inChannels,At=it;for(let je=0;je<u.inChannels;++je){let ut=v[Tt+je];for(let mt=0;mt<u.outChannels;++mt)A[De+mt]+=ut*D[At+mt];At+=u.outChannels}}}}}}}}return t.makeTensorInfo(k.shape,k.dtype,k.values)}var MT={kernelName:na,backendName:"cpu",kernelFunc:jH};function UH(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,dy:s}=e,{strides:a,pad:i,filterShape:l}=o;te([n,s],"conv3dBackpropFilterV2");let u=x.computeStrides(n.shape),c=x.computeStrides(s.shape),p=N.computeConv3DInfo(n.shape,l,a,1,i),m=p.strideDepth,f=p.strideHeight,d=p.strideWidth,h=p.filterDepth,g=p.filterHeight,y=p.filterWidth,b=new lt(p.filterShape,"float32"),w=b.values,[k,v,D,A]=b.strides,R=t.data.get(s.dataId).values,[P,L,G,j]=c,U=t.data.get(n.dataId).values,[H,q,X,oe]=u,Y=p.padInfo.front,re=p.padInfo.left,J=p.padInfo.top;for(let ie=0;ie<h;++ie){let ue=Math.max(0,Math.ceil((Y-ie)/m)),ae=Math.min(p.outDepth,(p.inDepth+Y-ie)/m),fe=ie*k;for(let de=0;de<g;++de){let xe=Math.max(0,Math.ceil((J-de)/f)),we=Math.min(p.outHeight,(p.inHeight+J-de)/f),De=de*v+fe;for(let Ne=0;Ne<y;++Ne){let ze=Math.max(0,Math.ceil((re-Ne)/d)),qe=Math.min(p.outWidth,(p.inWidth+re-Ne)/d),it=Ne*D+De;for(let Tt=0;Tt<p.inChannels;++Tt){let At=Tt*A+it;for(let je=0;je<p.outChannels;++je){let ut=0;for(let mt=0;mt<p.batchSize;++mt){let Pt=mt*H,xo=mt*P;for(let Kt=ue;Kt<ae;++Kt){let Dr=(ie+Kt*m-Y)*q+Pt,jo=Kt*L+xo;for(let rr=xe;rr<we;++rr){let Vr=(de+rr*f-J)*X+Dr,yr=rr*G+jo;for(let ro=ze;ro<qe;++ro){let Dl=(Ne+ro*d-re)*oe+Vr,Ua=ro*j+yr;ut+=U[Dl+Tt]*R[Ua+je]}}}}w[At+je]=ut}}}}}return t.makeTensorInfo(b.shape,b.dtype,b.values)}var LT={kernelName:jl,backendName:"cpu",kernelFunc:UH};function HH(r){let{inputs:e,backend:t,attrs:o}=r,{dy:n,filter:s}=e,{pad:a,strides:i,inputShape:l}=o;te([n],"conv3dBackpropInputV2");let u=x.computeStrides(n.shape),c=x.computeStrides(s.shape),p=N.computeConv3DInfo(l,s.shape,i,1,a),m=new lt(p.inShape,"float32"),f=m.values,[d,h,g,y]=m.strides,b=t.data.get(n.dataId).values,[w,k,v,D]=u,A=t.data.get(s.dataId).values,[R,P,L,G]=c,{batchSize:j,filterDepth:U,filterHeight:H,filterWidth:q,inChannels:X,inDepth:oe,inHeight:Y,inWidth:re,outChannels:J,outDepth:ie,outHeight:ue,outWidth:ae,strideDepth:fe,strideHeight:de,strideWidth:xe}=p,we=U-1-p.padInfo.front,De=H-1-p.padInfo.top,Ne=q-1-p.padInfo.left;for(let ze=0;ze<j;++ze)for(let qe=0;qe<X;++qe)for(let it=0;it<oe;++it){let Tt=it-we,At=Math.max(0,Math.ceil(Tt/fe)),je=Math.min(ie,(U+Tt)/fe);for(let ut=0;ut<Y;++ut){let mt=ut-De,Pt=Math.max(0,Math.ceil(mt/de)),xo=Math.min(ue,(H+mt)/de);for(let Kt=0;Kt<re;++Kt){let to=Kt-Ne,Dr=Math.max(0,Math.ceil(to/xe)),jo=Math.min(ae,(q+to)/xe),rr=0;for(let yo=At;yo<je;++yo){let Vr=yo*fe-Tt;for(let yr=Pt;yr<xo;++yr){let ro=yr*de-mt;for(let Eo=Dr;Eo<jo;++Eo){let Dl=Eo*xe-to,Ua=w*ze+k*yo+v*yr+D*Eo,ns=R*(U-1-Vr)+P*(H-1-ro)+L*(q-1-Dl)+G*qe;for(let Xi=0;Xi<J;++Xi){let Qp=b[Ua+Xi],gc=A[ns+Xi];rr+=Qp*gc}}}}f[d*ze+h*it+g*ut+y*Kt+qe]=rr}}}return t.makeTensorInfo(m.shape,m.dtype,m.values)}var zT={kernelName:Ul,backendName:"cpu",kernelFunc:HH};var qH=$e(Qo,r=>Math.cos(r)),BT={kernelName:Qo,backendName:"cpu",kernelFunc:qH};var KH=$e(ei,r=>Math.cosh(r)),VT={kernelName:ei,backendName:"cpu",kernelFunc:KH};function XH(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=ve([d,h,g,f],"float32"),b=t.data.get(s.dataId).values,w=t.data.get(a.dataId).values,k=t.data.get(n.dataId).values,v=x.computeStrides(n.shape),D=x.computeStrides(y.shape);for(let A=0;A<d;A++){let R=A*4,P=b[R],L=b[R+1],G=b[R+2],j=b[R+3],U=w[A];if(U>=c)continue;let H=h>1?(G-P)*(p-1)/(h-1):0,q=g>1?(j-L)*(m-1)/(g-1):0;for(let X=0;X<h;X++){let oe=h>1?P*(p-1)+X*H:.5*(P+G)*(p-1);if(oe<0||oe>p-1){for(let Y=0;Y<g;Y++)for(let re=0;re<f;re++){let J=re+Y*D[2]+X*D[1]+A*D[0];y.values[J]=u}continue}if(l==="bilinear"){let Y=Math.floor(oe),re=Math.ceil(oe),J=oe-Y;for(let ie=0;ie<g;ie++){let ue=g>1?L*(m-1)+ie*q:.5*(L+j)*(m-1);if(ue<0||ue>m-1){for(let xe=0;xe<f;xe++){let we=xe+ie*D[2]+X*D[1]+A*D[0];y.values[we]=u}continue}let ae=Math.floor(ue),fe=Math.ceil(ue),de=ue-ae;for(let xe=0;xe<f;xe++){let we=xe+ae*v[2]+Y*v[1]+U*v[0],De=k[we];we=xe+fe*v[2]+Y*v[1]+U*v[0];let Ne=k[we];we=xe+ae*v[2]+re*v[1]+U*v[0];let ze=k[we];we=xe+fe*v[2]+re*v[1]+U*v[0];let qe=k[we],it=De+(Ne-De)*de,Tt=ze+(qe-ze)*de;we=xe+ie*D[2]+X*D[1]+A*D[0],y.values[we]=it+(Tt-it)*J}}}else for(let Y=0;Y<g;++Y){let re=g>1?L*(m-1)+Y*q:.5*(L+j)*(m-1);if(re<0||re>m-1){for(let ue=0;ue<f;ue++){let ae=ue+Y*D[2]+X*D[1]+A*D[0];y.values[ae]=u}continue}let J=Math.round(re),ie=Math.round(oe);for(let ue=0;ue<f;ue++){let ae=ue+J*v[2]+ie*v[1]+U*v[0],fe=ue+Y*D[2]+X*D[1]+A*D[0];y.values[fe]=k[ae]}}}}return t.makeTensorInfo(y.shape,y.dtype,y.values)}var GT={kernelName:ti,backendName:"cpu",kernelFunc:XH};function YH(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{axis:s,exclusive:a,reverse:i}=o;te(n,"cumsum");let l=N.getAxesPermutation([s],n.shape.length),u=n;l!=null&&(u=tr({inputs:{x:n},backend:t,attrs:{perm:l}}));let c=N.getInnerMostAxes(1,n.shape.length)[0];if(c!==u.shape.length-1)throw new Error(`backend.cumsum in CPU expects an inner-most axis=${u.shape.length-1} but got axis=${c}`);let p=fr(u.dtype,"int32"),m=x.makeZerosTypedArray(x.sizeFromShape(u.shape),p),f=t.data.get(u.dataId).values,d=u.shape[u.shape.length-1],h=i?(y,b)=>y+d-b-1:(y,b)=>y+b;for(let y=0;y<f.length;y+=d)for(let b=0;b<d;b++){let w=h(y,b);if(b===0)m[w]=a?0:f[w];else{let k=h(y,b-1);m[w]=a?f[k]+m[k]:f[w]+m[k]}}let g=t.makeTensorInfo(u.shape,p,m);if(l!=null){let y=N.getUndoAxesPermutation(l),b=tr({inputs:{x:g},backend:t,attrs:{perm:y}});return t.disposeIntermediateTensorInfo(g),t.disposeIntermediateTensorInfo(u),b}return g}var WT={kernelName:en,backendName:"cpu",kernelFunc:YH};function ZH(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,weights:s}=e,{size:a,binaryOutput:i}=o;if(n.shape.length===1){let l=t.data.get(n.dataId).values,u=t.data.get(s.dataId).values,c=of(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=ik(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 jT={kernelName:Hl,backendName:"cpu",kernelFunc:ZH};function JH(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{blockSize:s,dataFormat:a}=o;x.assert(a==="NHWC",()=>`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<i;++y)for(let b=0;b<p;++b){let w=Math.floor(b/s),k=b%s;for(let v=0;v<m;++v){let D=Math.floor(v/s),A=v%s,R=(k*s+A)*f;for(let P=0;P<f;++P){let G=P+R+c*(D+u*(w+l*y));h[g++]=d[G]}}}return t.makeTensorInfo([i,p,m,f],n.dtype,h)}var UT={kernelName:ri,backendName:"cpu",kernelFunc:JH};function vk(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,filter:s}=e,{strides:a,pad:i,dilations:l,dimRoundingMode:u}=o;te([n,s],"depthwiseConv2DNative");let c=x.computeStrides(n.shape),p=x.computeStrides(s.shape),m=l;m==null&&(m=[1,1]),x.assert(N.eitherStridesOrDilationsAreOne(a,m),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${a} and dilations '${m}'`);let f=N.computeConv2DInfo(n.shape,s.shape,a,m,i,u,!0),{filterHeight:d,filterWidth:h,dilationHeight:g,dilationWidth:y,padInfo:b}=f,w=b.left,k=b.top,v=f.outChannels/f.inChannels,D=new lt(f.outShape,n.dtype),A=t.data.get(n.dataId).values,R=t.data.get(s.dataId).values,P=D.values;for(let L=0;L<f.batchSize;++L){let G=L*c[0],j=L*D.strides[0];for(let U=0;U<f.outHeight;++U){let H=j+U*D.strides[1],q=U*f.strideHeight-w;for(let X=0;X<d;++X){let oe=q+X*g;if(oe<0||oe>=f.inHeight)continue;let Y=X*p[0],re=G+oe*c[1];for(let J=0;J<f.outWidth;++J){let ie=H+J*D.strides[2],ue=J*f.strideWidth-k;for(let ae=0;ae<h;++ae){let fe=ue+ae*y;if(fe<0||fe>=f.inWidth)continue;let de=Y+ae*p[1],xe=re+fe*f.inChannels,we=ie,De=de;for(let Ne=0;Ne<f.inChannels;++Ne){let ze=A[xe+Ne];for(let qe=0;qe<v;++qe)P[we+qe]+=ze*R[De+qe];we+=v,De+=v}}}}}}return t.makeTensorInfo(D.shape,D.dtype,D.values)}var HT={kernelName:tn,backendName:"cpu",kernelFunc:vk};function QH(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;te([n,s],"depthwiseConv2dNativeBackpropFilter");let p=N.computeConv2DInfo(n.shape,c,a,i,l,u,!0),{strideHeight:m,strideWidth:f,filterHeight:d,filterWidth:h}=p,g=new lt(p.filterShape,"float32"),y=p.padInfo.left,b=p.padInfo.top,w=p.outChannels/p.inChannels,k=t.data.get(n.dataId).values,v=new lt(n.shape,n.dtype,k),D=t.data.get(s.dataId).values,A=new lt(s.shape,s.dtype,D);for(let R=0;R<d;++R){let P=Math.max(0,Math.ceil((b-R)/m)),L=Math.min(p.outHeight,(p.inHeight+b-R)/m);for(let G=0;G<h;++G){let j=Math.max(0,Math.ceil((y-G)/f)),U=Math.min(p.outWidth,(p.inWidth+y-G)/f);for(let H=0;H<p.outChannels;++H){let q=Math.trunc(H/w),X=H%w,oe=0;for(let Y=0;Y<p.batchSize;++Y)for(let re=P;re<L;++re){let J=R+re*m-b;for(let ie=j;ie<U;++ie){let ue=G+ie*f-y;oe+=v.get(Y,J,ue,q)*A.get(Y,re,ie,H)}}g.set(oe,R,G,q,X)}}}return t.makeTensorInfo(g.shape,g.dtype,g.values)}var qT={kernelName:ql,backendName:"cpu",kernelFunc:QH};function eq(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;te([n,s],"depthwiseConv2DNativeBackpropInput");let p=x.computeStrides(n.shape),m=x.computeStrides(s.shape),f=N.computeConv2DInfo(c,s.shape,a,i,l,u,!0),d=new lt(f.inShape,"float32"),h=d.values,[g,y,b]=d.strides,w=t.data.get(n.dataId).values,[k,v,D]=p,A=t.data.get(s.dataId).values,[R,P,L]=m,{batchSize:G,filterHeight:j,filterWidth:U,inChannels:H,inHeight:q,inWidth:X,outChannels:oe,outHeight:Y,outWidth:re,strideHeight:J,strideWidth:ie}=f,ue=j-1-f.padInfo.top,ae=U-1-f.padInfo.left,fe=oe/H;for(let de=0;de<G;++de)for(let xe=0;xe<H;++xe)for(let we=0;we<q;++we){let De=we-ue,Ne=Math.max(0,Math.ceil(De/J)),ze=Math.min(Y,(j+De)/J);for(let qe=0;qe<X;++qe){let it=qe-ae,Tt=Math.max(0,Math.ceil(it/ie)),At=Math.min(re,(U+it)/ie),je=0;for(let ut=Ne;ut<ze;++ut){let mt=ut*J-De;for(let Pt=Tt;Pt<At;++Pt){let xo=Pt*ie-it,Kt=k*de+v*ut+D*Pt,to=R*(j-1-mt)+P*(U-1-xo)+L*xe;for(let Dr=0;Dr<fe;++Dr){let jo=xe*fe+Dr,rr=w[Kt+jo],yo=A[to+Dr];je+=rr*yo}}}h[g*de+y*we+b*qe+xe]=je}}return t.makeTensorInfo(d.shape,d.dtype,d.values)}var KT={kernelName:Kl,backendName:"cpu",kernelFunc:eq};function tq(r){let{inputs:e,backend:t}=r,{x:o}=e,n=x.sizeFromShape(o.shape),s=t.data.get(o.dataId).values,a=ve([n,n],o.dtype),i=a.values;for(let u=0;u<s.length;u++)i[u*n+u]=s[u];let l=[...o.shape,...o.shape];return t.makeTensorInfo(l,a.dtype,a.values)}var XT={kernelName:Xl,backendName:"cpu",kernelFunc:tq};var YT={kernelName:sa,backendName:"cpu",kernelFunc:({inputs:r,backend:e,attrs:t})=>{let{x:o,filter:n}=r,{strides:s,pad:a,dilations:i}=t,l=e,u=l.data.get(o.dataId).values,c=o.shape.length,p=l.data.get(n.dataId).values,m=n.shape.length,{batchSize:f,inHeight:d,inWidth:h,inChannels:g,outHeight:y,outWidth:b,padInfo:w,strideHeight:k,strideWidth:v,filterHeight:D,filterWidth:A,dilationHeight:R,dilationWidth:P,outShape:L}=N.computeDilation2DInfo(o.shape,n.shape,s,a,"NHWC",i),G=x.sizeFromShape(L),j=L.length,U=x.getArrayFromDType(o.dtype,G);for(let q=0;q<f;++q)for(let X=0;X<y;++X){let oe=X*k-w.top;for(let Y=0;Y<b;++Y){let re=Y*v-w.left;for(let J=0;J<g;++J){let ie=Number.MIN_SAFE_INTEGER;for(let ae=0;ae<D;++ae){let fe=oe+ae*R;if(fe>=0&&fe<d)for(let de=0;de<A;++de){let xe=re+de*P;if(xe>=0&&xe<h){let we=x.locToIndex([q,fe,xe,J],c,x.computeStrides(o.shape)),De=x.locToIndex([ae,de,J],m,x.computeStrides(n.shape)),Ne=u[we]+p[De];Ne>ie&&(ie=Ne)}}}let ue=x.locToIndex([q,X,Y,J],j,x.computeStrides(L));U[ue]=ie}}}return{dataId:l.write(x.toTypedArray(U,o.dtype),L,o.dtype),shape:L,dtype:o.dtype}}};var ZT={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:w,strideWidth:k,filterHeight:v,filterWidth:D,dilationHeight:A,dilationWidth:R,outShape:P}=N.computeDilation2DInfo(o.shape,n.shape,a,i,"NHWC",l);x.assert(s.rank===P.length,()=>`Error in ${Fc}, dy must have the same rank as output ${P.length}, but got ${s.rank}`);let L=x.toNestedArray(P,u.data.get(s.dataId).values),G=x.makeZerosNestedTypedArray(n.shape,n.dtype);for(let U=0;U<m;++U)for(let H=0;H<g;++H){let q=H*w-b.top;for(let X=0;X<y;++X){let oe=X*k-b.left;for(let Y=0;Y<h;++Y){let re=Number.MIN_SAFE_INTEGER,J=0,ie=0;for(let ue=0;ue<v;++ue){let ae=q+ue*A;if(ae>=0&&ae<f)for(let fe=0;fe<D;++fe){let de=oe+fe*R;if(de>=0&&de<d){let xe=c[U][ae][de][Y]+p[ue][fe][Y];xe>re&&(re=xe,J=ue,ie=fe)}}}G[J][ie][Y]+=L[U][H][X][Y]}}}return{dataId:u.write(x.toTypedArray(G,o.dtype),n.shape,n.dtype),shape:n.shape,dtype:n.dtype}}};var JT={kernelName:Rc,backendName:"cpu",kernelFunc:({inputs:r,backend:e,attrs:t})=>{let{x:o,filter:n,dy:s}=r,{strides:a,pad:i,dilations:l}=t,u=e,c=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:w,strideWidth:k,filterHeight:v,filterWidth:D,dilationHeight:A,dilationWidth:R,outShape:P}=N.computeDilation2DInfo(o.shape,n.shape,a,i,"NHWC",l);x.assert(s.rank===P.length,()=>`Error in ${Rc}, dy must have the same rank as output ${P.length}, but got ${s.rank}`);let L=x.toNestedArray(P,u.data.get(s.dataId).values),G=x.makeZerosNestedTypedArray(o.shape,o.dtype);for(let U=0;U<m;++U)for(let H=0;H<g;++H){let q=H*w-b.top;for(let X=0;X<y;++X){let oe=X*k-b.left;for(let Y=0;Y<h;++Y){let re=Number.MIN_SAFE_INTEGER,J=q<0?0:q,ie=oe<0?0:oe;for(let ue=0;ue<v;++ue){let ae=q+ue*A;if(ae>=0&&ae<f)for(let fe=0;fe<D;++fe){let de=oe+fe*R;if(de>=0&&de<d){let xe=c[U][ae][de][Y]+p[ue][fe][Y];xe>re&&(re=xe,J=ae,ie=de)}}}G[U][J][ie][Y]+=L[U][H][X][Y]}}}return{dataId:u.write(x.toTypedArray(G,o.dtype),o.shape,o.dtype),shape:o.shape,dtype:o.dtype}}};function rq(r){let{inputs:e,backend:t}=r,{dy:o,y:n}=e;te([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<a.length;++l){let u=a[l];u>=1?s[l]=i[l]:s[l]=i[l]*(u+1)}return t.makeTensorInfo(n.shape,"float32",s)}var QT={kernelName:Yl,backendName:"cpu",kernelFunc:rq};var oq=Xe((r,e)=>r===e?1:0),Ck=et(si,oq,null,"bool"),e1={kernelName:si,backendName:"cpu",kernelFunc:Ck};var nq=N.ERF_P,sq=N.ERF_A1,iq=N.ERF_A2,aq=N.ERF_A3,lq=N.ERF_A4,uq=N.ERF_A5,cq=$e(ni,r=>{let e=Math.sign(r),t=Math.abs(r),o=1/(1+nq*t);return e*(1-((((uq*o+lq)*o+aq)*o+iq)*o+sq)*o*Math.exp(-t*t))}),t1={kernelName:ni,backendName:"cpu",kernelFunc:cq};function pp(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),Qe({inputs:{x:n},backend:t,attrs:{shape:i}})}var r1={kernelName:us,backendName:"cpu",kernelFunc:pp};var pq=Xe((r,e)=>r/e),pf=et(rn,pq),mf={kernelName:rn,backendName:"cpu",kernelFunc:pf};function kg(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<n;g++){let y=Kn({inputs:{x:i},backend:t,attrs:{begin:[g,0],size:[1,s]}}),b=Kn({inputs:{x:l},backend:t,attrs:{begin:[g,0],size:[1,s]}}),w=pr({inputs:{real:y,imag:b},backend:t}),{real:k,imag:v}=mq(w,e,t),D=N.mergeRealAndImagArrays(k,v);for(let A=0;A<s;A++){let R=N.getComplexWithIndex(D,A);p[g*s+A]=R.real,m[g*s+A]=R.imag}t.disposeIntermediateTensorInfo(y),t.disposeIntermediateTensorInfo(b),t.disposeIntermediateTensorInfo(w)}let f=t.makeTensorInfo(u,"float32",p),d=t.makeTensorInfo(u,"float32",m),h=pr({inputs:{real:f,imag:d},backend:t});return t.disposeIntermediateTensorInfo(f),t.disposeIntermediateTensorInfo(d),h}function mq(r,e,t){let o=x.sizeFromShape(r.shape),n=t.data.get(r.dataId),s=t.data.get(n.complexTensorInfos.real.dataId).values,a=t.data.get(n.complexTensorInfos.imag.dataId).values;if(fq(o)){let i=Ik(s,a,o,e,t),l=[r.shape[0],r.shape[1]];if(e){let u=t.makeTensorInfo(l,"float32",i.real),c=t.makeTensorInfo(l,"float32",i.imag),p=t.makeTensorInfo([],"float32",x.createScalarValue(o,"float32")),m=Ar({inputs:{x:p},backend:t}),f=mf.kernelFunc({inputs:{a:u,b:p},backend:t}),d=mf.kernelFunc({inputs:{a:c,b:m},backend:t}),h=t.data.get(f.dataId).values,g=t.data.get(d.dataId).values;return t.disposeIntermediateTensorInfo(u),t.disposeIntermediateTensorInfo(c),t.disposeIntermediateTensorInfo(p),t.disposeIntermediateTensorInfo(m),t.disposeIntermediateTensorInfo(f),t.disposeIntermediateTensorInfo(d),{real:h,imag:g}}return i}else{let i=N.mergeRealAndImagArrays(s,a),l=dq(i,o,e);return N.splitRealAndImagArrays(l)}}function fq(r){return(r&r-1)==0}function Ik(r,e,t,o,n){if(t===1)return{real:r,imag:e};let s=N.mergeRealAndImagArrays(r,e),a=t/2,i=N.complexWithEvenIndex(s),l=i.real,u=i.imag,c=[l.length],p=n.makeTensorInfo(c,"float32",l),m=n.makeTensorInfo(c,"float32",u),f=pr({inputs:{real:p,imag:m},backend:n}),d=N.complexWithOddIndex(s),h=d.real,g=d.imag,y=[h.length],b=n.makeTensorInfo(y,"float32",h),w=n.makeTensorInfo(y,"float32",g),k=pr({inputs:{real:b,imag:w},backend:n}),v=Ik(l,u,a,o,n),D=v.real,A=v.imag,R=[D.length],P=n.makeTensorInfo(R,"float32",D),L=n.makeTensorInfo(R,"float32",A),G=pr({inputs:{real:P,imag:L},backend:n}),j=Ik(h,g,a,o,n),U=j.real,H=j.imag,q=[U.length],X=n.makeTensorInfo(q,"float32",U),oe=n.makeTensorInfo(q,"float32",H),Y=pr({inputs:{real:X,imag:oe},backend:n}),re=N.exponents(t,o),J=[re.real.length],ie=n.makeTensorInfo(J,"float32",re.real),ue=n.makeTensorInfo(J,"float32",re.imag),ae=pr({inputs:{real:ie,imag:ue},backend:n}),fe=sf({inputs:{a:ae,b:Y},backend:n}),de=Ra({inputs:{a:G,b:fe},backend:n}),xe=cf({inputs:{a:G,b:fe},backend:n}),we=jn({inputs:{input:de},backend:n}),De=jn({inputs:{input:xe},backend:n}),Ne=zi({inputs:{input:de},backend:n}),ze=zi({inputs:{input:xe},backend:n}),qe=pl({inputs:[we,De],backend:n,attrs:{axis:0}}),it=pl({inputs:[Ne,ze],backend:n,attrs:{axis:0}}),Tt=n.data.get(qe.dataId).values,At=n.data.get(it.dataId).values;return n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(b),n.disposeIntermediateTensorInfo(w),n.disposeIntermediateTensorInfo(k),n.disposeIntermediateTensorInfo(P),n.disposeIntermediateTensorInfo(L),n.disposeIntermediateTensorInfo(G),n.disposeIntermediateTensorInfo(X),n.disposeIntermediateTensorInfo(oe),n.disposeIntermediateTensorInfo(Y),n.disposeIntermediateTensorInfo(ie),n.disposeIntermediateTensorInfo(ue),n.disposeIntermediateTensorInfo(ae),n.disposeIntermediateTensorInfo(fe),n.disposeIntermediateTensorInfo(de),n.disposeIntermediateTensorInfo(xe),n.disposeIntermediateTensorInfo(we),n.disposeIntermediateTensorInfo(Ne),n.disposeIntermediateTensorInfo(De),n.disposeIntermediateTensorInfo(ze),n.disposeIntermediateTensorInfo(qe),n.disposeIntermediateTensorInfo(it),{real:Tt,imag:At}}function dq(r,e,t){let o=new Float32Array(e*2);for(let n=0;n<e;n++){let s=0,a=0;for(let i=0;i<e;i++){let l=N.exponent(n*i,e,t),u=N.getComplexWithIndex(r,i);s+=u.real*l.real-u.imag*l.imag,a+=u.real*l.imag+u.imag*l.real}t&&(s/=e,a/=e),N.assignToTypedArray(o,s,a,n)}return o}function hq(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=Qe({inputs:{x:o},backend:t,attrs:{shape:[a,s]}}),l=kg(i,!1,t),u=Qe({inputs:{x:l},backend:t,attrs:{shape:o.shape}});return t.disposeIntermediateTensorInfo(i),t.disposeIntermediateTensorInfo(l),u}var o1={kernelName:Zl,backendName:"cpu",kernelFunc:hq};function ff(r){let{backend:e,attrs:t}=r,{shape:o,value:n,dtype:s}=t,a=s||x.inferDtype(n),i=x.getArrayFromDType(a,x.sizeFromShape(o));return gq(i,n,a),e.makeTensorInfo(o,a,i)}var n1={kernelName:ia,backendName:"cpu",kernelFunc:ff};function gq(r,e,t){r.fill(e)}var s1={kernelName:ai,backendName:"cpu",kernelFunc:({inputs:r,attrs:e,backend:t})=>{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<a;m++){let f=m*l*i*u;for(let d=0;d<i;d++){let h=d*(l*u);for(let g=0;g<l;g++){let y=g*u;for(let b=0;b<u;b++){let k=[a,d,g,b][2],v=Math.round(l-k),D=f+h+y+b,A=c[D];if(v>=0&&v<l){let R=v*u,P=f+h+R+b;A=c[P]}s[D]=A}}}}return{dataId:n.write(s,o.shape,o.dtype),shape:o.shape,dtype:o.dtype}}};var xq=Xe((r,e)=>Math.floor(r/e)),yq=et(sn,xq,null,"int32"),i1={kernelName:sn,backendName:"cpu",kernelFunc:yq};function bq(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=_k({inputs:{x:n,filter:s},backend:t,attrs:{strides:l,pad:u,dataFormat:c,dilations:p,dimRoundingMode:m}});if(a){let g=h;h=Ra({inputs:{a:h,b:a},backend:t}),t.disposeIntermediateTensorInfo(g)}if(f){let g=h;h=up(t,h,f,i,d),t.disposeIntermediateTensorInfo(g)}return h}var a1={kernelName:ks,backendName:"cpu",kernelFunc:bq};function wq(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=vk({inputs:{x:n,filter:s},backend:t,attrs:{strides:l,pad:u,dataFormat:c,dilations:p,dimRoundingMode:m}});if(a){let g=h;h=Ra({inputs:{a:h,b:a},backend:t}),t.disposeIntermediateTensorInfo(g)}if(f){let g=h;h=up(t,h,f,i,d),t.disposeIntermediateTensorInfo(g)}return h}var l1={kernelName:_s,backendName:"cpu",kernelFunc:wq};function kq(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]=N.prepareAndValidate(o,n);if(u===0)return t.makeTensorInfo(l,o.dtype,[]);let m=ve([u,c],o.dtype),f=t.data.get(n.dataId).values,d=t.data.get(o.dataId).values;for(let h=0;h<u;h++){let g=[],y=0;for(let b=0;b<i;b++){let w=f[h*i+b];y+=w*p[b],g.push(w)}if(y<0||y>=s/c)throw new Error(`Invalid indices: ${g} does not index into ${o.shape}`);for(let b=0;b<c;b++)m.values[h*c+b]=d[y*c+b]}return t.makeTensorInfo(l,m.dtype,m.values)}var u1={kernelName:li,backendName:"cpu",kernelFunc:kq};function _q(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,indices:s}=e,{axis:a,batchDims:i}=o;te([n,s],"gatherV2");let l=i;i==null&&(l=0);let u=x.sizeFromShape(s.shape),c=x.parseAxisParam(a,n.shape)[0],p=N.segment_util.collectGatherOpShapeInfo(n,s,c,l),m=Qe({inputs:{x:n},backend:t,attrs:{shape:[p.batchSize,p.outerSize,p.dimSize,p.sliceSize]}}),f=Qe({inputs:{x:s},backend:t,attrs:{shape:[p.batchSize,u/p.batchSize]}}),d=[p.batchSize,p.outerSize,u/p.batchSize,p.sliceSize],h=t.bufferSync(f),g=t.bufferSync(m),y=lk(g,h,d);return t.disposeIntermediateTensorInfo(m),t.disposeIntermediateTensorInfo(f),t.makeTensorInfo(p.outputShape,y.dtype,y.values)}var c1={kernelName:cs,backendName:"cpu",kernelFunc:_q};var vq=Xe((r,e)=>r>=e?1:0),Cq=et(ln,vq,null,"bool"),p1={kernelName:ln,backendName:"cpu",kernelFunc:Cq};function Iq(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=Qe({inputs:{x:o},backend:t,attrs:{shape:[a,s]}}),l=kg(i,!0,t),u=Qe({inputs:{x:l},backend:t,attrs:{shape:o.shape}});return t.disposeIntermediateTensorInfo(i),t.disposeIntermediateTensorInfo(l),u}var m1={kernelName:Jl,backendName:"cpu",kernelFunc:Iq};var Nq=$e(ci,r=>Number.isFinite(r)?1:0,"bool"),f1={kernelName:ci,backendName:"cpu",kernelFunc:Nq};var Sq=$e(pi,r=>Math.abs(r)===Infinity?1:0,"bool"),d1={kernelName:pi,backendName:"cpu",kernelFunc:Sq};var Tq=$e(mi,r=>Number.isNaN(r)?1:0,"bool"),h1={kernelName:mi,backendName:"cpu",kernelFunc:Tq};var Aq=Xe((r,e)=>r<=e?1:0),Eq=et(di,Aq,null,"bool"),g1={kernelName:di,backendName:"cpu",kernelFunc:Eq};function Dq(r){let{backend:e,attrs:t}=r,{start:o,stop:n,num:s}=t,a=uk(o,n,s);return e.makeTensorInfo([a.length],"float32",a)}var x1={kernelName:eu,backendName:"cpu",kernelFunc:Dq};var $q=$e(hi,r=>Math.log1p(r)),y1={kernelName:hi,backendName:"cpu",kernelFunc:$q};var Rq=Xe((r,e)=>r&&e),Fq=et(gi,Rq,null,"bool"),b1={kernelName:gi,backendName:"cpu",kernelFunc:Fq};var Oq=$e(Ja,r=>r?0:1,"bool"),w1={kernelName:Ja,backendName:"cpu",kernelFunc:Oq};var Pq=Xe((r,e)=>r||e),Mq=et(Qa,Pq,null,"bool"),k1={kernelName:Qa,backendName:"cpu",kernelFunc:Mq};function Lq(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{depthRadius:s,bias:a,alpha:i,beta:l}=o;te(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),w=0;for(;y<=b;y++){let k=p[y];w+=k*k}return w}for(let h=0;h<m;h++){let g=d(h),y=p[h]*Math.pow(a+i*g,-l);f[h]=y}return t.makeTensorInfo(n.shape,n.dtype,f)}var _1={kernelName:aa,backendName:"cpu",kernelFunc:Lq};function zq(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;te(a,"LRNGrad");let p=x.sizeFromShape(a.shape),m=a.shape[3],f=t.data.get(a.dataId).values,d=t.data.get(n.dataId).values,h=t.data.get(s.dataId).values,g=new Float32Array(p),y=p;for(let b=0;b<y;b++){let w=b%m,k=b-w+Math.max(0,w-i),v=b-w+Math.min(m,w+i+1),D=0;for(let A=k;A<v;A++)D+=Math.pow(d[A],2);D=u*D+l;for(let A=k;A<v;A++){let R=-2*u*c*d[A]*h[b]/D;b===A&&(R+=Math.pow(D,-c)),R*=f[b],g[A]+=R}}return t.makeTensorInfo(a.shape,n.dtype,g)}var v1={kernelName:tu,backendName:"cpu",kernelFunc:zq};function Nk(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{reductionIndices:s,keepDims:a}=o,i=t,l=n.shape,u=l.length,c=x.parseAxisParam(s,l),p=c,m=N.getAxesPermutation(p,u),f=i.data.get(n.dataId).values;if(m!=null){let k=new Array(u);for(let v=0;v<k.length;v++)k[v]=l[m[v]];f=af(f,l,n.dtype,m,k),p=N.getInnerMostAxes(p.length,u),l=k}te(n,"max"),N.assertAxesAreInnerMostDims("max",p,u);let[d,h]=N.computeOutAndReduceShapes(l,p),g=x.sizeFromShape(h),y=ck(f,g,d,n.dtype),b=i.write(y,d,n.dtype),w=d;return a&&(w=N.expandShapeToKeepDim(d,c)),{dataId:b,shape:w,dtype:n.dtype}}var C1={kernelName:pn,backendName:"cpu",kernelFunc:Nk};function Bq(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e;te(n,"maxPool");let{filterSize:s,strides:a,pad:i,dimRoundingMode:l}=o,u=1;x.assert(N.eitherStridesOrDilationsAreOne(a,u),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${u}'`);let c=N.computePool2DInfo(n.shape,s,a,u,i,l),p;if(c.filterWidth===1&&c.filterHeight===1&&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=cp(m,n.shape,n.dtype,f,c,"max");p=t.makeTensorInfo(c.outShape,n.dtype,d.values)}return p}var I1={kernelName:fn,backendName:"cpu",kernelFunc:Bq};function Vq(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{filterSize:s,strides:a,pad:i,dimRoundingMode:l,dataFormat:u}=o;te(n,"maxPool3d");let c=N.computePool3DInfo(n.shape,s,a,1,i,l,u),p=t.data.get(n.dataId).values,m=wg(p,n.shape,n.dtype,x.computeStrides(n.shape),c,"max");return t.makeTensorInfo(m.shape,"float32",m.values)}var N1={kernelName:la,backendName:"cpu",kernelFunc:Vq};function Gq(r){let{inputs:e,backend:t,attrs:o}=r,{dy:n,input:s}=e,{filterSize:a,strides:i,pad:l,dimRoundingMode:u}=o;te([n,s],"maxPool3DGrad");let c=N.computePool3DInfo(s.shape,a,i,1,l,u),p=t.bufferSync(s),m=_T(p,c),f=c.strideDepth,d=c.strideHeight,h=c.strideWidth,g=c.dilationDepth,y=c.dilationHeight,b=c.dilationWidth,w=c.effectiveFilterDepth,k=c.effectiveFilterHeight,v=c.effectiveFilterWidth,D=w-1-c.padInfo.front,A=v-1-c.padInfo.left,R=k-1-c.padInfo.top,P=ve(s.shape,"float32"),L=t.bufferSync(n);for(let G=0;G<c.batchSize;++G)for(let j=0;j<c.inChannels;++j)for(let U=0;U<c.inDepth;++U)for(let H=0;H<c.inHeight;++H)for(let q=0;q<c.inWidth;++q){let X=U-D,oe=H-R,Y=q-A,re=0;for(let J=0;J<w;J+=g){let ie=(X+J)/f;if(!(ie<0||ie>=c.outDepth||Math.floor(ie)!==ie))for(let ue=0;ue<k;ue+=y){let ae=(oe+ue)/d;if(!(ae<0||ae>=c.outHeight||Math.floor(ae)!==ae))for(let fe=0;fe<v;fe+=b){let de=(Y+fe)/h;if(de<0||de>=c.outWidth||Math.floor(de)!==de)continue;let xe=w*k*v-1-m.get(G,ie,ae,de,j),we=J*k*v+ue*v+fe,De=xe===we?1:0;if(De===0)continue;re+=L.get(G,ie,ae,de,j)*De}}}P.set(re,G,U,H,q,j)}return t.makeTensorInfo(P.shape,P.dtype,P.values)}var S1={kernelName:ou,backendName:"cpu",kernelFunc:Gq};function Wq(r){let{inputs:e,backend:t,attrs:o}=r,{dy:n,input:s,output:a}=e,i=s;te([s,a],"maxPoolGrad");let{filterSize:l,strides:u,pad:c,dimRoundingMode:p}=o,m=N.computePool2DInfo(i.shape,l,u,1,c,p),f=t.data.get(i.dataId).values,d=ve(m.outShape,i.dtype,bg(f,i.shape,i.dtype,m).values),h=m.strideHeight,g=m.strideWidth,y=m.dilationHeight,b=m.dilationWidth,w=m.effectiveFilterHeight,k=m.effectiveFilterWidth,v=k-1-m.padInfo.left,D=w-1-m.padInfo.top,A=ve(i.shape,"float32"),R=t.data.get(n.dataId).values,P=ve(n.shape,"float32",R);for(let L=0;L<m.batchSize;++L)for(let G=0;G<m.inChannels;++G)for(let j=0;j<m.inHeight;++j)for(let U=0;U<m.inWidth;++U){let H=j-D,q=U-v,X=0;for(let oe=0;oe<w;oe+=y){let Y=(H+oe)/h;if(!(Y<0||Y>=m.outHeight||Math.floor(Y)!==Y))for(let re=0;re<k;re+=b){let J=(q+re)/g;if(J<0||J>=m.outWidth||Math.floor(J)!==J)continue;let ie=w*k-1-d.get(L,Y,J,G),ue=oe*k+re,ae=ie===ue?1:0;if(ae===0)continue;X+=P.get(L,Y,J,G)*ae}}A.set(X,L,j,U,G)}return t.makeTensorInfo(A.shape,A.dtype,A.values)}var T1={kernelName:ru,backendName:"cpu",kernelFunc:Wq};function A1(r,e,t,o,n){let s=x.computeStrides(e),a=cp(r,e,t,s,n,"max"),i=bg(r,e,t,n,!0,o);return[a.values,i.values]}var E1={kernelName:nu,backendName:"cpu",kernelFunc:({inputs:r,attrs:e,backend:t})=>{let{x:o}=r,{filterSize:n,strides:s,pad:a,includeBatchInIndex:i}=e,l=t;te(o,"MaxPoolWithArgmax");let u=l.data.get(o.dataId).values,c=N.computePool2DInfo(o.shape,n,s,[1,1],a),[p,m]=A1(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 qu(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{axis:s,keepDims:a}=o;te(n,"sum");let i;n.dtype==="bool"?i=Un({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=N.getAxesPermutation(u,l),p=u,m=i;c!=null&&(m=tr({inputs:{x:i},backend:t,attrs:{perm:c}}),p=N.getInnerMostAxes(p.length,l)),N.assertAxesAreInnerMostDims("sum",p,m.shape.length);let[f,d]=N.computeOutAndReduceShapes(m.shape,p),h=N.upcastType(m.dtype,"int32"),g=ap(t,f,h),y=x.sizeFromShape(d),b=t.data.get(g.dataId).values,w=t.data.get(m.dataId).values;for(let k=0;k<b.length;++k){let v=k*y,D=0;for(let A=0;A<y;++A)D+=w[v+A];b[k]=D}if(a){let k=N.expandShapeToKeepDim(g.shape,u),v=g;g=Qe({inputs:{x:g},backend:t,attrs:{shape:k}}),t.disposeIntermediateTensorInfo(v)}return t.disposeIntermediateTensorInfo(i),c!=null&&t.disposeIntermediateTensorInfo(m),g}var D1={kernelName:Dn,backendName:"cpu",kernelFunc:qu};function jq(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{axis:s,keepDims:a}=o,i=x.parseAxisParam(s,n.shape),u=N.computeOutAndReduceShapes(n.shape,i)[1],c=x.sizeFromShape(u),p=[],m=t.makeTensorInfo([],"float32",new Float32Array([c]));p.push(m);let f=Un({inputs:{x:n},backend:t,attrs:{dtype:"float32"}});p.push(f);let d=pf({inputs:{a:f,b:m},backend:t});p.push(d);let h=qu({inputs:{x:d},backend:t,attrs:{axis:s,keepDims:a}});return p.forEach(g=>t.disposeIntermediateTensorInfo(g)),h}var $1={kernelName:dn,backendName:"cpu",kernelFunc:jq};function Uq(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{axis:s,keepDims:a}=o;te(n,"min");let i=x.parseAxisParam(s,n.shape),l=i,u=N.getAxesPermutation(l,n.shape.length),c=n;u!=null&&(c=tr({inputs:{x:n},backend:t,attrs:{perm:u}}),l=N.getInnerMostAxes(l.length,n.shape.length)),N.assertAxesAreInnerMostDims("min",l,c.shape.length);let[p,m]=N.computeOutAndReduceShapes(c.shape,l),f=x.sizeFromShape(m),d=x.makeZerosTypedArray(x.sizeFromShape(p),c.dtype),h=t.data.get(c.dataId).values;for(let y=0;y<d.length;++y){let b=y*f,w=h[b];for(let k=0;k<f;++k){let v=h[b+k];v<w&&(w=v)}d[y]=w}u!=null&&t.disposeIntermediateTensorInfo(c);let g=t.makeTensorInfo(p,c.dtype,d);if(a){let y=N.expandShapeToKeepDim(p,i),b=Qe({inputs:{x:g},backend:t,attrs:{shape:y}});return t.disposeIntermediateTensorInfo(g),b}return g}var R1={kernelName:hn,backendName:"cpu",kernelFunc:Uq};function Hq(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{paddings:s,mode:a}=o;te(n,"mirrorPad");let i=s.map((w,k)=>w[0]+n.shape[k]+w[1]),l=s.map(w=>w[0]),u=s.map((w,k)=>w[0]+n.shape[k]),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 w=0;w<d;w++){let k=x.indexToLoc(w,h,g);for(let D=0;D<h;D++)k[D]<l[D]?k[D]=l[D]*2-k[D]-c:k[D]>=u[D]&&(k[D]=(u[D]-1)*2-k[D]+c);k=k.map((D,A)=>D-l[A]);let v=x.locToIndex(k,m,f);y[w]=p[v]}return{dataId:t.write(y,i,n.dtype),shape:i,dtype:n.dtype}}var F1={kernelName:ua,backendName:"cpu",kernelFunc:Hq};var qq=Xe((r,e)=>{let t=r%e;return r<0&&e<0||r>=0&&e>=0?t:(t+e)%e}),Kq=et(xi,qq),O1={kernelName:xi,backendName:"cpu",kernelFunc:Kq};var M1=Tc(Gm());function Sk(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=Nk({inputs:{x:n},backend:t,attrs:{reductionIndices:l,keepDims:!1}}),c=N.expandShapeToKeepDim(u.shape,l),p=Qe({inputs:{x:u},backend:t,attrs:{shape:c}}),m=cf({inputs:{a:n,b:p},backend:t}),f=ak({inputs:{x:m},backend:t}),d=qu({inputs:{x:f},backend:t,attrs:{axis:l,keepDims:!1}}),h=Qe({inputs:{x:d},backend:t,attrs:{shape:c}}),g=pf({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 P1={kernelName:$n,backendName:"cpu",kernelFunc:Sk};function Xq(r){let{inputs:e,backend:t,attrs:o}=r,{logits:n}=e,{numSamples:s,seed:a,normalized:i}=o;te(n,"multinomial");let l=i?n:Sk({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<u;++d){let h=d*c,g=new Float32Array(c-1);g[0]=p[h];for(let w=1;w<g.length;++w)g[w]=g[w-1]+p[h+w];let y=M1.alea(a.toString()),b=d*s;for(let w=0;w<s;++w){let k=y();f[b+w]=g.length;for(let v=0;v<g.length;v++)if(k<g[v]){f[b+w]=v;break}}}return i||t.disposeIntermediateTensorInfo(l),t.makeTensorInfo(m,"int32",f)}var L1={kernelName:su,backendName:"cpu",kernelFunc:Xq};var Yq=Tr.nonMaxSuppressionV3Impl;function Zq(r){let{inputs:e,backend:t,attrs:o}=r,{boxes:n,scores:s}=e,{maxOutputSize:a,iouThreshold:i,scoreThreshold:l}=o;te(n,"NonMaxSuppression");let u=t.data.get(n.dataId).values,c=t.data.get(s.dataId).values,{selectedIndices:p}=Yq(u,c,a,i,l);return t.makeTensorInfo([p.length],"int32",new Int32Array(p))}var z1={kernelName:bi,backendName:"cpu",kernelFunc:Zq};var Jq=Tr.nonMaxSuppressionV4Impl;function Qq(r){let{inputs:e,backend:t,attrs:o}=r,{boxes:n,scores:s}=e,{maxOutputSize:a,iouThreshold:i,scoreThreshold:l,padToMaxOutputSize:u}=o;te(n,"NonMaxSuppressionPadded");let c=t.data.get(n.dataId).values,p=t.data.get(s.dataId).values,{selectedIndices:m,validOutputs:f}=Jq(c,p,a,i,l,u);return[t.makeTensorInfo([m.length],"int32",new Int32Array(m)),t.makeTensorInfo([],"int32",new Int32Array([f]))]}var B1={kernelName:wi,backendName:"cpu",kernelFunc:Qq};var eK=Tr.nonMaxSuppressionV5Impl;function tK(r){let{inputs:e,backend:t,attrs:o}=r,{boxes:n,scores:s}=e,{maxOutputSize:a,iouThreshold:i,scoreThreshold:l,softNmsSigma:u}=o;te(n,"NonMaxSuppressionWithScore");let c=t.data.get(n.dataId).values,p=t.data.get(s.dataId).values,m=a,f=i,d=l,h=u,{selectedIndices:g,selectedScores:y}=eK(c,p,m,f,d,h);return[t.makeTensorInfo([g.length],"int32",new Int32Array(g)),t.makeTensorInfo([y.length],"float32",new Float32Array(y))]}var V1={kernelName:ki,backendName:"cpu",kernelFunc:tK};function rK(r){let{inputs:e,backend:t,attrs:o}=r,{indices:n}=e,{depth:s,onValue:a,offValue:i}=o;te(n,"oneHot");let l=x.sizeFromShape(n.shape),u=new Float32Array(l*s);u.fill(i);let c=t.data.get(n.dataId).values;for(let p=0;p<l;++p)c[p]>=0&&c[p]<s&&(u[p*s+c[p]]=a);return t.makeTensorInfo([...n.shape,s],"int32",u)}var G1={kernelName:yn,backendName:"cpu",kernelFunc:rK};function df(r){let{inputs:e,backend:t}=r,{x:o}=e;if(o.dtype==="string")throw new Error("zerosLike is not supported for string tensors");if(o.dtype==="complex64"){let n=jn({inputs:{input:o},backend:t}),s=df({inputs:{x:n},backend:t}),a=zi({inputs:{input:o},backend:t}),i=df({inputs:{x:a},backend:t}),l=pr({inputs:{real:s,imag:i},backend:t});return t.disposeIntermediateTensorInfo(n),t.disposeIntermediateTensorInfo(s),t.disposeIntermediateTensorInfo(a),t.disposeIntermediateTensorInfo(i),l}else return ff({backend:t,attrs:{shape:o.shape,value:0,dtype:o.dtype}})}var W1={kernelName:bs,backendName:"cpu",kernelFunc:df};function j1(r){let{inputs:e,backend:t}=r,{x:o}=e;if(o.dtype==="string")throw new Error("onesLike is not supported for string tensors");if(o.dtype==="complex64"){let n=jn({inputs:{input:o},backend:t}),s=j1({inputs:{x:n},backend:t}),a=zi({inputs:{input:o},backend:t}),i=df({inputs:{x:a},backend:t}),l=pr({inputs:{real:s,imag:i},backend:t});return t.disposeIntermediateTensorInfo(n),t.disposeIntermediateTensorInfo(s),t.disposeIntermediateTensorInfo(a),t.disposeIntermediateTensorInfo(i),l}else return ff({backend:t,attrs:{shape:o.shape,value:1,dtype:o.dtype}})}var U1={kernelName:ms,backendName:"cpu",kernelFunc:j1};function Tk(r){let{inputs:e,backend:t,attrs:o}=r,{axis:n}=o;if(e.length===1)return pp({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=pp({inputs:{input:c},backend:t,attrs:{dim:n}});return i.push(p),p}),u=pl({inputs:l,backend:t,attrs:{axis:n}});return i.forEach(c=>t.disposeIntermediateTensorInfo(c)),u}var H1={kernelName:fs,backendName:"cpu",kernelFunc:Tk};function oK(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{paddings:s,constantValue:a}=o;te(n,"pad");let i=s.map((b,w)=>b[0]+n.shape[w]+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<c;b++){let k=x.indexToLoc(b,p,m).map((D,A)=>D+l[A]),v=x.locToIndex(k,d,h);g[v]=u[b]}return{dataId:t.write(g,i,n.dtype),shape:i,dtype:n.dtype}}var _g={kernelName:bn,backendName:"cpu",kernelFunc:oK};var nK=Xe((r,e)=>Math.pow(r,e)),sK=et(wn,nK),q1={kernelName:wn,backendName:"cpu",kernelFunc:sK};function iK(r){let{backend:e,attrs:t}=r,{start:o,stop:n,dtype:s,step:a}=t,i=lf(o,n,a,s);return e.makeTensorInfo([i.length],s,i)}var K1={kernelName:ca,backendName:"cpu",kernelFunc:iK};var aK=$e(vi,r=>1/r),X1={kernelName:vi,backendName:"cpu",kernelFunc:aK};function lK(r){let{inputs:e,backend:t,attrs:o}=r,{images:n}=e,{alignCorners:s,halfPixelCenters:a,size:i}=o;te(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],w=0,k=y[0]/b[0],v=y[1]/b[1];for(let D=0;D<p;D++)for(let A=0;A<u;A++){let R;a?R=k*(A+.5)-.5:R=k*A;let P=Math.max(0,Math.floor(R)),L=R-P,G=Math.min(m-1,Math.ceil(R)),j=D*l[0]+P*l[1],U=D*l[0]+G*l[1];for(let H=0;H<c;H++){let q;a?q=v*(H+.5)-.5:q=v*H;let X=Math.max(0,Math.floor(q)),oe=q-X,Y=Math.min(f-1,Math.ceil(q)),re=j+X*l[2],J=U+X*l[2],ie=j+Y*l[2],ue=U+Y*l[2];for(let ae=0;ae<d;ae++){let fe=h[re+ae],de=h[J+ae],xe=h[ie+ae],we=h[ue+ae],De=fe+(xe-fe)*oe,Ne=de+(we-de)*oe,ze=De+(Ne-De)*L;g[w++]=ze}}}return t.makeTensorInfo([p,u,c,d],"float32",g)}var Y1={kernelName:vn,backendName:"cpu",kernelFunc:lK};function uK(r){let{inputs:e,backend:t,attrs:o}=r,{images:n,dy:s}=e,{alignCorners:a}=o;te([s,n],"resizeBilinearGrad");let i=x.computeStrides(n.shape),[l,u,c,p]=n.shape,[,m,f]=s.shape,d=new Float32Array(l*u*c*p),h=[a&&m>1?u-1:u,a&&f>1?c-1:c],g=[a&&m>1?m-1:m,a&&f>1?f-1:f],y=h[0]/g[0],b=h[1]/g[1],w=t.data.get(s.dataId).values,k=0;for(let v=0;v<l;v++){let D=v*i[0];for(let A=0;A<m;A++){let R=A*y,P=Math.floor(R),L=Math.min(Math.ceil(R),u-1),G=D+P*i[1],j=D+L*i[1],U=R-P,H=1-U;for(let q=0;q<f;q++){let X=q*b,oe=Math.floor(X),Y=Math.min(Math.ceil(X),c-1),re=X-oe,J=1-re,ie=G+oe*i[2],ue=G+Y*i[2],ae=j+oe*i[2],fe=j+Y*i[2],de=H*J,xe=H*re,we=U*J,De=U*re;for(let Ne=0;Ne<p;Ne++){let ze=w[k++];d[ie+Ne]+=ze*de,d[ue+Ne]+=ze*xe,d[ae+Ne]+=ze*we,d[fe+Ne]+=ze*De}}}}return t.makeTensorInfo([l,c,u,p],"float32",d)}var Z1={kernelName:lu,backendName:"cpu",kernelFunc:uK};function cK(r){let{inputs:e,backend:t,attrs:o}=r,{images:n}=e,{alignCorners:s,halfPixelCenters:a,size:i}=o;te(n,"resizeNearestNeighbor");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(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],w=y[0]/b[0],k=y[1]/b[1],v=0;for(let D=0;D<p;D++){let A=D*l[0];for(let R=0;R<u;R++){let P=a?w*(R+.5):w*R,L=Math.min(m-1,s?Math.round(P):Math.floor(P));a&&(L=Math.max(0,L));let G=A+L*l[1];for(let j=0;j<c;j++){let U=a?k*(j+.5):k*j,H=Math.min(f-1,s?Math.round(U):Math.floor(U));a&&(H=Math.max(0,H));let q=G+H*l[2];for(let X=0;X<d;X++){let oe=h[q+X];g[v++]=oe}}}}return t.makeTensorInfo([p,u,c,d],n.dtype,g)}var J1={kernelName:pa,backendName:"cpu",kernelFunc:cK};function pK(r){let{inputs:e,backend:t,attrs:o}=r,{images:n,dy:s}=e,{alignCorners:a}=o;te([s,n],"resizeNearestNeighborGrad");let i=x.computeStrides(n.shape),l=x.computeStrides(s.shape),[u,c,p,m]=n.shape,[,f,d]=s.shape,h=new Float32Array(u*c*p*m),g=t.data.get(s.dataId).values,y=[a&&f>1?c-1:c,a&&d>1?p-1:p],b=[a&&f>1?f-1:f,a&&d>1?d-1:d],w=y[0]/b[0],k=y[1]/b[1],v=1/w,D=1/k,A=Math.ceil(v)*2+2,R=Math.ceil(D)*2+2;for(let P=0;P<u;P++){let L=P*i[0];for(let G=0;G<c;G++){let j=L+G*i[1],U=Math.floor(G*v),H=Math.floor(U-A/2);for(let q=0;q<p;q++){let X=j+q*i[2],oe=Math.floor(q*D),Y=Math.floor(oe-R/2);for(let re=0;re<m;re++){let J=0;for(let ie=0;ie<A;ie++){let ue=ie+H;if(ue<0||ue>=f)continue;let ae=L+ue*l[1],fe=ue*w,de=Math.min(c-1,a?Math.round(fe):Math.floor(fe));if(G===de)for(let xe=0;xe<R;xe++){let we=xe+Y;if(we<0||we>=d)continue;let De=ae+we*l[2],Ne=we*k,ze=Math.min(p-1,a?Math.round(Ne):Math.floor(Ne));q===ze&&(J+=g[De+re])}}h[X+re]=J}}}}return t.makeTensorInfo(n.shape,n.dtype,h)}var Q1={kernelName:au,backendName:"cpu",kernelFunc:pK};function mK(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{dims:s}=o;te(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 lt(n.shape,n.dtype),u=t.bufferSync(n);for(let c=0;c<l.size;c++){let p=l.indexToLoc(c),m=p.slice();i.forEach(f=>m[f]=n.shape[f]-1-m[f]),l.set(u.get(...m),...p)}return t.makeTensorInfo(l.shape,l.dtype,l.values)}var eA={kernelName:In,backendName:"cpu",kernelFunc:mK};var tA={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]=N.getImageCenter(a,c,p),h=255,g=Math.sin(n),y=Math.cos(n),b=i.data.get(o.dataId).values;for(let k=0;k<u;k++){let v=k*p*c*m;for(let D=0;D<c;D++){let A=D*(p*m);for(let R=0;R<p;R++){let P=R*m;for(let L=0;L<m;L++){let G=[u,D,R,L],j=G[2],U=G[1],H=(j-f)*y-(U-d)*g,q=(j-f)*g+(U-d)*y;H=Math.round(H+f),q=Math.round(q+d);let X=s;if(typeof s!="number"&&(L===3?X=h:X=s[L]),H>=0&&H<p&&q>=0&&q<c){let Y=q*(p*m),re=H*m,J=v+Y+re+L;X=b[J]}let oe=v+A+P+L;l[oe]=X}}}}return{dataId:i.write(l,o.shape,o.dtype),shape:o.shape,dtype:o.dtype}}};var fK=$e(Nn,r=>{let e=Math.floor(r);return r-e<.5?Math.floor(r):r-e>.5?Math.ceil(r):e%2==0?e:e+1}),rA={kernelName:Nn,backendName:"cpu",kernelFunc:fK};function vg(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 ve(t,e.dtype);let f=ve(c,e.dtype);f.values.fill(l);for(let d=0;d<s;d++){let h=[],g=0;for(let y=0;y<a;y++){let b=p[d*a+y];h.push(b),g+=b*i[y]}if(g<0||g>=o/n)throw new Error(`Invalid indices: ${h} does not index into ${t}`);for(let y=0;y<n;y++)u?f.values[g*n+y]+=m[d*n+y]:f.values[g*n+y]=e.rank===0?m[0]:m[d*n+y]}return f}function dK(r){let{inputs:e,backend:t,attrs:o}=r,{indices:n,updates:s}=e,{shape:a}=o,{sliceRank:i,numUpdates:l,sliceSize:u,strides:c,outputSize:p}=N.calculateShapes(s,n,a),m=!0,f=t.bufferSync(n),d=t.bufferSync(s),h=vg(f,d,a,p,u,l,i,c,0,m);return t.makeTensorInfo(a,h.dtype,h.values)}var oA={kernelName:Ci,backendName:"cpu",kernelFunc:dK};function hK(r){let{inputs:e,backend:t}=r,{condition:o,t:n,e:s}=e;te([o,n,s],"select");let a=o.shape.length,i=t.data.get(o.dataId).values,l=t.data.get(n.dataId).values,u=t.data.get(s.dataId).values,c=fr(n.dtype,s.dtype),p=x.makeZerosTypedArray(x.sizeFromShape(n.shape),c),m=0,f=a===0||a>1||n.shape.length===1?1:x.sizeFromShape(n.shape.slice(1));for(let d=0;d<i.length;d++)for(let h=0;h<f;h++)i[d]===1?p[m++]=l[d]:p[m++]=u[d];return t.makeTensorInfo(n.shape,c,p)}var nA={kernelName:hs,backendName:"cpu",kernelFunc:hK};var gK=N.SELU_SCALEALPHA,xK=N.SELU_SCALE,yK=$e(Ii,r=>r>=0?xK*r:gK*(Math.exp(r)-1)),sA={kernelName:Ii,backendName:"cpu",kernelFunc:yK};var bK=$e(An,r=>1/(1+Math.exp(-r))),iA={kernelName:An,backendName:"cpu",kernelFunc:bK};var wK=$e(Si,r=>r<0?-1:r>0?1:0),aA={kernelName:Si,backendName:"cpu",kernelFunc:wK};var kK=$e(Tn,r=>Math.sin(r)),lA={kernelName:Tn,backendName:"cpu",kernelFunc:kK};var _K=$e(Ni,r=>Math.sinh(r)),uA={kernelName:Ni,backendName:"cpu",kernelFunc:_K};var vK=11920928955078125e-23,cA=Math.log(vK)+2,CK=$e(Ti,r=>{let e=r>-cA,t=r<cA,o=Math.exp(r),n;return t?n=o:e?n=r:n=Math.log(1+o),n}),pA={kernelName:Ti,backendName:"cpu",kernelFunc:CK};function IK(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{blockShape:s,paddings:a}=o;te([n],"spaceToBatchND");let i=x.sizeFromShape(s),l=[[0,0]];l.push(...a);for(let D=1+s.length;D<n.shape.length;++D)l.push([0,0]);let u=_g.kernelFunc({inputs:{x:n},backend:t,attrs:{paddings:l,constantValue:0}}),c=N.getReshaped(u.shape,s,i,!1),p=N.getPermuted(c.length,s.length,!1),m=N.getReshapedPermuted(u.shape,s,i,!1),h=Qe({inputs:{x:u},backend:t,attrs:{shape:c}}),b=tr({inputs:{x:h},backend:t,attrs:{perm:p}}),v=Qe({inputs:{x:b},backend:t,attrs:{shape:m}});return t.disposeIntermediateTensorInfo(u),t.disposeIntermediateTensorInfo(h),t.disposeIntermediateTensorInfo(b),v}var mA={kernelName:ma,backendName:"cpu",kernelFunc:IK};function NK(r){let{inputs:e,backend:t,attrs:o}=r,{sparseIndices:n,sparseValues:s,defaultValue:a}=e,{outputShape:i}=o,{sliceRank:l,numUpdates:u,sliceSize:c,strides:p,outputSize:m}=N.calculateShapes(s,n,i),f=!1,d=t.bufferSync(n),h=t.bufferSync(s),g=t.data.get(a.dataId).values[0],y=vg(d,h,i,m,c,u,l,p,g,f);return t.makeTensorInfo(i,y.dtype,y.values)}var fA={kernelName:uu,backendName:"cpu",kernelFunc:NK};function SK(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=N.prepareSplitSize(n,s,i),u=new Array(n.shape.length).fill(0),c=n.shape.slice();return l.map(p=>{let m=[...c];m[i]=p;let f=Kn({inputs:{x:n},backend:t,attrs:{begin:u,size:m}});return u[i]+=p,f})}var dA={kernelName:xs,backendName:"cpu",kernelFunc:SK};var TK=$e(En,r=>Math.sqrt(r)),hA={kernelName:En,backendName:"cpu",kernelFunc:TK};var gA={kernelName:fa,backendName:"cpu",kernelFunc:({inputs:r,backend:e})=>{let{x:t}=r,o=e;te(t,"square");let n=o.data.get(t.dataId).values,s=new Float32Array(n.length);for(let i=0;i<n.length;++i){let l=n[i];s[i]=l*l}return{dataId:o.write(s,t.shape,t.dtype),shape:t.shape,dtype:t.dtype}}};var AK=$e(Oo,(r,e)=>{let t=e;return isNaN(r)?NaN:r>0?1:t.alpha}),xA={kernelName:Oo,backendName:"cpu",kernelFunc:AK};function EK(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;te(n,"stridedSlice");let{nonStrided:f,$begin:d,$strides:h,size:g,newShape:y,outShape:b}=nr.sliceInfo(n.shape,s,a,i,l,u,c,p,m),w=Qe({inputs:{x:n},backend:t,attrs:{shape:y}}),k;if(f){let D=Kn({inputs:{x:w},backend:t,attrs:{begin:d,size:g}});k=Qe({inputs:{x:D},backend:t,attrs:{shape:b}}),t.disposeIntermediateTensorInfo(D)}else if(b.some(D=>D===0))k=t.makeTensorInfo(b,n.dtype,[]);else{let D=t.bufferSync(w),A=pk(b,D,h,d);k=t.makeTensorInfo(A.shape,A.dtype,A.values)}let v=Qe({inputs:{x:k},backend:t,attrs:{shape:b}});return t.disposeIntermediateTensorInfo(w),t.disposeIntermediateTensorInfo(k),v}var yA={kernelName:Ai,backendName:"cpu",kernelFunc:EK};var DK=$e(Ei,r=>Math.tan(r)),bA={kernelName:Ei,backendName:"cpu",kernelFunc:DK};var $K=$e(On,r=>Math.tanh(r)),wA={kernelName:On,backendName:"cpu",kernelFunc:$K};function RK(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{reps:s}=o;te(n,"tile");let a=mk(t.bufferSync(n),s);return t.makeTensorInfo(a.shape,a.dtype,a.values)}var kA={kernelName:ko,backendName:"cpu",kernelFunc:RK};function FK(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{k:s,sorted:a}=o;te(n,"topk");let i=t.data.get(n.dataId).values,[l,u]=fk(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 _A={kernelName:Di,backendName:"cpu",kernelFunc:FK};function MK(r){let{inputs:e,attrs:t,backend:o}=r,{image:n,transforms:s}=e,{interpolation:a,fillMode:i,fillValue:l,outputShape:u}=t,[c,p,m,f]=n.shape,[d,h]=u!=null?u:[p,m],g=[c,d,h,f],y=x.computeStrides(n.shape),b=y[0],w=y[1],k=y[2],v=x.getTypedArrayFromDType(n.dtype,x.sizeFromShape(g));v.fill(l);let D=o.data.get(n.dataId).values,A=o.data.get(s.dataId).values;for(let P=0;P<c;++P){let L=s.shape[0]===1?A:A.subarray(P*8,P*8+8);for(let G=0;G<d;++G)for(let j=0;j<h;++j)for(let U=0;U<f;++U){let H,q=L[6]*j+L[7]*G+1;if(q===0)continue;let X=(L[0]*j+L[1]*G+L[2])/q,oe=(L[3]*j+L[4]*G+L[5])/q,Y=vA(X,m,i),re=vA(oe,p,i);switch(a){case"nearest":H=OK(D,p,m,b,w,k,P,re,Y,U,l);break;case"bilinear":H=PK(D,p,m,b,w,k,P,re,Y,U,l);break;default:throw new Error(`Error in Transform: Expect 'nearest' or 'bilinear', but got ${a}`)}let J=P*b+G*w+j*k+U;v[J]=H}return o.makeTensorInfo(g,n.dtype,v)}return{dataId:o.write(v,g,n.dtype),shape:n.shape,dtype:n.dtype}}var CA={kernelName:cu,backendName:"cpu",kernelFunc:MK};function vA(r,e,t){switch(t){case"reflect":return LK(r,e);case"wrap":return zK(r,e);case"nearest":return VK(r,e);case"constant":default:return BK(r,e)}}function LK(r,e){let t=r;if(t<0)if(e<=1)t=0;else{let o=2*e;t<o&&(t=o*Math.trunc(-t/o)+t),t=t<-e?t+o:-t-1}else if(t>e-1)if(e<=1)t=0;else{let o=2*e;t-=o*Math.trunc(t/o),t>=e&&(t=o-t-1)}return x.clamp(0,t,e-1)}function zK(r,e){let t=r;if(t<0)if(e<=1)t=0;else{let o=e-1;t+=e*(Math.trunc(-t/o)+1)}else if(t>e-1)if(e<=1)t=0;else{let o=e-1;t-=e*Math.trunc(t/o)}return x.clamp(0,t,e-1)}function BK(r,e){return r}function VK(r,e){return x.clamp(0,r,e-1)}function hf(r,e,t,o,n,s,a,i,l,u,c){let p=a*o+i*n+l*s+u;return 0<=i&&i<e&&0<=l&&l<t?r[p]:c}function OK(r,e,t,o,n,s,a,i,l,u,c){let p=Math.round(i),m=Math.round(l);return hf(r,e,t,o,n,s,a,p,m,u,c)}function PK(r,e,t,o,n,s,a,i,l,u,c){let p=Math.floor(i),m=Math.floor(l),f=p+1,d=m+1,h=(d-l)*hf(r,e,t,o,n,s,a,p,m,u,c)+(l-m)*hf(r,e,t,o,n,s,a,p,d,u,c),g=(d-l)*hf(r,e,t,o,n,s,a,f,m,u,c)+(l-m)*hf(r,e,t,o,n,s,a,f,d,u,c);return(f-i)*h+(i-p)*g}function GK(r){let{inputs:e,attrs:t,backend:o}=r,{axis:n}=t,{x:s}=e;te(s,"unique");let a=o.data.get(s.dataId).values,{outputValues:i,outputShape:l,indices:u}=dk(a,n,s.shape,s.dtype);return[o.makeTensorInfo(l,s.dtype,i),o.makeTensorInfo([u.length],"int32",u)]}var IA={kernelName:pu,backendName:"cpu",kernelFunc:GK};function WK(r){let{inputs:e,backend:t,attrs:o}=r,{value:n}=e,{axis:s}=o;s<0&&(s+=n.shape.length);let a=n.shape.length,i=n.shape[s],l=new Array(a-1),u=0;for(let f=0;f<a;f++)f!==s&&(l[u++]=n.shape[f]);let c=new Array(a).fill(0),p=n.shape.slice();p[s]=1;let m=new Array(i);for(let f=0;f<m.length;f++){c[s]=f;let d=Kn({inputs:{x:n},backend:t,attrs:{begin:c,size:p}});m[f]=Qe({inputs:{x:d},backend:t,attrs:{shape:l}}),t.disposeIntermediateTensorInfo(d)}return m}var NA={kernelName:ys,backendName:"cpu",kernelFunc:WK};function jK(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,segmentIds:s}=e,{numSegments:a}=o;te(n,"unsortedSegmentSum");let i=n.shape.length,l=s.shape.length,u=[],c=[],p=i-l,m=s;for(let d=0;d<p;++d){let h=pp({inputs:{input:m},backend:t,attrs:{dim:d+1}});m=h,c.push(h)}for(let d=0;d<a;++d){let h=x.createScalarValue(d,"int32"),g=t.makeTensorInfo([],"int32",h),y=Ck({inputs:{a:g,b:m},backend:t}),b=Un({inputs:{x:y},backend:t,attrs:{dtype:"float32"}}),w=sf({inputs:{a:b,b:n},backend:t}),k=qu({inputs:{x:w},backend:t,attrs:{axis:0,keepDims:!1}});u.push(k),c.push(g),c.push(y),c.push(b),c.push(w),c.push(k)}let f=Tk({inputs:u,backend:t,attrs:{axis:0}});return c.forEach(d=>t.disposeIntermediateTensorInfo(d)),f}var SA={kernelName:da,backendName:"cpu",kernelFunc:jK};var UK=[uT,gS,cT,pT,_S,mT,fT,dT,hT,gT,xT,yT,bT,wT,kT,vT,CT,IT,NT,lT,ST,TT,AT,wS,CS,ET,xS,DT,RT,OT,PT,FT,LT,zT,MT,BT,VT,GT,WT,jT,UT,HT,qT,KT,XT,YT,JT,ZT,mf,rT,QT,e1,t1,NS,r1,TS,o1,n1,s1,ES,i1,a1,l1,u1,c1,$S,p1,yS,m1,$T,f1,d1,h1,oT,FS,g1,x1,PS,y1,b1,w1,k1,_1,v1,LS,I1,N1,S1,T1,E1,C1,$1,R1,BS,F1,O1,L1,VS,WS,z1,B1,V1,US,G1,U1,H1,_g,q1,nT,KS,K1,bS,X1,sT,iT,aT,Y1,Z1,J1,Q1,eA,tA,rA,YS,oA,nA,sA,iA,aA,lA,uA,ZS,P1,pA,mA,fA,dA,hA,gA,QS,xA,yA,tT,D1,bA,wA,kA,_A,HS,CA,IA,NA,SA,W1];for(let r of UK)el(r);var EA={};Ke(EA,{assertNotComplex:()=>Rs,bindCanvasToFramebuffer:()=>t6,bindColorTextureToFramebuffer:()=>yf,bindTextureToProgramUniformSampler:()=>Wk,bindTextureUnit:()=>RA,bindVertexBufferToProgramAttribute:()=>Cg,callAndCheck:()=>Ie,canBeRepresented:()=>Dk,createFragmentShader:()=>Rk,createFramebuffer:()=>Bk,createProgram:()=>Fk,createStaticIndexBuffer:()=>Mk,createStaticVertexBuffer:()=>Pk,createTexture:()=>Lk,createVertexShader:()=>$k,getBatchDim:()=>Oa,getExtensionOrThrow:()=>mp,getFramebufferErrorMessage:()=>FA,getMaxTexturesInShader:()=>Hk,getNumChannels:()=>QK,getProgramUniformLocation:()=>Gk,getProgramUniformLocationOrThrow:()=>Vk,getRowsCols:()=>Pa,getShapeAs3D:()=>bf,getTextureShapeFromLogicalShape:()=>jk,getWebGLDisjointQueryTimerVersion:()=>qk,getWebGLErrorMessage:()=>DA,getWebGLMaxTextureSize:()=>Uk,hasExtension:()=>Io,isCapableOfRenderingToFloatTexture:()=>Xk,isDownloadFloatTextureEnabled:()=>Yk,isReshapeFree:()=>dl,isWebGLFenceEnabled:()=>Zk,isWebGLVersionEnabled:()=>Ag,linkProgram:()=>Ok,resetMaxTextureSize:()=>r6,resetMaxTexturesInShader:()=>o6,unbindColorTextureFromFramebuffer:()=>Ig,unbindTextureUnit:()=>e6,validateFramebuffer:()=>fp,validateProgram:()=>xf,validateTextureSize:()=>zk});var Ku={},Ak={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};function Ek(r,e){Ku[r]=e}function Vo(r){if(!(r in Ku)){let t=HK(r);if(t!==null)Ku[r]=t;else return console.log("Could not get context for WebGL version",r),null}let e=Ku[r];return e.isContextLost()?(delete Ku[r],Vo(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),Ku[r])}function qK(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 HK(r){if(r!==1&&r!==2)throw new Error("Cannot get WebGL rendering context, WebGL is disabled.");let e=qK(r);return e.addEventListener("webglcontextlost",t=>{t.preventDefault(),delete Ku[r]},!1),r===1?e.getContext("webgl",Ak)||e.getContext("experimental-webgl",Ak):e.getContext("webgl2",Ak)}var ml;(function(r){r[r.DENSE=0]="DENSE",r[r.SHARED_BATCH=1]="SHARED_BATCH"})(ml||(ml={}));var Er;(function(r){r[r.RENDER=0]="RENDER",r[r.UPLOAD=1]="UPLOAD",r[r.PIXELS=2]="PIXELS",r[r.DOWNLOAD=3]="DOWNLOAD"})(Er||(Er={}));var kr;(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"})(kr||(kr={}));function Xu(r,e){return[e,r]}function TA(r,e){return r*e}function fl(r){let e=x.sizeFromShape(r),t=Math.ceil(e/4);return x.sizeToSquarishShape(t)}function Bi(r,e){return[Math.max(1,Math.ceil(e/2)),Math.max(1,Math.ceil(r/2))]}function AA(r,e){let[t,o]=Bi(r,e);return t*o*4}function gf(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 Ie(r,e){let t=e();return W().getBool("DEBUG")&&KK(r),t}function KK(r){let e=r.getError();if(e!==r.NO_ERROR)throw new Error("WebGL Error: "+DA(r,e))}var XK=596e-10,YK=65504;function Dk(r){return!!(W().getBool("WEBGL_RENDER_FLOAT32_ENABLED")||r===0||XK<Math.abs(r)&&Math.abs(r)<YK)}function DA(r,e){switch(e){case r.NO_ERROR:return"NO_ERROR";case r.INVALID_ENUM:return"INVALID_ENUM";case r.INVALID_VALUE:return"INVALID_VALUE";case r.INVALID_OPERATION:return"INVALID_OPERATION";case r.INVALID_FRAMEBUFFER_OPERATION:return"INVALID_FRAMEBUFFER_OPERATION";case r.OUT_OF_MEMORY:return"OUT_OF_MEMORY";case r.CONTEXT_LOST_WEBGL:return"CONTEXT_LOST_WEBGL";default:return`Unknown error code ${e}`}}function mp(r,e){return Fa(r,()=>r.getExtension(e),'Extension "'+e+'" not supported on this browser.')}function $k(r,e){let t=Fa(r,()=>r.createShader(r.VERTEX_SHADER),"Unable to create vertex WebGLShader.");if(Ie(r,()=>r.shaderSource(t,e)),Ie(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 Rk(r,e){let t=Fa(r,()=>r.createShader(r.FRAGMENT_SHADER),"Unable to create fragment WebGLShader.");if(Ie(r,()=>r.shaderSource(t,e)),Ie(r,()=>r.compileShader(t)),r.getShaderParameter(t,r.COMPILE_STATUS)===!1)throw ZK(e,r.getShaderInfoLog(t)),new Error("Failed to compile fragment shader.");return t}var JK=/ERROR: [0-9]+:([0-9]+):/g;function ZK(r,e){let t=JK.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;p<a.length;p++)i=Math.max(a[p].length,i);let l=a.slice(0,o-1),u=a.slice(o-1,o),c=a.slice(o);console.log(l.join(`
|
|
`)),console.log(e.split(`
|
|
`)[0]),console.log(`%c ${x.rightPad(u[0],i)}`,"border:1px solid red; background-color:#e3d2d2; color:#a61717"),console.log(c.join(`
|
|
`))}function Fk(r){return Fa(r,()=>r.createProgram(),"Unable to create WebGLProgram.")}function Ok(r,e){if(Ie(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 xf(r,e){if(Ie(r,()=>r.validateProgram(e)),r.getProgramParameter(e,r.VALIDATE_STATUS)===!1)throw console.log(r.getProgramInfoLog(e)),new Error("Shader program validation failed.")}function Pk(r,e){let t=Fa(r,()=>r.createBuffer(),"Unable to create WebGLBuffer");return Ie(r,()=>r.bindBuffer(r.ARRAY_BUFFER,t)),Ie(r,()=>r.bufferData(r.ARRAY_BUFFER,e,r.STATIC_DRAW)),t}function Mk(r,e){let t=Fa(r,()=>r.createBuffer(),"Unable to create WebGLBuffer");return Ie(r,()=>r.bindBuffer(r.ELEMENT_ARRAY_BUFFER,t)),Ie(r,()=>r.bufferData(r.ELEMENT_ARRAY_BUFFER,e,r.STATIC_DRAW)),t}function QK(){return W().getNumber("WEBGL_VERSION")===2?1:4}function Lk(r){return Fa(r,()=>r.createTexture(),"Unable to create WebGLTexture.")}function zk(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 Bk(r){return Fa(r,()=>r.createFramebuffer(),"Unable to create WebGLFramebuffer.")}function Cg(r,e,t,o,n,s,a){let i=r.getAttribLocation(e,t);return i===-1?!1:(Ie(r,()=>r.bindBuffer(r.ARRAY_BUFFER,o)),Ie(r,()=>r.vertexAttribPointer(i,n,r.FLOAT,!1,s,a)),Ie(r,()=>r.enableVertexAttribArray(i)),!0)}function RA(r,e,t){$A(r,t),Ie(r,()=>r.activeTexture(r.TEXTURE0+t)),Ie(r,()=>r.bindTexture(r.TEXTURE_2D,e))}function e6(r,e){$A(r,e),Ie(r,()=>r.activeTexture(r.TEXTURE0+e)),Ie(r,()=>r.bindTexture(r.TEXTURE_2D,null))}function Vk(r,e,t){return Fa(r,()=>r.getUniformLocation(e,t),'uniform "'+t+'" not present in program.')}function Gk(r,e,t){return r.getUniformLocation(e,t)}function Wk(r,e,t,o){Ie(r,()=>RA(r,e,o)),Ie(r,()=>r.uniform1i(t,o))}function t6(r){Ie(r,()=>r.bindFramebuffer(r.FRAMEBUFFER,null)),Ie(r,()=>r.viewport(0,0,r.canvas.width,r.canvas.height)),Ie(r,()=>r.scissor(0,0,r.canvas.width,r.canvas.height))}function yf(r,e,t){Ie(r,()=>r.bindFramebuffer(r.FRAMEBUFFER,t)),Ie(r,()=>r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,e,0))}function Ig(r,e){Ie(r,()=>r.bindFramebuffer(r.FRAMEBUFFER,e)),Ie(r,()=>r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,null,0))}function fp(r){let e=r.checkFramebufferStatus(r.FRAMEBUFFER);if(e!==r.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+FA(r,e))}function FA(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 Fa(r,e,t){let o=Ie(r,()=>e());if(o==null)throw new Error(t);return o}function $A(r,e){let t=r.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,o=e+r.TEXTURE0;if(o<r.TEXTURE0||o>t){let n=`[gl.TEXTURE0, gl.TEXTURE${t}]`;throw new Error(`textureUnit must be in ${n}.`)}}function Oa(r,e=2){return x.sizeFromShape(r.slice(0,r.length-e))}function Pa(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 bf(r){let e=[1,1,1];return r.length===0||r.length===1&&r[0]===1||(e=[Oa(r),...Pa(r)]),e}function jk(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=Oa(r),s=2,a=2;return r.length&&([s,a]=Pa(r)),o=n*(s/2)*(a/2),x.sizeToSquarishShape(o).map(i=>i*2)}return x.sizeToSquarishShape(o)}function Ng(r){return r%2==0}function dl(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||Ng(t)&&Ng(o)&&(r[0]===1||e[0]===1))return!0}return r[1]===e[1]&&Ng(r[0])&&Ng(e[0])}var Sg,Tg;function Uk(r){if(Sg==null){let e=Vo(r);Sg=e.getParameter(e.MAX_TEXTURE_SIZE)}return Sg}function r6(){Sg=null}function o6(){Tg=null}function Hk(r){if(Tg==null){let e=Vo(r);Tg=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,Tg)}function qk(r){if(r===0)return 0;let e,t=Vo(r);return Io(t,"EXT_disjoint_timer_query_webgl2")&&r===2?e=2:Io(t,"EXT_disjoint_timer_query")?e=1:e=0,e}function Io(r,e){return r.getExtension(e)!=null}function Ag(r){try{if(Vo(r)!=null)return!0}catch(e){return console.log("Error when getting WebGL context: ",e),!1}return!1}function Xk(r){if(r===0)return!1;let e=Vo(r);if(r===1){if(!Io(e,"OES_texture_float"))return!1}else if(!Io(e,"EXT_color_buffer_float"))return!1;return Kk(e)}function Yk(r){if(r===0)return!1;let e=Vo(r);if(r===1){if(!Io(e,"OES_texture_float")||!Io(e,"WEBGL_color_buffer_float"))return!1}else{if(Io(e,"EXT_color_buffer_float"))return Kk(e);let o="EXT_color_buffer_half_float";if(Io(e,o)){let n=e.getExtension(o);return n6(e,n)}return!1}return Kk(e)}function Kk(r){let e=gf(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 n6(r,e){let t=gf(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 Zk(r){return r!==2?!1:Vo(r).fenceSync!=null}function Rs(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 Pe=W();Pe.registerFlag("HAS_WEBGL",()=>Pe.getNumber("WEBGL_VERSION")>0);Pe.registerFlag("WEBGL_VERSION",()=>Ag(2)?2:Ag(1)?1:0);Pe.registerFlag("WEBGL_CHECK_NUMERICAL_PROBLEMS",()=>!1);Pe.registerFlag("WEBGL_BUFFER_SUPPORTED",()=>Pe.get("WEBGL_VERSION")===2);Pe.registerFlag("WEBGL_CPU_FORWARD",()=>!0);Pe.registerFlag("WEBGL_FORCE_F16_TEXTURES",()=>!1);Pe.registerFlag("WEBGL_PACK",()=>Pe.getBool("HAS_WEBGL"));Pe.registerFlag("WEBGL_PACK_NORMALIZATION",()=>Pe.getBool("WEBGL_PACK"));Pe.registerFlag("WEBGL_PACK_CLIP",()=>Pe.getBool("WEBGL_PACK"));Pe.registerFlag("WEBGL_PACK_DEPTHWISECONV",()=>!1);Pe.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",()=>Pe.getBool("WEBGL_PACK"));Pe.registerFlag("WEBGL_PACK_UNARY_OPERATIONS",()=>Pe.getBool("WEBGL_PACK"));Pe.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",()=>Pe.getBool("WEBGL_PACK"));Pe.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",()=>Pe.getBool("WEBGL_PACK"));Pe.registerFlag("WEBGL_PACK_REDUCE",()=>Pe.getBool("WEBGL_PACK"));Pe.registerFlag("WEBGL_LAZILY_UNPACK",()=>Pe.getBool("WEBGL_PACK"));Pe.registerFlag("WEBGL_CONV_IM2COL",()=>Pe.getBool("WEBGL_PACK"));Pe.registerFlag("WEBGL_MAX_TEXTURE_SIZE",()=>Uk(Pe.getNumber("WEBGL_VERSION")));Pe.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",()=>Hk(Pe.getNumber("WEBGL_VERSION")));Pe.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",()=>{let r=Pe.getNumber("WEBGL_VERSION");return r===0?0:qk(r)});Pe.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",()=>Pe.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&!hu.isMobile());Pe.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE",()=>Xk(Pe.getNumber("WEBGL_VERSION")));Pe.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",()=>Pe.getBool("WEBGL_FORCE_F16_TEXTURES")?!1:Pe.getBool("WEBGL_RENDER_FLOAT32_CAPABLE"));Pe.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",()=>Yk(Pe.getNumber("WEBGL_VERSION")));Pe.registerFlag("WEBGL_FENCE_API_ENABLED",()=>Zk(Pe.getNumber("WEBGL_VERSION")));Pe.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",()=>Pe.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?4:0);Pe.registerFlag("WEBGL_DELETE_TEXTURE_THRESHOLD",()=>-1,r=>{if(r<0&&r!==-1)throw new Error(`WEBGL_DELETE_TEXTURE_THRESHOLD must be -1 (indicating never delete) or at least 0, but got ${r}.`)});Pe.registerFlag("WEBGL_FLUSH_THRESHOLD",()=>hu.isMobile()&&Pe.getBool("IS_CHROME")?1:-1,r=>{if(r<0&&r!==-1)throw new Error(`WEBGL_FLUSH_THRESHOLD must be -1 (indicating never manual flush) or at least 0, but got ${r}.`)});function Rt(){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 Fs(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 dp(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 Eg=`
|
|
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 Jk=class{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=ml.DENSE;let t=fl(e),o=Rt();this.outputShape=e,this.userCode=`
|
|
ivec3 outCoordsFromFlatIndex(int index) {
|
|
${Fs(["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 Qk=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=ml.DENSE;let t=fl(e),o=Rt();this.outputShape=e,this.userCode=`
|
|
ivec3 outCoordsFromFlatIndex(int index) {
|
|
${Fs(["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 e_=class{constructor(e){this.variableNames=["A"],this.outTexUsage=Er.DOWNLOAD;let t=Rt();this.outputShape=e,this.userCode=`
|
|
${Eg}
|
|
|
|
void main() {
|
|
float x = getAAtOutCoords();
|
|
${t.output} = encode_float(x);
|
|
}
|
|
`}};var t_=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=Er.DOWNLOAD;let t=Rt();this.outputShape=e,this.userCode=`
|
|
${Eg}
|
|
|
|
void main() {
|
|
ivec3 coords = getOutputCoords();
|
|
float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));
|
|
${t.output} = encode_float(x);
|
|
}
|
|
`}};var r_=class{constructor(e,t,o=!1){this.variableNames=["A"];let n=Rt(),[s,a]=t;this.outputShape=e;let i="result";o&&(i="floor(result * 255. + 0.5)"),this.userCode=`
|
|
${dp(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 o_=class{constructor(e,t,o=!1){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;let n=Rt(),[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=`
|
|
${dp(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};
|
|
}
|
|
`}};var OA={};Ke(OA,{bindVertexProgramAttributeStreams:()=>m_,createBufferFromOutputTexture:()=>h_,createFloat16MatrixTexture:()=>l_,createFloat16PackedMatrixTexture:()=>p_,createFloat32MatrixTexture:()=>a_,createIndexBuffer:()=>i_,createPackedMatrixTexture:()=>c_,createUnsignedBytesMatrixTexture:()=>u_,createVertexBuffer:()=>s_,createVertexShader:()=>n_,downloadByteEncodedFloatMatrixFromOutputTexture:()=>x_,downloadFloat32MatrixFromBuffer:()=>g_,downloadMatrixFromPackedOutputTexture:()=>b_,downloadPackedMatrixFromBuffer:()=>y_,getInternalFormatForFloat16MatrixTexture:()=>$g,getInternalFormatForFloat16PackedMatrixTexture:()=>Og,getInternalFormatForFloat32MatrixTexture:()=>Dg,getInternalFormatForPackedMatrixTexture:()=>Fg,getInternalFormatForUnsignedBytesMatrixTexture:()=>Rg,uploadDenseMatrixToTexture:()=>f_,uploadPixelDataToTexture:()=>d_});function n_(r){let e=Rt(),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 $k(r,t)}function s_(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 Pk(r,e)}function i_(r){let e=new Uint16Array([0,1,2,2,1,3]);return Mk(r,e)}function wf(r,e,t,o,n,s){zk(e,t);let a=Lk(r),i=r.TEXTURE_2D;return Ie(r,()=>r.bindTexture(i,a)),Ie(r,()=>r.texParameteri(i,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE)),Ie(r,()=>r.texParameteri(i,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE)),Ie(r,()=>r.texParameteri(i,r.TEXTURE_MIN_FILTER,r.NEAREST)),Ie(r,()=>r.texParameteri(i,r.TEXTURE_MAG_FILTER,r.NEAREST)),Ie(r,()=>r.texImage2D(i,0,o,e,t,0,n,s,null)),Ie(r,()=>r.bindTexture(r.TEXTURE_2D,null)),a}function Dg(r){return r.internalFormatFloat}function a_(r,e,t,o){let[n,s]=Xu(e,t);return wf(r,n,s,Dg(o),o.textureFormatFloat,r.FLOAT)}function $g(r){return r.internalFormatHalfFloat}function l_(r,e,t,o){let[n,s]=Xu(e,t);return wf(r,n,s,$g(o),o.textureFormatFloat,o.textureTypeHalfFloat)}function Rg(r){return r.downloadTextureFormat}function u_(r,e,t,o){let[n,s]=Xu(e,t);return wf(r,n,s,Rg(o),r.RGBA,r.UNSIGNED_BYTE)}function Fg(r){return r.internalFormatPackedFloat}function c_(r,e,t,o){let[n,s]=Bi(e,t);return wf(r,n,s,Fg(o),r.RGBA,r.FLOAT)}function Og(r){return r.internalFormatPackedHalfFloat}function p_(r,e,t,o){let[n,s]=Bi(e,t);return wf(r,n,s,Og(o),r.RGBA,o.textureTypeHalfFloat)}function m_(r,e,t){let o=0,n=3*4,s=3*4+2*4;return Ie(r,()=>r.bindBuffer(r.ARRAY_BUFFER,t)),Cg(r,e,"clipSpacePos",t,3,s,o)&&Cg(r,e,"uv",t,2,s,n)}function f_(r,e,t,o,n,s){Ie(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),Ie(r,()=>r.texImage2D(r.TEXTURE_2D,0,l,t,o,0,r.RGBA,i,a)),Ie(r,()=>r.bindTexture(r.TEXTURE_2D,null))}function d_(r,e,t){Ie(r,()=>r.bindTexture(r.TEXTURE_2D,e)),t.data instanceof Uint8Array?Ie(r,()=>r.texImage2D(r.TEXTURE_2D,0,r.RGBA,t.width,t.height,0,r.RGBA,r.UNSIGNED_BYTE,t.data)):Ie(r,()=>r.texImage2D(r.TEXTURE_2D,0,r.RGBA,r.RGBA,r.UNSIGNED_BYTE,t)),Ie(r,()=>r.bindTexture(r.TEXTURE_2D,null))}function h_(r,e,t,o){let n=r.createBuffer();Ie(r,()=>r.bindBuffer(r.PIXEL_PACK_BUFFER,n));let i=4*4*e*t;return Ie(r,()=>r.bufferData(r.PIXEL_PACK_BUFFER,i,r.STREAM_READ)),Ie(r,()=>r.readPixels(0,0,t,e,r.RGBA,r.FLOAT,0)),Ie(r,()=>r.bindBuffer(r.PIXEL_PACK_BUFFER,null)),n}function g_(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 x_(r,e,t,o){let[n,s]=Xu(e,t),a=4,i=new Uint8Array(TA(e*t,a));return Ie(r,()=>r.readPixels(0,0,n,s,o.downloadTextureFormat,r.UNSIGNED_BYTE,i)),new Float32Array(i.buffer)}function y_(r,e,t,o,n,s,a,i){let l=r,u=new Float32Array(AA(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 b_(r,e,t){let o=new Float32Array(e*t*4);return Ie(r,()=>r.readPixels(0,0,t,e,r.RGBA,r.FLOAT,o)),o}var Pg=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,Ek(t,e)):this.gl=Vo(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=mp(this.gl,s),Io(this.gl,a))this.textureHalfFloatExtension=mp(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),Io(this.gl,n))this.colorBufferHalfFloatExtension=mp(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",Io(this.gl,o))this.colorBufferFloatExtension=this.gl.getExtension(o);else if(Io(this.gl,n))this.colorBufferHalfFloatExtension=this.gl.getExtension(n);else throw new Error("GL context does not support color renderable floats");this.vertexBuffer=s_(this.gl),this.indexBuffer=i_(this.gl),this.framebuffer=Bk(this.gl),this.textureConfig=gf(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;Ie(e,()=>e.finish()),Ie(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,null)),Ie(e,()=>e.deleteFramebuffer(this.framebuffer)),Ie(e,()=>e.bindBuffer(e.ARRAY_BUFFER,null)),Ie(e,()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null)),Ie(e,()=>e.deleteBuffer(this.indexBuffer)),this.disposed=!0}createFloat32MatrixTexture(e,t){return this.throwIfDisposed(),a_(this.gl,e,t,this.textureConfig)}createFloat16MatrixTexture(e,t){return this.throwIfDisposed(),l_(this.gl,e,t,this.textureConfig)}createUnsignedBytesMatrixTexture(e,t){return this.throwIfDisposed(),u_(this.gl,e,t,this.textureConfig)}uploadPixelDataToTexture(e,t){this.throwIfDisposed(),d_(this.gl,e,t)}uploadDenseMatrixToTexture(e,t,o,n){this.throwIfDisposed(),f_(this.gl,e,t,o,n,this.textureConfig)}createFloat16PackedMatrixTexture(e,t){return this.throwIfDisposed(),p_(this.gl,e,t,this.textureConfig)}createPackedMatrixTexture(e,t){return this.throwIfDisposed(),c_(this.gl,e,t,this.textureConfig)}deleteMatrixTexture(e){this.throwIfDisposed(),this.outputTexture===e&&(Ig(this.gl,this.framebuffer),this.outputTexture=null),Ie(this.gl,()=>this.gl.deleteTexture(e))}downloadByteEncodedFloatMatrixFromOutputTexture(e,t,o){return this.downloadMatrixDriver(e,()=>x_(this.gl,t,o,this.textureConfig))}downloadPackedMatrixFromBuffer(e,t,o,n,s,a){return y_(this.gl,e,t,o,n,s,a,this.textureConfig)}downloadFloat32MatrixFromBuffer(e,t){return g_(this.gl,e,t)}createBufferFromTexture(e,t,o){this.bindTextureToFrameBuffer(e);let n=h_(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,()=>b_(this.gl,t,o))}createProgram(e){this.throwIfDisposed();let t=this.gl,o=Rk(t,e),n=n_(t),s=Fk(t);return Ie(t,()=>t.attachShader(s,n)),Ie(t,()=>t.attachShader(s,o)),Ok(t,s),this.debug&&xf(t,s),this.vertexAttrsAreBound||(this.setProgram(s),this.vertexAttrsAreBound=m_(t,this.program,this.vertexBuffer)),s}deleteProgram(e){this.throwIfDisposed(),e===this.program&&(this.program=null),e!=null&&Ie(this.gl,()=>this.gl.deleteProgram(e))}setProgram(e){this.throwIfDisposed(),this.program=e,this.program!=null&&this.debug&&xf(this.gl,this.program),Ie(this.gl,()=>this.gl.useProgram(e))}getUniformLocation(e,t,o=!0){return this.throwIfDisposed(),o?Vk(this.gl,e,t):Gk(this.gl,e,t)}getAttributeLocation(e,t){return this.throwIfDisposed(),Ie(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(),Wk(this.gl,e,t,o)}setOutputMatrixTexture(e,t,o){this.setOutputMatrixTextureDriver(e,o,t)}setOutputPackedMatrixTexture(e,t,o){this.throwIfDisposed();let[n,s]=Bi(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&&xf(this.gl,this.program),fp(this.gl)}executeProgram(){this.throwIfDisposed(),this.throwIfNoProgram();let e=this.gl;this.debug&&this.debugValidate(),Ie(e,()=>e.drawElements(e.TRIANGLES,6,e.UNSIGNED_SHORT,0))}blockUntilAllProgramsCompleted(){this.throwIfDisposed(),Ie(this.gl,()=>this.gl.finish())}getQueryTimerExtension(){return this.disjointQueryTimerExtension==null&&(this.disjointQueryTimerExtension=mp(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=s6(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(),yf(this.gl,e,this.framebuffer),this.debug&&fp(this.gl)}unbindTextureToFrameBuffer(){this.outputTexture!=null?(yf(this.gl,this.outputTexture,this.framebuffer),this.debug&&fp(this.gl)):Ig(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;yf(n,e,this.framebuffer),this.debug&&fp(n),this.outputTexture=e,Ie(n,()=>n.viewport(0,0,t,o)),Ie(n,()=>n.scissor(0,0,t,o))}setOutputMatrixWriteRegionDriver(e,t,o,n){this.throwIfDisposed(),Ie(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 s6(r){let e=0;for(;e<r.length&&r[e]();++e);return e-1}var{getBroadcastDims:PA}=N;function MA(r,e,t,o){let n=[];r.forEach(d=>{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=>i6(d,e,o)).join(`
|
|
`),i=e.texShape,l=Rt(),u=u6(l),c,p,m=m6(l);return e.isPacked?(c=a6(e.logicalShape,i),p=p6(l)):(c=l6(e.logicalShape,i),p=c6(l)),o&&(m+=f6),[m,u,p,s,c,a,t].join(`
|
|
`)}function hp(r){let e=r.shapeInfo.logicalShape;switch(e.length){case 0:return d6(r);case 1:return h6(r);case 2:return g6(r);case 3:return x6(r);case 4:return y6(r);case 5:return b6(r);case 6:return w6(r);default:throw new Error(`${e.length}-D input sampling is not yet supported`)}}function LA(r){switch(r.shapeInfo.logicalShape.length){case 0:return k6(r);case 1:return _6(r);case 2:return v6(r);case 3:return C6(r);default:return I6(r)}}function i6(r,e,t=!1){let o="";t?o+=LA(r):o+=hp(r);let n=r.shapeInfo.logicalShape,s=e.logicalShape;return n.length<=s.length&&(t?o+=N6(r,e):o+=S6(r,e)),o}function a6(r,e){switch(r.length){case 0:return zA();case 1:return T6(r,e);case 2:return D6(r,e);case 3:return A6(r,e);default:return E6(r,e)}}function l6(r,e){switch(r.length){case 0:return zA();case 1:return $6(r,e);case 2:return M6(r,e);case 3:return R6(r,e);case 4:return F6(r,e);case 5:return O6(r,e);case 6:return P6(r,e);default:throw new Error(`${r.length}-D output sampling is not yet supported`)}}function u6(r){return`
|
|
float sampleTexture(sampler2D textureSampler, vec2 uv) {
|
|
return ${r.texture2D}(textureSampler, uv).r;
|
|
}
|
|
`}function c6(r){return`
|
|
void setOutput(float val) {
|
|
${r.output} = vec4(val, 0, 0, 0);
|
|
}
|
|
`}function p6(r){return`
|
|
void setOutput(vec4 val) {
|
|
${r.output} = val;
|
|
}
|
|
`}function m6(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);
|
|
}
|
|
|
|
${L6}
|
|
${z6}
|
|
${B6}
|
|
`}var L6=`
|
|
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);
|
|
}
|
|
`,z6=`
|
|
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);
|
|
}
|
|
`,B6=`
|
|
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);
|
|
}
|
|
`,f6=`
|
|
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 zA(){return`
|
|
int getOutputCoords() {
|
|
return 0;
|
|
}
|
|
`}function T6(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 $6(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 A6(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 R6(r,e){let t=Fs(["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 E6(r,e){let t=[Math.ceil(e[0]/2),Math.ceil(e[1]/2)],o=Math.ceil(r[r.length-1]/2),n=o*Math.ceil(r[r.length-2]/2),s=n,a="",i="b, r, c";for(let l=2;l<r.length-1;l++)s*=r[r.length-l-1],a=`
|
|
int b${l} = index / ${s};
|
|
index -= b${l} * ${s};
|
|
`+a,i=`b${l}, `+i;return`
|
|
ivec${r.length} getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(${t[0]}, ${t[1]}));
|
|
int index = resTexRC.x * ${t[1]} + resTexRC.y;
|
|
|
|
${a}
|
|
|
|
int b = index / ${n};
|
|
index -= b * ${n};
|
|
|
|
int r = 2 * (index / ${o});
|
|
int c = imod(index, ${o}) * 2;
|
|
|
|
return ivec${r.length}(${i});
|
|
}
|
|
`}function F6(r,e){let t=Fs(["r","c","d","d2"],r);return`
|
|
ivec4 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(${e[0]}, ${e[1]}));
|
|
int index = resTexRC.x * ${e[1]} + resTexRC.y;
|
|
${t}
|
|
return ivec4(r, c, d, d2);
|
|
}
|
|
`}function O6(r,e){let t=Fs(["r","c","d","d2","d3"],r);return`
|
|
ivec5 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx * vec2(${e[0]},
|
|
${e[1]}));
|
|
|
|
int index = resTexRC.x * ${e[1]} + resTexRC.y;
|
|
|
|
${t}
|
|
|
|
ivec5 outShape = ivec5(r, c, d, d2, d3);
|
|
return outShape;
|
|
}
|
|
`}function P6(r,e){let t=Fs(["r","c","d","d2","d3","d4"],r);return`
|
|
ivec6 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(${e[0]}, ${e[1]}));
|
|
int index = resTexRC.x * ${e[1]} + resTexRC.y;
|
|
|
|
${t}
|
|
|
|
ivec6 result = ivec6(r, c, d, d2, d3, d4);
|
|
return result;
|
|
}
|
|
`}function D6(r,e){let t=[Math.ceil(e[0]/2),Math.ceil(e[1]/2)];if(x.arraysEqual(r,e))return`
|
|
ivec2 getOutputCoords() {
|
|
return 2 * ivec2(resultUV.yx * vec2(${t[0]}, ${t[1]}));
|
|
}
|
|
`;let o=Math.ceil(r[1]/2);return`
|
|
ivec2 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(${t[0]}, ${t[1]}));
|
|
|
|
int index = resTexRC.x * ${t[1]} + resTexRC.y;
|
|
int r = 2 * (index / ${o});
|
|
int c = imod(index, ${o}) * 2;
|
|
|
|
return ivec2(r, c);
|
|
}
|
|
`}function M6(r,e){return x.arraysEqual(r,e)?`
|
|
ivec2 getOutputCoords() {
|
|
return ivec2(resultUV.yx * vec2(${e[0]}, ${e[1]}));
|
|
}
|
|
`:r[1]===1?`
|
|
ivec2 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(${e[0]}, ${e[1]}));
|
|
int index = resTexRC.x * ${e[1]} + resTexRC.y;
|
|
return ivec2(index, 0);
|
|
}
|
|
`:r[0]===1?`
|
|
ivec2 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(${e[0]}, ${e[1]}));
|
|
int index = resTexRC.x * ${e[1]} + resTexRC.y;
|
|
return ivec2(0, index);
|
|
}
|
|
`:`
|
|
ivec2 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(${e[0]}, ${e[1]}));
|
|
int index = resTexRC.x * ${e[1]} + resTexRC.y;
|
|
int r = index / ${r[1]};
|
|
int c = index - r * ${r[1]};
|
|
return ivec2(r, c);
|
|
}
|
|
`}function Yu(r){return`offset${r}`}function k6(r){let e=r.name,t="get"+e.charAt(0).toUpperCase()+e.slice(1),o=Rt();return`
|
|
vec4 ${t}() {
|
|
return ${o.texture2D}(${e}, halfCR);
|
|
}
|
|
`}function d6(r){let e=r.name,t="get"+e.charAt(0).toUpperCase()+e.slice(1);if(r.shapeInfo.isUniform)return`float ${t}() {return ${e};}`;let[o,n]=r.shapeInfo.texShape;if(o===1&&n===1)return`
|
|
float ${t}() {
|
|
return sampleTexture(${e}, halfCR);
|
|
}
|
|
`;let[s,a]=r.shapeInfo.texShape,i=Yu(e);return`
|
|
float ${t}() {
|
|
vec2 uv = uvFromFlat(${s}, ${a}, ${i});
|
|
return sampleTexture(${e}, uv);
|
|
}
|
|
`}function _6(r){let e=r.name,t="get"+e.charAt(0).toUpperCase()+e.slice(1),o=r.shapeInfo.texShape,n=[Math.ceil(o[0]/2),Math.ceil(o[1]/2)],s=Rt();return`
|
|
vec4 ${t}(int index) {
|
|
vec2 uv = packedUVfrom1D(
|
|
${n[0]}, ${n[1]}, index);
|
|
return ${s.texture2D}(${e}, uv);
|
|
}
|
|
`}function h6(r){let e=r.name,t="get"+e.charAt(0).toUpperCase()+e.slice(1);if(r.shapeInfo.isUniform)return`
|
|
float ${t}(int index) {
|
|
${gp(r)}
|
|
}
|
|
`;let o=r.shapeInfo.texShape,n=o[0],s=o[1];if(s===1&&n===1)return`
|
|
float ${t}(int index) {
|
|
return sampleTexture(${e}, halfCR);
|
|
}
|
|
`;let a=Yu(e);return s===1?`
|
|
float ${t}(int index) {
|
|
vec2 uv = vec2(0.5, (float(index + ${a}) + 0.5) / ${n}.0);
|
|
return sampleTexture(${e}, uv);
|
|
}
|
|
`:n===1?`
|
|
float ${t}(int index) {
|
|
vec2 uv = vec2((float(index + ${a}) + 0.5) / ${s}.0, 0.5);
|
|
return sampleTexture(${e}, uv);
|
|
}
|
|
`:`
|
|
float ${t}(int index) {
|
|
vec2 uv = uvFromFlat(${n}, ${s}, index + ${a});
|
|
return sampleTexture(${e}, uv);
|
|
}
|
|
`}function v6(r){let e=r.shapeInfo.logicalShape,t=r.name,o="get"+t.charAt(0).toUpperCase()+t.slice(1),n=r.shapeInfo.texShape,s=n[0],a=n[1],i=Rt();if(n!=null&&x.arraysEqual(e,n))return`
|
|
vec4 ${o}(int row, int col) {
|
|
vec2 uv = (vec2(col, row) + halfCR) / vec2(${a}.0, ${s}.0);
|
|
|
|
return ${i.texture2D}(${t}, uv);
|
|
}
|
|
`;let l=[Math.ceil(n[0]/2),Math.ceil(n[1]/2)],u=Math.ceil(e[1]/2);return`
|
|
vec4 ${o}(int row, int col) {
|
|
vec2 uv = packedUVfrom2D(${u}, ${l[0]}, ${l[1]}, row, col);
|
|
return ${i.texture2D}(${t}, uv);
|
|
}
|
|
`}function g6(r){let e=r.shapeInfo.logicalShape,t=r.name,o="get"+t.charAt(0).toUpperCase()+t.slice(1),n=r.shapeInfo.texShape;if(n!=null&&x.arraysEqual(e,n)){let p=n[0],m=n[1];return`
|
|
float ${o}(int row, int col) {
|
|
vec2 uv = (vec2(col, row) + halfCR) / vec2(${m}.0, ${p}.0);
|
|
return sampleTexture(${t}, uv);
|
|
}
|
|
`}let{newShape:s,keptDims:a}=x.squeezeShape(e),i=s;if(i.length<e.length){let p=xp(r,i),m=["row","col"];return`
|
|
${hp(p)}
|
|
float ${o}(int row, int col) {
|
|
return ${o}(${yp(m,a)});
|
|
}
|
|
`}if(r.shapeInfo.isUniform)return`
|
|
float ${o}(int row, int col) {
|
|
int index = round(dot(vec2(row, col), vec2(${e[1]}, 1)));
|
|
${gp(r)}
|
|
}
|
|
`;let l=n[0],u=n[1],c=Yu(t);return u===1?`
|
|
float ${o}(int row, int col) {
|
|
float index = dot(vec3(row, col, ${c}), vec3(${e[1]}, 1, 1));
|
|
vec2 uv = vec2(0.5, (index + 0.5) / ${l}.0);
|
|
return sampleTexture(${t}, uv);
|
|
}
|
|
`:l===1?`
|
|
float ${o}(int row, int col) {
|
|
float index = dot(vec3(row, col, ${c}), vec3(${e[1]}, 1, 1));
|
|
vec2 uv = vec2((index + 0.5) / ${u}.0, 0.5);
|
|
return sampleTexture(${t}, uv);
|
|
}
|
|
`:`
|
|
float ${o}(int row, int col) {
|
|
// Explicitly use integer operations as dot() only works on floats.
|
|
int index = row * ${e[1]} + col + ${c};
|
|
vec2 uv = uvFromFlat(${l}, ${u}, index);
|
|
return sampleTexture(${t}, uv);
|
|
}
|
|
`}function C6(r){let e=r.shapeInfo.logicalShape,t=r.name,o="get"+t.charAt(0).toUpperCase()+t.slice(1),n=r.shapeInfo.texShape,s=[Math.ceil(n[0]/2),Math.ceil(n[1]/2)];if(e[0]===1){let p=e.slice(1),m=[1,2],f=xp(r,p),d=["b","row","col"];return`
|
|
${LA(f)}
|
|
vec4 ${o}(int b, int row, int col) {
|
|
return ${o}(${yp(d,m)});
|
|
}
|
|
`}let a=s[0],i=s[1],l=Math.ceil(e[2]/2),u=l*Math.ceil(e[1]/2),c=Rt();return`
|
|
vec4 ${o}(int b, int row, int col) {
|
|
vec2 uv = packedUVfrom3D(
|
|
${a}, ${i}, ${u}, ${l}, b, row, col);
|
|
return ${c.texture2D}(${t}, uv);
|
|
}
|
|
`}function x6(r){let e=r.shapeInfo.logicalShape,t=r.name,o="get"+t.charAt(0).toUpperCase()+t.slice(1),n=e[1]*e[2],s=e[2],{newShape:a,keptDims:i}=x.squeezeShape(e),l=a;if(l.length<e.length){let d=xp(r,l),h=["row","col","depth"];return`
|
|
${hp(d)}
|
|
float ${o}(int row, int col, int depth) {
|
|
return ${o}(${yp(h,i)});
|
|
}
|
|
`}if(r.shapeInfo.isUniform)return`
|
|
float ${o}(int row, int col, int depth) {
|
|
int index = round(dot(vec3(row, col, depth),
|
|
vec3(${n}, ${s}, 1)));
|
|
${gp(r)}
|
|
}
|
|
`;let u=r.shapeInfo.texShape,c=u[0],p=u[1],m=r.shapeInfo.flatOffset;if(p===n&&m==null)return`
|
|
float ${o}(int row, int col, int depth) {
|
|
float texR = float(row);
|
|
float texC = dot(vec2(col, depth), vec2(${s}, 1));
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${p}.0, ${c}.0);
|
|
return sampleTexture(${t}, uv);
|
|
}
|
|
`;if(p===s&&m==null)return`
|
|
float ${o}(int row, int col, int depth) {
|
|
float texR = dot(vec2(row, col), vec2(${e[1]}, 1));
|
|
float texC = float(depth);
|
|
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${p}.0, ${c}.0);
|
|
return sampleTexture(${t}, uv);
|
|
}
|
|
`;let f=Yu(t);return`
|
|
float ${o}(int row, int col, int depth) {
|
|
// Explicitly use integer operations as dot() only works on floats.
|
|
int index = row * ${n} + col * ${s} + depth + ${f};
|
|
vec2 uv = uvFromFlat(${c}, ${p}, index);
|
|
return sampleTexture(${t}, uv);
|
|
}
|
|
`}function I6(r){let e=r.shapeInfo.logicalShape,t=e.length,o=r.name,n="get"+o.charAt(0).toUpperCase()+o.slice(1),s=r.shapeInfo.texShape,a=[Math.ceil(s[0]/2),Math.ceil(s[1]/2)],i=a[0],l=a[1],u=Math.ceil(e[t-1]/2),c=u*Math.ceil(e[t-2]/2),p="int b, int row, int col",m=`b * ${c} + (row / 2) * ${u} + (col / 2)`;for(let d=2;d<t-1;d++)p=`int b${d}, `+p,c*=e[t-d-1],m=`b${d} * ${c} + `+m;let f=Rt();return`
|
|
vec4 ${n}(${p}) {
|
|
int index = ${m};
|
|
int texR = index / ${l};
|
|
int texC = index - texR * ${l};
|
|
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${l}, ${i});
|
|
return ${f.texture2D}(${o}, uv);
|
|
}
|
|
`}function y6(r){let e=r.shapeInfo.logicalShape,t=r.name,o="get"+t.charAt(0).toUpperCase()+t.slice(1),n=e[3],s=e[2]*n,a=e[1]*s,{newShape:i,keptDims:l}=x.squeezeShape(e);if(i.length<e.length){let d=xp(r,i),h=["row","col","depth","depth2"];return`
|
|
${hp(d)}
|
|
float ${o}(int row, int col, int depth, int depth2) {
|
|
return ${o}(${yp(h,l)});
|
|
}
|
|
`}if(r.shapeInfo.isUniform)return`
|
|
float ${o}(int row, int col, int depth, int depth2) {
|
|
int index = round(dot(vec4(row, col, depth, depth2),
|
|
vec4(${a}, ${s}, ${n}, 1)));
|
|
${gp(r)}
|
|
}
|
|
`;let u=r.shapeInfo.flatOffset,c=r.shapeInfo.texShape,p=c[0],m=c[1];if(m===a&&u==null)return`
|
|
float ${o}(int row, int col, int depth, int depth2) {
|
|
float texR = float(row);
|
|
float texC =
|
|
dot(vec3(col, depth, depth2),
|
|
vec3(${s}, ${n}, 1));
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${m}.0, ${p}.0);
|
|
return sampleTexture(${t}, uv);
|
|
}
|
|
`;if(m===n&&u==null)return`
|
|
float ${o}(int row, int col, int depth, int depth2) {
|
|
float texR = dot(vec3(row, col, depth),
|
|
vec3(${e[1]*e[2]}, ${e[2]}, 1));
|
|
float texC = float(depth2);
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${m}.0, ${p}.0);
|
|
return sampleTexture(${t}, uv);
|
|
}
|
|
`;let f=Yu(t);return`
|
|
float ${o}(int row, int col, int depth, int depth2) {
|
|
// Explicitly use integer operations as dot() only works on floats.
|
|
int index = row * ${a} + col * ${s} +
|
|
depth * ${n} + depth2;
|
|
vec2 uv = uvFromFlat(${p}, ${m}, index + ${f});
|
|
return sampleTexture(${t}, uv);
|
|
}
|
|
`}function b6(r){let e=r.shapeInfo.logicalShape,t=r.name,o="get"+t.charAt(0).toUpperCase()+t.slice(1),n=e[4],s=e[3]*n,a=e[2]*s,i=e[1]*a,{newShape:l,keptDims:u}=x.squeezeShape(e);if(l.length<e.length){let h=xp(r,l),g=["row","col","depth","depth2","depth3"];return`
|
|
${hp(h)}
|
|
float ${o}(int row, int col, int depth, int depth2, int depth3) {
|
|
return ${o}(${yp(g,u)});
|
|
}
|
|
`}if(r.shapeInfo.isUniform)return`
|
|
float ${o}(int row, int col, int depth, int depth2, int depth3) {
|
|
float index = dot(
|
|
vec4(row, col, depth, depth2),
|
|
vec4(${i}, ${a}, ${s}, ${n})) +
|
|
depth3;
|
|
${gp(r)}
|
|
}
|
|
`;let c=r.shapeInfo.flatOffset,p=r.shapeInfo.texShape,m=p[0],f=p[1];if(f===i&&c==null)return`
|
|
float ${o}(int row, int col, int depth, int depth2, int depth3) {
|
|
int texR = row;
|
|
float texC = dot(vec4(col, depth, depth2, depth3),
|
|
vec4(${a}, ${s}, ${n}, 1));
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${f}.0, ${m}.0);
|
|
return sampleTexture(${t}, uv);
|
|
}
|
|
`;if(f===n&&c==null)return`
|
|
float ${o}(int row, int col, int depth, int depth2, int depth3) {
|
|
float texR = dot(
|
|
vec4(row, col, depth, depth2),
|
|
vec4(${e[1]*e[2]*e[3]},
|
|
${e[2]*e[3]}, ${e[3]}, 1));
|
|
int texC = depth3;
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${f}.0, ${m}.0);
|
|
return sampleTexture(${t}, uv);
|
|
}
|
|
`;let d=Yu(t);return`
|
|
float ${o}(int row, int col, int depth, int depth2, int depth3) {
|
|
// Explicitly use integer operations as dot() only works on floats.
|
|
int index = row * ${i} + col * ${a} + depth * ${s} +
|
|
depth2 * ${n} + depth3 + ${d};
|
|
vec2 uv = uvFromFlat(${m}, ${f}, index);
|
|
return sampleTexture(${t}, uv);
|
|
}
|
|
`}function w6(r){let e=r.shapeInfo.logicalShape,t=r.name,o="get"+t.charAt(0).toUpperCase()+t.slice(1),{newShape:n,keptDims:s}=x.squeezeShape(e);if(n.length<e.length){let g=xp(r,n),y=["row","col","depth","depth2","depth3","depth4"];return`
|
|
${hp(g)}
|
|
float ${o}(int row, int col, int depth,
|
|
int depth2, int depth3, int depth4) {
|
|
return ${o}(${yp(y,s)});
|
|
}
|
|
`}let a=e[5],i=e[4]*a,l=e[3]*i,u=e[2]*l,c=e[1]*u;if(r.shapeInfo.isUniform)return`
|
|
float ${o}(int row, int col, int depth,
|
|
int depth2, int depth3, int depth4) {
|
|
int index = round(dot(
|
|
vec4(row, col, depth, depth2),
|
|
vec4(${c}, ${u}, ${l}, ${i})) +
|
|
dot(
|
|
vec2(depth3, depth4),
|
|
vec2(${a}, 1)));
|
|
${gp(r)}
|
|
}
|
|
`;let p=r.shapeInfo.flatOffset,m=r.shapeInfo.texShape,f=m[0],d=m[1];if(d===c&&p==null)return`
|
|
float ${o}(int row, int col, int depth,
|
|
int depth2, int depth3, int depth4) {
|
|
int texR = row;
|
|
float texC = dot(vec4(col, depth, depth2, depth3),
|
|
vec4(${u}, ${l}, ${i}, ${a})) +
|
|
float(depth4);
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${d}.0, ${f}.0);
|
|
return sampleTexture(${t}, uv);
|
|
}
|
|
`;if(d===a&&p==null)return`
|
|
float ${o}(int row, int col, int depth,
|
|
int depth2, int depth3, int depth4) {
|
|
float texR = dot(vec4(row, col, depth, depth2),
|
|
vec4(${e[1]*e[2]*e[3]*e[4]},
|
|
${e[2]*e[3]*e[4]},
|
|
${e[3]*e[4]},
|
|
${e[4]})) + float(depth3);
|
|
int texC = depth4;
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${d}.0, ${f}.0);
|
|
return sampleTexture(${t}, uv);
|
|
}
|
|
`;let h=Yu(t);return`
|
|
float ${o}(int row, int col, int depth,
|
|
int depth2, int depth3, int depth4) {
|
|
// Explicitly use integer operations as dot() only works on floats.
|
|
int index = row * ${c} + col * ${u} + depth * ${l} +
|
|
depth2 * ${i} + depth3 * ${a} + depth4 + ${h};
|
|
vec2 uv = uvFromFlat(${f}, ${d}, index);
|
|
return sampleTexture(${t}, uv);
|
|
}
|
|
`}function gp(r){let e=r.name,t=x.sizeFromShape(r.shapeInfo.logicalShape);return t<2?`return ${e};`:`
|
|
for (int i = 0; i < ${t}; i++) {
|
|
if (i == index) {
|
|
return ${e}[i];
|
|
}
|
|
}
|
|
`}function N6(r,e){let t=r.name,o=t.charAt(0).toUpperCase()+t.slice(1),n="get"+o+"AtOutCoords",s=r.shapeInfo.logicalShape.length,a=e.logicalShape.length,i=PA(r.shapeInfo.logicalShape,e.logicalShape),l=Le(a),u=a-s,c,p=["x","y","z","w","u","v"];s===0?c="":a<2&&i.length>=1?c="coords = 0;":c=i.map(b=>`coords.${p[b+u]} = 0;`).join(`
|
|
`);let m="";a<2&&s>0?m="coords":m=r.shapeInfo.logicalShape.map((b,w)=>`coords.${p[w+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,w=s-1;i.indexOf(b)>-1&&i.indexOf(w)>-1?f="return vec4(outputValue.x);":i.indexOf(b)>-1?f="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":i.indexOf(w)>-1&&(f="return vec4(outputValue.xx, outputValue.zz);")}return`
|
|
vec4 ${n}() {
|
|
${l} coords = getOutputCoords();
|
|
${c}
|
|
vec4 outputValue = get${o}(${m});
|
|
${f}
|
|
}
|
|
`}function S6(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=Le(l),c=PA(r.shapeInfo.logicalShape,e.logicalShape),p=l-i,m,f=["x","y","z","w","u","v"];i===0?m="":l<2&&c.length>=1?m="coords = 0;":m=c.map(h=>`coords.${f[h+p]} = 0;`).join(`
|
|
`);let d="";return l<2&&i>0?d="coords":d=r.shapeInfo.logicalShape.map((h,g)=>`coords.${f[g+p]}`).join(", "),`
|
|
float ${n}() {
|
|
${u} coords = getOutputCoords();
|
|
${m}
|
|
return get${o}(${d});
|
|
}
|
|
`}function Le(r){if(r<=1)return"int";if(r===2)return"ivec2";if(r===3)return"ivec3";if(r===4)return"ivec4";if(r===5)return"ivec5";if(r===6)return"ivec6";throw Error(`GPU for rank ${r} is not yet supported`)}function xp(r,e){let t=JSON.parse(JSON.stringify(r));return t.shapeInfo.logicalShape=e,t}function yp(r,e){return e.map(t=>r[t]).join(", ")}function BA(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=MA(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<e.variableNames.length;f++){let d=e.variableNames[f],h=!1;m[d]=r.getUniformLocation(u,d,h),m[`offset${d}`]=r.getUniformLocation(u,`offset${d}`,h)}return{program:e,source:l,webGLProgram:u,uniformLocations:m,inShapeInfos:a,outShapeInfo:i,infLoc:c,nanLoc:p}}function VA(r,e){if(r.length!==e.length)throw Error(`Binary was compiled with ${r.length} inputs, but was executed with ${e.length} inputs`);r.forEach((t,o)=>{let n=t.logicalShape,s=e[o],a=s.shape;if(!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 GA(r,e,t,o,n){VA(e.inShapeInfos,t),VA([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 WA(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:jA,bincountImpl:Mg,bincountReduceImpl:UA,ceilImpl:HA,concatImpl:qA,expImpl:KA,expm1Impl:XA,floorImpl:YA,gatherV2Impl:ZA,greaterImpl:JA,lessImpl:QA,linSpaceImpl:eE,logImpl:tE,maxImpl:rE,maximumImpl:oE,minimumImpl:nE,multiplyImpl:sE,negImpl:iE,prodImpl:aE,rangeImpl:lE,rsqrtImpl:uE,simpleAbsImpl:Lg,sliceImpl:cE,stridedSliceImpl:pE,subImpl:mE,tileImpl:fE,topKImpl:dE,transposeImpl:bp,uniqueImpl:hE}=yg;function w_(r,e){return["x","y","z","w","u","v"].slice(0,e).map(t=>`${r}.${t}`)}function Wt(r,e){return e===1?[r]:w_(r,e)}function gE(r,e){if(r===1)return"rc";let t="";for(let o=0;o<r;o++)t+=e[o],o<r-1&&(t+=",");return t}var k_=class{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outputShape=e;let t=e.length;if(t===0)this.userCode=`
|
|
void main() {
|
|
setOutput(vec4(getA(), 0., 0., 0.));
|
|
}
|
|
`;else{let o=Wt("rc",t),n=Le(t),s=V6(t,e,o),a=G6(t,e[e.length-1],e[e.length-2],o),i=W6(e,o);this.userCode=`
|
|
void main() {
|
|
${n} rc = getOutputCoords();
|
|
|
|
if(${s}) {
|
|
setOutput(vec4(0));
|
|
} else {
|
|
${a}
|
|
|
|
setOutput(vec4(${i}));
|
|
}
|
|
}
|
|
`}}};function j6(r,e){let t=[];for(let o=0;o<=1;o++)for(let n=0;n<=1;n++){let s=`${o===0?"r":"rp1"}, ${n===0?"c":"cp1"}`;for(let a=2;a<r;a++)s=`${e[e.length-1-a]},`+s;t.push(s)}return t}function V6(r,e,t){if(r===1)return`rc > ${e[0]}`;let o="";for(let n=r-2;n<r;n++)o+=`${t[n]} >= ${e[n]}`,n<r-1&&(o+="||");return o}function G6(r,e,t,o){if(r===1)return"";let n=o.slice(-2);return`
|
|
int r = ${n[0]};
|
|
int c = ${n[1]};
|
|
int rp1 = r + 1;
|
|
int cp1 = c + 1;
|
|
|
|
bool cEdge = cp1 >= ${e};
|
|
bool rEdge = rp1 >= ${t};
|
|
`}function W6(r,e){let t=r.length,o=j6(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 kf=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=`
|
|
${U6(t)}
|
|
${dp(e)}
|
|
|
|
void main() {
|
|
ivec3 rc = getOutputCoords();
|
|
|
|
vec4 result = vec4(0.);
|
|
|
|
ivec3 thisRC;
|
|
int rows = ${e[1]};
|
|
int cols = ${e[2]};
|
|
|
|
${o}
|
|
|
|
setOutput(result);
|
|
}
|
|
`}};function U6(r){return`
|
|
ivec3 inputCoordsFromReshapedOutCoords(int index) {
|
|
${Fs(["r","c","d"],r)}
|
|
return ivec3(r, c, d);
|
|
}
|
|
`}var __=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=yE(t,o),s=bE(e,n,o);s in this.freeTextures||(this.freeTextures[s]=[]),s in this.usedTextures||(this.usedTextures[s]=[]);let a=xE(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===kr.PACKED_2X2_FLOAT32?i=this.gpgpu.createPackedMatrixTexture(e[0],e[1]):n===kr.PACKED_2X2_FLOAT16?i=this.gpgpu.createFloat16PackedMatrixTexture(e[0],e[1]):n===kr.UNPACKED_FLOAT32?i=this.gpgpu.createFloat32MatrixTexture(e[0],e[1]):n===kr.UNPACKED_FLOAT16?i=this.gpgpu.createFloat16MatrixTexture(e[0],e[1]):n===kr.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=yE(o,n),a=bE(t,s,n);a in this.freeTextures||(this.freeTextures[a]=[]);let i=xE(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 H6(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 xE(r,e,t,o,n){let s=q6(e,o),a;if(n){let[l,u]=Bi(r[0],r[1]);a=l*u}else{let[l,u]=Xu(r[0],r[1]);a=l*u}let i=H6(t,s);return a*i}function q6(r,e){switch(r){case kr.PACKED_2X2_FLOAT32:return Fg(e);case kr.PACKED_2X2_FLOAT16:return Og(e);case kr.UNPACKED_FLOAT32:return Dg(e);case kr.UNPACKED_FLOAT16:return $g(e);case kr.PACKED_4X1_UNSIGNED_BYTE:return Rg(e);default:throw new Error(`Unknown physical texture type ${r}`)}}function K6(r){return W().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?r?kr.PACKED_2X2_FLOAT32:kr.UNPACKED_FLOAT32:r?kr.PACKED_2X2_FLOAT16:kr.UNPACKED_FLOAT16}function yE(r,e){if(r===Er.UPLOAD)return kr.PACKED_2X2_FLOAT32;if(r===Er.RENDER||r==null)return K6(e);if(r===Er.DOWNLOAD||r===Er.PIXELS)return kr.PACKED_4X1_UNSIGNED_BYTE;throw new Error(`Unknown logical texture type ${r}`)}function bE(r,e,t){return`${r[0]}_${r[1]}_${e}_${t}`}var ao=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);
|
|
}
|
|
`}},hr="if (isnan(x)) return x;",wE="return x;",v_="return abs(x);";var kE="return (x >= 0.0) ? x : (exp(x) - 1.0);",_E=hr+`
|
|
return (x < 0.0) ? 0.0 : x;
|
|
`,vE=hr+`
|
|
return (x < 0.0) ? 0.0 : min(6.0, x);
|
|
`,_f="return x;";var CE="return x;",IE=`
|
|
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;
|
|
`,NE=`
|
|
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;
|
|
`,SE=`
|
|
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;
|
|
`,Os=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 C_=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=e;let t=e.length,o=Wt("rc",t),n=Le(t),s=gE(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 X6=Tr.whereImpl,Y6=1e-7,Z6=1e-4,zg={};function J6(r){return r in zg||(zg[r]={}),zg[r]}var Q6=128,e5=600;function t5(){return W().global.screen==null?1024:W().global.screen.height*W().global.screen.width*window.devicePixelRatio*e5/1024/1024}var Zu=class extends js{constructor(e){super();if(this.pendingRead=new WeakMap,this.pendingDisposal=new WeakSet,this.dataRefCount=new WeakMap,this.numBytesInGPU=0,this.uploadWaitMs=0,this.downloadWaitMs=0,this.lastGlFlushTime=0,this.warnedAboutMemory=!1,this.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=Vo(W().getNumber("WEBGL_VERSION"));this.binaryCache=J6(W().getNumber("WEBGL_VERSION")),this.gpgpu=new Pg(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 __(this.gpgpu),this.numMBBeforeWarning=t5(),this.texData=new Za(this,Mo())}nextDataId(){return Zu.nextDataId++}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={id:this.nextDataId()};return this.texData.set(n,{shape:t,dtype:o,values:e,usage:Er.UPLOAD,refCount:1}),n}refCount(e){return this.texData.has(e)?this.texData.get(e).refCount:0}incRef(e){let t=this.texData.get(e);t.refCount++}decRef(e){if(this.texData.has(e)){let t=this.texData.get(e);t.refCount--}}move(e,t,o,n,s){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:Er.UPLOAD,refCount:s})}disposeIntermediateTensorInfo(e){this.disposeData(e.dataId)}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 Os(i,_f):m=new ao(i,_f);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=N.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 Os(n,_f):d=new ao(n,_f);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,...fl(n))}this.pendingRead.set(e,[]),a!=="complex64"&&await this.gpgpu.createAndWaitForFence();let p;if(a==="complex64"){let d=await Promise.all([this.read(i.real.dataId),this.read(i.imag.dataId)]),h=d[0],g=d[1];p=N.mergeRealAndImagArrays(h,g)}else if(u==null)p=this.getValuesFromTexture(e);else{let d=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)&&Mo().removeDataId(e,this),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 ve(e.shape,e.dtype,o)}checkNumericalProblems(e){if(e!=null)for(let t=0;t<e.length;t++){let o=e[t];if(!Dk(o))throw W().getBool("WEBGL_RENDER_FLOAT32_CAPABLE")?Error(`The value ${o} cannot be represented with your current settings. Consider enabling float32 rendering: 'tf.env().set('WEBGL_RENDER_FLOAT32_ENABLED', true);'`):Error(`The value ${o} cannot be represented on this device.`)}}getValuesFromTexture(e){let{shape:t,dtype:o,isPacked:n}=this.texData.get(e),s=x.sizeFromShape(t);if(W().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")){let m=this.decode(e),f=this.texData.get(m.dataId),d=this.gpgpu.downloadMatrixFromPackedTexture(f.texture,...fl(t)).subarray(0,s);return this.disposeIntermediateTensorInfo(m),d}let a=W().getBool("WEBGL_PACK")&&n===!0,i=a?bf(t):t,l=a?new t_(i):new e_(i),u=this.runWebGLProgram(l,[{shape:i,dtype:o,dataId:e}],"float32"),c=this.texData.get(u.dataId),p=this.gpgpu.downloadByteEncodedFloatMatrixFromOutputTexture(c.texture,c.texShape[0],c.texShape[1]).subarray(0,s);return this.disposeIntermediateTensorInfo(u),p}timerAvailable(){return W().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0}async time(e){let t=this.activeTimers,o=[],n=!1;this.programTimersStack==null?(this.programTimersStack=o,n=!0):this.activeTimers.push(o),this.activeTimers=o,e();let s=x.flatten(this.activeTimers.map(l=>l.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,t=!1){if(this.pendingDisposal.has(e))return!1;if(!this.texData.has(e))return!0;if(t?this.texData.get(e).refCount=0:this.texData.get(e).refCount--,!t&&this.texData.get(e).refCount>0)return!1;if(this.pendingRead.has(e))return this.pendingDisposal.add(e),this.pendingDeletes++,!1;this.releaseGPUData(e);let{complexTensorInfos:o}=this.texData.get(e);return o!=null&&(this.disposeData(o.real.dataId,t),this.disposeData(o.imag.dataId,t)),this.texData.delete(e),!0}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=Mo().findBackend("cpu")),this.cpuBackend):null}shouldExecuteOnCPU(e,t=Q6){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)<t)}getGPGPUContext(){return this.gpgpu}where(e){N.warn("tf.where() in webgl locks the UI thread. Call tf.whereAsync() instead");let t=e.dataSync();return X6(e.shape,t)}packedUnaryOp(e,t,o){let n=new Os(e.shape,t),s=this.compileAndRun(n,[e],o);return Mo().makeTensorFromDataId(s.dataId,s.shape,s.dtype)}abs(e){if(this.shouldExecuteOnCPU([e])&&e.dtype!=="complex64"){let n=Lg(this.texData.get(e.dataId).values);return this.makeOutput(e.shape,e.dtype,n)}if(W().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,v_,e.dtype);let t=new ao(e.shape,v_),o=this.compileAndRun(t,[e]);return Mo().makeTensorFromDataId(o.dataId,o.shape,o.dtype)}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 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 Mo().makeTensorFromDataId(n,e,t,this)}unpackTensor(e){let t=new C_(e.shape);return this.runWebGLProgram(t,[e],e.dtype)}packTensor(e){let t=new k_(e.shape),o=!0;return this.runWebGLProgram(t,[e],e.dtype,null,o)}packedReshape(e,t){let o=[Oa(e.shape),...Pa(e.shape)],n={dtype:e.dtype,shape:o,dataId:e.dataId},s=[Oa(t),...Pa(t)],a=new kf(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=bf(n),i;o?i=new Qk(a):i=new Jk(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===ml.DENSE){let g=fl(e.outputShape);i.texShape=g.map(y=>y*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(g=>{if(g.dtype==="complex64")throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");let y=this.texData.get(g.dataId);if(y.texture==null){if(!e.packedInputs&&x.sizeFromShape(g.shape)<=W().getNumber("WEBGL_SIZE_UPLOAD_UNIFORM"))return{shape:g.shape,texData:null,isUniform:!0,uniformValues:y.values};e.packedInputs&&(y.isPacked=!0,y.shape=g.shape)}else if(!!y.isPacked!=!!e.packedInputs)g=y.isPacked?this.unpackTensor(g):this.packTensor(g),l.push(g),y=this.texData.get(g.dataId);else if(y.isPacked&&!dl(y.shape,g.shape)){let b=g,w=g.shape;g.shape=y.shape,g=this.packedReshape(g,w),l.push(g),y=this.texData.get(g.dataId),b.shape=w}return this.uploadToGPU(g.dataId),{shape:g.shape,texData:y,isUniform:!1}});this.uploadToGPU(a.dataId);let c={shape:a.shape,texData:i,isUniform:!1},p=WA(e,u,c),m=this.getAndSaveBinary(p,()=>BA(this.gpgpu,e,u,c)),f=this.activeTimers!=null,d;f&&(d=this.startTimer()),GA(this.gpgpu,m,u,c,n),l.forEach(g=>this.disposeIntermediateTensorInfo(g)),f&&(d=this.endTimer(d),this.activeTimers.push({name:e.constructor.name,query:this.getQueryTime(d)}));let h=W().get("WEBGL_FLUSH_THRESHOLD");if(h>0){let g=x.now();g-this.lastGlFlushTime>h&&(this.gpgpu.gl.flush(),this.lastGlFlushTime=g)}if(!W().getBool("WEBGL_LAZILY_UNPACK")&&i.isPacked&&s===!1){let g=this.unpackTensor(a);return this.disposeIntermediateTensorInfo(a),g}return a}compileAndRun(e,t,o,n,s=!1){return o=o||t[0].dtype,this.runWebGLProgram(e,t,o,n,s)}getAndSaveBinary(e,t){return e in this.binaryCache||(this.binaryCache[e]=t()),this.binaryCache[e]}getTextureManager(){return this.textureManager}dispose(){this.disposed||(W().getBool("IS_TEST")||Object.keys(this.binaryCache).forEach(t=>{this.gpgpu.deleteProgram(this.binaryCache[t].webGLProgram),delete this.binaryCache[t]}),this.textureManager.dispose(),this.canvas!=null&&typeof HTMLCanvasElement!="undefined"&&this.canvas instanceof HTMLCanvasElement?this.canvas.remove():this.canvas=null,this.gpgpuCreatedLocally&&(this.gpgpu.program=null,this.gpgpu.dispose()),this.disposed=!0)}floatPrecision(){return this.floatPrecisionValue==null&&(this.floatPrecisionValue=V(()=>{if(!W().get("WEBGL_RENDER_FLOAT32_ENABLED")){let e=W().getBool("DEBUG");W().set("DEBUG",!1);let t=this.abs(le(1e-8)).dataSync()[0];if(W().set("DEBUG",e),t>0)return 32}return 16})),this.floatPrecisionValue}epsilon(){return this.floatPrecision()===32?Y6:Z6}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=jk(o,l),t.texShape=p),s!=null){let m=bf(o),f,d=p[1],h=p[0],g=s instanceof Uint8Array;l?([d,h]=Bi(p[0],p[1]),f=new o_(m,[h,d],g)):f=new r_(m,[h,d],g);let y=this.makeTensorInfo([h,d],n);g?this.texData.get(y.dataId).usage=Er.PIXELS:this.texData.get(y.dataId).usage=Er.UPLOAD,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(y.dataId),d,h,s);let b=!0,w=this.runWebGLProgram(f,[y],n,null,b),k=this.texData.get(w.dataId);t.texture=k.texture,t.texShape=k.texShape,t.isPacked=k.isPacked,t.usage=k.usage,this.disposeIntermediateTensorInfo(y),this.texData.delete(w.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=r5(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)}};Zu.nextDataId=0;function r5(r,e){if(e==="float32"||e==="complex64")return r;if(e==="int32"||e==="bool"){let t=e==="int32"?new Int32Array(r.length):new Uint8Array(r.length);for(let o=0;o<t.length;++o)t[o]=Math.round(r[o]);return t}else throw new Error(`Unknown dtype ${e}`)}var I_="3.3.0";function N_(){W().set("WEBGL_FORCE_F16_TEXTURES",!0)}hu.isBrowser()&&xu("webgl",()=>new Zu,2);var o5={forceHalfFloat:N_};var Bg=`
|
|
if (isnan(a)) return a;
|
|
if (isnan(b)) return b;
|
|
`;var Xn=class{constructor(e,t,o){this.variableNames=["A","B"],this.outputShape=N.assertAndGetBroadcastShape(t,o),this.userCode=`
|
|
float binaryOperation(float a, float b) {
|
|
${e}
|
|
}
|
|
|
|
void main() {
|
|
float a = getAAtOutCoords();
|
|
float b = getBAtOutCoords();
|
|
setOutput(binaryOperation(a, b));
|
|
}
|
|
`}};var hl=`
|
|
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 Ps=class{constructor(e,t,o,n=!1){this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=N.assertAndGetBroadcastShape(t,o);let s=this.outputShape.length,a="";if(n)if(s===0||x.sizeFromShape(this.outputShape)===1)a=`
|
|
result.y = 0.;
|
|
result.z = 0.;
|
|
result.w = 0.;
|
|
`;else if(a=`
|
|
${Le(s)} coords = getOutputCoords();
|
|
`,s===1)a+=`
|
|
result.y = (coords + 1) >= ${this.outputShape[0]} ? 0. : result.y;
|
|
result.z = 0.;
|
|
result.w = 0.;
|
|
`;else{let l=Wt("coords",s);a+=`
|
|
bool nextRowOutOfBounds =
|
|
(${l[s-2]} + 1) >= ${this.outputShape[s-2]};
|
|
bool nextColOutOfBounds =
|
|
(${l[s-1]} + 1) >= ${this.outputShape[s-1]};
|
|
result.y = nextColOutOfBounds ? 0. : result.y;
|
|
result.z = nextRowOutOfBounds ? 0. : result.z;
|
|
result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;
|
|
`}this.userCode=`
|
|
vec4 binaryOperation(vec4 a, vec4 b) {
|
|
${e}
|
|
}
|
|
|
|
void main() {
|
|
vec4 a = getAAtOutCoords();
|
|
vec4 b = getBAtOutCoords();
|
|
|
|
vec4 result = binaryOperation(a, b);
|
|
${a}
|
|
|
|
setOutput(result);
|
|
}
|
|
`}};function jt(r){let{inputs:e,backend:t}=r,{x:o}=e;return t.incRef(o.dataId),{dataId:o.dataId,shape:o.shape,dtype:o.dtype}}var TE={kernelName:Fo,backendName:"webgl",kernelFunc:jt};function lo(r){let{inputs:e,backend:t}=r,{real:o,imag:n}=e,s=t.makeTensorInfo(o.shape,"complex64"),a=t.texData.get(s.dataId),i=jt({inputs:{x:o},backend:t}),l=jt({inputs:{x:n},backend:t});return a.complexTensorInfos={real:i,imag:l},s}var AE={kernelName:Gl,backendName:"webgl",kernelFunc:lo};var S_="return (a < 0.) ? b * a : a;",T_=`
|
|
vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
|
|
return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
|
|
`;function n5(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 Ps(T_,n.shape,a.shape):new Xn(S_,n.shape,a.shape),l=t.runWebGLProgram(i,[n,a],n.dtype);return t.disposeIntermediateTensorInfo(a),l}var EE={kernelName:un,backendName:"webgl",kernelFunc:n5};var A_="return (a < 0.) ? b * a : a;",E_=`
|
|
vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
|
|
return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
|
|
`;function s5(r){let{inputs:e,backend:t}=r,{x:o,alpha:n}=e,s=W().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Ps(E_,o.shape,n.shape):new Xn(A_,o.shape,n.shape);return t.runWebGLProgram(s,[o,n],o.dtype)}var DE={kernelName:kn,backendName:"webgl",kernelFunc:s5};var Vg="if (isnan(x)) return x;",$E=`
|
|
if (isnan(a)) return a;
|
|
if (isnan(b)) return b;
|
|
`,RE=`
|
|
result.r = isNaN.r > 0. ? NAN : result.r;
|
|
result.g = isNaN.g > 0. ? NAN : result.g;
|
|
result.b = isNaN.b > 0. ? NAN : result.b;
|
|
result.a = isNaN.a > 0. ? NAN : result.a;
|
|
`;function ke({opSnippet:r,packedOpSnippet:e,cpuKernelImpl:t,dtype: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 Os(a.shape,e):c=new ao(a.shape,r),i.runWebGLProgram(c,[a],l)}}function nt({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(w=>{let[k,v]=w,D={dataId:k.dataId,dtype:k.dtype,shape:l.shape},A={dataId:v.dataId,dtype:v.dtype,shape:u.shape},R=new Xn(r,l.shape,u.shape);return c.runWebGLProgram(R,[D,A],fr(k.dtype,v.dtype))}),b=lo({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),w=c.texData.get(b.dataId);return w.values=g,b}let m=W().getBool("WEBGL_PACK_BINARY_OPERATIONS")&&e!=null,f;return m?f=new Ps(e,l.shape,u.shape,t):f=new Xn(r,l.shape,u.shape),c.runWebGLProgram(f,[l,u],p)}}function gl(r,e=!1){if(r==="linear")return e?CE:wE;if(r==="relu")return e?NE:_E;if(r==="elu")return e?IE:kE;if(r==="relu6")return e?SE:vE;if(r==="prelu")return e?E_:A_;if(r==="leakyrelu")return e?T_:S_;throw new Error(`Activation ${r} has not been implemented for the WebGL backend.`)}var vf=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 w="rc.x",k="rc.x";e[0]<t[0]?w=`int(min(float(rc.x), ${e[0]-1}.))`:t[0]<e[0]&&(k=`int(min(float(rc.x), ${t[0]-1}.))`),this.userCode=`
|
|
${g}
|
|
|
|
const float sharedDimension = ${p}.0;
|
|
|
|
vec4 dot2x2ARowBCol(ivec3 rc) {
|
|
vec4 result = vec4(0);
|
|
for (int i = 0; i < ${p}; i++) {
|
|
int batchA = ${w};
|
|
int batchB = ${k};
|
|
vec4 a = getMatrixA(batchA, ${m});
|
|
vec4 b = getMatrixB(batchB, ${f});
|
|
|
|
// These swizzled products need to be separately added.
|
|
// See: https://github.com/tensorflow/tfjs/issues/1735
|
|
result += (${d[0]} * ${h[0]});
|
|
result += (${d[1]} * ${h[1]});
|
|
}
|
|
return result;
|
|
}
|
|
|
|
void main() {
|
|
ivec3 rc = getOutputCoords();
|
|
vec4 result = dot2x2ARowBCol(rc);
|
|
|
|
${b}
|
|
|
|
${y}
|
|
|
|
setOutput(result);
|
|
}
|
|
`}};var D_={REAL:"return areal * breal - aimag * bimag;",IMAG:"return areal * bimag + aimag * breal;"},Gg=class{constructor(e,t,o){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=N.assertAndGetBroadcastShape(t,o),this.userCode=`
|
|
float binaryOpComplex(
|
|
float areal, float aimag, float breal, float bimag) {
|
|
${e}
|
|
}
|
|
|
|
void main() {
|
|
float areal = getARealAtOutCoords();
|
|
float aimag = getAImagAtOutCoords();
|
|
float breal = getBRealAtOutCoords();
|
|
float bimag = getBImagAtOutCoords();
|
|
setOutput(binaryOpComplex(areal, aimag, breal, bimag));
|
|
}
|
|
`}};var FE="return a * b;";function $_(r){let{inputs:e,backend:t}=r,{a:o,b:n}=e,s=N.upcastType(o.dtype,n.dtype);if(o.dtype==="complex64"){let i=t.texData.get(o.dataId),l=t.texData.get(n.dataId),u=new Gg(D_.REAL,o.shape,n.shape),c=new Gg(D_.IMAG,o.shape,n.shape),p=[{dataId:i.complexTensorInfos.real.dataId,dtype:i.complexTensorInfos.real.dtype,shape:o.shape},{dataId:i.complexTensorInfos.imag.dataId,dtype:i.complexTensorInfos.imag.dtype,shape:o.shape},{dataId:l.complexTensorInfos.real.dataId,dtype:l.complexTensorInfos.real.dtype,shape:n.shape},{dataId:l.complexTensorInfos.imag.dataId,dtype:l.complexTensorInfos.imag.dtype,shape:n.shape}],m=t.runWebGLProgram(u,p,"float32"),f=t.runWebGLProgram(c,p,"float32"),d=lo({inputs:{real:m,imag:f},backend:t});return t.disposeIntermediateTensorInfo(m),t.disposeIntermediateTensorInfo(f),d}if(t.shouldExecuteOnCPU([o,n])){let i=t.texData.get(o.dataId),l=t.texData.get(n.dataId),[u,c]=sE(o.shape,n.shape,i.values,l.values,s),p=t.makeTensorInfo(c,s),m=t.texData.get(p.dataId);return m.values=u,p}let a;return W().getBool("WEBGL_PACK_BINARY_OPERATIONS")?a=new Ps(FE,o.shape,n.shape):a=new Xn(FE,o.shape,n.shape),t.runWebGLProgram(a,[o,n],s)}var OE={kernelName:xn,backendName:"webgl",kernelFunc:$_};function PE(r,e,t){let o=[Oa(r.shape),...Pa(r.shape)],n={dtype:r.dtype,shape:o,dataId:r.dataId},s=[Oa(e),...Pa(e)],a=new kf(s,o),i=!0,l=t.runWebGLProgram(a,[n],r.dtype,null,i);return{dataId:l.dataId,shape:e,dtype:l.dtype}}function pe(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{shape:s}=o,a=t,i=x.sizeFromShape(n.shape),l=x.inferFromImplicitShape(s,i),u=x.sizeFromShape(l);x.assert(i===u,()=>`The new shape (${l}) has ${u} elements and the old shape (${n.shape}) has ${i} elements. The new shape and old shape must have the same number of elements.`);let c=a.texData.get(n.dataId);return c.isPacked&&!dl(n.shape,l)&&!(c.texture!==null&&dl(c.shape,l))?PE(n,l,a):(a.incRef(n.dataId),{dataId:n.dataId,shape:l,dtype:n.dtype})}var ME={kernelName:ds,backendName:"webgl",kernelFunc:pe};var Wg=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 R_=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 i5(r){let e=[];for(;e.length===0||e[e.length-1].outSize!==1;){let t=e.length?e[e.length-1].outSize:r[1],o=N.computeOptimalWindowSize(t);e.push({inSize:t,windowSize:o,outSize:Math.ceil(t/o)})}return e}function No(r,e,t,o){let n=i5(r.shape),s=r;for(let a=0;a<n.length;a++){let{inSize:i,windowSize:l,outSize:u}=n[a],c,p;t==="mean"?c=a===0?new Wg({windowSize:l,inSize:i,batchSize:r.shape[0],outSize:u},i):new Wg({windowSize:l,inSize:i,batchSize:r.shape[0],outSize:u}):c=new R_({windowSize:l,inSize:i,batchSize:r.shape[0],outSize:u},t),p=s,s=o.runWebGLProgram(c,[s],e),p.dataId!==r.dataId&&o.disposeIntermediateTensorInfo(p)}return s}var F_=class{constructor(e,t){this.variableNames=["A"];let o=new Array(e.length);for(let a=0;a<o.length;a++)o[a]=e[t[a]];this.outputShape=o,this.rank=o.length;let n=Le(this.rank),s=a5(t);this.userCode=`
|
|
void main() {
|
|
${n} resRC = getOutputCoords();
|
|
setOutput(getA(${s}));
|
|
}
|
|
`}};function a5(r){let e=r.length;if(e>6)throw Error(`Transpose for rank ${e} is not yet supported`);let t=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"],o=new Array(e);for(let n=0;n<r.length;n++)o[r[n]]=t[n];return o.join()}var O_=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0;let o=new Array(e.length);for(let c=0;c<o.length;c++)o[c]=e[t[c]];if(this.outputShape=o,this.rank=o.length,this.rank>6)throw Error(`Packed transpose for rank ${this.rank} is not yet supported.`);let n=Le(this.rank),s=w_("rc",this.rank),a=new Array(this.rank);for(let c=0;c<t.length;c++)a[t[c]]=s[c];let i=`vec2(${a.slice(-2).join()})`,l=`++${s[this.rank-1]} < ${o[this.rank-1]}`,u=`getChannel(getA(${a.join()}), ${i})`;this.userCode=`
|
|
void main() {
|
|
${n} rc = getOutputCoords();
|
|
vec4 result = vec4(0.);
|
|
result[0] = ${u};
|
|
if(${l}) {
|
|
result[1] = ${u};
|
|
}
|
|
--${s[this.rank-1]};
|
|
if(++${s[this.rank-2]} < ${o[this.rank-2]}) {
|
|
result[2] = ${u};
|
|
if(${l}) {
|
|
result[3] = ${u};
|
|
}
|
|
}
|
|
setOutput(result);
|
|
}
|
|
`}};function xl(r,e,t){let o=W().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new O_(r.shape,e):new F_(r.shape,e);return t.runWebGLProgram(o,[r],r.dtype)}function LE(r,e,t,o){let n=e,s=r.shape.length,a=x.parseAxisParam(n,r.shape),i=a,l=N.getAxesPermutation(i,s),u=l!=null,c=r;u&&(c=xl(r,l,o),i=N.getInnerMostAxes(i.length,s)),N.assertAxesAreInnerMostDims("sum",i,s);let[p,m]=N.computeOutAndReduceShapes(c.shape,i),f=p;t&&(f=N.expandShapeToKeepDim(p,a));let d=x.sizeFromShape(m),g=x.sizeFromShape(r.shape)/d,y=pe({inputs:{x:c},attrs:{shape:[g,d]},backend:o}),b=fu(r.dtype),w=No(y,b,"sum",o),k=pe({inputs:{x:w},attrs:{shape:f},backend:o});return o.disposeIntermediateTensorInfo(y),o.disposeIntermediateTensorInfo(w),u&&o.disposeIntermediateTensorInfo(c),k}function Cf(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{axis:s,keepDims:a}=o;return LE(n,s,a,t)}var zE={kernelName:Dn,backendName:"webgl",kernelFunc:Cf};function Mt(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{perm:s}=o,a=t,i=n.shape.length,l=new Array(i);for(let c=0;c<l.length;c++)l[c]=n.shape[s[c]];let u;if(a.shouldExecuteOnCPU([n])){let p=a.texData.get(n.dataId).values,m=bp(p,n.shape,n.dtype,s,l);u=a.makeTensorInfo(l,n.dtype);let f=a.texData.get(u.dataId);f.values=m}else u=xl(n,s,a);return u}var BE={kernelName:Pn,backendName:"webgl",kernelFunc:Mt};var P_=1e3;function Ju({a:r,b:e,transposeA:t,transposeB:o,backend:n,bias:s=null,preluActivationWeights:a=null,leakyreluAlpha:i=0,activation:l=null}){let u=r.shape.length,c=e.shape.length,p=t?r.shape[u-2]:r.shape[u-1],m=o?e.shape[c-1]:e.shape[c-2],f=t?r.shape[u-1]:r.shape[u-2],d=o?e.shape[c-2]:e.shape[c-1],h=r.shape.slice(0,-2),g=e.shape.slice(0,-2),y=x.sizeFromShape(h),b=x.sizeFromShape(g),w=y===b||y===1||b===1;x.assert(u>=2&&c>=2&&w,()=>`Error in matMul: the input batch dimensions must either be the same or at least one input batch dimension must be 1. Got input batch dimensions of (${h}) and (${g}).`);let v=(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 D=t?[y,p,f]:[y,f,p],A=o?[b,d,m]:[b,m,d],R=pe({inputs:{x:r},backend:n,attrs:{shape:D}}),P=pe({inputs:{x:e},backend:n,attrs:{shape:A}}),L=[R,P],G=Math.max(y,b),j=t?R.shape[1]:R.shape[2],U=s!=null,H=a!=null,q=l==="leakyrelu",X=l!=null?gl(l,!0):null,oe=U||H||q||X!=null,Y;if((f===1||d===1)&&j>P_&&oe===!1){let J=R,ie=P;t&&(J=Mt({inputs:{x:R},backend:n,attrs:{perm:[0,2,1]}}),L.push(J)),o&&(ie=Mt({inputs:{x:P},backend:n,attrs:{perm:[0,2,1]}}),L.push(ie));let ue=d!==1,ae=d===1,fe=J;ue&&(fe=pe({inputs:{x:J},backend:n,attrs:{shape:[G,j,1]}}),L.push(fe));let de=d===1?2:1,xe=ie;ae&&(xe=pe({inputs:{x:ie},backend:n,attrs:{shape:[G,1,j]}}),L.push(xe));let we=$_({inputs:{a:fe,b:xe},backend:n});Y=Cf({inputs:{x:we},backend:n,attrs:{axis:de,keepDims:!0}}),L.push(we)}else{let J=fr(r.dtype,e.dtype),ie=new vf(D,A,[G,f,d],t,o,U,X,H,q),ue=[R,P];if(s!=null&&ue.push(s),H&&ue.push(a),q){let ae=n.makeTensorInfo([],"float32",x.createScalarValue(i,"float32"));ue.push(ae),L.push(ae)}Y=n.runWebGLProgram(ie,ue,J)}let re=pe({inputs:{x:Y},backend:n,attrs:{shape:v}});L.push(Y);for(let J of L)n.disposeIntermediateTensorInfo(J);return re}function l5(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 Ju({a:n,b:s,transposeA:l,transposeB:u,backend:t,bias:a,preluActivationWeights:i,leakyreluAlpha:p,activation:c})}var VE={kernelName:ws,backendName:"webgl",kernelFunc:l5};var GE="return abs(x);";function u5(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=Lg(s.values);return t.makeTensorInfo(o.shape,o.dtype,a)}let n;return W().getBool("WEBGL_PACK_UNARY_OPERATIONS")?n=new Os(o.shape,GE):n=new ao(o.shape,GE),t.runWebGLProgram(n,[o],o.dtype)}var WE={kernelName:as,backendName:"webgl",kernelFunc:u5};var c5=hr+`
|
|
if (abs(x) > 1.) {
|
|
return NAN;
|
|
}
|
|
return acos(x);
|
|
`,p5=ke({opSnippet:c5}),jE={kernelName:qs,backendName:"webgl",kernelFunc:p5};var m5=hr+`
|
|
if (x < 1.0) return NAN;
|
|
return log(x + sqrt(x * x - 1.0));`,f5=ke({opSnippet:m5}),UE={kernelName:Ks,backendName:"webgl",kernelFunc:f5};var HE="return a + b;",d5=nt({opSnippet:HE,packedOpSnippet:HE,supportsComplex:!0,cpuKernelImpl:jA}),qE={kernelName:wo,backendName:"webgl",kernelFunc:d5};var M_=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 L_=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 jg(r){let{inputs:e,backend:t}=r,o=e;if(o.length===1)return jt({inputs:{x:o[0]},backend:t});if(o.length>W().get("WEBGL_MAX_TEXTURES_IN_SHADER")){let l=Math.floor(o.length/2),u=jg({inputs:o.slice(0,l),backend:t}),c=jg({inputs:o.slice(l),backend:t});return jg({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 L_(o[0].shape,s):new M_(o[0].shape,s);return t.runWebGLProgram(i,o,n)}var KE={kernelName:Ho,backendName:"webgl",kernelFunc:jg};function h5(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=N.getAxesPermutation(u,i),p=n;c!=null&&(p=Mt({inputs:{x:n},backend:t,attrs:{perm:c}}),u=N.getInnerMostAxes(u.length,i)),N.assertAxesAreInnerMostDims("all",u,i);let[m,f]=N.computeOutAndReduceShapes(p.shape,u),d=x.sizeFromShape(f),h=pe({inputs:{x:p},backend:t,attrs:{shape:[-1,d]}}),g=No(h,h.dtype,"all",t),y;if(a){let b=N.expandShapeToKeepDim(m,l);y=pe({inputs:{x:g},backend:t,attrs:{shape:b}})}else y=pe({inputs:{x:g},backend:t,attrs:{shape:m}});return t.disposeIntermediateTensorInfo(h),t.disposeIntermediateTensorInfo(g),c!=null&&t.disposeIntermediateTensorInfo(p),y}var XE={kernelName:Ml,backendName:"webgl",kernelFunc:h5};function g5(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=N.getAxesPermutation(u,i),p=n;c!=null&&(p=Mt({inputs:{x:n},backend:t,attrs:{perm:c}}),u=N.getInnerMostAxes(u.length,i)),N.assertAxesAreInnerMostDims("any",u,i);let[m,f]=N.computeOutAndReduceShapes(p.shape,u),d=x.sizeFromShape(f),h=pe({inputs:{x:p},backend:t,attrs:{shape:[-1,d]}}),g=No(h,h.dtype,"any",t),y;if(a){let b=N.expandShapeToKeepDim(m,l);y=pe({inputs:{x:g},backend:t,attrs:{shape:b}})}else y=pe({inputs:{x:g},backend:t,attrs:{shape:m}});return t.disposeIntermediateTensorInfo(h),t.disposeIntermediateTensorInfo(g),c!=null&&t.disposeIntermediateTensorInfo(p),y}var YE={kernelName:Ll,backendName:"webgl",kernelFunc:g5};var z_=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 B_=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=Le(l),c=Wt("coords",l),p,m;if(a===1){m=l+1;let R=Le(m);p=`
|
|
${R} sourceLocR = ${R}(${c.join()}, 0);
|
|
++${c[l-1]};
|
|
${R} sourceLocG = ${R}(${c.join()}, 0);
|
|
++${c[l-2]};
|
|
${R} sourceLocA = ${R}(${c.join()}, 0);
|
|
--${c[l-1]};
|
|
${R} sourceLocB = ${R}(${c.join()}, 0);
|
|
--${c[l-2]};`}else m=l,p=`
|
|
${u} sourceLocR = coords;
|
|
++${c[l-1]};
|
|
${u} sourceLocG = coords;
|
|
++${c[l-2]};
|
|
${u} sourceLocA = coords;
|
|
--${c[l-1]};
|
|
${u} sourceLocB = coords;
|
|
--${c[l-2]};`;let f=["x","y","z","w","u","v"].slice(0,m),d="."+f[m-1],h=f.map(R=>"int "+R),g=Wt("sourceLocR",m-1).concat("inIdx.r"),y=Wt("sourceLocG",m-1).concat("inIdx.g"),b=Wt("sourceLocB",m-1).concat("inIdx.b"),w=Wt("sourceLocA",m-1).concat("inIdx.a"),k=o==="max"?"greaterThan":"lessThan",v=n?"":`
|
|
inIdx = round(vec4(getBestIndicesAChannel(${g.join()}),
|
|
getBestIndicesAChannel(${y.join()}),
|
|
getBestIndicesAChannel(${b.join()}),
|
|
getBestIndicesAChannel(${w.join()})));`,D=`vec4(
|
|
getAChannel(${g.join()}),
|
|
hasNextCol ? getAChannel(${y.join()}) : 0.,
|
|
hasNextRow ? getAChannel(${b.join()}) : 0.,
|
|
hasNextRow && hasNextCol ? getAChannel(${w.join()}) : 0.)`,A=n?"":`
|
|
float getBestIndicesAChannel(${h.join()}) {
|
|
return getChannel(getBestIndicesA(${f.join()}),
|
|
vec2(${f.slice(-2).join()}));
|
|
}`;this.userCode=`
|
|
float getAChannel(${h.join()}) {
|
|
return getChannel(getA(${f.join()}),
|
|
vec2(${f.slice(-2).join()}));
|
|
}
|
|
${A}
|
|
void main() {
|
|
${u} coords = getOutputCoords();
|
|
bool hasNextCol = ${c[l-1]} < ${i[l-1]-1};
|
|
bool hasNextRow = ${c[l-2]} < ${i[l-2]-1};
|
|
${p}
|
|
ivec4 srcIdx = ivec4(sourceLocR${d}, sourceLocG${d},
|
|
sourceLocB${d}, sourceLocA${d}) * ${t};
|
|
ivec4 inIdx = srcIdx;
|
|
vec4 bestIndex = vec4(inIdx);
|
|
vec4 bestValue = ${D};
|
|
|
|
for (int i = 0; i < ${t}; i++) {
|
|
inIdx = srcIdx;
|
|
${v}
|
|
vec4 candidate = ${D};
|
|
bvec4 nan = isnan(candidate);
|
|
bvec4 replace = bvec4(
|
|
vec4(${k}(candidate, bestValue)) * (vec4(1.0) - vec4(nan)));
|
|
|
|
bestValue = vec4(replace.x ? candidate.x : bestValue.x,
|
|
replace.y ? candidate.y : bestValue.y,
|
|
replace.z ? candidate.z : bestValue.z,
|
|
replace.w ? candidate.w : bestValue.w);
|
|
bestIndex = mix(bestIndex, vec4(inIdx), vec4(replace));
|
|
srcIdx++;
|
|
}
|
|
setOutput(bestIndex);
|
|
}
|
|
`}};function ZE(r,e,t,o=null){let n=e.shape[0],s=e.shape[1];o!=null&&(n=o.shape[0],s=o.shape[1]);let a=N.computeOptimalWindowSize(s),i={windowSize:a,inSize:s,batchSize:n,outSize:Math.ceil(s/a)},l=new z_(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=ZE(r,e,t,c);return r.disposeIntermediateTensorInfo(c),p}function JE(r,e,t,o=null){let n=o!=null?o.shape:e.shape,s=n[n.length-1],a=N.computeOptimalWindowSize(s),i=new B_(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=JE(r,e,t,u);return r.disposeIntermediateTensorInfo(u),c}return u}function Ug(r,e,t,o){let n=[t];if(N.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]=N.computeOutAndReduceShapes(e.shape,n),l=x.sizeFromShape(i),u=pe({inputs:{x:e},backend:r,attrs:{shape:[-1,l]}});s.push(u);let c=ZE(r,u,o);s.push(c);let p=pe({inputs:{x:c},backend:r,attrs:{shape:a}});return s.forEach(m=>r.disposeIntermediateTensorInfo(m)),p}return JE(r,e,o)}function x5(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{axis:s}=o,a=x.parseAxisParam(s,n.shape),i=N.getAxesPermutation(a,n.shape.length),l=n,u=[];i!=null&&(l=Mt({inputs:{x:n},backend:t,attrs:{perm:i}}),u.push(l),a=N.getInnerMostAxes(a.length,l.shape.length)),N.assertAxesAreInnerMostDims("argMax",[a[0]],l.shape.length);let c=Ug(t,l,a[0],"max");return u.forEach(p=>t.disposeIntermediateTensorInfo(p)),c}var QE={kernelName:qo,backendName:"webgl",kernelFunc:x5};function y5(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{axis:s}=o,a=x.parseAxisParam(s,n.shape),i=N.getAxesPermutation(a,n.shape.length),l=n,u=[];i!=null&&(l=Mt({inputs:{x:n},backend:t,attrs:{perm:i}}),u.push(l),a=N.getInnerMostAxes(a.length,l.shape.length)),N.assertAxesAreInnerMostDims("argMin",[a[0]],l.shape.length);let c=Ug(t,l,a[0],"min");return u.forEach(p=>t.disposeIntermediateTensorInfo(p)),c}var e2={kernelName:ea,backendName:"webgl",kernelFunc:y5};var b5=hr+`
|
|
if (abs(x) > 1.) {
|
|
return NAN;
|
|
}
|
|
return asin(x);
|
|
`,w5=ke({opSnippet:b5}),t2={kernelName:Xs,backendName:"webgl",kernelFunc:w5};var k5=hr+"return log(x + sqrt(x * x + 1.0));",_5=ke({opSnippet:k5}),r2={kernelName:Ys,backendName:"webgl",kernelFunc:_5};var v5=hr+`
|
|
return atan(x);
|
|
`,C5=ke({opSnippet:v5}),o2={kernelName:Zs,backendName:"webgl",kernelFunc:C5};var I5=$E+`
|
|
return atan(a, b);
|
|
`,N5=`
|
|
vec4 result = atan(a, b);
|
|
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
|
|
`+RE+`
|
|
return result;
|
|
`,S5=nt({opSnippet:I5,packedOpSnippet:N5}),n2={kernelName:Qs,backendName:"webgl",kernelFunc:S5};var T5=hr+`
|
|
if ((x < -1.0) || (x > 1.0)) return NAN;
|
|
return (log(1.0 + x) - log(1.0 - x)) / 2.0;`,A5=ke({opSnippet:T5}),s2={kernelName:Js,backendName:"webgl",kernelFunc:A5};var Vi=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 R=">=";this.userCode=`
|
|
const ivec2 strides = ivec2(${i}, ${l});
|
|
const ivec2 pads = ivec2(${f}, ${d});
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int d = coords[3];
|
|
|
|
ivec2 xRCCorner = coords.yz * strides - pads;
|
|
int xRCorner = xRCCorner.x;
|
|
int xCCorner = xRCCorner.y;
|
|
|
|
// max/min x(?, ?, d) to get y(yR, yC, d).
|
|
// ? = to be determined
|
|
float minMaxValue = 0.0;
|
|
float minMaxValueFound = 0.0;
|
|
int minMaxPosition = 0;
|
|
float avgValue = 0.0;
|
|
|
|
for (int wR = 0; wR < ${p};
|
|
wR += ${u}) {
|
|
int xR = xRCorner + wR;
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < ${m};
|
|
wC += ${c}) {
|
|
int xC = xCCorner + wC;
|
|
|
|
if (xC < 0 || xC >= ${e.inWidth}) {
|
|
continue;
|
|
}
|
|
|
|
float value = getX(batch, xR, xC, d);
|
|
|
|
// If a min / max value has already been found, use it. If not,
|
|
// use the current value.
|
|
float currMinMaxValue = mix(
|
|
value, minMaxValue, minMaxValueFound);
|
|
if (value ${R} currMinMaxValue) {
|
|
minMaxValue = value;
|
|
minMaxValueFound = 1.0;
|
|
minMaxPosition = ${n?s?g:y:`wR * ${m} + wC`};
|
|
}
|
|
}
|
|
}
|
|
setOutput(float(minMaxPosition));
|
|
}
|
|
`;return}let w="max",k=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="avg"&&(k="avgValue / count");let v=Math.floor(a/4)*4,D=a%4,A=`
|
|
if (${h}) {
|
|
avgValue += dot(values, ones);
|
|
} else {
|
|
minMaxValue = ${w}(values, minMaxValue);
|
|
}
|
|
`;this.userCode=`
|
|
const ivec2 strides = ivec2(${i}, ${l});
|
|
const ivec2 pads = ivec2(${f}, ${d});
|
|
const float initializationValue = ${b};
|
|
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
|
|
|
|
float count = 0.0;
|
|
|
|
float getValue(int batch, int xR, int xC, int d) {
|
|
if (xC < 0 || xC >= ${e.inWidth}) {
|
|
return initializationValue;
|
|
}
|
|
count += 1.0;
|
|
return getX(batch, xR, xC, d);
|
|
}
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int d = coords[3];
|
|
|
|
ivec2 xRCCorner = coords.yz * strides - pads;
|
|
int xRCorner = xRCCorner.x;
|
|
int xCCorner = xRCCorner.y;
|
|
|
|
// max/min x(?, ?, d) to get y(yR, yC, d).
|
|
// ? = to be determined
|
|
vec4 minMaxValue = vec4(${b});
|
|
float avgValue = 0.0;
|
|
count = 0.0;
|
|
|
|
for (int wR = 0; wR < ${p};
|
|
wR += ${u}) {
|
|
int xR = xRCorner + wR;
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < ${v}; wC += 4) {
|
|
int xC = xCCorner + wC * ${c};
|
|
|
|
vec4 values = vec4(
|
|
getValue(batch, xR, xC, d),
|
|
getValue(batch, xR, xC + ${c}, d),
|
|
getValue(batch, xR, xC + 2 * ${c}, d),
|
|
getValue(batch, xR, xC + 3 * ${c}, d)
|
|
);
|
|
|
|
${A}
|
|
}
|
|
|
|
int xC = xCCorner + ${v};
|
|
if (${D===1}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xR, xC, d),
|
|
initializationValue,
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${A}
|
|
} else if (${D===2}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xR, xC, d),
|
|
getValue(batch, xR, xC + ${c}, d),
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${A}
|
|
} else if (${D===3}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xR, xC, d),
|
|
getValue(batch, xR, xC + ${c}, d),
|
|
getValue(batch, xR, xC + 2 * ${c}, d),
|
|
initializationValue
|
|
);
|
|
|
|
${A}
|
|
}
|
|
}
|
|
setOutput(${k});
|
|
}
|
|
`}},Qu=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 w=t==="avg",k="0.0";if(w||(k="-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 v="max",D=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="avg"&&(D="avgValue / count");let A=Math.floor(a/4)*4,R=a%4,P=`
|
|
if (${w}) {
|
|
avgValue += dot(values, ones);
|
|
} else {
|
|
minMaxValue = ${v}(values, minMaxValue);
|
|
}
|
|
`;this.userCode=`
|
|
const ivec3 strides =
|
|
ivec3(${i}, ${l}, ${u});
|
|
const ivec3 pads = ivec3(${g}, ${y}, ${b});
|
|
const float initializationValue = ${k};
|
|
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
|
|
|
|
float count = 0.0;
|
|
|
|
float getValue(int batch, int xD, int xR, int xC, int ch) {
|
|
if (xC < 0 || xC >= ${e.inWidth}) {
|
|
return initializationValue;
|
|
}
|
|
count += 1.0;
|
|
return getX(batch, xD, xR, xC, ch);
|
|
}
|
|
|
|
void main() {
|
|
ivec5 coords = getOutputCoords();
|
|
int batch = coords.x;
|
|
int ch = coords.u;
|
|
|
|
ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
|
|
int xDCorner = xCorner.x;
|
|
int xRCorner = xCorner.y;
|
|
int xCCorner = xCorner.z;
|
|
|
|
// max/min x(?, ?, ?, d) to get y(yD, yR, yC, ch).
|
|
// ? = to be determined
|
|
vec4 minMaxValue = vec4(${k});
|
|
float avgValue = 0.0;
|
|
count = 0.0;
|
|
|
|
for (int wD = 0; wD < ${f};
|
|
wD += ${c}) {
|
|
int xD = xDCorner + wD;
|
|
|
|
if (xD < 0 || xD >= ${e.inDepth}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wR = 0; wR < ${d};
|
|
wR += ${p}) {
|
|
int xR = xRCorner + wR;
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < ${A}; wC += 4) {
|
|
int xC = xCCorner + wC * ${m};
|
|
|
|
vec4 values = vec4(
|
|
getValue(batch, xD, xR, xC, ch),
|
|
getValue(batch, xD, xR, xC + ${m}, ch),
|
|
getValue(batch, xD, xR, xC + 2 * ${m}, ch),
|
|
getValue(batch, xD, xR, xC + 3 * ${m}, ch)
|
|
);
|
|
|
|
${P}
|
|
}
|
|
|
|
int xC = xCCorner + ${A};
|
|
if (${R===1}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xD, xR, xC, ch),
|
|
initializationValue,
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${P}
|
|
} else if (${R===2}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xD, xR, xC, ch),
|
|
getValue(batch, xD, xR, xC + ${m}, ch),
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${P}
|
|
} else if (${R===3}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xD, xR, xC, ch),
|
|
getValue(batch, xD, xR, xC + ${m}, ch),
|
|
getValue(batch, xD, xR, xC + 2 * ${m}, ch),
|
|
initializationValue
|
|
);
|
|
|
|
${P}
|
|
}
|
|
}
|
|
setOutput(${D});
|
|
}
|
|
}
|
|
`}};function E5(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e;Rs(n,"avgPool");let{filterSize:s,strides:a,pad:i,dimRoundingMode:l}=o,u=1;x.assert(N.eitherStridesOrDilationsAreOne(a,u),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${u}'`);let c=N.computePool2DInfo(n.shape,s,a,u,i,l);if(c.filterWidth===1&&c.filterHeight===1&&x.arraysEqual(c.inShape,c.outShape))return jt({inputs:{x:n},backend:t});let p=new Vi(c,"avg",!1);return t.runWebGLProgram(p,[n],"float32")}var i2={kernelName:Ko,backendName:"webgl",kernelFunc:E5};function D5(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{filterSize:s,strides:a,pad:i,dimRoundingMode:l,dataFormat:u}=o,c=[1,1,1],p=N.computePool3DInfo(n.shape,s,a,c,i,l,u),m=new Qu(p,"avg",!1);return t.runWebGLProgram(m,[n],"float32")}var a2={kernelName:ta,backendName:"webgl",kernelFunc:D5};var V_=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);
|
|
}
|
|
`}},G_=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 $5(r){let{inputs:e,backend:t,attrs:o}=r,{dy:n,input:s}=e,a=s,{filterSize:i,strides:l,pad:u,dimRoundingMode:c}=o,p=[1,1,1],m=N.computePool3DInfo(a.shape,i,l,p,u,c),f=new G_(m);return t.runWebGLProgram(f,[n],a.dtype)}var l2={kernelName:Bl,backendName:"webgl",kernelFunc:$5};function R5(r){let{inputs:e,backend:t,attrs:o}=r,{dy:n,input:s}=e,a=s;Rs([n,s],"avgPoolGrad");let{filterSize:i,strides:l,pad:u}=o,c=N.computePool2DInfo(a.shape,i,l,1,u),p=new V_(c);return t.runWebGLProgram(p,[n],a.dtype)}var u2={kernelName:zl,backendName:"webgl",kernelFunc:R5};function F5(r){let{inputs:e,backend:t,attrs:o}=r,{a:n,b:s}=e,{transposeA:a,transposeB:i}=o;return Ju({a:n,b:s,transposeA:a,transposeB:i,backend:t})}var c2={kernelName:Xo,backendName:"webgl",kernelFunc:F5};var W_=class{constructor(e,t,o,n,s,a){this.outputShape=[],this.variableNames=["x","mean","variance"],N.assertAndGetBroadcastShape(e,t),N.assertAndGetBroadcastShape(e,o);let i="0.0";n!=null&&(N.assertAndGetBroadcastShape(e,n),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");let l="1.0";s!=null&&(N.assertAndGetBroadcastShape(e,s),this.variableNames.push("scale"),l="getScaleAtOutCoords()"),this.outputShape=e,this.userCode=`
|
|
void main() {
|
|
float x = getXAtOutCoords();
|
|
float mean = getMeanAtOutCoords();
|
|
float variance = getVarianceAtOutCoords();
|
|
float offset = ${i};
|
|
float scale = ${l};
|
|
float inv = scale * inversesqrt(variance + float(${a}));
|
|
setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1)));
|
|
}
|
|
`}};var j_=class{constructor(e,t,o,n,s,a){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],N.assertAndGetBroadcastShape(e,t),N.assertAndGetBroadcastShape(e,o);let i="vec4(0.0)";n!=null&&(N.assertAndGetBroadcastShape(e,n),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");let l="vec4(1.0)";s!=null&&(N.assertAndGetBroadcastShape(e,s),this.variableNames.push("scale"),l="getScaleAtOutCoords()"),this.outputShape=e,this.userCode=`
|
|
void main() {
|
|
vec4 offset = ${i};
|
|
vec4 scale = ${l};
|
|
|
|
vec4 x = getXAtOutCoords();
|
|
vec4 mean = getMeanAtOutCoords();
|
|
vec4 variance = getVarianceAtOutCoords();
|
|
|
|
vec4 inv = scale * inversesqrt(variance + vec4(${a}));
|
|
|
|
setOutput((x - mean) * inv + offset);
|
|
}
|
|
`}};var O5=({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 j_(o.shape,n.shape,s.shape,c,p,l):new W_(o.shape,n.shape,s.shape,c,p,l);return e.runWebGLProgram(m,u,u[0].dtype)},p2={kernelName:an,backendName:"webgl",kernelFunc:O5};var U_=class{constructor(e){this.variableNames=["source"],this.outputShape=e,this.rank=e.length;let t=Le(this.rank),o=`uniform int start[${this.rank}];`,n=P5(this.rank),s,a=e.map((i,l)=>`sourceLoc.${H_[l]} = start[${l}] + coords.${H_[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)}}},H_=["x","y","z","w","u","v"];function P5(r){if(r===1)return"sourceLoc";if(r<=6)return H_.slice(0,r).map(e=>"sourceLoc."+e).join(",");throw Error(`Slicing for rank ${r} is not yet supported`)}var q_=class{constructor(e){this.variableNames=["source"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.rank=e.length;let t=Le(this.rank),o=Wt("coords",this.rank),n=Wt("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 M5(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.refCount=1,a.shape=t,a.dtype=r.dtype;let i=nr.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 Ma(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{begin:s,size:a}=o,[i,l]=nr.parseSliceParams(n,s,a);if(nr.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=cE(p.values,i,l,n.shape,n.dtype);return t.makeTensorInfo(l,n.dtype,m)}let{isPacked:u}=t.texData.get(n.dataId),c=nr.isSliceContinous(n.shape,i,l);if(u||!c){let p=W().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new q_(l):new U_(l),m=p.getCustomSetupFunc(i);return t.runWebGLProgram(p,[n],n.dtype,m)}return t.uploadToGPU(n.dataId),M5(n,i,l,t)}var m2={kernelName:gs,backendName:"webgl",kernelFunc:Ma};var L5=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,w)=>b*w),l=N.getReshaped(n.shape,s,i),u=N.getPermuted(l.length,s.length),c=N.getReshapedPermuted(n.shape,s,i),p=N.getSliceBeginCoords(a,s.length),m=N.getSliceSize(c,a,s.length),f=[],d=pe({inputs:{x:n},backend:t,attrs:{shape:l}}),h=Mt({inputs:{x:d},backend:t,attrs:{perm:u}}),g=pe({inputs:{x:h},backend:t,attrs:{shape:c}}),y=Ma({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},f2={kernelName:ra,backendName:"webgl",kernelFunc:L5};function z5(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=Mg(i,l,s.dtype,s.shape,a);return t.makeTensorInfo([a],s.dtype,u)}var d2={kernelName:Vl,backendName:"webgl",kernelFunc:z5};var B5="return float(a != b);",K_=nt({opSnippet:B5,dtype:"bool"}),h2={kernelName:yi,backendName:"webgl",kernelFunc:K_};function La(r){let{inputs:e,backend:t}=r,{input:o}=e,n=t.texData.get(o.dataId);return jt({inputs:{x:n.complexTensorInfos.real},backend:t})}var g2={kernelName:iu,backendName:"webgl",kernelFunc:La};var V5="return float(int(x));";function x2(r,e){let t=new ao(r.shape,V5),o=e.runWebGLProgram(t,[r],"int32");return{dataId:o.dataId,shape:o.shape,dtype:o.dtype}}function X_(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{dtype:s}=o;if(s==="complex64"){if(n.dtype==="complex64")return jt({inputs:{x:n},backend:t});let a=ht(n.shape),i=X_({inputs:{x:n},backend:t,attrs:{dtype:"float32"}}),l=lo({inputs:{real:i,imag:a},backend:t});return a.dispose(),t.disposeIntermediateTensorInfo(i),l}if(n.dtype==="complex64"){let a=La({inputs:{input:n},backend:t}),i=X_({inputs:{x:a},backend:t,attrs:{dtype:s}});return t.disposeIntermediateTensorInfo(a),i}if(!x.hasEncodingLoss(n.dtype,s)){let a=jt({inputs:{x:n},backend:t});return{dataId:a.dataId,shape:a.shape,dtype:s}}if(s==="int32")return x2(n,t);if(s==="bool"){let a=t.makeTensorInfo([],"bool",x.getTypedArrayFromDType("bool",1)),l=K_({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 y2={kernelName:$o,backendName:"webgl",kernelFunc:X_};var b2="return ceil(x);",G5=ke({opSnippet:b2,packedOpSnippet:b2,cpuKernelImpl:HA}),w2={kernelName:Yo,backendName:"webgl",kernelFunc:G5};var Y_=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 Z_=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 W5(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 Z_(n.shape):i=new Y_(n.shape);let l=i.getCustomSetupFunc(s,a);return t.runWebGLProgram(i,[n],n.dtype,l)}var k2={kernelName:Ro,backendName:"webgl",kernelFunc:W5};var J_=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 _2(r,e){return{dataId:e.dataId,dtype:e.dtype,shape:r.shape}}function j5(r){let{inputs:e,backend:t}=r,{x:o}=e,n=t.texData.get(o.dataId),s=new J_(o.shape),a=[_2(o,n.complexTensorInfos.real),_2(o,n.complexTensorInfos.imag)];return t.runWebGLProgram(s,a,a[0].dtype)}var v2={kernelName:oa,backendName:"webgl",kernelFunc:j5};var Q_=class{constructor(e){this.outputShape=[],this.outputShape=N.computeOutShape(e,1),this.variableNames=e.map((a,i)=>`T${i}`);let t=new Array(e.length-1);t[0]=e[0][1];for(let a=1;a<t.length;a++)t[a]=t[a-1]+e[a][1];let o=[`if (yC < ${t[0]}) setOutput(getT0(yR, yC));`];for(let a=1;a<t.length;a++){let i=t[a-1];o.push(`else if (yC < ${t[a]}) setOutput(getT${a}(yR, yC-${i}));`)}let n=t.length,s=t[t.length-1];o.push(`else setOutput(getT${n}(yR, yC-${s}));`),this.userCode=`
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
int yR = coords.x;
|
|
int yC = coords.y;
|
|
|
|
${o.join(`
|
|
`)}
|
|
}
|
|
`}};var ev=class{constructor(e,t){this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[],this.outputShape=N.computeOutShape(e,t);let o=this.outputShape,n=o.length,s=Le(n),a=Wt("coords",n),i=["x","y","z","w","u","v"].slice(0,n);this.variableNames=e.map((h,g)=>`T${g}`);let l=new Array(e.length-1);l[0]=e[0][t];for(let h=1;h<l.length;h++)l[h]=l[h-1]+e[h][t];let u=i[t],c=i.slice(-2),p=i.join(),m=`if (${u} < ${l[0]}) {
|
|
return getChannel(
|
|
getT0(${p}), vec2(${c.join()}));
|
|
}`;for(let h=1;h<l.length;h++){let g=l[h-1];m+=`
|
|
if (${u} < ${l[h]} && ${u} >= ${l[h-1]}) {
|
|
return getChannel(
|
|
getT${h}(${Hg(i,u,g)}),
|
|
vec2(${Hg(c,u,g)}));
|
|
}`}let f=l.length,d=l[l.length-1];m+=`
|
|
return getChannel(
|
|
getT${f}(${Hg(i,u,d)}),
|
|
vec2(${Hg(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 Hg(r,e,t){let o=r.indexOf(e);return r.map((s,a)=>a===o?`${s} - ${t}`:s).join()}function ec(r){let{inputs:e,backend:t}=r,{input:o}=e,n=t.texData.get(o.dataId);return jt({inputs:{x:n.complexTensorInfos.imag},backend:t})}var C2={kernelName:Ql,backendName:"webgl",kernelFunc:ec};function tc(r,e,t){let o=r[0].dtype;if(o==="complex64"){let u=r.map(d=>La({inputs:{input:d},backend:t})),c=r.map(d=>ec({inputs:{input:d},backend:t})),p=tc(u,e,t),m=tc(c,e,t),f=lo({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}=I2(r,e,t),p=u.map(g=>({vals:t.readSync(g.dataId),shape:g.shape})),m=u[0].shape[0]===1,f=qA(p,c,o,m),d=N.computeOutShape(r.map(g=>g.shape),e),h=t.makeTensorInfo(d,o,f);return u.forEach(g=>t.disposeIntermediateTensorInfo(g)),h}if(r.length>W().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){let u=Math.floor(r.length/2),c=tc(r.slice(0,u),e,t),p=tc(r.slice(u),e,t),m=tc([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 ev(r.map(c=>c.shape),e);return t.runWebGLProgram(u,r,o)}let{tensors2D:n,outShape:s}=I2(r,e,t),a=new Q_(n.map(u=>u.shape)),i=t.runWebGLProgram(a,n,o);n.forEach(u=>t.disposeIntermediateTensorInfo(u));let l=pe({inputs:{x:i},attrs:{shape:s},backend:t});return t.disposeIntermediateTensorInfo(i),l}function I2(r,e,t){let o=N.computeOutShape(r.map(s=>s.shape),e);return{tensors2D:r.map(s=>pe({inputs:{x:s},attrs:{shape:[-1,x.sizeFromShape(s.shape.slice(e))]},backend:t})),outShape:o}}function tv(r){let{inputs:e,backend:t,attrs:o}=r,{axis:n}=o,s=x.parseAxisParam(n,e[0].shape)[0],a=N.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 jt({inputs:{x:i[0]},backend:t});let l=i.map(u=>u.shape);return N.assertParamsConsistent(l,s),tc(i,s,t)}var N2={kernelName:ls,backendName:"webgl",kernelFunc:tv};var If=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,w=g?3:1,k="",v="";o&&(n?k=`float activation(float a) {
|
|
float b = getPreluActivationWeightsAtOutCoords();
|
|
${o}
|
|
}`:s?k=`float activation(float a) {
|
|
float b = getLeakyreluAlphaAtOutCoords();
|
|
${o}
|
|
}`:k=`
|
|
float activation(float x) {
|
|
${o}
|
|
}
|
|
`,v="result = activation(result);");let D=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),n&&this.variableNames.push("preluActivationWeights"),s&&this.variableNames.push("leakyreluAlpha"),this.userCode=`
|
|
${k}
|
|
|
|
const ivec2 strides = ivec2(${l}, ${u});
|
|
const ivec2 pads = ivec2(${a}, ${i});
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int d2 = coords[${w}];
|
|
|
|
ivec2 xRCCorner =
|
|
ivec2(coords[${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;
|
|
${D}
|
|
${v}
|
|
setOutput(result);
|
|
}
|
|
`}},rv=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 ov=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=Rt(),y=m==="channelsLast",b=y?0:1,w=y?1:2,k="";for(let v=0;v<=1;v++)for(let D=0;D<=1;D++)k+=`
|
|
blockIndex = rc.y + ${D};
|
|
pos = rc.x + ${v};
|
|
|
|
if(blockIndex < ${e[1]} && pos < ${e[0]}) {
|
|
offsetY = int(blockIndex / (${u})) * ${i} - ${d};
|
|
d0 = offsetY + ${p} * (pos / ${h});
|
|
|
|
if(d0 < ${t[b]} && d0 >= 0) {
|
|
|
|
offsetX = int(mod(float(blockIndex), ${u}.) * ${a}. - ${f}.);
|
|
d1 = offsetX + ${c} * (int(mod(float(pos), ${h}.) / ${s}.));
|
|
|
|
if(d1 < ${t[w]} && d1 >= 0) {
|
|
|
|
ch = int(mod(float(pos), ${s}.));
|
|
|
|
if (${y}) {
|
|
innerDims = vec2(d1, ch);
|
|
result[${v*2+D}] = getChannel(
|
|
getA(d0, int(innerDims.x),
|
|
int(innerDims.y)), innerDims);
|
|
} else {
|
|
innerDims = vec2(d0, d1);
|
|
result[${v*2+D}] = getChannel(
|
|
getA(ch, int(innerDims.x),
|
|
int(innerDims.y)), innerDims);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
`;this.userCode=`
|
|
void main() {
|
|
ivec2 rc = getOutputCoords();
|
|
|
|
vec4 result = vec4(0);
|
|
|
|
int blockIndex, pos, offsetY, d0, offsetX, d1, ch;
|
|
vec2 innerDims;
|
|
|
|
${k}
|
|
|
|
${g.output} = result;
|
|
}
|
|
`}};function qg({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>P_,w=l[2]%2!=0&&!!u.isPacked;if(b||!W().getBool("WEBGL_LAZILY_UNPACK")||!W().getBool("WEBGL_PACK_BINARY_OPERATIONS")||!w){let k=f?l[0]*l[1]*l[2]:l[0]*l[2]*l[3],v=pe({inputs:{x:r},backend:o,attrs:{shape:[1,k,t.inChannels]}}),D=pe({inputs:{x:e},backend:o,attrs:{shape:[1,t.inChannels,t.outChannels]}}),A=Ju({a:v,b:D,transposeA:d,transposeB:h,backend:o,bias:n,activation:i,preluActivationWeights:s,leakyreluAlpha:a});g=pe({inputs:{x:A},backend:o,attrs:{shape:t.outShape}}),y.push(v),y.push(D),y.push(A)}else{let k=f?l[0]*l[1]*(l[2]+1):l[0]*l[2]*(l[3]+1),v={dataId:r.dataId,shape:[1,k,t.inChannels],dtype:r.dtype},D=u.shape;u.shape=u.shape.slice(),u.shape[u.shape.length-2]++,x.assert(dl(u.shape,v.shape),()=>`packed reshape ${u.shape} to ${v.shape} isn't free`);let A=pe({inputs:{x:e},backend:o,attrs:{shape:[1,t.inChannels,t.outChannels]}});y.push(A);let R=Ju({a:v,b:A,backend:o,transposeA:d,transposeB:h,bias:n,activation:i,preluActivationWeights:s,leakyreluAlpha:a}),P=o.texData.get(R.dataId);x.assert(P.isPacked,()=>"batchMatMul result is expected to be packed"),u.shape=D,P.shape=t.outShape,g=jt({inputs:{x:R},backend:o}),g.shape=t.outShape,y.push(R)}for(let k of y)o.disposeIntermediateTensorInfo(k);return g}function Kg({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,w=!1,k=[],v=pe({inputs:{x:r},backend:o,attrs:{shape:r.shape.slice(1)}}),D=pe({inputs:{x:e},backend:o,attrs:{shape:[1,h,x.sizeFromShape(e.shape)/h]}});k.push(v),k.push(D);let A=new ov(y,v.shape,t),R=o.runWebGLProgram(A,[v],"float32"),P=pe({inputs:{x:R},backend:o,attrs:{shape:[1,y[0],y[1]]}});k.push(R),k.push(P);let L=n!=null,G=s!=null,j=i==="leakyrelu",U=i?gl(i,!0):null,H=new vf(P.shape,D.shape,[1,g,t.outChannels],b,w,L,U,G,j),q=[P,D];if(n&&q.push(n),G&&q.push(s),j){let re=o.makeTensorInfo([],"float32",x.createScalarValue(a,"float32"));q.push(re),k.push(re)}let X=o.runWebGLProgram(H,q,"float32"),oe=d?[1,m,p,t.outChannels]:[1,t.outChannels,m,p],Y=pe({inputs:{x:X},backend:o,attrs:{shape:oe}});k.push(X);for(let re of k)o.disposeIntermediateTensorInfo(re);return Y}function U5(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,filter:s}=e,{strides:a,pad:i,dataFormat:l,dilations:u,dimRoundingMode:c}=o,p=N.convertConv2DDataFormat(l),m=N.computeConv2DInfo(n.shape,s.shape,a,u,i,c,!1,p),f;if(m.filterHeight===1&&m.filterWidth===1&&m.dilationHeight===1&&m.dilationWidth===1&&m.strideHeight===1&&m.strideWidth===1&&(m.padInfo.type==="SAME"||m.padInfo.type==="VALID"))f=qg({x:n,filter:s,convInfo:m,backend:t});else if(W().getBool("WEBGL_CONV_IM2COL")&&n.shape[0]===1)f=Kg({x:n,filter:s,convInfo:m,backend:t});else{let h=new If(m);f=t.runWebGLProgram(h,[n,s],"float32")}let d=pe({inputs:{x:f},backend:t,attrs:{shape:m.outShape}});return t.disposeIntermediateTensorInfo(f),d}var S2={kernelName:Zo,backendName:"webgl",kernelFunc:U5};var nv=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);
|
|
}
|
|
`}},sv=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);
|
|
}
|
|
`}},iv=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);
|
|
}
|
|
`}},av=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 H5(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,dy:s}=e,{strides:a,pad:i,dataFormat:l,dimRoundingMode:u,filterShape:c}=o,p=N.convertConv2DDataFormat(l),m=N.computeConv2DInfo(n.shape,c,a,1,i,u,!1,p),f=new nv(m);return t.runWebGLProgram(f,[n,s],"float32")}var T2={kernelName:Wl,backendName:"webgl",kernelFunc:H5};function q5(r){let{inputs:e,backend:t,attrs:o}=r,{dy:n,filter:s}=e,{inputShape:a,strides:i,pad:l,dataFormat:u,dimRoundingMode:c}=o,p=N.convertConv2DDataFormat(u),m=N.computeConv2DInfo(a,s.shape,i,1,l,c,!1,p),f=new sv(m);return t.runWebGLProgram(f,[n,s],"float32")}var A2={kernelName:Jo,backendName:"webgl",kernelFunc:q5};function K5(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,filter:s}=e,{strides:a,pad:i,dilations:l}=o,u=N.computeConv3DInfo(n.shape,s.shape,a,l,i),c=new rv(u);return t.runWebGLProgram(c,[n,s],"float32")}var E2={kernelName:na,backendName:"webgl",kernelFunc:K5};function X5(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,dy:s}=e,{strides:a,pad:i,filterShape:l}=o,u=N.computeConv3DInfo(n.shape,l,a,1,i),c=new iv(u);return t.runWebGLProgram(c,[n,s],"float32")}var D2={kernelName:jl,backendName:"webgl",kernelFunc:X5};function Y5(r){let{inputs:e,backend:t,attrs:o}=r,{dy:n,filter:s}=e,{pad:a,strides:i,inputShape:l}=o,u=N.computeConv3DInfo(l,s.shape,i,1,a),c=new av(u);return t.runWebGLProgram(c,[n,s],"float32")}var $2={kernelName:Ul,backendName:"webgl",kernelFunc:Y5};var Z5=Vg+`
|
|
return cos(x);
|
|
`,J5=ke({opSnippet:Z5}),R2={kernelName:Qo,backendName:"webgl",kernelFunc:J5};var Q5=`
|
|
float e2x = exp(-x);
|
|
return (e2x + 1.0 / e2x) / 2.0;
|
|
`,eX=ke({opSnippet:Q5}),F2={kernelName:ei,backendName:"webgl",kernelFunc:eX};var lv=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,v]=m>1?[`${(l-1)/(m-1)}`,"(x2-x1) * width_ratio",`x1*${h} + float(x)*(width_scale)`]:["0.0","0.0",`0.5 * (x1+x2) * ${h}`];this.userCode=`
|
|
const float height_ratio = float(${g});
|
|
const float width_ratio = float(${w});
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int y = coords[1];
|
|
int x = coords[2];
|
|
int d = coords[3];
|
|
|
|
// get box vals
|
|
float y1 = getBoxes(b,0);
|
|
float x1 = getBoxes(b,1);
|
|
float y2 = getBoxes(b,2);
|
|
float x2 = getBoxes(b,3);
|
|
|
|
// get image in batch index
|
|
int bInd = round(getBoxInd(b));
|
|
if(bInd < 0 || bInd >= ${a}) {
|
|
return;
|
|
}
|
|
|
|
float height_scale = ${y};
|
|
float width_scale = ${k};
|
|
|
|
float in_y = ${b};
|
|
if( in_y < 0.0 || in_y > ${d} ) {
|
|
setOutput(float(${s}));
|
|
return;
|
|
}
|
|
float in_x = ${v};
|
|
if( in_x < 0.0 || in_x > ${h} ) {
|
|
setOutput(float(${s}));
|
|
return;
|
|
}
|
|
|
|
vec2 sourceFracIndexCR = vec2(in_x,in_y);
|
|
if(${f} == 1) {
|
|
// Compute the four integer indices.
|
|
ivec2 sourceFloorCR = ivec2(sourceFracIndexCR);
|
|
ivec2 sourceCeilCR = ivec2(ceil(sourceFracIndexCR));
|
|
|
|
float topLeft = getImage(b, sourceFloorCR.y, sourceFloorCR.x, d);
|
|
float bottomLeft = getImage(b, sourceCeilCR.y, sourceFloorCR.x, d);
|
|
float topRight = getImage(b, sourceFloorCR.y, sourceCeilCR.x, d);
|
|
float bottomRight = getImage(b, sourceCeilCR.y, sourceCeilCR.x, d);
|
|
|
|
vec2 fracCR = sourceFracIndexCR - vec2(sourceFloorCR);
|
|
|
|
float top = topLeft + (topRight - topLeft) * fracCR.x;
|
|
float bottom = bottomLeft + (bottomRight - bottomLeft) * fracCR.x;
|
|
float newValue = top + (bottom - top) * fracCR.y;
|
|
setOutput(newValue);
|
|
} else {
|
|
// Compute the coordinators of nearest neighbor point.
|
|
ivec2 sourceNearestCR = ivec2(floor(
|
|
sourceFracIndexCR + vec2(0.5,0.5)));
|
|
float newValue = getImage(b, sourceNearestCR.y, sourceNearestCR.x, d);
|
|
setOutput(newValue);
|
|
}
|
|
}
|
|
`}};var tX=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 lv(n.shape,s.shape,i,l,u);return t.runWebGLProgram(c,[n,s,a],"float32")},O2={kernelName:ti,backendName:"webgl",kernelFunc:tX};var Xg=class{constructor(e,t,o){this.variableNames=["x"],this.outputShape=e;let n=e.length,s=t?"0.0":`getX(${P2(n,"coords")})`,a=e[e.length-1],i="",l="";t?(i=o?`end != ${a-1}`:"end != 0",l=o?"end + 1":"end - 1"):(i=o?`end + pow2 < ${a}`:"end >= pow2",l=o?"end + pow2":"end - pow2"),this.userCode=`
|
|
uniform float index;
|
|
void main() {
|
|
${Le(n)} coords = getOutputCoords();
|
|
int end = ${M2(n,"coords")};
|
|
float val = ${s};
|
|
int pow2 = int(pow(2.0, index));
|
|
if (${i}) {
|
|
int idx = ${l};
|
|
${M2(n,"coords")} = idx;
|
|
val += getX(${P2(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 P2(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 M2(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 rX(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{axis:s,exclusive:a,reverse:i}=o,l=n.shape.length,u=N.getAxesPermutation([s],l),c=n;u!=null&&(c=Mt({inputs:{x:n},backend:t,attrs:{perm:u}}));let p=N.getInnerMostAxes(1,l)[0];if(p!==l-1)throw new Error(`WebGL cumsum shader expects an inner-most axis=${n.shape.length-1} but got axis=${s}`);let m=c.shape[p],f=jt({inputs:{x:c},backend:t});for(let d=0;d<=Math.ceil(Math.log2(m))-1;d++){let h=new Xg(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 Xg(c.shape,a,i),h=f;f=t.runWebGLProgram(d,[f],f.dtype),t.disposeIntermediateTensorInfo(h)}if(u!=null){let d=N.getUndoAxesPermutation(u),h=Mt({inputs:{x:f},backend:t,attrs:{perm:d}});return t.disposeIntermediateTensorInfo(f),t.disposeIntermediateTensorInfo(c),h}return f}var L2={kernelName:en,backendName:"webgl",kernelFunc:rX};function oX(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=Mg(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=UA(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 z2={kernelName:Hl,backendName:"webgl",kernelFunc:oX};var uv=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 nX(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 uv(d,s,a);return t.runWebGLProgram(h,[n],n.dtype)}var B2={kernelName:ri,backendName:"webgl",kernelFunc:nX};var Nf=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 w=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;
|
|
${w}
|
|
${b}
|
|
setOutput(result);
|
|
}
|
|
`}};var Sf=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 v=0;v<d;v++)for(let D=0;D<h;D++)y+=`
|
|
vec4 xTexelR${v}C${D*2} = vec4(0.);
|
|
vec4 wR${v}C${D} = vec4(0.);
|
|
vec4 xR${v}C${D} = vec4(0.);`;for(let v=0;v<d;v++)for(let D=0;D<g;D++){let A=D*2;if(y+=`
|
|
xR = xRCorner + ${v*m};
|
|
xC = xCCorner + ${A*f};
|
|
`,p===1){if(A<h&&(u%2==1?y+=`
|
|
xCOffset = xC + 1;
|
|
if(xR >= 0 && xR < ${a} && xCOffset >= 0 && xCOffset < ${i}) {
|
|
xTexelR${v}C${A} = getX(batch, xR, xCOffset, d1);
|
|
|
|
// Need to manually clear unused channels in case
|
|
// we're reading from recycled texture.
|
|
if(xCOffset + 1 >= ${i}) {
|
|
xTexelR${v}C${A}.zw = vec2(0.);
|
|
}
|
|
} else {
|
|
xTexelR${v}C${A} = vec4(0.);
|
|
}
|
|
|
|
xCOffset = xC + 1 - 2;
|
|
if(xR >= 0 && xR < ${a} && xCOffset >= 0 && xCOffset < ${i}) {
|
|
vec4 previous = getX(batch, xR, xCOffset, d1);
|
|
|
|
// Need to manually clear unused channels in case
|
|
// we're reading from recycled texture.
|
|
if(xCOffset + 1 >= ${i}) {
|
|
previous.zw = vec2(0.);
|
|
}
|
|
|
|
xR${v}C${A} = vec4(previous.zw, xTexelR${v}C${A}.xy);
|
|
} else {
|
|
xR${v}C${A} = vec4(0, 0, xTexelR${v}C${A}.xy);
|
|
}
|
|
`:y+=`
|
|
if(xR >= 0 && xR < ${a} && xC >= 0 && xC < ${i}) {
|
|
xTexelR${v}C${A} = getX(batch, xR, xC, d1);
|
|
} else {
|
|
xTexelR${v}C${A} = vec4(0.);
|
|
}
|
|
|
|
xR${v}C${A} = xTexelR${v}C${A};
|
|
`,A+1<h)){let R=u%2==0?x.nearestLargerEven(f):f;f%2==0&&u%2==1||f%2!=0&&u%2!=1?(y+=`
|
|
xCOffset = xC + ${u%2} + ${R};
|
|
|
|
if(xR >= 0 && xR < ${a} &&
|
|
xCOffset >= 0 && xCOffset < ${i}) {
|
|
xTexelR${v}C${A+2} = getX(batch, xR, xCOffset, d1);
|
|
}
|
|
`,f>1&&(y+=`
|
|
xCOffset -= 2;
|
|
if(xR >= 0 && xR < ${a} &&
|
|
xCOffset >= 0 && xCOffset < ${i}) {
|
|
xTexelR${v}C${A} = getX(batch, xR, xCOffset, d1);
|
|
} else {
|
|
xTexelR${v}C${A} = vec4(0.);
|
|
}
|
|
`),y+=`
|
|
xR${v}C${A+1} = vec4(
|
|
xTexelR${v}C${A}.zw, xTexelR${v}C${A+2}.xy);
|
|
`):y+=`
|
|
xCOffset = xC + ${R};
|
|
|
|
if(xR >= 0 && xR < ${a} &&
|
|
xCOffset >= 0 && xCOffset < ${i}) {
|
|
xTexelR${v}C${A+2} = getX(batch, xR, xCOffset, d1);
|
|
}
|
|
|
|
xR${v}C${A+1} = xTexelR${v}C${A+2};
|
|
`}}else A<h&&(y+=`
|
|
if(xR >= 0 && xR < ${a}) {
|
|
`,u%2==1?(y+=`
|
|
xCOffset = xC + 1 - ${p};
|
|
if(xCOffset >= 0 && xCOffset < ${i}) {
|
|
xTexelR${v}C${A} = getX(batch, xR, xCOffset, d1);
|
|
} else {
|
|
xTexelR${v}C${A} = vec4(0.);
|
|
}
|
|
|
|
if(xC + 1 >= 0 && xC + 1 < ${i}) {
|
|
xTexelR${v}C${A+2} = getX(batch, xR, xC + 1, d1);
|
|
} else {
|
|
xTexelR${v}C${A+2} = vec4(0.);
|
|
}
|
|
|
|
xR${v}C${A} = vec4(
|
|
xTexelR${v}C${A}.zw, xTexelR${v}C${A+2}.zw);
|
|
`,A+1<h&&(y+=`
|
|
vec4 final = vec4(0.);
|
|
xCOffset = xC + 1 + ${p};
|
|
if(xCOffset >= 0 && xCOffset < ${i}) {
|
|
final = getX(batch, xR, xCOffset, d1);
|
|
}
|
|
xR${v}C${A+1} = vec4(xTexelR${v}C${A+2}.xy, final.xy);
|
|
`)):(y+=`
|
|
if(xC >= 0 && xC < ${i}) {
|
|
xTexelR${v}C${A} = getX(batch, xR, xC, d1);
|
|
} else {
|
|
xTexelR${v}C${A} = vec4(0.);
|
|
}
|
|
|
|
xCOffset = xC + ${p};
|
|
if(xCOffset >= 0 && xCOffset < ${i}) {
|
|
xTexelR${v}C${A+2} = getX(batch, xR, xCOffset, d1);
|
|
} else {
|
|
xTexelR${v}C${A+2} = vec4(0.);
|
|
}
|
|
|
|
xR${v}C${A} = vec4(
|
|
xTexelR${v}C${A}.xy, xTexelR${v}C${A+2}.xy);
|
|
`,A+1<h&&(y+=`
|
|
xR${v}C${A+1} = vec4(
|
|
xTexelR${v}C${A}.zw, xTexelR${v}C${A+2}.zw);
|
|
`)),y+="}");A<h&&(y+=`
|
|
vec4 wTexelR${v}C${A} = getW(${v}, ${A}, d1, q);
|
|
wR${v}C${A} = vec4(wTexelR${v}C${A}.xz, wTexelR${v}C${A}.xz);
|
|
`,A+1<h&&(y+=`
|
|
vec4 wTexelR${v}C${A+1} = getW(${v}, ${A+1}, d1, q);
|
|
wR${v}C${A+1} =
|
|
vec4(wTexelR${v}C${A+1}.xz, wTexelR${v}C${A+1}.xz);`))}for(let v=0;v<d;v++)for(let D=0;D<h;D++)y+=`dotProd += xR${v}C${D} * wR${v}C${D};`;let b="",w="";o&&(n?b=`vec4 activation(vec4 a) {
|
|
vec4 b = getPreluActivationWeightsAtOutCoords();
|
|
${o}
|
|
}`:s?b=`vec4 activation(vec4 a) {
|
|
vec4 b = getLeakyreluAlphaAtOutCoords();
|
|
${o}
|
|
}`:b=`vec4 activation(vec4 x) {
|
|
${o}
|
|
}`,w="result = activation(result);");let k=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),n&&this.variableNames.push("preluActivationWeights"),s&&this.variableNames.push("leakyreluAlpha"),this.userCode=`
|
|
${b}
|
|
|
|
const ivec2 strides = ivec2(${c}, ${p});
|
|
const ivec2 pads = ivec2(${l}, ${u});
|
|
|
|
void main() {
|
|
|
|
ivec4 coords = getOutputCoords();
|
|
int batch = coords.x;
|
|
ivec2 xRCCorner = coords.yz * strides - pads;
|
|
int d2 = coords.w;
|
|
int d1 = d2;
|
|
int q = 0;
|
|
int xRCorner = xRCCorner.x;
|
|
int xCCorner = xRCCorner.y;
|
|
|
|
vec4 dotProd = vec4(0.);
|
|
|
|
${y}
|
|
|
|
vec4 result = dotProd;
|
|
${k}
|
|
${w}
|
|
setOutput(result);
|
|
}
|
|
`}};function sX(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,filter:s}=e,{strides:a,pad:i,dilations:l,dimRoundingMode:u}=o,c=l;c==null&&(c=[1,1]),x.assert(N.eitherStridesOrDilationsAreOne(a,c),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${a} and dilations '${c}'`);let p=N.computeConv2DInfo(n.shape,s.shape,a,c,i,u,!0),m;return W().getBool("WEBGL_PACK_DEPTHWISECONV")&&p.strideWidth<=2&&p.outChannels/p.inChannels==1?m=new Sf(p):m=new Nf(p),t.runWebGLProgram(m,[n,s],"float32")}var V2={kernelName:tn,backendName:"webgl",kernelFunc:sX};var cv=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);
|
|
}
|
|
`}},pv=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 iX(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,dy:s}=e,{strides:a,dilations:i,pad:l,dimRoundingMode:u,filterShape:c}=o,p=N.computeConv2DInfo(n.shape,c,a,i,l,u,!0),m=new cv(p);return t.runWebGLProgram(m,[n,s],"float32")}var G2={kernelName:ql,backendName:"webgl",kernelFunc:iX};function aX(r){let{inputs:e,backend:t,attrs:o}=r,{dy:n,filter:s}=e,{strides:a,dilations:i,pad:l,dimRoundingMode:u,inputShape:c}=o,p=N.computeConv2DInfo(c,s.shape,a,i,l,u,!0),m=new pv(p);return t.runWebGLProgram(m,[n,s],"float32")}var W2={kernelName:Kl,backendName:"webgl",kernelFunc:aX};var mv=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 lX(r){let{inputs:e,backend:t}=r,{x:o}=e,n=[...o.shape,...o.shape],s=x.sizeFromShape(o.shape),a=pe({inputs:{x:o},backend:t,attrs:{shape:[s]}}),i=new mv(s),l=t.runWebGLProgram(i,[a],a.dtype),u=pe({inputs:{x:l},backend:t,attrs:{shape:n}});return t.disposeIntermediateTensorInfo(a),t.disposeIntermediateTensorInfo(l),u}var j2={kernelName:Xl,backendName:"webgl",kernelFunc:lX};var fv=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 uX(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,filter:s}=e,{strides:a,pad:i,dilations:l}=o,u=N.computeDilation2DInfo(n.shape,s.shape,a,i,"NHWC",l),c,p=new fv(u);c=t.runWebGLProgram(p,[n,s],"float32");let m=pe({inputs:{x:c},backend:t,attrs:{shape:u.outShape}});return t.disposeIntermediateTensorInfo(c),m}var U2={kernelName:sa,backendName:"webgl",kernelFunc:uX};var cX="return (x >= 0.0) ? x : (exp(x) - 1.0);",pX=`
|
|
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;
|
|
`,mX=ke({opSnippet:cX,packedOpSnippet:pX}),H2={kernelName:oi,backendName:"webgl",kernelFunc:mX};var fX="return (b >= 1.0) ? a : a * (b + 1.0);",dX=`
|
|
vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));
|
|
return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));
|
|
`,hX=r=>{let{inputs:e,backend:t}=r,{dy:o,y:n}=e,s=W().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Ps(dX,o.shape,n.shape):new Xn(fX,o.shape,n.shape);return t.runWebGLProgram(s,[o,n],o.dtype)},q2={kernelName:Yl,backendName:"webgl",kernelFunc:hX};var gX=`
|
|
return vec4(equal(a, b));
|
|
`,xX="return float(a == b);",yX=nt({opSnippet:xX,packedOpSnippet:gX,dtype:"bool"}),K2={kernelName:si,backendName:"webgl",kernelFunc:yX};var bX=`
|
|
// Error function is calculated approximately with elementary function.
|
|
// See "Handbook of Mathematical Functions with Formulas,
|
|
// Graphs, and Mathematical Tables", Abramowitz and Stegun.
|
|
float p = ${N.ERF_P};
|
|
float a1 = ${N.ERF_A1};
|
|
float a2 = ${N.ERF_A2};
|
|
float a3 = ${N.ERF_A3};
|
|
float a4 = ${N.ERF_A4};
|
|
float a5 = ${N.ERF_A5};
|
|
|
|
float sign = sign(x);
|
|
x = abs(x);
|
|
float t = 1.0 / (1.0 + p * x);
|
|
return sign * (1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*exp(-x*x));
|
|
`,wX=ke({opSnippet:bX}),X2={kernelName:ni,backendName:"webgl",kernelFunc:wX};var Y2="return exp(x);",dv=ke({opSnippet:Y2,packedOpSnippet:Y2,cpuKernelImpl:KA}),Z2={kernelName:on,backendName:"webgl",kernelFunc:dv};function Yg(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),pe({inputs:{x:s},backend:o,attrs:{shape:i}})}var J2={kernelName:us,backendName:"webgl",kernelFunc:Yg};var Q2="return exp(x) - 1.0;",kX=ke({opSnippet:Q2,packedOpSnippet:Q2,cpuKernelImpl:XA}),eD={kernelName:ii,backendName:"webgl",kernelFunc:kX};var Zg=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 Jg(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,i=pe({inputs:{x:r},backend:t,attrs:{shape:[a,s]}}),l=i.shape,u=new Zg("real",l,e),c=new Zg("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=lo({inputs:{real:m,imag:f},backend:t});t.disposeIntermediateTensorInfo(m),t.disposeIntermediateTensorInfo(f);let h=pe({inputs:{x:d},backend:t,attrs:{shape:r.shape}});return t.disposeIntermediateTensorInfo(i),t.disposeIntermediateTensorInfo(d),h}function _X(r){let{inputs:e,backend:t}=r,{input:o}=e;return Jg(o,!1,t)}var tD={kernelName:Zl,backendName:"webgl",kernelFunc:_X};var hv=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 Tf(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 hv(o,n),i=a.getCustomSetupFunc(n);return e.runWebGLProgram(a,[],s,i)}}var rD={kernelName:ia,backendName:"webgl",kernelFunc:Tf};var gv=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 oD={kernelName:ai,backendName:"webgl",kernelFunc:({inputs:r,backend:e})=>{let{image:t}=r,o=e,n=new gv(t.shape);return o.runWebGLProgram(n,[t],t.dtype)}};var nD="return floor(x);",vX=ke({opSnippet:nD,packedOpSnippet:nD,cpuKernelImpl:YA}),sD={kernelName:nn,backendName:"webgl",kernelFunc:vX};var CX=`
|
|
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;
|
|
}
|
|
`,IX=`
|
|
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);
|
|
`,NX=nt({opSnippet:CX,packedOpSnippet:IX,dtype:"int32"}),iD={kernelName:sn,backendName:"webgl",kernelFunc:NX};var xv=class{constructor(e){this.variableNames=["A"];let t=Rt(),[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 yv=class{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;let t=Rt(),[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 aD={kernelName:Oc,backendName:"webgl",kernelFunc:SX},wp;function SX(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,u]=a?[n.videoWidth,n.videoHeight]:[n.width,n.height],c=[u,l],p=[u,l,s];(i||a)&&(wp==null&&(wp=document.createElement("canvas").getContext("2d")),wp.canvas.width=l,wp.canvas.height=u,wp.drawImage(n,0,0,l,u),n=wp.canvas);let m=t.makeTensorInfo(c,"int32");t.texData.get(m.dataId).usage=Er.PIXELS,t.gpgpu.uploadPixelDataToTexture(t.getTexture(m.dataId),n);let f=W().getBool("WEBGL_PACK")?new yv(p):new xv(p),d=t.runWebGLProgram(f,[m],"int32");return t.disposeData(m.dataId),d}function TX(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,filter:s,bias:a,preluActivationWeights:i}=e,{strides:l,pad:u,dataFormat:c,dilations:p,dimRoundingMode:m,activation:f,leakyreluAlpha:d}=o,h=N.convertConv2DDataFormat(c),g=N.computeConv2DInfo(n.shape,s.shape,l,p,u,m,!1,h),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=qg({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=Kg({x:n,filter:s,convInfo:g,backend:t,bias:a,activation:f,preluActivationWeights:i,leakyreluAlpha:d});else{let k=a!=null,v=i!=null,D=f==="leakyrelu",A=f?gl(f,!1):null,R=new If(g,k,A,v,D),P=[n,s];if(a&&P.push(a),i&&P.push(i),D){let L=t.makeTensorInfo([],"float32",x.createScalarValue(d,"float32"));P.push(L),b.push(L)}y=t.runWebGLProgram(R,P,"float32")}let w=pe({inputs:{x:y},backend:t,attrs:{shape:g.outShape}});return b.push(y),b.forEach(k=>t.disposeIntermediateTensorInfo(k)),w}var lD={kernelName:ks,backendName:"webgl",kernelFunc:TX};function AX(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(N.eitherStridesOrDilationsAreOne(l,h),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${l} and dilations '${h}'`);let g=N.computeConv2DInfo(n.shape,s.shape,l,h,u,p,!0),y=W().getBool("WEBGL_PACK_DEPTHWISECONV")&&g.strideWidth<=2&&g.outChannels/g.inChannels==1,b=m?gl(m,y):null,w=[n,s],k=a!=null,v=i!=null,D=m==="leakyrelu";if(k&&w.push(a),v&&w.push(i),D){let P=t.makeTensorInfo([],"float32",x.createScalarValue(f,"float32"));w.push(P),d.push(P)}let A;y?A=new Sf(g,k,b,v,D):A=new Nf(g,k,b,v,D);let R=t.runWebGLProgram(A,w,"float32");return d.forEach(P=>t.disposeIntermediateTensorInfo(P)),R}var uD={kernelName:_s,backendName:"webgl",kernelFunc:AX};var bv=class{constructor(e,t,o){this.sliceDim=e,this.strides=t,this.variableNames=["x","indices"],this.outputShape=o;let n=Le(t.length),s=Le(o.length),a=this.sliceDim>1?"strides[j]":"strides";this.userCode=`
|
|
${n} strides = ${n}(${this.strides});
|
|
void main() {
|
|
${s} coords = getOutputCoords();
|
|
int flattenIndex = 0;
|
|
for (int j = 0; j < ${this.sliceDim}; j++) {
|
|
int index = round(getIndices(coords[0], j));
|
|
flattenIndex += index * ${a};
|
|
}
|
|
setOutput(getX(flattenIndex, coords[1]));
|
|
}
|
|
`}};function EX(r){let{inputs:e,backend:t}=r,{params:o,indices:n}=e,s=n.shape,a=s[s.length-1],[i,l,u,c]=N.prepareAndValidate(o,n),p=pe({inputs:{x:n},backend:t,attrs:{shape:[l,a]}}),m=pe({inputs:{x:o},backend:t,attrs:{shape:[x.sizeFromShape(o.shape)/u,u]}}),f=new bv(a,c,[l,u]),d=t.runWebGLProgram(f,[m,p],m.dtype),h=pe({inputs:{x:d},backend:t,attrs:{shape:i}});return t.disposeIntermediateTensorInfo(p),t.disposeIntermediateTensorInfo(m),t.disposeIntermediateTensorInfo(d),h}var cD={kernelName:li,backendName:"webgl",kernelFunc:EX};var wv=class{constructor(e,t){this.variableNames=["A","indices"],this.outputShape=t,this.rank=t.length;let o=Le(this.rank),n=DX(e,2);this.userCode=`
|
|
void main() {
|
|
${o} resRC = getOutputCoords();
|
|
setOutput(getA(${n}));
|
|
}
|
|
`}};function DX(r,e){let t=["resRC.x","resRC.y","resRC.z","resRC.w"],o=[];for(let n=0;n<r.length;n++)n===2?o.push("int(getIndices(resRC.x, resRC.z))"):o.push(`${t[n]}`);return o.join()}function $X(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,indices:s}=e,{axis:a,batchDims:i}=o,l=x.parseAxisParam(a,n.shape)[0],u=N.segment_util.collectGatherOpShapeInfo(n,s,l,i),c=x.sizeFromShape(s.shape),p=[],m=pe({inputs:{x:n},backend:t,attrs:{shape:[u.batchSize,u.outerSize,u.dimSize,u.sliceSize]}}),f=pe({inputs:{x:s},backend:t,attrs:{shape:[u.batchSize,c/u.batchSize]}});p.push(m),p.push(f);let d=[u.batchSize,u.outerSize,c/u.batchSize,u.sliceSize];if(t.shouldExecuteOnCPU([n,s])||n.dtype==="string"){let b=t.bufferSync(f),w=t.bufferSync(m),k=ZA(w,b,d);return p.forEach(v=>t.disposeIntermediateTensorInfo(v)),t.makeTensorInfo(u.outputShape,k.dtype,k.values)}let h=new wv(m.shape,d),g=t.runWebGLProgram(h,[m,f],m.dtype);p.push(g);let y=pe({inputs:{x:g},backend:t,attrs:{shape:u.outputShape}});return p.forEach(b=>t.disposeIntermediateTensorInfo(b)),y}var pD={kernelName:cs,backendName:"webgl",kernelFunc:$X};var RX="return float(a > b);",FX=`
|
|
return vec4(greaterThan(a, b));
|
|
`,OX=nt({opSnippet:RX,packedOpSnippet:FX,cpuKernelImpl:JA,dtype:"bool"}),mD={kernelName:ui,backendName:"webgl",kernelFunc:OX};var PX="return float(a >= b);",MX=`
|
|
return vec4(greaterThanEqual(a, b));
|
|
`,LX=nt({opSnippet:PX,packedOpSnippet:MX,dtype:"bool"}),fD={kernelName:ln,backendName:"webgl",kernelFunc:LX};function zX(r){let{inputs:e,backend:t}=r,{input:o}=e;return Jg(o,!0,t)}var dD={kernelName:Jl,backendName:"webgl",kernelFunc:zX};var BX="return float(!isnan(x) && !isinf(x));",VX=ke({opSnippet:BX,dtype:"bool"}),hD={kernelName:ci,backendName:"webgl",kernelFunc:VX};var GX="return float(isinf(x));",WX=ke({opSnippet:GX,dtype:"bool"}),gD={kernelName:pi,backendName:"webgl",kernelFunc:WX};var jX="return float(isnan(x));",UX=ke({opSnippet:jX,dtype:"bool"}),xD={kernelName:mi,backendName:"webgl",kernelFunc:UX};var HX="return float(a < b);",qX=`
|
|
return vec4(lessThan(a, b));
|
|
`,KX=nt({opSnippet:HX,packedOpSnippet:qX,cpuKernelImpl:QA,dtype:"bool"}),yD={kernelName:fi,backendName:"webgl",kernelFunc:KX};var XX="return float(a <= b);",YX=`
|
|
return vec4(lessThanEqual(a, b));
|
|
`,ZX=nt({opSnippet:XX,packedOpSnippet:YX,dtype:"bool"}),bD={kernelName:di,backendName:"webgl",kernelFunc:ZX};function JX(r){let{backend:e,attrs:t}=r,{start:o,stop:n,num:s}=t,a=eE(o,n,s);return e.makeTensorInfo([a.length],"float32",a)}var wD={kernelName:eu,backendName:"webgl",kernelFunc:JX};var QX=`if (x < 0.0) return NAN;
|
|
return log(x);`,e8=`
|
|
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;
|
|
`,t8=ke({opSnippet:QX,packedOpSnippet:e8,cpuKernelImpl:tE}),kD={kernelName:cn,backendName:"webgl",kernelFunc:t8};var r8="return log(1.0 + x);",o8=ke({opSnippet:r8}),_D={kernelName:hi,backendName:"webgl",kernelFunc:o8};var n8="return float(a >= 1.0 && b >= 1.0);",s8=`
|
|
return vec4(
|
|
vec4(greaterThanEqual(a, vec4(1.0))) *
|
|
vec4(greaterThanEqual(b, vec4(1.0))));
|
|
`,i8=nt({opSnippet:n8,packedOpSnippet:s8,dtype:"bool"}),vD={kernelName:gi,backendName:"webgl",kernelFunc:i8};var a8="return float(!(x >= 1.0));",l8=ke({opSnippet:a8}),CD={kernelName:Ja,backendName:"webgl",kernelFunc:l8};var u8="return float(a >= 1.0 || b >= 1.0);",c8=`
|
|
return min(
|
|
vec4(greaterThanEqual(a, vec4(1.0))) +
|
|
vec4(greaterThanEqual(b, vec4(1.0))),
|
|
vec4(1.0));
|
|
`,p8=nt({opSnippet:u8,packedOpSnippet:c8,dtype:"bool"}),ID={kernelName:Qa,backendName:"webgl",kernelFunc:p8};var kv=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 _v=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 m8=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 _v(n.shape,s,a,i,l):new kv(n.shape,s,a,i,l);return t.runWebGLProgram(u,[n],n.dtype)},ND={kernelName:aa,backendName:"webgl",kernelFunc:m8};var vv=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 f8=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 vv(n.shape,i,l,u,c);return t.runWebGLProgram(p,[n,s,a],n.dtype)},SD={kernelName:tu,backendName:"webgl",kernelFunc:f8};function TD(r,e,t,o){let n=x.sizeFromShape(e),a=x.sizeFromShape(r.shape)/n,i=pe({inputs:{x:r},attrs:{shape:[a,n]},backend:o}),l=No(i,r.dtype,"max",o),u=pe({inputs:{x:l},attrs:{shape:t},backend:o});return o.disposeIntermediateTensorInfo(i),o.disposeIntermediateTensorInfo(l),u}function Cv(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=N.getAxesPermutation(u,i),p=c!=null,m=t.shouldExecuteOnCPU([n]),f=n;if(p){if(m){let w=t.texData.get(f.dataId).values,k=new Array(i);for(let A=0;A<k.length;A++)k[A]=n.shape[c[A]];let v=bp(w,n.shape,n.dtype,c,k);f=t.makeTensorInfo(k,n.dtype);let D=t.texData.get(f.dataId);D.values=v}else f=xl(n,c,t);u=N.getInnerMostAxes(u.length,i)}N.assertAxesAreInnerMostDims("max",u,i);let[d,h]=N.computeOutAndReduceShapes(f.shape,u),g=d;a&&(g=N.expandShapeToKeepDim(d,l));let y;if(m){let w=t.texData.get(f.dataId).values,k=rE(w,x.sizeFromShape(h),g,n.dtype);y=t.makeTensorInfo(g,n.dtype);let v=t.texData.get(y.dataId);v.values=k}else y=TD(f,h,g,t);return p&&t.disposeIntermediateTensorInfo(f),y}var AD={kernelName:pn,backendName:"webgl",kernelFunc:Cv};var d8=Bg+`
|
|
return max(a, b);
|
|
`,h8=`
|
|
vec4 result = vec4(max(a, b));
|
|
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
|
|
`+hl+`
|
|
return result;
|
|
`,g8=nt({opSnippet:d8,packedOpSnippet:h8,cpuKernelImpl:oE}),ED={kernelName:mn,backendName:"webgl",kernelFunc:g8};function x8(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e;Rs(n,"maxPool");let{filterSize:s,strides:a,pad:i,dimRoundingMode:l}=o,u=1;x.assert(N.eitherStridesOrDilationsAreOne(a,u),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${u}'`);let c=N.computePool2DInfo(n.shape,s,a,u,i,l);if(c.filterWidth===1&&c.filterHeight===1&&x.arraysEqual(c.inShape,c.outShape))return jt({inputs:{x:n},backend:t});let p=new Vi(c,"max",!1);return t.runWebGLProgram(p,[n],n.dtype)}var DD={kernelName:fn,backendName:"webgl",kernelFunc:x8};function y8(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{filterSize:s,strides:a,pad:i,dataFormat:l,dimRoundingMode:u}=o,c=[1,1,1],p=N.computePool3DInfo(n.shape,s,a,c,i,u,l),m=new Qu(p,"max",!1);return t.runWebGLProgram(m,[n],n.dtype)}var $D={kernelName:la,backendName:"webgl",kernelFunc:y8};var Iv=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);
|
|
}
|
|
`}},Nv=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 b8(r){let{inputs:e,backend:t,attrs:o}=r,{dy:n,input:s}=e,a=s,{filterSize:i,strides:l,pad:u,dimRoundingMode:c}=o,p=[1,1,1],m=N.computePool3DInfo(a.shape,i,l,p,u,c),f=new Qu(m,"max",!0),d=t.runWebGLProgram(f,[a],a.dtype),h=new Nv(m),g=t.runWebGLProgram(h,[n,d],a.dtype);return t.disposeIntermediateTensorInfo(d),g}var RD={kernelName:ou,backendName:"webgl",kernelFunc:b8};function w8(r){let{inputs:e,backend:t,attrs:o}=r,{dy:n,input:s,output:a}=e,i=s;Rs([s,a],"maxPoolGrad");let{filterSize:l,strides:u,pad:c,dimRoundingMode:p}=o,m=N.computePool2DInfo(i.shape,l,u,1,c,p),f=!0,d=new Vi(m,"max",f),h=t.runWebGLProgram(d,[i],i.dtype),g=new Iv(m),y=t.runWebGLProgram(g,[n,h],i.dtype);return t.disposeIntermediateTensorInfo(h),y}var FD={kernelName:ru,backendName:"webgl",kernelFunc:w8};function OD(r,e,t,o){let n=new Vi(t,"max",!1),s=o.runWebGLProgram(n,[r],"float32");n=new Vi(t,"max",!0,!0,e);let a=o.runWebGLProgram(n,[r],"float32");return[s,a]}var PD={kernelName:nu,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(N.eitherStridesOrDilationsAreOne(s,u),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${s} and dilations '${u}'`);let c=N.computePool2DInfo(o.shape,n,s,u,a),[p,m]=OD(o,i,c,l);return[p,m]}};function MD(r,e,t,o){let n=x.sizeFromShape(e),a=x.sizeFromShape(r.shape)/n,i=pe({inputs:{x:r},attrs:{shape:[a,n]},backend:o}),l=No(i,"float32","mean",o),u=pe({inputs:{x:l},attrs:{shape:t},backend:o});return o.disposeIntermediateTensorInfo(i),o.disposeIntermediateTensorInfo(l),u}var LD={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=N.getAxesPermutation(u,i),p=c!=null,m=a.shouldExecuteOnCPU([o]),f=[],d=o;if(p){if(m){let k=a.texData.get(d.dataId).values,v=new Array(i);for(let R=0;R<v.length;R++)v[R]=o.shape[c[R]];let D=bp(k,o.shape,o.dtype,c,v);d=a.makeTensorInfo(v,o.dtype);let A=a.texData.get(d.dataId);A.values=D}else d=xl(o,c,a);f.push(d),u=N.getInnerMostAxes(u.length,i)}N.assertAxesAreInnerMostDims("sum",u,i);let[h,g]=N.computeOutAndReduceShapes(d.shape,u),y=h;n&&(y=N.expandShapeToKeepDim(h,l));let b=MD(d,g,y,a);for(let w of f)a.disposeIntermediateTensorInfo(w);return b}};function k8(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=N.getAxesPermutation(u,i),p=n;c!=null&&(p=Mt({inputs:{x:n},backend:t,attrs:{perm:c}}),u=N.getInnerMostAxes(u.length,n.shape.length)),N.assertAxesAreInnerMostDims("min",u,i);let[m,f]=N.computeOutAndReduceShapes(p.shape,u),d=x.sizeFromShape(f),h=pe({inputs:{x:p},backend:t,attrs:{shape:[-1,d]}}),g=No(h,h.dtype,"min",t),y;if(a){let b=N.expandShapeToKeepDim(m,l);y=pe({inputs:{x:g},backend:t,attrs:{shape:b}})}else y=pe({inputs:{x:g},backend:t,attrs:{shape:m}});return t.disposeIntermediateTensorInfo(h),t.disposeIntermediateTensorInfo(g),c!=null&&t.disposeIntermediateTensorInfo(p),y}var zD={kernelName:hn,backendName:"webgl",kernelFunc:k8};var _8=Bg+`
|
|
return min(a, b);
|
|
`,v8=`
|
|
vec4 result = vec4(min(a, b));
|
|
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
|
|
`+hl+`
|
|
return result;
|
|
`,C8=nt({opSnippet:_8,packedOpSnippet:v8,cpuKernelImpl:nE}),BD={kernelName:gn,backendName:"webgl",kernelFunc:C8};var Sv=class{constructor(e,t,o){this.variableNames=["x"],this.outputShape=t.map((c,p)=>c[0]+e[p]+c[1]);let n=e.length,s=Le(n),a=t.map(c=>c[0]).join(","),i=t.map((c,p)=>c[0]+e[p]).join(","),l=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,n),u=o==="reflect"?0:1;if(n===1){this.userCode=`
|
|
int start = ${a};
|
|
int end = ${i};
|
|
|
|
void main() {
|
|
int outC = getOutputCoords();
|
|
if (outC < start) {
|
|
outC = start * 2 - outC - ${u};
|
|
} else if(outC >= end) {
|
|
outC = (end - 1) * 2 - outC + ${u};
|
|
}
|
|
setOutput(getX(outC - start));
|
|
}
|
|
`;return}this.userCode=`
|
|
${s} start = ${s}(${a});
|
|
${s} end = ${s}(${i});
|
|
|
|
void main() {
|
|
${s} outC = getOutputCoords();
|
|
for (int i = 0; i < ${n}; i++) {
|
|
if (outC[i] < start[i]) {
|
|
outC[i] = start[i] * 2 - outC[i] - ${u};
|
|
} else if(outC[i] >= end[i]) {
|
|
outC[i] = (end[i] - 1) * 2 - outC[i] + ${u};
|
|
}
|
|
}
|
|
${s} coords = outC - start;
|
|
setOutput(getX(${l}));
|
|
}
|
|
`}};var Tv=class{constructor(e,t,o){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t.map((d,h)=>d[0]+e[h]+d[1]);let n=e.length,s=Le(n),a=t.map(d=>d[0]).join(","),i=t.map((d,h)=>d[0]+e[h]).join(","),l=Wt("rc",n),u=Wt("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 I8=({inputs:r,backend:e,attrs:t})=>{let{x:o}=r,{paddings:n,mode:s}=t,a=W().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Tv(o.shape,n,s):new Sv(o.shape,n,s);return e.runWebGLProgram(a,[o],o.dtype)},VD={kernelName:ua,backendName:"webgl",kernelFunc:I8};var N8=`if (b == 0.0) return NAN;
|
|
return mod(a, b);`,S8=`
|
|
vec4 result = mod(a, b);
|
|
vec4 isNaN = vec4(equal(b, vec4(0.0)));
|
|
`+hl+`
|
|
return result;
|
|
`,T8=nt({opSnippet:N8,packedOpSnippet:S8}),GD={kernelName:xi,backendName:"webgl",kernelFunc:T8};var Av=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 A8=`
|
|
if (a == b) {
|
|
return 1.0;
|
|
};
|
|
return a / b;`,E8=`
|
|
// 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;
|
|
`,Ev=nt({opSnippet:A8,packedOpSnippet:E8,checkOutOfBounds:!0}),WD={kernelName:rn,backendName:"webgl",kernelFunc:Ev};var jD="return a - b;",Dv=nt({opSnippet:jD,packedOpSnippet:jD,supportsComplex:!0,cpuKernelImpl:mE}),UD={kernelName:Fn,backendName:"webgl",kernelFunc:Dv};function $v(r){let{inputs:e,backend:t,attrs:o}=r,{logits:n}=e,{dim:s}=o,a=x.parseAxisParam([s],n.shape),i=Cv({inputs:{x:n},backend:t,attrs:{reductionIndices:a,keepDims:!1}}),l=N.expandShapeToKeepDim(i.shape,a),u=pe({inputs:{x:i},backend:t,attrs:{shape:l}}),c=Dv({inputs:{a:n,b:u},backend:t}),p=dv({inputs:{x:c},backend:t}),m=Cf({inputs:{x:p},backend:t,attrs:{axis:a,keepDims:!1}}),f=pe({inputs:{x:m},backend:t,attrs:{shape:l}}),d=Ev({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 HD={kernelName:$n,backendName:"webgl",kernelFunc:$v};function D8(r){let{inputs:e,backend:t,attrs:o}=r,{logits:n}=e,{numSamples:s,seed:a,normalized:i}=o,l=i?n:$v({inputs:{logits:n},backend:t,attrs:{dim:n.shape.length-1}}),u=l.shape[0],c=l.shape[1],p=new Av(u,c,s),m=p.getCustomSetupFunc(a),f=t.runWebGLProgram(p,[l],"int32",m);return i||t.disposeIntermediateTensorInfo(l),f}var qD={kernelName:su,backendName:"webgl",kernelFunc:D8};var KD="return -x;";function $8(r){let{inputs:e,backend:t}=r,{x:o}=e;if(t.shouldExecuteOnCPU([o])){let s=t.texData.get(o.dataId),[a,i]=iE(s.values,o.shape,o.dtype);return t.makeTensorInfo(i,o.dtype,a)}let n;return W().getBool("WEBGL_PACK_UNARY_OPERATIONS")?n=new Os(o.shape,KD):n=new ao(o.shape,KD),t.runWebGLProgram(n,[o],o.dtype)}var XD={kernelName:ps,backendName:"webgl",kernelFunc:$8};var R8=Tr.nonMaxSuppressionV3Impl;function F8(r){N.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:e,backend:t,attrs:o}=r,{boxes:n,scores:s}=e,{maxOutputSize:a,iouThreshold:i,scoreThreshold:l}=o,u=t.readSync(n.dataId),c=t.readSync(s.dataId),{selectedIndices:p}=R8(u,c,a,i,l);return t.makeTensorInfo([p.length],"int32",new Int32Array(p))}var YD={kernelName:bi,backendName:"webgl",kernelFunc:F8};var O8=Tr.nonMaxSuppressionV4Impl;function P8(r){N.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:e,backend:t,attrs:o}=r,{boxes:n,scores:s}=e,{maxOutputSize:a,iouThreshold:i,scoreThreshold:l,padToMaxOutputSize:u}=o,c=t.readSync(n.dataId),p=t.readSync(s.dataId),{selectedIndices:m,validOutputs:f}=O8(c,p,a,i,l,u);return[t.makeTensorInfo([m.length],"int32",new Int32Array(m)),t.makeTensorInfo([],"int32",new Int32Array([f]))]}var ZD={kernelName:wi,backendName:"webgl",kernelFunc:P8};var M8=Tr.nonMaxSuppressionV5Impl;function L8(r){N.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:e,backend:t,attrs:o}=r,{boxes:n,scores:s}=e,{maxOutputSize:a,iouThreshold:i,scoreThreshold:l,softNmsSigma:u}=o,c=t.readSync(n.dataId),p=t.readSync(s.dataId),m=a,f=i,d=l,h=u,{selectedIndices:g,selectedScores:y}=M8(c,p,m,f,d,h);return[t.makeTensorInfo([g.length],"int32",new Int32Array(g)),t.makeTensorInfo([y.length],"float32",new Float32Array(y))]}var JD={kernelName:ki,backendName:"webgl",kernelFunc:L8};var Rv=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 z8=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 Rv(l,s,a,i),c=pe({inputs:{x:n},backend:t,attrs:{shape:[l]}}),p=t.runWebGLProgram(u,[c],n.dtype);t.disposeIntermediateTensorInfo(c);let m=[...n.shape,s],f=pe({inputs:{x:p},backend:t,attrs:{shape:m}});return t.disposeIntermediateTensorInfo(p),f},QD={kernelName:yn,backendName:"webgl",kernelFunc:z8};function Af(r){let{inputs:e,backend:t}=r,{x:o}=e;if(o.dtype==="complex64"){let n=La({inputs:{input:o},backend:t}),s=Af({inputs:{x:n},backend:t}),a=ec({inputs:{input:o},backend:t}),i=Af({inputs:{x:a},backend:t}),l=lo({inputs:{real:s,imag:i},backend:t});return t.disposeIntermediateTensorInfo(n),t.disposeIntermediateTensorInfo(s),t.disposeIntermediateTensorInfo(a),t.disposeIntermediateTensorInfo(i),l}else return Tf({attrs:{shape:o.shape,dtype:o.dtype,value:o.dtype==="string"?"":0},backend:t})}var e$={kernelName:bs,backendName:"webgl",kernelFunc:Af};function t$(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=La({inputs:{input:o},backend:t}),s=t$({inputs:{x:n},backend:t}),a=ec({inputs:{input:o},backend:t}),i=Af({inputs:{x:a},backend:t}),l=lo({inputs:{real:s,imag:i},backend:t});return t.disposeIntermediateTensorInfo(n),t.disposeIntermediateTensorInfo(s),t.disposeIntermediateTensorInfo(a),t.disposeIntermediateTensorInfo(i),l}else return Tf({attrs:{shape:o.shape,dtype:o.dtype,value:1},backend:t})}var r$={kernelName:ms,backendName:"webgl",kernelFunc:t$};function B8(r){let{inputs:e,backend:t,attrs:o}=r,{axis:n}=o;if(e.length===1)return Yg({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=Yg({inputs:{input:c},backend:t,attrs:{dim:n}});return i.push(p),p}),u=tv({inputs:l,backend:t,attrs:{axis:n}});return i.forEach(c=>t.disposeIntermediateTensorInfo(c)),u}var o$={kernelName:fs,backendName:"webgl",kernelFunc:B8};var Fv=class{constructor(e,t,o){this.variableNames=["x"],this.outputShape=t.map((u,c)=>u[0]+e[c]+u[1]);let n=e.length,s=Le(n),a=t.map(u=>u[0]).join(","),i=t.map((u,c)=>u[0]+e[c]).join(","),l=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,n);if(n===1){this.userCode=`
|
|
int start = ${a};
|
|
int end = ${i};
|
|
uniform float value;
|
|
|
|
void main() {
|
|
int outC = getOutputCoords();
|
|
if (outC < start || outC >= end) {
|
|
setOutput(value);
|
|
} else {
|
|
setOutput(getX(outC - start));
|
|
}
|
|
}
|
|
`;return}this.userCode=`
|
|
${s} start = ${s}(${a});
|
|
${s} end = ${s}(${i});
|
|
uniform float value;
|
|
|
|
void main() {
|
|
${s} outC = getOutputCoords();
|
|
if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {
|
|
setOutput(value);
|
|
} else {
|
|
${s} coords = outC - start;
|
|
setOutput(getX(${l}));
|
|
}
|
|
}
|
|
`}getCustomSetupFunc(e){return(t,o)=>{this.valueLoc==null&&(this.valueLoc=t.getUniformLocationNoThrow(o,"value")),t.gl.uniform1f(this.valueLoc,e)}}};var Ov=class{constructor(e,t,o){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t.map((h,g)=>h[0]+e[g]+h[1]);let n=e.length,s=Le(n),a=t.map(h=>h[0]).join(","),i=t.map((h,g)=>h[0]+e[g]).join(","),l=Wt("rc",n),u=Wt("source",n),c=`${l[n-1]} < ${this.outputShape[n-1]}`,p=n===1?"source":`vec2(${u.slice(-2).join()})`,m=[`${s} rc = outputLoc;`,`${l[n-1]} += 1;
|
|
if(${c}) {
|
|
`,n===1?"":`}
|
|
rc = outputLoc;
|
|
${l[n-2]} += 1;
|
|
if(${l[n-2]} < ${this.outputShape[n-2]}) {`,n===1?"":` ${l[n-1]} += 1;
|
|
if(${c}) {`],f=n===1?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))",d="";for(let h=0,g=n===1?2:4;h<g;h++)d+=`
|
|
${m[h]}
|
|
if (${f}) {
|
|
result[${h}] = float(value);
|
|
} else {
|
|
${s} source = rc - start;
|
|
result[${h}] = getChannel(getX(${u.join()}), ${p});
|
|
}
|
|
`;d+=n===1?"} ":"}}",this.userCode=`
|
|
const ${s} start = ${s}(${a});
|
|
const ${s} end = ${s}(${i});
|
|
uniform float value;
|
|
|
|
void main() {
|
|
${s} outputLoc = getOutputCoords();
|
|
vec4 result = vec4(0.);
|
|
${d}
|
|
setOutput(result);
|
|
}
|
|
`}getCustomSetupFunc(e){return(t,o)=>{this.valueLoc==null&&(this.valueLoc=t.getUniformLocationNoThrow(o,"value")),t.gl.uniform1f(this.valueLoc,e)}}};var Pv=r=>{let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{paddings:s,constantValue:a}=o,i=W().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Ov(n.shape,s,a):new Fv(n.shape,s,a),l=i.getCustomSetupFunc(a);return t.runWebGLProgram(i,[n],n.dtype,l)},n$={kernelName:bn,backendName:"webgl",kernelFunc:Pv};var V8=`
|
|
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);
|
|
`,G8=`
|
|
// 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));
|
|
`+hl+`
|
|
return result;
|
|
`,W8=nt({opSnippet:V8,packedOpSnippet:G8}),s$={kernelName:wn,backendName:"webgl",kernelFunc:W8};function j8(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=N.getAxesPermutation(c,i),m=n;p!=null&&(m=Mt({inputs:{x:n},backend:t,attrs:{perm:p}}),c=N.getInnerMostAxes(c.length,i),l.push(m)),N.assertAxesAreInnerMostDims("prod",c,i);let f;if(t.shouldExecuteOnCPU([m])){let d=t.texData.get(m.dataId).values,{outVals:h,outShape:g,outDtype:y}=aE(m.shape,m.dtype,d,c);f=t.makeTensorInfo(g,y,h)}else{let[d,h]=N.computeOutAndReduceShapes(m.shape,c),g=x.sizeFromShape(h),y=pe({inputs:{x:m},backend:t,attrs:{shape:[-1,g]}}),b=fu(n.dtype),w=No(y,b,"prod",t);f=pe({inputs:{x:w},backend:t,attrs:{shape:d}}),l.push(y),l.push(w)}if(a){l.push(f);let d=N.expandShapeToKeepDim(f.shape,u);f=pe({inputs:{x:f},backend:t,attrs:{shape:d}})}return l.forEach(d=>t.disposeIntermediateTensorInfo(d)),f}var i$={kernelName:_i,backendName:"webgl",kernelFunc:j8};var Mv=r=>{let{backend:e,attrs:t}=r,{start:o,stop:n,step:s,dtype:a}=t,i=lE(o,n,s,a);return e.makeTensorInfo([i.length],a,i)},a$={kernelName:ca,backendName:"webgl",kernelFunc:Mv};var U8="return 1.0 / x;",H8=ke({opSnippet:U8}),l$={kernelName:vi,backendName:"webgl",kernelFunc:H8};var q8=hr+`
|
|
return (x < 0.0) ? 0.0 : x;
|
|
`,K8=`
|
|
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;
|
|
`,X8=ke({opSnippet:q8,packedOpSnippet:K8}),u$={kernelName:_n,backendName:"webgl",kernelFunc:X8};var Y8=hr+`
|
|
return (x < 0.0) ? 0.0 : min(6.0, x);
|
|
`,Z8=`
|
|
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;
|
|
`,J8=ke({opSnippet:Y8,packedOpSnippet:Z8}),c$={kernelName:Cn,backendName:"webgl",kernelFunc:J8};var Lv=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 zv=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 Q8(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 zv(n.shape,l,u,s,a):new Lv(n.shape,l,u,s,a);return t.runWebGLProgram(c,[n],"float32")}var p$={kernelName:vn,backendName:"webgl",kernelFunc:Q8};var Bv=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 eY(r){let{inputs:e,backend:t,attrs:o}=r,{images:n,dy:s}=e,{alignCorners:a}=o,i=new Bv(s.shape,n.shape,a);return t.runWebGLProgram(i,[s],s.dtype)}var m$={kernelName:lu,backendName:"webgl",kernelFunc:eY};var Vv=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 tY(r){let{inputs:e,backend:t,attrs:o}=r,{images:n}=e,{alignCorners:s,halfPixelCenters:a,size:i}=o,[l,u]=i,c=new Vv(n.shape,l,u,s,a);return t.runWebGLProgram(c,[n],n.dtype)}var f$={kernelName:pa,backendName:"webgl",kernelFunc:tY};var Gv=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 rY(r){let{inputs:e,backend:t,attrs:o}=r,{images:n,dy:s}=e,{alignCorners:a}=o,i=new Gv(s.shape,n.shape,a);return t.runWebGLProgram(i,[s],s.dtype)}var d$={kernelName:au,backendName:"webgl",kernelFunc:rY};var Wv=class{constructor(e,t){this.variableNames=["x"];let o=e.length;if(o>4)throw new Error(`WebGL backend: Reverse of rank-${o} tensor is not yet supported`);if(this.outputShape=e,o===1){this.userCode=`
|
|
void main() {
|
|
int coord = getOutputCoords();
|
|
setOutput(getX(${e[0]} - coord - 1));
|
|
}
|
|
`;return}let n=i=>t.indexOf(i)!==-1&&e[i]!==1?`${e[i]} - coords[${i}] - 1`:`coords[${i}]`,s=e.map((i,l)=>n(l)).join(","),a=Le(o);this.userCode=`
|
|
void main() {
|
|
${a} coords = getOutputCoords();
|
|
setOutput(getX(${s}));
|
|
}
|
|
`}};var jv=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=Wt("rc",o),s=`${n[o-1]} + 1 < ${this.outputShape[o-1]}`,a=`${n[o-2]} + 1 < ${this.outputShape[o-2]}`,i=Le(o);o===1?this.userCode=`
|
|
void main(){
|
|
int rc = getOutputCoords();
|
|
vec4 result = vec4(0.);
|
|
result.r = getChannel(getX(${e[0]} - rc - 1),
|
|
${e[0]} - rc - 1);
|
|
if(${s}){
|
|
result.g = getChannel(getX(${e[0]} - (rc + 1) - 1),
|
|
${e[0]} - (rc + 1) - 1);
|
|
}
|
|
setOutput(result);
|
|
}
|
|
`:this.userCode=`
|
|
void main() {
|
|
${i} rc = getOutputCoords();
|
|
vec4 result = vec4(0.);
|
|
result.r = ${l(n.slice())};
|
|
if(${s}){
|
|
result.g = ${u(n.slice())};
|
|
}
|
|
if(${a}) {
|
|
result.b = ${c(n.slice())};
|
|
if(${s}) {
|
|
result.a = ${p(n.slice())};
|
|
}
|
|
}
|
|
setOutput(result);
|
|
}
|
|
`;function l(d){return m(d)}function u(d){return d[o-1]="("+d[o-1]+" + 1)",m(d)}function c(d){return d[o-2]="("+d[o-2]+" + 1)",m(d)}function p(d){return d[o-1]="("+d[o-1]+" + 1)",d[o-2]="("+d[o-2]+" + 1)",m(d)}function m(d){let h=e.map((b,w)=>f(w,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 oY(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 jt({inputs:{x:n},backend:t});let l=W().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new jv(n.shape,i):new Wv(n.shape,i);return t.runWebGLProgram(l,[n],n.dtype)}var h$={kernelName:In,backendName:"webgl",kernelFunc:oY};var Uv=class{constructor(e,t){this.variableNames=["Image"],this.outputShape=[];let o=e[1],n=e[2];this.outputShape=e;let s="";typeof t=="number"?s=`float outputValue = ${t.toFixed(2)};`:s=`
|
|
vec3 fill = vec3(${t.join(",")});
|
|
float outputValue = fill[coords[3]];`,this.userCode=`
|
|
uniform vec4 params;
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int x = coords[2];
|
|
int y = coords[1];
|
|
float coordXFloat = (float(x) - params[0]) * params[3] -
|
|
(float(y) - params[1]) * params[2];
|
|
float coordYFloat = (float(x) - params[0]) * params[2] +
|
|
(float(y) - params[1]) * params[3];
|
|
int coordX = int(round(coordXFloat + params[0]));
|
|
int coordY = int(round(coordYFloat + params[1]));
|
|
${s}
|
|
if(coordX >= 0 && coordX < ${n} && coordY >= 0 && coordY < ${o}) {
|
|
outputValue = getImage(coords[0], coordY, coordX, coords[3]);
|
|
}
|
|
setOutput(outputValue);
|
|
}
|
|
`}getCustomSetupFunc(e,t,o,n){return(s,a)=>{this.paramsLoc==null&&(this.paramsLoc=s.getUniformLocationNoThrow(a,"params")),s.gl.uniform4f(this.paramsLoc,e,t,o,n)}}};var g$={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 Uv(o.shape,s),[u,c]=N.getImageCenter(a,o.shape[1],o.shape[2]),p=l.getCustomSetupFunc(u,c,Math.sin(n),Math.cos(n));return i.runWebGLProgram(l,[o],o.dtype,p)}};var nY=`
|
|
// 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;
|
|
}
|
|
}
|
|
`,sY=ke({opSnippet:nY}),x$={kernelName:Nn,backendName:"webgl",kernelFunc:sY};var iY="return inversesqrt(x);",aY=ke({opSnippet:iY,cpuKernelImpl:uE}),y$={kernelName:Sn,backendName:"webgl",kernelFunc:aY};var Ef=class{constructor(e,t,o,n,s,a,i=!0){this.variableNames=["updates","indices","defaultValue"],this.outputShape=a;let l=Le(s.length),u=Le(a.length),c="";o===1?c="i":o===2&&(c="i, j");let p=`getIndices(${c})`,m="";n===1?m="i":n===2&&(m="i, coords[1]");let f=`getUpdates(${m})`,d=t>1?"strides[j]":"strides";this.userCode=`
|
|
${l} strides = ${l}(${s});
|
|
|
|
void main() {
|
|
${u} coords = getOutputCoords();
|
|
float sum = 0.0;
|
|
bool found = false;
|
|
for (int i = 0; i < ${e}; i++) {
|
|
int flattenedIndex = 0;
|
|
for (int j = 0; j < ${t}; j++) {
|
|
int index = round(${p});
|
|
flattenedIndex += index * ${d};
|
|
}
|
|
if (flattenedIndex == coords[0]) {
|
|
sum += ${f};
|
|
found = true;
|
|
}
|
|
}
|
|
setOutput(mix(getDefaultValue(), sum, float(found)));
|
|
}
|
|
`}};function lY(r){let{inputs:e,backend:t,attrs:o}=r,{indices:n,updates:s}=e,{shape:a}=o,{sliceRank:i,numUpdates:l,sliceSize:u,strides:c,outputSize:p}=N.calculateShapes(s,n,a),m=[p/u,u];if(p===0)return t.makeTensorInfo(a,n.dtype);let f=pe({inputs:{x:n},backend:t,attrs:{shape:[l,i]}}),d=pe({inputs:{x:s},backend:t,attrs:{shape:[l,u]}}),h=t.makeTensorInfo([],"float32",new Float32Array([0])),g=new Ef(l,i,f.shape.length,d.shape.length,c,m),y=t.runWebGLProgram(g,[d,f,h],d.dtype),b=pe({inputs:{x:y},backend:t,attrs:{shape:a}});return t.disposeIntermediateTensorInfo(f),t.disposeIntermediateTensorInfo(d),t.disposeIntermediateTensorInfo(y),t.disposeIntermediateTensorInfo(h),b}var b$={kernelName:Ci,backendName:"webgl",kernelFunc:lY};var Hv=class{constructor(e,t,o){this.variableNames=["c","a","b"],this.outputShape=t;let n,s;if(o>4)throw Error(`Where for rank ${o} is not yet supported`);if(o===1)s="resRC",n="resRC";else{let i=["resRC.x","resRC.y","resRC.z","resRC.w"],l=[],u=[];for(let c=0;c<t.length;c++)u.push(`${i[c]}`),c<e&&l.push(`${i[c]}`);n=l.join(),s=u.join()}let a=Le(o);this.userCode=`
|
|
void main() {
|
|
${a} resRC = getOutputCoords();
|
|
float cVal = getC(${n});
|
|
if (cVal >= 1.0) {
|
|
setOutput(getA(${s}));
|
|
} else {
|
|
setOutput(getB(${s}));
|
|
}
|
|
}
|
|
`}};function uY(r){let{inputs:e,backend:t}=r,{condition:o,t:n,e:s}=e,a=new Hv(o.shape.length,n.shape,n.shape.length);return t.runWebGLProgram(a,[o,n,s],fr(n.dtype,s.dtype))}var w$={kernelName:hs,backendName:"webgl",kernelFunc:uY};var cY=`
|
|
// Stable and Attracting Fixed Point (0, 1) for Normalized Weights.
|
|
// see: https://arxiv.org/abs/1706.02515
|
|
float scaleAlpha = ${N.SELU_SCALEALPHA};
|
|
float scale = ${N.SELU_SCALE};
|
|
return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);
|
|
`,pY=ke({opSnippet:cY}),k$={kernelName:Ii,backendName:"webgl",kernelFunc:pY};var mY="return 1.0 / (1.0 + exp(-1.0 * x));",fY=ke({opSnippet:mY}),_$={kernelName:An,backendName:"webgl",kernelFunc:fY};var dY=`
|
|
if (isnan(x)) { return 0.0; }
|
|
return sign(x);
|
|
`,hY=ke({opSnippet:dY}),v$={kernelName:Si,backendName:"webgl",kernelFunc:hY};var gY=Vg+`
|
|
return sin(x);
|
|
`,xY=ke({opSnippet:gY}),C$={kernelName:Tn,backendName:"webgl",kernelFunc:xY};var yY=`
|
|
float e2x = exp(x);
|
|
return (e2x - 1.0 / e2x) / 2.0;
|
|
`,bY=ke({opSnippet:yY}),I$={kernelName:Ni,backendName:"webgl",kernelFunc:bY};var wY=`
|
|
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;
|
|
`,kY=ke({opSnippet:wY}),N$={kernelName:Ti,backendName:"webgl",kernelFunc:kY};var _Y=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;y<n.shape.length;++y)l.push([0,0]);let u=[],c=Pv({inputs:{x:n},backend:t,attrs:{paddings:l,constantValue:0}}),p=N.getReshaped(c.shape,s,i,!1),m=N.getPermuted(p.length,s.length,!1),f=N.getReshapedPermuted(c.shape,s,i,!1),d=pe({inputs:{x:c},backend:t,attrs:{shape:p}}),h=Mt({inputs:{x:d},backend:t,attrs:{perm:m}}),g=pe({inputs:{x:h},backend:t,attrs:{shape:f}});return u.push(c),u.push(d),u.push(h),u.forEach(y=>t.disposeIntermediateTensorInfo(y)),g},S$={kernelName:ma,backendName:"webgl",kernelFunc:_Y};function vY(r){let{inputs:e,backend:t,attrs:o}=r,{sparseIndices:n,sparseValues:s,defaultValue:a}=e,{outputShape:i}=o,{sliceRank:l,numUpdates:u,strides:c,outputSize:p}=N.calculateShapes(s,n,i),m=!1,f=new Ef(u,l,n.shape.length,s.shape.length,c,[p,1],m),d=t.runWebGLProgram(f,[s,n,a],s.dtype),h=pe({inputs:{x:d},backend:t,attrs:{shape:i}});return t.disposeIntermediateTensorInfo(d),h}var T$={kernelName:uu,backendName:"webgl",kernelFunc:vY};function CY(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=N.prepareSplitSize(n,s,i),u=n.shape.length,c=new Array(u).fill(0),p=n.shape.slice();return l.map(m=>{let f=[...p];f[i]=m;let d=Ma({inputs:{x:n},backend:t,attrs:{begin:c,size:f}});return c[i]+=m,d})}var A$={kernelName:xs,backendName:"webgl",kernelFunc:CY};var IY="return sqrt(x);",NY=ke({opSnippet:IY}),E$={kernelName:En,backendName:"webgl",kernelFunc:NY};var SY="return x * x;",TY=ke({opSnippet:SY}),D$={kernelName:fa,backendName:"webgl",kernelFunc:TY};var $$="return (a - b) * (a - b);",AY=nt({opSnippet:$$,packedOpSnippet:$$}),R$={kernelName:Rn,backendName:"webgl",kernelFunc:AY};function EY({inputs:r,attrs:e,backend:t}){let{x:o}=r,n=hr+`
|
|
return x > 0.0 ? 1.0 : float(${e.alpha});
|
|
`,s=new ao(o.shape,n);return t.runWebGLProgram(s,[o],o.dtype)}var F$={kernelName:Oo,backendName:"webgl",kernelFunc:EY};var qv=class{constructor(e,t,o){this.variableNames=["x"],this.outputShape=o;let n=o.length,s=Le(o.length),a=Le(o.length),i="";if(n===1)i="coords * strides + begin";else{let l=0;i=o.map((u,c)=>(l++,o.length===1?`coords * strides[${c}] + begin[${c}]`:`coords[${l-1}] * strides[${c}] + begin[${c}]`)).join(",")}this.userCode=`
|
|
${s} begin = ${s}(${e});
|
|
${s} strides = ${s}(${t});
|
|
|
|
void main() {
|
|
${a} coords = getOutputCoords();
|
|
setOutput(getX(${i}));
|
|
}
|
|
`}};function DY(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}=nr.sliceInfo(n.shape,s,a,i,l,u,c,p,m),w=pe({inputs:{x:n},backend:t,attrs:{shape:y}}),k;if(f){let D=Ma({inputs:{x:w},backend:t,attrs:{begin:d,size:g}});k=pe({inputs:{x:D},backend:t,attrs:{shape:b}}),t.disposeIntermediateTensorInfo(D)}else if(b.some(D=>D===0))k=t.makeTensorInfo(b,n.dtype,[]);else if(t.shouldExecuteOnCPU([w])){let R=t.texData.get(w.dataId).values,P=ve(w.shape,w.dtype,R),L=pE(b,P,h,d);k=t.makeTensorInfo(b,w.dtype,L.values)}else{let A=new qv(d,h,b);k=t.runWebGLProgram(A,[w],w.dtype)}let v=pe({inputs:{x:k},backend:t,attrs:{shape:b}});return t.disposeIntermediateTensorInfo(w),t.disposeIntermediateTensorInfo(k),v}var O$={kernelName:Ai,backendName:"webgl",kernelFunc:DY};var $Y="return tan(x);",RY=ke({opSnippet:$Y}),P$={kernelName:Ei,backendName:"webgl",kernelFunc:RY};var FY=`
|
|
float e2x = exp(-2.0 * abs(x));
|
|
return sign(x) * (1.0 - e2x) / (1.0 + e2x);
|
|
`,OY=ke({opSnippet:FY}),M$={kernelName:On,backendName:"webgl",kernelFunc:OY};var Kv=class{constructor(e,t){this.variableNames=["A"];let o=new Array(e.length);for(let a=0;a<o.length;a++)o[a]=e[a]*t[a];this.outputShape=o,this.rank=o.length;let n=Le(this.rank),s=PY(e);this.userCode=`
|
|
void main() {
|
|
${n} resRC = getOutputCoords();
|
|
setOutput(getA(${s}));
|
|
}
|
|
`}};function PY(r){let e=r.length;if(e>5)throw Error(`Tile for rank ${e} is not yet supported`);if(e===1)return`imod(resRC, ${r[0]})`;let t=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u"],o=[];for(let n=0;n<r.length;n++)o.push(`imod(${t[n]}, ${r[n]})`);return o.join()}function Xv(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{reps:s}=o;if(n.dtype==="string"){let u=t.readSync(n.dataId).map(m=>x.decodeString(m)),c=ve(n.shape,n.dtype,u),p=fE(c,s);return t.makeTensorInfo(p.shape,p.dtype,p.values)}let a=new Kv(n.shape,s);return t.runWebGLProgram(a,[n],n.dtype)}var L$={kernelName:ko,backendName:"webgl",kernelFunc:Xv};function MY(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{k:s,sorted:a}=o,i=t.readSync(n.dataId),[l,u]=dE(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 z$={kernelName:Di,backendName:"webgl",kernelFunc:MY};var Yv=class{constructor(e,t,o,n,s,a){this.variableNames=["Image","Transforms"],this.outputShape=a;let i=o==="nearest"?1:2,l;switch(n){case"constant":l=1;break;case"reflect":l=2;break;case"wrap":l=3;break;case"nearest":l=4;break;default:l=1;break}this.userCode=`
|
|
float mapCoord(float outCoord, float len) {
|
|
float inCoord = outCoord;
|
|
if(${l} == 2) {
|
|
if (inCoord < 0.0) {
|
|
if (len <= 1.0) {
|
|
inCoord = 0.0;
|
|
} else {
|
|
float sz2 = 2.0 * len;
|
|
if (inCoord < sz2) {
|
|
inCoord = sz2 * float(int(float(-inCoord / sz2))) +
|
|
inCoord;
|
|
}
|
|
inCoord = inCoord < -len ? inCoord + sz2 : -inCoord - 1.0;
|
|
}
|
|
} else if (inCoord > len - 1.0) {
|
|
if (len <= 1.0) {
|
|
inCoord = 0.0;
|
|
} else {
|
|
float sz2 = 2.0 * len;
|
|
inCoord -= sz2 * float(int(float(inCoord / sz2)));
|
|
if (inCoord >= len) {
|
|
inCoord = sz2 - inCoord - 1.0;
|
|
}
|
|
}
|
|
}
|
|
return clamp(inCoord, 0.0, len - 1.0);
|
|
} else if (${l} == 3) {
|
|
if (inCoord < 0.0) {
|
|
if (len <= 1.0) {
|
|
inCoord = 0.0;
|
|
} else {
|
|
float sz = len - 1.0;
|
|
inCoord += len * (float(int(float(-inCoord / sz))) + 1.0);
|
|
}
|
|
} else if (inCoord > len - 1.0) {
|
|
if (len <= 1.0) {
|
|
inCoord = 0.0;
|
|
} else {
|
|
float sz = len - 1.0;
|
|
inCoord -= len * float(int(float(inCoord / sz)));
|
|
}
|
|
}
|
|
return clamp(inCoord, 0.0, len - 1.0);
|
|
} else if (${l} == 4) {
|
|
return clamp(outCoord, 0.0, len - 1.0);
|
|
} else {
|
|
return outCoord;
|
|
}
|
|
}
|
|
|
|
float readWithFillValue(int batch, int coordY, int coordX,
|
|
int channel) {
|
|
float outputValue;
|
|
if (0 <= coordY && coordY < ${e} && 0 <= coordX && coordX < ${t}) {
|
|
outputValue = getImage(batch, coordY, coordX, channel);
|
|
} else {
|
|
outputValue = float(${s});
|
|
}
|
|
return outputValue;
|
|
}
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
float outputValue;
|
|
int batch = coords[0];
|
|
int x = coords[2];
|
|
int y = coords[1];
|
|
int channel = coords[3];
|
|
float xf = float(x);
|
|
float yf = float(y);
|
|
float a1 = getTransforms(batch, 0);
|
|
float a2 = getTransforms(batch, 1);
|
|
float a3 = getTransforms(batch, 2);
|
|
float b1 = getTransforms(batch, 3);
|
|
float b2 = getTransforms(batch, 4);
|
|
float b3 = getTransforms(batch, 5);
|
|
float c1 = getTransforms(batch, 6);
|
|
float c2 = getTransforms(batch, 7);
|
|
float projection = c1 * xf + c2 * yf + 1.0;
|
|
if (projection == 0.0) {
|
|
outputValue = float(${s});
|
|
} else {
|
|
float inX = (a1 * xf + a2 * yf + a3) / projection;
|
|
float inY = (b1 * xf + b2 * yf + b3) / projection;
|
|
float mapX = mapCoord(inX, float(${t}));
|
|
float mapY = mapCoord(inY, float(${e}));
|
|
|
|
if (${i} == 1) {
|
|
int coordY = int(round(mapY));
|
|
int coordX = int(round(mapX));
|
|
outputValue = readWithFillValue(batch, coordY, coordX,
|
|
channel);
|
|
} else {
|
|
float yFloor = floor(mapY);
|
|
float xFloor = floor(mapX);
|
|
float yCeil = yFloor + 1.0;
|
|
float xCeil = xFloor + 1.0;
|
|
float valueYFloor = (xCeil - mapX) *
|
|
readWithFillValue(batch, int(yFloor), int(xFloor), channel) +
|
|
(mapX - xFloor) *
|
|
readWithFillValue(batch, int(yFloor), int(xCeil), channel);
|
|
float valueYCeil = (xCeil - mapX) *
|
|
readWithFillValue(batch, int(yCeil), int(xFloor), channel) +
|
|
(mapX - xFloor) *
|
|
readWithFillValue(batch, int(yCeil), int(xCeil), channel);
|
|
outputValue = (yCeil - mapY) * valueYFloor +
|
|
(mapY - yFloor) * valueYCeil;
|
|
}
|
|
}
|
|
setOutput(outputValue);
|
|
}
|
|
`}};function LY(r){let{inputs:e,backend:t,attrs:o}=r,{image:n,transforms:s}=e,{interpolation:a,fillMode:i,fillValue:l,outputShape:u}=o,[c,p,m,f]=n.shape,[d,h]=u!=null?u:[p,m],g=[c,d,h,f],y=new Yv(p,m,a,i,l,g);return t.runWebGLProgram(y,[n,s],"float32")}var B$={kernelName:cu,backendName:"webgl",kernelFunc:LY};function zY(r){let{inputs:e,attrs:t,backend:o}=r,{axis:n}=t,{x:s}=e;Rs(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}=hE(a,n,s.shape,s.dtype);return[o.makeTensorInfo(l,s.dtype,i),o.makeTensorInfo([u.length],"int32",u)]}var V$={kernelName:pu,backendName:"webgl",kernelFunc:zY};function BY(r){let{inputs:e,backend:t,attrs:o}=r,{value:n}=e,{axis:s}=o;s<0&&(s+=n.shape.length);let a=n,i=a.shape.length,l=n.shape[s],u=new Array(i-1),c=0;for(let h=0;h<i;h++)h!==s&&(u[c++]=a.shape[h]);let p=[],m=new Array(i).fill(0),f=a.shape.slice();f[s]=1;let d=new Array(l);for(let h=0;h<d.length;h++){m[s]=h;let g=Ma({inputs:{x:a},backend:t,attrs:{begin:m,size:f}}),y=pe({inputs:{x:g},backend:t,attrs:{shape:u}});d[h]=y,p.push(g)}return p.forEach(h=>t.disposeIntermediateTensorInfo(h)),d}var G$={kernelName:ys,backendName:"webgl",kernelFunc:BY};var Zv=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 VY(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,segmentIds:s}=e,{numSegments:a}=o,i=n.shape.length,l=[],u=0,c=N.getAxesPermutation([u],i),p=n;c!=null&&(p=Mt({inputs:{x:n},backend:t,attrs:{perm:c}}),l.push(p),u=N.getInnerMostAxes(1,i)[0]);let m=N.segment_util.computeOutShape(p.shape,u,a),f=x.sizeFromShape([p.shape[u]]),d=pe({inputs:{x:p},backend:t,attrs:{shape:[-1,f]}});l.push(d);let h=fu(n.dtype),g=(k,v,D,A,R)=>{let P=k.shape[0],L=k.shape[1],G=N.segment_util.segOpComputeOptimalWindowSize(L,R),j={windowSize:G,inSize:L,batchSize:P,numSegments:R},U=new Zv(j,v),H=t.compileAndRun(U,[k,D],A);if(l.push(H),H.shape[1]===R)return H;let q=Mv({backend:t,attrs:{start:0,stop:R,step:1,dtype:"float32"}}),X=Xv({inputs:{x:q},backend:t,attrs:{reps:[L/G]}});return l.push(q),l.push(X),g(H,v,X,A,R)},y=g(d,"unsortedSegmentSum",s,h,a),b=pe({inputs:{x:y},backend:t,attrs:{shape:m}}),w=b;if(c!=null){l.push(b);let k=N.getUndoAxesPermutation(c);w=Mt({inputs:{x:w},backend:t,attrs:{perm:k}})}return l.forEach(k=>t.disposeIntermediateTensorInfo(k)),w}var W$={kernelName:da,backendName:"webgl",kernelFunc:VY};var GY=[ND,SD,VE,WE,jE,UE,qE,KE,XE,YE,QE,e2,t2,r2,n2,o2,s2,a2,i2,l2,u2,c2,p2,f2,d2,y2,w2,k2,v2,AE,N2,T2,A2,S2,D2,$2,E2,R2,F2,O2,L2,z2,B2,G2,W2,V2,j2,U2,H2,q2,K2,X2,Z2,J2,eD,tD,rD,oD,sD,iD,aD,lD,uD,cD,pD,mD,fD,TE,dD,C2,hD,gD,xD,EE,yD,bD,wD,_D,kD,vD,CD,ID,AD,$D,DD,RD,FD,PD,ED,LD,zD,BD,VD,GD,qD,OE,XD,YD,ZD,JD,h2,QD,r$,o$,n$,s$,DE,i$,a$,g2,WD,l$,c$,u$,ME,p$,m$,f$,d$,h$,g$,x$,y$,b$,w$,k$,_$,v$,C$,I$,m2,HD,N$,S$,T$,A$,E$,D$,R$,F$,O$,UD,zE,P$,M$,L$,z$,B$,BE,V$,G$,W$,e$];for(let r of GY)el(r);var Lt;(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"})(Lt||(Lt={}));var yl;(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"})(yl||(yl={}));var j$;function WY(r){j$=r.wasm.cwrap(ws,null,["number","array","number","number","array","number","number","number","number","number","number","number","number"])}function jY(r){let{inputs:e,backend:t,attrs:o}=r,{a:n,b:s,bias:a,preluActivationWeights:i}=e;if(n.dtype!=="float32"||s.dtype!=="float32")throw new Error("_FusedMatMul for non non-float32 tensors not yet supported.");let{transposeA:l,transposeB:u,activation:c,leakyreluAlpha:p}=o,m=t.dataIdMap.get(n.dataId).id,f=t.dataIdMap.get(s.dataId).id,d=0;if(a!=null){let R=t.dataIdMap.get(a.dataId);if(R.shape.length!==1)throw new Error(`_FusedMatMul only supports rank-1 bias but got rank ${R.shape.length}.`);d=R.id}let h=i==null?0:t.dataIdMap.get(i.dataId).id,g=yl[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],w=n.shape[0],k=t.makeOutput([w,y,b],n.dtype),v=t.dataIdMap.get(k.dataId).id,D=new Uint8Array(new Int32Array(n.shape).buffer),A=new Uint8Array(new Int32Array(s.shape).buffer);return j$(m,D,n.shape.length,f,A,s.shape.length,l,u,g,d,h,p||0,v),k}var U$={kernelName:ws,backendName:"wasm",setupFunc:WY,kernelFunc:jY};function Nt(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 H$=Nt(as);function xt(r,e,t){let o;function n(a){o=a.wasm.cwrap(r,null,["number","array","number","number","array","number","number","number"])}function s(a){let{backend:i,inputs:l}=a,{a:u,b:c}=l,p=i.dataIdMap.get(u.dataId).id,m=i.dataIdMap.get(c.dataId).id,f=t!=null?t:u.dtype,d=N.assertAndGetBroadcastShape(u.shape,c.shape),h=i.makeOutput(d,f);if(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,w=()=>o(p,g,u.shape.length,m,y,c.shape.length,Lt[u.dtype],b);if(e&&u.dtype==="float32")return w(),h;let k=N.getBroadcastDims(u.shape,d),v=N.getBroadcastDims(c.shape,d),D=k.every((R,P)=>R===P),A=v.every((R,P)=>R===P);if(D&&A)return w(),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 UY=!0,q$=xt(wo,UY);var K$;function HY(r){K$=r.wasm.cwrap(Ho,null,["array","number","number","number"])}function qY(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 K$(s,n.length,Lt[o.dtype],a),o}var X$={kernelName:Ho,backendName:"wasm",setupFunc:HY,kernelFunc:qY};function rc(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 Y$={kernelName:Fo,backendName:"wasm",kernelFunc:rc};var Z$;function KY(r){Z$=r.wasm.cwrap(Pn,null,["number","array","number","number","number","array","number"])}function kp(r){let{inputs:e,backend:t,attrs:o}=r,[n,s]=YY(e.x.shape,o.perm),a=!0;for(let d=0;d<s.length;d++)s[d]!==d&&(a=!1);let i=XY(e.x.shape,o.perm),l={dataId:e.x.dataId,shape:n,dtype:e.x.dtype};if(a){let d=rc({inputs:e,backend:t});return d.shape=i,d}let u=t.makeOutput(i,l.dtype),c=t.dataIdMap.get(l.dataId).id,p=t.dataIdMap.get(u.dataId).id,m=new Uint8Array(new Int32Array(s).buffer),f=new Uint8Array(new Int32Array(l.shape).buffer);return Z$(c,f,l.shape.length,Lt[l.dtype],p,m,s.length),u}function XY(r,e){let t=new Array(r.length);for(let o=0;o<t.length;o++)t[o]=r[e[o]];return t}function YY(r,e){let t=[],o=[];for(let n=0;n<r.length;++n)r[n]!==1&&t.push(r[n]),r[e[n]]!==1&&o.push(e[n]);for(let n=0;n<o.length;++n){let s=-1;for(let a=0;a<o.length;++a)o[a]>=n&&(s===-1||o[s]>o[a])&&(s=a);o[s]=n}return[t,o]}var J$={kernelName:Pn,backendName:"wasm",kernelFunc:kp,setupFunc:KY};function Yn(r,e,t){let o=r.shape,n=r.shape.length,s=x.parseAxisParam(e,o),a=s,i=N.getAxesPermutation(a,n),l=null,u=!1;if(i!=null){let c=new Array(n);for(let f=0;f<c.length;f++)c[f]=o[i[f]];a=N.getInnerMostAxes(a.length,n),l=kp({inputs:{x:r},attrs:{perm:i},backend:t});let p=t.dataIdMap.get(r.dataId).id;t.dataIdMap.get(l.dataId).id!==p&&(u=!0)}return{transposed:l,originalAxes:s,axes:a,inputWasTransposed:u}}var Q$;function ZY(r){Q$=r.wasm.cwrap(qo,null,["number","number","number","number","number"])}function JY(r){let{backend:e,inputs:t,attrs:o}=r,{axis:n}=o,{x:s}=t,a=e.dataIdMap.get(s.dataId).id,i=a,l=s,{transposed:u,axes:c,inputWasTransposed:p}=Yn(s,n,e);if(p){let y=e.dataIdMap.get(u.dataId).id;y!==a&&(l=u,i=y)}let m=l.shape.slice(0,-1),f=e.makeOutput(m,"int32"),d=e.dataIdMap.get(f.dataId).id,h=x.sizeFromShape(f.shape),g=l.shape[c[0]];return Q$(i,Lt[l.dtype],h,g,d),p&&e.disposeData(u.dataId),f}var eR={kernelName:qo,backendName:"wasm",kernelFunc:JY,setupFunc:ZY};var tR;function QY(r){tR=r.wasm.cwrap(Ko,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function e7(r){let{inputs:e,attrs:t,backend:o}=r,n=e.x,s=o.dataIdMap.get(n.dataId).id,{filterSize:a,strides:i,pad:l,dimRoundingMode:u}=t,c=N.computePool2DInfo(n.shape,a,i,1,l,u),p=c.filterHeight,m=c.filterWidth,f=c.padInfo.top,d=c.padInfo.right,h=c.padInfo.bottom,g=c.padInfo.left,y=c.strideHeight,b=c.strideWidth,w=c.inChannels;if(c.dataFormat!=="channelsLast")throw new Error(`wasm backend does not support dataFormat:'${c.dataFormat}'. Please use 'channelsLast'.`);if(c.dilationWidth!==1||c.dilationHeight!==1)throw new Error(`was backend only supports average pooling with dilation = [1, 1], got [${c.dilationHeight}, ${c.dilationWidth}].`);let k=o.makeOutput(c.outShape,"float32"),v=o.dataIdMap.get(k.dataId).id;return tR(s,n.shape[0],n.shape[1],n.shape[2],p,m,f,d,h,g,y,b,w,v),k}var rR={kernelName:Ko,backendName:"wasm",setupFunc:QY,kernelFunc:e7};function Pr(r){let{inputs:e,attrs:t}=r,{x:o}=e,{shape:n}=t,s=x.sizeFromShape(o.shape),a=x.inferFromImplicitShape(n,s);return x.assert(s===x.sizeFromShape(a),()=>`new shape: ${a}, old shape: ${o.shape}. New shape and old shape must have the same number of elements.`),r.backend.incRef(o.dataId),{dataId:o.dataId,shape:a,dtype:o.dtype}}var oR={kernelName:ds,backendName:"wasm",kernelFunc:Pr};var nR;function t7(r){nR=r.wasm.cwrap(Xo,null,["number","array","number","number","array","number","number","number","number"])}function r7(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 k=(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 v=a?[g,c,m]:[g,m,c],D=i?[y,f,p]:[y,p,f],A=Pr({inputs:{x:n},backend:t,attrs:{shape:v}}),R=Pr({inputs:{x:s},backend:t,attrs:{shape:D}}),P=t.dataIdMap.get(A.dataId).id,L=t.dataIdMap.get(R.dataId).id,G=a?A.shape[2]:A.shape[1],j=i?R.shape[1]:R.shape[2],U=Math.max(g,y),H=t.makeOutput([U,G,j],A.dtype),q=t.dataIdMap.get(H.dataId).id,X=new Uint8Array(new Int32Array(A.shape).buffer),oe=new Uint8Array(new Int32Array(R.shape).buffer);return nR(P,X,A.shape.length,L,oe,R.shape.length,a,i,q),t.disposeData(A.dataId),t.disposeData(R.dataId),H.shape=k,H}var sR={kernelName:Xo,backendName:"wasm",setupFunc:t7,kernelFunc:r7};function oc(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 iR={kernelName:$o,backendName:"wasm",kernelFunc:oc};var aR=Nt(Yo);var lR;function o7(r){lR=r.wasm.cwrap(Ro,null,["number","number","number","number"])}function n7(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 lR(i,s,a,u),l}var uR={kernelName:Ro,backendName:"wasm",setupFunc:o7,kernelFunc:n7};function Jv(r){let{inputs:e,backend:t}=r,o=x.parseAxisParam(r.attrs.axis,e[0].shape)[0],n=N.computeOutShape(e.map(f=>f.shape),o),s=e.filter(f=>x.sizeFromShape(f.shape)>0);if(s.length===1)return rc({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(N.assertParamsConsistent(i,o),s[0].dtype==="string"){let f=s.map(w=>{let k=x.sizeFromShape(w.shape.slice(o));return Pr({inputs:{x:w},backend:t,attrs:{shape:[-1,k]}})}),d=f.map(w=>({vals:t.readSync(w.dataId),shape:w.shape}));n=N.computeOutShape(f.map(w=>w.shape),1);let h=f[0].shape[0]===1,g=nf(d,n,e[0].dtype,h),y=N.computeOutShape(s.map(w=>w.shape),o);a.shape=y;let b=t.dataIdMap.get(a.dataId);return b.stringBytes=N.fromStringArrayToUint8(g),f.forEach(w=>t.disposeData(w.dataId)),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<l;f++){let d=f*u;for(let h=0;h<p.length;h++){let g=c[h],y=f*g,b=p[h].subarray(y,y+g);m.set(b,d),d+=g}}return a}var cR={kernelName:ls,backendName:"wasm",kernelFunc:Jv};var pR;function s7(r){pR=r.wasm.cwrap(Zo,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function i7(r){let{inputs:e,attrs:t,backend:o}=r,{x:n,filter:s}=e,a=o.dataIdMap.get(n.dataId).id,i=o.dataIdMap.get(s.dataId).id,{strides:l,dilations:u,pad:c,dimRoundingMode:p,dataFormat:m}=t,f=N.convertConv2DDataFormat(m),d=N.computeConv2DInfo(n.shape,s.shape,l,u,c,p,!1,f),h=d.filterHeight,g=d.filterWidth,y=d.padInfo.top,b=d.padInfo.right,w=d.padInfo.bottom,k=d.padInfo.left,v=d.dilationHeight,D=d.dilationWidth,A=d.strideHeight,R=d.strideWidth,P=d.inChannels,L=d.outChannels,G=d.padInfo.type==="SAME"?1:0;if(d.dataFormat!=="channelsLast")throw new Error(`wasm backend Conv2D does not support dataFormat:'${d.dataFormat}'. Please use 'channelsLast'.`);let j=o.makeOutput(d.outShape,"float32"),U=o.dataIdMap.get(j.dataId).id;return pR(a,n.shape[0],n.shape[1],n.shape[2],i,h,g,y,b,w,k,G,v,D,A,R,P,L,U),j}var mR={kernelName:Zo,backendName:"wasm",setupFunc:s7,kernelFunc:i7};var fR;function a7(r){fR=r.wasm.cwrap(Jo,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function l7(r){let{backend:e,inputs:t,attrs:o}=r,{dy:n,filter:s}=t,{strides:a,pad:i,dataFormat:l,dimRoundingMode:u,inputShape:c}=o,p=1,m=N.convertConv2DDataFormat(l),f=N.computeConv2DInfo(c,s.shape,a,p,i,u,!1,m),{batchSize:d,filterHeight:h,filterWidth:g,inChannels:y,inHeight:b,inWidth:w,outChannels:k,outHeight:v,outWidth:D,strideHeight:A,strideWidth:R}=f,P=h-1-f.padInfo.top,L=g-1-f.padInfo.left,G=f.dataFormat==="channelsLast",j=x.computeStrides(f.inShape),U=x.computeStrides(n.shape),[H,q,X]=x.computeStrides(s.shape),oe=j[0],Y=G?j[1]:j[2],re=G?j[2]:1,J=G?1:j[1],ie=U[0],ue=G?U[1]:U[2],ae=G?U[2]:1,fe=G?1:U[1],de=e.makeOutput(f.inShape,"float32"),xe=e.dataIdMap.get(de.dataId).id,we=e.dataIdMap.get(n.dataId).id,De=e.dataIdMap.get(s.dataId).id;return fR(we,De,d,h,g,b,w,y,v,D,k,A,R,P,L,H,q,X,oe,Y,re,J,ie,ue,ae,fe,xe),de}var dR={kernelName:Jo,backendName:"wasm",setupFunc:a7,kernelFunc:l7};var hR=Nt(Qo);var Qv;(function(r){r[r.bilinear=0]="bilinear",r[r.nearest=1]="nearest"})(Qv||(Qv={}));var gR;function u7(r){gR=r.wasm.cwrap(ti,null,["number","number","number","number","array","number","number","number","number","number"])}function c7(r){let{backend:e,inputs:t,attrs:o}=r,{method:n,extrapolationValue:s,cropSize:a}=o,{image:i,boxes:l,boxInd:u}=t,c=l.shape[0],[p,m]=a,f=[c,p,m,i.shape[3]],d=e.dataIdMap.get(i.dataId),h;i.dtype!=="float32"&&(h=oc({backend:e,inputs:{x:i},attrs:{dtype:"float32"}}),d=e.dataIdMap.get(h.dataId));let g=d.id,y=e.dataIdMap.get(l.dataId).id,b=e.dataIdMap.get(u.dataId).id,w=e.makeOutput(f,"float32"),k=e.dataIdMap.get(w.dataId).id,v=new Uint8Array(new Int32Array(i.shape).buffer);return gR(g,y,b,c,v,p,m,Qv[n],s,k),h!=null&&e.disposeData(h.dataId),w}var xR={kernelName:ti,backendName:"wasm",setupFunc:u7,kernelFunc:c7};var yR;function p7(r){yR=r.wasm.cwrap(en,null,["number","number","number","number","number","number"])}function m7(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{axis:s,exclusive:a,reverse:i}=o,l=n.shape.length;x.assert(n.dtype==="float32"||n.dtype==="int32",()=>`cumsum does not support ${n.dtype} tensors in the WASM backend`);let u=N.getAxesPermutation([s],l),c=n;u!==null&&(c=kp({inputs:{x:n},attrs:{perm:u},backend:t}));let p=N.getInnerMostAxes(1,l)[0];N.assertAxesAreInnerMostDims("cumsum",[p],l);let m=t.makeOutput(c.shape,c.dtype),f=c.shape[p],d=t.dataIdMap.get(c.dataId).id,h=t.dataIdMap.get(m.dataId).id;yR(d,a?1:0,i?1:0,f,h,Lt[n.dtype]);let g=m;if(u!==null){let y=N.getUndoAxesPermutation(u);g=kp({inputs:{x:m},attrs:{perm:y},backend:t}),t.disposeData(c.dataId),t.disposeData(m.dataId)}return g}var bR={kernelName:en,backendName:"wasm",setupFunc:p7,kernelFunc:m7};var wR;function f7(r){wR=r.wasm.cwrap(ri,null,["number","number","number","array","number","array","array","number","number"])}function d7(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),w=new Uint8Array(new Int32Array(d).buffer),k=new Uint8Array(new Int32Array(x.computeStrides(d)).buffer),v=e.dataIdMap.get(h.dataId).id;return wR(y,s,a==="NHWC"?1:0,b,n.shape.length-1,w,k,d.length,v),h}var kR={kernelName:ri,backendName:"wasm",setupFunc:f7,kernelFunc:d7};var _R;function h7(r){_R=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 g7(r){let{inputs:e,attrs:t,backend:o}=r,{x:n,filter:s}=e,a=o.dataIdMap.get(n.dataId).id,i=o.dataIdMap.get(s.dataId).id,{strides:l,dilations:u,pad:c,dimRoundingMode:p}=t,m=u==null?[1,1]:u,f=N.computeConv2DInfo(n.shape,s.shape,l,m,c,p,!0),d=f.filterHeight,h=f.filterWidth,g=f.padInfo.top,y=f.padInfo.right,b=f.padInfo.bottom,w=f.padInfo.left,k=f.dilationHeight,v=f.dilationWidth,D=f.strideHeight,A=f.strideWidth,R=f.inChannels,P=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"),j=o.dataIdMap.get(G.dataId).id;return _R(a,n.shape[0],n.shape[1],n.shape[2],i,d,h,g,y,b,w,L,k,v,D,A,R,P,j),G}var vR={kernelName:tn,backendName:"wasm",setupFunc:h7,kernelFunc:g7};var x7=!1,CR=xt(si,x7,"bool");var IR=Nt(on);function Qg(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),Pr({inputs:{x:n},backend:o,attrs:{shape:i}})}var NR={kernelName:us,backendName:"wasm",kernelFunc:Qg};function y7(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 SR={kernelName:ia,backendName:"wasm",kernelFunc:y7};var TR;function b7(r){TR=r.wasm.cwrap(ai,null,["number","number","number","number","number","number"])}function w7(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 TR(s,i,l,u,c,a),n}var AR={kernelName:ai,backendName:"wasm",kernelFunc:w7,setupFunc:b7};var ER=Nt(nn);var k7=!1,DR=xt(sn,k7);var $R;function _7(r){$R=r.wasm.cwrap(an,null,["number","number","number","number","number","number","number"])}function v7(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 $R(c,p,m,f,d,n,g),h}var RR={kernelName:an,backendName:"wasm",setupFunc:_7,kernelFunc:v7};var FR;function C7(r){FR=r.wasm.cwrap(ks,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 I7(r){let{inputs:e,attrs:t,backend:o}=r,{x:n,filter:s,bias:a,preluActivationWeights:i}=e,{strides:l,pad:u,dilations:c,dataFormat:p,dimRoundingMode:m,activation:f,leakyreluAlpha:d}=t,h=N.computeConv2DInfo(n.shape,s.shape,l,c,u,m),g=yl[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,w=h.outChannels,k=0;if(a!=null){let ae=o.dataIdMap.get(a.dataId);if(ae.shape.length!==1)throw new Error(`FusedConv2D only supports rank-1 bias but got rank ${ae.shape.length}.`);if(ae.shape[0]!==w)throw new Error(`FusedConv2D bias shape (${ae.shape}) does not match the number of output channels (${w})`);k=ae.id}let v=h.filterHeight,D=h.filterWidth,A=h.padInfo.top,R=h.padInfo.right,P=h.padInfo.bottom,L=h.padInfo.left,G=h.dilationHeight,j=h.dilationWidth,U=h.strideHeight,H=h.strideWidth,q=h.inChannels,X=h.padInfo.type==="SAME"?1:0,oe=h.batchSize,Y=h.inHeight,re=h.inWidth;if(p!=="NHWC")throw new Error(`wasm backend FusedConv2D does not support dataFormat:'${p}'. Please use 'NHWC'.`);let J=o.makeOutput(h.outShape,"float32"),ie=o.dataIdMap.get(J.dataId).id,ue=i==null?0:o.dataIdMap.get(i.dataId).id;return FR(y,oe,Y,re,b,v,D,k,A,R,P,L,X,G,j,U,H,q,w,g,ue,d||0,ie),J}var OR={kernelName:ks,backendName:"wasm",setupFunc:C7,kernelFunc:I7};var PR;function N7(r){PR=r.wasm.cwrap(_s,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function S7(r){let{inputs:e,attrs:t,backend:o}=r,{x:n,filter:s,bias:a,preluActivationWeights:i}=e,{strides:l,pad:u,dilations:c,dataFormat:p,dimRoundingMode:m,activation:f,leakyreluAlpha:d}=t,h=N.computeConv2DInfo(n.shape,s.shape,l,c,u,m,!0),g=yl[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,w=h.outChannels,k=0;if(a!=null){let ae=o.dataIdMap.get(a.dataId);if(ae.shape.length!==1)throw new Error(`FusedDepthwiseConv2D only supports rank-1 bias but got rank ${ae.shape.length}.`);if(ae.shape[0]!==w)throw new Error(`FusedDepthwiseConv2D bias shape (${ae.shape}) does not match the number of output channels (${w})`);k=ae.id}let v=h.filterHeight,D=h.filterWidth,A=h.padInfo.top,R=h.padInfo.right,P=h.padInfo.bottom,L=h.padInfo.left,G=h.dilationHeight,j=h.dilationWidth,U=h.strideHeight,H=h.strideWidth,q=h.inChannels,X=h.padInfo.type==="SAME"?1:0,oe=h.batchSize,Y=h.inHeight,re=h.inWidth;if(p!=="NHWC")throw new Error(`wasm backend FusedDepthwiseConv2D does not support dataFormat:'${p}'. Please use 'NHWC'.`);let J=o.makeOutput(h.outShape,"float32"),ie=o.dataIdMap.get(J.dataId).id,ue=i==null?0:o.dataIdMap.get(i.dataId).id;return PR(y,oe,Y,re,b,v,D,k,A,R,P,L,X,G,j,U,H,q,w,g,ue,d||0,ie),J}var MR={kernelName:_s,backendName:"wasm",setupFunc:N7,kernelFunc:S7};var LR;function T7(r){LR=r.wasm.cwrap(li,null,["number","number","number","number","number","number","array","number"])}function A7(r){let{backend:e,inputs:t}=r,{params:o,indices:n}=t,[s,a,i,l]=Yh.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 LR(f,Lt[o.dtype],h,a,p,i,g,y),u}var zR={kernelName:li,backendName:"wasm",setupFunc:T7,kernelFunc:A7};var BR;function E7(r){BR=r.wasm.cwrap("Gather",null,["number","number","array","number","number","number","array","number"])}function D7(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=N.segment_util.collectGatherOpShapeInfo(n,s,l,i),c=Pr({inputs:{x:n},attrs:{shape:[u.batchSize,u.outerSize,u.dimSize,u.sliceSize]},backend:e}),p=x.sizeFromShape(s.shape),m=Pr({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,w=e.dataIdMap.get(m.dataId).id,k=e.dataIdMap.get(d.dataId).id,v=new Uint8Array(new Int32Array(x.computeStrides(c.shape)).buffer),D=new Uint8Array(new Int32Array(x.computeStrides(f)).buffer);return BR(y,Lt[n.dtype],v,h,w,u.batchSize,D,k),e.disposeData(c.dataId),e.disposeData(m.dataId),d.shape=u.outputShape,d}var VR={kernelName:cs,backendName:"wasm",setupFunc:E7,kernelFunc:D7};var $7=!1,GR=xt(ui,$7,"bool");var R7=!1,WR=xt(ln,R7,"bool");var jR;function F7(r){jR=r.wasm.cwrap(un,null,["number","number","number"])}function O7(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;jR(n,t,a)}return s}var UR={kernelName:un,backendName:"wasm",setupFunc:F7,kernelFunc:O7};var P7=!1,HR=xt(fi,P7,"bool");var M7=!1,qR=xt(di,M7,"bool");var KR=Nt(cn);var L7=!1,XR=xt(gi,L7,"bool");var YR;function z7(r){YR=r.wasm.cwrap(pn,null,["number, number, number"])}function B7(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}=Yn(a,n,e);if(f){let w=e.dataIdMap.get(c.dataId).id;u=c,l=w}let d=u.shape.length;N.assertAxesAreInnerMostDims("max",p,d);let[h,g]=N.computeOutAndReduceShapes(u.shape,p),y=x.sizeFromShape(g),b=e.makeOutput(h,a.dtype);if(x.sizeFromShape(u.shape)!==0){let w=e.dataIdMap.get(b.dataId).id;YR(l,y,w)}if(f&&e.disposeData(c.dataId),s){let w=N.expandShapeToKeepDim(b.shape,m);b.shape=w}return b}var ZR={kernelName:pn,backendName:"wasm",setupFunc:z7,kernelFunc:B7};var V7=!1,JR=xt(mn,V7);var QR;function G7(r){QR=r.wasm.cwrap(fn,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function W7(r){let{inputs:e,attrs:t,backend:o}=r,n=e.x,s=o.dataIdMap.get(n.dataId).id,{filterSize:a,strides:i,pad:l,dimRoundingMode:u}=t,c=N.computePool2DInfo(n.shape,a,i,1,l,u),p=c.filterHeight,m=c.filterWidth,f=c.padInfo.top,d=c.padInfo.right,h=c.padInfo.bottom,g=c.padInfo.left,y=c.dilationHeight,b=c.dilationWidth,w=c.strideHeight,k=c.strideWidth,v=c.inChannels,D=c.outChannels;if(c.dataFormat!=="channelsLast")throw new Error(`wasm backend does not support dataFormat:'${c.dataFormat}'. Please use 'channelsLast'.`);let A=o.makeOutput(c.outShape,"float32"),R=o.dataIdMap.get(A.dataId).id;return QR(s,n.shape[0],n.shape[1],n.shape[2],p,m,f,d,h,g,y,b,w,k,v,D,R),A}var eF={kernelName:fn,backendName:"wasm",setupFunc:G7,kernelFunc:W7};var tF;function j7(r){tF=r.wasm.cwrap(dn,null,["number, number, number"])}function U7(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}=Yn(a,n,e),d=p;if(f){let k=e.dataIdMap.get(c.dataId).id;k!==i&&(u=c,l=k,d=N.getInnerMostAxes(d.length,u.shape.length))}N.assertAxesAreInnerMostDims("mean",d,u.shape.length);let[h,g]=N.computeOutAndReduceShapes(u.shape,d),y=x.sizeFromShape(g),b=u;u.dtype!=="float32"&&(b=oc({backend:e,inputs:{x:u},attrs:{dtype:"float32"}}),l=e.dataIdMap.get(b.dataId).id);let w=e.makeOutput(h,"float32");if(x.sizeFromShape(u.shape)!==0){let k=e.dataIdMap.get(w.dataId).id;tF(l,y,k)}if(f&&e.disposeData(c.dataId),s){let k=N.expandShapeToKeepDim(w.shape,m);w.shape=k}return u.dtype!=="float32"&&e.disposeData(b.dataId),w}var rF={kernelName:dn,backendName:"wasm",setupFunc:j7,kernelFunc:U7};var oF;function H7(r){oF=r.wasm.cwrap(hn,null,["number, number, number"])}function q7(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}=Yn(a,n,e);if(f){let w=e.dataIdMap.get(c.dataId).id;w!==i&&(u=c,l=w)}let d=u.shape.length;N.assertAxesAreInnerMostDims("min",p,d);let[h,g]=N.computeOutAndReduceShapes(u.shape,p),y=x.sizeFromShape(g),b=e.makeOutput(h,u.dtype);if(x.sizeFromShape(u.shape)!==0){let w=e.dataIdMap.get(b.dataId).id;oF(l,y,w)}if(f&&e.disposeData(c.dataId),s){let w=N.expandShapeToKeepDim(b.shape,m);b.shape=w}return b}var nF={kernelName:hn,backendName:"wasm",setupFunc:H7,kernelFunc:q7};var K7=!1,sF=xt(gn,K7);var X7=!0,iF=xt(xn,X7);var aF=Nt(ps);function _p(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 lF;function Y7(r){lF=r.wasm.cwrap(bi,"number",["number","number","number","number","number"])}function Z7(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=lF(u,c,s,n,a),{pSelectedIndices:m,selectedSize:f,pSelectedScores:d,pValidOutputs:h}=_p(e,p);return e.wasm._free(d),e.wasm._free(h),e.makeOutput([f],"int32",m)}var uF={kernelName:bi,backendName:"wasm",setupFunc:Y7,kernelFunc:Z7};var cF;function J7(r){cF=r.wasm.cwrap(wi,"number",["number","number","number","number","number","bool"])}function Q7(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=cF(c,p,s,n,a,i),{pSelectedIndices:f,selectedSize:d,pSelectedScores:h,pValidOutputs:g}=_p(e,m);e.wasm._free(h);let y=e.makeOutput([d],"int32",f),b=e.makeOutput([],"int32",g);return[y,b]}var pF={kernelName:wi,backendName:"wasm",setupFunc:J7,kernelFunc:Q7};var mF;function eZ(r){mF=r.wasm.cwrap(ki,"number",["number","number","number","number","number","number"])}function tZ(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=mF(c,p,s,n,a,i),{pSelectedIndices:f,selectedSize:d,pSelectedScores:h,pValidOutputs:g}=_p(e,m);e.wasm._free(g);let y=e.makeOutput([d],"int32",f),b=e.makeOutput([d],"float32",h);return[y,b]}var fF={kernelName:ki,backendName:"wasm",setupFunc:eZ,kernelFunc:tZ};var rZ=!1,dF=xt(yi,rZ,"bool");var hF;function oZ(r){hF=r.wasm.cwrap(yn,null,["number","number","number","number","number"])}function nZ(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 hF(p,s,a,i,u),l}var gF={kernelName:yn,backendName:"wasm",setupFunc:oZ,kernelFunc:nZ};function sZ(r){let{inputs:{x:e},backend:t}=r,o=t.makeOutput(e.shape,e.dtype);return t.typedArrayFromHeap(o).fill(1),o}var xF={kernelName:ms,backendName:"wasm",kernelFunc:sZ};function iZ(r){let{inputs:e,backend:t,attrs:o}=r,{axis:n}=o;if(e.length===1)return Qg({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=Qg({inputs:{input:c},backend:t,attrs:{dim:n}});return i.push(p),p}),u=Jv({inputs:l,backend:t,attrs:{axis:n}});return i.forEach(c=>t.disposeData(c.dataId)),u}var yF={kernelName:fs,backendName:"wasm",kernelFunc:iZ};var bF;function aZ(r){bF=r.wasm.cwrap(bn,null,["number","array","number","number","array","array","number","number"])}function lZ(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 bF(a,u,e.shape.length,Lt[e.dtype],m,f,n,l),i}var wF={kernelName:bn,backendName:"wasm",kernelFunc:lZ,setupFunc:aZ};var uZ=!1,kF=xt(wn,uZ);var _F;function cZ(r){_F=r.wasm.cwrap(kn,null,["number","number","number"])}function pZ(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 _F(s,a,l),i}var vF={kernelName:kn,backendName:"wasm",setupFunc:cZ,kernelFunc:pZ};var CF;function mZ(r){CF=r.wasm.cwrap(_i,null,["number","number","number","number"])}function fZ(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}=Yn(a,n,e),d=p;if(f){let w=e.dataIdMap.get(c.dataId).id;w!==i&&(u=c,l=w,d=N.getInnerMostAxes(d.length,u.shape.length))}N.assertAxesAreInnerMostDims("prod",d,u.shape.length);let[h,g]=N.computeOutAndReduceShapes(u.shape,d),y=x.sizeFromShape(g),b=e.makeOutput(h,u.dtype);if(x.sizeFromShape(u.shape)!==0){let w=e.dataIdMap.get(b.dataId).id;CF(l,y,Lt[b.dtype],w)}if(f&&e.disposeData(c.dataId),s){let w=N.expandShapeToKeepDim(b.shape,m);b.shape=w}return b}var IF={kernelName:_i,backendName:"wasm",setupFunc:mZ,kernelFunc:fZ};var dZ=r=>{let{backend:e,attrs:t}=r,{start:o,stop:n,step:s,dtype:a}=t,i=lf(o,n,s,a),l=e.makeOutput([i.length],a);return e.typedArrayFromHeap(l).set(i),l},NF={kernelName:ca,backendName:"wasm",kernelFunc:dZ};var hZ=!0,SF=xt(rn,hZ);var TF=Nt(_n);var AF=Nt(Cn);var EF;function gZ(r){EF=r.wasm.cwrap(vn,null,["number","number","number","number","number","number","number","number","number","number"])}function xZ(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=oc({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 w=e.dataIdMap.get(b.dataId).id;return EF(y,c,p,m,f,l,u,s?1:0,a?1:0,w),g!=null&&e.disposeData(g.dataId),b}var DF={kernelName:vn,backendName:"wasm",setupFunc:gZ,kernelFunc:xZ};var $F;function yZ(r){$F=r.wasm.cwrap(In,null,["number","array","number","array","number","number"])}function bZ(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 rc({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);$F(l,c,a.length,p,n.shape.length,u);let m=Pr({inputs:{x:i},attrs:{shape:n.shape},backend:t});return t.disposeData(i.dataId),m}var RF={kernelName:In,backendName:"wasm",kernelFunc:bZ,setupFunc:yZ};var FF;function wZ(r){FF=r.wasm.cwrap($i,null,["number","number","number","number","number","number","number","number","array","number","number"])}function kZ(r){let{inputs:e,backend:t,attrs:o}=r,{image:n}=e,{radians:s,fillValue:a,center:i}=o,l=t.makeOutput(n.shape,n.dtype),u=t.dataIdMap.get(n.dataId).id,c=t.dataIdMap.get(l.dataId).id,[p,m,f,d]=n.shape,[h,g]=N.getImageCenter(i,m,f),y=a===0,b=255,w=typeof a=="number"?[a,a,a,y?0:b]:[...a,b],k=new Uint8Array(new Int32Array(w).buffer);return FF(u,p,m,f,d,s,h,g,k,w.length,c),l}var OF={kernelName:$i,backendName:"wasm",kernelFunc:kZ,setupFunc:wZ};var PF=Nt(Nn);var MF=Nt(Sn);var LF;function _Z(r){LF=r.wasm.cwrap(Ci,null,["number","number","number","number","number","number","array","number","number"])}function vZ(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}=Zh.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 LF(d,g,Lt[s.dtype],l,u,c,y,m,b),i}var zF={kernelName:Ci,backendName:"wasm",setupFunc:_Z,kernelFunc:vZ};var BF;function CZ(r){BF=r.wasm.cwrap("SelectV2",null,["number","number","number","number","number"])}function IZ(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 BF(a,i,l,f,c),u}var VF={kernelName:hs,backendName:"wasm",kernelFunc:IZ,setupFunc:CZ};var GF;function NZ(r){GF=r.wasm.cwrap(An,null,["number","number"])}function SZ(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||GF(o,s),n}var WF={kernelName:"Sigmoid",backendName:"wasm",setupFunc:NZ,kernelFunc:SZ};var jF=Nt(Tn);function nc(r){let{inputs:{x:e},attrs:{begin:t,size:o},backend:n}=r,[s,a]=nr.parseSliceParams(e,t,o),i=nr.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=nr.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=uf(l,s,a,e.shape,e.dtype);return p.stringBytes=d,u}let m=n.typedArrayFromHeap(u),f=e.shape.length;if(f===2)TZ(l,c[0],m,s,a);else if(f===3)AZ(l,c[0],c[1],m,s,a);else if(f===4)EZ(l,c[0],c[1],c[2],m,s,a);else{let d=uf(l,s,a,e.shape,e.dtype);m.set(d)}return u}function TZ(r,e,t,o,n){let s=0,a=o[0],i=o[1],l=a+n[0];for(let u=a;u<l;u++){let c=u*e+i;t.set(r.subarray(c,c+n[1]),s),s+=n[1]}}function AZ(r,e,t,o,n,s){let a=0,i=n[0],l=n[1],u=n[2],c=i+s[0],p=l+s[1];for(let m=i;m<c;m++)for(let f=l;f<p;f++){let d=m*e+f*t+u;o.set(r.subarray(d,d+s[2]),a),a+=s[2]}}function EZ(r,e,t,o,n,s,a){let i=0,l=s[0],u=s[1],c=s[2],p=l+a[0],m=u+a[1],f=c+a[2],d=s[3];for(let h=l;h<p;h++)for(let g=u;g<m;g++)for(let y=c;y<f;y++){let b=h*e+g*t+y*o+d;n.set(r.subarray(b,b+a[3]),i),i+=a[3]}}var UF={kernelName:gs,backendName:"wasm",kernelFunc:nc};var HF;function DZ(r){HF=r.wasm.cwrap($n,null,["number","number","number","number"])}function $Z(r){let{backend:e,inputs:{logits:t},attrs:{dim:o}}=r,n=e.dataIdMap.get(t.dataId).id,s=e.makeOutput(t.shape,t.dtype),a=e.dataIdMap.get(s.dataId).id,i=t.shape[o],l=x.sizeFromShape(t.shape)/i;return x.sizeFromShape(s.shape)===0||HF(n,a,i,l),s}var qF={kernelName:$n,backendName:"wasm",setupFunc:DZ,kernelFunc:$Z};function RZ(r){let{inputs:e,attrs:t,backend:o}=r,{x:n}=e,{numOrSizeSplits:s,axis:a}=t,i=x.parseAxisParam(a,n.shape)[0],l=N.prepareSplitSize(n,s,i),u=new Array(n.shape.length).fill(0),c=n.shape.slice();return l.map(p=>{let m=[...c];m[i]=p;let f=nc({inputs:{x:n},attrs:{begin:u,size:m},backend:o});return u[i]+=p,f})}var KF={kernelName:xs,backendName:"wasm",kernelFunc:RZ};var XF=Nt(En);var YF=Nt(fa);var FZ=!0,ZF=xt(Rn,FZ);var JF;function OZ(r){JF=r.wasm.cwrap(Oo,null,["number","number","number"])}function PZ(r){let{backend:e,inputs:t,attrs:o}=r,{alpha:n}=o,{x:s}=t,a=e.dataIdMap.get(s.dataId).id,i=e.makeOutput(s.shape,s.dtype),l=e.dataIdMap.get(i.dataId).id;return JF(a,n,l),i}var QF={kernelName:Oo,backendName:"wasm",setupFunc:OZ,kernelFunc:PZ};var eO;function MZ(r){eO=r.wasm.cwrap(Ai,null,["number","array","number","array","array","array","array","array","number","number"])}function LZ(r){let{backend:e,inputs:t,attrs:o}=r,{x:n}=t,{begin:s,end:a,strides:i}=o;i==null&&(i=new Array(s.length));let{beginMask:l,endMask:u,ellipsisMask:c,newAxisMask:p,shrinkAxisMask:m}=o,f=N.slice_util.maskToAxes(c);if(f.length>1)throw new Error("Multiple ellipses in slice is not allowed.");if(c!==0&&p!==0)throw new Error("Using both ellipsisMask and newAxisMask is not yet supported.");if(c!==0&&m!==0)throw new Error("Using both ellipsisMask and shrinkAxisMask is not yet supported.");let d=n.shape.length-s.length,h=N.slice_util.maskToAxes(p),g=n.shape.slice();h.forEach(G=>{s[G]=0,a[G]=1,g.splice(G,0,1)});let y=Pr({inputs:{x:n},attrs:{shape:g},backend:e}),{begin:b,end:w,strides:k}=N.slice_util.getNormalizedAxes(y.shape,f,d,s,a,i,l,u,c);s=b,a=w,i=k;let v=N.slice_util.maskToAxes(m);v.forEach(G=>{a[G]=s[G]+1,i[G]=1});let D=N.slice_util.computeOutShape(s,a,i),A=D.filter((G,j)=>v.indexOf(j)===-1);if(i.every(G=>G===1)){let G=nc({inputs:{x:y},attrs:{begin:s,size:D},backend:e});e.disposeData(y.dataId);let j=Pr({inputs:{x:G},attrs:{shape:A},backend:e});return e.disposeData(G.dataId),j}let P=e.makeOutput(A,"float32");if(!A.some(G=>G===0)){let G=e.dataIdMap.get(y.dataId).id,j=new Uint8Array(new Int32Array(x.computeStrides(y.shape)).buffer),U=new Uint8Array(new Int32Array(s).buffer),H=new Uint8Array(new Int32Array(a).buffer),q=new Uint8Array(new Int32Array(i).buffer),X=new Uint8Array(new Int32Array(A).buffer),oe=new Uint8Array(new Int32Array(x.computeStrides(A)).buffer),Y=e.dataIdMap.get(P.dataId).id;eO(G,j,y.shape.length,U,H,q,X,oe,A.length,Y)}e.disposeData(y.dataId);let L=Pr({inputs:{x:P},attrs:{shape:A},backend:e});return e.disposeData(P.dataId),L}var tO={kernelName:Ai,backendName:"wasm",setupFunc:MZ,kernelFunc:LZ};var zZ=!0,rO=xt(Fn,zZ);var oO;function BZ(r){oO=r.wasm.cwrap(Dn,null,["number, number, number"])}function VZ(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}=Yn(a,n,e),d=p;if(f){let w=e.dataIdMap.get(c.dataId).id;w!==i&&(u=c,l=w,d=N.getInnerMostAxes(d.length,u.shape.length))}N.assertAxesAreInnerMostDims("sum",d,u.shape.length);let[h,g]=N.computeOutAndReduceShapes(u.shape,d),y=x.sizeFromShape(g),b=e.makeOutput(h,u.dtype);if(x.sizeFromShape(u.shape)!==0){let w=e.dataIdMap.get(b.dataId).id;oO(l,y,w)}if(f&&e.disposeData(c.dataId),s){let w=N.expandShapeToKeepDim(b.shape,m);b.shape=w}return b}var nO={kernelName:Dn,backendName:"wasm",setupFunc:BZ,kernelFunc:VZ};var sO=Nt(On);var iO;function GZ(r){iO=r.wasm.cwrap(ko,null,["number","array","number","array","number","number"])}function WZ(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,s=t.dataIdMap.get(n.dataId).id,{reps:a}=o,i=new Array(n.shape.length);for(let m=0;m<i.length;m++)i[m]=n.shape[m]*a[m];let l=new Uint8Array(new Int32Array(n.shape).buffer),u=new Uint8Array(new Int32Array(i).buffer),c=t.makeOutput(i,n.dtype),p=t.dataIdMap.get(c.dataId).id;return iO(s,l,n.shape.length,u,i.length,Lt[c.dtype],p),c}var aO={kernelName:ko,backendName:"wasm",setupFunc:GZ,kernelFunc:WZ};var lO;function jZ(r){lO=r.wasm.cwrap(Di,null,["number","array","number","number","number","bool","number","number"])}var UZ=({inputs:r,backend:e,attrs:t})=>{let{x:o}=r,{k:n,sorted:s}=t,a=e.dataIdMap.get(o.dataId).id,i=new Uint8Array(new Int32Array(o.shape).buffer),l=o.shape.slice();l[l.length-1]=n;let u=e.makeOutput(l,o.dtype),c=e.dataIdMap.get(u.dataId).id,p=e.makeOutput(l,"int32"),m=e.dataIdMap.get(p.dataId).id;return lO(a,i,o.shape.length,Lt[o.dtype],n,s,c,m),[u,p]},uO={kernelName:Di,backendName:"wasm",setupFunc:jZ,kernelFunc:UZ};function HZ(r){let{inputs:e,backend:t,attrs:o}=r,{value:n}=e,{axis:s}=o;s<0&&(s+=n.shape.length);let a=n.shape[s],i=n.shape.length,l=new Array(i-1),u=0;for(let f=0;f<i;f++)f!==s&&(l[u++]=n.shape[f]);let c=new Array(a),p=new Array(i).fill(0),m=n.shape.slice();m[s]=1;for(let f=0;f<c.length;f++)p[s]=f,c[f]=nc({inputs:{x:n},attrs:{begin:p,size:m},backend:t});return c.map(({dataId:f,dtype:d})=>({dataId:f,dtype:d,shape:l}))}var cO={kernelName:ys,backendName:"wasm",kernelFunc:HZ};function qZ(r){let{inputs:{x:e},backend:t}=r,o=t.makeOutput(e.shape,e.dtype);return t.typedArrayFromHeap(o).fill(0),o}var pO={kernelName:bs,backendName:"wasm",kernelFunc:qZ};var KZ=[H$,q$,X$,eR,rR,sR,iR,aR,uR,cR,mR,dR,hR,xR,bR,kR,vR,CR,IR,NR,SR,AR,ER,DR,U$,RR,OR,MR,zR,VR,GR,WR,Y$,UR,HR,qR,KR,XR,ZR,JR,eF,rF,nF,sF,iF,aF,uF,pF,fF,dF,gF,xF,yF,wF,kF,vF,IF,NF,SF,TF,AF,oR,DF,RF,OF,MF,PF,zF,VF,WF,jF,UF,qF,KF,XF,YF,ZF,QF,tO,rO,nO,sO,aO,uO,J$,cO,pO];for(let r of KZ)el(r);var eC=W();eC.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])));eC.registerFlag("WASM_HAS_MULTITHREAD_SUPPORT",async()=>{if(eC.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 sC=Tc(dO());var hO='var Module={};function threadPrintErr(){var text=Array.prototype.slice.call(arguments).join(" ");console.error(text)}function threadAlert(){var text=Array.prototype.slice.call(arguments).join(" ");postMessage({cmd:"alert",text:text,threadId:Module["_pthread_self"]()})}var err=threadPrintErr;this.alert=threadAlert;Module["instantiateWasm"]=function(info,receiveInstance){var instance=new WebAssembly.Instance(Module["wasmModule"],info);Module["wasmModule"]=null;receiveInstance(instance);return instance.exports};function moduleLoaded(){}this.onmessage=function(e){try{if(e.data.cmd==="load"){Module["wasmModule"]=e.data.wasmModule;Module["wasmMemory"]=e.data.wasmMemory;Module["buffer"]=Module["wasmMemory"].buffer;Module["ENVIRONMENT_IS_PTHREAD"]=true;if(typeof e.data.urlOrBlob==="string"){importScripts(e.data.urlOrBlob)}else{var objectUrl=URL.createObjectURL(e.data.urlOrBlob);importScripts(objectUrl);URL.revokeObjectURL(objectUrl)}WasmBackendModuleThreadedSimd(Module).then(function(instance){Module=instance;moduleLoaded()})}else if(e.data.cmd==="objectTransfer"){Module["PThread"].receiveObjectTransfer(e.data)}else if(e.data.cmd==="run"){Module["__performance_now_clock_drift"]=performance.now()-e.data.time;Module["__emscripten_thread_init"](e.data.threadInfoStruct,0,0);var max=e.data.stackBase;var top=e.data.stackBase+e.data.stackSize;Module["establishStackSpace"](top,max);Module["_emscripten_tls_init"]();Module["PThread"].receiveObjectTransfer(e.data);Module["PThread"].setThreadStatus(Module["_pthread_self"](),1);try{var result=Module["invokeEntryPoint"](e.data.start_routine,e.data.arg);if(!Module["getNoExitRuntime"]())Module["PThread"].threadExit(result)}catch(ex){if(ex==="Canceled!"){Module["PThread"].threadCancel()}else if(ex!="unwind"){if(ex instanceof Module["ExitStatus"]){if(Module["getNoExitRuntime"]()){}else{Module["PThread"].threadExit(ex.status)}}else{Module["PThread"].threadExit(-2);throw ex}}}}else if(e.data.cmd==="cancel"){if(Module["_pthread_self"]()){Module["PThread"].threadCancel()}}else if(e.data.target==="setimmediate"){}else if(e.data.cmd==="processThreadQueue"){if(Module["_pthread_self"]()){Module["_emscripten_current_thread_process_queued_calls"]()}}else{err("worker.js received unknown command "+e.data.cmd);err(e.data)}}catch(ex){err("worker.js onmessage() captured an uncaught exception: "+ex);if(ex&&ex.stack)err(ex.stack);throw ex}};if(typeof process==="object"&&typeof process.versions==="object"&&typeof process.versions.node==="string"){self={location:{href:__filename}};var onmessage=this.onmessage;var nodeWorkerThreads=require("worker_threads");global.Worker=nodeWorkerThreads.Worker;var parentPort=nodeWorkerThreads.parentPort;parentPort.on("message",function(data){onmessage({data:data})});var nodeFS=require("fs");var nodeRead=function(filename){return nodeFS.readFileSync(filename,"utf8")};function globalEval(x){global.require=require;global.Module=Module;eval.call(null,x)}importScripts=function(f){globalEval(nodeRead(f))};postMessage=function(msg){parentPort.postMessage(msg)};if(typeof performance==="undefined"){performance={now:function(){return Date.now()}}}}';var xO=Tc(gO());var rx=class extends js{constructor(e){super();this.wasm=e,this.dataIdNextNumber=1,this.wasm.tfjs.init(),this.dataIdMap=new Za(this,Mo())}write(e,t,o){let n={id:this.dataIdNextNumber++};return this.move(n,e,t,o,1),n}numDataIds(){return this.dataIdMap.numDataIds()}async time(e){let t=x.now();return e(),{kernelMs:x.now()-t}}move(e,t,o,n,s){let a=this.dataIdNextNumber++;if(n==="string"){let c=t;this.dataIdMap.set(e,{id:a,stringBytes:c,shape:o,dtype:n,memoryOffset:null,refCount:s});return}let i=x.sizeFromShape(o),l=i*x.bytesPerElement(n),u=this.wasm._malloc(l);this.dataIdMap.set(e,{id:a,memoryOffset:u,shape:o,dtype:n,refCount:s}),this.wasm.tfjs.registerTensor(a,i,u),t!=null&&this.wasm.HEAPU8.set(new Uint8Array(t.buffer,t.byteOffset,l),u)}async read(e){return this.readSync(e)}readSync(e){let{memoryOffset:t,dtype: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 XZ(a.buffer,o)}disposeData(e,t=!1){if(this.dataIdMap.has(e)){let o=this.dataIdMap.get(e);if(o.refCount--,!t&&o.refCount>0)return!1;this.wasm._free(o.memoryOffset),this.wasm.tfjs.disposeData(o.id),this.dataIdMap.delete(e)}return!0}refCount(e){return this.dataIdMap.has(e)?this.dataIdMap.get(e).refCount:0}incRef(e){let t=this.dataIdMap.get(e);t!=null&&t.refCount++}floatPrecision(){return 32}getMemoryOffset(e){return this.dataIdMap.get(e).memoryOffset}dispose(){this.wasm.tfjs.dispose(),this.wasm=null}memory(){return{unreliable:!1}}makeOutput(e,t,o){let n;if(o==null)n=this.write(null,e,t);else{let s=this.dataIdNextNumber++;n={id:s},this.dataIdMap.set(n,{id:s,memoryOffset:o,shape:e,dtype:t,refCount:1});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 YZ(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 yO(r,e,t){if(ox!=null)return ox;let o="tfjs-backend-wasm.wasm";return r&&e?o="tfjs-backend-wasm-threaded-simd.wasm":r&&(o="tfjs-backend-wasm-simd.wasm"),Df!=null&&Df[o]!=null?Df[o]:t+o}async function bO(){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=(i,l)=>{if(i.endsWith(".worker.js")){let u=hO,c=new Blob([u],{type:"application/javascript"});return URL.createObjectURL(c)}return i.endsWith(".wasm")?yO(r,e,$f!=null?$f:l):l+i},iC&&(n.instantiateWasm=YZ(yO(r,e,$f!=null?$f:"")));let s=!1;n.onAbort=()=>{if(s||Rf)return;Rf=!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"})};let a;e&&r&&ox==null?(n.mainScriptUrlOrBlob=new Blob(["var WasmBackendModuleThreadedSimd = "+sC.default.toString()],{type:"text/javascript"}),a=(0,sC.default)(n)):a=(0,xO.default)(n),a.then(i=>{s=!0,Rf=!1;let l=null;i.tfjs={init:i.cwrap("init",null,[]),registerTensor:i.cwrap("register_tensor",null,["number","number","number"]),disposeData:i.cwrap("dispose_data",l,["number"]),dispose:i.cwrap("dispose",l,[])},t({wasm:i})})})}function XZ(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 ZZ=["tfjs-backend-wasm.wasm","tfjs-backend-wasm-simd.wasm","tfjs-backend-wasm-threaded-simd.wasm"],ox=null,$f=null,Df={},Rf=!1,iC=!1;function JZ(r,e=!1){if(tg("setWasmPath has been deprecated in favor of setWasmPaths and will be removed in a future release."),Rf)throw new Error("The WASM backend was already initialized. Make sure you call `setWasmPath()` before you call `tf.setBackend()` or `tf.ready()`");ox=r,iC=e}function QZ(r,e=!1){if(Rf)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")$f=r;else{Df=r;let t=ZZ.filter(o=>Df[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.`)}iC=e}var aC="3.3.0";var eJ=2;xu("wasm",async()=>{let{wasm:r}=await bO();return new rx(r)},eJ);F().prototype.abs=function(){return this.throwIfDisposed(),It(this)};F().prototype.acos=function(){return this.throwIfDisposed(),wm(this)};F().prototype.acosh=function(){return this.throwIfDisposed(),km(this)};F().prototype.add=function(r){return this.throwIfDisposed(),ee(this,r)};F().prototype.all=function(r,e){return this.throwIfDisposed(),bu(this,r,e)};F().prototype.any=function(r,e){return this.throwIfDisposed(),sl(this,r,e)};F().prototype.argMax=function(r){return this.throwIfDisposed(),il(this,r)};F().prototype.argMin=function(r){return this.throwIfDisposed(),_m(this,r)};F().prototype.asScalar=function(){return this.throwIfDisposed(),T(this.size===1,()=>"The array must have only 1 element."),M(this,[])};F().prototype.asType=function(r){return this.throwIfDisposed(),ne(this,r)};F().prototype.as1D=function(){return this.throwIfDisposed(),M(this,[this.size])};F().prototype.as2D=function(r,e){return this.throwIfDisposed(),M(this,[r,e])};F().prototype.as3D=function(r,e,t){return this.throwIfDisposed(),M(this,[r,e,t])};F().prototype.as4D=function(r,e,t,o){return this.throwIfDisposed(),M(this,[r,e,t,o])};F().prototype.as5D=function(r,e,t,o,n){return this.throwIfDisposed(),M(this,[r,e,t,o,n])};F().prototype.asin=function(){return this.throwIfDisposed(),vm(this)};F().prototype.asinh=function(){return this.throwIfDisposed(),Cm(this)};F().prototype.atan=function(){return this.throwIfDisposed(),Im(this)};F().prototype.atan2=function(r){return this.throwIfDisposed(),Nm(this,r)};F().prototype.atanh=function(){return this.throwIfDisposed(),Sm(this)};F().prototype.avgPool=function(r,e,t,o){return this.throwIfDisposed(),wa(this,r,e,t,o)};F().prototype.batchToSpaceND=function(r,e){return this.throwIfDisposed(),ka(this,r,e)};F().prototype.batchNorm=function(r,e,t,o,n){return this.throwIfDisposed(),Ln(this,r,e,t,o,n)};F().prototype.broadcastTo=function(r){return this.throwIfDisposed(),al(this,r)};F().prototype.cast=function(r){return this.throwIfDisposed(),ne(this,r)};F().prototype.ceil=function(){return this.throwIfDisposed(),Am(this)};F().prototype.clipByValue=function(r,e){return this.throwIfDisposed(),sr(this,r,e)};F().prototype.concat=function(r,e){return this.throwIfDisposed(),r instanceof Ve&&(r=[r]),Ze([this,...r],e)};F().prototype.conv1d=function(r,e,t,o,n,s){return this.throwIfDisposed(),_u(this,r,e,t,o,n,s)};F().prototype.conv2dTranspose=function(r,e,t,o,n){return this.throwIfDisposed(),vu(this,r,e,t,o,n)};F().prototype.conv2d=function(r,e,t,o,n,s){return this.throwIfDisposed(),Kr(this,r,e,t,o,n,s)};F().prototype.cos=function(){return this.throwIfDisposed(),_a(this)};F().prototype.cosh=function(){return this.throwIfDisposed(),Cu(this)};F().prototype.cumsum=function(r,e,t){return this.throwIfDisposed(),Iu(this,r,e,t)};F().prototype.depthToSpace=function(r,e){return this.throwIfDisposed(),Dm(this,r,e)};F().prototype.depthwiseConv2d=function(r,e,t,o,n,s){return this.throwIfDisposed(),Is(this,r,e,t,o,n,s)};F().prototype.dilation2d=function(r,e,t,o,n){return this.throwIfDisposed(),$m(this,r,e,t,o,n)};F().prototype.divNoNan=function(r){return this.throwIfDisposed(),Rm(this,r)};F().prototype.div=function(r){return this.throwIfDisposed(),me(this,r)};F().prototype.dot=function(r){return this.throwIfDisposed(),Iw(this,r)};F().prototype.elu=function(){return this.throwIfDisposed(),Ns(this)};F().prototype.equal=function(r){return this.throwIfDisposed(),vo(this,r)};F().prototype.erf=function(){return this.throwIfDisposed(),Fm(this)};F().prototype.exp=function(){return this.throwIfDisposed(),Yt(this)};F().prototype.expandDims=function(r){return this.throwIfDisposed(),ir(this,r)};F().prototype.expm1=function(){return this.throwIfDisposed(),Om(this)};F().prototype.fft=function(){return this.throwIfDisposed(),Ea(this)};F().prototype.flatten=function(){return this.throwIfDisposed(),M(this,[this.size])};F().prototype.floor=function(){return this.throwIfDisposed(),Ss(this)};F().prototype.floorDiv=function(r){return this.throwIfDisposed(),yu(this,r)};F().prototype.gather=function(r,e){return this.throwIfDisposed(),zn(this,r,e)};F().prototype.greaterEqual=function(r){return this.throwIfDisposed(),io(this,r)};F().prototype.greater=function(r){return this.throwIfDisposed(),Qt(this,r)};F().prototype.ifft=function(){return this.throwIfDisposed(),Mi(this)};F().prototype.irfft=function(){return this.throwIfDisposed(),Lu(this)};F().prototype.isFinite=function(){return this.throwIfDisposed(),Nw(this)};F().prototype.isInf=function(){return this.throwIfDisposed(),Sw(this)};F().prototype.isNaN=function(){return this.throwIfDisposed(),Tw(this)};F().prototype.leakyRelu=function(r){return this.throwIfDisposed(),Ca(this,r)};F().prototype.lessEqual=function(r){return this.throwIfDisposed(),Bo(this,r)};F().prototype.less=function(r){return this.throwIfDisposed(),Su(this,r)};F().prototype.localResponseNormalization=function(r,e,t,o){return this.throwIfDisposed(),Pm(this,r,e,t,o)};F().prototype.logSigmoid=function(){return this.throwIfDisposed(),Ew(this)};F().prototype.logSoftmax=function(r){return this.throwIfDisposed(),Au(this,r)};F().prototype.logSumExp=function(r,e){return this.throwIfDisposed(),Lm(this,r,e)};F().prototype.log=function(){return this.throwIfDisposed(),ar(this)};F().prototype.log1p=function(){return this.throwIfDisposed(),Tu(this)};F().prototype.logicalAnd=function(r){return this.throwIfDisposed(),dr(this,r)};F().prototype.logicalNot=function(){return this.throwIfDisposed(),Ia(this)};F().prototype.logicalOr=function(r){return this.throwIfDisposed(),Eu(this,r)};F().prototype.logicalXor=function(r){return this.throwIfDisposed(),Fw(this,r)};F().prototype.matMul=function(r,e,t){return this.throwIfDisposed(),We(this,r,e,t)};F().prototype.maxPool=function(r,e,t,o){return this.throwIfDisposed(),Na(this,r,e,t,o)};F().prototype.max=function(r,e){return this.throwIfDisposed(),lr(this,r,e)};F().prototype.maximum=function(r){return this.throwIfDisposed(),Yr(this,r)};F().prototype.mean=function(r,e){return this.throwIfDisposed(),dt(this,r,e)};F().prototype.min=function(r,e){return this.throwIfDisposed(),Pi(this,r,e)};F().prototype.minimum=function(r){return this.throwIfDisposed(),As(this,r)};F().prototype.mirrorPad=function(r,e){return this.throwIfDisposed(),Bm(this,r,e)};F().prototype.mod=function(r){return this.throwIfDisposed(),Vm(this,r)};F().prototype.mul=function(r){return this.throwIfDisposed(),O(this,r)};F().prototype.neg=function(){return this.throwIfDisposed(),He(this)};F().prototype.norm=function(r,e,t){return this.throwIfDisposed(),Vu(this,r,e,t)};F().prototype.notEqual=function(r){return this.throwIfDisposed(),Vn(this,r)};F().prototype.oneHot=function(r,e=1,t=0){return this.throwIfDisposed(),Cs(this,r,e,t)};F().prototype.onesLike=function(){return this.throwIfDisposed(),er(this)};F().prototype.pad=function(r,e){return this.throwIfDisposed(),Rr(this,r,e)};F().prototype.pool=function(r,e,t,o,n){return this.throwIfDisposed(),Mw(this,r,e,t,o,n)};F().prototype.pow=function(r){return this.throwIfDisposed(),Fr(this,r)};F().prototype.prelu=function(r){return this.throwIfDisposed(),Ta(this,r)};F().prototype.prod=function(r,e){return this.throwIfDisposed(),Du(this,r,e)};F().prototype.reciprocal=function(){return this.throwIfDisposed(),Wm(this)};F().prototype.relu=function(){return this.throwIfDisposed(),Nr(this)};F().prototype.relu6=function(){return this.throwIfDisposed(),Ru(this)};F().prototype.reshapeAs=function(r){return this.throwIfDisposed(),M(this,r.shape)};F().prototype.reshape=function(r){return this.throwIfDisposed(),M(this,r)};F().prototype.resizeBilinear=function(r,e,t){return this.throwIfDisposed(),dg(this,r,e,t)};F().prototype.resizeNearestNeighbor=function(r,e,t){return this.throwIfDisposed(),hg(this,r,e,t)};F().prototype.reverse=function(r){return this.throwIfDisposed(),Ht(this,r)};F().prototype.rfft=function(){return this.throwIfDisposed(),Da(this)};F().prototype.round=function(){return this.throwIfDisposed(),jm(this)};F().prototype.rsqrt=function(){return this.throwIfDisposed(),Fu(this)};F().prototype.selu=function(){return this.throwIfDisposed(),Ou(this)};F().prototype.separableConv2d=function(r,e,t,o,n,s){return this.throwIfDisposed(),Um(this,r,e,t,o,n,s)};F().prototype.sigmoid=function(){return this.throwIfDisposed(),qr(this)};F().prototype.sign=function(){return this.throwIfDisposed(),Hm(this)};F().prototype.sin=function(){return this.throwIfDisposed(),Pu(this)};F().prototype.sinh=function(){return this.throwIfDisposed(),Mu(this)};F().prototype.slice=function(r,e){return this.throwIfDisposed(),Re(this,r,e)};F().prototype.softmax=function(r){return this.throwIfDisposed(),Aa(this,r)};F().prototype.softplus=function(){return this.throwIfDisposed(),Ts(this)};F().prototype.spaceToBatchND=function(r,e){return this.throwIfDisposed(),Sa(this,r,e)};F().prototype.split=function(r,e){return this.throwIfDisposed(),ur(this,r,e)};F().prototype.sqrt=function(){return this.throwIfDisposed(),gt(this)};F().prototype.square=function(){return this.throwIfDisposed(),Oe(this)};F().prototype.squaredDifference=function(r){return this.throwIfDisposed(),zu(this,r)};F().prototype.squeeze=function(r){return this.throwIfDisposed(),Co(this,r)};F().prototype.stack=function(r,e){this.throwIfDisposed();let t=r instanceof Ve?[this,r]:[this,...r];return Bt(t,e)};F().prototype.step=function(r){return this.throwIfDisposed(),Ds(this,r)};F().prototype.stridedSlice=function(r,e,t,o,n,s,a,i){return this.throwIfDisposed(),Xm(this,r,e,t,o,n,s,a,i)};F().prototype.sub=function(r){return this.throwIfDisposed(),ce(this,r)};F().prototype.sum=function(r,e){return this.throwIfDisposed(),ge(this,r,e)};F().prototype.tan=function(){return this.throwIfDisposed(),Ym(this)};F().prototype.tanh=function(){return this.throwIfDisposed(),Oi(this)};F().prototype.tile=function(r){return this.throwIfDisposed(),zo(this,r)};F().prototype.toBool=function(){return this.throwIfDisposed(),ne(this,"bool")};F().prototype.toFloat=function(){return this.throwIfDisposed(),ne(this,"float32")};F().prototype.toInt=function(){return this.throwIfDisposed(),ne(this,"int32")};F().prototype.topk=function(r,e){return this.throwIfDisposed(),Zm(this,r,e)};F().prototype.transpose=function(r){return this.throwIfDisposed(),Ue(this,r)};F().prototype.unique=function(r){return this.throwIfDisposed(),Qc(this,r)};F().prototype.unsortedSegmentSum=function(r,e){return this.throwIfDisposed(),Jm(this,r,e)};F().prototype.unstack=function(r){return this.throwIfDisposed(),cr(this,r)};F().prototype.where=function(r,e){return this.throwIfDisposed(),Dt(r,this,e)};F().prototype.zerosLike=function(){return this.throwIfDisposed(),Ce(this)};var nx={kernelName:as,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>O(r,Ds(ne(t,"float32"),-1))}}};var wO={kernelName:qs,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>{let o=Oe(ne(t,"float32")),n=gt(ce(le(1),o));return He(me(r,n))}}}};var kO={kernelName:Ks,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>{let o=gt(ce(Oe(ne(t,"float32")),1));return me(r,o)}}}};var _O={kernelName:wo,inputsToSave:["a","b"],gradFunc:(r,e)=>{let[t,o]=e,n=Be(t.shape,o.shape);return{a:()=>{let i=r,l=kt(t.shape,n);return l.length>0&&(i=ge(i,l)),M(i,t.shape)},b:()=>{let i=r,l=kt(o.shape,n);return l.length>0&&(i=ge(i,l)),M(i,o.shape)}}}};var vO={kernelName:Ho,saveAllInputs:!0,gradFunc:(r,e)=>{let t={};return e.forEach((o,n)=>{t[n]=()=>r.clone()}),t}};var CO={kernelName:qo,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>Ce(t)}}};var IO={kernelName:ea,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>Ce(t)}}};var NO={kernelName:Xs,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>me(r,gt(ce(le(1),Oe(ne(t,"float32")))))}}};var SO={kernelName:Ys,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>{let o=gt(ee(le(1),Oe(ne(t,"float32"))));return me(r,o)}}}};var TO={kernelName:Qs,inputsToSave:["a","b"],gradFunc:(r,e)=>{let[t,o]=e,n=Be(t.shape,o.shape);return{a:()=>{let i=ee(Oe(t),Oe(o)),l=O(r,me(o,i)),u=kt(t.shape,n);return u.length>0&&(l=ge(l,u)),M(l,t.shape)},b:()=>{let i=ee(Oe(t),Oe(o)),l=He(O(r,me(t,i))),u=kt(o.shape,n);return u.length>0&&(l=ge(l,u)),M(l,o.shape)}}}};var AO={kernelName:Zs,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>me(r,ee(Oe(ne(t,"float32")),1))}}};var EO={kernelName:Js,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>me(r,ce(le(1),Oe(ne(t,"float32"))))}}};function tJ(r,e,t,o,n,s){let a=_(r,"dy","avgPool3dGrad"),i=_(e,"input","avgPool3dGrad"),l=a,u=i,c=!1;i.rank===4&&(c=!0,l=M(a,[1,a.shape[0],a.shape[1],a.shape[2],a.shape[3]]),u=M(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),T(l.rank===5,()=>`Error in avgPool3dGrad: dy must be rank 5 but got rank ${l.rank}.`),T(u.rank===5,()=>`Error in avgPool3dGrad: input must be rank 5 but got rank ${u.rank}.`),s!=null&&T(ot(n),()=>`Error in avgPool3dGrad: pad must be an integer when using, dimRoundingMode ${s} but got pad ${n}.`);let p={dy:l,input:u},m={filterSize:t,strides:o,pad:n,dimRoundingMode:s},f=E.runKernel(Bl,p,m);return c?M(f,[f.shape[1],f.shape[2],f.shape[3],f.shape[4]]):f}var DO=S({avgPool3dGrad_:tJ});var $O={kernelName:ta,inputsToSave:["x"],gradFunc:(r,e,t)=>{let[o]=e,{filterSize:n,strides:s,pad:a,dimRoundingMode:i}=t;return{x:()=>DO(r,o,n,s,a,i)}}};function rJ(r,e,t,o,n){let s=_(r,"dy","avgPoolGrad"),a=_(e,"input","avgPoolGrad");T(a.rank===s.rank,()=>`Rank of input (${a.rank}) does not match rank of dy (${s.rank})`);let i=a,l=s,u=!1;a.rank===3&&(u=!0,i=M(a,[1,a.shape[0],a.shape[1],a.shape[2]]),l=M(s,[1,s.shape[0],s.shape[1],s.shape[2]])),T(l.rank===4,()=>`Error in avgPoolGrad: dy must be rank 4 but got rank ${l.rank}.`),T(i.rank===4,()=>`Error in avgPoolGrad: input must be rank 4 but got rank ${i.rank}.`);let c={dy:l,input:i},p={filterSize:t,strides:o,pad:n},m=E.runKernel(zl,c,p);return u?M(m,[m.shape[1],m.shape[2],m.shape[3]]):m}var RO=S({avgPoolGrad_:rJ});var FO={kernelName:Ko,inputsToSave:["x"],gradFunc:(r,e,t)=>{let[o]=e,{filterSize:n,strides:s,pad:a}=t;return{x:()=>RO(r,o,n,s,a)}}};var OO={kernelName:Xo,inputsToSave:["a","b"],gradFunc:(r,e,t)=>{let[o,n]=e,{transposeA:s,transposeB:a}=t;return!s&&!a?{a:()=>We(r,n,!1,!0),b:()=>We(o,r,!0,!1)}:!s&&a?{a:()=>We(r,n,!1,!1),b:()=>We(r,o,!0,!1)}:s&&!a?{a:()=>We(n,r,!1,!0),b:()=>We(o,r,!1,!1)}:{a:()=>We(n,r,!0,!0),b:()=>We(r,o,!0,!0)}}};var PO={kernelName:ra,gradFunc:(r,e,t)=>{let{blockShape:o,crops:n}=t;return{x:()=>Sa(r,o,n)}}};var MO={kernelName:Db,gradFunc:(r,e,t)=>{let o=t,n=o.inputShape,s=o.shape,a=Array.from(s);for(let l=n.length-1;l>=0;l--)if(n[l]===s[l])a[l]=1;else if(n[l]!==1)throw new Error(`broadcastTo(): [${n}] cannot be broadcast to [${s}].`);let i=[];for(let l=0;l<a.length;l++)a[l]>1&&i.push(l);return{x:()=>ge(r,i,!0)}}};var LO={kernelName:$o,gradFunc:r=>({x:()=>r.clone()})};var zO={kernelName:Yo,gradFunc:r=>({x:()=>Ce(r)})};var BO={kernelName:Ro,inputsToSave:["x"],gradFunc:(r,e,t)=>{let[o]=e,{clipValueMin:n,clipValueMax:s}=t;return{x:()=>Dt(dr(io(o,n),Bo(o,s)),r,Ce(r))}}};var VO={kernelName:oa,inputsToSave:["x"],gradFunc:nx.gradFunc};var GO={kernelName:ls,saveAllInputs:!0,gradFunc:(r,e,t)=>{let o=e.map(l=>l.shape),{axis:n}=t,s=Jt(n,e[0].shape)[0],a=o.map(l=>l[s]);return ur(r,a,s).map(l=>()=>l)}};var WO={kernelName:Zo,inputsToSave:["x","filter"],gradFunc:(r,e,t)=>{let[o,n]=e,{dilations:s,strides:a,pad:i,dataFormat:l}=t;return T(Lo(s),()=>`Error in gradient of conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${s}'`),{x:()=>qc(o.shape,r,n,a,i,l),filter:()=>ep(o,r,n.shape,a,i,l)}}};var jO={kernelName:Jo,inputsToSave:["dy","filter"],gradFunc:(r,e,t)=>{let[o,n]=e,{strides:s,pad:a,dataFormat:i,dimRoundingMode:l}=t;return{dy:()=>Kr(r,n,s,a,i,1,l),filter:()=>ep(r,o,n.shape,s,a,i,l)}}};function oJ(r,e,t,o,n){let s=r;r.rank===4&&(s=M(r,[1,r.shape[0],r.shape[1],r.shape[2],r.shape[3]]));let a=e;a.rank===4&&(a=M(e,[1,e.shape[0],e.shape[1],e.shape[2],e.shape[3]])),T(s.rank===5,()=>`Error in conv3dDerFilter: input must be rank 5, but got shape ${s.shape}.`),T(a.rank===5,()=>`Error in conv3dDerFilter: dy must be rank 5, but got shape ${a.shape}.`),T(t.length===5,()=>`Error in conv3dDerFilter: filterShape must be length 5, but got ${t}.`),T(s.shape[4]===t[3],()=>`Error in conv3dDerFilter: depth of input ${s.shape[4]}) must match input depth in filter (${t[3]}.`),T(a.shape[4]===t[4],()=>`Error in conv3dDerFilter: depth of dy (${a.shape[4]}) must match output depth for filter (${t[4]}).`);let i={x:s,dy:a},l={strides:o,pad:n,filterShape:t};return E.runKernel(jl,i,l)}var UO=S({conv3DBackpropFilter_:oJ});var HO={kernelName:na,inputsToSave:["x","filter"],gradFunc:(r,e,t)=>{let{dilations:o,strides:n,pad:s}=t;T(Lo(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:()=>UO(a,r,i.shape,n,s)}}};var qO={kernelName:Qo,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>O(He(Pu(ne(t,"float32"))),r)}}};var KO={kernelName:ei,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>O(Mu(ne(t,"float32")),r)}}};var XO={kernelName:en,inputsToSave:["x"],gradFunc:(r,e,t)=>{let[o]=e,{axis:n,exclusive:s,reverse:a}=t;return{x:()=>{let i=Rw([n],o.rank),l=Iu(r,n,s,!a);return i!=null&&(l=Ue(l,i)),l}}}};var YO={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;T(Lo(i),()=>`Error in gradient of depthwiseConv2dNative: dilation rates greater than 1 are not yet supported. Got dilations '${i}'`);let[l,u]=e;return T(l.rank===4,()=>`Error in gradient of depthwiseConv2dNative: input must be rank 4, but got rank ${l.rank}.`),T(u.rank===4,()=>`Error in gradient of depthwiseConv2dNative: filter must be rank 4, but got rank ${u.rank}.`),T(l.shape[3]===u.shape[2],()=>`Error in gradient of depthwiseConv2d: number of input channels (${l.shape[3]}) must match the inChannels dimension in filter ${u.shape[2]}.`),T(wr(n,i),()=>`Error in gradient of depthwiseConv2d: Either strides or dilations must be 1. Got strides ${n} and dilations '${i}'.`),a!=null&&T(ot(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 ZO={kernelName:sa,inputsToSave:["x","filter"],gradFunc:(r,e,t)=>{let[o,n]=e,s={x:o,filter:n,dy:r},a={x:o,filter:n,dy:r};return{x:()=>E.runKernel(Rc,s,t),filter:()=>E.runKernel(Fc,a,t)}}};var JO={kernelName:oi,outputsToSave:[!0],gradFunc:(r,e)=>{let[t]=e,o={dy:r,y:t};return{x:()=>E.runKernel(Yl,o)}}};var QO={kernelName:ni,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e,o=O(Yt(He(Oe(t))),2/Math.sqrt(Math.PI));return{x:()=>O(r,o)}}};var eP={kernelName:on,outputsToSave:[!0],gradFunc:(r,e)=>{let[t]=e;return{x:()=>O(r,t)}}};var tP={kernelName:us,inputsToSave:["input"],gradFunc:(r,e)=>{let[t]=e;return{input:()=>M(r,t.shape)}}};var rP={kernelName:ii,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>O(r,Yt(t))}}};var oP={kernelName:nn,gradFunc:r=>({x:()=>Ce(r)})};var nP={kernelName:sn,inputsToSave:["a","b"],gradFunc:(r,e)=>{let[t,o]=e,n=Be(t.shape,o.shape);return{a:()=>{let i=me(r,ne(o,"float32")),l=kt(t.shape,n);return l.length>0?M(ge(i,l),t.shape):i},b:()=>{let i=O(r,ne(t,"float32")),l=kt(o.shape,n);l.length>0&&(i=M(ge(i,l),o.shape));let u=Oe(o);return He(me(i,ne(u,"float32")))}}}};var sP={kernelName:an,inputsToSave:["x","mean","variance","scale"],gradFunc:(r,e,t)=>{let{varianceEpsilon:o}=t,[n,s,a,i]=e,l=i==null?le(1):i,u=kt(s.shape,n.shape),c=[];if(s.rank===1){for(let k=0;k<n.shape.length-1;++k)c.push(n.shape[k]);c.push(1)}let p=ce(n,s),m=O(r,l),f=Fu(ee(a,le(o))),d=O(O(O(f,f),f),le(-.5));return{x:()=>s.rank===1?M(O(O(r,zo(M(f,[1,1,1,s.shape[0]]),c)),l),n.shape):M(O(O(r,f),l),n.shape),mean:()=>{let k=O(O(f,le(-1)),m);return s.rank===1&&(k=ge(k,u)),M(k,s.shape)},variance:()=>{let k=O(O(d,p),m);return s.rank===1&&(k=ge(k,u)),M(k,s.shape)},scale:()=>{let k=O(p,f),v=O(r,k);return s.rank===1&&(v=ge(v,u)),M(v,s.shape)},offset:()=>{let k=r;return s.rank===1&&(k=ge(k,u)),M(k,s.shape)}}}};var lP={kernelName:cs,inputsToSave:["x","indices"],gradFunc:(r,e,t)=>{let[o,n]=e,{axis:s}=t,a=Jt(s,o.shape)[0];return{x:()=>{let l=o.shape,u=n.size,c=l.slice(0,a),p=c.length,m=l.slice(s,l.length).slice(1),f=m.length,d=iP(0,p),h=iP(p+1,p+1+f),g=aP([c,[u],m]),y=M(r,g),b=M(n,[u]),w=aP([[p],d,h]),k=Ue(y,w),v=Jm(k,b,o.shape[a]),D=Mm(w);return v=Ue(v,D),v},indices:()=>n}}};function iP(r,e){let t=[];for(let o=r;o<e;++o)t.push(o);return t}function aP(r){let e=[];for(let t=0;t<r.length;++t)for(let o=0;o<r[t].length;++o)e.push(r[t][o]);return e}var uP={kernelName:ln,inputsToSave:["a","b"],gradFunc:(r,e)=>{let[t,o]=e;return{a:()=>Ce(t),b:()=>Ce(o)}}};var cP={kernelName:Fo,gradFunc:r=>({x:()=>ne(r,"float32")})};var pP={kernelName:ci,gradFunc:r=>({x:()=>Ce(r)})};var mP={kernelName:pi,gradFunc:r=>({x:()=>Ce(r)})};var fP={kernelName:mi,gradFunc:r=>({x:()=>Ce(r)})};var dP={kernelName:un,inputsToSave:["x"],gradFunc:(r,e,t)=>{let[o]=e,{alpha:n}=t,s=Qt(o,0);return{x:()=>Dt(s,r,O(r,n))}}};var hP={kernelName:hi,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>me(r,ee(t,1))}}};var gP={kernelName:cn,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>me(r,ne(t,"float32"))}}};var xP={kernelName:$b,inputsToSave:[],outputsToSave:[!0],gradFunc:(r,e,t)=>{let[o]=e,{axis:n}=t;return{logits:()=>{let s=!0,a=Yt(o);return ce(r,O(ge(r,n,s),a))}}}};function nJ(r,e,t,o=5,n=1,s=1,a=.5){let i={x:r,y:e,dy:t},l={depthRadius:o,bias:n,alpha:s,beta:a};return E.runKernel(tu,i,l)}var yP=S({localResponseNormalizationBackprop_:nJ});var bP={kernelName:aa,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(r,e,t)=>{let[o,n]=e,{depthRadius:s,bias:a,alpha:i,beta:l}=t;return{x:()=>yP(o,n,r,s,a,i,l)}}};function sx(r,e,t,o){return e.rank<t.rank&&(e=M(e,Bn(e.shape,o))),r.rank<t.rank&&(r=M(r,Bn(r.shape,o))),{x:()=>O(r,ne(vo(t,e),r.dtype))}}var lC={kernelName:pn,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(r,e,t)=>{let o=t,{reductionIndices:n}=o,s=e[0],a=e[1],i=Jt(n,s.shape),l=sx(r,a,s,i);return{x:()=>l.x()}}};var wP={kernelName:mn,inputsToSave:["a","b"],gradFunc:(r,e)=>{let[t,o]=e;return{a:()=>O(r,ne(io(t,o),"float32")),b:()=>O(r,ne(Su(t,o),"float32"))}}};function sJ(r,e,t,o,n,s,a){let i=_(r,"dy","maxPool3dGrad"),l=_(e,"input","maxPool3dGrad"),u=_(t,"output","maxPool3dGrad"),c=i,p=l,m=u,f=!1;l.rank===4&&(f=!0,c=M(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]]),p=M(l,[1,l.shape[0],l.shape[1],l.shape[2],l.shape[3]]),m=M(u,[1,u.shape[0],u.shape[1],u.shape[2],u.shape[3]])),T(c.rank===5,()=>`Error in maxPool3dGrad: dy must be rank 5 but got rank ${c.rank}.`),T(p.rank===5,()=>`Error in maxPool3dGrad: input must be rank 5 but got rank ${p.rank}.`),T(m.rank===5,()=>`Error in maxPool3dGrad: output must be rank 5 but got rank ${m.rank}.`),a!=null&&T(ot(s),()=>`Error in maxPool3dGrad: pad must be an integer when using, dimRoundingMode ${a} but got pad ${s}.`);let d={dy:c,input:p,output:m},h={filterSize:o,strides:n,pad:s,dimRoundingMode:a},g=E.runKernel(ou,d,h);return f?M(g,[g.shape[1],g.shape[2],g.shape[3],g.shape[4]]):g}var kP=S({maxPool3dGrad_:sJ});var _P={kernelName:la,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(r,e,t)=>{let[o,n]=e,{filterSize:s,strides:a,pad:i,dimRoundingMode:l}=t;return{x:()=>kP(r,o,n,s,a,i,l)}}};function iJ(r,e,t,o,n,s,a){let i=_(r,"dy","maxPoolGrad"),l=_(e,"input","maxPoolGrad"),u=_(t,"output","maxPoolGrad");T(l.rank===i.rank,()=>`Rank of input (${l.rank}) does not match rank of dy (${i.rank})`),T(i.rank===4,()=>`Error in maxPoolGrad: dy must be rank 4 but got rank ${i.rank}.`),T(l.rank===4,()=>`Error in maxPoolGrad: input must be rank 4 but got rank ${l.rank}.`),a!=null&&T(ot(s),()=>`Error in maxPoolGrad: pad must be an integer when using, dimRoundingMode ${a} but got pad ${s}.`);let c={dy:i,input:l,output:u},p={filterSize:o,strides:n,pad:s,dimRoundingMode:a};return E.runKernel(ru,c,p)}var vP=S({maxPoolGrad_:iJ});var CP={kernelName:fn,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(r,e,t)=>{let[o,n]=e,{filterSize:s,strides:a,pad:i}=t;return{x:()=>vP(r,o,n,s,a,i)}}};var IP={kernelName:dn,inputsToSave:["x"],gradFunc:(r,e,t)=>{let[o]=e,{axis:n}=t,s=Jt(n,o.shape),i=$w(o.shape,s)[1],l=ct(i);return{x:()=>{let c=o.shape.slice();s.forEach(f=>{c[f]=1});let p=M(r,c);return me(O(p,Ir(o.shape,"float32")),l)}}}};var NP={kernelName:hn,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(r,e,t)=>{let o=t,{axis:n}=o,[s,a]=e,i=Jt(n,s.shape),l=sx(r,a,s,i);return{x:()=>l.x()}}};var SP={kernelName:gn,inputsToSave:["a","b"],gradFunc:(r,e)=>{let[t,o]=e;return{a:()=>O(r,ne(Bo(t,o),"float32")),b:()=>O(r,ne(Qt(t,o),"float32"))}}};var TP={kernelName:ua,inputsToSave:["x"],gradFunc:(r,e,t)=>{let o=e[0],{paddings:n}=t,s=n.map(a=>a[0]);return{x:()=>Re(r,s,o.shape)}}};var AP={kernelName:xi,inputsToSave:["a","b"],gradFunc:(r,e)=>{let[t,o]=e,n=Be(t.shape,o.shape);return{a:()=>{let i=kt(t.shape,n);return i.length>0?M(ge(r,i),t.shape):r},b:()=>{let i=O(r,He(Ss(me(t,o)))),l=kt(o.shape,n);return l.length>0?M(ge(i,l),o.shape):i}}}};var EP={kernelName:xn,inputsToSave:["a","b"],gradFunc:(r,e)=>{let[t,o]=e,n=Be(t.shape,o.shape);return{a:()=>{let i=O(r,ne(o,"float32")),l=kt(t.shape,n);return l.length>0?M(ge(i,l),t.shape):i},b:()=>{let i=O(r,ne(t,"float32")),l=kt(o.shape,n);return l.length>0?M(ge(i,l),o.shape):i}}}};var DP={kernelName:ps,gradFunc:r=>({x:()=>He(r)})};var $P={kernelName:yn,inputsToSave:["indices"],gradFunc:(r,e)=>{let t=e[0];return{indices:()=>ht(t.shape,"float32")}}};var RP={kernelName:ms,gradFunc:r=>({x:()=>Ce(r)})};var FP={kernelName:fs,saveAllInputs:!0,gradFunc:(r,e,t)=>{let{axis:o}=t;return cr(r,o).map(s=>()=>s)}};var uC={kernelName:bn,inputsToSave:["x"],gradFunc:(r,e,t)=>{let o=e[0],{paddings:n}=t,s=n.map(a=>a[0]);return{x:()=>Re(r,s,o.shape)}}};var OP={kernelName:wn,inputsToSave:["a","b"],outputsToSave:[!0],gradFunc:(r,e)=>{let[t,o,n]=e,s=t,a=o,i=Be(s.shape,a.shape);return{a:()=>{let c=ne(a,"float32"),p=O(r,O(c,Fr(s,ce(c,le(1))))),m=kt(s.shape,i);return m.length>0&&(p=ge(p,m)),M(p,s.shape)},b:()=>{let c=Qt(s,0),p=Dt(c,ar(s),Ce(s)),m=O(r,O(n,p)),f=kt(a.shape,i);return f.length>0&&(m=ge(m,f)),M(m,a.shape)}}}};var PP={kernelName:kn,inputsToSave:["x","alpha"],gradFunc:(r,e)=>{let[t,o]=e,n=Qt(t,0);return{x:()=>Dt(n,r,O(r,o)),alpha:()=>{let s=Dt(n,Ce(r),O(r,t)),a=kt(o.shape,r.shape);return a.length>0&&(s=ge(s,a)),M(s,o.shape)}}}};var MP={kernelName:rn,inputsToSave:["a","b"],gradFunc:(r,e)=>{let[t,o]=e,n=Be(t.shape,o.shape);return{a:()=>{let i=me(r,ne(o,"float32")),l=kt(t.shape,n);return l.length>0?M(ge(i,l),t.shape):i},b:()=>{let i=O(r,ne(t,"float32")),l=kt(o.shape,n);l.length>0&&(i=M(ge(i,l),o.shape));let u=Oe(o);return He(me(i,ne(u,"float32")))}}}};var LP={kernelName:vi,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>me(r,He(Oe(t)))}}};var zP={kernelName:Cn,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e,o=O(Bo(t,6),Ds(t));return{x:()=>O(r,ne(o,"float32"))}}};var BP={kernelName:_n,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>O(r,ne(Ds(t),"float32"))}}};var VP={kernelName:ds,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>M(r,t.shape)}}};var GP={kernelName:vn,inputsToSave:["images"],gradFunc:(r,e,t)=>{let[o]=e,n={dy:r,images:o};return{images:()=>E.runKernel(lu,n,t)}}};var WP={kernelName:pa,inputsToSave:["images"],gradFunc:(r,e,t)=>{let[o]=e,n={dy:r,images:o};return{images:()=>E.runKernel(au,n,t)}}};var jP={kernelName:In,gradFunc:(r,e,t)=>{let{dims:o}=t,n=Jt(o,r.shape);return{x:()=>Ht(r,n)}}};var UP={kernelName:Nn,gradFunc:r=>({x:()=>Ce(r)})};var HP={kernelName:Sn,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>He(me(r,O(Fr(t,1.5),2)))}}};var qP={kernelName:hs,inputsToSave:["condition"],gradFunc:(r,e)=>{let[t]=e;return{condition:()=>ne(Ce(t),"float32"),t:()=>O(r,ne(t,r.dtype)),e:()=>O(r,ne(Ia(t),r.dtype))}}};var KP={kernelName:Ii,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>{let o=Qt(t,le(0)),n=le(nk),s=le(sk),a=O(r,s),i=O(O(r,n),Yt(ne(t,"float32")));return Dt(o,a,i)}}}};var XP={kernelName:An,outputsToSave:[!0],gradFunc:(r,e)=>{let[t]=e;return{x:()=>O(r,O(t,ce(le(1),t)))}}};var YP={kernelName:Si,gradFunc:r=>({x:()=>Ce(r)})};var ZP={kernelName:Tn,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>O(_a(ne(t,"float32")),r)}}};var JP={kernelName:Ni,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>O(Cu(ne(t,"float32")),r)}}};var QP={kernelName:gs,inputsToSave:["x"],gradFunc:(r,e,t)=>{let[o]=e,{begin:n,size:s}=t,a=o.shape,[i,l]=aw(o,n,s),u=[];for(let c=0;c<r.rank;c++)u.push([i[c],a[c]-i[c]-l[c]]);return{x:()=>Rr(r,u)}}};var eM={kernelName:$n,outputsToSave:[!0],gradFunc:(r,e,t)=>{let[o]=e,{dim:n}=t,s=!0,a=O(r,o);return{logits:()=>ce(a,O(ge(a,[n],s),o))}}};var tM={kernelName:Ti,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>O(r,qr(t))}}};var cC={kernelName:ma,gradFunc:(r,e,t)=>{let{blockShape:o,paddings:n}=t;return{x:()=>ka(r,o,n)}}};var pC={kernelName:xs,gradFunc:(r,e,t)=>{let{axis:o}=t;return{x:()=>Ze(r,o)}}};var rM={kernelName:En,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>me(r,O(gt(ne(t,"float32")),2))}}};var oM={kernelName:fa,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>O(r,O(ne(t,"float32"),2))}}};var nM={kernelName:Rn,inputsToSave:["a","b"],gradFunc:(r,e)=>{let[t,o]=e,n=le(2);return{a:()=>O(r,O(n,ce(t,o))),b:()=>O(r,O(n,ce(o,t)))}}};var sM={kernelName:Oo,gradFunc:r=>({x:()=>Ce(r)})};var iM={kernelName:Fn,inputsToSave:["a","b"],gradFunc:(r,e)=>{let[t,o]=e,n=Be(t.shape,o.shape);return{a:()=>{let i=r,l=kt(t.shape,n);return l.length>0&&(i=ge(i,l)),M(i,t.shape)},b:()=>{let i=r,l=kt(o.shape,n);return l.length>0&&(i=ge(i,l)),M(He(i),o.shape)}}}};var aM={kernelName:Dn,inputsToSave:["x"],gradFunc:(r,e,t)=>{let[o]=e,n=o.shape.slice(),{axis:s}=t;Jt(s,o.shape).forEach(u=>{n[u]=1});let i=M(r,n),l=O(i,Ir(o.shape,"float32"));return{x:()=>l}}};var lM={kernelName:Ei,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>me(r,Oe(_a(t)))}}};var uM={kernelName:On,outputsToSave:[!0],gradFunc:(r,e)=>{let[t]=e;return{x:()=>O(ce(le(1),Oe(t)),r)}}};var cM={kernelName:ko,inputsToSave:["x"],gradFunc:(r,e,t)=>{let[o]=e,{reps:n}=t;return{x:()=>{let a=Ce(o);if(o.rank===1)for(let i=0;i<n[0];++i)a=ee(a,Re(r,[i*o.shape[0]],[o.shape[0]]));else if(o.rank===2)for(let i=0;i<n[0];++i)for(let l=0;l<n[1];++l)a=ee(a,Re(r,[i*o.shape[0],l*o.shape[1]],[o.shape[0],o.shape[1]]));else if(o.rank===3)for(let i=0;i<n[0];++i)for(let l=0;l<n[1];++l)for(let u=0;u<n[2];++u)a=ee(a,Re(r,[i*o.shape[0],l*o.shape[1],u*o.shape[2]],[o.shape[0],o.shape[1],o.shape[2]]));else if(o.rank===4)for(let i=0;i<n[0];++i)for(let l=0;l<n[1];++l)for(let u=0;u<n[2];++u)for(let c=0;c<n[3];++c)a=ee(a,Re(r,[i*o.shape[0],l*o.shape[1],u*o.shape[2],c*o.shape[3]],[o.shape[0],o.shape[1],o.shape[2],o.shape[3]]));else throw new Error(`Gradient for tile operation is not implemented for rank-${o.rank} tensors yet.`);return a}}}};var pM={kernelName:Pn,gradFunc:(r,e,t)=>{let o=t,{perm:n}=o,s=Mm(n);return{x:()=>Ue(r,s)}}};var mM={kernelName:ys,gradFunc:(r,e,t)=>{let o=t,{axis:n}=o;return{value:()=>Bt(r,n)}}};var fM={kernelName:da,inputsToSave:["segmentIds"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>aJ(r,t)}}};function aJ(r,e){let t=Yr(e,Ce(e)),o=zn(r,t),n=io(e,le(0,"int32")),s=o.rank-n.rank;for(let i=0;i<s;++i)n=ir(n,i+1);n=dr(n,Ir(o.shape,"bool"));let a=Ce(o);return Dt(n,o,a)}var dM={kernelName:bs,gradFunc:r=>({x:()=>Ce(r)})};var lJ=[nx,wO,kO,_O,vO,CO,IO,NO,SO,TO,AO,EO,$O,FO,OO,PO,MO,LO,zO,BO,VO,GO,jO,WO,HO,qO,KO,XO,YO,ZO,MP,JO,QO,eP,tP,rP,nP,oP,sP,lP,uP,cP,pP,mP,fP,dP,hP,gP,xP,bP,lC,lC,wP,_P,CP,IP,NP,SP,TP,AP,EP,DP,$P,RP,FP,uC,uC,OP,PP,LP,zP,BP,VP,GP,WP,jP,UP,HP,qP,KP,XP,YP,ZP,JP,QP,eM,tM,cC,cC,pC,pC,rM,nM,oM,sM,iM,aM,lM,uM,cM,pM,mM,fM,dM];for(let r of lJ)Fb(r);var gC={};Ke(gC,{maxNorm:()=>cJ,minMaxNorm:()=>fJ,nonNeg:()=>mJ,unitNorm:()=>pJ});var mC;function Zt(){return mC==null&&(mC=pw().epsilon()),mC}function Zr(){return"channelsLast"}var So=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,So.prototype)}},Mr=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,Mr.prototype)}},z=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,z.prototype)}},Se=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,Se.prototype)}},Ff=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,Ff.prototype)}};function Zn(r,e){if(Array.isArray(r)){let t=[];for(let o=0;o<e;o++)t=t.concat(r);return t}else{let t=new Array(e);return t.fill(r),t}}function Go(r,e){if(!r)throw new Ff(e)}function fC(r,e){let t=0;for(let o of r)o===e&&t++;return t}function gr(r){return r.length===1?r[0]:r}function yt(r){return Array.isArray(r)?r:[r]}function Jn(r){let t=r.replace(/(.)([A-Z][a-z0-9]+)/g,"$1_$2").replace(/([a-z])([A-Z])/g,"$1_$2").toLowerCase();return t[0]!=="_"?t:"private"+t}function za(r){return r.length<=1||r.indexOf("_")===-1?r:r.replace(/[_]+(\w|$)/g,(e,t)=>t.toUpperCase())}var Qn={};function Cp(r){if(r==null)return null;let e={};return e.className=r.getClassName(),e.config=r.getConfig(),e}function dC(r){if(!(r==null||typeof r!="object"))if(Array.isArray(r))r.forEach(e=>dC(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:dC(o))}}}function Gi(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 Qn)a=Qn[s];else if(a=e[s],a==null)throw new z(`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 z(`${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 Qn?[i,l]=Qn.className:a in e&&([i,l]=e[a]),i==null)throw new z(`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(Qn))u[f]=Qn[f];for(let f of Object.keys(t))u[f]=t[f];let c=s.config;c.customObjects=u;let p=Object.assign({},Qn);for(let f of Object.keys(t))Qn[f]=t[f];dC(s.config);let m=l(i,s.config,t,n);return Qn=Object.assign({},p),m}else{let u=Object.assign({},Qn);for(let p of Object.keys(t))Qn[p]=t[p];let c=new i(s.config);return Qn=Object.assign({},u),c}}}function uJ(r,e){return r<e?-1:r>e?1:0}function Of(r,e){return-1*uJ(r,e)}function es(r){if(r==null)return r;let e=[];for(let t of r)e.indexOf(t)===-1&&e.push(t);return e}function hM(r){if(r==null)throw new z(`Invalid value in obj: ${JSON.stringify(r)}`);for(let e in r)if(r.hasOwnProperty(e))return!1;return!0}function Wi(r,e,t){if(t!=null&&r.indexOf(t)<0)throw new z(`${t} is not a valid ${e}. Valid values are ${r} or null/undefined.`)}function ix(r,e,t=0,o=Infinity){return Go(t>=0),Go(o>=t),Array.isArray(r)&&r.length>=t&&r.length<=o&&r.every(n=>typeof n===e)}function Ut(r,e){Array.isArray(r)?(x.assert(r.length>0,()=>`${e} is unexpectedly an empty array.`),r.forEach((t,o)=>Ut(t,`element ${o+1} of ${e}`))):x.assert(Number.isInteger(r)&&r>0,()=>`Expected ${e} to be a positive integer, but got ${gM(r)}.`)}function gM(r){return r===null?"null":Array.isArray(r)?"["+r.map(e=>gM(e)).join(",")+"]":typeof r=="string"?`"${r}"`:`${r}`}function xM(r,e){let t=x.now(),o;return(...s)=>{let a=x.now();return a-t<e||(t=a,o=r(...s)),o}}function ax(r){return r==="relu"?"relu":r==="linear"?"linear":r==="elu"?"elu":null}function hC(r,e){return V(()=>gt(ge(O(r,r),e,!0)))}var Ip=class extends Q.Serializable{getConfig(){return{}}},Pf=class extends Ip{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=hC(e,this.axis),o=sr(t,0,this.maxValue);return O(e,me(o,ee(Zt(),t)))})}getConfig(){return{maxValue:this.maxValue,axis:this.axis}}};Pf.className="MaxNorm";Q.registerClass(Pf);var Mf=class extends Ip{constructor(e){super();this.defaultAxis=0,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return V(()=>me(e,ee(Zt(),hC(e,this.axis))))}getConfig(){return{axis:this.axis}}};Mf.className="UnitNorm";Q.registerClass(Mf);var Lf=class extends Ip{apply(e){return Nr(e)}};Lf.className="NonNeg";Q.registerClass(Lf);var zf=class extends Ip{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=hC(e,this.axis),o=ee(O(this.rate,sr(t,this.minValue,this.maxValue)),O(1-this.rate,t));return O(e,me(o,ee(Zt(),t)))})}getConfig(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}}};zf.className="MinMaxNorm";Q.registerClass(zf);var yM={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};function Ft(r){return Cp(r)}function bM(r,e={}){return Gi(r,Q.SerializationMap.getMap().classNameMap,e,"constraint")}function Ot(r){if(r==null)return null;if(typeof r=="string"){let t={className:r in yM?yM[r]:r,config:{}};return bM(t)}else return r instanceof Ip?r:bM(r)}function cJ(r){return new Pf(r)}function pJ(r){return new Mf(r)}function mJ(){return new Lf}function fJ(r){return new zf(r)}var kC={};Ke(kC,{constant:()=>kJ,glorotNormal:()=>TJ,glorotUniform:()=>SJ,heNormal:()=>AJ,heUniform:()=>EJ,identity:()=>IJ,leCunNormal:()=>DJ,leCunUniform:()=>$J,ones:()=>wJ,orthogonal:()=>RJ,randomNormal:()=>vJ,randomUniform:()=>_J,truncatedNormal:()=>CJ,varianceScaling:()=>NJ,zeros:()=>bJ});var wM=["channelsFirst","channelsLast"],kM=["nearest","bilinear"],_M=["valid","same","causal"],vM=["max","avg"],CM=["sum","mul","concat","ave"];var Np=new Map;function $t(r){Wi(wM,"DataFormat",r)}function IM(r){Wi(kM,"InterpolationFormat",r)}function Jr(r){Wi(_M,"PaddingMode",r)}function xC(r){Wi(vM,"PoolMode",r)}var Bf=[],NM="/";function Ms(r,e){Bf.push(r);try{let t=e();return Bf.pop(),t}catch(t){throw Bf.pop(),t}}function dJ(){return Bf.length===0?"":Bf.join(NM)+NM}function lx(r){if(!SM(r))throw new Error("Not a valid tensor name: '"+r+"'");return dJ()+r}function ux(r){if(!SM(r))throw new Error("Not a valid tensor name: '"+r+"'");Np.has(r)||Np.set(r,0);let e=Np.get(r);if(Np.set(r,Np.get(r)+1),e>0){let t=`${r}_${e}`;return Np.set(t,1),t}else return r}var hJ=new RegExp(/^[A-Za-z0-9][-A-Za-z0-9\._\/]*$/);function SM(r){return!!r.match(hJ)}function TM(r){return r===parseInt(r.toString(),10)}function ts(r,e,t){e==null&&(e=0),t==null&&(t=r.length);let o=1;for(let n=e;n<t;++n)o*=r[n];return o}function AM(r){return r=Array.isArray(r)?new Float32Array(r):r,Vt(r)}function sc(r){return Pi(AM(r)).dataSync()[0]}function Ls(r){return lr(AM(r)).dataSync()[0]}function Lr(r,e){if(e<r)throw new z(`end (${e}) < begin (${r}) is forbidden.`);let t=[];for(let o=r;o<e;++o)t.push(o);return t}function Ba(r,e){return r.asType(e)}function Va(r,e=-1){let t=r.shape.slice();return e<0&&(e=t.length+e+1),t.splice(e,0,1),r.reshape(t)}function EM(r,e){return V(()=>{if(r.shape.length!==2)throw new z(`repeat() expects a rank-2 tensor, but received a rank-${r.shape.length} tensor.`);let t=Va(r,1);return cx(t,[1,e,1])})}function DM(r){let e=[ts(r.shape)];return r.reshape(e)}function $M(r){if(r.rank<=1)throw new z(`batchFlatten requires a minimum rank of 2. Got rank: ${r.rank}.`);let e=[r.shape[0],ts(r.shape,1)];return r.reshape(e)}function Ga(r,e,t){return V(()=>{switch(r.rank){case 1:return qm(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 Jc(r,[e,0,0,0],[t,r.shape[1],r.shape[2],r.shape[3]]);case 5:return Re(r,[e,0,0,0,0],[t,r.shape[1],r.shape[2],r.shape[3],r.shape[4]]);case 6:return Re(r,[e,0,0,0,0,0],[t,r.shape[1],r.shape[2],r.shape[3],r.shape[4],r.shape[5]]);default:throw new z(`sliceAlongFirstAxis() received an unsupported tensor rank: ${r.rank}`)}})}function yC(r,e,t){return V(()=>{switch(r.rank){case 1:return qm(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 Jc(r,[0,0,0,e],[r.shape[0],r.shape[1],r.shape[2],t]);default:throw new z(`sliceAlongLastAxis() received an unsupported tensor rank: ${r.rank}`)}})}function Vf(r,e,t,o){return V(()=>{switch(r.rank){case 1:return qm(r,e,t);case 2:switch(o){case 1:return Ga(r,e,t);case 2:return yC(r,e,t);default:throw new z(`The axis is not within the rank of the tensor ${o}`)}case 3:switch(o){case 1:return Ga(r,e,t);case 2:return Km(r,[0,e,0],[r.shape[0],t,r.shape[2]]);case 3:return yC(r,e,t);default:throw new z(`The axis is not within the rank of the tensor ${o}`)}case 4:switch(o){case 1:return Ga(r,e,t);case 2:return Jc(r,[0,e,0,0],[r.shape[0],t,r.shape[2],r.shape[3]]);case 3:return Jc(r,[0,0,e,0],[r.shape[0],r.shape[1],t,r.shape[3]]);case 4:return yC(r,e,t);default:throw new z(`The axis is not within the rank of the tensor ${o}`)}default:throw new z(`sliceAlongLastAxis() received an unsupported tensor rank: ${r.rank}`)}})}function Sp(r,e=-1){let t;return e<0&&(t=r[0].rank,t!==0?e=t:e=0),e===r[0].rank&&(e=-1),Ze(r,e)}function bC(r,e){switch(r.rank){case 1:return ww([r,e]);case 2:return kw([r,e],0);case 3:return _w([r,e],0);case 4:return vw([r,e],0);default:throw new z(`concatAlongFirstAxis() received an unsupported tensor rank: ${r.rank}`)}}function cx(r,e){if(Array.isArray(e)||(e=[e]),r.rank!==e.length)throw new z(`The length of input n (${e.length}) does not match the number of dimensions in input x (${r.rank})`);return zo(r,e)}function Tp(r,e=0,t=1,o,n){return lg(r,e,t,o,n)}function rs(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 Gn.matMul({a:r,b:e,transposeA:n,transposeB:s,bias:o?wC(r.rank,o,Zr()):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 Gn.matMul({a:r,b:e,transposeA:m,transposeB:f,bias:o?wC(r.rank,o,Zr()):null,activation:t}).reshape(p)}}function px(r,e,t){return V(()=>(Array.isArray(e)?e=Vt(e,"int32"):e=e.toInt(),zn(r,e,t)))}function ic(r){return O(r,r)}function wC(r,e,t){let o=e.shape;if(e.rank!==1&&e.rank!==r)throw new z(`Unexpected bias dimensions: ${e.rank}; expected it to be 1 or ${r}`);if(r===5){if(t==="channelsFirst")return 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 z(`Unsupported input rank by biasAdd: ${e.rank}`)}function uo(r,e,t){return V(()=>(t==null&&(t=Zr()),$t(t),r.add(wC(r.rank,e,t))))}function RM(r,e=1){if(e!==1)throw new Se(`Support for alpha values other than 1 (${e}) is not implemented yet.`);return Ns(r)}function FM(r){return V(()=>me(r,It(r).add(1)))}function mx(r,e,t,o){return V(()=>Zw(r,e,t,o))}function OM(r){return V(()=>{let e=ee(.5,O(.2,r));return sr(e,0,1)})}function bl(r,e,t=!1){return t?r():e()}var PM=["fanIn","fanOut","fanAvg"],MM=["normal","uniform","truncatedNormal"];function gJ(r){Wi(PM,"FanMode",r)}function xJ(r){Wi(MM,"Distribution",r)}var co=class extends Q.Serializable{fromConfigUsesCustomObjects(){return!1}getConfig(){return{}}},Gf=class extends co{apply(e,t){return ht(e,t)}};Gf.className="Zeros";Q.registerClass(Gf);var ac=class extends co{apply(e,t){return Ir(e,t)}};ac.className="Ones";Q.registerClass(ac);var Wf=class extends co{constructor(e){super();if(typeof e!="object")throw new z(`Expected argument of type ConstantConfig but got ${e}`);if(e.value===void 0)throw new z(`config must have value set but got ${e}`);this.value=e.value}apply(e,t){return V(()=>O(le(this.value),Ir(e,t)))}getConfig(){return{value:this.value}}};Wf.className="Constant";Q.registerClass(Wf);var jf=class extends co{constructor(e){super();this.DEFAULT_MINVAL=-.05,this.DEFAULT_MAXVAL=.05,this.minval=e.minval||this.DEFAULT_MINVAL,this.maxval=e.maxval||this.DEFAULT_MAXVAL,this.seed=e.seed}apply(e,t){return Es(e,this.minval,this.maxval,t)}getConfig(){return{minval:this.minval,maxval:this.maxval,seed:this.seed}}};jf.className="RandomUniform";Q.registerClass(jf);var Uf=class extends co{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 Tp(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}};Uf.className="RandomNormal";Q.registerClass(Uf);var Hf=class extends co{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 Bu(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}};Hf.className="TruncatedNormal";Q.registerClass(Hf);var qf=class extends co{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 z("Identity matrix initializer can only be used for 2D square matrices.");return O(this.gain,Kc(e[0]))})}getConfig(){return{gain:this.gain}}};qf.className="Identity";Q.registerClass(qf);function yJ(r,e="channelsLast"){let t,o;if($t(e),r.length===2)t=r[0],o=r[1];else if([3,4,5].indexOf(r.length)!==-1){if(e==="channelsFirst"){let n=ts(r,2);t=r[1]*n,o=r[0]*n}else if(e==="channelsLast"){let n=ts(r,0,r.length-2);t=r[r.length-2]*n,o=r[r.length-1]*n}}else{let n=ts(r);t=Math.sqrt(n),o=Math.sqrt(n)}return[t,o]}var zr=class extends co{constructor(e){super();if(e.scale<0)throw new z(`scale must be a positive float. Got: ${e.scale}`);this.scale=e.scale==null?1:e.scale,this.mode=e.mode==null?"fanIn":e.mode,gJ(this.mode),this.distribution=e.distribution==null?"normal":e.distribution,xJ(this.distribution),this.seed=e.seed}apply(e,t){let o=yJ(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 Bu(e,0,i,t,this.seed)}else{let i=Math.sqrt(3*a);return Es(e,-i,i,t)}}getConfig(){return{scale:this.scale,mode:this.mode,distribution:this.distribution,seed:this.seed}}};zr.className="VarianceScaling";Q.registerClass(zr);var Ap=class extends zr{constructor(e){super({scale:1,mode:"fanAvg",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return zr.className}};Ap.className="GlorotUniform";Q.registerClass(Ap);var Ep=class extends zr{constructor(e){super({scale:1,mode:"fanAvg",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return zr.className}};Ep.className="GlorotNormal";Q.registerClass(Ep);var Dp=class extends zr{constructor(e){super({scale:2,mode:"fanIn",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return zr.className}};Dp.className="HeNormal";Q.registerClass(Dp);var $p=class extends zr{constructor(e){super({scale:2,mode:"fanIn",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return zr.className}};$p.className="HeUniform";Q.registerClass($p);var Rp=class extends zr{constructor(e){super({scale:1,mode:"fanIn",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return zr.className}};Rp.className="LeCunNormal";Q.registerClass(Rp);var Fp=class extends zr{constructor(e){super({scale:1,mode:"fanIn",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return zr.className}};Fp.className="LeCunNormal";Q.registerClass(Fp);var Kf=class extends co{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=Tp(o,0,1,"float32"),s=ok.gramSchmidt(n);return e[0]>e[1]&&(s=s.transpose()),O(this.gain,s)})}getConfig(){return{gain:this.gain,seed:this.seed}}};Kf.className="Orthogonal";Q.registerClass(Kf);var LM={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 zM(r,e={}){return Gi(r,Q.SerializationMap.getMap().classNameMap,e,"initializer")}function _t(r){return Cp(r)}function pt(r){if(typeof r=="string"){let e=r in LM?LM[r]:r;if(e==="GlorotNormal")return new Ep;if(e==="GlorotUniform")return new Ap;if(e==="HeNormal")return new Dp;if(e==="HeUniform")return new $p;if(e==="LeCunNormal")return new Rp;if(e==="LeCunUniform")return new Fp;{let t={};return t.className=e,t.config={},zM(t)}}else return r instanceof co?r:zM(r)}function bJ(){return new Gf}function wJ(){return new ac}function kJ(r){return new Wf(r)}function _J(r){return new jf(r)}function vJ(r){return new Uf(r)}function CJ(r){return new Hf(r)}function IJ(r){return new qf(r)}function NJ(r){return new zr(r)}function SJ(r){return new Ap(r)}function TJ(r){return new Ep(r)}function AJ(r){return new Dp(r)}function EJ(r){return new $p(r)}function DJ(r){return new Rp(r)}function $J(r){return new Fp(r)}function RJ(r){return new Kf(r)}var oI={};Ke(oI,{Layer:()=>Me,RNN:()=>ho,RNNCell:()=>Sl,activation:()=>Z9,add:()=>iQ,alphaDropout:()=>WQ,average:()=>aQ,averagePooling1d:()=>nI,averagePooling2d:()=>sI,averagePooling3d:()=>iI,avgPool1d:()=>gQ,avgPool2d:()=>yQ,avgPool3d:()=>wQ,avgPooling1d:()=>xQ,avgPooling2d:()=>bQ,avgPooling3d:()=>kQ,batchNormalization:()=>fQ,bidirectional:()=>OQ,concatenate:()=>lQ,conv1d:()=>W9,conv2d:()=>j9,conv2dTranspose:()=>U9,conv3d:()=>H9,convLstm2d:()=>DQ,convLstm2dCell:()=>$Q,cropping2D:()=>K9,dense:()=>J9,depthwiseConv2d:()=>Y9,dot:()=>mQ,dropout:()=>Q9,elu:()=>M9,embedding:()=>sQ,flatten:()=>tQ,gaussianDropout:()=>GQ,gaussianNoise:()=>VQ,globalAveragePooling1d:()=>_Q,globalAveragePooling2d:()=>vQ,globalMaxPool1d:()=>MQ,globalMaxPool2d:()=>LQ,globalMaxPooling1d:()=>wL,globalMaxPooling2d:()=>kL,gru:()=>IQ,gruCell:()=>NQ,input:()=>Fx,inputLayer:()=>P9,layerNormalization:()=>dQ,leakyReLU:()=>z9,lstm:()=>SQ,lstmCell:()=>TQ,masking:()=>jQ,maxPool1d:()=>zQ,maxPool2d:()=>BQ,maxPooling1d:()=>_L,maxPooling2d:()=>vL,maxPooling3d:()=>CQ,maximum:()=>uQ,minimum:()=>cQ,multiply:()=>pQ,permute:()=>nQ,prelu:()=>B9,reLU:()=>L9,repeatVector:()=>rQ,reshape:()=>oQ,rnn:()=>RQ,separableConv2d:()=>q9,simpleRNN:()=>AQ,simpleRNNCell:()=>EQ,softmax:()=>V9,spatialDropout1d:()=>eQ,stackedRNNCells:()=>FQ,thresholdedReLU:()=>G9,timeDistributed:()=>PQ,upSampling2d:()=>X9,zeroPadding2d:()=>hQ});var FJ=0;function fx(){return FJ++}var dx={};function wl(r=""){return r in dx||(dx[r]=0),dx[r]+=1,r+dx[r].toString()}function hx(r){return Array.isArray(r)&&Array.isArray(r[0])}function Op(r){return r.length===0?[]:Array.isArray(r[0])?r:[r]}function Fe(r){let e;if(Array.isArray(r)){if(r.length!==1)throw new z(`Expected Tensor length to be 1; got ${r.length}`);e=r[0]}else e=r;return e}function Je(r){if(Array.isArray(r)&&Array.isArray(r[0])){if(r.length===1)return r=r,r[0];throw new z(`Expected exactly 1 Shape; got ${r.length}`)}else return r}function Pp(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 BM="Variable",Xf=class{constructor(e,t="float32",o=BM,n=!0,s=null){this.dtype=t==null?"float32":t,this.shape=e.shape,this.id=fx(),o=o==null?BM:o,this.originalName=lx(o),this.name=ux(this.originalName),this.trainable_=n,this.constraint=s,this.val=qw(e,this.trainable_,this.name,this.dtype)}read(){return this.assertNotDisposed(),this.val}write(e){return this.assertNotDisposed(),OJ(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 OJ(r,e){if(r.shape.toString()!==e.shape.toString())throw new Error("Shape mismatch: "+JSON.stringify(r.shape)+" vs. "+JSON.stringify(e.shape))}function Yf(r){return r.map(e=>e.read())}function Mp(r){r.forEach(e=>{e[0].write(e[1])})}var St=class{constructor(e){this.dtype=e.dtype,this.shape=e.shape,e.shape!=null?this.ndim=e.shape.length:this.ndim=e.ndim,this.maxNDim=e.maxNDim,this.minNDim=e.minNDim,this.axes=e.axes||{}}},Br=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=fx(),a!=null&&(this.originalName=lx(a),this.name=ux(this.originalName)),this.rank=t.length}},PJ=0,kl=class{constructor(e,t){this.callArgs=t,this.id=PJ++,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}}},MJ=0,Me=class extends Q.Serializable{constructor(e={}){super();this._callHook=null,this._addedWeightNames=[],this._stateful=!1,this.id=MJ++,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=Jn(o)+"_"+wl(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 Mr(`The layer has never been called and thus has no defined ${t}.`);if(this.inboundNodes.length<=e)throw new z(`Asked to get ${t} at node ${e}, but the layer has only ${this.inboundNodes.length} inbound nodes.`);return this.inboundNodes[e]}getInputAt(e){return gr(this.getNodeAtIndex(e,"input").inputTensors)}getOutputAt(e){return gr(this.getNodeAtIndex(e,"output").outputTensors)}get input(){if(this.inboundNodes.length>1)throw new So(`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 So(`Layer ${this.name} is not connected, no input to return.`);return gr(this.getNodeAtIndex(0,"input").inputTensors)}get output(){if(this.inboundNodes.length===0)throw new So(`Layer ${this.name} has no inbound nodes.`);if(this.inboundNodes.length>1)throw new So(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer output" is ill-defined. Use \`getOutputAt(nodeIndex)\` instead.`);return gr(this.getNodeAtIndex(0,"output").outputTensors)}get losses(){return this._losses}calculateLosses(){return this.losses.map(e=>e())}get updates(){return this._updates}get built(){return this._built}set built(e){this._built=e}get trainable(){return this.trainable_}set trainable(e){this._trainableWeights.forEach(t=>t.trainable=e),this.trainable_=e}get trainableWeights(){return this.trainable_?this._trainableWeights.filter(e=>e.trainable):[]}set trainableWeights(e){this._trainableWeights=e}get nonTrainableWeights(){return this.trainable?this._trainableWeights.filter(e=>!e.trainable).concat(this._nonTrainableWeights):this._trainableWeights.concat(this._nonTrainableWeights)}set nonTrainableWeights(e){this._nonTrainableWeights=e}get weights(){return this.trainableWeights.concat(this.nonTrainableWeights)}get stateful(){return this._stateful}resetStates(){if(!this.stateful)throw new Error("Cannot call the resetStates() method of a non-stateful Layer object.")}assertInputCompatibility(e){if(e=yt(e),this.inputSpec==null||this.inputSpec.length===0)return;let t=yt(this.inputSpec);if(e.length!==t.length)throw new z(`Layer ${this.name} expects ${t.length} inputs, but it received ${e.length} input tensors. Input received: ${e}`);for(let o=0;o<e.length;o++){let n=e[o],s=t[o];if(s==null)continue;let a=n.rank;if(s.ndim!=null&&a!==s.ndim)throw new z(`Input ${o} is incompatible with layer ${this.name}: expected ndim=${s.ndim}, found ndim=${a}`);if(s.maxNDim!=null&&a>s.maxNDim)throw new z(`Input ${o} is incompatible with layer ${this.name}: expected max_ndim=${s.maxNDim}, found ndim=${a}`);if(s.minNDim!=null&&a<s.minNDim)throw new z(`Input ${o} is incompatible with layer ${this.name}: expected min_ndim=${s.minNDim}, found ndim=${a}.`);if(s.dtype!=null&&n.dtype!==s.dtype)throw new z(`Input ${o} is incompatible with layer ${this.name} : expected dtype=${s.dtype}, found dtype=${n.dtype}.`);if(s.axes){let i=n.shape;for(let l in s.axes){let u=Number(l),c=s.axes[l],p=u>=0?i[u]:i[i.length+u];if(c!=null&&[c,null].indexOf(p)===-1)throw new z(`Input ${o} is incompatible with layer ${this.name}: expected axis ${u} of input shape to have value ${c} but got shape ${i}.`)}}if(s.shape!=null)for(let i=0;i<s.shape.length;++i){let l=s.shape[i],u=n.shape[i];if(l!=null&&u!=null&&l!==u)throw new z(`Input ${o} is incompatible with layer ${this.name}: expected shape=${s.shape}, found shape=${n.shape}.`)}}}call(e,t){return e}invokeCallHook(e,t){this._callHook!=null&&this._callHook(e,t)}setCallHook(e){this._callHook=e}clearCallHook(){this._callHook=null}apply(e,t){t=t||{},this.assertNotDisposed();let o=yt(e),n=!0;for(let a of o)if(!(a instanceof Br)){n=!1;break}let s=!0;for(let a of o)if(a instanceof Br){s=!1;break}if(n===s)throw new z("Arguments to apply() must be all SymbolicTensors or all Tensors");return Ms(this.name,()=>{if(!this.built){this.assertInputCompatibility(e);let a=[];for(let i of yt(e))a.push(i.shape);this.build(gr(a)),this.built=!0,this.initialWeights&&this.setWeights(this.initialWeights),this._refCount===null&&s&&(this._refCount=1)}if(this.assertInputCompatibility(e),s){let a=this.call(e,t),i=yt(a),l=[];for(let u of i)o.indexOf(u)!==-1&&(u=u.clone()),l.push(u);if(a=gr(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=LJ(e),i=this.computeOutputShape(a),l,u=zJ(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 Br(u,c,this,yt(e),t,this.name,p)):l=new Br(u,i,this,yt(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 So(`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 So(`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 Mr(`You tried to call countParams() on ${this.name}, but the layer is not built yet. Build it first by calling build(batchInputShape).`);return Pp(this.weights)}build(e){this.built=!0}getWeights(e=!1){return Yf(e?this.trainableWeights:this.weights)}setWeights(e){V(()=>{let t=this.weights;if(t.length!==e.length)throw new z(`You called setWeights(weights) on layer "${this.name}" with a weight list of length ${e.length}, but the layer was expecting ${t.length} weights. Provided weights: ${e}...`);if(t.length===0)return;let o=[],n=Yf(t);for(let s=0;s<n.length;++s){let a=n[s],i=t[s],l=e[s];if(!x.arraysEqual(a.shape,l.shape))throw new z(`Layer weight shape ${a.shape} not compatible with provided weight shape ${l.shape}`);o.push([i,l])}Mp(o)})}addWeight(e,t,o,n,s,a,i){if(this._addedWeightNames.indexOf(e)!==-1)throw new z(`Duplicate weight name ${e} for layer ${this.name}`);this._addedWeightNames.push(e),o==null&&(o="float32"),this.fastWeightInitDuringBuild&&(n=pt("zeros"));let l=n.apply(t,o),u=new Xf(l,o,e,a,i);return l.dispose(),s!=null&&this.addLoss(()=>s.apply(u.read())),a==null&&(a=!0),a?this._trainableWeights.push(u):this._nonTrainableWeights.push(u),u}setFastWeightInitDuringBuild(e){this.fastWeightInitDuringBuild=e}addLoss(e){e==null||Array.isArray(e)&&e.length===0||(e=yt(e),this._losses!==void 0&&this._losses!==null&&this.losses.push(...e))}computeOutputShape(e){return e}computeMask(e,t){if(!this.supportsMasking){if(t!=null)if(Array.isArray(t))t.forEach(o=>{if(o!=null)throw new TypeError(`Layer ${this.name} does not support masking, but was passed an inputMask.`)});else throw new TypeError(`Layer ${this.name} does not support masking, but was passed an inputMask.`);return null}return t}addInboundNode(e,t,o,n,s,a,i=null){let l=yt(e);t=yt(t),o=yt(o),n=yt(n),s=Op(s),a=Op(a);let u=[],c=[],p=[];for(let m of l)u.push(m.sourceLayer),c.push(m.nodeIndex),p.push(m.tensorIndex);new kl({outboundLayer:this,inboundLayers:u,nodeIndices:c,tensorIndices:p,inputTensors:l,outputTensors:t,inputMasks:o,outputMasks:n,inputShapes:s,outputShapes:a},i);for(let m=0;m<t.length;m++)t[m].sourceLayer=this,t[m].nodeIndex=this.inboundNodes.length-1,t[m].tensorIndex=m}getConfig(){let e={name:this.name,trainable:this.trainable};return this.batchInputShape!=null&&(e.batchInputShape=this.batchInputShape),this.dtype!=null&&(e.dtype=this.dtype),e}disposeWeights(){return this.weights.forEach(e=>e.dispose()),this.weights.length}assertNotDisposed(){if(this._refCount===0)throw new Error(`Layer '${this.name}' is already disposed.`)}dispose(){if(!this.built)throw new Error(`Cannot dispose Layer ${this.name} because it has not been built yet.`);if(this._refCount===null)throw new Error(`Cannot dispose Layer ${this.name} because it has not been used yet.`);this.assertNotDisposed();let e=0;return--this._refCount==0&&(e=this.disposeWeights()),{refCountAfterDispose:this._refCount,numDisposedVariables:e}}};function LJ(r){r=yt(r);let e=[];for(let t of r)e.push(t.shape);return gr(e)}function zJ(r){return"float32"}function _C(r,e,t){if((e==null||t!=null&&t>0)&&(e=r.sourceLayer,t=r.nodeIndex),e.inboundNodes.length===0)return[r];{let o=e.inboundNodes[t];if(o.inboundLayers.length===0)return o.inputTensors;{let n=[];for(let s=0;s<o.inboundLayers.length;s++){let a=o.inputTensors[s],i=o.inboundLayers[s],l=o.nodeIndices[s],u=_C(a,i,l);for(let c of u)n.indexOf(c)===-1&&n.push(c)}return n}}}var ji=class extends Me{constructor(e){super({dtype:e.dtype,name:e.name!=null?e.name:wl("input").toString()});if(e.batchSize==null&&(e.batchSize=null),e.sparse==null&&(e.sparse=!1),this.trainable=!1,this.built=!0,this.sparse=e.sparse,e.inputShape!=null&&e.batchInputShape!=null)throw new z("Only provide the inputShape OR batchInputShape argument to inputLayer, not both at the same time.");let t=e.batchInputShape;if(t==null){if(e.inputShape==null)throw new z("An InputLayer should be passed either a `batchInputShape` or an `inputShape`.");t=[e.batchSize].concat(e.inputShape)}else if(e.batchSize!=null)throw new z("Cannot specify batchSize if batchInputShape is specified when creating an InputLayer.");let o=e.dtype||"float32";this.batchInputShape=t,this.dtype=o,this.inputSpec=[{shape:t}];let n=new Br(this.dtype,this.batchInputShape,this,[],{},this.name);n.nodeIndex=0,n.tensorIndex=0,new kl({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:[n],outputTensors:[n],inputMasks:[null],outputMasks:[null],inputShapes:[t],outputShapes:[t]})}apply(e,t){throw new z(`Cannot pass any input to an InputLayer's apply() method. InputLayer name: ${this.name}`)}dispose(){return{refCountAfterDispose:this._refCount,numDisposedVariables:0}}getConfig(){return{batchInputShape:this.batchInputShape,dtype:this.dtype,sparse:this.sparse,name:this.name}}};ji.className="InputLayer";Q.registerClass(ji);function gx(r){if(r.batchShape==null&&r.shape==null)throw new Error("Please provide to Input either a `shape` or a `batchShape` argument. Note that `shape` does not include the batch dimension.");if(r.batchShape!=null&&r.shape!=null)throw new z("Please provide either a `shape` or `batchShape` argument to Input, but not both.");let e=r.batchShape;r.shape!=null&&e==null&&(e=[null].concat(r.shape));let t=r.dtype;return t==null&&(t="float32"),new ji({batchInputShape:e,name:r.name,dtype:t,sparse:r.sparse}).inboundNodes[0].outputTensors[0]}async function Ui(r){if(r==null)return;let e=[],t=[],o=[];for(let n in r){let s=r[n];if(typeof s!="number"){let a=s;e.push(a.data()),t.push(n),o.push(a)}}if(e.length>0){let n=await Promise.all(e);for(let s=0;s<n.length;++s)r[t[s]]=n[s][0];Ae(o)}}function xx(r){if(r!=null)for(let e in r){let t=r[e];typeof t!="number"&&t.dispose()}}var VM;(function(r){r[r.SILENT=0]="SILENT",r[r.VERBOSE=1]="VERBOSE"})(VM||(VM={}));var BJ=125,_l=class{constructor(){this.validationData=null}setParams(e){this.params=e}async onEpochBegin(e,t){}async onEpochEnd(e,t){}async onBatchBegin(e,t){}async onBatchEnd(e,t){}async onTrainBegin(e){}async onTrainEnd(e){}setModel(e){}},yx=class{constructor(e,t=10){e==null&&(e=[]),this.callbacks=e,this.queueLength=t}append(e){this.callbacks.push(e)}setParams(e){for(let t of this.callbacks)t.setParams(e)}setModel(e){for(let t of this.callbacks)t.setModel(e)}async onEpochBegin(e,t){t==null&&(t={});for(let o of this.callbacks)await o.onEpochBegin(e,t)}async onEpochEnd(e,t){t==null&&(t={});for(let o of this.callbacks)await o.onEpochEnd(e,t)}async onBatchBegin(e,t){t==null&&(t={});for(let o of this.callbacks)await o.onBatchBegin(e,t)}async onBatchEnd(e,t){t==null&&(t={});for(let o of this.callbacks)await o.onBatchEnd(e,t)}async onTrainBegin(e){e==null&&(e={});for(let t of this.callbacks)await t.onTrainBegin(e)}async onTrainEnd(e){e==null&&(e={});for(let t of this.callbacks)await t.onTrainEnd(e)}},GM=class extends _l{constructor(){super()}async onEpochBegin(e){this.seen=0,this.totals={}}async onBatchEnd(e,t){t==null&&(t={});let o=t.size==null?0:t.size;this.seen+=o;for(let n in t){let s=t[n];if(typeof s=="number")this.totals.hasOwnProperty(n)||(this.totals[n]=0),this.totals[n]=this.totals[n]+s*o;else{let a;n in this.totals?a=this.totals[n]:this.totals[n]=0;let i=V(()=>ee(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(me(1,this.seen),this.totals[o]);t[o]=n,this.totals[o].dispose(),Et(t[o])}))}},bx=class extends _l{async onTrainBegin(e){this.epoch=[],this.history={}}async onEpochEnd(e,t){t==null&&(t={}),this.epoch.push(e);for(let o in t)this.history[o]==null&&(this.history[o]=[]),this.history[o].push(t[o])}async syncData(){let e=[],t=[],o=[];for(let s in this.history){let a=this.history[s];for(let i=0;i<a.length;++i)if(typeof a[i]!="number"){let l=a[i];e.push(l.data()),t.push(s),o.push(i)}}let n=await Promise.all(e);for(let s=0;s<n.length;++s)this.history[t[s]][o[s]].dispose(),this.history[t[s]][o[s]]=n[s][0]}},wx=class extends _l{constructor(e,t){super();if(this.currentEpoch=0,this.yieldEvery=t||"auto",this.yieldEvery==="auto"&&(this.yieldEvery=BJ),this.yieldEvery==="never"&&e.onYield!=null)throw new Error("yieldEvery is `never` but you provided an `onYield` callback. Either change `yieldEvery` or remove the callback");x.isNumber(this.yieldEvery)&&(this.maybeWait=xM(this.maybeWait.bind(this),this.yieldEvery)),this.trainBegin=e.onTrainBegin,this.trainEnd=e.onTrainEnd,this.epochBegin=e.onEpochBegin,this.epochEnd=e.onEpochEnd,this.batchBegin=e.onBatchBegin,this.batchEnd=e.onBatchEnd,this.yield=e.onYield}async maybeWait(e,t,o){let n=[];this.yield!=null&&(await Ui(o),n.push(this.yield(e,t,o))),n.push(rf()),await Promise.all(n)}async onEpochBegin(e,t){this.currentEpoch=e,this.epochBegin!=null&&(await Ui(t),await this.epochBegin(e,t))}async onEpochEnd(e,t){let o=[];this.epochEnd!=null&&(await Ui(t),o.push(this.epochEnd(e,t))),this.yieldEvery==="epoch"&&o.push(rf()),await Promise.all(o)}async onBatchBegin(e,t){this.batchBegin!=null&&(await Ui(t),await this.batchBegin(e,t))}async onBatchEnd(e,t){let o=[];this.batchEnd!=null&&(await Ui(t),o.push(this.batchEnd(e,t))),this.yieldEvery==="batch"?o.push(rf()):x.isNumber(this.yieldEvery)&&o.push(this.maybeWait(this.currentEpoch,e,t)),await Promise.all(o)}async onTrainBegin(e){this.trainBegin!=null&&(await Ui(e),await this.trainBegin(e))}async onTrainEnd(e){this.trainEnd!=null&&(await Ui(e),await this.trainEnd(e))}};function kx(r,e){return r==null&&(r={}),r instanceof _l?[r]:Array.isArray(r)&&r[0]instanceof _l?r:yt(r).map(o=>new wx(o,e))}var po=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}`),po.checkForDuplicate(t),po.constructors[e]==null&&(po.constructors[e]=[]),po.constructors[e].push(t)}static checkForDuplicate(e){for(let t in po.constructors)po.constructors[+t].forEach(n=>{if(n===e)throw new z("Duplicate callback constructor.")})}static clear(){po.constructors={}}static createCallbacks(e){let t=[];for(let o in po.constructors){let n=+o;e>=n&&t.push(...po.constructors[n])}return t.map(o=>new o)}};po.constructors={};function _x(r,e,t,o,n,s,a,i,l){let u=new bx,c=[new GM,...po.createCallbacks(e)];r!=null&&c.push(...r),c.push(u);let p=new yx(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 Qr(r,e={},t=!1){return Gi(r,Q.SerializationMap.getMap().classNameMap,e,"layer",t)}function Zf(r,e){return V(()=>{r.dtype!=="float32"&&(r=r.asType("float32"));let t=ge(ic(r),e,!0),o=va(t.shape,Zt()),n=gt(Yr(t,o));return me(r,n)})}function Hi(r,e){return V(()=>dt(ic(ce(e,r)),-1))}function Lp(r,e){return V(()=>dt(It(ce(e,r)),-1))}function vl(r,e){return V(()=>{let t=ce(r,e),o=sr(It(r),Zt(),Number.MAX_VALUE),n=It(me(t,o));return O(100,dt(n,-1))})}function VJ(r,e){return V(()=>{let t=sr(e,Zt(),Number.MAX_VALUE),o=ar(ee(1,t)),n=sr(r,Zt(),Number.MAX_VALUE),s=ar(ee(1,n));return dt(ic(ce(o,s)),-1)})}function GJ(r,e){return V(()=>{let t=Yr(0,ce(1,O(r,e)));return dt(ic(t),-1)})}function WJ(r,e){return V(()=>{let t=Yr(0,ce(1,O(r,e)));return dt(t,-1)})}function jJ(r,e){return V(()=>{let t=ge(O(r,e),-1),o=lr(O(ce(1,r),e),-1);return Yr(0,ee(1,ce(o,t)))})}function UJ(r,e){return V(()=>{let t=Math.log(2),o=ce(e,r),n=ce(ee(o,Ts(O(-2,o))),t);return dt(n,-1)})}function lc(r,e,t=!1){return V(()=>{if(t)e=Aa(e);else{let o=ge(e,e.shape.length-1,!0);e=me(e,o)}return e=sr(e,Zt(),1-Zt()),He(ge(O(r.toFloat(),ar(e)),e.shape.length-1))})}function zp(r,e,t=!1){return V(()=>{let o=Ss(DM(r)).toInt();e=sr(e,Zt(),1-Zt());let n=e.shape,s=Cs(o,n[n.length-1]).reshape(n);return lc(s,e,t)})}function HJ(r,e){if(!x.arraysEqual(r.shape,e.shape))throw new z(`logits and labels must have the same shape, but got shapes ${JSON.stringify(r.shape)} and ${JSON.stringify(e.shape)}`);return V(()=>{let t=e.relu(),o=e.abs().neg();return t.sub(e.mul(r)).add(o.exp().log1p())})}function Bp(r,e){return V(()=>{let t;return t=sr(e,Zt(),1-Zt()),t=ar(me(t,ce(1,t))),dt(HJ(r,t),-1)})}function qJ(r,e){return V(()=>{let t=sr(r,Zt(),1),o=sr(e,Zt(),1);return ge(O(r,ar(me(t,o))),-1)})}function KJ(r,e){return V(()=>{let t=ar(ee(Zt(),e));return dt(ce(e,O(r,t)),-1)})}function Jf(r,e){return V(()=>{let t=Zf(r,-1),o=Zf(e,-1),n=O(t,o);return He(ge(n,-1))})}var Qf={meanSquaredError:Hi,meanAbsoluteError:Lp,meanAbsolutePercentageError:vl,meanSquaredLogarithmicError:VJ,squaredHinge:GJ,hinge:WJ,categoricalHinge:jJ,logcosh:UJ,categoricalCrossentropy:lc,sparseCategoricalCrossentropy:zp,binaryCrossentropy:Bp,kullbackLeiblerDivergence:qJ,poisson:KJ,cosineProximity:Jf};function vx(r){if(typeof r=="string"){if(r in Qf)return Qf[r];let e=`Unknown loss ${r}`;throw r.toLowerCase().includes("softmaxcrossentropy")&&(e=`Unknown loss ${r}. Use "categoricalCrossentropy" as the string name for tf.losses.softmaxCrossEntropy`),new z(e)}else return r}function ed(r,e){return V(()=>{let t=O(.5,er(e)),o=Ba(Qt(e,t),r.dtype);return dt(vo(r,o),-1)})}function td(r,e){return V(()=>Ba(vo(il(r,-1),il(e,-1)),"float32"))}function WM(r,e){return V(()=>dr(r.equal(1),e.equal(1)).sum().cast("float32"))}function XJ(r,e){return V(()=>dr(r.equal(1),e.equal(0)).sum().cast("float32"))}function YJ(r,e){return V(()=>dr(r.equal(0),e.equal(1)).sum().cast("float32"))}function vC(r,e){return V(()=>{let t=WM(r,e),o=YJ(r,e),n=t.add(o);return Dt(Qt(n,0),t.div(n),0).cast("float32")})}function jM(r,e){return V(()=>{let t=WM(r,e),o=XJ(r,e),n=t.add(o);return Dt(Qt(n,0),t.div(n),0).cast("float32")})}function Cx(r,e){return Bp(r,e)}function Ix(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)),vo(r,e).asType("float32")}var ZJ=Hi,JJ=Hi,QJ=Lp,e9=Lp,t9=vl,r9=vl,rd=lc,o9=Jf,CC=zp,Nx={binaryAccuracy:ed,categoricalAccuracy:td,precision:vC,categoricalCrossentropy:rd,sparseCategoricalCrossentropy:CC,mse:ZJ,MSE:JJ,mae:QJ,MAE:e9,mape:t9,MAPE:r9,cosine:o9};function UM(r){if(typeof r=="string"&&r in Nx)return Nx[r];if(typeof r!="string"&&r!=null)return r;throw new z(`Unknown metric ${r}`)}function od(r){if(Go(r!==null,`Unknown LossOrMetricFn ${r}`),typeof r=="string")return r;{let e;for(let t of Object.keys(Qf))if(Qf[t]===r){e=t;break}if(e!==void 0)return e;for(let t of Object.keys(Nx))if(Nx[t]===r){e=t;break}return e!==void 0?e:r.name}}function HM(r){let e={Adagrad:()=>cl.adagrad(.01),Adadelta:()=>cl.adadelta(1,.95,Zt()),Adam:()=>cl.adam(.001,.9,.999,Zt()),Adamax:()=>cl.adamax(.002,.9,.999,Zt(),0),RMSProp:()=>cl.rmsprop(.001,.9,0,Zt()),SGD:()=>cl.sgd(.01)};if(e.adagrad=e.Adagrad,e.adadelta=e.Adadelta,e.adam=e.Adam,e.adamax=e.Adamax,e.rmsprop=e.RMSProp,e.sgd=e.SGD,r in e)return e[r]();throw new z(`Unknown Optimizer ${r}`)}var qM=1*1024*1024;function NC(r,e,t=!1){if(r==null||typeof r!="object"||Object.getPrototypeOf(r)!==Object.prototype||!IC(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>qM&&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 <= ${qM}.`)}}function IC(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"||!IC(r[t]))return!1;return!0}else if(Array.isArray(r)){for(let e of r)if(!IC(e))return!1;return!0}else return!1;else{let e=typeof r;return e==="string"||e==="number"||e==="boolean"}}function KM(r,e,t,o=console.log){let n=s9(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)),Sx(s,t,o),o("=".repeat(e));let i=r.layers;for(let c=0;c<i.length;++c)n?i9(i[c],t,o):a9(i[c],t,a,o),o((c===i.length-1?"=":"_").repeat(e));r.checkTrainableWeightsConsistency();let l=n9(r),u=Pp(r.nonTrainableWeights);o(`Total params: ${l+u}`),o(`Trainable params: ${l}`),o(`Non-trainable params: ${u}`),o("_".repeat(e))}function n9(r){let e;return r.collectedTrainableWeights!=null?e=Pp(r.collectedTrainableWeights):e=Pp(r.trainableWeights),e}function s9(r){let e=!0,t=[],o=[];for(let n in r.nodesByDepth)t.push(r.nodesByDepth[n]);for(let n of t){if(n.length>1||n.length===1&&n[0].inboundLayers.length>1){e=!1;break}o.push(...n)}if(e)for(let n of r.layers){let s=!1;for(let a of n.inboundNodes)if(o.indexOf(a)!==-1)if(s){e=!1;break}else s=!0;if(!e)break}return e}function Sx(r,e,t=console.log){let o="";for(let n=0;n<r.length;++n)n>0&&(o=o.slice(0,o.length-1)+" "),o+=r[n],o=o.slice(0,e[n]),o+=" ".repeat(e[n]-o.length);t(o)}function i9(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()];Sx(a,e,t)}function a9(r,e,t,o){let n;try{n=JSON.stringify(r.outputShape)}catch(c){n="multiple"}let s=[];for(let c of r.inboundNodes)if(!(t!=null&&t.length>0&&t.indexOf(c)===-1))for(let p=0;p<c.inboundLayers.length;++p){let m=c.inboundLayers[p].name,f=c.nodeIndices[p],d=c.tensorIndices[p];s.push(`${m}[${f}][${d}]`)}let a=r.name,i=r.getClassName(),l=s.length===0?"":s[0],u=[`${a} (${i})`,n,r.countParams().toString(),l];Sx(u,e,o);for(let c=1;c<s.length;++c)Sx(["","","",s[c]],e,o)}function XM(r,e,t){return(r==="inboundNodes"||r==="outputLayers"||r==="inputLayers")&&e===0&&typeof t=="string"}function uc(r,e){if(r===null)return null;if(typeof r=="string")return za(r);if(typeof r=="number"||typeof r=="boolean")return r;if(r instanceof Array){let t=[],o=r.length;for(let n=0;n<o;++n){let s=r[n];XM(e,n,s)?t.push(s):t.push(uc(s,e))}return t}else{let t={};for(let o of Object.keys(r)){let n=r[o];if(o==="name"&&typeof n=="string")t[o]=n;else{let s=za(o);t[s]=uc(n,s)}}return t}}function Tx(r,e){if(r==null)return null;if(typeof r=="string")return Jn(r);if(typeof r=="number"||typeof r=="boolean")return r;if(r instanceof Array){let t=[],o=r.length;for(let n=0;n<o;++n){let s=r[n];XM(e,n,s)?t.push(s):t.push(Tx(s,e))}return t}else{let t={};for(let o of Object.keys(r)){let n=r[o],s=Jn(o);(o==="name"||o==="className")&&typeof n=="string"?t[s]=n:t[s]=Tx(n,o)}return t}}var Vp="3.3.0";function l9(r,e){if(r.dtype==null||r.dtype===e.dtype)return e;try{return ne(e,r.dtype)}catch(t){throw new z(`The dtype of the feed (${e.dtype}) can not be cast to the dtype of the key '${r.name}' (${r.dtype}).`)}}var zs=class{constructor(e){if(this.id2Value={},this.id2Mask={},this.name2Id={},e instanceof zs)for(let t in e.id2Value)this.id2Value[t]=e.id2Value[t],t in e.id2Mask&&(this.id2Mask[t]=e.id2Mask[t]);else{if(e==null)return;for(let t of e)this.add(t.key,t.value)}}add(e,t,o){if(this.id2Value[e.id]==null)this.id2Value[e.id]=l9(e,t),this.name2Id[e.name]=e.id,o!=null&&(this.id2Mask[e.id]=o);else throw new z(`Duplicate key: name=${e.name}, id=${e.id}`);return this}addFeed(e){this.add(e.key,e.value)}hasKey(e){return this.id2Value[e.id]!=null}names(){return Object.keys(this.name2Id)}getValue(e){if(e instanceof Br){if(this.id2Value[e.id]==null)throw new z(`Nonexistent key: ${e.name}`);return this.id2Value[e.id]}else{let t=this.name2Id[e];if(t==null)throw new z(`Feed dict has no SymbolicTensor name: ${e}`);return this.id2Value[t]}}getMask(e){if(e instanceof Br){if(this.id2Value[e.id]==null)throw new z(`Nonexistent key: ${e.name}`);return this.id2Mask[e.id]}else{let t=this.name2Id[e];if(t==null)throw new z(`Feed dict has no SymbolicTensor name: ${e}`);return this.id2Mask[t]}}disposeMasks(){this.id2Mask!=null&&Ae(this.id2Mask)}},SC={},YM={};function cc(r,e,t,o){let n=t==null?!1:t.training,s=Array.isArray(r),a=s?r:[r],i=a.map(d=>d.name),l=[],u=e.names();for(let d of i)u.indexOf(d)!==-1?l.push(e.getValue(d)):l.push(null);o!=null&&(o.maxNumTensors=-Infinity,o.minNumTensors=Infinity);let c=i.join(",")+"|"+e.names().join(","),p,m;if(SC[c]==null){let d=u9(a,e);p=d.sorted,m=d.recipientCounts,SC[c]=p,YM[c]=m}p=SC[c],m={},n||Object.assign(m,YM[c]);let f=new zs(e);for(let d=0;d<p.length;++d){if(o!=null){let P=Uc().numTensors;P>o.maxNumTensors&&(o.maxNumTensors=P),P<o.minNumTensors&&(o.minNumTensors=P)}let h=p[d],g=h.sourceLayer;if(g instanceof ji)continue;let y=[],b=[],w=[],k=!1;for(let P of h.inputs){let L=f.getValue(P),G=f.getMask(P);y.push(L),b.push(G),G!=null&&(k=!0),n||(m[P.name]--,m[P.name]===0&&!e.hasKey(P)&&i.indexOf(P.name)===-1&&!L.isDisposed&&P.sourceLayer.stateful!==!0&&w.push(L))}k&&(t=t||{},t.mask=b[0]);let v=yt(g.apply(y,t)),D=null;g.supportsMasking&&(D=g.computeMask(y,b));let A=c9(h),R=Array.isArray(A)?A:[A];for(let P=0;P<R.length;++P){f.hasKey(R[P])||f.add(R[P],v[P],Array.isArray(D)?D[0]:D);let L=i.indexOf(R[P].name);L!==-1&&(l[L]=v[P])}n||Ae(w)}return f.disposeMasks(),s?l:l[0]}function u9(r,e){x.assert(r!=null&&r.length>0,()=>"Expected at least one fetch, got none");let t=[],o={};if(r.length===1){let n=ZM(r[0],e);t=n.sorted,o=n.recipientMap}else{let n=new Set;for(let s of r){let{sorted:a,recipientMap:i}=ZM(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:p9(o)}}function p9(r){let e={};for(let t in r)e[t]=r[t].size;return e}function ZM(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 c9(r){let e;if(r.sourceLayer.inboundNodes.length===1)e=r.sourceLayer.output;else{let t=null;for(let o=0;o<r.sourceLayer.inboundNodes.length;++o)for(let n of r.sourceLayer.inboundNodes[o].outputTensors)if(n.id===r.id){t=o;break}e=r.sourceLayer.getOutputAt(t)}return e}var Wo=class extends Me{constructor(e){super({});if(this.containerNodes=new Set,this.name=e.name,this.name==null){let b=this.getClassName().toLowerCase();this.name=wl(b)}if(this.supportsMasking=!1,this.trainable_=!0,Array.isArray(e.inputs)?this.inputs=e.inputs.slice():this.inputs=[e.inputs],Array.isArray(e.outputs)?this.outputs=e.outputs.slice():this.outputs=[e.outputs],es(this.inputs).length!==this.inputs.length)throw new z(`The list of inputs passed to the model is redundant. All inputs should only appear once. Found: ${this.inputs.map(b=>b.name)}`);es(this.outputs).length!==this.outputs.length&&console.warn(`The list of outputs passed to the model is redundant. All outputs should only appear once. Found: ${this.outputs.map(b=>b.name)}`),this.inputLayers=[],this.inputLayersNodeIndices=[],this.inputLayersTensorIndices=[],this.outputLayers=[],this.outputLayersNodeIndices=[],this.outputLayersTensorIndices=[],this.layers=[],this.internalContainerRefs=[];for(let b of this.outputs){let w=b.sourceLayer,k=b.nodeIndex,v=b.tensorIndex;this.outputLayers.push(w),this.outputLayersNodeIndices.push(k),this.outputLayersTensorIndices.push(v)}for(let b of this.inputs){let w=b.sourceLayer,k=b.nodeIndex,v=b.tensorIndex;Go(k===0,"input layer has >1 nodes"),Go(v===0,"input layer has >1 tensors"),this.inputLayers.push(w),this.inputLayersNodeIndices.push(k),this.inputLayersTensorIndices.push(v)}this.inputNames=[],this.outputNames=[],this.feedInputShapes=[],this.feedInputNames=[],this.feedOutputNames=[];for(let b=0;b<this.inputLayers.length;b++){let w=this.inputLayers[b];if(!(w instanceof ji))throw new TypeError(`Input layers to a LayersModel must be InputLayer objects. Received inputs: ${e.inputs}. Input ${b} (0-based) originates from layer type ${w.getClassName()}.`);this.inputNames.push(w.name),this.feedInputShapes.push(w.batchInputShape),this.feedInputNames.push(w.name)}for(let b of this.outputLayers)this.outputNames.push(b.name);this.internalInputShapes=this.inputs.map(b=>b.shape),this.internalOutputShapes=this.outputs.map(b=>b.shape);let t={},o={},n={},s={},a={},i=[],l=(b,w,k,v,D,A)=>{(v==null||D==null||A==null)&&(v=b.sourceLayer,D=b.nodeIndex,A=b.tensorIndex);let R=v.inboundNodes[D];if(k.indexOf(R)!==-1)throw new Mr(`The tensor ${b.name} at layer "${v.name}" is part of a cycle.`);if(w.indexOf(R)!==-1)return;this.containerNodes.add(Wo.nodeKey(v,D)),v.id in a||(a[v.id]=Object.keys(a).length),k.indexOf(R)===-1&&k.push(R);let P=R.inboundLayers.length;for(let L=0;L<P;L++){let G=R.inputTensors[L],j=R.inboundLayers[L],U=R.nodeIndices[L],H=R.tensorIndices[L];l(G,w,k,j,U,H)}for(w.push(R);k.indexOf(R)>=0;)k.splice(k.indexOf(R),1);i.push(R)},u=[],c=[];for(let b of this.outputs)l(b,u,c);let p=i.slice().reverse();for(let b of p){o[b.id]=b,b.id in t||(t[b.id]=0);let w=t[b.id],k=n[b.outboundLayer.id]==null?0:n[b.outboundLayer.id];w=Math.max(w,k),n[b.outboundLayer.id]=w,s[b.outboundLayer.id]=b.outboundLayer,t[b.id]=w;for(let v=0;v<b.inboundLayers.length;v++){let D=b.inboundLayers[v],A=b.nodeIndices[v],R=D.inboundNodes[A],P=t[R.id]==null?0:t[R.id];t[R.id]=Math.max(w+1,P),o[R.id]=R}}let m={};for(let b in t){let w=t[b];w in m||(m[w]=[]),m[w].push(o[b])}let f={};for(let b in n){let w=n[b];w in f||(f[w]=[]),f[w].push(s[b])}let d=Object.keys(f).map(b=>parseInt(b,10)).sort(Of);this.layers=[];for(let b of d){let w=f[b];w.sort((k,v)=>{let D=a[k.id],A=a[v.id];return D<A?-1:D>A?1:0});for(let k of w)k instanceof Wo&&this.internalContainerRefs.push(k),this.layers.push(k)}this.layersByDepth=f,d=Object.keys(m).map(b=>parseInt(b,10)).sort(Of);let h=this.inputs.slice(),g=[];for(let b of d)for(let w of m[b]){let k=w.outboundLayer;if(k!=null){for(let v of w.inputTensors)if(h.indexOf(v)===-1)throw new Mr(`Graph disconnected: cannot obtain value for tensor ${v} at layer "${k.name}". The following previous layers were accessed without issue: ${g}`);for(let v of w.outputTensors)h.push(v);g.push(k.name)}}this.nodesByDepth=m;let y=this.layers.map(b=>b.name);for(let b of y){let w=y.filter(k=>k===b).length;if(w!==1)throw new Mr(`The name "${b}" is used ${w} times in the model. All layer names should be unique. Layer names: `+JSON.stringify(y))}this.outboundNodes=[],this.inboundNodes=[],new kl({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 z("Container instance unexpectedly contains _trainableWeights.The trainable weights of a Container are a union of the trainable weights of its consituent Layers. Its own _trainableWeights must remain an empty Array.");if(!this.trainable)return[];let e=[];for(let t of this.layers)e=e.concat(t.trainableWeights);return e}get nonTrainableWeights(){let e=[];for(let t of this.layers)e.push(...t.nonTrainableWeights);if(!this.trainable){let t=[];for(let 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 z(`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 z(`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 z(`${a.length} of ${n} weights are not set: ${a}`)}Mp(s)}updatedConfig(){let e=this.getConfig(),t={};return t.className=this.getClassName(),t.config=e,t.kerasVersion=`tfjs-layers ${Vp}`,t.backend="TensorFlow.js",t}toJSON(e,t=!0){let o=Tx(this.updatedConfig());return t?JSON.stringify(o):o}call(e,t){return V(()=>{e=yt(e);let o=new zs;for(let n=0;n<this.inputs.length;++n)o.add(this.inputs[n],e[n]);return cc(this.outputs,o,t)})}computeMask(e,t){return V(()=>{e=yt(e);let o;return t==null?o=Zn(null,e.length):o=yt(t),this.runInternalGraph(e,o)[1]})}computeOutputShape(e){let t=Op(e);if(t.length!==this.inputLayers.length)throw new z(`Invalid inputShape argument ${e}: model has ${this.inputLayers.length} tensor inputs.`);let o={};for(let i=0;i<t.length;i++){let l=this.inputLayers[i],u=t[i],c=l.name+"_0_0";o[c]=u}let n=Object.keys(this.nodesByDepth).map(i=>parseInt(i,10)).sort(Of);if(n.length>1)for(let i of n){let l=this.nodesByDepth[i];for(let u of l){let c=u.outboundLayer;if(this.inputLayers.map(h=>h.id).indexOf(c.id)!==-1)continue;let p=[];for(let h=0;h<u.inboundLayers.length;h++){let g=u.inboundLayers[h],y=u.nodeIndices[h],b=u.tensorIndices[h],w=`${g.name}_${y}_${b}`,k=o[w];p.push(k)}let m=c.computeOutputShape(gr(p)),f=Op(m),d=c.inboundNodes.indexOf(u);for(let h=0;h<f.length;h++){let g=`${c.name}_${d}_${h}`;o[g]=f[h]}}}let s=[],a=[];for(let i=0;i<this.outputLayers.length;i++){let l=this.outputLayers[i],u=this.outputLayersNodeIndices[i],c=this.outputLayersTensorIndices[i],p=`${l.name}_${u}_${c}`;a.push(p)}for(let i=0;i<a.length;i++){let l=a[i];Go(l in o),s.push(o[l])}return gr(s)}runInternalGraph(e,t){t==null&&(t=Zn(null,e.length));let o={};for(let l=0;l<this.inputs.length;++l){let u=this.inputs[l],c=e[l],p=t[l];o[u.id]=[c,p]}let n=Object.keys(this.nodesByDepth).map(l=>parseInt(l,10)).sort(Of);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,w;if(c.callArgs!=null&&(h=c.callArgs),d.length===1){let[k,v]=d[0];h.mask==null&&(h.mask=v),b=yt(p.call(k,h)),w=yt(p.computeMask(k,v)),g=[k],y=[v]}else g=d.map(k=>k[0]),y=d.map(k=>k[1]),h.mask==null&&(h.mask=y),b=yt(p.call(g,h)),w=yt(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 k=0;k<f.length;++k){let v=f[k],D=b[k],A=w[k];o[v.id]=[D,A]}}}}let s=[],a=[],i=[];for(let l of this.outputs){Go(l.id in o,`Could not compute output ${l.name} : ${l.id}`);let[u,c]=o[l.id];i.push(u.shape),s.push(u),a.push(c)}return[s,a,i]}buildNodeConversionMap(e){let t={},o;for(let n of this.layers){o=n instanceof Wo?1:0;for(let s=0;s<n.inboundNodes.length;s++){let a=Wo.nodeKey(n,s);this.containerNodes.has(a)&&(t[a]=o,o+=1)}}return t}getLayer(e,t){if(t!=null){if(this.layers.length<=t)throw new z(`Was asked to retrieve layer at index ${t}, but model only has ${this.layers.length} layer(s).`);return this.layers[t]}else if(e==null)throw new z("Provide either a layer name or layer index");for(let o of this.layers)if(o.name===e)return o;throw new z(`No such layer: ${e}`)}calculateLosses(){return V(()=>{let e=[];for(let t of this.layers)for(let o=0;o<t.inboundNodes.length;++o){let n=Wo.nodeKey(t,o);this.containerNodes.has(n)&&e.push(...t.calculateLosses())}return e})}getConfig(){let e={name:this.name},t=this.buildNodeConversionMap(this.layers),o=[];for(let a of this.layers){let i=a.getClassName(),l=a.getConfig(),u=[];for(let p=0;p<a.inboundNodes.length;p++){let m=a.inboundNodes[p],f=Wo.nodeKey(a,p),d={};if(this.containerNodes.has(f)){if(m.callArgs)try{JSON.stringify(m.callArgs),d=m.callArgs}catch(h){console.warn(`Layer ${a.name} was passed non-serializable keyword arguments: ${m.callArgs}. They will not be included in the serialized model (and thus will be missing at deserialization time).`),d={}}if(m.inboundLayers.length>0){let h=[];for(let g=0;g<m.inboundLayers.length;g++){let y=m.inboundLayers[g],b=m.nodeIndices[g],w=m.tensorIndices[g],k=Wo.nodeKey(y,b),v=t[k];v==null&&(v=0),h.push([y.name,v,w,d])}u.push(h)}}}let c={};c.name=a.name,c.className=i,c.config=l,c.inboundNodes=u,o.push(c)}e.layers=o;let n=[];for(let a=0;a<this.inputLayers.length;a++){let i=this.inputLayers[a],l=this.inputLayersNodeIndices[a],u=Wo.nodeKey(i,l);if(!this.containerNodes.has(u))continue;let c=t[u];c==null&&(c=0);let p=this.inputLayersTensorIndices[a];n.push([i.name,c,p])}e.inputLayers=n;let s=[];for(let a=0;a<this.outputLayers.length;a++){let i=this.outputLayers[a],l=this.outputLayersNodeIndices[a],u=Wo.nodeKey(i,l);if(!this.containerNodes.has(u))continue;let c=t[u];c==null&&(c=0);let p=this.outputLayersTensorIndices[a];s.push([i.name,c,p])}return e.outputLayers=s,e}static fromConfig(e,t,o={},n=!1){let s={},a={};function i(g,y){g.name in a?a[g.name].push(y):a[g.name]=[y]}function l(g,y){let b=[],w;for(let k of y){let v=k[0],D=k[1],A=k[2];if(w=k[3]==null?{}:k[3],!(v in s)){i(g,y);return}let R=s[v];if(R.inboundNodes.length<=D){i(g,y);return}let P=R.inboundNodes[D];b.push(P.outputTensors[A])}b.length>0&&g.apply(gr(b),w)}function u(g){let y=g.name,b=Qr(g,t.customObjects!=null?t.customObjects:{});b.setFastWeightInitDuringBuild(n),s[y]=b,g.inboundNodes.forEach(k=>{if(!(k instanceof Array))throw new z(`Corrupted configuration, expected array for nodeData: ${k}`);i(b,k)})}let c=t.name,p=t.layers;for(let g of p)u(g);for(;!hM(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 w of b)l(y,w)}}let m=[],f=[],d=t.inputLayers;for(let g of d){let y=g[0],b=g[1],w=g[2];Go(y in s);let v=s[y].inboundNodes[b].outputTensors;m.push(v[w])}let h=t.outputLayers;for(let g of h){let y=g[0],b=g[1],w=g[2];Go(y in s);let v=s[y].inboundNodes[b].outputTensors;f.push(v[w])}return new e({inputs:m,outputs:f,name:c})}get stateful(){if(this._stateful)throw new z("Container instance unexpectedly has _stateful = true. The statefulness of a Container is determined by the Layers it contains. Its _stateful property must remain the default false.");for(let e of this.layers)if(e.stateful)return!0;return!1}resetStates(){V(()=>{this.layers.forEach(e=>{e.stateful&&e.resetStates()})})}};function m9(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 Ax(r,e){return m9(r,e,"classWeight")}async function Ex(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])}),Vt(a,"float32")}else return null}function JM(r,e){return O(r,e)}var f9=32;function eL(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=QM("input",r.inputNames,t),a=QM("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<s.length;l++)x.assert(s[l].shape[0]===i,()=>`Batch size mismatch: input ${r.inputNames[l]} has ${s[l].shape[0]}; expected ${i} based on input ${r.inputNames[0]}.`);for(let l=0;l<a.length;l++)x.assert(a[l].shape[0]===i,()=>`Batch size mismatch: output ${r.outputNames[l]} has ${a[l].shape[0]}; expected ${i} based on input ${r.inputNames[0]}.`);return{xs:s,ys:a}}function QM(r,e,t){if(t instanceof Ve)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 z(`The feature data generated by the dataset lacks the required ${r} key '${n}'.`);o.push(t[n])}return o}}function d9(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 rL(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(tL(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=d9(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=kx(t.callbacks,t.yieldEvery),p=t.verbose==null?1:t.verbose,{callbackList:m,history:f}=_x(c,p,t.epochs,null,null,h9(e,t),null,n,u);m.setModel(r),r.history=f,await m.onTrainBegin(),r.stopTraining_=!1;let d=t.initialEpoch==null?0:t.initialEpoch,h=await e.iterator();for(;d<t.epochs;){let g={};await m.onEpochBegin(d);let y=0,b=0;for(o||(h=await e.iterator());o?y<t.batchesPerEpoch:!0;){let w=await h.next();if(o&&w.done){console.warn(`You provided \`batchesPerEpoch\` as ${t.batchesPerEpoch}, but your dataset iterator ran out of data after ${y} batches; interrupting training. Make sure that your dataset can generate at least \`batchesPerEpoch * epochs\` batches (in this case, ${t.batchesPerEpoch*t.epochs} batches). You may need to use the repeat() function when building your dataset.`);break}if(w.value!=null){let{xs:k,ys:v}=eL(r,w.value),D={};D.batch=b,D.size=k[0].shape[0],await m.onBatchBegin(b,D);let A=[];if(t.classWeight!=null){let L=Ax(t.classWeight,r.outputNames);for(let G=0;G<L.length;++G)A.push(await Ex(v[G],null,L[G]))}let R=k.concat(v).concat(A),P=i(R);Ae(R);for(let L=0;L<l.length;++L){let G=l[L],j=P[L];D[G]=j,Et(j)}await m.onBatchEnd(b,D),xx(D),b++,y++}if(o?y>=t.batchesPerEpoch:w.done){if(n){let k;tL(t.validationData)?k=yt(await r.evaluateDataset(t.validationData,{batches:t.validationBatches})):k=yt(r.evaluate(s,a,{batchSize:t.validationBatchSize==null?f9:t.validationBatchSize,verbose:0}));for(let v=0;v<r.metricsNames.length;++v)g[`val_${r.metricsNames[v]}`]=k[v]}break}if(r.stopTraining_)break}if(await m.onEpochEnd(d,g),d++,r.stopTraining_)break}return await m.onTrainEnd(),await r.history.syncData(),r.history}finally{r.isTraining=!1}}function h9(r,e){let t=null;return e.batchesPerEpoch!=null?t=e.batchesPerEpoch:Number.isFinite(r.size)&&(t=r.size),t}function tL(r){return typeof r.iterator=="function"}function g9(r){return typeof r.next=="function"}async function oL(r,e,t){t=t||{};let o=t.batches!=null,n=r.testFunction,s=[];if(t.verbose>0)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=g9(e)?e:await e.iterator(),i=0,l=0;for(;o?l<t.batches:!0;){let u=await a.next();if(s=V(()=>{if(u.value){let{xs:c,ys:p}=eL(r,u.value),m=c.concat(p),f=V(()=>n(m));if(Ae(m),l===0)for(let h=0;h<f.length;++h)s.push(le(0));let d=m[0].shape[0];for(let h=0;h<f.length;++h){let g=f[h],y=s[h];s[h]=V(()=>ee(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;u<s.length;++u){let c=s[u];s[u]=me(s[u],i),Ae(c)}return gr(s)}function Dx(r){x.assert(r>0&&Number.isInteger(r),()=>`batchSize is required to be a positive integer, but got ${r}`)}function Gp(r,e,t){return r==null?[null]:Array.isArray(r)?r.map(o=>Ga(o,e,t-e)):Ga(r,e,t-e)}function $x(r,e){return V(()=>r==null?null:Array.isArray(r)?r.map(t=>$x(t,e)):px(r,e.dtype==="int32"?e:e.toInt()))}function Rx(r,e){let t=[],o=0,n=null;for(;o<r;)n=o+e,n>=r&&(n=r),t.push([o,n]),o=n;return t}async function x9(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 z("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=Lr(0,g)),a==null&&(a=1);let{callbackList:b,history:w}=_x(i,a,s,m,g,f,n,h,p);b.setModel(r),r.history=w,await b.onTrainBegin(),r.stopTraining_=!1;for(let k=m;k<s;++k){await b.onEpochBegin(k);let v={};if(f!=null)throw new Se("stepsPerEpoch mode is not implemented yet.");{if(c==="batch")throw new Se("batch shuffling is not implemneted yet");c&&x.shuffle(y);let D=Vt(y),A=Rx(g,n);for(let R=0;R<A.length;++R){let P={};if(await b.onBatchBegin(R,P),V(()=>{let L=A[R][0],G=A[R][1],j=Ga(D,L,G-L);P.batch=R,P.size=G-L;let U=$x(t,j),H=e(U);for(let q=0;q<o.length;++q){let X=o[q],oe=H[q];P[X]=oe,Et(oe)}if(R===A.length-1&&h){let q=r.testLoop(l,u,n);for(let X=0;X<o.length;++X){let oe=o[X],Y=q[X];Et(Y),v["val_"+oe]=Y}}}),await b.onBatchEnd(R,P),xx(P),r.stopTraining_)break}D.dispose()}if(await b.onEpochEnd(k,v),r.stopTraining_)break}return await b.onTrainEnd(),await r.history.syncData(),r.history}async function nL(r,e,t,o={}){if(r.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");r.isTraining=!0;let n,s,a,i,l,u,c;try{let p=o.batchSize==null?32:o.batchSize;Dx(p);let m=!1,f=await r.standardizeUserData(e,t,o.sampleWeight,o.classWeight,m,p);n=f[0],s=f[1],c=f[2];let d=!1,h;if(o.validationData!=null&&o.validationData.length>0){if(d=!0,o.validationData.length===2)a=o.validationData[0],i=o.validationData[1];else throw o.validationData.length===3?new Se("validationData including sample weights is not supported yet."):new z(`When passing validation data, it must contain 2 (valX, valY) or 3 (valX, valY, valSampleWeight) items; ${o.validationData} is invalid.`);let A=!0,R=await r.standardizeUserData(a,i,null,null,A,p);l=R[0],u=R[1],h=l.concat(u)}else if(o.validationSplit!=null&&o.validationSplit>0&&o.validationSplit<1){d=!0;let A=Math.floor(n[0].shape[0]*(1-o.validationSplit)),R=n[0].shape[0];l=Gp(n,A,R),n=Gp(n,0,A),u=Gp(s,A,R),s=Gp(s,0,A),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,k;d?(r.makeTestFunction(),w=r.testFunction,k=b.slice().concat(b.map(A=>"val_"+A))):(w=null,h=[],k=b.slice());let v=kx(o.callbacks,o.yieldEvery);return await x9(r,y,g,b,p,o.epochs,o.verbose,v,w,h,o.shuffle,k,o.initialEpoch,null,null)}finally{r.isTraining=!1,Cl(n,e),Cl(s,t),Cl(l,a),Cl(u,i),c!=null&&Ae(c)}}function TC(r){let e=[];r instanceof Ve&&(r=[r]);for(let t=0;t<r.length;++t){let o=r[t];if(o.rank===1)e.push(Va(o,1));else{if(o.rank===0)throw new Error("Expected tensor to be at least 1D, but received a 0D tensor (scalar).");e.push(o)}}return e}function Cl(r,e){if(r==null)return;let t=[];if(e instanceof Ve)t.push(e.id);else if(Array.isArray(e))e.forEach(n=>t.push(n.id));else if(e!=null)for(let n in e){let s=e[n];t.push(s.id)}let o=[];if(r instanceof Ve)t.indexOf(r.id)===-1&&o.push(r);else if(Array.isArray(r))r.forEach(n=>{t.indexOf(n.id)===-1&&o.push(n)});else if(r!=null)for(let n in r){let s=r[n];t.indexOf(s.id)===-1&&o.push(s)}o.forEach(n=>{n.isDisposed||n.dispose()})}function y9(r){return r instanceof Ve}function AC(r){return Array.isArray(r)}function sL(r){return!y9(r)&&!AC(r)}function iL(r,e,t,o=!0,n=""){if(e==null||e.length===0){if(r!=null){let a=!1;if(AC(r)&&r.length>0)a=!0;else if(sL(r)){for(let i in r)if(r.hasOwnProperty(i)){a=!0;break}}else a=!0;if(a)throw new z(`Error when checking model ${n} expected no data, but got ${r}`)}return[]}if(r==null)return e.map(a=>null);let s;if(sL(r)){r=r,s=[];for(let a of e){if(r[a]==null)throw new z(`No data provided for "${a}". Need data for each key in: ${e}`);s.push(r[a])}}else if(AC(r)){if(r=r,r.length!==e.length)throw new z(`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 z(`The model ${n} expects ${e.length} Tensor(s), but only received one Tensor. Found: Tensor with shape ${r.shape}`);s=[r]}if(s=TC(s),t!=null)for(let a=0;a<e.length;++a){if(t[a]==null)continue;let i=s[a];if(i.shape.length!==t[a].length)throw new z(`Error when checking ${n}: expected ${e[a]} to have ${t[a].length} dimension(s). but got array with shape ${i.shape}`);for(let l=0;l<t[a].length;++l){if(l===0&&!o)continue;let u=i.shape[l],c=t[a][l];if(c!=null&&c>=0&&u!==c)throw new z(`Error when checking ${n}: expected ${e[a]} to have shape [${t[a]}], but got array with shape [${i.shape}].`)}}return s}function b9(r,e,t){let o=es(r.map(s=>s.shape[0]));o.sort();let n=es(e.map(s=>s.shape[0]));if(n.sort(),o.length>1)throw new z(`All input Tensors (x) should have the same number of samples. Got array shapes: ${JSON.stringify(r.map(s=>s.shape))}`);if(n.length>1)throw new z(`All target Tensors (y) should have the same number of samples. Got array shapes: ${JSON.stringify(e.map(s=>s.shape))}`);if(o.length>0&&n.length>0&&!x.arraysEqual(o,n))throw new z(`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 w9(r,e,t){let o=[Hi,Bp,lc];for(let n=0;n<r.length;++n){let s=r[n],a=e[n],i=t[n];if(a!=null){if(a===lc&&s.shape[s.shape.length-1]===1)throw new z(`You are passing a target array of shape ${s.shape} while using a loss 'categorical_crossentropy'. 'categorical_crossentropy'expects targets to be binary matrices (1s and 0s) of shape [samples, classes].`);if(o.indexOf(a)!==-1){let l=s.shape.slice(1),u=i.slice(1);for(let c=0;c<l.length;++c){let p=l[c],m=u[c];if(m!=null&&p!==m)throw new z(`A target Tensor with shape ${s.shape} was passed for an output of shape ${i}, while using a loss function that expects targets to have the same shape as the output.`)}}}}}function aL(r,e,t,o=!0,n=""){let s;if(Array.isArray(r)){if(r.length!==e.length)throw new z(`Error when checking model ${n}: the Array of Tensors that you are passing to your model is not the size the the model expected. Expected to see ${e.length} Tensor(s), but instead got ${r.length} Tensors(s).`);s=r}else{if(e.length>1)throw new z(`The model expects ${e.length} ${n} Tensors, but only received one Tensor. Found: array with shape ${JSON.stringify(r.shape)}.`);s=[r]}if(t!=null)for(let a=0;a<e.length;++a){if(t[a]==null)continue;let i=s[a];if(i.shape.length!==t[a].length)throw new z(`Error when checking ${n}: expected ${e[a]} to have ${t[a].length} dimension(s), but got array with shape ${JSON.stringify(i.shape)}`);for(let l=0;l<t[a].length;++l){if(l===0&&!o)continue;let u=i.shape[l],c=t[a][l];if(c!=null&&c!==u)throw new z(`Error when checking ${n}: expected ${e[a]} to have shape ${JSON.stringify(t[a])} but got array with shape ${JSON.stringify(i.shape)}.`)}}}function k9(r,e){if(r==null||Array.isArray(r)&&r.length===0)return e.map(o=>[]);let t;if(typeof r=="string"||typeof r=="function")t=[r];else if(Array.isArray(r)||typeof r=="object")t=r;else throw new TypeError(`Type of metrics argument not understood. Expected an string,function, Array, or Object, found: ${r}`);if(Array.isArray(t))return e.map(o=>t);{let o=[];for(let n of e){let s=t.hasOwnProperty(n)?t[n]:[];Array.isArray(s)||(s=[s]),o.push(s)}return o}}var _9="layers-model",To=class extends Wo{constructor(e){super(e);this.isTraining=!1}summary(e,t,o=console.log){if(!this.built)throw new z("This model has never been called, thus its weights have not been created yet. So no summary can be displayed. Build the model first (e.g., by calling it on some test data).");KM(this,e,t,o)}compile(e){if(e.loss==null&&(e.loss=[]),this.loss=e.loss,typeof e.optimizer=="string")this.optimizer_=HM(e.optimizer),this.isOptimizerOwned=!0;else{if(!(e.optimizer instanceof Or))throw new z("User-defined optimizer must be an instance of tf.Optimizer.");this.optimizer_=e.optimizer,this.isOptimizerOwned=!1}let t=[];if(!Array.isArray(e.loss)&&typeof e.loss!="string"&&typeof e.loss!="function"){e.loss=e.loss;for(let a in e.loss)if(this.outputNames.indexOf(a)===-1)throw new z(`Unknown entry in loss dictionary: "${a}". Only expected the following keys: ${this.outputNames}`);for(let a of this.outputNames)e.loss[a]==null&&console.warn(`Output "${a}" is missing from loss dictionary. We assume this was done on purpose, and we will not be expecting data to be passed to ${a} during training`),t.push(vx(e.loss[a]))}else if(Array.isArray(e.loss)){if(e.loss.length!==this.outputs.length)throw new z(`When passing an Array as loss, it should have one entry per model output. The model has ${this.outputs.length} output(s), but you passed loss=${e.loss}.`);t=e.loss.map(i=>vx(i))}else{let a=vx(e.loss);this.outputs.forEach(i=>{t.push(a)})}this.lossFunctions=t,this.feedOutputNames=[],this.feedOutputShapes=[],this.feedLossFns=[];for(let a=0;a<this.outputs.length;++a){let i=this.internalOutputShapes[a],l=this.outputNames[a];this.feedOutputNames.push(l),this.feedOutputShapes.push(i),this.feedLossFns.push(this.lossFunctions[a])}let o=[];this.metrics=e.metrics,this.metricsNames=["loss"],this.metricsTensors=[],Ms("loss",()=>{for(let a=0;a<this.outputs.length;++a){if(o.indexOf(a)!==-1)continue;let i=this.lossFunctions[a];this.outputs.length>1&&(this.metricsTensors.push([i,a]),this.metricsNames.push(this.outputNames[a]+"_loss"))}});let n=k9(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])};Ms("metric",()=>{for(let a=0;a<this.outputs.length;++a){if(o.indexOf(a)!==-1)continue;let i=n[a];(u=>{let c="",p,m,f;for(let d of u){if(typeof d=="string"&&["accuracy","acc","crossentropy","ce"].indexOf(d)!==-1){let g=this.internalOutputShapes[a];g[g.length-1]===1||this.lossFunctions[a]===Bp?["accuracy","acc"].indexOf(d)!==-1?m=ed:["crossentropy","ce"].indexOf(d)!==-1&&(m=Cx):this.lossFunctions[a]===zp?["accuracy","acc"].indexOf(d)!==-1?m=Ix:["crossentropy","ce"].indexOf(d)!==-1&&(m=CC):["accuracy","acc"].indexOf(d)!==-1?m=td:["crossentropy","ce"].indexOf(d)!==-1&&(m=rd);let y;["accuracy","acc"].indexOf(d)!==-1?y="acc":["crossentropy","ce"].indexOf(d)!==-1&&(y="ce"),f=m,p=c+y}else f=UM(d),p=c+od(d);let h;Ms(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;Dx(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 gr(u)}finally{Cl(a[0],e),Cl(a[1],t)}}async evaluateDataset(e,t){return this.makeTestFunction(),oL(this,e,t)}checkNumSamples(e,t,o,n="steps"){let s;if(o!=null){if(s=null,t!=null)throw new z(`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 z(`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 z("`outputs` is an empty Array, which is not allowed.");let o=Array.isArray(t),n=o?t:[t],s=this.retrieveSymbolicTensors(n),a=new zs;if(e instanceof Ve&&(e=[e]),Array.isArray(e)){if(e.length!==this.inputs.length)throw new z(`The number of inputs provided (${e.length}) does not match the number of inputs of this model (${this.inputs.length}).`);for(let l=0;l<this.inputs.length;++l)a.add(this.inputs[l],e[l])}else for(let l of this.inputs){let u=e[l.name];if(u==null)throw new z(`No value is provided for the model's input ${l.name}`);a.add(l,u)}let i=cc(s,a);return o?i:i[0]}retrieveSymbolicTensors(e){let t=Zn(null,e.length),o=e.length;for(let n of this.layers){let s=Array.isArray(n.output)?n.output:[n.output],a=s.map(i=>i.name);for(let i=0;i<e.length;++i){let l=a.indexOf(e[i]);if(l!==-1&&(t[i]=s[l],o--),o===0)break}if(o===0)break}if(o>0){let n=[];throw t.forEach((s,a)=>{s==null&&n.push(e[a])}),new z(`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=Rx(n,t),a=this.outputs.map(i=>[]);for(let i=0;i<s.length;++i)V(()=>{let u=s[i][0],c=s[i][1],p=Gp(e,u,c),m=[];if(Array.isArray(p))for(let d=0;d<p.length;++d)m.push({key:this.inputs[d],value:p[d]});else m.push({key:this.inputs[0],value:p});let f=new zs(m);return cc(this.outputs,f)}).forEach((u,c)=>a[c].push(u));return gr(a.map(i=>Ze(i,0)))})}predict(e,t={}){let o=TC(e);aL(o,this.inputNames,this.feedInputShapes,!1);try{let n=t.batchSize==null?32:t.batchSize;return Dx(n),this.predictLoop(o,n)}finally{Cl(o,e)}}predictOnBatch(e){aL(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 Mr("You must compile a model before training/testing. Use LayersModel.compile(modelCompileArgs).");let s=[];for(let a=0;a<this.feedOutputShapes.length;++a){let i=this.feedOutputShapes[a];this.feedLossFns[a]===zp?s.push(i.slice(0,i.length-1).concat([1])):s.push(i)}if(e=iL(e,this.feedInputNames,this.feedInputShapes,!1,"input"),t=iL(t,this.feedOutputNames,s,!1,"target"),b9(e,t,null),w9(t,this.feedLossFns,this.feedOutputShapes),this.stateful&&n!=null&&n>0&&e[0].shape[0]%n!=0)throw new z(`In a stateful network, you should only pass inputs with a number of samples that is divisible by the batch size ${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=Ax(n,this.outputNames);u=[];for(let p=0;p<c.length;++p)u.push(await Ex(l[p],null,c[p]))}return[i,l,u]}testLoop(e,t,o,n=0,s){return V(()=>{let a=this.checkNumSamples(t,o,s,"steps"),i=[];if(n>0)throw new Se("Verbose mode is not implemented yet.");if(s!=null)throw new Se("steps mode in testLoop() is not implemented yet");{let l=Rx(a,o),u=Vt(Lr(0,a));for(let c=0;c<l.length;++c){let p=l[c][0],m=l[c][1],f=Ga(u,p,m-p),d=$x(t,f),h=e(d);if(c===0)for(let g=0;g<h.length;++g)i.push(le(0));for(let g=0;g<h.length;++g){let y=h[g];i[g]=ee(i[g],O(m-p,y))}}for(let c=0;c<i.length;++c)i[c]=me(i[c],a)}return i})}getDedupedMetricsNames(){let e=this.metricsNames,t=[];for(let o=0;o<e.length;++o){let n=e[o],s=n;fC(e,n)>1&&(s+=`_${fC(e.slice(0,o),n)}`),t.push(s)}return t}makeTrainFunction(){return e=>{let t=[],o=e.slice(0,this.inputs.length),n=e.slice(this.inputs.length,this.inputs.length+this.outputs.length),s=e.slice(this.inputs.length+this.outputs.length,this.inputs.length+this.outputs.length*2),a=[],i=()=>{let p=[];for(let h=0;h<this.inputs.length;++h)p.push({key:this.inputs[h],value:o[h]});let m=new zs(p),f=cc(this.outputs,m,{training:!0}),d;for(let h=0;h<this.lossFunctions.length;++h){let y=this.lossFunctions[h](n[h],f[h]);s[h]!=null&&(y=JM(y,s[h]));let b=dt(y);t.push(b),h===0?d=y:d=ee(d,y)}for(let h=0;h<this.metricsTensors.length;++h){let g;if(this.outputs.length>1&&h<this.outputs.length)g=t[h];else{let y=this.metricsTensors[h][0],b=this.metricsTensors[h][1];g=dt(y(n[b],f[b]))}Et(g),a.push(g)}return d=dt(d),this.calculateLosses().forEach(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;u<this.inputs.length;++u)a.push({key:this.inputs[u],value:n[u]});let i=new zs(a),l=cc(this.outputs,i);for(let u=0;u<this.lossFunctions.length;++u){let c=this.lossFunctions[u],p=dt(c(s[u],l[u]));u===0?o=p:o=ee(o,p),t.push(o)}for(let u=0;u<this.metricsTensors.length;++u){let c=this.metricsTensors[u][0],p=this.metricsTensors[u][1],m=dt(c(s[p],l[p]));t.push(m)}return t})}async fit(e,t,o={}){return nL(this,e,t,o)}async fitDataset(e,t){return rL(this,e,t)}async trainOnBatch(e,t){let o=await this.standardizeUserData(e,t),n=o[0],s=o[1],i=this.makeTrainFunction()(n.concat(s)),l=[];for(let u of i){let c=await u.data();l.push(c[0])}return Ae(i),gr(l)}getNamedWeights(e){let t=[],o=e!=null&&e.trainableOnly,n=o?this.trainableWeights:this.weights,s=this.getWeights(o);for(let a=0;a<n.length;++a)o&&!n[a].trainable||t.push({name:n[a].originalName,tensor:s[a]});return t}set stopTraining(e){this.stopTraining_=e}get stopTraining(){return this.stopTraining_}get optimizer(){return this.optimizer_}set optimizer(e){this.optimizer_!==e&&(this.optimizer_=e,this.isOptimizerOwned=!1)}dispose(){let e=super.dispose();if(e.refCountAfterDispose===0&&this.optimizer!=null&&this.isOptimizerOwned){let t=Uc().numTensors;this.optimizer_.dispose(),e.numDisposedVariables+=t-Uc().numTensors}return e}getLossIdentifiers(){let e;if(typeof this.loss=="string")e=Jn(this.loss);else if(Array.isArray(this.loss)){for(let t of this.loss)if(typeof t!="string")throw new Error("Serialization of non-string loss is not supported.");e=this.loss.map(t=>Jn(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]=Jn(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[Jn(od(this.metrics))];if(Array.isArray(this.metrics))return this.metrics.map(e=>Jn(od(e)));{let e={};for(let t in this.metrics)e[t]=Jn(od(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=uc(e.optimizer_config),o=Qr(t),n;if(typeof e.loss=="string")n=za(e.loss);else if(Array.isArray(e.loss))n=e.loss.map(a=>za(a));else if(e.loss!=null){n={};for(let a in e.loss)n[a]=za(e.loss[a])}let s;if(Array.isArray(e.metrics))s=e.metrics.map(a=>za(a));else if(e.metrics!=null){s={};for(let a in e.metrics)s[a]=za(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 z(`Cannot find any save handlers for URL '${e}'`);if(u.length>1)throw new z(`Found more than one (${u.length}) save handlers for URL '${e}'`);e=u[0]}if(e.save==null)throw new z("LayersModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");let o=await Cr.encodeWeights(this.getNamedWeights(t)),n=!1,s=null,i={modelTopology:this.toJSON(s,n),format:_9,generatedBy:`TensorFlow.js tfjs-layers v${Vp}`,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;NC(this.userDefinedMetadata,this.name,u),i.userDefinedMetadata=this.userDefinedMetadata}return i.weightData=o.data,i.weightSpecs=o.specs,e.save(i)}setUserDefinedMetadata(e){NC(e,this.name),this.userDefinedMetadata=e}getUserDefinedMetadata(){return this.userDefinedMetadata}};To.className="Model";Q.registerClass(To);var EC=class extends To{};EC.className="Functional";Q.registerClass(EC);async function lL(r,e){"modelTopology"in r||(r={modelTopology:r}),r=r;let t=r.modelTopology;t.model_config!=null&&(t=t.model_config);let o=uc(t),n=Qr(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 uL(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 z(`Found more than one (${t.length}) load handlers for URL '${r}'`);r=t[0]}return v9(r,void 0,e)}async function v9(r,e,t){if(t==null&&(t={}),r.load==null)throw new z("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");let 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=Qr(uc(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 z("LayersModel artifacts contains weight data, but not weight specs. Therefore loading of weights cannot proceed.");let{modelWeights:u,optimizerWeights:c}=C9(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 C9(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 qi=class extends To{constructor(e){super({inputs:[],outputs:[]});if(e=e||{},this.trainable=!0,this.built=!1,this.name=e.name!=null?e.name:wl("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 z(`Negative dimension size caused by adding layer ${e.name} with input shape [${e.inboundNodes[0].inputTensors[0].shape}]`)}add(e){let t=e instanceof qi||e instanceof To,o;if(t){if(o=e,o.outputs.length!==1)throw new z("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");if(o.inputs.length!==1)throw new z("All layers in a Sequential model should have a single input tensor. For multi-input layers, use the functional API.")}if(this.outputs.length===0){if(e.inboundNodes.length===0){if(e.batchInputShape==null)throw new z("The first layer in a Sequential model must get an `inputShape` or `batchInputShape` argument.");let n=gx({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 z(`A layer added to a Sequential model must not already be connected somewhere else. LayersModel received layer ${e.name} which has ${e.inboundNodes.length} pre-existing inbound connections.`);if(e.inboundNodes[0].outputTensors.length!==1)throw new z("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");this.checkShape(e),this.outputs=[e.inboundNodes[0].outputTensors[0]],this.inputs=_C(this.outputs[0])}this.inboundNodes=[],new kl({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:Zn(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(Je(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 To({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 Mr("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 Mr("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 Mr("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 Mr("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 z("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 qi))throw new Se(`Sequential.fromConfig called on non-Sequential input: ${i}`);for(let l of s){let c=Qr(l,void 0,n);n&&c.setFastWeightInitDuringBuild(!0),i.add(c)}return i}set stopTraining(e){if(this.model==null)throw new z("Cannot set the stopTraining property of a sequential model before it is compiled.");this.model.stopTraining=e}get stopTraining(){if(this.model==null)throw new z("Cannot get the stopTraining property of a sequential model before it is compiled.");return this.model.stopTraining}getConfig(){let e=[];for(let t of this.layers){let o={};o.className=t.getClassName(),o.config=t.getConfig(),e.push(o)}return{name:this.name,layers:e}}};qi.className="Sequential";Q.registerClass(qi);function cL(r){return new To(r)}function pL(r){return new qi(r)}function mL(r,e){return e==null&&(e={}),uL(r,e)}function Fx(r){return gx(r)}function fL(r,e){po.registerCallbackConstructor(r,e)}var mo=class extends Q.Serializable{getConfig(){return{}}},DC=class extends mo{apply(e,t=1){return RM(e,t)}};DC.className="elu";Q.registerClass(DC);var $C=class extends mo{apply(e){return Ou(e)}};$C.className="selu";Q.registerClass($C);var RC=class extends mo{apply(e){return Nr(e)}};RC.className="relu";Q.registerClass(RC);var FC=class extends mo{apply(e){return V(()=>As(6,Nr(e)))}};FC.className="relu6";Q.registerClass(FC);var OC=class extends mo{apply(e){return e}};OC.className="linear";Q.registerClass(OC);var PC=class extends mo{apply(e){return qr(e)}};PC.className="sigmoid";Q.registerClass(PC);var MC=class extends mo{apply(e){return OM(e)}};MC.className="hardSigmoid";Q.registerClass(MC);var LC=class extends mo{apply(e){return Ts(e)}};LC.className="softplus";Q.registerClass(LC);var zC=class extends mo{apply(e){return FM(e)}};zC.className="softsign";Q.registerClass(zC);var BC=class extends mo{apply(e){return Oi(e)}};BC.className="tanh";Q.registerClass(BC);var nd=class extends mo{apply(e,t=-1){return Aa(e,t)}};nd.className="softmax";Q.registerClass(nd);var VC=class extends mo{apply(e,t=-1){return Au(e,t)}};VC.className="logSoftmax";Q.registerClass(VC);var GC=class extends mo{apply(e,t=1){return V(()=>qr(e.mul(t)).mul(e))}};GC.className="swish";Q.registerClass(GC);function Bs(r){return r.getClassName()}function WC(r,e={}){return Gi(r,Q.SerializationMap.getMap().classNameMap,e,"activation")}function Vs(r){if(r==null){let e={};return e.className="linear",e.config={},WC(e)}if(typeof r=="string"){let e={};return e.className=r,e.config={},WC(e)}else return r instanceof mo?r:WC(r)}function jC(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 UC=class extends Q.Serializable{},pc=class extends UC{constructor(e){super();jC(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=ht([1]);return this.hasL1&&(t=ee(t,ge(O(this.l1,It(e))))),this.hasL2&&(t=ee(t,ge(O(this.l2,ic(e))))),t.asScalar()})}getConfig(){return{l1:this.l1,l2:this.l2}}static fromConfig(e,t){return new e({l1:t.l1,l2:t.l2})}};pc.className="L1L2";Q.registerClass(pc);function dL(r){return jC(r),new pc({l1:r!=null?r.l1:null,l2:0})}function hL(r){return jC(r),new pc({l2:r!=null?r.l2:null,l1:0})}var gL={l1l2:"L1L2"};function st(r){return Cp(r)}function xL(r,e={}){return Gi(r,Q.SerializationMap.getMap().classNameMap,e,"regularizer")}function bt(r){if(r==null)return null;if(typeof r=="string"){let t={className:r in gL?gL[r]:r,config:{}};return xL(t)}else return r instanceof UC?r:xL(r)}var sd=class extends Me{constructor(e){super(e==null?{}:e);this.supportsMasking=!0,e!=null&&(this.maxValue=e.maxValue)}call(e,t){e=Fe(e);let o=Nr(e);return this.maxValue!=null&&(o=sr(o,0,this.maxValue)),o}computeOutputShape(e){return e}getConfig(){let e={maxValue:this.maxValue},t=super.getConfig();return Object.assign(e,t),e}};sd.className="ReLU";Q.registerClass(sd);var id=class extends Me{constructor(e){super(e==null?{}:e);this.DEFAULT_ALPHA=.3,e==null&&(e={}),this.alpha=e.alpha==null?this.DEFAULT_ALPHA:e.alpha}call(e,t){let o=Fe(e);return Ca(o,this.alpha)}computeOutputShape(e){return e}getConfig(){let e={alpha:this.alpha},t=super.getConfig();return Object.assign(e,t),e}};id.className="LeakyReLU";Q.registerClass(id);var ad=class extends Me{constructor(e){super(e==null?{}:e);if(this.DEFAULT_ALPHA_INITIALIZER="zeros",e==null&&(e={}),this.supportsMasking=!0,this.alphaInitializer=pt(e.alphaInitializer||this.DEFAULT_ALPHA_INITIALIZER),this.alphaRegularizer=bt(e.alphaRegularizer),this.alphaConstraint=Ot(e.alphaConstraint),e.sharedAxes==null)this.sharedAxes=null;else if(Array.isArray(e.sharedAxes))this.sharedAxes=e.sharedAxes;else if(typeof e.sharedAxes=="number")this.sharedAxes=[e.sharedAxes];else throw new z(`Expected sharedAxes to be a number or an array of numbers, but got ${e.sharedAxes}`)}build(e){e=Je(e);let t=e.slice(1);if(this.sharedAxes!=null)for(let n of this.sharedAxes)t[n-1]=1;this.alpha=this.addWeight("alpha",t,"float32",this.alphaInitializer,this.alphaRegularizer,!0,this.alphaConstraint);let o={};if(this.sharedAxes!=null)for(let n=1;n<e.length;++n)o[n]=e[n];this.inputSpec=[new St({ndim:e.length,axes:o})],this.built=!0}call(e,t){return e=Fe(e),Ta(e,this.alpha.read())}getConfig(){let e={alphaInitializer:_t(this.alphaInitializer),alphaRegularizer:st(this.alphaRegularizer),alphaConstraint:Ft(this.alphaConstraint),sharedAxes:this.sharedAxes},t=super.getConfig();return Object.assign(e,t),e}};ad.className="PReLU";Q.registerClass(ad);var ld=class extends Me{constructor(e){super(e==null?{}:e);if(this.DEFAULT_ALPHA=1,e==null&&(e={}),e.alpha!=null&&e.alpha!==this.DEFAULT_ALPHA)throw new Se(`Non-default alpha value (${e.alpha}) is not supported by the ELU layer yet.`);this.alpha=e.alpha==null?this.DEFAULT_ALPHA:e.alpha}call(e,t){let o=Fe(e);return Ns(o)}computeOutputShape(e){return e}getConfig(){let e={alpha:this.alpha},t=super.getConfig();return Object.assign(e,t),e}};ld.className="ELU";Q.registerClass(ld);var ud=class extends Me{constructor(e){super(e==null?{}:e);this.DEFAULT_THETA=1,e==null&&(e={}),this.theta=e.theta==null?this.DEFAULT_THETA:e.theta}call(e,t){let o=Fe(e);return o.mul(Ba(o.greater(this.theta),"float32"))}computeOutputShape(e){return e}getConfig(){let e={theta:this.theta},t=super.getConfig();return Object.assign(e,t),e}};ud.className="ThresholdedReLU";Q.registerClass(ud);var cd=class extends Me{constructor(e){super(e==null?{}:e);this.DEFAULT_AXIS=1,e==null&&(e={}),this.softmax=new nd().apply,this.axis=e.axis==null?this.DEFAULT_AXIS:e.axis}call(e,t){let o=Fe(e);return this.softmax(o,this.axis)}computeOutputShape(e){return e}getConfig(){let e={axis:this.axis},t=super.getConfig();return Object.assign(e,t),e}};cd.className="Softmax";Q.registerClass(cd);function Il(r,e,t){if(typeof r=="number")return Zn(r,e);if(r.length!==e)throw new z(`The ${t} argument must be an integer or tuple of ${e} integers. Received: ${r.length} elements.`);for(let o=0;o<e;++o){let n=r[o];if(!TM(n))throw new z(`The ${t} argument must be an integer or tuple of ${e} integers. Received: ${JSON.stringify(r)} including a non-integer number ${n}`)}return r}function fo(r,e,t,o,n=1){if(r==null)return r;let s=e+(e-1)*(n-1),a;return t==="same"?a=r:a=r-s+1,Math.floor((a+o-1)/o)}function pd(r,e,t,o){if(r==null)return null;if(o==="valid")r=r*e+Ls([t-e,0]);else if(o==="same")r=r*e;else throw new z(`Unsupport padding mode: ${o}.`);return r}function md(r,e){return V(()=>($t(e),e==="channelsFirst"?Ue(r,[0,2,3,1]):r))}function HC(r,e){return V(()=>($t(e),e==="channelsFirst"?Ue(r,[0,2,3,4,1]):r))}function I9(r,e,t,o=1,n="valid",s,a=1){return V(()=>{if(s==null&&(s=Zr()),$t(s),r.shape.length!==3)throw new z(`The input of a conv1dWithBias operation should be 3, but is ${r.shape.length} instead.`);if(e.shape.length!==3)throw new z(`The kernel for a conv1dWithBias operation should be 3, but is ${e.shape.length} instead`);if(t!=null&&t.shape.length!==1)throw new z(`The bias for a conv1dWithBias operation should be 1, but is ${e.shape.length} instead`);if(s==="channelsFirst"&&(r=Ue(r,[0,2,1])),n==="causal")throw new Se("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");let i=_u(r,e,o,n==="same"?"same":"valid","NWC",a);return t!=null&&(i=uo(i,t)),i})}function yL(r,e,t,o=[1,1],n="valid",s,a,i=null){return V(()=>{if(s==null&&(s=Zr()),$t(s),r.rank!==3&&r.rank!==4)throw new z(`conv2dWithBiasActivation expects input to be of rank 3 or 4, but received ${r.rank}.`);if(e.rank!==3&&e.rank!==4)throw new z(`conv2dWithBiasActivation expects kernel to be of rank 3 or 4, but received ${r.rank}.`);let l=md(r,s);if(n==="causal")throw new Se("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");return l=Gn.conv2d({x:l,filter:e,strides:o,pad:n==="same"?"same":"valid",dilations:a,dataFormat:"NHWC",bias:t,activation:i}),s==="channelsFirst"&&(l=Ue(l,[0,3,1,2])),l})}function N9(r,e,t,o=[1,1,1],n="valid",s,a){return V(()=>{if(s==null&&(s=Zr()),$t(s),r.rank!==4&&r.rank!==5)throw new z(`conv3dWithBias expects input to be of rank 4 or 5, but received ${r.rank}.`);if(e.rank!==4&&e.rank!==5)throw new z(`conv3dWithBias expects kernel to be of rank 4 or 5, but received ${r.rank}.`);let i=HC(r,s);if(n==="causal")throw new Se("The support for CAUSAL padding mode in conv3dWithBias is not implemented yet.");return i=Em(i,e,o,n==="same"?"same":"valid","NDHWC",a),t!=null&&(i=uo(i,t)),s==="channelsFirst"&&(i=Ue(i,[0,4,1,2,3])),i})}var Wp=class extends Me{constructor(e,t){super(t);if(this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",Wp.verifyArgs(t),this.rank=e,Ut(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=Il(t.kernelSize,e,"kernelSize"),this.strides=Il(t.strides==null?1:t.strides,e,"strides"),this.padding=t.padding==null?"valid":t.padding,Jr(this.padding),this.dataFormat=t.dataFormat==null?"channelsLast":t.dataFormat,$t(this.dataFormat),this.activation=Vs(t.activation),this.useBias=t.useBias==null?!0:t.useBias,this.biasInitializer=pt(t.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.biasConstraint=Ot(t.biasConstraint),this.biasRegularizer=bt(t.biasRegularizer),this.activityRegularizer=bt(t.activityRegularizer),this.dilationRate=Il(t.dilationRate==null?1:t.dilationRate,e,"dilationRate"),this.rank===1&&Array.isArray(this.dilationRate)&&this.dilationRate.length!==1)throw new z(`dilationRate must be a number or an array of a single number for 1D convolution, but received ${JSON.stringify(this.dilationRate)}`);if(this.rank===2){if(typeof this.dilationRate=="number")this.dilationRate=[this.dilationRate,this.dilationRate];else if(this.dilationRate.length!==2)throw new z(`dilationRate must be a number or array of two numbers for 2D convolution, but received ${JSON.stringify(this.dilationRate)}`)}else if(this.rank===3){if(typeof this.dilationRate=="number")this.dilationRate=[this.dilationRate,this.dilationRate,this.dilationRate];else if(this.dilationRate.length!==3)throw new z(`dilationRate must be a number or array of three numbers for 3D convolution, but received ${JSON.stringify(this.dilationRate)}`)}}static verifyArgs(e){if(Go("kernelSize"in e,"required key 'kernelSize' not in config"),typeof e.kernelSize!="number"&&!ix(e.kernelSize,"number",1,3))throw new z(`BaseConv expects config.kernelSize to be number or number[] with length 1, 2, or 3, but received ${JSON.stringify(e.kernelSize)}.`)}getConfig(){let e={kernelSize:this.kernelSize,strides:this.strides,padding:this.padding,dataFormat:this.dataFormat,dilationRate:this.dilationRate,activation:Bs(this.activation),useBias:this.useBias,biasInitializer:_t(this.biasInitializer),biasRegularizer:st(this.biasRegularizer),activityRegularizer:st(this.activityRegularizer),biasConstraint:Ft(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}},mc=class extends Wp{constructor(e,t){super(e,t);this.kernel=null,mc.verifyArgs(t),this.filters=t.filters,Ut(this.filters,"filters"),this.kernelInitializer=pt(t.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.kernelConstraint=Ot(t.kernelConstraint),this.kernelRegularizer=bt(t.kernelRegularizer)}build(e){e=Je(e);let t=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[t]==null)throw new z(`The channel dimension of the input should be defined. Found ${e[t]}`);let 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=Fe(e);let o,n=this.bias==null?null:this.bias.read(),s=ax(this.activation.getClassName());if(s!=null&&this.rank===2)o=yL(e,this.kernel.read(),n,this.strides,this.padding,this.dataFormat,this.dilationRate,s);else{if(this.rank===1)o=I9(e,this.kernel.read(),n,this.strides[0],this.padding,this.dataFormat,this.dilationRate[0]);else if(this.rank===2)o=yL(e,this.kernel.read(),n,this.strides,this.padding,this.dataFormat,this.dilationRate);else if(this.rank===3)o=N9(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=Je(e);let t=[],o=this.dataFormat==="channelsLast"?e.slice(1,e.length-1):e.slice(2);for(let s=0;s<o.length;++s){let a=fo(o[s],this.kernelSize[s],this.padding,this.strides[s],typeof this.dilationRate=="number"?this.dilationRate:this.dilationRate[s]);t.push(a)}let n=[e[0]];return this.dataFormat==="channelsLast"?(n=n.concat(t),n.push(this.filters)):(n.push(this.filters),n=n.concat(t)),n}getConfig(){let e={filters:this.filters,kernelInitializer:_t(this.kernelInitializer),kernelRegularizer:st(this.kernelRegularizer),kernelConstraint:Ft(this.kernelConstraint)},t=super.getConfig();return Object.assign(e,t),e}static verifyArgs(e){if(!("filters"in e)||typeof e.filters!="number"||e.filters<1)throw new z(`Convolution layer expected config.filters to be a 'number' > 0 but got ${JSON.stringify(e.filters)}`)}},Nl=class extends mc{constructor(e){super(2,e);Nl.verifyArgs(e)}getConfig(){let e=super.getConfig();return delete e.rank,e}static verifyArgs(e){if(typeof e.kernelSize!="number"&&!ix(e.kernelSize,"number",1,2))throw new z(`Conv2D expects config.kernelSize to be number or number[] with length 1 or 2, but received ${JSON.stringify(e.kernelSize)}.`)}};Nl.className="Conv2D";Q.registerClass(Nl);var fc=class extends mc{constructor(e){super(3,e);fc.verifyArgs(e)}getConfig(){let e=super.getConfig();return delete e.rank,e}static verifyArgs(e){if(typeof e.kernelSize!="number"&&!(Array.isArray(e.kernelSize)&&(e.kernelSize.length===1||e.kernelSize.length===3)))throw new z(`Conv3D expects config.kernelSize to be number or [number, number, number], but received ${JSON.stringify(e.kernelSize)}.`)}};fc.className="Conv3D";Q.registerClass(fc);var fd=class extends Nl{constructor(e){super(e);if(this.inputSpec=[new St({ndim:4})],this.padding!=="same"&&this.padding!=="valid")throw new z(`Conv2DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(e){if(e=Je(e),e.length!==4)throw new z("Input should have rank 4; Received input shape: "+JSON.stringify(e));let t=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[t]==null)throw new z("The channel dimension of the inputs should be defined. Found `None`.");let 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 St({ndim:4,axes:{[t]:o}})],this.built=!0}call(e,t){return V(()=>{let o=Fe(e);if(o.shape.length!==4)throw new z(`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=pd(l,m,c,this.padding),h=pd(u,f,p,this.padding),g=[s,d,h,this.filters];this.dataFormat!=="channelsLast"&&(o=Ue(o,[0,2,3,1]));let y=vu(o,this.kernel.read(),g,this.strides,this.padding);return this.dataFormat!=="channelsLast"&&(y=Ue(y,[0,3,1,2])),this.bias!=null&&(y=uo(y,this.bias.read(),this.dataFormat)),this.activation!=null&&(y=this.activation.apply(y)),y})}computeOutputShape(e){e=Je(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]=pd(t[n],l,a,this.padding),t[s]=pd(t[s],u,i,this.padding),t}getConfig(){let e=super.getConfig();return delete e.dilationRate,e}};fd.className="Conv2DTranspose";Q.registerClass(fd);var qC=class extends mc{constructor(e,t){super(e,t);if(this.DEFAULT_DEPTHWISE_INITIALIZER="glorotUniform",this.DEFAULT_POINTWISE_INITIALIZER="glorotUniform",this.depthwiseKernel=null,this.pointwiseKernel=null,t.filters==null)throw new z("The `filters` configuration field is required by SeparableConv, but is unspecified.");if(t.kernelInitializer!=null||t.kernelRegularizer!=null||t.kernelConstraint!=null)throw new z("Fields kernelInitializer, kernelRegularizer and kernelConstraint are invalid for SeparableConv2D. Use depthwiseInitializer, depthwiseRegularizer, depthwiseConstraint, pointwiseInitializer, pointwiseRegularizer and pointwiseConstraint instead.");if(t.padding!=null&&t.padding!=="same"&&t.padding!=="valid")throw new z(`SeparableConv${this.rank}D supports only padding modes: 'same' and 'valid', but received ${JSON.stringify(t.padding)}`);this.depthMultiplier=t.depthMultiplier==null?1:t.depthMultiplier,this.depthwiseInitializer=pt(t.depthwiseInitializer||this.DEFAULT_DEPTHWISE_INITIALIZER),this.depthwiseRegularizer=bt(t.depthwiseRegularizer),this.depthwiseConstraint=Ot(t.depthwiseConstraint),this.pointwiseInitializer=pt(t.depthwiseInitializer||this.DEFAULT_POINTWISE_INITIALIZER),this.pointwiseRegularizer=bt(t.pointwiseRegularizer),this.pointwiseConstraint=Ot(t.pointwiseConstraint)}build(e){if(e=Je(e),e.length<this.rank+2)throw new z(`Inputs to SeparableConv${this.rank}D should have rank ${this.rank+2}, but received input shape: ${JSON.stringify(e)}`);let t=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[t]==null||e[t]<0)throw new z(`The channel dimension of the inputs should be defined, but found ${JSON.stringify(e[t])}`);let o=e[t],n=this.kernelSize.concat([o,this.depthMultiplier]),s=[];for(let i=0;i<this.rank;++i)s.push(1);s.push(o*this.depthMultiplier,this.filters);let a=!0;this.depthwiseKernel=this.addWeight("depthwise_kernel",n,"float32",this.depthwiseInitializer,this.depthwiseRegularizer,a,this.depthwiseConstraint),this.pointwiseKernel=this.addWeight("pointwise_kernel",s,"float32",this.pointwiseInitializer,this.pointwiseRegularizer,a,this.pointwiseConstraint),this.useBias?this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,a,this.biasConstraint):this.bias=null,this.inputSpec=[new St({ndim:this.rank+2,axes:{[t]:o}})],this.built=!0}call(e,t){return V(()=>{e=Fe(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=Ue(e,[0,2,3,1])),o=Um(e,this.depthwiseKernel.read(),this.pointwiseKernel.read(),this.strides,this.padding,this.dilationRate,"NHWC")),this.useBias&&(o=uo(o,this.bias.read(),this.dataFormat)),this.activation!=null&&(o=this.activation.apply(o)),this.dataFormat==="channelsFirst"&&(o=Ue(o,[0,3,1,2])),o})}getConfig(){let e=super.getConfig();return delete e.rank,delete e.kernelInitializer,delete e.kernelRegularizer,delete e.kernelConstraint,e.depthwiseInitializer=_t(this.depthwiseInitializer),e.pointwiseInitializer=_t(this.pointwiseInitializer),e.depthwiseRegularizer=st(this.depthwiseRegularizer),e.pointwiseRegularizer=st(this.pointwiseRegularizer),e.depthwiseConstraint=Ft(this.depthwiseConstraint),e.pointwiseConstraint=Ft(this.pointwiseConstraint),e}};qC.className="SeparableConv";var dd=class extends qC{constructor(e){super(2,e)}};dd.className="SeparableConv2D";Q.registerClass(dd);var dc=class extends mc{constructor(e){super(1,e);dc.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"&&!ix(e.kernelSize,"number",1,1))throw new z(`Conv1D expects config.kernelSize to be number or number[] with length 1, but received ${JSON.stringify(e.kernelSize)}.`)}};dc.className="Conv1D";Q.registerClass(dc);var hd=class extends Me{constructor(e){super(e);typeof e.cropping=="number"?this.cropping=[[e.cropping,e.cropping],[e.cropping,e.cropping]]:typeof e.cropping[0]=="number"?this.cropping=[[e.cropping[0],e.cropping[0]],[e.cropping[1],e.cropping[1]]]:this.cropping=e.cropping,this.dataFormat=e.dataFormat===void 0?"channelsLast":e.dataFormat,this.inputSpec=[{ndim:4}]}computeOutputShape(e){return this.dataFormat==="channelsFirst"?[e[0],e[1],e[2]-this.cropping[0][0]-this.cropping[0][1],e[3]-this.cropping[1][0]-this.cropping[1][1]]:[e[0],e[1]-this.cropping[0][0]-this.cropping[0][1],e[2]-this.cropping[1][0]-this.cropping[1][1],e[3]]}call(e,t){return V(()=>{if(e=Fe(e),this.dataFormat==="channelsLast"){let o=Vf(e,this.cropping[0][0],e.shape[1]-this.cropping[0][0]-this.cropping[0][1],2);return Vf(o,this.cropping[1][0],e.shape[2]-this.cropping[1][1]-this.cropping[1][0],3)}else{let o=Vf(e,this.cropping[0][0],e.shape[2]-this.cropping[0][0]-this.cropping[0][1],3);return Vf(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}};hd.className="Cropping2D";Q.registerClass(hd);var gd=class extends Me{constructor(e){super(e);this.DEFAULT_SIZE=[2,2],this.inputSpec=[{ndim:4}],this.size=e.size==null?this.DEFAULT_SIZE:e.size,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,$t(this.dataFormat),this.interpolation=e.interpolation==null?"nearest":e.interpolation,IM(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=Fe(e),n=o.shape;if(this.dataFormat==="channelsFirst"){o=Ue(o,[0,2,3,1]);let s=this.size[0]*n[2],a=this.size[1]*n[3],i=this.interpolation==="nearest"?o.resizeNearestNeighbor([s,a]):o.resizeBilinear([s,a]);return Ue(i,[0,3,1,2])}else{let s=this.size[0]*n[1],a=this.size[1]*n[2];return this.interpolation==="nearest"?o.resizeNearestNeighbor([s,a]):o.resizeBilinear([s,a])}})}getConfig(){let e={size:this.size,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}};gd.className="UpSampling2D";Q.registerClass(gd);function S9(r,e,t=[1,1],o="valid",n,s){return V(()=>{n==null&&(n=Zr()),$t(n);let a=md(r,n);if(r.rank!==4)throw new z(`Input for depthwiseConv2d is required to be 4-D, but is instead ${r.rank}-D`);if(e.rank!==4)throw new z(`depthwiseKernel is required to be 4-D, but is instead ${e.rank}-D`);return a=Is(a,e,t,o==="same"?"same":"valid","NHWC",s),n==="channelsFirst"&&(a=Ue(a,[0,3,1,2])),a})}var xd=class extends Wp{constructor(e){super(2,e);this.depthwiseKernel=null,this.depthMultiplier=e.depthMultiplier==null?1:e.depthMultiplier,this.depthwiseInitializer=pt(e.depthwiseInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.depthwiseConstraint=Ot(e.depthwiseConstraint),this.depthwiseRegularizer=bt(e.depthwiseRegularizer)}build(e){if(e=Je(e),e.length<4)throw new z(`Inputs to DepthwiseConv2D should have rank 4. Received input shape: ${JSON.stringify(e)}.`);let t=this.dataFormat==="channelsFirst"?1:3;if(e[t]==null||e[t]<0)throw new z(`The channel dimension of the inputs to DepthwiseConv2D should be defined, but is not (${e[t]}).`);let 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=Fe(e);let o=S9(e,this.depthwiseKernel.read(),this.strides,this.padding,this.dataFormat,null);return this.useBias&&(o=uo(o,this.bias.read(),this.dataFormat)),this.activation!=null&&(o=this.activation.apply(o)),o})}computeOutputShape(e){e=Je(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=fo(t,this.kernelSize[0],this.padding,this.strides[0]),a=fo(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=_t(this.depthwiseInitializer),e.depthwiseRegularizer=st(this.depthwiseRegularizer),e.depthwiseConstraint=Ft(this.depthwiseRegularizer),e}};xd.className="DepthwiseConv2D";Q.registerClass(xd);function KC(r,e,t,o){if(Array.isArray(r)){if(e!=null||t!=null)throw new z("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 XC(r,e,t,o=!1,n,s,a=!1,i=!1){return V(()=>{let l=e.shape.length;if(l<3)throw new z(`Input should be at least 3D, but is ${l}D.`);let u=[1,0].concat(Lr(2,l));if(e=Ue(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=ir(n,-1)),n=Ue(n,u)),o&&(e=Ht(e,0),n!=null&&(n=Ht(n,0)));let c=[],p,m=t,f=e.shape[0],d=cr(e),h;n!=null&&(h=cr(n));for(let y=0;y<f;++y){let b=d[y],w=V(()=>r(b,m));if(n==null)p=w[0],m=w[1];else{let k=V(()=>{let v=h[y],D=er(v).sub(v),A=w[0].mul(v).add(m[0].mul(D)),R=m.map((P,L)=>w[1][L].mul(v).add(P.mul(D)));return{output:A,newStates:R}});p=k.output,m=k.newStates}i&&c.push(p)}let g;return i&&(g=Bt(c,1)),[p,g,m]})}var ho=class extends Me{constructor(e){super(e);let t;if(e.cell==null)throw new z("cell property is missing for the constructor of RNN.");if(Array.isArray(e.cell)?t=new jp({cells:e.cell}):t=e.cell,t.stateSize==null)throw new z("The RNN cell should have an attribute `stateSize` (tuple of integers, one integer per RNN state).");this.cell=t,this.returnSequences=e.returnSequences==null?!1:e.returnSequences,this.returnState=e.returnState==null?!1:e.returnState,this.goBackwards=e.goBackwards==null?!1:e.goBackwards,this._stateful=e.stateful==null?!1:e.stateful,this.unroll=e.unroll==null?!1:e.unroll,this.supportsMasking=!0,this.inputSpec=[new St({ndim:3})],this.stateSpec=null,this.states_=null,this.numConstants=null,this.keptStates=[]}getStates(){if(this.states_==null){let e=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1;return Lr(0,e).map(t=>null)}else return this.states_}setStates(e){this.states_=e}computeOutputShape(e){hx(e)&&(e=e[0]),e=e;let t=this.cell.stateSize;Array.isArray(t)||(t=[t]);let o=t[0],n;if(this.returnSequences?n=[e[0],e[1],o]:n=[e[0],o],this.returnState){let s=[];for(let a of t)s.push([e[0],a]);return[n].concat(s)}else return n}computeMask(e,t){return V(()=>{Array.isArray(t)&&(t=t[0]);let o=this.returnSequences?t:null;if(this.returnState){let n=this.states.map(s=>null);return[o].concat(n)}else return o})}get states(){if(this.states_==null){let e=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1,t=[];for(let o=0;o<e;++o)t.push(null);return t}else return this.states_}set states(e){this.states_=e}build(e){let t=null;if(this.numConstants!=null)throw new Se("Constants support is not implemented in RNN yet.");hx(e)&&(e=e[0]),e=e;let o=this.stateful?e[0]:null,n=e.slice(2);this.inputSpec[0]=new St({shape:[o,null,...n]});let s=[e[0]].concat(e.slice(2));if(t!=null)throw new Se("Constants support is not implemented in RNN yet.");this.cell.build(s);let a;if(Array.isArray(this.cell.stateSize)?a=this.cell.stateSize:a=[this.cell.stateSize],this.stateSpec!=null){if(!x.arraysEqual(this.stateSpec.map(i=>i.shape[i.shape.length-1]),a))throw new z(`An initialState was passed that is not compatible with cell.stateSize. Received stateSpec=${this.stateSpec}; However cell.stateSize is ${this.cell.stateSize}`)}else this.stateSpec=a.map(i=>new St({shape:[null,i]}));this.stateful&&this.resetStates()}resetStates(e,t=!1){V(()=>{if(!this.stateful)throw new So("Cannot call resetStates() on an RNN Layer that is not stateful.");let o=this.inputSpec[0].shape[0];if(o==null)throw new z("If an RNN is stateful, it needs to know its batch size. Specify the batch size of your input tensors: \n- If using a Sequential model, specify the batch size by passing a `batchInputShape` option to your first layer.\n- If using the functional API, specify the batch size by passing a `batchShape` option to your Input layer.");if(this.states_==null)Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(n=>ht([o,n])):this.states_=[ht([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=>ht([o,n])):this.states_[0]=ht([o,this.cell.stateSize]);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new z(`Layer ${this.name} expects ${this.states_.length} state(s), but it received ${e.length} state value(s). Input received: ${e}`);t===!0?this.keptStates.push(this.states_.slice()):Ae(this.states_);for(let n=0;n<this.states_.length;++n){let s=e[n],a=Array.isArray(this.cell.stateSize)?this.cell.stateSize[n]:this.cell.stateSize,i=[o,a];if(!x.arraysEqual(s.shape,i))throw new z(`State ${n} is incompatible with layer ${this.name}: expected shape=${i}, received shape=${s.shape}`);this.states_[n]=s}}this.states_=this.states_.map(n=>Et(n.clone()))})}apply(e,t){let o=t==null?null:t.initialState,n=t==null?null:t.constants;t==null&&(t={});let s=KC(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 St({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 Br){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=Fe(e),s==null&&(this.stateful?s=this.states_:s=this.getInitialState(e));let a=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1;if(s.length!==a)throw new z(`RNN Layer has ${a} state(s) but was passed ${s.length} initial state(s).`);this.unroll&&console.warn("Ignoring unroll = true for RNN layer, due to imperative backend.");let i={training:n},u=XC((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=ht(e.shape);return t=ge(t,[1,2]),t=Va(t),Array.isArray(this.cell.stateSize)?this.cell.stateSize.map(o=>o>1?cx(t,[1,o]):t):this.cell.stateSize>1?[cx(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()===ho.className&&(t.cell={className:this.cell.getClassName(),config:o}),Object.assign({},o,e,t)}static fromConfig(e,t,o={}){let n=t.cell,s=Qr(n,o);return new e(Object.assign(t,{cell:s}))}};ho.className="RNN";Q.registerClass(ho);var Sl=class extends Me{},Up=class extends Sl{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,Ut(this.units,"units"),this.activation=Vs(e.activation==null?this.DEFAULT_ACTIVATION:e.activation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=pt(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=pt(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=pt(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=bt(e.kernelRegularizer),this.recurrentRegularizer=bt(e.recurrentRegularizer),this.biasRegularizer=bt(e.biasRegularizer),this.kernelConstraint=Ot(e.kernelConstraint),this.recurrentConstraint=Ot(e.recurrentConstraint),this.biasConstraint=Ot(e.biasConstraint),this.dropout=sc([1,Ls([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=sc([1,Ls([0,e.recurrentDropout==null?0:e.recurrentDropout])]),this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){e=Je(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 z(`SimpleRNNCell expects 2 input Tensors, got ${e.length}.`);let o=e[1];e=e[0];let n=t.training==null?!1:t.training;0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=Wa({ones:()=>er(e),rate:this.dropout,training:n})),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=Wa({ones:()=>er(o),rate:this.recurrentDropout,training:n}));let s,a=this.dropoutMask,i=this.recurrentDropoutMask;a!=null?s=rs(O(e,a),this.kernel.read()):s=rs(e,this.kernel.read()),this.bias!=null&&(s=uo(s,this.bias.read())),i!=null&&(o=O(o,i));let l=ee(s,rs(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:Bs(this.activation),useBias:this.useBias,kernelInitializer:_t(this.kernelInitializer),recurrentInitializer:_t(this.recurrentInitializer),biasInitializer:_t(this.biasInitializer),kernelRegularizer:st(this.kernelRegularizer),recurrentRegularizer:st(this.recurrentRegularizer),biasRegularizer:st(this.biasRegularizer),activityRegularizer:st(this.activityRegularizer),kernelConstraint:Ft(this.kernelConstraint),recurrentConstraint:Ft(this.recurrentConstraint),biasConstraint:Ft(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout};return Object.assign({},e,t)}};Up.className="SimpleRNNCell";Q.registerClass(Up);var yd=class extends ho{constructor(e){e.cell=new Up(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)}};yd.className="SimpleRNN";Q.registerClass(yd);var Hp=class extends Sl{constructor(e){super(e);if(this.DEFAULT_ACTIVATION="tanh",this.DEFAULT_RECURRENT_ACTIVATION="hardSigmoid",this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_RECURRENT_INITIALIZER="orthogonal",this.DEFAULT_BIAS_INITIALIZER="zeros",e.resetAfter)throw new z("GRUCell does not support reset_after parameter set to true.");this.units=e.units,Ut(this.units,"units"),this.activation=Vs(e.activation===void 0?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=Vs(e.recurrentActivation===void 0?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=pt(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=pt(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=pt(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=bt(e.kernelRegularizer),this.recurrentRegularizer=bt(e.recurrentRegularizer),this.biasRegularizer=bt(e.biasRegularizer),this.kernelConstraint=Ot(e.kernelConstraint),this.recurrentConstraint=Ot(e.recurrentConstraint),this.biasConstraint=Ot(e.biasConstraint),this.dropout=sc([1,Ls([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=sc([1,Ls([0,e.recurrentDropout==null?0:e.recurrentDropout])]),this.implementation=e.implementation,this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){e=Je(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 z(`GRUCell expects 2 input Tensors (inputs, h, c), got ${e.length}.`);let o=t.training==null?!1:t.training,n=e[1];e=e[0],0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=Wa({ones:()=>er(e),rate:this.dropout,training:o,count:3})),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=Wa({ones:()=>er(n),rate:this.recurrentDropout,training:o,count:3}));let s=this.dropoutMask,a=this.recurrentDropoutMask,i,l,u;0<this.dropout&&this.dropout<1&&(e=O(e,s[0]));let c=rs(e,this.kernel.read());this.useBias&&(c=uo(c,this.bias.read())),0<this.recurrentDropout&&this.recurrentDropout<1&&(n=O(n,a[0]));let p=this.recurrentKernel.read(),[m,f]=ur(p,[2*this.units,this.units],p.rank-1),d=rs(n,m),[h,g,y]=ur(c,3,c.rank-1),[b,w]=ur(d,2,d.rank-1);i=this.recurrentActivation.apply(ee(h,b)),l=this.recurrentActivation.apply(ee(g,w));let k=rs(O(l,n),f);u=this.activation.apply(ee(y,k));let v=ee(O(i,n),O(ee(1,He(i)),u));return[v,v]})}getConfig(){let e=super.getConfig(),t={units:this.units,activation:Bs(this.activation),recurrentActivation:Bs(this.recurrentActivation),useBias:this.useBias,kernelInitializer:_t(this.kernelInitializer),recurrentInitializer:_t(this.recurrentInitializer),biasInitializer:_t(this.biasInitializer),kernelRegularizer:st(this.kernelRegularizer),recurrentRegularizer:st(this.recurrentRegularizer),biasRegularizer:st(this.biasRegularizer),activityRegularizer:st(this.activityRegularizer),kernelConstraint:Ft(this.kernelConstraint),recurrentConstraint:Ft(this.recurrentConstraint),biasConstraint:Ft(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation,resetAfter:!1};return Object.assign({},e,t)}};Hp.className="GRUCell";Q.registerClass(Hp);var bd=class extends ho{constructor(e){e.implementation===0&&console.warn("`implementation=0` has been deprecated, and now defaults to `implementation=1`. Please update your layer call."),e.cell=new Hp(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 t.implmentation===0&&(t.implementation=1),new e(t)}};bd.className="GRU";Q.registerClass(bd);var Tl=class extends Sl{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,Ut(this.units,"units"),this.activation=Vs(e.activation===void 0?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=Vs(e.recurrentActivation===void 0?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=pt(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=pt(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=pt(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.unitForgetBias=e.unitForgetBias,this.kernelRegularizer=bt(e.kernelRegularizer),this.recurrentRegularizer=bt(e.recurrentRegularizer),this.biasRegularizer=bt(e.biasRegularizer),this.kernelConstraint=Ot(e.kernelConstraint),this.recurrentConstraint=Ot(e.recurrentConstraint),this.biasConstraint=Ot(e.biasConstraint),this.dropout=sc([1,Ls([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=sc([1,Ls([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=Je(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 co{apply(l,u){let c=s.apply([a]),p=new ac().apply([a]),m=s.apply([a*2]);return bC(bC(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 z(`LSTMCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);let n=e[1],s=e[2];e=e[0],0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=Wa({ones:()=>er(e),rate:this.dropout,training:o,count:4})),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=Wa({ones:()=>er(n),rate:this.recurrentDropout,training:o,count:4}));let a=this.dropoutMask,i=this.recurrentDropoutMask,l,u,c,p;0<this.dropout&&this.dropout<1&&(e=O(e,a[0]));let m=rs(e,this.kernel.read());0<this.recurrentDropout&&this.recurrentDropout<1&&(n=O(n,i[0])),m=ee(m,rs(n,this.recurrentKernel.read())),this.useBias&&(m=uo(m,this.bias.read()));let[f,d,h,g]=ur(m,4,m.rank-1);l=this.recurrentActivation.apply(f),u=this.recurrentActivation.apply(d),c=ee(O(u,s),O(l,this.activation.apply(h))),p=this.recurrentActivation.apply(g);let y=O(p,this.activation.apply(c));return[y,y,c]})}getConfig(){let e=super.getConfig(),t={units:this.units,activation:Bs(this.activation),recurrentActivation:Bs(this.recurrentActivation),useBias:this.useBias,kernelInitializer:_t(this.kernelInitializer),recurrentInitializer:_t(this.recurrentInitializer),biasInitializer:_t(this.biasInitializer),unitForgetBias:this.unitForgetBias,kernelRegularizer:st(this.kernelRegularizer),recurrentRegularizer:st(this.recurrentRegularizer),biasRegularizer:st(this.biasRegularizer),activityRegularizer:st(this.activityRegularizer),kernelConstraint:Ft(this.kernelConstraint),recurrentConstraint:Ft(this.recurrentConstraint),biasConstraint:Ft(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation};return Object.assign({},e,t)}};Tl.className="LSTMCell";Q.registerClass(Tl);var wd=class extends ho{constructor(e){e.implementation===0&&console.warn("`implementation=0` has been deprecated, and now defaults to `implementation=1`. Please update your layer call."),e.cell=new Tl(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 t.implmentation===0&&(t.implementation=1),new e(t)}};wd.className="LSTM";Q.registerClass(wd);var jp=class extends Sl{constructor(e){super(e);this.cells=e.cells}get stateSize(){let e=[];for(let t of this.cells.slice().reverse())Array.isArray(t.stateSize)?e.push(...t.stateSize):e.push(t.stateSize);return e}call(e,t){return V(()=>{e=e;let o=e.slice(1),n=[];for(let i of this.cells.slice().reverse())Array.isArray(i.stateSize)?n.push(o.splice(0,i.stateSize.length)):n.push(o.splice(0,1));n.reverse();let s=[],a;for(let i=0;i<this.cells.length;++i){let l=this.cells[i];o=n[i],i===0?a=[e[0]].concat(o):a=[a[0]].concat(o),a=l.call(a,t),s.push(a.slice(1))}o=[];for(let i of s.slice().reverse())o.push(...i);return[a[0]].concat(o)})}build(e){hx(e)&&(e=e[0]),e=e;let t;this.cells.forEach((o,n)=>{Ms(`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(Qr(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 Yf(e)}setWeights(e){let t=[];for(let o of this.cells){let n=o.weights.length,s=e.splice(n);for(let a=0;a<o.weights.length;++a)t.push([o.weights[a],s[a]])}Mp(t)}};jp.className="StackedRNNCells";Q.registerClass(jp);function Wa(r){let{ones:e,rate:t,training:o=!1,count:n=1}=r,s=()=>mx(e(),t),a=()=>bl(s,e,o);return!n||n<=1?Et(a().clone()):Array(n).fill(void 0).map(a).map(l=>Et(l.clone()))}var T9=function(r,e){var t={};for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&e.indexOf(o)<0&&(t[o]=r[o]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var n=0,o=Object.getOwnPropertySymbols(r);n<o.length;n++)e.indexOf(o[n])<0&&Object.prototype.propertyIsEnumerable.call(r,o[n])&&(t[o[n]]=r[o[n]]);return t};var YC=class extends ho{constructor(e){if(e.unroll)throw new Se("Unrolling is not possible with convolutional RNNs.");if(Array.isArray(e.cell))throw new Se("It is not possible at the moment to stack convolutional cells.");super(e);this.inputSpec=[new St({ndim:5})]}call(e,t){return V(()=>{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 z("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=ht(s);return Array.isArray(t)?Array(t.length).fill(a):[a]})}resetStates(e,t=!1){V(()=>{if(!this.stateful)throw new So("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 z("If an RNN is stateful, it needs to know its batch size. Specify the batch size of your input tensors: \n- If using a Sequential model, specify the batch size by passing a `batchInputShape` option to your first layer.\n- If using the functional API, specify the batch size by passing a `batchShape` option to your Input layer.");if(this.getStates()==null)Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(()=>ht(s)):this.states_=[ht(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(()=>ht(s)):this.states_[0]=ht(s);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new z(`Layer ${this.name} expects ${this.states_.length} state(s), but it received ${e.length} state value(s). Input received: ${e}`);t?this.keptStates.push(this.states_.slice()):Ae(this.states_);for(let i=0;i<this.states_.length;++i){let l=e[i],u=s;if(!x.arraysEqual(l.shape,u))throw new z(`State ${i} is incompatible with layer ${this.name}: expected shape=${u}, received shape=${l.shape}`);this.states_[i]=l}}this.states_=this.states_.map(i=>Et(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=fo(u,n[0],s,a[0],i[0]),m=fo(c,n[1],s,a[1],i[1]);return[...e.slice(0,2),...l?[o,p,m]:[p,m,o]]}};YC.className="ConvRNN2D";var qp=class extends Tl{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,Ut(this.filters,"filters"),this.kernelSize=Il(o,2,"kernelSize"),this.kernelSize.forEach(l=>Ut(l,"kernelSize")),this.strides=Il(n||1,2,"strides"),this.strides.forEach(l=>Ut(l,"strides")),this.padding=s||"valid",Jr(this.padding),this.dataFormat=a||"channelsLast",$t(this.dataFormat),this.dilationRate=Il(i||1,2,"dilationRate"),this.dilationRate.forEach(l=>Ut(l,"dilationRate"))}build(e){var t;e=Je(e);let o=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[o]==null)throw new z(`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 co{apply(m,f){let d=u.apply([c]),h=Ir([c]),g=u.apply([c*2]);return Sp([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 z(`ConvLSTM2DCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);let o=t.training||!1,n=e[0],s=e[1],a=e[2],i=4;0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=Wa({ones:()=>er(n),rate:this.dropout,training:o,count:i}));let l=this.dropoutMask,u=(J,ie,ue)=>!ie||!ie[ue]?J:O(ie[ue],J),c=u(n,l,0),p=u(n,l,1),m=u(n,l,2),f=u(n,l,3);0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=Wa({ones:()=>er(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),w=3,[k,v,D,A]=ur(this.kernel.read(),i,w),[R,P,L,G]=this.useBias?ur(this.bias.read(),i):[null,null,null,null];c=this.inputConv(c,k,R,this.padding),p=this.inputConv(p,v,P,this.padding),m=this.inputConv(m,D,L,this.padding),f=this.inputConv(f,A,G,this.padding);let[j,U,H,q]=ur(this.recurrentKernel.read(),i,w);h=this.recurrentConv(h,j),g=this.recurrentConv(g,U),y=this.recurrentConv(y,H),b=this.recurrentConv(b,q);let X=this.recurrentActivation.apply(ee(c,h)),oe=this.recurrentActivation.apply(ee(p,g)),Y=ee(O(oe,a),O(X,this.activation.apply(ee(m,y)))),re=O(this.recurrentActivation.apply(ee(f,b)),this.activation.apply(Y));return[re,re,Y]})}getConfig(){let e=super.getConfig(),{units:t}=e,o=T9(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=Kr(e,t,this.strides,n||"valid",this.dataFormat==="channelsFirst"?"NCHW":"NHWC",this.dilationRate);return o?uo(s,o,this.dataFormat):s}recurrentConv(e,t){return Kr(e,t,1,"same",this.dataFormat==="channelsFirst"?"NCHW":"NHWC")}};qp.className="ConvLSTM2DCell";Q.registerClass(qp);var kd=class extends YC{constructor(e){let t=new qp(e);super(Object.assign({},e,{cell:t}))}static fromConfig(e,t){return new e(t)}};kd.className="ConvLSTM2D";Q.registerClass(kd);var Kp=class extends Me{constructor(e){super(e);this.rate=Math.max(Math.min(e.rate,1),0),this.noiseShape=e.noiseShape,this.seed=e.seed,this.supportsMasking=!0}getNoiseShape(e){if(this.noiseShape==null)return this.noiseShape;let t=e.shape,o=[];for(let n=0;n<this.noiseShape.length;++n)o.push(this.noiseShape[n]==null?t[n]:this.noiseShape[n]);return o}call(e,t){return V(()=>{this.invokeCallHook(e,t);let o=Fe(e);if(0<this.rate&&this.rate<1){let n=t.training==null?!1:t.training,s=this.getNoiseShape(o);return bl(()=>mx(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()}};Kp.className="Dropout";Q.registerClass(Kp);var _d=class extends Kp{constructor(e){super(e);this.inputSpec=[{ndim:3}]}getNoiseShape(e){let t=e.shape;return[t[0],1,t[2]]}};_d.className="SpatialDropout1D";Q.registerClass(_d);var vd=class extends Me{constructor(e){super(e);if(this.activation=null,this.useBias=!0,this.kernel=null,this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",e.batchInputShape==null&&e.inputShape==null&&e.inputDim!=null){let t=null;e.batchSize!=null&&(t=e.batchSize),this.batchInputShape=[t,e.inputDim]}this.units=e.units,Ut(this.units,"units"),this.activation=Vs(e.activation),e.useBias!=null&&(this.useBias=e.useBias),this.kernelInitializer=pt(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.biasInitializer=pt(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelConstraint=Ot(e.kernelConstraint),this.biasConstraint=Ot(e.biasConstraint),this.kernelRegularizer=bt(e.kernelRegularizer),this.biasRegularizer=bt(e.biasRegularizer),this.activityRegularizer=bt(e.activityRegularizer),this.supportsMasking=!0,this.inputSpec=[{minNDim:2}]}build(e){e=Je(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=Je(e);let t=e.slice();return t[t.length-1]=this.units,t}call(e,t){return V(()=>{this.invokeCallHook(e,t);let o=Fe(e),n=ax(this.activation.getClassName()),s;return n!=null?s=rs(o,this.kernel.read(),n,this.bias?this.bias.read():null):(s=rs(o,this.kernel.read()),this.bias!=null&&(s=uo(s,this.bias.read())),this.activation!=null&&(s=this.activation.apply(s))),s})}getConfig(){let e={units:this.units,activation:Bs(this.activation),useBias:this.useBias,kernelInitializer:_t(this.kernelInitializer),biasInitializer:_t(this.biasInitializer),kernelRegularizer:st(this.kernelRegularizer),biasRegularizer:st(this.biasRegularizer),activityRegularizer:st(this.activityRegularizer),kernelConstraint:Ft(this.kernelConstraint),biasConstraint:Ft(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}};vd.className="Dense";Q.registerClass(vd);var Cd=class extends Me{constructor(e){e=e||{},super(e),this.inputSpec=[{minNDim:3}],this.dataFormat=e.dataFormat}computeOutputShape(e){e=Je(e);for(let t of e.slice(1))if(t==null)throw new z(`The shape of the input to "Flatten" is not fully defined (got ${e.slice(1)}). Make sure to pass a complete "input_shape" or "batch_input_shape" argument to the first layer in your model.`);return[e[0],ts(e,1)]}call(e,t){return V(()=>{this.invokeCallHook(e,t);let o=Fe(e);if(this.dataFormat==="channelsFirst"&&o.rank>1){let n=[0];for(let s=2;s<o.rank;++s)n.push(s);n.push(1),o=o.transpose(n)}return $M(o)})}getConfig(){let e={};this.dataFormat!=null&&(e.dataFormat=this.dataFormat);let t=super.getConfig();return Object.assign(e,t),e}};Cd.className="Flatten";Q.registerClass(Cd);var Id=class extends Me{constructor(e){super(e);this.supportsMasking=!0,this.activation=Vs(e.activation)}call(e,t){return V(()=>{this.invokeCallHook(e,t);let o=Fe(e);return this.activation.apply(o)})}getConfig(){let e={activation:Bs(this.activation)},t=super.getConfig();return Object.assign(e,t),e}};Id.className="Activation";Q.registerClass(Id);var Nd=class extends Me{constructor(e){super(e);this.n=e.n,this.inputSpec=[{ndim:2}]}computeOutputShape(e){return[e[0],this.n,e[1]]}call(e,t){return V(()=>(e=Fe(e),EM(e,this.n)))}getConfig(){let e={n:this.n},t=super.getConfig();return Object.assign(e,t),e}};Nd.className="RepeatVector";Q.registerClass(Nd);var Sd=class extends Me{constructor(e){super(e);this.targetShape=e.targetShape;for(let t=0;t<this.targetShape.length;++t)this.isUnknown(this.targetShape[t])&&(this.targetShape[t]=null)}isUnknown(e){return e<0||e==null}fixUnknownDimension(e,t){let o="Total size of new array must be unchanged.",n=t.slice(),s=1,a=null;for(let l=0;l<n.length;++l){let u=n[l];if(this.isUnknown(u))if(a===null)a=l;else throw new z("Can only specifiy one unknown dimension.");else s*=u}let i=ts(e);if(a!==null){if(s===0||i%s!=0)throw new z(o);n[a]=i/s}else if(i!==s)throw new z(o);return n}computeOutputShape(e){let t=!1;for(let o=0;o<e.length;++o)if(this.isUnknown(e[o])){t=!0;break}return t?e.slice(0,1).concat(this.targetShape):e.slice(0,1).concat(this.fixUnknownDimension(e.slice(1),this.targetShape))}call(e,t){return V(()=>{this.invokeCallHook(e,t);let o=Fe(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}};Sd.className="Reshape";Q.registerClass(Sd);var Td=class extends Me{constructor(e){super(e);if(e.dims==null)throw new Error("Required configuration field `dims` is missing during Permute constructor call.");if(!Array.isArray(e.dims))throw new Error(`Permute constructor requires \`dims\` to be an Array, but received ${e.dims} instead.`);let t=Lr(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 St({ndim:this.dims.length+1})]}computeOutputShape(e){e=Je(e);let t=e.slice();return this.dims.forEach((o,n)=>{t[n+1]=e[o]}),t}call(e,t){return Ue(Fe(e),this.dimsIncludingBatch)}getConfig(){let e={dims:this.dims},t=super.getConfig();return Object.assign(e,t),e}};Td.className="Permute";Q.registerClass(Td);var Ad=class extends Me{constructor(e){super(e==null?{}:e);this.supportsMasking=!0,e!=null?this.maskValue=e.maskValue==null?0:e.maskValue:this.maskValue=0}computeOutputShape(e){return e}getConfig(){let e=super.getConfig(),t={maskValue:this.maskValue};return Object.assign(t,e),t}computeMask(e,t){let o=Fe(e),n=-1;return sl(Vn(o,this.maskValue),n)}call(e,t){return V(()=>{this.invokeCallHook(e,t);let o=Fe(e),n=-1,s=!0,a=sl(Vn(o,this.maskValue),n,s);return o.mul(a.asType(o.dtype))})}};Ad.className="Masking";Q.registerClass(Ad);var Ed=class extends Me{constructor(e){super(e);if(this.embeddings=null,this.DEFAULT_EMBEDDINGS_INITIALIZER="randomUniform",e.batchInputShape==null&&e.inputShape==null){let t=null;e.batchSize!=null&&(t=e.batchSize),e.inputLength==null?this.batchInputShape=[t,null]:this.batchInputShape=[t].concat(yt(e.inputLength))}this.inputDim=e.inputDim,Ut(this.inputDim,"inputDim"),this.outputDim=e.outputDim,Ut(this.outputDim,"outputDim"),this.embeddingsInitializer=pt(e.embeddingsInitializer||this.DEFAULT_EMBEDDINGS_INITIALIZER),this.embeddingsRegularizer=bt(e.embeddingsRegularizer),this.activityRegularizer=bt(e.activityRegularizer),this.embeddingsConstraint=Ot(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=Fe(e),Vn(e,Ce(e))):null)}computeOutputShape(e){if(e=Je(e),this.inputLength==null)return[...e,this.outputDim];let t=yt(this.inputLength);if(t.length!==e.length-1)throw new z(`"inputLength" is ${this.inputLength}, but received input shape has shape ${e}`);{let o=0;for(let n=0;n<t.length;++n){let s=t[n],a=e[n+1];if(s!=null&&a!=null&&s!==a)throw new z(`"inputLength" is ${this.inputLength}, but received input shape has shape ${e}`);s==null&&(t[o]=a),o++}}return[e[0],...t,this.outputDim]}call(e,t){return V(()=>{this.invokeCallHook(e,t);let o=Fe(e);return o.dtype!=="int32"&&(o=Ba(o,"int32")),px(this.embeddings.read(),o.as1D()).reshape(Je(this.computeOutputShape(o.shape)))})}getConfig(){let e={inputDim:this.inputDim,outputDim:this.outputDim,embeddingsInitializer:_t(this.embeddingsInitializer),embeddingsRegularizer:st(this.embeddingsRegularizer),activityRegularizer:st(this.activityRegularizer),embeddingsConstraint:Ft(this.embeddingsConstraint),maskZero:this.maskZero,inputLength:this.inputLength},t=super.getConfig();return Object.assign(e,t),e}};Ed.className="Embedding";Q.registerClass(Ed);var Al=class extends Me{constructor(e){super(e||{});this.supportsMasking=!0}mergeFunction(e){throw new Se}computeElementwiseOpOutputShape(e,t){if(e==null||t==null)return null;if(e.length<t.length)return this.computeElementwiseOpOutputShape(t,e);if(t.length===0)return e;let o=e.slice(0,e.length-t.length);for(let n=0;n<t.length;++n){let s=e[e.length-t.length+n],a=t[n];if(s==null||a==null||s<0||a<0)o.push(null);else if(s===1)o.push(a);else if(a===1)o.push(s);else{if(s!==a)throw new z("Operands could not be broadcast together with shapes "+JSON.stringify(e)+" "+JSON.stringify(t));o.push(s)}}return o}build(e){if(Array.isArray(e)&&!Array.isArray(e[0])&&(e=[Je(e)]),e=e,e.length<2)throw new z(`A merge layer should be called on an Array of at least 2 inputs. Got ${e.length} input(s).`);let t=[];for(let s of e)s!=null&&s[0]!==null&&t.push(s[0]);if(t=es(t),t.length>1)throw new z(`Can not merge tensors with different batch sizes. Got tensors with shapes: ${JSON.stringify(e)}.`);let o=e[0]==null?null:e[0].slice(1);for(let s=1;s<e.length;++s){let a=e[s]==null?null:e[s].slice(1);o=this.computeElementwiseOpOutputShape(o,a)}let n=e.map(s=>s.length);e.indexOf(null)===-1&&es(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=Ls(n);for(let a of e){let i=a.rank;for(let l=0;l<s-i;++l)a=Va(a,1);o.push(a)}return this.mergeFunction(o)}else{let s=!1;for(let l of e){let u=l.rank;if(u==null){let c=l.shape,p=c[0],m=c.slice(1).concat([p]),f=l.reshape([p].concat(ts(c.slice(1))));f=Ue(f,[1,0]),f=f.reshape(m),o.push(f),s=!0}else if(u>1){let c=Lr(1,u).concat([0]);o.push(Ue(l,c)),s=!0}else o.push(l)}let a=this.mergeFunction(o),i=a.rank;if(s){if(i==null){let l=a.shape,u=l.length,c=l[u-1],p=[c].concat(l.slice(0,l.length-1));a=Ue(a.reshape([-1,c]),[1,0]).reshape(p)}else if(i>1){let l=[i-1].concat(Lr(0,i-1));a=Ue(a,l)}}return a}}else return this.mergeFunction(e)})}computeOutputShape(e){e=e;let t;e[0]==null?t=null:t=e[0].slice(1);for(let n=1;n<e.length;++n){let s=e[n]==null?null:e[n].slice(1);t=this.computeElementwiseOpOutputShape(t,s)}let o=[];for(let n of e)n!=null&&n[0]!==null&&o.push(n[0]);return o=es(o),o.length===1?t=o.concat(t):t=[null].concat(t),t}computeMask(e,t){return V(()=>{if(t==null)return null;if(!Array.isArray(t))throw new z("`mask` should be an Array");if(!Array.isArray(e))throw new z("`inputs` should be an Array");if(t.length!==e.length)throw new z(`The Array 'inputs' and 'mask' are expected to have the same length, but have different lengths (${e.length} vs ${t.length})`);if(t.every(n=>n==null))return null;t=t.map(n=>n==null?n:ir(n,0));let o=t[0];for(let n=1;n<t.length-1;++n)o=dr(o,t[n]);return o})}},Dd=class extends Al{constructor(e){super(e)}mergeFunction(e){return V(()=>{let t=e[0].clone();for(let o=1;o<e.length;++o)t=ee(t,e[o]);return t})}};Dd.className="Add";Q.registerClass(Dd);var $d=class extends Al{constructor(e){super(e)}mergeFunction(e){return V(()=>{let t=e[0].clone();for(let o=1;o<e.length;++o)t=O(t,e[o]);return t})}};$d.className="Multiply";Q.registerClass($d);var Rd=class extends Al{constructor(e){super(e)}mergeFunction(e){return V(()=>{let t=e[0].clone();for(let o=1;o<e.length;++o)t=ee(t,e[o]);return O(1/e.length,t)})}};Rd.className="Average";Q.registerClass(Rd);var Fd=class extends Al{constructor(e){super(e)}mergeFunction(e){return V(()=>{let t=e[0];for(let o=1;o<e.length;++o)t=Yr(t,e[o]);return t})}};Fd.className="Maximum";Q.registerClass(Fd);var Od=class extends Al{constructor(e){super(e)}mergeFunction(e){return V(()=>{let t=e[0];for(let o=1;o<e.length;++o)t=As(t,e[o]);return t})}};Od.className="Minimum";Q.registerClass(Od);var Pd=class extends Al{constructor(e){super(e);this.DEFAULT_AXIS=-1,e==null&&(e={}),this.axis=e.axis==null?this.DEFAULT_AXIS:e.axis,this.supportsMasking=!0,this.reshapeRequired=!1}build(e){if(!(Array.isArray(e)&&Array.isArray(e[0]))||e.length===1)throw new z("A `Concatenate` layer should be called on a list of at least 2 inputs");e=e;let t=!0;for(let n of e)if(n!=null){t=!1;break}if(t)return;let o=[];for(let n=0;n<e.length;++n){let s=e[n].slice();s.splice(this.axis,1);let a=!1;for(let i of o)if(x.arraysEqual(i,s)){a=!0;break}a||o.push(s)}if(o.length>1)throw new z("A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got input shapes: "+JSON.stringify(e))}mergeFunction(e){return V(()=>Sp(e,this.axis))}computeOutputShape(e){if(!(Array.isArray(e)&&Array.isArray(e[0])))throw new z("A `Concatenate` layer should be called on a list of inputs.");let t=e,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 z("`mask` should be an array for Concatenate");if(!Array.isArray(e))throw new z("`inputs` should be an array for Concatenate");if(t.length!==e.length)throw new z(`Mismatch in the length of mask (${t.length}) and the legnth of inputs (${e.length})`);return V(()=>{let o=!0;if(t.forEach(a=>{if(a!=null){o=!1;return}}),o)return null;let n=[];for(let a=0;a<e.length;++a)t[a]==null?n.push(er(e[a]).asType("bool")):t[a].rank<e[a].rank?n.push(ir(t[a],-1)):n.push(t[a]);let s=Ze(n,this.axis);return bu(s,-1,!1)})}getConfig(){let e={axis:this.axis},t=super.getConfig();return Object.assign(e,t),e}};Pd.className="Concatenate";Q.registerClass(Pd);function Md(r,e){for(;r<0;)r+=e;return r}function A9(r,e,t){if(r.shape.length>3||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;u<a;++u)l.push(1);e=e.reshape(e.shape.concat(l))}else if(n>o){a=n-o;let l=[];for(let u=0;u<a;++u)l.push(1);r=r.reshape(r.shape.concat(l))}else a=0;let i;if(r.shape.length===2&&e.shape.length===2)s[0]===s[1]?i=r.mul(e).sum(s[0]):i=r.transpose([1,0]).mul(e).sum(s[1]);else{let l=s[0]!==r.shape.length-1,u=s[1]===e.shape.length-1;i=r.matMul(e,l,u)}if(a>0){let l;o>n?l=o+n-3:l=o-1;let u=[];for(let c=l;c<l+a;++c)u.push(c);i=i.squeeze(u)}return i.shape.length===1&&(i=i.expandDims(1)),i})}var Ld=class extends Al{constructor(e){super(e);this.axes=e.axes,this.normalize=e.normalize==null?!1:e.normalize,this.supportsMasking=!0,this.reshapeRequired=!1}build(e){x.assert(Array.isArray(e)&&e.length===2&&Array.isArray(e[0])&&Array.isArray(e[1]),()=>"A `Dot` layer should be called on a list of exactly 2 inputs.");let t=e[0],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 z(`Dimension incompatibility: ${t[n[0]]} !== ${o[n[1]]}`)}mergeFunction(e){if(e.length!==2)throw new z(`A \`Dot\` layer must be called on exactly 2 inputs, but received ${e.length} input(s).`);let t=e[0],o=e[1],n;return Array.isArray(this.axes)?n=this.axes.map((s,a)=>Md(s,e[a].shape.length)):n=[Md(this.axes,t.shape.length),Md(this.axes,o.shape.length)],this.normalize&&(t=Zf(t,n[0]),o=Zf(o,n[1])),A9(t,o,n)}interpretAxes(e,t){let o;return Array.isArray(this.axes)?o=this.axes:o=[Md(this.axes,e.length),Md(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";Q.registerClass(Ld);var zd=class extends Me{constructor(e){super(e);this.supportsMasking=!0,this.stddev=e.stddev}computeOutputShape(e){return e}getConfig(){let e=super.getConfig(),t={stddev:this.stddev};return Object.assign(t,e),t}call(e,t){return V(()=>{this.invokeCallHook(e,t);let o=Fe(e);return bl(()=>Tp(o.shape,0,this.stddev).add(o),()=>o,t.training||!1)})}};zd.className="GaussianNoise";Q.registerClass(zd);var Bd=class extends Me{constructor(e){super(e);this.supportsMasking=!0,this.rate=e.rate}computeOutputShape(e){return e}getConfig(){let e=super.getConfig(),t={rate:this.rate};return Object.assign(t,e),t}call(e,t){return V(()=>{this.invokeCallHook(e,t);let o=Fe(e);return this.rate>0&&this.rate<1?bl(()=>{let s=Math.sqrt(this.rate/(1-this.rate));return o.mul(Tp(o.shape,1,s))},()=>o,t.training||!1):o})}};Bd.className="GaussianDropout";Q.registerClass(Bd);var Vd=class extends Me{constructor(e){super(e);this.supportsMasking=!0,this.rate=e.rate,this.noiseShape=e.noiseShape}_getNoiseShape(e){return this.noiseShape||Fe(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 bl(()=>{let s=Fe(e),a=1.6732632423543772,i=1.0507009873554805,l=-a*i,u=io(Es(o),this.rate);u=Ba(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)},()=>Fe(e),t.training||!1)}return e})}};Vd.className="AlphaDropout";Q.registerClass(Vd);function Gd(r,e,t,o,n,s=.001){let a;if(r.rank===2)a=gw(r,e,t,o,n,s);else if(r.rank===3)a=xw(r,e,t,o,n,s);else if(r.rank===4)a=yw(r,e,t,o,n,s);else throw new Se(`batchNormalization is not implemented for array of rank ${r.rank} yet`);return a}function E9(r,e,t,o,n=.001){return V(()=>{let s=Xc(r,o),a=s.mean,i=s.variance;return[Gd(r,a,i,t,e,n),a,i]})}function D9(r,e,t,o,n=.001){return V(()=>{let s=Xc(r,o),a=s.mean,i=s.variance,l=[];for(let d of Lr(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[Gd(r,u,c,m,p,n),a,i]})}function $9(r,e,t,o,n=.001){return x.arraysEqual(o.slice().sort(),Lr(0,r.rank-1))?E9(r,e,t,o,n):D9(r,e,t,o,n)}var Wd=class extends Me{constructor(e){e==null&&(e={}),super(e),this.supportsMasking=!0,this.axis=e.axis==null?-1:e.axis,this.momentum=e.momentum==null?.99:e.momentum,this.epsilon=e.epsilon==null?.001:e.epsilon,this.center=e.center==null?!0:e.center,this.scale=e.scale==null?!0:e.scale,this.betaInitializer=pt(e.betaInitializer||"zeros"),this.gammaInitializer=pt(e.gammaInitializer||"ones"),this.movingMeanInitializer=pt(e.movingMeanInitializer||"zeros"),this.movingVarianceInitializer=pt(e.movingVarianceInitializer||"ones"),this.betaConstraint=Ot(e.betaConstraint),this.gammaConstraint=Ot(e.gammaConstraint),this.betaRegularizer=bt(e.betaRegularizer),this.gammaRegularizer=bt(e.gammaRegularizer)}build(e){e=Je(e);let t=this.axis>=0?this.axis:this.axis+e.length,o=e[t];if(o==null)throw new z(`Axis ${t} of input tensor should have a defined dimension but the layer received an input with shape ${JSON.stringify(e)}.`);this.inputSpec=[new St({ndim:e.length,axes:{[t]: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=Fe(e),s=n.shape,a=s.length,i=Lr(0,a),l=this.axis>=0?this.axis:this.axis+a;i.splice(l,1);let u=Zn(1,a);u[l]=s[l];let c=i.slice();c.sort();let p=!x.arraysEqual(c,Lr(0,a).slice(0,a-1)),m=()=>{if(p){let b=this.movingMean.read().reshape(u),w=this.movingVariance.read().reshape(u),k=this.center?this.beta.read().reshape(u):null,v=this.scale?this.gamma.read().reshape(u):null;return Gd(n,b,w,k,v,this.epsilon)}else return Gd(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]=$9(n,this.gamma.read(),this.beta.read(),i,this.epsilon),g=(b,w,k)=>{V(()=>{let v=1-k,D=b.read(),A=D.sub(w).mul(v);b.write(D.sub(A))})};return(()=>{g(this.movingMean,d,this.momentum),g(this.movingVariance,h,this.momentum)})(),f})}getConfig(){let e={axis:this.axis,momentum:this.momentum,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:_t(this.betaInitializer),gammaInitializer:_t(this.gammaInitializer),movingMeanInitializer:_t(this.movingMeanInitializer),movingVarianceInitializer:_t(this.movingVarianceInitializer),betaRegularizer:st(this.betaRegularizer),gammaRegularizer:st(this.gammaRegularizer),betaConstraint:Ft(this.betaConstraint),gammaConstraint:Ft(this.gammaConstraint)},t=super.getConfig();return Object.assign(e,t),e}};Wd.className="BatchNormalization";Q.registerClass(Wd);var jd=class extends Me{constructor(e){if(e==null&&(e={}),super(e),this.axis=e.axis==null?-1:e.axis,typeof this.axis=="number"){if(!Number.isInteger(this.axis))throw new Error(`Expected axis to be an integer, but received ${this.axis}`)}else if(Array.isArray(this.axis)){for(let t of this.axis)if(!Number.isInteger(t))throw new Error(`Expected axis to be an array of integers, but received ${JSON.stringify(this.axis)}`)}else throw new Error(`Expected axis to be an integer or an array of integers, but received ${JSON.stringify(this.axis)}`);this.epsilon=e.epsilon==null?.001:e.epsilon,this.center=e.center==null?!0:e.center,this.scale=e.scale==null?!0:e.scale,this.betaInitializer=pt(e.betaInitializer||"zeros"),this.gammaInitializer=pt(e.gammaInitializer||"ones"),this.betaRegularizer=bt(e.betaRegularizer),this.gammaRegularizer=bt(e.gammaRegularizer),this.supportsMasking=!0}build(e){e=Je(e);let t=e.length;typeof this.axis=="number"&&(this.axis=[this.axis]);for(let s=0;s<this.axis.length;++s)this.axis[s]<0&&(this.axis[s]+=t);for(let s of this.axis)if(s<0||s>=t)throw new Error(`Invalid axis: ${s}`);if(this.axis.length!==es(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=Fe(e),n=o.shape,s=n.length;return V(()=>{let a=!0,{mean:i,variance:l}=Xc(o,this.axis,a),u=Zn(1,s);for(let h of this.axis)u[h]=n[h];let c=h=>h!=null&&h.shape.length!==s&&this.axis!==[s-1]?h.reshape(u):h,p=c(this.gamma.read()),m=c(this.beta.read()),f=[],d=[];for(let h=0;h<s;++h)this.axis.indexOf(h)!==-1?(f.push(n[h]),d.push(1)):(f.push(1),d.push(n[h]));return i=i.tile(f),l=l.tile(f),p=p.tile(d),m=m.tile(d),Gd(o,i,l,m,p,this.epsilon)})}getConfig(){let e={axis:this.axis,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:_t(this.betaInitializer),gammaInitializer:_t(this.gammaInitializer),betaRegularizer:st(this.betaRegularizer),gammaRegularizer:st(this.gammaRegularizer)},t=super.getConfig();return Object.assign(e,t),e}};jd.className="LayerNormalization";Q.registerClass(jd);function R9(r,e,t){return V(()=>{if(r.rank!==4)throw new z(`temporalPadding expects input tensor to be 4-D, but received a ${r.rank}-D tensor.`);if(e==null&&(e=[[1,1],[1,1]]),e.length!==2||e[0].length!==2||e[1].length!==2)throw new z("spatial2dPadding expects `padding` to be an Array of two Arrays, each of which is an Array of two integers.");if(t==null&&(t=Zr()),t!=="channelsLast"&&t!=="channelsFirst")throw new z(`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]],Rr(r,o)})}var Ud=class extends Me{constructor(e){if(e==null&&(e={}),super(e),this.dataFormat=e.dataFormat==null?Zr():e.dataFormat,e.padding==null)this.padding=[[1,1],[1,1]];else if(typeof e.padding=="number")this.padding=[[e.padding,e.padding],[e.padding,e.padding]];else{if(e.padding=e.padding,e.padding.length!==2)throw new z(`ZeroPadding2D expects padding to be a length-2 array, but received a length-${e.padding.length} array.`);let t,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 z(`ZeroPadding2D expects height padding to be a length-2 array, but received a length-${e.padding[0].length} array.`);if(t=e.padding[0],e.padding[1].length!==2)throw new z(`ZeroPadding2D expects width padding to be a length-2 array, but received a length-${e.padding[1].length} array.`);o=e.padding[1]}this.padding=[t,o]}this.inputSpec=[new St({ndim:4})]}computeOutputShape(e){e=Je(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(()=>R9(Fe(e),this.padding,this.dataFormat))}getConfig(){let e={padding:this.padding,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}};Ud.className="ZeroPadding2D";Q.registerClass(Ud);function Ox(r,e,t,o,n,s){return V(()=>{$t(n),xC(s),Jr(o),t==null&&(t=[1,1]),o==null&&(o="valid"),n==null&&(n=Zr()),s==null&&(s="max"),r=md(r,n);let a,i=o==="same"?"same":"valid";return s==="max"?a=Na(r,e,t,i):a=wa(r,e,t,i),n==="channelsFirst"&&(a=Ue(a,[0,3,1,2])),a})}function bL(r,e,t,o,n,s){return V(()=>{$t(n),xC(s),Jr(o),t==null&&(t=[1,1,1]),o==null&&(o="valid"),n==null&&(n=Zr()),s==null&&(s="max"),r=HC(r,n);let a,i=o==="same"?"same":"valid";return s==="max"?a=zm(r,e,t,i):a=Tm(r,e,t,i),n==="channelsFirst"&&(a=Ue(a,[0,4,1,2,3])),a})}var ZC=class extends Me{constructor(e){if(e.poolSize==null&&(e.poolSize=2),super(e),typeof e.poolSize=="number")this.poolSize=[e.poolSize];else if(Array.isArray(e.poolSize)&&e.poolSize.length===1&&typeof e.poolSize[0]=="number")this.poolSize=e.poolSize;else throw new z(`poolSize for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.poolSize)}`);if(Ut(this.poolSize,"poolSize"),e.strides==null)this.strides=this.poolSize;else if(typeof e.strides=="number")this.strides=[e.strides];else if(Array.isArray(e.strides)&&e.strides.length===1&&typeof e.strides[0]=="number")this.strides=e.strides;else throw new z(`strides for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.strides)}`);Ut(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,Jr(this.padding),this.inputSpec=[new St({ndim:3})]}computeOutputShape(e){e=Je(e);let t=fo(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=Va(Fe(e),2);let o=this.poolingFunction(Fe(e),[this.poolSize[0],1],[this.strides[0],1],this.padding,"channelsLast");return Co(o,[2])})}getConfig(){let e={poolSize:this.poolSize,padding:this.padding,strides:this.strides},t=super.getConfig();return Object.assign(e,t),e}},Hd=class extends ZC{constructor(e){super(e)}poolingFunction(e,t,o,n,s){return $t(s),Jr(n),Ox(e,t,o,n,s,"max")}};Hd.className="MaxPooling1D";Q.registerClass(Hd);var qd=class extends ZC{constructor(e){super(e)}poolingFunction(e,t,o,n,s){return $t(s),Jr(n),Ox(e,t,o,n,s,"avg")}};qd.className="AveragePooling1D";Q.registerClass(qd);var JC=class extends Me{constructor(e){if(e.poolSize==null&&(e.poolSize=[2,2]),super(e),this.poolSize=Array.isArray(e.poolSize)?e.poolSize:[e.poolSize,e.poolSize],e.strides==null)this.strides=this.poolSize;else if(Array.isArray(e.strides)){if(e.strides.length!==2)throw new z(`If the strides property of a 2D pooling layer is an Array, it is expected to have a length of 2, but received length ${e.strides.length}.`);this.strides=e.strides}else this.strides=[e.strides,e.strides];Ut(this.poolSize,"poolSize"),Ut(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,$t(this.dataFormat),Jr(this.padding),this.inputSpec=[new St({ndim:4})]}computeOutputShape(e){e=Je(e);let t=this.dataFormat==="channelsFirst"?e[2]:e[1],o=this.dataFormat==="channelsFirst"?e[3]:e[2];return t=fo(t,this.poolSize[0],this.padding,this.strides[0]),o=fo(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(Fe(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}},Kd=class extends JC{constructor(e){super(e)}poolingFunction(e,t,o,n,s){return $t(s),Jr(n),Ox(e,t,o,n,s,"max")}};Kd.className="MaxPooling2D";Q.registerClass(Kd);var Xd=class extends JC{constructor(e){super(e)}poolingFunction(e,t,o,n,s){return $t(s),Jr(n),Ox(e,t,o,n,s,"avg")}};Xd.className="AveragePooling2D";Q.registerClass(Xd);var QC=class extends Me{constructor(e){if(e.poolSize==null&&(e.poolSize=[2,2,2]),super(e),this.poolSize=Array.isArray(e.poolSize)?e.poolSize:[e.poolSize,e.poolSize,e.poolSize],e.strides==null)this.strides=this.poolSize;else if(Array.isArray(e.strides)){if(e.strides.length!==3)throw new z(`If the strides property of a 3D pooling layer is an Array, it is expected to have a length of 3, but received length ${e.strides.length}.`);this.strides=e.strides}else this.strides=[e.strides,e.strides,e.strides];Ut(this.poolSize,"poolSize"),Ut(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,$t(this.dataFormat),Jr(this.padding),this.inputSpec=[new St({ndim:5})]}computeOutputShape(e){e=Je(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=fo(t,this.poolSize[0],this.padding,this.strides[0]),o=fo(o,this.poolSize[1],this.padding,this.strides[1]),n=fo(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(Fe(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 QC{constructor(e){super(e)}poolingFunction(e,t,o,n,s){return $t(s),Jr(n),bL(e,t,o,n,s,"max")}};Yd.className="MaxPooling3D";Q.registerClass(Yd);var Zd=class extends QC{constructor(e){super(e)}poolingFunction(e,t,o,n,s){return $t(s),Jr(n),bL(e,t,o,n,s,"avg")}};Zd.className="AveragePooling3D";Q.registerClass(Zd);var eI=class extends Me{constructor(e){super(e);this.inputSpec=[new St({ndim:3})]}computeOutputShape(e){return[e[0],e[2]]}call(e,t){throw new Se}},Jd=class extends eI{constructor(e){super(e||{})}call(e,t){return V(()=>{let o=Fe(e);return dt(o,1)})}};Jd.className="GlobalAveragePooling1D";Q.registerClass(Jd);var Qd=class extends eI{constructor(e){super(e||{})}call(e,t){return V(()=>{let o=Fe(e);return lr(o,1)})}};Qd.className="GlobalMaxPooling1D";Q.registerClass(Qd);var tI=class extends Me{constructor(e){super(e);this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,$t(this.dataFormat),this.inputSpec=[new St({ndim:4})]}computeOutputShape(e){return e=e,this.dataFormat==="channelsLast"?[e[0],e[3]]:[e[0],e[1]]}call(e,t){throw new Se}getConfig(){let e={dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}},eh=class extends tI{call(e,t){return V(()=>{let o=Fe(e);return this.dataFormat==="channelsLast"?dt(o,[1,2]):dt(o,[2,3])})}};eh.className="GlobalAveragePooling2D";Q.registerClass(eh);var th=class extends tI{call(e,t){return V(()=>{let o=Fe(e);return this.dataFormat==="channelsLast"?lr(o,[1,2]):lr(o,[2,3])})}};th.className="GlobalMaxPooling2D";Q.registerClass(th);var rI=class extends Me{constructor(e){super(e);this.layer=e.layer}build(e){this.built=!0}get trainable(){return this.layer!=null?this.layer.trainable:!1}set trainable(e){this.layer!=null&&(this.layer.trainable=e)}get trainableWeights(){return this.layer.trainableWeights}get nonTrainableWeights(){return this.layer.nonTrainableWeights}get updates(){return this.layer._updates}get losses(){return this.layer.losses}getWeights(){return this.layer.getWeights()}setWeights(e){this.layer.setWeights(e)}getConfig(){let e={layer:{className:this.layer.getClassName(),config:this.layer.getConfig()}},t=super.getConfig();return Object.assign(e,t),e}setFastWeightInitDuringBuild(e){super.setFastWeightInitDuringBuild(e),this.layer!=null&&this.layer.setFastWeightInitDuringBuild(e)}static fromConfig(e,t,o={}){let n=t.layer,s=Qr(n,o);delete t.layer;let a={layer:s};return Object.assign(a,t),new e(a)}},rh=class extends rI{constructor(e){super(e);this.supportsMasking=!0}build(e){if(e=Je(e),e.length<3)throw new z(`TimeDistributed layer expects an input shape >= 3D, but received input shape ${JSON.stringify(e)}`);this.inputSpec=[{shape:e}];let t=[e[0]].concat(e.slice(2));this.layer.built||(this.layer.build(t),this.layer.built=!0),super.build(e)}computeOutputShape(e){e=Je(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=Fe(e),XC((a,i)=>[Fe(this.layer.call(a,t)),[]],e,[],!1,null,null,!1,!0)[1]))}};rh.className="TimeDistributed";Q.registerClass(rh);function F9(r){Wi(CM,"BidirectionalMergeMode",r)}var O9="concat",oh=class extends rI{constructor(e){super(e);let t=e.layer.getConfig(),o={};o.className=e.layer.getClassName(),o.config=t,this.forwardLayer=Qr(o),t.goBackwards=t.goBackwards!==!0;let n={};if(n.className=e.layer.getClassName(),n.config=t,this.backwardLayer=Qr(n),this.forwardLayer.name="forward_"+this.forwardLayer.name,this.backwardLayer.name="backward_"+this.backwardLayer.name,this.mergeMode=e.mergeMode===void 0?O9:e.mergeMode,F9(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()):gr(n)}apply(e,t){let o=t==null?null:t.initialState,n=t==null?null:t.constants;t==null&&(t={});let s=KC(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 z("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 St({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 Br;for(let u of a)if(u instanceof Br!==l)throw new z("The initial state of a Bidirectional layer cannot be specified as a mix of symbolic and non-symbolic tensors");if(l){let u=[e].concat(a),c=this.inputSpec.concat(i),p=this.inputSpec;this.inputSpec=c;let m=super.apply(u,t);return this.inputSpec=p,m}else return super.apply(e,t)}call(e,t){return 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=Ht(s,1));let i;return this.mergeMode==="concat"?i=Sp([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){Ms(this.forwardLayer.name,()=>{this.forwardLayer.build(e)}),Ms(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=Qr(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)}};oh.className="Bidirectional";Q.registerClass(oh);function P9(r){return new ji(r)}function M9(r){return new ld(r)}function L9(r){return new sd(r)}function z9(r){return new id(r)}function B9(r){return new ad(r)}function V9(r){return new cd(r)}function G9(r){return new ud(r)}function W9(r){return new dc(r)}function j9(r){return new Nl(r)}function U9(r){return new fd(r)}function H9(r){return new fc(r)}function q9(r){return new dd(r)}function K9(r){return new hd(r)}function X9(r){return new gd(r)}function Y9(r){return new xd(r)}function Z9(r){return new Id(r)}function J9(r){return new vd(r)}function Q9(r){return new Kp(r)}function eQ(r){return new _d(r)}function tQ(r){return new Cd(r)}function rQ(r){return new Nd(r)}function oQ(r){return new Sd(r)}function nQ(r){return new Td(r)}function sQ(r){return new Ed(r)}function iQ(r){return new Dd(r)}function aQ(r){return new Rd(r)}function lQ(r){return new Pd(r)}function uQ(r){return new Fd(r)}function cQ(r){return new Od(r)}function pQ(r){return new $d(r)}function mQ(r){return new Ld(r)}function fQ(r){return new Wd(r)}function dQ(r){return new jd(r)}function hQ(r){return new Ud(r)}function nI(r){return new qd(r)}function gQ(r){return nI(r)}function xQ(r){return nI(r)}function sI(r){return new Xd(r)}function yQ(r){return sI(r)}function bQ(r){return sI(r)}function iI(r){return new Zd(r)}function wQ(r){return iI(r)}function kQ(r){return iI(r)}function _Q(r){return new Jd(r)}function vQ(r){return new eh(r)}function wL(r){return new Qd(r)}function kL(r){return new th(r)}function _L(r){return new Hd(r)}function vL(r){return new Kd(r)}function CQ(r){return new Yd(r)}function IQ(r){return new bd(r)}function NQ(r){return new Hp(r)}function SQ(r){return new wd(r)}function TQ(r){return new Tl(r)}function AQ(r){return new yd(r)}function EQ(r){return new Up(r)}function DQ(r){return new kd(r)}function $Q(r){return new qp(r)}function RQ(r){return new ho(r)}function FQ(r){return new jp(r)}function OQ(r){return new oh(r)}function PQ(r){return new rh(r)}var MQ=wL,LQ=kL,zQ=_L,BQ=vL;function VQ(r){return new zd(r)}function GQ(r){return new Bd(r)}function WQ(r){return new Vd(r)}function jQ(r){return new Ad(r)}var aI={};Ke(aI,{MAPE:()=>tee,MSE:()=>nee,binaryAccuracy:()=>UQ,binaryCrossentropy:()=>HQ,categoricalAccuracy:()=>KQ,categoricalCrossentropy:()=>XQ,cosineProximity:()=>JQ,mape:()=>ree,meanAbsoluteError:()=>QQ,meanAbsolutePercentageError:()=>eee,meanSquaredError:()=>oee,mse:()=>see,precision:()=>YQ,recall:()=>ZQ,sparseCategoricalAccuracy:()=>qQ});function UQ(r,e){return ed(r,e)}function HQ(r,e){return Cx(r,e)}function qQ(r,e){return Ix(r,e)}function KQ(r,e){return td(r,e)}function XQ(r,e){return rd(r,e)}function YQ(r,e){return vC(r,e)}function ZQ(r,e){return jM(r,e)}function JQ(r,e){return Jf(r,e)}function QQ(r,e){return Lp(r,e)}function eee(r,e){return vl(r,e)}function tee(r,e){return vl(r,e)}function ree(r,e){return vl(r,e)}function oee(r,e){return Hi(r,e)}function nee(r,e){return Hi(r,e)}function see(r,e){return Hi(r,e)}var lI={};Ke(lI,{modelFromJSON:()=>lL});var uI={};Ke(uI,{l1:()=>aee,l1l2:()=>iee,l2:()=>lee});function iee(r){return new pc(r)}function aee(r){return dL(r)}function lee(r){return hL(r)}var Px=class extends _l{constructor(){super(...arguments);this.model=null}setModel(e){if(!(e instanceof To))throw new Error("model must be a LayersModel, not some other Container");this.model=e}};function Mx(r,e){return r<e}function CL(r,e){return r>e}var Lx=class extends Px{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=Mx:this.mode==="max"?this.monitorFunc=CL:this.monitor.indexOf("acc")!==-1?this.monitorFunc=CL:this.monitorFunc=Mx,this.monitorFunc===Mx&&(this.minDelta*=-1)}async onTrainBegin(e){this.wait=0,this.stoppedEpoch=0,this.baseline!=null?this.best=this.baseline:this.best=this.monitorFunc===Mx?Infinity:-Infinity}async onEpochEnd(e,t){await Ui(t);let o=this.getMonitorValue(t);o!=null&&(this.monitorFunc(o-this.minDelta,this.best)?(this.best=o,this.wait=0):(this.wait++,this.wait>=this.patience&&(this.stoppedEpoch=e,this.model.stopTraining=!0)))}async onTrainEnd(e){this.stoppedEpoch>0&&this.verbose&&console.log(`Epoch ${this.stoppedEpoch}: early stopping.`)}getMonitorValue(e){e==null&&(e={});let t=e[this.monitor];return t==null&&console.warn(`Metric for EarlyStopping ${this.monitor} is not available. Available metrics are: ${Object.keys(e)}`),t}};function uee(r){return new Lx(r)}var IL={earlyStopping:uee};var os;(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"})(os||(os={}));var NL;(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={}))})(NL||(NL={}));var cI={};function SL(r,e){let t={tfOpName:r,category:"custom",inputs:[],attrs:[],customExecutor:e};cI[r]=t}function zx(r){return cI[r]}function TL(r){delete cI[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 xr(e.inputNames[s.inputIndexStart],t,o,n);if(s.type==="tensors")return e.inputNames.slice(i,l).map(m=>xr(m,t,o,n));let u=xr(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 xr(r,e,t,o){let[n,s]=eo(r);if(o!=null){let i=o.getHashTableHandleByName(n);if(i!=null)return i}let a=t.currentContextIds.find(i=>!!e[Bx(n,i)]);return a!==void 0?e[Bx(n,a)][s]:void 0}function AL(r,e,t){return e[Bx(r,t.currentContextId)]}function Gs(r,e){let[t,o]=eo(r);return[Bx(t,e&&e.currentContextId),o]}function Bx(r,e){return e?`${r}-${e}`:r}function eo(r){let e=r.split(":");return e.length===1?[r,0]:[e[0],Number(e[e.length-1])]}function nh(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 Ws(r){return r.kept?r:Po(r)}var pI={};Ke(pI,{json:()=>cee});var cee=[{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 mI={};Ke(mI,{json:()=>pee});var pee=[{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 fI={};Ke(fI,{json:()=>mee});var mee=[{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 dI={};Ke(dI,{json:()=>fee});var fee=[{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 hI={};Ke(hI,{json:()=>dee});var dee=[{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 gI={};Ke(gI,{json:()=>hee});var hee=[{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 xI={};Ke(xI,{json:()=>gee});var gee=[{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 yI={};Ke(yI,{json:()=>xee});var xee=[{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 bI={};Ke(bI,{json:()=>yee});var yee=[{tfOpName:"HashTable",category:"hash_table",inputs:[],attrs:[{tfName:"shared_name",name:"sharedName",type:"string"},{tfName:"use_node_name_sharing",name:"useNodeNameSharing",type:"bool"},{tfName:"key_dtype",name:"keyDType",type:"dtype"},{tfName:"value_dtype",name:"valueDType",type:"dtype"}]},{tfOpName:"HashTableV2",category:"hash_table",inputs:[],attrs:[{tfName:"shared_name",name:"sharedName",type:"string"},{tfName:"use_node_name_sharing",name:"useNodeNameSharing",type:"bool"},{tfName:"key_dtype",name:"keyDType",type:"dtype"},{tfName:"value_dtype",name:"valueDType",type:"dtype"}]},{tfOpName:"LookupTableImport",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"values",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableImportV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"values",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableFind",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableFindV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableSize",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"}]},{tfOpName:"LookupTableSizeV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"}]}];var wI={};Ke(wI,{json:()=>bee});var bee=[{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 kI={};Ke(kI,{json:()=>wee});var wee=[{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 _I={};Ke(_I,{json:()=>kee});var kee=[{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 vI={};Ke(vI,{json:()=>_ee});var _ee=[{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 CI={};Ke(CI,{json:()=>vee});var vee=[{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 II={};Ke(II,{json:()=>Cee});var Cee=[{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 NI={};Ke(NI,{json:()=>Iee});var Iee=[{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 SI={};Ke(SI,{json:()=>Nee});var Nee=[{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 Vx=class{static get Instance(){return this._instance||(this._instance=new this)}constructor(){let e=[pI,mI,fI,dI,hI,gI,xI,kI,wI,yI,_I,vI,CI,II,NI,SI,bI],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]=Gs(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]=Gs(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]=Gs(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=zx(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=Gx(e.attr,s.tfName,s.defaultValue),i===void 0&&!!s.tfDeprecatedName&&(i=Gx(e.attr,s.tfDeprecatedName,s.defaultValue));break;case"string[]":i=Xx(e.attr,s.tfName,s.defaultValue),i===void 0&&!!s.tfDeprecatedName&&(i=Xx(e.attr,s.tfDeprecatedName,s.defaultValue));break;case"number":i=jx(e.attr,s.tfName,s.defaultValue||0),i===void 0&&!!s.tfDeprecatedName&&(i=jx(e.attr,s.tfDeprecatedName,s.defaultValue));break;case"number[]":i=Kx(e.attr,s.tfName,s.defaultValue),i===void 0&&!!s.tfDeprecatedName&&(i=Kx(e.attr,s.tfDeprecatedName,s.defaultValue));break;case"bool":i=Wx(e.attr,s.tfName,s.defaultValue),i===void 0&&!!s.tfDeprecatedName&&(i=Wx(e.attr,s.tfDeprecatedName,s.defaultValue));break;case"bool[]":i=Zx(e.attr,s.tfName,s.defaultValue),i===void 0&&!!s.tfDeprecatedName&&(i=Zx(e.attr,s.tfDeprecatedName,s.defaultValue));break;case"shape":i=qx(e.attr,s.tfName,s.defaultValue),i===void 0&&!!s.tfDeprecatedName&&(i=qx(e.attr,s.tfDeprecatedName,s.defaultValue));break;case"shape[]":i=Yx(e.attr,s.tfName,s.defaultValue),i===void 0&&!!s.tfDeprecatedName&&(i=Yx(e.attr,s.tfDeprecatedName,s.defaultValue));break;case"dtype":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=Hx(e.attr,s.tfName,s.defaultValue),i===void 0&&!!s.tfDeprecatedName&&(i=Hx(e.attr,s.tfDeprecatedName,s.defaultValue));break;case"func":i=EL(e.attr,s.tfName,s.defaultValue),i===void 0&&!!s.tfDeprecatedName&&(i=EL(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]=Gs(p.name),f={name:m,op:"Placeholder",inputs:[],inputNames:[],category:"graph",inputParams:{},attrParams:{dtype:{value:TI(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]=Gs(f);m.inputs.push(s[d]),s[d].children.push(m)})});let u=e.ret;e.signature.outputArg.forEach(p=>{let[m,f]=Gs(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 See(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 DL(r,e){let t=Array.isArray(r)?String.fromCharCode.apply(null,r):See(r);return e?t:t.toLowerCase()}function Gx(r,e,t,o=!1){let n=r[e];return n!=null?DL(n.s,o):t}function Wx(r,e,t){let o=r[e];return o?o.b:t}function jx(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 TI(r){switch(typeof r=="string"&&(r=os[r]),r){case os.DT_FLOAT:return"float32";case os.DT_INT32:case os.DT_INT64:case os.DT_INT8:case os.DT_UINT8:return"int32";case os.DT_BOOL:return"bool";case os.DT_DOUBLE:return"float32";case os.DT_STRING:return"string";default:return null}}function EL(r,e,t){let o=r[e];return o&&o.func?o.func.name:t}function Ux(r,e,t){let o=r[e];return o&&o.type?TI(o.type):t}function Hx(r,e,t){let o=r[e];return o&&o.list&&o.list.type?o.list.type.map(n=>TI(n)):t}function $L(r){if(!r.unknownRank)return r.dim!=null?r.dim.map(e=>typeof e.size=="number"?e.size:parseInt(e.size,10)):[]}function qx(r,e,t){let o=r[e];return o&&o.shape?$L(o.shape):t}function Kx(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 Xx(r,e,t,o=!1){let n=r[e];return n&&n.list&&n.list.s?n.list.s.map(s=>DL(s,o)):t}function Yx(r,e,t){let o=r[e];return o&&o.list&&o.list.shape?o.list.shape.map(n=>$L(n)):t}function Zx(r,e,t){let o=r[e];return o&&o.list&&o.list.b?o.list.b:t}var AI=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 xr(e,this.tensorMap,this.context)}getAttr(e,t){let o=this.node.rawAttrs[e];if(o.tensor!=null)return xr(e,this.tensorMap,this.context);if(o.i!=null||o.f!=null)return jx(this.node.rawAttrs,e,t);if(o.s!=null)return Gx(this.node.rawAttrs,e,t);if(o.b!=null)return Wx(this.node.rawAttrs,e,t);if(o.shape!=null)return qx(this.node.rawAttrs,e,t);if(o.type!=null)return Ux(this.node.rawAttrs,e,t);if(o.list!=null){if(o.list.i!=null||o.list.f!=null)return Kx(this.node.rawAttrs,e,t);if(o.list.s!=null)return Xx(this.node.rawAttrs,e,t);if(o.list.shape!=null)return Yx(this.node.rawAttrs,e,t);if(o.list.b!=null)return Zx(this.node.rawAttrs,e,t);if(o.list.type!=null)return Hx(this.node.rawAttrs,e,t)}return t}};var RL=(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[mw(C("tensors",r,e,t))];case"FloorMod":case"Mod":return[Vm(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[me(C("a",r,e,t),C("b",r,e,t))];case"DivNoNan":return[Rm(C("a",r,e,t),C("b",r,e,t))];case"FloorDiv":return[yu(C("a",r,e,t),C("b",r,e,t))];case"Sub":return[ce(C("a",r,e,t),C("b",r,e,t))];case"Minimum":return[As(C("a",r,e,t),C("b",r,e,t))];case"Maximum":return[Yr(C("a",r,e,t),C("b",r,e,t))];case"Pow":return[Fr(C("a",r,e,t),C("b",r,e,t))];case"SquaredDifference":return[zu(C("a",r,e,t),C("b",r,e,t))];default:throw TypeError(`Node type ${r.op} is not implemented`)}};var FL=(r,e,t)=>{switch(r.op){case"Abs":case"ComplexAbs":return[It(C("x",r,e,t))];case"Acos":return[wm(C("x",r,e,t))];case"Acosh":return[km(C("x",r,e,t))];case"Asin":return[vm(C("x",r,e,t))];case"Asinh":return[Cm(C("x",r,e,t))];case"Atan":return[Im(C("x",r,e,t))];case"Atan2":return[Nm(C("x",r,e,t),C("y",r,e,t))];case"Atanh":return[Sm(C("x",r,e,t))];case"Ceil":return[Am(C("x",r,e,t))];case"Complex":return[_o(C("real",r,e,t),C("imag",r,e,t))];case"Cos":return[_a(C("x",r,e,t))];case"Cosh":return[Cu(C("x",r,e,t))];case"Elu":return[Ns(C("x",r,e,t))];case"Erf":return[Fm(C("x",r,e,t))];case"Exp":return[Yt(C("x",r,e,t))];case"Expm1":return[Om(C("x",r,e,t))];case"Floor":return[Ss(C("x",r,e,t))];case"Log":return[ar(C("x",r,e,t))];case"Log1p":return[Tu(C("x",r,e,t))];case"Imag":return[Nu(C("x",r,e,t))];case"Neg":return[He(C("x",r,e,t))];case"Reciprocal":return[Wm(C("x",r,e,t))];case"Real":return[ll(C("x",r,e,t))];case"Relu":return[Nr(C("x",r,e,t))];case"Round":return[jm(C("x",r,e,t))];case"Selu":return[Ou(C("x",r,e,t))];case"Sigmoid":return[qr(C("x",r,e,t))];case"Sin":return[Pu(C("x",r,e,t))];case"Sign":return[Hm(C("x",r,e,t))];case"Sinh":return[Mu(C("x",r,e,t))];case"Softplus":return[Ts(C("x",r,e,t))];case"Sqrt":return[gt(C("x",r,e,t))];case"Square":return[Oe(C("x",r,e,t))];case"Tanh":return[Oi(C("x",r,e,t))];case"Tan":return[Ym(C("x",r,e,t))];case"ClipByValue":return[sr(C("x",r,e,t),C("clipValueMin",r,e,t),C("clipValueMax",r,e,t))];case"Relu6":return[Ru(C("x",r,e,t))];case"Rsqrt":return[Fu(xr(r.inputNames[0],e,t))];case"Prod":return[Du(C("x",r,e,t),C("axes",r,e,t))];case"LeakyRelu":return[Ca(C("x",r,e,t),C("alpha",r,e,t))];case"Prelu":return[Ta(C("x",r,e,t),C("alpha",r,e,t))];default:throw TypeError(`Node type ${r.op} is not implemented`)}};function Ao(r,e,t=""){if(!(typeof r=="number"||typeof e=="number")){x.assert(r.length===e.length,()=>t+` Shapes ${r} and ${e} must match`);for(let o=0;o<r.length;o++){let n=r[o],s=e[o];x.assert(n<0||s<0||n===s,()=>t+` Shapes ${r} and ${e} must match`)}}}function OL(r){return!(typeof r=="number"||r.some(e=>e<0))}function Xp(r,e,t){let o=Jx(r,t),n=!OL(o);if(n&&e.length===0)throw new Error(`Tried to calculate elements of an empty list with non-fully-defined elementShape: ${o}`);if(n&&e.forEach(s=>{o=Jx(s.shape,o)}),!OL(o))throw new Error(`Non-fully-defined elementShape: ${o}`);return o}function Jx(r,e){if(typeof r=="number")return e;if(typeof e=="number")return r;if(r.length!==e.length)throw new Error(`Incompatible ranks during merge: ${r} vs. ${e}`);let t=[];for(let o=0;o<r.length;++o){let n=r[o],s=e[o];if(n>=0&&s>=0&&n!==s)throw new Error(`Incompatible shape during merge: ${r} vs. ${e}`);t[o]=n>=0?n:s}return t}var EI=class{constructor(e,t,o,n,s,a,i){this.name=e,this.dtype=t,this.maxSize=o,this.elementShape=n,this.identicalElementShapes=s,this.dynamicSize=a,this.clearAfterRead=i,this.tensors=[],this.closed_=!1,this.idTensor=le(0),Et(this.idTensor)}get id(){return this.idTensor.id}get closed(){return this.closed_}clearAndClose(e){this.tensors.forEach(t=>{(e==null||!e.has(t.tensor.id))&&t.tensor.dispose()}),this.tensors=[],this.closed_=!0,this.idTensor.dispose()}size(){return this.tensors.length}read(e){if(this.closed_)throw new Error(`TensorArray ${this.name} has already been closed.`);if(e<0||e>=this.size())throw new Error(`Tried to read from index ${e}, but array size is: ${this.size()}`);let t=this.tensors[e];if(t.cleared)throw new Error(`TensorArray ${this.name}: Could not read index ${e} twice because it was cleared after a previous read (perhaps try setting clear_after_read = false?).`);return this.clearAfterRead&&(t.cleared=!0),t.read=!0,t.tensor}readMany(e){return e.map(t=>this.read(t))}write(e,t){if(this.closed_)throw new Error(`TensorArray ${this.name} has already been closed.`);if(e<0||!this.dynamicSize&&e>=this.maxSize)throw new Error(`Tried to write to index ${e}, but array is not resizeable and size is: ${this.maxSize}`);let o=this.tensors[e]||{};if(t.dtype!==this.dtype)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e},
|
|
because the value dtype is ${t.dtype}, but TensorArray dtype is ${this.dtype}.`);if(this.size()===0&&(this.elementShape==null||this.elementShape.length===0)&&(this.elementShape=t.shape),Ao(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,Et(t),o.written=!0,this.tensors[e]=o}writeMany(e,t){if(e.length!==t.length)throw new Error(`TensorArray ${this.name}: could not write multiple tensors,because the index size: ${e.length} is not the same as tensors size: ${t.length}.`);e.forEach((o,n)=>this.write(o,t[n]))}gather(e,t){if(!!t&&t!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but gather requested dtype ${t}`);if(e)e=e.slice(0,this.size());else{e=[];for(let n=0;n<this.size();n++)e.push(n)}if(e.length===0)return $r([],[0].concat(this.elementShape));let o=this.readMany(e);return Ao(this.elementShape,o[0].shape,"TensorArray shape mismatch: "),Bt(o,0)}concat(e){if(!!e&&e!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but concat requested dtype ${e}`);if(this.size()===0)return $r([],[0].concat(this.elementShape));let t=[];for(let n=0;n<this.size();n++)t.push(n);let o=this.readMany(t);return Ao(this.elementShape,o[0].shape,`TensorArray shape mismatch: tensor array shape (${this.elementShape}) vs first tensor shape (${o[0].shape})`),Ze(o,0)}scatter(e,t){if(t.dtype!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but tensor has dtype ${t.dtype}`);if(e.length!==t.shape[0])throw new Error(`Expected len(indices) == tensor.shape[0], but saw: ${e.length} vs. ${t.shape[0]}`);let o=Math.max(...e);if(!this.dynamicSize&&o>=this.maxSize)throw new Error(`Max index must be < array size (${o} vs. ${this.maxSize})`);this.writeMany(e,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=M(t,[1,o,s]);for(let l=0;l<e.length;++l){let u=l===0?0:n[l-1],c=[0,u,0],p=[1,e[l],s];a[l]=M(Re(t,c,p),this.elementShape)}return a});let i=[];for(let l=0;l<e.length;l++)i[l]=l;this.writeMany(i,a)}};var hc=class{constructor(e,t,o,n=-1){this.tensors=e,this.elementShape=t,this.elementDtype=o,e!=null&&e.forEach(s=>{if(o!==s.dtype)throw new Error(`Invalid data types; op elements ${o}, but list elements ${s.dtype}`);Ao(t,s.shape,"TensorList shape mismatch: "),Et(s)}),this.idTensor=le(0),this.maxNumElements=n,Et(this.idTensor)}get id(){return this.idTensor.id}copy(){return new hc([...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.`);Ao(e,this.elementShape,"TensorList shape mismatch: ");let n=Xp(this.elementShape,this.tensors,e);return V(()=>{let s=this.tensors.map(a=>M(a,n));return Bt(s,0)})}popBack(e,t){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);if(this.size()===0)throw new Error("Trying to pop from an empty list.");let o=Xp(this.elementShape,this.tensors,e),n=this.tensors.pop();return Ao(n.shape,e,"TensorList shape mismatch: "),M(n,o)}pushBack(e){if(e.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${this.elementDtype}`);if(Ao(e.shape,this.elementShape,"TensorList shape mismatch: "),this.maxNumElements===this.size())throw new Error("Trying to push element into a full list.");Et(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.`);Ao(this.tensors[e].shape,t,"TensorList shape mismatch: ");let n=Xp(this.elementShape,this.tensors,t);return M(this.tensors[e],n)}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.`);Ao(this.elementShape,t.shape,"TensorList shape mismatch: "),Et(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}`);Ao(this.elementShape,o,"TensorList shape mismatch: "),e=e.slice(0,this.size());let n=Xp(this.elementShape,this.tensors,o);return e.length===0?$r([],[0].concat(n)):V(()=>{let s=e.map(a=>M(this.tensors[a],n));return Bt(s,0)})}concat(e,t){if(!!e&&e!==this.elementDtype)throw new Error(`TensorList dtype is ${this.elementDtype} but concat requested dtype ${e}`);Ao(this.elementShape,t,"TensorList shape mismatch: ");let o=Xp(this.elementShape,this.tensors,t);return this.size()===0?$r([],[0].concat(o)):V(()=>{let n=this.tensors.map(s=>M(s,o));return Ze(n,0)})}};function PL(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);Ao(n,e,"TensorList shape mismatch: ");let s=cr(r);return new hc(s,e,o)}function ML(r,e,t){return new hc([],r,e,t)}function LL(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 hc([],t,r.dtype,o),a=cr(r,0);return e.forEach((i,l)=>{s.setItem(i,a[l])}),s}function zL(r,e,t){let o=0,n=e.map(c=>(o+=c,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=r.shape.slice(1),a=Jx(s,t),i=o===0?0:r.size/o,l=V(()=>{let c=[];r=M(r,[1,o,i]);for(let p=0;p<e.length;++p){let m=p===0?0:n[p-1],f=[0,m,0],d=[1,e[p],i];c[p]=M(Re(r,f,d),a)}return r.dispose(),c}),u=new hc([],t,r.dtype,e.length);for(let c=0;c<l.length;c++)u.setItem(c,l[c]);return u}var BL=async(r,e,t)=>{switch(r.op){case"If":case"StatelessIf":{let o=C("thenBranch",r,e,t),n=C("elseBranch",r,e,t),s=C("cond",r,e,t),a=C("args",r,e,t);return(await s.data())[0]?t.functionMap[o].executeFunctionAsync(a,t.tensorArrayMap,t.tensorListMap):t.functionMap[n].executeFunctionAsync(a,t.tensorArrayMap,t.tensorListMap)}case"While":case"StatelessWhile":{let o=C("body",r,e,t),n=C("cond",r,e,t),s=C("args",r,e,t),a=await t.functionMap[n].executeFunctionAsync(s,t.tensorArrayMap,t.tensorListMap),i=s.map(c=>c.id),l=await a[0].data();a.forEach(c=>{!c.kept&&i.indexOf(c.id)===-1&&c.dispose()});let u=s;for(;l[0];){let c=u;u=await t.functionMap[o].executeFunctionAsync(u,t.tensorArrayMap,t.tensorListMap);let p=u.map(f=>f.id);c.forEach(f=>{!f.kept&&i.indexOf(f.id)===-1&&p.indexOf(f.id)===-1&&f.dispose()});let m=await t.functionMap[n].executeFunctionAsync(u,t.tensorArrayMap,t.tensorListMap);l=await m[0].data(),m.forEach(f=>{!f.kept&&i.indexOf(f.id)===-1&&p.indexOf(f.id)===-1&&f.dispose()})}return u}case"LoopCond":{let o=C("pred",r,e,t);return[Ws(o)]}case"Switch":{let o=C("pred",r,e,t),n=C("data",r,e,t);return n.kept||(n=Ws(n)),(await o.data())[0]?[void 0,n]:[n,void 0]}case"Merge":{let o=r.inputNames.find(n=>xr(n,e,t)!==void 0);if(o){let n=xr(o,e,t);return[Ws(n)]}return}case"Enter":{let o=C("frameName",r,e,t),n=C("tensor",r,e,t);return t.enterFrame(o),[Ws(n)]}case"Exit":{let o=C("tensor",r,e,t);return t.exitFrame(),[Ws(o)]}case"NextIteration":{let o=C("tensor",r,e,t);return t.nextIteration(),[Ws(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 EI(u,n,o,s,l,a,i);return t.addTensorArray(c),[c.idTensor,le(1)]}case"TensorArrayWriteV3":{let o=C("tensorArrayId",r,e,t),n=C("index",r,e,t),s=C("tensor",r,e,t),a=t.getTensorArray(o.id);return a.write(n,s),[a.idTensor]}case"TensorArrayReadV3":{let o=C("tensorArrayId",r,e,t),n=C("index",r,e,t);return[t.getTensorArray(o.id).read(n)]}case"TensorArrayGatherV3":{let o=C("tensorArrayId",r,e,t),n=C("indices",r,e,t),s=C("dtype",r,e,t);return[t.getTensorArray(o.id).gather(n,s)]}case"TensorArrayScatterV3":{let o=C("tensorArrayId",r,e,t),n=C("indices",r,e,t),s=C("tensor",r,e,t),a=t.getTensorArray(o.id);return a.scatter(n,s),[a.idTensor]}case"TensorArrayConcatV3":{let o=C("tensorArrayId",r,e,t),n=t.getTensorArray(o.id),s=C("dtype",r,e,t);return[n.concat(s)]}case"TensorArraySplitV3":{let o=C("tensorArrayId",r,e,t),n=C("tensor",r,e,t),s=C("lengths",r,e,t),a=t.getTensorArray(o.id);return a.split(s,n),[a.idTensor]}case"TensorArraySizeV3":{let o=C("tensorArrayId",r,e,t),n=t.getTensorArray(o.id);return[le(n.size(),"int32")]}case"TensorArrayCloseV3":{let o=C("tensorArrayId",r,e,t),n=t.getTensorArray(o.id);return n.clearAndClose(),[n.idTensor]}case"TensorListSetItem":{let o=C("tensorListId",r,e,t),n=C("index",r,e,t),s=C("tensor",r,e,t),a=t.getTensorList(o.id);return a.setItem(n,s),[a.idTensor]}case"TensorListGetItem":{let o=C("tensorListId",r,e,t),n=C("index",r,e,t),s=C("elementShape",r,e,t),a=C("elementDType",r,e,t);return[t.getTensorList(o.id).getItem(n,s,a)]}case"TensorListScatterV2":case"TensorListScatter":{let o=C("indices",r,e,t),n=C("tensor",r,e,t),s=C("elementShape",r,e,t),a=C("numElements",r,e,t),i=LL(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=ML(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=PL(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=zL(o,s,n);return t.addTensorList(a),[a.idTensor]}default:throw TypeError(`Node type ${r.op} is not implemented`)}};function VL(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=nh(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 GL=(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[_u(C("x",r,e,t),C("filter",r,e,t),o,n,s,a)]}case"Conv2D":{let o=C("strides",r,e,t),n=nh(r,e,t),s=C("dataFormat",r,e,t).toUpperCase(),a=C("dilations",r,e,t);return[Kr(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}=VL(r,e,t);return[Gn.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}=VL(r,e,t);return[Gn.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=nh(r,e,t);return[vu(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=nh(r,e,t),s=C("dilations",r,e,t),a=C("dataFormat",r,e,t).toUpperCase();return[Is(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[Em(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[wa(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[Na(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}=Ow(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[Tm(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[zm(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[$m(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 WL=(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[va(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[Aw(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[Pw(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[Cs(o,n,s,a)]}case"Ones":return[Ir(C("shape",r,e,t),C("dtype",r,e,t))];case"OnesLike":return[er(C("x",r,e,t))];case"RandomUniform":return[Es(C("shape",r,e,t),C("minval",r,e,t),C("maxval",r,e,t),C("dtype",r,e,t))];case"Range":{let o=C("start",r,e,t),n=C("stop",r,e,t),s=C("step",r,e,t);return[Zc(o,n,s,C("dtype",r,e,t))]}case"TruncatedNormal":{let o=C("shape",r,e,t),n=C("mean",r,e,t),s=C("stdDev",r,e,t),a=C("seed",r,e,t);return[Bu(o,n,s,C("dtype",r,e,t),a)]}case"Zeros":return[ht(C("shape",r,e,t),C("dtype",r,e,t))];case"ZerosLike":return[Ce(C("x",r,e,t))];default:throw TypeError(`Node type ${r.op} is not implemented`)}};function DI(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 jL=async(r,e,t)=>{switch(r.op){case"NonMaxSuppressionV5":{let{boxes:o,scores:n,maxOutputSize:s,iouThreshold:a,scoreThreshold:i,softNmsSigma:l}=DI(r,e,t),u=await $s.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}=DI(r,e,t),l=C("padToMaxOutputSize",r,e,t),u=await $s.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}=DI(r,e,t);return[await $s.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 Hw(C("x",r,e,t),C("y",r,e,t));default:throw TypeError(`Node type ${r.op} is not implemented`)}};var UL=(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=Qc(o);return[n.values,n.indices]}case"UniqueV2":{let o=C("x",r,e,t),n=C("axis",r,e,t),s=Qc(o,n);return[s.values,s.indices]}default:throw TypeError(`Node type ${r.op} is not implemented`)}};var HL=(r,e,t)=>{switch(r.op){case"Const":return e[r.name];case"PlaceholderWithDefault":let o=C("default",r,e,t);return[xr(r.name,e,t)||o];case"Placeholder":return[xr(r.name,e,t)];case"Identity":case"StopGradient":case"FakeQuantWithMinMaxVars":{let u=C("x",r,e,t);return[Ws(u)]}case"IdentityN":return C("x",r,e,t).map(u=>Ws(u));case"Snapshot":let n=C("x",r,e,t);return[Ws(n)];case"Shape":return[Vt(C("x",r,e,t).shape,"int32")];case"ShapeN":return C("x",r,e,t).map(u=>Vt(u.shape));case"Size":return[le(C("x",r,e,t).size,"int32")];case"Rank":return[le(C("x",r,e,t).rank,"int32")];case"NoOp":return[le(1)];case"Print":let s=C("x",r,e,t),a=C("data",r,e,t),i=C("message",r,e,t),l=C("summarize",r,e,t);console.warn("The graph has a tf.print() operation,usually used for debugging, which slows down performance."),console.log(i);for(let u=0;u<a.length;u++)console.log(Array.prototype.slice.call(a[u].dataSync()).slice(0,l));return[s];default:throw TypeError(`Node type ${r.op} is not implemented`)}};var $I=class{constructor(e,t){this.keyDType=e,this.valueDType=t,this.handle=le(0),this.tensorMap=new Map,Et(this.handle)}get id(){return this.handle.id}clearAndClose(){this.tensorMap.forEach(e=>e.dispose()),this.tensorMap.clear(),this.handle.dispose()}size(){return this.tensorMap.size}tensorSize(){return le(this.size(),"int32")}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<s;i++){let l=o[i],u=n[i];Et(u),this.tensorMap.set(l,u)}return this.handle})}async find(e,t){this.checkKeyAndValueTensor(e,t);let o=await e.data();return V(()=>{let n=[];for(let s=0;s<o.length;s++){let a=o[s],i=this.findWithDefault(a,t);n.push(i)}return Bt(n)})}findWithDefault(e,t){let o=this.tensorMap.get(e);return o!=null?o:t}checkKeyAndValueTensor(e,t){if(e.dtype!==this.keyDType)throw new Error(`Expect key dtype ${this.keyDType}, but got ${e.dtype}`);if(t.dtype!==this.valueDType)throw new Error(`Expect value dtype ${this.valueDType}, but got ${t.dtype}`)}};var qL=async(r,e,t,o)=>{switch(r.op){case"HashTable":case"HashTableV2":{let n=C("keyDType",r,e,t),s=C("valueDType",r,e,t),a=new $I(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)]}case"LookupTableSize":case"LookupTableSizeV2":{let n=C("tableHandle",r,e,t,o);return[o.getHashTableById(n.id).tensorSize()]}default:throw TypeError(`Node type ${r.op} is not implemented`)}};var KL=(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[$s.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[$s.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[$s.cropAndResize(o,n,s,a,i,l)]}default:throw TypeError(`Node type ${r.op} is not implemented`)}};var XL=(r,e,t)=>{switch(r.op){case"Equal":return[vo(C("a",r,e,t),C("b",r,e,t))];case"NotEqual":return[Vn(C("a",r,e,t),C("b",r,e,t))];case"Greater":return[Qt(C("a",r,e,t),C("b",r,e,t))];case"GreaterEqual":return[io(C("a",r,e,t),C("b",r,e,t))];case"Less":return[Su(C("a",r,e,t),C("b",r,e,t))];case"LessEqual":return[Bo(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[Ia(C("a",r,e,t))];case"LogicalOr":return[Eu(C("a",r,e,t),C("b",r,e,t))];case"Select":case"SelectV2":return[Dt(C("condition",r,e,t),C("a",r,e,t),C("b",r,e,t))];default:throw TypeError(`Node type ${r.op} is not implemented`)}};var YL=(r,e,t)=>{switch(r.op){case"BatchMatMul":case"BatchMatMulV2":case"MatMul":return[We(C("a",r,e,t),C("b",r,e,t),C("transposeA",r,e,t),C("transposeB",r,e,t))];case"Transpose":return[Ue(C("x",r,e,t),C("perm",r,e,t))];case"_FusedMatMul":let[o,n]=C("fusedOps",r,e,t),s=o==="biasadd",a=n==="prelu",i=C("numArgs",r,e,t),l=C("leakyreluAlpha",r,e,t);if(s){if(a&&i!==2)throw new Error("Fused MatMul with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!a&&i!==1)throw new Error("Fused MatMul with BiasAdd must have one extra argument: bias.")}let[u,c]=C("args",r,e,t);return[Gn.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 ZL=(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[Pm(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[Aa(C("x",r,e,t))];case"LogSoftmax":return[Au(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 JL=(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[dt(C("x",r,e,t),a,i)]}case"Min":{let a=C("axis",r,e,t),i=C("keepDims",r,e,t);return[Pi(C("x",r,e,t),a,i)]}case"Sum":{let a=C("axis",r,e,t),i=C("keepDims",r,e,t);return[ge(C("x",r,e,t),a,i)]}case"All":{let a=C("axis",r,e,t),i=C("keepDims",r,e,t);return[bu(C("x",r,e,t),a,i)]}case"Any":{let a=C("axis",r,e,t),i=C("keepDims",r,e,t);return[sl(C("x",r,e,t),a,i)]}case"ArgMax":{let a=C("axis",r,e,t);return[il(C("x",r,e,t),a)]}case"ArgMin":{let a=C("axis",r,e,t);return[_m(C("x",r,e,t),a)]}case"Prod":{let a=C("axis",r,e,t),i=C("keepDims",r,e,t);return[Du(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[Iu(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[bw(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[Cw(a,i,l,u)]}default:throw TypeError(`Node type ${r.op} is not implemented`)}};var QL=(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),[Ze(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<o.length;a++)o[a]&&n.push(a);let s=C("x",r,e,t);return[Ht(s,n)]}case"ReverseV2":{let o=C("axis",r,e,t),n=C("x",r,e,t);return[Ht(n,o)]}case"Slice":{let o=C("begin",r,e,t),n=C("size",r,e,t);return[Re(C("x",r,e,t),o,n)]}case"StridedSlice":{let o=C("begin",r,e,t),n=C("end",r,e,t),s=C("strides",r,e,t),a=C("beginMask",r,e,t),i=C("endMask",r,e,t),l=C("ellipsisMask",r,e,t),u=C("newAxisMask",r,e,t),c=C("shrinkAxisMask",r,e,t),p=C("x",r,e,t);return[Xm(p,o,n,s,a,i,l,u,c)]}case"Pack":return V(()=>{let o=C("axis",r,e,t),n=C("tensors",r,e,t),s=n[0].shape,a=Co(n[0]).shape,i=n.map(l=>{let u=x.arraysEqual(l.shape,s);if(!u&&!x.arraysEqual(Co(l).shape,a))throw new Error("the input tensors shape does not match");return u?l:M(l,s)});return[Bt(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[Xw(o,n,s)]}case"GatherNd":{let o=C("x",r,e,t),n=C("indices",r,e,t);return[Yw(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 ez=(r,e,t)=>{switch(r.op){case"FFT":return[Ea(C("x",r,e,t))];case"IFFT":return[Mi(C("x",r,e,t))];case"RFFT":return[Da(C("x",r,e,t))];case"IRFFT":return[Lu(C("x",r,e,t))];default:throw TypeError(`Node type ${r.op} is not implemented`)}};var tz=(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[ir(C("x",r,e,t),o)]}case"Squeeze":{let o=C("axis",r,e,t);return[Co(C("x",r,e,t),o)]}case"Reshape":return[M(C("x",r,e,t),C("shape",r,e,t))];case"MirrorPad":return[Bm(C("x",r,e,t),C("padding",r,e,t),C("mode",r,e,t))];case"PadV2":case"Pad":return[Rr(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[Sa(C("x",r,e,t),o,n)]}case"BatchToSpaceND":{let o=C("blockShape",r,e,t),n=C("crops",r,e,t);return[ka(C("x",r,e,t),o,n)]}case"DepthToSpace":{let o=C("blockSize",r,e,t),n=C("dataFormat",r,e,t).toUpperCase();return[Dm(C("x",r,e,t),o,n)]}case"BroadcastTo":return[al(C("x",r,e,t),C("shape",r,e,t))];default:throw TypeError(`Node type ${r.op} is not implemented`)}};function RI(r,e,t,o){let n=((s,a,i)=>{switch(s.category){case"arithmetic":return V(()=>RL(s,a,i));case"basic_math":return V(()=>FL(s,a,i));case"control":return BL(s,a,i);case"convolution":return V(()=>GL(s,a,i));case"creation":return V(()=>WL(s,a,i));case"dynamic":return jL(s,a,i);case"evaluation":return V(()=>UL(s,a,i));case"image":return V(()=>KL(s,a,i));case"graph":return V(()=>HL(s,a,i));case"logical":return V(()=>XL(s,a,i));case"matrices":return V(()=>YL(s,a,i));case"normalization":return V(()=>ZL(s,a,i));case"reduction":return V(()=>JL(s,a,i));case"slice_join":return V(()=>QL(s,a,i));case"spectral":return V(()=>ez(s,a,i));case"transformation":return V(()=>tz(s,a,i));case"hash_table":return qL(s,a,i,o);case"custom":let l=zx(s.op);if(l&&l.customExecutor)return l.customExecutor(new AI(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 Qx=class{constructor(e={},t={},o={},n={}){this.weightMap=e,this.tensorArrayMap=t,this.tensorListMap=o,this.functionMap=n,this.rootContext={id:0,frameName:"",iterationId:0},this.contexts=[this.rootContext],this.lastId=0,this.generateCurrentContextIds()}newFrame(e,t){return{id:e,frameName:t,iterationId:0}}set currentContext(e){this.contexts!==e&&(this.contexts=e,this.generateCurrentContextIds())}get currentContext(){return this.contexts}get currentContextId(){return this._currentContextIds[0]}get currentContextIds(){return this._currentContextIds}generateCurrentContextIds(){let e=[];for(let t=0;t<this.contexts.length-1;t++){let o=this.contexts.slice(0,this.contexts.length-t);e.push(this.contextIdforContexts(o))}e.push(""),this._currentContextIds=e}contextIdforContexts(e){return e?e.map(t=>t.id===0&&t.iterationId===0?"":`${t.frameName}-${t.iterationId}`).join("/"):""}enterFrame(e){this.contexts&&(this.lastId++,this.contexts=this.contexts.slice(),this.contexts.push(this.newFrame(this.lastId,e)),this._currentContextIds.unshift(this.contextIdforContexts(this.contexts)))}exitFrame(){if(this.contexts&&this.contexts.length>1)this.contexts=this.contexts.slice(),this.contexts.splice(-1),this.currentContextIds.shift();else throw new Error("Cannot exit frame, the context is empty")}nextIteration(){if(this.contexts&&this.contexts.length>0){this.contexts=this.contexts.slice(),this.lastId++;let e=Object.assign({},this.contexts[this.contexts.length-1]);e.iterationId+=1,e.id=this.lastId,this.contexts.splice(-1,1,e),this._currentContextIds.splice(0,1,this.contextIdforContexts(this.contexts))}else throw new Error("Cannot increase frame iteration, the context is empty")}getWeight(e){return this.weightMap[e]}addTensorArray(e){this.tensorArrayMap[e.id]=e}getTensorArray(e){return this.tensorArrayMap[e]}addTensorList(e){this.tensorListMap[e.id]=e}getTensorList(e){return this.tensorListMap[e]}dispose(e){for(let t in this.tensorArrayMap)this.tensorArrayMap[t].clearAndClose(e);for(let t in this.tensorListMap)this.tensorListMap[t].clearAndClose(e)}};function OI(r,e,t,o){let n=new Set,s=[],a=null,i=null,l=new Set,u=Object.keys(r).map(m=>eo(m)[0]),c=[];o!=null&&(c=o.map(m=>eo(m.name)[0]));let p=[...e];for(;p.length>0;){let m=p.pop();if((FI(m)||Tee(m)||Aee(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 rz(r,e,t){let{usedNodes:o,inputs:n}=t,s=[],a=Object.keys(n).map(c=>eo(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 Eee=["Switch","Merge","Enter","Exit","NextIteration","StatelessIf","StatelessWhile","if","While"],Dee=["NonMaxSuppressionV2","NonMaxSuppressionV3","NonMaxSuppressionV5","Where"],$ee=["HashTable","HashTableV2","LookupTableImport","LookupTableImportV2","LookupTableFind","LookupTableFindV2","LookupTableSize","LookupTableSizeV2"];function FI(r){return Eee.indexOf(r.op)>=0}function Tee(r){return Dee.indexOf(r.op)>=0}function Aee(r){return $ee.indexOf(r.op)>=0}var Yp=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 Yp(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=OI(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 rz(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[eo(p)[0]]),s=t.map(p=>eo(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 Qx(this.weightMap,u,c,this.functionExecutorMap),m=Object.assign({},this.weightMap);Object.keys(e).forEach(h=>{let[g,y]=eo(h),b=[];b[y]=e[h],m[g]=b});let f=this.getFrozenTensorIds(m),d={};for(let h=0;h<l.length;h++){let g=l[h];if(!m[g.name]){let y=RI(g,m,p,this._resourceManager);if(x.isPromise(y))throw new Error(`The execution of the op '${g.op}' returned a promise. Please use model.executeAsync() instead.`);m[g.name]=y,this.checkTensorForDisposal(g.name,g,m,p,f,s,d)}}return this.parent==null&&p.dispose(f),t.map(h=>xr(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=AL(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 Qx(this.weightMap,n,s,this.functionExecutorMap),i=await this.executeWithControlFlow(e,a,t,o),l=t.map(m=>xr(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(w=>this.graph.nodes[eo(w)[0]]),i=o.map(w=>eo(w)[0]),l=i.map(w=>this.graph.nodes[w]);l.length===0&&(l=this._outputs);let{usedNodes:u,missingInputs:c,dynamicNode:p,syncInputs:m}=OI(e,l,this.weightMap,this._initNodes),f=[...a,...this.graph.weights,...this._initNodes||[]].map(w=>({node:w,contexts:t.currentContext})),d=Object.assign({},this.weightMap);Object.keys(e).forEach(w=>{let[k,v]=eo(w),D=[];D[v]=e[w],d[k]=D});let h={},g=this.getFrozenTensorIds(d),y={};for(;f.length>0;){let w=this.processStack(a,f,t,d,y,g,i,h,u);await Promise.all(w)}p==null&&!n&&console.warn("This model execution did not contain any nodes with control flow or dynamic output shapes. You can use model.execute() instead.");let b=l.filter(w=>!FI(w)&&!xr(w.name,d,t)).map(w=>w.name);if(b.length>0){let w="";throw p!=null&&(w=`Alternatively, to avoid the dynamic ops, use model.execute() and specify the inputs [${m}]`),new Error(`Cannot compute the outputs [${b}] from the provided inputs [${s}]. Consider providing the following inputs: [${c}]. ${w}`)}return d}processStack(e,t,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]=Gs(p.node.name,o)),n[p.node.name]==null){let f=RI(p.node,n,o,this._resourceManager);m||([m]=Gs(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]=Gs(i.name,o);s[l]||!a.has(i.name)||(i.op==="Merge"?i.inputNames.some(u=>!!xr(u,n,o))&&(s[l]=!0,t.push({contexts:o.currentContext,node:i})):i.inputNames.every(u=>!!xr(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]=eo(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]=eo(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]=eo(t);if(!this.graph.nodes[o])throw new Error(`The output '${t}' is not found in the graph`)})}};var PI=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 Ree="?tfjs-format=file",Fee="model.json",ey=class{constructor(e,t={}){this.modelUrl=e,this.loadOptions=t,this.version="n/a",t==null&&(this.loadOptions={}),this.resourceManager=new PI}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 Yp(Vx.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=Vx.Instance.transformGraph(e.modelInitializer);this.initializer=new Yp(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 Ve)&&!Array.isArray(e))return e;if(e=Array.isArray(e)?e:[e],e.length!==this.inputNodes.length)throw new Error(`Input tensor count mismatch,the graph model has ${this.inputNodes.length} placeholders, while there are ${e.length} input tensors.`);return this.inputNodes.reduce((t,o,n)=>(t[o]=e[n],t),{})}normalizeOutputs(e){return e=e||this.outputNodes,Array.isArray(e)?e:[e]}execute(e,t){e=this.normalizeInputs(e),t=this.normalizeOutputs(t);let o=this.executor.execute(e,t);return o.length>1?o:o[0]}async executeAsync(e,t){e=this.normalizeInputs(e),t=this.normalizeOutputs(t);let o=await this.executor.executeAsync(e,t);return o.length>1?o:o[0]}convertTensorMapToTensorsMap(e){return Object.keys(e).reduce((t,o)=>(t[o]=[e[o]],t),{})}dispose(){this.executor.dispose(),this.initializer&&this.initializer.dispose(),this.resourceManager.dispose()}};async function oz(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}${Fee}${Ree}`);let t=new ey(r,e);return await t.load(),t}var nz="3.3.0";var ay={};Ke(ay,{CSVDataset:()=>uh,Dataset:()=>Ki,FileDataSource:()=>dh,TextLineDataset:()=>ah,URLDataSource:()=>hh,array:()=>Nz,csv:()=>Pz,func:()=>Mz,generator:()=>Lz,microphone:()=>Bz,version_data:()=>Vz,webcam:()=>zz,zip:()=>Sz});var Iz=Tc(Gm());var cz=Tc(Gm());function sz(r,e){return ty(r,e)}function ty(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(El(r)){let s=Array.isArray(r)?[]:{};o.add(r);for(let a in r){let i=r[a],l=ty(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 az(r,e=MI){return iz(r,e)}function iz(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(El(o)){let s=Array.isArray(o)?[]:{};t.add(o);for(let a in o){let i=r.map(u=>u[a]),l=iz(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 MI(r){return r===null?null:El(r[0])?{value:null,recurse:!0}:{value:r,recurse:!1}}async function ry(r,e){let t=new Map;ty(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 ty(r,e,t)}function El(r){return r!=null&&!ArrayBuffer.isView(r)&&(Array.isArray(r)||typeof r=="object"&&!(r instanceof Ve))}function lz(r){return r==null||Oee(r)||Array.isArray(r)||typeof r=="object"&&r instanceof Ve||x.isTypedArray(r)}function Oee(r){return r===null||typeof r!="object"&&typeof r!="function"}function uz(r){return sz(r,Pee)}function Pee(r){return r instanceof Ve?{value:r.clone(),recurse:!1}:El(r)?{value:null,recurse:!0}:{value:r,recurse:!1}}var sh=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 Zp=class extends sh{constructor(){super(Zp.INITIAL_CAPACITY)}isFull(){return!1}push(e){super.isFull()&&this.expand(),super.push(e)}unshift(e){super.isFull()&&this.expand(),super.unshift(e)}expand(){let e=this.capacity*2,t=new Array(e),o=this.length();for(let n=0;n<o;n++)t[n]=this.get(this.wrap(this.begin+n));this.data=t,this.capacity=e,this.doubledCapacity=2*this.capacity,this.begin=0,this.end=o}};Zp.INITIAL_CAPACITY=32;function LI(r){return new pz(r)}function ih(r){return new mz(r)}function fz(r,e){return new zI(r,e)}function hz(r,e=ja.FAIL){return new dz(r,e)}var qt=class{async toArray(){let e=[],t=await this.next();for(;!t.done;)e.push(t.value),t=await this.next();return e}async toArrayForTest(){let e=this.prefetch(100),t=[],o=await e.next();for(;!o.done;)t.push(o.value),o=await e.next();return t}async resolveFully(){let e=await this.next();for(;!e.done;)e=await this.next()}async resolveWhile(e){let t=await this.next(),o=e(t.value);for(;!t.done&&o;)t=await this.next(),o=e(t.value)}handleErrors(e){return new _z(this,e)}filter(e){return new wz(this,e)}map(e){return new kz(this,e)}mapAsync(e){return new BI(this,e)}serialMapAsync(e){return new BI(this,e).serial()}flatmap(e){return new vz(this,e)}async forEachAsync(e){return this.map(e).resolveFully()}async serialForEach(e){return this.serialMapAsync(e).resolveWhile(t=>t===!0)}rowMajorBatch(e,t=!0){return new bz(this,e,t)}columnMajorBatch(e,t=!0,o=MI){return this.rowMajorBatch(e,t).map(s=>az(s,o))}concatenate(e,t){return new zI(LI([this,e]),t)}take(e){return e<0||e==null?this:new yz(this,e)}skip(e){return e<0||e==null?this:new xz(this,e)}prefetch(e){return new VI(this,e)}shuffle(e,t){return new Cz(this,e,t)}serial(){return new gz(this)}},pz=class extends qt{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:uz(e),done:!1}}},mz=class extends qt{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}}},gz=class extends qt{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()}},xz=class extends qt{constructor(e,t){super();this.upstream=e,this.maxCount=t,this.count=0,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> Skip`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){for(;this.count++<this.maxCount;){let e=await this.upstream.next();if(e.done)return e;Ae(e.value)}return this.upstream.next()}},yz=class extends qt{constructor(e,t){super();this.upstream=e,this.maxCount=t,this.count=0}summary(){return`${this.upstream.summary()} -> Take`}async next(){return this.count++>=this.maxCount?{value:null,done:!0}:this.upstream.next()}},bz=class extends qt{constructor(e,t,o=!0){super();this.upstream=e,this.batchSize=t,this.enableSmallLastBatch=o,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> RowMajorBatch`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){let e=[];for(;e.length<this.batchSize;){let t=await this.upstream.next();if(t.done)return this.enableSmallLastBatch&&e.length>0?{value:e,done:!1}:{value:null,done:!0};e.push(t.value)}return{value:e,done:!1}}},wz=class extends qt{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)}}},kz=class extends qt{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}}},_z=class extends qt{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}}}},BI=class extends qt{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}}},Jp=class extends qt{constructor(){super();this.outputQueue=new Zp,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}}},vz=class extends Jp{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}},zI=class extends qt{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}},ja;(function(r){r[r.FAIL=0]="FAIL",r[r.SHORTEST=1]="SHORTEST",r[r.LONGEST=2]="LONGEST"})(ja||(ja={}));var dz=class extends qt{constructor(e,t=ja.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 qt?{value:a.next().then(l=>(t++,l.done&&o++,l.value)),recurse:!1}:{value:null,recurse:!0}}let s=await ry(this.iterators,n);if(t===o)return{value:null,done:!0};if(o>0)switch(this.mismatchMode){case ja.FAIL:throw new Error(`Zipped streams should have the same length. Mismatched at element ${this.count}.`);case ja.SHORTEST:return{value:null,done:!0};case ja.LONGEST:default:}return this.count++,{value:s,done:!1}}async next(){return this.currentPromise=this.nextState(this.currentPromise),this.currentPromise}},VI=class extends qt{constructor(e,t){super();this.upstream=e,this.bufferSize=t,this.buffer=new sh(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()}},Cz=class extends VI{constructor(e,t,o){super(e,t);this.upstream=e,this.windowSize=t,this.upstreamExhausted=!1,this.random=cz.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 Ki=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),go(async()=>(await o.iterator()).columnMajorBatch(e,t,Mee),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,go(async()=>(await t.iterator()).concatenate(await e.iterator()),o)}filter(e){let t=this,o;return this.size===Infinity?o=Infinity:o=null,go(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 go(async()=>(await t.iterator()).map(o=>V(()=>e(o))),this.size)}mapAsync(e){let t=this;return go(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 go(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,go(async()=>{let n=ih(async()=>({value:await t.iterator(),done:!1}));return fz(n.take(e))},o)}skip(e){let t=this,o;return this.size!=null&&e>=0&&this.size>=e?o=this.size-e:this.size!=null&&(this.size<e||e===void 0||e<0)?o=0:o=null,go(async()=>(await t.iterator()).skip(e),o)}shuffle(e,t,o=!0){if(e==null||e<0)throw this.size==null?new RangeError("`Dataset.shuffle()` requires bufferSize to be specified."):new RangeError(`\`Dataset.shuffle()\` requires bufferSize to be specified. If your data fits in main memory (for regular JS objects), and/or GPU memory (for \`tf.Tensor\`s), consider setting bufferSize to the dataset size (${this.size} elements)`);let n=this,s=Iz.alea(t||x.now().toString());return go(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,go(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()}};Ki.MAX_BUFFER_SIZE=1e4;function go(r,e=null){return new class extends Ki{constructor(){super(...arguments);this.size=e}async iterator(){return r()}}}function Nz(r){return go(async()=>LI(r),r.length)}function Sz(r){if(!El(r))throw new Error("The argument to zip() must be an object or array.");let e;if(Array.isArray(r))for(let t=0;t<r.length;t++)e=e==null?r[t].size:Math.min(e,r[t].size);else if(r instanceof Object)for(let t in r)e=e==null?r[t].size:Math.min(e,r[t].size);return go(async()=>{let t=await ry(r,o=>{if(o instanceof Ki)return{value:o.iterator(),recurse:!1};if(El(o))return{value:null,recurse:!0};throw new Error("Leaves of the structure passed to zip() must be Datasets, not primitives.")});return hz(t,ja.SHORTEST)},e)}function Mee(r){if(r===null)return null;let e=r[0];return lz(e)?{value:Lee(r),recurse:!1}:{value:null,recurse:!0}}function Lee(r){if(r.length===0)throw new Error("Can't make a batch of zero elements.");return r[0]instanceof Ve?Bt(r):$r(r)}var ah=class extends Ki{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 oy='"',lh=Symbol("out"),Tz=Symbol("field"),ny=Symbol("quote"),GI=Symbol("quoteafterquote"),Az=Symbol("quoteinquote"),uh=class extends Ki{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 ah(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;s<this.fullColumnNames.length;s++){let a=this.fullColumnNames[s],i=this.columnConfigs?this.columnConfigs[a]:null;if(!(this.configuredColumnsOnly&&!i)){let l=t[s],u=null;if(l==="")if(i&&i.default!==void 0)u=i.default;else{if(i&&(i.required||i.isLabel))throw new Error(`Required column ${a} is empty in this line: ${e}`);u=void 0}else{let c=Number(l);if(isNaN(c))i&&i.dtype==="bool"?u=this.getBoolean(l):u=l;else if(!i||!i.dtype)u=c;else switch(i.dtype){case"float32":u=c;break;case"int32":u=Math.floor(c);break;case"bool":u=this.getBoolean(l);break;default:u=c}}i&&i.isLabel?n[a]=u:o[a]=u}}return Object.keys(n).length===0?o:{xs:o,ys:n}}getBoolean(e){return e==="1"||e.toLowerCase()==="true"?1:0}parseRow(e,t=!0){let o=[],n=0,s=e.length,a=lh;for(let i=0;i<s;i++)switch(a){case lh:switch(e.charAt(i)){case oy:n=i+1,a=ny;break;case this.delimiter:if(n=i+1,this.delimiter===" "&&this.delimWhitespace)break;o.push(""),a=lh;break;default:a=Tz,n=i;break}break;case Tz:switch(e.charAt(i)){case this.delimiter:o.push(e.substring(n,i)),a=lh,n=i+1;break;default:}break;case ny:switch(e.charAt(i)){case oy:a=GI;break;default:}break;case GI:switch(e.charAt(i)){case this.delimiter:o.push(e.substring(n,i-1)),a=lh,n=i+1;break;case oy:a=ny;break;default:a=Az;break}break;case Az:switch(e.charAt(i)){case oy:a=ny;break;default:}break;default:}if(a===GI?o.push(e.substring(n,s-1)):o.push(e.substring(n)),t&&o.length!==this.fullColumnNames.length)throw new Error(`Invalid row in csv file. Should have ${this.fullColumnNames.length} elements in a row, but got ${o}`);return o}};var ch=class extends qt{constructor(e){super();this.microphoneConfig=e,this.isClosed=!1,this.fftSize=e.fftSize||1024;let t=Math.log2(this.fftSize);if(this.fftSize<0||t<4||t>14||!Number.isInteger(t))throw new Error(`Invalid fftSize: it must be a power of 2 between 2 to 4 and 2 to 14, but got ${this.fftSize}`);if(this.numFrames=e.numFramesPerSpectrogram||43,this.sampleRateHz=e.sampleRateHz,this.columnTruncateLength=e.columnTruncateLength||this.fftSize,this.audioTrackConstraints=e.audioTrackConstraints,this.smoothingTimeConstant=e.smoothingTimeConstant||0,this.includeSpectrogram=e.includeSpectrogram!==!1,this.includeWaveform=e.includeWaveform===!0,!this.includeSpectrogram&&!this.includeWaveform)throw new Error("Both includeSpectrogram and includeWaveform are false. At least one type of data should be returned.")}summary(){return"microphone"}static async create(e={}){if(W().get("IS_NODE"))throw new Error("microphone API is only supported in browser environment.");let t=new ch(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),$r(o,t)}};var ph=class extends qt{constructor(e,t){super();if(this.webcamVideoElement=e,this.webcamConfig=t,this.isClosed=!0,this.resize=!1,this.needToResize())if(this.resize=!0,this.cropSize=[this.webcamConfig.resizeHeight,this.webcamConfig.resizeWidth],this.cropBoxInd=Vt([0],"int32"),this.webcamConfig.centerCrop){let o=this.webcamConfig.resizeWidth*1/this.webcamVideoElement.width,n=this.webcamConfig.resizeHeight*1/this.webcamVideoElement.height,s=(1-o)/2,a=(1-n)/2,i=s+o,l=n+a;this.cropBox=Li([a,s,l,i],[1,4])}else this.cropBox=Li([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 ph(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=Xh.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=ir(ne(e,"float32"),0),o;o=$s.cropAndResize(t,this.cropBox,this.cropBoxInd,this.cropSize,"bilinear");let n=o.shape;return M(o,n.slice(1))})}async capture(){return(await this.next()).value}stop(){this.stream.getTracks().forEach(t=>t.stop());try{this.webcamVideoElement.srcObject=null}catch(t){console.log(t),this.webcamVideoElement.src=null}this.isClosed=!0}toArray(){throw new Error("Can not convert infinite video stream to array.")}};var mh=class{};var sy=class extends qt{split(e){return new Ez(this,e)}},Ez=class extends sy{constructor(e,t){super();this.upstream=e,this.impl=new Dz(e,t)}summary(){return this.impl.summary()}async next(){return this.impl.next()}},Dz=class extends Jp{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 WI=class extends qt{decodeUTF8(){return new Rz(this)}},Rz=class extends sy{constructor(e){super();this.upstream=e,this.impl=new Fz(e)}summary(){return this.impl.summary()}async next(){return this.impl.next()}},Fz=class extends Jp{constructor(e){super();if(this.upstream=e,W().get("IS_BROWSER"))this.decoder=new TextDecoder("utf-8");else{let{StringDecoder:t}=$z();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 fh=class extends WI{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 Oz(r,e={}){let t,o;typeof r=="string"?t=r:(t=r.url,o=zee(r));let n=await x.fetch(t,o);if(n.ok){let s=new Uint8Array(await n.arrayBuffer());return new fh(s,e)}else throw new Error(n.statusText)}var zee=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 iy(r){return typeof r=="string"&&r.substr(0,7)==="file://"}var dh=class extends mh{constructor(e,t={}){super();this.input=e,this.options=t}async iterator(){if(iy(this.input)&&W().get("IS_NODE")){let e=require("fs");this.input=e.readFileSync(this.input.substr(7))}return new fh(this.input,this.options)}};var hh=class extends mh{constructor(e,t={}){super();this.url=e,this.fileOptions=t}async iterator(){return iy(this.url)?new dh(this.url,this.fileOptions).iterator():Oz(this.url,this.fileOptions)}};function Pz(r,e={}){return new uh(new hh(r),e)}function Mz(r){let e=ih(r);return go(async()=>e)}function Lz(r){return go(async()=>{let e=await r();return ih(()=>e.next())})}async function zz(r,e){return ph.create(r,e)}async function Bz(r){return ch.create(r)}var Vz="3.3.0";var Bee={tfjs:r0,"tfjs-core":o0,"tfjs-data":n0,"tfjs-layers":s0,"tfjs-converter":i0,"tfjs-backend-cpu":hk,"tfjs-backend-webgl":I_,"tfjs-backend-wasm":aC};export{as as Abs,qs as Acos,Ks as Acosh,tp as AdadeltaOptimizer,rp as AdagradOptimizer,op as AdamOptimizer,np as AdamaxOptimizer,wo as Add,Ho as AddN,Ml as All,Ll as Any,qo as ArgMax,ea as ArgMin,Xs as Asin,Ys as Asinh,Zs as Atan,Qs as Atan2,Js as Atanh,Ko as AvgPool,ta as AvgPool3D,Bl as AvgPool3DGrad,zl as AvgPoolGrad,rx as BackendWasm,Xo as BatchMatMul,ra as BatchToSpaceND,Vl as Bincount,Db as BroadcastTo,Px as Callback,yx as CallbackList,$o as Cast,Yo as Ceil,Ro as ClipByValue,Gl as Complex,oa as ComplexAbs,ls as Concat,Zo as Conv2D,Wl as Conv2DBackpropFilter,Jo as Conv2DBackpropInput,na as Conv3D,jl as Conv3DBackpropFilterV2,Ul as Conv3DBackpropInputV2,Qo as Cos,ei as Cosh,ti as CropAndResize,en as Cumsum,wx as CustomCallback,Za as DataStorage,Hl as DenseBincount,ri as DepthToSpace,tn as DepthwiseConv2dNative,ql as DepthwiseConv2dNativeBackpropFilter,Kl as DepthwiseConv2dNativeBackpropInput,Xl as Diag,sa as Dilation2D,Fc as Dilation2DBackpropFilter,Rc as Dilation2DBackpropInput,Tb as ENV,Lx as EarlyStopping,oi as Elu,Yl as EluGrad,zh as Environment,si as Equal,ni as Erf,on as Exp,us as ExpandDims,ii as Expm1,Zl as FFT,ia as Fill,ai as FlipLeftRight,nn as Floor,sn as FloorDiv,Oc as FromPixels,an as FusedBatchNorm,ks as FusedConv2D,_s as FusedDepthwiseConv2D,Pg as GPGPUContext,li as GatherNd,cs as GatherV2,ey as GraphModel,ui as Greater,ln as GreaterEqual,bx as History,Jl as IFFT,Fo as Identity,Ql as Imag,St as InputSpec,ci as IsFinite,pi as IsInf,mi as IsNan,js as KernelBackend,aa as LRN,tu as LRNGrad,Xf as LayerVariable,To as LayersModel,un as LeakyRelu,fi as Less,di as LessEqual,eu as LinSpace,cn as Log,hi as Log1p,$b as LogSoftmax,gi as LogicalAnd,Ja as LogicalNot,Qa as LogicalOr,Hu as MathBackendCPU,Zu as MathBackendWebGL,pn as Max,fn as MaxPool,la as MaxPool3D,ou as MaxPool3DGrad,ru as MaxPoolGrad,nu as MaxPoolWithArgmax,mn as Maximum,dn as Mean,hn as Min,gn as Minimum,ua as MirrorPad,xi as Mod,sp as MomentumOptimizer,su as Multinomial,xn as Multiply,ps as Neg,bi as NonMaxSuppressionV3,wi as NonMaxSuppressionV4,ki as NonMaxSuppressionV5,yi as NotEqual,I0 as OP_SCOPE_SUFFIX,yn as OneHot,ms as OnesLike,Or as Optimizer,fs as Pack,bn as PadV2,lB as Pool,wn as Pow,kn as Prelu,_i as Prod,ip as RMSPropOptimizer,ho as RNN,ca as Range,Mb as Rank,iu as Real,rn as RealDiv,vi as Reciprocal,Gt as Reduction,_n as Relu,Cn as Relu6,ds as Reshape,vn as ResizeBilinear,lu as ResizeBilinearGrad,pa as ResizeNearestNeighbor,au as ResizeNearestNeighborGrad,In as Reverse,$i as RotateWithOffset,Nn as Round,Sn as Rsqrt,ul as SGDOptimizer,Ci as ScatterNd,hs as Select,Ii as Selu,qi as Sequential,An as Sigmoid,Si as Sign,Tn as Sin,Ni as Sinh,gs as Slice,$n as Softmax,Ti as Softplus,ma as SpaceToBatchND,uu as SparseToDense,xs as SplitV,En as Sqrt,fa as Square,Rn as SquaredDifference,Oo as Step,Ai as StridedSlice,Fn as Sub,Dn as Sum,Br as SymbolicTensor,Ei as Tan,On as Tanh,Ve as Tensor,lt as TensorBuffer,ko as Tile,Di as TopK,cu as Transform,Pn as Transpose,pu as Unique,ys as Unpack,da as UnsortedSegmentSum,rl as Variable,bs as ZerosLike,ws as _FusedMatMul,It as abs,wm as acos,km as acosh,ee as add,mw as addN,bu as all,sl as any,il as argMax,_m as argMin,vm as asin,Cm as asinh,Im as atan,Nm as atan2,Sm as atanh,wa as avgPool,Tm as avgPool3d,pw as backend,N as backend_util,pG as basicLSTMCell,Ln as batchNorm,gw as batchNorm2d,xw as batchNorm3d,yw as batchNorm4d,ka as batchToSpaceND,bw as bincount,b4 as booleanMaskAsync,al as broadcastTo,Xh as browser,ve as buffer,IL as callbacks,ne as cast,Am as ceil,sr as clipByValue,Po as clone,_o as complex,Ze as concat,ww as concat1d,kw as concat2d,_w as concat3d,vw as concat4d,gC as constraints,_u as conv1d,Kr as conv2d,vu as conv2dTranspose,Em as conv3d,$G as conv3dTranspose,pB as copyRegisteredKernels,_a as cos,Cu as cosh,tf as cosineWindow,Iu as cumsum,Xr as customGrad,ay as data,Cw as denseBincount,tg as deprecationWarn,Dm as depthToSpace,Is as depthwiseConv2d,TL as deregisterOp,hu as device_util,BG as diag,$m as dilation2d,CV as disableDeprecationWarnings,Ae as dispose,IV as disposeVariables,me as div,Rm as divNoNan,Iw as dot,Zw as dropout,Ns as elu,vV as enableDebugMode,_V as enableProdMode,Jw as enclosingPowerOfTwo,Mo as engine,W as env,vo as equal,Fm as erf,Yt as exp,ir as expandDims,Om as expm1,Kc as eye,Ea as fft,va as fill,DV as findBackend,$V as findBackendFactory,Ss as floor,yu as floorDiv,N_ as forceHalfFloat,Gn as fused,zn as gather,Yw as gatherND,Yh as gather_util,AV as getBackend,Bh as getGradient,Mc as getKernel,dm as getKernelsForBackend,OA as gpgpu_util,hW as grad,gW as grads,Qt as greater,io as greaterEqual,Mi as ifft,Nu as imag,$s as image,T4 as inTopKAsync,kC as initializers,Fx as input,Cr as io,Lu as irfft,Nw as isFinite,Sw as isInf,Tw as isNaN,Et as keep,Tr as kernel_impls,oI as layers,Ca as leakyRelu,Su as less,Bo as lessEqual,ok as linalg,Aw as linspace,oz as loadGraphModel,mL as loadLayersModel,Pm as localResponseNormalization,ar as log,Tu as log1p,Ew as logSigmoid,Au as logSoftmax,Lm as logSumExp,dr as logicalAnd,Ia as logicalNot,Eu as logicalOr,Fw as logicalXor,kU as losses,We as matMul,rN as math,lr as max,Na as maxPool,zm as maxPool3d,Ow as maxPoolWithArgmax,Yr as maximum,dt as mean,Uc as memory,aI as metrics,Pi as min,As as minimum,Bm as mirrorPad,Vm as mod,cL as model,lI as models,Xc as moments,_4 as movingAverage,O as mul,UW as multiRNNCell,Pw as multinomial,He as neg,rf as nextFrame,Vu as norm,Vn as notEqual,Cs as oneHot,Ir as ones,er as onesLike,S as op,YW as outerProduct,Rr as pad,QW as pad1d,tj as pad2d,oj as pad3d,sj as pad4d,Mw as pool,Fr as pow,Ta as prelu,tw as print,Du as prod,NV as profile,dj as rand,_j as randomGamma,lg as randomNormal,Es as randomUniform,Zc as range,TV as ready,ll as real,Wm as reciprocal,xu as registerBackend,fL as registerCallbackConstructor,Fb as registerGradient,el as registerKernel,SL as registerOp,uI as regularizers,Nr as relu,Ru as relu6,EV as removeBackend,M as reshape,Ht as reverse,Dj as reverse1d,Rj as reverse2d,Oj as reverse3d,Mj as reverse4d,Da as rfft,jm as round,Fu as rsqrt,le as scalar,Xw as scatterND,Zh as scatter_util,Ou as selu,Um as separableConv2d,pL as sequential,Q as serialization,bN as setBackend,RV as setPlatform,JZ as setWasmPath,QZ as setWasmPaths,Ek as setWebGLContext,Hw as setdiff1dAsync,yg as shared,qr as sigmoid,Hm as sign,wU as signal,Pu as sin,Mu as sinh,Re as slice,qm as slice1d,ug as slice2d,Km as slice3d,Jc as slice4d,nr as slice_util,Aa as softmax,Ts as softplus,Sa as spaceToBatchND,ef as sparseToDense,bU as spectral,ur as split,gt as sqrt,Oe as square,zu as squaredDifference,Co as squeeze,Bt as stack,Ds as step,Xm as stridedSlice,ce as sub,ge as sum,fu as sumOutType,Ym as tan,Oi as tanh,$r as tensor,Vt as tensor1d,Li as tensor2d,sw as tensor3d,u4 as tensor4d,c4 as tensor5d,p4 as tensor6d,Mn as tensor_util,gN as test_util,V as tidy,zo as tile,SV as time,Zm as topk,cl as train,Ue as transpose,Bu as truncatedNormal,Qc as unique,cB as unregisterGradient,uB as unregisterKernel,Jm as unsortedSegmentSum,cr as unstack,fr as upcastType,x as util,xW as valueAndGrad,yW as valueAndGrads,qw as variable,sg as variableGrads,Bee as version,nz as version_converter,kV as version_core,hk as version_cpu,Vp as version_layers,aC as version_wasm,I_ as version_webgl,o5 as webgl,EA as webgl_util,Dt as where,Qm as whereAsync,ht as zeros,Ce 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
|