lapd-face-search/assets/index-CjUl3rHt.js
Kyle McDonald 21aea707e6 Updates
2025-06-20 16:03:27 -07:00

5005 lines
1.3 MiB

(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))n(a);new MutationObserver(a=>{for(const s of a)if(s.type==="childList")for(const i of s.addedNodes)i.tagName==="LINK"&&i.rel==="modulepreload"&&n(i)}).observe(document,{childList:!0,subtree:!0});function r(a){const s={};return a.integrity&&(s.integrity=a.integrity),a.referrerPolicy&&(s.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?s.credentials="include":a.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function n(a){if(a.ep)return;a.ep=!0;const s=r(a);fetch(a.href,s)}})();const Zw=!1;var uy=Array.isArray,HA=Array.prototype.indexOf,py=Array.from,jA=Object.defineProperty,zp=Object.getOwnPropertyDescriptor,qA=Object.getOwnPropertyDescriptors,KA=Object.prototype,XA=Array.prototype,K1=Object.getPrototypeOf,Jw=Object.isExtensible;function ZA(e){for(var t=0;t<e.length;t++)e[t]()}const Pn=2,X1=4,Hc=8,dy=16,Ra=32,Gl=64,hy=128,pn=256,ac=512,Sn=1024,$a=2048,Ci=4096,_a=8192,cy=16384,Z1=32768,fy=65536,JA=1<<19,J1=1<<20,Jm=1<<21,qh=Symbol("$state"),YA=Symbol("");function Y1(e){return e===this.v}function QA(e,t){return e!=e?t==t:e!==t||e!==null&&typeof e=="object"||typeof e=="function"}function Q1(e){return!QA(e,this.v)}function eF(e){throw new Error("https://svelte.dev/e/effect_in_teardown")}function tF(){throw new Error("https://svelte.dev/e/effect_in_unowned_derived")}function rF(e){throw new Error("https://svelte.dev/e/effect_orphan")}function nF(){throw new Error("https://svelte.dev/e/effect_update_depth_exceeded")}function aF(){throw new Error("https://svelte.dev/e/state_descriptors_fixed")}function sF(){throw new Error("https://svelte.dev/e/state_prototype_fixed")}function iF(){throw new Error("https://svelte.dev/e/state_unsafe_mutation")}let oF=!1;const lF=1,uF=2,pF=16,dF=1,hF=2,Br=Symbol(),cF="http://www.w3.org/1999/xhtml";function fF(e){throw new Error("https://svelte.dev/e/lifecycle_outside_component")}let dn=null;function Yw(e){dn=e}function my(e,t=!1,r){var n=dn={p:dn,c:null,d:!1,e:null,m:!1,s:e,x:null,l:null};pk(()=>{n.d=!0})}function gy(e){const t=dn;if(t!==null){const i=t.e;if(i!==null){var r=mt,n=et;t.e=null;try{for(var a=0;a<i.length;a++){var s=i[a];ps(s.effect),la(s.reaction),by(s.fn)}}finally{ps(r),la(n)}}dn=t.p,t.m=!0}return{}}function ek(){return!0}function yl(e){if(typeof e!="object"||e===null||qh in e)return e;const t=K1(e);if(t!==KA&&t!==XA)return e;var r=new Map,n=uy(e),a=an(0),s=et,i=o=>{var l=et;la(s);var p=o();return la(l),p};return n&&r.set("length",an(e.length)),new Proxy(e,{defineProperty(o,l,p){(!("value"in p)||p.configurable===!1||p.enumerable===!1||p.writable===!1)&&aF();var u=r.get(l);return u===void 0?u=i(()=>{var d=an(p.value);return r.set(l,d),d}):At(u,p.value,!0),!0},deleteProperty(o,l){var p=r.get(l);if(p===void 0){if(l in o){const h=i(()=>an(Br));r.set(l,h),$m(a)}}else{if(n&&typeof l=="string"){var u=r.get("length"),d=Number(l);Number.isInteger(d)&&d<u.v&&At(u,d)}At(p,Br),$m(a)}return!0},get(o,l,p){var c;if(l===qh)return e;var u=r.get(l),d=l in o;if(u===void 0&&(!d||(c=zp(o,l))!=null&&c.writable)&&(u=i(()=>{var f=yl(d?o[l]:Br),m=an(f);return m}),r.set(l,u)),u!==void 0){var h=Ye(u);return h===Br?void 0:h}return Reflect.get(o,l,p)},getOwnPropertyDescriptor(o,l){var p=Reflect.getOwnPropertyDescriptor(o,l);if(p&&"value"in p){var u=r.get(l);u&&(p.value=Ye(u))}else if(p===void 0){var d=r.get(l),h=d==null?void 0:d.v;if(d!==void 0&&h!==Br)return{enumerable:!0,configurable:!0,value:h,writable:!0}}return p},has(o,l){var h;if(l===qh)return!0;var p=r.get(l),u=p!==void 0&&p.v!==Br||Reflect.has(o,l);if(p!==void 0||mt!==null&&(!u||(h=zp(o,l))!=null&&h.writable)){p===void 0&&(p=i(()=>{var c=u?yl(o[l]):Br,f=an(c);return f}),r.set(l,p));var d=Ye(p);if(d===Br)return!1}return u},set(o,l,p,u){var x;var d=r.get(l),h=l in o;if(n&&l==="length")for(var c=p;c<d.v;c+=1){var f=r.get(c+"");f!==void 0?At(f,Br):c in o&&(f=i(()=>an(Br)),r.set(c+"",f))}if(d===void 0)(!h||(x=zp(o,l))!=null&&x.writable)&&(d=i(()=>an(void 0)),At(d,yl(p)),r.set(l,d));else{h=d.v!==Br;var m=i(()=>yl(p));At(d,m)}var g=Reflect.getOwnPropertyDescriptor(o,l);if(g!=null&&g.set&&g.set.call(u,p),!h){if(n&&typeof l=="string"){var y=r.get("length"),b=Number(l);Number.isInteger(b)&&b>=y.v&&At(y,b+1)}$m(a)}return!0},ownKeys(o){Ye(a);var l=Reflect.ownKeys(o).filter(d=>{var h=r.get(d);return h===void 0||h.v!==Br});for(var[p,u]of r)u.v!==Br&&!(p in o)&&l.push(p);return l},setPrototypeOf(){sF()}})}function $m(e,t=1){At(e,e.v+t)}function yy(e){var t=Pn|$a,r=et!==null&&(et.f&Pn)!==0?et:null;return mt===null||r!==null&&(r.f&pn)!==0?t|=pn:mt.f|=J1,{ctx:dn,deps:null,effects:null,equals:Y1,f:t,fn:e,reactions:null,rv:0,v:null,wv:0,parent:r??mt}}function _p(e){const t=yy(e);return bk(t),t}function mF(e){const t=yy(e);return t.equals=Q1,t}function tk(e){var t=e.effects;if(t!==null){e.effects=null;for(var r=0;r<t.length;r+=1)us(t[r])}}function gF(e){for(var t=e.parent;t!==null;){if((t.f&Pn)===0)return t;t=t.parent}return null}function rk(e){var t,r=mt;ps(gF(e));try{tk(e),t=kk(e)}finally{ps(r)}return t}function nk(e){var t=rk(e);if(e.equals(t)||(e.v=t,e.wv=vk()),!jl){var r=(ts||(e.f&pn)!==0)&&e.deps!==null?Ci:Sn;ua(e,r)}}const Gp=new Map;function sc(e,t){var r={f:0,v:e,reactions:null,equals:Y1,rv:0,wv:0};return r}function an(e,t){const r=sc(e);return bk(r),r}function yF(e,t=!1,r=!0){const n=sc(e);return t||(n.equals=Q1),n}function At(e,t,r=!1){et!==null&&!ra&&ek()&&(et.f&(Pn|dy))!==0&&!(ir!=null&&ir[1].includes(e)&&ir[0]===et)&&iF();let n=r?yl(t):t;return ak(e,n)}function ak(e,t){if(!e.equals(t)){var r=e.v;jl?Gp.set(e,t):Gp.set(e,r),e.v=t,(e.f&Pn)!==0&&((e.f&$a)!==0&&rk(e),ua(e,(e.f&pn)===0?Sn:Ci)),e.wv=vk(),sk(e,$a),mt!==null&&(mt.f&Sn)!==0&&(mt.f&(Ra|Gl))===0&&(vn===null?AF([e]):vn.push(e))}return t}function sk(e,t){var r=e.reactions;if(r!==null)for(var n=r.length,a=0;a<n;a++){var s=r[a],i=s.f;(i&$a)===0&&(ua(s,t),(i&(Sn|pn))!==0&&((i&Pn)!==0?sk(s,Ci):ky(s)))}}let bF=!1;var Qw,ik,ok,lk;function xF(){if(Qw===void 0){Qw=window,ik=/Firefox/.test(navigator.userAgent);var e=Element.prototype,t=Node.prototype,r=Text.prototype;ok=zp(t,"firstChild").get,lk=zp(t,"nextSibling").get,Jw(e)&&(e.__click=void 0,e.__className=void 0,e.__attributes=null,e.__style=void 0,e.__e=void 0),Jw(r)&&(r.__t=void 0)}}function uk(e=""){return document.createTextNode(e)}function ic(e){return ok.call(e)}function jc(e){return lk.call(e)}function Gr(e,t){return ic(e)}function vF(e,t){{var r=ic(e);return r instanceof Comment&&r.data===""?jc(r):r}}function Fn(e,t=1,r=!1){let n=e;for(;t--;)n=jc(n);return n}function wF(e){e.textContent=""}function kF(e){mt===null&&et===null&&rF(),et!==null&&(et.f&pn)!==0&&mt===null&&tF(),jl&&eF()}function IF(e,t){var r=t.last;r===null?t.last=t.first=e:(r.next=e,e.prev=r,t.last=e)}function Hl(e,t,r,n=!0){var a=mt,s={ctx:dn,deps:null,nodes_start:null,nodes_end:null,f:e|$a,first:null,fn:t,last:null,next:null,parent:a,prev:null,teardown:null,transitions:null,wv:0};if(r)try{wy(s),s.f|=Z1}catch(l){throw us(s),l}else t!==null&&ky(s);var i=r&&s.deps===null&&s.first===null&&s.nodes_start===null&&s.teardown===null&&(s.f&(J1|hy))===0;if(!i&&n&&(a!==null&&IF(s,a),et!==null&&(et.f&Pn)!==0)){var o=et;(o.effects??(o.effects=[])).push(s)}return s}function pk(e){const t=Hl(Hc,null,!1);return ua(t,Sn),t.teardown=e,t}function SF(e){kF();var t=mt!==null&&(mt.f&Ra)!==0&&dn!==null&&!dn.m;if(t){var r=dn;(r.e??(r.e=[])).push({fn:e,effect:mt,reaction:et})}else{var n=by(e);return n}}function NF(e){const t=Hl(Gl,e,!0);return(r={})=>new Promise(n=>{r.outro?oc(t,()=>{us(t),n(void 0)}):(us(t),n(void 0))})}function by(e){return Hl(X1,e,!1)}function _F(e){return Hl(Hc,e,!0)}function bl(e,t=[],r=yy){const n=t.map(r);return xy(()=>e(...n.map(Ye)))}function xy(e,t=0){return Hl(Hc|dy|t,e,!0)}function Hp(e,t=!0){return Hl(Hc|Ra,e,!0,t)}function dk(e){var t=e.teardown;if(t!==null){const r=jl,n=et;e0(!0),la(null);try{t.call(null)}finally{e0(r),la(n)}}}function hk(e,t=!1){var r=e.first;for(e.first=e.last=null;r!==null;){var n=r.next;(r.f&Gl)!==0?r.parent=null:us(r,t),r=n}}function TF(e){for(var t=e.first;t!==null;){var r=t.next;(t.f&Ra)===0&&us(t),t=r}}function us(e,t=!0){var r=!1;(t||(e.f&JA)!==0)&&e.nodes_start!==null&&e.nodes_end!==null&&(CF(e.nodes_start,e.nodes_end),r=!0),hk(e,t&&!r),hc(e,0),ua(e,cy);var n=e.transitions;if(n!==null)for(const s of n)s.stop();dk(e);var a=e.parent;a!==null&&a.first!==null&&ck(e),e.next=e.prev=e.teardown=e.ctx=e.deps=e.fn=e.nodes_start=e.nodes_end=null}function CF(e,t){for(;e!==null;){var r=e===t?null:jc(e);e.remove(),e=r}}function ck(e){var t=e.parent,r=e.prev,n=e.next;r!==null&&(r.next=n),n!==null&&(n.prev=r),t!==null&&(t.first===e&&(t.first=n),t.last===e&&(t.last=r))}function oc(e,t){var r=[];vy(e,r,!0),fk(r,()=>{us(e),t&&t()})}function fk(e,t){var r=e.length;if(r>0){var n=()=>--r||t();for(var a of e)a.out(n)}else t()}function vy(e,t,r){if((e.f&_a)===0){if(e.f^=_a,e.transitions!==null)for(const i of e.transitions)(i.is_global||r)&&t.push(i);for(var n=e.first;n!==null;){var a=n.next,s=(n.f&fy)!==0||(n.f&Ra)!==0;vy(n,t,s?r:!1),n=a}}}function lc(e){mk(e,!0)}function mk(e,t){if((e.f&_a)!==0){e.f^=_a;for(var r=e.first;r!==null;){var n=r.next,a=(r.f&fy)!==0||(r.f&Ra)!==0;mk(r,a?t:!1),r=n}if(e.transitions!==null)for(const s of e.transitions)(s.is_global||t)&&s.in()}}let uc=[];function EF(){var e=uc;uc=[],ZA(e)}function gk(e){uc.length===0&&queueMicrotask(EF),uc.push(e)}function $F(e){var t=mt;if((t.f&Z1)===0){if((t.f&hy)===0)throw e;t.fn(e)}else yk(e,t)}function yk(e,t){for(;t!==null;){if((t.f&hy)!==0)try{t.fn(e);return}catch{}t=t.parent}throw e}let Ym=!1,pc=null,ni=!1,jl=!1;function e0(e){jl=e}let Kh=[];let et=null,ra=!1;function la(e){et=e}let mt=null;function ps(e){mt=e}let ir=null;function bk(e){et!==null&&et.f&Jm&&(ir===null?ir=[et,[e]]:ir[1].push(e))}let Cr=null,nn=0,vn=null;function AF(e){vn=e}let xk=1,dc=0,ts=!1;function vk(){return++xk}function qc(e){var d;var t=e.f;if((t&$a)!==0)return!0;if((t&Ci)!==0){var r=e.deps,n=(t&pn)!==0;if(r!==null){var a,s,i=(t&ac)!==0,o=n&&mt!==null&&!ts,l=r.length;if(i||o){var p=e,u=p.parent;for(a=0;a<l;a++)s=r[a],(i||!((d=s==null?void 0:s.reactions)!=null&&d.includes(p)))&&(s.reactions??(s.reactions=[])).push(p);i&&(p.f^=ac),o&&u!==null&&(u.f&pn)===0&&(p.f^=pn)}for(a=0;a<l;a++)if(s=r[a],qc(s)&&nk(s),s.wv>e.wv)return!0}(!n||mt!==null&&!ts)&&ua(e,Sn)}return!1}function wk(e,t,r=!0){var n=e.reactions;if(n!==null)for(var a=0;a<n.length;a++){var s=n[a];ir!=null&&ir[1].includes(e)&&ir[0]===et||((s.f&Pn)!==0?wk(s,t,!1):t===s&&(r?ua(s,$a):(s.f&Sn)!==0&&ua(s,Ci),ky(s)))}}function kk(e){var c;var t=Cr,r=nn,n=vn,a=et,s=ts,i=ir,o=dn,l=ra,p=e.f;Cr=null,nn=0,vn=null,ts=(p&pn)!==0&&(ra||!ni||et===null),et=(p&(Ra|Gl))===0?e:null,ir=null,Yw(e.ctx),ra=!1,dc++,e.f|=Jm;try{var u=(0,e.fn)(),d=e.deps;if(Cr!==null){var h;if(hc(e,nn),d!==null&&nn>0)for(d.length=nn+Cr.length,h=0;h<Cr.length;h++)d[nn+h]=Cr[h];else e.deps=d=Cr;if(!ts)for(h=nn;h<d.length;h++)((c=d[h]).reactions??(c.reactions=[])).push(e)}else d!==null&&nn<d.length&&(hc(e,nn),d.length=nn);if(ek()&&vn!==null&&!ra&&d!==null&&(e.f&(Pn|Ci|$a))===0)for(h=0;h<vn.length;h++)wk(vn[h],e);return a!==null&&a!==e&&(dc++,vn!==null&&(n===null?n=vn:n.push(...vn))),u}catch(f){$F(f)}finally{Cr=t,nn=r,vn=n,et=a,ts=s,ir=i,Yw(o),ra=l,e.f^=Jm}}function FF(e,t){let r=t.reactions;if(r!==null){var n=HA.call(r,e);if(n!==-1){var a=r.length-1;a===0?r=t.reactions=null:(r[n]=r[a],r.pop())}}r===null&&(t.f&Pn)!==0&&(Cr===null||!Cr.includes(t))&&(ua(t,Ci),(t.f&(pn|ac))===0&&(t.f^=ac),tk(t),hc(t,0))}function hc(e,t){var r=e.deps;if(r!==null)for(var n=t;n<r.length;n++)FF(e,r[n])}function wy(e){var t=e.f;if((t&cy)===0){ua(e,Sn);var r=mt,n=ni;mt=e,ni=!0;try{(t&dy)!==0?TF(e):hk(e),dk(e);var a=kk(e);e.teardown=typeof a=="function"?a:null,e.wv=xk;var s;Zw&&oF&&(e.f&$a)!==0&&e.deps}finally{ni=n,mt=r}}}function RF(){try{nF()}catch(e){if(pc!==null)yk(e,pc);else throw e}}function DF(){var e=ni;try{var t=0;for(ni=!0;Kh.length>0;){t++>1e3&&RF();var r=Kh,n=r.length;Kh=[];for(var a=0;a<n;a++){var s=OF(r[a]);MF(s)}Gp.clear()}}finally{Ym=!1,ni=e,pc=null}}function MF(e){var t=e.length;if(t!==0)for(var r=0;r<t;r++){var n=e[r];(n.f&(cy|_a))===0&&qc(n)&&(wy(n),n.deps===null&&n.first===null&&n.nodes_start===null&&(n.teardown===null?ck(n):n.fn=null))}}function ky(e){Ym||(Ym=!0,queueMicrotask(DF));for(var t=pc=e;t.parent!==null;){t=t.parent;var r=t.f;if((r&(Gl|Ra))!==0){if((r&Sn)===0)return;t.f^=Sn}}Kh.push(t)}function OF(e){for(var t=[],r=e;r!==null;){var n=r.f,a=(n&(Ra|Gl))!==0,s=a&&(n&Sn)!==0;if(!s&&(n&_a)===0){(n&X1)!==0?t.push(r):a?r.f^=Sn:qc(r)&&wy(r);var i=r.first;if(i!==null){r=i;continue}}var o=r.parent;for(r=r.next;r===null&&o!==null;)r=o.next,o=o.parent}return t}function Ye(e){var t=e.f,r=(t&Pn)!==0;if(et!==null&&!ra){if(!(ir!=null&&ir[1].includes(e))||ir[0]!==et){var n=et.deps;e.rv<dc&&(e.rv=dc,Cr===null&&n!==null&&n[nn]===e?nn++:Cr===null?Cr=[e]:(!ts||!Cr.includes(e))&&Cr.push(e))}}else if(r&&e.deps===null&&e.effects===null){var a=e,s=a.parent;s!==null&&(s.f&pn)===0&&(a.f^=pn)}return r&&(a=e,qc(a)&&nk(a)),jl&&Gp.has(e)?Gp.get(e):e.v}function Ik(e){var t=ra;try{return ra=!0,e()}finally{ra=t}}const LF=-7169;function ua(e,t){e.f=e.f&LF|t}const zF=["touchstart","touchmove"];function PF(e){return zF.includes(e)}function BF(e){var t=et,r=mt;la(null),ps(null);try{return e()}finally{la(t),ps(r)}}const Sk=new Set,Qm=new Set;function WF(e,t,r,n={}){function a(s){if(n.capture||Tp.call(t,s),!s.cancelBubble)return BF(()=>r==null?void 0:r.call(this,s))}return e.startsWith("pointer")||e.startsWith("touch")||e==="wheel"?gk(()=>{t.addEventListener(e,a,n)}):t.addEventListener(e,a,n),a}function eg(e,t,r,n,a){var s={capture:n,passive:a},i=WF(e,t,r,s);(t===document.body||t===window||t===document||t instanceof HTMLMediaElement)&&pk(()=>{t.removeEventListener(e,i,s)})}function UF(e){for(var t=0;t<e.length;t++)Sk.add(e[t]);for(var r of Qm)r(e)}function Tp(e){var b;var t=this,r=t.ownerDocument,n=e.type,a=((b=e.composedPath)==null?void 0:b.call(e))||[],s=a[0]||e.target,i=0,o=e.__root;if(o){var l=a.indexOf(o);if(l!==-1&&(t===document||t===window)){e.__root=t;return}var p=a.indexOf(t);if(p===-1)return;l<=p&&(i=l)}if(s=a[i]||e.target,s!==t){jA(e,"currentTarget",{configurable:!0,get(){return s||r}});var u=et,d=mt;la(null),ps(null);try{for(var h,c=[];s!==null;){var f=s.assignedSlot||s.parentNode||s.host||null;try{var m=s["__"+n];if(m!=null&&(!s.disabled||e.target===s))if(uy(m)){var[g,...y]=m;g.apply(s,[e,...y])}else m.call(s,e)}catch(x){h?c.push(x):h=x}if(e.cancelBubble||f===t||f===null)break;s=f}if(h){for(let x of c)queueMicrotask(()=>{throw x});throw h}}finally{e.__root=t,delete e.currentTarget,la(u),ps(d)}}}function VF(e){var t=document.createElement("template");return t.innerHTML=e.replaceAll("<!>","<!---->"),t.content}function t0(e,t){var r=mt;r.nodes_start===null&&(r.nodes_start=e,r.nodes_end=t)}function Hn(e,t){var r=(t&dF)!==0,n=(t&hF)!==0,a,s=!e.startsWith("<!>");return()=>{a===void 0&&(a=VF(s?e:"<!>"+e),r||(a=ic(a)));var i=n||ik?document.importNode(a,!0):a.cloneNode(!0);if(r){var o=ic(i),l=i.lastChild;t0(o,l)}else t0(i,i);return i}}function Rn(e,t){e!==null&&e.before(t)}function tg(e,t){var r=t==null?"":typeof t=="object"?t+"":t;r!==(e.__t??(e.__t=e.nodeValue))&&(e.__t=r,e.nodeValue=r+"")}function GF(e,t){return HF(e,t)}const pl=new Map;function HF(e,{target:t,anchor:r,props:n={},events:a,context:s,intro:i=!0}){xF();var o=new Set,l=d=>{for(var h=0;h<d.length;h++){var c=d[h];if(!o.has(c)){o.add(c);var f=PF(c);t.addEventListener(c,Tp,{passive:f});var m=pl.get(c);m===void 0?(document.addEventListener(c,Tp,{passive:f}),pl.set(c,1)):pl.set(c,m+1)}}};l(py(Sk)),Qm.add(l);var p=void 0,u=NF(()=>{var d=r??t.appendChild(uk());return Hp(()=>{if(s){my({});var h=dn;h.c=s}a&&(n.$$events=a),p=e(d,n)||{},s&&gy()}),()=>{var f;for(var h of o){t.removeEventListener(h,Tp);var c=pl.get(h);--c===0?(document.removeEventListener(h,Tp),pl.delete(h)):pl.set(h,c)}Qm.delete(l),d!==r&&((f=d.parentNode)==null||f.removeChild(d))}});return jF.set(p,u),p}let jF=new WeakMap;function xl(e,t,[r,n]=[0,0]){var a=e,s=null,i=null,o=Br,l=r>0?fy:0,p=!1;const u=(h,c=!0)=>{p=!0,d(c,h)},d=(h,c)=>{o!==(o=h)&&(o?(s?lc(s):c&&(s=Hp(()=>c(a))),i&&oc(i,()=>{i=null})):(i?lc(i):c&&(i=Hp(()=>c(a,[r+1,n]))),s&&oc(s,()=>{s=null})))};xy(()=>{p=!1,t(u),p||d(null,null)},l)}function qF(e,t){return t}function KF(e,t,r,n){for(var a=[],s=t.length,i=0;i<s;i++)vy(t[i].e,a,!0);var o=s>0&&a.length===0&&r!==null;if(o){var l=r.parentNode;wF(l),l.append(r),n.clear(),Za(e,t[0].prev,t[s-1].next)}fk(a,()=>{for(var p=0;p<s;p++){var u=t[p];o||(n.delete(u.k),Za(e,u.prev,u.next)),us(u.e,!o)}})}function XF(e,t,r,n,a,s=null){var i=e,o={flags:t,items:new Map,first:null};{var l=e;i=l.appendChild(uk())}var p=null,u=!1,d=mF(()=>{var h=r();return uy(h)?h:h==null?[]:py(h)});xy(()=>{var h=Ye(d),c=h.length;u&&c===0||(u=c===0,ZF(h,o,i,a,t,n,r),s!==null&&(c===0?p?lc(p):p=Hp(()=>s(i)):p!==null&&oc(p,()=>{p=null})),Ye(d))})}function ZF(e,t,r,n,a,s,i){var o=e.length,l=t.items,p=t.first,u=p,d,h=null,c=[],f=[],m,g,y,b;for(b=0;b<o;b+=1){if(m=e[b],g=s(m,b),y=l.get(g),y===void 0){var x=u?u.e.nodes_start:r;h=YF(x,t,h,h===null?t.first:h.next,m,g,b,n,a,i),l.set(g,h),c=[],f=[],u=h.next;continue}if(JF(y,m,b),(y.e.f&_a)!==0&&lc(y.e),y!==u){if(d!==void 0&&d.has(y)){if(c.length<f.length){var v=f[0],w;h=v.prev;var N=c[0],T=c[c.length-1];for(w=0;w<c.length;w+=1)r0(c[w],v,r);for(w=0;w<f.length;w+=1)d.delete(f[w]);Za(t,N.prev,T.next),Za(t,h,N),Za(t,T,v),u=v,h=T,b-=1,c=[],f=[]}else d.delete(y),r0(y,u,r),Za(t,y.prev,y.next),Za(t,y,h===null?t.first:h.next),Za(t,h,y),h=y;continue}for(c=[],f=[];u!==null&&u.k!==g;)(u.e.f&_a)===0&&(d??(d=new Set)).add(u),f.push(u),u=u.next;if(u===null)continue;y=u}c.push(y),h=y,u=y.next}if(u!==null||d!==void 0){for(var E=d===void 0?[]:py(d);u!==null;)(u.e.f&_a)===0&&E.push(u),u=u.next;var $=E.length;if($>0){var R=o===0?r:null;KF(t,E,R,l)}}mt.first=t.first&&t.first.e,mt.last=h&&h.e}function JF(e,t,r,n){ak(e.v,t),e.i=r}function YF(e,t,r,n,a,s,i,o,l,p){var u=(l&lF)!==0,d=(l&pF)===0,h=u?d?yF(a,!1,!1):sc(a):a,c=(l&uF)===0?i:sc(i),f={i:c,v:h,k:s,a:null,e:null,prev:r,next:n};try{return f.e=Hp(()=>o(e,h,c,p),bF),f.e.prev=r&&r.e,f.e.next=n&&n.e,r===null?t.first=f:(r.next=f,r.e.next=f.e),n!==null&&(n.prev=f,n.e.prev=f.e),f}finally{}}function r0(e,t,r){for(var n=e.next?e.next.e.nodes_start:r,a=t?t.e.nodes_start:r,s=e.e.nodes_start;s!==n;){var i=jc(s);a.before(s),s=i}}function Za(e,t,r){t===null?e.first=r:(t.next=r,t.e.next=r&&r.e),r!==null&&(r.prev=t,r.e.prev=t&&t.e)}function n0(e,t=!1){var r=t?" !important;":";",n="";for(var a in e){var s=e[a];s!=null&&s!==""&&(n+=" "+a+": "+s+r)}return n}function QF(e,t){if(t){var r="",n,a;return Array.isArray(t)?(n=t[0],a=t[1]):n=t,n&&(r+=n0(n)),a&&(r+=n0(a,!0)),r=r.trim(),r===""?null:r}return String(e)}function Am(e,t={},r,n){for(var a in r){var s=r[a];t[a]!==s&&(r[a]==null?e.style.removeProperty(a):e.style.setProperty(a,s,n))}}function eR(e,t,r,n){var a=e.__style;if(a!==t){var s=QF(t,n);s==null?e.removeAttribute("style"):e.style.cssText=s,e.__style=t}else n&&(Array.isArray(n)?(Am(e,r==null?void 0:r[0],n[0]),Am(e,r==null?void 0:r[1],n[1],"important")):Am(e,r,n));return n}const tR=Symbol("is custom element"),rR=Symbol("is html");function Ja(e,t,r,n){var a=nR(e);a[t]!==(a[t]=r)&&(t==="loading"&&(e[YA]=r),r==null?e.removeAttribute(t):typeof r!="string"&&aR(e).includes(t)?e[t]=r:e.setAttribute(t,r))}function nR(e){return e.__attributes??(e.__attributes={[tR]:e.nodeName.includes("-"),[rR]:e.namespaceURI===cF})}var a0=new Map;function aR(e){var t=a0.get(e.nodeName);if(t)return t;a0.set(e.nodeName,t=[]);for(var r,n=e,a=Element.prototype;a!==n;){r=qA(n);for(var s in r)r[s].set&&t.push(s);n=K1(n)}return t}function s0(e,t){return e===t||(e==null?void 0:e[qh])===t}function sR(e={},t,r,n){return by(()=>{var a,s;return _F(()=>{a=s,s=[],Ik(()=>{e!==r(...s)&&(t(e,...s),a&&s0(r(...a),e)&&t(null,...a))})}),()=>{gk(()=>{s&&s0(r(...s),e)&&t(null,...s)})}}),e}function iR(e){dn===null&&fF(),SF(()=>{const t=Ik(e);if(typeof t=="function")return t})}const oR="5";var q1;typeof window<"u"&&((q1=window.__svelte??(window.__svelte={})).v??(q1.v=new Set)).add(oR);var lR=Object.defineProperty,uR=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),Iy=(e,t)=>{for(var r in t)lR(e,r,{get:t[r],enumerable:!0})},pR={};Iy(pR,{Abs:()=>Kl,Acos:()=>$i,Acosh:()=>Ai,AdadeltaOptimizer:()=>Vb,AdagradOptimizer:()=>Gb,AdamOptimizer:()=>Hb,AdamaxOptimizer:()=>jb,Add:()=>Ts,AddN:()=>Fi,All:()=>Xl,Any:()=>Zl,ArgMax:()=>Jl,ArgMin:()=>Yl,Asin:()=>Ri,Asinh:()=>Di,Atan:()=>Mi,Atan2:()=>Li,Atanh:()=>Oi,AvgPool:()=>zi,AvgPool3D:()=>Ql,AvgPool3DGrad:()=>cd,AvgPoolGrad:()=>hd,BackendWasm:()=>R$,BatchMatMul:()=>Pi,BatchToSpaceND:()=>eu,Bincount:()=>tu,BitwiseAnd:()=>ru,BroadcastArgs:()=>fd,BroadcastTo:()=>Pk,Callback:()=>F2,CallbackList:()=>NN,Cast:()=>Bi,Ceil:()=>Wi,ClipByValue:()=>Cs,Complex:()=>Yc,ComplexAbs:()=>md,Concat:()=>nu,Conv2D:()=>Ui,Conv2DBackpropFilter:()=>Qc,Conv2DBackpropInput:()=>Vi,Conv3D:()=>Gi,Conv3DBackpropFilterV2:()=>au,Conv3DBackpropInputV2:()=>su,Cos:()=>Hi,Cosh:()=>ji,CropAndResize:()=>ou,Cumprod:()=>iu,Cumsum:()=>qi,CustomCallback:()=>TN,DataStorage:()=>Xc,DenseBincount:()=>gd,DepthToSpace:()=>lu,DepthwiseConv2dNative:()=>Ki,DepthwiseConv2dNativeBackpropFilter:()=>ef,DepthwiseConv2dNativeBackpropInput:()=>tf,Diag:()=>yd,Dilation2D:()=>Xi,Dilation2DBackpropFilter:()=>Cl,Dilation2DBackpropInput:()=>Tl,Draw:()=>rf,ENV:()=>Cy,EarlyStopping:()=>R2,Einsum:()=>nf,Elu:()=>Ji,EluGrad:()=>uu,Environment:()=>Lk,Equal:()=>pu,Erf:()=>Yi,Exp:()=>Qi,ExpandDims:()=>du,Expm1:()=>eo,FFT:()=>af,Fill:()=>bd,FlipLeftRight:()=>hu,Floor:()=>to,FloorDiv:()=>ro,FromPixels:()=>gc,FusedBatchNorm:()=>no,FusedConv2D:()=>ui,FusedDepthwiseConv2D:()=>pi,GPGPUContext:()=>rc,GatherNd:()=>fu,GatherV2:()=>cu,GraphModel:()=>Fv,Greater:()=>mu,GreaterEqual:()=>ao,History:()=>_N,IFFT:()=>sf,Identity:()=>so,Imag:()=>of,InputSpec:()=>Rt,IsFinite:()=>io,IsInf:()=>oo,IsNan:()=>lo,KernelBackend:()=>pd,LRN:()=>co,LRNGrad:()=>ku,LayerVariable:()=>yN,LayersModel:()=>Ca,LeakyRelu:()=>uo,Less:()=>gu,LessEqual:()=>yu,LinSpace:()=>bu,Log:()=>po,Log1p:()=>ho,LogSoftmax:()=>Wk,LogicalAnd:()=>xu,LogicalNot:()=>vu,LogicalOr:()=>wu,LogicalXor:()=>Bk,LowerBound:()=>tD,MathBackendCPU:()=>Mv,MathBackendWebGL:()=>uw,MatrixBandPart:()=>rD,Max:()=>fo,MaxPool:()=>go,MaxPool3D:()=>Iu,MaxPool3DGrad:()=>vd,MaxPoolGrad:()=>xd,MaxPoolWithArgmax:()=>wd,Maximum:()=>mo,Mean:()=>yo,Min:()=>bo,Minimum:()=>xo,MirrorPad:()=>vo,Mod:()=>wo,MomentumOptimizer:()=>qb,Multinomial:()=>Su,Multiply:()=>ko,Neg:()=>Nu,NonMaxSuppressionV3:()=>Tu,NonMaxSuppressionV4:()=>Cu,NonMaxSuppressionV5:()=>Eu,NotEqual:()=>_u,OP_SCOPE_SUFFIX:()=>Ry,OneHot:()=>Io,OnesLike:()=>$u,Optimizer:()=>Pa,OptimizerConstructors:()=>ZS,Pack:()=>Au,PadV2:()=>So,Pool:()=>nD,Pow:()=>No,Prelu:()=>_o,Prod:()=>To,RMSPropOptimizer:()=>Kb,RNN:()=>Ba,RaggedGather:()=>lf,RaggedRange:()=>uf,RaggedTensorToTensor:()=>pf,Range:()=>kd,Rank:()=>ag,Real:()=>df,RealDiv:()=>Zi,Reciprocal:()=>Co,Reduction:()=>mr,Relu:()=>Eo,Relu6:()=>Fo,Reshape:()=>Fu,ResizeBilinear:()=>Ao,ResizeBilinearGrad:()=>Du,ResizeNearestNeighbor:()=>$o,ResizeNearestNeighborGrad:()=>Ru,Reverse:()=>Ro,RotateWithOffset:()=>Xu,Round:()=>Do,Rsqrt:()=>Mo,SGDOptimizer:()=>qf,ScatterNd:()=>Mu,SearchSorted:()=>Lu,Select:()=>zu,Selu:()=>Oo,Sequential:()=>im,Sigmoid:()=>Bo,Sign:()=>Po,Sin:()=>Lo,Sinh:()=>zo,Slice:()=>Pu,Softmax:()=>Go,Softplus:()=>Wo,SpaceToBatchND:()=>Bu,SparseFillEmptyRows:()=>Id,SparseReshape:()=>Uu,SparseSegmentMean:()=>Sd,SparseSegmentSum:()=>Nd,SparseToDense:()=>Vu,SplitV:()=>Wu,Sqrt:()=>Uo,Square:()=>_d,SquaredDifference:()=>Ho,StaticRegexReplace:()=>Td,Step:()=>$s,StridedSlice:()=>Gu,StringNGrams:()=>Cd,StringSplit:()=>Ed,StringToHashBucketFast:()=>$d,Sub:()=>jo,Sum:()=>Vo,SymbolicTensor:()=>Un,Tan:()=>qo,Tanh:()=>Ko,Tensor:()=>ze,TensorBuffer:()=>Dt,TensorScatterUpdate:()=>Ou,Tile:()=>Es,TopK:()=>Hu,Transform:()=>ju,Transpose:()=>Ta,Unique:()=>Ad,Unpack:()=>qu,UnsortedSegmentSum:()=>Fd,UpperBound:()=>aD,Variable:()=>di,ZerosLike:()=>Ku,_FusedMatMul:()=>li,abs:()=>Ft,acos:()=>zy,acosh:()=>Py,add:()=>J,addN:()=>mI,all:()=>gf,any:()=>Jp,argMax:()=>mi,argMin:()=>By,asin:()=>Wy,asinh:()=>Uy,atan:()=>Vy,atan2:()=>Gy,atanh:()=>Hy,avgPool:()=>Oa,avgPool3d:()=>qy,backend:()=>Dy,backend_util:()=>_,basicLSTMCell:()=>xI,batchNorm:()=>Xo,batchNorm2d:()=>Ky,batchNorm3d:()=>Xy,batchNorm4d:()=>Zy,batchToSpaceND:()=>Pd,bincount:()=>Jy,bitwiseAnd:()=>vI,booleanMaskAsync:()=>uS,broadcastArgs:()=>wI,broadcastTo:()=>ai,broadcast_util:()=>Zu,browser:()=>Yd,buffer:()=>Le,callbacks:()=>Q6,cast:()=>se,ceil:()=>Yy,clipByValue:()=>ur,clone:()=>sa,complex:()=>Aa,concat:()=>lt,concat1d:()=>Qy,concat2d:()=>eb,concat3d:()=>tb,concat4d:()=>rb,constraints:()=>wN,conv1d:()=>yf,conv2d:()=>br,conv2dTranspose:()=>bf,conv3d:()=>ab,conv3dTranspose:()=>sb,copyRegisteredKernels:()=>lD,cos:()=>Bd,cosh:()=>xf,cosineWindow:()=>Uf,cumprod:()=>ed,cumsum:()=>vf,customGrad:()=>ha,data:()=>n_,denseBincount:()=>xc,deprecationWarn:()=>tI,depthToSpace:()=>ib,depthwiseConv2d:()=>Zo,deregisterOp:()=>rj,device_util:()=>Od,diag:()=>II,dilation2d:()=>ob,disableDeprecationWarnings:()=>zD,dispose:()=>Ce,disposeVariables:()=>PD,div:()=>fe,divNoNan:()=>lb,dot:()=>ub,dropout:()=>zb,einsum:()=>Js,elu:()=>Ju,enableDebugMode:()=>LD,enableProdMode:()=>OD,enclosingPowerOfTwo:()=>Pb,engine:()=>wn,ensureShape:()=>NI,env:()=>j,equal:()=>Kr,erf:()=>wf,euclideanNorm:()=>hb,exp:()=>pr,expandDims:()=>Xt,expm1:()=>cb,eye:()=>kf,fft:()=>Zd,fill:()=>qr,findBackend:()=>HD,findBackendFactory:()=>jD,floor:()=>Qu,floorDiv:()=>mf,forceHalfFloat:()=>TC,fused:()=>Ol,gather:()=>ep,gatherND:()=>cS,gather_util:()=>Jb,getBackend:()=>rI,getGradient:()=>rg,getKernel:()=>Kp,getKernelsForBackend:()=>yc,getThreadsCount:()=>ife,gpgpu_util:()=>aC,grad:()=>S3,grads:()=>N3,greater:()=>Ir,greaterEqual:()=>La,ifft:()=>Ml,imag:()=>Wd,image:()=>sn,inTopKAsync:()=>fS,initializers:()=>kN,input:()=>WN,io:()=>or,irfft:()=>Mf,isFinite:()=>fb,isInf:()=>mb,isNaN:()=>gb,keep:()=>Pt,kernel_impls:()=>ga,layers:()=>IN,leakyRelu:()=>Ud,less:()=>Al,lessEqual:()=>Fs,linalg:()=>Ub,linspace:()=>$I,loadGraphModel:()=>lq,loadGraphModelSync:()=>uq,loadLayersModel:()=>KG,localResponseNormalization:()=>yb,log:()=>Xr,log1p:()=>Vd,logSigmoid:()=>bb,logSoftmax:()=>Sf,logSumExp:()=>Gd,logicalAnd:()=>Nn,logicalNot:()=>Hd,logicalOr:()=>Nf,logicalXor:()=>xb,losses:()=>_S,lowerBound:()=>FI,matMul:()=>Me,math:()=>LS,max:()=>hn,maxPool:()=>jt,maxPool3d:()=>vb,maxPoolWithArgmax:()=>RI,maximum:()=>ma,mean:()=>kt,memory:()=>dg,meshgrid:()=>DI,metrics:()=>E2,min:()=>$l,minimum:()=>ys,mirrorPad:()=>wb,mod:()=>kb,model:()=>JG,models:()=>$2,moments:()=>jd,movingAverage:()=>pS,mul:()=>z,multiRNNCell:()=>MI,multinomial:()=>OI,neg:()=>gt,nextFrame:()=>Yb,norm:()=>Yu,notEqual:()=>bi,oneHot:()=>Fl,ones:()=>$r,onesLike:()=>Zr,op:()=>L,outerProduct:()=>LI,pad:()=>jn,pad1d:()=>zI,pad2d:()=>PI,pad3d:()=>BI,pad4d:()=>WI,pool:()=>Ib,pow:()=>da,prelu:()=>Kd,print:()=>Ly,prod:()=>Sb,profile:()=>BD,raggedGather:()=>UI,raggedRange:()=>VI,raggedTensorToTensor:()=>GI,rand:()=>HI,randomGamma:()=>XI,randomNormal:()=>Tf,randomStandardNormal:()=>ZI,randomUniform:()=>Rs,randomUniformInt:()=>JI,range:()=>xi,ready:()=>VD,real:()=>Rl,reciprocal:()=>Eb,registerBackend:()=>ff,registerCallbackConstructor:()=>QG,registerGradient:()=>Uk,registerKernel:()=>Rd,registerOp:()=>tj,regularizers:()=>A2,relu:()=>rt,relu6:()=>Cf,removeBackend:()=>GD,reshape:()=>B,reverse:()=>mn,reverse1d:()=>YI,reverse2d:()=>QI,reverse3d:()=>eS,reverse4d:()=>tS,rfft:()=>Jd,round:()=>Ef,rsqrt:()=>$f,scalar:()=>we,scatterND:()=>dS,scatter_util:()=>zf,searchSorted:()=>_f,selu:()=>Af,separableConv2d:()=>tp,sequential:()=>YG,serialization:()=>ne,setBackend:()=>UD,setPlatform:()=>qD,setThreadsCount:()=>sfe,setWasmPath:()=>nfe,setWasmPaths:()=>afe,setWebGLContext:()=>CT,setdiff1dAsync:()=>rS,shared:()=>Ov,sigmoid:()=>In,sign:()=>$b,signal:()=>NS,sin:()=>Ff,sinh:()=>Rf,slice:()=>Ve,slice1d:()=>Xd,slice2d:()=>Df,slice3d:()=>rp,slice4d:()=>Dl,slice_util:()=>Wt,softmax:()=>Ds,softplus:()=>Jo,spaceToBatchND:()=>qd,sparse:()=>TS,sparseToDense:()=>hS,spectral:()=>SS,split:()=>Ar,sqrt:()=>Yt,square:()=>ot,squaredDifference:()=>Of,squeeze:()=>Ms,stack:()=>Mt,step:()=>Yo,stridedSlice:()=>Ab,string:()=>CS,sub:()=>de,sum:()=>ge,sumOutType:()=>cf,tan:()=>Fb,tanh:()=>gs,tensor:()=>yr,tensor1d:()=>Qe,tensor2d:()=>ia,tensor3d:()=>Lf,tensor4d:()=>bs,tensor5d:()=>nS,tensor6d:()=>aS,tensorScatterUpdate:()=>iS,tensor_util:()=>Mn,test_util:()=>jI,tidy:()=>W,tile:()=>jr,time:()=>WD,topk:()=>Db,train:()=>Ks,transpose:()=>Oe,truncatedNormal:()=>Bf,unique:()=>Mb,unregisterGradient:()=>oD,unregisterKernel:()=>iD,unsortedSegmentSum:()=>Wf,unstack:()=>Tt,upcastType:()=>cn,upperBound:()=>oS,util:()=>k,valueAndGrad:()=>_3,valueAndGrads:()=>T3,variable:()=>Ob,variableGrads:()=>AI,version:()=>cfe,version_converter:()=>dq,version_core:()=>JB,version_cpu:()=>hK,version_layers:()=>wx,version_wasm:()=>ofe,version_webgl:()=>tQ,webgl:()=>rQ,webgl_util:()=>TT,where:()=>Jt,whereAsync:()=>Lb,zeros:()=>It,zerosLike:()=>He});var dR=Object.create,Sy=Object.defineProperty,hR=Object.getOwnPropertyDescriptor,cR=Object.getOwnPropertyNames,fR=Object.getPrototypeOf,mR=Object.prototype.hasOwnProperty,Lt=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Ee=(e,t)=>{for(var r in t)Sy(e,r,{get:t[r],enumerable:!0})},gR=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of cR(t))!mR.call(e,a)&&a!==r&&Sy(e,a,{get:()=>t[a],enumerable:!(n=hR(t,a))||n.enumerable});return e},_s=(e,t,r)=>(r=e!=null?dR(fR(e)):{},gR(!e||!e.__esModule?Sy(r,"default",{value:e,enumerable:!0}):r,e)),yR=Lt((e,t)=>{t.exports=n;var r=null;try{r=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}function n(S,D,P){this.low=S|0,this.high=D|0,this.unsigned=!!P}n.prototype.__isLong__,Object.defineProperty(n.prototype,"__isLong__",{value:!0});function a(S){return(S&&S.__isLong__)===!0}n.isLong=a;var s={},i={};function o(S,D){var P,U,H;return D?(S>>>=0,(H=0<=S&&S<256)&&(U=i[S],U)?U:(P=p(S,(S|0)<0?-1:0,!0),H&&(i[S]=P),P)):(S|=0,(H=-128<=S&&S<128)&&(U=s[S],U)?U:(P=p(S,S<0?-1:0,!1),H&&(s[S]=P),P))}n.fromInt=o;function l(S,D){if(isNaN(S))return D?v:x;if(D){if(S<0)return v;if(S>=g)return $}else{if(S<=-y)return R;if(S+1>=y)return E}return S<0?l(-S,D).neg():p(S%m|0,S/m|0,D)}n.fromNumber=l;function p(S,D,P){return new n(S,D,P)}n.fromBits=p;var u=Math.pow;function d(S,D,P){if(S.length===0)throw Error("empty string");if(S==="NaN"||S==="Infinity"||S==="+Infinity"||S==="-Infinity")return x;if(typeof D=="number"?(P=D,D=!1):D=!!D,P=P||10,P<2||36<P)throw RangeError("radix");var U;if((U=S.indexOf("-"))>0)throw Error("interior hyphen");if(U===0)return d(S.substring(1),D,P).neg();for(var H=l(u(P,8)),q=x,G=0;G<S.length;G+=8){var Z=Math.min(8,S.length-G),ee=parseInt(S.substring(G,G+Z),P);if(Z<8){var X=l(u(P,Z));q=q.mul(X).add(l(ee))}else q=q.mul(H),q=q.add(l(ee))}return q.unsigned=D,q}n.fromString=d;function h(S,D){return typeof S=="number"?l(S,D):typeof S=="string"?d(S,D):p(S.low,S.high,typeof D=="boolean"?D:S.unsigned)}n.fromValue=h;var c=65536,f=1<<24,m=c*c,g=m*m,y=g/2,b=o(f),x=o(0);n.ZERO=x;var v=o(0,!0);n.UZERO=v;var w=o(1);n.ONE=w;var N=o(1,!0);n.UONE=N;var T=o(-1);n.NEG_ONE=T;var E=p(-1,2147483647,!1);n.MAX_VALUE=E;var $=p(-1,-1,!0);n.MAX_UNSIGNED_VALUE=$;var R=p(0,-2147483648,!1);n.MIN_VALUE=R;var F=n.prototype;F.toInt=function(){return this.unsigned?this.low>>>0:this.low},F.toNumber=function(){return this.unsigned?(this.high>>>0)*m+(this.low>>>0):this.high*m+(this.low>>>0)},F.toString=function(S){if(S=S||10,S<2||36<S)throw RangeError("radix");if(this.isZero())return"0";if(this.isNegative())if(this.eq(R)){var D=l(S),P=this.div(D),U=P.mul(D).sub(this);return P.toString(S)+U.toInt().toString(S)}else return"-"+this.neg().toString(S);for(var H=l(u(S,6),this.unsigned),q=this,G="";;){var Z=q.div(H),ee=q.sub(Z.mul(H)).toInt()>>>0,X=ee.toString(S);if(q=Z,q.isZero())return X+G;for(;X.length<6;)X="0"+X;G=""+X+G}},F.getHighBits=function(){return this.high},F.getHighBitsUnsigned=function(){return this.high>>>0},F.getLowBits=function(){return this.low},F.getLowBitsUnsigned=function(){return this.low>>>0},F.getNumBitsAbs=function(){if(this.isNegative())return this.eq(R)?64:this.neg().getNumBitsAbs();for(var S=this.high!=0?this.high:this.low,D=31;D>0&&!(S&1<<D);D--);return this.high!=0?D+33:D+1},F.isZero=function(){return this.high===0&&this.low===0},F.eqz=F.isZero,F.isNegative=function(){return!this.unsigned&&this.high<0},F.isPositive=function(){return this.unsigned||this.high>=0},F.isOdd=function(){return(this.low&1)===1},F.isEven=function(){return(this.low&1)===0},F.equals=function(S){return a(S)||(S=h(S)),this.unsigned!==S.unsigned&&this.high>>>31===1&&S.high>>>31===1?!1:this.high===S.high&&this.low===S.low},F.eq=F.equals,F.notEquals=function(S){return!this.eq(S)},F.neq=F.notEquals,F.ne=F.notEquals,F.lessThan=function(S){return this.comp(S)<0},F.lt=F.lessThan,F.lessThanOrEqual=function(S){return this.comp(S)<=0},F.lte=F.lessThanOrEqual,F.le=F.lessThanOrEqual,F.greaterThan=function(S){return this.comp(S)>0},F.gt=F.greaterThan,F.greaterThanOrEqual=function(S){return this.comp(S)>=0},F.gte=F.greaterThanOrEqual,F.ge=F.greaterThanOrEqual,F.compare=function(S){if(a(S)||(S=h(S)),this.eq(S))return 0;var D=this.isNegative(),P=S.isNegative();return D&&!P?-1:!D&&P?1:this.unsigned?S.high>>>0>this.high>>>0||S.high===this.high&&S.low>>>0>this.low>>>0?-1:1:this.sub(S).isNegative()?-1:1},F.comp=F.compare,F.negate=function(){return!this.unsigned&&this.eq(R)?R:this.not().add(w)},F.neg=F.negate,F.add=function(S){a(S)||(S=h(S));var D=this.high>>>16,P=this.high&65535,U=this.low>>>16,H=this.low&65535,q=S.high>>>16,G=S.high&65535,Z=S.low>>>16,ee=S.low&65535,X=0,re=0,te=0,ae=0;return ae+=H+ee,te+=ae>>>16,ae&=65535,te+=U+Z,re+=te>>>16,te&=65535,re+=P+G,X+=re>>>16,re&=65535,X+=D+q,X&=65535,p(te<<16|ae,X<<16|re,this.unsigned)},F.subtract=function(S){return a(S)||(S=h(S)),this.add(S.neg())},F.sub=F.subtract,F.multiply=function(S){if(this.isZero())return x;if(a(S)||(S=h(S)),r){var D=r.mul(this.low,this.high,S.low,S.high);return p(D,r.get_high(),this.unsigned)}if(S.isZero())return x;if(this.eq(R))return S.isOdd()?R:x;if(S.eq(R))return this.isOdd()?R:x;if(this.isNegative())return S.isNegative()?this.neg().mul(S.neg()):this.neg().mul(S).neg();if(S.isNegative())return this.mul(S.neg()).neg();if(this.lt(b)&&S.lt(b))return l(this.toNumber()*S.toNumber(),this.unsigned);var P=this.high>>>16,U=this.high&65535,H=this.low>>>16,q=this.low&65535,G=S.high>>>16,Z=S.high&65535,ee=S.low>>>16,X=S.low&65535,re=0,te=0,ae=0,ie=0;return ie+=q*X,ae+=ie>>>16,ie&=65535,ae+=H*X,te+=ae>>>16,ae&=65535,ae+=q*ee,te+=ae>>>16,ae&=65535,te+=U*X,re+=te>>>16,te&=65535,te+=H*ee,re+=te>>>16,te&=65535,te+=q*Z,re+=te>>>16,te&=65535,re+=P*X+U*ee+H*Z+q*G,re&=65535,p(ae<<16|ie,re<<16|te,this.unsigned)},F.mul=F.multiply,F.divide=function(S){if(a(S)||(S=h(S)),S.isZero())throw Error("division by zero");if(r){if(!this.unsigned&&this.high===-2147483648&&S.low===-1&&S.high===-1)return this;var D=(this.unsigned?r.div_u:r.div_s)(this.low,this.high,S.low,S.high);return p(D,r.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?v:x;var P,U,H;if(this.unsigned){if(S.unsigned||(S=S.toUnsigned()),S.gt(this))return v;if(S.gt(this.shru(1)))return N;H=v}else{if(this.eq(R)){if(S.eq(w)||S.eq(T))return R;if(S.eq(R))return w;var q=this.shr(1);return P=q.div(S).shl(1),P.eq(x)?S.isNegative()?w:T:(U=this.sub(S.mul(P)),H=P.add(U.div(S)),H)}else if(S.eq(R))return this.unsigned?v:x;if(this.isNegative())return S.isNegative()?this.neg().div(S.neg()):this.neg().div(S).neg();if(S.isNegative())return this.div(S.neg()).neg();H=x}for(U=this;U.gte(S);){P=Math.max(1,Math.floor(U.toNumber()/S.toNumber()));for(var G=Math.ceil(Math.log(P)/Math.LN2),Z=G<=48?1:u(2,G-48),ee=l(P),X=ee.mul(S);X.isNegative()||X.gt(U);)P-=Z,ee=l(P,this.unsigned),X=ee.mul(S);ee.isZero()&&(ee=w),H=H.add(ee),U=U.sub(X)}return H},F.div=F.divide,F.modulo=function(S){if(a(S)||(S=h(S)),r){var D=(this.unsigned?r.rem_u:r.rem_s)(this.low,this.high,S.low,S.high);return p(D,r.get_high(),this.unsigned)}return this.sub(this.div(S).mul(S))},F.mod=F.modulo,F.rem=F.modulo,F.not=function(){return p(~this.low,~this.high,this.unsigned)},F.and=function(S){return a(S)||(S=h(S)),p(this.low&S.low,this.high&S.high,this.unsigned)},F.or=function(S){return a(S)||(S=h(S)),p(this.low|S.low,this.high|S.high,this.unsigned)},F.xor=function(S){return a(S)||(S=h(S)),p(this.low^S.low,this.high^S.high,this.unsigned)},F.shiftLeft=function(S){return a(S)&&(S=S.toInt()),(S&=63)===0?this:S<32?p(this.low<<S,this.high<<S|this.low>>>32-S,this.unsigned):p(0,this.low<<S-32,this.unsigned)},F.shl=F.shiftLeft,F.shiftRight=function(S){return a(S)&&(S=S.toInt()),(S&=63)===0?this:S<32?p(this.low>>>S|this.high<<32-S,this.high>>S,this.unsigned):p(this.high>>S-32,this.high>=0?0:-1,this.unsigned)},F.shr=F.shiftRight,F.shiftRightUnsigned=function(S){if(a(S)&&(S=S.toInt()),S&=63,S===0)return this;var D=this.high;if(S<32){var P=this.low;return p(P>>>S|D<<32-S,D>>>S,this.unsigned)}else return S===32?p(D,0,this.unsigned):p(D>>>S-32,0,this.unsigned)},F.shru=F.shiftRightUnsigned,F.shr_u=F.shiftRightUnsigned,F.toSigned=function(){return this.unsigned?p(this.low,this.high,!1):this},F.toUnsigned=function(){return this.unsigned?this:p(this.low,this.high,!0)},F.toBytes=function(S){return S?this.toBytesLE():this.toBytesBE()},F.toBytesLE=function(){var S=this.high,D=this.low;return[D&255,D>>>8&255,D>>>16&255,D>>>24,S&255,S>>>8&255,S>>>16&255,S>>>24]},F.toBytesBE=function(){var S=this.high,D=this.low;return[S>>>24,S>>>16&255,S>>>8&255,S&255,D>>>24,D>>>16&255,D>>>8&255,D&255]},n.fromBytes=function(S,D,P){return P?n.fromBytesLE(S,D):n.fromBytesBE(S,D)},n.fromBytesLE=function(S,D){return new n(S[0]|S[1]<<8|S[2]<<16|S[3]<<24,S[4]|S[5]<<8|S[6]<<16|S[7]<<24,D)},n.fromBytesBE=function(S,D){return new n(S[4]<<24|S[5]<<16|S[6]<<8|S[7],S[0]<<24|S[1]<<16|S[2]<<8|S[3],D)}}),bR=Lt(()=>{}),xR=Lt(()=>{}),vR=Lt((e,t)=>{(function(r,n,a){function s(p){var u=this,d=l();u.next=function(){var h=2091639*u.s0+u.c*23283064365386963e-26;return u.s0=u.s1,u.s1=u.s2,u.s2=h-(u.c=h|0)},u.c=1,u.s0=d(" "),u.s1=d(" "),u.s2=d(" "),u.s0-=d(p),u.s0<0&&(u.s0+=1),u.s1-=d(p),u.s1<0&&(u.s1+=1),u.s2-=d(p),u.s2<0&&(u.s2+=1),d=null}function i(p,u){return u.c=p.c,u.s0=p.s0,u.s1=p.s1,u.s2=p.s2,u}function o(p,u){var d=new s(p),h=u&&u.state,c=d.next;return c.int32=function(){return d.next()*4294967296|0},c.double=function(){return c()+(c()*2097152|0)*11102230246251565e-32},c.quick=c,h&&(typeof h=="object"&&i(h,d),c.state=function(){return i(d,{})}),c}function l(){var p=4022871197,u=function(d){d=String(d);for(var h=0;h<d.length;h++){p+=d.charCodeAt(h);var c=.02519603282416938*p;p=c>>>0,c-=p,c*=p,p=c>>>0,c-=p,p+=c*4294967296}return(p>>>0)*23283064365386963e-26};return u}n&&n.exports?n.exports=o:a&&a.amd?a(function(){return o}):this.alea=o})(e,typeof t=="object"&&t,typeof define=="function"&&define)}),wR=Lt((e,t)=>{(function(r,n,a){function s(l){var p=this,u="";p.x=0,p.y=0,p.z=0,p.w=0,p.next=function(){var h=p.x^p.x<<11;return p.x=p.y,p.y=p.z,p.z=p.w,p.w^=p.w>>>19^h^h>>>8},l===(l|0)?p.x=l:u+=l;for(var d=0;d<u.length+64;d++)p.x^=u.charCodeAt(d)|0,p.next()}function i(l,p){return p.x=l.x,p.y=l.y,p.z=l.z,p.w=l.w,p}function o(l,p){var u=new s(l),d=p&&p.state,h=function(){return(u.next()>>>0)/4294967296};return h.double=function(){do var c=u.next()>>>11,f=(u.next()>>>0)/4294967296,m=(c+f)/(1<<21);while(m===0);return m},h.int32=u.next,h.quick=h,d&&(typeof d=="object"&&i(d,u),h.state=function(){return i(u,{})}),h}n&&n.exports?n.exports=o:a&&a.amd?a(function(){return o}):this.xor128=o})(e,typeof t=="object"&&t,typeof define=="function"&&define)}),kR=Lt((e,t)=>{(function(r,n,a){function s(l){var p=this,u="";p.next=function(){var h=p.x^p.x>>>2;return p.x=p.y,p.y=p.z,p.z=p.w,p.w=p.v,(p.d=p.d+362437|0)+(p.v=p.v^p.v<<4^(h^h<<1))|0},p.x=0,p.y=0,p.z=0,p.w=0,p.v=0,l===(l|0)?p.x=l:u+=l;for(var d=0;d<u.length+64;d++)p.x^=u.charCodeAt(d)|0,d==u.length&&(p.d=p.x<<10^p.x>>>4),p.next()}function i(l,p){return p.x=l.x,p.y=l.y,p.z=l.z,p.w=l.w,p.v=l.v,p.d=l.d,p}function o(l,p){var u=new s(l),d=p&&p.state,h=function(){return(u.next()>>>0)/4294967296};return h.double=function(){do var c=u.next()>>>11,f=(u.next()>>>0)/4294967296,m=(c+f)/(1<<21);while(m===0);return m},h.int32=u.next,h.quick=h,d&&(typeof d=="object"&&i(d,u),h.state=function(){return i(u,{})}),h}n&&n.exports?n.exports=o:a&&a.amd?a(function(){return o}):this.xorwow=o})(e,typeof t=="object"&&t,typeof define=="function"&&define)}),IR=Lt((e,t)=>{(function(r,n,a){function s(l){var p=this;p.next=function(){var d=p.x,h=p.i,c,f;return c=d[h],c^=c>>>7,f=c^c<<24,c=d[h+1&7],f^=c^c>>>10,c=d[h+3&7],f^=c^c>>>3,c=d[h+4&7],f^=c^c<<7,c=d[h+7&7],c=c^c<<13,f^=c^c<<9,d[h]=f,p.i=h+1&7,f};function u(d,h){var c,f=[];if(h===(h|0))f[0]=h;else for(h=""+h,c=0;c<h.length;++c)f[c&7]=f[c&7]<<15^h.charCodeAt(c)+f[c+1&7]<<13;for(;f.length<8;)f.push(0);for(c=0;c<8&&f[c]===0;++c);for(c==8?f[7]=-1:f[c],d.x=f,d.i=0,c=256;c>0;--c)d.next()}u(p,l)}function i(l,p){return p.x=l.x.slice(),p.i=l.i,p}function o(l,p){l==null&&(l=+new Date);var u=new s(l),d=p&&p.state,h=function(){return(u.next()>>>0)/4294967296};return h.double=function(){do var c=u.next()>>>11,f=(u.next()>>>0)/4294967296,m=(c+f)/(1<<21);while(m===0);return m},h.int32=u.next,h.quick=h,d&&(d.x&&i(d,u),h.state=function(){return i(u,{})}),h}n&&n.exports?n.exports=o:a&&a.amd?a(function(){return o}):this.xorshift7=o})(e,typeof t=="object"&&t,typeof define=="function"&&define)}),SR=Lt((e,t)=>{(function(r,n,a){function s(l){var p=this;p.next=function(){var d=p.w,h=p.X,c=p.i,f,m;return p.w=d=d+1640531527|0,m=h[c+34&127],f=h[c=c+1&127],m^=m<<13,f^=f<<17,m^=m>>>15,f^=f>>>12,m=h[c]=m^f,p.i=c,m+(d^d>>>16)|0};function u(d,h){var c,f,m,g,y,b=[],x=128;for(h===(h|0)?(f=h,h=null):(h=h+"\0",f=0,x=Math.max(x,h.length)),m=0,g=-32;g<x;++g)h&&(f^=h.charCodeAt((g+32)%h.length)),g===0&&(y=f),f^=f<<10,f^=f>>>15,f^=f<<4,f^=f>>>13,g>=0&&(y=y+1640531527|0,c=b[g&127]^=f+y,m=c==0?m+1:0);for(m>=128&&(b[(h&&h.length||0)&127]=-1),m=127,g=4*128;g>0;--g)f=b[m+34&127],c=b[m=m+1&127],f^=f<<13,c^=c<<17,f^=f>>>15,c^=c>>>12,b[m]=f^c;d.w=y,d.X=b,d.i=m}u(p,l)}function i(l,p){return p.i=l.i,p.w=l.w,p.X=l.X.slice(),p}function o(l,p){l==null&&(l=+new Date);var u=new s(l),d=p&&p.state,h=function(){return(u.next()>>>0)/4294967296};return h.double=function(){do var c=u.next()>>>11,f=(u.next()>>>0)/4294967296,m=(c+f)/(1<<21);while(m===0);return m},h.int32=u.next,h.quick=h,d&&(d.X&&i(d,u),h.state=function(){return i(u,{})}),h}n&&n.exports?n.exports=o:a&&a.amd?a(function(){return o}):this.xor4096=o})(e,typeof t=="object"&&t,typeof define=="function"&&define)}),NR=Lt((e,t)=>{(function(r,n,a){function s(l){var p=this,u="";p.next=function(){var h=p.b,c=p.c,f=p.d,m=p.a;return h=h<<25^h>>>7^c,c=c-f|0,f=f<<24^f>>>8^m,m=m-h|0,p.b=h=h<<20^h>>>12^c,p.c=c=c-f|0,p.d=f<<16^c>>>16^m,p.a=m-h|0},p.a=0,p.b=0,p.c=-1640531527,p.d=1367130551,l===Math.floor(l)?(p.a=l/4294967296|0,p.b=l|0):u+=l;for(var d=0;d<u.length+20;d++)p.b^=u.charCodeAt(d)|0,p.next()}function i(l,p){return p.a=l.a,p.b=l.b,p.c=l.c,p.d=l.d,p}function o(l,p){var u=new s(l),d=p&&p.state,h=function(){return(u.next()>>>0)/4294967296};return h.double=function(){do var c=u.next()>>>11,f=(u.next()>>>0)/4294967296,m=(c+f)/(1<<21);while(m===0);return m},h.int32=u.next,h.quick=h,d&&(typeof d=="object"&&i(d,u),h.state=function(){return i(u,{})}),h}n&&n.exports?n.exports=o:a&&a.amd?a(function(){return o}):this.tychei=o})(e,typeof t=="object"&&t,typeof define=="function"&&define)}),_R=Lt(()=>{}),TR=Lt((e,t)=>{(function(r,n,a){var s=256,i=6,o=52,l="random",p=a.pow(s,i),u=a.pow(2,o),d=u*2,h=s-1,c;function f(w,N,T){var E=[];N=N==!0?{entropy:!0}:N||{};var $=b(y(N.entropy?[w,v(n)]:w??x(),3),E),R=new m(E),F=function(){for(var S=R.g(i),D=p,P=0;S<u;)S=(S+P)*s,D*=s,P=R.g(1);for(;S>=d;)S/=2,D/=2,P>>>=1;return(S+P)/D};return F.int32=function(){return R.g(4)|0},F.quick=function(){return R.g(4)/4294967296},F.double=F,b(v(R.S),n),(N.pass||T||function(S,D,P,U){return U&&(U.S&&g(U,R),S.state=function(){return g(R,{})}),P?(a[l]=S,D):S})(F,$,"global"in N?N.global:this==a,N.state)}function m(w){var N,T=w.length,E=this,$=0,R=E.i=E.j=0,F=E.S=[];for(T||(w=[T++]);$<s;)F[$]=$++;for($=0;$<s;$++)F[$]=F[R=h&R+w[$%T]+(N=F[$])],F[R]=N;(E.g=function(S){for(var D,P=0,U=E.i,H=E.j,q=E.S;S--;)D=q[U=h&U+1],P=P*s+q[h&(q[U]=q[H=h&H+D])+(q[H]=D)];return E.i=U,E.j=H,P})(s)}function g(w,N){return N.i=w.i,N.j=w.j,N.S=w.S.slice(),N}function y(w,N){var T=[],E=typeof w,$;if(N&&E=="object")for($ in w)try{T.push(y(w[$],N-1))}catch{}return T.length?T:E=="string"?w:w+"\0"}function b(w,N){for(var T=w+"",E,$=0;$<T.length;)N[h&$]=h&(E^=N[h&$]*19)+T.charCodeAt($++);return v(N)}function x(){try{var w;return c&&(w=c.randomBytes)?w=w(s):(w=new Uint8Array(s),(r.crypto||r.msCrypto).getRandomValues(w)),v(w)}catch{var N=r.navigator,T=N&&N.plugins;return[+new Date,r,T,r.screen,v(n)]}}function v(w){return String.fromCharCode.apply(0,w)}if(b(a.random(),n),typeof t=="object"&&t.exports){t.exports=f;try{c=_R()}catch{}}else typeof define=="function"&&define.amd?define(function(){return f}):a["seed"+l]=f})(typeof self<"u"?self:e,[],Math)}),Kc=Lt((e,t)=>{var r=vR(),n=wR(),a=kR(),s=IR(),i=SR(),o=NR(),l=TR();l.alea=r,l.xor128=n,l.xorwow=a,l.xorshift7=s,l.xor4096=i,l.tychei=o,t.exports=l}),Nk=Lt(()=>{}),Ny=Lt(()=>{}),_k=Lt(()=>{}),CR=Lt(()=>{}),ER=Lt(()=>{}),$R=Lt(()=>{}),AR=Lt((e,t)=>{var r=(()=>{var n=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename<"u"&&(n=n||__filename),function(a){a=a||{};function s(){return G.buffer!=he&&Ge(G.buffer),Ie}function i(){return G.buffer!=he&&Ge(G.buffer),_e}function o(){return G.buffer!=he&&Ge(G.buffer),Fe}function l(){return G.buffer!=he&&Ge(G.buffer),Pe}function p(){return G.buffer!=he&&Ge(G.buffer),st}var u=typeof a<"u"?a:{},d,h;u.ready=new Promise(function(M,K){d=M,h=K});var c;typeof process<"u"&&process.listeners&&(c={uncaughtException:process.listeners("uncaughtException"),unhandledRejection:process.listeners("unhandledRejection")});var f=Object.assign({},u),m=(M,K)=>{throw K},g=typeof window=="object",y=typeof importScripts=="function",b=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",x=u.ENVIRONMENT_IS_PTHREAD||!1,v="";function w(M){return u.locateFile?u.locateFile(M,v):v+M}var N,T,E;function $(M){M instanceof xa||U("exiting due to exception: "+M)}if(b){var R=Ny(),F=_k();y?v=F.dirname(v)+"/":v=__dirname+"/",N=(K,le)=>(K=Va(K)?new URL(K):F.normalize(K),R.readFileSync(K,le?void 0:"utf8")),E=K=>{var le=N(K,!0);return le.buffer||(le=new Uint8Array(le)),le},T=(K,le,Ne)=>{K=Va(K)?new URL(K):F.normalize(K),R.readFile(K,function(Ae,De){Ae?Ne(Ae):le(De.buffer)})},process.argv.length>1&&process.argv[1].replace(/\\/g,"/"),process.argv.slice(2),process.on("uncaughtException",function(K){if(!(K instanceof xa))throw K}),process.on("unhandledRejection",function(K){throw K}),m=(K,le)=>{if(_t())throw process.exitCode=K,le;$(le),process.exit(K)},u.inspect=function(){return"[Emscripten Module object]"};let M;try{M=CR()}catch(K){throw console.error('The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?'),K}global.Worker=M.Worker}else(g||y)&&(y?v=self.location.href:typeof document<"u"&&document.currentScript&&(v=document.currentScript.src),typeof n<"u"&&n&&(v=n),v.indexOf("blob:")!==0?v=v.substr(0,v.replace(/[?#].*/,"").lastIndexOf("/")+1):v="",b||(N=M=>{var K=new XMLHttpRequest;return K.open("GET",M,!1),K.send(null),K.responseText},y&&(E=M=>{var K=new XMLHttpRequest;return K.open("GET",M,!1),K.responseType="arraybuffer",K.send(null),new Uint8Array(K.response)}),T=(M,K,le)=>{var Ne=new XMLHttpRequest;Ne.open("GET",M,!0),Ne.responseType="arraybuffer",Ne.onload=()=>{if(Ne.status==200||Ne.status==0&&Ne.response){K(Ne.response);return}le()},Ne.onerror=le,Ne.send(null)}));b&&typeof performance>"u"&&(global.performance=ER().performance);var S=console.log.bind(console),D=console.warn.bind(console);b&&(S=M=>R.writeSync(1,M+`
`),D=M=>R.writeSync(2,M+`
`));var P=u.print||S,U=u.printErr||D;Object.assign(u,f),f=null,u.arguments&&u.arguments,u.thisProgram&&u.thisProgram,u.quit&&(m=u.quit);var H;u.wasmBinary&&(H=u.wasmBinary);var q=u.noExitRuntime||!0;typeof WebAssembly!="object"&&ba("no native wasm support detected");var G,Z,ee=!1,X;function re(M,K){M||ba(K)}var te=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0;function ae(M,K,le){K>>>=0;for(var Ne=K+le,Ae=K;M[Ae]&&!(Ae>=Ne);)++Ae;if(Ae-K>16&&M.buffer&&te)return te.decode(M.buffer instanceof SharedArrayBuffer?M.slice(K,Ae):M.subarray(K,Ae));for(var De="";K<Ae;){var me=M[K++];if(!(me&128)){De+=String.fromCharCode(me);continue}var ke=M[K++]&63;if((me&224)==192){De+=String.fromCharCode((me&31)<<6|ke);continue}var wt=M[K++]&63;if((me&240)==224?me=(me&15)<<12|ke<<6|wt:me=(me&7)<<18|ke<<12|wt<<6|M[K++]&63,me<65536)De+=String.fromCharCode(me);else{var tn=me-65536;De+=String.fromCharCode(55296|tn>>10,56320|tn&1023)}}return De}function ie(M,K){return M>>>=0,M?ae(i(),M,K):""}function ve(M,K,le,Ne){if(le>>>=0,!(Ne>0))return 0;for(var Ae=le,De=le+Ne-1,me=0;me<M.length;++me){var ke=M.charCodeAt(me);if(ke>=55296&&ke<=57343){var wt=M.charCodeAt(++me);ke=65536+((ke&1023)<<10)|wt&1023}if(ke<=127){if(le>=De)break;K[le++>>>0]=ke}else if(ke<=2047){if(le+1>=De)break;K[le++>>>0]=192|ke>>6,K[le++>>>0]=128|ke&63}else if(ke<=65535){if(le+2>=De)break;K[le++>>>0]=224|ke>>12,K[le++>>>0]=128|ke>>6&63,K[le++>>>0]=128|ke&63}else{if(le+3>=De)break;K[le++>>>0]=240|ke>>18,K[le++>>>0]=128|ke>>12&63,K[le++>>>0]=128|ke>>6&63,K[le++>>>0]=128|ke&63}}return K[le>>>0]=0,le-Ae}function be(M,K,le){return ve(M,i(),K,le)}var he,Ie,_e,Fe,Pe,st;x&&(he=u.buffer);function Ge(M){he=M,u.HEAP8=Ie=new Int8Array(M),u.HEAP16=new Int16Array(M),u.HEAP32=Fe=new Int32Array(M),u.HEAPU8=_e=new Uint8Array(M),u.HEAPU16=new Uint16Array(M),u.HEAPU32=Pe=new Uint32Array(M),u.HEAPF32=new Float32Array(M),u.HEAPF64=st=new Float64Array(M)}var qe=u.INITIAL_MEMORY||16777216;if(x)G=u.wasmMemory,he=u.buffer;else if(u.wasmMemory)G=u.wasmMemory;else if(G=new WebAssembly.Memory({initial:qe/65536,maximum:65536,shared:!0}),!(G.buffer instanceof SharedArrayBuffer))throw U("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"),b&&U("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and/or recent version)"),Error("bad memory");G&&(he=G.buffer),qe=he.byteLength,Ge(he);var $e,Je=[],ht=[],Lr=[];function _t(){return q}function Nr(){if(u.preRun)for(typeof u.preRun=="function"&&(u.preRun=[u.preRun]);u.preRun.length;)yn(u.preRun.shift());ct(Je)}function tr(){!x&&ct(ht)}function _r(){if(!x){if(u.postRun)for(typeof u.postRun=="function"&&(u.postRun=[u.postRun]);u.postRun.length;)Tr(u.postRun.shift());ct(Lr)}}function yn(M){Je.unshift(M)}function zr(M){ht.unshift(M)}function Tr(M){Lr.unshift(M)}var rr=0,Qr=null;function Ua(M){rr++,u.monitorRunDependencies&&u.monitorRunDependencies(rr)}function yp(M){if(rr--,u.monitorRunDependencies&&u.monitorRunDependencies(rr),rr==0&&Qr){var K=Qr;Qr=null,K()}}function ba(M){u.onAbort&&u.onAbort(M),M="Aborted("+M+")",U(M),ee=!0,X=1,M+=". Build with -sASSERTIONS for more info.";var K=new WebAssembly.RuntimeError(M);throw h(K),K}var bp="data:application/octet-stream;base64,";function Kn(M){return M.startsWith(bp)}function Va(M){return M.startsWith("file://")}var nr;nr="tfjs-backend-wasm-threaded-simd.wasm",Kn(nr)||(nr=w(nr));function mh(M){try{if(M==nr&&H)return new Uint8Array(H);if(E)return E(M);throw"both async and sync fetching of the wasm failed"}catch(K){ba(K)}}function gh(){if(!H&&(g||y)){if(typeof fetch=="function"&&!Va(nr))return fetch(nr,{credentials:"same-origin"}).then(function(M){if(!M.ok)throw"failed to load wasm binary file at '"+nr+"'";return M.arrayBuffer()}).catch(function(){return mh(nr)});if(T)return new Promise(function(M,K){T(nr,function(le){M(new Uint8Array(le))},K)})}return Promise.resolve().then(function(){return mh(nr)})}function yh(){var M={env:Ww,wasi_snapshot_preview1:Ww};function K(me,ke){var wt=me.exports;if(u.asm=wt,va(u.asm._emscripten_tls_init),$e=u.asm.__indirect_function_table,zr(u.asm.__wasm_call_ctors),Z=ke,!x){var tn=ce.unusedWorkers.length;ce.unusedWorkers.forEach(function(wa){ce.loadWasmModuleToWorker(wa,function(){--tn||yp()})})}}x||Ua();function le(me){K(me.instance,me.module)}function Ne(me){return gh().then(function(ke){return WebAssembly.instantiate(ke,M)}).then(function(ke){return ke}).then(me,function(ke){U("failed to asynchronously prepare wasm: "+ke),ba(ke)})}function Ae(){return!H&&typeof WebAssembly.instantiateStreaming=="function"&&!Kn(nr)&&!Va(nr)&&!b&&typeof fetch=="function"?fetch(nr,{credentials:"same-origin"}).then(function(me){var ke=WebAssembly.instantiateStreaming(me,M);return ke.then(le,function(wt){return U("wasm streaming compile failed: "+wt),U("falling back to ArrayBuffer instantiation"),Ne(le)})}):Ne(le)}if(u.instantiateWasm)try{var De=u.instantiateWasm(M,K);return De}catch(me){U("Module.instantiateWasm callback failed with error: "+me),h(me)}return Ae().catch(h),{}}var bh={};function xa(M){this.name="ExitStatus",this.message="Program terminated with exit("+M+")",this.status=M}function ol(M){var K=ce.pthreads[M];delete ce.pthreads[M],K.terminate(),Tm(M),ce.runningWorkers.splice(ce.runningWorkers.indexOf(K),1),K.pthread_ptr=0}function xh(M){var K=ce.pthreads[M];K.postMessage({cmd:"cancel"})}function Vs(M){var K=ce.pthreads[M];re(K),ce.returnWorkerToPool(K)}function Gs(M){var K=ce.getNewWorker();if(!K)return 6;ce.runningWorkers.push(K),ce.pthreads[M.pthread_ptr]=K,K.pthread_ptr=M.pthread_ptr;var le={cmd:"run",start_routine:M.startRoutine,arg:M.arg,pthread_ptr:M.pthread_ptr};return K.runPthread=()=>{b&&K.ref(),K.postMessage(le,M.transferList),delete K.runPthread},K.loaded&&K.runPthread(),0}function vh(M){if(x)return ll(1,1,M);X=M,_t()||(ce.terminateAllThreads(),u.onExit&&u.onExit(M),ee=!0),m(M,new xa(M))}function Q(M,K){if(X=M,!K&&x)throw Ue(M),"unwind";vh(M)}var oe=Q;function Se(M){if(M instanceof xa||M=="unwind")return X;m(1,M)}var ce={unusedWorkers:[],runningWorkers:[],tlsInitFunctions:[],pthreads:{},init:function(){x?ce.initWorker():ce.initMainThread()},initMainThread:function(){for(var M=8;M--;)ce.allocateUnusedWorker()},initWorker:function(){q=!1},setExitStatus:function(M){X=M},terminateAllThreads:function(){for(var M of Object.values(ce.pthreads))ce.returnWorkerToPool(M);for(var M of ce.unusedWorkers)M.terminate();ce.unusedWorkers=[]},returnWorkerToPool:function(M){var K=M.pthread_ptr;delete ce.pthreads[K],ce.unusedWorkers.push(M),ce.runningWorkers.splice(ce.runningWorkers.indexOf(M),1),M.pthread_ptr=0,b&&M.unref(),Tm(K)},receiveObjectTransfer:function(M){},threadInitTLS:function(){ce.tlsInitFunctions.forEach(M=>M())},loadWasmModuleToWorker:function(M,K){M.onmessage=De=>{var me=De.data,ke=me.cmd;if(M.pthread_ptr&&(ce.currentProxiedOperationCallerThread=M.pthread_ptr),me.targetThread&&me.targetThread!=Sh()){var wt=ce.pthreads[me.targetThread];wt?wt.postMessage(me,me.transferList):U('Internal error! Worker sent a message "'+ke+'" to target pthread '+me.targetThread+", but that thread no longer exists!"),ce.currentProxiedOperationCallerThread=void 0;return}ke==="processProxyingQueue"?Sm(me.queue):ke==="spawnThread"?Gs(me):ke==="cleanupThread"?Vs(me.thread):ke==="killThread"?ol(me.thread):ke==="cancelThread"?xh(me.thread):ke==="loaded"?(M.loaded=!0,b&&M.unref(),K&&K(M),M.runPthread&&M.runPthread()):ke==="print"?P("Thread "+me.threadId+": "+me.text):ke==="printErr"?U("Thread "+me.threadId+": "+me.text):ke==="alert"?alert("Thread "+me.threadId+": "+me.text):me.target==="setimmediate"?M.postMessage(me):ke==="callHandler"?u[me.handler](...me.args):ke&&U("worker sent an unknown command "+ke),ce.currentProxiedOperationCallerThread=void 0},M.onerror=De=>{var me="worker sent an error!";throw U(me+" "+De.filename+":"+De.lineno+": "+De.message),De},b&&(M.on("message",function(De){M.onmessage({data:De})}),M.on("error",function(De){M.onerror(De)}),M.on("detachedExit",function(){}));var le=[],Ne=["onExit","onAbort","print","printErr"];for(var Ae of Ne)u.hasOwnProperty(Ae)&&le.push(Ae);M.postMessage({cmd:"load",handlers:le,urlOrBlob:u.mainScriptUrlOrBlob||n,wasmMemory:G,wasmModule:Z})},allocateUnusedWorker:function(){var M,K=w("tfjs-backend-wasm-threaded-simd.worker.js");M=new Worker(K),ce.unusedWorkers.push(M)},getNewWorker:function(){return ce.unusedWorkers.length==0&&(ce.allocateUnusedWorker(),ce.loadWasmModuleToWorker(ce.unusedWorkers[0])),ce.unusedWorkers.pop()}};u.PThread=ce;function ct(M){for(;M.length>0;)M.shift()(u)}function bt(){var M=Sh(),K=o()[M+52>>>2],le=o()[M+56>>>2],Ne=K-le;jw(K,Ne),Nh(K)}u.establishStackSpace=bt;function Ue(M){if(x)return ll(2,0,M);try{oe(M)}catch(K){Se(K)}}var Re=[];function $t(M){var K=Re[M];return K||(M>=Re.length&&(Re.length=M+1),Re[M]=K=$e.get(M)),K}function en(M,K){var le=$t(M)(K);_t()?ce.setExitStatus(le):Hw(le)}u.invokeEntryPoint=en;function va(M){ce.tlsInitFunctions.push(M)}function wh(M){Uw(M,!y,1,!g),ce.threadInitTLS()}function xp(M){x?postMessage({cmd:"cleanupThread",thread:M}):Vs(M)}function kh(M,K,le,Ne){return x?ll(3,1,M,K,le,Ne):cr(M,K,le,Ne)}function cr(M,K,le,Ne){if(typeof SharedArrayBuffer>"u")return U("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var Ae=[],De=0;if(x&&(Ae.length===0||De))return kh(M,K,le,Ne);var me={startRoutine:le,pthread_ptr:M,arg:Ne,transferList:Ae};return x?(me.cmd="spawnThread",postMessage(me,Ae),0):Gs(me)}function Ga(){return 65536}var Ih=!0;function IA(){return Ih}function Sm(M){Atomics.store(o(),M>>2,1),Sh()&&Gw(M),Atomics.compareExchange(o(),M>>2,1,0)}u.executeNotifiedProxyingQueue=Sm;function SA(M,K,le,Ne){if(M==K)setTimeout(()=>Sm(Ne));else if(x)postMessage({targetThread:M,cmd:"processProxyingQueue",queue:Ne});else{var Ae=ce.pthreads[M];if(!Ae)return;Ae.postMessage({cmd:"processProxyingQueue",queue:Ne})}return 1}function NA(M,K,le){return-1}function _A(){ba("")}function vp(M){vp.shown||(vp.shown={}),vp.shown[M]||(vp.shown[M]=1,b&&(M="warning: "+M),U(M))}function TA(){b||y||vp("Blocking on the main thread is very dangerous, see https://emscripten.org/docs/porting/pthreads.html#blocking-on-the-main-browser-thread")}function CA(){return Date.now()}function Ow(){return 4294901760}function EA(){return Ow()}var Nm;b?Nm=()=>{var M=process.hrtime();return M[0]*1e3+M[1]/1e6}:Nm=()=>performance.timeOrigin+performance.now();function $A(M,K,le){i().copyWithin(M>>>0,K>>>0,K+le>>>0)}function AA(){return b?$R().cpus().length:navigator.hardwareConcurrency}function FA(M){var K=Cm(),le=M();return Nh(K),le}function ll(M,K){var le=arguments.length-2,Ne=arguments;return FA(()=>{for(var Ae=le,De=_h(Ae*8),me=De>>3,ke=0;ke<le;ke++){var wt=Ne[2+ke];p()[me+ke>>>0]=wt}return Vw(M,Ae,De,K)})}var _m=[];function RA(M,K,le){_m.length=K;for(var Ne=le>>3,Ae=0;Ae<K;Ae++)_m[Ae]=p()[Ne+Ae>>>0];var De=M<0,me=De?bh[-M-1]:UA[M];return me.apply(null,_m)}function DA(M){try{return G.grow(M-he.byteLength+65535>>>16),Ge(G.buffer),1}catch{}}function MA(M){var K=i().length;if(M=M>>>0,M<=K)return!1;var le=Ow();if(M>le)return!1;let Ne=(wt,tn)=>wt+(tn-wt%tn)%tn;for(var Ae=1;Ae<=4;Ae*=2){var De=K*(1+.2/Ae);De=Math.min(De,M+100663296);var me=Math.min(le,Ne(Math.max(M,De),65536)),ke=DA(me);if(ke)return!0}return!1}function OA(){throw"unwind"}function Lw(M){return x?ll(4,1,M):52}function zw(M,K,le,Ne,Ae){return x?ll(5,1,M,K,le,Ne,Ae):70}var LA=[null,[],[]];function zA(M,K){var le=LA[M];K===0||K===10?((M===1?P:U)(ae(le,0)),le.length=0):le.push(K)}function Pw(M,K,le,Ne){if(x)return ll(6,1,M,K,le,Ne);for(var Ae=0,De=0;De<le;De++){var me=l()[K>>>2],ke=l()[K+4>>>2];K+=8;for(var wt=0;wt<ke;wt++)zA(M,i()[me+wt>>>0]);Ae+=ke}return l()[Ne>>>2]=Ae,0}function Bw(M){var K=u["_"+M];return K}function PA(M,K){s().set(M,K>>>0)}function BA(M,K,le,Ne,Ae){var De={string:rn=>{var ul=0;if(rn!=null&&rn!==0){var Xw=(rn.length<<2)+1;ul=_h(Xw),be(rn,ul,Xw)}return ul},array:rn=>{var ul=_h(rn.length);return PA(rn,ul),ul}};function me(rn){return K==="string"?ie(rn):K==="boolean"?!!rn:rn}var ke=Bw(M),wt=[],tn=0;if(Ne)for(var wa=0;wa<Ne.length;wa++){var Kw=De[le[wa]];Kw?(tn===0&&(tn=Cm()),wt[wa]=Kw(Ne[wa])):wt[wa]=Ne[wa]}var Em=ke.apply(null,wt);function GA(rn){return tn!==0&&Nh(tn),me(rn)}return Em=GA(Em),Em}function WA(M,K,le,Ne){le=le||[];var Ae=le.every(me=>me==="number"||me==="boolean"),De=K!=="string";return De&&Ae&&!Ne?Bw(M):function(){return BA(M,K,le,arguments)}}ce.init();var UA=[null,vh,Ue,kh,Lw,zw,Pw],Ww={__emscripten_init_main_thread_js:wh,__emscripten_thread_cleanup:xp,__pthread_create_js:cr,_emscripten_default_pthread_stack_size:Ga,_emscripten_get_now_is_monotonic:IA,_emscripten_notify_task_queue:SA,_emscripten_set_offscreencanvas_size:NA,abort:_A,emscripten_check_blocking_allowed:TA,emscripten_date_now:CA,emscripten_get_heap_max:EA,emscripten_get_now:Nm,emscripten_memcpy_big:$A,emscripten_num_logical_cores:AA,emscripten_receive_on_main_thread_js:RA,emscripten_resize_heap:MA,emscripten_unwind_to_js_event_loop:OA,exit:oe,fd_close:Lw,fd_seek:zw,fd_write:Pw,memory:G||u.wasmMemory};yh(),u.___wasm_call_ctors=function(){return(u.___wasm_call_ctors=u.asm.__wasm_call_ctors).apply(null,arguments)},u._init=function(){return(u._init=u.asm.init).apply(null,arguments)},u._init_with_threads_count=function(){return(u._init_with_threads_count=u.asm.init_with_threads_count).apply(null,arguments)},u._get_threads_count=function(){return(u._get_threads_count=u.asm.get_threads_count).apply(null,arguments)},u._register_tensor=function(){return(u._register_tensor=u.asm.register_tensor).apply(null,arguments)},u._dispose_data=function(){return(u._dispose_data=u.asm.dispose_data).apply(null,arguments)},u._dispose=function(){return(u._dispose=u.asm.dispose).apply(null,arguments)},u._Abs=function(){return(u._Abs=u.asm.Abs).apply(null,arguments)},u._Acos=function(){return(u._Acos=u.asm.Acos).apply(null,arguments)},u._Acosh=function(){return(u._Acosh=u.asm.Acosh).apply(null,arguments)},u._Add=function(){return(u._Add=u.asm.Add).apply(null,arguments)},u._AddN=function(){return(u._AddN=u.asm.AddN).apply(null,arguments)},u._All=function(){return(u._All=u.asm.All).apply(null,arguments)},u._Any=function(){return(u._Any=u.asm.Any).apply(null,arguments)},u._ArgMax=function(){return(u._ArgMax=u.asm.ArgMax).apply(null,arguments)},u._ArgMin=function(){return(u._ArgMin=u.asm.ArgMin).apply(null,arguments)},u._Asin=function(){return(u._Asin=u.asm.Asin).apply(null,arguments)},u._Asinh=function(){return(u._Asinh=u.asm.Asinh).apply(null,arguments)},u._Atan=function(){return(u._Atan=u.asm.Atan).apply(null,arguments)},u._Atan2=function(){return(u._Atan2=u.asm.Atan2).apply(null,arguments)},u._Atanh=function(){return(u._Atanh=u.asm.Atanh).apply(null,arguments)},u._AvgPool=function(){return(u._AvgPool=u.asm.AvgPool).apply(null,arguments)},u._AvgPool3D=function(){return(u._AvgPool3D=u.asm.AvgPool3D).apply(null,arguments)},u._AvgPool3DGrad=function(){return(u._AvgPool3DGrad=u.asm.AvgPool3DGrad).apply(null,arguments)},u._AvgPoolGrad=function(){return(u._AvgPoolGrad=u.asm.AvgPoolGrad).apply(null,arguments)},u._BatchMatMul=function(){return(u._BatchMatMul=u.asm.BatchMatMul).apply(null,arguments)},u._Bincount=function(){return(u._Bincount=u.asm.Bincount).apply(null,arguments)},u._BitwiseAnd=function(){return(u._BitwiseAnd=u.asm.BitwiseAnd).apply(null,arguments)},u._Ceil=function(){return(u._Ceil=u.asm.Ceil).apply(null,arguments)},u._ClipByValue=function(){return(u._ClipByValue=u.asm.ClipByValue).apply(null,arguments)},u._Conv2D=function(){return(u._Conv2D=u.asm.Conv2D).apply(null,arguments)},u._Conv2DBackpropInput=function(){return(u._Conv2DBackpropInput=u.asm.Conv2DBackpropInput).apply(null,arguments)},u._Conv3D=function(){return(u._Conv3D=u.asm.Conv3D).apply(null,arguments)},u._Conv3DBackpropFilterV2=function(){return(u._Conv3DBackpropFilterV2=u.asm.Conv3DBackpropFilterV2).apply(null,arguments)},u._Conv3DBackpropInputV2=function(){return(u._Conv3DBackpropInputV2=u.asm.Conv3DBackpropInputV2).apply(null,arguments)},u._Cos=function(){return(u._Cos=u.asm.Cos).apply(null,arguments)},u._Cosh=function(){return(u._Cosh=u.asm.Cosh).apply(null,arguments)},u._CropAndResize=function(){return(u._CropAndResize=u.asm.CropAndResize).apply(null,arguments)},u._Cumprod=function(){return(u._Cumprod=u.asm.Cumprod).apply(null,arguments)},u._Cumsum=function(){return(u._Cumsum=u.asm.Cumsum).apply(null,arguments)},u._DenseBincount=function(){return(u._DenseBincount=u.asm.DenseBincount).apply(null,arguments)},u._DepthToSpace=function(){return(u._DepthToSpace=u.asm.DepthToSpace).apply(null,arguments)},u._DepthwiseConv2dNative=function(){return(u._DepthwiseConv2dNative=u.asm.DepthwiseConv2dNative).apply(null,arguments)},u._Diag=function(){return(u._Diag=u.asm.Diag).apply(null,arguments)},u._Dilation2D=function(){return(u._Dilation2D=u.asm.Dilation2D).apply(null,arguments)},u._Dilation2DBackpropFilter=function(){return(u._Dilation2DBackpropFilter=u.asm.Dilation2DBackpropFilter).apply(null,arguments)},u._Dilation2DBackpropInput=function(){return(u._Dilation2DBackpropInput=u.asm.Dilation2DBackpropInput).apply(null,arguments)},u._Elu=function(){return(u._Elu=u.asm.Elu).apply(null,arguments)},u._EluGrad=function(){return(u._EluGrad=u.asm.EluGrad).apply(null,arguments)},u._Equal=function(){return(u._Equal=u.asm.Equal).apply(null,arguments)},u._Erf=function(){return(u._Erf=u.asm.Erf).apply(null,arguments)},u._Exp=function(){return(u._Exp=u.asm.Exp).apply(null,arguments)},u._Expm1=function(){return(u._Expm1=u.asm.Expm1).apply(null,arguments)},u._FlipLeftRight=function(){return(u._FlipLeftRight=u.asm.FlipLeftRight).apply(null,arguments)},u._Floor=function(){return(u._Floor=u.asm.Floor).apply(null,arguments)},u._FloorDiv=function(){return(u._FloorDiv=u.asm.FloorDiv).apply(null,arguments)},u._FusedBatchNorm=function(){return(u._FusedBatchNorm=u.asm.FusedBatchNorm).apply(null,arguments)},u._FusedConv2D=function(){return(u._FusedConv2D=u.asm.FusedConv2D).apply(null,arguments)},u._FusedDepthwiseConv2D=function(){return(u._FusedDepthwiseConv2D=u.asm.FusedDepthwiseConv2D).apply(null,arguments)},u._Gather=function(){return(u._Gather=u.asm.Gather).apply(null,arguments)},u._GatherNd=function(){return(u._GatherNd=u.asm.GatherNd).apply(null,arguments)},u._Greater=function(){return(u._Greater=u.asm.Greater).apply(null,arguments)},u._GreaterEqual=function(){return(u._GreaterEqual=u.asm.GreaterEqual).apply(null,arguments)},u._IsFinite=function(){return(u._IsFinite=u.asm.IsFinite).apply(null,arguments)},u._IsInf=function(){return(u._IsInf=u.asm.IsInf).apply(null,arguments)},u._IsNan=function(){return(u._IsNan=u.asm.IsNan).apply(null,arguments)},u._LRN=function(){return(u._LRN=u.asm.LRN).apply(null,arguments)},u._LRNGrad=function(){return(u._LRNGrad=u.asm.LRNGrad).apply(null,arguments)},u._LeakyRelu=function(){return(u._LeakyRelu=u.asm.LeakyRelu).apply(null,arguments)},u._Less=function(){return(u._Less=u.asm.Less).apply(null,arguments)},u._LessEqual=function(){return(u._LessEqual=u.asm.LessEqual).apply(null,arguments)},u._LinSpace=function(){return(u._LinSpace=u.asm.LinSpace).apply(null,arguments)},u._Log=function(){return(u._Log=u.asm.Log).apply(null,arguments)},u._Log1p=function(){return(u._Log1p=u.asm.Log1p).apply(null,arguments)},u._LogicalAnd=function(){return(u._LogicalAnd=u.asm.LogicalAnd).apply(null,arguments)},u._LogicalNot=function(){return(u._LogicalNot=u.asm.LogicalNot).apply(null,arguments)},u._LogicalOr=function(){return(u._LogicalOr=u.asm.LogicalOr).apply(null,arguments)},u._LogicalXor=function(){return(u._LogicalXor=u.asm.LogicalXor).apply(null,arguments)},u._Max=function(){return(u._Max=u.asm.Max).apply(null,arguments)},u._MaxPool=function(){return(u._MaxPool=u.asm.MaxPool).apply(null,arguments)},u._MaxPool3D=function(){return(u._MaxPool3D=u.asm.MaxPool3D).apply(null,arguments)},u._MaxPool3DGrad=function(){return(u._MaxPool3DGrad=u.asm.MaxPool3DGrad).apply(null,arguments)},u._MaxPoolGrad=function(){return(u._MaxPoolGrad=u.asm.MaxPoolGrad).apply(null,arguments)},u._MaxPoolWithArgmax=function(){return(u._MaxPoolWithArgmax=u.asm.MaxPoolWithArgmax).apply(null,arguments)},u._Maximum=function(){return(u._Maximum=u.asm.Maximum).apply(null,arguments)},u._Mean=function(){return(u._Mean=u.asm.Mean).apply(null,arguments)},u._Min=function(){return(u._Min=u.asm.Min).apply(null,arguments)},u._Minimum=function(){return(u._Minimum=u.asm.Minimum).apply(null,arguments)},u._MirrorPad=function(){return(u._MirrorPad=u.asm.MirrorPad).apply(null,arguments)},u._Mod=function(){return(u._Mod=u.asm.Mod).apply(null,arguments)},u._Multinomial=function(){return(u._Multinomial=u.asm.Multinomial).apply(null,arguments)},u._Multiply=function(){return(u._Multiply=u.asm.Multiply).apply(null,arguments)},u._Neg=function(){return(u._Neg=u.asm.Neg).apply(null,arguments)},u._NonMaxSuppressionV3=function(){return(u._NonMaxSuppressionV3=u.asm.NonMaxSuppressionV3).apply(null,arguments)},u._NonMaxSuppressionV4=function(){return(u._NonMaxSuppressionV4=u.asm.NonMaxSuppressionV4).apply(null,arguments)},u._NonMaxSuppressionV5=function(){return(u._NonMaxSuppressionV5=u.asm.NonMaxSuppressionV5).apply(null,arguments)},u._NotEqual=function(){return(u._NotEqual=u.asm.NotEqual).apply(null,arguments)},u._OneHot=function(){return(u._OneHot=u.asm.OneHot).apply(null,arguments)},u._PadV2=function(){return(u._PadV2=u.asm.PadV2).apply(null,arguments)},u._Pow=function(){return(u._Pow=u.asm.Pow).apply(null,arguments)},u._Prelu=function(){return(u._Prelu=u.asm.Prelu).apply(null,arguments)},u._Prod=function(){return(u._Prod=u.asm.Prod).apply(null,arguments)},u._RealDiv=function(){return(u._RealDiv=u.asm.RealDiv).apply(null,arguments)},u._Reciprocal=function(){return(u._Reciprocal=u.asm.Reciprocal).apply(null,arguments)},u._Relu=function(){return(u._Relu=u.asm.Relu).apply(null,arguments)},u._Relu6=function(){return(u._Relu6=u.asm.Relu6).apply(null,arguments)},u._ResizeBilinear=function(){return(u._ResizeBilinear=u.asm.ResizeBilinear).apply(null,arguments)},u._ResizeBilinearGrad=function(){return(u._ResizeBilinearGrad=u.asm.ResizeBilinearGrad).apply(null,arguments)},u._ResizeNearestNeighbor=function(){return(u._ResizeNearestNeighbor=u.asm.ResizeNearestNeighbor).apply(null,arguments)},u._ResizeNearestNeighborGrad=function(){return(u._ResizeNearestNeighborGrad=u.asm.ResizeNearestNeighborGrad).apply(null,arguments)},u._Reverse=function(){return(u._Reverse=u.asm.Reverse).apply(null,arguments)},u._RotateWithOffset=function(){return(u._RotateWithOffset=u.asm.RotateWithOffset).apply(null,arguments)},u._Round=function(){return(u._Round=u.asm.Round).apply(null,arguments)},u._Rsqrt=function(){return(u._Rsqrt=u.asm.Rsqrt).apply(null,arguments)},u._ScatterNd=function(){return(u._ScatterNd=u.asm.ScatterNd).apply(null,arguments)},u._SearchSorted=function(){return(u._SearchSorted=u.asm.SearchSorted).apply(null,arguments)},u._SelectV2=function(){return(u._SelectV2=u.asm.SelectV2).apply(null,arguments)},u._Selu=function(){return(u._Selu=u.asm.Selu).apply(null,arguments)},u._Sigmoid=function(){return(u._Sigmoid=u.asm.Sigmoid).apply(null,arguments)},u._Sign=function(){return(u._Sign=u.asm.Sign).apply(null,arguments)},u._Sin=function(){return(u._Sin=u.asm.Sin).apply(null,arguments)},u._Sinh=function(){return(u._Sinh=u.asm.Sinh).apply(null,arguments)},u._Softmax=function(){return(u._Softmax=u.asm.Softmax).apply(null,arguments)},u._Softplus=function(){return(u._Softplus=u.asm.Softplus).apply(null,arguments)},u._SparseFillEmptyRows=function(){return(u._SparseFillEmptyRows=u.asm.SparseFillEmptyRows).apply(null,arguments)},u._SparseReshape=function(){return(u._SparseReshape=u.asm.SparseReshape).apply(null,arguments)},u._SparseSegmentReduction=function(){return(u._SparseSegmentReduction=u.asm.SparseSegmentReduction).apply(null,arguments)},u._SparseToDense=function(){return(u._SparseToDense=u.asm.SparseToDense).apply(null,arguments)},u._Sqrt=function(){return(u._Sqrt=u.asm.Sqrt).apply(null,arguments)},u._Square=function(){return(u._Square=u.asm.Square).apply(null,arguments)},u._SquaredDifference=function(){return(u._SquaredDifference=u.asm.SquaredDifference).apply(null,arguments)},u._Step=function(){return(u._Step=u.asm.Step).apply(null,arguments)},u._StridedSlice=function(){return(u._StridedSlice=u.asm.StridedSlice).apply(null,arguments)},u._Sub=function(){return(u._Sub=u.asm.Sub).apply(null,arguments)},u._Sum=function(){return(u._Sum=u.asm.Sum).apply(null,arguments)},u._Tan=function(){return(u._Tan=u.asm.Tan).apply(null,arguments)},u._Tanh=function(){return(u._Tanh=u.asm.Tanh).apply(null,arguments)},u._TensorScatterUpdate=function(){return(u._TensorScatterUpdate=u.asm.TensorScatterUpdate).apply(null,arguments)},u._Tile=function(){return(u._Tile=u.asm.Tile).apply(null,arguments)},u._TopK=function(){return(u._TopK=u.asm.TopK).apply(null,arguments)},u._Transform=function(){return(u._Transform=u.asm.Transform).apply(null,arguments)},u._Transpose=function(){return(u._Transpose=u.asm.Transpose).apply(null,arguments)},u.__FusedMatMul=function(){return(u.__FusedMatMul=u.asm._FusedMatMul).apply(null,arguments)},u._malloc=function(){return(u._malloc=u.asm.malloc).apply(null,arguments)},u._free=function(){return(u._free=u.asm.free).apply(null,arguments)},u.__emscripten_tls_init=function(){return(u.__emscripten_tls_init=u.asm._emscripten_tls_init).apply(null,arguments)};var Sh=u._pthread_self=function(){return(Sh=u._pthread_self=u.asm.pthread_self).apply(null,arguments)};u.___errno_location=function(){return(u.___errno_location=u.asm.__errno_location).apply(null,arguments)};var Uw=u.__emscripten_thread_init=function(){return(Uw=u.__emscripten_thread_init=u.asm._emscripten_thread_init).apply(null,arguments)};u.__emscripten_thread_crashed=function(){return(u.__emscripten_thread_crashed=u.asm._emscripten_thread_crashed).apply(null,arguments)},u._emscripten_main_thread_process_queued_calls=function(){return(u._emscripten_main_thread_process_queued_calls=u.asm.emscripten_main_thread_process_queued_calls).apply(null,arguments)},u._emscripten_main_browser_thread_id=function(){return(u._emscripten_main_browser_thread_id=u.asm.emscripten_main_browser_thread_id).apply(null,arguments)};var Vw=u._emscripten_run_in_main_runtime_thread_js=function(){return(Vw=u._emscripten_run_in_main_runtime_thread_js=u.asm.emscripten_run_in_main_runtime_thread_js).apply(null,arguments)};u._emscripten_dispatch_to_thread_=function(){return(u._emscripten_dispatch_to_thread_=u.asm.emscripten_dispatch_to_thread_).apply(null,arguments)};var Gw=u.__emscripten_proxy_execute_task_queue=function(){return(Gw=u.__emscripten_proxy_execute_task_queue=u.asm._emscripten_proxy_execute_task_queue).apply(null,arguments)},Tm=u.__emscripten_thread_free_data=function(){return(Tm=u.__emscripten_thread_free_data=u.asm._emscripten_thread_free_data).apply(null,arguments)},Hw=u.__emscripten_thread_exit=function(){return(Hw=u.__emscripten_thread_exit=u.asm._emscripten_thread_exit).apply(null,arguments)},jw=u._emscripten_stack_set_limits=function(){return(jw=u._emscripten_stack_set_limits=u.asm.emscripten_stack_set_limits).apply(null,arguments)},Cm=u.stackSave=function(){return(Cm=u.stackSave=u.asm.stackSave).apply(null,arguments)},Nh=u.stackRestore=function(){return(Nh=u.stackRestore=u.asm.stackRestore).apply(null,arguments)},_h=u.stackAlloc=function(){return(_h=u.stackAlloc=u.asm.stackAlloc).apply(null,arguments)};u.dynCall_iijjiiii=function(){return(u.dynCall_iijjiiii=u.asm.dynCall_iijjiiii).apply(null,arguments)},u.dynCall_jiji=function(){return(u.dynCall_jiji=u.asm.dynCall_jiji).apply(null,arguments)},u.keepRuntimeAlive=_t,u.wasmMemory=G,u.cwrap=WA,u.ExitStatus=xa,u.PThread=ce;var Th;Qr=function M(){Th||qw(),Th||(Qr=M)};function qw(M){if(rr>0)return;if(x){d(u),tr(),startWorker(u);return}if(Nr(),rr>0)return;function K(){Th||(Th=!0,u.calledRun=!0,!ee&&(tr(),d(u),u.onRuntimeInitialized&&u.onRuntimeInitialized(),_r()))}u.setStatus?(u.setStatus("Running..."),setTimeout(function(){setTimeout(function(){u.setStatus("")},1),K()},1)):K()}if(u.preInit)for(typeof u.preInit=="function"&&(u.preInit=[u.preInit]);u.preInit.length>0;)u.preInit.pop()();qw();var Ch;c&&(Ch={uncaughtException:process.listeners("uncaughtException").filter(function(M){return!c.uncaughtException.indexOf(M)>-1}),unhandledRejection:process.listeners("unhandledRejection").filter(function(M){return!c.unhandledRejection.indexOf(M)>-1})});var Eh;if(typeof WasmBackendModule<"u")Eh=WasmBackendModule;else if(typeof a<"u")Eh=a;else throw new Error("Could not find wasm module in post.js");if(Ch){var VA=Eh._dispose;Eh._dispose=function(){VA(),Ch.uncaughtException.forEach(function(M){process.removeListener("uncaughtException",M)}),Ch.unhandledRejection.forEach(function(M){process.removeListener("unhandledRejection",M)})}}return a.ready}})();typeof e=="object"&&typeof t=="object"?t.exports=r:typeof define=="function"&&define.amd?define([],function(){return r}):typeof e=="object"&&(e.WasmBackendModuleThreadedSimd=r)}),FR=Lt((e,t)=>{t.exports.wasmWorkerContents=`"use strict";var Module={};var ENVIRONMENT_IS_NODE=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string";if(ENVIRONMENT_IS_NODE){var nodeWorkerThreads=require("worker_threads");var parentPort=nodeWorkerThreads.parentPort;parentPort.on("message",data=>onmessage({data:data}));var fs=require("fs");Object.assign(global,{self:global,require:require,Module:Module,location:{href:__filename},Worker:nodeWorkerThreads.Worker,importScripts:function(f){(0,eval)(fs.readFileSync(f,"utf8")+"//# sourceURL="+f)},postMessage:function(msg){parentPort.postMessage(msg)},performance:global.performance||{now:function(){return Date.now()}}})}var initializedJS=false;var pendingNotifiedProxyingQueues=[];function threadPrintErr(){var text=Array.prototype.slice.call(arguments).join(" ");if(ENVIRONMENT_IS_NODE){fs.writeSync(2,text+"
");return}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;self.alert=threadAlert;Module["instantiateWasm"]=(info,receiveInstance)=>{var instance=new WebAssembly.Instance(Module["wasmModule"],info);receiveInstance(instance);Module["wasmModule"]=null;return instance.exports};self.onunhandledrejection=e=>{throw e.reason??e};self.startWorker=instance=>{Module=instance;postMessage({"cmd":"loaded"})};self.onmessage=e=>{try{if(e.data.cmd==="load"){Module["wasmModule"]=e.data.wasmModule;for(const handler of e.data.handlers){Module[handler]=function(){postMessage({cmd:"callHandler",handler:handler,args:[...arguments]})}}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)}else if(e.data.cmd==="run"){Module["__emscripten_thread_init"](e.data.pthread_ptr,0,0,1);Module["establishStackSpace"]();Module["PThread"].receiveObjectTransfer(e.data);Module["PThread"].threadInitTLS();if(!initializedJS){pendingNotifiedProxyingQueues.forEach(queue=>{Module["executeNotifiedProxyingQueue"](queue)});pendingNotifiedProxyingQueues=[];initializedJS=true}try{Module["invokeEntryPoint"](e.data.start_routine,e.data.arg)}catch(ex){if(ex!="unwind"){if(ex instanceof Module["ExitStatus"]){if(Module["keepRuntimeAlive"]()){}else{Module["__emscripten_thread_exit"](ex.status)}}else{throw ex}}}}else if(e.data.cmd==="cancel"){if(Module["_pthread_self"]()){Module["__emscripten_thread_exit"](-1)}}else if(e.data.target==="setimmediate"){}else if(e.data.cmd==="processProxyingQueue"){if(initializedJS){Module["executeNotifiedProxyingQueue"](e.data.queue)}else{pendingNotifiedProxyingQueues.push(e.data.queue)}}else if(e.data.cmd){err("worker.js received unknown command "+e.data.cmd);err(e.data)}}catch(ex){if(Module["__emscripten_thread_crashed"]){Module["__emscripten_thread_crashed"]()}throw ex}};`}),RR=Lt((e,t)=>{var r=(()=>{var n=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename<"u"&&(n=n||__filename),function(a){a=a||{};var s=typeof a<"u"?a:{},i,o;s.ready=new Promise(function(Q,oe){i=Q,o=oe});var l;typeof process<"u"&&process.listeners&&(l={uncaughtException:process.listeners("uncaughtException"),unhandledRejection:process.listeners("unhandledRejection")});var p=Object.assign({},s),u=typeof window=="object",d=typeof importScripts=="function",h=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",c="";function f(Q){return s.locateFile?s.locateFile(Q,c):c+Q}var m,g,y;if(h){var b=Ny(),x=_k();d?c=x.dirname(c)+"/":c=__dirname+"/",m=(Q,oe)=>(Q=qe(Q)?new URL(Q):x.normalize(Q),b.readFileSync(Q,oe?void 0:"utf8")),y=Q=>{var oe=m(Q,!0);return oe.buffer||(oe=new Uint8Array(oe)),oe},g=(Q,oe,Se)=>{Q=qe(Q)?new URL(Q):x.normalize(Q),b.readFile(Q,function(ce,ct){ce?Se(ce):oe(ct.buffer)})},process.argv.length>1&&process.argv[1].replace(/\\/g,"/"),process.argv.slice(2),process.on("uncaughtException",function(Q){if(!(Q instanceof _t))throw Q}),process.on("unhandledRejection",function(Q){throw Q}),s.inspect=function(){return"[Emscripten Module object]"}}else(u||d)&&(d?c=self.location.href:typeof document<"u"&&document.currentScript&&(c=document.currentScript.src),n&&(c=n),c.indexOf("blob:")!==0?c=c.substr(0,c.replace(/[?#].*/,"").lastIndexOf("/")+1):c="",m=Q=>{var oe=new XMLHttpRequest;return oe.open("GET",Q,!1),oe.send(null),oe.responseText},d&&(y=Q=>{var oe=new XMLHttpRequest;return oe.open("GET",Q,!1),oe.responseType="arraybuffer",oe.send(null),new Uint8Array(oe.response)}),g=(Q,oe,Se)=>{var ce=new XMLHttpRequest;ce.open("GET",Q,!0),ce.responseType="arraybuffer",ce.onload=()=>{if(ce.status==200||ce.status==0&&ce.response){oe(ce.response);return}Se()},ce.onerror=Se,ce.send(null)});var v=s.print||console.log.bind(console),w=s.printErr||console.warn.bind(console);Object.assign(s,p),p=null,s.arguments&&s.arguments,s.thisProgram&&s.thisProgram,s.quit&&s.quit;var N;s.wasmBinary&&(N=s.wasmBinary),s.noExitRuntime,typeof WebAssembly!="object"&&Pe("no native wasm support detected");var T,E=!1,$=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0;function R(Q,oe,Se){oe>>>=0;for(var ce=oe+Se,ct=oe;Q[ct]&&!(ct>=ce);)++ct;if(ct-oe>16&&Q.buffer&&$)return $.decode(Q.subarray(oe,ct));for(var bt="";oe<ct;){var Ue=Q[oe++];if(!(Ue&128)){bt+=String.fromCharCode(Ue);continue}var Re=Q[oe++]&63;if((Ue&224)==192){bt+=String.fromCharCode((Ue&31)<<6|Re);continue}var $t=Q[oe++]&63;if((Ue&240)==224?Ue=(Ue&15)<<12|Re<<6|$t:Ue=(Ue&7)<<18|Re<<12|$t<<6|Q[oe++]&63,Ue<65536)bt+=String.fromCharCode(Ue);else{var en=Ue-65536;bt+=String.fromCharCode(55296|en>>10,56320|en&1023)}}return bt}function F(Q,oe){return Q>>>=0,Q?R(H,Q,oe):""}function S(Q,oe,Se,ce){if(Se>>>=0,!(ce>0))return 0;for(var ct=Se,bt=Se+ce-1,Ue=0;Ue<Q.length;++Ue){var Re=Q.charCodeAt(Ue);if(Re>=55296&&Re<=57343){var $t=Q.charCodeAt(++Ue);Re=65536+((Re&1023)<<10)|$t&1023}if(Re<=127){if(Se>=bt)break;oe[Se++>>>0]=Re}else if(Re<=2047){if(Se+1>=bt)break;oe[Se++>>>0]=192|Re>>6,oe[Se++>>>0]=128|Re&63}else if(Re<=65535){if(Se+2>=bt)break;oe[Se++>>>0]=224|Re>>12,oe[Se++>>>0]=128|Re>>6&63,oe[Se++>>>0]=128|Re&63}else{if(Se+3>=bt)break;oe[Se++>>>0]=240|Re>>18,oe[Se++>>>0]=128|Re>>12&63,oe[Se++>>>0]=128|Re>>6&63,oe[Se++>>>0]=128|Re&63}}return oe[Se>>>0]=0,Se-ct}function D(Q,oe,Se){return S(Q,H,oe,Se)}var P,U,H,q;function G(Q){P=Q,s.HEAP8=U=new Int8Array(Q),s.HEAP16=new Int16Array(Q),s.HEAP32=new Int32Array(Q),s.HEAPU8=H=new Uint8Array(Q),s.HEAPU16=new Uint16Array(Q),s.HEAPU32=q=new Uint32Array(Q),s.HEAPF32=new Float32Array(Q),s.HEAPF64=new Float64Array(Q)}s.INITIAL_MEMORY;var Z=[],ee=[],X=[];function re(){if(s.preRun)for(typeof s.preRun=="function"&&(s.preRun=[s.preRun]);s.preRun.length;)ie(s.preRun.shift());Nr(Z)}function te(){Nr(ee)}function ae(){if(s.postRun)for(typeof s.postRun=="function"&&(s.postRun=[s.postRun]);s.postRun.length;)be(s.postRun.shift());Nr(X)}function ie(Q){Z.unshift(Q)}function ve(Q){ee.unshift(Q)}function be(Q){X.unshift(Q)}var he=0,Ie=null;function _e(Q){he++,s.monitorRunDependencies&&s.monitorRunDependencies(he)}function Fe(Q){if(he--,s.monitorRunDependencies&&s.monitorRunDependencies(he),he==0&&Ie){var oe=Ie;Ie=null,oe()}}function Pe(Q){s.onAbort&&s.onAbort(Q),Q="Aborted("+Q+")",w(Q),E=!0,Q+=". Build with -sASSERTIONS for more info.";var oe=new WebAssembly.RuntimeError(Q);throw o(oe),oe}var st="data:application/octet-stream;base64,";function Ge(Q){return Q.startsWith(st)}function qe(Q){return Q.startsWith("file://")}var $e;$e="tfjs-backend-wasm.wasm",Ge($e)||($e=f($e));function Je(Q){try{if(Q==$e&&N)return new Uint8Array(N);if(y)return y(Q);throw"both async and sync fetching of the wasm failed"}catch(oe){Pe(oe)}}function ht(){if(!N&&(u||d)){if(typeof fetch=="function"&&!qe($e))return fetch($e,{credentials:"same-origin"}).then(function(Q){if(!Q.ok)throw"failed to load wasm binary file at '"+$e+"'";return Q.arrayBuffer()}).catch(function(){return Je($e)});if(g)return new Promise(function(Q,oe){g($e,function(Se){Q(new Uint8Array(Se))},oe)})}return Promise.resolve().then(function(){return Je($e)})}function Lr(){var Q={env:gh,wasi_snapshot_preview1:gh};function oe(Ue,Re){var $t=Ue.exports;s.asm=$t,T=s.asm.memory,G(T.buffer),s.asm.__indirect_function_table,ve(s.asm.__wasm_call_ctors),Fe()}_e();function Se(Ue){oe(Ue.instance)}function ce(Ue){return ht().then(function(Re){return WebAssembly.instantiate(Re,Q)}).then(function(Re){return Re}).then(Ue,function(Re){w("failed to asynchronously prepare wasm: "+Re),Pe(Re)})}function ct(){return!N&&typeof WebAssembly.instantiateStreaming=="function"&&!Ge($e)&&!qe($e)&&!h&&typeof fetch=="function"?fetch($e,{credentials:"same-origin"}).then(function(Ue){var Re=WebAssembly.instantiateStreaming(Ue,Q);return Re.then(Se,function($t){return w("wasm streaming compile failed: "+$t),w("falling back to ArrayBuffer instantiation"),ce(Se)})}):ce(Se)}if(s.instantiateWasm)try{var bt=s.instantiateWasm(Q,oe);return bt}catch(Ue){w("Module.instantiateWasm callback failed with error: "+Ue),o(Ue)}return ct().catch(o),{}}function _t(Q){this.name="ExitStatus",this.message="Program terminated with exit("+Q+")",this.status=Q}function Nr(Q){for(;Q.length>0;)Q.shift()(s)}function tr(){Pe("")}function _r(){return 4294901760}function yn(){return _r()}function zr(Q,oe,Se){H.copyWithin(Q>>>0,oe>>>0,oe+Se>>>0)}function Tr(Q){try{return T.grow(Q-P.byteLength+65535>>>16),G(T.buffer),1}catch{}}function rr(Q){var oe=H.length;Q=Q>>>0;var Se=_r();if(Q>Se)return!1;let ce=($t,en)=>$t+(en-$t%en)%en;for(var ct=1;ct<=4;ct*=2){var bt=oe*(1+.2/ct);bt=Math.min(bt,Q+100663296);var Ue=Math.min(Se,ce(Math.max(Q,bt),65536)),Re=Tr(Ue);if(Re)return!0}return!1}function Qr(Q){return 52}function Ua(Q,oe,Se,ce,ct){return 70}var yp=[null,[],[]];function ba(Q,oe){var Se=yp[Q];oe===0||oe===10?((Q===1?v:w)(R(Se,0)),Se.length=0):Se.push(oe)}function bp(Q,oe,Se,ce){for(var ct=0,bt=0;bt<Se;bt++){var Ue=q[oe>>>2],Re=q[oe+4>>>2];oe+=8;for(var $t=0;$t<Re;$t++)ba(Q,H[Ue+$t>>>0]);ct+=Re}return q[ce>>>2]=ct,0}function Kn(Q){var oe=s["_"+Q];return oe}function Va(Q,oe){U.set(Q,oe>>>0)}function nr(Q,oe,Se,ce,ct){var bt={string:cr=>{var Ga=0;if(cr!=null&&cr!==0){var Ih=(cr.length<<2)+1;Ga=xa(Ih),D(cr,Ga,Ih)}return Ga},array:cr=>{var Ga=xa(cr.length);return Va(cr,Ga),Ga}};function Ue(cr){return oe==="string"?F(cr):oe==="boolean"?!!cr:cr}var Re=Kn(Q),$t=[],en=0;if(ce)for(var va=0;va<ce.length;va++){var wh=bt[Se[va]];wh?(en===0&&(en=yh()),$t[va]=wh(ce[va])):$t[va]=ce[va]}var xp=Re.apply(null,$t);function kh(cr){return en!==0&&bh(en),Ue(cr)}return xp=kh(xp),xp}function mh(Q,oe,Se,ce){Se=Se||[];var ct=Se.every(Ue=>Ue==="number"||Ue==="boolean"),bt=oe!=="string";return bt&&ct&&!ce?Kn(Q):function(){return nr(Q,oe,Se,arguments)}}var gh={abort:tr,emscripten_get_heap_max:yn,emscripten_memcpy_big:zr,emscripten_resize_heap:rr,fd_close:Qr,fd_seek:Ua,fd_write:bp};Lr(),s.___wasm_call_ctors=function(){return(s.___wasm_call_ctors=s.asm.__wasm_call_ctors).apply(null,arguments)},s._init=function(){return(s._init=s.asm.init).apply(null,arguments)},s._init_with_threads_count=function(){return(s._init_with_threads_count=s.asm.init_with_threads_count).apply(null,arguments)},s._get_threads_count=function(){return(s._get_threads_count=s.asm.get_threads_count).apply(null,arguments)},s._register_tensor=function(){return(s._register_tensor=s.asm.register_tensor).apply(null,arguments)},s._dispose_data=function(){return(s._dispose_data=s.asm.dispose_data).apply(null,arguments)},s._dispose=function(){return(s._dispose=s.asm.dispose).apply(null,arguments)},s._Abs=function(){return(s._Abs=s.asm.Abs).apply(null,arguments)},s._Acos=function(){return(s._Acos=s.asm.Acos).apply(null,arguments)},s._Acosh=function(){return(s._Acosh=s.asm.Acosh).apply(null,arguments)},s._Add=function(){return(s._Add=s.asm.Add).apply(null,arguments)},s._AddN=function(){return(s._AddN=s.asm.AddN).apply(null,arguments)},s._All=function(){return(s._All=s.asm.All).apply(null,arguments)},s._Any=function(){return(s._Any=s.asm.Any).apply(null,arguments)},s._ArgMax=function(){return(s._ArgMax=s.asm.ArgMax).apply(null,arguments)},s._ArgMin=function(){return(s._ArgMin=s.asm.ArgMin).apply(null,arguments)},s._Asin=function(){return(s._Asin=s.asm.Asin).apply(null,arguments)},s._Asinh=function(){return(s._Asinh=s.asm.Asinh).apply(null,arguments)},s._Atan=function(){return(s._Atan=s.asm.Atan).apply(null,arguments)},s._Atan2=function(){return(s._Atan2=s.asm.Atan2).apply(null,arguments)},s._Atanh=function(){return(s._Atanh=s.asm.Atanh).apply(null,arguments)},s._AvgPool=function(){return(s._AvgPool=s.asm.AvgPool).apply(null,arguments)},s._AvgPool3D=function(){return(s._AvgPool3D=s.asm.AvgPool3D).apply(null,arguments)},s._AvgPool3DGrad=function(){return(s._AvgPool3DGrad=s.asm.AvgPool3DGrad).apply(null,arguments)},s._AvgPoolGrad=function(){return(s._AvgPoolGrad=s.asm.AvgPoolGrad).apply(null,arguments)},s._BatchMatMul=function(){return(s._BatchMatMul=s.asm.BatchMatMul).apply(null,arguments)},s._Bincount=function(){return(s._Bincount=s.asm.Bincount).apply(null,arguments)},s._BitwiseAnd=function(){return(s._BitwiseAnd=s.asm.BitwiseAnd).apply(null,arguments)},s._Ceil=function(){return(s._Ceil=s.asm.Ceil).apply(null,arguments)},s._ClipByValue=function(){return(s._ClipByValue=s.asm.ClipByValue).apply(null,arguments)},s._Conv2D=function(){return(s._Conv2D=s.asm.Conv2D).apply(null,arguments)},s._Conv2DBackpropInput=function(){return(s._Conv2DBackpropInput=s.asm.Conv2DBackpropInput).apply(null,arguments)},s._Conv3D=function(){return(s._Conv3D=s.asm.Conv3D).apply(null,arguments)},s._Conv3DBackpropFilterV2=function(){return(s._Conv3DBackpropFilterV2=s.asm.Conv3DBackpropFilterV2).apply(null,arguments)},s._Conv3DBackpropInputV2=function(){return(s._Conv3DBackpropInputV2=s.asm.Conv3DBackpropInputV2).apply(null,arguments)},s._Cos=function(){return(s._Cos=s.asm.Cos).apply(null,arguments)},s._Cosh=function(){return(s._Cosh=s.asm.Cosh).apply(null,arguments)},s._CropAndResize=function(){return(s._CropAndResize=s.asm.CropAndResize).apply(null,arguments)},s._Cumprod=function(){return(s._Cumprod=s.asm.Cumprod).apply(null,arguments)},s._Cumsum=function(){return(s._Cumsum=s.asm.Cumsum).apply(null,arguments)},s._DenseBincount=function(){return(s._DenseBincount=s.asm.DenseBincount).apply(null,arguments)},s._DepthToSpace=function(){return(s._DepthToSpace=s.asm.DepthToSpace).apply(null,arguments)},s._DepthwiseConv2dNative=function(){return(s._DepthwiseConv2dNative=s.asm.DepthwiseConv2dNative).apply(null,arguments)},s._Diag=function(){return(s._Diag=s.asm.Diag).apply(null,arguments)},s._Dilation2D=function(){return(s._Dilation2D=s.asm.Dilation2D).apply(null,arguments)},s._Dilation2DBackpropFilter=function(){return(s._Dilation2DBackpropFilter=s.asm.Dilation2DBackpropFilter).apply(null,arguments)},s._Dilation2DBackpropInput=function(){return(s._Dilation2DBackpropInput=s.asm.Dilation2DBackpropInput).apply(null,arguments)},s._Elu=function(){return(s._Elu=s.asm.Elu).apply(null,arguments)},s._EluGrad=function(){return(s._EluGrad=s.asm.EluGrad).apply(null,arguments)},s._Equal=function(){return(s._Equal=s.asm.Equal).apply(null,arguments)},s._Erf=function(){return(s._Erf=s.asm.Erf).apply(null,arguments)},s._Exp=function(){return(s._Exp=s.asm.Exp).apply(null,arguments)},s._Expm1=function(){return(s._Expm1=s.asm.Expm1).apply(null,arguments)},s._FlipLeftRight=function(){return(s._FlipLeftRight=s.asm.FlipLeftRight).apply(null,arguments)},s._Floor=function(){return(s._Floor=s.asm.Floor).apply(null,arguments)},s._FloorDiv=function(){return(s._FloorDiv=s.asm.FloorDiv).apply(null,arguments)},s._FusedBatchNorm=function(){return(s._FusedBatchNorm=s.asm.FusedBatchNorm).apply(null,arguments)},s._FusedConv2D=function(){return(s._FusedConv2D=s.asm.FusedConv2D).apply(null,arguments)},s._FusedDepthwiseConv2D=function(){return(s._FusedDepthwiseConv2D=s.asm.FusedDepthwiseConv2D).apply(null,arguments)},s._Gather=function(){return(s._Gather=s.asm.Gather).apply(null,arguments)},s._GatherNd=function(){return(s._GatherNd=s.asm.GatherNd).apply(null,arguments)},s._Greater=function(){return(s._Greater=s.asm.Greater).apply(null,arguments)},s._GreaterEqual=function(){return(s._GreaterEqual=s.asm.GreaterEqual).apply(null,arguments)},s._IsFinite=function(){return(s._IsFinite=s.asm.IsFinite).apply(null,arguments)},s._IsInf=function(){return(s._IsInf=s.asm.IsInf).apply(null,arguments)},s._IsNan=function(){return(s._IsNan=s.asm.IsNan).apply(null,arguments)},s._LRN=function(){return(s._LRN=s.asm.LRN).apply(null,arguments)},s._LRNGrad=function(){return(s._LRNGrad=s.asm.LRNGrad).apply(null,arguments)},s._LeakyRelu=function(){return(s._LeakyRelu=s.asm.LeakyRelu).apply(null,arguments)},s._Less=function(){return(s._Less=s.asm.Less).apply(null,arguments)},s._LessEqual=function(){return(s._LessEqual=s.asm.LessEqual).apply(null,arguments)},s._LinSpace=function(){return(s._LinSpace=s.asm.LinSpace).apply(null,arguments)},s._Log=function(){return(s._Log=s.asm.Log).apply(null,arguments)},s._Log1p=function(){return(s._Log1p=s.asm.Log1p).apply(null,arguments)},s._LogicalAnd=function(){return(s._LogicalAnd=s.asm.LogicalAnd).apply(null,arguments)},s._LogicalNot=function(){return(s._LogicalNot=s.asm.LogicalNot).apply(null,arguments)},s._LogicalOr=function(){return(s._LogicalOr=s.asm.LogicalOr).apply(null,arguments)},s._LogicalXor=function(){return(s._LogicalXor=s.asm.LogicalXor).apply(null,arguments)},s._Max=function(){return(s._Max=s.asm.Max).apply(null,arguments)},s._MaxPool=function(){return(s._MaxPool=s.asm.MaxPool).apply(null,arguments)},s._MaxPool3D=function(){return(s._MaxPool3D=s.asm.MaxPool3D).apply(null,arguments)},s._MaxPool3DGrad=function(){return(s._MaxPool3DGrad=s.asm.MaxPool3DGrad).apply(null,arguments)},s._MaxPoolGrad=function(){return(s._MaxPoolGrad=s.asm.MaxPoolGrad).apply(null,arguments)},s._MaxPoolWithArgmax=function(){return(s._MaxPoolWithArgmax=s.asm.MaxPoolWithArgmax).apply(null,arguments)},s._Maximum=function(){return(s._Maximum=s.asm.Maximum).apply(null,arguments)},s._Mean=function(){return(s._Mean=s.asm.Mean).apply(null,arguments)},s._Min=function(){return(s._Min=s.asm.Min).apply(null,arguments)},s._Minimum=function(){return(s._Minimum=s.asm.Minimum).apply(null,arguments)},s._MirrorPad=function(){return(s._MirrorPad=s.asm.MirrorPad).apply(null,arguments)},s._Mod=function(){return(s._Mod=s.asm.Mod).apply(null,arguments)},s._Multinomial=function(){return(s._Multinomial=s.asm.Multinomial).apply(null,arguments)},s._Multiply=function(){return(s._Multiply=s.asm.Multiply).apply(null,arguments)},s._Neg=function(){return(s._Neg=s.asm.Neg).apply(null,arguments)},s._NonMaxSuppressionV3=function(){return(s._NonMaxSuppressionV3=s.asm.NonMaxSuppressionV3).apply(null,arguments)},s._NonMaxSuppressionV4=function(){return(s._NonMaxSuppressionV4=s.asm.NonMaxSuppressionV4).apply(null,arguments)},s._NonMaxSuppressionV5=function(){return(s._NonMaxSuppressionV5=s.asm.NonMaxSuppressionV5).apply(null,arguments)},s._NotEqual=function(){return(s._NotEqual=s.asm.NotEqual).apply(null,arguments)},s._OneHot=function(){return(s._OneHot=s.asm.OneHot).apply(null,arguments)},s._PadV2=function(){return(s._PadV2=s.asm.PadV2).apply(null,arguments)},s._Pow=function(){return(s._Pow=s.asm.Pow).apply(null,arguments)},s._Prelu=function(){return(s._Prelu=s.asm.Prelu).apply(null,arguments)},s._Prod=function(){return(s._Prod=s.asm.Prod).apply(null,arguments)},s._RealDiv=function(){return(s._RealDiv=s.asm.RealDiv).apply(null,arguments)},s._Reciprocal=function(){return(s._Reciprocal=s.asm.Reciprocal).apply(null,arguments)},s._Relu=function(){return(s._Relu=s.asm.Relu).apply(null,arguments)},s._Relu6=function(){return(s._Relu6=s.asm.Relu6).apply(null,arguments)},s._ResizeBilinear=function(){return(s._ResizeBilinear=s.asm.ResizeBilinear).apply(null,arguments)},s._ResizeBilinearGrad=function(){return(s._ResizeBilinearGrad=s.asm.ResizeBilinearGrad).apply(null,arguments)},s._ResizeNearestNeighbor=function(){return(s._ResizeNearestNeighbor=s.asm.ResizeNearestNeighbor).apply(null,arguments)},s._ResizeNearestNeighborGrad=function(){return(s._ResizeNearestNeighborGrad=s.asm.ResizeNearestNeighborGrad).apply(null,arguments)},s._Reverse=function(){return(s._Reverse=s.asm.Reverse).apply(null,arguments)},s._RotateWithOffset=function(){return(s._RotateWithOffset=s.asm.RotateWithOffset).apply(null,arguments)},s._Round=function(){return(s._Round=s.asm.Round).apply(null,arguments)},s._Rsqrt=function(){return(s._Rsqrt=s.asm.Rsqrt).apply(null,arguments)},s._ScatterNd=function(){return(s._ScatterNd=s.asm.ScatterNd).apply(null,arguments)},s._SearchSorted=function(){return(s._SearchSorted=s.asm.SearchSorted).apply(null,arguments)},s._SelectV2=function(){return(s._SelectV2=s.asm.SelectV2).apply(null,arguments)},s._Selu=function(){return(s._Selu=s.asm.Selu).apply(null,arguments)},s._Sigmoid=function(){return(s._Sigmoid=s.asm.Sigmoid).apply(null,arguments)},s._Sign=function(){return(s._Sign=s.asm.Sign).apply(null,arguments)},s._Sin=function(){return(s._Sin=s.asm.Sin).apply(null,arguments)},s._Sinh=function(){return(s._Sinh=s.asm.Sinh).apply(null,arguments)},s._Softmax=function(){return(s._Softmax=s.asm.Softmax).apply(null,arguments)},s._Softplus=function(){return(s._Softplus=s.asm.Softplus).apply(null,arguments)},s._SparseFillEmptyRows=function(){return(s._SparseFillEmptyRows=s.asm.SparseFillEmptyRows).apply(null,arguments)},s._SparseReshape=function(){return(s._SparseReshape=s.asm.SparseReshape).apply(null,arguments)},s._SparseSegmentReduction=function(){return(s._SparseSegmentReduction=s.asm.SparseSegmentReduction).apply(null,arguments)},s._SparseToDense=function(){return(s._SparseToDense=s.asm.SparseToDense).apply(null,arguments)},s._Sqrt=function(){return(s._Sqrt=s.asm.Sqrt).apply(null,arguments)},s._Square=function(){return(s._Square=s.asm.Square).apply(null,arguments)},s._SquaredDifference=function(){return(s._SquaredDifference=s.asm.SquaredDifference).apply(null,arguments)},s._Step=function(){return(s._Step=s.asm.Step).apply(null,arguments)},s._StridedSlice=function(){return(s._StridedSlice=s.asm.StridedSlice).apply(null,arguments)},s._Sub=function(){return(s._Sub=s.asm.Sub).apply(null,arguments)},s._Sum=function(){return(s._Sum=s.asm.Sum).apply(null,arguments)},s._Tan=function(){return(s._Tan=s.asm.Tan).apply(null,arguments)},s._Tanh=function(){return(s._Tanh=s.asm.Tanh).apply(null,arguments)},s._TensorScatterUpdate=function(){return(s._TensorScatterUpdate=s.asm.TensorScatterUpdate).apply(null,arguments)},s._Tile=function(){return(s._Tile=s.asm.Tile).apply(null,arguments)},s._TopK=function(){return(s._TopK=s.asm.TopK).apply(null,arguments)},s._Transform=function(){return(s._Transform=s.asm.Transform).apply(null,arguments)},s._Transpose=function(){return(s._Transpose=s.asm.Transpose).apply(null,arguments)},s.__FusedMatMul=function(){return(s.__FusedMatMul=s.asm._FusedMatMul).apply(null,arguments)},s._malloc=function(){return(s._malloc=s.asm.malloc).apply(null,arguments)},s._free=function(){return(s._free=s.asm.free).apply(null,arguments)},s.___errno_location=function(){return(s.___errno_location=s.asm.__errno_location).apply(null,arguments)};var yh=s.stackSave=function(){return(yh=s.stackSave=s.asm.stackSave).apply(null,arguments)},bh=s.stackRestore=function(){return(bh=s.stackRestore=s.asm.stackRestore).apply(null,arguments)},xa=s.stackAlloc=function(){return(xa=s.stackAlloc=s.asm.stackAlloc).apply(null,arguments)};s.dynCall_iijjiiii=function(){return(s.dynCall_iijjiiii=s.asm.dynCall_iijjiiii).apply(null,arguments)},s.dynCall_jiji=function(){return(s.dynCall_jiji=s.asm.dynCall_jiji).apply(null,arguments)},s.cwrap=mh;var ol;Ie=function Q(){ol||xh(),ol||(Ie=Q)};function xh(Q){if(he>0||(re(),he>0))return;function oe(){ol||(ol=!0,s.calledRun=!0,!E&&(te(),i(s),s.onRuntimeInitialized&&s.onRuntimeInitialized(),ae()))}s.setStatus?(s.setStatus("Running..."),setTimeout(function(){setTimeout(function(){s.setStatus("")},1),oe()},1)):oe()}if(s.preInit)for(typeof s.preInit=="function"&&(s.preInit=[s.preInit]);s.preInit.length>0;)s.preInit.pop()();xh();var Vs;l&&(Vs={uncaughtException:process.listeners("uncaughtException").filter(function(Q){return!l.uncaughtException.indexOf(Q)>-1}),unhandledRejection:process.listeners("unhandledRejection").filter(function(Q){return!l.unhandledRejection.indexOf(Q)>-1})});var Gs;if(typeof a<"u")Gs=a;else if(typeof WasmBackendModuleThreadedSimd<"u")Gs=WasmBackendModuleThreadedSimd;else throw new Error("Could not find wasm module in post.js");if(Vs){var vh=Gs._dispose;Gs._dispose=function(){vh(),Vs.uncaughtException.forEach(function(Q){process.removeListener("uncaughtException",Q)}),Vs.unhandledRejection.forEach(function(Q){process.removeListener("unhandledRejection",Q)})}}return a.ready}})();typeof e=="object"&&typeof t=="object"?t.exports=r:typeof define=="function"&&define.amd?define([],function(){return r}):typeof e=="object"&&(e.WasmBackendModule=r)}),Xc=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}},pd=class{refCount(e){return Pr("refCount")}incRef(e){return Pr("incRef")}timerAvailable(){return!0}time(e){return Pr("time")}read(e){return Pr("read")}readSync(e){return Pr("readSync")}readToGPU(e,t){return Pr("readToGPU")}numDataIds(){return Pr("numDataIds")}disposeData(e,t){return Pr("disposeData")}write(e,t,r){return Pr("write")}move(e,t,r,n,a){return Pr("move")}createTensorFromGPUData(e,t,r){return Pr("createTensorFromGPUData")}memory(){return Pr("memory")}floatPrecision(){return Pr("floatPrecision")}epsilon(){return this.floatPrecision()===32?1e-7:1e-4}dispose(){return Pr("dispose")}};function Pr(e){throw new Error(`'${e}' not yet implemented or not found in the registry. This kernel may not be supported by the tfjs backend you have chosen`)}function Tk(e){let t=e.length,r=0;for(;t>0;)r=Math.random()*t|0,t--,cc(e,t,r)}function DR(e,t){if(e.length!==t.length)throw new Error(`Array sizes must match to be shuffled together First array length was ${e.length}Second array length was ${t.length}`);let r=e.length,n=0;for(;r>0;)n=Math.random()*r|0,r--,cc(e,r,n),cc(t,r,n)}function jp(e,t,r){return Math.max(e,Math.min(t,r))}function MR(e){return e%2===0?e:e+1}function cc(e,t,r){let n=e[t];e[t]=e[r],e[r]=n}function OR(e){let t=0;for(let r=0;r<e.length;r++)t+=e[r];return t}function LR(e,t){let r=Math.random();return t*r+(1-r)*e}function zR(e,t){let r=0;for(let n=0;n<e.length;n++){let a=Number(e[n])-Number(t[n]);r+=a*a}return r}function A(e,t){if(!e)throw new Error(typeof t=="string"?t:t())}function wr(e,t,r=""){A(Da(e,t),()=>r+` Shapes ${e} and ${t} must match`)}function Ei(e){A(e!=null,()=>"The input to the tensor constructor must be a non-null value.")}function nt(e){if(e.length===0)return 1;let t=e[0];for(let r=1;r<e.length;r++)t*=e[r];return t}function PR(e){return e.length===0}function Ck(e,t){if(e===t)return!0;if(e==null||t==null||e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(e[r]!==null&&t[r]!==null&&e[r]!==t[r])return!1;return!0}function Da(e,t){if(e===t)return!0;if(e==null||t==null||e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(e[r]!==t[r])return!1;return!0}function _l(e){return e%1===0}function BR(e){if(Math.tanh!=null)return Math.tanh(e);if(e===1/0)return 1;if(e===-1/0)return-1;{let t=Math.exp(2*e);return(t-1)/(t+1)}}function WR(e){let t=Math.ceil(Math.sqrt(e));return[t,Math.ceil(e/t)]}function UR(e){let t=new Uint32Array(e);for(let r=0;r<e;++r)t[r]=r;return Tk(t),t}function Pp(e,t){return t<=e.length?e:e+" ".repeat(t-e.length)}function VR(e,t=a=>0,r,n){return new Promise((a,s)=>{let i=0,o=()=>{if(e()){a();return}i++;let l=t(i);if(r!=null&&i>=r){s();return}n!=null?n(o,l):setTimeout(o,l)};o()})}function GR(e,t){let r=1,n=-1;for(let s=0;s<e.length;++s)if(e[s]>=0)r*=e[s];else if(e[s]===-1){if(n!==-1)throw Error(`Shapes can only have 1 implicit size. Found -1 at dim ${n} and dim ${s}`);n=s}else if(e[s]<0)throw Error(`Shapes can not be < 0. Found ${e[s]} at dim ${s}`);if(n===-1){if(t>0&&t!==r)throw Error(`Size(${t}) must match the product of shape ${e}`);return e}if(r===0)throw Error(`Cannot infer the missing size in [${e}] when there are 0 elements`);if(t%r!==0)throw Error(`The implicit shape can't be a fractional number. Got ${t} / ${r}`);let a=e.slice();return a[n]=t/r,a}function _n(e,t){let r=t.length;return e=e==null?t.map((n,a)=>a):[].concat(e),A(e.every(n=>n>=-r&&n<r),()=>`All values in axis param must be in range [-${r}, ${r}) but got axis ${e}`),A(e.every(n=>_l(n)),()=>`All values in axis param must be integers but got axis ${e}`),e.map(n=>n<0?r+n:n)}function Ek(e,t){let r=[],n=[],a=t!=null&&Array.isArray(t)&&t.length===0,s=t==null||a?null:_n(t,e).sort(),i=0;for(let o=0;o<e.length;++o){if(s!=null){if(s[i]===o&&e[o]!==1)throw new Error(`Can't squeeze axis ${o} since its dim '${e[o]}' is not 1`);(s[i]==null||s[i]>o)&&e[o]===1&&(r.push(e[o]),n.push(o)),s[i]<=o&&i++}e[o]!==1&&(r.push(e[o]),n.push(o))}return{newShape:r,keptDims:n}}function $k(e,t){return _y(e,t)}function _y(e,t){let r=null;if(e==null||e==="float32")r=new Float32Array(t);else if(e==="int32")r=new Int32Array(t);else if(e==="bool")r=new Uint8Array(t);else if(e==="string")r=new Array(t);else throw new Error(`Unknown data type ${e}`);return r}function Ak(e,t){for(let r=0;r<e.length;r++){let n=e[r];if(isNaN(n)||!isFinite(n))throw Error(`A tensor of type ${t} being uploaded contains ${n}.`)}}function Fk(e){return e==="bool"||e==="complex64"||e==="float32"||e==="int32"||e==="string"}function HR(e,t){return!(t==="complex64"||t==="float32"&&e!=="complex64"||t==="int32"&&e!=="float32"&&e!=="complex64"||t==="bool"&&e==="bool")}function fc(e){if(e==="float32"||e==="int32")return 4;if(e==="complex64")return 8;if(e==="bool")return 1;throw new Error(`Unknown dtype ${e}`)}function Rk(e){if(e==null)return 0;let t=0;return e.forEach(r=>t+=r.length),t}function rs(e){return typeof e=="string"||e instanceof String}function Dk(e){return typeof e=="boolean"}function Mk(e){return typeof e=="number"}function dd(e){return Array.isArray(e)?dd(e[0]):e instanceof Float32Array?"float32":e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray?"int32":Mk(e)?"float32":rs(e)?"string":Dk(e)?"bool":"float32"}function ds(e){return!!(e&&e.constructor&&e.call&&e.apply)}function mc(e,t){for(let r=t;r<e;++r)if(e%r===0)return r;return e}function ql(e){let t=e.length;if(t<2)return[];let r=new Array(t-1);r[t-2]=e[t-1];for(let n=t-3;n>=0;--n)r[n]=r[n+1]*e[n+1];return r}function Ok(e,t,r,n=!1){let a=new Array;if(t.length===1){let s=t[0]*(n?2:1);for(let i=0;i<s;i++)a[i]=r[e+i]}else{let s=t[0],i=t.slice(1),o=i.reduce((l,p)=>l*p)*(n?2:1);for(let l=0;l<s;l++)a[l]=Ok(e+l*o,i,r,n)}return a}function wl(e,t,r=!1){if(e.length===0)return t[0];let n=e.reduce((a,s)=>a*s)*(r?2:1);if(n===0)return[];if(n!==t.length)throw new Error(`[${e}] does not match the input size ${t.length}${r?" for a complex tensor":""}.`);return Ok(0,e,t,r)}function jR(e,t){if(Array.isArray(e))return e;if(t==="float32")return e instanceof Float32Array?e:new Float32Array(e);if(t==="int32")return e instanceof Int32Array?e:new Int32Array(e);if(t==="bool"||t==="string")return Uint8Array.from(new Int32Array(e));throw new Error(`Unknown dtype ${t}`)}function Ty(e,t){let r=Zc(e,t);for(let n=0;n<r.length;n++)r[n]=1;return r}function Zc(e,t){if(t==null||t==="float32"||t==="complex64")return new Float32Array(e);if(t==="int32")return new Int32Array(e);if(t==="bool")return new Uint8Array(e);throw new Error(`Unknown data type ${t}`)}function qR(e,t){let r=e.reduce((n,a)=>n*a,1);if(t==null||t==="float32")return wl(e,new Float32Array(r));if(t==="int32")return wl(e,new Int32Array(r));if(t==="bool")return wl(e,new Uint8Array(r));throw new Error(`Unknown data type ${t}`)}function Yr(e){e.forEach(t=>{A(Number.isInteger(t)&&t>=0,()=>`Tensor must have a shape comprised of positive integers but got shape [${e}].`)})}function KR(e,t,r){if(t===0)return 0;if(t===1)return e[0];let n=e[e.length-1];for(let a=0;a<e.length-1;++a)n+=r[a]*e[a];return n}function XR(e,t,r){if(t===0)return[];if(t===1)return[e];let n=new Array(t);for(let a=0;a<n.length-1;++a)n[a]=Math.floor(e/r[a]),e-=n[a]*r[a];return n[n.length-1]=e,n}function Jc(e){return e&&e.then&&typeof e.then=="function"}var i0="tfjsflags",Lk=class{constructor(e){this.global=e,this.flags={},this.flagRegistry={},this.urlFlags={},this.getQueryParams=ZR,this.populateURLFlags()}setPlatform(e,t){this.platform!=null&&(j().getBool("IS_TEST")||j().getBool("PROD")||console.warn(`Platform ${this.platformName} has already been set. Overwriting the platform with ${e}.`)),this.platformName=e,this.platform=t}registerFlag(e,t,r){if(this.flagRegistry[e]={evaluationFn:t,setHook:r},this.urlFlags[e]!=null){let n=this.urlFlags[e];j().getBool("IS_TEST")||j().getBool("PROD")||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(Jc(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)}getString(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>"u"||typeof this.global.location>"u"||typeof this.global.location.search>"u")return;let e=this.getQueryParams(this.global.location.search);i0 in e&&e[i0].split(",").forEach(t=>{let[r,n]=t.split(":");this.urlFlags[r]=YR(r,n)})}};function ZR(e){let t={};return e.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,(r,...n)=>(JR(t,n[0],n[1]),n.join("="))),t}function JR(e,t,r){e[decodeURIComponent(t)]=decodeURIComponent(r||"")}function YR(e,t){let r=t.toLowerCase();return r==="true"||r==="false"?r==="true":`${+r}`===r?+r:t}function j(){return Cy}var Cy=null;function QR(e){Cy=e}var Fm;function zk(){if(Fm==null){let e;if(typeof window<"u")e=window;else if(typeof global<"u")e=global;else if(typeof process<"u")e=process;else if(typeof self<"u")e=self;else throw new Error("Could not find a global object");Fm=e}return Fm}function eD(){let e=zk();return e._tfGlobals==null&&(e._tfGlobals=new Map),e._tfGlobals}function Ey(e,t){let r=eD();if(r.has(e))return r.get(e);{let n=t();return r.set(e,n),r.get(e)}}var Kl="Abs",$i="Acos",Ai="Acosh",Ts="Add",Fi="AddN",Xl="All",Zl="Any",Jl="ArgMax",Yl="ArgMin",Ri="Asin",Di="Asinh",Mi="Atan",Oi="Atanh",Li="Atan2",zi="AvgPool",hd="AvgPoolGrad",Ql="AvgPool3D",cd="AvgPool3DGrad",Pi="BatchMatMul",eu="BatchToSpaceND",tu="Bincount",ru="BitwiseAnd",Pk="BroadcastTo",fd="BroadcastArgs",Bi="Cast",Wi="Ceil",Cs="ClipByValue",Yc="Complex",md="ComplexAbs",nu="Concat",Ui="Conv2D",Qc="Conv2DBackpropFilter",Vi="Conv2DBackpropInput",Gi="Conv3D",au="Conv3DBackpropFilterV2",su="Conv3DBackpropInputV2",Hi="Cos",ji="Cosh",iu="Cumprod",qi="Cumsum",ou="CropAndResize",gd="DenseBincount",lu="DepthToSpace",Ki="DepthwiseConv2dNative",ef="DepthwiseConv2dNativeBackpropFilter",tf="DepthwiseConv2dNativeBackpropInput",yd="Diag",Xi="Dilation2D",Tl="Dilation2DBackpropInput",Cl="Dilation2DBackpropFilter",rf="Draw",Zi="RealDiv",nf="Einsum",Ji="Elu",uu="EluGrad",Yi="Erf",pu="Equal",Qi="Exp",du="ExpandDims",eo="Expm1",af="FFT",bd="Fill",hu="FlipLeftRight",to="Floor",ro="FloorDiv",no="FusedBatchNorm",cu="GatherV2",fu="GatherNd",mu="Greater",ao="GreaterEqual",so="Identity",sf="IFFT",of="Imag",io="IsFinite",oo="IsInf",lo="IsNan",uo="LeakyRelu",gu="Less",yu="LessEqual",bu="LinSpace",po="Log",ho="Log1p",xu="LogicalAnd",vu="LogicalNot",wu="LogicalOr",Bk="LogicalXor",Wk="LogSoftmax",tD="LowerBound",co="LRN",ku="LRNGrad",rD="MatrixBandPart",fo="Max",mo="Maximum",go="MaxPool",xd="MaxPoolGrad",Iu="MaxPool3D",vd="MaxPool3DGrad",wd="MaxPoolWithArgmax",yo="Mean",bo="Min",xo="Minimum",vo="MirrorPad",wo="Mod",Su="Multinomial",ko="Multiply",Nu="Neg",_u="NotEqual",Tu="NonMaxSuppressionV3",Cu="NonMaxSuppressionV4",Eu="NonMaxSuppressionV5",$u="OnesLike",Io="OneHot",Au="Pack",So="PadV2",nD="Pool",No="Pow",_o="Prelu",To="Prod",lf="RaggedGather",uf="RaggedRange",pf="RaggedTensorToTensor",kd="Range",df="Real",Co="Reciprocal",Eo="Relu",Fu="Reshape",$o="ResizeNearestNeighbor",Ru="ResizeNearestNeighborGrad",Ao="ResizeBilinear",Du="ResizeBilinearGrad",Fo="Relu6",Ro="Reverse",Do="Round",Mo="Rsqrt",Mu="ScatterNd",Ou="TensorScatterUpdate",Lu="SearchSorted",zu="Select",Oo="Selu",Pu="Slice",Lo="Sin",zo="Sinh",Po="Sign",Bo="Sigmoid",Wo="Softplus",Uo="Sqrt",Vo="Sum",Bu="SpaceToBatchND",Wu="SplitV",Go="Softmax",Id="SparseFillEmptyRows",Uu="SparseReshape",Sd="SparseSegmentMean",Nd="SparseSegmentSum",Vu="SparseToDense",Ho="SquaredDifference",_d="Square",Td="StaticRegexReplace",Gu="StridedSlice",Cd="StringNGrams",Ed="StringSplit",$d="StringToHashBucketFast",jo="Sub",qo="Tan",Ko="Tanh",Es="Tile",Hu="TopK",ju="Transform",Ta="Transpose",Ad="Unique",qu="Unpack",Fd="UnsortedSegmentSum",aD="UpperBound",Ku="ZerosLike",$s="Step",gc="FromPixels",Xu="RotateWithOffset",li="_FusedMatMul",ui="FusedConv2D",pi="FusedDepthwiseConv2D";function es(...e){j().getBool("IS_TEST")||j().getBool("PROD")||console.warn(...e)}function sD(...e){j().getBool("IS_TEST")||j().getBool("PROD")||console.log(...e)}var El=Ey("kernelRegistry",()=>new Map),qp=Ey("gradRegistry",()=>new Map);function Kp(e,t){let r=$y(e,t);return El.get(r)}function rg(e){return qp.get(e)}function yc(e){let t=El.entries(),r=[];for(;;){let{done:n,value:a}=t.next();if(n)break;let[s,i]=a,[o]=s.split("_");o===e&&r.push(i)}return r}function Rd(e){let{kernelName:t,backendName:r}=e,n=$y(t,r);El.has(n)&&es(`The kernel '${t}' for backend '${r}' is already registered`),El.set(n,e)}function Uk(e){let{kernelName:t}=e;qp.has(t)&&j().getBool("DEBUG")&&es(`Overriding the gradient for '${t}'`),qp.set(t,e)}function iD(e,t){let r=$y(e,t);if(!El.has(r))throw new Error(`The kernel '${e}' for backend '${t}' is not registered`);El.delete(r)}function oD(e){if(!qp.has(e))throw new Error(`The gradient '${e}' for backend is not registered`);qp.delete(e)}function lD(e,t){yc(e).forEach(r=>{let n=Object.assign({},r,{backendName:t});Rd(n)})}function $y(e,t){return`${t}_${e}`}var k={};Ee(k,{arraysEqual:()=>Da,arraysEqualWithNull:()=>Ck,assert:()=>A,assertNonNegativeIntegerDimensions:()=>Yr,assertNonNull:()=>Ei,assertShapesMatch:()=>wr,bytesFromStringArray:()=>Rk,bytesPerElement:()=>fc,checkConversionForErrors:()=>Ak,clamp:()=>jp,computeStrides:()=>ql,convertBackendValuesAndArrayBuffer:()=>jR,createScalarValue:()=>fD,createShuffledIndices:()=>UR,decodeString:()=>bc,distSquared:()=>zR,encodeString:()=>Md,fetch:()=>gD,fingerPrint64:()=>cD,flatten:()=>hs,getArrayFromDType:()=>_y,getTypedArrayFromDType:()=>$k,hasEncodingLoss:()=>HR,hexToLong:()=>Dd,indexToLoc:()=>XR,inferDtype:()=>dd,inferFromImplicitShape:()=>GR,isBoolean:()=>Dk,isFunction:()=>ds,isInt:()=>_l,isNumber:()=>Mk,isPromise:()=>Jc,isScalarShape:()=>PR,isString:()=>rs,isTypedArray:()=>Kt,isValidDtype:()=>Fk,locToIndex:()=>KR,makeOnesTypedArray:()=>Ty,makeZerosNestedTypedArray:()=>qR,makeZerosTypedArray:()=>Zc,nearestDivisor:()=>mc,nearestLargerEven:()=>MR,now:()=>Xp,parseAxisParam:()=>_n,randUniform:()=>LR,repeatedTry:()=>VR,rightPad:()=>Pp,shuffle:()=>Tk,shuffleCombo:()=>DR,sizeFromShape:()=>nt,sizeToSquarishShape:()=>WR,squeezeShape:()=>Ek,sum:()=>OR,swap:()=>cc,tanh:()=>BR,toNestedArray:()=>wl,toTypedArray:()=>hf});function Vk(e){return e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray}var o0=_s(yR()),Zs=o0.default||o0;function Dd(e){return Zs.fromString(e,!0,16)}var Gk=Dd("c3a5c85c97cb3127"),qs=Dd("b492b66fbe98f273"),fr=Dd("9ae16a3b2f90404f");function ng(e){return e.xor(e.shru(47))}function Hk(e,t,r){let n=e.slice(t,t+r);return Zs.fromBytes(Array.from(n),!0,!0)}function ft(e,t){return Hk(e,t,8)}function l0(e,t){return Hk(e,t,4)}function qt(e,t){return t===0?e:e.shru(t).or(e.shl(64-t))}function is(e,t,r=Dd("9ddfea08eb382d69")){let n=e.xor(t).mul(r);n=n.xor(n.shru(47));let a=t.xor(n).mul(r);return a=a.xor(a.shru(47)),a=a.mul(r),a}function uD(e,t,r,n,a,s){a=a.add(e),s=qt(s.add(a).add(n),21);let i=a;return a=a.add(t),a=a.add(r),s=s.add(qt(a,44)),[a.add(n),s.add(i)]}function $h(e,t,r,n){return uD(ft(e,t),ft(e,t+8),ft(e,t+16),ft(e,t+24),r,n)}function pD(e,t=e.length){if(t>=8){let r=fr.add(t*2),n=ft(e,0).add(fr),a=ft(e,t-8),s=qt(a,37).mul(r).add(n),i=qt(n,25).add(a).mul(r);return is(s,i,r)}if(t>=4){let r=fr.add(t*2),n=l0(e,0);return is(n.shl(3).add(t),l0(e,t-4),r)}if(t>0){let r=e[0],n=e[t>>1],a=e[t-1],s=r+(n<<8),i=t+(a<<2);return ng(fr.mul(s).xor(Gk.mul(i))).mul(fr)}return fr}function dD(e,t=e.length){let r=fr.add(t*2),n=ft(e,0).mul(qs),a=ft(e,8),s=ft(e,t-8).mul(r),i=ft(e,t-16).mul(fr);return is(qt(n.add(a),43).add(qt(s,30)).add(i),n.add(qt(a.add(fr),18)).add(s),r)}function hD(e,t=e.length){let r=fr.add(t*2),n=ft(e,0).mul(fr),a=ft(e,8),s=ft(e,t-8).mul(r),i=ft(e,t-16).mul(fr),o=qt(n.add(a),43).add(qt(s,30)).add(i),l=is(o,n.add(qt(a.add(fr),18)).add(s),r),p=ft(e,16).mul(r),u=ft(e,24),d=o.add(ft(e,t-32)).mul(r),h=l.add(ft(e,t-24)).mul(r);return is(qt(p.add(u),43).add(qt(d,30)).add(h),p.add(qt(u.add(n),18)).add(d),r)}function cD(e,t=e.length){let r=Zs.fromNumber(81,!0);if(t<=32)return t<=16?pD(e,t):dD(e,t);if(t<=64)return hD(e,t);let n=r,a=r.mul(qs).add(113),s=ng(a.mul(fr).add(113)).mul(fr),i=[Zs.UZERO,Zs.UZERO],o=[Zs.UZERO,Zs.UZERO];n=n.mul(fr).add(ft(e,0));let l=0,p=(t-1>>6)*64,u=p+(t-1&63)-63;do n=qt(n.add(a).add(i[0]).add(ft(e,l+8)),37).mul(qs),a=qt(a.add(i[1]).add(ft(e,l+48)),42).mul(qs),n=n.xor(o[1]),a=a.add(i[0]).add(ft(e,l+40)),s=qt(s.add(o[0]),33).mul(qs),i=$h(e,l,i[1].mul(qs),n.add(o[0])),o=$h(e,l+32,s.add(o[1]),a.add(ft(e,l+16))),[s,n]=[n,s],l+=64;while(l!==p);let d=qs.add(s.and(255).shl(1));return l=u,o[0]=o[0].add(t-1&63),i[0]=i[0].add(o[0]),o[0]=o[0].add(i[0]),n=qt(n.add(a).add(i[0]).add(ft(e,l+8)),37).mul(d),a=qt(a.add(i[1]).add(ft(e,l+48)),42).mul(d),n=n.xor(o[1].mul(9)),a=a.add(i[0].mul(9).add(ft(e,l+40))),s=qt(s.add(o[0]),33).mul(d),i=$h(e,l,i[1].mul(d),n.add(o[0])),o=$h(e,l+32,s.add(o[1]),a.add(ft(e,l+16))),[s,n]=[n,s],is(is(i[0],o[0],d).add(ng(a).mul(Gk)).add(s),is(i[1],o[1],d).add(n),d)}function fD(e,t){return t==="string"?Md(e):hf([e],t)}function mD(e,t){return e instanceof Float32Array&&t==="float32"||e instanceof Int32Array&&t==="int32"||e instanceof Uint8Array&&t==="bool"}function hf(e,t){if(t==="string")throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(e)&&(e=hs(e)),j().getBool("DEBUG")&&Ak(e,t),mD(e,t))return e;if(t==null||t==="float32"||t==="complex64")return new Float32Array(e);if(t==="int32")return new Int32Array(e);if(t==="bool"){let r=new Uint8Array(e.length);for(let n=0;n<r.length;++n)Math.round(e[n])!==0&&(r[n]=1);return r}else throw new Error(`Unknown data type ${t}`)}function Xp(){return j().platform.now()}function gD(e,t){return j().platform.fetch(e,t)}function Md(e,t="utf-8"){return t=t||"utf-8",j().platform.encode(e,t)}function bc(e,t="utf-8"){return t=t||"utf-8",j().platform.decode(e,t)}function Kt(e){return j().platform.isTypedArray!=null?j().platform.isTypedArray(e):Vk(e)}function hs(e,t=[],r=!1){if(t==null&&(t=[]),typeof e=="boolean"||typeof e=="number"||typeof e=="string"||Jc(e)||e==null||Kt(e)&&r)t.push(e);else if(Array.isArray(e)||Kt(e))for(let n=0;n<e.length;++n)hs(e[n],t,r);else{let n=-1;for(let a of Object.keys(e))/^([1-9]+[0-9]*|0)$/.test(a)&&(n=Math.max(n,Number(a)));for(let a=0;a<=n;a++)hs(e[a],t,r)}return t}var yD=class{constructor(e,t){this.backendTimer=e,this.logger=t,t==null&&(this.logger=new xD)}profileKernel(e,t,r){let n,a=()=>{n=r()},s,i=Xp();if(this.backendTimer.timerAvailable())s=this.backendTimer.time(a);else{a();for(let o of n)o.dataSync();s=Promise.resolve({kernelMs:Xp()-i})}if(j().getBool("CHECK_COMPUTATION_FOR_ERRORS"))for(let o=0;o<n.length;o++){let l=n[o];l.data().then(p=>{bD(p,l.dtype,e)})}return{kernelName:e,outputs:n,inputs:t,timeMs:s.then(o=>o.kernelMs),extraInfo:s.then(o=>o.getExtraProfileInfo!=null?o.getExtraProfileInfo():"")}}logKernelProfile(e){let{kernelName:t,outputs:r,timeMs:n,inputs:a,extraInfo:s}=e;r.forEach(i=>{Promise.all([i.data(),n,s]).then(o=>{this.logger.logKernelProfile(t,i,o[0],o[1],a,o[2])})})}};function bD(e,t,r){if(t!=="float32")return!1;for(let n=0;n<e.length;n++){let a=e[n];if(isNaN(a)||!isFinite(a))return console.warn(`Found ${a} in the result of '${r}'`),!0}return!1}var xD=class{logKernelProfile(e,t,r,n,a,s){let i=typeof n=="number"?Pp(`${n}ms`,9):n.error,o=Pp(e,25),l=t.rank,p=t.size,u=Pp(t.shape.toString(),14),d="";for(let h in a){let c=a[h];if(c!=null){let f=c.shape||t.shape,m=f.length;d+=`${h}: ${m}D ${m>0?f:""} `}}console.log(`%c${o} %c${i} %c${l}D ${u} %c${p} %c${d} %c${s}`,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")}};function vD(e,t,r){let n={},a={};for(let l=0;l<t.length;l++)n[t[l].id]=!0;for(let l=0;l<e.length;l++){let p=e[l],u=p.inputs;for(let d in u){let h=u[d],c=!1;for(let f=0;f<t.length;f++)if(n[h.id]){p.outputs.forEach(m=>n[m.id]=!0),c=!0,a[p.id]=!0;break}if(c)break}}let s={};s[r.id]=!0;let i={};for(let l=e.length-1;l>=0;l--){let p=e[l],u=p.inputs;for(let d=0;d<p.outputs.length;d++)if(s[p.outputs[d].id]){for(let h in u)s[u[h].id]=!0,i[p.id]=!0;break}}let o=[];for(let l=0;l<e.length;l++){let p=e[l];if(a[p.id]&&i[p.id]){let u={};for(let h in p.inputs){let c=p.inputs[h];n[c.id]&&(u[h]=c)}let d=Object.assign({},p);d.inputs=u,d.outputs=p.outputs,o.push(d)}}return o}function wD(e,t,r,n){for(let a=t.length-1;a>=0;a--){let s=t[a],i=[];if(s.outputs.forEach(l=>{let p=e[l.id];p!=null?i.push(p):i.push(null)}),s.gradient==null)throw new Error(`Cannot compute gradient: gradient function not found for ${s.kernelName}.`);let o=s.gradient(i);for(let l in s.inputs){if(!(l in o))throw new Error(`Cannot backprop through input ${l}. Available gradients found: ${Object.keys(o)}.`);let p=r(()=>o[l]());if(p.dtype!=="float32")throw new Error(`Error in gradient for op ${s.kernelName}. The gradient of input ${l} must have 'float32' dtype, but has '${p.dtype}'`);let u=s.inputs[l];if(!Da(p.shape,u.shape))throw new Error(`Error in gradient for op ${s.kernelName}. The gradient of input '${l}' has shape '${p.shape}', which does not match the shape of the input '${u.shape}'`);if(e[u.id]==null)e[u.id]=p;else{let d=e[u.id];e[u.id]=n(d,p),d.dispose()}}}}var u0=20,wp=3,Rm=7;function kD(e,t,r,n){let a=ql(t),s=ID(e,t,r,a),i=t.length,o=Xh(e,t,r,a,s),l=["Tensor"];return n&&(l.push(` dtype: ${r}`),l.push(` rank: ${i}`),l.push(` shape: [${t}]`),l.push(" values:")),l.push(o.map(p=>" "+p).join(`
`)),l.join(`
`)}function ID(e,t,r,n){let a=nt(t),s=n[n.length-1],i=new Array(s).fill(0),o=t.length,l=r==="complex64"?Ep(e):e;if(o>1)for(let p=0;p<a/s;p++){let u=p*s;for(let d=0;d<s;d++)i[d]=Math.max(i[d],Cp(l[u+d],0,r).length)}return i}function Cp(e,t,r){let n;return Array.isArray(e)?n=`${parseFloat(e[0].toFixed(Rm))} + ${parseFloat(e[1].toFixed(Rm))}j`:rs(e)?n=`'${e}'`:r==="bool"?n=jk(e):n=parseFloat(e.toFixed(Rm)).toString(),Pp(n,t)}function jk(e){return e===0?"false":"true"}function Xh(e,t,r,n,a,s=!0){let i=r==="complex64"?2:1,o=t[0],l=t.length;if(l===0){if(r==="complex64"){let m=Ep(e);return[Cp(m[0],0,r)]}return r==="bool"?[jk(e[0])]:[e[0].toString()]}if(l===1){if(o>u0){let m=wp*i,g=Array.from(e.slice(0,m)),y=Array.from(e.slice((o-wp)*i,o*i));return r==="complex64"&&(g=Ep(g),y=Ep(y)),["["+g.map((b,x)=>Cp(b,a[x],r)).join(", ")+", ..., "+y.map((b,x)=>Cp(b,a[o-wp+x],r)).join(", ")+"]"]}return["["+(r==="complex64"?Ep(e):Array.from(e)).map((m,g)=>Cp(m,a[g],r)).join(", ")+"]"]}let p=t.slice(1),u=n.slice(1),d=n[0]*i,h=[];if(o>u0){for(let m=0;m<wp;m++){let g=m*d,y=g+d;h.push(...Xh(e.slice(g,y),p,r,u,a,!1))}h.push("...");for(let m=o-wp;m<o;m++){let g=m*d,y=g+d;h.push(...Xh(e.slice(g,y),p,r,u,a,m===o-1))}}else for(let m=0;m<o;m++){let g=m*d,y=g+d;h.push(...Xh(e.slice(g,y),p,r,u,a,m===o-1))}let c=l===2?",":"";h[0]="["+(o>0?h[0]+c:"");for(let m=1;m<h.length-1;m++)h[m]=" "+h[m]+c;let f=`,
`;for(let m=2;m<l;m++)f+=`
`;return h[h.length-1]=" "+h[h.length-1]+"]"+(s?"":f),h}function Ep(e){let t=[];for(let r=0;r<e.length;r+=2)t.push([e[r],e[r+1]]);return t}var Dt=class{constructor(e,t,r){if(this.dtype=t,this.shape=e.slice(),this.size=nt(e),r!=null){let n=r.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=r||_y(t,this.size),this.strides=ql(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 r=this.locToIndex(t);this.values[r]=e}get(...e){e.length===0&&(e=[0]);let t=0;for(let n of e){if(n<0||n>=this.shape[t]){let a=`Requested out of range element at ${e}. Buffer shape=${this.shape}`;throw new Error(a)}t++}let r=e[e.length-1];for(let n=0;n<e.length-1;++n)r+=this.strides[n]*e[n];return this.values[r]}locToIndex(e){if(this.rank===0)return 0;if(this.rank===1)return e[0];let t=e[e.length-1];for(let r=0;r<e.length-1;++r)t+=this.strides[r]*e[r];return t}indexToLoc(e){if(this.rank===0)return[];if(this.rank===1)return[e];let t=new Array(this.shape.length);for(let r=0;r<t.length-1;++r)t[r]=Math.floor(e/this.strides[r]),e-=t[r]*this.strides[r];return t[t.length-1]=e,t}get rank(){return this.shape.length}toTensor(){return Dn().makeTensor(this.values,this.shape,this.dtype)}},Dn=null,fl=null;function SD(e){Dn=e}function ND(e){fl=e}var ze=class{constructor(e,t,r,n){this.kept=!1,this.isDisposedInternal=!1,this.shape=e.slice(),this.dtype=t||"float32",this.size=nt(e),this.strides=ql(e),this.dataId=r,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 fl.buffer(this.shape,this.dtype,e)}bufferSync(){return fl.buffer(this.shape,this.dtype,this.dataSync())}async array(){let e=await this.data();return wl(this.shape,e,this.dtype==="complex64")}arraySync(){return wl(this.shape,this.dataSync(),this.dtype==="complex64")}async data(){this.throwIfDisposed();let e=Dn().read(this.dataId);if(this.dtype==="string"){let t=await e;try{return t.map(r=>bc(r))}catch{throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}}return e}dataToGPU(e){return this.throwIfDisposed(),Dn().readToGPU(this.dataId,e)}dataSync(){this.throwIfDisposed();let e=Dn().readSync(this.dataId);if(this.dtype==="string")try{return e.map(t=>bc(t))}catch{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 Dn().read(this.dataId);return this.dtype==="string"?e:new Uint8Array(e.buffer)}dispose(){this.isDisposed||(this.kerasMask&&this.kerasMask.dispose(),Dn().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return fl.print(this,e)}clone(){return this.throwIfDisposed(),fl.clone(this)}toString(e=!1){let t=this.dataSync();return kD(t,this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),fl.cast(this,e)}variable(e=!0,t,r){return this.throwIfDisposed(),Dn().makeVariable(this,e,t,r)}};Object.defineProperty(ze,Symbol.hasInstance,{value:e=>!!e&&e.data!=null&&e.dataSync!=null&&e.throwIfDisposed!=null});function Y(){return Ey("Tensor",()=>ze)}Y();var di=class extends ze{constructor(e,t,r,n){super(e.shape,e.dtype,e.dataId,n),this.trainable=t,this.name=r}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(!Da(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);Dn().disposeTensor(this),this.dataId=e.dataId,Dn().incRef(this,null)}dispose(){Dn().disposeVariable(this),this.isDisposedInternal=!0}};Object.defineProperty(di,Symbol.hasInstance,{value:e=>e instanceof ze&&e.assign!=null&&e.assign instanceof Function});var Mn={};Ee(Mn,{assertTypesMatch:()=>Xk,getTensorsInContainer:()=>Ay,isTensorInList:()=>TD,makeTypesMatch:()=>Nt});var ag;(function(e){e.R0="R0",e.R1="R1",e.R2="R2",e.R3="R3",e.R4="R4",e.R5="R5",e.R6="R6"})(ag||(ag={}));var sg;(function(e){e.float32="float32",e.int32="int32",e.bool="int32",e.complex64="complex64"})(sg||(sg={}));var ig;(function(e){e.float32="float32",e.int32="int32",e.bool="bool",e.complex64="complex64"})(ig||(ig={}));var og;(function(e){e.float32="float32",e.int32="float32",e.bool="float32",e.complex64="complex64"})(og||(og={}));var lg;(function(e){e.float32="complex64",e.int32="complex64",e.bool="complex64",e.complex64="complex64"})(lg||(lg={}));var _D={float32:og,int32:sg,bool:ig,complex64:lg};function cn(e,t){if(e==="string"||t==="string"){if(e==="string"&&t==="string")return"string";throw new Error(`Can not upcast ${e} with ${t}`)}return _D[e][t]}function cf(e){return cn(e,"int32")}function qk(e){return e!=null&&typeof e=="object"&&"texture"in e&&e.texture instanceof WebGLTexture}function Kk(e){return typeof GPUBuffer<"u"&&e!=null&&typeof e=="object"&&"buffer"in e&&e.buffer instanceof GPUBuffer}function Nt(e,t){if(e.dtype===t.dtype)return[e,t];let r=cn(e.dtype,t.dtype);return[e.cast(r),t.cast(r)]}function Xk(e,t){A(e.dtype===t.dtype,()=>`The dtypes of the first(${e.dtype}) and second(${t.dtype}) input must match`)}function TD(e,t){return t.some(r=>r.id===e.id)}function Ay(e){let t=[];return Zk(e,t,new Set),t}function Zk(e,t,r){if(e==null)return;if(e instanceof ze){t.push(e);return}if(!CD(e))return;let n=e;for(let a in n){let s=n[a];r.has(s)||(r.add(s),Zk(s,t,r))}}function CD(e){return Array.isArray(e)||typeof e=="object"}function Dm(e){return e.kernelName!=null}var p0=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()}},Fy=class ug{constructor(t){this.ENV=t,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new p0}async ready(){if(this.pendingBackendInit!=null)return this.pendingBackendInit.then(()=>{});if(this.backendInstance!=null)return;let t=this.getSortedBackends();for(let r=0;r<t.length;r++){let n=t[r];if(await this.initializeBackend(n).success){await this.setBackend(n);return}}throw new Error("Could not initialize any backends, all backend initializations failed.")}get backend(){if(this.pendingBackendInit!=null)throw new Error(`Backend '${this.backendName}' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`);if(this.backendInstance==null){let{name:t,asyncInit:r}=this.initializeBackendsAndReturnBest();if(r)throw new Error(`The highest priority backend '${t}' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`);this.setBackend(t)}return this.backendInstance}backendNames(){return Object.keys(this.registryFactory)}findBackend(t){if(!(t in this.registry))if(t in this.registryFactory){let{asyncInit:r}=this.initializeBackend(t);if(r)return null}else return null;return this.registry[t]}findBackendFactory(t){return t in this.registryFactory?this.registryFactory[t].factory:null}registerBackend(t,r,n=1){return t in this.registryFactory?(es(`${t} backend was already registered. Reusing existing backend factory.`),!1):(this.registryFactory[t]={factory:r,priority:n},!0)}async setBackend(t){if(this.registryFactory[t]==null)throw new Error(`Backend name '${t}' not found in registry`);if(this.backendName=t,this.registry[t]==null){this.backendInstance=null;let{success:r,asyncInit:n}=this.initializeBackend(t);if(!(n?await r:r))return!1}return this.backendInstance=this.registry[t],this.setupRegisteredKernels(),this.profiler=new yD(this.backendInstance),!0}setupRegisteredKernels(){yc(this.backendName).forEach(t=>{t.setupFunc!=null&&t.setupFunc(this.backendInstance)})}disposeRegisteredKernels(t){yc(t).forEach(r=>{r.disposeFunc!=null&&r.disposeFunc(this.registry[t])})}initializeBackend(t){let r=this.registryFactory[t];if(r==null)throw new Error(`Cannot initialize backend ${t}, no registration found.`);try{let n=r.factory();if(n&&!(n instanceof pd)&&typeof n.then=="function"){let a=++this.pendingBackendInitId,s=n.then(i=>a<this.pendingBackendInitId?!1:(this.registry[t]=i,this.pendingBackendInit=null,!0)).catch(i=>(a<this.pendingBackendInitId||(this.pendingBackendInit=null,es(`Initialization of backend ${t} failed`),es(i.stack||i.message)),!1));return this.pendingBackendInit=s,{success:s,asyncInit:!0}}else return this.registry[t]=n,{success:!0,asyncInit:!1}}catch(n){return es(`Initialization of backend ${t} failed`),es(n.stack||n.message),{success:!1,asyncInit:!1}}}removeBackend(t){if(!(t in this.registryFactory))throw new Error(`${t} backend not found in registry`);this.backendName===t&&this.pendingBackendInit!=null&&this.pendingBackendInitId++,t in this.registry&&(this.disposeRegisteredKernels(t),this.registry[t].dispose(),delete this.registry[t]),delete this.registryFactory[t],this.backendName===t&&(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((t,r)=>this.registryFactory[r].priority-this.registryFactory[t].priority)}initializeBackendsAndReturnBest(){let t=this.getSortedBackends();for(let r=0;r<t.length;r++){let n=t[r],{success:a,asyncInit:s}=this.initializeBackend(n);if(s||a)return{name:n,asyncInit:s}}throw new Error("Could not initialize any backends, all backend initializations failed.")}moveData(t,r){let n=this.state.tensorInfo.get(r),a=n.backend,s=this.readSync(r),i=a.refCount(r);a.disposeData(r,!0),n.backend=t,t.move(r,s,n.shape,n.dtype,i),this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack[this.state.numDataMovesStack.length-1]++}tidy(t,r){let n=null;if(r==null){if(typeof t!="function")throw new Error("Please provide a function to tidy()");r=t}else{if(typeof t!="string"&&!(t instanceof String))throw new Error("When calling with two arguments, the first argument to tidy() must be a string");if(typeof r!="function")throw new Error("When calling with two arguments, the 2nd argument to tidy() must be a function");n=t}let a;return this.scopedRun(()=>this.startScope(n),()=>this.endScope(a),()=>(a=r(),a instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),a))}scopedRun(t,r,n){t();try{let a=n();return r(),a}catch(a){throw r(),a}}nextTensorId(){return ug.nextTensorId++}nextVariableId(){return ug.nextVariableId++}clone(t){let r=O.runKernel(so,{x:t}),n={x:t},a=i=>({x:()=>{let o="float32",l={x:i},p={dtype:o};return O.runKernel(Bi,l,p)}}),s=[];return this.addTapeNode(this.state.activeScope.name,n,[r],a,s,{}),r}runKernel(t,r,n){if(this.backendName==null&&this.backend,Kp(t,this.backendName)==null)throw new Error(`Kernel '${t}' not registered for backend '${this.backendName}'`);return this.runKernelFunc({kernelName:t,inputs:r,attrs:n})}shouldCheckForMemLeaks(){return this.ENV.getBool("IS_TEST")}checkKernelForMemLeak(t,r,n){let a=this.backend.numDataIds(),s=0;n.forEach(l=>{s+=l.dtype==="complex64"?3:1});let i=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],o=a-r-s-i;if(o>0)throw new Error(`Backend '${this.backendName}' has an internal memory leak (${o} data ids) after running '${t}'`)}runKernelFunc(t){let r,n=[],a=this.isTapeOn(),s=this.state.numBytes,i=this.state.numTensors;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0);let o;this.backendName==null&&this.backend;let l,p=Dm(t)?t.kernelName:this.state.activeScope!=null?this.state.activeScope.name:"";if(Dm(t)){let{kernelName:f,inputs:m,attrs:g}=t;this.backendName==null&&this.backend;let y=Kp(f,this.backendName);A(y!=null,()=>`Cannot find registered kernel '${f}' for backend '${this.backendName}'`),o=()=>{let b=this.backend.numDataIds();l=y.kernelFunc({inputs:m,attrs:g,backend:this.backend});let x=Array.isArray(l)?l:[l];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(f,b,x);let v=x.map(w=>w.rank!=null?w:this.makeTensorFromTensorInfo(w));if(a){let w=this.getTensorsForGradient(f,m,v);n=this.saveTensorsForBackwardMode(w)}return v}}else{let{forwardFunc:f}=t,m=g=>{a&&(n=g.map(y=>this.keep(this.clone(y))))};o=()=>{let g=this.backend.numDataIds();l=this.tidy(()=>f(this.backend,m));let y=Array.isArray(l)?l:[l];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(p,g,y),y}}let{inputs:u,attrs:d}=t,h=Dm(t)?null:t.backwardsFunc,c;return this.scopedRun(()=>this.state.kernelDepth++,()=>this.state.kernelDepth--,()=>{!this.ENV.getBool("DEBUG")&&!this.state.profiling?r=o():(c=this.profiler.profileKernel(p,u,()=>o()),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(c),r=c.outputs)}),a&&this.addTapeNode(p,u,r,h,n,d),this.state.profiling&&this.state.activeProfile.kernels.push({name:p,bytesAdded:this.state.numBytes-s,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-i,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(u).map(f=>u[f]!=null?u[f].shape:null),outputShapes:r.map(f=>f.shape),kernelTimeMs:c.timeMs,extraInfo:c.extraInfo}),Array.isArray(l)?r:r[0]}saveTensorsForBackwardMode(t){return t.map(r=>this.keep(this.clone(r)))}getTensorsForGradient(t,r,n){let a=rg(t);if(a!=null){let s=a.inputsToSave||[],i=a.outputsToSave||[],o;a.saveAllInputs?(A(Array.isArray(r),()=>"saveAllInputs is true, expected inputs to be an array."),o=Object.keys(r).map(p=>r[p])):o=s.map(p=>r[p]);let l=n.filter((p,u)=>i[u]);return o.concat(l)}return[]}makeTensor(t,r,n,a){if(t==null)throw new Error("Values passed to engine.makeTensor() are null");n=n||"float32",a=a||this.backend;let s=t;n==="string"&&rs(t[0])&&(s=t.map(l=>Md(l)));let i=a.write(s,r,n),o=new ze(r,n,i,this.nextTensorId());if(this.trackTensor(o,a),n==="string"){let l=this.state.tensorInfo.get(i),p=Rk(s);this.state.numBytes+=p-l.bytes,l.bytes=p}return o}makeTensorFromDataId(t,r,n,a){n=n||"float32";let s={dataId:t,shape:r,dtype:n};return this.makeTensorFromTensorInfo(s,a)}makeTensorFromTensorInfo(t,r){let{dataId:n,shape:a,dtype:s}=t,i=new ze(a,s,n,this.nextTensorId());return this.trackTensor(i,r),i}makeVariable(t,r=!0,n,a){n=n||this.nextVariableId().toString(),a!=null&&a!==t.dtype&&(t=t.cast(a));let s=new di(t,r,n,this.nextTensorId());if(this.state.registeredVariables[s.name]!=null)throw new Error(`Variable with name ${s.name} was already registered`);return this.state.registeredVariables[s.name]=s,this.incRef(s,this.backend),s}trackTensor(t,r){this.state.numTensors++,t.dtype==="string"&&this.state.numStringTensors++;let n=0;t.dtype!=="complex64"&&t.dtype!=="string"&&(n=t.size*fc(t.dtype)),this.state.numBytes+=n,this.state.tensorInfo.has(t.dataId)||(this.state.numDataBuffers++,this.state.tensorInfo.set(t.dataId,{backend:r||this.backend,dtype:t.dtype,shape:t.shape,bytes:n})),t instanceof di||this.track(t)}incRef(t,r){this.trackTensor(t,r),this.backend.incRef(t.dataId)}removeDataId(t,r){this.state.tensorInfo.has(t)&&this.state.tensorInfo.get(t).backend===r&&(this.state.tensorInfo.delete(t),this.state.numDataBuffers--)}disposeTensor(t){if(!this.state.tensorInfo.has(t.dataId))return;let r=this.state.tensorInfo.get(t.dataId);if(this.state.numTensors--,t.dtype==="string"&&(this.state.numStringTensors--,this.state.numBytes-=r.bytes),t.dtype!=="complex64"&&t.dtype!=="string"){let n=t.size*fc(t.dtype);this.state.numBytes-=n}r.backend.disposeData(t.dataId)&&this.removeDataId(t.dataId,r.backend)}disposeVariables(){for(let t in this.state.registeredVariables){let r=this.state.registeredVariables[t];this.disposeVariable(r)}}disposeVariable(t){this.disposeTensor(t),this.state.registeredVariables[t.name]!=null&&delete this.state.registeredVariables[t.name]}memory(){let t=this.backend.memory();return t.numTensors=this.state.numTensors,t.numDataBuffers=this.state.numDataBuffers,t.numBytes=this.state.numBytes,this.state.numStringTensors>0&&(t.unreliable=!0,t.reasons==null&&(t.reasons=[]),t.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)")),t}async profile(t){this.state.profiling=!0;let r=this.state.numBytes,n=this.state.numTensors;this.state.activeProfile.kernels=[],this.state.activeProfile.result=await t(),this.state.profiling=!1,this.state.activeProfile.peakBytes=Math.max(...this.state.activeProfile.kernels.map(a=>a.totalBytesSnapshot)),this.state.activeProfile.newBytes=this.state.numBytes-r,this.state.activeProfile.newTensors=this.state.numTensors-n;for(let a of this.state.activeProfile.kernels)a.kernelTimeMs=await a.kernelTimeMs,a.extraInfo=await a.extraInfo;return this.state.activeProfile}isTapeOn(){return this.state.gradientDepth>0&&this.state.kernelDepth===0}addTapeNode(t,r,n,a,s,i){let o={id:this.state.nextTapeNodeId++,kernelName:t,inputs:r,outputs:n,saved:s},l=rg(t);l!=null&&(a=l.gradFunc),a!=null&&(o.gradient=p=>(p=p.map((u,d)=>{if(u==null){let h=n[d],c=Zc(h.size,h.dtype);return this.makeTensor(c,h.shape,h.dtype)}return u}),a(p.length>1?p:p[0],s,i))),this.state.activeTape.push(o)}keep(t){return t.kept=!0,t}startTape(){this.state.gradientDepth===0&&(this.state.activeTape=[]),this.state.gradientDepth++}endTape(){this.state.gradientDepth--}startScope(t){let r={track:[],name:"unnamed scope",id:this.state.nextScopeId++};t&&(r.name=t),this.state.scopeStack.push(r),this.state.activeScope=r}endScope(t){let r=Ay(t),n=new Set(r.map(s=>s.id));for(let s=0;s<this.state.activeScope.track.length;s++){let i=this.state.activeScope.track[s];!i.kept&&!n.has(i.id)&&i.dispose()}let a=this.state.scopeStack.pop();this.state.activeScope=this.state.scopeStack.length===0?null:this.state.scopeStack[this.state.scopeStack.length-1],r.forEach(s=>{!s.kept&&s.scopeId===a.id&&this.track(s)})}gradients(t,r,n,a=!1){if(A(r.length>0,()=>"gradients() received an empty list of xs."),n!=null&&n.dtype!=="float32")throw new Error(`dy must have 'float32' dtype, but has '${n.dtype}'`);let s=this.scopedRun(()=>this.startTape(),()=>this.endTape(),()=>this.tidy("forward",t));A(s instanceof ze,()=>"The result y returned by f() must be a tensor.");let i=vD(this.state.activeTape,r,s);if(!a&&i.length===0&&r.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 o={};o[s.id]=n??ED(s.shape),wD(o,i,p=>this.tidy(p),$D);let l=r.map(p=>o[p.id]);return this.state.gradientDepth===0&&(this.state.activeTape.forEach(p=>{for(let u of p.saved)u.dispose()}),this.state.activeTape=null),{value:s,grads:l}})}customGrad(t){return A(ds(t),()=>"The f passed in customGrad(f) must be a function."),(...r)=>{A(r.every(o=>o instanceof ze),()=>"The args passed in customGrad(f)(x1, x2,...) must all be tensors");let n,a={};r.forEach((o,l)=>{a[l]=o});let s=(o,l)=>(n=t(...r,l),A(n.value instanceof ze,()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"),A(ds(n.gradFunc),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function."),n.value),i=(o,l)=>{let p=n.gradFunc(o,l),u=Array.isArray(p)?p:[p];A(u.length===r.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(u.every(h=>h instanceof ze),()=>"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 d={};return u.forEach((h,c)=>{d[c]=()=>h}),d};return this.runKernelFunc({forwardFunc:s,backwardsFunc:i,inputs:a})}}readSync(t){return this.state.tensorInfo.get(t).backend.readSync(t)}read(t){return this.state.tensorInfo.get(t).backend.read(t)}readToGPU(t,r){return this.state.tensorInfo.get(t).backend.readToGPU(t,r)}async time(t){let r=Xp(),n=await this.backend.time(t);return n.wallMs=Xp()-r,n}track(t){return this.state.activeScope!=null&&(t.scopeId=this.state.activeScope.id,this.state.activeScope.track.push(t)),t}get registeredVariables(){return this.state.registeredVariables}reset(){this.pendingBackendInitId++,this.state.dispose(),this.ENV.reset(),this.state=new p0;for(let t in this.registry)this.disposeRegisteredKernels(t),this.registry[t].dispose(),delete this.registry[t];this.backendName=null,this.backendInstance=null,this.pendingBackendInit=null}};Fy.nextTensorId=0;Fy.nextVariableId=0;function ED(e){let t=Ty(nt(e),"float32");return O.makeTensor(t,e,"float32")}function Jk(){let e=zk();if(e._tfengine==null){let t=new Lk(e);e._tfengine=new Fy(t)}return QR(e._tfengine.ENV),SD(()=>e._tfengine),e._tfengine}var O=Jk();function $D(e,t){let r={a:e,b:t};return O.runKernel(Ts,r)}var Od={};Ee(Od,{isBrowser:()=>Yk,isMobile:()=>RD,mockIsMobile:()=>FD});function AD(){return typeof navigator<"u"&&navigator!=null}var pg;function FD(e){pg=e}function RD(e){if(pg!==void 0)return pg;if(e||AD()){if(e||(e=navigator),e.product==="ReactNative")return!0;let t=e.userAgent||e.vendor||(typeof window<"u"?window.opera:"");if(!t){let r=e;return r.userAgentData&&r.userAgentData.mobile}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(t)||/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(t.substr(0,4))}return!1}function Yk(){return typeof window<"u"&&window.document!=null||typeof WorkerGlobalScope<"u"}var Rr=j();Rr.registerFlag("DEBUG",()=>!1,e=>{e&&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.")});Rr.registerFlag("IS_BROWSER",()=>Yk());Rr.registerFlag("IS_NODE",()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u");Rr.registerFlag("IS_CHROME",()=>typeof navigator<"u"&&navigator!=null&&navigator.userAgent!=null&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor));Rr.registerFlag("IS_SAFARI",()=>typeof navigator<"u"&&navigator!=null&&navigator.userAgent!=null&&/Safari/.test(navigator.userAgent)&&/Apple/.test(navigator.vendor));Rr.registerFlag("PROD",()=>!1);Rr.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",()=>Rr.getBool("DEBUG"));Rr.registerFlag("DEPRECATION_WARNINGS_ENABLED",()=>!0);Rr.registerFlag("IS_TEST",()=>!1);Rr.registerFlag("CHECK_COMPUTATION_FOR_ERRORS",()=>Rr.getBool("DEBUG"));Rr.registerFlag("WRAP_TO_IMAGEBITMAP",()=>!1);Rr.registerFlag("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU",()=>!1);Rr.registerFlag("USE_SETTIMEOUTCUSTOM",()=>!1);function pa(e,t){let r=e;if(Kt(e))return t==="string"?[]:[e.length];if(qk(e)){let a=e.channels||"RGBA";return[e.height,e.width*a.length]}else if(Kk(e))return[e.buffer.size/(t==null?4:fc(t))];if(!Array.isArray(e))return[];let n=[];for(;Array.isArray(r)||Kt(r)&&t!=="string";)n.push(r.length),r=r[0];return Array.isArray(e)&&j().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&Qk(e,n,[]),n}function Qk(e,t,r){if(r=r||[],!Array.isArray(e)&&!Kt(e)){A(t.length===0,()=>`Element arr[${r.join("][")}] is a primitive, but should be an array/TypedArray of ${t[0]} elements`);return}A(t.length>0,()=>`Element arr[${r.join("][")}] should be a primitive, but is an array of ${e.length} elements`),A(e.length===t[0],()=>`Element arr[${r.join("][")}] should have ${t[0]} elements, but has ${e.length} elements`);let n=t.slice(1);for(let a=0;a<e.length;++a)Qk(e[a],n,r.concat(a))}function d0(e,t,r,n){if(e!=="string_or_numeric"){if(e==null)throw new Error("Expected dtype cannot be null.");if(e!=="numeric"&&e!==t||e==="numeric"&&t==="string")throw new Error(`Argument '${r}' passed to '${n}' must be ${e} tensor, but got ${t} tensor`)}}function C(e,t,r,n="numeric"){if(e instanceof Y())return d0(n,e.dtype,t,r),e;let a=dd(e);if(a!=="string"&&["bool","int32","float32"].indexOf(n)>=0&&(a=n),d0(n,a,t,r),e==null||!Kt(e)&&!Array.isArray(e)&&typeof e!="number"&&typeof e!="boolean"&&typeof e!="string"){let o=e==null?"null":e.constructor.name;throw new Error(`Argument '${t}' passed to '${r}' must be a Tensor or TensorLike, but got '${o}'`)}let s=pa(e,a);!Kt(e)&&!Array.isArray(e)&&(e=[e]);let i=a!=="string"?hf(e,a):hs(e,[],!0);return O.makeTensor(i,s,a)}function Zp(e,t,r,n="numeric"){if(!Array.isArray(e))throw new Error(`Argument ${t} passed to ${r} must be a \`Tensor[]\` or \`TensorLike[]\``);return e.map((a,s)=>C(a,`${t}[${s}]`,r,n))}var Ry="__op";function L(e){let t=Object.keys(e);if(t.length!==1)throw new Error(`Please provide an object with a single key (operation name) mapping to a function. Got an object with ${t.length} keys.`);let r=t[0],n=e[r];r.endsWith("_")&&(r=r.substring(0,r.length-1)),r=r+Ry;let a=(...s)=>{O.startScope(r);try{let i=n(...s);return Jc(i)&&console.error("Cannot return a Promise inside of tidy."),O.endScope(i),i}catch(i){throw O.endScope(null),i}};return Object.defineProperty(a,"name",{value:r,configurable:!0}),a}function DD(e,t){let r=C(e,"real","complex"),n=C(t,"imag","complex");wr(r.shape,n.shape,`real and imag shapes, ${r.shape} and ${n.shape}, must match in call to tf.complex().`);let a={real:r,imag:n};return O.runKernel(Yc,a)}var Aa=L({complex_:DD});function As(e,t,r,n){if(n==null)n=dd(e);else if(n==="complex64")throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(Kk(e)||qk(e)){if(n!=="float32"&&n!=="int32")throw new Error(`Creating tensor from GPU data only supports 'float32'|'int32' dtype, while the dtype is ${n}.`);return O.backend.createTensorFromGPUData(e,t||r,n)}if(!Kt(e)&&!Array.isArray(e)&&typeof e!="number"&&typeof e!="boolean"&&typeof e!="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(t!=null){Yr(t);let a=nt(t),s=nt(r);A(a===s,()=>`Based on the provided shape, [${t}], the tensor should have ${a} values but has ${s}`);for(let i=0;i<r.length;++i){let o=r[i],l=i===r.length-1?o!==nt(t.slice(i)):!0;A(r[i]===t[i]||!l,()=>`Error creating a new Tensor. Inferred shape (${r}) does not match the provided shape (${t}). `)}}return!Kt(e)&&!Array.isArray(e)&&(e=[e]),t=t||r,e=n!=="string"?hf(e,n):hs(e,[],!0),O.makeTensor(e,t,n)}function yr(e,t,r){let n=pa(e,r);return As(e,t,n,r)}var hi={float32:4,float16:2,int32:4,uint16:2,uint8:1,bool:1,complex64:8},Ma=class eI{static join(t){return new eI(t).slice()}constructor(t){if(this.shards=[],this.previousShardIndex=0,t==null||(t instanceof Array||(t=[t]),t=t.map(n=>Kt(n)?n.buffer:n),t.length===0))return;this.bufferUniformSize=t[0].byteLength;let r=0;for(let n=0;n<t.length;n++){let a=t[n];n!==t.length-1&&a.byteLength!==this.bufferUniformSize&&(this.bufferUniformSize=void 0);let s=r+a.byteLength;this.shards.push({buffer:a,start:r,end:s}),r=s}this.shards.length===0&&(this.byteLength=0),this.byteLength=this.shards[this.shards.length-1].end}slice(t=0,r=this.byteLength){if(this.shards.length===0)return new ArrayBuffer(0);if(t=isNaN(Number(t))?0:t,r=isNaN(Number(r))?0:r,t=Math.max(0,t),r=Math.min(this.byteLength,r),r<=t)return new ArrayBuffer(0);let n=this.findShardForByte(t);if(n===-1)throw new Error(`Could not find start shard for byte ${t}`);let a=r-t,s=new ArrayBuffer(a),i=new Uint8Array(s),o=0;for(let l=n;l<this.shards.length;l++){let p=this.shards[l],u=t+o-p.start,d=o,h=Math.min(r,p.end)-p.start,c=new Uint8Array(p.buffer,u,h-u);if(i.set(c,d),o+=c.length,r<p.end)break}return s}findShardForByte(t){if(this.shards.length===0||t<0||t>=this.byteLength)return-1;if(this.bufferUniformSize!=null)return this.previousShardIndex=Math.floor(t/this.bufferUniformSize),this.previousShardIndex;function r(a){return t<a.start?-1:t>=a.end?1:0}if(r(this.shards[this.previousShardIndex])===0)return this.previousShardIndex;let n=MD(this.shards,r);return n===-1?-1:(this.previousShardIndex=n,this.previousShardIndex)}};function MD(e,t){let r=0,n=e.length;for(;r<=n;){let a=Math.floor((n-r)/2)+r,s=t(e[a]);if(s===0)return a;s<0?n=a:r=a+1}return-1}function OD(){j().set("PROD",!0)}function LD(){j().set("DEBUG",!0)}function zD(){j().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")}function tI(e){j().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(e+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}function PD(){O.disposeVariables()}function wn(){return O}function dg(){return O.memory()}function BD(e){return O.profile(e)}function W(e,t){return O.tidy(e,t)}function Ce(e){Ay(e).forEach(t=>t.dispose())}function Pt(e){return O.keep(e)}function WD(e){return O.time(e)}function UD(e){return O.setBackend(e)}function VD(){return O.ready()}function rI(){return O.backendName}function GD(e){O.removeBackend(e)}function HD(e){return O.findBackend(e)}function jD(e){return O.findBackendFactory(e)}function ff(e,t,r=1){return O.registerBackend(e,t,r)}function Dy(){return O.backend}function qD(e,t){j().setPlatform(e,t)}var cs=4;async function KD(e,t){let r=[],n=[],a=Array.isArray(e)?e.map(i=>i.name):Object.keys(e);for(let i=0;i<a.length;++i){let o=a[i],l=Array.isArray(e)?e[i].tensor:e[o];if(l.dtype!=="float32"&&l.dtype!=="int32"&&l.dtype!=="bool"&&l.dtype!=="string"&&l.dtype!=="complex64")throw new Error(`Unsupported dtype in weight '${o}': ${l.dtype}`);let p={name:o,shape:l.shape,dtype:l.dtype};if(l.dtype==="string"){let u=new Promise(async d=>{let h=await l.bytes(),c=h.reduce((g,y)=>g+y.length,0)+cs*h.length,f=new Uint8Array(c),m=0;for(let g=0;g<h.length;g++){let y=h[g],b=new Uint8Array(new Uint32Array([y.length]).buffer);f.set(b,m),m+=cs,f.set(y,m),m+=y.length}d(f)});n.push(u)}else n.push(l.data());t!=null&&(p.group=t),r.push(p)}let s=await Promise.all(n);return{data:JD(s),specs:r}}function nI(e,t){let r=new Ma(e),n={},a=0;for(let s of t){let i=XD(s,(o,l)=>r.slice(a+o,a+l));n[s.name]=aI(s,r.slice(a,a+i)),a+=i}return n}function XD(e,t){let r=nt(e.shape),n;if("quantization"in e){let a=e.quantization;n=hi[a.dtype]}else if(e.dtype==="string"){let a=0;for(let s=0;s<r;s++)a+=cs+new Uint32Array(t(a,a+cs))[0];return a}else n=hi[e.dtype];return r*n}async function ZD(e,t){let r=nt(e.shape),n;if("quantization"in e){let a=e.quantization;n=hi[a.dtype]}else if(e.dtype==="string"){let a=0;for(let s=0;s<r;s++)a+=cs+new Uint32Array(await t(a,a+cs))[0];return a}else n=hi[e.dtype];return r*n}function aI(e,t){let r=e.name,n=e.dtype,a=e.shape,s=nt(a),i,o=0;if("quantization"in e){let l=e.quantization;if(l.dtype==="uint8"||l.dtype==="uint16"){if(!("min"in l&&"scale"in l))throw new Error(`Weight ${e.name} with quantization ${l.dtype} doesn't have corresponding metadata min and scale.`)}else if(l.dtype==="float16"){if(n!=="float32")throw new Error(`Weight ${e.name} is quantized with ${l.dtype} which only supports weights of type float32 not ${n}.`)}else throw new Error(`Weight ${e.name} has unknown quantization dtype ${l.dtype}. Supported quantization dtypes are: 'uint8', 'uint16', and 'float16'.`);let p=hi[l.dtype],u=l.dtype==="uint8"?new Uint8Array(t):new Uint16Array(t);if(n==="float32")if(l.dtype==="uint8"||l.dtype==="uint16"){i=new Float32Array(u.length);for(let d=0;d<u.length;d++){let h=u[d];i[d]=h*l.scale+l.min}}else if(l.dtype==="float16")i=aM()(u);else throw new Error(`Unsupported quantization type ${l.dtype} for weight type float32.`);else if(n==="int32"){if(l.dtype!=="uint8"&&l.dtype!=="uint16")throw new Error(`Unsupported quantization type ${l.dtype} for weight type int32.`);i=new Int32Array(u.length);for(let d=0;d<u.length;d++){let h=u[d];i[d]=Math.round(h*l.scale+l.min)}}else throw new Error(`Unsupported dtype in weight '${r}': ${n}`);o+=s*p}else if(n==="string"){let l=nt(e.shape);i=[];for(let p=0;p<l;p++){let u=new Uint32Array(t.slice(o,o+cs))[0];o+=cs;let d=new Uint8Array(t.slice(o,o+u));i.push(d),o+=u}}else{let l=hi[n];if(n==="float32")i=new Float32Array(t);else if(n==="int32")i=new Int32Array(t);else if(n==="bool")i=new Uint8Array(t);else if(n==="complex64"){i=new Float32Array(t);let p=new Float32Array(i.length/2),u=new Float32Array(i.length/2);for(let f=0;f<p.length;f++)p[f]=i[f*2],u[f]=i[f*2+1];let d=yr(p,a,"float32"),h=yr(u,a,"float32"),c=Aa(d,h);return d.dispose(),h.dispose(),c}else throw new Error(`Unsupported dtype in weight '${r}': ${n}`);o+=s*l}return yr(i,a,n)}async function h0(e,t,r){let n=new Uint8Array(t);for(;n.byteLength<r;){let{done:a,value:s}=await e.read();if(a&&s==null){let o=r-n.byteLength;throw new Error(`Reader is done but ${o} bytes are still expected`)}let i=new Uint8Array(n.length+s.byteLength);i.set(n,0),i.set(new Uint8Array(s),n.length),n=i}return n.buffer}async function sI(e,t){let r={},n=e.getReader(),a=new ArrayBuffer(0);for(let s of t){let i=await ZD(s,async(p,u)=>(a=await h0(n,a,u),a.slice(p,u)));a=await h0(n,a,i);let o=a.slice(0,i);a=a.slice(i);let l=aI(s,o);if(r[s.name]=l,rI()==="webgpu"){let p=Dy();"uploadToGPU"in p&&nt(l.shape)>=j().get("WEBGPU_CPU_HANDOFF_SIZE_THRESHOLD")&&p.uploadToGPU(l.dataId)}}return r}function JD(e){if(e===null)throw new Error(`Invalid input value: ${JSON.stringify(e)}`);let t=0,r=[];e.forEach(s=>{if(t+=s.byteLength,r.push(s.byteLength===s.buffer.byteLength?s:new s.constructor(s)),!(s instanceof Float32Array||s instanceof Int32Array||s instanceof Uint8Array))throw new Error(`Unsupported TypedArray subtype: ${s.constructor.name}`)});let n=new Uint8Array(t),a=0;return r.forEach(s=>{n.set(new Uint8Array(s.buffer),a),a+=s.byteLength}),n.buffer}var My=typeof Buffer<"u"&&(typeof Blob>"u"||typeof atob>"u"||typeof btoa>"u");function c0(e){return My?Buffer.byteLength(e,"utf8"):new Blob([e]).size}function YD(e){if(My)return Buffer.from(e).toString("base64");let t=new Uint8Array(e),r="";for(let n=0,a=t.length;n<a;n++)r+=String.fromCharCode(t[n]);return btoa(r)}function QD(e){if(My){let n=Buffer.from(e,"base64");return n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength)}let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;++n)r.set([t.charCodeAt(n)],n);return r.buffer}function eM(e){return Ma.join(e)}function f0(e){let t="/";for(e=e.trim();e.endsWith(t);)e=e.slice(0,e.length-1);let r=e.split(t);return r[r.length-1]}function iI(e,t){let r={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,weightsManifest:t};return e.signature!=null&&(r.signature=e.signature),e.userDefinedMetadata!=null&&(r.userDefinedMetadata=e.userDefinedMetadata),e.modelInitializer!=null&&(r.modelInitializer=e.modelInitializer),e.initializerSignature!=null&&(r.initializerSignature=e.initializerSignature),e.trainingConfig!=null&&(r.trainingConfig=e.trainingConfig),r}function oI(e,t,r){let n={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy};if(e.trainingConfig!=null&&(n.trainingConfig=e.trainingConfig),e.weightsManifest!=null){if(!t)throw new Error("modelJSON has weightsManifest but weightSpecs is null");if(!r)throw new Error("modelJSON has weightsManifest but weightData is null");n.weightSpecs=t,n.weightData=r}return e.signature!=null&&(n.signature=e.signature),e.userDefinedMetadata!=null&&(n.userDefinedMetadata=e.userDefinedMetadata),e.modelInitializer!=null&&(n.modelInitializer=e.modelInitializer),e.initializerSignature!=null&&(n.initializerSignature=e.initializerSignature),n}async function Oy(e,t){let r,n;return e.weightsManifest!=null&&([r,n]=await t(e.weightsManifest)),oI(e,r,n)}function Ld(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("Expected JSON model topology, received ArrayBuffer.");return{dateSaved:new Date,modelTopologyType:"JSON",modelTopologyBytes:e.modelTopology==null?0:c0(JSON.stringify(e.modelTopology)),weightSpecsBytes:e.weightSpecs==null?0:c0(JSON.stringify(e.weightSpecs)),weightDataBytes:e.weightData==null?0:new Ma(e.weightData).byteLength}}function hg(e){let t=[];for(let r of e)t.push(...r.weights);return t}function tM(){let e=r=>{let n=r<<13,a=0;for(;!(n&8388608);)a-=8388608,n<<=1;return n&=-8388609,a+=947912704,n|a},t=new Uint32Array(2048);t[0]=0;for(let r=1;r<1024;r++)t[r]=e(r);for(let r=1024;r<2048;r++)t[r]=939524096+(r-1024<<13);return t}function rM(){let e=new Uint32Array(64);e[0]=0,e[31]=1199570944,e[32]=2147483648,e[63]=3347054592;for(let t=1;t<31;t++)e[t]=t<<23;for(let t=33;t<63;t++)e[t]=2147483648+(t-32<<23);return e}function nM(){let e=new Uint32Array(64);for(let t=0;t<64;t++)e[t]=1024;return e[0]=e[32]=0,e}function aM(){let e=tM(),t=rM(),r=nM();return n=>{let a=new ArrayBuffer(4*n.length),s=new Uint32Array(a);for(let i=0;i<n.length;i++){let o=n[i],l=e[r[o>>10]+(o&1023)]+t[o>>10];s[i]=l}return new Float32Array(a)}}var fn=class $n{constructor(){this.saveRouters=[],this.loadRouters=[]}static getInstance(){return $n.instance==null&&($n.instance=new $n),$n.instance}static registerSaveRouter(t){$n.getInstance().saveRouters.push(t)}static registerLoadRouter(t){$n.getInstance().loadRouters.push(t)}static getSaveHandlers(t){return $n.getHandlers(t,"save")}static getLoadHandlers(t,r){return $n.getHandlers(t,"load",r)}static getHandlers(t,r,n){let a=[];return(r==="load"?$n.getInstance().loadRouters:$n.getInstance().saveRouters).forEach(s=>{let i=s(t,n);i!==null&&a.push(i)}),a}},sM=e=>fn.registerSaveRouter(e),iM=e=>fn.registerLoadRouter(e),oM=e=>fn.getSaveHandlers(e),lM=(e,t)=>fn.getLoadHandlers(e,t),cg="tensorflowjs",fg=1,ti="models_store",ns="model_info_store";function lI(){if(!j().getBool("IS_BROWSER"))throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");let e=typeof window>"u"?self:window,t=e.indexedDB||e.mozIndexedDB||e.webkitIndexedDB||e.msIndexedDB||e.shimIndexedDB;if(t==null)throw new Error("The current browser does not appear to support IndexedDB.");return t}function mg(e){let t=e.result;t.createObjectStore(ti,{keyPath:"modelPath"}),t.createObjectStore(ns,{keyPath:"modelPath"})}var ci=class{constructor(e){if(this.indexedDB=lI(),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((r,n)=>{let a=this.indexedDB.open(cg,fg);a.onupgradeneeded=()=>mg(a),a.onsuccess=()=>{let s=a.result;if(t==null){let i=s.transaction(ti,"readonly"),o=i.objectStore(ti).get(this.modelPath);o.onsuccess=()=>{if(o.result==null)return s.close(),n(new Error(`Cannot find model with path '${this.modelPath}' in IndexedDB.`));r(o.result.modelArtifacts)},o.onerror=l=>(s.close(),n(o.error)),i.oncomplete=()=>s.close()}else{t.weightData=Ma.join(t.weightData);let i=Ld(t),o=s.transaction(ns,"readwrite"),l=o.objectStore(ns),p;try{p=l.put({modelPath:this.modelPath,modelArtifactsInfo:i})}catch(d){return n(d)}let u;p.onsuccess=()=>{u=s.transaction(ti,"readwrite");let d=u.objectStore(ti),h;try{h=d.put({modelPath:this.modelPath,modelArtifacts:t,modelArtifactsInfo:i})}catch(c){return n(c)}h.onsuccess=()=>r({modelArtifactsInfo:i}),h.onerror=c=>{l=o.objectStore(ns);let f=l.delete(this.modelPath);f.onsuccess=()=>(s.close(),n(h.error)),f.onerror=m=>(s.close(),n(h.error))}},p.onerror=d=>(s.close(),n(p.error)),o.oncomplete=()=>{u==null?s.close():u.oncomplete=()=>s.close()}}},a.onerror=s=>n(a.error)})}};ci.URL_SCHEME="indexeddb://";var uI=e=>j().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(ci.URL_SCHEME)?uM(e.slice(ci.URL_SCHEME.length)):null;fn.registerSaveRouter(uI);fn.registerLoadRouter(uI);function uM(e){return new ci(e)}function pM(e){return e.startsWith(ci.URL_SCHEME)?e.slice(ci.URL_SCHEME.length):e}var dM=class{constructor(){this.indexedDB=lI()}async listModels(){return new Promise((e,t)=>{let r=this.indexedDB.open(cg,fg);r.onupgradeneeded=()=>mg(r),r.onsuccess=()=>{let n=r.result,a=n.transaction(ns,"readonly"),s=a.objectStore(ns).getAll();s.onsuccess=()=>{let i={};for(let o of s.result)i[o.modelPath]=o.modelArtifactsInfo;e(i)},s.onerror=i=>(n.close(),t(s.error)),a.oncomplete=()=>n.close()},r.onerror=n=>t(r.error)})}async removeModel(e){return e=pM(e),new Promise((t,r)=>{let n=this.indexedDB.open(cg,fg);n.onupgradeneeded=()=>mg(n),n.onsuccess=()=>{let a=n.result,s=a.transaction(ns,"readwrite"),i=s.objectStore(ns),o=i.get(e),l;o.onsuccess=()=>{if(o.result==null)return a.close(),r(new Error(`Cannot find model with path '${e}' in IndexedDB.`));{let p=i.delete(e),u=()=>{l=a.transaction(ti,"readwrite");let d=l.objectStore(ti).delete(e);d.onsuccess=()=>t(o.result.modelArtifactsInfo),d.onerror=h=>r(o.error)};p.onsuccess=u,p.onerror=d=>(u(),a.close(),r(o.error))}},o.onerror=p=>(a.close(),r(o.error)),s.oncomplete=()=>{l==null?a.close():l.oncomplete=()=>a.close()}},n.onerror=a=>r(n.error)})}},Na="/",ml="tensorflowjs_models",pI="info",hM="model_topology",cM="weight_specs",fM="weight_data",mM="model_metadata";function dI(e){return{info:[ml,e,pI].join(Na),topology:[ml,e,hM].join(Na),weightSpecs:[ml,e,cM].join(Na),weightData:[ml,e,fM].join(Na),modelMetadata:[ml,e,mM].join(Na)}}function hI(e){for(let t of Object.values(e))window.localStorage.removeItem(t)}function gM(e){let t=e.split(Na);if(t.length<3)throw new Error(`Invalid key format: ${e}`);return t.slice(1,t.length-1).join(Na)}function yM(e){return e.startsWith(fi.URL_SCHEME)?e.slice(fi.URL_SCHEME.length):e}var fi=class{constructor(e){if(!j().getBool("IS_BROWSER")||typeof window>"u"||typeof window.localStorage>"u")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=dI(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),r=JSON.stringify(e.weightSpecs),n=Ld(e),a=Ma.join(e.weightData);try{this.LS.setItem(this.keys.info,JSON.stringify(n)),this.LS.setItem(this.keys.topology,t),this.LS.setItem(this.keys.weightSpecs,r),this.LS.setItem(this.keys.weightData,YD(a));let s={format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,signature:e.signature!=null?e.signature:void 0,userDefinedMetadata:e.userDefinedMetadata!=null?e.userDefinedMetadata:void 0,modelInitializer:e.modelInitializer!=null?e.modelInitializer:void 0,initializerSignature:e.initializerSignature!=null?e.initializerSignature:void 0,trainingConfig:e.trainingConfig!=null?e.trainingConfig:void 0};return this.LS.setItem(this.keys.modelMetadata,JSON.stringify(s)),{modelArtifactsInfo:n}}catch{throw hI(this.keys),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={},r=JSON.parse(this.LS.getItem(this.keys.topology));if(r==null)throw new Error(`In local storage, the topology of model '${this.modelPath}' is missing.`);t.modelTopology=r;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 a=this.LS.getItem(this.keys.modelMetadata);if(a!=null){let i=JSON.parse(a);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),i.initializerSignature!=null&&(t.initializerSignature=i.initializerSignature),i.trainingConfig!=null&&(t.trainingConfig=i.trainingConfig)}let s=this.LS.getItem(this.keys.weightData);if(s==null)throw new Error(`In local storage, the binary weight values of model '${this.modelPath}' are missing.`);return t.weightData=QD(s),t}};fi.URL_SCHEME="localstorage://";var cI=e=>j().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(fi.URL_SCHEME)?bM(e.slice(fi.URL_SCHEME.length)):null;fn.registerSaveRouter(cI);fn.registerLoadRouter(cI);function bM(e){return new fi(e)}var xM=class{constructor(){A(j().getBool("IS_BROWSER"),()=>"Current environment is not a web browser"),A(typeof window>"u"||typeof window.localStorage<"u",()=>"Current browser does not appear to support localStorage"),this.LS=window.localStorage}async listModels(){let e={},t=ml+Na,r=Na+pI;for(let n=0;n<this.LS.length;++n){let a=this.LS.key(n);if(a.startsWith(t)&&a.endsWith(r)){let s=gM(a);e[s]=JSON.parse(this.LS.getItem(a))}}return e}async removeModel(e){e=yM(e);let t=dI(e);if(this.LS.getItem(t.info)==null)throw new Error(`Cannot find model at path '${e}'`);let r=JSON.parse(this.LS.getItem(t.info));return hI(t),r}},kl="://",fs=class qa{constructor(){this.managers={}}static getInstance(){return qa.instance==null&&(qa.instance=new qa),qa.instance}static registerManager(t,r){A(t!=null,()=>"scheme must not be undefined or null."),t.endsWith(kl)&&(t=t.slice(0,t.indexOf(kl))),A(t.length>0,()=>"scheme must not be an empty string.");let n=qa.getInstance();A(n.managers[t]==null,()=>`A model store manager is already registered for scheme '${t}'.`),n.managers[t]=r}static getManager(t){let r=qa.getInstance().managers[t];if(r==null)throw new Error(`Cannot find model manager for scheme '${t}'`);return r}static getSchemes(){return Object.keys(qa.getInstance().managers)}};function Zh(e){if(e.indexOf(kl)===-1)throw new Error(`The url string provided does not contain a scheme. Supported schemes are: ${fs.getSchemes().join(",")}`);return{scheme:e.split(kl)[0],path:e.split(kl)[1]}}async function fI(e,t,r=!1){A(e!==t,()=>`Old path and new path are the same: '${e}'`);let n=fn.getLoadHandlers(e);A(n.length>0,()=>`Copying failed because no load handler is found for source URL ${e}.`),A(n.length<2,()=>`Copying failed because more than one (${n.length}) load handlers for source URL ${e}.`);let a=n[0],s=fn.getSaveHandlers(t);A(s.length>0,()=>`Copying failed because no save handler is found for destination URL ${t}.`),A(s.length<2,()=>`Copying failed because more than one (${n.length}) save handlers for destination URL ${t}.`);let i=s[0],o=Zh(e).scheme,l=Zh(e).path,p=o===Zh(e).scheme,u=await a.load();r&&p&&await fs.getManager(o).removeModel(l);let d=await i.save(u);return r&&!p&&await fs.getManager(o).removeModel(l),d.modelArtifactsInfo}async function vM(){let e=fs.getSchemes(),t={};for(let r of e){let n=await fs.getManager(r).listModels();for(let a in n){let s=r+kl+a;t[s]=n[a]}}return t}async function wM(e){let t=Zh(e);return fs.getManager(t.scheme).removeModel(t.path)}async function kM(e,t){return fI(e,t,!1)}async function IM(e,t){return fI(e,t,!0)}var SM=class{constructor(){this.messageName="setTimeoutCustom",this.functionRefs=[],this.handledMessageCount=0,this.hasEventListener=!1}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)}setTimeoutCustom(e,t){if(typeof window>"u"||!j().getBool("USE_SETTIMEOUTCUSTOM")){setTimeout(e,t);return}this.functionRefs.push(e),setTimeout(()=>{window.postMessage({name:this.messageName,index:this.functionRefs.length-1},"*")},t),this.hasEventListener||(this.hasEventListener=!0,window.addEventListener("message",r=>{if(r.source===window&&r.data.name===this.messageName){r.stopPropagation();let n=this.functionRefs[r.data.index];n(),this.handledMessageCount++,this.handledMessageCount===this.functionRefs.length&&(this.functionRefs=[],this.handledMessageCount=0)}},!0))}isTypedArray(e){return Vk(e)}};if(j().get("IS_BROWSER")){j().setPlatform("browser",new SM);try{fs.registerManager(fi.URL_SCHEME,new xM)}catch{}try{fs.registerManager(ci.URL_SCHEME,new dM)}catch{}}var NM={importFetch:()=>bR()},Mm,_M=class{constructor(){this.util=xR(),this.textEncoder=new this.util.TextEncoder}fetch(e,t){return j().global.fetch!=null?j().global.fetch(e,t):(Mm==null&&(Mm=NM.importFetch()),Mm(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)}isTypedArray(e){return this.util.types.isFloat32Array(e)||this.util.types.isInt32Array(e)||this.util.types.isUint8Array(e)||this.util.types.isUint8ClampedArray(e)}};j().get("IS_NODE")&&!j().get("IS_BROWSER")&&j().setPlatform("node",new _M);function Le(e,t="float32",r){return t=t||"float32",Yr(e),new Dt(e,t,r)}function TM(e,t){let r=C(e,"x","cast");if(!Fk(t))throw new Error(`Failed to cast to unknown dtype ${t}`);if(t==="string"&&r.dtype!=="string"||t!=="string"&&r.dtype==="string")throw new Error("Only strings can be casted to strings");let n={x:r},a={dtype:t};return O.runKernel(Bi,n,a)}var se=L({cast_:TM});function CM(e){let t={x:C(e,"x","clone","string_or_numeric")};return O.runKernel(so,t)}var sa=L({clone_:CM});function Ly(e,t=!1){console.log(e.toString(t))}Jk();var EM={buffer:Le,cast:se,clone:sa,print:Ly};ND(EM);function $M(e,t){let r=C(e,"a","add"),n=C(t,"b","add");[r,n]=Nt(r,n);let a={a:r,b:n};return O.runKernel(Ts,a)}var J=L({add_:$M});function AM(e,t){let r=C(e,"a","floorDiv"),n=C(t,"b","floorDiv");[r,n]=Nt(r,n);let a={a:r,b:n};return O.runKernel(ro,a)}var mf=L({floorDiv_:AM});function FM(e,t){let r=C(e,"a","div"),n=C(t,"b","div");if([r,n]=Nt(r,n),r.dtype==="int32"&&n.dtype==="int32")return mf(r,n);let a={a:r,b:n},s={};return O.runKernel(Zi,a,s)}var fe=L({div_:FM});function RM(e,t){let r=C(e,"a","mul"),n=C(t,"b","mul");[r,n]=Nt(r,n);let a={a:r,b:n};return O.runKernel(ko,a)}var z=L({mul_:RM});function DM(e){let t=C(e,"x","abs");if(t.dtype==="complex64"){let r={x:t};return O.runKernel(md,r)}else{let r={x:t};return O.runKernel(Kl,r)}}var Ft=L({abs_:DM});function MM(e){let t={x:C(e,"x","acos")};return O.runKernel($i,t)}var zy=L({acos_:MM});function OM(e){let t={x:C(e,"x","acosh")};return O.runKernel(Ai,t)}var Py=L({acosh_:OM});function LM(e){A(Array.isArray(e),()=>"The argument passed to tf.addN() must be a list of tensors"),A(e.length>=1,()=>`Must pass at least one tensor to tf.addN(), but got ${e.length}`);let t=e.map((a,s)=>C(a,`tensors${s}`,"addN")),r=t[0];t.forEach(a=>{if(a.dtype!==r.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")}),t.forEach(a=>{if(!Da(a.shape,r.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});let n=t;return O.runKernel(Fi,n)}var mI=L({addN_:LM});function zM(e,t=null,r=!1){let n={x:C(e,"x","all","bool")},a={axis:t,keepDims:r};return O.runKernel(Xl,n,a)}var gf=L({all_:zM});function PM(e,t=null,r=!1){let n={x:C(e,"x","any","bool")},a={axis:t,keepDims:r};return O.runKernel(Zl,n,a)}var Jp=L({any_:PM});function BM(e,t=0){let r={x:C(e,"x","argMax")},n={axis:t};return O.runKernel(Jl,r,n)}var mi=L({argMax_:BM});function WM(e,t=0){let r={x:C(e,"x","argMin")},n={axis:t};return O.runKernel(Yl,r,n)}var By=L({argMin_:WM});function UM(e){let t={x:C(e,"x","asin")};return O.runKernel(Ri,t)}var Wy=L({asin_:UM});function VM(e){let t={x:C(e,"x","asinh")};return O.runKernel(Di,t)}var Uy=L({asinh_:VM});function GM(e){let t={x:C(e,"x","atan")};return O.runKernel(Mi,t)}var Vy=L({atan_:GM});function HM(e,t){let r=C(e,"a","atan2"),n=C(t,"b","atan2");[r,n]=Nt(r,n);let a={a:r,b:n};return O.runKernel(Li,a)}var Gy=L({atan2_:HM});function jM(e){let t={x:C(e,"x","atanh")};return O.runKernel(Oi,t)}var Hy=L({atanh_:jM});function qM(e,t,r,n,a="NHWC",s){let i=e[3],o=[...t,i],l=bI(a);return zd(e,o,r,s,n,null,null,l)}function gI(e,t,r,n,a,s,i="channelsLast"){let[o,l]=Yp(t),p;if(i==="channelsLast")p=[o,l,e[3],e[3]];else if(i==="channelsFirst")p=[o,l,e[1],e[1]];else throw new Error(`Unknown dataFormat ${i}`);return zd(e,p,r,n,a,s,!1,i)}function KM(e,t,r,n,a,s,i="NDHWC"){let[o,l,p]=gg(t),u,d;if(i==="NDHWC")d="channelsLast",u=[o,l,p,e[4],e[4]];else if(i==="NCDHW")d="channelsFirst",u=[o,l,p,e[1],e[1]];else throw new Error(`Unknown dataFormat ${i}`);return yI(e,u,r,n,a,!1,d,s)}function zd(e,t,r,n,a,s,i=!1,o="channelsLast"){let[l,p,u,d]=[-1,-1,-1,-1];if(o==="channelsLast")[l,p,u,d]=e;else if(o==="channelsFirst")[l,d,p,u]=e;else throw new Error(`Unknown dataFormat ${o}`);let[h,c,,f]=t,[m,g]=Yp(r),[y,b]=Yp(n),x=Il(h,y),v=Il(c,b),{padInfo:w,outHeight:N,outWidth:T}=JM(a,p,u,m,g,x,v,s,o),E=i?f*d:f,$;return o==="channelsFirst"?$=[l,E,N,T]:o==="channelsLast"&&($=[l,N,T,E]),{batchSize:l,dataFormat:o,inHeight:p,inWidth:u,inChannels:d,outHeight:N,outWidth:T,outChannels:E,padInfo:w,strideHeight:m,strideWidth:g,filterHeight:h,filterWidth:c,effectiveFilterHeight:x,effectiveFilterWidth:v,dilationHeight:y,dilationWidth:b,inShape:e,outShape:$,filterShape:t}}function yI(e,t,r,n,a,s=!1,i="channelsLast",o){let[l,p,u,d,h]=[-1,-1,-1,-1,-1];if(i==="channelsLast")[l,p,u,d,h]=e;else if(i==="channelsFirst")[l,h,p,u,d]=e;else throw new Error(`Unknown dataFormat ${i}`);let[c,f,m,,g]=t,[y,b,x]=gg(r),[v,w,N]=gg(n),T=Il(c,v),E=Il(f,w),$=Il(m,N),{padInfo:R,outDepth:F,outHeight:S,outWidth:D}=YM(a,p,u,d,y,b,x,T,E,$,o),P=s?g*h:g,U;return i==="channelsFirst"?U=[l,P,F,S,D]:i==="channelsLast"&&(U=[l,F,S,D,P]),{batchSize:l,dataFormat:i,inDepth:p,inHeight:u,inWidth:d,inChannels:h,outDepth:F,outHeight:S,outWidth:D,outChannels:P,padInfo:R,strideDepth:y,strideHeight:b,strideWidth:x,filterDepth:c,filterHeight:f,filterWidth:m,effectiveFilterDepth:T,effectiveFilterHeight:E,effectiveFilterWidth:$,dilationDepth:v,dilationHeight:w,dilationWidth:N,inShape:e,outShape:U,filterShape:t}}function XM(e,t,r,n,a){n==null&&(n=jy(e,t,r));let s=e[0],i=e[1],o=Qp((s-t+2*n)/r+1,a),l=Qp((i-t+2*n)/r+1,a);return[o,l]}function ZM(e,t,r,n,a,s){a==null&&(a=jy(e,t[0],n[0]));let i=[0,0,0,r];for(let o=0;o<3;o++)e[o]+2*a>=t[o]&&(i[o]=Qp((e[o]-t[o]+2*a)/n[o]+1,s));return i}function jy(e,t,r,n=1){let a=Il(t,n);return Math.floor((e[0]*(r-1)-r+a)/2)}function Yp(e){return typeof e=="number"?[e,e,e]:e.length===2?[e[0],e[1],1]:e}function gg(e){return typeof e=="number"?[e,e,e]:e}function Il(e,t){return t<=1?e:e+(e-1)*(t-1)}function JM(e,t,r,n,a,s,i,o,l){let p,u,d;if(typeof e=="number"){p={top:e,bottom:e,left:e,right:e,type:e===0?"VALID":"NUMBER"};let h=XM([t,r],s,n,e,o);u=h[0],d=h[1]}else if(e==="same"){u=Math.ceil(t/n),d=Math.ceil(r/a);let h=Math.max(0,(u-1)*n+s-t),c=Math.max(0,(d-1)*a+i-r),f=Math.floor(h/2),m=h-f,g=Math.floor(c/2),y=c-g;p={top:f,bottom:m,left:g,right:y,type:"SAME"}}else if(e==="valid")p={top:0,bottom:0,left:0,right:0,type:"VALID"},u=Math.ceil((t-s+1)/n),d=Math.ceil((r-i+1)/a);else if(typeof e=="object"){let h=l==="channelsLast"?e[1][0]:e[2][0],c=l==="channelsLast"?e[1][1]:e[2][1],f=l==="channelsLast"?e[2][0]:e[3][0],m=l==="channelsLast"?e[2][1]:e[3][1];p={top:h,bottom:c,left:f,right:m,type:h===0&&c===0&&f===0&&m===0?"VALID":"EXPLICIT"},u=Qp((t-s+h+c)/n+1,o),d=Qp((r-i+f+m)/a+1,o)}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:p,outHeight:u,outWidth:d}}function YM(e,t,r,n,a,s,i,o,l,p,u){let d,h,c,f;if(e==="valid"&&(e=0),typeof e=="number"){d={top:e,bottom:e,left:e,right:e,front:e,back:e,type:e===0?"VALID":"NUMBER"};let m=ZM([t,r,n,1],[o,l,p],1,[a,s,i],e,u);h=m[0],c=m[1],f=m[2]}else if(e==="same"){h=Math.ceil(t/a),c=Math.ceil(r/s),f=Math.ceil(n/i);let m=(h-1)*a+o-t,g=(c-1)*s+l-r,y=(f-1)*i+p-n,b=Math.floor(m/2),x=m-b,v=Math.floor(g/2),w=g-v,N=Math.floor(y/2),T=y-N;d={top:v,bottom:w,left:N,right:T,front:b,back:x,type:"SAME"}}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:d,outDepth:h,outHeight:c,outWidth:f}}function Qp(e,t){if(!t)return Math.trunc(e);switch(t){case"round":return Math.round(e);case"ceil":return Math.ceil(e);case"floor":return Math.floor(e);default:throw new Error(`Unknown roundingMode ${t}`)}}function ms(e){let[t,r,n]=Yp(e);return t===1&&r===1&&n===1}function fa(e,t){return ms(e)||ms(t)}function gi(e){return Yp(e).every(t=>t>0)}function bI(e){if(e==="NHWC")return"channelsLast";if(e==="NCHW")return"channelsFirst";throw new Error(`Unknown dataFormat ${e}`)}function kr(e,t,r){if(r!=null){if(typeof t=="string")throw Error(`Error in ${e}: pad must be an integer when using dimRoundingMode ${r} but got pad ${t}.`);if(typeof t=="number")A(_l(t),()=>`Error in ${e}: pad must be an integer when using dimRoundingMode ${r} but got pad ${t}.`);else if(typeof t=="object")t.forEach(n=>{n.forEach(a=>{A(_l(a),()=>`Error in ${e}: pad must be an integer when using dimRoundingMode ${r} but got pad ${a}.`)})});else throw Error(`Error in ${e}: Unknown padding parameter: ${t}`)}}function QM(e,t){let r={x:C(e,"x","reshape","string_or_numeric")},n={shape:t};return O.runKernel(Fu,r,n)}var B=L({reshape_:QM});function eO(e,t,r,n,a){let s=C(e,"x","avgPool","float32"),i=1;A(fa(r,i),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${r} and dilations '${i}'`);let o=s,l=!1;s.rank===3&&(l=!0,o=B(s,[1,s.shape[0],s.shape[1],s.shape[2]])),A(o.rank===4,()=>`Error in avgPool: x must be rank 4 but got rank ${o.rank}.`),kr("avgPool",n,a);let p={x:o},u={filterSize:t,strides:r,pad:n,dimRoundingMode:a},d=O.runKernel(zi,p,u);return d=se(d,s.dtype),l?B(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var Oa=L({avgPool_:eO});function tO(e,t,r,n,a,s="NDHWC"){let i=C(e,"x","avgPool3d","float32"),o=i,l=!1;i.rank===4&&(l=!0,o=B(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),A(o.rank===5,()=>`Error in avgPool3d: x must be rank 5 but got rank ${o.rank}.`),A(s==="NDHWC",()=>`Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of ${s}`),A(typeof r=="number"&&r>0||Array.isArray(r)&&r[0]>0&&r[1]>0&&r[2]>0,()=>`Error in avgPool3d: Stride must be > 0, but got '${r}'`),kr("avgPool3d",n,a);let p={x:o},u={filterSize:t,strides:r,pad:n,dimRoundingMode:a,dataFormat:s},d=O.runKernel(Ql,p,u);return d=se(d,o.dtype),l?B(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}var qy=L({avgPool3d_:tO});function rO(e,t=0){A(e.length>=1,()=>"Pass at least one tensor to concat");let r=Zp(e,"tensors","concat","string_or_numeric");if(r[0].dtype==="complex64"&&r.forEach(s=>{if(s.dtype!=="complex64")throw new Error(`Cannot concatenate complex64 tensors with a tensor
with dtype ${s.dtype}. `)}),r.length===1)return sa(r[0]);let n=r,a={axis:t};return O.runKernel(nu,n,a)}var lt=L({concat_:rO});function nO(e,t,r=!1,n=!1){let a=C(e,"a","matMul"),s=C(t,"b","matMul");[a,s]=Nt(a,s);let i={a,b:s},o={transposeA:r,transposeB:n};return O.runKernel(Pi,i,o)}var Me=L({matMul_:nO});function aO(e){let t={x:C(e,"x","sigmoid","float32")};return O.runKernel(Bo,t)}var In=L({sigmoid_:aO});function sO(e,t,r){let n=C(e,"x","slice","string_or_numeric");if(n.rank===0)throw new Error("Slicing scalar is not possible");let a={x:n},s={begin:t,size:r};return O.runKernel(Pu,a,s)}var Ve=L({slice_:sO});function iO(e){let t={x:C(e,"x","tanh","float32")};return O.runKernel(Ko,t)}var gs=L({tanh_:iO});function oO(e,t,r,n,a,s){let i=C(e,"forgetBias","basicLSTMCell"),o=C(t,"lstmKernel","basicLSTMCell"),l=C(r,"lstmBias","basicLSTMCell"),p=C(n,"data","basicLSTMCell"),u=C(a,"c","basicLSTMCell"),d=C(s,"h","basicLSTMCell"),h=lt([p,d],1),c=Me(h,o),f=J(c,l),m=f.shape[0],g=f.shape[1]/4,y=[m,g],b=Ve(f,[0,0],y),x=Ve(f,[0,g],y),v=Ve(f,[0,g*2],y),w=Ve(f,[0,g*3],y),N=J(z(In(b),gs(x)),z(u,In(J(i,v)))),T=z(gs(N),In(w));return[N,T]}var xI=L({basicLSTMCell_:oO});function lO(e,t,r){let n=C(e,"x","batchToSpaceND"),a=t.reduce((o,l)=>o*l);A(n.rank>=1+t.length,()=>`input rank is ${n.rank} but should be > than blockShape.length ${t.length}`),A(r.length===t.length,()=>`crops.length is ${r.length} but should be equal to blockShape.length ${t.length}`),A(n.shape[0]%a===0,()=>`input tensor batch is ${n.shape[0]} but is not divisible by the product of the elements of blockShape ${t.join(" * ")} === ${a}`);let s={x:n},i={blockShape:t,crops:r};return O.runKernel(eu,s,i)}var Pd=L({batchToSpaceND_:lO});function uO(e){let t;return e.rank===0||e.rank===1?t=B(e,[1,1,1,e.size]):e.rank===2?t=B(e,[1,1,e.shape[0],e.shape[1]]):e.rank===3?t=B(e,[1,e.shape[0],e.shape[1],e.shape[2]]):t=e,t}function pO(e,t,r,n,a,s){s==null&&(s=.001);let i=C(e,"x","batchNorm"),o=C(t,"mean","batchNorm"),l=C(r,"variance","batchNorm"),p;a!=null&&(p=C(a,"scale","batchNorm"));let u;n!=null&&(u=C(n,"offset","batchNorm")),A(o.rank===l.rank,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),A(u==null||o.rank===u.rank,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),A(p==null||o.rank===p.rank,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let d={x:uO(i),scale:p,offset:u,mean:o,variance:l},h={varianceEpsilon:s},c=O.runKernel(no,d,h);return B(c,i.shape)}var Xo=L({batchNorm_:pO});function dO(e,t,r,n,a,s){let i=C(e,"x","batchNorm"),o=C(t,"mean","batchNorm"),l=C(r,"variance","batchNorm"),p;a!=null&&(p=C(a,"scale","batchNorm"));let u;return n!=null&&(u=C(n,"offset","batchNorm")),A(i.rank===2,()=>`Error in batchNorm2D: x must be rank 2 but got rank ${i.rank}.`),A(o.rank===2||o.rank===1,()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${o.rank}.`),A(l.rank===2||l.rank===1,()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${l.rank}.`),p!=null&&A(p.rank===2||p.rank===1,()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${p.rank}.`),u!=null&&A(u.rank===2||u.rank===1,()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${u.rank}.`),Xo(i,o,l,u,p,s)}var Ky=L({batchNorm2d_:dO});function hO(e,t,r,n,a,s){let i=C(e,"x","batchNorm"),o=C(t,"mean","batchNorm"),l=C(r,"variance","batchNorm"),p;a!=null&&(p=C(a,"scale","batchNorm"));let u;return n!=null&&(u=C(n,"offset","batchNorm")),A(i.rank===3,()=>`Error in batchNorm3D: x must be rank 3 but got rank ${i.rank}.`),A(o.rank===3||o.rank===1,()=>`Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank ${o.rank}.`),A(l.rank===3||l.rank===1,()=>`Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank ${l.rank}.`),p!=null&&A(p.rank===3||p.rank===1,()=>`Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank ${p.rank}.`),u!=null&&A(u.rank===3||u.rank===1,()=>`Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank ${u.rank}.`),Xo(i,o,l,u,p,s)}var Xy=L({batchNorm3d_:hO});function cO(e,t,r,n,a,s){let i=C(e,"x","batchNorm"),o=C(t,"mean","batchNorm"),l=C(r,"variance","batchNorm"),p;a!=null&&(p=C(a,"scale","batchNorm"));let u;return n!=null&&(u=C(n,"offset","batchNorm")),A(i.rank===4,()=>`Error in batchNorm4D: x must be rank 4 but got rank ${i.rank}.`),A(o.rank===4||o.rank===1,()=>`Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank ${o.rank}.`),A(l.rank===4||l.rank===1,()=>`Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank ${l.rank}.`),p!=null&&A(p.rank===4||p.rank===1,()=>`Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank ${p.rank}.`),u!=null&&A(u.rank===4||u.rank===1,()=>`Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank ${u.rank}.`),Xo(i,o,l,u,p,s)}var Zy=L({batchNorm4d_:cO});function fO(e,t,r){let n=C(e,"x","bincount"),a=C(t,"weights","bincount");A(n.dtype==="int32",()=>`Error in bincount: input dtype must be int32, but got ${n.dtype}`),A(r>=0,()=>`size must be non-negative, but got ${r}.`),A(a.size===n.size||a.size===0,()=>`Error in bincount: weights must have the same size as input or0-length, but got input shape: ${n.shape}, weights shape: ${a.shape}.`);let s={x:n,weights:a},i={size:r};return O.runKernel(tu,s,i)}var Jy=L({bincount_:fO});function mO(e,t){let r=C(e,"x","bitwiseAnd"),n=C(t,"y","bitwiseAnd");if(!Da(r.shape,n.shape))throw new Error(`BitwiseAnd: Tensors must have the same shape. x: ${r.shape}, y: ${n.shape}`);if(r.dtype!=="int32"||n.dtype!=="int32")throw new Error(`BitwiseAnd: Only supports 'int32' values in tensor, found type of x: ${r.dtype} and type of y: ${n.dtype}`);let a={a:r,b:n};return O.runKernel(ru,a)}var vI=L({bitwiseAnd_:mO});function gO(e,t){let r=C(e,"s0","broadcastArgs","int32"),n=C(t,"s1","broadcastArgs","int32");if(r.rank!==1)throw new Error(`broadcastArgs(): first input must be a vector (rank=1). Has rank ${r.rank}`);if(n.rank!==1)throw new Error(`broadcastArgs(): second input must be a vector (rank=1). Has rank ${n.rank}`);let a={s0:r,s1:n};return O.runKernel(fd,a)}var wI=L({broadcastArgs_:gO});function yO(e,t){let r=C(e,"broadcastTo","x"),n=r.shape;if(Yr(t),t.length<r.rank)throw new Error(`broadcastTo(): shape.length=${t.length} < input.rank=${r.rank}.`);if(t.length>r.rank){let l=r.shape.slice();for(;l.length<t.length;)l.unshift(1);r=B(r,l)}let a=r.shape,s=Array.from(t);for(let l=t.length-1;l>=0;l--)if(a[l]===t[l])s[l]=1;else if(r.shape[l]!==1)throw new Error(`broadcastTo(): [${n}] cannot be broadcast to [${t}].`);if(s.map((l,p)=>l>1?p:-1).filter(l=>l>=0).length===0)return sa(r);let i={x:r},o={reps:s};return O.runKernel(Es,i,o)}var ai=L({broadcastTo_:yO});function bO(e){let t={x:C(e,"x","ceil","float32")};return O.runKernel(Wi,t)}var Yy=L({ceil_:bO});function qr(e,t,r){Yr(e),r=r||dd(t);let n={shape:e,value:t,dtype:r};return O.runKernel(bd,{},n)}function xO(e,t,r){let n=C(e,"x","clipByValue");if(A(t<=r,()=>`Error in clip: min (${t}) must be less than or equal to max (${r}).`),t===r)return qr(n.shape,t,n.dtype);let a={x:n},s={clipValueMin:t,clipValueMax:r};return O.runKernel(Cs,a,s)}var ur=L({clipByValue_:xO});function vO(e){return lt(e,0)}var Qy=L({concat1d_:vO});function wO(e,t){return lt(e,t)}var eb=L({concat2d_:wO});function kO(e,t){return lt(e,t)}var tb=L({concat3d_:kO});function IO(e,t){return lt(e,t)}var rb=L({concat4d_:IO});function SO(e,t,r,n,a="NHWC",s=[1,1],i){let o=C(e,"x","conv2d","float32"),l=C(t,"filter","conv2d","float32"),p=o,u=!1;o.rank===3&&(u=!0,p=B(o,[1,o.shape[0],o.shape[1],o.shape[2]])),A(p.rank===4,()=>`Error in conv2d: input must be rank 4, but got rank ${p.rank}.`),A(l.rank===4,()=>`Error in conv2d: filter must be rank 4, but got rank ${l.rank}.`),kr("conv2d",n,i);let d=a==="NHWC"?p.shape[3]:p.shape[1];A(d===l.shape[2],()=>`Error in conv2d: depth of input (${d}) must match input depth for filter ${l.shape[2]}.`),A(fa(r,s),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${r} and dilations '${s}'`),A(gi(s),()=>"Error in conv2D: Dilated rates should be larger than 0."),A(gi(r),()=>"Error in conv2D: Strides should be larger than 0.");let h={x:p,filter:l},c={strides:r,pad:n,dataFormat:a,dilations:s,dimRoundingMode:i},f=O.runKernel(Ui,h,c);return u?B(f,[f.shape[1],f.shape[2],f.shape[3]]):f}var br=L({conv2d_:SO});function NO(e,t,r,n,a="NWC",s=1,i){let o=C(e,"x","conv1d"),l=C(t,"filter","conv1d"),p=o,u=!1;o.rank===2&&(u=!0,p=B(o,[1,o.shape[0],o.shape[1]])),A(p.rank===3,()=>`Error in conv1d: input must be rank 3, but got rank ${p.rank}.`),A(l.rank===3,()=>`Error in conv1d: filter must be rank 3, but got rank ${l.rank}.`),kr("conv1d",n,i),A(p.shape[2]===l.shape[1],()=>`Error in conv1d: depth of input (${p.shape[2]}) must match input depth for filter ${l.shape[1]}.`),A(fa(r,s),()=>`Error in conv1D: Either stride or dilation must be 1. Got stride ${r} and dilation '${s}'`),A(gi(s),()=>"Error in conv1D: Dilated rates should be larger than 0."),A(gi(r),()=>"Error in conv1D: Stride should be larger than 0."),A(a==="NWC",()=>`Error in conv1d: got dataFormat of ${a} but only NWC is currently supported.`);let d=B(l,[1,l.shape[0],l.shape[1],l.shape[2]]),h=B(p,[p.shape[0],1,p.shape[1],p.shape[2]]),c=br(h,d,[1,r],n,"NHWC",[1,s],i);return u?B(c,[c.shape[2],c.shape[3]]):B(c,[c.shape[0],c.shape[2],c.shape[3]])}var yf=L({conv1d_:NO});function _O(e,t,r,n,a,s="NHWC",i){A(e.length===t.rank,()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`);let o=e,l=t,p=!1;t.rank===3&&(p=!0,l=B(t,[1,t.shape[0],t.shape[1],t.shape[2]]),o=[1,e[0],e[1],e[2]]),A(o.length===4,()=>`Error in conv2dDerInput: inShape must be length 4, but got length ${o.length}.`),A(l.rank===4,()=>`Error in conv2dDerInput: dy must be rank 4, but got rank ${l.rank}`),A(r.rank===4,()=>`Error in conv2dDerInput: filter must be rank 4, but got rank ${r.rank}`);let u=s==="NHWC"?o[3]:o[1],d=s==="NHWC"?l.shape[3]:l.shape[1];A(u===r.shape[2],()=>`Error in conv2dDerInput: depth of input (${u}) must match input depth for filter ${r.shape[2]}.`),A(d===r.shape[3],()=>`Error in conv2dDerInput: depth of output (${d}) must match output depth for filter ${r.shape[3]}.`),kr("conv2dDerInput",a,i);let h={dy:l,filter:r},c={strides:n,pad:a,dataFormat:s,dimRoundingMode:i,inputShape:o},f=O.runKernel(Vi,h,c);return p?B(f,[f.shape[1],f.shape[2],f.shape[3]]):f}var nb=L({conv2DBackpropInput_:_O});function TO(e,t,r,n,a,s){let i=C(e,"x","conv2dTranspose"),o=C(t,"filter","conv2dTranspose");return nb(r,i,o,n,a,"NHWC",s)}var bf=L({conv2dTranspose_:TO});function CO(e,t,r,n,a="NDHWC",s=[1,1,1]){let i=C(e,"x","conv3d"),o=C(t,"filter","conv3d"),l=i,p=!1;i.rank===4&&(p=!0,l=B(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),A(l.rank===5,()=>`Error in conv3d: input must be rank 5, but got rank ${l.rank}.`),A(o.rank===5,()=>`Error in conv3d: filter must be rank 5, but got rank ${o.rank}.`),A(l.shape[4]===o.shape[3],()=>`Error in conv3d: depth of input (${l.shape[4]}) must match input depth for filter ${o.shape[3]}.`),A(fa(r,s),()=>`Error in conv3D: Either strides or dilations must be 1. Got strides ${r} and dilations '${s}'`),A(a==="NDHWC",()=>`Error in conv3d: got dataFormat of ${a} but only NDHWC is currently supported.`),A(gi(s),()=>"Error in conv3D: Dilated rates should be larger than 0."),A(gi(r),()=>"Error in conv3D: Strides should be larger than 0.");let u={x:l,filter:o},d={strides:r,pad:n,dataFormat:a,dilations:s},h=O.runKernel(Gi,u,d);return p?B(h,[h.shape[1],h.shape[2],h.shape[3],h.shape[4]]):h}var ab=L({conv3d_:CO});function EO(e,t,r,n,a){A(e.length===t.rank,()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`);let s=e,i=t,o=!1;t.rank===4&&(o=!0,i=B(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]]),s=[1,e[0],e[1],e[2],e[3]]);let l=s[4],p=i.shape[4];A(s.length===5,()=>`Error in conv3dDerInput: inShape must be length 5, but got length ${s.length}.`),A(i.rank===5,()=>`Error in conv3dDerInput: dy must be rank 5, but got rank ${i.rank}`),A(r.rank===5,()=>`Error in conv3dDerInput: filter must be rank 5, but got rank ${r.rank}`),A(l===r.shape[3],()=>`Error in conv3dDerInput: depth of input (${l}) must match input depth for filter ${r.shape[3]}.`),A(p===r.shape[4],()=>`Error in conv3dDerInput: depth of output (${p}) must match output depth for filter ${r.shape[4]}.`);let u={dy:i,filter:r},d={pad:a,strides:n,inputShape:s},h=O.runKernel(su,u,d);return o?B(h,[h.shape[1],h.shape[2],h.shape[3],h.shape[4]]):h}var kI=L({conv3DBackpropInput_:EO});function $O(e,t,r,n,a){let s=C(e,"x","conv3dTranspose"),i=C(t,"filter","conv3dTranspose");return kI(r,s,i,n,a)}var sb=L({conv3dTranspose_:$O});function AO(e){let t={x:C(e,"x","cos","float32")};return O.runKernel(Hi,t)}var Bd=L({cos_:AO});function FO(e){let t={x:C(e,"x","cosh","float32")};return O.runKernel(ji,t)}var xf=L({cosh_:FO});function RO(e,t=0,r=!1,n=!1){let a={x:C(e,"x","cumprod")},s={axis:t,exclusive:r,reverse:n};return O.runKernel(iu,a,s)}var ed=L({cumprod_:RO});function DO(e,t=0,r=!1,n=!1){let a={x:C(e,"x","cumsum")},s={axis:t,exclusive:r,reverse:n};return O.runKernel(qi,a,s)}var vf=L({cumsum_:DO});function MO(e,t,r,n=!1){let a=C(e,"x","denseBincount"),s=C(t,"weights","denseBincount");A(a.dtype==="int32",()=>`Error in denseBincount: input dtype must be int32, but got ${a.dtype}`),A(a.rank<=2,()=>`Error in denseBincount: input must be at most rank 2, but got rank ${a.rank}.`),A(r>=0,()=>`size must be non-negative, but got ${r}.`),A(s.size===a.size||s.size===0,()=>`Error in denseBincount: weights must have the same shape as x or 0-length, but got x shape: ${a.shape}, weights shape: ${s.shape}.`);let i={x:a,weights:s},o={size:r,binaryOutput:n};return O.runKernel(gd,i,o)}var xc=L({denseBincount_:MO});function OO(e,t,r="NHWC"){let n=C(e,"x","depthToSpace","float32"),a=r==="NHWC"?n.shape[1]:n.shape[2],s=r==="NHWC"?n.shape[2]:n.shape[3],i=r==="NHWC"?n.shape[3]:n.shape[1];A(t>1,()=>`blockSize should be > 1 for depthToSpace, but was: ${t}`),A(a*t>=0,()=>`Negative dimension size caused by overflow when multiplying
${a} and ${t} for depthToSpace with input shape
${n.shape}`),A(s*t>=0,()=>`Negative dimension size caused by overflow when multiplying
${s} and ${t} for depthToSpace with input shape
${n.shape}`),A(i%(t*t)===0,()=>`Dimension size must be evenly divisible by ${t*t} but is ${i} for depthToSpace with input shape ${n.shape}`);let o={x:n},l={blockSize:t,dataFormat:r};return O.runKernel(lu,o,l)}var ib=L({depthToSpace_:OO});function LO(e,t,r,n,a="NHWC",s=[1,1],i){let o=C(e,"x","depthwiseConv2d","float32"),l=C(t,"filter","depthwiseConv2d","float32"),p=o,u=!1;o.rank===3&&(u=!0,p=B(o,[1,o.shape[0],o.shape[1],o.shape[2]])),A(p.rank===4,()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${p.rank}.`),A(l.rank===4,()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${l.rank}.`);let d=a==="NHWC"?p.shape[3]:p.shape[1];A(d===l.shape[2],()=>`Error in depthwiseConv2d: number of input channels (${d}) must match the inChannels dimension in filter ${l.shape[2]}.`),kr("depthwiseConv2d",n,i);let h={x:p,filter:l},c={strides:r,pad:n,dataFormat:a,dilations:s,dimRoundingMode:i},f=O.runKernel(Ki,h,c);return u?B(f,[f.shape[1],f.shape[2],f.shape[3]]):f}var Zo=L({depthwiseConv2d_:LO});function zO(e){let t={x:C(e,"x","diag")};return O.runKernel(yd,t)}var II=L({diag_:zO});function PO(e,t,r,n,a=[1,1],s="NHWC"){let i=C(e,"x","dilation2d"),o=C(t,"filter","dilation2d");A(i.rank===3||i.rank===4,()=>`Error in dilation2d: input must be rank 3 or 4, but got rank ${i.rank}.`),A(o.rank===3,()=>`Error in dilation2d: filter must be rank 3, but got rank ${o.rank}.`),A(s==="NHWC",()=>`Error in dilation2d: Only NHWC is currently supported, but got dataFormat of ${s}`);let l=i,p=!1;i.rank===3&&(l=B(i,[1,i.shape[0],i.shape[1],i.shape[2]]),p=!0),A(l.shape[3]===o.shape[2],()=>`Error in dilation2d: input and filter must have the same depth: ${l.shape[3]} vs ${o.shape[2]}`);let u={x:l,filter:o},d={strides:r,pad:n,dilations:a},h=O.runKernel(Xi,u,d);return p?B(h,[h.shape[1],h.shape[2],h.shape[3]]):h}var ob=L({dilation2d_:PO}),Zu={};Ee(Zu,{assertAndGetBroadcastShape:()=>ut,getBroadcastDims:()=>SI,getReductionAxes:()=>Ot});function SI(e,t){let r=e.length,n=[];for(let a=0;a<r;a++){let s=r-1-a,i=e[s]||1;(t[t.length-1-a]||1)>1&&i===1&&n.unshift(s)}return n}function Ot(e,t){let r=[];for(let n=0;n<t.length;n++){let a=e[e.length-n-1],s=t.length-n-1,i=t[s];(a==null||a===1&&i>1)&&r.unshift(s)}return r}function ut(e,t){let r=Math.max(e.length,t.length),n=new Array(r);for(let a=0;a<r;a++){let s=e[e.length-a-1];s==null&&(s=1);let i=t[t.length-a-1];if(i==null&&(i=1),s===1)n[r-a-1]=i;else if(i===1)n[r-a-1]=s;else if(s!==i){let o=`Operands could not be broadcast together with shapes ${e} and ${t}.`;throw Error(o)}else n[r-a-1]=s}return n}function BO(e,t){let r=C(e,"a","equal","string_or_numeric"),n=C(t,"b","equal","string_or_numeric");[r,n]=Nt(r,n),ut(r.shape,n.shape);let a={a:r,b:n};return O.runKernel(pu,a)}var Kr=L({equal_:BO});function WO(e,t,r){let n=C(t,"a","where"),a=C(r,"b","where"),s=C(e,"condition","where","bool"),i=ut(ut(s.shape,n.shape),a.shape),o=ai(s,i),l=ai(n,i),p=ai(a,i),u={condition:o,t:l,e:p};return O.runKernel(zu,u)}var Jt=L({where_:WO});function UO(e){let t={x:C(e,"x","zerosLike")};return O.runKernel(Ku,t)}var He=L({zerosLike_:UO});function VO(e,t){let r=C(e,"a","div"),n=C(t,"b","div");[r,n]=Nt(r,n);let a=fe(r,n),s=He(a),i=Kr(n,s);return Jt(i,s,a)}var lb=L({divNoNan_:VO});function GO(e,t){let r=C(e,"t1","dot"),n=C(t,"t2","dot");A((r.rank===1||r.rank===2)&&(n.rank===1||n.rank===2),()=>`Error in dot: inputs must all be rank 1 or 2, but got ranks ${r.rank} and ${n.rank}.`);let a=r.rank===1?r.size:r.shape[1],s=n.rank===1?n.size:n.shape[0];if(A(a===s,()=>`Error in dot: inner dimensions of inputs must match, but got ${a} and ${s}.`),r.rank===1&&n.rank===1){let i=B(r,[1,-1]),o=B(n,[-1,1]),l=Me(i,o);return B(l,[])}else if(r.rank===1&&n.rank===2){let i=B(r,[1,-1]),o=B(n,[n.shape[0],n.shape[1]]),l=Me(i,o);return B(l,[l.size])}else if(r.rank===2&&n.rank===1){let i=B(n,[-1,1]),o=Me(r,i);return B(o,[o.size])}else{let i=B(n,[n.shape[0],n.shape[1]]);return Me(r,i)}}var ub=L({dot_:GO});function HO(e,...t){let r=t.map((a,s)=>C(a,`tensors${s}`,"einsum")),n={equation:e};return O.runKernel(nf,r,n)}var Js=L({einsum_:HO});function jO(e){let t={x:C(e,"x","elu","float32")};return O.runKernel(Ji,t)}var Ju=L({elu_:jO});function qO(e,t){let r=C(e,"x","ensureShape","string_or_numeric");if(!Ck(r.shape,t))throw new Error(`EnsureShape: Shape of tensor ${r.shape} is not compatible with expected shape ${t}`);return e}var NI=L({ensureShape_:qO});function KO(e){let t=C(e,"x","erf");A(t.dtype==="int32"||t.dtype==="float32",()=>"Input dtype must be `int32` or `float32`."),t.dtype==="int32"&&(t=se(t,"float32"));let r={x:t};return O.runKernel(Yi,r)}var wf=L({erf_:KO});function pb(e,t){for(let r=0;r<e.length;++r)if(e[e.length-r-1]!==t-1-r)return!1;return!0}function _I(e,t,r){let n=e.length+t.length,a=[],s=0,i=0;for(let o=0;o<n;o++)r.indexOf(o)===-1?a.push(e[s++]):a.push(t[i++]);return a}function TI(e,t){let r=[],n=e.length;for(let s=0;s<n;s++)t.indexOf(s)===-1&&r.push(e[s]);let a=t.map(s=>e[s]);return[r,a]}function yi(e,t){let r=t.map(n=>1);return _I(e,r,t)}function XO(e,t,r){A(pb(t,r),()=>`${e} supports only inner-most axes for now. Got axes ${t} and rank-${r} input.`)}function CI(e,t){if(pb(e,t))return null;let r=[];for(let n=0;n<t;++n)e.indexOf(n)===-1&&r.push(n);return e.forEach(n=>r.push(n)),r}function db(e){return e.map((t,r)=>[r,t]).sort((t,r)=>t[1]-r[1]).map(t=>t[0])}function ZO(e,t){let r=[];for(let n=t-e;n<t;++n)r.push(n);return r}function JO(e,t=null,r=!1){let n={x:C(e,"x","max")},a={reductionIndices:t,keepDims:r};return O.runKernel(fo,n,a)}var hn=L({max_:JO});function YO(e,t=null,r=!1){let n={x:C(e,"x","min")},a={axis:t,keepDims:r};return O.runKernel(bo,n,a)}var $l=L({min_:YO});function QO(e,t){let r=C(e,"base","pow"),n=C(t,"exp","pow");[r,n]=Nt(r,n);let a={a:r,b:n};return O.runKernel(No,a)}var da=L({pow_:QO});function we(e,t){if((Kt(e)&&t!=="string"||Array.isArray(e))&&t!=="complex64")throw new Error("Error creating a new Scalar: value must be a primitive (number|boolean|string)");if(t==="string"&&Kt(e)&&!(e instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");return As(e,[],[],t)}function e3(e){let t={x:C(e,"x","sqrt","float32")};return O.runKernel(Uo,t)}var Yt=L({sqrt_:e3});function t3(e){let t=C(e,"x","square"),r={};return O.runKernel("Square",{x:t},r)}var ot=L({square_:t3});function r3(e,t=null,r=!1){let n=C(e,"x","sum");n.dtype==="bool"&&(n=se(n,"int32"));let a={x:n},s={axis:t,keepDims:r};return O.runKernel(Vo,a,s)}var ge=L({sum_:r3});function n3(e,t="euclidean",r=null,n=!1){e=C(e,"x","norm");let a=EI(e,t,r),s=a.shape;if(n){let i=_n(r,e.shape);s=yi(a.shape,i)}return B(a,s)}function EI(e,t,r=null){if(e.rank===0)return Ft(e);if(e.rank!==1&&r===null)return EI(B(e,[-1]),t,r);if(e.rank===1||typeof r=="number"||Array.isArray(r)&&r.length===1){if(t===1)return ge(Ft(e),r);if(t===1/0)return hn(Ft(e),r);if(t===-1/0)return $l(Ft(e),r);if(t==="euclidean"||t===2)return Yt(ge(da(Ft(e),we(2,"int32")),r));throw new Error(`Error in norm: invalid ord value: ${t}`)}if(Array.isArray(r)&&r.length===2){if(t===1)return hn(ge(Ft(e),r[0]),r[1]-1);if(t===1/0)return hn(ge(Ft(e),r[1]),r[0]);if(t===-1/0)return $l(ge(Ft(e),r[1]),r[0]);if(t==="fro"||t==="euclidean")return Yt(ge(ot(e),r));throw new Error(`Error in norm: invalid ord value: ${t}`)}throw new Error(`Error in norm: invalid axis: ${r}`)}var Yu=L({norm_:n3});function a3(e,t=null,r=!1){return Yu(e,"euclidean",t,r)}var hb=L({euclideanNorm_:a3});function s3(e){let t={x:C(e,"x","exp")};return O.runKernel(Qi,t)}var pr=L({exp_:s3});function i3(e,t=0){let r=C(e,"x","expandDims","string_or_numeric");A(t<=r.rank,()=>"Axis must be <= rank of the tensor");let n={input:r},a={dim:t};return O.runKernel(du,n,a)}var Xt=L({expandDims_:i3});function o3(e){let t={x:C(e,"x","expm1")};return O.runKernel(eo,t)}var cb=L({expm1_:o3});function l3(e,t){let r=C(e,"x","tile","string_or_numeric");A(r.rank===t.length,()=>`Error in transpose: rank of input ${r.rank} must match length of reps ${t}.`);let n={x:r},a={reps:t};return O.runKernel(Es,n,a)}var jr=L({tile_:l3});function u3(e,t,r,n="float32"){t==null&&(t=e);let a=Le([e,t],n),s=e<=t?e:t;for(let o=0;o<s;++o)a.set(1,o,o);let i=B(a.toTensor(),[e,t]);if(r==null)return i;if(r.length===1)return jr(Xt(i,0),[r[0],1,1]);if(r.length===2)return jr(Xt(Xt(i,0),0),[r[0],r[1],1,1]);if(r.length===3)return jr(Xt(Xt(Xt(i,0),0),0),[r[0],r[1],r[2],1,1]);throw new Error(`eye() currently supports only 1D and 2D batchShapes, but received ${r.length}D.`)}var kf=L({eye_:u3});function p3(e){let t={x:C(e,"x","floor","float32")};return O.runKernel(to,t)}var Qu=L({floor_:p3});function d3(e,t,r=0,n=0){let a=C(e,"x","gather"),s=C(t,"indices","gather","int32"),i={x:a,indices:s},o={axis:r,batchDims:n};return O.runKernel(cu,i,o)}var ep=L({gather_:d3});function h3(e,t){let r=C(e,"a","greater","string_or_numeric"),n=C(t,"b","greater","string_or_numeric");[r,n]=Nt(r,n),ut(r.shape,n.shape);let a={a:r,b:n};return O.runKernel(mu,a)}var Ir=L({greater_:h3});function c3(e,t){let r=C(e,"a","greaterEqual","string_or_numeric"),n=C(t,"b","greaterEqual","string_or_numeric");[r,n]=Nt(r,n),ut(r.shape,n.shape);let a={a:r,b:n};return O.runKernel(ao,a)}var La=L({greaterEqual_:c3});function f3(e){let t={input:C(e,"input","imag")};return O.runKernel(of,t)}var Wd=L({imag_:f3});function m3(e){let t={x:C(e,"x","isFinite")};return O.runKernel(io,t)}var fb=L({isFinite_:m3});function g3(e){let t={x:C(e,"x","isInf")};return O.runKernel(oo,t)}var mb=L({isInf_:g3});function y3(e){let t={x:C(e,"x","isNaN")};return O.runKernel(lo,t)}var gb=L({isNaN_:y3});function b3(e,t=.2){let r={x:C(e,"x","leakyRelu")},n={alpha:t};return O.runKernel(uo,r,n)}var Ud=L({leakyRelu_:b3});function x3(e,t){let r=C(e,"a","less","string_or_numeric"),n=C(t,"b","less","string_or_numeric");[r,n]=Nt(r,n),ut(r.shape,n.shape);let a={a:r,b:n};return O.runKernel(gu,a)}var Al=L({less_:x3});function v3(e,t){let r=C(e,"a","lessEqual","string_or_numeric"),n=C(t,"b","lessEqual","string_or_numeric");[r,n]=Nt(r,n),ut(r.shape,n.shape);let a={a:r,b:n};return O.runKernel(yu,a)}var Fs=L({lessEqual_:v3});function $I(e,t,r){if(r<=0)throw new Error("The number of values should be positive.");let n={start:e,stop:t,num:r};return O.runKernel(bu,{},n)}function w3(e,t=5,r=1,n=1,a=.5){let s=C(e,"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(_l(t),()=>`Error in localResponseNormalization: depthRadius must be an integer but got depthRadius ${t}.`);let i=s,o=!1;s.rank===3&&(o=!0,i=B(s,[1,s.shape[0],s.shape[1],s.shape[2]]));let l={x:i},p={depthRadius:t,bias:r,alpha:n,beta:a},u=O.runKernel(co,l,p);return o?B(u,[u.shape[1],u.shape[2],u.shape[3]]):u}var yb=L({localResponseNormalization_:w3});function k3(e){let t={x:C(e,"x","log","float32")};return O.runKernel(po,t)}var Xr=L({log_:k3});function I3(e){let t={x:C(e,"x","log1p")};return O.runKernel(ho,t)}var Vd=L({log1p_:I3});function S3(e){return A(ds(e),()=>"The f passed in grad(f) must be a function"),(t,r)=>{let n=C(t,"x","tf.grad","string_or_numeric"),a=r!=null?C(r,"dy","tf.grad"):null;return O.tidy(()=>{let{value:s,grads:i}=O.gradients(()=>e(n),[n],a);return a!=null&&wr(s.shape,a.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),If(i),i[0]})}}function N3(e){return A(ds(e),()=>"The f passed in grads(f) must be a function"),(t,r)=>{A(Array.isArray(t),()=>"The args passed in grads(f)(args) must be an array of `Tensor`s or `TensorLike`s");let n=Zp(t,"args","tf.grads","string_or_numeric"),a=r!=null?C(r,"dy","tf.grads"):null;return O.tidy(()=>{let{value:s,grads:i}=O.gradients(()=>e(...n),n,a);return a!=null&&wr(s.shape,a.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),If(i),i})}}function _3(e){return A(ds(e),()=>"The f passed in valueAndGrad(f) must be a function"),(t,r)=>{A(t instanceof ze,()=>"The x passed in valueAndGrad(f)(x) must be a tensor"),A(r==null||r instanceof ze,()=>"The dy passed in valueAndGrad(f)(x, dy) must be a tensor");let{grads:n,value:a}=O.gradients(()=>e(t),[t],r);return If(n),{grad:n[0],value:a}}}function T3(e){return A(ds(e),()=>"The f passed in valueAndGrads(f) must be a function"),(t,r)=>{A(Array.isArray(t)&&t.every(a=>a instanceof ze),()=>"The args passed in valueAndGrads(f)(args) must be array of tensors"),A(r==null||r instanceof ze,()=>"The dy passed in valueAndGrads(f)(args, dy) must be a tensor");let n=O.gradients(()=>e(...t),t,r);return r!=null&&wr(n.value.shape,r.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),If(n.grads),n}}function AI(e,t){A(ds(e),()=>"The f passed in variableGrads(f) must be a function"),A(t==null||Array.isArray(t)&&t.every(p=>p instanceof di),()=>"The varList passed in variableGrads(f, varList) must be an array of variables");let r=t!=null;if(!r){t=[];for(let p in O.registeredVariables)t.push(O.registeredVariables[p])}let n=r?t.filter(p=>!p.trainable):null,a=t.length;t=t.filter(p=>p.trainable),A(t.length>0,()=>`variableGrads() expects at least one of the input variables to be trainable, but none of the ${a} variables is trainable.`);let s=!0,{value:i,grads:o}=O.gradients(e,t,null,s);A(o.some(p=>p!=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(i.rank===0,()=>`The f passed in variableGrads(f) must return a scalar, but it returned a rank-${i.rank} tensor`);let l={};return t.forEach((p,u)=>{o[u]!=null&&(l[p.name]=o[u])}),n!=null&&n.forEach(p=>l[p.name]=null),{value:i,grads:l}}function ha(e){return O.customGrad(e)}function If(e){if(e.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 C3(e){let t={x:C(e,"x","neg")};return O.runKernel(Nu,t)}var gt=L({neg_:C3});function E3(e){let t={x:C(e,"x","softplus")};return O.runKernel(Wo,t)}var Jo=L({softplus_:E3});function $3(e){let t=C(e,"x","logSigmoid");return ha(r=>({value:gt(Jo(gt(r))),gradFunc:n=>z(n,In(gt(r)))}))(t)}var bb=L({logSigmoid_:$3});function A3(e,t){let r=C(e,"a","sub"),n=C(t,"b","sub");[r,n]=Nt(r,n);let a={a:r,b:n};return O.runKernel(jo,a)}var de=L({sub_:A3});function F3(e,t=-1){let r=C(e,"logits","logSoftmax");if(t===-1&&(t=r.rank-1),t!==r.rank-1)throw Error(`Log Softmax along a non-last dimension is not yet supported. Logits was rank ${r.rank} and axis was ${t}`);return ha((n,a)=>{let s=hn(n,t,!0),i=de(n,s),o=de(se(i,"float32"),Xr(ge(pr(i),t,!0)));return a([o]),{value:o,gradFunc:(l,p)=>{let[u]=p,d=!0,h=pr(u);return de(l,z(ge(l,t,d),h))}}})(r)}var Sf=L({logSoftmax_:F3});function R3(e,t=null,r=!1){let n=C(e,"x","logSumExp"),a=_n(t,n.shape),s=hn(n,a,!0),i=de(n,s),o=pr(i),l=ge(o,a),p=Xr(l),u=J(B(s,p.shape),p);if(r){let d=yi(u.shape,a);return B(u,d)}return u}var Gd=L({logSumExp_:R3});function D3(e,t){let r=C(e,"a","logicalAnd","bool"),n=C(t,"b","logicalAnd","bool");ut(r.shape,n.shape);let a={a:r,b:n};return O.runKernel(xu,a)}var Nn=L({logicalAnd_:D3});function M3(e){let t={x:C(e,"x","logicalNot","bool")};return O.runKernel(vu,t)}var Hd=L({logicalNot_:M3});function O3(e,t){let r=C(e,"a","logicalOr","bool"),n=C(t,"b","logicalOr","bool");ut(r.shape,n.shape);let a={a:r,b:n};return O.runKernel(wu,a)}var Nf=L({logicalOr_:O3});function L3(e,t){let r=C(e,"a","logicalXor","bool"),n=C(t,"b","logicalXor","bool");return ut(r.shape,n.shape),Nn(Nf(e,t),Hd(Nn(e,t)))}var xb=L({logicalXor_:L3}),Ah=2147483648;function z3(e,t,r="left"){let n=C(e,"sortedSequence","searchSorted"),a=C(t,"values","searchSorted"),s=n.shape[n.shape.length-1],i=a.shape[a.shape.length-1],o=B(n,[-1,s]),l=B(a,[-1,i]);if(o.rank<2)throw new Error("Sorted input argument must be at least 2-dimensional");if(o.shape[0]!==l.shape[0])throw new Error("Leading dimension of 'sortedSequence' and 'values' must match.");if(nt(l.shape)>=Ah)throw new Error(`values tensor size must less than ${Ah}`);if(o.shape[1]>=Ah)throw new Error(`trailing dim_size must less than ${Ah} for int32 output type, was ${o.shape[1]}`);let p={sortedSequence:o,values:l},u={side:r};return O.runKernel(Lu,p,u)}var _f=L({searchSorted_:z3});function FI(e,t){return _f(e,t,"left")}function P3(e,t,r,n,a){let s=C(e,"x","maxPool"),i=1,o=s,l=!1;s.rank===3&&(l=!0,o=B(s,[1,s.shape[0],s.shape[1],s.shape[2]])),A(o.rank===4,()=>`Error in maxPool: input must be rank 4 but got rank ${o.rank}.`),A(fa(r,i),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${r} and dilations '${i}'`),kr("maxPool",n,a);let p={x:o},u={filterSize:t,strides:r,pad:n,dimRoundingMode:a},d=O.runKernel(go,p,u);return l?B(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var jt=L({maxPool_:P3});function B3(e,t=[1,1,1],r,n,a,s="NDHWC"){let i=C(e,"x","maxPool3d"),o=i,l=!1;i.rank===4&&(l=!0,o=B(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),A(o.rank===5,()=>`Error in maxPool3d: x must be rank 5 but got rank ${o.rank}.`),A(s==="NDHWC",()=>`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${s}`),kr("maxPool3d",n,a);let p={x:o},u={filterSize:t,strides:r,pad:n,dimRoundingMode:a,dataFormat:s},d=O.runKernel(Iu,p,u);return l?B(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}var vb=L({maxPool3d_:B3});function W3(e,t,r,n,a=!1){let s={x:C(e,"x","maxPoolWithArgmax")},i={filterSize:t,strides:r,pad:n,includeBatchInIndex:a},o=O.runKernel(wd,s,i);return{result:o[0],indexes:o[1]}}var RI=L({maxPoolWithArgmax_:W3});function U3(e,t){let r=C(e,"a","maximum"),n=C(t,"b","maximum");[r,n]=Nt(r,n),r.dtype==="bool"&&(r=se(r,"int32"),n=se(n,"int32")),ut(r.shape,n.shape);let a={a:r,b:n};return O.runKernel(mo,a)}var ma=L({maximum_:U3});function V3(e,t=null,r=!1){let n={x:C(e,"x","mean")},a={axis:t,keepDims:r};return O.runKernel(yo,n,a)}var kt=L({mean_:V3});function It(e,t="float32"){if(Yr(e),t==="complex64"){let n=It(e,"float32"),a=It(e,"float32");return Aa(n,a)}let r=Zc(nt(e),t);return O.makeTensor(r,e,t)}function $r(e,t="float32"){if(Yr(e),t==="complex64"){let n=$r(e,"float32"),a=It(e,"float32");return Aa(n,a)}let r=Ty(nt(e),t);return O.makeTensor(r,e,t)}function DI(e,t,{indexing:r="xy"}={}){if(r!=="xy"&&r!=="ij")throw new TypeError(`${r} is not a valid third argument to meshgrid`);if(e===void 0)return[];let n=C(e,"x","meshgrid",e instanceof ze?e.dtype:"float32");if(t===void 0)return[n];let a=C(t,"y","meshgrid",t instanceof ze?t.dtype:"float32"),s=nt(n.shape),i=nt(a.shape);return r==="xy"?(n=B(n,[1,-1]),a=B(a,[-1,1]),[Me($r([i,1],n.dtype),n),Me(a,$r([1,s],a.dtype))]):(n=B(n,[-1,1]),a=B(a,[1,-1]),[Me(n,$r([1,i],n.dtype)),Me($r([s,1],a.dtype),a)])}function G3(e,t){let r=C(e,"a","minimum"),n=C(t,"b","minimum");[r,n]=Nt(r,n),r.dtype==="bool"&&(r=se(r,"int32"),n=se(n,"int32")),ut(r.shape,n.shape);let a={a:r,b:n};return O.runKernel(xo,a)}var ys=L({minimum_:G3});function H3(e,t,r){A(r==="reflect"||r==="symmetric",()=>`Invalid mode. Mode must be either reflect or symmetric. Got ${r}.`);let n=C(e,"x","mirrorPad");if(n.rank===0)throw new Error("mirrorPad(scalar) is not defined. Pass non-scalar to mirrorPad");A(t.length===n.rank,()=>`Padding doesn't match input. Must be ${n.rank}. Got ${t.length}.`);let a=r==="reflect"?1:0;for(let o=0;o<n.rank;o++)A(t[o].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),A(t[o][0]>=0&&t[o][0]<=n.shape[o]-a&&t[o][1]>=0&&t[o][1]<=n.shape[o]-a,()=>`Padding in dimension ${o} cannot be greater than or equal to ${n.shape[o]-a} or less than 0 for input of shape ${n.shape}`);let s={paddings:t,mode:r},i={x:n};return O.runKernel(vo,i,s)}var wb=L({mirrorPad_:H3});function j3(e,t){let r=C(e,"a","mod"),n=C(t,"b","mod");[r,n]=Nt(r,n);let a={a:r,b:n};return O.runKernel(wo,a)}var kb=L({mod_:j3});function q3(e,t=null,r=!1){e=C(e,"x","moments");let n=_n(t,e.shape),a=kt(e,n,r),s=a.shape;r||(s=yi(a.shape,n));let i=ot(de(se(e,"float32"),B(a,s))),o=kt(i,n,r);return{mean:a,variance:o}}var jd=L({moments_:q3});function K3(e,t,r,n){let a=C(t,"data","multiRNNCell"),s=Zp(r,"c","multiRNNCell"),i=Zp(n,"h","multiRNNCell"),o=a,l=[];for(let d=0;d<e.length;d++){let h=e[d](o,s[d],i[d]);l.push(h[0]),l.push(h[1]),o=h[1]}let p=[],u=[];for(let d=0;d<l.length;d+=2)p.push(l[d]),u.push(l[d+1]);return[p,u]}var MI=L({multiRNNCell_:K3});function X3(e,t,r,n=!1){let a=C(e,"logits","multinomial"),s=a.size,i=a.rank;if(s<2)throw new Error(`Error in multinomial: you need at least 2 outcomes, but got ${s}.`);if(i>2)throw new Error(`Rank of probabilities must be 1 or 2, but is ${i}`);r=r||Math.random();let o={logits:i===1?B(a,[1,-1]):a},l={numSamples:t,seed:r,normalized:n},p=O.runKernel(Su,o,l);return i===1?B(p,[p.size]):p}var OI=L({multinomial_:X3});function Z3(e,t){let r=C(e,"a","notEqual","string_or_numeric"),n=C(t,"b","notEqual","string_or_numeric");[r,n]=Nt(r,n),ut(r.shape,n.shape);let a={a:r,b:n};return O.runKernel(_u,a)}var bi=L({notEqual_:Z3});function J3(e,t,r=1,n=0,a="int32"){if(t<2)throw new Error(`Error in oneHot: depth must be >=2, but it is ${t}`);let s={indices:C(e,"indices","oneHot","int32")},i={dtype:a,depth:t,onValue:r,offValue:n};return O.runKernel(Io,s,i)}var Fl=L({oneHot_:J3});function Y3(e){let t={x:C(e,"x","onesLike")};return O.runKernel($u,t)}var Zr=L({onesLike_:Y3});function Q3(e,t){let r=C(e,"v1","outerProduct"),n=C(t,"v2","outerProduct");A(r.rank===1&&n.rank===1,()=>`Error in outerProduct: inputs must be rank 1, but got ranks ${r.rank} and ${n.rank}.`);let a=B(r,[-1,1]),s=B(n,[1,-1]);return Me(a,s)}var LI=L({outerProduct_:Q3});function eL(e,t,r=0){let n=C(e,"x","pad");if(n.rank===0)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");let a={paddings:t,constantValue:r},s={x:n};return O.runKernel(So,s,a)}var jn=L({pad_:eL});function tL(e,t,r=0){return A(t.length===2,()=>"Invalid number of paddings. Must be length of 2."),jn(e,[t],r)}var zI=L({pad1d_:tL});function rL(e,t,r=0){return A(t.length===2&&t[0].length===2&&t[1].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),jn(e,t,r)}var PI=L({pad2d_:rL});function nL(e,t,r=0){return A(t.length===3&&t[0].length===2&&t[1].length===2&&t[2].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),jn(e,t,r)}var BI=L({pad3d_:nL});function aL(e,t,r=0){return A(t.length===4&&t[0].length===2&&t[1].length===2&&t[2].length===2&&t[3].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),jn(e,t,r)}var WI=L({pad4d_:aL});function sL(e,t,r){let n=C(e,"x","spaceToBatchND");A(n.rank>=1+t.length,()=>`input rank ${n.rank} should be > than [blockShape] ${t.length}`),A(r.length===t.length,()=>`paddings.shape[0] ${r.length} must be equal to [blockShape] ${t.length}`),A(n.shape.reduce((i,o,l)=>l>0&&l<=t.length?i&&(o+r[l-1][0]+r[l-1][1])%t[l-1]===0:i,!0),()=>`input spatial dimensions ${n.shape.slice(1)} with paddings ${r.toString()} must be divisible by blockShapes ${t.toString()}`);let a={x:n},s={blockShape:t,paddings:r};return O.runKernel(Bu,a,s)}var qd=L({spaceToBatchND_:sL});function iL(e,t,r,n,a,s,i){a==null&&(a=[1,1]),s==null&&(s=1),n===0&&(n="valid");let o=C(e,"x","maxPool"),l=o,p=!1;o.rank===3&&(p=!0,l=B(o,[1,o.shape[0],o.shape[1],o.shape[2]])),A(fa(s,a),()=>`Error in pool: Either strides or dilations must be 1. Got strides ${s} and dilations '${a}'`);let u=gI(l.shape,t,s,a,n),d=[u.dilationHeight,u.dilationWidth],h;n==="same"?h=lL([u.filterHeight,u.filterWidth],d):h=[[0,0],[0,0]];let c=d[0]===1&&d[1]===1,[f,m]=oL([u.inHeight,u.inWidth],d,h),g=c?n:"valid",y=c?l:qd(l,d,f),b=(r==="avg"?()=>Oa(y,t,s,g,i):()=>jt(y,t,s,g,i))(),x=c?b:Pd(b,d,m);return p?B(x,[x.shape[1],x.shape[2],x.shape[3]]):x}function oL(e,t,r){let n=r.map(u=>u[0]),a=r.map(u=>u[1]),s=e.concat(n,a),i=t.map((u,d)=>(u-s[d]%u)%u),o=a.map((u,d)=>u+i[d]),l=t.map((u,d)=>[n[d],o[d]]),p=t.map((u,d)=>[0,i[d]]);return[l,p]}function lL(e,t){let r=e.map((s,i)=>s+(s-1)*(t[i]-1)).map(s=>s-1),n=r.map(s=>Math.floor(s/2)),a=r.map((s,i)=>s-n[i]);return r.map((s,i)=>[n[i],a[i]])}var Ib=L({pool_:iL});function uL(e,t){let r=C(e,"x","prelu"),n=C(t,"alpha","prelu"),a={x:r,alpha:n};return O.runKernel(_o,a)}var Kd=L({prelu_:uL});function pL(e,t=null,r=!1){let n=C(e,"x","prod");n.dtype==="bool"&&(n=se(n,"int32"));let a={x:n},s={axis:t,keepDims:r};return O.runKernel(To,a,s)}var Sb=L({prod_:pL});function dL(e,t,r,n){let a=e.map((u,d)=>C(u,`tensors${d}`,"raggedGather","int32")),s=C(t,"paramsDenseValues","raggedGather"),i=C(r,"indices","raggedGather","int32"),o={paramsNestedSplits:a,paramsDenseValues:s,indices:i},l={outputRaggedRank:n},p=O.runKernel(lf,o,l);return{outputNestedSplits:p.slice(0,p.length-1),outputDenseValues:p[p.length-1]}}var UI=L({raggedGather_:dL});function hL(e,t,r){let n=C(e,"starts","raggedRange"),a=C(t,"limits","raggedRange",n.dtype),s=C(r,"deltas","raggedRange",n.dtype),i={starts:n,limits:a,deltas:s},o=O.runKernel(uf,i);return{rtNestedSplits:o[0],rtDenseValues:o[1]}}var VI=L({raggedRange_:hL});function cL(e,t,r,n,a){let s=C(e,"shape","raggedTensorToTensor","int32"),i=C(t,"values","raggedTensorToTensor"),o=C(r,"defaultValue","raggedTensorToTensor",i.dtype),l=n.map((d,h)=>C(d,`tensors${h}`,"raggedTensorToTensor","int32")),p={shape:s,values:i,defaultValue:o,rowPartitionTensors:l},u={rowPartitionTypes:a};return O.runKernel(pf,p,u)}var GI=L({raggedTensorToTensor_:cL});function fL(e,t,r){Yr(e);let n=nt(e),a=null;if(r==null||r==="float32")a=new Float32Array(n);else if(r==="int32")a=new Int32Array(n);else if(r==="bool")a=new Uint8Array(n);else throw new Error(`Unknown data type ${r}`);for(let s=0;s<n;s++)a[s]=t();return O.makeTensor(a,e,r)}var HI=L({rand_:fL}),Nb=_s(Kc()),jI={};Ee(jI,{TEST_EPSILON_FLOAT16:()=>qI,createVideoElement:()=>kL,encodeStrings:()=>KI,expectArrayBuffersEqual:()=>wL,expectArraysClose:()=>gL,expectArraysEqual:()=>bL,expectNumbersClose:()=>xL,expectPromiseToFail:()=>yL,expectValuesInRange:()=>vL,play:()=>IL,testEpsilon:()=>_b});var mL=.001,qI=.1;function gL(e,t,r){return r==null&&(r=_b()),yg(e,t,(n,a)=>Tb(n,a,r))}function _b(){return O.backend.floatPrecision()===32?mL:qI}function yg(e,t,r){let n=!0;if((Kt(e)||Kt(t))&&(n=!1),Kt(e)&&Kt(t)&&(n=!0),n){let i=e.constructor.name,o=t.constructor.name;if(i!==o)throw new Error(`Arrays are of different type. Actual: ${i}. Expected: ${o}`)}if(Array.isArray(e)&&Array.isArray(t)){let i=pa(e),o=pa(t);if(!Da(i,o))throw new Error(`Arrays have different shapes. Actual: [${i}]. Expected: [${o}]`)}let a=Kt(e)?e:hs(e),s=Kt(t)?t:hs(t);if(a.length!==s.length)throw new Error(`Arrays have different lengths actual: ${a.length} vs expected: ${s.length}.
Actual: ${a}.
Expected: ${s}.`);for(let i=0;i<s.length;++i){let o=a[i],l=s[i];if(!r(o,l))throw new Error(`Arrays differ: actual[${i}] = ${o}, expected[${i}] = ${l}.
Actual: ${a}.
Expected: ${s}.`)}typeof expect<"u"&&expect().nothing()}function yL(e,t){e().then(()=>t.fail(),()=>t()),typeof expect<"u"&&expect().nothing()}function bL(e,t){let r=typeof t=="string"||typeof t=="number"||typeof t=="boolean"?[t]:t;return rs(e)||rs(e[0])||rs(t)||rs(t[0])?yg(e,r,(n,a)=>n==a):yg(e,t,(n,a)=>Tb(n,a,0))}function xL(e,t,r){if(r==null&&(r=_b()),!Tb(e,t,r))throw new Error(`Numbers differ: actual === ${e}, expected === ${t}`);typeof expect<"u"&&expect().nothing()}function Tb(e,t,r){return!isFinite(e)&&!isFinite(t)?!0:!(isNaN(e)||isNaN(t)||Math.abs(e-t)>r)}function vL(e,t,r){for(let n=0;n<e.length;n++)if(e[n]<t||e[n]>r)throw new Error(`Value out of range:${e[n]} low: ${t}, high: ${r}`)}function wL(e,t){let r=new Float32Array(e),n=new Float32Array(t);if(r.length!==n.length)throw new Error(`Expected ArrayBuffer to be of length ${n.length}, but it was ${r.length}`);for(let a=0;a<n.length;a++)if(r[a]!==n[a])throw new Error(`Expected ArrayBuffer value at ${a} to be ${n[a]} but got ${r[a]} instead`)}function KI(e){for(let t=0;t<e.length;t++){let r=e[t];Array.isArray(r)?KI(r):e[t]=Md(r)}return e}function kL(e){let t=document.createElement("video");return"playsInline"in t&&(t.playsInline=!0),t.muted=!0,t.loop=!0,t.style.position="fixed",t.style.left="0px",t.style.top="0px",t.preload="auto",t.appendChild(e),new Promise(r=>{t.addEventListener("loadeddata",n=>r(t)),t.load()})}async function IL(e){await e.play(),"requestVideoFrameCallback"in e&&await new Promise(t=>{e.requestVideoFrameCallback(t)})}var Cb=class{constructor(e,t,r,n,a){this.mean=e,this.stdDev=t,this.dtype=r,this.nextVal=NaN,this.truncated=n,this.truncated&&(this.upper=this.mean+this.stdDev*2,this.lower=this.mean-this.stdDev*2);let s=a||Math.random();this.random=Nb.alea(s.toString())}nextValue(){if(!isNaN(this.nextVal)){let n=this.nextVal;return this.nextVal=NaN,n}let e,t,r=!1;for(;!r;){let n,a,s;do n=2*this.random()-1,a=2*this.random()-1,s=n*n+a*a;while(s>=1||s===0);let i=Math.sqrt(-2*Math.log(s)/s);e=this.mean+this.stdDev*n*i,t=this.mean+this.stdDev*a*i,(!this.truncated||this.isValidTruncated(e))&&(r=!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}},SL=class{constructor(e,t,r,n){this.alpha=e,this.beta=1/t,this.dtype=r;let a=n||Math.random();this.randu=Nb.alea(a.toString()),this.randn=new Cb(0,1,r,!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,r,n,a,s;for(;;){do n=this.randn.nextValue(),s=1+this.c*n;while(s<=0);if(s*=s*s,e=n*n,t=1-.331*e*e,r=.5*e+this.d*(1-s+Math.log(s)),a=this.randu(),a<t||Math.log(a)<r)break}return s=1/this.beta*this.d*s,this.alpha<1&&(s*=Math.pow(this.randu(),1/this.alpha)),this.convertValue(s)}convertValue(e){return this.dtype==="float32"?e:Math.round(e)}},NL=class{constructor(e=0,t=1,r,n){if(this.canReturnFloat=()=>this.dtype==null||this.dtype==="float32",this.min=e,this.range=t-e,this.dtype=r,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=Nb.alea(n)}convertValue(e){return this.canReturnFloat()?e:Math.round(e)}nextValue(){return this.convertValue(this.min+this.range*this.random())}};function _L(e,t,r=1,n="float32",a){if(Yr(e),r==null&&(r=1),n==null&&(n="float32"),n!=="float32"&&n!=="int32")throw new Error(`Unsupported data type ${n}`);let s=new SL(t,r,n,a),i=Le(e,n);for(let o=0;o<i.values.length;o++)i.values[o]=s.nextValue();return i.toTensor()}var XI=L({randomGamma_:_L});function TL(e,t=0,r=1,n,a){if(Yr(e),n!=null&&n==="bool")throw new Error(`Unsupported data type ${n}`);let s=new Cb(t,r,n,!1,a),i=Le(e,n);for(let o=0;o<i.values.length;o++)i.values[o]=s.nextValue();return i.toTensor()}var Tf=L({randomNormal_:TL});function CL(e,t,r){if(t!=null&&t==="bool")throw new Error(`Unsupported data type ${t}`);return Tf(e,0,1,t,r)}var ZI=L({randomStandardNormal_:CL});function EL(e,t=0,r=1,n="float32",a){Yr(e);let s=Le(e,n),i=new NL(t,r,null,a);for(let o=0;o<s.values.length;o++)s.values[o]=i.nextValue();return s.toTensor()}var Rs=L({randomUniform_:EL});function $L(e,t,r,n){return Rs(e,t,r,"int32",n)}var JI=L({randomUniformInt_:$L});function xi(e,t,r=1,n="float32"){if(r===0)throw new Error("Cannot have a step of zero");let a={start:e,stop:t,step:r,dtype:n};return O.runKernel(kd,{},a)}function AL(e){let t={input:C(e,"input","real")};return O.runKernel(df,t)}var Rl=L({real_:AL});function FL(e){let t={x:C(e,"x","reciprocal")};return O.runKernel(Co,t)}var Eb=L({reciprocal_:FL});function RL(e){let t={x:C(e,"x","relu")};return O.runKernel(Eo,t)}var rt=L({relu_:RL});function DL(e){let t={x:C(e,"x","relu6")};return O.runKernel(Fo,t)}var Cf=L({relu6_:DL});function ML(e,t){let r={x:C(e,"x","reverse")},n={dims:t};return O.runKernel(Ro,r,n)}var mn=L({reverse_:ML});function OL(e){let t=C(e,"x","reverse");return A(t.rank===1,()=>`Error in reverse1D: x must be rank 1 but got rank ${t.rank}.`),mn(t,0)}var YI=L({reverse1d_:OL});function LL(e,t){let r=C(e,"x","reverse");return A(r.rank===2,()=>`Error in reverse2D: x must be rank 2 but got rank ${r.rank}.`),mn(r,t)}var QI=L({reverse2d_:LL});function zL(e,t){let r=C(e,"x","reverse");return A(r.rank===3,()=>`Error in reverse3D: x must be rank 3 but got rank ${r.rank}.`),mn(r,t)}var eS=L({reverse3d_:zL});function PL(e,t){let r=C(e,"x","reverse");return A(r.rank===4,()=>`Error in reverse4D: x must be rank 4 but got rank ${r.rank}.`),mn(r,t)}var tS=L({reverse4d_:PL});function BL(e){let t={x:C(e,"x","round")};return O.runKernel(Do,t)}var Ef=L({round_:BL});function WL(e){let t={x:C(e,"x","rsqrt","float32")};return O.runKernel(Mo,t)}var $f=L({rsqrt_:WL});function UL(e){let t={x:C(e,"x","selu")};return O.runKernel(Oo,t)}var Af=L({selu_:UL});function VL(e,t,r,n,a,s=[1,1],i="NHWC"){let o=C(e,"x","separableConv2d"),l=C(t,"depthwiseFilter","separableConv2d"),p=C(r,"pointwiseFilter","separableConv2d"),u=o,d=!1;if(o.rank===3&&(d=!0,u=B(o,[1,o.shape[0],o.shape[1],o.shape[2]])),i==="NCHW")throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");A(u.rank===4,()=>`Error in separableConv2d: input must be rank 4, but got rank ${u.rank}.`),A(l.rank===4,()=>`Error in separableConv2d: depthwise filter must be rank 4, but got rank ${l.rank}.`),A(p.rank===4,()=>`Error in separableConv2d: pointwise filter must be rank 4, but got rank ${l.rank}.`),A(p.shape[0]===1,()=>`Error in separableConv2d: the first dimension of pointwise filter must be 1, but got ${p.shape[0]}.`),A(p.shape[1]===1,()=>`Error in separableConv2d: the second dimension of pointwise filter must be 1, but got ${p.shape[1]}.`);let h=l.shape[2],c=l.shape[3];A(p.shape[2]===h*c,()=>`Error in separableConv2d: the third dimension of pointwise filter must be ${h*c}, but got ${p.shape[2]}.`);let f=Zo(u,l,n,a,i,s),m=br(f,p,1,"valid",i);return d?B(m,[m.shape[1],m.shape[2],m.shape[3]]):m}var tp=L({separableConv2d_:VL});async function GL(e,t){let r=C(e,"x","setdiff1d"),n=C(t,"y","setdiff1d");A(r.dtype===n.dtype,()=>`x and y should have the same dtype, but got x (${r.dtype}) and y (${n.dtype}).`),A(r.rank===1,()=>`x should be 1D tensor, but got x (${r.shape}).`),A(n.rank===1,()=>`y should be 1D tensor, but got y (${n.shape}).`);let a=await r.data(),s=await n.data(),i=new Set(s),o=0;for(let u=0;u<a.length;u++)i.has(a[u])||o++;let l=new Dt([o],r.dtype),p=new Dt([o],"int32");for(let u=0,d=0;u<a.length;u++)i.has(a[u])||(l.values[d]=a[u],p.values[d]=u,d++);return[l.toTensor(),p.toTensor()]}var rS=GL;function HL(e){let t={x:C(e,"x","sign")};return O.runKernel(Po,t)}var $b=L({sign_:HL});function jL(e){let t={x:C(e,"x","sin","float32")};return O.runKernel(Lo,t)}var Ff=L({sin_:jL});function qL(e){let t={x:C(e,"x","sinh")};return O.runKernel(zo,t)}var Rf=L({sinh_:qL});function KL(e,t,r){let n=C(e,"x","slice1d");return A(n.rank===1,()=>`slice1d expects a rank-1 tensor, but got a rank-${n.rank} tensor`),Ve(n,[t],[r])}var Xd=L({slice1d_:KL});function XL(e,t,r){let n=C(e,"x","slice2d");return A(n.rank===2,()=>`slice2d expects a rank-2 tensor, but got a rank-${n.rank} tensor`),Ve(n,t,r)}var Df=L({slice2d_:XL});function ZL(e,t,r){let n=C(e,"x","slice3d");return A(n.rank===3,()=>`slice3d expects a rank-3 tensor, but got a rank-${n.rank} tensor`),Ve(n,t,r)}var rp=L({slice3d_:ZL});function JL(e,t,r){let n=C(e,"x","slice4d");return A(n.rank===4,()=>`slice4d expects a rank-4 tensor, but got a rank-${n.rank} tensor`),Ve(n,t,r)}var Dl=L({slice4d_:JL});function YL(e,t=-1){let r=C(e,"logits","softmax","float32");if(t===-1&&(t=r.rank-1),t!==r.rank-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${r.rank} and dim was ${t}`);let n={logits:r},a={dim:t};return O.runKernel(Go,n,a)}var Ds=L({softmax_:YL});function QL(e){A(e.dtype==="complex64",()=>`The dtype for tf.spectral.fft() must be complex64 but got ${e.dtype}.`);let t={input:e};return O.runKernel(af,t)}var Zd=L({fft_:QL});function ez(e){A(e.dtype==="complex64",()=>`The dtype for tf.spectral.ifft() must be complex64 but got ${e.dtype}.`);let t={input:e};return O.runKernel(sf,t)}var Ml=L({ifft_:ez});function tz(e){let t=e.shape[e.shape.length-1],r=e.size/t,n;if(t<=2){let a=B(e,[r,t]);n=Ml(a)}else{let a=[r,2*(t-1)],s=B(Rl(e),[r,t]),i=B(Wd(e),[r,t]),o=mn(Ve(s,[0,1],[r,t-2]),1),l=z(mn(Ve(i,[0,1],[r,t-2]),1),we(-1)),p=lt([s,o],1),u=lt([i,l],1),d=B(Aa(p,u),[a[0],a[1]]);n=Ml(d)}if(n=Rl(n),e.rank===3&&e.shape[0]!==0){let a=n,s=e.shape[0];n=B(n,[s,n.shape[0]/s,n.shape[1]]),a.dispose()}return n}var Mf=L({irfft_:tz});function rz(e,t,r=0){let n={x:C(e,"x","split")},a={numOrSizeSplits:t,axis:r};return O.runKernel(Wu,n,a)}var Ar=L({split_:rz});function nz(e,t){A(e.dtype==="float32",()=>`The dtype for rfft() must be real value but got ${e.dtype}`);let r=e.shape[e.shape.length-1],n=e.size/r,a;if(t!=null&&t<r){let f=e.shape.map(g=>0),m=e.shape.map(g=>g);m[e.shape.length-1]=t,a=Ve(e,f,m),r=t}else if(t!=null&&t>r){let f=e.shape.map(m=>m);f[e.shape.length-1]=t-r,a=lt([e,It(f)],e.shape.length-1),r=t}else a=e;let s=He(a),i=B(Aa(a,s),[n,r]),o=Zd(i),l=Math.floor(r/2)+1,p=Rl(o),u=Wd(o),d=Ar(p,[l,r-l],p.shape.length-1),h=Ar(u,[l,r-l],u.shape.length-1),c=a.shape.slice();return c[a.shape.length-1]=l,B(Aa(d[0],h[0]),c)}var Jd=L({rfft_:nz});function az(e,t){let r=C(e,"a","squaredDifference"),n=C(t,"b","squaredDifference");[r,n]=Nt(r,n),ut(r.shape,n.shape);let a={a:r,b:n},s={};return O.runKernel(Ho,a,s)}var Of=L({squaredDifference_:az});function sz(e,t){let r=C(e,"x","squeeze","string_or_numeric");return B(r,Ek(r.shape,t).newShape)}var Ms=L({squeeze_:sz});function iz(e,t=0){let r=Zp(e,"tensors","stack","string_or_numeric");A(r.length>=1,()=>"Pass at least one tensor to tf.stack"),r.length>0&&A(t<=r[0].rank,()=>"Axis must be <= rank of the tensor");let n=r,a={axis:t};return O.runKernel(Au,n,a)}var Mt=L({stack_:iz});function oz(e,t=0){let r={x:C(e,"x","step")},n={alpha:t};return O.runKernel($s,r,n)}var Yo=L({step_:oz});function lz(e,t,r,n,a=0,s=0,i=0,o=0,l=0){let p={x:C(e,"x","stridedSlice","string_or_numeric")},u={begin:t,end:r,strides:n,beginMask:a,endMask:s,ellipsisMask:i,newAxisMask:o,shrinkAxisMask:l};return O.runKernel(Gu,p,u)}var Ab=L({stridedSlice_:lz});function uz(e){let t={x:C(e,"x","tan","float32")};return O.runKernel(qo,t)}var Fb=L({tan_:uz});function Qe(e,t){Ei(e);let r=pa(e,t);if(r.length!==1)throw new Error("tensor1d() requires values to be a flat/TypedArray");return As(e,null,r,t)}function ia(e,t,r){if(Ei(e),t!=null&&t.length!==2)throw new Error("tensor2d() requires shape to have two numbers");let n=pa(e,r);if(n.length!==2&&n.length!==1)throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray");if(n.length===1&&t==null)throw new Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");return As(e,t,n,r)}function Lf(e,t,r){if(Ei(e),t!=null&&t.length!==3)throw new Error("tensor3d() requires shape to have three numbers");let n=pa(e,r);if(n.length!==3&&n.length!==1)throw new Error("tensor3d() requires values to be number[][][] or flat/TypedArray");if(n.length===1&&t==null)throw new Error("tensor3d() requires shape to be provided when `values` are a flat array");return As(e,t,n,r)}function bs(e,t,r){if(Ei(e),t!=null&&t.length!==4)throw new Error("tensor4d() requires shape to have four numbers");let n=pa(e,r);if(n.length!==4&&n.length!==1)throw new Error("tensor4d() requires values to be number[][][][] or flat/TypedArray");if(n.length===1&&t==null)throw new Error("tensor4d() requires shape to be provided when `values` are a flat array");return As(e,t,n,r)}function nS(e,t,r){if(Ei(e),t!=null&&t.length!==5)throw new Error("tensor5d() requires shape to have five numbers");let n=pa(e,r);if(n.length!==5&&n.length!==1)throw new Error("tensor5d() requires values to be number[][][][][] or flat/TypedArray");if(n.length===1&&t==null)throw new Error("tensor5d() requires shape to be provided when `values` are a flat array");return As(e,t,n,r)}function aS(e,t,r){if(Ei(e),t!=null&&t.length!==6)throw new Error("tensor6d() requires shape to have six numbers");let n=pa(e,r);if(n.length!==6&&n.length!==1)throw new Error("tensor6d() requires values to be number[][][][][][] or flat/TypedArray");if(n.length===1&&t==null)throw new Error("tensor6d() requires shape to be provided when `values` are a flat array");return t=t||n,As(e,t,n,r)}var zf={};Ee(zf,{calculateShapes:()=>sS,validateInput:()=>Pf,validateUpdateShape:()=>Rb});function Rb(e,t,r){let n=t.rank>1?t.shape[t.rank-1]:1,a=t.rank>1?t.rank-1:1,s=`Must have updates.shape = indices.shape[:batchDim] + shape[sliceDim:], got updates.shape: ${r.shape}, indices.shape: ${t.shape}, shape: ${e}, sliceDim: ${n}, and batchDim: ${a}.`;if(r.rank<a)throw new Error(s+` update.rank < ${a}. `);if(e.length<n+(r.rank-a))throw new Error(s+` Output shape length < ${n+(r.rank-a)}`);if(r.rank!==a+e.length-n)throw new Error(s+` update.rank != ${a+e.length-n}`);for(let i=0;i<a;++i)if(r.shape[i]!==t.shape[i])throw new Error(s+` updates.shape[${i}] (${r.shape[i]}) != indices.shape[${i}] (${t.shape[i]}).`);for(let i=0;i<r.rank-a;++i)if(r.shape[i+a]!==e[i+n])throw new Error(s+` updates.shape[${i+a}] (${r.shape[i+a]}) != shape[${i+a}] (${e[i+a]})`)}function Pf(e,t,r){if(t.rank<1)throw new Error(`tf.scatterND() expects the indices to be rank 1 or higher, but the rank was ${t.rank}.`);if(e.rank<1)throw new Error(`tf.scatterND() expects the updates to be rank 1 or higher, but the rank was ${e.rank}.`);if(t.dtype!=="int32")throw new Error(`The dtype of 'indices' should be int32, but got dtype: ${t.dtype}`);if(r.length<1)throw new Error(`Output rank must be greater or equal to 1, but got shape: ${r}`);if(r.length===0){if(t.size===0)throw new Error(`Indices specified for empty output. indices shape: ${t.shape}`);if(e.size===0)throw new Error(`Updates specified for empty output. updates shape: ${e.shape}`)}Rb(r,t,e)}function sS(e,t,r){let n=t.shape.length,a=n>1?t.shape[n-1]:1,s=r.length,i=1;for(let d=a;d<s;++d)i*=r[d];let o=a<1?1:a,l=nt(t.shape)/o,p=[...ql(r.slice(0,a)),1],u=nt(r);return{sliceRank:a,numUpdates:l,sliceSize:i,strides:p,outputSize:u}}function pz(e,t,r){let n=C(e,"tensor","tensorScatterupdate"),a=C(t,"indices","tensorScatterupdate","int32"),s=C(r,"updates","tensorScatterupdate");if(Pf(s,a,n.shape),n.dtype!==s.dtype)throw new Error(`tensor and updates must have the same dtype, instead they are ${n.dtype} and ${s.dtype}.`);let i={tensor:n,indices:a,updates:s},o={};return O.runKernel(Ou,i,o)}var iS=L({tensorScatterUpdate_:pz});function dz(e,t=1,r=!0){let n=C(e,"x","topk");if(n.rank===0)throw new Error("topk() expects the input to be of rank 1 or higher");let a=n.shape[n.shape.length-1];if(t<0)throw new Error(`'k' passed to topk() must be >= 0 but got ${t}`);if(t>a)throw new Error(`'k' passed to topk() must be <= the last dimension (${a}) but got ${t}`);let s={x:n},i={k:t,sorted:r},[o,l]=O.runKernel(Hu,s,i);return{values:o,indices:l}}var Db=L({topk_:dz});function hz(e,t=0,r=1,n,a){if(Yr(e),n!=null&&n==="bool")throw new Error("Unsupported data type $ { dtype }");let s=new Cb(t,r,n,!0,a),i=Le(e,n);for(let o=0;o<i.values.length;o++)i.values[o]=s.nextValue();return i.toTensor()}var Bf=L({truncatedNormal_:hz});function cz(e,t=0){let r=C(e,"x","unique","string_or_numeric");A(r.rank>0,()=>"The input tensor must be at least 1D");let n={x:r},a={axis:t},[s,i]=O.runKernel(Ad,n,a);return{values:s,indices:i}}var Mb=L({unique_:cz});function fz(e,t,r){let n=C(e,"x","unsortedSegmentSum"),a=C(t,"segmentIds","unsortedSegmentSum","int32");A(_l(r),()=>"numSegments must be of dtype int");let s={x:n,segmentIds:a},i={numSegments:r};return O.runKernel(Fd,s,i)}var Wf=L({unsortedSegmentSum_:fz});function mz(e,t=0){let r=C(e,"x","unstack","string_or_numeric");A(t>=-r.shape.length&&t<r.shape.length,()=>`Axis = ${t} is not in [-${r.shape.length}, ${r.shape.length})`);let n={value:r},a={axis:t};return O.runKernel(qu,n,a)}var Tt=L({unstack_:mz});function oS(e,t){return _f(e,t,"right")}function Ob(e,t=!0,r,n){return O.makeVariable(e,t,r,n)}function lS(e,t){let r=[];for(let s=0;s<t.length;s++)t[s]&&r.push(s);let n=Le(e,"int32"),a=Le([r.length,e.length],"int32");for(let s=0;s<r.length;s++){let i=n.indexToLoc(r[s]),o=s*e.length;a.values.set(i,o)}return a.toTensor()}async function gz(e){let t=C(e,"condition","whereAsync","bool"),r=await t.data(),n=lS(t.shape,r);return e!==t&&t.dispose(),n}var Lb=gz;async function yz(e,t,r){let n=C(e,"tensor","boolMask"),a=C(t,"mask","boolMask","bool"),s=r??0,i=a.rank,o=n.shape;A(i>0,()=>"mask cannot be scalar"),wr(o.slice(s,s+i),a.shape,"mask's shape must match the first K dimensions of tensor's shape,");let l=1;for(let m=s;m<s+i;m++)l*=o[m];let p=o.slice(0,s).concat([l],o.slice(s+i)),u=B(n,p),d=B(a,[-1]),h=await Lb(d),c=Ms(h,[1]),f=ep(u,c,s);return e!==n&&n.dispose(),t!==a&&a.dispose(),c.dispose(),u.dispose(),d.dispose(),h.dispose(),f}var uS=yz;function bz(e,t,r){let n=C(e,"x","transpose");if(t==null&&(t=n.shape.map((i,o)=>o).reverse()),A(n.rank===t.length,()=>`Error in transpose: rank of input ${n.rank} must match length of perm ${t}.`),t.forEach(i=>{A(i>=0&&i<n.rank,()=>`All entries in 'perm' must be between 0 and ${n.rank-1} but got ${t}`)}),n.rank<=1)return n.clone();let a={x:n},s={perm:t};return n.dtype==="complex64"?W(()=>{let i=Rl(n),o=Wd(n);return i=O.runKernel(Ta,{x:i},s),o=O.runKernel(Ta,{x:o},s),r&&(o=gt(o)),Aa(i,o)}):O.runKernel(Ta,a,s)}var Oe=L({transpose_:bz});function xz(e,t,r,n,a=!0){let s=C(e,"v","movingAverage"),i=C(t,"x","movingAverage"),o=C(r,"decay","movingAverage");Xk(s,i),A(Da(s.shape,i.shape),()=>"Shape mismatch in v and x");let l=we(1),p=de(l,o),u=z(de(i,s),p);if(a){A(n!=null,()=>"When using zeroDebias: true, step is required.");let d=C(n,"step","movingAverage");u=fe(u,de(l,da(o,d)))}return J(s,u)}var pS=L({movingAverage_:xz});function vz(e,t,r){Yr(r);let n=C(e,"indices","scatterND","int32"),a=C(t,"updates","scatterND");Pf(a,n,r);let s={indices:n,updates:a},i={shape:r};return O.runKernel(Mu,s,i)}var dS=L({scatterND_:vz});function wz(e,t,r,n){if(e.dtype!=="int32")throw new Error(`tf.sparseToDense() expects the indices to be int32 type, but the dtype was ${e.dtype}.`);if(e.rank>2)throw new Error(`sparseIndices should be a scalar, vector, or matrix, but got shape ${e.shape}.`);let a=e.rank>0?e.shape[0]:1,s=e.rank>1?e.shape[1]:1;if(r.length!==s)throw new Error(`outputShape has incorrect number of elements:, ${r.length}, should be: ${s}.`);let i=t.size;if(!(t.rank===0||t.rank===1&&i===a))throw new Error(`sparseValues has incorrect shape ${t.shape}, should be [] or [${a}]`);if(t.dtype!==n.dtype)throw new Error("sparseValues.dtype must match defaultValues.dtype")}function kz(e,t,r,n=0){Yr(r);let a=C(e,"sparseIndices","sparseToDense","int32"),s=C(t,"sparseValues","sparseToDense","string_or_numeric"),i=C(n,"defaultValue","sparseToDense",s.dtype);wz(a,s,r,i);let o={sparseIndices:a,sparseValues:s,defaultValue:i},l={outputShape:r};return O.runKernel(Vu,o,l)}var hS=L({sparseToDense_:kz});function Iz(e,t){let r=C(t,"indices","gatherND","int32"),n={params:C(e,"x","gatherND","string_or_numeric"),indices:r};return O.runKernel(fu,n)}var cS=L({gatherND_:Iz});function Sz(e,t){if(t==null)return e.shape.slice();if(Da(e.shape,t))return t;if(e.shape.length===t.length){let r=[];for(let n=0;n<e.shape.length;n++)t[n]==null&&e.shape[n]!=null?r.push(e.shape[n]):r.push(t[n]);return r}return t}function Nz(e,t,r,n){let a=C(e,"x","dropout");if(A(a.dtype==="float32",()=>`x has to be a floating point tensor since it's going to be scaled, but got a ${a.dtype} tensor instead.`),A(t>=0&&t<1,()=>`rate must be a float in the range [0, 1), but got ${t}.`),t===0)return e instanceof ze?a.clone():a;let s=Sz(a,r),i=1-t,o=fe(Qu(J(Rs(s,0,1,"float32",n),i)),i);return z(a,o)}var zb=L({dropout_:Nz});function Pb(e){return Math.floor(Math.pow(2,Math.ceil(Math.log(e)/Math.log(2))))}function Uf(e,t,r){let n=1-e%2,a=new Float32Array(e);for(let s=0;s<e;++s){let i=2*Math.PI*s/(e+n-1);a[s]=t-r*Math.cos(i)}return Qe(a,"float32")}async function _z(e,t,r=1){let n=C(e,"predictions","inTopK"),a=C(t,"targets","inTopK");A(n.rank>1,()=>`inTopK() expects the predictions to be of rank 2 or higher, but got ${n.rank}`),A(n.rank-1===a.rank,()=>`predictions rank should be 1 larger than targets rank, but got predictions rank ${n.rank} and targets rank ${a.rank}`),wr(n.shape.slice(0,n.shape.length-1),a.shape,"predictions's shape should be align with the targets' shape, except the last dimension.");let s=n.shape[n.shape.length-1];A(r>0&&r<=s,()=>`'k' passed to inTopK() must be > 0 && <= the predictions last dimension (${s}), but got ${r}`);let i=await n.data(),o=await a.data(),[l,p]=[i.length/s,s],u=$k("bool",l);for(let d=0;d<l;d++){let h=d*p,c=i.subarray(h,h+p),f=[];for(let m=0;m<c.length;m++)f.push({value:c[m],index:m});f.sort((m,g)=>g.value-m.value),u[d]=0;for(let m=0;m<r;m++)if(f[m].index===o[d]){u[d]=1;break}}return e!==n&&n.dispose(),t!==a&&a.dispose(),yr(u,a.shape,"bool")}var fS=_z,Ol={};Ee(Ol,{conv2d:()=>Ez,depthwiseConv2d:()=>Rz,matMul:()=>Mz});function Tz(e,t,r,n,a,s="NHWC",i){let o=e;e.rank===3&&(o=B(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let l=t;l.rank===3&&(l=B(t,[1,t.shape[0],t.shape[1],t.shape[2]])),A(o.rank===4,()=>`Error in conv2dDerFilter: input must be rank 4, but got shape ${o.shape}.`),A(l.rank===4,()=>`Error in conv2dDerFilter: dy must be rank 4, but got shape ${l.shape}.`),A(r.length===4,()=>`Error in conv2dDerFilter: filterShape must be length 4, but got ${r}.`);let p=s==="NHWC"?o.shape[3]:o.shape[1],u=s==="NHWC"?l.shape[3]:l.shape[1];A(p===r[2],()=>`Error in conv2dDerFilter: depth of input ${p}) must match input depth in filter (${r[2]}.`),A(u===r[3],()=>`Error in conv2dDerFilter: depth of dy (${u}) must match output depth for filter (${r[3]}).`),kr("conv2dDerFilter",a,i);let d={x:o,dy:l},h={strides:n,pad:a,dataFormat:s,dimRoundingMode:i,filterShape:r};return O.runKernel(Qc,d,h)}var Bb=L({conv2DBackpropFilter_:Tz});function Vf(e,t,r){if(r==null||r==="linear")return e;if(r==="relu")return z(e,Yo(t));throw new Error(`Cannot compute gradient for fused activation ${r}.`)}function Gf(e,t){let r=t,n=Ot(e.shape,t.shape);return n.length>0&&(r=ge(r,n)),B(r,e.shape)}function Hf(e,t,r,n){if(t==="linear")return e;if(t==="relu")return rt(e);if(t==="elu")return Ju(e);if(t==="relu6")return Cf(e);if(t==="prelu")return Kd(e,r);if(t==="leakyrelu")return Ud(e,n);if(t==="sigmoid")return In(e);throw new Error(`Unknown fused activation ${t}.`)}var jf=(e,t)=>!(e>0)||t==="linear";function Cz({x:e,filter:t,strides:r,pad:n,dataFormat:a="NHWC",dilations:s=[1,1],dimRoundingMode:i,bias:o,activation:l="linear",preluActivationWeights:p,leakyreluAlpha:u}){if(l=l||"linear",jf(O.state.gradientDepth,l)===!1){A(a==="NHWC",()=>`Error in fused conv2d: got dataFormat of ${a} but only NHWC is currently supported for the case of gradient depth is 0 and the activation is not linear.`);let N=br(e,t,r,n,a,s,i);return o!=null&&(N=J(N,o)),Hf(N,l,p,u)}let d=C(e,"x","conv2d","float32"),h=C(t,"filter","conv2d","float32"),c=d,f=!1;d.rank===3&&(f=!0,c=B(d,[1,d.shape[0],d.shape[1],d.shape[2]])),A(c.rank===4,()=>`Error in fused conv2d: input must be rank 4, but got rank ${c.rank}.`),A(h.rank===4,()=>`Error in fused conv2d: filter must be rank 4, but got rank ${h.rank}.`),kr("fused conv2d",n,i);let m=a==="NHWC"?c.shape[3]:c.shape[1];A(h.shape[2]===m,()=>`Error in conv2d: depth of input (${m}) must match input depth for filter ${h.shape[2]}.`),A(fa(r,s),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${r} and dilations '${s}'`);let g=zd(c.shape,h.shape,r,s,n,i),y;o!=null&&(y=C(o,"bias","fused conv2d"),[y]=Nt(y,d),a==="NHWC"?ut(g.outShape,y.shape):(A(y.shape.length<=1,()=>`Error in fused conv2d: only supports scalar or 1-D Tensor bias for NCHW format but got the bias of rank-${y.shape.length}.`),A(y.shape.length===0||y.shape[0]===g.outChannels||y.shape[0]===1,()=>`Error in fused conv2d: bias shape (${y.shape}) is not compatible with the number of output channels (${g.outChannels})`)));let b;if(p!=null){let N=p.shape;if(A(N.length<=1||N.length===3,()=>`Error in fused conv2d: only supports scalar, 1-D Tensor or 3-D Tensor PReLU activation weights but got a tensor of rank-${N.length}.`),N.length===1)A(N[0]===1||N[0]===g.outChannels,()=>`Error in fused conv2d: PReLU activation weights (${N}) is not compatible with the number of output channels (${g.outChannels}).`);else if(N.length===3)try{ut(N,g.outShape)}catch{let E=`Error in fused conv2d: PReLU activation weights (${N}) is not compatible with the output shape of the conv2d (${g.outShape}).`;throw Error(E)}b=C(p,"prelu weights","fused conv2d")}let x=(N,T)=>{A(a==="NHWC",()=>`Error in gradient of fused conv2D: got dataFormat of ${a} but only NHWC is currently supported.`);let[E,$,R,F]=T,S=Vf(N,R,l);A(ms(s),()=>`Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${s}'`);let D=nb($.shape,S,E,r,n),P=Bb($,S,E.shape,r,n),U=[D,P];if(F!=null){let H=Gf(F,S);U.push(H)}return U},v={x:c,filter:h,bias:y,preluActivationWeights:b},w={strides:r,pad:n,dataFormat:a,dilations:s,dimRoundingMode:i,activation:l,leakyreluAlpha:u};return o==null?ha((N,T,E)=>{let $=O.runKernel(ui,v,w);return E([T,N,$]),f&&($=B($,[$.shape[1],$.shape[2],$.shape[3]])),{value:$,gradFunc:x}})(c,h):ha((N,T,E,$)=>{let R=O.runKernel(ui,v,w);return $([T,N,R,E]),f&&(R=B(R,[R.shape[1],R.shape[2],R.shape[3]])),{value:R,gradFunc:x}})(c,h,y)}var Ez=L({fusedConv2d_:Cz});function $z(e,t,r,n,a,s=[1,1],i){let o=e;e.rank===3&&(o=B(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let l=t;l.rank===3&&(l=B(t,[1,t.shape[0],t.shape[1],t.shape[2]]));let p={x:o,dy:l},u={strides:n,pad:a,dimRoundingMode:i,dilations:s,filterShape:r};return O.runKernel(ef,p,u)}var mS=L({depthwiseConv2dNativeBackpropFilter_:$z});function Az(e,t,r,n,a,s=[1,1],i){let o=t,l=!1;t.rank===3&&(l=!0,o=B(t,[1,t.shape[0],t.shape[1],t.shape[2]]));let p={dy:o,filter:r},u={strides:n,pad:a,dimRoundingMode:i,dilations:s,inputShape:e},d=O.runKernel(tf,p,u);return l?B(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var gS=L({depthwiseConv2dNativeBackpropInput_:Az});function Fz({x:e,filter:t,strides:r,pad:n,dataFormat:a="NHWC",dilations:s=[1,1],dimRoundingMode:i,bias:o,activation:l="linear",preluActivationWeights:p,leakyreluAlpha:u}){if(jf(O.state.gradientDepth,l)===!1){let w=Zo(e,t,r,n,a,s,i);return o!=null&&(w=J(w,o)),Hf(w,l,p,u)}let d=C(e,"x","depthwiseConv2d","float32"),h=C(t,"filter","depthwiseConv2d","float32"),c=d,f=!1;d.rank===3&&(f=!0,c=B(d,[1,d.shape[0],d.shape[1],d.shape[2]])),A(c.rank===4,()=>`Error in fused depthwiseConv2d: input must be rank 4, but got rank ${c.rank}.`),A(h.rank===4,()=>`Error in fused depthwiseConv2d: filter must be rank 4, but got rank ${h.rank}.`),A(c.shape[3]===h.shape[2],()=>`Error in fused depthwiseConv2d: number of input channels (${c.shape[3]}) must match the inChannels dimension in filter ${h.shape[2]}.`),s==null&&(s=[1,1]),A(fa(r,s),()=>`Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides ${r} and dilations '${s}'`),kr("fused depthwiseConv2d",n,i);let m=zd(c.shape,h.shape,r,s,n,i,!0),g;o!=null&&(g=C(o,"bias","fused conv2d"),[g]=Nt(g,d),ut(m.outShape,g.shape));let y;p!=null&&(y=C(p,"prelu weights","fused depthwiseConv2d"));let b=(w,N)=>{A(ms(s),()=>`Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '${s}'`);let[T,E,$,R]=N,F=Vf(w,$,l),S=gS(E.shape,F,T,r,n,s,i),D=mS(E,F,T.shape,r,n,s,i);if(R!=null){let P=Gf(g,F);return[S,D,P]}return[S,D]},x={x:c,filter:h,bias:g,preluActivationWeights:y},v={strides:r,pad:n,dataFormat:a,dilations:s,dimRoundingMode:i,activation:l,leakyreluAlpha:u};return o==null?ha((w,N,T)=>{let E=O.runKernel(pi,x,v);return T([N,w,E]),f&&(E=B(E,[E.shape[1],E.shape[2],E.shape[3]])),{value:E,gradFunc:b}})(c,h):ha((w,N,T,E)=>{let $=O.runKernel(pi,x,v);return E([N,w,$,T]),f&&($=B($,[$.shape[1],$.shape[2],$.shape[3]])),{value:$,gradFunc:b}})(c,h,g)}var Rz=L({fusedDepthwiseConv2d_:Fz});function Dz({a:e,b:t,transposeA:r=!1,transposeB:n=!1,bias:a,activation:s="linear",preluActivationWeights:i,leakyreluAlpha:o=.2}){if(jf(O.state.gradientDepth,s)===!1){let R=Me(e,t,r,n);return a!=null&&(R=J(R,a)),Hf(R,s,i,o)}let l=C(e,"a","fused matMul"),p=C(t,"b","fused matMul");[l,p]=Nt(l,p);let u=r?l.shape[l.rank-2]:l.shape[l.rank-1],d=n?p.shape[p.rank-1]:p.shape[p.rank-2],h=r?l.shape[l.rank-1]:l.shape[l.rank-2],c=n?p.shape[p.rank-2]:p.shape[p.rank-1],f=l.shape.slice(0,-2),m=p.shape.slice(0,-2),g=nt(f),y=nt(m);A(u===d,()=>`Error in fused matMul: inner shapes (${u}) and (${d}) of Tensors with shapes ${l.shape} and ${p.shape} and transposeA=${r} and transposeB=${n} must match.`);let b=ut(l.shape.slice(0,-2),p.shape.slice(0,-2)).concat([h,c]),x=r?B(l,[g,u,h]):B(l,[g,h,u]),v=n?B(p,[y,c,d]):B(p,[y,d,c]),w;a!=null&&(w=C(a,"bias","fused matMul"),[w]=Nt(w,l),ut(b,w.shape));let N;i!=null&&(N=C(i,"prelu weights","fused matMul"));let T=(R,F)=>{let[S,D,P,U]=F,H=Vf(B(R,P.shape),P,s),q,G;if(!r&&!n?(q=Me(H,D,!1,!0),G=Me(S,H,!0,!1)):!r&&n?(q=Me(H,D,!1,!1),G=Me(H,S,!0,!1)):r&&!n?(q=Me(D,H,!1,!0),G=Me(S,H,!1,!1)):(q=Me(D,H,!0,!0),G=Me(H,S,!0,!0)),a!=null){let Z=Gf(U,H);return[q,G,Z]}else return[q,G]},E={a:x,b:v,bias:w,preluActivationWeights:N},$={transposeA:r,transposeB:n,activation:s,leakyreluAlpha:o};return a==null?ha((R,F,S)=>{let D=O.runKernel(li,E,$);return S([R,F,D]),{value:B(D,b),gradFunc:T}})(x,v):ha((R,F,S,D)=>{let P=O.runKernel(li,E,$);return D([R,F,P,S]),{value:B(P,b),gradFunc:T}})(x,v,w)}var Mz=L({fusedMatMul_:Dz});function Oz(e){return Uf(e,.54,.46)}var Lz=L({hammingWindow_:Oz});function zz(e){return Uf(e,.5,.5)}var yS=L({hannWindow_:zz});function Pz(e,t,r,n=!1,a=0){let s=0,i=[];for(;s+t<=e.size;)i.push(Ve(e,s,t)),s+=r;if(n)for(;s<e.size;){let o=s+t-e.size,l=lt([Ve(e,s,t-o),qr([o],a)]);i.push(l),s+=r}return i.length===0?ia([],[0,t]):B(lt(i),[i.length,t])}var bS=L({frame_:Pz});function Bz(e,t,r,n,a=yS){n==null&&(n=Pb(t));let s=bS(e,t,r),i=z(s,a(t));return Jd(i,n)}var Wz=L({stft_:Bz});function Uz(e,t,r,n,a="bilinear",s=0){let i=C(e,"image","cropAndResize"),o=C(t,"boxes","cropAndResize","float32"),l=C(r,"boxInd","cropAndResize","int32"),p=o.shape[0];A(i.rank===4,()=>`Error in cropAndResize: image must be rank 4,but got rank ${i.rank}.`),A(o.rank===2&&o.shape[1]===4,()=>`Error in cropAndResize: boxes must be have size [${p},4] but had shape ${o.shape}.`),A(l.rank===1&&l.shape[0]===p,()=>`Error in cropAndResize: boxInd must be have size [${p}] but had shape ${o.shape}.`),A(n.length===2,()=>`Error in cropAndResize: cropSize must be of length 2, but got length ${n.length}.`),A(n[0]>=1&&n[1]>=1,()=>`cropSize must be atleast [1,1], but was ${n}`),A(a==="bilinear"||a==="nearest",()=>`method must be bilinear or nearest, but was ${a}`);let u={image:i,boxes:o,boxInd:l},d={method:a,extrapolationValue:s,cropSize:n};return O.runKernel(ou,u,d)}var Vz=L({cropAndResize_:Uz});function Gz(e){let t=C(e,"image","flipLeftRight","float32");A(t.rank===4,()=>`Error in flipLeftRight: image must be rank 4,but got rank ${t.rank}.`);let r={image:t};return O.runKernel(hu,r,{})}var Hz=L({flipLeftRight_:Gz});function jz(e){let t=C(e,"image","grayscaleToRGB"),r=t.rank-1,n=t.shape[r];A(t.rank>=2,()=>`Error in grayscaleToRGB: images must be at least rank 2, but got rank ${t.rank}.`),A(n===1,()=>`Error in grayscaleToRGB: last dimension of a grayscale image should be size 1, but got size ${n}.`);let a=new Array(t.rank);return a.fill(1,0,r),a[r]=3,jr(t,a)}var qz=L({grayscaleToRGB_:jz});function Kz(e){let t=C(e,"image","RGBToGrayscale"),r=t.rank-1,n=t.shape[r];A(t.rank>=2,()=>`Error in RGBToGrayscale: images must be at least rank 2, but got rank ${t.rank}.`),A(n===3,()=>`Error in RGBToGrayscale: last dimension of an RGB image should be size 3, but got size ${n}.`);let a=t.dtype,s=se(t,"float32"),i=Qe([.2989,.587,.114]),o;switch(t.rank){case 2:o=Js("ij,j->i",s,i);break;case 3:o=Js("ijk,k->ij",s,i);break;case 4:o=Js("ijkl,l->ijk",s,i);break;case 5:o=Js("ijklm,m->ijkl",s,i);break;case 6:o=Js("ijklmn,n->ijklm",s,i);break;default:throw new Error("Not a valid tensor rank.")}return o=Xt(o,-1),se(o,a)}var Xz=L({rgbToGrayscale_:Kz});function Zz(e,t,r=0,n=.5){let a=C(e,"image","rotateWithOffset","float32");A(a.rank===4,()=>`Error in rotateWithOffset: image must be rank 4,but got rank ${a.rank}.`);let s={image:a},i={radians:t,fillValue:r,center:n};return O.runKernel(Xu,s,i)}var Jz=L({rotateWithOffset_:Zz});function np(e,t,r,n,a,s){n==null&&(n=.5),a==null&&(a=Number.NEGATIVE_INFINITY),s==null&&(s=0);let i=e.shape[0];return r=Math.min(r,i),A(0<=n&&n<=1,()=>`iouThreshold must be in [0, 1], but was '${n}'`),A(e.rank===2,()=>`boxes must be a 2D tensor, but was of rank '${e.rank}'`),A(e.shape[1]===4,()=>`boxes must have 4 columns, but 2nd dimension was ${e.shape[1]}`),A(t.rank===1,()=>"scores must be a 1D tensor"),A(t.shape[0]===i,()=>`scores has incompatible shape with boxes. Expected ${i}, but was ${t.shape[0]}`),A(0<=s&&s<=1,()=>`softNmsSigma must be in [0, 1], but was '${s}'`),{maxOutputSize:r,iouThreshold:n,scoreThreshold:a,softNmsSigma:s}}function Yz(e,t,r,n=.5,a=Number.NEGATIVE_INFINITY){let s=C(e,"boxes","nonMaxSuppression","float32"),i=C(t,"scores","nonMaxSuppression","float32"),o=np(s,i,r,n,a);r=o.maxOutputSize,n=o.iouThreshold,a=o.scoreThreshold;let l={maxOutputSize:r,iouThreshold:n,scoreThreshold:a};return O.runKernel(Tu,{boxes:s,scores:i},l)}var Qz=L({nonMaxSuppression_:Yz});function eP(e,t,r){let n=tP(e,t,r),a=n<0?-(n+1):n;e.splice(a,0,t)}function tP(e,t,r){return nP(e,t,r||rP)}function rP(e,t){return e>t?1:e<t?-1:0}function nP(e,t,r){let n=0,a=e.length,s=0,i=!1;for(;n<a;){s=n+(a-n>>>1);let o=r(t,e[s]);o>0?n=s+1:(a=s,i=!o)}return i?n:-n-1}function xS(e,t,r,n,a){return Wb(e,t,r,n,a,0)}function vS(e,t,r,n,a,s){return Wb(e,t,r,n,a,0,!1,s,!0)}function wS(e,t,r,n,a,s){return Wb(e,t,r,n,a,s,!0)}function Wb(e,t,r,n,a,s,i=!1,o=!1,l=!1){let p=[];for(let g=0;g<t.length;g++)t[g]>a&&p.push({score:t[g],boxIndex:g,suppressBeginIndex:0});p.sort(m0);let u=s>0?-.5/s:0,d=[],h=[];for(;d.length<r&&p.length>0;){let g=p.pop(),{score:y,boxIndex:b,suppressBeginIndex:x}=g;if(y<a)break;let v=!1;for(let w=d.length-1;w>=x;--w){let N=aP(e,b,d[w]);if(N>=n){v=!0;break}if(g.score=g.score*sP(n,u,N),g.score<=a)break}g.suppressBeginIndex=d.length,v||(g.score===y?(d.push(b),h.push(g.score)):g.score>a&&eP(p,g,m0))}let c=d.length,f=r-c;o&&f>0&&(d.push(...new Array(f).fill(0)),h.push(...new Array(f).fill(0)));let m={selectedIndices:d};return i&&(m.selectedScores=h),l&&(m.validOutputs=c),m}function aP(e,t,r){let n=e.subarray(t*4,t*4+4),a=e.subarray(r*4,r*4+4),s=Math.min(n[0],n[2]),i=Math.min(n[1],n[3]),o=Math.max(n[0],n[2]),l=Math.max(n[1],n[3]),p=Math.min(a[0],a[2]),u=Math.min(a[1],a[3]),d=Math.max(a[0],a[2]),h=Math.max(a[1],a[3]),c=(o-s)*(l-i),f=(d-p)*(h-u);if(c<=0||f<=0)return 0;let m=Math.max(s,p),g=Math.max(i,u),y=Math.min(o,d),b=Math.min(l,h),x=Math.max(y-m,0)*Math.max(b-g,0);return x/(c+f-x)}function sP(e,t,r){let n=Math.exp(t*r*r);return r<=e?n:0}function m0(e,t){return e.score-t.score||e.score===t.score&&t.boxIndex-e.boxIndex}async function iP(e,t,r,n=.5,a=Number.NEGATIVE_INFINITY){let s=C(e,"boxes","nonMaxSuppressionAsync"),i=C(t,"scores","nonMaxSuppressionAsync"),o=np(s,i,r,n,a);r=o.maxOutputSize,n=o.iouThreshold,a=o.scoreThreshold;let l=await Promise.all([s.data(),i.data()]),p=l[0],u=l[1],{selectedIndices:d}=xS(p,u,r,n,a);return s!==e&&s.dispose(),i!==t&&i.dispose(),Qe(d,"int32")}var oP=iP;function lP(e,t,r,n=.5,a=Number.NEGATIVE_INFINITY,s=0){let i=C(e,"boxes","nonMaxSuppression"),o=C(t,"scores","nonMaxSuppression"),l=np(i,o,r,n,a,s);r=l.maxOutputSize,n=l.iouThreshold,a=l.scoreThreshold,s=l.softNmsSigma;let p={boxes:i,scores:o},u={maxOutputSize:r,iouThreshold:n,scoreThreshold:a,softNmsSigma:s},d=O.runKernel(Eu,p,u);return{selectedIndices:d[0],selectedScores:d[1]}}var uP=L({nonMaxSuppressionWithScore_:lP});async function pP(e,t,r,n=.5,a=Number.NEGATIVE_INFINITY,s=0){let i=C(e,"boxes","nonMaxSuppressionAsync"),o=C(t,"scores","nonMaxSuppressionAsync"),l=np(i,o,r,n,a,s);r=l.maxOutputSize,n=l.iouThreshold,a=l.scoreThreshold,s=l.softNmsSigma;let p=await Promise.all([i.data(),o.data()]),u=p[0],d=p[1],{selectedIndices:h,selectedScores:c}=wS(u,d,r,n,a,s);return i!==e&&i.dispose(),o!==t&&o.dispose(),{selectedIndices:Qe(h,"int32"),selectedScores:Qe(c)}}var dP=pP;function hP(e,t,r,n=.5,a=Number.NEGATIVE_INFINITY,s=!1){let i=C(e,"boxes","nonMaxSuppression"),o=C(t,"scores","nonMaxSuppression"),l=np(i,o,r,n,a,null),p=l.maxOutputSize,u=l.iouThreshold,d=l.scoreThreshold,h={boxes:i,scores:o},c={maxOutputSize:p,iouThreshold:u,scoreThreshold:d,padToMaxOutputSize:s},f=O.runKernel(Cu,h,c);return{selectedIndices:f[0],validOutputs:f[1]}}var cP=L({nonMaxSuppressionPadded_:hP});async function fP(e,t,r,n=.5,a=Number.NEGATIVE_INFINITY,s=!1){let i=C(e,"boxes","nonMaxSuppressionAsync"),o=C(t,"scores","nonMaxSuppressionAsync"),l=np(i,o,r,n,a,null),p=l.maxOutputSize,u=l.iouThreshold,d=l.scoreThreshold,[h,c]=await Promise.all([i.data(),o.data()]),{selectedIndices:f,validOutputs:m}=vS(h,c,p,u,d,s);return i!==e&&i.dispose(),o!==t&&o.dispose(),{selectedIndices:Qe(f,"int32"),validOutputs:we(m,"int32")}}var mP=fP;function gP(e,t,r=!1,n=!1){let a=C(e,"images","resizeBilinear");A(a.rank===3||a.rank===4,()=>`Error in resizeBilinear: x must be rank 3 or 4, but got rank ${a.rank}.`),A(t.length===2,()=>`Error in resizeBilinear: new shape must 2D, but got shape ${t}.`),A(n===!1||r===!1,()=>"Error in resizeBilinear: If halfPixelCenters is true, alignCorners must be false.");let s=a,i=!1;a.rank===3&&(i=!0,s=B(a,[1,a.shape[0],a.shape[1],a.shape[2]]));let o={images:s},l={alignCorners:r,halfPixelCenters:n,size:t},p=O.runKernel(Ao,o,l);return i?B(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var kS=L({resizeBilinear_:gP});function yP(e,t,r=!1,n=!1){let a=C(e,"images","resizeNearestNeighbor");A(a.rank===3||a.rank===4,()=>`Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank ${a.rank}.`),A(t.length===2,()=>`Error in resizeNearestNeighbor: new shape must 2D, but got shape ${t}.`),A(a.dtype==="float32"||a.dtype==="int32",()=>"`images` must have `int32` or `float32` as dtype"),A(n===!1||r===!1,()=>"Error in resizeNearestNeighbor: If halfPixelCenters is true, alignCorners must be false.");let s=a,i=!1;a.rank===3&&(i=!0,s=B(a,[1,a.shape[0],a.shape[1],a.shape[2]]));let o={images:s},l={alignCorners:r,halfPixelCenters:n,size:t},p=O.runKernel($o,o,l);return i?B(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var IS=L({resizeNearestNeighbor_:yP});function bP(e,t="binary",r=!1,n=.5){let a=C(e,"image","threshold"),s=.2989,i=.587,o=.114,l=a.shape[0]*a.shape[1],p=z(Qe([n]),255),u,d,h,c;if(A(a.rank===3,()=>`Error in threshold: image must be rank 3,but got rank ${a.rank}.`),A(a.shape[2]===3||a.shape[2]===1,()=>`Error in threshold: image color channel must be equal to 3 or 1but got ${a.shape[2]}.`),A(a.dtype==="int32"||a.dtype==="float32",()=>`Error in dtype: image dtype must be int32 or float32,but got dtype ${a.dtype}.`),A(t==="otsu"||t==="binary",()=>`Method must be binary or otsu, but was ${t}`),a.shape[2]===3){[u,d,h]=Ar(a,[1,1,1],-1);let m=z(u,s),g=z(d,i),y=z(h,o);c=J(J(m,g),y)}else c=e;if(t==="otsu"){let m=Jy(se(Ef(c),"int32"),yr([]),256);p=xP(m,l)}let f=r?Fs(c,p):Ir(c,p);return se(z(f,255),"int32")}function xP(e,t){let r=Qe([-1]),n=Qe([0]),a=Qe([0]),s,i,o,l,p,u;for(let d=0;d<e.size-1;d++){s=Ve(e,0,d+1),i=Ve(e,d+1),p=fe(ge(s),t),u=fe(ge(i),t);let h=ge(z(s,xi(0,s.size)));o=fe(h,ge(s));let c=qr(i.shape,s.size),f=J(xi(0,i.size),c),m=z(i,f);l=fe(ge(m),ge(i));let g=de(o,l),y=de(o,l),b=z(p,u);a=z(z(b,g),y);let x=Ir(a,n);n=Jt(x,a,n),r=Jt(x,Qe([d]),r)}return r}var vP=L({threshold_:bP});function wP(e,t,r="nearest",n="constant",a=0,s){let i=C(e,"image","transform","float32"),o=C(t,"transforms","transform","float32");A(i.rank===4,()=>`Error in transform: image must be rank 4,but got rank ${i.rank}.`),A(o.rank===2&&(o.shape[0]===i.shape[0]||o.shape[0]===1)&&o.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:i,transforms:o},p={interpolation:r,fillMode:n,fillValue:a,outputShape:s};return O.runKernel(ju,l,p)}var kP=L({transform_:wP});function IP(e,t,r){let n=C(e,"a","bandPart");A(n.rank>=2,()=>`bandPart(): Rank must be at least 2, got ${n.rank}.`);let a=n.shape,[s,i]=n.shape.slice(-2),o,l;typeof t=="number"?(A(t%1===0,()=>`bandPart(): numLower must be an integer, got ${t}.`),A(t<=s,()=>`bandPart(): numLower (${t}) must not be greater than the number of rows (${s}).`),o=C(t<0?s:t,"numLower","bandPart")):(A(t.dtype==="int32",()=>"bandPart(): numLower's dtype must be an int32."),o=Jt(Al(t,0),s,ys(t,s))),typeof r=="number"?(A(r%1===0,()=>`bandPart(): numUpper must be an integer, got ${r}.`),A(r<=i,()=>`bandPart(): numUpper (${r}) must not be greater than the number of columns (${i}).`),l=C(r<0?i:r,"numUpper","bandPart")):(A(r.dtype==="int32",()=>"bandPart(): numUpper's dtype must be an int32."),l=Jt(Al(r,0),i,ys(r,i)));let p=B(xi(0,s,1,"int32"),[-1,1]),u=xi(0,i,1,"int32"),d=de(p,u),h=Nn(Fs(d,o),La(d,gt(l))),c=It([s,i],n.dtype);return B(Mt(Tt(B(n,[-1,s,i])).map(f=>Jt(h,f,c))),a)}var SP=L({bandPart_:IP});function NP(e){let t;if(Array.isArray(e)){t=!1,A(e!=null&&e.length>0,()=>"Gram-Schmidt process: input must not be null, undefined, or empty");let a=e[0].shape[0];for(let s=1;s<e.length;++s)A(e[s].shape[0]===a,()=>`Gram-Schmidt: Non-unique lengths found in the input vectors: (${e[s].shape[0]} vs. ${a})`)}else t=!0,e=Ar(e,e.shape[0],0).map(a=>Ms(a,[0]));A(e.length<=e[0].shape[0],()=>`Gram-Schmidt: Number of vectors (${e.length}) exceeds number of dimensions (${e[0].shape[0]}).`);let r=[],n=e;for(let a=0;a<e.length;++a)r.push(O.tidy(()=>{let s=n[a];if(a>0)for(let i=0;i<a;++i){let o=z(ge(z(r[i],s)),r[i]);s=de(s,o)}return fe(s,Yu(s,"euclidean"))}));return t?Mt(r,0):r}var _P=L({gramSchmidt_:NP});function TP(e,t=!1){if(A(e.rank>=2,()=>`qr() requires input tensor to have a rank >= 2, but got rank ${e.rank}`),e.rank===2)return g0(e,t);{let r=e.shape.slice(0,e.shape.length-2).reduce((l,p)=>l*p),n=Tt(B(e,[r,e.shape[e.shape.length-2],e.shape[e.shape.length-1]]),0),a=[],s=[];n.forEach(l=>{let[p,u]=g0(l,t);a.push(p),s.push(u)});let i=B(Mt(a,0),e.shape),o=B(Mt(s,0),e.shape);return[i,o]}}function g0(e,t=!1){return O.tidy(()=>{A(e.shape.length===2,()=>`qr2d() requires a 2D Tensor, but got a ${e.shape.length}D Tensor.`);let r=e.shape[0],n=e.shape[1],a=kf(r),s=sa(e),i=ia([[1]],[1,1]),o=sa(i),l=r>=n?n:r;for(let p=0;p<l;++p){let u=s,d=o,h=a;[o,s,a]=O.tidy(()=>{let c=Ve(s,[p,p],[r-p,1]),f=Yu(c),m=Ve(s,[p,p],[1,1]),g=Jt(Ir(m,0),ia([[-1]]),ia([[1]])),y=de(m,z(g,f)),b=fe(c,y);b.shape[0]===1?o=sa(i):o=lt([i,Ve(b,[1,0],[b.shape[0]-1,b.shape[1]])],0);let x=gt(fe(Me(g,y),f)),v=Ve(s,[p,0],[r-p,n]),w=z(x,o),N=Oe(o);if(p===0)s=de(v,Me(w,Me(N,v)));else{let $=de(v,Me(w,Me(N,v)));s=lt([Ve(s,[0,0],[p,n]),$],0)}let T=Oe(w),E=Ve(a,[0,p],[r,a.shape[1]-p]);if(p===0)a=de(E,Me(Me(E,o),T));else{let $=de(E,Me(Me(E,o),T));a=lt([Ve(a,[0,0],[r,p]),$],1)}return[o,s,a]}),Ce([u,d,h])}return!t&&r>n&&(a=Ve(a,[0,0],[r,n]),s=Ve(s,[0,0],[n,n])),[a,s]})}var CP=L({qr_:TP}),mr;(function(e){e[e.NONE=0]="NONE",e[e.MEAN=1]="MEAN",e[e.SUM=2]="SUM",e[e.SUM_BY_NONZERO_WEIGHTS=3]="SUM_BY_NONZERO_WEIGHTS"})(mr||(mr={}));function EP(e,t,r=mr.SUM_BY_NONZERO_WEIGHTS){let n=C(e,"losses","computeWeightedLoss"),a=null;t!=null&&(a=C(t,"weights","computeWeightedLoss"));let s=a==null?n:z(n,a);if(r===mr.NONE)return s;if(r===mr.SUM)return ge(s);if(r===mr.MEAN){if(a==null)return kt(s);{let i=n.size/a.size,o=fe(ge(s),ge(a));return i>1?fe(o,we(i)):o}}if(r===mr.SUM_BY_NONZERO_WEIGHTS){if(a==null)return fe(ge(s),we(n.size));{let i=z(a,$r(n.shape)),o=se(ge(bi(i,we(0))),"float32");return fe(ge(s),o)}}throw Error(`Unknown reduction: ${r}`)}var za=L({computeWeightedLoss_:EP});function $P(e,t,r,n=mr.SUM_BY_NONZERO_WEIGHTS){let a=C(e,"labels","absoluteDifference"),s=C(t,"predictions","absoluteDifference"),i=null;r!=null&&(i=C(r,"weights","absoluteDifference")),wr(a.shape,s.shape,"Error in absoluteDifference: ");let o=Ft(de(a,s));return za(o,i,n)}var AP=L({absoluteDifference_:$P});function FP(e,t,r,n,a=mr.SUM_BY_NONZERO_WEIGHTS){let s=C(e,"labels","cosineDistance"),i=C(t,"predictions","cosineDistance"),o=null;n!=null&&(o=C(n,"weights","cosineDistance")),wr(s.shape,i.shape,"Error in cosineDistance: ");let l=we(1),p=de(l,ge(z(s,i),r,!0));return za(p,o,a)}var RP=L({cosineDistance_:FP});function DP(e,t,r,n=mr.SUM_BY_NONZERO_WEIGHTS){let a=C(e,"labels","hingeLoss"),s=C(t,"predictions","hingeLoss"),i=null;r!=null&&(i=C(r,"weights","hingeLoss")),wr(a.shape,s.shape,"Error in hingeLoss: ");let o=we(1);a=de(z(we(2),a),o);let l=rt(de(o,z(a,s)));return za(l,i,n)}var MP=L({hingeLoss_:DP});function OP(e,t,r,n=1,a=mr.SUM_BY_NONZERO_WEIGHTS){let s=C(e,"labels","huberLoss"),i=C(t,"predictions","huberLoss"),o=null;r!=null&&(o=C(r,"weights","huberLoss")),wr(s.shape,i.shape,"Error in huberLoss: ");let l=we(n),p=Ft(de(i,s)),u=ys(p,l),d=de(p,u),h=J(z(we(.5),ot(u)),z(l,d));return za(h,o,a)}var LP=L({huberLoss_:OP});function zP(e,t,r,n=1e-7,a=mr.SUM_BY_NONZERO_WEIGHTS){let s=C(e,"labels","logLoss"),i=C(t,"predictions","logLoss"),o=null;r!=null&&(o=C(r,"weights","logLoss")),wr(s.shape,i.shape,"Error in logLoss: ");let l=we(1),p=we(n),u=gt(z(s,Xr(J(i,p)))),d=z(de(l,s),Xr(J(de(l,i),p))),h=de(u,d);return za(h,o,a)}var PP=L({logLoss_:zP});function BP(e,t,r,n=mr.SUM_BY_NONZERO_WEIGHTS){let a=C(e,"labels","meanSquaredError"),s=C(t,"predictions","meanSquaredError"),i=null;r!=null&&(i=C(r,"weights","meanSquaredError")),wr(a.shape,s.shape,"Error in meanSquaredError: ");let o=Of(a,s);return za(o,i,n)}var WP=L({meanSquaredError_:BP});function UP(e,t){let r=C(e,"labels","sigmoidCrossEntropyWithLogits"),n=C(t,"logits","sigmoidCrossEntropyWithLogits");wr(r.shape,n.shape,"Error in sigmoidCrossEntropyWithLogits: ");let a=rt(n),s=z(n,r),i=Vd(pr(gt(Ft(n))));return J(de(a,s),i)}function VP(e,t,r,n=0,a=mr.SUM_BY_NONZERO_WEIGHTS){let s=C(e,"multiClassLabels","sigmoidCrossEntropy"),i=C(t,"logits","sigmoidCrossEntropy"),o=null;if(r!=null&&(o=C(r,"weights","sigmoidCrossEntropy")),wr(s.shape,i.shape,"Error in sigmoidCrossEntropy: "),n>0){let p=we(n),u=we(1),d=we(.5);s=J(z(s,de(u,p)),z(d,p))}let l=UP(s,i);return za(l,o,a)}var GP=L({sigmoidCrossEntropy_:VP});function HP(e,t,r=-1){if(r===-1&&(r=t.rank-1),r!==t.rank-1)throw Error(`Softmax cross entropy along a non-last dimension is not yet supported. Labels / logits was rank ${t.rank} and dim was ${r}`);return ha((n,a,s)=>{let i=Gd(a,[r],!0),o=de(se(a,"float32"),i);s([n,o]);let l=gt(z(o,n));return{value:ge(l,[r]),gradFunc:(p,u)=>{let[d,h]=u,c=yi(p.shape,[r]);return[z(B(p,c),de(se(d,"float32"),pr(h))),z(B(p,c),de(pr(h),se(d,"float32")))]}}})(e,t)}function jP(e,t,r,n=0,a=mr.SUM_BY_NONZERO_WEIGHTS){let s=C(e,"onehotLabels","softmaxCrossEntropy"),i=C(t,"logits","softmaxCrossEntropy"),o=null;if(r!=null&&(o=C(r,"weights","softmaxCrossEntropy")),wr(s.shape,i.shape,"Error in softmaxCrossEntropy: "),n>0){let p=we(n),u=we(1),d=we(s.shape[1]);s=J(z(s,de(u,p)),fe(p,d))}let l=HP(s,i);return za(l,o,a)}var qP=L({softmaxCrossEntropy_:jP});function KP(e,t,r,n){let a=C(e,"indices","sparseFillEmptyRows","int32"),s=C(t,"values","sparseFillEmptyRows"),i=C(r,"denseShape","sparseFillEmptyRows","int32"),o=C(n,"defaultValue","sparseFillEmptyRows",s.dtype);if(a.rank!==2)throw new Error(`Indices should be Tensor2D but received shape
${a.shape}`);if(s.rank!==1)throw new Error(`Values should be Tensor1D but received shape ${s.shape}`);if(i.rank!==1)throw new Error(`Dense shape should be Tensor1D but received shape ${i.shape}`);if(o.rank!==0)throw new Error(`Default value should be a scalar but received shape ${o.shape}`);let l={indices:a,values:s,denseShape:i,defaultValue:o},p=O.runKernel(Id,l);return{outputIndices:p[0],outputValues:p[1],emptyRowIndicator:p[2],reverseIndexMap:p[3]}}var XP=L({sparseFillEmptyRows_:KP});function ZP(e,t,r){let n=C(e,"inputIndices","sparseReshape","int32"),a=C(t,"inputShape","sparseReshape","int32"),s=C(r,"newShape","sparseReshape","int32");if(n.rank!==2)throw new Error(`Input indices should be Tensor2D but received shape
${n.shape}`);if(a.rank!==1)throw new Error(`Input shape should be Tensor1D but received shape ${a.shape}`);if(s.rank!==1)throw new Error(`New shape should be Tensor1D but received shape ${s.shape}`);let i={inputIndices:n,inputShape:a,newShape:s},o=O.runKernel(Uu,i);return{outputIndices:o[0],outputShape:o[1]}}var JP=L({sparseReshape_:ZP});function YP(e,t,r){let n=C(e,"data","sparseSegmentMean"),a=C(t,"indices","sparseSegmentMean","int32"),s=C(r,"segmentIds","sparseSegmentMean","int32");if(n.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(a.rank!==1)throw new Error(`Indices should be Tensor1D but received shape
${a.shape}`);if(s.rank!==1)throw new Error(`Segment ids should be Tensor1D but received shape
${s.shape}`);let i={data:n,indices:a,segmentIds:s};return O.runKernel(Sd,i)}var QP=L({sparseSegmentMean_:YP});function eB(e,t,r){let n=C(e,"data","sparseSegmentSum"),a=C(t,"indices","sparseSegmentSum","int32"),s=C(r,"segmentIds","sparseSegmentSum","int32");if(n.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(a.rank!==1)throw new Error(`Indices should be Tensor1D but received shape
${a.shape}`);if(s.rank!==1)throw new Error(`Segment ids should be Tensor1D but received shape
${s.shape}`);let i={data:n,indices:a,segmentIds:s};return O.runKernel(Nd,i)}var tB=L({sparseSegmentSum_:eB});function rB(e,t,r,n,a,s,i,o){let l=C(e,"data","stringNGrams","string");if(l.dtype!=="string")throw new Error("Data must be of datatype string");if(l.shape.length!==1)throw new Error(`Data must be a vector, saw: ${l.shape}`);let p=C(t,"dataSplits","stringNGrams");if(p.dtype!=="int32")throw new Error("Data splits must be of datatype int32");let u={separator:r,nGramWidths:n,leftPad:a,rightPad:s,padWidth:i,preserveShortSequences:o},d={data:l,dataSplits:p},h=O.runKernel(Cd,d,u);return{nGrams:h[0],nGramsSplits:h[1]}}var nB=L({stringNGrams_:rB});function aB(e,t,r=!0){let n=C(e,"input","stringSplit","string"),a=C(t,"delimiter","stringSplit","string");if(n.rank!==1)throw new Error(`Input should be Tensor1D but received shape ${n.shape}`);if(a.rank!==0)throw new Error(`Delimiter should be a scalar but received shape ${a.shape}`);let s={skipEmpty:r},i={input:n,delimiter:a},o=O.runKernel(Ed,i,s);return{indices:o[0],values:o[1],shape:o[2]}}var sB=L({stringSplit_:aB});function iB(e,t){let r=C(e,"input","stringToHashBucketFast","string"),n={numBuckets:t};if(t<=0)throw new Error("Number of buckets must be at least 1");let a={input:r};return O.runKernel($d,a,n)}var oB=L({stringToHashBucketFast_:iB});function lB(e,t,r,n=!0){let a=C(e,"input","staticRegexReplace","string"),s={pattern:t,rewrite:r,replaceGlobal:n};return O.runKernel(Td,{x:a},s)}var uB=L({staticRegexReplace_:lB}),SS={fft:Zd,ifft:Ml,rfft:Jd,irfft:Mf},NS={hammingWindow:Lz,hannWindow:yS,frame:bS,stft:Wz},sn={flipLeftRight:Hz,grayscaleToRGB:qz,resizeNearestNeighbor:IS,resizeBilinear:kS,rgbToGrayscale:Xz,rotateWithOffset:Jz,cropAndResize:Vz,nonMaxSuppression:Qz,nonMaxSuppressionAsync:oP,nonMaxSuppressionWithScore:uP,nonMaxSuppressionWithScoreAsync:dP,nonMaxSuppressionPadded:cP,nonMaxSuppressionPaddedAsync:mP,threshold:vP,transform:kP},Ub={bandPart:SP,gramSchmidt:_P,qr:CP},_S={absoluteDifference:AP,computeWeightedLoss:za,cosineDistance:RP,hingeLoss:MP,huberLoss:LP,logLoss:PP,meanSquaredError:WP,sigmoidCrossEntropy:GP,softmaxCrossEntropy:qP},TS={sparseFillEmptyRows:XP,sparseReshape:JP,sparseSegmentMean:QP,sparseSegmentSum:tB},CS={stringNGrams:nB,stringSplit:sB,stringToHashBucketFast:oB,staticRegexReplace:uB},ne={};Ee(ne,{Serializable:()=>ES,SerializationMap:()=>$S,getRegisteredName:()=>dB,registerClass:()=>AS});var pB=new Map,bg=new Map,ES=class{getClassName(){return this.constructor.className}static fromConfig(e,t){return new e(t)}},$S=class gl{constructor(){this.classNameMap={}}static getMap(){return gl.instance==null&&(gl.instance=new gl),gl.instance}static register(t){gl.getMap().classNameMap[t.className]=[t,t.fromConfig]}};function AS(e,t,r){A(e.className!=null,()=>"Class being registered does not have the static className property defined."),A(typeof e.className=="string",()=>"className is required to be a string, but got type "+typeof e.className),A(e.className.length>0,()=>"Class being registered has an empty-string as its className, which is disallowed."),typeof t>"u"&&(t="Custom"),typeof r>"u"&&(r=e.className);let n=r,a=t+">"+n;return $S.register(e),pB.set(a,e),bg.set(e,a),e}function dB(e){return bg.has(e)?bg.get(e):e.className}var Pa=class extends ES{minimize(e,t=!1,r){let{value:n,grads:a}=this.computeGradients(e,r);if(r!=null){let s=r.map(i=>({name:i.name,tensor:a[i.name]}));this.applyGradients(s)}else this.applyGradients(a);return Ce(a),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 AI(e,t)}dispose(){this.iterations_!=null&&Ce(this.iterations_)}async saveIterations(){return this.iterations_==null&&(this.iterations_=0),{name:"iter",tensor:we(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(Pa,Symbol.hasInstance,{value:e=>e.minimize!=null&&e.computeGradients!=null&&e.applyGradients!=null});var Vb=class extends Pa{static get className(){return"Adadelta"}constructor(e,t,r=null){super(),this.learningRate=e,this.rho=t,this.epsilon=r,this.accumulatedGrads=[],this.accumulatedUpdates=[],r==null&&(this.epsilon=O.backend.epsilon())}applyGradients(e){(Array.isArray(e)?e.map(t=>t.name):Object.keys(e)).forEach((t,r)=>{let n=O.registeredVariables[t],a=!1;this.accumulatedGrads[r]==null&&(this.accumulatedGrads[r]={originalName:`${t}/accum_grad`,variable:W(()=>He(n).variable(a))}),this.accumulatedUpdates[r]==null&&(this.accumulatedUpdates[r]={originalName:`${t}/accum_var`,variable:W(()=>He(n).variable(a))});let s=Array.isArray(e)?e[r].tensor:e[t];if(s==null)return;let i=this.accumulatedGrads[r].variable,o=this.accumulatedUpdates[r].variable;W(()=>{let l=J(z(i,this.rho),z(ot(s),1-this.rho)),p=z(fe(Yt(J(o,this.epsilon)),Yt(J(i,this.epsilon))),s),u=J(z(o,this.rho),z(ot(p),1-this.rho));i.assign(l),o.assign(u);let d=J(z(p,-this.learningRate),n);n.assign(d)})}),this.incrementIterations()}dispose(){this.accumulatedUpdates!=null&&(Ce(this.accumulatedGrads.map(e=>e.variable)),Ce(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,r=!1;this.accumulatedGrads=e.slice(0,t).map(n=>({originalName:n.name,variable:n.tensor.variable(r)})),this.accumulatedUpdates=e.slice(t,t*2).map(n=>({originalName:n.name,variable:n.tensor.variable(r)}))}getConfig(){return{learningRate:this.learningRate,rho:this.rho,epsilon:this.epsilon}}static fromConfig(e,t){return new e(t.learningRate,t.rho,t.epsilon)}},Gb=class extends Pa{static get className(){return"Adagrad"}constructor(e,t=.1){super(),this.learningRate=e,this.initialAccumulatorValue=t,this.accumulatedGrads=[]}applyGradients(e){(Array.isArray(e)?e.map(t=>t.name):Object.keys(e)).forEach((t,r)=>{let n=O.registeredVariables[t];this.accumulatedGrads[r]==null&&(this.accumulatedGrads[r]={originalName:`${t}/accumulator`,variable:W(()=>qr(n.shape,this.initialAccumulatorValue).variable(!1))});let a=Array.isArray(e)?e[r].tensor:e[t];if(a==null)return;let s=this.accumulatedGrads[r].variable;W(()=>{let i=J(s,ot(a));s.assign(i);let o=J(z(fe(a,Yt(J(i,O.backend.epsilon()))),-this.learningRate),n);n.assign(o)})}),this.incrementIterations()}dispose(){this.accumulatedGrads!=null&&Ce(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(r=>({originalName:r.name,variable:r.tensor.variable(t)}))}getConfig(){return{learningRate:this.learningRate,initialAccumulatorValue:this.initialAccumulatorValue}}static fromConfig(e,t){return new e(t.learningRate,t.initialAccumulatorValue)}},Hb=class extends Pa{static get className(){return"Adam"}constructor(e,t,r,n=null){super(),this.learningRate=e,this.beta1=t,this.beta2=r,this.epsilon=n,this.accumulatedFirstMoment=[],this.accumulatedSecondMoment=[],W(()=>{this.accBeta1=we(t).variable(),this.accBeta2=we(r).variable()}),n==null&&(this.epsilon=O.backend.epsilon())}applyGradients(e){let t=Array.isArray(e)?e.map(r=>r.name):Object.keys(e);W(()=>{let r=de(1,this.accBeta1),n=de(1,this.accBeta2);t.forEach((a,s)=>{let i=O.registeredVariables[a],o=!1;this.accumulatedFirstMoment[s]==null&&(this.accumulatedFirstMoment[s]={originalName:`${a}/m`,variable:W(()=>He(i).variable(o))}),this.accumulatedSecondMoment[s]==null&&(this.accumulatedSecondMoment[s]={originalName:`${a}/v`,variable:W(()=>He(i).variable(o))});let l=Array.isArray(e)?e[s].tensor:e[a];if(l==null)return;let p=this.accumulatedFirstMoment[s].variable,u=this.accumulatedSecondMoment[s].variable,d=J(z(p,this.beta1),z(l,1-this.beta1)),h=J(z(u,this.beta2),z(ot(l),1-this.beta2)),c=fe(d,r),f=fe(h,n);p.assign(d),u.assign(h);let m=J(z(fe(c,J(Yt(f),this.epsilon)),-this.learningRate),i);i.assign(m)}),this.accBeta1.assign(z(this.accBeta1,this.beta1)),this.accBeta2.assign(z(this.accBeta2,this.beta2))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.accBeta2.dispose(),this.accumulatedFirstMoment!=null&&Ce(this.accumulatedFirstMoment.map(e=>e.variable)),this.accumulatedSecondMoment!=null&&Ce(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),W(()=>{this.accBeta1.assign(da(this.beta1,this.iterations_+1)),this.accBeta2.assign(da(this.beta2,this.iterations_+1))});let t=e.length/2,r=!1;this.accumulatedFirstMoment=e.slice(0,t).map(n=>({originalName:n.name,variable:n.tensor.variable(r)})),this.accumulatedSecondMoment=e.slice(t,t*2).map(n=>({originalName:n.name,variable:n.tensor.variable(r)}))}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)}},jb=class extends Pa{static get className(){return"Adamax"}constructor(e,t,r,n=null,a=0){super(),this.learningRate=e,this.beta1=t,this.beta2=r,this.epsilon=n,this.decay=a,this.accumulatedFirstMoment=[],this.accumulatedWeightedInfNorm=[],W(()=>{this.iteration=we(0).variable(),this.accBeta1=we(t).variable()}),n==null&&(this.epsilon=O.backend.epsilon())}applyGradients(e){let t=Array.isArray(e)?e.map(r=>r.name):Object.keys(e);W(()=>{let r=de(1,this.accBeta1),n=fe(-this.learningRate,J(z(this.iteration,this.decay),1));t.forEach((a,s)=>{let i=O.registeredVariables[a],o=!1;this.accumulatedFirstMoment[s]==null&&(this.accumulatedFirstMoment[s]={originalName:`${a}/m`,variable:He(i).variable(o)}),this.accumulatedWeightedInfNorm[s]==null&&(this.accumulatedWeightedInfNorm[s]={originalName:`${a}/v`,variable:He(i).variable(o)});let l=Array.isArray(e)?e[s].tensor:e[a];if(l==null)return;let p=this.accumulatedFirstMoment[s].variable,u=this.accumulatedWeightedInfNorm[s].variable,d=J(z(p,this.beta1),z(l,1-this.beta1)),h=z(u,this.beta2),c=Ft(l),f=ma(h,c);p.assign(d),u.assign(f);let m=J(z(fe(n,r),fe(d,J(f,this.epsilon))),i);i.assign(m)}),this.iteration.assign(J(this.iteration,1)),this.accBeta1.assign(z(this.accBeta1,this.beta1))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.iteration.dispose(),this.accumulatedFirstMoment!=null&&Ce(this.accumulatedFirstMoment.map(e=>e.variable)),this.accumulatedWeightedInfNorm!=null&&Ce(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)}},qf=class extends Pa{static get className(){return"SGD"}constructor(e){super(),this.learningRate=e,this.setLearningRate(e)}applyGradients(e){(Array.isArray(e)?e.map(t=>t.name):Object.keys(e)).forEach((t,r)=>{let n=Array.isArray(e)?e[r].tensor:e[t];if(n==null)return;let a=O.registeredVariables[t];W(()=>{let s=J(z(this.c,n),a);a.assign(s)})}),this.incrementIterations()}setLearningRate(e){this.learningRate=e,this.c!=null&&this.c.dispose(),this.c=Pt(we(-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)}},qb=class extends qf{static get className(){return"Momentum"}constructor(e,t,r=!1){super(e),this.learningRate=e,this.momentum=t,this.useNesterov=r,this.accumulations=[],this.m=we(this.momentum)}applyGradients(e){(Array.isArray(e)?e.map(t=>t.name):Object.keys(e)).forEach((t,r)=>{let n=O.registeredVariables[t];this.accumulations[r]==null&&(this.accumulations[r]={originalName:`${t}/momentum`,variable:W(()=>He(n).variable(!1))});let a=this.accumulations[r].variable,s=Array.isArray(e)?e[r].tensor:e[t];s!=null&&W(()=>{let i,o=J(z(this.m,a),s);this.useNesterov?i=J(z(this.c,J(s,z(o,this.m))),n):i=J(z(this.c,o),n),a.assign(o),n.assign(i)})}),this.incrementIterations()}dispose(){this.m.dispose(),this.accumulations!=null&&Ce(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(r=>({originalName:r.name,variable:r.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)}},Kb=class extends Pa{static get className(){return"RMSProp"}constructor(e,t=.9,r=0,n=null,a=!1){if(super(),this.learningRate=e,this.decay=t,this.momentum=r,this.epsilon=n,this.accumulatedMeanSquares=[],this.accumulatedMoments=[],this.accumulatedMeanGrads=[],this.centered=a,n==null&&(this.epsilon=O.backend.epsilon()),e==null)throw new Error("learningRate for RMSPropOptimizer must be defined.")}applyGradients(e){(Array.isArray(e)?e.map(t=>t.name):Object.keys(e)).forEach((t,r)=>{let n=O.registeredVariables[t],a=!1;this.accumulatedMeanSquares[r]==null&&(this.accumulatedMeanSquares[r]={originalName:`${t}/rms`,variable:W(()=>He(n).variable(a))}),this.accumulatedMoments[r]==null&&(this.accumulatedMoments[r]={originalName:`${t}/momentum`,variable:W(()=>He(n).variable(a))}),this.accumulatedMeanGrads[r]==null&&this.centered&&(this.accumulatedMeanGrads[r]={originalName:`${t}/mg`,variable:W(()=>He(n).variable(a))});let s=Array.isArray(e)?e[r].tensor:e[t];if(s==null)return;let i=this.accumulatedMeanSquares[r].variable,o=this.accumulatedMoments[r].variable;W(()=>{let l=J(z(i,this.decay),z(ot(s),1-this.decay));if(this.centered){let p=this.accumulatedMeanGrads[r].variable,u=J(z(p,this.decay),z(s,1-this.decay)),d=fe(z(s,this.learningRate),Yt(de(l,J(ot(u),this.epsilon)))),h=J(z(o,this.momentum),d);i.assign(l),p.assign(u),o.assign(h);let c=de(n,h);n.assign(c)}else{let p=J(z(i,this.decay),z(ot(s),1-this.decay)),u=J(z(o,this.momentum),fe(z(s,this.learningRate),Yt(J(p,this.epsilon))));i.assign(p),o.assign(u);let d=de(n,u);n.assign(d)}})}),this.incrementIterations()}dispose(){this.accumulatedMeanSquares!=null&&Ce(this.accumulatedMeanSquares.map(e=>e.variable)),this.accumulatedMeanGrads!=null&&this.centered&&Ce(this.accumulatedMeanGrads.map(e=>e.variable)),this.accumulatedMoments!=null&&Ce(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,r=!1;this.accumulatedMeanSquares=e.slice(0,t).map(n=>({originalName:n.name,variable:n.tensor.variable(r)})),this.accumulatedMoments=e.slice(t,t*2).map(n=>({originalName:n.name,variable:n.tensor.variable(r)})),this.centered&&(this.accumulatedMeanGrads=e.slice(t*2,t*3).map(n=>({originalName:n.name,variable:n.tensor.variable(r)})))}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)}},hB=[Vb,Gb,Hb,jb,qb,Kb,qf];function cB(){for(let e of hB)AS(e)}var or={};Ee(or,{CompositeArrayBuffer:()=>Ma,browserFiles:()=>vB,browserHTTPRequest:()=>_B,concatenateArrayBuffers:()=>eM,copyModel:()=>kM,decodeWeights:()=>nI,decodeWeightsStream:()=>sI,encodeWeights:()=>KD,fromMemory:()=>CB,fromMemorySync:()=>OS,getLoadHandlers:()=>lM,getModelArtifactsForJSON:()=>Oy,getModelArtifactsForJSONSync:()=>oI,getModelArtifactsInfoForJSON:()=>Ld,getSaveHandlers:()=>oM,getWeightSpecs:()=>hg,http:()=>Zb,isHTTPScheme:()=>vg,listModels:()=>vM,loadWeights:()=>kB,moveModel:()=>IM,registerLoadRouter:()=>iM,registerSaveRouter:()=>sM,removeModel:()=>wM,weightsLoaderFactory:()=>RS,withSaveHandler:()=>EB,withSaveHandlerSync:()=>$B});var fB="model",mB=".json",gB=".weights.bin";function y0(e){return new Promise(t=>setTimeout(t)).then(e)}var vc=class xg{constructor(t){if(!j().getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");t.startsWith(xg.URL_SCHEME)&&(t=t.slice(xg.URL_SCHEME.length)),(t==null||t.length===0)&&(t=fB),this.modelJsonFileName=t+mB,this.weightDataFileName=t+gB}async save(t){if(typeof document>"u")throw new Error("Browser downloads are not supported in this environment since `document` is not present");let r=Ma.join(t.weightData),n=window.URL.createObjectURL(new Blob([r],{type:"application/octet-stream"}));if(t.modelTopology instanceof ArrayBuffer)throw new Error("BrowserDownloads.save() does not support saving model topology in binary formats yet.");{let a=[{paths:["./"+this.weightDataFileName],weights:t.weightSpecs}],s=iI(t,a),i=window.URL.createObjectURL(new Blob([JSON.stringify(s)],{type:"application/json"})),o=this.modelJsonAnchor==null?document.createElement("a"):this.modelJsonAnchor;if(o.download=this.modelJsonFileName,o.href=i,await y0(()=>o.dispatchEvent(new MouseEvent("click"))),t.weightData!=null){let l=this.weightDataAnchor==null?document.createElement("a"):this.weightDataAnchor;l.download=this.weightDataFileName,l.href=n,await y0(()=>l.dispatchEvent(new MouseEvent("click")))}return{modelArtifactsInfo:Ld(t)}}}};vc.URL_SCHEME="downloads://";var yB=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.jsonFile=e[0],this.weightsFiles=e.slice(1)}async load(){return new Promise((e,t)=>{let r=new FileReader;r.onload=n=>{let a=JSON.parse(n.target.result),s=a.modelTopology;if(s==null){t(new Error(`modelTopology field is missing from file ${this.jsonFile.name}`));return}if(a.weightsManifest==null){t(new Error(`weightManifest field is missing from file ${this.jsonFile.name}`));return}if(this.weightsFiles.length===0){e({modelTopology:s});return}let i=Oy(a,o=>this.loadWeights(o));e(i)},r.onerror=n=>t(`Failed to read model topology and weights manifest JSON from file '${this.jsonFile.name}'. BrowserFiles supports loading Keras-style tf.Model artifacts only.`),r.readAsText(this.jsonFile)})}loadWeights(e){let t=[],r=[];for(let s of e)t.push(...s.weights),r.push(...s.paths);let n=this.checkManifestAndWeightFiles(e),a=r.map(s=>this.loadWeightsFile(s,n[s]));return Promise.all(a).then(s=>[t,s])}loadWeightsFile(e,t){return new Promise((r,n)=>{let a=new FileReader;a.onload=s=>{let i=s.target.result;r(i)},a.onerror=s=>n(`Failed to weights data from file of path '${e}'.`),a.readAsArrayBuffer(t)})}checkManifestAndWeightFiles(e){let t=[],r=this.weightsFiles.map(a=>f0(a.name)),n={};for(let a of e)a.paths.forEach(s=>{let i=f0(s);if(t.indexOf(i)!==-1)throw new Error(`Duplicate file basename found in weights manifest: '${i}'`);if(t.push(i),r.indexOf(i)===-1)throw new Error(`Weight file with basename '${i}' is not provided.`);n[s]=this.weightsFiles[r.indexOf(i)]});if(t.length!==this.weightsFiles.length)throw new Error(`Mismatch in the number of files in weights manifest (${t.length}) and the number of weight files provided (${this.weightsFiles.length}).`);return n}},bB=e=>j().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(vc.URL_SCHEME)?xB(e.slice(vc.URL_SCHEME.length)):null;fn.registerSaveRouter(bB);function xB(e="model"){return new vc(e)}function vB(e){return new yB(e)}function b0(e,t,r,n){i(e),r=r??0,n=n??1,o(r,n);let a=0,s=l=>(l.then(p=>{let u=r+ ++a/e.length*(n-r);return t(u),p}),l);function i(l){A(l!=null&&Array.isArray(l)&&l.length>0,()=>"promises must be a none empty array")}function o(l,p){A(l>=0&&l<=1,()=>`Progress fraction must be in range [0, 1], but got startFraction ${l}`),A(p>=0&&p<=1,()=>`Progress fraction must be in range [0, 1], but got endFraction ${p}`),A(p>=l,()=>`startFraction must be no more than endFraction, but got startFraction ${l} and endFraction ${p}`)}return Promise.all(e.map(s))}async function FS(e,t){t==null&&(t={});let r=t.fetchFunc==null?j().platform.fetch:t.fetchFunc,n=e.map(s=>r(s,t.requestInit,{isBinary:!0})),a=(t.onProgress==null?await Promise.all(n):await b0(n,t.onProgress,0,.5)).map(s=>s.arrayBuffer());return t.onProgress==null?await Promise.all(a):await b0(a,t.onProgress,.5,1)}function wB(e,t){var r;let n=t.fetchFunc==null?j().platform.fetch:t.fetchFunc,a=0,s;return(r=t.onProgress)===null||r===void 0||r.call(t,0),new ReadableStream({pull:async i=>{for(var o;a<e.length;){s||(s=(await n(e[a],t.requestInit,{isBinary:!0})).body.getReader());let{done:l,value:p}=await s.read();if(l){a++,s=void 0,(o=t.onProgress)===null||o===void 0||o.call(t,a/e.length);continue}i.enqueue(p);return}i.close()}})}async function kB(e,t="",r,n){return RS(a=>FS(a,{requestInit:n}))(e,t,r)}function RS(e){return async(t,r="",n)=>{let a=t.map(()=>!1),s={},i=n!=null?n.map(()=>!1):[],o=[];if(t.forEach((c,f)=>{let m=0;c.weights.forEach(g=>{let y="quantization"in g?g.quantization.dtype:g.dtype,b=hi[y]*nt(g.shape),x=()=>{a[f]=!0,s[f]==null&&(s[f]=[]),s[f].push({manifestEntry:g,groupOffset:m,sizeBytes:b})};n!=null?n.forEach((v,w)=>{v===g.name&&(x(),i[w]=!0)}):x(),o.push(g.name),m+=b})}),!i.every(c=>c)){let c=n.filter((f,m)=>!i[m]);throw new Error(`Could not find weights in manifest with names: ${c.join(", ")}.
Manifest JSON has weights with names: ${o.join(", ")}.`)}let l=a.reduce((c,f,m)=>(f&&c.push(m),c),[]),p=[];l.forEach(c=>{t[c].paths.forEach(f=>{let m=r+(r.endsWith("/")?"":"/")+f;p.push(m)})});let u=await e(p),d={},h=0;return l.forEach(c=>{let f=t[c].paths.length,m=new Ma(u.slice(h,h+f));s[c].forEach(g=>{let y=m.slice(g.groupOffset,g.groupOffset+g.sizeBytes),b=nI(y,[g.manifestEntry]);for(let x in b)d[x]=b[x]}),h+=f}),d}}var IB="application/octet-stream",SB="application/json",Xb=class{constructor(e,t){if(this.DEFAULT_METHOD="POST",t==null&&(t={}),this.weightPathPrefix=t.weightPathPrefix,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=j().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||{},this.loadOptions=t}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 r=[{paths:["./model.weights.bin"],weights:e.weightSpecs}],n=iI(e,r);if(t.body.append("model.json",new Blob([JSON.stringify(n)],{type:SB}),"model.json"),e.weightData!=null){let s=Ma.join(e.weightData);t.body.append("model.weights.bin",new Blob([s],{type:IB}),"model.weights.bin")}let a=await this.fetch(this.path,t);if(a.ok)return{modelArtifactsInfo:Ld(e),responses:[a]};throw new Error(`BrowserHTTPRequest.save() failed due to HTTP response status ${a.status}.`)}async loadModelJSON(){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{let s=`Failed to parse model JSON of response from ${this.path}.`;throw this.path.endsWith(".pb")?s+=" 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.":s+=" Please make sure the server is serving valid JSON for this request.",new Error(s)}let r=t.modelTopology,n=t.weightsManifest;if(r==null&&n==null)throw new Error(`The JSON from HTTP path ${this.path} contains neither model topology or manifest for weights.`);return t}async load(){if(this.loadOptions.streamWeights)return this.loadStream();let e=await this.loadModelJSON();return Oy(e,t=>this.loadWeights(t))}async loadStream(){let e=await this.loadModelJSON(),t=await this.getWeightUrls(e.weightsManifest),r=hg(e.weightsManifest),n=()=>wB(t,this.loadOptions);return Object.assign(Object.assign({},e),{weightSpecs:r,getWeightStream:n})}async getWeightUrls(e){let t=Array.isArray(this.path)?this.path[1]:this.path,[r,n]=NB(t),a=this.weightPathPrefix||r,s=[],i=[];for(let o of e)for(let l of o.paths)this.weightUrlConverter!=null?i.push(this.weightUrlConverter(l)):s.push(a+l+n);return this.weightUrlConverter&&s.push(...await Promise.all(i)),s}async loadWeights(e){let t=await this.getWeightUrls(e),r=hg(e),n=await FS(t,this.loadOptions);return[r,n]}};Xb.URL_SCHEME_REGEX=/^https?:\/\//;function NB(e){let t=e.lastIndexOf("/"),r=e.lastIndexOf("?"),n=e.substring(0,t),a=r>t?e.substring(r):"";return[n+"/",a]}function vg(e){return e.match(Xb.URL_SCHEME_REGEX)!=null}var DS=(e,t)=>{if(typeof fetch>"u"&&(t==null||t.fetchFunc==null))return null;{let r=!0;if(Array.isArray(e)?r=e.every(n=>vg(n)):r=vg(e),r)return Zb(e,t)}return null};fn.registerSaveRouter(DS);fn.registerLoadRouter(DS);function Zb(e,t){return new Xb(e,t)}function _B(e,t){return Zb(e,t)}var Om=class{constructor(e){this.modelArtifacts=e}load(){return this.modelArtifacts}},MS=class{constructor(e){this.saveHandler=e}save(e){return this.saveHandler(e)}},TB=class{constructor(e){e.load&&(this.load=()=>Promise.resolve(e.load())),e.save&&(this.save=t=>Promise.resolve(e.save(t)))}};function CB(e,t,r,n){let a=arguments;return new TB(OS(...a))}function OS(e,t,r,n){return arguments.length===1?e.modelTopology!=null||e.weightSpecs!=null?new Om(e):(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 Om({modelTopology:e})):(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 Om({modelTopology:e,weightSpecs:t,weightData:r,trainingConfig:n}))}function EB(e){return new MS(e)}function $B(e){return new MS(e)}var LS={};Ee(LS,{confusionMatrix:()=>FB});function AB(e,t,r){let n=C(e,"labels","confusionMatrix"),a=C(t,"predictions","confusionMatrix");A(r==null||r>0&&Number.isInteger(r),()=>`If provided, numClasses must be a positive integer, but got ${r}`),A(n.rank===1,()=>`Expected the rank of labels to be 1, but got ${n.rank}`),A(a.rank===1,()=>`Expected the rank of predictions to be 1, but got ${a.rank}`),A(n.shape[0]===a.shape[0],()=>`Mismatch in the number of examples: ${n.shape[0]} vs. ${a.shape[0]}. Labels and predictions should have the same number of elements.`),A(r>0&&Number.isInteger(r),()=>`numClasses is required to be a positive integer, but got ${r}`);let s=Fl(se(n,"int32"),r),i=Fl(se(a,"int32"),r),o=Oe(s),l=Me(o,i);return se(l,"int32")}var FB=L({confusionMatrix_:AB}),Yd={};Ee(Yd,{draw:()=>BB,fromPixels:()=>WB,fromPixelsAsync:()=>LB,toPixels:()=>PB});var Hs,x0=!1;function zS(e,t=3){if(t>4)throw new Error("Cannot construct Tensor with more than 4 channels from pixels.");if(e==null)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");let r=!1,n=!1,a=!1,s=!1,i=!1,o=!1;if(e.data instanceof Uint8Array)r=!0;else if(typeof ImageData<"u"&&e instanceof ImageData)n=!0;else if(typeof HTMLVideoElement<"u"&&e instanceof HTMLVideoElement)a=!0;else if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement)s=!0;else if(e.getContext!=null)i=!0;else if(typeof ImageBitmap<"u"&&e instanceof ImageBitmap)o=!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 ${e.constructor.name}`);if(Kp(gc,O.backendName)!=null){let h={pixels:e},c={numChannels:t};return O.runKernel(gc,h,c)}let[l,p]=a?[e.videoWidth,e.videoHeight]:[e.width,e.height],u;if(i)u=e.getContext("2d").getImageData(0,0,l,p).data;else if(n||r)u=e.data;else if(s||a||o){if(Hs==null)if(typeof document>"u")if(typeof OffscreenCanvas<"u"&&typeof OffscreenCanvasRenderingContext2D<"u")Hs=new OffscreenCanvas(1,1).getContext("2d");else throw new Error("Cannot parse input in current context. Reason: OffscreenCanvas Context2D rendering is not supported.");else Hs=document.createElement("canvas").getContext("2d",{willReadFrequently:!0});Hs.canvas.width=l,Hs.canvas.height=p,Hs.drawImage(e,0,0,l,p),u=Hs.getImageData(0,0,l,p).data}let d;if(t===4)d=new Int32Array(u);else{let h=l*p;d=new Int32Array(h*t);for(let c=0;c<h;c++)for(let f=0;f<t;++f)d[c*t+f]=u[c*4+f]}return Lf(d,[p,l,t],"int32")}function RB(e){return e!=null&&e.data instanceof Uint8Array}function DB(){return typeof window<"u"&&typeof ImageBitmap<"u"&&window.hasOwnProperty("createImageBitmap")}function MB(e){return e!=null&&e.width!==0&&e.height!==0}function OB(e){return DB()&&!(e instanceof ImageBitmap)&&MB(e)&&!RB(e)}async function LB(e,t=3){let r=null;if(j().getBool("WRAP_TO_IMAGEBITMAP")&&OB(e)){let n;try{n=await createImageBitmap(e,{premultiplyAlpha:"none"})}catch{n=null}n!=null&&n.width===e.width&&n.height===e.height?r=n:r=e}else r=e;return zS(r,t)}function PS(e){if(e.rank!==2&&e.rank!==3)throw new Error(`toPixels only supports rank 2 or 3 tensors, got rank ${e.rank}.`);let t=e.rank===2?1:e.shape[2];if(t>4||t===2)throw new Error(`toPixels only supports depth of size 1, 3 or 4 but got ${t}`);if(e.dtype!=="float32"&&e.dtype!=="int32")throw new Error(`Unsupported type for toPixels: ${e.dtype}. Please use float32 or int32 tensors.`)}function zB(e){let t=(e==null?void 0:e.alpha)||1;if(t>1||t<0)throw new Error(`Alpha value ${t} is suppoed to be in range [0 - 1].`)}async function PB(e,t){let r=C(e,"img","toPixels");if(!(e instanceof ze)){let p=r;r=se(p,"int32"),p.dispose()}PS(r);let[n,a]=r.shape.slice(0,2),s=r.rank===2?1:r.shape[2],i=await r.data(),o=r.dtype==="float32"?255:1,l=new Uint8ClampedArray(a*n*4);for(let p=0;p<n*a;++p){let u=[0,0,0,255];for(let h=0;h<s;h++){let c=i[p*s+h];if(r.dtype==="float32"){if(c<0||c>1)throw new Error(`Tensor values for a float32 Tensor must be in the range [0 - 1] but encountered ${c}.`)}else if(r.dtype==="int32"&&(c<0||c>255))throw new Error(`Tensor values for a int32 Tensor must be in the range [0 - 255] but encountered ${c}.`);s===1?(u[0]=c*o,u[1]=c*o,u[2]=c*o):u[h]=c*o}let d=p*4;l[d+0]=Math.round(u[0]),l[d+1]=Math.round(u[1]),l[d+2]=Math.round(u[2]),l[d+3]=Math.round(u[3])}if(t!=null){x0||Kp(rf,O.backendName)!=null&&(console.warn("tf.browser.toPixels is not efficient to draw tensor on canvas. Please try tf.browser.draw instead."),x0=!0),t.width=a,t.height=n;let p=t.getContext("2d"),u=new ImageData(l,a,n);p.putImageData(u,0,0)}return r!==e&&r.dispose(),l}function BB(e,t,r){let n=C(e,"img","draw");if(!(e instanceof ze)){let i=n;n=se(i,"int32"),i.dispose()}PS(n),zB(r==null?void 0:r.imageOptions);let a={image:n},s={canvas:t,options:r};O.runKernel(rf,a,s)}var WB=L({fromPixels_:zS}),Jb={};Ee(Jb,{prepareAndValidate:()=>BS});function BS(e,t){let r=e.shape.length,n=t.shape.length;if(r<1)throw new Error(`tf.gatherND() expects the input to be rank 1 or higher, but the rank was ${r}.`);if(n<1)throw new Error(`tf.gatherND() expects the indices to be rank 1 or higher, but the rank was ${n}.`);if(t.dtype!=="int32")throw new Error(`tf.gatherND() expects the indices to be int32 type, but the dtype was ${t.dtype}.`);if(t.shape[n-1]>r)throw new Error(`index innermost dimension length must be <= tensor rank; saw: ${t.shape[n-1]} vs. ${r}`);if(nt(e.shape)===0)throw new Error(`Requested more than 0 entries, but input is empty. Input shape: ${e.shape}.`);let a=t.shape,s=a[a.length-1],i=1;for(let d=0;d<a.length-1;++d)i*=a[d];let o=e.shape,l=a.slice();l.pop();let p=1;for(let d=s;d<r;++d)p*=o[d],l.push(o[d]);let u=[...ql(e.shape).map(d=>d/p),1].slice(0,s);return[l,i,p,u]}var Wt={};Ee(Wt,{assertParamsValid:()=>VB,computeFlatOffset:()=>KB,computeOutShape:()=>HB,getNormalizedAxes:()=>jB,isSliceContinous:()=>qB,maskToAxes:()=>GB,parseSliceParams:()=>XS,sliceInfo:()=>XB,startForAxis:()=>qS,startIndicesWithElidedDims:()=>GS,stopForAxis:()=>KS,stopIndicesWithElidedDims:()=>HS,stridesForAxis:()=>jS,stridesWithElidedDims:()=>WS});var wg=-2,UB=-1;function VB(e,t,r){let n=e.shape.length;A(n===t.length,()=>`Error in slice${n}D: Length of begin ${t} must match the rank of the array (${n}).`),A(n===r.length,()=>`Error in slice${n}D: Length of size ${r} must match the rank of the array (${n}).`);for(let a=0;a<n;++a)A(t[a]+r[a]<=e.shape[a],()=>`Error in slice${n}D: begin[${a}] + size[${a}] (${t[a]+r[a]}) would overflow input.shape[${a}] (${e.shape[a]})`)}function GB(e){let t=[],r=0;for(;e>0;)e&1&&t.push(r),e/=2,r++;return t}function HB(e,t,r){let n=[];for(let a=0;a<e.length;a++)n[a]=Math.ceil((t[a]-e[a])/r[a]);return n}function WS(e,t,r,n){let a=[...e];for(let s=a.length;s<n.length;s++)a.push(1);for(let s=0;s<r;s++)s===0?a[t]=1:(a.splice(t,0,1),a.pop());return a}function US(e,t,r){return r<=e?r:r-(t-1)}function VS(e,t){let r=[];for(let n=0;n<e;n++)r.push(t+n);return r}function jB(e,t,r,n,a,s,i,o,l){let p=e.length,u=new Array(p),d=new Array(p),h=new Array(p);if(t.length&&r>0){let c=t[0],f=r+1;u=GS(i,c,f,n,e),d=HS(o,c,f,a,e),h=WS(s,c,f,e)}else for(let c=0;c<p;c++)u[c]=qS(i,n,s,e,c,l),d[c]=KS(o,a,s,e,c,l),h[c]=jS(s,c,l);return{begin:u,end:d,strides:h}}function GS(e,t,r,n,a){let s=[...a],i=VS(r,t);for(let o=0;o<s.length;o++)if(i.indexOf(o)>-1)s[o]=0;else{let l=US(t,r,o),p=n[l];e&1<<l&&(p=0),s[o]=p}return s}function HS(e,t,r,n,a){let s=[...a],i=VS(r,t);for(let o=0;o<s.length;o++)if(i.indexOf(o)>-1)s[o]=Number.MAX_SAFE_INTEGER;else{let l=US(t,r,o),p=n[l];e&1<<l&&(p=Number.MAX_SAFE_INTEGER),s[o]=p}for(let o=0;o<s.length;o++){let l=a[o];s[o]<0&&(s[o]+=l),s[o]=jp(0,s[o],a[o])}return s}function jS(e,t,r){let n=e[t];return(r&1<<t||n==null)&&(n=1),n}function qS(e,t,r,n,a,s){let i=t[a],o=r[a]||1;(e&1<<a||s&1<<a||i==null)&&(o>0?i=Number.MIN_SAFE_INTEGER:i=Number.MAX_SAFE_INTEGER);let l=n[a];return i<0&&(i+=l),i=jp(0,i,l-1),i}function KS(e,t,r,n,a,s){let i=t[a],o=r[a]||1;(e&1<<a||s&1<<a||i==null)&&(o>0?i=Number.MAX_SAFE_INTEGER:i=Number.MIN_SAFE_INTEGER);let l=n[a];return i<0&&(i+=l),o>0?i=jp(0,i,l):i=jp(-1,i,l-1),i}function qB(e,t,r){let n=r.length;for(let a=0;a<r.length;a++)if(r[a]>1){n=a;break}for(let a=n+1;a<r.length;a++)if(t[a]>0||r[a]!==e[a])return!1;return!0}function KB(e,t){let r=e.length>0?e[e.length-1]:1;for(let n=0;n<e.length-1;n++)r+=e[n]*t[n];return r}function XS(e,t,r){let n,a=e.shape.length;typeof t=="number"?n=[t,...new Array(a-1).fill(0)]:t.length<a?n=t.concat(new Array(a-t.length).fill(0)):n=t.slice(),n.forEach(i=>{A(i!==-1,()=>"slice() does not support negative begin indexing.")});let s;return r==null?s=new Array(a).fill(-1):typeof r=="number"?s=[r,...new Array(a-1).fill(-1)]:r.length<a?s=r.concat(new Array(a-r.length).fill(-1)):s=r,s=s.map((i,o)=>i>=0?i:(A(i===-1,()=>`Negative size values should be exactly -1 but got ${i} for the slice() size at index ${o}.`),e.shape[o]-n[o])),[n,s]}function XB(e,t,r,n,a,s,i,o,l){let p;if(n==null?(p=new Array(t.length),p.fill(1)):p=n,i!=null&&i&i-1)throw new Error("Multiple ellipses in slice is not allowed.");let u=!1,d={dims:p.length,numAddAxisAfterEllipsis:0,begin:t.slice(),end:r.slice(),strides:p.slice(),beginMask:a,endMask:s,ellipsisMask:i,newAxisMask:o,shrinkAxisMask:l};for(let b=0;b<d.dims;b++)u&&1<<b&o&&d.numAddAxisAfterEllipsis++,1<<b&i&&(u=!0);u||(d.ellipsisMask|=1<<d.dims,d.dims++);let h={dims:e.length,beginMask:0,endMask:0,beginValid:!1,endValid:!1};ZB(d,h);let c=!0,f=!0,m=!0,g=[],y=[];for(let b=0;b<e.length;++b){if(h.strides[b]===0)throw Error(`strides[${b}] must be non-zero`);let x=!!(h.shrinkAxisMask&1<<b),v=e[b];if(v===-1){g.push(x?1:-1);continue}let w=[h.beginMask&1<<b,h.endMask&1<<b],N=[h.strides[b]>0?0:-1,h.strides[b]>0?v:v-1];if(x&&h.strides[b]<=0)throw Error("only stride 1 allowed on non-range indexing.");m=m&&h.strides[b]===1;let T=!!(h.beginMask&1<<b&&h.endMask&1<<b);if(h.beginValid&&h.endValid){if(x){let F=h.begin[b]<0?v+h.begin[b]:h.begin[b];if(h.begin[b]=F,h.end[b]=h.begin[b]+1,F<0||F>=v)throw Error(`slice index ${h.begin[b]} of dimension ${b} out of bounds.`)}else h.begin[b]=v0(h.begin[b],0,h.strides[b],v,w,N),h.end[b]=v0(h.end[b],1,h.strides[b],v,w,N);let R=h.strides[b]===1&&h.begin[b]===0&&h.end[b]===v;c=c&&R,f=f&&(b===0&&h.strides[b]===1||R)}else c=c&&h.strides[b]===1&&T,f=f&&(b===0&&h.strides[b]===1||T);let E,$=!1;if(h.beginValid&&h.endValid?(E=h.end[b]-h.begin[b],$=!0):x?(E=1,$=!0):T&&v>=0&&(h.strides[b]<0?E=-v:E=v,$=!0),$){let R;E===0||E<0!=h.strides[b]<0?R=0:R=Math.trunc(E/h.strides[b])+(E%h.strides[b]!==0?1:0),g.push(R)}else g.push(-1)}for(let b=0;b<h.finalShapeGatherIndices.length;++b){let x=h.finalShapeGatherIndices[b];x>=0?y.push(g[x]):x===wg&&y.push(1)}return{finalShapeSparse:y.filter((b,x)=>h.finalShapeGatherIndices[x]!==wg),finalShape:y,isIdentity:c,sliceDim0:f,isSimpleSlice:m,begin:h.begin,end:h.end,strides:h.strides}}function ZB(e,t){t.beginMask=0,t.endMask=0,t.shrinkAxisMask=0;let r=0;t.beginValid=e.begin!=null,t.endValid=e.end!=null,t.begin=new Array(t.dims),t.end=new Array(t.dims),t.strides=new Array(t.dims),t.finalShapeGatherIndices=[],t.finalShapeGatherIndicesSparse=[],t.inputShapeGatherIndicesSparse=new Array(t.dims);for(let n=0;n<e.dims;n++)if(1<<n&e.ellipsisMask){let a=Math.min(t.dims-(e.dims-n)+1+e.numAddAxisAfterEllipsis,t.dims);for(;r<a;r++)t.begin[r]=0,t.end[r]=0,t.strides[r]=1,t.beginMask|=1<<r,t.endMask|=1<<r,t.finalShapeGatherIndices.push(r),t.finalShapeGatherIndicesSparse.push(-1),t.inputShapeGatherIndicesSparse[r]=n}else if(1<<n&e.newAxisMask)t.finalShapeGatherIndices.push(wg),t.finalShapeGatherIndicesSparse.push(-1);else{if(r===t.begin.length)throw Error(`Index out of range using input dim ${r}; input has only ${t.dims} dims, ${t.begin.length}.`);e.begin!=null&&(t.begin[r]=e.begin[n]),e.end!=null&&(t.end[r]=e.end[n]),t.strides[r]=e.strides[n],e.beginMask&1<<n&&(t.beginMask|=1<<r),e.endMask&1<<n&&(t.endMask|=1<<r),e.shrinkAxisMask&1<<n?(t.finalShapeGatherIndices.push(UB),t.finalShapeGatherIndicesSparse.push(-1),t.shrinkAxisMask|=1<<r):(t.finalShapeGatherIndices.push(r),t.finalShapeGatherIndicesSparse.push(n)),t.inputShapeGatherIndicesSparse[r]=n,r++}}function v0(e,t,r,n,a,s){if(a[t])return r>0?s[t]:s[t+1&1];{let i=e<0?n+e:e;return i<s[0]?s[0]:i>s[1]?s[1]:i}}var JB="4.22.0",ZS=class{static sgd(e){return new qf(e)}static momentum(e,t,r=!1){return new qb(e,t,r)}static rmsprop(e,t=.9,r=0,n=null,a=!1){return new Kb(e,t,r,n,a)}static adam(e=.001,t=.9,r=.999,n=null){return new Hb(e,t,r,n)}static adadelta(e=.001,t=.95,r=null){return new Vb(e,t,r)}static adamax(e=.002,t=.9,r=.999,n=null,a=0){return new jb(e,t,r,n,a)}static adagrad(e,t=.1){return new Gb(e,t)}},Ks=ZS,YB=typeof requestAnimationFrame<"u"?requestAnimationFrame:typeof setImmediate<"u"?setImmediate:e=>e();function Yb(){return new Promise(e=>YB(()=>e()))}var _={};Ee(_,{ERF_A1:()=>cW,ERF_A2:()=>fW,ERF_A3:()=>mW,ERF_A4:()=>gW,ERF_A5:()=>yW,ERF_P:()=>hW,PARALLELIZE_THRESHOLD:()=>Qb,RowPartitionType:()=>Qn,SELU_SCALE:()=>YS,SELU_SCALEALPHA:()=>JS,applyActivation:()=>Hf,assertAndGetBroadcastShape:()=>ut,assertAxesAreInnerMostDims:()=>XO,assertParamsConsistent:()=>QB,assignToTypedArray:()=>IW,axesAreInnerMostDims:()=>pb,calculateShapes:()=>sS,checkEinsumDimSizes:()=>EW,checkPadOnDimRoundingMode:()=>kr,combineLocations:()=>_I,combineRaggedTensorToTensorShapes:()=>tW,complexWithEvenIndex:()=>vW,complexWithOddIndex:()=>wW,computeConv2DInfo:()=>zd,computeConv3DInfo:()=>yI,computeDefaultPad:()=>jy,computeDilation2DInfo:()=>qM,computeOptimalWindowSize:()=>sW,computeOutAndReduceShapes:()=>TI,computeOutShape:()=>eW,computePool2DInfo:()=>gI,computePool3DInfo:()=>KM,convertConv2DDataFormat:()=>bI,decodeEinsumEquation:()=>TW,eitherStridesOrDilationsAreOne:()=>fa,expandShapeToKeepDim:()=>yi,exponent:()=>NW,exponents:()=>SW,fromStringArrayToUint8:()=>ZW,fromUint8ToStringArray:()=>XW,getAxesPermutation:()=>CI,getBroadcastDims:()=>SI,getComplexWithIndex:()=>kW,getEinsumComputePath:()=>$W,getEinsumPermutation:()=>CW,getFusedBiasGradient:()=>Gf,getFusedDyActivation:()=>Vf,getImageCenter:()=>iW,getInnerMostAxes:()=>ZO,getPermuted:()=>lW,getRaggedRank:()=>nW,getReductionAxes:()=>Ot,getReshaped:()=>oW,getReshapedPermuted:()=>uW,getRowPartitionTypesHelper:()=>rW,getSliceBeginCoords:()=>pW,getSliceSize:()=>dW,getSparseFillEmptyRowsIndicesDenseShapeMismatch:()=>DW,getSparseFillEmptyRowsNegativeIndexErrorMessage:()=>MW,getSparseFillEmptyRowsOutOfRangeIndexErrorMessage:()=>OW,getSparseReshapeEmptyTensorZeroOutputDimErrorMessage:()=>PW,getSparseReshapeInputOutputMismatchErrorMessage:()=>WW,getSparseReshapeInputOutputMultipleErrorMessage:()=>BW,getSparseReshapeMultipleNegativeOneOutputDimErrorMessage:()=>LW,getSparseReshapeNegativeOutputDimErrorMessage:()=>zW,getSparseSegmentReductionIndicesOutOfRangeErrorMessage:()=>HW,getSparseSegmentReductionNegativeSegmentIdsErrorMessage:()=>UW,getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage:()=>VW,getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage:()=>GW,getUndoAxesPermutation:()=>db,isIdentityPermutation:()=>AW,log:()=>sD,mergeRealAndImagArrays:()=>bW,prepareAndValidate:()=>BS,prepareSplitSize:()=>RW,segment_util:()=>QS,shouldFuse:()=>jf,slice_util:()=>Wt,splitRealAndImagArrays:()=>xW,stridesOrDilationsArePositive:()=>gi,tupleValuesAreOne:()=>ms,upcastType:()=>cn,validateDefaultValueShape:()=>aW,validateInput:()=>Pf,validateUpdateShape:()=>Rb,warn:()=>es});function QB(e,t){let r=e[0].length;e.forEach((a,s)=>{A(a.length===r,()=>`Error in concat${r}D: rank of tensors[${s}] must be the same as the rank of the rest (${r})`)}),A(t>=0&&t<r,()=>`Error in concat${r}D: axis must be between 0 and ${r-1}.`);let n=e[0];e.forEach((a,s)=>{for(let i=0;i<r;i++)A(i===t||a[i]===n[i],()=>`Error in concat${r}D: Shape of tensors[${s}] (${a}) does not match the shape of the rest (${n}) along the non-concatenated axis ${s}.`)})}function eW(e,t){let r=e[0].slice();for(let n=1;n<e.length;n++)r[t]+=e[n][t];return r}var Qn;(function(e){e[e.FIRST_DIM_SIZE=0]="FIRST_DIM_SIZE",e[e.VALUE_ROWIDS=1]="VALUE_ROWIDS",e[e.ROW_LENGTHS=2]="ROW_LENGTHS",e[e.ROW_SPLITS=3]="ROW_SPLITS",e[e.ROW_LIMITS=4]="ROW_LIMITS",e[e.ROW_STARTS=5]="ROW_STARTS"})(Qn||(Qn={}));function tW(e,t,r){let n=new Array;if(r==null&&t==null)return n;if(t==null)for(;n.length<e+r.length;)n.push(-1);else n=t.slice();if(r==null)return n;if(e+r.length!==n.length)throw new Error(`rt input.shape and shape=${t} are incompatible: rt input.rank = ${e+r.length}, but shape.rank = ${n.length}`);for(let a=1;a<r.length;++a){let s=r[a],i=n[n.length-r.length+a],o=n[i];if(s>=0)if(o>=0){if(o!==s)throw new Error(`rt input.shape and shape=${t} are incompatible: rt input.shape[${a+e}] = ${s} but shape[${a+e}] = ${o}`)}else n[i]=s}return n}function rW(e){let t={FIRST_DIM_SIZE:Qn.FIRST_DIM_SIZE,VALUE_ROWIDS:Qn.VALUE_ROWIDS,ROW_LENGTHS:Qn.ROW_LENGTHS,ROW_SPLITS:Qn.ROW_SPLITS,ROW_LIMITS:Qn.ROW_LIMITS,ROW_STARTS:Qn.ROW_STARTS},r=[];for(let n of e)if(n in t)r.push(t[n]);else break;return r}function nW(e){return e.length===0?0:e[0]===Qn.FIRST_DIM_SIZE?e.length-1:e.length}function aW(e,t){if(e==null||t==null)return;let r=e.length,n=t.length;if(r>=n)throw new Error(`defaultValue.shape=${e} and ragged tensor flatValues.shape=${t}, are incompatible: defaultValue.rank = ${r} must be less than ragged tensor input flatValues.rank = ${n})`);for(let a=0;a<Math.min(r,n-1);++a){let s=e[a],i=t[a+1];if(s>=0&&i>=0&&s!==1&&s!==i)throw new Error(`defaultValue.shape=${e}, and ragged tensor input flatValues.shape=${t} are incompatible: defaultValue.shape[${a-e.length}] = ${s} but ragged tensor input.flatValues.shape[${a-e.length}] = ${i}`)}}var Qb=30;function sW(e){return e<=Qb?e:mc(e,Math.floor(Math.sqrt(e)))}function iW(e,t,r){let n=r*(typeof e=="number"?e:e[0]),a=t*(typeof e=="number"?e:e[1]);return[n,a]}function oW(e,t,r,n=!0){let a=[];if(n)a=a.concat(t.slice(0)),a.push(e[0]/r),a=a.concat(e.slice(1));else{a=a.concat(e[0]);let s=t.length;for(let i=0;i<s;++i)a=a.concat([e[i+1]/t[i],t[i]]);a=a.concat(e.slice(s+1))}return a}function lW(e,t,r=!0){let n=[];if(r){n.push(t);for(let a=t+1;a<e;++a)a<=2*t?(n.push(a),n.push(a-(t+1))):n.push(a)}else{let a=[],s=[];for(let i=1;i<e;++i)i>=t*2+1||i%2===1?s.push(i):a.push(i);n.push(...a),n.push(0),n.push(...s)}return n}function uW(e,t,r,n=!0){let a=[];n?a.push(e[0]/r):a.push(e[0]*r);for(let s=1;s<e.length;++s)s<=t.length?n?a.push(t[s-1]*e[s]):a.push(e[s]/t[s-1]):a.push(e[s]);return a}function pW(e,t){let r=[0];for(let n=0;n<t;++n)r.push(e[n][0]);return r}function dW(e,t,r){let n=e.slice(0,1);for(let a=0;a<r;++a)n.push(e[a+1]-t[a][0]-t[a][1]);return n}var JS=1.7580993408473768,YS=1.0507009873554805,hW=.3275911,cW=.254829592,fW=-.284496736,mW=1.421413741,gW=-1.453152027,yW=1.061405429;function bW(e,t){if(e.length!==t.length)throw new Error(`Cannot merge real and imag arrays of different lengths. real:${e.length}, imag: ${t.length}.`);let r=new Float32Array(e.length*2);for(let n=0;n<r.length;n+=2)r[n]=e[n/2],r[n+1]=t[n/2];return r}function xW(e){let t=new Float32Array(e.length/2),r=new Float32Array(e.length/2);for(let n=0;n<e.length;n+=2)t[n/2]=e[n],r[n/2]=e[n+1];return{real:t,imag:r}}function vW(e){let t=Math.ceil(e.length/4),r=new Float32Array(t),n=new Float32Array(t);for(let a=0;a<e.length;a+=4)r[Math.floor(a/4)]=e[a],n[Math.floor(a/4)]=e[a+1];return{real:r,imag:n}}function wW(e){let t=Math.floor(e.length/4),r=new Float32Array(t),n=new Float32Array(t);for(let a=2;a<e.length;a+=4)r[Math.floor(a/4)]=e[a],n[Math.floor(a/4)]=e[a+1];return{real:r,imag:n}}function kW(e,t){let r=e[t*2],n=e[t*2+1];return{real:r,imag:n}}function IW(e,t,r,n){e[n*2]=t,e[n*2+1]=r}function SW(e,t){let r=new Float32Array(e/2),n=new Float32Array(e/2);for(let a=0;a<Math.ceil(e/2);a++){let s=(t?2:-2)*Math.PI*(a/e);r[a]=Math.cos(s),n[a]=Math.sin(s)}return{real:r,imag:n}}function NW(e,t,r){let n=(r?2:-2)*Math.PI*(e/t),a=Math.cos(n),s=Math.sin(n);return{real:a,imag:s}}var Lm="->",_W=/->/g,w0=",",k0="...";function TW(e,t){e=e.replace(/\s/g,"");let r=(e.length-e.replace(_W,"").length)/Lm.length;if(r<1)throw new Error("Equations without an arrow are not supported.");if(r>1)throw new Error(`Equation must contain exactly one arrow ("${Lm}").`);let[n,a]=e.split(Lm);A(n.indexOf(k0)===-1,()=>`The ellipsis notation ("${k0}") is not supported yet.`);let s=n.split(w0),i=s.length;if(t!==i)throw new Error(`Expected ${i} input tensors, received ${t}`);if(i>2)throw new Error("Support for more than 2 input tensors is not implemented yet.");let o=[];for(let h=0;h<a.length;++h){let c=a[h];if(!s.some(f=>f.indexOf(c)!==-1))throw new Error(`Output subscripts contain the label ${c} not present in the input subscripts.`);o.indexOf(c)===-1&&o.push(c)}for(let h=0;h<n.length;++h){let c=n[h];o.indexOf(c)===-1&&c!==w0&&o.push(c)}let l=new Array(s.length);for(let h=0;h<i;++h){if(new Set(s[h].split("")).size!==s[h].length)throw new Error(`Found duplicate axes in input component ${s[h]}. Support for duplicate axes in input is not implemented yet.`);l[h]=[];for(let c=0;c<s[h].length;++c)l[h].push(o.indexOf(s[h][c]))}let p=o.length,u=a.length,d=[];for(let h=u;h<p;++h)d.push(h);return{allDims:o,summedDims:d,idDims:l}}function CW(e,t){let r=new Array(e);r.fill(-1);for(let a=0;a<t.length;++a)r[t[a]]=a;let n=[];for(let a=0;a<e;++a)r[a]===-1&&n.push(a);return r=r.filter(a=>a!==-1),{permutationIndices:r,expandDims:n}}function EW(e,t,r){let n=new Array(e);for(let a=0;a<r.length;++a){let s=r[a].shape;for(let i=0;i<t[a].length;++i)n[t[a][i]]===void 0?n[t[a][i]]=s[i]:A(n[t[a][i]]===s[i],()=>`Expected dimension ${n[t[a][i]]} at axis ${i} of input shaped ${JSON.stringify(s)}, but got dimension ${s[i]}`)}}function $W(e,t){let r=e,n=[],a=0;e.length===0&&r.push(-1),a=e.length+1;for(let i=0;i<a;++i)n.push([]);let s=[];for(let i=0;i<r.length;++i){let o=r[i],l=FW(t,o);for(let p of l)s.indexOf(p)===-1&&(n[i].push(p),s.push(p))}return{path:r,steps:n}}function AW(e){return e.every((t,r)=>t===r)}function FW(e,t){let r=[];for(let n=0;n<e.length;++n)(e[n].length===0||e[n].indexOf(t)!==-1||t===-1)&&r.push(n);return r}function RW(e,t,r=0){let n=[];if(typeof t=="number")A(e.shape[r]%t===0,()=>"Number of splits must evenly divide the axis."),n=new Array(t).fill(e.shape[r]/t);else{let a=t.reduce((i,o)=>(o===-1&&(i+=1),i),0);A(a<=1,()=>"There should be only one negative value in split array.");let s=t.indexOf(-1);if(s!==-1){let i=t.reduce((o,l)=>l>0?o+l:o);t[s]=e.shape[r]-i}A(e.shape[r]===t.reduce((i,o)=>i+o),()=>"The sum of sizes must match the size of the axis dimension."),n=t}return n}function DW(e){return`Received SparseTensor with denseShape[0] = 0 but
indices.shape[0] = ${e}`}function MW(e,t){return`indices(${e}, 0) is invalid: ${t} < 0`}function OW(e,t,r){return`indices(${e}, 0) is invalid: ${t} >= ${r}`}function LW(e,t){return`only one output dimension may be -1, not both ${e} and ${t}`}function zW(e,t){return`size ${e} must be non-negative, not ${t}`}function PW(){return"reshape cannot infer the missing input size for an empty tensor unless all specified input sizes are non-zero"}function BW(e,t){let r=nt(e),n=nt(t);return`Input to reshape is a SparseTensor with ${r}
dense values, but the requested shape requires a multiple of ${n}. inputShape=${e} outputShape= ${t}`}function WW(e,t){let r=nt(e),n=nt(t);return`Input to reshape is a tensor with ${r} dense values, but the requested shape has ${n}. inputShape=${e} outputShape=${t}`}function UW(){return"segment ids must be >= 0"}function VW(){return"segment ids are not increasing"}function GW(e,t){return`Segment id ${e} out of range [0, ${t}), possibly because segmentIds input is not sorted.`}function HW(e,t,r){return`Bad: indices[${e}] == ${t} out of range [0, ${r})`}var QS={};Ee(QS,{collectGatherOpShapeInfo:()=>KW,computeOutShape:()=>qW,segOpComputeOptimalWindowSize:()=>jW});function jW(e,t){let r=!1,n;for(e<=Qb?(n=e,r=!0):n=mc(e,Math.floor(Math.sqrt(e)));!r;)n>t||n===e?r=!0:n=mc(e,n+1);return n}function qW(e,t,r){let n=[],a=e.length;for(let s=0;s<a;s++)s!==t?n.push(e[s]):n.push(r);return n}function KW(e,t,r,n){let a=t.shape.length,s=e.shape.length;if(n!==0&&(n<-a||n>a))throw new Error(`Expect batchDims in the range of [-${a}, ${a}], but got ${n}`);if(n<0&&(n+=a),n>s)throw new Error(`batchDims (${n}) must be less than rank(x) (
${s}).`);if(r<n)throw new Error(`batchDims (${n}) must be less than or equal to axis (${r}).`);for(let d=0;d<n;++d)if(e.shape[d]!==t.shape[d])throw new Error(`x.shape[${d}]: ${e.shape[d]} should be equal to indices.shape[${d}]: ${t.shape[d]}.`);let i=e.shape[r],o=[],l=1,p=1,u=1;for(let d=0;d<n;++d)o.push(e.shape[d]),l*=e.shape[d];for(let d=n;d<r;d++)o.push(e.shape[d]),p*=e.shape[d];for(let d=n;d<a;d++)o.push(t.shape[d]);for(let d=r+1;d<s;d++)o.push(e.shape[d]),u*=e.shape[d];return{batchSize:l,sliceSize:u,outerSize:p,dimSize:i,outputShape:o}}function XW(e){try{return e.map(t=>bc(t))}catch(t){throw new Error(`Failed to decode encoded string bytes into utf-8, error: ${t}`)}}function ZW(e){return e.map(t=>Md(t))}var ga={};Ee(ga,{nonMaxSuppressionV3Impl:()=>xS,nonMaxSuppressionV4Impl:()=>vS,nonMaxSuppressionV5Impl:()=>wS,whereImpl:()=>lS});cB();var eN={kernelName:Kl,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>z(e,Yo(se(r,"float32"),-1))}}},JW={kernelName:$i,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>{let n=ot(se(r,"float32")),a=Yt(de(we(1),n));return gt(fe(e,a))}}}},YW={kernelName:Ai,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>{let n=Yt(de(ot(se(r,"float32")),1));return fe(e,n)}}}},QW={kernelName:Ts,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[r,n]=t,a=ut(r.shape,n.shape);return{a:()=>{let s=e,i=Ot(r.shape,a);return i.length>0&&(s=ge(s,i)),B(s,r.shape)},b:()=>{let s=e,i=Ot(n.shape,a);return i.length>0&&(s=ge(s,i)),B(s,n.shape)}}}},e4={kernelName:Fi,saveAllInputs:!0,gradFunc:(e,t)=>{let r={};return t.forEach((n,a)=>{r[a]=()=>e.clone()}),r}},t4={kernelName:Jl,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>He(r)}}},r4={kernelName:Yl,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>He(r)}}},n4={kernelName:Ri,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>fe(e,Yt(de(we(1),ot(se(r,"float32")))))}}},a4={kernelName:Di,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>{let n=Yt(J(we(1),ot(se(r,"float32"))));return fe(e,n)}}}},s4={kernelName:Li,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[r,n]=t,a=ut(r.shape,n.shape);return{a:()=>{let s=J(ot(r),ot(n)),i=z(e,fe(n,s)),o=Ot(r.shape,a);return o.length>0&&(i=ge(i,o)),B(i,r.shape)},b:()=>{let s=J(ot(r),ot(n)),i=gt(z(e,fe(r,s))),o=Ot(n.shape,a);return o.length>0&&(i=ge(i,o)),B(i,n.shape)}}}},i4={kernelName:Mi,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>fe(e,J(ot(se(r,"float32")),1))}}},o4={kernelName:Oi,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>fe(e,de(we(1),ot(se(r,"float32"))))}}};function l4(e,t,r,n,a,s){let i=C(e,"dy","avgPool3dGrad"),o=C(t,"input","avgPool3dGrad"),l=i,p=o,u=!1;o.rank===4&&(u=!0,l=B(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]]),p=B(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),A(l.rank===5,()=>`Error in avgPool3dGrad: dy must be rank 5 but got rank ${l.rank}.`),A(p.rank===5,()=>`Error in avgPool3dGrad: input must be rank 5 but got rank ${p.rank}.`),kr("avgPool3dGrad",a,s);let d={dy:l,input:p},h={filterSize:r,strides:n,pad:a,dimRoundingMode:s},c=O.runKernel(cd,d,h);return u?B(c,[c.shape[1],c.shape[2],c.shape[3],c.shape[4]]):c}var u4=L({avgPool3dGrad_:l4}),p4={kernelName:Ql,inputsToSave:["x"],gradFunc:(e,t,r)=>{let[n]=t,{filterSize:a,strides:s,pad:i,dimRoundingMode:o}=r;return{x:()=>u4(e,n,a,s,i,o)}}};function d4(e,t,r,n,a){let s=C(e,"dy","avgPoolGrad"),i=C(t,"input","avgPoolGrad");A(i.rank===s.rank,()=>`Rank of input (${i.rank}) does not match rank of dy (${s.rank})`);let o=i,l=s,p=!1;i.rank===3&&(p=!0,o=B(i,[1,i.shape[0],i.shape[1],i.shape[2]]),l=B(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(o.rank===4,()=>`Error in avgPoolGrad: input must be rank 4 but got rank ${o.rank}.`);let u={dy:l,input:o},d={filterSize:r,strides:n,pad:a},h=O.runKernel(hd,u,d);return p?B(h,[h.shape[1],h.shape[2],h.shape[3]]):h}var h4=L({avgPoolGrad_:d4}),c4={kernelName:zi,inputsToSave:["x"],gradFunc:(e,t,r)=>{let[n]=t,{filterSize:a,strides:s,pad:i}=r;return{x:()=>h4(e,n,a,s,i)}}},f4={kernelName:Pi,inputsToSave:["a","b"],gradFunc:(e,t,r)=>{let[n,a]=t,{transposeA:s,transposeB:i}=r;return!s&&!i?{a:()=>Me(e,a,!1,!0),b:()=>Me(n,e,!0,!1)}:!s&&i?{a:()=>Me(e,a,!1,!1),b:()=>Me(e,n,!0,!1)}:s&&!i?{a:()=>Me(a,e,!1,!0),b:()=>Me(n,e,!1,!1)}:{a:()=>Me(a,e,!0,!0),b:()=>Me(e,n,!0,!0)}}},m4={kernelName:eu,gradFunc:(e,t,r)=>{let{blockShape:n,crops:a}=r;return{x:()=>qd(e,n,a)}}},g4={kernelName:Pk,gradFunc:(e,t,r)=>{let n=r,a=n.inputShape,s=n.shape,i=Array.from(s);for(let l=a.length-1;l>=0;l--)if(a[l]===s[l])i[l]=1;else if(a[l]!==1)throw new Error(`broadcastTo(): [${a}] cannot be broadcast to [${s}].`);let o=[];for(let l=0;l<i.length;l++)i[l]>1&&o.push(l);return{x:()=>ge(e,o,!0)}}},y4={kernelName:Bi,gradFunc:e=>({x:()=>e.clone()})},b4={kernelName:Wi,gradFunc:e=>({x:()=>He(e)})},x4={kernelName:Cs,inputsToSave:["x"],gradFunc:(e,t,r)=>{let[n]=t,{clipValueMin:a,clipValueMax:s}=r;return{x:()=>Jt(Nn(La(n,a),Fs(n,s)),e,He(e))}}},v4={kernelName:md,inputsToSave:["x"],gradFunc:eN.gradFunc},w4={kernelName:nu,saveAllInputs:!0,gradFunc:(e,t,r)=>{let n=t.map(o=>o.shape),{axis:a}=r,s=_n(a,t[0].shape)[0],i=n.map(o=>o[s]);return Ar(e,i,s).map(o=>()=>o)}},k4={kernelName:Ui,inputsToSave:["x","filter"],gradFunc:(e,t,r)=>{let[n,a]=t,{dilations:s,strides:i,pad:o,dataFormat:l}=r;return A(ms(s),()=>`Error in gradient of conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${s}'`),{x:()=>nb(n.shape,e,a,i,o,l),filter:()=>Bb(n,e,a.shape,i,o,l)}}},I4={kernelName:Vi,inputsToSave:["dy","filter"],gradFunc:(e,t,r)=>{let[n,a]=t,{strides:s,pad:i,dataFormat:o,dimRoundingMode:l}=r;return{dy:()=>br(e,a,s,i,o,1,l),filter:()=>Bb(e,n,a.shape,s,i,o,l)}}};function S4(e,t,r,n,a){let s=e;e.rank===4&&(s=B(e,[1,e.shape[0],e.shape[1],e.shape[2],e.shape[3]]));let i=t;i.rank===4&&(i=B(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]])),A(s.rank===5,()=>`Error in conv3dDerFilter: input must be rank 5, but got shape ${s.shape}.`),A(i.rank===5,()=>`Error in conv3dDerFilter: dy must be rank 5, but got shape ${i.shape}.`),A(r.length===5,()=>`Error in conv3dDerFilter: filterShape must be length 5, but got ${r}.`),A(s.shape[4]===r[3],()=>`Error in conv3dDerFilter: depth of input ${s.shape[4]}) must match input depth in filter (${r[3]}.`),A(i.shape[4]===r[4],()=>`Error in conv3dDerFilter: depth of dy (${i.shape[4]}) must match output depth for filter (${r[4]}).`);let o={x:s,dy:i},l={strides:n,pad:a,filterShape:r};return O.runKernel(au,o,l)}var N4=L({conv3DBackpropFilter_:S4}),_4={kernelName:Gi,inputsToSave:["x","filter"],gradFunc:(e,t,r)=>{let{dilations:n,strides:a,pad:s}=r;A(ms(n),()=>`Error in gradient of conv3D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${n}'`);let[i,o]=t;return{x:()=>kI(i.shape,e,o,a,s),filter:()=>N4(i,e,o.shape,a,s)}}},T4={kernelName:Hi,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>z(gt(Ff(se(r,"float32"))),e)}}},C4={kernelName:ji,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>z(Rf(se(r,"float32")),e)}}},E4={kernelName:qi,inputsToSave:["x"],gradFunc:(e,t,r)=>{let[n]=t,{axis:a,exclusive:s,reverse:i}=r;return{x:()=>{let o=CI([a],n.rank),l=vf(e,a,s,!i);return o!=null&&(l=Oe(l,o)),l}}}},$4={kernelName:Ki,inputsToSave:["x","filter"],gradFunc:(e,t,r)=>{let{dilations:n,strides:a,pad:s,dimRoundingMode:i}=r,o=n??[1,1];A(ms(o),()=>`Error in gradient of depthwiseConv2dNative: dilation rates greater than 1 are not yet supported. Got dilations '${o}'`);let[l,p]=t;return A(l.rank===4,()=>`Error in gradient of depthwiseConv2dNative: input must be rank 4, but got rank ${l.rank}.`),A(p.rank===4,()=>`Error in gradient of depthwiseConv2dNative: filter must be rank 4, but got rank ${p.rank}.`),A(l.shape[3]===p.shape[2],()=>`Error in gradient of depthwiseConv2d: number of input channels (${l.shape[3]}) must match the inChannels dimension in filter ${p.shape[2]}.`),A(fa(a,o),()=>`Error in gradient of depthwiseConv2d: Either strides or dilations must be 1. Got strides ${a} and dilations '${o}'.`),kr("depthwiseConv2d",s,i),{x:()=>gS(l.shape,e,p,a,s,o,i),filter:()=>mS(l,e,p.shape,a,s,o,i)}}},A4={kernelName:Xi,inputsToSave:["x","filter"],gradFunc:(e,t,r)=>{let[n,a]=t,s={x:n,filter:a,dy:e},i={x:n,filter:a,dy:e};return{x:()=>O.runKernel(Tl,s,r),filter:()=>O.runKernel(Cl,i,r)}}},F4={kernelName:Ji,outputsToSave:[!0],gradFunc:(e,t)=>{let[r]=t,n={dy:e,y:r};return{x:()=>O.runKernel(uu,n)}}},R4={kernelName:Yi,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t,n=z(pr(gt(ot(r))),2/Math.sqrt(Math.PI));return{x:()=>z(e,n)}}},D4={kernelName:Qi,outputsToSave:[!0],gradFunc:(e,t)=>{let[r]=t;return{x:()=>z(e,r)}}},M4={kernelName:du,inputsToSave:["input"],gradFunc:(e,t)=>{let[r]=t;return{input:()=>B(e,r.shape)}}},O4={kernelName:eo,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>z(e,pr(r))}}},L4={kernelName:to,gradFunc:e=>({x:()=>He(e)})},z4={kernelName:ro,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[r,n]=t,a=ut(r.shape,n.shape);return{a:()=>{let s=fe(e,se(n,"float32")),i=Ot(r.shape,a);return i.length>0?B(ge(s,i),r.shape):s},b:()=>{let s=z(e,se(r,"float32")),i=Ot(n.shape,a);i.length>0&&(s=B(ge(s,i),n.shape));let o=ot(n);return gt(fe(s,se(o,"float32")))}}}},P4={kernelName:no,inputsToSave:["x","mean","variance","scale"],gradFunc:(e,t,r)=>{let{varianceEpsilon:n}=r,[a,s,i,o]=t,l=o??we(1),p=Ot(s.shape,a.shape),u=[];if(s.rank===1){for(let m=0;m<a.shape.length-1;++m)u.push(a.shape[m]);u.push(1)}let d=de(a,s),h=z(e,l),c=$f(J(i,we(n))),f=z(z(z(c,c),c),we(-.5));return{x:()=>s.rank===1?B(z(z(e,jr(B(c,[1,1,1,s.shape[0]]),u)),l),a.shape):B(z(z(e,c),l),a.shape),mean:()=>{let m=z(z(c,we(-1)),h);return s.rank===1&&(m=ge(m,p)),B(m,s.shape)},variance:()=>{let m=z(z(f,d),h);return s.rank===1&&(m=ge(m,p)),B(m,s.shape)},scale:()=>{let m=z(d,c),g=z(e,m);return s.rank===1&&(g=ge(g,p)),B(g,s.shape)},offset:()=>{let m=e;return s.rank===1&&(m=ge(m,p)),B(m,s.shape)}}}},B4={kernelName:cu,inputsToSave:["x","indices"],gradFunc:(e,t,r)=>{let[n,a]=t,{axis:s,batchDims:i}=r,o=_n(s,n.shape)[0],l=(p,u,d)=>()=>{let h=p.shape,c=u.size,f=h.slice(0,o),m=f.length,g=h.slice(s,h.length).slice(1),y=g.length,b=I0(0,m),x=I0(m+1,m+1+y),v=S0([f,[c],g]),w=B(d,v),N=B(u,[c]),T=S0([[m],b,x]),E=Oe(w,T),$=Wf(E,N,p.shape[o]),R=db(T);return $=Oe($,R),$};if(i===1){let p=n.shape[0],u=n.split(p,0);return{x:()=>Mt(u.map((d,h)=>l(d,a.slice(h,1),e.slice(h,1))())).reshape(n.shape),indices:()=>a}}else return{x:l(n,a,e),indices:()=>a}}};function I0(e,t){let r=[];for(let n=e;n<t;++n)r.push(n);return r}function S0(e){let t=[];for(let r=0;r<e.length;++r)for(let n=0;n<e[r].length;++n)t.push(e[r][n]);return t}var W4={kernelName:ao,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[r,n]=t;return{a:()=>He(r),b:()=>He(n)}}},U4={kernelName:so,gradFunc:e=>({x:()=>se(e,"float32")})},V4={kernelName:io,gradFunc:e=>({x:()=>He(e)})},G4={kernelName:oo,gradFunc:e=>({x:()=>He(e)})},H4={kernelName:lo,gradFunc:e=>({x:()=>He(e)})},j4={kernelName:uo,inputsToSave:["x"],gradFunc:(e,t,r)=>{let[n]=t,{alpha:a}=r,s=Ir(n,0);return{x:()=>Jt(s,e,z(e,a))}}},q4={kernelName:ho,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>fe(e,J(r,1))}}},K4={kernelName:po,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>fe(e,se(r,"float32"))}}},X4={kernelName:Wk,inputsToSave:[],outputsToSave:[!0],gradFunc:(e,t,r)=>{let[n]=t,{axis:a}=r;return{logits:()=>{let s=pr(n);return de(e,z(ge(e,a,!0),s))}}}};function Z4(e,t,r,n=5,a=1,s=1,i=.5){let o={x:e,y:t,dy:r},l={depthRadius:n,bias:a,alpha:s,beta:i};return O.runKernel(ku,o,l)}var J4=L({localResponseNormalizationBackprop_:Z4}),Y4={kernelName:co,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,r)=>{let[n,a]=t,{depthRadius:s,bias:i,alpha:o,beta:l}=r;return{x:()=>J4(n,a,e,s,i,o,l)}}};function tN(e,t,r,n){return t.rank<r.rank&&(t=B(t,yi(t.shape,n))),e.rank<r.rank&&(e=B(e,yi(e.shape,n))),{x:()=>z(e,se(Kr(r,t),e.dtype))}}var N0={kernelName:fo,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,r)=>{let n=r,{reductionIndices:a}=n,s=t[0],i=t[1],o=_n(a,s.shape),l=tN(e,i,s,o);return{x:()=>l.x()}}},Q4={kernelName:mo,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[r,n]=t;return{a:()=>z(e,se(La(r,n),"float32")),b:()=>z(e,se(Al(r,n),"float32"))}}};function eU(e,t,r,n,a,s,i){let o=C(e,"dy","maxPool3dGrad"),l=C(t,"input","maxPool3dGrad"),p=C(r,"output","maxPool3dGrad"),u=o,d=l,h=p,c=!1;l.rank===4&&(c=!0,u=B(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]]),d=B(l,[1,l.shape[0],l.shape[1],l.shape[2],l.shape[3]]),h=B(p,[1,p.shape[0],p.shape[1],p.shape[2],p.shape[3]])),A(u.rank===5,()=>`Error in maxPool3dGrad: dy must be rank 5 but got rank ${u.rank}.`),A(d.rank===5,()=>`Error in maxPool3dGrad: input must be rank 5 but got rank ${d.rank}.`),A(h.rank===5,()=>`Error in maxPool3dGrad: output must be rank 5 but got rank ${h.rank}.`),kr("maxPool3dGrad",s,i);let f={dy:u,input:d,output:h},m={filterSize:n,strides:a,pad:s,dimRoundingMode:i},g=O.runKernel(vd,f,m);return c?B(g,[g.shape[1],g.shape[2],g.shape[3],g.shape[4]]):g}var tU=L({maxPool3dGrad_:eU}),rU={kernelName:Iu,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,r)=>{let[n,a]=t,{filterSize:s,strides:i,pad:o,dimRoundingMode:l}=r;return{x:()=>tU(e,n,a,s,i,o,l)}}};function nU(e,t,r,n,a,s,i){let o=C(e,"dy","maxPoolGrad"),l=C(t,"input","maxPoolGrad"),p=C(r,"output","maxPoolGrad");A(l.rank===o.rank,()=>`Rank of input (${l.rank}) does not match rank of dy (${o.rank})`),A(o.rank===4,()=>`Error in maxPoolGrad: dy must be rank 4 but got rank ${o.rank}.`),A(l.rank===4,()=>`Error in maxPoolGrad: input must be rank 4 but got rank ${l.rank}.`),kr("maxPoolGrad",s,i);let u={dy:o,input:l,output:p},d={filterSize:n,strides:a,pad:s,dimRoundingMode:i};return O.runKernel(xd,u,d)}var aU=L({maxPoolGrad_:nU}),sU={kernelName:go,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,r)=>{let[n,a]=t,{filterSize:s,strides:i,pad:o}=r;return{x:()=>aU(e,n,a,s,i,o)}}},iU={kernelName:yo,inputsToSave:["x"],gradFunc:(e,t,r)=>{let[n]=t,{axis:a}=r,s=_n(a,n.shape),i=TI(n.shape,s)[1],o=nt(i);return{x:()=>{let l=n.shape.slice();s.forEach(u=>{l[u]=1});let p=B(e,l);return fe(z(p,$r(n.shape,"float32")),o)}}}},oU={kernelName:bo,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,r)=>{let n=r,{axis:a}=n,[s,i]=t,o=_n(a,s.shape),l=tN(e,i,s,o);return{x:()=>l.x()}}},lU={kernelName:xo,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[r,n]=t;return{a:()=>z(e,se(Fs(r,n),"float32")),b:()=>z(e,se(Ir(r,n),"float32"))}}},uU={kernelName:vo,inputsToSave:["x"],gradFunc:(e,t,r)=>{let n=t[0],{paddings:a}=r,s=a.map(i=>i[0]);return{x:()=>Ve(e,s,n.shape)}}},pU={kernelName:wo,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[r,n]=t,a=ut(r.shape,n.shape);return{a:()=>{let s=Ot(r.shape,a);return s.length>0?B(ge(e,s),r.shape):e},b:()=>{let s=z(e,gt(Qu(fe(r,n)))),i=Ot(n.shape,a);return i.length>0?B(ge(s,i),n.shape):s}}}},dU={kernelName:ko,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[r,n]=t,a=ut(r.shape,n.shape);return{a:()=>{let s=z(e,se(n,"float32")),i=Ot(r.shape,a);return i.length>0?B(ge(s,i),r.shape):s},b:()=>{let s=z(e,se(r,"float32")),i=Ot(n.shape,a);return i.length>0?B(ge(s,i),n.shape):s}}}},hU={kernelName:Nu,gradFunc:e=>({x:()=>gt(e)})},cU={kernelName:Io,inputsToSave:["indices"],gradFunc:(e,t)=>{let r=t[0];return{indices:()=>It(r.shape,"float32")}}},fU={kernelName:$u,gradFunc:e=>({x:()=>He(e)})},mU={kernelName:Au,saveAllInputs:!0,gradFunc:(e,t,r)=>{let{axis:n}=r;return Tt(e,n).map(a=>()=>a)}},_0={kernelName:So,inputsToSave:["x"],gradFunc:(e,t,r)=>{let n=t[0],{paddings:a}=r,s=a.map(i=>i[0]);return{x:()=>Ve(e,s,n.shape)}}},gU={kernelName:No,inputsToSave:["a","b"],outputsToSave:[!0],gradFunc:(e,t)=>{let[r,n,a]=t,s=r,i=n,o=ut(s.shape,i.shape);return{a:()=>{let l=se(i,"float32"),p=z(e,z(l,da(s,de(l,we(1))))),u=Ot(s.shape,o);return u.length>0&&(p=ge(p,u)),B(p,s.shape)},b:()=>{let l=Ir(s,0),p=Jt(l,Xr(s),He(s)),u=z(e,z(a,p)),d=Ot(i.shape,o);return d.length>0&&(u=ge(u,d)),B(u,i.shape)}}}},yU={kernelName:_o,inputsToSave:["x","alpha"],gradFunc:(e,t)=>{let[r,n]=t,a=Ir(r,0);return{x:()=>Jt(a,e,z(e,n)),alpha:()=>{let s=Jt(a,He(e),z(e,r)),i=Ot(n.shape,e.shape);return i.length>0&&(s=ge(s,i)),B(s,n.shape)}}}};function bU(e,t,r){let n=e.shape.slice();n[r]=1;let a=B(t,n),s=ed(e,r,!0,!1),i=ed(e,r,!0,!0),o=z(s,i);return z(a,o)}function xU(e,t,r){let n=e.shape.length,a=n-r.length,s=_.getAxesPermutation(r,n),i=e;s!=null&&(i=Oe(e,s));let o=i.shape.slice(),l=o.splice(n-r.length,r.length).reduce((d,h)=>d*h,1);o.push(l);let p=i.reshape(o),u=bU(p,t,a);if(u=u.reshape(i.shape),s!=null){let d=_.getUndoAxesPermutation(s);u=Oe(u,d)}return u}var vU={kernelName:To,inputsToSave:["x"],gradFunc:(e,t,r)=>{let[n]=t,{axis:a}=r,s=[];return a==null?s=n.shape.map((i,o)=>o):typeof a=="number"?s=[a]:s=a,{x:()=>xU(n,e,s)}}},wU={kernelName:Zi,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[r,n]=t,a=ut(r.shape,n.shape);return{a:()=>{let s=fe(e,se(n,"float32")),i=Ot(r.shape,a);return i.length>0?B(ge(s,i),r.shape):s},b:()=>{let s=z(e,se(r,"float32")),i=Ot(n.shape,a);i.length>0&&(s=B(ge(s,i),n.shape));let o=ot(n);return gt(fe(s,se(o,"float32")))}}}},kU={kernelName:Co,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>fe(e,gt(ot(r)))}}},IU={kernelName:Fo,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t,n=z(Fs(r,6),Yo(r));return{x:()=>z(e,se(n,"float32"))}}},SU={kernelName:Eo,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>z(e,se(Yo(r),"float32"))}}},NU={kernelName:Fu,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>B(e,r.shape)}}},_U={kernelName:Ao,inputsToSave:["images"],gradFunc:(e,t,r)=>{let[n]=t,a={dy:e,images:n};return{images:()=>O.runKernel(Du,a,r)}}},TU={kernelName:$o,inputsToSave:["images"],gradFunc:(e,t,r)=>{let[n]=t,a={dy:e,images:n};return{images:()=>O.runKernel(Ru,a,r)}}},CU={kernelName:Ro,gradFunc:(e,t,r)=>{let{dims:n}=r,a=_n(n,e.shape);return{x:()=>mn(e,a)}}},EU={kernelName:Do,gradFunc:e=>({x:()=>He(e)})},$U={kernelName:Mo,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>gt(fe(e,z(da(r,1.5),2)))}}},AU={kernelName:zu,inputsToSave:["condition"],gradFunc:(e,t)=>{let[r]=t;return{condition:()=>se(He(r),"float32"),t:()=>z(e,se(r,e.dtype)),e:()=>z(e,se(Hd(r),e.dtype))}}},FU={kernelName:Oo,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>{let n=Ir(r,we(0)),a=we(JS),s=we(YS),i=z(e,s),o=z(z(e,a),pr(se(r,"float32")));return Jt(n,i,o)}}}},RU={kernelName:Bo,outputsToSave:[!0],gradFunc:(e,t)=>{let[r]=t;return{x:()=>z(e,z(r,de(we(1),r)))}}},DU={kernelName:Po,gradFunc:e=>({x:()=>He(e)})},MU={kernelName:Lo,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>z(Bd(se(r,"float32")),e)}}},OU={kernelName:zo,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>z(xf(se(r,"float32")),e)}}},LU={kernelName:Pu,inputsToSave:["x"],gradFunc:(e,t,r)=>{let[n]=t,{begin:a,size:s}=r,i=n.shape,[o,l]=XS(n,a,s),p=[];for(let u=0;u<e.rank;u++)p.push([o[u],i[u]-o[u]-l[u]]);return{x:()=>jn(e,p)}}},zU={kernelName:Go,outputsToSave:[!0],gradFunc:(e,t,r)=>{let[n]=t,{dim:a}=r,s=!0,i=z(e,n);return{logits:()=>de(i,z(ge(i,[a],s),n))}}},PU={kernelName:Wo,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>z(e,In(r))}}},T0={kernelName:Bu,gradFunc:(e,t,r)=>{let{blockShape:n,paddings:a}=r;return{x:()=>Pd(e,n,a)}}},C0={kernelName:Wu,gradFunc:(e,t,r)=>{let{axis:n}=r;return{x:()=>lt(e,n)}}},BU={kernelName:Uo,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>fe(e,z(Yt(se(r,"float32")),2))}}},WU={kernelName:_d,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>z(e,z(se(r,"float32"),2))}}},UU={kernelName:Ho,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[r,n]=t,a=we(2);return{a:()=>z(e,z(a,de(r,n))),b:()=>z(e,z(a,de(n,r)))}}},VU={kernelName:$s,gradFunc:e=>({x:()=>He(e)})},GU={kernelName:jo,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[r,n]=t,a=ut(r.shape,n.shape);return{a:()=>{let s=e,i=Ot(r.shape,a);return i.length>0&&(s=ge(s,i)),B(s,r.shape)},b:()=>{let s=e,i=Ot(n.shape,a);return i.length>0&&(s=ge(s,i)),B(gt(s),n.shape)}}}},HU={kernelName:Vo,inputsToSave:["x"],gradFunc:(e,t,r)=>{let[n]=t,a=n.shape.slice(),{axis:s}=r;_n(s,n.shape).forEach(l=>{a[l]=1});let i=B(e,a),o=z(i,$r(n.shape,"float32"));return{x:()=>o}}},jU={kernelName:qo,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>fe(e,ot(Bd(r)))}}},qU={kernelName:Ko,outputsToSave:[!0],gradFunc:(e,t)=>{let[r]=t;return{x:()=>z(de(we(1),ot(r)),e)}}},KU={kernelName:Es,inputsToSave:["x"],gradFunc:(e,t,r)=>{let[n]=t,{reps:a}=r;return{x:()=>{let s=He(n);if(n.rank===1)for(let i=0;i<a[0];++i)s=J(s,Ve(e,[i*n.shape[0]],[n.shape[0]]));else if(n.rank===2)for(let i=0;i<a[0];++i)for(let o=0;o<a[1];++o)s=J(s,Ve(e,[i*n.shape[0],o*n.shape[1]],[n.shape[0],n.shape[1]]));else if(n.rank===3)for(let i=0;i<a[0];++i)for(let o=0;o<a[1];++o)for(let l=0;l<a[2];++l)s=J(s,Ve(e,[i*n.shape[0],o*n.shape[1],l*n.shape[2]],[n.shape[0],n.shape[1],n.shape[2]]));else if(n.rank===4)for(let i=0;i<a[0];++i)for(let o=0;o<a[1];++o)for(let l=0;l<a[2];++l)for(let p=0;p<a[3];++p)s=J(s,Ve(e,[i*n.shape[0],o*n.shape[1],l*n.shape[2],p*n.shape[3]],[n.shape[0],n.shape[1],n.shape[2],n.shape[3]]));else throw new Error(`Gradient for tile operation is not implemented for rank-${n.rank} tensors yet.`);return s}}}},XU={kernelName:Ta,gradFunc:(e,t,r)=>{let n=r,{perm:a}=n,s=db(a);return{x:()=>Oe(e,s)}}},ZU={kernelName:qu,gradFunc:(e,t,r)=>{let n=r,{axis:a}=n;return{value:()=>Mt(e,a)}}},JU={kernelName:Fd,inputsToSave:["segmentIds"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>YU(e,r)}}};function YU(e,t){let r=ma(t,He(t)),n=ep(e,r),a=La(t,we(0,"int32")),s=n.rank-a.rank;for(let o=0;o<s;++o)a=Xt(a,o+1);a=Nn(a,$r(n.shape,"bool"));let i=He(n);return Jt(a,n,i)}var QU={kernelName:Ku,gradFunc:e=>({x:()=>He(e)})},eV=[eN,JW,YW,QW,e4,t4,r4,n4,a4,s4,i4,o4,p4,c4,f4,m4,g4,y4,b4,x4,v4,w4,I4,k4,_4,T4,C4,E4,$4,A4,wU,F4,R4,D4,M4,O4,z4,L4,P4,B4,W4,U4,V4,G4,H4,j4,q4,K4,X4,Y4,N0,N0,Q4,rU,sU,iU,oU,lU,uU,pU,dU,hU,cU,fU,mU,_0,_0,gU,yU,vU,kU,IU,SU,NU,_U,TU,CU,EU,$U,AU,FU,RU,DU,MU,OU,LU,zU,PU,T0,T0,C0,C0,BU,UU,WU,VU,GU,HU,jU,qU,KU,XU,ZU,JU,QU];for(let e of eV)Uk(e);Y().prototype.abs=function(){return this.throwIfDisposed(),Ft(this)};Y().prototype.acos=function(){return this.throwIfDisposed(),zy(this)};Y().prototype.acosh=function(){return this.throwIfDisposed(),Py(this)};Y().prototype.add=function(e){return this.throwIfDisposed(),J(this,e)};Y().prototype.all=function(e,t){return this.throwIfDisposed(),gf(this,e,t)};Y().prototype.any=function(e,t){return this.throwIfDisposed(),Jp(this,e,t)};Y().prototype.argMax=function(e){return this.throwIfDisposed(),mi(this,e)};Y().prototype.argMin=function(e){return this.throwIfDisposed(),By(this,e)};Y().prototype.asScalar=function(){return this.throwIfDisposed(),A(this.size===1,()=>"The array must have only 1 element."),B(this,[])};Y().prototype.asType=function(e){return this.throwIfDisposed(),se(this,e)};Y().prototype.as1D=function(){return this.throwIfDisposed(),B(this,[this.size])};Y().prototype.as2D=function(e,t){return this.throwIfDisposed(),B(this,[e,t])};Y().prototype.as3D=function(e,t,r){return this.throwIfDisposed(),B(this,[e,t,r])};Y().prototype.as4D=function(e,t,r,n){return this.throwIfDisposed(),B(this,[e,t,r,n])};Y().prototype.as5D=function(e,t,r,n,a){return this.throwIfDisposed(),B(this,[e,t,r,n,a])};Y().prototype.asin=function(){return this.throwIfDisposed(),Wy(this)};Y().prototype.asinh=function(){return this.throwIfDisposed(),Uy(this)};Y().prototype.atan=function(){return this.throwIfDisposed(),Vy(this)};Y().prototype.atan2=function(e){return this.throwIfDisposed(),Gy(this,e)};Y().prototype.atanh=function(){return this.throwIfDisposed(),Hy(this)};Y().prototype.avgPool=function(e,t,r,n){return this.throwIfDisposed(),Oa(this,e,t,r,n)};Y().prototype.batchToSpaceND=function(e,t){return this.throwIfDisposed(),Pd(this,e,t)};Y().prototype.batchNorm=function(e,t,r,n,a){return this.throwIfDisposed(),Xo(this,e,t,r,n,a)};Y().prototype.broadcastTo=function(e){return this.throwIfDisposed(),ai(this,e)};Y().prototype.cast=function(e){return this.throwIfDisposed(),se(this,e)};Y().prototype.ceil=function(){return this.throwIfDisposed(),Yy(this)};Y().prototype.clipByValue=function(e,t){return this.throwIfDisposed(),ur(this,e,t)};Y().prototype.concat=function(e,t){return this.throwIfDisposed(),e instanceof ze&&(e=[e]),lt([this,...e],t)};Y().prototype.conv1d=function(e,t,r,n,a,s){return this.throwIfDisposed(),yf(this,e,t,r,n,a,s)};Y().prototype.conv2dTranspose=function(e,t,r,n,a){return this.throwIfDisposed(),bf(this,e,t,r,n,a)};Y().prototype.conv2d=function(e,t,r,n,a,s){return this.throwIfDisposed(),br(this,e,t,r,n,a,s)};Y().prototype.cos=function(){return this.throwIfDisposed(),Bd(this)};Y().prototype.cosh=function(){return this.throwIfDisposed(),xf(this)};Y().prototype.cumprod=function(e,t,r){return this.throwIfDisposed(),ed(this,e,t,r)};Y().prototype.cumsum=function(e,t,r){return this.throwIfDisposed(),vf(this,e,t,r)};Y().prototype.depthToSpace=function(e,t){return this.throwIfDisposed(),ib(this,e,t)};Y().prototype.depthwiseConv2d=function(e,t,r,n,a,s){return this.throwIfDisposed(),Zo(this,e,t,r,n,a,s)};Y().prototype.dilation2d=function(e,t,r,n,a){return this.throwIfDisposed(),ob(this,e,t,r,n,a)};Y().prototype.divNoNan=function(e){return this.throwIfDisposed(),lb(this,e)};Y().prototype.div=function(e){return this.throwIfDisposed(),fe(this,e)};Y().prototype.dot=function(e){return this.throwIfDisposed(),ub(this,e)};Y().prototype.elu=function(){return this.throwIfDisposed(),Ju(this)};Y().prototype.equal=function(e){return this.throwIfDisposed(),Kr(this,e)};Y().prototype.erf=function(){return this.throwIfDisposed(),wf(this)};Y().prototype.euclideanNorm=function(e,t){return this.throwIfDisposed(),hb(this,e,t)};Y().prototype.exp=function(){return this.throwIfDisposed(),pr(this)};Y().prototype.expandDims=function(e){return this.throwIfDisposed(),Xt(this,e)};Y().prototype.expm1=function(){return this.throwIfDisposed(),cb(this)};Y().prototype.fft=function(){return this.throwIfDisposed(),Zd(this)};Y().prototype.flatten=function(){return this.throwIfDisposed(),B(this,[this.size])};Y().prototype.floor=function(){return this.throwIfDisposed(),Qu(this)};Y().prototype.floorDiv=function(e){return this.throwIfDisposed(),mf(this,e)};Y().prototype.gather=function(e,t,r){return this.throwIfDisposed(),ep(this,e,t,r)};Y().prototype.greaterEqual=function(e){return this.throwIfDisposed(),La(this,e)};Y().prototype.greater=function(e){return this.throwIfDisposed(),Ir(this,e)};Y().prototype.ifft=function(){return this.throwIfDisposed(),Ml(this)};Y().prototype.irfft=function(){return this.throwIfDisposed(),Mf(this)};Y().prototype.isFinite=function(){return this.throwIfDisposed(),fb(this)};Y().prototype.isInf=function(){return this.throwIfDisposed(),mb(this)};Y().prototype.isNaN=function(){return this.throwIfDisposed(),gb(this)};Y().prototype.leakyRelu=function(e){return this.throwIfDisposed(),Ud(this,e)};Y().prototype.lessEqual=function(e){return this.throwIfDisposed(),Fs(this,e)};Y().prototype.less=function(e){return this.throwIfDisposed(),Al(this,e)};Y().prototype.localResponseNormalization=function(e,t,r,n){return this.throwIfDisposed(),yb(this,e,t,r,n)};Y().prototype.logSigmoid=function(){return this.throwIfDisposed(),bb(this)};Y().prototype.logSoftmax=function(e){return this.throwIfDisposed(),Sf(this,e)};Y().prototype.logSumExp=function(e,t){return this.throwIfDisposed(),Gd(this,e,t)};Y().prototype.log=function(){return this.throwIfDisposed(),Xr(this)};Y().prototype.log1p=function(){return this.throwIfDisposed(),Vd(this)};Y().prototype.logicalAnd=function(e){return this.throwIfDisposed(),Nn(this,e)};Y().prototype.logicalNot=function(){return this.throwIfDisposed(),Hd(this)};Y().prototype.logicalOr=function(e){return this.throwIfDisposed(),Nf(this,e)};Y().prototype.logicalXor=function(e){return this.throwIfDisposed(),xb(this,e)};Y().prototype.matMul=function(e,t,r){return this.throwIfDisposed(),Me(this,e,t,r)};Y().prototype.maxPool=function(e,t,r,n){return this.throwIfDisposed(),jt(this,e,t,r,n)};Y().prototype.max=function(e,t){return this.throwIfDisposed(),hn(this,e,t)};Y().prototype.maximum=function(e){return this.throwIfDisposed(),ma(this,e)};Y().prototype.mean=function(e,t){return this.throwIfDisposed(),kt(this,e,t)};Y().prototype.min=function(e,t){return this.throwIfDisposed(),$l(this,e,t)};Y().prototype.minimum=function(e){return this.throwIfDisposed(),ys(this,e)};Y().prototype.mirrorPad=function(e,t){return this.throwIfDisposed(),wb(this,e,t)};Y().prototype.mod=function(e){return this.throwIfDisposed(),kb(this,e)};Y().prototype.mul=function(e){return this.throwIfDisposed(),z(this,e)};Y().prototype.neg=function(){return this.throwIfDisposed(),gt(this)};Y().prototype.norm=function(e,t,r){return this.throwIfDisposed(),Yu(this,e,t,r)};Y().prototype.notEqual=function(e){return this.throwIfDisposed(),bi(this,e)};Y().prototype.oneHot=function(e,t=1,r=0){return this.throwIfDisposed(),Fl(this,e,t,r)};Y().prototype.onesLike=function(){return this.throwIfDisposed(),Zr(this)};Y().prototype.pad=function(e,t){return this.throwIfDisposed(),jn(this,e,t)};Y().prototype.pool=function(e,t,r,n,a,s){return this.throwIfDisposed(),Ib(this,e,t,r,n,a,s)};Y().prototype.pow=function(e){return this.throwIfDisposed(),da(this,e)};Y().prototype.prelu=function(e){return this.throwIfDisposed(),Kd(this,e)};Y().prototype.prod=function(e,t){return this.throwIfDisposed(),Sb(this,e,t)};Y().prototype.reciprocal=function(){return this.throwIfDisposed(),Eb(this)};Y().prototype.relu=function(){return this.throwIfDisposed(),rt(this)};Y().prototype.relu6=function(){return this.throwIfDisposed(),Cf(this)};Y().prototype.reshapeAs=function(e){return this.throwIfDisposed(),B(this,e.shape)};Y().prototype.reshape=function(e){return this.throwIfDisposed(),B(this,e)};Y().prototype.resizeBilinear=function(e,t,r){return this.throwIfDisposed(),kS(this,e,t,r)};Y().prototype.resizeNearestNeighbor=function(e,t,r){return this.throwIfDisposed(),IS(this,e,t,r)};Y().prototype.reverse=function(e){return this.throwIfDisposed(),mn(this,e)};Y().prototype.rfft=function(){return this.throwIfDisposed(),Jd(this)};Y().prototype.round=function(){return this.throwIfDisposed(),Ef(this)};Y().prototype.rsqrt=function(){return this.throwIfDisposed(),$f(this)};Y().prototype.selu=function(){return this.throwIfDisposed(),Af(this)};Y().prototype.separableConv2d=function(e,t,r,n,a,s){return this.throwIfDisposed(),tp(this,e,t,r,n,a,s)};Y().prototype.sigmoid=function(){return this.throwIfDisposed(),In(this)};Y().prototype.sign=function(){return this.throwIfDisposed(),$b(this)};Y().prototype.sin=function(){return this.throwIfDisposed(),Ff(this)};Y().prototype.sinh=function(){return this.throwIfDisposed(),Rf(this)};Y().prototype.slice=function(e,t){return this.throwIfDisposed(),Ve(this,e,t)};Y().prototype.softmax=function(e){return this.throwIfDisposed(),Ds(this,e)};Y().prototype.softplus=function(){return this.throwIfDisposed(),Jo(this)};Y().prototype.spaceToBatchND=function(e,t){return this.throwIfDisposed(),qd(this,e,t)};Y().prototype.split=function(e,t){return this.throwIfDisposed(),Ar(this,e,t)};Y().prototype.sqrt=function(){return this.throwIfDisposed(),Yt(this)};Y().prototype.square=function(){return this.throwIfDisposed(),ot(this)};Y().prototype.squaredDifference=function(e){return this.throwIfDisposed(),Of(this,e)};Y().prototype.squeeze=function(e){return this.throwIfDisposed(),Ms(this,e)};Y().prototype.stack=function(e,t){this.throwIfDisposed();let r=e instanceof ze?[this,e]:[this,...e];return Mt(r,t)};Y().prototype.step=function(e){return this.throwIfDisposed(),Yo(this,e)};Y().prototype.stridedSlice=function(e,t,r,n,a,s,i,o){return this.throwIfDisposed(),Ab(this,e,t,r,n,a,s,i,o)};Y().prototype.sub=function(e){return this.throwIfDisposed(),de(this,e)};Y().prototype.sum=function(e,t){return this.throwIfDisposed(),ge(this,e,t)};Y().prototype.tan=function(){return this.throwIfDisposed(),Fb(this)};Y().prototype.tanh=function(){return this.throwIfDisposed(),gs(this)};Y().prototype.tile=function(e){return this.throwIfDisposed(),jr(this,e)};Y().prototype.toBool=function(){return this.throwIfDisposed(),se(this,"bool")};Y().prototype.toFloat=function(){return this.throwIfDisposed(),se(this,"float32")};Y().prototype.toInt=function(){return this.throwIfDisposed(),se(this,"int32")};Y().prototype.topk=function(e,t){return this.throwIfDisposed(),Db(this,e,t)};Y().prototype.transpose=function(e){return this.throwIfDisposed(),Oe(this,e)};Y().prototype.unique=function(e){return this.throwIfDisposed(),Mb(this,e)};Y().prototype.unsortedSegmentSum=function(e,t){return this.throwIfDisposed(),Wf(this,e,t)};Y().prototype.unstack=function(e){return this.throwIfDisposed(),Tt(this,e)};Y().prototype.where=function(e,t){return this.throwIfDisposed(),Jt(e,this,t)};Y().prototype.zerosLike=function(){return this.throwIfDisposed(),He(this)};var Ya=class rN extends Error{constructor(t){super(t),Object.setPrototypeOf(this,rN.prototype)}},na=class nN extends Error{constructor(t){super(t),Object.setPrototypeOf(this,nN.prototype)}},V=class aN extends Error{constructor(t){super(t),Object.setPrototypeOf(this,aN.prototype)}},Be=class sN extends Error{constructor(t){super(t),Object.setPrototypeOf(this,sN.prototype)}},tV=class iN extends Error{constructor(t){super(t),Object.setPrototypeOf(this,iN.prototype)}},oN=class{constructor(e){this.maxEntries=e||100,this.cache=new Map}get(e){let t;return this.cache.has(e)&&(t=this.cache.get(e),this.cache.delete(e),this.cache.set(e,t)),t}put(e,t){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.maxEntries){let r=this.cache.keys().next().value;this.cache.delete(r)}this.cache.set(e,t)}getMaxEntries(){return this.maxEntries}setMaxEntries(e){if(e<0)throw new Error(`The maxEntries of LRU caches must be at least 0, but got ${e}.`);if(this.maxEntries>e)for(let t=0;t<this.maxEntries-e;t++){let r=this.cache.keys().next().value;this.cache.delete(r)}this.maxEntries=e}};function vi(e,t){if(Array.isArray(e)){let r=[];for(let n=0;n<t;n++)r=r.concat(e);return r}else{let r=new Array(t);return r.fill(e),r}}function ea(e,t){if(!e)throw new tV(t)}function E0(e,t){let r=0;for(let n of e)n===t&&r++;return r}function Er(e){return e.length===1?e[0]:e}function tt(e){return Array.isArray(e)?e:[e]}function ka(e){let t=e.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 Ys(e){return e.length<=1||e.indexOf("_")===-1?e:e.replace(/[_]+(\w|$)/g,(t,r)=>r.toUpperCase())}var bn={};function ex(e){if(e==null)return null;let t={};return t.className=e.getClassName(),t.config=e.getConfig(),t}function kg(e){if(!(e==null||typeof e!="object"))if(Array.isArray(e))e.forEach(t=>kg(t));else{let t=Object.keys(e);for(let r of t){let n=e[r];n!=null&&typeof n=="object"&&(!Array.isArray(n)&&n.type==="ndarray"&&typeof n.value=="number"?e[r]=n.value:kg(n))}}}function Qd(e,t={},r={},n="object",a=!1){if(typeof e=="string"){let s=e,i;if(s in r)i=r[s];else if(s in bn)i=bn[s];else if(i=t[s],i==null)throw new V(`Unknown ${n}: ${e}. This may be due to one of the following reasons:
1. The ${n} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.
2. The custom ${n} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);return i}else{let s=e;if(s.className==null||s.config==null)throw new V(`${n}: Improper config format: ${JSON.stringify(s)}.
'className' and 'config' must set.`);let i=s.className,o,l;if(i in r?[o,l]=r[i]:i in bn?[o,l]=bn.className:i in t&&([o,l]=t[i]),o==null)throw new V(`Unknown ${n}: ${i}. This may be due to one of the following reasons:
1. The ${n} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.
2. The custom ${n} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);if(l!=null){let p={};for(let c of Object.keys(bn))p[c]=bn[c];for(let c of Object.keys(r))p[c]=r[c];let u=s.config;u.customObjects=p;let d=Object.assign({},bn);for(let c of Object.keys(r))bn[c]=r[c];kg(s.config);let h=l(o,s.config,r,a);return bn=Object.assign({},d),h}else{let p=Object.assign({},bn);for(let d of Object.keys(r))bn[d]=r[d];let u=new o(s.config);return bn=Object.assign({},p),u}}}function rV(e,t){return e<t?-1:e>t?1:0}function Fh(e,t){return-1*rV(e,t)}function os(e){if(e==null)return e;let t=[];for(let r of e)t.indexOf(r)===-1&&t.push(r);return t}function nV(e){if(e==null)throw new V(`Invalid value in obj: ${JSON.stringify(e)}`);for(let t in e)if(e.hasOwnProperty(t))return!1;return!0}function Qo(e,t,r){if(r!=null&&e.indexOf(r)<0)throw new V(`${r} is not a valid ${t}. Valid values are ${e} or null/undefined.`)}function tx(e,t,r=0,n=1/0){return ea(r>=0),ea(n>=r),Array.isArray(e)&&e.length>=r&&e.length<=n&&e.every(a=>typeof a===t)}function Zt(e,t){Array.isArray(e)?(k.assert(e.length>0,()=>`${t} is unexpectedly an empty array.`),e.forEach((r,n)=>Zt(r,`element ${n+1} of ${t}`))):k.assert(Number.isInteger(e)&&e>0,()=>`Expected ${t} to be a positive integer, but got ${lN(e)}.`)}function lN(e){return e===null?"null":Array.isArray(e)?"["+e.map(t=>lN(t)).join(",")+"]":typeof e=="string"?`"${e}"`:`${e}`}function aV(e,t,r){let n=r!=null?r():k.now(),a;return(...s)=>{let i=r!=null?r():k.now();return i-n<t||(n=i,a=e(...s)),a}}function uN(e){return e==="relu"?"relu":e==="linear"?"linear":e==="elu"?"elu":null}var sV=0;function pN(){return sV++}var Rh={};function Kf(e=""){return e in Rh||(Rh[e]=0),Rh[e]+=1,e+Rh[e].toString()}var iV=["channelsFirst","channelsLast"],oV=["nearest","bilinear"],lV=["valid","same","causal"],uV=["max","avg"],pV=["sum","mul","concat","ave"],dl=new Map;function Ct(e){Qo(iV,"DataFormat",e)}function dV(e){Qo(oV,"InterpolationFormat",e)}function gn(e){Qo(lV,"PaddingMode",e)}function dN(e){Qo(uV,"PoolMode",e)}var Bp=[],$0="/";function si(e,t){Bp.push(e);try{let r=t();return Bp.pop(),r}catch(r){throw Bp.pop(),r}}function hV(){return Bp.length===0?"":Bp.join($0)+$0}function hN(e){if(!fN(e))throw new Error("Not a valid tensor name: '"+e+"'");return hV()+e}function cN(e){if(!fN(e))throw new Error("Not a valid tensor name: '"+e+"'");dl.has(e)||dl.set(e,0);let t=dl.get(e);if(dl.set(e,dl.get(e)+1),t>0){let r=`${e}_${t}`;return dl.set(r,1),r}else return e}var cV=new RegExp(/^[A-Za-z0-9][-A-Za-z0-9\._\/]*$/);function fN(e){return!!e.match(cV)}function fV(e){return e===parseInt(e.toString(),10)}function ls(e,t,r){t==null&&(t=0),r==null&&(r=e.length);let n=1;for(let a=t;a<r;++a)n*=e[a];return n}function Ll(e){if(e.length===0)return Number.NaN;let t=Number.POSITIVE_INFINITY;for(let r=0;r<e.length;r++){let n=e[r];n<t&&(t=n)}return t}function xs(e){if(e.length===0)return Number.NaN;let t=Number.NEGATIVE_INFINITY;for(let r=0;r<e.length;r++){let n=e[r];n>t&&(t=n)}return t}function Bn(e,t){if(t<e)throw new V(`end (${t}) < begin (${e}) is forbidden.`);let r=[];for(let n=e;n<t;++n)r.push(n);return r}var zm;function Bt(){return zm==null&&(zm=Dy().epsilon()),zm}function Wn(){return"channelsLast"}function Fa(e,t){return se(e,t)}function eh(e,t=-1){let r=e.shape.slice();return t<0&&(t=r.length+t+1),r.splice(t,0,1),B(e,r)}function mV(e,t){return W(()=>{if(e.shape.length!==2)throw new V(`repeat() expects a rank-2 tensor, but received a rank-${e.shape.length} tensor.`);let r=eh(e,1);return Ig(r,[1,t,1])})}function gV(e){let t=[ls(e.shape)];return B(e,t)}function yV(e){if(e.rank<=1)throw new V(`batchFlatten requires a minimum rank of 2. Got rank: ${e.rank}.`);let t=[e.shape[0],ls(e.shape,1)];return B(e,t)}function ii(e,t,r){return W(()=>{switch(e.rank){case 1:return Xd(e,t,r);case 2:return Df(e,[t,0],[r,e.shape[1]]);case 3:return rp(e,[t,0,0],[r,e.shape[1],e.shape[2]]);case 4:return Dl(e,[t,0,0,0],[r,e.shape[1],e.shape[2],e.shape[3]]);case 5:return Ve(e,[t,0,0,0,0],[r,e.shape[1],e.shape[2],e.shape[3],e.shape[4]]);case 6:return Ve(e,[t,0,0,0,0,0],[r,e.shape[1],e.shape[2],e.shape[3],e.shape[4],e.shape[5]]);default:throw new V(`sliceAlongFirstAxis() received an unsupported tensor rank: ${e.rank}`)}})}function Pm(e,t,r){return W(()=>{switch(e.rank){case 1:return Xd(e,t,r);case 2:return Df(e,[0,t],[e.shape[0],r]);case 3:return rp(e,[0,0,t],[e.shape[0],e.shape[1],r]);case 4:return Dl(e,[0,0,0,t],[e.shape[0],e.shape[1],e.shape[2],r]);default:throw new V(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`)}})}function Dh(e,t,r,n){return W(()=>{switch(e.rank){case 1:return Xd(e,t,r);case 2:switch(n){case 1:return ii(e,t,r);case 2:return Pm(e,t,r);default:throw new V(`The axis is not within the rank of the tensor ${n}`)}case 3:switch(n){case 1:return ii(e,t,r);case 2:return rp(e,[0,t,0],[e.shape[0],r,e.shape[2]]);case 3:return Pm(e,t,r);default:throw new V(`The axis is not within the rank of the tensor ${n}`)}case 4:switch(n){case 1:return ii(e,t,r);case 2:return Dl(e,[0,t,0,0],[e.shape[0],r,e.shape[2],e.shape[3]]);case 3:return Dl(e,[0,0,t,0],[e.shape[0],e.shape[1],r,e.shape[3]]);case 4:return Pm(e,t,r);default:throw new V(`The axis is not within the rank of the tensor ${n}`)}default:throw new V(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`)}})}function rx(e,t=-1){let r;return t<0&&(r=e[0].rank,r!==0?t=r:t=0),t===e[0].rank&&(t=-1),lt(e,t)}function A0(e,t){switch(e.rank){case 1:return Qy([e,t]);case 2:return eb([e,t],0);case 3:return tb([e,t],0);case 4:return rb([e,t],0);default:throw new V(`concatAlongFirstAxis() received an unsupported tensor rank: ${e.rank}`)}}function Ig(e,t){if(Array.isArray(t)||(t=[t]),e.rank!==t.length)throw new V(`The length of input n (${t.length}) does not match the number of dimensions in input x (${e.rank})`);return jr(e,t)}function Xf(e,t=0,r=1,n,a){return Tf(e,t,r,n,a)}function oa(e,t,r,n){if(e.rank<2||t.rank<2)throw new Be(`dot requires both inputs to be rank >= 2 but got x shape = ${e.shape} and y shape = ${t.shape}`);if(t.rank>=3){let a=e.shape.slice(-1)[0],s=t.shape.slice(-2)[0];if(a!==s)throw new Be(`If rank y >= 3, then the second last dim of y must equal the last dim of x but got x shape = ${e.shape} and y shape = ${t.shape}`)}if(e.rank===2&&t.rank===2)return Ol.matMul({a:e,b:t,transposeA:!1,transposeB:!1,bias:n?Sg(e.rank,n,Wn()):null,activation:r});{let a=e.shape.slice(),s=a.pop();e=B(e,[-1,s]);let i=t.shape.slice(),o=i.pop(),l=i.pop(),p=[...i,o],u=Array.from({length:t.rank},(h,c)=>c===0?t.rank-2:c<=t.rank-2?c-1:c);t=B(Oe(t,u),[l,-1]);let d=[...a,...p];return B(Ol.matMul({a:e,b:t,transposeA:!1,transposeB:!1,bias:n?Sg(e.rank,n,Wn()):null,activation:r}),d)}}function mN(e,t,r){return W(()=>(Array.isArray(t)?t=Qe(t,"int32"):t=se(t,"int32"),ep(e,t,r)))}function th(e){return z(e,e)}function Sg(e,t,r){let n=t.shape;if(t.rank!==1&&t.rank!==e)throw new V(`Unexpected bias dimensions: ${t.rank}; expected it to be 1 or ${e}`);if(e===5){if(r==="channelsFirst")return n.length===1?B(t,[1,n[0],1,1,1]):B(t,[1,n[3],n[0],n[1],n[2]]);if(r==="channelsLast")return n.length===1?B(t,[1,1,1,1,n[0]]):B(t,[1].concat(n))}else if(e===4){if(r==="channelsFirst")return n.length===1?B(t,[1,n[0],1,1]):B(t,[1,n[2],n[0],n[1]]);if(r==="channelsLast")return n.length===1?B(t,[1,1,1,n[0]]):B(t,[1].concat(n))}else if(e===3){if(r==="channelsFirst")return n.length===1?B(t,[1,n[0],1]):B(t,[1,n[1],n[0]]);if(r==="channelsLast")return n.length===1?B(t,[1,1,n[0]]):B(t,[1].concat(n))}else if(e<3)return t;throw new V(`Unsupported input rank by biasAdd: ${t.rank}`)}function qn(e,t,r){return W(()=>(r==null&&(r=Wn()),Ct(r),J(e,Sg(e.rank,t,r))))}function bV(e,t=1){if(t!==1)throw new Be(`Support for alpha values other than 1 (${t}) is not implemented yet.`);return Ju(e)}function xV(e){return W(()=>fe(e,J(Ft(e),1)))}function gN(e,t,r,n){return W(()=>zb(e,t,r,n))}function vV(e){return W(()=>{let t=J(.5,z(.2,e));return ur(t,0,1)})}function rh(e,t,r=!1){return r?e():t()}var wV=["fanIn","fanOut","fanAvg"],kV=["normal","uniform","truncatedNormal"];function IV(e){Qo(wV,"FanMode",e)}function SV(e){Qo(kV,"Distribution",e)}var Tn=class extends ne.Serializable{fromConfigUsesCustomObjects(){return!1}getConfig(){return{}}},nx=class extends Tn{apply(e,t){return It(e,t)}};nx.className="Zeros";ne.registerClass(nx);var Zf=class extends Tn{apply(e,t){return $r(e,t)}};Zf.className="Ones";ne.registerClass(Zf);var ax=class extends Tn{constructor(e){if(super(),typeof e!="object")throw new V(`Expected argument of type ConstantConfig but got ${e}`);if(e.value===void 0)throw new V(`config must have value set but got ${e}`);this.value=e.value}apply(e,t){return W(()=>z(we(this.value),$r(e,t)))}getConfig(){return{value:this.value}}};ax.className="Constant";ne.registerClass(ax);var sx=class extends Tn{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 Rs(e,this.minval,this.maxval,t,this.seed)}getConfig(){return{minval:this.minval,maxval:this.maxval,seed:this.seed}}};sx.className="RandomUniform";ne.registerClass(sx);var ix=class extends Tn{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 Be(`randomNormal does not support dType ${t}.`);return Xf(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}};ix.className="RandomNormal";ne.registerClass(ix);var ox=class extends Tn{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 Be(`truncatedNormal does not support dType ${t}.`);return Bf(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}};ox.className="TruncatedNormal";ne.registerClass(ox);var lx=class extends Tn{constructor(e){super(),this.gain=e.gain!=null?e.gain:1}apply(e,t){return W(()=>{if(e.length!==2||e[0]!==e[1])throw new V("Identity matrix initializer can only be used for 2D square matrices.");return z(this.gain,kf(e[0]))})}getConfig(){return{gain:this.gain}}};lx.className="Identity";ne.registerClass(lx);function NV(e,t="channelsLast"){let r,n;if(Ct(t),e.length===2)r=e[0],n=e[1];else if([3,4,5].indexOf(e.length)!==-1){if(t==="channelsFirst"){let a=ls(e,2);r=e[1]*a,n=e[0]*a}else if(t==="channelsLast"){let a=ls(e,0,e.length-2);r=e[e.length-2]*a,n=e[e.length-1]*a}}else{let a=ls(e);r=Math.sqrt(a),n=Math.sqrt(a)}return[r,n]}var Dr=class extends Tn{constructor(e){if(super(),e.scale<0)throw new V(`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,IV(this.mode),this.distribution=e.distribution==null?"normal":e.distribution,SV(this.distribution),this.seed=e.seed}apply(e,t){let r=NV(e),n=r[0],a=r[1],s=this.scale;if(this.mode==="fanIn"?s/=Math.max(1,n):this.mode==="fanOut"?s/=Math.max(1,a):s/=Math.max(1,(n+a)/2),this.distribution==="normal"){let i=Math.sqrt(s);if(t=t||"float32",t!=="float32"&&t!=="int32")throw new Be(`${this.getClassName()} does not support dType ${t}.`);return Bf(e,0,i,t,this.seed)}else{let i=Math.sqrt(3*s);return Rs(e,-i,i,t,this.seed)}}getConfig(){return{scale:this.scale,mode:this.mode,distribution:this.distribution,seed:this.seed}}};Dr.className="VarianceScaling";ne.registerClass(Dr);var Jf=class extends Dr{constructor(e){super({scale:1,mode:"fanAvg",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return Dr.className}};Jf.className="GlorotUniform";ne.registerClass(Jf);var Yf=class extends Dr{constructor(e){super({scale:1,mode:"fanAvg",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return Dr.className}};Yf.className="GlorotNormal";ne.registerClass(Yf);var Qf=class extends Dr{constructor(e){super({scale:2,mode:"fanIn",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return Dr.className}};Qf.className="HeNormal";ne.registerClass(Qf);var em=class extends Dr{constructor(e){super({scale:2,mode:"fanIn",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return Dr.className}};em.className="HeUniform";ne.registerClass(em);var tm=class extends Dr{constructor(e){super({scale:1,mode:"fanIn",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return Dr.className}};tm.className="LeCunNormal";ne.registerClass(tm);var rm=class extends Dr{constructor(e){super({scale:1,mode:"fanIn",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return Dr.className}};rm.className="LeCunUniform";ne.registerClass(rm);var ux=class extends Tn{constructor(e){super(),this.DEFAULT_GAIN=1,this.ELEMENTS_WARN_SLOW=2e3,this.gain=e.gain==null?this.DEFAULT_GAIN:e.gain,this.seed=e.seed}apply(e,t){return W(()=>{if(e.length<2)throw new Be("Shape must be at least 2D.");if(t!=="int32"&&t!=="float32"&&t!==void 0)throw new TypeError(`Unsupported data type ${t}.`);t=t;let r=k.sizeFromShape(e.slice(0,-1)),n=e[e.length-1],a=r*n;a>this.ELEMENTS_WARN_SLOW&&console.warn(`Orthogonal initializer is being called on a matrix with more than ${this.ELEMENTS_WARN_SLOW} (${a}) elements: Slowness may result.`);let s=[Math.max(n,r),Math.min(n,r)],i=Xf(s,0,1,t,this.seed),o=Ub.qr(i,!1),l=o[0],p=o[1].flatten().stridedSlice([0],[Math.min(n,r)*Math.min(n,r)],[Math.min(n,r)+1]);return l=z(l,p.sign()),r<n&&(l=l.transpose()),z(we(this.gain),l.reshape(e))})}getConfig(){return{gain:this.gain,seed:this.seed}}};ux.className="Orthogonal";ne.registerClass(ux);var F0={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 R0(e,t={}){return Qd(e,ne.SerializationMap.getMap().classNameMap,t,"initializer")}function St(e){return ex(e)}function xt(e){if(typeof e=="string"){let t=e in F0?F0[e]:e;if(t==="GlorotNormal")return new Yf;if(t==="GlorotUniform")return new Jf;if(t==="HeNormal")return new Qf;if(t==="HeUniform")return new em;if(t==="LeCunNormal")return new tm;if(t==="LeCunUniform")return new rm;{let r={};return r.className=t,r.config={},R0(r)}}else return e instanceof Tn?e:R0(e)}function Ng(e){return Array.isArray(e)&&Array.isArray(e[0])}function wc(e){return e.length===0?[]:Array.isArray(e[0])?e:[e]}function Te(e){let t;if(Array.isArray(e)){if(e.length!==1)throw new V(`Expected Tensor length to be 1; got ${e.length}`);t=e[0]}else t=e;return t}function Xe(e){if(Array.isArray(e)&&Array.isArray(e[0])){if(e.length===1)return e=e,e[0];throw new V(`Expected exactly 1 Shape; got ${e.length}`)}else return e}function kc(e){let t=0;for(let r of e)r.shape.length===0?t+=1:t+=r.shape.reduce((n,a)=>n*a);return t}var D0="Variable",yN=class{constructor(e,t="float32",r=D0,n=!0,a=null){this.dtype=t??"float32",this.shape=e.shape,this.id=pN(),r=r??D0,this.originalName=hN(r),this.name=cN(this.originalName),this.trainable_=n,this.constraint=a,this.val=Ob(e,this.trainable_,this.name,this.dtype)}read(){return this.assertNotDisposed(),this.val}write(e){return this.assertNotDisposed(),_V(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 _V(e,t){if(e.shape.toString()!==t.shape.toString())throw new Error("Shape mismatch: "+JSON.stringify(e.shape)+" vs. "+JSON.stringify(t.shape))}function _g(e){return e.map(t=>t.read())}function px(e){e.forEach(t=>{t[0].write(t[1])})}var Rt=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||{}}},Un=class{constructor(e,t,r,n,a,s,i){this.dtype=e,this.shape=t,this.sourceLayer=r,this.inputs=n,this.callArgs=a,this.outputTensorIndex=i,this.id=pN(),s!=null&&(this.originalName=hN(s),this.name=cN(this.originalName)),this.rank=t.length}},TV=0,nm=class{constructor(e,t){this.callArgs=t,this.id=TV++,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 r of e.inboundLayers)r!=null&&r.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}}},CV=0,We=class extends ne.Serializable{constructor(e={}){super(),this._callHook=null,this._addedWeightNames=[],this._stateful=!1,this.id=CV++,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 r=this.getClassName();t=ka(r)+"_"+Kf(r)}if(this.name=t,this.trainable_=e.trainable==null?!0:e.trainable,e.inputShape!=null||e.batchInputShape!=null){let r;if(e.batchInputShape!=null)r=e.batchInputShape;else if(e.inputShape!=null){let a=null;e.batchSize!=null&&(a=e.batchSize),r=[a].concat(e.inputShape)}this.batchInputShape=r;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 na(`The layer has never been called and thus has no defined ${t}.`);if(this.inboundNodes.length<=e)throw new V(`Asked to get ${t} at node ${e}, but the layer has only ${this.inboundNodes.length} inbound nodes.`);return this.inboundNodes[e]}getInputAt(e){return Er(this.getNodeAtIndex(e,"input").inputTensors)}getOutputAt(e){return Er(this.getNodeAtIndex(e,"output").outputTensors)}get input(){if(this.inboundNodes.length>1)throw new Ya(`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 Ya(`Layer ${this.name} is not connected, no input to return.`);return Er(this.getNodeAtIndex(0,"input").inputTensors)}get output(){if(this.inboundNodes.length===0)throw new Ya(`Layer ${this.name} has no inbound nodes.`);if(this.inboundNodes.length>1)throw new Ya(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer output" is ill-defined. Use \`getOutputAt(nodeIndex)\` instead.`);return Er(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){let t=tt(e);if(this.inputSpec==null||this.inputSpec.length===0)return;let r=tt(this.inputSpec);if(t.length!==r.length)throw new V(`Layer ${this.name} expects ${r.length} inputs, but it received ${t.length} input tensors. Input received: ${e}`);for(let n=0;n<t.length;n++){let a=t[n],s=r[n];if(s==null)continue;let i=a.rank;if(s.ndim!=null&&i!==s.ndim)throw new V(`Input ${n} is incompatible with layer ${this.name}: expected ndim=${s.ndim}, found ndim=${i}`);if(s.maxNDim!=null&&i>s.maxNDim)throw new V(`Input ${n} is incompatible with layer ${this.name}: expected max_ndim=${s.maxNDim}, found ndim=${i}`);if(s.minNDim!=null&&i<s.minNDim)throw new V(`Input ${n} is incompatible with layer ${this.name}: expected min_ndim=${s.minNDim}, found ndim=${i}.`);if(s.dtype!=null&&a.dtype!==s.dtype)throw new V(`Input ${n} is incompatible with layer ${this.name} : expected dtype=${s.dtype}, found dtype=${a.dtype}.`);if(s.axes){let o=a.shape;for(let l in s.axes){let p=Number(l),u=s.axes[l],d=p>=0?o[p]:o[o.length+p];if(u!=null&&[u,null].indexOf(d)===-1)throw new V(`Input ${n} is incompatible with layer ${this.name}: expected axis ${p} of input shape to have value ${u} but got shape ${o}.`)}}if(s.shape!=null)for(let o=0;o<s.shape.length;++o){let l=s.shape[o],p=a.shape[o];if(l!=null&&p!=null&&l!==p)throw new V(`Input ${n} is incompatible with layer ${this.name}: expected shape=${s.shape}, found shape=${a.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 r=tt(e),n=AV(e),a=FV(e);if(n===a)throw new V("Arguments to apply() must be all SymbolicTensors or all Tensors");return si(this.name,()=>{if(!this.built){this.assertInputCompatibility(e);let s=[];for(let i of tt(e))s.push(i.shape);this.build(Er(s)),this.built=!0,this.initialWeights&&this.setWeights(this.initialWeights),this._refCount===null&&a&&(this._refCount=1)}if(this.assertInputCompatibility(e),a){let s=this.call(e,t);this.supportsMasking&&this.setMaskMetadata(e,s);let i=tt(s),o=[];for(let l of i)r.indexOf(l)!==-1&&(l=l.clone()),o.push(l);if(s=Er(o),this.activityRegularizer!=null)throw new Be("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return s}else{let s=EV(e),i=this.computeOutputShape(s),o,l=$V(e);if(this.warnOnIncompatibleInputShape(Array.isArray(e)?s[0]:s),i!=null&&i.length>0&&Array.isArray(i[0])?o=i.map((p,u)=>new Un(l,p,this,tt(e),t,this.name,u)):o=new Un(l,i,this,tt(e),t,this.name),this.addInboundNode(e,o,null,null,s,i,t),this._refCount++,this.activityRegularizer!=null)throw new Be("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return o}})}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((r,n)=>{r!=null&&e[n]!=null&&e[n]!==r&&(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 Ya(`The layer ${this.name} has never been called and thus has no defined output shape.`);let e=[];for(let t of this.inboundNodes){let r=JSON.stringify(t.outputShapes);e.indexOf(r)===-1&&e.push(r)}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 Ya(`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 na(`You tried to call countParams() on ${this.name}, but the layer is not built yet. Build it first by calling build(batchInputShape).`);return kc(this.weights)}build(e){this.built=!0}getWeights(e=!1){return _g(e?this.trainableWeights:this.weights)}setWeights(e){W(()=>{let t=this.weights;if(t.length!==e.length)throw new V(`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 r=[],n=_g(t);for(let a=0;a<n.length;++a){let s=n[a],i=t[a],o=e[a];if(!k.arraysEqual(s.shape,o.shape))throw new V(`Layer weight shape ${s.shape} not compatible with provided weight shape ${o.shape}`);r.push([i,o])}px(r)})}addWeight(e,t,r,n,a,s,i,o){if(this._addedWeightNames.indexOf(e)!==-1)throw new V(`Duplicate weight name ${e} for layer ${this.name}`);this._addedWeightNames.push(e),r==null&&(r="float32"),this.fastWeightInitDuringBuild&&(n=o!=null?o():xt("zeros"));let l=n.apply(t,r),p=new yN(l,r,e,s,i);return l.dispose(),a!=null&&this.addLoss(()=>a.apply(p.read())),s==null&&(s=!0),s?this._trainableWeights.push(p):this._nonTrainableWeights.push(p),p}setFastWeightInitDuringBuild(e){this.fastWeightInitDuringBuild=e}addLoss(e){e==null||Array.isArray(e)&&e.length===0||(e=tt(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(r=>{if(r!=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}setMaskMetadata(e,t,r){if(!this.supportsMasking)return;let n=this.computeMask(e,r),a=tt(t),s=tt(n);if(a.length!==s.length)throw new Error(`${this.name} outputs ${a.length} tensors but ${a.length} masks for those tensors`);for(let i=0;i<a.length;i++)a[i].kerasMask=s[i]}addInboundNode(e,t,r,n,a,s,i=null){let o=tt(e);t=tt(t),r=tt(r),n=tt(n),a=wc(a),s=wc(s);let l=[],p=[],u=[];for(let d of o)l.push(d.sourceLayer),p.push(d.nodeIndex),u.push(d.tensorIndex);new nm({outboundLayer:this,inboundLayers:l,nodeIndices:p,tensorIndices:u,inputTensors:o,outputTensors:t,inputMasks:r,outputMasks:n,inputShapes:a,outputShapes:s},i);for(let d=0;d<t.length;d++)t[d].sourceLayer=this,t[d].nodeIndex=this.inboundNodes.length-1,t[d].tensorIndex=d}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 EV(e){e=tt(e);let t=[];for(let r of e)t.push(r.shape);return Er(t)}function $V(e){return"float32"}function bN(e,t,r){if((t==null||r!=null&&r>0)&&(t=e.sourceLayer,r=e.nodeIndex),t.inboundNodes.length===0)return[e];{let n=t.inboundNodes[r];if(n.inboundLayers.length===0)return n.inputTensors;{let a=[];for(let s=0;s<n.inboundLayers.length;s++){let i=n.inputTensors[s],o=n.inboundLayers[s],l=n.nodeIndices[s],p=bN(i,o,l);for(let u of p)a.indexOf(u)===-1&&a.push(u)}return a}}}function AV(e){let t=!0;for(let r of tt(e))if(!(r instanceof Un)){t=!1;break}return t}function FV(e){let t=!0;for(let r of tt(e))if(r instanceof Un){t=!1;break}return t}var ap=class extends We{constructor(e){if(super({dtype:e.dtype,name:e.name!=null?e.name:Kf("input").toString()}),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 V("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 V("An InputLayer should be passed either a `batchInputShape` or an `inputShape`.");t=[e.batchSize].concat(e.inputShape)}else if(e.batchSize!=null)throw new V("Cannot specify batchSize if batchInputShape is specified when creating an InputLayer.");let r=e.dtype||"float32";this.batchInputShape=t,this.dtype=r,this.inputSpec=[{shape:t}];let n=new Un(this.dtype,this.batchInputShape,this,[],{},this.name);n.nodeIndex=0,n.tensorIndex=0,new nm({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:[n],outputTensors:[n],inputMasks:[null],outputMasks:[null],inputShapes:[t],outputShapes:[t]})}apply(e,t){throw new V(`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}}};ap.className="InputLayer";ne.registerClass(ap);function xN(e){if(e.batchShape==null&&e.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(e.batchShape!=null&&e.shape!=null)throw new V("Please provide either a `shape` or `batchShape` argument to Input, but not both.");let t=e.batchShape;e.shape!=null&&t==null&&(t=[null].concat(e.shape));let r=e.dtype;return r==null&&(r="float32"),new ap({batchInputShape:t,name:e.name,dtype:r,sparse:e.sparse}).inboundNodes[0].outputTensors[0]}function RV(e,t){if(e.dtype==null||e.dtype===t.dtype)return t;try{return se(t,e.dtype)}catch{throw new V(`The dtype of the feed (${t.dtype}) can not be cast to the dtype of the key '${e.name}' (${e.dtype}).`)}}var vl=class vN{constructor(t){if(this.id2Value={},this.id2Mask={},this.name2Id={},t instanceof vN)for(let r in t.id2Value)this.id2Value[r]=t.id2Value[r],r in t.id2Mask&&(this.id2Mask[r]=t.id2Mask[r]);else{if(t==null)return;for(let r of t)this.add(r.key,r.value)}}add(t,r,n){if(this.id2Value[t.id]==null)this.id2Value[t.id]=RV(t,r),this.name2Id[t.name]=t.id,n!=null&&(this.id2Mask[t.id]=n);else throw new V(`Duplicate key: name=${t.name}, id=${t.id}`);return this}addFeed(t){this.add(t.key,t.value)}hasKey(t){return this.id2Value[t.id]!=null}names(){return Object.keys(this.name2Id)}getValue(t){if(t instanceof Un){if(this.id2Value[t.id]==null)throw new V(`Nonexistent key: ${t.name}`);return this.id2Value[t.id]}else{let r=this.name2Id[t];if(r==null)throw new V(`Feed dict has no SymbolicTensor name: ${t}`);return this.id2Value[r]}}getMask(t){if(t instanceof Un){if(this.id2Value[t.id]==null)throw new V(`Nonexistent key: ${t.name}`);return this.id2Mask[t.id]}else{let r=this.name2Id[t];if(r==null)throw new V(`Feed dict has no SymbolicTensor name: ${t}`);return this.id2Mask[r]}}disposeMasks(){this.id2Mask!=null&&Ce(this.id2Mask)}},Ic=new oN,Sc=new oN;function DV(e){Ic!=null&&Ic.setMaxEntries(e),Sc!=null&&Sc.setMaxEntries(e)}function $p(e,t,r,n){let a=r==null?!1:r.training,s=Array.isArray(e),i=s?e:[e],o=i.map(f=>f.name),l=[],p=t.names();for(let f of o)p.indexOf(f)!==-1?l.push(t.getValue(f)):l.push(null);let u=o.join(",")+"|"+t.names().sort().join(","),d=Ic.get(u),h;if(d==null){let f=MV(i,t);d=f.sorted,h=f.recipientCounts,Ic.put(u,d),Sc.put(u,h)}h={},a||Object.assign(h,Sc.get(u));let c=new vl(t);for(let f=0;f<d.length;++f){let m=d[f],g=m.sourceLayer;if(g instanceof ap)continue;let y=[],b=[],x=[],v=!1;for(let $ of m.inputs){let R=c.getValue($),F=c.getMask($);y.push(R),b.push(F),F!=null&&(v=!0),a||(h[$.name]--,h[$.name]===0&&!t.hasKey($)&&o.indexOf($.name)===-1&&!R.isDisposed&&$.sourceLayer.stateful!==!0&&x.push(R))}v&&(r=r||{},r.mask=b[0]);let w=tt(g.apply(y,r)),N=null;g.supportsMasking&&(N=g.computeMask(y,b));let T=LV(m),E=Array.isArray(T)?T:[T];for(let $=0;$<E.length;++$){c.hasKey(E[$])||c.add(E[$],w[$],Array.isArray(N)?N[0]:N);let R=o.indexOf(E[$].name);R!==-1&&(l[R]=w[$])}a||Ce(x)}return c.disposeMasks(),s?l:l[0]}function MV(e,t){k.assert(e!=null&&e.length>0,()=>"Expected at least one fetch, got none");let r=[],n={};if(e.length===1){let a=M0(e[0],t);r=a.sorted,n=a.recipientMap}else{let a=new Set;for(let s of e){let{sorted:i,recipientMap:o}=M0(s,t);for(let l of i)a.has(l.name)||(r.push(l),a.add(l.name));for(let l in o)n[l]==null&&(n[l]=new Set),o[l].forEach(p=>n[l].add(p))}}return{sorted:r,recipientCounts:OV(n)}}function OV(e){let t={};for(let r in e)t[r]=e[r].size;return t}function M0(e,t){let r=new Set,n=[],a={};for(let o of t.names())r.add(o);let s=[],i=[];for(s.push(e);s.length>0;){let o=s[s.length-1];if(r.has(o.name)){s.pop();continue}let l=i[i.length-1]===s.length-1;if(o.inputs.length===0||l)s.pop(),n.push(o),r.add(o.name),l&&i.pop();else{i.push(s.length-1);for(let p of o.inputs)a[p.name]==null&&(a[p.name]=new Set),a[p.name].add(o.name),!r.has(p.name)&&s.push(p)}}return{sorted:n,recipientMap:a}}function LV(e){let t;if(e.sourceLayer.inboundNodes.length===1)t=e.sourceLayer.output;else{let r=null;for(let n=0;n<e.sourceLayer.inboundNodes.length;++n)for(let a of e.sourceLayer.inboundNodes[n].outputTensors)if(a.id===e.id){r=n;break}t=e.sourceLayer.getOutputAt(r)}return t}var zV=j();zV.registerFlag("TOPOLOGICAL_SORT_CACHE_MAX_ENTRIES",()=>100,DV);var wN={};Ee(wN,{maxNorm:()=>PV,minMaxNorm:()=>UV,nonNeg:()=>WV,unitNorm:()=>BV});function dx(e,t){return W(()=>Yt(ge(z(e,e),t,!0)))}var nh=class extends ne.Serializable{getConfig(){return{}}},hx=class extends nh{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 W(()=>{let t=dx(e,this.axis),r=ur(t,0,this.maxValue);return z(e,fe(r,J(Bt(),t)))})}getConfig(){return{maxValue:this.maxValue,axis:this.axis}}};hx.className="MaxNorm";ne.registerClass(hx);var cx=class extends nh{constructor(e){super(),this.defaultAxis=0,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return W(()=>fe(e,J(Bt(),dx(e,this.axis))))}getConfig(){return{axis:this.axis}}};cx.className="UnitNorm";ne.registerClass(cx);var fx=class extends nh{apply(e){return rt(e)}};fx.className="NonNeg";ne.registerClass(fx);var mx=class extends nh{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 W(()=>{let t=dx(e,this.axis),r=J(z(this.rate,ur(t,this.minValue,this.maxValue)),z(1-this.rate,t));return z(e,fe(r,J(Bt(),t)))})}getConfig(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}}};mx.className="MinMaxNorm";ne.registerClass(mx);var O0={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};function Ut(e){return ex(e)}function L0(e,t={}){return Qd(e,ne.SerializationMap.getMap().classNameMap,t,"constraint")}function Vt(e){if(e==null)return null;if(typeof e=="string"){let t={className:e in O0?O0[e]:e,config:{}};return L0(t)}else return e instanceof nh?e:L0(e)}function PV(e){return new hx(e)}function BV(e){return new cx(e)}function WV(){return new fx}function UV(e){return new mx(e)}var kN={};Ee(kN,{constant:()=>HV,glorotNormal:()=>YV,glorotUniform:()=>JV,heNormal:()=>QV,heUniform:()=>eG,identity:()=>XV,leCunNormal:()=>tG,leCunUniform:()=>rG,ones:()=>GV,orthogonal:()=>nG,randomNormal:()=>qV,randomUniform:()=>jV,truncatedNormal:()=>KV,varianceScaling:()=>ZV,zeros:()=>VV});function VV(){return new nx}function GV(){return new Zf}function HV(e){return new ax(e)}function jV(e){return new sx(e)}function qV(e){return new ix(e)}function KV(e){return new ox(e)}function XV(e){return new lx(e)}function ZV(e){return new Dr(e)}function JV(e){return new Jf(e)}function YV(e){return new Yf(e)}function QV(e){return new Qf(e)}function eG(e){return new em(e)}function tG(e){return new tm(e)}function rG(e){return new rm(e)}function nG(e){return new ux(e)}var IN={};Ee(IN,{Layer:()=>We,RNN:()=>Ba,RNNCell:()=>sh,activation:()=>DH,add:()=>VH,alphaDropout:()=>_6,average:()=>GH,averagePooling1d:()=>Tv,averagePooling2d:()=>Cv,averagePooling3d:()=>Ev,avgPool1d:()=>QH,avgPool2d:()=>t6,avgPool3d:()=>n6,avgPooling1d:()=>e6,avgPooling2d:()=>r6,avgPooling3d:()=>a6,batchNormalization:()=>ZH,bidirectional:()=>b6,categoryEncoding:()=>A6,centerCrop:()=>E6,concatenate:()=>HH,conv1d:()=>NH,conv2d:()=>_H,conv2dTranspose:()=>TH,conv3d:()=>CH,conv3dTranspose:()=>EH,convLstm2d:()=>f6,convLstm2dCell:()=>m6,cropping2D:()=>AH,dense:()=>MH,depthwiseConv2d:()=>RH,dot:()=>XH,dropout:()=>OH,elu:()=>xH,embedding:()=>UH,flatten:()=>zH,gaussianDropout:()=>N6,gaussianNoise:()=>S6,globalAveragePooling1d:()=>s6,globalAveragePooling2d:()=>i6,globalMaxPool1d:()=>v6,globalMaxPool2d:()=>w6,globalMaxPooling1d:()=>N2,globalMaxPooling2d:()=>_2,gru:()=>l6,gruCell:()=>u6,input:()=>WN,inputLayer:()=>bH,layerNormalization:()=>JH,leakyReLU:()=>wH,lstm:()=>p6,lstmCell:()=>d6,masking:()=>T6,maxPool1d:()=>k6,maxPool2d:()=>I6,maxPooling1d:()=>T2,maxPooling2d:()=>C2,maxPooling3d:()=>o6,maximum:()=>jH,minimum:()=>qH,multiply:()=>KH,permute:()=>WH,prelu:()=>kH,randomWidth:()=>F6,reLU:()=>vH,repeatVector:()=>PH,rescaling:()=>C6,reshape:()=>BH,resizing:()=>$6,rnn:()=>g6,separableConv2d:()=>$H,simpleRNN:()=>h6,simpleRNNCell:()=>c6,softmax:()=>IH,spatialDropout1d:()=>LH,stackedRNNCells:()=>y6,thresholdedReLU:()=>SH,timeDistributed:()=>x6,upSampling2d:()=>FH,zeroPadding2d:()=>YH});async function Ka(e){if(e==null)return;let t=[],r=[],n=[];for(let a in e){let s=e[a];if(typeof s!="number"){let i=s;t.push(i.data()),r.push(a),n.push(i)}}if(t.length>0){let a=await Promise.all(t);for(let s=0;s<a.length;++s)e[r[s]]=a[s][0];Ce(n)}}function SN(e){if(e!=null)for(let t in e){let r=e[t];typeof r!="number"&&r.dispose()}}var z0;(function(e){e[e.SILENT=0]="SILENT",e[e.VERBOSE=1]="VERBOSE"})(z0||(z0={}));var aG=125,zl=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){}},NN=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 r of this.callbacks)await r.onEpochBegin(e,t)}async onEpochEnd(e,t){t==null&&(t={});for(let r of this.callbacks)await r.onEpochEnd(e,t)}async onBatchBegin(e,t){t==null&&(t={});for(let r of this.callbacks)await r.onBatchBegin(e,t)}async onBatchEnd(e,t){t==null&&(t={});for(let r of this.callbacks)await r.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)}},sG=class extends zl{constructor(){super()}async onEpochBegin(e){this.seen=0,this.totals={}}async onBatchEnd(e,t){t==null&&(t={});let r=t.size==null?0:t.size;this.seen+=r;for(let n in t){let a=t[n];if(typeof a=="number")this.totals.hasOwnProperty(n)||(this.totals[n]=0),this.totals[n]=this.totals[n]+a*r;else{let s;n in this.totals?s=this.totals[n]:this.totals[n]=0;let i=W(()=>J(this.totals[n],z(a,r)));this.totals[n]=i,s!=null&&s.dispose()}}}async onEpochEnd(e,t){if(t!=null)for(let r of this.params.metrics)this.totals[r]!=null&&(typeof this.totals[r]=="number"?t[r]=this.totals[r]/this.seen:W(()=>{let n=z(fe(1,this.seen),this.totals[r]);t[r]=n,this.totals[r].dispose(),Pt(t[r])}))}},_N=class extends zl{async onTrainBegin(e){this.epoch=[],this.history={}}async onEpochEnd(e,t){t==null&&(t={}),this.epoch.push(e);for(let r in t)this.history[r]==null&&(this.history[r]=[]),this.history[r].push(t[r])}async syncData(){let e=[],t=[],r=[];for(let a in this.history){let s=this.history[a];for(let i=0;i<s.length;++i)if(typeof s[i]!="number"){let o=s[i];e.push(o.data()),t.push(a),r.push(i)}}let n=await Promise.all(e);for(let a=0;a<n.length;++a)this.history[t[a]][r[a]].dispose(),this.history[t[a]][r[a]]=n[a][0]}},TN=class extends zl{constructor(e,t){if(super(),this.currentEpoch=0,this.nowFunc=e.nowFunc,this.nextFrameFunc=e.nextFrameFunc||Yb,this.yieldEvery=t||"auto",this.yieldEvery==="auto"&&(this.yieldEvery=aG),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");k.isNumber(this.yieldEvery)&&(this.maybeWait=aV(this.maybeWait.bind(this),this.yieldEvery,this.nowFunc)),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,r){let n=[];this.yield!=null&&(await Ka(r),n.push(this.yield(e,t,r))),n.push(this.nextFrameFunc()),await Promise.all(n)}async onEpochBegin(e,t){this.currentEpoch=e,this.epochBegin!=null&&(await Ka(t),await this.epochBegin(e,t))}async onEpochEnd(e,t){let r=[];this.epochEnd!=null&&(await Ka(t),r.push(this.epochEnd(e,t))),this.yieldEvery==="epoch"&&r.push(this.nextFrameFunc()),await Promise.all(r)}async onBatchBegin(e,t){this.batchBegin!=null&&(await Ka(t),await this.batchBegin(e,t))}async onBatchEnd(e,t){let r=[];this.batchEnd!=null&&(await Ka(t),r.push(this.batchEnd(e,t))),this.yieldEvery==="batch"?r.push(this.nextFrameFunc()):k.isNumber(this.yieldEvery)&&r.push(this.maybeWait(this.currentEpoch,e,t)),await Promise.all(r)}async onTrainBegin(e){this.trainBegin!=null&&(await Ka(e),await this.trainBegin(e))}async onTrainEnd(e){this.trainEnd!=null&&(await Ka(e),await this.trainEnd(e))}};function CN(e,t){return e==null&&(e={}),e instanceof zl?[e]:Array.isArray(e)&&e[0]instanceof zl?e:tt(e).map(r=>new TN(r,t))}var gx=class Zn{constructor(){}static registerCallbackConstructor(t,r){k.assert(t>=0&&Number.isInteger(t),()=>`Verbosity level is expected to be an integer >= 0, but got ${t}`),Zn.checkForDuplicate(r),Zn.constructors[t]==null&&(Zn.constructors[t]=[]),Zn.constructors[t].push(r)}static checkForDuplicate(t){for(let r in Zn.constructors)Zn.constructors[+r].forEach(n=>{if(n===t)throw new V("Duplicate callback constructor.")})}static clear(){Zn.constructors={}}static createCallbacks(t){let r=[];for(let n in Zn.constructors){let a=+n;t>=a&&r.push(...Zn.constructors[a])}return r.map(n=>new n)}};gx.constructors={};function EN(e,t,r,n,a,s,i,o,l){let p=new _N,u=[new sG,...gx.createCallbacks(t)];e!=null&&u.push(...e),u.push(p);let d=new NN(u);return d.setParams({epochs:r,initialEpoch:n,samples:a,steps:s,batchSize:i,verbose:t,doValidation:o,metrics:l}),{callbackList:d,history:p}}function On(e,t={},r=!1){return Qd(e,ne.SerializationMap.getMap().classNameMap,t,"layer",r)}function Nc(e,t){return W(()=>{e.dtype!=="float32"&&(e=se(e,"float32"));let r=ge(th(e),t,!0),n=qr(r.shape,Bt()),a=Yt(ma(r,n));return fe(e,a)})}function el(e,t){return W(()=>kt(th(de(t,e)),-1))}function am(e,t){return W(()=>kt(Ft(de(t,e)),-1))}function sp(e,t){return W(()=>{let r=de(e,t),n=ur(Ft(e),Bt(),Number.MAX_VALUE),a=Ft(fe(r,n));return z(100,kt(a,-1))})}function iG(e,t){return W(()=>{let r=ur(t,Bt(),Number.MAX_VALUE),n=Xr(J(1,r)),a=ur(e,Bt(),Number.MAX_VALUE),s=Xr(J(1,a));return kt(th(de(n,s)),-1)})}function oG(e,t){return W(()=>{let r=ma(0,de(1,z(e,t)));return kt(th(r),-1)})}function lG(e,t){return W(()=>{let r=ma(0,de(1,z(e,t)));return kt(r,-1)})}function uG(e,t){return W(()=>{let r=ge(z(e,t),-1),n=hn(z(de(1,e),t),-1);return ma(0,J(1,de(n,r)))})}function pG(e,t){return W(()=>{let r=Math.log(2),n=de(t,e),a=de(J(n,Jo(z(-2,n))),r);return kt(a,-1)})}function td(e,t,r=!1){return W(()=>{if(r)t=Ds(t);else{let n=ge(t,t.shape.length-1,!0);t=fe(t,n)}return t=ur(t,Bt(),1-Bt()),gt(ge(z(se(e,"float32"),Xr(t)),t.shape.length-1))})}function _c(e,t,r=!1){return W(()=>{let n=se(Qu(gV(e)),"int32");t=ur(t,Bt(),1-Bt());let a=t.shape,s=B(Fl(n,a[a.length-1]),a);return td(s,t,r)})}function dG(e,t){if(!k.arraysEqual(e.shape,t.shape))throw new V(`logits and labels must have the same shape, but got shapes ${JSON.stringify(e.shape)} and ${JSON.stringify(t.shape)}`);return W(()=>{let r=rt(t),n=gt(Ft(t));return J(de(r,z(t,e)),Vd(pr(n)))})}function sm(e,t){return W(()=>{let r;return r=ur(t,Bt(),1-Bt()),r=Xr(fe(r,de(1,r))),kt(dG(e,r),-1)})}function hG(e,t){return W(()=>{let r=ur(e,Bt(),1),n=ur(t,Bt(),1);return ge(z(e,Xr(fe(r,n))),-1)})}function cG(e,t){return W(()=>{let r=Xr(J(Bt(),t));return kt(de(t,z(e,r)),-1)})}function yx(e,t){return W(()=>{let r=Nc(e,-1),n=Nc(t,-1),a=z(r,n);return gt(ge(a,-1))})}var Tc={meanSquaredError:el,meanAbsoluteError:am,meanAbsolutePercentageError:sp,meanSquaredLogarithmicError:iG,squaredHinge:oG,hinge:lG,categoricalHinge:uG,logcosh:pG,categoricalCrossentropy:td,sparseCategoricalCrossentropy:_c,binaryCrossentropy:sm,kullbackLeiblerDivergence:hG,poisson:cG,cosineProximity:yx};function Bm(e){if(typeof e=="string"){if(e in Tc)return Tc[e];let t=`Unknown loss ${e}`;throw e.toLowerCase().includes("softmaxcrossentropy")&&(t=`Unknown loss ${e}. Use "categoricalCrossentropy" as the string name for tf.losses.softmaxCrossEntropy`),new V(t)}else return e}function bx(e,t){return W(()=>{let r=z(.5,Zr(t)),n=Fa(Ir(t,r),e.dtype);return kt(Kr(e,n),-1)})}function xx(e,t){return W(()=>Fa(Kr(mi(e,-1),mi(t,-1)),"float32"))}function $N(e,t){return W(()=>se(ge(Nn(Kr(e,1),Kr(t,1))),"float32"))}function fG(e,t){return W(()=>se(ge(Nn(Kr(e,1),Kr(t,0))),"float32"))}function mG(e,t){return W(()=>se(ge(Nn(Kr(e,0),Kr(t,1))),"float32"))}function AN(e,t){return W(()=>{let r=$N(e,t),n=mG(e,t),a=J(r,n);return se(Jt(Ir(a,0),fe(r,a),0),"float32")})}function gG(e,t){return W(()=>{let r=$N(e,t),n=fG(e,t),a=J(r,n);return se(Jt(Ir(a,0),fe(r,a),0),"float32")})}function FN(e,t){return sm(e,t)}function RN(e,t){return e.rank===t.rank&&(e=Ms(e,[e.rank-1])),t=mi(t,-1),t.dtype!==e.dtype&&(t=se(t,e.dtype)),se(Kr(e,t),"float32")}function yG(e,t){return W(()=>{let r=e.sub(t).square().sum(),n=e.sub(e.mean()).square().sum();return we(1).sub(r.div(n))})}var bG=el,xG=el,vG=am,wG=am,kG=sp,IG=sp,vx=td,SG=yx,DN=_c,Cc={binaryAccuracy:bx,categoricalAccuracy:xx,precision:AN,categoricalCrossentropy:vx,sparseCategoricalCrossentropy:DN,mse:bG,MSE:xG,mae:vG,MAE:wG,mape:kG,MAPE:IG,cosine:SG};function NG(e){if(typeof e=="string"&&e in Cc)return Cc[e];if(typeof e!="string"&&e!=null)return e;throw new V(`Unknown metric ${e}`)}function Mh(e){if(ea(e!==null,`Unknown LossOrMetricFn ${e}`),typeof e=="string")return e;{let t;for(let r of Object.keys(Tc))if(Tc[r]===e){t=r;break}if(t!==void 0)return t;for(let r of Object.keys(Cc))if(Cc[r]===e){t=r;break}return t!==void 0?t:e.name}}function _G(e){let t={Adagrad:()=>Ks.adagrad(.01),Adadelta:()=>Ks.adadelta(1,.95,Bt()),Adam:()=>Ks.adam(.001,.9,.999,Bt()),Adamax:()=>Ks.adamax(.002,.9,.999,Bt(),0),RMSProp:()=>Ks.rmsprop(.001,.9,0,Bt()),SGD:()=>Ks.sgd(.01)};if(t.adagrad=t.Adagrad,t.adadelta=t.Adadelta,t.adam=t.Adam,t.adamax=t.Adamax,t.rmsprop=t.RMSProp,t.sgd=t.SGD,e in t)return t[e]();throw new V(`Unknown Optimizer ${e}`)}function P0(e,t,r=!1){if(e==null||typeof e!="object"||Object.getPrototypeOf(e)!==Object.prototype||!Tg(e))throw new Error("User-defined metadata is expected to be a JSON object, but is not.");if(r){let n=JSON.stringify(e);n.length>1048576&&console.warn(`User-defined metadata of model "${t}" is too large in size (length=${n.length} when serialized). It is not recommended to store such large objects in user-defined metadata. Please make sure its serialized length is <= 1048576.`)}}function Tg(e){if(e===null)return!0;if(typeof e=="object")if(Object.getPrototypeOf(e)===Object.prototype){let t=Object.keys(e);for(let r of t)if(typeof r!="string"||!Tg(e[r]))return!1;return!0}else if(Array.isArray(e)){for(let t of e)if(!Tg(t))return!1;return!0}else return!1;else{let t=typeof e;return t==="string"||t==="number"||t==="boolean"}}function TG(e,t,r,n=console.log){let a=EG(e),s=["Layer (type)","Input Shape","Output shape","Param #"];a?(t=t||90,r=r||[.32,.61,.89,1]):(t=t||115,r=r||[.24,.48,.7,.8,1]),r[r.length-1]<=1&&(r=r.map(u=>Math.floor(t*u)));let i;if(!a){s.push("Receives inputs"),i=[];for(let u in e.nodesByDepth)i.push(...e.nodesByDepth[u])}n("_".repeat(t)),Ec(s,r,n),n("=".repeat(t));let o=e.layers;for(let u=0;u<o.length;++u)a?$G(o[u],r,n):AG(o[u],r,i,n),n((u===o.length-1?"=":"_").repeat(t));e.checkTrainableWeightsConsistency();let l=CG(e),p=kc(e.nonTrainableWeights);n(`Total params: ${l+p}`),n(`Trainable params: ${l}`),n(`Non-trainable params: ${p}`),n("_".repeat(t))}function CG(e){let t;return e.collectedTrainableWeights!=null?t=kc(e.collectedTrainableWeights):t=kc(e.trainableWeights),t}function EG(e){let t=!0,r=[],n=[];for(let a in e.nodesByDepth)r.push(e.nodesByDepth[a]);for(let a of r){if(a.length>1||a.length===1&&a[0].inboundLayers.length>1){t=!1;break}n.push(...a)}if(t)for(let a of e.layers){let s=!1;for(let i of a.inboundNodes)if(n.indexOf(i)!==-1)if(s){t=!1;break}else s=!0;if(!t)break}return t}function Ec(e,t,r=console.log){let n="";for(let a=0;a<e.length;++a)a>0&&(n=n.slice(0,n.length-1)+" "),n+=e[a],n=n.slice(0,t[a]),n+=" ".repeat(t[a]-n.length);r(n)}function $G(e,t,r){let n,a;try{a=e.inboundNodes.map(l=>JSON.stringify(l.inputShapes)).join(",")}catch{a="multiple"}try{n=JSON.stringify(e.outputShape)}catch{n="multiple"}let s=e.name,i=e.getClassName(),o=[`${s} (${i})`,a,n,e.countParams().toString()];Ec(o,t,r)}function AG(e,t,r,n){let a,s;try{s=e.inboundNodes.map(d=>JSON.stringify(d.inputShapes)).join(",")}catch{s="multiple"}try{a=JSON.stringify(e.outputShape)}catch{a="multiple"}let i=[];for(let d of e.inboundNodes)if(!(r!=null&&r.length>0&&r.indexOf(d)===-1))for(let h=0;h<d.inboundLayers.length;++h){let c=d.inboundLayers[h].name,f=d.nodeIndices[h],m=d.tensorIndices[h];i.push(`${c}[${f}][${m}]`)}let o=e.name,l=e.getClassName(),p=i.length===0?"":i[0],u=[`${o} (${l})`,s,a,e.countParams().toString(),p];Ec(u,t,n);for(let d=1;d<i.length;++d)Ec(["","","","",i[d]],t,n)}function MN(e,t,r){return(e==="inboundNodes"||e==="outputLayers"||e==="inputLayers")&&t===0&&typeof r=="string"}function rd(e,t){if(e===null)return null;if(typeof e=="string")return Ys(e);if(typeof e=="number"||typeof e=="boolean")return e;if(e instanceof Array){let r=[],n=e.length;for(let a=0;a<n;++a){let s=e[a];MN(t,a,s)?r.push(s):r.push(rd(s,t))}return r}else{let r={};for(let n of Object.keys(e)){let a=e[n];if(n==="name"&&typeof a=="string")r[n]=a;else{let s=Ys(n);r[s]=rd(a,s)}}return r}}function Cg(e,t){if(e==null)return null;if(typeof e=="string")return ka(e);if(typeof e=="number"||typeof e=="boolean")return e;if(e instanceof Array){let r=[],n=e.length;for(let a=0;a<n;++a){let s=e[a];MN(t,a,s)?r.push(s):r.push(Cg(s,t))}return r}else{let r={};for(let n of Object.keys(e)){let a=e[n],s=ka(n);(n==="name"||n==="className")&&typeof a=="string"?r[s]=a:r[s]=Cg(a,n)}return r}}var wx="4.22.0",FG=e=>{let t=Object.keys(e);if(t.length===0)return!1;let r=t[0].split("/");return!isNaN(parseInt(r[r.length-1],10))},RG=class Jn extends We{constructor(t){if(super({}),this.containerNodes=new Set,this.name=t.name,this.name==null){let b=this.getClassName().toLowerCase();this.name=Kf(b)}if(this.supportsMasking=!1,this.trainable_=!0,Array.isArray(t.inputs)?this.inputs=t.inputs.slice():this.inputs=[t.inputs],Array.isArray(t.outputs)?this.outputs=t.outputs.slice():this.outputs=[t.outputs],os(this.inputs).length!==this.inputs.length)throw new V(`The list of inputs passed to the model is redundant. All inputs should only appear once. Found: ${this.inputs.map(b=>b.name)}`);os(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 x=b.sourceLayer,v=b.nodeIndex,w=b.tensorIndex;this.outputLayers.push(x),this.outputLayersNodeIndices.push(v),this.outputLayersTensorIndices.push(w)}for(let b of this.inputs){let x=b.sourceLayer,v=b.nodeIndex,w=b.tensorIndex;ea(v===0,"input layer has >1 nodes"),ea(w===0,"input layer has >1 tensors"),this.inputLayers.push(x),this.inputLayersNodeIndices.push(v),this.inputLayersTensorIndices.push(w)}this.inputNames=[],this.outputNames=[],this.feedInputShapes=[],this.feedInputNames=[],this.feedOutputNames=[];for(let b=0;b<this.inputLayers.length;b++){let x=this.inputLayers[b];if(!(x instanceof ap))throw new TypeError(`Input layers to a LayersModel must be InputLayer objects. Received inputs: ${t.inputs}. Input ${b} (0-based) originates from layer type ${x.getClassName()}.`);this.inputNames.push(x.name),this.feedInputShapes.push(x.batchInputShape),this.feedInputNames.push(x.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 r={},n={},a={},s={},i={},o=[],l=(b,x,v,w,N,T)=>{(w==null||N==null||T==null)&&(w=b.sourceLayer,N=b.nodeIndex,T=b.tensorIndex);let E=w.inboundNodes[N];if(v.indexOf(E)!==-1)throw new na(`The tensor ${b.name} at layer "${w.name}" is part of a cycle.`);if(x.indexOf(E)!==-1)return;this.containerNodes.add(Jn.nodeKey(w,N)),w.id in i||(i[w.id]=Object.keys(i).length),v.indexOf(E)===-1&&v.push(E);let $=E.inboundLayers.length;for(let R=0;R<$;R++){let F=E.inputTensors[R],S=E.inboundLayers[R],D=E.nodeIndices[R],P=E.tensorIndices[R];l(F,x,v,S,D,P)}for(x.push(E);v.indexOf(E)>=0;)v.splice(v.indexOf(E),1);o.push(E)},p=[],u=[];for(let b of this.outputs)l(b,p,u);let d=o.slice().reverse();for(let b of d){n[b.id]=b,b.id in r||(r[b.id]=0);let x=r[b.id],v=a[b.outboundLayer.id]==null?0:a[b.outboundLayer.id];x=Math.max(x,v),a[b.outboundLayer.id]=x,s[b.outboundLayer.id]=b.outboundLayer,r[b.id]=x;for(let w=0;w<b.inboundLayers.length;w++){let N=b.inboundLayers[w],T=b.nodeIndices[w],E=N.inboundNodes[T],$=r[E.id]==null?0:r[E.id];r[E.id]=Math.max(x+1,$),n[E.id]=E}}let h={};for(let b in r){let x=r[b];x in h||(h[x]=[]),h[x].push(n[b])}let c={};for(let b in a){let x=a[b];x in c||(c[x]=[]),c[x].push(s[b])}let f=Object.keys(c).map(b=>parseInt(b,10)).sort(Fh);this.layers=[];for(let b of f){let x=c[b];x.sort((v,w)=>{let N=i[v.id],T=i[w.id];return N<T?-1:N>T?1:0});for(let v of x)v instanceof Jn&&this.internalContainerRefs.push(v),this.layers.push(v)}this.layersByDepth=c,f=Object.keys(h).map(b=>parseInt(b,10)).sort(Fh);let m=this.inputs.slice(),g=[];for(let b of f)for(let x of h[b]){let v=x.outboundLayer;if(v!=null){for(let w of x.inputTensors)if(m.indexOf(w)===-1)throw new na(`Graph disconnected: cannot obtain value for tensor ${w} at layer "${v.name}". The following previous layers were accessed without issue: ${g}`);for(let w of x.outputTensors)m.push(w);g.push(v.name)}}this.nodesByDepth=h;let y=this.layers.map(b=>b.name);for(let b of y){let x=y.filter(v=>v===b).length;if(x!==1)throw new na(`The name "${b}" is used ${x} times in the model. All layer names should be unique. Layer names: `+JSON.stringify(y))}this.outboundNodes=[],this.inboundNodes=[],new nm({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 t={refCountAfterDispose:null,numDisposedVariables:0};if(--this._refCount===0){for(let r of this.layers)t.numDisposedVariables+=r.dispose().numDisposedVariables;for(let r of this.internalContainerRefs)t.numDisposedVariables+=r.dispose().numDisposedVariables}return t.refCountAfterDispose=this._refCount,t}get trainable(){return this.trainable_}set trainable(t){this.layers.forEach(r=>{r._trainableWeights.forEach(n=>n.trainable=t)}),this.trainable_=t}get trainableWeights(){if(this._trainableWeights.length>0)throw new V("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 t=[];for(let r of this.layers)t=t.concat(r.trainableWeights);return t}get nonTrainableWeights(){let t=[];for(let r of this.layers)t.push(...r.nonTrainableWeights);if(!this.trainable){let r=[];for(let n of this.layers)r.push(...n.trainableWeights);return r.concat(t)}return t}get weights(){return this.trainableWeights.concat(this.nonTrainableWeights)}loadWeights(t,r=!0){let n={},a=0,s=FG(t);s&&this.parseWeights(t);for(let o of this.layers)for(let[l,p]of o.weights.entries()){let u=s?`${p.name.split("/").slice(0,-1).join("/")+"/"}${l}`:p.originalName;if(n[u]!=null)throw new V(`Duplicate weight name: ${u}`);n[u]=p,a++}let i=[];for(let o in t){let l=o;if(n[o]==null){let p=o.split("/");l=p.slice(0,-2).concat([p[p.length-1]]).join("/")}if(n[l]!=null)i.push([n[l],t[o]]);else if(r)throw new V(`Provided weight data has no target variable: ${o}`);delete n[l]}if(r){let o=[];for(let l in n)o.push(l);if(o.length>0)throw new V(`${o.length} of ${a} weights are not set: ${o}`)}px(i)}parseWeights(t){for(let r in Object.keys(t)){let n=r.split("/"),a=["vars","layer_checkpoint_dependencies"],s=n.map(i=>i.startsWith("_")?i.slice(1):i).filter(i=>!a.includes(i)).join("/");s!==r&&(t[s]=t[r],delete t[r])}}updatedConfig(){let t=this.getConfig(),r={};return r.className=this.getClassName(),r.config=t,r.kerasVersion=`tfjs-layers ${wx}`,r.backend="TensorFlow.js",r}toJSON(t,r=!0){let n=Cg(this.updatedConfig());return r?JSON.stringify(n):n}call(t,r){return W(()=>{t=tt(t);let n=new vl;for(let a=0;a<this.inputs.length;++a)n.add(this.inputs[a],t[a]);return $p(this.outputs,n,r)})}computeMask(t,r){return W(()=>{t=tt(t);let n;return r==null?n=vi(null,t.length):n=tt(r),this.runInternalGraph(t,n)[1]})}computeOutputShape(t){let r=wc(t);if(r.length!==this.inputLayers.length)throw new V(`Invalid inputShape argument ${t}: model has ${this.inputLayers.length} tensor inputs.`);let n={};for(let o=0;o<r.length;o++){let l=this.inputLayers[o],p=r[o],u=l.name+"_0_0";n[u]=p}let a=Object.keys(this.nodesByDepth).map(o=>parseInt(o,10)).sort(Fh);if(a.length>1)for(let o of a){let l=this.nodesByDepth[o];for(let p of l){let u=p.outboundLayer;if(this.inputLayers.map(m=>m.id).indexOf(u.id)!==-1)continue;let d=[];for(let m=0;m<p.inboundLayers.length;m++){let g=p.inboundLayers[m],y=p.nodeIndices[m],b=p.tensorIndices[m],x=`${g.name}_${y}_${b}`,v=n[x];d.push(v)}let h=u.computeOutputShape(Er(d)),c=wc(h),f=u.inboundNodes.indexOf(p);for(let m=0;m<c.length;m++){let g=`${u.name}_${f}_${m}`;n[g]=c[m]}}}let s=[],i=[];for(let o=0;o<this.outputLayers.length;o++){let l=this.outputLayers[o],p=this.outputLayersNodeIndices[o],u=this.outputLayersTensorIndices[o],d=`${l.name}_${p}_${u}`;i.push(d)}for(let o=0;o<i.length;o++){let l=i[o];ea(l in n),s.push(n[l])}return Er(s)}runInternalGraph(t,r){r==null&&(r=vi(null,t.length));let n={};for(let l=0;l<this.inputs.length;++l){let p=this.inputs[l],u=t[l],d=r[l];n[p.id]=[u,d]}let a=Object.keys(this.nodesByDepth).map(l=>parseInt(l,10)).sort(Fh);for(let l of a){let p=this.nodesByDepth[l];for(let u of p){let d=u.outboundLayer,h=u.inputTensors,c=u.outputTensors,f=new Array;for(let m of h)m.id in n&&f.push(n[m.id]);if(f.length===h.length){let m={},g,y,b,x;if(u.callArgs!=null&&(m=u.callArgs),f.length===1){let[v,w]=f[0];m.mask==null&&(m.mask=w),b=tt(d.call(v,m)),x=tt(d.computeMask(v,w)),g=[v],y=[w]}else g=f.map(v=>v[0]),y=f.map(v=>v[1]),m.mask==null&&(m.mask=y),b=tt(d.call(g,m)),x=tt(d.computeMask(g,y));if(d.activityRegularizer)throw new Be("LayersModel invocation with concrete Tensor value(s) in the presence of activity regularizer(s) is not supported yet.");for(let v=0;v<c.length;++v){let w=c[v],N=b[v],T=x[v];n[w.id]=[N,T]}}}}let s=[],i=[],o=[];for(let l of this.outputs){ea(l.id in n,`Could not compute output ${l.name} : ${l.id}`);let[p,u]=n[l.id];o.push(p.shape),s.push(p),i.push(u)}return[s,i,o]}buildNodeConversionMap(t){let r={},n;for(let a of this.layers){n=a instanceof Jn?1:0;for(let s=0;s<a.inboundNodes.length;s++){let i=Jn.nodeKey(a,s);this.containerNodes.has(i)&&(r[i]=n,n+=1)}}return r}getLayer(t,r){if(r!=null)return this.findLayer(r);if(t==null)throw new V("Provide either a layer name or layer index");if(typeof t=="number")return this.findLayer(t);for(let n of this.layers)if(n.name===t)return n;throw new V(`No such layer: ${t}`)}findLayer(t){if(this.layers.length<=t)throw new V(`Was asked to retrieve layer at index ${t}, but model only has ${this.layers.length} layer(s).`);return this.layers[t]}calculateLosses(){return W(()=>{let t=[];for(let r of this.layers)for(let n=0;n<r.inboundNodes.length;++n){let a=Jn.nodeKey(r,n);this.containerNodes.has(a)&&t.push(...r.calculateLosses())}return t})}getConfig(){let t={name:this.name},r=this.buildNodeConversionMap(this.layers),n=[];for(let i of this.layers){let o=i.getClassName(),l=i.getConfig(),p=[];for(let d=0;d<i.inboundNodes.length;d++){let h=i.inboundNodes[d],c=Jn.nodeKey(i,d),f={};if(this.containerNodes.has(c)){if(h.callArgs)try{JSON.stringify(h.callArgs),f=h.callArgs}catch{console.warn(`Layer ${i.name} was passed non-serializable keyword arguments: ${h.callArgs}. They will not be included in the serialized model (and thus will be missing at deserialization time).`),f={}}if(h.inboundLayers.length>0){let m=[];for(let g=0;g<h.inboundLayers.length;g++){let y=h.inboundLayers[g],b=h.nodeIndices[g],x=h.tensorIndices[g],v=Jn.nodeKey(y,b),w=r[v];w==null&&(w=0),m.push([y.name,w,x,f])}p.push(m)}}}let u={};u.name=i.name,u.className=o,u.config=l,u.inboundNodes=p,n.push(u)}t.layers=n;let a=[];for(let i=0;i<this.inputLayers.length;i++){let o=this.inputLayers[i],l=this.inputLayersNodeIndices[i],p=Jn.nodeKey(o,l);if(!this.containerNodes.has(p))continue;let u=r[p];u==null&&(u=0);let d=this.inputLayersTensorIndices[i];a.push([o.name,u,d])}t.inputLayers=a;let s=[];for(let i=0;i<this.outputLayers.length;i++){let o=this.outputLayers[i],l=this.outputLayersNodeIndices[i],p=Jn.nodeKey(o,l);if(!this.containerNodes.has(p))continue;let u=r[p];u==null&&(u=0);let d=this.outputLayersTensorIndices[i];s.push([o.name,u,d])}return t.outputLayers=s,t}static fromConfig(t,r,n={},a=!1){let s={},i={};function o(g,y){g.name in i?i[g.name].push(y):i[g.name]=[y]}function l(g,y){let b=[],x;for(let v of y){let w=v[0],N=v[1],T=v[2];if(x=v[3]==null?{}:v[3],!(w in s)){o(g,y);return}let E=s[w];if(E.inboundNodes.length<=N){o(g,y);return}let $=E.inboundNodes[N];b.push($.outputTensors[T])}b.length>0&&g.apply(Er(b),x)}function p(g){let y=g.name,b=On(g,r.customObjects!=null?r.customObjects:{});b.setFastWeightInitDuringBuild(a),s[y]=b,g.inboundNodes.forEach(x=>{if(!(x instanceof Array))throw new V(`Corrupted configuration, expected array for nodeData: ${x}`);o(b,x)})}let u=r.name,d=r.layers;for(let g of d)p(g);for(;!nV(i);)for(let g of d){let y=s[g.name];if(y.name in i){let b=i[y.name];delete i[y.name];for(let x of b)l(y,x)}}let h=[],c=[],f=r.inputLayers;for(let g of f){let y=g[0],b=g[1],x=g[2];ea(y in s);let v=s[y].inboundNodes[b].outputTensors;h.push(v[x])}let m=r.outputLayers;for(let g of m){let y=g[0],b=g[1],x=g[2];ea(y in s);let v=s[y].inboundNodes[b].outputTensors;c.push(v[x])}return new t({inputs:h,outputs:c,name:u})}get stateful(){if(this._stateful)throw new V("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 t of this.layers)if(t.stateful)return!0;return!1}resetStates(){W(()=>{this.layers.forEach(t=>{t.stateful&&t.resetStates()})})}};function DG(e,t,r){let n=t.length;if(e==null||Array.isArray(e)&&e.length===0)return t.map(a=>null);if(n===1)return Array.isArray(e)&&e.length===1?e:typeof e=="object"&&t[0]in e?[e[t[0]]]:[e];if(Array.isArray(e)){if(e.length!==n)throw new Error(`Provided ${r} is an array of ${e.length} element(s), but the model has ${n} outputs. Make sure a set of weights is provided for each model output.`);return e}else if(typeof e=="object"&&Object.keys(e).length>0&&typeof e[Object.keys(e)[0]]=="object"){let a=[];return t.forEach(s=>{s in e?a.push(e[s]):a.push(null)}),a}else throw new Error(`The model has multiple (${n}) outputs, so ${r} must be either an array with ${n} elements or an object with ${t} keys. Provided ${r} not understood: ${JSON.stringify(e)}`)}function ON(e,t){return DG(e,t,"classWeight")}async function LN(e,t,r,n){if(r!=null){let a=W(()=>{if(e.shape.length===1)return sa(e);if(e.shape.length===2){if(e.shape[1]>1)return mi(e,1);if(e.shape[1]===1)return B(e,[e.shape[0]]);throw new Error(`Encountered unexpected last-dimension size (${e.shape[1]}) during handling of class weights. The size is expected to be >= 1.`)}else throw new Error(`Unexpected rank of target (y) tensor (${e.rank}) during handling of class weights. The rank is expected to be 1 or 2.`)}),s=Array.from(await a.data());Ce(a);let i=[];return s.forEach(o=>{if(r[o]==null)throw new Error(`classWeight must contain all classes in the training data. The class ${o} exists in the data but not in classWeight`);i.push(r[o])}),Qe(i,"float32")}else return null}function MG(e,t){return z(e,t)}var OG=32;function zN(e,t){let r,n,a=t;r=a.xs,n=a.ys,k.assert(r!=null&&n!=null,()=>`A Dataset iterator for fitDataset() is expected to generate objects of the form \`{xs: xVal, ys: yVal}\`, where the two values may be \`tf.Tensor\`, an array of Tensors, or a map of string to Tensor. The provided Dataset instead generates ${t}`);let s=B0("input",e.inputNames,r),i=B0("output",e.outputNames,n),o=s[0].shape[0];k.assert(s.length===e.inputs.length,()=>`LayersModel has ${e.inputs.length} inputs, but the dataset provides ${s.length} inputs. (Expected input keys: ${JSON.stringify(e.inputNames)})`),k.assert(i.length===e.outputs.length,()=>`LayersModel has ${e.outputs.length} outputs, but the dataset provides ${i.length} outputs. (Expected output keys: ${JSON.stringify(e.outputNames)})`);for(let l=0;l<s.length;l++)k.assert(s[l].shape[0]===o,()=>`Batch size mismatch: input ${e.inputNames[l]} has ${s[l].shape[0]}; expected ${o} based on input ${e.inputNames[0]}.`);for(let l=0;l<i.length;l++)k.assert(i[l].shape[0]===o,()=>`Batch size mismatch: output ${e.outputNames[l]} has ${i[l].shape[0]}; expected ${o} based on input ${e.inputNames[0]}.`);return{xs:s,ys:i}}function B0(e,t,r){if(r instanceof ze)return[r];if(Array.isArray(r))return k.assert(r.length===t.length,()=>`Received an array of ${r.length} Tensors, but expected ${t.length} to match the ${e} keys ${t}.`),r;{let n=[];for(let a of t){if(r[a]==null)throw new V(`The feature data generated by the dataset lacks the required ${e} key '${a}'.`);n.push(r[a])}return n}}function LG(e){if(e.length===3)throw new Be("Validation with sample weights is not implemented yet.");return{xs:e[0],ys:e[1]}}async function zG(e,t,r){let n=r.batchesPerEpoch!=null;if(k.assert(e.optimizer!=null,()=>"You must compile a model before training/testing. Use LayersModel.compile(modelCompileConfig)."),k.assert(r!=null,()=>"For fitDataset(), the 2nd argument (config) is required, but it is not provided in this call."),k.assert(r.epochs!=null&&r.epochs>0&&Number.isInteger(r.epochs),()=>`For fitDataset(), config.epochs is expected to be a positive integer, but got ${r.epochs}`),k.assert(!n||r.batchesPerEpoch>0&&Number.isInteger(r.batchesPerEpoch),()=>`For fitDataset(), config.batchesPerEpoch is expected to be a positive integer if specified, but got ${r.batchesPerEpoch}`),k.assert(r.validationSplit==null,()=>"`validationSplit` is not supported by `fitDataset()`. Use validationData instead."),e.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");e.isTraining=!0;try{let a=r.validationData!=null,s,i;if(a)if(W0(r.validationData))k.assert(r.validationBatches==null||r.validationBatches>0&&Number.isInteger(r.validationBatches),()=>`For fitDataset() with dataset-based validation, config.validationBatches is expected not to be provided, or to be a positive integer, but got ${r.validationBatches}`);else{let g=LG(r.validationData);s=g.xs,i=g.ys}let o=e.makeTrainFunction(),l=e.getDedupedMetricsNames(),p;a?p=l.slice().concat(l.map(g=>"val_"+g)):p=l.slice();let u=CN(r.callbacks,r.yieldEvery),d=r.verbose==null?1:r.verbose,{callbackList:h,history:c}=EN(u,d,r.epochs,null,null,PG(t,r),null,a,p);h.setModel(e),e.history=c,await h.onTrainBegin(),e.stopTraining_=!1;let f=r.initialEpoch==null?0:r.initialEpoch,m=await t.iterator();for(;f<r.epochs;){let g={};await h.onEpochBegin(f);let y=0,b=0;for(n||(m=await t.iterator());!n||y<r.batchesPerEpoch;){let x=await m.next();if(n&&x.done){console.warn(`You provided \`batchesPerEpoch\` as ${r.batchesPerEpoch}, but your dataset iterator ran out of data after ${y} batches; interrupting training. Make sure that your dataset can generate at least \`batchesPerEpoch * epochs\` batches (in this case, ${r.batchesPerEpoch*r.epochs} batches). You may need to use the repeat() function when building your dataset.`);break}if(x.value!=null){let{xs:v,ys:w}=zN(e,x.value),N={};N.batch=b,N.size=v[0].shape[0],await h.onBatchBegin(b,N);let T=[];if(r.classWeight!=null){let R=ON(r.classWeight,e.outputNames);for(let F=0;F<R.length;++F)T.push(await LN(w[F],null,R[F]))}let E=v.concat(w).concat(T),$=o(E);Ce(E);for(let R=0;R<l.length;++R){let F=l[R],S=$[R];N[F]=S,Pt(S)}await h.onBatchEnd(b,N),SN(N),b++,y++}if(n?y>=r.batchesPerEpoch:x.done){if(a){let v;W0(r.validationData)?v=tt(await e.evaluateDataset(r.validationData,{batches:r.validationBatches})):v=tt(e.evaluate(s,i,{batchSize:r.validationBatchSize==null?OG:r.validationBatchSize,verbose:0}));for(let w=0;w<e.metricsNames.length;++w)g[`val_${e.metricsNames[w]}`]=v[w]}break}if(e.stopTraining_)break}if(await h.onEpochEnd(f,g),f++,e.stopTraining_)break}return await h.onTrainEnd(),await e.history.syncData(),e.history}finally{e.isTraining=!1}}function PG(e,t){let r=null;return t.batchesPerEpoch!=null?r=t.batchesPerEpoch:Number.isFinite(e.size)&&(r=e.size),r}function W0(e){return typeof e.iterator=="function"}function BG(e){return typeof e.next=="function"}async function WG(e,t,r){r=r||{};let n=r.batches!=null,a=e.testFunction,s=[];if(r.verbose>0)throw new Be("Verbose mode is not implemented yet.");k.assert(!n||r.batches>0&&Number.isInteger(r.batches),()=>`Test loop expects \`batches\` to be a positive integer, but received ${JSON.stringify(r.batches)}`);let i=BG(t)?t:await t.iterator(),o=0,l=0;for(;!n||l<r.batches;){let p=await i.next();if(s=W(()=>{if(p.value){let{xs:u,ys:d}=zN(e,p.value),h=u.concat(d),c=W(()=>a(h));if(Ce(h),l===0)for(let m=0;m<c.length;++m)s.push(we(0));let f=h[0].shape[0];for(let m=0;m<c.length;++m){let g=c[m],y=s[m];s[m]=W(()=>J(s[m],z(f,g))),l>0&&Ce(y)}Ce(c),o+=f,++l}return s}),p.done){n&&console.warn(`Your dataset iterator ran out of data during evaluateDataset(). Interrupting evalution. Make sure that your dataset can generate at least \`batches\` batches (in this case, ${r.batches} batches). You may need to use the repeat() function when building your dataset.`);break}}for(let p=0;p<s.length;++p){let u=s[p];s[p]=fe(s[p],o),Ce(u)}return Er(s)}function Wm(e){k.assert(e>0&&Number.isInteger(e),()=>`batchSize is required to be a positive integer, but got ${e}`)}function kp(e,t,r){return e==null?[null]:Array.isArray(e)?e.map(n=>ii(n,t,r-t)):ii(e,t,r-t)}function Eg(e,t){return W(()=>e==null?null:Array.isArray(e)?e.map(r=>Eg(r,t)):mN(e,t.dtype==="int32"?t:se(t,"int32")))}function Um(e,t){let r=[],n=0,a=null;for(;n<e;)a=n+t,a>=e&&(a=e),r.push([n,a]),n=a;return r}function PN(e){let t=[];e instanceof ze&&(e=[e]);for(let r=0;r<e.length;++r){let n=e[r];if(n.rank===1)t.push(eh(n,1));else{if(n.rank===0)throw new Error("Expected tensor to be at least 1D, but received a 0D tensor (scalar).");t.push(n)}}return t}function En(e,t){if(e==null)return;let r=[];if(t instanceof ze)r.push(t.id);else if(Array.isArray(t))t.forEach(a=>r.push(a.id));else if(t!=null)for(let a in t){let s=t[a];r.push(s.id)}let n=[];if(e instanceof ze)r.indexOf(e.id)===-1&&n.push(e);else if(Array.isArray(e))e.forEach(a=>{r.indexOf(a.id)===-1&&n.push(a)});else if(e!=null)for(let a in e){let s=e[a];r.indexOf(s.id)===-1&&n.push(s)}n.forEach(a=>{a.isDisposed||a.dispose()})}function UG(e){return e instanceof ze}function $g(e){return Array.isArray(e)}function U0(e){return!UG(e)&&!$g(e)}function V0(e,t,r,n=!0,a=""){if(t==null||t.length===0){if(e!=null){let i=!1;if($g(e)&&e.length>0)i=!0;else if(U0(e)){for(let o in e)if(e.hasOwnProperty(o)){i=!0;break}}else i=!0;if(i)throw new V(`Error when checking model ${a} expected no data, but got ${e}`)}return[]}if(e==null)return t.map(i=>null);let s;if(U0(e)){e=e,s=[];for(let i of t){if(e[i]==null)throw new V(`No data provided for "${i}". Need data for each key in: ${t}`);s.push(e[i])}}else if($g(e)){if(e=e,e.length!==t.length)throw new V(`Error when checking model ${a}: the Array of Tensors that you are passing to your model is not the size the model expected. Expected to see ${t.length} Tensor(s), but instead got the following list of Tensor(s): ${e}`);s=e}else{if(e=e,t.length>1)throw new V(`The model ${a} expects ${t.length} Tensor(s), but only received one Tensor. Found: Tensor with shape ${e.shape}`);s=[e]}if(s=PN(s),r!=null)for(let i=0;i<t.length;++i){if(r[i]==null)continue;let o=s[i];if(o.shape.length!==r[i].length)throw new V(`Error when checking ${a}: expected ${t[i]} to have ${r[i].length} dimension(s). but got array with shape ${o.shape}`);for(let l=0;l<r[i].length;++l){if(l===0&&!n)continue;let p=o.shape[l],u=r[i][l];if(u!=null&&u>=0&&p!==u)throw new V(`${a} expected a batch of elements where each example has shape [${r[i].slice(1,r[i].length)}] (i.e.,tensor shape [*,${r[i].slice(1,r[i].length)}]) but the ${a} received an input with ${o.shape[0]} examples, each with shape [${o.shape.slice(1,o.shape.length)}] (tensor shape [${o.shape}])`)}}return s}function VG(e,t,r){let n=os(e.map(s=>s.shape[0]));n.sort();let a=os(t.map(s=>s.shape[0]));if(a.sort(),n.length>1)throw new V(`All input Tensors (x) should have the same number of samples. Got array shapes: ${JSON.stringify(e.map(s=>s.shape))}`);if(a.length>1)throw new V(`All target Tensors (y) should have the same number of samples. Got array shapes: ${JSON.stringify(t.map(s=>s.shape))}`);if(n.length>0&&a.length>0&&!k.arraysEqual(n,a))throw new V(`Input Tensors should have the same number of samples as target Tensors. Found ${n[0]} input sample(s) and ${a[0]} target sample(s).`)}function GG(e,t,r){let n=[el,sm,td];for(let a=0;a<e.length;++a){let s=e[a],i=t[a],o=r[a];if(i!=null){if(i===td&&s.shape[s.shape.length-1]===1)throw new V(`You are passing a target array of shape ${s.shape} while using a loss 'categorical_crossentropy'. 'categorical_crossentropy'expects targets to be binary matrices (1s and 0s) of shape [samples, classes].`);if(n.indexOf(i)!==-1){let l=s.shape.slice(1),p=o.slice(1);for(let u=0;u<l.length;++u){let d=l[u],h=p[u];if(h!=null&&d!==h)throw new V(`A target Tensor with shape ${s.shape} was passed for an output of shape ${o}, while using a loss function that expects targets to have the same shape as the output.`)}}}}}function G0(e,t,r,n=!0,a=""){let s;if(Array.isArray(e)){if(e.length!==t.length)throw new V(`Error when checking model ${a}: the Array of Tensors that you are passing to your model is not the size the the model expected. Expected to see ${t.length} Tensor(s), but instead got ${e.length} Tensors(s).`);s=e}else{if(t.length>1)throw new V(`The model expects ${t.length} ${a} Tensors, but only received one Tensor. Found: array with shape ${JSON.stringify(e.shape)}.`);s=[e]}if(r!=null)for(let i=0;i<t.length;++i){if(r[i]==null)continue;let o=s[i];if(o.shape.length!==r[i].length)throw new V(`Error when checking ${a}: expected ${t[i]} to have ${r[i].length} dimension(s), but got array with shape ${JSON.stringify(o.shape)}`);for(let l=0;l<r[i].length;++l){if(l===0&&!n)continue;let p=o.shape[l],u=r[i][l];if(u!=null&&u!==p)throw new V(`Error when checking ${a}: expected ${t[i]} to have shape ${JSON.stringify(r[i])} but got array with shape ${JSON.stringify(o.shape)}.`)}}}function HG(e,t){if(e==null||Array.isArray(e)&&e.length===0)return t.map(n=>[]);let r;if(typeof e=="string"||typeof e=="function")r=[e];else if(Array.isArray(e)||typeof e=="object")r=e;else throw new TypeError(`Type of metrics argument not understood. Expected an string,function, Array, or Object, found: ${e}`);if(Array.isArray(r))return t.map(n=>r);{let n=[];for(let a of t){let s=r.hasOwnProperty(a)?r[a]:[];Array.isArray(s)||(s=[s]),n.push(s)}return n}}var jG="layers-model",Ca=class extends RG{constructor(e){super(e),this.isTraining=!1}summary(e,t,r=console.log){if(!this.built)throw new V("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).");TG(this,e,t,r)}compile(e){if(e.loss==null&&(e.loss=[]),this.loss=e.loss,typeof e.optimizer=="string")this.optimizer_=_G(e.optimizer),this.isOptimizerOwned=!0;else{if(!(e.optimizer instanceof Pa))throw new V("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 s in e.loss)if(this.outputNames.indexOf(s)===-1)throw new V(`Unknown entry in loss dictionary: "${s}". Only expected the following keys: ${this.outputNames}`);for(let s of this.outputNames)e.loss[s]==null&&console.warn(`Output "${s}" is missing from loss dictionary. We assume this was done on purpose, and we will not be expecting data to be passed to ${s} during training`),t.push(Bm(e.loss[s]))}else if(Array.isArray(e.loss)){if(e.loss.length!==this.outputs.length)throw new V(`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(s=>Bm(s))}else{let s=Bm(e.loss);this.outputs.forEach(i=>{t.push(s)})}this.lossFunctions=t,this.feedOutputNames=[],this.feedOutputShapes=[],this.feedLossFns=[];for(let s=0;s<this.outputs.length;++s){let i=this.internalOutputShapes[s],o=this.outputNames[s];this.feedOutputNames.push(o),this.feedOutputShapes.push(i),this.feedLossFns.push(this.lossFunctions[s])}let r=[];this.metrics=e.metrics,this.metricsNames=["loss"],this.metricsTensors=[],si("loss",()=>{for(let s=0;s<this.outputs.length;++s){if(r.indexOf(s)!==-1)continue;let i=this.lossFunctions[s];this.outputs.length>1&&(this.metricsTensors.push([i,s]),this.metricsNames.push(this.outputNames[s]+"_loss"))}});let n=HG(e.metrics,this.outputNames),a=(s,i,o)=>{this.outputNames.length>1&&(i=this.outputNames[s]+"_"+i),this.metricsNames.push(i),this.metricsTensors.push([o,s])};si("metric",()=>{for(let s=0;s<this.outputs.length;++s){if(r.indexOf(s)!==-1)continue;let i=n[s];(o=>{let l="",p,u,d;for(let h of o){if(typeof h=="string"&&["accuracy","acc","crossentropy","ce"].indexOf(h)!==-1){let f=this.internalOutputShapes[s];f[f.length-1]===1||this.lossFunctions[s]===sm?["accuracy","acc"].indexOf(h)!==-1?u=bx:["crossentropy","ce"].indexOf(h)!==-1&&(u=FN):this.lossFunctions[s]===_c?["accuracy","acc"].indexOf(h)!==-1?u=RN:["crossentropy","ce"].indexOf(h)!==-1&&(u=DN):["accuracy","acc"].indexOf(h)!==-1?u=xx:["crossentropy","ce"].indexOf(h)!==-1&&(u=vx);let m;["accuracy","acc"].indexOf(h)!==-1?m="acc":["crossentropy","ce"].indexOf(h)!==-1&&(m="ce"),d=u,p=l+m}else d=NG(h),p=l+Mh(h);let c;si(p,()=>{c=d}),a(s,p,c)}})(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,r={}){let n=r.batchSize==null?32:r.batchSize;Wm(n);let a=this.standardizeUserDataXY(e,t,!0,n);try{let s=a[0].concat(a[1]);this.makeTestFunction();let i=this.testFunction,o=this.testLoop(i,s,n,r.verbose,r.steps);return Er(o)}finally{En(a[0],e),En(a[1],t)}}async evaluateDataset(e,t){return this.makeTestFunction(),WG(this,e,t)}checkNumSamples(e,t,r,n="steps"){let a;if(r!=null){if(a=null,t!=null)throw new V(`If ${n} is set, batchSize must be null or undefined.Got batchSize = ${t}`)}else if(e!=null)Array.isArray(e)?a=e[0].shape[0]:a=e.shape[0];else throw new V(`Either the input data should have a defined shape, or ${n} shoud be specified.`);return a}execute(e,t){if(Array.isArray(t)&&t.length===0)throw new V("`outputs` is an empty Array, which is not allowed.");let r=Array.isArray(t),n=r?t:[t],a=this.retrieveSymbolicTensors(n),s=new vl;if(e instanceof ze&&(e=[e]),Array.isArray(e)){if(e.length!==this.inputs.length)throw new V(`The number of inputs provided (${e.length}) does not match the number of inputs of this model (${this.inputs.length}).`);for(let o=0;o<this.inputs.length;++o)s.add(this.inputs[o],e[o])}else for(let o of this.inputs){let l=e[o.name];if(l==null)throw new V(`No value is provided for the model's input ${o.name}`);s.add(o,l)}let i=$p(a,s);return r?i:i[0]}retrieveSymbolicTensors(e){let t=vi(null,e.length),r=e.length;for(let n of this.layers){let a=Array.isArray(n.output)?n.output:[n.output],s=a.map(i=>i.name);for(let i=0;i<e.length;++i){let o=s.indexOf(e[i]);if(o!==-1&&(t[i]=a[o],r--),r===0)break}if(r===0)break}if(r>0){let n=[];throw t.forEach((a,s)=>{a==null&&n.push(e[s])}),new V(`Cannot find SymbolicTensors for output name(s): ${JSON.stringify(n)}`)}return t}predictLoop(e,t=32,r=!1){return W(()=>{let n=this.checkNumSamples(e);if(r)throw new Be("Verbose predictLoop() is not implemented yet.");let a=Um(n,t),s=this.outputs.map(i=>[]);for(let i=0;i<a.length;++i)W(()=>{let o=a[i][0],l=a[i][1],p=kp(e,o,l),u=[];if(Array.isArray(p))for(let h=0;h<p.length;++h)u.push({key:this.inputs[h],value:p[h]});else u.push({key:this.inputs[0],value:p});let d=new vl(u);return $p(this.outputs,d)}).forEach((o,l)=>s[l].push(o));return Er(s.map(i=>lt(i,0)))})}predict(e,t={}){let r=PN(e);G0(r,this.inputNames,this.feedInputShapes,!1);try{let n=t.batchSize==null?32:t.batchSize;return Wm(n),this.predictLoop(r,n)}finally{En(r,e)}}predictOnBatch(e){G0(e,this.inputNames,this.feedInputShapes,!0);let t=(Array.isArray(e)?e[0]:e).shape[0];return this.predictLoop(e,t)}standardizeUserDataXY(e,t,r=!0,n){if(this.optimizer_==null)throw new na("You must compile a model before training/testing. Use LayersModel.compile(modelCompileArgs).");let a=[];for(let s=0;s<this.feedOutputShapes.length;++s){let i=this.feedOutputShapes[s];this.feedLossFns[s]===_c?a.push(i.slice(0,i.length-1).concat([1])):a.push(i)}if(e=V0(e,this.feedInputNames,this.feedInputShapes,!1,"input"),t=V0(t,this.feedOutputNames,a,!1,"target"),VG(e,t),GG(t,this.feedLossFns,this.feedOutputShapes),this.stateful&&n!=null&&n>0&&e[0].shape[0]%n!==0)throw new V(`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,r,n,a=!0,s){let[i,o]=this.standardizeUserDataXY(e,t,a,s);if(r!=null)throw new Error("sample weight is not supported yet.");let l=null;if(n!=null){let p=ON(n,this.outputNames);l=[];for(let u=0;u<p.length;++u)l.push(await LN(o[u],null,p[u]))}return[i,o,l]}testLoop(e,t,r,n=0,a){return W(()=>{let s=this.checkNumSamples(t,r,a,"steps"),i=[];if(n>0)throw new Be("Verbose mode is not implemented yet.");if(a!=null)throw new Be("steps mode in testLoop() is not implemented yet");{let o=Um(s,r),l=Qe(Bn(0,s));for(let p=0;p<o.length;++p){let u=o[p][0],d=o[p][1],h=ii(l,u,d-u),c=Eg(t,h),f=e(c);if(p===0)for(let m=0;m<f.length;++m)i.push(we(0));for(let m=0;m<f.length;++m){let g=f[m];i[m]=J(i[m],z(d-u,g))}}for(let p=0;p<i.length;++p)i[p]=fe(i[p],s)}return i})}getDedupedMetricsNames(){let e=this.metricsNames,t=[];for(let r=0;r<e.length;++r){let n=e[r],a=n;if(E0(e,n)>1){let s=E0(e.slice(0,r),n);a+=`_${s}`}t.push(a)}return t}makeTrainFunction(){return e=>{let t=[],r=e.slice(0,this.inputs.length),n=e.slice(this.inputs.length,this.inputs.length+this.outputs.length),a=e.slice(this.inputs.length+this.outputs.length,this.inputs.length+this.outputs.length*2),s=[],i=()=>{let l=[];for(let h=0;h<this.inputs.length;++h)l.push({key:this.inputs[h],value:r[h]});let p=new vl(l),u=$p(this.outputs,p,{training:!0}),d;for(let h=0;h<this.lossFunctions.length;++h){let c=this.lossFunctions[h],f=c(n[h],u[h]);a[h]!=null&&(f=MG(f,a[h]));let m=kt(f);t.push(m),h===0?d=f:d=J(d,f)}for(let h=0;h<this.metricsTensors.length;++h){let c;if(this.outputs.length>1&&h<this.outputs.length)c=t[h];else{let f=this.metricsTensors[h][0],m=this.metricsTensors[h][1];c=kt(f(n[m],u[m]))}Pt(c),s.push(c)}return d=kt(d),this.calculateLosses().forEach(h=>{d=J(d,h)}),d},o=this.collectedTrainableWeights.map(l=>l.read());return[this.optimizer_.minimize(i,!0,o)].concat(s)}}makeTestFunction(){this.testFunction=e=>W(()=>{let t=[],r,n=e.slice(0,this.inputs.length),a=e.slice(this.inputs.length,this.inputs.length+this.outputs.length),s=[];for(let l=0;l<this.inputs.length;++l)s.push({key:this.inputs[l],value:n[l]});let i=new vl(s),o=$p(this.outputs,i);for(let l=0;l<this.lossFunctions.length;++l){let p=this.lossFunctions[l],u=kt(p(a[l],o[l]));l===0?r=u:r=J(r,u),t.push(r)}for(let l=0;l<this.metricsTensors.length;++l){let p=this.metricsTensors[l][0],u=this.metricsTensors[l][1],d=kt(p(a[u],o[u]));t.push(d)}return t})}async fit(e,t,r={}){if(this.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");this.isTraining=!0;let n,a,s,i,o,l,p,u,d;try{let h=r.batchSize==null?32:r.batchSize;Wm(h);let c=await this.standardizeUserData(e,t,r.sampleWeight,r.classWeight,!1,h);n=c[0],a=c[1],d=c[2];let f=!1,m;if(r.validationData!=null&&r.validationData.length>0){if(f=!0,r.validationData.length===2)o=r.validationData[0],l=r.validationData[1];else throw r.validationData.length===3?new Be("validationData including sample weights is not supported yet."):new V(`When passing validation data, it must contain 2 (valX, valY) or 3 (valX, valY, valSampleWeight) items; ${r.validationData} is invalid.`);let N=await this.standardizeUserData(o,l,null,null,!0,h);p=N[0],u=N[1],m=p.concat(u)}else if(r.validationSplit!=null&&r.validationSplit>0&&r.validationSplit<1){f=!0;let N=Math.floor(n[0].shape[0]*(1-r.validationSplit)),T=n[0].shape[0];p=kp(n,N,T),s=n,n=kp(n,0,N),u=kp(a,N,T),i=a,a=kp(a,0,N),m=p.concat(u)}else r.validationSteps!=null&&(f=!0);let g=n.concat(a).concat(d);this.checkTrainableWeightsConsistency();let y=this.makeTrainFunction(),b=this.getDedupedMetricsNames(),x,v;f?(this.makeTestFunction(),x=this.testFunction,v=b.slice().concat(b.map(N=>"val_"+N))):(x=null,m=[],v=b.slice());let w=CN(r.callbacks,r.yieldEvery);return await this.fitLoop(y,g,b,h,r.epochs,r.verbose,w,x,m,r.shuffle,v,r.initialEpoch,null,null)}finally{this.isTraining=!1,En(n,e),En(a,t),En(s,e),En(i,t),En(p,o),En(u,l),d!=null&&Ce(d)}}async fitLoop(e,t,r,n,a,s,i,o,l,p,u,d,h,c){n==null&&(n=32),a==null&&(a=1),p==null&&(p=!0),d==null&&(d=0);let f=!1;if(o!=null&&l!=null&&(f=!0),c!=null&&(f=!0,h==null))throw new V("Can only use `validationSteps` when doing step-wise training, i.e., `stepsPerEpoch` must be set.");let m=this.checkNumSamples(t,n,h,"steps_per_epoch"),g;m!=null&&(g=Bn(0,m)),s==null&&(s=1);let{callbackList:y,history:b}=EN(i,s,a,d,m,h,n,f,u);y.setModel(this),this.history=b,await y.onTrainBegin(),this.stopTraining_=!1;for(let x=d;x<a;++x){await y.onEpochBegin(x);let v={};if(h!=null)throw new Be("stepsPerEpoch mode is not implemented yet.");{if(p==="batch")throw new Be("batch shuffling is not implemneted yet");p&&k.shuffle(g);let w=Qe(g),N=Um(m,n);for(let T=0;T<N.length;++T){let E={};if(await y.onBatchBegin(T,E),W(()=>{let $=N[T][0],R=N[T][1],F=ii(w,$,R-$);E.batch=T,E.size=R-$;let S=Eg(t,F),D=e(S);for(let P=0;P<r.length;++P){let U=r[P],H=D[P];E[U]=H,Pt(H)}if(T===N.length-1&&f){let P=this.testLoop(o,l,n);for(let U=0;U<r.length;++U){let H=r[U],q=P[U];Pt(q),v["val_"+H]=q}}}),await y.onBatchEnd(T,E),SN(E),this.stopTraining_)break}w.dispose()}if(await y.onEpochEnd(x,v),this.stopTraining_)break}return await y.onTrainEnd(),await this.history.syncData(),this.history}async fitDataset(e,t){return zG(this,e,t)}async trainOnBatch(e,t){let r=await this.standardizeUserData(e,t),n=r[0],a=r[1],s=this.makeTrainFunction()(n.concat(a)),i=[];for(let o of s){let l=await o.data();i.push(l[0])}return Ce(s),En(r[0],e),En(r[1],t),Er(i)}getNamedWeights(e){let t=[],r=e!=null&&e.trainableOnly,n=r?this.trainableWeights:this.weights,a=this.getWeights(r);for(let s=0;s<n.length;++s)r&&!n[s].trainable||t.push({name:n[s].originalName,tensor:a[s]});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=dg().numTensors;this.optimizer_.dispose(),e.numDisposedVariables+=t-dg().numTensors}return e}getLossIdentifiers(){let e;if(typeof this.loss=="string")e=ka(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=>ka(t))}else{let t=Object.keys(this.loss);e={};let r=this.loss;for(let n of t)if(typeof r[n]=="string")e[n]=ka(r[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[ka(Mh(this.metrics))];if(Array.isArray(this.metrics))return this.metrics.map(e=>ka(Mh(e)));{let e={};for(let t in this.metrics)e[t]=ka(Mh(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=rd(e.optimizer_config),r=On(t),n;if(typeof e.loss=="string")n=Ys(e.loss);else if(Array.isArray(e.loss))n=e.loss.map(s=>Ys(s));else if(e.loss!=null){n={};for(let s in e.loss)n[s]=Ys(e.loss[s])}let a;if(Array.isArray(e.metrics))a=e.metrics.map(s=>Ys(s));else if(e.metrics!=null){a={};for(let s in e.metrics)a[s]=Ys(e.metrics[s])}this.compile({loss:n,metrics:a,optimizer:r})}async save(e,t){if(typeof e=="string"){let a=or.getSaveHandlers(e);if(a.length===0)throw new V(`Cannot find any save handlers for URL '${e}'`);if(a.length>1)throw new V(`Found more than one (${a.length}) save handlers for URL '${e}'`);e=a[0]}if(e.save==null)throw new V("LayersModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");let r=await or.encodeWeights(this.getNamedWeights(t)),n={modelTopology:this.toJSON(null,!1),format:jG,generatedBy:`TensorFlow.js tfjs-layers v${wx}`,convertedBy:null};if(t!=null&&t.includeOptimizer&&this.optimizer!=null){n.trainingConfig=this.getTrainingConfig();let a="optimizer",{data:s,specs:i}=await or.encodeWeights(await this.optimizer.getWeights(),a);r.specs.push(...i),r.data=or.concatenateArrayBuffers([r.data,s])}return this.userDefinedMetadata!=null&&(P0(this.userDefinedMetadata,this.name,!0),n.userDefinedMetadata=this.userDefinedMetadata),n.weightData=r.data,n.weightSpecs=r.specs,e.save(n)}setUserDefinedMetadata(e){P0(e,this.name),this.userDefinedMetadata=e}getUserDefinedMetadata(){return this.userDefinedMetadata}};Ca.className="Model";ne.registerClass(Ca);var BN=class extends Ca{};BN.className="Functional";ne.registerClass(BN);async function qG(e,t){"modelTopology"in e||(e={modelTopology:e}),e=e;let r=e.modelTopology;r.model_config!=null&&(r=r.model_config);let n=rd(r),a=On(n,t);if(e.weightsManifest!=null){let s=await or.loadWeights(e.weightsManifest,e.pathPrefix,a.weights.map(o=>o.originalName)),i={};for(let o of a.weights)i[o.originalName]=s[o.originalName];a.loadWeights(i),Ce(s)}return a}async function KG(e,t){if(t==null&&(t={}),typeof e=="string"){let r=or.getLoadHandlers(e,t);if(r.length===0)r.push(or.browserHTTPRequest(e,t));else if(r.length>1)throw new V(`Found more than one (${r.length}) load handlers for URL '${e}'`);e=r[0]}return XG(e,void 0,t)}async function XG(e,t,r){if(r==null&&(r={}),e.load==null)throw new V("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");let n=await e.load(),a=n.modelTopology;a.model_config!=null&&(a=a.model_config);let s=r.strict==null?!0:r.strict,i=n.weightData!=null&&n.weightSpecs!=null&&s,o=On(rd(a),t,i),l=n.trainingConfig;if(l!=null&&o.loadTrainingConfig(l),n.userDefinedMetadata!=null&&o.setUserDefinedMetadata(n.userDefinedMetadata),n.weightData!=null){if(n.weightSpecs==null)throw new V("LayersModel artifacts contains weight data, but not weight specs. Therefore loading of weights cannot proceed.");let{modelWeights:p,optimizerWeights:u}=ZG(n.weightData,n.weightSpecs);o.loadWeights(p,s),o.optimizer!=null&&u.length>0&&await o.optimizer.setWeights(u),Ce(p),Ce(u.map(d=>d.tensor))}return o}function ZG(e,t){let r=or.decodeWeights(e,t),n={},a=[];return t.forEach(s=>{s.group==="optimizer"?a.push({name:s.name,tensor:r[s.name]}):n[s.name]=r[s.name]}),{modelWeights:n,optimizerWeights:a}}var im=class Ag extends Ca{constructor(t){if(super({inputs:[],outputs:[]}),t=t||{},this.trainable=!0,this.built=!1,this.name=t.name!=null?t.name:Kf("sequential_"),t.layers!=null)for(let r of t.layers)this.add(r)}checkShape(t){if(t.inboundNodes[0].outputTensors[0].shape.some(r=>r<0))throw new V(`Negative dimension size caused by adding layer ${t.name} with input shape [${t.inboundNodes[0].inputTensors[0].shape}]`)}add(t){let r=t instanceof Ag||t instanceof Ca,n;if(r){if(n=t,n.outputs.length!==1)throw new V("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");if(n.inputs.length!==1)throw new V("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(t.inboundNodes.length===0){if(t.batchInputShape==null)throw new V("The first layer in a Sequential model must get an `inputShape` or `batchInputShape` argument.");let a=xN({batchShape:t.batchInputShape,dtype:t.dtype,name:t.name+"_input"});t.apply(a)}if(r)this.outputs=n.outputs,this.inputs=n.inputs;else{if(t.inboundNodes.length!==1)throw new V(`A layer added to a Sequential model must not already be connected somewhere else. LayersModel received layer ${t.name} which has ${t.inboundNodes.length} pre-existing inbound connections.`);if(t.inboundNodes[0].outputTensors.length!==1)throw new V("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");this.checkShape(t),this.outputs=[t.inboundNodes[0].outputTensors[0]],this.inputs=bN(this.outputs[0])}this.inboundNodes=[],new nm({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:vi(null,this.inputs.length),outputMasks:[null],inputShapes:this.inputs.map(a=>a.shape),outputShapes:this.outputs[0].shape})}else{let a=t.apply(this.outputs[0]);if(Array.isArray(a))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(t),this.outputs=[a],this.inboundNodes[0].outputTensors=this.outputs,this.inboundNodes[0].outputShapes=[this.outputs[0].shape]}this.layers.push(t),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 t=this.layers.length-1;this.layers[t].outboundNodes=[],this.outputs=[this.layers[t].output],this.inboundNodes[0].outputTensors=this.outputs,this.inboundNodes[0].outputShapes=[this.outputs[0].shape]}}call(t,r){return this.model==null&&this.build(),this.model.call(t,r)}build(t){if(Xe(t),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 Ca({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(t,r,n=console.log){this.built||this.build(),super.summary(t,r,n)}setWeights(t){this.model==null&&this.build(),this.model.setWeights(t)}evaluate(t,r,n={}){if(!this.built)throw new na("The model needs to be compiled before being used.");return this.model.evaluate(t,r,n)}async evaluateDataset(t,r){if(!this.built)throw new na("The model needs to be compiled before being used.");return this.model.evaluateDataset(t,r)}predict(t,r={}){return this.model==null&&this.build(),this.model.predict(t,r)}predictOnBatch(t){return this.model==null&&this.build(),this.model.predictOnBatch(t)}compile(t){this.build(),this.model.compile(t),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(t){this.model.optimizer=t}async fit(t,r,n={}){if(!this.built)throw new na("The model needs to be compiled before being used.");return this.model.fit(t,r,n)}async fitDataset(t,r){if(!this.built)throw new na("The model needs to be compiled before being used.");return this.model.fitDataset(t,r)}async trainOnBatch(t,r){return this.model.trainOnBatch(t,r)}static fromConfig(t,r,n={},a=!1){let s,i={};if(r instanceof Array){if(r[0].className==null||r[0].className==="Merge")throw new V("Legacy serialization format not supported yet.");s=r}else k.assert(r.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=r.layers,delete r.layers,i=r;let o=new t(i);if(!(o instanceof Ag))throw new Be(`Sequential.fromConfig called on non-Sequential input: ${o}`);for(let l of s){let p=On(l,void 0,a);a&&p.setFastWeightInitDuringBuild(!0),o.add(p)}return o}set stopTraining(t){if(this.model==null)throw new V("Cannot set the stopTraining property of a sequential model before it is compiled.");this.model.stopTraining=t}get stopTraining(){if(this.model==null)throw new V("Cannot get the stopTraining property of a sequential model before it is compiled.");return this.model.stopTraining}getConfig(){let t=[];for(let r of this.layers){let n={};n.className=r.getClassName(),n.config=r.getConfig(),t.push(n)}return{name:this.name,layers:t}}};im.className="Sequential";ne.registerClass(im);function JG(e){return new Ca(e)}function YG(e){return new im(e)}function WN(e){return xN(e)}function QG(e,t){gx.registerCallbackConstructor(e,t)}var dr=class extends ne.Serializable{getConfig(){return{}}},UN=class extends dr{apply(e,t=1){return bV(e,t)}};UN.className="elu";ne.registerClass(UN);var VN=class extends dr{apply(e){return Af(e)}};VN.className="selu";ne.registerClass(VN);var GN=class extends dr{apply(e){return rt(e)}};GN.className="relu";ne.registerClass(GN);var HN=class extends dr{apply(e){return W(()=>ys(6,rt(e)))}};HN.className="relu6";ne.registerClass(HN);var jN=class extends dr{apply(e){return e}};jN.className="linear";ne.registerClass(jN);var qN=class extends dr{apply(e){return In(e)}};qN.className="sigmoid";ne.registerClass(qN);var KN=class extends dr{apply(e){return vV(e)}};KN.className="hardSigmoid";ne.registerClass(KN);var XN=class extends dr{apply(e){return Jo(e)}};XN.className="softplus";ne.registerClass(XN);var ZN=class extends dr{apply(e){return xV(e)}};ZN.className="softsign";ne.registerClass(ZN);var JN=class extends dr{apply(e){return gs(e)}};JN.className="tanh";ne.registerClass(JN);var kx=class extends dr{apply(e,t=-1){return Ds(e,t)}};kx.className="softmax";ne.registerClass(kx);var YN=class extends dr{apply(e,t=-1){return Sf(e,t)}};YN.className="logSoftmax";ne.registerClass(YN);var QN=class extends dr{apply(e){return W(()=>W(()=>{let t=Math.sqrt(2),r=z(.5,J(1,wf(fe(e,t))));return z(e,r)}))}};QN.className="gelu";ne.registerClass(QN);var e2=class extends dr{apply(e){return W(()=>z(.5,z(e,J(1,gs(z(Yt(fe(2,Math.PI)),J(e,z(.044715,da(e,3)))))))))}};e2.className="gelu_new";ne.registerClass(e2);var t2=class extends dr{apply(e){return W(()=>z(e,gs(Jo(e))))}};t2.className="mish";ne.registerClass(t2);var r2=class extends dr{apply(e,t=1){return W(()=>z(In(z(e,t)),e))}};r2.className="swish";ne.registerClass(r2);function vs(e){return e.getClassName()}function Vm(e,t={}){return Qd(e,ne.SerializationMap.getMap().classNameMap,t,"activation")}function ws(e){if(e==null){let t={};return t.className="linear",t.config={},Vm(t)}if(typeof e=="string"){let t={};return t.className=e,t.config={},Vm(t)}else return e instanceof dr?e:Vm(e)}function Ix(e){if(e!=null&&typeof e!="object")throw new Error(`Argument to L1L2 regularizer's constructor is expected to be an object, but received: ${e}`)}var n2=class extends ne.Serializable{},ah=class extends n2{constructor(e){super(),Ix(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 W(()=>{let t=It([1]);return this.hasL1&&(t=J(t,ge(z(this.l1,Ft(e))))),this.hasL2&&(t=J(t,ge(z(this.l2,th(e))))),B(t,[])})}getConfig(){return{l1:this.l1,l2:this.l2}}static fromConfig(e,t){return new e({l1:t.l1,l2:t.l2})}};ah.className="L1L2";ne.registerClass(ah);function eH(e){return Ix(e),new ah({l1:e!=null?e.l1:null,l2:0})}function tH(e){return Ix(e),new ah({l2:e!=null?e.l2:null,l1:0})}var H0={l1l2:"L1L2"};function dt(e){return ex(e)}function j0(e,t={}){return Qd(e,ne.SerializationMap.getMap().classNameMap,t,"regularizer")}function vt(e){if(e==null)return null;if(typeof e=="string"){let t={className:e in H0?H0[e]:e,config:{}};return j0(t)}else return e instanceof n2?e:j0(e)}var Sx=class extends We{constructor(e){super(e??{}),this.supportsMasking=!0,e!=null&&(this.maxValue=e.maxValue)}call(e,t){e=Te(e);let r=rt(e);return this.maxValue!=null&&(r=ur(r,0,this.maxValue)),r}computeOutputShape(e){return e}getConfig(){let e={maxValue:this.maxValue},t=super.getConfig();return Object.assign(e,t),e}};Sx.className="ReLU";ne.registerClass(Sx);var Nx=class extends We{constructor(e){super(e??{}),this.DEFAULT_ALPHA=.3,e==null&&(e={}),this.alpha=e.alpha==null?this.DEFAULT_ALPHA:e.alpha}call(e,t){let r=Te(e);return Ud(r,this.alpha)}computeOutputShape(e){return e}getConfig(){let e={alpha:this.alpha},t=super.getConfig();return Object.assign(e,t),e}};Nx.className="LeakyReLU";ne.registerClass(Nx);var _x=class extends We{constructor(e){if(super(e??{}),this.DEFAULT_ALPHA_INITIALIZER="zeros",e==null&&(e={}),this.supportsMasking=!0,this.alphaInitializer=xt(e.alphaInitializer||this.DEFAULT_ALPHA_INITIALIZER),this.alphaRegularizer=vt(e.alphaRegularizer),this.alphaConstraint=Vt(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 V(`Expected sharedAxes to be a number or an array of numbers, but got ${e.sharedAxes}`)}build(e){e=Xe(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 r={};if(this.sharedAxes!=null)for(let n=1;n<e.length;++n)r[n]=e[n];this.inputSpec=[new Rt({ndim:e.length,axes:r})],this.built=!0}call(e,t){return e=Te(e),Kd(e,this.alpha.read())}getConfig(){let e={alphaInitializer:St(this.alphaInitializer),alphaRegularizer:dt(this.alphaRegularizer),alphaConstraint:Ut(this.alphaConstraint),sharedAxes:this.sharedAxes},t=super.getConfig();return Object.assign(e,t),e}};_x.className="PReLU";ne.registerClass(_x);var Tx=class extends We{constructor(e){if(super(e??{}),this.DEFAULT_ALPHA=1,e==null&&(e={}),e.alpha!=null&&e.alpha!==this.DEFAULT_ALPHA)throw new Be(`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 r=Te(e);return Ju(r)}computeOutputShape(e){return e}getConfig(){let e={alpha:this.alpha},t=super.getConfig();return Object.assign(e,t),e}};Tx.className="ELU";ne.registerClass(Tx);var Cx=class extends We{constructor(e){super(e??{}),this.DEFAULT_THETA=1,e==null&&(e={}),this.theta=e.theta==null?this.DEFAULT_THETA:e.theta}call(e,t){let r=Te(e);return z(r,se(Ir(r,this.theta),"float32"))}computeOutputShape(e){return e}getConfig(){let e={theta:this.theta},t=super.getConfig();return Object.assign(e,t),e}};Cx.className="ThresholdedReLU";ne.registerClass(Cx);var Ex=class extends We{constructor(e){super(e??{}),this.DEFAULT_AXIS=1,e==null&&(e={}),this.softmax=new kx().apply,this.axis=e.axis==null?this.DEFAULT_AXIS:e.axis}call(e,t){return W(()=>{let r=Te(e),n=t.mask;if(n!=null){let a=z(de($r(r.shape),se(n,r.dtype)),we(-1e9));r=J(r,a)}return this.axis instanceof Array?this.axis.length>1?pr(de(r,Gd(r,this.axis,!0))):this.softmax(r,this.axis[0]):this.softmax(r,this.axis)})}computeOutputShape(e){return e}getConfig(){let e={axis:this.axis},t=super.getConfig();return Object.assign(e,t),e}};Ex.className="Softmax";ne.registerClass(Ex);function Sl(e,t,r){if(typeof e=="number")return vi(e,t);if(e.length!==t)throw new V(`The ${r} argument must be an integer or tuple of ${t} integers. Received: ${e.length} elements.`);for(let n=0;n<t;++n){let a=e[n];if(!fV(a))throw new V(`The ${r} argument must be an integer or tuple of ${t} integers. Received: ${JSON.stringify(e)} including a non-integer number ${a}`)}return e}function Ln(e,t,r,n,a=1){if(e==null)return e;let s=t+(t-1)*(a-1),i;return r==="same"?i=e:i=e-s+1,Math.floor((i+n-1)/n)}function ta(e,t,r,n){if(e==null)return null;if(n==="valid")e=e*t+xs([r-t,0]);else if(n==="same")e=e*t;else throw new V(`Unsupport padding mode: ${n}.`);return e}function $x(e,t){return W(()=>(Ct(t),t==="channelsFirst"?Oe(e,[0,2,3,1]):e))}function a2(e,t){return W(()=>(Ct(t),t==="channelsFirst"?Oe(e,[0,2,3,4,1]):e))}function rH(e,t,r,n=1,a="valid",s,i=1){return W(()=>{if(s==null&&(s=Wn()),Ct(s),e.shape.length!==3)throw new V(`The input of a conv1dWithBias operation should be 3, but is ${e.shape.length} instead.`);if(t.shape.length!==3)throw new V(`The kernel for a conv1dWithBias operation should be 3, but is ${t.shape.length} instead`);if(r!=null&&r.shape.length!==1)throw new V(`The bias for a conv1dWithBias operation should be 1, but is ${r.shape.length} instead`);if(s==="channelsFirst"&&(e=Oe(e,[0,2,1])),a==="causal")throw new Be("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");let o=yf(e,t,n,a==="same"?"same":"valid","NWC",i);return r!=null&&(o=qn(o,r)),o})}function q0(e,t,r,n=[1,1],a="valid",s,i,o=null){return W(()=>{if(s==null&&(s=Wn()),Ct(s),e.rank!==3&&e.rank!==4)throw new V(`conv2dWithBiasActivation expects input to be of rank 3 or 4, but received ${e.rank}.`);if(t.rank!==3&&t.rank!==4)throw new V(`conv2dWithBiasActivation expects kernel to be of rank 3 or 4, but received ${e.rank}.`);let l=$x(e,s);if(a==="causal")throw new Be("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");return l=Ol.conv2d({x:l,filter:t,strides:n,pad:a==="same"?"same":"valid",dilations:i,dataFormat:"NHWC",bias:r,activation:o}),s==="channelsFirst"&&(l=Oe(l,[0,3,1,2])),l})}function nH(e,t,r,n=[1,1,1],a="valid",s,i){return W(()=>{if(s==null&&(s=Wn()),Ct(s),e.rank!==4&&e.rank!==5)throw new V(`conv3dWithBias expects input to be of rank 4 or 5, but received ${e.rank}.`);if(t.rank!==4&&t.rank!==5)throw new V(`conv3dWithBias expects kernel to be of rank 4 or 5, but received ${e.rank}.`);let o=a2(e,s);if(a==="causal")throw new Be("The support for CAUSAL padding mode in conv3dWithBias is not implemented yet.");return o=ab(o,t,n,a==="same"?"same":"valid","NDHWC",i),r!=null&&(o=qn(o,r)),s==="channelsFirst"&&(o=Oe(o,[0,4,1,2,3])),o})}var s2=class i2 extends We{constructor(t,r){if(super(r),this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",i2.verifyArgs(r),this.rank=t,Zt(this.rank,"rank"),this.rank!==1&&this.rank!==2&&this.rank!==3)throw new Be(`Convolution layer for rank other than 1, 2, or 3 (${this.rank}) is not implemented yet.`);if(this.kernelSize=Sl(r.kernelSize,t,"kernelSize"),this.strides=Sl(r.strides==null?1:r.strides,t,"strides"),this.padding=r.padding==null?"valid":r.padding,gn(this.padding),this.dataFormat=r.dataFormat==null?"channelsLast":r.dataFormat,Ct(this.dataFormat),this.activation=ws(r.activation),this.useBias=r.useBias==null?!0:r.useBias,this.biasInitializer=xt(r.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.biasConstraint=Vt(r.biasConstraint),this.biasRegularizer=vt(r.biasRegularizer),this.activityRegularizer=vt(r.activityRegularizer),this.dilationRate=Sl(r.dilationRate==null?1:r.dilationRate,t,"dilationRate"),this.rank===1&&Array.isArray(this.dilationRate)&&this.dilationRate.length!==1)throw new V(`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 V(`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 V(`dilationRate must be a number or array of three numbers for 3D convolution, but received ${JSON.stringify(this.dilationRate)}`)}}static verifyArgs(t){if(ea("kernelSize"in t,"required key 'kernelSize' not in config"),typeof t.kernelSize!="number"&&!tx(t.kernelSize,"number",1,3))throw new V(`BaseConv expects config.kernelSize to be number or number[] with length 1, 2, or 3, but received ${JSON.stringify(t.kernelSize)}.`)}getConfig(){let t={kernelSize:this.kernelSize,strides:this.strides,padding:this.padding,dataFormat:this.dataFormat,dilationRate:this.dilationRate,activation:vs(this.activation),useBias:this.useBias,biasInitializer:St(this.biasInitializer),biasRegularizer:dt(this.biasRegularizer),activityRegularizer:dt(this.activityRegularizer),biasConstraint:Ut(this.biasConstraint)},r=super.getConfig();return Object.assign(t,r),t}},om=class o2 extends s2{constructor(t,r){super(t,r),this.kernel=null,o2.verifyArgs(r),this.filters=r.filters,Zt(this.filters,"filters"),this.kernelInitializer=xt(r.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.kernelConstraint=Vt(r.kernelConstraint),this.kernelRegularizer=vt(r.kernelRegularizer)}build(t){t=Xe(t);let r=this.dataFormat==="channelsFirst"?1:t.length-1;if(t[r]==null)throw new V(`The channel dimension of the input should be defined. Found ${t[r]}`);let n=t[r],a=this.kernelSize.concat([n,this.filters]);this.kernel=this.addWeight("kernel",a,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:{[r]:n}}],this.built=!0}call(t,r){return W(()=>{t=Te(t);let n,a=this.bias==null?null:this.bias.read(),s=uN(this.activation.getClassName());if(s!=null&&this.rank===2)n=q0(t,this.kernel.read(),a,this.strides,this.padding,this.dataFormat,this.dilationRate,s);else{if(this.rank===1)n=rH(t,this.kernel.read(),a,this.strides[0],this.padding,this.dataFormat,this.dilationRate[0]);else if(this.rank===2)n=q0(t,this.kernel.read(),a,this.strides,this.padding,this.dataFormat,this.dilationRate);else if(this.rank===3)n=nH(t,this.kernel.read(),a,this.strides,this.padding,this.dataFormat,this.dilationRate);else throw new Be("convolutions greater than 3D are not implemented yet.");this.activation!=null&&(n=this.activation.apply(n))}return n})}computeOutputShape(t){t=Xe(t);let r=[],n=this.dataFormat==="channelsLast"?t.slice(1,t.length-1):t.slice(2);for(let s=0;s<n.length;++s){let i=Ln(n[s],this.kernelSize[s],this.padding,this.strides[s],typeof this.dilationRate=="number"?this.dilationRate:this.dilationRate[s]);r.push(i)}let a=[t[0]];return this.dataFormat==="channelsLast"?(a=a.concat(r),a.push(this.filters)):(a.push(this.filters),a=a.concat(r)),a}getConfig(){let t={filters:this.filters,kernelInitializer:St(this.kernelInitializer),kernelRegularizer:dt(this.kernelRegularizer),kernelConstraint:Ut(this.kernelConstraint)},r=super.getConfig();return Object.assign(t,r),t}static verifyArgs(t){if(!("filters"in t)||typeof t.filters!="number"||t.filters<1)throw new V(`Convolution layer expected config.filters to be a 'number' > 0 but got ${JSON.stringify(t.filters)}`)}},lm=class l2 extends om{constructor(t){super(2,t),l2.verifyArgs(t)}getConfig(){let t=super.getConfig();return delete t.rank,t}static verifyArgs(t){if(typeof t.kernelSize!="number"&&!tx(t.kernelSize,"number",1,2))throw new V(`Conv2D expects config.kernelSize to be number or number[] with length 1 or 2, but received ${JSON.stringify(t.kernelSize)}.`)}};lm.className="Conv2D";ne.registerClass(lm);var um=class u2 extends om{constructor(t){super(3,t),u2.verifyArgs(t)}getConfig(){let t=super.getConfig();return delete t.rank,t}static verifyArgs(t){if(typeof t.kernelSize!="number"&&!(Array.isArray(t.kernelSize)&&(t.kernelSize.length===1||t.kernelSize.length===3)))throw new V(`Conv3D expects config.kernelSize to be number or [number, number, number], but received ${JSON.stringify(t.kernelSize)}.`)}};um.className="Conv3D";ne.registerClass(um);var Ax=class extends lm{constructor(e){if(super(e),this.inputSpec=[new Rt({ndim:4})],this.padding!=="same"&&this.padding!=="valid")throw new V(`Conv2DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(e){if(e=Xe(e),e.length!==4)throw new V("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 V("The channel dimension of the inputs should be defined. Found `None`.");let r=e[t],n=this.kernelSize.concat([this.filters,r]);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 Rt({ndim:4,axes:{[t]:r}})],this.built=!0}call(e,t){return W(()=>{let r=Te(e);if(r.shape.length!==4)throw new V(`Conv2DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${r.shape.length}`);let n=r.shape,a=n[0],s,i;this.dataFormat==="channelsFirst"?(s=2,i=3):(s=1,i=2);let o=n[s],l=n[i],p=this.kernelSize[0],u=this.kernelSize[1],d=this.strides[0],h=this.strides[1],c=ta(o,d,p,this.padding),f=ta(l,h,u,this.padding),m=[a,c,f,this.filters];this.dataFormat!=="channelsLast"&&(r=Oe(r,[0,2,3,1]));let g=bf(r,this.kernel.read(),m,this.strides,this.padding);return this.dataFormat!=="channelsLast"&&(g=Oe(g,[0,3,1,2])),this.bias!=null&&(g=qn(g,this.bias.read(),this.dataFormat)),this.activation!=null&&(g=this.activation.apply(g)),g})}computeOutputShape(e){e=Xe(e);let t=e.slice(),r,n,a;this.dataFormat==="channelsFirst"?(r=1,n=2,a=3):(r=3,n=1,a=2);let s=this.kernelSize[0],i=this.kernelSize[1],o=this.strides[0],l=this.strides[1];return t[r]=this.filters,t[n]=ta(t[n],o,s,this.padding),t[a]=ta(t[a],l,i,this.padding),t}getConfig(){let e=super.getConfig();return delete e.dilationRate,e}};Ax.className="Conv2DTranspose";ne.registerClass(Ax);var Fx=class extends um{constructor(e){if(super(e),this.inputSpec=[new Rt({ndim:5})],this.padding!=="same"&&this.padding!=="valid")throw new V(`Conv3DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(e){if(e=Xe(e),e.length!==5)throw new V("Input should have rank 5; Received input shape: "+JSON.stringify(e));let t=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[t]==null)throw new V("The channel dimension of the inputs should be defined. Found `None`.");let r=e[t],n=this.kernelSize.concat([this.filters,r]);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 Rt({ndim:5,axes:{[t]:r}})],this.built=!0}call(e,t){return W(()=>{let r=Te(e);if(r.shape.length!==5)throw new V(`Conv3DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${r.shape.length}`);let n=r.shape,a=n[0],s,i,o;this.dataFormat==="channelsFirst"?(o=2,s=3,i=4):(o=1,s=2,i=3);let l=n[o],p=n[s],u=n[i],d=this.kernelSize[0],h=this.kernelSize[1],c=this.kernelSize[2],f=this.strides[0],m=this.strides[1],g=this.strides[2],y=ta(l,f,d,this.padding),b=ta(p,m,h,this.padding),x=ta(u,g,c,this.padding),v=[a,y,b,x,this.filters];this.dataFormat!=="channelsLast"&&(r=Oe(r,[0,2,3,4,1]));let w=sb(r,this.kernel.read(),v,this.strides,this.padding);return this.dataFormat!=="channelsLast"&&(w=Oe(w,[0,4,1,2,3])),this.bias!==null&&(w=qn(w,this.bias.read(),this.dataFormat)),this.activation!==null&&(w=this.activation.apply(w)),w})}computeOutputShape(e){e=Xe(e);let t=e.slice(),r,n,a,s;this.dataFormat==="channelsFirst"?(r=1,n=2,a=3,s=4):(r=4,n=1,a=2,s=3);let i=this.kernelSize[0],o=this.kernelSize[1],l=this.kernelSize[2],p=this.strides[0],u=this.strides[1],d=this.strides[2];return t[r]=this.filters,t[n]=ta(t[n],p,i,this.padding),t[a]=ta(t[a],u,o,this.padding),t[s]=ta(t[s],d,l,this.padding),t}getConfig(){let e=super.getConfig();return delete e.dilationRate,e}};Fx.className="Conv3DTranspose";ne.registerClass(Fx);var p2=class extends om{constructor(e,t){if(super(e,t),this.DEFAULT_DEPTHWISE_INITIALIZER="glorotUniform",this.DEFAULT_POINTWISE_INITIALIZER="glorotUniform",this.depthwiseKernel=null,this.pointwiseKernel=null,t.filters==null)throw new V("The `filters` configuration field is required by SeparableConv, but is unspecified.");if(t.kernelInitializer!=null||t.kernelRegularizer!=null||t.kernelConstraint!=null)throw new V("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 V(`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=xt(t.depthwiseInitializer||this.DEFAULT_DEPTHWISE_INITIALIZER),this.depthwiseRegularizer=vt(t.depthwiseRegularizer),this.depthwiseConstraint=Vt(t.depthwiseConstraint),this.pointwiseInitializer=xt(t.depthwiseInitializer||this.DEFAULT_POINTWISE_INITIALIZER),this.pointwiseRegularizer=vt(t.pointwiseRegularizer),this.pointwiseConstraint=Vt(t.pointwiseConstraint)}build(e){if(e=Xe(e),e.length<this.rank+2)throw new V(`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 V(`The channel dimension of the inputs should be defined, but found ${JSON.stringify(e[t])}`);let r=e[t],n=this.kernelSize.concat([r,this.depthMultiplier]),a=[];for(let i=0;i<this.rank;++i)a.push(1);a.push(r*this.depthMultiplier,this.filters);let s=!0;this.depthwiseKernel=this.addWeight("depthwise_kernel",n,"float32",this.depthwiseInitializer,this.depthwiseRegularizer,s,this.depthwiseConstraint),this.pointwiseKernel=this.addWeight("pointwise_kernel",a,"float32",this.pointwiseInitializer,this.pointwiseRegularizer,s,this.pointwiseConstraint),this.useBias?this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,s,this.biasConstraint):this.bias=null,this.inputSpec=[new Rt({ndim:this.rank+2,axes:{[t]:r}})],this.built=!0}call(e,t){return W(()=>{e=Te(e);let r;if(this.rank===1)throw new Be("1D separable convolution is not implemented yet.");return this.rank===2&&(this.dataFormat==="channelsFirst"&&(e=Oe(e,[0,2,3,1])),r=tp(e,this.depthwiseKernel.read(),this.pointwiseKernel.read(),this.strides,this.padding,this.dilationRate,"NHWC")),this.useBias&&(r=qn(r,this.bias.read(),this.dataFormat)),this.activation!=null&&(r=this.activation.apply(r)),this.dataFormat==="channelsFirst"&&(r=Oe(r,[0,3,1,2])),r})}getConfig(){let e=super.getConfig();return delete e.rank,delete e.kernelInitializer,delete e.kernelRegularizer,delete e.kernelConstraint,e.depthwiseInitializer=St(this.depthwiseInitializer),e.pointwiseInitializer=St(this.pointwiseInitializer),e.depthwiseRegularizer=dt(this.depthwiseRegularizer),e.pointwiseRegularizer=dt(this.pointwiseRegularizer),e.depthwiseConstraint=Ut(this.depthwiseConstraint),e.pointwiseConstraint=Ut(this.pointwiseConstraint),e}};p2.className="SeparableConv";var Rx=class extends p2{constructor(e){super(2,e)}};Rx.className="SeparableConv2D";ne.registerClass(Rx);var Dx=class d2 extends om{constructor(t){super(1,t),d2.verifyArgs(t),this.inputSpec=[{ndim:3}]}getConfig(){let t=super.getConfig();return delete t.rank,delete t.dataFormat,t}static verifyArgs(t){if(typeof t.kernelSize!="number"&&!tx(t.kernelSize,"number",1,1))throw new V(`Conv1D expects config.kernelSize to be number or number[] with length 1, but received ${JSON.stringify(t.kernelSize)}.`)}};Dx.className="Conv1D";ne.registerClass(Dx);var Mx=class extends We{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 W(()=>{if(e=Te(e),this.dataFormat==="channelsLast"){let r=Dh(e,this.cropping[0][0],e.shape[1]-this.cropping[0][0]-this.cropping[0][1],2);return Dh(r,this.cropping[1][0],e.shape[2]-this.cropping[1][1]-this.cropping[1][0],3)}else{let r=Dh(e,this.cropping[0][0],e.shape[2]-this.cropping[0][0]-this.cropping[0][1],3);return Dh(r,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}};Mx.className="Cropping2D";ne.registerClass(Mx);var Ox=class extends We{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,Ct(this.dataFormat),this.interpolation=e.interpolation==null?"nearest":e.interpolation,dV(this.interpolation)}computeOutputShape(e){if(this.dataFormat==="channelsFirst"){let t=e[2]==null?null:this.size[0]*e[2],r=e[3]==null?null:this.size[1]*e[3];return[e[0],e[1],t,r]}else{let t=e[1]==null?null:this.size[0]*e[1],r=e[2]==null?null:this.size[1]*e[2];return[e[0],t,r,e[3]]}}call(e,t){return W(()=>{let r=Te(e),n=r.shape;if(this.dataFormat==="channelsFirst"){r=Oe(r,[0,2,3,1]);let a=this.size[0]*n[2],s=this.size[1]*n[3],i=this.interpolation==="nearest"?sn.resizeNearestNeighbor(r,[a,s]):sn.resizeBilinear(r,[a,s]);return Oe(i,[0,3,1,2])}else{let a=this.size[0]*n[1],s=this.size[1]*n[2];return this.interpolation==="nearest"?sn.resizeNearestNeighbor(r,[a,s]):sn.resizeBilinear(r,[a,s])}})}getConfig(){let e={size:this.size,dataFormat:this.dataFormat,interpolation:this.interpolation},t=super.getConfig();return Object.assign(e,t),e}};Ox.className="UpSampling2D";ne.registerClass(Ox);function aH(e,t,r=[1,1],n="valid",a,s){return W(()=>{a==null&&(a=Wn()),Ct(a);let i=$x(e,a);if(e.rank!==4)throw new V(`Input for depthwiseConv2d is required to be 4-D, but is instead ${e.rank}-D`);if(t.rank!==4)throw new V(`depthwiseKernel is required to be 4-D, but is instead ${t.rank}-D`);return i=Zo(i,t,r,n==="same"?"same":"valid","NHWC",s),a==="channelsFirst"&&(i=Oe(i,[0,3,1,2])),i})}var Lx=class extends s2{constructor(e){super(2,e),this.depthwiseKernel=null,this.depthMultiplier=e.depthMultiplier==null?1:e.depthMultiplier,this.depthwiseInitializer=xt(e.depthwiseInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.depthwiseConstraint=Vt(e.depthwiseConstraint),this.depthwiseRegularizer=vt(e.depthwiseRegularizer)}build(e){if(e=Xe(e),e.length<4)throw new V(`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 V(`The channel dimension of the inputs to DepthwiseConv2D should be defined, but is not (${e[t]}).`);let r=e[t],n=[this.kernelSize[0],this.kernelSize[1],r,this.depthMultiplier];this.depthwiseKernel=this.addWeight("depthwise_kernel",n,null,this.depthwiseInitializer,this.depthwiseRegularizer,!0,this.depthwiseConstraint),this.useBias?this.bias=this.addWeight("bias",[r*this.depthMultiplier],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return W(()=>{e=Te(e);let r=aH(e,this.depthwiseKernel.read(),this.strides,this.padding,this.dataFormat,null);return this.useBias&&(r=qn(r,this.bias.read(),this.dataFormat)),this.activation!=null&&(r=this.activation.apply(r)),r})}computeOutputShape(e){e=Xe(e);let t=this.dataFormat==="channelsFirst"?e[2]:e[1],r=this.dataFormat==="channelsFirst"?e[3]:e[2],n=this.dataFormat==="channelsFirst"?e[1]*this.depthMultiplier:e[3]*this.depthMultiplier,a=Ln(t,this.kernelSize[0],this.padding,this.strides[0]),s=Ln(r,this.kernelSize[1],this.padding,this.strides[1]);return this.dataFormat==="channelsFirst"?[e[0],n,a,s]:[e[0],a,s,n]}getConfig(){let e=super.getConfig();return e.depthMultiplier=this.depthMultiplier,e.depthwiseInitializer=St(this.depthwiseInitializer),e.depthwiseRegularizer=dt(this.depthwiseRegularizer),e.depthwiseConstraint=Ut(this.depthwiseRegularizer),e}};Lx.className="DepthwiseConv2D";ne.registerClass(Lx);function h2(e,t,r,n){if(Array.isArray(e)){if(t!=null||r!=null)throw new V("When inputs is an array, neither initialState or constants should be provided");n!=null&&(r=e.slice(e.length-n,e.length),e=e.slice(0,e.length-n)),e.length>1&&(t=e.slice(1,e.length)),e=e[0]}function a(s){return s==null||Array.isArray(s)?s:[s]}return t=a(t),r=a(r),{inputs:e,initialState:t,constants:r}}function c2(e,t,r,n=!1,a,s,i=!1,o=!1){return W(()=>{let l=t.shape.length;if(l<3)throw new V(`Input should be at least 3D, but is ${l}D.`);let p=[1,0].concat(Bn(2,l));t=Oe(t,p),s!=null,i&&console.warn("Backend rnn(): the unroll = true option is not applicable to the imperative deeplearn.js backend."),a!=null&&(a=se(se(a,"bool"),"float32"),a.rank===l-1&&(a=Xt(a,-1)),a=Oe(a,p)),n&&(t=mn(t,0),a!=null&&(a=mn(a,0)));let u=[],d,h=r,c=t.shape[0],f=Tt(t),m;a!=null&&(m=Tt(a));for(let y=0;y<c;++y){let b=f[y],x=W(()=>e(b,h));if(a==null)d=x[0],h=x[1];else{let v=W(()=>{let w=m[y],N=de(Zr(w),w),T=J(z(x[0],w),z(h[0],N)),E=h.map(($,R)=>J(z(x[1][R],w),z($,N)));return{output:T,newStates:E}});d=v.output,h=v.newStates}o&&u.push(d)}let g;return o&&(g=Mt(u,1)),[d,g,h]})}var Ba=class f2 extends We{constructor(t){super(t);let r;if(t.cell==null)throw new V("cell property is missing for the constructor of RNN.");if(Array.isArray(t.cell)?r=new hm({cells:t.cell}):r=t.cell,r.stateSize==null)throw new V("The RNN cell should have an attribute `stateSize` (tuple of integers, one integer per RNN state).");this.cell=r,this.returnSequences=t.returnSequences==null?!1:t.returnSequences,this.returnState=t.returnState==null?!1:t.returnState,this.goBackwards=t.goBackwards==null?!1:t.goBackwards,this._stateful=t.stateful==null?!1:t.stateful,this.unroll=t.unroll==null?!1:t.unroll,this.supportsMasking=!0,this.inputSpec=[new Rt({ndim:3})],this.stateSpec=null,this.states_=null,this.numConstants=null,this.keptStates=[]}getStates(){if(this.states_==null){let t=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1;return Bn(0,t).map(r=>null)}else return this.states_}setStates(t){this.states_=t}computeOutputShape(t){Ng(t)&&(t=t[0]),t=t;let r=this.cell.stateSize;Array.isArray(r)||(r=[r]);let n=r[0],a;if(this.returnSequences?a=[t[0],t[1],n]:a=[t[0],n],this.returnState){let s=[];for(let i of r)s.push([t[0],i]);return[a].concat(s)}else return a}computeMask(t,r){return W(()=>{Array.isArray(r)&&(r=r[0]);let n=this.returnSequences?r:null;if(this.returnState){let a=this.states.map(s=>null);return[n].concat(a)}else return n})}get states(){if(this.states_==null){let t=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1,r=[];for(let n=0;n<t;++n)r.push(null);return r}else return this.states_}set states(t){this.states_=t}build(t){if(this.numConstants!=null)throw new Be("Constants support is not implemented in RNN yet.");Ng(t)&&(t=t[0]),t=t;let r=this.stateful?t[0]:null,n=t.slice(2);this.inputSpec[0]=new Rt({shape:[r,null,...n]});let a=[t[0]].concat(t.slice(2));this.cell.build(a);let s;if(Array.isArray(this.cell.stateSize)?s=this.cell.stateSize:s=[this.cell.stateSize],this.stateSpec!=null){if(!k.arraysEqual(this.stateSpec.map(i=>i.shape[i.shape.length-1]),s))throw new V(`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=s.map(i=>new Rt({shape:[null,i]}));this.stateful&&this.resetStates()}resetStates(t,r=!1){W(()=>{if(!this.stateful)throw new Ya("Cannot call resetStates() on an RNN Layer that is not stateful.");let n=this.inputSpec[0].shape[0];if(n==null)throw new V("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(a=>It([n,a])):this.states_=[It([n,this.cell.stateSize])];else if(t==null)Ce(this.states_),this.keptStates!=null&&(Ce(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(a=>It([n,a])):this.states_[0]=It([n,this.cell.stateSize]);else{if(Array.isArray(t)||(t=[t]),t.length!==this.states_.length)throw new V(`Layer ${this.name} expects ${this.states_.length} state(s), but it received ${t.length} state value(s). Input received: ${t}`);r===!0?this.keptStates.push(this.states_.slice()):Ce(this.states_);for(let a=0;a<this.states_.length;++a){let s=t[a],i=Array.isArray(this.cell.stateSize)?this.cell.stateSize[a]:this.cell.stateSize,o=[n,i];if(!k.arraysEqual(s.shape,o))throw new V(`State ${a} is incompatible with layer ${this.name}: expected shape=${o}, received shape=${s.shape}`);this.states_[a]=s}}this.states_=this.states_.map(a=>Pt(a.clone()))})}apply(t,r){let n=r==null?null:r.initialState,a=r==null?null:r.constants;r==null&&(r={});let s=h2(t,n,a,this.numConstants);t=s.inputs,n=s.initialState,a=s.constants;let i=[],o=[];if(n!=null){r.initialState=n,i=i.concat(n),this.stateSpec=[];for(let l of n)this.stateSpec.push(new Rt({shape:l.shape}));o=o.concat(this.stateSpec)}if(a!=null&&(r.constants=a,i=i.concat(a),this.numConstants=a.length),i[0]instanceof Un){let l=[t].concat(i),p=this.inputSpec.concat(o),u=this.inputSpec;this.inputSpec=p;let d=super.apply(l,r);return this.inputSpec=u,d}else return super.apply(t,r)}call(t,r){return W(()=>{let n=r==null?null:r.mask,a=r==null?null:r.training,s=r==null?null:r.initialState;t=Te(t),s==null&&(this.stateful?s=this.states_:s=this.getInitialState(t));let i=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1;if(s.length!==i)throw new V(`RNN Layer has ${i} 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 o={training:a},l=c2((c,f)=>{let m=this.cell.call([c].concat(f),o);return[m[0],m.slice(1)]},t,s,this.goBackwards,n,null,this.unroll,this.returnSequences),p=l[0],u=l[1],d=l[2];this.stateful&&this.resetStates(d,a);let h=this.returnSequences?u:p;return this.returnState?[h].concat(d):h})}getInitialState(t){return W(()=>{let r=It(t.shape);return r=ge(r,[1,2]),r=eh(r),Array.isArray(this.cell.stateSize)?this.cell.stateSize.map(n=>n>1?Ig(r,[1,n]):r):this.cell.stateSize>1?[Ig(r,[1,this.cell.stateSize])]:[r]})}get trainableWeights(){return this.trainable?this.cell.trainableWeights:[]}get nonTrainableWeights(){return this.trainable?this.cell.nonTrainableWeights:this.cell.weights}setFastWeightInitDuringBuild(t){super.setFastWeightInitDuringBuild(t),this.cell!=null&&this.cell.setFastWeightInitDuringBuild(t)}getConfig(){let t=super.getConfig(),r={returnSequences:this.returnSequences,returnState:this.returnState,goBackwards:this.goBackwards,stateful:this.stateful,unroll:this.unroll};this.numConstants!=null&&(r.numConstants=this.numConstants);let n=this.cell.getConfig();return this.getClassName()===f2.className&&(r.cell={className:this.cell.getClassName(),config:n}),Object.assign(Object.assign(Object.assign({},n),t),r)}static fromConfig(t,r,n={}){let a=r.cell,s=On(a,n);return new t(Object.assign(r,{cell:s}))}};Ba.className="RNN";ne.registerClass(Ba);var sh=class extends We{},pm=class extends sh{constructor(e){super(e),this.DEFAULT_ACTIVATION="tanh",this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_RECURRENT_INITIALIZER="orthogonal",this.DEFAULT_BIAS_INITIALIZER="zeros",this.units=e.units,Zt(this.units,"units"),this.activation=ws(e.activation==null?this.DEFAULT_ACTIVATION:e.activation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=xt(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=xt(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=xt(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=vt(e.kernelRegularizer),this.recurrentRegularizer=vt(e.recurrentRegularizer),this.biasRegularizer=vt(e.biasRegularizer),this.kernelConstraint=Vt(e.kernelConstraint),this.recurrentConstraint=Vt(e.recurrentConstraint),this.biasConstraint=Vt(e.biasConstraint),this.dropout=Ll([1,xs([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=Ll([1,xs([0,e.recurrentDropout==null?0:e.recurrentDropout])]),this.dropoutFunc=e.dropoutFunc,this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){e=Xe(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 W(()=>{if(e=e,e.length!==2)throw new V(`SimpleRNNCell expects 2 input Tensors, got ${e.length}.`);let r=e[1];e=e[0];let n=t.training==null?!1:t.training;0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=ks({ones:()=>Zr(e),rate:this.dropout,training:n,dropoutFunc:this.dropoutFunc})),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=ks({ones:()=>Zr(r),rate:this.recurrentDropout,training:n,dropoutFunc:this.dropoutFunc}));let a,s=this.dropoutMask,i=this.recurrentDropoutMask;s!=null?a=oa(z(e,s),this.kernel.read()):a=oa(e,this.kernel.read()),this.bias!=null&&(a=qn(a,this.bias.read())),i!=null&&(r=z(r,i));let o=J(a,oa(r,this.recurrentKernel.read()));return this.activation!=null&&(o=this.activation.apply(o)),[o,o]})}getConfig(){let e=super.getConfig(),t={units:this.units,activation:vs(this.activation),useBias:this.useBias,kernelInitializer:St(this.kernelInitializer),recurrentInitializer:St(this.recurrentInitializer),biasInitializer:St(this.biasInitializer),kernelRegularizer:dt(this.kernelRegularizer),recurrentRegularizer:dt(this.recurrentRegularizer),biasRegularizer:dt(this.biasRegularizer),activityRegularizer:dt(this.activityRegularizer),kernelConstraint:Ut(this.kernelConstraint),recurrentConstraint:Ut(this.recurrentConstraint),biasConstraint:Ut(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout};return Object.assign(Object.assign({},e),t)}};pm.className="SimpleRNNCell";ne.registerClass(pm);var zx=class extends Ba{constructor(e){e.cell=new pm(e),super(e)}call(e,t){return W(()=>{this.cell.dropoutMask!=null&&(Ce(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(Ce(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);let r=t==null?null:t.mask,n=t==null?null:t.training,a=t==null?null:t.initialState;return super.call(e,{mask:r,training:n,initialState:a})})}static fromConfig(e,t){return new e(t)}};zx.className="SimpleRNN";ne.registerClass(zx);var dm=class extends sh{constructor(e){if(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",e.resetAfter)throw new V("GRUCell does not support reset_after parameter set to true.");this.units=e.units,Zt(this.units,"units"),this.activation=ws(e.activation===void 0?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=ws(e.recurrentActivation===void 0?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=xt(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=xt(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=xt(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=vt(e.kernelRegularizer),this.recurrentRegularizer=vt(e.recurrentRegularizer),this.biasRegularizer=vt(e.biasRegularizer),this.kernelConstraint=Vt(e.kernelConstraint),this.recurrentConstraint=Vt(e.recurrentConstraint),this.biasConstraint=Vt(e.biasConstraint),this.dropout=Ll([1,xs([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=Ll([1,xs([0,e.recurrentDropout==null?0:e.recurrentDropout])]),this.dropoutFunc=e.dropoutFunc,this.implementation=e.implementation,this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){e=Xe(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 W(()=>{if(e=e,e.length!==2)throw new V(`GRUCell expects 2 input Tensors (inputs, h, c), got ${e.length}.`);let r=t.training==null?!1:t.training,n=e[1];e=e[0],0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=ks({ones:()=>Zr(e),rate:this.dropout,training:r,count:3,dropoutFunc:this.dropoutFunc})),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=ks({ones:()=>Zr(n),rate:this.recurrentDropout,training:r,count:3,dropoutFunc:this.dropoutFunc}));let a=this.dropoutMask,s=this.recurrentDropoutMask,i,o,l;0<this.dropout&&this.dropout<1&&(e=z(e,a[0]));let p=oa(e,this.kernel.read());this.useBias&&(p=qn(p,this.bias.read())),0<this.recurrentDropout&&this.recurrentDropout<1&&(n=z(n,s[0]));let u=this.recurrentKernel.read(),[d,h]=Ar(u,[2*this.units,this.units],u.rank-1),c=oa(n,d),[f,m,g]=Ar(p,3,p.rank-1),[y,b]=Ar(c,2,c.rank-1);i=this.recurrentActivation.apply(J(f,y)),o=this.recurrentActivation.apply(J(m,b));let x=oa(z(o,n),h);l=this.activation.apply(J(g,x));let v=J(z(i,n),z(J(1,gt(i)),l));return[v,v]})}getConfig(){let e=super.getConfig(),t={units:this.units,activation:vs(this.activation),recurrentActivation:vs(this.recurrentActivation),useBias:this.useBias,kernelInitializer:St(this.kernelInitializer),recurrentInitializer:St(this.recurrentInitializer),biasInitializer:St(this.biasInitializer),kernelRegularizer:dt(this.kernelRegularizer),recurrentRegularizer:dt(this.recurrentRegularizer),biasRegularizer:dt(this.biasRegularizer),activityRegularizer:dt(this.activityRegularizer),kernelConstraint:Ut(this.kernelConstraint),recurrentConstraint:Ut(this.recurrentConstraint),biasConstraint:Ut(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation,resetAfter:!1};return Object.assign(Object.assign({},e),t)}};dm.className="GRUCell";ne.registerClass(dm);var Px=class extends Ba{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 dm(e),super(e)}call(e,t){return W(()=>{this.cell.dropoutMask!=null&&(Ce(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(Ce(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);let r=t==null?null:t.mask,n=t==null?null:t.training,a=t==null?null:t.initialState;return super.call(e,{mask:r,training:n,initialState:a})})}static fromConfig(e,t){return t.implmentation===0&&(t.implementation=1),new e(t)}};Px.className="GRU";ne.registerClass(Px);var ih=class extends sh{constructor(e){super(e),this.DEFAULT_ACTIVATION="tanh",this.DEFAULT_RECURRENT_ACTIVATION="hardSigmoid",this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_RECURRENT_INITIALIZER="orthogonal",this.DEFAULT_BIAS_INITIALIZER="zeros",this.units=e.units,Zt(this.units,"units"),this.activation=ws(e.activation===void 0?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=ws(e.recurrentActivation===void 0?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=xt(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=xt(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=xt(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.unitForgetBias=e.unitForgetBias,this.kernelRegularizer=vt(e.kernelRegularizer),this.recurrentRegularizer=vt(e.recurrentRegularizer),this.biasRegularizer=vt(e.biasRegularizer),this.kernelConstraint=Vt(e.kernelConstraint),this.recurrentConstraint=Vt(e.recurrentConstraint),this.biasConstraint=Vt(e.biasConstraint),this.dropout=Ll([1,xs([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=Ll([1,xs([0,e.recurrentDropout==null?0:e.recurrentDropout])]),this.dropoutFunc=e.dropoutFunc,this.implementation=e.implementation,this.stateSize=[this.units,this.units],this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){var t;e=Xe(e);let r=e[e.length-1];this.kernel=this.addWeight("kernel",[r,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 a=this.biasInitializer,s=this.units;n=new(t=class extends Tn{apply(i,o){let l=a.apply([s]),p=new Zf().apply([s]),u=a.apply([s*2]);return A0(A0(l,p),u)}},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 W(()=>{let r=t.training==null?!1:t.training;if(e=e,e.length!==3)throw new V(`LSTMCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);let n=e[1],a=e[2];e=e[0],0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=ks({ones:()=>Zr(e),rate:this.dropout,training:r,count:4,dropoutFunc:this.dropoutFunc})),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=ks({ones:()=>Zr(n),rate:this.recurrentDropout,training:r,count:4,dropoutFunc:this.dropoutFunc}));let s=this.dropoutMask,i=this.recurrentDropoutMask,o,l,p,u;0<this.dropout&&this.dropout<1&&(e=z(e,s[0]));let d=oa(e,this.kernel.read());0<this.recurrentDropout&&this.recurrentDropout<1&&(n=z(n,i[0])),d=J(d,oa(n,this.recurrentKernel.read())),this.useBias&&(d=qn(d,this.bias.read()));let[h,c,f,m]=Ar(d,4,d.rank-1);o=this.recurrentActivation.apply(h),l=this.recurrentActivation.apply(c),p=J(z(l,a),z(o,this.activation.apply(f))),u=this.recurrentActivation.apply(m);let g=z(u,this.activation.apply(p));return[g,g,p]})}getConfig(){let e=super.getConfig(),t={units:this.units,activation:vs(this.activation),recurrentActivation:vs(this.recurrentActivation),useBias:this.useBias,kernelInitializer:St(this.kernelInitializer),recurrentInitializer:St(this.recurrentInitializer),biasInitializer:St(this.biasInitializer),unitForgetBias:this.unitForgetBias,kernelRegularizer:dt(this.kernelRegularizer),recurrentRegularizer:dt(this.recurrentRegularizer),biasRegularizer:dt(this.biasRegularizer),activityRegularizer:dt(this.activityRegularizer),kernelConstraint:Ut(this.kernelConstraint),recurrentConstraint:Ut(this.recurrentConstraint),biasConstraint:Ut(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation};return Object.assign(Object.assign({},e),t)}};ih.className="LSTMCell";ne.registerClass(ih);var Bx=class extends Ba{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 ih(e),super(e)}call(e,t){return W(()=>{this.cell.dropoutMask!=null&&(Ce(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(Ce(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);let r=t==null?null:t.mask,n=t==null?null:t.training,a=t==null?null:t.initialState;return super.call(e,{mask:r,training:n,initialState:a})})}static fromConfig(e,t){return t.implmentation===0&&(t.implementation=1),new e(t)}};Bx.className="LSTM";ne.registerClass(Bx);var hm=class extends sh{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 W(()=>{e=e;let r=e.slice(1),n=[];for(let i of this.cells.slice().reverse())Array.isArray(i.stateSize)?n.push(r.splice(0,i.stateSize.length)):n.push(r.splice(0,1));n.reverse();let a=[],s;for(let i=0;i<this.cells.length;++i){let o=this.cells[i];r=n[i],i===0?s=[e[0]].concat(r):s=[s[0]].concat(r),s=o.call(s,t),a.push(s.slice(1))}r=[];for(let i of a.slice().reverse())r.push(...i);return[s[0]].concat(r)})}build(e){Ng(e)&&(e=e[0]),e=e;let t;this.cells.forEach((r,n)=>{si(`RNNCell_${n}`,()=>{r.build(e),Array.isArray(r.stateSize)?t=r.stateSize[0]:t=r.stateSize,e=[e[0],t]})}),this.built=!0}getConfig(){let e=super.getConfig(),t=n=>({className:n.getClassName(),config:n.getConfig()}),r={cells:this.cells.map(t)};return Object.assign(Object.assign({},e),r)}static fromConfig(e,t,r={}){let n=[];for(let a of t.cells)n.push(On(a,r));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 r of this.cells)t.push(...r.trainableWeights);return t.concat(e)}return e}getWeights(){let e=[];for(let t of this.cells)e.push(...t.weights);return _g(e)}setWeights(e){let t=[];for(let r of this.cells){let n=r.weights.length,a=e.splice(n);for(let s=0;s<r.weights.length;++s)t.push([r.weights[s],a[s]])}px(t)}};hm.className="StackedRNNCells";ne.registerClass(hm);function ks(e){let{ones:t,rate:r,training:n=!1,count:a=1,dropoutFunc:s}=e,i=()=>s!=null?s(t(),r):gN(t(),r),o=()=>rh(i,t,n);return!a||a<=1?Pt(o().clone()):Array(a).fill(void 0).map(o).map(l=>Pt(l.clone()))}var sH=function(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var a=0,n=Object.getOwnPropertySymbols(e);a<n.length;a++)t.indexOf(n[a])<0&&Object.prototype.propertyIsEnumerable.call(e,n[a])&&(r[n[a]]=e[n[a]]);return r},m2=class extends Ba{constructor(e){if(e.unroll)throw new Be("Unrolling is not possible with convolutional RNNs.");if(Array.isArray(e.cell))throw new Be("It is not possible at the moment to stack convolutional cells.");super(e),this.inputSpec=[new Rt({ndim:5})]}call(e,t){return W(()=>{if(this.cell.dropoutMask!=null&&(Ce(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(Ce(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null),t&&t.constants)throw new V("ConvRNN2D cell does not support constants");let r=t==null?null:t.mask,n=t==null?null:t.training,a=t==null?null:t.initialState;return super.call(e,{mask:r,training:n,initialState:a})})}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 W(()=>{let{stateSize:t}=this.cell,r=e.shape,n=this.computeSingleOutputShape(r),a=[n[0],...n.slice(2)],s=It(a);return Array.isArray(t)?Array(t.length).fill(s):[s]})}resetStates(e,t=!1){W(()=>{if(!this.stateful)throw new Ya("Cannot call resetStates() on an RNN Layer that is not stateful.");let r=this.inputSpec[0].shape,n=this.computeSingleOutputShape(r),a=[n[0],...n.slice(2)];if(r[0]==null)throw new V("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(()=>It(a)):this.states_=[It(a)];else if(e==null)Ce(this.states_),this.keptStates!=null&&(Ce(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(()=>It(a)):this.states_[0]=It(a);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new V(`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()):Ce(this.states_);for(let s=0;s<this.states_.length;++s){let i=e[s],o=a;if(!k.arraysEqual(i.shape,o))throw new V(`State ${s} is incompatible with layer ${this.name}: expected shape=${o}, received shape=${i.shape}`);this.states_[s]=i}}this.states_=this.states_.map(s=>Pt(s.clone()))})}computeSingleOutputShape(e){let{dataFormat:t,filters:r,kernelSize:n,padding:a,strides:s,dilationRate:i}=this.cell,o=t==="channelsFirst",l=e[o?3:2],p=e[o?4:3],u=Ln(l,n[0],a,s[0],i[0]),d=Ln(p,n[1],a,s[1],i[1]);return[...e.slice(0,2),...o?[r,u,d]:[u,d,r]]}};m2.className="ConvRNN2D";var cm=class extends ih{constructor(e){let{filters:t,kernelSize:r,strides:n,padding:a,dataFormat:s,dilationRate:i}=e;super(Object.assign(Object.assign({},e),{units:t})),this.filters=t,Zt(this.filters,"filters"),this.kernelSize=Sl(r,2,"kernelSize"),this.kernelSize.forEach(o=>Zt(o,"kernelSize")),this.strides=Sl(n||1,2,"strides"),this.strides.forEach(o=>Zt(o,"strides")),this.padding=a||"valid",gn(this.padding),this.dataFormat=s||"channelsLast",Ct(this.dataFormat),this.dilationRate=Sl(i||1,2,"dilationRate"),this.dilationRate.forEach(o=>Zt(o,"dilationRate"))}build(e){var t;e=Xe(e);let r=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[r]==null)throw new V(`The channel dimension of the input should be defined. Found ${e[r]}`);let n=e[r],a=4,s=this.kernelSize.concat([n,this.filters*a]);this.kernel=this.addWeight("kernel",s,null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint);let i=this.kernelSize.concat([this.filters,this.filters*a]);if(this.recurrentKernel=this.addWeight("recurrent_kernel",i,null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias){let o;if(this.unitForgetBias){let l=this.biasInitializer,p=this.filters;o=new(t=class extends Tn{apply(u,d){let h=l.apply([p]),c=$r([p]),f=l.apply([p*2]);return rx([h,c,f])}},t.className="CustomInit",t)}else o=this.biasInitializer;this.bias=this.addWeight("bias",[this.filters*a],null,o,this.biasRegularizer,!0,this.biasConstraint)}this.built=!0}call(e,t){return W(()=>{if(e.length!==3)throw new V(`ConvLSTM2DCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);let r=t.training||!1,n=e[0],a=e[1],s=e[2],i=4;0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=ks({ones:()=>Zr(n),rate:this.dropout,training:r,count:i,dropoutFunc:this.dropoutFunc}));let o=this.dropoutMask,l=(Z,ee,X)=>!ee||!ee[X]?Z:z(ee[X],Z),p=l(n,o,0),u=l(n,o,1),d=l(n,o,2),h=l(n,o,3);0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=ks({ones:()=>Zr(a),rate:this.recurrentDropout,training:r,count:i,dropoutFunc:this.dropoutFunc}));let c=this.recurrentDropoutMask,f=l(a,c,0),m=l(a,c,1),g=l(a,c,2),y=l(a,c,3),b=3,[x,v,w,N]=Ar(this.kernel.read(),i,b),[T,E,$,R]=this.useBias?Ar(this.bias.read(),i):[null,null,null,null];p=this.inputConv(p,x,T,this.padding),u=this.inputConv(u,v,E,this.padding),d=this.inputConv(d,w,$,this.padding),h=this.inputConv(h,N,R,this.padding);let[F,S,D,P]=Ar(this.recurrentKernel.read(),i,b);f=this.recurrentConv(f,F),m=this.recurrentConv(m,S),g=this.recurrentConv(g,D),y=this.recurrentConv(y,P);let U=this.recurrentActivation.apply(J(p,f)),H=this.recurrentActivation.apply(J(u,m)),q=J(z(H,s),z(U,this.activation.apply(J(d,g)))),G=z(this.recurrentActivation.apply(J(h,y)),this.activation.apply(q));return[G,G,q]})}getConfig(){let e=super.getConfig(),{units:t}=e,r=sH(e,["units"]),n={filters:this.filters,kernelSize:this.kernelSize,padding:this.padding,dataFormat:this.dataFormat,dilationRate:this.dilationRate,strides:this.strides};return Object.assign(Object.assign({},r),n)}inputConv(e,t,r,n){let a=br(e,t,this.strides,n||"valid",this.dataFormat==="channelsFirst"?"NCHW":"NHWC",this.dilationRate);return r?qn(a,r,this.dataFormat):a}recurrentConv(e,t){return br(e,t,1,"same",this.dataFormat==="channelsFirst"?"NCHW":"NHWC")}};cm.className="ConvLSTM2DCell";ne.registerClass(cm);var Wx=class extends m2{constructor(e){let t=new cm(e);super(Object.assign(Object.assign({},e),{cell:t}))}static fromConfig(e,t){return new e(t)}};Wx.className="ConvLSTM2D";ne.registerClass(Wx);var fm=class extends We{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,r=[];for(let n=0;n<this.noiseShape.length;++n)r.push(this.noiseShape[n]==null?t[n]:this.noiseShape[n]);return r}call(e,t){return W(()=>{this.invokeCallHook(e,t);let r=Te(e);if(0<this.rate&&this.rate<1){let n=t.training==null?!1:t.training,a=this.getNoiseShape(r);return rh(()=>gN(r,this.rate,a,this.seed),()=>r,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()}};fm.className="Dropout";ne.registerClass(fm);var Ux=class extends fm{constructor(e){super(e),this.inputSpec=[{ndim:3}]}getNoiseShape(e){let t=e.shape;return[t[0],1,t[2]]}};Ux.className="SpatialDropout1D";ne.registerClass(Ux);var Vx=class extends We{constructor(e){if(super(e),this.activation=null,this.useBias=!0,this.kernel=null,this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",e.batchInputShape==null&&e.inputShape==null&&e.inputDim!=null){let t=null;e.batchSize!=null&&(t=e.batchSize),this.batchInputShape=[t,e.inputDim]}this.units=e.units,Zt(this.units,"units"),this.activation=ws(e.activation),e.useBias!=null&&(this.useBias=e.useBias),this.kernelInitializer=xt(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.biasInitializer=xt(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelConstraint=Vt(e.kernelConstraint),this.biasConstraint=Vt(e.biasConstraint),this.kernelRegularizer=vt(e.kernelRegularizer),this.biasRegularizer=vt(e.biasRegularizer),this.activityRegularizer=vt(e.activityRegularizer),this.supportsMasking=!0,this.inputSpec=[{minNDim:2}]}build(e){e=Xe(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=Xe(e);let t=e.slice();return t[t.length-1]=this.units,t}call(e,t){return W(()=>{this.invokeCallHook(e,t);let r=Te(e),n=uN(this.activation.getClassName()),a;return n!=null?a=oa(r,this.kernel.read(),n,this.bias?this.bias.read():null):(a=oa(r,this.kernel.read()),this.bias!=null&&(a=qn(a,this.bias.read())),this.activation!=null&&(a=this.activation.apply(a))),a})}getConfig(){let e={units:this.units,activation:vs(this.activation),useBias:this.useBias,kernelInitializer:St(this.kernelInitializer),biasInitializer:St(this.biasInitializer),kernelRegularizer:dt(this.kernelRegularizer),biasRegularizer:dt(this.biasRegularizer),activityRegularizer:dt(this.activityRegularizer),kernelConstraint:Ut(this.kernelConstraint),biasConstraint:Ut(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}};Vx.className="Dense";ne.registerClass(Vx);var Gx=class extends We{constructor(e){e=e||{},super(e),this.inputSpec=[{minNDim:3}],this.dataFormat=e.dataFormat}computeOutputShape(e){e=Xe(e);for(let t of e.slice(1))if(t==null)throw new V(`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],ls(e,1)]}call(e,t){return W(()=>{this.invokeCallHook(e,t);let r=Te(e);if(this.dataFormat==="channelsFirst"&&r.rank>1){let n=[0];for(let a=2;a<r.rank;++a)n.push(a);n.push(1),r=Oe(r,n)}return yV(r)})}getConfig(){let e={};this.dataFormat!=null&&(e.dataFormat=this.dataFormat);let t=super.getConfig();return Object.assign(e,t),e}};Gx.className="Flatten";ne.registerClass(Gx);var Hx=class extends We{constructor(e){super(e),this.supportsMasking=!0,this.activation=ws(e.activation)}call(e,t){return W(()=>{this.invokeCallHook(e,t);let r=Te(e);return this.activation.apply(r)})}getConfig(){let e={activation:vs(this.activation)},t=super.getConfig();return Object.assign(e,t),e}};Hx.className="Activation";ne.registerClass(Hx);var jx=class extends We{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 W(()=>(e=Te(e),mV(e,this.n)))}getConfig(){let e={n:this.n},t=super.getConfig();return Object.assign(e,t),e}};jx.className="RepeatVector";ne.registerClass(jx);var qx=class extends We{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 r="Total size of new array must be unchanged.",n=t.slice(),a=1,s=null;for(let o=0;o<n.length;++o){let l=n[o];if(this.isUnknown(l))if(s===null)s=o;else throw new V("Can only specifiy one unknown dimension.");else a*=l}let i=ls(e);if(s!==null){if(a===0||i%a!==0)throw new V(r);n[s]=i/a}else if(i!==a)throw new V(r);return n}computeOutputShape(e){let t=!1;for(let r=0;r<e.length;++r)if(this.isUnknown(e[r])){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 W(()=>{this.invokeCallHook(e,t);let r=Te(e),n=r.shape,a=n.slice(0,1).concat(this.fixUnknownDimension(n.slice(1),this.targetShape));return B(r,a)})}getConfig(){let e={targetShape:this.targetShape},t=super.getConfig();return Object.assign(e,t),e}};qx.className="Reshape";ne.registerClass(qx);var Kx=class extends We{constructor(e){if(super(e),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=Bn(1,e.dims.length+1);if(!k.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 Rt({ndim:this.dims.length+1})]}computeOutputShape(e){e=Xe(e);let t=e.slice();return this.dims.forEach((r,n)=>{t[n+1]=e[r]}),t}call(e,t){return Oe(Te(e),this.dimsIncludingBatch)}getConfig(){let e={dims:this.dims},t=super.getConfig();return Object.assign(e,t),e}};Kx.className="Permute";ne.registerClass(Kx);var Xx=class extends We{constructor(e){super(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 r=Te(e);return Jp(bi(r,this.maskValue),-1)}call(e,t){return W(()=>{this.invokeCallHook(e,t);let r=Te(e),n=Jp(bi(r,this.maskValue),-1,!0);return z(r,se(n,r.dtype))})}};Xx.className="Masking";ne.registerClass(Xx);var Zx=class extends We{constructor(e){if(super(e),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(tt(e.inputLength))}this.inputDim=e.inputDim,Zt(this.inputDim,"inputDim"),this.outputDim=e.outputDim,Zt(this.outputDim,"outputDim"),this.embeddingsInitializer=xt(e.embeddingsInitializer||this.DEFAULT_EMBEDDINGS_INITIALIZER),this.embeddingsRegularizer=vt(e.embeddingsRegularizer),this.activityRegularizer=vt(e.activityRegularizer),this.embeddingsConstraint=Vt(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 W(()=>this.maskZero?(e=Te(e),bi(e,He(e))):null)}computeOutputShape(e){if(e=Xe(e),this.inputLength==null)return[...e,this.outputDim];let t=tt(this.inputLength);if(t.length!==e.length-1)throw new V(`"inputLength" is ${this.inputLength}, but received input shape has shape ${e}`);{let r=0;for(let n=0;n<t.length;++n){let a=t[n],s=e[n+1];if(a!=null&&s!=null&&a!==s)throw new V(`"inputLength" is ${this.inputLength}, but received input shape has shape ${e}`);a==null&&(t[r]=s),r++}}return[e[0],...t,this.outputDim]}call(e,t){return W(()=>{this.invokeCallHook(e,t);let r=Te(e);r.dtype!=="int32"&&(r=Fa(r,"int32"));let n=mN(this.embeddings.read(),B(r,[r.size]));return B(n,Xe(this.computeOutputShape(r.shape)))})}getConfig(){let e={inputDim:this.inputDim,outputDim:this.outputDim,embeddingsInitializer:St(this.embeddingsInitializer),embeddingsRegularizer:dt(this.embeddingsRegularizer),activityRegularizer:dt(this.activityRegularizer),embeddingsConstraint:Ut(this.embeddingsConstraint),maskZero:this.maskZero,inputLength:this.inputLength},t=super.getConfig();return Object.assign(e,t),e}};Zx.className="Embedding";ne.registerClass(Zx);var tl=class extends We{constructor(e){super(e||{}),this.supportsMasking=!0}mergeFunction(e){throw new Be}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 r=e.slice(0,e.length-t.length);for(let n=0;n<t.length;++n){let a=e[e.length-t.length+n],s=t[n];if(a==null||s==null||a<0||s<0)r.push(null);else if(a===1)r.push(s);else if(s===1)r.push(a);else{if(a!==s)throw new V("Operands could not be broadcast together with shapes "+JSON.stringify(e)+" "+JSON.stringify(t));r.push(a)}}return r}build(e){if(Array.isArray(e)&&!Array.isArray(e[0])&&(e=[Xe(e)]),e=e,e.length<2)throw new V(`A merge layer should be called on an Array of at least 2 inputs. Got ${e.length} input(s).`);let t=[];for(let a of e)a!=null&&a[0]!==null&&t.push(a[0]);if(t=os(t),t.length>1)throw new V(`Can not merge tensors with different batch sizes. Got tensors with shapes: ${JSON.stringify(e)}.`);let r=e[0]==null?null:e[0].slice(1);for(let a=1;a<e.length;++a){let s=e[a]==null?null:e[a].slice(1);r=this.computeElementwiseOpOutputShape(r,s)}let n=e.map(a=>a.length);e.indexOf(null)===-1&&os(n).length===1?this.reshapeRequired=!1:this.reshapeRequired=!0}call(e,t){return W(()=>{if(e=e,this.reshapeRequired){let r=[],n=e.map(a=>a.rank);if(n.indexOf(null)===-1){let a=xs(n);for(let s of e){let i=s.rank;for(let o=0;o<a-i;++o)s=eh(s,1);r.push(s)}return this.mergeFunction(r)}else{let a=!1;for(let o of e){let l=o.rank;if(l==null){let p=o.shape,u=p[0],d=p.slice(1).concat([u]),h=B(o,[u].concat(ls(p.slice(1))));h=Oe(h,[1,0]),h=B(h,d),r.push(h),a=!0}else if(l>1){let p=Bn(1,l).concat([0]);r.push(Oe(o,p)),a=!0}else r.push(o)}let s=this.mergeFunction(r),i=s.rank;if(a){if(i==null){let o=s.shape,l=o.length,p=o[l-1],u=[p].concat(o.slice(0,o.length-1));s=B(Oe(B(s,[-1,p]),[1,0]),u)}else if(i>1){let o=[i-1].concat(Bn(0,i-1));s=Oe(s,o)}}return s}}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 a=e[n]==null?null:e[n].slice(1);t=this.computeElementwiseOpOutputShape(t,a)}let r=[];for(let n of e)n!=null&&n[0]!==null&&r.push(n[0]);return r=os(r),r.length===1?t=r.concat(t):t=[null].concat(t),t}computeMask(e,t){return W(()=>{if(t==null)return null;if(!Array.isArray(t))throw new V("`mask` should be an Array");if(!Array.isArray(e))throw new V("`inputs` should be an Array");if(t.length!==e.length)throw new V(`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:Xt(n,0));let r=t[0];for(let n=1;n<t.length-1;++n)r=Nn(r,t[n]);return r})}},Jx=class extends tl{constructor(e){super(e)}mergeFunction(e){return W(()=>{let t=e[0].clone();for(let r=1;r<e.length;++r)t=J(t,e[r]);return t})}};Jx.className="Add";ne.registerClass(Jx);var Yx=class extends tl{constructor(e){super(e)}mergeFunction(e){return W(()=>{let t=e[0].clone();for(let r=1;r<e.length;++r)t=z(t,e[r]);return t})}};Yx.className="Multiply";ne.registerClass(Yx);var Qx=class extends tl{constructor(e){super(e)}mergeFunction(e){return W(()=>{let t=e[0].clone();for(let r=1;r<e.length;++r)t=J(t,e[r]);return z(1/e.length,t)})}};Qx.className="Average";ne.registerClass(Qx);var ev=class extends tl{constructor(e){super(e)}mergeFunction(e){return W(()=>{let t=e[0];for(let r=1;r<e.length;++r)t=ma(t,e[r]);return t})}};ev.className="Maximum";ne.registerClass(ev);var tv=class extends tl{constructor(e){super(e)}mergeFunction(e){return W(()=>{let t=e[0];for(let r=1;r<e.length;++r)t=ys(t,e[r]);return t})}};tv.className="Minimum";ne.registerClass(tv);var rv=class extends tl{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 V("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 r=[];for(let n=0;n<e.length;++n){let a=e[n].slice();a.splice(this.axis,1);let s=!1;for(let i of r)if(k.arraysEqual(i,a)){s=!0;break}s||r.push(a)}if(r.length>1)throw new V("A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got input shapes: "+JSON.stringify(e))}mergeFunction(e){return W(()=>rx(e,this.axis))}computeOutputShape(e){if(!(Array.isArray(e)&&Array.isArray(e[0])))throw new V("A `Concatenate` layer should be called on a list of inputs.");let t=e,r=t[0].slice(),n=this.axis<0?r.length+this.axis:this.axis;for(let a of t.slice(1)){if(r[n]==null||a[n]==null){r[n]=null;break}r[n]+=a[n]}return r}computeMask(e,t){if(t==null)return null;if(!Array.isArray(t))throw new V("`mask` should be an array for Concatenate");if(!Array.isArray(e))throw new V("`inputs` should be an array for Concatenate");if(t.length!==e.length)throw new V(`Mismatch in the length of mask (${t.length}) and the legnth of inputs (${e.length})`);return W(()=>{let r=!0;if(t.forEach(s=>{if(s!=null){r=!1;return}}),r)return null;let n=[];for(let s=0;s<e.length;++s)t[s]==null?n.push(se(Zr(e[s]),"bool")):t[s].rank<e[s].rank?n.push(Xt(t[s],-1)):n.push(t[s]);let a=lt(n,this.axis);return gf(a,-1,!1)})}getConfig(){let e={axis:this.axis},t=super.getConfig();return Object.assign(e,t),e}};rv.className="Concatenate";ne.registerClass(rv);function Ip(e,t){for(;e<0;)e+=t;return e}function iH(e,t,r){if(e.shape.length>3||t.shape.length>3)throw new Be("batchDot is not implemented for tensors of 4D or higher rank yet");if(k.assert(e.shape.length>=2,()=>`batchDot requires the rank of x to be >= 2, but got ${e.shape.length}`),k.assert(e.shape.length>=2,()=>`batchDot requires the rank of y to be >= 2, but got ${t.shape.length}`),typeof r=="number"&&(r=[r,r]),e.dtype==="complex64"||t.dtype==="complex64")throw new Be("batchDot is not implemented for complex64-type Tensors yet.");let n=e.shape.length,a=t.shape.length;r==null&&(r=[n-1,a-2]);let s=r;return W(()=>{let i;if(n>a){i=n-a;let l=[];for(let p=0;p<i;++p)l.push(1);t=B(t,t.shape.concat(l))}else if(a>n){i=a-n;let l=[];for(let p=0;p<i;++p)l.push(1);e=B(e,e.shape.concat(l))}else i=0;let o;if(e.shape.length===2&&t.shape.length===2)s[0]===s[1]?o=ge(z(e,t),s[0]):o=ge(z(Oe(e,[1,0]),t),s[1]);else{let l=s[0]!==e.shape.length-1,p=s[1]===t.shape.length-1;o=Me(e,t,l,p)}if(i>0){let l;n>a?l=n+a-3:l=n-1;let p=[];for(let u=l;u<l+i;++u)p.push(u);o=Ms(o,p)}return o.shape.length===1&&(o=Xt(o,1)),o})}var nv=class extends tl{constructor(e){super(e),this.axes=e.axes,this.normalize=e.normalize==null?!1:e.normalize,this.supportsMasking=!0,this.reshapeRequired=!1}build(e){k.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],r=e[1];if(t.length>3||r.length>3)throw new Be("Dot layer does not support tensors of 4D or higher rank yet.");let n=this.interpretAxes(t,r);if(t[n[0]]!==r[n[1]])throw new V(`Dimension incompatibility: ${t[n[0]]} !== ${r[n[1]]}`)}mergeFunction(e){if(e.length!==2)throw new V(`A \`Dot\` layer must be called on exactly 2 inputs, but received ${e.length} input(s).`);let t=e[0],r=e[1],n;return Array.isArray(this.axes)?n=this.axes.map((a,s)=>Ip(a,e[s].shape.length)):n=[Ip(this.axes,t.shape.length),Ip(this.axes,r.shape.length)],this.normalize&&(t=Nc(t,n[0]),r=Nc(r,n[1])),iH(t,r,n)}interpretAxes(e,t){let r;return Array.isArray(this.axes)?r=this.axes:r=[Ip(this.axes,e.length),Ip(this.axes,t.length)],r}computeOutputShape(e){k.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(),r=e[1].slice();if(t.length>3||r.length>3)throw new Be("Dot layer does not support tensors of 4D or higher rank yet.");let n=this.interpretAxes(t,r);t.splice(n[0],1),r.splice(n[1],1),r.splice(0,1);let a=t.concat(r);return a.length===1&&a.push(1),a}computeMask(e,t){return null}getConfig(){let e={axes:this.axes,normalize:this.normalize},t=super.getConfig();return Object.assign(e,t),e}};nv.className="Dot";ne.registerClass(nv);var av=class extends We{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 W(()=>{this.invokeCallHook(e,t);let r=Te(e);return rh(()=>J(Xf(r.shape,0,this.stddev),r),()=>r,t.training||!1)})}};av.className="GaussianNoise";ne.registerClass(av);var sv=class extends We{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 W(()=>{this.invokeCallHook(e,t);let r=Te(e);return this.rate>0&&this.rate<1?rh(()=>{let n=Math.sqrt(this.rate/(1-this.rate));return z(r,Xf(r.shape,1,n))},()=>r,t.training||!1):r})}};sv.className="GaussianDropout";ne.registerClass(sv);var iv=class extends We{constructor(e){super(e),this.supportsMasking=!0,this.rate=e.rate,this.noiseShape=e.noiseShape}_getNoiseShape(e){return this.noiseShape||Te(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 W(()=>{if(this.rate<1&&this.rate>0){let r=this._getNoiseShape(e);return rh(()=>{let n=Te(e),a=-1.6732632423543772*1.0507009873554805,s=La(Rs(r),this.rate);s=Fa(s,"float32");let i=((1-this.rate)*(1+this.rate*a**2))**-.5,o=-i*a*this.rate,l=J(z(n,s),z(J(s,-1),a));return J(z(l,i),o)},()=>Te(e),t.training||!1)}return e})}};iv.className="AlphaDropout";ne.registerClass(iv);function nd(e,t,r,n,a,s=.001){let i;if(e.rank===2)i=Ky(e,t,r,n,a,s);else if(e.rank===3)i=Xy(e,t,r,n,a,s);else if(e.rank===4)i=Zy(e,t,r,n,a,s);else throw new Be(`batchNormalization is not implemented for array of rank ${e.rank} yet`);return i}function oH(e,t,r,n,a=.001){return W(()=>{let s=jd(e,n),i=s.mean,o=s.variance;return[nd(e,i,o,r,t,a),i,o]})}function lH(e,t,r,n,a=.001){return W(()=>{let s=jd(e,n),i=s.mean,o=s.variance,l=[];for(let c of Bn(0,e.rank))n.indexOf(c)!==-1?l.push(1):l.push(e.shape[c]);let p=B(i,l),u=B(o,l),d=t==null?null:B(t,l),h=r==null?null:B(r,l);return[nd(e,p,u,h,d,a),i,o]})}function uH(e,t,r,n,a=.001){return k.arraysEqual(n.slice().sort(),Bn(0,e.rank-1))?oH(e,t,r,n,a):lH(e,t,r,n,a)}var ov=class extends We{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=xt(e.betaInitializer||"zeros"),this.gammaInitializer=xt(e.gammaInitializer||"ones"),this.movingMeanInitializer=xt(e.movingMeanInitializer||"zeros"),this.movingVarianceInitializer=xt(e.movingVarianceInitializer||"ones"),this.betaConstraint=Vt(e.betaConstraint),this.gammaConstraint=Vt(e.gammaConstraint),this.betaRegularizer=vt(e.betaRegularizer),this.gammaRegularizer=vt(e.gammaRegularizer)}build(e){e=Xe(e);let t=this.axis>=0?this.axis:this.axis+e.length,r=e[t];if(r==null)throw new V(`Axis ${t} of input tensor should have a defined dimension but the layer received an input with shape ${JSON.stringify(e)}.`);this.inputSpec=[new Rt({ndim:e.length,axes:{[t]:r}})];let n=[r];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 W(()=>{let r=t.training==null?!1:t.training,n=Te(e),a=n.shape,s=a.length,i=Bn(0,s),o=this.axis>=0?this.axis:this.axis+s;i.splice(o,1);let l=vi(1,s);l[o]=a[o];let p=i.slice();p.sort();let u=!k.arraysEqual(p,Bn(0,s).slice(0,s-1)),d=()=>{if(u){let g=B(this.movingMean.read(),l),y=B(this.movingVariance.read(),l),b=this.center?B(this.beta.read(),l):null,x=this.scale?B(this.gamma.read(),l):null;return nd(n,g,y,b,x,this.epsilon)}else return nd(n,this.movingMean.read(),this.movingVariance.read(),this.beta==null?null:this.beta.read(),this.gamma==null?null:this.gamma.read(),this.epsilon)};if(!r)return d();let[h,c,f]=uH(n,this.gamma.read(),this.beta.read(),i,this.epsilon),m=(g,y,b)=>{W(()=>{let x=1-b,v=g.read(),w=z(de(v,y),x);g.write(de(v,w))})};return m(this.movingMean,c,this.momentum),m(this.movingVariance,f,this.momentum),h})}getConfig(){let e={axis:this.axis,momentum:this.momentum,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:St(this.betaInitializer),gammaInitializer:St(this.gammaInitializer),movingMeanInitializer:St(this.movingMeanInitializer),movingVarianceInitializer:St(this.movingVarianceInitializer),betaRegularizer:dt(this.betaRegularizer),gammaRegularizer:dt(this.gammaRegularizer),betaConstraint:Ut(this.betaConstraint),gammaConstraint:Ut(this.gammaConstraint)},t=super.getConfig();return Object.assign(e,t),e}};ov.className="BatchNormalization";ne.registerClass(ov);var lv=class extends We{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=xt(e.betaInitializer||"zeros"),this.gammaInitializer=xt(e.gammaInitializer||"ones"),this.betaRegularizer=vt(e.betaRegularizer),this.gammaRegularizer=vt(e.gammaRegularizer),this.supportsMasking=!0}build(e){e=Xe(e);let t=e.length;typeof this.axis=="number"&&(this.axis=[this.axis]);for(let a=0;a<this.axis.length;++a)this.axis[a]<0&&(this.axis[a]+=t);for(let a of this.axis)if(a<0||a>=t)throw new Error(`Invalid axis: ${a}`);if(this.axis.length!==os(this.axis).length)throw new Error(`Found duplicate axes in: ${this.axis}`);let r=this.axis.map(a=>e[a]),n=!0;this.scale?this.gamma=this.addWeight("gamma",r,"float32",this.gammaInitializer,this.gammaRegularizer,n):this.gamma=null,this.center?this.beta=this.addWeight("beta",r,"float32",this.betaInitializer,this.betaRegularizer,n):this.beta=null,this.built=!0}call(e,t){let r=Te(e),n=r.shape,a=n.length;return W(()=>{let{mean:s,variance:i}=jd(r,this.axis,!0),o=vi(1,a);for(let c of this.axis)o[c]=n[c];let l=c=>c!=null&&c.shape.length!==a?B(c,o):c,p=this.scale?l(this.gamma.read()):null,u=this.center?l(this.beta.read()):null,d=[],h=[];for(let c=0;c<a;++c)this.axis.indexOf(c)!==-1?(d.push(n[c]),h.push(1)):(d.push(1),h.push(n[c]));return s=jr(s,d),i=jr(i,d),p!=null&&(p=jr(p,h)),u!=null&&(u=jr(u,h)),nd(r,s,i,u,p,this.epsilon)})}getConfig(){let e={axis:this.axis,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:St(this.betaInitializer),gammaInitializer:St(this.gammaInitializer),betaRegularizer:dt(this.betaRegularizer),gammaRegularizer:dt(this.gammaRegularizer)},t=super.getConfig();return Object.assign(e,t),e}};lv.className="LayerNormalization";ne.registerClass(lv);function pH(e,t,r){return W(()=>{if(e.rank!==4)throw new V(`temporalPadding expects input tensor to be 4-D, but received a ${e.rank}-D tensor.`);if(t==null&&(t=[[1,1],[1,1]]),t.length!==2||t[0].length!==2||t[1].length!==2)throw new V("spatial2dPadding expects `padding` to be an Array of two Arrays, each of which is an Array of two integers.");if(r==null&&(r=Wn()),r!=="channelsLast"&&r!=="channelsFirst")throw new V(`Unknown data format: ${r}. Supported data formats are 'channelsLast' and 'channelsFirst.`);let n;return r==="channelsFirst"?n=[[0,0],[0,0],t[0],t[1]]:n=[[0,0],t[0],t[1],[0,0]],jn(e,n)})}var uv=class extends We{constructor(e){if(e==null&&(e={}),super(e),this.dataFormat=e.dataFormat==null?Wn():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 V(`ZeroPadding2D expects padding to be a length-2 array, but received a length-${e.padding.length} array.`);let t,r;if(typeof e.padding[0]=="number")t=[e.padding[0],e.padding[0]],r=[e.padding[1],e.padding[1]];else{if(e.padding=e.padding,e.padding[0].length!==2)throw new V(`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 V(`ZeroPadding2D expects width padding to be a length-2 array, but received a length-${e.padding[1].length} array.`);r=e.padding[1]}this.padding=[t,r]}this.inputSpec=[new Rt({ndim:4})]}computeOutputShape(e){e=Xe(e);let t,r;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?r=e[3]+this.padding[1][0]+this.padding[1][1]:r=null,[e[0],e[1],t,r]):(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?r=e[2]+this.padding[1][0]+this.padding[1][1]:r=null,[e[0],t,r,e[3]])}call(e,t){return W(()=>pH(Te(e),this.padding,this.dataFormat))}getConfig(){let e={padding:this.padding,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}};uv.className="ZeroPadding2D";ne.registerClass(uv);function mm(e,t,r,n,a,s){return W(()=>{Ct(a),dN(s),gn(n),r==null&&(r=[1,1]),n==null&&(n="valid"),a==null&&(a=Wn()),s==null&&(s="max"),e=$x(e,a);let i,o=n==="same"?"same":"valid";return s==="max"?i=jt(e,t,r,o):i=Oa(e,t,r,o),a==="channelsFirst"&&(i=Oe(i,[0,3,1,2])),i})}function g2(e,t,r,n,a,s){return W(()=>{Ct(a),dN(s),gn(n),r==null&&(r=[1,1,1]),n==null&&(n="valid"),a==null&&(a=Wn()),s==null&&(s="max"),e=a2(e,a);let i,o=n==="same"?"same":"valid";return s==="max"?i=vb(e,t,r,o):i=qy(e,t,r,o),a==="channelsFirst"&&(i=Oe(i,[0,4,1,2,3])),i})}var y2=class extends We{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 V(`poolSize for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.poolSize)}`);if(Zt(this.poolSize,"poolSize"),e.strides==null)this.strides=this.poolSize;else if(typeof e.strides=="number")this.strides=[e.strides];else if(Array.isArray(e.strides)&&e.strides.length===1&&typeof e.strides[0]=="number")this.strides=e.strides;else throw new V(`strides for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.strides)}`);Zt(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,gn(this.padding),this.inputSpec=[new Rt({ndim:3})]}computeOutputShape(e){e=Xe(e);let t=Ln(e[1],this.poolSize[0],this.padding,this.strides[0]);return[e[0],t,e[2]]}call(e,t){return W(()=>{this.invokeCallHook(e,t),e=eh(Te(e),2);let r=this.poolingFunction(Te(e),[this.poolSize[0],1],[this.strides[0],1],this.padding,"channelsLast");return Ms(r,[2])})}getConfig(){let e={poolSize:this.poolSize,padding:this.padding,strides:this.strides},t=super.getConfig();return Object.assign(e,t),e}},pv=class extends y2{constructor(e){super(e)}poolingFunction(e,t,r,n,a){return Ct(a),gn(n),mm(e,t,r,n,a,"max")}};pv.className="MaxPooling1D";ne.registerClass(pv);var dv=class extends y2{constructor(e){super(e)}poolingFunction(e,t,r,n,a){return Ct(a),gn(n),mm(e,t,r,n,a,"avg")}};dv.className="AveragePooling1D";ne.registerClass(dv);var b2=class extends We{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 V(`If the strides property of a 2D pooling layer is an Array, it is expected to have a length of 2, but received length ${e.strides.length}.`);this.strides=e.strides}else this.strides=[e.strides,e.strides];Zt(this.poolSize,"poolSize"),Zt(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,Ct(this.dataFormat),gn(this.padding),this.inputSpec=[new Rt({ndim:4})]}computeOutputShape(e){e=Xe(e);let t=this.dataFormat==="channelsFirst"?e[2]:e[1],r=this.dataFormat==="channelsFirst"?e[3]:e[2];return t=Ln(t,this.poolSize[0],this.padding,this.strides[0]),r=Ln(r,this.poolSize[1],this.padding,this.strides[1]),this.dataFormat==="channelsFirst"?[e[0],e[1],t,r]:[e[0],t,r,e[3]]}call(e,t){return W(()=>(this.invokeCallHook(e,t),this.poolingFunction(Te(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}},hv=class extends b2{constructor(e){super(e)}poolingFunction(e,t,r,n,a){return Ct(a),gn(n),mm(e,t,r,n,a,"max")}};hv.className="MaxPooling2D";ne.registerClass(hv);var cv=class extends b2{constructor(e){super(e)}poolingFunction(e,t,r,n,a){return Ct(a),gn(n),mm(e,t,r,n,a,"avg")}};cv.className="AveragePooling2D";ne.registerClass(cv);var x2=class extends We{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 V(`If the strides property of a 3D pooling layer is an Array, it is expected to have a length of 3, but received length ${e.strides.length}.`);this.strides=e.strides}else this.strides=[e.strides,e.strides,e.strides];Zt(this.poolSize,"poolSize"),Zt(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,Ct(this.dataFormat),gn(this.padding),this.inputSpec=[new Rt({ndim:5})]}computeOutputShape(e){e=Xe(e);let t=this.dataFormat==="channelsFirst"?e[2]:e[1],r=this.dataFormat==="channelsFirst"?e[3]:e[2],n=this.dataFormat==="channelsFirst"?e[4]:e[3];return t=Ln(t,this.poolSize[0],this.padding,this.strides[0]),r=Ln(r,this.poolSize[1],this.padding,this.strides[1]),n=Ln(n,this.poolSize[2],this.padding,this.strides[2]),this.dataFormat==="channelsFirst"?[e[0],e[1],t,r,n]:[e[0],t,r,n,e[4]]}call(e,t){return W(()=>(this.invokeCallHook(e,t),this.poolingFunction(Te(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}},fv=class extends x2{constructor(e){super(e)}poolingFunction(e,t,r,n,a){return Ct(a),gn(n),g2(e,t,r,n,a,"max")}};fv.className="MaxPooling3D";ne.registerClass(fv);var mv=class extends x2{constructor(e){super(e)}poolingFunction(e,t,r,n,a){return Ct(a),gn(n),g2(e,t,r,n,a,"avg")}};mv.className="AveragePooling3D";ne.registerClass(mv);var v2=class extends We{constructor(e){super(e),this.inputSpec=[new Rt({ndim:3})]}computeOutputShape(e){return[e[0],e[2]]}call(e,t){throw new Be}},gv=class extends v2{constructor(e){super(e||{})}call(e,t){return W(()=>{let r=Te(e);return kt(r,1)})}};gv.className="GlobalAveragePooling1D";ne.registerClass(gv);var yv=class extends v2{constructor(e){super(e||{})}call(e,t){return W(()=>{let r=Te(e);return hn(r,1)})}};yv.className="GlobalMaxPooling1D";ne.registerClass(yv);var w2=class extends We{constructor(e){super(e),this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,Ct(this.dataFormat),this.inputSpec=[new Rt({ndim:4})]}computeOutputShape(e){return e=e,this.dataFormat==="channelsLast"?[e[0],e[3]]:[e[0],e[1]]}call(e,t){throw new Be}getConfig(){let e={dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}},bv=class extends w2{call(e,t){return W(()=>{let r=Te(e);return this.dataFormat==="channelsLast"?kt(r,[1,2]):kt(r,[2,3])})}};bv.className="GlobalAveragePooling2D";ne.registerClass(bv);var xv=class extends w2{call(e,t){return W(()=>{let r=Te(e);return this.dataFormat==="channelsLast"?hn(r,[1,2]):hn(r,[2,3])})}};xv.className="GlobalMaxPooling2D";ne.registerClass(xv);var k2=class extends We{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,r={}){let n=t.layer,a=On(n,r);delete t.layer;let s={layer:a};return Object.assign(s,t),new e(s)}},vv=class extends k2{constructor(e){super(e),this.supportsMasking=!0}build(e){if(e=Xe(e),e.length<3)throw new V(`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=Xe(e);let t=[e[0]].concat(e.slice(2)),r=this.layer.computeOutputShape(t),n=e[1];return[r[0],n].concat(r.slice(1))}call(e,t){return W(()=>(e=Te(e),c2((r,n)=>[Te(this.layer.call(r,t)),[]],e,[],!1,null,null,!1,!0)[1]))}};vv.className="TimeDistributed";ne.registerClass(vv);function dH(e){Qo(pV,"BidirectionalMergeMode",e)}var hH="concat",wv=class extends k2{constructor(e){super(e);let t=e.layer.getConfig(),r={};r.className=e.layer.getClassName(),r.config=t,this.forwardLayer=On(r),t.goBackwards=t.goBackwards!==!0;let n={};if(n.className=e.layer.getClassName(),n.config=t,this.backwardLayer=On(n),this.forwardLayer.name="forward_"+this.forwardLayer.name,this.backwardLayer.name="backward_"+this.backwardLayer.name,this.mergeMode=e.mergeMode===void 0?hH:e.mergeMode,dH(this.mergeMode),e.weights)throw new Be("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,r=Math.floor(t/2);this.forwardLayer.setWeights(e.slice(0,r)),this.backwardLayer.setWeights(e.slice(r))}computeOutputShape(e){let t=this.forwardLayer.computeOutputShape(e);Array.isArray(t)&&Array.isArray(t[0])||(t=[t]),t=t;let r,n,a;return this.returnState&&(a=t.slice(1)),r=t[0],r=r,this.mergeMode==="concat"?(r[r.length-1]*=2,n=[r]):this.mergeMode==null?n=[r,r.slice()]:n=[r],this.returnState?this.mergeMode==null?n.concat(a).concat(a.slice()):[r].concat(a).concat(a.slice()):Er(n)}apply(e,t){let r=t==null?null:t.initialState,n=t==null?null:t.constants;t==null&&(t={});let a=h2(e,r,n,this.numConstants);if(e=a.inputs,r=a.initialState,n=a.constants,Array.isArray(e)&&(r=e.slice(1),e=e[0]),(r==null||r.length===0)&&n==null)return super.apply(e,t);let s=[],i=[];if(r!=null){let l=r.length;if(l%2>0)throw new V("When passing `initialState` to a Bidrectional RNN, the state should be an Array containing the states of the underlying RNNs.");t.initialState=r,s.push(...r);let p=r.map(u=>new Rt({shape:u.shape}));this.forwardLayer.stateSpec=p.slice(0,l/2),this.backwardLayer.stateSpec=p.slice(l/2),i.push(...p)}if(n!=null)throw new Be("Support for constants in Bidirectional layers is not implemented yet.");let o=s[0]instanceof Un;for(let l of s)if(l instanceof Un!==o)throw new V("The initial state of a Bidirectional layer cannot be specified as a mix of symbolic and non-symbolic tensors");if(o){let l=[e].concat(s),p=this.inputSpec.concat(i),u=this.inputSpec;this.inputSpec=p;let d=super.apply(l,t);return this.inputSpec=u,d}else return super.apply(e,t)}call(e,t){return W(()=>{let r=t.initialState,n,a;if(r==null)n=this.forwardLayer.call(e,t),a=this.backwardLayer.call(e,t);else{let o=r.slice(0,r.length/2),l=r.slice(r.length/2);n=this.forwardLayer.call(e,Object.assign(t,{initialState:o})),a=this.backwardLayer.call(e,Object.assign(t,{initialState:l}))}let s;this.returnState&&(Array.isArray(n)&&(s=n.slice(1).concat(a.slice(1))),n=n[0],a=a[0]),this.returnSequences&&(a=mn(a,1));let i;return this.mergeMode==="concat"?i=rx([n,a]):this.mergeMode==="sum"?i=J(n,a):this.mergeMode==="ave"?i=z(.5,J(n,a)):this.mergeMode==="mul"?i=z(n,a):this.mergeMode==null&&(i=[n,a]),this.returnState?this.mergeMode==null?i.concat(s):[i].concat(s):i})}resetStates(e){this.forwardLayer.resetStates(),this.backwardLayer.resetStates()}build(e){si(this.forwardLayer.name,()=>{this.forwardLayer.build(e)}),si(this.backwardLayer.name,()=>{this.backwardLayer.build(e)}),this.built=!0}computeMask(e,t){Array.isArray(t)&&(t=t[0]);let r;if(this.returnSequences?this.mergeMode==null?r=[t,t]:r=t:this.mergeMode==null?r=[null,null]:r=null,this.returnState){let n=this.forwardLayer.states.map(a=>null);return Array.isArray(r)?r.concat(n).concat(n):[r].concat(n).concat(n)}else return r}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 r=On(t.layer);if(delete t.layer,t.numConstants!=null)throw new Be("Deserialization of a Bidirectional layer with numConstants present is not supported yet.");let n=t;return n.layer=r,new e(n)}};wv.className="Bidirectional";ne.registerClass(wv);var kv=class extends We{constructor(e){super(e),this.scale=e.scale,e.offset?this.offset=e.offset:this.offset=0}getConfig(){let e={scale:this.scale,offset:this.offset},t=super.getConfig();return Object.assign(e,t),e}call(e,t){return W(()=>(e=Te(e),e.dtype!=="float32"&&(e=Fa(e,"float32")),J(z(e,this.scale),this.offset)))}};kv.className="Rescaling";ne.registerClass(kv);var{resizeBilinear:cH,cropAndResize:fH}=sn,Iv=class extends We{constructor(e){super(e),this.height=e.height,this.width=e.width}centerCrop(e,t,r,n,a,s,i,o){return W(()=>{let l,p=!1,u=t/s,d=r/i,h=(n+t)/s,c=(a+r)/i,f=[u,d,h,c],m=[];e.rank===3?(p=!0,l=Mt([e])):l=e;for(let x=0;x<l.shape[0];x++)m.push(f);let g=yr(m,[m.length,4]),y=xi(0,m.length,1,"int32"),b=fH(l,g,y,[n,a],"nearest");return Fa(p?Te(Tt(b)):b,o)})}upsize(e,t,r,n){return W(()=>{let a=cH(e,[t,r]);return Fa(a,n)})}call(e,t){return W(()=>{let r=Te(e),n=r.dtype,a=r.shape,s=a[a.length-3],i=a[a.length-2],o=0;s!==this.height&&(o=Math.floor((s-this.height)/2));let l=0;return i!==this.width&&(l=Math.floor((i-this.width)/2),l===0&&(l=1)),o>=0&&l>=0?this.centerCrop(r,o,l,this.height,this.width,s,i,n):this.upsize(e,this.height,this.width,n)})}getConfig(){let e={height:this.height,width:this.width},t=super.getConfig();return Object.assign(e,t),e}computeOutputShape(e){e=Xe(e);let t=e.length-3,r=e.length-2;return e[t]=this.height,e[r]=this.width,e}};Iv.className="CenterCrop";ne.registerClass(Iv);function mH(e,t,r,n){let a=Te(e);if(a.dtype!=="int32"&&(a=Fa(a,"int32")),t==="int")return a;let s=a.shape;if(a.rank===0&&(a=Xt(a,-1)),t==="oneHot"&&a.shape[a.shape.length-1]!==1&&(a=Xt(a,-1)),a.rank>2)throw new V(`When outputMode is not int, maximum output rank is 2 Received outputMode ${t} and input shape ${s} which would result in output rank ${a.rank}.`);let i=["multiHot","oneHot"].includes(t),o=a,l;if(typeof n<"u"&&t==="count"?l=xc(o,n,r,i):l=xc(o,[],r,i),t!=="tfIdf")return l;if(n)return z(l,n);throw new V("When outputMode is 'tfIdf', weights must be provided.")}var Sv=class extends We{constructor(e){super(e),this.numTokens=e.numTokens,e.outputMode?this.outputMode=e.outputMode:this.outputMode="multiHot"}getConfig(){let e={numTokens:this.numTokens,outputMode:this.outputMode},t=super.getConfig();return Object.assign(e,t),e}computeOutputShape(e){return e=Xe(e),e==null?[this.numTokens]:this.outputMode==="oneHot"&&e[e.length-1]!==1?(e.push(this.numTokens),e):(e[e.length-1]=this.numTokens,e)}call(e,t){return W(()=>{e=Te(e),e.dtype!=="int32"&&(e=Fa(e,"int32"));let r;if(typeof t.countWeights<"u"){if(this.outputMode!=="count")throw new V(`countWeights is not used when outputMode !== count.
Received countWeights=${t.countWeights}`);r=Te(t.countWeights)}let n=hn(e),a=$l(e),s=Ir(this.numTokens,n).bufferSync().get(0),i=La(a,0).bufferSync().get(0);if(!(s&&i))throw new V(`Input values must be between 0 < values <= numTokens with numTokens=${this.numTokens}`);return mH(e,this.outputMode,this.numTokens,r)})}};Sv.className="CategoryEncoding";ne.registerClass(Sv);var gH=["bilinear","nearest"],K0=new Set(gH),Nv=class extends We{constructor(e){if(super(e),this.height=e.height,this.width=e.width,e.interpolation)if(K0.has(e.interpolation))this.interpolation=e.interpolation;else throw new V(`Invalid interpolation parameter: ${e.interpolation} is not implemented`);else this.interpolation="bilinear";this.cropToAspectRatio=!!e.cropToAspectRatio}computeOutputShape(e){e=Xe(e);let t=e[2];return[this.height,this.width,t]}getConfig(){let e={height:this.height,width:this.width,interpolation:this.interpolation,cropToAspectRatio:this.cropToAspectRatio},t=super.getConfig();return Object.assign(e,t),e}call(e,t){return W(()=>{let r=[this.height,this.width];if(this.interpolation==="bilinear")return sn.resizeBilinear(e,r,!this.cropToAspectRatio);if(this.interpolation==="nearest")return sn.resizeNearestNeighbor(e,r,!this.cropToAspectRatio);throw new Error(`Interpolation is ${this.interpolation} but only ${[...K0]} are supported`)})}};Nv.className="Resizing";ne.registerClass(Nv);var I2=class{constructor(e){this.seed=e}next(){if(this.seed!==void 0)return this.seed++}};I2.className="RandomSeed";var S2=class extends We{constructor(e){super(e),this.randomGenerator=new I2(e.seed)}getConfig(){let e={seed:this.randomGenerator.seed},t=super.getConfig();return Object.assign(e,t),e}};S2.className="BaseRandomLayer";var yH=["bilinear","nearest"],X0=new Set(yH),_v=class extends S2{constructor(e){super(e);let{factor:t,interpolation:r="bilinear"}=e;if(this.factor=t,Array.isArray(this.factor)&&this.factor.length===2)this.widthLower=this.factor[0],this.widthUpper=this.factor[1];else if(!Array.isArray(this.factor)&&this.factor>0)this.widthLower=-this.factor,this.widthUpper=this.factor;else throw new V(`Invalid factor: ${this.factor}. Must be positive number or tuple of 2 numbers`);if(this.widthLower<-1||this.widthUpper<-1)throw new V(`factor must have values larger than -1. Got: ${this.factor}`);if(this.widthUpper<this.widthLower)throw new V(`factor cannot have upper bound less than lower bound.
Got upper bound: ${this.widthUpper}.
Got lower bound: ${this.widthLower}
`);if(r)if(X0.has(r))this.interpolation=r;else throw new V(`Invalid interpolation parameter: ${r} is not implemented`)}getConfig(){let e={factor:this.factor,interpolation:this.interpolation},t=super.getConfig();return Object.assign(e,t),e}computeOutputShape(e){e=Xe(e);let t=e[2];return[this.imgHeight,-1,t]}call(e,t){return W(()=>{let r=Te(e);this.imgHeight=r.shape[r.shape.length-3];let n=r.shape[r.shape.length-2];this.widthFactor=Rs([1],1+this.widthLower,1+this.widthUpper,"float32",this.randomGenerator.next());let a=this.widthFactor.dataSync()[0]*n;a=Math.round(a);let s=[this.imgHeight,a];switch(this.interpolation){case"bilinear":return sn.resizeBilinear(e,s);case"nearest":return sn.resizeNearestNeighbor(e,s);default:throw new Error(`Interpolation is ${this.interpolation}
but only ${[...X0]} are supported`)}})}};_v.className="RandomWidth";ne.registerClass(_v);function bH(e){return new ap(e)}function xH(e){return new Tx(e)}function vH(e){return new Sx(e)}function wH(e){return new Nx(e)}function kH(e){return new _x(e)}function IH(e){return new Ex(e)}function SH(e){return new Cx(e)}function NH(e){return new Dx(e)}function _H(e){return new lm(e)}function TH(e){return new Ax(e)}function CH(e){return new um(e)}function EH(e){return new Fx(e)}function $H(e){return new Rx(e)}function AH(e){return new Mx(e)}function FH(e){return new Ox(e)}function RH(e){return new Lx(e)}function DH(e){return new Hx(e)}function MH(e){return new Vx(e)}function OH(e){return new fm(e)}function LH(e){return new Ux(e)}function zH(e){return new Gx(e)}function PH(e){return new jx(e)}function BH(e){return new qx(e)}function WH(e){return new Kx(e)}function UH(e){return new Zx(e)}function VH(e){return new Jx(e)}function GH(e){return new Qx(e)}function HH(e){return new rv(e)}function jH(e){return new ev(e)}function qH(e){return new tv(e)}function KH(e){return new Yx(e)}function XH(e){return new nv(e)}function ZH(e){return new ov(e)}function JH(e){return new lv(e)}function YH(e){return new uv(e)}function Tv(e){return new dv(e)}function QH(e){return Tv(e)}function e6(e){return Tv(e)}function Cv(e){return new cv(e)}function t6(e){return Cv(e)}function r6(e){return Cv(e)}function Ev(e){return new mv(e)}function n6(e){return Ev(e)}function a6(e){return Ev(e)}function s6(e){return new gv(e)}function i6(e){return new bv(e)}function N2(e){return new yv(e)}function _2(e){return new xv(e)}function T2(e){return new pv(e)}function C2(e){return new hv(e)}function o6(e){return new fv(e)}function l6(e){return new Px(e)}function u6(e){return new dm(e)}function p6(e){return new Bx(e)}function d6(e){return new ih(e)}function h6(e){return new zx(e)}function c6(e){return new pm(e)}function f6(e){return new Wx(e)}function m6(e){return new cm(e)}function g6(e){return new Ba(e)}function y6(e){return new hm(e)}function b6(e){return new wv(e)}function x6(e){return new vv(e)}var v6=N2,w6=_2,k6=T2,I6=C2;function S6(e){return new av(e)}function N6(e){return new sv(e)}function _6(e){return new iv(e)}function T6(e){return new Xx(e)}function C6(e){return new kv(e)}function E6(e){return new Iv(e)}function $6(e){return new Nv(e)}function A6(e){return new Sv(e)}function F6(e){return new _v(e)}var E2={};Ee(E2,{MAPE:()=>V6,MSE:()=>j6,binaryAccuracy:()=>R6,binaryCrossentropy:()=>D6,categoricalAccuracy:()=>O6,categoricalCrossentropy:()=>L6,cosineProximity:()=>B6,mape:()=>G6,meanAbsoluteError:()=>W6,meanAbsolutePercentageError:()=>U6,meanSquaredError:()=>H6,mse:()=>q6,precision:()=>z6,r2Score:()=>K6,recall:()=>P6,sparseCategoricalAccuracy:()=>M6});function R6(e,t){return bx(e,t)}function D6(e,t){return FN(e,t)}function M6(e,t){return RN(e,t)}function O6(e,t){return xx(e,t)}function L6(e,t){return vx(e,t)}function z6(e,t){return AN(e,t)}function P6(e,t){return gG(e,t)}function B6(e,t){return yx(e,t)}function W6(e,t){return am(e,t)}function U6(e,t){return sp(e,t)}function V6(e,t){return sp(e,t)}function G6(e,t){return sp(e,t)}function H6(e,t){return el(e,t)}function j6(e,t){return el(e,t)}function q6(e,t){return el(e,t)}function K6(e,t){return yG(e,t)}var $2={};Ee($2,{modelFromJSON:()=>qG});var A2={};Ee(A2,{l1:()=>Z6,l1l2:()=>X6,l2:()=>J6});function X6(e){return new ah(e)}function Z6(e){return eH(e)}function J6(e){return tH(e)}var F2=class extends zl{constructor(){super(...arguments),this.model=null}setModel(e){if(!(e instanceof Ca))throw new Error("model must be a LayersModel, not some other Container");this.model=e}};function Oh(e,t){return e<t}function Z0(e,t){return e>t}var R2=class extends F2{constructor(e){if(super(),e==null&&(e={}),e.restoreBestWeights)throw new Be("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=Oh:this.mode==="max"?this.monitorFunc=Z0:this.monitor.indexOf("acc")!==-1?this.monitorFunc=Z0:this.monitorFunc=Oh,this.monitorFunc===Oh&&(this.minDelta*=-1)}async onTrainBegin(e){this.wait=0,this.stoppedEpoch=0,this.baseline!=null?this.best=this.baseline:this.best=this.monitorFunc===Oh?1/0:-1/0}async onEpochEnd(e,t){await Ka(t);let r=this.getMonitorValue(t);r!=null&&(this.monitorFunc(r-this.minDelta,this.best)?(this.best=r,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 Y6(e){return new R2(e)}var Q6={earlyStopping:Y6},ej=j();ej.registerFlag("KEEP_INTERMEDIATE_TENSORS",()=>!1,e=>{e&&console.warn("Keep intermediate tensors is ON. This will print the values of all intermediate tensors during model inference. Not all models support this mode. For details, check e2e/benchmarks/ model_config.js. This significantly impacts performance.")});var Wr;(function(e){e[e.DT_INVALID=0]="DT_INVALID",e[e.DT_FLOAT=1]="DT_FLOAT",e[e.DT_DOUBLE=2]="DT_DOUBLE",e[e.DT_INT32=3]="DT_INT32",e[e.DT_UINT8=4]="DT_UINT8",e[e.DT_INT16=5]="DT_INT16",e[e.DT_INT8=6]="DT_INT8",e[e.DT_STRING=7]="DT_STRING",e[e.DT_COMPLEX64=8]="DT_COMPLEX64",e[e.DT_INT64=9]="DT_INT64",e[e.DT_BOOL=10]="DT_BOOL",e[e.DT_QINT8=11]="DT_QINT8",e[e.DT_QUINT8=12]="DT_QUINT8",e[e.DT_QINT32=13]="DT_QINT32",e[e.DT_BFLOAT16=14]="DT_BFLOAT16",e[e.DT_QINT16=15]="DT_QINT16",e[e.DT_QUINT16=16]="DT_QUINT16",e[e.DT_UINT16=17]="DT_UINT16",e[e.DT_COMPLEX128=18]="DT_COMPLEX128",e[e.DT_HALF=19]="DT_HALF",e[e.DT_RESOURCE=20]="DT_RESOURCE",e[e.DT_VARIANT=21]="DT_VARIANT",e[e.DT_UINT32=22]="DT_UINT32",e[e.DT_UINT64=23]="DT_UINT64",e[e.DT_FLOAT_REF=101]="DT_FLOAT_REF",e[e.DT_DOUBLE_REF=102]="DT_DOUBLE_REF",e[e.DT_INT32_REF=103]="DT_INT32_REF",e[e.DT_UINT8_REF=104]="DT_UINT8_REF",e[e.DT_INT16_REF=105]="DT_INT16_REF",e[e.DT_INT8_REF=106]="DT_INT8_REF",e[e.DT_STRING_REF=107]="DT_STRING_REF",e[e.DT_COMPLEX64_REF=108]="DT_COMPLEX64_REF",e[e.DT_INT64_REF=109]="DT_INT64_REF",e[e.DT_BOOL_REF=110]="DT_BOOL_REF",e[e.DT_QINT8_REF=111]="DT_QINT8_REF",e[e.DT_QUINT8_REF=112]="DT_QUINT8_REF",e[e.DT_QINT32_REF=113]="DT_QINT32_REF",e[e.DT_BFLOAT16_REF=114]="DT_BFLOAT16_REF",e[e.DT_QINT16_REF=115]="DT_QINT16_REF",e[e.DT_QUINT16_REF=116]="DT_QUINT16_REF",e[e.DT_UINT16_REF=117]="DT_UINT16_REF",e[e.DT_COMPLEX128_REF=118]="DT_COMPLEX128_REF",e[e.DT_HALF_REF=119]="DT_HALF_REF",e[e.DT_RESOURCE_REF=120]="DT_RESOURCE_REF",e[e.DT_VARIANT_REF=121]="DT_VARIANT_REF",e[e.DT_UINT32_REF=122]="DT_UINT32_REF",e[e.DT_UINT64_REF=123]="DT_UINT64_REF"})(Wr||(Wr={}));var J0;(function(e){(function(t){t[t.LEGACY=0]="LEGACY",t[t.V1=1]="V1",t[t.V2=2]="V2"})(e.CheckpointFormatVersion||(e.CheckpointFormatVersion={}))})(J0||(J0={}));var $v={};function tj(e,t){let r={tfOpName:e,category:"custom",inputs:[],attrs:[],customExecutor:t};$v[e]=r}function D2(e){return $v[e]}function rj(e){delete $v[e]}function I(e,t,r,n,a){let s=t.inputParams[e];if(s&&s.inputIndexStart!==void 0){let o=s.inputIndexStart,l=s.inputIndexEnd===0?void 0:s.inputIndexEnd===void 0?o+1:s.inputIndexEnd,p=o<0?t.inputNames.length+o:o;if(s.type==="tensor")return ar(t.inputNames[p],r,n,a);if(s.type==="tensors"){let h=t.inputs.slice(o,l);return t.inputNames.slice(o,l).filter((c,f)=>{var m;return((m=h[f])===null||m===void 0?void 0:m.op)!=="NoOp"}).map(c=>ar(c,r,n,a))}let u=ar(t.inputNames[p],r,n,a),d=u.dataSync();return s.type==="number"?d[0]:k.toNestedArray(u.shape,d)}let i=t.attrParams[e];return i&&i.value}function ar(e,t,r,n){let[a,s]=Vr(e,r);if(n!=null){let o=n.getHashTableHandleByName(a);if(o!=null)return o}let i=r.currentContextIds.find(o=>!!t[$c(a,o)]);return i!==void 0?t[$c(a,i)][s]:void 0}function Y0(e,t,r){return t[$c(e,r.currentContextId)]}function Ia(e,t){let[r,n,a]=Vr(e,t);return[$c(r,t&&t.currentContextId),n,a]}function $c(e,t){return t?`${e}-${t}`:e}function Vr(e,t){if(e==="")return["",0,void 0];let r=t!=null&&t.parseNodeNameCache!=null;if(r){let s=t.parseNodeNameCache.get(e);if(s!=null)return s}let n=e.split(":"),a;if(n.length===1)a=[e,0,void 0];else{let s=n[0],i=n.length===3?n[1]:void 0,o=Number(n[n.length-1]);a=[s,o,i]}return r&&t.parseNodeNameCache.set(e,a),a}function Jh(e,t,r){let n=I("pad",e,t,r);if(n==="explicit"){n=I("explicitPaddings",e,t,r);let a=[[0,0],[0,0],[0,0],[0,0]];for(let s=0;s<4;s++)a[s][0]=n[s*2],a[s][1]=n[s*2+1];return a}return n}function Sa(e){return e.kept?e:sa(e)}var M2={};Ee(M2,{json:()=>nj});var nj=[{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}]}],O2={};Ee(O2,{json:()=>aj});var aj=[{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:"LeakyRelu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"alpha",name:"alpha",type:"number",defaultValue:.2},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"IsNan",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"IsFinite",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"IsInf",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}],L2={};Ee(L2,{json:()=>sj});var sj=[{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:"TensorListConcatV2",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"}]},{tfOpName:"TensorListLength",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"}]},{tfOpName:"TensorListResize",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"size",type:"number"}]}],z2={};Ee(z2,{json:()=>ij});var ij=[{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",defaultValue:.2}]},{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"}]}],P2={};Ee(P2,{json:()=>oj});var oj=[{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"}]},{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:"RandomStandardNormal",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"seed",name:"seed",type:"number",defaultValue:0},{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:"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:"RandomUniformInt",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"minval",name:"minval",type:"number"},{tfName:"maxval",name:"maxval",type:"number"},{tfName:"seed",name:"seed",type:"number",defaultValue:0},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,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"}]}],B2={};Ee(B2,{json:()=>lj});var lj=[{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}]}],W2={};Ee(W2,{json:()=>uj});var uj=[{tfOpName:"LowerBound",category:"evaluation",inputs:[{start:0,name:"sortedSequence",type:"tensor"},{start:1,name:"values",type:"tensor"}]},{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:"UpperBound",category:"evaluation",inputs:[{start:0,name:"sortedSequence",type:"tensor"},{start:1,name:"values",type:"tensor"}]},{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"}]}],U2={};Ee(U2,{json:()=>pj});var pj=[{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"}]}],V2={};Ee(V2,{json:()=>dj});var dj=[{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"}]},{tfOpName:"InitializeTable",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"values",type:"tensor"}]},{tfOpName:"InitializeTableV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"values",type:"tensor"}]}],G2={};Ee(G2,{json:()=>hj});var hj=[{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"}]},{tfOpName:"ImageProjectiveTransformV3",category:"image",inputs:[{start:0,name:"images",type:"tensor"},{start:1,name:"transforms",type:"tensor"},{start:2,name:"outputShape",type:"number[]"},{start:3,name:"fillValue",type:"number"}],attrs:[{tfName:"interpolation",name:"interpolation",type:"string"},{tfName:"fill_mode",name:"fillMode",type:"string"}]}],H2={};Ee(H2,{json:()=>cj});var cj=[{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}]},{tfOpName:"BitwiseAnd",category:"logical",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"y",type:"tensor"}]}],j2={};Ee(j2,{json:()=>fj});var fj=[{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:"leakyrelu_alpha",name:"leakyreluAlpha",type:"number",defaultValue:.2},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"transpose_a",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"transpose_b",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"BatchMatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"adj_x",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"adj_y",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"BatchMatMulV2",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"adj_x",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"adj_y",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Transpose",category:"matrices",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"perm",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Einsum",category:"matrices",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}],attrs:[{tfName:"equation",name:"equation",type:"string"},{tfName:"N",name:"n",type:"number",defaultValue:2},{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"MatrixBandPart",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"numLower",type:"tensor"},{start:1,name:"numUpper",type:"tensor"}]}],q2={};Ee(q2,{json:()=>mj});var mj=[{tfOpName:"EuclideanNorm",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool",defaultValue:!1}]},{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"}]}],K2={};Ee(K2,{json:()=>gj});var gj=[{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"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Cumprod",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"}]},{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"}]}],X2={};Ee(X2,{json:()=>yj});var yj=[{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}]},{tfOpName:"TensorScatterUpdate",category:"slice_join",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"values",type:"tensor"}]}],Z2={};Ee(Z2,{json:()=>bj});var bj=[{tfOpName:"SparseFillEmptyRows",category:"sparse",inputs:[{start:0,name:"indices",type:"tensor"},{start:1,name:"values",type:"tensor"},{start:2,name:"denseShape",type:"tensor"},{start:3,name:"defaultValue",type:"tensor"}]},{tfOpName:"SparseReshape",category:"sparse",inputs:[{start:0,name:"inputIndices",type:"tensor"},{start:1,name:"inputShape",type:"tensor"},{start:2,name:"newShape",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"SparseSegmentMean",category:"sparse",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"segmentIds",type:"tensor"}]},{tfOpName:"SparseSegmentSum",category:"sparse",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"segmentIds",type:"tensor"}]}],J2={};Ee(J2,{json:()=>xj});var xj=[{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}]}],Y2={};Ee(Y2,{json:()=>vj});var vj=[{tfOpName:"StaticRegexReplace",category:"string",inputs:[{start:0,name:"input",type:"tensor"}],attrs:[{tfName:"pattern",name:"pattern",type:"string"},{tfName:"rewrite",name:"rewrite",type:"string"},{tfName:"replace_global",name:"replaceGlobal",type:"bool"}]},{tfOpName:"StringNGrams",category:"string",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"dataSplits",type:"tensor"}],attrs:[{tfName:"separator",name:"separator",type:"string"},{tfName:"ngram_widths",name:"nGramWidths",type:"number[]"},{tfName:"left_pad",name:"leftPad",type:"string"},{tfName:"right_pad",name:"rightPad",type:"string"},{tfName:"pad_width",name:"padWidth",type:"number"},{tfName:"preserve_short_sequences",name:"preserveShortSequences",type:"bool"}],outputs:["ngrams","ngrams_splits"]},{tfOpName:"StringSplit",category:"string",inputs:[{start:0,name:"input",type:"tensor"},{start:1,name:"delimiter",type:"tensor"}],attrs:[{tfName:"skip_empty",name:"skipEmpty",type:"bool"}],outputs:["indices","values","shape"]},{tfOpName:"StringToHashBucketFast",category:"string",inputs:[{start:0,name:"input",type:"tensor"}],attrs:[{tfName:"num_buckets",name:"numBuckets",type:"number"}]}],Q2={};Ee(Q2,{json:()=>wj});var wj=[{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:"EnsureShape",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:[]},{tfOpName:"BroadcastArgs",category:"transformation",inputs:[{start:0,name:"s0",type:"tensor"},{start:1,name:"s1",type:"tensor"}],attrs:[]}],Q0=class{static get Instance(){return this._instance||(this._instance=new this)}constructor(){let e=[M2,O2,L2,z2,P2,B2,W2,U2,V2,G2,H2,j2,q2,K2,X2,Z2,J2,Y2,Q2],t=[].concat(...e.map(r=>r.json));this.opMappers=t.reduce((r,n)=>(r[n.tfOpName]=n,r),{})}transformGraph(e,t={}){let r=e.node,n=[],a=[],s=[],i=r.reduce((f,m)=>(f[m.name]=this.mapNode(m),m.op.startsWith("Placeholder")?n.push(f[m.name]):m.op==="Const"?a.push(f[m.name]):(m.input==null||m.input.length===0)&&s.push(f[m.name]),f),{}),o=[],l=[],p={},u={};t!=null&&(p=this.mapSignatureEntries(t.inputs),u=this.mapSignatureEntries(t.outputs));let d=Object.keys(i);d.forEach(f=>{let m=i[f];m.inputNames.forEach((g,y)=>{let[b,,x]=Ia(g),v=i[b];if(v.outputs!=null){let w=v.outputs.indexOf(x);if(w!==-1){let N=`${b}:${w}`;m.inputNames[y]=N}}m.inputs.push(v),v.children.push(m)})}),Object.keys(u).length===0?d.forEach(f=>{let m=i[f];m.children.length===0&&l.push(m)}):Object.keys(u).forEach(f=>{let[m]=Ia(f),g=i[m];g!=null&&(g.signatureKey=u[f],l.push(g))}),Object.keys(p).length>0?Object.keys(p).forEach(f=>{let[m]=Ia(f),g=i[m];g&&(g.signatureKey=p[f],o.push(g))}):o=n;let h={};e.library!=null&&e.library.function!=null&&(h=e.library.function.reduce((f,m)=>(f[m.signature.name]=this.mapFunction(m),f),{}));let c={nodes:i,inputs:o,outputs:l,weights:a,placeholders:n,signature:t,functions:h};return s.length>0&&(c.initNodes=s),c}mapSignatureEntries(e){return Object.keys(e||{}).reduce((t,r)=>(t[e[r].name]=r,t),{})}mapNode(e){let t=D2(e.op)||this.opMappers[e.op]||{};e.attr==null&&(e.attr={});let r={name:e.name,op:e.op,category:t.category,inputNames:(e.input||[]).map(n=>n.startsWith("^")?n.slice(1):n),inputs:[],children:[],inputParams:{},attrParams:{},rawAttrs:e.attr,outputs:t.outputs};return t.inputs!=null&&(r.inputParams=t.inputs.reduce((n,a)=>(n[a.name]={type:a.type,inputIndexStart:a.start,inputIndexEnd:a.end},n),{})),t.attrs!=null&&(r.attrParams=t.attrs.reduce((n,a)=>{let s=a.type,i;switch(a.type){case"string":i=Fg(e.attr,a.tfName,a.defaultValue),i===void 0&&a.tfDeprecatedName&&(i=Fg(e.attr,a.tfDeprecatedName,a.defaultValue));break;case"string[]":i=Pg(e.attr,a.tfName,a.defaultValue),i===void 0&&a.tfDeprecatedName&&(i=Pg(e.attr,a.tfDeprecatedName,a.defaultValue));break;case"number":i=Dg(e.attr,a.tfName,a.defaultValue||0),i===void 0&&a.tfDeprecatedName&&(i=Dg(e.attr,a.tfDeprecatedName,a.defaultValue));break;case"number[]":i=zg(e.attr,a.tfName,a.defaultValue),i===void 0&&a.tfDeprecatedName&&(i=zg(e.attr,a.tfDeprecatedName,a.defaultValue));break;case"bool":i=Rg(e.attr,a.tfName,a.defaultValue),i===void 0&&a.tfDeprecatedName&&(i=Rg(e.attr,a.tfDeprecatedName,a.defaultValue));break;case"bool[]":i=Wg(e.attr,a.tfName,a.defaultValue),i===void 0&&a.tfDeprecatedName&&(i=Wg(e.attr,a.tfDeprecatedName,a.defaultValue));break;case"shape":i=Lg(e.attr,a.tfName,a.defaultValue),i===void 0&&a.tfDeprecatedName&&(i=Lg(e.attr,a.tfDeprecatedName,a.defaultValue));break;case"shape[]":i=Bg(e.attr,a.tfName,a.defaultValue),i===void 0&&a.tfDeprecatedName&&(i=Bg(e.attr,a.tfDeprecatedName,a.defaultValue));break;case"dtype":i=Mg(e.attr,a.tfName,a.defaultValue),i===void 0&&a.tfDeprecatedName&&(i=Mg(e.attr,a.tfDeprecatedName,a.defaultValue));break;case"dtype[]":i=Og(e.attr,a.tfName,a.defaultValue),i===void 0&&a.tfDeprecatedName&&(i=Og(e.attr,a.tfDeprecatedName,a.defaultValue));break;case"func":i=e1(e.attr,a.tfName,a.defaultValue),i===void 0&&a.tfDeprecatedName&&(i=e1(e.attr,a.tfDeprecatedName,a.defaultValue));break;case"tensor":case"tensors":break;default:throw new Error(`Unsupported param type: ${a.type} for op: ${e.op}`)}return n[a.name]={value:i,type:s},n},{})),r}mapFunction(e){let t=e.nodeDef,r=[],n=[],a={};t!=null&&(a=t.reduce((p,u)=>(p[u.name]=this.mapNode(u),u.op==="Const"&&n.push(p[u.name]),p),{}));let s=[],i=[];e.signature.inputArg.forEach(p=>{let[u]=Ia(p.name),d={name:u,op:"Placeholder",inputs:[],inputNames:[],category:"graph",inputParams:{},attrParams:{dtype:{value:Av(p.type),type:"dtype"}},children:[]};d.signatureKey=p.name,s.push(d),a[u]=d}),Object.keys(a).forEach(p=>{let u=a[p];u.inputNames.forEach((d,h)=>{let[c,,f]=Ia(d),m=a[c];if(m.outputs!=null){let g=m.outputs.indexOf(f);if(g!==-1){let y=`${c}:${g}`;u.inputNames[h]=y}}u.inputs.push(m),m.children.push(u)})});let o=e.ret;e.signature.outputArg.forEach(p=>{let[u,d]=Ia(o[p.name]),h=a[u];h!=null&&(h.defaultOutput=d,i.push(h))});let l=this.mapArgsToSignature(e);return{nodes:a,inputs:s,outputs:i,weights:n,placeholders:r,signature:l}}mapArgsToSignature(e){return{methodName:e.signature.name,inputs:e.signature.inputArg.reduce((t,r)=>(t[r.name]=this.mapArgToTensorInfo(r),t),{}),outputs:e.signature.outputArg.reduce((t,r)=>(t[r.name]=this.mapArgToTensorInfo(r,e.ret),t),{})}}mapArgToTensorInfo(e,t){let r=e.name;return t!=null&&(r=t[r]),{name:r,dtype:e.type}}};function kj(e){let t=j().global;if(typeof t.atob<"u")return t.atob(e);if(typeof Buffer<"u")return new Buffer(e,"base64").toString();throw new Error("Unable to decode base64 in this environment. Missing built-in atob() or Buffer()")}function e_(e,t){let r=Array.isArray(e)?String.fromCharCode.apply(null,e):kj(e);return t?r:r.toLowerCase()}function Fg(e,t,r,n=!1){let a=e[t];return a!=null?e_(a.s,n):r}function Rg(e,t,r){let n=e[t];return n?n.b:r}function Dg(e,t,r){let n=e[t]||{},a=n.i!=null?n.i:n.f!=null?n.f:r;return typeof a=="number"?a:parseInt(a,10)}function Av(e){switch(typeof e=="string"&&(e=Wr[e]),e){case Wr.DT_FLOAT:case Wr.DT_HALF:return"float32";case Wr.DT_INT32:case Wr.DT_INT64:case Wr.DT_INT8:case Wr.DT_UINT8:return"int32";case Wr.DT_BOOL:return"bool";case Wr.DT_DOUBLE:return"float32";case Wr.DT_STRING:return"string";case Wr.DT_COMPLEX64:case Wr.DT_COMPLEX128:return"complex64";default:return null}}function e1(e,t,r){let n=e[t];return n&&n.func?n.func.name:r}function Mg(e,t,r){let n=e[t];return n&&n.type?Av(n.type):r}function Og(e,t,r){let n=e[t];return n&&n.list&&n.list.type?n.list.type.map(a=>Av(a)):r}function t_(e){if(!e.unknownRank)return e.dim!=null?e.dim.map(t=>typeof t.size=="number"?t.size:parseInt(t.size,10)):[]}function Lg(e,t,r){let n=e[t];return n&&n.shape?t_(n.shape):r}function zg(e,t,r){let n=e[t];return n?((n.list.f&&n.list.f.length?n.list.f:n.list.i)||[]).map(a=>typeof a=="number"?a:parseInt(a,10)):r}function Pg(e,t,r,n=!1){let a=e[t];return a&&a.list&&a.list.s?a.list.s.map(s=>e_(s,n)):r}function Bg(e,t,r){let n=e[t];return n&&n.list&&n.list.shape?n.list.shape.map(a=>t_(a)):r}function Wg(e,t,r){let n=e[t];return n&&n.list&&n.list.b?n.list.b:r}var Ij=class{constructor(e,t,r){this.node=e,this.tensorMap=t,this.context=r,this.inputs=[],this.attrs={},this.inputs=e.inputNames.map(n=>this.getInput(n)),e.rawAttrs!=null&&(this.attrs=Object.keys(e.rawAttrs).reduce((n,a)=>(n[a]=this.getAttr(a),n),{}))}getInput(e){return ar(e,this.tensorMap,this.context)}getAttr(e,t){let r=this.node.rawAttrs[e];if(r.tensor!=null)return ar(e,this.tensorMap,this.context);if(r.i!=null||r.f!=null)return Dg(this.node.rawAttrs,e,t);if(r.s!=null)return Fg(this.node.rawAttrs,e,t);if(r.b!=null)return Rg(this.node.rawAttrs,e,t);if(r.shape!=null)return Lg(this.node.rawAttrs,e,t);if(r.type!=null)return Mg(this.node.rawAttrs,e,t);if(r.list!=null){if(r.list.i!=null||r.list.f!=null)return zg(this.node.rawAttrs,e,t);if(r.list.s!=null)return Pg(this.node.rawAttrs,e,t);if(r.list.shape!=null)return Bg(this.node.rawAttrs,e,t);if(r.list.b!=null)return Wg(this.node.rawAttrs,e,t);if(r.list.type!=null)return Og(this.node.rawAttrs,e,t)}return t}},er={};Ee(er,{OP_SCOPE_SUFFIX:()=>Ry,abs:()=>Ft,acos:()=>zy,acosh:()=>Py,add:()=>J,addN:()=>mI,all:()=>gf,any:()=>Jp,argMax:()=>mi,argMin:()=>By,asin:()=>Wy,asinh:()=>Uy,atan:()=>Vy,atan2:()=>Gy,atanh:()=>Hy,avgPool:()=>Oa,avgPool3d:()=>qy,basicLSTMCell:()=>xI,batchNorm:()=>Xo,batchNorm2d:()=>Ky,batchNorm3d:()=>Xy,batchNorm4d:()=>Zy,batchToSpaceND:()=>Pd,bincount:()=>Jy,bitwiseAnd:()=>vI,booleanMaskAsync:()=>uS,broadcastArgs:()=>wI,broadcastTo:()=>ai,buffer:()=>Le,cast:()=>se,ceil:()=>Yy,clipByValue:()=>ur,clone:()=>sa,complex:()=>Aa,concat:()=>lt,concat1d:()=>Qy,concat2d:()=>eb,concat3d:()=>tb,concat4d:()=>rb,conv1d:()=>yf,conv2d:()=>br,conv2dTranspose:()=>bf,conv3d:()=>ab,conv3dTranspose:()=>sb,cos:()=>Bd,cosh:()=>xf,cosineWindow:()=>Uf,cumprod:()=>ed,cumsum:()=>vf,denseBincount:()=>xc,depthToSpace:()=>ib,depthwiseConv2d:()=>Zo,diag:()=>II,dilation2d:()=>ob,div:()=>fe,divNoNan:()=>lb,dot:()=>ub,dropout:()=>zb,einsum:()=>Js,elu:()=>Ju,enclosingPowerOfTwo:()=>Pb,ensureShape:()=>NI,equal:()=>Kr,erf:()=>wf,euclideanNorm:()=>hb,exp:()=>pr,expandDims:()=>Xt,expm1:()=>cb,eye:()=>kf,fft:()=>Zd,fill:()=>qr,floor:()=>Qu,floorDiv:()=>mf,fused:()=>Ol,gather:()=>ep,gatherND:()=>cS,greater:()=>Ir,greaterEqual:()=>La,ifft:()=>Ml,imag:()=>Wd,image:()=>sn,inTopKAsync:()=>fS,irfft:()=>Mf,isFinite:()=>fb,isInf:()=>mb,isNaN:()=>gb,leakyRelu:()=>Ud,less:()=>Al,lessEqual:()=>Fs,linalg:()=>Ub,linspace:()=>$I,localResponseNormalization:()=>yb,log:()=>Xr,log1p:()=>Vd,logSigmoid:()=>bb,logSoftmax:()=>Sf,logSumExp:()=>Gd,logicalAnd:()=>Nn,logicalNot:()=>Hd,logicalOr:()=>Nf,logicalXor:()=>xb,losses:()=>_S,lowerBound:()=>FI,matMul:()=>Me,max:()=>hn,maxPool:()=>jt,maxPool3d:()=>vb,maxPoolWithArgmax:()=>RI,maximum:()=>ma,mean:()=>kt,meshgrid:()=>DI,min:()=>$l,minimum:()=>ys,mirrorPad:()=>wb,mod:()=>kb,moments:()=>jd,movingAverage:()=>pS,mul:()=>z,multiRNNCell:()=>MI,multinomial:()=>OI,neg:()=>gt,norm:()=>Yu,notEqual:()=>bi,oneHot:()=>Fl,ones:()=>$r,onesLike:()=>Zr,op:()=>L,outerProduct:()=>LI,pad:()=>jn,pad1d:()=>zI,pad2d:()=>PI,pad3d:()=>BI,pad4d:()=>WI,pool:()=>Ib,pow:()=>da,prelu:()=>Kd,print:()=>Ly,prod:()=>Sb,raggedGather:()=>UI,raggedRange:()=>VI,raggedTensorToTensor:()=>GI,rand:()=>HI,randomGamma:()=>XI,randomNormal:()=>Tf,randomStandardNormal:()=>ZI,randomUniform:()=>Rs,randomUniformInt:()=>JI,range:()=>xi,real:()=>Rl,reciprocal:()=>Eb,relu:()=>rt,relu6:()=>Cf,reshape:()=>B,reverse:()=>mn,reverse1d:()=>YI,reverse2d:()=>QI,reverse3d:()=>eS,reverse4d:()=>tS,rfft:()=>Jd,round:()=>Ef,rsqrt:()=>$f,scalar:()=>we,scatterND:()=>dS,searchSorted:()=>_f,selu:()=>Af,separableConv2d:()=>tp,setdiff1dAsync:()=>rS,sigmoid:()=>In,sign:()=>$b,signal:()=>NS,sin:()=>Ff,sinh:()=>Rf,slice:()=>Ve,slice1d:()=>Xd,slice2d:()=>Df,slice3d:()=>rp,slice4d:()=>Dl,softmax:()=>Ds,softplus:()=>Jo,spaceToBatchND:()=>qd,sparse:()=>TS,sparseToDense:()=>hS,spectral:()=>SS,split:()=>Ar,sqrt:()=>Yt,square:()=>ot,squaredDifference:()=>Of,squeeze:()=>Ms,stack:()=>Mt,step:()=>Yo,stridedSlice:()=>Ab,string:()=>CS,sub:()=>de,sum:()=>ge,tan:()=>Fb,tanh:()=>gs,tensor:()=>yr,tensor1d:()=>Qe,tensor2d:()=>ia,tensor3d:()=>Lf,tensor4d:()=>bs,tensor5d:()=>nS,tensor6d:()=>aS,tensorScatterUpdate:()=>iS,tile:()=>jr,topk:()=>Db,transpose:()=>Oe,truncatedNormal:()=>Bf,unique:()=>Mb,unsortedSegmentSum:()=>Wf,unstack:()=>Tt,upperBound:()=>oS,variable:()=>Ob,where:()=>Jt,whereAsync:()=>Lb,zeros:()=>It,zerosLike:()=>He});var Sj=(e,t,r,n=er)=>{switch(e.op){case"BiasAdd":case"AddV2":case"Add":return[n.add(I("a",e,t,r),I("b",e,t,r))];case"AddN":return[n.addN(I("tensors",e,t,r))];case"FloorMod":case"Mod":return[n.mod(I("a",e,t,r),I("b",e,t,r))];case"Mul":return[n.mul(I("a",e,t,r),I("b",e,t,r))];case"RealDiv":case"Div":return[n.div(I("a",e,t,r),I("b",e,t,r))];case"DivNoNan":return[n.divNoNan(I("a",e,t,r),I("b",e,t,r))];case"FloorDiv":return[n.floorDiv(I("a",e,t,r),I("b",e,t,r))];case"Sub":return[n.sub(I("a",e,t,r),I("b",e,t,r))];case"Minimum":return[n.minimum(I("a",e,t,r),I("b",e,t,r))];case"Maximum":return[n.maximum(I("a",e,t,r),I("b",e,t,r))];case"Pow":return[n.pow(I("a",e,t,r),I("b",e,t,r))];case"SquaredDifference":return[n.squaredDifference(I("a",e,t,r),I("b",e,t,r))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},Nj=(e,t,r,n=er)=>{switch(e.op){case"Abs":case"ComplexAbs":return[n.abs(I("x",e,t,r))];case"Acos":return[n.acos(I("x",e,t,r))];case"Acosh":return[n.acosh(I("x",e,t,r))];case"Asin":return[n.asin(I("x",e,t,r))];case"Asinh":return[n.asinh(I("x",e,t,r))];case"Atan":return[n.atan(I("x",e,t,r))];case"Atan2":return[n.atan2(I("x",e,t,r),I("y",e,t,r))];case"Atanh":return[n.atanh(I("x",e,t,r))];case"Ceil":return[n.ceil(I("x",e,t,r))];case"Complex":return[n.complex(I("real",e,t,r),I("imag",e,t,r))];case"Cos":return[n.cos(I("x",e,t,r))];case"Cosh":return[n.cosh(I("x",e,t,r))];case"Elu":return[n.elu(I("x",e,t,r))];case"Erf":return[n.erf(I("x",e,t,r))];case"Exp":return[n.exp(I("x",e,t,r))];case"Expm1":return[n.expm1(I("x",e,t,r))];case"Floor":return[n.floor(I("x",e,t,r))];case"Log":return[n.log(I("x",e,t,r))];case"Log1p":return[n.log1p(I("x",e,t,r))];case"Imag":return[n.imag(I("x",e,t,r))];case"Neg":return[n.neg(I("x",e,t,r))];case"Reciprocal":return[n.reciprocal(I("x",e,t,r))];case"Real":return[n.real(I("x",e,t,r))];case"Relu":return[n.relu(I("x",e,t,r))];case"Round":return[n.round(I("x",e,t,r))];case"Selu":return[n.selu(I("x",e,t,r))];case"Sigmoid":return[n.sigmoid(I("x",e,t,r))];case"Sin":return[n.sin(I("x",e,t,r))];case"Sign":return[n.sign(I("x",e,t,r))];case"Sinh":return[n.sinh(I("x",e,t,r))];case"Softplus":return[n.softplus(I("x",e,t,r))];case"Sqrt":return[n.sqrt(I("x",e,t,r))];case"Square":return[n.square(I("x",e,t,r))];case"Tanh":return[n.tanh(I("x",e,t,r))];case"Tan":return[n.tan(I("x",e,t,r))];case"ClipByValue":return[n.clipByValue(I("x",e,t,r),I("clipValueMin",e,t,r),I("clipValueMax",e,t,r))];case"Relu6":return[n.relu6(I("x",e,t,r))];case"Rsqrt":return[n.rsqrt(ar(e.inputNames[0],t,r))];case"LeakyRelu":return[n.leakyRelu(I("x",e,t,r),I("alpha",e,t,r))];case"Prelu":return[n.prelu(I("x",e,t,r),I("alpha",e,t,r))];case"IsNan":return[n.isNaN(ar(e.inputNames[0],t,r))];case"IsInf":return[n.isInf(ar(e.inputNames[0],t,r))];case"IsFinite":return[n.isFinite(ar(e.inputNames[0],t,r))];default:throw TypeError(`Node type ${e.op} is not implemented`)}};function kn(e,t,r=""){if(!(typeof e=="number"||typeof t=="number")){k.assert(e.length===t.length,()=>r+` Shapes ${e} and ${t} must match`);for(let n=0;n<e.length;n++){let a=e[n],s=t[n];k.assert(a<0||s<0||a===s,()=>r+` Shapes ${e} and ${t} must match`)}}}function t1(e){return!(typeof e=="number"||e.some(t=>t<0))}function Sp(e,t,r){let n=Ug(e,r),a=!t1(n);if(a&&t.length===0)throw new Error(`Tried to calculate elements of an empty list with non-fully-defined elementShape: ${n}`);if(a&&t.forEach(s=>{n=Ug(s.shape,n)}),!t1(n))throw new Error(`Non-fully-defined elementShape: ${n}`);return n}function Ug(e,t){if(typeof e=="number")return t;if(typeof t=="number")return e;if(e.length!==t.length)throw new Error(`Incompatible ranks during merge: ${e} vs. ${t}`);let r=[];for(let n=0;n<e.length;++n){let a=e[n],s=t[n];if(a>=0&&s>=0&&a!==s)throw new Error(`Incompatible shape during merge: ${e} vs. ${t}`);r[n]=a>=0?a:s}return r}var _j=class{constructor(e,t,r,n,a,s,i){this.name=e,this.dtype=t,this.maxSize=r,this.elementShape=n,this.identicalElementShapes=a,this.dynamicSize=s,this.clearAfterRead=i,this.tensors=[],this.closed_=!1,this.idTensor=we(0),Pt(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 r=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),kn(this.elementShape,t.shape,`TensorArray ${this.name}: Could not write to TensorArray index ${e}.`),r.read)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e}, because it has already been read.`);if(r.written)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e}, because it has already been written.`);r.tensor=t,Pt(t),r.written=!0,this.tensors[e]=r}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((r,n)=>this.write(r,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 yr([],[0].concat(this.elementShape));let r=this.readMany(e);return kn(this.elementShape,r[0].shape,"TensorArray shape mismatch: "),Mt(r,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 yr([],[0].concat(this.elementShape));let t=[];for(let n=0;n<this.size();n++)t.push(n);let r=this.readMany(t);return kn(this.elementShape,r[0].shape,`TensorArray shape mismatch: tensor array shape (${this.elementShape}) vs first tensor shape (${r[0].shape})`),lt(r,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 r=Math.max(...e);if(!this.dynamicSize&&r>=this.maxSize)throw new Error(`Max index must be < array size (${r} vs. ${this.maxSize})`);this.writeMany(e,Tt(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 r=0,n=e.map(o=>(r+=o,r));if(r!==t.shape[0])throw new Error(`Expected sum of lengths to be equal to
tensor.shape[0], but sum of lengths is
${r}, 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 a=r===0?0:t.size/r,s=[];W(()=>{t=B(t,[1,r,a]);for(let o=0;o<e.length;++o){let l=[0,o===0?0:n[o-1],0],p=[1,e[o],a];s[o]=B(Ve(t,l,p),this.elementShape)}return s});let i=[];for(let o=0;o<e.length;o++)i[o]=o;this.writeMany(i,s)}},gm=class Vg{get id(){return this.idTensor.id}constructor(t,r,n,a=-1){this.tensors=t,this.elementShape=r,this.elementDtype=n,t!=null&&t.forEach(s=>{if(n!==s.dtype)throw new Error(`Invalid data types; op elements ${n}, but list elements ${s.dtype}`);kn(r,s.shape,"TensorList shape mismatch: "),Pt(s)}),this.idTensor=we(0),this.maxNumElements=a,Pt(this.idTensor)}copy(){return new Vg([...this.tensors],this.elementShape,this.elementDtype)}clearAndClose(t){this.tensors.forEach(r=>{(t==null||!t.has(r.id))&&r.dispose()}),this.tensors.length=0,this.idTensor.dispose()}size(){return this.tensors.length}stack(t,r,n=-1){if(r!==this.elementDtype)throw new Error(`Invalid data types; op elements ${r}, but list elements ${this.elementDtype}`);if(n!==-1&&this.tensors.length!==n)throw new Error(`Operation expected a list with ${n} elements but got a list with ${this.tensors.length} elements.`);kn(t,this.elementShape,"TensorList shape mismatch: ");let a=Sp(this.elementShape,this.tensors,t);return W(()=>{let s=this.tensors.map(i=>B(i,a));return Mt(s,0)})}popBack(t,r){if(r!==this.elementDtype)throw new Error(`Invalid data types; op elements ${r}, but list elements ${this.elementDtype}`);if(this.size()===0)throw new Error("Trying to pop from an empty list.");let n=Sp(this.elementShape,this.tensors,t),a=this.tensors.pop();return a.kept=!1,kn(a.shape,t,"TensorList shape mismatch: "),B(a,n)}pushBack(t){if(t.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t.dtype}, but list elements ${this.elementDtype}`);if(kn(t.shape,this.elementShape,"TensorList shape mismatch: "),this.maxNumElements===this.size())throw new Error("Trying to push element into a full list.");Pt(t),this.tensors.push(t)}resize(t){if(t<0)throw new Error(`TensorListResize expects size to be non-negative. Got: ${t}`);if(this.maxNumElements!==-1&&t>this.maxNumElements)throw new Error(`TensorListResize input size ${t} is greater maxNumElement ${this.maxNumElements}.`);let r=new Vg([],this.elementShape,this.elementDtype,this.maxNumElements);r.tensors.length=t;for(let n=0;n<Math.min(this.tensors.length,t);++n)r.tensors[n]=this.tensors[n];return r}getItem(t,r,n){if(n!==this.elementDtype)throw new Error(`Invalid data types; op elements ${n}, but list elements ${this.elementDtype}`);if(t<0||t>this.tensors.length)throw new Error(`Trying to access element ${t} in a list with ${this.tensors.length} elements.`);if(this.tensors[t]==null)throw new Error(`element at index ${t} is null.`);kn(this.tensors[t].shape,r,"TensorList shape mismatch: ");let a=Sp(this.elementShape,this.tensors,r);return B(this.tensors[t],a)}setItem(t,r){if(r.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${r.dtype}, but list elements ${this.elementDtype}`);if(t<0||this.maxNumElements!==-1&&t>=this.maxNumElements)throw new Error(`Trying to set element ${t} in a list with max ${this.maxNumElements} elements.`);kn(this.elementShape,r.shape,"TensorList shape mismatch: "),Pt(r),this.tensors[t]!=null&&(this.tensors[t].kept=!1),this.tensors[t]=r}gather(t,r,n){if(r!==this.elementDtype)throw new Error(`Invalid data types; op elements ${r}, but list elements ${this.elementDtype}`);kn(this.elementShape,n,"TensorList shape mismatch: "),t=t.slice(0,this.size());let a=Sp(this.elementShape,this.tensors,n);return t.length===0?yr([],[0].concat(a)):W(()=>{let s=t.map(i=>B(this.tensors[i],a));return Mt(s,0)})}concat(t,r){if(t&&t!==this.elementDtype)throw new Error(`TensorList dtype is ${this.elementDtype} but concat requested dtype ${t}`);kn(this.elementShape,r,"TensorList shape mismatch: ");let n=Sp(this.elementShape,this.tensors,r);return this.size()===0?yr([],[0].concat(n)):W(()=>{let a=this.tensors.map(s=>B(s,n));return lt(a,0)})}};function Tj(e,t,r){let n=e.dtype;if(e.shape.length<1)throw new Error(`Tensor must be at least a vector, but saw shape: ${e.shape}`);if(e.dtype!==r)throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${r}`);let a=e.shape.slice(1);kn(a,t,"TensorList shape mismatch: ");let s=Tt(e);return new gm(s,t,n)}function Cj(e,t,r,n){return new gm([],e,t,n)}function Ej(e,t,r,n){if(t.length!==e.shape[0])throw new Error(`Expected len(indices) == tensor.shape[0], but saw: ${t.length} vs. ${e.shape[0]}`);let a=Math.max(...t);if(n!=null&&n!==-1&&a>=n)throw new Error(`Max index must be < array size (${a} vs. ${n})`);let s=new gm([],r,e.dtype,n),i=Tt(e,0);return t.forEach((o,l)=>{s.setItem(o,i[l])}),s}function $j(e,t,r){let n=0,a=t.map(u=>(n+=u,n));if(n!==e.shape[0])throw new Error(`Expected sum of lengths to be equal to
tensor.shape[0], but sum of lengths is
${n}, and tensor's shape is: ${e.shape}`);let s=e.shape.slice(1),i=Ug(s,r),o=n===0?0:e.size/n,l=W(()=>{let u=[];e=B(e,[1,n,o]);for(let d=0;d<t.length;++d){let h=[0,d===0?0:a[d-1],0],c=[1,t[d],o];u[d]=B(Ve(e,h,c),i)}return e.dispose(),u}),p=new gm([],r,e.dtype,t.length);for(let u=0;u<l.length;u++)p.setItem(u,l[u]);return p}var Aj=async(e,t,r)=>{switch(e.op){case"If":case"StatelessIf":{let n=I("thenBranch",e,t,r),a=I("elseBranch",e,t,r),s=I("cond",e,t,r),i=I("args",e,t,r);return(await s.data())[0]?r.functionMap[n].executeFunctionAsync(i,r.tensorArrayMap,r.tensorListMap):r.functionMap[a].executeFunctionAsync(i,r.tensorArrayMap,r.tensorListMap)}case"While":case"StatelessWhile":{let n=I("body",e,t,r),a=I("cond",e,t,r),s=I("args",e,t,r),i=await r.functionMap[a].executeFunctionAsync(s,r.tensorArrayMap,r.tensorListMap),o=s.map(u=>u.id),l=await i[0].data();i.forEach(u=>{!u.kept&&o.indexOf(u.id)===-1&&u.dispose()});let p=s;for(;l[0];){let u=p;p=await r.functionMap[n].executeFunctionAsync(p,r.tensorArrayMap,r.tensorListMap);let d=p.map(c=>c.id);u.forEach(c=>{!c.kept&&o.indexOf(c.id)===-1&&d.indexOf(c.id)===-1&&c.dispose()});let h=await r.functionMap[a].executeFunctionAsync(p,r.tensorArrayMap,r.tensorListMap);l=await h[0].data(),h.forEach(c=>{!c.kept&&o.indexOf(c.id)===-1&&d.indexOf(c.id)===-1&&c.dispose()})}return p}case"LoopCond":{let n=I("pred",e,t,r);return[Sa(n)]}case"Switch":{let n=I("pred",e,t,r),a=I("data",e,t,r);return a.kept||(a=Sa(a)),(await n.data())[0]?[void 0,a]:[a,void 0]}case"Merge":{let n=e.inputNames.find(a=>ar(a,t,r)!==void 0);if(n){let a=ar(n,t,r);return[Sa(a)]}return}case"Enter":{let n=I("frameName",e,t,r),a=I("tensor",e,t,r);return r.enterFrame(n),[Sa(a)]}case"Exit":{let n=I("tensor",e,t,r);return r.exitFrame(),[Sa(n)]}case"NextIteration":{let n=I("tensor",e,t,r);return r.nextIteration(),[Sa(n)]}case"TensorArrayV3":{let n=I("size",e,t,r),a=I("dtype",e,t,r),s=I("elementShape",e,t,r),i=I("dynamicSize",e,t,r),o=I("clearAfterRead",e,t,r),l=I("identicalElementShapes",e,t,r),p=I("name",e,t,r),u=new _j(p,a,n,s,l,i,o);return r.addTensorArray(u),[u.idTensor,we(1)]}case"TensorArrayWriteV3":{let n=I("tensorArrayId",e,t,r),a=I("index",e,t,r),s=I("tensor",e,t,r),i=r.getTensorArray(n.id);return i.write(a,s),[i.idTensor]}case"TensorArrayReadV3":{let n=I("tensorArrayId",e,t,r),a=I("index",e,t,r);return[r.getTensorArray(n.id).read(a)]}case"TensorArrayGatherV3":{let n=I("tensorArrayId",e,t,r),a=I("indices",e,t,r),s=I("dtype",e,t,r);return[r.getTensorArray(n.id).gather(a,s)]}case"TensorArrayScatterV3":{let n=I("tensorArrayId",e,t,r),a=I("indices",e,t,r),s=I("tensor",e,t,r),i=r.getTensorArray(n.id);return i.scatter(a,s),[i.idTensor]}case"TensorArrayConcatV3":{let n=I("tensorArrayId",e,t,r),a=r.getTensorArray(n.id),s=I("dtype",e,t,r);return[a.concat(s)]}case"TensorArraySplitV3":{let n=I("tensorArrayId",e,t,r),a=I("tensor",e,t,r),s=I("lengths",e,t,r),i=r.getTensorArray(n.id);return i.split(s,a),[i.idTensor]}case"TensorArraySizeV3":{let n=I("tensorArrayId",e,t,r),a=r.getTensorArray(n.id);return[we(a.size(),"int32")]}case"TensorArrayCloseV3":{let n=I("tensorArrayId",e,t,r),a=r.getTensorArray(n.id);return a.clearAndClose(),[a.idTensor]}case"TensorListSetItem":{let n=I("tensorListId",e,t,r),a=I("index",e,t,r),s=I("tensor",e,t,r),i=r.getTensorList(n.id);return i.setItem(a,s),[i.idTensor]}case"TensorListGetItem":{let n=I("tensorListId",e,t,r),a=I("index",e,t,r),s=I("elementShape",e,t,r),i=I("elementDType",e,t,r);return[r.getTensorList(n.id).getItem(a,s,i)]}case"TensorListScatterV2":case"TensorListScatter":{let n=I("indices",e,t,r),a=I("tensor",e,t,r),s=I("elementShape",e,t,r),i=I("numElements",e,t,r),o=Ej(a,n,s,i);return r.addTensorList(o),[o.idTensor]}case"TensorListReserve":case"EmptyTensorList":{let n=I("elementShape",e,t,r),a=I("elementDType",e,t,r),s;e.op==="TensorListReserve"?s="numElements":s="maxNumElements";let i=I(s,e,t,r),o=e.op==="TensorListReserve"?-1:i,l=Cj(n,a,i,o);return r.addTensorList(l),[l.idTensor]}case"TensorListGather":{let n=I("tensorListId",e,t,r),a=I("indices",e,t,r),s=I("elementShape",e,t,r),i=I("elementDType",e,t,r);return[r.getTensorList(n.id).gather(a,i,s)]}case"TensorListStack":{let n=I("tensorListId",e,t,r),a=I("elementShape",e,t,r),s=I("elementDType",e,t,r),i=I("numElements",e,t,r);return[r.getTensorList(n.id).stack(a,s,i)]}case"TensorListFromTensor":{let n=I("tensor",e,t,r),a=I("elementShape",e,t,r),s=I("elementDType",e,t,r),i=Tj(n,a,s);return r.addTensorList(i),[i.idTensor]}case"TensorListConcat":case"TensorListConcatV2":{let n=I("tensorListId",e,t,r),a=r.getTensorList(n.id),s=I("dtype",e,t,r),i=I("elementShape",e,t,r);return[a.concat(s,i)]}case"TensorListPushBack":{let n=I("tensorListId",e,t,r),a=I("tensor",e,t,r),s=r.getTensorList(n.id);return s.pushBack(a),[s.idTensor]}case"TensorListPopBack":{let n=I("tensorListId",e,t,r),a=I("elementShape",e,t,r),s=I("elementDType",e,t,r);return[r.getTensorList(n.id).popBack(a,s)]}case"TensorListSplit":{let n=I("tensor",e,t,r),a=I("elementShape",e,t,r),s=I("lengths",e,t,r),i=$j(n,s,a);return r.addTensorList(i),[i.idTensor]}case"TensorListLength":{let n=I("tensorListId",e,t,r),a=r.getTensorList(n.id);return[we(a.size(),"int32")]}case"TensorListResize":{let n=I("tensorListId",e,t,r),a=I("size",e,t,r),s=r.getTensorList(n.id).resize(a);return r.addTensorList(s),[s.idTensor]}default:throw TypeError(`Node type ${e.op} is not implemented`)}};function r1(e,t,r){let[n,a]=I("fusedOps",e,t,r),s=n==="biasadd",i=!s,o=a==="prelu",l=n==="fusedbatchnorm",p=I("numArgs",e,t,r);if(s){if(o&&p!==2)throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!o&&s&&p!==1)throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd must have one extra argument: bias.")}if(l)throw new Error("FusedConv2d and DepthwiseConv2d with FusedBatchNorm is not supported");let u=I("strides",e,t,r),d=Jh(e,t,r),h=I("dataFormat",e,t,r).toUpperCase(),c=I("dilations",e,t,r),[f,m]=I("args",e,t,r);i&&(m=f,f=void 0);let g=I("leakyreluAlpha",e,t,r);return{stride:u,pad:d,dataFormat:h,dilations:c,biasArg:f,preluArg:m,activationFunc:a,leakyreluAlpha:g}}var Fj=(e,t,r,n=er)=>{switch(e.op){case"Conv1D":{let a=I("stride",e,t,r),s=I("pad",e,t,r),i=I("dataFormat",e,t,r).toUpperCase(),o=I("dilation",e,t,r);return[n.conv1d(I("x",e,t,r),I("filter",e,t,r),a,s,i,o)]}case"Conv2D":{let a=I("strides",e,t,r),s=Jh(e,t,r),i=I("dataFormat",e,t,r).toUpperCase(),o=I("dilations",e,t,r);return[n.conv2d(I("x",e,t,r),I("filter",e,t,r),[a[1],a[2]],s,i,[o[1],o[2]])]}case"_FusedConv2D":{let{stride:a,pad:s,dataFormat:i,dilations:o,biasArg:l,preluArg:p,activationFunc:u,leakyreluAlpha:d}=r1(e,t,r);return[n.fused.conv2d({x:I("x",e,t,r),filter:I("filter",e,t,r),strides:[a[1],a[2]],pad:s,dataFormat:i,dilations:[o[1],o[2]],bias:l,activation:u,preluActivationWeights:p,leakyreluAlpha:d})]}case"FusedDepthwiseConv2dNative":{let{stride:a,pad:s,dataFormat:i,dilations:o,biasArg:l,preluArg:p,activationFunc:u,leakyreluAlpha:d}=r1(e,t,r);return[n.fused.depthwiseConv2d({x:I("x",e,t,r),filter:I("filter",e,t,r),strides:[a[1],a[2]],pad:s,dataFormat:i,dilations:[o[1],o[2]],bias:l,activation:u,preluActivationWeights:p,leakyreluAlpha:d})]}case"Conv2DBackpropInput":case"Conv2dTranspose":{let a=I("outputShape",e,t,r),s=I("strides",e,t,r),i=Jh(e,t,r);return[n.conv2dTranspose(I("x",e,t,r),I("filter",e,t,r),a,[s[1],s[2]],i)]}case"DepthwiseConv2dNative":case"DepthwiseConv2d":{let a=I("strides",e,t,r),s=Jh(e,t,r),i=I("dilations",e,t,r),o=I("dataFormat",e,t,r).toUpperCase();return[n.depthwiseConv2d(I("input",e,t,r),I("filter",e,t,r),[a[1],a[2]],s,o,[i[1],i[2]])]}case"Conv3D":{let a=I("strides",e,t,r),s=I("pad",e,t,r),i=I("dataFormat",e,t,r).toUpperCase(),o=I("dilations",e,t,r);return[n.conv3d(I("x",e,t,r),I("filter",e,t,r),[a[1],a[2],a[3]],s,i,[o[1],o[2],o[3]])]}case"AvgPool":{let a=I("strides",e,t,r),s=I("pad",e,t,r),i=I("kernelSize",e,t,r);return[n.avgPool(I("x",e,t,r),[i[1],i[2]],[a[1],a[2]],s)]}case"MaxPool":{let a=I("strides",e,t,r),s=I("pad",e,t,r),i=I("kernelSize",e,t,r);return[n.maxPool(I("x",e,t,r),[i[1],i[2]],[a[1],a[2]],s)]}case"MaxPoolWithArgmax":{let a=I("strides",e,t,r),s=I("pad",e,t,r),i=I("kernelSize",e,t,r),o=I("includeBatchInIndex",e,t,r),{result:l,indexes:p}=n.maxPoolWithArgmax(I("x",e,t,r),[i[1],i[2]],[a[1],a[2]],s,o);return[l,p]}case"AvgPool3D":{let a=I("strides",e,t,r),s=I("pad",e,t,r),i=I("kernelSize",e,t,r);return[n.avgPool3d(I("x",e,t,r),[i[1],i[2],i[3]],[a[1],a[2],a[3]],s)]}case"MaxPool3D":{let a=I("strides",e,t,r),s=I("pad",e,t,r),i=I("kernelSize",e,t,r);return[n.maxPool3d(I("x",e,t,r),[i[1],i[2],i[3]],[a[1],a[2],a[3]],s)]}case"Dilation2D":{let a=I("strides",e,t,r),s=I("pad",e,t,r),i=I("dilations",e,t,r),o=a[1],l=a[2],p=i[1],u=i[2];return[n.dilation2d(I("x",e,t,r),I("filter",e,t,r),[o,l],s,[p,u],"NHWC")]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},Rj=(e,t,r,n=er)=>{switch(e.op){case"Fill":{let a=I("shape",e,t,r),s=I("dtype",e,t,r),i=I("value",e,t,r);return[n.fill(a,i,s)]}case"LinSpace":{let a=I("start",e,t,r),s=I("stop",e,t,r),i=I("num",e,t,r);return[n.linspace(a,s,i)]}case"Multinomial":{let a=I("logits",e,t,r),s=I("numSamples",e,t,r),i=I("seed",e,t,r);return[n.multinomial(a,s,i)]}case"OneHot":{let a=I("indices",e,t,r),s=I("depth",e,t,r),i=I("onValue",e,t,r),o=I("offValue",e,t,r),l=I("dtype",e,t,r);return[n.oneHot(a,s,i,o,l)]}case"Ones":return[n.ones(I("shape",e,t,r),I("dtype",e,t,r))];case"OnesLike":return[n.onesLike(I("x",e,t,r))];case"RandomStandardNormal":return[n.randomStandardNormal(I("shape",e,t,r),I("dtype",e,t,r),I("seed",e,t,r))];case"RandomUniform":return[n.randomUniform(I("shape",e,t,r),I("minval",e,t,r),I("maxval",e,t,r),I("dtype",e,t,r))];case"RandomUniformInt":return[n.randomUniformInt(I("shape",e,t,r),I("minval",e,t,r),I("maxval",e,t,r),I("seed",e,t,r))];case"Range":{let a=I("start",e,t,r),s=I("stop",e,t,r),i=I("step",e,t,r);return[n.range(a,s,i,I("dtype",e,t,r))]}case"TruncatedNormal":{let a=I("shape",e,t,r),s=I("mean",e,t,r),i=I("stdDev",e,t,r),o=I("seed",e,t,r);return[n.truncatedNormal(a,s,i,I("dtype",e,t,r),o)]}case"Zeros":return[n.zeros(I("shape",e,t,r),I("dtype",e,t,r))];case"ZerosLike":return[n.zerosLike(I("x",e,t,r))];default:throw TypeError(`Node type ${e.op} is not implemented`)}};function Gm(e,t,r){let n=I("boxes",e,t,r),a=I("scores",e,t,r),s=I("maxOutputSize",e,t,r),i=I("iouThreshold",e,t,r),o=I("scoreThreshold",e,t,r),l=I("softNmsSigma",e,t,r);return{boxes:n,scores:a,maxOutputSize:s,iouThreshold:i,scoreThreshold:o,softNmsSigma:l}}var Dj=async(e,t,r,n,a=er)=>{switch(e.op){case"NonMaxSuppressionV5":{let{boxes:s,scores:i,maxOutputSize:o,iouThreshold:l,scoreThreshold:p,softNmsSigma:u}=Gm(e,t,r),d=await a.image.nonMaxSuppressionWithScoreAsync(s,i,o,l,p,u);return[d.selectedIndices,d.selectedScores]}case"NonMaxSuppressionV4":{let{boxes:s,scores:i,maxOutputSize:o,iouThreshold:l,scoreThreshold:p}=Gm(e,t,r),u=I("padToMaxOutputSize",e,t,r),d=await a.image.nonMaxSuppressionPaddedAsync(s,i,o,l,p,u);return[d.selectedIndices,d.validOutputs]}case"NonMaxSuppressionV3":case"NonMaxSuppressionV2":{let{boxes:s,scores:i,maxOutputSize:o,iouThreshold:l,scoreThreshold:p}=Gm(e,t,r);return[await a.image.nonMaxSuppressionAsync(s,i,o,l,p)]}case"Where":{let s=a.cast(I("condition",e,t,r),"bool"),i=[await a.whereAsync(s)];return s.dispose(),i}case"ListDiff":return a.setdiff1dAsync(I("x",e,t,r),I("y",e,t,r));default:throw TypeError(`Node type ${e.op} is not implemented`)}},Mj=(e,t,r,n=er)=>{switch(e.op){case"LowerBound":{let a=I("sortedSequence",e,t,r),s=I("values",e,t,r);return[n.lowerBound(a,s)]}case"TopKV2":{let a=I("x",e,t,r),s=I("k",e,t,r),i=I("sorted",e,t,r),o=n.topk(a,s,i);return[o.values,o.indices]}case"UpperBound":{let a=I("sortedSequence",e,t,r),s=I("values",e,t,r);return[n.upperBound(a,s)]}case"Unique":{let a=I("x",e,t,r),s=n.unique(a);return[s.values,s.indices]}case"UniqueV2":{let a=I("x",e,t,r),s=I("axis",e,t,r),i=n.unique(a,s);return[i.values,i.indices]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},Oj=(e,t,r,n=er)=>{switch(e.op){case"Const":return t[e.name];case"PlaceholderWithDefault":let a=I("default",e,t,r);return[ar(e.name,t,r)||a];case"Placeholder":return[ar(e.name,t,r)];case"Identity":case"StopGradient":case"FakeQuantWithMinMaxVars":{let u=I("x",e,t,r);return[Sa(u)]}case"IdentityN":return I("x",e,t,r).map(u=>Sa(u));case"Snapshot":let s=I("x",e,t,r);return[Sa(s)];case"Shape":return[n.tensor1d(I("x",e,t,r).shape,"int32")];case"ShapeN":return I("x",e,t,r).map(u=>n.tensor1d(u.shape));case"Size":return[n.scalar(I("x",e,t,r).size,"int32")];case"Rank":return[n.scalar(I("x",e,t,r).rank,"int32")];case"NoOp":return[n.scalar(1)];case"Print":let i=I("x",e,t,r),o=I("data",e,t,r),l=I("message",e,t,r),p=I("summarize",e,t,r);console.warn("The graph has a tf.print() operation,usually used for debugging, which slows down performance."),console.log(l);for(let u=0;u<o.length;u++)console.log(Array.prototype.slice.call(o[u].dataSync()).slice(0,p));return[i];default:throw TypeError(`Node type ${e.op} is not implemented`)}},Lj=class{get id(){return this.handle.id}constructor(e,t){this.keyDType=e,this.valueDType=t,this.handle=we(0),this.tensorMap=new Map,Pt(this.handle)}clearAndClose(){this.tensorMap.forEach(e=>e.dispose()),this.tensorMap.clear(),this.handle.dispose()}size(){return this.tensorMap.size}tensorSize(){return we(this.size(),"int32")}async import(e,t){this.checkKeyAndValueTensor(e,t);let r=await e.data();return this.tensorMap.forEach(n=>n.dispose()),this.tensorMap.clear(),W(()=>{let n=Tt(t),a=r.length,s=n.length;k.assert(a===s,()=>`The number of elements doesn't match, keys has ${a} elements, the values has ${s} elements.`);for(let i=0;i<a;i++){let o=r[i],l=n[i];Pt(l),this.tensorMap.set(o,l)}return this.handle})}async find(e,t){this.checkKeyAndValueTensor(e,t);let r=await e.data();return W(()=>{let n=[];for(let a=0;a<r.length;a++){let s=r[a],i=this.findWithDefault(s,t);n.push(i)}return Mt(n)})}findWithDefault(e,t){let r=this.tensorMap.get(e);return r??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}`)}},zj=async(e,t,r,n)=>{switch(e.op){case"HashTable":case"HashTableV2":{let a=n.getHashTableHandleByName(e.name);if(a!=null)return[a];{let s=I("keyDType",e,t,r),i=I("valueDType",e,t,r),o=new Lj(s,i);return n.addHashTable(e.name,o),[o.handle]}}case"InitializeTable":case"InitializeTableV2":case"LookupTableImport":case"LookupTableImportV2":{let a=I("tableHandle",e,t,r,n),s=I("keys",e,t,r),i=I("values",e,t,r);return[await n.getHashTableById(a.id).import(s,i)]}case"LookupTableFind":case"LookupTableFindV2":{let a=I("tableHandle",e,t,r,n),s=I("keys",e,t,r),i=I("defaultValue",e,t,r);return[await n.getHashTableById(a.id).find(s,i)]}case"LookupTableSize":case"LookupTableSizeV2":{let a=I("tableHandle",e,t,r,n);return[n.getHashTableById(a.id).tensorSize()]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},Pj=(e,t,r,n=er)=>{switch(e.op){case"ResizeBilinear":{let a=I("images",e,t,r),s=I("size",e,t,r),i=I("alignCorners",e,t,r),o=I("halfPixelCenters",e,t,r);return[n.image.resizeBilinear(a,[s[0],s[1]],i,o)]}case"ResizeNearestNeighbor":{let a=I("images",e,t,r),s=I("size",e,t,r),i=I("alignCorners",e,t,r),o=I("halfPixelCenters",e,t,r);return[n.image.resizeNearestNeighbor(a,[s[0],s[1]],i,o)]}case"CropAndResize":{let a=I("image",e,t,r),s=I("boxes",e,t,r),i=I("boxInd",e,t,r),o=I("cropSize",e,t,r),l=I("method",e,t,r),p=I("extrapolationValue",e,t,r);return[n.image.cropAndResize(a,s,i,o,l,p)]}case"ImageProjectiveTransformV3":{let a=I("images",e,t,r),s=I("transforms",e,t,r),i=I("outputShape",e,t,r),o=I("fillValue",e,t,r),l=I("interpolation",e,t,r),p=I("fillMode",e,t,r);return[n.image.transform(a,s,l.toLowerCase(),p.toLowerCase(),o,i)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},Bj=(e,t,r,n=er)=>{switch(e.op){case"Equal":return[n.equal(I("a",e,t,r),I("b",e,t,r))];case"NotEqual":return[n.notEqual(I("a",e,t,r),I("b",e,t,r))];case"Greater":return[n.greater(I("a",e,t,r),I("b",e,t,r))];case"GreaterEqual":return[n.greaterEqual(I("a",e,t,r),I("b",e,t,r))];case"Less":return[n.less(I("a",e,t,r),I("b",e,t,r))];case"LessEqual":return[n.lessEqual(I("a",e,t,r),I("b",e,t,r))];case"LogicalAnd":return[n.logicalAnd(I("a",e,t,r),I("b",e,t,r))];case"LogicalNot":return[n.logicalNot(I("a",e,t,r))];case"LogicalOr":return[n.logicalOr(I("a",e,t,r),I("b",e,t,r))];case"Select":case"SelectV2":return[n.where(I("condition",e,t,r),I("a",e,t,r),I("b",e,t,r))];case"BitwiseAnd":return[n.bitwiseAnd(I("a",e,t,r),I("b",e,t,r))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},Wj=(e,t,r,n=er)=>{switch(e.op){case"BatchMatMul":case"BatchMatMulV2":case"MatMul":return[n.matMul(I("a",e,t,r),I("b",e,t,r),I("transposeA",e,t,r),I("transposeB",e,t,r))];case"Einsum":return[n.einsum(I("equation",e,t,r),...I("tensors",e,t,r))];case"Transpose":return[n.transpose(I("x",e,t,r),I("perm",e,t,r))];case"_FusedMatMul":let[a,s]=I("fusedOps",e,t,r),i=a==="biasadd",o=s==="prelu",l=I("numArgs",e,t,r),p=I("leakyreluAlpha",e,t,r);if(i){if(o&&l!==2)throw new Error("Fused MatMul with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!o&&l!==1)throw new Error("Fused MatMul with BiasAdd must have one extra argument: bias.")}let[u,d]=I("args",e,t,r);return[n.fused.matMul({a:I("a",e,t,r),b:I("b",e,t,r),transposeA:I("transposeA",e,t,r),transposeB:I("transposeB",e,t,r),bias:u,activation:s,preluActivationWeights:d,leakyreluAlpha:p})];case"MatrixBandPart":return[n.linalg.bandPart(I("a",e,t,r),I("numLower",e,t,r),I("numUpper",e,t,r))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},Uj=(e,t,r,n=er)=>{switch(e.op){case"EuclideanNorm":return[n.euclideanNorm(I("x",e,t,r),I("axis",e,t,r),I("keepDims",e,t,r))];case"FusedBatchNorm":case"FusedBatchNormV2":return[n.batchNorm(I("x",e,t,r),I("mean",e,t,r),I("variance",e,t,r),I("offset",e,t,r),I("scale",e,t,r),I("epsilon",e,t,r))];case"FusedBatchNormV3":return[n.batchNorm(I("x",e,t,r),I("mean",e,t,r),I("variance",e,t,r),I("offset",e,t,r),I("scale",e,t,r),I("epsilon",e,t,r))];case"LRN":return[n.localResponseNormalization(I("x",e,t,r),I("radius",e,t,r),I("bias",e,t,r),I("alpha",e,t,r),I("beta",e,t,r))];case"Softmax":return[n.softmax(I("x",e,t,r))];case"LogSoftmax":return[n.logSoftmax(I("x",e,t,r))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},Vj=(e,t,r,n=er)=>{switch(e.op){case"RaggedGather":{let{outputNestedSplits:a,outputDenseValues:s}=n.raggedGather(I("paramsNestedSplits",e,t,r),I("paramsDenseValues",e,t,r),I("indices",e,t,r),I("outputRaggedRank",e,t,r));return a.concat(s)}case"RaggedRange":{let{rtNestedSplits:a,rtDenseValues:s}=n.raggedRange(I("starts",e,t,r),I("limits",e,t,r),I("splits",e,t,r));return[a,s]}case"RaggedTensorToTensor":return[n.raggedTensorToTensor(I("shape",e,t,r),I("values",e,t,r),I("defaultValue",e,t,r),I("rowPartitionTensors",e,t,r),I("rowPartitionTypes",e,t,r))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},Gj=(e,t,r,n=er)=>{switch(e.op){case"Max":{let o=I("axis",e,t,r),l=I("keepDims",e,t,r);return[n.max(I("x",e,t,r),o,l)]}case"Mean":{let o=I("axis",e,t,r),l=I("keepDims",e,t,r);return[n.mean(I("x",e,t,r),o,l)]}case"Min":{let o=I("axis",e,t,r),l=I("keepDims",e,t,r);return[n.min(I("x",e,t,r),o,l)]}case"Sum":{let o=I("axis",e,t,r),l=I("keepDims",e,t,r);return[n.sum(I("x",e,t,r),o,l)]}case"All":{let o=I("axis",e,t,r),l=I("keepDims",e,t,r);return[n.all(I("x",e,t,r),o,l)]}case"Any":{let o=I("axis",e,t,r),l=I("keepDims",e,t,r);return[n.any(I("x",e,t,r),o,l)]}case"ArgMax":{let o=I("axis",e,t,r);return[n.argMax(I("x",e,t,r),o)]}case"ArgMin":{let o=I("axis",e,t,r);return[n.argMin(I("x",e,t,r),o)]}case"Prod":{let o=I("axis",e,t,r),l=I("keepDims",e,t,r);return[n.prod(I("x",e,t,r),o,l)]}case"Cumprod":{let o=I("axis",e,t,r),l=I("exclusive",e,t,r),p=I("reverse",e,t,r);return[n.cumprod(I("x",e,t,r),o,l,p)]}case"Cumsum":{let o=I("axis",e,t,r),l=I("exclusive",e,t,r),p=I("reverse",e,t,r);return[n.cumsum(I("x",e,t,r),o,l,p)]}case"Bincount":let a=I("x",e,t,r),s=I("weights",e,t,r),i=I("size",e,t,r);return[n.bincount(a,s,i)];case"DenseBincount":{let o=I("x",e,t,r),l=I("weights",e,t,r),p=I("size",e,t,r),u=I("binaryOutput",e,t,r);return[n.denseBincount(o,l,p,u)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},Hj=(e,t,r,n=er)=>{switch(e.op){case"ConcatV2":case"Concat":{let a=I("n",e,t,r),s=I("axis",e,t,r),i=I("tensors",e,t,r);return i=i.slice(0,a),[n.concat(i,s)]}case"Gather":{let a=I("x",e,t,r),s=I("indices",e,t,r);return[n.gather(a,n.cast(s,"int32"),0)]}case"GatherV2":{let a=I("axis",e,t,r),s=I("batchDims",e,t,r),i=I("x",e,t,r),o=I("indices",e,t,r);return[n.gather(i,n.cast(o,"int32"),a,s)]}case"Reverse":{let a=I("dims",e,t,r),s=[];for(let o=0;o<a.length;o++)a[o]&&s.push(o);let i=I("x",e,t,r);return[n.reverse(i,s)]}case"ReverseV2":{let a=I("axis",e,t,r),s=I("x",e,t,r);return[n.reverse(s,a)]}case"Slice":{let a=I("begin",e,t,r),s=I("size",e,t,r);return[n.slice(I("x",e,t,r),a,s)]}case"StridedSlice":{let a=I("begin",e,t,r),s=I("end",e,t,r),i=I("strides",e,t,r),o=I("beginMask",e,t,r),l=I("endMask",e,t,r),p=I("ellipsisMask",e,t,r),u=I("newAxisMask",e,t,r),d=I("shrinkAxisMask",e,t,r),h=I("x",e,t,r);return[n.stridedSlice(h,a,s,i,o,l,p,u,d)]}case"Pack":return W(()=>{let a=I("axis",e,t,r),s=I("tensors",e,t,r),i=s[0].shape,o=n.squeeze(s[0]).shape,l=s.map(p=>{let u=k.arraysEqual(p.shape,i);if(!u&&!k.arraysEqual(n.squeeze(p).shape,o))throw new Error("the input tensors shape does not match");return u?p:n.reshape(p,i)});return[n.stack(l,a)]});case"Unpack":{let a=I("axis",e,t,r),s=I("tensor",e,t,r);return n.unstack(s,a)}case"Tile":{let a=I("reps",e,t,r);return[n.tile(I("x",e,t,r),a)]}case"Split":case"SplitV":{let a=I("axis",e,t,r),s=I("numOrSizeSplits",e,t,r),i=I("x",e,t,r);return n.split(i,s,a)}case"ScatterNd":{let a=I("indices",e,t,r),s=I("values",e,t,r),i=I("shape",e,t,r);return[n.scatterND(a,s,i)]}case"GatherNd":{let a=I("x",e,t,r),s=I("indices",e,t,r);return[n.gatherND(a,s)]}case"SparseToDense":{let a=I("sparseIndices",e,t,r),s=I("outputShape",e,t,r),i=I("sparseValues",e,t,r),o=I("defaultValue",e,t,r);return[n.sparseToDense(a,i,s,i.dtype===o.dtype?o:n.cast(o,i.dtype))]}case"TensorScatterUpdate":{let a=I("indices",e,t,r),s=I("values",e,t,r),i=I("tensor",e,t,r);return[n.tensorScatterUpdate(i,a,s)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},jj=(e,t,r,n=er)=>{switch(e.op){case"SparseFillEmptyRows":{let{outputIndices:a,outputValues:s,emptyRowIndicator:i,reverseIndexMap:o}=n.sparse.sparseFillEmptyRows(I("indices",e,t,r),I("values",e,t,r),I("denseShape",e,t,r),I("defaultValue",e,t,r));return[a,s,i,o]}case"SparseReshape":{let{outputIndices:a,outputShape:s}=n.sparse.sparseReshape(I("inputIndices",e,t,r),I("inputShape",e,t,r),I("newShape",e,t,r));return[a,s]}case"SparseSegmentMean":return[n.sparse.sparseSegmentMean(I("data",e,t,r),I("indices",e,t,r),I("segmentIds",e,t,r))];case"SparseSegmentSum":return[n.sparse.sparseSegmentSum(I("data",e,t,r),I("indices",e,t,r),I("segmentIds",e,t,r))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},qj=(e,t,r,n=er)=>{switch(e.op){case"FFT":return[n.fft(I("x",e,t,r))];case"IFFT":return[n.ifft(I("x",e,t,r))];case"RFFT":return[n.rfft(I("x",e,t,r))];case"IRFFT":return[n.irfft(I("x",e,t,r))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},Kj=(e,t,r,n=er)=>{switch(e.op){case"StaticRegexReplace":return[n.string.staticRegexReplace(I("input",e,t,r),I("pattern",e,t,r),I("rewrite",e,t,r),I("replaceGlobal",e,t,r))];case"StringNGrams":{let{nGrams:a,nGramsSplits:s}=n.string.stringNGrams(I("data",e,t,r),I("dataSplits",e,t,r),I("separator",e,t,r),I("nGramWidths",e,t,r),I("leftPad",e,t,r),I("rightPad",e,t,r),I("padWidth",e,t,r),I("preserveShortSequences",e,t,r));return[a,s]}case"StringSplit":{let{indices:a,values:s,shape:i}=n.string.stringSplit(I("input",e,t,r),I("delimiter",e,t,r),I("skipEmpty",e,t,r));return[a,s,i]}case"StringToHashBucketFast":return[n.string.stringToHashBucketFast(I("input",e,t,r),I("numBuckets",e,t,r))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},Xj=(e,t,r,n=er)=>{switch(e.op){case"Cast":return[n.cast(I("x",e,t,r),I("dtype",e,t,r))];case"ExpandDims":{let a=I("axis",e,t,r);return[n.expandDims(I("x",e,t,r),a)]}case"Squeeze":{let a=I("axis",e,t,r);return[n.squeeze(I("x",e,t,r),a)]}case"Reshape":return[n.reshape(I("x",e,t,r),I("shape",e,t,r))];case"EnsureShape":return[n.ensureShape(I("x",e,t,r),I("shape",e,t,r))];case"MirrorPad":return[n.mirrorPad(I("x",e,t,r),I("padding",e,t,r),I("mode",e,t,r))];case"PadV2":case"Pad":return[n.pad(I("x",e,t,r),I("padding",e,t,r),I("constantValue",e,t,r))];case"SpaceToBatchND":{let a=I("blockShape",e,t,r),s=I("paddings",e,t,r);return[n.spaceToBatchND(I("x",e,t,r),a,s)]}case"BatchToSpaceND":{let a=I("blockShape",e,t,r),s=I("crops",e,t,r);return[n.batchToSpaceND(I("x",e,t,r),a,s)]}case"DepthToSpace":{let a=I("blockSize",e,t,r),s=I("dataFormat",e,t,r).toUpperCase();return[n.depthToSpace(I("x",e,t,r),a,s)]}case"BroadcastTo":return[n.broadcastTo(I("x",e,t,r),I("shape",e,t,r))];case"BroadcastArgs":return[n.broadcastArgs(I("s0",e,t,r),I("s1",e,t,r))];default:throw TypeError(`Node type ${e.op} is not implemented`)}};function n1(e,t,r,n,a=W){let s=((i,o,l)=>{switch(i.category){case"arithmetic":return a(()=>Sj(i,o,l));case"basic_math":return a(()=>Nj(i,o,l));case"control":return Aj(i,o,l);case"convolution":return a(()=>Fj(i,o,l));case"creation":return a(()=>Rj(i,o,l));case"dynamic":return Dj(i,o,l);case"evaluation":return a(()=>Mj(i,o,l));case"image":return a(()=>Pj(i,o,l));case"graph":return a(()=>Oj(i,o,l));case"logical":return a(()=>Bj(i,o,l));case"matrices":return a(()=>Wj(i,o,l));case"normalization":return a(()=>Uj(i,o,l));case"ragged":return a(()=>Vj(i,o,l));case"reduction":return a(()=>Gj(i,o,l));case"slice_join":return a(()=>Hj(i,o,l));case"sparse":return a(()=>jj(i,o,l));case"spectral":return a(()=>qj(i,o,l));case"string":return a(()=>Kj(i,o,l));case"transformation":return a(()=>Xj(i,o,l));case"hash_table":return zj(i,o,l,n);case"custom":let p=D2(i.op);if(p&&p.customExecutor)return p.customExecutor(new Ij(i,o,l));throw TypeError(`Custom op ${i.op} is not registered.`);default:throw TypeError(`Unknown op '${i.op}'. File an issue at https://github.com/tensorflow/tfjs/issues so we can add it, or register a custom execution with tf.registerOp()`)}})(e,t,r);return k.isPromise(s)?s.then(i=>[].concat(i)):[].concat(s)}var a1=class{constructor(e={},t={},r={},n={},a){this.weightMap=e,this.tensorArrayMap=t,this.tensorListMap=r,this.functionMap=n,this.parseNodeNameCache=a,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 r=this.contexts.slice(0,this.contexts.length-t);e.push(this.contextIdforContexts(r))}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 s1(e,t,r,n){let a=new Set,s=[],i=null,o=null,l=new Set,p=new Set(Object.keys(e).map(h=>Vr(h)[0]));n=n||[];let u=new Set(n.map(h=>Vr(h.name)[0])),d=[...t];for(;d.length>0;){let h=d.pop();if((Qs(h)||nq(h)||aq(h))&&i==null&&(i=h,o=i.children.map(c=>c.name).filter(c=>a.has(c))),a.add(h.name),r[h.name]==null&&!p.has(h.name)&&!u.has(h.name)){if(h.inputs.length===0){s.push(h.name);continue}h.inputs.forEach(c=>{l.has(c.name)||(l.add(c.name),d.push(c))})}}return{inputs:e,outputs:t,usedNodes:a,missingInputs:s,dynamicNode:i,syncInputs:o}}function Zj(e,t){let{usedNodes:r,inputs:n}=t,a=Object.keys(n).map(g=>Vr(g)[0]).map(g=>e.nodes[g]),s=e.initNodes||[],i=g=>r.has(typeof g=="string"?g:g.name);function o(g){return[...new Map(g.map(y=>[y.name,y])).values()]}let l=o([...a,...e.weights,...s]).filter(i),p=o([...l,...Object.values(e.nodes)]).filter(i),u=new Map(p.map(g=>[g.name,g])),d={};for(let g of p){d[g.name]=d[g.name]||0;for(let y of g.children)i(y)||(d[y.name]=Number.POSITIVE_INFINITY),d[y.name]=(d[y.name]||0)+1}let h=Object.entries(d).filter(([,g])=>g===0).map(([g])=>g),c=[...h];for(;h.length>0;){let g=h.pop(),y=u.get(g);for(let b of y.children.filter(i))--d[b.name]===0&&(c.push(b.name),h.push(b.name))}let f=c.map(g=>u.get(g)),m=Jj(f,l);return Yj(m,l),m}function Jj(e,t){let r=new Map(e.map(s=>[s.name,s])),n=t.map(s=>s.name),a=new Set(n);for(;n.length>0;){let s=n.pop(),i=r.get(s);for(let o of i.children)!r.has(o.name)||a.has(o.name)||(a.add(o.name),n.push(o.name))}return e.filter(s=>a.has(s.name))}var Lh=class extends Error{constructor(e){super(`NodesExecutionOrderError: ${e}`)}};function Yj(e,t){let r=new Map(e.map((o,l)=>[o.name,l])),n=new Set(t.map(o=>o.name)),a=o=>n.has(typeof o=="string"?o:o.name),s=new Set(e.map(o=>o.name)),i=o=>s.has(typeof o=="string"?o:o.name);for(let o of e){for(let l of o.children.filter(i)){if(!r.has(l.name))throw new Lh(`Child ${l.name} of node ${o.name} is unreachable.`);if(r.get(o.name)>r.get(l.name))throw new Lh(`Node ${o.name} is scheduled to run after its child ${l.name}.`)}if(!a(o))for(let l of o.inputs){if(!r.has(l.name))throw new Lh(`Input ${l.name} of node ${o.name} is unreachable.`);if(r.get(l.name)>r.get(o.name))throw new Lh(`Node ${o.name} is scheduled to run before its input ${l.name}.`)}}}function Qj(e){let t=new Map(e.map((o,l)=>[o.name,l])),r=Number.MAX_SAFE_INTEGER,n=e.map((o,l)=>Qs(o)?r:l),a=o=>{let l=n[t.get(o.name)];return l??-1},s=e.map((o,l)=>o.children.map(a).reduce((p,u)=>Math.max(p,u),n[l])),i=new Map;for(let o=0;o<e.length;++o){let l=s[o];if(l===r)continue;let p=e[o],u=e[l];i.has(u.name)||i.set(u.name,[]),i.get(u.name).push(p)}return i}var eq=new Set(["Switch","Merge","Enter","Exit","NextIteration","StatelessIf","StatelessWhile","if","While"]),tq=new Set(["NonMaxSuppressionV2","NonMaxSuppressionV3","NonMaxSuppressionV5","Where"]),rq=new Set(["HashTable","HashTableV2","LookupTableImport","LookupTableImportV2","LookupTableFind","LookupTableFindV2","LookupTableSize","LookupTableSizeV2"]);function Qs(e){return eq.has(e.op)}function nq(e){return tq.has(e.op)}function aq(e){return rq.has(e.op)}var i1=class r_{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(t){let r=Object.keys(t).map(n=>t[n].map(a=>a.id));this._weightIds=[].concat(...r),this._weightMap=t}set resourceManager(t){this._resourceManager=t}get inputs(){return this._inputs.map(t=>({name:t.name,shape:t.attrParams.shape?t.attrParams.shape.value:void 0,dtype:t.attrParams.dtype?t.attrParams.dtype.value:void 0}))}get outputs(){return this._outputs.map(t=>({name:t.name,shape:t.attrParams.shape?t.attrParams.shape.value:void 0,dtype:t.attrParams.dtype?t.attrParams.dtype.value:void 0}))}get inputNodes(){return this._inputs.map(t=>t.signatureKey||t.name)}get outputNodes(){return this._outputs.map(t=>{let r=t.signatureKey||t.name;return t.defaultOutput?`${r}:${t.defaultOutput}`:r})}get functions(){return Object.keys(this._functions).reduce((t,r)=>(t[r]=this._functions[r].signature,t),{})}constructor(t,r){this.graph=t,this.parent=r,this.compiledMap=new Map,this.parseNodeNameCache=new Map,this._weightMap={},this.SEPARATOR=",",this._functions={},this._functionExecutorMap={},this.keepIntermediateTensors=!1,this._outputs=t.outputs,this._inputs=t.inputs,this._initNodes=t.initNodes,this._signature=t.signature,this._functions=t.functions,t.functions!=null&&Object.keys(t.functions).forEach(n=>{this._functionExecutorMap[n]=new r_(t.functions[n],this)})}getCompilationKey(t,r){let n=t.map(s=>s.name).sort(),a=r.map(s=>s.name).sort();return n.join(this.SEPARATOR)+"--"+a.join(this.SEPARATOR)}compile(t,r){let n=s1(t,r,this.weightMap,this._initNodes),{missingInputs:a,dynamicNode:s,syncInputs:i}=n;if(s!=null)throw new Error(`This execution contains the node '${s.name}', which has the dynamic op '${s.op}'. Please use model.executeAsync() instead. Alternatively, to avoid the dynamic ops, specify the inputs [${i}]`);if(a.length>0){let p=r.map(d=>d.name),u=Object.keys(t);throw new Error(`Cannot compute the outputs [${p}] from the provided inputs [${u}]. Missing the following inputs: [${a}]`)}let o=Zj(this.graph,n),l=Qj(o);return{orderedNodes:o,nodeLiveUntilMap:l}}cloneAndKeepTensor(t){if(t==null)return null;let r=t.clone();return Pt(r),r}cloneTensorList(t){return t?t.map(r=>this.cloneAndKeepTensor(r)):null}cloneTensorMap(t){return Object.fromEntries(Object.entries(t).map(([r,n])=>[r,this.cloneTensorList(n)]))}execute(t,r){this.disposeIntermediateTensors(),t=this.mapInputs(t);let n=Object.keys(t).sort();this.checkInputs(t),this.checkInputShapeAndType(t),r=this.mapOutputs(r),this.checkOutputs(r);let a=n.map(h=>this.graph.nodes[Vr(h)[0]]),s=r.map(h=>Vr(h)[0]),i=new Set(s),o=s.map(h=>this.graph.nodes[h]);o.length===0&&(o=this._outputs);let l=this.getCompilationKey(a,o),p=this.compiledMap.get(l);p==null&&(p=this.compile(t,o),this.compiledMap.set(l,p));try{this.keepIntermediateTensors=j().getBool("KEEP_INTERMEDIATE_TENSORS")}catch(h){this.keepIntermediateTensors=!1,console.warn(h.message)}let u={},d={};return W(()=>{let h=new a1(this.weightMap,u,d,this.functionExecutorMap,this.parseNodeNameCache),c=Object.assign({},this.weightMap);this.keepIntermediateTensors&&(this.clonedTensorsMap=this.cloneTensorMap(this.weightMap)),Object.keys(t).forEach(y=>{let[b,x]=Vr(y,h),v=[];v[x]=t[y],c[b]=v,this.keepIntermediateTensors&&(this.clonedTensorsMap[b]=this.cloneTensorList(v))});let f=this.getFrozenTensorIds(c),{orderedNodes:m,nodeLiveUntilMap:g}=p;for(let y of m){if(c[y.name])continue;let b=n1(y,c,h,this._resourceManager);if(k.isPromise(b))throw new Error(`The execution of the op '${y.op}' returned a promise. Please use model.executeAsync() instead.`);c[y.name]=b,this.keepIntermediateTensors&&(this.clonedTensorsMap[y.name]=this.cloneTensorList(b)),this.checkTensorForDisposalWithNodeLiveUntilInfo(y,c,h,f,i,g.get(y.name))}return this.parent==null&&h.dispose(f),r.map(y=>ar(y,c,h))})}getFrozenTensorIds(t){let r=[].concat.apply([],Object.keys(t).map(n=>t[n]).map(n=>n.map(a=>a.id)));return new Set(r)}checkTensorForDisposal(t,r,n,a,s,i,o){if(!(Qs(r)||i.has(t))){for(let l of n[t])l!=null&&(o[l.id]=(o[l.id]||0)+r.children.length);for(let l of r.inputs){if(Qs(l))continue;let p=Y0(l.name,n,a);if(p!=null)for(let u of p){if(!u||u.kept||s.has(u.id))continue;let d=o[u.id];d===1?(u.dispose(),delete o[u.id]):d!=null&&o[u.id]--}}}}checkTensorForDisposalWithNodeLiveUntilInfo(t,r,n,a,s,i){function o(l){return Qs(l)||s.has(l.name)}if(!(Qs(t)||i==null))for(let l of i){if(o(l))continue;let p=Y0(l.name,r,n);for(let u of p)!u||u.kept||a.has(u.id)||u.dispose()}}async executeAsync(t,r){return this._executeAsync(t,r)}disposeIntermediateTensors(){this.clonedTensorsMap&&(Object.values(this.clonedTensorsMap).forEach(t=>{for(let r of t)r&&!r.isDisposed&&r.dispose()}),this.clonedTensorsMap=null)}getIntermediateTensors(){return this.clonedTensorsMap}async _executeAsync(t,r,n=!1,a={},s={}){this.disposeIntermediateTensors(),n||(t=this.mapInputs(t),this.checkInputs(t),this.checkInputShapeAndType(t),r=this.mapOutputs(r),this.checkOutputs(r));try{this.keepIntermediateTensors=j().getBool("KEEP_INTERMEDIATE_TENSORS")}catch(h){this.keepIntermediateTensors=!1,console.warn(h.message)}let i=new a1(this.weightMap,a,s,this.functionExecutorMap,this.parseNodeNameCache);this.keepIntermediateTensors&&(this.clonedTensorsMap=this.cloneTensorMap(this.weightMap));let o=await this.executeWithControlFlow(t,i,r,n),l=r.map(h=>ar(h,o,i)),p=l.map(h=>h.id),u=Object.keys(t).map(h=>t[h].id),d=new Set([...p,...u,...this.weightIds]);return Object.values(o).forEach(h=>{h.forEach(c=>{c&&!c.isDisposed&&!d.has(c.id)&&c.dispose()})}),this.parent==null&&i.dispose(d),l}async executeFunctionAsync(t,r,n){let a=t.reduce((s,i,o)=>(s[this.inputs[o].name]=i,s),{});return this._executeAsync(a,this.outputNodes,!0,r,n)}async executeWithControlFlow(t,r,n,a){let s=Object.keys(t),i=s.map(v=>this.graph.nodes[Vr(v)[0]]),o=n.map(v=>Vr(v)[0]),l=new Set(o),p=o.map(v=>this.graph.nodes[v]);p.length===0&&(p=this._outputs);let{usedNodes:u,missingInputs:d,dynamicNode:h,syncInputs:c}=s1(t,p,this.weightMap,this._initNodes),f=[...i,...this.graph.weights,...this._initNodes||[]].map(v=>({node:v,contexts:r.currentContext})),m=Object.assign({},this.weightMap);Object.keys(t).forEach(v=>{let[w,N]=Vr(v),T=[];T[N]=t[v],m[w]=T});let g={},y=this.getFrozenTensorIds(m),b={};for(;f.length>0;){let v=this.processStack(i,f,r,m,b,y,l,g,u);await Promise.all(v)}h==null&&!a&&console.warn("This model execution did not contain any nodes with control flow or dynamic output shapes. You can use model.execute() instead.");let x=p.filter(v=>!Qs(v)&&!ar(v.name,m,r)).map(v=>v.name);if(x.length>0){let v="";throw h!=null&&(v=`Alternatively, to avoid the dynamic ops, use model.execute() and specify the inputs [${c}]`),new Error(`Cannot compute the outputs [${x}] from the provided inputs [${s}]. Consider providing the following inputs: [${d}]. ${v}`)}return m}processStack(t,r,n,a,s,i,o,l,p){let u=[];for(;r.length>0;){let d=r.pop();n.currentContext=d.contexts;let h="";if(d.node.op==="Enter"&&I("isConstant",d.node,a,n)&&([h]=Ia(d.node.name,n)),a[d.node.name]==null){let c=n1(d.node,a,n,this._resourceManager);h||([h]=Ia(d.node.name,n));let f=n.currentContext;k.isPromise(c)?u.push(c.then(m=>(a[h]=m,this.keepIntermediateTensors&&(this.clonedTensorsMap[h]=this.cloneTensorList(m)),n.currentContext=f,this.checkTensorForDisposal(h,d.node,a,n,i,o,l),this.processChildNodes(d.node,r,n,a,s,p),m))):(a[h]=c,this.keepIntermediateTensors&&(this.clonedTensorsMap[h]=this.cloneTensorList(c)),this.checkTensorForDisposal(h,d.node,a,n,i,o,l),this.processChildNodes(d.node,r,n,a,s,p))}else this.processChildNodes(d.node,r,n,a,s,p)}return u}processChildNodes(t,r,n,a,s,i){t.children.forEach(o=>{let[l]=Ia(o.name,n);s[l]||!i.has(o.name)||(o.op==="Merge"?o.inputNames.some(p=>!!ar(p,a,n))&&(s[l]=!0,r.push({contexts:n.currentContext,node:o})):o.inputNames.every(p=>!!ar(p,a,n))&&(s[l]=!0,r.push({contexts:n.currentContext,node:o})))})}dispose(){Object.keys(this.weightMap).forEach(t=>this.weightMap[t].forEach(r=>r.dispose()))}checkInputShapeAndType(t){Object.keys(t).forEach(r=>{let n=t[r],[a]=Vr(r),s=this.graph.nodes[a];if(s.attrParams.shape&&s.attrParams.shape.value){let i=s.attrParams.shape.value,o=i.length===n.shape.length&&n.shape.every((l,p)=>i[p]===-1||i[p]===l);k.assert(o,()=>`The shape of dict['${s.name}'] provided in model.execute(dict) must be [${i}], but was [${n.shape}]`)}s.attrParams.dtype&&s.attrParams.dtype.value&&k.assert(n.dtype===s.attrParams.dtype.value,()=>`The dtype of dict['${s.name}'] provided in model.execute(dict) must be ${s.attrParams.dtype.value}, but was ${n.dtype}`)})}mapInputs(t){var r,n;let a={};for(let s in t){let i=(n=(r=this._signature)===null||r===void 0?void 0:r.inputs)===null||n===void 0?void 0:n[s];i!=null?a[i.name]=t[s]:a[s]=t[s]}return a}checkInputs(t){let r=Object.keys(t).filter(n=>{let[a]=Vr(n);return this.graph.nodes[a]==null});if(r.length>0)throw new Error(`The dict provided in model.execute(dict) has keys: [${r}] that are not part of graph`)}mapOutputs(t){return t.map(r=>{var n,a;let s=(a=(n=this._signature)===null||n===void 0?void 0:n.outputs)===null||a===void 0?void 0:a[r];return s!=null?s.name:r},{})}checkOutputs(t){t.forEach(r=>{let[n]=Vr(r);if(!this.graph.nodes[n])throw new Error(`The output '${r}' is not found in the graph`)})}},sq=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]}},iq="?tfjs-format=file",oq="model.json",Fv=class{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}get modelStructuredOutputKeys(){return this.structuredOutputKeys}constructor(e,t={},r=or){this.modelUrl=e,this.loadOptions=t,this.version="n/a",this.io=r,t==null&&(this.loadOptions={}),this.resourceManager=new sq}findIOHandler(){let e=this.modelUrl;if(e.load!=null)this.handler=e;else if(this.loadOptions.requestInit!=null)this.handler=this.io.browserHTTPRequest(e,this.loadOptions);else{let t=this.io.getLoadHandlers(e,this.loadOptions);if(t.length===0)t.push(this.io.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]}}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=this.handler.load();return k.isPromise(e)?e.then(t=>t.getWeightStream==null?this.loadSync(t):this.loadStreaming(t)):this.loadSync(e)}loadSync(e){let t=this.io.decodeWeights(e.weightData,e.weightSpecs);return this.loadWithWeightMap(e,t)}async loadStreaming(e){if(e.getWeightStream==null)throw new Error("Model artifacts missing streamWeights function");let t=await sI(e.getWeightStream(),e.weightSpecs);return this.loadWithWeightMap(e,t)}loadWithWeightMap(e,t){this.artifacts=e;let r=this.artifacts.modelTopology,n=this.artifacts.signature;if(this.artifacts.userDefinedMetadata!=null){let a=this.artifacts.userDefinedMetadata;a.signature!=null&&(n=a.signature),a.structuredOutputKeys!=null&&(this.structuredOutputKeys=a.structuredOutputKeys)}if(this.signature=n,this.version=`${r.versions.producer}.${r.versions.minConsumer}`,this.executor=new i1(Q0.Instance.transformGraph(r,this.signature)),this.executor.weightMap=this.convertTensorMapToTensorsMap(t),this.executor.resourceManager=this.resourceManager,e.modelInitializer!=null&&e.modelInitializer.node!=null){let a=Q0.Instance.transformGraph(e.modelInitializer);this.initializer=new i1(a),this.initializer.weightMap=this.executor.weightMap,this.initializer.resourceManager=this.resourceManager,this.initializerSignature=e.initializerSignature}return!0}async save(e,t){if(typeof e=="string"){let r=this.io.getSaveHandlers(e);if(r.length===0)throw new Error(`Cannot find any save handlers for URL '${e}'`);if(r.length>1)throw new Error(`Found more than one (${r.length}) save handlers for URL '${e}'`);e=r[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)}addStructuredOutputNames(e){if(this.structuredOutputKeys){let t=e instanceof ze?[e]:e,r={};return t.forEach((n,a)=>r[this.structuredOutputKeys[a]]=n),r}return e}predict(e,t){let r=this.execute(e,this.outputNodes);return this.addStructuredOutputNames(r)}async predictAsync(e,t){let r=await this.executeAsync(e,this.outputNodes);return this.addStructuredOutputNames(r)}normalizeInputs(e){var t;if(!(e instanceof ze)&&!Array.isArray(e)){let a=(t=this.signature)===null||t===void 0?void 0:t.inputs;if(a!=null)for(let s in a){let i=a[s];i.resourceId!=null&&(e[s]=this.resourceIdToCapturedInput[i.resourceId])}return e}e=Array.isArray(e)?e:[e];let r=Object.keys(this.resourceIdToCapturedInput).length;if(e.length+r!==this.inputNodes.length)throw new Error(`Input tensor count mismatch, the graph model has ${this.inputNodes.length-r} non-resource placeholders, while there are ${e.length} input tensors provided.`);let n=0;return this.inputNodes.reduce((a,s)=>{var i,o,l;let p=(l=(o=(i=this.signature)===null||i===void 0?void 0:i.inputs)===null||o===void 0?void 0:o[s])===null||l===void 0?void 0:l.resourceId;return p!=null?a[s]=this.resourceIdToCapturedInput[p]:a[s]=e[n++],a},{})}normalizeOutputs(e){return e=e||this.outputNodes,Array.isArray(e)?e:[e]}executeInitializerGraph(){return this.initializer==null?[]:this.initializerSignature==null?this.initializer.execute({},[]):this.initializer.execute({},Object.keys(this.initializerSignature.outputs))}async executeInitializerGraphAsync(){return this.initializer==null?[]:this.initializerSignature==null?this.initializer.executeAsync({},[]):this.initializer.executeAsync({},Object.keys(this.initializerSignature.outputs))}setResourceIdToCapturedInput(e){if(this.resourceIdToCapturedInput={},this.initializerSignature){let t=this.initializerSignature.outputs,r=Object.keys(t);for(let n=0;n<r.length;n++){let a=r[n],s=t[a];this.resourceIdToCapturedInput[s.resourceId]=e[n]}}}execute(e,t){this.resourceIdToCapturedInput==null&&this.setResourceIdToCapturedInput(this.executeInitializerGraph()),e=this.normalizeInputs(e),t=this.normalizeOutputs(t);let r=this.executor.execute(e,t);return r.length>1?r:r[0]}async executeAsync(e,t){this.resourceIdToCapturedInput==null&&this.setResourceIdToCapturedInput(await this.executeInitializerGraphAsync()),e=this.normalizeInputs(e),t=this.normalizeOutputs(t);let r=await this.executor.executeAsync(e,t);return r.length>1?r:r[0]}getIntermediateTensors(){return this.executor.getIntermediateTensors()}disposeIntermediateTensors(){this.executor.disposeIntermediateTensors()}convertTensorMapToTensorsMap(e){return Object.keys(e).reduce((t,r)=>(t[r]=[e[r]],t),{})}dispose(){this.executor.dispose(),this.initializer&&(this.initializer.dispose(),this.resourceIdToCapturedInput&&Ce(this.resourceIdToCapturedInput)),this.resourceManager.dispose()}};async function lq(e,t={},r=or){if(e==null)throw new Error("modelUrl in loadGraphModel() cannot be null. Please provide a url or an IOHandler that loads the model");t==null&&(t={}),t.fromTFHub&&typeof e=="string"&&(e=pq(e));let n=new Fv(e,t,r);return await n.load(),n}function uq(e){if(e==null)throw new Error("modelUrl in loadGraphModelSync() cannot be null. Please provide model artifacts or an IOHandler that loads the model");let t;if(e instanceof Array){let[n,a]=e;if(!n)throw new Error("modelJSON must be the first element of the array");if(!a||!(a instanceof ArrayBuffer))throw new Error("An ArrayBuffer of weights must be the second element of the array");if(!("modelTopology"in n))throw new Error("Model JSON is missing 'modelTopology'");if(!("weightsManifest"in n))throw new Error("Model JSON is missing 'weightsManifest'");let s=or.getWeightSpecs(n.weightsManifest),i=or.getModelArtifactsForJSONSync(n,s,a);t=or.fromMemorySync(i)}else if("load"in e)t=e;else if("modelTopology"in e&&"weightSpecs"in e&&"weightData"in e)t=or.fromMemorySync(e);else throw new Error("Unknown model format");let r=new Fv(t);return r.load(),r}function pq(e){return e.endsWith("/")||(e=e+"/"),`${e}${oq}${iq}`}var dq="4.22.0",n_={};Ee(n_,{CSVDataset:()=>f_,Dataset:()=>ip,FileDataSource:()=>w_,TextLineDataset:()=>c_,URLDataSource:()=>k_,array:()=>Dq,csv:()=>qq,func:()=>Kq,generator:()=>Xq,microphone:()=>Jq,version_data:()=>Yq,webcam:()=>Zq,zip:()=>Mq});var hq=_s(Kc()),cq=_s(Kc());function fq(e,t){return Ac(e,t)}function Ac(e,t,r=new Map,n=new Set){if(e==null)return null;if(typeof Blob=="function"&&e instanceof Blob)return e.slice();if(n.has(e))throw new Error("Circular references are not supported.");if(r.has(e))return r.get(e);let a=t(e);if(a.recurse&&a.value!==null)throw new Error("A deep map function may not return both a value and recurse=true.");if(a.recurse)if(Pl(e)){let s=Array.isArray(e)?[]:{};n.add(e);for(let i in e){let o=e[i],l=Ac(o,t,r,n);s[i]=l}return n.delete(e),e.__proto__&&(s.__proto__=e.__proto__),s}else throw new Error(`Can't recurse into non-iterable type: ${e}`);else return r.set(e,a.value),a.value}function mq(e,t=s_){return a_(e,t)}function a_(e,t,r=new Set){let n=e[0];if(r.has(n))throw new Error("Circular references are not supported.");let a=t(e);if(a.recurse&&a.value!==null)throw new Error("A deep zip function may not return both a value and recurse=true.");if(a.recurse)if(Pl(n)){let s=Array.isArray(n)?[]:{};r.add(n);for(let i in n){let o=e.map(p=>p[i]),l=a_(o,t,r);s[i]=l}return r.delete(n),s}else throw new Error(`Can't recurse into non-iterable type: ${n}`);else return a.value}function s_(e){return e===null?null:Pl(e[0])?{value:null,recurse:!0}:{value:e,recurse:!1}}async function i_(e,t){let r=new Map;Ac(e,t,r);for(let n of Array.from(r.keys())){let a=r.get(n);if(k.isPromise(a)){let s=await a;r.set(n,s)}}return Ac(e,t,r)}function Pl(e){let t=!1;if(j().get("IS_BROWSER"))t=e instanceof TextDecoder;else{let{StringDecoder:r}=Nk();t=e instanceof r}return e!=null&&!ArrayBuffer.isView(e)&&(Array.isArray(e)||typeof e=="object"&&!(e instanceof ze)&&!(e instanceof Promise)&&!t)}function gq(e){return e==null||yq(e)||Array.isArray(e)||typeof e=="object"&&e instanceof ze||k.isTypedArray(e)}function yq(e){return e===null||typeof e!="object"&&typeof e!="function"}function bq(e){return fq(e,xq)}function xq(e){return e instanceof ze?{value:e.clone(),recurse:!1}:Pl(e)?{value:null,recurse:!0}:{value:e,recurse:!1}}var o_=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),r=this.get(t);return this.set(t,this.pop()),r}},l_=class u_ extends o_{constructor(){super(u_.INITIAL_CAPACITY)}isFull(){return!1}push(t){super.isFull()&&this.expand(),super.push(t)}unshift(t){super.isFull()&&this.expand(),super.unshift(t)}expand(){let t=this.capacity*2,r=new Array(t),n=this.length();for(let a=0;a<n;a++)r[a]=this.get(this.wrap(this.begin+a));this.data=r,this.capacity=t,this.doubledCapacity=2*this.capacity,this.begin=0,this.end=n}};l_.INITIAL_CAPACITY=32;function p_(e){return new kq(e)}function Rv(e){return new Iq(e)}function vq(e,t){return new d_(e,t)}function wq(e,t=as.FAIL){return new Fq(e,t)}var Qt=class{async toArray(){let e=[],t=await this.next();for(;!t.done;)e.push(t.value),t=await this.next();return e}async toArrayForTest(){let e=this.prefetch(100),t=[],r=await e.next();for(;!r.done;)t.push(r.value),r=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(),r=e(t.value);for(;!t.done&&r;)t=await this.next(),r=e(t.value)}handleErrors(e){return new $q(this,e)}filter(e){return new Cq(this,e)}map(e){return new Eq(this,e)}mapAsync(e){return new o1(this,e)}serialMapAsync(e){return new o1(this,e).serial()}flatmap(e){return new Aq(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 Tq(this,e,t)}columnMajorBatch(e,t=!0,r=s_){return this.rowMajorBatch(e,t).map(n=>mq(n,r))}concatenate(e,t){return new d_(p_([this,e]),t)}take(e){return e<0||e==null?this:new _q(this,e)}skip(e){return e<0||e==null?this:new Nq(this,e)}prefetch(e){return new h_(this,e)}shuffle(e,t){return new Rq(this,e,t)}serial(){return new Sq(this)}},kq=class extends Qt{constructor(e){super(),this.items=e,this.trav=0}summary(){return`Array of ${this.items.length} items`}async next(){if(this.trav>=this.items.length)return{value:null,done:!0};let e=this.items[this.trav];return this.trav++,{value:bq(e),done:!1}}},Iq=class extends Qt{constructor(e){super(),this.nextFn=e}summary(){return"Function call"}async next(){try{return this.nextFn()}catch(e){throw e.message=`Error thrown while iterating through a dataset: ${e.message}`,e}}},Sq=class extends Qt{constructor(e){super(),this.upstream=e,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> Serial`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){return this.upstream.next()}},Nq=class extends Qt{constructor(e,t){super(),this.upstream=e,this.maxCount=t,this.count=0,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> Skip`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){for(;this.count++<this.maxCount;){let e=await this.upstream.next();if(e.done)return e;Ce(e.value)}return this.upstream.next()}},_q=class extends Qt{constructor(e,t){super(),this.upstream=e,this.maxCount=t,this.count=0}summary(){return`${this.upstream.summary()} -> Take`}async next(){return this.count++>=this.maxCount?{value:null,done:!0}:this.upstream.next()}},Tq=class extends Qt{constructor(e,t,r=!0){super(),this.upstream=e,this.batchSize=t,this.enableSmallLastBatch=r,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}}},Cq=class extends Qt{constructor(e,t){super(),this.upstream=e,this.predicate=t,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> Filter`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){for(;;){let e=await this.upstream.next();if(e.done||this.predicate(e.value))return e;Ce(e.value)}}},Eq=class extends Qt{constructor(e,t){super(),this.upstream=e,this.transform=t}summary(){return`${this.upstream.summary()} -> Map`}async next(){let e=await this.upstream.next();if(e.done)return{value:null,done:!0};let t=Mn.getTensorsInContainer(e.value),r=this.transform(e.value),n=Mn.getTensorsInContainer(r);for(let a of t)Mn.isTensorInList(a,n)||a.dispose();return{value:r,done:!1}}},$q=class extends Qt{constructor(e,t){super(),this.upstream=e,this.handler=t,this.count=0,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> handleErrors`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){for(;;)try{return await this.upstream.next()}catch(e){if(!this.handler(e))return{value:null,done:!0}}}},o1=class extends Qt{constructor(e,t){super(),this.upstream=e,this.transform=t}summary(){return`${this.upstream.summary()} -> AsyncMap`}async next(){let e=await this.upstream.next();if(e.done)return{value:null,done:!0};let t=Mn.getTensorsInContainer(e.value),r=await this.transform(e.value),n=Mn.getTensorsInContainer(r);for(let a of t)Mn.isTensorInList(a,n)||a.dispose();return{value:r,done:!1}}},Dv=class extends Qt{constructor(){super(),this.outputQueue=new l_,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}}},Aq=class extends Dv{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),r=this.transform(e.value),n=Mn.getTensorsInContainer(r);this.outputQueue.pushAll(r);for(let a of t)Mn.isTensorInList(a,n)||a.dispose();return!0}},d_=class extends Qt{constructor(e,t){super(),this.baseErrorHandler=t,this.lastRead=null,this.iterator=null,this.moreIterators=e}summary(){return"TODO: fill in upstream of chained summaries -> Chained"}async next(){return this.lastRead=this.readFromChain(this.lastRead),this.lastRead}async readFromChain(e){if(await e,this.iterator==null){let r=await this.moreIterators.next();if(r.done)return{value:null,done:!0};this.iterator=r.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}},as;(function(e){e[e.FAIL=0]="FAIL",e[e.SHORTEST=1]="SHORTEST",e[e.LONGEST=2]="LONGEST"})(as||(as={}));var Fq=class extends Qt{constructor(e,t=as.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,r=0;function n(s){return s instanceof Qt?{value:s.next().then(i=>(t++,i.done&&r++,i.value)),recurse:!1}:{value:null,recurse:!0}}let a=await i_(this.iterators,n);if(t===r)return{value:null,done:!0};if(r>0)switch(this.mismatchMode){case as.FAIL:throw new Error(`Zipped streams should have the same length. Mismatched at element ${this.count}.`);case as.SHORTEST:return{value:null,done:!0};case as.LONGEST:}return this.count++,{value:a,done:!1}}async next(){return this.currentPromise=this.nextState(this.currentPromise),this.currentPromise}},h_=class extends Qt{constructor(e,t){super(),this.upstream=e,this.bufferSize=t,this.buffer=new o_(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()}},Rq=class extends h_{constructor(e,t,r){super(e,t),this.upstream=e,this.windowSize=t,this.upstreamExhausted=!1,this.random=cq.alea(r||k.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}}},ip=class{constructor(){this.size=null}batch(e,t=!0){let r=this;k.assert(e>0,()=>`batchSize needs to be positive, but it is
${e}`);let n;return this.size===1/0||this.size==null?n=this.size:t?n=Math.ceil(this.size/e):n=Math.floor(this.size/e),Ur(async()=>(await r.iterator()).columnMajorBatch(e,t,Oq),n)}concatenate(e){let t=this,r;return this.size===1/0||e.size===1/0?r=1/0:this.size!=null&&e.size!=null?r=this.size+e.size:r=null,Ur(async()=>(await t.iterator()).concatenate(await e.iterator()),r)}filter(e){let t=this,r;return this.size===1/0?r=1/0:r=null,Ur(async()=>(await t.iterator()).filter(n=>W(()=>e(n))),r)}async forEachAsync(e){return(await this.iterator()).forEachAsync(e)}map(e){let t=this;return Ur(async()=>(await t.iterator()).map(r=>W(()=>e(r))),this.size)}mapAsync(e){let t=this;return Ur(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 Ur(async()=>(await t.iterator()).prefetch(e),this.size)}repeat(e){let t=this,r;return this.size!=null&&e>0?r=this.size*e:e===0?r=0:this.size!=null&&(e===void 0||e<0)?r=1/0:r=null,Ur(async()=>{let n=Rv(async()=>({value:await t.iterator(),done:!1}));return vq(n.take(e))},r)}skip(e){let t=this,r;return this.size!=null&&e>=0&&this.size>=e?r=this.size-e:this.size!=null&&(this.size<e||e===void 0||e<0)?r=0:r=null,Ur(async()=>(await t.iterator()).skip(e),r)}shuffle(e,t,r=!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,a=hq.alea(t||k.now().toString());return Ur(async()=>{let s=a.int32();return r&&(s+=a.int32()),(await n.iterator()).shuffle(e,s.toString())},this.size)}take(e){let t=this,r;return this.size!=null&&this.size>e?r=e:this.size!=null&&this.size<=e?r=this.size:r=null,Ur(async()=>(await t.iterator()).take(e),r)}async toArray(){if(this.size===1/0)throw new Error("Can not convert infinite data stream to array.");return(await this.iterator()).toArray()}async toArrayForTest(){if(this.size===1/0)throw new Error("Can not convert infinite data stream to array.");return(await this.iterator()).toArrayForTest()}};ip.MAX_BUFFER_SIZE=1e4;function Ur(e,t=null){return new class extends ip{constructor(){super(...arguments),this.size=t}async iterator(){return e()}}}function Dq(e){return Ur(async()=>p_(e),e.length)}function Mq(e){if(!Pl(e))throw new Error("The argument to zip() must be an object or array.");let t;if(Array.isArray(e))for(let r=0;r<e.length;r++)t=t==null?e[r].size:Math.min(t,e[r].size);else if(e instanceof Object)for(let r in e)t=t==null?e[r].size:Math.min(t,e[r].size);return Ur(async()=>{let r=await i_(e,n=>{if(n instanceof ip)return{value:n.iterator(),recurse:!1};if(Pl(n))return{value:null,recurse:!0};throw new Error("Leaves of the structure passed to zip() must be Datasets, not primitives.")});return wq(r,as.SHORTEST)},t)}function Oq(e){if(e===null)return null;let t=e[0];return gq(t)?{value:Lq(e),recurse:!1}:{value:null,recurse:!0}}function Lq(e){if(e.length===0)throw new Error("Can't make a batch of zero elements.");return e[0]instanceof ze?Mt(e):yr(e)}var c_=class extends ip{constructor(e){super(),this.input=e}async iterator(){return(await this.input.iterator()).decodeUTF8().split(`
`).map(e=>(e.endsWith("\r")&&(e=e.slice(0,-1)),e))}},zh='"',Np=Symbol("out"),l1=Symbol("field"),Ph=Symbol("quote"),Hm=Symbol("quoteafterquote"),u1=Symbol("quoteinquote"),f_=class extends ip{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&&k.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,a)=>(n[a]=n[a]+1||1,n),{}),r=Object.keys(t).filter(n=>t[n]>1);if(k.assert(r.length===0,()=>"Duplicate column names found: "+r.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 e=await(await this.base.iterator()).next();if(e.done)throw new Error("No data was found for CSV parsing.");let t=e.value;return this.parseRow(t,!1)}else return null}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 c_(e),t||(t={}),this.hasHeader=t.hasHeader!==!1,this.fullColumnNames=t.columnNames,this.columnConfigs=t.columnConfigs,this.configuredColumnsOnly=t.configuredColumnsOnly,t.delimWhitespace?(k.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 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),r={},n={};for(let a=0;a<this.fullColumnNames.length;a++){let s=this.fullColumnNames[a],i=this.columnConfigs?this.columnConfigs[s]:null;if(!(this.configuredColumnsOnly&&!i)){let o=t[a],l=null;if(o==="")if(i&&i.default!==void 0)l=i.default;else{if(i&&(i.required||i.isLabel))throw new Error(`Required column ${s} is empty in this line: ${e}`);l=void 0}else{let p=Number(o);if(isNaN(p))i&&i.dtype==="bool"?l=this.getBoolean(o):l=o;else if(!i||!i.dtype)l=p;else switch(i.dtype){case"float32":l=p;break;case"int32":l=Math.floor(p);break;case"bool":l=this.getBoolean(o);break;default:l=p}}i&&i.isLabel?n[s]=l:r[s]=l}}return Object.keys(n).length===0?r:{xs:r,ys:n}}getBoolean(e){return e==="1"||e.toLowerCase()==="true"?1:0}parseRow(e,t=!0){let r=[],n=0,a=e.length,s=Np;for(let i=0;i<a;i++)switch(s){case Np:switch(e.charAt(i)){case zh:n=i+1,s=Ph;break;case this.delimiter:if(n=i+1,this.delimiter===" "&&this.delimWhitespace)break;r.push(""),s=Np;break;default:s=l1,n=i;break}break;case l1:switch(e.charAt(i)){case this.delimiter:r.push(e.substring(n,i)),s=Np,n=i+1;break}break;case Ph:switch(e.charAt(i)){case zh:s=Hm;break}break;case Hm:switch(e.charAt(i)){case this.delimiter:r.push(e.substring(n,i-1)),s=Np,n=i+1;break;case zh:s=Ph;break;default:s=u1;break}break;case u1:switch(e.charAt(i)){case zh:s=Ph;break}break}if(s===Hm?r.push(e.substring(n,a-1)):r.push(e.substring(n)),t&&r.length!==this.fullColumnNames.length)throw new Error(`Invalid row in csv file. Should have ${this.fullColumnNames.length} elements in a row, but got ${r}`);return r}},zq=class m_ extends Qt{constructor(t){super(),this.microphoneConfig=t,this.isClosed=!1,this.fftSize=t.fftSize||1024;let r=Math.log2(this.fftSize);if(this.fftSize<0||r<4||r>14||!Number.isInteger(r))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=t.numFramesPerSpectrogram||43,this.sampleRateHz=t.sampleRateHz,this.columnTruncateLength=t.columnTruncateLength||this.fftSize,this.audioTrackConstraints=t.audioTrackConstraints,this.smoothingTimeConstant=t.smoothingTimeConstant||0,this.includeSpectrogram=t.includeSpectrogram!==!1,this.includeWaveform=t.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(t={}){if(!j().get("IS_BROWSER"))throw new Error("microphone API is only supported in browser environment.");let r=new m_(t);return await r.start(),r}async start(){try{this.stream=await navigator.mediaDevices.getUserMedia({audio:this.audioTrackConstraints==null?!0:this.audioTrackConstraints,video:!1})}catch(n){throw new Error(`Error thrown while initializing video stream: ${n.message}`)}if(!this.stream)throw new Error("Could not obtain audio from microphone.");let t=window.AudioContext||window.webkitAudioContext;if(this.audioContext=new t,!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 r=this.audioContext.createMediaStreamSource(this.stream);this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=this.fftSize*2,this.analyser.smoothingTimeConstant=this.smoothingTimeConstant,r.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 t,r,n=await this.getAudioData();if(this.includeSpectrogram){let a=this.flattenQueue(n.freqDataQueue);t=this.getTensorFromAudioDataArray(a,[this.numFrames,this.columnTruncateLength,1])}if(this.includeWaveform){let a=this.flattenQueue(n.timeDataQueue);r=this.getTensorFromAudioDataArray(a,[this.numFrames*this.fftSize,1])}return{value:{spectrogram:t,waveform:r},done:!1}}async capture(){return(await this.next()).value}async getAudioData(){let t=[],r=[],n=0;return new Promise(a=>{let s=setInterval(()=>{this.includeSpectrogram&&(this.analyser.getFloatFrequencyData(this.freqData),this.freqData[0]===-1/0&&a({freqDataQueue:t,timeDataQueue:r}),t.push(this.freqData.slice(0,this.columnTruncateLength))),this.includeWaveform&&(this.analyser.getFloatTimeDomainData(this.timeData),r.push(this.timeData.slice())),++n===this.numFrames&&(clearInterval(s),a({freqDataQueue:t,timeDataQueue:r}))},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(t){let r=t[0].length,n=new Float32Array(t.length*r);return t.forEach((a,s)=>n.set(a,s*r)),n}getTensorFromAudioDataArray(t,r){let n=new Float32Array(k.sizeFromShape(r));return n.set(t,n.length-t.length),yr(n,r)}},Pq=class g_ extends Qt{constructor(t,r){if(super(),this.webcamVideoElement=t,this.webcamConfig=r,this.isClosed=!0,this.resize=!1,this.needToResize())if(this.resize=!0,this.cropSize=[this.webcamConfig.resizeHeight,this.webcamConfig.resizeWidth],this.cropBoxInd=Qe([0],"int32"),this.webcamConfig.centerCrop){let n=this.webcamConfig.resizeWidth*1/this.webcamVideoElement.width,a=this.webcamConfig.resizeHeight*1/this.webcamVideoElement.height,s=(1-n)/2,i=(1-a)/2,o=s+n,l=a+i;this.cropBox=ia([i,s,l,o],[1,4])}else this.cropBox=ia([0,0,1,1],[1,4])}summary(){return"webcam"}static async create(t,r={}){if(!j().get("IS_BROWSER"))throw new Error("tf.data.webcam is only supported in browser environment.");if(!t){if(t=document.createElement("video"),!r.resizeWidth||!r.resizeHeight)throw new Error("Please provide webcam video element, or resizeWidth and resizeHeight to create a hidden video element.");t.width=r.resizeWidth,t.height=r.resizeHeight}let n=new g_(t,r);return await n.start(),n}async start(){this.webcamConfig.facingMode&&k.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(t){throw t.message=`Error thrown while initializing video stream: ${t.message}`,t}if(!this.stream)throw new Error("Could not obtain video from webcam.");try{this.webcamVideoElement.srcObject=this.stream}catch(t){console.log(t),this.webcamVideoElement.src=window.URL.createObjectURL(this.stream)}return this.webcamVideoElement.play(),this.isClosed=!1,new Promise(t=>{this.webcamVideoElement.onloadedmetadata=()=>{t()}})}async next(){if(this.isClosed)return{value:null,done:!0};let t;try{t=Yd.fromPixels(this.webcamVideoElement)}catch(r){throw new Error(`Error thrown converting video to pixels: ${JSON.stringify(r)}`)}if(this.resize)try{return{value:this.cropAndResizeFrame(t),done:!1}}catch(r){throw new Error(`Error thrown cropping the video: ${r.message}`)}finally{t.dispose()}else return{value:t,done:!1}}needToResize(){return!!(this.webcamConfig.resizeWidth&&this.webcamConfig.resizeHeight&&(this.webcamVideoElement.width!==this.webcamConfig.resizeWidth||this.webcamVideoElement.height!==this.webcamConfig.resizeHeight))}cropAndResizeFrame(t){return W(()=>{let r=Xt(se(t,"float32"),0),n;n=sn.cropAndResize(r,this.cropBox,this.cropBoxInd,this.cropSize,"bilinear");let a=n.shape;return B(n,a.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.")}},y_=class{},b_=class extends Qt{split(e){return new Bq(this,e)}},Bq=class extends b_{constructor(e,t){super(),this.upstream=e,this.impl=new Wq(e,t)}summary(){return this.impl.summary()}async next(){return this.impl.next()}},Wq=class extends Dv{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 r of t.slice(0,-1))this.outputQueue.push(r);return this.carryover=t[t.length-1],!0}},Uq=class extends Qt{decodeUTF8(){return new Vq(this)}},Vq=class extends b_{constructor(e){super(),this.upstream=e,this.impl=new Gq(e)}summary(){return this.impl.summary()}async next(){return this.impl.next()}},Gq=class extends Dv{constructor(e){if(super(),this.upstream=e,j().get("IS_BROWSER"))this.decoder=new TextDecoder("utf-8");else{let{StringDecoder:t}=Nk();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 r;return j().get("IS_BROWSER")?r=this.decoder.decode(t,{stream:!0}):r=this.decoder.write(Buffer.from(t.buffer)),this.outputQueue.push(r),!0}},x_=class extends Uq{constructor(e,t={}){super(),this.file=e,this.options=t,k.assert(e instanceof Uint8Array||(j().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((e,t)=>{let r=this.offset+this.chunkSize;if(this.file instanceof Uint8Array)e(new Uint8Array(this.file.slice(this.offset,r)));else{let n=new FileReader;n.onload=s=>{let i=n.result;if(i instanceof ArrayBuffer&&(i=new Uint8Array(i)),!(i instanceof Uint8Array))return t(new TypeError("FileReader returned unknown type."));e(i)},n.onabort=s=>t(new Error("Aborted")),n.onerror=s=>t(new Error(s.type));let a=this.file.slice(this.offset,r);n.readAsArrayBuffer(a)}this.offset=r}),done:!1}}};async function Hq(e,t={},r){let n,a;typeof e=="string"?n=e:(n=e.url,a=jq(e));let s=await(0,k.fetch)(n,a);if(s.ok){let i=new Uint8Array(await s.arrayBuffer());return new x_(i,t)}else throw new Error(s.statusText)}var jq=e=>({method:e.method,headers:e.headers,body:e.body,mode:e.mode,credentials:e.credentials,cache:e.cache,redirect:e.redirect,referrer:e.referrer,integrity:e.integrity});function v_(e){return typeof e=="string"&&e.slice(0,7)==="file://"}var w_=class extends y_{constructor(e,t={}){super(),this.input=e,this.options=t}async iterator(){if(v_(this.input)&&j().get("IS_NODE")){let e=Ny();this.input=e.readFileSync(this.input.slice(7))}return new x_(this.input,this.options)}},k_=class extends y_{constructor(e,t={}){super(),this.url=e,this.fileOptions=t}async iterator(){return v_(this.url)?new w_(this.url,this.fileOptions).iterator():Hq(this.url,this.fileOptions)}};function qq(e,t={}){return new f_(new k_(e),t)}function Kq(e){let t=Rv(e);return Ur(async()=>t)}function Xq(e){return Ur(async()=>{let t=await e();return Rv(()=>t.next())})}async function Zq(e,t){return Pq.create(e,t)}async function Jq(e){return zq.create(e)}var Yq="4.22.0";function ye(e,t){Array.isArray(e)||(e=[e]),e.forEach(r=>{r!=null&&k.assert(r.dtype!=="complex64",()=>`${t} does not support complex64 tensors in the CPU backend.`)})}var Qq=ga.whereImpl,Mv=class I_ extends pd{nextDataId(){return I_.nextDataId++}constructor(){super(),this.blockSize=48,this.firstUse=!0,this.data=new Xc(this,wn())}write(t,r,n){this.firstUse&&(this.firstUse=!1,j().get("IS_NODE")&&_.warn(`
============================
Hi, looks like you are running TensorFlow.js in Node.js. To speed things up dramatically, install our node backend, visit https://github.com/tensorflow/tfjs-node for more details.
============================`));let a={id:this.nextDataId()};return this.data.set(a,{values:t,dtype:n,refCount:1}),a}makeTensorInfo(t,r,n){let a;if(r==="string"&&n!=null&&n.length>0&&k.isString(n[0])){let s=n.map(i=>k.encodeString(i));a=this.write(s,t,r)}else a=this.write(n,t,r);return{dataId:a,shape:t,dtype:r}}refCount(t){return this.data.has(t)?this.data.get(t).refCount:0}incRef(t){let r=this.data.get(t);r.refCount++}decRef(t){if(this.data.has(t)){let r=this.data.get(t);r.refCount--}}move(t,r,n,a,s){this.data.set(t,{values:r,dtype:a,refCount:s})}numDataIds(){return this.data.numDataIds()}async read(t){return this.readSync(t)}readSync(t){let{dtype:r,complexTensorInfos:n}=this.data.get(t);if(r==="complex64"){let a=this.readSync(n.real.dataId),s=this.readSync(n.imag.dataId);return _.mergeRealAndImagArrays(a,s)}return k.convertBackendValuesAndArrayBuffer(this.data.get(t).values,r)}bufferSync(t){let r=this.readSync(t.dataId);if(t.dtype==="string")try{let n=r.map(a=>k.decodeString(a));return Le(t.shape,t.dtype,n)}catch{throw new Error("Failed to decode encoded string bytes into utf-8")}return Le(t.shape,t.dtype,r)}makeOutput(t,r,n){return wn().makeTensorFromTensorInfo(this.makeTensorInfo(r,n,t),this)}disposeData(t,r=!1){if(this.data.has(t)){if(this.data.get(t).refCount--,!r&&this.data.get(t).refCount>0)return!1;let{complexTensorInfos:n}=this.data.get(t);n!=null&&(this.disposeData(n.real.dataId,!0),this.disposeData(n.imag.dataId,!0)),this.data.delete(t)}return!0}disposeIntermediateTensorInfo(t){this.disposeData(t.dataId)}async time(t){let r=k.now();return t(),{kernelMs:k.now()-r}}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(t){ye([t],"where");let r=this.readSync(t.dataId);return Qq(t.shape,r)}dispose(){}floatPrecision(){return 32}epsilon(){return super.epsilon()}};Mv.nextDataId=0;var Ov={};Ee(Ov,{addImpl:()=>__,bincountImpl:()=>zv,bincountReduceImpl:()=>T_,bitwiseAndImpl:()=>C_,castImpl:()=>N_,ceilImpl:()=>E_,concatImpl:()=>Pv,equalImpl:()=>$_,expImpl:()=>F_,expm1Impl:()=>D_,floorDivImpl:()=>O_,floorImpl:()=>M_,gatherNdImpl:()=>L_,gatherV2Impl:()=>z_,greaterEqualImpl:()=>B_,greaterImpl:()=>P_,lessEqualImpl:()=>U_,lessImpl:()=>W_,linSpaceImpl:()=>V_,logImpl:()=>G_,maxImpl:()=>H_,maximumImpl:()=>j_,minimumImpl:()=>q_,multiplyImpl:()=>Bv,negImpl:()=>K_,notEqualImpl:()=>X_,prodImpl:()=>Z_,raggedGatherImpl:()=>J_,raggedRangeImpl:()=>Y_,raggedTensorToTensorImpl:()=>Q_,rangeImpl:()=>Uv,rsqrtImpl:()=>eT,scatterImpl:()=>ri,sigmoidImpl:()=>Y5,simpleAbsImpl:()=>S_,sliceImpl:()=>Rc,sparseFillEmptyRowsImpl:()=>rT,sparseReshapeImpl:()=>nT,sparseSegmentReductionImpl:()=>Vv,sqrtImpl:()=>tK,squaredDifferenceImpl:()=>aT,staticRegexReplaceImpl:()=>sT,stridedSliceImpl:()=>iT,stringNGramsImpl:()=>Gv,stringSplitImpl:()=>Hv,stringToHashBucketFastImpl:()=>jv,subImpl:()=>oT,tileImpl:()=>lT,topKImpl:()=>pT,transposeImpl:()=>Wv,uniqueImpl:()=>Kv});function S_(e){let t=new Float32Array(e.length);for(let r=0;r<e.length;++r)t[r]=Math.abs(e[r]);return t}var e5=e=>{let{x:t}=e.inputs,r=e.backend;ye(t,"abs");let n=new Float32Array(k.sizeFromShape(t.shape)),a=r.data.get(t.dataId).values;return n=S_(a),r.makeOutput(n,t.shape,t.dtype)},t5={kernelName:Kl,backendName:"cpu",kernelFunc:e5};function Et(e){return(t,r,n,a,s)=>{let i=_.assertAndGetBroadcastShape(t,r),o=i.length,l=k.computeStrides(i),p=k.sizeFromShape(i),u=k.getTypedArrayFromDType(s,p),d=t.length,h=r.length,c=k.computeStrides(t),f=k.computeStrides(r),m=_.getBroadcastDims(t,i),g=_.getBroadcastDims(r,i);if(m.length+g.length===0)for(let y=0;y<u.length;++y)u[y]=e(n[y%n.length],a[y%a.length]);else for(let y=0;y<u.length;++y){let b=k.indexToLoc(y,o,l),x=b.slice(-d);m.forEach(T=>x[T]=0);let v=k.locToIndex(x,d,c),w=b.slice(-h);g.forEach(T=>w[T]=0);let N=k.locToIndex(w,h,f);u[y]=e(n[v],a[N])}return[u,i]}}function Hr(e){let{inputs:t,backend:r}=e,{real:n,imag:a}=t,s=r.data.get(n.dataId).values,i=r.data.get(a.dataId).values,o=r.makeTensorInfo(n.shape,"complex64"),l=r.data.get(o.dataId);return l.complexTensorInfos={real:r.makeTensorInfo(n.shape,"float32",s),imag:r.makeTensorInfo(a.shape,"float32",i)},o}var r5={kernelName:Yc,backendName:"cpu",kernelFunc:Hr};function Fc(e,t,r="float32"){if(r==="complex64"){let a=Fc(e,t,"float32"),s=Fc(e,t,"float32");return Hr({inputs:{real:a,imag:s},backend:e})}let n=k.makeZerosTypedArray(k.sizeFromShape(t),r);return e.makeTensorInfo(t,r,n)}function ca(e){let{inputs:t,backend:r}=e,{x:n}=t;return r.incRef(n.dataId),{dataId:n.dataId,shape:n.shape,dtype:n.dtype}}var n5={kernelName:so,backendName:"cpu",kernelFunc:ca};function wi(e){let{inputs:t,backend:r}=e,{input:n}=t,a=r.data.get(n.dataId).complexTensorInfos.real,s=r.data.get(a.dataId).values;return r.makeTensorInfo(a.shape,a.dtype,s)}var a5={kernelName:df,backendName:"cpu",kernelFunc:wi};function N_(e,t,r,n){if(n==="int32"){let a=Int32Array.from(e);return[t,"int32",a]}if(n==="bool"){let a=k.toTypedArray([0],r),[s,i]=Et((o,l)=>o!==l?1:0)(t,[],e,a,"bool");return[i,"bool",s]}throw new Error(`Error in Cast: failed to cast ${r} to ${n}`)}function Is(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{dtype:s}=n;if(s==="complex64"){if(a.dtype==="complex64")return ca({inputs:{x:a},backend:r});let u=Fc(r,a.shape,a.dtype),d=Is({inputs:{x:a},backend:r,attrs:{dtype:"float32"}}),h=Hr({inputs:{real:d,imag:u},backend:r});return r.disposeIntermediateTensorInfo(u),r.disposeIntermediateTensorInfo(d),h}if(a.dtype==="complex64"){let u=wi({inputs:{input:a},backend:r}),d=Is({inputs:{x:u},backend:r,attrs:{dtype:s}});return r.disposeIntermediateTensorInfo(u),d}if(!k.hasEncodingLoss(a.dtype,s)){let u=ca({inputs:{x:a},backend:r});return{dataId:u.dataId,shape:u.shape,dtype:s}}let i=r.data.get(a.dataId).values,[o,l,p]=N_(i,a.shape,a.dtype,s);return r.makeTensorInfo(o,l,p)}var s5={kernelName:Bi,backendName:"cpu",kernelFunc:Is};function Gt(e,t,r,n){return r==null?({inputs:a,backend:s})=>{let{a:i,b:o}=a,l=s;ye([i,o],e);let p=l.data.get(i.dataId).values,u=l.data.get(o.dataId).values,d=i.dtype==="string"?_.fromUint8ToStringArray(p):p,h=i.dtype==="string"?_.fromUint8ToStringArray(u):u,c=n||i.dtype,[f,m]=t(i.shape,o.shape,d,h,c);return l.makeTensorInfo(m,c,f)}:({inputs:a,backend:s})=>{let{a:i,b:o}=a,l=s;if(i.dtype==="complex64"||o.dtype==="complex64"){let p=Is({inputs:{x:i},backend:l,attrs:{dtype:"complex64"}}),u=l.data.get(p.dataId),d=u.complexTensorInfos.real,h=u.complexTensorInfos.imag,c=l.data.get(d.dataId).values,f=l.data.get(h.dataId).values,m=Is({inputs:{x:o},backend:l,attrs:{dtype:"complex64"}}),g=l.data.get(m.dataId),y=g.complexTensorInfos.real,b=g.complexTensorInfos.imag,x=l.data.get(y.dataId).values,v=l.data.get(b.dataId).values,[w,N,T]=r(i.shape,o.shape,c,f,x,v),E=l.makeTensorInfo(T,"float32",w),$=l.makeTensorInfo(T,"float32",N),R=Hr({inputs:{real:E,imag:$},backend:l});return l.disposeIntermediateTensorInfo(p),l.disposeIntermediateTensorInfo(m),l.disposeIntermediateTensorInfo(E),l.disposeIntermediateTensorInfo($),R}else{let p=l.data.get(i.dataId).values,u=l.data.get(o.dataId).values,d=n||i.dtype,[h,c]=t(i.shape,o.shape,p,u,d);return l.makeTensorInfo(c,d,h)}}}function Lv(e){return(t,r,n,a,s,i)=>{let o=_.assertAndGetBroadcastShape(t,r),l=k.sizeFromShape(o),p=o.length,u=k.computeStrides(o),d=k.getTypedArrayFromDType("float32",l),h=k.getTypedArrayFromDType("float32",l),c=_.getBroadcastDims(t,o),f=_.getBroadcastDims(r,o),m=_.mergeRealAndImagArrays(n,a),g=_.mergeRealAndImagArrays(s,i),y=t.length,b=k.computeStrides(t),x=r.length,v=k.computeStrides(r);if(c.length+f.length===0)for(let w=0;w<d.length;w++){let N=w%m.length,T=w%g.length,E=e(m[N*2],m[N*2+1],g[T*2],g[T*2+1]);d[w]=E.real,h[w]=E.imag}else for(let w=0;w<d.length;w++){let N=k.indexToLoc(w,p,u),T=N.slice(-y);c.forEach(S=>T[S]=0);let E=k.locToIndex(T,y,b),$=N.slice(-x);f.forEach(S=>$[S]=0);let R=k.locToIndex($,x,v),F=e(m[E*2],m[E*2+1],g[R*2],g[R*2+1]);d[w]=F.real,h[w]=F.imag}return[d,h,o]}}var __=Et((e,t)=>e+t),i5=Lv((e,t,r,n)=>({real:e+r,imag:t+n})),Bl=Gt(Ts,__,i5),o5={kernelName:Ts,backendName:"cpu",kernelFunc:Bl};function zv(e,t,r,n,a){let s=k.sizeFromShape(n),i=k.makeZerosTypedArray(a,r);for(let o=0;o<e.length;o++){let l=e[o];if(l<0)throw new Error("Input x must be non-negative!");l>=a||(s>0?i[l]+=t[o]:i[l]+=1)}return i}function T_(e,t,r,n=!1){let a=e.shape[0],s=e.shape[1],i=Le([a,r],t.dtype);for(let o=0;o<a;o++)for(let l=0;l<s;l++){let p=e.get(o,l);if(p<0)throw new Error("Input x must be non-negative!");p>=r||(n?i.set(1,o,p):t.size>0?i.set(i.get(o,p)+t.get(o,l),o,p):i.set(i.get(o,p)+1,o,p))}return i}var C_=Et((e,t)=>e&t),l5=Gt(ru,C_),u5={kernelName:ru,backendName:"cpu",kernelFunc:l5};function ya(e){return(t,r,n)=>{let a=k.getArrayFromDType(r,t.length);for(let s=0;s<t.length;++s)a[s]=e(t[s],n);return a}}function at(e,t,r){let n=ya(t);return Os(e,n,r)}function Os(e,t,r){return({inputs:n,attrs:a,backend:s})=>{let{x:i}=n;ye(i,e);let o=s,l=o.data.get(i.dataId).values,p;if(i.dtype==="string"){if(!Array.isArray(l))throw new Error("String tensor's value was not an instance of Array");p=_.fromUint8ToStringArray(l)}else p=l;let u=r||i.dtype,d=t(p,u,a);return o.makeTensorInfo(i.shape,u,d)}}var E_=ya(e=>Math.ceil(e)),p5=Os(Wi,E_),d5={kernelName:Wi,backendName:"cpu",kernelFunc:p5};function Pv(e,t,r,n){let a=k.getArrayFromDType(r,k.sizeFromShape(t));if(n&&r!=="string"){let s=0;e.forEach(i=>{let o=k.sizeFromShape(i.shape);a.set(i.vals,s),s+=o})}else{let s=0;e.forEach(i=>{let o=r==="string"?_.fromUint8ToStringArray(i.vals):i.vals,l=0;for(let p=0;p<i.shape[0];++p){let u=p*t[1]+s;for(let d=0;d<i.shape[1];++d)a[u+d]=o[l++]}s+=i.shape[1]})}return a}var $_=Et((e,t)=>e===t?1:0),A_=Gt(pu,$_,null,"bool"),h5={kernelName:pu,backendName:"cpu",kernelFunc:A_},F_=ya(e=>Math.exp(e)),R_=Os(Qi,F_,"float32"),c5={kernelName:Qi,backendName:"cpu",kernelFunc:R_},D_=ya(e=>Math.expm1(e)),f5=Os(eo,D_),m5={kernelName:eo,backendName:"cpu",kernelFunc:f5},M_=ya(e=>Math.floor(e)),g5=Os(to,M_),y5={kernelName:to,backendName:"cpu",kernelFunc:g5},O_=Et((e,t)=>Math.floor(e/t)),b5=Gt(ro,O_,null,"int32"),x5={kernelName:ro,backendName:"cpu",kernelFunc:b5};function L_(e,t,r,n,a,s,i,o,l){let p=Le([n,s],r);for(let u=0;u<n;u++){let d=[],h=0;for(let c=0;c<a;c++){let f=e[u*a+c];h+=f*i[c],d.push(f)}if(h<0||h>=l/s)throw new Error(`Invalid indices: ${d} does not index into ${o}`);for(let c=0;c<s;c++)p.values[u*s+c]=t.get(...t.indexToLoc(h*s+c))}return p}function z_(e,t,r){let n=Le(r,e.dtype);for(let a=0;a<n.size;++a){let s=n.indexToLoc(a).slice(),i=s[0],o=s[2],l=t.locToIndex([i,o]);s[2]=t.values[l];let p=e.locToIndex(s);0<=p&&p<e.values.length&&(n.values[a]=e.values[p])}return n}var P_=Et((e,t)=>e>t?1:0),v5=Gt(mu,P_,null,"bool"),w5={kernelName:mu,backendName:"cpu",kernelFunc:v5},B_=Et((e,t)=>e>=t?1:0),k5=Gt(ao,B_,null,"bool"),I5={kernelName:ao,backendName:"cpu",kernelFunc:k5},W_=Et((e,t)=>e<t?1:0),S5=Gt(gu,W_,null,"bool"),N5={kernelName:gu,backendName:"cpu",kernelFunc:S5},U_=Et((e,t)=>e<=t?1:0),_5=Gt(yu,U_,null,"bool"),T5={kernelName:yu,backendName:"cpu",kernelFunc:_5};function V_(e,t,r){let n=(t-e)/(r-1),a=k.makeZerosTypedArray(r,"float32");a[0]=e;for(let s=1;s<a.length;s++)a[s]=a[s-1]+n;return a}var G_=ya(e=>Math.log(e)),C5=Os(po,G_),E5={kernelName:po,backendName:"cpu",kernelFunc:C5};function H_(e,t,r,n){let a=k.getTypedArrayFromDType(n,k.sizeFromShape(r));for(let s=0;s<a.length;++s){let i=s*t,o=e[i];for(let l=0;l<t;++l){let p=e[i+l];(Number.isNaN(p)||p>o)&&(o=p)}a[s]=o}return a}var j_=Et((e,t)=>Math.max(e,t)),$5=Gt(mo,j_),A5={kernelName:mo,backendName:"cpu",kernelFunc:$5},q_=Et((e,t)=>Math.min(e,t)),F5=Gt(xo,q_),R5={kernelName:xo,backendName:"cpu",kernelFunc:F5},Bv=Et((e,t)=>e*t),D5=Lv((e,t,r,n)=>({real:e*r-t*n,imag:e*n+t*r})),ym=Gt(ko,Bv,D5),M5={kernelName:ko,backendName:"cpu",kernelFunc:ym};function K_(e,t,r){let n=k.createScalarValue(-1,r);return Bv([],t,n,e,r)}function O5(e){let{inputs:t,backend:r}=e,{x:n}=t;ye(n,"neg");let a=r.data.get(n.dataId).values,[s,i]=K_(a,n.shape,n.dtype);return r.makeTensorInfo(i,n.dtype,s)}var L5={kernelName:Nu,backendName:"cpu",kernelFunc:O5},X_=Et((e,t)=>e!==t?1:0),z5=Gt(_u,X_,null,"bool"),P5={kernelName:_u,backendName:"cpu",kernelFunc:z5};function Wv(e,t,r,n,a){let s=t.length,i=k.sizeFromShape(t),o=k.computeStrides(t),l=k.computeStrides(a),p=k.getTypedArrayFromDType(r,k.sizeFromShape(a));for(let u=0;u<i;++u){let d=k.indexToLoc(u,s,o),h=new Array(d.length);for(let f=0;f<h.length;f++)h[f]=d[n[f]];let c=k.locToIndex(h,s,l);p[c]=e[u]}return p}function Mr(e){let{inputs:t,attrs:r,backend:n}=e,{x:a}=t,{perm:s}=r;ye(a,"transpose");let i=a.shape.length,o=new Array(i);for(let u=0;u<o.length;u++)o[u]=a.shape[s[u]];let l=n.data.get(a.dataId).values,p=Wv(l,a.shape,a.dtype,s,o);return{dataId:n.write(p,o,a.dtype),shape:o,dtype:a.dtype}}var B5={kernelName:Ta,backendName:"cpu",kernelFunc:Mr};function Z_(e,t,r,n){let[a,s]=_.computeOutAndReduceShapes(e,n),i=cn(t,"int32"),o=k.makeZerosTypedArray(k.sizeFromShape(a),i),l=k.sizeFromShape(s);for(let p=0;p<o.length;++p){let u=p*l,d=1;for(let h=0;h<l;++h)d*=r[u+h];o[p]=d}return{outVals:o,outShape:a,outDtype:i}}function W5(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{axis:s,keepDims:i}=n;ye(a,"prod");let o=a.shape.length,l=k.parseAxisParam(s,a.shape),p=_.getAxesPermutation(l,o),u=l,d=a,h=[];p!=null&&(d=Mr({inputs:{x:a},backend:r,attrs:{perm:p}}),h.push(d),u=_.getInnerMostAxes(u.length,o));let c=r.data.get(d.dataId).values,{outVals:f,outShape:m,outDtype:g}=Z_(d.shape,d.dtype,c,u),y=m;return i&&(y=_.expandShapeToKeepDim(m,l)),h.forEach(b=>r.disposeIntermediateTensorInfo(b)),r.makeTensorInfo(y,g,f)}var U5={kernelName:To,backendName:"cpu",kernelFunc:W5};function V5(e,t,r){e.forEach((n,a)=>{if(n<0||n>=r){let s=k.indexToLoc(a,t.length,k.computeStrides(t)).join(",");throw new Error(`indices[${s}] = ${n} is not in [0, ${r})`)}})}function G5(e,t){for(let r=0;r<e.length;++r){let n=e[r],a=r===e.length-1?t:e[r+1].length;if(n.length===0)throw new Error("Ragged splits may not be empty");if(n[0]<0)throw new Error("Ragged splits must be non-negative");if(n[n.length-1]>a)throw new Error("Ragged splits must not point past values");for(let s=1;s<n.length;++s)if(n[s-1]>n[s])throw new Error("Ragged splits must be sorted in ascending order")}}function H5(e,t,r,n){let a=[],s=0,i=t.length-1+r.length,o=new Array(i).fill(null).map(()=>[0]);G5(r,n);let l=1;for(let p=0;p<t.length-1;++p){l*=t[p];let u=t[p+1];for(let d=1;d<l+1;++d)o[p].push(d*u)}for(let p=0;p<e.length;++p){let u=e[p],d=e[p]+1;for(let h=0;h<r.length;++h){let c=r[h],f=h+t.length-1;if(f>=0){let m=o[f],g=m[m.length-1]-c[u];for(let y=u;y<d;++y)o[f].push(c[y+1]+g)}u=c[u],d=c[d]}d!==u&&(a.push([u,d]),s+=d-u)}return{outSplits:o,valueSlices:a,numValues:s}}function j5(e){let t=[];for(let r=0;r<e.length;++r){let n=e[r].length,a=k.getArrayFromDType("int32",n);t.push(a),e[r].forEach((s,i)=>a[i]=s)}return t}function p1(e,t){let r=e.slice(0,t);for(;r.length<t;)r.push(1);for(let n=t;n<e.length;n++)r[t-1]*=e[n];return r}function q5(e,t,r,n,a,s){let i=p1(t,2)[1],o=p1(s,2)[1],l=0;for(let p of r)for(let u=p[0];u<p[1];++u){for(let d=0;d<n;++d)a[l*o+d]=e[u*i+d];++l}}function K5(e,t,r,n,a){let s=t.slice();s[0]=a;let i=k.getArrayFromDType(r,k.sizeFromShape(s)),o=e.length,l=o===0?0:o/t[0];return q5(e,t,n,l,i,s),[i,s]}function J_(e,t,r,n,a,s,i,o){if(e.length===0)throw new Error("paramsNestedSplits must be non empty");if(t[0].length===0)throw new Error("Split tensors must not be scalars");let l=t[0][0]-1;if(V5(s,i,l),n.length===0)throw new Error("params.rank must be nonzero");let p=n[0],{outSplits:u,valueSlices:d,numValues:h}=H5(s,i,e,p),c=j5(u),f=K5(r,n,a,d,h);return[c,f[0],f[1]]}var d1=2147483647;function Y_(e,t,r,n,a,s,i){if(t.length>1)throw new Error("starts must be a scalar or vector");if(a.length>1)throw new Error("limits must be a scalar or vector");if(i.length>1)throw new Error("deltas must be a scalar or vector");let o=t.length===0,l=a.length===0,p=i.length===0,u=[];o||u.push(t[0]),l||u.push(a[0]),p||u.push(i[0]);for(let g=1;g<u.length;++g)if(u[g]!==u[g-1])throw new Error("starts, limits, and deltas must have the same shape");let d=u.length===0?1:u[0],h=k.getArrayFromDType("int32",d+1);h[0]=0;for(let g=0;g<d;++g){let y=o?e[0]:e[g],b=l?n[0]:n[g],x=p?s[0]:s[g];if(x===0)throw new Error("Requires delta != 0");let v;if(x>0&&b<y||x<0&&b>y)v=0;else if(v=Math.ceil(Math.abs((b-y)/x)),v>d1)throw new Error(`Requires ((limit - start) / delta) <= ${d1}`);h[g+1]=h[g]+v}let c=h[d],f=k.getArrayFromDType(r,c),m=0;for(let g=0;g<d;++g){let y=h[g+1]-h[g],b=o?e[0]:e[g],x=p?s[0]:s[g];for(let v=0;v<y;++v)f[m++]=b,b+=x}return[h,f]}var xn=_.RowPartitionType,X5=class Gg{constructor(t,r,n,a,s,i,o,l,p,u){this.shape=t,this.shapeShape=r,this.values=n,this.valuesShape=a,this.valuesDType=s,this.defaultValue=i,this.defaultValueShape=o,this.rowPartitionValues=l,this.rowPartitionValuesShapes=p,this.rowPartitionTypes=_.getRowPartitionTypesHelper(u),this.raggedRank=_.getRaggedRank(this.rowPartitionTypes)}getRowPartitionTypeByDimension(t){return this.rowPartitionTypes[0]===xn.FIRST_DIM_SIZE?this.rowPartitionTypes[t+1]:this.rowPartitionTypes[t]}getRowPartitionTensor(t){return this.rowPartitionTypes[0]===xn.FIRST_DIM_SIZE?this.rowPartitionValues[t+1]:this.rowPartitionValues[t]}getMaxWidth(t){let r=this.getRowPartitionTensor(t-1);switch(this.getRowPartitionTypeByDimension(t-1)){case xn.VALUE_ROWIDS:return Gg.getMaxWidthValueRowID(r);case xn.ROW_SPLITS:return Gg.getMaxWidthRowSplit(r);default:throw new Error(`Cannot handle partition type ${xn[this.getRowPartitionTypeByDimension(t-1)]}`)}}static getMaxWidthRowSplit(t){let r=t.length;if(r===0||r===1)return 0;let n=0;for(let a=0;a<r-1;++a){let s=t[a+1]-t[a];s>n&&(n=s)}return n}static getMaxWidthValueRowID(t){let r=t.length;if(r===0)return 0;let n=0,a=t[0],s=0;for(let i=1;i<r;++i){let o=t[i];o!==a&&(a=o,s=Math.max(i-n,s),n=i)}return Math.max(r-n,s)}tensorShapeFromTensor(t,r,n=!0){if(r.length===0){if(t[0]===-1)return[];throw new Error("The only valid scalar shape tensor is the fully unknown shape specified as -1.")}return c1(t,n)}calculateOutputSize(t){let r=this.valuesShape,n=this.defaultValueShape;_.validateDefaultValueShape(n,r);let a=this.tensorShapeFromTensor(this.shape,this.shapeShape),s=_.combineRaggedTensorToTensorShapes(this.raggedRank,a,r);s[0]<0&&(s[0]=t);for(let i=1;i<=this.raggedRank;++i)s[i]<0&&(s[i]=this.getMaxWidth(i));return s}calculateFirstParentOutputIndex(t,r,n){let a=Math.min(t,n),s=[],i=0;for(let o=0;o<a;++o,i+=r)s.push(i);for(let o=a;o<t;++o)s.push(-1);return k.assert(s.length===t,()=>"Final length of result must be equal to firstDimension."),s}calculateOutputIndexRowSplit(t,r,n,a){let s=t.length,i=[];for(let o=0;o<s-1;++o){let l=t[o+1]-t[o],p=Math.min(a,l),u=r[o];u===-1&&(p=0);for(let d=0;d<p;++d)i.push(u),u+=n;for(let d=0;d<l-p;++d)i.push(-1)}if(s>0&&i.length!==t[s-1])throw new Error("Invalid row split size.");return i}calculateOutputIndexValueRowID(t,r,n,a){let s=t.length,i=[];if(s===0)return[];let o=0,l=t[0];if(l>=r.length)throw new Error(`Got currentValueRowId=${l}, which is not less than ${r.length}`);let p=r[l];i.push(p);for(let u=1;u<s;++u){let d=t[u];if(d===l)p>=0&&(++o,o<a?p+=n:p=-1);else{if(o=0,l=d,d>=r.length)throw new Error(`Got nextValueRowId=${d} which is not less than ${r.length}`);p=r[d]}i.push(p)}if(i.length!==t.length)throw new Error("Invalid row ids.");return i}calculateOutputIndex(t,r,n,a){let s=this.getRowPartitionTensor(t),i=this.getRowPartitionTypeByDimension(t);switch(i){case xn.VALUE_ROWIDS:return this.calculateOutputIndexValueRowID(s,r,n,a);case xn.ROW_SPLITS:if(s.length-1>r.length)throw new Error(`Row partition size is greater than output size: ${s.length-1} > ${r.length}`);return this.calculateOutputIndexRowSplit(s,r,n,a);default:throw new Error(`Unsupported partition type: ${xn[i]}`)}}getFirstDimensionSize(){let t=this.rowPartitionValues[0];if(this.rowPartitionTypes.length===0)throw new Error("No row_partition_types given.");let r=this.rowPartitionTypes[0];switch(r){case xn.FIRST_DIM_SIZE:return t[0];case xn.VALUE_ROWIDS:throw new Error("Cannot handle VALUE_ROWIDS in first dimension.");case xn.ROW_SPLITS:return this.rowPartitionValuesShapes[0][0]-1;default:throw new Error(`Cannot handle type ${xn[r]}`)}}compute(){if(this.rowPartitionValues[0].length<=0)throw new Error("Invalid first partition input. Tensor requires at least one element.");let t=this.getFirstDimensionSize(),r=this.calculateOutputSize(t),n=new Array(this.raggedRank+1);n[n.length-1]=1;for(let i=n.length-2;i>=0;--i)n[i]=n[i+1]*r[i+1];let a=c1(r,!1),s=k.getArrayFromDType(this.valuesDType,k.sizeFromShape(a));if(n[0]*r[0]>0){let i=this.calculateFirstParentOutputIndex(t,n[0],r[0]);for(let o=1;o<=this.raggedRank;++o)i=this.calculateOutputIndex(o-1,i,n[o],r[o]);this.setOutput(this.raggedRank,i,s,a)}return[a,s]}setOutput(t,r,n,a){if(n.length===0)return;let s=this.values,i=n,o=a.slice();o=o.slice(t+1);let l=k.sizeFromShape(o),p=r.length,u=this.defaultValue;if(u.length!==l&&u.length!==1){let f=this.defaultValueShape;W(()=>{let m=B(u,f);u=ai(m,o).dataSync()})}let d=0,h=0,c=0;for(let f=0;f<=p;++f){let m=f<p?r[f]:-1;if(m===c){++c;continue}if(h<c){let g=s.subarray(d*l),y=i.subarray(h*l),b=(c-h)*l;h1(y,g,b)}if(f>=p){let g=n.length;m=Math.floor(g/l)}if(m>c)if(this.defaultValue.length===1)i.subarray(c*l,m*l).fill(this.defaultValue[0]),c=m;else for(;m>c;){let g=i.slice(c*l);h1(g,u,l),++c}m<0?(d=f+1,h=c):(d=f,h=c,c=h+1)}}};function h1(e,t,r){for(let n=0;n<r;n++)e[n]=t[n]}function c1(e,t){let r=[];for(let n of e){if(n<0){if(!t)throw new Error(`Dimension ${n} must be >= 0`);if(n<-1)throw new Error(`Dimension ${n} must be >= -1`);n=-1}r.push(n)}return r}function Q_(e,t,r,n,a,s,i,o,l,p){return new X5(e,t,r,n,a,s,i,o,l,p).compute()}function Uv(e,t,r,n){let a=e===t,s=e<t&&r<0,i=t<e&&r>1;if(a||s||i)return k.makeZerosTypedArray(0,n);let o=Math.abs(Math.ceil((t-e)/r)),l=k.makeZerosTypedArray(o,n);t<e&&r===1&&(r=-1),l[0]=e;for(let p=1;p<l.length;p++)l[p]=l[p-1]+r;return l}var eT=ya(e=>1/Math.sqrt(e)),Z5=Os(Mo,eT),J5={kernelName:Mo,backendName:"cpu",kernelFunc:Z5};function ri(e,t,r,n,a,s,i,o,l,p){let u=[n/a,a],d=e.values,h=t.values;if(n===0)return Le(r,t.dtype);let c=l instanceof Dt?l:Le(u,t.dtype);typeof l=="string"||typeof l=="number"?c.values.fill(l):typeof l=="boolean"&&c.values.fill(+l);for(let f=0;f<s;f++){let m=[],g=0;for(let y=0;y<i;y++){let b=d[f*i+y];m.push(b),g+=b*o[y]}if(g<0||g>=n/a)throw new Error(`Invalid indices: ${m} does not index into ${r}`);for(let y=0;y<a;y++)p?c.values[g*a+y]+=h[f*a+y]:c.values[g*a+y]=t.rank===0?h[0]:h[f*a+y]}return c}var Y5=ya(e=>1/(1+Math.exp(-e))),tT=at(Bo,e=>1/(1+Math.exp(-e))),Q5={kernelName:Bo,backendName:"cpu",kernelFunc:tT};function Rc(e,t,r,n,a){let s=Wt.isSliceContinous(n,t,r),i=k.sizeFromShape(r),o=k.computeStrides(n);if(s){let d=Wt.computeFlatOffset(t,o);return a==="string"?e.slice(d,d+i):e.subarray(d,d+i)}let l=a==="string"?_.fromUint8ToStringArray(e):e,p=Le(n,a,l),u=Le(r,a);for(let d=0;d<u.size;++d){let h=u.indexToLoc(d),c=h.map((f,m)=>f+t[m]);u.set(p.get(...c),...h)}return a==="string"?_.fromStringArrayToUint8(u.values):u.values}function ki(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{begin:s,size:i}=n;ye(a,"slice");let[o,l]=Wt.parseSliceParams(a,s,i);Wt.assertParamsValid(a,o,l);let p=r.data.get(a.dataId).values,u=Rc(p,o,l,a.shape,a.dtype);return r.makeTensorInfo(l,a.dtype,u)}var eK={kernelName:Pu,backendName:"cpu",kernelFunc:ki};function rT(e,t,r,n,a,s,i){let o=t[0],l=s[0],p=new Array(l),u=new Array(o),d=t[1];if(l===0){if(o!==0)throw new Error(_.getSparseFillEmptyRowsIndicesDenseShapeMismatch(o));let g=k.getArrayFromDType(r,0),y=k.getArrayFromDType(a,0);return[g,[0,d],y,p,u]}let h=!0,c=0,f=new Array(l).fill(0);for(let g=0;g<o;++g){let y=e[g*d];if(y<0)throw new Error(_.getSparseFillEmptyRowsNegativeIndexErrorMessage(g,y));if(y>=l)throw new Error(_.getSparseFillEmptyRowsOutOfRangeIndexErrorMessage(g,y,l));++f[y],h=h&&y>=c,c=y}let m=!0;for(let g=0;g<l;++g){let y=f[g]===0;p[g]=y,m=m&&!y,f[g]=Math.max(f[g],1),g>0&&(f[g]+=f[g-1])}if(m&&h){let g=e,y=n;for(let b=0;b<o;++b)u[b]=b;return[g,[o,d],y,p,u]}else{let g=f[l-1],y=k.getArrayFromDType(r,g*d),b=k.getArrayFromDType(a,g),x=new Array(l).fill(0);for(let v=0;v<o;++v){let w=e[v*d],N=x[w],T=(w===0?0:f[w-1])+N;x[w]++;for(let E=0;E<d;++E)y[T*d+E]=e[v*d+E];b[T]=n[v],u[v]=T}for(let v=0;v<l;++v)if(x[v]===0){let w=v===0?0:f[v-1];y[w*d+0]=v;for(let N=1;N<d;++N)y[w*d+N]=0;b[w]=i}return[y,[g,d],b,p,u]}}function nT(e,t,r,n,a){let s=k.sizeFromShape(n),i=t[0],o=a.length,l=[],p=1,u=-1;for(let m=0;m<o;++m){let g=a[m];if(g===-1){if(u!==-1)throw new Error(_.getSparseReshapeMultipleNegativeOneOutputDimErrorMessage(u,m));u=m,l.push(1)}else{if(g<0)throw new Error(_.getSparseReshapeNegativeOutputDimErrorMessage(m,g));p*=g,l.push(g)}}if(u!==-1){if(p<=0)throw new Error(_.getSparseReshapeEmptyTensorZeroOutputDimErrorMessage());let m=Math.trunc(s/p);if(p*m!==s)throw new Error(_.getSparseReshapeInputOutputMultipleErrorMessage(n,l));l[u]=m}if(k.sizeFromShape(l)!==s)throw new Error(_.getSparseReshapeInputOutputMismatchErrorMessage(n,l));let d=n.length,h=[];if(d>0){h[d-1]=1;for(let m=d-2;m>=0;--m)h[m]=h[m+1]*n[m+1]}let c=[];if(o>0){c[o-1]=1;for(let m=o-2;m>=0;--m)c[m]=c[m+1]*l[m+1]}let f=k.getArrayFromDType(r,i*o);for(let m=0;m<i;++m){let g=0;for(let y=0;y<d;++y)g+=e[m*d+y]*h[y];for(let y=0;y<o;++y)f[m*o+y]=Math.trunc(g/c[y]),g%=c[y]}return[f,[i,o],l]}function Vv(e,t,r,n,a,s=!1,i=0){let o=n.length,l=[t[0],e.length/t[0]],p=l[1],u=o>0?a[o-1]+1:0;if(u<0)throw new Error(_.getSparseSegmentReductionNegativeSegmentIdsErrorMessage());let d=t.slice();d[0]=u;let h=d.reduce((b,x)=>b*x,1),c=k.getArrayFromDType(r,h);if(o===0)return u>0&&c.fill(i),[c,d];if(u<=0)throw new Error(_.getSparseSegmentReductionNegativeSegmentIdsErrorMessage());let f=0,m=1,g=0,y=a[f];for(;;){let b=0;if(m<o){if(b=a[m],y===b){++m;continue}if(y>=b)throw new Error(_.getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage())}if(y<0||y>=u)throw new Error(_.getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage(y,u));y>g&&c.fill(i,g*p,y*p);for(let x=f;x<m;++x){let v=n[x];if(v<0||v>=l[0])throw new Error(_.getSparseSegmentReductionIndicesOutOfRangeErrorMessage(x,n[x],l[0]));for(let w=0;w<p;w++)c[y*p+w]+=e[v*p+w]}if(s)for(let x=0;x<p;x++)c[y*p+x]/=m-f;if(f=m,++m,g=y+1,y=b,m>o)break}return g<u&&c.fill(i,g*p,u*p),[c,d]}var tK=ya(e=>Math.sqrt(e)),rK=at(Uo,e=>Math.sqrt(e)),nK={kernelName:Uo,backendName:"cpu",kernelFunc:rK},aT=Et((e,t)=>{let r=e-t;return r*r}),aK=Gt(Ho,aT),sK={kernelName:Ho,backendName:"cpu",kernelFunc:aK},sT=ya((e,t)=>{let{pattern:r,replaceGlobal:n,rewrite:a}=t;return e.replace(new RegExp(r,n?"g":""),a)}),iK=Os(Td,sT),oK={kernelName:Td,backendName:"cpu",kernelFunc:iK};function iT(e,t,r,n){let a=Le(e,t.dtype);for(let s=0;s<a.size;s++){let i=a.indexToLoc(s),o=new Array(i.length);for(let l=0;l<o.length;l++)o[l]=i[l]*r[l]+n[l];a.set(t.get(...o),...i)}return a}var lK=class{constructor(e,t,r,n,a,s){this.separator=k.encodeString(e),this.nGramWidths=t,this.leftPad=k.encodeString(r),this.rightPad=k.encodeString(n),this.padWidth=a,this.preserveShort=s}getPadWidth(e){return Math.min(this.padWidth<0?e-1:this.padWidth,e-1)}getNumNGrams(e,t){let r=this.getPadWidth(t);return Math.max(0,e+2*r-t+1)}createNGrams(e,t,r,n,a,s){for(let i=0;i<a;++i){let o=this.getPadWidth(s),l=Math.max(0,o-i),p=Math.max(0,o-(a-(i+1))),u=s-(l+p),d=t+(l>0?0:i-o),h=0;h+=l*this.leftPad.length;for(let y=0;y<u;++y)h+=e[d+y].length;h+=p*this.rightPad.length;let c=l+p+u-1;h+=c*this.separator.length,r[n+i]=new Uint8Array(h);let f=r[n+i],m=0,g=y=>y.forEach(b=>f[m++]=b);for(let y=0;y<l;++y)g(this.leftPad),g(this.separator);for(let y=0;y<u-1;++y)g(e[d+y]),g(this.separator);if(u>0){g(e[d+u-1]);for(let y=0;y<p;++y)g(this.separator),g(this.rightPad)}else{for(let y=0;y<p-1;++y)g(this.rightPad),g(this.separator);g(this.rightPad)}}}compute(e,t){let r=e.length,n=t.length;if(n>0){let o=t[0];if(o!==0)throw new Error(`First split value must be 0, got ${o}`);for(let l=1;l<n;++l){let p=t[l]>=o;if(p=p&&t[l]<=r,!p)throw new Error(`Invalid split value ${t[l]}, must be in [${o}, ${r}]`);o=t[l]}if(o!==r)throw new Error(`Last split value must be data size. Expected ${r}, got ${o}`)}let a=n-1,s=k.getArrayFromDType("int32",n);if(r===0||n===0){let o=new Array(r);for(let l=0;l<=a;++l)s[l]=0;return[o,s]}s[0]=0;for(let o=1;o<=a;++o){let l=t[o]-t[o-1],p=0;this.nGramWidths.forEach(u=>{p+=this.getNumNGrams(l,u)}),this.preserveShort&&l>0&&p===0&&(p=1),s[o]=s[o-1]+p}let i=new Array(s[a]);for(let o=0;o<a;++o){let l=t[o],p=s[o];if(this.nGramWidths.forEach(u=>{let d=t[o+1]-t[o],h=this.getNumNGrams(d,u);this.createNGrams(e,l,i,p,h,u),p+=h}),this.preserveShort&&p===s[o]){let u=t[o+1]-t[o];if(u===0)continue;let d=u+2*this.padWidth;this.createNGrams(e,l,i,p,1,d)}}return[i,s]}};function Gv(e,t,r,n,a,s,i,o){return new lK(r,n,a,s,i,o).compute(e,t)}function uK(e,t,r,n){if(!e.length)return;if(t.length===0){for(let s=0;s<e.length;++s)n.push(e.subarray(s,s+1));return}if(t.length===1){let s=t[0],i=e.indexOf(s);for(;i!==-1;){let o=e.subarray(0,i);(!r||o.length!==0)&&n.push(o),e=e.subarray(i+1),i=e.indexOf(s)}(!r||e.length!==0)&&n.push(e);return}let a=0;for(let s=0;s<e.length+1;s++)if(s===e.length||t.indexOf(e[s])!==-1){let i=e.subarray(a,s);(!r||i.length!==0)&&n.push(i),a=s+1}}function Hv(e,t,r){let n=e.length,a=[],s=0,i=0,o=new Array(n);for(let h=0;h<n;++h){let c=a.length;uK(e[h],t,r,a);let f=a.length-c;o[h]=f,s+=f,i=Math.max(i,f)}let l=k.getArrayFromDType("int32",s*2),p=new Array(s),u=[n,i],d=0;for(let h=0;h<n;++h)for(let c=0;c<o[h];++c)l[d*2]=h,l[d*2+1]=c,p[d]=a[d],++d;return[l,p,u]}function jv(e,t){let r=k.getArrayFromDType("int32",e.length);for(let n=0;n<e.length;++n)r[n]=k.fingerPrint64(e[n]).modulo(t).getLowBitsUnsigned();return r}var oT=Et((e,t)=>e-t),pK=Lv((e,t,r,n)=>({real:e-r,imag:t-n})),qv=Gt(jo,oT,pK),dK={kernelName:jo,backendName:"cpu",kernelFunc:qv};function lT(e,t){let r=new Array(e.rank);for(let a=0;a<r.length;a++)r[a]=e.shape[a]*t[a];let n=Le(r,e.dtype);for(let a=0;a<n.values.length;++a){let s=n.indexToLoc(a),i=new Array(e.rank);for(let l=0;l<i.length;l++)i[l]=s[l]%e.shape[l];let o=e.locToIndex(i);n.values[a]=e.values[o]}return n}var Ap=(e,t)=>{let r=t.value-e.value;return r===0?e.index-t.index:r};function uT(e,t,r=0,n=e.length-1){for(;n>r;){if(n-r>600){let o=n-r+1,l=t-r+1,p=Math.log(o),u=.5*Math.exp(2*p/3),d=.5*Math.sqrt(p*u*(o-u)/o)*Math.sign(l-o/2),h=Math.max(r,Math.floor(t-l*u/o+d)),c=Math.min(n,Math.floor(t+(o-l)*u/o+d));uT(e,t,h,c)}let a=e[t],s=r,i=n;for(k.swap(e,r,t),Ap(e[n],a)>0&&k.swap(e,r,n);s<i;){for(k.swap(e,s,i),s++,i--;Ap(e[s],a)<0;)s=s+1;for(;Ap(e[i],a)>0;)i=i-1}Ap(e[r],a)===0?k.swap(e,r,i):(i=i+1,k.swap(e,i,n)),i<=t&&(r=i+1),t<=i&&(n=i-1)}}function pT(e,t,r,n,a){let s=t[t.length-1],[i,o]=[e.length/s,s],l=k.getTypedArrayFromDType(r,i*n),p=k.getTypedArrayFromDType("int32",i*n);for(let d=0;d<i;d++){let h=d*o,c=e.subarray(h,h+o),f=new Array(c.length);c.forEach((b,x)=>f[x]={value:b,index:x}),n<f.length&&(uT(f,n),f=f.slice(0,n)),a&&f.sort(Ap);let m=d*n,g=l.subarray(m,m+n),y=p.subarray(m,m+n);for(let b=0;b<n;b++)g[b]=f[b].value,y[b]=f[b].index}let u=t.slice();return u[u.length-1]=n,[Le(u,r,l),Le(u,"int32",p)]}function Kv(e,t,r,n){let a=k.parseAxisParam(t,r)[0],s=[1,r[0],1];for(let f=0;f<a;f++)s[0]*=r[f];s[1]=r[a];for(let f=a+1;f<r.length;f++)s[2]*=r[f];let i=new Map,o=new Int32Array(r[a]),l=new Dt(s,n,e),p=[],u=s[0]===1&&s[2]===1;for(let f=0;f<r[a];f++){let m;if(u)m=e[f].toString();else{let y=[];for(let b=0;b<s[0];b++)for(let x=0;x<s[2];x++)y.push(l.get(b,f,x));m=y.join(",")}let g=i.get(m);if(g!=null)o[f]=g;else{let y=i.size;i.set(m,y),o[f]=y,p.push(f)}}let d=s.slice();d[1]=i.size;let h=new Dt(d,n);p.forEach((f,m)=>{for(let g=0;g<s[0];g++)for(let y=0;y<s[2];y++)h.set(l.get(g,f,y),g,m,y)});let c=r.slice();return c[a]=d[1],{outputValues:h.values,outputShape:c,indices:o}}var hK="4.22.0";ff("cpu",()=>new Mv,1);var dT=at(Ji,e=>e>=0?e:Math.exp(e)-1),cK={kernelName:Ji,backendName:"cpu",kernelFunc:dT};function hT(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{alpha:s}=n;ye([a],"leakyRelu");let i=k.sizeFromShape(a.shape),o=r.data.get(a.dataId).values,l=k.getTypedArrayFromDType("float32",i);for(let p=0;p<o.length;p++)l[p]=o[p]<0?s*o[p]:o[p];return r.makeTensorInfo(a.shape,"float32",l)}var fK={kernelName:uo,backendName:"cpu",kernelFunc:hT},mK=Et((e,t)=>e<0?t*e:e);function cT(e){let{inputs:t,backend:r}=e,{x:n,alpha:a}=t;ye([n,a],"prelu");let s=r.data.get(n.dataId).values,i=r.data.get(a.dataId).values,[o,l]=mK(n.shape,a.shape,s,i,"float32");return r.makeTensorInfo(l,"float32",o)}var gK={kernelName:_o,backendName:"cpu",kernelFunc:cT},fT=at(Eo,e=>Math.max(0,e)),yK={kernelName:Eo,backendName:"cpu",kernelFunc:fT},mT=at(Fo,e=>Math.min(Math.max(0,e),6)),bK={kernelName:Fo,backendName:"cpu",kernelFunc:mT};function Dc(e,t,r,n,a){if(r==="linear")return ca({inputs:{x:t},backend:e});if(r==="relu")return fT({inputs:{x:t},backend:e});if(r==="elu")return dT({inputs:{x:t},backend:e});if(r==="relu6")return mT({inputs:{x:t},backend:e});if(r==="prelu")return cT({inputs:{x:t,alpha:n},backend:e});if(r==="leakyrelu")return hT({inputs:{x:t},backend:e,attrs:{alpha:a}});if(r==="sigmoid")return tT({inputs:{x:t},backend:e});throw new Error(`Activation ${r} has not been implemented for the CPU backend.`)}function yt(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{shape:s}=n,i=k.sizeFromShape(a.shape),o=k.inferFromImplicitShape(s,i),l=k.sizeFromShape(o);k.assert(i===l,()=>`The new shape (${o}) has ${l} elements and the old shape (${a.shape}) has ${i} elements. The new shape and old shape must have the same number of elements.`),r.incRef(a.dataId);let p=r.data.get(a.dataId);if(p.complexTensorInfos!=null){let u=p.complexTensorInfos.real,d=p.complexTensorInfos.imag;u.shape=o,d.shape=o}return{dataId:a.dataId,shape:o,dtype:a.dtype}}var xK={kernelName:Fu,backendName:"cpu",kernelFunc:yt};function gT(e){let{inputs:t,backend:r,attrs:n}=e,{a,b:s}=t,{transposeA:i,transposeB:o}=n;ye([a,s],"matMul");let l=a.shape.length,p=s.shape.length,u=i?a.shape[l-2]:a.shape[l-1],d=o?s.shape[p-1]:s.shape[p-2],h=i?a.shape[l-1]:a.shape[l-2],c=o?s.shape[p-2]:s.shape[p-1],f=a.shape.slice(0,-2),m=s.shape.slice(0,-2),g=k.sizeFromShape(f),y=k.sizeFromShape(m),b=Zu.assertAndGetBroadcastShape(a.shape.slice(0,-2),s.shape.slice(0,-2)).concat([h,c]);k.assert(u===d,()=>`Error in matMul: inner shapes (${u}) and (${d}) of Tensors with shapes ${a.shape} and ${s.shape} and transposeA=${i} and transposeB=${o} must match.`);let x=i?[g,u,h]:[g,h,u],v=o?[y,c,d]:[y,d,c],w=yt({inputs:{x:a},backend:r,attrs:{shape:x}}),N=yt({inputs:{x:s},backend:r,attrs:{shape:v}}),T=i?w.shape[1]:w.shape[2],E=i?w.shape[2]:w.shape[1],$=o?N.shape[1]:N.shape[2],R=Math.max(g,y),F=r.data.get(w.dataId).values,S=r.data.get(N.dataId).values,D=k.computeStrides(w.shape),P=k.computeStrides(N.shape),[U,H,q]=i?[D[0],1,D[1]]:[D[0],D[1],1],[G,Z,ee]=o?[1,P[1],P[0]]:[P[1],1,P[0]],X=E*$,re=Le([R,E,$],w.dtype),te=re.values,ae=r.blockSize;for(let ie=0;ie<R;ie++){let ve=ie%g,be=ie%y;for(let he=0;he<E;he+=ae){let Ie=Math.min(he+ae,E);for(let _e=0;_e<$;_e+=ae){let Fe=Math.min(_e+ae,$);for(let Pe=0;Pe<T;Pe+=ae){let st=Math.min(Pe+ae,T);for(let Ge=he;Ge<Ie;Ge++)for(let qe=_e;qe<Fe;qe++){let $e=0;for(let Je=Pe;Je<st;Je++){let ht=F[ve*U+Ge*H+Je*q],Lr=S[Je*G+qe*Z+be*ee];$e+=ht*Lr}te[ie*X+(Ge*$+qe)]+=$e}}}}}return r.disposeIntermediateTensorInfo(w),r.disposeIntermediateTensorInfo(N),r.makeTensorInfo(b,re.dtype,re.values)}var vK={kernelName:Pi,backendName:"cpu",kernelFunc:gT};function wK(e){let{inputs:t,backend:r,attrs:n}=e,{a,b:s,bias:i,preluActivationWeights:o}=t,{transposeA:l,transposeB:p,activation:u,leakyreluAlpha:d}=n,h,c,f,m=[];h=gT({inputs:{a,b:s},attrs:{transposeA:l,transposeB:p},backend:r}),i&&(c=Bl({inputs:{a:h,b:i},backend:r}),m.push(h),h=c),u&&(f=Dc(r,h,u,o,d),m.push(h),h=f);for(let g of m)r.disposeIntermediateTensorInfo(g);return h}var kK={kernelName:li,backendName:"cpu",kernelFunc:wK},IK=at($i,e=>Math.acos(e)),SK={kernelName:$i,backendName:"cpu",kernelFunc:IK},NK=at(Ai,e=>Math.acosh(e)),_K={kernelName:Ai,backendName:"cpu",kernelFunc:NK};function TK(e){let{inputs:t,backend:r}=e,n=t;ye(t,"addN");let a=n.map(o=>r.data.get(o.dataId).values),s=Le(n[0].shape,n[0].dtype),i=s.values;for(let o=0;o<n.length;o++){let l=a[o];for(let p=0;p<i.length;p++)i[p]+=l[p]}return r.makeTensorInfo(s.shape,s.dtype,s.values)}var CK={kernelName:Fi,backendName:"cpu",kernelFunc:TK};function EK(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{axis:s,keepDims:i}=n;ye(a,"all");let o=k.parseAxisParam(s,a.shape),l=o,p=_.getAxesPermutation(l,a.shape.length),u=a;p!=null&&(u=Mr({inputs:{x:a},backend:r,attrs:{perm:p}}),l=_.getInnerMostAxes(l.length,a.shape.length)),_.assertAxesAreInnerMostDims("all",l,u.shape.length);let[d,h]=_.computeOutAndReduceShapes(u.shape,l),c=k.sizeFromShape(h),f=k.makeZerosTypedArray(k.sizeFromShape(d),u.dtype),m=r.data.get(u.dataId).values;for(let y=0;y<f.length;++y){let b=y*c,x=m[b];for(let v=0;v<c;++v){let w=m[b+v];x=x&&w}f[y]=x}p!=null&&r.disposeIntermediateTensorInfo(u);let g=r.makeTensorInfo(d,u.dtype,f);if(i){let y=_.expandShapeToKeepDim(d,o),b=yt({inputs:{x:g},backend:r,attrs:{shape:y}});return r.disposeIntermediateTensorInfo(g),b}return g}var $K={kernelName:Xl,backendName:"cpu",kernelFunc:EK};function AK(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{axis:s,keepDims:i}=n;ye(a,"any");let o=k.parseAxisParam(s,a.shape),l=o,p=_.getAxesPermutation(l,a.shape.length),u=a;p!=null&&(u=Mr({inputs:{x:a},backend:r,attrs:{perm:p}}),l=_.getInnerMostAxes(l.length,a.shape.length)),_.assertAxesAreInnerMostDims("any",l,u.shape.length);let[d,h]=_.computeOutAndReduceShapes(u.shape,l),c=k.sizeFromShape(h),f=k.makeZerosTypedArray(k.sizeFromShape(d),u.dtype),m=r.data.get(u.dataId).values;for(let y=0;y<f.length;++y){let b=y*c,x=m[b];for(let v=0;v<c;++v){let w=m[b+v];x=x||w}f[y]=x}p!=null&&r.disposeIntermediateTensorInfo(u);let g=r.makeTensorInfo(d,u.dtype,f);if(i){let y=_.expandShapeToKeepDim(d,o),b=yt({inputs:{x:g},backend:r,attrs:{shape:y}});return r.disposeIntermediateTensorInfo(g),b}return g}var FK={kernelName:Zl,backendName:"cpu",kernelFunc:AK};function RK(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{axis:s}=n;ye(a,"argMax");let i=k.parseAxisParam(s,a.shape),o=_.getAxesPermutation(i,a.shape.length),l=a,p=[];o!=null&&(l=Mr({inputs:{x:a},backend:r,attrs:{perm:o}}),p.push(l),i=_.getInnerMostAxes(i.length,l.shape.length)),i=[i[0]],_.assertAxesAreInnerMostDims("argMax",i,l.shape.length);let[u,d]=_.computeOutAndReduceShapes(l.shape,i),h=k.sizeFromShape(u),c=k.makeZerosTypedArray(h,"int32"),f=k.sizeFromShape(d),m=r.data.get(l.dataId).values;for(let g=0;g<c.length;++g){let y=g*f,b=m[y],x=0;for(let v=0;v<f;++v){let w=m[y+v];w>b&&(b=w,x=v)}c[g]=x}return p.forEach(g=>r.disposeIntermediateTensorInfo(g)),r.makeTensorInfo(u,"int32",c)}var DK={kernelName:Jl,backendName:"cpu",kernelFunc:RK};function MK(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{axis:s}=n;ye(a,"argMin");let i=k.parseAxisParam(s,a.shape),o=_.getAxesPermutation(i,a.shape.length),l=a,p=[];o!=null&&(l=Mr({inputs:{x:a},backend:r,attrs:{perm:o}}),p.push(l),i=_.getInnerMostAxes(i.length,l.shape.length)),i=[i[0]],_.assertAxesAreInnerMostDims("argMin",i,l.shape.length);let[u,d]=_.computeOutAndReduceShapes(l.shape,i),h=k.sizeFromShape(u),c=k.makeZerosTypedArray(h,"int32"),f=k.sizeFromShape(d),m=r.data.get(l.dataId).values;for(let g=0;g<c.length;++g){let y=g*f,b=m[y],x=0;for(let v=0;v<f;++v){let w=m[y+v];w<b&&(b=w,x=v)}c[g]=x}return p.forEach(g=>r.disposeIntermediateTensorInfo(g)),r.makeTensorInfo(u,"int32",c)}var OK={kernelName:Yl,backendName:"cpu",kernelFunc:MK},LK=at(Ri,e=>Math.asin(e)),zK={kernelName:Ri,backendName:"cpu",kernelFunc:LK},PK=at(Di,e=>Math.asinh(e)),BK={kernelName:Di,backendName:"cpu",kernelFunc:PK},WK=at(Mi,e=>Math.atan(e)),UK={kernelName:Mi,backendName:"cpu",kernelFunc:WK},VK=Et((e,t)=>Math.atan2(e,t)),GK=Gt(Li,VK),HK={kernelName:Li,backendName:"cpu",kernelFunc:GK},jK=at(Oi,e=>Math.atanh(e)),qK={kernelName:Oi,backendName:"cpu",kernelFunc:jK};function Xv(e,t,r,n,a,s){let i=a.strideHeight,o=a.strideWidth,l=a.dilationHeight,p=a.dilationWidth,u=a.effectiveFilterHeight,d=a.effectiveFilterWidth,h=a.padInfo.top,c=a.padInfo.left,f=s==="max"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,m=Le(a.outShape,r),g=m.values,y=a.outShape[1]*a.outShape[2]*a.outShape[3],b=a.outShape[2]*a.outShape[3],x=a.outShape[3];for(let v=0;v<a.batchSize;++v){let w=v*y,N=v*n[0];for(let T=0;T<a.inChannels;++T)for(let E=0;E<a.outHeight;++E){let $=E*i-h,R=Math.max(0,$),F=Math.min(a.inHeight,u+$),S=w+E*b;for(let D=0;D<a.outWidth;++D){let P=D*o-c,U=Math.max(0,P),H=Math.min(a.inWidth,d+P),q=f,G=0,Z=0;for(let X=R;X<F;X+=l){let re=N+X*n[1];for(let te=U;te<H;te+=p){let ae=re+te*n[2],ie=e[ae+T];s==="max"&&ie>q?q=ie:s==="avg"&&(G+=ie,Z++)}if(isNaN(q))break}let ee=S+D*x+T;g[ee]=s==="avg"?G/Z:q}}}return m}function yT(e,t,r,n,a=!1,s=!1){let i=Le(n.outShape,"int32"),o=n.strideHeight,l=n.strideWidth,p=n.dilationHeight,u=n.dilationWidth,d=n.effectiveFilterHeight,h=n.effectiveFilterWidth,c=n.padInfo.top,f=n.padInfo.left,m=Le(t,r,e);for(let g=0;g<n.batchSize;++g)for(let y=0;y<n.inChannels;++y)for(let b=0;b<n.outHeight;++b){let x=b*o-c,v=x;for(;v<0;)v+=p;let w=Math.min(n.inHeight,d+x);for(let N=0;N<n.outWidth;++N){let T=N*l-f,E=T;for(;E<0;)E+=u;let $=Math.min(n.inWidth,h+T),R=Number.NEGATIVE_INFINITY,F=-1;for(let S=v;S<w;S+=p){let D=S-x;for(let P=E;P<$;P+=u){let U=P-T,H=m.get(g,S,P,y);H>R&&(R=H,a?F=s?((g*n.inHeight+S)*n.inWidth+P)*n.inChannels+y:(S*n.inWidth+P)*n.inChannels+y:F=D*h+U)}}i.set(F,g,b,N,y)}}return i}function bT(e,t,r,n,a,s){let i=a.strideDepth,o=a.strideHeight,l=a.strideWidth,p=a.dilationDepth,u=a.dilationHeight,d=a.dilationWidth,h=a.effectiveFilterDepth,c=a.effectiveFilterHeight,f=a.effectiveFilterWidth,m=a.padInfo.front,g=a.padInfo.top,y=a.padInfo.left,b=s==="max"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,x=Le(a.outShape,r),v=x.values,w=a.outShape[1]*a.outShape[2]*a.outShape[3]*a.outShape[4],N=a.outShape[2]*a.outShape[3]*a.outShape[4],T=a.outShape[3]*a.outShape[4],E=a.outShape[4];for(let $=0;$<a.batchSize;++$){let R=$*w,F=$*n[0];for(let S=0;S<a.inChannels;++S)for(let D=0;D<a.outDepth;++D){let P=D*i-m,U=P;for(;U<0;)U+=p;let H=Math.min(a.inDepth,h+P),q=R+D*N;for(let G=0;G<a.outHeight;++G){let Z=G*o-g,ee=Z;for(;ee<0;)ee+=u;let X=Math.min(a.inHeight,c+Z),re=q+G*T;for(let te=0;te<a.outWidth;++te){let ae=te*l-y,ie=ae;for(;ie<0;)ie+=d;let ve=Math.min(a.inWidth,f+ae),be=re+te*E,he=b,Ie=0,_e=0;for(let Pe=U;Pe<H;Pe+=p){let st=F+Pe*n[1];for(let Ge=ee;Ge<X;Ge+=u){let qe=st+Ge*n[2];for(let $e=ie;$e<ve;$e+=d){let Je=qe+$e*n[3],ht=e[Je+S];if(s==="max"&&ht>he?he=ht:s==="avg"&&(Ie+=ht,_e++),isNaN(he))break}if(isNaN(he))break}if(isNaN(he))break}let Fe=be+S;v[Fe]=s==="avg"?Ie/Math.max(_e,1):he}}}}return x}function KK(e,t){let r=Le(t.outShape,"int32"),n=t.strideDepth,a=t.strideHeight,s=t.strideWidth,i=t.dilationDepth,o=t.dilationHeight,l=t.dilationWidth,p=t.effectiveFilterDepth,u=t.effectiveFilterHeight,d=t.effectiveFilterWidth,h=t.padInfo.front,c=t.padInfo.top,f=t.padInfo.left;for(let m=0;m<t.batchSize;++m)for(let g=0;g<t.inChannels;++g)for(let y=0;y<t.outDepth;++y){let b=y*n-h,x=b;for(;x<0;)x+=i;let v=Math.min(t.inDepth,p+b);for(let w=0;w<t.outHeight;++w){let N=w*a-c,T=N;for(;T<0;)T+=o;let E=Math.min(t.inHeight,u+N);for(let $=0;$<t.outWidth;++$){let R=$*s-f,F=R;for(;F<0;)F+=l;let S=Math.min(t.inWidth,d+R),D=Number.NEGATIVE_INFINITY,P=-1;for(let U=x;U<v;U+=i){let H=U-b;for(let q=T;q<E;q+=o){let G=q-N;for(let Z=F;Z<S;Z+=l){let ee=Z-R,X=e.get(m,U,q,Z,g);X>=D&&(D=X,P=H*u*d+G*u+ee)}}}r.set(P,m,y,w,$,g)}}}return r}function XK(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t;ye(a,"avgPool");let{filterSize:s,strides:i,pad:o,dimRoundingMode:l}=n,p=1;k.assert(_.eitherStridesOrDilationsAreOne(i,p),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${i} and dilations '${p}'`);let u=_.computePool2DInfo(a.shape,s,i,p,o,l),d;if(u.filterWidth===1&&u.filterHeight===1&&k.arraysEqual(u.inShape,u.outShape))d=ca({inputs:{x:a},backend:r});else{let h=r.data.get(a.dataId).values,c=k.computeStrides(a.shape),f=Xv(h,a.shape,a.dtype,c,u,"avg");d=r.makeTensorInfo(u.outShape,a.dtype,f.values)}return d}var ZK={kernelName:zi,backendName:"cpu",kernelFunc:XK};function JK(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{filterSize:s,strides:i,pad:o,dimRoundingMode:l,dataFormat:p}=n;ye(a,"avgPool3d");let u=_.computePool3DInfo(a.shape,s,i,1,o,l,p),d=r.data.get(a.dataId).values,h=bT(d,a.shape,a.dtype,k.computeStrides(a.shape),u,"avg");return r.makeTensorInfo(h.shape,"float32",h.values)}var YK={kernelName:Ql,backendName:"cpu",kernelFunc:JK};function QK(e){let{inputs:t,backend:r,attrs:n}=e,{dy:a,input:s}=t,{filterSize:i,strides:o,pad:l,dimRoundingMode:p}=n;ye([a,s],"avgPool3DGrad");let u=_.computePool3DInfo(s.shape,i,o,1,l,p),d=u.strideDepth,h=u.strideHeight,c=u.strideWidth,f=u.filterDepth,m=u.filterHeight,g=u.filterWidth,y=u.dilationDepth,b=u.dilationHeight,x=u.dilationWidth,v=u.effectiveFilterDepth,w=u.effectiveFilterHeight,N=u.effectiveFilterWidth,T=v-1-u.padInfo.front,E=N-1-u.padInfo.left,$=w-1-u.padInfo.top,R=Le(s.shape,"float32"),F=1/(f*m*g),S=r.bufferSync(a);for(let D=0;D<u.batchSize;++D)for(let P=0;P<u.inChannels;++P)for(let U=0;U<u.inDepth;++U)for(let H=0;H<u.inHeight;++H)for(let q=0;q<u.inWidth;++q){let G=U-T,Z=H-$,ee=q-E,X=0;for(let re=0;re<v;re+=y){let te=(G+re)/d;if(!(te<0||te>=u.outDepth||Math.floor(te)!==te))for(let ae=0;ae<w;ae+=b){let ie=(Z+ae)/h;if(!(ie<0||ie>=u.outHeight||Math.floor(ie)!==ie))for(let ve=0;ve<N;ve+=x){let be=(ee+ve)/c;if(be<0||be>=u.outWidth||Math.floor(be)!==be)continue;let he=S.get(D,te,ie,be,P);X+=he}}}R.set(X*F,D,U,H,q,P)}return r.makeTensorInfo(R.shape,R.dtype,R.values)}var e8={kernelName:cd,backendName:"cpu",kernelFunc:QK};function t8(e){let{inputs:t,backend:r,attrs:n}=e,{dy:a,input:s}=t,i=s;ye([a,s],"avgPoolGrad");let{filterSize:o,strides:l,pad:p}=n,u=_.computePool2DInfo(i.shape,o,l,1,p),d=u.strideHeight,h=u.strideWidth,c=u.filterHeight,f=u.filterWidth,m=u.dilationHeight,g=u.dilationWidth,y=u.effectiveFilterHeight,b=u.effectiveFilterWidth,x=b-1-u.padInfo.left,v=y-1-u.padInfo.top,w=Le(i.shape,"float32"),N=1/(c*f),T=r.data.get(a.dataId).values,E=Le(a.shape,"float32",T);for(let $=0;$<u.batchSize;++$)for(let R=0;R<u.inChannels;++R)for(let F=0;F<u.inHeight;++F)for(let S=0;S<u.inWidth;++S){let D=F-v,P=S-x,U=0;for(let H=0;H<y;H+=m){let q=(D+H)/d;if(!(q<0||q>=u.outHeight||Math.floor(q)!==q))for(let G=0;G<b;G+=g){let Z=(P+G)/h;if(Z<0||Z>=u.outWidth||Math.floor(Z)!==Z)continue;let ee=E.get($,q,Z,R);U+=ee}}w.set(U*N,$,F,S,R)}return r.makeTensorInfo(w.shape,w.dtype,w.values)}var r8={kernelName:hd,backendName:"cpu",kernelFunc:t8};function n8(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,scale:s,offset:i,mean:o,variance:l}=t;k.assert(o.shape.length===l.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),k.assert(i==null||o.shape.length===i.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),k.assert(s==null||o.shape.length===s.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks."),ye([a,o,l,s,i],"batchNorm");let{varianceEpsilon:p}=n;p==null&&(p=.001);let u=r.data.get(a.dataId).values,d=r.data.get(o.dataId).values,h=r.data.get(l.dataId).values,c=s?r.data.get(s.dataId).values:new Float32Array([1]),f=i?r.data.get(i.dataId).values:new Float32Array([0]),m=new Float32Array(u.length),g=f.length,y=c.length,b=h.length,x=d.length,v=0,w=0,N=0,T=0;for(let E=0;E<u.length;++E)m[E]=f[v++]+(u[E]-d[w++])*c[N++]/Math.sqrt(h[T++]+p),v>=g&&(v=0),w>=x&&(w=0),N>=y&&(N=0),T>=b&&(T=0);return r.makeTensorInfo(a.shape,a.dtype,m)}var a8={kernelName:no,backendName:"cpu",kernelFunc:n8};function s8(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{blockShape:s,crops:i}=n;ye([a],"batchToSpaceND");let o=s.reduce((y,b)=>y*b),l=_.getReshaped(a.shape,s,o),p=_.getPermuted(l.length,s.length),u=_.getReshapedPermuted(a.shape,s,o),d=_.getSliceBeginCoords(i,s.length),h=_.getSliceSize(u,i,s.length),c=yt({inputs:{x:a},backend:r,attrs:{shape:l}}),f=Mr({inputs:{x:c},backend:r,attrs:{perm:p}}),m=yt({inputs:{x:f},backend:r,attrs:{shape:u}}),g=ki({inputs:{x:m},backend:r,attrs:{begin:d,size:h}});return r.disposeIntermediateTensorInfo(c),r.disposeIntermediateTensorInfo(f),r.disposeIntermediateTensorInfo(m),g}var i8={kernelName:eu,backendName:"cpu",kernelFunc:s8};function o8(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,weights:s}=t,{size:i}=n,o=r.data.get(a.dataId).values,l=r.data.get(s.dataId).values,p=zv(o,l,s.dtype,s.shape,i);return r.makeTensorInfo([i],s.dtype,p)}var l8={kernelName:tu,backendName:"cpu",kernelFunc:o8};function u8(e){let{inputs:t,backend:r}=e,{s0:n,s1:a}=t,s=r.data.get(n.dataId).values,i=r.data.get(a.dataId).values,o=_.assertAndGetBroadcastShape(Array.from(s),Array.from(i));return r.makeTensorInfo([o.length],"int32",Int32Array.from(o))}var p8={kernelName:fd,backendName:"cpu",kernelFunc:u8},d8=at(Cs,(e,t)=>{let r=t;return e>r.clipValueMax?r.clipValueMax:e<r.clipValueMin?r.clipValueMin:e}),h8={kernelName:Cs,backendName:"cpu",kernelFunc:d8},c8=e=>{let{x:t}=e.inputs,r=e.backend,n=new Float32Array(k.sizeFromShape(t.shape)),a=r.data.get(t.dataId),s=a.complexTensorInfos.real,i=a.complexTensorInfos.imag,o=r.data.get(s.dataId).values,l=r.data.get(i.dataId).values;for(let p=0;p<o.length;p++){let u=o[p],d=l[p];n[p]=Math.hypot(u,d)}return r.makeOutput(n,t.shape,"float32")},f8={kernelName:md,backendName:"cpu",kernelFunc:c8};function Wl(e){let{inputs:t,backend:r}=e,{input:n}=t,a=r.data.get(n.dataId).complexTensorInfos.imag,s=r.data.get(a.dataId).values;return r.makeTensorInfo(a.shape,a.dtype,s)}var m8={kernelName:of,backendName:"cpu",kernelFunc:Wl};function Ul(e){let{inputs:t,backend:r,attrs:n}=e,{axis:a}=n,s=k.parseAxisParam(a,t[0].shape)[0],i=t.map(m=>m.shape);_.assertParamsConsistent(i,s);let o=_.computeOutShape(t.map(m=>m.shape),s);if(k.sizeFromShape(o)===0)return r.makeTensorInfo(o,t[0].dtype,[]);let l=t.filter(m=>k.sizeFromShape(m.shape)>0);if(l.length===1)return ca({inputs:{x:l[0]},backend:r});if(l[0].dtype==="complex64"){let m=l.map(v=>wi({inputs:{input:v},backend:r})),g=l.map(v=>Wl({inputs:{input:v},backend:r})),y=Ul({inputs:m,backend:r,attrs:{axis:s}}),b=Ul({inputs:g,backend:r,attrs:{axis:s}}),x=Hr({inputs:{real:y,imag:b},backend:r});return m.forEach(v=>r.disposeIntermediateTensorInfo(v)),g.forEach(v=>r.disposeIntermediateTensorInfo(v)),r.disposeIntermediateTensorInfo(y),r.disposeIntermediateTensorInfo(b),x}let p=l.map(m=>{let g=[-1,k.sizeFromShape(m.shape.slice(s))];return yt({inputs:{x:m},backend:r,attrs:{shape:g}})}),u=p.map(m=>({vals:r.data.get(m.dataId).values,shape:m.shape}));o=_.computeOutShape(p.map(m=>m.shape),1);let d=p[0].shape[0]===1,h=Pv(u,o,t[0].dtype,d),c=_.computeOutShape(l.map(m=>m.shape),s),f=r.makeTensorInfo(c,t[0].dtype,h);return p.forEach(m=>r.disposeIntermediateTensorInfo(m)),f}var g8={kernelName:nu,backendName:"cpu",kernelFunc:Ul};function xT(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,filter:s}=t,{strides:i,pad:o,dataFormat:l,dilations:p,dimRoundingMode:u}=n;ye([a,s],"conv2d");let d=_.convertConv2DDataFormat(l),h=_.computeConv2DInfo(a.shape,s.shape,i,p,o,u,!1,d),c=h.filterHeight,f=h.filterWidth,m=h.dilationHeight,g=h.dilationWidth,y=h.padInfo.left,b=h.padInfo.top,x=h.dataFormat==="channelsLast",v=new Dt(h.outShape,a.dtype),w=k.computeStrides(a.shape),N=k.computeStrides(s.shape),T=w[0],E=x?w[1]:w[2],$=x?w[2]:1,R=x?1:w[1],F=v.strides[0],S=x?v.strides[1]:v.strides[2],D=x?v.strides[2]:1,P=x?1:v.strides[1],U=r.data.get(a.dataId).values,H=r.data.get(s.dataId).values,q=v.values;for(let G=0;G<h.batchSize;++G){let Z=G*T,ee=G*F;for(let X=0;X<h.outHeight;++X){let re=ee+X*S,te=X*h.strideHeight-b;for(let ae=0;ae<c;++ae){let ie=te+ae*m;if(ie<0||ie>=h.inHeight)continue;let ve=ae*N[0],be=Z+ie*E;for(let he=0;he<h.outWidth;++he){let Ie=re+he*D,_e=he*h.strideWidth-y;for(let Fe=0;Fe<f;++Fe){let Pe=_e+Fe*g;if(Pe<0||Pe>=h.inWidth)continue;let st=ve+Fe*N[1],Ge=be+Pe*$,qe=st;for(let $e=0;$e<h.inChannels;++$e){let Je=U[Ge+$e*R];for(let ht=0;ht<h.outChannels;++ht)q[Ie+ht*P]+=Je*H[qe+ht];qe+=h.outChannels}}}}}}return r.makeTensorInfo(v.shape,v.dtype,q)}var y8={kernelName:Ui,backendName:"cpu",kernelFunc:xT};function b8(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,dy:s}=t,{strides:i,pad:o,dataFormat:l,dimRoundingMode:p,filterShape:u}=n;ye([a,s],"conv2dBackpropFilter");let d=_.convertConv2DDataFormat(l),h=_.computeConv2DInfo(a.shape,u,i,1,o,p,!1,d),{strideHeight:c,strideWidth:f,filterHeight:m,filterWidth:g}=h,y=h.dataFormat==="channelsLast",b=new Dt(h.filterShape,"float32"),x=h.padInfo.left,v=h.padInfo.top,w=r.data.get(a.dataId).values,N=r.data.get(s.dataId).values,T=new Dt(a.shape,a.dtype,w),E=new Dt(s.shape,s.dtype,N);for(let $=0;$<m;++$){let R=Math.max(0,Math.ceil((v-$)/c)),F=Math.min(h.outHeight,(h.inHeight+v-$)/c);for(let S=0;S<g;++S){let D=Math.max(0,Math.ceil((x-S)/f)),P=Math.min(h.outWidth,(h.inWidth+x-S)/f);for(let U=0;U<h.inChannels;++U)for(let H=0;H<h.outChannels;++H){let q=0;for(let G=0;G<h.batchSize;++G)for(let Z=R;Z<F;++Z){let ee=$+Z*c-v;for(let X=D;X<P;++X){let re=S+X*f-x;y?q+=T.get(G,ee,re,U)*E.get(G,Z,X,H):q+=T.get(G,U,ee,re)*E.get(G,H,Z,X)}}b.set(q,$,S,U,H)}}}return r.makeTensorInfo(b.shape,b.dtype,b.values)}var x8={kernelName:Qc,backendName:"cpu",kernelFunc:b8};function v8(e){let{inputs:t,backend:r,attrs:n}=e,{dy:a,filter:s}=t,{inputShape:i,strides:o,pad:l,dataFormat:p,dimRoundingMode:u}=n;ye([a,s],"conv2dBackpropInput");let d=k.computeStrides(s.shape),h=k.computeStrides(a.shape),c=_.convertConv2DDataFormat(p),f=_.computeConv2DInfo(i,s.shape,o,1,l,u,!1,c),m=new Dt(f.inShape,"float32"),g=m.values,y=r.data.get(a.dataId).values,b=r.data.get(s.dataId).values,[x,v,w]=d,{batchSize:N,filterHeight:T,filterWidth:E,inChannels:$,inHeight:R,inWidth:F,outChannels:S,outHeight:D,outWidth:P,strideHeight:U,strideWidth:H}=f;c=f.dataFormat;let q=T-1-f.padInfo.top,G=E-1-f.padInfo.left,Z=c==="channelsLast",ee=m.strides[0],X=Z?m.strides[1]:m.strides[2],re=Z?m.strides[2]:1,te=Z?1:m.strides[1],ae=h[0],ie=Z?h[1]:h[2],ve=Z?h[2]:1,be=Z?1:h[1];for(let he=0;he<N;++he)for(let Ie=0;Ie<$;++Ie)for(let _e=0;_e<R;++_e){let Fe=_e-q,Pe=Math.max(0,Math.ceil(Fe/U)),st=Math.min(D,(T+Fe)/U);for(let Ge=0;Ge<F;++Ge){let qe=Ge-G,$e=Math.max(0,Math.ceil(qe/H)),Je=Math.min(P,(E+qe)/H),ht=0;for(let _t=Pe;_t<st;++_t){let Nr=_t*U-Fe;for(let tr=$e;tr<Je;++tr){let _r=tr*H-qe,yn=ae*he+ie*_t+ve*tr,zr=x*(T-1-Nr)+v*(E-1-_r)+w*Ie;for(let Tr=0;Tr<S;++Tr){let rr=y[yn+be*Tr],Qr=b[zr+Tr];ht+=rr*Qr}}}let Lr=ee*he+X*_e+re*Ge+te*Ie;g[Lr]=ht}}return r.makeTensorInfo(m.shape,m.dtype,m.values)}var w8={kernelName:Vi,backendName:"cpu",kernelFunc:v8};function k8(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,filter:s}=t,{strides:i,pad:o,dilations:l}=n;ye([a,s],"conv3d");let p=_.computeConv3DInfo(a.shape,s.shape,i,l,o),{filterDepth:u,filterHeight:d,filterWidth:h,dilationDepth:c,dilationHeight:f,dilationWidth:m,padInfo:g}=p,y=g.front,b=g.left,x=g.top,v=new Dt(p.outShape,a.dtype),w=r.data.get(a.dataId).values,N=r.data.get(s.dataId).values,T=v.values,E=k.computeStrides(a.shape),$=k.computeStrides(s.shape);for(let R=0;R<p.batchSize;++R){let F=R*E[0],S=R*v.strides[0];for(let D=0;D<p.outDepth;++D){let P=S+D*v.strides[1],U=D*p.strideDepth-y;for(let H=0;H<u;++H){let q=U+H*c;if(q<0||q>=p.inDepth)continue;let G=H*$[0],Z=F+q*E[1];for(let ee=0;ee<p.outHeight;++ee){let X=P+ee*v.strides[2],re=ee*p.strideHeight-x;for(let te=0;te<d;++te){let ae=re+te*f;if(ae<0||ae>=p.inHeight)continue;let ie=G+te*$[1],ve=Z+ae*E[2];for(let be=0;be<p.outWidth;++be){let he=X+be*p.outChannels,Ie=be*p.strideWidth-b;for(let _e=0;_e<h;++_e){let Fe=Ie+_e*m;if(Fe<0||Fe>=p.inWidth)continue;let Pe=ie+_e*$[2],st=ve+Fe*p.inChannels,Ge=Pe;for(let qe=0;qe<p.inChannels;++qe){let $e=w[st+qe];for(let Je=0;Je<p.outChannels;++Je)T[he+Je]+=$e*N[Ge+Je];Ge+=p.outChannels}}}}}}}}return r.makeTensorInfo(v.shape,v.dtype,v.values)}var I8={kernelName:Gi,backendName:"cpu",kernelFunc:k8};function S8(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,dy:s}=t,{strides:i,pad:o,filterShape:l}=n;ye([a,s],"conv3dBackpropFilterV2");let p=k.computeStrides(a.shape),u=k.computeStrides(s.shape),d=_.computeConv3DInfo(a.shape,l,i,1,o),h=d.strideDepth,c=d.strideHeight,f=d.strideWidth,m=d.filterDepth,g=d.filterHeight,y=d.filterWidth,b=new Dt(d.filterShape,"float32"),x=b.values,[v,w,N,T]=b.strides,E=r.data.get(s.dataId).values,[$,R,F,S]=u,D=r.data.get(a.dataId).values,[P,U,H,q]=p,G=d.padInfo.front,Z=d.padInfo.left,ee=d.padInfo.top;for(let X=0;X<m;++X){let re=Math.max(0,Math.ceil((G-X)/h)),te=Math.min(d.outDepth,(d.inDepth+G-X)/h),ae=X*v;for(let ie=0;ie<g;++ie){let ve=Math.max(0,Math.ceil((ee-ie)/c)),be=Math.min(d.outHeight,(d.inHeight+ee-ie)/c),he=ie*w+ae;for(let Ie=0;Ie<y;++Ie){let _e=Math.max(0,Math.ceil((Z-Ie)/f)),Fe=Math.min(d.outWidth,(d.inWidth+Z-Ie)/f),Pe=Ie*N+he;for(let st=0;st<d.inChannels;++st){let Ge=st*T+Pe;for(let qe=0;qe<d.outChannels;++qe){let $e=0;for(let Je=0;Je<d.batchSize;++Je){let ht=Je*P,Lr=Je*$;for(let _t=re;_t<te;++_t){let Nr=(X+_t*h-G)*U+ht,tr=_t*R+Lr;for(let _r=ve;_r<be;++_r){let yn=(ie+_r*c-ee)*H+Nr,zr=_r*F+tr;for(let Tr=_e;Tr<Fe;++Tr){let rr=(Ie+Tr*f-Z)*q+yn,Qr=Tr*S+zr;$e+=D[rr+st]*E[Qr+qe]}}}}x[Ge+qe]=$e}}}}}return r.makeTensorInfo(b.shape,b.dtype,b.values)}var N8={kernelName:au,backendName:"cpu",kernelFunc:S8};function _8(e){let{inputs:t,backend:r,attrs:n}=e,{dy:a,filter:s}=t,{pad:i,strides:o,inputShape:l}=n;ye([a],"conv3dBackpropInputV2");let p=k.computeStrides(a.shape),u=k.computeStrides(s.shape),d=_.computeConv3DInfo(l,s.shape,o,1,i),h=new Dt(d.inShape,"float32"),c=h.values,[f,m,g,y]=h.strides,b=r.data.get(a.dataId).values,[x,v,w,N]=p,T=r.data.get(s.dataId).values,[E,$,R,F]=u,{batchSize:S,filterDepth:D,filterHeight:P,filterWidth:U,inChannels:H,inDepth:q,inHeight:G,inWidth:Z,outChannels:ee,outDepth:X,outHeight:re,outWidth:te,strideDepth:ae,strideHeight:ie,strideWidth:ve}=d,be=D-1-d.padInfo.front,he=P-1-d.padInfo.top,Ie=U-1-d.padInfo.left;for(let _e=0;_e<S;++_e)for(let Fe=0;Fe<H;++Fe)for(let Pe=0;Pe<q;++Pe){let st=Pe-be,Ge=Math.max(0,Math.ceil(st/ae)),qe=Math.min(X,(D+st)/ae);for(let $e=0;$e<G;++$e){let Je=$e-he,ht=Math.max(0,Math.ceil(Je/ie)),Lr=Math.min(re,(P+Je)/ie);for(let _t=0;_t<Z;++_t){let Nr=_t-Ie,tr=Math.max(0,Math.ceil(Nr/ve)),_r=Math.min(te,(U+Nr)/ve),yn=0;for(let zr=Ge;zr<qe;++zr){let Tr=zr*ae-st;for(let rr=ht;rr<Lr;++rr){let Qr=rr*ie-Je;for(let Ua=tr;Ua<_r;++Ua){let yp=Ua*ve-Nr,ba=x*_e+v*zr+w*rr+N*Ua,bp=E*(D-1-Tr)+$*(P-1-Qr)+R*(U-1-yp)+F*Fe;for(let Kn=0;Kn<ee;++Kn){let Va=b[ba+Kn],nr=T[bp+Kn];yn+=Va*nr}}}}c[f*_e+m*Pe+g*$e+y*_t+Fe]=yn}}}return r.makeTensorInfo(h.shape,h.dtype,h.values)}var T8={kernelName:su,backendName:"cpu",kernelFunc:_8},C8=at(Hi,e=>Math.cos(e)),E8={kernelName:Hi,backendName:"cpu",kernelFunc:C8},$8=at(ji,e=>Math.cosh(e)),A8={kernelName:ji,backendName:"cpu",kernelFunc:$8};function F8(e){let{inputs:t,backend:r,attrs:n}=e,{image:a,boxes:s,boxInd:i}=t,{cropSize:o,method:l,extrapolationValue:p}=n,[u,d,h,c]=a.shape,f=s.shape[0],[m,g]=o,y=Le([f,m,g,c],"float32"),b=r.data.get(s.dataId).values,x=r.data.get(i.dataId).values,v=r.data.get(a.dataId).values,w=k.computeStrides(a.shape),N=k.computeStrides(y.shape);for(let T=0;T<f;T++){let E=T*4,$=b[E],R=b[E+1],F=b[E+2],S=b[E+3],D=x[T];if(D>=u)continue;let P=m>1?(F-$)*(d-1)/(m-1):0,U=g>1?(S-R)*(h-1)/(g-1):0;for(let H=0;H<m;H++){let q=m>1?$*(d-1)+H*P:.5*($+F)*(d-1);if(q<0||q>d-1){for(let G=0;G<g;G++)for(let Z=0;Z<c;Z++){let ee=Z+G*N[2]+H*N[1]+T*N[0];y.values[ee]=p}continue}if(l==="bilinear"){let G=Math.floor(q),Z=Math.ceil(q),ee=q-G;for(let X=0;X<g;X++){let re=g>1?R*(h-1)+X*U:.5*(R+S)*(h-1);if(re<0||re>h-1){for(let ve=0;ve<c;ve++){let be=ve+X*N[2]+H*N[1]+T*N[0];y.values[be]=p}continue}let te=Math.floor(re),ae=Math.ceil(re),ie=re-te;for(let ve=0;ve<c;ve++){let be=ve+te*w[2]+G*w[1]+D*w[0],he=v[be];be=ve+ae*w[2]+G*w[1]+D*w[0];let Ie=v[be];be=ve+te*w[2]+Z*w[1]+D*w[0];let _e=v[be];be=ve+ae*w[2]+Z*w[1]+D*w[0];let Fe=v[be],Pe=he+(Ie-he)*ie,st=_e+(Fe-_e)*ie;be=ve+X*N[2]+H*N[1]+T*N[0],y.values[be]=Pe+(st-Pe)*ee}}}else for(let G=0;G<g;++G){let Z=g>1?R*(h-1)+G*U:.5*(R+S)*(h-1);if(Z<0||Z>h-1){for(let re=0;re<c;re++){let te=re+G*N[2]+H*N[1]+T*N[0];y.values[te]=p}continue}let ee=Math.round(Z),X=Math.round(q);for(let re=0;re<c;re++){let te=re+ee*w[2]+X*w[1]+D*w[0],ae=re+G*N[2]+H*N[1]+T*N[0];y.values[ae]=v[te]}}}}return r.makeTensorInfo(y.shape,y.dtype,y.values)}var R8={kernelName:ou,backendName:"cpu",kernelFunc:F8};function D8(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{axis:s,exclusive:i,reverse:o}=n;ye(a,"cumprod");let l=_.getAxesPermutation([s],a.shape.length),p=a;l!=null&&(p=Mr({inputs:{x:a},backend:r,attrs:{perm:l}}));let u=_.getInnerMostAxes(1,a.shape.length)[0];if(u!==p.shape.length-1)throw new Error(`backend.cumprod in CPU expects an inner-most axis=${p.shape.length-1} but got axis=${u}`);let d=cn(p.dtype,"int32"),h=k.makeOnesTypedArray(k.sizeFromShape(p.shape),d),c=r.data.get(p.dataId).values,f=p.shape[p.shape.length-1],m=o?(y,b)=>y+f-b-1:(y,b)=>y+b;for(let y=0;y<c.length;y+=f)for(let b=0;b<f;b++){let x=m(y,b);if(b===0)h[x]=i?1:c[x];else{let v=m(y,b-1);h[x]=i?c[v]*h[v]:c[x]*h[v]}}let g=r.makeTensorInfo(p.shape,d,h);if(l!=null){let y=_.getUndoAxesPermutation(l),b=Mr({inputs:{x:g},backend:r,attrs:{perm:y}});return r.disposeIntermediateTensorInfo(g),r.disposeIntermediateTensorInfo(p),b}return g}var M8={kernelName:iu,backendName:"cpu",kernelFunc:D8};function O8(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{axis:s,exclusive:i,reverse:o}=n;ye(a,"cumsum");let l=_.getAxesPermutation([s],a.shape.length),p=a;l!=null&&(p=Mr({inputs:{x:a},backend:r,attrs:{perm:l}}));let u=_.getInnerMostAxes(1,a.shape.length)[0];if(u!==p.shape.length-1)throw new Error(`backend.cumsum in CPU expects an inner-most axis=${p.shape.length-1} but got axis=${u}`);let d=cn(p.dtype,"int32"),h=k.makeZerosTypedArray(k.sizeFromShape(p.shape),d),c=r.data.get(p.dataId).values,f=p.shape[p.shape.length-1],m=o?(y,b)=>y+f-b-1:(y,b)=>y+b;for(let y=0;y<c.length;y+=f)for(let b=0;b<f;b++){let x=m(y,b);if(b===0)h[x]=i?0:c[x];else{let v=m(y,b-1);h[x]=i?c[v]+h[v]:c[x]+h[v]}}let g=r.makeTensorInfo(p.shape,d,h);if(l!=null){let y=_.getUndoAxesPermutation(l),b=Mr({inputs:{x:g},backend:r,attrs:{perm:y}});return r.disposeIntermediateTensorInfo(g),r.disposeIntermediateTensorInfo(p),b}return g}var L8={kernelName:qi,backendName:"cpu",kernelFunc:O8};function z8(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,weights:s}=t,{size:i,binaryOutput:o}=n;if(a.shape.length===1){let l=r.data.get(a.dataId).values,p=r.data.get(s.dataId).values,u=zv(l,p,s.dtype,s.shape,i);return r.makeTensorInfo([i],s.dtype,u)}else if(a.shape.length===2){let l=r.bufferSync(a),p=r.bufferSync(s),u=T_(l,p,i,o);return r.makeTensorInfo(u.shape,s.dtype,u.values)}throw new Error(`Error in denseBincount: input must be at most rank 2, but got rank${a.shape.length}.`)}var P8={kernelName:gd,backendName:"cpu",kernelFunc:z8};function B8(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{blockSize:s,dataFormat:i}=n;k.assert(i==="NHWC",()=>`Only NHWC dataFormat supported on CPU for depthToSpace. Got ${i}`);let o=a.shape[0],l=a.shape[1],p=a.shape[2],u=a.shape[3],d=l*s,h=p*s,c=u/(s*s),f=r.data.get(a.dataId).values,m=new Float32Array(o*d*h*c),g=0;for(let y=0;y<o;++y)for(let b=0;b<d;++b){let x=Math.floor(b/s),v=b%s;for(let w=0;w<h;++w){let N=Math.floor(w/s),T=w%s,E=(v*s+T)*c;for(let $=0;$<c;++$){let R=$+E+u*(N+p*(x+l*y));m[g++]=f[R]}}}return r.makeTensorInfo([o,d,h,c],a.dtype,m)}var W8={kernelName:lu,backendName:"cpu",kernelFunc:B8};function vT(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,filter:s}=t,{strides:i,pad:o,dilations:l,dimRoundingMode:p}=n;ye([a,s],"depthwiseConv2DNative");let u=k.computeStrides(a.shape),d=k.computeStrides(s.shape),h=l;h==null&&(h=[1,1]),k.assert(_.eitherStridesOrDilationsAreOne(i,h),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${i} and dilations '${h}'`);let c=_.computeConv2DInfo(a.shape,s.shape,i,h,o,p,!0),{filterHeight:f,filterWidth:m,dilationHeight:g,dilationWidth:y,padInfo:b}=c,x=b.left,v=b.top,w=c.outChannels/c.inChannels,N=new Dt(c.outShape,a.dtype),T=r.data.get(a.dataId).values,E=r.data.get(s.dataId).values,$=N.values;for(let R=0;R<c.batchSize;++R){let F=R*u[0],S=R*N.strides[0];for(let D=0;D<c.outHeight;++D){let P=S+D*N.strides[1],U=D*c.strideHeight-v;for(let H=0;H<f;++H){let q=U+H*g;if(q<0||q>=c.inHeight)continue;let G=H*d[0],Z=F+q*u[1];for(let ee=0;ee<c.outWidth;++ee){let X=P+ee*N.strides[2],re=ee*c.strideWidth-x;for(let te=0;te<m;++te){let ae=re+te*y;if(ae<0||ae>=c.inWidth)continue;let ie=G+te*d[1],ve=Z+ae*c.inChannels,be=X,he=ie;for(let Ie=0;Ie<c.inChannels;++Ie){let _e=T[ve+Ie];for(let Fe=0;Fe<w;++Fe)$[be+Fe]+=_e*E[he+Fe];be+=w,he+=w}}}}}}return r.makeTensorInfo(N.shape,N.dtype,N.values)}var U8={kernelName:Ki,backendName:"cpu",kernelFunc:vT};function V8(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,dy:s}=t,{strides:i,dilations:o,pad:l,dimRoundingMode:p,filterShape:u}=n;ye([a,s],"depthwiseConv2dNativeBackpropFilter");let d=_.computeConv2DInfo(a.shape,u,i,o,l,p,!0),{strideHeight:h,strideWidth:c,filterHeight:f,filterWidth:m}=d,g=new Dt(d.filterShape,"float32"),y=d.padInfo.left,b=d.padInfo.top,x=d.outChannels/d.inChannels,v=r.data.get(a.dataId).values,w=new Dt(a.shape,a.dtype,v),N=r.data.get(s.dataId).values,T=new Dt(s.shape,s.dtype,N);for(let E=0;E<f;++E){let $=Math.max(0,Math.ceil((b-E)/h)),R=Math.min(d.outHeight,(d.inHeight+b-E)/h);for(let F=0;F<m;++F){let S=Math.max(0,Math.ceil((y-F)/c)),D=Math.min(d.outWidth,(d.inWidth+y-F)/c);for(let P=0;P<d.outChannels;++P){let U=Math.trunc(P/x),H=P%x,q=0;for(let G=0;G<d.batchSize;++G)for(let Z=$;Z<R;++Z){let ee=E+Z*h-b;for(let X=S;X<D;++X){let re=F+X*c-y;q+=w.get(G,ee,re,U)*T.get(G,Z,X,P)}}g.set(q,E,F,U,H)}}}return r.makeTensorInfo(g.shape,g.dtype,g.values)}var G8={kernelName:ef,backendName:"cpu",kernelFunc:V8};function H8(e){let{inputs:t,backend:r,attrs:n}=e,{dy:a,filter:s}=t,{strides:i,dilations:o,pad:l,dimRoundingMode:p,inputShape:u}=n;ye([a,s],"depthwiseConv2DNativeBackpropInput");let d=k.computeStrides(a.shape),h=k.computeStrides(s.shape),c=_.computeConv2DInfo(u,s.shape,i,o,l,p,!0),f=new Dt(c.inShape,"float32"),m=f.values,[g,y,b]=f.strides,x=r.data.get(a.dataId).values,[v,w,N]=d,T=r.data.get(s.dataId).values,[E,$,R]=h,{batchSize:F,filterHeight:S,filterWidth:D,inChannels:P,inHeight:U,inWidth:H,outChannels:q,outHeight:G,outWidth:Z,strideHeight:ee,strideWidth:X}=c,re=S-1-c.padInfo.top,te=D-1-c.padInfo.left,ae=q/P;for(let ie=0;ie<F;++ie)for(let ve=0;ve<P;++ve)for(let be=0;be<U;++be){let he=be-re,Ie=Math.max(0,Math.ceil(he/ee)),_e=Math.min(G,(S+he)/ee);for(let Fe=0;Fe<H;++Fe){let Pe=Fe-te,st=Math.max(0,Math.ceil(Pe/X)),Ge=Math.min(Z,(D+Pe)/X),qe=0;for(let $e=Ie;$e<_e;++$e){let Je=$e*ee-he;for(let ht=st;ht<Ge;++ht){let Lr=ht*X-Pe,_t=v*ie+w*$e+N*ht,Nr=E*(S-1-Je)+$*(D-1-Lr)+R*ve;for(let tr=0;tr<ae;++tr){let _r=ve*ae+tr,yn=x[_t+_r],zr=T[Nr+tr];qe+=yn*zr}}}m[g*ie+y*be+b*Fe+ve]=qe}}return r.makeTensorInfo(f.shape,f.dtype,f.values)}var j8={kernelName:tf,backendName:"cpu",kernelFunc:H8};function q8(e){let{inputs:t,backend:r}=e,{x:n}=t,a=k.sizeFromShape(n.shape),s=r.data.get(n.dataId).values,i=Le([a,a],n.dtype),o=i.values;for(let p=0;p<s.length;p++)o[p*a+p]=s[p];let l=[...n.shape,...n.shape];return r.makeTensorInfo(l,i.dtype,i.values)}var K8={kernelName:yd,backendName:"cpu",kernelFunc:q8},X8={kernelName:Xi,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:r})=>{let{x:n,filter:a}=e,{strides:s,pad:i,dilations:o}=r,l=t,p=l.data.get(n.dataId).values,u=n.shape.length,d=l.data.get(a.dataId).values,h=a.shape.length,{batchSize:c,inHeight:f,inWidth:m,inChannels:g,outHeight:y,outWidth:b,padInfo:x,strideHeight:v,strideWidth:w,filterHeight:N,filterWidth:T,dilationHeight:E,dilationWidth:$,outShape:R}=_.computeDilation2DInfo(n.shape,a.shape,s,i,"NHWC",o),F=k.sizeFromShape(R),S=R.length,D=k.getArrayFromDType(n.dtype,F);for(let P=0;P<c;++P)for(let U=0;U<y;++U){let H=U*v-x.top;for(let q=0;q<b;++q){let G=q*w-x.left;for(let Z=0;Z<g;++Z){let ee=Number.MIN_SAFE_INTEGER;for(let re=0;re<N;++re){let te=H+re*E;if(te>=0&&te<f)for(let ae=0;ae<T;++ae){let ie=G+ae*$;if(ie>=0&&ie<m){let ve=k.locToIndex([P,te,ie,Z],u,k.computeStrides(n.shape)),be=k.locToIndex([re,ae,Z],h,k.computeStrides(a.shape)),he=p[ve]+d[be];he>ee&&(ee=he)}}}let X=k.locToIndex([P,U,q,Z],S,k.computeStrides(R));D[X]=ee}}}return{dataId:l.write(k.toTypedArray(D,n.dtype),R,n.dtype),shape:R,dtype:n.dtype}}},Z8={kernelName:Cl,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:r})=>{let{x:n,filter:a,dy:s}=e,{strides:i,pad:o,dilations:l}=r,p=t,u=k.toNestedArray(n.shape,p.data.get(n.dataId).values),d=k.toNestedArray(a.shape,p.data.get(a.dataId).values),{batchSize:h,inHeight:c,inWidth:f,inChannels:m,outHeight:g,outWidth:y,padInfo:b,strideHeight:x,strideWidth:v,filterHeight:w,filterWidth:N,dilationHeight:T,dilationWidth:E,outShape:$}=_.computeDilation2DInfo(n.shape,a.shape,i,o,"NHWC",l);k.assert(s.rank===$.length,()=>`Error in ${Cl}, dy must have the same rank as output ${$.length}, but got ${s.rank}`);let R=k.toNestedArray($,p.data.get(s.dataId).values),F=k.makeZerosNestedTypedArray(a.shape,a.dtype);for(let S=0;S<h;++S)for(let D=0;D<g;++D){let P=D*x-b.top;for(let U=0;U<y;++U){let H=U*v-b.left;for(let q=0;q<m;++q){let G=Number.MIN_SAFE_INTEGER,Z=0,ee=0;for(let X=0;X<w;++X){let re=P+X*T;if(re>=0&&re<c)for(let te=0;te<N;++te){let ae=H+te*E;if(ae>=0&&ae<f){let ie=u[S][re][ae][q]+d[X][te][q];ie>G&&(G=ie,Z=X,ee=te)}}}F[Z][ee][q]+=R[S][D][U][q]}}}return{dataId:p.write(k.toTypedArray(F,n.dtype),a.shape,a.dtype),shape:a.shape,dtype:a.dtype}}},J8={kernelName:Tl,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:r})=>{let{x:n,filter:a,dy:s}=e,{strides:i,pad:o,dilations:l}=r,p=t,u=k.toNestedArray(n.shape,p.data.get(n.dataId).values),d=k.toNestedArray(a.shape,p.data.get(a.dataId).values),{batchSize:h,inHeight:c,inWidth:f,inChannels:m,outHeight:g,outWidth:y,padInfo:b,strideHeight:x,strideWidth:v,filterHeight:w,filterWidth:N,dilationHeight:T,dilationWidth:E,outShape:$}=_.computeDilation2DInfo(n.shape,a.shape,i,o,"NHWC",l);k.assert(s.rank===$.length,()=>`Error in ${Tl}, dy must have the same rank as output ${$.length}, but got ${s.rank}`);let R=k.toNestedArray($,p.data.get(s.dataId).values),F=k.makeZerosNestedTypedArray(n.shape,n.dtype);for(let S=0;S<h;++S)for(let D=0;D<g;++D){let P=D*x-b.top;for(let U=0;U<y;++U){let H=U*v-b.left;for(let q=0;q<m;++q){let G=Number.MIN_SAFE_INTEGER,Z=P<0?0:P,ee=H<0?0:H;for(let X=0;X<w;++X){let re=P+X*T;if(re>=0&&re<c)for(let te=0;te<N;++te){let ae=H+te*E;if(ae>=0&&ae<f){let ie=u[S][re][ae][q]+d[X][te][q];ie>G&&(G=ie,Z=re,ee=ae)}}}F[S][Z][ee][q]+=R[S][D][U][q]}}}return{dataId:p.write(k.toTypedArray(F,n.dtype),n.shape,n.dtype),shape:n.shape,dtype:n.dtype}}};function Y8(e){let{inputs:t,backend:r,attrs:n}=e,{image:a}=t,{canvas:s,options:i}=n,{contextOptions:o,imageOptions:l}=i||{},p=(l==null?void 0:l.alpha)||1,u=(o==null?void 0:o.contextType)||"2d";if(u!=="2d")throw new Error(`Context type ${o.contextType} is not supported by the CPU backend.`);let d=s.getContext(u,(o==null?void 0:o.contextAttributes)||{});if(d==null)throw new Error(`Could not get the context with ${u} type.`);let[h,c]=a.shape.slice(0,2),f=a.shape.length===2?1:a.shape[2],m=r.data.get(a.dataId).values,g=a.dtype==="float32"?255:1,y=new Uint8ClampedArray(c*h*4);for(let x=0;x<h*c;++x){let v=[0,0,0,255*p];for(let N=0;N<f;N++){let T=m[x*f+N];if(a.dtype==="float32"){if(T<0||T>1)throw new Error(`Tensor values for a float32 Tensor must be in the range [0 - 1] but encountered ${T}.`)}else if(a.dtype==="int32"&&(T<0||T>255))throw new Error(`Tensor values for a int32 Tensor must be in the range [0 - 255] but encountered ${T}.`);f===1?(v[0]=T*g,v[1]=T*g,v[2]=T*g):v[N]=T*g}let w=x*4;y[w+0]=Math.round(v[0]),y[w+1]=Math.round(v[1]),y[w+2]=Math.round(v[2]),y[w+3]=Math.round(v[3])}s.width=c,s.height=h;let b=new ImageData(y,c,h);return d.putImageData(b,0,0),a}var Q8={kernelName:rf,backendName:"cpu",kernelFunc:Y8};function oh(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{axis:s,keepDims:i}=n;ye(a,"sum");let o;a.dtype==="bool"?o=Is({inputs:{x:a},backend:r,attrs:{dtype:"int32"}}):o=ca({inputs:{x:a},backend:r});let l=o.shape.length,p=k.parseAxisParam(s,o.shape),u=_.getAxesPermutation(p,l),d=p,h=o;u!=null&&(h=Mr({inputs:{x:o},backend:r,attrs:{perm:u}}),d=_.getInnerMostAxes(d.length,l)),_.assertAxesAreInnerMostDims("sum",d,h.shape.length);let[c,f]=_.computeOutAndReduceShapes(h.shape,d),m=_.upcastType(h.dtype,"int32"),g=Fc(r,c,m),y=k.sizeFromShape(f),b=r.data.get(g.dataId).values,x=r.data.get(h.dataId).values;for(let v=0;v<b.length;++v){let w=v*y,N=0;for(let T=0;T<y;++T)N+=x[w+T];b[v]=N}if(i){let v=_.expandShapeToKeepDim(g.shape,p),w=g;g=yt({inputs:{x:g},backend:r,attrs:{shape:v}}),r.disposeIntermediateTensorInfo(w)}return r.disposeIntermediateTensorInfo(o),u!=null&&r.disposeIntermediateTensorInfo(h),g}var eX={kernelName:Vo,backendName:"cpu",kernelFunc:oh};function tX(e){let{inputs:t,backend:r,attrs:n}=e,{equation:a}=n,s=t,{allDims:i,summedDims:o,idDims:l}=_.decodeEinsumEquation(a,s.length);_.checkEinsumDimSizes(i.length,l,s);let{path:p,steps:u}=_.getEinsumComputePath(o,l),d=u.length,h=null,c=i.length,f=[];for(let m=0;m<d;++m){for(let g of u[m]){let{permutationIndices:y,expandDims:b}=_.getEinsumPermutation(c,l[g]),x;_.isIdentityPermutation(y)?x=s[g]:(x=Mr({inputs:{x:s[g]},backend:r,attrs:{perm:y}}),f.push(x));let v=x.shape.slice();for(let w=0;w<b.length;++w)v.splice(b[w],0,1);k.arraysEqual(x.shape,v)||(x=yt({inputs:{x},backend:r,attrs:{shape:v}}),f.push(x)),h===null?h=x:(h=ym({inputs:{a:x,b:h},backend:r}),f.push(h))}m<d-1&&(p[m]>=0&&(h=oh({inputs:{x:h},backend:r,attrs:{axis:p[m]-(i.length-c),keepDims:!1}}),f.push(h)),c--)}for(let m of f)m!==h&&r.disposeIntermediateTensorInfo(m);return h}var rX={kernelName:nf,backendName:"cpu",kernelFunc:tX};function nX(e){let{inputs:t,backend:r}=e,{dy:n,y:a}=t;ye([n,a],"eluGrad");let s=new Float32Array(k.sizeFromShape(a.shape)),i=r.data.get(a.dataId).values,o=r.data.get(n.dataId).values;for(let l=0;l<i.length;++l){let p=i[l];p>=0?s[l]=o[l]:s[l]=o[l]*(p+1)}return r.makeTensorInfo(a.shape,"float32",s)}var aX={kernelName:uu,backendName:"cpu",kernelFunc:nX},sX=_.ERF_P,iX=_.ERF_A1,oX=_.ERF_A2,lX=_.ERF_A3,uX=_.ERF_A4,pX=_.ERF_A5,dX=at(Yi,e=>{let t=Math.sign(e),r=Math.abs(e),n=1/(1+sX*r);return t*(1-((((pX*n+uX)*n+lX)*n+oX)*n+iX)*n*Math.exp(-r*r))}),hX={kernelName:Yi,backendName:"cpu",kernelFunc:dX};function Mc(e){let{inputs:t,backend:r,attrs:n}=e,{input:a}=t,{dim:s}=n,i=a.shape.length,o=a.shape.slice(),l=s;return s<0&&(k.assert(-(i+1)<=s,()=>`Axis must be in the interval [${-(i+1)}, ${i}]`),l=i+s+1),o.splice(l,0,1),yt({inputs:{x:a},backend:r,attrs:{shape:o}})}var cX={kernelName:du,backendName:"cpu",kernelFunc:Mc},fX=Et((e,t)=>e/t),Zv=Gt(Zi,fX),Hg={kernelName:Zi,backendName:"cpu",kernelFunc:Zv};function wT(e,t,r){let n=e.shape,a=n[0],s=n[1],i=r.data.get(e.dataId),o=i.complexTensorInfos.real,l=i.complexTensorInfos.imag,p=[a,s],u=k.sizeFromShape(p),d=k.getTypedArrayFromDType("float32",u),h=k.getTypedArrayFromDType("float32",u);for(let g=0;g<a;g++){let y=ki({inputs:{x:o},backend:r,attrs:{begin:[g,0],size:[1,s]}}),b=ki({inputs:{x:l},backend:r,attrs:{begin:[g,0],size:[1,s]}}),x=Hr({inputs:{real:y,imag:b},backend:r}),{real:v,imag:w}=mX(x,t,r),N=_.mergeRealAndImagArrays(v,w);for(let T=0;T<s;T++){let E=_.getComplexWithIndex(N,T);d[g*s+T]=E.real,h[g*s+T]=E.imag}r.disposeIntermediateTensorInfo(y),r.disposeIntermediateTensorInfo(b),r.disposeIntermediateTensorInfo(x)}let c=r.makeTensorInfo(p,"float32",d),f=r.makeTensorInfo(p,"float32",h),m=Hr({inputs:{real:c,imag:f},backend:r});return r.disposeIntermediateTensorInfo(c),r.disposeIntermediateTensorInfo(f),m}function mX(e,t,r){let n=k.sizeFromShape(e.shape),a=r.data.get(e.dataId),s=r.data.get(a.complexTensorInfos.real.dataId).values,i=r.data.get(a.complexTensorInfos.imag.dataId).values;if(gX(n)){let o=jg(s,i,n,t,r),l=[e.shape[0],e.shape[1]];if(t){let p=r.makeTensorInfo(l,"float32",o.real),u=r.makeTensorInfo(l,"float32",o.imag),d=r.makeTensorInfo([],"float32",k.createScalarValue(n,"float32")),h=ca({inputs:{x:d},backend:r}),c=Hg.kernelFunc({inputs:{a:p,b:d},backend:r}),f=Hg.kernelFunc({inputs:{a:u,b:h},backend:r}),m=r.data.get(c.dataId).values,g=r.data.get(f.dataId).values;return r.disposeIntermediateTensorInfo(p),r.disposeIntermediateTensorInfo(u),r.disposeIntermediateTensorInfo(d),r.disposeIntermediateTensorInfo(h),r.disposeIntermediateTensorInfo(c),r.disposeIntermediateTensorInfo(f),{real:m,imag:g}}return o}else{let o=_.mergeRealAndImagArrays(s,i),l=yX(o,n,t);return _.splitRealAndImagArrays(l)}}function gX(e){return(e&e-1)===0}function jg(e,t,r,n,a){if(r===1)return{real:e,imag:t};let s=_.mergeRealAndImagArrays(e,t),i=r/2,o=_.complexWithEvenIndex(s),l=o.real,p=o.imag,u=[l.length],d=a.makeTensorInfo(u,"float32",l),h=a.makeTensorInfo(u,"float32",p),c=Hr({inputs:{real:d,imag:h},backend:a}),f=_.complexWithOddIndex(s),m=f.real,g=f.imag,y=[m.length],b=a.makeTensorInfo(y,"float32",m),x=a.makeTensorInfo(y,"float32",g),v=Hr({inputs:{real:b,imag:x},backend:a}),w=jg(l,p,i,n,a),N=w.real,T=w.imag,E=[N.length],$=a.makeTensorInfo(E,"float32",N),R=a.makeTensorInfo(E,"float32",T),F=Hr({inputs:{real:$,imag:R},backend:a}),S=jg(m,g,i,n,a),D=S.real,P=S.imag,U=[D.length],H=a.makeTensorInfo(U,"float32",D),q=a.makeTensorInfo(U,"float32",P),G=Hr({inputs:{real:H,imag:q},backend:a}),Z=_.exponents(r,n),ee=[Z.real.length],X=a.makeTensorInfo(ee,"float32",Z.real),re=a.makeTensorInfo(ee,"float32",Z.imag),te=Hr({inputs:{real:X,imag:re},backend:a}),ae=ym({inputs:{a:te,b:G},backend:a}),ie=Bl({inputs:{a:F,b:ae},backend:a}),ve=qv({inputs:{a:F,b:ae},backend:a}),be=wi({inputs:{input:ie},backend:a}),he=wi({inputs:{input:ve},backend:a}),Ie=Wl({inputs:{input:ie},backend:a}),_e=Wl({inputs:{input:ve},backend:a}),Fe=Ul({inputs:[be,he],backend:a,attrs:{axis:0}}),Pe=Ul({inputs:[Ie,_e],backend:a,attrs:{axis:0}}),st=a.data.get(Fe.dataId).values,Ge=a.data.get(Pe.dataId).values;return a.disposeIntermediateTensorInfo(d),a.disposeIntermediateTensorInfo(h),a.disposeIntermediateTensorInfo(c),a.disposeIntermediateTensorInfo(b),a.disposeIntermediateTensorInfo(x),a.disposeIntermediateTensorInfo(v),a.disposeIntermediateTensorInfo($),a.disposeIntermediateTensorInfo(R),a.disposeIntermediateTensorInfo(F),a.disposeIntermediateTensorInfo(H),a.disposeIntermediateTensorInfo(q),a.disposeIntermediateTensorInfo(G),a.disposeIntermediateTensorInfo(X),a.disposeIntermediateTensorInfo(re),a.disposeIntermediateTensorInfo(te),a.disposeIntermediateTensorInfo(ae),a.disposeIntermediateTensorInfo(ie),a.disposeIntermediateTensorInfo(ve),a.disposeIntermediateTensorInfo(be),a.disposeIntermediateTensorInfo(Ie),a.disposeIntermediateTensorInfo(he),a.disposeIntermediateTensorInfo(_e),a.disposeIntermediateTensorInfo(Fe),a.disposeIntermediateTensorInfo(Pe),{real:st,imag:Ge}}function yX(e,t,r){let n=new Float32Array(t*2);for(let a=0;a<t;a++){let s=0,i=0;for(let o=0;o<t;o++){let l=_.exponent(a*o,t,r),p=_.getComplexWithIndex(e,o);s+=p.real*l.real-p.imag*l.imag,i+=p.real*l.imag+p.imag*l.real}r&&(s/=t,i/=t),_.assignToTypedArray(n,s,i,a)}return n}function bX(e){let{inputs:t,backend:r}=e,{input:n}=t,a=k.sizeFromShape(n.shape),s=n.shape[n.shape.length-1],i=a/s,o=yt({inputs:{x:n},backend:r,attrs:{shape:[i,s]}}),l=wT(o,!1,r),p=yt({inputs:{x:l},backend:r,attrs:{shape:n.shape}});return r.disposeIntermediateTensorInfo(o),r.disposeIntermediateTensorInfo(l),p}var xX={kernelName:af,backendName:"cpu",kernelFunc:bX};function Jv(e){let{backend:t,attrs:r}=e,{shape:n,value:a,dtype:s}=r,i=s||k.inferDtype(a),o=k.getArrayFromDType(i,k.sizeFromShape(n));return wX(o,a),t.makeTensorInfo(n,i,o)}var vX={kernelName:bd,backendName:"cpu",kernelFunc:Jv};function wX(e,t,r){e.fill(t)}var kX={kernelName:hu,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:r})=>{let{image:n}=e,a=r,s=k.getTypedArrayFromDType(n.dtype,k.sizeFromShape(n.shape)),[i,o,l,p]=n.shape,u=a.data.get(n.dataId).values;for(let d=0;d<i;d++){let h=d*l*o*p;for(let c=0;c<o;c++){let f=c*(l*p);for(let m=0;m<l;m++){let g=m*p;for(let y=0;y<p;y++){let b=Math.round(l-m-1),x=h+f+g+y,v=u[x];if(b>=0&&b<l){let w=b*p,N=h+f+w+y;v=u[N]}s[x]=v}}}}return{dataId:a.write(s,n.shape,n.dtype),shape:n.shape,dtype:n.dtype}}};function IX(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,filter:s,bias:i,preluActivationWeights:o}=t,{strides:l,pad:p,dataFormat:u,dilations:d,dimRoundingMode:h,activation:c,leakyreluAlpha:f}=n,m=xT({inputs:{x:a,filter:s},backend:r,attrs:{strides:l,pad:p,dataFormat:u,dilations:d,dimRoundingMode:h}});if(i){let g=m;if(u==="NCHW"&&i.shape.length===1&&i.shape[0]!==1){let y=yt({inputs:{x:i},backend:r,attrs:{shape:[i.shape[0],1,1]}});m=Bl({inputs:{a:m,b:y},backend:r}),r.disposeIntermediateTensorInfo(y)}else m=Bl({inputs:{a:m,b:i},backend:r});r.disposeIntermediateTensorInfo(g)}if(c){let g=m;if(u==="NCHW"&&c==="prelu"&&o.shape.length===1&&o.shape[0]!==1){let y=yt({inputs:{x:o},backend:r,attrs:{shape:[o.shape[0],1,1]}});m=Dc(r,m,c,y,f),r.disposeIntermediateTensorInfo(y)}else m=Dc(r,m,c,o,f);r.disposeIntermediateTensorInfo(g)}return m}var SX={kernelName:ui,backendName:"cpu",kernelFunc:IX};function NX(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,filter:s,bias:i,preluActivationWeights:o}=t,{strides:l,pad:p,dataFormat:u,dilations:d,dimRoundingMode:h,activation:c,leakyreluAlpha:f}=n,m=vT({inputs:{x:a,filter:s},backend:r,attrs:{strides:l,pad:p,dataFormat:u,dilations:d,dimRoundingMode:h}});if(i){let g=m;m=Bl({inputs:{a:m,b:i},backend:r}),r.disposeIntermediateTensorInfo(g)}if(c){let g=m;m=Dc(r,m,c,o,f),r.disposeIntermediateTensorInfo(g)}return m}var _X={kernelName:pi,backendName:"cpu",kernelFunc:NX};function TX(e){let{inputs:t,backend:r}=e,{params:n,indices:a}=t,s=k.sizeFromShape(n.shape),i=a.shape,o=i[i.length-1],[l,p,u,d]=_.prepareAndValidate(n,a);if(p===0)return r.makeTensorInfo(l,n.dtype,[]);let h=r.data.get(a.dataId).values,c=r.bufferSync(n),f=L_(h,c,n.dtype,p,o,u,d,n.shape,s);return r.makeTensorInfo(l,n.dtype,f.values)}var CX={kernelName:fu,backendName:"cpu",kernelFunc:TX};function EX(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,indices:s}=t,{axis:i,batchDims:o}=n;ye([a,s],"gatherV2");let l=k.parseAxisParam(i,a.shape)[0],p=r.data.get(s.dataId).values,u=a.shape[l];for(let v=0;v<p.length;++v){let w=p[v];k.assert(w<=u-1&&w>=0,()=>`GatherV2: the index value ${w} is not in [0, ${u-1}]`)}let d=o;o==null&&(d=0);let h=k.sizeFromShape(s.shape),c=_.segment_util.collectGatherOpShapeInfo(a,s,l,d),f=yt({inputs:{x:a},backend:r,attrs:{shape:[c.batchSize,c.outerSize,c.dimSize,c.sliceSize]}}),m=yt({inputs:{x:s},backend:r,attrs:{shape:[c.batchSize,h/c.batchSize]}}),g=[c.batchSize,c.outerSize,h/c.batchSize,c.sliceSize],y=r.bufferSync(m),b=r.bufferSync(f),x=z_(b,y,g);return r.disposeIntermediateTensorInfo(f),r.disposeIntermediateTensorInfo(m),r.makeTensorInfo(c.outputShape,x.dtype,x.values)}var $X={kernelName:cu,backendName:"cpu",kernelFunc:EX};function AX(e){let{inputs:t,backend:r}=e,{input:n}=t,a=k.sizeFromShape(n.shape),s=n.shape[n.shape.length-1],i=a/s,o=yt({inputs:{x:n},backend:r,attrs:{shape:[i,s]}}),l=wT(o,!0,r),p=yt({inputs:{x:l},backend:r,attrs:{shape:n.shape}});return r.disposeIntermediateTensorInfo(o),r.disposeIntermediateTensorInfo(l),p}var FX={kernelName:sf,backendName:"cpu",kernelFunc:AX},RX=at(io,e=>Number.isFinite(e)?1:0,"bool"),DX={kernelName:io,backendName:"cpu",kernelFunc:RX},MX=at(oo,e=>Math.abs(e)===1/0?1:0,"bool"),OX={kernelName:oo,backendName:"cpu",kernelFunc:MX},LX=at(lo,e=>Number.isNaN(e)?1:0,"bool"),zX={kernelName:lo,backendName:"cpu",kernelFunc:LX};function PX(e){let{backend:t,attrs:r}=e,{start:n,stop:a,num:s}=r,i=V_(n,a,s);return t.makeTensorInfo([i.length],"float32",i)}var BX={kernelName:bu,backendName:"cpu",kernelFunc:PX},WX=at(ho,e=>Math.log1p(e)),UX={kernelName:ho,backendName:"cpu",kernelFunc:WX},VX=Et((e,t)=>e&&t),GX=Gt(xu,VX,null,"bool"),HX={kernelName:xu,backendName:"cpu",kernelFunc:GX},jX=at(vu,e=>e?0:1,"bool"),qX={kernelName:vu,backendName:"cpu",kernelFunc:jX},KX=Et((e,t)=>e||t),XX=Gt(wu,KX,null,"bool"),ZX={kernelName:wu,backendName:"cpu",kernelFunc:XX};function JX(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{depthRadius:s,bias:i,alpha:o,beta:l}=n;ye(a,"LRN");let p=a.shape[3],u=p-1,d=r.data.get(a.dataId).values,h=k.sizeFromShape(a.shape),c=new Float32Array(h);function f(m){let g=m%p,y=m-g+Math.max(0,g-s),b=m-g+Math.min(g+s,u),x=0;for(;y<=b;y++){let v=d[y];x+=v*v}return x}for(let m=0;m<h;m++){let g=f(m),y=d[m]*Math.pow(i+o*g,-l);c[m]=y}return r.makeTensorInfo(a.shape,a.dtype,c)}var YX={kernelName:co,backendName:"cpu",kernelFunc:JX};function QX(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,y:s,dy:i}=t,{depthRadius:o,bias:l,alpha:p,beta:u}=n;ye(i,"LRNGrad");let d=k.sizeFromShape(i.shape),h=i.shape[3],c=r.data.get(i.dataId).values,f=r.data.get(a.dataId).values,m=r.data.get(s.dataId).values,g=new Float32Array(d),y=d;for(let b=0;b<y;b++){let x=b%h,v=b-x+Math.max(0,x-o),w=b-x+Math.min(h,x+o+1),N=0;for(let T=v;T<w;T++)N+=Math.pow(f[T],2);N=p*N+l;for(let T=v;T<w;T++){let E=-2*p*u*f[T]*m[b]/N;b===T&&(E+=Math.pow(N,-u)),E*=c[b],g[T]+=E}}return r.makeTensorInfo(i.shape,a.dtype,g)}var e7={kernelName:ku,backendName:"cpu",kernelFunc:QX};function kT(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{reductionIndices:s,keepDims:i}=n,o=r,l=a.shape,p=l.length,u=k.parseAxisParam(s,l),d=u,h=_.getAxesPermutation(d,p),c=o.data.get(a.dataId).values;if(h!=null){let v=new Array(p);for(let w=0;w<v.length;w++)v[w]=l[h[w]];c=Wv(c,l,a.dtype,h,v),d=_.getInnerMostAxes(d.length,p),l=v}ye(a,"max"),_.assertAxesAreInnerMostDims("max",d,p);let[f,m]=_.computeOutAndReduceShapes(l,d),g=k.sizeFromShape(m),y=H_(c,g,f,a.dtype),b=o.write(y,f,a.dtype),x=f;return i&&(x=_.expandShapeToKeepDim(f,u)),{dataId:b,shape:x,dtype:a.dtype}}var t7={kernelName:fo,backendName:"cpu",kernelFunc:kT};function r7(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t;ye(a,"maxPool");let{filterSize:s,strides:i,pad:o,dimRoundingMode:l}=n,p=1;k.assert(_.eitherStridesOrDilationsAreOne(i,p),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${i} and dilations '${p}'`);let u=_.computePool2DInfo(a.shape,s,i,p,o,l),d;if(u.filterWidth===1&&u.filterHeight===1&&k.arraysEqual(u.inShape,u.outShape))d=ca({inputs:{x:a},backend:r});else{let h=r.data.get(a.dataId).values,c=k.computeStrides(a.shape),f=Xv(h,a.shape,a.dtype,c,u,"max");d=r.makeTensorInfo(u.outShape,a.dtype,f.values)}return d}var n7={kernelName:go,backendName:"cpu",kernelFunc:r7};function a7(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{filterSize:s,strides:i,pad:o,dimRoundingMode:l,dataFormat:p}=n;ye(a,"maxPool3d");let u=_.computePool3DInfo(a.shape,s,i,1,o,l,p),d=r.data.get(a.dataId).values,h=bT(d,a.shape,a.dtype,k.computeStrides(a.shape),u,"max");return r.makeTensorInfo(h.shape,"float32",h.values)}var s7={kernelName:Iu,backendName:"cpu",kernelFunc:a7};function i7(e){let{inputs:t,backend:r,attrs:n}=e,{dy:a,input:s}=t,{filterSize:i,strides:o,pad:l,dimRoundingMode:p}=n;ye([a,s],"maxPool3DGrad");let u=_.computePool3DInfo(s.shape,i,o,1,l,p),d=r.bufferSync(s),h=KK(d,u),c=u.strideDepth,f=u.strideHeight,m=u.strideWidth,g=u.dilationDepth,y=u.dilationHeight,b=u.dilationWidth,x=u.effectiveFilterDepth,v=u.effectiveFilterHeight,w=u.effectiveFilterWidth,N=x-1-u.padInfo.front,T=w-1-u.padInfo.left,E=v-1-u.padInfo.top,$=Le(s.shape,"float32"),R=r.bufferSync(a);for(let F=0;F<u.batchSize;++F)for(let S=0;S<u.inChannels;++S)for(let D=0;D<u.inDepth;++D)for(let P=0;P<u.inHeight;++P)for(let U=0;U<u.inWidth;++U){let H=D-N,q=P-E,G=U-T,Z=0;for(let ee=0;ee<x;ee+=g){let X=(H+ee)/c;if(!(X<0||X>=u.outDepth||Math.floor(X)!==X))for(let re=0;re<v;re+=y){let te=(q+re)/f;if(!(te<0||te>=u.outHeight||Math.floor(te)!==te))for(let ae=0;ae<w;ae+=b){let ie=(G+ae)/m;if(ie<0||ie>=u.outWidth||Math.floor(ie)!==ie)continue;let ve=x*v*w-1-h.get(F,X,te,ie,S),be=ee*v*w+re*w+ae,he=ve===be?1:0;if(he===0)continue;let Ie=R.get(F,X,te,ie,S);Z+=Ie*he}}}$.set(Z,F,D,P,U,S)}return r.makeTensorInfo($.shape,$.dtype,$.values)}var o7={kernelName:vd,backendName:"cpu",kernelFunc:i7};function l7(e){let{inputs:t,backend:r,attrs:n}=e,{dy:a,input:s,output:i}=t,o=s;ye([s,i],"maxPoolGrad");let{filterSize:l,strides:p,pad:u,dimRoundingMode:d}=n,h=_.computePool2DInfo(o.shape,l,p,1,u,d),c=r.data.get(o.dataId).values,f=Le(h.outShape,o.dtype,yT(c,o.shape,o.dtype,h).values),m=h.strideHeight,g=h.strideWidth,y=h.dilationHeight,b=h.dilationWidth,x=h.effectiveFilterHeight,v=h.effectiveFilterWidth,w=v-1-h.padInfo.left,N=x-1-h.padInfo.top,T=Le(o.shape,"float32"),E=r.data.get(a.dataId).values,$=Le(a.shape,"float32",E);for(let R=0;R<h.batchSize;++R)for(let F=0;F<h.inChannels;++F)for(let S=0;S<h.inHeight;++S)for(let D=0;D<h.inWidth;++D){let P=S-N,U=D-w,H=0;for(let q=0;q<x;q+=y){let G=(P+q)/m;if(!(G<0||G>=h.outHeight||Math.floor(G)!==G))for(let Z=0;Z<v;Z+=b){let ee=(U+Z)/g;if(ee<0||ee>=h.outWidth||Math.floor(ee)!==ee)continue;let X=x*v-1-f.get(R,G,ee,F),re=q*v+Z,te=X===re?1:0;if(te===0)continue;let ae=$.get(R,G,ee,F);H+=ae*te}}T.set(H,R,S,D,F)}return r.makeTensorInfo(T.shape,T.dtype,T.values)}var u7={kernelName:xd,backendName:"cpu",kernelFunc:l7};function p7(e,t,r,n,a){let s=k.computeStrides(t),i=Xv(e,t,r,s,a,"max"),o=yT(e,t,r,a,!0,n);return[i.values,o.values]}var d7={kernelName:wd,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:r})=>{let{x:n}=e,{filterSize:a,strides:s,pad:i,includeBatchInIndex:o}=t,l=r;ye(n,"MaxPoolWithArgmax");let p=l.data.get(n.dataId).values,u=_.computePool2DInfo(n.shape,a,s,[1,1],i),[d,h]=p7(p,n.shape,n.dtype,o,u),c=l.write(d,u.outShape,n.dtype),f=l.write(h,u.outShape,n.dtype);return[{dataId:c,shape:u.outShape,dtype:n.dtype},{dataId:f,shape:u.outShape,dtype:"int32"}]}};function h7(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{axis:s,keepDims:i}=n,o=k.parseAxisParam(s,a.shape),l=_.computeOutAndReduceShapes(a.shape,o)[1],p=k.sizeFromShape(l),u=[],d=r.makeTensorInfo([],"float32",new Float32Array([p]));u.push(d);let h=Is({inputs:{x:a},backend:r,attrs:{dtype:"float32"}});u.push(h);let c=Zv({inputs:{a:h,b:d},backend:r});u.push(c);let f=oh({inputs:{x:c},backend:r,attrs:{axis:s,keepDims:i}});return u.forEach(m=>r.disposeIntermediateTensorInfo(m)),f}var c7={kernelName:yo,backendName:"cpu",kernelFunc:h7};function f7(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{axis:s,keepDims:i}=n;ye(a,"min");let o=k.parseAxisParam(s,a.shape),l=o,p=_.getAxesPermutation(l,a.shape.length),u=a;p!=null&&(u=Mr({inputs:{x:a},backend:r,attrs:{perm:p}}),l=_.getInnerMostAxes(l.length,a.shape.length)),_.assertAxesAreInnerMostDims("min",l,u.shape.length);let[d,h]=_.computeOutAndReduceShapes(u.shape,l),c=k.sizeFromShape(h),f=k.makeZerosTypedArray(k.sizeFromShape(d),u.dtype),m=r.data.get(u.dataId).values;for(let y=0;y<f.length;++y){let b=y*c,x=m[b];for(let v=0;v<c;++v){let w=m[b+v];(Number.isNaN(w)||w<x)&&(x=w)}f[y]=x}p!=null&&r.disposeIntermediateTensorInfo(u);let g=r.makeTensorInfo(d,u.dtype,f);if(i){let y=_.expandShapeToKeepDim(d,o),b=yt({inputs:{x:g},backend:r,attrs:{shape:y}});return r.disposeIntermediateTensorInfo(g),b}return g}var m7={kernelName:bo,backendName:"cpu",kernelFunc:f7};function g7(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{paddings:s,mode:i}=n;ye(a,"mirrorPad");let o=s.map((b,x)=>b[0]+a.shape[x]+b[1]),l=s.map(b=>b[0]),p=s.map((b,x)=>b[0]+a.shape[x]),u=i==="reflect"?0:1,d=r.data.get(a.dataId).values,h=a.shape.length,c=k.computeStrides(a.shape),f=k.sizeFromShape(o),m=o.length,g=k.computeStrides(o),y=k.getTypedArrayFromDType(a.dtype,f);for(let b=0;b<f;b++){let x=k.indexToLoc(b,m,g);for(let w=0;w<m;w++)x[w]<l[w]?x[w]=l[w]*2-x[w]-u:x[w]>=p[w]&&(x[w]=(p[w]-1)*2-x[w]+u);x=x.map((w,N)=>w-l[N]);let v=k.locToIndex(x,h,c);y[b]=d[v]}return{dataId:r.write(y,o,a.dtype),shape:o,dtype:a.dtype}}var y7={kernelName:vo,backendName:"cpu",kernelFunc:g7},b7=Et((e,t)=>{let r=e%t;return e<0&&t<0||e>=0&&t>=0?r:(r+t)%t}),x7=Gt(wo,b7),v7={kernelName:wo,backendName:"cpu",kernelFunc:x7},w7=_s(Kc());function IT(e){let{inputs:t,backend:r,attrs:n}=e,{logits:a}=t,{dim:s}=n,i=a.shape.length,o=s;if(o===-1&&(o=i-1),o!==i-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${i} and dim was ${o}`);let l=k.parseAxisParam([o],a.shape),p=kT({inputs:{x:a},backend:r,attrs:{reductionIndices:l,keepDims:!1}}),u=_.expandShapeToKeepDim(p.shape,l),d=yt({inputs:{x:p},backend:r,attrs:{shape:u}}),h=qv({inputs:{a,b:d},backend:r}),c=R_({inputs:{x:h},backend:r}),f=oh({inputs:{x:c},backend:r,attrs:{axis:l,keepDims:!1}}),m=yt({inputs:{x:f},backend:r,attrs:{shape:u}}),g=Zv({inputs:{a:c,b:m},backend:r});return r.disposeIntermediateTensorInfo(p),r.disposeIntermediateTensorInfo(d),r.disposeIntermediateTensorInfo(h),r.disposeIntermediateTensorInfo(c),r.disposeIntermediateTensorInfo(f),r.disposeIntermediateTensorInfo(m),g}var k7={kernelName:Go,backendName:"cpu",kernelFunc:IT};function I7(e){let{inputs:t,backend:r,attrs:n}=e,{logits:a}=t,{numSamples:s,seed:i,normalized:o}=n;ye(a,"multinomial");let l=o?a:IT({inputs:{logits:a},backend:r,attrs:{dim:-1}}),p=l.shape[0],u=l.shape[1],d=r.data.get(l.dataId).values,h=[p,s],c=k.makeZerosTypedArray(k.sizeFromShape(h),"int32");for(let f=0;f<p;++f){let m=f*u,g=new Float32Array(u-1);g[0]=d[m];for(let x=1;x<g.length;++x)g[x]=g[x-1]+d[m+x];let y=w7.alea(i.toString()),b=f*s;for(let x=0;x<s;++x){let v=y();c[b+x]=g.length;for(let w=0;w<g.length;w++)if(v<g[w]){c[b+x]=w;break}}}return o||r.disposeIntermediateTensorInfo(l),r.makeTensorInfo(h,"int32",c)}var S7={kernelName:Su,backendName:"cpu",kernelFunc:I7},N7=ga.nonMaxSuppressionV3Impl;function _7(e){let{inputs:t,backend:r,attrs:n}=e,{boxes:a,scores:s}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l}=n;ye(a,"NonMaxSuppression");let p=r.data.get(a.dataId).values,u=r.data.get(s.dataId).values,{selectedIndices:d}=N7(p,u,i,o,l);return r.makeTensorInfo([d.length],"int32",new Int32Array(d))}var T7={kernelName:Tu,backendName:"cpu",kernelFunc:_7},C7=ga.nonMaxSuppressionV4Impl;function E7(e){let{inputs:t,backend:r,attrs:n}=e,{boxes:a,scores:s}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l,padToMaxOutputSize:p}=n;ye(a,"NonMaxSuppressionPadded");let u=r.data.get(a.dataId).values,d=r.data.get(s.dataId).values,{selectedIndices:h,validOutputs:c}=C7(u,d,i,o,l,p);return[r.makeTensorInfo([h.length],"int32",new Int32Array(h)),r.makeTensorInfo([],"int32",new Int32Array([c]))]}var $7={kernelName:Cu,backendName:"cpu",kernelFunc:E7},A7=ga.nonMaxSuppressionV5Impl;function F7(e){let{inputs:t,backend:r,attrs:n}=e,{boxes:a,scores:s}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l,softNmsSigma:p}=n;ye(a,"NonMaxSuppressionWithScore");let u=r.data.get(a.dataId).values,d=r.data.get(s.dataId).values,h=i,c=o,f=l,m=p,{selectedIndices:g,selectedScores:y}=A7(u,d,h,c,f,m);return[r.makeTensorInfo([g.length],"int32",new Int32Array(g)),r.makeTensorInfo([y.length],"float32",new Float32Array(y))]}var R7={kernelName:Eu,backendName:"cpu",kernelFunc:F7};function D7(e){let{inputs:t,backend:r,attrs:n}=e,{indices:a}=t,{dtype:s,depth:i,onValue:o,offValue:l}=n;ye(a,"oneHot");let p=k.sizeFromShape(a.shape),u=new Float32Array(p*i);u.fill(l);let d=r.data.get(a.dataId).values;for(let h=0;h<p;++h)d[h]>=0&&d[h]<i&&(u[h*i+d[h]]=o);return r.makeTensorInfo([...a.shape,i],s,u)}var M7={kernelName:Io,backendName:"cpu",kernelFunc:D7};function Oc(e){let{inputs:t,backend:r}=e,{x:n}=t;if(n.dtype==="string")throw new Error("zerosLike is not supported for string tensors");if(n.dtype==="complex64"){let a=wi({inputs:{input:n},backend:r}),s=Oc({inputs:{x:a},backend:r}),i=Wl({inputs:{input:n},backend:r}),o=Oc({inputs:{x:i},backend:r}),l=Hr({inputs:{real:s,imag:o},backend:r});return r.disposeIntermediateTensorInfo(a),r.disposeIntermediateTensorInfo(s),r.disposeIntermediateTensorInfo(i),r.disposeIntermediateTensorInfo(o),l}else return Jv({backend:r,attrs:{shape:n.shape,value:0,dtype:n.dtype}})}var O7={kernelName:Ku,backendName:"cpu",kernelFunc:Oc};function ST(e){let{inputs:t,backend:r}=e,{x:n}=t;if(n.dtype==="string")throw new Error("onesLike is not supported for string tensors");if(n.dtype==="complex64"){let a=wi({inputs:{input:n},backend:r}),s=ST({inputs:{x:a},backend:r}),i=Wl({inputs:{input:n},backend:r}),o=Oc({inputs:{x:i},backend:r}),l=Hr({inputs:{real:s,imag:o},backend:r});return r.disposeIntermediateTensorInfo(a),r.disposeIntermediateTensorInfo(s),r.disposeIntermediateTensorInfo(i),r.disposeIntermediateTensorInfo(o),l}else return Jv({backend:r,attrs:{shape:n.shape,value:1,dtype:n.dtype}})}var L7={kernelName:$u,backendName:"cpu",kernelFunc:ST};function NT(e){let{inputs:t,backend:r,attrs:n}=e,{axis:a}=n;if(t.length===1)return Mc({inputs:{input:t[0]},backend:r,attrs:{dim:a}});let s=t[0].shape,i=t[0].dtype;t.forEach(u=>{k.assertShapesMatch(s,u.shape,"All tensors passed to stack must have matching shapes"),k.assert(i===u.dtype,()=>"All tensors passed to stack must have matching dtypes")});let o=[],l=t.map(u=>{let d=Mc({inputs:{input:u},backend:r,attrs:{dim:a}});return o.push(d),d}),p=Ul({inputs:l,backend:r,attrs:{axis:a}});return o.forEach(u=>r.disposeIntermediateTensorInfo(u)),p}var z7={kernelName:Au,backendName:"cpu",kernelFunc:NT};function P7(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{paddings:s,constantValue:i}=n;ye(a,"pad");let o=s.map((y,b)=>y[0]+a.shape[b]+y[1]),l=s.map(y=>y[0]),p=r.data.get(a.dataId).values,u=k.sizeFromShape(a.shape),d=a.shape.length,h=k.computeStrides(a.shape),c=k.sizeFromShape(o),f=o.length,m=k.computeStrides(o),g=k.getTypedArrayFromDType(a.dtype,c);i!==0&&g.fill(i);for(let y=0;y<u;y++){let b=k.indexToLoc(y,d,h).map((v,w)=>v+l[w]),x=k.locToIndex(b,f,m);g[x]=p[y]}return{dataId:r.write(g,o,a.dtype),shape:o,dtype:a.dtype}}var _T={kernelName:So,backendName:"cpu",kernelFunc:P7},B7=Et((e,t)=>Math.pow(e,t)),W7=Gt(No,B7),U7={kernelName:No,backendName:"cpu",kernelFunc:W7};function V7(e){let{inputs:t,backend:r,attrs:n}=e,{paramsNestedSplits:a,paramsDenseValues:s,indices:i}=t,{outputRaggedRank:o}=n,l=a.map(y=>r.data.get(y.dataId).values),p=a.map(y=>y.shape),u=r.data.get(s.dataId).values,d=r.data.get(i.dataId).values,[h,c,f]=J_(l,p,u,s.shape,s.dtype,d,i.shape),m=h.map(y=>r.makeTensorInfo([y.length],"int32",y)),g=r.makeTensorInfo(f,s.dtype,c);return m.concat([g])}var G7={kernelName:lf,backendName:"cpu",kernelFunc:V7};function H7(e){let{inputs:t,backend:r}=e,{starts:n,limits:a,deltas:s}=t,i=r.data.get(n.dataId).values,o=r.data.get(a.dataId).values,l=r.data.get(s.dataId).values,[p,u]=Y_(i,n.shape,n.dtype,o,a.shape,l,s.shape),d=r.makeTensorInfo([p.length],"int32",p),h=r.makeTensorInfo([u.length],n.dtype,u);return[d,h]}var j7={kernelName:uf,backendName:"cpu",kernelFunc:H7};function q7(e){let{inputs:t,backend:r,attrs:n}=e,{shape:a,values:s,defaultValue:i,rowPartitionTensors:o}=t,{rowPartitionTypes:l}=n,p=r.data.get(a.dataId).values,u=r.data.get(s.dataId).values,d=r.data.get(i.dataId).values,h=o.map(g=>r.data.get(g.dataId).values),c=o.map(g=>g.shape),[f,m]=Q_(p,a.shape,u,s.shape,s.dtype,d,i.shape,h,c,l);return r.makeTensorInfo(f,s.dtype,m)}var K7={kernelName:pf,backendName:"cpu",kernelFunc:q7};function X7(e){let{backend:t,attrs:r}=e,{start:n,stop:a,dtype:s,step:i}=r,o=Uv(n,a,i,s);return t.makeTensorInfo([o.length],s,o)}var Z7={kernelName:kd,backendName:"cpu",kernelFunc:X7},J7=at(Co,e=>1/e),Y7={kernelName:Co,backendName:"cpu",kernelFunc:J7};function Q7(e){let{inputs:t,backend:r,attrs:n}=e,{images:a}=t,{alignCorners:s,halfPixelCenters:i,size:o}=n;ye(a,"resizeBilinear");let l=k.computeStrides(a.shape),[p,u]=o,[d,h,c,f]=a.shape,m=r.data.get(a.dataId).values,g=new Float32Array(k.sizeFromShape([d,p,u,f])),y=[s&&p>1?h-1:h,s&&u>1?c-1:c],b=[s&&p>1?p-1:p,s&&u>1?u-1:u],x=0,v=y[0]/b[0],w=y[1]/b[1];for(let N=0;N<d;N++)for(let T=0;T<p;T++){let E;i?E=v*(T+.5)-.5:E=v*T;let $=Math.max(0,Math.floor(E)),R=E-$,F=Math.min(h-1,Math.ceil(E)),S=N*l[0]+$*l[1],D=N*l[0]+F*l[1];for(let P=0;P<u;P++){let U;i?U=w*(P+.5)-.5:U=w*P;let H=Math.max(0,Math.floor(U)),q=U-H,G=Math.min(c-1,Math.ceil(U)),Z=S+H*l[2],ee=D+H*l[2],X=S+G*l[2],re=D+G*l[2];for(let te=0;te<f;te++){let ae=m[Z+te],ie=m[ee+te],ve=m[X+te],be=m[re+te],he=ae+(ve-ae)*q,Ie=ie+(be-ie)*q,_e=he+(Ie-he)*R;g[x++]=_e}}}return r.makeTensorInfo([d,p,u,f],"float32",g)}var eZ={kernelName:Ao,backendName:"cpu",kernelFunc:Q7};function tZ(e){let{inputs:t,backend:r,attrs:n}=e,{images:a,dy:s}=t,{alignCorners:i}=n;ye([s,a],"resizeBilinearGrad");let o=k.computeStrides(a.shape),[l,p,u,d]=a.shape,[,h,c]=s.shape,f=new Float32Array(l*p*u*d),m=[i&&h>1?p-1:p,i&&c>1?u-1:u],g=[i&&h>1?h-1:h,i&&c>1?c-1:c],y=m[0]/g[0],b=m[1]/g[1],x=r.data.get(s.dataId).values,v=0;for(let w=0;w<l;w++){let N=w*o[0];for(let T=0;T<h;T++){let E=T*y,$=Math.floor(E),R=Math.min(Math.ceil(E),p-1),F=N+$*o[1],S=N+R*o[1],D=E-$,P=1-D;for(let U=0;U<c;U++){let H=U*b,q=Math.floor(H),G=Math.min(Math.ceil(H),u-1),Z=H-q,ee=1-Z,X=F+q*o[2],re=F+G*o[2],te=S+q*o[2],ae=S+G*o[2],ie=P*ee,ve=P*Z,be=D*ee,he=D*Z;for(let Ie=0;Ie<d;Ie++){let _e=x[v++];f[X+Ie]+=_e*ie,f[re+Ie]+=_e*ve,f[te+Ie]+=_e*be,f[ae+Ie]+=_e*he}}}}return r.makeTensorInfo([l,u,p,d],"float32",f)}var rZ={kernelName:Du,backendName:"cpu",kernelFunc:tZ};function nZ(e){let{inputs:t,backend:r,attrs:n}=e,{images:a}=t,{alignCorners:s,halfPixelCenters:i,size:o}=n;ye(a,"resizeNearestNeighbor");let l=k.computeStrides(a.shape),[p,u]=o,[d,h,c,f]=a.shape,m=r.data.get(a.dataId).values,g=new Float32Array(d*p*u*f),y=[s&&p>1?h-1:h,s&&u>1?c-1:c],b=[s&&p>1?p-1:p,s&&u>1?u-1:u],x=y[0]/b[0],v=y[1]/b[1],w=0;for(let N=0;N<d;N++){let T=N*l[0];for(let E=0;E<p;E++){let $=i?x*(E+.5):x*E,R=Math.min(h-1,s?Math.round($):Math.floor($));i&&(R=Math.max(0,R));let F=T+R*l[1];for(let S=0;S<u;S++){let D=i?v*(S+.5):v*S,P=Math.min(c-1,s?Math.round(D):Math.floor(D));i&&(P=Math.max(0,P));let U=F+P*l[2];for(let H=0;H<f;H++){let q=m[U+H];g[w++]=q}}}}return r.makeTensorInfo([d,p,u,f],a.dtype,g)}var aZ={kernelName:$o,backendName:"cpu",kernelFunc:nZ};function sZ(e){let{inputs:t,backend:r,attrs:n}=e,{images:a,dy:s}=t,{alignCorners:i}=n;ye([s,a],"resizeNearestNeighborGrad");let o=k.computeStrides(a.shape),l=k.computeStrides(s.shape),[p,u,d,h]=a.shape,[,c,f]=s.shape,m=new Float32Array(p*u*d*h),g=r.data.get(s.dataId).values,y=[i&&c>1?u-1:u,i&&f>1?d-1:d],b=[i&&c>1?c-1:c,i&&f>1?f-1:f],x=y[0]/b[0],v=y[1]/b[1],w=1/x,N=1/v,T=Math.ceil(w)*2+2,E=Math.ceil(N)*2+2;for(let $=0;$<p;$++){let R=$*o[0];for(let F=0;F<u;F++){let S=R+F*o[1],D=Math.floor(F*w),P=Math.floor(D-T/2);for(let U=0;U<d;U++){let H=S+U*o[2],q=Math.floor(U*N),G=Math.floor(q-E/2);for(let Z=0;Z<h;Z++){let ee=0;for(let X=0;X<T;X++){let re=X+P;if(re<0||re>=c)continue;let te=R+re*l[1],ae=re*x,ie=Math.min(u-1,i?Math.round(ae):Math.floor(ae));if(F===ie)for(let ve=0;ve<E;ve++){let be=ve+G;if(be<0||be>=f)continue;let he=te+be*l[2],Ie=be*v,_e=Math.min(d-1,i?Math.round(Ie):Math.floor(Ie));U===_e&&(ee+=g[he+Z])}}m[H+Z]=ee}}}}return r.makeTensorInfo(a.shape,a.dtype,m)}var iZ={kernelName:Ru,backendName:"cpu",kernelFunc:sZ};function oZ(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{dims:s}=n;ye(a,"reverse");let i=a.shape.length,o=k.parseAxisParam(s,a.shape);if(i===0)return ca({inputs:{x:a},backend:r});let l=new Dt(a.shape,a.dtype),p=r.bufferSync(a);for(let u=0;u<l.size;u++){let d=l.indexToLoc(u),h=d.slice();o.forEach(c=>h[c]=a.shape[c]-1-h[c]),l.set(p.get(...h),...d)}return r.makeTensorInfo(l.shape,l.dtype,l.values)}var lZ={kernelName:Ro,backendName:"cpu",kernelFunc:oZ},uZ={kernelName:Xu,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:r})=>{let{image:n}=e,{radians:a,fillValue:s,center:i}=t,o=r,l=k.getTypedArrayFromDType(n.dtype,k.sizeFromShape(n.shape)),[p,u,d,h]=n.shape,[c,f]=_.getImageCenter(i,u,d),m=255,g=Math.sin(a),y=Math.cos(a),b=o.data.get(n.dataId).values;for(let x=0;x<p;x++){let v=x*d*u*h;for(let w=0;w<u;w++){let N=w*(d*h);for(let T=0;T<d;T++){let E=T*h;for(let $=0;$<h;$++){let R=[p,w,T,$],F=R[2],S=R[1],D=(F-c)*y-(S-f)*g,P=(F-c)*g+(S-f)*y;D=Math.round(D+c),P=Math.round(P+f);let U=s;if(typeof s!="number"&&($===3?U=m:U=s[$]),D>=0&&D<d&&P>=0&&P<u){let q=P*(d*h),G=D*h,Z=v+q+G+$;U=b[Z]}let H=v+N+E+$;l[H]=U}}}}return{dataId:o.write(l,n.shape,n.dtype),shape:n.shape,dtype:n.dtype}}},pZ=at(Do,e=>{let t=Math.floor(e);return e-t<.5?Math.floor(e):e-t>.5?Math.ceil(e):t%2===0?t:t+1}),dZ={kernelName:Do,backendName:"cpu",kernelFunc:pZ};function hZ(e){let{inputs:t,backend:r,attrs:n}=e,{indices:a,updates:s}=t,{shape:i}=n,{sliceRank:o,numUpdates:l,sliceSize:p,strides:u,outputSize:d}=_.calculateShapes(s,a,i),h=!0,c=r.bufferSync(a),f=r.bufferSync(s),m=ri(c,f,i,d,p,l,o,u,0,h);return r.makeTensorInfo(i,m.dtype,m.values)}var cZ={kernelName:Mu,backendName:"cpu",kernelFunc:hZ};function fZ(e,t){let r=0,n=e.length,a=0;for(;r<n;)a=Math.floor((r+n)/2),e[a]<t?r=a+1:n=a;return n}function mZ(e,t){let r=0,n=e.length,a=0;for(;r<n;)a=Math.floor((r+n)/2),e[a]<=t?r=a+1:n=a;return n}function gZ(e,t,r,n,a,s){let i=k.getArrayFromDType("int32",r*a);for(let o=0;o<r;++o){let l=e.slice(o*n,(o+1)*n),p=o*a;for(let u=0;u<a;++u)i[p+u]=s==="left"?fZ(l,t[u+p]):mZ(l,t[u+p])}return i}function yZ(e){let{inputs:t,backend:r,attrs:n}=e,{sortedSequence:a,values:s}=t,{side:i}=n,o=r.data.get(a.dataId).values,l=r.data.get(s.dataId).values,p=gZ(o,l,a.shape[0],a.shape[1],s.shape[1],i);return r.makeTensorInfo(s.shape,"int32",p)}var bZ={kernelName:Lu,backendName:"cpu",kernelFunc:yZ};function xZ(e){let{inputs:t,backend:r}=e,{condition:n,t:a,e:s}=t;ye([n,a,s],"select");let i=n.shape.length,o=r.data.get(n.dataId).values,l=r.data.get(a.dataId).values,p=r.data.get(s.dataId).values,u=cn(a.dtype,s.dtype),d=k.makeZerosTypedArray(k.sizeFromShape(a.shape),u),h=0,c=i===0||i>1||a.shape.length===1?1:k.sizeFromShape(a.shape.slice(1));for(let f=0;f<o.length;f++)for(let m=0;m<c;m++)o[f]===1?d[h++]=l[f]:d[h++]=p[f];return r.makeTensorInfo(a.shape,u,d)}var vZ={kernelName:zu,backendName:"cpu",kernelFunc:xZ},wZ=_.SELU_SCALEALPHA,kZ=_.SELU_SCALE,IZ=at(Oo,e=>e>=0?kZ*e:wZ*(Math.exp(e)-1)),SZ={kernelName:Oo,backendName:"cpu",kernelFunc:IZ},NZ=at(Po,e=>e<0?-1:e>0?1:0),_Z={kernelName:Po,backendName:"cpu",kernelFunc:NZ},TZ=at(Lo,e=>Math.sin(e)),CZ={kernelName:Lo,backendName:"cpu",kernelFunc:TZ},EZ=at(zo,e=>Math.sinh(e)),$Z={kernelName:zo,backendName:"cpu",kernelFunc:EZ},AZ=11920928955078125e-23,f1=Math.log(AZ)+2,FZ=at(Wo,e=>{let t=e>-f1,r=e<f1,n=Math.exp(e),a;return r?a=n:t?a=e:a=Math.log(1+n),a}),RZ={kernelName:Wo,backendName:"cpu",kernelFunc:FZ};function DZ(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{blockShape:s,paddings:i}=n;ye([a],"spaceToBatchND");let o=k.sizeFromShape(s),l=[[0,0]];l.push(...i);for(let g=1+s.length;g<a.shape.length;++g)l.push([0,0]);let p=_T.kernelFunc({inputs:{x:a},backend:r,attrs:{paddings:l,constantValue:0}}),u=_.getReshaped(p.shape,s,o,!1),d=_.getPermuted(u.length,s.length,!1),h=_.getReshapedPermuted(p.shape,s,o,!1),c=yt({inputs:{x:p},backend:r,attrs:{shape:u}}),f=Mr({inputs:{x:c},backend:r,attrs:{perm:d}}),m=yt({inputs:{x:f},backend:r,attrs:{shape:h}});return r.disposeIntermediateTensorInfo(p),r.disposeIntermediateTensorInfo(c),r.disposeIntermediateTensorInfo(f),m}var MZ={kernelName:Bu,backendName:"cpu",kernelFunc:DZ};function OZ(e){let{inputs:t,backend:r}=e,{indices:n,values:a,denseShape:s,defaultValue:i}=t;if(s.shape.length!==1)throw new Error(`Dense shape must be a vector, saw:
${s.shape}`);if(n.shape.length!==2)throw new Error(`Indices must be a matrix, saw:
${n.shape}`);if(a.shape.length!==1)throw new Error(`Values must be a vector, saw:
${a.shape}`);if(i.shape.length!==0)throw new Error(`Default value must be a scalar, saw:
${i.shape}`);let o=r.data.get(n.dataId).values,l=r.data.get(a.dataId).values,p=r.data.get(s.dataId).values,u=r.data.get(i.dataId).values[0],[d,h,c,f,m]=rT(o,n.shape,n.dtype,l,a.dtype,p,u);return[r.makeTensorInfo(h,n.dtype,d),r.makeTensorInfo([h[0]],a.dtype,c),r.makeTensorInfo([f.length],"bool",new Uint8Array(f.map(g=>Number(g)))),r.makeTensorInfo([m.length],n.dtype,new Int32Array(m))]}var LZ={kernelName:Id,backendName:"cpu",kernelFunc:OZ};function zZ(e){let{inputs:t,backend:r}=e,{inputIndices:n,inputShape:a,newShape:s}=t;if(n.shape.length!==2)throw new Error(`Input indices should be a matrix but received shape
${n.shape}`);if(a.shape.length!==1)throw new Error(`Input shape should be a vector but received shape
${a.shape}`);if(s.shape.length!==1)throw new Error(`Target shape should be a vector but received shape ${s.shape}`);let i=Array.from(r.data.get(a.dataId).values),o=r.data.get(n.dataId).values,l=Array.from(r.data.get(s.dataId).values),[p,u,d]=nT(o,n.shape,n.dtype,i,l);return[r.makeTensorInfo(u,n.dtype,p),r.makeTensorInfo([d.length],s.dtype,new Int32Array(d))]}var PZ={kernelName:Uu,backendName:"cpu",kernelFunc:zZ};function BZ(e){let{inputs:t,backend:r}=e,{data:n,indices:a,segmentIds:s}=t;if(n.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(a.shape.length!==1)throw new Error(`Indices should be a vector but received shape
${a.shape}`);if(s.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape
${s.shape}`);if(a.shape[0]!==s.shape[0])throw new Error("segmentIds and indices should have same size.");let i=r.data.get(n.dataId).values,o=r.data.get(a.dataId).values,l=r.data.get(s.dataId).values,[p,u]=Vv(i,n.shape,n.dtype,o,l,!0);return r.makeTensorInfo(u,n.dtype,p)}var WZ={kernelName:Sd,backendName:"cpu",kernelFunc:BZ};function UZ(e){let{inputs:t,backend:r}=e,{data:n,indices:a,segmentIds:s}=t;if(n.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(a.shape.length!==1)throw new Error(`Indices should be a vector but received shape
${a.shape}`);if(s.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape
${s.shape}`);if(a.shape[0]!==s.shape[0])throw new Error("segmentIds and indices should have same size.");let i=r.data.get(n.dataId).values,o=r.data.get(a.dataId).values,l=r.data.get(s.dataId).values,[p,u]=Vv(i,n.shape,n.dtype,o,l);return r.makeTensorInfo(u,n.dtype,p)}var VZ={kernelName:Nd,backendName:"cpu",kernelFunc:UZ};function GZ(e){let{inputs:t,backend:r,attrs:n}=e,{sparseIndices:a,sparseValues:s,defaultValue:i}=t,{outputShape:o}=n,{sliceRank:l,numUpdates:p,sliceSize:u,strides:d,outputSize:h}=_.calculateShapes(s,a,o),c=!1,f=r.bufferSync(a),m;switch(s.dtype){case"bool":{let g=r.bufferSync(s),y=!!r.data.get(i.dataId).values[0];m=ri(f,g,o,h,u,p,l,d,y,c);break}case"float32":{let g=r.bufferSync(s),y=r.data.get(i.dataId).values[0];m=ri(f,g,o,h,u,p,l,d,y,c);break}case"int32":{let g=r.bufferSync(s),y=r.data.get(i.dataId).values[0];m=ri(f,g,o,h,u,p,l,d,y,c);break}case"string":{let g=r.bufferSync(s),y=k.decodeString(r.data.get(i.dataId).values[0]);m=ri(f,g,o,h,u,p,l,d,y,c);break}default:throw new Error(`Unsupported type ${s.dtype}`)}return r.makeTensorInfo(o,m.dtype,m.values)}var HZ={kernelName:Vu,backendName:"cpu",kernelFunc:GZ};function jZ(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{numOrSizeSplits:s,axis:i}=n,o=k.parseAxisParam(i,a.shape)[0],l=_.prepareSplitSize(a,s,o),p=new Array(a.shape.length).fill(0),u=a.shape.slice();return l.map(d=>{let h=[...u];h[o]=d;let c=ki({inputs:{x:a},backend:r,attrs:{begin:p,size:h}});return p[o]+=d,c})}var qZ={kernelName:Wu,backendName:"cpu",kernelFunc:jZ},KZ={kernelName:_d,backendName:"cpu",kernelFunc:({inputs:e,backend:t})=>{let{x:r}=e,n=t;ye(r,"square");let a=n.data.get(r.dataId).values,s=new Float32Array(a.length);for(let i=0;i<a.length;++i){let o=a[i];s[i]=o*o}return{dataId:n.write(s,r.shape,r.dtype),shape:r.shape,dtype:r.dtype}}},XZ=at($s,(e,t)=>{let r=t;return isNaN(e)?NaN:e>0?1:r.alpha}),ZZ={kernelName:$s,backendName:"cpu",kernelFunc:XZ};function JZ(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{begin:s,end:i,strides:o,beginMask:l,endMask:p,ellipsisMask:u,newAxisMask:d,shrinkAxisMask:h}=n;ye(a,"stridedSlice");let{finalShapeSparse:c,finalShape:f,isIdentity:m,sliceDim0:g,isSimpleSlice:y,begin:b,end:x,strides:v}=Wt.sliceInfo(a.shape,s,i,o,l,p,u,d,h),w;if(m)w=yt({inputs:{x:a},backend:r,attrs:{shape:f}});else if(g||y){k.assert(a.shape.length>=1,()=>`Input must have rank at least 1, got: ${a.shape.length}`);let N=Wt.computeOutShape(b,x,v),T=ki({inputs:{x:a},backend:r,attrs:{begin:b,size:N}});w=yt({inputs:{x:T},backend:r,attrs:{shape:f}}),r.disposeIntermediateTensorInfo(T)}else{let N=r.bufferSync(a),T=iT(c,N,v,b);w=r.makeTensorInfo(f,T.dtype,T.values)}return w}var YZ={kernelName:Gu,backendName:"cpu",kernelFunc:JZ};function QZ(e){let{inputs:t,backend:r,attrs:n}=e,{separator:a,nGramWidths:s,leftPad:i,rightPad:o,padWidth:l,preserveShortSequences:p}=n,{data:u,dataSplits:d}=t,h=r.data.get(u.dataId).values,c=r.data.get(d.dataId).values,[f,m]=Gv(h,c,a,s,i,o,l,p);return[r.makeTensorInfo([f.length],"string",f),r.makeTensorInfo(d.shape,"int32",m)]}var eJ={kernelName:Cd,backendName:"cpu",kernelFunc:QZ};function tJ(e){let{inputs:t,backend:r,attrs:n}=e,{skipEmpty:a}=n,{input:s,delimiter:i}=t;if(s.dtype!=="string")throw new Error("Input must be of datatype string");if(s.shape.length!==1)throw new Error(`Input must be a vector, got shape: ${s.shape}`);if(i.shape.length!==0)throw new Error(`Delimiter must be a scalar, got shape: ${i.shape}`);let o=r.data.get(s.dataId).values,l=r.data.get(i.dataId).values[0],[p,u,d]=Hv(o,l,a),h=u.length;return[r.makeTensorInfo([h,2],"int32",p),r.makeTensorInfo([h],"string",u),r.makeTensorInfo([2],"int32",new Int32Array(d))]}var rJ={kernelName:Ed,backendName:"cpu",kernelFunc:tJ};function nJ(e){let{inputs:t,backend:r,attrs:n}=e,{numBuckets:a}=n,{input:s}=t;if(s.dtype!=="string")throw new Error("Input must be of datatype string");if(a<=0)throw new Error("Number of buckets must be at least 1");let i=r.data.get(s.dataId).values,o=jv(i,a);return r.makeTensorInfo(s.shape,"int32",o)}var aJ={kernelName:$d,backendName:"cpu",kernelFunc:nJ},sJ=at(qo,e=>Math.tan(e)),iJ={kernelName:qo,backendName:"cpu",kernelFunc:sJ},oJ=at(Ko,e=>Math.tanh(e)),lJ={kernelName:Ko,backendName:"cpu",kernelFunc:oJ};function uJ(e){let{inputs:t,backend:r}=e,{tensor:n,indices:a,updates:s}=t,{sliceRank:i,numUpdates:o,sliceSize:l,strides:p,outputSize:u}=_.calculateShapes(s,a,n.shape),d=!1,h=r.bufferSync(a),c=r.bufferSync(s),f=r.bufferSync(n),m=ri(h,c,n.shape,u,l,o,i,p,f,d);return r.makeTensorInfo(n.shape,m.dtype,m.values)}var pJ={kernelName:Ou,backendName:"cpu",kernelFunc:uJ};function dJ(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{reps:s}=n;ye(a,"tile");let i=lT(r.bufferSync(a),s);return r.makeTensorInfo(i.shape,i.dtype,i.values)}var hJ={kernelName:Es,backendName:"cpu",kernelFunc:dJ};function cJ(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{k:s,sorted:i}=n;ye(a,"topk");let o=r.data.get(a.dataId).values,[l,p]=pT(o,a.shape,a.dtype,s,i);return[r.makeTensorInfo(l.shape,l.dtype,l.values),r.makeTensorInfo(p.shape,p.dtype,p.values)]}var fJ={kernelName:Hu,backendName:"cpu",kernelFunc:cJ};function mJ(e){let{inputs:t,attrs:r,backend:n}=e,{image:a,transforms:s}=t,{interpolation:i,fillMode:o,fillValue:l,outputShape:p}=r,[u,d,h,c]=a.shape,[f,m]=p??[d,h],g=[u,f,m,c],y=k.computeStrides(a.shape),b=y[0],x=y[1],v=y[2],w=k.computeStrides(g),N=w[0],T=w[1],E=w[2],$=k.getTypedArrayFromDType(a.dtype,k.sizeFromShape(g));$.fill(l);let R=n.data.get(a.dataId).values,F=n.data.get(s.dataId).values;for(let S=0;S<u;++S){let D=s.shape[0]===1?F:F.subarray(S*8,S*8+8);for(let P=0;P<f;++P)for(let U=0;U<m;++U)for(let H=0;H<c;++H){let q,G=D[6]*U+D[7]*P+1;if(G===0)continue;let Z=(D[0]*U+D[1]*P+D[2])/G,ee=(D[3]*U+D[4]*P+D[5])/G,X=m1(Z,h,o),re=m1(ee,d,o);switch(i){case"nearest":q=wJ(R,d,h,b,x,v,S,re,X,H,l);break;case"bilinear":q=kJ(R,d,h,b,x,v,S,re,X,H,l);break;default:throw new Error(`Error in Transform: Expect 'nearest' or 'bilinear', but got ${i}`)}let te=S*N+P*T+U*E+H;$[te]=q}return n.makeTensorInfo(g,a.dtype,$)}return{dataId:n.write($,g,a.dtype),shape:a.shape,dtype:a.dtype}}var gJ={kernelName:ju,backendName:"cpu",kernelFunc:mJ};function m1(e,t,r){switch(r){case"reflect":return yJ(e,t);case"wrap":return bJ(e,t);case"nearest":return vJ(e,t);case"constant":default:return xJ(e)}}function yJ(e,t){let r=e;if(r<0)if(t<=1)r=0;else{let n=2*t;r<n&&(r=n*Math.trunc(-r/n)+r),r=r<-t?r+n:-r-1}else if(r>t-1)if(t<=1)r=0;else{let n=2*t;r-=n*Math.trunc(r/n),r>=t&&(r=n-r-1)}return k.clamp(0,r,t-1)}function bJ(e,t){let r=e;if(r<0)if(t<=1)r=0;else{let n=t-1;r+=t*(Math.trunc(-r/n)+1)}else if(r>t-1)if(t<=1)r=0;else{let n=t-1;r-=t*Math.trunc(r/n)}return k.clamp(0,r,t-1)}function xJ(e,t){return e}function vJ(e,t){return k.clamp(0,e,t-1)}function Fp(e,t,r,n,a,s,i,o,l,p,u){let d=i*n+o*a+l*s+p;return 0<=o&&o<t&&0<=l&&l<r?e[d]:u}function wJ(e,t,r,n,a,s,i,o,l,p,u){let d=Math.round(o),h=Math.round(l);return Fp(e,t,r,n,a,s,i,d,h,p,u)}function kJ(e,t,r,n,a,s,i,o,l,p,u){let d=Math.floor(o),h=Math.floor(l),c=d+1,f=h+1,m=(f-l)*Fp(e,t,r,n,a,s,i,d,h,p,u)+(l-h)*Fp(e,t,r,n,a,s,i,d,f,p,u),g=(f-l)*Fp(e,t,r,n,a,s,i,c,h,p,u)+(l-h)*Fp(e,t,r,n,a,s,i,c,f,p,u);return(c-o)*m+(o-d)*g}function IJ(e){let{inputs:t,attrs:r,backend:n}=e,{axis:a}=r,{x:s}=t;ye(s,"unique");let i=n.data.get(s.dataId).values,{outputValues:o,outputShape:l,indices:p}=Kv(i,a,s.shape,s.dtype);return[n.makeTensorInfo(l,s.dtype,o),n.makeTensorInfo([p.length],"int32",p)]}var SJ={kernelName:Ad,backendName:"cpu",kernelFunc:IJ};function NJ(e){let{inputs:t,backend:r,attrs:n}=e,{value:a}=t,{axis:s}=n;s<0&&(s+=a.shape.length);let i=a.shape.length,o=a.shape[s],l=new Array(i-1),p=0;for(let c=0;c<i;c++)c!==s&&(l[p++]=a.shape[c]);let u=new Array(i).fill(0),d=a.shape.slice();d[s]=1;let h=new Array(o);for(let c=0;c<h.length;c++){u[s]=c;let f=ki({inputs:{x:a},backend:r,attrs:{begin:u,size:d}});h[c]=yt({inputs:{x:f},backend:r,attrs:{shape:l}}),r.disposeIntermediateTensorInfo(f)}return h}var _J={kernelName:qu,backendName:"cpu",kernelFunc:NJ};function TJ(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,segmentIds:s}=t,{numSegments:i}=n;ye(a,"unsortedSegmentSum");let o=a.shape.length,l=s.shape.length,p=[],u=[],d=o-l,h=s;for(let f=0;f<d;++f){let m=Mc({inputs:{input:h},backend:r,attrs:{dim:f+1}});h=m,u.push(m)}for(let f=0;f<i;++f){let m=k.createScalarValue(f,"int32"),g=r.makeTensorInfo([],"int32",m),y=A_({inputs:{a:g,b:h},backend:r}),b=Is({inputs:{x:y},backend:r,attrs:{dtype:"float32"}}),x=ym({inputs:{a:b,b:a},backend:r}),v=oh({inputs:{x},backend:r,attrs:{axis:0,keepDims:!1}});p.push(v),u.push(g),u.push(y),u.push(b),u.push(x),u.push(v)}let c=NT({inputs:p,backend:r,attrs:{axis:0}});return u.forEach(f=>r.disposeIntermediateTensorInfo(f)),c}var CJ={kernelName:Fd,backendName:"cpu",kernelFunc:TJ},EJ=[kK,t5,SK,_K,o5,CK,$K,FK,DK,OK,zK,BK,UK,HK,qK,ZK,YK,e8,r8,vK,a8,i8,l8,u5,p8,s5,d5,h8,r5,f8,g8,y8,x8,w8,I8,N8,T8,E8,A8,R8,M8,L8,P8,W8,U8,G8,j8,K8,X8,Z8,J8,Q8,rX,cK,aX,h5,hX,c5,cX,m5,xX,vX,kX,y5,x5,SX,_X,CX,$X,w5,I5,n5,FX,m8,DX,OX,zX,fK,N5,T5,BX,E5,UX,HX,qX,ZX,YX,e7,t7,A5,n7,s7,o7,u7,d7,c7,m7,R5,y7,v7,S7,M5,L5,T7,$7,R7,P5,M7,L7,z7,_T,U7,gK,U5,G7,j7,K7,Z7,a5,Hg,Y7,yK,bK,xK,eZ,rZ,aZ,iZ,lZ,uZ,dZ,J5,cZ,bZ,vZ,SZ,Q5,_Z,CZ,$Z,eK,k7,RZ,MZ,LZ,PZ,WZ,VZ,HZ,qZ,nK,KZ,sK,oK,ZZ,YZ,eJ,rJ,aJ,dK,eX,iJ,lJ,pJ,hJ,fJ,gJ,B5,SJ,_J,CJ,O7];for(let e of EJ)Rd(e);var TT={};Ee(TT,{assertNotComplex:()=>lp,bindCanvasToFramebuffer:()=>BJ,bindColorTextureToFramebuffer:()=>Qh,bindTextureToProgramUniformSampler:()=>VT,bindTextureUnit:()=>BT,bindVertexBufferToProgramAttribute:()=>qg,callAndCheck:()=>pe,canBeRepresented:()=>ET,createFragmentShader:()=>FT,createFramebuffer:()=>PT,createProgram:()=>RT,createStaticIndexBuffer:()=>OT,createStaticVertexBuffer:()=>MT,createTexture:()=>LT,createVertexShader:()=>AT,getBatchDim:()=>Ii,getExtensionOrThrow:()=>Rp,getFramebufferErrorMessage:()=>GT,getMaxTexturesInShader:()=>KT,getNumChannels:()=>zJ,getProgramUniformLocation:()=>UT,getProgramUniformLocationOrThrow:()=>WT,getRowsCols:()=>Si,getShapeAs3D:()=>Mp,getTextureShapeFromLogicalShape:()=>jT,getWebGLDisjointQueryTimerVersion:()=>XT,getWebGLErrorMessage:()=>$T,getWebGLMaxTextureSize:()=>qT,hasExtension:()=>ln,isCapableOfRenderingToFloatTexture:()=>ZT,isDownloadFloatTextureEnabled:()=>JT,isReshapeFree:()=>sd,isWebGLFenceEnabled:()=>YT,isWebGLVersionEnabled:()=>Xg,linkProgram:()=>DT,logShaderSourceAndInfoLog:()=>Qv,resetMaxTextureSize:()=>WJ,resetMaxTexturesInShader:()=>UJ,unbindColorTextureFromFramebuffer:()=>Kg,unbindTextureUnit:()=>PJ,validateFramebuffer:()=>Dp,validateProgram:()=>Yh,validateTextureSize:()=>zT});var ei={},Bh={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};function CT(e,t){ei[e]=t}function Vn(e,t){if(!(e in ei)||t!=null){let n=AJ(e,t);if(n!==null)ei[e]=n;else return console.log("Could not get context for WebGL version",e),null}let r=ei[e];return r==null||r.isContextLost()?(delete ei[e],Vn(e)):(r.disable(r.DEPTH_TEST),r.disable(r.STENCIL_TEST),r.disable(r.BLEND),r.disable(r.DITHER),r.disable(r.POLYGON_OFFSET_FILL),r.disable(r.SAMPLE_COVERAGE),r.enable(r.SCISSOR_TEST),r.enable(r.CULL_FACE),r.cullFace(r.BACK),ei[e])}function $J(e){if(!j().getBool("IS_SAFARI")&&typeof OffscreenCanvas<"u"&&e===2)return new OffscreenCanvas(300,150);if(typeof document<"u")return document.createElement("canvas");throw new Error("Cannot create a canvas in this context")}function AJ(e,t){if(e!==1&&e!==2)throw new Error("Cannot get WebGL rendering context, WebGL is disabled.");let r=t??$J(e);return r.addEventListener("webglcontextlost",n=>{n.preventDefault(),delete ei[e]},!1),j().getBool("SOFTWARE_WEBGL_ENABLED")&&(Bh.failIfMajorPerformanceCaveat=!1),e===1?r.getContext("webgl",Bh)||r.getContext("experimental-webgl",Bh):r.getContext("webgl2",Bh)}var ad;(function(e){e[e.DENSE=0]="DENSE",e[e.SHARED_BATCH=1]="SHARED_BATCH"})(ad||(ad={}));var on;(function(e){e[e.RENDER=0]="RENDER",e[e.UPLOAD=1]="UPLOAD",e[e.PIXELS=2]="PIXELS",e[e.DOWNLOAD=3]="DOWNLOAD"})(on||(on={}));var sr;(function(e){e[e.UNPACKED_FLOAT16=0]="UNPACKED_FLOAT16",e[e.UNPACKED_FLOAT32=1]="UNPACKED_FLOAT32",e[e.PACKED_4X1_UNSIGNED_BYTE=2]="PACKED_4X1_UNSIGNED_BYTE",e[e.PACKED_2X2_FLOAT32=3]="PACKED_2X2_FLOAT32",e[e.PACKED_2X2_FLOAT16=4]="PACKED_2X2_FLOAT16"})(sr||(sr={}));function lh(e,t){return[t,e]}function FJ(e,t){return e*t}function Wh(e){let t=k.sizeFromShape(e),r=Math.ceil(t/4);return k.sizeToSquarishShape(r)}function op(e,t){return[Math.max(1,Math.ceil(t/2)),Math.max(1,Math.ceil(e/2))]}function RJ(e,t){let[r,n]=op(e,t);return r*n*4}function Yv(e,t){let r=e,n,a,s,i,o,l,p,u,d,h;return j().getNumber("WEBGL_VERSION")===2?(n=r.R32F,a=r.R16F,s=r.RGBA16F,i=r.RGBA32F,o=r.RED,p=4,u=1,d=r.HALF_FLOAT,h=r.FLOAT,l=r.RGBA8):(n=e.RGBA,a=e.RGBA,s=e.RGBA,i=r.RGBA,o=e.RGBA,p=4,u=4,d=t!=null?t.HALF_FLOAT_OES:null,h=e.FLOAT,l=e.RGBA),{internalFormatFloat:n,internalFormatHalfFloat:a,internalFormatPackedHalfFloat:s,internalFormatPackedFloat:i,textureFormatFloat:o,downloadTextureFormat:l,downloadUnpackNumChannels:p,defaultNumChannels:u,textureTypeHalfFloat:d,textureTypeFloat:h}}function pe(e,t){let r=t();return j().getBool("DEBUG")&&DJ(e),r}function DJ(e){let t=e.getError();if(t!==e.NO_ERROR)throw new Error("WebGL Error: "+$T(e,t))}var MJ=596e-10,OJ=65504;function ET(e){return!!(j().getBool("WEBGL_RENDER_FLOAT32_ENABLED")||e===0||MJ<Math.abs(e)&&Math.abs(e)<OJ)}function $T(e,t){switch(t){case e.NO_ERROR:return"NO_ERROR";case e.INVALID_ENUM:return"INVALID_ENUM";case e.INVALID_VALUE:return"INVALID_VALUE";case e.INVALID_OPERATION:return"INVALID_OPERATION";case e.INVALID_FRAMEBUFFER_OPERATION:return"INVALID_FRAMEBUFFER_OPERATION";case e.OUT_OF_MEMORY:return"OUT_OF_MEMORY";case e.CONTEXT_LOST_WEBGL:return"CONTEXT_LOST_WEBGL";default:return`Unknown error code ${t}`}}function Rp(e,t){return Wa(e,()=>e.getExtension(t),'Extension "'+t+'" not supported on this browser.')}function AT(e,t){let r=Wa(e,()=>e.createShader(e.VERTEX_SHADER),"Unable to create vertex WebGLShader.");if(pe(e,()=>e.shaderSource(r,t)),pe(e,()=>e.compileShader(r)),e.getShaderParameter(r,e.COMPILE_STATUS)===!1)throw console.log(e.getShaderInfoLog(r)),new Error("Failed to compile vertex shader.");return r}function FT(e,t){let r=Wa(e,()=>e.createShader(e.FRAGMENT_SHADER),"Unable to create fragment WebGLShader.");if(pe(e,()=>e.shaderSource(r,t)),pe(e,()=>e.compileShader(r)),j().get("ENGINE_COMPILE_ONLY"))return r;if(e.getShaderParameter(r,e.COMPILE_STATUS)===!1)throw Qv(t,e.getShaderInfoLog(r)),new Error("Failed to compile fragment shader.");return r}var LJ=/ERROR: [0-9]+:([0-9]+):/g;function Qv(e,t){let r=LJ.exec(t);if(r==null){console.log(`Couldn't parse line number in error: ${t}`),console.log(e);return}let n=+r[1],a=e.split(`
`),s=a.length.toString().length+2,i=a.map((d,h)=>k.rightPad((h+1).toString(),s)+d),o=0;for(let d=0;d<i.length;d++)o=Math.max(i[d].length,o);let l=i.slice(0,n-1),p=i.slice(n-1,n),u=i.slice(n);console.log(l.join(`
`)),console.log(t.split(`
`)[0]),console.log(`%c ${k.rightPad(p[0],o)}`,"border:1px solid red; background-color:#e3d2d2; color:#a61717"),console.log(u.join(`
`))}function RT(e){return Wa(e,()=>e.createProgram(),"Unable to create WebGLProgram.")}function DT(e,t){if(pe(e,()=>e.linkProgram(t)),!j().get("ENGINE_COMPILE_ONLY")&&e.getProgramParameter(t,e.LINK_STATUS)===!1)throw console.log(e.getProgramInfoLog(t)),new Error("Failed to link vertex and fragment shaders.")}function Yh(e,t){if(pe(e,()=>e.validateProgram(t)),e.getProgramParameter(t,e.VALIDATE_STATUS)===!1)throw console.log(e.getProgramInfoLog(t)),new Error("Shader program validation failed.")}function MT(e,t){let r=Wa(e,()=>e.createBuffer(),"Unable to create WebGLBuffer");return pe(e,()=>e.bindBuffer(e.ARRAY_BUFFER,r)),pe(e,()=>e.bufferData(e.ARRAY_BUFFER,t,e.STATIC_DRAW)),r}function OT(e,t){let r=Wa(e,()=>e.createBuffer(),"Unable to create WebGLBuffer");return pe(e,()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,r)),pe(e,()=>e.bufferData(e.ELEMENT_ARRAY_BUFFER,t,e.STATIC_DRAW)),r}function zJ(){return j().getNumber("WEBGL_VERSION")===2?1:4}function LT(e){return Wa(e,()=>e.createTexture(),"Unable to create WebGLTexture.")}function zT(e,t){let r=j().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(e<=0||t<=0){let n=`[${e}x${t}]`;throw new Error("Requested texture size "+n+" is invalid.")}if(e>r||t>r){let n=`[${e}x${t}]`,a=`[${r}x${r}]`;throw new Error("Requested texture size "+n+" greater than WebGL maximum on this browser / GPU "+a+".")}}function PT(e){return Wa(e,()=>e.createFramebuffer(),"Unable to create WebGLFramebuffer.")}function qg(e,t,r,n,a,s,i){let o=e.getAttribLocation(t,r);return o===-1?!1:(pe(e,()=>e.bindBuffer(e.ARRAY_BUFFER,n)),pe(e,()=>e.vertexAttribPointer(o,a,e.FLOAT,!1,s,i)),pe(e,()=>e.enableVertexAttribArray(o)),!0)}function BT(e,t,r){HT(e,r),pe(e,()=>e.activeTexture(e.TEXTURE0+r)),pe(e,()=>e.bindTexture(e.TEXTURE_2D,t))}function PJ(e,t){HT(e,t),pe(e,()=>e.activeTexture(e.TEXTURE0+t)),pe(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function WT(e,t,r){return Wa(e,()=>e.getUniformLocation(t,r),'uniform "'+r+'" not present in program.')}function UT(e,t,r){return e.getUniformLocation(t,r)}function VT(e,t,r,n){pe(e,()=>BT(e,t,n)),pe(e,()=>e.uniform1i(r,n))}function BJ(e){pe(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,null)),pe(e,()=>e.viewport(0,0,e.canvas.width,e.canvas.height)),pe(e,()=>e.scissor(0,0,e.canvas.width,e.canvas.height))}function Qh(e,t,r){pe(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,r)),pe(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0))}function Kg(e,t){pe(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,t)),pe(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,null,0))}function Dp(e){let t=e.checkFramebufferStatus(e.FRAMEBUFFER);if(t!==e.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+GT(e,t))}function GT(e,t){switch(t){case e.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case e.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case e.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:return"FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case e.FRAMEBUFFER_UNSUPPORTED:return"FRAMEBUFFER_UNSUPPORTED";default:return`unknown error ${t}`}}function Wa(e,t,r){let n=pe(e,()=>t());if(n==null)throw new Error(r);return n}function HT(e,t){let r=e.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,n=t+e.TEXTURE0;if(n<e.TEXTURE0||n>r){let a=`[gl.TEXTURE0, gl.TEXTURE${r}]`;throw new Error(`textureUnit must be in ${a}.`)}}function Ii(e,t=2){return k.sizeFromShape(e.slice(0,e.length-t))}function Si(e){if(e.length===0)throw Error("Cannot get rows and columns of an empty shape array.");return[e.length>1?e[e.length-2]:1,e[e.length-1]]}function Mp(e){let t=[1,1,1];return e.length===0||e.length===1&&e[0]===1||(t=[Ii(e),...Si(e)]),t}function jT(e,t=!1){let r=j().getNumber("WEBGL_MAX_TEXTURE_SIZE"),n=j().getNumber("WEBGL_MAX_SIZE_FOR_NARROW_TEXTURE");n===1/0&&j().getBool("WEBGL_AUTO_SQUARIFY_NARROW_TEXTURE_SHAPE")&&(n=r/2),t&&(r=r*2,n=n*2,e=e.map((o,l)=>l>=e.length-2?k.nearestLargerEven(e[l]):e[l]),e.length===1&&(e=[2,e[0]])),e.length!==2&&(e=k.squeezeShape(e).newShape);let a=k.sizeFromShape(e),s=null;e.length<=1&&a<=r?s=[1,a]:e.length===2&&e[0]<=r&&e[1]<=r?s=e:e.length===3&&e[0]*e[1]<=r&&e[2]<=r?s=[e[0]*e[1],e[2]]:e.length===3&&e[0]<=r&&e[1]*e[2]<=r?s=[e[0],e[1]*e[2]]:e.length===4&&e[0]*e[1]*e[2]<=r&&e[3]<=r?s=[e[0]*e[1]*e[2],e[3]]:e.length===4&&e[0]<=r&&e[1]*e[2]*e[3]<=r&&(s=[e[0],e[1]*e[2]*e[3]]);let i=s!=null&&Math.max(...s)>n&&Math.min(...s)<=(t?2:1)&&Math.min(...s)>0;if(s==null||i)if(t){let o=Ii(e),l=2,p=2;e.length&&([l,p]=Si(e)),a=o*(l/2)*(p/2),s=k.sizeToSquarishShape(a).map(u=>u*2)}else s=k.sizeToSquarishShape(a);return s}function Uh(e){return e%2===0}function sd(e,t){if(e=e.slice(-2),t=t.slice(-2),k.arraysEqual(e,t)||!e.length||!t.length||e[0]===0||e[1]===0||t[0]===0||t[1]===0)return!0;if(e.length!==t.length){let r=e[e.length-1],n=t[t.length-1];if(r===n||Uh(r)&&Uh(n)&&(e[0]===1||t[0]===1))return!0}return e[1]===t[1]&&Uh(e[0])&&Uh(t[0])}var ec,tc;function qT(e){if(ec==null){let t=Vn(e);ec=t.getParameter(t.MAX_TEXTURE_SIZE)}return ec}function WJ(){ec=null}function UJ(){tc=null}function KT(e){if(tc==null){let t=Vn(e);tc=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,tc)}function XT(e){if(e===0)return 0;let t,r=Vn(e);return ln(r,"EXT_disjoint_timer_query_webgl2")&&e===2?t=2:ln(r,"EXT_disjoint_timer_query")?t=1:t=0,t}function ln(e,t){return e.getExtension(t)!=null}function Xg(e){try{if(Vn(e)!=null)return!0}catch(t){return console.log("Error when getting WebGL context: ",t),!1}return!1}function ZT(e){if(e===0)return!1;let t=Vn(e);if(e===1){if(!ln(t,"OES_texture_float"))return!1}else if(!ln(t,"EXT_color_buffer_float"))return!1;return Zg(t)}function JT(e){if(e===0)return!1;let t=Vn(e);if(e===1){if(!ln(t,"OES_texture_float")||!ln(t,"WEBGL_color_buffer_float"))return!1}else{if(ln(t,"EXT_color_buffer_float"))return Zg(t);let r="EXT_color_buffer_half_float";if(ln(t,r)){let n=t.getExtension(r);return VJ(t,n)}return!1}return Zg(t)}function Zg(e){let t=Yv(e),r=e.createTexture();e.bindTexture(e.TEXTURE_2D,r),e.texImage2D(e.TEXTURE_2D,0,t.internalFormatFloat,1,1,0,t.textureFormatFloat,t.textureTypeFloat,null);let n=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,n),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,r,0);let a=e.checkFramebufferStatus(e.FRAMEBUFFER)===e.FRAMEBUFFER_COMPLETE;return e.bindTexture(e.TEXTURE_2D,null),e.bindFramebuffer(e.FRAMEBUFFER,null),e.deleteTexture(r),e.deleteFramebuffer(n),a}function VJ(e,t){let r=Yv(e,t),n=e.createTexture();e.bindTexture(e.TEXTURE_2D,n),e.texImage2D(e.TEXTURE_2D,0,r.internalFormatHalfFloat,1,1,0,r.textureFormatFloat,r.textureTypeHalfFloat,null);let a=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,a),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,n,0);let s=e.checkFramebufferStatus(e.FRAMEBUFFER)===e.FRAMEBUFFER_COMPLETE;return e.bindTexture(e.TEXTURE_2D,null),e.bindFramebuffer(e.FRAMEBUFFER,null),e.deleteTexture(n),e.deleteFramebuffer(a),s}function YT(e){return e!==2?!1:Vn(e).fenceSync!=null}function lp(e,t){Array.isArray(e)||(e=[e]),e.forEach(r=>{r!=null&&k.assert(r.dtype!=="complex64",()=>`${t} does not support complex64 tensors in the WebGL backend.`)})}var xe=j();xe.registerFlag("HAS_WEBGL",()=>xe.getNumber("WEBGL_VERSION")>0);xe.registerFlag("WEBGL_VERSION",()=>Xg(2)?2:Xg(1)?1:0);xe.registerFlag("WEBGL_CHECK_NUMERICAL_PROBLEMS",()=>!1);xe.registerFlag("WEBGL_BUFFER_SUPPORTED",()=>xe.get("WEBGL_VERSION")===2);xe.registerFlag("WEBGL_CPU_FORWARD",()=>!0);xe.registerFlag("WEBGL_FORCE_F16_TEXTURES",()=>!1);xe.registerFlag("WEBGL_PACK",()=>xe.getBool("HAS_WEBGL"));xe.registerFlag("WEBGL_PACK_NORMALIZATION",()=>xe.getBool("WEBGL_PACK"));xe.registerFlag("WEBGL_PACK_CLIP",()=>xe.getBool("WEBGL_PACK"));xe.registerFlag("WEBGL_PACK_DEPTHWISECONV",()=>xe.getBool("WEBGL_PACK"));xe.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",()=>xe.getBool("WEBGL_PACK"));xe.registerFlag("WEBGL_PACK_UNARY_OPERATIONS",()=>xe.getBool("WEBGL_PACK"));xe.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",()=>xe.getBool("WEBGL_PACK"));xe.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",()=>xe.getBool("WEBGL_PACK"));xe.registerFlag("WEBGL_PACK_REDUCE",()=>xe.getBool("WEBGL_PACK"));xe.registerFlag("WEBGL_LAZILY_UNPACK",()=>xe.getBool("WEBGL_PACK"));xe.registerFlag("WEBGL_CONV_IM2COL",()=>xe.getBool("WEBGL_PACK"));xe.registerFlag("WEBGL_PACK_CONV2DTRANSPOSE",()=>xe.getBool("WEBGL_PACK"));xe.registerFlag("WEBGL_MAX_TEXTURE_SIZE",()=>qT(xe.getNumber("WEBGL_VERSION")));xe.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",()=>KT(xe.getNumber("WEBGL_VERSION")));xe.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",()=>{let e=xe.getNumber("WEBGL_VERSION");return e===0?0:XT(e)});xe.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",()=>xe.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&!Od.isMobile());xe.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE",()=>ZT(xe.getNumber("WEBGL_VERSION")));xe.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",()=>xe.getBool("WEBGL_FORCE_F16_TEXTURES")?!1:xe.getBool("WEBGL_RENDER_FLOAT32_CAPABLE"));xe.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",()=>JT(xe.getNumber("WEBGL_VERSION")));xe.registerFlag("WEBGL_FENCE_API_ENABLED",()=>YT(xe.getNumber("WEBGL_VERSION")));xe.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",()=>xe.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?4:0);xe.registerFlag("WEBGL_DELETE_TEXTURE_THRESHOLD",()=>-1,e=>{if(typeof e!="number")throw new Error(`WEBGL_DELETE_TEXTURE_THRESHOLD must be a number but got ${e}.`);if(e<0&&e!==-1)throw new Error(`WEBGL_DELETE_TEXTURE_THRESHOLD must be -1 (indicating never delete) or at least 0, but got ${e}.`)});xe.registerFlag("WEBGL_FLUSH_THRESHOLD",()=>Od.isMobile()?1:-1,e=>{if(typeof e!="number")throw new Error(`WEBGL_FLUSH_THRESHOLD must be a number but got ${e}.`);if(e<0&&e!==-1)throw new Error(`WEBGL_FLUSH_THRESHOLD must be -1 (indicating never manual flush) or at least 0, but got ${e}.`)});xe.registerFlag("CPU_HANDOFF_SIZE_THRESHOLD",()=>128);xe.registerFlag("WEBGL_USE_SHAPES_UNIFORMS",()=>!1);xe.registerFlag("TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD",()=>1e5);xe.registerFlag("TOPK_K_CPU_HANDOFF_THRESHOLD",()=>128);xe.registerFlag("WEBGL_EXP_CONV",()=>!1);xe.registerFlag("SOFTWARE_WEBGL_ENABLED",()=>xe.getBool("IS_TEST"));xe.registerFlag("WEBGL_MAX_SIZE_FOR_NARROW_TEXTURE",()=>1/0);xe.registerFlag("WEBGL_AUTO_SQUARIFY_NARROW_TEXTURE_SHAPE",()=>!1);xe.registerFlag("WEBGL2_ISNAN_CUSTOM",()=>!1);xe.registerFlag("ENGINE_COMPILE_ONLY",()=>!1);function Sr(){let e,t,r,n,a,s,i,o,l,p;return j().getNumber("WEBGL_VERSION")===2?(e="#version 300 es",t="in",r="out",n="in",a="texture",s="outputColor",i="out vec4 outputColor;",o=j().getBool("WEBGL2_ISNAN_CUSTOM")?`
bool isnan_custom(float val) {
uint floatToUint = floatBitsToUint(val);
return (floatToUint & 0x7fffffffu) > 0x7f800000u;
}
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="",p=`
#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)));
}
`):(e="",t="attribute",r="varying",n="varying",a="texture2D",s="gl_FragColor",i="",o=`
#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));
}
`,p=`
int round(float value) {
return int(floor(value + 0.5));
}
ivec4 round(vec4 value) {
return ivec4(floor(value + vec4(0.5)));
}
`),{version:e,attribute:t,varyingVs:r,varyingFs:n,texture2D:a,output:s,defineOutput:i,defineSpecialNaN:o,defineSpecialInf:l,defineRound:p}}function rl(e,t,r="index"){let n=k.computeStrides(t);return n.map((a,s)=>{let i=`int ${e[s]} = ${r} / ${a}`,o=s===n.length-1?`int ${e[s+1]} = ${r} - ${e[s]} * ${a}`:`index -= ${e[s]} * ${a}`;return`${i}; ${o};`}).join("")}function bm(e,t,r="index"){let n=k.computeStrides(t);return n.map((a,s)=>{let i=`int ${e[s]} = ${r} / outShapeStrides[${s}]`,o=s===n.length-1?`int ${e[s+1]} = ${r} - ${e[s]} * outShapeStrides[${s}]`:`index -= ${e[s]} * outShapeStrides[${s}]`;return`${i}; ${o};`}).join("")}function GJ(e,t){let r=e.length,n=e.map(s=>`${t}[${s}]`),a=new Array(r-1);a[r-2]=n[r-1];for(let s=r-3;s>=0;--s)a[s]=`(${a[s+1]} * ${n[s+1]})`;return a}function HJ(e,t,r="index"){let n=e.map((s,i)=>i),a=GJ(n,t);return a.map((s,i)=>{let o=`int ${e[i]} = ${r} / ${a[i]}`,l=i===a.length-1?`int ${e[i+1]} = ${r} - ${e[i]} * ${a[i]}`:`index -= ${e[i]} * ${a[i]}`;return`${o}; ${l};`}).join("")}function ew(e){let t=k.computeStrides(e).map(r=>r.toString());return`
int getFlatIndex(ivec3 coords) {
return coords.x * ${t[0]} + coords.y * ${t[1]} + coords.z;
}
`}function tw(){return`
int getFlatIndex(ivec3 coords) {
return coords.x * outShapeStrides[0] + coords.y * outShapeStrides[1] + coords.z;
}
`}var QT=`
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;
}
`,{getBroadcastDims:eC}=_;function jJ(e,t,r){let n=[];if(e.forEach(h=>{let c=k.sizeFromShape(h.shapeInfo.logicalShape);if(h.shapeInfo.isUniform?n.push(`uniform float ${h.name}${c>1?`[${c}]`:""};`):(n.push(`uniform sampler2D ${h.name};`),n.push(`uniform int offset${h.name};`)),r.enableShapeUniforms){let{uniformShape:f}=rw(r.packedInputs,h.shapeInfo.logicalShape,h.shapeInfo.texShape);switch(f.length){case 1:n.push(`uniform int ${h.name}Shape;`);break;case 2:n.push(`uniform ivec2 ${h.name}Shape;`);break;case 3:n.push(`uniform ivec3 ${h.name}Shape;`);break;case 4:n.push(`uniform ivec4 ${h.name}Shape;`);break}n.push(`uniform ivec2 ${h.name}TexShape;`)}}),r.enableShapeUniforms){switch(t.logicalShape.length){case 1:n.push("uniform int outShape;");break;case 2:n.push("uniform ivec2 outShape;"),n.push("uniform int outShapeStrides;");break;case 3:n.push("uniform ivec3 outShape;"),n.push("uniform ivec2 outShapeStrides;");break;case 4:n.push("uniform ivec4 outShape;"),n.push("uniform ivec3 outShapeStrides;");break}n.push("uniform ivec2 outTexShape;")}r.customUniforms&&r.customUniforms.forEach(h=>{n.push(`uniform ${h.type} ${h.name}${h.arrayIndex?`[${h.arrayIndex}]`:""};`)});let a=n.join(`
`),s=e.map(h=>qJ(h,t,r.packedInputs,r.enableShapeUniforms)).join(`
`),i=t.texShape,o=Sr(),l=ZJ(o),p,u,d=QJ(o);return t.isPacked?(p=KJ(t.logicalShape,i,r.enableShapeUniforms),u=YJ(o)):(p=XJ(t.logicalShape,i,r.enableShapeUniforms),u=JJ(o)),r.packedInputs&&(d+=n9),[d,l,u,a,p,s,r.userCode].join(`
`)}function up(e,t=!1){let r=e.shapeInfo.logicalShape;switch(r.length){case 0:return m9(e,t);case 1:return y9(e,t);case 2:return x9(e,t);case 3:return w9(e,t);case 4:return I9(e,t);case 5:return S9(e);case 6:return N9(e);default:throw new Error(`${r.length}-D input sampling is not yet supported`)}}function tC(e,t){switch(e.shapeInfo.logicalShape.length){case 0:return f9(e);case 1:return g9(e,t);case 2:return b9(e,t);case 3:return v9(e,t);default:return k9(e,t)}}function qJ(e,t,r=!1,n){let a="";r?a+=tC(e,n):a+=up(e,n);let s=e.shapeInfo.logicalShape,i=t.logicalShape;return s.length<=i.length&&(r?a+=_9(e,t):a+=T9(e,t)),a}function KJ(e,t,r){switch(e.length){case 0:return rC();case 1:return a9(e,t,r);case 2:return h9(e,t,r);case 3:return i9(e,t,r);default:return l9(e,t,r)}}function XJ(e,t,r){switch(e.length){case 0:return rC();case 1:return s9(e,t,r);case 2:return c9(e,t,r);case 3:return o9(e,t,r);case 4:return u9(e,t,r);case 5:return p9(e,t);case 6:return d9(e,t);default:throw new Error(`${e.length}-D output sampling is not yet supported`)}}function ZJ(e){return`
float sampleTexture(sampler2D textureSampler, vec2 uv) {
return ${e.texture2D}(textureSampler, uv).r;
}
`}function JJ(e){return`
void setOutput(float val) {
${e.output} = vec4(val, 0, 0, 0);
}
`}function YJ(e){return`
void setOutput(vec4 val) {
${e.output} = val;
}
`}function QJ(e){return`${e.version}
precision highp float;
precision highp int;
precision highp sampler2D;
${e.varyingFs} vec2 resultUV;
${e.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;
${e.defineSpecialNaN}
${e.defineSpecialInf}
${e.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);
}
${e9}
${t9}
${r9}
`}var e9=`
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);
}
`,t9=`
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);
}
`,r9=`
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);
}
`,n9=`
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 rC(){return`
int getOutputCoords() {
return 0;
}
`}function a9(e,t,r){let n=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];return n[0]===1?r?`
int getOutputCoords() {
return 2 * int(resultUV.x * ceil(float(outTexShape[1]) / 2.0));
}
`:`
int getOutputCoords() {
return 2 * int(resultUV.x * ${n[1]}.0);
}
`:n[1]===1?r?`
int getOutputCoords() {
return 2 * int(resultUV.y * ceil(float(outTexShape[0]) / 2.0));
}
`:`
int getOutputCoords() {
return 2 * int(resultUV.y * ${n[0]}.0);
}
`:r?`
int getOutputCoords() {
ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(packedTexShape[0], packedTexShape[1]));
return 2 * (resTexRC.x * packedTexShape[1] + resTexRC.y);
}
`:`
int getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${n[0]}, ${n[1]}));
return 2 * (resTexRC.x * ${n[1]} + resTexRC.y);
}
`}function s9(e,t,r){return t[0]===1?r?`
int getOutputCoords() {
return int(resultUV.x * float(outTexShape[1]));
}
`:`
int getOutputCoords() {
return int(resultUV.x * ${t[1]}.0);
}
`:t[1]===1?r?`
int getOutputCoords() {
return int(resultUV.y * float(outTexShape[0]));
}
`:`
int getOutputCoords() {
return int(resultUV.y * ${t[0]}.0);
}
`:r?`
int getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(outTexShape[0], outTexShape[1]));
return resTexRC.x * outTexShape[1] + resTexRC.y;
}
`:`
int getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
return resTexRC.x * ${t[1]} + resTexRC.y;
}
`}function i9(e,t,r){if(r)return`
ivec3 getOutputCoords() {
ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));
int texelsInLogicalRow = int(ceil(float(outShape[2]) / 2.0));
int texelsInBatch = texelsInLogicalRow * int(ceil(float(outShape[1]) / 2.0));
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(packedTexShape[0], packedTexShape[1]));
int index = resTexRC.x * packedTexShape[1] + resTexRC.y;
int b = index / texelsInBatch;
index -= b * texelsInBatch;
int r = 2 * (index / texelsInLogicalRow);
int c = imod(index, texelsInLogicalRow) * 2;
return ivec3(b, r, c);
}
`;let n=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],a=Math.ceil(e[2]/2),s=a*Math.ceil(e[1]/2);return`
ivec3 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${n[0]}, ${n[1]}));
int index = resTexRC.x * ${n[1]} + resTexRC.y;
int b = index / ${s};
index -= b * ${s};
int r = 2 * (index / ${a});
int c = imod(index, ${a}) * 2;
return ivec3(b, r, c);
}
`}function o9(e,t,r){if(r)return`
ivec3 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(outTexShape[0], outTexShape[1]));
int index = resTexRC.x * outTexShape[1] + resTexRC.y;
${bm(["r","c","d"],e)}
return ivec3(r, c, d);
}
`;let n=rl(["r","c","d"],e);return`
ivec3 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
${n}
return ivec3(r, c, d);
}
`}function l9(e,t,r){if(r)return`
ivec4 getOutputCoords() {
ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(packedTexShape[0], packedTexShape[1]));
int index = resTexRC.x * packedTexShape[1] + resTexRC.y;
int texelsInLogicalRow = int(ceil(float(outShape[3]) / 2.0));
int texelsInBatch = texelsInLogicalRow * int(ceil(float(outShape[2]) / 2.0));
int texelsInBatchN = texelsInBatch * outShape[1];
int b2 = index / texelsInBatchN;
index -= b2 * texelsInBatchN;
int b = index / texelsInBatch;
index -= b * texelsInBatch;
int r = 2 * (index / texelsInLogicalRow);
int c = imod(index, texelsInLogicalRow) * 2;
return ivec4(b2, b, r, c);
}
`;let n=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],a=Math.ceil(e[e.length-1]/2),s=a*Math.ceil(e[e.length-2]/2),i=s,o="",l="b, r, c";for(let p=2;p<e.length-1;p++)i*=e[e.length-p-1],o=`
int b${p} = index / ${i};
index -= b${p} * ${i};
`+o,l=`b${p}, `+l;return`
ivec${e.length} getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${n[0]}, ${n[1]}));
int index = resTexRC.x * ${n[1]} + resTexRC.y;
${o}
int b = index / ${s};
index -= b * ${s};
int r = 2 * (index / ${a});
int c = imod(index, ${a}) * 2;
return ivec${e.length}(${l});
}
`}function u9(e,t,r){if(r)return`
ivec4 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(outTexShape[0], outTexShape[1]));
int index = resTexRC.x * outTexShape[1] + resTexRC.y;
${bm(["r","c","d","d2"],e)}
return ivec4(r, c, d, d2);
}
`;let n=rl(["r","c","d","d2"],e);return`
ivec4 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
${n}
return ivec4(r, c, d, d2);
}
`}function p9(e,t){let r=rl(["r","c","d","d2","d3"],e);return`
ivec5 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx * vec2(${t[0]},
${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
${r}
ivec5 outShape = ivec5(r, c, d, d2, d3);
return outShape;
}
`}function d9(e,t){let r=rl(["r","c","d","d2","d3","d4"],e);return`
ivec6 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
${r}
ivec6 result = ivec6(r, c, d, d2, d3, d4);
return result;
}
`}function h9(e,t,r){let n=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];if(k.arraysEqual(e,t))return r?`
ivec2 getOutputCoords() {
ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));
return 2 * ivec2(resultUV.yx * vec2(packedTexShape[0], packedTexShape[1]));
}
`:`
ivec2 getOutputCoords() {
return 2 * ivec2(resultUV.yx * vec2(${n[0]}, ${n[1]}));
}
`;let a=Math.ceil(e[1]/2);return r?`
ivec2 getOutputCoords() {
ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));
int texelsInLogicalRow = int(ceil(float(outShape[1]) / 2.0));
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(packedTexShape[0], packedTexShape[1]));
int index = resTexRC.x * packedTexShape[1] + resTexRC.y;
int r = 2 * (index / texelsInLogicalRow);
int c = imod(index, texelsInLogicalRow) * 2;
return ivec2(r, c);
}
`:`
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${n[0]}, ${n[1]}));
int index = resTexRC.x * ${n[1]} + resTexRC.y;
int r = 2 * (index / ${a});
int c = imod(index, ${a}) * 2;
return ivec2(r, c);
}
`}function c9(e,t,r){return k.arraysEqual(e,t)?r?`
ivec2 getOutputCoords() {
return ivec2(resultUV.yx * vec2(outTexShape[0], outTexShape[1]));
}
`:`
ivec2 getOutputCoords() {
return ivec2(resultUV.yx * vec2(${t[0]}, ${t[1]}));
}
`:e[1]===1?r?`
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(outTexShape[0], outTexShape[1]));
int index = resTexRC.x * outTexShape[1] + resTexRC.y;
return ivec2(index, 0);
}
`:`
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
return ivec2(index, 0);
}
`:e[0]===1?r?`
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(outTexShape[0], outTexShape[1]));
int index = resTexRC.x * outTexShape[1] + resTexRC.y;
return ivec2(0, index);
}
`:`
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
return ivec2(0, index);
}
`:r?`
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(outTexShape[0], outTexShape[1]));
int index = resTexRC.x * outTexShape[1] + resTexRC.y;
int r = index / outShape[1];
int c = index - r * outShape[1];
return ivec2(r, c);
}
`:`
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
int r = index / ${e[1]};
int c = index - r * ${e[1]};
return ivec2(r, c);
}
`}function nl(e){return`offset${e}`}function f9(e){let t=e.name,r="get"+t.charAt(0).toUpperCase()+t.slice(1),n=Sr();return`
vec4 ${r}() {
return ${n.texture2D}(${t}, halfCR);
}
`}function m9(e,t){let r=e.name,n="get"+r.charAt(0).toUpperCase()+r.slice(1);if(e.shapeInfo.isUniform)return`float ${n}() {return ${r};}`;let[a,s]=e.shapeInfo.texShape;if(a===1&&s===1)return`
float ${n}() {
return sampleTexture(${r}, halfCR);
}
`;let i=nl(r);if(t)return`
float ${n}() {
vec2 uv = uvFromFlat(${r}TexShape[0], ${r}TexShape[1], ${i});
return sampleTexture(${r}, uv);
}
`;let[o,l]=e.shapeInfo.texShape;return`
float ${n}() {
vec2 uv = uvFromFlat(${o}, ${l}, ${i});
return sampleTexture(${r}, uv);
}
`}function g9(e,t){let r=e.name,n="get"+r.charAt(0).toUpperCase()+r.slice(1),a=e.shapeInfo.texShape,s=Sr();if(t)return`
vec4 ${n}(int index) {
ivec2 packedTexShape = ivec2(ceil(float(${r}TexShape[0]) / 2.0), ceil(float(${r}TexShape[1]) / 2.0));
vec2 uv = packedUVfrom1D(
packedTexShape[0], packedTexShape[1], index);
return ${s.texture2D}(${r}, uv);
}
`;let i=[Math.ceil(a[0]/2),Math.ceil(a[1]/2)];return`
vec4 ${n}(int index) {
vec2 uv = packedUVfrom1D(
${i[0]}, ${i[1]}, index);
return ${s.texture2D}(${r}, uv);
}
`}function y9(e,t){let r=e.name,n="get"+r.charAt(0).toUpperCase()+r.slice(1);if(e.shapeInfo.isUniform)return`
float ${n}(int index) {
${pp(e)}
}
`;let a=e.shapeInfo.texShape,s=a[0],i=a[1];if(i===1&&s===1)return`
float ${n}(int index) {
return sampleTexture(${r}, halfCR);
}
`;let o=nl(r);return i===1?t?`
float ${n}(int index) {
vec2 uv = vec2(0.5, (float(index + ${o}) + 0.5) / float(${r}TexShape[0]));
return sampleTexture(${r}, uv);
}
`:`
float ${n}(int index) {
vec2 uv = vec2(0.5, (float(index + ${o}) + 0.5) / ${s}.0);
return sampleTexture(${r}, uv);
}
`:s===1?t?`
float ${n}(int index) {
vec2 uv = vec2((float(index + ${o}) + 0.5) / float(${r}TexShape[1]), 0.5);
return sampleTexture(${r}, uv);
}
`:`
float ${n}(int index) {
vec2 uv = vec2((float(index + ${o}) + 0.5) / ${i}.0, 0.5);
return sampleTexture(${r}, uv);
}
`:t?`
float ${n}(int index) {
vec2 uv = uvFromFlat(${r}TexShape[0], ${r}TexShape[1], index + ${o});
return sampleTexture(${r}, uv);
}
`:`
float ${n}(int index) {
vec2 uv = uvFromFlat(${s}, ${i}, index + ${o});
return sampleTexture(${r}, uv);
}
`}function b9(e,t){let r=e.shapeInfo.logicalShape,n=e.name,a="get"+n.charAt(0).toUpperCase()+n.slice(1),s=e.shapeInfo.texShape,i=s[0],o=s[1],l=Sr();if(s!=null&&k.arraysEqual(r,s))return t?`
vec4 ${a}(int row, int col) {
vec2 uv = (vec2(col, row) + halfCR) / vec2(${n}TexShape[1], ${n}TexShape[0]);
return ${l.texture2D}(${n}, uv);
}
`:`
vec4 ${a}(int row, int col) {
vec2 uv = (vec2(col, row) + halfCR) / vec2(${o}.0, ${i}.0);
return ${l.texture2D}(${n}, uv);
}
`;if(t)return`
vec4 ${a}(int row, int col) {
ivec2 packedTexShape = ivec2(ceil(float(${n}TexShape[0]) / 2.0), ceil(float(${n}TexShape[1]) / 2.0));
int valuesPerRow = int(ceil(float(${n}Shape[1]) / 2.0));
vec2 uv = packedUVfrom2D(valuesPerRow, packedTexShape[0], packedTexShape[1], row, col);
return ${l.texture2D}(${n}, uv);
}
`;let p=[Math.ceil(s[0]/2),Math.ceil(s[1]/2)],u=Math.ceil(r[1]/2);return`
vec4 ${a}(int row, int col) {
vec2 uv = packedUVfrom2D(${u}, ${p[0]}, ${p[1]}, row, col);
return ${l.texture2D}(${n}, uv);
}
`}function x9(e,t){let r=e.shapeInfo.logicalShape,n=e.name,a="get"+n.charAt(0).toUpperCase()+n.slice(1),s=e.shapeInfo.texShape;if(s!=null&&k.arraysEqual(r,s)){if(t)return`
float ${a}(int row, int col) {
vec2 uv = (vec2(col, row) + halfCR) / vec2(${n}TexShape[1], ${n}TexShape[0]);
return sampleTexture(${n}, uv);
}
`;let h=s[0],c=s[1];return`
float ${a}(int row, int col) {
vec2 uv = (vec2(col, row) + halfCR) / vec2(${c}.0, ${h}.0);
return sampleTexture(${n}, uv);
}
`}let{newShape:i,keptDims:o}=k.squeezeShape(r),l=i;if(l.length<r.length){let h=dp(e,l),c=["row","col"];return`
${up(h,t)}
float ${a}(int row, int col) {
return ${a}(${hp(c,o)});
}
`}if(e.shapeInfo.isUniform)return`
float ${a}(int row, int col) {
int index = round(dot(vec2(row, col), vec2(${r[1]}, 1)));
${pp(e)}
}
`;let p=s[0],u=s[1],d=nl(n);return u===1?t?`
float ${a}(int row, int col) {
float index = dot(vec3(row, col, ${d}), vec3(${n}Shape[1], 1, 1));
vec2 uv = vec2(0.5, (index + 0.5) / float(${n}TexShape[0]));
return sampleTexture(${n}, uv);
}
`:`
float ${a}(int row, int col) {
float index = dot(vec3(row, col, ${d}), vec3(${r[1]}, 1, 1));
vec2 uv = vec2(0.5, (index + 0.5) / ${p}.0);
return sampleTexture(${n}, uv);
}
`:p===1?t?`
float ${a}(int row, int col) {
float index = dot(vec3(row, col, ${d}), vec3(${n}Shape[1], 1, 1));
vec2 uv = vec2((index + 0.5) / float(${n}TexShape[1]), 0.5);
return sampleTexture(${n}, uv);
}
`:`
float ${a}(int row, int col) {
float index = dot(vec3(row, col, ${d}), vec3(${r[1]}, 1, 1));
vec2 uv = vec2((index + 0.5) / ${u}.0, 0.5);
return sampleTexture(${n}, uv);
}
`:t?`
float ${a}(int row, int col) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${n}Shape[1] + col + ${d};
vec2 uv = uvFromFlat(${n}TexShape[0], ${n}TexShape[1], index);
return sampleTexture(${n}, uv);
}
`:`
float ${a}(int row, int col) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${r[1]} + col + ${d};
vec2 uv = uvFromFlat(${p}, ${u}, index);
return sampleTexture(${n}, uv);
}
`}function v9(e,t){let r=e.shapeInfo.logicalShape,n=e.name,a="get"+n.charAt(0).toUpperCase()+n.slice(1),s=e.shapeInfo.texShape,i=[Math.ceil(s[0]/2),Math.ceil(s[1]/2)];if(r[0]===1){let h=r.slice(1),c=[1,2],f=dp(e,h),m=["b","row","col"];return`
${tC(f,t)}
vec4 ${a}(int b, int row, int col) {
return ${a}(${hp(m,c)});
}
`}let o=Sr();if(t)return`
vec4 ${a}(int b, int row, int col) {
ivec2 packedTexShape = ivec2(ceil(float(${n}TexShape[0]) / 2.0), ceil(float(${n}TexShape[1]) / 2.0));
int valuesPerRow = int(ceil(float(${n}Shape[2]) / 2.0));
int texelsInBatch = valuesPerRow * int(ceil(float(${n}Shape[1]) / 2.0));
vec2 uv = packedUVfrom3D(
packedTexShape[0], packedTexShape[1], texelsInBatch, valuesPerRow, b, row, col);
return ${o.texture2D}(${n}, uv);
}
`;let l=i[0],p=i[1],u=Math.ceil(r[2]/2),d=u*Math.ceil(r[1]/2);return`
vec4 ${a}(int b, int row, int col) {
vec2 uv = packedUVfrom3D(
${l}, ${p}, ${d}, ${u}, b, row, col);
return ${o.texture2D}(${n}, uv);
}
`}function w9(e,t){let r=e.shapeInfo.logicalShape,n=e.name,a="get"+n.charAt(0).toUpperCase()+n.slice(1),s=r[1]*r[2],i=r[2],{newShape:o,keptDims:l}=k.squeezeShape(r),p=o;if(p.length<r.length){let m=dp(e,p),g=["row","col","depth"];return`
${up(m,t)}
float ${a}(int row, int col, int depth) {
return ${a}(${hp(g,l)});
}
`}if(e.shapeInfo.isUniform)return`
float ${a}(int row, int col, int depth) {
int index = round(dot(vec3(row, col, depth),
vec3(${s}, ${i}, 1)));
${pp(e)}
}
`;let u=e.shapeInfo.texShape,d=u[0],h=u[1],c=e.shapeInfo.flatOffset;if(h===s&&c==null)return t?`
float ${a}(int row, int col, int depth) {
int stride1 = ${n}Shape[2];
float texR = float(row);
float texC = dot(vec2(col, depth), vec2(stride1, 1));
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${n}TexShape[1], ${n}TexShape[0]);
return sampleTexture(${n}, uv);
}
`:`
float ${a}(int row, int col, int depth) {
float texR = float(row);
float texC = dot(vec2(col, depth), vec2(${i}, 1));
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${h}.0, ${d}.0);
return sampleTexture(${n}, uv);
}
`;if(h===i&&c==null)return t?`
float ${a}(int row, int col, int depth) {
float texR = dot(vec2(row, col), vec2(${n}Shape[1], 1));
float texC = float(depth);
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${n}TexShape[1], ${n}TexShape[0]);
return sampleTexture(${n}, uv);
}
`:`
float ${a}(int row, int col, int depth) {
float texR = dot(vec2(row, col), vec2(${r[1]}, 1));
float texC = float(depth);
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${h}.0, ${d}.0);
return sampleTexture(${n}, uv);
}
`;let f=nl(n);return t?`
float ${a}(int row, int col, int depth) {
// Explicitly use integer operations as dot() only works on floats.
int stride0 = ${n}Shape[1] * ${n}Shape[2];
int stride1 = ${n}Shape[2];
int index = row * stride0 + col * stride1 + depth + ${f};
vec2 uv = uvFromFlat(${n}TexShape[0], ${n}TexShape[1], index);
return sampleTexture(${n}, uv);
}
`:`
float ${a}(int row, int col, int depth) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${s} + col * ${i} + depth + ${f};
vec2 uv = uvFromFlat(${d}, ${h}, index);
return sampleTexture(${n}, uv);
}
`}function k9(e,t){let r=e.name,n="get"+r.charAt(0).toUpperCase()+r.slice(1),a=Sr();if(t)return`
vec4 ${n}(int b2, int b, int row, int col) {
int valuesPerRow = int(ceil(float(${r}Shape[3]) / 2.0));
int texelsInBatch = valuesPerRow * int(ceil(float(${r}Shape[2]) / 2.0));
int index = b * texelsInBatch + (row / 2) * valuesPerRow + (col / 2);
texelsInBatch *= ${r}Shape[1];
index = b2 * texelsInBatch + index;
ivec2 packedTexShape = ivec2(ceil(float(${r}TexShape[0]) / 2.0), ceil(float(${r}TexShape[1]) / 2.0));
int texR = index / packedTexShape[1];
int texC = index - texR * packedTexShape[1];
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(packedTexShape[1], packedTexShape[0]); return ${a.texture2D}(${r}, uv);
}
`;let s=e.shapeInfo.logicalShape,i=s.length,o=e.shapeInfo.texShape,l=[Math.ceil(o[0]/2),Math.ceil(o[1]/2)],p=l[0],u=l[1],d=Math.ceil(s[i-1]/2),h=d*Math.ceil(s[i-2]/2),c="int b, int row, int col",f=`b * ${h} + (row / 2) * ${d} + (col / 2)`;for(let m=2;m<i-1;m++)c=`int b${m}, `+c,h*=s[i-m-1],f=`b${m} * ${h} + `+f;return`
vec4 ${n}(${c}) {
int index = ${f};
int texR = index / ${u};
int texC = index - texR * ${u};
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${u}, ${p});
return ${a.texture2D}(${r}, uv);
}
`}function I9(e,t){let r=e.shapeInfo.logicalShape,n=e.name,a="get"+n.charAt(0).toUpperCase()+n.slice(1),s=r[3],i=r[2]*s,o=r[1]*i,{newShape:l,keptDims:p}=k.squeezeShape(r);if(l.length<r.length){let b=dp(e,l),x=["row","col","depth","depth2"];return`
${up(b,t)}
float ${a}(int row, int col, int depth, int depth2) {
return ${a}(${hp(x,p)});
}
`}if(e.shapeInfo.isUniform)return`
float ${a}(int row, int col, int depth, int depth2) {
int index = round(dot(vec4(row, col, depth, depth2),
vec4(${o}, ${i}, ${s}, 1)));
${pp(e)}
}
`;let u=e.shapeInfo.flatOffset,d=e.shapeInfo.texShape,h=d[0],c=d[1],f=`int stride2 = ${n}Shape[3];`,m=`int stride1 = ${n}Shape[2] * stride2;`,g=`int stride0 = ${n}Shape[1] * stride1;`;if(c===o&&u==null)return t?`
float ${a}(int row, int col, int depth, int depth2) {
${f}
${m}
float texR = float(row);
float texC =
dot(vec3(col, depth, depth2),
vec3(stride1, stride2, 1));
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${n}TexShape[1], ${n}TexShape[0]);
return sampleTexture(${n}, uv);
}
`:`
float ${a}(int row, int col, int depth, int depth2) {
float texR = float(row);
float texC =
dot(vec3(col, depth, depth2),
vec3(${i}, ${s}, 1));
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${c}.0, ${h}.0);
return sampleTexture(${n}, uv);
}
`;if(c===s&&u==null)return t?`
float ${a}(int row, int col, int depth, int depth2) {
float texR = dot(vec3(row, col, depth),
vec3(${n}Shape[1] * ${n}Shape[2], ${n}Shape[2], 1));
float texC = float(depth2);
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${n}TexShape[1], ${n}TexShape[0]);
return sampleTexture(${n}, uv);
}
`:`
float ${a}(int row, int col, int depth, int depth2) {
float texR = dot(vec3(row, col, depth),
vec3(${r[1]*r[2]}, ${r[2]}, 1));
float texC = float(depth2);
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${c}.0, ${h}.0);
return sampleTexture(${n}, uv);
}
`;let y=nl(n);return t?`
float ${a}(int row, int col, int depth, int depth2) {
// Explicitly use integer operations as dot() only works on floats.
${f}
${m}
${g}
int index = row * stride0 + col * stride1 +
depth * stride2 + depth2;
vec2 uv = uvFromFlat(${n}TexShape[0], ${n}TexShape[1], index + ${y});
return sampleTexture(${n}, uv);
}
`:`
float ${a}(int row, int col, int depth, int depth2) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${o} + col * ${i} +
depth * ${s} + depth2;
vec2 uv = uvFromFlat(${h}, ${c}, index + ${y});
return sampleTexture(${n}, uv);
}
`}function S9(e){let t=e.shapeInfo.logicalShape,r=e.name,n="get"+r.charAt(0).toUpperCase()+r.slice(1),a=t[4],s=t[3]*a,i=t[2]*s,o=t[1]*i,{newShape:l,keptDims:p}=k.squeezeShape(t);if(l.length<t.length){let m=dp(e,l),g=["row","col","depth","depth2","depth3"];return`
${up(m)}
float ${n}(int row, int col, int depth, int depth2, int depth3) {
return ${n}(${hp(g,p)});
}
`}if(e.shapeInfo.isUniform)return`
float ${n}(int row, int col, int depth, int depth2, int depth3) {
float index = dot(
vec4(row, col, depth, depth2),
vec4(${o}, ${i}, ${s}, ${a})) +
depth3;
${pp(e)}
}
`;let u=e.shapeInfo.flatOffset,d=e.shapeInfo.texShape,h=d[0],c=d[1];if(c===o&&u==null)return`
float ${n}(int row, int col, int depth, int depth2, int depth3) {
int texR = row;
float texC = dot(vec4(col, depth, depth2, depth3),
vec4(${i}, ${s}, ${a}, 1));
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${c}.0, ${h}.0);
return sampleTexture(${r}, uv);
}
`;if(c===a&&u==null)return`
float ${n}(int row, int col, int depth, int depth2, int depth3) {
float texR = dot(
vec4(row, col, depth, depth2),
vec4(${t[1]*t[2]*t[3]},
${t[2]*t[3]}, ${t[3]}, 1));
int texC = depth3;
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${c}.0, ${h}.0);
return sampleTexture(${r}, uv);
}
`;let f=nl(r);return`
float ${n}(int row, int col, int depth, int depth2, int depth3) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${o} + col * ${i} + depth * ${s} +
depth2 * ${a} + depth3 + ${f};
vec2 uv = uvFromFlat(${h}, ${c}, index);
return sampleTexture(${r}, uv);
}
`}function N9(e){let t=e.shapeInfo.logicalShape,r=e.name,n="get"+r.charAt(0).toUpperCase()+r.slice(1),{newShape:a,keptDims:s}=k.squeezeShape(t);if(a.length<t.length){let g=dp(e,a),y=["row","col","depth","depth2","depth3","depth4"];return`
${up(g)}
float ${n}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
return ${n}(${hp(y,s)});
}
`}let i=t[5],o=t[4]*i,l=t[3]*o,p=t[2]*l,u=t[1]*p;if(e.shapeInfo.isUniform)return`
float ${n}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
int index = round(dot(
vec4(row, col, depth, depth2),
vec4(${u}, ${p}, ${l}, ${o})) +
dot(
vec2(depth3, depth4),
vec2(${i}, 1)));
${pp(e)}
}
`;let d=e.shapeInfo.flatOffset,h=e.shapeInfo.texShape,c=h[0],f=h[1];if(f===u&&d==null)return`
float ${n}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
int texR = row;
float texC = dot(vec4(col, depth, depth2, depth3),
vec4(${p}, ${l}, ${o}, ${i})) +
float(depth4);
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${f}.0, ${c}.0);
return sampleTexture(${r}, uv);
}
`;if(f===i&&d==null)return`
float ${n}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
float texR = dot(vec4(row, col, depth, depth2),
vec4(${t[1]*t[2]*t[3]*t[4]},
${t[2]*t[3]*t[4]},
${t[3]*t[4]},
${t[4]})) + float(depth3);
int texC = depth4;
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${f}.0, ${c}.0);
return sampleTexture(${r}, uv);
}
`;let m=nl(r);return`
float ${n}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${u} + col * ${p} + depth * ${l} +
depth2 * ${o} + depth3 * ${i} + depth4 + ${m};
vec2 uv = uvFromFlat(${c}, ${f}, index);
return sampleTexture(${r}, uv);
}
`}function pp(e){let t=e.name,r=k.sizeFromShape(e.shapeInfo.logicalShape);return r<2?`return ${t};`:`
for (int i = 0; i < ${r}; i++) {
if (i == index) {
return ${t}[i];
}
}
`}function _9(e,t){let r=e.name,n=r.charAt(0).toUpperCase()+r.slice(1),a="get"+n+"AtOutCoords",s=e.shapeInfo.logicalShape.length,i=t.logicalShape.length,o=eC(e.shapeInfo.logicalShape,t.logicalShape),l=pt(i),p=i-s,u,d=["x","y","z","w","u","v"];s===0?u="":i<2&&o.length>=1?u="coords = 0;":u=o.map(g=>`coords.${d[g+p]} = 0;`).join(`
`);let h="";i<2&&s>0?h="coords":h=e.shapeInfo.logicalShape.map((g,y)=>`coords.${d[y+p]}`).join(", ");let c="return outputValue;",f=k.sizeFromShape(e.shapeInfo.logicalShape)===1,m=k.sizeFromShape(t.logicalShape)===1;if(s===1&&!f&&!m)c=`
return vec4(outputValue.xy, outputValue.xy);
`;else if(f&&!m)i===1?c=`
return vec4(outputValue.x, outputValue.x, 0., 0.);
`:c=`
return vec4(outputValue.x);
`;else if(o.length){let g=s-2,y=s-1;o.indexOf(g)>-1&&o.indexOf(y)>-1?c="return vec4(outputValue.x);":o.indexOf(g)>-1?c="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":o.indexOf(y)>-1&&(c="return vec4(outputValue.xx, outputValue.zz);")}return`
vec4 ${a}() {
${l} coords = getOutputCoords();
${u}
vec4 outputValue = get${n}(${h});
${c}
}
`}function T9(e,t){let r=e.name,n=r.charAt(0).toUpperCase()+r.slice(1),a="get"+n+"AtOutCoords",s=t.texShape,i=e.shapeInfo.texShape,o=e.shapeInfo.logicalShape.length,l=t.logicalShape.length;if(!e.shapeInfo.isUniform&&o===l&&e.shapeInfo.flatOffset==null&&k.arraysEqual(i,s))return`
float ${a}() {
return sampleTexture(${r}, resultUV);
}
`;let p=pt(l),u=eC(e.shapeInfo.logicalShape,t.logicalShape),d=l-o,h,c=["x","y","z","w","u","v"];o===0?h="":l<2&&u.length>=1?h="coords = 0;":h=u.map(m=>`coords.${c[m+d]} = 0;`).join(`
`);let f="";return l<2&&o>0?f="coords":f=e.shapeInfo.logicalShape.map((m,g)=>`coords.${c[g+d]}`).join(", "),`
float ${a}() {
${p} coords = getOutputCoords();
${h}
return get${n}(${f});
}
`}function pt(e){if(e<=1)return"int";if(e===2)return"ivec2";if(e===3)return"ivec3";if(e===4)return"ivec4";if(e===5)return"ivec5";if(e===6)return"ivec6";throw Error(`GPU for rank ${e} is not yet supported`)}function rw(e,t,r){let{newShape:n,keptDims:a}=k.squeezeShape(t),s=t.length,i=e&&s===3&&t[0]===1,o=i?t.slice(1):n,l=!e&&s>1&&!k.arraysEqual(t,r)&&n.length<s||i;return{useSqueezeShape:l,uniformShape:l?o:t,keptDims:a}}function dp(e,t){let r=JSON.parse(JSON.stringify(e));return r.shapeInfo.logicalShape=t,r}function hp(e,t){return t.map(r=>e[r]).join(", ")}function C9(e,t,r,n){let a=r.map((u,d)=>{let h={logicalShape:u.shape,texShape:u.isUniform?null:u.texData.texShape,isUniform:u.isUniform,isPacked:u.isUniform?!1:u.texData.isPacked,flatOffset:null};return u.texData!=null&&u.texData.slice!=null&&u.texData.slice.flatOffset>0&&(h.flatOffset=u.texData.slice.flatOffset),{name:t.variableNames[d],shapeInfo:h}}),s=a.map(u=>u.shapeInfo),i={logicalShape:n.shape,texShape:n.texData.texShape,isUniform:!1,isPacked:n.texData.isPacked,flatOffset:null},o=jJ(a,i,t),l=FT(e.gl,o),p=e.createProgram(l);return j().get("ENGINE_COMPILE_ONLY")?{program:t,fragmentShader:l,source:o,webGLProgram:p,inShapeInfos:s,outShapeInfo:i,variablesLocations:null,customUniformLocations:null,infLoc:null,nanLoc:null,outShapeLocation:null,outShapeStridesLocation:null,outTexShapeLocation:null}:(e.buildVao(p),Object.assign({program:t,fragmentShader:l,source:o,webGLProgram:p,inShapeInfos:s,outShapeInfo:i},nC(e,t,p)))}function nC(e,t,r){let n=[],a=[],s,i,o,l=null,p=null;p=e.getUniformLocation(r,"NAN",!1),j().getNumber("WEBGL_VERSION")===1&&(l=e.getUniformLocation(r,"INFINITY",!1));let u=!1;for(let d of t.variableNames){let h={name:d,uniform:e.getUniformLocation(r,d,u),offset:e.getUniformLocation(r,`offset${d}`,u)};t.enableShapeUniforms&&(h.shape=e.getUniformLocation(r,`${d}Shape`,u),h.texShape=e.getUniformLocation(r,`${d}TexShape`,u)),n.push(h)}if(t.enableShapeUniforms&&(s=e.getUniformLocation(r,"outShape",u),o=e.getUniformLocation(r,"outShapeStrides",u),i=e.getUniformLocation(r,"outTexShape",u)),t.customUniforms)for(let d of t.customUniforms)a.push(e.getUniformLocation(r,d.name,u));return{variablesLocations:n,customUniformLocations:a,infLoc:l,nanLoc:p,outShapeLocation:s,outShapeStridesLocation:o,outTexShapeLocation:i}}function g1(e,t){if(e.length!==t.length)throw Error(`Binary was compiled with ${e.length} inputs, but was executed with ${t.length} inputs`);e.forEach((r,n)=>{let a=r.logicalShape,s=t[n],i=s.shape;if(!k.arraysEqual(a,i))throw Error(`Binary was compiled with different shapes than the current args. Shapes ${a} and ${i} must match`);if(r.isUniform&&s.isUniform)return;let o=r.texShape,l=s.isUniform?null:s.texData.texShape;if(!k.arraysEqual(o,l))throw Error(`Binary was compiled with different texture shapes than the current args. Shape ${o} and ${l} must match`)})}function E9(e,t,r,n,a){t.program.enableShapeUniforms||(g1(t.inShapeInfos,r),g1([t.outShapeInfo],[n]));let s=n.texData.texture,i=n.texData.texShape;n.texData.isPacked?e.setOutputPackedMatrixTexture(s.texture,i[0],i[1]):e.setOutputMatrixTexture(s.texture,i[0],i[1]),e.setProgram(t.webGLProgram),e.bindVertexArray(t.webGLProgram.vao),j().getNumber("WEBGL_VERSION")===1&&t.infLoc!==null&&e.gl.uniform1f(t.infLoc,1/0),t.nanLoc!==null&&e.gl.uniform1f(t.nanLoc,NaN);for(let l=0;l<r.length;++l){let p=r[l],{uniform:u,offset:d,shape:h,texShape:c}=t.variablesLocations[l];if(h){let{uniformShape:f}=rw(t.program.packedInputs,p.shape,p.texData.texShape);switch(f.length){case 1:e.gl.uniform1iv(h,new Int32Array(f));break;case 2:e.gl.uniform2iv(h,new Int32Array(f));break;case 3:e.gl.uniform3iv(h,new Int32Array(f));break;case 4:e.gl.uniform4iv(h,new Int32Array(f));break}}if(c&&e.gl.uniform2i(c,p.texData.texShape[0],p.texData.texShape[1]),u!=null){if(p.isUniform){if(k.sizeFromShape(p.shape)<2)e.gl.uniform1f(u,p.uniformValues[0]);else{let f=p.uniformValues;f instanceof Float32Array||(f=new Float32Array(f)),e.gl.uniform1fv(u,f)}continue}p.texData.slice!=null&&d!=null&&e.gl.uniform1i(d,p.texData.slice.flatOffset),e.setInputMatrixTexture(p.texData.texture.texture,u,l)}}let o=t.outShapeLocation;if(o)switch(n.shape.length){case 1:e.gl.uniform1iv(o,new Int32Array(n.shape));break;case 2:e.gl.uniform2iv(o,new Int32Array(n.shape));break;case 3:e.gl.uniform3iv(o,new Int32Array(n.shape));break;case 4:e.gl.uniform4iv(o,new Int32Array(n.shape));break}if(t.outShapeStridesLocation){let l=k.computeStrides(n.shape);switch(n.shape.length){case 2:e.gl.uniform1iv(t.outShapeStridesLocation,new Int32Array(l));break;case 3:e.gl.uniform2iv(t.outShapeStridesLocation,new Int32Array(l));break;case 4:e.gl.uniform3iv(t.outShapeStridesLocation,new Int32Array(l));break}}if(t.outTexShapeLocation&&e.gl.uniform2i(t.outTexShapeLocation,n.texData.texShape[0],n.texData.texShape[1]),t.program.customUniforms&&a)for(let l=0;l<t.program.customUniforms.length;++l){let p=t.program.customUniforms[l],u=t.customUniformLocations[l],d=a[l];if(p.type==="float")e.gl.uniform1fv(u,d);else if(p.type==="vec2")e.gl.uniform2fv(u,d);else if(p.type==="vec3")e.gl.uniform3fv(u,d);else if(p.type==="vec4")e.gl.uniform4fv(u,d);else if(p.type==="int")e.gl.uniform1iv(u,d);else if(p.type==="ivec2")e.gl.uniform2iv(u,d);else if(p.type==="ivec3")e.gl.uniform3iv(u,d);else if(p.type==="ivec4")e.gl.uniform4iv(u,d);else throw Error(`uniform type ${p.type} is not supported yet.`)}e.executeProgram()}function $9(e,t,r){let n="";t.concat(r).forEach(i=>{let o=i.texData!=null&&i.texData.slice!=null&&i.texData.slice.flatOffset>0;if(e.enableShapeUniforms&&!i.isUniform){let l=i.texData.texShape,{useSqueezeShape:p,uniformShape:u,keptDims:d}=rw(e.packedInputs,i.shape,l),h="",c="",f="";if(u.length===1&&e.packedInputs){let w=[Math.ceil(l[0]/2),Math.ceil(l[1]/2)];h=`${w[0]>1}_${w[1]>1}`}else if(u.length===2&&!e.packedInputs)c=`${u[0]>1}_${u[1]>1}`;else if(u.length>2&&!e.packedInputs){let w=k.computeStrides(u);f=`${w[0]===l[1]}_${w[w.length-1]===l[1]}`}let m=i.shape.length,g=u.length===2&&k.arraysEqual(i.shape,l),y=k.sizeFromShape(i.shape)===1,b=_.getBroadcastDims(i.shape,r.shape),x=!e.packedInputs&&m===r.shape.length&&k.arraysEqual(l,r.texData.texShape),v=e.packedInputs||u.length>2?"":`${l[0]>1}_${l[1]>1}`;n+=`${m}_${x}_${p?d:""}_${u.length}_${y}_${b}_${g}_${h}_${c}_${f}_${v}_${o}`}else{let l=i.isUniform?"uniform":i.texData.texShape;n+=`${i.shape}_${l}_${o}`}});let a=e.userCode,s=e.constructor.name;return s+="_"+n+"_"+a+`${j().getNumber("WEBGL_VERSION")}`,s}function hr(e){return j().getBool("WEBGL_USE_SHAPES_UNIFORMS")&&e<=4}var A9=class{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=ad.DENSE,this.customUniforms=[{name:"texShape",type:"ivec2"}];let t=Sr();this.outputShape=e,this.enableShapeUniforms=hr(this.outputShape.length),this.userCode=`
ivec3 outCoordsFromFlatIndex(int index) {
${this.enableShapeUniforms?bm(["r","c","d"],e):rl(["r","c","d"],e)}
return ivec3(r, c, d);
}
void main() {
ivec2 resTexRC = ivec2(resultUV.yx * vec2(texShape[0], texShape[1]));
int index = 4 * (resTexRC.x * texShape[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);
}
${t.output} = result;
}
`}},F9=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=ad.DENSE,this.customUniforms=[{name:"texShape",type:"ivec2"}];let t=Sr();this.outputShape=e,this.enableShapeUniforms=hr(this.outputShape.length),this.userCode=`
ivec3 outCoordsFromFlatIndex(int index) {
${this.enableShapeUniforms?bm(["r","c","d"],e):rl(["r","c","d"],e)}
return ivec3(r, c, d);
}
void main() {
ivec2 resTexRC = ivec2(resultUV.yx * vec2(texShape[0], texShape[1]));
int index = 4 * (resTexRC.x * texShape[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));
}
${t.output} = result;
}
`}},R9=class{constructor(e){this.variableNames=["A"],this.outTexUsage=on.DOWNLOAD;let t=Sr();this.outputShape=e,this.userCode=`
${QT}
void main() {
float x = getAAtOutCoords();
${t.output} = encode_float(x);
}
`}},D9=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=on.DOWNLOAD;let t=Sr();this.outputShape=e,this.userCode=`
${QT}
void main() {
ivec3 coords = getOutputCoords();
float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));
${t.output} = encode_float(x);
}
`}},M9={R:0,G:1,B:2,A:3},y1=class{constructor(e,t=!1,r="RGBA"){this.variableNames=["A"],this.customUniforms=[{name:"texShape",type:"ivec2"}];let n=Sr();this.outputShape=e,this.enableShapeUniforms=hr(this.outputShape.length);let a="result";t&&(a="floor(result * 255. + 0.5)");let s="";for(let i=0;i<r.length;i++){let o=r[i];s+=`
if(offset == ${i}) {
result = values[${M9[o]}];
}`}this.userCode=`
${this.enableShapeUniforms?tw():ew(e)}
void main() {
ivec3 coords = getOutputCoords();
int flatIndex = getFlatIndex(coords);
float result = 0.;
int offset = imod(flatIndex, ${r.length});
flatIndex = idiv(flatIndex, ${r.length}, 1.);
int r = flatIndex / texShape[1];
if (r < texShape[0]) {
int c = imod(flatIndex, texShape[1]);
vec2 uv = (vec2(c, r) + halfCR) / vec2(texShape[1], texShape[0]);
vec4 values = ${n.texture2D}(A, uv);
${s}
}
${n.output} = vec4(${a}, 0., 0., 0.);
}
`}},O9=class{constructor(e,t=!1){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.customUniforms=[{name:"texShape",type:"ivec2"}];let r=Sr();this.outputShape=e,this.enableShapeUniforms=hr(this.outputShape.length);let n="",a="result";t&&(a="floor(result * 255. + 0.5)");for(let s=0;s<=1;s++)for(let i=0;i<=1;i++){let o=s*2+i;n+=`
localCoords = coords;
if(localCoords[2] + ${i} < ${this.enableShapeUniforms?"outShape[2]":`${e[2]}`}) {
localCoords[2] += ${i};
if (localCoords[1] + ${s} < ${this.enableShapeUniforms?"outShape[1]":`${e[1]}`}) {
localCoords[1] += ${s};
flatIndex = getFlatIndex(localCoords);
offset = imod(flatIndex, 4);
flatIndex = idiv(flatIndex, 4, 1.);
int r = flatIndex / texShape[1];
int c = imod(flatIndex, texShape[1]);
vec2 uv = (vec2(c, r) + halfCR) / vec2(texShape[1], texShape[0]);
values = ${r.texture2D}(A, uv);
if (offset == 0) {
result[${o}] = values[0];
} else if (offset == 1) {
result[${o}] = values[1];
} else if (offset == 2) {
result[${o}] = values[2];
} else {
result[${o}] = values[3];
}
}
}
`}this.userCode=`
${this.enableShapeUniforms?tw():ew(e)}
void main() {
ivec3 coords = getOutputCoords();
vec4 result = vec4(0.);
int flatIndex, r, c, offset;
ivec3 localCoords;
vec2 uv;
vec4 values;
${n}
${r.output} = ${a};
}
`}},aC={};Ee(aC,{bindVertexProgramAttributeStreams:()=>cC,createBufferFromOutputTexture:()=>gC,createFloat16MatrixTexture:()=>uC,createFloat16PackedMatrixTexture:()=>hC,createFloat32MatrixTexture:()=>lC,createIndexBuffer:()=>oC,createPackedMatrixTexture:()=>dC,createUnsignedBytesMatrixTexture:()=>pC,createVertexBuffer:()=>iC,createVertexShader:()=>sC,downloadByteEncodedFloatMatrixFromOutputTexture:()=>bC,downloadFloat32MatrixFromBuffer:()=>yC,downloadMatrixFromPackedOutputTexture:()=>vC,downloadPackedMatrixFromBuffer:()=>xC,getInternalFormatForFloat16MatrixTexture:()=>aw,getInternalFormatForFloat16PackedMatrixTexture:()=>ow,getInternalFormatForFloat32MatrixTexture:()=>nw,getInternalFormatForPackedMatrixTexture:()=>iw,getInternalFormatForUnsignedBytesMatrixTexture:()=>sw,uploadDenseMatrixToTexture:()=>fC,uploadPixelDataToTexture:()=>mC});function sC(e){let t=Sr(),r=`${t.version}
precision highp float;
${t.attribute} vec3 clipSpacePos;
${t.attribute} vec2 uv;
${t.varyingVs} vec2 resultUV;
void main() {
gl_Position = vec4(clipSpacePos, 1);
resultUV = uv;
}`;return AT(e,r)}function iC(e){let t=new Float32Array([-1,1,0,0,1,-1,-1,0,0,0,1,1,0,1,1,1,-1,0,1,0]);return MT(e,t)}function oC(e){let t=new Uint16Array([0,1,2,2,1,3]);return OT(e,t)}function uh(e,t,r,n,a,s){zT(t,r);let i=LT(e),o=e.TEXTURE_2D;return pe(e,()=>e.bindTexture(o,i)),pe(e,()=>e.texParameteri(o,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE)),pe(e,()=>e.texParameteri(o,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)),pe(e,()=>e.texParameteri(o,e.TEXTURE_MIN_FILTER,e.NEAREST)),pe(e,()=>e.texParameteri(o,e.TEXTURE_MAG_FILTER,e.NEAREST)),j().getNumber("WEBGL_VERSION")===1?pe(e,()=>e.texImage2D(o,0,n,t,r,0,a,s,null)):pe(e,()=>e.texStorage2D(o,1,n,t,r)),pe(e,()=>e.bindTexture(e.TEXTURE_2D,null)),{texture:i,texShape:[r,t]}}function nw(e){return e.internalFormatFloat}function lC(e,t,r,n){let[a,s]=lh(t,r);return uh(e,a,s,nw(n),n.textureFormatFloat,e.FLOAT)}function aw(e){return e.internalFormatHalfFloat}function uC(e,t,r,n){let[a,s]=lh(t,r);return uh(e,a,s,aw(n),n.textureFormatFloat,n.textureTypeHalfFloat)}function sw(e){return e.downloadTextureFormat}function pC(e,t,r,n){let[a,s]=lh(t,r);return uh(e,a,s,sw(n),e.RGBA,e.UNSIGNED_BYTE)}function iw(e){return e.internalFormatPackedFloat}function dC(e,t,r,n){let[a,s]=op(t,r);return uh(e,a,s,iw(n),e.RGBA,e.FLOAT)}function ow(e){return e.internalFormatPackedHalfFloat}function hC(e,t,r,n){let[a,s]=op(t,r);return uh(e,a,s,ow(n),e.RGBA,n.textureTypeHalfFloat)}function cC(e,t,r){return pe(e,()=>e.bindBuffer(e.ARRAY_BUFFER,r)),qg(e,t,"clipSpacePos",r,3,20,0)&&qg(e,t,"uv",r,2,20,12)}function fC(e,t,r,n,a,s){pe(e,()=>e.bindTexture(e.TEXTURE_2D,t));let i,o,l;a instanceof Uint8Array?(i=new Uint8Array(r*n*4),o=e.UNSIGNED_BYTE,l=e.RGBA):(i=new Float32Array(r*n*4),o=e.FLOAT,l=s.internalFormatPackedFloat),i.set(a),j().getNumber("WEBGL_VERSION")===2?pe(e,()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,r,n,e.RGBA,o,i)):pe(e,()=>e.texImage2D(e.TEXTURE_2D,0,l,r,n,0,e.RGBA,o,i)),pe(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function mC(e,t,r){pe(e,()=>e.bindTexture(e.TEXTURE_2D,t)),r.data instanceof Uint8Array?j().getNumber("WEBGL_VERSION")===2?pe(e,()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,r.width,r.height,e.RGBA,e.UNSIGNED_BYTE,r.data)):pe(e,()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,r.width,r.height,0,e.RGBA,e.UNSIGNED_BYTE,r.data)):j().getNumber("WEBGL_VERSION")===2?pe(e,()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,e.RGBA,e.UNSIGNED_BYTE,r)):pe(e,()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,r)),pe(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function gC(e,t,r,n){let a=e.createBuffer();pe(e,()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,a));let s=4*4*t*r;return pe(e,()=>e.bufferData(e.PIXEL_PACK_BUFFER,s,e.STREAM_READ)),pe(e,()=>e.readPixels(0,0,r,t,e.RGBA,e.FLOAT,0)),pe(e,()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,null)),a}function yC(e,t,r){let n=e,a=new Float32Array(r);return n.bindBuffer(n.PIXEL_PACK_BUFFER,t),n.getBufferSubData(n.PIXEL_PACK_BUFFER,0,a),n.bindBuffer(n.PIXEL_PACK_BUFFER,null),a}function bC(e,t,r,n){let[a,s]=lh(t,r),i=4,o=new Uint8Array(FJ(t*r,i));return pe(e,()=>e.readPixels(0,0,a,s,n.downloadTextureFormat,e.UNSIGNED_BYTE,o)),new Float32Array(o.buffer)}function xC(e,t,r,n,a,s,i,o){let l=e,p=new Float32Array(RJ(s,i));return l.bindBuffer(l.PIXEL_PACK_BUFFER,t),l.getBufferSubData(l.PIXEL_PACK_BUFFER,0,p),l.bindBuffer(l.PIXEL_PACK_BUFFER,null),p}function vC(e,t,r){let n=new Float32Array(t*r*4);return pe(e,()=>e.readPixels(0,0,r,t,e.RGBA,e.FLOAT,n)),n}var rc=class{constructor(e){this.outputTexture=null,this.program=null,this.disposed=!1,this.itemsToPoll=[];let t=j().getNumber("WEBGL_VERSION");if(e!=null?(this.gl=e,CT(t,e)):this.gl=Vn(t),e=this.gl,j().getNumber("WEBGL_VERSION")===2){let a=e;this.createVertexArray=()=>pe(a,()=>a.createVertexArray()),this.bindVertexArray=s=>pe(a,()=>a.bindVertexArray(s)),this.deleteVertexArray=s=>pe(a,()=>a.deleteVertexArray(s)),this.getVertexArray=()=>pe(a,()=>a.getParameter(a.VERTEX_ARRAY_BINDING))}else if(e!=null){let a=e.getExtension("OES_vertex_array_object");if(a==null)throw new Error("All WebGL1 implementations are expected to offer OES_vertex_array_object.");this.createVertexArray=()=>pe(e,()=>a.createVertexArrayOES()),this.bindVertexArray=s=>pe(e,()=>a.bindVertexArrayOES(s)),this.deleteVertexArray=s=>pe(e,()=>a.deleteVertexArrayOES(s)),this.getVertexArray=()=>pe(e,()=>e.getParameter(a.VERTEX_ARRAY_BINDING_OES))}let r="WEBGL_color_buffer_float",n="EXT_color_buffer_half_float";if(this.parallelCompilationExtension=this.gl.getExtension("KHR_parallel_shader_compile"),j().getNumber("WEBGL_VERSION")===1){let a="OES_texture_float",s="OES_texture_half_float";if(this.textureFloatExtension=Rp(this.gl,a),ln(this.gl,s))this.textureHalfFloatExtension=Rp(this.gl,s);else if(j().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(r),ln(this.gl,n))this.colorBufferHalfFloatExtension=Rp(this.gl,n);else if(j().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(r="EXT_color_buffer_float",ln(this.gl,r))this.colorBufferFloatExtension=this.gl.getExtension(r);else if(ln(this.gl,n))this.colorBufferHalfFloatExtension=this.gl.getExtension(n);else throw new Error("GL context does not support color renderable floats");this.vertexBuffer=iC(this.gl),this.indexBuffer=oC(this.gl),this.framebuffer=PT(this.gl),this.textureConfig=Yv(this.gl,this.textureHalfFloatExtension)}get debug(){return j().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;pe(e,()=>e.finish()),pe(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,null)),pe(e,()=>e.deleteFramebuffer(this.framebuffer)),pe(e,()=>e.bindBuffer(e.ARRAY_BUFFER,null)),pe(e,()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null)),pe(e,()=>e.deleteBuffer(this.indexBuffer)),this.disposed=!0}createFloat32MatrixTexture(e,t){return this.throwIfDisposed(),lC(this.gl,e,t,this.textureConfig)}createFloat16MatrixTexture(e,t){return this.throwIfDisposed(),uC(this.gl,e,t,this.textureConfig)}createUnsignedBytesMatrixTexture(e,t){return this.throwIfDisposed(),pC(this.gl,e,t,this.textureConfig)}uploadPixelDataToTexture(e,t){this.throwIfDisposed(),mC(this.gl,e,t)}uploadDenseMatrixToTexture(e,t,r,n){this.throwIfDisposed(),fC(this.gl,e,t,r,n,this.textureConfig)}createFloat16PackedMatrixTexture(e,t){return this.throwIfDisposed(),hC(this.gl,e,t,this.textureConfig)}createPackedMatrixTexture(e,t){return this.throwIfDisposed(),dC(this.gl,e,t,this.textureConfig)}deleteMatrixTexture(e){this.throwIfDisposed(),this.outputTexture===e&&(Kg(this.gl,this.framebuffer),this.outputTexture=null),pe(this.gl,()=>this.gl.deleteTexture(e))}downloadByteEncodedFloatMatrixFromOutputTexture(e,t,r){return this.downloadMatrixDriver(e,()=>bC(this.gl,t,r,this.textureConfig))}downloadPackedMatrixFromBuffer(e,t,r,n,a,s){return xC(this.gl,e,t,r,n,a,s,this.textureConfig)}downloadFloat32MatrixFromBuffer(e,t){return yC(this.gl,e,t)}createBufferFromTexture(e,t,r){this.bindTextureToFrameBuffer(e);let n=gC(this.gl,t,r,this.textureConfig);return this.unbindTextureToFrameBuffer(),n}createAndWaitForFence(){let e=this.createFence(this.gl);return this.pollFence(e)}createFence(e){let t,r;if(j().getBool("WEBGL_FENCE_API_ENABLED")){let n=e,a=n.fenceSync(n.SYNC_GPU_COMMANDS_COMPLETE,0);e.flush(),r=()=>{let s=n.clientWaitSync(a,0,0);return s===n.ALREADY_SIGNALED||s===n.CONDITION_SATISFIED},t=a}else j().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(t=this.beginQuery(),this.endQuery(),r=()=>this.isQueryAvailable(t,j().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))):r=()=>!0;return{query:t,isFencePassed:r}}downloadMatrixFromPackedTexture(e,t,r){return this.downloadMatrixDriver(e,()=>vC(this.gl,t,r))}createProgram(e){this.throwIfDisposed();let t=this.gl;this.vertexShader==null&&(this.vertexShader=sC(t));let r=RT(t);pe(t,()=>t.attachShader(r,this.vertexShader)),pe(t,()=>t.attachShader(r,e)),DT(t,r);let n=Object.assign(r,{vao:this.createVertexArray()});return this.debug&&Yh(t,n),n}buildVao(e){this.setProgram(e),this.bindVertexArray(e.vao);let t=this.gl;pe(t,()=>t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.indexBuffer)),cC(t,e,this.vertexBuffer)}deleteProgram(e){this.throwIfDisposed(),e===this.program&&(this.program=null),e!=null&&(pe(this.gl,()=>this.gl.deleteProgram(e)),this.deleteVertexArray(e.vao))}setProgram(e){this.throwIfDisposed(),this.program=e,this.program!=null&&this.debug&&Yh(this.gl,this.program),pe(this.gl,()=>this.gl.useProgram(e))}getUniformLocation(e,t,r=!0){return this.throwIfDisposed(),r?WT(this.gl,e,t):UT(this.gl,e,t)}getAttributeLocation(e,t){return this.throwIfDisposed(),pe(this.gl,()=>this.gl.getAttribLocation(e,t))}getUniformLocationNoThrow(e,t){return this.throwIfDisposed(),this.gl.getUniformLocation(e,t)}setInputMatrixTexture(e,t,r){this.throwIfDisposed(),this.throwIfNoProgram(),VT(this.gl,e,t,r)}setOutputMatrixTexture(e,t,r){this.setOutputMatrixTextureDriver(e,r,t)}setOutputPackedMatrixTexture(e,t,r){this.throwIfDisposed();let[n,a]=op(t,r);this.setOutputMatrixTextureDriver(e,n,a)}setOutputMatrixWriteRegion(e,t,r,n){this.setOutputMatrixWriteRegionDriver(r,e,n,t)}setOutputPackedMatrixWriteRegion(e,t,r,n){throw new Error("setOutputPackedMatrixWriteRegion not implemented.")}debugValidate(){this.program!=null&&Yh(this.gl,this.program),Dp(this.gl)}executeProgram(){this.throwIfDisposed(),this.throwIfNoProgram();let e=this.gl;if(this.debug){let t=this.getVertexArray();console.assert(t===this.program.vao,"VAO changed between setProgram and executeProgram!"),this.debugValidate()}pe(e,()=>e.drawElements(e.TRIANGLES,6,e.UNSIGNED_SHORT,0))}blockUntilAllProgramsCompleted(){this.throwIfDisposed(),pe(this.gl,()=>this.gl.finish())}getQueryTimerExtension(){return this.disjointQueryTimerExtension==null&&(this.disjointQueryTimerExtension=Rp(this.gl,j().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(j().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2){let r=this.gl,n=this.getQueryTimerExtensionWebGL2(),a=r.createQuery();return r.beginQuery(n.TIME_ELAPSED_EXT,a),a}let e=this.getQueryTimerExtensionWebGL1(),t=e.createQueryEXT();return e.beginQueryEXT(e.TIME_ELAPSED_EXT,t),t}endQuery(){if(j().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2){let t=this.gl,r=this.getQueryTimerExtensionWebGL2();t.endQuery(r.TIME_ELAPSED_EXT);return}let e=this.getQueryTimerExtensionWebGL1();e.endQueryEXT(e.TIME_ELAPSED_EXT)}async waitForQueryAndGetTime(e){return await k.repeatedTry(()=>this.disposed||this.isQueryAvailable(e,j().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))),this.getQueryTime(e,j().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))}getQueryTime(e,t){if(t===0)return null;if(t===2){let r=this.gl;return r.getQueryParameter(e,r.QUERY_RESULT)/1e6}else{let r=this.getQueryTimerExtensionWebGL1();return r.getQueryObjectEXT(e,r.QUERY_RESULT_EXT)/1e6}}isQueryAvailable(e,t){if(t===0)return!0;if(t===2){let r=this.gl,n=this.getQueryTimerExtensionWebGL2(),a=r.getQueryParameter(e,r.QUERY_RESULT_AVAILABLE);return this.disjoint==null&&(this.disjoint=this.gl.getParameter(n.GPU_DISJOINT_EXT)),a&&!this.disjoint}else{let r=this.getQueryTimerExtensionWebGL1(),n=r.getQueryObjectEXT(e,r.QUERY_RESULT_AVAILABLE_EXT);return this.disjoint==null&&(this.disjoint=this.gl.getParameter(r.GPU_DISJOINT_EXT)),n&&!this.disjoint}}pollFence(e){return new Promise(t=>{this.addItemToPoll(()=>e.isFencePassed(),()=>t())})}pollItems(){let e=L9(this.itemsToPoll.map(t=>t.isDoneFn));for(let t=0;t<=e;++t){let{resolveFn:r}=this.itemsToPoll[t];r()}this.itemsToPoll=this.itemsToPoll.slice(e+1)}addItemToPoll(e,t){if(this.itemsToPoll.push({isDoneFn:e,resolveFn:t}),this.itemsToPoll.length>1)return;let r;"setTimeoutCustom"in j().platform&&(r=j().platform.setTimeoutCustom.bind(j().platform)),k.repeatedTry(()=>(this.pollItems(),this.itemsToPoll.length===0),()=>0,null,r)}bindTextureToFrameBuffer(e){this.throwIfDisposed(),Qh(this.gl,e,this.framebuffer),this.debug&&Dp(this.gl)}unbindTextureToFrameBuffer(){this.outputTexture!=null?(Qh(this.gl,this.outputTexture,this.framebuffer),this.debug&&Dp(this.gl)):Kg(this.gl,this.framebuffer)}downloadMatrixDriver(e,t){this.bindTextureToFrameBuffer(e);let r=t();return this.unbindTextureToFrameBuffer(),r}setOutputMatrixTextureDriver(e,t,r){this.throwIfDisposed();let n=this.gl;Qh(n,e,this.framebuffer),this.debug&&Dp(n),this.outputTexture=e,pe(n,()=>n.viewport(0,0,t,r)),pe(n,()=>n.scissor(0,0,t,r))}setOutputMatrixWriteRegionDriver(e,t,r,n){this.throwIfDisposed(),pe(this.gl,()=>this.gl.scissor(e,t,r,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 L9(e){let t=0;for(;t<e.length&&e[t]();++t);return t-1}var{addImpl:z9,bincountImpl:wC,bincountReduceImpl:P9,bitwiseAndImpl:B9,castImpl:W9,ceilImpl:U9,concatImpl:V9,equalImpl:G9,expImpl:H9,expm1Impl:j9,floorImpl:q9,gatherNdImpl:K9,gatherV2Impl:X9,greaterImpl:Z9,greaterEqualImpl:J9,lessImpl:Y9,lessEqualImpl:Q9,linSpaceImpl:eY,logImpl:tY,maxImpl:rY,maximumImpl:nY,minimumImpl:aY,multiplyImpl:sY,negImpl:iY,notEqualImpl:oY,prodImpl:lY,raggedGatherImpl:uY,raggedRangeImpl:pY,raggedTensorToTensorImpl:dY,rangeImpl:hY,rsqrtImpl:cY,scatterImpl:fY,sigmoidImpl:mY,simpleAbsImpl:kC,sliceImpl:gY,sparseFillEmptyRowsImpl:yY,sparseReshapeImpl:bY,sparseSegmentReductionImpl:IC,sqrtImpl:xY,staticRegexReplaceImpl:vY,stridedSliceImpl:wY,stringNGramsImpl:kY,stringSplitImpl:IY,stringToHashBucketFastImpl:SY,subImpl:NY,tileImpl:_Y,topKImpl:TY,transposeImpl:lw,uniqueImpl:CY}=Ov;function SC(e,t){return["x","y","z","w","u","v"].slice(0,t).map(r=>`${e}.${r}`)}function gr(e,t){return t===1?[e]:SC(e,t)}function EY(e,t){if(e===1)return"rc";let r="";for(let n=0;n<e;n++)r+=t[n],n<e-1&&(r+=",");return r}var $Y=class{constructor(e){if(this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outputShape=e,this.rank=e.length,this.enableShapeUniforms=hr(this.outputShape.length),this.rank===0)this.userCode=`
void main() {
setOutput(vec4(getA(), 0., 0., 0.));
}
`;else{let t=gr("rc",this.rank),r=pt(this.rank),n=this.getOutOfBoundsCondition(t),a=this.getSetup(t),s=this.getOutput(t);this.userCode=`
void main() {
${r} rc = getOutputCoords();
if(${n}) {
setOutput(vec4(0));
} else {
${a}
setOutput(vec4(${s}));
}
}
`}}getSourceCoordsArr(e){let t=[];for(let r=0;r<=1;r++)for(let n=0;n<=1;n++){let a=`${r===0?"r":"rp1"}, ${n===0?"c":"cp1"}`;for(let s=2;s<this.rank;s++)a=`${e[e.length-1-s]},`+a;t.push(a)}return t}getOutOfBoundsCondition(e){if(this.rank===1)return`rc > ${this.enableShapeUniforms?"outShape":this.outputShape[0]}`;let t="";for(let r=this.rank-2;r<this.rank;r++)t+=`${e[r]} >= ${this.enableShapeUniforms?`outShape[${r}]`:this.outputShape[r]}`,r<this.rank-1&&(t+="||");return t}getSetup(e){if(this.rank===1)return"";let t=e.slice(-2),r=this.enableShapeUniforms?`outShape[${this.rank} - 1]`:this.outputShape[this.rank-1],n=this.enableShapeUniforms?`outShape[${this.rank} - 2]`:this.outputShape[this.rank-2];return`
int r = ${t[0]};
int c = ${t[1]};
int rp1 = r + 1;
int cp1 = c + 1;
bool cEdge = cp1 >= ${r};
bool rEdge = rp1 >= ${n};
`}getOutput(e){let t=this.getSourceCoordsArr(e);return this.rank===1?`getA(rc), (rc + 1 >= ${this.enableShapeUniforms?"outShape":this.outputShape[0]} ? 0. : getA(rc + 1)), 0, 0`:`getA(${t[0]}),
cEdge ? 0. : getA(${t[1]}),
rEdge ? 0. : getA(${t[2]}),
rEdge || cEdge ? 0. : getA(${t[3]})`}},NC=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"inputShape",type:"ivec3"}],this.outputShape=e,this.enableShapeUniforms=hr(this.outputShape.length);let r="";for(let n=0;n<4;n++){let a="thisRC = rc;";n%2===1&&(a+="thisRC.z += 1;"),n>1&&(a+="thisRC.y += 1;"),r+=`
${a}
${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=`
${AY(t,this.enableShapeUniforms)}
${this.enableShapeUniforms?tw():ew(e)}
void main() {
ivec3 rc = getOutputCoords();
vec4 result = vec4(0.);
ivec3 thisRC;
int rows = ${this.enableShapeUniforms?"outShape[1]":e[1]};
int cols = ${this.enableShapeUniforms?"outShape[2]":e[2]};
${r}
setOutput(result);
}
`}};function AY(e,t){return`
ivec3 inputCoordsFromReshapedOutCoords(int index) {
${t?HJ(["r","c","d"],"inputShape"):rl(["r","c","d"],e)}
return ivec3(r, c, d);
}
`}var FY=class{constructor(e){this.gpgpu=e,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0,this.freeTextures={},this.usedTextures={},this.logEnabled=!1}acquireTexture(e,t,r){let n=x1(t,r),a=v1(e,n,r);a in this.freeTextures||(this.freeTextures[a]=[]),a in this.usedTextures||(this.usedTextures[a]=[]);let s=b1(e,n,this.gpgpu.gl,this.gpgpu.textureConfig,r);if(this.freeTextures[a].length>0){this.numFreeTextures--,this.numUsedTextures++,this._numBytesFree-=s,this.log();let o=this.freeTextures[a].pop();return this.usedTextures[a].push(o),o}let i;return n===sr.PACKED_2X2_FLOAT32?i=this.gpgpu.createPackedMatrixTexture(e[0],e[1]):n===sr.PACKED_2X2_FLOAT16?i=this.gpgpu.createFloat16PackedMatrixTexture(e[0],e[1]):n===sr.UNPACKED_FLOAT32?i=this.gpgpu.createFloat32MatrixTexture(e[0],e[1]):n===sr.UNPACKED_FLOAT16?i=this.gpgpu.createFloat16MatrixTexture(e[0],e[1]):n===sr.PACKED_4X1_UNSIGNED_BYTE&&(i=this.gpgpu.createUnsignedBytesMatrixTexture(e[0],e[1])),this.usedTextures[a].push(i),this.numUsedTextures++,this._numBytesAllocated+=s,this.log(),i}releaseTexture(e,t,r,n){if(this.freeTextures==null)return;let a=x1(r,n),s=v1(t,a,n);s in this.freeTextures||(this.freeTextures[s]=[]);let i=b1(t,a,this.gpgpu.gl,this.gpgpu.textureConfig,n),o=j().getNumber("WEBGL_DELETE_TEXTURE_THRESHOLD");o!==-1&&this._numBytesAllocated>o?(this.gpgpu.deleteMatrixTexture(e.texture),this._numBytesAllocated-=i):(this.freeTextures[s].push(e),this.numFreeTextures++,this._numBytesFree+=i),this.numUsedTextures--;let l=this.usedTextures[s],p=l&&l.indexOf(e);if(p==null||p<0)throw new Error("Cannot release a texture that was never provided by this texture manager");l[p]=l[l.length-1],l.pop(),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.texture)});for(let e in this.usedTextures)this.usedTextures[e].forEach(t=>{this.gpgpu.deleteMatrixTexture(t.texture)});this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0}}};function RY(e,t){let r=e;if(t===r.R32F)return 4;if(t===r.R16F)return 2;if(t===r.RGBA32F||t===e.RGBA)return 16;if(t===r.RGBA16F)return 8;if(t===r.RGBA8)return 4;throw new Error(`Unknown internal format ${t}`)}function b1(e,t,r,n,a){let s=DY(t,n),i;if(a){let[l,p]=op(e[0],e[1]);i=l*p}else{let[l,p]=lh(e[0],e[1]);i=l*p}let o=RY(r,s);return i*o}function DY(e,t){switch(e){case sr.PACKED_2X2_FLOAT32:return iw(t);case sr.PACKED_2X2_FLOAT16:return ow(t);case sr.UNPACKED_FLOAT32:return nw(t);case sr.UNPACKED_FLOAT16:return aw(t);case sr.PACKED_4X1_UNSIGNED_BYTE:return sw(t);default:throw new Error(`Unknown physical texture type ${e}`)}}function MY(e){return j().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?e?sr.PACKED_2X2_FLOAT32:sr.UNPACKED_FLOAT32:e?sr.PACKED_2X2_FLOAT16:sr.UNPACKED_FLOAT16}function x1(e,t){if(e===on.UPLOAD)return sr.PACKED_2X2_FLOAT32;if(e===on.RENDER||e==null)return MY(t);if(e===on.DOWNLOAD||e===on.PIXELS)return sr.PACKED_4X1_UNSIGNED_BYTE;throw new Error(`Unknown logical texture type ${e}`)}function v1(e,t,r){return`${e[0]}_${e[1]}_${t}_${r}`}var aa=class{constructor(e,t){this.variableNames=["A"],this.outputShape=e,this.enableShapeUniforms=hr(this.outputShape.length),this.userCode=`
float unaryOperation(float x) {
${t}
}
void main() {
float x = getAAtOutCoords();
float y = unaryOperation(x);
setOutput(y);
}
`}},Cn="if (isnan(x)) return x;",OY="return x;",w1="return abs(x);",LY="return (x >= 0.0) ? x : (exp(x) - 1.0);",zY=Cn+`
return (x < 0.0) ? 0.0 : x;
`,PY=Cn+`
return (x < 0.0) ? 0.0 : min(6.0, x);
`,Qa="return x;",BY="return 1.0 / (1.0 + exp(-1.0 * x));",WY="return x;",UY=`
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;
`,VY=`
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;
`,GY=`
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;
`,HY="return 1.0 / (1.0 + exp(-1.0 * x));",ss=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.enableShapeUniforms=hr(this.outputShape.length),this.userCode=`
vec4 unaryOperation(vec4 x) {
${t}
}
void main() {
vec4 x = getAAtOutCoords();
vec4 y = unaryOperation(x);
setOutput(y);
}
`}},jY=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=e,this.enableShapeUniforms=hr(this.outputShape.length);let t=e.length,r=gr("rc",t),n=pt(t),a=EY(t,r),s=r.slice(-2),i=t<=1?"rc":`vec2(${s.join(",")})`;this.userCode=`
void main() {
${n} rc = getOutputCoords();
vec4 packedInput = getA(${a});
setOutput(getChannel(packedInput, ${i}));
}
`}},qY=ga.whereImpl,KY=1e-7,XY=1e-4,jm={};function ZY(e){return e in jm||(jm[e]={}),jm[e]}var JY=j().getNumber("CPU_HANDOFF_SIZE_THRESHOLD"),YY=600;function QY(){return j().global.screen==null?1024:j().global.screen.height*j().global.screen.width*window.devicePixelRatio*YY/1024/1024}var uw=class _C extends pd{nextDataId(){return _C.nextDataId++}constructor(t){if(super(),this.pendingRead=new WeakMap,this.pendingDisposal=new WeakSet,this.dataRefCount=new WeakMap,this.numBytesInGPU=0,this.uploadWaitMs=0,this.downloadWaitMs=0,this.lastGlFlushTime=0,this.warnedAboutMemory=!1,this.pendingDeletes=0,this.disposed=!1,!j().getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");let r;if(t!=null){if(t instanceof rc)r=t;else{let n=Vn(j().getNumber("WEBGL_VERSION"),t);r=new rc(n)}this.binaryCache={},this.gpgpuCreatedLocally=!1}else{let n=Vn(j().getNumber("WEBGL_VERSION"));r=new rc(n),this.binaryCache=ZY(j().getNumber("WEBGL_VERSION")),this.gpgpuCreatedLocally=!0}this.gpgpu=r,this.canvas=this.gpgpu.gl.canvas,this.textureManager=new FY(this.gpgpu),this.numMBBeforeWarning=QY(),this.texData=new Xc(this,wn())}numDataIds(){return this.texData.numDataIds()-this.pendingDeletes}writeTexture(t,r,n,a,s,i){let o=this.makeTensorInfo(r,n),l=this.texData.get(o.dataId);l.isPacked=!1,l.texture={texture:t,texShape:[a,s]},l.texShape=[a,s];let p=Mp(r),u=new y1(p,!1,i),d=this.runWebGLProgram(u,[o],n,[[a,s]]);return d.shape=r,l.texture=null,this.disposeIntermediateTensorInfo(o),d.dataId}write(t,r,n){if((j().getBool("WEBGL_CHECK_NUMERICAL_PROBLEMS")||j().getBool("DEBUG"))&&this.checkNumericalProblems(t),n==="complex64"&&t!=null)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");let a={id:this.nextDataId()};return this.texData.set(a,{shape:r,dtype:n,values:t,usage:on.UPLOAD,refCount:1}),a}refCount(t){return this.texData.has(t)?this.texData.get(t).refCount:0}incRef(t){let r=this.texData.get(t);r.refCount++}decRef(t){if(this.texData.has(t)){let r=this.texData.get(t);r.refCount--}}move(t,r,n,a,s){if(j().getBool("DEBUG")&&this.checkNumericalProblems(r),a==="complex64")throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");this.texData.set(t,{shape:n,dtype:a,values:r,usage:on.UPLOAD,refCount:s})}disposeIntermediateTensorInfo(t){this.disposeData(t.dataId)}readSync(t){let r=this.texData.get(t),{values:n,dtype:a,complexTensorInfos:s,slice:i,shape:o,isPacked:l}=r;if(i!=null){let h;l?h=new ss(o,Qa):h=new aa(o,Qa);let c=this.runWebGLProgram(h,[{dataId:t,shape:o,dtype:a}],a),f=this.readSync(c.dataId);return this.disposeIntermediateTensorInfo(c),f}if(n!=null)return this.convertAndCacheOnCPU(t);if(a==="string")return n;let p=this.activeTimers!=null,u;p&&(u=k.now());let d;if(a==="complex64"){let h=this.readSync(s.real.dataId),c=this.readSync(s.imag.dataId);d=_.mergeRealAndImagArrays(h,c)}else d=this.getValuesFromTexture(t);return p&&(this.downloadWaitMs+=k.now()-u),this.convertAndCacheOnCPU(t,d)}async read(t){if(this.pendingRead.has(t)){let f=this.pendingRead.get(t);return new Promise(m=>f.push(m))}let r=this.texData.get(t),{values:n,shape:a,slice:s,dtype:i,complexTensorInfos:o,isPacked:l}=r;if(s!=null){let f;l?f=new ss(a,Qa):f=new aa(a,Qa);let m=this.runWebGLProgram(f,[{dataId:t,shape:a,dtype:i}],i),g=this.read(m.dataId);return this.disposeIntermediateTensorInfo(m),g}if(n!=null)return this.convertAndCacheOnCPU(t);if(j().getBool("DEBUG")&&!j().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&j().getNumber("WEBGL_VERSION")===2)throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.");let p=null,u;if(i!=="complex64"&&j().get("WEBGL_BUFFER_SUPPORTED")){u=this.decode(t);let f=this.texData.get(u.dataId);p=this.gpgpu.createBufferFromTexture(f.texture.texture,...Wh(a))}this.pendingRead.set(t,[]),i!=="complex64"&&await this.gpgpu.createAndWaitForFence();let d;if(i==="complex64"){let f=await Promise.all([this.read(o.real.dataId),this.read(o.imag.dataId)]),m=f[0],g=f[1];d=_.mergeRealAndImagArrays(m,g)}else if(p==null)d=this.getValuesFromTexture(t);else{let f=k.sizeFromShape(a);d=this.gpgpu.downloadFloat32MatrixFromBuffer(p,f)}if(u!=null&&this.disposeIntermediateTensorInfo(u),p!=null){let f=this.gpgpu.gl;pe(f,()=>f.deleteBuffer(p))}let h=this.convertAndCacheOnCPU(t,d),c=this.pendingRead.get(t);return this.pendingRead.delete(t),c.forEach(f=>f(h)),this.pendingDisposal.has(t)&&(this.pendingDisposal.delete(t),this.disposeData(t)&&wn().removeDataId(t,this),this.pendingDeletes--),h}readToGPU(t,r={}){let n=this.texData.get(t),{values:a,shape:s,slice:i,dtype:o,isPacked:l,texture:p}=n;if(o==="complex64")throw new Error("Does not support reading texture for complex64 dtype.");if(i!=null){let c;l?c=new ss(s,Qa):c=new aa(s,Qa);let f=this.runWebGLProgram(c,[{dataId:t,shape:s,dtype:o}],o),m=this.readToGPU(f,r);return this.disposeIntermediateTensorInfo(f),m}if(p==null)throw a!=null?new Error("Data is not on GPU but on CPU."):new Error("There is no data on GPU or CPU.");let u=this.decode(t,r.customTexShape),d=wn().makeTensorFromTensorInfo(u),h=this.texData.get(u.dataId);return Object.assign({tensorRef:d},h.texture)}bufferSync(t){let r=this.readSync(t.dataId);if(t.dtype==="string")try{let n=r.map(a=>k.decodeString(a));return Le(t.shape,t.dtype,n)}catch{throw new Error("Failed to decode encoded string bytes into utf-8")}return Le(t.shape,t.dtype,r)}checkNumericalProblems(t){if(t!=null)for(let r=0;r<t.length;r++){let n=t[r];if(!ET(n))throw j().getBool("WEBGL_RENDER_FLOAT32_CAPABLE")?Error(`The value ${n} cannot be represented with your current settings. Consider enabling float32 rendering: 'tf.env().set('WEBGL_RENDER_FLOAT32_ENABLED', true);'`):Error(`The value ${n} cannot be represented on this device.`)}}getValuesFromTexture(t){let{shape:r,dtype:n,isPacked:a}=this.texData.get(t),s=k.sizeFromShape(r);if(j().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")){let h=this.decode(t),c=this.texData.get(h.dataId),f=this.gpgpu.downloadMatrixFromPackedTexture(c.texture.texture,...Wh(r)).subarray(0,s);return this.disposeIntermediateTensorInfo(h),f}let i=j().getBool("WEBGL_PACK")&&a===!0,o=i?Mp(r):r,l=i?new D9(o):new R9(o),p=this.runWebGLProgram(l,[{shape:o,dtype:n,dataId:t}],"float32"),u=this.texData.get(p.dataId),d=this.gpgpu.downloadByteEncodedFloatMatrixFromOutputTexture(u.texture.texture,u.texShape[0],u.texShape[1]).subarray(0,s);return this.disposeIntermediateTensorInfo(p),d}timerAvailable(){return j().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0}time(t){let r=this.activeTimers,n=[],a=!1;this.programTimersStack==null?(this.programTimersStack=n,a=!0):this.activeTimers.push(n),this.activeTimers=n,t();let s=k.flatten(this.activeTimers.map(l=>l.query)).filter(l=>l!=null),i=k.flatten(this.activeTimers.map(l=>l.name)).filter(l=>l!=null);this.activeTimers=r,a&&(this.programTimersStack=null);let o={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:null,wallMs:null};return(async()=>{if(j().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0){let l=await Promise.all(s);o.kernelMs=k.sum(l),o.getExtraProfileInfo=()=>l.map((p,u)=>({name:i[u],ms:p})).map(p=>`${p.name}: ${p.ms}`).join(", ")}else o.kernelMs={error:"WebGL query timers are not supported in this environment."};return this.uploadWaitMs=0,this.downloadWaitMs=0,o})()}memory(){return{unreliable:!1,numBytesInGPU:this.numBytesInGPU,numBytesInGPUAllocated:this.textureManager.numBytesAllocated,numBytesInGPUFree:this.textureManager.numBytesFree}}startTimer(){return j().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?this.gpgpu.beginQuery():{startMs:k.now(),endMs:null}}endTimer(t){return j().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?(this.gpgpu.endQuery(),t):(t.endMs=k.now(),t)}async getQueryTime(t){if(j().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0)return this.gpgpu.waitForQueryAndGetTime(t);let r=t;return r.endMs-r.startMs}disposeData(t,r=!1){if(this.pendingDisposal.has(t))return!1;if(!this.texData.has(t))return!0;if(r?this.texData.get(t).refCount=0:this.texData.get(t).refCount--,!r&&this.texData.get(t).refCount>0)return!1;if(this.pendingRead.has(t))return this.pendingDisposal.add(t),this.pendingDeletes++,!1;this.releaseGPUData(t);let{complexTensorInfos:n}=this.texData.get(t);return n!=null&&(this.disposeData(n.real.dataId,r),this.disposeData(n.imag.dataId,r)),this.texData.delete(t),!0}releaseGPUData(t){let{texture:r,dtype:n,texShape:a,usage:s,isPacked:i,slice:o}=this.texData.get(t),l=o&&o.origDataId||t,p=this.dataRefCount.get(l);p>1?this.dataRefCount.set(l,p-1):(this.dataRefCount.delete(l),r!=null&&(this.numBytesInGPU-=this.computeBytes(a,n),this.textureManager.releaseTexture(r,a,s,i)));let u=this.texData.get(t);u.texture=null,u.texShape=null,u.isPacked=!1,u.slice=null}getTexture(t){return this.uploadToGPU(t),this.texData.get(t).texture.texture}getDataInfo(t){return this.texData.get(t)}shouldExecuteOnCPU(t,r=JY){return j().getBool("WEBGL_CPU_FORWARD")&&t.every(n=>this.texData.get(n.dataId).texture==null&&k.sizeFromShape(n.shape)<r)}getGPGPUContext(){return this.gpgpu}where(t){_.warn("tf.where() in webgl locks the UI thread. Call tf.whereAsync() instead");let r=t.dataSync();return qY(t.shape,r)}packedUnaryOp(t,r,n){let a=new ss(t.shape,r),s=this.compileAndRun(a,[t],n);return wn().makeTensorFromTensorInfo(s)}abs(t){if(this.shouldExecuteOnCPU([t])&&t.dtype!=="complex64"){let a=kC(this.texData.get(t.dataId).values);return this.makeOutput(t.shape,t.dtype,a)}if(j().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,w1,t.dtype);let r=new aa(t.shape,w1),n=this.compileAndRun(r,[t]);return wn().makeTensorFromTensorInfo(n)}makeTensorInfo(t,r,n){let a;if(r==="string"&&n!=null&&n.length>0&&k.isString(n[0])){let s=n.map(i=>k.encodeString(i));a=this.write(s,t,r)}else a=this.write(n,t,r);return this.texData.get(a).usage=null,{dataId:a,shape:t,dtype:r}}makeOutput(t,r,n){return wn().makeTensorFromTensorInfo(this.makeTensorInfo(t,r,n),this)}unpackTensor(t){let r=new jY(t.shape);return this.runWebGLProgram(r,[t],t.dtype)}packTensor(t){let r=new $Y(t.shape);return this.runWebGLProgram(r,[t],t.dtype,null,!0)}packedReshape(t,r){let n=[Ii(t.shape),...Si(t.shape)],a={dtype:t.dtype,shape:n,dataId:t.dataId},s=[Ii(r),...Si(r)],i=new NC(s,n),o=!0,l=[n],p=this.runWebGLProgram(i,[a],t.dtype,l,o);return{dataId:p.dataId,shape:r,dtype:p.dtype}}decode(t,r){let n=this.texData.get(t),{isPacked:a,shape:s,dtype:i}=n;if(r!=null){let h=k.sizeFromShape(s),c=r[0]*r[1]*4;k.assert(h<=c,()=>"customTexShape is too small. Row * Column * 4 should be equal or larger than the size of the tensor data.")}let o=Mp(s),l;a?l=new F9(o):l=new A9(o);let p=!0,u=[r??Wh(o)],d=this.runWebGLProgram(l,[{shape:o,dtype:i,dataId:t}],i,u,p,r);return{dtype:i,shape:s,dataId:d.dataId}}runWebGLProgram(t,r,n,a,s=!1,i){let o=this.makeTensorInfo(t.outputShape,n),l=this.texData.get(o.dataId);if(t.packedOutput&&(l.isPacked=!0),t.outPackingScheme===ad.DENSE){let y=i??Wh(t.outputShape);l.texShape=y.map(b=>b*2)}if(t.outTexUsage!=null&&(l.usage=t.outTexUsage),k.sizeFromShape(o.shape)===0)return l.values=k.getTypedArrayFromDType(o.dtype,0),o;let p=[],u=r.map(y=>{if(y.dtype==="complex64")throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");let b=this.texData.get(y.dataId);if(b.texture==null){if(!t.packedInputs&&k.sizeFromShape(y.shape)<=j().getNumber("WEBGL_SIZE_UPLOAD_UNIFORM"))return{shape:y.shape,texData:null,isUniform:!0,uniformValues:b.values};t.packedInputs&&(b.isPacked=!0,b.shape=y.shape)}if(this.uploadToGPU(y.dataId),!!b.isPacked!=!!t.packedInputs)y=b.isPacked?this.unpackTensor(y):this.packTensor(y),p.push(y),b=this.texData.get(y.dataId);else if(b.isPacked&&!sd(b.shape,y.shape)){let x=y,v=y.shape;y.shape=b.shape,y=this.packedReshape(y,v),p.push(y),b=this.texData.get(y.dataId),x.shape=v}return{shape:y.shape,texData:b,isUniform:!1}});this.uploadToGPU(o.dataId);let d={shape:o.shape,texData:l,isUniform:!1},h=$9(t,u,d),c=this.getAndSaveBinary(h,()=>C9(this.gpgpu,t,u,d)),f=this.activeTimers!=null,m;f&&(m=this.startTimer()),j().get("ENGINE_COMPILE_ONLY")||E9(this.gpgpu,c,u,d,a),p.forEach(y=>this.disposeIntermediateTensorInfo(y)),f&&(m=this.endTimer(m),this.activeTimers.push({name:t.constructor.name,query:this.getQueryTime(m)}));let g=j().getNumber("WEBGL_FLUSH_THRESHOLD");if(g>0){let y=k.now();y-this.lastGlFlushTime>g&&(this.gpgpu.gl.flush(),this.lastGlFlushTime=y)}if(!j().getBool("WEBGL_LAZILY_UNPACK")&&l.isPacked&&s===!1){let y=this.unpackTensor(o);return this.disposeIntermediateTensorInfo(o),y}return o}compileAndRun(t,r,n,a,s=!1){return n=n||r[0].dtype,this.runWebGLProgram(t,r,n,a,s)}getAndSaveBinary(t,r){return t in this.binaryCache||(this.binaryCache[t]=r()),this.binaryCache[t]}getTextureManager(){return this.textureManager}dispose(){this.disposed||(j().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<"u"&&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=W(()=>{if(!j().get("WEBGL_RENDER_FLOAT32_ENABLED")){let t=j().getBool("DEBUG");j().set("DEBUG",!1);let r=this.abs(we(1e-8)).dataSync()[0];if(j().set("DEBUG",t),r>0)return 32}return 16})),this.floatPrecisionValue}epsilon(){return this.floatPrecision()===32?KY:XY}uploadToGPU(t){let r=this.texData.get(t),{shape:n,dtype:a,values:s,texture:i,usage:o,isPacked:l}=r;if(i!=null)return;let p=this.activeTimers!=null,u;p&&(u=k.now());let d=r.texShape;if(d==null&&(d=jT(n,l),r.texShape=d),s!=null){let h=Mp(n),c,f=d[1],m=d[0],g=s instanceof Uint8Array||s instanceof Uint8ClampedArray;(l||!g)&&([f,m]=op(d[0],d[1])),l?c=new O9(h,g):c=new y1(h,g);let y=g?[m,f]:d,b=this.makeTensorInfo(y,a),x=this.texData.get(b.dataId);g?x.usage=on.PIXELS:x.usage=on.UPLOAD,x.texShape=y,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(b.dataId),f,m,s);let v=[[m,f]],w=this.runWebGLProgram(c,[b],a,v,!0),N=this.texData.get(w.dataId);r.texShape=N.texShape,r.isPacked=N.isPacked,r.usage=N.usage,j().get("ENGINE_COMPILE_ONLY")?this.disposeData(w.dataId):(r.texture=N.texture,r.values=null,this.texData.delete(w.dataId)),this.disposeIntermediateTensorInfo(b),p&&(this.uploadWaitMs+=k.now()-u)}else{let h=this.acquireTexture(d,o,a,l);r.texture=h}}convertAndCacheOnCPU(t,r){let n=this.texData.get(t),{dtype:a}=n;return r!=null&&(n.values=eQ(r,a)),n.values}acquireTexture(t,r,n,a){if(this.numBytesInGPU+=this.computeBytes(t,n),!this.warnedAboutMemory&&this.numBytesInGPU>this.numMBBeforeWarning*1024*1024){let s=(this.numBytesInGPU/1024/1024).toFixed(2);this.warnedAboutMemory=!0,console.warn(`High memory usage in GPU: ${s} MB, most likely due to a memory leak`)}return this.textureManager.acquireTexture(t,r,a)}computeBytes(t,r){return t[0]*t[1]*k.bytesPerElement(r)}checkCompileCompletion(){for(let[,t]of Object.entries(this.binaryCache))this.checkCompletion_(t)}async checkCompileCompletionAsync(){let t=[];if(this.gpgpu.parallelCompilationExtension){for(let[,r]of Object.entries(this.binaryCache))t.push(this.checkCompletionAsync_(r));return Promise.all(t)}else{for(let[,r]of Object.entries(this.binaryCache)){let n=new Promise(a=>{try{this.checkCompletion_(r),a(!0)}catch(s){throw s}});t.push(n)}return Promise.all(t)}}async checkCompletionAsync_(t){return this.gpgpu.gl.getProgramParameter(t.webGLProgram,this.gpgpu.parallelCompilationExtension.COMPLETION_STATUS_KHR)?this.checkCompletion_(t):(await Yb(),this.checkCompletionAsync_(t))}checkCompletion_(t){if(this.gpgpu.gl.getProgramParameter(t.webGLProgram,this.gpgpu.gl.LINK_STATUS)===!1)throw console.log(this.gpgpu.gl.getProgramInfoLog(t.webGLProgram)),this.gpgpu.gl.getShaderParameter(t.fragmentShader,this.gpgpu.gl.COMPILE_STATUS)===!1?(Qv(t.source,this.gpgpu.gl.getShaderInfoLog(t.fragmentShader)),new Error("Failed to compile fragment shader.")):new Error("Failed to link vertex and fragment shaders.");return!0}getUniformLocations(){for(let t of Object.values(this.binaryCache)){this.gpgpu.buildVao(t.webGLProgram);let{variablesLocations:r,customUniformLocations:n,infLoc:a,nanLoc:s,outShapeLocation:i,outShapeStridesLocation:o,outTexShapeLocation:l}=nC(this.gpgpu,t.program,t.webGLProgram);t.variablesLocations=r,t.customUniformLocations=n,t.infLoc=a,t.nanLoc=s,t.outShapeLocation=i,t.outShapeStridesLocation=o,t.outTexShapeLocation=l}}createTensorFromGPUData(t,r,n){t.channels=t.channels||"RGBA";let{texture:a,height:s,width:i,channels:o}=t,l=wn().backend;if(!l.gpgpu.gl.isTexture(a))throw new Error("The texture is invalid. Also, please make sure the texture and the TFJS WebGL backend are using the same canvas. If you want to use your own custom canvas, you have to create and use the custom TFJS WebGL backend created from the canvas through 'new tf.MathBackendWebGL(customCanvas)'.");let p=l.writeTexture(a,r,n,s,i,o);return wn().makeTensorFromDataId(p,r,n,l)}};uw.nextDataId=0;function eQ(e,t){if(t==="float32"||t==="complex64")return e;if(t==="int32"||t==="bool"){let r=t==="int32"?new Int32Array(e.length):new Uint8Array(e.length);for(let n=0;n<r.length;++n)r[n]=Math.round(e[n]);return r}else throw new Error(`Unknown dtype ${t}`)}var tQ="4.22.0";function TC(){j().set("WEBGL_FORCE_F16_TEXTURES",!0)}Od.isBrowser()&&ff("webgl",()=>new uw,2);var rQ={forceHalfFloat:TC},pw=`
if (isnan(a)) return a;
if (isnan(b)) return b;
`,Ni=class{constructor(e,t,r){this.variableNames=["A","B"],this.outputShape=_.assertAndGetBroadcastShape(t,r),this.enableShapeUniforms=hr(this.outputShape.length),this.userCode=`
float binaryOperation(float a, float b) {
${e}
}
void main() {
float a = getAAtOutCoords();
float b = getBAtOutCoords();
setOutput(binaryOperation(a, b));
}
`}},al=`
result.r = isNaN.r ? NAN : result.r;
result.g = isNaN.g ? NAN : result.g;
result.b = isNaN.b ? NAN : result.b;
result.a = isNaN.a ? NAN : result.a;
`,cp=class{constructor(e,t,r,n=!1){this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=_.assertAndGetBroadcastShape(t,r);let a=this.outputShape.length;this.enableShapeUniforms=hr(a);let s="";if(n)if(a===0||k.sizeFromShape(this.outputShape)===1)s=`
result.y = 0.;
result.z = 0.;
result.w = 0.;
`;else if(s=`
${pt(a)} coords = getOutputCoords();
`,a===1)this.enableShapeUniforms?s+=`
result.y = (coords + 1) >= outShape ? 0. : result.y;
result.z = 0.;
result.w = 0.;
`:s+=`
result.y = (coords + 1) >= ${this.outputShape[0]} ? 0. : result.y;
result.z = 0.;
result.w = 0.;
`;else{let i=gr("coords",a);this.enableShapeUniforms?s+=`
bool nextRowOutOfBounds =
(${i[a-2]} + 1) >= outShape[${a} - 2];
bool nextColOutOfBounds =
(${i[a-1]} + 1) >= outShape[${a} - 1];
result.y = nextColOutOfBounds ? 0. : result.y;
result.z = nextRowOutOfBounds ? 0. : result.z;
result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;
`:s+=`
bool nextRowOutOfBounds =
(${i[a-2]} + 1) >= ${this.outputShape[a-2]};
bool nextColOutOfBounds =
(${i[a-1]} + 1) >= ${this.outputShape[a-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);
${s}
setOutput(result);
}
`}};function Jr(e){let{inputs:t,backend:r}=e,{x:n}=t;return r.incRef(n.dataId),{dataId:n.dataId,shape:n.shape,dtype:n.dtype}}var nQ={kernelName:so,backendName:"webgl",kernelFunc:Jr};function Ls(e){let{inputs:t,backend:r}=e,{real:n,imag:a}=t,s=r.makeTensorInfo(n.shape,"complex64"),i=r.texData.get(s.dataId),o=Jr({inputs:{x:n},backend:r}),l=Jr({inputs:{x:a},backend:r});return i.complexTensorInfos={real:o,imag:l},s}var aQ={kernelName:Yc,backendName:"webgl",kernelFunc:Ls},CC="return (a < 0.) ? b * a : a;",EC=`
vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
`;function sQ(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{alpha:s}=n,i=r.makeTensorInfo([],"float32",k.createScalarValue(s,"float32")),o=j().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new cp(EC,a.shape,i.shape):new Ni(CC,a.shape,i.shape),l=r.runWebGLProgram(o,[a,i],"float32");return r.disposeIntermediateTensorInfo(i),l}var iQ={kernelName:uo,backendName:"webgl",kernelFunc:sQ},$C="return (a < 0.) ? b * a : a;",AC=`
vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
`;function oQ(e){let{inputs:t,backend:r}=e,{x:n,alpha:a}=t,s=j().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new cp(AC,n.shape,a.shape):new Ni($C,n.shape,a.shape);return r.runWebGLProgram(s,[n,a],"float32")}var lQ={kernelName:_o,backendName:"webgl",kernelFunc:oQ},fp="if (isnan(x)) return x;";function Ke({opSnippet:e,packedOpSnippet:t,cpuKernelImpl:r,dtype:n}){return({inputs:a,backend:s})=>{let{x:i}=a,o=s,l=n||i.dtype;if(o.shouldExecuteOnCPU([i])&&r!=null){let d=o.texData.get(i.dataId),h=r(d.values,l);return o.makeTensorInfo(i.shape,l,h)}let p=j().getBool("WEBGL_PACK_UNARY_OPERATIONS")&&t!=null,u;return p?u=new ss(i.shape,t):u=new aa(i.shape,e),o.runWebGLProgram(u,[i],l)}}function lr({opSnippet:e,packedOpSnippet:t,checkOutOfBounds:r=!1,supportsComplex:n=!1,cpuKernelImpl:a,dtype:s}){return({inputs:i,backend:o})=>{let{a:l,b:p}=i,u=o;if(n&&l.dtype==="complex64"){let f=u.texData.get(l.dataId),m=u.texData.get(p.dataId),[g,y]=[[f.complexTensorInfos.real,m.complexTensorInfos.real],[f.complexTensorInfos.imag,m.complexTensorInfos.imag]].map(x=>{let[v,w]=x,N={dataId:v.dataId,dtype:v.dtype,shape:l.shape},T={dataId:w.dataId,dtype:w.dtype,shape:p.shape},E=new Ni(e,l.shape,p.shape);return u.runWebGLProgram(E,[N,T],cn(v.dtype,w.dtype))}),b=Ls({inputs:{real:g,imag:y},backend:u});return u.disposeIntermediateTensorInfo(g),u.disposeIntermediateTensorInfo(y),b}let d=s||cn(l.dtype,p.dtype);if((l.dtype==="string"||p.dtype==="string"||u.shouldExecuteOnCPU([l,p]))&&a!=null){let f=u.texData.get(l.dataId).values,m=u.texData.get(p.dataId).values,g=l.dtype==="string"?_.fromUint8ToStringArray(f):f,y=l.dtype==="string"?_.fromUint8ToStringArray(m):m,[b,x]=a(l.shape,p.shape,g,y,d),v=u.makeTensorInfo(x,d),w=u.texData.get(v.dataId);return w.values=b,v}let h=j().getBool("WEBGL_PACK_BINARY_OPERATIONS")&&t!=null,c;return h?c=new cp(t,l.shape,p.shape,r):c=new Ni(e,l.shape,p.shape),u.runWebGLProgram(c,[l,p],d)}}function id(e,t=!1){if(e==="linear")return t?WY:OY;if(e==="relu")return t?VY:zY;if(e==="elu")return t?UY:LY;if(e==="relu6")return t?GY:PY;if(e==="prelu")return t?AC:$C;if(e==="leakyrelu")return t?EC:CC;if(e==="sigmoid")return t?HY:BY;throw new Error(`Activation ${e} has not been implemented for the WebGL backend.`)}var FC=class{constructor(e,t,r,n=!1,a=!1,s=!1,i=null,o=!1,l=!1){this.variableNames=["matrixA","matrixB"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=r,this.enableShapeUniforms=hr(this.outputShape.length);let p=n?e[1]:e[2],u=Math.ceil(p/2),d=n?"i * 2, rc.y":"rc.y, i * 2",h=a?"rc.z, i * 2":"i * 2, rc.z",c=n?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],f=a?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"],m="",g="";i&&(o?m=`vec4 activation(vec4 a) {
vec4 b = getPreluActivationWeightsAtOutCoords();
${i}
}`:l?m=`vec4 activation(vec4 a) {
vec4 b = getLeakyreluAlphaAtOutCoords();
${i}
}`:m=`vec4 activation(vec4 x) {
${i}
}`,g="result = activation(result);");let y=s?"result += getBiasAtOutCoords();":"";s&&this.variableNames.push("bias"),o&&this.variableNames.push("preluActivationWeights"),l&&this.variableNames.push("leakyreluAlpha");let b="rc.x",x="rc.x";e[0]<t[0]?b=`imod(rc.x, ${e[0]})`:t[0]<e[0]&&(x=`imod(rc.x, ${t[0]})`),this.userCode=`
${m}
// Don't use uniform for sharedDimensionPacked for performance.
const float sharedDimension = ${u}.0;
vec4 dot2x2ARowBCol(ivec3 rc) {
vec4 result = vec4(0);
int batchA = ${b};
int batchB = ${x};
for (int i = 0; i < ${u}; i++) {
vec4 a = getMatrixA(batchA, ${d});
vec4 b = getMatrixB(batchB, ${h});
// These swizzled products need to be separately added.
// See: https://github.com/tensorflow/tfjs/issues/1735
result += (${c[0]} * ${f[0]});
result += (${c[1]} * ${f[1]});
}
return result;
}
void main() {
ivec3 rc = getOutputCoords();
vec4 result = dot2x2ARowBCol(rc);
${y}
${g}
setOutput(result);
}
`}},k1={REAL:"return areal * breal - aimag * bimag;",IMAG:"return areal * bimag + aimag * breal;"},I1=class{constructor(e,t,r){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=_.assertAndGetBroadcastShape(t,r),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));
}
`}},S1="return a * b;";function dw(e){let{inputs:t,backend:r}=e,{a:n,b:a}=t,s=_.upcastType(n.dtype,a.dtype);if(n.dtype==="complex64"){let o=r.texData.get(n.dataId),l=r.texData.get(a.dataId),p=new I1(k1.REAL,n.shape,a.shape),u=new I1(k1.IMAG,n.shape,a.shape),d=[{dataId:o.complexTensorInfos.real.dataId,dtype:o.complexTensorInfos.real.dtype,shape:n.shape},{dataId:o.complexTensorInfos.imag.dataId,dtype:o.complexTensorInfos.imag.dtype,shape:n.shape},{dataId:l.complexTensorInfos.real.dataId,dtype:l.complexTensorInfos.real.dtype,shape:a.shape},{dataId:l.complexTensorInfos.imag.dataId,dtype:l.complexTensorInfos.imag.dtype,shape:a.shape}],h=r.runWebGLProgram(p,d,"float32"),c=r.runWebGLProgram(u,d,"float32"),f=Ls({inputs:{real:h,imag:c},backend:r});return r.disposeIntermediateTensorInfo(h),r.disposeIntermediateTensorInfo(c),f}if(r.shouldExecuteOnCPU([n,a])){let o=r.texData.get(n.dataId),l=r.texData.get(a.dataId),[p,u]=sY(n.shape,a.shape,o.values,l.values,s),d=r.makeTensorInfo(u,s),h=r.texData.get(d.dataId);return h.values=p,d}let i;return j().getBool("WEBGL_PACK_BINARY_OPERATIONS")?i=new cp(S1,n.shape,a.shape):i=new Ni(S1,n.shape,a.shape),r.runWebGLProgram(i,[n,a],s)}var uQ={kernelName:ko,backendName:"webgl",kernelFunc:dw};function pQ(e,t,r){let n=[Ii(e.shape),...Si(e.shape)],a={dtype:e.dtype,shape:n,dataId:e.dataId},s=[Ii(t),...Si(t)],i=new NC(s,n),o=!0,l=[n],p=r.runWebGLProgram(i,[a],e.dtype,l,o);return{dataId:p.dataId,shape:t,dtype:p.dtype}}function ue(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{shape:s}=n,i=r,o=k.sizeFromShape(a.shape),l=k.inferFromImplicitShape(s,o),p=k.sizeFromShape(l);k.assert(o===p,()=>`The new shape (${l}) has ${p} elements and the old shape (${a.shape}) has ${o} elements. The new shape and old shape must have the same number of elements.`);let u=i.texData.get(a.dataId);return u.isPacked&&!sd(a.shape,l)&&!(u.texture!==null&&sd(u.shape,l))?pQ(a,l,i):(i.incRef(a.dataId),{dataId:a.dataId,shape:l,dtype:a.dtype})}var dQ={kernelName:Fu,backendName:"webgl",kernelFunc:ue},N1=class{constructor(e,t){this.variableNames=["x"];let{windowSize:r,batchSize:n,inSize:a,outSize:s}=e;this.outputShape=[n,s];let i=Math.floor(r/4)*4,o=r%4,l="sumValue += dot(values, ones);";if(t!=null){let u=1/t;l=`sumValue += dot(values * ${k.isInt(u)?u.toPrecision(2):u}, ones);`}let p="";a%r>0&&(p=`
if (inIdx < 0 || inIdx >= ${a}) {
return 0.0;
}
`),this.userCode=`
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
float getValue(int batch, int inIdx) {
${p}
return getX(batch, inIdx);
}
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
int outIdx = coords[1];
int inOffset = outIdx * ${r};
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)
);
${l}
}
int inIdx = inOffset + ${i};
if (${o===1}) {
vec4 values = vec4(getValue(batch, inIdx), 0.0, 0.0, 0.0);
${l}
} else if (${o===2}) {
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1), 0.0, 0.0);
${l}
} else if (${o===3}) {
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2), 0.0);
${l}
}
setOutput(sumValue);
}
`}},hQ=class{constructor(e,t){this.variableNames=["x"];let{windowSize:r,batchSize:n,inSize:a,outSize:s}=e;this.outputShape=[n,s];let i="0.0",o="";t==="prod"?i="1.0":t==="min"?(i="1.0 / 1e-20",o="min"):t==="max"&&(i="-1.0 / 1e-20",o="max");let l=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="sum"?l="sumValue":t==="prod"?l="prodValue":t==="all"?l="allValue":t==="any"&&(l="anyValue");let p=Math.floor(r/4)*4,u=r%4,d=`
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 = ${o}(values, minMaxValue);
if (${t==="min"} || ${t==="max"}) {
minMaxValue = ${o}(values, minMaxValue);
bvec4 isNaN = isnan(values);
if (isNaN.r || isNaN.g || isNaN.b || isNaN.a) {
minMaxValue = vec4(NAN);
}
}
}
`,h="vec4";t==="all"?(i="1.0",d=`
bool reducedAllValue = all(values);
float floatedReducedAllValue = float(reducedAllValue);
allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);
`,h="bvec4"):t==="any"&&(i="0.0",d=`
bool reducedAnyValue = any(values);
float floatedReducedAnyValue = float(reducedAnyValue);
anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);
`,h="bvec4");let c="";a%r>0&&(c=`
if (inIdx < 0 || inIdx >= ${a}) {
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) {
${c}
return getX(batch, inIdx);
}
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
int outIdx = coords[1];
int inOffset = outIdx * ${r};
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 < ${p}; i += 4) {
int inIdx = inOffset + i;
${h} values = ${h}(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
getValue(batch, inIdx + 3)
);
${d}
}
int inIdx = inOffset + ${p};
if (${u===1}) {
${h} values = ${h}(
getValue(batch, inIdx),
initializationValue,
initializationValue,
initializationValue
);
${d}
} else if (${u===2}) {
${h} values = ${h}(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
initializationValue,
initializationValue
);
${d}
} else if (${u===3}) {
${h} values = ${h}(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
initializationValue
);
${d}
}
setOutput(${l});
}
`}};function cQ(e){let t=[];for(;t.length===0||t[t.length-1].outSize!==1;){let r=t.length?t[t.length-1].outSize:e[1],n=_.computeOptimalWindowSize(r);t.push({inSize:r,windowSize:n,outSize:Math.ceil(r/n)})}return t}function sl(e,t,r,n){let a=cQ(e.shape),s=e;for(let i=0;i<a.length;i++){let{inSize:o,windowSize:l,outSize:p}=a[i],u,d;r==="mean"?u=i===0?new N1({windowSize:l,inSize:o,batchSize:e.shape[0],outSize:p},o):new N1({windowSize:l,inSize:o,batchSize:e.shape[0],outSize:p}):u=new hQ({windowSize:l,inSize:o,batchSize:e.shape[0],outSize:p},r),d=s,s=n.runWebGLProgram(u,[s],t),d.dataId!==e.dataId&&n.disposeIntermediateTensorInfo(d)}return s}var fQ=class{constructor(e,t){this.variableNames=["A"];let r=new Array(e.length);for(let s=0;s<r.length;s++)r[s]=e[t[s]];this.outputShape=r,this.rank=r.length;let n=pt(this.rank),a=mQ(t);this.userCode=`
void main() {
${n} resRC = getOutputCoords();
setOutput(getA(${a}));
}
`}};function mQ(e){let t=e.length;if(t>6)throw Error(`Transpose for rank ${t} is not yet supported`);let r=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"],n=new Array(t);for(let a=0;a<e.length;a++)n[e[a]]=r[a];return n.join()}var gQ=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0;let r=new Array(e.length);for(let p=0;p<r.length;p++)r[p]=e[t[p]];if(this.outputShape=r,this.rank=r.length,this.rank>6)throw Error(`Packed transpose for rank ${this.rank} is not yet supported.`);let n=pt(this.rank),a=SC("rc",this.rank),s=new Array(this.rank);for(let p=0;p<t.length;p++)s[t[p]]=a[p];let i=`vec2(${s.slice(-2).join()})`,o=`++${a[this.rank-1]} < ${r[this.rank-1]}`,l=`getChannel(getA(${s.join()}), ${i})`;this.userCode=`
void main() {
${n} rc = getOutputCoords();
vec4 result = vec4(0.);
result[0] = ${l};
if(${o}) {
result[1] = ${l};
}
--${a[this.rank-1]};
if(++${a[this.rank-2]} < ${r[this.rank-2]}) {
result[2] = ${l};
if(${o}) {
result[3] = ${l};
}
}
setOutput(result);
}
`}};function xm(e,t,r){let n=j().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new gQ(e.shape,t):new fQ(e.shape,t);return r.runWebGLProgram(n,[e],e.dtype)}function yQ(e,t,r,n){let a=t,s=e.shape.length,i=k.parseAxisParam(a,e.shape),o=i,l=_.getAxesPermutation(o,s),p=l!=null,u=e;p&&(u=xm(e,l,n),o=_.getInnerMostAxes(o.length,s)),_.assertAxesAreInnerMostDims("sum",o,s);let[d,h]=_.computeOutAndReduceShapes(u.shape,o),c=d;r&&(c=_.expandShapeToKeepDim(d,i));let f=k.sizeFromShape(h),m=k.sizeFromShape(e.shape)/f,g=ue({inputs:{x:u},attrs:{shape:[m,f]},backend:n}),y=cf(e.dtype),b=sl(g,y,"sum",n),x=ue({inputs:{x:b},attrs:{shape:c},backend:n});return n.disposeIntermediateTensorInfo(g),n.disposeIntermediateTensorInfo(b),p&&n.disposeIntermediateTensorInfo(u),x}function vm(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{axis:s,keepDims:i}=n;return yQ(a,s,i,r)}var bQ={kernelName:Vo,backendName:"webgl",kernelFunc:vm};function xr(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{perm:s}=n,i=r,o=a.shape.length,l=new Array(o);for(let u=0;u<l.length;u++)l[u]=a.shape[s[u]];let p;if(i.shouldExecuteOnCPU([a])){let u=i.texData.get(a.dataId).values,d=lw(u,a.shape,a.dtype,s,l);p=i.makeTensorInfo(l,a.dtype);let h=i.texData.get(p.dataId);h.values=d}else p=xm(a,s,i);return p}var xQ={kernelName:Ta,backendName:"webgl",kernelFunc:xr},RC=1e3;function Lc({a:e,b:t,transposeA:r,transposeB:n,backend:a,bias:s=null,preluActivationWeights:i=null,leakyreluAlpha:o=0,activation:l=null}){let p=e.shape.length,u=t.shape.length,d=r?e.shape[p-2]:e.shape[p-1],h=n?t.shape[u-1]:t.shape[u-2],c=r?e.shape[p-1]:e.shape[p-2],f=n?t.shape[u-2]:t.shape[u-1],m=e.shape.slice(0,-2),g=t.shape.slice(0,-2),y=k.sizeFromShape(m),b=k.sizeFromShape(g),x=Zu.assertAndGetBroadcastShape(e.shape.slice(0,-2),t.shape.slice(0,-2)).concat([c,f]);k.assert(d===h,()=>`Error in matMul: inner shapes (${d}) and (${h}) of Tensors with shapes ${e.shape} and ${t.shape} and transposeA=${r} and transposeB=${n} must match.`);let v=r?[y,d,c]:[y,c,d],w=n?[b,f,h]:[b,h,f],N=ue({inputs:{x:e},backend:a,attrs:{shape:v}}),T=ue({inputs:{x:t},backend:a,attrs:{shape:w}}),E=[N,T],$=Math.max(y,b),R=r?N.shape[1]:N.shape[2],F=s!=null,S=i!=null,D=l==="leakyrelu",P=l!=null?id(l,!0):null,U=F||S||D||P!=null,H;if((c===1||f===1)&&R>RC&&U===!1){let G=N,Z=T;r&&(G=xr({inputs:{x:N},backend:a,attrs:{perm:[0,2,1]}}),E.push(G)),n&&(Z=xr({inputs:{x:T},backend:a,attrs:{perm:[0,2,1]}}),E.push(Z));let ee=f!==1,X=f===1,re=G;ee&&(re=ue({inputs:{x:G},backend:a,attrs:{shape:[$,R,1]}}),E.push(re));let te=f===1?2:1,ae=Z;X&&(ae=ue({inputs:{x:Z},backend:a,attrs:{shape:[$,1,R]}}),E.push(ae));let ie=dw({inputs:{a:re,b:ae},backend:a});H=vm({inputs:{x:ie},backend:a,attrs:{axis:te,keepDims:!0}}),E.push(ie)}else{let G=cn(e.dtype,t.dtype),Z=new FC(v,w,[$,c,f],r,n,F,P,S,D),ee=[N,T];if(s!=null&&ee.push(s),S&&ee.push(i),D){let X=a.makeTensorInfo([],"float32",k.createScalarValue(o,"float32"));ee.push(X),E.push(X)}H=a.runWebGLProgram(Z,ee,G)}let q=ue({inputs:{x:H},backend:a,attrs:{shape:x}});E.push(H);for(let G of E)a.disposeIntermediateTensorInfo(G);return q}function vQ(e){let{inputs:t,backend:r,attrs:n}=e,{a,b:s,bias:i,preluActivationWeights:o}=t,{transposeA:l,transposeB:p,activation:u,leakyreluAlpha:d}=n;return Lc({a,b:s,transposeA:l,transposeB:p,backend:r,bias:i,preluActivationWeights:o,leakyreluAlpha:d,activation:u})}var wQ={kernelName:li,backendName:"webgl",kernelFunc:vQ},_1="return abs(x);";function kQ(e){let{inputs:t,backend:r}=e,{x:n}=t;if(r.shouldExecuteOnCPU([n])&&n.dtype!=="complex64"){let s=r.texData.get(n.dataId),i=kC(s.values);return r.makeTensorInfo(n.shape,n.dtype,i)}let a;return j().getBool("WEBGL_PACK_UNARY_OPERATIONS")?a=new ss(n.shape,_1):a=new aa(n.shape,_1),r.runWebGLProgram(a,[n],n.dtype)}var IQ={kernelName:Kl,backendName:"webgl",kernelFunc:kQ},SQ=Cn+`
if (abs(x) > 1.) {
return NAN;
}
return acos(x);
`,NQ=Ke({opSnippet:SQ}),_Q={kernelName:$i,backendName:"webgl",kernelFunc:NQ},TQ=Cn+`
if (x < 1.0) return NAN;
return log(x + sqrt(x * x - 1.0));`,CQ=Ke({opSnippet:TQ}),EQ={kernelName:Ai,backendName:"webgl",kernelFunc:CQ},T1="return a + b;",$Q=lr({opSnippet:T1,packedOpSnippet:T1,supportsComplex:!0,cpuKernelImpl:z9}),AQ={kernelName:Ts,backendName:"webgl",kernelFunc:$Q},FQ=class{constructor(e,t){this.outputShape=[],this.outputShape=e,this.variableNames=t.map((a,s)=>`T${s}`);let r=[];this.variableNames.forEach(a=>{r.push(`float v${a} = get${a}AtOutCoords();`)});let n=this.variableNames.map(a=>`v${a}`).join(" + ");this.userCode=`
void main() {
${r.join(`
`)}
float result = ${n};
setOutput(result);
}
`}},RQ=class{constructor(e,t){this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.variableNames=t.map((a,s)=>`T${s}`);let r=[];this.variableNames.forEach(a=>{r.push(`vec4 v${a} = get${a}AtOutCoords();`)});let n=this.variableNames.map(a=>`v${a}`).join(" + ");this.userCode=`
void main() {
${r.join(`
`)}
vec4 result = ${n};
setOutput(result);
}
`}};function nc(e){let{inputs:t,backend:r}=e,n=t;if(n.length===1)return Jr({inputs:{x:n[0]},backend:r});if(n.length>j().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){let o=Math.floor(n.length/2),l=nc({inputs:n.slice(0,o),backend:r}),p=nc({inputs:n.slice(o),backend:r});return nc({inputs:[l,p],backend:r})}let a=n.map(o=>o.dtype).reduce((o,l)=>cn(o,l)),s=n.map(o=>o.shape),i=j().getBool("WEBGL_PACK")?new RQ(n[0].shape,s):new FQ(n[0].shape,s);return r.runWebGLProgram(i,n,a)}var DQ={kernelName:Fi,backendName:"webgl",kernelFunc:nc};function MQ(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{axis:s,keepDims:i}=n,o=a.shape.length,l=k.parseAxisParam(s,a.shape),p=l,u=_.getAxesPermutation(p,o),d=a;u!=null&&(d=xr({inputs:{x:a},backend:r,attrs:{perm:u}}),p=_.getInnerMostAxes(p.length,o)),_.assertAxesAreInnerMostDims("all",p,o);let[h,c]=_.computeOutAndReduceShapes(d.shape,p),f=k.sizeFromShape(c),m=ue({inputs:{x:d},backend:r,attrs:{shape:[-1,f]}}),g=sl(m,m.dtype,"all",r),y;if(i){let b=_.expandShapeToKeepDim(h,l);y=ue({inputs:{x:g},backend:r,attrs:{shape:b}})}else y=ue({inputs:{x:g},backend:r,attrs:{shape:h}});return r.disposeIntermediateTensorInfo(m),r.disposeIntermediateTensorInfo(g),u!=null&&r.disposeIntermediateTensorInfo(d),y}var OQ={kernelName:Xl,backendName:"webgl",kernelFunc:MQ};function LQ(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{axis:s,keepDims:i}=n,o=a.shape.length,l=k.parseAxisParam(s,a.shape),p=l,u=_.getAxesPermutation(p,o),d=a;u!=null&&(d=xr({inputs:{x:a},backend:r,attrs:{perm:u}}),p=_.getInnerMostAxes(p.length,o)),_.assertAxesAreInnerMostDims("any",p,o);let[h,c]=_.computeOutAndReduceShapes(d.shape,p),f=k.sizeFromShape(c),m=ue({inputs:{x:d},backend:r,attrs:{shape:[-1,f]}}),g=sl(m,m.dtype,"any",r),y;if(i){let b=_.expandShapeToKeepDim(h,l);y=ue({inputs:{x:g},backend:r,attrs:{shape:b}})}else y=ue({inputs:{x:g},backend:r,attrs:{shape:h}});return r.disposeIntermediateTensorInfo(m),r.disposeIntermediateTensorInfo(g),u!=null&&r.disposeIntermediateTensorInfo(d),y}var zQ={kernelName:Zl,backendName:"webgl",kernelFunc:LQ},PQ=class{constructor(e,t,r){this.variableNames=["A"];let{windowSize:n,batchSize:a,outSize:s}=e;r||this.variableNames.push("bestIndicesA"),this.outputShape=[a,s];let i=t==="max"?">":"<",o=r?"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 = ${o};
float candidate = getA(batch, inIdx);
if (candidate ${i} bestValue) {
bestValue = candidate;
bestIndex = inIdx;
}
}
setOutput(float(bestIndex));
}
`}},BQ=class{constructor(e,t,r,n){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,k.assert(e.length>2,()=>`Packed arg${r.charAt(0).toUpperCase()+r.slice(1)} supports only inputs with rank above 2.`);let a=e[e.length-1],s=Math.ceil(a/t);this.outputShape=e.slice(0,-1),s>1&&this.outputShape.push(s),n||this.variableNames.push("bestIndicesA");let i=this.outputShape,o=i.length,l=pt(o),p=gr("coords",o),u,d;if(s===1){d=o+1;let T=pt(d);u=`
${T} sourceLocR = ${T}(${p.join()}, 0);
++${p[o-1]};
${T} sourceLocG = ${T}(${p.join()}, 0);
++${p[o-2]};
${T} sourceLocA = ${T}(${p.join()}, 0);
--${p[o-1]};
${T} sourceLocB = ${T}(${p.join()}, 0);
--${p[o-2]};`}else d=o,u=`
${l} sourceLocR = coords;
++${p[o-1]};
${l} sourceLocG = coords;
++${p[o-2]};
${l} sourceLocA = coords;
--${p[o-1]};
${l} sourceLocB = coords;
--${p[o-2]};`;let h=["x","y","z","w","u","v"].slice(0,d),c="."+h[d-1],f=h.map(T=>"int "+T),m=gr("sourceLocR",d-1).concat("inIdx.r"),g=gr("sourceLocG",d-1).concat("inIdx.g"),y=gr("sourceLocB",d-1).concat("inIdx.b"),b=gr("sourceLocA",d-1).concat("inIdx.a"),x=r==="max"?"greaterThan":"lessThan",v=n?"":`
inIdx = round(vec4(getBestIndicesAChannel(${m.join()}),
getBestIndicesAChannel(${g.join()}),
getBestIndicesAChannel(${y.join()}),
getBestIndicesAChannel(${b.join()})));`,w=`vec4(
getAChannel(${m.join()}),
hasNextCol ? getAChannel(${g.join()}) : 0.,
hasNextRow ? getAChannel(${y.join()}) : 0.,
hasNextRow && hasNextCol ? getAChannel(${b.join()}) : 0.)`,N=n?"":`
float getBestIndicesAChannel(${f.join()}) {
return getChannel(getBestIndicesA(${h.join()}),
vec2(${h.slice(-2).join()}));
}`;this.userCode=`
float getAChannel(${f.join()}) {
return getChannel(getA(${h.join()}),
vec2(${h.slice(-2).join()}));
}
${N}
void main() {
${l} coords = getOutputCoords();
bool hasNextCol = ${p[o-1]} < ${i[o-1]-1};
bool hasNextRow = ${p[o-2]} < ${i[o-2]-1};
${u}
ivec4 srcIdx = ivec4(sourceLocR${c}, sourceLocG${c},
sourceLocB${c}, sourceLocA${c}) * ${t};
ivec4 inIdx = srcIdx;
vec4 bestIndex = vec4(inIdx);
vec4 bestValue = ${w};
for (int i = 0; i < ${t}; i++) {
inIdx = srcIdx;
${v}
vec4 candidate = ${w};
bvec4 nan = isnan(candidate);
bvec4 replace = bvec4(
vec4(${x}(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 DC(e,t,r,n=null){let a=t.shape[0],s=t.shape[1];n!=null&&(a=n.shape[0],s=n.shape[1]);let i=_.computeOptimalWindowSize(s),o={windowSize:i,inSize:s,batchSize:a,outSize:Math.ceil(s/i)},l=new PQ(o,r,n==null),p=[t];n!=null&&p.push(n);let u=e.runWebGLProgram(l,p,"int32");if(u.shape[1]===1)return u;let d=DC(e,t,r,u);return e.disposeIntermediateTensorInfo(u),d}function MC(e,t,r,n=null){let a=n!=null?n.shape:t.shape,s=a[a.length-1],i=_.computeOptimalWindowSize(s),o=new BQ(a,i,r,n==null),l=n==null?[t]:[t,n],p=e.runWebGLProgram(o,l,"int32");if(p.shape.length===t.shape.length){let u=MC(e,t,r,p);return e.disposeIntermediateTensorInfo(p),u}return p}function OC(e,t,r,n){let a=[r];if(_.assertAxesAreInnerMostDims("arg"+n.charAt(0).toUpperCase()+n.slice(1),a,t.shape.length),!j().getBool("WEBGL_PACK_REDUCE")||t.shape.length<=2){let s=[],i=e.texData.get(t.dataId),o=i!==null&&i.isPacked,l=t;o&&(l=e.unpackTensor(t),s.push(l));let[p,u]=_.computeOutAndReduceShapes(l.shape,a),d=k.sizeFromShape(u),h=ue({inputs:{x:l},backend:e,attrs:{shape:[-1,d]}});s.push(h);let c=DC(e,h,n);s.push(c);let f=ue({inputs:{x:c},backend:e,attrs:{shape:p}});return s.forEach(m=>e.disposeIntermediateTensorInfo(m)),f}return MC(e,t,n)}function WQ(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{axis:s}=n,i=k.parseAxisParam(s,a.shape),o=_.getAxesPermutation(i,a.shape.length),l=a,p=[];o!=null&&(l=xr({inputs:{x:a},backend:r,attrs:{perm:o}}),p.push(l),i=_.getInnerMostAxes(i.length,l.shape.length)),_.assertAxesAreInnerMostDims("argMax",[i[0]],l.shape.length);let u=OC(r,l,i[0],"max");return p.forEach(d=>r.disposeIntermediateTensorInfo(d)),u}var UQ={kernelName:Jl,backendName:"webgl",kernelFunc:WQ};function VQ(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{axis:s}=n,i=k.parseAxisParam(s,a.shape),o=_.getAxesPermutation(i,a.shape.length),l=a,p=[];o!=null&&(l=xr({inputs:{x:a},backend:r,attrs:{perm:o}}),p.push(l),i=_.getInnerMostAxes(i.length,l.shape.length)),_.assertAxesAreInnerMostDims("argMin",[i[0]],l.shape.length);let u=OC(r,l,i[0],"min");return p.forEach(d=>r.disposeIntermediateTensorInfo(d)),u}var GQ={kernelName:Yl,backendName:"webgl",kernelFunc:VQ},HQ=Cn+`
if (abs(x) > 1.) {
return NAN;
}
return asin(x);
`,jQ=Ke({opSnippet:HQ}),qQ={kernelName:Ri,backendName:"webgl",kernelFunc:jQ},KQ=Cn+"return log(x + sqrt(x * x + 1.0));",XQ=Ke({opSnippet:KQ}),ZQ={kernelName:Di,backendName:"webgl",kernelFunc:XQ},JQ=Cn+`
return atan(x);
`,YQ=Ke({opSnippet:JQ}),QQ={kernelName:Mi,backendName:"webgl",kernelFunc:YQ},eee=pw+`
return atan(a, b);
`,tee=`
vec4 result = atan(a, b);
bvec4 isNaNA = isnan(a);
bvec4 isNaNB = isnan(b);
bvec4 isNaN = bvec4(isNaNA.x || isNaNB.x, isNaNA.y || isNaNB.y, isNaNA.z || isNaNB.z, isNaNA.w || isNaNB.w);
`+al+`
return result;
`,ree=lr({opSnippet:eee,packedOpSnippet:tee}),nee={kernelName:Li,backendName:"webgl",kernelFunc:ree},aee=Cn+`
if ((x < -1.0) || (x > 1.0)) return NAN;
return (log(1.0 + x) - log(1.0 - x)) / 2.0;`,see=Ke({opSnippet:aee}),iee={kernelName:Oi,backendName:"webgl",kernelFunc:see},od=class{constructor(e,t,r,n=!1,a=!1){if(this.variableNames=["x"],t==="avg"&&r)throw new Error("Cannot compute positions for average pool.");let s=e.filterWidth,i=e.strideHeight,o=e.strideWidth,l=e.dilationHeight,p=e.dilationWidth,u=e.effectiveFilterHeight,d=e.effectiveFilterWidth,h=e.padInfo.top,c=e.padInfo.left;this.outputShape=e.outShape;let f=t==="avg",m=`((batch * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + d`,g=`(xR * ${e.inWidth} + xC) * ${e.inChannels} + d`,y="0.0";if(f||(y="-1.0 / 1e-20"),r){let T=">=";this.userCode=`
const ivec2 strides = ivec2(${i}, ${o});
const ivec2 pads = ivec2(${h}, ${c});
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 < ${u};
wR += ${l}) {
int xR = xRCorner + wR;
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int wC = 0; wC < ${d};
wC += ${p}) {
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 ${T} currMinMaxValue) {
minMaxValue = value;
minMaxValueFound = 1.0;
minMaxPosition = ${n?a?m:g:`wR * ${d} + wC`};
}
}
}
setOutput(float(minMaxPosition));
}
`;return}let b="max",x=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="avg"&&(x="avgValue / max(count, 1.0)");let v=Math.floor(s/4)*4,w=s%4,N=`
if (${f}) {
avgValue += dot(values, ones);
} else {
minMaxValue = ${b}(values, minMaxValue);
}
`;this.userCode=`
const ivec2 strides = ivec2(${i}, ${o});
const ivec2 pads = ivec2(${h}, ${c});
const float initializationValue = ${y};
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(${y});
float avgValue = 0.0;
count = 0.0;
for (int wR = 0; wR < ${u};
wR += ${l}) {
int xR = xRCorner + wR;
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int wC = 0; wC < ${v}; wC += 4) {
int xC = xCCorner + wC * ${p};
vec4 values = vec4(
getValue(batch, xR, xC, d),
getValue(batch, xR, xC + ${p}, d),
getValue(batch, xR, xC + 2 * ${p}, d),
getValue(batch, xR, xC + 3 * ${p}, d)
);
${N}
}
int xC = xCCorner + ${v};
if (${w===1}) {
vec4 values = vec4(
getValue(batch, xR, xC, d),
initializationValue,
initializationValue,
initializationValue
);
${N}
} else if (${w===2}) {
vec4 values = vec4(
getValue(batch, xR, xC, d),
getValue(batch, xR, xC + ${p}, d),
initializationValue,
initializationValue
);
${N}
} else if (${w===3}) {
vec4 values = vec4(
getValue(batch, xR, xC, d),
getValue(batch, xR, xC + ${p}, d),
getValue(batch, xR, xC + 2 * ${p}, d),
initializationValue
);
${N}
}
}
setOutput(${x});
}
`}},hw=class{constructor(e,t,r,n=!1,a=!1){if(this.variableNames=["x"],t==="avg"&&r)throw new Error("Cannot compute positions for average pool.");let s=e.filterWidth,i=e.strideDepth,o=e.strideHeight,l=e.strideWidth,p=e.dilationDepth,u=e.dilationHeight,d=e.dilationWidth,h=e.effectiveFilterDepth,c=e.effectiveFilterHeight,f=e.effectiveFilterWidth,m=e.padInfo.front,g=e.padInfo.top,y=e.padInfo.left;this.outputShape=e.outShape;let b=t==="avg",x="0.0";if(b||(x="-1.0 / 1e-20"),r){let $=">=";this.userCode=`
const ivec3 strides =
ivec3(${i}, ${o}, ${l});
const ivec3 pads = ivec3(${m}, ${g}, ${y});
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 < ${h};
wD += ${p}) {
int xD = xDCorner + wD;
if (xD < 0 || xD >= ${e.inDepth}) {
continue;
}
for (int wR = 0; wR < ${c};
wR += ${u}) {
int xR = xRCorner + wR;
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int wC = 0; wC < ${f};
wC += ${d}) {
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 ${$} currMinMaxValue) {
minMaxValue = value;
minMaxValueFound = 1.0;
minMaxPosition = ${n?a?`(((batch * ${e.inDepth} + xD) * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + ch`:`((xD * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + ch`:`wD * ${c} * ${f} +
wR * ${f} + wC`};
}
}
}
}
setOutput(float(minMaxPosition));
}
`;return}let v="max",w=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="avg"&&(w="avgValue / max(count, 1.0)");let N=Math.floor(s/4)*4,T=s%4,E=`
if (${b}) {
avgValue += dot(values, ones);
} else {
minMaxValue = ${v}(values, minMaxValue);
}
`;this.userCode=`
const ivec3 strides =
ivec3(${i}, ${o}, ${l});
const ivec3 pads = ivec3(${m}, ${g}, ${y});
const float initializationValue = ${x};
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(${x});
float avgValue = 0.0;
count = 0.0;
for (int wD = 0; wD < ${h};
wD += ${p}) {
int xD = xDCorner + wD;
if (xD < 0 || xD >= ${e.inDepth}) {
continue;
}
for (int wR = 0; wR < ${c};
wR += ${u}) {
int xR = xRCorner + wR;
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int wC = 0; wC < ${N}; wC += 4) {
int xC = xCCorner + wC * ${d};
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
getValue(batch, xD, xR, xC + ${d}, ch),
getValue(batch, xD, xR, xC + 2 * ${d}, ch),
getValue(batch, xD, xR, xC + 3 * ${d}, ch)
);
${E}
}
int xC = xCCorner + ${N};
if (${T===1}) {
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
initializationValue,
initializationValue,
initializationValue
);
${E}
} else if (${T===2}) {
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
getValue(batch, xD, xR, xC + ${d}, ch),
initializationValue,
initializationValue
);
${E}
} else if (${T===3}) {
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
getValue(batch, xD, xR, xC + ${d}, ch),
getValue(batch, xD, xR, xC + 2 * ${d}, ch),
initializationValue
);
${E}
}
}
}
setOutput(${w});
}
`}};function oee(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t;lp(a,"avgPool");let{filterSize:s,strides:i,pad:o,dimRoundingMode:l}=n,p=1;k.assert(_.eitherStridesOrDilationsAreOne(i,p),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${i} and dilations '${p}'`);let u=_.computePool2DInfo(a.shape,s,i,p,o,l);if(u.filterWidth===1&&u.filterHeight===1&&k.arraysEqual(u.inShape,u.outShape))return Jr({inputs:{x:a},backend:r});let d=new od(u,"avg",!1);return r.runWebGLProgram(d,[a],"float32")}var lee={kernelName:zi,backendName:"webgl",kernelFunc:oee};function uee(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{filterSize:s,strides:i,pad:o,dimRoundingMode:l,dataFormat:p}=n,u=[1,1,1],d=_.computePool3DInfo(a.shape,s,i,u,o,l,p),h=new hw(d,"avg",!1);return r.runWebGLProgram(h,[a],"float32")}var pee={kernelName:Ql,backendName:"webgl",kernelFunc:uee},dee=class{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;let t=e.filterHeight,r=e.filterWidth,n=e.strideHeight,a=e.strideWidth,s=e.dilationHeight,i=e.dilationWidth,o=e.effectiveFilterHeight,l=e.effectiveFilterWidth,p=o-1-e.padInfo.top,u=l-1-e.padInfo.left,d=1/(t*r);this.userCode=`
const ivec2 pads = ivec2(${p}, ${u});
const float avgMultiplier = float(${d});
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 < ${o};
wR += ${s}) {
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 < ${l};
wC+= ${i}) {
float dyC = float(dyCCorner + wC) / ${a}.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);
}
`}},hee=class{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;let t=e.filterDepth,r=e.filterHeight,n=e.filterWidth,a=e.strideDepth,s=e.strideHeight,i=e.strideWidth,o=e.dilationDepth,l=e.dilationHeight,p=e.dilationWidth,u=e.effectiveFilterDepth,d=e.effectiveFilterHeight,h=e.effectiveFilterWidth,c=u-1-e.padInfo.front,f=d-1-e.padInfo.top,m=h-1-e.padInfo.left,g=1/(t*r*n);this.userCode=`
const ivec3 pads = ivec3(${c}, ${f}, ${m});
const float avgMultiplier = float(${g});
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 < ${u};
wD += ${o}) {
float dyD = float(dyDCorner + wD) / ${a}.0;
if (dyD < 0.0 || dyD >= ${e.outDepth}.0 || fract(dyD) > 0.0) {
continue;
}
int idyD = int(dyD);
for (int wR = 0; wR < ${d};
wR += ${l}) {
float dyR = float(dyRCorner + wR) / ${s}.0;
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||
fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
for (int wC = 0; wC < ${h};
wC += ${p}) {
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 cee(e){let{inputs:t,backend:r,attrs:n}=e,{dy:a,input:s}=t,i=s,{filterSize:o,strides:l,pad:p,dimRoundingMode:u}=n,d=[1,1,1],h=_.computePool3DInfo(i.shape,o,l,d,p,u),c=new hee(h);return r.runWebGLProgram(c,[a],i.dtype)}var fee={kernelName:cd,backendName:"webgl",kernelFunc:cee};function mee(e){let{inputs:t,backend:r,attrs:n}=e,{dy:a,input:s}=t,i=s;lp([a,s],"avgPoolGrad");let{filterSize:o,strides:l,pad:p}=n,u=_.computePool2DInfo(i.shape,o,l,1,p),d=new dee(u);return r.runWebGLProgram(d,[a],i.dtype)}var gee={kernelName:hd,backendName:"webgl",kernelFunc:mee};function yee(e){let{inputs:t,backend:r,attrs:n}=e,{a,b:s}=t,{transposeA:i,transposeB:o}=n;return Lc({a,b:s,transposeA:i,transposeB:o,backend:r})}var bee={kernelName:Pi,backendName:"webgl",kernelFunc:yee},xee=class{constructor(e,t,r,n,a,s){this.outputShape=[],this.variableNames=["x","mean","variance"],_.assertAndGetBroadcastShape(e,t),_.assertAndGetBroadcastShape(e,r);let i="0.0";n!=null&&(_.assertAndGetBroadcastShape(e,n),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");let o="1.0";a!=null&&(_.assertAndGetBroadcastShape(e,a),this.variableNames.push("scale"),o="getScaleAtOutCoords()"),this.outputShape=e,this.userCode=`
void main() {
float x = getXAtOutCoords();
float mean = getMeanAtOutCoords();
float variance = getVarianceAtOutCoords();
float offset = ${i};
float scale = ${o};
float inv = scale * inversesqrt(variance + float(${s}));
setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1)));
}
`}},vee=class{constructor(e,t,r,n,a,s){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],_.assertAndGetBroadcastShape(e,t),_.assertAndGetBroadcastShape(e,r);let i="vec4(0.0)";n!=null&&(_.assertAndGetBroadcastShape(e,n),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");let o="vec4(1.0)";a!=null&&(_.assertAndGetBroadcastShape(e,a),this.variableNames.push("scale"),o="getScaleAtOutCoords()"),this.outputShape=e,this.userCode=`
void main() {
vec4 offset = ${i};
vec4 scale = ${o};
vec4 x = getXAtOutCoords();
vec4 mean = getMeanAtOutCoords();
vec4 variance = getVarianceAtOutCoords();
vec4 inv = scale * inversesqrt(variance + vec4(${s}));
setOutput((x - mean) * inv + offset);
}
`}},wee=({inputs:e,backend:t,attrs:r})=>{let{x:n,mean:a,variance:s,offset:i,scale:o}=e;k.assert(a.shape.length===s.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),k.assert(i==null||a.shape.length===i.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),k.assert(o==null||a.shape.length===o.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let{varianceEpsilon:l}=r;l==null&&(l=.001);let p=[n,a,s],u=null;i!=null&&(u=i.shape,p.push(i));let d=null;o!=null&&(d=o.shape,p.push(o));let h=j().getBool("WEBGL_PACK_NORMALIZATION")?new vee(n.shape,a.shape,s.shape,u,d,l):new xee(n.shape,a.shape,s.shape,u,d,l);return t.runWebGLProgram(h,p,p[0].dtype)},kee={kernelName:no,backendName:"webgl",kernelFunc:wee},Iee=class{constructor(e){this.variableNames=["source"],this.outputShape=e,this.rank=e.length;let t=pt(this.rank);this.customUniforms=[{name:"start",arrayIndex:this.rank,type:"int"}];let r=See(this.rank),n,a=e.map((s,i)=>`sourceLoc.${Jg[i]} = start[${i}] + coords.${Jg[i]};`);n=`
${t} sourceLoc;
${t} coords = getOutputCoords();
${a.join(`
`)}
`,this.userCode=`
void main() {
${n}
setOutput(getSource(${r}));
}
`}},Jg=["x","y","z","w","u","v"];function See(e){if(e===1)return"sourceLoc";if(e<=6)return Jg.slice(0,e).map(t=>"sourceLoc."+t).join(",");throw Error(`Slicing for rank ${e} is not yet supported`)}var Nee=class{constructor(e){this.variableNames=["source"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.rank=e.length,this.customUniforms=[{name:"start",arrayIndex:this.rank,type:"int"}];let t=pt(this.rank),r=gr("coords",this.rank),n=gr("sourceLoc",this.rank),a=this.rank===1?"sourceLoc":`vec2(${n.slice(-2).join()})`,s=`getChannel(getSource(${n.join()}), ${a})`,i=`
result.x = ${s};
if (++${r[this.rank-1]} < ${e[this.rank-1]}) {
++${n[this.rank-1]};
result.y = ${s};
--${n[this.rank-1]};
}
`,o=this.rank===1?"":`
--${r[this.rank-1]};
if (++${r[this.rank-2]} < ${e[this.rank-2]}) {
++${n[this.rank-2]};
result.z = ${s};
if (++${r[this.rank-1]} < ${e[this.rank-1]}) {
++${n[this.rank-1]};
result.w = ${s};
}
}
`,l=this.rank<=4?`sourceLoc = coords +
${t}(${e.map((p,u)=>`start[${u}]`).join()});`:e.map((p,u)=>`${n[u]} = ${r[u]} + start[${u}];`).join(`
`);this.userCode=`
void main() {
${t} coords = getOutputCoords();
${t} sourceLoc;
${l}
vec4 result = vec4(0.);
${i}
${o}
setOutput(result);
}
`}};function _ee(e,t,r,n){let a=n.texData.get(e.dataId),s=n.makeTensorInfo(r,e.dtype),i=n.texData.get(s.dataId);Object.assign(i,a),i.refCount=1,i.shape=r,i.dtype=e.dtype;let o=Wt.computeFlatOffset(t,k.computeStrides(e.shape));a.slice&&(o+=a.slice.flatOffset),i.slice={flatOffset:o,origDataId:a.slice&&a.slice.origDataId||e.dataId};let l=n.dataRefCount.get(i.slice.origDataId)||1;return n.dataRefCount.set(i.slice.origDataId,l+1),s}function mp(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{begin:s,size:i}=n,[o,l]=Wt.parseSliceParams(a,s,i);if(Wt.assertParamsValid(a,o,l),k.sizeFromShape(l)===0)return r.makeTensorInfo(l,a.dtype,[]);if(r.shouldExecuteOnCPU([a])||a.dtype==="string"){let d=r.texData.get(a.dataId),h=gY(d.values,o,l,a.shape,a.dtype);return r.makeTensorInfo(l,a.dtype,h)}let{isPacked:p}=r.texData.get(a.dataId),u=Wt.isSliceContinous(a.shape,o,l);if(p||!u){let d=j().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Nee(l):new Iee(l),h=[o];return r.runWebGLProgram(d,[a],a.dtype,h)}return r.uploadToGPU(a.dataId),_ee(a,o,l,r)}var Tee={kernelName:Pu,backendName:"webgl",kernelFunc:mp},Cee=e=>{let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{blockShape:s,crops:i}=n;k.assert(a.shape.length<=4,()=>"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet");let o=s.reduce((b,x)=>b*x),l=_.getReshaped(a.shape,s,o),p=_.getPermuted(l.length,s.length),u=_.getReshapedPermuted(a.shape,s,o),d=_.getSliceBeginCoords(i,s.length),h=_.getSliceSize(u,i,s.length),c=[],f=ue({inputs:{x:a},backend:r,attrs:{shape:l}}),m=xr({inputs:{x:f},backend:r,attrs:{perm:p}}),g=ue({inputs:{x:m},backend:r,attrs:{shape:u}}),y=mp({inputs:{x:g},backend:r,attrs:{begin:d,size:h}});return c.push(f),c.push(m),c.push(g),c.forEach(b=>r.disposeIntermediateTensorInfo(b)),y},Eee={kernelName:eu,backendName:"webgl",kernelFunc:Cee};function $ee(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,weights:s}=t,{size:i}=n,o=r.readSync(a.dataId),l=r.readSync(s.dataId),p=wC(o,l,s.dtype,s.shape,i);return r.makeTensorInfo([i],s.dtype,p)}var Aee={kernelName:tu,backendName:"webgl",kernelFunc:$ee},Fee=`
int r = int(a.r) & int(b.r);
int g = int(a.g) & int(b.g);
int rb = int(a.b) & int(b.b);
int ra = int(a.a) & int(b.a);
return vec4(r, g, rb, ra);
`,Ree=`
return float(int(a.r) & int(b.r));
`;function Dee(e){let{inputs:t,backend:r}=e,{a:n,b:a}=t,s=j().getBool("WEBGL_PACK_BINARY_OPERATIONS"),i=j().getNumber("WEBGL_VERSION");if(r.shouldExecuteOnCPU([n,a])||i===1){let l=r.texData.get(n.dataId).values,p=r.texData.get(a.dataId).values,[u,d]=B9(n.shape,a.shape,l,p,n.dtype),h=r.makeTensorInfo(d,n.dtype),c=r.texData.get(h.dataId);return c.values=u,h}let o;return s?o=new cp(Fee,n.shape,a.shape,!1):o=new Ni(Ree,n.shape,a.shape),r.runWebGLProgram(o,[n,a],n.dtype)}var Mee={kernelName:ru,backendName:"webgl",kernelFunc:Dee};function Oee(e){let{inputs:t,backend:r}=e,{s0:n,s1:a}=t,s=r.readSync(n.dataId),i=r.readSync(a.dataId),o=_.assertAndGetBroadcastShape(Array.from(s),Array.from(i));return r.makeTensorInfo([o.length],"int32",Int32Array.from(o))}var Lee={kernelName:fd,backendName:"webgl",kernelFunc:Oee},zee="return float(a != b);",LC=lr({opSnippet:zee,cpuKernelImpl:oY,dtype:"bool"}),Pee={kernelName:_u,backendName:"webgl",kernelFunc:LC};function ph(e){let{inputs:t,backend:r}=e,{input:n}=t,a=r.texData.get(n.dataId);return Jr({inputs:{x:a.complexTensorInfos.real},backend:r})}var Bee={kernelName:df,backendName:"webgl",kernelFunc:ph},Wee="return float(int(x));";function Uee(e,t){let r=new aa(e.shape,Wee),n=t.runWebGLProgram(r,[e],"int32");return{dataId:n.dataId,shape:n.shape,dtype:n.dtype}}function Yg(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{dtype:s}=n;if(s==="complex64"){if(a.dtype==="complex64")return Jr({inputs:{x:a},backend:r});let i=It(a.shape),o=Yg({inputs:{x:a},backend:r,attrs:{dtype:"float32"}}),l=Ls({inputs:{real:o,imag:i},backend:r});return i.dispose(),r.disposeIntermediateTensorInfo(o),l}if(a.dtype==="complex64"){let i=ph({inputs:{input:a},backend:r}),o=Yg({inputs:{x:i},backend:r,attrs:{dtype:s}});return r.disposeIntermediateTensorInfo(i),o}if(!k.hasEncodingLoss(a.dtype,s)){let i=Jr({inputs:{x:a},backend:r});return{dataId:i.dataId,shape:i.shape,dtype:s}}if(r.shouldExecuteOnCPU([a])){let i=r.texData.get(a.dataId).values,[o,l,p]=W9(i,a.shape,a.dtype,s);return r.makeTensorInfo(o,l,p)}if(s==="int32")return Uee(a,r);if(s==="bool"){let i=r.makeTensorInfo([],"bool",k.getTypedArrayFromDType("bool",1)),o=LC({inputs:{a,b:i},backend:r});return r.disposeIntermediateTensorInfo(i),o}throw new Error(`Error in Cast: failed to cast ${a.dtype} to ${s}`)}var Vee={kernelName:Bi,backendName:"webgl",kernelFunc:Yg},C1="return ceil(x);",Gee=Ke({opSnippet:C1,packedOpSnippet:C1,cpuKernelImpl:U9}),Hee={kernelName:Wi,backendName:"webgl",kernelFunc:Gee},jee=class{constructor(e){this.variableNames=["A"],this.customUniforms=[{name:"minVal",type:"float"},{name:"maxVal",type:"float"}],this.outputShape=e,this.userCode=`
void main() {
float value = getAAtOutCoords();
if (isnan(value)) {
setOutput(value);
return;
}
setOutput(clamp(value, minVal, maxVal));
}
`}},qee=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"minVal",type:"float"},{name:"maxVal",type:"float"}],this.outputShape=e,this.userCode=`
void main() {
vec4 value = getAAtOutCoords();
if (any(isnan(value))) {
setOutput(value);
return;
}
setOutput(clamp(value, vec4(minVal), vec4(maxVal)));
}
`}};function Kee(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{clipValueMin:s,clipValueMax:i}=n,o;j().getBool("WEBGL_PACK_CLIP")?o=new qee(a.shape):o=new jee(a.shape);let l=[[s],[i]];return r.runWebGLProgram(o,[a],a.dtype,l)}var Xee={kernelName:Cs,backendName:"webgl",kernelFunc:Kee},Zee=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 E1(e,t){return{dataId:t.dataId,dtype:t.dtype,shape:e.shape}}function Jee(e){let{inputs:t,backend:r}=e,{x:n}=t,a=r.texData.get(n.dataId),s=new Zee(n.shape),i=[E1(n,a.complexTensorInfos.real),E1(n,a.complexTensorInfos.imag)];return r.runWebGLProgram(s,i,i[0].dtype)}var Yee={kernelName:md,backendName:"webgl",kernelFunc:Jee},Qee=class{constructor(e){this.outputShape=[],this.outputShape=_.computeOutShape(e,1),this.variableNames=e.map((s,i)=>`T${i}`);let t=new Array(e.length-1);t[0]=e[0][1];for(let s=1;s<t.length;s++)t[s]=t[s-1]+e[s][1];let r=[`if (yC < ${t[0]}) setOutput(getT0(yR, yC));`];for(let s=1;s<t.length;s++){let i=t[s-1];r.push(`else if (yC < ${t[s]}) setOutput(getT${s}(yR, yC-${i}));`)}let n=t.length,a=t[t.length-1];r.push(`else setOutput(getT${n}(yR, yC-${a}));`),this.userCode=`
void main() {
ivec2 coords = getOutputCoords();
int yR = coords.x;
int yC = coords.y;
${r.join(`
`)}
}
`}},ete=class{constructor(e,t){this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[],this.outputShape=_.computeOutShape(e,t);let r=this.outputShape,n=r.length,a=pt(n),s=gr("coords",n),i=["x","y","z","w","u","v"].slice(0,n);this.variableNames=e.map((f,m)=>`T${m}`);let o=new Array(e.length-1);o[0]=e[0][t];for(let f=1;f<o.length;f++)o[f]=o[f-1]+e[f][t];let l=i[t],p=i.slice(-2),u=i.join(),d=`if (${l} < ${o[0]}) {
return getChannel(
getT0(${u}), vec2(${p.join()}));
}`;for(let f=1;f<o.length;f++){let m=o[f-1];d+=`
if (${l} < ${o[f]} && ${l} >= ${o[f-1]}) {
return getChannel(
getT${f}(${Vh(i,l,m)}),
vec2(${Vh(p,l,m)}));
}`}let h=o.length,c=o[o.length-1];d+=`
return getChannel(
getT${h}(${Vh(i,l,c)}),
vec2(${Vh(p,l,c)}));`,this.userCode=`
float getValue(${i.map(f=>"int "+f)}) {
${d}
}
void main() {
${a} coords = getOutputCoords();
vec4 result = vec4(getValue(${s}), 0., 0., 0.);
${s[n-1]} = ${s[n-1]} + 1;
if (${s[n-1]} < ${r[n-1]}) {
result.g = getValue(${s});
}
${s[n-2]} = ${s[n-2]} + 1;
if (${s[n-2]} < ${r[n-2]}) {
result.a = getValue(${s});
}
${s[n-1]} = ${s[n-1]} - 1;
if (${s[n-2]} < ${r[n-2]} &&
${s[n-1]} < ${r[n-1]}) {
result.b = getValue(${s});
}
setOutput(result);
}
`}};function Vh(e,t,r){let n=e.indexOf(t);return e.map((a,s)=>s===n?`${a} - ${r}`:a).join()}function wm(e){let{inputs:t,backend:r}=e,{input:n}=t,a=r.texData.get(n.dataId);return Jr({inputs:{x:a.complexTensorInfos.imag},backend:r})}var tte={kernelName:of,backendName:"webgl",kernelFunc:wm};function Op(e,t,r){let n=e[0].dtype;if(n==="complex64"){let c=e.map(b=>ph({inputs:{input:b},backend:r})),f=e.map(b=>wm({inputs:{input:b},backend:r})),m=Op(c,t,r),g=Op(f,t,r),y=Ls({inputs:{real:m,imag:g},backend:r});return c.forEach(b=>r.disposeIntermediateTensorInfo(b)),f.forEach(b=>r.disposeIntermediateTensorInfo(b)),r.disposeIntermediateTensorInfo(m),r.disposeIntermediateTensorInfo(g),y}let a=r.shouldExecuteOnCPU(e);if(n==="string"&&(a=!0),a){let c=e.map(v=>{let w=[-1,k.sizeFromShape(v.shape.slice(t))];return ue({inputs:{x:v},backend:r,attrs:{shape:w}})}),f=c.map(v=>({vals:r.readSync(v.dataId),shape:v.shape})),m=_.computeOutShape(c.map(v=>v.shape),1),g=c[0].shape[0]===1,y=V9(f,m,n,g),b=_.computeOutShape(e.map(v=>v.shape),t),x=r.makeTensorInfo(b,n,y);return c.forEach(v=>r.disposeIntermediateTensorInfo(v)),x}let s=e.filter(c=>k.sizeFromShape(c.shape)>0),i=j().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&s[0].shape.length>1;if(s.length===1){let c=i?new aa(e[0].shape,Qa):new ss(e[0].shape,Qa);return r.runWebGLProgram(c,e,n)}let o=j().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER");if(s.length>o){let c=[];for(let m=0;m<s.length;m+=o){let g=s.slice(m,m+o);c.push(Op(g,t,r))}let f=Op(c,t,r);for(let m of c)r.disposeIntermediateTensorInfo(m);return f}if(i){let c=new ete(s.map(f=>f.shape),t);return r.runWebGLProgram(c,s,n)}let{tensors2D:l,outShape:p}=rte(s,t,r),u=new Qee(l.map(c=>c.shape)),d=r.runWebGLProgram(u,l,n);l.forEach(c=>r.disposeIntermediateTensorInfo(c));let h=ue({inputs:{x:d},attrs:{shape:p},backend:r});return r.disposeIntermediateTensorInfo(d),h}function rte(e,t,r){let n=_.computeOutShape(e.map(a=>a.shape),t);return{tensors2D:e.map(a=>ue({inputs:{x:a},attrs:{shape:[-1,k.sizeFromShape(a.shape.slice(t))]},backend:r})),outShape:n}}function zC(e){let{inputs:t,backend:r,attrs:n}=e,{axis:a}=n,s=k.parseAxisParam(a,t[0].shape)[0],i=t.map(p=>p.shape);_.assertParamsConsistent(i,s);let o=_.computeOutShape(t.map(p=>p.shape),s);if(k.sizeFromShape(o)===0)return r.makeTensorInfo(o,t[0].dtype,[]);let l=t.filter(p=>k.sizeFromShape(p.shape)>0);return l.length===1?Jr({inputs:{x:l[0]},backend:r}):Op(l,s,r)}var nte={kernelName:nu,backendName:"webgl",kernelFunc:zC},PC=class{constructor(e,t=!1,r=null,n=!1,a=!1){this.variableNames=["x","W"],this.outputShape=e.outShape;let s=e.padInfo.top,i=e.padInfo.left,o=e.strideHeight,l=e.strideWidth,p=e.dilationHeight,u=e.dilationWidth,d=e.filterHeight,h=e.filterWidth,c=Math.floor(e.inChannels/4)*4,f=e.inChannels%4,m=e.dataFormat==="channelsLast",g=m?1:2,y=m?2:3,b=m?3:1,x="",v="";r&&(n?x=`float activation(float a) {
float b = getPreluActivationWeightsAtOutCoords();
${r}
}`:a?x=`float activation(float a) {
float b = getLeakyreluAlphaAtOutCoords();
${r}
}`:x=`
float activation(float x) {
${r}
}
`,v="result = activation(result);");let w=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),n&&this.variableNames.push("preluActivationWeights"),a&&this.variableNames.push("leakyreluAlpha"),this.userCode=`
${x}
const ivec2 strides = ivec2(${o}, ${l});
const ivec2 pads = ivec2(${s}, ${i});
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
int d2 = coords[${b}];
ivec2 xRCCorner =
ivec2(coords[${g}], coords[${y}]) * 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 < ${d}; wR++) {
int xR = xRCorner + wR * ${p};
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int wC = 0; wC < ${h}; wC++) {
int xC = xCCorner + wC * ${u};
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
for (int d1 = 0; d1 < ${c}; 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 (${m}) {
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 (${f===1}) {
if (${m}) {
dotProd +=
getX(batch, xR, xC, ${c}) *
getW(wR, wC, ${c}, d2);
} else {
dotProd +=
getX(batch, ${c}, xR, xC) *
getW(wR, wC, ${c}, d2);
}
} else if (${f===2}) {
vec2 wValues = vec2(
getW(wR, wC, ${c}, d2),
getW(wR, wC, ${c} + 1, d2)
);
if (${m}) {
vec2 xValues = vec2(
getX(batch, xR, xC, ${c}),
getX(batch, xR, xC, ${c} + 1)
);
dotProd += dot(xValues, wValues);
} else {
vec2 xValues = vec2(
getX(batch, ${c}, xR, xC),
getX(batch, ${c} + 1, xR, xC)
);
dotProd += dot(xValues, wValues);
}
} else if (${f===3}) {
vec3 wValues = vec3(
getW(wR, wC, ${c}, d2),
getW(wR, wC, ${c} + 1, d2),
getW(wR, wC, ${c} + 2, d2)
);
if (${m}) {
vec3 xValues = vec3(
getX(batch, xR, xC, ${c}),
getX(batch, xR, xC, ${c} + 1),
getX(batch, xR, xC, ${c} + 2)
);
dotProd += dot(xValues, wValues);
} else {
vec3 xValues = vec3(
getX(batch, ${c}, xR, xC),
getX(batch, ${c} + 1, xR, xC),
getX(batch, ${c} + 2, xR, xC)
);
dotProd += dot(xValues, wValues);
}
}
}
}
float result = dotProd;
${w}
${v}
setOutput(result);
}
`}},ate=class{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;let t=e.padInfo.front,r=e.padInfo.top,n=e.padInfo.left,a=e.strideDepth,s=e.strideHeight,i=e.strideWidth,o=e.dilationDepth,l=e.dilationHeight,p=e.dilationWidth,u=e.filterDepth,d=e.filterHeight,h=e.filterWidth,c=Math.floor(e.inChannels/4)*4,f=e.inChannels%4;this.userCode=`
const ivec3 strides = ivec3(${a}, ${s}, ${i});
const ivec3 pads = ivec3(${t}, ${r}, ${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 < ${u}; wF++) {
int xF = xFCorner + wF * ${o};
if (xF < 0 || xF >= ${e.inDepth}) {
continue;
}
for (int wR = 0; wR < ${d}; wR++) {
int xR = xRCorner + wR * ${l};
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int wC = 0; wC < ${h}; wC++) {
int xC = xCCorner + wC * ${p};
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
for (int d1 = 0; d1 < ${c}; 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 (${f===1}) {
dotProd +=
getX(batch, xF, xR, xC, ${c}) *
getW(wF, wR, wC, ${c}, d2);
} else if (${f===2}) {
vec2 xValues = vec2(
getX(batch, xF, xR, xC, ${c}),
getX(batch, xF, xR, xC, ${c} + 1)
);
vec2 wValues = vec2(
getW(wF, wR, wC, ${c}, d2),
getW(wF, wR, wC, ${c} + 1, d2)
);
dotProd += dot(xValues, wValues);
} else if (${f===3}) {
vec3 xValues = vec3(
getX(batch, xF, xR, xC, ${c}),
getX(batch, xF, xR, xC, ${c} + 1),
getX(batch, xF, xR, xC, ${c} + 2)
);
vec3 wValues = vec3(
getW(wF, wR, wC, ${c}, d2),
getW(wF, wR, wC, ${c} + 1, d2),
getW(wF, wR, wC, ${c} + 2, d2)
);
dotProd += dot(xValues, wValues);
}
}
}
}
setOutput(dotProd);
}
`}},BC=class{constructor(e,t=!1,r=null,n=!1,a=!1){this.variableNames=["x","W"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"pads",type:"ivec2"},{name:"strides",type:"ivec2"},{name:"dilations",type:"ivec2"},{name:"inDims",type:"ivec2"}],this.outputShape=e.outShape,this.enableShapeUniforms=hr(this.outputShape.length);let s=e.padInfo.left,i=e.strideWidth,o=e.dilationWidth,l=e.filterHeight,p=e.filterWidth,u=p,d=`
int xR; int xC; int xCOffset;
vec4 wTexel; vec4 previous; vec4 final;`;for(let m=0;m<p;m++)d+=`
vec4 xTexelC${m*2};
int xTexelC${m*2}Ready;
vec4 xTexelC${m*2+1};
int xTexelC${m*2+1}Ready;
vec4 xC${m};`;d+=`
for (int r = 0; r < ${l}; r++) {
for (int d1 = 0; d1 < ${e.inChannels}; d1 += 2) {
`;for(let m=0;m<p;m++)d+=`
xTexelC${m*2} = vec4(0.0);
xTexelC${m*2}Ready = 0;
xTexelC${m*2+1} = vec4(0.0);
xTexelC${m*2+1}Ready = 0;
xC${m} = vec4(0.0);`;d+=`
xR = xRCorner + r * dilations[0];
if (xR >=0 && xR < inDims[0]) {
`;for(let m=0;m<(u+1)/2;m++){let g=m*2;if(d+=`
xC = xCCorner + ${g*o};
`,i===1){if(g<p&&(s%2===1?(d+=`
xCOffset = xC + 1;
if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${g}Ready == 0) {
xTexelC${g} = getX(batch, xR, xCOffset, d1);
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if (xCOffset + 1 >= inDims[1]) {
xTexelC${g}.zw = vec2(0.0);
}
xTexelC${g}Ready = 1;
}
`,o===1&&g>0?d+=`
xC${g} = vec4(xTexelC${g-2}.zw, xTexelC${g}.xy);
`:d+=`
xCOffset = xC + 1 - 2;
if (xCOffset >= 0 && xCOffset < inDims[1]) {
previous = getX(batch, xR, xCOffset, d1);
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if (xCOffset + 1 >= inDims[1]) {
previous.zw = vec2(0.0);
}
xC${g} = vec4(previous.zw, xTexelC${g}.xy);
} else {
xC${g} = vec4(0.0, 0.0, xTexelC${g}.xy);
}
`):d+=`
if (xC >= 0 && xC < inDims[1] && xTexelC${g}Ready == 0) {
xTexelC${g} = getX(batch, xR, xC, d1);
if (xC + 1 >= inDims[1]) {
xTexelC${g}.zw = vec2(0.0);
}
xTexelC${g}Ready = 1;
}
xC${g} = xTexelC${g};
`,g+1<p)){let y=s%2===0?k.nearestLargerEven(o):o;o%2===0&&s%2===1||o%2!==0&&s%2!==1?(d+=`
xCOffset = xC + imod(pads[1], 2) + ${y};
if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${g+1}Ready == 0) {
xTexelC${g+1} = getX(batch, xR, xCOffset, d1);
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if (xCOffset + 1 >= inDims[1]) {
xTexelC${g+1}.zw = vec2(0.0);
}
xTexelC${g+1}Ready = 1;
}
`,o>1?d+=`
xCOffset -= 2;
if (xCOffset >= 0 && xCOffset < inDims[1]) {
previous = getX(batch, xR, xCOffset, d1);
xC${g+1} = vec4(previous.zw, xTexelC${g+1}.xy);
} else {
xC${g+1} = vec4(0.0, 0.0, xTexelC${g+1}.xy);
}
`:d+=`
xC${g+1} = vec4(xTexelC${g}.zw, xTexelC${g+1}.xy);
`):y===1?d+=`
xC${g+1} = xTexelC${g};
`:d+=`
xCOffset = xC + ${y};
if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${g+1}Ready == 0) {
xTexelC${g+1} = getX(batch, xR, xCOffset, d1);
if (xCOffset + 1 >= inDims[1]) {
xTexelC${g+1}.zw = vec2(0.0);
}
xTexelC${g+1}Ready = 1;
}
xC${g+1} = xTexelC${g+1};
`}}else g<p&&(s%2===1?(d+=`
xCOffset = xC + 1 - strides[1];
if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${g}Ready == 0) {
xTexelC${g} = getX(batch, xR, xCOffset, d1);
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if (xCOffset + 1 >= inDims[1]) {
xTexelC${g}.zw = vec2(0.0);
}
xTexelC${g}Ready = 1;
}
if(xC + 1 >= 0 && xC + 1 < inDims[1] && xTexelC${g+1}Ready == 0) {
xTexelC${g+1} = getX(batch, xR, xC + 1, d1);
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if (xC + 2 >= inDims[1]) {
xTexelC${g+1}.zw = vec2(0.0);
}
xTexelC${g+1}Ready = 1;
}
xC${g} = vec4(xTexelC${g}.zw, xTexelC${g+1}.zw);
`,g+1<p&&(d+=`
final = vec4(0.0);
xCOffset = xC + 1 + strides[1];
if(xCOffset >= 0 && xCOffset < inDims[1]) {
final = getX(batch, xR, xCOffset, d1);
}
xC${g+1} = vec4(xTexelC${g+1}.xy, final.xy);
`)):(d+=`
if(xC >= 0 && xC < inDims[1] && xTexelC${g}Ready == 0) {
xTexelC${g} = getX(batch, xR, xC, d1);
if (xC + 1 >= inDims[1]) {
xTexelC${g}.zw = vec2(0.0);
}
xTexelC${g}Ready = 1;
}
xCOffset = xC + strides[1];
if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${g+1}Ready == 0) {
xTexelC${g+1} = getX(batch, xR, xCOffset, d1);
if (xCOffset + 1 >= inDims[1]) {
xTexelC${g+1}.zw = vec2(0.);
}
xTexelC${g+1}Ready = 1;
}
xC${g} = vec4(
xTexelC${g}.xy, xTexelC${g+1}.xy);
`,g+1<p&&(d+=`
xC${g+1} = vec4(xTexelC${g}.zw, xTexelC${g+1}.zw);
`)));g<p&&(d+=`
wTexel = getW(r, ${g}, d1, d2);
dotProd += xC${g}.xxzz * vec4(wTexel.xy, wTexel.xy);
if(d1 + 1 < ${e.inChannels}) {
dotProd += xC${g}.yyww * vec4(wTexel.zw, wTexel.zw);
}
`,g+1<p&&(d+=`
wTexel = getW(r, ${g+1}, d1, d2);
dotProd += xC${g+1}.xxzz * vec4(wTexel.xy, wTexel.xy);
if(d1 + 1 < ${e.inChannels}) {
dotProd += xC${g+1}.yyww * vec4(wTexel.zw, wTexel.zw);
}
`))}d+=`
}
`,d+=`
}
`,d+=`
}
`;let h="",c="";r&&(n?h=`vec4 activation(vec4 a) {
vec4 b = getPreluActivationWeightsAtOutCoords();
${r}
}`:a?h=`vec4 activation(vec4 a) {
vec4 b = getLeakyreluAlphaAtOutCoords();
${r}
}`:h=`vec4 activation(vec4 x) {
${r}
}`,c="result = activation(result);");let f=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),n&&this.variableNames.push("preluActivationWeights"),a&&this.variableNames.push("leakyreluAlpha"),this.userCode=`
${h}
void main() {
ivec4 coords = getOutputCoords();
int batch = coords.x;
ivec2 xRCCorner = coords.yz * strides - pads;
int d2 = coords.w;
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
//intialize dotProd with a small epsilon seems to reduce GPU accuracy loss.
vec4 dotProd = vec4(0.000000000000001);
${d}
vec4 result = dotProd - vec4(0.000000000000001);
${f}
${c}
setOutput(result);
}
`}},ste=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"inputShape",type:"ivec4"},{name:"pad",type:"ivec2"},{name:"stride",type:"ivec2"},{name:"dilation",type:"ivec2"},{name:"inChannels",type:"int"},{name:"itemsPerBlockRow",type:"int"},{name:"outWidth",type:"int"}],this.outputShape=e,this.enableShapeUniforms=hr(this.outputShape.length);let{dataFormat:r}=t,n=Sr(),a=r==="channelsLast",s=a?1:2,i=a?2:3,o=this.enableShapeUniforms?"if(blockIndex < outShape[2] && pos < outShape[1]) {":`if(blockIndex < ${e[2]} && pos < ${e[1]}) {`,l="";for(let p=0;p<=1;p++)for(let u=0;u<=1;u++)l+=`
blockIndex = rc.z + ${u};
pos = rc.y + ${p};
${o}
offsetY = int(blockIndex / outWidth) * stride[0] - pad[0];
d0 = offsetY + dilation[0] * (pos / itemsPerBlockRow);
if(d0 < inputShape[${s}] && d0 >= 0) {
// Use custom imod instead mod. On Intel GPU, mod may generate
// unexpected value.
// https://github.com/tensorflow/tfjs/issues/5447
offsetX = imod(blockIndex, outWidth) * stride[1] - pad[1];
d1 = offsetX + dilation[1] * (imod(pos, itemsPerBlockRow) /
inChannels);
if(d1 < inputShape[${i}] && d1 >= 0) {
ch = imod(pos, inChannels);
if (${a}) {
innerDims = vec2(d1, ch);
result[${p*2+u}] = getChannel(
getA(rc.x, d0, int(innerDims.x),
int(innerDims.y)), innerDims);
} else {
innerDims = vec2(d0, d1);
result[${p*2+u}] = getChannel(
getA(rc.x, ch, int(innerDims.x),
int(innerDims.y)), innerDims);
}
}
}
}
`;this.userCode=`
void main() {
ivec3 rc = getOutputCoords();
vec4 result = vec4(0);
int blockIndex, pos, offsetY, d0, offsetX, d1, ch;
vec2 innerDims;
${l}
${n.output} = result;
}
`}};function zc(e,t){let r=e.length;return r>=3?t?[...e.slice(0,-3),e[r-3]*e[r-2],e[r-1]]:[...e.slice(0,-3),e[r-3],e[r-2]*e[r-1]]:!t&&r===1&&e[0]>1?[e[0],1]:null}function WC({x:e,filter:t,convInfo:r,backend:n,bias:a=null,preluActivationWeights:s=null,leakyreluAlpha:i=0,activation:o=null}){let l=e.shape,p=n.texData.get(e.dataId),u=r.inChannels,d=l[0]*l[1]*l[2],h=r.outChannels,c=r.dataFormat==="channelsLast",f=!1,m=!1,g,y=[];if(s!=null){let b=zc(s.shape,c);b!=null&&(s=ue({inputs:{x:s},backend:n,attrs:{shape:b}}),y.push(s))}if(a!=null){let b=zc(a.shape,c);b!=null&&(a=ue({inputs:{x:a},backend:n,attrs:{shape:b}}),y.push(a))}if(!((d===1||h===1)&&u>RC)&&p.isPacked&&c&&p.texture!=null&&l[2]%2!==0&&k.arraysEqual(p.shape.slice(-3),l.slice(-3))){let b=l[0]*l[1]*(l[2]+1),x={dataId:e.dataId,shape:[1,b,r.inChannels],dtype:e.dtype},v=p.shape;p.shape=p.shape.slice(),p.shape[p.shape.length-2]++,k.assert(sd(p.shape,x.shape),()=>`packed reshape ${p.shape} to ${x.shape} isn't free`);let w=ue({inputs:{x:t},backend:n,attrs:{shape:[1,r.inChannels,r.outChannels]}});y.push(w);let N=Lc({a:x,b:w,backend:n,transposeA:f,transposeB:m,bias:a,activation:o,preluActivationWeights:s,leakyreluAlpha:i}),T=n.texData.get(N.dataId);k.assert(T.isPacked,()=>"batchMatMul result is expected to be packed"),p.shape=v,T.shape=r.outShape,g=Jr({inputs:{x:N},backend:n}),g.shape=r.outShape,y.push(N)}else{let b=r.outHeight*r.outWidth,x=ue({inputs:{x:e},backend:n,attrs:{shape:c?[r.batchSize,b,r.inChannels]:[r.batchSize,r.inChannels,b]}}),v=ue({inputs:{x:t},backend:n,attrs:{shape:[1,r.inChannels,r.outChannels]}}),w=Lc({a:c?x:v,b:c?v:x,transposeA:!c,transposeB:m,backend:n,bias:a,activation:o,preluActivationWeights:s,leakyreluAlpha:i});g=ue({inputs:{x:w},backend:n,attrs:{shape:r.outShape}}),y.push(x),y.push(v),y.push(w)}for(let b of y)n.disposeIntermediateTensorInfo(b);return g}function UC({x:e,filter:t,convInfo:r,backend:n,bias:a=null,preluActivationWeights:s=null,leakyreluAlpha:i=0,activation:o=null}){let{filterWidth:l,filterHeight:p,inChannels:u,outWidth:d,outHeight:h,dataFormat:c}=r,f=c==="channelsLast",m=l*p*u,g=h*d,y=[r.batchSize,m,g],b=!0,x=!1,v=[];if(s!=null){let G=zc(s.shape,f);G!=null&&(s=ue({inputs:{x:s},backend:n,attrs:{shape:G}}),v.push(s))}if(a!=null){let G=zc(a.shape,f);G!=null&&(a=ue({inputs:{x:a},backend:n,attrs:{shape:G}}),v.push(a))}let w=ue({inputs:{x:t},backend:n,attrs:{shape:[1,m,k.sizeFromShape(t.shape)/m]}});v.push(w);let N=new ste(y,r),T=[e.shape,[r.padInfo.top,r.padInfo.left],[r.strideHeight,r.strideWidth],[r.dilationHeight,r.dilationWidth],[r.inChannels],[r.filterWidth*r.inChannels],[r.outWidth]],E=n.runWebGLProgram(N,[e],"float32",T),$=ue({inputs:{x:E},backend:n,attrs:{shape:y}});v.push(E),v.push($);let R=a!=null,F=s!=null,S=o==="leakyrelu",D=o?id(o,!0):null,P=new FC(f?$.shape:w.shape,f?w.shape:$.shape,f?[r.batchSize,g,r.outChannels]:[r.batchSize,r.outChannels,g],b,x,R,D,F,S),U=f?[$,w]:[w,$];if(a&&U.push(a),F&&U.push(s),S){let G=n.makeTensorInfo([],"float32",k.createScalarValue(i,"float32"));U.push(G),v.push(G)}let H=n.runWebGLProgram(P,U,"float32"),q=ue({inputs:{x:H},backend:n,attrs:{shape:r.outShape}});v.push(H);for(let G of v)n.disposeIntermediateTensorInfo(G);return q}function ite(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,filter:s}=t,{strides:i,pad:o,dataFormat:l,dilations:p,dimRoundingMode:u}=n,d=_.convertConv2DDataFormat(l),h=_.computeConv2DInfo(a.shape,s.shape,i,p,o,u,!1,d),c;if(h.filterHeight===1&&h.filterWidth===1&&h.dilationHeight===1&&h.dilationWidth===1&&h.strideHeight===1&&h.strideWidth===1&&(h.padInfo.type==="SAME"||h.padInfo.type==="VALID"))c=WC({x:a,filter:s,convInfo:h,backend:r});else if(h.strideWidth<=2&&d==="channelsLast"&&j().getBool("WEBGL_EXP_CONV")){let m=new BC(h),g=[[h.padInfo.top,h.padInfo.left],[h.strideHeight,h.strideWidth],[h.dilationHeight,h.dilationWidth],[h.inHeight,h.inWidth]];c=r.runWebGLProgram(m,[a,s],"float32",g)}else if(j().getBool("WEBGL_CONV_IM2COL"))c=UC({x:a,filter:s,convInfo:h,backend:r});else{let m=new PC(h);c=r.runWebGLProgram(m,[a,s],"float32")}let f=ue({inputs:{x:c},backend:r,attrs:{shape:h.outShape}});return r.disposeIntermediateTensorInfo(c),f}var ote={kernelName:Ui,backendName:"webgl",kernelFunc:ite},lte=class{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;let t=e.strideHeight,r=e.strideWidth,n=e.padInfo.top,a=e.padInfo.left,s=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 * ${r} - ${a};
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
${s?`float dyValue = getDy(b, yR, yC, d2);
float xValue = getX(b, xR, xC, d1);
dotProd += (xValue * dyValue);`:`float dyValue = getDy(b, d2, yR, yC);
float xValue = getX(b, d1, xR, xC);
dotProd += (xValue * dyValue);`}
}
}
}
setOutput(dotProd);
}
`}},ute=class{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;let t=e.filterHeight,r=e.filterWidth,n=e.strideHeight,a=e.strideWidth,s=e.dataFormat==="channelsLast",i=t-1-e.padInfo.top,o=r-1-e.padInfo.left,l=s?1:2,p=s?2:3,u=s?3:1;this.userCode=`
const ivec2 pads = ivec2(${i}, ${o});
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
int d1 = coords[${u}];
ivec2 dyCorner = ivec2(coords[${l}], coords[${p}]) - 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 < ${r}; wC++) {
float dyC = float(dyCCorner + wC) / ${a}.0;
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
int wCPerm = ${r} - 1 - wC;
for (int d2 = 0; d2 < ${e.outChannels}; d2++) {
if (${s}) {
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);
}
`}},pte=class{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;let t=e.strideDepth,r=e.strideHeight,n=e.strideWidth,a=e.padInfo.front,s=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} - ${a};
if (xF < 0 || xF >= ${e.inDepth}) {
continue;
}
for (int yR = 0; yR < ${e.outHeight}; yR++) {
int xR = wR + yR * ${r} - ${s};
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);
}
`}},dte=class{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;let t=e.filterDepth,r=e.filterHeight,n=e.filterWidth,a=e.strideDepth,s=e.strideHeight,i=e.strideWidth,o=t-1-e.padInfo.front,l=r-1-e.padInfo.top,p=n-1-e.padInfo.left;this.userCode=`
const ivec3 pads = ivec3(${o}, ${l}, ${p});
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) / ${a}.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 < ${r}; wR++) {
float dyR = float(dyRCorner + wR) / ${s}.0;
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||
fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
int wRPerm = ${r} - 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 hte(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,dy:s}=t,{strides:i,pad:o,dataFormat:l,dimRoundingMode:p,filterShape:u}=n,d=_.convertConv2DDataFormat(l),h=_.computeConv2DInfo(a.shape,u,i,1,o,p,!1,d),c=new lte(h);return r.runWebGLProgram(c,[a,s],"float32")}var cte={kernelName:Qc,backendName:"webgl",kernelFunc:hte},fte=class{constructor(e){this.variableNames=["dy","W"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"strides",type:"vec2"}],this.outputShape=e.inShape,this.enableShapeUniforms=hr(this.outputShape.length);let t=e.filterHeight,r=e.filterWidth,n=t-1-e.padInfo.top,a=r-1-e.padInfo.left;this.userCode=`
const ivec2 pads = ivec2(${n}, ${a});
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
int d1 = coords[3];
ivec2 dyCorner = ivec2(coords[1], coords[2]) - pads;
int dyRCorner = dyCorner.x;
int dyCCorner = dyCorner.y;
vec4 result = vec4(0.);
for (int wR = 0; wR < ${t}; wR++) {
float dyR = float(dyRCorner + wR) / strides[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 < ${r}; wC++) {
int wCPerm = ${r} - 1 - wC;
float dyC = float(dyCCorner + wC) / strides[1];
bool idyCVal = (dyC >= 0.0) && (dyC < ${e.outWidth}.0)
&& (fract(dyC) == 0.0);
int idyC = int(dyC);
float dyC2 = float(dyCCorner + wC + 1) / strides[1];
bool idyCVal2 = (dyC2 >= 0.0) && (dyC2 < ${e.outWidth}.0)
&& (fract(dyC2) == 0.0);
int idyC2 = int(dyC2);
if (idyCVal && idyCVal2) {
for (int d2 = 0; d2 < ${e.outChannels}; d2 += 2) {
vec4 wValue = getW(wRPerm, wCPerm, d1, d2);
vec4 dySample = getDy(batch, idyR, idyC, d2);
vec4 dySample2 = (idyC / 2 == idyC2 / 2) ?
dySample : getDy(batch, idyR, idyC2, d2);
vec2 dyValue = mod(float(idyC), 2.) == 0. ?
dySample.xy : dySample.zw;
result.xy += vec2(dot(dyValue, wValue.xy),
dot(dyValue, wValue.zw));
dyValue = mod(float(idyC2), 2.) == 0. ?
dySample2.xy : dySample2.zw;
result.zw += vec2(dot(dyValue, wValue.xy),
dot(dyValue, wValue.zw));
}
} else if (idyCVal) {
for (int d2 = 0; d2 < ${e.outChannels}; d2 += 2) {
vec4 wValue = getW(wRPerm, wCPerm, d1, d2);
vec4 dySample = getDy(batch, idyR, idyC, d2);
vec2 dyValue = mod(float(idyC), 2.) == 0. ?
dySample.xy : dySample.zw;
result.xy += vec2(dot(dyValue, wValue.xy),
dot(dyValue, wValue.zw));
}
} else if (idyCVal2) {
for (int d2 = 0; d2 < ${e.outChannels}; d2 += 2) {
vec4 wValue = getW(wRPerm, wCPerm, d1, d2);
vec4 dySample = getDy(batch, idyR, idyC2, d2);
vec2 dyValue = mod(float(idyC2), 2.) == 0. ?
dySample.xy : dySample.zw;
result.zw += vec2(dot(dyValue, wValue.xy),
dot(dyValue, wValue.zw));
}
}
}
}
setOutput(result);
}
`}};function mte(e){let{inputs:t,backend:r,attrs:n}=e,{dy:a,filter:s}=t,{inputShape:i,strides:o,pad:l,dataFormat:p,dimRoundingMode:u}=n,d=_.convertConv2DDataFormat(p),h=_.computeConv2DInfo(i,s.shape,o,1,l,u,!1,d);if(j().getBool("WEBGL_PACK_CONV2DTRANSPOSE")&&d==="channelsLast"){let c=[[h.strideHeight,h.strideWidth]],f=new fte(h);return r.runWebGLProgram(f,[a,s],"float32",c)}else{let c=new ute(h);return r.runWebGLProgram(c,[a,s],"float32")}}var gte={kernelName:Vi,backendName:"webgl",kernelFunc:mte};function yte(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,filter:s}=t,{strides:i,pad:o,dilations:l}=n,p=_.computeConv3DInfo(a.shape,s.shape,i,l,o),u=new ate(p);return r.runWebGLProgram(u,[a,s],"float32")}var bte={kernelName:Gi,backendName:"webgl",kernelFunc:yte};function xte(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,dy:s}=t,{strides:i,pad:o,filterShape:l}=n,p=_.computeConv3DInfo(a.shape,l,i,1,o),u=new pte(p);return r.runWebGLProgram(u,[a,s],"float32")}var vte={kernelName:au,backendName:"webgl",kernelFunc:xte};function wte(e){let{inputs:t,backend:r,attrs:n}=e,{dy:a,filter:s}=t,{pad:i,strides:o,inputShape:l}=n,p=_.computeConv3DInfo(l,s.shape,o,1,i),u=new dte(p);return r.runWebGLProgram(u,[a,s],"float32")}var kte={kernelName:su,backendName:"webgl",kernelFunc:wte},Ite=fp+`
return cos(x);
`,Ste=`
vec4 result = cos(x);
bvec4 isNaN = isnan(x);
${al}
return result;
`,Nte=Ke({opSnippet:Ite,packedOpSnippet:Ste}),_te={kernelName:Hi,backendName:"webgl",kernelFunc:Nte},Tte=`
float e2x = exp(-x);
return (e2x + 1.0 / e2x) / 2.0;
`,Cte=Ke({opSnippet:Tte}),Ete={kernelName:ji,backendName:"webgl",kernelFunc:Cte},$te=class{constructor(e,t,r,n,a){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];let[s,i,o,l]=e,[p]=t,[u,d]=r;this.outputShape=[p,u,d,l];let h=n==="bilinear"?1:0,[c,f]=[`${i-1}.0`,`${o-1}.0`],[m,g,y]=u>1?[`${(i-1)/(u-1)}`,"(y2-y1) * height_ratio",`y1*${c} + float(y)*(height_scale)`]:["0.0","0.0",`0.5 * (y1+y2) * ${c}`],[b,x,v]=d>1?[`${(o-1)/(d-1)}`,"(x2-x1) * width_ratio",`x1*${f} + float(x)*(width_scale)`]:["0.0","0.0",`0.5 * (x1+x2) * ${f}`];this.userCode=`
const float height_ratio = float(${m});
const float width_ratio = float(${b});
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 >= ${s}) {
return;
}
float height_scale = ${g};
float width_scale = ${x};
float in_y = ${y};
if( in_y < 0.0 || in_y > ${c} ) {
setOutput(float(${a}));
return;
}
float in_x = ${v};
if( in_x < 0.0 || in_x > ${f} ) {
setOutput(float(${a}));
return;
}
vec2 sourceFracIndexCR = vec2(in_x,in_y);
if(${h} == 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);
}
}
`}},Ate=e=>{let{inputs:t,backend:r,attrs:n}=e,{image:a,boxes:s,boxInd:i}=t,{cropSize:o,method:l,extrapolationValue:p}=n,u=new $te(a.shape,s.shape,o,l,p);return r.runWebGLProgram(u,[a,s,i],"float32")},Fte={kernelName:ou,backendName:"webgl",kernelFunc:Ate},ld;(function(e){e.Prod="*",e.Sum="+"})(ld||(ld={}));var $1=class{constructor(e,t,r,n){this.op=e,this.outputShape=t,this.variableNames=["x"],this.customUniforms=[{name:"index",type:"float"}];let a=this.outputShape.length,s=this.op===ld.Prod?"1.0":"0.0",i=r?s:`getX(${A1(a,"coords",this.op)})`,o=this.outputShape[this.outputShape.length-1],l="",p="";r?(l=n?`end != ${o-1}`:"end != 0",p=n?"end + 1":"end - 1"):(l=n?`end + pow2 < ${o}`:"end >= pow2",p=n?"end + pow2":"end - pow2"),this.userCode=`
void main() {
${pt(a)} coords = getOutputCoords();
int end = ${F1(a,"coords",this.op)};
float val = ${i};
int pow2 = int(pow(2.0, index));
if (${l}) {
int idx = ${p};
${F1(a,"coords",this.op)} = idx;
val ${this.op}= getX(${A1(a,"coords",this.op)});
}
setOutput(val);
}
`}};function A1(e,t,r){if(e===1)return`${t}`;if(e===2)return`${t}.x, ${t}.y`;if(e===3)return`${t}.x, ${t}.y, ${t}.z`;if(e===4)return`${t}.x, ${t}.y, ${t}.z, ${t}.w`;throw new Error(`Cumulative ${r} for rank ${e} is not yet supported`)}function F1(e,t,r){if(e===1)return`${t}`;if(e===2)return`${t}.y`;if(e===3)return`${t}.z`;if(e===4)return`${t}.w`;throw new Error(`Cumulative ${r} for rank ${e} is not yet supported`)}function VC(e,t,r,n,a,s){let i=t.shape.length,o=_.getAxesPermutation([n],i),l=t;o!=null&&(l=xr({inputs:{x:t},backend:r,attrs:{perm:o}}));let p=_.getInnerMostAxes(1,i)[0];if(p!==i-1)throw new Error(`WebGL cumprod shader expects an inner-most axis=${t.shape.length-1} but got axis=${n}`);let u=l.shape[p],d=Jr({inputs:{x:l},backend:r});for(let h=0;h<=Math.ceil(Math.log2(u))-1;h++){let c=new $1(e,l.shape,!1,s),f=[[h]],m=d;d=r.runWebGLProgram(c,[d],d.dtype,f),r.disposeIntermediateTensorInfo(m)}if(a){let h=new $1(e,l.shape,a,s),c=d;d=r.runWebGLProgram(h,[d],d.dtype),r.disposeIntermediateTensorInfo(c)}if(o!=null){let h=_.getUndoAxesPermutation(o),c=xr({inputs:{x:d},backend:r,attrs:{perm:h}});return r.disposeIntermediateTensorInfo(d),r.disposeIntermediateTensorInfo(l),c}return d}function Rte(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{axis:s,exclusive:i,reverse:o}=n;return VC(ld.Prod,a,r,s,i,o)}var Dte={kernelName:iu,backendName:"webgl",kernelFunc:Rte};function Mte(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{axis:s,exclusive:i,reverse:o}=n;return VC(ld.Sum,a,r,s,i,o)}var Ote={kernelName:qi,backendName:"webgl",kernelFunc:Mte};function Lte(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,weights:s}=t,{size:i,binaryOutput:o}=n;if(a.shape.length===1){let l=r.readSync(a.dataId),p=r.readSync(s.dataId),u=wC(l,p,s.dtype,s.shape,i);return r.makeTensorInfo([i],s.dtype,u)}else if(a.shape.length===2){let l=r.bufferSync(a),p=r.bufferSync(s),u=P9(l,p,i,o);return r.makeTensorInfo(u.shape,s.dtype,u.values)}throw new Error(`Error in denseBincount: input must be at most rank 2, but got rank${a.shape.length}.`)}var zte={kernelName:gd,backendName:"webgl",kernelFunc:Lte},Pte=class{constructor(e,t,r){this.variableNames=["x"],this.outputShape=[],this.outputShape=e,this.blockSize=t,this.dataFormat=r,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 Bte(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{blockSize:s,dataFormat:i}=n,o=a.shape[0],l=i==="NHWC"?a.shape[1]:a.shape[2],p=i==="NHWC"?a.shape[2]:a.shape[3],u=i==="NHWC"?a.shape[3]:a.shape[1],d=l*s,h=p*s,c=u/(s*s),f=i==="NHWC"?[o,d,h,c]:[o,c,d,h],m=new Pte(f,s,i);return r.runWebGLProgram(m,[a],a.dtype)}var Wte={kernelName:lu,backendName:"webgl",kernelFunc:Bte},GC=class{constructor(e,t=!1,r=null,n=!1,a=!1){this.variableNames=["x","W"],this.customUniforms=[{name:"pads",type:"ivec2"},{name:"strides",type:"ivec2"},{name:"dilations",type:"ivec2"},{name:"inDims",type:"ivec2"}],this.outputShape=e.outShape,this.enableShapeUniforms=hr(this.outputShape.length);let s=e.filterHeight,i=e.filterWidth,o=e.outChannels/e.inChannels,l="",p="";r&&(n?l=`float activation(float a) {
float b = getPreluActivationWeightsAtOutCoords();
${r}
}`:a?l=`float activation(float a) {
float b = getLeakyreluAlphaAtOutCoords();
${r}
}`:l=`
float activation(float x) {
${r}
}
`,p="result = activation(result);");let u=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),n&&this.variableNames.push("preluActivationWeights"),a&&this.variableNames.push("leakyreluAlpha"),this.userCode=`
${l}
void main() {
ivec4 coords = getOutputCoords();
int batch = coords.x;
ivec2 xRCCorner = coords.yz * strides - pads;
int d2 = coords.w;
int d1 = d2 / ${o};
int q = d2 - d1 * ${o};
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 < ${s}; wR++) {
int xR = xRCorner + wR * dilations[0];
if (xR < 0 || xR >= inDims[0]) {
continue;
}
for (int wC = 0; wC < ${i}; wC++) {
int xC = xCCorner + wC * dilations[1];
if (xC < 0 || xC >= inDims[1]) {
continue;
}
float xVal = getX(batch, xR, xC, d1);
float wVal = getW(wR, wC, d1, q);
dotProd += xVal * wVal;
}
}
float result = dotProd;
${u}
${p}
setOutput(result);
}
`}},HC=class{constructor(e,t=!1,r=null,n=!1,a=!1){this.variableNames=["x","W"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"pads",type:"ivec2"},{name:"strides",type:"ivec2"},{name:"dilations",type:"ivec2"},{name:"inDims",type:"ivec2"}],this.outputShape=e.outShape,this.enableShapeUniforms=hr(this.outputShape.length);let s=e.outChannels/e.inChannels,i=e.padInfo.left,o=e.strideWidth,l=e.dilationWidth,p=e.filterHeight,u=e.filterWidth,d=u,h=`
int xR; int xC; int xCOffset;
vec4 wTexel; vec4 previous; vec4 final;`;for(let g=0;g<u;g++)h+=`
vec4 xTexelC${g*2};
int xTexelC${g*2}Ready;
vec4 xTexelC${g*2+1};
int xTexelC${g*2+1}Ready;
vec4 xC${g};`;h+=`
for (int r = 0; r < ${p}; r++) {
`;for(let g=0;g<u;g++)h+=`
xTexelC${g*2} = vec4(0.0);
xTexelC${g*2}Ready = 0;
xTexelC${g*2+1} = vec4(0.0);
xTexelC${g*2+1}Ready = 0;
xC${g} = vec4(0.0);`;h+=`
xR = xRCorner + r * dilations[0];
if (xR >=0 && xR < inDims[0]) {
`;for(let g=0;g<(d+1)/2;g++){let y=g*2;if(h+=`
xC = xCCorner + ${y*l};
`,o===1){if(y<u&&(i%2===1?(h+=`
xCOffset = xC + 1;
if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${y}Ready == 0) {
xTexelC${y} = getX(batch, xR, xCOffset, d1);
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if (xCOffset + 1 >= inDims[1]) {
xTexelC${y}.zw = vec2(0.0);
}
xTexelC${y}Ready = 1;
}
`,l===1&&y>0?h+=`
xC${y} = vec4(xTexelC${y-2}.zw, xTexelC${y}.xy);
`:h+=`
xCOffset = xC + 1 - 2;
if (xCOffset >= 0 && xCOffset < inDims[1]) {
previous = getX(batch, xR, xCOffset, d1);
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if (xCOffset + 1 >= inDims[1]) {
previous.zw = vec2(0.0);
}
xC${y} = vec4(previous.zw, xTexelC${y}.xy);
} else {
xC${y} = vec4(0.0, 0.0, xTexelC${y}.xy);
}
`):h+=`
if (xC >= 0 && xC < inDims[1] && xTexelC${y}Ready == 0) {
xTexelC${y} = getX(batch, xR, xC, d1);
if (xC + 1 >= inDims[1]) {
xTexelC${y}.zw = vec2(0.0);
}
xTexelC${y}Ready = 1;
}
xC${y} = xTexelC${y};
`,y+1<u)){let b=i%2===0?k.nearestLargerEven(l):l;l%2===0&&i%2===1||l%2!==0&&i%2!==1?(h+=`
xCOffset = xC + imod(pads[1], 2) + ${b};
if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${y+1}Ready == 0) {
xTexelC${y+1} = getX(batch, xR, xCOffset, d1);
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if (xCOffset + 1 >= inDims[1]) {
xTexelC${y+1}.zw = vec2(0.0);
}
xTexelC${y+1}Ready = 1;
}
`,l>1?h+=`
xCOffset -= 2;
if (xCOffset >= 0 && xCOffset < inDims[1]) {
previous = getX(batch, xR, xCOffset, d1);
xC${y+1} = vec4(previous.zw, xTexelC${y+1}.xy);
} else {
xC${y+1} = vec4(0.0, 0.0, xTexelC${y+1}.xy);
}
`:h+=`
xC${y+1} = vec4(xTexelC${y}.zw, xTexelC${y+1}.xy);
`):b===1?h+=`
xC${y+1} = xTexelC${y};
`:h+=`
xCOffset = xC + ${b};
if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${y+1}Ready == 0) {
xTexelC${y+1} = getX(batch, xR, xCOffset, d1);
if (xCOffset + 1 >= inDims[1]) {
xTexelC${y+1}.zw = vec2(0.0);
}
xTexelC${y+1}Ready = 1;
}
xC${y+1} = xTexelC${y+1};
`}}else y<u&&(i%2===1?(h+=`
xCOffset = xC + 1 - strides[1];
if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${y}Ready == 0) {
xTexelC${y} = getX(batch, xR, xCOffset, d1);
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if (xCOffset + 1 >= inDims[1]) {
xTexelC${y}.zw = vec2(0.0);
}
xTexelC${y}Ready = 1;
}
if(xC + 1 >= 0 && xC + 1 < inDims[1] && xTexelC${y+1}Ready == 0) {
xTexelC${y+1} = getX(batch, xR, xC + 1, d1);
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if (xC + 2 >= inDims[1]) {
xTexelC${y+1}.zw = vec2(0.0);
}
xTexelC${y+1}Ready = 1;
}
xC${y} = vec4(xTexelC${y}.zw, xTexelC${y+1}.zw);
`,y+1<u&&(h+=`
final = vec4(0.0);
xCOffset = xC + 1 + strides[1];
if(xCOffset >= 0 && xCOffset < inDims[1]) {
final = getX(batch, xR, xCOffset, d1);
}
xC${y+1} = vec4(xTexelC${y+1}.xy, final.xy);
`)):(h+=`
if(xC >= 0 && xC < inDims[1] && xTexelC${y}Ready == 0) {
xTexelC${y} = getX(batch, xR, xC, d1);
if (xC + 1 >= inDims[1]) {
xTexelC${y}.zw = vec2(0.0);
}
xTexelC${y}Ready = 1;
}
xCOffset = xC + strides[1];
if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${y+1}Ready == 0) {
xTexelC${y+1} = getX(batch, xR, xCOffset, d1);
if (xCOffset + 1 >= inDims[1]) {
xTexelC${y+1}.zw = vec2(0.);
}
xTexelC${y+1}Ready = 1;
}
xC${y} = vec4(
xTexelC${y}.xy, xTexelC${y+1}.xy);
`,y+1<u&&(h+=`
xC${y+1} = vec4(xTexelC${y}.zw, xTexelC${y+1}.zw);
`)));y<u&&(h+=`
wTexel = getW(r, ${y}, d1, q);
dotProd += xC${y} * vec4(wTexel.xz, wTexel.xz);
`,y+1<u&&(h+=`
wTexel = getW(r, ${y+1}, d1, q);
dotProd += xC${y+1} * vec4(wTexel.xz, wTexel.xz);
`))}h+=`
}
`,h+=`
}
`;let c="",f="";r&&(n?c=`vec4 activation(vec4 a) {
vec4 b = getPreluActivationWeightsAtOutCoords();
${r}
}`:a?c=`vec4 activation(vec4 a) {
vec4 b = getLeakyreluAlphaAtOutCoords();
${r}
}`:c=`vec4 activation(vec4 x) {
${r}
}`,f="result = activation(result);");let m=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),n&&this.variableNames.push("preluActivationWeights"),a&&this.variableNames.push("leakyreluAlpha"),this.userCode=`
${c}
void main() {
ivec4 coords = getOutputCoords();
int batch = coords.x;
ivec2 xRCCorner = coords.yz * strides - pads;
int d2 = coords.w;
int d1 = d2 / ${s};
int q = d2 - d1 * ${s};
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
//intialize dotProd with a small epsilon seems to reduce GPU accuracy loss.
vec4 dotProd = vec4(0.000000000000001);
${h}
vec4 result = dotProd - vec4(0.000000000000001);
${m}
${f}
setOutput(result);
}
`}};function Ute(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,filter:s}=t,{strides:i,pad:o,dilations:l,dimRoundingMode:p}=n,u=l;u==null&&(u=[1,1]),k.assert(_.eitherStridesOrDilationsAreOne(i,u),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${i} and dilations '${u}'`);let d=_.computeConv2DInfo(a.shape,s.shape,i,u,o,p,!0),h;j().getBool("WEBGL_PACK_DEPTHWISECONV")&&d.strideWidth<=2&&d.outChannels/d.inChannels===1?h=new HC(d):h=new GC(d);let c=[[d.padInfo.top,d.padInfo.left],[d.strideHeight,d.strideWidth],[d.dilationHeight,d.dilationWidth],[d.inHeight,d.inWidth]];return r.runWebGLProgram(h,[a,s],"float32",c)}var Vte={kernelName:Ki,backendName:"webgl",kernelFunc:Ute},Gte=class{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;let t=e.strideHeight,r=e.strideWidth,n=e.padInfo.top,a=e.padInfo.left,s=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 * ${s} + 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 * ${r} - ${a};
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);
}
`}},Hte=class{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;let t=e.filterHeight,r=e.filterWidth,n=e.strideHeight,a=e.strideWidth,s=t-1-e.padInfo.top,i=r-1-e.padInfo.left,o=e.outChannels/e.inChannels;this.userCode=`
const ivec2 pads = ivec2(${s}, ${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 < ${r}; wC++) {
float dyC = float(dyCCorner + wC) / ${a}.0;
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
int wCPerm = ${r} - 1 - wC;
// TO DO: Vec4 over the channelMul
for (int dm = 0; dm < ${o}; dm++) {
int d2 = d1 * ${o} + dm;
float xValue = getDy(batch, idyR, idyC, d2);
float wValue = getW(wRPerm, wCPerm, d1, dm);
dotProd += xValue * wValue;
}
}
}
setOutput(dotProd);
}
`}};function jte(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,dy:s}=t,{strides:i,dilations:o,pad:l,dimRoundingMode:p,filterShape:u}=n,d=_.computeConv2DInfo(a.shape,u,i,o,l,p,!0),h=new Gte(d);return r.runWebGLProgram(h,[a,s],"float32")}var qte={kernelName:ef,backendName:"webgl",kernelFunc:jte};function Kte(e){let{inputs:t,backend:r,attrs:n}=e,{dy:a,filter:s}=t,{strides:i,dilations:o,pad:l,dimRoundingMode:p,inputShape:u}=n,d=_.computeConv2DInfo(u,s.shape,i,o,l,p,!0),h=new Hte(d);return r.runWebGLProgram(h,[a,s],"float32")}var Xte={kernelName:tf,backendName:"webgl",kernelFunc:Kte},Zte=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 Jte(e){let{inputs:t,backend:r}=e,{x:n}=t,a=[...n.shape,...n.shape],s=k.sizeFromShape(n.shape),i=ue({inputs:{x:n},backend:r,attrs:{shape:[s]}}),o=new Zte(s),l=r.runWebGLProgram(o,[i],i.dtype),p=ue({inputs:{x:l},backend:r,attrs:{shape:a}});return r.disposeIntermediateTensorInfo(i),r.disposeIntermediateTensorInfo(l),p}var Yte={kernelName:yd,backendName:"webgl",kernelFunc:Jte},Qte=class{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;let{inHeight:t,inWidth:r,padInfo:n,strideHeight:a,strideWidth:s,filterHeight:i,filterWidth:o,dilationHeight:l,dilationWidth:p}=e,{top:u,left:d}=n;this.userCode=`
const ivec2 strides = ivec2(${a}, ${s});
const ivec2 pads = ivec2(${u}, ${d});
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 * ${l};
if (hIn >= 0 && hIn < ${t}) {
for (int w = 0; w < ${o}; w++) {
int wIn = wBeg + w * ${p};
if (wIn >= 0 && wIn < ${r}) {
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 ere(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,filter:s}=t,{strides:i,pad:o,dilations:l}=n,p=_.computeDilation2DInfo(a.shape,s.shape,i,o,"NHWC",l),u,d=new Qte(p);u=r.runWebGLProgram(d,[a,s],"float32");let h=ue({inputs:{x:u},backend:r,attrs:{shape:p.outShape}});return r.disposeIntermediateTensorInfo(u),h}var tre={kernelName:Xi,backendName:"webgl",kernelFunc:ere};function rre(e){let{inputs:t,backend:r,attrs:n}=e,{equation:a}=n,s=t,{allDims:i,summedDims:o,idDims:l}=_.decodeEinsumEquation(a,s.length);_.checkEinsumDimSizes(i.length,l,s);let{path:p,steps:u}=_.getEinsumComputePath(o,l),d=u.length,h=null,c=i.length,f=[];for(let m=0;m<d;++m){for(let g of u[m]){let{permutationIndices:y,expandDims:b}=_.getEinsumPermutation(c,l[g]),x;_.isIdentityPermutation(y)?x=s[g]:(x=xr({inputs:{x:s[g]},backend:r,attrs:{perm:y}}),f.push(x));let v=x.shape.slice();for(let w=0;w<b.length;++w)v.splice(b[w],0,1);k.arraysEqual(x.shape,v)||(x=ue({inputs:{x},backend:r,attrs:{shape:v}}),f.push(x)),h===null?h=x:(h=dw({inputs:{a:x,b:h},backend:r}),f.push(h))}m<d-1&&(p[m]>=0&&(h=vm({inputs:{x:h},backend:r,attrs:{axis:p[m]-(i.length-c),keepDims:!1}}),f.push(h)),c--)}for(let m of f)m!==h&&r.disposeIntermediateTensorInfo(m);return h}var nre={kernelName:nf,backendName:"webgl",kernelFunc:rre},are="return (x >= 0.0) ? x : (exp(x) - 1.0);",sre=`
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;
`,ire=Ke({opSnippet:are,packedOpSnippet:sre}),ore={kernelName:Ji,backendName:"webgl",kernelFunc:ire},lre="return (b >= 0.0) ? a : a * (b + 1.0);",ure=`
vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));
return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));
`,pre=e=>{let{inputs:t,backend:r}=e,{dy:n,y:a}=t,s=j().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new cp(ure,n.shape,a.shape):new Ni(lre,n.shape,a.shape);return r.runWebGLProgram(s,[n,a],n.dtype)},dre={kernelName:uu,backendName:"webgl",kernelFunc:pre},hre=`
return vec4(equal(a, b));
`,cre="return float(a == b);",fre=lr({opSnippet:cre,packedOpSnippet:hre,dtype:"bool",cpuKernelImpl:G9}),mre={kernelName:pu,backendName:"webgl",kernelFunc:fre},gre=`
// Error function is calculated approximately with elementary function.
// See "Handbook of Mathematical Functions with Formulas,
// Graphs, and Mathematical Tables", Abramowitz and Stegun.
float p = ${_.ERF_P};
float a1 = ${_.ERF_A1};
float a2 = ${_.ERF_A2};
float a3 = ${_.ERF_A3};
float a4 = ${_.ERF_A4};
float a5 = ${_.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));
`,yre=Ke({opSnippet:gre}),bre={kernelName:Yi,backendName:"webgl",kernelFunc:yre},xre=fp+`
return exp(x);
`,vre=`
vec4 result = exp(x);
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;
`,jC=Ke({opSnippet:xre,packedOpSnippet:vre,cpuKernelImpl:H9,dtype:"float32"}),wre={kernelName:Qi,backendName:"webgl",kernelFunc:jC};function Qg(e){let{inputs:t,attrs:r,backend:n}=e,{dim:a}=r,{input:s}=t,i=s.shape.length,o=s.shape.slice(),l=a;return a<0&&(k.assert(-(i+1)<=a,()=>`Axis must be in the interval [${-(i+1)}, ${i}]`),l=i+a+1),o.splice(l,0,1),ue({inputs:{x:s},backend:n,attrs:{shape:o}})}var kre={kernelName:du,backendName:"webgl",kernelFunc:Qg},R1="return exp(x) - 1.0;",Ire=Ke({opSnippet:R1,packedOpSnippet:R1,cpuKernelImpl:j9}),Sre={kernelName:eo,backendName:"webgl",kernelFunc:Ire},D1=class{constructor(e,t,r){this.variableNames=["real","imag"];let n=t[1];this.outputShape=t;let a=r?`2.0 * ${Math.PI}`:`-2.0 * ${Math.PI}`,s=r?`${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 = ${a};
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) / ${s};
}
return result;
}
void main() {
ivec2 coords = getOutputCoords();
setOutput(mulMatDFT(coords[0], coords[1]));
}
`}};function qC(e,t,r){let n=r.texData.get(e.dataId),a=k.sizeFromShape(e.shape),s=e.shape[e.shape.length-1],i=a/s,o=ue({inputs:{x:e},backend:r,attrs:{shape:[i,s]}}),l=o.shape,p=new D1("real",l,t),u=new D1("imag",l,t),d=[{dataId:n.complexTensorInfos.real.dataId,dtype:n.complexTensorInfos.real.dtype,shape:l},{dataId:n.complexTensorInfos.imag.dataId,dtype:n.complexTensorInfos.imag.dtype,shape:l}],h=r.runWebGLProgram(p,d,"float32"),c=r.runWebGLProgram(u,d,"float32"),f=Ls({inputs:{real:h,imag:c},backend:r});r.disposeIntermediateTensorInfo(h),r.disposeIntermediateTensorInfo(c);let m=ue({inputs:{x:f},backend:r,attrs:{shape:e.shape}});return r.disposeIntermediateTensorInfo(o),r.disposeIntermediateTensorInfo(f),m}function Nre(e){let{inputs:t,backend:r}=e,{input:n}=t;return qC(n,!1,r)}var _re={kernelName:af,backendName:"webgl",kernelFunc:Nre},Tre=class{constructor(e,t){this.outputShape=[],this.customUniforms=[{name:"value",type:"float"}],this.variableNames=["x"],this.outputShape=e,this.userCode=`
void main() {
// Input can be obtained from uniform value.
setOutput(value);
}
`}};function dh(e){let{backend:t,attrs:r}=e,{shape:n,value:a}=r,{dtype:s}=r;if(s=s||k.inferDtype(a),s==="string"){let i=k.getArrayFromDType(s,k.sizeFromShape(n));return i.fill(a),t.makeTensorInfo(n,s,i)}else{let i=new Tre(n,a),o=[[a]];return t.runWebGLProgram(i,[],s,o)}}var Cre={kernelName:bd,backendName:"webgl",kernelFunc:dh},Ere=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 - 1;
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);
}
`}},$re={kernelName:hu,backendName:"webgl",kernelFunc:({inputs:e,backend:t})=>{let{image:r}=e,n=t,a=new Ere(r.shape);return n.runWebGLProgram(a,[r],r.dtype)}},M1="return floor(x);",Are=Ke({opSnippet:M1,packedOpSnippet:M1,cpuKernelImpl:q9}),Fre={kernelName:to,backendName:"webgl",kernelFunc:Are},Rre=`
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;
}
`,Dre=`
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);
`,Mre=lr({opSnippet:Rre,packedOpSnippet:Dre,dtype:"int32"}),Ore={kernelName:ro,backendName:"webgl",kernelFunc:Mre},Lre=class{constructor(e){this.variableNames=["A"];let t=Sr(),[r,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, ${r}.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));
}
`}},zre=class{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;let t=Sr(),[r,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, ${r}.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;
}
`}},Pre={kernelName:gc,backendName:"webgl",kernelFunc:Bre},hl,qm=j().getBool("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU");function Bre(e){let{inputs:t,backend:r,attrs:n}=e,{pixels:a}=t,{numChannels:s}=n,i=typeof HTMLVideoElement<"u"&&a instanceof HTMLVideoElement,o=typeof HTMLImageElement<"u"&&a instanceof HTMLImageElement,[l,p]=i?[a.videoWidth,a.videoHeight]:[a.width,a.height],u=[p,l],d=[p,l,s];if(o||i){let m=j().getBool("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU");(hl==null||m!==qm)&&(qm=m,hl=document.createElement("canvas").getContext("2d",{willReadFrequently:qm})),hl.canvas.width=l,hl.canvas.height=p,hl.drawImage(a,0,0,l,p),a=hl.canvas}let h=r.makeTensorInfo(u,"int32");r.texData.get(h.dataId).usage=on.PIXELS,r.gpgpu.uploadPixelDataToTexture(r.getTexture(h.dataId),a);let c=j().getBool("WEBGL_PACK")?new zre(d):new Lre(d),f=r.runWebGLProgram(c,[h],"int32");return r.disposeData(h.dataId),f}function Wre(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,filter:s,bias:i,preluActivationWeights:o}=t,{strides:l,pad:p,dataFormat:u,dilations:d,dimRoundingMode:h,activation:c,leakyreluAlpha:f}=n,m=_.convertConv2DDataFormat(u),g=_.computeConv2DInfo(a.shape,s.shape,l,d,p,h,!1,m),y,b=[],x=i!=null,v=o!=null,w=c==="leakyrelu",N=()=>{let E=[a,s],$=(R,F)=>{if(F==="NCHW"&&R.shape.length===1&&R.shape[0]!==1){let S=ue({inputs:{x:R},backend:r,attrs:{shape:[R.shape[0],1,1]}});return b.push(S),S}return R};if(x&&E.push($(i,u)),v&&E.push($(o,u)),w){let R=r.makeTensorInfo([],"float32",k.createScalarValue(f,"float32"));E.push(R),b.push(R)}return E};if(g.filterHeight===1&&g.filterWidth===1&&g.dilationHeight===1&&g.dilationWidth===1&&g.strideHeight===1&&g.strideWidth===1&&(g.padInfo.type==="SAME"||g.padInfo.type==="VALID"))y=WC({x:a,filter:s,convInfo:g,backend:r,bias:i,activation:c,preluActivationWeights:o,leakyreluAlpha:f});else if(g.strideWidth<=2&&m==="channelsLast"&&j().getBool("WEBGL_EXP_CONV")){let E=c?id(c,!0):null,$=new BC(g,x,E,v,w),R=[[g.padInfo.top,g.padInfo.left],[g.strideHeight,g.strideWidth],[g.dilationHeight,g.dilationWidth],[g.inHeight,g.inWidth]],F=N();y=r.runWebGLProgram($,F,"float32",R)}else if(j().getBool("WEBGL_CONV_IM2COL"))y=UC({x:a,filter:s,convInfo:g,backend:r,bias:i,activation:c,preluActivationWeights:o,leakyreluAlpha:f});else{let E=c?id(c,!1):null,$=new PC(g,x,E,v,w),R=N();y=r.runWebGLProgram($,R,"float32")}let T=ue({inputs:{x:y},backend:r,attrs:{shape:g.outShape}});return b.push(y),b.forEach(E=>r.disposeIntermediateTensorInfo(E)),T}var Ure={kernelName:ui,backendName:"webgl",kernelFunc:Wre};function Vre(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,filter:s,bias:i,preluActivationWeights:o}=t,{strides:l,pad:p,dilations:u,dimRoundingMode:d,activation:h,leakyreluAlpha:c}=n,f=[],m=u;m==null&&(m=[1,1]),k.assert(_.eitherStridesOrDilationsAreOne(l,m),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${l} and dilations '${m}'`);let g=_.computeConv2DInfo(a.shape,s.shape,l,m,p,d,!0),y=j().getBool("WEBGL_PACK_DEPTHWISECONV")&&g.strideWidth<=2&&g.outChannels/g.inChannels===1,b=h?id(h,y):null,x=[a,s],v=i!=null,w=o!=null,N=h==="leakyrelu";if(v&&x.push(i),w&&x.push(o),N){let R=r.makeTensorInfo([],"float32",k.createScalarValue(c,"float32"));x.push(R),f.push(R)}let T;y?T=new HC(g,v,b,w,N):T=new GC(g,v,b,w,N);let E=[[g.padInfo.top,g.padInfo.left],[g.strideHeight,g.strideWidth],[g.dilationHeight,g.dilationWidth],[g.inHeight,g.inWidth]],$=r.runWebGLProgram(T,x,"float32",E);return f.forEach(R=>r.disposeIntermediateTensorInfo(R)),$}var Gre={kernelName:pi,backendName:"webgl",kernelFunc:Vre},Hre=class{constructor(e,t,r,n){this.sliceDim=e,this.strides=t,this.paramsShape=n,this.variableNames=["x","indices"],this.outputShape=r;let a=pt(r.length),s=`
int index;`;for(let i=0;i<this.sliceDim;i++)s+=`
index = round(getIndices(coords[0], ${i}));
out_of_bounds = out_of_bounds || index < 0;
out_of_bounds = out_of_bounds || index >= ${this.paramsShape[i]};
flattenIndex += index * ${this.strides[i]};`;this.userCode=`
void main() {
${a} coords = getOutputCoords();
int flattenIndex = 0;
bool out_of_bounds = false;
${s}
setOutput(out_of_bounds ? 0.0 : getX(flattenIndex, coords[1]));
}
`}};function jre(e){let{inputs:t,backend:r}=e,{params:n,indices:a}=t,s=a.shape,i=s[s.length-1],o=k.sizeFromShape(n.shape),[l,p,u,d]=_.prepareAndValidate(n,a),h=ue({inputs:{x:a},backend:r,attrs:{shape:[p,i]}}),c=ue({inputs:{x:n},backend:r,attrs:{shape:[k.sizeFromShape(n.shape)/u,u]}});if(r.shouldExecuteOnCPU([n,a])||n.dtype==="string"){let y=r.readSync(a.dataId),b=r.bufferSync(n),x=K9(y,b,n.dtype,p,i,u,d,n.shape,o);return r.makeTensorInfo(l,n.dtype,x.values)}let f=new Hre(i,d,[p,u],n.shape),m=r.runWebGLProgram(f,[c,h],c.dtype),g=ue({inputs:{x:m},backend:r,attrs:{shape:l}});return r.disposeIntermediateTensorInfo(h),r.disposeIntermediateTensorInfo(c),r.disposeIntermediateTensorInfo(m),g}var qre={kernelName:fu,backendName:"webgl",kernelFunc:jre},Kre=class{constructor(e,t){this.variableNames=["A","indices"],this.outputShape=t,this.rank=t.length;let r=pt(this.rank),n=Xre(e);this.userCode=`
void main() {
${r} resRC = getOutputCoords();
int index = int(getIndices(resRC.x, resRC.z));
float inBounds = (index >= 0) && (index < ${e[2]}) ? 1.0 : 0.0;
setOutput(inBounds * getA(${n}));
}
`}};function Xre(e,t){let r=["resRC.x","resRC.y","resRC.z","resRC.w"],n=[];for(let a=0;a<e.length;a++)a===2?n.push("index"):n.push(`${r[a]}`);return n.join()}function KC(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,indices:s}=t,{axis:i,batchDims:o}=n,l=k.parseAxisParam(i,a.shape)[0];if(j().get("DEBUG")){let b=r.readSync(s.dataId),x=a.shape[l];for(let v=0;v<b.length;++v){let w=b[v];k.assert(w<=x-1&&w>=0,()=>`GatherV2: the index value ${w} is not in [0, ${x-1}]`)}}let p=_.segment_util.collectGatherOpShapeInfo(a,s,l,o),u=k.sizeFromShape(s.shape),d=[],h=ue({inputs:{x:a},backend:r,attrs:{shape:[p.batchSize,p.outerSize,p.dimSize,p.sliceSize]}}),c=ue({inputs:{x:s},backend:r,attrs:{shape:[p.batchSize,u/p.batchSize]}});d.push(h),d.push(c);let f=[p.batchSize,p.outerSize,u/p.batchSize,p.sliceSize];if(r.shouldExecuteOnCPU([a,s])||a.dtype==="string"){let b=r.bufferSync(c),x=r.bufferSync(h),v=X9(x,b,f);return d.forEach(w=>r.disposeIntermediateTensorInfo(w)),r.makeTensorInfo(p.outputShape,v.dtype,v.values)}let m=new Kre(h.shape,f),g=r.runWebGLProgram(m,[h,c],h.dtype);d.push(g);let y=ue({inputs:{x:g},backend:r,attrs:{shape:p.outputShape}});return d.forEach(b=>r.disposeIntermediateTensorInfo(b)),y}var Zre={kernelName:cu,backendName:"webgl",kernelFunc:KC},Jre="return float(a > b);",Yre=`
return vec4(greaterThan(a, b));
`,Qre=lr({opSnippet:Jre,packedOpSnippet:Yre,cpuKernelImpl:Z9,dtype:"bool"}),ene={kernelName:mu,backendName:"webgl",kernelFunc:Qre},tne="return float(a >= b);",rne=`
return vec4(greaterThanEqual(a, b));
`,nne=lr({opSnippet:tne,packedOpSnippet:rne,dtype:"bool",cpuKernelImpl:J9}),ane={kernelName:ao,backendName:"webgl",kernelFunc:nne};function sne(e){let{inputs:t,backend:r}=e,{input:n}=t;return qC(n,!0,r)}var ine={kernelName:sf,backendName:"webgl",kernelFunc:sne},one="return float(!isnan(x) && !isinf(x));",lne=Ke({opSnippet:one,dtype:"bool"}),une={kernelName:io,backendName:"webgl",kernelFunc:lne},pne="return float(isinf(x));",dne=Ke({opSnippet:pne,dtype:"bool"}),hne={kernelName:oo,backendName:"webgl",kernelFunc:dne},cne="return float(isnan(x));",fne=Ke({opSnippet:cne,dtype:"bool"}),mne={kernelName:lo,backendName:"webgl",kernelFunc:fne},gne="return float(a < b);",yne=`
return vec4(lessThan(a, b));
`,bne=lr({opSnippet:gne,packedOpSnippet:yne,cpuKernelImpl:Y9,dtype:"bool"}),xne={kernelName:gu,backendName:"webgl",kernelFunc:bne},vne="return float(a <= b);",wne=`
return vec4(lessThanEqual(a, b));
`,kne=lr({opSnippet:vne,packedOpSnippet:wne,cpuKernelImpl:Q9,dtype:"bool"}),Ine={kernelName:yu,backendName:"webgl",kernelFunc:kne};function Sne(e){let{backend:t,attrs:r}=e,{start:n,stop:a,num:s}=r,i=eY(n,a,s);return t.makeTensorInfo([i.length],"float32",i)}var Nne={kernelName:bu,backendName:"webgl",kernelFunc:Sne},_ne=fp+`
return x < 0.0 ? 0./0. : log(x);
`,Tne=`
vec4 result = log(x);
bvec4 isNaN = isnan(x);
result.r = isNaN.r ? x.r : (x.r < 0.0 ? 0./0. : result.r);
result.g = isNaN.g ? x.g : (x.g < 0.0 ? 0./0. : result.g);
result.b = isNaN.b ? x.b : (x.b < 0.0 ? 0./0. : result.b);
result.a = isNaN.a ? x.a : (x.a < 0.0 ? 0./0. : result.a);
return result;
`,Cne=Ke({opSnippet:_ne,packedOpSnippet:Tne,cpuKernelImpl:tY}),Ene={kernelName:po,backendName:"webgl",kernelFunc:Cne},$ne=fp+`
return log(1.0 + x);
`,Ane=Ke({opSnippet:$ne}),Fne={kernelName:ho,backendName:"webgl",kernelFunc:Ane},Rne="return float(a >= 1.0 && b >= 1.0);",Dne=`
return vec4(
vec4(greaterThanEqual(a, vec4(1.0))) *
vec4(greaterThanEqual(b, vec4(1.0))));
`,Mne=lr({opSnippet:Rne,packedOpSnippet:Dne,dtype:"bool"}),One={kernelName:xu,backendName:"webgl",kernelFunc:Mne},Lne="return float(!(x >= 1.0));",zne=Ke({opSnippet:Lne}),Pne={kernelName:vu,backendName:"webgl",kernelFunc:zne},Bne="return float(a >= 1.0 || b >= 1.0);",Wne=`
return min(
vec4(greaterThanEqual(a, vec4(1.0))) +
vec4(greaterThanEqual(b, vec4(1.0))),
vec4(1.0));
`,Une=lr({opSnippet:Bne,packedOpSnippet:Wne,dtype:"bool"}),Vne={kernelName:wu,backendName:"webgl",kernelFunc:Une},Gne=class{constructor(e,t,r,n,a){this.variableNames=["x"],this.outputShape=[];let s=t,i=e[3]-1;this.outputShape=e;let o,l=`float(${r}) + float(${n}) * sum`;a===.5?o=`inversesqrt(${l})`:a===1?o=`1.0/(${l})`:o=`exp(log(${l}) * float(-${a}));`,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 = -${s}; j <= ${s}; j++) {
int idx = d + j;
if (idx >= 0 && idx <= ${i}) {
float z = getX(b, r, c, idx);
sum += z * z;
}
}
float val = x * ${o};
setOutput(val);
}
`}},Hne=class{constructor(e,t,r,n,a){this.variableNames=["x"],this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0;let s=t,i=e[3]-1;this.outputShape=e;let o,l=`float(${r}) + float(${n}) * sum`;a===.5?o=`inversesqrt(${l})`:a===1?o=`1.0/(${l})`:o=`exp(log(${l}) * float(-${a}));`,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 - ${s};
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 = - ${s}; j <= ${s}; 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 * ${o};
setOutput(result);
}
`}},jne=e=>{let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{depthRadius:s,bias:i,alpha:o,beta:l}=n,p=j().getBool("WEBGL_PACK_NORMALIZATION")?new Hne(a.shape,s,i,o,l):new Gne(a.shape,s,i,o,l);return r.runWebGLProgram(p,[a],a.dtype)},qne={kernelName:co,backendName:"webgl",kernelFunc:jne},Kne=class{constructor(e,t,r,n,a){this.variableNames=["inputImage","outputImage","dy"],this.outputShape=[],this.outputShape=e,this.depth=e[3],this.depthRadius=t,this.bias=r,this.alpha=n,this.beta=a,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(${r});
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(${a})
* getInputImage(b, r, c, k) * getOutputImage(b, r, c, d)
/ norm;
if (k == d) {
dyi += pow(norm, -1.0 * ${a});
}
if (k == coords[3]) {
dyi *= getDy(b, r, c, d);
result += dyi;
}
}
else {
break;
}
}
}
setOutput(result);
}
`}},Xne=e=>{let{inputs:t,backend:r,attrs:n}=e,{x:a,y:s,dy:i}=t,{depthRadius:o,bias:l,alpha:p,beta:u}=n,d=new Kne(a.shape,o,l,p,u);return r.runWebGLProgram(d,[a,s,i],a.dtype)},Zne={kernelName:ku,backendName:"webgl",kernelFunc:Xne};function Jne(e,t,r,n){let a=k.sizeFromShape(t),s=k.sizeFromShape(e.shape)/a,i=ue({inputs:{x:e},attrs:{shape:[s,a]},backend:n}),o=sl(i,e.dtype,"max",n),l=ue({inputs:{x:o},attrs:{shape:r},backend:n});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(o),l}function XC(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{reductionIndices:s,keepDims:i}=n,o=a.shape.length,l=k.parseAxisParam(s,a.shape),p=l,u=_.getAxesPermutation(p,o),d=u!=null,h=r.shouldExecuteOnCPU([a]),c=a;if(d){if(h){let b=r.texData.get(c.dataId).values,x=new Array(o);for(let N=0;N<x.length;N++)x[N]=a.shape[u[N]];let v=lw(b,a.shape,a.dtype,u,x);c=r.makeTensorInfo(x,a.dtype);let w=r.texData.get(c.dataId);w.values=v}else c=xm(a,u,r);p=_.getInnerMostAxes(p.length,o)}_.assertAxesAreInnerMostDims("max",p,o);let[f,m]=_.computeOutAndReduceShapes(c.shape,p),g=f;i&&(g=_.expandShapeToKeepDim(f,l));let y;if(h){let b=r.texData.get(c.dataId).values,x=rY(b,k.sizeFromShape(m),g,a.dtype);y=r.makeTensorInfo(g,a.dtype);let v=r.texData.get(y.dataId);v.values=x}else y=Jne(c,m,g,r);return d&&r.disposeIntermediateTensorInfo(c),y}var Yne={kernelName:fo,backendName:"webgl",kernelFunc:XC},Qne=pw+`
return max(a, b);
`,eae=`
vec4 result = vec4(max(a, b));
bvec4 isNaNA = isnan(a);
bvec4 isNaNB = isnan(b);
bvec4 isNaN = bvec4(isNaNA.x || isNaNB.x, isNaNA.y || isNaNB.y, isNaNA.z || isNaNB.z, isNaNA.w || isNaNB.w);
`+al+`
return result;
`,tae=lr({opSnippet:Qne,packedOpSnippet:eae,cpuKernelImpl:nY}),rae={kernelName:mo,backendName:"webgl",kernelFunc:tae};function nae(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t;lp(a,"maxPool");let{filterSize:s,strides:i,pad:o,dimRoundingMode:l}=n,p=1;k.assert(_.eitherStridesOrDilationsAreOne(i,p),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${i} and dilations '${p}'`);let u=_.computePool2DInfo(a.shape,s,i,p,o,l);if(u.filterWidth===1&&u.filterHeight===1&&k.arraysEqual(u.inShape,u.outShape))return Jr({inputs:{x:a},backend:r});let d=new od(u,"max",!1);return r.runWebGLProgram(d,[a],a.dtype)}var aae={kernelName:go,backendName:"webgl",kernelFunc:nae};function sae(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{filterSize:s,strides:i,pad:o,dataFormat:l,dimRoundingMode:p}=n,u=[1,1,1],d=_.computePool3DInfo(a.shape,s,i,u,o,p,l),h=new hw(d,"max",!1);return r.runWebGLProgram(h,[a],a.dtype)}var iae={kernelName:Iu,backendName:"webgl",kernelFunc:sae},oae=class{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;let t=e.strideHeight,r=e.strideWidth,n=e.dilationHeight,a=e.effectiveFilterHeight,s=e.effectiveFilterWidth,i=a-1-e.padInfo.top,o=s-1-e.padInfo.left,l=a*s-1;this.userCode=`
const ivec2 pads = ivec2(${i}, ${o});
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 < ${a};
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 < ${s}; wC++) {
float dyC = float(dyCCorner + wC) / ${r}.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 = ${l} - int(getMaxPos(b, idyR, idyC, d));
// Get the current value, check it against the value from the
// position matrix.
int curPosValue = wR * ${s} + wC;
float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);
dotProd += dyValue * mask;
}
}
setOutput(dotProd);
}
`}},lae=class{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;let t=e.strideDepth,r=e.strideHeight,n=e.strideWidth,a=e.dilationDepth,s=e.dilationHeight,i=e.dilationWidth,o=e.effectiveFilterDepth,l=e.effectiveFilterHeight,p=e.effectiveFilterWidth,u=o-1-e.padInfo.front,d=l-1-e.padInfo.top,h=p-1-e.padInfo.left,c=o*l*p-1;this.userCode=`
const ivec3 pads = ivec3(${u}, ${d}, ${h});
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 < ${o};
wD += ${a}) {
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 < ${l};
wR += ${s}) {
float dyR = float(dyRCorner + wR) / ${r}.0;
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||
fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
for (int wC = 0; wC < ${p};
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 = ${c} -
int(getMaxPos(batch, idyD, idyR, idyC, ch));
// Get the current value, check it against the value from the
// position matrix.
int curPosValue =
wD * ${l} * ${p} +
wR * ${p} + wC;
float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);
dotProd += dyValue * mask;
}
}
}
setOutput(dotProd);
}
`}};function uae(e){let{inputs:t,backend:r,attrs:n}=e,{dy:a,input:s}=t,i=s,{filterSize:o,strides:l,pad:p,dimRoundingMode:u}=n,d=[1,1,1],h=_.computePool3DInfo(i.shape,o,l,d,p,u),c=new hw(h,"max",!0),f=r.runWebGLProgram(c,[i],i.dtype),m=new lae(h),g=r.runWebGLProgram(m,[a,f],i.dtype);return r.disposeIntermediateTensorInfo(f),g}var pae={kernelName:vd,backendName:"webgl",kernelFunc:uae};function dae(e){let{inputs:t,backend:r,attrs:n}=e,{dy:a,input:s,output:i}=t,o=s;lp([s,i],"maxPoolGrad");let{filterSize:l,strides:p,pad:u,dimRoundingMode:d}=n,h=_.computePool2DInfo(o.shape,l,p,1,u,d),c=!0,f=new od(h,"max",c),m=r.runWebGLProgram(f,[o],o.dtype),g=new oae(h),y=r.runWebGLProgram(g,[a,m],o.dtype);return r.disposeIntermediateTensorInfo(m),y}var hae={kernelName:xd,backendName:"webgl",kernelFunc:dae};function cae(e,t,r,n){let a=new od(r,"max",!1),s=n.runWebGLProgram(a,[e],"float32");a=new od(r,"max",!0,!0,t);let i=n.runWebGLProgram(a,[e],"float32");return[s,i]}var fae={kernelName:wd,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:r})=>{let{x:n}=e,{filterSize:a,strides:s,pad:i,includeBatchInIndex:o}=t,l=r;k.assert(n.shape.length===4,()=>`Error in maxPool: input must be rank 4 but got rank ${n.shape.length}.`);let p=[1,1];k.assert(_.eitherStridesOrDilationsAreOne(s,p),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${s} and dilations '${p}'`);let u=_.computePool2DInfo(n.shape,a,s,p,i),[d,h]=cae(n,o,u,l);return[d,h]}};function mae(e,t,r,n){let a=k.sizeFromShape(t),s=k.sizeFromShape(e.shape)/a,i=ue({inputs:{x:e},attrs:{shape:[s,a]},backend:n}),o=sl(i,"float32","mean",n),l=ue({inputs:{x:o},attrs:{shape:r},backend:n});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(o),l}var gae={kernelName:yo,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:r})=>{let{x:n}=e,{keepDims:a,axis:s}=t,i=r,o=n.shape.length,l=k.parseAxisParam(s,n.shape),p=l,u=_.getAxesPermutation(p,o),d=u!=null,h=i.shouldExecuteOnCPU([n]),c=[],f=n;if(d){if(h){let x=i.texData.get(f.dataId).values,v=new Array(o);for(let T=0;T<v.length;T++)v[T]=n.shape[u[T]];let w=lw(x,n.shape,n.dtype,u,v);f=i.makeTensorInfo(v,n.dtype);let N=i.texData.get(f.dataId);N.values=w}else f=xm(n,u,i);c.push(f),p=_.getInnerMostAxes(p.length,o)}_.assertAxesAreInnerMostDims("sum",p,o);let[m,g]=_.computeOutAndReduceShapes(f.shape,p),y=m;a&&(y=_.expandShapeToKeepDim(m,l));let b=mae(f,g,y,i);for(let x of c)i.disposeIntermediateTensorInfo(x);return b}};function yae(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{axis:s,keepDims:i}=n,o=a.shape.length,l=k.parseAxisParam(s,a.shape),p=l,u=_.getAxesPermutation(p,o),d=a;u!=null&&(d=xr({inputs:{x:a},backend:r,attrs:{perm:u}}),p=_.getInnerMostAxes(p.length,a.shape.length)),_.assertAxesAreInnerMostDims("min",p,o);let[h,c]=_.computeOutAndReduceShapes(d.shape,p),f=k.sizeFromShape(c),m=ue({inputs:{x:d},backend:r,attrs:{shape:[-1,f]}}),g=sl(m,m.dtype,"min",r),y;if(i){let b=_.expandShapeToKeepDim(h,l);y=ue({inputs:{x:g},backend:r,attrs:{shape:b}})}else y=ue({inputs:{x:g},backend:r,attrs:{shape:h}});return r.disposeIntermediateTensorInfo(m),r.disposeIntermediateTensorInfo(g),u!=null&&r.disposeIntermediateTensorInfo(d),y}var bae={kernelName:bo,backendName:"webgl",kernelFunc:yae},xae=pw+`
return min(a, b);
`,vae=`
vec4 result = vec4(min(a, b));
bvec4 isNaNA = isnan(a);
bvec4 isNaNB = isnan(b);
bvec4 isNaN = bvec4(isNaNA.x || isNaNB.x, isNaNA.y || isNaNB.y, isNaNA.z || isNaNB.z, isNaNA.w || isNaNB.w);
`+al+`
return result;
`,wae=lr({opSnippet:xae,packedOpSnippet:vae,cpuKernelImpl:aY}),kae={kernelName:xo,backendName:"webgl",kernelFunc:wae},Iae=class{constructor(e,t,r){this.variableNames=["x"],this.outputShape=t.map((p,u)=>p[0]+e[u]+p[1]);let n=e.length,a=pt(n),s=t.map(p=>p[0]).join(","),i=t.map((p,u)=>p[0]+e[u]).join(","),o=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,n),l=r==="reflect"?0:1;if(n===1){this.userCode=`
int start = ${s};
int end = ${i};
void main() {
int outC = getOutputCoords();
if (outC < start) {
outC = start * 2 - outC - ${l};
} else if(outC >= end) {
outC = (end - 1) * 2 - outC + ${l};
}
setOutput(getX(outC - start));
}
`;return}this.userCode=`
${a} start = ${a}(${s});
${a} end = ${a}(${i});
void main() {
${a} outC = getOutputCoords();
for (int i = 0; i < ${n}; i++) {
if (outC[i] < start[i]) {
outC[i] = start[i] * 2 - outC[i] - ${l};
} else if(outC[i] >= end[i]) {
outC[i] = (end[i] - 1) * 2 - outC[i] + ${l};
}
}
${a} coords = outC - start;
setOutput(getX(${o}));
}
`}},Sae=class{constructor(e,t,r){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t.map((c,f)=>c[0]+e[f]+c[1]);let n=e.length,a=pt(n),s=t.map(c=>c[0]).join(","),i=t.map((c,f)=>c[0]+e[f]).join(","),o=gr("rc",n),l=gr("source",n),p=`${o[n-1]} < ${this.outputShape[n-1]}`,u=n===1?"source":`vec2(${l.slice(-2).join()})`,d=r==="reflect"?0:1,h="";if(n===1){let c=`
${a} source = rc;
if (source < start) {
source = start * 2 - source - ${d};
} else if (source >= end) {
source = (end - 1) * 2 - source + ${d};
}
source -= start;
`;h=`
${a} rc = outputLoc;
${c}
result[0] = getChannel(getX(${l.join()}), ${u});
${o[n-1]} += 1;
if(${p}) {
${c}
result[1] = getChannel(getX(${l.join()}), ${u});
}
`}else{let c=`
${a} source = rc;
${a} lt = ${a}(lessThan(source, start));
${a} gte = ${a}(greaterThanEqual(source, end));
${a} orig = 1 - (lt + gte);
source = orig * source +
lt * (start * 2 - source - ${d}) +
gte * ((end - 1) * 2 - source + ${d});
source -= start;
`;h=`
${a} rc = outputLoc;
${c}
result[0] = getChannel(getX(${l.join()}), ${u});
${o[n-1]} += 1;
if(${p}) {
${c}
result[1] = getChannel(getX(${l.join()}), ${u});
}
rc = outputLoc;
${o[n-2]} += 1;
if(${o[n-2]} < ${this.outputShape[n-2]}) {
${c}
result[2] = getChannel(getX(${l.join()}), ${u});
${o[n-1]} += 1;
if(${p}) {
${c}
result[3] = getChannel(getX(${l.join()}), ${u});
}
}
`}this.userCode=`
const ${a} start = ${a}(${s});
const ${a} end = ${a}(${i});
void main() {
${a} outputLoc = getOutputCoords();
vec4 result = vec4(0.);
${h}
setOutput(result);
}
`}},Nae=({inputs:e,backend:t,attrs:r})=>{let{x:n}=e,{paddings:a,mode:s}=r,i=j().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Sae(n.shape,a,s):new Iae(n.shape,a,s);return t.runWebGLProgram(i,[n],n.dtype)},_ae={kernelName:vo,backendName:"webgl",kernelFunc:Nae},Tae=`if (b == 0.0) return NAN;
return mod(a, b);`,Cae=`
vec4 result = mod(a, b);
bvec4 isNaN = equal(b, vec4(0.0));
`+al+`
return result;
`,Eae=lr({opSnippet:Tae,packedOpSnippet:Cae}),$ae={kernelName:wo,backendName:"webgl",kernelFunc:Eae},Aae=class{constructor(e,t,r){this.variableNames=["probs"],this.customUniforms=[{name:"seed",type:"float"}],this.outputShape=[e,r],this.userCode=`
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}));
}
`}},Fae=`
if (a == b) {
return 1.0;
};
return a / b;`,Rae=`
// 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;
`,ZC=lr({opSnippet:Fae,packedOpSnippet:Rae,checkOutOfBounds:!0}),Dae={kernelName:Zi,backendName:"webgl",kernelFunc:ZC},O1="return a - b;",JC=lr({opSnippet:O1,packedOpSnippet:O1,supportsComplex:!0,cpuKernelImpl:NY}),Mae={kernelName:jo,backendName:"webgl",kernelFunc:JC};function YC(e){let{inputs:t,backend:r,attrs:n}=e,{logits:a}=t,{dim:s}=n,i=k.parseAxisParam([s],a.shape),o=XC({inputs:{x:a},backend:r,attrs:{reductionIndices:i,keepDims:!1}}),l=_.expandShapeToKeepDim(o.shape,i),p=ue({inputs:{x:o},backend:r,attrs:{shape:l}}),u=JC({inputs:{a,b:p},backend:r}),d=jC({inputs:{x:u},backend:r}),h=vm({inputs:{x:d},backend:r,attrs:{axis:i,keepDims:!1}}),c=ue({inputs:{x:h},backend:r,attrs:{shape:l}}),f=ZC({inputs:{a:d,b:c},backend:r});return r.disposeIntermediateTensorInfo(o),r.disposeIntermediateTensorInfo(p),r.disposeIntermediateTensorInfo(u),r.disposeIntermediateTensorInfo(d),r.disposeIntermediateTensorInfo(h),r.disposeIntermediateTensorInfo(c),f}var Oae={kernelName:Go,backendName:"webgl",kernelFunc:YC};function Lae(e){let{inputs:t,backend:r,attrs:n}=e,{logits:a}=t,{numSamples:s,seed:i,normalized:o}=n,l=o?a:YC({inputs:{logits:a},backend:r,attrs:{dim:a.shape.length-1}}),p=l.shape[0],u=l.shape[1],d=new Aae(p,u,s),h=[[i]],c=r.runWebGLProgram(d,[l],"int32",h);return o||r.disposeIntermediateTensorInfo(l),c}var zae={kernelName:Su,backendName:"webgl",kernelFunc:Lae},Pae=Cn+`
return -x;
`,Bae=`
vec4 result = -x;
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;
`;function Wae(e){let{inputs:t,backend:r}=e,{x:n}=t;if(r.shouldExecuteOnCPU([n])){let s=r.texData.get(n.dataId),[i,o]=iY(s.values,n.shape,n.dtype);return r.makeTensorInfo(o,n.dtype,i)}let a;return j().getBool("WEBGL_PACK_UNARY_OPERATIONS")?a=new ss(n.shape,Bae):a=new aa(n.shape,Pae),r.runWebGLProgram(a,[n],n.dtype)}var Uae={kernelName:Nu,backendName:"webgl",kernelFunc:Wae},Vae=ga.nonMaxSuppressionV3Impl;function Gae(e){_.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:t,backend:r,attrs:n}=e,{boxes:a,scores:s}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l}=n,p=r.readSync(a.dataId),u=r.readSync(s.dataId),{selectedIndices:d}=Vae(p,u,i,o,l);return r.makeTensorInfo([d.length],"int32",new Int32Array(d))}var Hae={kernelName:Tu,backendName:"webgl",kernelFunc:Gae},jae=ga.nonMaxSuppressionV4Impl;function qae(e){_.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:t,backend:r,attrs:n}=e,{boxes:a,scores:s}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l,padToMaxOutputSize:p}=n,u=r.readSync(a.dataId),d=r.readSync(s.dataId),{selectedIndices:h,validOutputs:c}=jae(u,d,i,o,l,p);return[r.makeTensorInfo([h.length],"int32",new Int32Array(h)),r.makeTensorInfo([],"int32",new Int32Array([c]))]}var Kae={kernelName:Cu,backendName:"webgl",kernelFunc:qae},Xae=ga.nonMaxSuppressionV5Impl;function Zae(e){_.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:t,backend:r,attrs:n}=e,{boxes:a,scores:s}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l,softNmsSigma:p}=n,u=r.readSync(a.dataId),d=r.readSync(s.dataId),h=i,c=o,f=l,m=p,{selectedIndices:g,selectedScores:y}=Xae(u,d,h,c,f,m);return[r.makeTensorInfo([g.length],"int32",new Int32Array(g)),r.makeTensorInfo([y.length],"float32",new Float32Array(y))]}var Jae={kernelName:Eu,backendName:"webgl",kernelFunc:Zae},Yae=class{constructor(e,t,r,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(${r}),
float(index == coords.y)));
}
`}},Qae=e=>{let{inputs:t,backend:r,attrs:n}=e,{indices:a}=t,{dtype:s,depth:i,onValue:o,offValue:l}=n,p=k.sizeFromShape(a.shape),u=new Yae(p,i,o,l),d=ue({inputs:{x:a},backend:r,attrs:{shape:[p]}}),h=r.runWebGLProgram(u,[d],s);r.disposeIntermediateTensorInfo(d);let c=[...a.shape,i],f=ue({inputs:{x:h},backend:r,attrs:{shape:c}});return r.disposeIntermediateTensorInfo(h),f},ese={kernelName:Io,backendName:"webgl",kernelFunc:Qae};function Pc(e){let{inputs:t,backend:r}=e,{x:n}=t;if(n.dtype==="complex64"){let a=ph({inputs:{input:n},backend:r}),s=Pc({inputs:{x:a},backend:r}),i=wm({inputs:{input:n},backend:r}),o=Pc({inputs:{x:i},backend:r}),l=Ls({inputs:{real:s,imag:o},backend:r});return r.disposeIntermediateTensorInfo(a),r.disposeIntermediateTensorInfo(s),r.disposeIntermediateTensorInfo(i),r.disposeIntermediateTensorInfo(o),l}else return dh({attrs:{shape:n.shape,dtype:n.dtype,value:n.dtype==="string"?"":0},backend:r})}var tse={kernelName:Ku,backendName:"webgl",kernelFunc:Pc};function QC(e){let{inputs:t,backend:r}=e,{x:n}=t;if(n.dtype==="string")throw new Error("onesLike is not supported under string dtype");if(n.dtype==="complex64"){let a=ph({inputs:{input:n},backend:r}),s=QC({inputs:{x:a},backend:r}),i=wm({inputs:{input:n},backend:r}),o=Pc({inputs:{x:i},backend:r}),l=Ls({inputs:{real:s,imag:o},backend:r});return r.disposeIntermediateTensorInfo(a),r.disposeIntermediateTensorInfo(s),r.disposeIntermediateTensorInfo(i),r.disposeIntermediateTensorInfo(o),l}else return dh({attrs:{shape:n.shape,dtype:n.dtype,value:1},backend:r})}var rse={kernelName:$u,backendName:"webgl",kernelFunc:QC};function nse(e){let{inputs:t,backend:r,attrs:n}=e,{axis:a}=n;if(t.length===1)return Qg({inputs:{input:t[0]},backend:r,attrs:{dim:a}});let s=t[0].shape,i=t[0].dtype;t.forEach(u=>{k.assertShapesMatch(s,u.shape,"All tensors passed to stack must have matching shapes"),k.assert(i===u.dtype,()=>"All tensors passed to stack must have matching dtypes")});let o=[],l=t.map(u=>{let d=Qg({inputs:{input:u},backend:r,attrs:{dim:a}});return o.push(d),d}),p=zC({inputs:l,backend:r,attrs:{axis:a}});return o.forEach(u=>r.disposeIntermediateTensorInfo(u)),p}var ase={kernelName:Au,backendName:"webgl",kernelFunc:nse},sse=class{constructor(e,t,r){this.variableNames=["x"],this.customUniforms=[{name:"value",type:"float"}],this.outputShape=t.map((l,p)=>l[0]+e[p]+l[1]);let n=e.length,a=pt(n),s=t.map(l=>l[0]).join(","),i=t.map((l,p)=>l[0]+e[p]).join(","),o=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,n);if(n===1){this.userCode=`
int start = ${s};
int end = ${i};
void main() {
int outC = getOutputCoords();
if (outC < start || outC >= end) {
setOutput(value);
} else {
setOutput(getX(outC - start));
}
}
`;return}this.userCode=`
${a} start = ${a}(${s});
${a} end = ${a}(${i});
void main() {
${a} outC = getOutputCoords();
if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {
setOutput(value);
} else {
${a} coords = outC - start;
setOutput(getX(${o}));
}
}
`}},ise=class{constructor(e,t,r){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"value",type:"float"}],this.outputShape=t.map((f,m)=>f[0]+e[m]+f[1]);let n=e.length,a=pt(n),s=t.map(f=>f[0]).join(","),i=t.map((f,m)=>f[0]+e[m]).join(","),o=gr("rc",n),l=gr("source",n),p=`${o[n-1]} < ${this.outputShape[n-1]}`,u=n===1?"source":`vec2(${l.slice(-2).join()})`,d=[`${a} rc = outputLoc;`,`${o[n-1]} += 1;
if(${p}) {
`,n===1?"":`}
rc = outputLoc;
${o[n-2]} += 1;
if(${o[n-2]} < ${this.outputShape[n-2]}) {`,n===1?"":` ${o[n-1]} += 1;
if(${p}) {`],h=n===1?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))",c="";for(let f=0,m=n===1?2:4;f<m;f++)c+=`
${d[f]}
if (${h}) {
result[${f}] = float(value);
} else {
${a} source = rc - start;
result[${f}] = getChannel(getX(${l.join()}), ${u});
}
`;c+=n===1?"} ":"}}",this.userCode=`
const ${a} start = ${a}(${s});
const ${a} end = ${a}(${i});
void main() {
${a} outputLoc = getOutputCoords();
vec4 result = vec4(0.);
${c}
setOutput(result);
}
`}},eE=e=>{let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{paddings:s,constantValue:i}=n;if(k.sizeFromShape(a.shape)===0){let p=s.map((u,d)=>u[0]+a.shape[d]+u[1]);return dh({backend:r,attrs:{shape:p,value:i,dtype:a.dtype}})}let o=j().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new ise(a.shape,s,i):new sse(a.shape,s,i),l=[[i]];return r.runWebGLProgram(o,[a],a.dtype,l)},ose={kernelName:So,backendName:"webgl",kernelFunc:eE},lse=`
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);
`,use=`
// 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;
bvec4 isNaN1 = lessThan(a, vec4(0.0));
bvec4 isNaN2 = lessThan(floor(b), b);
bvec4 isNaN = bvec4(isNaN1.x && isNaN2.x, isNaN1.y && isNaN2.y, isNaN1.z && isNaN2.z, isNaN1.w && isNaN2.w);
`+al+`
return result;
`,pse=lr({opSnippet:lse,packedOpSnippet:use}),dse={kernelName:No,backendName:"webgl",kernelFunc:pse};function hse(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{axis:s,keepDims:i}=n,o=a.shape.length,l=[],p=k.parseAxisParam(s,a.shape),u=p,d=_.getAxesPermutation(u,o),h=a;d!=null&&(h=xr({inputs:{x:a},backend:r,attrs:{perm:d}}),u=_.getInnerMostAxes(u.length,o),l.push(h)),_.assertAxesAreInnerMostDims("prod",u,o);let c;if(r.shouldExecuteOnCPU([h])){let f=r.texData.get(h.dataId).values,{outVals:m,outShape:g,outDtype:y}=lY(h.shape,h.dtype,f,u);c=r.makeTensorInfo(g,y,m)}else{let[f,m]=_.computeOutAndReduceShapes(h.shape,u),g=k.sizeFromShape(m),y=ue({inputs:{x:h},backend:r,attrs:{shape:[-1,g]}}),b=cf(a.dtype),x=sl(y,b,"prod",r);c=ue({inputs:{x},backend:r,attrs:{shape:f}}),l.push(y),l.push(x)}if(i){l.push(c);let f=_.expandShapeToKeepDim(c.shape,p);c=ue({inputs:{x:c},backend:r,attrs:{shape:f}})}return l.forEach(f=>r.disposeIntermediateTensorInfo(f)),c}var cse={kernelName:To,backendName:"webgl",kernelFunc:hse};function fse(e){let{inputs:t,backend:r,attrs:n}=e,{paramsNestedSplits:a,paramsDenseValues:s,indices:i}=t,{outputRaggedRank:o}=n,l=a.map(y=>r.readSync(y.dataId)),p=a.map(y=>y.shape),u=r.readSync(s.dataId),d=r.readSync(i.dataId),[h,c,f]=uY(l,p,u,s.shape,s.dtype,d,i.shape,o),m=h.map(y=>r.makeTensorInfo([y.length],"int32",y)),g=r.makeTensorInfo(f,s.dtype,c);return m.concat([g])}var mse={kernelName:lf,backendName:"webgl",kernelFunc:fse};function gse(e){let{inputs:t,backend:r}=e,{starts:n,limits:a,deltas:s}=t,i=r.readSync(n.dataId),o=r.readSync(a.dataId),l=r.readSync(s.dataId),[p,u]=pY(i,n.shape,n.dtype,o,a.shape,l,s.shape),d=r.makeTensorInfo([p.length],"int32",p),h=r.makeTensorInfo([u.length],n.dtype,u);return[d,h]}var yse={kernelName:uf,backendName:"webgl",kernelFunc:gse};function bse(e){let{inputs:t,backend:r,attrs:n}=e,{shape:a,values:s,defaultValue:i,rowPartitionTensors:o}=t,{rowPartitionTypes:l}=n,p=r.readSync(a.dataId),u=r.readSync(s.dataId),d=r.readSync(i.dataId),h=o.map(g=>r.readSync(g.dataId)),c=o.map(g=>g.shape),[f,m]=dY(p,a.shape,u,s.shape,s.dtype,d,i.shape,h,c,l);return r.makeTensorInfo(f,s.dtype,m)}var xse={kernelName:pf,backendName:"webgl",kernelFunc:bse},tE=e=>{let{backend:t,attrs:r}=e,{start:n,stop:a,step:s,dtype:i}=r,o=hY(n,a,s,i);return t.makeTensorInfo([o.length],i,o)},vse={kernelName:kd,backendName:"webgl",kernelFunc:tE},wse="return 1.0 / x;",kse=Ke({opSnippet:wse}),Ise={kernelName:Co,backendName:"webgl",kernelFunc:kse},Sse=Cn+`
return (x < 0.0) ? 0.0 : x;
`,Nse=`
vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0)));
bvec4 isNaN = isnan(x);
result.r = isNaN.r ? x.r : result.r;
result.g = isNaN.g ? x.g : result.g;
result.b = isNaN.b ? x.b : result.b;
result.a = isNaN.a ? x.a : result.a;
return result;
`,_se=Ke({opSnippet:Sse,packedOpSnippet:Nse}),Tse={kernelName:Eo,backendName:"webgl",kernelFunc:_se},Cse=Cn+`
return (x < 0.0) ? 0.0 : min(6.0, x);
`,Ese=`
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;
`,$se=Ke({opSnippet:Cse,packedOpSnippet:Ese}),Ase={kernelName:Fo,backendName:"webgl",kernelFunc:$se},Fse=class{constructor(e,t,r,n,a){this.variableNames=["A"],this.outputShape=[];let[s,i,o,l]=e;this.outputShape=[s,t,r,l];let p=[n&&t>1?i-1:i,n&&r>1?o-1:o],u=[n&&t>1?t-1:t,n&&r>1?r-1:r],d;a?d="(vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC - vec2(0.5)":d="vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
const vec2 effectiveInputOverOutputRatioRC = vec2(
${p[0]/u[0]},
${p[1]/u[1]});
const vec2 inputShapeRC = vec2(${i}.0, ${o}.0);
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
ivec2 yRC = coords.yz;
// Fractional source index.
vec2 sourceFracIndexRC = ${d};
// 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);
}
`}},Rse=class{constructor(e,t,r,n,a){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];let[s,i,o,l]=e;this.outputShape=[s,t,r,l];let p=[n&&t>1?i-1:i,n&&r>1?o-1:o],u=[n&&t>1?t-1:t,n&&r>1?r-1:r],d;a?d="(vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC - vec3(0.5)":d="vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
const vec3 effectiveInputOverOutputRatioRC = vec3(
${p[0]/u[0]},
${p[1]/u[1]},
${p[1]/u[1]});
const vec3 inputShapeRC = vec3(${i}.0, ${o}.0,
${o}.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 = ${d};
// 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 < ${l-1};
bool hasNextRow = coords.z < ${r-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 Dse(e){let{inputs:t,backend:r,attrs:n}=e,{images:a}=t,{alignCorners:s,halfPixelCenters:i,size:o}=n,[l,p]=o,u=j().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new Rse(a.shape,l,p,s,i):new Fse(a.shape,l,p,s,i);return r.runWebGLProgram(u,[a],"float32")}var Mse={kernelName:Ao,backendName:"webgl",kernelFunc:Dse},Ose=class{constructor(e,t,r){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t;let[,n,a]=t,[,s,i]=e,o=[r&&s>1?n-1:n,r&&i>1?a-1:a],l=[r&&s>1?s-1:s,r&&i>1?i-1:i],p=o[0]/l[0],u=o[1]/l[1],d=1/p,h=1/u,c=Math.ceil(d)*2+2,f=Math.ceil(h)*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(${p});
const float widthScale = float(${u});
const float invHeightScale = float(${d});
const float invWidthScale = float(${h});
const int winHeight = int(${c});
const int winWidth = int(${f});
// 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 >= ${s}) {
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), ${a-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 Lse(e){let{inputs:t,backend:r,attrs:n}=e,{images:a,dy:s}=t,{alignCorners:i}=n,o=new Ose(s.shape,a.shape,i);return r.runWebGLProgram(o,[s],s.dtype)}var zse={kernelName:Du,backendName:"webgl",kernelFunc:Lse},Pse=class{constructor(e,t,r,n,a){this.variableNames=["A"],this.outputShape=[];let[s,i,o,l]=e;this.outputShape=[s,t,r,l];let p=[n&&t>1?i-1:i,n&&r>1?o-1:o],u=[n&&t>1?t-1:t,n&&r>1?r-1:r],d=n?"0.5":"0.0",h;a?h="max((vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC, vec2(0.0))":h="vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
const vec2 effectiveInputOverOutputRatioRC = vec2(
${p[0]/u[0]},
${p[1]/u[1]});
const vec2 inputShapeRC = vec2(${i}.0, ${o}.0);
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
ivec2 yRC = coords.yz;
// Fractional source index.
vec2 sourceFracIndexRC = ${h};
// Compute the coordinators of nearest neighbor point.
ivec2 sourceNearestRC = ivec2(
min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${d})));
float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d);
setOutput(newValue);
}
`}},Bse=class{constructor(e,t,r,n,a){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];let[s,i,o,l]=e;this.outputShape=[s,t,r,l];let p=[n&&t>1?i-1:i,n&&r>1?o-1:o],u=[n&&t>1?t-1:t,n&&r>1?r-1:r],d=n?"0.5":"0.0",h;a?h="max((vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC, vec3(0.0))":h="vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
const vec3 effectiveInputOverOutputRatioRC = vec3(
${p[0]/u[0]},
${p[1]/u[1]},
${p[1]/u[1]});
const vec3 inputShapeRC = vec3(${i}.0, ${o}.0,
${o}.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 = ${h};
// Compute the coordinators of nearest neighbor point.
ivec3 sourceNearestRC = ivec3(
min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${d})));
// Should we calculate next column and row elements in 2x2 packed cell.
bool hasNextCol = d < ${l-1};
bool hasNextRow = coords.z < ${r-1};
vec4 newValue = vec4(
getAValue(b, sourceNearestRC.x, sourceNearestRC.y, d),
hasNextCol ? getAValue(b, sourceNearestRC.x, sourceNearestRC.y, d + 1)
: 0.0,
hasNextRow ? getAValue(b, sourceNearestRC.x, sourceNearestRC.z, d)
: 0.0,
(hasNextRow && hasNextCol) ?
getAValue(b, sourceNearestRC.x, sourceNearestRC.z, d + 1) : 0.0);
setOutput(newValue);
}
`}};function Wse(e){let{inputs:t,backend:r,attrs:n}=e,{images:a}=t,{alignCorners:s,halfPixelCenters:i,size:o}=n,[l,p]=o,u=j().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new Bse(a.shape,l,p,s,i):new Pse(a.shape,l,p,s,i);return r.runWebGLProgram(u,[a],a.dtype)}var Use={kernelName:$o,backendName:"webgl",kernelFunc:Wse},Vse=class{constructor(e,t,r){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t;let[,n,a]=t,[,s,i]=e,o=[r&&s>1?n-1:n,r&&i>1?a-1:a],l=[r&&s>1?s-1:s,r&&i>1?i-1:i],p=o[0]/l[0],u=o[1]/l[1],d=1/p,h=1/u,c=Math.ceil(d)*2+2,f=Math.ceil(h)*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(${p});
const float widthScale = float(${u});
const float invHeightScale = float(${d});
const float invWidthScale = float(${h});
const int winHeight = int(${c});
const int winWidth = int(${f});
// 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 >= ${s}) {
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(${o[0]}) *
(float(dyR) / float(${l[0]}));
float sourceFracCol =
float(${o[1]}) *
(float(dyC) / float(${l[1]}));
int sourceNearestRow = int(min(
float(int(${n}) - 1),
${r} ? float(round(sourceFracRow)) :
float(floor(sourceFracRow))));
int sourceNearestCol = int(min(
float(int(${a}) - 1),
${r} ? float(round(sourceFracCol)) :
float(floor(sourceFracCol))));
if (r == sourceNearestRow && c == sourceNearestCol) {
accumulator += getDy(b, dyR, dyC, d);
}
}
}
// End loop over dy
setOutput(accumulator);
}
`}};function Gse(e){let{inputs:t,backend:r,attrs:n}=e,{images:a,dy:s}=t,{alignCorners:i}=n,o=new Vse(s.shape,a.shape,i);return r.runWebGLProgram(o,[s],s.dtype)}var Hse={kernelName:Ru,backendName:"webgl",kernelFunc:Gse},jse=class{constructor(e,t){this.variableNames=["x"];let r=e.length;if(r>4)throw new Error(`WebGL backend: Reverse of rank-${r} tensor is not yet supported`);if(this.outputShape=e,r===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}]`,a=e.map((i,o)=>n(o)).join(","),s=pt(r);this.userCode=`
void main() {
${s} coords = getOutputCoords();
setOutput(getX(${a}));
}
`}},qse=class{constructor(e,t){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0;let r=e.length;if(r>4)throw new Error(`WebGL backend: Reverse of rank-${r} tensor is not yet supported`);this.outputShape=e;let n=gr("rc",r),a=`${n[r-1]} + 1 < ${this.outputShape[r-1]}`,s=`${n[r-2]} + 1 < ${this.outputShape[r-2]}`,i=pt(r);r===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(${a}){
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 = ${o(n.slice())};
if(${a}){
result.g = ${l(n.slice())};
}
if(${s}) {
result.b = ${p(n.slice())};
if(${a}) {
result.a = ${u(n.slice())};
}
}
setOutput(result);
}
`;function o(c){return d(c)}function l(c){return c[r-1]="("+c[r-1]+" + 1)",d(c)}function p(c){return c[r-2]="("+c[r-2]+" + 1)",d(c)}function u(c){return c[r-1]="("+c[r-1]+" + 1)",c[r-2]="("+c[r-2]+" + 1)",d(c)}function d(c){let f=e.map((y,b)=>h(b,c)),m=f.join(","),g=f.slice(-2).join(",");return`getChannel(getX(${m}), vec2(${g}))`}function h(c,f){return t.indexOf(c)!==-1&&e[c]!==1?`${e[c]} - ${f[c]} - 1`:`${f[c]}`}}};function Kse(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{dims:s}=n,i=a.shape.length,o=k.parseAxisParam(s,a.shape);if(i===0)return Jr({inputs:{x:a},backend:r});let l=j().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new qse(a.shape,o):new jse(a.shape,o);return r.runWebGLProgram(l,[a],a.dtype)}var Xse={kernelName:Ro,backendName:"webgl",kernelFunc:Kse},Zse=class{constructor(e,t){this.variableNames=["Image"],this.outputShape=[],this.customUniforms=[{name:"params",type:"vec4"}];let r=e[1],n=e[2];this.outputShape=e;let a="";typeof t=="number"?a=`float outputValue = ${t.toFixed(2)};`:a=`
vec3 fill = vec3(${t.join(",")});
float outputValue = fill[coords[3]];`,this.userCode=`
void main() {
ivec4 coords = getOutputCoords();
int x = coords[2];
int y = coords[1];
float coordXFloat = (float(x) - 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]));
${a}
if(coordX >= 0 && coordX < ${n} && coordY >= 0 && coordY < ${r}) {
outputValue = getImage(coords[0], coordY, coordX, coords[3]);
}
setOutput(outputValue);
}
`}},Jse={kernelName:Xu,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:r})=>{let{image:n}=e,{radians:a,fillValue:s,center:i}=t,o=r,l=new Zse(n.shape,s),[p,u]=_.getImageCenter(i,n.shape[1],n.shape[2]),d=[[p,u,Math.sin(a),Math.cos(a)]];return o.runWebGLProgram(l,[n],n.dtype,d)}},Yse=`
// 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;
}
}
`,Qse=Ke({opSnippet:Yse}),eie={kernelName:Do,backendName:"webgl",kernelFunc:Qse},tie="return inversesqrt(x);",rie=Ke({opSnippet:tie,cpuKernelImpl:cY}),nie={kernelName:Mo,backendName:"webgl",kernelFunc:rie},cw=class{constructor(e,t,r,n,a,s,i=!0,o=!1){this.variableNames=["updates","indices","defaultValue"],this.outputShape=s;let l=pt(a.length),p=pt(s.length),u="";r===1?u="i":r===2&&(u="i, j");let d=`getIndices(${u})`,h="";n===1?h="i":n===2&&(h="i, coords[1]");let c=`getUpdates(${h})`,f="";o&&(f="coords[0], coords[1]");let m=`getDefaultValue(${f})`,g=t>1?"strides[j]":"strides";this.userCode=`
${l} strides = ${l}(${a});
void main() {
${p} 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(${d});
flattenedIndex += index * ${g};
}
if (flattenedIndex == coords[0]) {
sum += ${c};
found = true;
}
}
setOutput(mix(${m}, sum, float(found)));
}
`}},aie=class{constructor(e,t,r,n,a,s,i=!0,o=!1){this.variableNames=["updates","indices","defaultValue"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=s;let l=pt(a.length),p=pt(s.length),u="";r===1?u="i":r===2&&(u="i, j");let d=`getIndices(${u})`,h="";n===1?h="i":n===2&&(h="i, coords[1]");let c=`getUpdates(${h})`,f="";o&&(f="coords[0], coords[1]");let m=`getDefaultValue(${f})`,g=t>1?"strides[j]":"strides",y=t>1?"strides[j + 1]":"strides";this.userCode=`
${l} strides = ${l}(${a});
void main() {
${p} coords = getOutputCoords();
vec4 sum = vec4(0.);
vec4 found = vec4(0.);
for (int i = 0; i < ${e}; i+=2) {
ivec2 flattenedIndex = ivec2(0);
for (int j = 0; j < ${t}; j+=2) {
ivec4 index = round(${d});
flattenedIndex += index.xz * ${g};
if (j + 1 < ${t}) {
flattenedIndex += index.yw * ${y};
}
}
if (flattenedIndex[0] == coords[0] || flattenedIndex[1] == coords[0] ||
flattenedIndex[0] == coords[0] + 1 || flattenedIndex[1] == coords[0] + 1) {
vec4 updVals = ${c};
if (flattenedIndex[0] == coords[0]) {
sum.xy += updVals.xy;
found.xy = vec2(1.);
} else if (flattenedIndex[0] == coords[0] + 1) {
sum.zw += updVals.xy;
found.zw = vec2(1.);
}
if (flattenedIndex[1] == coords[0]) {
sum.xy += updVals.zw;
found.xy = vec2(1.);
} else if (flattenedIndex[1] == coords[0] + 1) {
sum.zw += updVals.zw;
found.zw = vec2(1.);
}
}
}
setOutput(mix(${m}, sum, found));
}
`}};function sie(e){let{inputs:t,backend:r,attrs:n}=e,{indices:a,updates:s}=t,{shape:i}=n,{sliceRank:o,numUpdates:l,sliceSize:p,strides:u,outputSize:d}=_.calculateShapes(s,a,i),h=[d/p,p];if(d===0)return r.makeTensorInfo(i,a.dtype);let c=ue({inputs:{x:a},backend:r,attrs:{shape:[l,o]}}),f=ue({inputs:{x:s},backend:r,attrs:{shape:[l,p]}}),m=r.makeTensorInfo([],"float32",new Float32Array([0])),g;j().getBool("WEBGL_PACK")?g=new aie(l,o,c.shape.length,f.shape.length,u,h):g=new cw(l,o,c.shape.length,f.shape.length,u,h);let y=r.runWebGLProgram(g,[f,c,m],f.dtype),b=ue({inputs:{x:y},backend:r,attrs:{shape:i}});return r.disposeIntermediateTensorInfo(c),r.disposeIntermediateTensorInfo(f),r.disposeIntermediateTensorInfo(y),r.disposeIntermediateTensorInfo(m),b}var iie={kernelName:Mu,backendName:"webgl",kernelFunc:sie},oie=class{constructor(e,t,r,n){this.variableNames=["sortedSequence","values"],this.customUniforms=[{name:"numInputs",type:"int"}],this.outputShape=[e,r];let a="while (left < right) {",s=`for (int i = 0; i < ${Math.ceil(Math.log2(t+1))}; ++i) { if (left >= right) break;`,i=j().getNumber("WEBGL_VERSION")===2?a:s,o=n==="left"?"<":"<=";this.userCode=`
int findBound(int batch, float value) {
int left = 0;
int right = numInputs;
int mid;
${i}
mid = (left + right) / 2;
if (getSortedSequence(batch, mid) ${o} value) {
left = mid + 1;
} else {
right = mid;
}
}
return right;
}
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
int valueIndex = coords[1];
float value = getValues(batch, valueIndex);
setOutput(float(findBound(batch, value)));
}
`}};function lie(e){let{inputs:t,backend:r,attrs:n}=e,{sortedSequence:a,values:s}=t,{side:i}=n,o=new oie(a.shape[0],a.shape[1],s.shape[1],i),l=[[a.shape[1]]];return r.runWebGLProgram(o,[a,s],"int32",l)}var uie={kernelName:Lu,backendName:"webgl",kernelFunc:lie},pie=class{constructor(e,t,r){this.variableNames=["c","a","b"],this.outputShape=t;let n,a;if(r>4)throw Error(`Where for rank ${r} is not yet supported`);if(r===1)a="resRC",n="resRC";else{let i=["resRC.x","resRC.y","resRC.z","resRC.w"],o=[],l=[];for(let p=0;p<t.length;p++)l.push(`${i[p]}`),p<e&&o.push(`${i[p]}`);n=o.join(),a=l.join()}let s=pt(r);this.userCode=`
void main() {
${s} resRC = getOutputCoords();
float cVal = getC(${n});
if (cVal >= 1.0) {
setOutput(getA(${a}));
} else {
setOutput(getB(${a}));
}
}
`}};function die(e){let{inputs:t,backend:r}=e,{condition:n,t:a,e:s}=t,i=new pie(n.shape.length,a.shape,a.shape.length);return r.runWebGLProgram(i,[n,a,s],cn(a.dtype,s.dtype))}var hie={kernelName:zu,backendName:"webgl",kernelFunc:die},cie=`
// Stable and Attracting Fixed Point (0, 1) for Normalized Weights.
// see: https://arxiv.org/abs/1706.02515
float scaleAlpha = ${_.SELU_SCALEALPHA};
float scale = ${_.SELU_SCALE};
return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);
`,fie=Ke({opSnippet:cie}),mie={kernelName:Oo,backendName:"webgl",kernelFunc:fie},gie=fp+`
return 1.0 / (1.0 + exp(-1.0 * x));
`,yie=`
vec4 result = 1.0 / (1.0 + exp(-1.0 * x));
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;
`,bie=Ke({opSnippet:gie,packedOpSnippet:yie,cpuKernelImpl:mY}),xie={kernelName:Bo,backendName:"webgl",kernelFunc:bie},vie=`
if (isnan(x)) { return 0.0; }
return sign(x);
`,wie=Ke({opSnippet:vie}),kie={kernelName:Po,backendName:"webgl",kernelFunc:wie},Iie=fp+`
return sin(x);
`,Sie=`
vec4 result = sin(x);
bvec4 isNaN = isnan(x);
${al}
return result;
`,Nie=Ke({opSnippet:Iie,packedOpSnippet:Sie}),_ie={kernelName:Lo,backendName:"webgl",kernelFunc:Nie},Tie=`
float e2x = exp(x);
return (e2x - 1.0 / e2x) / 2.0;
`,Cie=Ke({opSnippet:Tie}),Eie={kernelName:zo,backendName:"webgl",kernelFunc:Cie},$ie=`
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;
`,Aie=Ke({opSnippet:$ie}),Fie={kernelName:Wo,backendName:"webgl",kernelFunc:Aie},Rie=e=>{let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{blockShape:s,paddings:i}=n;k.assert(a.shape.length<=4,()=>"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet");let o=s.reduce((y,b)=>y*b),l=[[0,0]];l.push(...i);for(let y=1+s.length;y<a.shape.length;++y)l.push([0,0]);let p=[],u=eE({inputs:{x:a},backend:r,attrs:{paddings:l,constantValue:0}}),d=_.getReshaped(u.shape,s,o,!1),h=_.getPermuted(d.length,s.length,!1),c=_.getReshapedPermuted(u.shape,s,o,!1),f=ue({inputs:{x:u},backend:r,attrs:{shape:d}}),m=xr({inputs:{x:f},backend:r,attrs:{perm:h}}),g=ue({inputs:{x:m},backend:r,attrs:{shape:c}});return p.push(u),p.push(f),p.push(m),p.forEach(y=>r.disposeIntermediateTensorInfo(y)),g},Die={kernelName:Bu,backendName:"webgl",kernelFunc:Rie};function Mie(e){let{inputs:t,backend:r}=e,{indices:n,values:a,denseShape:s,defaultValue:i}=t;if(s.shape.length!==1)throw new Error(`Dense shape must be a vector, saw:
${s.shape}`);if(n.shape.length!==2)throw new Error(`Indices must be a matrix, saw:
${n.shape}`);if(a.shape.length!==1)throw new Error(`Values must be a vector, saw:
${a.shape}`);if(i.shape.length!==0)throw new Error(`Default value must be a scalar, saw:
${i.shape}`);let o=r.readSync(n.dataId),l=r.readSync(a.dataId),p=r.readSync(s.dataId),u=r.readSync(i.dataId)[0],[d,h,c,f,m]=yY(o,n.shape,n.dtype,l,a.dtype,p,u);return[r.makeTensorInfo(h,n.dtype,d),r.makeTensorInfo([h[0]],a.dtype,c),r.makeTensorInfo([f.length],"bool",new Uint8Array(f.map(g=>Number(g)))),r.makeTensorInfo([m.length],n.dtype,new Int32Array(m))]}var Oie={kernelName:Id,backendName:"webgl",kernelFunc:Mie};function Lie(e){let{inputs:t,backend:r}=e,{inputIndices:n,inputShape:a,newShape:s}=t;if(n.shape.length!==2)throw new Error(`Input indices should be a matrix but received shape ${n.shape}`);if(a.shape.length!==1)throw new Error(`Input shape should be a vector but received shape ${a.shape}`);if(s.shape.length!==1)throw new Error(`Target shape should be a vector but received shape ${s.shape}`);let i=Array.from(r.readSync(a.dataId)),o=r.readSync(n.dataId),l=Array.from(r.readSync(s.dataId)),[p,u,d]=bY(o,n.shape,n.dtype,i,l);return[r.makeTensorInfo(u,n.dtype,p),r.makeTensorInfo([d.length],s.dtype,new Int32Array(d))]}var zie={kernelName:Uu,backendName:"webgl",kernelFunc:Lie};function Pie(e){let{inputs:t,backend:r}=e,{data:n,indices:a,segmentIds:s}=t;if(n.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(a.shape.length!==1)throw new Error(`Indices should be a vector but received shape
${a.shape}`);if(s.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape
${s.shape}`);let i=r.readSync(n.dataId),o=r.readSync(a.dataId),l=r.readSync(s.dataId),[p,u]=IC(i,n.shape,n.dtype,o,l,!0);return r.makeTensorInfo(u,n.dtype,p)}var Bie={kernelName:Sd,backendName:"webgl",kernelFunc:Pie};function Wie(e){let{inputs:t,backend:r}=e,{data:n,indices:a,segmentIds:s}=t;if(n.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(a.shape.length!==1)throw new Error(`Indices should be a vector but received shape
${a.shape}`);if(s.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape
${s.shape}`);let i=r.readSync(n.dataId),o=r.readSync(a.dataId),l=r.readSync(s.dataId),[p,u]=IC(i,n.shape,n.dtype,o,l);return r.makeTensorInfo(u,n.dtype,p)}var Uie={kernelName:Nd,backendName:"webgl",kernelFunc:Wie};function Vie(e){let{inputs:t,backend:r,attrs:n}=e,{sparseIndices:a,sparseValues:s,defaultValue:i}=t,{outputShape:o}=n,{sliceRank:l,numUpdates:p,sliceSize:u,strides:d,outputSize:h}=_.calculateShapes(s,a,o),c=!1;if(s.dtype==="string"){let y=r.bufferSync(a),b=r.bufferSync(s),x=k.decodeString(r.readSync(i.dataId)[0]),v=fY(y,b,o,h,u,p,l,d,x,c);return r.makeTensorInfo(o,v.dtype,v.values)}let f=new cw(p,l,a.shape.length,s.shape.length,d,[h,1],c),m=r.runWebGLProgram(f,[s,a,i],s.dtype),g=ue({inputs:{x:m},backend:r,attrs:{shape:o}});return r.disposeIntermediateTensorInfo(m),g}var Gie={kernelName:Vu,backendName:"webgl",kernelFunc:Vie};function Hie(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{numOrSizeSplits:s,axis:i}=n,o=k.parseAxisParam(i,a.shape)[0],l=_.prepareSplitSize(a,s,o),p=a.shape.length,u=new Array(p).fill(0),d=a.shape.slice();return l.map(h=>{let c=[...d];c[o]=h;let f=mp({inputs:{x:a},backend:r,attrs:{begin:u,size:c}});return u[o]+=h,f})}var jie={kernelName:Wu,backendName:"webgl",kernelFunc:Hie},L1="return sqrt(x);",qie=Ke({opSnippet:L1,packedOpSnippet:L1,cpuKernelImpl:xY}),Kie={kernelName:Uo,backendName:"webgl",kernelFunc:qie},Xie="return x * x;",Zie=Ke({opSnippet:Xie}),Jie={kernelName:_d,backendName:"webgl",kernelFunc:Zie},z1="return (a - b) * (a - b);",Yie=lr({opSnippet:z1,packedOpSnippet:z1}),Qie={kernelName:Ho,backendName:"webgl",kernelFunc:Yie};function eoe(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t;if(a.dtype!=="string")throw new Error("Input must be of datatype string");let s=r.readSync(a.dataId),i=_.fromUint8ToStringArray(s),o=vY(i,"string",n);return r.makeTensorInfo(a.shape,"string",o)}var toe={kernelName:Td,backendName:"webgl",kernelFunc:eoe};function roe({inputs:e,attrs:t,backend:r}){let{x:n}=e,a=Cn+`
return x > 0.0 ? 1.0 : float(${t.alpha});
`,s=new aa(n.shape,a);return r.runWebGLProgram(s,[n],n.dtype)}var noe={kernelName:$s,backendName:"webgl",kernelFunc:roe},aoe=class{constructor(e,t,r){this.variableNames=["x"],this.outputShape=r;let n=r.length,a=pt(r.length),s=pt(r.length),i="";if(n===1)i="coords * strides + begin";else{let o=0;i=r.map((l,p)=>(o++,r.length===1?`coords * strides[${p}] + begin[${p}]`:`coords[${o-1}] * strides[${p}] + begin[${p}]`)).join(",")}this.userCode=`
${a} begin = ${a}(${e});
${a} strides = ${a}(${t});
void main() {
${s} coords = getOutputCoords();
setOutput(getX(${i}));
}
`}};function soe(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{begin:s,end:i,strides:o,beginMask:l,endMask:p,ellipsisMask:u,newAxisMask:d,shrinkAxisMask:h}=n,{finalShapeSparse:c,finalShape:f,isIdentity:m,sliceDim0:g,isSimpleSlice:y,begin:b,end:x,strides:v}=Wt.sliceInfo(a.shape,s,i,o,l,p,u,d,h),w;if(m)w=ue({inputs:{x:a},backend:r,attrs:{shape:f}});else if(g||y){k.assert(a.shape.length>=1,()=>`Input must have rank at least 1, got: ${a.shape.length}`);let T=Wt.computeOutShape(b,x,v),E=mp({inputs:{x:a},backend:r,attrs:{begin:b,size:T}});w=ue({inputs:{x:E},backend:r,attrs:{shape:f}}),r.disposeIntermediateTensorInfo(E)}else if(r.shouldExecuteOnCPU([a])){let T=r.readSync(a.dataId),E=Le(a.shape,a.dtype,T),$=wY(c,E,v,b);w=r.makeTensorInfo(f,a.dtype,$.values)}else{let T=new aoe(b,v,c);w=r.runWebGLProgram(T,[a],a.dtype)}let N=ue({inputs:{x:w},backend:r,attrs:{shape:f}});return r.disposeIntermediateTensorInfo(w),N}var ioe={kernelName:Gu,backendName:"webgl",kernelFunc:soe};function ooe(e){let{inputs:t,backend:r,attrs:n}=e,{separator:a,nGramWidths:s,leftPad:i,rightPad:o,padWidth:l,preserveShortSequences:p}=n,{data:u,dataSplits:d}=t,h=r.readSync(u.dataId),c=r.readSync(d.dataId),[f,m]=kY(h,c,a,s,i,o,l,p);return[r.makeTensorInfo([f.length],"string",f),r.makeTensorInfo(d.shape,"int32",m)]}var loe={kernelName:Cd,backendName:"webgl",kernelFunc:ooe};function uoe(e){let{inputs:t,backend:r,attrs:n}=e,{skipEmpty:a}=n,{input:s,delimiter:i}=t;if(s.dtype!=="string")throw new Error("Input must be of datatype string");if(s.shape.length!==1)throw new Error(`Input must be a vector, got shape: ${s.shape}`);if(i.shape.length!==0)throw new Error(`Delimiter must be a scalar, got shape: ${i.shape}`);let o=r.readSync(s.dataId),l=r.readSync(i.dataId)[0],[p,u,d]=IY(o,l,a),h=u.length;return[r.makeTensorInfo([h,2],"int32",p),r.makeTensorInfo([h],"string",u),r.makeTensorInfo([2],"int32",new Int32Array(d))]}var poe={kernelName:Ed,backendName:"webgl",kernelFunc:uoe};function doe(e){let{inputs:t,backend:r,attrs:n}=e,{numBuckets:a}=n,{input:s}=t;if(s.dtype!=="string")throw new Error("Input must be of datatype string");if(a<=0)throw new Error("Number of buckets must be at least 1");let i=r.readSync(s.dataId),o=SY(i,a);return r.makeTensorInfo(s.shape,"int32",o)}var hoe={kernelName:$d,backendName:"webgl",kernelFunc:doe},coe="return tan(x);",foe=Ke({opSnippet:coe}),moe={kernelName:qo,backendName:"webgl",kernelFunc:foe},goe=`
float e2x = exp(-2.0 * abs(x));
return sign(x) * (1.0 - e2x) / (1.0 + e2x);
`,yoe=Ke({opSnippet:goe}),boe={kernelName:Ko,backendName:"webgl",kernelFunc:yoe};function xoe(e){let{inputs:t,backend:r,attrs:n}=e,{tensor:a,indices:s,updates:i}=t,{sliceRank:o,numUpdates:l,sliceSize:p,strides:u,outputSize:d}=_.calculateShapes(i,s,a.shape),h=[d/p,p];if(d===0)return r.makeTensorInfo(a.shape,s.dtype);let c=ue({inputs:{x:s},backend:r,attrs:{shape:[l,o]}}),f=ue({inputs:{x:i},backend:r,attrs:{shape:[l,p]}}),m=ue({inputs:{x:a},backend:r,attrs:{shape:h}}),g=new cw(l,o,c.shape.length,f.shape.length,u,h,!1,!0),y=r.runWebGLProgram(g,[f,c,m],m.dtype),b=ue({inputs:{x:y},backend:r,attrs:{shape:a.shape}});return r.disposeIntermediateTensorInfo(c),r.disposeIntermediateTensorInfo(f),r.disposeIntermediateTensorInfo(m),r.disposeIntermediateTensorInfo(y),b}var voe={kernelName:Ou,backendName:"webgl",kernelFunc:xoe},woe=class{constructor(e,t){this.variableNames=["A"];let r=new Array(e.length);for(let s=0;s<r.length;s++)r[s]=e[s]*t[s];this.outputShape=r,this.rank=r.length;let n=pt(this.rank),a=koe(e);this.userCode=`
void main() {
${n} resRC = getOutputCoords();
setOutput(getA(${a}));
}
`}};function koe(e){let t=e.length;if(t>5)throw Error(`Tile for rank ${t} is not yet supported`);if(t===1)return`imod(resRC, ${e[0]})`;let r=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u"],n=[];for(let a=0;a<e.length;a++)n.push(`imod(${r[a]}, ${e[a]})`);return n.join()}function rE(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{reps:s}=n;if(a.dtype==="string"||a.shape.length>5){let o=r.readSync(a.dataId),l=a.dtype==="string"?o.map(d=>k.decodeString(d)):o,p=Le(a.shape,a.dtype,l),u=_Y(p,s);return r.makeTensorInfo(u.shape,u.dtype,u.values)}let i=new woe(a.shape,s);return r.runWebGLProgram(i,[a],a.dtype)}var Ioe={kernelName:Es,backendName:"webgl",kernelFunc:rE},Soe=class{constructor(e){this.variableNames=["x","indices"],this.customUniforms=[{name:"n",type:"int"},{name:"firstPass",type:"int"},{name:"negativeInf",type:"float"},{name:"dir",type:"int"},{name:"inc",type:"int"}],this.outputShape=e,this.userCode=`
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
int elemIdx = coords[1];
// We compare elements pair-wise within a group of size 2 * inc.
// The comparing rule for each group alternates between ascending
// and descending. Within each group, we compare each pair at
// positions i and i+inc. To decide whether an element at position i
// is x0 or x1, we mod it by 2 * inc, if the result is smaller than
// inc, it is in the first half of the group, we denote it as x0,
// otherwise we denote it as x1.
// For example, as shown in the Bitonic top K paper referenced above,
// Figure5(a) shows that element[1] is in the
// second half of the group when group size is 2, but it is in the
// first half of the group when group size is 4.
bool isFirstInPair = imod(elemIdx, 2 * inc) < inc;
int i = isFirstInPair ? elemIdx : elemIdx - inc;
int i0 = firstPass == 1 ? i : int(getIndices(batch, i));
int i1 = firstPass == 1 ? i + inc : int(getIndices(batch, i + inc));
float x0 = i0 < n ? getX(batch, i0) : negativeInf;
float x1 = i1 < n ? getX(batch, i1) : negativeInf;
// Denotes which direction indices are in (ascending or descending).
bool reverse = imod(elemIdx, 2 * dir) >= dir;
bool isGreater = x0 > x1 || (x0 == x1 && i1 > i0);
if (reverse == isGreater) { // Elements in opposite order of direction
int iTemp = i0;
i0 = i1;
i1 = iTemp;
}
if (isFirstInPair) {
setOutput(float(i0));
} else {
setOutput(float(i1));
}
}
`}},Noe=class{constructor(e){this.variableNames=["x","indices"],this.customUniforms=[{name:"n",type:"int"},{name:"firstPass",type:"int"},{name:"k",type:"int"}],this.outputShape=e,this.userCode=`
void main() {
// Takes max of indices (0, k), (1, k + 1), (2, k + 2) ...
ivec2 coords = getOutputCoords();
int batch = coords[0];
int elemIdx = coords[1];
// The output size is half of the previous size.
// If the previous sequence is | | | | _ _ _ _ | | | | _ _ _ _ (k=4),
// we only need to output the indices at positions |, the indices at
// positions _ can be thrown away, see Figure5(b) After Phase 2
// (Merge phase) in the Bitonic Top K paper referenced above.
// For example, the paper shows we only need to output the orange bars.
// The output sequence should look like this | | | | | | | |.
// Because the sequence is halved, to map the output index back
// to the previous sequence to find the corresponding value,
// we need to double the index. When we double the index,
// we basically interpolate a position, so 2i looks like
// | _ | _ | _ | _ | _ | _ | _. We move the | to the first k position
// of each 2k positions by - elemIdx % k. E.g. for output at
// index 4,5,6,7, we want to get the corresponding element at
// original index 8,9,10,11, for output at index 8,9,10,11,
// we want to get the corresponding element at original index
// 16,17,18,19, so on and so forth.
int i = elemIdx < k ? elemIdx : (elemIdx * 2 - imod(elemIdx, k));
int i0 = firstPass == 1 ? i : int(getIndices(batch, i));
int i1 = firstPass == 1 ? i + k : int(getIndices(batch, i + k));
float x0 = getX(batch, i0);
float x1 = i1 < n ? getX(batch, i1) : x0;
setOutput(x0 >= x1 ? float(i0) : float(i1));
}
`}};function js(e,t){t!==null&&e.disposeIntermediateTensorInfo(t)}function P1(e){let t=1;for(;t<e;)t*=2;return t}function _oe(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{k:s,sorted:i}=n,o=j().getNumber("TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD"),l=j().getNumber("TOPK_K_CPU_HANDOFF_THRESHOLD"),p=a.shape,u=p[p.length-1];if(r.shouldExecuteOnCPU([a])||u<o||s>l){let $=r.readSync(a.dataId),[R,F]=TY($,p,a.dtype,s,i);return[r.makeTensorInfo(R.shape,R.dtype,R.values),r.makeTensorInfo(F.shape,F.dtype,F.values)]}if(s===0)return p[p.length-1]=0,[r.makeTensorInfo(p,a.dtype,[]),r.makeTensorInfo(p,"int32",[])];if(u===1)return[a,dh({attrs:{shape:p,dtype:"int32",value:0},backend:r})];let d=r.texData.get(a.dataId),h=d!==null&&d.isPacked,c=h?r.unpackTensor(a):a,f=k.sizeFromShape(p)/u,m=ue({inputs:{x:c},attrs:{shape:[f,u]},backend:r});h&&js(r,c);let g=P1(s),y=P1(u),b=null,x=()=>b===null?[m,m]:[m,b],v=($,R,F)=>{let S=x(),D=new Soe(F),P=[[u],[b===null?1:0],[Number.NEGATIVE_INFINITY],[$],[R]],U=b;b=r.runWebGLProgram(D,S,"int32",P),js(r,U)};for(let $=1;$<g;$*=2){let R=$*2;for(let F=$;F>=1;F/=2)v(R,F,[f,y])}for(let $=y;$>g;$/=2){let R=x(),F=new Noe([f,$/2]),S=[[u],[b===null?1:0],[g]],D=b;b=r.runWebGLProgram(F,R,"int32",S),js(r,D);let P=g/2,U=P*2;for(let H=P;H>=1;H/=2)v(U,H,b.shape)}let w=b;b=mp({inputs:{x:b},backend:r,attrs:{begin:0,size:[f,s]}}),js(r,w);let N=KC({inputs:{x:m,indices:b},backend:r,attrs:{axis:1,batchDims:1}});js(r,m);let T=p.slice(0,-1);T.push(s),w=b,b=ue({inputs:{x:b},attrs:{shape:T},backend:r}),js(r,w);let E=N;return N=ue({inputs:{x:N},attrs:{shape:T},backend:r}),js(r,E),[N,b]}var Toe={kernelName:Hu,backendName:"webgl",kernelFunc:_oe},Coe=class{constructor(e,t,r,n,a,s){this.variableNames=["Image","Transforms"],this.outputShape=s;let i=r==="nearest"?1:2,o;switch(n){case"constant":o=1;break;case"reflect":o=2;break;case"wrap":o=3;break;case"nearest":o=4;break;default:o=1;break}this.userCode=`
float mapCoord(float outCoord, float len) {
float inCoord = outCoord;
if(${o} == 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 (${o} == 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 (${o} == 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(${a});
}
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(${a});
} 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 Eoe(e){let{inputs:t,backend:r,attrs:n}=e,{image:a,transforms:s}=t,{interpolation:i,fillMode:o,fillValue:l,outputShape:p}=n,[u,d,h,c]=a.shape,[f,m]=p??[d,h],g=[u,f,m,c],y=new Coe(d,h,i,o,l,g);return r.runWebGLProgram(y,[a,s],"float32")}var $oe={kernelName:ju,backendName:"webgl",kernelFunc:Eoe};function Aoe(e){let{inputs:t,attrs:r,backend:n}=e,{axis:a}=r,{x:s}=t;lp(s,"unique"),console.warn("WARNING: ","UI might be locked temporarily as data is being downloaded");let i=n.readSync(s.dataId),{outputValues:o,outputShape:l,indices:p}=CY(i,a,s.shape,s.dtype);return[n.makeTensorInfo(l,s.dtype,o),n.makeTensorInfo([p.length],"int32",p)]}var Foe={kernelName:Ad,backendName:"webgl",kernelFunc:Aoe};function Roe(e){let{inputs:t,backend:r,attrs:n}=e,{value:a}=t,{axis:s}=n;s<0&&(s+=a.shape.length);let i=a,o=i.shape.length,l=a.shape[s],p=new Array(o-1),u=0;for(let m=0;m<o;m++)m!==s&&(p[u++]=i.shape[m]);let d=[],h=new Array(o).fill(0),c=i.shape.slice();c[s]=1;let f=new Array(l);for(let m=0;m<f.length;m++){h[s]=m;let g=mp({inputs:{x:i},backend:r,attrs:{begin:h,size:c}}),y=ue({inputs:{x:g},backend:r,attrs:{shape:p}});f[m]=y,d.push(g)}return d.forEach(m=>r.disposeIntermediateTensorInfo(m)),f}var Doe={kernelName:qu,backendName:"webgl",kernelFunc:Roe},Moe=class{constructor(e,t){this.variableNames=["x","segmentIds"];let r=e.windowSize,n=e.batchSize,a=e.inSize,s=e.numSegments,i=s*Math.ceil(a/r);this.outputShape=[n,i];let o="0.0",l="sumValue",p=Math.floor(r/4)*4,u=r%4,d=`
sumValue += dot(values, segFilter);
`,h="";a%r>0&&(h=`
if (inIdx < 0 || inIdx >= ${a}) {
return initializationValue;
}
`);let c="";a%r>0&&(c=`
if (inIdx < 0 || inIdx >= ${a}) {
return -1.0;
}
`),this.userCode=`
const float initializationValue = ${o};
float getValue(int batch, int inIdx) {
${h}
return getX(batch, inIdx);
}
float getSegmentIdAtIndex(int inIdx) {
${c}
return getSegmentIds(inIdx);
}
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
int outIdx = coords[1];
int inOffset = int(floor(float(outIdx) / float(
${s})) * float(${r}));
int currentSeg = int(mod(float(outIdx), float(${s})));
float sumValue = 0.0;
for (int i = 0; i < ${p}; 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
);
${d}
}
int inIdx = inOffset + ${p};
if (${u===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
);
${d}
} else if (${u===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
);
${d}
} else if (${u===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
);
${d}
}
setOutput(${l});
}
`}};function Ooe(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,segmentIds:s}=t,{numSegments:i}=n,o=a.shape.length,l=[],p=0,u=_.getAxesPermutation([p],o),d=a;u!=null&&(d=xr({inputs:{x:a},backend:r,attrs:{perm:u}}),l.push(d),p=_.getInnerMostAxes(1,o)[0]);let h=_.segment_util.computeOutShape(d.shape,p,i),c=k.sizeFromShape([d.shape[p]]),f=ue({inputs:{x:d},backend:r,attrs:{shape:[-1,c]}});l.push(f);let m=cf(a.dtype),g=(v,w,N,T,E)=>{let $=v.shape[0],R=v.shape[1],F=_.segment_util.segOpComputeOptimalWindowSize(R,E),S={windowSize:F,inSize:R,batchSize:$,numSegments:E},D=new Moe(S,w),P=r.compileAndRun(D,[v,N],T);if(l.push(P),P.shape[1]===E)return P;let U=tE({backend:r,attrs:{start:0,stop:E,step:1,dtype:"float32"}}),H=rE({inputs:{x:U},backend:r,attrs:{reps:[R/F]}});return l.push(U),l.push(H),g(P,w,H,T,E)},y=g(f,"unsortedSegmentSum",s,m,i),b=ue({inputs:{x:y},backend:r,attrs:{shape:h}}),x=b;if(u!=null){l.push(b);let v=_.getUndoAxesPermutation(u);x=xr({inputs:{x},backend:r,attrs:{perm:v}})}return l.forEach(v=>r.disposeIntermediateTensorInfo(v)),x}var Loe={kernelName:Fd,backendName:"webgl",kernelFunc:Ooe},zoe=[wQ,IQ,_Q,EQ,AQ,DQ,OQ,zQ,UQ,GQ,qQ,ZQ,QQ,nee,iee,lee,pee,fee,gee,bee,kee,Eee,Aee,Mee,Lee,Vee,Hee,Xee,aQ,Yee,nte,ote,cte,gte,bte,vte,kte,_te,Ete,Fte,Dte,Ote,zte,Wte,Vte,qte,Xte,Yte,tre,nre,ore,dre,mre,bre,wre,kre,Sre,_re,Cre,$re,Fre,Ore,Pre,Ure,Gre,qre,Zre,ene,ane,nQ,ine,tte,une,hne,mne,iQ,xne,Ine,Nne,Ene,Fne,One,Pne,Vne,qne,Zne,Yne,rae,aae,iae,pae,hae,fae,gae,bae,kae,_ae,$ae,zae,uQ,Uae,Hae,Kae,Jae,Pee,ese,rse,ase,ose,dse,lQ,cse,mse,yse,xse,vse,Bee,Dae,Ise,Tse,Ase,dQ,Mse,zse,Use,Hse,Xse,Jse,eie,nie,iie,uie,hie,mie,xie,kie,_ie,Eie,Tee,Oae,Fie,Die,Oie,zie,Bie,Uie,Gie,jie,Kie,Jie,Qie,toe,noe,ioe,loe,poe,hoe,Mae,bQ,moe,boe,voe,Ioe,Toe,$oe,xQ,Foe,Doe,Loe,tse];for(let e of zoe)Rd(e);var Ze;(function(e){e[e.float32=0]="float32",e[e.int32=1]="int32",e[e.bool=2]="bool",e[e.string=3]="string",e[e.complex64=4]="complex64"})(Ze||(Ze={}));var ud;(function(e){e[e.linear=0]="linear",e[e.relu=1]="relu",e[e.relu6=2]="relu6",e[e.prelu=3]="prelu",e[e.leakyrelu=4]="leakyrelu",e[e.sigmoid=5]="sigmoid",e[e.elu=6]="elu"})(ud||(ud={}));var nE;function Poe(e){nE=e.wasm.cwrap(li,null,["number","array","number","number","array","number","number","number","number","number","number","number","number"])}function Boe(e){let{inputs:t,backend:r,attrs:n}=e,{a,b:s,bias:i,preluActivationWeights:o}=t;if(a.dtype!=="float32"||s.dtype!=="float32")throw new Error("_FusedMatMul for non non-float32 tensors not yet supported.");let{transposeA:l,transposeB:p,activation:u,leakyreluAlpha:d}=n,h=r.dataIdMap.get(a.dataId).id,c=r.dataIdMap.get(s.dataId).id,f=0;if(i!=null){let E=r.dataIdMap.get(i.dataId);if(E.shape.length!==1)throw new Error(`_FusedMatMul only supports rank-1 bias but got rank ${E.shape.length}.`);f=E.id}let m=o==null?0:r.dataIdMap.get(o.dataId).id,g=ud[u];if(g==null)throw new Error(`${u} activation not yet supported for FusedConv2D in the wasm backend.`);let y=l?a.shape[2]:a.shape[1],b=p?s.shape[1]:s.shape[2],x=Zu.assertAndGetBroadcastShape(a.shape.slice(0,-2),s.shape.slice(0,-2)),v=r.makeOutput([...x,y,b],a.dtype),w=r.dataIdMap.get(v.dataId).id,N=new Uint8Array(new Int32Array(a.shape).buffer),T=new Uint8Array(new Int32Array(s.shape).buffer);return nE(h,N,a.shape.length,c,T,s.shape.length,l,p,g,f,m,d||0,w),v}var Woe={kernelName:li,backendName:"wasm",setupFunc:Poe,kernelFunc:Boe};function je(e,t){let r;function n(s){r=s.wasm.cwrap(e,null,["number","number","number"])}function a(s){let{backend:i,inputs:{x:o}}=s,l=i.dataIdMap.get(o.dataId).id,p=i.makeOutput(o.shape,t||o.dtype),u=i.dataIdMap.get(p.dataId).id;return k.sizeFromShape(p.shape)===0||r(l,Ze[o.dtype],u),p}return{kernelName:e,backendName:"wasm",setupFunc:n,kernelFunc:a}}var Uoe=je(Kl),Voe=je($i),Goe=je(Ai);function zt(e,t,r){let n;function a(i){n=i.wasm.cwrap(e,null,["number","array","number","number","array","number","number","number"])}function s(i){let{backend:o,inputs:l}=i,{a:p,b:u}=l,d=o.dataIdMap.get(p.dataId).id,h=o.dataIdMap.get(u.dataId).id,c=r??p.dtype,f=_.assertAndGetBroadcastShape(p.shape,u.shape),m=o.makeOutput(f,c);if(k.sizeFromShape(f)===0)return m;let g=new Uint8Array(new Int32Array(p.shape).buffer),y=new Uint8Array(new Int32Array(u.shape).buffer),b=o.dataIdMap.get(m.dataId).id;return n(d,g,p.shape.length,h,y,u.shape.length,Ze[p.dtype],b),m}return{kernelName:e,backendName:"wasm",setupFunc:a,kernelFunc:s}}var Hoe=zt(Ts),aE;function joe(e){aE=e.wasm.cwrap(Fi,null,["array","number","number","number"])}function qoe(e){let{inputs:t,backend:r}=e,n=r.makeOutput(t[0].shape,t[0].dtype);if(k.sizeFromShape(n.shape)===0)return n;let a=t.map(o=>r.dataIdMap.get(o.dataId).id),s=new Uint8Array(new Int32Array(a).buffer),i=r.dataIdMap.get(n.dataId).id;return aE(s,a.length,Ze[n.dtype],i),n}var Koe={kernelName:Fi,backendName:"wasm",setupFunc:joe,kernelFunc:qoe};function km(e){let{inputs:{x:t},backend:r}=e;if(t.dtype==="string")return yr(r.readSync(t.dataId),t.shape,t.dtype);let n=r.makeOutput(t.shape,t.dtype),a=r.typedArrayFromHeap(t);return r.typedArrayFromHeap(n).set(a),n}var Xoe={kernelName:so,backendName:"wasm",kernelFunc:km},sE;function Zoe(e){sE=e.wasm.cwrap(Ta,null,["number","array","number","number","number","array","number"])}function Ss(e){let{inputs:t,backend:r,attrs:n}=e,[a,s]=Yoe(t.x.shape,n.perm),i=!0;for(let f=0;f<s.length;f++)s[f]!==f&&(i=!1);let o=Joe(t.x.shape,n.perm),l={dataId:t.x.dataId,shape:a,dtype:t.x.dtype};if(i){let f=km({inputs:t,backend:r});return f.shape=o,f}let p=r.makeOutput(o,l.dtype),u=r.dataIdMap.get(l.dataId).id,d=r.dataIdMap.get(p.dataId).id,h=new Uint8Array(new Int32Array(s).buffer),c=new Uint8Array(new Int32Array(l.shape).buffer);return sE(u,c,l.shape.length,Ze[l.dtype],d,h,s.length),p}function Joe(e,t){let r=new Array(e.length);for(let n=0;n<r.length;n++)r[n]=e[t[n]];return r}function Yoe(e,t){let r=[],n=[];for(let a=0;a<e.length;++a)e[a]!==1&&r.push(e[a]),e[t[a]]!==1&&n.push(t[a]);for(let a=0;a<n.length;++a){let s=-1;for(let i=0;i<n.length;++i)n[i]>=a&&(s===-1||n[s]>n[i])&&(s=i);n[s]=a}return[r,n]}var Qoe={kernelName:Ta,backendName:"wasm",kernelFunc:Ss,setupFunc:Zoe};function zs(e,t,r){let n=e.shape,a=e.shape.length,s=k.parseAxisParam(t,n),i=s,o=_.getAxesPermutation(i,a),l=null,p=!1;if(o!=null){let u=new Array(a);for(let h=0;h<u.length;h++)u[h]=n[o[h]];i=_.getInnerMostAxes(i.length,a),l=Ss({inputs:{x:e},attrs:{perm:o},backend:r});let d=r.dataIdMap.get(e.dataId).id;r.dataIdMap.get(l.dataId).id!==d&&(p=!0)}return{transposed:l,originalAxes:s,axes:i,inputWasTransposed:p}}var iE;function ele(e){iE=e.wasm.cwrap(Xl,null,["number, number, number"])}function tle(e){let{backend:t,inputs:r,attrs:n}=e,{axis:a,keepDims:s}=n,{x:i}=r,o=t.dataIdMap.get(i.dataId).id,l=i,{transposed:p,axes:u,originalAxes:d,inputWasTransposed:h}=zs(i,a,t);if(h){let b=t.dataIdMap.get(p.dataId).id;l=p,o=b}let c=l.shape.length;_.assertAxesAreInnerMostDims("all",u,c);let[f,m]=_.computeOutAndReduceShapes(l.shape,u),g=k.sizeFromShape(m),y=t.makeOutput(f,i.dtype);if(k.sizeFromShape(l.shape)!==0){let b=t.dataIdMap.get(y.dataId).id;iE(o,g,b)}if(h&&t.disposeData(p.dataId),s){let b=_.expandShapeToKeepDim(y.shape,d);y.shape=b}return y}var rle={kernelName:Xl,backendName:"wasm",setupFunc:ele,kernelFunc:tle},oE;function nle(e){oE=e.wasm.cwrap(Zl,null,["number, number, number"])}function ale(e){let{backend:t,inputs:r,attrs:n}=e,{axis:a,keepDims:s}=n,{x:i}=r,o=t.dataIdMap.get(i.dataId).id,l=i,{transposed:p,axes:u,originalAxes:d,inputWasTransposed:h}=zs(i,a,t);if(h){let b=t.dataIdMap.get(p.dataId).id;l=p,o=b}let c=l.shape.length;_.assertAxesAreInnerMostDims("any",u,c);let[f,m]=_.computeOutAndReduceShapes(l.shape,u),g=k.sizeFromShape(m),y=t.makeOutput(f,i.dtype);if(k.sizeFromShape(l.shape)!==0){let b=t.dataIdMap.get(y.dataId).id;oE(o,g,b)}if(h&&t.disposeData(p.dataId),s){let b=_.expandShapeToKeepDim(y.shape,d);y.shape=b}return y}var sle={kernelName:Zl,backendName:"wasm",setupFunc:nle,kernelFunc:ale};function lE(e){let t;function r(a){t=a.wasm.cwrap(e,null,["number","number","number","number","number"])}function n(a){let{backend:s,inputs:i,attrs:o}=a,{axis:l}=o,{x:p}=i,u=s.dataIdMap.get(p.dataId).id,d=u,h=p,{transposed:c,axes:f,inputWasTransposed:m}=zs(p,l,s);if(m){let w=s.dataIdMap.get(c.dataId).id;w!==u&&(h=c,d=w)}let g=h.shape.slice(0,-1),y=s.makeOutput(g,"int32"),b=s.dataIdMap.get(y.dataId).id,x=k.sizeFromShape(y.shape),v=h.shape[f[0]];return t(d,Ze[h.dtype],x,v,b),m&&s.disposeData(c.dataId),y}return{kernelName:e,backendName:"wasm",setupFunc:r,kernelFunc:n}}var ile=lE(Jl),ole=lE(Yl),lle=je(Ri),ule=je(Di),ple=je(Mi),dle=zt(Li),hle=je(Oi),uE;function cle(e){uE=e.wasm.cwrap(zi,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function fle(e){let{inputs:t,attrs:r,backend:n}=e,a=t.x,s=n.dataIdMap.get(a.dataId).id,{filterSize:i,strides:o,pad:l,dimRoundingMode:p}=r,u=_.computePool2DInfo(a.shape,i,o,1,l,p),d=u.filterHeight,h=u.filterWidth,c=u.padInfo.top,f=u.padInfo.right,m=u.padInfo.bottom,g=u.padInfo.left,y=u.strideHeight,b=u.strideWidth,x=u.inChannels;if(u.dataFormat!=="channelsLast")throw new Error(`wasm backend does not support dataFormat:'${u.dataFormat}'. Please use 'channelsLast'.`);if(u.dilationWidth!==1||u.dilationHeight!==1)throw new Error(`was backend only supports average pooling with dilation = [1, 1], got [${u.dilationHeight}, ${u.dilationWidth}].`);let v=n.makeOutput(u.outShape,"float32"),w=n.dataIdMap.get(v.dataId).id;return uE(s,a.shape[0],a.shape[1],a.shape[2],d,h,c,f,m,g,y,b,x,w),v}var mle={kernelName:zi,backendName:"wasm",setupFunc:cle,kernelFunc:fle},pE;function gle(e){pE=e.wasm.cwrap("AvgPool3D",null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function yle(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{filterSize:s,strides:i,pad:o,dimRoundingMode:l,dataFormat:p}=n,u=_.computePool3DInfo(a.shape,s,i,1,o,l,p),d=r.makeOutput(u.outShape,a.dtype);return pE(r.dataIdMap.get(a.dataId).id,r.dataIdMap.get(d.dataId).id,u.batchSize,u.inChannels,u.inDepth,u.inHeight,u.inWidth,u.outDepth,u.outHeight,u.outWidth,u.strideDepth,u.strideHeight,u.strideWidth,u.dilationDepth,u.dilationHeight,u.dilationWidth,u.effectiveFilterDepth,u.effectiveFilterHeight,u.effectiveFilterWidth,u.padInfo.front,u.padInfo.top,u.padInfo.left),d}var ble={kernelName:Ql,backendName:"wasm",setupFunc:gle,kernelFunc:yle},dE;function xle(e){dE=e.wasm.cwrap("AvgPool3DGrad",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"])}function vle(e){let{inputs:t,backend:r,attrs:n}=e,{dy:a,input:s}=t,{filterSize:i,strides:o,pad:l,dimRoundingMode:p}=n,u=_.computePool3DInfo(s.shape,i,o,1,l,p),d=r.makeOutput(s.shape,s.dtype);return dE(r.dataIdMap.get(a.dataId).id,r.dataIdMap.get(d.dataId).id,u.batchSize,u.inChannels,u.inDepth,u.inHeight,u.inWidth,u.outDepth,u.outHeight,u.outWidth,u.strideDepth,u.strideHeight,u.strideWidth,u.dilationDepth,u.dilationHeight,u.dilationWidth,u.effectiveFilterDepth,u.effectiveFilterHeight,u.effectiveFilterWidth,u.padInfo.front,u.padInfo.top,u.padInfo.left,u.filterDepth,u.filterHeight,u.filterWidth),d}var wle={kernelName:cd,backendName:"wasm",setupFunc:xle,kernelFunc:vle},hE;function kle(e){hE=e.wasm.cwrap("AvgPoolGrad",null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function Ile(e){let{inputs:t,backend:r,attrs:n}=e,{dy:a,input:s}=t,{filterSize:i,strides:o,pad:l}=n,p=_.computePool2DInfo(s.shape,i,o,1,l),u=r.makeOutput(s.shape,s.dtype);return hE(r.dataIdMap.get(a.dataId).id,r.dataIdMap.get(u.dataId).id,p.batchSize,p.inChannels,p.inHeight,p.inWidth,p.outHeight,p.outWidth,p.strideHeight,p.strideWidth,p.dilationHeight,p.dilationWidth,p.effectiveFilterHeight,p.effectiveFilterWidth,p.padInfo.top,p.padInfo.left,p.filterHeight,p.filterWidth),u}var Sle={kernelName:hd,backendName:"wasm",setupFunc:kle,kernelFunc:Ile};function Fr(e){let{inputs:t,attrs:r}=e,{x:n}=t,{shape:a}=r,s=k.sizeFromShape(n.shape),i=k.inferFromImplicitShape(a,s);return k.assert(s===k.sizeFromShape(i),()=>`new shape: ${i}, old shape: ${n.shape}. New shape and old shape must have the same number of elements.`),e.backend.incRef(n.dataId),{dataId:n.dataId,shape:i,dtype:n.dtype}}var Nle={kernelName:Fu,backendName:"wasm",kernelFunc:Fr},cE;function _le(e){cE=e.wasm.cwrap(Pi,null,["number","array","number","number","array","number","number","number","number"])}function Tle(e){let{inputs:t,backend:r,attrs:n}=e,{a,b:s}=t,{transposeA:i,transposeB:o}=n;if(a.dtype!=="float32"||s.dtype!=="float32")throw new Error("BatchMatMul for non non-float32 tensors not yet supported.");let l=a.shape.length,p=s.shape.length,u=i?a.shape[l-2]:a.shape[l-1],d=o?s.shape[p-1]:s.shape[p-2],h=i?a.shape[l-1]:a.shape[l-2],c=o?s.shape[p-2]:s.shape[p-1],f=a.shape.slice(0,-2),m=s.shape.slice(0,-2),g=k.sizeFromShape(f),y=k.sizeFromShape(m),b=Zu.assertAndGetBroadcastShape(a.shape.slice(0,-2),s.shape.slice(0,-2)).concat([h,c]);k.assert(u===d,()=>`Error in matMul: inner shapes (${u}) and (${d}) of Tensors with shapes ${a.shape} and ${s.shape} and transposeA=${i} and transposeB=${o} must match.`);let x=i?[g,u,h]:[g,h,u],v=o?[y,c,d]:[y,d,c],w=Fr({inputs:{x:a},backend:r,attrs:{shape:x}}),N=Fr({inputs:{x:s},backend:r,attrs:{shape:v}}),T=r.dataIdMap.get(w.dataId).id,E=r.dataIdMap.get(N.dataId).id,$=i?w.shape[2]:w.shape[1],R=o?N.shape[1]:N.shape[2],F=Math.max(g,y),S=r.makeOutput([F,$,R],w.dtype),D=r.dataIdMap.get(S.dataId).id,P=new Uint8Array(new Int32Array(w.shape).buffer),U=new Uint8Array(new Int32Array(N.shape).buffer);return cE(T,P,w.shape.length,E,U,N.shape.length,i,o,D),r.disposeData(w.dataId),r.disposeData(N.dataId),S.shape=b,S}var Cle={kernelName:Pi,backendName:"wasm",setupFunc:_le,kernelFunc:Tle};function _i(e){let{inputs:{x:t},attrs:{begin:r,size:n},backend:a}=e,[s,i]=Wt.parseSliceParams(t,r,n),o=Wt.isSliceContinous(t.shape,s,i),l=a.readSync(t.dataId),p=a.makeOutput(i,t.dtype),u=k.computeStrides(t.shape),d=a.dataIdMap.get(p.dataId);if(o){let f=Wt.computeFlatOffset(s,u);return t.dtype==="string"?d.stringBytes=l.slice(f,f+k.sizeFromShape(i)):a.typedArrayFromHeap(p).set(l.subarray(f,f+k.sizeFromShape(i))),p}if(t.dtype==="string"){let f=Rc(l,s,i,t.shape,t.dtype);return d.stringBytes=f,p}let h=a.typedArrayFromHeap(p),c=t.shape.length;if(c===2)Ele(l,u[0],h,s,i);else if(c===3)$le(l,u[0],u[1],h,s,i);else if(c===4)Ale(l,u[0],u[1],u[2],h,s,i);else{let f=Rc(l,s,i,t.shape,t.dtype);h.set(f)}return p}function Ele(e,t,r,n,a){let s=0,i=n[0],o=n[1],l=i+a[0];for(let p=i;p<l;p++){let u=p*t+o;r.set(e.subarray(u,u+a[1]),s),s+=a[1]}}function $le(e,t,r,n,a,s){let i=0,o=a[0],l=a[1],p=a[2],u=o+s[0],d=l+s[1];for(let h=o;h<u;h++)for(let c=l;c<d;c++){let f=h*t+c*r+p;n.set(e.subarray(f,f+s[2]),i),i+=s[2]}}function Ale(e,t,r,n,a,s,i){let o=0,l=s[0],p=s[1],u=s[2],d=l+i[0],h=p+i[1],c=u+i[2],f=s[3];for(let m=l;m<d;m++)for(let g=p;g<h;g++)for(let y=u;y<c;y++){let b=m*t+g*r+y*n+f;a.set(e.subarray(b,b+i[3]),o),o+=i[3]}}var Fle={kernelName:Pu,backendName:"wasm",kernelFunc:_i};function Rle(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{blockShape:s,crops:i}=n,o=s.reduce((y,b)=>y*b),l=_.getReshaped(a.shape,s,o),p=_.getPermuted(l.length,s.length),u=_.getReshapedPermuted(a.shape,s,o),d=_.getSliceBeginCoords(i,s.length),h=_.getSliceSize(u,i,s.length),c=Fr({inputs:{x:a},backend:r,attrs:{shape:l}}),f=Ss({inputs:{x:c},backend:r,attrs:{perm:p}}),m=Fr({inputs:{x:f},backend:r,attrs:{shape:u}}),g=_i({inputs:{x:m},backend:r,attrs:{begin:d,size:h}});return r.disposeData(c.dataId),r.disposeData(f.dataId),r.disposeData(m.dataId),g}var Dle={kernelName:eu,backendName:"wasm",kernelFunc:Rle},fE;function Mle(e){fE=e.wasm.cwrap(tu,null,["number","number","boolean","number","number","number"])}function Ole(e){let{backend:t,inputs:r,attrs:n}=e,{x:a,weights:s}=r,{size:i}=n,o=s.shape.reduce((d,h)=>d*h,1)!==0,l=a.shape.length===1?[i]:[a.shape[0],i],p=t.makeOutput(l,s.dtype);function u(d){return t.dataIdMap.get(d.dataId).id}return fE(u(a),i,o,u(s),Ze[s.dtype],u(p)),p}var Lle={kernelName:tu,backendName:"wasm",setupFunc:Mle,kernelFunc:Ole},zle=zt(ru);function Ple(e){let{inputs:t,backend:r}=e,{s0:n,s1:a}=t,s=r.typedArrayFromHeap(n),i=r.typedArrayFromHeap(a),o=_.assertAndGetBroadcastShape(Array.from(s),Array.from(i));return r.makeOutput([o.length],"int32",void 0,new Int32Array(o))}var Ble={kernelName:fd,backendName:"wasm",kernelFunc:Ple};function Ps(e){let{inputs:{x:t},attrs:{dtype:r},backend:n}=e,a=n.makeOutput(t.shape,r),s=n.typedArrayFromHeap(t);return n.typedArrayFromHeap(a).set(s),a}var Wle={kernelName:Bi,backendName:"wasm",kernelFunc:Ps},Ule=je(Wi),mE;function Vle(e){mE=e.wasm.cwrap(Cs,null,["number","number","number","number"])}function Gle(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{clipValueMin:s,clipValueMax:i}=n,o=r.dataIdMap.get(a.dataId).id,l=r.makeOutput(a.shape,a.dtype),p=r.dataIdMap.get(l.dataId).id;return mE(o,s,i,p),l}var Hle={kernelName:Cs,backendName:"wasm",setupFunc:Vle,kernelFunc:Gle};function gE(e){let{inputs:t,backend:r}=e,n=k.parseAxisParam(e.attrs.axis,t[0].shape)[0],a=t.map(c=>c.shape);_.assertParamsConsistent(a,n);let s=_.computeOutShape(t.map(c=>c.shape),n),i=t.filter(c=>k.sizeFromShape(c.shape)>0);if(i.length===1)return km({inputs:{x:i[0]},backend:r});let o=r.makeOutput(s,t[0].dtype);if(k.sizeFromShape(s)===0)return o;if(i[0].dtype==="string"){let c=i.map(x=>{let v=[-1,k.sizeFromShape(x.shape.slice(n))];return Fr({inputs:{x},backend:r,attrs:{shape:v}})}),f=c.map(x=>({vals:r.readSync(x.dataId),shape:x.shape}));s=_.computeOutShape(c.map(x=>x.shape),1);let m=c[0].shape[0]===1,g=Pv(f,s,t[0].dtype,m),y=_.computeOutShape(i.map(x=>x.shape),n);o.shape=y;let b=r.dataIdMap.get(o.dataId);return b.stringBytes=_.fromStringArrayToUint8(g),c.forEach(x=>r.disposeData(x.dataId)),o}let l=k.sizeFromShape(i[0].shape.slice(0,n)),p=0,u=i.map(c=>{let f=k.sizeFromShape(c.shape.slice(n));return p+=f,f}),d=i.map(c=>r.typedArrayFromHeap(c)),h=r.typedArrayFromHeap(o);for(let c=0;c<l;c++){let f=c*p;for(let m=0;m<d.length;m++){let g=u[m],y=c*g,b=d[m].subarray(y,y+g);h.set(b,f),f+=g}}return o}var jle={kernelName:nu,backendName:"wasm",kernelFunc:gE},yE;function qle(e){yE=e.wasm.cwrap(Ui,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function Kle(e){let{inputs:t,attrs:r,backend:n}=e,{x:a,filter:s}=t,i=n.dataIdMap.get(a.dataId).id,o=n.dataIdMap.get(s.dataId).id,{strides:l,dilations:p,pad:u,dimRoundingMode:d,dataFormat:h}=r,c=_.convertConv2DDataFormat(h),f=_.computeConv2DInfo(a.shape,s.shape,l,p,u,d,!1,c),m=f.filterHeight,g=f.filterWidth,y=f.padInfo.top,b=f.padInfo.right,x=f.padInfo.bottom,v=f.padInfo.left,w=f.dilationHeight,N=f.dilationWidth,T=f.strideHeight,E=f.strideWidth,$=f.inChannels,R=f.outChannels,F=f.padInfo.type==="SAME"?1:0;if(f.dataFormat!=="channelsLast")throw new Error(`wasm backend Conv2D does not support dataFormat:'${f.dataFormat}'. Please use 'channelsLast'.`);let S=n.makeOutput(f.outShape,"float32"),D=n.dataIdMap.get(S.dataId).id;return yE(i,a.shape[0],a.shape[1],a.shape[2],o,m,g,y,b,x,v,F,w,N,T,E,$,R,D),S}var Xle={kernelName:Ui,backendName:"wasm",setupFunc:qle,kernelFunc:Kle},bE;function Zle(e){bE=e.wasm.cwrap(Vi,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 Jle(e){let{backend:t,inputs:r,attrs:n}=e,{dy:a,filter:s}=r,{strides:i,pad:o,dataFormat:l,dimRoundingMode:p,inputShape:u}=n,d=1,h=_.convertConv2DDataFormat(l),c=_.computeConv2DInfo(u,s.shape,i,d,o,p,!1,h),{batchSize:f,filterHeight:m,filterWidth:g,inChannels:y,inHeight:b,inWidth:x,outChannels:v,outHeight:w,outWidth:N,strideHeight:T,strideWidth:E}=c,$=m-1-c.padInfo.top,R=g-1-c.padInfo.left,F=c.dataFormat==="channelsLast",S=k.computeStrides(c.inShape),D=k.computeStrides(a.shape),[P,U,H]=k.computeStrides(s.shape),q=S[0],G=F?S[1]:S[2],Z=F?S[2]:1,ee=F?1:S[1],X=D[0],re=F?D[1]:D[2],te=F?D[2]:1,ae=F?1:D[1],ie=t.makeOutput(c.inShape,"float32"),ve=t.dataIdMap.get(ie.dataId).id,be=t.dataIdMap.get(a.dataId).id,he=t.dataIdMap.get(s.dataId).id;return bE(be,he,f,m,g,b,x,y,w,N,v,T,E,$,R,P,U,H,q,G,Z,ee,X,re,te,ae,ve),ie}var Yle={kernelName:Vi,backendName:"wasm",setupFunc:Zle,kernelFunc:Jle},xE;function Qle(e){xE=e.wasm.cwrap(Gi,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"])}function eue(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,filter:s}=t,{strides:i,pad:o,dilations:l}=n;if(a.dtype!=="float32")throw new Error(`Tensor x must have dtype float32, got ${a.dtype}`);if(s.dtype!=="float32")throw new Error(`Tensor filter must have dtype float32, got ${s.dtype}`);let p=_.computeConv3DInfo(a.shape,s.shape,i,l,o),u=r.makeOutput(p.outShape,a.dtype);return xE(r.dataIdMap.get(a.dataId).id,r.dataIdMap.get(s.dataId).id,r.dataIdMap.get(u.dataId).id,p.batchSize,p.inDepth,p.inHeight,p.inWidth,p.inChannels,p.outDepth,p.outHeight,p.outWidth,p.outChannels,p.strideDepth,p.strideHeight,p.strideWidth,p.dilationDepth,p.dilationHeight,p.dilationWidth,p.filterDepth,p.filterHeight,p.filterWidth,p.padInfo.front,p.padInfo.top,p.padInfo.left),u}var tue={kernelName:Gi,backendName:"wasm",setupFunc:Qle,kernelFunc:eue},vE;function rue(e){vE=e.wasm.cwrap(au,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"])}function nue(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,dy:s}=t,{strides:i,pad:o,filterShape:l}=n;if(a.dtype!=="float32")throw new Error(`Tensor dy must have dtype float32, got ${a.dtype}`);if(s.dtype!=="float32")throw new Error(`Tensor filter must have dtype float32, got ${s.dtype}`);let p=_.computeConv3DInfo(a.shape,l,i,1,o),u=r.makeOutput(p.filterShape,s.dtype);return vE(r.dataIdMap.get(a.dataId).id,r.dataIdMap.get(s.dataId).id,r.dataIdMap.get(u.dataId).id,p.batchSize,p.inDepth,p.inHeight,p.inWidth,p.inChannels,p.outDepth,p.outHeight,p.outWidth,p.outChannels,p.strideDepth,p.strideHeight,p.strideWidth,p.dilationDepth,p.dilationHeight,p.dilationWidth,p.filterDepth,p.filterHeight,p.filterWidth,p.padInfo.front,p.padInfo.top,p.padInfo.left),u}var aue={kernelName:au,backendName:"wasm",setupFunc:rue,kernelFunc:nue},wE;function sue(e){wE=e.wasm.cwrap(su,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"])}function iue(e){let{inputs:t,backend:r,attrs:n}=e,{dy:a,filter:s}=t,{pad:i,strides:o,inputShape:l}=n;if(a.dtype!=="float32")throw new Error(`Tensor dy must have dtype float32, got ${a.dtype}`);if(s.dtype!=="float32")throw new Error(`Tensor filter must have dtype float32, got ${s.dtype}`);let p=_.computeConv3DInfo(l,s.shape,o,1,i),u=r.makeOutput(p.inShape,a.dtype);return wE(r.dataIdMap.get(s.dataId).id,r.dataIdMap.get(a.dataId).id,r.dataIdMap.get(u.dataId).id,p.batchSize,p.inDepth,p.inHeight,p.inWidth,p.inChannels,p.outDepth,p.outHeight,p.outWidth,p.outChannels,p.strideDepth,p.strideHeight,p.strideWidth,p.dilationDepth,p.dilationHeight,p.dilationWidth,p.filterDepth,p.filterHeight,p.filterWidth,p.padInfo.front,p.padInfo.top,p.padInfo.left),u}var oue={kernelName:su,backendName:"wasm",setupFunc:sue,kernelFunc:iue},lue=je(Hi),uue=je(ji),ey;(function(e){e[e.bilinear=0]="bilinear",e[e.nearest=1]="nearest"})(ey||(ey={}));var kE;function pue(e){kE=e.wasm.cwrap(ou,null,["number","number","number","number","array","number","number","number","number","number"])}function due(e){let{backend:t,inputs:r,attrs:n}=e,{method:a,extrapolationValue:s,cropSize:i}=n,{image:o,boxes:l,boxInd:p}=r,u=l.shape[0],[d,h]=i,c=[u,d,h,o.shape[3]],f=t.dataIdMap.get(o.dataId),m;o.dtype!=="float32"&&(m=Ps({backend:t,inputs:{x:o},attrs:{dtype:"float32"}}),f=t.dataIdMap.get(m.dataId));let g=f.id,y=t.dataIdMap.get(l.dataId).id,b=t.dataIdMap.get(p.dataId).id,x=t.makeOutput(c,"float32"),v=t.dataIdMap.get(x.dataId).id,w=new Uint8Array(new Int32Array(o.shape).buffer);return kE(g,y,b,u,w,d,h,ey[a],s,v),m!=null&&t.disposeData(m.dataId),x}var hue={kernelName:ou,backendName:"wasm",setupFunc:pue,kernelFunc:due},IE;function cue(e){IE=e.wasm.cwrap(iu,null,["number","number","number","number","number","number"])}function fue(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{axis:s,exclusive:i,reverse:o}=n,l=a.shape.length;k.assert(a.dtype==="float32"||a.dtype==="int32",()=>`cumprod does not support ${a.dtype} tensors in the WASM backend`);let p=_.getAxesPermutation([s],l),u=a;p!==null&&(u=Ss({inputs:{x:a},attrs:{perm:p},backend:r}));let d=_.getInnerMostAxes(1,l)[0];_.assertAxesAreInnerMostDims("cumprod",[d],l);let h=r.makeOutput(u.shape,u.dtype),c=u.shape[d],f=r.dataIdMap.get(u.dataId).id,m=r.dataIdMap.get(h.dataId).id;IE(f,i?1:0,o?1:0,c,m,Ze[a.dtype]);let g=h;if(p!==null){let y=_.getUndoAxesPermutation(p);g=Ss({inputs:{x:h},attrs:{perm:y},backend:r}),r.disposeData(u.dataId),r.disposeData(h.dataId)}return g}var mue={kernelName:iu,backendName:"wasm",setupFunc:cue,kernelFunc:fue},SE;function gue(e){SE=e.wasm.cwrap(qi,null,["number","number","number","number","number","number"])}function yue(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{axis:s,exclusive:i,reverse:o}=n,l=a.shape.length;k.assert(a.dtype==="float32"||a.dtype==="int32",()=>`cumsum does not support ${a.dtype} tensors in the WASM backend`);let p=_.getAxesPermutation([s],l),u=a;p!==null&&(u=Ss({inputs:{x:a},attrs:{perm:p},backend:r}));let d=_.getInnerMostAxes(1,l)[0];_.assertAxesAreInnerMostDims("cumsum",[d],l);let h=r.makeOutput(u.shape,u.dtype),c=u.shape[d],f=r.dataIdMap.get(u.dataId).id,m=r.dataIdMap.get(h.dataId).id;SE(f,i?1:0,o?1:0,c,m,Ze[a.dtype]);let g=h;if(p!==null){let y=_.getUndoAxesPermutation(p);g=Ss({inputs:{x:h},attrs:{perm:y},backend:r}),r.disposeData(u.dataId),r.disposeData(h.dataId)}return g}var bue={kernelName:qi,backendName:"wasm",setupFunc:gue,kernelFunc:yue},NE;function xue(e){NE=e.wasm.cwrap("DenseBincount",null,["number","array","number","number","boolean","number","number","boolean","number"])}function vue(e){let{backend:t,inputs:r,attrs:n}=e,{x:a,weights:s}=r,{size:i,binaryOutput:o}=n,l=s.shape.reduce((h,c)=>h*c,1)!==0,p=a.shape.length===1?[i]:[a.shape[0],i],u=t.makeOutput(p,s.dtype);function d(h){return t.dataIdMap.get(h.dataId).id}return NE(d(a),new Uint8Array(new Int32Array(a.shape).buffer),a.shape.length,i,l,d(s),Ze[s.dtype],o,d(u)),u}var wue={kernelName:gd,backendName:"wasm",setupFunc:xue,kernelFunc:vue},_E;function kue(e){_E=e.wasm.cwrap(lu,null,["number","number","number","array","number","array","array","number","number"])}function Iue(e){let{backend:t,inputs:r,attrs:n}=e,{x:a}=r,{blockSize:s,dataFormat:i}=n,o=a.shape[0],l=i==="NHWC"?a.shape[1]:a.shape[2],p=i==="NHWC"?a.shape[2]:a.shape[3],u=i==="NHWC"?a.shape[3]:a.shape[1],d=l*s,h=p*s,c=u/(s*s),f=i==="NHWC"?[o,d,h,c]:[o,c,d,h],m=t.makeOutput(f,"float32"),g=t.dataIdMap.get(a.dataId).id,y=new Uint8Array(new Int32Array(k.computeStrides(a.shape)).buffer),b=new Uint8Array(new Int32Array(f).buffer),x=new Uint8Array(new Int32Array(k.computeStrides(f)).buffer),v=t.dataIdMap.get(m.dataId).id;return _E(g,s,i==="NHWC"?1:0,y,a.shape.length-1,b,x,f.length,v),m}var Sue={kernelName:lu,backendName:"wasm",setupFunc:kue,kernelFunc:Iue},TE;function Nue(e){TE=e.wasm.cwrap(Ki,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function _ue(e){let{inputs:t,attrs:r,backend:n}=e,{x:a,filter:s}=t,i=n.dataIdMap.get(a.dataId).id,o=n.dataIdMap.get(s.dataId).id,{strides:l,dilations:p,pad:u,dimRoundingMode:d}=r,h=p??[1,1],c=_.computeConv2DInfo(a.shape,s.shape,l,h,u,d,!0),f=c.filterHeight,m=c.filterWidth,g=c.padInfo.top,y=c.padInfo.right,b=c.padInfo.bottom,x=c.padInfo.left,v=c.dilationHeight,w=c.dilationWidth,N=c.strideHeight,T=c.strideWidth,E=c.inChannels,$=c.outChannels,R=c.padInfo.type==="SAME"?1:0;if(c.dataFormat!=="channelsLast")throw new Error(`wasm backend DepthwiseConv2dNative does not support dataFormat:'${c.dataFormat}'. Please use 'channelsLast'.`);let F=n.makeOutput(c.outShape,"float32"),S=n.dataIdMap.get(F.dataId).id;return TE(i,a.shape[0],a.shape[1],a.shape[2],o,f,m,g,y,b,x,R,v,w,N,T,E,$,S),F}var Tue={kernelName:Ki,backendName:"wasm",setupFunc:Nue,kernelFunc:_ue},CE;function Cue(e){CE=e.wasm.cwrap("Diag",null,["number","number","number","number"])}function Eue(e){let{inputs:t,backend:r}=e,{x:n}=t,a=k.sizeFromShape(n.shape),s=r.makeOutput([...n.shape,...n.shape],n.dtype);return CE(r.dataIdMap.get(n.dataId).id,Ze[n.dtype],a,r.dataIdMap.get(s.dataId).id),s}var $ue={kernelName:yd,backendName:"wasm",setupFunc:Cue,kernelFunc:Eue},EE;function Aue(e){EE=e.wasm.cwrap(Xi,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function Fue(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,filter:s}=t,{strides:i,pad:o,dilations:l}=n;if(a.dtype!==s.dtype)throw new Error(`Dilation2D error: x must have the same dtype as filter. Got ${a.dtype} and ${s.dtype}`);let p=_.computeDilation2DInfo(a.shape,s.shape,i,o,"NHWC",l),u=r.makeOutput(p.outShape,a.dtype);return EE(r.dataIdMap.get(a.dataId).id,r.dataIdMap.get(s.dataId).id,r.dataIdMap.get(u.dataId).id,Ze[a.dtype],p.batchSize,p.inChannels,p.inHeight,p.inWidth,p.outHeight,p.outWidth,p.strideHeight,p.strideWidth,p.dilationHeight,p.dilationWidth,p.filterHeight,p.filterWidth,p.padInfo.top,p.padInfo.left),u}var Rue={kernelName:Xi,backendName:"wasm",setupFunc:Aue,kernelFunc:Fue},$E;function Due(e){$E=e.wasm.cwrap(Cl,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function Mue(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,filter:s,dy:i}=t,{strides:o,pad:l,dilations:p}=n;if(a.dtype!==s.dtype||a.dtype!==i.dtype)throw new Error(`Dilation2DBackpropFilter error: x must have the same dtype as filter and dy. Got ${a.dtype}, ${s.dtype}, and ${i.dtype}`);let u=_.computeDilation2DInfo(a.shape,s.shape,o,l,"NHWC",p),d=r.makeOutput(s.shape,s.dtype);return $E(r.dataIdMap.get(a.dataId).id,r.dataIdMap.get(s.dataId).id,r.dataIdMap.get(i.dataId).id,r.dataIdMap.get(d.dataId).id,Ze[a.dtype],u.batchSize,u.inChannels,u.inHeight,u.inWidth,u.outHeight,u.outWidth,u.strideHeight,u.strideWidth,u.dilationHeight,u.dilationWidth,u.filterHeight,u.filterWidth,u.padInfo.top,u.padInfo.left),d}var Oue={kernelName:Cl,backendName:"wasm",setupFunc:Due,kernelFunc:Mue},AE;function Lue(e){AE=e.wasm.cwrap(Tl,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function zue(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,filter:s,dy:i}=t,{strides:o,pad:l,dilations:p}=n;if(a.dtype!==s.dtype||a.dtype!==i.dtype)throw new Error(`Dilation2DBackpropInput error: x must have the same dtype as filter and dy. Got ${a.dtype}, ${s.dtype}, and ${i.dtype}`);let u=_.computeDilation2DInfo(a.shape,s.shape,o,l,"NHWC",p),d=r.makeOutput(a.shape,a.dtype);return AE(r.dataIdMap.get(a.dataId).id,r.dataIdMap.get(s.dataId).id,r.dataIdMap.get(i.dataId).id,r.dataIdMap.get(d.dataId).id,Ze[a.dtype],u.batchSize,u.inChannels,u.inHeight,u.inWidth,u.outHeight,u.outWidth,u.strideHeight,u.strideWidth,u.dilationHeight,u.dilationWidth,u.filterHeight,u.filterWidth,u.padInfo.top,u.padInfo.left),d}var Pue={kernelName:Tl,backendName:"wasm",setupFunc:Lue,kernelFunc:zue},Bue=je(Ji),FE;function Wue(e){FE=e.wasm.cwrap(uu,null,["number","number","number"])}function Uue(e){let{inputs:t,backend:r}=e,{dy:n,y:a}=t,s=r.makeOutput(a.shape,"float32"),i=o=>r.dataIdMap.get(o.dataId).id;return FE(i(a),i(n),i(s)),s}var Vue={kernelName:uu,backendName:"wasm",setupFunc:Wue,kernelFunc:Uue},Gue=!1,Hue=zt(pu,Gue,"bool"),jue=je(Yi),que=je(Qi,"float32");function ty(e){let{inputs:t,attrs:r,backend:n}=e,{input:a}=t,{dim:s}=r,i=a.shape.length,o=a.shape.slice(),l=s;return s<0&&(k.assert(-(i+1)<=s,()=>`Axis must be in the interval [${-(i+1)}, ${i}]`),l=i+s+1),o.splice(l,0,1),Fr({inputs:{x:a},backend:n,attrs:{shape:o}})}var Kue={kernelName:du,backendName:"wasm",kernelFunc:ty},Xue=je(eo,"float32");function RE(e){let{attrs:{shape:t,value:r},backend:n}=e,{attrs:{dtype:a}}=e;a=a||k.inferDtype(r);let s=n.makeOutput(t,a);return n.typedArrayFromHeap(s).fill(r),s}var Zue={kernelName:bd,backendName:"wasm",kernelFunc:RE},DE;function Jue(e){DE=e.wasm.cwrap(hu,null,["number","number","number","number","number","number"])}function Yue(e){let{inputs:t,backend:r}=e,{image:n}=t,a=r.makeOutput(n.shape,n.dtype),s=r.dataIdMap.get(n.dataId).id,i=r.dataIdMap.get(a.dataId).id,[o,l,p,u]=n.shape;return DE(s,o,l,p,u,i),a}var Que={kernelName:hu,backendName:"wasm",kernelFunc:Yue,setupFunc:Jue},epe=je(to),tpe=zt(ro),ME;function rpe(e){ME=e.wasm.cwrap(no,null,["number","number","number","number","number","number","number"])}function npe(e){let{backend:t,inputs:r,attrs:n}=e,{varianceEpsilon:a}=n,{x:s,mean:i,variance:o,offset:l,scale:p}=r,u=t.dataIdMap.get(s.dataId).id,d=t.dataIdMap.get(i.dataId).id,h=t.dataIdMap.get(o.dataId).id,c=l!=null?t.dataIdMap.get(l.dataId).id:0,f=p!=null?t.dataIdMap.get(p.dataId).id:0,m=t.makeOutput(s.shape,s.dtype);if(k.sizeFromShape(s.shape)===0)return m;let g=t.dataIdMap.get(m.dataId).id;return ME(u,d,h,c,f,a,g),m}var ape={kernelName:no,backendName:"wasm",setupFunc:rpe,kernelFunc:npe},OE;function spe(e){OE=e.wasm.cwrap(ui,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 ipe(e){let{inputs:t,attrs:r,backend:n}=e,{x:a,filter:s,bias:i,preluActivationWeights:o}=t,{strides:l,pad:p,dilations:u,dataFormat:d,dimRoundingMode:h,activation:c,leakyreluAlpha:f}=r,m=_.computeConv2DInfo(a.shape,s.shape,l,u,p,h),g=ud[c];if(g==null)throw new Error(`${c} activation not yet supported for FusedConv2D in the wasm backend.`);let y=n.dataIdMap.get(a.dataId).id,b=n.dataIdMap.get(s.dataId).id,x=m.outChannels,v=0;if(i!=null){let te=n.dataIdMap.get(i.dataId);if(te.shape.length!==1)throw new Error(`FusedConv2D only supports rank-1 bias but got rank ${te.shape.length}.`);if(te.shape[0]!==x)throw new Error(`FusedConv2D bias shape (${te.shape}) does not match the number of output channels (${x})`);v=te.id}let w=m.filterHeight,N=m.filterWidth,T=m.padInfo.top,E=m.padInfo.right,$=m.padInfo.bottom,R=m.padInfo.left,F=m.dilationHeight,S=m.dilationWidth,D=m.strideHeight,P=m.strideWidth,U=m.inChannels,H=m.padInfo.type==="SAME"?1:0,q=m.batchSize,G=m.inHeight,Z=m.inWidth;if(d!=="NHWC")throw new Error(`wasm backend FusedConv2D does not support dataFormat:'${d}'. Please use 'NHWC'.`);let ee=n.makeOutput(m.outShape,"float32"),X=n.dataIdMap.get(ee.dataId).id,re=o==null?0:n.dataIdMap.get(o.dataId).id;return OE(y,q,G,Z,b,w,N,v,T,E,$,R,H,F,S,D,P,U,x,g,re,f||0,X),ee}var ope={kernelName:ui,backendName:"wasm",setupFunc:spe,kernelFunc:ipe},LE;function lpe(e){LE=e.wasm.cwrap(pi,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 upe(e){let{inputs:t,attrs:r,backend:n}=e,{x:a,filter:s,bias:i,preluActivationWeights:o}=t,{strides:l,pad:p,dilations:u,dataFormat:d,dimRoundingMode:h,activation:c,leakyreluAlpha:f}=r,m=_.computeConv2DInfo(a.shape,s.shape,l,u,p,h,!0),g=ud[c];if(g==null)throw new Error(`${c} activation not yet supported for FusedDepthwiseConv2D in the wasm backend.`);let y=n.dataIdMap.get(a.dataId).id,b=n.dataIdMap.get(s.dataId).id,x=m.outChannels,v=0;if(i!=null){let te=n.dataIdMap.get(i.dataId);if(te.shape.length!==1)throw new Error(`FusedDepthwiseConv2D only supports rank-1 bias but got rank ${te.shape.length}.`);if(te.shape[0]!==x)throw new Error(`FusedDepthwiseConv2D bias shape (${te.shape}) does not match the number of output channels (${x})`);v=te.id}let w=m.filterHeight,N=m.filterWidth,T=m.padInfo.top,E=m.padInfo.right,$=m.padInfo.bottom,R=m.padInfo.left,F=m.dilationHeight,S=m.dilationWidth,D=m.strideHeight,P=m.strideWidth,U=m.inChannels,H=m.padInfo.type==="SAME"?1:0,q=m.batchSize,G=m.inHeight,Z=m.inWidth;if(d!=="NHWC")throw new Error(`wasm backend FusedDepthwiseConv2D does not support dataFormat:'${d}'. Please use 'NHWC'.`);let ee=n.makeOutput(m.outShape,"float32"),X=n.dataIdMap.get(ee.dataId).id,re=o==null?0:n.dataIdMap.get(o.dataId).id;return LE(y,q,G,Z,b,w,N,v,T,E,$,R,H,F,S,D,P,U,x,g,re,f||0,X),ee}var ppe={kernelName:pi,backendName:"wasm",setupFunc:lpe,kernelFunc:upe},zE;function dpe(e){zE=e.wasm.cwrap(fu,null,["number","number","number","number","number","number","array","number"])}function hpe(e){let{backend:t,inputs:r}=e,{params:n,indices:a}=r,[s,i,o,l]=Jb.prepareAndValidate(n,a),p=t.makeOutput(s,n.dtype);if(i===0)return p;let u=a.shape,d=u[u.length-1],h=t.dataIdMap.get(n.dataId).id,c=t.dataIdMap.get(a.dataId).id,f=new Uint8Array(new Int32Array(l).buffer),m=t.dataIdMap.get(p.dataId).id;return zE(h,Ze[n.dtype],c,i,d,o,f,m),p}var cpe={kernelName:fu,backendName:"wasm",setupFunc:dpe,kernelFunc:hpe},PE;function fpe(e){PE=e.wasm.cwrap("Gather",null,["number","number","array","number","number","number","array","number"])}function mpe(e){let{backend:t,inputs:r,attrs:n}=e,{x:a,indices:s}=r,{axis:i,batchDims:o}=n,l=k.parseAxisParam(i,a.shape)[0],p=t.readSync(s.dataId),u=a.shape[l];for(let T=0;T<p.length;++T){let E=p[T];k.assert(E<=u-1&&E>=0,()=>`GatherV2: the index value ${E} is not in [0, ${u-1}]`)}let d=_.segment_util.collectGatherOpShapeInfo(a,s,l,o),h=Fr({inputs:{x:a},attrs:{shape:[d.batchSize,d.outerSize,d.dimSize,d.sliceSize]},backend:t}),c=k.sizeFromShape(s.shape),f=Fr({inputs:{x:s},attrs:{shape:[d.batchSize,c/d.batchSize]},backend:t}),m=[d.batchSize,d.outerSize,c/d.batchSize,d.sliceSize],g=t.makeOutput(m,a.dtype);if(k.sizeFromShape(a.shape)===0)return g;let y=h.shape.length-1,b=t.dataIdMap.get(h.dataId).id,x=t.dataIdMap.get(f.dataId).id,v=t.dataIdMap.get(g.dataId).id,w=new Uint8Array(new Int32Array(k.computeStrides(h.shape)).buffer),N=new Uint8Array(new Int32Array(k.computeStrides(m)).buffer);return PE(b,Ze[a.dtype],w,y,x,d.batchSize,N,v),t.disposeData(h.dataId),t.disposeData(f.dataId),g.shape=d.outputShape,g}var gpe={kernelName:cu,backendName:"wasm",setupFunc:fpe,kernelFunc:mpe},ype=!1,bpe=zt(mu,ype,"bool"),xpe=!1,vpe=zt(ao,xpe,"bool"),wpe=je(io,"bool"),kpe=je(oo,"bool"),Ipe=je(lo,"bool"),BE;function Spe(e){BE=e.wasm.cwrap(uo,null,["number","number","number","number"])}function Npe(e){let{inputs:{x:t},attrs:{alpha:r},backend:n}=e,a=n.dataIdMap.get(t.dataId).id,s=n.makeOutput(t.shape,"float32");if(k.sizeFromShape(t.shape)!==0){let i=n.dataIdMap.get(s.dataId).id;BE(a,Ze[t.dtype],r,i)}return s}var _pe={kernelName:uo,backendName:"wasm",setupFunc:Spe,kernelFunc:Npe},Tpe=!1,Cpe=zt(gu,Tpe,"bool"),Epe=!1,$pe=zt(yu,Epe,"bool"),WE;function Ape(e){WE=e.wasm.cwrap(bu,null,["number","number","number","number"])}function Fpe(e){let{attrs:t,backend:r}=e,{start:n,stop:a,num:s}=t,i=Math.floor(s),o=r.makeOutput([i],"float32");return WE(r.dataIdMap.get(o.dataId).id,n,a,i),o}var Rpe={kernelName:bu,backendName:"wasm",setupFunc:Ape,kernelFunc:Fpe},Dpe=je(po),Mpe=je(ho),Ope=!1,Lpe=zt(xu,Ope,"bool"),zpe=je(vu),Ppe=!1,Bpe=zt(wu,Ppe,"bool"),Wpe=!1,Upe=zt(Bk,Wpe,"bool"),UE;function Vpe(e){UE=e.wasm.cwrap(co,null,["number","number","number","number","number","number","number"])}function Gpe(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{depthRadius:s,bias:i,alpha:o,beta:l}=n;if(a.dtype!=="float32")throw new Error("LRN error: x must have dtype float32");let p=r.makeOutput(a.shape,a.dtype);return UE(r.dataIdMap.get(a.dataId).id,r.dataIdMap.get(p.dataId).id,a.shape[3],s,i,o,l),p}var Hpe={kernelName:co,backendName:"wasm",setupFunc:Vpe,kernelFunc:Gpe},VE;function jpe(e){VE=e.wasm.cwrap(ku,null,["number","number","number","number","number","number","number","number","number"])}function qpe(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,y:s,dy:i}=t,{depthRadius:o,bias:l,alpha:p,beta:u}=n;if(a.dtype!=="float32"||s.dtype!=="float32"||i.dtype!=="float32")throw new Error("LRNGrad error: x, y, and dy must have dtype float32");let d=r.makeOutput(a.shape,a.dtype);return VE(r.dataIdMap.get(a.dataId).id,r.dataIdMap.get(s.dataId).id,r.dataIdMap.get(i.dataId).id,r.dataIdMap.get(d.dataId).id,i.shape[3],o,l,p,u),d}var Kpe={kernelName:ku,backendName:"wasm",setupFunc:jpe,kernelFunc:qpe},GE;function Xpe(e){GE=e.wasm.cwrap(fo,null,["number","number","number","number"])}function Zpe(e){let{backend:t,inputs:r,attrs:n}=e,{reductionIndices:a,keepDims:s}=n,{x:i}=r,o=t.dataIdMap.get(i.dataId).id,l=i,{transposed:p,axes:u,originalAxes:d,inputWasTransposed:h}=zs(i,a,t);if(h){let b=t.dataIdMap.get(p.dataId).id;l=p,o=b}let c=l.shape.length;_.assertAxesAreInnerMostDims("max",u,c);let[f,m]=_.computeOutAndReduceShapes(l.shape,u),g=k.sizeFromShape(m),y=t.makeOutput(f,i.dtype);if(k.sizeFromShape(l.shape)!==0){let b=t.dataIdMap.get(y.dataId).id;GE(o,Ze[i.dtype],g,b)}if(h&&t.disposeData(p.dataId),s){let b=_.expandShapeToKeepDim(y.shape,d);y.shape=b}return y}var Jpe={kernelName:fo,backendName:"wasm",setupFunc:Xpe,kernelFunc:Zpe},Ype=zt(mo),HE;function Qpe(e){HE=e.wasm.cwrap(go,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function ede(e){let{inputs:t,attrs:r,backend:n}=e,a=t.x,s=n.dataIdMap.get(a.dataId).id;k.assert(a.dtype==="float32",()=>`Error in MaxPool: only float32 input is supported. Got ${a.dtype}.`);let{filterSize:i,strides:o,pad:l,dimRoundingMode:p}=r,u=_.computePool2DInfo(a.shape,i,o,1,l,p),d=u.filterHeight,h=u.filterWidth,c=u.padInfo.top,f=u.padInfo.right,m=u.padInfo.bottom,g=u.padInfo.left,y=u.dilationHeight,b=u.dilationWidth,x=u.strideHeight,v=u.strideWidth,w=u.inChannels,N=u.outChannels;if(u.dataFormat!=="channelsLast")throw new Error(`wasm backend does not support dataFormat:'${u.dataFormat}'. Please use 'channelsLast'.`);let T=n.makeOutput(u.outShape,"float32"),E=n.dataIdMap.get(T.dataId).id;return HE(s,a.shape[0],a.shape[1],a.shape[2],d,h,c,f,m,g,y,b,x,v,w,N,E),T}var tde={kernelName:go,backendName:"wasm",setupFunc:Qpe,kernelFunc:ede},jE;function rde(e){jE=e.wasm.cwrap("MaxPool3D",null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function nde(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{filterSize:s,strides:i,pad:o,dimRoundingMode:l,dataFormat:p}=n,u=_.computePool3DInfo(a.shape,s,i,1,o,l,p),d=r.makeOutput(u.outShape,a.dtype);return jE(r.dataIdMap.get(a.dataId).id,r.dataIdMap.get(d.dataId).id,u.batchSize,u.inChannels,u.inDepth,u.inHeight,u.inWidth,u.outDepth,u.outHeight,u.outWidth,u.strideDepth,u.strideHeight,u.strideWidth,u.dilationDepth,u.dilationHeight,u.dilationWidth,u.effectiveFilterDepth,u.effectiveFilterHeight,u.effectiveFilterWidth,u.padInfo.front,u.padInfo.top,u.padInfo.left),d}var ade={kernelName:Iu,backendName:"wasm",setupFunc:rde,kernelFunc:nde},qE;function sde(e){qE=e.wasm.cwrap("MaxPool3DGrad",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 ide(e){let{inputs:t,backend:r,attrs:n}=e,{dy:a,input:s}=t,{filterSize:i,strides:o,pad:l,dimRoundingMode:p}=n,u=_.computePool3DInfo(s.shape,i,o,1,l,p),d=r.makeOutput(s.shape,s.dtype);return qE(r.dataIdMap.get(s.dataId).id,r.dataIdMap.get(a.dataId).id,r.dataIdMap.get(d.dataId).id,u.batchSize,u.inChannels,u.inDepth,u.inHeight,u.inWidth,u.outDepth,u.outHeight,u.outWidth,u.strideDepth,u.strideHeight,u.strideWidth,u.dilationDepth,u.dilationHeight,u.dilationWidth,u.effectiveFilterDepth,u.effectiveFilterHeight,u.effectiveFilterWidth,u.padInfo.front,u.padInfo.top,u.padInfo.left),d}var ode={kernelName:vd,backendName:"wasm",setupFunc:sde,kernelFunc:ide},KE;function lde(e){KE=e.wasm.cwrap("MaxPoolGrad",null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function ude(e){let{inputs:t,backend:r,attrs:n}=e,{dy:a,input:s}=t,{filterSize:i,strides:o,pad:l,dimRoundingMode:p}=n,u=_.computePool2DInfo(s.shape,i,o,1,l,p),d=r.makeOutput(s.shape,s.dtype);return KE(r.dataIdMap.get(s.dataId).id,r.dataIdMap.get(a.dataId).id,r.dataIdMap.get(d.dataId).id,u.batchSize,u.inChannels,u.inHeight,u.inWidth,u.outHeight,u.outWidth,u.strideHeight,u.strideWidth,u.dilationHeight,u.dilationWidth,u.effectiveFilterHeight,u.effectiveFilterWidth,u.padInfo.top,u.padInfo.left),d}var pde={kernelName:xd,backendName:"wasm",setupFunc:lde,kernelFunc:ude},XE;function dde(e){XE=e.wasm.cwrap("MaxPoolWithArgmax",null,["number","number","number","number","boolean","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function hde(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{filterSize:s,strides:i,pad:o,includeBatchInIndex:l}=n;k.assert(a.shape.length===4,()=>`Error in maxPool: input must be rank 4 but got rank ${a.shape.length}.`);let p=[1,1];k.assert(_.eitherStridesOrDilationsAreOne(i,p),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${i} and dilations '${p}'`);let u=_.computePool2DInfo(a.shape,s,i,[1,1],o),d=r.makeOutput(u.outShape,a.dtype),h=r.makeOutput(u.outShape,"int32");return XE(r.dataIdMap.get(a.dataId).id,r.dataIdMap.get(d.dataId).id,r.dataIdMap.get(h.dataId).id,Ze[a.dtype],l,u.batchSize,u.inChannels,u.inHeight,u.inWidth,u.outHeight,u.outWidth,u.strideHeight,u.strideWidth,u.dilationHeight,u.dilationWidth,u.effectiveFilterHeight,u.effectiveFilterWidth,u.padInfo.top,u.padInfo.left),[d,h]}var cde={kernelName:wd,backendName:"wasm",setupFunc:dde,kernelFunc:hde},ZE;function fde(e){ZE=e.wasm.cwrap(yo,null,["number, number, number"])}function mde(e){let{backend:t,inputs:r,attrs:n}=e,{axis:a,keepDims:s}=n,{x:i}=r,o=t.dataIdMap.get(i.dataId).id,l=o,p=i,{transposed:u,axes:d,originalAxes:h,inputWasTransposed:c}=zs(i,a,t),f=d;if(c){let v=t.dataIdMap.get(u.dataId).id;v!==o&&(p=u,l=v,f=_.getInnerMostAxes(f.length,p.shape.length))}_.assertAxesAreInnerMostDims("mean",f,p.shape.length);let[m,g]=_.computeOutAndReduceShapes(p.shape,f),y=k.sizeFromShape(g),b=p;p.dtype!=="float32"&&(b=Ps({backend:t,inputs:{x:p},attrs:{dtype:"float32"}}),l=t.dataIdMap.get(b.dataId).id);let x=t.makeOutput(m,"float32");if(k.sizeFromShape(p.shape)!==0){let v=t.dataIdMap.get(x.dataId).id;ZE(l,y,v)}if(c&&t.disposeData(u.dataId),s){let v=_.expandShapeToKeepDim(x.shape,h);x.shape=v}return p.dtype!=="float32"&&t.disposeData(b.dataId),x}var gde={kernelName:yo,backendName:"wasm",setupFunc:fde,kernelFunc:mde},JE;function yde(e){JE=e.wasm.cwrap(bo,null,["number","number","number","number"])}function bde(e){let{backend:t,inputs:r,attrs:n}=e,{axis:a,keepDims:s}=n,{x:i}=r,o=t.dataIdMap.get(i.dataId).id,l=o,p=i,{transposed:u,axes:d,originalAxes:h,inputWasTransposed:c}=zs(i,a,t);if(c){let x=t.dataIdMap.get(u.dataId).id;x!==o&&(p=u,l=x)}let f=p.shape.length;_.assertAxesAreInnerMostDims("min",d,f);let[m,g]=_.computeOutAndReduceShapes(p.shape,d),y=k.sizeFromShape(g),b=t.makeOutput(m,p.dtype);if(k.sizeFromShape(p.shape)!==0){let x=t.dataIdMap.get(b.dataId).id;JE(l,Ze[i.dtype],y,x)}if(c&&t.disposeData(u.dataId),s){let x=_.expandShapeToKeepDim(b.shape,h);b.shape=x}return b}var xde={kernelName:bo,backendName:"wasm",setupFunc:yde,kernelFunc:bde},vde=zt(xo),ry;(function(e){e[e.reflect=0]="reflect",e[e.symmetric=1]="symmetric"})(ry||(ry={}));var YE;function wde(e){YE=e.wasm.cwrap(vo,null,["number","array","number","number","array","array","number","number"])}function kde(e){let{inputs:{x:t},backend:r,attrs:{paddings:n,mode:a}}=e,s=n.map((f,m)=>f[0]+t.shape[m]+f[1]),i=r.dataIdMap.get(t.dataId).id,o=r.makeOutput(s,t.dtype),l=r.dataIdMap.get(o.dataId).id,p=new Uint8Array(new Int32Array(t.shape).buffer),u=n.map(f=>f[0]),d=n.map(f=>f[1]),h=new Uint8Array(new Int32Array(u).buffer),c=new Uint8Array(new Int32Array(d).buffer);return YE(i,p,t.shape.length,Ze[t.dtype],h,c,ry[a],l),o}var Ide={kernelName:vo,backendName:"wasm",kernelFunc:kde,setupFunc:wde},QE;function Sde(e){QE=e.wasm.cwrap(Go,null,["number","number","number","number"])}function e$(e){let{backend:t,inputs:{logits:r},attrs:{dim:n}}=e,a=t.dataIdMap.get(r.dataId).id,s=t.makeOutput(r.shape,r.dtype),i=t.dataIdMap.get(s.dataId).id,o=r.shape[n],l=k.sizeFromShape(r.shape)/o;return k.sizeFromShape(s.shape)===0||QE(a,i,o,l),s}var Nde={kernelName:Go,backendName:"wasm",setupFunc:Sde,kernelFunc:e$},t$;function _de(e){t$=e.wasm.cwrap(Su,null,["number","number","number","number","number","number"])}function Tde(e){let{inputs:t,backend:r,attrs:n}=e,{logits:a}=t,{numSamples:s,seed:i,normalized:o}=n;if(a.dtype!=="float32")throw new Error(`Tensor logits must have dtype float32, got ${a.dtype}`);let l=o?a:e$({inputs:{logits:a},backend:r,attrs:{dim:a.shape.length-1}}),[p,u]=l.shape,d=r.makeOutput([p,s],"int32");return t$(r.dataIdMap.get(l.dataId).id,p,u,s,i,r.dataIdMap.get(d.dataId).id),o||r.disposeData(l.dataId),d}var Cde={kernelName:Su,backendName:"wasm",setupFunc:_de,kernelFunc:Tde},Ede=zt(wo),$de=zt(ko),Ade=je(Nu);function fw(e,t){let r=new Int32Array(e.wasm.HEAPU8.buffer,t,4),n=r[0],a=r[1],s=r[2],i=r[3];return e.wasm._free(t),{pSelectedIndices:n,selectedSize:a,pSelectedScores:s,pValidOutputs:i}}var r$;function Fde(e){r$=e.wasm.cwrap(Tu,"number",["number","number","number","number","number"])}function Rde(e){let{backend:t,inputs:r,attrs:n}=e,{iouThreshold:a,maxOutputSize:s,scoreThreshold:i}=n,{boxes:o,scores:l}=r,p=t.dataIdMap.get(o.dataId).id,u=t.dataIdMap.get(l.dataId).id,d=r$(p,u,s,a,i),{pSelectedIndices:h,selectedSize:c,pSelectedScores:f,pValidOutputs:m}=fw(t,d);return t.wasm._free(f),t.wasm._free(m),t.makeOutput([c],"int32",h)}var Dde={kernelName:Tu,backendName:"wasm",setupFunc:Fde,kernelFunc:Rde},n$;function Mde(e){n$=e.wasm.cwrap(Cu,"number",["number","number","number","number","number","bool"])}function Ode(e){let{backend:t,inputs:r,attrs:n}=e,{iouThreshold:a,maxOutputSize:s,scoreThreshold:i,padToMaxOutputSize:o}=n,{boxes:l,scores:p}=r,u=t.dataIdMap.get(l.dataId).id,d=t.dataIdMap.get(p.dataId).id,h=n$(u,d,s,a,i,o),{pSelectedIndices:c,selectedSize:f,pSelectedScores:m,pValidOutputs:g}=fw(t,h);t.wasm._free(m);let y=t.makeOutput([f],"int32",c),b=t.makeOutput([],"int32",g);return[y,b]}var Lde={kernelName:Cu,backendName:"wasm",setupFunc:Mde,kernelFunc:Ode},a$;function zde(e){a$=e.wasm.cwrap(Eu,"number",["number","number","number","number","number","number"])}function Pde(e){let{backend:t,inputs:r,attrs:n}=e,{iouThreshold:a,maxOutputSize:s,scoreThreshold:i,softNmsSigma:o}=n,{boxes:l,scores:p}=r,u=t.dataIdMap.get(l.dataId).id,d=t.dataIdMap.get(p.dataId).id,h=a$(u,d,s,a,i,o),{pSelectedIndices:c,selectedSize:f,pSelectedScores:m,pValidOutputs:g}=fw(t,h);t.wasm._free(g);let y=t.makeOutput([f],"int32",c),b=t.makeOutput([f],"float32",m);return[y,b]}var Bde={kernelName:Eu,backendName:"wasm",setupFunc:zde,kernelFunc:Pde},Wde=!1,Ude=zt(_u,Wde,"bool"),s$;function Vde(e){s$=e.wasm.cwrap(Io,null,["number","number","number","number","number"])}function Gde(e){let{inputs:t,backend:r,attrs:n}=e,{indices:a}=t,{dtype:s,depth:i,onValue:o,offValue:l}=n,p=r.makeOutput([...a.shape,i],s),u=r.dataIdMap.get(p.dataId).id,d=r.dataIdMap.get(a.dataId).id;return s$(d,i,o,l,u),p}var Hde={kernelName:Io,backendName:"wasm",setupFunc:Vde,kernelFunc:Gde};function jde(e){let{inputs:{x:t},backend:r}=e,n=r.makeOutput(t.shape,t.dtype);return r.typedArrayFromHeap(n).fill(1),n}var qde={kernelName:$u,backendName:"wasm",kernelFunc:jde};function Kde(e){let{inputs:t,backend:r,attrs:n}=e,{axis:a}=n;if(t.length===1)return ty({inputs:{input:t[0]},backend:r,attrs:{dim:a}});let s=t[0].shape,i=t[0].dtype;t.forEach(u=>{k.assertShapesMatch(s,u.shape,"All tensors passed to stack must have matching shapes"),k.assert(i===u.dtype,()=>"All tensors passed to stack must have matching dtypes")});let o=[],l=t.map(u=>{let d=ty({inputs:{input:u},backend:r,attrs:{dim:a}});return o.push(d),d}),p=gE({inputs:l,backend:r,attrs:{axis:a}});return o.forEach(u=>r.disposeData(u.dataId)),p}var Xde={kernelName:Au,backendName:"wasm",kernelFunc:Kde},i$;function Zde(e){i$=e.wasm.cwrap(So,null,["number","array","number","number","array","array","number","number"])}function Jde(e){let{inputs:{x:t},backend:r,attrs:{paddings:n,constantValue:a}}=e,s=n.map((f,m)=>f[0]+t.shape[m]+f[1]);if(k.sizeFromShape(t.shape)===0)return RE({backend:r,attrs:{shape:s,value:a,dtype:t.dtype}});let i=r.dataIdMap.get(t.dataId).id,o=r.makeOutput(s,t.dtype),l=r.dataIdMap.get(o.dataId).id,p=new Uint8Array(new Int32Array(t.shape).buffer),u=n.map(f=>f[0]),d=n.map(f=>f[1]),h=new Uint8Array(new Int32Array(u).buffer),c=new Uint8Array(new Int32Array(d).buffer);return i$(i,p,t.shape.length,Ze[t.dtype],h,c,a,l),o}var o$={kernelName:So,backendName:"wasm",kernelFunc:Jde,setupFunc:Zde},Yde=zt(No),l$;function Qde(e){l$=e.wasm.cwrap(_o,null,["number","number","number"])}function ehe(e){let{inputs:t,backend:r}=e,{x:n,alpha:a}=t,s=r.dataIdMap.get(n.dataId).id,i=r.dataIdMap.get(a.dataId).id,o=s,l=n,p=l;l.dtype!=="float32"&&(p=Ps({backend:r,inputs:{x:n},attrs:{dtype:"float32"}}),o=r.dataIdMap.get(p.dataId).id);let u=r.makeOutput(n.shape,"float32"),d=r.dataIdMap.get(u.dataId).id;return l$(o,i,d),l.dtype!=="float32"&&r.disposeData(p.dataId),u}var the={kernelName:_o,backendName:"wasm",setupFunc:Qde,kernelFunc:ehe},u$;function rhe(e){u$=e.wasm.cwrap(To,null,["number","number","number","number"])}function nhe(e){let{backend:t,inputs:r,attrs:n}=e,{axis:a,keepDims:s}=n,{x:i}=r,o=t.dataIdMap.get(i.dataId).id,l=o,p=i,{transposed:u,axes:d,originalAxes:h,inputWasTransposed:c}=zs(i,a,t),f=d;if(c){let x=t.dataIdMap.get(u.dataId).id;x!==o&&(p=u,l=x,f=_.getInnerMostAxes(f.length,p.shape.length))}_.assertAxesAreInnerMostDims("prod",f,p.shape.length);let[m,g]=_.computeOutAndReduceShapes(p.shape,f),y=k.sizeFromShape(g),b=t.makeOutput(m,p.dtype);if(k.sizeFromShape(p.shape)!==0){let x=t.dataIdMap.get(b.dataId).id;u$(l,y,Ze[b.dtype],x)}if(c&&t.disposeData(u.dataId),s){let x=_.expandShapeToKeepDim(b.shape,h);b.shape=x}return b}var ahe={kernelName:To,backendName:"wasm",setupFunc:rhe,kernelFunc:nhe},she=e=>{let{backend:t,attrs:r}=e,{start:n,stop:a,step:s,dtype:i}=r,o=Uv(n,a,s,i),l=t.makeOutput([o.length],i);return t.typedArrayFromHeap(l).set(o),l},ihe={kernelName:kd,backendName:"wasm",kernelFunc:she},ohe=zt(Zi),lhe=je(Co),uhe=je(Eo),phe=je(Fo),p$;function dhe(e){p$=e.wasm.cwrap(Ao,null,["number","number","number","number","number","number","number","number","number","number"])}function hhe(e){let{backend:t,inputs:r,attrs:n}=e,{images:a}=r,{alignCorners:s,halfPixelCenters:i,size:o}=n,[l,p]=o,[u,d,h,c]=a.shape,f=[u,l,p,c],m=t.dataIdMap.get(a.dataId),g;m.dtype!=="float32"&&(g=Ps({backend:t,inputs:{x:a},attrs:{dtype:"float32"}}),m=t.dataIdMap.get(g.dataId));let y=m.id,b=t.makeOutput(f,"float32");if(k.sizeFromShape(a.shape)===0)return b;let x=t.dataIdMap.get(b.dataId).id;return p$(y,u,d,h,c,l,p,s?1:0,i?1:0,x),g!=null&&t.disposeData(g.dataId),b}var che={kernelName:Ao,backendName:"wasm",setupFunc:dhe,kernelFunc:hhe},d$;function fhe(e){d$=e.wasm.cwrap(Du,null,["number","number","number","array","array","boolean"])}function mhe(e){let{inputs:t,backend:r,attrs:n}=e,{images:a,dy:s}=t,{alignCorners:i}=n,o=r.makeOutput(a.shape,"float32"),l=r.dataIdMap.get(a.dataId),p;return l.dtype!=="float32"&&(p=Ps({backend:r,inputs:{x:a},attrs:{dtype:"float32"}}),l=r.dataIdMap.get(p.dataId)),d$(r.dataIdMap.get(a.dataId).id,r.dataIdMap.get(s.dataId).id,r.dataIdMap.get(o.dataId).id,new Uint8Array(new Int32Array(a.shape).buffer),new Uint8Array(new Int32Array(s.shape).buffer),i),p!=null&&r.disposeData(p.dataId),o}var ghe={kernelName:Du,backendName:"wasm",setupFunc:fhe,kernelFunc:mhe},h$;function yhe(e){h$=e.wasm.cwrap($o,null,["number","number","number","number","number","number","number","number","number","number"])}function bhe(e){let{backend:t,inputs:r,attrs:n}=e,{images:a}=r,{alignCorners:s,halfPixelCenters:i,size:o}=n,[l,p]=o,[u,d,h,c]=a.shape,f=[u,l,p,c],m=t.makeOutput(f,"float32");if(k.sizeFromShape(a.shape)===0)return m;let g=t.dataIdMap.get(a.dataId),y;g.dtype!=="float32"&&(y=Ps({backend:t,inputs:{x:a},attrs:{dtype:"float32"}}),g=t.dataIdMap.get(y.dataId));let b=g.id,x=t.dataIdMap.get(m.dataId).id;return h$(b,u,d,h,c,l,p,s?1:0,i?1:0,x),y!=null&&t.disposeData(y.dataId),m}var xhe={kernelName:$o,backendName:"wasm",setupFunc:yhe,kernelFunc:bhe},c$;function vhe(e){c$=e.wasm.cwrap(Ru,null,["number","number","number","array","array","boolean"])}function whe(e){let{inputs:t,backend:r,attrs:n}=e,{images:a,dy:s}=t,{alignCorners:i}=n,o=r.makeOutput(a.shape,"float32"),l=r.dataIdMap.get(a.dataId),p;return l.dtype!=="float32"&&(p=Ps({backend:r,inputs:{x:a},attrs:{dtype:"float32"}}),l=r.dataIdMap.get(p.dataId)),c$(r.dataIdMap.get(a.dataId).id,r.dataIdMap.get(s.dataId).id,r.dataIdMap.get(o.dataId).id,new Uint8Array(new Int32Array(a.shape).buffer),new Uint8Array(new Int32Array(s.shape).buffer),i),p!=null&&r.disposeData(p.dataId),o}var khe={kernelName:Ru,backendName:"wasm",setupFunc:vhe,kernelFunc:whe},f$;function Ihe(e){f$=e.wasm.cwrap(Ro,null,["number","array","number","array","number","number"])}function She(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{dims:s}=n,i=k.parseAxisParam(s,a.shape);if(a.shape.length===0)return km({inputs:{x:a},backend:r});let o=r.makeOutput(a.shape,a.dtype),l=r.dataIdMap.get(a.dataId).id,p=r.dataIdMap.get(o.dataId).id,u=new Uint8Array(new Int32Array(i).buffer),d=new Uint8Array(new Int32Array(a.shape).buffer);f$(l,u,i.length,d,a.shape.length,p);let h=Fr({inputs:{x:o},attrs:{shape:a.shape},backend:r});return r.disposeData(o.dataId),h}var Nhe={kernelName:Ro,backendName:"wasm",kernelFunc:She,setupFunc:Ihe},m$;function _he(e){m$=e.wasm.cwrap(Xu,null,["number","number","number","number","number","number","number","number","array","number","number"])}function The(e){let{inputs:t,backend:r,attrs:n}=e,{image:a}=t,{radians:s,fillValue:i,center:o}=n,l=r.makeOutput(a.shape,a.dtype),p=r.dataIdMap.get(a.dataId).id,u=r.dataIdMap.get(l.dataId).id,[d,h,c,f]=a.shape,[m,g]=_.getImageCenter(o,h,c),y=i===0,b=255,x=typeof i=="number"?[i,i,i,y?0:b]:[...i,b],v=new Uint8Array(new Int32Array(x).buffer);return m$(p,d,h,c,f,s,m,g,v,x.length,u),l}var Che={kernelName:Xu,backendName:"wasm",kernelFunc:The,setupFunc:_he},Ehe=je(Do),$he=je(Mo),g$;function Ahe(e){g$=e.wasm.cwrap(Mu,null,["number","number","number","number","number","number","array","number","number"])}function Fhe(e){let{backend:t,inputs:r,attrs:n}=e,{indices:a,updates:s}=r,{shape:i}=n,o=t.makeOutput(i,s.dtype);if(k.sizeFromShape(i)===0)return o;let{sliceRank:l,numUpdates:p,sliceSize:u,strides:d,outputSize:h}=zf.calculateShapes(s,a,i),c=t.dataIdMap.get(a.dataId).id,f=t.dataIdMap.get(s.dataId).id,m=new Uint8Array(new Int32Array(d).buffer),g=t.dataIdMap.get(o.dataId).id;return g$(c,f,Ze[s.dtype],l,p,u,m,h,g),o}var Rhe={kernelName:Mu,backendName:"wasm",setupFunc:Ahe,kernelFunc:Fhe},y$;function Dhe(e){y$=e.wasm.cwrap(Lu,null,["number","number","number","number","number","number","bool","number"])}function Mhe(e){let{inputs:t,backend:r,attrs:n}=e,{sortedSequence:a,values:s}=t,{side:i}=n;if(a.dtype!==s.dtype)throw new Error(`SearchSorted error: sorted_sequence must have the same dtype as values. Got ${a.dtype} and ${s.dtype}`);let o=r.makeOutput(s.shape,"int32");function l(p){return r.dataIdMap.get(p.dataId).id}return y$(l(a),l(s),a.shape[0],a.shape[1],s.shape[1],Ze[a.dtype],i==="left",l(o)),o}var Ohe={kernelName:Lu,backendName:"wasm",setupFunc:Dhe,kernelFunc:Mhe},b$;function Lhe(e){b$=e.wasm.cwrap("SelectV2",null,["number","number","number","number","number"])}function zhe(e){let{inputs:t,backend:r}=e,{condition:n,t:a,e:s}=t,i=r.dataIdMap.get(n.dataId).id,o=r.dataIdMap.get(a.dataId).id,l=r.dataIdMap.get(s.dataId).id,p=r.makeOutput(a.shape,a.dtype),u=r.dataIdMap.get(p.dataId).id,d=n.shape.length,h=a.shape.length,c=d===0||d>1||h===1?1:k.sizeFromShape(a.shape.slice(1));return b$(i,o,l,c,u),p}var Phe={kernelName:zu,backendName:"wasm",kernelFunc:zhe,setupFunc:Lhe},Bhe=je(Oo),x$;function Whe(e){x$=e.wasm.cwrap(Bo,null,["number","number"])}function Uhe(e){let{backend:t,inputs:{x:r}}=e,n=t.dataIdMap.get(r.dataId).id,a=t.makeOutput(r.shape,r.dtype),s=t.dataIdMap.get(a.dataId).id;return k.sizeFromShape(a.shape)===0||x$(n,s),a}var Vhe={kernelName:"Sigmoid",backendName:"wasm",setupFunc:Whe,kernelFunc:Uhe},Ghe=je(Po),Hhe=je(Lo),jhe=je(zo),qhe=je(Wo);function Khe(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{blockShape:s,paddings:i}=n,o=k.sizeFromShape(s),l=[[0,0]];l.push(...i);for(let g=1+s.length;g<a.shape.length;++g)l.push([0,0]);let p=o$.kernelFunc({inputs:{x:a},backend:r,attrs:{paddings:l,constantValue:0}}),u=_.getReshaped(p.shape,s,o,!1),d=_.getPermuted(u.length,s.length,!1),h=_.getReshapedPermuted(p.shape,s,o,!1),c=Fr({inputs:{x:p},backend:r,attrs:{shape:u}}),f=Ss({inputs:{x:c},backend:r,attrs:{perm:d}}),m=Fr({inputs:{x:f},backend:r,attrs:{shape:h}});return r.disposeData(p.dataId),r.disposeData(c.dataId),r.disposeData(f.dataId),m}var Xhe={kernelName:Bu,backendName:"wasm",kernelFunc:Khe},v$;function Zhe(e){v$=e.wasm.cwrap("SparseFillEmptyRows","number",["number","number","number","number","number","number","number","number","number","number","number","number"])}function Jhe(e){let{backend:t,inputs:r}=e,{indices:n,values:a,denseShape:s,defaultValue:i}=r,o=n.shape[0],l=n.shape[1],p=t.readSync(s.dataId)[0],u=[o+p,l],d=t.dataIdMap.get(n.dataId).id,h=t.dataIdMap.get(a.dataId).id,c=t.dataIdMap.get(i.dataId).id,f=t.makeOutput(u,n.dtype),m=t.dataIdMap.get(f.dataId).id,g=t.makeOutput(u.slice(0,1),a.dtype),y=t.dataIdMap.get(g.dataId).id,b=t.makeOutput([p],"bool"),x=t.dataIdMap.get(b.dataId).id,v=t.makeOutput([o],n.dtype),w=t.dataIdMap.get(v.dataId).id,N=t.makeOutput([4],"int32"),T=t.dataIdMap.get(N.dataId).id,E=v$(d,h,Ze[a.dtype],o,p,l,c,m,y,x,w,T),$=t.readSync(N.dataId),R;switch($[0]){case 1:{R=_.getSparseFillEmptyRowsIndicesDenseShapeMismatch($[1]);break}case 2:{R=_.getSparseFillEmptyRowsNegativeIndexErrorMessage($[1],$[2]);break}case 3:R=_.getSparseFillEmptyRowsOutOfRangeIndexErrorMessage($[1],$[2],$[3]);break;default:R=""}if(t.disposeData(N.dataId),R)throw t.disposeData(f.dataId),t.disposeData(g.dataId),t.disposeData(b.dataId),t.disposeData(v.dataId),new Error(R);let F=f,S=g;return E!==u[0]&&(F=_i({inputs:{x:f},attrs:{begin:0,size:[E,l]},backend:t}),S=_i({inputs:{x:g},attrs:{begin:0,size:E},backend:t}),t.disposeData(f.dataId),t.disposeData(g.dataId)),[F,S,b,v]}var Yhe={kernelName:Id,backendName:"wasm",setupFunc:Zhe,kernelFunc:Jhe},w$;function Qhe(e){w$=e.wasm.cwrap(Uu,null,["number","number","number","number","number","number","number"])}function ece(e){let{backend:t,inputs:r}=e,{inputIndices:n,inputShape:a,newShape:s}=r;if(n.shape.length!==2)throw new Error(`Input indices should be a matrix but received shape
${n.shape}`);if(a.shape.length!==1)throw new Error(`Input shape should be a vector but received shape
${a.shape}`);if(s.shape.length!==1)throw new Error(`Target shape should be a vector but received shape ${s.shape}`);let i=t.dataIdMap.get(n.dataId).id,o=t.dataIdMap.get(a.dataId).id,l=t.dataIdMap.get(s.dataId).id,p=n.shape[0],u=k.sizeFromShape(s.shape),d=t.makeOutput([p,u],n.dtype),h=t.dataIdMap.get(d.dataId).id,c=t.makeOutput([u],s.dtype),f=t.dataIdMap.get(c.dataId).id,m=t.makeOutput([3],"int32"),g=t.dataIdMap.get(m.dataId).id;w$(i,o,l,p,h,f,g);let y=t.readSync(m.dataId),b;switch(y[0]){case 0:{b=_.getSparseReshapeMultipleNegativeOneOutputDimErrorMessage(y[1],y[2]);break}case 1:{b=_.getSparseReshapeNegativeOutputDimErrorMessage(y[1],y[2]);break}case 2:b=_.getSparseReshapeEmptyTensorZeroOutputDimErrorMessage();break;case 3:{let x=Array.from(t.readSync(a.dataId)),v=Array.from(t.readSync(c.dataId));b=_.getSparseReshapeInputOutputMultipleErrorMessage(x,v);break}case 4:{let x=Array.from(t.readSync(a.dataId)),v=Array.from(t.readSync(c.dataId));b=_.getSparseReshapeInputOutputMismatchErrorMessage(x,v);break}default:b=""}if(t.disposeData(m.dataId),b)throw t.disposeData(d.dataId),t.disposeData(c.dataId),new Error(b);return[d,c]}var tce={kernelName:Uu,backendName:"wasm",setupFunc:Qhe,kernelFunc:ece},k$;function I$(e){k$=e.wasm.cwrap("SparseSegmentReduction",null,["number","number","number","number","number","number","number","number","number"])}function S$(e,t){let{backend:r,inputs:n}=e,{data:a,indices:s,segmentIds:i}=n,o=s.shape[0],l=r.readSync(i.dataId,o-1,o)[0],p=o>0?l+1:0;if(p<0)throw new Error(_.getSparseSegmentReductionNegativeSegmentIdsErrorMessage());let u=a.shape.slice();u[0]=p;let d=r.dataIdMap.get(a.dataId).id,h=r.dataIdMap.get(s.dataId).id,c=r.dataIdMap.get(i.dataId).id,f=r.makeOutput(u,a.dtype),m=r.dataIdMap.get(f.dataId).id,g=r.makeOutput([4],"int32"),y=r.dataIdMap.get(g.dataId).id;k$(d,Ze[a.dtype],a.shape[0],h,c,m,y,t,0);let b=r.readSync(g.dataId),x;switch(b[0]){case 0:{x=_.getSparseSegmentReductionNegativeSegmentIdsErrorMessage();break}case 1:{x=_.getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage();break}case 2:x=_.getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage(b[1],b[2]);break;case 3:x=_.getSparseSegmentReductionIndicesOutOfRangeErrorMessage(b[1],b[2],b[3]);break;default:x=""}if(r.disposeData(g.dataId),x)throw r.disposeData(f.dataId),new Error(x);return f}function rce(e){return S$(e,!0)}var nce={kernelName:Sd,backendName:"wasm",setupFunc:I$,kernelFunc:rce};function ace(e){return S$(e,!1)}var sce={kernelName:Nd,backendName:"wasm",setupFunc:I$,kernelFunc:ace},N$;function ice(e){N$=e.wasm.cwrap(Vu,null,["number","number","number","number","number","number","number","number","array","number","number"])}function oce(e){let{backend:t,inputs:r,attrs:n}=e,{sparseIndices:a,sparseValues:s,defaultValue:i}=r,{outputShape:o}=n,l=t.makeOutput(o,i.dtype);if(k.sizeFromShape(o)===0)return l;let{sliceRank:p,numUpdates:u,sliceSize:d,strides:h,outputSize:c}=_.calculateShapes(s,a,o),f=t.dataIdMap.get(a.dataId).id,m=t.dataIdMap.get(s.dataId).id,g=t.dataIdMap.get(i.dataId).id,y=new Uint8Array(new Int32Array(h).buffer),b=t.dataIdMap.get(l.dataId).id;return N$(f,m,s.shape.length,g,Ze[i.dtype],p,u,d,y,c,b),l}var lce={kernelName:Vu,backendName:"wasm",setupFunc:ice,kernelFunc:oce};function uce(e){let{inputs:t,attrs:r,backend:n}=e,{x:a}=t,{numOrSizeSplits:s,axis:i}=r,o=k.parseAxisParam(i,a.shape)[0],l=_.prepareSplitSize(a,s,o),p=new Array(a.shape.length).fill(0),u=a.shape.slice();return l.map(d=>{let h=[...u];h[o]=d;let c=_i({inputs:{x:a},attrs:{begin:p,size:h},backend:n});return p[o]+=d,c})}var pce={kernelName:Wu,backendName:"wasm",kernelFunc:uce},dce=je(Uo),hce=je(_d),cce=zt(Ho),_$;function fce(e){_$=e.wasm.cwrap($s,null,["number","number","number","number"])}function mce(e){let{backend:t,inputs:r,attrs:n}=e,{alpha:a}=n,{x:s}=r,i=t.dataIdMap.get(s.dataId).id,o=t.makeOutput(s.shape,s.dtype),l=t.dataIdMap.get(o.dataId).id;return _$(i,a,Ze[s.dtype],l),o}var gce={kernelName:$s,backendName:"wasm",setupFunc:fce,kernelFunc:mce},T$;function yce(e){T$=e.wasm.cwrap(Gu,null,["number","array","number","array","array","array","array","array","number","number"])}function bce(e){let{backend:t,inputs:r,attrs:n}=e,{x:a}=r,{begin:s,end:i,strides:o,beginMask:l,endMask:p,ellipsisMask:u,newAxisMask:d,shrinkAxisMask:h}=n,{finalShapeSparse:c,finalShape:f,isIdentity:m,sliceDim0:g,isSimpleSlice:y,begin:b,end:x,strides:v}=Wt.sliceInfo(a.shape,s,i,o,l,p,u,d,h),w;if(m)w=Fr({inputs:{x:a},backend:t,attrs:{shape:f}});else if(g||y){k.assert(a.shape.length>=1,()=>`Input must have rank at least 1, got: ${a.shape.length}`);let N=Wt.computeOutShape(b,x,v),T=_i({inputs:{x:a},backend:t,attrs:{begin:b,size:N}});w=Fr({inputs:{x:T},backend:t,attrs:{shape:f}}),t.disposeData(T.dataId)}else{let N=t.makeOutput(c,"float32"),T=t.dataIdMap.get(a.dataId).id,E=new Uint8Array(new Int32Array(k.computeStrides(a.shape)).buffer),$=new Uint8Array(new Int32Array(b).buffer),R=new Uint8Array(new Int32Array(x).buffer),F=new Uint8Array(new Int32Array(v).buffer),S=new Uint8Array(new Int32Array(c).buffer),D=new Uint8Array(new Int32Array(k.computeStrides(c)).buffer),P=t.dataIdMap.get(N.dataId).id;T$(T,E,a.shape.length,$,R,F,S,D,c.length,P),w=Fr({inputs:{x:N},backend:t,attrs:{shape:f}}),t.disposeData(N.dataId)}return w}var xce={kernelName:Gu,backendName:"wasm",setupFunc:yce,kernelFunc:bce};function vce(e){let{backend:t,inputs:r,attrs:n}=e,{data:a,dataSplits:s}=r,{separator:i,nGramWidths:o,leftPad:l,rightPad:p,padWidth:u,preserveShortSequences:d}=n,h=t.readSync(a.dataId),c=t.readSync(s.dataId),[f,m]=Gv(h,c,i,o,l,p,u,d),g=t.makeOutput([f.length],"string"),y=t.dataIdMap.get(g.dataId);y.stringBytes=f;let b=t.makeOutput(s.shape,"int32");return t.typedArrayFromHeap(b).set(m),[g,b]}var wce={kernelName:Cd,backendName:"wasm",kernelFunc:vce};function kce(e){let{backend:t,inputs:r,attrs:n}=e,{input:a,delimiter:s}=r,{skipEmpty:i}=n,o=t.readSync(a.dataId),l=t.readSync(s.dataId),[p,u,d]=Hv(o,l[0],i),h=u.length,c=t.makeOutput([h,2],"int32");t.typedArrayFromHeap(c).set(p);let f=t.makeOutput([h],"string"),m=t.dataIdMap.get(f.dataId);m.stringBytes=u;let g=t.makeOutput([2],"int32");return t.typedArrayFromHeap(g).set(d),[c,f,g]}var Ice={kernelName:Ed,backendName:"wasm",kernelFunc:kce};function Sce(e){let{backend:t,inputs:r,attrs:n}=e,{input:a}=r,{numBuckets:s}=n,i=t.readSync(a.dataId),o=jv(i,s),l=t.makeOutput(a.shape,"int32");return t.typedArrayFromHeap(l).set(o),l}var Nce={kernelName:$d,backendName:"wasm",kernelFunc:Sce},_ce=zt(jo),C$;function Tce(e){C$=e.wasm.cwrap(Vo,null,["number","number","number","number"])}function Cce(e){let{backend:t,inputs:r,attrs:n}=e,{axis:a,keepDims:s}=n,{x:i}=r,o=t.dataIdMap.get(i.dataId).id,l=o,p=i,{transposed:u,axes:d,originalAxes:h,inputWasTransposed:c}=zs(i,a,t),f=d;if(c){let x=t.dataIdMap.get(u.dataId).id;x!==o&&(p=u,l=x,f=_.getInnerMostAxes(f.length,p.shape.length))}_.assertAxesAreInnerMostDims("sum",f,p.shape.length);let[m,g]=_.computeOutAndReduceShapes(p.shape,f),y=k.sizeFromShape(g),b=t.makeOutput(m,p.dtype);if(k.sizeFromShape(p.shape)!==0){let x=t.dataIdMap.get(b.dataId).id;C$(l,y,Ze[b.dtype],x)}if(c&&t.disposeData(u.dataId),s){let x=_.expandShapeToKeepDim(b.shape,h);b.shape=x}return b}var Ece={kernelName:Vo,backendName:"wasm",setupFunc:Tce,kernelFunc:Cce},$ce=je(qo),Ace=je(Ko),E$;function Fce(e){E$=e.wasm.cwrap(Ou,null,["number","number","number","number","number","number","array","number","number","number"])}function Rce(e){let{backend:t,inputs:r,attrs:n}=e,{tensor:a,indices:s,updates:i}=r,o=t.makeOutput(a.shape,a.dtype);if(k.sizeFromShape(a.shape)===0)return o;let{sliceRank:l,numUpdates:p,sliceSize:u,strides:d,outputSize:h}=zf.calculateShapes(i,s,a.shape),c=t.dataIdMap.get(s.dataId).id,f=t.dataIdMap.get(i.dataId).id,m=t.dataIdMap.get(a.dataId).id,g=new Uint8Array(new Int32Array(d).buffer),y=t.dataIdMap.get(o.dataId).id;return E$(c,f,Ze[i.dtype],l,p,u,g,h,y,m),o}var Dce={kernelName:Ou,backendName:"wasm",setupFunc:Fce,kernelFunc:Rce},$$;function Mce(e){$$=e.wasm.cwrap(Es,null,["number","array","number","array","number","number"])}function Oce(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,s=r.dataIdMap.get(a.dataId).id,{reps:i}=n,o=new Array(a.shape.length);for(let h=0;h<o.length;h++)o[h]=a.shape[h]*i[h];let l=new Uint8Array(new Int32Array(a.shape).buffer),p=new Uint8Array(new Int32Array(o).buffer),u=r.makeOutput(o,a.dtype),d=r.dataIdMap.get(u.dataId).id;return $$(s,l,a.shape.length,p,o.length,Ze[u.dtype],d),u}var Lce={kernelName:Es,backendName:"wasm",setupFunc:Mce,kernelFunc:Oce},A$;function zce(e){A$=e.wasm.cwrap(Hu,null,["number","array","number","number","number","bool","number","number"])}var Pce=({inputs:e,backend:t,attrs:r})=>{let{x:n}=e,{k:a,sorted:s}=r,i=t.dataIdMap.get(n.dataId).id,o=new Uint8Array(new Int32Array(n.shape).buffer),l=n.shape.slice();l[l.length-1]=a;let p=t.makeOutput(l,n.dtype),u=t.dataIdMap.get(p.dataId).id,d=t.makeOutput(l,"int32"),h=t.dataIdMap.get(d.dataId).id;return A$(i,o,n.shape.length,Ze[n.dtype],a,s,u,h),[p,d]},Bce={kernelName:Hu,backendName:"wasm",setupFunc:zce,kernelFunc:Pce},F$;function Wce(e){F$=e.wasm.cwrap(ju,null,["number","number","bool","number","number","number","number","number","number","array","number","array","number","number","number","number","number"])}function Uce(e){let{backend:t,inputs:r,attrs:n}=e,{image:a,transforms:s}=r,{interpolation:i,fillMode:o,fillValue:l,outputShape:p}=n,[u,d,h,c]=a.shape,[f,m]=p??[d,h],g=[u,f,m,c],y=new Uint8Array(new Int32Array(k.computeStrides(a.shape)).buffer),b=new Uint8Array(new Int32Array(k.computeStrides(g)).buffer),x=t.makeOutput(g,a.dtype),v=t.dataIdMap.get(x.dataId).id,w=t.dataIdMap.get(a.dataId).id,N=t.dataIdMap.get(s.dataId).id,T=i==="nearest"?1:2,E;switch(o){case"constant":E=1;break;case"reflect":E=2;break;case"wrap":E=3;break;case"nearest":E=4;break;default:E=1;break}return F$(w,N,s.shape[0]>1,u,f,m,c,h,d,y,a.shape.length-1,b,g.length-1,T,E,l,v),x}var Vce={kernelName:ju,backendName:"wasm",setupFunc:Wce,kernelFunc:Uce};function Gce(e){let{inputs:t,attrs:r,backend:n}=e,{axis:a}=r,{x:s}=t,{outputValues:i,outputShape:o,indices:l}=Kv(n.readSync(s.dataId),a,s.shape,s.dtype);return[n.makeOutput(o,s.dtype,void 0,i),n.makeOutput([l.length],"int32",void 0,l)]}var Hce={kernelName:Ad,backendName:"wasm",kernelFunc:Gce};function jce(e){let{inputs:t,backend:r,attrs:n}=e,{value:a}=t,{axis:s}=n;s<0&&(s+=a.shape.length);let i=a.shape[s],o=a.shape.length,l=new Array(o-1),p=0;for(let c=0;c<o;c++)c!==s&&(l[p++]=a.shape[c]);let u=new Array(i),d=new Array(o).fill(0),h=a.shape.slice();h[s]=1;for(let c=0;c<u.length;c++)d[s]=c,u[c]=_i({inputs:{x:a},attrs:{begin:d,size:h},backend:r});return u.map(({dataId:c,dtype:f})=>({dataId:c,dtype:f,shape:l}))}var qce={kernelName:qu,backendName:"wasm",kernelFunc:jce};function Kce(e){let{inputs:{x:t},backend:r}=e,n=r.makeOutput(t.shape,t.dtype);return r.typedArrayFromHeap(n).fill(0),n}var Xce={kernelName:Ku,backendName:"wasm",kernelFunc:Kce},Zce=[Woe,Uoe,Voe,Goe,Hoe,Koe,rle,sle,ile,ole,lle,ule,ple,dle,hle,mle,Sle,ble,wle,Cle,Dle,Lle,zle,Ble,Wle,Ule,Hle,jle,Xle,Yle,tue,aue,oue,lue,uue,hue,mue,bue,wue,Sue,Tue,$ue,Rue,Oue,Pue,Bue,Vue,Hue,jue,que,Kue,Xue,Zue,Que,epe,tpe,ape,ope,ppe,cpe,gpe,bpe,vpe,Xoe,wpe,kpe,Ipe,_pe,Cpe,$pe,Rpe,Mpe,Dpe,Lpe,zpe,Bpe,Upe,Hpe,Kpe,Jpe,Ype,tde,ade,ode,pde,cde,gde,xde,vde,Ide,Cde,Ede,$de,Ade,Dde,Lde,Bde,Ude,Hde,qde,Xde,o$,Yde,the,ahe,ihe,ohe,lhe,uhe,phe,Nle,che,ghe,xhe,khe,Nhe,Che,Ehe,$he,Rhe,Ohe,Phe,Bhe,Vhe,Ghe,Hhe,jhe,Fle,Nde,qhe,Xhe,Yhe,tce,nce,sce,lce,pce,dce,hce,cce,gce,xce,wce,Ice,Nce,_ce,Ece,$ce,Ace,Dce,Lce,Bce,Vce,Qoe,Hce,qce,Xce];for(let e of Zce)Rd(e);var ny=j();ny.registerFlag("WASM_HAS_SIMD_SUPPORT",async()=>{try{return 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]))}catch{return!1}});ny.registerFlag("WASM_HAS_MULTITHREAD_SUPPORT",async()=>{if(ny.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{return!1}});var B1=_s(AR()),Jce=_s(FR()),W1=_s(RR()),U1=B1.default||B1,Yce=W1.default||W1,R$=class extends pd{constructor(e){super(),this.wasm=e,this.dataIdNextNumber=1,this.wasm.tfjs.initWithThreadsCount(D$),ay=this.wasm.tfjs.getThreadsCount(),this.dataIdMap=new Xc(this,wn())}write(e,t,r){let n={id:this.dataIdNextNumber++};return this.move(n,e,t,r,1),n}numDataIds(){return this.dataIdMap.numDataIds()}async time(e){let t=k.now();return e(),{kernelMs:k.now()-t}}move(e,t,r,n,a){let s=this.dataIdNextNumber++;if(n==="string"){let p=t;this.dataIdMap.set(e,{id:s,stringBytes:p,shape:r,dtype:n,memoryOffset:null,refCount:a});return}let i=k.sizeFromShape(r),o=i*k.bytesPerElement(n),l=this.wasm._malloc(o)>>>0;this.dataIdMap.set(e,{id:s,memoryOffset:l,shape:r,dtype:n,refCount:a}),this.wasm.tfjs.registerTensor(s,i,l),t!=null&&this.wasm.HEAPU8.set(new Uint8Array(t.buffer,t.byteOffset,o),l)}async read(e){return this.readSync(e)}readSync(e,t,r){let{memoryOffset:n,dtype:a,shape:s,stringBytes:i}=this.dataIdMap.get(e);if(a==="string")return(t==null||t===0)&&(r==null||r>=i.length)?i:i.slice(t,r);t=t||0,r=r||k.sizeFromShape(s);let o=k.bytesPerElement(a),l=this.wasm.HEAPU8.slice(n+t*o,n+r*o);return tfe(l.buffer,a)}disposeData(e,t=!1){if(this.dataIdMap.has(e)){let r=this.dataIdMap.get(e);if(r.refCount--,!t&&r.refCount>0)return!1;this.wasm._free(r.memoryOffset),this.wasm.tfjs.disposeData(r.id),this.dataIdMap.delete(e)}return!0}refCount(e){return this.dataIdMap.has(e)?this.dataIdMap.get(e).refCount:0}incRef(e){let t=this.dataIdMap.get(e);t!=null&&t.refCount++}floatPrecision(){return 32}getMemoryOffset(e){return this.dataIdMap.get(e).memoryOffset}dispose(){this.wasm.tfjs.dispose(),"PThread"in this.wasm&&this.wasm.PThread.terminateAllThreads(),this.wasm=null}memory(){return{unreliable:!1}}makeOutput(e,t,r,n){let a;if(r==null)a=this.write(n??null,e,t);else{let s=this.dataIdNextNumber++;a={id:s},this.dataIdMap.set(a,{id:s,memoryOffset:r,shape:e,dtype:t,refCount:1});let i=k.sizeFromShape(e);this.wasm.tfjs.registerTensor(s,i,r)}return{dataId:a,shape:e,dtype:t}}typedArrayFromHeap({shape:e,dtype:t,dataId:r}){let n=this.wasm.HEAPU8.buffer,{memoryOffset:a}=this.dataIdMap.get(r),s=k.sizeFromShape(e);switch(t){case"float32":return new Float32Array(n,a,s);case"int32":return new Int32Array(n,a,s);case"bool":return new Uint8Array(n,a,s);default:throw new Error(`Unknown dtype ${t}`)}}};function Qce(e){return(t,r)=>(k.fetch(e,{credentials:"same-origin"}).then(n=>{n.ok||t.env.a(`failed to load wasm binary file at '${e}'`),n.arrayBuffer().then(a=>{WebAssembly.instantiate(a,t).then(s=>{r(s.instance,s.module)})})}),{})}function V1(e,t,r){if(Bc!=null)return Bc;let n="tfjs-backend-wasm.wasm";return e&&t?n="tfjs-backend-wasm-threaded-simd.wasm":e&&(n="tfjs-backend-wasm-simd.wasm"),Wp!=null&&Wp[n]!=null?Wp[n]:r+n}async function efe(){let[e,t]=await Promise.all([j().getAsync("WASM_HAS_SIMD_SUPPORT"),j().getAsync("WASM_HAS_MULTITHREAD_SUPPORT")]);return new Promise((r,n)=>{let a={};a.locateFile=(o,l)=>{if(o.endsWith(".worker.js")){let p=Jce.wasmWorkerContents.replace(/\n/g,"\\n"),u=new Blob([p],{type:"application/javascript"});return URL.createObjectURL(u)}return o.endsWith(".wasm")?V1(e,t,Lp??l):l+o},mw&&(a.instantiateWasm=Qce(V1(e,t,Lp??"")));let s=!1;a.onAbort=()=>{s||Up||(Up=!0,n({message:"Make sure the server can serve the `.wasm` file relative to the bundled js file. For more details see https://github.com/tensorflow/tfjs/blob/master/tfjs-backend-wasm/README.md#using-bundlers"}))};let i;t&&e&&Bc==null?(a.mainScriptUrlOrBlob=new Blob(["var WasmBackendModuleThreadedSimd = "+U1.toString()],{type:"text/javascript"}),i=U1(a)):i=Yce(a),i.then(o=>{s=!0,Up=!1;let l=null;o.tfjs={init:o.cwrap("init",null,[]),initWithThreadsCount:o.cwrap("init_with_threads_count",null,["number"]),getThreadsCount:o.cwrap("get_threads_count","number",[]),registerTensor:o.cwrap("register_tensor",null,["number","number","number"]),disposeData:o.cwrap("dispose_data",l,["number"]),dispose:o.cwrap("dispose",l,[])},r({wasm:o})}).catch(n)})}function tfe(e,t){switch(t){case"float32":return new Float32Array(e);case"int32":return new Int32Array(e);case"bool":return new Uint8Array(e);default:throw new Error(`Unknown dtype ${t}`)}}var rfe=["tfjs-backend-wasm.wasm","tfjs-backend-wasm-simd.wasm","tfjs-backend-wasm-threaded-simd.wasm"],Bc=null,Lp=null,Wp={},Up=!1,mw=!1;function nfe(e,t=!1){if(tI("setWasmPath has been deprecated in favor of setWasmPaths and will be removed in a future release."),Up)throw new Error("The WASM backend was already initialized. Make sure you call `setWasmPath()` before you call `tf.setBackend()` or `tf.ready()`");Bc=e,mw=t}function afe(e,t=!1){if(Up)throw new Error("The WASM backend was already initialized. Make sure you call `setWasmPaths()` before you call `tf.setBackend()` or `tf.ready()`");if(typeof e=="string")Lp=e;else{Wp=e;let r=rfe.filter(n=>Wp[n]==null);if(r.length>0)throw new Error(`There were no entries found for the following binaries: ${r.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.`)}mw=t}var D$=-1,ay=-1;function sfe(e){D$=e}function ife(){if(ay===-1)throw new Error("WASM backend not initialized.");return ay}var ofe="4.22.0",lfe=2;ff("wasm",async()=>{let{wasm:e}=await efe();return new R$(e)},lfe);var G1="4.22.0",ufe="4.22.0",pfe="4.22.0",dfe="4.22.0",hfe="4.22.0",cfe={tfjs:G1,"tfjs-core":G1,"tfjs-converter":ufe,"tfjs-backend-cpu":pfe,"tfjs-backend-webgl":dfe,"tfjs-backend-wasm":hfe},ffe={};Iy(ffe,{AnchorPosition:()=>X$,DrawBox:()=>Y$,DrawBoxOptions:()=>J$,DrawFaceLandmarks:()=>mA,DrawFaceLandmarksOptions:()=>fA,DrawTextField:()=>kw,DrawTextFieldOptions:()=>ww,drawContour:()=>Xa,drawDetections:()=>Cfe,drawFaceExpressions:()=>Ufe,drawFaceLandmarks:()=>Hfe});function Xa(e,t,r=!1){if(e.beginPath(),t.slice(1).forEach(({x:n,y:a},s)=>{let i=t[s];e.moveTo(i.x,i.y),e.lineTo(n,a)}),r){let n=t[t.length-1],a=t[0];if(!n||!a)return;e.moveTo(n.x,n.y),e.lineTo(a.x,a.y)}e.stroke()}var mfe={};Iy(mfe,{computeReshapedDimensions:()=>z$,getCenterPoint:()=>yw,isDimensions:()=>iy,isEven:()=>sy,isFloat:()=>L$,isTensor:()=>gp,isTensor1D:()=>gfe,isTensor2D:()=>O$,isTensor3D:()=>hh,isTensor4D:()=>Ea,isValidNumber:()=>oi,isValidProbablitiy:()=>yfe,range:()=>Vl,round:()=>gw});var Nl=class M${constructor(t,r){if(!oi(t)||!oi(r))throw new Error(`Dimensions.constructor - expected width and height to be valid numbers, instead have ${JSON.stringify({width:t,height:r})}`);this._width=t,this._height=r}get width(){return this._width}get height(){return this._height}reverse(){return new M$(1/this.width,1/this.height)}};function gp(e,t){return e instanceof ze&&e.shape.length===t}function gfe(e){return gp(e,1)}function O$(e){return gp(e,2)}function hh(e){return gp(e,3)}function Ea(e){return gp(e,4)}function L$(e){return e%1!==0}function sy(e){return e%2===0}function gw(e,t=2){let r=10**t;return Math.floor(e*r)/r}function iy(e){return e&&e.width&&e.height}function z$({width:e,height:t},r){let n=r/Math.max(t,e);return new Nl(Math.round(e*n),Math.round(t*n))}function yw(e){return e.reduce((t,r)=>t.add(r),new it(0,0)).div(new it(e.length,e.length))}function Vl(e,t,r){return Array(e).fill(0).map((n,a)=>t+a*r)}function oi(e){return!!e&&e!==1/0&&e!==-1/0&&!Number.isNaN(e)||e===0}function yfe(e){return oi(e)&&e>=0&&e<=1}var it=class Xs{constructor(t,r){this._x=t,this._y=r}get x(){return this._x}get y(){return this._y}add(t){return new Xs(this.x+t.x,this.y+t.y)}sub(t){return new Xs(this.x-t.x,this.y-t.y)}mul(t){return new Xs(this.x*t.x,this.y*t.y)}div(t){return new Xs(this.x/t.x,this.y/t.y)}abs(){return new Xs(Math.abs(this.x),Math.abs(this.y))}magnitude(){return Math.sqrt(this.x**2+this.y**2)}floor(){return new Xs(Math.floor(this.x),Math.floor(this.y))}},Ti=class An{static isRect(t){return!!t&&[t.x,t.y,t.width,t.height].every(oi)}static assertIsValidBox(t,r,n=!1){if(!An.isRect(t))throw new Error(`${r} - invalid box: ${JSON.stringify(t)}, expected object with properties x, y, width, height`);if(!n&&(t.width<0||t.height<0))throw new Error(`${r} - width (${t.width}) and height (${t.height}) must be positive numbers`)}constructor(t,r=!0){let n=t||{},a=[n.left,n.top,n.right,n.bottom].every(oi),s=[n.x,n.y,n.width,n.height].every(oi);if(!s&&!a)throw new Error(`Box.constructor - expected box to be IBoundingBox | IRect, instead have ${JSON.stringify(n)}`);let[i,o,l,p]=s?[n.x,n.y,n.width,n.height]:[n.left,n.top,n.right-n.left,n.bottom-n.top];An.assertIsValidBox({x:i,y:o,width:l,height:p},"Box.constructor",r),this._x=i,this._y=o,this._width=l,this._height=p}get x(){return this._x}get y(){return this._y}get width(){return this._width}get height(){return this._height}get left(){return this.x}get top(){return this.y}get right(){return this.x+this.width}get bottom(){return this.y+this.height}get area(){return this.width*this.height}get topLeft(){return new it(this.left,this.top)}get topRight(){return new it(this.right,this.top)}get bottomLeft(){return new it(this.left,this.bottom)}get bottomRight(){return new it(this.right,this.bottom)}round(){let[t,r,n,a]=[this.x,this.y,this.width,this.height].map(s=>Math.round(s));return new An({x:t,y:r,width:n,height:a})}floor(){let[t,r,n,a]=[this.x,this.y,this.width,this.height].map(s=>Math.floor(s));return new An({x:t,y:r,width:n,height:a})}toSquare(){let{x:t,y:r,width:n,height:a}=this,s=Math.abs(n-a);return n<a&&(t-=s/2,n+=s),a<n&&(r-=s/2,a+=s),new An({x:t,y:r,width:n,height:a})}rescale(t){let r=iy(t)?t.width:t,n=iy(t)?t.height:t;return new An({x:this.x*r,y:this.y*n,width:this.width*r,height:this.height*n})}pad(t,r){let[n,a,s,i]=[this.x-t/2,this.y-r/2,this.width+t,this.height+r];return new An({x:n,y:a,width:s,height:i})}clipAtImageBorders(t,r){let{x:n,y:a,right:s,bottom:i}=this,o=Math.max(n,0),l=Math.max(a,0),p=s-o,u=i-l,d=Math.min(p,t-o),h=Math.min(u,r-l);return new An({x:o,y:l,width:d,height:h}).floor()}shift(t,r){let{width:n,height:a}=this,s=this.x+t,i=this.y+r;return new An({x:s,y:i,width:n,height:a})}padAtBorders(t,r){let n=this.width+1,a=this.height+1,s=1,i=1,o=n,l=a,p=this.left,u=this.top,d=this.right,h=this.bottom;return d>r&&(o=-d+r+n,d=r),h>t&&(l=-h+t+a,h=t),p<1&&(l=2-p,p=1),u<1&&(l=2-u,u=1),{dy:i,edy:l,dx:s,edx:o,y:u,ey:h,x:p,ex:d,w:n,h:a}}calibrate(t){return new An({left:this.left+t.left*this.width,top:this.top+t.top*this.height,right:this.right+t.right*this.width,bottom:this.bottom+t.bottom*this.height}).toSquare().round()}},P$=class extends Ti{constructor(e,t,r,n,a=!1){super({left:e,top:t,right:r,bottom:n},a)}},B$=class W${constructor(t,r,n,a,s){this._imageDims=new Nl(s.width,s.height),this._score=t,this._classScore=r,this._className=n,this._box=new Ti(a).rescale(this._imageDims)}get score(){return this._score}get classScore(){return this._classScore}get className(){return this._className}get box(){return this._box}get imageDims(){return this._imageDims}get imageWidth(){return this.imageDims.width}get imageHeight(){return this.imageDims.height}get relativeBox(){return new Ti(this._box).rescale(this.imageDims.reverse())}forSize(t,r){return new W$(this.score,this.classScore,this.className,this.relativeBox,{width:t,height:r})}},Gn=class U$ extends B${constructor(t,r,n){super(t,t,"",r,n)}forSize(t,r){let{score:n,relativeBox:a,imageDims:s}=super.forSize(t,r);return new U$(n,a,s)}};function bfe(e,t,r=!0){let n=Math.max(0,Math.min(e.right,t.right)-Math.max(e.left,t.left)),a=Math.max(0,Math.min(e.bottom,t.bottom)-Math.max(e.top,t.top)),s=n*a;return r?s/(e.area+t.area-s):s/Math.min(e.area,t.area)}function xfe(e){let t=e.map(o=>o.x),r=e.map(o=>o.y),n=t.reduce((o,l)=>l<o?l:o,1/0),a=r.reduce((o,l)=>l<o?l:o,1/0),s=t.reduce((o,l)=>o<l?l:o,0),i=r.reduce((o,l)=>o<l?l:o,0);return new P$(n,a,s,i)}function vfe(e,t,r,n=!0){let a=t.map((i,o)=>({score:i,boxIndex:o})).sort((i,o)=>i.score-o.score).map(i=>i.boxIndex),s=[];for(;a.length>0;){let i=a.pop();s.push(i);let o=a,l=[];for(let p=0;p<o.length;p++){let u=o[p],d=e[i],h=e[u];l.push(bfe(d,h,n))}a=a.filter((p,u)=>l[u]<=r)}return s}function ch(e,t){return W(()=>{let[r,n,a]=t,s=qr([...e.shape.slice(0,3),1],r,"float32"),i=qr([...e.shape.slice(0,3),1],n,"float32"),o=qr([...e.shape.slice(0,3),1],a,"float32"),l=lt([s,i,o],3);return de(e,l)})}function wfe(e,t=!1){return W(()=>{let[r,n]=e.shape.slice(1);if(r===n)return e;let a=Math.abs(r-n),s=Math.round(a*(t?.5:1)),i=r>n?2:1,o=d=>{let h=e.shape.slice();return h[i]=d,qr(h,0,"float32")},l=o(s),p=a-l.shape[i],u=[t&&p?o(p):null,e,l].filter(d=>!!d).map(d=>se(d,"float32"));return lt(u,i)})}function Km(e){return 1/(1+Math.exp(-e))}var V$=class extends Ti{constructor(e,t,r,n,a=!1){super({x:e,y:t,width:r,height:n},a)}},kfe=.5,Ife=.43,Sfe=.45,Wc=class{constructor(e,t,r=new it(0,0)){let{width:n,height:a}=t;this._imgDims=new Nl(n,a),this._shift=r,this._positions=e.map(s=>s.mul(new it(n,a)).add(r))}get shift(){return new it(this._shift.x,this._shift.y)}get imageWidth(){return this._imgDims.width}get imageHeight(){return this._imgDims.height}get positions(){return this._positions}get relativePositions(){return this._positions.map(e=>e.sub(this._shift).div(new it(this.imageWidth,this.imageHeight)))}forSize(e,t){return new this.constructor(this.relativePositions,{width:e,height:t})}shiftBy(e,t){return new this.constructor(this.relativePositions,this._imgDims,new it(e,t))}shiftByPoint(e){return this.shiftBy(e.x,e.y)}align(e,t={}){if(e){let a=e instanceof Gn?e.box.floor():new Ti(e);return this.shiftBy(a.x,a.y).align(null,t)}let{useDlibAlignment:r,minBoxPadding:n}={useDlibAlignment:!1,minBoxPadding:.2,...t};return r?this.alignDlib():this.alignMinBbox(n)}alignDlib(){let e=this.getRefPointsForAlignment(),[t,r,n]=e,a=u=>n.sub(u).magnitude(),s=(a(t)+a(r))/2,i=Math.floor(s/Sfe),o=yw(e),l=Math.floor(Math.max(0,o.x-kfe*i)),p=Math.floor(Math.max(0,o.y-Ife*i));return new V$(l,p,Math.min(i,this.imageWidth+l),Math.min(i,this.imageHeight+p))}alignMinBbox(e){let t=xfe(this.positions);return t.pad(t.width*e,t.height*e)}getRefPointsForAlignment(){throw new Error("getRefPointsForAlignment not implemented by base class")}},G$=class extends Wc{getJawOutline(){return this.positions.slice(0,17)}getLeftEyeBrow(){return this.positions.slice(17,22)}getRightEyeBrow(){return this.positions.slice(22,27)}getNose(){return this.positions.slice(27,36)}getLeftEye(){return this.positions.slice(36,42)}getRightEye(){return this.positions.slice(42,48)}getMouth(){return this.positions.slice(48,68)}getRefPointsForAlignment(){return[this.getLeftEye(),this.getRightEye(),this.getMouth()].map(yw)}};function Uc(e){return e.detection instanceof Gn}function Nfe(e,t){return{...e,detection:t}}function H$(){let e=window.fetch;if(!e)throw new Error("fetch - missing fetch implementation for browser environment");return{Canvas:HTMLCanvasElement,CanvasRenderingContext2D,Image:HTMLImageElement,ImageData,Video:HTMLVideoElement,createCanvasElement:()=>document.createElement("canvas"),createImageElement:()=>document.createElement("img"),createVideoElement:()=>document.createElement("video"),fetch:e,readFile:()=>{throw new Error("readFile - filesystem not available for browser environment")}}}function bw(){return typeof global=="object"&&typeof process<"u"&&process.versions!=null&&process.versions.node!=null}function j$(e){let t="";if(!e&&bw())try{e=uR("fs")}catch(r){t=r.toString()}return{readFile:e?r=>new Promise((n,a)=>{e.readFile(r,(s,i)=>s?a(s):n(i))}):()=>{throw new Error(`readFile - failed to require fs in nodejs environment with error: ${t}`)}}}function q$(){let e=global.Canvas||global.HTMLCanvasElement,t=global.Image||global.HTMLImageElement,r=global.Video||global.HTMLVideoElement,n=()=>{if(e)return new e;throw new Error("createCanvasElement - missing Canvas implementation for nodejs environment")},a=()=>{if(t)return new t;throw new Error("createImageElement - missing Image implementation for nodejs environment")},s=()=>{if(r)return new r;throw new Error("createVideoElement - missing Video implementation for nodejs environment")},i=global.fetch,o=j$();return{Canvas:e||class{},CanvasRenderingContext2D:global.CanvasRenderingContext2D||class{},Image:t||class{},ImageData:global.ImageData||class{},Video:global.HTMLVideoElement||class{},createCanvasElement:n,createImageElement:a,createVideoElement:s,fetch:i,...o}}function K$(){return typeof window=="object"&&typeof document<"u"&&typeof HTMLImageElement<"u"&&typeof HTMLCanvasElement<"u"&&typeof HTMLVideoElement<"u"&&typeof ImageData<"u"&&typeof CanvasRenderingContext2D<"u"}var Ht;function _fe(){if(!Ht)throw new Error("getEnv - environment is not defined, check isNodejs() and isBrowser()");return Ht}function oy(e){Ht=e}function xw(){return K$()?oy(H$()):bw()?oy(q$()):null}function Tfe(e){if(Ht||xw(),!Ht)throw new Error("monkeyPatch - environment is not defined, check isNodejs() and isBrowser()");let{Canvas:t=Ht.Canvas,Image:r=Ht.Image}=e;Ht.Canvas=t,Ht.Image=r,Ht.createCanvasElement=e.createCanvasElement||(()=>new t),Ht.createImageElement=e.createImageElement||(()=>new r),Ht.ImageData=e.ImageData||Ht.ImageData,Ht.Video=e.Video||Ht.Video,Ht.fetch=e.fetch||Ht.fetch,Ht.readFile=e.readFile||Ht.readFile}var Or={getEnv:_fe,setEnv:oy,initialize:xw,createBrowserEnv:H$,createFileSystem:j$,createNodejsEnv:q$,monkeyPatch:Tfe,isBrowser:K$,isNodejs:bw};xw();function vw(e){return!Or.isNodejs()&&typeof e=="string"?document.getElementById(e):e}function Ns(e){let{Canvas:t,CanvasRenderingContext2D:r}=Or.getEnv();if(e instanceof r)return e;let n=vw(e);if(!(n instanceof t))throw new Error("resolveContext2d - expected canvas to be of instance of Canvas");let a=n.getContext("2d",{willReadFrequently:!0});if(!a)throw new Error("resolveContext2d - canvas 2d context is null");return a}var X$=(e=>(e.TOP_LEFT="TOP_LEFT",e.TOP_RIGHT="TOP_RIGHT",e.BOTTOM_LEFT="BOTTOM_LEFT",e.BOTTOM_RIGHT="BOTTOM_RIGHT",e))(X$||{}),ww=class{constructor(e={}){let{anchorPosition:t,backgroundColor:r,fontColor:n,fontSize:a,fontStyle:s,padding:i}=e;this.anchorPosition=t||"TOP_LEFT",this.backgroundColor=r||"rgba(0, 0, 0, 0.5)",this.fontColor=n||"rgba(255, 255, 255, 1)",this.fontSize=a||14,this.fontStyle=s||"Georgia",this.padding=i||4}},kw=class Z${constructor(t,r,n={}){this.text=typeof t=="string"?[t]:t instanceof Z$?t.text:t,this.anchor=r,this.options=new ww(n)}measureWidth(t){let{padding:r}=this.options;return this.text.map(n=>t.measureText(n).width).reduce((n,a)=>n<a?a:n,0)+2*r}measureHeight(){let{fontSize:t,padding:r}=this.options;return this.text.length*t+2*r}getUpperLeft(t,r){let{anchorPosition:n}=this.options,a=n==="BOTTOM_RIGHT"||n==="TOP_RIGHT",s=n==="BOTTOM_LEFT"||n==="BOTTOM_RIGHT",i=this.measureWidth(t),o=this.measureHeight(),l=a?this.anchor.x-i:this.anchor.x,p=s?this.anchor.y-o:this.anchor.y;if(r){let{width:u,height:d}=r,h=Math.max(Math.min(l,u-i),0),c=Math.max(Math.min(p,d-o),0);return{x:h,y:c}}return{x:l,y:p}}draw(t){let r=vw(t),n=Ns(r),{backgroundColor:a,fontColor:s,fontSize:i,fontStyle:o,padding:l}=this.options;n.font=`${i}px ${o}`;let p=this.measureWidth(n),u=this.measureHeight();n.fillStyle=a;let d=this.getUpperLeft(n,r);n.fillRect(d.x,d.y,p,u),n.fillStyle=s,this.text.forEach((h,c)=>{let f=l+d.x,m=l+d.y+(c+1)*i;n.fillText(h,f,m)})}},J$=class{constructor(e={}){let{boxColor:t,lineWidth:r,label:n,drawLabelOptions:a}=e;this.boxColor=t||"rgba(0, 0, 255, 1)",this.lineWidth=r||2,this.label=n;let s={anchorPosition:"BOTTOM_LEFT",backgroundColor:this.boxColor};this.drawLabelOptions=new ww({...s,...a})}},Y$=class{constructor(e,t={}){this.box=new Ti(e),this.options=new J$(t)}draw(e){let t=Ns(e),{boxColor:r,lineWidth:n}=this.options,{x:a,y:s,width:i,height:o}=this.box;t.strokeStyle=r,t.lineWidth=n,t.strokeRect(a,s,i,o);let{label:l}=this.options;l&&new kw([l],{x:a-n/2,y:s},this.options.drawLabelOptions).draw(e)}};function Cfe(e,t){(Array.isArray(t)?t:[t]).forEach(r=>{let n=r instanceof Gn?r.score:Uc(r)?r.detection.score:void 0,a=r instanceof Gn?r.box:Uc(r)?r.detection.box:new Ti(r),s=n?`${gw(n)}`:void 0;new Y$(a,{label:s}).draw(e)})}function Q$(e){let{Image:t,Video:r}=Or.getEnv();return e instanceof t&&e.complete||e instanceof r&&e.readyState>=3}function Efe(e){return new Promise((t,r)=>{if(e instanceof Or.getEnv().Canvas||Q$(e)){t(null);return}function n(s){s.currentTarget&&(s.currentTarget.removeEventListener("load",a),s.currentTarget.removeEventListener("error",n),r(s))}function a(s){s.currentTarget&&(s.currentTarget.removeEventListener("load",a),s.currentTarget.removeEventListener("error",n),t(s))}e.addEventListener("load",a),e.addEventListener("error",n)})}function eA(e){let{Image:t,Video:r}=Or.getEnv();return e instanceof t?new Nl(e.naturalWidth,e.naturalHeight):e instanceof r?new Nl(e.videoWidth,e.videoHeight):new Nl(e.width,e.height)}function Vc({width:e,height:t}){let{createCanvasElement:r}=Or.getEnv(),n=r();return n.width=e,n.height=t,n}function tA(e,t){let{ImageData:r}=Or.getEnv();if(!(e instanceof r)&&!Q$(e))throw new Error("createCanvasFromMedia - media has not finished loading yet");let{width:n,height:a}=eA(e),s=Vc({width:n,height:a});return e instanceof r?Ns(s).putImageData(e,0,0):Ns(s).drawImage(e,0,0,n,a),s}async function $fe(e,t){let r=t||Or.getEnv().createCanvasElement(),[n,a,s]=e.shape.slice(Ea(e)?1:0),i=W(()=>e.as3D(n,a,s).toInt());return await Yd.toPixels(i,r),i.dispose(),r}function H1(e){let{Image:t,Canvas:r,Video:n}=Or.getEnv();return e instanceof t||e instanceof r||e instanceof n}function Afe(e,t,r=!1){let{Image:n,Canvas:a}=Or.getEnv();if(!(e instanceof n||e instanceof a))throw new Error("imageToSquare - expected arg0 to be HTMLImageElement | HTMLCanvasElement");if(t<=0)return Vc({width:1,height:1});let s=eA(e),i=t/Math.max(s.height,s.width),o=i*s.width,l=i*s.height,p=Vc({width:t,height:t}),u=e instanceof a?e:tA(e),d=Math.abs(o-l)/2,h=r&&o<l?d:0,c=r&&l<o?d:0;return u.width>0&&u.height>0&&Ns(p).drawImage(u,h,c,o,l),p}var Gc=class{constructor(e,t=!1){if(this._imageTensors=[],this._canvases=[],this._treatAsBatchInput=!1,this._inputDimensions=[],this._inputSize=0,!Array.isArray(e))throw new Error(`NetInput.constructor - expected inputs to be an Array of TResolvedNetInput or to be instanceof tf.Tensor4D, instead have ${e}`);this._treatAsBatchInput=t,this._batchSize=e.length,e.forEach((r,n)=>{if(hh(r)){this._imageTensors[n]=r,this._inputDimensions[n]=r.shape;return}if(Ea(r)){let s=r.shape[0];if(s!==1)throw new Error(`NetInput - tf.Tensor4D with batchSize ${s} passed, but not supported in input array`);this._imageTensors[n]=r,this._inputDimensions[n]=r.shape.slice(1);return}let a=r instanceof Or.getEnv().Canvas?r:tA(r);this._canvases[n]=a,this._inputDimensions[n]=[a.height,a.width,3]})}get imageTensors(){return this._imageTensors}get canvases(){return this._canvases}get isBatchInput(){return this.batchSize>1||this._treatAsBatchInput}get batchSize(){return this._batchSize}get inputDimensions(){return this._inputDimensions}get inputSize(){return this._inputSize}get reshapedInputDimensions(){return Vl(this.batchSize,0,1).map((e,t)=>this.getReshapedInputDimensions(t))}getInput(e){return this.canvases[e]||this.imageTensors[e]}getInputDimensions(e){return this._inputDimensions[e]}getInputHeight(e){return this._inputDimensions[e][0]}getInputWidth(e){return this._inputDimensions[e][1]}getReshapedInputDimensions(e){if(typeof this.inputSize!="number")throw new Error("getReshapedInputDimensions - inputSize not set, toBatchTensor has not been called yet");let t=this.getInputWidth(e),r=this.getInputHeight(e);return z$({width:t,height:r},this.inputSize)}toBatchTensor(e,t=!0){return this._inputSize=e,W(()=>{let r=Vl(this.batchSize,0,1).map(n=>{let a=this.getInput(n);if(a instanceof ze){let s=Ea(a)?a:Xt(a);return s=wfe(s,t),(s.shape[1]!==e||s.shape[2]!==e)&&(s=sn.resizeBilinear(s,[e,e],!1,!1)),s.as3D(e,e,3)}if(a instanceof Or.getEnv().Canvas)return Yd.fromPixels(Afe(a,e,t));throw new Error(`toBatchTensor - at batchIdx ${n}, expected input to be instanceof tf.Tensor or instanceof HTMLCanvasElement, instead have ${a}`)});return Mt(r.map(n=>se(n,"float32"))).as4D(this.batchSize,e,e,3)})}};async function vr(e){if(e instanceof Gc)return e;let t=Array.isArray(e)?e:[e];if(!t.length)throw new Error("toNetInput - empty array passed as input");let r=a=>Array.isArray(e)?` at input index ${a}:`:"",n=t.map(vw);return n.forEach((a,s)=>{if(!H1(a)&&!hh(a)&&!Ea(a))throw typeof t[s]=="string"?new Error(`toNetInput -${r(s)} string passed, but could not resolve HTMLElement for element id ${t[s]}`):new Error(`toNetInput -${r(s)} expected media to be of type HTMLImageElement | HTMLVideoElement | HTMLCanvasElement | tf.Tensor3D, or to be an element id`);if(Ea(a)){let i=a.shape[0];if(i!==1)throw new Error(`toNetInput -${r(s)} tf.Tensor4D with batchSize ${i} passed, but not supported in input array`)}}),await Promise.all(n.map(a=>H1(a)&&Efe(a))),new Gc(n,Array.isArray(e))}async function rA(e,t){let{Canvas:r}=Or.getEnv(),n=e;if(!(e instanceof r)){let s=await vr(e);if(s.batchSize>1)throw new Error("extractFaces - batchSize > 1 not supported");let i=s.getInput(0);n=i instanceof r?i:await $fe(i)}let a=Ns(n);return t.map(s=>s instanceof Gn?s.forSize(n.width,n.height).box.floor():s).map(s=>s.clipAtImageBorders(n.width,n.height)).map(({x:s,y:i,width:o,height:l})=>{let p=Vc({width:o,height:l});return o>0&&l>0&&Ns(p).putImageData(a.getImageData(s,i,o,l),0,0),p})}async function nA(e,t){if(!hh(e)&&!Ea(e))throw new Error("extractFaceTensors - expected image tensor to be 3D or 4D");if(Ea(e)&&e.shape[0]>1)throw new Error("extractFaceTensors - batchSize > 1 not supported");return W(()=>{let[r,n,a]=e.shape.slice(Ea(e)?1:0);return t.map(s=>s instanceof Gn?s.forSize(n,r).box:s).map(s=>s.clipAtImageBorders(n,r)).filter(s=>s.width>0&&s.height>0).map(({x:s,y:i,width:o,height:l})=>rp(e.as3D(r,n,a),[i,s,0],[l,o,a]))})}async function Ffe(e,t){let{fetch:r}=Or.getEnv(),n=await r(e,t);if(!(n.status<400))throw new Error(`failed to fetch: (${n.status}) ${n.statusText}, from url: ${n.url}`);return n}async function Rfe(e){return(await Ffe(e)).json()}function aA(e,t){let r=`${t}-weights_manifest.json`;if(!e)return{modelBaseUri:"",manifestUri:r};if(e==="/")return{modelBaseUri:"/",manifestUri:`/${r}`};let n=e.startsWith("http://")?"http://":e.startsWith("https://")?"https://":"";e=e.replace(n,"");let a=e.split("/").filter(o=>o),s=e.endsWith(".json")?a[a.length-1]:r,i=n+(e.endsWith(".json")?a.slice(0,a.length-1):a).join("/");return i=e.startsWith("/")?`/${i}`:i,{modelBaseUri:i,manifestUri:i==="/"?`/${s}`:`${i}/${s}`}}async function Dfe(e,t){let{manifestUri:r,modelBaseUri:n}=aA(e,t),a=await Rfe(r);return or.loadWeights(a,n)}var Bs=class{constructor(e){this._params=void 0,this._paramMappings=[],this._name=e}get params(){return this._params}get paramMappings(){return this._paramMappings}get isLoaded(){return!!this.params}getParamFromPath(e){let{obj:t,objProp:r}=this.traversePropertyPath(e);return t[r]}reassignParamFromPath(e,t){let{obj:r,objProp:n}=this.traversePropertyPath(e);r[n].dispose(),r[n]=t}getParamList(){return this._paramMappings.map(({paramPath:e})=>({path:e,tensor:this.getParamFromPath(e)}))}getTrainableParams(){return this.getParamList().filter(e=>e.tensor instanceof di)}getFrozenParams(){return this.getParamList().filter(e=>!(e.tensor instanceof di))}variable(){this.getFrozenParams().forEach(({path:e,tensor:t})=>{this.reassignParamFromPath(e,t.variable())})}freeze(){this.getTrainableParams().forEach(({path:e,tensor:t})=>{let r=yr(t.dataSync());t.dispose(),this.reassignParamFromPath(e,r)})}dispose(e=!0){this.getParamList().forEach(t=>{if(e&&t.tensor.isDisposed)throw new Error(`param tensor has already been disposed for path ${t.path}`);t.tensor.dispose()}),this._params=void 0}serializeParams(){return new Float32Array(this.getParamList().map(({tensor:e})=>Array.from(e.dataSync())).reduce((e,t)=>e.concat(t)))}async load(e){if(e instanceof Float32Array){this.extractWeights(e);return}await this.loadFromUri(e)}async loadFromUri(e){if(e&&typeof e!="string")throw new Error(`${this._name}.loadFromUri - expected model uri`);let t=await Dfe(e,this.getDefaultModelName());this.loadFromWeightMap(t)}async loadFromDisk(e){if(e&&typeof e!="string")throw new Error(`${this._name}.loadFromDisk - expected model file path`);let{readFile:t}=Or.getEnv(),{manifestUri:r,modelBaseUri:n}=aA(e,this.getDefaultModelName()),a=l=>Promise.all(l.map(p=>t(p).then(u=>typeof u=="string"?Buffer.from(u):u.buffer))),s=or.weightsLoaderFactory(a),i=JSON.parse((await t(r)).toString()),o=await s(i,n);this.loadFromWeightMap(o)}loadFromWeightMap(e){let{paramMappings:t,params:r}=this.extractParamsFromWeightMap(e);this._paramMappings=t,this._params=r}extractWeights(e){let{paramMappings:t,params:r}=this.extractParams(e);this._paramMappings=t,this._params=r}traversePropertyPath(e){if(!this.params)throw new Error("traversePropertyPath - model has no loaded params");let t=e.split("/").reduce((a,s)=>{if(!a.nextObj.hasOwnProperty(s))throw new Error(`traversePropertyPath - object does not have property ${s}, for path ${e}`);return{obj:a.nextObj,objProp:s,nextObj:a.nextObj[s]}},{nextObj:this.params}),{obj:r,objProp:n}=t;if(!r||!n||!(r[n]instanceof ze))throw new Error(`traversePropertyPath - parameter is not a tensor, for path ${e}`);return{obj:r,objProp:n}}};function un(e,t,r){return W(()=>{let n=tp(e,t.depthwise_filter,t.pointwise_filter,r,"same");return n=J(n,t.bias),n})}function Xm(e,t,r=!1){return W(()=>{let n=rt(r?J(br(e,t.conv0.filters,[2,2],"same"),t.conv0.bias):un(e,t.conv0,[2,2])),a=un(n,t.conv1,[1,1]),s=rt(J(n,a)),i=un(s,t.conv2,[1,1]);return rt(J(n,J(a,i)))})}function Gh(e,t,r=!1,n=!0){return W(()=>{let a=rt(r?J(br(e,t.conv0.filters,n?[2,2]:[1,1],"same"),t.conv0.bias):un(e,t.conv0,n?[2,2]:[1,1])),s=un(a,t.conv1,[1,1]),i=rt(J(a,s)),o=un(i,t.conv2,[1,1]),l=rt(J(a,J(s,o))),p=un(l,t.conv3,[1,1]);return rt(J(a,J(s,J(o,p))))})}function Vp(e,t,r="same",n=!1){return W(()=>{let a=J(br(e,t.filters,[1,1],r),t.bias);return n?rt(a):a})}function Ws(e,t){Object.keys(e).forEach(r=>{t.some(n=>n.originalPath===r)||e[r].dispose()})}function Iw(e,t){return(r,n,a,s)=>{let i=bs(e(r*n*a*a),[a,a,r,n]),o=Qe(e(n));return t.push({paramPath:`${s}/filters`},{paramPath:`${s}/bias`}),{filters:i,bias:o}}}function sA(e,t){return(r,n,a)=>{let s=ia(e(r*n),[r,n]),i=Qe(e(n));return t.push({paramPath:`${a}/weights`},{paramPath:`${a}/bias`}),{weights:s,bias:i}}}var iA=class{constructor(e,t,r){this.depthwise_filter=e,this.pointwise_filter=t,this.bias=r}};function Sw(e,t){return(r,n,a)=>{let s=bs(e(9*r),[3,3,r,1]),i=bs(e(r*n),[1,1,r,n]),o=Qe(e(n));return t.push({paramPath:`${a}/depthwise_filter`},{paramPath:`${a}/pointwise_filter`},{paramPath:`${a}/bias`}),new iA(s,i,o)}}function Nw(e){return t=>{let r=e(`${t}/depthwise_filter`,4),n=e(`${t}/pointwise_filter`,4),a=e(`${t}/bias`,1);return new iA(r,n,a)}}function il(e,t){return(r,n,a)=>{let s=e[r];if(!gp(s,n))throw new Error(`expected weightMap[${r}] to be a Tensor${n}D, instead have ${s}`);return t.push({originalPath:r,paramPath:a||r}),s}}function Us(e){let t=e;function r(a){let s=t.slice(0,a);return t=t.slice(a),s}function n(){return t}return{extractWeights:r,getRemainingWeights:n}}function oA(e,t){let r=Iw(e,t),n=Sw(e,t);function a(i,o,l,p=!1){let u=p?r(i,o,3,`${l}/conv0`):n(i,o,`${l}/conv0`),d=n(o,o,`${l}/conv1`),h=n(o,o,`${l}/conv2`);return{conv0:u,conv1:d,conv2:h}}function s(i,o,l,p=!1){let{conv0:u,conv1:d,conv2:h}=a(i,o,l,p),c=n(o,o,`${l}/conv3`);return{conv0:u,conv1:d,conv2:h,conv3:c}}return{extractDenseBlock3Params:a,extractDenseBlock4Params:s}}function Mfe(e){let t=[],{extractWeights:r,getRemainingWeights:n}=Us(e),{extractDenseBlock4Params:a}=oA(r,t),s=a(3,32,"dense0",!0),i=a(32,64,"dense1"),o=a(64,128,"dense2"),l=a(128,256,"dense3");if(n().length!==0)throw new Error(`weights remaing after extract: ${n().length}`);return{paramMappings:t,params:{dense0:s,dense1:i,dense2:o,dense3:l}}}function lA(e){return t=>{let r=e(`${t}/filters`,4),n=e(`${t}/bias`,1);return{filters:r,bias:n}}}function uA(e,t){let r=il(e,t),n=lA(r),a=Nw(r);function s(o,l=!1){let p=l?n(`${o}/conv0`):a(`${o}/conv0`),u=a(`${o}/conv1`),d=a(`${o}/conv2`);return{conv0:p,conv1:u,conv2:d}}function i(o,l=!1){let p=l?n(`${o}/conv0`):a(`${o}/conv0`),u=a(`${o}/conv1`),d=a(`${o}/conv2`),h=a(`${o}/conv3`);return{conv0:p,conv1:u,conv2:d,conv3:h}}return{extractDenseBlock3Params:s,extractDenseBlock4Params:i}}function Ofe(e){let t=[],{extractDenseBlock4Params:r}=uA(e,t),n={dense0:r("dense0",!0),dense1:r("dense1"),dense2:r("dense2"),dense3:r("dense3")};return Ws(e,t),{params:n,paramMappings:t}}var pA=class extends Bs{constructor(){super("FaceFeatureExtractor")}forwardInput(e){let{params:t}=this;if(!t)throw new Error("FaceFeatureExtractor - load model before inference");return W(()=>{let r=se(e.toBatchTensor(112,!0),"float32"),n=ch(r,[122.782,117.001,104.298]).div(255),a=Gh(n,t.dense0,!0);return a=Gh(a,t.dense1),a=Gh(a,t.dense2),a=Gh(a,t.dense3),a=Oa(a,[7,7],[2,2],"valid"),a})}async forward(e){return this.forwardInput(await vr(e))}getDefaultModelName(){return"face_feature_extractor_model"}extractParamsFromWeightMap(e){return Ofe(e)}extractParams(e){return Mfe(e)}};function ly(e,t){return W(()=>J(Me(e,t.weights),t.bias))}function Lfe(e,t,r){let n=[],{extractWeights:a,getRemainingWeights:s}=Us(e),i=sA(a,n)(t,r,"fc");if(s().length!==0)throw new Error(`weights remaing after extract: ${s().length}`);return{paramMappings:n,params:{fc:i}}}function zfe(e){let t=[],r=il(e,t);function n(s){let i=r(`${s}/weights`,2),o=r(`${s}/bias`,1);return{weights:i,bias:o}}let a={fc:n("fc")};return Ws(e,t),{params:a,paramMappings:t}}function dA(e){let t={},r={};return Object.keys(e).forEach(n=>{let a=n.startsWith("fc")?r:t;a[n]=e[n]}),{featureExtractorMap:t,classifierMap:r}}var hA=class extends Bs{constructor(e,t){super(e),this._faceFeatureExtractor=t}get faceFeatureExtractor(){return this._faceFeatureExtractor}runNet(e){let{params:t}=this;if(!t)throw new Error(`${this._name} - load model before inference`);return W(()=>{let r=e instanceof Gc?this.faceFeatureExtractor.forwardInput(e):e;return ly(r.as2D(r.shape[0],-1),t.fc)})}dispose(e=!0){this.faceFeatureExtractor.dispose(e),super.dispose(e)}loadClassifierParams(e){let{params:t,paramMappings:r}=this.extractClassifierParams(e);this._params=t,this._paramMappings=r}extractClassifierParams(e){return Lfe(e,this.getClassifierChannelsIn(),this.getClassifierChannelsOut())}extractParamsFromWeightMap(e){let{featureExtractorMap:t,classifierMap:r}=dA(e);return this.faceFeatureExtractor.loadFromWeightMap(t),zfe(r)}extractParams(e){let t=this.getClassifierChannelsIn(),r=this.getClassifierChannelsOut(),n=r*t+r,a=e.slice(0,e.length-n),s=e.slice(e.length-n);return this.faceFeatureExtractor.extractWeights(a),this.extractClassifierParams(s)}},j1=["neutral","happy","sad","angry","fearful","disgusted","surprised"],_w=class{constructor(e){if(this.neutral=0,this.happy=0,this.sad=0,this.angry=0,this.fearful=0,this.disgusted=0,this.surprised=0,e.length!==7)throw new Error(`FaceExpressions.constructor - expected probabilities.length to be 7, have: ${e.length}`);j1.forEach((t,r)=>{this[t]=e[r]})}asSortedArray(){return j1.map(e=>({expression:e,probability:this[e]})).sort((e,t)=>t.probability-e.probability)}},Pfe=class extends hA{constructor(e=new pA){super("FaceExpressionNet",e)}forwardInput(e){return W(()=>Ds(this.runNet(e)))}async forward(e){return this.forwardInput(await vr(e))}async predictExpressions(e){let t=await vr(e),r=await this.forwardInput(t),n=await Promise.all(Tt(r).map(async s=>{let i=s.dataSync();return s.dispose(),i}));r.dispose();let a=n.map(s=>new _w(s));return t.isBatchInput?a:a[0]}getDefaultModelName(){return"face_expression_model"}getClassifierChannelsIn(){return 256}getClassifierChannelsOut(){return 7}};function Bfe(e){return e.expressions instanceof _w}function Wfe(e,t){return{...e,expressions:t}}function Ufe(e,t,r=.1,n){(Array.isArray(t)?t:[t]).forEach(a=>{let s=a instanceof _w?a:Bfe(a)?a.expressions:void 0;if(!s)throw new Error("drawFaceExpressions - expected faceExpressions to be FaceExpressions | WithFaceExpressions<{}> or array thereof");let i=s.asSortedArray().filter(l=>l.probability>r),o=Uc(a)?a.detection.box.bottomLeft:n||new it(0,0);new kw(i.map(l=>`${l.expression} (${gw(l.probability)})`),o).draw(e)})}function cA(e){return Uc(e)&&e.landmarks instanceof Wc&&e.unshiftedLandmarks instanceof Wc&&e.alignedRect instanceof Gn}function Vfe(e){let t=l=>l*180/Math.PI,r=(l,p)=>Math.sqrt((l.x-p.x)**2+(l.y-p.y)**2),n={roll:void 0,pitch:void 0,yaw:void 0},a=(l,p,u)=>{let d=Math.floor(l.x-p.x),h=Math.floor(p.x-u.x);return d-h},s=(l,p)=>{let u=Math.hypot(p.x-l.x,p.y-l.y),d=p.y-l.y,h=Math.asin(d/u),c=t(h),f=Math.floor(90-c),m=p.x-l.x<0?-1:1;return f*m},i=(l,p,u)=>{let d=r(l,u),h=new it((l.x+u.x)/2,(l.y+u.y)/2),c=r(p,h),f=Math.atan(c/d),m=Math.floor(t(f)),g=h.y-p.y<0?-1:1;return m*g};if(!e||!e.positions||e.positions.length!==68)return n;let o=e.positions;return n.roll=s(o[27],o[66]),n.pitch=i(o[14],o[30],o[2]),n.yaw=a(o[14],o[33],o[2]),n}function Gfe(e,t){let{box:r}=e.detection,n=t.shiftBy(r.x,r.y),a=n.align(),{imageDims:s}=e.detection,i=new Gn(e.detection.score,a.rescale(s.reverse()),s),o=Vfe(t);return{...e,landmarks:n,unshiftedLandmarks:t,alignedRect:i,angle:o}}var fA=class{constructor(e={}){let{drawLines:t=!0,drawPoints:r=!0,lineWidth:n,lineColor:a,pointSize:s,pointColor:i}=e;this.drawLines=t,this.drawPoints=r,this.lineWidth=n||1,this.pointSize=s||2,this.lineColor=a||"rgba(0, 255, 255, 1)",this.pointColor=i||"rgba(255, 0, 255, 1)"}},mA=class{constructor(e,t={}){this.faceLandmarks=e,this.options=new fA(t)}draw(e){let t=Ns(e),{drawLines:r,drawPoints:n,lineWidth:a,lineColor:s,pointSize:i,pointColor:o}=this.options;if(r&&this.faceLandmarks instanceof G$&&(t.strokeStyle=s,t.lineWidth=a,Xa(t,this.faceLandmarks.getJawOutline()),Xa(t,this.faceLandmarks.getLeftEyeBrow()),Xa(t,this.faceLandmarks.getRightEyeBrow()),Xa(t,this.faceLandmarks.getNose()),Xa(t,this.faceLandmarks.getLeftEye(),!0),Xa(t,this.faceLandmarks.getRightEye(),!0),Xa(t,this.faceLandmarks.getMouth(),!0)),n){t.strokeStyle=o,t.fillStyle=o;let l=p=>{t.beginPath(),t.arc(p.x,p.y,i,0,2*Math.PI),t.fill()};this.faceLandmarks.positions.forEach(l)}}};function Hfe(e,t){(Array.isArray(t)?t:[t]).forEach(r=>{let n=r instanceof Wc?r:cA(r)?r.landmarks:void 0;if(!n)throw new Error("drawFaceLandmarks - expected faceExpressions to be FaceLandmarks | WithFaceLandmarks<WithFaceDetection<{}>> or array thereof");new mA(n).draw(e)})}function jfe(e,t){let r=Iw(e,t),n=Sw(e,t);function a(i,o,l){let p=n(i,o,`${l}/separable_conv0`),u=n(o,o,`${l}/separable_conv1`),d=r(i,o,1,`${l}/expansion_conv`);return{separable_conv0:p,separable_conv1:u,expansion_conv:d}}function s(i,o){let l=n(i,i,`${o}/separable_conv0`),p=n(i,i,`${o}/separable_conv1`),u=n(i,i,`${o}/separable_conv2`);return{separable_conv0:l,separable_conv1:p,separable_conv2:u}}return{extractConvParams:r,extractSeparableConvParams:n,extractReductionBlockParams:a,extractMainBlockParams:s}}function qfe(e,t){let r=[],{extractWeights:n,getRemainingWeights:a}=Us(e),{extractConvParams:s,extractSeparableConvParams:i,extractReductionBlockParams:o,extractMainBlockParams:l}=jfe(n,r),p=s(3,32,3,"entry_flow/conv_in"),u=o(32,64,"entry_flow/reduction_block_0"),d=o(64,128,"entry_flow/reduction_block_1"),h={conv_in:p,reduction_block_0:u,reduction_block_1:d},c={};Vl(t,0,1).forEach(y=>{c[`main_block_${y}`]=l(128,`middle_flow/main_block_${y}`)});let f=o(128,256,"exit_flow/reduction_block"),m=i(256,512,"exit_flow/separable_conv"),g={reduction_block:f,separable_conv:m};if(a().length!==0)throw new Error(`weights remaing after extract: ${a().length}`);return{paramMappings:r,params:{entry_flow:h,middle_flow:c,exit_flow:g}}}function Kfe(e,t){let r=il(e,t),n=lA(r),a=Nw(r);function s(o){let l=a(`${o}/separable_conv0`),p=a(`${o}/separable_conv1`),u=n(`${o}/expansion_conv`);return{separable_conv0:l,separable_conv1:p,expansion_conv:u}}function i(o){let l=a(`${o}/separable_conv0`),p=a(`${o}/separable_conv1`),u=a(`${o}/separable_conv2`);return{separable_conv0:l,separable_conv1:p,separable_conv2:u}}return{extractConvParams:n,extractSeparableConvParams:a,extractReductionBlockParams:s,extractMainBlockParams:i}}function Xfe(e,t){let r=[],{extractConvParams:n,extractSeparableConvParams:a,extractReductionBlockParams:s,extractMainBlockParams:i}=Kfe(e,r),o=n("entry_flow/conv_in"),l=s("entry_flow/reduction_block_0"),p=s("entry_flow/reduction_block_1"),u={conv_in:o,reduction_block_0:l,reduction_block_1:p},d={};Vl(t,0,1).forEach(m=>{d[`main_block_${m}`]=i(`middle_flow/main_block_${m}`)});let h=s("exit_flow/reduction_block"),c=a("exit_flow/separable_conv"),f={reduction_block:h,separable_conv:c};return Ws(e,r),{params:{entry_flow:u,middle_flow:d,exit_flow:f},paramMappings:r}}function gA(e,t,r){return J(br(e,t.filters,r,"same"),t.bias)}function Zm(e,t,r=!0){let n=r?rt(e):e;return n=un(n,t.separable_conv0,[1,1]),n=un(rt(n),t.separable_conv1,[1,1]),n=jt(n,[3,3],[2,2],"same"),n=J(n,gA(e,t.expansion_conv,[2,2])),n}function Zfe(e,t){let r=un(rt(e),t.separable_conv0,[1,1]);return r=un(rt(r),t.separable_conv1,[1,1]),r=un(rt(r),t.separable_conv2,[1,1]),r=J(r,e),r}var Jfe=class extends Bs{constructor(e){super("TinyXception"),this._numMainBlocks=e}forwardInput(e){let{params:t}=this;if(!t)throw new Error("TinyXception - load model before inference");return W(()=>{let r=se(e.toBatchTensor(112,!0),"float32"),n=ch(r,[122.782,117.001,104.298]).div(255),a=rt(gA(n,t.entry_flow.conv_in,[2,2]));return a=Zm(a,t.entry_flow.reduction_block_0,!1),a=Zm(a,t.entry_flow.reduction_block_1),Vl(this._numMainBlocks,0,1).forEach(s=>{a=Zfe(a,t.middle_flow[`main_block_${s}`])}),a=Zm(a,t.exit_flow.reduction_block),a=rt(un(a,t.exit_flow.separable_conv,[1,1])),a})}async forward(e){return this.forwardInput(await vr(e))}getDefaultModelName(){return"tiny_xception_model"}extractParamsFromWeightMap(e){return Xfe(e,this._numMainBlocks)}extractParams(e){return qfe(e,this._numMainBlocks)}};function Yfe(e){let t=[],{extractWeights:r,getRemainingWeights:n}=Us(e),a=sA(r,t),s=a(512,1,"fc/age"),i=a(512,2,"fc/gender");if(n().length!==0)throw new Error(`weights remaing after extract: ${n().length}`);return{paramMappings:t,params:{fc:{age:s,gender:i}}}}function Qfe(e){let t=[],r=il(e,t);function n(s){let i=r(`${s}/weights`,2),o=r(`${s}/bias`,1);return{weights:i,bias:o}}let a={fc:{age:n("fc/age"),gender:n("fc/gender")}};return Ws(e,t),{params:a,paramMappings:t}}var eme=(e=>(e.FEMALE="female",e.MALE="male",e))(eme||{}),tme=class extends Bs{constructor(e=new Jfe(2)){super("AgeGenderNet"),this._faceFeatureExtractor=e}get faceFeatureExtractor(){return this._faceFeatureExtractor}runNet(e){let{params:t}=this;if(!t)throw new Error(`${this._name} - load model before inference`);return W(()=>{let r=e instanceof Gc?this.faceFeatureExtractor.forwardInput(e):e,n=Oa(r,[7,7],[2,2],"valid").as2D(r.shape[0],-1),a=ly(n,t.fc.age).as1D(),s=ly(n,t.fc.gender);return{age:a,gender:s}})}forwardInput(e){return W(()=>{let{age:t,gender:r}=this.runNet(e);return{age:t,gender:Ds(r)}})}async forward(e){return this.forwardInput(await vr(e))}async predictAgeAndGender(e){let t=await vr(e),r=await this.forwardInput(t),n=Tt(r.age),a=Tt(r.gender),s=n.map((o,l)=>({ageTensor:o,genderTensor:a[l]})),i=await Promise.all(s.map(async({ageTensor:o,genderTensor:l})=>{let p=o.dataSync()[0],u=l.dataSync()[0],d=u>.5,h=d?"male":"female",c=d?u:1-u;return o.dispose(),l.dispose(),{age:p,gender:h,genderProbability:c}}));return r.age.dispose(),r.gender.dispose(),t.isBatchInput?i:i[0]}getDefaultModelName(){return"age_gender_model"}dispose(e=!0){this.faceFeatureExtractor.dispose(e),super.dispose(e)}loadClassifierParams(e){let{params:t,paramMappings:r}=this.extractClassifierParams(e);this._params=t,this._paramMappings=r}extractClassifierParams(e){return Yfe(e)}extractParamsFromWeightMap(e){let{featureExtractorMap:t,classifierMap:r}=dA(e);return this.faceFeatureExtractor.loadFromWeightMap(t),Qfe(r)}extractParams(e){let t=e.slice(0,e.length-1539),r=e.slice(e.length-1539);return this.faceFeatureExtractor.extractWeights(t),this.extractClassifierParams(r)}},yA=class extends hA{postProcess(e,t,r){let n=r.map(({width:s,height:i})=>{let o=t/Math.max(i,s);return{width:s*o,height:i*o}}),a=n.length;return W(()=>{let s=(p,u)=>Mt([qr([68],p,"float32"),qr([68],u,"float32")],1).as2D(1,136).as1D(),i=(p,u)=>{let{width:d,height:h}=n[p];return u(d,h)?Math.abs(d-h)/2:0},o=p=>i(p,(u,d)=>u<d),l=p=>i(p,(u,d)=>d<u);return e.mul(qr([a,136],t,"float32")).sub(Mt(Array.from(Array(a),(p,u)=>s(o(u),l(u))))).div(Mt(Array.from(Array(a),(p,u)=>s(n[u].width,n[u].height))))})}forwardInput(e){return W(()=>{let t=this.runNet(e);return this.postProcess(t,e.inputSize,e.inputDimensions.map(([r,n])=>({height:r,width:n})))})}async forward(e){return this.forwardInput(await vr(e))}async detectLandmarks(e){let t=await vr(e),r=W(()=>Tt(this.forwardInput(t))),n=await Promise.all(r.map(async(a,s)=>{let i=Array.from(a.dataSync()),o=i.filter((p,u)=>sy(u)),l=i.filter((p,u)=>!sy(u));return new G$(Array(68).fill(0).map((p,u)=>new it(o[u],l[u])),{height:t.getInputHeight(s),width:t.getInputWidth(s)})}));return r.forEach(a=>a.dispose()),t.isBatchInput?n:n[0]}getClassifierChannelsOut(){return 136}},rme=class extends yA{constructor(e=new pA){super("FaceLandmark68Net",e)}getDefaultModelName(){return"face_landmark_68_model"}getClassifierChannelsIn(){return 256}};function nme(e){let t=[],{extractDenseBlock3Params:r}=uA(e,t),n={dense0:r("dense0",!0),dense1:r("dense1"),dense2:r("dense2")};return Ws(e,t),{params:n,paramMappings:t}}function ame(e){let t=[],{extractWeights:r,getRemainingWeights:n}=Us(e),{extractDenseBlock3Params:a}=oA(r,t),s=a(3,32,"dense0",!0),i=a(32,64,"dense1"),o=a(64,128,"dense2");if(n().length!==0)throw new Error(`weights remaing after extract: ${n().length}`);return{paramMappings:t,params:{dense0:s,dense1:i,dense2:o}}}var sme=class extends Bs{constructor(){super("TinyFaceFeatureExtractor")}forwardInput(e){let{params:t}=this;if(!t)throw new Error("TinyFaceFeatureExtractor - load model before inference");return W(()=>{let r=se(e.toBatchTensor(112,!0),"float32"),n=ch(r,[122.782,117.001,104.298]).div(255),a=Xm(n,t.dense0,!0);return a=Xm(a,t.dense1),a=Xm(a,t.dense2),a=Oa(a,[14,14],[2,2],"valid"),a})}async forward(e){return this.forwardInput(await vr(e))}getDefaultModelName(){return"face_feature_extractor_tiny_model"}extractParamsFromWeightMap(e){return nme(e)}extractParams(e){return ame(e)}},ime=class extends yA{constructor(e=new sme){super("FaceLandmark68TinyNet",e)}getDefaultModelName(){return"face_landmark_68_tiny_model"}getClassifierChannelsIn(){return 128}};function ome(e,t){return J(z(e,t.weights),t.biases)}function Tw(e,t,r,n,a="same"){let{filters:s,bias:i}=t.conv,o=br(e,s,r,a);return o=J(o,i),o=ome(o,t.scale),n?rt(o):o}function lme(e,t){return Tw(e,t,[1,1],!0)}function bA(e,t){return Tw(e,t,[1,1],!1)}function xA(e,t){return Tw(e,t,[2,2],!0,"valid")}function ume(e,t){function r(o,l,p){let u=e(o),d=u.length/(l*p*p);if(L$(d))throw new Error(`depth has to be an integer: ${d}, weights.length: ${u.length}, numFilters: ${l}, filterSize: ${p}`);return W(()=>Oe(bs(u,[l,d,p,p]),[2,3,1,0]))}function n(o,l,p,u){let d=r(o,l,p),h=Qe(e(l));return t.push({paramPath:`${u}/filters`},{paramPath:`${u}/bias`}),{filters:d,bias:h}}function a(o,l){let p=Qe(e(o)),u=Qe(e(o));return t.push({paramPath:`${l}/weights`},{paramPath:`${l}/biases`}),{weights:p,biases:u}}function s(o,l,p,u){let d=n(o,l,p,`${u}/conv`),h=a(l,`${u}/scale`);return{conv:d,scale:h}}function i(o,l,p,u,d=!1){let h=s((d?.5:1)*o,l,p,`${u}/conv1`),c=s(o,l,p,`${u}/conv2`);return{conv1:h,conv2:c}}return{extractConvLayerParams:s,extractResidualLayerParams:i}}function pme(e){let{extractWeights:t,getRemainingWeights:r}=Us(e),n=[],{extractConvLayerParams:a,extractResidualLayerParams:s}=ume(t,n),i=a(4704,32,7,"conv32_down"),o=s(9216,32,3,"conv32_1"),l=s(9216,32,3,"conv32_2"),p=s(9216,32,3,"conv32_3"),u=s(36864,64,3,"conv64_down",!0),d=s(36864,64,3,"conv64_1"),h=s(36864,64,3,"conv64_2"),c=s(36864,64,3,"conv64_3"),f=s(147456,128,3,"conv128_down",!0),m=s(147456,128,3,"conv128_1"),g=s(147456,128,3,"conv128_2"),y=s(589824,256,3,"conv256_down",!0),b=s(589824,256,3,"conv256_1"),x=s(589824,256,3,"conv256_2"),v=s(589824,256,3,"conv256_down_out"),w=W(()=>Oe(ia(t(256*128),[128,256]),[1,0]));if(n.push({paramPath:"fc"}),r().length!==0)throw new Error(`weights remaing after extract: ${r().length}`);return{params:{conv32_down:i,conv32_1:o,conv32_2:l,conv32_3:p,conv64_down:u,conv64_1:d,conv64_2:h,conv64_3:c,conv128_down:f,conv128_1:m,conv128_2:g,conv256_down:y,conv256_1:b,conv256_2:x,conv256_down_out:v,fc:w},paramMappings:n}}function dme(e,t){let r=il(e,t);function n(i){let o=r(`${i}/scale/weights`,1),l=r(`${i}/scale/biases`,1);return{weights:o,biases:l}}function a(i){let o=r(`${i}/conv/filters`,4),l=r(`${i}/conv/bias`,1),p=n(i);return{conv:{filters:o,bias:l},scale:p}}function s(i){return{conv1:a(`${i}/conv1`),conv2:a(`${i}/conv2`)}}return{extractConvLayerParams:a,extractResidualLayerParams:s}}function hme(e){let t=[],{extractConvLayerParams:r,extractResidualLayerParams:n}=dme(e,t),a=r("conv32_down"),s=n("conv32_1"),i=n("conv32_2"),o=n("conv32_3"),l=n("conv64_down"),p=n("conv64_1"),u=n("conv64_2"),d=n("conv64_3"),h=n("conv128_down"),c=n("conv128_1"),f=n("conv128_2"),m=n("conv256_down"),g=n("conv256_1"),y=n("conv256_2"),b=n("conv256_down_out"),{fc:x}=e;if(t.push({originalPath:"fc",paramPath:"fc"}),!O$(x))throw new Error(`expected weightMap[fc] to be a Tensor2D, instead have ${x}`);let v={conv32_down:a,conv32_1:s,conv32_2:i,conv32_3:o,conv64_down:l,conv64_1:p,conv64_2:u,conv64_3:d,conv128_down:h,conv128_1:c,conv128_2:f,conv256_down:m,conv256_1:g,conv256_2:y,conv256_down_out:b,fc:x};return Ws(e,t),{params:v,paramMappings:t}}function Xn(e,t){let r=lme(e,t.conv1);return r=bA(r,t.conv2),r=J(r,e),r=rt(r),r}function Hh(e,t){let r=xA(e,t.conv1);r=bA(r,t.conv2);let n=Oa(e,2,2,"valid"),a=It(n.shape),s=n.shape[3]!==r.shape[3];if(n.shape[1]!==r.shape[1]||n.shape[2]!==r.shape[2]){let i=[...r.shape];i[1]=1;let o=It(i);r=lt([r,o],1);let l=[...r.shape];l[2]=1;let p=It(l);r=lt([r,p],2)}return n=s?lt([n,a],3):n,r=J(n,r),r=rt(r),r}var cme=class extends Bs{constructor(){super("FaceRecognitionNet")}forwardInput(e){let{params:t}=this;if(!t)throw new Error("FaceRecognitionNet - load model before inference");return W(()=>{let r=se(e.toBatchTensor(150,!0),"float32"),n=ch(r,[122.782,117.001,104.298]).div(255),a=xA(n,t.conv32_down);a=jt(a,3,2,"valid"),a=Xn(a,t.conv32_1),a=Xn(a,t.conv32_2),a=Xn(a,t.conv32_3),a=Hh(a,t.conv64_down),a=Xn(a,t.conv64_1),a=Xn(a,t.conv64_2),a=Xn(a,t.conv64_3),a=Hh(a,t.conv128_down),a=Xn(a,t.conv128_1),a=Xn(a,t.conv128_2),a=Hh(a,t.conv256_down),a=Xn(a,t.conv256_1),a=Xn(a,t.conv256_2),a=Hh(a,t.conv256_down_out);let s=a.mean([1,2]);return Me(s,t.fc)})}async forward(e){return this.forwardInput(await vr(e))}async computeFaceDescriptor(e){var t;if((t=e==null?void 0:e.shape)!=null&&t.some(s=>s<=0))return new Float32Array(128);let r=await vr(e),n=W(()=>Tt(this.forwardInput(r))),a=await Promise.all(n.map(s=>s.data()));return n.forEach(s=>s.dispose()),r.isBatchInput?a:a[0]}getDefaultModelName(){return"face_recognition_model"}extractParamsFromWeightMap(e){return hme(e)}extractParams(e){return pme(e)}};function fme(e,t){return{...e,descriptor:t}}function mme(e,t){return{...e,age:t}}function gme(e,t,r){return{...e,gender:t,genderProbability:r}}function yme(e,t){function r(l,p){let u=bs(e(9*l),[3,3,l,1]),d=Qe(e(l)),h=Qe(e(l)),c=Qe(e(l)),f=Qe(e(l));return t.push({paramPath:`${p}/filters`},{paramPath:`${p}/batch_norm_scale`},{paramPath:`${p}/batch_norm_offset`},{paramPath:`${p}/batch_norm_mean`},{paramPath:`${p}/batch_norm_variance`}),{filters:u,batch_norm_scale:d,batch_norm_offset:h,batch_norm_mean:c,batch_norm_variance:f}}function n(l,p,u,d,h){let c=bs(e(l*p*u*u),[u,u,l,p]),f=Qe(e(p));return t.push({paramPath:`${d}/filters`},{paramPath:`${d}/${h?"batch_norm_offset":"bias"}`}),{filters:c,bias:f}}function a(l,p,u,d){let{filters:h,bias:c}=n(l,p,u,d,!0);return{filters:h,batch_norm_offset:c}}function s(l,p,u){let d=r(l,`${u}/depthwise_conv`),h=a(l,p,1,`${u}/pointwise_conv`);return{depthwise_conv:d,pointwise_conv:h}}function i(){let l=a(3,32,3,"mobilenetv1/conv_0"),p=s(32,64,"mobilenetv1/conv_1"),u=s(64,128,"mobilenetv1/conv_2"),d=s(128,128,"mobilenetv1/conv_3"),h=s(128,256,"mobilenetv1/conv_4"),c=s(256,256,"mobilenetv1/conv_5"),f=s(256,512,"mobilenetv1/conv_6"),m=s(512,512,"mobilenetv1/conv_7"),g=s(512,512,"mobilenetv1/conv_8"),y=s(512,512,"mobilenetv1/conv_9"),b=s(512,512,"mobilenetv1/conv_10"),x=s(512,512,"mobilenetv1/conv_11"),v=s(512,1024,"mobilenetv1/conv_12"),w=s(1024,1024,"mobilenetv1/conv_13");return{conv_0:l,conv_1:p,conv_2:u,conv_3:d,conv_4:h,conv_5:c,conv_6:f,conv_7:m,conv_8:g,conv_9:y,conv_10:b,conv_11:x,conv_12:v,conv_13:w}}function o(){let l=a(1024,256,1,"prediction_layer/conv_0"),p=a(256,512,3,"prediction_layer/conv_1"),u=a(512,128,1,"prediction_layer/conv_2"),d=a(128,256,3,"prediction_layer/conv_3"),h=a(256,128,1,"prediction_layer/conv_4"),c=a(128,256,3,"prediction_layer/conv_5"),f=a(256,64,1,"prediction_layer/conv_6"),m=a(64,128,3,"prediction_layer/conv_7"),g=n(512,12,1,"prediction_layer/box_predictor_0/box_encoding_predictor"),y=n(512,9,1,"prediction_layer/box_predictor_0/class_predictor"),b=n(1024,24,1,"prediction_layer/box_predictor_1/box_encoding_predictor"),x=n(1024,18,1,"prediction_layer/box_predictor_1/class_predictor"),v=n(512,24,1,"prediction_layer/box_predictor_2/box_encoding_predictor"),w=n(512,18,1,"prediction_layer/box_predictor_2/class_predictor"),N=n(256,24,1,"prediction_layer/box_predictor_3/box_encoding_predictor"),T=n(256,18,1,"prediction_layer/box_predictor_3/class_predictor"),E=n(256,24,1,"prediction_layer/box_predictor_4/box_encoding_predictor"),$=n(256,18,1,"prediction_layer/box_predictor_4/class_predictor"),R=n(128,24,1,"prediction_layer/box_predictor_5/box_encoding_predictor"),F=n(128,18,1,"prediction_layer/box_predictor_5/class_predictor");return{conv_0:l,conv_1:p,conv_2:u,conv_3:d,conv_4:h,conv_5:c,conv_6:f,conv_7:m,box_predictor_0:{box_encoding_predictor:g,class_predictor:y},box_predictor_1:{box_encoding_predictor:b,class_predictor:x},box_predictor_2:{box_encoding_predictor:v,class_predictor:w},box_predictor_3:{box_encoding_predictor:N,class_predictor:T},box_predictor_4:{box_encoding_predictor:E,class_predictor:$},box_predictor_5:{box_encoding_predictor:R,class_predictor:F}}}return{extractMobilenetV1Params:i,extractPredictionLayerParams:o}}function bme(e){let t=[],{extractWeights:r,getRemainingWeights:n}=Us(e),{extractMobilenetV1Params:a,extractPredictionLayerParams:s}=yme(r,t),i=a(),o=s(),l={extra_dim:Lf(r(5118*4),[1,5118,4])};if(t.push({paramPath:"output_layer/extra_dim"}),n().length!==0)throw new Error(`weights remaing after extract: ${n().length}`);return{params:{mobilenetv1:i,prediction_layer:o,output_layer:l},paramMappings:t}}function xme(e,t){let r=il(e,t);function n(p,u,d){let h=r(`${p}/Conv2d_${u}_pointwise/weights`,4,`${d}/filters`),c=r(`${p}/Conv2d_${u}_pointwise/convolution_bn_offset`,1,`${d}/batch_norm_offset`);return{filters:h,batch_norm_offset:c}}function a(p){let u=`mobilenetv1/conv_${p}`,d=`MobilenetV1/Conv2d_${p}_depthwise`,h=`${u}/depthwise_conv`,c=`${u}/pointwise_conv`,f=r(`${d}/depthwise_weights`,4,`${h}/filters`),m=r(`${d}/BatchNorm/gamma`,1,`${h}/batch_norm_scale`),g=r(`${d}/BatchNorm/beta`,1,`${h}/batch_norm_offset`),y=r(`${d}/BatchNorm/moving_mean`,1,`${h}/batch_norm_mean`),b=r(`${d}/BatchNorm/moving_variance`,1,`${h}/batch_norm_variance`);return{depthwise_conv:{filters:f,batch_norm_scale:m,batch_norm_offset:g,batch_norm_mean:y,batch_norm_variance:b},pointwise_conv:n("MobilenetV1",p,c)}}function s(){return{conv_0:n("MobilenetV1",0,"mobilenetv1/conv_0"),conv_1:a(1),conv_2:a(2),conv_3:a(3),conv_4:a(4),conv_5:a(5),conv_6:a(6),conv_7:a(7),conv_8:a(8),conv_9:a(9),conv_10:a(10),conv_11:a(11),conv_12:a(12),conv_13:a(13)}}function i(p,u){let d=r(`${p}/weights`,4,`${u}/filters`),h=r(`${p}/biases`,1,`${u}/bias`);return{filters:d,bias:h}}function o(p){let u=i(`Prediction/BoxPredictor_${p}/BoxEncodingPredictor`,`prediction_layer/box_predictor_${p}/box_encoding_predictor`),d=i(`Prediction/BoxPredictor_${p}/ClassPredictor`,`prediction_layer/box_predictor_${p}/class_predictor`);return{box_encoding_predictor:u,class_predictor:d}}function l(){return{conv_0:n("Prediction",0,"prediction_layer/conv_0"),conv_1:n("Prediction",1,"prediction_layer/conv_1"),conv_2:n("Prediction",2,"prediction_layer/conv_2"),conv_3:n("Prediction",3,"prediction_layer/conv_3"),conv_4:n("Prediction",4,"prediction_layer/conv_4"),conv_5:n("Prediction",5,"prediction_layer/conv_5"),conv_6:n("Prediction",6,"prediction_layer/conv_6"),conv_7:n("Prediction",7,"prediction_layer/conv_7"),box_predictor_0:o(0),box_predictor_1:o(1),box_predictor_2:o(2),box_predictor_3:o(3),box_predictor_4:o(4),box_predictor_5:o(5)}}return{extractMobilenetV1Params:s,extractPredictionLayerParams:l}}function vme(e){let t=[],{extractMobilenetV1Params:r,extractPredictionLayerParams:n}=xme(e,t),a=e["Output/extra_dim"];if(t.push({originalPath:"Output/extra_dim",paramPath:"output_layer/extra_dim"}),!hh(a))throw new Error(`expected weightMap['Output/extra_dim'] to be a Tensor3D, instead have ${a}`);let s={mobilenetv1:r(),prediction_layer:n(),output_layer:{extra_dim:a}};return Ws(e,t),{params:s,paramMappings:t}}function Yn(e,t,r){return W(()=>{let n=br(e,t.filters,r,"same");return n=J(n,t.batch_norm_offset),ur(n,0,6)})}var wme=.0010000000474974513;function kme(e,t,r){return W(()=>{let n=Zo(e,t.filters,r,"same");return n=Xo(n,t.batch_norm_mean,t.batch_norm_variance,t.batch_norm_offset,t.batch_norm_scale,wme),ur(n,0,6)})}function Ime(e){return[2,4,6,12].some(t=>t===e)?[2,2]:[1,1]}function Sme(e,t){return W(()=>{let r,n=Yn(e,t.conv_0,[2,2]);if([t.conv_1,t.conv_2,t.conv_3,t.conv_4,t.conv_5,t.conv_6,t.conv_7,t.conv_8,t.conv_9,t.conv_10,t.conv_11,t.conv_12,t.conv_13].forEach((a,s)=>{let i=s+1,o=Ime(i);n=kme(n,a.depthwise_conv,o),n=Yn(n,a.pointwise_conv,[1,1]),i===11&&(r=n)}),r===null)throw new Error("mobileNetV1 - output of conv layer 11 is null");return{out:n,conv11:r}})}function Nme(e,t,r){let n=e.arraySync(),a=Math.min(n[t][0],n[t][2]),s=Math.min(n[t][1],n[t][3]),i=Math.max(n[t][0],n[t][2]),o=Math.max(n[t][1],n[t][3]),l=Math.min(n[r][0],n[r][2]),p=Math.min(n[r][1],n[r][3]),u=Math.max(n[r][0],n[r][2]),d=Math.max(n[r][1],n[r][3]),h=(i-a)*(o-s),c=(u-l)*(d-p);if(h<=0||c<=0)return 0;let f=Math.max(a,l),m=Math.max(s,p),g=Math.min(i,u),y=Math.min(o,d),b=Math.max(g-f,0)*Math.max(y-m,0);return b/(h+c-b)}function _me(e,t,r,n,a){let s=e.shape[0],i=Math.min(r,s),o=t.map((u,d)=>({score:u,boxIndex:d})).filter(u=>u.score>a).sort((u,d)=>d.score-u.score),l=u=>u<=n?1:0,p=[];return o.forEach(u=>{if(p.length>=i)return;let d=u.score;for(let h=p.length-1;h>=0;--h){let c=Nme(e,u.boxIndex,p[h]);if(c!==0&&(u.score*=l(c),u.score<=a))break}d===u.score&&p.push(u.boxIndex)}),p}function Tme(e){let t=Tt(Oe(e,[1,0])),r=[de(t[2],t[0]),de(t[3],t[1])],n=[J(t[0],fe(r[0],2)),J(t[1],fe(r[1],2))];return{sizes:r,centers:n}}function Cme(e,t){let{sizes:r,centers:n}=Tme(e),a=Tt(Oe(t,[1,0])),s=fe(z(pr(fe(a[2],5)),r[0]),2),i=J(z(fe(a[0],10),r[0]),n[0]),o=fe(z(pr(fe(a[3],5)),r[1]),2),l=J(z(fe(a[1],10),r[1]),n[1]);return Oe(Mt([de(i,s),de(l,o),J(i,s),J(l,o)]),[1,0])}function Eme(e,t,r){return W(()=>{let n=e.shape[0],a=Cme(B(jr(r.extra_dim,[n,1,1]),[-1,4]),B(e,[-1,4]));a=B(a,[n,a.shape[0]/n,4]);let s=In(Ve(t,[0,0,1],[-1,-1,-1])),i=Ve(s,[0,0,0],[-1,-1,1]);i=B(i,[n,i.shape[1]]);let o=Tt(a),l=Tt(i);return{boxes:o,scores:l}})}function cl(e,t){return W(()=>{let r=e.shape[0],n=B(Vp(e,t.box_encoding_predictor),[r,-1,1,4]),a=B(Vp(e,t.class_predictor),[r,-1,3]);return{boxPredictionEncoding:n,classPrediction:a}})}function $me(e,t,r){return W(()=>{let n=Yn(e,r.conv_0,[1,1]),a=Yn(n,r.conv_1,[2,2]),s=Yn(a,r.conv_2,[1,1]),i=Yn(s,r.conv_3,[2,2]),o=Yn(i,r.conv_4,[1,1]),l=Yn(o,r.conv_5,[2,2]),p=Yn(l,r.conv_6,[1,1]),u=Yn(p,r.conv_7,[2,2]),d=cl(t,r.box_predictor_0),h=cl(e,r.box_predictor_1),c=cl(a,r.box_predictor_2),f=cl(i,r.box_predictor_3),m=cl(l,r.box_predictor_4),g=cl(u,r.box_predictor_5),y=lt([d.boxPredictionEncoding,h.boxPredictionEncoding,c.boxPredictionEncoding,f.boxPredictionEncoding,m.boxPredictionEncoding,g.boxPredictionEncoding],1),b=lt([d.classPrediction,h.classPrediction,c.classPrediction,f.classPrediction,m.classPrediction,g.classPrediction],1);return{boxPredictions:y,classPredictions:b}})}var Im=class{constructor({minConfidence:e,maxResults:t}={}){if(this._name="SsdMobilenetv1Options",this._minConfidence=e||.5,this._maxResults=t||100,typeof this._minConfidence!="number"||this._minConfidence<=0||this._minConfidence>=1)throw new Error(`${this._name} - expected minConfidence to be a number between 0 and 1`);if(typeof this._maxResults!="number")throw new Error(`${this._name} - expected maxResults to be a number`)}get minConfidence(){return this._minConfidence}get maxResults(){return this._maxResults}},Ame=class extends Bs{constructor(){super("SsdMobilenetv1")}forwardInput(e){let{params:t}=this;if(!t)throw new Error("SsdMobilenetv1 - load model before inference");return W(()=>{let r=se(e.toBatchTensor(512,!1),"float32"),n=de(fe(r,127.5),1),a=Sme(n,t.mobilenetv1),{boxPredictions:s,classPredictions:i}=$me(a.out,a.conv11,t.prediction_layer);return Eme(s,i,t.output_layer)})}async forward(e){return this.forwardInput(await vr(e))}async locateFaces(e,t={}){let{maxResults:r,minConfidence:n}=new Im(t),a=await vr(e),{boxes:s,scores:i}=this.forwardInput(a),o=s[0],l=i[0];for(let y=1;y<s.length;y++)s[y].dispose(),i[y].dispose();let p=Array.from(l.dataSync()),u=_me(o,p,r,.5,n),d=a.getReshapedInputDimensions(0),h=a.inputSize,c=h/d.width,f=h/d.height,m=o.arraySync(),g=u.map(y=>{let[b,x]=[Math.max(0,m[y][0]),Math.min(1,m[y][2])].map(N=>N*f),[v,w]=[Math.max(0,m[y][1]),Math.min(1,m[y][3])].map(N=>N*c);return new Gn(p[y],new V$(v,b,w-v,x-b),{height:a.getInputHeight(0),width:a.getInputWidth(0)})});return o.dispose(),l.dispose(),g}getDefaultModelName(){return"ssd_mobilenetv1_model"}extractParamsFromWeightMap(e){return vme(e)}extractParams(e){return bme(e)}},Fme=.4,Rme=[new it(.738768,.874946),new it(2.42204,2.65704),new it(4.30971,7.04493),new it(10.246,4.59428),new it(12.6868,11.8741)],Dme=[new it(1.603231,2.094468),new it(6.041143,7.080126),new it(2.882459,3.518061),new it(4.266906,5.178857),new it(9.041765,10.66308)],Mme=[117.001,114.697,97.404],Ome="tiny_yolov2_model",Lme="tiny_yolov2_separable_conv_model",jh=e=>typeof e=="number";function zme(e){if(!e)throw new Error(`invalid config: ${e}`);if(typeof e.withSeparableConvs!="boolean")throw new Error(`config.withSeparableConvs has to be a boolean, have: ${e.withSeparableConvs}`);if(!jh(e.iouThreshold)||e.iouThreshold<0||e.iouThreshold>1)throw new Error(`config.iouThreshold has to be a number between [0, 1], have: ${e.iouThreshold}`);if(!Array.isArray(e.classes)||!e.classes.length||!e.classes.every(t=>typeof t=="string"))throw new Error(`config.classes has to be an array class names: string[], have: ${JSON.stringify(e.classes)}`);if(!Array.isArray(e.anchors)||!e.anchors.length||!e.anchors.map(t=>t||{}).every(t=>jh(t.x)&&jh(t.y)))throw new Error(`config.anchors has to be an array of { x: number, y: number }, have: ${JSON.stringify(e.anchors)}`);if(e.meanRgb&&(!Array.isArray(e.meanRgb)||e.meanRgb.length!==3||!e.meanRgb.every(jh)))throw new Error(`config.meanRgb has to be an array of shape [number, number, number], have: ${JSON.stringify(e.meanRgb)}`)}function Cw(e){return W(()=>{let t=z(e,we(.10000000149011612));return J(rt(de(e,t)),t)})}function Ha(e,t){return W(()=>{let r=jn(e,[[0,0],[1,1],[1,1],[0,0]]);return r=br(r,t.conv.filters,[1,1],"valid"),r=de(r,t.bn.sub),r=z(r,t.bn.truediv),r=J(r,t.conv.bias),Cw(r)})}function ja(e,t){return W(()=>{let r=jn(e,[[0,0],[1,1],[1,1],[0,0]]);return r=tp(r,t.depthwise_filter,t.pointwise_filter,[1,1],"valid"),r=J(r,t.bias),Cw(r)})}function Pme(e,t){let r=Iw(e,t);function n(i,o){let l=Qe(e(i)),p=Qe(e(i));return t.push({paramPath:`${o}/sub`},{paramPath:`${o}/truediv`}),{sub:l,truediv:p}}function a(i,o,l){let p=r(i,o,3,`${l}/conv`),u=n(o,`${l}/bn`);return{conv:p,bn:u}}let s=Sw(e,t);return{extractConvParams:r,extractConvWithBatchNormParams:a,extractSeparableConvParams:s}}function Bme(e,t,r,n){let{extractWeights:a,getRemainingWeights:s}=Us(e),i=[],{extractConvParams:o,extractConvWithBatchNormParams:l,extractSeparableConvParams:p}=Pme(a,i),u;if(t.withSeparableConvs){let[d,h,c,f,m,g,y,b,x]=n,v=t.isFirstLayerConv2d?o(d,h,3,"conv0"):p(d,h,"conv0"),w=p(h,c,"conv1"),N=p(c,f,"conv2"),T=p(f,m,"conv3"),E=p(m,g,"conv4"),$=p(g,y,"conv5"),R=b?p(y,b,"conv6"):void 0,F=x?p(b,x,"conv7"):void 0,S=o(x||b||y,5*r,1,"conv8");u={conv0:v,conv1:w,conv2:N,conv3:T,conv4:E,conv5:$,conv6:R,conv7:F,conv8:S}}else{let[d,h,c,f,m,g,y,b,x]=n,v=l(d,h,"conv0"),w=l(h,c,"conv1"),N=l(c,f,"conv2"),T=l(f,m,"conv3"),E=l(m,g,"conv4"),$=l(g,y,"conv5"),R=l(y,b,"conv6"),F=l(b,x,"conv7"),S=o(x,5*r,1,"conv8");u={conv0:v,conv1:w,conv2:N,conv3:T,conv4:E,conv5:$,conv6:R,conv7:F,conv8:S}}if(s().length!==0)throw new Error(`weights remaing after extract: ${s().length}`);return{params:u,paramMappings:i}}function Wme(e,t){let r=il(e,t);function n(o){let l=r(`${o}/sub`,1),p=r(`${o}/truediv`,1);return{sub:l,truediv:p}}function a(o){let l=r(`${o}/filters`,4),p=r(`${o}/bias`,1);return{filters:l,bias:p}}function s(o){let l=a(`${o}/conv`),p=n(`${o}/bn`);return{conv:l,bn:p}}let i=Nw(r);return{extractConvParams:a,extractConvWithBatchNormParams:s,extractSeparableConvParams:i}}function Ume(e,t){let r=[],{extractConvParams:n,extractConvWithBatchNormParams:a,extractSeparableConvParams:s}=Wme(e,r),i;if(t.withSeparableConvs){let o=t.filterSizes&&t.filterSizes.length||9;i={conv0:t.isFirstLayerConv2d?n("conv0"):s("conv0"),conv1:s("conv1"),conv2:s("conv2"),conv3:s("conv3"),conv4:s("conv4"),conv5:s("conv5"),conv6:o>7?s("conv6"):void 0,conv7:o>8?s("conv7"):void 0,conv8:n("conv8")}}else i={conv0:a("conv0"),conv1:a("conv1"),conv2:a("conv2"),conv3:a("conv3"),conv4:a("conv4"),conv5:a("conv5"),conv6:a("conv6"),conv7:a("conv7"),conv8:n("conv8")};return Ws(e,r),{params:i,paramMappings:r}}var Ew=class{constructor({inputSize:e,scoreThreshold:t}={}){if(this._name="TinyYolov2Options",this._inputSize=e||416,this._scoreThreshold=t||.5,typeof this._inputSize!="number"||this._inputSize%32!==0)throw new Error(`${this._name} - expected inputSize to be a number divisible by 32`);if(typeof this._scoreThreshold!="number"||this._scoreThreshold<=0||this._scoreThreshold>=1)throw new Error(`${this._name} - expected scoreThreshold to be a number between 0 and 1`)}get inputSize(){return this._inputSize}get scoreThreshold(){return this._scoreThreshold}},vA=class wA extends Bs{constructor(t){super("TinyYolov2"),zme(t),this._config=t}get config(){return this._config}get withClassScores(){return this.config.withClassScores||this.config.classes.length>1}get boxEncodingSize(){return 5+(this.withClassScores?this.config.classes.length:0)}runTinyYolov2(t,r){let n=Ha(t,r.conv0);return n=jt(n,[2,2],[2,2],"same"),n=Ha(n,r.conv1),n=jt(n,[2,2],[2,2],"same"),n=Ha(n,r.conv2),n=jt(n,[2,2],[2,2],"same"),n=Ha(n,r.conv3),n=jt(n,[2,2],[2,2],"same"),n=Ha(n,r.conv4),n=jt(n,[2,2],[2,2],"same"),n=Ha(n,r.conv5),n=jt(n,[2,2],[1,1],"same"),n=Ha(n,r.conv6),n=Ha(n,r.conv7),Vp(n,r.conv8,"valid",!1)}runMobilenet(t,r){let n=this.config.isFirstLayerConv2d?Cw(Vp(t,r.conv0,"valid",!1)):ja(t,r.conv0);return n=jt(n,[2,2],[2,2],"same"),n=ja(n,r.conv1),n=jt(n,[2,2],[2,2],"same"),n=ja(n,r.conv2),n=jt(n,[2,2],[2,2],"same"),n=ja(n,r.conv3),n=jt(n,[2,2],[2,2],"same"),n=ja(n,r.conv4),n=jt(n,[2,2],[2,2],"same"),n=ja(n,r.conv5),n=jt(n,[2,2],[1,1],"same"),n=r.conv6?ja(n,r.conv6):n,n=r.conv7?ja(n,r.conv7):n,Vp(n,r.conv8,"valid",!1)}forwardInput(t,r){let{params:n}=this;if(!n)throw new Error("TinyYolov2 - load model before inference");return W(()=>{let a=se(t.toBatchTensor(r,!1),"float32");return a=this.config.meanRgb?ch(a,this.config.meanRgb):a,a=a.div(255),this.config.withSeparableConvs?this.runMobilenet(a,n):this.runTinyYolov2(a,n)})}async forward(t,r){return this.forwardInput(await vr(t),r)}async detect(t,r={}){let{inputSize:n,scoreThreshold:a}=new Ew(r),s=await vr(t),i=await this.forwardInput(s,n),o=W(()=>Tt(i)[0].expandDims()),l={width:s.getInputWidth(0),height:s.getInputHeight(0)},p=await this.extractBoxes(o,s.getReshapedInputDimensions(0),a);i.dispose(),o.dispose();let u=p.map(f=>f.box),d=p.map(f=>f.score),h=p.map(f=>f.classScore),c=p.map(f=>this.config.classes[f.label]);return vfe(u.map(f=>f.rescale(n)),d,this.config.iouThreshold,!0).map(f=>new B$(d[f],h[f],c[f],u[f],l))}getDefaultModelName(){return""}extractParamsFromWeightMap(t){return Ume(t,this.config)}extractParams(t){let r=this.config.filterSizes||wA.DEFAULT_FILTER_SIZES,n=r?r.length:void 0;if(n!==7&&n!==8&&n!==9)throw new Error(`TinyYolov2 - expected 7 | 8 | 9 convolutional filters, but found ${n} filterSizes in config`);return Bme(t,this.config,this.boxEncodingSize,r)}async extractBoxes(t,r,n){let{width:a,height:s}=r,i=Math.max(a,s),o=i/a,l=i/s,p=t.shape[1],u=this.config.anchors.length,[d,h,c]=W(()=>{let y=t.reshape([p,p,u,this.boxEncodingSize]),b=y.slice([0,0,0,0],[p,p,u,4]),x=y.slice([0,0,0,4],[p,p,u,1]),v=this.withClassScores?Ds(y.slice([0,0,0,5],[p,p,u,this.config.classes.length]),3):we(0);return[b,x,v]}),f=[],m=await h.array(),g=await d.array();for(let y=0;y<p;y++)for(let b=0;b<p;b++)for(let x=0;x<u;x++){let v=Km(m[y][b][x][0]);if(!n||v>n){let w=(b+Km(g[y][b][x][0]))/p*o,N=(y+Km(g[y][b][x][1]))/p*l,T=Math.exp(g[y][b][x][2])*this.config.anchors[x].x/p*o,E=Math.exp(g[y][b][x][3])*this.config.anchors[x].y/p*l,$=w-T/2,R=N-E/2,F={row:y,col:b,anchor:x},{classScore:S,label:D}=this.withClassScores?await this.extractPredictedClass(c,F):{classScore:1,label:0};f.push({box:new P$($,R,$+T,R+E),score:v,classScore:v*S,label:D,...F})}}return d.dispose(),h.dispose(),c.dispose(),f}async extractPredictedClass(t,r){let{row:n,col:a,anchor:s}=r,i=await t.array();return Array(this.config.classes.length).fill(0).map((o,l)=>i[n][a][s][l]).map((o,l)=>({classScore:o,label:l})).reduce((o,l)=>o.classScore>l.classScore?o:l)}};vA.DEFAULT_FILTER_SIZES=[3,16,32,64,128,256,512,1024,1024];var kA=vA,Vme=class extends kA{constructor(e=!0){let t={withSeparableConvs:e,iouThreshold:Fme,classes:["face"],...e?{anchors:Dme,meanRgb:Mme}:{anchors:Rme,withClassScores:!0}};super(t)}get withSeparableConvs(){return this.config.withSeparableConvs}get anchors(){return this.config.anchors}async locateFaces(e,t){return(await this.detect(e,t)).map(r=>new Gn(r.score,r.relativeBox,{width:r.imageWidth,height:r.imageHeight}))}getDefaultModelName(){return this.withSeparableConvs?Lme:Ome}extractParamsFromWeightMap(e){return super.extractParamsFromWeightMap(e)}},Gme=class extends Ew{constructor(){super(...arguments),this._name="TinyFaceDetectorOptions"}},fh=class{async then(e){return e(await this.run())}async run(){throw new Error("ComposableTask - run is not implemented")}};async function $w(e,t,r,n,a=({alignedRect:s})=>s){let s=e.map(l=>cA(l)?a(l):l.detection),i=n||(t instanceof ze?await nA(t,s):await rA(t,s)),o=await r(i);return i.forEach(l=>l instanceof ze&&l.dispose()),o}var Hme=.4,jme=[new it(1.603231,2.094468),new it(6.041143,7.080126),new it(2.882459,3.518061),new it(4.266906,5.178857),new it(9.041765,10.66308)],qme=[117.001,114.697,97.404],Kme=class extends kA{constructor(){let e={withSeparableConvs:!0,iouThreshold:Hme,classes:["face"],anchors:jme,meanRgb:qme,isFirstLayerConv2d:!0,filterSizes:[3,16,32,64,128,256,512]};super(e)}get anchors(){return this.config.anchors}async locateFaces(e,t){return(await this.detect(e,t)).map(r=>new Gn(r.score,r.relativeBox,{width:r.imageWidth,height:r.imageHeight}))}getDefaultModelName(){return"tiny_face_detector_model"}extractParamsFromWeightMap(e){return super.extractParamsFromWeightMap(e)}},zn={ssdMobilenetv1:new Ame,tinyFaceDetector:new Kme,tinyYolov2:new Vme,faceLandmark68Net:new rme,faceLandmark68TinyNet:new ime,faceRecognitionNet:new cme,faceExpressionNet:new Pfe,ageGenderNet:new tme},Xme=class extends fh{constructor(e,t,r){super(),this.parentTask=e,this.input=t,this.extractedFaces=r}},Aw=class extends Xme{async run(){let e=await this.parentTask,t=await $w(e,this.input,async r=>Promise.all(r.map(n=>zn.faceExpressionNet.predictExpressions(n))),this.extractedFaces);return e.map((r,n)=>Wfe(r,t[n]))}withAgeAndGender(){return new Rw(this,this.input)}},Fw=class extends Aw{withAgeAndGender(){return new Dw(this,this.input)}withFaceDescriptors(){return new Mw(this,this.input)}},Zme=class extends fh{constructor(e,t,r){super(),this.parentTask=e,this.input=t,this.extractedFaces=r}},Rw=class extends Zme{async run(){let e=await this.parentTask,t=await $w(e,this.input,async r=>Promise.all(r.map(n=>zn.ageGenderNet.predictAgeAndGender(n))),this.extractedFaces);return e.map((r,n)=>{let{age:a,gender:s,genderProbability:i}=t[n];return mme(gme(r,s,i),a)})}withFaceExpressions(){return new Aw(this,this.input)}},Dw=class extends Rw{withFaceExpressions(){return new Fw(this,this.input)}withFaceDescriptors(){return new Mw(this,this.input)}},Jme=class extends fh{constructor(e,t){super(),this.parentTask=e,this.input=t}},Mw=class extends Jme{async run(){let e=await this.parentTask;return(await $w(e,this.input,t=>Promise.all(t.map(r=>zn.faceRecognitionNet.computeFaceDescriptor(r))),null,t=>t.landmarks.align(null,{useDlibAlignment:!0}))).map((t,r)=>fme(e[r],t))}withFaceExpressions(){return new Fw(this,this.input)}withAgeAndGender(){return new Dw(this,this.input)}},Yme=class extends fh{constructor(e,t,r){super(),this.parentTask=e,this.input=t,this.useTinyLandmarkNet=r}get landmarkNet(){return this.useTinyLandmarkNet?zn.faceLandmark68TinyNet:zn.faceLandmark68Net}},Qme=class extends Yme{async run(){let e=await this.parentTask,t=e.map(a=>a.detection),r=this.input instanceof ze?await nA(this.input,t):await rA(this.input,t),n=await Promise.all(r.map(a=>this.landmarkNet.detectLandmarks(a)));return r.forEach(a=>a instanceof ze&&a.dispose()),e.filter((a,s)=>n[s]).map((a,s)=>Gfe(a,n[s]))}withFaceExpressions(){return new Fw(this,this.input)}withAgeAndGender(){return new Dw(this,this.input)}withFaceDescriptors(){return new Mw(this,this.input)}},ege=class extends fh{constructor(e,t=new Im){super(),this.input=e,this.options=t}},tge=class extends ege{async run(){let{input:e,options:t}=this,r;if(t instanceof Gme)r=zn.tinyFaceDetector.locateFaces(e,t);else if(t instanceof Im)r=zn.ssdMobilenetv1.locateFaces(e,t);else if(t instanceof Ew)r=zn.tinyYolov2.locateFaces(e,t);else throw new Error("detectFaces - expected options to be instance of TinyFaceDetectorOptions | SsdMobilenetv1Options | TinyYolov2Options");return r}runAndExtendWithFaceDetections(){return new Promise((e,t)=>{this.run().then(r=>e(r.map(n=>Nfe({},n)))).catch(r=>t(r))})}withFaceLandmarks(e=!1){return new Qme(this.runAndExtendWithFaceDetections(),this.input,e)}withFaceExpressions(){return new Aw(this.runAndExtendWithFaceDetections(),this.input)}withAgeAndGender(){return new Rw(this.runAndExtendWithFaceDetections(),this.input)}};function rge(e,t=new Im){return new tge(e,t)}var nge=Hn('<a target="_blank"><img class="svelte-1lkxzkn"/></a>'),age=Hn('<img class="svelte-1lkxzkn"/>'),sge=Hn('<a target="_blank" class="view-profile-link svelte-1lkxzkn">View Profile</a>'),ige=Hn('<span class="no-profile-link svelte-1lkxzkn">No Profile</span>'),oge=Hn('<div class="cop svelte-1lkxzkn"><div class="cop-face"><!></div> <div class="cop-info svelte-1lkxzkn"><div class="name svelte-1lkxzkn"> </div> <div class="serial svelte-1lkxzkn"> </div> <div class="link svelte-1lkxzkn"><!></div></div></div>');function lge(e,t){my(t,!0);const r="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iODAiIGhlaWdodD0iODAiIHZpZXdCb3g9IjAgMCA4MCA4MCIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHJlY3Qgd2lkdGg9IjgwIiBoZWlnaHQ9IjgwIiBmaWxsPSIjRjNGNEY2Ii8+CjxwYXRoIGQ9Ik0yNCAzMkM0MS42NzMxIDMyIDU2IDM3LjM3MjYgNTYgNDRDNTYgNTAuNjI3NCA0MS42NzMxIDU2IDI0IDU2QzYuMzI2ODggNTYgLTggNTAuNjI3NCAtOCA0Qy04IDM3LjM3MjYgNi4zMjY4OCAzMiAyNCAzMloiIGZpbGw9IiM5QTlCOCIvPgo8L3N2Zz4=";let n=_p(()=>t.cop.name?t.cop.name:t.cop.filename?t.cop.filename.split(".")[0]:t.cop.image?t.cop.image.split(".")[0]:(console.warn(`No name or filename for match ${t.index}:`,t.cop),`Face ${t.index}`)),a=_p(()=>`./images/${t.cop.filename}`),s=_p(()=>{if(t.cop.serial&&t.cop.name){const w=t.cop.name.toLowerCase().replace(/\s+/g,"-");return`https://watchthewatchers.net/lapd/cop/${t.cop.serial}/${w}`}else return null}),i=_p(()=>Ye(n)&&Ye(n).includes(" "));var o=oge(),l=Gr(o),p=Gr(l);{var u=w=>{var N=nge(),T=Gr(N);bl(()=>{Ja(N,"href",Ye(s)),Ja(T,"src",Ye(a)),Ja(T,"alt",Ye(n))}),eg("error",T,()=>At(a,r)),Rn(w,N)},d=w=>{var N=age();bl(()=>{Ja(N,"src",Ye(a)),Ja(N,"alt",Ye(n))}),eg("error",N,()=>At(a,r)),Rn(w,N)};xl(p,w=>{Ye(s)?w(u):w(d,!1)})}var h=Fn(l,2),c=Gr(h),f=Gr(c),m=Fn(c,2),g=Gr(m),y=Fn(m,2),b=Gr(y);{var x=w=>{var N=sge();bl(()=>Ja(N,"href",Ye(s))),Rn(w,N)},v=w=>{var N=ige();Rn(w,N)};xl(b,w=>{Ye(s)&&Ye(i)?w(x):w(v,!1)})}bl(()=>{tg(f,Ye(n)),tg(g,`Serial: ${t.cop.serial||"N/A"}`)}),Rn(e,o),gy()}var uge=Hn('<div class="status svelte-4rj7r7">Loading...</div>'),pge=Hn('<div class="uploaded-face-section svelte-4rj7r7"><div class="cop uploaded-cop svelte-4rj7r7"><div class="cop-face"><img alt="Uploaded face" class="uploaded-face-img svelte-4rj7r7"/></div></div></div>'),dge=Hn('<hr class="results-divider svelte-4rj7r7"/>'),hge=Hn('<div class="cop svelte-4rj7r7"><!></div>'),cge=Hn('<form class="svelte-4rj7r7"><label for="image-input" class="svelte-4rj7r7">Select Photo</label> <input id="image-input" type="file" accept="image/*" hidden=""/></form> <img alt="User uploaded face" class="uploaded-photo svelte-4rj7r7"/> <div class="status svelte-4rj7r7"> </div> <!> <!> <div class="cops svelte-4rj7r7"></div>',1),fge=Hn(`<main class="svelte-4rj7r7"><h1 class="svelte-4rj7r7">LAPD FACE SEARCH</h1> <h2 class="svelte-4rj7r7">Find LAPD cops with face recognition</h2> <p class="svelte-4rj7r7">Search over 9000 headshots of LAPD cops using face recognition.<br class="svelte-4rj7r7"/>Analysis happens on your device and images are not uploaded.<br class="svelte-4rj7r7"/>Blurry,
low-resolution photos will not match.</p> <!> <!></main>`);function mge(e,t){my(t,!0);let r,n,a,s=an(void 0),i=an(!1),o=an(!1),l=an(void 0),p=an(yl([])),u=_p(()=>Ye(i)&&Ye(o));async function d(w){try{const N=await fetch(w);if(!N.ok)throw new Error(`HTTP error! status: ${N.status}`);const T=await N.arrayBuffer(),$=new DataView(T).getUint32(0,!0),R=new Uint8Array(T,4,$),F=new TextDecoder().decode(R),S=JSON.parse(F),D=4+$,P=new Uint8Array(T,D);return{data:new Float32Array(P.buffer,P.byteOffset,P.byteLength/4),shape:S.shape,dtype:S.dtype}}catch(N){throw console.error("Error loading matrix:",N),N}}async function h(){At(s,"Loading...");try{const[w,N,T,E,$]=await Promise.all([zn.ssdMobilenetv1.loadFromUri("./models"),zn.faceLandmark68Net.loadFromUri("./models"),zn.faceRecognitionNet.loadFromUri("./models"),d("analysis/lapd_descriptors.bin"),fetch("analysis/lapd_metadata.json")]);if(!$.ok)throw new Error(`HTTP error! status: ${$.status}`);const R=await $.json();r=E,n=R,At(i,!0),At(o,!0),console.log("Face descriptors shape:",r.shape),console.log("Combined data length:",n.length),console.log("First few combined data entries:",n.slice(0,3)),At(s,"")}catch(w){console.error("Error loading models and database:",w),At(s,"Error loading face API models and database. Please make sure all model files and database files are available.")}}function c(w){const N=new FileReader;N.onload=function(T){At(l,T.target.result,!0)},N.readAsDataURL(w.target.files[0])}async function f(){try{const w=await rge(a).withFaceLandmarks().withFaceDescriptors();if(w.length===0){At(s,"No faces detected in image. Please try a different image with clearly visible faces."),At(p,[],!0);return}const N=w.reduce((X,re)=>{const te=re.detection.box.width*re.detection.box.height,ae=X.detection.box.width*X.detection.box.height;return te>ae?re:X}),T=N.descriptor,E=N.detection.box,$=document.createElement("canvas"),R=$.getContext("2d");$.width=a.naturalWidth,$.height=a.naturalHeight,R.drawImage(a,0,0);const F=document.createElement("canvas"),S=F.getContext("2d"),D=20,P=E.width+D*2,U=E.height+D*2,H=Math.max(0,E.x-D),q=Math.max(0,E.y-D);F.width=P,F.height=U,S.drawImage($,H,q,P,U,0,0,P,U),At(s,"Comparing with database...");const G=[],Z=r.shape[0],ee=r.shape[1];for(let X=0;X<Z;X++){const re=X*ee,te=r.data.slice(re,re+ee),ae=m(T,te);G.push({index:X,distance:ae,data:n[X]})}G.sort((X,re)=>X.distance-re.distance),At(p,G.slice(0,9),!0),F.remove(),$.remove(),At(s,"")}catch(w){console.error("Error in face recognition:",w)}}function m(w,N){let T=0;for(let E=0;E<w.length;E++){const $=w[E]-N[E];T+=$*$}return T}iR(()=>{h()});var g=fge(),y=Fn(Gr(g),6);{var b=w=>{var N=uge();Rn(w,N)};xl(y,w=>{Ye(u)||w(b)})}var x=Fn(y,2);{var v=w=>{var N=cge(),T=vF(N),E=Fn(Gr(T),2);E.__input=c;var $=Fn(T,2);eR($,"",{},{display:"none"}),sR($,q=>a=q,()=>a);var R=Fn($,2),F=Gr(R),S=Fn(R,2);{var D=q=>{var G=pge(),Z=Gr(G),ee=Gr(Z),X=Gr(ee);bl(()=>Ja(X,"src",Ye(l))),Rn(q,G)};xl(S,q=>{Ye(l)&&q(D)})}var P=Fn(S,2);{var U=q=>{var G=dge();Rn(q,G)};xl(P,q=>{Ye(p).length>0&&q(U)})}var H=Fn(P,2);XF(H,21,()=>Ye(p),qF,(q,G)=>{var Z=hge(),ee=Gr(Z);lge(ee,{get cop(){return Ye(G).data},get index(){return Ye(G).index},get distance(){return Ye(G).distance}}),Rn(q,Z)}),bl(()=>{Ja($,"src",Ye(l)),tg(F,Ye(s))}),eg("load",$,f),Rn(w,N)};xl(x,w=>{Ye(u)&&w(v)})}Rn(e,g),gy()}UF(["input"]);GF(mge,{target:document.getElementById("app")});