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 nB=Object.create,Mh=Object.defineProperty,sB=Object.getPrototypeOf,iB=Object.prototype.hasOwnProperty,aB=Object.getOwnPropertyNames,lB=Object.getOwnPropertyDescriptor;var uB=r=>Mh(r,"__esModule",{value:!0});var Ht=(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})},cB=(r,e,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of aB(e))!iB.call(r,o)&&o!=="default"&&Mh(r,o,{get:()=>e[o],enumerable:!(t=lB(e,o))||t.enumerable});return r},Ac=r=>cB(uB(Mh(r!=null?nB(sB(r)):{},"default",r&&r.__esModule&&"default"in r?{get:()=>r.default,enumerable:!0}:{value:r,enumerable:!0})),r);var tN=Ht(()=>{});var ON=Ht((FN,zw)=>{(function(r,e,t){function o(i){var l=this,u=a();l.next=function(){var c=2091639*l.s0+l.c*23283064365386963e-26;return l.s0=l.s1,l.s1=l.s2,l.s2=c-(l.c=c|0)},l.c=1,l.s0=u(" "),l.s1=u(" "),l.s2=u(" "),l.s0-=u(i),l.s0<0&&(l.s0+=1),l.s1-=u(i),l.s1<0&&(l.s1+=1),l.s2-=u(i),l.s2<0&&(l.s2+=1),u=null}function n(i,l){return l.c=i.c,l.s0=i.s0,l.s1=i.s1,l.s2=i.s2,l}function s(i,l){var u=new o(i),c=l&&l.state,p=u.next;return p.int32=function(){return u.next()*4294967296|0},p.double=function(){return p()+(p()*2097152|0)*11102230246251565e-32},p.quick=p,c&&(typeof c=="object"&&n(c,u),p.state=function(){return n(u,{})}),p}function a(){var i=4022871197,l=function(u){u=u.toString();for(var c=0;c<u.length;c++){i+=u.charCodeAt(c);var p=.02519603282416938*i;i=p>>>0,p-=i,p*=i,i=p>>>0,p-=i,i+=p*4294967296}return(i>>>0)*23283064365386963e-26};return l}e&&e.exports?e.exports=s:t&&t.amd?t(function(){return s}):this.alea=s})(FN,typeof zw=="object"&&zw,typeof define=="function"&&define)});var MN=Ht((PN,Bw)=>{(function(r,e,t){function o(a){var i=this,l="";i.x=0,i.y=0,i.z=0,i.w=0,i.next=function(){var c=i.x^i.x<<11;return i.x=i.y,i.y=i.z,i.z=i.w,i.w^=i.w>>>19^c^c>>>8},a===(a|0)?i.x=a:l+=a;for(var u=0;u<l.length+64;u++)i.x^=l.charCodeAt(u)|0,i.next()}function n(a,i){return i.x=a.x,i.y=a.y,i.z=a.z,i.w=a.w,i}function s(a,i){var l=new o(a),u=i&&i.state,c=function(){return(l.next()>>>0)/4294967296};return c.double=function(){do var p=l.next()>>>11,m=(l.next()>>>0)/4294967296,f=(p+m)/(1<<21);while(f===0);return f},c.int32=l.next,c.quick=c,u&&(typeof u=="object"&&n(u,l),c.state=function(){return n(l,{})}),c}e&&e.exports?e.exports=s:t&&t.amd?t(function(){return s}):this.xor128=s})(PN,typeof Bw=="object"&&Bw,typeof define=="function"&&define)});var zN=Ht((LN,Vw)=>{(function(r,e,t){function o(a){var i=this,l="";i.next=function(){var c=i.x^i.x>>>2;return i.x=i.y,i.y=i.z,i.z=i.w,i.w=i.v,(i.d=i.d+362437|0)+(i.v=i.v^i.v<<4^(c^c<<1))|0},i.x=0,i.y=0,i.z=0,i.w=0,i.v=0,a===(a|0)?i.x=a:l+=a;for(var u=0;u<l.length+64;u++)i.x^=l.charCodeAt(u)|0,u==l.length&&(i.d=i.x<<10^i.x>>>4),i.next()}function n(a,i){return i.x=a.x,i.y=a.y,i.z=a.z,i.w=a.w,i.v=a.v,i.d=a.d,i}function s(a,i){var l=new o(a),u=i&&i.state,c=function(){return(l.next()>>>0)/4294967296};return c.double=function(){do var p=l.next()>>>11,m=(l.next()>>>0)/4294967296,f=(p+m)/(1<<21);while(f===0);return f},c.int32=l.next,c.quick=c,u&&(typeof u=="object"&&n(u,l),c.state=function(){return n(l,{})}),c}e&&e.exports?e.exports=s:t&&t.amd?t(function(){return s}):this.xorwow=s})(LN,typeof Vw=="object"&&Vw,typeof define=="function"&&define)});var VN=Ht((BN,Gw)=>{(function(r,e,t){function o(a){var i=this;i.next=function(){var u=i.x,c=i.i,p,m,f;return p=u[c],p^=p>>>7,m=p^p<<24,p=u[c+1&7],m^=p^p>>>10,p=u[c+3&7],m^=p^p>>>3,p=u[c+4&7],m^=p^p<<7,p=u[c+7&7],p=p^p<<13,m^=p^p<<9,u[c]=m,i.i=c+1&7,m};function l(u,c){var p,m,f=[];if(c===(c|0))m=f[0]=c;else for(c=""+c,p=0;p<c.length;++p)f[p&7]=f[p&7]<<15^c.charCodeAt(p)+f[p+1&7]<<13;for(;f.length<8;)f.push(0);for(p=0;p<8&&f[p]===0;++p);for(p==8?m=f[7]=-1:m=f[p],u.x=f,u.i=0,p=256;p>0;--p)u.next()}l(i,a)}function n(a,i){return i.x=a.x.slice(),i.i=a.i,i}function s(a,i){a==null&&(a=+new Date);var l=new o(a),u=i&&i.state,c=function(){return(l.next()>>>0)/4294967296};return c.double=function(){do var p=l.next()>>>11,m=(l.next()>>>0)/4294967296,f=(p+m)/(1<<21);while(f===0);return f},c.int32=l.next,c.quick=c,u&&(u.x&&n(u,l),c.state=function(){return n(l,{})}),c}e&&e.exports?e.exports=s:t&&t.amd?t(function(){return s}):this.xorshift7=s})(BN,typeof Gw=="object"&&Gw,typeof define=="function"&&define)});var WN=Ht((GN,Ww)=>{(function(r,e,t){function o(a){var i=this;i.next=function(){var u=i.w,c=i.X,p=i.i,m,f;return i.w=u=u+1640531527|0,f=c[p+34&127],m=c[p=p+1&127],f^=f<<13,m^=m<<17,f^=f>>>15,m^=m>>>12,f=c[p]=f^m,i.i=p,f+(u^u>>>16)|0};function l(u,c){var p,m,f,d,h,g=[],x=128;for(c===(c|0)?(m=c,c=null):(c=c+"\0",m=0,x=Math.max(x,c.length)),f=0,d=-32;d<x;++d)c&&(m^=c.charCodeAt((d+32)%c.length)),d===0&&(h=m),m^=m<<10,m^=m>>>15,m^=m<<4,m^=m>>>13,d>=0&&(h=h+1640531527|0,p=g[d&127]^=m+h,f=p==0?f+1:0);for(f>=128&&(g[(c&&c.length||0)&127]=-1),f=127,d=4*128;d>0;--d)m=g[f+34&127],p=g[f=f+1&127],m^=m<<13,p^=p<<17,m^=m>>>15,p^=p>>>12,g[f]=m^p;u.w=h,u.X=g,u.i=f}l(i,a)}function n(a,i){return i.i=a.i,i.w=a.w,i.X=a.X.slice(),i}function s(a,i){a==null&&(a=+new Date);var l=new o(a),u=i&&i.state,c=function(){return(l.next()>>>0)/4294967296};return c.double=function(){do var p=l.next()>>>11,m=(l.next()>>>0)/4294967296,f=(p+m)/(1<<21);while(f===0);return f},c.int32=l.next,c.quick=c,u&&(u.X&&n(u,l),c.state=function(){return n(l,{})}),c}e&&e.exports?e.exports=s:t&&t.amd?t(function(){return s}):this.xor4096=s})(GN,typeof Ww=="object"&&Ww,typeof define=="function"&&define)});var UN=Ht((jN,jw)=>{(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})(jN,typeof jw=="object"&&jw,typeof define=="function"&&define)});var Uw=Ht(()=>{});var HN=Ht((Aye,ig)=>{(function(r,e){var t=this,o=256,n=6,s=52,a="random",i=e.pow(o,n),l=e.pow(2,s),u=l*2,c=o-1,p;function m(w,k,_){var D=[];k=k==!0?{entropy:!0}:k||{};var T=g(h(k.entropy?[w,b(r)]:w==null?x():w,3),D),R=new f(D),O=function(){for(var M=R.g(n),G=i,j=0;M<l;)M=(M+j)*o,G*=o,j=R.g(1);for(;M>=u;)M/=2,G/=2,j>>>=1;return(M+j)/G};return O.int32=function(){return R.g(4)|0},O.quick=function(){return R.g(4)/4294967296},O.double=O,g(b(R.S),r),(k.pass||_||function(M,G,j,U){return U&&(U.S&&d(U,R),M.state=function(){return d(R,{})}),j?(e[a]=M,G):M})(O,T,"global"in k?k.global:this==e,k.state)}e["seed"+a]=m;function f(w){var k,_=w.length,D=this,T=0,R=D.i=D.j=0,O=D.S=[];for(_||(w=[_++]);T<o;)O[T]=T++;for(T=0;T<o;T++)O[T]=O[R=c&R+w[T%_]+(k=O[T])],O[R]=k;(D.g=function(M){for(var G,j=0,U=D.i,H=D.j,q=D.S;M--;)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 _=[],D=typeof w,T;if(k&&D=="object")for(T in w)try{_.push(h(w[T],k-1))}catch(R){}return _.length?_:D=="string"?w:w+"\0"}function g(w,k){for(var _=w+"",D,T=0;T<_.length;)k[c&T]=c&(D^=k[c&T]*19)+_.charCodeAt(T++);return b(k)}function x(){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,_=k&&k.plugins;return[+new Date,t,_,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=Uw()}catch(w){}}else typeof define=="function"&&define.amd&&define(function(){return m})})([],Math)});var Hw=Ht((Eye,qN)=>{var zj=ON(),Bj=MN(),Vj=zN(),Gj=VN(),Wj=WN(),jj=UN(),$u=HN();$u.alea=zj;$u.xor128=Bj;$u.xorwow=Vj;$u.xorshift7=Gj;$u.xor4096=Wj;$u.tychei=jj;qN.exports=$u});var Cp=Ht(()=>{});var kO=Ht(()=>{});var _O=Ht(()=>{});var vO=Ht((ex,nC)=>{var sC=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&&or(J.buffer),ut}function o(){return J.buffer!=je&&or(J.buffer),mt}function n(){return J.buffer!=je&&or(J.buffer),Xt}function s(){return J.buffer!=je&&or(J.buffer),to}function a(){return J.buffer!=je&&or(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,x=!1,b=!1;h=typeof window=="object",g=typeof importScripts=="function",x=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",b=!h&&!x&&!g;var w=i.ENVIRONMENT_IS_PTHREAD||!1;w&&(je=i.buffer);var k="";function _(I){return i.locateFile?i.locateFile(I,k):k+I}var D,T,R,O,M,G;if(x){g?k=Cp().dirname(k)+"/":k=__dirname+"/",D=function($,B){return M||(M=require("fs")),G||(G=Cp()),$=G.normalize($),M.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 um))throw I}),process.on("unhandledRejection",Zi),d=function(I){process.exit(I)},i.inspect=function(){return"[Emscripten Module object]"};var j;try{j=kO()}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="",x?(D=function($,B){return M||(M=require("fs")),G||(G=Cp()),$=G.normalize($),M.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)}),T=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)}),O=function(I){document.title=I});x&&typeof performance=="undefined"&&(global.performance=_O().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(Wr){var Tc=0;if(Wr!=null&&Wr!==0){var pI=(Wr.length<<2)+1;Tc=Ic(pI),qe(Wr,Tc,pI)}return Tc},array:function(Wr){var Tc=Ic(Wr.length);return Tt(Wr,Tc),Tc}};function ye(Wr){return $==="string"?Ne(Wr):$==="boolean"?Boolean(Wr):Wr}var Te=de(I),wt=[],wr=0;if(K)for(var fr=0;fr<K.length;fr++){var Ya=he[B[fr]];Ya?(wr===0&&(wr=lm()),wt[fr]=Ya(K[fr])):wt[fr]=K[fr]}var Sc=Te.apply(null,wt);return Sc=ye(Sc),wr!==0&&Cc(wr),Sc}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,Xt,to,$r,jo;function or(I){je=I,i.HEAP8=ut=new Int8Array(I),i.HEAP16=Pt=new Int16Array(I),i.HEAP32=Xt=new Int32Array(I),i.HEAPU8=mt=new Uint8Array(I),i.HEAPU16=xo=new Uint16Array(I),i.HEAPU32=to=new Uint32Array(I),i.HEAPF32=$r=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"),x&&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,or(je);var Gr,br=[],ro=[],Eo=[],Dl=[],Ua=[],ns=!1,Xi=!1;w||ro.push({func:function(){Eh()}}),w&&(ns=!0);function em(){if(!w){if(i.preRun)for(typeof i.preRun=="function"&&(i.preRun=[i.preRun]);i.preRun.length;)xh(i.preRun.shift());bc(br)}}function xc(){ns=!0,bc(ro)}function uy(){w||bc(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;)cy(i.postRun.shift());bc(Ua)}}function xh(I){br.unshift(I)}function cy(I){Ua.unshift(I)}var Yi=0,Ha=null,$l=null;function py(I){fe(!w,"addRunDependency cannot be used in a pthread worker"),Yi++,i.monitorRunDependencies&&i.monitorRunDependencies(Yi)}function my(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 yc="data:application/octet-stream;base64,";function bh(I){return yh(I,yc)}var fy="file://";function wh(I){return yh(I,fy)}var no="tfjs-backend-wasm-threaded-simd.wasm";bh(no)||(no=_(no));function dy(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 dy(no)});if(T)return new Promise(function(I,$){T(no,function(B){I(new Uint8Array(B))},$)})}return Promise.resolve().then(function(){return dy(no)})}function hy(){var I={a:sb};function $(ye,Te){var wt=ye.exports;if(i.asm=wt,Gr=i.asm.F,ie=Te,!w){var wr=Ee.unusedWorkers.length;Ee.unusedWorkers.forEach(function(fr){Ee.loadWasmModuleToWorker(fr,function(){--wr||my("wasm-instantiate")})})}}w||py("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(){sI(I,$)},0)}};function gy(){Ee.initRuntime()}function bc(I){for(;I.length>0;){var $=I.shift();if(typeof $=="function"){$(i);continue}var B=$.func;typeof B=="number"?$.arg===void 0?Gr.get(B)():Gr.get(B)($.arg):B($.arg===void 0?null:$.arg)}}function wc(I,$){if(I<=0||I>t().length||I&!0||$<0)return-28;if($==0)return 0;$>=2147483647&&($=Infinity);var B=Atomics.load(n(),Nc>>2),K=0;if(B==I){var be=Atomics.compareExchange(n(),Nc>>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=wc;function xy(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 yy(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 by(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),nI(I)},initWorker:function(){},pthreads:{},threadExitHandlers:[],setThreadStatus:function(){},runExitHandlers:function(){for(;Ee.threadExitHandlers.length>0;)Ee.threadExitHandlers.pop()();w&&vc()&&oI()},threadExit:function(I){var $=vc();$&&(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(),wc($+0,2147483647),Oh(0,0,0),w&&postMessage({cmd:"exit"}))},threadCancel:function(){Ee.runExitHandlers();var I=vc();Atomics.store(s(),I+4>>2,-1),Atomics.store(s(),I+0>>2,1),wc(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,am($),am(I.threadInfoStruct)}I.threadInfoStruct=0,I.allocatedOwnStack&&I.stackBase&&am(I.stackBase),I.stackBase=0,I.worker&&(I.worker.pthread=null)}},returnWorkerToPool:function(I){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()[cI>>2]=0;try{I()}finally{n()[cI>>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!=vc()){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")wb();else if(be==="spawnThread")Th(B.data);else if(be==="cleanupThread")by(K.thread);else if(be==="killThread")xy(K.thread);else if(be==="cancelThread")yy(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{oB(K.returnCode)}catch(Te){if(Te instanceof um)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)},x&&(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=_("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 wy(I,$){lI(I,$),Cc(I)}i.establishStackSpace=wy;function ky(){return re}i.getNoExitRuntime=ky;function _y(I,$){return Gr.get(I)($)}i.invokeEntryPoint=_y;function vy(I,$,B,K){Zi("Assertion failed: "+Ne(I)+", at: "+[$?Ne($):"unknown filename",B,K?Ne(K):"unknown function"])}function Cy(I,$){var B=_main(I,$)}var Rl;x?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 Iy(I){return n()[tI()>>2]=I,I}function Ny(I,$){if(w)return qa(1,1,I,$)}function Sy(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 Ty(){Zi()}function Ay(I,$,B){var K=Fy($,B);return _h[I].apply(null,K)}function Ey(I,$){}function Dy(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(),Nc>>2,I);;){if(be=performance.now(),be>he)return ye=Atomics.exchange(n(),Nc>>2,0),-73;if(ye=Atomics.exchange(n(),Nc>>2,0),ye==0)break;if(wb(),Atomics.load(n(),I>>2)!=$)return-6;ye=Atomics.exchange(n(),Nc>>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 $y(I,$,B){o().copyWithin(I,$,$+B)}function Ry(){return x?require("os").cpus().length:navigator.hardwareConcurrency}function qa(I,$){for(var B=arguments.length-2,K=lm(),be=B,he=Ic(be*8),ye=he>>3,Te=0;Te<B;Te++){var wt=arguments[2+Te];a()[ye+Te]=wt}var wr=aI(I,be,he,$);return Cc(K),wr}var tm=[],rm=[];function Fy(I,$){rm.length=0;var B;for($>>=2;B=o()[I++];){var K=B<105;K&&$&1&&$++,rm.push(K?a()[$++>>1]:n()[$]),++$}return rm}function Oy(I,$,B){tm.length=$;for(var K=B>>3,be=0;be<$;be++)tm[be]=a()[K+be];var he=I<0,ye=he?_h[-I-1]:nb[I];return ye.apply(null,tm)}function Py(){return o().length}function My(I){try{return J.grow(I-je.byteLength+65535>>>16),or(J.buffer),1}catch($){}}function Ly(I){var $=Py();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=My(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=lm(),ye=Ic(12);n()[ye>>2]=B,n()[ye+4>>2]=K,n()[ye+8>>2]=be,kb(0,I,637534208,$,K,ye),Cc(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 zy(I){var $=it(I)+1,B=Fl($);return qe(I,B,$),B}function By(I,$,B,K){var be=lm(),he=Ic(12),ye=0;$&&(ye=zy($)),n()[he>>2]=ye,n()[he+4>>2]=B,n()[he+8>>2]=K,kb(0,I,657457152,0,ye,he),Cc(be)}function Vy(I,$,B,K){$=$?Ne($):"",By(I,$,B,K)}function Gy(I){return I>2?Ne(I):I}var Wy=[0,typeof document!="undefined"?document:0,typeof window!="undefined"?window:0];function jy(I){I=Gy(I);var $=Wy[I]||(typeof document!="undefined"?document.querySelector(I):void 0);return $}function om(I){return jy(I)}function vh(I,$,B){var K=om(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 Vy(ye,I,$,B),1}else return-4;return 0}function Ch(I,$,B){return w?qa(2,1,I,$,B):vh(I,$,B)}function Uy(I,$,B){var K=om(I);return K?vh(I,$,B):Ch(I,$,B)}function Hy(I){}function qy(I,$){}function Ky(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 Xy(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 Yy(I){var $=I.getExtension("WEBGL_draw_buffers");if($)return I.drawBuffers=function(B,K){$.drawBuffersWEBGL(B,K)},1}function Zy(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]=vc();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),am(ft.contexts[I].handle),ft.contexts[I]=null},initExtensions:function(I){if(I||(I=ft.currentContext),!I.initExtensionsDone){I.initExtensionsDone=!0;var $=I.GLctx;Ky($),Xy($),Yy($),$.disjointTimerQueryExt=$.getExtension("EXT_disjoint_timer_query"),Zy($);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 wr=ft.getNewId(ft.uniforms);K[Te]=[ye.size,wr],ft.uniforms[wr]=wt;for(var fr=1;fr<ye.size;++fr){var Ya=Te+"["+fr+"]";wt=Ka.getUniformLocation($,Ya),wr=ft.getNewId(ft.uniforms),ft.uniforms[wr]=wt}}}}},Jy=["default","low-power","high-performance"];function Qy(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:Jy[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=om(I);if(!he||be.explicitSwapControl)return 0;var ye=ft.createContext(he,be);return ye}function eb(I,$){return Qy(I,$)}var kc={mappings:{},buffers:[null,[],[]],printChar:function(I,$){var B=kc.buffers[I];$===0||$===10?((I===1?U:H)(De(B,0)),B.length=0):B.push($)},varargs:void 0,get:function(){kc.varargs+=4;var I=n()[kc.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++)kc.printChar(I,o()[ye+wt]);be+=Te}return n()[K>>2]=be,0}function tb(I){var $=Ee.threadExitHandlers.pop();I&&$()}function rb(I,$){Ee.threadExitHandlers.push(function(){Gr.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=rI(),wt=Te+40;Atomics.store(s(),ye+(172>>2),wt),$.pthread=he;var wr={cmd:"run",start_routine:I.startRoutine,arg:I.arg,threadInfoStruct:I.pthread_ptr,stackBase:I.stackBase,stackSize:I.stackSize};$.runPthread=function(){wr.time=performance.now(),$.postMessage(wr,I.transferList)},$.loaded&&($.runPthread(),delete $.runPthread)}function ob(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 iI(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 wr=Te==0;wr?Te=uI(16,ye):(Te-=ye,fe(Te>0));for(var fr=Fl(228),Ya=0;Ya<228>>2;++Ya)s()[(fr>>2)+Ya]=0;n()[I>>2]=fr,n()[fr+12>>2]=fr;var Sc=fr+152;n()[Sc>>2]=Sc;var Wr={stackBase:Te,stackSize:ye,allocatedOwnStack:wr,detached:wt,startRoutine:B,pthread_ptr:fr,arg:K,transferList:be};return w?(Wr.cmd="spawnThread",postMessage(Wr,be)):Th(Wr),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 Iy(28),-1}w||Ee.initMainThreadBlock();var Ka,nb=[null,Ny,Ch,Ih,Nh,Sh,Ah],sb={e:vy,r:Cy,x:Sy,b:Ty,y:Ay,j:Ey,c:Dy,d:wc,f:Rl,p:$y,z:Ry,u:Oy,q:Ly,v:Uy,i:Hy,t:qy,w:eb,m:Ih,n:Nh,g:Sh,o:gy,a:J||i.wasmMemory,k:tb,l:rb,h:ob,s:Ah},eI=hy(),Eh=i.___wasm_call_ctors=function(){return(Eh=i.___wasm_call_ctors=i.asm.A).apply(null,arguments)},ib=i._init=function(){return(ib=i._init=i.asm.B).apply(null,arguments)},ab=i._register_tensor=function(){return(ab=i._register_tensor=i.asm.C).apply(null,arguments)},lb=i._dispose_data=function(){return(lb=i._dispose_data=i.asm.D).apply(null,arguments)},ub=i._dispose=function(){return(ub=i._dispose=i.asm.E).apply(null,arguments)},cb=i._Abs=function(){return(cb=i._Abs=i.asm.G).apply(null,arguments)},pb=i._Add=function(){return(pb=i._Add=i.asm.H).apply(null,arguments)},mb=i._AddN=function(){return(mb=i._AddN=i.asm.I).apply(null,arguments)},fb=i._ArgMax=function(){return(fb=i._ArgMax=i.asm.J).apply(null,arguments)},db=i._AvgPool=function(){return(db=i._AvgPool=i.asm.K).apply(null,arguments)},hb=i._BatchMatMul=function(){return(hb=i._BatchMatMul=i.asm.L).apply(null,arguments)},gb=i._Ceil=function(){return(gb=i._Ceil=i.asm.M).apply(null,arguments)},xb=i._ClipByValue=function(){return(xb=i._ClipByValue=i.asm.N).apply(null,arguments)},yb=i._Conv2D=function(){return(yb=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)},nm=i._CropAndResize=function(){return(nm=i._CropAndResize=i.asm.R).apply(null,arguments)},_c=i._Cumsum=function(){return(_c=i._Cumsum=i.asm.S).apply(null,arguments)},bb=i._DepthToSpace=function(){return(bb=i._DepthToSpace=i.asm.T).apply(null,arguments)},sm=i._DepthwiseConv2dNative=function(){return(sm=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)},Yt=i._FloorDiv=function(){return(Yt=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)},vr=i._Gather=function(){return(vr=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)},im=i._LeakyRelu=function(){return(im=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)},m3=i._LogicalAnd=function(){return(m3=i._LogicalAnd=i.asm.ja).apply(null,arguments)},f3=i._Max=function(){return(f3=i._Max=i.asm.ka).apply(null,arguments)},d3=i._MaxPool=function(){return(d3=i._MaxPool=i.asm.la).apply(null,arguments)},h3=i._Maximum=function(){return(h3=i._Maximum=i.asm.ma).apply(null,arguments)},g3=i._Mean=function(){return(g3=i._Mean=i.asm.na).apply(null,arguments)},x3=i._Min=function(){return(x3=i._Min=i.asm.oa).apply(null,arguments)},y3=i._Minimum=function(){return(y3=i._Minimum=i.asm.pa).apply(null,arguments)},b3=i._Multiply=function(){return(b3=i._Multiply=i.asm.qa).apply(null,arguments)},w3=i._Neg=function(){return(w3=i._Neg=i.asm.ra).apply(null,arguments)},k3=i._NonMaxSuppressionV3=function(){return(k3=i._NonMaxSuppressionV3=i.asm.sa).apply(null,arguments)},_3=i._NonMaxSuppressionV4=function(){return(_3=i._NonMaxSuppressionV4=i.asm.ta).apply(null,arguments)},v3=i._NonMaxSuppressionV5=function(){return(v3=i._NonMaxSuppressionV5=i.asm.ua).apply(null,arguments)},C3=i._NotEqual=function(){return(C3=i._NotEqual=i.asm.va).apply(null,arguments)},I3=i._OneHot=function(){return(I3=i._OneHot=i.asm.wa).apply(null,arguments)},N3=i._PadV2=function(){return(N3=i._PadV2=i.asm.xa).apply(null,arguments)},S3=i._Pow=function(){return(S3=i._Pow=i.asm.ya).apply(null,arguments)},T3=i._Prelu=function(){return(T3=i._Prelu=i.asm.za).apply(null,arguments)},A3=i._Prod=function(){return(A3=i._Prod=i.asm.Aa).apply(null,arguments)},E3=i._RealDiv=function(){return(E3=i._RealDiv=i.asm.Ba).apply(null,arguments)},D3=i._Relu=function(){return(D3=i._Relu=i.asm.Ca).apply(null,arguments)},$3=i._Relu6=function(){return($3=i._Relu6=i.asm.Da).apply(null,arguments)},R3=i._ResizeBilinear=function(){return(R3=i._ResizeBilinear=i.asm.Ea).apply(null,arguments)},F3=i._Reverse=function(){return(F3=i._Reverse=i.asm.Fa).apply(null,arguments)},O3=i._RotateWithOffset=function(){return(O3=i._RotateWithOffset=i.asm.Ga).apply(null,arguments)},P3=i._Round=function(){return(P3=i._Round=i.asm.Ha).apply(null,arguments)},M3=i._Rsqrt=function(){return(M3=i._Rsqrt=i.asm.Ia).apply(null,arguments)},L3=i._ScatterNd=function(){return(L3=i._ScatterNd=i.asm.Ja).apply(null,arguments)},z3=i._SelectV2=function(){return(z3=i._SelectV2=i.asm.Ka).apply(null,arguments)},B3=i._Sigmoid=function(){return(B3=i._Sigmoid=i.asm.La).apply(null,arguments)},V3=i._Sin=function(){return(V3=i._Sin=i.asm.Ma).apply(null,arguments)},G3=i._Softmax=function(){return(G3=i._Softmax=i.asm.Na).apply(null,arguments)},W3=i._Sqrt=function(){return(W3=i._Sqrt=i.asm.Oa).apply(null,arguments)},j3=i._Square=function(){return(j3=i._Square=i.asm.Pa).apply(null,arguments)},U3=i._SquaredDifference=function(){return(U3=i._SquaredDifference=i.asm.Qa).apply(null,arguments)},H3=i._Step=function(){return(H3=i._Step=i.asm.Ra).apply(null,arguments)},q3=i._StridedSlice=function(){return(q3=i._StridedSlice=i.asm.Sa).apply(null,arguments)},K3=i._Sub=function(){return(K3=i._Sub=i.asm.Ta).apply(null,arguments)},X3=i._Sum=function(){return(X3=i._Sum=i.asm.Ua).apply(null,arguments)},Y3=i._Tanh=function(){return(Y3=i._Tanh=i.asm.Va).apply(null,arguments)},Z3=i._Tile=function(){return(Z3=i._Tile=i.asm.Wa).apply(null,arguments)},J3=i._TopK=function(){return(J3=i._TopK=i.asm.Xa).apply(null,arguments)},Q3=i._Transpose=function(){return(Q3=i._Transpose=i.asm.Ya).apply(null,arguments)},eB=i.__FusedMatMul=function(){return(eB=i.__FusedMatMul=i.asm.Za).apply(null,arguments)},Fl=i._malloc=function(){return(Fl=i._malloc=i.asm._a).apply(null,arguments)},am=i._free=function(){return(am=i._free=i.asm.$a).apply(null,arguments)},tI=i.___errno_location=function(){return(tI=i.___errno_location=i.asm.ab).apply(null,arguments)},rI=i._emscripten_get_global_libc=function(){return(rI=i._emscripten_get_global_libc=i.asm.bb).apply(null,arguments)},vc=i._pthread_self=function(){return(vc=i._pthread_self=i.asm.cb).apply(null,arguments)},oI=i.___pthread_tsd_run_dtors=function(){return(oI=i.___pthread_tsd_run_dtors=i.asm.db).apply(null,arguments)},wb=i._emscripten_main_thread_process_queued_calls=function(){return(wb=i._emscripten_main_thread_process_queued_calls=i.asm.eb).apply(null,arguments)},tB=i._emscripten_current_thread_process_queued_calls=function(){return(tB=i._emscripten_current_thread_process_queued_calls=i.asm.fb).apply(null,arguments)},nI=i._emscripten_register_main_browser_thread_id=function(){return(nI=i._emscripten_register_main_browser_thread_id=i.asm.gb).apply(null,arguments)},sI=i.__emscripten_do_dispatch_to_thread=function(){return(sI=i.__emscripten_do_dispatch_to_thread=i.asm.hb).apply(null,arguments)},iI=i._emscripten_sync_run_in_main_thread_4=function(){return(iI=i._emscripten_sync_run_in_main_thread_4=i.asm.ib).apply(null,arguments)},aI=i._emscripten_run_in_main_runtime_thread_js=function(){return(aI=i._emscripten_run_in_main_runtime_thread_js=i.asm.jb).apply(null,arguments)},kb=i.__emscripten_call_on_thread=function(){return(kb=i.__emscripten_call_on_thread=i.asm.kb).apply(null,arguments)},rB=i._emscripten_tls_init=function(){return(rB=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)},lm=i.stackSave=function(){return(lm=i.stackSave=i.asm.nb).apply(null,arguments)},Cc=i.stackRestore=function(){return(Cc=i.stackRestore=i.asm.ob).apply(null,arguments)},Ic=i.stackAlloc=function(){return(Ic=i.stackAlloc=i.asm.pb).apply(null,arguments)},lI=i._emscripten_stack_set_limits=function(){return(lI=i._emscripten_stack_set_limits=i.asm.qb).apply(null,arguments)},uI=i._memalign=function(){return(uI=i._memalign=i.asm.rb).apply(null,arguments)},cI=i.__emscripten_allow_main_runtime_queued_calls=9880,Nc=i.__emscripten_main_thread_futex=11368;i.cwrap=we,i.PThread=Ee,i.PThread=Ee,i.wasmMemory=J,i.ExitStatus=um;var Ph;function um(I){this.name="ExitStatus",this.message="Program terminated with exit("+I+")",this.status=I}$l=function I(){Ph||_b(),Ph||($l=I)};function _b(I){if(I=I||m,Yi>0)return;if(w){l(i),postMessage({cmd:"loaded"});return}if(em(),Yi>0)return;function $(){Ph||(Ph=!0,i.calledRun=!0,!ue&&(xc(),uy(),l(i),i.onRuntimeInitialized&&i.onRuntimeInitialized(),oo()))}i.setStatus?(i.setStatus("Running..."),setTimeout(function(){setTimeout(function(){i.setStatus("")},1),$()},1)):$()}i.run=_b;function oB(I,$){if(!($&&re&&I===0)){if(!$&&w)throw postMessage({cmd:"exitProcess",returnCode:I}),new um(I);re||(Ee.terminateAllThreads(),ae=I,gh(),i.onExit&&i.onExit(I),ue=!0),d(I,new um(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()),_b(),e.ready}}();typeof ex=="object"&&typeof nC=="object"?nC.exports=sC:typeof define=="function"&&define.amd?define([],function(){return sC}):typeof ex=="object"&&(ex.WasmBackendModuleThreadedSimd=sC)});var IO=Ht((tx,iC)=>{var aC=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,x,b,w,k,_;m?(p?d=Cp().dirname(d)+"/":d=__dirname+"/",g=function(se,_e){return k||(k=require("fs")),_||(_=Cp()),se=_.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 bb))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)}),x=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),T=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 O=t.noExitRuntime||!0;typeof WebAssembly!="object"&&ns("no native wasm support detected");var M,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,Yt){var zt={string:function(bo){var Xa=0;if(bo!=null&&bo!==0){var Fh=(bo.length<<2)+1;Xa=nm(Fh),ie(bo,Xa,Fh)}return Xa},array:function(bo){var Xa=nm(bo.length);return ue(bo,Xa),Xa}};function tt(bo){return se==="string"?re(bo):se==="boolean"?Boolean(bo):bo}var rt=H(Z),vr=[],Ji=0;if(at)for(var Qi=0;Qi<at.length;Qi++){var Rh=zt[_e[Qi]];Rh?(Ji===0&&(Ji=Dh()),vr[Qi]=Rh(at[Qi])):vr[Qi]=at[Qi]}var im=rt.apply(null,vr);return im=tt(im),Ji!==0&&$h(Ji),im}function X(Z,se,_e,at){_e=_e||[];var Yt=_e.every(function(tt){return tt==="number"}),zt=se!=="string";return zt&&Yt&&!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,Yt=se;Z[Yt]&&!(Yt>=at);)++Yt;if(Yt-se>16&&Z.subarray&&oe)return oe.decode(Z.subarray(se,Yt));for(var zt="";se<Yt;){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 vr=Z[se++]&63;if((tt&240)==224?tt=(tt&15)<<12|rt<<6|vr:tt=(tt&7)<<18|rt<<12|vr<<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 Yt=_e,zt=_e+at-1,tt=0;tt<Z.length;++tt){var rt=Z.charCodeAt(tt);if(rt>=55296&&rt<=57343){var vr=Z.charCodeAt(++tt);rt=65536+((rt&1023)<<10)|vr&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-Yt}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=[],Xt=!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 $r(){Xt=!0,Ha(mt)}function jo(){Ha(Pt)}function or(){if(t.postRun)for(typeof t.postRun=="function"&&(t.postRun=[t.postRun]);t.postRun.length;)Gr(t.postRun.shift());Ha(xo)}function yo(Z){ut.unshift(Z)}function Gr(Z){xo.unshift(Z)}var br=0,ro=null,Eo=null;function Dl(Z){br++,t.monitorRunDependencies&&t.monitorRunDependencies(br)}function Ua(Z){if(br--,t.monitorRunDependencies&&t.monitorRunDependencies(br),br==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+="",T(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 em="data:application/octet-stream;base64,";function xc(Z){return Xi(Z,em)}var uy="file://";function gh(Z){return Xi(Z,uy)}var oo="tfjs-backend-wasm.wasm";xc(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 cy(){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(x)return new Promise(function(Z,se){x(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 vr=tt.exports;t.asm=vr,M=t.asm.g,Tt(M.buffer),je=t.asm.m,Ua("wasm-instantiate")}Dl("wasm-instantiate");function _e(tt){se(tt.instance)}function at(tt){return cy().then(function(rt){return WebAssembly.instantiate(rt,Z)}).then(tt,function(rt){T("failed to asynchronously prepare wasm: "+rt),ns(rt)})}function Yt(){return!R&&typeof WebAssembly.instantiateStreaming=="function"&&!xc(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(vr){return T("wasm streaming compile failed: "+vr),T("falling back to ArrayBuffer instantiation"),at(_e)})}):at(_e)}if(t.instantiateWasm)try{var zt=t.instantiateWasm(Z,se);return zt}catch(tt){return T("Module.instantiateWasm callback failed with error: "+tt),!1}return Yt().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 py(Z,se,_e){xe.copyWithin(Z,se,se+_e)}function my(){return xe.length}function Zi(Z){try{return M.grow(Z-fe.byteLength+65535>>>16),Tt(M.buffer),1}catch(se){}}function yh(Z){var se=my(),_e=2147483648;if(Z>_e)return!1;for(var at=1;at<=4;at*=2){var Yt=se*(1+.2/at);Yt=Math.min(Yt,Z+100663296);var zt=Math.min(_e,ae(Math.max(Z,Yt),65536)),tt=Zi(zt);if(tt)return!0}return!1}var yc={mappings:{},buffers:[null,[],[]],printChar:function(Z,se){var _e=yc.buffers[Z];se===0||se===10?((Z===1?D:T)(Y(_e,0)),_e.length=0):_e.push(se)},varargs:void 0,get:function(){yc.varargs+=4;var Z=Ne[yc.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 fy(Z,se,_e,at,Yt){}function wh(Z,se,_e,at){for(var Yt=0,zt=0;zt<_e;zt++){for(var tt=Ne[se+zt*8>>2],rt=Ne[se+(zt*8+4)>>2],vr=0;vr<rt;vr++)yc.printChar(Z,xe[tt+vr]);Yt+=rt}return Ne[at>>2]=Yt,0}var no={a:$l,d:py,e:yh,f:bh,c:fy,b:wh},dy=Yi(),kh=t.___wasm_call_ctors=function(){return(kh=t.___wasm_call_ctors=t.asm.h).apply(null,arguments)},hy=t._init=function(){return(hy=t._init=t.asm.i).apply(null,arguments)},_h=t._register_tensor=function(){return(_h=t._register_tensor=t.asm.j).apply(null,arguments)},gy=t._dispose_data=function(){return(gy=t._dispose_data=t.asm.k).apply(null,arguments)},bc=t._dispose=function(){return(bc=t._dispose=t.asm.l).apply(null,arguments)},wc=t._Abs=function(){return(wc=t._Abs=t.asm.n).apply(null,arguments)},xy=t._Add=function(){return(xy=t._Add=t.asm.o).apply(null,arguments)},yy=t._AddN=function(){return(yy=t._AddN=t.asm.p).apply(null,arguments)},by=t._ArgMax=function(){return(by=t._ArgMax=t.asm.q).apply(null,arguments)},Ee=t._AvgPool=function(){return(Ee=t._AvgPool=t.asm.r).apply(null,arguments)},wy=t._BatchMatMul=function(){return(wy=t._BatchMatMul=t.asm.s).apply(null,arguments)},ky=t._Ceil=function(){return(ky=t._Ceil=t.asm.t).apply(null,arguments)},_y=t._ClipByValue=function(){return(_y=t._ClipByValue=t.asm.u).apply(null,arguments)},vy=t._Conv2D=function(){return(vy=t._Conv2D=t.asm.v).apply(null,arguments)},Cy=t._Conv2DBackpropInput=function(){return(Cy=t._Conv2DBackpropInput=t.asm.w).apply(null,arguments)},Rl=t._Cos=function(){return(Rl=t._Cos=t.asm.x).apply(null,arguments)},Iy=t._CropAndResize=function(){return(Iy=t._CropAndResize=t.asm.y).apply(null,arguments)},Ny=t._Cumsum=function(){return(Ny=t._Cumsum=t.asm.z).apply(null,arguments)},Sy=t._DepthToSpace=function(){return(Sy=t._DepthToSpace=t.asm.A).apply(null,arguments)},Ty=t._DepthwiseConv2dNative=function(){return(Ty=t._DepthwiseConv2dNative=t.asm.B).apply(null,arguments)},Ay=t._Equal=function(){return(Ay=t._Equal=t.asm.C).apply(null,arguments)},Ey=t._Exp=function(){return(Ey=t._Exp=t.asm.D).apply(null,arguments)},Dy=t._FlipLeftRight=function(){return(Dy=t._FlipLeftRight=t.asm.E).apply(null,arguments)},$y=t._Floor=function(){return($y=t._Floor=t.asm.F).apply(null,arguments)},Ry=t._FloorDiv=function(){return(Ry=t._FloorDiv=t.asm.G).apply(null,arguments)},qa=t._FusedBatchNorm=function(){return(qa=t._FusedBatchNorm=t.asm.H).apply(null,arguments)},tm=t._FusedConv2D=function(){return(tm=t._FusedConv2D=t.asm.I).apply(null,arguments)},rm=t._FusedDepthwiseConv2D=function(){return(rm=t._FusedDepthwiseConv2D=t.asm.J).apply(null,arguments)},Fy=t._Gather=function(){return(Fy=t._Gather=t.asm.K).apply(null,arguments)},Oy=t._GatherNd=function(){return(Oy=t._GatherNd=t.asm.L).apply(null,arguments)},Py=t._Greater=function(){return(Py=t._Greater=t.asm.M).apply(null,arguments)},My=t._GreaterEqual=function(){return(My=t._GreaterEqual=t.asm.N).apply(null,arguments)},Ly=t._LeakyRelu=function(){return(Ly=t._LeakyRelu=t.asm.O).apply(null,arguments)},Ye=t._Less=function(){return(Ye=t._Less=t.asm.P).apply(null,arguments)},zy=t._LessEqual=function(){return(zy=t._LessEqual=t.asm.Q).apply(null,arguments)},By=t._Log=function(){return(By=t._Log=t.asm.R).apply(null,arguments)},Vy=t._LogicalAnd=function(){return(Vy=t._LogicalAnd=t.asm.S).apply(null,arguments)},Gy=t._Max=function(){return(Gy=t._Max=t.asm.T).apply(null,arguments)},Wy=t._MaxPool=function(){return(Wy=t._MaxPool=t.asm.U).apply(null,arguments)},jy=t._Maximum=function(){return(jy=t._Maximum=t.asm.V).apply(null,arguments)},om=t._Mean=function(){return(om=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)},Uy=t._Multiply=function(){return(Uy=t._Multiply=t.asm.Z).apply(null,arguments)},Hy=t._Neg=function(){return(Hy=t._Neg=t.asm._).apply(null,arguments)},qy=t._NonMaxSuppressionV3=function(){return(qy=t._NonMaxSuppressionV3=t.asm.$).apply(null,arguments)},Ky=t._NonMaxSuppressionV4=function(){return(Ky=t._NonMaxSuppressionV4=t.asm.aa).apply(null,arguments)},Xy=t._NonMaxSuppressionV5=function(){return(Xy=t._NonMaxSuppressionV5=t.asm.ba).apply(null,arguments)},Yy=t._NotEqual=function(){return(Yy=t._NotEqual=t.asm.ca).apply(null,arguments)},Zy=t._OneHot=function(){return(Zy=t._OneHot=t.asm.da).apply(null,arguments)},ft=t._PadV2=function(){return(ft=t._PadV2=t.asm.ea).apply(null,arguments)},Jy=t._Pow=function(){return(Jy=t._Pow=t.asm.fa).apply(null,arguments)},Qy=t._Prelu=function(){return(Qy=t._Prelu=t.asm.ga).apply(null,arguments)},eb=t._Prod=function(){return(eb=t._Prod=t.asm.ha).apply(null,arguments)},kc=t._RealDiv=function(){return(kc=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)},tb=t._Reverse=function(){return(tb=t._Reverse=t.asm.ma).apply(null,arguments)},rb=t._RotateWithOffset=function(){return(rb=t._RotateWithOffset=t.asm.na).apply(null,arguments)},Th=t._Round=function(){return(Th=t._Round=t.asm.oa).apply(null,arguments)},ob=t._Rsqrt=function(){return(ob=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)},nb=t._Sigmoid=function(){return(nb=t._Sigmoid=t.asm.sa).apply(null,arguments)},sb=t._Sin=function(){return(sb=t._Sin=t.asm.ta).apply(null,arguments)},eI=t._Softmax=function(){return(eI=t._Softmax=t.asm.ua).apply(null,arguments)},Eh=t._Sqrt=function(){return(Eh=t._Sqrt=t.asm.va).apply(null,arguments)},ib=t._Square=function(){return(ib=t._Square=t.asm.wa).apply(null,arguments)},ab=t._SquaredDifference=function(){return(ab=t._SquaredDifference=t.asm.xa).apply(null,arguments)},lb=t._Step=function(){return(lb=t._Step=t.asm.ya).apply(null,arguments)},ub=t._StridedSlice=function(){return(ub=t._StridedSlice=t.asm.za).apply(null,arguments)},cb=t._Sub=function(){return(cb=t._Sub=t.asm.Aa).apply(null,arguments)},pb=t._Sum=function(){return(pb=t._Sum=t.asm.Ba).apply(null,arguments)},mb=t._Tanh=function(){return(mb=t._Tanh=t.asm.Ca).apply(null,arguments)},fb=t._Tile=function(){return(fb=t._Tile=t.asm.Da).apply(null,arguments)},db=t._TopK=function(){return(db=t._TopK=t.asm.Ea).apply(null,arguments)},hb=t._Transpose=function(){return(hb=t._Transpose=t.asm.Fa).apply(null,arguments)},gb=t.__FusedMatMul=function(){return(gb=t.__FusedMatMul=t.asm.Ga).apply(null,arguments)},xb=t._malloc=function(){return(xb=t._malloc=t.asm.Ha).apply(null,arguments)},yb=t._free=function(){return(yb=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)},nm=t.stackAlloc=function(){return(nm=t.stackAlloc=t.asm.La).apply(null,arguments)};t.cwrap=X;var _c;function bb(Z){this.name="ExitStatus",this.message="Program terminated with exit("+Z+")",this.status=Z}Eo=function Z(){_c||sm(),_c||(Eo=Z)};function sm(Z){if(Z=Z||i,br>0||(to(),br>0))return;function se(){_c||(_c=!0,t.calledRun=!0,!G&&($r(),jo(),o(t),t.onRuntimeInitialized&&t.onRuntimeInitialized(),or()))}t.setStatus?(t.setStatus("Running..."),setTimeout(function(){setTimeout(function(){t.setStatus("")},1),se()},1)):se()}if(t.run=sm,t.preInit)for(typeof t.preInit=="function"&&(t.preInit=[t.preInit]);t.preInit.length>0;)t.preInit.pop()();return sm(),e.ready}}();typeof tx=="object"&&typeof iC=="object"?iC.exports=aC:typeof define=="function"&&define.amd?define([],function(){return aC}):typeof tx=="object"&&(tx.WasmBackendModule=aC)});var hz=Ht((dz,B0)=>{(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=String(u);for(var c=0;c<u.length;c++){i+=u.charCodeAt(c);var p=.02519603282416938*i;i=p>>>0,p-=i,p*=i,i=p>>>0,p-=i,i+=p*4294967296}return(i>>>0)*23283064365386963e-26};return l}e&&e.exports?e.exports=s:t&&t.amd?t(function(){return s}):this.alea=s})(dz,typeof B0=="object"&&B0,typeof define=="function"&&define)});var xz=Ht((gz,V0)=>{(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})(gz,typeof V0=="object"&&V0,typeof define=="function"&&define)});var bz=Ht((yz,G0)=>{(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})(yz,typeof G0=="object"&&G0,typeof define=="function"&&define)});var kz=Ht((wz,W0)=>{(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})(wz,typeof W0=="object"&&W0,typeof define=="function"&&define)});var vz=Ht((_z,j0)=>{(function(r,e,t){function o(a){var i=this;i.next=function(){var u=i.w,c=i.X,p=i.i,m,f;return i.w=u=u+1640531527|0,f=c[p+34&127],m=c[p=p+1&127],f^=f<<13,m^=m<<17,f^=f>>>15,m^=m>>>12,f=c[p]=f^m,i.i=p,f+(u^u>>>16)|0};function l(u,c){var p,m,f,d,h,g=[],x=128;for(c===(c|0)?(m=c,c=null):(c=c+"\0",m=0,x=Math.max(x,c.length)),f=0,d=-32;d<x;++d)c&&(m^=c.charCodeAt((d+32)%c.length)),d===0&&(h=m),m^=m<<10,m^=m>>>15,m^=m<<4,m^=m>>>13,d>=0&&(h=h+1640531527|0,p=g[d&127]^=m+h,f=p==0?f+1:0);for(f>=128&&(g[(c&&c.length||0)&127]=-1),f=127,d=4*128;d>0;--d)m=g[f+34&127],p=g[f=f+1&127],m^=m<<13,p^=p<<17,m^=m>>>15,p^=p>>>12,g[f]=m^p;u.w=h,u.X=g,u.i=f}l(i,a)}function n(a,i){return i.i=a.i,i.w=a.w,i.X=a.X.slice(),i}function s(a,i){a==null&&(a=+new Date);var l=new o(a),u=i&&i.state,c=function(){return(l.next()>>>0)/4294967296};return c.double=function(){do var p=l.next()>>>11,m=(l.next()>>>0)/4294967296,f=(p+m)/(1<<21);while(f===0);return f},c.int32=l.next,c.quick=c,u&&(u.X&&n(u,l),c.state=function(){return n(l,{})}),c}e&&e.exports?e.exports=s:t&&t.amd?t(function(){return s}):this.xor4096=s})(_z,typeof j0=="object"&&j0,typeof define=="function"&&define)});var Iz=Ht((Cz,U0)=>{(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})(Cz,typeof U0=="object"&&U0,typeof define=="function"&&define)});var Sz=Ht((Nz,ty)=>{(function(r,e,t){var o=256,n=6,s=52,a="random",i=t.pow(o,n),l=t.pow(2,s),u=l*2,c=o-1,p;function m(w,k,_){var D=[];k=k==!0?{entropy:!0}:k||{};var T=g(h(k.entropy?[w,b(e)]:w==null?x():w,3),D),R=new f(D),O=function(){for(var M=R.g(n),G=i,j=0;M<l;)M=(M+j)*o,G*=o,j=R.g(1);for(;M>=u;)M/=2,G/=2,j>>>=1;return(M+j)/G};return O.int32=function(){return R.g(4)|0},O.quick=function(){return R.g(4)/4294967296},O.double=O,g(b(R.S),e),(k.pass||_||function(M,G,j,U){return U&&(U.S&&d(U,R),M.state=function(){return d(R,{})}),j?(t[a]=M,G):M})(O,T,"global"in k?k.global:this==t,k.state)}function f(w){var k,_=w.length,D=this,T=0,R=D.i=D.j=0,O=D.S=[];for(_||(w=[_++]);T<o;)O[T]=T++;for(T=0;T<o;T++)O[T]=O[R=c&R+w[T%_]+(k=O[T])],O[R]=k;(D.g=function(M){for(var G,j=0,U=D.i,H=D.j,q=D.S;M--;)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 _=[],D=typeof w,T;if(k&&D=="object")for(T in w)try{_.push(h(w[T],k-1))}catch(R){}return _.length?_:D=="string"?w:w+"\0"}function g(w,k){for(var _=w+"",D,T=0;T<_.length;)k[c&T]=c&(D^=k[c&T]*19)+_.charCodeAt(T++);return b(k)}function x(){try{var w;return p&&(w=p.randomBytes)?w=w(o):(w=new Uint8Array(o),(r.crypto||r.msCrypto).getRandomValues(w)),b(w)}catch(D){var k=r.navigator,_=k&&k.plugins;return[+new Date,r,_,r.screen,b(e)]}}function b(w){return String.fromCharCode.apply(0,w)}if(g(t.random(),e),typeof ty=="object"&&ty.exports){ty.exports=m;try{p=Uw()}catch(w){}}else typeof define=="function"&&define.amd?define(function(){return m}):t["seed"+a]=m})(typeof self!="undefined"?self:Nz,[],Math)});var H0=Ht((GOt,Tz)=>{var ste=hz(),ite=xz(),ate=bz(),lte=kz(),ute=vz(),cte=Iz(),gc=Sz();gc.alea=ste;gc.xor128=ite;gc.xorwow=ate;gc.xorshift7=lte;gc.xor4096=ute;gc.tychei=cte;Tz.exports=gc});var r3=Ht(()=>{});var mI="3.3.0";var fI="3.3.0";var dI="3.3.0";var hI="3.3.0";var gI="3.3.0";var pB=1e-7,mB=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?pB:mB}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 xI(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 fB(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 Ec(r,e,t){return Math.max(r,Math.min(e,t))}function dB(r){return r%2==0?r:r+1}function hB(r){let e=0;for(let t=0;t<r.length;t++)e+=r[t];return e}function gB(r,e){let t=Math.random();return e*t+(1-t)*r}function xB(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 A(r,e){if(!r)throw new Error(typeof e=="string"?e:e())}function vt(r,e,t=""){A(jr(r,e),()=>t+` Shapes ${r} and ${e} must match`)}function Do(r){A(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)||nr(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 yB(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 bB(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 wB(r){let e=Math.ceil(Math.sqrt(r));return[e,Math.ceil(r/e)]}function kB(r){let e=new Uint32Array(r);for(let t=0;t<r;++t)e[t]=t;return xI(e),e}function Ol(r,e){return e<=r.length?r:r+" ".repeat(e-r.length)}function _B(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 vB(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 Qt(r,e){let t=e.length;return r=r==null?e.map((o,n)=>n):[].concat(r),A(r.every(o=>o>=-t&&o<t),()=>`All values in axis param must be in range [-${t}, ${t}) but got axis ${r}`),A(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 vb(r,e){let t=[],o=[],n=e!=null&&Array.isArray(e)&&e.length===0,s=e==null||n?null:Qt(e,r).sort(),a=0;for(let i=0;i<r.length;++i){if(s!=null){if(s[a]===i&&r[i]!==1)throw new Error(`Can't squeeze axis ${i} since its dim '${r[i]}' is not 1`);(s[a]==null||s[a]>i)&&r[i]===1&&(t.push(r[i]),o.push(i)),s[a]<=i&&a++}r[i]!==1&&(t.push(r[i]),o.push(i))}return{newShape:t,keptDims:o}}function Cb(r,e){let t=null;if(r==null||r==="float32")t=new Float32Array(e);else if(r==="int32")t=new Int32Array(e);else if(r==="bool")t=new Uint8Array(e);else throw new Error(`Unknown data type ${r}`);return t}function Ib(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 Nb(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 Sb(r){return r==="bool"||r==="complex64"||r==="float32"||r==="int32"||r==="string"}function CB(r,e){return!(e==="complex64"||e==="float32"&&r!=="complex64"||e==="int32"&&r!=="float32"&&r!=="complex64"||e==="bool"&&r==="bool")}function nr(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 Tb(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 yI(r){return typeof r=="boolean"}function bI(r){return typeof r=="number"}function Dc(r){return Array.isArray(r)?Dc(r[0]):r instanceof Float32Array?"float32":r instanceof Int32Array||r instanceof Uint8Array?"int32":bI(r)?"float32":is(r)?"string":yI(r)?"bool":"float32"}function Us(r){return!!(r&&r.constructor&&r.call&&r.apply)}function $c(r,e){for(let t=e;t<r;++t)if(r%t==0)return t;return r}function Hs(r){let e=r.length;if(e<2)return[];let t=new Array(e-1);t[e-2]=r[e-1];for(let o=e-3;o>=0;--o)t[o]=t[o+1]*r[o+1];return t}function wI(r,e,t){let o=new Array;if(e.length===1){let n=e[0];for(let s=0;s<n;s++)o[s]=t[r+s]}else{let n=e[0],s=e.slice(1),a=s.reduce((i,l)=>i*l);for(let i=0;i<n;i++)o[i]=wI(r+i*a,s,t)}return o}function 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 wI(0,r,e)}function cm(r,e){let t=Rc(r,e);for(let o=0;o<t.length;o++)t[o]=1;return t}function Rc(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 IB(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 pm(r){r.forEach(e=>{A(Number.isInteger(e)&&e>=0,()=>`Tensor must have a shape comprised of positive integers but got shape [${r}].`)})}function NB(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 SB(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 mm(r){return r&&r.then&&typeof r.then=="function"}var kI="tfjsflags",zh=class{constructor(e){this.global=e,this.flags={},this.flagRegistry={},this.urlFlags={},this.populateURLFlags()}setPlatform(e,t){this.platform!=null&&console.warn(`Platform ${this.platformName} has already been set. Overwriting the platform with ${t}.`),this.platformName=e,this.platform=t}registerFlag(e,t,o){if(this.flagRegistry[e]={evaluationFn:t,setHook:o},this.urlFlags[e]!=null){let n=this.urlFlags[e];console.warn(`Setting feature override from URL ${e}: ${n}.`),this.set(e,n)}}async getAsync(e){return e in this.flags?this.flags[e]:(this.flags[e]=await this.evaluateFlag(e),this.flags[e])}get(e){if(e in this.flags)return this.flags[e];let t=this.evaluateFlag(e);if(mm(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=TB(this.global.location.search);kI in e&&e[kI].split(",").forEach(o=>{let[n,s]=o.split(":");this.urlFlags[n]=AB(n,s)})}};function TB(r){let e={};return r.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,(t,...o)=>(EB(e,o[0],o[1]),o.join("="))),e}function EB(r,e,t){r[decodeURIComponent(e)]=decodeURIComponent(t||"")}function AB(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 Ab}var Ab=null;function _I(r){Ab=r}var Eb;function Db(){if(Eb==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");Eb=r}return Eb}function DB(){let r=Db();return r._tfGlobals==null&&(r._tfGlobals=new Map),r._tfGlobals}function fm(r,e){let t=DB();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",$b="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",Fc="Dilation2DBackpropInput",Oc="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",Rb="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",$B="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",Pc="FromPixels",$i="RotateWithOffset",ws="_FusedMatMul",ks="FusedConv2D",_s="FusedDepthwiseConv2D";var Mc=fm("kernelRegistry",()=>new Map),dm=fm("gradRegistry",()=>new Map);function Lc(r,e){let t=Fb(r,e);return Mc.get(t)}function Bh(r){return dm.get(r)}function hm(r){let e=Mc.entries(),t=[];for(;;){let{done:o,value:n}=e.next();if(o)break;let[s,a]=n,[i]=s.split("_");i===r&&t.push(a)}return t}function el(r){let{kernelName:e,backendName:t}=r,o=Fb(e,t);Mc.has(o)&&console.warn(`The kernel '${e}' for backend '${t}' is already registered`),Mc.set(o,r)}function Ob(r){let{kernelName:e}=r;dm.has(e)&&W().getBool("DEBUG")&&console.warn(`Overriding the gradient for '${e}'`),dm.set(e,r)}function RB(r,e){let t=Fb(r,e);if(!Mc.has(t))throw new Error(`The kernel '${r}' for backend '${e}' is not registered`);Mc.delete(t)}function FB(r){if(!dm.has(r))throw new Error(`The gradient '${r}' for backend is not registered`);dm.delete(r)}function OB(r,e){hm(r).forEach(o=>{let n=Object.assign({},o,{backendName:e});el(n)})}function Fb(r,e){return`${e}_${r}`}var y={};Ke(y,{arraysEqual:()=>jr,assert:()=>A,assertNonNegativeIntegerDimensions:()=>pm,assertNonNull:()=>Do,assertShapesMatch:()=>vt,bytesFromStringArray:()=>Tb,bytesPerElement:()=>Lh,checkConversionForErrors:()=>Nb,clamp:()=>Ec,computeStrides:()=>Hs,createScalarValue:()=>PB,createShuffledIndices:()=>kB,decodeString:()=>Bc,distSquared:()=>xB,encodeString:()=>tl,fetch:()=>LB,flatten:()=>ss,getArrayFromDType:()=>Ib,getTypedArrayFromDType:()=>Cb,hasEncodingLoss:()=>CB,indexToLoc:()=>SB,inferDtype:()=>Dc,inferFromImplicitShape:()=>vB,isBoolean:()=>yI,isFunction:()=>Us,isInt:()=>ot,isNumber:()=>bI,isPromise:()=>mm,isScalarShape:()=>yB,isString:()=>is,isTypedArray:()=>nr,isValidDtype:()=>Sb,locToIndex:()=>NB,makeOnesTypedArray:()=>cm,makeZerosNestedTypedArray:()=>IB,makeZerosTypedArray:()=>Rc,nearestDivisor:()=>$c,nearestLargerEven:()=>dB,now:()=>mu,parseAxisParam:()=>Qt,randUniform:()=>gB,repeatedTry:()=>_B,rightPad:()=>Ol,shuffle:()=>xI,shuffleCombo:()=>fB,sizeFromShape:()=>ct,sizeToSquarishShape:()=>wB,squeezeShape:()=>vb,sum:()=>hB,tanh:()=>bB,toNestedArray:()=>Pl,toTypedArray:()=>zc});function PB(r,e){return e==="string"?tl(r):zc([r],e)}function MB(r,e){return r instanceof Float32Array&&e==="float32"||r instanceof Int32Array&&e==="int32"||r instanceof Uint8Array&&e==="bool"}function zc(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")&&Nb(r,e),MB(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 LB(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 Bc(r,e="utf-8"){return e=e||"utf-8",W().platform.decode(r,e)}var Pb=class{constructor(e,t){this.backendTimer=e,this.logger=t,t==null&&(this.logger=new vI)}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=>{zB(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 zB(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 vI=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 CI(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 II(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 NI=20,gm=3,Mb=7;function SI(r,e,t,o){let n=Hs(e),s=BB(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 BB(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"?ym(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],xm(l[c+p],0,t).length)}return a}function xm(r,e,t){let o;return Array.isArray(r)?o=`${parseFloat(r[0].toFixed(Mb))} + ${parseFloat(r[1].toFixed(Mb))}j`:is(r)?o=`'${r}'`:t==="bool"?o=TI(r):o=parseFloat(r.toFixed(Mb)).toString(),Ol(o,e)}function TI(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=ym(r);return[xm(h[0],0,t)]}return t==="bool"?[TI(r[0])]:[r[0].toString()]}if(l===1){if(i>NI){let g=gm*a,x=Array.from(r.slice(0,g)),b=Array.from(r.slice((i-gm)*a,i*a));return t==="complex64"&&(x=ym(x),b=ym(b)),["["+x.map((w,k)=>xm(w,n[k],t)).join(", ")+", ..., "+b.map((w,k)=>xm(w,n[i-gm+k],t)).join(", ")+"]"]}let h=t==="complex64"?ym(r):Array.from(r);return["["+h.map((g,x)=>xm(g,n[x],t)).join(", ")+"]"]}let u=e.slice(1),c=o.slice(1),p=o[0]*a,m=[];if(i>NI){for(let h=0;h<gm;h++){let g=h*p,x=g+p;m.push(...Vh(r.slice(g,x),u,t,c,n,!1))}m.push("...");for(let h=i-gm;h<i;h++){let g=h*p,x=g+p;m.push(...Vh(r.slice(g,x),u,t,c,n,h===i-1))}}else for(let h=0;h<i;h++){let g=h*p,x=g+p;m.push(...Vh(r.slice(g,x),u,t,c,n,h===i-1))}let f=l===2?",":"";m[0]="["+m[0]+f;for(let h=1;h<m.length-1;h++)m[h]=" "+m[h]+f;let d=`,
|
|
`;for(let h=2;h<l;h++)d+=`
|
|
`;return m[m.length-1]=" "+m[m.length-1]+"]"+(s?"":d),m}function ym(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;A(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||Ib(t,this.size),this.strides=Hs(e)}set(e,...t){t.length===0&&(t=[0]),A(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,Vc=null,VB=null;function AI(r){Ri=r}function EI(r){Vc=r}function DI(r){VB=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 Vc.buffer(this.shape,this.dtype,e)}bufferSync(){return Vc.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=>Bc(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=>Bc(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 Vc.print(this,e)}clone(){return this.throwIfDisposed(),Vc.clone(this)}toString(e=!1){let t=this.dataSync();return SI(t,this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),Vc.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 fm("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:()=>Wb,getTensorsInContainer:()=>bm,isTensorInList:()=>WB,makeTypesMatch:()=>Ge});var Lb;(function(r){r.R0="R0",r.R1="R1",r.R2="R2",r.R3="R3",r.R4="R4",r.R5="R5",r.R6="R6"})(Lb||(Lb={}));var zb;(function(r){r.float32="float32",r.int32="int32",r.bool="int32",r.complex64="complex64"})(zb||(zb={}));var Bb;(function(r){r.float32="float32",r.int32="int32",r.bool="bool",r.complex64="complex64"})(Bb||(Bb={}));var Vb;(function(r){r.float32="float32",r.int32="float32",r.bool="float32",r.complex64="complex64"})(Vb||(Vb={}));var Gb;(function(r){r.float32="complex64",r.int32="complex64",r.bool="complex64",r.complex64="complex64"})(Gb||(Gb={}));var GB={float32:Vb,int32:zb,bool:Bb,complex64:Gb};function dr(r,e){if(r==="string"||e==="string"){if(r==="string"&&e==="string")return"string";throw new Error(`Can not upcast ${r} with ${e}`)}return GB[r][e]}function fu(r){return dr(r,"int32")}function Ge(r,e){if(r.dtype===e.dtype)return[r,e];let t=dr(r.dtype,e.dtype);return[r.cast(t),e.cast(t)]}function Wb(r,e){A(r.dtype===e.dtype,()=>`The dtypes of the first(${r.dtype}) and second(${e.dtype}) input must match`)}function WB(r,e){return e.some(t=>t.id===r.id)}function bm(r){let e=[],t=new Set;return $I(r,e,t),e}function $I(r,e,t){if(r==null)return;if(r instanceof Ve){e.push(r);return}if(!jB(r))return;let o=r;for(let n in o){let s=o[n];t.has(s)||(t.add(s),$I(s,e,t))}}function jB(r){return Array.isArray(r)||typeof r=="object"}function jb(r){return r.kernelName!=null}var Ub=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 Ub}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 Pb(this.backendInstance),!0}setupRegisteredKernels(){hm(this.backendName).forEach(t=>{t.setupFunc!=null&&t.setupFunc(this.backendInstance)})}disposeRegisteredKernels(e){hm(e).forEach(o=>{o.disposeFunc!=null&&o.disposeFunc(this.registry[e])})}initializeBackend(e){let t=this.registryFactory[e];if(t==null)throw new Error(`Cannot initialize backend ${e}, no registration found.`);try{let o=t.factory();if(o&&!(o instanceof 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(!(Lc(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=jb(e)?e.kernelName:this.state.activeScope!=null?this.state.activeScope.name:"";if(jb(e)){let{kernelName:d,inputs:h,attrs:g}=e;this.backendName==null&&this.backend;let x=Lc(d,this.backendName);A(x!=null,()=>`Cannot find registered kernel '${d}' for backend '${this.backendName}'`),i=()=>{let b=this.backend.numDataIds();l=x.kernelFunc({inputs:h,attrs:g,backend:this.backend});let w=Array.isArray(l)?l:[l];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(d,b,w);let k=w.map(_=>{if(_.rank!=null)return _;let{dataId:D,shape:T,dtype:R}=_;return this.makeTensorFromDataId(D,T,R)});if(n){let _=this.getTensorsForGradient(d,h,k);o=this.saveTensorsForBackwardMode(_)}return k}}else{let{forwardFunc:d}=e,h=g=>{!n||(o=g.map(x=>this.keep(this.clone(x))))};i=()=>{let g=this.backend.numDataIds();l=this.tidy(()=>d(this.backend,h));let x=Array.isArray(l)?l:[l];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(u,g,x),x}}let{inputs:c,attrs:p}=e,m=jb(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?(A(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=Tb(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=Rc(m.size,m.dtype);return this.makeTensor(f,m.shape,m.dtype)}return c}),n(u.length>1?u:u[0],s,a))),this.state.activeTape.push(i)}keep(e){return e.kept=!0,e}startTape(){this.state.gradientDepth===0&&(this.state.activeTape=[]),this.state.gradientDepth++}endTape(){this.state.gradientDepth--}startScope(e){let t={track:[],name:"unnamed scope",id:this.state.nextScopeId++};e&&(t.name=e),this.state.scopeStack.push(t),this.state.activeScope=t}endScope(e){let t=bm(e),o=new Set(t.map(s=>s.id));for(let s=0;s<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(A(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));A(s instanceof Ve,()=>"The result y returned by f() must be a tensor.");let a=CI(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?UB(s.shape):o,II(i,a,u=>this.tidy(u),HB);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 A(Us(e),()=>"The f passed in customGrad(f) must be a function."),(...t)=>{A(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),A(o.value instanceof Ve,()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"),A(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];A(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(...)."),A(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 Ub;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 UB(r){let e=cm(ct(r),"float32");return E.makeTensor(e,r,"float32")}function Hb(){let r=Db();if(r._tfengine==null){let e=new zh(r);r._tfengine=new du(e)}return _I(r._tfengine.ENV),AI(()=>r._tfengine),r._tfengine}var E=Hb();function HB(r,e){let t={a:r,b:e};return E.runKernel(wo,t)}var hu={};Ke(hu,{isBrowser:()=>qb,isMobile:()=>KB});function qB(){return typeof navigator!="undefined"&&navigator!=null}function KB(){if(qB()){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 qb(){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",()=>qb());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 Cr(r,e){let t=r;if(nr(r))return e==="string"?[]:[r.length];if(!Array.isArray(r))return[];let o=[];for(;Array.isArray(t)||nr(t)&&e!=="string";)o.push(t.length),t=t[0];return Array.isArray(r)&&W().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&RI(r,o,[]),o}function RI(r,e,t){if(t=t||[],!Array.isArray(r)&&!nr(r)){A(e.length===0,()=>`Element arr[${t.join("][")}] is a primitive, but should be an array/TypedArray of ${e[0]} elements`);return}A(e.length>0,()=>`Element arr[${t.join("][")}] should be a primitive, but is an array of ${r.length} elements`),A(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)RI(r[n],o,t.concat(n))}function FI(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 v(r,e,t,o="numeric"){if(r instanceof Ve)return FI(o,r.dtype,e,t),r;let n=Dc(r);if(n!=="string"&&["bool","int32","float32"].indexOf(o)>=0&&(n=o),FI(o,n,e,t),r==null||!nr(r)&&!Array.isArray(r)&&typeof r!="number"&&typeof r!="boolean"&&typeof r!="string"){let l=r==null?"null":r.constructor.name;throw new Error(`Argument '${e}' passed to '${t}' must be a Tensor or TensorLike, but got '${l}'`)}let s=Cr(r,n);!nr(r)&&!Array.isArray(r)&&(r=[r]);let i=n!=="string"?zc(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)=>v(s,`${e}[${a}]`,t,o))}var OI="__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+OI;let n=(...s)=>{E.startScope(t);try{let a=o(...s);return mm(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 XB(r,e){let t=v(r,"real","complex"),o=v(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_:XB});function Ur(r,e,t,o){if(o==null&&(o=Dc(r)),o==="complex64")throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(!nr(r)&&!Array.isArray(r)&&typeof r!="number"&&typeof r!="boolean"&&typeof r!="string")throw new Error("values passed to tensor(values) must be a number/boolean/string or an array of numbers/booleans/strings, or a TypedArray");if(e!=null){pm(e);let n=ct(e),s=ct(t);A(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;A(t[a]===e[a]||!l,()=>`Error creating a new Tensor. Inferred shape (${t}) does not match the provided shape (${e}). `)}}return!nr(r)&&!Array.isArray(r)&&(r=[r]),e=e||t,r=o!=="string"?zc(r,o):ss(r,[],!0),E.makeTensor(r,e,o)}function Rr(r,e,t){let o=Cr(r,t);return Ur(r,e,o,t)}var wm={float32:4,float16:2,int32:4,uint16:2,uint8:1,bool:1,complex64:8};var Gh=4;async function PI(r,e){let t=[],o=[],n=Array.isArray(r)?r.map(a=>a.name):Object.keys(r);for(let a=0;a<n.length;++a){let i=n[a],l=Array.isArray(r)?r[a].tensor:r[i];if(l.dtype!=="float32"&&l.dtype!=="int32"&&l.dtype!=="bool"&&l.dtype!=="string"&&l.dtype!=="complex64")throw new Error(`Unsupported dtype in weight '${i}': ${l.dtype}`);let u={name:i,shape:l.shape,dtype:l.dtype};if(l.dtype==="string"){let c=new Promise(async p=>{let m=await l.bytes(),f=m.reduce((g,x)=>g+x.length,0)+Gh*m.length,d=new Uint8Array(f),h=0;for(let g=0;g<m.length;g++){let x=m[g],b=new Uint8Array(new Uint32Array([x.length]).buffer);d.set(b,h),h+=Gh,d.set(x,h),h+=x.length}p(d)});o.push(c)}else o.push(l.data());e!=null&&(u.group=e),t.push(u)}let s=await Promise.all(o);return{data:YB(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=wm[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=ZB()),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=wm[i],m=r.slice(n,n+u*p);if(i==="float32")c=new Float32Array(m);else if(i==="int32")c=new Int32Array(m);else if(i==="bool")c=new Uint8Array(m);else if(i==="complex64"){c=new Float32Array(m);let f=new Float32Array(c.length/2),d=new Float32Array(c.length/2);for(let x=0;x<f.length;x++)f[x]=c[x*2],d[x]=c[x*2+1];let h=Rr(f,l,"float32"),g=Rr(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]=Rr(c,l,i))}return t}function YB(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 Kb=typeof Buffer!="undefined"&&(typeof Blob=="undefined"||typeof atob=="undefined"||typeof btoa=="undefined");function MI(r){return Kb?Buffer.byteLength(r):new Blob([r]).size}function LI(r){if(Kb)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 zI(r){if(Kb){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 Gc(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 Xb(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:MI(JSON.stringify(r.modelTopology)),weightSpecsBytes:r.weightSpecs==null?0:MI(JSON.stringify(r.weightSpecs)),weightDataBytes:r.weightData==null?0:r.weightData.byteLength}}function JB(){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 QB(){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 eV(){let r=new Uint32Array(64);for(let e=0;e<64;e++)r[e]=1024;return r[0]=r[32]=0,r}function ZB(){let r=JB(),e=QB(),t=eV();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}},BI=r=>Ct.registerSaveRouter(r),VI=r=>Ct.registerLoadRouter(r),GI=r=>Ct.getSaveHandlers(r),WI=(r,e)=>Ct.getLoadHandlers(r,e);var Yb="tensorflowjs",Zb=1,gu="models_store",ol="model_info_store";function jI(){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 Jb(r){let e=r.result;e.createObjectStore(gu,{keyPath:"modelPath"}),e.createObjectStore(ol,{keyPath:"modelPath"})}var ga=class{constructor(e){if(this.indexedDB=jI(),e==null||!e)throw new Error("For IndexedDB, modelPath must not be null, undefined or empty.");this.modelPath=e}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");return this.databaseAction(this.modelPath,e)}async load(){return this.databaseAction(this.modelPath)}databaseAction(e,t){return new Promise((o,n)=>{let s=this.indexedDB.open(Yb,Zb);s.onupgradeneeded=()=>Jb(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 UI=r=>W().getBool("IS_BROWSER")&&!Array.isArray(r)&&r.startsWith(ga.URL_SCHEME)?tV(r.slice(ga.URL_SCHEME.length)):null;Ct.registerSaveRouter(UI);Ct.registerLoadRouter(UI);function tV(r){return new ga(r)}function rV(r){return r.startsWith(ga.URL_SCHEME)?r.slice(ga.URL_SCHEME.length):r}var Qb=class{constructor(){this.indexedDB=jI()}async listModels(){return new Promise((e,t)=>{let o=this.indexedDB.open(Yb,Zb);o.onupgradeneeded=()=>Jb(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=rV(e),new Promise((t,o)=>{let n=this.indexedDB.open(Yb,Zb);n.onupgradeneeded=()=>Jb(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="/",Wc="tensorflowjs_models",HI="info",oV="model_topology",nV="weight_specs",sV="weight_data",iV="model_metadata";function qI(r){return{info:[Wc,r,HI].join(xa),topology:[Wc,r,oV].join(xa),weightSpecs:[Wc,r,nV].join(xa),weightData:[Wc,r,sV].join(xa),modelMetadata:[Wc,r,iV].join(xa)}}function aV(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 lV(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=qI(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,LI(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=zI(a),t}};ya.URL_SCHEME="localstorage://";var KI=r=>W().getBool("IS_BROWSER")&&!Array.isArray(r)&&r.startsWith(ya.URL_SCHEME)?uV(r.slice(ya.URL_SCHEME.length)):null;Ct.registerSaveRouter(KI);Ct.registerLoadRouter(KI);function uV(r){return new ya(r)}var ew=class{constructor(){A(W().getBool("IS_BROWSER"),()=>"Current environment is not a web browser"),A(typeof window=="undefined"||typeof window.localStorage!="undefined",()=>"Current browser does not appear to support localStorage"),this.LS=window.localStorage}async listModels(){let e={},t=Wc+xa,o=xa+HI;for(let n=0;n<this.LS.length;++n){let s=this.LS.key(n);if(s.startsWith(t)&&s.endsWith(o)){let a=aV(s);e[a]=JSON.parse(this.LS.getItem(s))}}return e}async removeModel(e){e=lV(e);let t=qI(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 jc="://",Hr=class{constructor(){this.managers={}}static getInstance(){return Hr.instance==null&&(Hr.instance=new Hr),Hr.instance}static registerManager(e,t){A(e!=null,()=>"scheme must not be undefined or null."),e.endsWith(jc)&&(e=e.slice(0,e.indexOf(jc))),A(e.length>0,()=>"scheme must not be an empty string.");let o=Hr.getInstance();A(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(jc)===-1)throw new Error(`The url string provided does not contain a scheme. Supported schemes are: ${Hr.getSchemes().join(",")}`);return{scheme:r.split(jc)[0],path:r.split(jc)[1]}}async function XI(r,e,t=!1){A(r!==e,()=>`Old path and new path are the same: '${r}'`);let o=Ct.getLoadHandlers(r);A(o.length>0,()=>`Copying failed because no load handler is found for source URL ${r}.`),A(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);A(s.length>0,()=>`Copying failed because no save handler is found for destination URL ${e}.`),A(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 YI(){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+jc+n;e[s]=o[n]}}return e}async function ZI(r){let e=jh(r);return Hr.getManager(e.scheme).removeModel(e.path)}async function JI(r,e){return XI(r,e,!1)}async function QI(r,e){return XI(r,e,!0)}var eN=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 eN);try{Hr.registerManager(ya.URL_SCHEME,new ew)}catch(r){}try{Hr.registerManager(ga.URL_SCHEME,new Qb)}catch(r){}}var cV={importFetch:()=>tN()},tw;var rN=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):(tw==null&&(tw=cV.importFetch()),tw(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 rN);function ve(r,e="float32",t){return e=e||"float32",pm(r),new lt(r,e,t)}function pV(r,e){let t=v(r,"x","cast");if(!Sb(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_:pV});function mV(r){let t={x:v(r,"x","clone","string_or_numeric")};return E.runKernel(Fo,t)}var Po=S({clone_:mV});function rw(r,e=!1){console.log(r.toString(e))}Hb();var fV={buffer:ve,cast:ne,clone:Po,print:rw};EI(fV);var Ir={};Ke(Ir,{browserFiles:()=>sN,browserHTTPRequest:()=>lN,concatenateArrayBuffers:()=>Gc,copyModel:()=>JI,decodeWeights:()=>Wh,encodeWeights:()=>PI,fromMemory:()=>cN,getLoadHandlers:()=>WI,getModelArtifactsInfoForJSON:()=>Fi,getSaveHandlers:()=>GI,http:()=>qh,isHTTPScheme:()=>Hh,listModels:()=>YI,loadWeights:()=>iN,moveModel:()=>QI,registerLoadRouter:()=>VI,registerSaveRouter:()=>BI,removeModel:()=>ZI,weightsLoaderFactory:()=>sw,withSaveHandler:()=>pN});var dV="model",hV=".json",gV=".weights.bin";function oN(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=dV),this.modelTopologyFileName=e+hV,this.weightDataFileName=e+gV}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 oN(()=>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 oN(()=>i.dispatchEvent(new MouseEvent("click")))}return{modelArtifactsInfo:Fi(e)}}}};nl.URL_SCHEME="downloads://";var nN=class{constructor(e){if(e==null||e.length<1)throw new Error(`When calling browserFiles, at least 1 file is required, but received ${e}`);this.files=e}async load(){let e=this.files[0],t=this.files.slice(1);return new Promise((o,n)=>{let s=new FileReader;s.onload=a=>{let i=JSON.parse(a.target.result),l=i.modelTopology;if(l==null){n(new Error(`modelTopology field is missing from file ${e.name}`));return}t.length===0&&o({modelTopology:l});let u=i.weightsManifest;if(u==null){n(new Error(`weightManifest field is missing from file ${e.name}`));return}let c;try{c=this.checkManifestAndWeightFiles(u,t)}catch(d){n(d);return}let p=[],m=[],f=[];u.forEach(d=>{d.paths.forEach(h=>{m.push(h),f.push(null)}),p.push(...d.weights)}),u.forEach(d=>{d.paths.forEach(h=>{let g=new FileReader;g.onload=x=>{let b=x.target.result,w=m.indexOf(h);if(f[w]=b,f.indexOf(null)===-1){let k={modelTopology:l,weightSpecs:p,weightData:Gc(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=x=>n(`Failed to weights data from file of path '${h}'.`),g.readAsArrayBuffer(c[h])})})},s.onerror=a=>n(`Failed to read model topology and weights manifest JSON from file '${e.name}'. BrowserFiles supports loading Keras-style tf.Model artifacts only.`),s.readAsText(e)})}checkManifestAndWeightFiles(e,t){let o=[],n=t.map(a=>Xb(a.name)),s={};for(let a of e)a.paths.forEach(i=>{let l=Xb(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}},yV=r=>W().getBool("IS_BROWSER")&&!Array.isArray(r)&&r.startsWith(nl.URL_SCHEME)?xV(r.slice(nl.URL_SCHEME.length)):null;Ct.registerSaveRouter(yV);function xV(r="model"){return new nl(r)}function sN(r){return new nN(r)}function ow(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){A(l!=null&&Array.isArray(l)&&l.length>0,()=>"promises must be a none empty array")}function i(l,u){A(l>=0&&l<=1,()=>`Progress fraction must be in range [0, 1], but got startFraction ${l}`),A(u>=0&&u<=1,()=>`Progress fraction must be in range [0, 1], but got endFraction ${u}`),A(u>=l,()=>`startFraction must be no more than endFraction, but got startFraction ${l} and endFraction ${u}`)}return Promise.all(r.map(s))}async function nw(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 ow(o,e.onProgress,n,s)).map(p=>p.arrayBuffer()),l=.5,u=1;return e.onProgress==null?await Promise.all(i):await ow(i,e.onProgress,l,u)}async function iN(r,e="",t,o){return sw(a=>nw(a,{requestInit:o}))(r,e,t)}function sw(r){return async(e,t="",o)=>{let n=e.map(()=>!1),s={},a=o!=null?o.map(()=>!1):[],i=[];if(e.forEach((f,d)=>{let h=0;f.weights.forEach(g=>{let x="quantization"in g?g.quantization.dtype:g.dtype,b=wm[x]*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,_)=>{k===g.name&&(w(),a[_]=!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),x=new Uint8Array(g),b=0;for(let k=0;k<d;k++){let _=new Uint8Array(c[m+k]);x.set(_,b),b+=_.byteLength}s[f].forEach(k=>{let _=g.slice(k.groupOffset,k.groupOffset+k.sizeBytes),D=Wh(_,[k.manifestEntry]);for(let T in D)p[T]=D[T]}),m+=d}),p}}var bV="application/octet-stream",wV="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?(A(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,A(e!=null&&e.length>0,()=>"URL path for http must not be null, undefined or empty."),Array.isArray(e)&&A(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:wV}),"model.json"),e.weightData!=null&&t.body.append("model.weights.bin",new Blob([e.weightData],{type:bV}),"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]=kV(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 nw(i,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress});return[a,Gc(u)]}};Uh.URL_SCHEME_REGEX=/^https?:\/\//;function kV(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 aN=(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(aN);Ct.registerLoadRouter(aN);function qh(r,e){return new Uh(r,e)}function lN(r,e){return qh(r,e)}var Kh=class{constructor(e){this.modelArtifacts=e}async load(){return this.modelArtifacts}},uN=class{constructor(e){this.saveHandler=e}async save(e){return this.saveHandler(e)}};function cN(r,e,t,o){return arguments.length===1?r.modelTopology!=null||r.weightSpecs!=null?new 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 pN(r){return new uN(r)}var mN={};Ke(mN,{confusionMatrix:()=>NV});function _V(r,e,t=!1,o=!1){let n=v(r,"a","matMul"),s=v(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_:_V});function vV(r,e,t=1,o=0){if(e<2)throw new Error(`Error in oneHot: depth must be >=2, but it is ${e}`);let s={indices:v(r,"indices","oneHot","int32")},a={depth:e,onValue:t,offValue:o};return E.runKernel(yn,s,a)}var Cs=S({oneHot_:vV});function CV(r,e){let t=v(r,"x","transpose");if(e==null&&(e=t.shape.map((s,a)=>a).reverse()),A(t.rank===e.length,()=>`Error in transpose: rank of input ${t.rank} must match length of perm ${e}.`),e.forEach(s=>{A(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_:CV});function IV(r,e,t){let o=v(r,"labels","confusionMatrix"),n=v(e,"predictions","confusionMatrix");A(t==null||t>0&&Number.isInteger(t),()=>`If provided, numClasses must be a positive integer, but got ${t}`),A(o.rank===1,()=>`Expected the rank of labels to be 1, but got ${o.rank}`),A(n.rank===1,()=>`Expected the rank of predictions to be 1, but got ${n.rank}`),A(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.`),A(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 NV=S({confusionMatrix_:IV});var Xh={};Ke(Xh,{fromPixels:()=>RV,fromPixelsAsync:()=>DV,toPixels:()=>$V});function iw(r,e,t){if(Do(r),e!=null&&e.length!==3)throw new Error("tensor3d() requires shape to have three numbers");let o=Cr(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 Uc;function fN(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(Lc(Pc,E.backendName)!=null){let d={pixels:r},h={numChannels:e};return E.runKernel(Pc,d,h)}let[u,c]=n?[r.videoWidth,r.videoHeight]:[r.width,r.height],p;a?p=r.getContext("2d").getImageData(0,0,u,c).data:o||t?p=r.data:(s||n||i)&&(Uc==null&&(Uc=document.createElement("canvas").getContext("2d")),Uc.canvas.width=u,Uc.canvas.height=c,Uc.drawImage(r,0,0,u,c),p=Uc.getImageData(0,0,u,c).data);let m;if(e===4)m=new Int32Array(p);else{let d=u*c;m=new Int32Array(d*e);for(let h=0;h<d;h++)for(let g=0;g<e;++g)m[h*e+g]=p[h*4+g]}return iw(m,[c,u,e],"int32")}function SV(r){return r!=null&&r.data instanceof Uint8Array}function TV(){return typeof window!="undefined"&&typeof ImageBitmap!="undefined"&&window.hasOwnProperty("createImageBitmap")}function AV(r){return r!=null&&r.width!==0&&r.height!==0}function EV(r){return TV()&&!(r instanceof ImageBitmap)&&AV(r)&&!SV(r)}async function DV(r,e=3){let t=null;if(W().getBool("WRAP_TO_IMAGEBITMAP")&&EV(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 fN(t,e)}async function $V(r,e){let t=v(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 RV=S({fromPixels_:fN});var Yh={};Ke(Yh,{prepareAndValidate:()=>dN});function dN(r,e){let t=r.shape.length,o=e.shape.length;if(t<1)throw new Error(`tf.gatherND() expects the input to be rank 1 or higher, but the rank was ${t}.`);if(o<1)throw new Error(`tf.gatherND() expects the indices to be rank 1 or higher, but the rank was ${o}.`);if(e.dtype!=="int32")throw new Error(`tf.gatherND() expects the indices to be int32 type, but the dtype was ${e.dtype}.`);if(e.shape[o-1]>t)throw new Error(`index innermost dimension length must be <= tensor rank; saw: ${e.shape[o-1]} vs. ${t}`);if(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:()=>hN,validateInput:()=>Jh,validateUpdateShape:()=>aw});function aw(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}`)}aw(t,e,r)}function hN(r,e,t){let o=e.shape.length,n=o>1?e.shape[o-1]:1,s=t.length,a=1;for(let p=n;p<s;++p)a*=t[p];let i=n<1?1:n,l=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 sr={};Ke(sr,{assertParamsValid:()=>FV,computeFlatOffset:()=>PV,computeOutShape:()=>gN,getNormalizedAxes:()=>IN,isSliceContinous:()=>OV,maskToAxes:()=>Qh,parseSliceParams:()=>lw,sliceInfo:()=>MV,startForAxis:()=>vN,startIndicesWithElidedDims:()=>wN,stopForAxis:()=>CN,stopIndicesWithElidedDims:()=>kN,stridesForAxis:()=>_N,stridesWithElidedDims:()=>xN});function FV(r,e,t){let o=r.shape.length;A(o===e.length,()=>`Error in slice${o}D: Length of begin ${e} must match the rank of the array (${o}).`),A(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)A(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 gN(r,e,t){let o=[];for(let n=0;n<r.length;n++)o[n]=Math.ceil((e[n]-r[n])/t[n]);return o}function xN(r,e,t,o){let n=[...r];for(let s=n.length;s<o.length;s++)n.push(1);for(let s=0;s<t;s++)s===0?n[e]=1:(n.splice(e,0,1),n.pop());return n}function yN(r,e,t){return t<=r?t:t-(e-1)}function bN(r,e){let t=[];for(let o=0;o<r;o++)t.push(e+o);return t}function IN(r,e,t,o,n,s,a,i,l){let u=r.length,c=new Array(u),p=new Array(u),m=new Array(u);if(e.length&&t>0){let f=e[0],d=t+1;c=wN(a,f,d,o,r),p=kN(i,f,d,n,r),m=xN(s,f,d,r)}else for(let f=0;f<u;f++)c[f]=vN(a,o,s,r,f,l),p[f]=CN(i,n,s,r,f,l),m[f]=_N(s,f,l);return{begin:c,end:p,strides:m}}function wN(r,e,t,o,n){let s=[...n],a=bN(t,e);for(let i=0;i<s.length;i++)if(a.indexOf(i)>-1)s[i]=0;else{let l=yN(e,t,i),u=o[l];r&1<<l&&(u=0),s[i]=u}return s}function kN(r,e,t,o,n){let s=[...n],a=bN(t,e);for(let i=0;i<s.length;i++)if(a.indexOf(i)>-1)s[i]=Number.MAX_SAFE_INTEGER;else{let l=yN(e,t,i),u=o[l];r&1<<l&&(u=Number.MAX_SAFE_INTEGER),s[i]=u}for(let i=0;i<s.length;i++){let l=n[i];s[i]<0&&(s[i]+=l),s[i]=Ec(0,s[i],n[i])}return s}function _N(r,e,t){let o=r[e];return(t&1<<e||o==null)&&(o=1),o}function vN(r,e,t,o,n,s){let a=e[n],i=t[n]||1;(r&1<<n||s&1<<n||a==null)&&(i>0?a=Number.MIN_SAFE_INTEGER:a=Number.MAX_SAFE_INTEGER);let l=o[n];return a<0&&(a+=l),a=Ec(0,a,l-1),a}function CN(r,e,t,o,n,s){let a=e[n],i=t[n]||1;(r&1<<n||s&1<<n||a==null)&&(i>0?a=Number.MAX_SAFE_INTEGER:a=Number.MIN_SAFE_INTEGER);let l=o[n];return a<0&&(a+=l),i>0?a=Ec(0,a,l):a=Ec(-1,a,l-1),a}function OV(r,e,t){let o=t.length;for(let n=0;n<t.length;n++)if(t[n]>1){o=n;break}for(let n=o+1;n<t.length;n++)if(e[n]>0||t[n]!==r[n])return!1;return!0}function PV(r,e){let t=r.length>0?r[r.length-1]:1;for(let o=0;o<r.length-1;o++)t+=r[o]*e[o];return t}function lw(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=>{A(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:(A(a===-1,()=>`Negative size values should be exactly -1 but got ${a} for the slice() size at index ${i}.`),r.shape[i]-o[i])),[o,s]}function MV(r,e,t,o,n,s,a,i,l){let u=e.slice(),c=t.slice(),p=o;o==null&&(p=new Array(u.length));let m=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(T=>{u[T]=0,c[T]=1,h.splice(T,0,1)});let{begin:g,end:x,strides:b}=IN(h,m,f,u,c,p,n,s,a);u=g,c=x,p=b;let w=Qh(l);w.forEach(T=>{c[T]=u[T]+1,p[T]=1});let k=gN(u,c,p),_=k.filter((T,R)=>w.indexOf(R)===-1);return{nonStrided:p.every(T=>T===1),$begin:u,$end:c,$strides:p,size:k,newShape:h,outShape:_}}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){A(r.className!=null,()=>"Class being registered does not have the static className property defined."),A(typeof r.className=="string",()=>"className is required to be a string, but got type "+typeof r.className),A(r.className.length>0,()=>"Class being registered has an empty-string as its className, which is disallowed."),ba.register(r)}var NN={};Ke(NN,{TEST_EPSILON_FLOAT16:()=>SN,encodeStrings:()=>TN,expectArrayBuffersEqual:()=>jV,expectArraysClose:()=>zV,expectArraysEqual:()=>VV,expectNumbersClose:()=>GV,expectPromiseToFail:()=>BV,expectValuesInRange:()=>WV,testEpsilon:()=>uw});var LV=.001,SN=.1;function zV(r,e,t){return t==null&&(t=uw()),cw(r,e,(o,n)=>pw(o,n,t))}function uw(){return E.backend.floatPrecision()===32?LV:SN}function cw(r,e,t){let o=!0;if((nr(r)||nr(e))&&(o=!1),nr(r)&&nr(e)&&(o=!0),o){let a=r.constructor.name,i=e.constructor.name;if(a!==i)throw new Error(`Arrays are of different type. Actual: ${a}. Expected: ${i}`)}if(Array.isArray(r)&&Array.isArray(e)){let a=Cr(r),i=Cr(e);if(!jr(a,i))throw new Error(`Arrays have different shapes. Actual: [${a}]. Expected: [${i}]`)}let n=nr(r)?r:ss(r),s=nr(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 BV(r,e){r().then(()=>e.fail(),()=>e())}function VV(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])?cw(r,t,(o,n)=>o==n):cw(r,e,(o,n)=>pw(o,n,0))}function GV(r,e,t){if(t==null&&(t=uw()),!pw(r,e,t))throw new Error(`Numbers differ: actual === ${r}, expected === ${e}`)}function pw(r,e,t){return!isFinite(r)&&!isFinite(e)?!0:!(isNaN(r)||isNaN(e)||Math.abs(r-e)>t)}function WV(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 jV(r,e){expect(new Float32Array(r)).toEqual(new Float32Array(e))}function TN(r){for(let e=0;e<r.length;e++){let t=r[e];Array.isArray(t)?TN(t):r[e]=tl(t)}return r}var UV="3.3.0";function HV(){W().set("PROD",!0)}function qV(){W().set("DEBUG",!0)}function KV(){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().")}DI(tg);function XV(){E.disposeVariables()}function Mo(){return E}function Hc(){return E.memory()}function YV(r){return E.profile(r)}function V(r,e){return E.tidy(r,e)}function Ae(r){bm(r).forEach(t=>t.dispose())}function Et(r){return E.keep(r)}function ZV(r){return E.time(r)}function AN(r){return E.setBackend(r)}function JV(){return E.ready()}function QV(){return E.backendName}function eG(r){E.removeBackend(r)}function tG(r){return E.findBackend(r)}function rG(r){return E.findBackendFactory(r)}function xu(r,e,t=1){return E.registerBackend(r,e,t)}function mw(){return E.backend}function oG(r,e){W().setPlatform(r,e)}function nG(r,e){let t=v(r,"a","add"),o=v(e,"b","add");[t,o]=Ge(t,o);let n={a:t,b:o};return E.runKernel(wo,n)}var ee=S({add_:nG});function sG(r,e){let t=v(r,"a","floorDiv"),o=v(e,"b","floorDiv");[t,o]=Ge(t,o);let n={a:t,b:o};return E.runKernel(sn,n)}var yu=S({floorDiv_:sG});function iG(r,e){let t=v(r,"a","div"),o=v(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_:iG});function aG(r,e){let t=v(r,"a","mul"),o=v(e,"b","mul");[t,o]=Ge(t,o);let n={a:t,b:o};return E.runKernel(xn,n)}var P=S({mul_:aG});function lG(r){let e=v(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_:lG});function uG(r){let t={x:v(r,"x","acos")};return E.runKernel(qs,t)}var km=S({acos_:uG});function cG(r){let t={x:v(r,"x","acosh")};return E.runKernel(Ks,t)}var _m=S({acosh_:cG});function pG(r){A(Array.isArray(r),()=>"The argument passed to tf.addN() must be a list of tensors"),A(r.length>=1,()=>`Must pass at least one tensor to tf.addN(), but got ${r.length}`);let e=r.map((n,s)=>v(n,`tensors${s}`,"addN")),t=e[0];e.forEach(n=>{if(n.dtype!==t.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")}),e.forEach(n=>{if(!jr(n.shape,t.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});let o=e;return E.runKernel(Ho,o)}var fw=S({addN_:pG});function mG(r,e=null,t=!1){let n={x:v(r,"x","all","bool")},s={axis:e,keepDims:t};return E.runKernel(Ml,n,s)}var bu=S({all_:mG});function fG(r,e=null,t=!1){let n={x:v(r,"x","any","bool")},s={axis:e,keepDims:t};return E.runKernel(Ll,n,s)}var sl=S({any_:fG});function dG(r,e=0){let o={x:v(r,"x","argMax")},n={axis:e};return E.runKernel(qo,o,n)}var il=S({argMax_:dG});function hG(r,e=0){let o={x:v(r,"x","argMin")},n={axis:e};return E.runKernel(ea,o,n)}var vm=S({argMin_:hG});function gG(r){let t={x:v(r,"x","asin")};return E.runKernel(Xs,t)}var Cm=S({asin_:gG});function xG(r){let t={x:v(r,"x","asinh")};return E.runKernel(Ys,t)}var Im=S({asinh_:xG});function yG(r){let t={x:v(r,"x","atan")};return E.runKernel(Zs,t)}var Nm=S({atan_:yG});function bG(r,e){let t=v(r,"a","atan2"),o=v(e,"b","atan2");[t,o]=Ge(t,o);let n={a:t,b:o};return E.runKernel(Qs,n)}var Sm=S({atan2_:bG});function wG(r){let t={x:v(r,"x","atanh")};return E.runKernel(Js,t)}var Tm=S({atanh_:wG});function kG(r,e,t,o,n="NHWC",s){let a=r[3],i=[...e,a],l=EN(n);return wu(r,i,t,s,o,null,null,l)}function dw(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 _G(r,e,t,o,n,s,a="NDHWC"){let[i,l,u]=hw(e),c,p;if(a==="NDHWC")p="channelsLast",c=[i,l,u,r[4],r[4]];else if(a==="NCDHW")p="channelsFirst",c=[i,l,u,r[1],r[1]];else throw new Error(`Unknown dataFormat ${a}`);return DN(r,c,t,o,n,!1,p,s)}function wu(r,e,t,o,n,s,a=!1,i="channelsLast"){let[l,u,c,p]=[-1,-1,-1,-1];if(i==="channelsLast")[l,u,c,p]=r;else if(i==="channelsFirst")[l,p,u,c]=r;else throw new Error(`Unknown dataFormat ${i}`);let[m,f,,d]=e,[h,g]=rg(t),[x,b]=rg(o),w=qc(m,x),k=qc(f,b),{padInfo:_,outHeight:D,outWidth:T}=vG(n,u,c,h,g,w,k,s,i),R=a?d*p:d,O;return i==="channelsFirst"?O=[l,R,D,T]:i==="channelsLast"&&(O=[l,D,T,R]),{batchSize:l,dataFormat:i,inHeight:u,inWidth:c,inChannels:p,outHeight:D,outWidth:T,outChannels:R,padInfo:_,strideHeight:h,strideWidth:g,filterHeight:m,filterWidth:f,effectiveFilterHeight:w,effectiveFilterWidth:k,dilationHeight:x,dilationWidth:b,inShape:r,outShape:O,filterShape:e}}function DN(r,e,t,o,n,s=!1,a="channelsLast",i){let[l,u,c,p,m]=[-1,-1,-1,-1,-1];if(a==="channelsLast")[l,u,c,p,m]=r;else if(a==="channelsFirst")[l,m,u,c,p]=r;else throw new Error(`Unknown dataFormat ${a}`);let[f,d,h,,g]=e,[x,b,w]=hw(t),[k,_,D]=hw(o),T=qc(f,k),R=qc(d,_),O=qc(h,D),{padInfo:M,outDepth:G,outHeight:j,outWidth:U}=CG(n,u,c,p,x,b,w,T,R,O,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:M,strideDepth:x,strideHeight:b,strideWidth:w,filterDepth:f,filterHeight:d,filterWidth:h,effectiveFilterDepth:T,effectiveFilterHeight:R,effectiveFilterWidth:O,dilationDepth:k,dilationHeight:_,dilationWidth:D,inShape:r,outShape:q,filterShape:e}}function IG(r,e,t,o,n){o==null&&(o=gw(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 NG(r,e,t,o,n,s){n==null&&(n=gw(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 gw(r,e,t,o=1){let n=qc(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 hw(r){return typeof r=="number"?[r,r,r]:r}function qc(r,e){return e<=1?r:r+(r-1)*(e-1)}function vG(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=IG([e,t],s,o,r,i);c=f[0],p=f[1]}else if(r==="same"){c=Math.ceil(e/o),p=Math.ceil(t/n);let m=Math.max(0,(c-1)*o+s-e),f=Math.max(0,(p-1)*n+a-t),d=Math.floor(m/2),h=m-d,g=Math.floor(f/2),x=f-g;u={top:d,bottom:h,left:g,right:x,type:"SAME"}}else if(r==="valid")u={top:0,bottom:0,left:0,right:0,type:"VALID"},c=Math.ceil((e-s+1)/o),p=Math.ceil((t-a+1)/n);else if(typeof r=="object"){let m=l==="channelsLast"?r[1][0]:r[2][0],f=l==="channelsLast"?r[1][1]:r[2][1],d=l==="channelsLast"?r[2][0]:r[3][0],h=l==="channelsLast"?r[2][1]:r[3][1];u={top:m,bottom:f,left:d,right:h,type:m===0&&f===0&&d===0&&h===0?"VALID":"EXPLICIT"},c=ku((e-s+m+f)/o+1,i),p=ku((t-a+d+h)/n+1,i)}else throw Error(`Unknown padding parameter: ${r}`);return{padInfo:u,outHeight:c,outWidth:p}}function CG(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=NG([e,t,o,1],i,1,n,r,c);m=g[0],f=g[1],d=g[2]}else if(r==="same"){m=Math.ceil(e/n),f=Math.ceil(t/s),d=Math.ceil(o/a);let h=(m-1)*n+i-e,g=(f-1)*s+l-t,x=(d-1)*a+u-o,b=Math.floor(h/2),w=h-b,k=Math.floor(g/2),_=g-k,D=Math.floor(x/2),T=x-D;p={top:k,bottom:_,left:D,right:T,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 kr(r,e){return Lo(r)||Lo(e)}function EN(r){if(r==="NHWC")return"channelsLast";if(r==="NCHW")return"channelsFirst";throw new Error(`Unknown dataFormat ${r}`)}function SG(r,e){let o={x:v(r,"x","reshape","string_or_numeric")},n={shape:e};return E.runKernel(ds,o,n)}var L=S({reshape_:SG});function TG(r,e,t,o,n){let s=v(r,"x","avgPool","float32"),a=1;A(kr(t,a),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${t} and dilations '${a}'`);let i=s,l=!1;s.rank===3&&(l=!0,i=L(s,[1,s.shape[0],s.shape[1],s.shape[2]])),A(i.rank===4,()=>`Error in avgPool: x must be rank 4 but got rank ${i.rank}.`),n!=null&&A(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?L(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var wa=S({avgPool_:TG});function AG(r,e,t,o,n,s="NDHWC"){let a=v(r,"x","avgPool3d","float32"),i=a,l=!1;a.rank===4&&(l=!0,i=L(a,[1,a.shape[0],a.shape[1],a.shape[2],a.shape[3]])),A(i.rank===5,()=>`Error in avgPool3d: x must be rank 5 but got rank ${i.rank}.`),A(s==="NDHWC",()=>`Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of ${s}`),n!=null&&A(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?L(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}var Am=S({avgPool3d_:AG});function EG(r,e=0){A(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_:EG});function DG(r){let t={x:v(r,"x","sigmoid")};return E.runKernel(An,t)}var qr=S({sigmoid_:DG});function $G(r,e,t){let o=v(r,"x","slice","string_or_numeric");if(o.rank===0)throw new Error("Slicing scalar is not possible");let n={x:o},s={begin:e,size:t};return E.runKernel(gs,n,s)}var Re=S({slice_:$G});function RG(r){let t={x:v(r,"x","tanh")};return E.runKernel(On,t)}var Oi=S({tanh_:RG});function FG(r,e,t,o,n,s){let a=v(r,"forgetBias","basicLSTMCell"),i=v(e,"lstmKernel","basicLSTMCell"),l=v(t,"lstmBias","basicLSTMCell"),u=v(o,"data","basicLSTMCell"),c=v(n,"c","basicLSTMCell"),p=v(s,"h","basicLSTMCell"),m=Ze([u,p],1),f=We(m,i),d=ee(f,l),h=d.shape[0],g=d.shape[1]/4,x=[h,g],b=Re(d,[0,0],x),w=Re(d,[0,g],x),k=Re(d,[0,g*2],x),_=Re(d,[0,g*3],x),D=ee(P(qr(b),Oi(w)),P(c,qr(ee(a,k)))),T=P(Oi(D),qr(_));return[D,T]}var OG=S({basicLSTMCell_:FG});function PG(r,e,t){let o=v(r,"x","batchToSpaceND"),n=e.reduce((i,l)=>i*l);A(o.rank>=1+e.length,()=>`input rank is ${o.rank} but should be > than blockShape.length ${e.length}`),A(t.length===e.length,()=>`crops.length is ${t.length} but should be equal to blockShape.length ${e.length}`),A(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_:PG});function $N(r){let e;return r.rank===0||r.rank===1?e=L(r,[1,1,1,r.size]):r.rank===2?e=L(r,[1,1,r.shape[0],r.shape[1]]):r.rank===3?e=L(r,[1,r.shape[0],r.shape[1],r.shape[2]]):e=r,e}function MG(r,e,t,o,n,s){s==null&&(s=.001);let a=v(r,"x","batchNorm"),i=v(e,"mean","batchNorm"),l=v(t,"variance","batchNorm"),u;n!=null&&(u=v(n,"scale","batchNorm"));let c;o!=null&&(c=v(o,"offset","batchNorm")),A(i.rank===l.rank,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),A(c==null||i.rank===c.rank,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),A(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 L(d,a.shape)}var Ln=S({batchNorm_:MG});function LG(r,e,t,o,n,s){let a=v(r,"x","batchNorm"),i=v(e,"mean","batchNorm"),l=v(t,"variance","batchNorm"),u;n!=null&&(u=v(n,"scale","batchNorm"));let c;return o!=null&&(c=v(o,"offset","batchNorm")),A(a.rank===2,()=>`Error in batchNorm2D: x must be rank 2 but got rank ${a.rank}.`),A(i.rank===2||i.rank===1,()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${i.rank}.`),A(l.rank===2||l.rank===1,()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${l.rank}.`),u!=null&&A(u.rank===2||u.rank===1,()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${u.rank}.`),c!=null&&A(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 xw=S({batchNorm2d_:LG});function zG(r,e,t,o,n,s){let a=v(r,"x","batchNorm"),i=v(e,"mean","batchNorm"),l=v(t,"variance","batchNorm"),u;n!=null&&(u=v(n,"scale","batchNorm"));let c;return o!=null&&(c=v(o,"offset","batchNorm")),A(a.rank===3,()=>`Error in batchNorm3D: x must be rank 3 but got rank ${a.rank}.`),A(i.rank===3||i.rank===1,()=>`Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank ${i.rank}.`),A(l.rank===3||l.rank===1,()=>`Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank ${l.rank}.`),u!=null&&A(u.rank===3||u.rank===1,()=>`Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank ${u.rank}.`),c!=null&&A(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 yw=S({batchNorm3d_:zG});function BG(r,e,t,o,n,s){let a=v(r,"x","batchNorm"),i=v(e,"mean","batchNorm"),l=v(t,"variance","batchNorm"),u;n!=null&&(u=v(n,"scale","batchNorm"));let c;return o!=null&&(c=v(o,"offset","batchNorm")),A(a.rank===4,()=>`Error in batchNorm4D: x must be rank 4 but got rank ${a.rank}.`),A(i.rank===4||i.rank===1,()=>`Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank ${i.rank}.`),A(l.rank===4||l.rank===1,()=>`Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank ${l.rank}.`),u!=null&&A(u.rank===4||u.rank===1,()=>`Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank ${u.rank}.`),c!=null&&A(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 bw=S({batchNorm4d_:BG});function VG(r,e,t){let o=v(r,"x","bincount"),n=v(e,"weights","bincount");A(o.dtype==="int32",()=>`Error in bincount: input dtype must be int32, but got ${o.dtype}`),A(t>=0,()=>`size must be non-negative, but got ${t}.`),A(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 ww=S({bincount_:VG});function GG(r,e){let t=v(r,"broadcastTo","x"),o=t.shape;if(e.some(u=>!(u>0)||u%1!=0))throw new Error(`broadcastTo(): Invalid broadcast shape [${e}].`);if(e.length<t.rank)throw new Error(`broadcastTo(): shape.length=${e.length} < input.rank=${t.rank}.`);if(e.length>t.rank){let u=t.shape.slice();for(;u.length<e.length;)u.unshift(1);t=L(t,u)}let n=t.shape,s=Array.from(e);for(let u=e.length-1;u>=0;u--)if(n[u]===e[u])s[u]=1;else if(t.shape[u]!==1)throw new Error(`broadcastTo(): [${o}] cannot be broadcast to [${e}].`);if(s.map((u,c)=>u>1?c:-1).filter(u=>u>=0).length===0)return Po(t);let i={x:t},l={reps:s};return E.runKernel(ko,i,l)}var al=S({broadcastTo_:GG});function WG(r){let t={x:v(r,"x","ceil")};return E.runKernel(Yo,t)}var Em=S({ceil_:WG});function jG(r,e,t){let o=v(r,"x","clipByValue");A(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 ir=S({clipByValue_:jG});function UG(r){return Ze(r,0)}var kw=S({concat1d_:UG});function HG(r,e){return Ze(r,e)}var _w=S({concat2d_:HG});function qG(r,e){return Ze(r,e)}var vw=S({concat3d_:qG});function KG(r,e){return Ze(r,e)}var Cw=S({concat4d_:KG});function XG(r,e,t,o,n="NHWC",s=[1,1],a){let i=v(r,"x","conv2d"),l=v(e,"filter","conv2d"),u=i,c=!1;i.rank===3&&(c=!0,u=L(i,[1,i.shape[0],i.shape[1],i.shape[2]])),A(u.rank===4,()=>`Error in conv2d: input must be rank 4, but got rank ${u.rank}.`),A(l.rank===4,()=>`Error in conv2d: filter must be rank 4, but got rank ${l.rank}.`),a!=null&&A(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];A(p===l.shape[2],()=>`Error in conv2d: depth of input (${p}) must match input depth for filter ${l.shape[2]}.`),A(kr(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?L(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var Kr=S({conv2d_:XG});function YG(r,e,t,o,n="NWC",s=1,a){let i=v(r,"x","conv1d"),l=v(e,"filter","conv1d"),u=i,c=!1;i.rank===2&&(c=!0,u=L(i,[1,i.shape[0],i.shape[1]])),A(u.rank===3,()=>`Error in conv1d: input must be rank 3, but got rank ${u.rank}.`),A(l.rank===3,()=>`Error in conv1d: filter must be rank 3, but got rank ${l.rank}.`),a!=null&&A(ot(o),()=>`Error in conv1d: pad must be an integer when using, dimRoundingMode ${a} but got pad ${o}.`),A(u.shape[2]===l.shape[1],()=>`Error in conv1d: depth of input (${u.shape[2]}) must match input depth for filter ${l.shape[1]}.`),A(kr(t,s),()=>`Error in conv1D: Either stride or dilation must be 1. Got stride ${t} and dilation '${s}'`),A(n==="NWC",()=>`Error in conv1d: got dataFormat of ${n} but only NWC is currently supported.`);let p=L(l,[1,l.shape[0],l.shape[1],l.shape[2]]),m=L(u,[u.shape[0],1,u.shape[1],u.shape[2]]),g=Kr(m,p,[1,t],o,"NHWC",[1,s],a);return c?L(g,[g.shape[2],g.shape[3]]):L(g,[g.shape[0],g.shape[2],g.shape[3]])}var _u=S({conv1d_:YG});function ZG(r,e,t,o,n,s="NHWC",a){A(r.length===e.rank,()=>`Length of inShape (${r.length}) and rank of dy (${e.rank}) must match`);let i=r,l=e,u=!1;e.rank===3&&(u=!0,l=L(e,[1,e.shape[0],e.shape[1],e.shape[2]]),i=[1,r[0],r[1],r[2]]),A(i.length===4,()=>`Error in conv2dDerInput: inShape must be length 4, but got length ${i.length}.`),A(l.rank===4,()=>`Error in conv2dDerInput: dy must be rank 4, but got rank ${l.rank}`),A(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];A(c===t.shape[2],()=>`Error in conv2dDerInput: depth of input (${c}) must match input depth for filter ${t.shape[2]}.`),A(p===t.shape[3],()=>`Error in conv2dDerInput: depth of output (${p}) must match output depth for filter ${t.shape[3]}.`),a!=null&&A(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?L(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var Kc=S({conv2DBackpropInput_:ZG});function JG(r,e,t,o,n,s){let a=v(r,"x","conv2dTranspose"),i=v(e,"filter","conv2dTranspose");return Kc(t,a,i,o,n,"NHWC",s)}var vu=S({conv2dTranspose_:JG});function QG(r,e,t,o,n="NDHWC",s=[1,1,1]){let a=v(r,"x","conv3d"),i=v(e,"filter","conv3d"),l=a,u=!1;a.rank===4&&(u=!0,l=L(a,[1,a.shape[0],a.shape[1],a.shape[2],a.shape[3]])),A(l.rank===5,()=>`Error in conv3d: input must be rank 5, but got rank ${l.rank}.`),A(i.rank===5,()=>`Error in conv3d: filter must be rank 5, but got rank ${i.rank}.`),A(l.shape[4]===i.shape[3],()=>`Error in conv3d: depth of input (${l.shape[4]}) must match input depth for filter ${i.shape[3]}.`),A(kr(t,s),()=>`Error in conv3D: Either strides or dilations must be 1. Got strides ${t} and dilations '${s}'`),A(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?L(m,[m.shape[1],m.shape[2],m.shape[3],m.shape[4]]):m}var Dm=S({conv3d_:QG});function eW(r,e,t,o,n){A(r.length===e.rank,()=>`Length of inShape (${r.length}) and rank of dy (${e.rank}) must match`);let s=r,a=e,i=!1;e.rank===4&&(i=!0,a=L(e,[1,e.shape[0],e.shape[1],e.shape[2],e.shape[3]]),s=[1,r[0],r[1],r[2],r[3]]);let l=s[4],u=a.shape[4];A(s.length===5,()=>`Error in conv3dDerInput: inShape must be length 5, but got length ${s.length}.`),A(a.rank===5,()=>`Error in conv3dDerInput: dy must be rank 5, but got rank ${a.rank}`),A(t.rank===5,()=>`Error in conv3dDerInput: filter must be rank 5, but got rank ${t.rank}`),A(l===t.shape[3],()=>`Error in conv3dDerInput: depth of input (${l}) must match input depth for filter ${t.shape[3]}.`),A(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?L(m,[m.shape[1],m.shape[2],m.shape[3],m.shape[4]]):m}var og=S({conv3DBackpropInput_:eW});function tW(r,e,t,o,n){let s=v(r,"x","conv3dTranspose"),a=v(e,"filter","conv3dTranspose");return og(t,s,a,o,n)}var rW=S({conv3dTranspose_:tW});function oW(r){let t={x:v(r,"x","cos")};return E.runKernel(Qo,t)}var _a=S({cos_:oW});function nW(r){let t={x:v(r,"x","cosh")};return E.runKernel(ei,t)}var Cu=S({cosh_:nW});function sW(r,e=0,t=!1,o=!1){let s={x:v(r,"x","cumsum")},a={axis:e,exclusive:t,reverse:o};return E.runKernel(en,s,a)}var Iu=S({cumsum_:sW});function iW(r,e,t,o=!1){let n=v(r,"x","denseBincount"),s=v(e,"weights","denseBincount");A(n.dtype==="int32",()=>`Error in denseBincount: input dtype must be int32, but got ${n.dtype}`),A(n.rank<=2,()=>`Error in denseBincount: input must be at most rank 2, but got rank ${n.rank}.`),A(t>=0,()=>`size must be non-negative, but got ${t}.`),A(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 Iw=S({denseBincount_:iW});function aW(r,e,t="NHWC"){let o=v(r,"x","depthToSpace"),n=t==="NHWC"?o.shape[1]:o.shape[2],s=t==="NHWC"?o.shape[2]:o.shape[3],a=t==="NHWC"?o.shape[3]:o.shape[1];A(n*e>=0,()=>`Negative dimension size caused by overflow when multiplying
|
|
${n} and ${e} for depthToSpace with input shape
|
|
${o.shape}`),A(s*e>=0,()=>`Negative dimension size caused by overflow when multiplying
|
|
${s} and ${e} for depthToSpace with input shape
|
|
${o.shape}`),A(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 $m=S({depthToSpace_:aW});function lW(r,e,t,o,n="NHWC",s=[1,1],a){let i=v(r,"x","depthwiseConv2d"),l=v(e,"filter","depthwiseConv2d"),u=i,c=!1;i.rank===3&&(c=!0,u=L(i,[1,i.shape[0],i.shape[1],i.shape[2]])),A(u.rank===4,()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${u.rank}.`),A(l.rank===4,()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${l.rank}.`),A(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&&A(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?L(f,[f.shape[1],f.shape[2],f.shape[3]]):f}var Is=S({depthwiseConv2d_:lW});function uW(r){let t={x:v(r,"x","diag")};return E.runKernel(Xl,t)}var cW=S({diag_:uW});function pW(r,e,t,o,n=[1,1],s="NHWC"){let a=v(r,"x","dilation2d"),i=v(e,"filter","dilation2d");A(a.rank===3||a.rank===4,()=>`Error in dilation2d: input must be rank 3 or 4, but got rank ${a.rank}.`),A(i.rank===3,()=>`Error in dilation2d: filter must be rank 3, but got rank ${i.rank}.`),A(s==="NHWC",()=>`Error in dilation2d: Only NHWC is currently supported, but got dataFormat of ${s}`);let l=a,u=!1;a.rank===3&&(l=L(a,[1,a.shape[0],a.shape[1],a.shape[2]]),u=!0);let c={x:l,filter:i},p={strides:t,pad:o,dilations:n},m=E.runKernel(sa,c,p);return u?L(m,[m.shape[1],m.shape[2],m.shape[3]]):m}var Rm=S({dilation2d_:pW});function mW(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 fW(r,e){let t=v(r,"a","equal"),o=v(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_:fW});function dW(r,e,t){let o=v(e,"a","where"),n=v(t,"b","where"),s=v(r,"condition","where","bool"),a=Be(o.shape,n.shape),i=al(o,a),l=al(n,a);s.rank===1&&A(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_:dW});function hW(r){let t={x:v(r,"x","zerosLike")};return E.runKernel(bs,t)}var Ce=S({zerosLike_:hW});function gW(r,e){let t=v(r,"a","div"),o=v(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 Fm=S({divNoNan_:gW});function xW(r,e){let t=v(r,"t1","dot"),o=v(e,"t2","dot");A((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(A(n===s,()=>`Error in dot: inner dimensions of inputs must match, but got ${n} and ${s}.`),t.rank===1&&o.rank===1){let a=L(t,[1,-1]),i=L(o,[-1,1]),l=We(a,i);return L(l,[])}else if(t.rank===1&&o.rank===2){let a=L(t,[1,-1]),i=L(o,[o.shape[0],o.shape[1]]),l=We(a,i);return L(l,[l.size])}else if(t.rank===2&&o.rank===1){let a=L(o,[-1,1]),i=We(t,a);return L(i,[i.size])}else{let a=L(o,[o.shape[0],o.shape[1]]);return We(t,a)}}var Nw=S({dot_:xW});function yW(r){let t={x:v(r,"x","elu")};return E.runKernel(oi,t)}var Ns=S({elu_:yW});function bW(r){let e=v(r,"x","erf");A(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 Om=S({erf_:bW});function wW(r){let t={x:v(r,"x","exp")};return E.runKernel(on,t)}var Zt=S({exp_:wW});function kW(r,e=0){let t=v(r,"x","expandDims","string_or_numeric");A(e<=t.rank,()=>"Axis must be <= rank of the tensor");let o={input:t},n={dim:e};return E.runKernel(us,o,n)}var ar=S({expandDims_:kW});function _W(r){let t={x:v(r,"x","expm1")};return E.runKernel(ii,t)}var Pm=S({expm1_:_W});function vW(r,e){let t=v(r,"x","tile","string_or_numeric");A(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_:vW});function CW(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=L(n.toTensor(),[r,e]);if(t==null)return a;if(t.length===1)return zo(ar(a,0),[t[0],1,1]);if(t.length===2)return zo(ar(ar(a,0),0),[t[0],t[1],1,1]);if(t.length===3)return zo(ar(ar(ar(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 Xc=S({eye_:CW});function va(r,e,t){let o={shape:r,value:e,dtype:t};return E.runKernel(ia,{},o)}function IW(r){let t={x:v(r,"x","floor")};return E.runKernel(nn,t)}var Ss=S({floor_:IW});function NW(r,e,t=0,o=0){let n=v(r,"x","gather"),s=v(e,"indices","gather","int32"),a={x:n,indices:s},i={axis:t,batchDims:o};return E.runKernel(cs,a,i)}var zn=S({gather_:NW});function SW(r,e){let t=v(r,"a","greater"),o=v(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 er=S({greater_:SW});function TW(r,e){let t=v(r,"a","greaterEqual"),o=v(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_:TW});function AW(r){let t={input:v(r,"input","imag")};return E.runKernel(Ql,t)}var Nu=S({imag_:AW});function EW(r){let t={x:v(r,"x","isFinite")};return E.runKernel(ci,t)}var Sw=S({isFinite_:EW});function DW(r){let t={x:v(r,"x","isInf")};return E.runKernel(pi,t)}var Tw=S({isInf_:DW});function $W(r){let t={x:v(r,"x","isNaN")};return E.runKernel(mi,t)}var Aw=S({isNaN_:$W});function RW(r,e=.2){let o={x:v(r,"x","leakyRelu")},n={alpha:e};return E.runKernel(un,o,n)}var Ca=S({leakyRelu_:RW});function FW(r,e){let t=v(r,"a","less"),o=v(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_:FW});function OW(r,e){let t=v(r,"a","lessEqual"),o=v(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_:OW});function Ew(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 PW(r,e=5,t=1,o=1,n=.5){let s=v(r,"x","localResponseNormalization");A(s.rank===4||s.rank===3,()=>`Error in localResponseNormalization: x must be rank 3 or 4 but got
|
|
rank ${s.rank}.`),A(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=L(s,[1,s.shape[0],s.shape[1],s.shape[2]]));let l={x:a},u={depthRadius:e,bias:t,alpha:o,beta:n},c=E.runKernel(aa,l,u);return i?L(c,[c.shape[1],c.shape[2],c.shape[3]]):c}var Mm=S({localResponseNormalization_:PW});function MW(r){let t={x:v(r,"x","log")};return E.runKernel(cn,t)}var lr=S({log_:MW});function LW(r){let t={x:v(r,"x","log1p")};return E.runKernel(hi,t)}var Tu=S({log1p_:LW});function zW(r){return A(Us(r),()=>"The f passed in grad(f) must be a function"),(e,t)=>{let o=v(e,"x","tf.grad","string_or_numeric"),n=t!=null?v(t,"dy","tf.grad"):null;return 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 BW(r){return A(Us(r),()=>"The f passed in grads(f) must be a function"),(e,t)=>{A(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?v(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 VW(r){return A(Us(r),()=>"The f passed in valueAndGrad(f) must be a function"),(e,t)=>{A(e instanceof Ve,()=>"The x passed in valueAndGrad(f)(x) must be a tensor"),A(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 GW(r){return A(Us(r),()=>"The f passed in valueAndGrads(f) must be a function"),(e,t)=>{A(Array.isArray(e)&&e.every(n=>n instanceof Ve),()=>"The args passed in valueAndGrads(f)(args) must be array of tensors"),A(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){A(Us(r),()=>"The f passed in variableGrads(f) must be a function"),A(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),A(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);A(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()."),A(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 WW(r){let t={x:v(r,"x","neg")};return E.runKernel(ps,t)}var He=S({neg_:WW});function jW(r){let t={x:v(r,"x","softplus")};return E.runKernel(Ti,t)}var Ts=S({softplus_:jW});function UW(r){let e=v(r,"x","logSigmoid");return Xr(o=>({value:He(Ts(He(o))),gradFunc:a=>P(a,qr(He(o)))}))(e)}var Dw=S({logSigmoid_:UW});function HW(r,e=null,t=!1){let n={x:v(r,"x","max")},s={reductionIndices:e,keepDims:t};return E.runKernel(pn,n,s)}var ur=S({max_:HW});function qW(r,e){let t=v(r,"a","sub"),o=v(e,"b","sub");[t,o]=Ge(t,o);let n={a:t,b:o};return E.runKernel(Fn,n)}var ce=S({sub_:qW});function KW(r,e=null,t=!1){let o=v(r,"x","sum");o.dtype==="bool"&&(o=ne(o,"int32"));let n={x:o},s={axis:e,keepDims:t};return E.runKernel(Dn,n,s)}var ge=S({sum_:KW});function XW(r,e=-1){let t=v(r,"logits","logSoftmax");if(e===-1&&(e=t.rank-1),e!==t.rank-1)throw Error(`Log Softmax along a non-last dimension is not yet supported. Logits was rank ${t.rank} and axis was ${e}`);return Xr((n,s)=>{let a=!0,i=ur(n,e,!0),l=ce(n,i),u=ce(ne(l,"float32"),lr(ge(Zt(l),e,a)));return s([u]),{value:u,gradFunc:(p,m)=>{let[f]=m,d=!0,h=Zt(f);return ce(p,P(ge(p,e,d),h))}}})(t)}var Au=S({logSoftmax_:XW});function $w(r,e){for(let t=0;t<r.length;++t)if(r[r.length-t-1]!==e-1-t)return!1;return!0}function RN(r,e,t){let o=r.length+e.length,n=[],s=0,a=0;for(let i=0;i<o;i++)t.indexOf(i)===-1?n.push(r[s++]):n.push(e[a++]);return n}function Rw(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 RN(r,t,e)}function YW(r,e,t){A($w(e,t),()=>`${r} supports only inner-most axes for now. Got axes ${e} and rank-${t} input.`)}function Fw(r,e){if($w(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 Lm(r){return r.map((e,t)=>[t,e]).sort((e,t)=>e[1]-t[1]).map(e=>e[0])}function ZW(r,e){let t=[];for(let o=e-r;o<e;++o)t.push(o);return t}function JW(r,e=null,t=!1){let o=v(r,"x","logSumExp"),n=Qt(e,o.shape),s=ur(o,n,!0),a=ce(o,s),i=Zt(a),l=ge(i,n),u=lr(l),c=ee(L(s,u.shape),u);if(t){let p=Bn(c.shape,n);return L(c,p)}return c}var zm=S({logSumExp_:JW});function QW(r,e){let t=v(r,"a","logicalAnd","bool"),o=v(e,"b","logicalAnd","bool");Be(t.shape,o.shape);let n={a:t,b:o};return E.runKernel(gi,n)}var hr=S({logicalAnd_:QW});function ej(r){let t={x:v(r,"x","logicalNot","bool")};return E.runKernel(Ja,t)}var Ia=S({logicalNot_:ej});function tj(r,e){let t=v(r,"a","logicalOr","bool"),o=v(e,"b","logicalOr","bool");Be(t.shape,o.shape);let n={a:t,b:o};return E.runKernel(Qa,n)}var Eu=S({logicalOr_:tj});function rj(r,e){let t=v(r,"a","logicalXor","bool"),o=v(e,"b","logicalXor","bool");return Be(t.shape,o.shape),hr(Eu(r,e),Ia(hr(r,e)))}var Ow=S({logicalXor_:rj});function oj(r,e,t,o,n){let s=v(r,"x","maxPool"),a=1,i=s,l=!1;s.rank===3&&(l=!0,i=L(s,[1,s.shape[0],s.shape[1],s.shape[2]])),A(i.rank===4,()=>`Error in maxPool: input must be rank 4 but got rank ${i.rank}.`),A(kr(t,a),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${t} and dilations '${a}'`),n!=null&&A(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?L(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var Na=S({maxPool_:oj});function nj(r,e=[1,1,1],t,o,n,s="NDHWC"){let a=v(r,"x","maxPool3d"),i=a,l=!1;a.rank===4&&(l=!0,i=L(a,[1,a.shape[0],a.shape[1],a.shape[2],a.shape[3]])),A(i.rank===5,()=>`Error in maxPool3d: x must be rank 5 but got rank ${i.rank}.`),A(s==="NDHWC",()=>`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${s}`),n!=null&&A(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?L(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}var Bm=S({maxPool3d_:nj});function sj(r,e,t,o,n=!1){let a={x:v(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 Pw=S({maxPoolWithArgmax_:sj});function ij(r,e){let t=v(r,"a","maximum"),o=v(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_:ij});function aj(r,e=null,t=!1){let n={x:v(r,"x","mean")},s={axis:e,keepDims:t};return E.runKernel(dn,n,s)}var dt=S({mean_:aj});function lj(r,e=null,t=!1){let n={x:v(r,"x","min")},s={axis:e,keepDims:t};return E.runKernel(hn,n,s)}var Pi=S({min_:lj});function uj(r,e){let t=v(r,"a","minimum"),o=v(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_:uj});function cj(r,e,t){A(t==="reflect"||t==="symmetric",()=>`Invalid mode. Mode must be either reflect or symmetric. Got ${t}.`);let o=v(r,"x","mirrorPad");if(o.rank===0)throw new Error("mirrorPad(scalar) is not defined. Pass non-scalar to mirrorPad");A(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++)A(e[i].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),A(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 Vm=S({mirrorPad_:cj});function pj(r,e){let t=v(r,"a","mod"),o=v(e,"b","mod");[t,o]=Ge(t,o);let n={a:t,b:o};return E.runKernel(xi,n)}var Gm=S({mod_:pj});function mj(r){let e=v(r,"x","square"),t={};return E.runKernel("Square",{x:e},t)}var Oe=S({square_:mj});function fj(r,e=null,t=!1){r=v(r,"x","moments");let o=Qt(e,r.shape),n=dt(r,o,t),s=n.shape;t||(s=Bn(n.shape,o));let a=Oe(ce(ne(r,"float32"),L(n,s))),i=dt(a,o,t);return{mean:n,variance:i}}var Yc=S({moments_:fj});function dj(r,e,t,o){let n=v(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 hj=S({multiRNNCell_:dj});function gj(r,e,t,o=!1){let n=v(r,"logits","multinomial"),s=n.size,a=n.rank;if(s<2)throw new Error(`Error in multinomial: you need at least 2 outcomes, but got ${s}.`);if(a>2)throw new Error(`Rank of probabilities must be 1 or 2, but is ${a}`);t=t||Math.random();let l={logits:a===1?L(n,[1,-1]):n},u={numSamples:e,seed:t,normalized:o},c=E.runKernel(su,l,u);return a===1?L(c,[c.size]):c}var Mw=S({multinomial_:gj});function xj(r,e){let t=v(r,"a","notEqual"),o=v(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_:xj});function ht(r,e="float32"){if(e==="complex64"){let o=ht(r,"float32"),n=ht(r,"float32");return _o(o,n)}let t=Rc(ct(r),e);return E.makeTensor(t,r,e)}function Nr(r,e="float32"){if(e==="complex64"){let o=Nr(r,"float32"),n=ht(r,"float32");return _o(o,n)}let t=cm(ct(r),e);return E.makeTensor(t,r,e)}function yj(r){let t={x:v(r,"x","onesLike")};return E.runKernel(ms,t)}var tr=S({onesLike_:yj});function bj(r,e){let t=v(r,"v1","outerProduct"),o=v(e,"v2","outerProduct");A(t.rank===1&&o.rank===1,()=>`Error in outerProduct: inputs must be rank 1, but got ranks ${t.rank} and ${o.rank}.`);let n=L(t,[-1,1]),s=L(o,[1,-1]);return We(n,s)}var wj=S({outerProduct_:bj});function kj(r,e,t=0){let o=v(r,"x","pad");if(o.rank===0)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");let n={paddings:e,constantValue:t},s={x:o};return E.runKernel(bn,s,n)}var Fr=S({pad_:kj});function _j(r,e,t=0){return A(e.length===2,()=>"Invalid number of paddings. Must be length of 2."),Fr(r,[e],t)}var vj=S({pad1d_:_j});function Cj(r,e,t=0){return A(e.length===2&&e[0].length===2&&e[1].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),Fr(r,e,t)}var Ij=S({pad2d_:Cj});function Nj(r,e,t=0){return A(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."),Fr(r,e,t)}var Sj=S({pad3d_:Nj});function Tj(r,e,t=0){return A(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."),Fr(r,e,t)}var Aj=S({pad4d_:Tj});function Ej(r,e,t){let o=v(r,"x","spaceToBatchND");A(o.rank>=1+e.length,()=>`input rank ${o.rank} should be > than [blockShape] ${e.length}`),A(t.length===e.length,()=>`paddings.shape[0] ${t.length} must be equal to [blockShape] ${e.length}`),A(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_:Ej});function Rj(r,e,t,o,n,s){n==null&&(n=[1,1]),s==null&&(s=1),o===0&&(o="valid");let a=v(r,"x","maxPool"),i=a,l=!1;a.rank===3&&(l=!0,i=L(a,[1,a.shape[0],a.shape[1],a.shape[2]])),A(kr(s,n),()=>`Error in pool: Either strides or dilations must be 1. Got strides ${s} and dilations '${n}'`);let u=dw(i.shape,e,s,n,o),c=[u.dilationHeight,u.dilationWidth],p;o==="same"?p=$j([u.filterHeight,u.filterWidth],c):p=[[0,0],[0,0]];let m=c[0]===1&&c[1]===1,[f,d]=Dj([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?L(w,[w.shape[1],w.shape[2],w.shape[3]]):w}function Dj(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 $j(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 Lw=S({pool_:Rj});function Fj(r,e){let t=v(r,"base","pow"),o=v(e,"exp","pow");[t,o]=Ge(t,o);let n={a:t,b:o};return E.runKernel(wn,n)}var Or=S({pow_:Fj});function Oj(r,e){let t=v(r,"x","prelu"),o=v(e,"alpha","prelu"),n={x:t,alpha:o};return E.runKernel(kn,n)}var Ta=S({prelu_:Oj});function Pj(r,e=null,t=!1){let o=v(r,"x","prod");o.dtype==="bool"&&(o=ne(o,"int32"));let n={x:o},s={axis:e,keepDims:t};return E.runKernel(_i,n,s)}var Du=S({prod_:Pj});function Mj(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 Lj=S({rand_:Mj});var ag=Ac(Hw());var Zc=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}},qw=class{constructor(e,t,o,n){this.alpha=e,this.beta=1/t,this.dtype=o;let s=n||Math.random();this.randu=ag.alea(s.toString()),this.randn=new Zc(0,1,o,!1,this.randu()),e<1?this.d=e+2/3:this.d=e-1/3,this.c=1/Math.sqrt(9*this.d)}nextValue(){let e,t,o,n,s,a;for(;;){do n=this.randn.nextValue(),a=1+this.c*n;while(a<=0);if(a*=a*a,e=n*n,t=1-.331*e*e,o=.5*e+this.d*(1-a+Math.log(a)),s=this.randu(),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)}},Kw=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 Uj(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 qw(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 Hj=S({randomGamma_:Uj});function qj(r,e=0,t=1,o,n){if(o!=null&&o==="bool")throw new Error(`Unsupported data type ${o}`);let s=new Zc(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_:qj});function Kj(r,e=0,t=1,o="float32",n){let s=ve(r,o),a=new Kw(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_:Kj});function Jc(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 Xj(r){let t={input:v(r,"input","real")};return E.runKernel(iu,t)}var ll=S({real_:Xj});function Yj(r){let t={x:v(r,"x","reciprocal")};return E.runKernel(vi,t)}var Wm=S({reciprocal_:Yj});function Zj(r){let t={x:v(r,"x","relu")};return E.runKernel(_n,t)}var Sr=S({relu_:Zj});function Jj(r){let t={x:v(r,"x","relu6")};return E.runKernel(Cn,t)}var Ru=S({relu6_:Jj});function Qj(r,e){let o={x:v(r,"x","reverse")},n={dims:e};return E.runKernel(In,o,n)}var qt=S({reverse_:Qj});function e4(r){let e=v(r,"x","reverse");return A(e.rank===1,()=>`Error in reverse1D: x must be rank 1 but got rank ${e.rank}.`),qt(e,0)}var t4=S({reverse1d_:e4});function r4(r,e){let t=v(r,"x","reverse");return A(t.rank===2,()=>`Error in reverse2D: x must be rank 2 but got rank ${t.rank}.`),qt(t,e)}var o4=S({reverse2d_:r4});function n4(r,e){let t=v(r,"x","reverse");return A(t.rank===3,()=>`Error in reverse3D: x must be rank 3 but got rank ${t.rank}.`),qt(t,e)}var s4=S({reverse3d_:n4});function i4(r,e){let t=v(r,"x","reverse");return A(t.rank===4,()=>`Error in reverse4D: x must be rank 4 but got rank ${t.rank}.`),qt(t,e)}var a4=S({reverse4d_:i4});function l4(r){let t={x:v(r,"x","round")};return E.runKernel(Nn,t)}var jm=S({round_:l4});function u4(r){let t={x:v(r,"x","rsqrt")};return E.runKernel(Sn,t)}var Fu=S({rsqrt_:u4});function le(r,e){if((nr(r)&&e!=="string"||Array.isArray(r))&&e!=="complex64")throw new Error("Error creating a new Scalar: value must be a primitive (number|boolean|string)");if(e==="string"&&nr(r)&&!(r instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");return Ur(r,[],[],e)}function c4(r){let t={x:v(r,"x","selu")};return E.runKernel(Ii,t)}var Ou=S({selu_:c4});function p4(r,e,t,o,n,s=[1,1],a="NHWC"){let i=v(r,"x","separableConv2d"),l=v(e,"depthwiseFilter","separableConv2d"),u=v(t,"pointwiseFilter","separableConv2d"),c=i,p=!1;if(i.rank===3&&(p=!0,c=L(i,[1,i.shape[0],i.shape[1],i.shape[2]])),a==="NCHW")throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");A(c.rank===4,()=>`Error in separableConv2d: input must be rank 4, but got rank ${c.rank}.`),A(l.rank===4,()=>`Error in separableConv2d: depthwise filter must be rank 4, but got rank ${l.rank}.`),A(u.rank===4,()=>`Error in separableConv2d: pointwise filter must be rank 4, but got rank ${l.rank}.`),A(u.shape[0]===1,()=>`Error in separableConv2d: the first dimension of pointwise filter must be 1, but got ${u.shape[0]}.`),A(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];A(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?L(g,[g.shape[1],g.shape[2],g.shape[3]]):g}var Um=S({separableConv2d_:p4});async function m4(r,e){let t=v(r,"x","setdiff1d"),o=v(e,"y","setdiff1d");A(t.dtype===o.dtype,()=>`x and y should have the same dtype, but got x (${t.dtype}) and y (${o.dtype}).`),A(t.rank===1,()=>`x should be 1D tensor, but got x (${t.shape}).`),A(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 Xw=m4;function f4(r){let t={x:v(r,"x","sign")};return E.runKernel(Si,t)}var Hm=S({sign_:f4});function d4(r){let t={x:v(r,"x","sin")};return E.runKernel(Tn,t)}var Pu=S({sin_:d4});function h4(r){let t={x:v(r,"x","sinh")};return E.runKernel(Ni,t)}var Mu=S({sinh_:h4});function g4(r,e,t){let o=v(r,"x","slice1d");return A(o.rank===1,()=>`slice1d expects a rank-1 tensor, but got a rank-${o.rank} tensor`),Re(o,[e],[t])}var qm=S({slice1d_:g4});function x4(r,e,t){let o=v(r,"x","slice2d");return A(o.rank===2,()=>`slice2d expects a rank-2 tensor, but got a rank-${o.rank} tensor`),Re(o,e,t)}var ug=S({slice2d_:x4});function y4(r,e,t){let o=v(r,"x","slice3d");return A(o.rank===3,()=>`slice3d expects a rank-3 tensor, but got a rank-${o.rank} tensor`),Re(o,e,t)}var Km=S({slice3d_:y4});function b4(r,e,t){let o=v(r,"x","slice4d");return A(o.rank===4,()=>`slice4d expects a rank-4 tensor, but got a rank-${o.rank} tensor`),Re(o,e,t)}var Qc=S({slice4d_:b4});function w4(r,e=-1){let t=v(r,"logits","softmax","float32");if(e===-1&&(e=t.rank-1),e!==t.rank-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${t.rank} and dim was ${e}`);let o={logits:t},n={dim:e};return E.runKernel($n,o,n)}var Aa=S({softmax_:w4});function k4(r){A(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_:k4});function _4(r){A(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_:_4});function v4(r){let e=r.shape[r.shape.length-1],t=r.size/e,o;if(e<=2){let n=L(r,[t,e]);o=Mi(n)}else{let n=[t,2*(e-1)],s=L(ll(r),[t,e]),a=L(Nu(r),[t,e]),i=qt(Re(s,[0,1],[t,e-2]),1),l=P(qt(Re(a,[0,1],[t,e-2]),1),le(-1)),u=Ze([s,i],1),c=Ze([a,l],1),p=L(_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=L(o,[s,o.shape[0]/s,o.shape[1]]),n.dispose()}return o}var Lu=S({irfft_:v4});function C4(r,e,t=0){let n={x:v(r,"x","split")},s={numOrSizeSplits:e,axis:t};return E.runKernel(xs,n,s)}var cr=S({split_:C4});function I4(r,e){A(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=L(_o(n,s),[o,t]),i=Ea(a),l=Math.floor(t/2)+1,u=ll(i),c=Nu(i),p=cr(u,[l,t-l],u.shape.length-1),m=cr(c,[l,t-l],c.shape.length-1),f=n.shape.slice();return f[n.shape.length-1]=l,L(_o(p[0],m[0]),f)}var Da=S({rfft_:I4});function N4(r){let t={x:v(r,"x","sqrt")};return E.runKernel(En,t)}var gt=S({sqrt_:N4});function S4(r,e){let t=v(r,"a","squaredDifference"),o=v(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_:S4});function T4(r,e){let t=v(r,"x","squeeze");return L(t,vb(t.shape,e).newShape)}var Co=S({squeeze_:T4});function A4(r,e=0){let t=ha(r,"tensors","stack","string_or_numeric");A(t.length>=1,()=>"Pass at least one tensor to tf.stack"),t.length>0&&A(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_:A4});function E4(r,e=0){let o={x:v(r,"x","step")},n={alpha:e};return E.runKernel(Oo,o,n)}var Ds=S({step_:E4});function D4(r,e,t,o,n=0,s=0,a=0,i=0,l=0){let c={x:v(r,"x","stridedSlice")},p={begin:e,end:t,strides:o,beginMask:n,endMask:s,ellipsisMask:a,newAxisMask:i,shrinkAxisMask:l};return E.runKernel(Ai,c,p)}var Xm=S({stridedSlice_:D4});function $4(r){let t={x:v(r,"x","tan")};return E.runKernel(Ei,t)}var Ym=S({tan_:$4});function Vt(r,e){Do(r);let t=Cr(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=Cr(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 R4(r,e,t){if(Do(r),e!=null&&e.length!==4)throw new Error("tensor4d() requires shape to have four numbers");let o=Cr(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 F4(r,e,t){if(Do(r),e!=null&&e.length!==5)throw new Error("tensor5d() requires shape to have five numbers");let o=Cr(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 O4(r,e,t){if(Do(r),e!=null&&e.length!==6)throw new Error("tensor6d() requires shape to have six numbers");let o=Cr(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 P4(r,e=1,t=!0){let o=v(r,"x","topk");if(o.rank===0)throw new Error("topk() expects the input to be of rank 1 or higher");let n=o.shape[o.shape.length-1];if(e>n)throw new Error(`'k' passed to topk() must be <= the last dimension (${n}) but got ${e}`);let s={x:o},a={k:e,sorted:t},[i,l]=E.runKernel(Di,s,a);return{values:i,indices:l}}var Zm=S({topk_:P4});function M4(r,e=0,t=1,o,n){if(o!=null&&o==="bool")throw new Error("Unsupported data type $ { dtype }");let s=new Zc(e,t,o,!0,n),a=ve(r,o);for(let i=0;i<a.values.length;i++)a.values[i]=s.nextValue();return a.toTensor()}var Bu=S({truncatedNormal_:M4});function L4(r,e=0){let t=v(r,"x","unique","string_or_numeric");A(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 ep=S({unique_:L4});function z4(r,e,t){let o=v(r,"x","unsortedSegmentSum"),n=v(e,"segmentIds","unsortedSegmentSum","int32");A(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_:z4});function B4(r,e=0){let t=v(r,"x","unstack","string_or_numeric");A(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 pr=S({unstack_:B4});function Yw(r,e=!0,t,o){return E.makeVariable(r,e,t,o)}function Zw(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 V4(r){let e=v(r,"condition","whereAsync","bool"),t=await e.data(),o=Zw(e.shape,t);return r!==e&&e.dispose(),o}var Qm=V4;async function G4(r,e,t){let o=v(r,"tensor","boolMask"),n=v(e,"mask","boolMask","bool"),s=t==null?0:t,a=n.rank,i=o.shape;A(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=L(o,u),p=L(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 W4=G4;function j4(r,e="euclidean",t=null,o=!1){r=v(r,"x","norm");let n=KN(r,e,t),s=n.shape;if(o){let a=Qt(t,r.shape);s=Bn(n.shape,a)}return L(n,s)}function KN(r,e,t=null){if(r.rank===0)return It(r);if(r.rank!==1&&t===null)return KN(L(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 ur(It(r),t);if(e===-Infinity)return Pi(It(r),t);if(e==="euclidean"||e===2)return gt(ge(Or(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 ur(ge(It(r),t[0]),t[1]-1);if(e===Infinity)return ur(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_:j4});function U4(r,e,t,o,n=!0){let s=v(r,"v","movingAverage"),a=v(e,"x","movingAverage"),i=v(t,"decay","movingAverage");Wb(s,a),A(jr(s.shape,a.shape),()=>"Shape mismatch in v and x");let l=le(1),u=ce(l,i),c=P(ce(a,s),u);if(n){A(o!=null,()=>"When using zeroDebias: true, step is required.");let p=v(o,"step","movingAverage");c=me(c,ce(l,Or(i,p)))}return ee(s,c)}var H4=S({movingAverage_:U4});function q4(r,e,t){let o=v(r,"indices","scatterND","int32"),n=v(e,"updates","scatterND");Jh(n,o,t);let s={indices:o,updates:n},a={shape:t};return E.runKernel(Ci,s,a)}var Jw=S({scatterND_:q4});function XN(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 K4(r,e,t,o=0){let n=v(r,"sparseIndices","sparseToDense","int32"),s=v(e,"sparseValues","sparseToDense"),a=v(o,"defaultValue","sparseToDense",s.dtype);XN(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_:K4});function X4(r,e){let t=v(e,"indices","gatherND","int32"),n={params:v(r,"x","gatherND"),indices:t};return E.runKernel(li,n)}var Qw=S({gatherND_:X4});function YN(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 Y4(r,e,t,o){let n=v(r,"x","dropout");if(A(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.`),A(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=YN(n,t),a=1-e,i=me(Ss(ee(Es(s,0,1,"float32",o),a)),a);return P(n,i)}var ek=S({dropout_:Y4});function tk(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 Z4(r,e,t=1){let o=v(r,"predictions","inTopK"),n=v(e,"targets","inTopK");A(o.rank>1,()=>`inTopK() expects the predictions to be of rank 2 or higher, but got ${o.rank}`),A(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];A(t>0&&t<=s,()=>`'k' passed to inTopK() must be > 0 && <= the predictions last dimension (${s}), but got ${t}`);let a=await o.data(),i=await n.data(),[l,u]=[a.length/s,s],c=Cb("bool",l);for(let p=0;p<l;p++){let m=p*u,f=a.subarray(m,m+u),d=[];for(let h=0;h<f.length;h++)d.push({value:f[h],index:h});d.sort((h,g)=>g.value-h.value),c[p]=0;for(let h=0;h<t;h++)if(d[h].index===i[p]){c[p]=1;break}}return r!==o&&o.dispose(),e!==n&&n.dispose(),Rr(c,n.shape,"bool")}var J4=Z4;var Gn={};Ke(Gn,{conv2d:()=>tU,depthwiseConv2d:()=>sU,matMul:()=>aU});function Q4(r,e,t,o,n,s="NHWC",a){let i=r;r.rank===3&&(i=L(r,[1,r.shape[0],r.shape[1],r.shape[2]]));let l=e;l.rank===3&&(l=L(e,[1,e.shape[0],e.shape[1],e.shape[2]])),A(i.rank===4,()=>`Error in conv2dDerFilter: input must be rank 4, but got shape ${i.shape}.`),A(l.rank===4,()=>`Error in conv2dDerFilter: dy must be rank 4, but got shape ${l.shape}.`),A(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];A(u===t[2],()=>`Error in conv2dDerFilter: depth of input ${u}) must match input depth in filter (${t[2]}.`),A(c===t[3],()=>`Error in conv2dDerFilter: depth of dy (${c}) must match output depth for filter (${t[3]}).`),a!=null&&A(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 tp=S({conv2DBackpropFilter_:Q4});function Gu(r,e,t){if(t==null||t==="linear")return r;if(t==="relu")return P(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)),L(t,r.shape)}function ju(r,e,t,o){if(e==="linear")return r;if(e==="relu")return Sr(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 eU({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 _=Kr(r,e,t,o,n,s,a);return i!=null&&(_=ee(_,i)),ju(_,l,u,c)}let p=v(r,"x","conv2d"),m=v(e,"filter","conv2d"),f=p,d=!1;p.rank===3&&(d=!0,f=L(p,[1,p.shape[0],p.shape[1],p.shape[2]])),A(f.rank===4,()=>`Error in fused conv2d: input must be rank 4, but got rank ${f.rank}.`),A(m.rank===4,()=>`Error in fused conv2d: filter must be rank 4, but got rank ${m.rank}.`),a!=null&&A(ot(o),()=>`Error in fused conv2d: pad must be an integer when using, dimRoundingMode ${a} but got pad ${o}.`),A(f.shape[3]===m.shape[2],()=>`Error in conv2d: depth of input (${f.shape[3]}) must match input depth for filter ${m.shape[2]}.`),A(kr(t,s),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${t} and dilations '${s}'`),A(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=v(i,"bias","fused conv2d"),[g]=Ge(g,p),Be(h.outShape,g.shape));let x;u!=null&&(x=v(u,"prelu weights","fused conv2d"));let b=(_,D)=>{let[T,R,O,M]=D,G=Gu(_,O,l);A(Lo(s),()=>`Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${s}'`);let j=Kc(R.shape,G,T,t,o),U=tp(R,G,T.shape,t,o),H=[j,U];if(M!=null){let q=Wu(M,G);H.push(q)}return H},w={x:f,filter:m,bias:g,preluActivationWeights:x},k={strides:t,pad:o,dataFormat:n,dilations:s,dimRoundingMode:a,activation:l,leakyreluAlpha:c};return i==null?Xr((D,T,R)=>{let O=E.runKernel(ks,w,k);return R([T,D,O]),d&&(O=L(O,[O.shape[1],O.shape[2],O.shape[3]])),{value:O,gradFunc:b}})(f,m):Xr((D,T,R,O)=>{let M=E.runKernel(ks,w,k);return O([T,D,M,R]),d&&(M=L(M,[M.shape[1],M.shape[2],M.shape[3]])),{value:M,gradFunc:b}})(f,m,g)}var tU=S({fusedConv2d_:eU});function rU(r,e,t,o,n,s=[1,1],a){let i=r;r.rank===3&&(i=L(r,[1,r.shape[0],r.shape[1],r.shape[2]]));let l=e;l.rank===3&&(l=L(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let u={x:i,dy:l},c={strides:o,pad:n,dimRoundingMode:a,dilations:s,filterShape:t};return E.runKernel(ql,u,c)}var cg=S({depthwiseConv2dNativeBackpropFilter_:rU});function oU(r,e,t,o,n,s=[1,1],a){let i=e,l=!1;e.rank===3&&(l=!0,i=L(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let u={dy:i,filter:t},c={strides:o,pad:n,dimRoundingMode:a,dilations:s,inputShape:r},p=E.runKernel(Kl,u,c);return l?L(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var pg=S({depthwiseConv2dNativeBackpropInput_:oU});function nU({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 _=Is(r,e,t,o,n,s,a);return i!=null&&(_=ee(_,i)),ju(_,l,u,c)}let p=v(r,"x","depthwiseConv2d"),m=v(e,"filter","depthwiseConv2d"),f=p,d=!1;p.rank===3&&(d=!0,f=L(p,[1,p.shape[0],p.shape[1],p.shape[2]])),A(f.rank===4,()=>`Error in fused depthwiseConv2d: input must be rank 4, but got rank ${f.rank}.`),A(m.rank===4,()=>`Error in fused depthwiseConv2d: filter must be rank 4, but got rank ${m.rank}.`),A(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]),A(kr(t,s),()=>`Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides ${t} and dilations '${s}'`),a!=null&&A(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=v(i,"bias","fused conv2d"),[g]=Ge(g,p),Be(h.outShape,g.shape));let x;u!=null&&(x=v(u,"prelu weights","fused depthwiseConv2d"));let b=(_,D)=>{A(Lo(s),()=>`Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '${s}'`);let[T,R,O,M]=D,G=Gu(_,O,l),j=pg(R.shape,G,T,t,o,s,a),U=cg(R,G,T.shape,t,o,s,a);if(M!=null){let H=Wu(g,G);return[j,U,H]}return[j,U]},w={x:f,filter:m,bias:g,preluActivationWeights:x},k={strides:t,pad:o,dataFormat:n,dilations:s,dimRoundingMode:a,activation:l,leakyreluAlpha:c};return i==null?Xr((D,T,R)=>{let O=E.runKernel(_s,w,k);return R([T,D,O]),d&&(O=L(O,[O.shape[1],O.shape[2],O.shape[3]])),{value:O,gradFunc:b}})(f,m):Xr((D,T,R,O)=>{let M=E.runKernel(_s,w,k);return O([T,D,M,R]),d&&(M=L(M,[M.shape[1],M.shape[2],M.shape[3]])),{value:M,gradFunc:b}})(f,m,g)}var sU=S({fusedDepthwiseConv2d_:nU});function iU({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 M=We(r,e,t,o);return n!=null&&(M=ee(M,n)),ju(M,s,a,i)}let l=v(r,"a","fused matMul"),u=v(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),x=ct(h);A(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}.`),A(jr(d,h),()=>`Error in fused matMul: outer dimensions (${d}) and (${h}) of Tensors with shapes ${l.shape} and ${u.shape} must match.`),A(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?L(l,[g,c,m]):L(l,[g,m,c]),k=o?L(u,[x,f,p]):L(u,[x,p,f]),_;n!=null&&(_=v(n,"bias","fused matMul"),[_]=Ge(_,l),Be(b,_.shape));let D;a!=null&&(D=v(a,"prelu weights","fused matMul"));let T=(M,G)=>{let[j,U,H,q]=G,X=Gu(L(M,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:_,preluActivationWeights:D},O={transposeA:t,transposeB:o,activation:s,leakyreluAlpha:i};return n==null?Xr((G,j,U)=>{let H=E.runKernel(ws,R,O);return U([G,j,H]),{value:L(H,b),gradFunc:T}})(w,k):Xr((G,j,U,H)=>{let q=E.runKernel(ws,R,O);return H([G,j,q,U]),{value:L(q,b),gradFunc:T}})(w,k,_)}var aU=S({fusedMatMul_:iU});function lU(r){return tf(r,.54,.46)}var ZN=S({hammingWindow_:lU});function uU(r){return tf(r,.5,.5)}var mg=S({hannWindow_:uU});function cU(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]):L(Ze(a),[a.length,e])}var fg=S({frame_:cU});function pU(r,e,t,o,n=mg){o==null&&(o=tk(e));let s=fg(r,e,t),a=P(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 JN=S({stft_:pU});function mU(r,e,t,o,n="bilinear",s=0){let a=v(r,"image","cropAndResize"),i=v(e,"boxes","cropAndResize","float32"),l=v(t,"boxInd","cropAndResize","int32"),u=i.shape[0];A(a.rank===4,()=>`Error in cropAndResize: image must be rank 4,but got rank ${a.rank}.`),A(i.rank===2&&i.shape[1]===4,()=>`Error in cropAndResize: boxes must be have size [${u},4] but had shape ${i.shape}.`),A(l.rank===1&&l.shape[0]===u,()=>`Error in cropAndResize: boxInd must be have size [${u}] but had shape ${i.shape}.`),A(o.length===2,()=>`Error in cropAndResize: cropSize must be of length 2, but got length ${o.length}.`),A(o[0]>=1&&o[1]>=1,()=>`cropSize must be atleast [1,1], but was ${o}`),A(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 QN=S({cropAndResize_:mU});function fU(r){let e=v(r,"image","flipLeftRight","float32");A(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 eS=S({flipLeftRight_:fU});function dU(r,e,t=0,o=.5){let n=v(r,"image","rotateWithOffset","float32");A(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 tS=S({rotateWithOffset_:dU});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),A(0<=o&&o<=1,()=>`iouThreshold must be in [0, 1], but was '${o}'`),A(r.rank===2,()=>`boxes must be a 2D tensor, but was of rank '${r.rank}'`),A(r.shape[1]===4,()=>`boxes must have 4 columns, but 2nd dimension was ${r.shape[1]}`),A(e.rank===1,()=>"scores must be a 1D tensor"),A(e.shape[0]===a,()=>`scores has incompatible shape with boxes. Expected ${a}, but was ${e.shape[0]}`),A(0<=s&&s<=1,()=>`softNmsSigma must be in [0, 1], but was '${s}'`),{maxOutputSize:t,iouThreshold:o,scoreThreshold:n,softNmsSigma:s}}function hU(r,e,t,o=.5,n=Number.NEGATIVE_INFINITY){let s=v(r,"boxes","nonMaxSuppression"),a=v(e,"scores","nonMaxSuppression"),i=Wn(s,a,t,o,n);t=i.maxOutputSize,o=i.iouThreshold,n=i.scoreThreshold;let l={maxOutputSize:t,iouThreshold:o,scoreThreshold:n};return E.runKernel(bi,{boxes:s,scores:a},l)}var rS=S({nonMaxSuppression_:hU});function oS(r,e,t){let o=gU(r,e,t),n=o<0?-(o+1):o;r.splice(n,0,e)}function gU(r,e,t){return yU(r,e,t||xU)}function xU(r,e){return r>e?1:r<e?-1:0}function yU(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 ok(r,e,t,o,n){return rk(r,e,t,o,n,0)}function nk(r,e,t,o,n,s){return rk(r,e,t,o,n,0,!1,s,!0)}function sk(r,e,t,o,n,s){return rk(r,e,t,o,n,s,!0)}function rk(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(nS);let c=s>0?-.5/s:0,p=[],m=[];for(;p.length<t&&u.length>0;){let g=u.pop(),{score:x,boxIndex:b,suppressBeginIndex:w}=g;if(x<n)break;let k=!1;for(let _=p.length-1;_>=w;--_){let D=bU(r,b,p[_]);if(D>=o){k=!0;break}if(g.score=g.score*wU(o,c,D),g.score<=n)break}g.suppressBeginIndex=p.length,k||(g.score===x?(p.push(b),m.push(g.score)):g.score>n&&oS(u,g,nS))}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 bU(r,e,t){let o=r.subarray(e*4,e*4+4),n=r.subarray(t*4,t*4+4),s=Math.min(o[0],o[2]),a=Math.min(o[1],o[3]),i=Math.max(o[0],o[2]),l=Math.max(o[1],o[3]),u=Math.min(n[0],n[2]),c=Math.min(n[1],n[3]),p=Math.max(n[0],n[2]),m=Math.max(n[1],n[3]),f=(i-s)*(l-a),d=(p-u)*(m-c);if(f<=0||d<=0)return 0;let h=Math.max(s,u),g=Math.max(a,c),x=Math.min(i,p),b=Math.min(l,m),w=Math.max(x-h,0)*Math.max(b-g,0);return w/(f+d-w)}function wU(r,e,t){let o=Math.exp(e*t*t);return t<=r?o:0}function nS(r,e){return r.score-e.score||r.score===e.score&&e.boxIndex-r.boxIndex}async function kU(r,e,t,o=.5,n=Number.NEGATIVE_INFINITY){let s=v(r,"boxes","nonMaxSuppressionAsync"),a=v(e,"scores","nonMaxSuppressionAsync"),i=Wn(s,a,t,o,n);t=i.maxOutputSize,o=i.iouThreshold,n=i.scoreThreshold;let l=await Promise.all([s.data(),a.data()]),u=l[0],c=l[1],{selectedIndices:p}=ok(u,c,t,o,n);return s!==r&&s.dispose(),a!==e&&a.dispose(),Vt(p,"int32")}var sS=kU;function _U(r,e,t,o=.5,n=Number.NEGATIVE_INFINITY,s=0){let a=v(r,"boxes","nonMaxSuppression"),i=v(e,"scores","nonMaxSuppression"),l=Wn(a,i,t,o,n,s);t=l.maxOutputSize,o=l.iouThreshold,n=l.scoreThreshold,s=l.softNmsSigma;let u={boxes:a,scores:i},c={maxOutputSize:t,iouThreshold:o,scoreThreshold:n,softNmsSigma:s},p=E.runKernel(ki,u,c);return{selectedIndices:p[0],selectedScores:p[1]}}var iS=S({nonMaxSuppressionWithScore_:_U});async function vU(r,e,t,o=.5,n=Number.NEGATIVE_INFINITY,s=0){let a=v(r,"boxes","nonMaxSuppressionAsync"),i=v(e,"scores","nonMaxSuppressionAsync"),l=Wn(a,i,t,o,n,s);t=l.maxOutputSize,o=l.iouThreshold,n=l.scoreThreshold,s=l.softNmsSigma;let u=await Promise.all([a.data(),i.data()]),c=u[0],p=u[1],{selectedIndices:m,selectedScores:f}=sk(c,p,t,o,n,s);return a!==r&&a.dispose(),i!==e&&i.dispose(),{selectedIndices:Vt(m,"int32"),selectedScores:Vt(f)}}var aS=vU;function CU(r,e,t,o=.5,n=Number.NEGATIVE_INFINITY,s=!1){let a=v(r,"boxes","nonMaxSuppression"),i=v(e,"scores","nonMaxSuppression"),l=Wn(a,i,t,o,n,null),u=l.maxOutputSize,c=l.iouThreshold,p=l.scoreThreshold,m={boxes:a,scores:i},f={maxOutputSize:u,iouThreshold:c,scoreThreshold:p,padToMaxOutputSize:s},d=E.runKernel(wi,m,f);return{selectedIndices:d[0],validOutputs:d[1]}}var lS=S({nonMaxSuppressionPadded_:CU});async function IU(r,e,t,o=.5,n=Number.NEGATIVE_INFINITY,s=!1){let a=v(r,"boxes","nonMaxSuppressionAsync"),i=v(e,"scores","nonMaxSuppressionAsync"),l=Wn(a,i,t,o,n,null),u=l.maxOutputSize,c=l.iouThreshold,p=l.scoreThreshold,[m,f]=await Promise.all([a.data(),i.data()]),{selectedIndices:d,validOutputs:h}=nk(m,f,u,c,p,s);return a!==r&&a.dispose(),i!==e&&i.dispose(),{selectedIndices:Vt(d,"int32"),validOutputs:le(h,"int32")}}var uS=IU;function NU(r,e,t=!1,o=!1){let n=v(r,"images","resizeBilinear");A(n.rank===3||n.rank===4,()=>`Error in resizeBilinear: x must be rank 3 or 4, but got rank ${n.rank}.`),A(e.length===2,()=>`Error in resizeBilinear: new shape must 2D, but got shape ${e}.`),A(o===!1||t===!1,()=>"Error in resizeBilinear: If halfPixelCenters is true, alignCorners must be false.");let s=n,a=!1;n.rank===3&&(a=!0,s=L(n,[1,n.shape[0],n.shape[1],n.shape[2]]));let[]=e,i={images:s},l={alignCorners:t,halfPixelCenters:o,size:e},u=E.runKernel(vn,i,l);return a?L(u,[u.shape[1],u.shape[2],u.shape[3]]):u}var dg=S({resizeBilinear_:NU});function SU(r,e,t=!1,o=!1){let n=v(r,"images","resizeNearestNeighbor");A(n.rank===3||n.rank===4,()=>`Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank ${n.rank}.`),A(e.length===2,()=>`Error in resizeNearestNeighbor: new shape must 2D, but got shape ${e}.`),A(n.dtype==="float32"||n.dtype==="int32",()=>"`images` must have `int32` or `float32` as dtype"),A(o===!1||t===!1,()=>"Error in resizeNearestNeighbor: If halfPixelCenters is true, alignCorners must be false.");let s=n,a=!1;n.rank===3&&(a=!0,s=L(n,[1,n.shape[0],n.shape[1],n.shape[2]]));let[]=e,i={images:s},l={alignCorners:t,halfPixelCenters:o,size:e},u=E.runKernel(pa,i,l);return a?L(u,[u.shape[1],u.shape[2],u.shape[3]]):u}var hg=S({resizeNearestNeighbor_:SU});function TU(r,e,t="nearest",o="constant",n=0,s){let a=v(r,"image","transform","float32"),i=v(e,"transforms","transform","float32");A(a.rank===4,()=>`Error in transform: image must be rank 4,but got rank ${a.rank}.`),A(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"),A(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 cS=S({transform_:TU});function AU(r,e,t){A(e%1==0,()=>`bandPart(): numLower must be an integer, got ${e}.`),A(t%1==0,()=>`bandPart(): numUpper must be an integer, got ${t}.`);let o=v(r,"a","bandPart");A(o.rank>=2,()=>`bandPart(): Rank must be at least 2, got ${o.rank}.`);let n=o.shape,[s,a]=o.shape.slice(-2);if(!(e<=s))throw new Error(`bandPart(): numLower (${e}) must not be greater than the number of rows (${s}).`);if(!(t<=a))throw new Error(`bandPart(): numUpper (${t}) must not be greater than the number of columns (${a}).`);e<0&&(e=s),t<0&&(t=a);let i=L(Jc(0,s,1,"int32"),[-1,1]),l=Jc(0,a,1,"int32"),u=ce(i,l),c=hr(Bo(u,le(+e,"int32")),io(u,le(-t,"int32"))),p=ht([s,a],o.dtype);return L(Bt(pr(L(o,[-1,s,a])).map(m=>Dt(c,m,p))),n)}var pS=S({bandPart_:AU});function EU(r){let e;if(Array.isArray(r)){e=!1,A(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)A(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=cr(r,r.shape[0],0).map(n=>Co(n,[0]));A(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=P(ge(P(t[a],s)),t[a]);s=ce(s,i)}return me(s,Vu(s,"euclidean"))}));return e?Bt(t,0):t}var mS=S({gramSchmidt_:EU});function DU(r,e=!1){if(A(r.rank>=2,()=>`qr() requires input tensor to have a rank >= 2, but got rank ${r.rank}`),r.rank===2)return fS(r,e);{let t=r.shape.slice(0,r.shape.length-2).reduce((l,u)=>l*u),o=pr(L(r,[t,r.shape[r.shape.length-2],r.shape[r.shape.length-1]]),0),n=[],s=[];o.forEach(l=>{let[u,c]=fS(l,e);n.push(u),s.push(c)});let a=L(Bt(n,0),r.shape),i=L(Bt(s,0),r.shape);return[a,i]}}function fS(r,e=!1){return E.tidy(()=>{A(r.shape.length===2,()=>`qr2d() requires a 2D Tensor, but got a ${r.shape.length}D Tensor.`);let t=r.shape[0],o=r.shape[1],n=Xc(t),s=Po(r),a=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(er(h,0),Li([[-1]]),Li([[1]])),x=ce(h,P(g,d)),b=me(f,x);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,x),d)),k=Re(s,[u,0],[t-u,o]),_=P(w,i),D=Ue(i);if(u===0)s=ce(k,We(_,We(D,k)));else{let O=ce(k,We(_,We(D,k)));s=Ze([Re(s,[0,0],[u,o]),O],0)}let T=Ue(_),R=Re(n,[0,u],[t,n.shape[1]-u]);if(u===0)n=ce(R,We(We(R,i),T));else{let O=ce(R,We(We(R,i),T));n=Ze([Re(n,[0,0],[t,u]),O],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 dS=S({qr_:DU});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 $U(r,e,t=Gt.SUM_BY_NONZERO_WEIGHTS){let o=v(r,"losses","computeWeightedLoss"),n=null;e!=null&&(n=v(e,"weights","computeWeightedLoss"));let s=n==null?o:P(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=P(n,Nr(o.shape)),i=ne(ge(Vn(a,le(0))),"float32");return me(ge(s),i)}}throw Error(`Unknown reduction: ${t}`)}var Tr=S({computeWeightedLoss_:$U});function RU(r,e,t,o=Gt.SUM_BY_NONZERO_WEIGHTS){let n=v(r,"labels","absoluteDifference"),s=v(e,"predictions","absoluteDifference"),a=null;t!=null&&(a=v(t,"weights","absoluteDifference")),vt(n.shape,s.shape,"Error in absoluteDifference: ");let i=It(ce(n,s));return Tr(i,a,o)}var hS=S({absoluteDifference_:RU});function FU(r,e,t,o,n=Gt.SUM_BY_NONZERO_WEIGHTS){let s=v(r,"labels","cosineDistance"),a=v(e,"predictions","cosineDistance"),i=null;o!=null&&(i=v(o,"weights","cosineDistance")),vt(s.shape,a.shape,"Error in cosineDistance: ");let l=le(1),u=ce(l,ge(P(s,a),t,!0));return Tr(u,i,n)}var gS=S({cosineDistance_:FU});function OU(r,e,t,o=Gt.SUM_BY_NONZERO_WEIGHTS){let n=v(r,"labels","hingeLoss"),s=v(e,"predictions","hingeLoss"),a=null;t!=null&&(a=v(t,"weights","hingeLoss")),vt(n.shape,s.shape,"Error in hingeLoss: ");let i=le(1);n=ce(P(le(2),n),i);let l=Sr(ce(i,P(n,s)));return Tr(l,a,o)}var xS=S({hingeLoss_:OU});function PU(r,e,t,o=1,n=Gt.SUM_BY_NONZERO_WEIGHTS){let s=v(r,"labels","huberLoss"),a=v(e,"predictions","huberLoss"),i=null;t!=null&&(i=v(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(P(le(.5),Oe(c)),P(l,p));return Tr(m,i,n)}var yS=S({huberLoss_:PU});function MU(r,e,t,o=1e-7,n=Gt.SUM_BY_NONZERO_WEIGHTS){let s=v(r,"labels","logLoss"),a=v(e,"predictions","logLoss"),i=null;t!=null&&(i=v(t,"weights","logLoss")),vt(s.shape,a.shape,"Error in logLoss: ");let l=le(1),u=le(o),c=He(P(s,lr(ee(a,u)))),p=P(ce(l,s),lr(ee(ce(l,a),u))),m=ce(c,p);return Tr(m,i,n)}var bS=S({logLoss_:MU});function LU(r,e,t,o=Gt.SUM_BY_NONZERO_WEIGHTS){let n=v(r,"labels","meanSquaredError"),s=v(e,"predictions","meanSquaredError"),a=null;t!=null&&(a=v(t,"weights","meanSquaredError")),vt(n.shape,s.shape,"Error in meanSquaredError: ");let i=zu(n,s);return Tr(i,a,o)}var wS=S({meanSquaredError_:LU});function zU(r,e){let t=v(r,"labels","sigmoidCrossEntropyWithLogits"),o=v(e,"logits","sigmoidCrossEntropyWithLogits");vt(t.shape,o.shape,"Error in sigmoidCrossEntropyWithLogits: ");let n=Sr(o),s=P(o,t),a=Tu(Zt(He(It(o))));return ee(ce(n,s),a)}function BU(r,e,t,o=0,n=Gt.SUM_BY_NONZERO_WEIGHTS){let s=v(r,"multiClassLabels","sigmoidCrossEntropy"),a=v(e,"logits","sigmoidCrossEntropy"),i=null;if(t!=null&&(i=v(t,"weights","sigmoidCrossEntropy")),vt(s.shape,a.shape,"Error in sigmoidCrossEntropy: "),o>0){let u=le(o),c=le(1),p=le(.5);s=ee(P(s,ce(c,u)),P(p,u))}let l=zU(s,a);return Tr(l,i,n)}var kS=S({sigmoidCrossEntropy_:BU});function VU(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=zm(s,[t],!0),u=ce(ne(s,"float32"),l);a([n,u]);let c=He(P(u,n));return{value:ge(c,[t]),gradFunc:(f,d)=>{let[h,g]=d,x=Bn(f.shape,[t]);return[P(L(f,x),ce(ne(h,"float32"),Zt(g))),P(L(f,x),ce(Zt(g),ne(h,"float32")))]}}})(r,e)}function GU(r,e,t,o=0,n=Gt.SUM_BY_NONZERO_WEIGHTS){let s=v(r,"onehotLabels","softmaxCrossEntropy"),a=v(e,"logits","softmaxCrossEntropy"),i=null;if(t!=null&&(i=v(t,"weights","softmaxCrossEntropy")),vt(s.shape,a.shape,"Error in softmaxCrossEntropy: "),o>0){let u=le(o),c=le(1),p=le(s.shape[1]);s=ee(P(s,ce(c,u)),me(u,p))}let l=VU(s,a);return Tr(l,i,n)}var _S=S({softmaxCrossEntropy_:GU});var WU={fft:Ea,ifft:Mi,rfft:Da,irfft:Lu},jU={hammingWindow:ZN,hannWindow:mg,frame:fg,stft:JN},$s={flipLeftRight:eS,resizeNearestNeighbor:hg,resizeBilinear:dg,rotateWithOffset:tS,cropAndResize:QN,nonMaxSuppression:rS,nonMaxSuppressionAsync:sS,nonMaxSuppressionWithScore:iS,nonMaxSuppressionWithScoreAsync:aS,nonMaxSuppressionPadded:lS,nonMaxSuppressionPaddedAsync:uS,transform:cS},ik={bandPart:pS,gramSchmidt:mS,qr:dS},UU={absoluteDifference:hS,computeWeightedLoss:Tr,cosineDistance:gS,hingeLoss:xS,huberLoss:yS,logLoss:bS,meanSquaredError:wS,sigmoidCrossEntropy:kS,softmaxCrossEntropy:_S};var Pr=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(Pr,Symbol.hasInstance,{value:r=>r.minimize!=null&&r.computeGradients!=null&&r.applyGradients!=null});var rp=class extends Pr{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(P(l,this.rho),P(Oe(i),1-this.rho)),p=P(me(gt(ee(u,this.epsilon)),gt(ee(l,this.epsilon))),i),m=ee(P(u,this.rho),P(Oe(p),1-this.rho));l.assign(c),u.assign(m);let f=ee(P(p,-this.learningRate),s);s.assign(f)})}),this.incrementIterations()}dispose(){this.accumulatedUpdates!=null&&(Ae(this.accumulatedGrads.map(e=>e.variable)),Ae(this.accumulatedUpdates.map(e=>e.variable)))}async getWeights(){let e=[...this.accumulatedGrads,...this.accumulatedUpdates];return[await this.saveIterations()].concat(e.map(t=>({name:t.originalName,tensor:t.variable})))}async setWeights(e){e=await this.extractIterations(e);let t=e.length/2,o=!1;this.accumulatedGrads=e.slice(0,t).map(n=>({originalName:n.name,variable:n.tensor.variable(o)})),this.accumulatedUpdates=e.slice(t,t*2).map(n=>({originalName:n.name,variable:n.tensor.variable(o)}))}getConfig(){return{learningRate:this.learningRate,rho:this.rho,epsilon:this.epsilon}}static fromConfig(e,t){return new e(t.learningRate,t.rho,t.epsilon)}};rp.className="Adadelta";so(rp);var op=class extends Pr{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(P(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)}};op.className="Adagrad";so(op);var np=class extends Pr{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(P(c,this.beta1),P(u,1-this.beta1)),f=ee(P(p,this.beta2),P(Oe(u),1-this.beta2)),d=me(m,o),h=me(f,n);c.assign(m),p.assign(f);let g=ee(P(me(d,ee(gt(h),this.epsilon)),-this.learningRate),i);i.assign(g)}),this.accBeta1.assign(P(this.accBeta1,this.beta1)),this.accBeta2.assign(P(this.accBeta2,this.beta2))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.accBeta2.dispose(),this.accumulatedFirstMoment!=null&&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(Or(this.beta1,this.iterations_+1)),this.accBeta2.assign(Or(this.beta2,this.iterations_+1))});let t=e.length/2,o=!1;this.accumulatedFirstMoment=e.slice(0,t).map(n=>({originalName:n.name,variable:n.tensor.variable(o)})),this.accumulatedSecondMoment=e.slice(t,t*2).map(n=>({originalName:n.name,variable:n.tensor.variable(o)}))}getConfig(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon}}static fromConfig(e,t){return new e(t.learningRate,t.beta1,t.beta2,t.epsilon)}};np.className="Adam";so(np);var sp=class extends Pr{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(P(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(P(c,this.beta1),P(u,1-this.beta1)),f=P(p,this.beta2),d=It(u),h=Yr(f,d);c.assign(m),p.assign(h);let g=ee(P(me(n,o),me(m,ee(h,this.epsilon))),i);i.assign(g)}),this.iteration.assign(ee(this.iteration,1)),this.accBeta1.assign(P(this.accBeta1,this.beta1))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.iteration.dispose(),this.accumulatedFirstMoment!=null&&Ae(this.accumulatedFirstMoment.map(e=>e.variable)),this.accumulatedWeightedInfNorm!=null&&Ae(this.accumulatedWeightedInfNorm.map(e=>e.variable))}async getWeights(){throw new Error("getWeights() is not implemented for Adamax yet.")}async setWeights(e){throw new Error("setWeights() is not implemented for Adamax yet.")}getConfig(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon,decay:this.decay}}static fromConfig(e,t){return new e(t.learningRate,t.beta1,t.beta2,t.epsilon,t.decay)}};sp.className="Adamax";so(sp);var ul=class extends Pr{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(P(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 ip=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(P(this.m,a),i);this.useNesterov?l=ee(P(this.c,ee(i,P(u,this.m))),s):l=ee(P(this.c,u),s),a.assign(u),s.assign(l)})}),this.incrementIterations()}dispose(){this.m.dispose(),this.accumulations!=null&&Ae(this.accumulations.map(e=>e.variable))}setMomentum(e){this.momentum=e}async getWeights(){return[await this.saveIterations()].concat(this.accumulations.map(e=>({name:e.originalName,tensor:e.variable})))}async setWeights(e){e=await this.extractIterations(e);let t=!1;this.accumulations=e.map(o=>({originalName:o.name,variable:o.tensor.variable(t)}))}getConfig(){return{learningRate:this.learningRate,momentum:this.momentum,useNesterov:this.useNesterov}}static fromConfig(e,t){return new e(t.learningRate,t.momentum,t.useNesterov)}};ip.className="Momentum";so(ip);var ap=class extends Pr{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(P(l,this.decay),P(Oe(i),1-this.decay));if(this.centered){let p=this.accumulatedMeanGrads[n].variable,m=ee(P(p,this.decay),P(i,1-this.decay)),f=me(P(i,this.learningRate),gt(ce(c,ee(Oe(m),this.epsilon)))),d=ee(P(u,this.momentum),f);l.assign(c),p.assign(m),u.assign(d);let h=ce(s,d);s.assign(h)}else{let p=ee(P(l,this.decay),P(Oe(i),1-this.decay)),m=ee(P(u,this.momentum),me(P(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)}};ap.className="RMSProp";so(ap);var $a=class{static sgd(e){return new ul(e)}static momentum(e,t,o=!1){return new ip(e,t,o)}static rmsprop(e,t=.9,o=0,n=null,s=!1){return new ap(e,t,o,n,s)}static adam(e=.001,t=.9,o=.999,n=null){return new np(e,t,o,n)}static adadelta(e=.001,t=.95,o=null){return new rp(e,t,o)}static adamax(e=.002,t=.9,o=.999,n=null,s=0){return new sp(e,t,o,n,s)}static adagrad(e,t=.1){return new op(e,t)}};var cl={sgd:$a.sgd,momentum:$a.momentum,adadelta:$a.adadelta,adagrad:$a.adagrad,rmsprop:$a.rmsprop,adamax:$a.adamax,adam:$a.adam};var HU=(()=>typeof requestAnimationFrame!="undefined"?requestAnimationFrame:typeof setImmediate!="undefined"?setImmediate:r=>r())();function rf(){return new Promise(r=>HU(()=>r()))}var N={};Ke(N,{ERF_A1:()=>oH,ERF_A2:()=>nH,ERF_A3:()=>sH,ERF_A4:()=>iH,ERF_A5:()=>aH,ERF_P:()=>rH,PARALLELIZE_THRESHOLD:()=>gg,SELU_SCALE:()=>lk,SELU_SCALEALPHA:()=>ak,applyActivation:()=>ju,assertAndGetBroadcastShape:()=>Be,assertAxesAreInnerMostDims:()=>YW,assertParamsConsistent:()=>qU,assignToTypedArray:()=>hH,axesAreInnerMostDims:()=>$w,calculateShapes:()=>hN,combineLocations:()=>RN,complexWithEvenIndex:()=>mH,complexWithOddIndex:()=>fH,computeConv2DInfo:()=>wu,computeConv3DInfo:()=>DN,computeDefaultPad:()=>gw,computeDilation2DInfo:()=>kG,computeOptimalWindowSize:()=>XU,computeOutAndReduceShapes:()=>Rw,computeOutShape:()=>KU,computePool2DInfo:()=>dw,computePool3DInfo:()=>_G,convertConv2DDataFormat:()=>EN,eitherStridesOrDilationsAreOne:()=>kr,expandShapeToKeepDim:()=>Bn,exponent:()=>xH,exponents:()=>gH,fromStringArrayToUint8:()=>vH,fromUint8ToStringArray:()=>_H,getAxesPermutation:()=>Fw,getBroadcastDims:()=>mW,getComplexWithIndex:()=>dH,getFusedBiasGradient:()=>Wu,getFusedDyActivation:()=>Gu,getImageCenter:()=>YU,getInnerMostAxes:()=>ZW,getPermuted:()=>JU,getReductionAxes:()=>kt,getReshaped:()=>ZU,getReshapedPermuted:()=>QU,getSliceBeginCoords:()=>eH,getSliceSize:()=>tH,getUndoAxesPermutation:()=>Lm,log:()=>uH,mergeRealAndImagArrays:()=>cH,prepareAndValidate:()=>dN,prepareSplitSize:()=>yH,segment_util:()=>vS,shouldFuse:()=>Uu,slice_util:()=>sr,splitRealAndImagArrays:()=>pH,tupleValuesAreOne:()=>Lo,upcastType:()=>dr,validateInput:()=>Jh,validateUpdateShape:()=>aw,warn:()=>lH});function qU(r,e){let t=r[0].length;r.forEach((n,s)=>{A(n.length===t,()=>`Error in concat${t}D: rank of tensors[${s}] must be the same as the rank of the rest (${t})`)}),A(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++)A(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 KU(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 XU(r){return r<=gg?r:$c(r,Math.floor(Math.sqrt(r)))}function YU(r,e,t){let o=t*(typeof r=="number"?r:r[0]),n=e*(typeof r=="number"?r:r[1]);return[o,n]}function ZU(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 JU(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 QU(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 eH(r,e){let t=[0];for(let o=0;o<e;++o)t.push(r[o][0]);return t}function tH(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 ak=1.7580993408473768,lk=1.0507009873554805;var rH=.3275911,oH=.254829592,nH=-.284496736,sH=1.421413741,iH=-1.453152027,aH=1.061405429;function lH(...r){W().getBool("IS_TEST")||console.warn(...r)}function uH(...r){W().getBool("IS_TEST")||console.log(...r)}function cH(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 pH(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 mH(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 fH(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 dH(r,e){let t=r[e*2],o=r[e*2+1];return{real:t,imag:o}}function hH(r,e,t,o){r[o*2]=e,r[o*2+1]=t}function gH(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 xH(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 yH(r,e,t=0){let o=[];if(typeof e=="number")A(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);A(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}A(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 vS={};Ke(vS,{collectGatherOpShapeInfo:()=>kH,computeOutShape:()=>wH,segOpComputeOptimalWindowSize:()=>bH});function bH(r,e){let t=!1,o;for(r<=gg?(o=r,t=!0):o=$c(r,Math.floor(Math.sqrt(r)));!t;)o>e||o===r?t=!0:o=$c(r,o+1);return o}function wH(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 kH(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 _H(r){try{return r.map(e=>Bc(e))}catch(e){throw new Error(`Failed to decode encoded string bytes into utf-8, error: ${e}`)}}function vH(r){return r.map(e=>tl(e))}var Ar={};Ke(Ar,{nonMaxSuppressionV3Impl:()=>ok,nonMaxSuppressionV4Impl:()=>nk,nonMaxSuppressionV5Impl:()=>sk,whereImpl:()=>Zw});function te(r,e){Array.isArray(r)||(r=[r]),r.forEach(t=>{t!=null&&y.assert(t.dtype!=="complex64",()=>`${e} does not support complex64 tensors in the CPU backend.`)})}var CH=Ar.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&&y.isString(o[0])){let s=o.map(a=>y.encodeString(a));n=this.write(s,e,t)}else n=this.write(o,e,t);return{dataId:n,shape:e,dtype:t}}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=>y.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=y.now();return e(),{kernelMs:y.now()-t}}memory(){return{unreliable:!0,reasons:["The reported memory is an upper bound. Due to automatic garbage collection, the true allocated memory may be less."]}}where(e){te([e],"where");let t=this.readSync(e.dataId);return CH(e.shape,t)}dispose(){}floatPrecision(){return 32}epsilon(){return super.epsilon()}};Hu.nextDataId=0;var yg={};Ke(yg,{addImpl:()=>ES,bincountImpl:()=>of,bincountReduceImpl:()=>uk,ceilImpl:()=>$S,concatImpl:()=>nf,expImpl:()=>FS,expm1Impl:()=>PS,floorImpl:()=>LS,gatherV2Impl:()=>pk,greaterImpl:()=>BS,lessImpl:()=>GS,linSpaceImpl:()=>mk,logImpl:()=>jS,maxImpl:()=>fk,maximumImpl:()=>HS,minimumImpl:()=>KS,multiplyImpl:()=>xg,negImpl:()=>ZS,notEqualImpl:()=>QS,prodImpl:()=>rT,rangeImpl:()=>lf,rsqrtImpl:()=>nT,simpleAbsImpl:()=>CS,sliceImpl:()=>uf,squaredDifferenceImpl:()=>aT,stridedSliceImpl:()=>dk,subImpl:()=>uT,tileImpl:()=>hk,topKImpl:()=>gk,transposeImpl:()=>af,uniqueImpl:()=>xk});function CS(r){let e=new Float32Array(r.length);for(let t=0;t<r.length;++t)e[t]=Math.abs(r[t]);return e}var IH=r=>{let{x:e}=r.inputs,t=r.backend;te(e,"abs");let o=new Float32Array(y.sizeFromShape(e.shape)),n=t.data.get(e.dataId).values;return o=CS(n),t.makeOutput(o,e.shape,"float32")},IS={kernelName:as,backendName:"cpu",kernelFunc:IH};function Xe(r){return(e,t,o,n,s)=>{let a=N.assertAndGetBroadcastShape(e,t),i=a.length,l=y.computeStrides(a),u=y.sizeFromShape(a),c=y.getTypedArrayFromDType(s,u),p=e.length,m=t.length,f=y.computeStrides(e),d=y.computeStrides(t),h=N.getBroadcastDims(e,a),g=N.getBroadcastDims(t,a);if(h.length+g.length===0)for(let x=0;x<c.length;++x)c[x]=r(o[x%o.length],n[x%n.length]);else for(let x=0;x<c.length;++x){let b=y.indexToLoc(x,i,l),w=b.slice(-p);h.forEach(T=>w[T]=0);let k=y.locToIndex(w,p,f),_=b.slice(-m);g.forEach(T=>_[T]=0);let D=y.locToIndex(_,m,d);c[x]=r(o[k],n[D])}return[c,a]}}function mr(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 NS={kernelName:Gl,backendName:"cpu",kernelFunc:mr};function lp(r,e,t="float32"){if(t==="complex64"){let n=lp(r,e,"float32"),s=lp(r,e,"float32");return mr({inputs:{real:n,imag:s},backend:r})}let o=y.makeZerosTypedArray(y.sizeFromShape(e),t);return r.makeTensorInfo(e,t,o)}function Er(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 SS={kernelName:Fo,backendName:"cpu",kernelFunc:Er};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 TS={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 Er({inputs:{x:n},backend:t});let a=lp(t,n.shape,n.dtype),i=Un({inputs:{x:n},backend:t,attrs:{dtype:"float32"}}),l=mr({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(!y.hasEncodingLoss(n.dtype,s)){let a=Er({inputs:{x:n},backend:t});return{dataId:a.dataId,shape:a.shape,dtype:s}}if(s==="int32"){let a=t.data.get(n.dataId).values,i=Int32Array.from(a);return t.makeTensorInfo(n.shape,"int32",i)}if(s==="bool"){let a=t.data.get(n.dataId).values,i=y.toTypedArray([0],n.dtype),[l,u]=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 AS={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),x=g.complexTensorInfos.real,b=g.complexTensorInfos.imag,w=l.data.get(x.dataId).values,k=l.data.get(b.dataId).values,[_,D,T]=t(a.shape,i.shape,f,d,w,k),R=l.makeTensorInfo(T,"float32",_),O=l.makeTensorInfo(T,"float32",D),M=mr({inputs:{real:R,imag:O},backend:l});return l.disposeIntermediateTensorInfo(u),l.disposeIntermediateTensorInfo(h),l.disposeIntermediateTensorInfo(R),l.disposeIntermediateTensorInfo(O),M}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 up(r){return(e,t,o,n,s,a)=>{let i=N.assertAndGetBroadcastShape(e,t),l=y.sizeFromShape(i),u=i.length,c=y.computeStrides(i),p=y.getTypedArrayFromDType("float32",l),m=y.getTypedArrayFromDType("float32",l),f=N.getBroadcastDims(e,i),d=N.getBroadcastDims(t,i),h=N.mergeRealAndImagArrays(o,n),g=N.mergeRealAndImagArrays(s,a),x=e.length,b=y.computeStrides(e),w=t.length,k=y.computeStrides(t);if(f.length+d.length===0)for(let _=0;_<p.length;_++){let D=_%h.length,T=_%g.length,R=r(h[D*2],h[D*2+1],g[T*2],g[T*2+1]);p[_]=R.real,m[_]=R.imag}else for(let _=0;_<p.length;_++){let D=y.indexToLoc(_,u,c),T=D.slice(-x);f.forEach(j=>T[j]=0);let R=y.locToIndex(T,x,b),O=D.slice(-w);d.forEach(j=>O[j]=0);let M=y.locToIndex(O,w,k),G=r(h[R*2],h[R*2+1],g[M*2],g[M*2+1]);p[_]=G.real,m[_]=G.imag}return[p,m,i]}}var ES=Xe((r,e)=>r+e),NH=up((r,e,t,o)=>({real:r+t,imag:e+o})),Ra=et(wo,ES,NH),DS={kernelName:wo,backendName:"cpu",kernelFunc:Ra};function of(r,e,t,o,n){let s=y.sizeFromShape(o),a=y.makeZerosTypedArray(n,t);for(let i=0;i<r.length;i++){let l=r[i];if(l<0)throw new Error("Input x must be non-negative!");l>=n||(s>0?a[l]+=e[i]:a[l]+=1)}return a}function uk(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=y.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=y.sizeFromShape(a.shape),c=t||a.dtype,p=y.getArrayFromDType(c,u);for(let m=0;m<u;++m)p[m]=e(l[m],n);return i.makeTensorInfo(a.shape,c,p)}}function 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 $S=Hn(r=>Math.ceil(r)),SH=qn(Yo,$S),RS={kernelName:Yo,backendName:"cpu",kernelFunc:SH};function nf(r,e,t,o){let n=y.getArrayFromDType(t,y.sizeFromShape(e));if(o&&t!=="string"){let s=0;r.forEach(a=>{let i=y.sizeFromShape(a.shape);n.set(a.vals,s),s+=i})}else{let s=0;r.forEach(a=>{let i=t==="string"?N.fromUint8ToStringArray(a.vals):a.vals,l=0;for(let u=0;u<a.shape[0];++u){let c=u*e[1]+s;for(let p=0;p<a.shape[1];++p)n[c+p]=i[l++]}s+=a.shape[1]})}return n}var FS=Hn(r=>Math.exp(r)),ck=qn(on,FS),OS={kernelName:on,backendName:"cpu",kernelFunc:ck};var PS=Hn(r=>Math.expm1(r)),TH=qn(ii,PS),MS={kernelName:ii,backendName:"cpu",kernelFunc:TH};var LS=Hn(r=>Math.floor(r)),AH=qn(nn,LS),zS={kernelName:nn,backendName:"cpu",kernelFunc:AH};function pk(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 BS=Xe((r,e)=>r>e?1:0),EH=et(ui,BS,null,"bool"),VS={kernelName:ui,backendName:"cpu",kernelFunc:EH};var GS=Xe((r,e)=>r<e?1:0),DH=et(fi,GS,null,"bool"),WS={kernelName:fi,backendName:"cpu",kernelFunc:DH};function mk(r,e,t){let o=(e-r)/(t-1),n=y.makeZerosTypedArray(t,"float32");n[0]=r;for(let s=1;s<n.length;s++)n[s]=n[s-1]+o;return n}var jS=Hn(r=>Math.log(r)),$H=qn(cn,jS),US={kernelName:cn,backendName:"cpu",kernelFunc:$H};function fk(r,e,t,o){let n=y.getTypedArrayFromDType(o,y.sizeFromShape(t));for(let s=0;s<n.length;++s){let a=s*e,i=r[a];for(let l=0;l<e;++l){let u=r[a+l];u>i&&(i=u)}n[s]=i}return n}var HS=Xe((r,e)=>Math.max(r,e)),RH=et(mn,HS),qS={kernelName:mn,backendName:"cpu",kernelFunc:RH};var KS=Xe((r,e)=>Math.min(r,e)),FH=et(gn,KS),XS={kernelName:gn,backendName:"cpu",kernelFunc:FH};var xg=Xe((r,e)=>r*e),OH=up((r,e,t,o)=>({real:r*t-e*o,imag:r*o+e*t})),sf=et(xn,xg,OH),YS={kernelName:xn,backendName:"cpu",kernelFunc:sf};function ZS(r,e,t){let o=y.createScalarValue(-1,t);return xg([],e,o,r,t)}function PH(r){let{inputs:e,backend:t}=r,{x:o}=e;te(o,"neg");let n=t.data.get(o.dataId).values,[s,a]=ZS(n,o.shape,o.dtype);return t.makeTensorInfo(a,o.dtype,s)}var JS={kernelName:ps,backendName:"cpu",kernelFunc:PH};var QS=Xe((r,e)=>r!==e?1:0),MH=et(yi,QS,null,"bool"),eT={kernelName:yi,backendName:"cpu",kernelFunc:MH};function af(r,e,t,o,n){let s=e.length,a=y.sizeFromShape(e),i=y.computeStrides(e),l=y.computeStrides(n),u=y.getTypedArrayFromDType(t,y.sizeFromShape(n));for(let c=0;c<a;++c){let p=y.indexToLoc(c,s,i),m=new Array(p.length);for(let d=0;d<m.length;d++)m[d]=p[o[d]];let f=y.locToIndex(m,s,l);u[f]=r[c]}return u}function rr(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 tT={kernelName:Pn,backendName:"cpu",kernelFunc:rr};function rT(r,e,t,o){let[n,s]=N.computeOutAndReduceShapes(r,o),a=dr(e,"int32"),i=y.makeZerosTypedArray(y.sizeFromShape(n),a),l=y.sizeFromShape(s);for(let u=0;u<i.length;++u){let c=u*l,p=1;for(let m=0;m<l;++m)p*=t[c+m];i[u]=p}return{outVals:i,outShape:n,outDtype:a}}function LH(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=y.parseAxisParam(s,n.shape),u=N.getAxesPermutation(l,i),c=l,p=n,m=[];u!=null&&(p=rr({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}=rT(p.shape,p.dtype,f,c),x=h;return a&&(x=N.expandShapeToKeepDim(h,l)),m.forEach(b=>t.disposeIntermediateTensorInfo(b)),t.makeTensorInfo(x,g,d)}var oT={kernelName:_i,backendName:"cpu",kernelFunc:LH};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 y.makeZerosTypedArray(0,o);let i=Math.abs(Math.ceil((e-r)/t)),l=y.makeZerosTypedArray(i,o);e<r&&t===1&&(t=-1),l[0]=r;for(let u=1;u<l.length;u++)l[u]=l[u-1]+t;return l}var nT=Hn(r=>1/Math.sqrt(r)),zH=qn(Sn,nT),sT={kernelName:Sn,backendName:"cpu",kernelFunc:zH};function uf(r,e,t,o,n){let s=sr.isSliceContinous(o,e,t),a=y.sizeFromShape(t),i=y.computeStrides(o);if(s){let p=sr.computeFlatOffset(e,i);return n==="string"?r.slice(p,p+a):r.subarray(p,p+a)}let l=n==="string"?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]=sr.parseSliceParams(n,s,a);sr.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 iT={kernelName:gs,backendName:"cpu",kernelFunc:Kn};var aT=Xe((r,e)=>{let t=r-e;return t*t}),BH=et(Rn,aT),lT={kernelName:Rn,backendName:"cpu",kernelFunc:BH};function dk(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 uT=Xe((r,e)=>r-e),VH=up((r,e,t,o)=>({real:r-t,imag:e-o})),cf=et(Fn,uT,VH),cT={kernelName:Fn,backendName:"cpu",kernelFunc:cf};function hk(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 gk(r,e,t,o,n){let s=e[e.length-1],[a,i]=[r.length/s,s],l=y.getTypedArrayFromDType(t,a*o),u=y.getTypedArrayFromDType("int32",a*o);for(let p=0;p<a;p++){let m=p*i,f=r.subarray(m,m+i),d=[];for(let b=0;b<f.length;b++)d.push({value:f[b],index:b});d.sort((b,w)=>w.value-b.value);let h=p*o,g=l.subarray(h,h+o),x=u.subarray(h,h+o);for(let b=0;b<o;b++)g[b]=d[b].value,x[b]=d[b].index}let c=e.slice();return c[c.length-1]=o,[ve(c,t,l),ve(c,"int32",u)]}function xk(r,e,t,o){let n=y.parseAxisParam(e,t)[0],s=[1,t[0],1];for(let d=0;d<n;d++)s[0]*=t[d];s[1]=t[n];for(let d=n+1;d<t.length;d++)s[2]*=t[d];let a={},i=new Int32Array(t[n]),l=new 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 x=0;x<s[0];x++)for(let b=0;b<s[2];b++)g.push(l.get(x,d,b));h=g.join(",")}if(a[h]!==void 0)i[d]=a[h];else{let g=Object.keys(a).length;a[h]=g,i[d]=g,u.push(d)}}let p=s.slice();p[1]=Object.keys(a).length;let m=new lt(p,o);u.forEach((d,h)=>{for(let g=0;g<s[0];g++)for(let x=0;x<s[2];x++)m.set(l.get(g,d,x),g,h,x)});let f=t.slice();return f[n]=p[1],{outputValues:m.values,outputShape:f,indices:i}}var yk="3.3.0";xu("cpu",()=>new Hu,1);var bk=$e(oi,r=>r>=0?r:Math.exp(r)-1),pT={kernelName:oi,backendName:"cpu",kernelFunc:bk};function wk(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{alpha:s}=o;te([n],"leakyRelu");let a=y.sizeFromShape(n.shape),i=t.data.get(n.dataId).values,l=y.getTypedArrayFromDType("float32",a);for(let u=0;u<i.length;u++)l[u]=i[u]<0?s*i[u]:i[u];return t.makeTensorInfo(n.shape,"float32",l)}var mT={kernelName:un,backendName:"cpu",kernelFunc:wk};var GH=Xe((r,e)=>r<0?e*r:r);function kk(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]=GH(o.shape,n.shape,s,a,o.dtype);return t.makeTensorInfo(l,o.dtype,i)}var fT={kernelName:kn,backendName:"cpu",kernelFunc:kk};var _k=$e(_n,r=>Math.max(0,r)),dT={kernelName:_n,backendName:"cpu",kernelFunc:_k};var vk=$e(Cn,r=>Math.min(Math.max(0,r),6)),hT={kernelName:Cn,backendName:"cpu",kernelFunc:vk};function cp(r,e,t,o,n){if(t==="linear")return Er({inputs:{x:e},backend:r});if(t==="relu")return _k({inputs:{x:e},backend:r});if(t==="elu")return bk({inputs:{x:e},backend:r});if(t==="relu6")return vk({inputs:{x:e},backend:r});if(t==="prelu")return kk({inputs:{x:e,alpha:o},backend:r});if(t==="leakyrelu")return wk({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=y.sizeFromShape(n.shape),i=y.inferFromImplicitShape(s,a),l=y.sizeFromShape(i);y.assert(a===l,()=>`The new shape (${i}) has ${l} elements and the old shape (${n.shape}) has ${a} elements. The new shape and old shape must have the same number of elements.`),t.incRef(n.dataId);let u=t.data.get(n.dataId);if(u.complexTensorInfos!=null){let c=u.complexTensorInfos.real,p=u.complexTensorInfos.imag;c.shape=i,p.shape=i}return{dataId:n.dataId,shape:i,dtype:n.dtype}}var gT={kernelName:ds,backendName:"cpu",kernelFunc:Qe};function Ck(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=y.sizeFromShape(d),x=y.sizeFromShape(h),b=g===x||g===1||x===1;y.assert(l>=2&&u>=2&&b,()=>`Error in matMul: the input batch dimensions must either be the same or at least one input batch dimension must be 1. Got input batch dimensions of (${d}) and (${h}).`);let k=(g>x?n.shape.slice(0,-2):s.shape.slice(0,-2)).concat([m,f]);y.assert(c===p,()=>`Error in matMul: inner shapes (${c}) and (${p}) of Tensors with shapes ${n.shape} and ${s.shape} and transposeA=${a} and transposeB=${i} must match.`);let _=a?[g,c,m]:[g,m,c],D=i?[x,f,p]:[x,p,f],T=Qe({inputs:{x:n},backend:t,attrs:{shape:_}}),R=Qe({inputs:{x:s},backend:t,attrs:{shape:D}}),O=a?T.shape[1]:T.shape[2],M=a?T.shape[2]:T.shape[1],G=i?R.shape[1]:R.shape[2],j=Math.max(g,x),U=t.data.get(T.dataId).values,H=t.data.get(R.dataId).values,q=y.computeStrides(T.shape),X=y.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=M*G,fe=ve([j,M,G],T.dtype),de=fe.values,xe=t.blockSize;for(let we=0;we<j;we++)for(let De=0;De<M;De+=xe)for(let Ne=0;Ne<G;Ne+=xe)for(let ze=0;ze<O;ze+=xe){let qe=Math.min(De+xe,M),it=Math.min(Ne+xe,G),Tt=Math.min(ze+xe,O);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,x-1)*ue,Xt=U[Pt+At*Y+mt*re],to=H[mt*J+je*ie+xo];ut+=Xt*to}de[we*ae+(At*G+je)]+=ut}}return t.disposeIntermediateTensorInfo(T),t.disposeIntermediateTensorInfo(R),t.makeTensorInfo(k,fe.dtype,fe.values)}var xT={kernelName:Xo,backendName:"cpu",kernelFunc:Ck};function WH(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=Ck({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=cp(t,m,c,i,p),h.push(m),m=d);for(let x of h)t.disposeIntermediateTensorInfo(x);return m}var yT={kernelName:ws,backendName:"cpu",kernelFunc:WH};var jH=$e(qs,r=>Math.acos(r)),bT={kernelName:qs,backendName:"cpu",kernelFunc:jH};var UH=$e(Ks,r=>Math.acosh(r)),wT={kernelName:Ks,backendName:"cpu",kernelFunc:UH};function HH(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 kT={kernelName:Ho,backendName:"cpu",kernelFunc:HH};function qH(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{axis:s,keepDims:a}=o;te(n,"all");let i=y.parseAxisParam(s,n.shape),l=i,u=N.getAxesPermutation(l,n.shape.length),c=n;u!=null&&(c=rr({inputs:{x:n},backend:t,attrs:{perm:u}}),l=N.getInnerMostAxes(l.length,n.shape.length)),N.assertAxesAreInnerMostDims("all",l,c.shape.length);let[p,m]=N.computeOutAndReduceShapes(c.shape,l),f=y.sizeFromShape(m),d=y.makeZerosTypedArray(y.sizeFromShape(p),c.dtype),h=t.data.get(c.dataId).values;for(let x=0;x<d.length;++x){let b=x*f,w=h[b];for(let k=0;k<f;++k){let _=h[b+k];w=w&&_}d[x]=w}u!=null&&t.disposeIntermediateTensorInfo(c);let g=t.makeTensorInfo(p,c.dtype,d);if(a){let x=N.expandShapeToKeepDim(p,i),b=Qe({inputs:{x:g},backend:t,attrs:{shape:x}});return t.disposeIntermediateTensorInfo(g),b}return g}var _T={kernelName:Ml,backendName:"cpu",kernelFunc:qH};function KH(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{axis:s,keepDims:a}=o;te(n,"any");let i=y.parseAxisParam(s,n.shape),l=i,u=N.getAxesPermutation(l,n.shape.length),c=n;u!=null&&(c=rr({inputs:{x:n},backend:t,attrs:{perm:u}}),l=N.getInnerMostAxes(l.length,n.shape.length)),N.assertAxesAreInnerMostDims("any",l,c.shape.length);let[p,m]=N.computeOutAndReduceShapes(c.shape,l),f=y.sizeFromShape(m),d=y.makeZerosTypedArray(y.sizeFromShape(p),c.dtype),h=t.data.get(c.dataId).values;for(let x=0;x<d.length;++x){let b=x*f,w=h[b];for(let k=0;k<f;++k){let _=h[b+k];w=w||_}d[x]=w}u!=null&&t.disposeIntermediateTensorInfo(c);let g=t.makeTensorInfo(p,c.dtype,d);if(a){let x=N.expandShapeToKeepDim(p,i),b=Qe({inputs:{x:g},backend:t,attrs:{shape:x}});return t.disposeIntermediateTensorInfo(g),b}return g}var vT={kernelName:Ll,backendName:"cpu",kernelFunc:KH};function XH(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{axis:s}=o;te(n,"argMax");let a=y.parseAxisParam(s,n.shape),i=N.getAxesPermutation(a,n.shape.length),l=n,u=[];i!=null&&(l=rr({inputs:{x:n},backend:t,attrs:{perm:i}}),u.push(l),a=N.getInnerMostAxes(a.length,l.shape.length)),a=[a[0]],N.assertAxesAreInnerMostDims("argMax",a,l.shape.length);let[c,p]=N.computeOutAndReduceShapes(l.shape,a),m=y.sizeFromShape(c),f=y.makeZerosTypedArray(m,"int32"),d=y.sizeFromShape(p),h=t.data.get(l.dataId).values;for(let g=0;g<f.length;++g){let x=g*d,b=h[x],w=0;for(let k=0;k<d;++k){let _=h[x+k];_>b&&(b=_,w=k)}f[g]=w}return u.forEach(g=>t.disposeIntermediateTensorInfo(g)),t.makeTensorInfo(c,"int32",f)}var CT={kernelName:qo,backendName:"cpu",kernelFunc:XH};function YH(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{axis:s}=o;te(n,"argMin");let a=y.parseAxisParam(s,n.shape),i=N.getAxesPermutation(a,n.shape.length),l=n,u=[];i!=null&&(l=rr({inputs:{x:n},backend:t,attrs:{perm:i}}),u.push(l),a=N.getInnerMostAxes(a.length,l.shape.length)),a=[a[0]],N.assertAxesAreInnerMostDims("argMin",a,l.shape.length);let[c,p]=N.computeOutAndReduceShapes(l.shape,a),m=y.sizeFromShape(c),f=y.makeZerosTypedArray(m,"int32"),d=y.sizeFromShape(p),h=t.data.get(l.dataId).values;for(let g=0;g<f.length;++g){let x=g*d,b=h[x],w=0;for(let k=0;k<d;++k){let _=h[x+k];_<b&&(b=_,w=k)}f[g]=w}return u.forEach(g=>t.disposeIntermediateTensorInfo(g)),t.makeTensorInfo(c,"int32",f)}var IT={kernelName:ea,backendName:"cpu",kernelFunc:YH};var ZH=$e(Xs,r=>Math.asin(r)),NT={kernelName:Xs,backendName:"cpu",kernelFunc:ZH};var JH=$e(Ys,r=>Math.asinh(r)),ST={kernelName:Ys,backendName:"cpu",kernelFunc:JH};var QH=$e(Zs,r=>Math.atan(r)),TT={kernelName:Zs,backendName:"cpu",kernelFunc:QH};var eq=Xe((r,e)=>Math.atan2(r,e)),tq=et(Qs,eq),AT={kernelName:Qs,backendName:"cpu",kernelFunc:tq};var rq=$e(Js,r=>Math.atanh(r)),ET={kernelName:Js,backendName:"cpu",kernelFunc:rq};function pp(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,x=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 _=k*x,D=k*o[0];for(let T=0;T<n.inChannels;++T)for(let R=0;R<n.outHeight;++R){let O=R*a-m,M=Math.max(0,O),G=Math.min(n.inHeight,c+O),j=_+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=M;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+T];s==="max"&&de>oe?oe=de:s==="avg"&&(Y+=de,re++)}if(isNaN(oe))break}let J=j+U*w+T;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 x=0;x<o.inChannels;++x)for(let b=0;b<o.outHeight;++b){let w=b*i-f,k=w;for(;k<0;)k+=u;let _=Math.min(o.inHeight,p+w);for(let D=0;D<o.outWidth;++D){let T=D*l-d,R=T;for(;R<0;)R+=c;let O=Math.min(o.inWidth,m+T),M=Number.NEGATIVE_INFINITY,G=-1;for(let j=k;j<_;j+=u){let U=j-w;for(let H=R;H<O;H+=c){let q=H-T,X=h.get(g,j,H,x);X>M&&(M=X,n?G=s?((g*o.inHeight+j)*o.inWidth+H)*o.inChannels+x:(j*o.inWidth+H)*o.inChannels+x:G=U*m+q)}}a.set(G,g,b,D,x)}}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,x=n.padInfo.left,b=s==="max"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,w=ve(n.outShape,t),k=w.values,_=n.outShape[1]*n.outShape[2]*n.outShape[3]*n.outShape[4],D=n.outShape[2]*n.outShape[3]*n.outShape[4],T=n.outShape[3]*n.outShape[4],R=n.outShape[4];for(let O=0;O<n.batchSize;++O){let M=O*_,G=O*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=M+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*T;for(let ae=0;ae<n.outWidth;++ae){let fe=ae*l-x,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 DT(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 x=0;x<e.outDepth;++x){let b=x*o-m,w=b;for(;w<0;)w+=a;let k=Math.min(e.inDepth,u+b);for(let _=0;_<e.outHeight;++_){let D=_*n-f,T=D;for(;T<0;)T+=i;let R=Math.min(e.inHeight,c+D);for(let O=0;O<e.outWidth;++O){let M=O*s-d,G=M;for(;G<0;)G+=l;let j=Math.min(e.inWidth,p+M),U=Number.NEGATIVE_INFINITY,H=-1;for(let q=w;q<k;q+=a){let X=q-b;for(let oe=T;oe<R;oe+=i){let Y=oe-D;for(let re=G;re<j;re+=l){let J=re-M,ie=r.get(h,q,oe,re,g);ie>=U&&(U=ie,H=X*c*p+Y*c+J)}}}t.set(H,h,x,_,O,g)}}}return t}function oq(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;y.assert(N.eitherStridesOrDilationsAreOne(a,u),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${u}'`);let c=N.computePool2DInfo(n.shape,s,a,u,i,l),p;if(c.filterWidth===1&&c.filterHeight===1&&y.arraysEqual(c.inShape,c.outShape))p=Er({inputs:{x:n},backend:t});else{let m=t.data.get(n.dataId).values,f=y.computeStrides(n.shape),d=pp(m,n.shape,n.dtype,f,c,"avg");p=t.makeTensorInfo(c.outShape,n.dtype,d.values)}return p}var $T={kernelName:Ko,backendName:"cpu",kernelFunc:oq};function nq(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,y.computeStrides(n.shape),c,"avg");return t.makeTensorInfo(m.shape,"float32",m.values)}var RT={kernelName:ta,backendName:"cpu",kernelFunc:nq};function sq(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,x=c.dilationDepth,b=c.dilationHeight,w=c.dilationWidth,k=c.effectiveFilterDepth,_=c.effectiveFilterHeight,D=c.effectiveFilterWidth,T=k-1-c.padInfo.front,R=D-1-c.padInfo.left,O=_-1-c.padInfo.top,M=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-T,re=X-O,J=oe-R,ie=0;for(let ue=0;ue<k;ue+=x){let ae=(Y+ue)/p;if(!(ae<0||ae>=c.outDepth||Math.floor(ae)!==ae))for(let fe=0;fe<_;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)}}}M.set(ie*G,U,q,X,oe,H)}return t.makeTensorInfo(M.shape,M.dtype,M.values)}var FT={kernelName:Bl,backendName:"cpu",kernelFunc:sq};function iq(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,x=c.effectiveFilterHeight,b=c.effectiveFilterWidth,w=b-1-c.padInfo.left,k=x-1-c.padInfo.top,_=ve(a.shape,"float32"),D=1/(f*d),T=t.data.get(n.dataId).values,R=ve(n.shape,"float32",T);for(let O=0;O<c.batchSize;++O)for(let M=0;M<c.inChannels;++M)for(let G=0;G<c.inHeight;++G)for(let j=0;j<c.inWidth;++j){let U=G-k,H=j-w,q=0;for(let X=0;X<x;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(O,oe,re,M)}}_.set(q*D,O,G,j,M)}return t.makeTensorInfo(_.shape,_.dtype,_.values)}var OT={kernelName:zl,backendName:"cpu",kernelFunc:iq};function aq(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,scale:s,offset:a,mean:i,variance:l}=e;y.assert(i.shape.length===l.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),y.assert(a==null||i.shape.length===a.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),y.assert(s==null||i.shape.length===s.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks."),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,x=f.length,b=m.length,w=p.length,k=0,_=0,D=0,T=0;for(let R=0;R<c.length;++R)h[R]=d[k++]+(c[R]-p[_++])*f[D++]/Math.sqrt(m[T++]+u),k>=g&&(k=0),_>=w&&(_=0),D>=x&&(D=0),T>=b&&(T=0);return t.makeTensorInfo(n.shape,n.dtype,h)}var PT={kernelName:an,backendName:"cpu",kernelFunc:aq};function lq(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{blockShape:s,crops:a}=o;te([n],"batchToSpaceND");let i=s.reduce((x,b)=>x*b),l=N.getReshaped(n.shape,s,i),u=N.getPermuted(l.length,s.length),c=N.getReshapedPermuted(n.shape,s,i),p=N.getSliceBeginCoords(a,s.length),m=N.getSliceSize(c,a,s.length),f=Qe({inputs:{x:n},backend:t,attrs:{shape:l}}),d=rr({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 MT={kernelName:ra,backendName:"cpu",kernelFunc:lq};function uq(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 LT={kernelName:Vl,backendName:"cpu",kernelFunc:uq};var cq=$e(Ro,(r,e)=>{let t=e;return r>t.clipValueMax?t.clipValueMax:r<t.clipValueMin?t.clipValueMin:r}),zT={kernelName:Ro,backendName:"cpu",kernelFunc:cq};var pq=r=>{let{x:e}=r.inputs,t=r.backend,o=new Float32Array(y.sizeFromShape(e.shape)),n=t.data.get(e.dataId),s=n.complexTensorInfos.real,a=n.complexTensorInfos.imag,i=t.data.get(s.dataId).values,l=t.data.get(a.dataId).values;for(let u=0;u<i.length;u++){let c=i[u],p=l[u];o[u]=Math.hypot(c,p)}return t.makeOutput(o,e.shape,"float32")},BT={kernelName:oa,backendName:"cpu",kernelFunc:pq};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 VT={kernelName:Ql,backendName:"cpu",kernelFunc:zi};function pl(r){let{inputs:e,backend:t,attrs:o}=r,{axis:n}=o,s=y.parseAxisParam(n,e[0].shape)[0],a=N.computeOutShape(e.map(h=>h.shape),s);if(y.sizeFromShape(a)===0)return t.makeTensorInfo(a,e[0].dtype,[]);let i=e.filter(h=>y.sizeFromShape(h.shape)>0);if(i.length===1)return Er({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})),x=pl({inputs:h,backend:t,attrs:{axis:s}}),b=pl({inputs:g,backend:t,attrs:{axis:s}}),w=mr({inputs:{real:x,imag:b},backend:t});return h.forEach(k=>t.disposeIntermediateTensorInfo(k)),g.forEach(k=>t.disposeIntermediateTensorInfo(k)),t.disposeIntermediateTensorInfo(x),t.disposeIntermediateTensorInfo(b),w}let u=i.map(h=>{let g=y.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 GT={kernelName:ls,backendName:"cpu",kernelFunc:pl};function Ik(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,x=m.padInfo.left,b=m.padInfo.top,w=m.dataFormat==="channelsLast",k=new lt(m.outShape,n.dtype),_=y.computeStrides(n.shape),D=y.computeStrides(s.shape),T=_[0],R=w?_[1]:_[2],O=w?_[2]:1,M=w?1:_[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*T,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-x;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*O,je=Tt;for(let ut=0;ut<m.inChannels;++ut){let mt=q[At+ut*M];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 WT={kernelName:Zo,backendName:"cpu",kernelFunc:Ik};function mq(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,x=m.dataFormat==="channelsLast",b=new lt(m.filterShape,"float32"),w=m.padInfo.left,k=m.padInfo.top,_=t.data.get(n.dataId).values,D=t.data.get(s.dataId).values,T=new lt(n.shape,n.dtype,_),R=new lt(s.shape,s.dtype,D);for(let O=0;O<h;++O){let M=Math.max(0,Math.ceil((k-O)/f)),G=Math.min(m.outHeight,(m.inHeight+k-O)/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=M;re<G;++re){let J=O+re*f-k;for(let ie=U;ie<H;++ie){let ue=j+ie*d-w;x?oe+=T.get(Y,J,ue,q)*R.get(Y,re,ie,X):oe+=T.get(Y,q,J,ue)*R.get(Y,X,re,ie)}}b.set(oe,O,j,q,X)}}}return t.makeTensorInfo(b.shape,b.dtype,b.values)}var jT={kernelName:Wl,backendName:"cpu",kernelFunc:mq};function fq(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=y.computeStrides(s.shape),m=y.computeStrides(n.shape),f=N.convertConv2DDataFormat(u),d=N.computeConv2DInfo(a,s.shape,i,1,l,c,!1,f),h=new lt(d.inShape,"float32"),g=h.values,x=t.data.get(n.dataId).values,b=t.data.get(s.dataId).values,[w,k,_]=p,{batchSize:D,filterHeight:T,filterWidth:R,inChannels:O,inHeight:M,inWidth:G,outChannels:j,outHeight:U,outWidth:H,strideHeight:q,strideWidth:X}=d;f=d.dataFormat;let oe=T-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<O;++Ne)for(let ze=0;ze<M;++ze){let qe=ze-oe,it=Math.max(0,Math.ceil(qe/q)),Tt=Math.min(U,(T+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 Xt=it;Xt<Tt;++Xt){let to=Xt*q-qe;for(let $r=ut;$r<mt;++$r){let jo=$r*X-je,or=fe*De+de*Xt+xe*$r,yo=w*(T-1-to)+k*(R-1-jo)+_*Ne;for(let Gr=0;Gr<j;++Gr){let br=x[or+we*Gr],ro=b[yo+Gr];Pt+=br*ro}}}let xo=J*De+ie*ze+ue*At+ae*Ne;g[xo]=Pt}}return t.makeTensorInfo(h.shape,h.dtype,h.values)}var UT={kernelName:Jo,backendName:"cpu",kernelFunc:fq};function dq(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,x=g.front,b=g.left,w=g.top,k=new lt(u.outShape,n.dtype),_=t.data.get(n.dataId).values,D=t.data.get(s.dataId).values,T=k.values,R=y.computeStrides(n.shape),O=y.computeStrides(s.shape);for(let M=0;M<u.batchSize;++M){let G=M*R[0],j=M*k.strides[0];for(let U=0;U<u.outDepth;++U){let H=j+U*k.strides[1],q=U*u.strideDepth-x;for(let X=0;X<c;++X){let oe=q+X*f;if(oe<0||oe>=u.inDepth)continue;let Y=X*O[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*O[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*O[2],Tt=xe+qe*u.inChannels,At=it;for(let je=0;je<u.inChannels;++je){let ut=_[Tt+je];for(let mt=0;mt<u.outChannels;++mt)T[De+mt]+=ut*D[At+mt];At+=u.outChannels}}}}}}}}return t.makeTensorInfo(k.shape,k.dtype,k.values)}var HT={kernelName:na,backendName:"cpu",kernelFunc:dq};function hq(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=y.computeStrides(n.shape),c=y.computeStrides(s.shape),p=N.computeConv3DInfo(n.shape,l,a,1,i),m=p.strideDepth,f=p.strideHeight,d=p.strideWidth,h=p.filterDepth,g=p.filterHeight,x=p.filterWidth,b=new lt(p.filterShape,"float32"),w=b.values,[k,_,D,T]=b.strides,R=t.data.get(s.dataId).values,[O,M,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*_+fe;for(let Ne=0;Ne<x;++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*T+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*O;for(let Xt=ue;Xt<ae;++Xt){let $r=(ie+Xt*m-Y)*q+Pt,jo=Xt*M+xo;for(let or=xe;or<we;++or){let Gr=(de+or*f-J)*X+$r,br=or*G+jo;for(let ro=ze;ro<qe;++ro){let Dl=(Ne+ro*d-re)*oe+Gr,Ua=ro*j+br;ut+=U[Dl+Tt]*R[Ua+je]}}}}w[At+je]=ut}}}}}return t.makeTensorInfo(b.shape,b.dtype,b.values)}var qT={kernelName:jl,backendName:"cpu",kernelFunc:hq};function gq(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=y.computeStrides(n.shape),c=y.computeStrides(s.shape),p=N.computeConv3DInfo(l,s.shape,i,1,a),m=new lt(p.inShape,"float32"),f=m.values,[d,h,g,x]=m.strides,b=t.data.get(n.dataId).values,[w,k,_,D]=u,T=t.data.get(s.dataId).values,[R,O,M,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 Xt=0;Xt<re;++Xt){let to=Xt-Ne,$r=Math.max(0,Math.ceil(to/xe)),jo=Math.min(ae,(q+to)/xe),or=0;for(let yo=At;yo<je;++yo){let Gr=yo*fe-Tt;for(let br=Pt;br<xo;++br){let ro=br*de-mt;for(let Eo=$r;Eo<jo;++Eo){let Dl=Eo*xe-to,Ua=w*ze+k*yo+_*br+D*Eo,ns=R*(U-1-Gr)+O*(H-1-ro)+M*(q-1-Dl)+G*qe;for(let Xi=0;Xi<J;++Xi){let em=b[Ua+Xi],xc=T[ns+Xi];or+=em*xc}}}}f[d*ze+h*it+g*ut+x*Xt+qe]=or}}}return t.makeTensorInfo(m.shape,m.dtype,m.values)}var KT={kernelName:Ul,backendName:"cpu",kernelFunc:gq};var xq=$e(Qo,r=>Math.cos(r)),XT={kernelName:Qo,backendName:"cpu",kernelFunc:xq};var yq=$e(ei,r=>Math.cosh(r)),YT={kernelName:ei,backendName:"cpu",kernelFunc:yq};function bq(r){let{inputs:e,backend:t,attrs:o}=r,{image:n,boxes:s,boxInd:a}=e,{cropSize:i,method:l,extrapolationValue:u}=o,[c,p,m,f]=n.shape,d=s.shape[0],[h,g]=i,x=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,_=y.computeStrides(n.shape),D=y.computeStrides(x.shape);for(let T=0;T<d;T++){let R=T*4,O=b[R],M=b[R+1],G=b[R+2],j=b[R+3],U=w[T];if(U>=c)continue;let H=h>1?(G-O)*(p-1)/(h-1):0,q=g>1?(j-M)*(m-1)/(g-1):0;for(let X=0;X<h;X++){let oe=h>1?O*(p-1)+X*H:.5*(O+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]+T*D[0];x.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?M*(m-1)+ie*q:.5*(M+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]+T*D[0];x.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*_[2]+Y*_[1]+U*_[0],De=k[we];we=xe+fe*_[2]+Y*_[1]+U*_[0];let Ne=k[we];we=xe+ae*_[2]+re*_[1]+U*_[0];let ze=k[we];we=xe+fe*_[2]+re*_[1]+U*_[0];let qe=k[we],it=De+(Ne-De)*de,Tt=ze+(qe-ze)*de;we=xe+ie*D[2]+X*D[1]+T*D[0],x.values[we]=it+(Tt-it)*J}}}else for(let Y=0;Y<g;++Y){let re=g>1?M*(m-1)+Y*q:.5*(M+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]+T*D[0];x.values[ae]=u}continue}let J=Math.round(re),ie=Math.round(oe);for(let ue=0;ue<f;ue++){let ae=ue+J*_[2]+ie*_[1]+U*_[0],fe=ue+Y*D[2]+X*D[1]+T*D[0];x.values[fe]=k[ae]}}}}return t.makeTensorInfo(x.shape,x.dtype,x.values)}var ZT={kernelName:ti,backendName:"cpu",kernelFunc:bq};function wq(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=rr({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=dr(u.dtype,"int32"),m=y.makeZerosTypedArray(y.sizeFromShape(u.shape),p),f=t.data.get(u.dataId).values,d=u.shape[u.shape.length-1],h=i?(x,b)=>x+d-b-1:(x,b)=>x+b;for(let x=0;x<f.length;x+=d)for(let b=0;b<d;b++){let w=h(x,b);if(b===0)m[w]=a?0:f[w];else{let k=h(x,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 x=N.getUndoAxesPermutation(l),b=rr({inputs:{x:g},backend:t,attrs:{perm:x}});return t.disposeIntermediateTensorInfo(g),t.disposeIntermediateTensorInfo(u),b}return g}var JT={kernelName:en,backendName:"cpu",kernelFunc:wq};function kq(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=uk(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 QT={kernelName:Hl,backendName:"cpu",kernelFunc:kq};function _q(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{blockSize:s,dataFormat:a}=o;y.assert(a==="NHWC",()=>`Only NHWC dataFormat supported on CPU for depthToSpace. Got ${a}`),y.assert(s>1,()=>`blockSize should be > 1 for depthToSpace, but was: ${s}`);let i=n.shape[0],l=n.shape[1],u=n.shape[2],c=n.shape[3],p=l*s,m=u*s,f=c/(s*s),d=t.data.get(n.dataId).values,h=new Float32Array(i*p*m*f),g=0;for(let x=0;x<i;++x)for(let b=0;b<p;++b){let w=Math.floor(b/s),k=b%s;for(let _=0;_<m;++_){let D=Math.floor(_/s),T=_%s,R=(k*s+T)*f;for(let O=0;O<f;++O){let G=O+R+c*(D+u*(w+l*x));h[g++]=d[G]}}}return t.makeTensorInfo([i,p,m,f],n.dtype,h)}var e1={kernelName:ri,backendName:"cpu",kernelFunc:_q};function Nk(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=y.computeStrides(n.shape),p=y.computeStrides(s.shape),m=l;m==null&&(m=[1,1]),y.assert(N.eitherStridesOrDilationsAreOne(a,m),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${a} and dilations '${m}'`);let f=N.computeConv2DInfo(n.shape,s.shape,a,m,i,u,!0),{filterHeight:d,filterWidth:h,dilationHeight:g,dilationWidth:x,padInfo:b}=f,w=b.left,k=b.top,_=f.outChannels/f.inChannels,D=new lt(f.outShape,n.dtype),T=t.data.get(n.dataId).values,R=t.data.get(s.dataId).values,O=D.values;for(let M=0;M<f.batchSize;++M){let G=M*c[0],j=M*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*x;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=T[xe+Ne];for(let qe=0;qe<_;++qe)O[we+qe]+=ze*R[De+qe];we+=_,De+=_}}}}}}return t.makeTensorInfo(D.shape,D.dtype,D.values)}var t1={kernelName:tn,backendName:"cpu",kernelFunc:Nk};function vq(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"),x=p.padInfo.left,b=p.padInfo.top,w=p.outChannels/p.inChannels,k=t.data.get(n.dataId).values,_=new lt(n.shape,n.dtype,k),D=t.data.get(s.dataId).values,T=new lt(s.shape,s.dtype,D);for(let R=0;R<d;++R){let O=Math.max(0,Math.ceil((b-R)/m)),M=Math.min(p.outHeight,(p.inHeight+b-R)/m);for(let G=0;G<h;++G){let j=Math.max(0,Math.ceil((x-G)/f)),U=Math.min(p.outWidth,(p.inWidth+x-G)/f);for(let 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=O;re<M;++re){let J=R+re*m-b;for(let ie=j;ie<U;++ie){let ue=G+ie*f-x;oe+=_.get(Y,J,ue,q)*T.get(Y,re,ie,H)}}g.set(oe,R,G,q,X)}}}return t.makeTensorInfo(g.shape,g.dtype,g.values)}var r1={kernelName:ql,backendName:"cpu",kernelFunc:vq};function Cq(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=y.computeStrides(n.shape),m=y.computeStrides(s.shape),f=N.computeConv2DInfo(c,s.shape,a,i,l,u,!0),d=new lt(f.inShape,"float32"),h=d.values,[g,x,b]=d.strides,w=t.data.get(n.dataId).values,[k,_,D]=p,T=t.data.get(s.dataId).values,[R,O,M]=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,Xt=k*de+_*ut+D*Pt,to=R*(j-1-mt)+O*(U-1-xo)+M*xe;for(let $r=0;$r<fe;++$r){let jo=xe*fe+$r,or=w[Xt+jo],yo=T[to+$r];je+=or*yo}}}h[g*de+x*we+b*qe+xe]=je}}return t.makeTensorInfo(d.shape,d.dtype,d.values)}var o1={kernelName:Kl,backendName:"cpu",kernelFunc:Cq};function Iq(r){let{inputs:e,backend:t}=r,{x:o}=e,n=y.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 n1={kernelName:Xl,backendName:"cpu",kernelFunc:Iq};var s1={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:x,outWidth:b,padInfo:w,strideHeight:k,strideWidth:_,filterHeight:D,filterWidth:T,dilationHeight:R,dilationWidth:O,outShape:M}=N.computeDilation2DInfo(o.shape,n.shape,s,a,"NHWC",i),G=y.sizeFromShape(M),j=M.length,U=y.getArrayFromDType(o.dtype,G);for(let q=0;q<f;++q)for(let X=0;X<x;++X){let oe=X*k-w.top;for(let Y=0;Y<b;++Y){let re=Y*_-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<T;++de){let xe=re+de*O;if(xe>=0&&xe<h){let we=y.locToIndex([q,fe,xe,J],c,y.computeStrides(o.shape)),De=y.locToIndex([ae,de,J],m,y.computeStrides(n.shape)),Ne=u[we]+p[De];Ne>ie&&(ie=Ne)}}}let ue=y.locToIndex([q,X,Y,J],j,y.computeStrides(M));U[ue]=ie}}}return{dataId:l.write(y.toTypedArray(U,o.dtype),M,o.dtype),shape:M,dtype:o.dtype}}};var i1={kernelName:Oc,backendName:"cpu",kernelFunc:({inputs:r,backend:e,attrs:t})=>{let{x:o,filter:n,dy:s}=r,{strides:a,pad:i,dilations:l}=t,u=e,c=y.toNestedArray(o.shape,u.data.get(o.dataId).values),p=y.toNestedArray(n.shape,u.data.get(n.dataId).values),{batchSize:m,inHeight:f,inWidth:d,inChannels:h,outHeight:g,outWidth:x,padInfo:b,strideHeight:w,strideWidth:k,filterHeight:_,filterWidth:D,dilationHeight:T,dilationWidth:R,outShape:O}=N.computeDilation2DInfo(o.shape,n.shape,a,i,"NHWC",l);y.assert(s.rank===O.length,()=>`Error in ${Oc}, dy must have the same rank as output ${O.length}, but got ${s.rank}`);let M=y.toNestedArray(O,u.data.get(s.dataId).values),G=y.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<x;++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<_;++ue){let ae=q+ue*T;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]+=M[U][H][X][Y]}}}return{dataId:u.write(y.toTypedArray(G,o.dtype),n.shape,n.dtype),shape:n.shape,dtype:n.dtype}}};var a1={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=y.toNestedArray(o.shape,u.data.get(o.dataId).values),p=y.toNestedArray(n.shape,u.data.get(n.dataId).values),{batchSize:m,inHeight:f,inWidth:d,inChannels:h,outHeight:g,outWidth:x,padInfo:b,strideHeight:w,strideWidth:k,filterHeight:_,filterWidth:D,dilationHeight:T,dilationWidth:R,outShape:O}=N.computeDilation2DInfo(o.shape,n.shape,a,i,"NHWC",l);y.assert(s.rank===O.length,()=>`Error in ${Fc}, dy must have the same rank as output ${O.length}, but got ${s.rank}`);let M=y.toNestedArray(O,u.data.get(s.dataId).values),G=y.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<x;++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<_;++ue){let ae=q+ue*T;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]+=M[U][H][X][Y]}}}return{dataId:u.write(y.toTypedArray(G,o.dtype),o.shape,o.dtype),shape:o.shape,dtype:o.dtype}}};function Nq(r){let{inputs:e,backend:t}=r,{dy:o,y:n}=e;te([o,n],"eluGrad");let s=new Float32Array(y.sizeFromShape(n.shape)),a=t.data.get(n.dataId).values,i=t.data.get(o.dataId).values;for(let l=0;l<a.length;++l){let u=a[l];u>=1?s[l]=i[l]:s[l]=i[l]*(u+1)}return t.makeTensorInfo(n.shape,"float32",s)}var l1={kernelName:Yl,backendName:"cpu",kernelFunc:Nq};var Sq=Xe((r,e)=>r===e?1:0),Sk=et(si,Sq,null,"bool"),u1={kernelName:si,backendName:"cpu",kernelFunc:Sk};var Tq=N.ERF_P,Aq=N.ERF_A1,Eq=N.ERF_A2,Dq=N.ERF_A3,$q=N.ERF_A4,Rq=N.ERF_A5,Fq=$e(ni,r=>{let e=Math.sign(r),t=Math.abs(r),o=1/(1+Tq*t);return e*(1-((((Rq*o+$q)*o+Dq)*o+Eq)*o+Aq)*o*Math.exp(-t*t))}),c1={kernelName:ni,backendName:"cpu",kernelFunc:Fq};function mp(r){let{inputs:e,backend:t,attrs:o}=r,{input:n}=e,{dim:s}=o,a=n.shape.length,i=n.shape.slice(),l=s;return s<0&&(y.assert(-(a+1)<=s,()=>`Axis must be in the interval [${-(a+1)}, ${a}]`),l=a+s+1),i.splice(l,0,1),Qe({inputs:{x:n},backend:t,attrs:{shape:i}})}var p1={kernelName:us,backendName:"cpu",kernelFunc:mp};var Oq=Xe((r,e)=>r/e),pf=et(rn,Oq),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=y.sizeFromShape(u),p=y.getTypedArrayFromDType("float32",c),m=y.getTypedArrayFromDType("float32",c);for(let g=0;g<n;g++){let x=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=mr({inputs:{real:x,imag:b},backend:t}),{real:k,imag:_}=Pq(w,e,t),D=N.mergeRealAndImagArrays(k,_);for(let T=0;T<s;T++){let R=N.getComplexWithIndex(D,T);p[g*s+T]=R.real,m[g*s+T]=R.imag}t.disposeIntermediateTensorInfo(x),t.disposeIntermediateTensorInfo(b),t.disposeIntermediateTensorInfo(w)}let f=t.makeTensorInfo(u,"float32",p),d=t.makeTensorInfo(u,"float32",m),h=mr({inputs:{real:f,imag:d},backend:t});return t.disposeIntermediateTensorInfo(f),t.disposeIntermediateTensorInfo(d),h}function Pq(r,e,t){let o=y.sizeFromShape(r.shape),n=t.data.get(r.dataId),s=t.data.get(n.complexTensorInfos.real.dataId).values,a=t.data.get(n.complexTensorInfos.imag.dataId).values;if(Mq(o)){let i=Tk(s,a,o,e,t),l=[r.shape[0],r.shape[1]];if(e){let u=t.makeTensorInfo(l,"float32",i.real),c=t.makeTensorInfo(l,"float32",i.imag),p=t.makeTensorInfo([],"float32",y.createScalarValue(o,"float32")),m=Er({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=Lq(i,o,e);return N.splitRealAndImagArrays(l)}}function Mq(r){return(r&r-1)==0}function Tk(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=mr({inputs:{real:p,imag:m},backend:n}),d=N.complexWithOddIndex(s),h=d.real,g=d.imag,x=[h.length],b=n.makeTensorInfo(x,"float32",h),w=n.makeTensorInfo(x,"float32",g),k=mr({inputs:{real:b,imag:w},backend:n}),_=Tk(l,u,a,o,n),D=_.real,T=_.imag,R=[D.length],O=n.makeTensorInfo(R,"float32",D),M=n.makeTensorInfo(R,"float32",T),G=mr({inputs:{real:O,imag:M},backend:n}),j=Tk(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=mr({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=mr({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(O),n.disposeIntermediateTensorInfo(M),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 Lq(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 zq(r){let{inputs:e,backend:t}=r,{input:o}=e,n=y.sizeFromShape(o.shape),s=o.shape[o.shape.length-1],a=n/s,i=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 m1={kernelName:Zl,backendName:"cpu",kernelFunc:zq};function ff(r){let{backend:e,attrs:t}=r,{shape:o,value:n,dtype:s}=t,a=s||y.inferDtype(n),i=y.getArrayFromDType(a,y.sizeFromShape(o));return Bq(i,n,a),e.makeTensorInfo(o,a,i)}var f1={kernelName:ia,backendName:"cpu",kernelFunc:ff};function Bq(r,e,t){r.fill(e)}var d1={kernelName:ai,backendName:"cpu",kernelFunc:({inputs:r,attrs:e,backend:t})=>{let{image:o}=r,n=t,s=y.getTypedArrayFromDType(o.dtype,y.sizeFromShape(o.shape)),[a,i,l,u]=o.shape,c=n.data.get(o.dataId).values;for(let m=0;m<a;m++){let f=m*l*i*u;for(let d=0;d<i;d++){let h=d*(l*u);for(let g=0;g<l;g++){let x=g*u;for(let b=0;b<u;b++){let k=[a,d,g,b][2],_=Math.round(l-k),D=f+h+x+b,T=c[D];if(_>=0&&_<l){let R=_*u,O=f+h+R+b;T=c[O]}s[D]=T}}}}return{dataId:n.write(s,o.shape,o.dtype),shape:o.shape,dtype:o.dtype}}};var Vq=Xe((r,e)=>Math.floor(r/e)),Gq=et(sn,Vq,null,"int32"),h1={kernelName:sn,backendName:"cpu",kernelFunc:Gq};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=Ik({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=cp(t,h,f,i,d),t.disposeIntermediateTensorInfo(g)}return h}var g1={kernelName:ks,backendName:"cpu",kernelFunc:Wq};function jq(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=Nk({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=cp(t,h,f,i,d),t.disposeIntermediateTensorInfo(g)}return h}var x1={kernelName:_s,backendName:"cpu",kernelFunc:jq};function Uq(r){let{inputs:e,backend:t}=r,{params:o,indices:n}=e,s=y.sizeFromShape(o.shape),a=n.shape,i=a[a.length-1],[l,u,c,p]=N.prepareAndValidate(o,n);if(u===0)return t.makeTensorInfo(l,o.dtype,[]);let m=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=[],x=0;for(let b=0;b<i;b++){let w=f[h*i+b];x+=w*p[b],g.push(w)}if(x<0||x>=s/c)throw new Error(`Invalid indices: ${g} does not index into ${o.shape}`);for(let b=0;b<c;b++)m.values[h*c+b]=d[x*c+b]}return t.makeTensorInfo(l,m.dtype,m.values)}var y1={kernelName:li,backendName:"cpu",kernelFunc:Uq};function Hq(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=y.sizeFromShape(s.shape),c=y.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),x=pk(g,h,d);return t.disposeIntermediateTensorInfo(m),t.disposeIntermediateTensorInfo(f),t.makeTensorInfo(p.outputShape,x.dtype,x.values)}var b1={kernelName:cs,backendName:"cpu",kernelFunc:Hq};var qq=Xe((r,e)=>r>=e?1:0),Kq=et(ln,qq,null,"bool"),w1={kernelName:ln,backendName:"cpu",kernelFunc:Kq};function Xq(r){let{inputs:e,backend:t}=r,{input:o}=e,n=y.sizeFromShape(o.shape),s=o.shape[o.shape.length-1],a=n/s,i=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 k1={kernelName:Jl,backendName:"cpu",kernelFunc:Xq};var Yq=$e(ci,r=>Number.isFinite(r)?1:0,"bool"),_1={kernelName:ci,backendName:"cpu",kernelFunc:Yq};var Zq=$e(pi,r=>Math.abs(r)===Infinity?1:0,"bool"),v1={kernelName:pi,backendName:"cpu",kernelFunc:Zq};var Jq=$e(mi,r=>Number.isNaN(r)?1:0,"bool"),C1={kernelName:mi,backendName:"cpu",kernelFunc:Jq};var Qq=Xe((r,e)=>r<=e?1:0),eK=et(di,Qq,null,"bool"),I1={kernelName:di,backendName:"cpu",kernelFunc:eK};function tK(r){let{backend:e,attrs:t}=r,{start:o,stop:n,num:s}=t,a=mk(o,n,s);return e.makeTensorInfo([a.length],"float32",a)}var N1={kernelName:eu,backendName:"cpu",kernelFunc:tK};var rK=$e(hi,r=>Math.log1p(r)),S1={kernelName:hi,backendName:"cpu",kernelFunc:rK};var oK=Xe((r,e)=>r&&e),nK=et(gi,oK,null,"bool"),T1={kernelName:gi,backendName:"cpu",kernelFunc:nK};var sK=$e(Ja,r=>r?0:1,"bool"),A1={kernelName:Ja,backendName:"cpu",kernelFunc:sK};var iK=Xe((r,e)=>r||e),aK=et(Qa,iK,null,"bool"),E1={kernelName:Qa,backendName:"cpu",kernelFunc:aK};function lK(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=y.sizeFromShape(n.shape),f=new Float32Array(m);function d(h){let g=h%u,x=h-g+Math.max(0,g-s),b=h-g+Math.min(g+s,c),w=0;for(;x<=b;x++){let k=p[x];w+=k*k}return w}for(let h=0;h<m;h++){let g=d(h),x=p[h]*Math.pow(a+i*g,-l);f[h]=x}return t.makeTensorInfo(n.shape,n.dtype,f)}var D1={kernelName:aa,backendName:"cpu",kernelFunc:lK};function uK(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=y.sizeFromShape(a.shape),m=a.shape[3],f=t.data.get(a.dataId).values,d=t.data.get(n.dataId).values,h=t.data.get(s.dataId).values,g=new Float32Array(p),x=p;for(let b=0;b<x;b++){let w=b%m,k=b-w+Math.max(0,w-i),_=b-w+Math.min(m,w+i+1),D=0;for(let T=k;T<_;T++)D+=Math.pow(d[T],2);D=u*D+l;for(let T=k;T<_;T++){let R=-2*u*c*d[T]*h[b]/D;b===T&&(R+=Math.pow(D,-c)),R*=f[b],g[T]+=R}}return t.makeTensorInfo(a.shape,n.dtype,g)}var $1={kernelName:tu,backendName:"cpu",kernelFunc:uK};function Ak(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{reductionIndices:s,keepDims:a}=o,i=t,l=n.shape,u=l.length,c=y.parseAxisParam(s,l),p=c,m=N.getAxesPermutation(p,u),f=i.data.get(n.dataId).values;if(m!=null){let k=new Array(u);for(let _=0;_<k.length;_++)k[_]=l[m[_]];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=y.sizeFromShape(h),x=fk(f,g,d,n.dtype),b=i.write(x,d,n.dtype),w=d;return a&&(w=N.expandShapeToKeepDim(d,c)),{dataId:b,shape:w,dtype:n.dtype}}var R1={kernelName:pn,backendName:"cpu",kernelFunc:Ak};function cK(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;y.assert(N.eitherStridesOrDilationsAreOne(a,u),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${u}'`);let c=N.computePool2DInfo(n.shape,s,a,u,i,l),p;if(c.filterWidth===1&&c.filterHeight===1&&y.arraysEqual(c.inShape,c.outShape))p=Er({inputs:{x:n},backend:t});else{let m=t.data.get(n.dataId).values,f=y.computeStrides(n.shape),d=pp(m,n.shape,n.dtype,f,c,"max");p=t.makeTensorInfo(c.outShape,n.dtype,d.values)}return p}var F1={kernelName:fn,backendName:"cpu",kernelFunc:cK};function pK(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,y.computeStrides(n.shape),c,"max");return t.makeTensorInfo(m.shape,"float32",m.values)}var O1={kernelName:la,backendName:"cpu",kernelFunc:pK};function mK(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=DT(p,c),f=c.strideDepth,d=c.strideHeight,h=c.strideWidth,g=c.dilationDepth,x=c.dilationHeight,b=c.dilationWidth,w=c.effectiveFilterDepth,k=c.effectiveFilterHeight,_=c.effectiveFilterWidth,D=w-1-c.padInfo.front,T=_-1-c.padInfo.left,R=k-1-c.padInfo.top,O=ve(s.shape,"float32"),M=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-T,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+=x){let ae=(oe+ue)/d;if(!(ae<0||ae>=c.outHeight||Math.floor(ae)!==ae))for(let fe=0;fe<_;fe+=b){let de=(Y+fe)/h;if(de<0||de>=c.outWidth||Math.floor(de)!==de)continue;let xe=w*k*_-1-m.get(G,ie,ae,de,j),we=J*k*_+ue*_+fe,De=xe===we?1:0;if(De===0)continue;re+=M.get(G,ie,ae,de,j)*De}}}O.set(re,G,U,H,q,j)}return t.makeTensorInfo(O.shape,O.dtype,O.values)}var P1={kernelName:ou,backendName:"cpu",kernelFunc:mK};function fK(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,x=m.dilationHeight,b=m.dilationWidth,w=m.effectiveFilterHeight,k=m.effectiveFilterWidth,_=k-1-m.padInfo.left,D=w-1-m.padInfo.top,T=ve(i.shape,"float32"),R=t.data.get(n.dataId).values,O=ve(n.shape,"float32",R);for(let M=0;M<m.batchSize;++M)for(let G=0;G<m.inChannels;++G)for(let j=0;j<m.inHeight;++j)for(let U=0;U<m.inWidth;++U){let H=j-D,q=U-_,X=0;for(let oe=0;oe<w;oe+=x){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(M,Y,J,G),ue=oe*k+re,ae=ie===ue?1:0;if(ae===0)continue;X+=O.get(M,Y,J,G)*ae}}T.set(X,M,j,U,G)}return t.makeTensorInfo(T.shape,T.dtype,T.values)}var M1={kernelName:ru,backendName:"cpu",kernelFunc:fK};function L1(r,e,t,o,n){let s=y.computeStrides(e),a=pp(r,e,t,s,n,"max"),i=bg(r,e,t,n,!0,o);return[a.values,i.values]}var z1={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]=L1(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=Er({inputs:{x:n},backend:t});let l=i.shape.length,u=y.parseAxisParam(s,i.shape),c=N.getAxesPermutation(u,l),p=u,m=i;c!=null&&(m=rr({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=lp(t,f,h),x=y.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 _=k*x,D=0;for(let T=0;T<x;++T)D+=w[_+T];b[k]=D}if(a){let k=N.expandShapeToKeepDim(g.shape,u),_=g;g=Qe({inputs:{x:g},backend:t,attrs:{shape:k}}),t.disposeIntermediateTensorInfo(_)}return t.disposeIntermediateTensorInfo(i),c!=null&&t.disposeIntermediateTensorInfo(m),g}var B1={kernelName:Dn,backendName:"cpu",kernelFunc:qu};function dK(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{axis:s,keepDims:a}=o,i=y.parseAxisParam(s,n.shape),u=N.computeOutAndReduceShapes(n.shape,i)[1],c=y.sizeFromShape(u),p=[],m=t.makeTensorInfo([],"float32",new Float32Array([c]));p.push(m);let f=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 V1={kernelName:dn,backendName:"cpu",kernelFunc:dK};function hK(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{axis:s,keepDims:a}=o;te(n,"min");let i=y.parseAxisParam(s,n.shape),l=i,u=N.getAxesPermutation(l,n.shape.length),c=n;u!=null&&(c=rr({inputs:{x:n},backend:t,attrs:{perm:u}}),l=N.getInnerMostAxes(l.length,n.shape.length)),N.assertAxesAreInnerMostDims("min",l,c.shape.length);let[p,m]=N.computeOutAndReduceShapes(c.shape,l),f=y.sizeFromShape(m),d=y.makeZerosTypedArray(y.sizeFromShape(p),c.dtype),h=t.data.get(c.dataId).values;for(let x=0;x<d.length;++x){let b=x*f,w=h[b];for(let k=0;k<f;++k){let _=h[b+k];_<w&&(w=_)}d[x]=w}u!=null&&t.disposeIntermediateTensorInfo(c);let g=t.makeTensorInfo(p,c.dtype,d);if(a){let x=N.expandShapeToKeepDim(p,i),b=Qe({inputs:{x:g},backend:t,attrs:{shape:x}});return t.disposeIntermediateTensorInfo(g),b}return g}var G1={kernelName:hn,backendName:"cpu",kernelFunc:hK};function gK(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=y.computeStrides(n.shape),d=y.sizeFromShape(i),h=i.length,g=y.computeStrides(i),x=y.getTypedArrayFromDType(n.dtype,d);for(let w=0;w<d;w++){let k=y.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,T)=>D-l[T]);let _=y.locToIndex(k,m,f);x[w]=p[_]}return{dataId:t.write(x,i,n.dtype),shape:i,dtype:n.dtype}}var W1={kernelName:ua,backendName:"cpu",kernelFunc:gK};var xK=Xe((r,e)=>{let t=r%e;return r<0&&e<0||r>=0&&e>=0?t:(t+e)%e}),yK=et(xi,xK),j1={kernelName:xi,backendName:"cpu",kernelFunc:yK};var H1=Ac(Hw());function Ek(r){let{inputs:e,backend:t,attrs:o}=r,{logits:n}=e,{dim:s}=o,a=n.shape.length,i=s;if(i===-1&&(i=a-1),i!==a-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${a} and dim was ${i}`);let l=y.parseAxisParam([i],n.shape),u=Ak({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=ck({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 U1={kernelName:$n,backendName:"cpu",kernelFunc:Ek};function bK(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:Ek({inputs:{logits:n},backend:t,attrs:{dim:-1}}),u=l.shape[0],c=l.shape[1],p=t.data.get(l.dataId).values,m=[u,s],f=y.makeZerosTypedArray(y.sizeFromShape(m),"int32");for(let d=0;d<u;++d){let h=d*c,g=new Float32Array(c-1);g[0]=p[h];for(let w=1;w<g.length;++w)g[w]=g[w-1]+p[h+w];let x=H1.alea(a.toString()),b=d*s;for(let w=0;w<s;++w){let k=x();f[b+w]=g.length;for(let _=0;_<g.length;_++)if(k<g[_]){f[b+w]=_;break}}}return i||t.disposeIntermediateTensorInfo(l),t.makeTensorInfo(m,"int32",f)}var q1={kernelName:su,backendName:"cpu",kernelFunc:bK};var wK=Ar.nonMaxSuppressionV3Impl;function kK(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}=wK(u,c,a,i,l);return t.makeTensorInfo([p.length],"int32",new Int32Array(p))}var K1={kernelName:bi,backendName:"cpu",kernelFunc:kK};var _K=Ar.nonMaxSuppressionV4Impl;function vK(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}=_K(c,p,a,i,l,u);return[t.makeTensorInfo([m.length],"int32",new Int32Array(m)),t.makeTensorInfo([],"int32",new Int32Array([f]))]}var X1={kernelName:wi,backendName:"cpu",kernelFunc:vK};var CK=Ar.nonMaxSuppressionV5Impl;function IK(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:x}=CK(c,p,m,f,d,h);return[t.makeTensorInfo([g.length],"int32",new Int32Array(g)),t.makeTensorInfo([x.length],"float32",new Float32Array(x))]}var Y1={kernelName:ki,backendName:"cpu",kernelFunc:IK};function NK(r){let{inputs:e,backend:t,attrs:o}=r,{indices:n}=e,{depth:s,onValue:a,offValue:i}=o;te(n,"oneHot");let l=y.sizeFromShape(n.shape),u=new Float32Array(l*s);u.fill(i);let c=t.data.get(n.dataId).values;for(let p=0;p<l;++p)c[p]>=0&&c[p]<s&&(u[p*s+c[p]]=a);return t.makeTensorInfo([...n.shape,s],"int32",u)}var Z1={kernelName:yn,backendName:"cpu",kernelFunc:NK};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=mr({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 J1={kernelName:bs,backendName:"cpu",kernelFunc:df};function Q1(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=Q1({inputs:{x:n},backend:t}),a=zi({inputs:{input:o},backend:t}),i=df({inputs:{x:a},backend:t}),l=mr({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 eA={kernelName:ms,backendName:"cpu",kernelFunc:Q1};function Dk(r){let{inputs:e,backend:t,attrs:o}=r,{axis:n}=o;if(e.length===1)return mp({inputs:{input:e[0]},backend:t,attrs:{dim:n}});let s=e[0].shape,a=e[0].dtype;e.forEach(c=>{y.assertShapesMatch(s,c.shape,"All tensors passed to stack must have matching shapes"),y.assert(a===c.dtype,()=>"All tensors passed to stack must have matching dtypes")});let i=[],l=e.map(c=>{let p=mp({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 tA={kernelName:fs,backendName:"cpu",kernelFunc:Dk};function SK(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=y.sizeFromShape(n.shape),p=n.shape.length,m=y.computeStrides(n.shape),f=y.sizeFromShape(i),d=i.length,h=y.computeStrides(i),g=y.getTypedArrayFromDType(n.dtype,f);a!==0&&g.fill(a);for(let b=0;b<c;b++){let k=y.indexToLoc(b,p,m).map((D,T)=>D+l[T]),_=y.locToIndex(k,d,h);g[_]=u[b]}return{dataId:t.write(g,i,n.dtype),shape:i,dtype:n.dtype}}var _g={kernelName:bn,backendName:"cpu",kernelFunc:SK};var TK=Xe((r,e)=>Math.pow(r,e)),AK=et(wn,TK),rA={kernelName:wn,backendName:"cpu",kernelFunc:AK};function EK(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 oA={kernelName:ca,backendName:"cpu",kernelFunc:EK};var DK=$e(vi,r=>1/r),nA={kernelName:vi,backendName:"cpu",kernelFunc:DK};function $K(r){let{inputs:e,backend:t,attrs:o}=r,{images:n}=e,{alignCorners:s,halfPixelCenters:a,size:i}=o;te(n,"resizeBilinear");let l=y.computeStrides(n.shape),[u,c]=i,[p,m,f,d]=n.shape,h=t.data.get(n.dataId).values,g=new Float32Array(y.sizeFromShape([p,u,c,d])),x=[s&&u>1?m-1:m,s&&c>1?f-1:f],b=[s&&u>1?u-1:u,s&&c>1?c-1:c],w=0,k=x[0]/b[0],_=x[1]/b[1];for(let D=0;D<p;D++)for(let T=0;T<u;T++){let R;a?R=k*(T+.5)-.5:R=k*T;let O=Math.max(0,Math.floor(R)),M=R-O,G=Math.min(m-1,Math.ceil(R)),j=D*l[0]+O*l[1],U=D*l[0]+G*l[1];for(let H=0;H<c;H++){let q;a?q=_*(H+.5)-.5:q=_*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)*M;g[w++]=ze}}}return t.makeTensorInfo([p,u,c,d],"float32",g)}var sA={kernelName:vn,backendName:"cpu",kernelFunc:$K};function RK(r){let{inputs:e,backend:t,attrs:o}=r,{images:n,dy:s}=e,{alignCorners:a}=o;te([s,n],"resizeBilinearGrad");let i=y.computeStrides(n.shape),[l,u,c,p]=n.shape,[,m,f]=s.shape,d=new Float32Array(l*u*c*p),h=[a&&m>1?u-1:u,a&&f>1?c-1:c],g=[a&&m>1?m-1:m,a&&f>1?f-1:f],x=h[0]/g[0],b=h[1]/g[1],w=t.data.get(s.dataId).values,k=0;for(let _=0;_<l;_++){let D=_*i[0];for(let T=0;T<m;T++){let R=T*x,O=Math.floor(R),M=Math.min(Math.ceil(R),u-1),G=D+O*i[1],j=D+M*i[1],U=R-O,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 iA={kernelName:lu,backendName:"cpu",kernelFunc:RK};function FK(r){let{inputs:e,backend:t,attrs:o}=r,{images:n}=e,{alignCorners:s,halfPixelCenters:a,size:i}=o;te(n,"resizeNearestNeighbor");let l=y.computeStrides(n.shape),[u,c]=i,[p,m,f,d]=n.shape,h=t.data.get(n.dataId).values,g=new Float32Array(p*u*c*d),x=[s&&u>1?m-1:m,s&&c>1?f-1:f],b=[s&&u>1?u-1:u,s&&c>1?c-1:c],w=x[0]/b[0],k=x[1]/b[1],_=0;for(let D=0;D<p;D++){let T=D*l[0];for(let R=0;R<u;R++){let O=a?w*(R+.5):w*R,M=Math.min(m-1,s?Math.round(O):Math.floor(O));a&&(M=Math.max(0,M));let G=T+M*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[_++]=oe}}}}return t.makeTensorInfo([p,u,c,d],n.dtype,g)}var aA={kernelName:pa,backendName:"cpu",kernelFunc:FK};function OK(r){let{inputs:e,backend:t,attrs:o}=r,{images:n,dy:s}=e,{alignCorners:a}=o;te([s,n],"resizeNearestNeighborGrad");let i=y.computeStrides(n.shape),l=y.computeStrides(s.shape),[u,c,p,m]=n.shape,[,f,d]=s.shape,h=new Float32Array(u*c*p*m),g=t.data.get(s.dataId).values,x=[a&&f>1?c-1:c,a&&d>1?p-1:p],b=[a&&f>1?f-1:f,a&&d>1?d-1:d],w=x[0]/b[0],k=x[1]/b[1],_=1/w,D=1/k,T=Math.ceil(_)*2+2,R=Math.ceil(D)*2+2;for(let O=0;O<u;O++){let M=O*i[0];for(let G=0;G<c;G++){let j=M+G*i[1],U=Math.floor(G*_),H=Math.floor(U-T/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<T;ie++){let ue=ie+H;if(ue<0||ue>=f)continue;let ae=M+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 lA={kernelName:au,backendName:"cpu",kernelFunc:OK};function PK(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{dims:s}=o;te(n,"reverse");let a=n.shape.length,i=y.parseAxisParam(s,n.shape);if(a===0)return Er({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 uA={kernelName:In,backendName:"cpu",kernelFunc:PK};var cA={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=y.getTypedArrayFromDType(o.dtype,y.sizeFromShape(o.shape)),[u,c,p,m]=o.shape,[f,d]=N.getImageCenter(a,c,p),h=255,g=Math.sin(n),x=Math.cos(n),b=i.data.get(o.dataId).values;for(let k=0;k<u;k++){let _=k*p*c*m;for(let D=0;D<c;D++){let T=D*(p*m);for(let R=0;R<p;R++){let O=R*m;for(let M=0;M<m;M++){let G=[u,D,R,M],j=G[2],U=G[1],H=(j-f)*x-(U-d)*g,q=(j-f)*g+(U-d)*x;H=Math.round(H+f),q=Math.round(q+d);let X=s;if(typeof s!="number"&&(M===3?X=h:X=s[M]),H>=0&&H<p&&q>=0&&q<c){let Y=q*(p*m),re=H*m,J=_+Y+re+M;X=b[J]}let oe=_+T+O+M;l[oe]=X}}}}return{dataId:i.write(l,o.shape,o.dtype),shape:o.shape,dtype:o.dtype}}};var MK=$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}),pA={kernelName:Nn,backendName:"cpu",kernelFunc:MK};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 x=0;x<a;x++){let b=p[d*a+x];h.push(b),g+=b*i[x]}if(g<0||g>=o/n)throw new Error(`Invalid indices: ${h} does not index into ${t}`);for(let x=0;x<n;x++)u?f.values[g*n+x]+=m[d*n+x]:f.values[g*n+x]=e.rank===0?m[0]:m[d*n+x]}return f}function LK(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 mA={kernelName:Ci,backendName:"cpu",kernelFunc:LK};function zK(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=dr(n.dtype,s.dtype),p=y.makeZerosTypedArray(y.sizeFromShape(n.shape),c),m=0,f=a===0||a>1||n.shape.length===1?1:y.sizeFromShape(n.shape.slice(1));for(let d=0;d<i.length;d++)for(let h=0;h<f;h++)i[d]===1?p[m++]=l[d]:p[m++]=u[d];return t.makeTensorInfo(n.shape,c,p)}var fA={kernelName:hs,backendName:"cpu",kernelFunc:zK};var BK=N.SELU_SCALEALPHA,VK=N.SELU_SCALE,GK=$e(Ii,r=>r>=0?VK*r:BK*(Math.exp(r)-1)),dA={kernelName:Ii,backendName:"cpu",kernelFunc:GK};var WK=$e(An,r=>1/(1+Math.exp(-r))),hA={kernelName:An,backendName:"cpu",kernelFunc:WK};var jK=$e(Si,r=>r<0?-1:r>0?1:0),gA={kernelName:Si,backendName:"cpu",kernelFunc:jK};var UK=$e(Tn,r=>Math.sin(r)),xA={kernelName:Tn,backendName:"cpu",kernelFunc:UK};var HK=$e(Ni,r=>Math.sinh(r)),yA={kernelName:Ni,backendName:"cpu",kernelFunc:HK};var qK=11920928955078125e-23,bA=Math.log(qK)+2,KK=$e(Ti,r=>{let e=r>-bA,t=r<bA,o=Math.exp(r),n;return t?n=o:e?n=r:n=Math.log(1+o),n}),wA={kernelName:Ti,backendName:"cpu",kernelFunc:KK};function XK(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{blockShape:s,paddings:a}=o;te([n],"spaceToBatchND");let i=y.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=rr({inputs:{x:h},backend:t,attrs:{perm:p}}),_=Qe({inputs:{x:b},backend:t,attrs:{shape:m}});return t.disposeIntermediateTensorInfo(u),t.disposeIntermediateTensorInfo(h),t.disposeIntermediateTensorInfo(b),_}var kA={kernelName:ma,backendName:"cpu",kernelFunc:XK};function YK(r){let{inputs:e,backend:t,attrs:o}=r,{sparseIndices:n,sparseValues:s,defaultValue:a}=e,{outputShape:i}=o,{sliceRank:l,numUpdates:u,sliceSize:c,strides:p,outputSize:m}=N.calculateShapes(s,n,i),f=!1,d=t.bufferSync(n),h=t.bufferSync(s),g=t.data.get(a.dataId).values[0],x=vg(d,h,i,m,c,u,l,p,g,f);return t.makeTensorInfo(i,x.dtype,x.values)}var _A={kernelName:uu,backendName:"cpu",kernelFunc:YK};function ZK(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{numOrSizeSplits:s,axis:a}=o,i=y.parseAxisParam(a,n.shape)[0],l=N.prepareSplitSize(n,s,i),u=new Array(n.shape.length).fill(0),c=n.shape.slice();return l.map(p=>{let m=[...c];m[i]=p;let f=Kn({inputs:{x:n},backend:t,attrs:{begin:u,size:m}});return u[i]+=p,f})}var vA={kernelName:xs,backendName:"cpu",kernelFunc:ZK};var JK=$e(En,r=>Math.sqrt(r)),CA={kernelName:En,backendName:"cpu",kernelFunc:JK};var IA={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 QK=$e(Oo,(r,e)=>{let t=e;return isNaN(r)?NaN:r>0?1:t.alpha}),NA={kernelName:Oo,backendName:"cpu",kernelFunc:QK};function e6(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:x,outShape:b}=sr.sliceInfo(n.shape,s,a,i,l,u,c,p,m),w=Qe({inputs:{x:n},backend:t,attrs:{shape:x}}),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),T=dk(b,D,h,d);k=t.makeTensorInfo(T.shape,T.dtype,T.values)}let _=Qe({inputs:{x:k},backend:t,attrs:{shape:b}});return t.disposeIntermediateTensorInfo(w),t.disposeIntermediateTensorInfo(k),_}var SA={kernelName:Ai,backendName:"cpu",kernelFunc:e6};var t6=$e(Ei,r=>Math.tan(r)),TA={kernelName:Ei,backendName:"cpu",kernelFunc:t6};var r6=$e(On,r=>Math.tanh(r)),AA={kernelName:On,backendName:"cpu",kernelFunc:r6};function o6(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{reps:s}=o;te(n,"tile");let a=hk(t.bufferSync(n),s);return t.makeTensorInfo(a.shape,a.dtype,a.values)}var EA={kernelName:ko,backendName:"cpu",kernelFunc:o6};function n6(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]=gk(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 DA={kernelName:Di,backendName:"cpu",kernelFunc:n6};function a6(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],x=y.computeStrides(n.shape),b=x[0],w=x[1],k=x[2],_=y.getTypedArrayFromDType(n.dtype,y.sizeFromShape(g));_.fill(l);let D=o.data.get(n.dataId).values,T=o.data.get(s.dataId).values;for(let O=0;O<c;++O){let M=s.shape[0]===1?T:T.subarray(O*8,O*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=M[6]*j+M[7]*G+1;if(q===0)continue;let X=(M[0]*j+M[1]*G+M[2])/q,oe=(M[3]*j+M[4]*G+M[5])/q,Y=$A(X,m,i),re=$A(oe,p,i);switch(a){case"nearest":H=s6(D,p,m,b,w,k,O,re,Y,U,l);break;case"bilinear":H=i6(D,p,m,b,w,k,O,re,Y,U,l);break;default:throw new Error(`Error in Transform: Expect 'nearest' or 'bilinear', but got ${a}`)}let J=O*b+G*w+j*k+U;_[J]=H}return o.makeTensorInfo(g,n.dtype,_)}return{dataId:o.write(_,g,n.dtype),shape:n.shape,dtype:n.dtype}}var RA={kernelName:cu,backendName:"cpu",kernelFunc:a6};function $A(r,e,t){switch(t){case"reflect":return l6(r,e);case"wrap":return u6(r,e);case"nearest":return p6(r,e);case"constant":default:return c6(r,e)}}function l6(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 y.clamp(0,t,e-1)}function u6(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 y.clamp(0,t,e-1)}function c6(r,e){return r}function p6(r,e){return y.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 s6(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 i6(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 m6(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}=xk(a,n,s.shape,s.dtype);return[o.makeTensorInfo(l,s.dtype,i),o.makeTensorInfo([u.length],"int32",u)]}var FA={kernelName:pu,backendName:"cpu",kernelFunc:m6};function f6(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 OA={kernelName:ys,backendName:"cpu",kernelFunc:f6};function d6(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=mp({inputs:{input:m},backend:t,attrs:{dim:d+1}});m=h,c.push(h)}for(let d=0;d<a;++d){let h=y.createScalarValue(d,"int32"),g=t.makeTensorInfo([],"int32",h),x=Sk({inputs:{a:g,b:m},backend:t}),b=Un({inputs:{x},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(x),c.push(b),c.push(w),c.push(k)}let f=Dk({inputs:u,backend:t,attrs:{axis:0}});return c.forEach(d=>t.disposeIntermediateTensorInfo(d)),f}var PA={kernelName:da,backendName:"cpu",kernelFunc:d6};var h6=[yT,IS,bT,wT,DS,kT,_T,vT,CT,IT,NT,ST,TT,AT,ET,$T,RT,FT,OT,xT,PT,MT,LT,AS,RS,zT,NS,BT,GT,jT,UT,WT,qT,KT,HT,XT,YT,ZT,JT,QT,e1,t1,r1,o1,n1,s1,a1,i1,mf,pT,l1,u1,c1,OS,p1,MS,m1,f1,d1,zS,h1,g1,x1,y1,b1,VS,w1,SS,k1,VT,_1,v1,C1,mT,WS,I1,N1,US,S1,T1,A1,E1,D1,$1,qS,F1,O1,P1,M1,z1,R1,V1,G1,XS,W1,j1,q1,YS,JS,K1,X1,Y1,eT,Z1,eA,tA,_g,rA,fT,oT,oA,TS,nA,dT,hT,gT,sA,iA,aA,lA,uA,cA,pA,sT,mA,fA,dA,hA,gA,xA,yA,iT,U1,wA,kA,_A,vA,CA,IA,lT,NA,SA,cT,B1,TA,AA,EA,DA,tT,RA,FA,OA,PA,J1];for(let r of h6)el(r);var zA={};Ke(zA,{assertNotComplex:()=>Rs,bindCanvasToFramebuffer:()=>I6,bindColorTextureToFramebuffer:()=>yf,bindTextureToProgramUniformSampler:()=>Hk,bindTextureUnit:()=>GA,bindVertexBufferToProgramAttribute:()=>Cg,callAndCheck:()=>Ie,canBeRepresented:()=>Fk,createFragmentShader:()=>Pk,createFramebuffer:()=>Wk,createProgram:()=>Mk,createStaticIndexBuffer:()=>Bk,createStaticVertexBuffer:()=>zk,createTexture:()=>Vk,createVertexShader:()=>Ok,getBatchDim:()=>Oa,getExtensionOrThrow:()=>fp,getFramebufferErrorMessage:()=>WA,getMaxTexturesInShader:()=>Xk,getNumChannels:()=>v6,getProgramUniformLocation:()=>Uk,getProgramUniformLocationOrThrow:()=>jk,getRowsCols:()=>Pa,getShapeAs3D:()=>bf,getTextureShapeFromLogicalShape:()=>qk,getWebGLDisjointQueryTimerVersion:()=>Yk,getWebGLErrorMessage:()=>BA,getWebGLMaxTextureSize:()=>Kk,hasExtension:()=>Io,isCapableOfRenderingToFloatTexture:()=>Jk,isDownloadFloatTextureEnabled:()=>Qk,isReshapeFree:()=>dl,isWebGLFenceEnabled:()=>e_,isWebGLVersionEnabled:()=>Ag,linkProgram:()=>Lk,resetMaxTextureSize:()=>N6,resetMaxTexturesInShader:()=>S6,unbindColorTextureFromFramebuffer:()=>Ig,unbindTextureUnit:()=>C6,validateFramebuffer:()=>dp,validateProgram:()=>xf,validateTextureSize:()=>Gk});var Ku={},$k={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};function Rk(r,e){Ku[r]=e}function Vo(r){if(!(r in Ku)){let t=g6(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 x6(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 g6(r){if(r!==1&&r!==2)throw new Error("Cannot get WebGL rendering context, WebGL is disabled.");let e=x6(r);return e.addEventListener("webglcontextlost",t=>{t.preventDefault(),delete Ku[r]},!1),r===1?e.getContext("webgl",$k)||e.getContext("experimental-webgl",$k):e.getContext("webgl2",$k)}var ml;(function(r){r[r.DENSE=0]="DENSE",r[r.SHARED_BATCH=1]="SHARED_BATCH"})(ml||(ml={}));var Dr;(function(r){r[r.RENDER=0]="RENDER",r[r.UPLOAD=1]="UPLOAD",r[r.PIXELS=2]="PIXELS",r[r.DOWNLOAD=3]="DOWNLOAD"})(Dr||(Dr={}));var _r;(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"})(_r||(_r={}));function Xu(r,e){return[e,r]}function MA(r,e){return r*e}function fl(r){let e=y.sizeFromShape(r),t=Math.ceil(e/4);return y.sizeToSquarishShape(t)}function Bi(r,e){return[Math.max(1,Math.ceil(e/2)),Math.max(1,Math.ceil(r/2))]}function LA(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")&&y6(r),t}function y6(r){let e=r.getError();if(e!==r.NO_ERROR)throw new Error("WebGL Error: "+BA(r,e))}var b6=596e-10,w6=65504;function Fk(r){return!!(W().getBool("WEBGL_RENDER_FLOAT32_ENABLED")||r===0||b6<Math.abs(r)&&Math.abs(r)<w6)}function BA(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 fp(r,e){return Fa(r,()=>r.getExtension(e),'Extension "'+e+'" not supported on this browser.')}function Ok(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 Pk(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 k6(e,r.getShaderInfoLog(t)),new Error("Failed to compile fragment shader.");return t}var _6=/ERROR: [0-9]+:([0-9]+):/g;function k6(r,e){let t=_6.exec(e);if(t==null){console.log(`Couldn't parse line number in error: ${e}`),console.log(r);return}let o=+t[1],n=r.split(`
|
|
`),s=n.length.toString().length+2,a=n.map((p,m)=>y.rightPad((m+1).toString(),s)+p),i=0;for(let p=0;p<a.length;p++)i=Math.max(a[p].length,i);let l=a.slice(0,o-1),u=a.slice(o-1,o),c=a.slice(o);console.log(l.join(`
|
|
`)),console.log(e.split(`
|
|
`)[0]),console.log(`%c ${y.rightPad(u[0],i)}`,"border:1px solid red; background-color:#e3d2d2; color:#a61717"),console.log(c.join(`
|
|
`))}function Mk(r){return Fa(r,()=>r.createProgram(),"Unable to create WebGLProgram.")}function Lk(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 zk(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 Bk(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 v6(){return W().getNumber("WEBGL_VERSION")===2?1:4}function Vk(r){return Fa(r,()=>r.createTexture(),"Unable to create WebGLTexture.")}function Gk(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 Wk(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 GA(r,e,t){VA(r,t),Ie(r,()=>r.activeTexture(r.TEXTURE0+t)),Ie(r,()=>r.bindTexture(r.TEXTURE_2D,e))}function C6(r,e){VA(r,e),Ie(r,()=>r.activeTexture(r.TEXTURE0+e)),Ie(r,()=>r.bindTexture(r.TEXTURE_2D,null))}function jk(r,e,t){return Fa(r,()=>r.getUniformLocation(e,t),'uniform "'+t+'" not present in program.')}function Uk(r,e,t){return r.getUniformLocation(e,t)}function Hk(r,e,t,o){Ie(r,()=>GA(r,e,o)),Ie(r,()=>r.uniform1i(t,o))}function I6(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 dp(r){let e=r.checkFramebufferStatus(r.FRAMEBUFFER);if(e!==r.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+WA(r,e))}function WA(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 VA(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 y.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 qk(r,e=!1){let t=W().getNumber("WEBGL_MAX_TEXTURE_SIZE");e&&(t=t*2,r=r.map((n,s)=>s>=r.length-2?y.nearestLargerEven(r[s]):r[s]),r.length===1&&(r=[2,r[0]])),r.length!==2&&(r=y.squeezeShape(r).newShape);let o=y.sizeFromShape(r);if(r.length<=1&&o<=t)return[1,o];if(r.length===2&&r[0]<=t&&r[1]<=t)return r;if(r.length===3&&r[0]*r[1]<=t&&r[2]<=t)return[r[0]*r[1],r[2]];if(r.length===3&&r[0]<=t&&r[1]*r[2]<=t)return[r[0],r[1]*r[2]];if(r.length===4&&r[0]*r[1]*r[2]<=t&&r[3]<=t)return[r[0]*r[1]*r[2],r[3]];if(r.length===4&&r[0]<=t&&r[1]*r[2]*r[3]<=t)return[r[0],r[1]*r[2]*r[3]];if(e){let n=Oa(r),s=2,a=2;return r.length&&([s,a]=Pa(r)),o=n*(s/2)*(a/2),y.sizeToSquarishShape(o).map(i=>i*2)}return y.sizeToSquarishShape(o)}function Ng(r){return r%2==0}function dl(r,e){if(r=r.slice(-2),e=e.slice(-2),y.arraysEqual(r,e)||!r.length||!e.length||r[0]===0||r[1]===0||e[0]===0||e[1]===0)return!0;if(r.length!==e.length){let t=r.slice(-1)[0],o=e.slice(-1)[0];if(t===o||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 Kk(r){if(Sg==null){let e=Vo(r);Sg=e.getParameter(e.MAX_TEXTURE_SIZE)}return Sg}function N6(){Sg=null}function S6(){Tg=null}function Xk(r){if(Tg==null){let e=Vo(r);Tg=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,Tg)}function Yk(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 Jk(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 Zk(e)}function Qk(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 Zk(e);let o="EXT_color_buffer_half_float";if(Io(e,o)){let n=e.getExtension(o);return T6(e,n)}return!1}return Zk(e)}function Zk(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 T6(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 e_(r){return r!==2?!1:Vo(r).fenceSync!=null}function Rs(r,e){Array.isArray(r)||(r=[r]),r.forEach(t=>{t!=null&&y.assert(t.dtype!=="complex64",()=>`${e} does not support complex64 tensors in the WebGL backend.`)})}var Pe=W();Pe.registerFlag("HAS_WEBGL",()=>Pe.getNumber("WEBGL_VERSION")>0);Pe.registerFlag("WEBGL_VERSION",()=>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",()=>Kk(Pe.getNumber("WEBGL_VERSION")));Pe.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",()=>Xk(Pe.getNumber("WEBGL_VERSION")));Pe.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",()=>{let r=Pe.getNumber("WEBGL_VERSION");return r===0?0:Yk(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",()=>Jk(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",()=>Qk(Pe.getNumber("WEBGL_VERSION")));Pe.registerFlag("WEBGL_FENCE_API_ENABLED",()=>e_(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=y.computeStrides(e);return o.map((n,s)=>{let a=`int ${r[s]} = ${t} / ${n}`,i=s===o.length-1?`int ${r[s+1]} = ${t} - ${r[s]} * ${n}`:`index -= ${r[s]} * ${n}`;return`${a}; ${i};`}).join("")}function hp(r){let e=y.computeStrides(r).map(t=>t.toString());return`
|
|
int getFlatIndex(ivec3 coords) {
|
|
return coords.x * ${e[0]} + coords.y * ${e[1]} + coords.z;
|
|
}
|
|
`}var 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 t_=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 r_=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 o_=class{constructor(e){this.variableNames=["A"],this.outTexUsage=Dr.DOWNLOAD;let t=Rt();this.outputShape=e,this.userCode=`
|
|
${Eg}
|
|
|
|
void main() {
|
|
float x = getAAtOutCoords();
|
|
${t.output} = encode_float(x);
|
|
}
|
|
`}};var n_=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=Dr.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 s_=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=`
|
|
${hp(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 i_=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=`
|
|
${hp(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 jA={};Ke(jA,{bindVertexProgramAttributeStreams:()=>h_,createBufferFromOutputTexture:()=>y_,createFloat16MatrixTexture:()=>p_,createFloat16PackedMatrixTexture:()=>d_,createFloat32MatrixTexture:()=>c_,createIndexBuffer:()=>u_,createPackedMatrixTexture:()=>f_,createUnsignedBytesMatrixTexture:()=>m_,createVertexBuffer:()=>l_,createVertexShader:()=>a_,downloadByteEncodedFloatMatrixFromOutputTexture:()=>w_,downloadFloat32MatrixFromBuffer:()=>b_,downloadMatrixFromPackedOutputTexture:()=>__,downloadPackedMatrixFromBuffer:()=>k_,getInternalFormatForFloat16MatrixTexture:()=>$g,getInternalFormatForFloat16PackedMatrixTexture:()=>Og,getInternalFormatForFloat32MatrixTexture:()=>Dg,getInternalFormatForPackedMatrixTexture:()=>Fg,getInternalFormatForUnsignedBytesMatrixTexture:()=>Rg,uploadDenseMatrixToTexture:()=>g_,uploadPixelDataToTexture:()=>x_});function a_(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 Ok(r,t)}function l_(r){let e=new Float32Array([-1,1,0,0,1,-1,-1,0,0,0,1,1,0,1,1,1,-1,0,1,0]);return zk(r,e)}function u_(r){let e=new Uint16Array([0,1,2,2,1,3]);return Bk(r,e)}function wf(r,e,t,o,n,s){Gk(e,t);let a=Vk(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 c_(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 p_(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 m_(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 f_(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 d_(r,e,t,o){let[n,s]=Bi(e,t);return wf(r,n,s,Og(o),r.RGBA,o.textureTypeHalfFloat)}function h_(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 g_(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 x_(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 y_(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 b_(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 w_(r,e,t,o){let[n,s]=Xu(e,t),a=4,i=new Uint8Array(MA(e*t,a));return Ie(r,()=>r.readPixels(0,0,n,s,o.downloadTextureFormat,r.UNSIGNED_BYTE,i)),new Float32Array(i.buffer)}function k_(r,e,t,o,n,s,a,i){let l=r,u=new Float32Array(LA(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 __(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,Rk(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=fp(this.gl,s),Io(this.gl,a))this.textureHalfFloatExtension=fp(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=fp(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=l_(this.gl),this.indexBuffer=u_(this.gl),this.framebuffer=Wk(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(),c_(this.gl,e,t,this.textureConfig)}createFloat16MatrixTexture(e,t){return this.throwIfDisposed(),p_(this.gl,e,t,this.textureConfig)}createUnsignedBytesMatrixTexture(e,t){return this.throwIfDisposed(),m_(this.gl,e,t,this.textureConfig)}uploadPixelDataToTexture(e,t){this.throwIfDisposed(),x_(this.gl,e,t)}uploadDenseMatrixToTexture(e,t,o,n){this.throwIfDisposed(),g_(this.gl,e,t,o,n,this.textureConfig)}createFloat16PackedMatrixTexture(e,t){return this.throwIfDisposed(),d_(this.gl,e,t,this.textureConfig)}createPackedMatrixTexture(e,t){return this.throwIfDisposed(),f_(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,()=>w_(this.gl,t,o,this.textureConfig))}downloadPackedMatrixFromBuffer(e,t,o,n,s,a){return k_(this.gl,e,t,o,n,s,a,this.textureConfig)}downloadFloat32MatrixFromBuffer(e,t){return b_(this.gl,e,t)}createBufferFromTexture(e,t,o){this.bindTextureToFrameBuffer(e);let n=y_(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,()=>__(this.gl,t,o))}createProgram(e){this.throwIfDisposed();let t=this.gl,o=Pk(t,e),n=a_(t),s=Mk(t);return Ie(t,()=>t.attachShader(s,n)),Ie(t,()=>t.attachShader(s,o)),Lk(t,s),this.debug&&xf(t,s),this.vertexAttrsAreBound||(this.setProgram(s),this.vertexAttrsAreBound=h_(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?jk(this.gl,e,t):Uk(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(),Hk(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),dp(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=fp(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 y.repeatedTry(()=>this.disposed||this.isQueryAvailable(e,W().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))),this.getQueryTime(e,W().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))}getQueryTime(e,t){if(t===0)return null;if(t===2){let 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=A6(this.itemsToPoll.map(t=>t.isDoneFn));for(let t=0;t<=e;++t){let{resolveFn:o}=this.itemsToPoll[t];o()}this.itemsToPoll=this.itemsToPoll.slice(e+1)}addItemToPoll(e,t){this.itemsToPoll.push({isDoneFn:e,resolveFn:t}),!(this.itemsToPoll.length>1)&&y.repeatedTry(()=>(this.pollItems(),this.itemsToPoll.length===0))}bindTextureToFrameBuffer(e){this.throwIfDisposed(),yf(this.gl,e,this.framebuffer),this.debug&&dp(this.gl)}unbindTextureToFrameBuffer(){this.outputTexture!=null?(yf(this.gl,this.outputTexture,this.framebuffer),this.debug&&dp(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&&dp(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 A6(r){let e=0;for(;e<r.length&&r[e]();++e);return e-1}var{getBroadcastDims:UA}=N;function HA(r,e,t,o){let n=[];r.forEach(d=>{let h=y.sizeFromShape(d.shapeInfo.logicalShape);d.shapeInfo.isUniform?n.push(`uniform float ${d.name}${h>1?`[${h}]`:""};`):(n.push(`uniform sampler2D ${d.name};`),n.push(`uniform int offset${d.name};`))});let s=n.join(`
|
|
`),a=r.map(d=>E6(d,e,o)).join(`
|
|
`),i=e.texShape,l=Rt(),u=R6(l),c,p,m=P6(l);return e.isPacked?(c=D6(e.logicalShape,i),p=O6(l)):(c=$6(e.logicalShape,i),p=F6(l)),o&&(m+=M6),[m,u,p,s,c,a,t].join(`
|
|
`)}function gp(r){let e=r.shapeInfo.logicalShape;switch(e.length){case 0:return L6(r);case 1:return z6(r);case 2:return B6(r);case 3:return V6(r);case 4:return G6(r);case 5:return W6(r);case 6:return j6(r);default:throw new Error(`${e.length}-D input sampling is not yet supported`)}}function qA(r){switch(r.shapeInfo.logicalShape.length){case 0:return U6(r);case 1:return H6(r);case 2:return q6(r);case 3:return K6(r);default:return X6(r)}}function E6(r,e,t=!1){let o="";t?o+=qA(r):o+=gp(r);let n=r.shapeInfo.logicalShape,s=e.logicalShape;return n.length<=s.length&&(t?o+=Y6(r,e):o+=Z6(r,e)),o}function D6(r,e){switch(r.length){case 0:return KA();case 1:return J6(r,e);case 2:return t5(r,e);case 3:return Q6(r,e);default:return e5(r,e)}}function $6(r,e){switch(r.length){case 0:return KA();case 1:return r5(r,e);case 2:return a5(r,e);case 3:return o5(r,e);case 4:return n5(r,e);case 5:return s5(r,e);case 6:return i5(r,e);default:throw new Error(`${r.length}-D output sampling is not yet supported`)}}function R6(r){return`
|
|
float sampleTexture(sampler2D textureSampler, vec2 uv) {
|
|
return ${r.texture2D}(textureSampler, uv).r;
|
|
}
|
|
`}function F6(r){return`
|
|
void setOutput(float val) {
|
|
${r.output} = vec4(val, 0, 0, 0);
|
|
}
|
|
`}function O6(r){return`
|
|
void setOutput(vec4 val) {
|
|
${r.output} = val;
|
|
}
|
|
`}function P6(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);
|
|
}
|
|
|
|
${l5}
|
|
${u5}
|
|
${c5}
|
|
`}var l5=`
|
|
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);
|
|
}
|
|
`,u5=`
|
|
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);
|
|
}
|
|
`,c5=`
|
|
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);
|
|
}
|
|
`,M6=`
|
|
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 KA(){return`
|
|
int getOutputCoords() {
|
|
return 0;
|
|
}
|
|
`}function J6(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 r5(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 Q6(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 o5(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 e5(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 n5(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 s5(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 i5(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 t5(r,e){let t=[Math.ceil(e[0]/2),Math.ceil(e[1]/2)];if(y.arraysEqual(r,e))return`
|
|
ivec2 getOutputCoords() {
|
|
return 2 * ivec2(resultUV.yx * vec2(${t[0]}, ${t[1]}));
|
|
}
|
|
`;let o=Math.ceil(r[1]/2);return`
|
|
ivec2 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(${t[0]}, ${t[1]}));
|
|
|
|
int index = resTexRC.x * ${t[1]} + resTexRC.y;
|
|
int r = 2 * (index / ${o});
|
|
int c = imod(index, ${o}) * 2;
|
|
|
|
return ivec2(r, c);
|
|
}
|
|
`}function a5(r,e){return y.arraysEqual(r,e)?`
|
|
ivec2 getOutputCoords() {
|
|
return ivec2(resultUV.yx * vec2(${e[0]}, ${e[1]}));
|
|
}
|
|
`:r[1]===1?`
|
|
ivec2 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(${e[0]}, ${e[1]}));
|
|
int index = resTexRC.x * ${e[1]} + resTexRC.y;
|
|
return ivec2(index, 0);
|
|
}
|
|
`:r[0]===1?`
|
|
ivec2 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(${e[0]}, ${e[1]}));
|
|
int index = resTexRC.x * ${e[1]} + resTexRC.y;
|
|
return ivec2(0, index);
|
|
}
|
|
`:`
|
|
ivec2 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(${e[0]}, ${e[1]}));
|
|
int index = resTexRC.x * ${e[1]} + resTexRC.y;
|
|
int r = index / ${r[1]};
|
|
int c = index - r * ${r[1]};
|
|
return ivec2(r, c);
|
|
}
|
|
`}function Yu(r){return`offset${r}`}function U6(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 L6(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 H6(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 z6(r){let e=r.name,t="get"+e.charAt(0).toUpperCase()+e.slice(1);if(r.shapeInfo.isUniform)return`
|
|
float ${t}(int index) {
|
|
${xp(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 q6(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&&y.arraysEqual(e,n))return`
|
|
vec4 ${o}(int row, int col) {
|
|
vec2 uv = (vec2(col, row) + halfCR) / vec2(${a}.0, ${s}.0);
|
|
|
|
return ${i.texture2D}(${t}, uv);
|
|
}
|
|
`;let l=[Math.ceil(n[0]/2),Math.ceil(n[1]/2)],u=Math.ceil(e[1]/2);return`
|
|
vec4 ${o}(int row, int col) {
|
|
vec2 uv = packedUVfrom2D(${u}, ${l[0]}, ${l[1]}, row, col);
|
|
return ${i.texture2D}(${t}, uv);
|
|
}
|
|
`}function B6(r){let e=r.shapeInfo.logicalShape,t=r.name,o="get"+t.charAt(0).toUpperCase()+t.slice(1),n=r.shapeInfo.texShape;if(n!=null&&y.arraysEqual(e,n)){let p=n[0],m=n[1];return`
|
|
float ${o}(int row, int col) {
|
|
vec2 uv = (vec2(col, row) + halfCR) / vec2(${m}.0, ${p}.0);
|
|
return sampleTexture(${t}, uv);
|
|
}
|
|
`}let{newShape:s,keptDims:a}=y.squeezeShape(e),i=s;if(i.length<e.length){let p=yp(r,i),m=["row","col"];return`
|
|
${gp(p)}
|
|
float ${o}(int row, int col) {
|
|
return ${o}(${bp(m,a)});
|
|
}
|
|
`}if(r.shapeInfo.isUniform)return`
|
|
float ${o}(int row, int col) {
|
|
int index = round(dot(vec2(row, col), vec2(${e[1]}, 1)));
|
|
${xp(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 K6(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=yp(r,p),d=["b","row","col"];return`
|
|
${qA(f)}
|
|
vec4 ${o}(int b, int row, int col) {
|
|
return ${o}(${bp(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 V6(r){let e=r.shapeInfo.logicalShape,t=r.name,o="get"+t.charAt(0).toUpperCase()+t.slice(1),n=e[1]*e[2],s=e[2],{newShape:a,keptDims:i}=y.squeezeShape(e),l=a;if(l.length<e.length){let d=yp(r,l),h=["row","col","depth"];return`
|
|
${gp(d)}
|
|
float ${o}(int row, int col, int depth) {
|
|
return ${o}(${bp(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)));
|
|
${xp(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 X6(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 G6(r){let e=r.shapeInfo.logicalShape,t=r.name,o="get"+t.charAt(0).toUpperCase()+t.slice(1),n=e[3],s=e[2]*n,a=e[1]*s,{newShape:i,keptDims:l}=y.squeezeShape(e);if(i.length<e.length){let d=yp(r,i),h=["row","col","depth","depth2"];return`
|
|
${gp(d)}
|
|
float ${o}(int row, int col, int depth, int depth2) {
|
|
return ${o}(${bp(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)));
|
|
${xp(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 W6(r){let e=r.shapeInfo.logicalShape,t=r.name,o="get"+t.charAt(0).toUpperCase()+t.slice(1),n=e[4],s=e[3]*n,a=e[2]*s,i=e[1]*a,{newShape:l,keptDims:u}=y.squeezeShape(e);if(l.length<e.length){let h=yp(r,l),g=["row","col","depth","depth2","depth3"];return`
|
|
${gp(h)}
|
|
float ${o}(int row, int col, int depth, int depth2, int depth3) {
|
|
return ${o}(${bp(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;
|
|
${xp(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 j6(r){let e=r.shapeInfo.logicalShape,t=r.name,o="get"+t.charAt(0).toUpperCase()+t.slice(1),{newShape:n,keptDims:s}=y.squeezeShape(e);if(n.length<e.length){let g=yp(r,n),x=["row","col","depth","depth2","depth3","depth4"];return`
|
|
${gp(g)}
|
|
float ${o}(int row, int col, int depth,
|
|
int depth2, int depth3, int depth4) {
|
|
return ${o}(${bp(x,s)});
|
|
}
|
|
`}let a=e[5],i=e[4]*a,l=e[3]*i,u=e[2]*l,c=e[1]*u;if(r.shapeInfo.isUniform)return`
|
|
float ${o}(int row, int col, int depth,
|
|
int depth2, int depth3, int depth4) {
|
|
int index = round(dot(
|
|
vec4(row, col, depth, depth2),
|
|
vec4(${c}, ${u}, ${l}, ${i})) +
|
|
dot(
|
|
vec2(depth3, depth4),
|
|
vec2(${a}, 1)));
|
|
${xp(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 xp(r){let e=r.name,t=y.sizeFromShape(r.shapeInfo.logicalShape);return t<2?`return ${e};`:`
|
|
for (int i = 0; i < ${t}; i++) {
|
|
if (i == index) {
|
|
return ${e}[i];
|
|
}
|
|
}
|
|
`}function Y6(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=UA(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=y.sizeFromShape(r.shapeInfo.logicalShape)===1,x=y.sizeFromShape(e.logicalShape)===1;if(s===1&&!h&&!x)f=`
|
|
return vec4(outputValue.xy, outputValue.xy);
|
|
`;else if(h&&!x)a===1?f=`
|
|
return vec4(outputValue.x, outputValue.x, 0., 0.);
|
|
`:f=`
|
|
return vec4(outputValue.x);
|
|
`;else if(i.length){let b=s-2,w=s-1;i.indexOf(b)>-1&&i.indexOf(w)>-1?f="return vec4(outputValue.x);":i.indexOf(b)>-1?f="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":i.indexOf(w)>-1&&(f="return vec4(outputValue.xx, outputValue.zz);")}return`
|
|
vec4 ${n}() {
|
|
${l} coords = getOutputCoords();
|
|
${c}
|
|
vec4 outputValue = get${o}(${m});
|
|
${f}
|
|
}
|
|
`}function Z6(r,e){let t=r.name,o=t.charAt(0).toUpperCase()+t.slice(1),n="get"+o+"AtOutCoords",s=e.texShape,a=r.shapeInfo.texShape,i=r.shapeInfo.logicalShape.length,l=e.logicalShape.length;if(!r.shapeInfo.isUniform&&i===l&&r.shapeInfo.flatOffset==null&&y.arraysEqual(a,s))return`
|
|
float ${n}() {
|
|
return sampleTexture(${t}, resultUV);
|
|
}
|
|
`;let u=Le(l),c=UA(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 yp(r,e){let t=JSON.parse(JSON.stringify(r));return t.shapeInfo.logicalShape=e,t}function bp(r,e){return e.map(t=>r[t]).join(", ")}function XA(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=HA(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 YA(r,e){if(r.length!==e.length)throw Error(`Binary was compiled with ${r.length} inputs, but was executed with ${e.length} inputs`);r.forEach((t,o)=>{let n=t.logicalShape,s=e[o],a=s.shape;if(!y.arraysEqual(n,a))throw Error(`Binary was compiled with different shapes than the current args. Shapes ${n} and ${a} must match`);if(t.isUniform&&s.isUniform)return;let i=t.texShape,l=s.isUniform?null:s.texData.texShape;if(!y.arraysEqual(i,l))throw Error(`Binary was compiled with different texture shapes than the current args. Shape ${i} and ${l} must match`)})}function ZA(r,e,t,o,n){YA(e.inShapeInfos,t),YA([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(y.sizeFromShape(i.shape)<2)r.gl.uniform1f(c,i.uniformValues[0]);else{let m=i.uniformValues;m instanceof Float32Array||(m=new Float32Array(m)),r.gl.uniform1fv(c,m)}return}i.texData.slice!=null&&p!=null&&r.gl.uniform1i(p,i.texData.slice.flatOffset),r.setInputMatrixTexture(i.texData.texture,c,l)}}),n!=null&&n(r,e.webGLProgram),r.executeProgram()}function JA(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:QA,bincountImpl:Mg,bincountReduceImpl:eE,ceilImpl:tE,concatImpl:rE,expImpl:oE,expm1Impl:nE,floorImpl:sE,gatherV2Impl:iE,greaterImpl:aE,lessImpl:lE,linSpaceImpl:uE,logImpl:cE,maxImpl:pE,maximumImpl:mE,minimumImpl:fE,multiplyImpl:dE,negImpl:hE,prodImpl:gE,rangeImpl:xE,rsqrtImpl:yE,simpleAbsImpl:Lg,sliceImpl:bE,stridedSliceImpl:wE,subImpl:kE,tileImpl:_E,topKImpl:vE,transposeImpl:wp,uniqueImpl:CE}=yg;function v_(r,e){return["x","y","z","w","u","v"].slice(0,e).map(t=>`${r}.${t}`)}function Wt(r,e){return e===1?[r]:v_(r,e)}function IE(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 C_=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=p5(t,e,o),a=m5(t,e[e.length-1],e[e.length-2],o),i=f5(e,o);this.userCode=`
|
|
void main() {
|
|
${n} rc = getOutputCoords();
|
|
|
|
if(${s}) {
|
|
setOutput(vec4(0));
|
|
} else {
|
|
${a}
|
|
|
|
setOutput(vec4(${i}));
|
|
}
|
|
}
|
|
`}}};function d5(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 p5(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 m5(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 f5(r,e){let t=r.length,o=d5(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=`
|
|
${h5(t)}
|
|
${hp(e)}
|
|
|
|
void main() {
|
|
ivec3 rc = getOutputCoords();
|
|
|
|
vec4 result = vec4(0.);
|
|
|
|
ivec3 thisRC;
|
|
int rows = ${e[1]};
|
|
int cols = ${e[2]};
|
|
|
|
${o}
|
|
|
|
setOutput(result);
|
|
}
|
|
`}};function h5(r){return`
|
|
ivec3 inputCoordsFromReshapedOutCoords(int index) {
|
|
${Fs(["r","c","d"],r)}
|
|
return ivec3(r, c, d);
|
|
}
|
|
`}var I_=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=SE(t,o),s=TE(e,n,o);s in this.freeTextures||(this.freeTextures[s]=[]),s in this.usedTextures||(this.usedTextures[s]=[]);let a=NE(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===_r.PACKED_2X2_FLOAT32?i=this.gpgpu.createPackedMatrixTexture(e[0],e[1]):n===_r.PACKED_2X2_FLOAT16?i=this.gpgpu.createFloat16PackedMatrixTexture(e[0],e[1]):n===_r.UNPACKED_FLOAT32?i=this.gpgpu.createFloat32MatrixTexture(e[0],e[1]):n===_r.UNPACKED_FLOAT16?i=this.gpgpu.createFloat16MatrixTexture(e[0],e[1]):n===_r.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=SE(o,n),a=TE(t,s,n);a in this.freeTextures||(this.freeTextures[a]=[]);let i=NE(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 g5(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 NE(r,e,t,o,n){let s=x5(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=g5(t,s);return a*i}function x5(r,e){switch(r){case _r.PACKED_2X2_FLOAT32:return Fg(e);case _r.PACKED_2X2_FLOAT16:return Og(e);case _r.UNPACKED_FLOAT32:return Dg(e);case _r.UNPACKED_FLOAT16:return $g(e);case _r.PACKED_4X1_UNSIGNED_BYTE:return Rg(e);default:throw new Error(`Unknown physical texture type ${r}`)}}function y5(r){return W().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?r?_r.PACKED_2X2_FLOAT32:_r.UNPACKED_FLOAT32:r?_r.PACKED_2X2_FLOAT16:_r.UNPACKED_FLOAT16}function SE(r,e){if(r===Dr.UPLOAD)return _r.PACKED_2X2_FLOAT32;if(r===Dr.RENDER||r==null)return y5(e);if(r===Dr.DOWNLOAD||r===Dr.PIXELS)return _r.PACKED_4X1_UNSIGNED_BYTE;throw new Error(`Unknown logical texture type ${r}`)}function TE(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);
|
|
}
|
|
`}},gr="if (isnan(x)) return x;",AE="return x;",N_="return abs(x);";var EE="return (x >= 0.0) ? x : (exp(x) - 1.0);",DE=gr+`
|
|
return (x < 0.0) ? 0.0 : x;
|
|
`,$E=gr+`
|
|
return (x < 0.0) ? 0.0 : min(6.0, x);
|
|
`,_f="return x;";var RE="return x;",FE=`
|
|
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;
|
|
`,OE=`
|
|
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;
|
|
`,PE=`
|
|
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 S_=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=IE(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 b5=Ar.whereImpl,w5=1e-7,k5=1e-4,zg={};function _5(r){return r in zg||(zg[r]={}),zg[r]}var v5=128,C5=600;function I5(){return W().global.screen==null?1024:W().global.screen.height*W().global.screen.width*window.devicePixelRatio*C5/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=_5(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 I_(this.gpgpu),this.numMBBeforeWarning=I5(),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:Dr.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:Dr.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=y.now());let p;if(n==="complex64"){let m=this.readSync(s.real.dataId),f=this.readSync(s.imag.dataId);p=N.mergeRealAndImagArrays(m,f)}else p=this.getValuesFromTexture(e);return u&&(this.downloadWaitMs+=y.now()-c),this.convertAndCacheOnCPU(e,p)}async read(e){if(this.pendingRead.has(e)){let d=this.pendingRead.get(e);return new Promise(h=>d.push(h))}let t=this.texData.get(e),{values:o,shape:n,slice:s,dtype:a,complexTensorInfos:i,isPacked:l}=t;if(s!=null){let d;l?d=new 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=y.sizeFromShape(n);p=this.gpgpu.downloadFloat32MatrixFromBuffer(u,d)}c!=null&&this.disposeIntermediateTensorInfo(c);let m=this.convertAndCacheOnCPU(e,p),f=this.pendingRead.get(e);return this.pendingRead.delete(e),f.forEach(d=>d(m)),this.pendingDisposal.has(e)&&(this.pendingDisposal.delete(e),this.disposeData(e)&&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=>y.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(!Fk(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=y.sizeFromShape(t);if(W().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")){let m=this.decode(e),f=this.texData.get(m.dataId),d=this.gpgpu.downloadMatrixFromPackedTexture(f.texture,...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 n_(i):new o_(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=y.flatten(this.activeTimers.map(l=>l.query)).filter(l=>l!=null),a=y.flatten(this.activeTimers.map(l=>l.name)).filter(l=>l!=null);this.activeTimers=t,n&&(this.programTimersStack=null);let i={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:null,wallMs:null};if(W().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0){let l=await Promise.all(s);i.kernelMs=y.sum(l),i.getExtraProfileInfo=()=>l.map((u,c)=>({name:a[c],ms:u})).map(u=>`${u.name}: ${u.ms}`).join(", ")}else i.kernelMs={error:"WebGL query timers are not supported in this environment."};return this.uploadWaitMs=0,this.downloadWaitMs=0,i}memory(){return{unreliable:!1,numBytesInGPU:this.numBytesInGPU,numBytesInGPUAllocated:this.textureManager.numBytesAllocated,numBytesInGPUFree:this.textureManager.numBytesFree}}startTimer(){return W().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?this.gpgpu.beginQuery():{startMs:y.now(),endMs:null}}endTimer(e){return W().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?(this.gpgpu.endQuery(),e):(e.endMs=y.now(),e)}async getQueryTime(e){if(W().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0)return this.gpgpu.waitForQueryAndGetTime(e);let t=e;return t.endMs-t.startMs}disposeData(e,t=!1){if(this.pendingDisposal.has(e))return!1;if(!this.texData.has(e))return!0;if(t?this.texData.get(e).refCount=0:this.texData.get(e).refCount--,!t&&this.texData.get(e).refCount>0)return!1;if(this.pendingRead.has(e))return this.pendingDisposal.add(e),this.pendingDeletes++,!1;this.releaseGPUData(e);let{complexTensorInfos: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=v5){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&&y.sizeFromShape(n.shape)<t)}getGPGPUContext(){return this.gpgpu}where(e){N.warn("tf.where() in webgl locks the UI thread. Call tf.whereAsync() instead");let t=e.dataSync();return b5(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,N_,e.dtype);let t=new ao(e.shape,N_),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&&y.isString(o[0])){let s=o.map(a=>y.encodeString(a));n=this.write(s,e,t)}else n=this.write(o,e,t);return this.texData.get(n).usage=null,{dataId:n,shape:e,dtype:t}}makeOutput(e,t,o){let{dataId:n}=this.makeTensorInfo(e,t,o);return Mo().makeTensorFromDataId(n,e,t,this)}unpackTensor(e){let t=new S_(e.shape);return this.runWebGLProgram(t,[e],e.dtype)}packTensor(e){let t=new C_(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 r_(a):i=new t_(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(x=>x*2)}if(e.outTexUsage!=null&&(i.usage=e.outTexUsage),y.sizeFromShape(a.shape)===0)return i.values=y.getTypedArrayFromDType(a.dtype,0),a;let l=[],u=t.map(g=>{if(g.dtype==="complex64")throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");let x=this.texData.get(g.dataId);if(x.texture==null){if(!e.packedInputs&&y.sizeFromShape(g.shape)<=W().getNumber("WEBGL_SIZE_UPLOAD_UNIFORM"))return{shape:g.shape,texData:null,isUniform:!0,uniformValues:x.values};e.packedInputs&&(x.isPacked=!0,x.shape=g.shape)}else if(!!x.isPacked!=!!e.packedInputs)g=x.isPacked?this.unpackTensor(g):this.packTensor(g),l.push(g),x=this.texData.get(g.dataId);else if(x.isPacked&&!dl(x.shape,g.shape)){let b=g,w=g.shape;g.shape=x.shape,g=this.packedReshape(g,w),l.push(g),x=this.texData.get(g.dataId),b.shape=w}return this.uploadToGPU(g.dataId),{shape:g.shape,texData:x,isUniform:!1}});this.uploadToGPU(a.dataId);let c={shape:a.shape,texData:i,isUniform:!1},p=JA(e,u,c),m=this.getAndSaveBinary(p,()=>XA(this.gpgpu,e,u,c)),f=this.activeTimers!=null,d;f&&(d=this.startTimer()),ZA(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=y.now();g-this.lastGlFlushTime>h&&(this.gpgpu.gl.flush(),this.lastGlFlushTime=g)}if(!W().getBool("WEBGL_LAZILY_UNPACK")&&i.isPacked&&s===!1){let g=this.unpackTensor(a);return this.disposeIntermediateTensorInfo(a),g}return a}compileAndRun(e,t,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?w5:k5}uploadToGPU(e){let t=this.texData.get(e),{shape:o,dtype:n,values:s,texture:a,usage:i,isPacked:l}=t;if(a!=null)return;let u=this.activeTimers!=null,c;u&&(c=y.now());let p=t.texShape;if(p==null&&(p=qk(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 i_(m,[h,d],g)):f=new s_(m,[h,d],g);let x=this.makeTensorInfo([h,d],n);g?this.texData.get(x.dataId).usage=Dr.PIXELS:this.texData.get(x.dataId).usage=Dr.UPLOAD,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(x.dataId),d,h,s);let b=!0,w=this.runWebGLProgram(f,[x],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(x),this.texData.delete(w.dataId),t.values=null,u&&(this.uploadWaitMs+=y.now()-c)}else{let m=this.acquireTexture(p,i,n,l);t.texture=m}}convertAndCacheOnCPU(e,t){let o=this.texData.get(e),{dtype:n}=o;return this.releaseGPUData(e),t!=null&&(o.values=N5(t,n)),o.values}acquireTexture(e,t,o,n){if(this.numBytesInGPU+=this.computeBytes(e,o),!this.warnedAboutMemory&&this.numBytesInGPU>this.numMBBeforeWarning*1024*1024){let s=(this.numBytesInGPU/1024/1024).toFixed(2);this.warnedAboutMemory=!0,console.warn(`High memory usage in GPU: ${s} MB, most likely due to a memory leak`)}return this.textureManager.acquireTexture(e,t,n)}computeBytes(e,t){return e[0]*e[1]*y.bytesPerElement(t)}};Zu.nextDataId=0;function N5(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 T_="3.3.0";function A_(){W().set("WEBGL_FORCE_F16_TEXTURES",!0)}hu.isBrowser()&&xu("webgl",()=>new Zu,2);var S5={forceHalfFloat:A_};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||y.sizeFromShape(this.outputShape)===1)a=`
|
|
result.y = 0.;
|
|
result.z = 0.;
|
|
result.w = 0.;
|
|
`;else if(a=`
|
|
${Le(s)} coords = getOutputCoords();
|
|
`,s===1)a+=`
|
|
result.y = (coords + 1) >= ${this.outputShape[0]} ? 0. : result.y;
|
|
result.z = 0.;
|
|
result.w = 0.;
|
|
`;else{let l=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 ME={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 LE={kernelName:Gl,backendName:"webgl",kernelFunc:lo};var E_="return (a < 0.) ? b * a : a;",D_=`
|
|
vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
|
|
return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
|
|
`;function T5(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{alpha:s}=o,a=t.makeTensorInfo([],"float32",y.createScalarValue(s,"float32")),i=W().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Ps(D_,n.shape,a.shape):new Xn(E_,n.shape,a.shape),l=t.runWebGLProgram(i,[n,a],n.dtype);return t.disposeIntermediateTensorInfo(a),l}var zE={kernelName:un,backendName:"webgl",kernelFunc:T5};var $_="return (a < 0.) ? b * a : a;",R_=`
|
|
vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
|
|
return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
|
|
`;function A5(r){let{inputs:e,backend:t}=r,{x:o,alpha:n}=e,s=W().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Ps(R_,o.shape,n.shape):new Xn($_,o.shape,n.shape);return t.runWebGLProgram(s,[o,n],o.dtype)}var BE={kernelName:kn,backendName:"webgl",kernelFunc:A5};var Vg="if (isnan(x)) return x;",VE=`
|
|
if (isnan(a)) return a;
|
|
if (isnan(b)) return b;
|
|
`,GE=`
|
|
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,x]=[[d.complexTensorInfos.real,h.complexTensorInfos.real],[d.complexTensorInfos.imag,h.complexTensorInfos.imag]].map(w=>{let[k,_]=w,D={dataId:k.dataId,dtype:k.dtype,shape:l.shape},T={dataId:_.dataId,dtype:_.dtype,shape:u.shape},R=new Xn(r,l.shape,u.shape);return c.runWebGLProgram(R,[D,T],dr(k.dtype,_.dtype))}),b=lo({inputs:{real:g,imag:x},backend:c});return c.disposeIntermediateTensorInfo(g),c.disposeIntermediateTensorInfo(x),b}let p=s||dr(l.dtype,u.dtype);if(c.shouldExecuteOnCPU([l,u])&&n!=null){let d=c.texData.get(l.dataId),h=c.texData.get(u.dataId),[g,x]=n(l.shape,u.shape,d.values,h.values,p),b=c.makeTensorInfo(x,p),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?RE:AE;if(r==="relu")return e?OE:DE;if(r==="elu")return e?FE:EE;if(r==="relu6")return e?PE:$E;if(r==="prelu")return e?R_:$_;if(r==="leakyrelu")return e?D_:E_;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="",x="";i&&(l?g=`vec4 activation(vec4 a) {
|
|
vec4 b = getPreluActivationWeightsAtOutCoords();
|
|
${i}
|
|
}`:u?g=`vec4 activation(vec4 a) {
|
|
vec4 b = getLeakyreluAlphaAtOutCoords();
|
|
${i}
|
|
}`:g=`vec4 activation(vec4 x) {
|
|
${i}
|
|
}`,x="result = activation(result);");let b=a?"result += getBiasAtOutCoords();":"";a&&this.variableNames.push("bias"),l&&this.variableNames.push("preluActivationWeights"),u&&this.variableNames.push("leakyreluAlpha");let w="rc.x",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}
|
|
|
|
${x}
|
|
|
|
setOutput(result);
|
|
}
|
|
`}};var F_={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 WE="return a * b;";function O_(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(F_.REAL,o.shape,n.shape),c=new Gg(F_.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]=dE(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(WE,o.shape,n.shape):a=new Xn(WE,o.shape,n.shape),t.runWebGLProgram(a,[o,n],s)}var jE={kernelName:xn,backendName:"webgl",kernelFunc:O_};function UE(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=y.sizeFromShape(n.shape),l=y.inferFromImplicitShape(s,i),u=y.sizeFromShape(l);y.assert(i===u,()=>`The new shape (${l}) has ${u} elements and the old shape (${n.shape}) has ${i} elements. The new shape and old shape must have the same number of elements.`);let c=a.texData.get(n.dataId);return c.isPacked&&!dl(n.shape,l)&&!(c.texture!==null&&dl(c.shape,l))?UE(n,l,a):(a.incRef(n.dataId),{dataId:n.dataId,shape:l,dtype:n.dtype})}var HE={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 * ${y.isInt(p)?p.toPrecision(2):p}, ones);`}let c="";s%o>0&&(c=`
|
|
if (inIdx < 0 || inIdx >= ${s}) {
|
|
return 0.0;
|
|
}
|
|
`),this.userCode=`
|
|
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
|
|
|
|
float getValue(int batch, int inIdx) {
|
|
${c}
|
|
return getX(batch, inIdx);
|
|
}
|
|
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int outIdx = coords[1];
|
|
int inOffset = outIdx * ${o};
|
|
|
|
float sumValue = 0.0;
|
|
|
|
for (int i = 0; i < ${i}; i += 4) {
|
|
int inIdx = inOffset + i;
|
|
vec4 values = vec4(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1),
|
|
getValue(batch, inIdx + 2),
|
|
getValue(batch, inIdx + 3)
|
|
);
|
|
|
|
${u}
|
|
}
|
|
|
|
int inIdx = inOffset + ${i};
|
|
if (${l===1}) {
|
|
vec4 values = vec4(getValue(batch, inIdx), 0.0, 0.0, 0.0);
|
|
|
|
${u}
|
|
} else if (${l===2}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1), 0.0, 0.0);
|
|
|
|
${u}
|
|
} else if (${l===3}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1),
|
|
getValue(batch, inIdx + 2), 0.0);
|
|
|
|
${u}
|
|
}
|
|
setOutput(sumValue);
|
|
}
|
|
`}};var P_=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 E5(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=E5(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 P_({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 M_=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=D5(t);this.userCode=`
|
|
void main() {
|
|
${n} resRC = getOutputCoords();
|
|
setOutput(getA(${s}));
|
|
}
|
|
`}};function D5(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 L_=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=v_("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 L_(r.shape,e):new M_(r.shape,e);return t.runWebGLProgram(o,[r],r.dtype)}function qE(r,e,t,o){let n=e,s=r.shape.length,a=y.parseAxisParam(n,r.shape),i=a,l=N.getAxesPermutation(i,s),u=l!=null,c=r;u&&(c=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=y.sizeFromShape(m),g=y.sizeFromShape(r.shape)/d,x=pe({inputs:{x:c},attrs:{shape:[g,d]},backend:o}),b=fu(r.dtype),w=No(x,b,"sum",o),k=pe({inputs:{x:w},attrs:{shape:f},backend:o});return o.disposeIntermediateTensorInfo(x),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 qE(n,s,a,t)}var KE={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=wp(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 XE={kernelName:Pn,backendName:"webgl",kernelFunc:Mt};var z_=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),x=y.sizeFromShape(h),b=y.sizeFromShape(g),w=x===b||x===1||b===1;y.assert(u>=2&&c>=2&&w,()=>`Error in matMul: the input batch dimensions must either be the same or at least one input batch dimension must be 1. Got input batch dimensions of (${h}) and (${g}).`);let _=(x>b?r.shape.slice(0,-2):e.shape.slice(0,-2)).concat([f,d]);y.assert(p===m,()=>`Error in matMul: inner shapes (${p}) and (${m}) of Tensors with shapes ${r.shape} and ${e.shape} and transposeA=${t} and transposeB=${o} must match.`);let D=t?[x,p,f]:[x,f,p],T=o?[b,d,m]:[b,m,d],R=pe({inputs:{x:r},backend:n,attrs:{shape:D}}),O=pe({inputs:{x:e},backend:n,attrs:{shape:T}}),M=[R,O],G=Math.max(x,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>z_&&oe===!1){let J=R,ie=O;t&&(J=Mt({inputs:{x:R},backend:n,attrs:{perm:[0,2,1]}}),M.push(J)),o&&(ie=Mt({inputs:{x:O},backend:n,attrs:{perm:[0,2,1]}}),M.push(ie));let ue=d!==1,ae=d===1,fe=J;ue&&(fe=pe({inputs:{x:J},backend:n,attrs:{shape:[G,j,1]}}),M.push(fe));let de=d===1?2:1,xe=ie;ae&&(xe=pe({inputs:{x:ie},backend:n,attrs:{shape:[G,1,j]}}),M.push(xe));let we=O_({inputs:{a:fe,b:xe},backend:n});Y=Cf({inputs:{x:we},backend:n,attrs:{axis:de,keepDims:!0}}),M.push(we)}else{let J=dr(r.dtype,e.dtype),ie=new vf(D,T,[G,f,d],t,o,U,X,H,q),ue=[R,O];if(s!=null&&ue.push(s),H&&ue.push(a),q){let ae=n.makeTensorInfo([],"float32",y.createScalarValue(i,"float32"));ue.push(ae),M.push(ae)}Y=n.runWebGLProgram(ie,ue,J)}let re=pe({inputs:{x:Y},backend:n,attrs:{shape:_}});M.push(Y);for(let J of M)n.disposeIntermediateTensorInfo(J);return re}function $5(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 YE={kernelName:ws,backendName:"webgl",kernelFunc:$5};var ZE="return abs(x);";function R5(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,ZE):n=new ao(o.shape,ZE),t.runWebGLProgram(n,[o],o.dtype)}var JE={kernelName:as,backendName:"webgl",kernelFunc:R5};var F5=gr+`
|
|
if (abs(x) > 1.) {
|
|
return NAN;
|
|
}
|
|
return acos(x);
|
|
`,O5=ke({opSnippet:F5}),QE={kernelName:qs,backendName:"webgl",kernelFunc:O5};var P5=gr+`
|
|
if (x < 1.0) return NAN;
|
|
return log(x + sqrt(x * x - 1.0));`,M5=ke({opSnippet:P5}),e2={kernelName:Ks,backendName:"webgl",kernelFunc:M5};var t2="return a + b;",L5=nt({opSnippet:t2,packedOpSnippet:t2,supportsComplex:!0,cpuKernelImpl:QA}),r2={kernelName:wo,backendName:"webgl",kernelFunc:L5};var B_=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 V_=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)=>dr(l,u)),s=o.map(l=>l.shape),i=W().getBool("WEBGL_PACK")?new V_(o[0].shape,s):new B_(o[0].shape,s);return t.runWebGLProgram(i,o,n)}var o2={kernelName:Ho,backendName:"webgl",kernelFunc:jg};function z5(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{axis:s,keepDims:a}=o,i=n.shape.length,l=y.parseAxisParam(s,n.shape),u=l,c=N.getAxesPermutation(u,i),p=n;c!=null&&(p=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=y.sizeFromShape(f),h=pe({inputs:{x:p},backend:t,attrs:{shape:[-1,d]}}),g=No(h,h.dtype,"all",t),x;if(a){let b=N.expandShapeToKeepDim(m,l);x=pe({inputs:{x:g},backend:t,attrs:{shape:b}})}else x=pe({inputs:{x:g},backend:t,attrs:{shape:m}});return t.disposeIntermediateTensorInfo(h),t.disposeIntermediateTensorInfo(g),c!=null&&t.disposeIntermediateTensorInfo(p),x}var n2={kernelName:Ml,backendName:"webgl",kernelFunc:z5};function B5(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{axis:s,keepDims:a}=o,i=n.shape.length,l=y.parseAxisParam(s,n.shape),u=l,c=N.getAxesPermutation(u,i),p=n;c!=null&&(p=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=y.sizeFromShape(f),h=pe({inputs:{x:p},backend:t,attrs:{shape:[-1,d]}}),g=No(h,h.dtype,"any",t),x;if(a){let b=N.expandShapeToKeepDim(m,l);x=pe({inputs:{x:g},backend:t,attrs:{shape:b}})}else x=pe({inputs:{x:g},backend:t,attrs:{shape:m}});return t.disposeIntermediateTensorInfo(h),t.disposeIntermediateTensorInfo(g),c!=null&&t.disposeIntermediateTensorInfo(p),x}var s2={kernelName:Ll,backendName:"webgl",kernelFunc:B5};var G_=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 W_=class{constructor(e,t,o,n){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,y.assert(e.length>2,()=>`Packed arg${o.charAt(0).toUpperCase()+o.slice(1)} supports only inputs with rank above 2.`);let s=e[e.length-1],a=Math.ceil(s/t);this.outputShape=e.slice(0,-1),a>1&&this.outputShape.push(a),n||this.variableNames.push("bestIndicesA");let i=this.outputShape,l=i.length,u=Le(l),c=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"),x=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",_=n?"":`
|
|
inIdx = round(vec4(getBestIndicesAChannel(${g.join()}),
|
|
getBestIndicesAChannel(${x.join()}),
|
|
getBestIndicesAChannel(${b.join()}),
|
|
getBestIndicesAChannel(${w.join()})));`,D=`vec4(
|
|
getAChannel(${g.join()}),
|
|
hasNextCol ? getAChannel(${x.join()}) : 0.,
|
|
hasNextRow ? getAChannel(${b.join()}) : 0.,
|
|
hasNextRow && hasNextCol ? getAChannel(${w.join()}) : 0.)`,T=n?"":`
|
|
float getBestIndicesAChannel(${h.join()}) {
|
|
return getChannel(getBestIndicesA(${f.join()}),
|
|
vec2(${f.slice(-2).join()}));
|
|
}`;this.userCode=`
|
|
float getAChannel(${h.join()}) {
|
|
return getChannel(getA(${f.join()}),
|
|
vec2(${f.slice(-2).join()}));
|
|
}
|
|
${T}
|
|
void main() {
|
|
${u} coords = getOutputCoords();
|
|
bool hasNextCol = ${c[l-1]} < ${i[l-1]-1};
|
|
bool hasNextRow = ${c[l-2]} < ${i[l-2]-1};
|
|
${p}
|
|
ivec4 srcIdx = ivec4(sourceLocR${d}, sourceLocG${d},
|
|
sourceLocB${d}, sourceLocA${d}) * ${t};
|
|
ivec4 inIdx = srcIdx;
|
|
vec4 bestIndex = vec4(inIdx);
|
|
vec4 bestValue = ${D};
|
|
|
|
for (int i = 0; i < ${t}; i++) {
|
|
inIdx = srcIdx;
|
|
${_}
|
|
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 i2(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 G_(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=i2(r,e,t,c);return r.disposeIntermediateTensorInfo(c),p}function a2(r,e,t,o=null){let n=o!=null?o.shape:e.shape,s=n[n.length-1],a=N.computeOptimalWindowSize(s),i=new W_(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=a2(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=y.sizeFromShape(i),u=pe({inputs:{x:e},backend:r,attrs:{shape:[-1,l]}});s.push(u);let c=i2(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 a2(r,e,o)}function V5(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{axis:s}=o,a=y.parseAxisParam(s,n.shape),i=N.getAxesPermutation(a,n.shape.length),l=n,u=[];i!=null&&(l=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 l2={kernelName:qo,backendName:"webgl",kernelFunc:V5};function G5(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{axis:s}=o,a=y.parseAxisParam(s,n.shape),i=N.getAxesPermutation(a,n.shape.length),l=n,u=[];i!=null&&(l=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 u2={kernelName:ea,backendName:"webgl",kernelFunc:G5};var W5=gr+`
|
|
if (abs(x) > 1.) {
|
|
return NAN;
|
|
}
|
|
return asin(x);
|
|
`,j5=ke({opSnippet:W5}),c2={kernelName:Xs,backendName:"webgl",kernelFunc:j5};var U5=gr+"return log(x + sqrt(x * x + 1.0));",H5=ke({opSnippet:U5}),p2={kernelName:Ys,backendName:"webgl",kernelFunc:H5};var q5=gr+`
|
|
return atan(x);
|
|
`,K5=ke({opSnippet:q5}),m2={kernelName:Zs,backendName:"webgl",kernelFunc:K5};var X5=VE+`
|
|
return atan(a, b);
|
|
`,Y5=`
|
|
vec4 result = atan(a, b);
|
|
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
|
|
`+GE+`
|
|
return result;
|
|
`,Z5=nt({opSnippet:X5,packedOpSnippet:Y5}),f2={kernelName:Qs,backendName:"webgl",kernelFunc:Z5};var J5=gr+`
|
|
if ((x < -1.0) || (x > 1.0)) return NAN;
|
|
return (log(1.0 + x) - log(1.0 - x)) / 2.0;`,Q5=ke({opSnippet:J5}),d2={kernelName:Js,backendName:"webgl",kernelFunc:Q5};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`,x=`(xR * ${e.inWidth} + xC) * ${e.inChannels} + d`,b="0.0";if(h||(b="-1.0 / 1e-20"),o){let R=">=";this.userCode=`
|
|
const ivec2 strides = ivec2(${i}, ${l});
|
|
const ivec2 pads = ivec2(${f}, ${d});
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int d = coords[3];
|
|
|
|
ivec2 xRCCorner = coords.yz * strides - pads;
|
|
int xRCorner = xRCCorner.x;
|
|
int xCCorner = xRCCorner.y;
|
|
|
|
// max/min x(?, ?, d) to get y(yR, yC, d).
|
|
// ? = to be determined
|
|
float minMaxValue = 0.0;
|
|
float minMaxValueFound = 0.0;
|
|
int minMaxPosition = 0;
|
|
float avgValue = 0.0;
|
|
|
|
for (int wR = 0; wR < ${p};
|
|
wR += ${u}) {
|
|
int xR = xRCorner + wR;
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < ${m};
|
|
wC += ${c}) {
|
|
int xC = xCCorner + wC;
|
|
|
|
if (xC < 0 || xC >= ${e.inWidth}) {
|
|
continue;
|
|
}
|
|
|
|
float value = getX(batch, xR, xC, d);
|
|
|
|
// If a min / max value has already been found, use it. If not,
|
|
// use the current value.
|
|
float currMinMaxValue = mix(
|
|
value, minMaxValue, minMaxValueFound);
|
|
if (value ${R} currMinMaxValue) {
|
|
minMaxValue = value;
|
|
minMaxValueFound = 1.0;
|
|
minMaxPosition = ${n?s?g:x:`wR * ${m} + wC`};
|
|
}
|
|
}
|
|
}
|
|
setOutput(float(minMaxPosition));
|
|
}
|
|
`;return}let w="max",k=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="avg"&&(k="avgValue / count");let _=Math.floor(a/4)*4,D=a%4,T=`
|
|
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 < ${_}; wC += 4) {
|
|
int xC = xCCorner + wC * ${c};
|
|
|
|
vec4 values = vec4(
|
|
getValue(batch, xR, xC, d),
|
|
getValue(batch, xR, xC + ${c}, d),
|
|
getValue(batch, xR, xC + 2 * ${c}, d),
|
|
getValue(batch, xR, xC + 3 * ${c}, d)
|
|
);
|
|
|
|
${T}
|
|
}
|
|
|
|
int xC = xCCorner + ${_};
|
|
if (${D===1}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xR, xC, d),
|
|
initializationValue,
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${T}
|
|
} else if (${D===2}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xR, xC, d),
|
|
getValue(batch, xR, xC + ${c}, d),
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${T}
|
|
} 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
|
|
);
|
|
|
|
${T}
|
|
}
|
|
}
|
|
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,x=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 M=">=";this.userCode=`
|
|
const ivec3 strides =
|
|
ivec3(${i}, ${l}, ${u});
|
|
const ivec3 pads = ivec3(${g}, ${x}, ${b});
|
|
|
|
void main() {
|
|
ivec5 coords = getOutputCoords();
|
|
int batch = coords.x;
|
|
int ch = coords.u;
|
|
|
|
ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
|
|
int xDCorner = xCorner.x;
|
|
int xRCorner = xCorner.y;
|
|
int xCCorner = xCorner.z;
|
|
|
|
// max/min x(?, ?, ?, ch) to get y(yD, yR, yC, ch).
|
|
// ? = to be determined
|
|
float minMaxValue = 0.0;
|
|
float minMaxValueFound = 0.0;
|
|
int minMaxPosition = 0;
|
|
|
|
for (int wD = 0; wD < ${f};
|
|
wD += ${c}) {
|
|
int xD = xDCorner + wD;
|
|
|
|
if (xD < 0 || xD >= ${e.inDepth}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wR = 0; wR < ${d};
|
|
wR += ${p}) {
|
|
int xR = xRCorner + wR;
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < ${h};
|
|
wC += ${m}) {
|
|
int xC = xCCorner + wC;
|
|
|
|
if (xC < 0 || xC >= ${e.inWidth}) {
|
|
continue;
|
|
}
|
|
|
|
float value = getX(batch, xD, xR, xC, ch);
|
|
|
|
// If a min / max value has already been found, use it. If not,
|
|
// use the current value.
|
|
float currMinMaxValue = mix(
|
|
value, minMaxValue, minMaxValueFound);
|
|
if (value ${M} currMinMaxValue) {
|
|
minMaxValue = value;
|
|
minMaxValueFound = 1.0;
|
|
minMaxPosition = ${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 _="max",D=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="avg"&&(D="avgValue / count");let T=Math.floor(a/4)*4,R=a%4,O=`
|
|
if (${w}) {
|
|
avgValue += dot(values, ones);
|
|
} else {
|
|
minMaxValue = ${_}(values, minMaxValue);
|
|
}
|
|
`;this.userCode=`
|
|
const ivec3 strides =
|
|
ivec3(${i}, ${l}, ${u});
|
|
const ivec3 pads = ivec3(${g}, ${x}, ${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 < ${T}; wC += 4) {
|
|
int xC = xCCorner + wC * ${m};
|
|
|
|
vec4 values = vec4(
|
|
getValue(batch, xD, xR, xC, ch),
|
|
getValue(batch, xD, xR, xC + ${m}, ch),
|
|
getValue(batch, xD, xR, xC + 2 * ${m}, ch),
|
|
getValue(batch, xD, xR, xC + 3 * ${m}, ch)
|
|
);
|
|
|
|
${O}
|
|
}
|
|
|
|
int xC = xCCorner + ${T};
|
|
if (${R===1}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xD, xR, xC, ch),
|
|
initializationValue,
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${O}
|
|
} else if (${R===2}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xD, xR, xC, ch),
|
|
getValue(batch, xD, xR, xC + ${m}, ch),
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${O}
|
|
} 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
|
|
);
|
|
|
|
${O}
|
|
}
|
|
}
|
|
setOutput(${D});
|
|
}
|
|
}
|
|
`}};function eX(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;y.assert(N.eitherStridesOrDilationsAreOne(a,u),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${u}'`);let c=N.computePool2DInfo(n.shape,s,a,u,i,l);if(c.filterWidth===1&&c.filterHeight===1&&y.arraysEqual(c.inShape,c.outShape))return jt({inputs:{x:n},backend:t});let p=new Vi(c,"avg",!1);return t.runWebGLProgram(p,[n],"float32")}var h2={kernelName:Ko,backendName:"webgl",kernelFunc:eX};function tX(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 g2={kernelName:ta,backendName:"webgl",kernelFunc:tX};var j_=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);
|
|
}
|
|
`}},U_=class{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;let t=e.filterDepth,o=e.filterHeight,n=e.filterWidth,s=e.strideDepth,a=e.strideHeight,i=e.strideWidth,l=e.dilationDepth,u=e.dilationHeight,c=e.dilationWidth,p=e.effectiveFilterDepth,m=e.effectiveFilterHeight,f=e.effectiveFilterWidth,d=p-1-e.padInfo.front,h=m-1-e.padInfo.top,g=f-1-e.padInfo.left,x=1/(t*o*n);this.userCode=`
|
|
const ivec3 pads = ivec3(${d}, ${h}, ${g});
|
|
const float avgMultiplier = float(${x});
|
|
|
|
void main() {
|
|
ivec5 coords = getOutputCoords();
|
|
int batch = coords.x;
|
|
int ch = coords.u;
|
|
|
|
ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
|
|
int dyDCorner = dyCorner.x;
|
|
int dyRCorner = dyCorner.y;
|
|
int dyCCorner = dyCorner.z;
|
|
|
|
// Convolve dy(?, ?, ?, d) with pos mask(:, :, :, ch) to get
|
|
// dx(xD, xR, xC, ch).
|
|
// ? = to be determined. : = across all values in that axis.
|
|
float dotProd = 0.0;
|
|
|
|
for (int wD = 0; wD < ${p};
|
|
wD += ${l}) {
|
|
float dyD = float(dyDCorner + wD) / ${s}.0;
|
|
|
|
if (dyD < 0.0 || dyD >= ${e.outDepth}.0 || fract(dyD) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyD = int(dyD);
|
|
|
|
for (int wR = 0; wR < ${m};
|
|
wR += ${u}) {
|
|
float dyR = float(dyRCorner + wR) / ${a}.0;
|
|
|
|
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||
|
|
fract(dyR) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyR = int(dyR);
|
|
|
|
for (int wC = 0; wC < ${f};
|
|
wC += ${c}) {
|
|
float dyC = float(dyCCorner + wC) / ${i}.0;
|
|
|
|
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
|
|
fract(dyC) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyC = int(dyC);
|
|
|
|
float dyValue = getDy(batch, idyD, idyR, idyC, ch);
|
|
|
|
dotProd += dyValue * avgMultiplier;
|
|
}
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`}};function rX(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 U_(m);return t.runWebGLProgram(f,[n],a.dtype)}var x2={kernelName:Bl,backendName:"webgl",kernelFunc:rX};function oX(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 j_(c);return t.runWebGLProgram(p,[n],a.dtype)}var y2={kernelName:zl,backendName:"webgl",kernelFunc:oX};function nX(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 b2={kernelName:Xo,backendName:"webgl",kernelFunc:nX};var H_=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 q_=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 sX=({inputs:r,backend:e,attrs:t})=>{let{x:o,mean:n,variance:s,offset:a,scale:i}=r;y.assert(n.shape.length===s.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),y.assert(a==null||n.shape.length===a.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),y.assert(i==null||n.shape.length===i.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let{varianceEpsilon:l}=t;l==null&&(l=.001);let u=[o,n,s],c=null;a!=null&&(c=a.shape,u.push(a));let p=null;i!=null&&(p=i.shape,u.push(i));let m=W().getBool("WEBGL_PACK_NORMALIZATION")?new q_(o.shape,n.shape,s.shape,c,p,l):new H_(o.shape,n.shape,s.shape,c,p,l);return e.runWebGLProgram(m,u,u[0].dtype)},w2={kernelName:an,backendName:"webgl",kernelFunc:sX};var K_=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=iX(this.rank),s,a=e.map((i,l)=>`sourceLoc.${X_[l]} = start[${l}] + coords.${X_[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)}}},X_=["x","y","z","w","u","v"];function iX(r){if(r===1)return"sourceLoc";if(r<=6)return X_.slice(0,r).map(e=>"sourceLoc."+e).join(",");throw Error(`Slicing for rank ${r} is not yet supported`)}var Y_=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 aX(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=sr.computeFlatOffset(e,y.computeStrides(r.shape));n.slice&&(i+=n.slice.flatOffset),a.slice={flatOffset:i,origDataId:n.slice&&n.slice.origDataId||r.dataId};let l=o.dataRefCount.get(a.slice.origDataId)||1;return o.dataRefCount.set(a.slice.origDataId,l+1),s}function Ma(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{begin:s,size:a}=o,[i,l]=sr.parseSliceParams(n,s,a);if(sr.assertParamsValid(n,i,l),y.sizeFromShape(l)===0)return t.makeTensorInfo(l,n.dtype,[]);if(t.shouldExecuteOnCPU([n])||n.dtype==="string"){let p=t.texData.get(n.dataId),m=bE(p.values,i,l,n.shape,n.dtype);return t.makeTensorInfo(l,n.dtype,m)}let{isPacked:u}=t.texData.get(n.dataId),c=sr.isSliceContinous(n.shape,i,l);if(u||!c){let p=W().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Y_(l):new K_(l),m=p.getCustomSetupFunc(i);return t.runWebGLProgram(p,[n],n.dtype,m)}return t.uploadToGPU(n.dataId),aX(n,i,l,t)}var k2={kernelName:gs,backendName:"webgl",kernelFunc:Ma};var lX=r=>{let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{blockShape:s,crops:a}=o;y.assert(n.shape.length<=4,()=>"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet");let i=s.reduce((b,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}}),x=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)),x},_2={kernelName:ra,backendName:"webgl",kernelFunc:lX};function uX(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 v2={kernelName:Vl,backendName:"webgl",kernelFunc:uX};var cX="return float(a != b);",Z_=nt({opSnippet:cX,dtype:"bool"}),C2={kernelName:yi,backendName:"webgl",kernelFunc:Z_};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 I2={kernelName:iu,backendName:"webgl",kernelFunc:La};var pX="return float(int(x));";function N2(r,e){let t=new ao(r.shape,pX),o=e.runWebGLProgram(t,[r],"int32");return{dataId:o.dataId,shape:o.shape,dtype:o.dtype}}function J_(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=J_({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=J_({inputs:{x:a},backend:t,attrs:{dtype:s}});return t.disposeIntermediateTensorInfo(a),i}if(!y.hasEncodingLoss(n.dtype,s)){let a=jt({inputs:{x:n},backend:t});return{dataId:a.dataId,shape:a.shape,dtype:s}}if(s==="int32")return N2(n,t);if(s==="bool"){let a=t.makeTensorInfo([],"bool",y.getTypedArrayFromDType("bool",1)),l=Z_({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 S2={kernelName:$o,backendName:"webgl",kernelFunc:J_};var T2="return ceil(x);",mX=ke({opSnippet:T2,packedOpSnippet:T2,cpuKernelImpl:tE}),A2={kernelName:Yo,backendName:"webgl",kernelFunc:mX};var Q_=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 ev=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 fX(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 ev(n.shape):i=new Q_(n.shape);let l=i.getCustomSetupFunc(s,a);return t.runWebGLProgram(i,[n],n.dtype,l)}var E2={kernelName:Ro,backendName:"webgl",kernelFunc:fX};var tv=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 D2(r,e){return{dataId:e.dataId,dtype:e.dtype,shape:r.shape}}function dX(r){let{inputs:e,backend:t}=r,{x:o}=e,n=t.texData.get(o.dataId),s=new tv(o.shape),a=[D2(o,n.complexTensorInfos.real),D2(o,n.complexTensorInfos.imag)];return t.runWebGLProgram(s,a,a[0].dtype)}var $2={kernelName:oa,backendName:"webgl",kernelFunc:dX};var rv=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 ov=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 R2={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}=F2(r,e,t),p=u.map(g=>({vals:t.readSync(g.dataId),shape:g.shape})),m=u[0].shape[0]===1,f=rE(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 ov(r.map(c=>c.shape),e);return t.runWebGLProgram(u,r,o)}let{tensors2D:n,outShape:s}=F2(r,e,t),a=new rv(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 F2(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,y.sizeFromShape(s.shape.slice(e))]},backend:t})),outShape:o}}function nv(r){let{inputs:e,backend:t,attrs:o}=r,{axis:n}=o,s=y.parseAxisParam(n,e[0].shape)[0],a=N.computeOutShape(e.map(u=>u.shape),s);if(y.sizeFromShape(a)===0)return t.makeTensorInfo(a,e[0].dtype,[]);let i=e.filter(u=>y.sizeFromShape(u.shape)>0);if(i.length===1)return jt({inputs:{x:i[0]},backend:t});let l=i.map(u=>u.shape);return N.assertParamsConsistent(l,s),tc(i,s,t)}var O2={kernelName:ls,backendName:"webgl",kernelFunc:nv};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",x=g?1:2,b=g?2:3,w=g?3:1,k="",_="";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}
|
|
}
|
|
`,_="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[${x}], coords[${b}]) * strides - pads;
|
|
int xRCorner = xRCCorner.x;
|
|
int xCCorner = xRCCorner.y;
|
|
|
|
// Convolve x(?, ?, d1) with w(:, :, d1, d2) to get y(yR, yC, d2).
|
|
// ? = to be determined. : = across all values in that axis.
|
|
float dotProd = 0.0;
|
|
for (int wR = 0; wR < ${m}; wR++) {
|
|
int xR = xRCorner + wR * ${c};
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < ${f}; wC++) {
|
|
int xC = xCCorner + wC * ${p};
|
|
|
|
if (xC < 0 || xC >= ${e.inWidth}) {
|
|
continue;
|
|
}
|
|
|
|
for (int d1 = 0; d1 < ${d}; d1 += 4) {
|
|
vec4 wValues = vec4(
|
|
getW(wR, wC, d1, d2),
|
|
getW(wR, wC, d1 + 1, d2),
|
|
getW(wR, wC, d1 + 2, d2),
|
|
getW(wR, wC, d1 + 3, d2)
|
|
);
|
|
|
|
if (${g}) {
|
|
vec4 xValues = vec4(
|
|
getX(batch, xR, xC, d1),
|
|
getX(batch, xR, xC, d1 + 1),
|
|
getX(batch, xR, xC, d1 + 2),
|
|
getX(batch, xR, xC, d1 + 3)
|
|
);
|
|
dotProd += dot(xValues, wValues);
|
|
} else {
|
|
vec4 xValues = vec4(
|
|
getX(batch, d1, xR, xC),
|
|
getX(batch, d1 + 1, xR, xC),
|
|
getX(batch, d1 + 2, xR, xC),
|
|
getX(batch, d1 + 3, xR, xC)
|
|
);
|
|
dotProd += dot(xValues, wValues);
|
|
}
|
|
}
|
|
|
|
if (${h===1}) {
|
|
|
|
if (${g}) {
|
|
dotProd +=
|
|
getX(batch, xR, xC, ${d}) *
|
|
getW(wR, wC, ${d}, d2);
|
|
} else {
|
|
dotProd +=
|
|
getX(batch, ${d}, xR, xC) *
|
|
getW(wR, wC, ${d}, d2);
|
|
}
|
|
|
|
} else if (${h===2}) {
|
|
vec2 wValues = vec2(
|
|
getW(wR, wC, ${d}, d2),
|
|
getW(wR, wC, ${d} + 1, d2)
|
|
);
|
|
|
|
if (${g}) {
|
|
vec2 xValues = vec2(
|
|
getX(batch, xR, xC, ${d}),
|
|
getX(batch, xR, xC, ${d} + 1)
|
|
);
|
|
dotProd += dot(xValues, wValues);
|
|
} else {
|
|
vec2 xValues = vec2(
|
|
getX(batch, ${d}, xR, xC),
|
|
getX(batch, ${d} + 1, xR, xC)
|
|
);
|
|
dotProd += dot(xValues, wValues);
|
|
}
|
|
|
|
} else if (${h===3}) {
|
|
vec3 wValues = vec3(
|
|
getW(wR, wC, ${d}, d2),
|
|
getW(wR, wC, ${d} + 1, d2),
|
|
getW(wR, wC, ${d} + 2, d2)
|
|
);
|
|
|
|
if (${g}) {
|
|
vec3 xValues = vec3(
|
|
getX(batch, xR, xC, ${d}),
|
|
getX(batch, xR, xC, ${d} + 1),
|
|
getX(batch, xR, xC, ${d} + 2)
|
|
);
|
|
dotProd += dot(xValues, wValues);
|
|
} else {
|
|
vec3 xValues = vec3(
|
|
getX(batch, ${d}, xR, xC),
|
|
getX(batch, ${d} + 1, xR, xC),
|
|
getX(batch, ${d} + 2, xR, xC)
|
|
);
|
|
dotProd += dot(xValues, wValues);
|
|
}
|
|
|
|
}
|
|
}
|
|
}
|
|
|
|
float result = dotProd;
|
|
${D}
|
|
${_}
|
|
setOutput(result);
|
|
}
|
|
`}},sv=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 iv=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(),x=m==="channelsLast",b=x?0:1,w=x?1:2,k="";for(let _=0;_<=1;_++)for(let D=0;D<=1;D++)k+=`
|
|
blockIndex = rc.y + ${D};
|
|
pos = rc.x + ${_};
|
|
|
|
if(blockIndex < ${e[1]} && pos < ${e[0]}) {
|
|
offsetY = int(blockIndex / (${u})) * ${i} - ${d};
|
|
d0 = offsetY + ${p} * (pos / ${h});
|
|
|
|
if(d0 < ${t[b]} && d0 >= 0) {
|
|
|
|
offsetX = int(mod(float(blockIndex), ${u}.) * ${a}. - ${f}.);
|
|
d1 = offsetX + ${c} * (int(mod(float(pos), ${h}.) / ${s}.));
|
|
|
|
if(d1 < ${t[w]} && d1 >= 0) {
|
|
|
|
ch = int(mod(float(pos), ${s}.));
|
|
|
|
if (${x}) {
|
|
innerDims = vec2(d1, ch);
|
|
result[${_*2+D}] = getChannel(
|
|
getA(d0, int(innerDims.x),
|
|
int(innerDims.y)), innerDims);
|
|
} else {
|
|
innerDims = vec2(d0, d1);
|
|
result[${_*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,x=[],b=(p===1||m===1)&&c>z_,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],_=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]}}),T=Ju({a:_,b:D,transposeA:d,transposeB:h,backend:o,bias:n,activation:i,preluActivationWeights:s,leakyreluAlpha:a});g=pe({inputs:{x:T},backend:o,attrs:{shape:t.outShape}}),x.push(_),x.push(D),x.push(T)}else{let k=f?l[0]*l[1]*(l[2]+1):l[0]*l[2]*(l[3]+1),_={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]++,y.assert(dl(u.shape,_.shape),()=>`packed reshape ${u.shape} to ${_.shape} isn't free`);let T=pe({inputs:{x:e},backend:o,attrs:{shape:[1,t.inChannels,t.outChannels]}});x.push(T);let R=Ju({a:_,b:T,backend:o,transposeA:d,transposeB:h,bias:n,activation:i,preluActivationWeights:s,leakyreluAlpha:a}),O=o.texData.get(R.dataId);y.assert(O.isPacked,()=>"batchMatMul result is expected to be packed"),u.shape=D,O.shape=t.outShape,g=jt({inputs:{x:R},backend:o}),g.shape=t.outShape,x.push(R)}for(let k of x)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,x=[h,g],b=!0,w=!1,k=[],_=pe({inputs:{x:r},backend:o,attrs:{shape:r.shape.slice(1)}}),D=pe({inputs:{x:e},backend:o,attrs:{shape:[1,h,y.sizeFromShape(e.shape)/h]}});k.push(_),k.push(D);let T=new iv(x,_.shape,t),R=o.runWebGLProgram(T,[_],"float32"),O=pe({inputs:{x:R},backend:o,attrs:{shape:[1,x[0],x[1]]}});k.push(R),k.push(O);let M=n!=null,G=s!=null,j=i==="leakyrelu",U=i?gl(i,!0):null,H=new vf(O.shape,D.shape,[1,g,t.outChannels],b,w,M,U,G,j),q=[O,D];if(n&&q.push(n),G&&q.push(s),j){let re=o.makeTensorInfo([],"float32",y.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 hX(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 P2={kernelName:Zo,backendName:"webgl",kernelFunc:hX};var av=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);
|
|
}
|
|
`}},lv=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);
|
|
}
|
|
`}},uv=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);
|
|
}
|
|
`}},cv=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 gX(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 av(m);return t.runWebGLProgram(f,[n,s],"float32")}var M2={kernelName:Wl,backendName:"webgl",kernelFunc:gX};function xX(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 lv(m);return t.runWebGLProgram(f,[n,s],"float32")}var L2={kernelName:Jo,backendName:"webgl",kernelFunc:xX};function yX(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 sv(u);return t.runWebGLProgram(c,[n,s],"float32")}var z2={kernelName:na,backendName:"webgl",kernelFunc:yX};function bX(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 uv(u);return t.runWebGLProgram(c,[n,s],"float32")}var B2={kernelName:jl,backendName:"webgl",kernelFunc:bX};function wX(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 cv(u);return t.runWebGLProgram(c,[n,s],"float32")}var V2={kernelName:Ul,backendName:"webgl",kernelFunc:wX};var kX=Vg+`
|
|
return cos(x);
|
|
`,_X=ke({opSnippet:kX}),G2={kernelName:Qo,backendName:"webgl",kernelFunc:_X};var vX=`
|
|
float e2x = exp(-x);
|
|
return (e2x + 1.0 / e2x) / 2.0;
|
|
`,CX=ke({opSnippet:vX}),W2={kernelName:ei,backendName:"webgl",kernelFunc:CX};var pv=class{constructor(e,t,o,n,s){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];let[a,i,l,u]=e,[c]=t,[p,m]=o;this.outputShape=[c,p,m,u];let f=n==="bilinear"?1:0,[d,h]=[`${i-1}.0`,`${l-1}.0`],[g,x,b]=p>1?[`${(i-1)/(p-1)}`,"(y2-y1) * height_ratio",`y1*${d} + float(y)*(height_scale)`]:["0.0","0.0",`0.5 * (y1+y2) * ${d}`],[w,k,_]=m>1?[`${(l-1)/(m-1)}`,"(x2-x1) * width_ratio",`x1*${h} + float(x)*(width_scale)`]:["0.0","0.0",`0.5 * (x1+x2) * ${h}`];this.userCode=`
|
|
const float height_ratio = float(${g});
|
|
const float width_ratio = float(${w});
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int y = coords[1];
|
|
int x = coords[2];
|
|
int d = coords[3];
|
|
|
|
// get box vals
|
|
float y1 = getBoxes(b,0);
|
|
float x1 = getBoxes(b,1);
|
|
float y2 = getBoxes(b,2);
|
|
float x2 = getBoxes(b,3);
|
|
|
|
// get image in batch index
|
|
int bInd = round(getBoxInd(b));
|
|
if(bInd < 0 || bInd >= ${a}) {
|
|
return;
|
|
}
|
|
|
|
float height_scale = ${x};
|
|
float width_scale = ${k};
|
|
|
|
float in_y = ${b};
|
|
if( in_y < 0.0 || in_y > ${d} ) {
|
|
setOutput(float(${s}));
|
|
return;
|
|
}
|
|
float in_x = ${_};
|
|
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 IX=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 pv(n.shape,s.shape,i,l,u);return t.runWebGLProgram(c,[n,s,a],"float32")},j2={kernelName:ti,backendName:"webgl",kernelFunc:IX};var Xg=class{constructor(e,t,o){this.variableNames=["x"],this.outputShape=e;let n=e.length,s=t?"0.0":`getX(${U2(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 = ${H2(n,"coords")};
|
|
float val = ${s};
|
|
int pow2 = int(pow(2.0, index));
|
|
if (${i}) {
|
|
int idx = ${l};
|
|
${H2(n,"coords")} = idx;
|
|
val += getX(${U2(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 U2(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 H2(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 NX(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),x=f;f=t.runWebGLProgram(h,[f],f.dtype,g),t.disposeIntermediateTensorInfo(x)}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 q2={kernelName:en,backendName:"webgl",kernelFunc:NX};function SX(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=eE(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 K2={kernelName:Hl,backendName:"webgl",kernelFunc:SX};var mv=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 TX(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{blockSize:s,dataFormat:a}=o;y.assert(s>1,()=>`blockSize should be > 1 for depthToSpace, but was: ${s}`);let i=n.shape[0],l=a==="NHWC"?n.shape[1]:n.shape[2],u=a==="NHWC"?n.shape[2]:n.shape[3],c=a==="NHWC"?n.shape[3]:n.shape[1],p=l*s,m=u*s,f=c/(s*s),d=a==="NHWC"?[i,p,m,f]:[i,f,p,m],h=new mv(d,s,a);return t.runWebGLProgram(h,[n],n.dtype)}var X2={kernelName:ri,backendName:"webgl",kernelFunc:TX};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,x="",b="";o&&(n?x=`float activation(float a) {
|
|
float b = getPreluActivationWeightsAtOutCoords();
|
|
${o}
|
|
}`:s?x=`float activation(float a) {
|
|
float b = getLeakyreluAlphaAtOutCoords();
|
|
${o}
|
|
}`:x=`
|
|
float activation(float x) {
|
|
${o}
|
|
}
|
|
`,b="result = activation(result);");let w=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),n&&this.variableNames.push("preluActivationWeights"),s&&this.variableNames.push("leakyreluAlpha"),this.userCode=`
|
|
${x}
|
|
|
|
const ivec2 strides = ivec2(${c}, ${p});
|
|
const ivec2 pads = ivec2(${l}, ${u});
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int batch = coords.x;
|
|
ivec2 xRCCorner = coords.yz * strides - pads;
|
|
int d2 = coords.w;
|
|
int d1 = d2 / ${g};
|
|
int q = d2 - d1 * ${g};
|
|
|
|
int xRCorner = xRCCorner.x;
|
|
int xCCorner = xRCCorner.y;
|
|
|
|
// Convolve x(?, ?, d1) with w(:, :, d1, q) to get y(yR, yC, d2).
|
|
// ? = to be determined. : = across all values in that axis.
|
|
float dotProd = 0.0;
|
|
// TO DO(dsmilkov): Flatten the two for loops and vec4 the operations.
|
|
for (int wR = 0; wR < ${d}; wR++) {
|
|
int xR = xRCorner + wR * ${m};
|
|
|
|
if (xR < 0 || xR >= ${a}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < ${h}; wC++) {
|
|
int xC = xCCorner + wC * ${f};
|
|
|
|
if (xC < 0 || xC >= ${i}) {
|
|
continue;
|
|
}
|
|
|
|
float xVal = getX(batch, xR, xC, d1);
|
|
float wVal = getW(wR, wC, d1, q);
|
|
dotProd += xVal * wVal;
|
|
}
|
|
}
|
|
|
|
float result = dotProd;
|
|
${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,x="int xR; int xC; int xCOffset;";for(let _=0;_<d;_++)for(let D=0;D<h;D++)x+=`
|
|
vec4 xTexelR${_}C${D*2} = vec4(0.);
|
|
vec4 wR${_}C${D} = vec4(0.);
|
|
vec4 xR${_}C${D} = vec4(0.);`;for(let _=0;_<d;_++)for(let D=0;D<g;D++){let T=D*2;if(x+=`
|
|
xR = xRCorner + ${_*m};
|
|
xC = xCCorner + ${T*f};
|
|
`,p===1){if(T<h&&(u%2==1?x+=`
|
|
xCOffset = xC + 1;
|
|
if(xR >= 0 && xR < ${a} && xCOffset >= 0 && xCOffset < ${i}) {
|
|
xTexelR${_}C${T} = getX(batch, xR, xCOffset, d1);
|
|
|
|
// Need to manually clear unused channels in case
|
|
// we're reading from recycled texture.
|
|
if(xCOffset + 1 >= ${i}) {
|
|
xTexelR${_}C${T}.zw = vec2(0.);
|
|
}
|
|
} else {
|
|
xTexelR${_}C${T} = vec4(0.);
|
|
}
|
|
|
|
xCOffset = xC + 1 - 2;
|
|
if(xR >= 0 && xR < ${a} && xCOffset >= 0 && xCOffset < ${i}) {
|
|
vec4 previous = getX(batch, xR, xCOffset, d1);
|
|
|
|
// Need to manually clear unused channels in case
|
|
// we're reading from recycled texture.
|
|
if(xCOffset + 1 >= ${i}) {
|
|
previous.zw = vec2(0.);
|
|
}
|
|
|
|
xR${_}C${T} = vec4(previous.zw, xTexelR${_}C${T}.xy);
|
|
} else {
|
|
xR${_}C${T} = vec4(0, 0, xTexelR${_}C${T}.xy);
|
|
}
|
|
`:x+=`
|
|
if(xR >= 0 && xR < ${a} && xC >= 0 && xC < ${i}) {
|
|
xTexelR${_}C${T} = getX(batch, xR, xC, d1);
|
|
} else {
|
|
xTexelR${_}C${T} = vec4(0.);
|
|
}
|
|
|
|
xR${_}C${T} = xTexelR${_}C${T};
|
|
`,T+1<h)){let R=u%2==0?y.nearestLargerEven(f):f;f%2==0&&u%2==1||f%2!=0&&u%2!=1?(x+=`
|
|
xCOffset = xC + ${u%2} + ${R};
|
|
|
|
if(xR >= 0 && xR < ${a} &&
|
|
xCOffset >= 0 && xCOffset < ${i}) {
|
|
xTexelR${_}C${T+2} = getX(batch, xR, xCOffset, d1);
|
|
}
|
|
`,f>1&&(x+=`
|
|
xCOffset -= 2;
|
|
if(xR >= 0 && xR < ${a} &&
|
|
xCOffset >= 0 && xCOffset < ${i}) {
|
|
xTexelR${_}C${T} = getX(batch, xR, xCOffset, d1);
|
|
} else {
|
|
xTexelR${_}C${T} = vec4(0.);
|
|
}
|
|
`),x+=`
|
|
xR${_}C${T+1} = vec4(
|
|
xTexelR${_}C${T}.zw, xTexelR${_}C${T+2}.xy);
|
|
`):x+=`
|
|
xCOffset = xC + ${R};
|
|
|
|
if(xR >= 0 && xR < ${a} &&
|
|
xCOffset >= 0 && xCOffset < ${i}) {
|
|
xTexelR${_}C${T+2} = getX(batch, xR, xCOffset, d1);
|
|
}
|
|
|
|
xR${_}C${T+1} = xTexelR${_}C${T+2};
|
|
`}}else T<h&&(x+=`
|
|
if(xR >= 0 && xR < ${a}) {
|
|
`,u%2==1?(x+=`
|
|
xCOffset = xC + 1 - ${p};
|
|
if(xCOffset >= 0 && xCOffset < ${i}) {
|
|
xTexelR${_}C${T} = getX(batch, xR, xCOffset, d1);
|
|
} else {
|
|
xTexelR${_}C${T} = vec4(0.);
|
|
}
|
|
|
|
if(xC + 1 >= 0 && xC + 1 < ${i}) {
|
|
xTexelR${_}C${T+2} = getX(batch, xR, xC + 1, d1);
|
|
} else {
|
|
xTexelR${_}C${T+2} = vec4(0.);
|
|
}
|
|
|
|
xR${_}C${T} = vec4(
|
|
xTexelR${_}C${T}.zw, xTexelR${_}C${T+2}.zw);
|
|
`,T+1<h&&(x+=`
|
|
vec4 final = vec4(0.);
|
|
xCOffset = xC + 1 + ${p};
|
|
if(xCOffset >= 0 && xCOffset < ${i}) {
|
|
final = getX(batch, xR, xCOffset, d1);
|
|
}
|
|
xR${_}C${T+1} = vec4(xTexelR${_}C${T+2}.xy, final.xy);
|
|
`)):(x+=`
|
|
if(xC >= 0 && xC < ${i}) {
|
|
xTexelR${_}C${T} = getX(batch, xR, xC, d1);
|
|
} else {
|
|
xTexelR${_}C${T} = vec4(0.);
|
|
}
|
|
|
|
xCOffset = xC + ${p};
|
|
if(xCOffset >= 0 && xCOffset < ${i}) {
|
|
xTexelR${_}C${T+2} = getX(batch, xR, xCOffset, d1);
|
|
} else {
|
|
xTexelR${_}C${T+2} = vec4(0.);
|
|
}
|
|
|
|
xR${_}C${T} = vec4(
|
|
xTexelR${_}C${T}.xy, xTexelR${_}C${T+2}.xy);
|
|
`,T+1<h&&(x+=`
|
|
xR${_}C${T+1} = vec4(
|
|
xTexelR${_}C${T}.zw, xTexelR${_}C${T+2}.zw);
|
|
`)),x+="}");T<h&&(x+=`
|
|
vec4 wTexelR${_}C${T} = getW(${_}, ${T}, d1, q);
|
|
wR${_}C${T} = vec4(wTexelR${_}C${T}.xz, wTexelR${_}C${T}.xz);
|
|
`,T+1<h&&(x+=`
|
|
vec4 wTexelR${_}C${T+1} = getW(${_}, ${T+1}, d1, q);
|
|
wR${_}C${T+1} =
|
|
vec4(wTexelR${_}C${T+1}.xz, wTexelR${_}C${T+1}.xz);`))}for(let _=0;_<d;_++)for(let D=0;D<h;D++)x+=`dotProd += xR${_}C${D} * wR${_}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.);
|
|
|
|
${x}
|
|
|
|
vec4 result = dotProd;
|
|
${k}
|
|
${w}
|
|
setOutput(result);
|
|
}
|
|
`}};function AX(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,filter:s}=e,{strides:a,pad:i,dilations:l,dimRoundingMode:u}=o,c=l;c==null&&(c=[1,1]),y.assert(N.eitherStridesOrDilationsAreOne(a,c),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${a} and dilations '${c}'`);let p=N.computeConv2DInfo(n.shape,s.shape,a,c,i,u,!0),m;return 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 Y2={kernelName:tn,backendName:"webgl",kernelFunc:AX};var fv=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);
|
|
}
|
|
`}},dv=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 EX(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 fv(p);return t.runWebGLProgram(m,[n,s],"float32")}var Z2={kernelName:ql,backendName:"webgl",kernelFunc:EX};function DX(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 dv(p);return t.runWebGLProgram(m,[n,s],"float32")}var J2={kernelName:Kl,backendName:"webgl",kernelFunc:DX};var hv=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 $X(r){let{inputs:e,backend:t}=r,{x:o}=e,n=[...o.shape,...o.shape],s=y.sizeFromShape(o.shape),a=pe({inputs:{x:o},backend:t,attrs:{shape:[s]}}),i=new hv(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 Q2={kernelName:Xl,backendName:"webgl",kernelFunc:$X};var gv=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 RX(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 gv(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 eD={kernelName:sa,backendName:"webgl",kernelFunc:RX};var FX="return (x >= 0.0) ? x : (exp(x) - 1.0);",OX=`
|
|
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;
|
|
`,PX=ke({opSnippet:FX,packedOpSnippet:OX}),tD={kernelName:oi,backendName:"webgl",kernelFunc:PX};var MX="return (b >= 1.0) ? a : a * (b + 1.0);",LX=`
|
|
vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));
|
|
return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));
|
|
`,zX=r=>{let{inputs:e,backend:t}=r,{dy:o,y:n}=e,s=W().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Ps(LX,o.shape,n.shape):new Xn(MX,o.shape,n.shape);return t.runWebGLProgram(s,[o,n],o.dtype)},rD={kernelName:Yl,backendName:"webgl",kernelFunc:zX};var BX=`
|
|
return vec4(equal(a, b));
|
|
`,VX="return float(a == b);",GX=nt({opSnippet:VX,packedOpSnippet:BX,dtype:"bool"}),oD={kernelName:si,backendName:"webgl",kernelFunc:GX};var WX=`
|
|
// 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));
|
|
`,jX=ke({opSnippet:WX}),nD={kernelName:ni,backendName:"webgl",kernelFunc:jX};var sD="return exp(x);",xv=ke({opSnippet:sD,packedOpSnippet:sD,cpuKernelImpl:oE}),iD={kernelName:on,backendName:"webgl",kernelFunc:xv};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&&(y.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 aD={kernelName:us,backendName:"webgl",kernelFunc:Yg};var lD="return exp(x) - 1.0;",UX=ke({opSnippet:lD,packedOpSnippet:lD,cpuKernelImpl:nE}),uD={kernelName:ii,backendName:"webgl",kernelFunc:UX};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=y.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 HX(r){let{inputs:e,backend:t}=r,{input:o}=e;return Jg(o,!1,t)}var cD={kernelName:Zl,backendName:"webgl",kernelFunc:HX};var yv=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||y.inferDtype(n),s==="string"){let a=y.getArrayFromDType(s,y.sizeFromShape(o));return a.fill(n),e.makeTensorInfo(o,s,a)}else{let a=new yv(o,n),i=a.getCustomSetupFunc(n);return e.runWebGLProgram(a,[],s,i)}}var pD={kernelName:ia,backendName:"webgl",kernelFunc:Tf};var bv=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 mD={kernelName:ai,backendName:"webgl",kernelFunc:({inputs:r,backend:e})=>{let{image:t}=r,o=e,n=new bv(t.shape);return o.runWebGLProgram(n,[t],t.dtype)}};var fD="return floor(x);",qX=ke({opSnippet:fD,packedOpSnippet:fD,cpuKernelImpl:sE}),dD={kernelName:nn,backendName:"webgl",kernelFunc:qX};var KX=`
|
|
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;
|
|
}
|
|
`,XX=`
|
|
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);
|
|
`,YX=nt({opSnippet:KX,packedOpSnippet:XX,dtype:"int32"}),hD={kernelName:sn,backendName:"webgl",kernelFunc:YX};var wv=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 kv=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 gD={kernelName:Pc,backendName:"webgl",kernelFunc:ZX},kp;function ZX(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)&&(kp==null&&(kp=document.createElement("canvas").getContext("2d")),kp.canvas.width=l,kp.canvas.height=u,kp.drawImage(n,0,0,l,u),n=kp.canvas);let m=t.makeTensorInfo(c,"int32");t.texData.get(m.dataId).usage=Dr.PIXELS,t.gpgpu.uploadPixelDataToTexture(t.getTexture(m.dataId),n);let f=W().getBool("WEBGL_PACK")?new kv(p):new wv(p),d=t.runWebGLProgram(f,[m],"int32");return t.disposeData(m.dataId),d}function JX(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,filter:s,bias:a,preluActivationWeights:i}=e,{strides:l,pad:u,dataFormat:c,dilations:p,dimRoundingMode:m,activation:f,leakyreluAlpha:d}=o,h=N.convertConv2DDataFormat(c),g=N.computeConv2DInfo(n.shape,s.shape,l,p,u,m,!1,h),x,b=[];if(g.filterHeight===1&&g.filterWidth===1&&g.dilationHeight===1&&g.dilationWidth===1&&g.strideHeight===1&&g.strideWidth===1&&(g.padInfo.type==="SAME"||g.padInfo.type==="VALID"))x=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)x=Kg({x:n,filter:s,convInfo:g,backend:t,bias:a,activation:f,preluActivationWeights:i,leakyreluAlpha:d});else{let k=a!=null,_=i!=null,D=f==="leakyrelu",T=f?gl(f,!1):null,R=new If(g,k,T,_,D),O=[n,s];if(a&&O.push(a),i&&O.push(i),D){let M=t.makeTensorInfo([],"float32",y.createScalarValue(d,"float32"));O.push(M),b.push(M)}x=t.runWebGLProgram(R,O,"float32")}let w=pe({inputs:{x},backend:t,attrs:{shape:g.outShape}});return b.push(x),b.forEach(k=>t.disposeIntermediateTensorInfo(k)),w}var xD={kernelName:ks,backendName:"webgl",kernelFunc:JX};function QX(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,filter:s,bias:a,preluActivationWeights:i}=e,{strides:l,pad:u,dilations:c,dimRoundingMode:p,activation:m,leakyreluAlpha:f}=o,d=[],h=c;h==null&&(h=[1,1]),y.assert(N.eitherStridesOrDilationsAreOne(l,h),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${l} and dilations '${h}'`);let g=N.computeConv2DInfo(n.shape,s.shape,l,h,u,p,!0),x=W().getBool("WEBGL_PACK_DEPTHWISECONV")&&g.strideWidth<=2&&g.outChannels/g.inChannels==1,b=m?gl(m,x):null,w=[n,s],k=a!=null,_=i!=null,D=m==="leakyrelu";if(k&&w.push(a),_&&w.push(i),D){let O=t.makeTensorInfo([],"float32",y.createScalarValue(f,"float32"));w.push(O),d.push(O)}let T;x?T=new Sf(g,k,b,_,D):T=new Nf(g,k,b,_,D);let R=t.runWebGLProgram(T,w,"float32");return d.forEach(O=>t.disposeIntermediateTensorInfo(O)),R}var yD={kernelName:_s,backendName:"webgl",kernelFunc:QX};var _v=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 e8(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:[y.sizeFromShape(o.shape)/u,u]}}),f=new _v(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 bD={kernelName:li,backendName:"webgl",kernelFunc:e8};var vv=class{constructor(e,t){this.variableNames=["A","indices"],this.outputShape=t,this.rank=t.length;let o=Le(this.rank),n=t8(e,2);this.userCode=`
|
|
void main() {
|
|
${o} resRC = getOutputCoords();
|
|
setOutput(getA(${n}));
|
|
}
|
|
`}};function t8(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 r8(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,indices:s}=e,{axis:a,batchDims:i}=o,l=y.parseAxisParam(a,n.shape)[0],u=N.segment_util.collectGatherOpShapeInfo(n,s,l,i),c=y.sizeFromShape(s.shape),p=[],m=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=iE(w,b,d);return p.forEach(_=>t.disposeIntermediateTensorInfo(_)),t.makeTensorInfo(u.outputShape,k.dtype,k.values)}let h=new vv(m.shape,d),g=t.runWebGLProgram(h,[m,f],m.dtype);p.push(g);let x=pe({inputs:{x:g},backend:t,attrs:{shape:u.outputShape}});return p.forEach(b=>t.disposeIntermediateTensorInfo(b)),x}var wD={kernelName:cs,backendName:"webgl",kernelFunc:r8};var o8="return float(a > b);",n8=`
|
|
return vec4(greaterThan(a, b));
|
|
`,s8=nt({opSnippet:o8,packedOpSnippet:n8,cpuKernelImpl:aE,dtype:"bool"}),kD={kernelName:ui,backendName:"webgl",kernelFunc:s8};var i8="return float(a >= b);",a8=`
|
|
return vec4(greaterThanEqual(a, b));
|
|
`,l8=nt({opSnippet:i8,packedOpSnippet:a8,dtype:"bool"}),_D={kernelName:ln,backendName:"webgl",kernelFunc:l8};function u8(r){let{inputs:e,backend:t}=r,{input:o}=e;return Jg(o,!0,t)}var vD={kernelName:Jl,backendName:"webgl",kernelFunc:u8};var c8="return float(!isnan(x) && !isinf(x));",p8=ke({opSnippet:c8,dtype:"bool"}),CD={kernelName:ci,backendName:"webgl",kernelFunc:p8};var m8="return float(isinf(x));",f8=ke({opSnippet:m8,dtype:"bool"}),ID={kernelName:pi,backendName:"webgl",kernelFunc:f8};var d8="return float(isnan(x));",h8=ke({opSnippet:d8,dtype:"bool"}),ND={kernelName:mi,backendName:"webgl",kernelFunc:h8};var g8="return float(a < b);",x8=`
|
|
return vec4(lessThan(a, b));
|
|
`,y8=nt({opSnippet:g8,packedOpSnippet:x8,cpuKernelImpl:lE,dtype:"bool"}),SD={kernelName:fi,backendName:"webgl",kernelFunc:y8};var b8="return float(a <= b);",w8=`
|
|
return vec4(lessThanEqual(a, b));
|
|
`,k8=nt({opSnippet:b8,packedOpSnippet:w8,dtype:"bool"}),TD={kernelName:di,backendName:"webgl",kernelFunc:k8};function _8(r){let{backend:e,attrs:t}=r,{start:o,stop:n,num:s}=t,a=uE(o,n,s);return e.makeTensorInfo([a.length],"float32",a)}var AD={kernelName:eu,backendName:"webgl",kernelFunc:_8};var v8=`if (x < 0.0) return NAN;
|
|
return log(x);`,C8=`
|
|
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;
|
|
`,I8=ke({opSnippet:v8,packedOpSnippet:C8,cpuKernelImpl:cE}),ED={kernelName:cn,backendName:"webgl",kernelFunc:I8};var N8="return log(1.0 + x);",S8=ke({opSnippet:N8}),DD={kernelName:hi,backendName:"webgl",kernelFunc:S8};var T8="return float(a >= 1.0 && b >= 1.0);",A8=`
|
|
return vec4(
|
|
vec4(greaterThanEqual(a, vec4(1.0))) *
|
|
vec4(greaterThanEqual(b, vec4(1.0))));
|
|
`,E8=nt({opSnippet:T8,packedOpSnippet:A8,dtype:"bool"}),$D={kernelName:gi,backendName:"webgl",kernelFunc:E8};var D8="return float(!(x >= 1.0));",$8=ke({opSnippet:D8}),RD={kernelName:Ja,backendName:"webgl",kernelFunc:$8};var R8="return float(a >= 1.0 || b >= 1.0);",F8=`
|
|
return min(
|
|
vec4(greaterThanEqual(a, vec4(1.0))) +
|
|
vec4(greaterThanEqual(b, vec4(1.0))),
|
|
vec4(1.0));
|
|
`,O8=nt({opSnippet:R8,packedOpSnippet:F8,dtype:"bool"}),FD={kernelName:Qa,backendName:"webgl",kernelFunc:O8};var Cv=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 Iv=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 P8=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 Iv(n.shape,s,a,i,l):new Cv(n.shape,s,a,i,l);return t.runWebGLProgram(u,[n],n.dtype)},OD={kernelName:aa,backendName:"webgl",kernelFunc:P8};var Nv=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 M8=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 Nv(n.shape,i,l,u,c);return t.runWebGLProgram(p,[n,s,a],n.dtype)},PD={kernelName:tu,backendName:"webgl",kernelFunc:M8};function MD(r,e,t,o){let n=y.sizeFromShape(e),a=y.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 Sv(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{reductionIndices:s,keepDims:a}=o,i=n.shape.length,l=y.parseAxisParam(s,n.shape),u=l,c=N.getAxesPermutation(u,i),p=c!=null,m=t.shouldExecuteOnCPU([n]),f=n;if(p){if(m){let w=t.texData.get(f.dataId).values,k=new Array(i);for(let T=0;T<k.length;T++)k[T]=n.shape[c[T]];let _=wp(w,n.shape,n.dtype,c,k);f=t.makeTensorInfo(k,n.dtype);let D=t.texData.get(f.dataId);D.values=_}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 x;if(m){let w=t.texData.get(f.dataId).values,k=pE(w,y.sizeFromShape(h),g,n.dtype);x=t.makeTensorInfo(g,n.dtype);let _=t.texData.get(x.dataId);_.values=k}else x=MD(f,h,g,t);return p&&t.disposeIntermediateTensorInfo(f),x}var LD={kernelName:pn,backendName:"webgl",kernelFunc:Sv};var L8=Bg+`
|
|
return max(a, b);
|
|
`,z8=`
|
|
vec4 result = vec4(max(a, b));
|
|
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
|
|
`+hl+`
|
|
return result;
|
|
`,B8=nt({opSnippet:L8,packedOpSnippet:z8,cpuKernelImpl:mE}),zD={kernelName:mn,backendName:"webgl",kernelFunc:B8};function V8(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;y.assert(N.eitherStridesOrDilationsAreOne(a,u),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${u}'`);let c=N.computePool2DInfo(n.shape,s,a,u,i,l);if(c.filterWidth===1&&c.filterHeight===1&&y.arraysEqual(c.inShape,c.outShape))return jt({inputs:{x:n},backend:t});let p=new Vi(c,"max",!1);return t.runWebGLProgram(p,[n],n.dtype)}var BD={kernelName:fn,backendName:"webgl",kernelFunc:V8};function G8(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 VD={kernelName:la,backendName:"webgl",kernelFunc:G8};var Tv=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);
|
|
}
|
|
`}},Av=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 W8(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 Av(m),g=t.runWebGLProgram(h,[n,d],a.dtype);return t.disposeIntermediateTensorInfo(d),g}var GD={kernelName:ou,backendName:"webgl",kernelFunc:W8};function j8(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 Tv(m),x=t.runWebGLProgram(g,[n,h],i.dtype);return t.disposeIntermediateTensorInfo(h),x}var WD={kernelName:ru,backendName:"webgl",kernelFunc:j8};function jD(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 UD={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;y.assert(o.shape.length===4,()=>`Error in maxPool: input must be rank 4 but got rank ${o.shape.length}.`);let u=[1,1];y.assert(N.eitherStridesOrDilationsAreOne(s,u),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${s} and dilations '${u}'`);let c=N.computePool2DInfo(o.shape,n,s,u,a),[p,m]=jD(o,i,c,l);return[p,m]}};function HD(r,e,t,o){let n=y.sizeFromShape(e),a=y.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 qD={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=y.parseAxisParam(s,o.shape),u=l,c=N.getAxesPermutation(u,i),p=c!=null,m=a.shouldExecuteOnCPU([o]),f=[],d=o;if(p){if(m){let k=a.texData.get(d.dataId).values,_=new Array(i);for(let R=0;R<_.length;R++)_[R]=o.shape[c[R]];let D=wp(k,o.shape,o.dtype,c,_);d=a.makeTensorInfo(_,o.dtype);let T=a.texData.get(d.dataId);T.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),x=h;n&&(x=N.expandShapeToKeepDim(h,l));let b=HD(d,g,x,a);for(let w of f)a.disposeIntermediateTensorInfo(w);return b}};function U8(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{axis:s,keepDims:a}=o,i=n.shape.length,l=y.parseAxisParam(s,n.shape),u=l,c=N.getAxesPermutation(u,i),p=n;c!=null&&(p=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=y.sizeFromShape(f),h=pe({inputs:{x:p},backend:t,attrs:{shape:[-1,d]}}),g=No(h,h.dtype,"min",t),x;if(a){let b=N.expandShapeToKeepDim(m,l);x=pe({inputs:{x:g},backend:t,attrs:{shape:b}})}else x=pe({inputs:{x:g},backend:t,attrs:{shape:m}});return t.disposeIntermediateTensorInfo(h),t.disposeIntermediateTensorInfo(g),c!=null&&t.disposeIntermediateTensorInfo(p),x}var KD={kernelName:hn,backendName:"webgl",kernelFunc:U8};var H8=Bg+`
|
|
return min(a, b);
|
|
`,q8=`
|
|
vec4 result = vec4(min(a, b));
|
|
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
|
|
`+hl+`
|
|
return result;
|
|
`,K8=nt({opSnippet:H8,packedOpSnippet:q8,cpuKernelImpl:fE}),XD={kernelName:gn,backendName:"webgl",kernelFunc:K8};var Ev=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 Dv=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 X8=({inputs:r,backend:e,attrs:t})=>{let{x:o}=r,{paddings:n,mode:s}=t,a=W().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Dv(o.shape,n,s):new Ev(o.shape,n,s);return e.runWebGLProgram(a,[o],o.dtype)},YD={kernelName:ua,backendName:"webgl",kernelFunc:X8};var Y8=`if (b == 0.0) return NAN;
|
|
return mod(a, b);`,Z8=`
|
|
vec4 result = mod(a, b);
|
|
vec4 isNaN = vec4(equal(b, vec4(0.0)));
|
|
`+hl+`
|
|
return result;
|
|
`,J8=nt({opSnippet:Y8,packedOpSnippet:Z8}),ZD={kernelName:xi,backendName:"webgl",kernelFunc:J8};var $v=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 Q8=`
|
|
if (a == b) {
|
|
return 1.0;
|
|
};
|
|
return a / b;`,eY=`
|
|
// 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;
|
|
`,Rv=nt({opSnippet:Q8,packedOpSnippet:eY,checkOutOfBounds:!0}),JD={kernelName:rn,backendName:"webgl",kernelFunc:Rv};var QD="return a - b;",Fv=nt({opSnippet:QD,packedOpSnippet:QD,supportsComplex:!0,cpuKernelImpl:kE}),e$={kernelName:Fn,backendName:"webgl",kernelFunc:Fv};function Ov(r){let{inputs:e,backend:t,attrs:o}=r,{logits:n}=e,{dim:s}=o,a=y.parseAxisParam([s],n.shape),i=Sv({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=Fv({inputs:{a:n,b:u},backend:t}),p=xv({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=Rv({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 t$={kernelName:$n,backendName:"webgl",kernelFunc:Ov};function tY(r){let{inputs:e,backend:t,attrs:o}=r,{logits:n}=e,{numSamples:s,seed:a,normalized:i}=o,l=i?n:Ov({inputs:{logits:n},backend:t,attrs:{dim:n.shape.length-1}}),u=l.shape[0],c=l.shape[1],p=new $v(u,c,s),m=p.getCustomSetupFunc(a),f=t.runWebGLProgram(p,[l],"int32",m);return i||t.disposeIntermediateTensorInfo(l),f}var r$={kernelName:su,backendName:"webgl",kernelFunc:tY};var o$="return -x;";function rY(r){let{inputs:e,backend:t}=r,{x:o}=e;if(t.shouldExecuteOnCPU([o])){let s=t.texData.get(o.dataId),[a,i]=hE(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,o$):n=new ao(o.shape,o$),t.runWebGLProgram(n,[o],o.dtype)}var n$={kernelName:ps,backendName:"webgl",kernelFunc:rY};var oY=Ar.nonMaxSuppressionV3Impl;function nY(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}=oY(u,c,a,i,l);return t.makeTensorInfo([p.length],"int32",new Int32Array(p))}var s$={kernelName:bi,backendName:"webgl",kernelFunc:nY};var sY=Ar.nonMaxSuppressionV4Impl;function iY(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}=sY(c,p,a,i,l,u);return[t.makeTensorInfo([m.length],"int32",new Int32Array(m)),t.makeTensorInfo([],"int32",new Int32Array([f]))]}var i$={kernelName:wi,backendName:"webgl",kernelFunc:iY};var aY=Ar.nonMaxSuppressionV5Impl;function lY(r){N.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:e,backend:t,attrs:o}=r,{boxes:n,scores:s}=e,{maxOutputSize:a,iouThreshold:i,scoreThreshold:l,softNmsSigma:u}=o,c=t.readSync(n.dataId),p=t.readSync(s.dataId),m=a,f=i,d=l,h=u,{selectedIndices:g,selectedScores:x}=aY(c,p,m,f,d,h);return[t.makeTensorInfo([g.length],"int32",new Int32Array(g)),t.makeTensorInfo([x.length],"float32",new Float32Array(x))]}var a$={kernelName:ki,backendName:"webgl",kernelFunc:lY};var Pv=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 uY=r=>{let{inputs:e,backend:t,attrs:o}=r,{indices:n}=e,{depth:s,onValue:a,offValue:i}=o,l=y.sizeFromShape(n.shape),u=new Pv(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},l$={kernelName:yn,backendName:"webgl",kernelFunc:uY};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 u$={kernelName:bs,backendName:"webgl",kernelFunc:Af};function c$(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=c$({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 p$={kernelName:ms,backendName:"webgl",kernelFunc:c$};function cY(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=>{y.assertShapesMatch(s,c.shape,"All tensors passed to stack must have matching shapes"),y.assert(a===c.dtype,()=>"All tensors passed to stack must have matching dtypes")});let i=[],l=e.map(c=>{let p=Yg({inputs:{input:c},backend:t,attrs:{dim:n}});return i.push(p),p}),u=nv({inputs:l,backend:t,attrs:{axis:n}});return i.forEach(c=>t.disposeIntermediateTensorInfo(c)),u}var m$={kernelName:fs,backendName:"webgl",kernelFunc:cY};var Mv=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 Lv=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 zv=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 Lv(n.shape,s,a):new Mv(n.shape,s,a),l=i.getCustomSetupFunc(a);return t.runWebGLProgram(i,[n],n.dtype,l)},f$={kernelName:bn,backendName:"webgl",kernelFunc:zv};var pY=`
|
|
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);
|
|
`,mY=`
|
|
// 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;
|
|
`,fY=nt({opSnippet:pY,packedOpSnippet:mY}),d$={kernelName:wn,backendName:"webgl",kernelFunc:fY};function dY(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{axis:s,keepDims:a}=o,i=n.shape.length,l=[],u=y.parseAxisParam(s,n.shape),c=u,p=N.getAxesPermutation(c,i),m=n;p!=null&&(m=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:x}=gE(m.shape,m.dtype,d,c);f=t.makeTensorInfo(g,x,h)}else{let[d,h]=N.computeOutAndReduceShapes(m.shape,c),g=y.sizeFromShape(h),x=pe({inputs:{x:m},backend:t,attrs:{shape:[-1,g]}}),b=fu(n.dtype),w=No(x,b,"prod",t);f=pe({inputs:{x:w},backend:t,attrs:{shape:d}}),l.push(x),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 h$={kernelName:_i,backendName:"webgl",kernelFunc:dY};var Bv=r=>{let{backend:e,attrs:t}=r,{start:o,stop:n,step:s,dtype:a}=t,i=xE(o,n,s,a);return e.makeTensorInfo([i.length],a,i)},g$={kernelName:ca,backendName:"webgl",kernelFunc:Bv};var hY="return 1.0 / x;",gY=ke({opSnippet:hY}),x$={kernelName:vi,backendName:"webgl",kernelFunc:gY};var xY=gr+`
|
|
return (x < 0.0) ? 0.0 : x;
|
|
`,yY=`
|
|
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;
|
|
`,bY=ke({opSnippet:xY,packedOpSnippet:yY}),y$={kernelName:_n,backendName:"webgl",kernelFunc:bY};var wY=gr+`
|
|
return (x < 0.0) ? 0.0 : min(6.0, x);
|
|
`,kY=`
|
|
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;
|
|
`,_Y=ke({opSnippet:wY,packedOpSnippet:kY}),b$={kernelName:Cn,backendName:"webgl",kernelFunc:_Y};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;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 Gv=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 vY(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 Gv(n.shape,l,u,s,a):new Vv(n.shape,l,u,s,a);return t.runWebGLProgram(c,[n],"float32")}var w$={kernelName:vn,backendName:"webgl",kernelFunc:vY};var Wv=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 CY(r){let{inputs:e,backend:t,attrs:o}=r,{images:n,dy:s}=e,{alignCorners:a}=o,i=new Wv(s.shape,n.shape,a);return t.runWebGLProgram(i,[s],s.dtype)}var k$={kernelName:lu,backendName:"webgl",kernelFunc:CY};var jv=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 IY(r){let{inputs:e,backend:t,attrs:o}=r,{images:n}=e,{alignCorners:s,halfPixelCenters:a,size:i}=o,[l,u]=i,c=new jv(n.shape,l,u,s,a);return t.runWebGLProgram(c,[n],n.dtype)}var _$={kernelName:pa,backendName:"webgl",kernelFunc:IY};var Uv=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 NY(r){let{inputs:e,backend:t,attrs:o}=r,{images:n,dy:s}=e,{alignCorners:a}=o,i=new Uv(s.shape,n.shape,a);return t.runWebGLProgram(i,[s],s.dtype)}var v$={kernelName:au,backendName:"webgl",kernelFunc:NY};var Hv=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 qv=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(","),x=h.slice(-2).join(",");return`getChannel(getX(${g}), vec2(${x}))`}function f(d,h){return t.indexOf(d)!==-1&&e[d]!==1?`${e[d]} - ${h[d]} - 1`:`${h[d]}`}}};function SY(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{dims:s}=o,a=n.shape.length,i=y.parseAxisParam(s,n.shape);if(a===0)return jt({inputs:{x:n},backend:t});let l=W().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new qv(n.shape,i):new Hv(n.shape,i);return t.runWebGLProgram(l,[n],n.dtype)}var C$={kernelName:In,backendName:"webgl",kernelFunc:SY};var Kv=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 I$={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 Kv(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 TY=`
|
|
// 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;
|
|
}
|
|
}
|
|
`,AY=ke({opSnippet:TY}),N$={kernelName:Nn,backendName:"webgl",kernelFunc:AY};var EY="return inversesqrt(x);",DY=ke({opSnippet:EY,cpuKernelImpl:yE}),S$={kernelName:Sn,backendName:"webgl",kernelFunc:DY};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 $Y(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),x=t.runWebGLProgram(g,[d,f,h],d.dtype),b=pe({inputs:{x},backend:t,attrs:{shape:a}});return t.disposeIntermediateTensorInfo(f),t.disposeIntermediateTensorInfo(d),t.disposeIntermediateTensorInfo(x),t.disposeIntermediateTensorInfo(h),b}var T$={kernelName:Ci,backendName:"webgl",kernelFunc:$Y};var Xv=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 RY(r){let{inputs:e,backend:t}=r,{condition:o,t:n,e:s}=e,a=new Xv(o.shape.length,n.shape,n.shape.length);return t.runWebGLProgram(a,[o,n,s],dr(n.dtype,s.dtype))}var A$={kernelName:hs,backendName:"webgl",kernelFunc:RY};var FY=`
|
|
// 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);
|
|
`,OY=ke({opSnippet:FY}),E$={kernelName:Ii,backendName:"webgl",kernelFunc:OY};var PY="return 1.0 / (1.0 + exp(-1.0 * x));",MY=ke({opSnippet:PY}),D$={kernelName:An,backendName:"webgl",kernelFunc:MY};var LY=`
|
|
if (isnan(x)) { return 0.0; }
|
|
return sign(x);
|
|
`,zY=ke({opSnippet:LY}),$$={kernelName:Si,backendName:"webgl",kernelFunc:zY};var BY=Vg+`
|
|
return sin(x);
|
|
`,VY=ke({opSnippet:BY}),R$={kernelName:Tn,backendName:"webgl",kernelFunc:VY};var GY=`
|
|
float e2x = exp(x);
|
|
return (e2x - 1.0 / e2x) / 2.0;
|
|
`,WY=ke({opSnippet:GY}),F$={kernelName:Ni,backendName:"webgl",kernelFunc:WY};var jY=`
|
|
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;
|
|
`,UY=ke({opSnippet:jY}),O$={kernelName:Ti,backendName:"webgl",kernelFunc:UY};var HY=r=>{let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{blockShape:s,paddings:a}=o;y.assert(n.shape.length<=4,()=>"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet");let i=s.reduce((x,b)=>x*b),l=[[0,0]];l.push(...a);for(let x=1+s.length;x<n.shape.length;++x)l.push([0,0]);let u=[],c=zv({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(x=>t.disposeIntermediateTensorInfo(x)),g},P$={kernelName:ma,backendName:"webgl",kernelFunc:HY};function qY(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 M$={kernelName:uu,backendName:"webgl",kernelFunc:qY};function KY(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{numOrSizeSplits:s,axis:a}=o,i=y.parseAxisParam(a,n.shape)[0],l=N.prepareSplitSize(n,s,i),u=n.shape.length,c=new Array(u).fill(0),p=n.shape.slice();return l.map(m=>{let f=[...p];f[i]=m;let d=Ma({inputs:{x:n},backend:t,attrs:{begin:c,size:f}});return c[i]+=m,d})}var L$={kernelName:xs,backendName:"webgl",kernelFunc:KY};var XY="return sqrt(x);",YY=ke({opSnippet:XY}),z$={kernelName:En,backendName:"webgl",kernelFunc:YY};var ZY="return x * x;",JY=ke({opSnippet:ZY}),B$={kernelName:fa,backendName:"webgl",kernelFunc:JY};var V$="return (a - b) * (a - b);",QY=nt({opSnippet:V$,packedOpSnippet:V$}),G$={kernelName:Rn,backendName:"webgl",kernelFunc:QY};function e7({inputs:r,attrs:e,backend:t}){let{x:o}=r,n=gr+`
|
|
return x > 0.0 ? 1.0 : float(${e.alpha});
|
|
`,s=new ao(o.shape,n);return t.runWebGLProgram(s,[o],o.dtype)}var W$={kernelName:Oo,backendName:"webgl",kernelFunc:e7};var Yv=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 t7(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{begin:s,end:a,strides:i,beginMask:l,endMask:u,ellipsisMask:c,newAxisMask:p,shrinkAxisMask:m}=o,{nonStrided:f,$begin:d,$strides:h,size:g,newShape:x,outShape:b}=sr.sliceInfo(n.shape,s,a,i,l,u,c,p,m),w=pe({inputs:{x:n},backend:t,attrs:{shape:x}}),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,O=ve(w.shape,w.dtype,R),M=wE(b,O,h,d);k=t.makeTensorInfo(b,w.dtype,M.values)}else{let T=new Yv(d,h,b);k=t.runWebGLProgram(T,[w],w.dtype)}let _=pe({inputs:{x:k},backend:t,attrs:{shape:b}});return t.disposeIntermediateTensorInfo(w),t.disposeIntermediateTensorInfo(k),_}var j$={kernelName:Ai,backendName:"webgl",kernelFunc:t7};var r7="return tan(x);",o7=ke({opSnippet:r7}),U$={kernelName:Ei,backendName:"webgl",kernelFunc:o7};var n7=`
|
|
float e2x = exp(-2.0 * abs(x));
|
|
return sign(x) * (1.0 - e2x) / (1.0 + e2x);
|
|
`,s7=ke({opSnippet:n7}),H$={kernelName:On,backendName:"webgl",kernelFunc:s7};var Zv=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=i7(e);this.userCode=`
|
|
void main() {
|
|
${n} resRC = getOutputCoords();
|
|
setOutput(getA(${s}));
|
|
}
|
|
`}};function i7(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 Jv(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{reps:s}=o;if(n.dtype==="string"){let u=t.readSync(n.dataId).map(m=>y.decodeString(m)),c=ve(n.shape,n.dtype,u),p=_E(c,s);return t.makeTensorInfo(p.shape,p.dtype,p.values)}let a=new Zv(n.shape,s);return t.runWebGLProgram(a,[n],n.dtype)}var q$={kernelName:ko,backendName:"webgl",kernelFunc:Jv};function a7(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{k:s,sorted:a}=o,i=t.readSync(n.dataId),[l,u]=vE(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 K$={kernelName:Di,backendName:"webgl",kernelFunc:a7};var Qv=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 l7(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],x=new Qv(p,m,a,i,l,g);return t.runWebGLProgram(x,[n,s],"float32")}var X$={kernelName:cu,backendName:"webgl",kernelFunc:l7};function u7(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}=CE(a,n,s.shape,s.dtype);return[o.makeTensorInfo(l,s.dtype,i),o.makeTensorInfo([u.length],"int32",u)]}var Y$={kernelName:pu,backendName:"webgl",kernelFunc:u7};function c7(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}}),x=pe({inputs:{x:g},backend:t,attrs:{shape:u}});d[h]=x,p.push(g)}return p.forEach(h=>t.disposeIntermediateTensorInfo(h)),d}var Z$={kernelName:ys,backendName:"webgl",kernelFunc:c7};var eC=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 p7(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=y.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,_,D,T,R)=>{let O=k.shape[0],M=k.shape[1],G=N.segment_util.segOpComputeOptimalWindowSize(M,R),j={windowSize:G,inSize:M,batchSize:O,numSegments:R},U=new eC(j,_),H=t.compileAndRun(U,[k,D],T);if(l.push(H),H.shape[1]===R)return H;let q=Bv({backend:t,attrs:{start:0,stop:R,step:1,dtype:"float32"}}),X=Jv({inputs:{x:q},backend:t,attrs:{reps:[M/G]}});return l.push(q),l.push(X),g(H,_,X,T,R)},x=g(d,"unsortedSegmentSum",s,h,a),b=pe({inputs:{x},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 J$={kernelName:da,backendName:"webgl",kernelFunc:p7};var m7=[OD,PD,YE,JE,QE,e2,r2,o2,n2,s2,l2,u2,c2,p2,f2,m2,d2,g2,h2,x2,y2,b2,w2,_2,v2,S2,A2,E2,$2,LE,O2,M2,L2,P2,B2,V2,z2,G2,W2,j2,q2,K2,X2,Z2,J2,Y2,Q2,eD,tD,rD,oD,nD,iD,aD,uD,cD,pD,mD,dD,hD,gD,xD,yD,bD,wD,kD,_D,ME,vD,R2,CD,ID,ND,zE,SD,TD,AD,DD,ED,$D,RD,FD,LD,VD,BD,GD,WD,UD,zD,qD,KD,XD,YD,ZD,r$,jE,n$,s$,i$,a$,C2,l$,p$,m$,f$,d$,BE,h$,g$,I2,JD,x$,b$,y$,HE,w$,k$,_$,v$,C$,I$,N$,S$,T$,A$,E$,D$,$$,R$,F$,k2,t$,O$,P$,M$,L$,z$,B$,G$,W$,j$,e$,KE,U$,H$,q$,K$,X$,XE,Y$,Z$,J$,u$];for(let r of m7)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 Q$;function f7(r){Q$=r.wasm.cwrap(ws,null,["number","array","number","number","array","number","number","number","number","number","number","number","number"])}function d7(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 x=l?n.shape[2]:n.shape[1],b=u?s.shape[1]:s.shape[2],w=n.shape[0],k=t.makeOutput([w,x,b],n.dtype),_=t.dataIdMap.get(k.dataId).id,D=new Uint8Array(new Int32Array(n.shape).buffer),T=new Uint8Array(new Int32Array(s.shape).buffer);return Q$(m,D,n.shape.length,f,T,s.shape.length,l,u,g,d,h,p||0,_),k}var eR={kernelName:ws,backendName:"wasm",setupFunc:f7,kernelFunc:d7};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 y.sizeFromShape(l.shape)===0||e(i,u),l}return{kernelName:r,backendName:"wasm",setupFunc:t,kernelFunc:o}}var tR=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(y.sizeFromShape(d)===0)return h;let g=new Uint8Array(new Int32Array(u.shape).buffer),x=new Uint8Array(new Int32Array(c.shape).buffer),b=i.dataIdMap.get(h.dataId).id,w=()=>o(p,g,u.shape.length,m,x,c.shape.length,Lt[u.dtype],b);if(e&&u.dtype==="float32")return w(),h;let k=N.getBroadcastDims(u.shape,d),_=N.getBroadcastDims(c.shape,d),D=k.every((R,O)=>R===O),T=_.every((R,O)=>R===O);if(D&&T)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 h7=!0,rR=xt(wo,h7);var oR;function g7(r){oR=r.wasm.cwrap(Ho,null,["array","number","number","number"])}function x7(r){let{inputs:e,backend:t}=r,o=t.makeOutput(e[0].shape,e[0].dtype);if(y.sizeFromShape(o.shape)===0)return o;let n=e.map(i=>t.dataIdMap.get(i.dataId).id),s=new Uint8Array(new Int32Array(n).buffer),a=t.dataIdMap.get(o.dataId).id;return oR(s,n.length,Lt[o.dtype],a),o}var nR={kernelName:Ho,backendName:"wasm",setupFunc:g7,kernelFunc:x7};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 sR={kernelName:Fo,backendName:"wasm",kernelFunc:rc};var iR;function y7(r){iR=r.wasm.cwrap(Pn,null,["number","array","number","number","number","array","number"])}function _p(r){let{inputs:e,backend:t,attrs:o}=r,[n,s]=w7(e.x.shape,o.perm),a=!0;for(let d=0;d<s.length;d++)s[d]!==d&&(a=!1);let i=b7(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 iR(c,f,l.shape.length,Lt[l.dtype],p,m,s.length),u}function b7(r,e){let t=new Array(r.length);for(let o=0;o<t.length;o++)t[o]=r[e[o]];return t}function w7(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 aR={kernelName:Pn,backendName:"wasm",kernelFunc:_p,setupFunc:y7};function Yn(r,e,t){let o=r.shape,n=r.shape.length,s=y.parseAxisParam(e,o),a=s,i=N.getAxesPermutation(a,n),l=null,u=!1;if(i!=null){let c=new Array(n);for(let f=0;f<c.length;f++)c[f]=o[i[f]];a=N.getInnerMostAxes(a.length,n),l=_p({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 lR;function k7(r){lR=r.wasm.cwrap(qo,null,["number","number","number","number","number"])}function _7(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 x=e.dataIdMap.get(u.dataId).id;x!==a&&(l=u,i=x)}let m=l.shape.slice(0,-1),f=e.makeOutput(m,"int32"),d=e.dataIdMap.get(f.dataId).id,h=y.sizeFromShape(f.shape),g=l.shape[c[0]];return lR(i,Lt[l.dtype],h,g,d),p&&e.disposeData(u.dataId),f}var uR={kernelName:qo,backendName:"wasm",kernelFunc:_7,setupFunc:k7};var cR;function v7(r){cR=r.wasm.cwrap(Ko,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function C7(r){let{inputs:e,attrs:t,backend:o}=r,n=e.x,s=o.dataIdMap.get(n.dataId).id,{filterSize:a,strides:i,pad:l,dimRoundingMode:u}=t,c=N.computePool2DInfo(n.shape,a,i,1,l,u),p=c.filterHeight,m=c.filterWidth,f=c.padInfo.top,d=c.padInfo.right,h=c.padInfo.bottom,g=c.padInfo.left,x=c.strideHeight,b=c.strideWidth,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"),_=o.dataIdMap.get(k.dataId).id;return cR(s,n.shape[0],n.shape[1],n.shape[2],p,m,f,d,h,g,x,b,w,_),k}var pR={kernelName:Ko,backendName:"wasm",setupFunc:v7,kernelFunc:C7};function Mr(r){let{inputs:e,attrs:t}=r,{x:o}=e,{shape:n}=t,s=y.sizeFromShape(o.shape),a=y.inferFromImplicitShape(n,s);return y.assert(s===y.sizeFromShape(a),()=>`new shape: ${a}, old shape: ${o.shape}. New shape and old shape must have the same number of elements.`),r.backend.incRef(o.dataId),{dataId:o.dataId,shape:a,dtype:o.dtype}}var mR={kernelName:ds,backendName:"wasm",kernelFunc:Mr};var fR;function I7(r){fR=r.wasm.cwrap(Xo,null,["number","array","number","number","array","number","number","number","number"])}function N7(r){let{inputs:e,backend:t,attrs:o}=r,{a:n,b:s}=e,{transposeA:a,transposeB:i}=o;if(n.dtype!=="float32"||s.dtype!=="float32")throw new Error("BatchMatMul for non non-float32 tensors not yet supported.");let l=n.shape.length,u=s.shape.length,c=a?n.shape[l-2]:n.shape[l-1],p=i?s.shape[u-1]:s.shape[u-2],m=a?n.shape[l-1]:n.shape[l-2],f=i?s.shape[u-2]:s.shape[u-1],d=n.shape.slice(0,-2),h=s.shape.slice(0,-2),g=y.sizeFromShape(d),x=y.sizeFromShape(h),b=g===x||g===1||x===1;y.assert(l>=2&&u>=2&&b,()=>`Error in matMul: the input batch dimensions must either be the same or at least one input batch dimension must be 1. Got input batch dimensions of (${d}) and (${h}).`);let k=(g>x?n.shape.slice(0,-2):s.shape.slice(0,-2)).concat([m,f]);y.assert(c===p,()=>`Error in matMul: inner shapes (${c}) and (${p}) of Tensors with shapes ${n.shape} and ${s.shape} and transposeA=${a} and transposeB=${i} must match.`);let _=a?[g,c,m]:[g,m,c],D=i?[x,f,p]:[x,p,f],T=Mr({inputs:{x:n},backend:t,attrs:{shape:_}}),R=Mr({inputs:{x:s},backend:t,attrs:{shape:D}}),O=t.dataIdMap.get(T.dataId).id,M=t.dataIdMap.get(R.dataId).id,G=a?T.shape[2]:T.shape[1],j=i?R.shape[1]:R.shape[2],U=Math.max(g,x),H=t.makeOutput([U,G,j],T.dtype),q=t.dataIdMap.get(H.dataId).id,X=new Uint8Array(new Int32Array(T.shape).buffer),oe=new Uint8Array(new Int32Array(R.shape).buffer);return fR(O,X,T.shape.length,M,oe,R.shape.length,a,i,q),t.disposeData(T.dataId),t.disposeData(R.dataId),H.shape=k,H}var dR={kernelName:Xo,backendName:"wasm",setupFunc:I7,kernelFunc:N7};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 hR={kernelName:$o,backendName:"wasm",kernelFunc:oc};var gR=Nt(Yo);var xR;function S7(r){xR=r.wasm.cwrap(Ro,null,["number","number","number","number"])}function T7(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 xR(i,s,a,u),l}var yR={kernelName:Ro,backendName:"wasm",setupFunc:S7,kernelFunc:T7};function tC(r){let{inputs:e,backend:t}=r,o=y.parseAxisParam(r.attrs.axis,e[0].shape)[0],n=N.computeOutShape(e.map(f=>f.shape),o),s=e.filter(f=>y.sizeFromShape(f.shape)>0);if(s.length===1)return rc({inputs:{x:s[0]},backend:t});let a=t.makeOutput(n,e[0].dtype);if(y.sizeFromShape(n)===0)return a;let i=s.map(f=>f.shape);if(N.assertParamsConsistent(i,o),s[0].dtype==="string"){let f=s.map(w=>{let k=y.sizeFromShape(w.shape.slice(o));return Mr({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),x=N.computeOutShape(s.map(w=>w.shape),o);a.shape=x;let b=t.dataIdMap.get(a.dataId);return b.stringBytes=N.fromStringArrayToUint8(g),f.forEach(w=>t.disposeData(w.dataId)),a}let l=y.sizeFromShape(s[0].shape.slice(0,o)),u=0,c=s.map(f=>{let d=y.sizeFromShape(f.shape.slice(o));return u+=d,d}),p=s.map(f=>t.typedArrayFromHeap(f)),m=t.typedArrayFromHeap(a);for(let f=0;f<l;f++){let d=f*u;for(let h=0;h<p.length;h++){let g=c[h],x=f*g,b=p[h].subarray(x,x+g);m.set(b,d),d+=g}}return a}var bR={kernelName:ls,backendName:"wasm",kernelFunc:tC};var wR;function A7(r){wR=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 E7(r){let{inputs:e,attrs:t,backend:o}=r,{x:n,filter:s}=e,a=o.dataIdMap.get(n.dataId).id,i=o.dataIdMap.get(s.dataId).id,{strides:l,dilations:u,pad:c,dimRoundingMode:p,dataFormat:m}=t,f=N.convertConv2DDataFormat(m),d=N.computeConv2DInfo(n.shape,s.shape,l,u,c,p,!1,f),h=d.filterHeight,g=d.filterWidth,x=d.padInfo.top,b=d.padInfo.right,w=d.padInfo.bottom,k=d.padInfo.left,_=d.dilationHeight,D=d.dilationWidth,T=d.strideHeight,R=d.strideWidth,O=d.inChannels,M=d.outChannels,G=d.padInfo.type==="SAME"?1:0;if(d.dataFormat!=="channelsLast")throw new Error(`wasm backend Conv2D does not support dataFormat:'${d.dataFormat}'. Please use 'channelsLast'.`);let j=o.makeOutput(d.outShape,"float32"),U=o.dataIdMap.get(j.dataId).id;return wR(a,n.shape[0],n.shape[1],n.shape[2],i,h,g,x,b,w,k,G,_,D,T,R,O,M,U),j}var kR={kernelName:Zo,backendName:"wasm",setupFunc:A7,kernelFunc:E7};var _R;function D7(r){_R=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 $7(r){let{backend:e,inputs:t,attrs:o}=r,{dy:n,filter:s}=t,{strides:a,pad:i,dataFormat:l,dimRoundingMode:u,inputShape:c}=o,p=1,m=N.convertConv2DDataFormat(l),f=N.computeConv2DInfo(c,s.shape,a,p,i,u,!1,m),{batchSize:d,filterHeight:h,filterWidth:g,inChannels:x,inHeight:b,inWidth:w,outChannels:k,outHeight:_,outWidth:D,strideHeight:T,strideWidth:R}=f,O=h-1-f.padInfo.top,M=g-1-f.padInfo.left,G=f.dataFormat==="channelsLast",j=y.computeStrides(f.inShape),U=y.computeStrides(n.shape),[H,q,X]=y.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 _R(we,De,d,h,g,b,w,x,_,D,k,T,R,O,M,H,q,X,oe,Y,re,J,ie,ue,ae,fe,xe),de}var vR={kernelName:Jo,backendName:"wasm",setupFunc:D7,kernelFunc:$7};var CR=Nt(Qo);var rC;(function(r){r[r.bilinear=0]="bilinear",r[r.nearest=1]="nearest"})(rC||(rC={}));var IR;function R7(r){IR=r.wasm.cwrap(ti,null,["number","number","number","number","array","number","number","number","number","number"])}function F7(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,x=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,_=new Uint8Array(new Int32Array(i.shape).buffer);return IR(g,x,b,c,_,p,m,rC[n],s,k),h!=null&&e.disposeData(h.dataId),w}var NR={kernelName:ti,backendName:"wasm",setupFunc:R7,kernelFunc:F7};var SR;function O7(r){SR=r.wasm.cwrap(en,null,["number","number","number","number","number","number"])}function P7(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{axis:s,exclusive:a,reverse:i}=o,l=n.shape.length;y.assert(n.dtype==="float32"||n.dtype==="int32",()=>`cumsum does not support ${n.dtype} tensors in the WASM backend`);let u=N.getAxesPermutation([s],l),c=n;u!==null&&(c=_p({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;SR(d,a?1:0,i?1:0,f,h,Lt[n.dtype]);let g=m;if(u!==null){let x=N.getUndoAxesPermutation(u);g=_p({inputs:{x:m},attrs:{perm:x},backend:t}),t.disposeData(c.dataId),t.disposeData(m.dataId)}return g}var TR={kernelName:en,backendName:"wasm",setupFunc:O7,kernelFunc:P7};var AR;function M7(r){AR=r.wasm.cwrap(ri,null,["number","number","number","array","number","array","array","number","number"])}function L7(r){let{backend:e,inputs:t,attrs:o}=r,{x:n}=t,{blockSize:s,dataFormat:a}=o;y.assert(s>1,()=>`blockSize should be > 1 for depthToSpace, but was: ${s}`);let i=n.shape[0],l=a==="NHWC"?n.shape[1]:n.shape[2],u=a==="NHWC"?n.shape[2]:n.shape[3],c=a==="NHWC"?n.shape[3]:n.shape[1],p=l*s,m=u*s,f=c/(s*s),d=a==="NHWC"?[i,p,m,f]:[i,f,p,m],h=e.makeOutput(d,"float32"),x=e.dataIdMap.get(n.dataId).id,b=new Uint8Array(new Int32Array(y.computeStrides(n.shape)).buffer),w=new Uint8Array(new Int32Array(d).buffer),k=new Uint8Array(new Int32Array(y.computeStrides(d)).buffer),_=e.dataIdMap.get(h.dataId).id;return AR(x,s,a==="NHWC"?1:0,b,n.shape.length-1,w,k,d.length,_),h}var ER={kernelName:ri,backendName:"wasm",setupFunc:M7,kernelFunc:L7};var DR;function z7(r){DR=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 B7(r){let{inputs:e,attrs:t,backend:o}=r,{x:n,filter:s}=e,a=o.dataIdMap.get(n.dataId).id,i=o.dataIdMap.get(s.dataId).id,{strides:l,dilations:u,pad:c,dimRoundingMode:p}=t,m=u==null?[1,1]:u,f=N.computeConv2DInfo(n.shape,s.shape,l,m,c,p,!0),d=f.filterHeight,h=f.filterWidth,g=f.padInfo.top,x=f.padInfo.right,b=f.padInfo.bottom,w=f.padInfo.left,k=f.dilationHeight,_=f.dilationWidth,D=f.strideHeight,T=f.strideWidth,R=f.inChannels,O=f.outChannels,M=f.padInfo.type==="SAME"?1:0;if(f.dataFormat!=="channelsLast")throw new Error(`wasm backend DepthwiseConv2dNative does not support dataFormat:'${f.dataFormat}'. Please use 'channelsLast'.`);let G=o.makeOutput(f.outShape,"float32"),j=o.dataIdMap.get(G.dataId).id;return DR(a,n.shape[0],n.shape[1],n.shape[2],i,d,h,g,x,b,w,M,k,_,D,T,R,O,j),G}var $R={kernelName:tn,backendName:"wasm",setupFunc:z7,kernelFunc:B7};var V7=!1,RR=xt(si,V7,"bool");var FR=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&&(y.assert(-(a+1)<=s,()=>`Axis must be in the interval [${-(a+1)}, ${a}]`),l=a+s+1),i.splice(l,0,1),Mr({inputs:{x:n},backend:o,attrs:{shape:i}})}var OR={kernelName:us,backendName:"wasm",kernelFunc:Qg};function G7(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 PR={kernelName:ia,backendName:"wasm",kernelFunc:G7};var MR;function W7(r){MR=r.wasm.cwrap(ai,null,["number","number","number","number","number","number"])}function j7(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 MR(s,i,l,u,c,a),n}var LR={kernelName:ai,backendName:"wasm",kernelFunc:j7,setupFunc:W7};var zR=Nt(nn);var U7=!1,BR=xt(sn,U7);var VR;function H7(r){VR=r.wasm.cwrap(an,null,["number","number","number","number","number","number","number"])}function q7(r){let{backend:e,inputs:t,attrs:o}=r,{varianceEpsilon:n}=o,{x:s,mean:a,variance:i,offset:l,scale:u}=t,c=e.dataIdMap.get(s.dataId).id,p=e.dataIdMap.get(a.dataId).id,m=e.dataIdMap.get(i.dataId).id,f=l!=null?e.dataIdMap.get(l.dataId).id:0,d=u!=null?e.dataIdMap.get(u.dataId).id:0,h=e.makeOutput(s.shape,s.dtype);if(y.sizeFromShape(s.shape)===0)return h;let g=e.dataIdMap.get(h.dataId).id;return VR(c,p,m,f,d,n,g),h}var GR={kernelName:an,backendName:"wasm",setupFunc:H7,kernelFunc:q7};var WR;function K7(r){WR=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 X7(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 x=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 _=h.filterHeight,D=h.filterWidth,T=h.padInfo.top,R=h.padInfo.right,O=h.padInfo.bottom,M=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 WR(x,oe,Y,re,b,_,D,k,T,R,O,M,X,G,j,U,H,q,w,g,ue,d||0,ie),J}var jR={kernelName:ks,backendName:"wasm",setupFunc:K7,kernelFunc:X7};var UR;function Y7(r){UR=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 Z7(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 x=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 _=h.filterHeight,D=h.filterWidth,T=h.padInfo.top,R=h.padInfo.right,O=h.padInfo.bottom,M=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 UR(x,oe,Y,re,b,_,D,k,T,R,O,M,X,G,j,U,H,q,w,g,ue,d||0,ie),J}var HR={kernelName:_s,backendName:"wasm",setupFunc:Y7,kernelFunc:Z7};var qR;function J7(r){qR=r.wasm.cwrap(li,null,["number","number","number","number","number","number","array","number"])}function Q7(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),x=e.dataIdMap.get(u.dataId).id;return qR(f,Lt[o.dtype],h,a,p,i,g,x),u}var KR={kernelName:li,backendName:"wasm",setupFunc:J7,kernelFunc:Q7};var XR;function eZ(r){XR=r.wasm.cwrap("Gather",null,["number","number","array","number","number","number","array","number"])}function tZ(r){let{backend:e,inputs:t,attrs:o}=r,{x:n,indices:s}=t,{axis:a,batchDims:i}=o,l=y.parseAxisParam(a,n.shape)[0],u=N.segment_util.collectGatherOpShapeInfo(n,s,l,i),c=Mr({inputs:{x:n},attrs:{shape:[u.batchSize,u.outerSize,u.dimSize,u.sliceSize]},backend:e}),p=y.sizeFromShape(s.shape),m=Mr({inputs:{x:s},attrs:{shape:[u.batchSize,p/u.batchSize]},backend:e}),f=[u.batchSize,u.outerSize,p/u.batchSize,u.sliceSize],d=e.makeOutput(f,n.dtype);if(y.sizeFromShape(n.shape)===0)return d;let h=c.shape.length-1,x=e.dataIdMap.get(c.dataId).id,w=e.dataIdMap.get(m.dataId).id,k=e.dataIdMap.get(d.dataId).id,_=new Uint8Array(new Int32Array(y.computeStrides(c.shape)).buffer),D=new Uint8Array(new Int32Array(y.computeStrides(f)).buffer);return XR(x,Lt[n.dtype],_,h,w,u.batchSize,D,k),e.disposeData(c.dataId),e.disposeData(m.dataId),d.shape=u.outputShape,d}var YR={kernelName:cs,backendName:"wasm",setupFunc:eZ,kernelFunc:tZ};var rZ=!1,ZR=xt(ui,rZ,"bool");var oZ=!1,JR=xt(ln,oZ,"bool");var QR;function nZ(r){QR=r.wasm.cwrap(un,null,["number","number","number"])}function sZ(r){let{inputs:{x:e},attrs:{alpha:t},backend:o}=r,n=o.dataIdMap.get(e.dataId).id,s=o.makeOutput(e.shape,e.dtype);if(y.sizeFromShape(e.shape)!==0){let a=o.dataIdMap.get(s.dataId).id;QR(n,t,a)}return s}var eF={kernelName:un,backendName:"wasm",setupFunc:nZ,kernelFunc:sZ};var iZ=!1,tF=xt(fi,iZ,"bool");var aZ=!1,rF=xt(di,aZ,"bool");var oF=Nt(cn);var lZ=!1,nF=xt(gi,lZ,"bool");var sF;function uZ(r){sF=r.wasm.cwrap(pn,null,["number, number, number"])}function cZ(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),x=y.sizeFromShape(g),b=e.makeOutput(h,a.dtype);if(y.sizeFromShape(u.shape)!==0){let w=e.dataIdMap.get(b.dataId).id;sF(l,x,w)}if(f&&e.disposeData(c.dataId),s){let w=N.expandShapeToKeepDim(b.shape,m);b.shape=w}return b}var iF={kernelName:pn,backendName:"wasm",setupFunc:uZ,kernelFunc:cZ};var pZ=!1,aF=xt(mn,pZ);var lF;function mZ(r){lF=r.wasm.cwrap(fn,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function fZ(r){let{inputs:e,attrs:t,backend:o}=r,n=e.x,s=o.dataIdMap.get(n.dataId).id,{filterSize:a,strides:i,pad:l,dimRoundingMode:u}=t,c=N.computePool2DInfo(n.shape,a,i,1,l,u),p=c.filterHeight,m=c.filterWidth,f=c.padInfo.top,d=c.padInfo.right,h=c.padInfo.bottom,g=c.padInfo.left,x=c.dilationHeight,b=c.dilationWidth,w=c.strideHeight,k=c.strideWidth,_=c.inChannels,D=c.outChannels;if(c.dataFormat!=="channelsLast")throw new Error(`wasm backend does not support dataFormat:'${c.dataFormat}'. Please use 'channelsLast'.`);let T=o.makeOutput(c.outShape,"float32"),R=o.dataIdMap.get(T.dataId).id;return lF(s,n.shape[0],n.shape[1],n.shape[2],p,m,f,d,h,g,x,b,w,k,_,D,R),T}var uF={kernelName:fn,backendName:"wasm",setupFunc:mZ,kernelFunc:fZ};var cF;function dZ(r){cF=r.wasm.cwrap(dn,null,["number, number, number"])}function hZ(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),x=y.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(y.sizeFromShape(u.shape)!==0){let k=e.dataIdMap.get(w.dataId).id;cF(l,x,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 pF={kernelName:dn,backendName:"wasm",setupFunc:dZ,kernelFunc:hZ};var mF;function gZ(r){mF=r.wasm.cwrap(hn,null,["number, number, number"])}function xZ(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),x=y.sizeFromShape(g),b=e.makeOutput(h,u.dtype);if(y.sizeFromShape(u.shape)!==0){let w=e.dataIdMap.get(b.dataId).id;mF(l,x,w)}if(f&&e.disposeData(c.dataId),s){let w=N.expandShapeToKeepDim(b.shape,m);b.shape=w}return b}var fF={kernelName:hn,backendName:"wasm",setupFunc:gZ,kernelFunc:xZ};var yZ=!1,dF=xt(gn,yZ);var bZ=!0,hF=xt(xn,bZ);var gF=Nt(ps);function vp(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 xF;function wZ(r){xF=r.wasm.cwrap(bi,"number",["number","number","number","number","number"])}function kZ(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=xF(u,c,s,n,a),{pSelectedIndices:m,selectedSize:f,pSelectedScores:d,pValidOutputs:h}=vp(e,p);return e.wasm._free(d),e.wasm._free(h),e.makeOutput([f],"int32",m)}var yF={kernelName:bi,backendName:"wasm",setupFunc:wZ,kernelFunc:kZ};var bF;function _Z(r){bF=r.wasm.cwrap(wi,"number",["number","number","number","number","number","bool"])}function vZ(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=bF(c,p,s,n,a,i),{pSelectedIndices:f,selectedSize:d,pSelectedScores:h,pValidOutputs:g}=vp(e,m);e.wasm._free(h);let x=e.makeOutput([d],"int32",f),b=e.makeOutput([],"int32",g);return[x,b]}var wF={kernelName:wi,backendName:"wasm",setupFunc:_Z,kernelFunc:vZ};var kF;function CZ(r){kF=r.wasm.cwrap(ki,"number",["number","number","number","number","number","number"])}function IZ(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=kF(c,p,s,n,a,i),{pSelectedIndices:f,selectedSize:d,pSelectedScores:h,pValidOutputs:g}=vp(e,m);e.wasm._free(g);let x=e.makeOutput([d],"int32",f),b=e.makeOutput([d],"float32",h);return[x,b]}var _F={kernelName:ki,backendName:"wasm",setupFunc:CZ,kernelFunc:IZ};var NZ=!1,vF=xt(yi,NZ,"bool");var CF;function SZ(r){CF=r.wasm.cwrap(yn,null,["number","number","number","number","number"])}function TZ(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 CF(p,s,a,i,u),l}var IF={kernelName:yn,backendName:"wasm",setupFunc:SZ,kernelFunc:TZ};function AZ(r){let{inputs:{x:e},backend:t}=r,o=t.makeOutput(e.shape,e.dtype);return t.typedArrayFromHeap(o).fill(1),o}var NF={kernelName:ms,backendName:"wasm",kernelFunc:AZ};function EZ(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=>{y.assertShapesMatch(s,c.shape,"All tensors passed to stack must have matching shapes"),y.assert(a===c.dtype,()=>"All tensors passed to stack must have matching dtypes")});let i=[],l=e.map(c=>{let p=Qg({inputs:{input:c},backend:t,attrs:{dim:n}});return i.push(p),p}),u=tC({inputs:l,backend:t,attrs:{axis:n}});return i.forEach(c=>t.disposeData(c.dataId)),u}var SF={kernelName:fs,backendName:"wasm",kernelFunc:EZ};var TF;function DZ(r){TF=r.wasm.cwrap(bn,null,["number","array","number","number","array","array","number","number"])}function $Z(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 TF(a,u,e.shape.length,Lt[e.dtype],m,f,n,l),i}var AF={kernelName:bn,backendName:"wasm",kernelFunc:$Z,setupFunc:DZ};var RZ=!1,EF=xt(wn,RZ);var DF;function FZ(r){DF=r.wasm.cwrap(kn,null,["number","number","number"])}function OZ(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 DF(s,a,l),i}var $F={kernelName:kn,backendName:"wasm",setupFunc:FZ,kernelFunc:OZ};var RF;function PZ(r){RF=r.wasm.cwrap(_i,null,["number","number","number","number"])}function MZ(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),x=y.sizeFromShape(g),b=e.makeOutput(h,u.dtype);if(y.sizeFromShape(u.shape)!==0){let w=e.dataIdMap.get(b.dataId).id;RF(l,x,Lt[b.dtype],w)}if(f&&e.disposeData(c.dataId),s){let w=N.expandShapeToKeepDim(b.shape,m);b.shape=w}return b}var FF={kernelName:_i,backendName:"wasm",setupFunc:PZ,kernelFunc:MZ};var LZ=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},OF={kernelName:ca,backendName:"wasm",kernelFunc:LZ};var zZ=!0,PF=xt(rn,zZ);var MF=Nt(_n);var LF=Nt(Cn);var zF;function BZ(r){zF=r.wasm.cwrap(vn,null,["number","number","number","number","number","number","number","number","number","number"])}function VZ(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 x=h.id,b=e.makeOutput(d,"float32");if(y.sizeFromShape(n.shape)===0)return b;let w=e.dataIdMap.get(b.dataId).id;return zF(x,c,p,m,f,l,u,s?1:0,a?1:0,w),g!=null&&e.disposeData(g.dataId),b}var BF={kernelName:vn,backendName:"wasm",setupFunc:BZ,kernelFunc:VZ};var VF;function GZ(r){VF=r.wasm.cwrap(In,null,["number","array","number","array","number","number"])}function WZ(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{dims:s}=o,a=y.parseAxisParam(s,n.shape);if(n.shape.length===0)return 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);VF(l,c,a.length,p,n.shape.length,u);let m=Mr({inputs:{x:i},attrs:{shape:n.shape},backend:t});return t.disposeData(i.dataId),m}var GF={kernelName:In,backendName:"wasm",kernelFunc:WZ,setupFunc:GZ};var WF;function jZ(r){WF=r.wasm.cwrap($i,null,["number","number","number","number","number","number","number","number","array","number","number"])}function UZ(r){let{inputs:e,backend:t,attrs:o}=r,{image:n}=e,{radians:s,fillValue:a,center:i}=o,l=t.makeOutput(n.shape,n.dtype),u=t.dataIdMap.get(n.dataId).id,c=t.dataIdMap.get(l.dataId).id,[p,m,f,d]=n.shape,[h,g]=N.getImageCenter(i,m,f),x=a===0,b=255,w=typeof a=="number"?[a,a,a,x?0:b]:[...a,b],k=new Uint8Array(new Int32Array(w).buffer);return WF(u,p,m,f,d,s,h,g,k,w.length,c),l}var jF={kernelName:$i,backendName:"wasm",kernelFunc:UZ,setupFunc:jZ};var UF=Nt(Nn);var HF=Nt(Sn);var qF;function HZ(r){qF=r.wasm.cwrap(Ci,null,["number","number","number","number","number","number","array","number","number"])}function qZ(r){let{backend:e,inputs:t,attrs:o}=r,{indices:n,updates:s}=t,{shape:a}=o,i=e.makeOutput(a,s.dtype);if(y.sizeFromShape(a)===0)return i;let{sliceRank:l,numUpdates:u,sliceSize:c,strides:p,outputSize:m}=Zh.calculateShapes(s,n,a),d=e.dataIdMap.get(n.dataId).id,g=e.dataIdMap.get(s.dataId).id,x=new Uint8Array(new Int32Array(p).buffer),b=e.dataIdMap.get(i.dataId).id;return qF(d,g,Lt[s.dtype],l,u,c,x,m,b),i}var KF={kernelName:Ci,backendName:"wasm",setupFunc:HZ,kernelFunc:qZ};var XF;function KZ(r){XF=r.wasm.cwrap("SelectV2",null,["number","number","number","number","number"])}function XZ(r){let{inputs:e,backend:t}=r,{condition:o,t:n,e:s}=e,a=t.dataIdMap.get(o.dataId).id,i=t.dataIdMap.get(n.dataId).id,l=t.dataIdMap.get(s.dataId).id,u=t.makeOutput(n.shape,n.dtype),c=t.dataIdMap.get(u.dataId).id,p=o.shape.length,m=n.shape.length,f=p===0||p>1||m===1?1:y.sizeFromShape(n.shape.slice(1));return XF(a,i,l,f,c),u}var YF={kernelName:hs,backendName:"wasm",kernelFunc:XZ,setupFunc:KZ};var ZF;function YZ(r){ZF=r.wasm.cwrap(An,null,["number","number"])}function ZZ(r){let{backend:e,inputs:{x:t}}=r,o=e.dataIdMap.get(t.dataId).id,n=e.makeOutput(t.shape,t.dtype),s=e.dataIdMap.get(n.dataId).id;return y.sizeFromShape(n.shape)===0||ZF(o,s),n}var JF={kernelName:"Sigmoid",backendName:"wasm",setupFunc:YZ,kernelFunc:ZZ};var QF=Nt(Tn);function nc(r){let{inputs:{x:e},attrs:{begin:t,size:o},backend:n}=r,[s,a]=sr.parseSliceParams(e,t,o),i=sr.isSliceContinous(e.shape,s,a),l=n.readSync(e.dataId),u=n.makeOutput(a,e.dtype),c=y.computeStrides(e.shape),p=n.dataIdMap.get(u.dataId);if(i){let d=sr.computeFlatOffset(s,c);return e.dtype==="string"?p.stringBytes=l.slice(d,d+y.sizeFromShape(a)):n.typedArrayFromHeap(u).set(l.subarray(d,d+y.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)JZ(l,c[0],m,s,a);else if(f===3)QZ(l,c[0],c[1],m,s,a);else if(f===4)e9(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 JZ(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 QZ(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 e9(r,e,t,o,n,s,a){let i=0,l=s[0],u=s[1],c=s[2],p=l+a[0],m=u+a[1],f=c+a[2],d=s[3];for(let h=l;h<p;h++)for(let g=u;g<m;g++)for(let x=c;x<f;x++){let b=h*e+g*t+x*o+d;n.set(r.subarray(b,b+a[3]),i),i+=a[3]}}var eO={kernelName:gs,backendName:"wasm",kernelFunc:nc};var tO;function t9(r){tO=r.wasm.cwrap($n,null,["number","number","number","number"])}function r9(r){let{backend:e,inputs:{logits:t},attrs:{dim:o}}=r,n=e.dataIdMap.get(t.dataId).id,s=e.makeOutput(t.shape,t.dtype),a=e.dataIdMap.get(s.dataId).id,i=t.shape[o],l=y.sizeFromShape(t.shape)/i;return y.sizeFromShape(s.shape)===0||tO(n,a,i,l),s}var rO={kernelName:$n,backendName:"wasm",setupFunc:t9,kernelFunc:r9};function o9(r){let{inputs:e,attrs:t,backend:o}=r,{x:n}=e,{numOrSizeSplits:s,axis:a}=t,i=y.parseAxisParam(a,n.shape)[0],l=N.prepareSplitSize(n,s,i),u=new Array(n.shape.length).fill(0),c=n.shape.slice();return l.map(p=>{let m=[...c];m[i]=p;let f=nc({inputs:{x:n},attrs:{begin:u,size:m},backend:o});return u[i]+=p,f})}var oO={kernelName:xs,backendName:"wasm",kernelFunc:o9};var nO=Nt(En);var sO=Nt(fa);var n9=!0,iO=xt(Rn,n9);var aO;function s9(r){aO=r.wasm.cwrap(Oo,null,["number","number","number"])}function i9(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 aO(a,n,l),i}var lO={kernelName:Oo,backendName:"wasm",setupFunc:s9,kernelFunc:i9};var uO;function a9(r){uO=r.wasm.cwrap(Ai,null,["number","array","number","array","array","array","array","array","number","number"])}function l9(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 x=Mr({inputs:{x:n},attrs:{shape:g},backend:e}),{begin:b,end:w,strides:k}=N.slice_util.getNormalizedAxes(x.shape,f,d,s,a,i,l,u,c);s=b,a=w,i=k;let _=N.slice_util.maskToAxes(m);_.forEach(G=>{a[G]=s[G]+1,i[G]=1});let D=N.slice_util.computeOutShape(s,a,i),T=D.filter((G,j)=>_.indexOf(j)===-1);if(i.every(G=>G===1)){let G=nc({inputs:{x},attrs:{begin:s,size:D},backend:e});e.disposeData(x.dataId);let j=Mr({inputs:{x:G},attrs:{shape:T},backend:e});return e.disposeData(G.dataId),j}let O=e.makeOutput(T,"float32");if(!T.some(G=>G===0)){let G=e.dataIdMap.get(x.dataId).id,j=new Uint8Array(new Int32Array(y.computeStrides(x.shape)).buffer),U=new Uint8Array(new Int32Array(s).buffer),H=new Uint8Array(new Int32Array(a).buffer),q=new Uint8Array(new Int32Array(i).buffer),X=new Uint8Array(new Int32Array(T).buffer),oe=new Uint8Array(new Int32Array(y.computeStrides(T)).buffer),Y=e.dataIdMap.get(O.dataId).id;uO(G,j,x.shape.length,U,H,q,X,oe,T.length,Y)}e.disposeData(x.dataId);let M=Mr({inputs:{x:O},attrs:{shape:T},backend:e});return e.disposeData(O.dataId),M}var cO={kernelName:Ai,backendName:"wasm",setupFunc:a9,kernelFunc:l9};var u9=!0,pO=xt(Fn,u9);var mO;function c9(r){mO=r.wasm.cwrap(Dn,null,["number, number, number"])}function p9(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),x=y.sizeFromShape(g),b=e.makeOutput(h,u.dtype);if(y.sizeFromShape(u.shape)!==0){let w=e.dataIdMap.get(b.dataId).id;mO(l,x,w)}if(f&&e.disposeData(c.dataId),s){let w=N.expandShapeToKeepDim(b.shape,m);b.shape=w}return b}var fO={kernelName:Dn,backendName:"wasm",setupFunc:c9,kernelFunc:p9};var dO=Nt(On);var hO;function m9(r){hO=r.wasm.cwrap(ko,null,["number","array","number","array","number","number"])}function f9(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 hO(s,l,n.shape.length,u,i.length,Lt[c.dtype],p),c}var gO={kernelName:ko,backendName:"wasm",setupFunc:m9,kernelFunc:f9};var xO;function d9(r){xO=r.wasm.cwrap(Di,null,["number","array","number","number","number","bool","number","number"])}var h9=({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 xO(a,i,o.shape.length,Lt[o.dtype],n,s,c,m),[u,p]},yO={kernelName:Di,backendName:"wasm",setupFunc:d9,kernelFunc:h9};function g9(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 bO={kernelName:ys,backendName:"wasm",kernelFunc:g9};function x9(r){let{inputs:{x:e},backend:t}=r,o=t.makeOutput(e.shape,e.dtype);return t.typedArrayFromHeap(o).fill(0),o}var wO={kernelName:bs,backendName:"wasm",kernelFunc:x9};var y9=[tR,rR,nR,uR,pR,dR,hR,gR,yR,bR,kR,vR,CR,NR,TR,ER,$R,RR,FR,OR,PR,LR,zR,BR,eR,GR,jR,HR,KR,YR,ZR,JR,sR,eF,tF,rF,oF,nF,iF,aF,uF,pF,fF,dF,hF,gF,yF,wF,_F,vF,IF,NF,SF,AF,EF,$F,FF,OF,PF,MF,LF,mR,BF,GF,jF,HF,UF,KF,YF,JF,QF,eO,rO,oO,nO,sO,iO,lO,cO,pO,fO,dO,gO,yO,aR,bO,wO];for(let r of y9)el(r);var oC=W();oC.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])));oC.registerFlag("WASM_HAS_MULTITHREAD_SUPPORT",async()=>{if(oC.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 lC=Ac(vO());var CO='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 NO=Ac(IO());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=y.now();return e(),{kernelMs:y.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=y.sizeFromShape(o),l=i*y.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+y.sizeFromShape(n)*y.bytesPerElement(o));return b9(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=y.sizeFromShape(e);this.wasm.tfjs.registerTensor(s,a,o)}return{dataId:n,shape:e,dtype:t}}typedArrayFromHeap({shape:e,dtype:t,dataId:o}){let n=this.wasm.HEAPU8.buffer,{memoryOffset:s}=this.dataIdMap.get(o),a=y.sizeFromShape(e);switch(t){case"float32":return new Float32Array(n,s,a);case"int32":return new Int32Array(n,s,a);case"bool":return new Uint8Array(n,s,a);default:throw new Error(`Unknown dtype ${t}`)}}};function w9(r){return(e,t)=>(y.fetch(r,{credentials:"same-origin"}).then(o=>{o.ok||e.env.a(`failed to load wasm binary file at '${r}'`),o.arrayBuffer().then(n=>{WebAssembly.instantiate(n,e).then(s=>{t(s.instance)})})}),{})}function SO(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 TO(){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=CO,c=new Blob([u],{type:"application/javascript"});return URL.createObjectURL(c)}return i.endsWith(".wasm")?SO(r,e,$f!=null?$f:l):l+i},uC&&(n.instantiateWasm=w9(SO(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 = "+lC.default.toString()],{type:"text/javascript"}),a=(0,lC.default)(n)):a=(0,NO.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 b9(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 k9=["tfjs-backend-wasm.wasm","tfjs-backend-wasm-simd.wasm","tfjs-backend-wasm-threaded-simd.wasm"],ox=null,$f=null,Df={},Rf=!1,uC=!1;function _9(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,uC=e}function v9(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=k9.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.`)}uC=e}var cC="3.3.0";var C9=2;xu("wasm",async()=>{let{wasm:r}=await TO();return new rx(r)},C9);F().prototype.abs=function(){return this.throwIfDisposed(),It(this)};F().prototype.acos=function(){return this.throwIfDisposed(),km(this)};F().prototype.acosh=function(){return this.throwIfDisposed(),_m(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(),vm(this,r)};F().prototype.asScalar=function(){return this.throwIfDisposed(),A(this.size===1,()=>"The array must have only 1 element."),L(this,[])};F().prototype.asType=function(r){return this.throwIfDisposed(),ne(this,r)};F().prototype.as1D=function(){return this.throwIfDisposed(),L(this,[this.size])};F().prototype.as2D=function(r,e){return this.throwIfDisposed(),L(this,[r,e])};F().prototype.as3D=function(r,e,t){return this.throwIfDisposed(),L(this,[r,e,t])};F().prototype.as4D=function(r,e,t,o){return this.throwIfDisposed(),L(this,[r,e,t,o])};F().prototype.as5D=function(r,e,t,o,n){return this.throwIfDisposed(),L(this,[r,e,t,o,n])};F().prototype.asin=function(){return this.throwIfDisposed(),Cm(this)};F().prototype.asinh=function(){return this.throwIfDisposed(),Im(this)};F().prototype.atan=function(){return this.throwIfDisposed(),Nm(this)};F().prototype.atan2=function(r){return this.throwIfDisposed(),Sm(this,r)};F().prototype.atanh=function(){return this.throwIfDisposed(),Tm(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(),Em(this)};F().prototype.clipByValue=function(r,e){return this.throwIfDisposed(),ir(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(),$m(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(),Rm(this,r,e,t,o,n)};F().prototype.divNoNan=function(r){return this.throwIfDisposed(),Fm(this,r)};F().prototype.div=function(r){return this.throwIfDisposed(),me(this,r)};F().prototype.dot=function(r){return this.throwIfDisposed(),Nw(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(),Om(this)};F().prototype.exp=function(){return this.throwIfDisposed(),Zt(this)};F().prototype.expandDims=function(r){return this.throwIfDisposed(),ar(this,r)};F().prototype.expm1=function(){return this.throwIfDisposed(),Pm(this)};F().prototype.fft=function(){return this.throwIfDisposed(),Ea(this)};F().prototype.flatten=function(){return this.throwIfDisposed(),L(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(),er(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(),Sw(this)};F().prototype.isInf=function(){return this.throwIfDisposed(),Tw(this)};F().prototype.isNaN=function(){return this.throwIfDisposed(),Aw(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(),Mm(this,r,e,t,o)};F().prototype.logSigmoid=function(){return this.throwIfDisposed(),Dw(this)};F().prototype.logSoftmax=function(r){return this.throwIfDisposed(),Au(this,r)};F().prototype.logSumExp=function(r,e){return this.throwIfDisposed(),zm(this,r,e)};F().prototype.log=function(){return this.throwIfDisposed(),lr(this)};F().prototype.log1p=function(){return this.throwIfDisposed(),Tu(this)};F().prototype.logicalAnd=function(r){return this.throwIfDisposed(),hr(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(),Ow(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(),ur(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(),Vm(this,r,e)};F().prototype.mod=function(r){return this.throwIfDisposed(),Gm(this,r)};F().prototype.mul=function(r){return this.throwIfDisposed(),P(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(),tr(this)};F().prototype.pad=function(r,e){return this.throwIfDisposed(),Fr(this,r,e)};F().prototype.pool=function(r,e,t,o,n){return this.throwIfDisposed(),Lw(this,r,e,t,o,n)};F().prototype.pow=function(r){return this.throwIfDisposed(),Or(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(),Sr(this)};F().prototype.relu6=function(){return this.throwIfDisposed(),Ru(this)};F().prototype.reshapeAs=function(r){return this.throwIfDisposed(),L(this,r.shape)};F().prototype.reshape=function(r){return this.throwIfDisposed(),L(this,r)};F().prototype.resizeBilinear=function(r,e,t){return this.throwIfDisposed(),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(),qt(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(),cr(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(),ep(this,r)};F().prototype.unsortedSegmentSum=function(r,e){return this.throwIfDisposed(),Jm(this,r,e)};F().prototype.unstack=function(r){return this.throwIfDisposed(),pr(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:()=>P(r,Ds(ne(t,"float32"),-1))}}};var AO={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 EO={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 DO={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)),L(i,t.shape)},b:()=>{let i=r,l=kt(o.shape,n);return l.length>0&&(i=ge(i,l)),L(i,o.shape)}}}};var $O={kernelName:Ho,saveAllInputs:!0,gradFunc:(r,e)=>{let t={};return e.forEach((o,n)=>{t[n]=()=>r.clone()}),t}};var RO={kernelName:qo,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>Ce(t)}}};var FO={kernelName:ea,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>Ce(t)}}};var OO={kernelName:Xs,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>me(r,gt(ce(le(1),Oe(ne(t,"float32")))))}}};var PO={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 MO={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=P(r,me(o,i)),u=kt(t.shape,n);return u.length>0&&(l=ge(l,u)),L(l,t.shape)},b:()=>{let i=ee(Oe(t),Oe(o)),l=He(P(r,me(t,i))),u=kt(o.shape,n);return u.length>0&&(l=ge(l,u)),L(l,o.shape)}}}};var LO={kernelName:Zs,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>me(r,ee(Oe(ne(t,"float32")),1))}}};var zO={kernelName:Js,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>me(r,ce(le(1),Oe(ne(t,"float32"))))}}};function I9(r,e,t,o,n,s){let a=v(r,"dy","avgPool3dGrad"),i=v(e,"input","avgPool3dGrad"),l=a,u=i,c=!1;i.rank===4&&(c=!0,l=L(a,[1,a.shape[0],a.shape[1],a.shape[2],a.shape[3]]),u=L(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),A(l.rank===5,()=>`Error in avgPool3dGrad: dy must be rank 5 but got rank ${l.rank}.`),A(u.rank===5,()=>`Error in avgPool3dGrad: input must be rank 5 but got rank ${u.rank}.`),s!=null&&A(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?L(f,[f.shape[1],f.shape[2],f.shape[3],f.shape[4]]):f}var BO=S({avgPool3dGrad_:I9});var VO={kernelName:ta,inputsToSave:["x"],gradFunc:(r,e,t)=>{let[o]=e,{filterSize:n,strides:s,pad:a,dimRoundingMode:i}=t;return{x:()=>BO(r,o,n,s,a,i)}}};function N9(r,e,t,o,n){let s=v(r,"dy","avgPoolGrad"),a=v(e,"input","avgPoolGrad");A(a.rank===s.rank,()=>`Rank of input (${a.rank}) does not match rank of dy (${s.rank})`);let i=a,l=s,u=!1;a.rank===3&&(u=!0,i=L(a,[1,a.shape[0],a.shape[1],a.shape[2]]),l=L(s,[1,s.shape[0],s.shape[1],s.shape[2]])),A(l.rank===4,()=>`Error in avgPoolGrad: dy must be rank 4 but got rank ${l.rank}.`),A(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?L(m,[m.shape[1],m.shape[2],m.shape[3]]):m}var GO=S({avgPoolGrad_:N9});var WO={kernelName:Ko,inputsToSave:["x"],gradFunc:(r,e,t)=>{let[o]=e,{filterSize:n,strides:s,pad:a}=t;return{x:()=>GO(r,o,n,s,a)}}};var jO={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 UO={kernelName:ra,gradFunc:(r,e,t)=>{let{blockShape:o,crops:n}=t;return{x:()=>Sa(r,o,n)}}};var HO={kernelName:$b,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 qO={kernelName:$o,gradFunc:r=>({x:()=>r.clone()})};var KO={kernelName:Yo,gradFunc:r=>({x:()=>Ce(r)})};var XO={kernelName:Ro,inputsToSave:["x"],gradFunc:(r,e,t)=>{let[o]=e,{clipValueMin:n,clipValueMax:s}=t;return{x:()=>Dt(hr(io(o,n),Bo(o,s)),r,Ce(r))}}};var YO={kernelName:oa,inputsToSave:["x"],gradFunc:nx.gradFunc};var ZO={kernelName:ls,saveAllInputs:!0,gradFunc:(r,e,t)=>{let o=e.map(l=>l.shape),{axis:n}=t,s=Qt(n,e[0].shape)[0],a=o.map(l=>l[s]);return cr(r,a,s).map(l=>()=>l)}};var JO={kernelName:Zo,inputsToSave:["x","filter"],gradFunc:(r,e,t)=>{let[o,n]=e,{dilations:s,strides:a,pad:i,dataFormat:l}=t;return A(Lo(s),()=>`Error in gradient of conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${s}'`),{x:()=>Kc(o.shape,r,n,a,i,l),filter:()=>tp(o,r,n.shape,a,i,l)}}};var QO={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:()=>tp(r,o,n.shape,s,a,i,l)}}};function S9(r,e,t,o,n){let s=r;r.rank===4&&(s=L(r,[1,r.shape[0],r.shape[1],r.shape[2],r.shape[3]]));let a=e;a.rank===4&&(a=L(e,[1,e.shape[0],e.shape[1],e.shape[2],e.shape[3]])),A(s.rank===5,()=>`Error in conv3dDerFilter: input must be rank 5, but got shape ${s.shape}.`),A(a.rank===5,()=>`Error in conv3dDerFilter: dy must be rank 5, but got shape ${a.shape}.`),A(t.length===5,()=>`Error in conv3dDerFilter: filterShape must be length 5, but got ${t}.`),A(s.shape[4]===t[3],()=>`Error in conv3dDerFilter: depth of input ${s.shape[4]}) must match input depth in filter (${t[3]}.`),A(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 eP=S({conv3DBackpropFilter_:S9});var tP={kernelName:na,inputsToSave:["x","filter"],gradFunc:(r,e,t)=>{let{dilations:o,strides:n,pad:s}=t;A(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:()=>eP(a,r,i.shape,n,s)}}};var rP={kernelName:Qo,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>P(He(Pu(ne(t,"float32"))),r)}}};var oP={kernelName:ei,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>P(Mu(ne(t,"float32")),r)}}};var nP={kernelName:en,inputsToSave:["x"],gradFunc:(r,e,t)=>{let[o]=e,{axis:n,exclusive:s,reverse:a}=t;return{x:()=>{let i=Fw([n],o.rank),l=Iu(r,n,s,!a);return i!=null&&(l=Ue(l,i)),l}}}};var sP={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;A(Lo(i),()=>`Error in gradient of depthwiseConv2dNative: dilation rates greater than 1 are not yet supported. Got dilations '${i}'`);let[l,u]=e;return A(l.rank===4,()=>`Error in gradient of depthwiseConv2dNative: input must be rank 4, but got rank ${l.rank}.`),A(u.rank===4,()=>`Error in gradient of depthwiseConv2dNative: filter must be rank 4, but got rank ${u.rank}.`),A(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]}.`),A(kr(n,i),()=>`Error in gradient of depthwiseConv2d: Either strides or dilations must be 1. Got strides ${n} and dilations '${i}'.`),a!=null&&A(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 iP={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(Fc,s,t),filter:()=>E.runKernel(Oc,a,t)}}};var aP={kernelName:oi,outputsToSave:[!0],gradFunc:(r,e)=>{let[t]=e,o={dy:r,y:t};return{x:()=>E.runKernel(Yl,o)}}};var lP={kernelName:ni,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e,o=P(Zt(He(Oe(t))),2/Math.sqrt(Math.PI));return{x:()=>P(r,o)}}};var uP={kernelName:on,outputsToSave:[!0],gradFunc:(r,e)=>{let[t]=e;return{x:()=>P(r,t)}}};var cP={kernelName:us,inputsToSave:["input"],gradFunc:(r,e)=>{let[t]=e;return{input:()=>L(r,t.shape)}}};var pP={kernelName:ii,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>P(r,Zt(t))}}};var mP={kernelName:nn,gradFunc:r=>({x:()=>Ce(r)})};var fP={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?L(ge(i,l),t.shape):i},b:()=>{let i=P(r,ne(t,"float32")),l=kt(o.shape,n);l.length>0&&(i=L(ge(i,l),o.shape));let u=Oe(o);return He(me(i,ne(u,"float32")))}}}};var dP={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=P(r,l),f=Fu(ee(a,le(o))),d=P(P(P(f,f),f),le(-.5));return{x:()=>s.rank===1?L(P(P(r,zo(L(f,[1,1,1,s.shape[0]]),c)),l),n.shape):L(P(P(r,f),l),n.shape),mean:()=>{let k=P(P(f,le(-1)),m);return s.rank===1&&(k=ge(k,u)),L(k,s.shape)},variance:()=>{let k=P(P(d,p),m);return s.rank===1&&(k=ge(k,u)),L(k,s.shape)},scale:()=>{let k=P(p,f),_=P(r,k);return s.rank===1&&(_=ge(_,u)),L(_,s.shape)},offset:()=>{let k=r;return s.rank===1&&(k=ge(k,u)),L(k,s.shape)}}}};var xP={kernelName:cs,inputsToSave:["x","indices"],gradFunc:(r,e,t)=>{let[o,n]=e,{axis:s}=t,a=Qt(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=hP(0,p),h=hP(p+1,p+1+f),g=gP([c,[u],m]),x=L(r,g),b=L(n,[u]),w=gP([[p],d,h]),k=Ue(x,w),_=Jm(k,b,o.shape[a]),D=Lm(w);return _=Ue(_,D),_},indices:()=>n}}};function hP(r,e){let t=[];for(let o=r;o<e;++o)t.push(o);return t}function gP(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 yP={kernelName:ln,inputsToSave:["a","b"],gradFunc:(r,e)=>{let[t,o]=e;return{a:()=>Ce(t),b:()=>Ce(o)}}};var bP={kernelName:Fo,gradFunc:r=>({x:()=>ne(r,"float32")})};var wP={kernelName:ci,gradFunc:r=>({x:()=>Ce(r)})};var kP={kernelName:pi,gradFunc:r=>({x:()=>Ce(r)})};var _P={kernelName:mi,gradFunc:r=>({x:()=>Ce(r)})};var vP={kernelName:un,inputsToSave:["x"],gradFunc:(r,e,t)=>{let[o]=e,{alpha:n}=t,s=er(o,0);return{x:()=>Dt(s,r,P(r,n))}}};var CP={kernelName:hi,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>me(r,ee(t,1))}}};var IP={kernelName:cn,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>me(r,ne(t,"float32"))}}};var NP={kernelName:Rb,inputsToSave:[],outputsToSave:[!0],gradFunc:(r,e,t)=>{let[o]=e,{axis:n}=t;return{logits:()=>{let s=!0,a=Zt(o);return ce(r,P(ge(r,n,s),a))}}}};function T9(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 SP=S({localResponseNormalizationBackprop_:T9});var TP={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:()=>SP(o,n,r,s,a,i,l)}}};function sx(r,e,t,o){return e.rank<t.rank&&(e=L(e,Bn(e.shape,o))),r.rank<t.rank&&(r=L(r,Bn(r.shape,o))),{x:()=>P(r,ne(vo(t,e),r.dtype))}}var pC={kernelName:pn,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(r,e,t)=>{let o=t,{reductionIndices:n}=o,s=e[0],a=e[1],i=Qt(n,s.shape),l=sx(r,a,s,i);return{x:()=>l.x()}}};var AP={kernelName:mn,inputsToSave:["a","b"],gradFunc:(r,e)=>{let[t,o]=e;return{a:()=>P(r,ne(io(t,o),"float32")),b:()=>P(r,ne(Su(t,o),"float32"))}}};function A9(r,e,t,o,n,s,a){let i=v(r,"dy","maxPool3dGrad"),l=v(e,"input","maxPool3dGrad"),u=v(t,"output","maxPool3dGrad"),c=i,p=l,m=u,f=!1;l.rank===4&&(f=!0,c=L(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]]),p=L(l,[1,l.shape[0],l.shape[1],l.shape[2],l.shape[3]]),m=L(u,[1,u.shape[0],u.shape[1],u.shape[2],u.shape[3]])),A(c.rank===5,()=>`Error in maxPool3dGrad: dy must be rank 5 but got rank ${c.rank}.`),A(p.rank===5,()=>`Error in maxPool3dGrad: input must be rank 5 but got rank ${p.rank}.`),A(m.rank===5,()=>`Error in maxPool3dGrad: output must be rank 5 but got rank ${m.rank}.`),a!=null&&A(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?L(g,[g.shape[1],g.shape[2],g.shape[3],g.shape[4]]):g}var EP=S({maxPool3dGrad_:A9});var DP={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:()=>EP(r,o,n,s,a,i,l)}}};function E9(r,e,t,o,n,s,a){let i=v(r,"dy","maxPoolGrad"),l=v(e,"input","maxPoolGrad"),u=v(t,"output","maxPoolGrad");A(l.rank===i.rank,()=>`Rank of input (${l.rank}) does not match rank of dy (${i.rank})`),A(i.rank===4,()=>`Error in maxPoolGrad: dy must be rank 4 but got rank ${i.rank}.`),A(l.rank===4,()=>`Error in maxPoolGrad: input must be rank 4 but got rank ${l.rank}.`),a!=null&&A(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 $P=S({maxPoolGrad_:E9});var RP={kernelName:fn,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(r,e,t)=>{let[o,n]=e,{filterSize:s,strides:a,pad:i}=t;return{x:()=>$P(r,o,n,s,a,i)}}};var FP={kernelName:dn,inputsToSave:["x"],gradFunc:(r,e,t)=>{let[o]=e,{axis:n}=t,s=Qt(n,o.shape),i=Rw(o.shape,s)[1],l=ct(i);return{x:()=>{let c=o.shape.slice();s.forEach(f=>{c[f]=1});let p=L(r,c);return me(P(p,Nr(o.shape,"float32")),l)}}}};var OP={kernelName:hn,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(r,e,t)=>{let o=t,{axis:n}=o,[s,a]=e,i=Qt(n,s.shape),l=sx(r,a,s,i);return{x:()=>l.x()}}};var PP={kernelName:gn,inputsToSave:["a","b"],gradFunc:(r,e)=>{let[t,o]=e;return{a:()=>P(r,ne(Bo(t,o),"float32")),b:()=>P(r,ne(er(t,o),"float32"))}}};var MP={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 LP={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?L(ge(r,i),t.shape):r},b:()=>{let i=P(r,He(Ss(me(t,o)))),l=kt(o.shape,n);return l.length>0?L(ge(i,l),o.shape):i}}}};var zP={kernelName:xn,inputsToSave:["a","b"],gradFunc:(r,e)=>{let[t,o]=e,n=Be(t.shape,o.shape);return{a:()=>{let i=P(r,ne(o,"float32")),l=kt(t.shape,n);return l.length>0?L(ge(i,l),t.shape):i},b:()=>{let i=P(r,ne(t,"float32")),l=kt(o.shape,n);return l.length>0?L(ge(i,l),o.shape):i}}}};var BP={kernelName:ps,gradFunc:r=>({x:()=>He(r)})};var VP={kernelName:yn,inputsToSave:["indices"],gradFunc:(r,e)=>{let t=e[0];return{indices:()=>ht(t.shape,"float32")}}};var GP={kernelName:ms,gradFunc:r=>({x:()=>Ce(r)})};var WP={kernelName:fs,saveAllInputs:!0,gradFunc:(r,e,t)=>{let{axis:o}=t;return pr(r,o).map(s=>()=>s)}};var mC={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 jP={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=P(r,P(c,Or(s,ce(c,le(1))))),m=kt(s.shape,i);return m.length>0&&(p=ge(p,m)),L(p,s.shape)},b:()=>{let c=er(s,0),p=Dt(c,lr(s),Ce(s)),m=P(r,P(n,p)),f=kt(a.shape,i);return f.length>0&&(m=ge(m,f)),L(m,a.shape)}}}};var UP={kernelName:kn,inputsToSave:["x","alpha"],gradFunc:(r,e)=>{let[t,o]=e,n=er(t,0);return{x:()=>Dt(n,r,P(r,o)),alpha:()=>{let s=Dt(n,Ce(r),P(r,t)),a=kt(o.shape,r.shape);return a.length>0&&(s=ge(s,a)),L(s,o.shape)}}}};var HP={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?L(ge(i,l),t.shape):i},b:()=>{let i=P(r,ne(t,"float32")),l=kt(o.shape,n);l.length>0&&(i=L(ge(i,l),o.shape));let u=Oe(o);return He(me(i,ne(u,"float32")))}}}};var qP={kernelName:vi,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>me(r,He(Oe(t)))}}};var KP={kernelName:Cn,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e,o=P(Bo(t,6),Ds(t));return{x:()=>P(r,ne(o,"float32"))}}};var XP={kernelName:_n,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>P(r,ne(Ds(t),"float32"))}}};var YP={kernelName:ds,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>L(r,t.shape)}}};var ZP={kernelName:vn,inputsToSave:["images"],gradFunc:(r,e,t)=>{let[o]=e,n={dy:r,images:o};return{images:()=>E.runKernel(lu,n,t)}}};var JP={kernelName:pa,inputsToSave:["images"],gradFunc:(r,e,t)=>{let[o]=e,n={dy:r,images:o};return{images:()=>E.runKernel(au,n,t)}}};var QP={kernelName:In,gradFunc:(r,e,t)=>{let{dims:o}=t,n=Qt(o,r.shape);return{x:()=>qt(r,n)}}};var eM={kernelName:Nn,gradFunc:r=>({x:()=>Ce(r)})};var tM={kernelName:Sn,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>He(me(r,P(Or(t,1.5),2)))}}};var rM={kernelName:hs,inputsToSave:["condition"],gradFunc:(r,e)=>{let[t]=e;return{condition:()=>ne(Ce(t),"float32"),t:()=>P(r,ne(t,r.dtype)),e:()=>P(r,ne(Ia(t),r.dtype))}}};var oM={kernelName:Ii,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>{let o=er(t,le(0)),n=le(ak),s=le(lk),a=P(r,s),i=P(P(r,n),Zt(ne(t,"float32")));return Dt(o,a,i)}}}};var nM={kernelName:An,outputsToSave:[!0],gradFunc:(r,e)=>{let[t]=e;return{x:()=>P(r,P(t,ce(le(1),t)))}}};var sM={kernelName:Si,gradFunc:r=>({x:()=>Ce(r)})};var iM={kernelName:Tn,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>P(_a(ne(t,"float32")),r)}}};var aM={kernelName:Ni,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>P(Cu(ne(t,"float32")),r)}}};var lM={kernelName:gs,inputsToSave:["x"],gradFunc:(r,e,t)=>{let[o]=e,{begin:n,size:s}=t,a=o.shape,[i,l]=lw(o,n,s),u=[];for(let c=0;c<r.rank;c++)u.push([i[c],a[c]-i[c]-l[c]]);return{x:()=>Fr(r,u)}}};var uM={kernelName:$n,outputsToSave:[!0],gradFunc:(r,e,t)=>{let[o]=e,{dim:n}=t,s=!0,a=P(r,o);return{logits:()=>ce(a,P(ge(a,[n],s),o))}}};var cM={kernelName:Ti,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>P(r,qr(t))}}};var fC={kernelName:ma,gradFunc:(r,e,t)=>{let{blockShape:o,paddings:n}=t;return{x:()=>ka(r,o,n)}}};var dC={kernelName:xs,gradFunc:(r,e,t)=>{let{axis:o}=t;return{x:()=>Ze(r,o)}}};var pM={kernelName:En,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>me(r,P(gt(ne(t,"float32")),2))}}};var mM={kernelName:fa,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>P(r,P(ne(t,"float32"),2))}}};var fM={kernelName:Rn,inputsToSave:["a","b"],gradFunc:(r,e)=>{let[t,o]=e,n=le(2);return{a:()=>P(r,P(n,ce(t,o))),b:()=>P(r,P(n,ce(o,t)))}}};var dM={kernelName:Oo,gradFunc:r=>({x:()=>Ce(r)})};var hM={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)),L(i,t.shape)},b:()=>{let i=r,l=kt(o.shape,n);return l.length>0&&(i=ge(i,l)),L(He(i),o.shape)}}}};var gM={kernelName:Dn,inputsToSave:["x"],gradFunc:(r,e,t)=>{let[o]=e,n=o.shape.slice(),{axis:s}=t;Qt(s,o.shape).forEach(u=>{n[u]=1});let i=L(r,n),l=P(i,Nr(o.shape,"float32"));return{x:()=>l}}};var xM={kernelName:Ei,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>me(r,Oe(_a(t)))}}};var yM={kernelName:On,outputsToSave:[!0],gradFunc:(r,e)=>{let[t]=e;return{x:()=>P(ce(le(1),Oe(t)),r)}}};var bM={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 wM={kernelName:Pn,gradFunc:(r,e,t)=>{let o=t,{perm:n}=o,s=Lm(n);return{x:()=>Ue(r,s)}}};var kM={kernelName:ys,gradFunc:(r,e,t)=>{let o=t,{axis:n}=o;return{value:()=>Bt(r,n)}}};var _M={kernelName:da,inputsToSave:["segmentIds"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>D9(r,t)}}};function D9(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=ar(n,i+1);n=hr(n,Nr(o.shape,"bool"));let a=Ce(o);return Dt(n,o,a)}var vM={kernelName:bs,gradFunc:r=>({x:()=>Ce(r)})};var $9=[nx,AO,EO,DO,$O,RO,FO,OO,PO,MO,LO,zO,VO,WO,jO,UO,HO,qO,KO,XO,YO,ZO,QO,JO,tP,rP,oP,nP,sP,iP,HP,aP,lP,uP,cP,pP,fP,mP,dP,xP,yP,bP,wP,kP,_P,vP,CP,IP,NP,TP,pC,pC,AP,DP,RP,FP,OP,PP,MP,LP,zP,BP,VP,GP,WP,mC,mC,jP,UP,qP,KP,XP,YP,ZP,JP,QP,eM,tM,rM,oM,nM,sM,iM,aM,lM,uM,cM,fC,fC,dC,dC,pM,fM,mM,dM,hM,gM,xM,yM,bM,wM,kM,_M,vM];for(let r of $9)Ob(r);var bC={};Ke(bC,{maxNorm:()=>F9,minMaxNorm:()=>M9,nonNeg:()=>P9,unitNorm:()=>O9});var hC;function Jt(){return hC==null&&(hC=mw().epsilon()),hC}function Zr(){return"channelsLast"}var So=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,So.prototype)}},Lr=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,Lr.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 gC(r,e){let t=0;for(let o of r)o===e&&t++;return t}function xr(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 Ip(r){if(r==null)return null;let e={};return e.className=r.getClassName(),e.config=r.getConfig(),e}function xC(r){if(!(r==null||typeof r!="object"))if(Array.isArray(r))r.forEach(e=>xC(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:xC(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];xC(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 R9(r,e){return r<e?-1:r>e?1:0}function Of(r,e){return-1*R9(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 CM(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)?(y.assert(r.length>0,()=>`${e} is unexpectedly an empty array.`),r.forEach((t,o)=>Ut(t,`element ${o+1} of ${e}`))):y.assert(Number.isInteger(r)&&r>0,()=>`Expected ${e} to be a positive integer, but got ${IM(r)}.`)}function IM(r){return r===null?"null":Array.isArray(r)?"["+r.map(e=>IM(e)).join(",")+"]":typeof r=="string"?`"${r}"`:`${r}`}function NM(r,e){let t=y.now(),o;return(...s)=>{let a=y.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 yC(r,e){return V(()=>gt(ge(P(r,r),e,!0)))}var Np=class extends Q.Serializable{getConfig(){return{}}},Pf=class extends Np{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=yC(e,this.axis),o=ir(t,0,this.maxValue);return P(e,me(o,ee(Jt(),t)))})}getConfig(){return{maxValue:this.maxValue,axis:this.axis}}};Pf.className="MaxNorm";Q.registerClass(Pf);var Mf=class extends Np{constructor(e){super();this.defaultAxis=0,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return V(()=>me(e,ee(Jt(),yC(e,this.axis))))}getConfig(){return{axis:this.axis}}};Mf.className="UnitNorm";Q.registerClass(Mf);var Lf=class extends Np{apply(e){return Sr(e)}};Lf.className="NonNeg";Q.registerClass(Lf);var zf=class extends Np{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=yC(e,this.axis),o=ee(P(this.rate,ir(t,this.minValue,this.maxValue)),P(1-this.rate,t));return P(e,me(o,ee(Jt(),t)))})}getConfig(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}}};zf.className="MinMaxNorm";Q.registerClass(zf);var SM={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};function Ft(r){return Ip(r)}function TM(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 SM?SM[r]:r,config:{}};return TM(t)}else return r instanceof Np?r:TM(r)}function F9(r){return new Pf(r)}function O9(r){return new Mf(r)}function P9(){return new Lf}function M9(r){return new zf(r)}var CC={};Ke(CC,{constant:()=>U9,glorotNormal:()=>J9,glorotUniform:()=>Z9,heNormal:()=>Q9,heUniform:()=>eJ,identity:()=>X9,leCunNormal:()=>tJ,leCunUniform:()=>rJ,ones:()=>j9,orthogonal:()=>oJ,randomNormal:()=>q9,randomUniform:()=>H9,truncatedNormal:()=>K9,varianceScaling:()=>Y9,zeros:()=>W9});var AM=["channelsFirst","channelsLast"],EM=["nearest","bilinear"],DM=["valid","same","causal"],$M=["max","avg"],RM=["sum","mul","concat","ave"];var Sp=new Map;function $t(r){Wi(AM,"DataFormat",r)}function FM(r){Wi(EM,"InterpolationFormat",r)}function Jr(r){Wi(DM,"PaddingMode",r)}function wC(r){Wi($M,"PoolMode",r)}var Bf=[],OM="/";function Ms(r,e){Bf.push(r);try{let t=e();return Bf.pop(),t}catch(t){throw Bf.pop(),t}}function L9(){return Bf.length===0?"":Bf.join(OM)+OM}function lx(r){if(!PM(r))throw new Error("Not a valid tensor name: '"+r+"'");return L9()+r}function ux(r){if(!PM(r))throw new Error("Not a valid tensor name: '"+r+"'");Sp.has(r)||Sp.set(r,0);let e=Sp.get(r);if(Sp.set(r,Sp.get(r)+1),e>0){let t=`${r}_${e}`;return Sp.set(t,1),t}else return r}var z9=new RegExp(/^[A-Za-z0-9][-A-Za-z0-9\._\/]*$/);function PM(r){return!!r.match(z9)}function MM(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 LM(r){return r=Array.isArray(r)?new Float32Array(r):r,Vt(r)}function sc(r){return Pi(LM(r)).dataSync()[0]}function Ls(r){return ur(LM(r)).dataSync()[0]}function zr(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 zM(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 BM(r){let e=[ts(r.shape)];return r.reshape(e)}function VM(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 Qc(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 kC(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 Qc(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 kC(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 kC(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 Qc(r,[0,e,0,0],[r.shape[0],t,r.shape[2],r.shape[3]]);case 3:return Qc(r,[0,0,e,0],[r.shape[0],r.shape[1],t,r.shape[3]]);case 4:return kC(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 Tp(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 _C(r,e){switch(r.rank){case 1:return kw([r,e]);case 2:return _w([r,e],0);case 3:return vw([r,e],0);case 4:return Cw([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 Ap(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?vC(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?vC(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 P(r,r)}function vC(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(vC(r.rank,e,t))))}function GM(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 WM(r){return V(()=>me(r,It(r).add(1)))}function mx(r,e,t,o){return V(()=>ek(r,e,t,o))}function jM(r){return V(()=>{let e=ee(.5,P(.2,r));return ir(e,0,1)})}function bl(r,e,t=!1){return t?r():e()}var UM=["fanIn","fanOut","fanAvg"],HM=["normal","uniform","truncatedNormal"];function B9(r){Wi(UM,"FanMode",r)}function V9(r){Wi(HM,"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 Nr(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(()=>P(le(this.value),Nr(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 Ap(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 P(this.gain,Xc(e[0]))})}getConfig(){return{gain:this.gain}}};qf.className="Identity";Q.registerClass(qf);function G9(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 Br=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,B9(this.mode),this.distribution=e.distribution==null?"normal":e.distribution,V9(this.distribution),this.seed=e.seed}apply(e,t){let o=G9(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}}};Br.className="VarianceScaling";Q.registerClass(Br);var Ep=class extends Br{constructor(e){super({scale:1,mode:"fanAvg",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return Br.className}};Ep.className="GlorotUniform";Q.registerClass(Ep);var Dp=class extends Br{constructor(e){super({scale:1,mode:"fanAvg",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return Br.className}};Dp.className="GlorotNormal";Q.registerClass(Dp);var $p=class extends Br{constructor(e){super({scale:2,mode:"fanIn",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return Br.className}};$p.className="HeNormal";Q.registerClass($p);var Rp=class extends Br{constructor(e){super({scale:2,mode:"fanIn",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return Br.className}};Rp.className="HeUniform";Q.registerClass(Rp);var Fp=class extends Br{constructor(e){super({scale:1,mode:"fanIn",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return Br.className}};Fp.className="LeCunNormal";Q.registerClass(Fp);var Op=class extends Br{constructor(e){super({scale:1,mode:"fanIn",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return Br.className}};Op.className="LeCunNormal";Q.registerClass(Op);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=Ap(o,0,1,"float32"),s=ik.gramSchmidt(n);return e[0]>e[1]&&(s=s.transpose()),P(this.gain,s)})}getConfig(){return{gain:this.gain,seed:this.seed}}};Kf.className="Orthogonal";Q.registerClass(Kf);var qM={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 KM(r,e={}){return Gi(r,Q.SerializationMap.getMap().classNameMap,e,"initializer")}function _t(r){return Ip(r)}function pt(r){if(typeof r=="string"){let e=r in qM?qM[r]:r;if(e==="GlorotNormal")return new Dp;if(e==="GlorotUniform")return new Ep;if(e==="HeNormal")return new $p;if(e==="HeUniform")return new Rp;if(e==="LeCunNormal")return new Fp;if(e==="LeCunUniform")return new Op;{let t={};return t.className=e,t.config={},KM(t)}}else return r instanceof co?r:KM(r)}function W9(){return new Gf}function j9(){return new ac}function U9(r){return new Wf(r)}function H9(r){return new jf(r)}function q9(r){return new Uf(r)}function K9(r){return new Hf(r)}function X9(r){return new qf(r)}function Y9(r){return new Br(r)}function Z9(r){return new Ep(r)}function J9(r){return new Dp(r)}function Q9(r){return new $p(r)}function eJ(r){return new Rp(r)}function tJ(r){return new Fp(r)}function rJ(r){return new Op(r)}function oJ(r){return new Kf(r)}var i0={};Ke(i0,{Layer:()=>Me,RNN:()=>ho,RNNCell:()=>Sl,activation:()=>kQ,add:()=>EQ,alphaDropout:()=>fee,average:()=>DQ,averagePooling1d:()=>a0,averagePooling2d:()=>l0,averagePooling3d:()=>u0,avgPool1d:()=>BQ,avgPool2d:()=>GQ,avgPool3d:()=>jQ,avgPooling1d:()=>VQ,avgPooling2d:()=>WQ,avgPooling3d:()=>UQ,batchNormalization:()=>MQ,bidirectional:()=>see,concatenate:()=>$Q,conv1d:()=>fQ,conv2d:()=>dQ,conv2dTranspose:()=>hQ,conv3d:()=>gQ,convLstm2d:()=>tee,convLstm2dCell:()=>ree,cropping2D:()=>yQ,dense:()=>_Q,depthwiseConv2d:()=>wQ,dot:()=>PQ,dropout:()=>vQ,elu:()=>aQ,embedding:()=>AQ,flatten:()=>IQ,gaussianDropout:()=>mee,gaussianNoise:()=>pee,globalAveragePooling1d:()=>HQ,globalAveragePooling2d:()=>qQ,globalMaxPool1d:()=>aee,globalMaxPool2d:()=>lee,globalMaxPooling1d:()=>AL,globalMaxPooling2d:()=>EL,gru:()=>XQ,gruCell:()=>YQ,input:()=>Fx,inputLayer:()=>iQ,layerNormalization:()=>LQ,leakyReLU:()=>uQ,lstm:()=>ZQ,lstmCell:()=>JQ,masking:()=>dee,maxPool1d:()=>uee,maxPool2d:()=>cee,maxPooling1d:()=>DL,maxPooling2d:()=>$L,maxPooling3d:()=>KQ,maximum:()=>RQ,minimum:()=>FQ,multiply:()=>OQ,permute:()=>TQ,prelu:()=>cQ,reLU:()=>lQ,repeatVector:()=>NQ,reshape:()=>SQ,rnn:()=>oee,separableConv2d:()=>xQ,simpleRNN:()=>QQ,simpleRNNCell:()=>eee,softmax:()=>pQ,spatialDropout1d:()=>CQ,stackedRNNCells:()=>nee,thresholdedReLU:()=>mQ,timeDistributed:()=>iee,upSampling2d:()=>bQ,zeroPadding2d:()=>zQ});var nJ=0;function fx(){return nJ++}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 Pp(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 Mp(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 XM="Variable",Xf=class{constructor(e,t="float32",o=XM,n=!0,s=null){this.dtype=t==null?"float32":t,this.shape=e.shape,this.id=fx(),o=o==null?XM:o,this.originalName=lx(o),this.name=ux(this.originalName),this.trainable_=n,this.constraint=s,this.val=Yw(e,this.trainable_,this.name,this.dtype)}read(){return this.assertNotDisposed(),this.val}write(e){return this.assertNotDisposed(),sJ(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 sJ(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 Lp(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||{}}},Vr=class{constructor(e,t,o,n,s,a,i){this.dtype=e,this.shape=t,this.sourceLayer=o,this.inputs=n,this.callArgs=s,this.outputTensorIndex=i,this.id=fx(),a!=null&&(this.originalName=lx(a),this.name=ux(this.originalName)),this.rank=t.length}},iJ=0,kl=class{constructor(e,t){this.callArgs=t,this.id=iJ++,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}}},aJ=0,Me=class extends Q.Serializable{constructor(e={}){super();this._callHook=null,this._addedWeightNames=[],this._stateful=!1,this.id=aJ++,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 Lr(`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 xr(this.getNodeAtIndex(e,"input").inputTensors)}getOutputAt(e){return xr(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 xr(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 xr(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 Vr)){n=!1;break}let s=!0;for(let a of o)if(a instanceof Vr){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(xr(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=xr(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=uJ(e);if(this.warnOnIncompatibleInputShape(Array.isArray(e)?a[0]:a),i!=null&&i.length>0&&Array.isArray(i[0])?l=i.map((c,p)=>new Vr(u,c,this,yt(e),t,this.name,p)):l=new Vr(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 Lr(`You tried to call countParams() on ${this.name}, but the layer is not built yet. Build it first by calling build(batchInputShape).`);return Mp(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(!y.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])}Lp(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=Pp(s),a=Pp(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 xr(e)}function uJ(r){return"float32"}function IC(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=IC(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 Vr(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 YM;(function(r){r[r.SILENT=0]="SILENT",r[r.VERBOSE=1]="VERBOSE"})(YM||(YM={}));var cJ=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)}},ZM=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],P(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=P(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=cJ),this.yieldEvery==="never"&&e.onYield!=null)throw new Error("yieldEvery is `never` but you provided an `onYield` callback. Either change `yieldEvery` or remove the callback");y.isNumber(this.yieldEvery)&&(this.maybeWait=NM(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()):y.isNumber(this.yieldEvery)&&o.push(this.maybeWait(this.currentEpoch,e,t)),await Promise.all(o)}async onTrainBegin(e){this.trainBegin!=null&&(await Ui(e),await this.trainBegin(e))}async onTrainEnd(e){this.trainEnd!=null&&(await Ui(e),await this.trainEnd(e))}};function 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){y.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 ZM,...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,Jt()),n=gt(Yr(t,o));return me(r,n)})}function Hi(r,e){return V(()=>dt(ic(ce(e,r)),-1))}function zp(r,e){return V(()=>dt(It(ce(e,r)),-1))}function vl(r,e){return V(()=>{let t=ce(r,e),o=ir(It(r),Jt(),Number.MAX_VALUE),n=It(me(t,o));return P(100,dt(n,-1))})}function pJ(r,e){return V(()=>{let t=ir(e,Jt(),Number.MAX_VALUE),o=lr(ee(1,t)),n=ir(r,Jt(),Number.MAX_VALUE),s=lr(ee(1,n));return dt(ic(ce(o,s)),-1)})}function mJ(r,e){return V(()=>{let t=Yr(0,ce(1,P(r,e)));return dt(ic(t),-1)})}function fJ(r,e){return V(()=>{let t=Yr(0,ce(1,P(r,e)));return dt(t,-1)})}function dJ(r,e){return V(()=>{let t=ge(P(r,e),-1),o=ur(P(ce(1,r),e),-1);return Yr(0,ee(1,ce(o,t)))})}function hJ(r,e){return V(()=>{let t=Math.log(2),o=ce(e,r),n=ce(ee(o,Ts(P(-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=ir(e,Jt(),1-Jt()),He(ge(P(r.toFloat(),lr(e)),e.shape.length-1))})}function Bp(r,e,t=!1){return V(()=>{let o=Ss(BM(r)).toInt();e=ir(e,Jt(),1-Jt());let n=e.shape,s=Cs(o,n[n.length-1]).reshape(n);return lc(s,e,t)})}function gJ(r,e){if(!y.arraysEqual(r.shape,e.shape))throw new z(`logits and labels must have the same shape, but got shapes ${JSON.stringify(r.shape)} and ${JSON.stringify(e.shape)}`);return V(()=>{let t=e.relu(),o=e.abs().neg();return t.sub(e.mul(r)).add(o.exp().log1p())})}function Vp(r,e){return V(()=>{let t;return t=ir(e,Jt(),1-Jt()),t=lr(me(t,ce(1,t))),dt(gJ(r,t),-1)})}function xJ(r,e){return V(()=>{let t=ir(r,Jt(),1),o=ir(e,Jt(),1);return ge(P(r,lr(me(t,o))),-1)})}function yJ(r,e){return V(()=>{let t=lr(ee(Jt(),e));return dt(ce(e,P(r,t)),-1)})}function Jf(r,e){return V(()=>{let t=Zf(r,-1),o=Zf(e,-1),n=P(t,o);return He(ge(n,-1))})}var Qf={meanSquaredError:Hi,meanAbsoluteError:zp,meanAbsolutePercentageError:vl,meanSquaredLogarithmicError:pJ,squaredHinge:mJ,hinge:fJ,categoricalHinge:dJ,logcosh:hJ,categoricalCrossentropy:lc,sparseCategoricalCrossentropy:Bp,binaryCrossentropy:Vp,kullbackLeiblerDivergence:xJ,poisson:yJ,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=P(.5,tr(e)),o=Ba(er(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 JM(r,e){return V(()=>hr(r.equal(1),e.equal(1)).sum().cast("float32"))}function bJ(r,e){return V(()=>hr(r.equal(1),e.equal(0)).sum().cast("float32"))}function wJ(r,e){return V(()=>hr(r.equal(0),e.equal(1)).sum().cast("float32"))}function NC(r,e){return V(()=>{let t=JM(r,e),o=wJ(r,e),n=t.add(o);return Dt(er(n,0),t.div(n),0).cast("float32")})}function QM(r,e){return V(()=>{let t=JM(r,e),o=bJ(r,e),n=t.add(o);return Dt(er(n,0),t.div(n),0).cast("float32")})}function Cx(r,e){return Vp(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 kJ=Hi,_J=Hi,vJ=zp,CJ=zp,IJ=vl,NJ=vl,rd=lc,SJ=Jf,SC=Bp,Nx={binaryAccuracy:ed,categoricalAccuracy:td,precision:NC,categoricalCrossentropy:rd,sparseCategoricalCrossentropy:SC,mse:kJ,MSE:_J,mae:vJ,MAE:CJ,mape:IJ,MAPE:NJ,cosine:SJ};function eL(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 tL(r){let e={Adagrad:()=>cl.adagrad(.01),Adadelta:()=>cl.adadelta(1,.95,Jt()),Adam:()=>cl.adam(.001,.9,.999,Jt()),Adamax:()=>cl.adamax(.002,.9,.999,Jt(),0),RMSProp:()=>cl.rmsprop(.001,.9,0,Jt()),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 rL=1*1024*1024;function AC(r,e,t=!1){if(r==null||typeof r!="object"||Object.getPrototypeOf(r)!==Object.prototype||!TC(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>rL&&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 <= ${rL}.`)}}function TC(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"||!TC(r[t]))return!1;return!0}else if(Array.isArray(r)){for(let e of r)if(!TC(e))return!1;return!0}else return!1;else{let e=typeof r;return e==="string"||e==="number"||e==="boolean"}}function oL(r,e,t,o=console.log){let n=AJ(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?EJ(i[c],t,o):DJ(i[c],t,a,o),o((c===i.length-1?"=":"_").repeat(e));r.checkTrainableWeightsConsistency();let l=TJ(r),u=Mp(r.nonTrainableWeights);o(`Total params: ${l+u}`),o(`Trainable params: ${l}`),o(`Non-trainable params: ${u}`),o("_".repeat(e))}function TJ(r){let e;return r.collectedTrainableWeights!=null?e=Mp(r.collectedTrainableWeights):e=Mp(r.trainableWeights),e}function AJ(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 EJ(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 DJ(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 nL(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];nL(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];nL(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 Gp="3.3.0";function $J(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]=$J(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 Vr){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 Vr){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)}},EC={},sL={};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(EC[c]==null){let d=RJ(a,e);p=d.sorted,m=d.recipientCounts,EC[c]=p,sL[c]=m}p=EC[c],m={},n||Object.assign(m,sL[c]);let f=new zs(e);for(let d=0;d<p.length;++d){if(o!=null){let O=Hc().numTensors;O>o.maxNumTensors&&(o.maxNumTensors=O),O<o.minNumTensors&&(o.minNumTensors=O)}let h=p[d],g=h.sourceLayer;if(g instanceof ji)continue;let x=[],b=[],w=[],k=!1;for(let O of h.inputs){let M=f.getValue(O),G=f.getMask(O);x.push(M),b.push(G),G!=null&&(k=!0),n||(m[O.name]--,m[O.name]===0&&!e.hasKey(O)&&i.indexOf(O.name)===-1&&!M.isDisposed&&O.sourceLayer.stateful!==!0&&w.push(M))}k&&(t=t||{},t.mask=b[0]);let _=yt(g.apply(x,t)),D=null;g.supportsMasking&&(D=g.computeMask(x,b));let T=FJ(h),R=Array.isArray(T)?T:[T];for(let O=0;O<R.length;++O){f.hasKey(R[O])||f.add(R[O],_[O],Array.isArray(D)?D[0]:D);let M=i.indexOf(R[O].name);M!==-1&&(l[M]=_[O])}n||Ae(w)}return f.disposeMasks(),s?l:l[0]}function RJ(r,e){y.assert(r!=null&&r.length>0,()=>"Expected at least one fetch, got none");let t=[],o={};if(r.length===1){let n=iL(r[0],e);t=n.sorted,o=n.recipientMap}else{let n=new Set;for(let s of r){let{sorted:a,recipientMap:i}=iL(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:OJ(o)}}function OJ(r){let e={};for(let t in r)e[t]=r[t].size;return e}function iL(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 FJ(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,_=b.tensorIndex;this.outputLayers.push(w),this.outputLayersNodeIndices.push(k),this.outputLayersTensorIndices.push(_)}for(let b of this.inputs){let w=b.sourceLayer,k=b.nodeIndex,_=b.tensorIndex;Go(k===0,"input layer has >1 nodes"),Go(_===0,"input layer has >1 tensors"),this.inputLayers.push(w),this.inputLayersNodeIndices.push(k),this.inputLayersTensorIndices.push(_)}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,_,D,T)=>{(_==null||D==null||T==null)&&(_=b.sourceLayer,D=b.nodeIndex,T=b.tensorIndex);let R=_.inboundNodes[D];if(k.indexOf(R)!==-1)throw new Lr(`The tensor ${b.name} at layer "${_.name}" is part of a cycle.`);if(w.indexOf(R)!==-1)return;this.containerNodes.add(Wo.nodeKey(_,D)),_.id in a||(a[_.id]=Object.keys(a).length),k.indexOf(R)===-1&&k.push(R);let O=R.inboundLayers.length;for(let M=0;M<O;M++){let G=R.inputTensors[M],j=R.inboundLayers[M],U=R.nodeIndices[M],H=R.tensorIndices[M];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 _=0;_<b.inboundLayers.length;_++){let D=b.inboundLayers[_],T=b.nodeIndices[_],R=D.inboundNodes[T],O=t[R.id]==null?0:t[R.id];t[R.id]=Math.max(w+1,O),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,_)=>{let D=a[k.id],T=a[_.id];return D<T?-1:D>T?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 _ of w.inputTensors)if(h.indexOf(_)===-1)throw new Lr(`Graph disconnected: cannot obtain value for tensor ${_} at layer "${k.name}". The following previous layers were accessed without issue: ${g}`);for(let _ of w.outputTensors)h.push(_);g.push(k.name)}}this.nodesByDepth=m;let x=this.layers.map(b=>b.name);for(let b of x){let w=x.filter(k=>k===b).length;if(w!==1)throw new Lr(`The name "${b}" is used ${w} times in the model. All layer names should be unique. Layer names: `+JSON.stringify(x))}this.outboundNodes=[],this.inboundNodes=[],new 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}`)}Lp(s)}updatedConfig(){let e=this.getConfig(),t={};return t.className=this.getClassName(),t.config=e,t.kerasVersion=`tfjs-layers ${Gp}`,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=Pp(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],x=u.nodeIndices[h],b=u.tensorIndices[h],w=`${g.name}_${x}_${b}`,k=o[w];p.push(k)}let m=c.computeOutputShape(xr(p)),f=Pp(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 xr(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,x,b,w;if(c.callArgs!=null&&(h=c.callArgs),d.length===1){let[k,_]=d[0];h.mask==null&&(h.mask=_),b=yt(p.call(k,h)),w=yt(p.computeMask(k,_)),g=[k],x=[_]}else g=d.map(k=>k[0]),x=d.map(k=>k[1]),h.mask==null&&(h.mask=x),b=yt(p.call(g,h)),w=yt(p.computeMask(g,x));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 _=f[k],D=b[k],T=w[k];o[_.id]=[D,T]}}}}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 x=m.inboundLayers[g],b=m.nodeIndices[g],w=m.tensorIndices[g],k=Wo.nodeKey(x,b),_=t[k];_==null&&(_=0),h.push([x.name,_,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,x){g.name in a?a[g.name].push(x):a[g.name]=[x]}function l(g,x){let b=[],w;for(let k of x){let _=k[0],D=k[1],T=k[2];if(w=k[3]==null?{}:k[3],!(_ in s)){i(g,x);return}let R=s[_];if(R.inboundNodes.length<=D){i(g,x);return}let O=R.inboundNodes[D];b.push(O.outputTensors[T])}b.length>0&&g.apply(xr(b),w)}function u(g){let x=g.name,b=Qr(g,t.customObjects!=null?t.customObjects:{});b.setFastWeightInitDuringBuild(n),s[x]=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(;!CM(a);)for(let g of p){let x=s[g.name];if(x.name in a){let b=a[x.name];delete a[x.name];for(let w of b)l(x,w)}}let m=[],f=[],d=t.inputLayers;for(let g of d){let x=g[0],b=g[1],w=g[2];Go(x in s);let _=s[x].inboundNodes[b].outputTensors;m.push(_[w])}let h=t.outputLayers;for(let g of h){let x=g[0],b=g[1],w=g[2];Go(x in s);let _=s[x].inboundNodes[b].outputTensors;f.push(_[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 PJ(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 PJ(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 aL(r,e){return P(r,e)}var MJ=32;function uL(r,e){let t,o,n=e;t=n.xs,o=n.ys,y.assert(t!=null&&o!=null,()=>`A Dataset iterator for fitDataset() is expected to generate objects of the form \`{xs: xVal, ys: yVal}\`, where the two values may be \`tf.Tensor\`, an array of Tensors, or a map of string to Tensor. The provided Dataset instead generates ${e}`);let s=lL("input",r.inputNames,t),a=lL("output",r.outputNames,o),i=s[0].shape[0];y.assert(s.length===r.inputs.length,()=>`LayersModel has ${r.inputs.length} inputs, but the dataset provides ${s.length} inputs. (Expected input keys: ${JSON.stringify(r.inputNames)})`),y.assert(a.length===r.outputs.length,()=>`LayersModel has ${r.outputs.length} outputs, but the dataset provides ${a.length} outputs. (Expected output keys: ${JSON.stringify(r.outputNames)})`);for(let l=0;l<s.length;l++)y.assert(s[l].shape[0]===i,()=>`Batch size mismatch: input ${r.inputNames[l]} has ${s[l].shape[0]}; expected ${i} based on input ${r.inputNames[0]}.`);for(let l=0;l<a.length;l++)y.assert(a[l].shape[0]===i,()=>`Batch size mismatch: output ${r.outputNames[l]} has ${a[l].shape[0]}; expected ${i} based on input ${r.inputNames[0]}.`);return{xs:s,ys:a}}function lL(r,e,t){if(t instanceof Ve)return[t];if(Array.isArray(t))return y.assert(t.length===e.length,()=>`Received an array of ${t.length} Tensors, but expected ${e.length} to match the ${r} keys ${e}.`),t;{let o=[];for(let n of e){if(t[n]==null)throw new z(`The feature data generated by the dataset lacks the required ${r} key '${n}'.`);o.push(t[n])}return o}}function LJ(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 pL(r,e,t){let o=t.batchesPerEpoch!=null;if(y.assert(r.optimizer!=null,()=>"You must compile a model before training/testing. Use LayersModel.compile(modelCompileConfig)."),y.assert(t!=null,()=>"For fitDataset(), the 2nd argument (config) is required, but it is not provided in this call."),y.assert(t.epochs!=null&&t.epochs>0&&Number.isInteger(t.epochs),()=>`For fitDataset(), config.epochs is expected to be a positive integer, but got ${t.epochs}`),y.assert(!o||t.batchesPerEpoch>0&&Number.isInteger(t.batchesPerEpoch),()=>`For fitDataset(), config.batchesPerEpoch is expected to be a positive integer if specified, but got ${t.batchesPerEpoch}`),y.assert(t.validationSplit==null,()=>"`validationSplit` is not supported by `fitDataset()`. Use validationData instead."),r.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");r.isTraining=!0;try{let n=t.validationData!=null,s,a;if(n)if(cL(t.validationData))y.assert(t.validationBatches==null||t.validationBatches>0&&Number.isInteger(t.validationBatches),()=>`For fitDataset() with dataset-based validation, config.validationBatches is expected not to be provided, or to be a positive integer, but got ${t.validationBatches}`);else{let g=LJ(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,zJ(e,t),null,n,u);m.setModel(r),r.history=f,await m.onTrainBegin(),r.stopTraining_=!1;let d=t.initialEpoch==null?0:t.initialEpoch,h=await e.iterator();for(;d<t.epochs;){let g={};await m.onEpochBegin(d);let x=0,b=0;for(o||(h=await e.iterator());o?x<t.batchesPerEpoch:!0;){let 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 ${x} batches; interrupting training. Make sure that your dataset can generate at least \`batchesPerEpoch * epochs\` batches (in this case, ${t.batchesPerEpoch*t.epochs} batches). You may need to use the repeat() function when building your dataset.`);break}if(w.value!=null){let{xs:k,ys:_}=uL(r,w.value),D={};D.batch=b,D.size=k[0].shape[0],await m.onBatchBegin(b,D);let T=[];if(t.classWeight!=null){let M=Ax(t.classWeight,r.outputNames);for(let G=0;G<M.length;++G)T.push(await Ex(_[G],null,M[G]))}let R=k.concat(_).concat(T),O=i(R);Ae(R);for(let M=0;M<l.length;++M){let G=l[M],j=O[M];D[G]=j,Et(j)}await m.onBatchEnd(b,D),xx(D),b++,x++}if(o?x>=t.batchesPerEpoch:w.done){if(n){let k;cL(t.validationData)?k=yt(await r.evaluateDataset(t.validationData,{batches:t.validationBatches})):k=yt(r.evaluate(s,a,{batchSize:t.validationBatchSize==null?MJ:t.validationBatchSize,verbose:0}));for(let _=0;_<r.metricsNames.length;++_)g[`val_${r.metricsNames[_]}`]=k[_]}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 zJ(r,e){let t=null;return e.batchesPerEpoch!=null?t=e.batchesPerEpoch:Number.isFinite(r.size)&&(t=r.size),t}function cL(r){return typeof r.iterator=="function"}function BJ(r){return typeof r.next=="function"}async function mL(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.");y.assert(!o||t.batches>0&&Number.isInteger(t.batches),()=>`Test loop expects \`batches\` to be a positive integer, but received ${JSON.stringify(t.batches)}`);let a=BJ(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}=uL(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],x=s[h];s[h]=V(()=>ee(s[h],P(d,g))),l>0&&Ae(x)}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 xr(s)}function Dx(r){y.assert(r>0&&Number.isInteger(r),()=>`batchSize is required to be a positive integer, but got ${r}`)}function Wp(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 VJ(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"),x;g!=null&&(x=zr(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 _={};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&&y.shuffle(x);let D=Vt(x),T=Rx(g,n);for(let R=0;R<T.length;++R){let O={};if(await b.onBatchBegin(R,O),V(()=>{let M=T[R][0],G=T[R][1],j=Ga(D,M,G-M);O.batch=R,O.size=G-M;let U=$x(t,j),H=e(U);for(let q=0;q<o.length;++q){let X=o[q],oe=H[q];O[X]=oe,Et(oe)}if(R===T.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),_["val_"+oe]=Y}}}),await b.onBatchEnd(R,O),xx(O),r.stopTraining_)break}D.dispose()}if(await b.onEpochEnd(k,_),r.stopTraining_)break}return await b.onTrainEnd(),await r.history.syncData(),r.history}async function fL(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 T=!0,R=await r.standardizeUserData(a,i,null,null,T,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 T=Math.floor(n[0].shape[0]*(1-o.validationSplit)),R=n[0].shape[0];l=Wp(n,T,R),n=Wp(n,0,T),u=Wp(s,T,R),s=Wp(s,0,T),h=l.concat(u)}else o.validationSteps!=null&&(d=!0);let g=n.concat(s).concat(c);r.checkTrainableWeightsConsistency();let x=r.makeTrainFunction(),b=r.getDedupedMetricsNames(),w,k;d?(r.makeTestFunction(),w=r.testFunction,k=b.slice().concat(b.map(T=>"val_"+T))):(w=null,h=[],k=b.slice());let _=kx(o.callbacks,o.yieldEvery);return await VJ(r,x,g,b,p,o.epochs,o.verbose,_,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 DC(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 GJ(r){return r instanceof Ve}function $C(r){return Array.isArray(r)}function dL(r){return!GJ(r)&&!$C(r)}function hL(r,e,t,o=!0,n=""){if(e==null||e.length===0){if(r!=null){let a=!1;if($C(r)&&r.length>0)a=!0;else if(dL(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(dL(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($C(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=DC(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 WJ(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&&!y.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 jJ(r,e,t){let o=[Hi,Vp,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 gL(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 UJ(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 HJ="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).");oL(this,e,t,o)}compile(e){if(e.loss==null&&(e.loss=[]),this.loss=e.loss,typeof e.optimizer=="string")this.optimizer_=tL(e.optimizer),this.isOptimizerOwned=!0;else{if(!(e.optimizer instanceof Pr))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=UJ(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]===Vp?["accuracy","acc"].indexOf(d)!==-1?m=ed:["crossentropy","ce"].indexOf(d)!==-1&&(m=Cx):this.lossFunctions[a]===Bp?["accuracy","acc"].indexOf(d)!==-1?m=Ix:["crossentropy","ce"].indexOf(d)!==-1&&(m=SC):["accuracy","acc"].indexOf(d)!==-1?m=td:["crossentropy","ce"].indexOf(d)!==-1&&(m=rd);let x;["accuracy","acc"].indexOf(d)!==-1?x="acc":["crossentropy","ce"].indexOf(d)!==-1&&(x="ce"),f=m,p=c+x}else f=eL(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 xr(u)}finally{Cl(a[0],e),Cl(a[1],t)}}async evaluateDataset(e,t){return this.makeTestFunction(),mL(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=Wp(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 xr(a.map(i=>Ze(i,0)))})}predict(e,t={}){let o=DC(e);gL(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){gL(e,this.inputNames,this.feedInputShapes,!0);let t=(Array.isArray(e)?e[0]:e).shape[0];return this.predictLoop(e,t)}standardizeUserDataXY(e,t,o=!0,n){if(this.optimizer_==null)throw new Lr("You must compile a model before training/testing. Use LayersModel.compile(modelCompileArgs).");let s=[];for(let a=0;a<this.feedOutputShapes.length;++a){let i=this.feedOutputShapes[a];this.feedLossFns[a]===Bp?s.push(i.slice(0,i.length-1).concat([1])):s.push(i)}if(e=hL(e,this.feedInputNames,this.feedInputShapes,!1,"input"),t=hL(t,this.feedOutputNames,s,!1,"target"),WJ(e,t,null),jJ(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(zr(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 x=h[g];i[g]=ee(i[g],P(m-p,x))}}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;gC(e,n)>1&&(s+=`_${gC(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 x=this.lossFunctions[h](n[h],f[h]);s[h]!=null&&(x=aL(x,s[h]));let b=dt(x);t.push(b),h===0?d=x:d=ee(d,x)}for(let h=0;h<this.metricsTensors.length;++h){let g;if(this.outputs.length>1&&h<this.outputs.length)g=t[h];else{let x=this.metricsTensors[h][0],b=this.metricsTensors[h][1];g=dt(x(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 fL(this,e,t,o)}async fitDataset(e,t){return pL(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),xr(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=Hc().numTensors;this.optimizer_.dispose(),e.numDisposedVariables+=t-Hc().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=Ir.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 Ir.encodeWeights(this.getNamedWeights(t)),n=!1,s=null,i={modelTopology:this.toJSON(s,n),format:HJ,generatedBy:`TensorFlow.js tfjs-layers v${Gp}`,convertedBy:null};if((t==null?!1:t.includeOptimizer)&&this.optimizer!=null){i.trainingConfig=this.getTrainingConfig();let u="optimizer",{data:c,specs:p}=await Ir.encodeWeights(await this.optimizer.getWeights(),u);o.specs.push(...p),o.data=Ir.concatenateArrayBuffers([o.data,c])}if(this.userDefinedMetadata!=null){let u=!0;AC(this.userDefinedMetadata,this.name,u),i.userDefinedMetadata=this.userDefinedMetadata}return i.weightData=o.data,i.weightSpecs=o.specs,e.save(i)}setUserDefinedMetadata(e){AC(e,this.name),this.userDefinedMetadata=e}getUserDefinedMetadata(){return this.userDefinedMetadata}};To.className="Model";Q.registerClass(To);var RC=class extends To{};RC.className="Functional";Q.registerClass(RC);async function xL(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 Ir.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 yL(r,e){if(e==null&&(e={}),typeof r=="string"){let t=Ir.getLoadHandlers(r,e);if(t.length===0)t.push(Ir.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 qJ(r,void 0,e)}async function qJ(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}=KJ(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 KJ(r,e){let t=Ir.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=IC(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 Lr("The model needs to be compiled before being used.");return this.model.evaluate(e,t,o)}async evaluateDataset(e,t){if(!this.built)throw new Lr("The model needs to be compiled before being used.");return this.model.evaluateDataset(e,t)}predict(e,t={}){return this.model==null&&this.build(),this.model.predict(e,t)}predictOnBatch(e){return this.model==null&&this.build(),this.model.predictOnBatch(e)}compile(e){this.build(),this.model.compile(e),this.optimizer_=this.model.optimizer,this.isOptimizerOwned=this.model.isOptimizerOwned,this.loss=this.model.loss,this.metrics=this.model.metrics,this.metricsTensors=this.model.metricsTensors,this.metricsNames=this.model.metricsNames}get optimizer(){return this.model==null?void 0:this.model.optimizer}set optimizer(e){this.model.optimizer=e}async fit(e,t,o={}){if(!this.built)throw new Lr("The model needs to be compiled before being used.");return this.model.fit(e,t,o)}async fitDataset(e,t){if(!this.built)throw new Lr("The model needs to be compiled before being used.");return this.model.fitDataset(e,t)}async trainOnBatch(e,t){return this.model.trainOnBatch(e,t)}static fromConfig(e,t,o={},n=!1){let s,a={};if(t instanceof Array){if(t[0].className==null||t[0].className==="Merge")throw new z("Legacy serialization format not supported yet.");s=t}else y.assert(t.layers!=null,()=>"When the config data for a Sequential model is not an Array, it must be an Object that contains the 'layers' field."),s=t.layers,delete t.layers,a=t;let i=new e(a);if(!(i instanceof 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 bL(r){return new To(r)}function wL(r){return new qi(r)}function kL(r,e){return e==null&&(e={}),yL(r,e)}function Fx(r){return gx(r)}function _L(r,e){po.registerCallbackConstructor(r,e)}var mo=class extends Q.Serializable{getConfig(){return{}}},FC=class extends mo{apply(e,t=1){return GM(e,t)}};FC.className="elu";Q.registerClass(FC);var OC=class extends mo{apply(e){return Ou(e)}};OC.className="selu";Q.registerClass(OC);var PC=class extends mo{apply(e){return Sr(e)}};PC.className="relu";Q.registerClass(PC);var MC=class extends mo{apply(e){return V(()=>As(6,Sr(e)))}};MC.className="relu6";Q.registerClass(MC);var LC=class extends mo{apply(e){return e}};LC.className="linear";Q.registerClass(LC);var zC=class extends mo{apply(e){return qr(e)}};zC.className="sigmoid";Q.registerClass(zC);var BC=class extends mo{apply(e){return jM(e)}};BC.className="hardSigmoid";Q.registerClass(BC);var VC=class extends mo{apply(e){return Ts(e)}};VC.className="softplus";Q.registerClass(VC);var GC=class extends mo{apply(e){return WM(e)}};GC.className="softsign";Q.registerClass(GC);var WC=class extends mo{apply(e){return Oi(e)}};WC.className="tanh";Q.registerClass(WC);var nd=class extends mo{apply(e,t=-1){return Aa(e,t)}};nd.className="softmax";Q.registerClass(nd);var jC=class extends mo{apply(e,t=-1){return Au(e,t)}};jC.className="logSoftmax";Q.registerClass(jC);var UC=class extends mo{apply(e,t=1){return V(()=>qr(e.mul(t)).mul(e))}};UC.className="swish";Q.registerClass(UC);function Bs(r){return r.getClassName()}function HC(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={},HC(e)}if(typeof r=="string"){let e={};return e.className=r,e.config={},HC(e)}else return r instanceof mo?r:HC(r)}function qC(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 KC=class extends Q.Serializable{},pc=class extends KC{constructor(e){super();qC(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(P(this.l1,It(e))))),this.hasL2&&(t=ee(t,ge(P(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 vL(r){return qC(r),new pc({l1:r!=null?r.l1:null,l2:0})}function CL(r){return qC(r),new pc({l2:r!=null?r.l2:null,l1:0})}var IL={l1l2:"L1L2"};function st(r){return Ip(r)}function NL(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 IL?IL[r]:r,config:{}};return NL(t)}else return r instanceof KC?r:NL(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=Sr(e);return this.maxValue!=null&&(o=ir(o,0,this.maxValue)),o}computeOutputShape(e){return e}getConfig(){let e={maxValue:this.maxValue},t=super.getConfig();return Object.assign(e,t),e}};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(!MM(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 XC(r,e){return V(()=>($t(e),e==="channelsFirst"?Ue(r,[0,2,3,4,1]):r))}function XJ(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 SL(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 YJ(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=XC(r,s);if(n==="causal")throw new Se("The support for CAUSAL padding mode in conv3dWithBias is not implemented yet.");return i=Dm(i,e,o,n==="same"?"same":"valid","NDHWC",a),t!=null&&(i=uo(i,t)),s==="channelsFirst"&&(i=Ue(i,[0,4,1,2,3])),i})}var jp=class extends Me{constructor(e,t){super(t);if(this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",jp.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 jp{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=SL(e,this.kernel.read(),n,this.strides,this.padding,this.dataFormat,this.dilationRate,s);else{if(this.rank===1)o=XJ(e,this.kernel.read(),n,this.strides[0],this.padding,this.dataFormat,this.dilationRate[0]);else if(this.rank===2)o=SL(e,this.kernel.read(),n,this.strides,this.padding,this.dataFormat,this.dilationRate);else if(this.rank===3)o=YJ(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 x=vu(o,this.kernel.read(),g,this.strides,this.padding);return this.dataFormat!=="channelsLast"&&(x=Ue(x,[0,3,1,2])),this.bias!=null&&(x=uo(x,this.bias.read(),this.dataFormat)),this.activation!=null&&(x=this.activation.apply(x)),x})}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 YC=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}};YC.className="SeparableConv";var dd=class extends YC{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,FM(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 ZJ(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 jp{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=ZJ(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 ZC(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 JC(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(zr(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=ar(n,-1)),n=Ue(n,u)),o&&(e=qt(e,0),n!=null&&(n=qt(n,0)));let c=[],p,m=t,f=e.shape[0],d=pr(e),h;n!=null&&(h=pr(n));for(let x=0;x<f;++x){let b=d[x],w=V(()=>r(b,m));if(n==null)p=w[0],m=w[1];else{let k=V(()=>{let _=h[x],D=tr(_).sub(_),T=w[0].mul(_).add(m[0].mul(D)),R=m.map((O,M)=>w[1][M].mul(_).add(O.mul(D)));return{output:T,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 Up({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 zr(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(!y.arraysEqual(this.stateSpec.map(i=>i.shape[i.shape.length-1]),a))throw new z(`An initialState was passed that is not compatible with cell.stateSize. Received stateSpec=${this.stateSpec}; However cell.stateSize is ${this.cell.stateSize}`)}else this.stateSpec=a.map(i=>new St({shape:[null,i]}));this.stateful&&this.resetStates()}resetStates(e,t=!1){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(!y.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=ZC(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 Vr){let u=[e].concat(a),c=this.inputSpec.concat(i),p=this.inputSpec;this.inputSpec=c;let m=super.apply(u,t);return this.inputSpec=p,m}else return super.apply(e,t)}call(e,t){return V(()=>{let o=t==null?null:t.mask,n=t==null?null:t.training,s=t==null?null:t.initialState;e=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=JC((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{},Hp=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:()=>tr(e),rate:this.dropout,training:n})),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=Wa({ones:()=>tr(o),rate:this.recurrentDropout,training:n}));let s,a=this.dropoutMask,i=this.recurrentDropoutMask;a!=null?s=rs(P(e,a),this.kernel.read()):s=rs(e,this.kernel.read()),this.bias!=null&&(s=uo(s,this.bias.read())),i!=null&&(o=P(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)}};Hp.className="SimpleRNNCell";Q.registerClass(Hp);var yd=class extends ho{constructor(e){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 new e(t)}};yd.className="SimpleRNN";Q.registerClass(yd);var qp=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:()=>tr(e),rate:this.dropout,training:o,count:3})),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=Wa({ones:()=>tr(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=P(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=P(n,a[0]));let p=this.recurrentKernel.read(),[m,f]=cr(p,[2*this.units,this.units],p.rank-1),d=rs(n,m),[h,g,x]=cr(c,3,c.rank-1),[b,w]=cr(d,2,d.rank-1);i=this.recurrentActivation.apply(ee(h,b)),l=this.recurrentActivation.apply(ee(g,w));let k=rs(P(l,n),f);u=this.activation.apply(ee(x,k));let _=ee(P(i,n),P(ee(1,He(i)),u));return[_,_]})}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)}};qp.className="GRUCell";Q.registerClass(qp);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 qp(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 _C(_C(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:()=>tr(e),rate:this.dropout,training:o,count:4})),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=Wa({ones:()=>tr(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=P(e,a[0]));let m=rs(e,this.kernel.read());0<this.recurrentDropout&&this.recurrentDropout<1&&(n=P(n,i[0])),m=ee(m,rs(n,this.recurrentKernel.read())),this.useBias&&(m=uo(m,this.bias.read()));let[f,d,h,g]=cr(m,4,m.rank-1);l=this.recurrentActivation.apply(f),u=this.recurrentActivation.apply(d),c=ee(P(u,s),P(l,this.activation.apply(h))),p=this.recurrentActivation.apply(g);let x=P(p,this.activation.apply(c));return[x,x,c]})}getConfig(){let e=super.getConfig(),t={units:this.units,activation: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 Up=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]])}Lp(t)}};Up.className="StackedRNNCells";Q.registerClass(Up);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 JJ=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 QC=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(!y.arraysEqual(l.shape,u))throw new z(`State ${i} is incompatible with layer ${this.name}: expected shape=${u}, received shape=${l.shape}`);this.states_[i]=l}}this.states_=this.states_.map(i=>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]]}};QC.className="ConvRNN2D";var Kp=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=Nr([c]),g=u.apply([c*2]);return Tp([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:()=>tr(n),rate:this.dropout,training:o,count:i}));let l=this.dropoutMask,u=(J,ie,ue)=>!ie||!ie[ue]?J:P(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:()=>tr(s),rate:this.recurrentDropout,training:o,count:i}));let d=this.recurrentDropoutMask,h=u(s,d,0),g=u(s,d,1),x=u(s,d,2),b=u(s,d,3),w=3,[k,_,D,T]=cr(this.kernel.read(),i,w),[R,O,M,G]=this.useBias?cr(this.bias.read(),i):[null,null,null,null];c=this.inputConv(c,k,R,this.padding),p=this.inputConv(p,_,O,this.padding),m=this.inputConv(m,D,M,this.padding),f=this.inputConv(f,T,G,this.padding);let[j,U,H,q]=cr(this.recurrentKernel.read(),i,w);h=this.recurrentConv(h,j),g=this.recurrentConv(g,U),x=this.recurrentConv(x,H),b=this.recurrentConv(b,q);let X=this.recurrentActivation.apply(ee(c,h)),oe=this.recurrentActivation.apply(ee(p,g)),Y=ee(P(oe,a),P(X,this.activation.apply(ee(m,x)))),re=P(this.recurrentActivation.apply(ee(f,b)),this.activation.apply(Y));return[re,re,Y]})}getConfig(){let e=super.getConfig(),{units:t}=e,o=JJ(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")}};Kp.className="ConvLSTM2DCell";Q.registerClass(Kp);var kd=class extends QC{constructor(e){let t=new Kp(e);super(Object.assign({},e,{cell:t}))}static fromConfig(e,t){return new e(t)}};kd.className="ConvLSTM2D";Q.registerClass(kd);var Xp=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()}};Xp.className="Dropout";Q.registerClass(Xp);var _d=class extends Xp{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 VM(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),zM(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=zr(1,e.dims.length+1);if(!y.arraysEqual(e.dims.slice().sort(),t))throw new Error("Invalid permutation `dims`: "+JSON.stringify(e.dims)+" `dims` must contain consecutive integers starting from 1.");this.dims=e.dims,this.dimsIncludingBatch=[0].concat(this.dims),this.inputSpec=[new St({ndim:this.dims.length+1})]}computeOutputShape(e){e=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=zr(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(zr(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:ar(n,0));let o=t[0];for(let n=1;n<t.length-1;++n)o=hr(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=P(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 P(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(y.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(()=>Tp(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(tr(e[a]).asType("bool")):t[a].rank<e[a].rank?n.push(ar(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 QJ(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(y.assert(r.shape.length>=2,()=>`batchDot requires the rank of x to be >= 2, but got ${r.shape.length}`),y.assert(r.shape.length>=2,()=>`batchDot requires the rank of y to be >= 2, but got ${e.shape.length}`),typeof t=="number"&&(t=[t,t]),r.dtype==="complex64"||e.dtype==="complex64")throw new 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){y.assert(Array.isArray(e)&&e.length===2&&Array.isArray(e[0])&&Array.isArray(e[1]),()=>"A `Dot` layer should be called on a list of exactly 2 inputs.");let t=e[0],o=e[1];if(t.length>3||o.length>3)throw new 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])),QJ(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){y.assert(Array.isArray(e)&&e.length===2&&Array.isArray(e[0])&&Array.isArray(e[1]),()=>"A `Dot` layer should be called on a list of exactly 2 inputs.");let t=e[0].slice(),o=e[1].slice();if(t.length>3||o.length>3)throw new 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(()=>Ap(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(Ap(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=xw(r,e,t,o,n,s);else if(r.rank===3)a=yw(r,e,t,o,n,s);else if(r.rank===4)a=bw(r,e,t,o,n,s);else throw new Se(`batchNormalization is not implemented for array of rank ${r.rank} yet`);return a}function eQ(r,e,t,o,n=.001){return V(()=>{let s=Yc(r,o),a=s.mean,i=s.variance;return[Gd(r,a,i,t,e,n),a,i]})}function tQ(r,e,t,o,n=.001){return V(()=>{let s=Yc(r,o),a=s.mean,i=s.variance,l=[];for(let d of zr(0,r.rank))o.indexOf(d)!==-1?l.push(1):l.push(r.shape[d]);let u=a.reshape(l),c=i.reshape(l),p=e==null?null:e.reshape(l),m=t==null?null:t.reshape(l);return[Gd(r,u,c,m,p,n),a,i]})}function rQ(r,e,t,o,n=.001){return y.arraysEqual(o.slice().sort(),zr(0,r.rank-1))?eQ(r,e,t,o,n):tQ(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=zr(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=!y.arraysEqual(c,zr(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,_=this.scale?this.gamma.read().reshape(u):null;return Gd(n,b,w,k,_,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]=rQ(n,this.gamma.read(),this.beta.read(),i,this.epsilon),g=(b,w,k)=>{V(()=>{let _=1-k,D=b.read(),T=D.sub(w).mul(_);b.write(D.sub(T))})};return(()=>{g(this.movingMean,d,this.momentum),g(this.movingVariance,h,this.momentum)})(),f})}getConfig(){let e={axis:this.axis,momentum:this.momentum,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:_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}=Yc(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 oQ(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]],Fr(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(()=>oQ(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),wC(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 TL(r,e,t,o,n,s){return V(()=>{$t(n),wC(s),Jr(o),t==null&&(t=[1,1,1]),o==null&&(o="valid"),n==null&&(n=Zr()),s==null&&(s="max"),r=XC(r,n);let a,i=o==="same"?"same":"valid";return s==="max"?a=Bm(r,e,t,i):a=Am(r,e,t,i),n==="channelsFirst"&&(a=Ue(a,[0,4,1,2,3])),a})}var e0=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 e0{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 e0{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 t0=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 t0{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 t0{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 r0=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 r0{constructor(e){super(e)}poolingFunction(e,t,o,n,s){return $t(s),Jr(n),TL(e,t,o,n,s,"max")}};Yd.className="MaxPooling3D";Q.registerClass(Yd);var Zd=class extends r0{constructor(e){super(e)}poolingFunction(e,t,o,n,s){return $t(s),Jr(n),TL(e,t,o,n,s,"avg")}};Zd.className="AveragePooling3D";Q.registerClass(Zd);var o0=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 o0{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 o0{constructor(e){super(e||{})}call(e,t){return V(()=>{let o=Fe(e);return ur(o,1)})}};Qd.className="GlobalMaxPooling1D";Q.registerClass(Qd);var n0=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 n0{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 n0{call(e,t){return V(()=>{let o=Fe(e);return this.dataFormat==="channelsLast"?ur(o,[1,2]):ur(o,[2,3])})}};th.className="GlobalMaxPooling2D";Q.registerClass(th);var s0=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 s0{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),JC((a,i)=>[Fe(this.layer.call(a,t)),[]],e,[],!1,null,null,!1,!0)[1]))}};rh.className="TimeDistributed";Q.registerClass(rh);function nQ(r){Wi(RM,"BidirectionalMergeMode",r)}var sQ="concat",oh=class extends s0{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?sQ:e.mergeMode,nQ(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()):xr(n)}apply(e,t){let o=t==null?null:t.initialState,n=t==null?null:t.constants;t==null&&(t={});let s=ZC(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 Vr;for(let u of a)if(u instanceof Vr!==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=qt(s,1));let i;return this.mergeMode==="concat"?i=Tp([n,s]):this.mergeMode==="sum"?i=ee(n,s):this.mergeMode==="ave"?i=P(.5,ee(n,s)):this.mergeMode==="mul"?i=P(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 iQ(r){return new ji(r)}function aQ(r){return new ld(r)}function lQ(r){return new sd(r)}function uQ(r){return new id(r)}function cQ(r){return new ad(r)}function pQ(r){return new cd(r)}function mQ(r){return new ud(r)}function fQ(r){return new dc(r)}function dQ(r){return new Nl(r)}function hQ(r){return new fd(r)}function gQ(r){return new fc(r)}function xQ(r){return new dd(r)}function yQ(r){return new hd(r)}function bQ(r){return new gd(r)}function wQ(r){return new xd(r)}function kQ(r){return new Id(r)}function _Q(r){return new vd(r)}function vQ(r){return new Xp(r)}function CQ(r){return new _d(r)}function IQ(r){return new Cd(r)}function NQ(r){return new Nd(r)}function SQ(r){return new Sd(r)}function TQ(r){return new Td(r)}function AQ(r){return new Ed(r)}function EQ(r){return new Dd(r)}function DQ(r){return new Rd(r)}function $Q(r){return new Pd(r)}function RQ(r){return new Fd(r)}function FQ(r){return new Od(r)}function OQ(r){return new $d(r)}function PQ(r){return new Ld(r)}function MQ(r){return new Wd(r)}function LQ(r){return new jd(r)}function zQ(r){return new Ud(r)}function a0(r){return new qd(r)}function BQ(r){return a0(r)}function VQ(r){return a0(r)}function l0(r){return new Xd(r)}function GQ(r){return l0(r)}function WQ(r){return l0(r)}function u0(r){return new Zd(r)}function jQ(r){return u0(r)}function UQ(r){return u0(r)}function HQ(r){return new Jd(r)}function qQ(r){return new eh(r)}function AL(r){return new Qd(r)}function EL(r){return new th(r)}function DL(r){return new Hd(r)}function $L(r){return new Kd(r)}function KQ(r){return new Yd(r)}function XQ(r){return new bd(r)}function YQ(r){return new qp(r)}function ZQ(r){return new wd(r)}function JQ(r){return new Tl(r)}function QQ(r){return new yd(r)}function eee(r){return new Hp(r)}function tee(r){return new kd(r)}function ree(r){return new Kp(r)}function oee(r){return new ho(r)}function nee(r){return new Up(r)}function see(r){return new oh(r)}function iee(r){return new rh(r)}var aee=AL,lee=EL,uee=DL,cee=$L;function pee(r){return new zd(r)}function mee(r){return new Bd(r)}function fee(r){return new Vd(r)}function dee(r){return new Ad(r)}var c0={};Ke(c0,{MAPE:()=>Iee,MSE:()=>Tee,binaryAccuracy:()=>hee,binaryCrossentropy:()=>gee,categoricalAccuracy:()=>yee,categoricalCrossentropy:()=>bee,cosineProximity:()=>_ee,mape:()=>Nee,meanAbsoluteError:()=>vee,meanAbsolutePercentageError:()=>Cee,meanSquaredError:()=>See,mse:()=>Aee,precision:()=>wee,recall:()=>kee,sparseCategoricalAccuracy:()=>xee});function hee(r,e){return ed(r,e)}function gee(r,e){return Cx(r,e)}function xee(r,e){return Ix(r,e)}function yee(r,e){return td(r,e)}function bee(r,e){return rd(r,e)}function wee(r,e){return NC(r,e)}function kee(r,e){return QM(r,e)}function _ee(r,e){return Jf(r,e)}function vee(r,e){return zp(r,e)}function Cee(r,e){return vl(r,e)}function Iee(r,e){return vl(r,e)}function Nee(r,e){return vl(r,e)}function See(r,e){return Hi(r,e)}function Tee(r,e){return Hi(r,e)}function Aee(r,e){return Hi(r,e)}var p0={};Ke(p0,{modelFromJSON:()=>xL});var m0={};Ke(m0,{l1:()=>Dee,l1l2:()=>Eee,l2:()=>$ee});function Eee(r){return new pc(r)}function Dee(r){return vL(r)}function $ee(r){return CL(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 RL(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=RL:this.monitor.indexOf("acc")!==-1?this.monitorFunc=RL: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 Ree(r){return new Lx(r)}var FL={earlyStopping:Ree};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 OL;(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={}))})(OL||(OL={}));var f0={};function PL(r,e){let t={tfOpName:r,category:"custom",inputs:[],attrs:[],customExecutor:e};f0[r]=t}function zx(r){return f0[r]}function ML(r){delete f0[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 yr(e.inputNames[s.inputIndexStart],t,o,n);if(s.type==="tensors")return e.inputNames.slice(i,l).map(m=>yr(m,t,o,n));let u=yr(e.inputNames.slice(i)[0],t,o,n),c=u.dataSync();return s.type==="number"?c[0]:y.toNestedArray(u.shape,c)}let a=e.attrParams[r];return a&&a.value}function yr(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 LL(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 d0={};Ke(d0,{json:()=>Fee});var Fee=[{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 h0={};Ke(h0,{json:()=>Oee});var Oee=[{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 g0={};Ke(g0,{json:()=>Pee});var Pee=[{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 x0={};Ke(x0,{json:()=>Mee});var Mee=[{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 y0={};Ke(y0,{json:()=>Lee});var Lee=[{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 b0={};Ke(b0,{json:()=>zee});var zee=[{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 w0={};Ke(w0,{json:()=>Bee});var Bee=[{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 k0={};Ke(k0,{json:()=>Vee});var Vee=[{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 _0={};Ke(_0,{json:()=>Gee});var Gee=[{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 v0={};Ke(v0,{json:()=>Wee});var Wee=[{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 C0={};Ke(C0,{json:()=>jee});var jee=[{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 I0={};Ke(I0,{json:()=>Uee});var Uee=[{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 N0={};Ke(N0,{json:()=>Hee});var Hee=[{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 S0={};Ke(S0,{json:()=>qee});var qee=[{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 T0={};Ke(T0,{json:()=>Kee});var Kee=[{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 A0={};Ke(A0,{json:()=>Xee});var Xee=[{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 E0={};Ke(E0,{json:()=>Yee});var Yee=[{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=[d0,h0,g0,x0,y0,b0,w0,C0,v0,k0,I0,N0,S0,T0,A0,E0,_0],t=[].concat(...e.map(o=>o.json));this.opMappers=t.reduce((o,n)=>(o[n.tfOpName]=n,o),{})}transformGraph(e,t={}){let o=e.node,n=[],s=[],a=[],i=o.reduce((h,g)=>(h[g.name]=this.mapNode(g),g.op.startsWith("Placeholder")?n.push(h[g.name]):g.op==="Const"?s.push(h[g.name]):(g.input==null||g.input.length===0)&&a.push(h[g.name]),h),{}),l=[],u=[],c={},p={};t!=null&&(c=this.mapSignatureEntries(t.inputs),p=this.mapSignatureEntries(t.outputs));let m=Object.keys(i);m.forEach(h=>{let g=i[h];g.inputNames.forEach(x=>{let[b]=Gs(x);g.inputs.push(i[b]),i[b].children.push(g)})}),Object.keys(p).length===0?m.forEach(h=>{let g=i[h];g.children.length===0&&u.push(g)}):Object.keys(p).forEach(h=>{let[g]=Gs(h),x=i[g];x!=null&&(x.signatureKey=p[h],u.push(x))}),Object.keys(c).length>0?Object.keys(c).forEach(h=>{let[g]=Gs(h),x=i[g];x&&(x.signatureKey=c[h],l.push(x))}):l=n;let f={};e.library!=null&&e.library.function!=null&&(f=e.library.function.reduce((h,g)=>(h[g.signature.name]=this.mapFunction(g),h),{}));let d={nodes:i,inputs:l,outputs:u,weights:s,placeholders:n,signature:t,functions:f};return a.length>0&&(d.initNodes=a),d}mapSignatureEntries(e){return Object.keys(e||{}).reduce((t,o)=>(t[e[o].name]=o,t),{})}mapNode(e){let t=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=zL(e.attr,s.tfName,s.defaultValue),i===void 0&&!!s.tfDeprecatedName&&(i=zL(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:D0(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 Zee(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 BL(r,e){let t=Array.isArray(r)?String.fromCharCode.apply(null,r):Zee(r);return e?t:t.toLowerCase()}function Gx(r,e,t,o=!1){let n=r[e];return n!=null?BL(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 D0(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 zL(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?D0(o.type):t}function Hx(r,e,t){let o=r[e];return o&&o.list&&o.list.type?o.list.type.map(n=>D0(n)):t}function VL(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?VL(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=>BL(s,o)):t}function Yx(r,e,t){let o=r[e];return o&&o.list&&o.list.shape?o.list.shape.map(n=>VL(n)):t}function Zx(r,e,t){let o=r[e];return o&&o.list&&o.list.b?o.list.b:t}var $0=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 yr(e,this.tensorMap,this.context)}getAttr(e,t){let o=this.node.rawAttrs[e];if(o.tensor!=null)return yr(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 GL=(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[fw(C("tensors",r,e,t))];case"FloorMod":case"Mod":return[Gm(C("a",r,e,t),C("b",r,e,t))];case"Mul":return[P(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[Fm(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[Or(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 WL=(r,e,t)=>{switch(r.op){case"Abs":case"ComplexAbs":return[It(C("x",r,e,t))];case"Acos":return[km(C("x",r,e,t))];case"Acosh":return[_m(C("x",r,e,t))];case"Asin":return[Cm(C("x",r,e,t))];case"Asinh":return[Im(C("x",r,e,t))];case"Atan":return[Nm(C("x",r,e,t))];case"Atan2":return[Sm(C("x",r,e,t),C("y",r,e,t))];case"Atanh":return[Tm(C("x",r,e,t))];case"Ceil":return[Em(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[Om(C("x",r,e,t))];case"Exp":return[Zt(C("x",r,e,t))];case"Expm1":return[Pm(C("x",r,e,t))];case"Floor":return[Ss(C("x",r,e,t))];case"Log":return[lr(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[Sr(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[ir(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(yr(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")){y.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];y.assert(n<0||s<0||n===s,()=>t+` Shapes ${r} and ${e} must match`)}}}function jL(r){return!(typeof r=="number"||r.some(e=>e<0))}function Yp(r,e,t){let o=Jx(r,t),n=!jL(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)}),!jL(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 R0=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 Rr([],[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 Rr([],[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,pr(t,0))}split(e,t){if(t.dtype!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but tensor has dtype ${t.dtype}`);let o=0,n=e.map(l=>(o+=l,o));if(o!==t.shape[0])throw new Error(`Expected sum of lengths to be equal to
|
|
tensor.shape[0], but sum of lengths is
|
|
${o}, and tensor's shape is: ${t.shape}`);if(!this.dynamicSize&&e.length!==this.maxSize)throw new Error(`TensorArray's size is not equal to the size of lengths (${this.maxSize} vs. ${e.length}), and the TensorArray is not marked as dynamically resizeable`);let s=o===0?0:t.size/o,a=[];V(()=>{t=L(t,[1,o,s]);for(let l=0;l<e.length;++l){let u=l===0?0:n[l-1],c=[0,u,0],p=[1,e[l],s];a[l]=L(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=Yp(this.elementShape,this.tensors,e);return V(()=>{let s=this.tensors.map(a=>L(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=Yp(this.elementShape,this.tensors,e),n=this.tensors.pop();return Ao(n.shape,e,"TensorList shape mismatch: "),L(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=Yp(this.elementShape,this.tensors,t);return L(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=Yp(this.elementShape,this.tensors,o);return e.length===0?Rr([],[0].concat(n)):V(()=>{let s=e.map(a=>L(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=Yp(this.elementShape,this.tensors,t);return this.size()===0?Rr([],[0].concat(o)):V(()=>{let n=this.tensors.map(s=>L(s,o));return Ze(n,0)})}};function UL(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=pr(r);return new hc(s,e,o)}function HL(r,e,t){return new hc([],r,e,t)}function qL(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=pr(r,0);return e.forEach((i,l)=>{s.setItem(i,a[l])}),s}function KL(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=L(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]=L(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 XL=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=>yr(n,e,t)!==void 0);if(o){let n=yr(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 R0(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=qL(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=HL(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=UL(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=KL(o,s,n);return t.addTensorList(a),[a.idTensor]}default:throw TypeError(`Node type ${r.op} is not implemented`)}};function YL(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 ZL=(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}=YL(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}=YL(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[Dm(C("x",r,e,t),C("filter",r,e,t),[o[1],o[2],o[3]],n,s,[a[1],a[2],a[3]])]}case"AvgPool":{let o=C("strides",r,e,t),n=C("pad",r,e,t),s=C("kernelSize",r,e,t);return[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}=Pw(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[Am(C("x",r,e,t),[s[1],s[2],s[3]],[o[1],o[2],o[3]],n)]}case"MaxPool3D":{let o=C("strides",r,e,t),n=C("pad",r,e,t),s=C("kernelSize",r,e,t);return[Bm(C("x",r,e,t),[s[1],s[2],s[3]],[o[1],o[2],o[3]],n)]}case"Dilation2D":{let o=C("strides",r,e,t),n=C("pad",r,e,t),s=C("dilations",r,e,t),a=o[1],i=o[2],l=s[1],u=s[2];return[Rm(C("x",r,e,t),C("filter",r,e,t),[a,i],n,[l,u],"NHWC")]}default:throw TypeError(`Node type ${r.op} is not implemented`)}};var JL=(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[Ew(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[Mw(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[Nr(C("shape",r,e,t),C("dtype",r,e,t))];case"OnesLike":return[tr(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[Jc(o,n,s,C("dtype",r,e,t))]}case"TruncatedNormal":{let o=C("shape",r,e,t),n=C("mean",r,e,t),s=C("stdDev",r,e,t),a=C("seed",r,e,t);return[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 F0(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 QL=async(r,e,t)=>{switch(r.op){case"NonMaxSuppressionV5":{let{boxes:o,scores:n,maxOutputSize:s,iouThreshold:a,scoreThreshold:i,softNmsSigma:l}=F0(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}=F0(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}=F0(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 Xw(C("x",r,e,t),C("y",r,e,t));default:throw TypeError(`Node type ${r.op} is not implemented`)}};var ez=(r,e,t)=>{switch(r.op){case"TopKV2":{let o=C("x",r,e,t),n=C("k",r,e,t),s=C("sorted",r,e,t),a=Zm(o,n,s);return[a.values,a.indices]}case"Unique":{let o=C("x",r,e,t),n=ep(o);return[n.values,n.indices]}case"UniqueV2":{let o=C("x",r,e,t),n=C("axis",r,e,t),s=ep(o,n);return[s.values,s.indices]}default:throw TypeError(`Node type ${r.op} is not implemented`)}};var tz=(r,e,t)=>{switch(r.op){case"Const":return e[r.name];case"PlaceholderWithDefault":let o=C("default",r,e,t);return[yr(r.name,e,t)||o];case"Placeholder":return[yr(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 O0=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=pr(t),s=o.length,a=n.length;y.assert(s===a,()=>`The number of elements doesn't match, keys has ${s} elements, the values has ${a} elements.`);for(let i=0;i<s;i++){let l=o[i],u=n[i];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 rz=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 O0(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 oz=(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 nz=(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[er(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[hr(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 sz=(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 iz=(r,e,t)=>{switch(r.op){case"FusedBatchNorm":case"FusedBatchNormV2":return[Ln(C("x",r,e,t),C("mean",r,e,t),C("variance",r,e,t),C("offset",r,e,t),C("scale",r,e,t),C("epsilon",r,e,t))];case"FusedBatchNormV3":return[Ln(C("x",r,e,t),C("mean",r,e,t),C("variance",r,e,t),C("offset",r,e,t),C("scale",r,e,t),C("epsilon",r,e,t))];case"LRN":return[Mm(C("x",r,e,t),C("radius",r,e,t),C("bias",r,e,t),C("alpha",r,e,t),C("beta",r,e,t))];case"Softmax":return[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 az=(r,e,t)=>{switch(r.op){case"Max":{let a=C("axis",r,e,t),i=C("keepDims",r,e,t);return[ur(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[vm(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[ww(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[Iw(a,i,l,u)]}default:throw TypeError(`Node type ${r.op} is not implemented`)}};var lz=(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[qt(s,n)]}case"ReverseV2":{let o=C("axis",r,e,t),n=C("x",r,e,t);return[qt(n,o)]}case"Slice":{let o=C("begin",r,e,t),n=C("size",r,e,t);return[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=y.arraysEqual(l.shape,s);if(!u&&!y.arraysEqual(Co(l).shape,a))throw new Error("the input tensors shape does not match");return u?l:L(l,s)});return[Bt(i,o)]});case"Unpack":{let o=C("axis",r,e,t),n=C("tensor",r,e,t);return pr(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 cr(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[Jw(o,n,s)]}case"GatherNd":{let o=C("x",r,e,t),n=C("indices",r,e,t);return[Qw(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 uz=(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 cz=(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[ar(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[L(C("x",r,e,t),C("shape",r,e,t))];case"MirrorPad":return[Vm(C("x",r,e,t),C("padding",r,e,t),C("mode",r,e,t))];case"PadV2":case"Pad":return[Fr(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[$m(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 P0(r,e,t,o){let n=((s,a,i)=>{switch(s.category){case"arithmetic":return V(()=>GL(s,a,i));case"basic_math":return V(()=>WL(s,a,i));case"control":return XL(s,a,i);case"convolution":return V(()=>ZL(s,a,i));case"creation":return V(()=>JL(s,a,i));case"dynamic":return QL(s,a,i);case"evaluation":return V(()=>ez(s,a,i));case"image":return V(()=>oz(s,a,i));case"graph":return V(()=>tz(s,a,i));case"logical":return V(()=>nz(s,a,i));case"matrices":return V(()=>sz(s,a,i));case"normalization":return V(()=>iz(s,a,i));case"reduction":return V(()=>az(s,a,i));case"slice_join":return V(()=>lz(s,a,i));case"spectral":return V(()=>uz(s,a,i));case"transformation":return V(()=>cz(s,a,i));case"hash_table":return rz(s,a,i,o);case"custom":let l=zx(s.op);if(l&&l.customExecutor)return l.customExecutor(new $0(s,a,i));throw TypeError(`Custom op ${s.op} is not registered.`);default:throw TypeError(`Unknown op '${s.op}'. File an issue at https://github.com/tensorflow/tfjs/issues so we can add it, or register a custom execution with tf.registerOp()`)}})(r,e,t);return y.isPromise(n)?n.then(s=>[].concat(s)):[].concat(n)}var 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 L0(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((M0(m)||Jee(m)||Qee(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 pz(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 ete=["Switch","Merge","Enter","Exit","NextIteration","StatelessIf","StatelessWhile","if","While"],tte=["NonMaxSuppressionV2","NonMaxSuppressionV3","NonMaxSuppressionV5","Where"],rte=["HashTable","HashTableV2","LookupTableImport","LookupTableImportV2","LookupTableFind","LookupTableFindV2","LookupTableSize","LookupTableSizeV2"];function M0(r){return ete.indexOf(r.op)>=0}function Jee(r){return tte.indexOf(r.op)>=0}function Qee(r){return rte.indexOf(r.op)>=0}var Zp=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 Zp(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=L0(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 pz(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,x]=eo(h),b=[];b[x]=e[h],m[g]=b});let f=this.getFrozenTensorIds(m),d={};for(let h=0;h<l.length;h++){let g=l[h];if(!m[g.name]){let x=P0(g,m,p,this._resourceManager);if(y.isPromise(x))throw new Error(`The execution of the op '${g.op}' returned a promise. Please use model.executeAsync() instead.`);m[g.name]=x,this.checkTensorForDisposal(g.name,g,m,p,f,s,d)}}return this.parent==null&&p.dispose(f),t.map(h=>yr(h,m,p))})}getFrozenTensorIds(e){let t=[].concat.apply([],Object.keys(e).map(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=LL(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=>yr(m,i,a)),u=l.map(m=>m.id),c=Object.keys(e).map(m=>e[m].id),p=new Set([...u,...c,...this.weightIds]);return Object.keys(i).forEach(m=>{i[m].forEach(d=>{d&&!d.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}=L0(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,_]=eo(w),D=[];D[_]=e[w],d[k]=D});let h={},g=this.getFrozenTensorIds(d),x={};for(;f.length>0;){let w=this.processStack(a,f,t,d,x,g,i,h,u);await Promise.all(w)}p==null&&!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=>!M0(w)&&!yr(w.name,d,t)).map(w=>w.name);if(b.length>0){let w="";throw p!=null&&(w=`Alternatively, to avoid the dynamic ops, use model.execute() and specify the inputs [${m}]`),new Error(`Cannot compute the outputs [${b}] from the provided inputs [${s}]. Consider providing the following inputs: [${c}]. ${w}`)}return d}processStack(e,t,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=P0(p.node,n,o,this._resourceManager);m||([m]=Gs(p.node.name,o));let d=o.currentContext;y.isPromise(f)?c.push(f.then(h=>(n[m]=h,o.currentContext=d,this.checkTensorForDisposal(m,p.node,n,o,a,i,l),this.processChildNodes(p.node,t,o,n,s,u),h))):(n[m]=f,this.checkTensorForDisposal(m,p.node,n,o,a,i,l),this.processChildNodes(p.node,t,o,n,s,u))}else this.processChildNodes(p.node,t,o,n,s,u)}return c}processChildNodes(e,t,o,n,s,a){e.children.forEach(i=>{let[l]=Gs(i.name,o);s[l]||!a.has(i.name)||(i.op==="Merge"?i.inputNames.some(u=>!!yr(u,n,o))&&(s[l]=!0,t.push({contexts:o.currentContext,node:i})):i.inputNames.every(u=>!!yr(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);y.assert(i,()=>`The shape of dict['${s.name}'] provided in model.execute(dict) must be [${a}], but was [${o.shape}]`)}s.attrParams.dtype&&s.attrParams.dtype.value&&y.assert(o.dtype===s.attrParams.dtype.value,()=>`The dtype of dict['${s.name}'] provided in model.execute(dict) must be ${s.attrParams.dtype.value}, but was ${o.dtype}`)})}mapInputs(e){let t={};for(let o in e)if(this._signature!=null&&this._signature.inputs!=null&&this._signature.inputs[o]!=null){let n=this._signature.inputs[o];t[n.name]=e[o]}else t[o]=e[o];return t}checkInputs(e){let t=Object.keys(e).filter(o=>{let[n]=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 z0=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 ote="?tfjs-format=file",nte="model.json",ey=class{constructor(e,t={}){this.modelUrl=e,this.loadOptions=t,this.version="n/a",t==null&&(this.loadOptions={}),this.resourceManager=new z0}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=Ir.browserHTTPRequest(e,this.loadOptions);else{let t=Ir.getLoadHandlers(e,this.loadOptions);if(t.length===0)t.push(Ir.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=Ir.decodeWeights(this.artifacts.weightData,this.artifacts.weightSpecs);if(this.executor=new Zp(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 Zp(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=Ir.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 mz(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}${nte}${ote}`);let t=new ey(r,e);return await t.load(),t}var fz="3.3.0";var ly={};Ke(ly,{CSVDataset:()=>uh,Dataset:()=>Ki,FileDataSource:()=>dh,TextLineDataset:()=>ah,URLDataSource:()=>hh,array:()=>Yz,csv:()=>i3,func:()=>a3,generator:()=>l3,microphone:()=>c3,version_data:()=>p3,webcam:()=>u3,zip:()=>Zz});var Xz=Ac(H0());var Fz=Ac(H0());function Az(r,e){return ry(r,e)}function ry(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=ry(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 Dz(r,e=q0){return Ez(r,e)}function Ez(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=Ez(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 q0(r){return r===null?null:El(r[0])?{value:null,recurse:!0}:{value:r,recurse:!1}}async function oy(r,e){let t=new Map;ry(r,e,t);for(let n of Array.from(t.keys())){let s=t.get(n);if(y.isPromise(s)){let a=await s;t.set(n,a)}}return ry(r,e,t)}function El(r){return r!=null&&!ArrayBuffer.isView(r)&&(Array.isArray(r)||typeof r=="object"&&!(r instanceof Ve))}function $z(r){return r==null||pte(r)||Array.isArray(r)||typeof r=="object"&&r instanceof Ve||y.isTypedArray(r)}function pte(r){return r===null||typeof r!="object"&&typeof r!="function"}function Rz(r){return Az(r,mte)}function mte(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 Jp=class extends sh{constructor(){super(Jp.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}};Jp.INITIAL_CAPACITY=32;function K0(r){return new Oz(r)}function ih(r){return new Pz(r)}function Mz(r,e){return new X0(r,e)}function zz(r,e=ja.FAIL){return new Lz(r,e)}var Kt=class{async toArray(){let e=[],t=await this.next();for(;!t.done;)e.push(t.value),t=await this.next();return e}async toArrayForTest(){let e=this.prefetch(100),t=[],o=await e.next();for(;!o.done;)t.push(o.value),o=await e.next();return t}async resolveFully(){let e=await this.next();for(;!e.done;)e=await this.next()}async resolveWhile(e){let t=await this.next(),o=e(t.value);for(;!t.done&&o;)t=await this.next(),o=e(t.value)}handleErrors(e){return new Hz(this,e)}filter(e){return new jz(this,e)}map(e){return new Uz(this,e)}mapAsync(e){return new Y0(this,e)}serialMapAsync(e){return new Y0(this,e).serial()}flatmap(e){return new qz(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 Wz(this,e,t)}columnMajorBatch(e,t=!0,o=q0){return this.rowMajorBatch(e,t).map(s=>Dz(s,o))}concatenate(e,t){return new X0(K0([this,e]),t)}take(e){return e<0||e==null?this:new Gz(this,e)}skip(e){return e<0||e==null?this:new Vz(this,e)}prefetch(e){return new Z0(this,e)}shuffle(e,t){return new Kz(this,e,t)}serial(){return new Bz(this)}},Oz=class extends Kt{constructor(e){super();this.items=e,this.trav=0}summary(){return`Array of ${this.items.length} items`}async next(){if(this.trav>=this.items.length)return{value:null,done:!0};let e=this.items[this.trav];return this.trav++,{value:Rz(e),done:!1}}},Pz=class extends Kt{constructor(e){super();this.nextFn=e}summary(){return"Function call"}async next(){try{return this.nextFn()}catch(e){throw e.message=`Error thrown while iterating through a dataset: ${e.message}`,e}}},Bz=class extends Kt{constructor(e){super();this.upstream=e,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> Serial`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){return this.upstream.next()}},Vz=class extends Kt{constructor(e,t){super();this.upstream=e,this.maxCount=t,this.count=0,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> Skip`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){for(;this.count++<this.maxCount;){let e=await this.upstream.next();if(e.done)return e;Ae(e.value)}return this.upstream.next()}},Gz=class extends Kt{constructor(e,t){super();this.upstream=e,this.maxCount=t,this.count=0}summary(){return`${this.upstream.summary()} -> Take`}async next(){return this.count++>=this.maxCount?{value:null,done:!0}:this.upstream.next()}},Wz=class extends Kt{constructor(e,t,o=!0){super();this.upstream=e,this.batchSize=t,this.enableSmallLastBatch=o,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> RowMajorBatch`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){let e=[];for(;e.length<this.batchSize;){let t=await this.upstream.next();if(t.done)return this.enableSmallLastBatch&&e.length>0?{value:e,done:!1}:{value:null,done:!0};e.push(t.value)}return{value:e,done:!1}}},jz=class extends Kt{constructor(e,t){super();this.upstream=e,this.predicate=t,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> Filter`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){for(;;){let e=await this.upstream.next();if(e.done||this.predicate(e.value))return e;Ae(e.value)}}},Uz=class extends Kt{constructor(e,t){super();this.upstream=e,this.transform=t}summary(){return`${this.upstream.summary()} -> Map`}async next(){let e=await this.upstream.next();if(e.done)return{value:null,done:!0};let t=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}}},Hz=class extends Kt{constructor(e,t){super();this.upstream=e,this.handler=t,this.count=0,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> handleErrors`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){for(;;)try{return await this.upstream.next()}catch(e){if(!this.handler(e))return{value:null,done:!0}}}},Y0=class extends Kt{constructor(e,t){super();this.upstream=e,this.transform=t}summary(){return`${this.upstream.summary()} -> AsyncMap`}async next(){let e=await this.upstream.next();if(e.done)return{value:null,done:!0};let t=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}}},Qp=class extends Kt{constructor(){super();this.outputQueue=new Jp,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}}},qz=class extends Qp{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}},X0=class extends Kt{constructor(e,t){super();this.baseErrorHandler=t,this.lastRead=null,this.iterator=null,this.moreIterators=e}summary(){return"TODO: fill in upstream of chained summaries -> Chained"}async next(){return this.lastRead=this.readFromChain(this.lastRead),this.lastRead}async readFromChain(e){if(await e,this.iterator==null){let o=await this.moreIterators.next();if(o.done)return{value:null,done:!0};this.iterator=o.value,this.baseErrorHandler!=null&&(this.iterator=this.iterator.handleErrors(this.baseErrorHandler))}let t=await this.iterator.next();return t.done?(this.iterator=null,this.readFromChain(e)):t}},ja;(function(r){r[r.FAIL=0]="FAIL",r[r.SHORTEST=1]="SHORTEST",r[r.LONGEST=2]="LONGEST"})(ja||(ja={}));var Lz=class extends Kt{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 Kt?{value:a.next().then(l=>(t++,l.done&&o++,l.value)),recurse:!1}:{value:null,recurse:!0}}let s=await oy(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}},Z0=class extends Kt{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()}},Kz=class extends Z0{constructor(e,t,o){super(e,t);this.upstream=e,this.windowSize=t,this.upstreamExhausted=!1,this.random=Fz.alea(o||y.now().toString()),this.lastRead=Promise.resolve({value:null,done:!1})}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}randomInt(e){return Math.floor(this.random()*e)}chooseIndex(){return this.randomInt(this.buffer.length())}async serialNext(){for(this.upstreamExhausted||this.refill();!this.buffer.isEmpty();){let e=this.chooseIndex(),t=await this.buffer.shuffleExcise(e);if(t.done)this.upstreamExhausted=!0;else return this.refill(),t}return{value:null,done:!0}}};var Ki=class{constructor(){this.size=null}batch(e,t=!0){let o=this;y.assert(e>0,()=>`batchSize needs to be positive, but it is
|
|
${e}`);let n;return this.size===Infinity||this.size==null?n=this.size:t?n=Math.ceil(this.size/e):n=Math.floor(this.size/e),go(async()=>(await o.iterator()).columnMajorBatch(e,t,fte),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 Mz(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=Xz.alea(t||y.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 Yz(r){return go(async()=>K0(r),r.length)}function Zz(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 oy(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 zz(t,ja.SHORTEST)},e)}function fte(r){if(r===null)return null;let e=r[0];return $z(e)?{value:dte(r),recurse:!1}:{value:null,recurse:!0}}function dte(r){if(r.length===0)throw new Error("Can't make a batch of zero elements.");return r[0]instanceof Ve?Bt(r):Rr(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 ny='"',lh=Symbol("out"),Jz=Symbol("field"),sy=Symbol("quote"),J0=Symbol("quoteafterquote"),Qz=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?(y.assert(t.delimiter==null,()=>"Delimiter should not be provided when delimWhitespace is true."),this.delimWhitespace=!0,this.delimiter=" "):this.delimiter=t.delimiter?t.delimiter:","}async columnNames(){return this.columnNamesValidated||await this.setColumnNames(),this.configuredColumnsOnly?Object.keys(this.columnConfigs):this.fullColumnNames}async setColumnNames(){let e=await this.maybeReadHeaderLine();if(!this.fullColumnNames&&!e)throw new Error("Column names must be provided if there is no header line.");this.fullColumnNames&&e&&y.assert(e.length===this.fullColumnNames.length,()=>"The length of provided columnNames ("+this.fullColumnNames.length.toString()+") does not match the length of the header line read from file ("+e.length.toString()+")."),this.fullColumnNames||(this.fullColumnNames=e);let t=this.fullColumnNames.reduce((n,s)=>(n[s]=n[s]+1||1,n),{}),o=Object.keys(t).filter(n=>t[n]>1);if(y.assert(o.length===0,()=>"Duplicate column names found: "+o.toString()),this.columnConfigs){for(let n of Object.keys(this.columnConfigs))if(this.fullColumnNames.indexOf(n)===-1)throw new Error('The key "'+n+'" provided in columnConfigs does not match any of the column names ('+this.fullColumnNames.toString()+").")}this.columnNamesValidated=!0}async maybeReadHeaderLine(){if(this.hasHeader){let t=await(await this.base.iterator()).next();if(t.done)throw new Error("No data was found for CSV parsing.");let o=t.value;return this.parseRow(o,!1)}else return null}async iterator(){this.columnNamesValidated||await this.setColumnNames();let e=await this.base.iterator();return this.hasHeader&&(e=e.skip(1)),e.map(t=>this.makeDataElement(t))}makeDataElement(e){let t=this.parseRow(e),o={},n={};for(let s=0;s<this.fullColumnNames.length;s++){let a=this.fullColumnNames[s],i=this.columnConfigs?this.columnConfigs[a]:null;if(!(this.configuredColumnsOnly&&!i)){let l=t[s],u=null;if(l==="")if(i&&i.default!==void 0)u=i.default;else{if(i&&(i.required||i.isLabel))throw new Error(`Required column ${a} is empty in this line: ${e}`);u=void 0}else{let c=Number(l);if(isNaN(c))i&&i.dtype==="bool"?u=this.getBoolean(l):u=l;else if(!i||!i.dtype)u=c;else switch(i.dtype){case"float32":u=c;break;case"int32":u=Math.floor(c);break;case"bool":u=this.getBoolean(l);break;default:u=c}}i&&i.isLabel?n[a]=u:o[a]=u}}return Object.keys(n).length===0?o:{xs:o,ys:n}}getBoolean(e){return e==="1"||e.toLowerCase()==="true"?1:0}parseRow(e,t=!0){let o=[],n=0,s=e.length,a=lh;for(let i=0;i<s;i++)switch(a){case lh:switch(e.charAt(i)){case ny:n=i+1,a=sy;break;case this.delimiter:if(n=i+1,this.delimiter===" "&&this.delimWhitespace)break;o.push(""),a=lh;break;default:a=Jz,n=i;break}break;case Jz:switch(e.charAt(i)){case this.delimiter:o.push(e.substring(n,i)),a=lh,n=i+1;break;default:}break;case sy:switch(e.charAt(i)){case ny:a=J0;break;default:}break;case J0:switch(e.charAt(i)){case this.delimiter:o.push(e.substring(n,i-1)),a=lh,n=i+1;break;case ny:a=sy;break;default:a=Qz;break}break;case Qz:switch(e.charAt(i)){case ny:a=sy;break;default:}break;default:}if(a===J0?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 Kt{constructor(e){super();this.microphoneConfig=e,this.isClosed=!1,this.fftSize=e.fftSize||1024;let t=Math.log2(this.fftSize);if(this.fftSize<0||t<4||t>14||!Number.isInteger(t))throw new Error(`Invalid fftSize: it must be a power of 2 between 2 to 4 and 2 to 14, but got ${this.fftSize}`);if(this.numFrames=e.numFramesPerSpectrogram||43,this.sampleRateHz=e.sampleRateHz,this.columnTruncateLength=e.columnTruncateLength||this.fftSize,this.audioTrackConstraints=e.audioTrackConstraints,this.smoothingTimeConstant=e.smoothingTimeConstant||0,this.includeSpectrogram=e.includeSpectrogram!==!1,this.includeWaveform=e.includeWaveform===!0,!this.includeSpectrogram&&!this.includeWaveform)throw new Error("Both includeSpectrogram and includeWaveform are false. At least one type of data should be returned.")}summary(){return"microphone"}static async create(e={}){if(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(y.sizeFromShape(t));return o.set(e,o.length-e.length),Rr(o,t)}};var ph=class extends Kt{constructor(e,t){super();if(this.webcamVideoElement=e,this.webcamConfig=t,this.isClosed=!0,this.resize=!1,this.needToResize())if(this.resize=!0,this.cropSize=[this.webcamConfig.resizeHeight,this.webcamConfig.resizeWidth],this.cropBoxInd=Vt([0],"int32"),this.webcamConfig.centerCrop){let o=this.webcamConfig.resizeWidth*1/this.webcamVideoElement.width,n=this.webcamConfig.resizeHeight*1/this.webcamVideoElement.height,s=(1-o)/2,a=(1-n)/2,i=s+o,l=n+a;this.cropBox=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&&y.assert(this.webcamConfig.facingMode==="user"||this.webcamConfig.facingMode==="environment",()=>`Invalid webcam facing mode: ${this.webcamConfig.facingMode}. Please provide 'user' or 'environment'`);try{this.stream=await navigator.mediaDevices.getUserMedia({video:{deviceId:this.webcamConfig.deviceId,facingMode:this.webcamConfig.facingMode?this.webcamConfig.facingMode:"user",width:this.webcamVideoElement.width,height:this.webcamVideoElement.height}})}catch(e){throw e.message=`Error thrown while initializing video stream: ${e.message}`,e}if(!this.stream)throw new Error("Could not obtain video from webcam.");try{this.webcamVideoElement.srcObject=this.stream}catch(e){console.log(e),this.webcamVideoElement.src=window.URL.createObjectURL(this.stream)}return this.webcamVideoElement.play(),this.isClosed=!1,new Promise(e=>{this.webcamVideoElement.onloadedmetadata=()=>{e()}})}async next(){if(this.isClosed)return{value:null,done:!0};let e;try{e=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=ar(ne(e,"float32"),0),o;o=$s.cropAndResize(t,this.cropBox,this.cropBoxInd,this.cropSize,"bilinear");let n=o.shape;return L(o,n.slice(1))})}async capture(){return(await this.next()).value}stop(){this.stream.getTracks().forEach(t=>t.stop());try{this.webcamVideoElement.srcObject=null}catch(t){console.log(t),this.webcamVideoElement.src=null}this.isClosed=!0}toArray(){throw new Error("Can not convert infinite video stream to array.")}};var mh=class{};var iy=class extends Kt{split(e){return new e3(this,e)}},e3=class extends iy{constructor(e,t){super();this.upstream=e,this.impl=new t3(e,t)}summary(){return this.impl.summary()}async next(){return this.impl.next()}},t3=class extends Qp{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 Q0=class extends Kt{decodeUTF8(){return new o3(this)}},o3=class extends iy{constructor(e){super();this.upstream=e,this.impl=new n3(e)}summary(){return this.impl.summary()}async next(){return this.impl.next()}},n3=class extends Qp{constructor(e){super();if(this.upstream=e,W().get("IS_BROWSER"))this.decoder=new TextDecoder("utf-8");else{let{StringDecoder:t}=r3();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 Q0{constructor(e,t={}){super();this.file=e,this.options=t,y.assert(e instanceof Uint8Array||(W().get("IS_BROWSER")?e instanceof File||e instanceof Blob:!1),()=>"FileChunkIterator only supports File, Blob and Uint8Array right now."),this.offset=t.offset||0,this.chunkSize=t.chunkSize||1024*1024}summary(){return`FileChunks ${this.file}`}async next(){return this.offset>=(this.file instanceof Uint8Array?this.file.byteLength:this.file.size)?{value:null,done:!0}:{value:await new Promise((t,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 s3(r,e={}){let t,o;typeof r=="string"?t=r:(t=r.url,o=hte(r));let n=await y.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 hte=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 ay(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(ay(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 ay(this.url)?new dh(this.url,this.fileOptions).iterator():s3(this.url,this.fileOptions)}};function i3(r,e={}){return new uh(new hh(r),e)}function a3(r){let e=ih(r);return go(async()=>e)}function l3(r){return go(async()=>{let e=await r();return ih(()=>e.next())})}async function u3(r,e){return ph.create(r,e)}async function c3(r){return ch.create(r)}var p3="3.3.0";var gte={tfjs:mI,"tfjs-core":fI,"tfjs-data":dI,"tfjs-layers":hI,"tfjs-converter":gI,"tfjs-backend-cpu":yk,"tfjs-backend-webgl":T_,"tfjs-backend-wasm":cC};export{as as Abs,qs as Acos,Ks as Acosh,rp as AdadeltaOptimizer,op as AdagradOptimizer,np as AdamOptimizer,sp 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,$b 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,Oc as Dilation2DBackpropFilter,Fc as Dilation2DBackpropInput,Ab 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,Pc 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,Rb 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,ip as MomentumOptimizer,su as Multinomial,xn as Multiply,ps as Neg,bi as NonMaxSuppressionV3,wi as NonMaxSuppressionV4,ki as NonMaxSuppressionV5,yi as NotEqual,OI as OP_SCOPE_SUFFIX,yn as OneHot,ms as OnesLike,Pr as Optimizer,fs as Pack,bn as PadV2,$B as Pool,wn as Pow,kn as Prelu,_i as Prod,ap as RMSPropOptimizer,ho as RNN,ca as Range,Lb 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,Vr 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,km as acos,_m as acosh,ee as add,fw as addN,bu as all,sl as any,il as argMax,vm as argMin,Cm as asin,Im as asinh,Nm as atan,Sm as atan2,Tm as atanh,wa as avgPool,Am as avgPool3d,mw as backend,N as backend_util,OG as basicLSTMCell,Ln as batchNorm,xw as batchNorm2d,yw as batchNorm3d,bw as batchNorm4d,ka as batchToSpaceND,ww as bincount,W4 as booleanMaskAsync,al as broadcastTo,Xh as browser,ve as buffer,FL as callbacks,ne as cast,Em as ceil,ir as clipByValue,Po as clone,_o as complex,Ze as concat,kw as concat1d,_w as concat2d,vw as concat3d,Cw as concat4d,bC as constraints,_u as conv1d,Kr as conv2d,vu as conv2dTranspose,Dm as conv3d,rW as conv3dTranspose,OB as copyRegisteredKernels,_a as cos,Cu as cosh,tf as cosineWindow,Iu as cumsum,Xr as customGrad,ly as data,Iw as denseBincount,tg as deprecationWarn,$m as depthToSpace,Is as depthwiseConv2d,ML as deregisterOp,hu as device_util,cW as diag,Rm as dilation2d,KV as disableDeprecationWarnings,Ae as dispose,XV as disposeVariables,me as div,Fm as divNoNan,Nw as dot,ek as dropout,Ns as elu,qV as enableDebugMode,HV as enableProdMode,tk as enclosingPowerOfTwo,Mo as engine,W as env,vo as equal,Om as erf,Zt as exp,ar as expandDims,Pm as expm1,Xc as eye,Ea as fft,va as fill,tG as findBackend,rG as findBackendFactory,Ss as floor,yu as floorDiv,A_ as forceHalfFloat,Gn as fused,zn as gather,Qw as gatherND,Yh as gather_util,QV as getBackend,Bh as getGradient,Lc as getKernel,hm as getKernelsForBackend,jA as gpgpu_util,zW as grad,BW as grads,er as greater,io as greaterEqual,Mi as ifft,Nu as imag,$s as image,J4 as inTopKAsync,CC as initializers,Fx as input,Ir as io,Lu as irfft,Sw as isFinite,Tw as isInf,Aw as isNaN,Et as keep,Ar as kernel_impls,i0 as layers,Ca as leakyRelu,Su as less,Bo as lessEqual,ik as linalg,Ew as linspace,mz as loadGraphModel,kL as loadLayersModel,Mm as localResponseNormalization,lr as log,Tu as log1p,Dw as logSigmoid,Au as logSoftmax,zm as logSumExp,hr as logicalAnd,Ia as logicalNot,Eu as logicalOr,Ow as logicalXor,UU as losses,We as matMul,mN as math,ur as max,Na as maxPool,Bm as maxPool3d,Pw as maxPoolWithArgmax,Yr as maximum,dt as mean,Hc as memory,c0 as metrics,Pi as min,As as minimum,Vm as mirrorPad,Gm as mod,bL as model,p0 as models,Yc as moments,H4 as movingAverage,P as mul,hj as multiRNNCell,Mw as multinomial,He as neg,rf as nextFrame,Vu as norm,Vn as notEqual,Cs as oneHot,Nr as ones,tr as onesLike,S as op,wj as outerProduct,Fr as pad,vj as pad1d,Ij as pad2d,Sj as pad3d,Aj as pad4d,Lw as pool,Or as pow,Ta as prelu,rw as print,Du as prod,YV as profile,Lj as rand,Hj as randomGamma,lg as randomNormal,Es as randomUniform,Jc as range,JV as ready,ll as real,Wm as reciprocal,xu as registerBackend,_L as registerCallbackConstructor,Ob as registerGradient,el as registerKernel,PL as registerOp,m0 as regularizers,Sr as relu,Ru as relu6,eG as removeBackend,L as reshape,qt as reverse,t4 as reverse1d,o4 as reverse2d,s4 as reverse3d,a4 as reverse4d,Da as rfft,jm as round,Fu as rsqrt,le as scalar,Jw as scatterND,Zh as scatter_util,Ou as selu,Um as separableConv2d,wL as sequential,Q as serialization,AN as setBackend,oG as setPlatform,_9 as setWasmPath,v9 as setWasmPaths,Rk as setWebGLContext,Xw as setdiff1dAsync,yg as shared,qr as sigmoid,Hm as sign,jU as signal,Pu as sin,Mu as sinh,Re as slice,qm as slice1d,ug as slice2d,Km as slice3d,Qc as slice4d,sr as slice_util,Aa as softmax,Ts as softplus,Sa as spaceToBatchND,ef as sparseToDense,WU as spectral,cr 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,Rr as tensor,Vt as tensor1d,Li as tensor2d,iw as tensor3d,R4 as tensor4d,F4 as tensor5d,O4 as tensor6d,Mn as tensor_util,NN as test_util,V as tidy,zo as tile,ZV as time,Zm as topk,cl as train,Ue as transpose,Bu as truncatedNormal,ep as unique,FB as unregisterGradient,RB as unregisterKernel,Jm as unsortedSegmentSum,pr as unstack,dr as upcastType,y as util,VW as valueAndGrad,GW as valueAndGrads,Yw as variable,sg as variableGrads,gte as version,fz as version_converter,UV as version_core,yk as version_cpu,Gp as version_layers,cC as version_wasm,T_ as version_webgl,S5 as webgl,zA 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
|