var Vb=Object.defineProperty;var jb=(e,t,n)=>t in e?Vb(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var j=(e,t,n)=>(jb(e,typeof t!="symbol"?t+"":t,n),n);(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))r(i);new MutationObserver(i=>{for(const a of i)if(a.type==="childList")for(const s of a.addedNodes)s.tagName==="LINK"&&s.rel==="modulepreload"&&r(s)}).observe(document,{childList:!0,subtree:!0});function n(i){const a={};return i.integrity&&(a.integrity=i.integrity),i.referrerPolicy&&(a.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?a.credentials="include":i.crossOrigin==="anonymous"?a.credentials="omit":a.credentials="same-origin",a}function r(i){if(i.ep)return;i.ep=!0;const a=n(i);fetch(i.href,a)}})();function Gb(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Oy={exports:{}},au={},My={exports:{}},Ae={};/** * @license React * react.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */var Us=Symbol.for("react.element"),Hb=Symbol.for("react.portal"),qb=Symbol.for("react.fragment"),Kb=Symbol.for("react.strict_mode"),Yb=Symbol.for("react.profiler"),Qb=Symbol.for("react.provider"),Xb=Symbol.for("react.context"),Zb=Symbol.for("react.forward_ref"),Jb=Symbol.for("react.suspense"),ex=Symbol.for("react.memo"),tx=Symbol.for("react.lazy"),ih=Symbol.iterator;function nx(e){return e===null||typeof e!="object"?null:(e=ih&&e[ih]||e["@@iterator"],typeof e=="function"?e:null)}var zy={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},Ry=Object.assign,Py={};function pa(e,t,n){this.props=e,this.context=t,this.refs=Py,this.updater=n||zy}pa.prototype.isReactComponent={};pa.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")};pa.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function By(){}By.prototype=pa.prototype;function rp(e,t,n){this.props=e,this.context=t,this.refs=Py,this.updater=n||zy}var ip=rp.prototype=new By;ip.constructor=rp;Ry(ip,pa.prototype);ip.isPureReactComponent=!0;var ah=Array.isArray,Dy=Object.prototype.hasOwnProperty,ap={current:null},Ny={key:!0,ref:!0,__self:!0,__source:!0};function Ly(e,t,n){var r,i={},a=null,s=null;if(t!=null)for(r in t.ref!==void 0&&(s=t.ref),t.key!==void 0&&(a=""+t.key),t)Dy.call(t,r)&&!Ny.hasOwnProperty(r)&&(i[r]=t[r]);var o=arguments.length-2;if(o===1)i.children=n;else if(1>>1,ie=L[V];if(0>>1;Vi(He,Z))qei(Dt,He)?(L[V]=Dt,L[qe]=Z,V=qe):(L[V]=He,L[Re]=Z,V=Re);else if(qei(Dt,Z))L[V]=Dt,L[qe]=Z,V=qe;else break e}}return X}function i(L,X){var Z=L.sortIndex-X.sortIndex;return Z!==0?Z:L.id-X.id}if(typeof performance=="object"&&typeof performance.now=="function"){var a=performance;e.unstable_now=function(){return a.now()}}else{var s=Date,o=s.now();e.unstable_now=function(){return s.now()-o}}var l=[],d=[],c=1,u=null,f=3,h=!1,g=!1,$=!1,E=typeof setTimeout=="function"?setTimeout:null,y=typeof clearTimeout=="function"?clearTimeout:null,_=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function v(L){for(var X=n(d);X!==null;){if(X.callback===null)r(d);else if(X.startTime<=L)r(d),X.sortIndex=X.expirationTime,t(l,X);else break;X=n(d)}}function b(L){if($=!1,v(L),!g)if(n(l)!==null)g=!0,H(C);else{var X=n(d);X!==null&&re(b,X.startTime-L)}}function C(L,X){g=!1,$&&($=!1,y(M),M=-1),h=!0;var Z=f;try{for(v(X),u=n(l);u!==null&&(!(u.expirationTime>X)||L&&!z());){var V=u.callback;if(typeof V=="function"){u.callback=null,f=u.priorityLevel;var ie=V(u.expirationTime<=X);X=e.unstable_now(),typeof ie=="function"?u.callback=ie:u===n(l)&&r(l),v(X)}else r(l);u=n(l)}if(u!==null)var xe=!0;else{var Re=n(d);Re!==null&&re(b,Re.startTime-X),xe=!1}return xe}finally{u=null,f=Z,h=!1}}var I=!1,O=null,M=-1,W=5,G=-1;function z(){return!(e.unstable_now()-GL||125V?(L.sortIndex=Z,t(d,L),n(l)===null&&L===n(d)&&($?(y(M),M=-1):$=!0,re(b,Z-V))):(L.sortIndex=ie,t(l,L),g||h||(g=!0,H(C))),L},e.unstable_shouldYield=z,e.unstable_wrapCallback=function(L){var X=f;return function(){var Z=f;f=X;try{return L.apply(this,arguments)}finally{f=Z}}}})(Vy);Wy.exports=Vy;var hx=Wy.exports;/** * @license React * react-dom.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */var jy=Ot,an=hx;function Q(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),Hd=Object.prototype.hasOwnProperty,mx=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,oh={},lh={};function gx(e){return Hd.call(lh,e)?!0:Hd.call(oh,e)?!1:mx.test(e)?lh[e]=!0:(oh[e]=!0,!1)}function yx(e,t,n,r){if(n!==null&&n.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return r?!1:n!==null?!n.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function wx(e,t,n,r){if(t===null||typeof t>"u"||yx(e,t,n,r))return!0;if(r)return!1;if(n!==null)switch(n.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function Wt(e,t,n,r,i,a,s){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=i,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=a,this.removeEmptyString=s}var Tt={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){Tt[e]=new Wt(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];Tt[t]=new Wt(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){Tt[e]=new Wt(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){Tt[e]=new Wt(e,2,!1,e,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(e){Tt[e]=new Wt(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){Tt[e]=new Wt(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){Tt[e]=new Wt(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){Tt[e]=new Wt(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){Tt[e]=new Wt(e,5,!1,e.toLowerCase(),null,!1,!1)});var op=/[\-:]([a-z])/g;function lp(e){return e[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e){var t=e.replace(op,lp);Tt[t]=new Wt(t,1,!1,e,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(op,lp);Tt[t]=new Wt(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(op,lp);Tt[t]=new Wt(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){Tt[e]=new Wt(e,1,!1,e.toLowerCase(),null,!1,!1)});Tt.xlinkHref=new Wt("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){Tt[e]=new Wt(e,1,!1,e.toLowerCase(),null,!0,!0)});function up(e,t,n,r){var i=Tt.hasOwnProperty(t)?Tt[t]:null;(i!==null?i.type!==0:r||!(2o||i[s]!==a[o]){var l=` `+i[s].replace(" at new "," at ");return e.displayName&&l.includes("")&&(l=l.replace("",e.displayName)),l}while(1<=s&&0<=o);break}}}finally{Vu=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?ts(e):""}function _x(e){switch(e.tag){case 5:return ts(e.type);case 16:return ts("Lazy");case 13:return ts("Suspense");case 19:return ts("SuspenseList");case 0:case 2:case 15:return e=ju(e.type,!1),e;case 11:return e=ju(e.type.render,!1),e;case 1:return e=ju(e.type,!0),e;default:return""}}function Qd(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case Ni:return"Fragment";case Di:return"Portal";case qd:return"Profiler";case dp:return"StrictMode";case Kd:return"Suspense";case Yd:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case qy:return(e.displayName||"Context")+".Consumer";case Hy:return(e._context.displayName||"Context")+".Provider";case cp:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case pp:return t=e.displayName||null,t!==null?t:Qd(e.type)||"Memo";case Tr:t=e._payload,e=e._init;try{return Qd(e(t))}catch{}}return null}function vx(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return Qd(t);case 8:return t===dp?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function Vr(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function Yy(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function $x(e){var t=Yy(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=""+e[t];if(!e.hasOwnProperty(t)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var i=n.get,a=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return i.call(this)},set:function(s){r=""+s,a.call(this,s)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(s){r=""+s},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function To(e){e._valueTracker||(e._valueTracker=$x(e))}function Qy(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=Yy(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function vl(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function Xd(e,t){var n=t.checked;return it({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function dh(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=Vr(t.value!=null?t.value:n),e._wrapperState={initialChecked:r,initialValue:n,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function Xy(e,t){t=t.checked,t!=null&&up(e,"checked",t,!1)}function Zd(e,t){Xy(e,t);var n=Vr(t.value),r=t.type;if(n!=null)r==="number"?(n===0&&e.value===""||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if(r==="submit"||r==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?Jd(e,t.type,n):t.hasOwnProperty("defaultValue")&&Jd(e,t.type,Vr(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function ch(e,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var r=t.type;if(!(r!=="submit"&&r!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}n=e.name,n!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,n!==""&&(e.name=n)}function Jd(e,t,n){(t!=="number"||vl(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var ns=Array.isArray;function Yi(e,t,n,r){if(e=e.options,t){t={};for(var i=0;i"+t.valueOf().toString()+"",t=Io.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function $s(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var ss={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},bx=["Webkit","ms","Moz","O"];Object.keys(ss).forEach(function(e){bx.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),ss[t]=ss[e]})});function tw(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||ss.hasOwnProperty(e)&&ss[e]?(""+t).trim():t+"px"}function nw(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,i=tw(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,i):e[n]=i}}var xx=it({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function nc(e,t){if(t){if(xx[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(Q(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(Q(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(Q(61))}if(t.style!=null&&typeof t.style!="object")throw Error(Q(62))}}function rc(e,t){if(e.indexOf("-")===-1)return typeof t.is=="string";switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var ic=null;function fp(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var ac=null,Qi=null,Xi=null;function hh(e){if(e=js(e)){if(typeof ac!="function")throw Error(Q(280));var t=e.stateNode;t&&(t=du(t),ac(e.stateNode,e.type,t))}}function rw(e){Qi?Xi?Xi.push(e):Xi=[e]:Qi=e}function iw(){if(Qi){var e=Qi,t=Xi;if(Xi=Qi=null,hh(e),t)for(e=0;e>>=0,e===0?32:31-(Rx(e)/Px|0)|0}var Ao=64,Oo=4194304;function rs(e){switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function Sl(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,i=e.suspendedLanes,a=e.pingedLanes,s=n&268435455;if(s!==0){var o=s&~i;o!==0?r=rs(o):(a&=s,a!==0&&(r=rs(a)))}else s=n&~i,s!==0?r=rs(s):a!==0&&(r=rs(a));if(r===0)return 0;if(t!==0&&t!==r&&!(t&i)&&(i=r&-r,a=t&-t,i>=a||i===16&&(a&4194240)!==0))return t;if(r&4&&(r|=n&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=r;0n;n++)t.push(e);return t}function Ws(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-Pn(t),e[t]=n}function Lx(e,t){var n=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0=ls),xh=" ",Sh=!1;function Sw(e,t){switch(e){case"keyup":return f3.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Ew(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var Li=!1;function m3(e,t){switch(e){case"compositionend":return Ew(t);case"keypress":return t.which!==32?null:(Sh=!0,xh);case"textInput":return e=t.data,e===xh&&Sh?null:e;default:return null}}function g3(e,t){if(Li)return e==="compositionend"||!$p&&Sw(e,t)?(e=bw(),sl=wp=Mr=null,Li=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=Th(n)}}function Iw(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?Iw(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function Aw(){for(var e=window,t=vl();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=vl(e.document)}return t}function bp(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}function E3(e){var t=Aw(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&Iw(n.ownerDocument.documentElement,n)){if(r!==null&&bp(n)){if(t=r.start,e=r.end,e===void 0&&(e=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(e,n.value.length);else if(e=(t=n.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var i=n.textContent.length,a=Math.min(r.start,i);r=r.end===void 0?a:Math.min(r.end,i),!e.extend&&a>r&&(i=r,r=a,a=i),i=Ih(n,a);var s=Ih(n,r);i&&s&&(e.rangeCount!==1||e.anchorNode!==i.node||e.anchorOffset!==i.offset||e.focusNode!==s.node||e.focusOffset!==s.offset)&&(t=t.createRange(),t.setStart(i.node,i.offset),e.removeAllRanges(),a>r?(e.addRange(t),e.extend(s.node,s.offset)):(t.setEnd(s.node,s.offset),e.addRange(t)))}}for(t=[],e=n;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n=document.documentMode,Fi=null,cc=null,ds=null,pc=!1;function Ah(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;pc||Fi==null||Fi!==vl(r)||(r=Fi,"selectionStart"in r&&bp(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),ds&&Cs(ds,r)||(ds=r,r=Cl(cc,"onSelect"),0Vi||(e.current=wc[Vi],wc[Vi]=null,Vi--)}function Ye(e,t){Vi++,wc[Vi]=e.current,e.current=t}var jr={},Rt=Kr(jr),qt=Kr(!1),mi=jr;function aa(e,t){var n=e.type.contextTypes;if(!n)return jr;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var i={},a;for(a in n)i[a]=t[a];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=i),i}function Kt(e){return e=e.childContextTypes,e!=null}function Il(){Ze(qt),Ze(Rt)}function Dh(e,t,n){if(Rt.current!==jr)throw Error(Q(168));Ye(Rt,t),Ye(qt,n)}function Lw(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var i in r)if(!(i in t))throw Error(Q(108,vx(e)||"Unknown",i));return it({},n,r)}function Al(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||jr,mi=Rt.current,Ye(Rt,e),Ye(qt,qt.current),!0}function Nh(e,t,n){var r=e.stateNode;if(!r)throw Error(Q(169));n?(e=Lw(e,t,mi),r.__reactInternalMemoizedMergedChildContext=e,Ze(qt),Ze(Rt),Ye(Rt,e)):Ze(qt),Ye(qt,n)}var sr=null,cu=!1,id=!1;function Fw(e){sr===null?sr=[e]:sr.push(e)}function D3(e){cu=!0,Fw(e)}function Yr(){if(!id&&sr!==null){id=!0;var e=0,t=Ge;try{var n=sr;for(Ge=1;e>=s,i-=s,or=1<<32-Pn(t)+i|n<M?(W=O,O=null):W=O.sibling;var G=f(y,O,v[M],b);if(G===null){O===null&&(O=W);break}e&&O&&G.alternate===null&&t(y,O),_=a(G,_,M),I===null?C=G:I.sibling=G,I=G,O=W}if(M===v.length)return n(y,O),et&&ai(y,M),C;if(O===null){for(;MM?(W=O,O=null):W=O.sibling;var z=f(y,O,G.value,b);if(z===null){O===null&&(O=W);break}e&&O&&z.alternate===null&&t(y,O),_=a(z,_,M),I===null?C=z:I.sibling=z,I=z,O=W}if(G.done)return n(y,O),et&&ai(y,M),C;if(O===null){for(;!G.done;M++,G=v.next())G=u(y,G.value,b),G!==null&&(_=a(G,_,M),I===null?C=G:I.sibling=G,I=G);return et&&ai(y,M),C}for(O=r(y,O);!G.done;M++,G=v.next())G=h(O,y,M,G.value,b),G!==null&&(e&&G.alternate!==null&&O.delete(G.key===null?M:G.key),_=a(G,_,M),I===null?C=G:I.sibling=G,I=G);return e&&O.forEach(function(K){return t(y,K)}),et&&ai(y,M),C}function E(y,_,v,b){if(typeof v=="object"&&v!==null&&v.type===Ni&&v.key===null&&(v=v.props.children),typeof v=="object"&&v!==null){switch(v.$$typeof){case Co:e:{for(var C=v.key,I=_;I!==null;){if(I.key===C){if(C=v.type,C===Ni){if(I.tag===7){n(y,I.sibling),_=i(I,v.props.children),_.return=y,y=_;break e}}else if(I.elementType===C||typeof C=="object"&&C!==null&&C.$$typeof===Tr&&Gh(C)===I.type){n(y,I.sibling),_=i(I,v.props),_.ref=Ua(y,I,v),_.return=y,y=_;break e}n(y,I);break}else t(y,I);I=I.sibling}v.type===Ni?(_=pi(v.props.children,y.mode,b,v.key),_.return=y,y=_):(b=hl(v.type,v.key,v.props,null,y.mode,b),b.ref=Ua(y,_,v),b.return=y,y=b)}return s(y);case Di:e:{for(I=v.key;_!==null;){if(_.key===I)if(_.tag===4&&_.stateNode.containerInfo===v.containerInfo&&_.stateNode.implementation===v.implementation){n(y,_.sibling),_=i(_,v.children||[]),_.return=y,y=_;break e}else{n(y,_);break}else t(y,_);_=_.sibling}_=pd(v,y.mode,b),_.return=y,y=_}return s(y);case Tr:return I=v._init,E(y,_,I(v._payload),b)}if(ns(v))return g(y,_,v,b);if(Ba(v))return $(y,_,v,b);No(y,v)}return typeof v=="string"&&v!==""||typeof v=="number"?(v=""+v,_!==null&&_.tag===6?(n(y,_.sibling),_=i(_,v),_.return=y,y=_):(n(y,_),_=cd(v,y.mode,b),_.return=y,y=_),s(y)):n(y,_)}return E}var oa=Kw(!0),Yw=Kw(!1),Gs={},Xn=Kr(Gs),Os=Kr(Gs),Ms=Kr(Gs);function ui(e){if(e===Gs)throw Error(Q(174));return e}function Op(e,t){switch(Ye(Ms,t),Ye(Os,e),Ye(Xn,Gs),e=t.nodeType,e){case 9:case 11:t=(t=t.documentElement)?t.namespaceURI:tc(null,"");break;default:e=e===8?t.parentNode:t,t=e.namespaceURI||null,e=e.tagName,t=tc(t,e)}Ze(Xn),Ye(Xn,t)}function la(){Ze(Xn),Ze(Os),Ze(Ms)}function Qw(e){ui(Ms.current);var t=ui(Xn.current),n=tc(t,e.type);t!==n&&(Ye(Os,e),Ye(Xn,n))}function Mp(e){Os.current===e&&(Ze(Xn),Ze(Os))}var nt=Kr(0);function Bl(e){for(var t=e;t!==null;){if(t.tag===13){var n=t.memoizedState;if(n!==null&&(n=n.dehydrated,n===null||n.data==="$?"||n.data==="$!"))return t}else if(t.tag===19&&t.memoizedProps.revealOrder!==void 0){if(t.flags&128)return t}else if(t.child!==null){t.child.return=t,t=t.child;continue}if(t===e)break;for(;t.sibling===null;){if(t.return===null||t.return===e)return null;t=t.return}t.sibling.return=t.return,t=t.sibling}return null}var ad=[];function zp(){for(var e=0;en?n:4,e(!0);var r=sd.transition;sd.transition={};try{e(!1),t()}finally{Ge=n,sd.transition=r}}function p_(){return yn().memoizedState}function U3(e,t,n){var r=Ur(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},f_(e))h_(t,n);else if(n=jw(e,t,n,r),n!==null){var i=Ft();Bn(n,e,r,i),m_(n,t,r)}}function W3(e,t,n){var r=Ur(e),i={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(f_(e))h_(t,i);else{var a=e.alternate;if(e.lanes===0&&(a===null||a.lanes===0)&&(a=t.lastRenderedReducer,a!==null))try{var s=t.lastRenderedState,o=a(s,n);if(i.hasEagerState=!0,i.eagerState=o,Dn(o,s)){var l=t.interleaved;l===null?(i.next=i,Ip(t)):(i.next=l.next,l.next=i),t.interleaved=i;return}}catch{}finally{}n=jw(e,t,i,r),n!==null&&(i=Ft(),Bn(n,e,r,i),m_(n,t,r))}}function f_(e){var t=e.alternate;return e===rt||t!==null&&t===rt}function h_(e,t){cs=Dl=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function m_(e,t,n){if(n&4194240){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,mp(e,n)}}var Nl={readContext:gn,useCallback:It,useContext:It,useEffect:It,useImperativeHandle:It,useInsertionEffect:It,useLayoutEffect:It,useMemo:It,useReducer:It,useRef:It,useState:It,useDebugValue:It,useDeferredValue:It,useTransition:It,useMutableSource:It,useSyncExternalStore:It,useId:It,unstable_isNewReconciler:!1},V3={readContext:gn,useCallback:function(e,t){return Hn().memoizedState=[e,t===void 0?null:t],e},useContext:gn,useEffect:qh,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,dl(4194308,4,o_.bind(null,t,e),n)},useLayoutEffect:function(e,t){return dl(4194308,4,e,t)},useInsertionEffect:function(e,t){return dl(4,2,e,t)},useMemo:function(e,t){var n=Hn();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=Hn();return t=n!==void 0?n(t):t,r.memoizedState=r.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},r.queue=e,e=e.dispatch=U3.bind(null,rt,e),[r.memoizedState,e]},useRef:function(e){var t=Hn();return e={current:e},t.memoizedState=e},useState:Hh,useDebugValue:Np,useDeferredValue:function(e){return Hn().memoizedState=e},useTransition:function(){var e=Hh(!1),t=e[0];return e=F3.bind(null,e[1]),Hn().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=rt,i=Hn();if(et){if(n===void 0)throw Error(Q(407));n=n()}else{if(n=t(),bt===null)throw Error(Q(349));yi&30||Jw(r,t,n)}i.memoizedState=n;var a={value:n,getSnapshot:t};return i.queue=a,qh(t_.bind(null,r,a,e),[e]),r.flags|=2048,Ps(9,e_.bind(null,r,a,n,t),void 0,null),n},useId:function(){var e=Hn(),t=bt.identifierPrefix;if(et){var n=lr,r=or;n=(r&~(1<<32-Pn(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=zs++,0<\/script>",e=e.removeChild(e.firstChild)):typeof r.is=="string"?e=s.createElement(n,{is:r.is}):(e=s.createElement(n),n==="select"&&(s=e,r.multiple?s.multiple=!0:r.size&&(s.size=r.size))):e=s.createElementNS(e,n),e[qn]=t,e[As]=r,S_(e,t,!1,!1),t.stateNode=e;e:{switch(s=rc(n,r),n){case"dialog":Qe("cancel",e),Qe("close",e),i=r;break;case"iframe":case"object":case"embed":Qe("load",e),i=r;break;case"video":case"audio":for(i=0;ida&&(t.flags|=128,r=!0,Wa(a,!1),t.lanes=4194304)}else{if(!r)if(e=Bl(s),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),Wa(a,!0),a.tail===null&&a.tailMode==="hidden"&&!s.alternate&&!et)return At(t),null}else 2*ct()-a.renderingStartTime>da&&n!==1073741824&&(t.flags|=128,r=!0,Wa(a,!1),t.lanes=4194304);a.isBackwards?(s.sibling=t.child,t.child=s):(n=a.last,n!==null?n.sibling=s:t.child=s,a.last=s)}return a.tail!==null?(t=a.tail,a.rendering=t,a.tail=t.sibling,a.renderingStartTime=ct(),t.sibling=null,n=nt.current,Ye(nt,r?n&1|2:n&1),t):(At(t),null);case 22:case 23:return jp(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?Jt&1073741824&&(At(t),t.subtreeFlags&6&&(t.flags|=8192)):At(t),null;case 24:return null;case 25:return null}throw Error(Q(156,t.tag))}function X3(e,t){switch(Sp(t),t.tag){case 1:return Kt(t.type)&&Il(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return la(),Ze(qt),Ze(Rt),zp(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return Mp(t),null;case 13:if(Ze(nt),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(Q(340));sa()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return Ze(nt),null;case 4:return la(),null;case 10:return Tp(t.type._context),null;case 22:case 23:return jp(),null;case 24:return null;default:return null}}var Fo=!1,zt=!1,Z3=typeof WeakSet=="function"?WeakSet:Set,oe=null;function qi(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){ot(e,t,r)}else n.current=null}function Ac(e,t,n){try{n()}catch(r){ot(e,t,r)}}var nm=!1;function J3(e,t){if(fc=El,e=Aw(),bp(e)){if("selectionStart"in e)var n={start:e.selectionStart,end:e.selectionEnd};else e:{n=(n=e.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var i=r.anchorOffset,a=r.focusNode;r=r.focusOffset;try{n.nodeType,a.nodeType}catch{n=null;break e}var s=0,o=-1,l=-1,d=0,c=0,u=e,f=null;t:for(;;){for(var h;u!==n||i!==0&&u.nodeType!==3||(o=s+i),u!==a||r!==0&&u.nodeType!==3||(l=s+r),u.nodeType===3&&(s+=u.nodeValue.length),(h=u.firstChild)!==null;)f=u,u=h;for(;;){if(u===e)break t;if(f===n&&++d===i&&(o=s),f===a&&++c===r&&(l=s),(h=u.nextSibling)!==null)break;u=f,f=u.parentNode}u=h}n=o===-1||l===-1?null:{start:o,end:l}}else n=null}n=n||{start:0,end:0}}else n=null;for(hc={focusedElem:e,selectionRange:n},El=!1,oe=t;oe!==null;)if(t=oe,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,oe=e;else for(;oe!==null;){t=oe;try{var g=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(g!==null){var $=g.memoizedProps,E=g.memoizedState,y=t.stateNode,_=y.getSnapshotBeforeUpdate(t.elementType===t.type?$:Tn(t.type,$),E);y.__reactInternalSnapshotBeforeUpdate=_}break;case 3:var v=t.stateNode.containerInfo;v.nodeType===1?v.textContent="":v.nodeType===9&&v.documentElement&&v.removeChild(v.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(Q(163))}}catch(b){ot(t,t.return,b)}if(e=t.sibling,e!==null){e.return=t.return,oe=e;break}oe=t.return}return g=nm,nm=!1,g}function ps(e,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var i=r=r.next;do{if((i.tag&e)===e){var a=i.destroy;i.destroy=void 0,a!==void 0&&Ac(t,n,a)}i=i.next}while(i!==r)}}function hu(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var n=t=t.next;do{if((n.tag&e)===e){var r=n.create;n.destroy=r()}n=n.next}while(n!==t)}}function Oc(e){var t=e.ref;if(t!==null){var n=e.stateNode;switch(e.tag){case 5:e=n;break;default:e=n}typeof t=="function"?t(e):t.current=e}}function C_(e){var t=e.alternate;t!==null&&(e.alternate=null,C_(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[qn],delete t[As],delete t[yc],delete t[P3],delete t[B3])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function T_(e){return e.tag===5||e.tag===3||e.tag===4}function rm(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||T_(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function Mc(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(e,t):n.insertBefore(e,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(e,n)):(t=n,t.appendChild(e)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=Tl));else if(r!==4&&(e=e.child,e!==null))for(Mc(e,t,n),e=e.sibling;e!==null;)Mc(e,t,n),e=e.sibling}function zc(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(zc(e,t,n),e=e.sibling;e!==null;)zc(e,t,n),e=e.sibling}var Et=null,An=!1;function Sr(e,t,n){for(n=n.child;n!==null;)I_(e,t,n),n=n.sibling}function I_(e,t,n){if(Qn&&typeof Qn.onCommitFiberUnmount=="function")try{Qn.onCommitFiberUnmount(su,n)}catch{}switch(n.tag){case 5:zt||qi(n,t);case 6:var r=Et,i=An;Et=null,Sr(e,t,n),Et=r,An=i,Et!==null&&(An?(e=Et,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):Et.removeChild(n.stateNode));break;case 18:Et!==null&&(An?(e=Et,n=n.stateNode,e.nodeType===8?rd(e.parentNode,n):e.nodeType===1&&rd(e,n),Es(e)):rd(Et,n.stateNode));break;case 4:r=Et,i=An,Et=n.stateNode.containerInfo,An=!0,Sr(e,t,n),Et=r,An=i;break;case 0:case 11:case 14:case 15:if(!zt&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){i=r=r.next;do{var a=i,s=a.destroy;a=a.tag,s!==void 0&&(a&2||a&4)&&Ac(n,t,s),i=i.next}while(i!==r)}Sr(e,t,n);break;case 1:if(!zt&&(qi(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(o){ot(n,t,o)}Sr(e,t,n);break;case 21:Sr(e,t,n);break;case 22:n.mode&1?(zt=(r=zt)||n.memoizedState!==null,Sr(e,t,n),zt=r):Sr(e,t,n);break;default:Sr(e,t,n)}}function im(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new Z3),t.forEach(function(r){var i=lS.bind(null,e,r);n.has(r)||(n.add(r),r.then(i,i))})}}function $n(e,t){var n=t.deletions;if(n!==null)for(var r=0;ri&&(i=s),r&=~a}if(r=i,r=ct()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*tS(r/1960))-r,10e?16:e,zr===null)var r=!1;else{if(e=zr,zr=null,Ul=0,Ne&6)throw Error(Q(331));var i=Ne;for(Ne|=4,oe=e.current;oe!==null;){var a=oe,s=a.child;if(oe.flags&16){var o=a.deletions;if(o!==null){for(var l=0;lct()-Wp?ci(e,0):Up|=n),Yt(e,t)}function D_(e,t){t===0&&(e.mode&1?(t=Oo,Oo<<=1,!(Oo&130023424)&&(Oo=4194304)):t=1);var n=Ft();e=mr(e,t),e!==null&&(Ws(e,t,n),Yt(e,n))}function oS(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),D_(e,n)}function lS(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,i=e.memoizedState;i!==null&&(n=i.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(Q(314))}r!==null&&r.delete(t),D_(e,n)}var N_;N_=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||qt.current)Ht=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return Ht=!1,Y3(e,t,n);Ht=!!(e.flags&131072)}else Ht=!1,et&&t.flags&1048576&&Uw(t,Ml,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;cl(e,t),e=t.pendingProps;var i=aa(t,Rt.current);Ji(t,n),i=Pp(null,t,r,e,i,n);var a=Bp();return t.flags|=1,typeof i=="object"&&i!==null&&typeof i.render=="function"&&i.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,Kt(r)?(a=!0,Al(t)):a=!1,t.memoizedState=i.state!==null&&i.state!==void 0?i.state:null,Ap(t),i.updater=pu,t.stateNode=i,i._reactInternals=t,xc(t,r,e,n),t=kc(null,t,r,!0,a,n)):(t.tag=0,et&&a&&xp(t),Nt(null,t,i,n),t=t.child),t;case 16:r=t.elementType;e:{switch(cl(e,t),e=t.pendingProps,i=r._init,r=i(r._payload),t.type=r,i=t.tag=dS(r),e=Tn(r,e),i){case 0:t=Ec(null,t,r,e,n);break e;case 1:t=Jh(null,t,r,e,n);break e;case 11:t=Xh(null,t,r,e,n);break e;case 14:t=Zh(null,t,r,Tn(r.type,e),n);break e}throw Error(Q(306,r,""))}return t;case 0:return r=t.type,i=t.pendingProps,i=t.elementType===r?i:Tn(r,i),Ec(e,t,r,i,n);case 1:return r=t.type,i=t.pendingProps,i=t.elementType===r?i:Tn(r,i),Jh(e,t,r,i,n);case 3:e:{if($_(t),e===null)throw Error(Q(387));r=t.pendingProps,a=t.memoizedState,i=a.element,Gw(e,t),Pl(t,r,null,n);var s=t.memoizedState;if(r=s.element,a.isDehydrated)if(a={element:r,isDehydrated:!1,cache:s.cache,pendingSuspenseBoundaries:s.pendingSuspenseBoundaries,transitions:s.transitions},t.updateQueue.baseState=a,t.memoizedState=a,t.flags&256){i=ua(Error(Q(423)),t),t=em(e,t,r,n,i);break e}else if(r!==i){i=ua(Error(Q(424)),t),t=em(e,t,r,n,i);break e}else for(en=Nr(t.stateNode.containerInfo.firstChild),nn=t,et=!0,Mn=null,n=Yw(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(sa(),r===i){t=gr(e,t,n);break e}Nt(e,t,r,n)}t=t.child}return t;case 5:return Qw(t),e===null&&vc(t),r=t.type,i=t.pendingProps,a=e!==null?e.memoizedProps:null,s=i.children,mc(r,i)?s=null:a!==null&&mc(r,a)&&(t.flags|=32),v_(e,t),Nt(e,t,s,n),t.child;case 6:return e===null&&vc(t),null;case 13:return b_(e,t,n);case 4:return Op(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=oa(t,null,r,n):Nt(e,t,r,n),t.child;case 11:return r=t.type,i=t.pendingProps,i=t.elementType===r?i:Tn(r,i),Xh(e,t,r,i,n);case 7:return Nt(e,t,t.pendingProps,n),t.child;case 8:return Nt(e,t,t.pendingProps.children,n),t.child;case 12:return Nt(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,i=t.pendingProps,a=t.memoizedProps,s=i.value,Ye(zl,r._currentValue),r._currentValue=s,a!==null)if(Dn(a.value,s)){if(a.children===i.children&&!qt.current){t=gr(e,t,n);break e}}else for(a=t.child,a!==null&&(a.return=t);a!==null;){var o=a.dependencies;if(o!==null){s=a.child;for(var l=o.firstContext;l!==null;){if(l.context===r){if(a.tag===1){l=cr(-1,n&-n),l.tag=2;var d=a.updateQueue;if(d!==null){d=d.shared;var c=d.pending;c===null?l.next=l:(l.next=c.next,c.next=l),d.pending=l}}a.lanes|=n,l=a.alternate,l!==null&&(l.lanes|=n),$c(a.return,n,t),o.lanes|=n;break}l=l.next}}else if(a.tag===10)s=a.type===t.type?null:a.child;else if(a.tag===18){if(s=a.return,s===null)throw Error(Q(341));s.lanes|=n,o=s.alternate,o!==null&&(o.lanes|=n),$c(s,n,t),s=a.sibling}else s=a.child;if(s!==null)s.return=a;else for(s=a;s!==null;){if(s===t){s=null;break}if(a=s.sibling,a!==null){a.return=s.return,s=a;break}s=s.return}a=s}Nt(e,t,i.children,n),t=t.child}return t;case 9:return i=t.type,r=t.pendingProps.children,Ji(t,n),i=gn(i),r=r(i),t.flags|=1,Nt(e,t,r,n),t.child;case 14:return r=t.type,i=Tn(r,t.pendingProps),i=Tn(r.type,i),Zh(e,t,r,i,n);case 15:return w_(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,i=t.pendingProps,i=t.elementType===r?i:Tn(r,i),cl(e,t),t.tag=1,Kt(r)?(e=!0,Al(t)):e=!1,Ji(t,n),qw(t,r,i),xc(t,r,i,n),kc(null,t,r,!0,e,n);case 19:return x_(e,t,n);case 22:return __(e,t,n)}throw Error(Q(156,t.tag))};function L_(e,t){return cw(e,t)}function uS(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function hn(e,t,n,r){return new uS(e,t,n,r)}function Hp(e){return e=e.prototype,!(!e||!e.isReactComponent)}function dS(e){if(typeof e=="function")return Hp(e)?1:0;if(e!=null){if(e=e.$$typeof,e===cp)return 11;if(e===pp)return 14}return 2}function Wr(e,t){var n=e.alternate;return n===null?(n=hn(e.tag,t,e.key,e.mode),n.elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=e.flags&14680064,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function hl(e,t,n,r,i,a){var s=2;if(r=e,typeof e=="function")Hp(e)&&(s=1);else if(typeof e=="string")s=5;else e:switch(e){case Ni:return pi(n.children,i,a,t);case dp:s=8,i|=8;break;case qd:return e=hn(12,n,t,i|2),e.elementType=qd,e.lanes=a,e;case Kd:return e=hn(13,n,t,i),e.elementType=Kd,e.lanes=a,e;case Yd:return e=hn(19,n,t,i),e.elementType=Yd,e.lanes=a,e;case Ky:return gu(n,i,a,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case Hy:s=10;break e;case qy:s=9;break e;case cp:s=11;break e;case pp:s=14;break e;case Tr:s=16,r=null;break e}throw Error(Q(130,e==null?e:typeof e,""))}return t=hn(s,n,t,i),t.elementType=e,t.type=r,t.lanes=a,t}function pi(e,t,n,r){return e=hn(7,e,r,t),e.lanes=n,e}function gu(e,t,n,r){return e=hn(22,e,r,t),e.elementType=Ky,e.lanes=n,e.stateNode={isHidden:!1},e}function cd(e,t,n){return e=hn(6,e,null,t),e.lanes=n,e}function pd(e,t,n){return t=hn(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function cS(e,t,n,r,i){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=Hu(0),this.expirationTimes=Hu(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Hu(0),this.identifierPrefix=r,this.onRecoverableError=i,this.mutableSourceEagerHydrationData=null}function qp(e,t,n,r,i,a,s,o,l){return e=new cS(e,t,n,o,l),t===1?(t=1,a===!0&&(t|=8)):t=0,a=hn(3,null,null,t),e.current=a,a.stateNode=e,a.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},Ap(a),e}function pS(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(V_)}catch(e){console.error(e)}}V_(),Uy.exports=ln;var yS=Uy.exports,pm=yS;Gd.createRoot=pm.createRoot,Gd.hydrateRoot=pm.hydrateRoot;const ft={},wS=Object.freeze(Object.defineProperty({__proto__:null,default:ft},Symbol.toStringTag,{value:"Module"})),_S="3.0.0-alpha.0",$u=typeof self<"u",vS=$u&&self.constructor.name==="DedicatedWorkerGlobalScope",j_=$u&&"caches"in self,$S=typeof navigator<"u"&&"gpu"in navigator;var Ay;const bS=typeof process<"u"&&((Ay=process==null?void 0:process.release)==null?void 0:Ay.name)==="node",jl=!q_(ft),G_=!q_(ft),Gl=Object.freeze({IS_BROWSER_ENV:$u,IS_WEBWORKER_ENV:vS,IS_WEB_CACHE_AVAILABLE:j_,IS_WEBGPU_AVAILABLE:$S,IS_NODE_ENV:bS,IS_FS_AVAILABLE:jl,IS_PATH_AVAILABLE:G_}),Xp=jl&&G_,H_=Xp?ft.dirname(ft.dirname(ft.fileURLToPath(import.meta.url))):"./",xS=Xp?ft.join(H_,"/.cache/"):null,fm="/models/",SS=Xp?ft.join(H_,fm):fm,Zt={version:_S,backends:{onnx:{},tfjs:{}},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!$u,localModelPath:SS,useFS:jl,useBrowserCache:j_,useFSCache:jl,cacheDir:xS,useCustomCache:!1,customCache:null};function q_(e){return Object.keys(e).length===0}const dn=class{constructor(){let e=function(...t){return e._call(...t)};return Object.setPrototypeOf(e,new.target.prototype)}_call(...e){throw Error("Must implement _call method in subclass")}};function ja(e,t){e&&e(t)}function ES(e){return Object.fromEntries(Object.entries(e).map(([t,n])=>[n,t]))}function K_(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function kS(e){return Number.isInteger(e)||typeof e=="bigint"}function kt(...e){return Array.prototype.concat.apply([],e)}function ta(e,t){return Object.assign({},...t.map(n=>{if(e[n]!==void 0)return{[n]:e[n]}}))}var rr={};class bu{constructor(t){j(this,"_CONTENT_TYPE_MAP",{txt:"text/plain",html:"text/html",css:"text/css",js:"text/javascript",json:"application/json",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif"});if(this.filePath=t,this.headers=new Headers,this.exists=ft.existsSync(t),this.exists){this.status=200,this.statusText="OK";let n=ft.statSync(t);this.headers.set("content-length",n.size.toString()),this.updateContentType();let r=this;this.body=new ReadableStream({start(i){r.arrayBuffer().then(a=>{i.enqueue(new Uint8Array(a)),i.close()})}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){const t=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",this._CONTENT_TYPE_MAP[t]??"application/octet-stream")}clone(){let t=new bu(this.filePath);return t.exists=this.exists,t.status=this.status,t.statusText=this.statusText,t.headers=new Headers(this.headers),t}async arrayBuffer(){return(await ft.promises.readFile(this.filePath)).buffer}async blob(){const t=await ft.promises.readFile(this.filePath);return new Blob([t],{type:this.headers.get("content-type")})}async text(){return await ft.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}}function Nc(e,t=null){let n;try{n=new URL(e)}catch{return!1}return t&&!t.includes(n.hostname)?!1:n.protocol==="http:"||n.protocol==="https:"}async function hm(e){var t;if(Zt.useFS&&!Nc(e))return new bu(e);if(typeof process<"u"&&((t=process==null?void 0:process.release)==null?void 0:t.name)==="node"){const n=!!(rr!=null&&rr.TESTING_REMOTELY),r=Zt.version,i=new Headers;if(i.set("User-Agent",`transformers.js/${r}; is_ci/${n};`),Nc(e,["huggingface.co","hf.co"])){const s=(rr==null?void 0:rr.HF_TOKEN)??(rr==null?void 0:rr.HF_ACCESS_TOKEN);s&&i.set("Authorization",`Bearer ${s}`)}return fetch(e,{headers:i})}else return fetch(e)}const CS={400:"Bad request error occurred while trying to load file",401:"Unauthorized access to file",403:"Forbidden access to file",404:"Could not locate file",408:"Request timeout error occurred while trying to load file",500:"Internal server error error occurred while trying to load file",502:"Bad gateway error occurred while trying to load file",503:"Service unavailable error occurred while trying to load file",504:"Gateway timeout error occurred while trying to load file"};function TS(e,t,n){if(!n)return null;const r=CS[e]??`Error (${e}) occurred while trying to load file`;throw Error(`${r}: "${t}".`)}class mm{constructor(t){this.path=t}async match(t){let n=ft.join(this.path,t),r=new bu(n);if(r.exists)return r}async put(t,n){const r=Buffer.from(await n.arrayBuffer());let i=ft.join(this.path,t);try{await ft.promises.mkdir(ft.dirname(i),{recursive:!0}),await ft.promises.writeFile(i,r)}catch(a){console.warn("An error occurred while writing the file to cache:",a)}}}async function IS(e,...t){for(let n of t)try{let r=await e.match(n);if(r)return r}catch{continue}}async function Lc(e,t,n=!0,r={}){if(!Zt.allowLocalModels&&r.local_files_only)throw Error("Invalid configuration detected: local models are disabled (`env.allowLocalModels=false`) but you have requested to only use local models (`local_files_only=true`).");ja(r.progress_callback,{status:"initiate",name:e,file:t});let i;if(!i&&Zt.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{i=await caches.open("transformers-cache")}catch(y){console.warn("An error occurred while opening the browser cache:",y)}}if(!i&&Zt.useFSCache&&(i=new mm(r.cache_dir??Zt.cacheDir)),!i&&Zt.useCustomCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");const a=r.revision??"main";let s=Vo(e,t),o=Vo(Zt.localModelPath,s),l=Vo(Zt.remoteHost,Zt.remotePathTemplate.replaceAll("{model}",e).replaceAll("{revision}",encodeURIComponent(a)),t),d=a==="main"?s:Vo(e,a,t),c,u=i instanceof mm?d:l,f=!1,h;i&&(h=await IS(i,o,u));const g=h!==void 0;if(h===void 0){if(Zt.allowLocalModels)if(Nc(s)){if(r.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${s}.`)}else try{h=await hm(o),c=o}catch(_){console.warn(`Unable to load from local path "${o}": "${_}"`)}if(h===void 0||h.status===404){if(r.local_files_only||!Zt.allowRemoteModels){if(n)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${o}".`);return null}if(h=await hm(l),h.status!==200)return TS(h.status,l,n);c=u}f=i&&typeof Response<"u"&&h instanceof Response&&h.status===200}ja(r.progress_callback,{status:"download",name:e,file:t});const $={status:"progress",name:e,file:t};let E;return r.progress_callback?g&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent)?(E=new Uint8Array(await h.arrayBuffer()),ja(r.progress_callback,{...$,progress:100,loaded:E.length,total:E.length})):E=await AS(h,y=>{ja(r.progress_callback,{...$,...y})}):E=new Uint8Array(await h.arrayBuffer()),f&&c&&await i.match(c)===void 0&&await i.put(c,new Response(E,{headers:h.headers})).catch(y=>{console.warn(`Unable to add response to browser cache: ${y}.`)}),ja(r.progress_callback,{status:"done",name:e,file:t}),E}async function di(e,t,n=!0,r={}){let i=await Lc(e,t,n,r);if(i===null)return{};let s=new TextDecoder("utf-8").decode(i);return JSON.parse(s)}async function AS(e,t){const n=e.headers.get("Content-Length");n===null&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let r=parseInt(n??"0"),i=new Uint8Array(r),a=0;const s=e.body.getReader();async function o(){const{done:l,value:d}=await s.read();if(l)return;let c=a+d.length;if(c>r){r=c;let f=new Uint8Array(r);f.set(i),i=f}i.set(d,a),a=c;const u=a/r*100;return t({progress:u,loaded:a,total:r}),o()}return await o(),i}function Vo(...e){return e=e.map((t,n)=>(n&&(t=t.replace(new RegExp("^/"),"")),n!==e.length-1&&(t=t.replace(new RegExp("/$"),"")),t)),e.join("/")}function OS(e,t,n){const r=new Array(n.length),i=new Array(n.length);for(let o=n.length-1,l=1;o>=0;--o)i[o]=l,r[o]=t[n[o]],l*=r[o];const a=n.map((o,l)=>i[n.indexOf(l)]),s=new e.constructor(e.length);for(let o=0;o=0;--d)l+=c%t[d]*a[d],c=Math.floor(c/t[d]);s[l]=e[o]}return[s,r]}function Y_(e){const t=Zp(e)[0],n=e.map(a=>Math.exp(a-t)),r=n.reduce((a,s)=>a+s,0);return n.map(a=>a/r)}function Q_(e,t=0){return e=Array.from(e).map((n,r)=>[r,n]).sort((n,r)=>r[1]-n[1]),t!==null&&t>0&&(e=e.slice(0,t)),e}function MS(e){if(e.length===0)throw Error("Array must not be empty");let t=e[0],n=0;for(let r=1;rt&&(t=e[r],n=r);return[Number(t),n]}function zS(e,t){if(t%2===0||t<=0)throw new Error("Window size must be a positive odd number");const n=new e.constructor(e.length),r=new e.constructor(t),i=Math.floor(t/2);for(let a=0;a=e.length&&(l=2*(e.length-1)-l),r[s++]=e[l]}r.sort(),n[a]=r[i]}return n}function jo(e,t){const n=Math.pow(10,t);return Math.round(e*n)/n}/*! * ONNX Runtime Web v1.17.1 * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */var Jp=Object.defineProperty,RS=Object.getOwnPropertyDescriptor,PS=Object.getOwnPropertyNames,BS=Object.prototype.hasOwnProperty,ee=(e,t)=>()=>(e&&(t=e(e=0)),t),ma=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),ga=(e,t)=>{for(var n in t)Jp(e,n,{get:t[n],enumerable:!0})},DS=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of PS(t))!BS.call(e,i)&&i!==n&&Jp(e,i,{get:()=>t[i],enumerable:!(r=RS(t,i))||r.enumerable});return e},fi=e=>DS(Jp({},"__esModule",{value:!0}),e),Ga,Er,na,ef,tf=ee(()=>{Ga=new Map,Er=[],na=(e,t,n)=>{if(t&&typeof t.init=="function"&&typeof t.createInferenceSessionHandler=="function"){let r=Ga.get(e);if(r===void 0)Ga.set(e,{backend:t,priority:n});else{if(r.priority>n)return;if(r.priority===n&&r.backend!==t)throw new Error(`cannot register backend "${e}" using priority ${n}`)}if(n>=0){let i=Er.indexOf(e);i!==-1&&Er.splice(i,1);for(let a=0;a{let t=e.length===0?Er:e,n=[];for(let r of t){let i=Ga.get(r);if(i){if(i.initialized)return i.backend;if(i.aborted)continue;let a=!!i.initPromise;try{return a||(i.initPromise=i.backend.init(r)),await i.initPromise,i.initialized=!0,i.backend}catch(s){a||n.push({name:r,err:s}),i.aborted=!0}finally{delete i.initPromise}}}throw new Error(`no available backend found. ERR: ${n.map(r=>`[${r.name}] ${r.err}`).join(", ")}`)}}),NS=ee(()=>{tf()}),X_,LS=ee(()=>{X_="1.17.1"}),fd,ra,Z_=ee(()=>{LS(),fd="warning",ra={wasm:{},webgl:{},webgpu:{},versions:{common:X_},set logLevel(e){if(e!==void 0){if(typeof e!="string"||["verbose","info","warning","error","fatal"].indexOf(e)===-1)throw new Error(`Unsupported logging level: ${e}`);fd=e}},get logLevel(){return fd}},Object.defineProperty(ra,"logLevel",{enumerable:!0})}),je,FS=ee(()=>{Z_(),je=ra}),J_,ev,US=ee(()=>{J_=(e,t)=>{let n=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);n.width=e.dims[3],n.height=e.dims[2];let r=n.getContext("2d");if(r!=null){let i,a;(t==null?void 0:t.tensorLayout)!==void 0&&t.tensorLayout==="NHWC"?(i=e.dims[2],a=e.dims[3]):(i=e.dims[3],a=e.dims[2]);let s=(t==null?void 0:t.format)!==void 0?t.format:"RGB",o=t==null?void 0:t.norm,l,d;o===void 0||o.mean===void 0?l=[255,255,255,255]:typeof o.mean=="number"?l=[o.mean,o.mean,o.mean,o.mean]:(l=[o.mean[0],o.mean[1],o.mean[2],0],o.mean[3]!==void 0&&(l[3]=o.mean[3])),o===void 0||o.bias===void 0?d=[0,0,0,0]:typeof o.bias=="number"?d=[o.bias,o.bias,o.bias,o.bias]:(d=[o.bias[0],o.bias[1],o.bias[2],0],o.bias[3]!==void 0&&(d[3]=o.bias[3]));let c=a*i,u=0,f=c,h=c*2,g=-1;s==="RGBA"?(u=0,f=c,h=c*2,g=c*3):s==="RGB"?(u=0,f=c,h=c*2):s==="RBG"&&(u=0,h=c,f=c*2);for(let $=0;${let n=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),r;if(n!=null){let i,a,s;(t==null?void 0:t.tensorLayout)!==void 0&&t.tensorLayout==="NHWC"?(i=e.dims[2],a=e.dims[1],s=e.dims[3]):(i=e.dims[3],a=e.dims[2],s=e.dims[1]);let o=t!==void 0&&t.format!==void 0?t.format:"RGB",l=t==null?void 0:t.norm,d,c;l===void 0||l.mean===void 0?d=[255,255,255,255]:typeof l.mean=="number"?d=[l.mean,l.mean,l.mean,l.mean]:(d=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(d[3]=l.mean[3])),l===void 0||l.bias===void 0?c=[0,0,0,0]:typeof l.bias=="number"?c=[l.bias,l.bias,l.bias,l.bias]:(c=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(c[3]=l.bias[3]));let u=a*i;if(t!==void 0&&(t.format!==void 0&&s===4&&t.format!=="RGBA"||s===3&&t.format!=="RGB"&&t.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let f=4,h=0,g=1,$=2,E=3,y=0,_=u,v=u*2,b=-1;o==="RGBA"?(y=0,_=u,v=u*2,b=u*3):o==="RGB"?(y=0,_=u,v=u*2):o==="RBG"&&(y=0,v=u,_=u*2),r=n.createImageData(i,a);for(let C=0;C{nf(),Go=(e,t)=>{if(e===void 0)throw new Error("Image buffer must be defined");if(t.height===void 0||t.width===void 0)throw new Error("Image height and width must be defined");if(t.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:n,width:r}=t,i=t.norm??{mean:255,bias:0},a,s;typeof i.mean=="number"?a=[i.mean,i.mean,i.mean,i.mean]:a=[i.mean[0],i.mean[1],i.mean[2],i.mean[3]??255],typeof i.bias=="number"?s=[i.bias,i.bias,i.bias,i.bias]:s=[i.bias[0],i.bias[1],i.bias[2],i.bias[3]??0];let o=t.format!==void 0?t.format:"RGBA",l=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:"RGB",d=n*r,c=l==="RGBA"?new Float32Array(d*4):new Float32Array(d*3),u=4,f=0,h=1,g=2,$=3,E=0,y=d,_=d*2,v=-1;o==="RGB"&&(u=3,f=0,h=1,g=2,$=-1),l==="RGBA"?v=d*3:l==="RBG"?(E=0,_=d,y=d*2):l==="BGR"&&(_=0,y=d,E=d*2);for(let b=0;b{let n=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,r=typeof ImageData<"u"&&e instanceof ImageData,i=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,a=typeof e=="string",s,o=t??{},l=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},d=c=>c instanceof HTMLCanvasElement||c instanceof OffscreenCanvas?c.getContext("2d"):null;if(n){let c=l();c.width=e.width,c.height=e.height;let u=d(c);if(u!=null){let f=e.height,h=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(f=t.resizedHeight,h=t.resizedWidth),t!==void 0){if(o=t,t.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");o.tensorFormat="RGBA",o.height=f,o.width=h}else o.tensorFormat="RGBA",o.height=f,o.width=h;u.drawImage(e,0,0),s=u.getImageData(0,0,h,f).data}else throw new Error("Can not access image data")}else if(r){let c,u;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(c=t.resizedHeight,u=t.resizedWidth):(c=e.height,u=e.width),t!==void 0&&(o=t),o.format="RGBA",o.height=c,o.width=u,t!==void 0){let f=l();f.width=u,f.height=c;let h=d(f);if(h!=null)h.putImageData(e,0,0),s=h.getImageData(0,0,u,c).data;else throw new Error("Can not access image data")}else s=e.data}else if(i){if(t===void 0)throw new Error("Please provide image config with format for Imagebitmap");let c=l();c.width=e.width,c.height=e.height;let u=d(c);if(u!=null){let f=e.height,h=e.width;return u.drawImage(e,0,0,h,f),s=u.getImageData(0,0,h,f).data,o.height=f,o.width=h,Go(s,o)}else throw new Error("Can not access image data")}else{if(a)return new Promise((c,u)=>{let f=l(),h=d(f);if(!e||!h)return u();let g=new Image;g.crossOrigin="Anonymous",g.src=e,g.onload=()=>{f.width=g.width,f.height=g.height,h.drawImage(g,0,0,f.width,f.height);let $=h.getImageData(0,0,f.width,f.height);o.height=f.height,o.width=f.width,c(Go($.data,o))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(s!==void 0)return Go(s,o);throw new Error("Input data provided is not supported - aborted tensor creation")},nv=(e,t)=>{let{width:n,height:r,download:i,dispose:a}=t,s=[1,r,n,4];return new zn({location:"texture",type:"float32",texture:e,dims:s,download:i,dispose:a})},rv=(e,t)=>{let{dataType:n,dims:r,download:i,dispose:a}=t;return new zn({location:"gpu-buffer",type:n??"float32",gpuBuffer:e,dims:r,download:i,dispose:a})},iv=(e,t,n)=>new zn({location:"cpu-pinned",type:e,data:t,dims:n??[t.length]})}),ms,ml,hd,av,VS=ee(()=>{ms=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["float16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array]]),ml=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),hd=!1,av=()=>{if(!hd){hd=!0;let e=typeof BigInt64Array<"u"&&typeof BigInt64Array.from=="function",t=typeof BigUint64Array<"u"&&typeof BigUint64Array.from=="function";e&&(ms.set("int64",BigInt64Array),ml.set(BigInt64Array,"int64")),t&&(ms.set("uint64",BigUint64Array),ml.set(BigUint64Array,"uint64"))}}}),sv,ov,jS=ee(()=>{nf(),sv=e=>{let t=1;for(let n=0;n{switch(e.location){case"cpu":return new zn(e.type,e.data,t);case"cpu-pinned":return new zn({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new zn({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new zn({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),zn,nf=ee(()=>{US(),WS(),VS(),jS(),zn=class{constructor(e,t,n){av();let r,i;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,r=e.type,i=e.dims,e.location){case"cpu-pinned":{let s=ms.get(r);if(!s)throw new TypeError(`unsupported type "${r}" to create tensor from pinned buffer`);if(!(e.data instanceof s))throw new TypeError(`buffer should be of type ${s.name}`);this.cpuData=e.data;break}case"texture":{if(r!=="float32")throw new TypeError(`unsupported type "${r}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break}case"gpu-buffer":{if(r!=="float32"&&r!=="float16"&&r!=="int32"&&r!=="int64"&&r!=="uint32"&&r!=="bool")throw new TypeError(`unsupported type "${r}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let s,o;if(typeof e=="string")if(r=e,o=n,e==="string"){if(!Array.isArray(t))throw new TypeError("A string tensor's data must be a string array.");s=t}else{let l=ms.get(e);if(l===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if(e==="float16")throw new TypeError("Creating a float16 tensor from number array is not supported. Please use Uint16Array as data.");e==="uint64"||e==="int64"?s=l.from(t,BigInt):s=l.from(t)}else if(t instanceof l)s=t;else throw new TypeError(`A ${r} tensor's data must be type of ${l}`)}else if(o=t,Array.isArray(e)){if(e.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let l=typeof e[0];if(l==="string")r="string",s=e;else if(l==="boolean")r="bool",s=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${l}.`)}else{let l=ml.get(e.constructor);if(l===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);r=l,s=e}if(o===void 0)o=[s.length];else if(!Array.isArray(o))throw new TypeError("A tensor's dims must be a number array");i=o,this.cpuData=s,this.dataLocation="cpu"}let a=sv(i);if(this.cpuData&&a!==this.cpuData.length)throw new Error(`Tensor's size(${a}) does not match data length(${this.cpuData.length}).`);this.type=r,this.dims=i,this.size=a}static async fromImage(e,t){return tv(e,t)}static fromTexture(e,t){return nv(e,t)}static fromGpuBuffer(e,t){return rv(e,t)}static fromPinnedBuffer(e,t,n){return iv(e,t,n)}toDataURL(e){return J_(this,e)}toImageData(e){return ev(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}async getData(e){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let t=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=t,e&&this.disposer&&(this.disposer(),this.disposer=void 0),t}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return ov(this,e)}}}),Lt,rf=ee(()=>{nf(),Lt=zn}),Ds,md,Nn,Ln,lv=ee(()=>{Z_(),Ds=(e,t)=>{ra.wasm.trace&&console.timeStamp(`${e}::ORT::${t}`)},md=(e,t)=>{var i;let n=((i=new Error().stack)==null?void 0:i.split(/\r\n|\r|\n/g))||[],r=!1;for(let a=0;a{ra.wasm.trace&&md("BEGIN",e)},Ln=e=>{ra.wasm.trace&&md("END",e)}}),uv,GS=ee(()=>{tf(),rf(),lv(),uv=class dv{constructor(t){this.handler=t}async run(t,n,r){Nn();let i={},a={};if(typeof t!="object"||t===null||t instanceof Lt||Array.isArray(t))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let s=!0;if(typeof n=="object"){if(n===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(n instanceof Lt)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(n)){if(n.length===0)throw new TypeError("'fetches' cannot be an empty array.");s=!1;for(let d of n){if(typeof d!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(d)===-1)throw new RangeError(`'fetches' contains invalid output name: ${d}.`);i[d]=null}if(typeof r=="object"&&r!==null)a=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else{let d=!1,c=Object.getOwnPropertyNames(n);for(let u of this.outputNames)if(c.indexOf(u)!==-1){let f=n[u];(f===null||f instanceof Lt)&&(d=!0,s=!1,i[u]=f)}if(d){if(typeof r=="object"&&r!==null)a=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else a=n}}else if(typeof n<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let d of this.inputNames)if(typeof t[d]>"u")throw new Error(`input '${d}' is missing in 'feeds'.`);if(s)for(let d of this.outputNames)i[d]=null;let o=await this.handler.run(t,i,a),l={};for(let d in o)if(Object.hasOwnProperty.call(o,d)){let c=o[d];c instanceof Lt?l[d]=c:l[d]=new Lt(c.type,c.data,c.dims)}return Ln(),l}async release(){return this.handler.dispose()}static async create(t,n,r,i){Nn();let a,s={};if(typeof t=="string"){if(a=t,typeof n=="object"&&n!==null)s=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof Uint8Array){if(a=t,typeof n=="object"&&n!==null)s=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer){let d=t,c=0,u=t.byteLength;if(typeof n=="object"&&n!==null)s=n;else if(typeof n=="number"){if(c=n,!Number.isSafeInteger(c))throw new RangeError("'byteOffset' must be an integer.");if(c<0||c>=d.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${d.byteLength}).`);if(u=t.byteLength-c,typeof r=="number"){if(u=r,!Number.isSafeInteger(u))throw new RangeError("'byteLength' must be an integer.");if(u<=0||c+u>d.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${d.byteLength-c}].`);if(typeof i=="object"&&i!==null)s=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else if(typeof r<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof n<"u")throw new TypeError("'options' must be an object.");a=new Uint8Array(d,c,u)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let o=(s.executionProviders||[]).map(d=>typeof d=="string"?d:d.name),l=await(await ef(o)).createInferenceSessionHandler(a,s);return Ln(),new dv(l)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}}),af,HS=ee(()=>{GS(),af=uv}),qS=ee(()=>{}),gm,cv,KS=ee(()=>{tf(),rf(),gm="Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.",cv=class pv{constructor(t,n,r){this.handler=t,this.hasOptimizerModel=n,this.hasEvalModel=r}get trainingInputNames(){return this.handler.inputNames}get trainingOutputNames(){return this.handler.outputNames}get evalInputNames(){if(this.hasEvalModel)return this.handler.evalInputNames;throw new Error("This training session has no evalModel loaded.")}get evalOutputNames(){if(this.hasEvalModel)return this.handler.evalOutputNames;throw new Error("This training session has no evalModel loaded.")}static async create(t,n){let r=t.evalModel||"",i=t.optimizerModel||"",a=n||{},s=(a.executionProviders||[]).map(l=>typeof l=="string"?l:l.name),o=await ef(s);if(o.createTrainingSessionHandler){let l=await o.createTrainingSessionHandler(t.checkpointState,t.trainModel,r,i,a);return new pv(l,!!t.optimizerModel,!!t.evalModel)}else throw new Error(gm)}typeNarrowingForRunStep(t,n,r,i,a){let s={},o={};if(typeof r!="object"||r===null||r instanceof Lt||Array.isArray(r))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let l=!0;if(typeof i=="object"){if(i===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(i instanceof Lt)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(i)){if(i.length===0)throw new TypeError("'fetches' cannot be an empty array.");l=!1;for(let d of i){if(typeof d!="string")throw new TypeError("'fetches' must be a string array or an object.");if(n.indexOf(d)===-1)throw new RangeError(`'fetches' contains invalid output name: ${d}.`);s[d]=null}if(typeof a=="object"&&a!==null)o=a;else if(typeof a<"u")throw new TypeError("'options' must be an object.")}else{let d=!1,c=Object.getOwnPropertyNames(i);for(let u of n)if(c.indexOf(u)!==-1){let f=i[u];(f===null||f instanceof Lt)&&(d=!0,l=!1,s[u]=f)}if(d){if(typeof a=="object"&&a!==null)o=a;else if(typeof a<"u")throw new TypeError("'options' must be an object.")}else o=i}}else if(typeof i<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let d of t)if(typeof r[d]>"u")throw new Error(`input '${d}' is missing in 'feeds'.`);if(l)for(let d of n)s[d]=null;return[s,o]}convertHandlerReturnTypeToMapOfTensors(t){let n={};for(let r in t)if(Object.hasOwnProperty.call(t,r)){let i=t[r];i instanceof Lt?n[r]=i:n[r]=new Lt(i.type,i.data,i.dims)}return n}async lazyResetGrad(){await this.handler.lazyResetGrad()}async runTrainStep(t,n,r){let[i,a]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,t,n,r),s=await this.handler.runTrainStep(t,i,a);return this.convertHandlerReturnTypeToMapOfTensors(s)}async runOptimizerStep(t){if(this.hasOptimizerModel)await this.handler.runOptimizerStep(t||{});else throw new Error("This TrainingSession has no OptimizerModel loaded.")}async runEvalStep(t,n,r){if(this.hasEvalModel){let[i,a]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,t,n,r),s=await this.handler.runEvalStep(t,i,a);return this.convertHandlerReturnTypeToMapOfTensors(s)}else throw new Error("This TrainingSession has no EvalModel loaded.")}async getParametersSize(t=!0){return this.handler.getParametersSize(t)}async loadParametersBuffer(t,n=!0){let r=await this.getParametersSize(n);if(t.length!==4*r)throw new Error("Size of the buffer passed into loadParametersBuffer must match the number of parameters in the model. Please use getParametersSize method to check.");return this.handler.loadParametersBuffer(t,n)}async getContiguousParameters(t=!0){return this.handler.getContiguousParameters(t)}async release(){return this.handler.dispose()}}}),sf,YS=ee(()=>{KS(),sf=cv}),fv={};ga(fv,{InferenceSession:()=>af,TRACE:()=>Ds,TRACE_FUNC_BEGIN:()=>Nn,TRACE_FUNC_END:()=>Ln,Tensor:()=>Lt,TrainingSession:()=>sf,env:()=>je,registerBackend:()=>na});var Fn=ee(()=>{NS(),FS(),HS(),rf(),lv(),qS(),YS()}),of={};ga(of,{createReadStream:()=>gv,readFile:()=>hv,readFileSync:()=>mv});var hv,mv,gv,yv=ee(()=>{hv=void 0,mv=void 0,gv=void 0}),lf={};ga(lf,{join:()=>wv});var wv,_v=ee(()=>{wv=void 0}),QS=ma((e,t)=>{var n=(()=>{var r=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename<"u"&&(r=r||__filename),function(i={}){var a=i,s,o;a.ready=new Promise((m,x)=>{s=m,o=x}),a.mountExternalData=(m,x)=>{(a.Fa||(a.Fa=new Map)).set(m,x)},a.unmountExternalData=()=>{delete a.Fa},a.jsepInit=(m,x,k,A,F,q,se,$e)=>{a.ab=m,a.Qa=x,a.Sa=k,a.La=A,a.Ra=F,a.sa=q,a.Ta=se,a.Ua=$e,x=(ce,pe,we)=>(...Ie)=>{let Le=Xt,B=pe==null?void 0:pe();Ie=ce(...Ie);let ve=pe==null?void 0:pe();return B!==ve&&(ce=ve,we(B),pe=we=null),Xt!=Le?mo():Ie},k=ce=>async(...pe)=>{try{if(a.Ea)throw Error("Session already started");let we=a.Ea={Va:pe[0],errors:[]},Ie=await ce(...pe);if(a.Ea!==we)throw Error("Session mismatch");m.flush();let Le=we.errors;if(0ve),0a._OrtRun,ce=>a._OrtRun=ce)),a._OrtRunWithBinding=k(x(a._OrtRunWithBinding,()=>a._OrtRunWithBinding,ce=>a._OrtRunWithBinding=ce)),a._OrtBindInput=x(a._OrtBindInput,()=>a._OrtBindInput,ce=>a._OrtBindInput=ce),a.jsepRegisterBuffer=(ce,pe,we,Ie)=>m.registerBuffer(ce,pe,we,Ie),a.jsepUnregisterBuffers=ce=>{m.unregisterBuffers(ce)},a.jsepGetBuffer=ce=>m.getBuffer(ce),a.jsepCreateDownloader=(ce,pe,we)=>m.createDownloader(ce,pe,we)};var l=Object.assign({},a),d="./this.program",c=(m,x)=>{throw x},u=typeof window=="object",f=typeof importScripts=="function",h=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",g="",$,E,y;if(h){var _=(yv(),fi(of)),v=(_v(),fi(lf));g=f?v.dirname(g)+"/":__dirname+"/",$=(m,x)=>(m=xe(m)?new URL(m):v.normalize(m),_.readFileSync(m,x?void 0:"utf8")),y=m=>(m=$(m,!0),m.buffer||(m=new Uint8Array(m)),m),E=(m,x,k,A=!0)=>{m=xe(m)?new URL(m):v.normalize(m),_.readFile(m,A?void 0:"utf8",(F,q)=>{F?k(F):x(A?q.buffer:q)})},!a.thisProgram&&1{throw process.exitCode=m,x},a.inspect=()=>"[Emscripten Module object]"}else(u||f)&&(f?g=self.location.href:typeof document<"u"&&document.currentScript&&(g=document.currentScript.src),r&&(g=r),g.indexOf("blob:")!==0?g=g.substr(0,g.replace(/[?#].*/,"").lastIndexOf("/")+1):g="",$=m=>{var x=new XMLHttpRequest;return x.open("GET",m,!1),x.send(null),x.responseText},f&&(y=m=>{var x=new XMLHttpRequest;return x.open("GET",m,!1),x.responseType="arraybuffer",x.send(null),new Uint8Array(x.response)}),E=(m,x,k)=>{var A=new XMLHttpRequest;A.open("GET",m,!0),A.responseType="arraybuffer",A.onload=()=>{A.status==200||A.status==0&&A.response?x(A.response):k()},A.onerror=k,A.send(null)});var b=console.log.bind(console),C=console.error.bind(console);Object.assign(a,l),l=null,typeof WebAssembly!="object"&&V("no native wasm support detected");var I,O=!1,M,W,G,z,K,ae,ue;function R(){var m=I.buffer;a.HEAP8=W=new Int8Array(m),a.HEAP16=new Int16Array(m),a.HEAPU8=G=new Uint8Array(m),a.HEAPU16=new Uint16Array(m),a.HEAP32=z=new Int32Array(m),a.HEAPU32=K=new Uint32Array(m),a.HEAPF32=ae=new Float32Array(m),a.HEAPF64=ue=new Float64Array(m)}var H=[],re=[],L=[],X=0,Z=null;function V(m){throw m="Aborted("+m+")",C(m),O=!0,M=1,m=new WebAssembly.RuntimeError(m+". Build with -sASSERTIONS for more info."),o(m),m}var ie=m=>m.startsWith("data:application/octet-stream;base64,"),xe=m=>m.startsWith("file://"),Re;if(Re="ort-wasm-simd.wasm",!ie(Re)){var He=Re;Re=a.locateFile?a.locateFile(He,g):g+He}function qe(m){if(y)return y(m);throw"both async and sync fetching of the wasm failed"}function Dt(m){if(u||f){if(typeof fetch=="function"&&!xe(m))return fetch(m,{credentials:"same-origin"}).then(x=>{if(!x.ok)throw"failed to load wasm binary file at '"+m+"'";return x.arrayBuffer()}).catch(()=>qe(m));if(E)return new Promise((x,k)=>{E(m,A=>x(new Uint8Array(A)),k)})}return Promise.resolve().then(()=>qe(m))}function er(m,x,k){return Dt(m).then(A=>WebAssembly.instantiate(A,x)).then(A=>A).then(k,A=>{C(`failed to asynchronously prepare wasm: ${A}`),V(A)})}function ht(m,x){var k=Re;return typeof WebAssembly.instantiateStreaming!="function"||ie(k)||xe(k)||h||typeof fetch!="function"?er(k,m,x):fetch(k,{credentials:"same-origin"}).then(A=>WebAssembly.instantiateStreaming(A,m).then(x,function(F){return C(`wasm streaming compile failed: ${F}`),C("falling back to ArrayBuffer instantiation"),er(k,m,x)}))}var at,Qt={931056:(m,x,k,A)=>{if(typeof a>"u"||!a.Fa)return 1;if(m=ut(m>>>0),m.startsWith("./")&&(m=m.substring(2)),m=a.Fa.get(m),!m)return 2;if(x>>>=0,k>>>=0,x+k>m.byteLength)return 3;try{return G.set(m.subarray(x,x+k),A>>>0>>>0),0}catch{return 4}},931557:m=>a.Qa(m),931590:m=>a.Sa(m),931622:(m,x,k)=>{a.La(m,x,k,!0)},931661:(m,x,k)=>{a.La(m,x,k)},931694:m=>{a.sa("Abs",m,void 0)},931745:m=>{a.sa("Neg",m,void 0)},931796:m=>{a.sa("Floor",m,void 0)},931849:m=>{a.sa("Ceil",m,void 0)},931901:m=>{a.sa("Reciprocal",m,void 0)},931959:m=>{a.sa("Sqrt",m,void 0)},932011:m=>{a.sa("Exp",m,void 0)},932062:m=>{a.sa("Erf",m,void 0)},932113:m=>{a.sa("Sigmoid",m,void 0)},932168:m=>{a.sa("Log",m,void 0)},932219:m=>{a.sa("Sin",m,void 0)},932270:m=>{a.sa("Cos",m,void 0)},932321:m=>{a.sa("Tan",m,void 0)},932372:m=>{a.sa("Asin",m,void 0)},932424:m=>{a.sa("Acos",m,void 0)},932476:m=>{a.sa("Atan",m,void 0)},932528:m=>{a.sa("Sinh",m,void 0)},932580:m=>{a.sa("Cosh",m,void 0)},932632:m=>{a.sa("Asinh",m,void 0)},932685:m=>{a.sa("Acosh",m,void 0)},932738:m=>{a.sa("Atanh",m,void 0)},932791:m=>{a.sa("Tanh",m,void 0)},932843:m=>{a.sa("Not",m,void 0)},932894:(m,x,k)=>{a.sa("Clip",m,{min:x,max:k})},932963:m=>{a.sa("Clip",m,void 0)},933015:(m,x)=>{a.sa("Elu",m,{alpha:x})},933073:m=>{a.sa("Relu",m,void 0)},933125:(m,x)=>{a.sa("LeakyRelu",m,{alpha:x})},933189:(m,x)=>{a.sa("ThresholdedRelu",m,{alpha:x})},933259:(m,x)=>{a.sa("Cast",m,{to:x})},933317:m=>{a.sa("Add",m,void 0)},933368:m=>{a.sa("Sub",m,void 0)},933419:m=>{a.sa("Mul",m,void 0)},933470:m=>{a.sa("Div",m,void 0)},933521:m=>{a.sa("Pow",m,void 0)},933572:m=>{a.sa("Equal",m,void 0)},933625:m=>{a.sa("Greater",m,void 0)},933680:m=>{a.sa("GreaterOrEqual",m,void 0)},933742:m=>{a.sa("Less",m,void 0)},933794:m=>{a.sa("LessOrEqual",m,void 0)},933853:(m,x,k,A,F)=>{a.sa("ReduceMean",m,{keepDims:!!x,noopWithEmptyAxes:!!k,axes:A?Array.from(z.subarray(A>>>0,F>>>0)):[]})},934012:(m,x,k,A,F)=>{a.sa("ReduceMax",m,{keepDims:!!x,noopWithEmptyAxes:!!k,axes:A?Array.from(z.subarray(A>>>0,F>>>0)):[]})},934170:(m,x,k,A,F)=>{a.sa("ReduceMin",m,{keepDims:!!x,noopWithEmptyAxes:!!k,axes:A?Array.from(z.subarray(A>>>0,F>>>0)):[]})},934328:(m,x,k,A,F)=>{a.sa("ReduceProd",m,{keepDims:!!x,noopWithEmptyAxes:!!k,axes:A?Array.from(z.subarray(A>>>0,F>>>0)):[]})},934487:(m,x,k,A,F)=>{a.sa("ReduceSum",m,{keepDims:!!x,noopWithEmptyAxes:!!k,axes:A?Array.from(z.subarray(A>>>0,F>>>0)):[]})},934645:(m,x,k,A,F)=>{a.sa("ReduceL1",m,{keepDims:!!x,noopWithEmptyAxes:!!k,axes:A?Array.from(z.subarray(A>>>0,F>>>0)):[]})},934802:(m,x,k,A,F)=>{a.sa("ReduceL2",m,{keepDims:!!x,noopWithEmptyAxes:!!k,axes:A?Array.from(z.subarray(A>>>0,F>>>0)):[]})},934959:(m,x,k,A,F)=>{a.sa("ReduceLogSum",m,{keepDims:!!x,noopWithEmptyAxes:!!k,axes:A?Array.from(z.subarray(A>>>0,F>>>0)):[]})},935120:(m,x,k,A,F)=>{a.sa("ReduceSumSquare",m,{keepDims:!!x,noopWithEmptyAxes:!!k,axes:A?Array.from(z.subarray(A>>>0,F>>>0)):[]})},935284:(m,x,k,A,F)=>{a.sa("ReduceLogSumExp",m,{keepDims:!!x,noopWithEmptyAxes:!!k,axes:A?Array.from(z.subarray(A>>>0,F>>>0)):[]})},935448:m=>{a.sa("Where",m,void 0)},935501:(m,x,k)=>{a.sa("Transpose",m,{perm:x?Array.from(z.subarray(x>>>0,k>>>0)):[]})},935609:(m,x,k,A,F,q,se,$e,ce,pe,we,Ie,Le,B,ve)=>{a.sa("ConvTranspose",m,{format:ce?"NHWC":"NCHW",autoPad:x,dilations:[k],group:A,kernel_shape:[F],pads:[q,se],strides:[$e],wIsConst:()=>!!W[pe>>>0],outputPadding:we?Array.from(z.subarray(we>>>0,Ie>>>0)):[],outputShape:Le?Array.from(z.subarray(Le>>>0,B>>>0)):[],activation:ut(ve)})},936011:(m,x,k,A,F,q,se,$e,ce,pe,we,Ie,Le,B)=>{a.sa("ConvTranspose",m,{format:$e?"NHWC":"NCHW",autoPad:x,dilations:Array.from(z.subarray(k>>>0,(k>>>0)+2>>>0)),group:A,kernelShape:Array.from(z.subarray(F>>>0,(F>>>0)+2>>>0)),pads:Array.from(z.subarray(q>>>0,(q>>>0)+4>>>0)),strides:Array.from(z.subarray(se>>>0,(se>>>0)+2>>>0)),wIsConst:()=>!!W[ce>>>0],outputPadding:pe?Array.from(z.subarray(pe>>>0,we>>>0)):[],outputShape:Ie?Array.from(z.subarray(Ie>>>0,Le>>>0)):[],activation:ut(B)})},936576:(m,x,k,A,F,q,se,$e,ce,pe,we,Ie,Le,B,ve)=>{a.sa("ConvTranspose",m,{format:ce?"NHWC":"NCHW",autoPad:x,dilations:[k],group:A,kernel_shape:[F],pads:[q,se],strides:[$e],wIsConst:()=>!!W[pe>>>0],outputPadding:we?Array.from(z.subarray(we>>>0,Ie>>>0)):[],outputShape:Le?Array.from(z.subarray(Le>>>0,B>>>0)):[],activation:ut(ve)})},936978:(m,x,k,A,F,q,se,$e,ce,pe,we,Ie,Le,B)=>{a.sa("ConvTranspose",m,{format:$e?"NHWC":"NCHW",autoPad:x,dilations:Array.from(z.subarray(k>>>0,(k>>>0)+2>>>0)),group:A,kernelShape:Array.from(z.subarray(F>>>0,(F>>>0)+2>>>0)),pads:Array.from(z.subarray(q>>>0,(q>>>0)+4>>>0)),strides:Array.from(z.subarray(se>>>0,(se>>>0)+2>>>0)),wIsConst:()=>!!W[ce>>>0],outputPadding:pe?Array.from(z.subarray(pe>>>0,we>>>0)):[],outputShape:Ie?Array.from(z.subarray(Ie>>>0,Le>>>0)):[],activation:ut(B)})},937543:(m,x)=>{a.sa("GlobalAveragePool",m,{format:x?"NHWC":"NCHW"})},937634:(m,x,k,A,F,q,se,$e,ce,pe,we,Ie,Le,B,ve,Me)=>{a.sa("AveragePool",m,{format:Me?"NHWC":"NCHW",auto_pad:x,ceil_mode:k,count_include_pad:A,storage_order:F,dilations:[q,se],kernel_shape:[$e,ce],pads:[pe,we,Ie,Le],strides:[B,ve]})},937918:(m,x)=>{a.sa("GlobalAveragePool",m,{format:x?"NHWC":"NCHW"})},938009:(m,x,k,A,F,q,se,$e,ce,pe,we,Ie,Le,B,ve,Me)=>{a.sa("AveragePool",m,{format:Me?"NHWC":"NCHW",auto_pad:x,ceil_mode:k,count_include_pad:A,storage_order:F,dilations:[q,se],kernel_shape:[$e,ce],pads:[pe,we,Ie,Le],strides:[B,ve]})},938293:(m,x)=>{a.sa("GlobalMaxPool",m,{format:x?"NHWC":"NCHW"})},938380:(m,x,k,A,F,q,se,$e,ce,pe,we,Ie,Le,B,ve,Me)=>{a.sa("MaxPool",m,{format:Me?"NHWC":"NCHW",auto_pad:x,ceil_mode:k,count_include_pad:A,storage_order:F,dilations:[q,se],kernel_shape:[$e,ce],pads:[pe,we,Ie,Le],strides:[B,ve]})},938660:(m,x)=>{a.sa("GlobalMaxPool",m,{format:x?"NHWC":"NCHW"})},938747:(m,x,k,A,F,q,se,$e,ce,pe,we,Ie,Le,B,ve,Me)=>{a.sa("MaxPool",m,{format:Me?"NHWC":"NCHW",auto_pad:x,ceil_mode:k,count_include_pad:A,storage_order:F,dilations:[q,se],kernel_shape:[$e,ce],pads:[pe,we,Ie,Le],strides:[B,ve]})},939027:(m,x,k,A,F)=>{a.sa("Gemm",m,{alpha:x,beta:k,transA:A,transB:F})},939131:m=>{a.sa("MatMul",m,void 0)},939185:(m,x,k,A)=>{a.sa("ArgMax",m,{keepDims:!!x,selectLastIndex:!!k,axis:A})},939293:(m,x,k,A)=>{a.sa("ArgMin",m,{keepDims:!!x,selectLastIndex:!!k,axis:A})},939401:(m,x)=>{a.sa("Softmax",m,{axis:x})},939464:(m,x)=>{a.sa("Concat",m,{axis:x})},939524:(m,x,k,A,F)=>{a.sa("Split",m,{axis:x,numOutputs:k,splitSizes:A?Array.from(z.subarray(A>>>0,F>>>0)):[]})},939664:m=>{a.sa("Expand",m,void 0)},939718:(m,x)=>{a.sa("Gather",m,{axis:Number(x)})},939789:(m,x)=>{a.sa("GatherElements",m,{axis:Number(x)})},939868:(m,x,k,A,F,q,se,$e,ce,pe,we)=>{a.sa("Resize",m,{antialias:x,axes:k?Array.from(z.subarray(k>>>0,A>>>0)):[],coordinateTransformMode:ut(F),cubicCoeffA:q,excludeOutside:se,extrapolationValue:$e,keepAspectRatioPolicy:ut(ce),mode:ut(pe),nearestMode:ut(we)})},940214:(m,x,k,A,F,q,se)=>{a.sa("Slice",m,{starts:x?Array.from(z.subarray(x>>>0,k>>>0)):[],ends:A?Array.from(z.subarray(A>>>0,F>>>0)):[],axes:q?Array.from(z.subarray(q>>>0,se>>>0)):[]})},940430:m=>{a.sa("Tile",m,void 0)},940482:(m,x,k)=>{a.sa("LayerNormalization",m,{axis:Number(x),epsilon:Number(k)})},940589:(m,x,k)=>{a.sa("InstanceNormalization",m,{epsilon:x,format:k?"NHWC":"NCHW"})},940703:(m,x,k)=>{a.sa("InstanceNormalization",m,{epsilon:x,format:k?"NHWC":"NCHW"})},940817:m=>{a.sa("Range",m,void 0)},940870:(m,x)=>{a.sa("Einsum",m,{equation:ut(x)})},940951:(m,x,k,A,F)=>{a.sa("Pad",m,{mode:x,value:k,pads:A?Array.from(z.subarray(A>>>0,F>>>0)):[]})},941078:(m,x,k,A,F,q)=>{a.sa("BatchNormalization",m,{epsilon:x,momentum:k,spatial:!!F,trainingMode:!!A,format:q?"NHWC":"NCHW"})},941247:(m,x,k,A,F,q)=>{a.sa("BatchNormalization",m,{epsilon:x,momentum:k,spatial:!!F,trainingMode:!!A,format:q?"NHWC":"NCHW"})},941416:(m,x,k)=>{a.sa("CumSum",m,{exclusive:Number(x),reverse:Number(k)})},941513:(m,x,k,A,F,q,se,$e,ce)=>{a.sa("Attention",m,{numHeads:x,isUnidirectional:k,maskFilterValue:A,scale:F,doRotary:q,qkvHiddenSizes:se?Array.from(z.subarray(Number($e)>>>0,Number($e)+se>>>0)):[],pastPresentShareBuffer:!!ce})},941785:m=>{a.sa("Gelu",m,void 0)},941837:(m,x,k,A,F,q)=>{a.sa("MultiHeadAttention",m,{numHeads:x,isUnidirectional:k,maskFilterValue:A,scale:F,doRotary:q})},941996:m=>{a.sa("BiasAdd",m,void 0)},942051:m=>{a.sa("BiasSplitGelu",m,void 0)},942112:(m,x)=>{a.sa("SkipLayerNormalization",m,{epsilon:x})},942193:(m,x,k,A,F,q,se,$e,ce,pe,we,Ie,Le)=>{a.sa("Conv",m,{format:ce?"NHWC":"NCHW",auto_pad:x,dilations:[k],group:A,kernel_shape:[F],pads:q?Array.from(z.subarray(q>>>0,se>>>0)):[],strides:[$e],w_is_const:()=>!!W[pe>>>0],activation:ut(we),activation_params:Ie?Array.from(ae.subarray(Ie>>>0,Le>>>0)):[]})},942563:(m,x,k,A,F,q,se,$e,ce,pe,we,Ie,Le,B,ve,Me)=>{a.sa("Conv",m,{format:Ie?"NHWC":"NCHW",auto_pad:x,dilations:[k,A],group:F,kernel_shape:[q,se],pads:$e?Array.from(z.subarray($e>>>0,ce>>>0)):[],strides:[pe,we],w_is_const:()=>!!W[Le>>>0],activation:ut(B),activation_params:ve?Array.from(ae.subarray(ve>>>0,Me>>>0)):[]})},942954:m=>{a.Ta(m)},942988:(m,x)=>a.Ua(m,x,a.Ea.Va,a.Ea.errors)};function cn(m){this.name="ExitStatus",this.message=`Program terminated with exit(${m})`,this.status=m}function Ei(m){this.Ja=m-24,this.Oa=function(x){K[this.Ja+4>>>2>>>0]=x},this.Na=function(x){K[this.Ja+8>>>2>>>0]=x},this.$a=function(x,k){this.Ma(),this.Oa(x),this.Na(k)},this.Ma=function(){K[this.Ja+16>>>2>>>0]=0}}var vr=0,va=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,Qr=(m,x,k)=>{x>>>=0;var A=x+k;for(k=x;m[k]&&!(k>=A);)++k;if(16F?A+=String.fromCharCode(F):(F-=65536,A+=String.fromCharCode(55296|F>>10,56320|F&1023))}}else A+=String.fromCharCode(F)}return A},ut=(m,x)=>(m>>>=0)?Qr(G,m,x):"",ki=m=>{for(var x=0,k=0;k=A?x++:2047>=A?x+=2:55296<=A&&57343>=A?(x+=4,++k):x+=3}return x},$a=(m,x,k,A)=>{if(k>>>=0,!(0=se){var $e=m.charCodeAt(++q);se=65536+((se&1023)<<10)|$e&1023}if(127>=se){if(k>=A)break;x[k++>>>0]=se}else{if(2047>=se){if(k+1>=A)break;x[k++>>>0]=192|se>>6}else{if(65535>=se){if(k+2>=A)break;x[k++>>>0]=224|se>>12}else{if(k+3>=A)break;x[k++>>>0]=240|se>>18,x[k++>>>0]=128|se>>12&63}x[k++>>>0]=128|se>>6&63}x[k++>>>0]=128|se&63}}return x[k>>>0]=0,k-F},tr=m=>m%4===0&&(m%100!==0||m%400===0),uo=[0,31,60,91,121,152,182,213,244,274,305,335],nr=[0,31,59,90,120,151,181,212,243,273,304,334],Ci=m=>{var x=ki(m)+1,k=Mi(x);return k&&$a(m,G,k,x),k},Xr=[],Ti=(m,x)=>{Xr.length=0;for(var k;k=G[m++>>>0];){var A=k!=105;A&=k!=112,x+=A&&x%8?4:0,Xr.push(k==112?K[x>>>2>>>0]:k==105?z[x>>>2>>>0]:ue[x>>>3>>>0]),x+=A?8:4}return Xr},Ii={},Un=()=>{if(!Ai){var m={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:d||"./this.program"},x;for(x in Ii)Ii[x]===void 0?delete m[x]:m[x]=Ii[x];var k=[];for(x in m)k.push(`${x}=${m[x]}`);Ai=k}return Ai},Ai,co=[null,[],[]],_t=[31,29,31,30,31,30,31,31,30,31,30,31],po=[31,28,31,30,31,30,31,31,30,31,30,31];function Ke(m){var x=Array(ki(m)+1);return $a(m,x,0,x.length),x}function ba(m,x,k,A){function F(B,ve,Me){for(B=typeof B=="number"?B.toString():B||"";B.lengthvo?-1:0Vn-B.getDate())ve-=Vn-B.getDate()+1,B.setDate(1),11>Me?B.setMonth(Me+1):(B.setMonth(0),B.setFullYear(B.getFullYear()+1));else{B.setDate(B.getDate()+ve);break}}return Me=new Date(B.getFullYear()+1,0,4),ve=$e(new Date(B.getFullYear(),0,4)),Me=$e(Me),0>=se(ve,B)?0>=se(Me,B)?B.getFullYear()+1:B.getFullYear():B.getFullYear()-1}m>>>=0,x>>>=0,k>>>=0,A>>>=0;var pe=K[A+40>>>2>>>0];A={Ya:z[A>>>2>>>0],Xa:z[A+4>>>2>>>0],Ga:z[A+8>>>2>>>0],Ka:z[A+12>>>2>>>0],Ha:z[A+16>>>2>>>0],Da:z[A+20>>>2>>>0],xa:z[A+24>>>2>>>0],Ca:z[A+28>>>2>>>0],bb:z[A+32>>>2>>>0],Wa:z[A+36>>>2>>>0],Za:pe?ut(pe):""},k=ut(k),pe={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"};for(var we in pe)k=k.replace(new RegExp(we,"g"),pe[we]);var Ie="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),Le="January February March April May June July August September October November December".split(" ");pe={"%a":B=>Ie[B.xa].substring(0,3),"%A":B=>Ie[B.xa],"%b":B=>Le[B.Ha].substring(0,3),"%B":B=>Le[B.Ha],"%C":B=>q((B.Da+1900)/100|0,2),"%d":B=>q(B.Ka,2),"%e":B=>F(B.Ka,2," "),"%g":B=>ce(B).toString().substring(2),"%G":B=>ce(B),"%H":B=>q(B.Ga,2),"%I":B=>(B=B.Ga,B==0?B=12:12{for(var ve=0,Me=0;Me<=B.Ha-1;ve+=(tr(B.Da+1900)?_t:po)[Me++]);return q(B.Ka+ve,3)},"%m":B=>q(B.Ha+1,2),"%M":B=>q(B.Xa,2),"%n":()=>` `,"%p":B=>0<=B.Ga&&12>B.Ga?"AM":"PM","%S":B=>q(B.Ya,2),"%t":()=>" ","%u":B=>B.xa||7,"%U":B=>q(Math.floor((B.Ca+7-B.xa)/7),2),"%V":B=>{var ve=Math.floor((B.Ca+7-(B.xa+6)%7)/7);if(2>=(B.xa+371-B.Ca-2)%7&&ve++,ve)ve==53&&(Me=(B.xa+371-B.Ca)%7,Me==4||Me==3&&tr(B.Da)||(ve=1));else{ve=52;var Me=(B.xa+7-B.Ca-1)%7;(Me==4||Me==5&&tr(B.Da%400-1))&&ve++}return q(ve,2)},"%w":B=>B.xa,"%W":B=>q(Math.floor((B.Ca+7-(B.xa+6)%7)/7),2),"%y":B=>(B.Da+1900).toString().substring(2),"%Y":B=>B.Da+1900,"%z":B=>{B=B.Wa;var ve=0<=B;return B=Math.abs(B)/60,(ve?"+":"-")+("0000"+(B/60*100+B%60)).slice(-4)},"%Z":B=>B.Za,"%%":()=>"%"},k=k.replace(/%%/g,"\0\0");for(we in pe)k.includes(we)&&(k=k.replace(new RegExp(we,"g"),pe[we](A)));return k=k.replace(/\0\0/g,"%"),we=Ke(k),we.length>x?0:(W.set(we,m>>>0),we.length-1)}var $r=m=>{try{m()}catch(x){V(x)}};function xa(){var m=me,x={};for(let[k,A]of Object.entries(m))x[k]=typeof A=="function"?function(){ye.push(k);try{return A.apply(null,arguments)}finally{O||(ye.pop(),Xt&&Wn===1&&ye.length===0&&(Wn=0,$r(za),typeof Fibers<"u"&&Fibers.cb()))}}:A;return x}var Wn=0,Xt=null,fo=0,ye=[],Zr={},Sa={},Ru=0,Oi=null,ho=[];function mo(){return new Promise((m,x)=>{Oi={resolve:m,reject:x}})}function go(){var m=Mi(65548),x=m+12;K[m>>>2>>>0]=x,K[m+4>>>2>>>0]=x+65536,x=ye[0];var k=Zr[x];return k===void 0&&(k=Ru++,Zr[x]=k,Sa[k]=x),z[m+8>>>2>>>0]=k,m}function yo(m){if(!O){if(Wn===0){var x=!1,k=!1;m((A=0)=>{if(!O&&(fo=A,x=!0,k)){Wn=2,$r(()=>Ra(Xt)),typeof Browser<"u"&&Browser.Ia.Pa&&Browser.Ia.resume(),A=!1;try{var F=(0,me[Sa[z[Xt+8>>>2>>>0]]])()}catch($e){F=$e,A=!0}var q=!1;if(!Xt){var se=Oi;se&&(Oi=null,(A?se.reject:se.resolve)(F),q=!0)}if(A&&!q)throw F}}),k=!0,x||(Wn=1,Xt=go(),typeof Browser<"u"&&Browser.Ia.Pa&&Browser.Ia.pause(),$r(()=>Ma(Xt)))}else Wn===2?(Wn=0,$r(Pa),Ca(Xt),Xt=null,ho.forEach(A=>{var F;if(!O)try{A();try{M=M=A=M,(F=a.onExit)==null||F.call(a,A),O=!0,c(A,new cn(A))}catch(q){q instanceof cn||q=="unwind"||c(1,q)}}catch(q){q instanceof cn||q=="unwind"||c(1,q)}})):V(`invalid state: ${Wn}`);return fo}}function Ea(m){return yo(x=>{m().then(x)})}var wo={n:function(m,x,k){return Ea(async()=>{await a.Ra(m,x,k)})},a:function(m,x,k){throw m>>>=0,new Ei(m).$a(x>>>0,k>>>0),vr=m,vr},g:function(){return 0},J:function(){},A:function(){},C:function(){},L:function(){return 0},H:function(){},D:function(){},G:function(){},l:function(){},B:function(){},y:function(){},I:function(){},z:function(){},m:()=>1,q:function(m,x,k){m=x+2097152>>>0<4194305-!!m?(m>>>0)+4294967296*x:NaN,k>>>=0,m=new Date(1e3*m),z[k>>>2>>>0]=m.getUTCSeconds(),z[k+4>>>2>>>0]=m.getUTCMinutes(),z[k+8>>>2>>>0]=m.getUTCHours(),z[k+12>>>2>>>0]=m.getUTCDate(),z[k+16>>>2>>>0]=m.getUTCMonth(),z[k+20>>>2>>>0]=m.getUTCFullYear()-1900,z[k+24>>>2>>>0]=m.getUTCDay(),z[k+28>>>2>>>0]=(m.getTime()-Date.UTC(m.getUTCFullYear(),0,1,0,0,0,0))/864e5|0},r:function(m,x,k){m=x+2097152>>>0<4194305-!!m?(m>>>0)+4294967296*x:NaN,k>>>=0,m=new Date(1e3*m),z[k>>>2>>>0]=m.getSeconds(),z[k+4>>>2>>>0]=m.getMinutes(),z[k+8>>>2>>>0]=m.getHours(),z[k+12>>>2>>>0]=m.getDate(),z[k+16>>>2>>>0]=m.getMonth(),z[k+20>>>2>>>0]=m.getFullYear()-1900,z[k+24>>>2>>>0]=m.getDay(),z[k+28>>>2>>>0]=(tr(m.getFullYear())?uo:nr)[m.getMonth()]+m.getDate()-1|0,z[k+36>>>2>>>0]=-(60*m.getTimezoneOffset()),x=new Date(m.getFullYear(),6,1).getTimezoneOffset();var A=new Date(m.getFullYear(),0,1).getTimezoneOffset();z[k+32>>>2>>>0]=(x!=A&&m.getTimezoneOffset()==Math.min(A,x))|0},s:function(m){m>>>=0;var x=new Date(z[m+20>>>2>>>0]+1900,z[m+16>>>2>>>0],z[m+12>>>2>>>0],z[m+8>>>2>>>0],z[m+4>>>2>>>0],z[m>>>2>>>0],0),k=z[m+32>>>2>>>0],A=x.getTimezoneOffset(),F=new Date(x.getFullYear(),6,1).getTimezoneOffset(),q=new Date(x.getFullYear(),0,1).getTimezoneOffset(),se=Math.min(q,F);return 0>k?z[m+32>>>2>>>0]=+(F!=q&&se==A):0>>2>>>0]=x.getDay(),z[m+28>>>2>>>0]=(tr(x.getFullYear())?uo:nr)[x.getMonth()]+x.getDate()-1|0,z[m>>>2>>>0]=x.getSeconds(),z[m+4>>>2>>>0]=x.getMinutes(),z[m+8>>>2>>>0]=x.getHours(),z[m+12>>>2>>>0]=x.getDate(),z[m+16>>>2>>>0]=x.getMonth(),z[m+20>>>2>>>0]=x.getYear(),m=x.getTime(),isNaN(m)?(z[ka()>>>2>>>0]=61,m=-1):m/=1e3,Ta((at=m,1<=+Math.abs(at)?0>>0:~~+Math.ceil((at-+(~~at>>>0))/4294967296)>>>0:0)),m>>>0},o:function(){return-52},p:function(){},w:function(m,x,k){function A(ce){return(ce=ce.toTimeString().match(/\(([A-Za-z ]+)\)$/))?ce[1]:"GMT"}k>>>=0;var F=new Date().getFullYear(),q=new Date(F,0,1),se=new Date(F,6,1);F=q.getTimezoneOffset();var $e=se.getTimezoneOffset();K[m>>>0>>>2>>>0]=60*Math.max(F,$e),z[x>>>0>>>2>>>0]=+(F!=$e),m=A(q),x=A(se),m=Ci(m),x=Ci(x),$e>>2>>>0]=m,K[k+4>>>2>>>0]=x):(K[k>>>2>>>0]=x,K[k+4>>>2>>>0]=m)},e:()=>{V("")},b:function(m,x,k){return m>>>=0,x=Ti(x>>>0,k>>>0),Qt[m].apply(null,x)},i:function(m,x,k){return m>>>=0,x=Ti(x>>>0,k>>>0),Qt[m].apply(null,x)},h:()=>Date.now(),x:function(){return 4294901760},c:()=>performance.now(),K:function(m,x,k){return x>>>=0,G.copyWithin(m>>>0>>>0,x>>>0,x+(k>>>0)>>>0)},u:function(m){m>>>=0;var x=G.length;if(4294901760=k;k*=2){var A=x*(1+.2/k);A=Math.min(A,m+100663296);var F=Math;A=Math.max(m,A);e:{F=(F.min.call(F,4294901760,A+(65536-A%65536)%65536)-I.buffer.byteLength+65535)/65536;try{I.grow(F),R();var q=1;break e}catch{}q=void 0}if(q)return!0}return!1},E:function(m,x){m>>>=0,x>>>=0;var k=0;return Un().forEach((A,F)=>{var q=x+k;for(F=K[m+4*F>>>2>>>0]=q,q=0;q>>0>>>0]=A.charCodeAt(q);W[F>>>0>>>0]=0,k+=A.length+1}),0},F:function(m,x){m>>>=0,x>>>=0;var k=Un();K[m>>>2>>>0]=k.length;var A=0;return k.forEach(F=>A+=F.length+1),K[x>>>2>>>0]=A,0},f:()=>52,k:function(){return 52},t:function(){return 70},j:function(m,x,k,A){x>>>=0,k>>>=0,A>>>=0;for(var F=0,q=0;q>>2>>>0],$e=K[x+4>>>2>>>0];x+=8;for(var ce=0;ce<$e;ce++){var pe=G[se+ce>>>0],we=co[m];pe===0||pe===10?((m===1?b:C)(Qr(we,0)),we.length=0):we.push(pe)}F+=$e}return K[A>>>2>>>0]=F,0},v:ba,d:function(m,x,k,A){return ba(m>>>0,x>>>0,k>>>0,A>>>0)}},me=function(){function m(k){return me=k.exports,me=xa(),me=_o(),I=me.M,R(),re.unshift(me.N),X--,X==0&&Z&&(k=Z,Z=null,k()),me}var x={a:wo};if(X++,a.instantiateWasm)try{return a.instantiateWasm(x,m)}catch(k){C(`Module.instantiateWasm callback failed with error: ${k}`),o(k)}return ht(x,function(k){m(k.instance)}).catch(o),{}}();a._OrtInit=(m,x)=>(a._OrtInit=me.O)(m,x),a._OrtGetLastError=(m,x)=>(a._OrtGetLastError=me.P)(m,x),a._OrtCreateSessionOptions=(m,x,k,A,F,q,se,$e,ce,pe)=>(a._OrtCreateSessionOptions=me.Q)(m,x,k,A,F,q,se,$e,ce,pe),a._OrtAppendExecutionProvider=(m,x)=>(a._OrtAppendExecutionProvider=me.R)(m,x),a._OrtAddFreeDimensionOverride=(m,x,k)=>(a._OrtAddFreeDimensionOverride=me.S)(m,x,k),a._OrtAddSessionConfigEntry=(m,x,k)=>(a._OrtAddSessionConfigEntry=me.T)(m,x,k),a._OrtReleaseSessionOptions=m=>(a._OrtReleaseSessionOptions=me.U)(m),a._OrtCreateSession=(m,x,k)=>(a._OrtCreateSession=me.V)(m,x,k),a._OrtReleaseSession=m=>(a._OrtReleaseSession=me.W)(m),a._OrtGetInputOutputCount=(m,x,k)=>(a._OrtGetInputOutputCount=me.X)(m,x,k),a._OrtGetInputName=(m,x)=>(a._OrtGetInputName=me.Y)(m,x),a._OrtGetOutputName=(m,x)=>(a._OrtGetOutputName=me.Z)(m,x),a._OrtFree=m=>(a._OrtFree=me._)(m),a._OrtCreateTensor=(m,x,k,A,F,q)=>(a._OrtCreateTensor=me.$)(m,x,k,A,F,q),a._OrtGetTensorData=(m,x,k,A,F)=>(a._OrtGetTensorData=me.aa)(m,x,k,A,F),a._OrtReleaseTensor=m=>(a._OrtReleaseTensor=me.ba)(m),a._OrtCreateRunOptions=(m,x,k,A)=>(a._OrtCreateRunOptions=me.ca)(m,x,k,A),a._OrtAddRunConfigEntry=(m,x,k)=>(a._OrtAddRunConfigEntry=me.da)(m,x,k),a._OrtReleaseRunOptions=m=>(a._OrtReleaseRunOptions=me.ea)(m),a._OrtCreateBinding=m=>(a._OrtCreateBinding=me.fa)(m),a._OrtBindInput=(m,x,k)=>(a._OrtBindInput=me.ga)(m,x,k),a._OrtBindOutput=(m,x,k,A)=>(a._OrtBindOutput=me.ha)(m,x,k,A),a._OrtClearBoundOutputs=m=>(a._OrtClearBoundOutputs=me.ia)(m),a._OrtReleaseBinding=m=>(a._OrtReleaseBinding=me.ja)(m),a._OrtRunWithBinding=(m,x,k,A,F)=>(a._OrtRunWithBinding=me.ka)(m,x,k,A,F),a._OrtRun=(m,x,k,A,F,q,se,$e)=>(a._OrtRun=me.la)(m,x,k,A,F,q,se,$e),a._OrtEndProfiling=m=>(a._OrtEndProfiling=me.ma)(m),a._JsepOutput=(m,x,k)=>(a._JsepOutput=me.na)(m,x,k),a._JsepGetNodeName=m=>(a._JsepGetNodeName=me.oa)(m);var ka=()=>(ka=me.pa)(),Mi=a._malloc=m=>(Mi=a._malloc=me.qa)(m),Ca=a._free=m=>(Ca=a._free=me.ra)(m),Ta=m=>(Ta=me.ta)(m),Ia=()=>(Ia=me.ua)(),Aa=m=>(Aa=me.va)(m),Oa=m=>(Oa=me.wa)(m),Ma=m=>(Ma=me.ya)(m),za=()=>(za=me.za)(),Ra=m=>(Ra=me.Aa)(m),Pa=()=>(Pa=me.Ba)();a.___start_em_js=943100,a.___stop_em_js=943261;function _o(){var m=me;m=Object.assign({},m);var x=A=>()=>A()>>>0,k=A=>F=>A(F)>>>0;return m.pa=x(m.pa),m.qa=k(m.qa),m.ua=x(m.ua),m.wa=k(m.wa),m}a.stackAlloc=Oa,a.stackSave=Ia,a.stackRestore=Aa,a.UTF8ToString=ut,a.stringToUTF8=(m,x,k)=>$a(m,G,x,k),a.lengthBytesUTF8=ki;var br;Z=function m(){br||Jr(),br||(Z=m)};function Jr(){if(!(0n)}),XS=ma(()=>{}),ZS=ma(()=>{}),vv={};ga(vv,{cpus:()=>$v});var $v,JS=ee(()=>{$v=void 0}),eE=ma((e,t)=>{var n=(()=>{var r=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename<"u"&&(r=r||__filename),function(i={}){function a(){return H.buffer!=Z.buffer&&qe(),Z}function s(){return H.buffer!=Z.buffer&&qe(),V}function o(){return H.buffer!=Z.buffer&&qe(),ie}function l(){return H.buffer!=Z.buffer&&qe(),xe}function d(){return H.buffer!=Z.buffer&&qe(),Re}function c(){return H.buffer!=Z.buffer&&qe(),He}var u=i,f,h;u.ready=new Promise((p,w)=>{f=p,h=w}),u.mountExternalData=(p,w)=>{(u.cb||(u.cb=new Map)).set(p,w)},u.unmountExternalData=()=>{delete u.cb},u.jsepInit=(p,w,S,T,P,U,Y,ge)=>{u.Mb=p,u.wb=w,u.yb=S,u.kb=T,u.xb=P,u.Ea=U,u.zb=Y,u.Ab=ge,w=(he,fe,be)=>(...De)=>{let Ve=jn,D=fe==null?void 0:fe();De=he(...De);let Se=fe==null?void 0:fe();return D!==Se&&(he=Se,be(D),fe=be=null),jn!=Ve?Pb():De},S=he=>async(...fe)=>{try{if(u.bb)throw Error("Session already started");let be=u.bb={Cb:fe[0],errors:[]},De=await he(...fe);if(u.bb!==be)throw Error("Session mismatch");p.flush();let Ve=be.errors;if(0Se),0u._OrtRun,he=>u._OrtRun=he)),u._OrtRunWithBinding=S(w(u._OrtRunWithBinding,()=>u._OrtRunWithBinding,he=>u._OrtRunWithBinding=he)),u._OrtBindInput=w(u._OrtBindInput,()=>u._OrtBindInput,he=>u._OrtBindInput=he),u.jsepRegisterBuffer=(he,fe,be,De)=>p.registerBuffer(he,fe,be,De),u.jsepUnregisterBuffers=he=>{p.unregisterBuffers(he)},u.jsepGetBuffer=he=>p.getBuffer(he),u.jsepCreateDownloader=(he,fe,be)=>p.createDownloader(he,fe,be)};var g=Object.assign({},u),$="./this.program",E=(p,w)=>{throw w},y=typeof window=="object",_=typeof importScripts=="function",v=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",b=u.ENVIRONMENT_IS_PTHREAD||!1,C="";function I(p){return u.locateFile?u.locateFile(p,C):C+p}var O,M,W;if(v){var G=(yv(),fi(of)),z=(_v(),fi(lf));C=_?z.dirname(C)+"/":__dirname+"/",O=(w,S)=>(w=Qr(w)?new URL(w):z.normalize(w),G.readFileSync(w,S?void 0:"utf8")),W=w=>(w=O(w,!0),w.buffer||(w=new Uint8Array(w)),w),M=(w,S,T,P=!0)=>{w=Qr(w)?new URL(w):z.normalize(w),G.readFile(w,P?void 0:"utf8",(U,Y)=>{U?T(U):S(P?Y.buffer:Y)})},!u.thisProgram&&1{throw process.exitCode=w,S},u.inspect=()=>"[Emscripten Module object]";let p;try{p=XS()}catch(w){throw console.error('The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?'),w}global.Worker=p.Worker}else(y||_)&&(_?C=self.location.href:typeof document<"u"&&document.currentScript&&(C=document.currentScript.src),typeof r<"u"&&r&&(C=r),C.indexOf("blob:")!==0?C=C.substr(0,C.replace(/[?#].*/,"").lastIndexOf("/")+1):C="",v||(O=p=>{var w=new XMLHttpRequest;return w.open("GET",p,!1),w.send(null),w.responseText},_&&(W=p=>{var w=new XMLHttpRequest;return w.open("GET",p,!1),w.responseType="arraybuffer",w.send(null),new Uint8Array(w.response)}),M=(p,w,S)=>{var T=new XMLHttpRequest;T.open("GET",p,!0),T.responseType="arraybuffer",T.onload=()=>{T.status==200||T.status==0&&T.response?w(T.response):S()},T.onerror=S,T.send(null)}));v&&typeof performance>"u"&&(global.performance=ZS().performance);var K=console.log.bind(console),ae=console.error.bind(console);v&&(K=(...p)=>G.writeSync(1,p.join(" ")+` `),ae=(...p)=>G.writeSync(2,p.join(" ")+` `));var ue=K,R=ae;Object.assign(u,g),g=null,typeof WebAssembly!="object"&&vr("no native wasm support detected");var H,re,L=!1,X,Z,V,ie,xe,Re,He;function qe(){var p=H.buffer;u.HEAP8=Z=new Int8Array(p),u.HEAP16=new Int16Array(p),u.HEAPU8=V=new Uint8Array(p),u.HEAPU16=new Uint16Array(p),u.HEAP32=ie=new Int32Array(p),u.HEAPU32=xe=new Uint32Array(p),u.HEAPF32=Re=new Float32Array(p),u.HEAPF64=He=new Float64Array(p)}var Dt=16777216;if(b)H=u.wasmMemory;else if(u.wasmMemory)H=u.wasmMemory;else if(H=new WebAssembly.Memory({initial:Dt/65536,maximum:65536,shared:!0}),!(H.buffer instanceof SharedArrayBuffer))throw R("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"),v&&R("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and/or recent version)"),Error("bad memory");qe(),Dt=H.buffer.byteLength;var er=[],ht=[],at=[],Qt=0,cn=null;function Ei(){if(Qt--,Qt==0&&cn){var p=cn;cn=null,p()}}function vr(p){throw p="Aborted("+p+")",R(p),L=!0,X=1,p=new WebAssembly.RuntimeError(p+". Build with -sASSERTIONS for more info."),h(p),p}var va=p=>p.startsWith("data:application/octet-stream;base64,"),Qr=p=>p.startsWith("file://"),ut;ut="ort-wasm-simd-threaded.wasm",va(ut)||(ut=I(ut));function ki(p){if(W)return W(p);throw"both async and sync fetching of the wasm failed"}function $a(p){if(y||_){if(typeof fetch=="function"&&!Qr(p))return fetch(p,{credentials:"same-origin"}).then(w=>{if(!w.ok)throw"failed to load wasm binary file at '"+p+"'";return w.arrayBuffer()}).catch(()=>ki(p));if(M)return new Promise((w,S)=>{M(p,T=>w(new Uint8Array(T)),S)})}return Promise.resolve().then(()=>ki(p))}function tr(p,w,S){return $a(p).then(T=>WebAssembly.instantiate(T,w)).then(T=>T).then(S,T=>{R(`failed to asynchronously prepare wasm: ${T}`),vr(T)})}function uo(p,w){var S=ut;return typeof WebAssembly.instantiateStreaming!="function"||va(S)||Qr(S)||v||typeof fetch!="function"?tr(S,p,w):fetch(S,{credentials:"same-origin"}).then(T=>WebAssembly.instantiateStreaming(T,p).then(w,function(P){return R(`wasm streaming compile failed: ${P}`),R("falling back to ArrayBuffer instantiation"),tr(S,p,w)}))}var nr,Ci={932428:(p,w,S,T)=>{if(typeof u>"u"||!u.cb)return 1;if(p=_t(p>>>0),p.startsWith("./")&&(p=p.substring(2)),p=u.cb.get(p),!p)return 2;if(w>>>=0,S>>>=0,T>>>=0,w+S>p.byteLength)return 3;try{return s().set(p.subarray(w,w+S),T>>>0),0}catch{return 4}},932929:p=>u.wb(p),932962:p=>u.yb(p),932994:(p,w,S)=>{u.kb(p,w,S,!0)},933033:(p,w,S)=>{u.kb(p,w,S)},933066:p=>{u.Ea("Abs",p,void 0)},933117:p=>{u.Ea("Neg",p,void 0)},933168:p=>{u.Ea("Floor",p,void 0)},933221:p=>{u.Ea("Ceil",p,void 0)},933273:p=>{u.Ea("Reciprocal",p,void 0)},933331:p=>{u.Ea("Sqrt",p,void 0)},933383:p=>{u.Ea("Exp",p,void 0)},933434:p=>{u.Ea("Erf",p,void 0)},933485:p=>{u.Ea("Sigmoid",p,void 0)},933540:p=>{u.Ea("Log",p,void 0)},933591:p=>{u.Ea("Sin",p,void 0)},933642:p=>{u.Ea("Cos",p,void 0)},933693:p=>{u.Ea("Tan",p,void 0)},933744:p=>{u.Ea("Asin",p,void 0)},933796:p=>{u.Ea("Acos",p,void 0)},933848:p=>{u.Ea("Atan",p,void 0)},933900:p=>{u.Ea("Sinh",p,void 0)},933952:p=>{u.Ea("Cosh",p,void 0)},934004:p=>{u.Ea("Asinh",p,void 0)},934057:p=>{u.Ea("Acosh",p,void 0)},934110:p=>{u.Ea("Atanh",p,void 0)},934163:p=>{u.Ea("Tanh",p,void 0)},934215:p=>{u.Ea("Not",p,void 0)},934266:(p,w,S)=>{u.Ea("Clip",p,{min:w,max:S})},934335:p=>{u.Ea("Clip",p,void 0)},934387:(p,w)=>{u.Ea("Elu",p,{alpha:w})},934445:p=>{u.Ea("Relu",p,void 0)},934497:(p,w)=>{u.Ea("LeakyRelu",p,{alpha:w})},934561:(p,w)=>{u.Ea("ThresholdedRelu",p,{alpha:w})},934631:(p,w)=>{u.Ea("Cast",p,{to:w})},934689:p=>{u.Ea("Add",p,void 0)},934740:p=>{u.Ea("Sub",p,void 0)},934791:p=>{u.Ea("Mul",p,void 0)},934842:p=>{u.Ea("Div",p,void 0)},934893:p=>{u.Ea("Pow",p,void 0)},934944:p=>{u.Ea("Equal",p,void 0)},934997:p=>{u.Ea("Greater",p,void 0)},935052:p=>{u.Ea("GreaterOrEqual",p,void 0)},935114:p=>{u.Ea("Less",p,void 0)},935166:p=>{u.Ea("LessOrEqual",p,void 0)},935225:(p,w,S,T,P)=>{u.Ea("ReduceMean",p,{keepDims:!!w,noopWithEmptyAxes:!!S,axes:T?Array.from(o().subarray(T>>>0,P>>>0)):[]})},935384:(p,w,S,T,P)=>{u.Ea("ReduceMax",p,{keepDims:!!w,noopWithEmptyAxes:!!S,axes:T?Array.from(o().subarray(T>>>0,P>>>0)):[]})},935542:(p,w,S,T,P)=>{u.Ea("ReduceMin",p,{keepDims:!!w,noopWithEmptyAxes:!!S,axes:T?Array.from(o().subarray(T>>>0,P>>>0)):[]})},935700:(p,w,S,T,P)=>{u.Ea("ReduceProd",p,{keepDims:!!w,noopWithEmptyAxes:!!S,axes:T?Array.from(o().subarray(T>>>0,P>>>0)):[]})},935859:(p,w,S,T,P)=>{u.Ea("ReduceSum",p,{keepDims:!!w,noopWithEmptyAxes:!!S,axes:T?Array.from(o().subarray(T>>>0,P>>>0)):[]})},936017:(p,w,S,T,P)=>{u.Ea("ReduceL1",p,{keepDims:!!w,noopWithEmptyAxes:!!S,axes:T?Array.from(o().subarray(T>>>0,P>>>0)):[]})},936174:(p,w,S,T,P)=>{u.Ea("ReduceL2",p,{keepDims:!!w,noopWithEmptyAxes:!!S,axes:T?Array.from(o().subarray(T>>>0,P>>>0)):[]})},936331:(p,w,S,T,P)=>{u.Ea("ReduceLogSum",p,{keepDims:!!w,noopWithEmptyAxes:!!S,axes:T?Array.from(o().subarray(T>>>0,P>>>0)):[]})},936492:(p,w,S,T,P)=>{u.Ea("ReduceSumSquare",p,{keepDims:!!w,noopWithEmptyAxes:!!S,axes:T?Array.from(o().subarray(T>>>0,P>>>0)):[]})},936656:(p,w,S,T,P)=>{u.Ea("ReduceLogSumExp",p,{keepDims:!!w,noopWithEmptyAxes:!!S,axes:T?Array.from(o().subarray(T>>>0,P>>>0)):[]})},936820:p=>{u.Ea("Where",p,void 0)},936873:(p,w,S)=>{u.Ea("Transpose",p,{perm:w?Array.from(o().subarray(w>>>0,S>>>0)):[]})},936981:(p,w,S,T,P,U,Y,ge,he,fe,be,De,Ve,D,Se)=>{u.Ea("ConvTranspose",p,{format:he?"NHWC":"NCHW",autoPad:w,dilations:[S],group:T,kernel_shape:[P],pads:[U,Y],strides:[ge],wIsConst:()=>!!a()[fe>>>0],outputPadding:be?Array.from(o().subarray(be>>>0,De>>>0)):[],outputShape:Ve?Array.from(o().subarray(Ve>>>0,D>>>0)):[],activation:_t(Se)})},937383:(p,w,S,T,P,U,Y,ge,he,fe,be,De,Ve,D)=>{u.Ea("ConvTranspose",p,{format:ge?"NHWC":"NCHW",autoPad:w,dilations:Array.from(o().subarray(S>>>0,(S>>>0)+2>>>0)),group:T,kernelShape:Array.from(o().subarray(P>>>0,(P>>>0)+2>>>0)),pads:Array.from(o().subarray(U>>>0,(U>>>0)+4>>>0)),strides:Array.from(o().subarray(Y>>>0,(Y>>>0)+2>>>0)),wIsConst:()=>!!a()[he>>>0],outputPadding:fe?Array.from(o().subarray(fe>>>0,be>>>0)):[],outputShape:De?Array.from(o().subarray(De>>>0,Ve>>>0)):[],activation:_t(D)})},937948:(p,w,S,T,P,U,Y,ge,he,fe,be,De,Ve,D,Se)=>{u.Ea("ConvTranspose",p,{format:he?"NHWC":"NCHW",autoPad:w,dilations:[S],group:T,kernel_shape:[P],pads:[U,Y],strides:[ge],wIsConst:()=>!!a()[fe>>>0],outputPadding:be?Array.from(o().subarray(be>>>0,De>>>0)):[],outputShape:Ve?Array.from(o().subarray(Ve>>>0,D>>>0)):[],activation:_t(Se)})},938350:(p,w,S,T,P,U,Y,ge,he,fe,be,De,Ve,D)=>{u.Ea("ConvTranspose",p,{format:ge?"NHWC":"NCHW",autoPad:w,dilations:Array.from(o().subarray(S>>>0,(S>>>0)+2>>>0)),group:T,kernelShape:Array.from(o().subarray(P>>>0,(P>>>0)+2>>>0)),pads:Array.from(o().subarray(U>>>0,(U>>>0)+4>>>0)),strides:Array.from(o().subarray(Y>>>0,(Y>>>0)+2>>>0)),wIsConst:()=>!!a()[he>>>0],outputPadding:fe?Array.from(o().subarray(fe>>>0,be>>>0)):[],outputShape:De?Array.from(o().subarray(De>>>0,Ve>>>0)):[],activation:_t(D)})},938915:(p,w)=>{u.Ea("GlobalAveragePool",p,{format:w?"NHWC":"NCHW"})},939006:(p,w,S,T,P,U,Y,ge,he,fe,be,De,Ve,D,Se,Fe)=>{u.Ea("AveragePool",p,{format:Fe?"NHWC":"NCHW",auto_pad:w,ceil_mode:S,count_include_pad:T,storage_order:P,dilations:[U,Y],kernel_shape:[ge,he],pads:[fe,be,De,Ve],strides:[D,Se]})},939290:(p,w)=>{u.Ea("GlobalAveragePool",p,{format:w?"NHWC":"NCHW"})},939381:(p,w,S,T,P,U,Y,ge,he,fe,be,De,Ve,D,Se,Fe)=>{u.Ea("AveragePool",p,{format:Fe?"NHWC":"NCHW",auto_pad:w,ceil_mode:S,count_include_pad:T,storage_order:P,dilations:[U,Y],kernel_shape:[ge,he],pads:[fe,be,De,Ve],strides:[D,Se]})},939665:(p,w)=>{u.Ea("GlobalMaxPool",p,{format:w?"NHWC":"NCHW"})},939752:(p,w,S,T,P,U,Y,ge,he,fe,be,De,Ve,D,Se,Fe)=>{u.Ea("MaxPool",p,{format:Fe?"NHWC":"NCHW",auto_pad:w,ceil_mode:S,count_include_pad:T,storage_order:P,dilations:[U,Y],kernel_shape:[ge,he],pads:[fe,be,De,Ve],strides:[D,Se]})},940032:(p,w)=>{u.Ea("GlobalMaxPool",p,{format:w?"NHWC":"NCHW"})},940119:(p,w,S,T,P,U,Y,ge,he,fe,be,De,Ve,D,Se,Fe)=>{u.Ea("MaxPool",p,{format:Fe?"NHWC":"NCHW",auto_pad:w,ceil_mode:S,count_include_pad:T,storage_order:P,dilations:[U,Y],kernel_shape:[ge,he],pads:[fe,be,De,Ve],strides:[D,Se]})},940399:(p,w,S,T,P)=>{u.Ea("Gemm",p,{alpha:w,beta:S,transA:T,transB:P})},940503:p=>{u.Ea("MatMul",p,void 0)},940557:(p,w,S,T)=>{u.Ea("ArgMax",p,{keepDims:!!w,selectLastIndex:!!S,axis:T})},940665:(p,w,S,T)=>{u.Ea("ArgMin",p,{keepDims:!!w,selectLastIndex:!!S,axis:T})},940773:(p,w)=>{u.Ea("Softmax",p,{axis:w})},940836:(p,w)=>{u.Ea("Concat",p,{axis:w})},940896:(p,w,S,T,P)=>{u.Ea("Split",p,{axis:w,numOutputs:S,splitSizes:T?Array.from(o().subarray(T>>>0,P>>>0)):[]})},941036:p=>{u.Ea("Expand",p,void 0)},941090:(p,w)=>{u.Ea("Gather",p,{axis:Number(w)})},941161:(p,w)=>{u.Ea("GatherElements",p,{axis:Number(w)})},941240:(p,w,S,T,P,U,Y,ge,he,fe,be)=>{u.Ea("Resize",p,{antialias:w,axes:S?Array.from(o().subarray(S>>>0,T>>>0)):[],coordinateTransformMode:_t(P),cubicCoeffA:U,excludeOutside:Y,extrapolationValue:ge,keepAspectRatioPolicy:_t(he),mode:_t(fe),nearestMode:_t(be)})},941586:(p,w,S,T,P,U,Y)=>{u.Ea("Slice",p,{starts:w?Array.from(o().subarray(w>>>0,S>>>0)):[],ends:T?Array.from(o().subarray(T>>>0,P>>>0)):[],axes:U?Array.from(o().subarray(U>>>0,Y>>>0)):[]})},941802:p=>{u.Ea("Tile",p,void 0)},941854:(p,w,S)=>{u.Ea("LayerNormalization",p,{axis:Number(w),epsilon:Number(S)})},941961:(p,w,S)=>{u.Ea("InstanceNormalization",p,{epsilon:w,format:S?"NHWC":"NCHW"})},942075:(p,w,S)=>{u.Ea("InstanceNormalization",p,{epsilon:w,format:S?"NHWC":"NCHW"})},942189:p=>{u.Ea("Range",p,void 0)},942242:(p,w)=>{u.Ea("Einsum",p,{equation:_t(w)})},942323:(p,w,S,T,P)=>{u.Ea("Pad",p,{mode:w,value:S,pads:T?Array.from(o().subarray(T>>>0,P>>>0)):[]})},942450:(p,w,S,T,P,U)=>{u.Ea("BatchNormalization",p,{epsilon:w,momentum:S,spatial:!!P,trainingMode:!!T,format:U?"NHWC":"NCHW"})},942619:(p,w,S,T,P,U)=>{u.Ea("BatchNormalization",p,{epsilon:w,momentum:S,spatial:!!P,trainingMode:!!T,format:U?"NHWC":"NCHW"})},942788:(p,w,S)=>{u.Ea("CumSum",p,{exclusive:Number(w),reverse:Number(S)})},942885:(p,w,S,T,P,U,Y,ge,he)=>{u.Ea("Attention",p,{numHeads:w,isUnidirectional:S,maskFilterValue:T,scale:P,doRotary:U,qkvHiddenSizes:Y?Array.from(o().subarray(Number(ge)>>>0,Number(ge)+Y>>>0)):[],pastPresentShareBuffer:!!he})},943157:p=>{u.Ea("Gelu",p,void 0)},943209:(p,w,S,T,P,U)=>{u.Ea("MultiHeadAttention",p,{numHeads:w,isUnidirectional:S,maskFilterValue:T,scale:P,doRotary:U})},943368:p=>{u.Ea("BiasAdd",p,void 0)},943423:p=>{u.Ea("BiasSplitGelu",p,void 0)},943484:(p,w)=>{u.Ea("SkipLayerNormalization",p,{epsilon:w})},943565:(p,w,S,T,P,U,Y,ge,he,fe,be,De,Ve)=>{u.Ea("Conv",p,{format:he?"NHWC":"NCHW",auto_pad:w,dilations:[S],group:T,kernel_shape:[P],pads:U?Array.from(o().subarray(U>>>0,Y>>>0)):[],strides:[ge],w_is_const:()=>!!a()[fe>>>0],activation:_t(be),activation_params:De?Array.from(d().subarray(De>>>0,Ve>>>0)):[]})},943935:(p,w,S,T,P,U,Y,ge,he,fe,be,De,Ve,D,Se,Fe)=>{u.Ea("Conv",p,{format:De?"NHWC":"NCHW",auto_pad:w,dilations:[S,T],group:P,kernel_shape:[U,Y],pads:ge?Array.from(o().subarray(ge>>>0,he>>>0)):[],strides:[fe,be],w_is_const:()=>!!a()[Ve>>>0],activation:_t(D),activation_params:Se?Array.from(d().subarray(Se>>>0,Fe>>>0)):[]})},944326:p=>{u.zb(p)},944360:(p,w)=>u.Ab(p,w,u.bb.Cb,u.bb.errors)};function Xr(p){this.name="ExitStatus",this.message=`Program terminated with exit(${p})`,this.status=p}var Ti=p=>{p.terminate(),p.onmessage=()=>{}},Ii=p=>{ye.Ya.length==0&&(Xt(),ye.lb(ye.Ya[0]));var w=ye.Ya.pop();if(!w)return 6;ye.Za.push(w),ye.Qa[p.Xa]=w,w.Xa=p.Xa;var S={cmd:"run",start_routine:p.Db,arg:p.tb,pthread_ptr:p.Xa};return v&&w.unref(),w.postMessage(S,p.Jb),0},Un=0,Ai=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,co=(p,w,S)=>{w>>>=0;var T=w+S;for(S=w;p[S]&&!(S>=T);)++S;if(16P?T+=String.fromCharCode(P):(P-=65536,T+=String.fromCharCode(55296|P>>10,56320|P&1023))}}else T+=String.fromCharCode(P)}return T},_t=(p,w)=>(p>>>=0)?co(s(),p,w):"",po=p=>{var w=Lu();return p=p(),So(w),p};function Ke(p,w){var S=arguments.length-2,T=arguments;return po(()=>{for(var P=Fu(8*S),U=P>>>3,Y=0;Y>>0]=ge}return qf(p,S,P,w)})}function ba(p){var w;if(b)return Ke(0,1,p);X=p,0{if(X=p,b)throw Sa(p),"unwind";ba(p)},xa=p=>{p instanceof Xr||p=="unwind"||E(1,p)};function Wn(){for(var p=u.numThreads;p--;)Xt();er.unshift(()=>{Qt++,fo(()=>Ei())})}function Xt(){var p=I("ort-wasm-simd-threaded.worker.js");p=new Worker(p),ye.Ya.push(p)}function fo(p){b?p():Promise.all(ye.Ya.map(ye.lb)).then(p)}var ye={Ya:[],Za:[],pb:[],Qa:{},hb(){b?(ye.receiveObjectTransfer=ye.Bb,ye.threadInitTLS=ye.ob,ye.setExitStatus=ye.nb):Wn()},nb:p=>X=p,Nb:["$terminateWorker"],Eb:()=>{for(var p of ye.Za)Ti(p);for(p of ye.Ya)Ti(p);ye.Ya=[],ye.Za=[],ye.Qa=[]},mb:p=>{var w=p.Xa;delete ye.Qa[w],ye.Ya.push(p),ye.Za.splice(ye.Za.indexOf(p),1),p.Xa=0,Du(w)},Bb(){},ob(){ye.pb.forEach(p=>p())},lb:p=>new Promise(w=>{p.onmessage=U=>{U=U.data;var Y=U.cmd;if(U.targetThread&&U.targetThread!=xo()){var ge=ye.Qa[U.targetThread];ge?ge.postMessage(U,U.transferList):R(`Internal error! Worker sent a message "${Y}" to target pthread ${U.targetThread}, but that thread no longer exists!`)}else Y==="checkMailbox"?Jr():Y==="spawnThread"?Ii(U):Y==="cleanupThread"?ye.mb(ye.Qa[U.thread]):Y==="killThread"?(U=U.thread,Y=ye.Qa[U],delete ye.Qa[U],Ti(Y),Du(U),ye.Za.splice(ye.Za.indexOf(Y),1),Y.Xa=0):Y==="cancelThread"?ye.Qa[U.thread].postMessage({cmd:"cancel"}):Y==="loaded"?(p.loaded=!0,v&&!p.Xa&&p.unref(),w(p)):Y==="alert"?alert(`Thread ${U.threadId}: ${U.text}`):U.target==="setimmediate"?p.postMessage(U):Y==="callHandler"?u[U.handler](...U.args):Y&&R(`worker sent an unknown command ${Y}`)},p.onerror=U=>{throw R(`worker sent an error! ${U.filename}:${U.lineno}: ${U.message}`),U},v&&(p.on("message",U=>p.onmessage({data:U})),p.on("error",U=>p.onerror(U)));var S=[],T=["onExit"],P;for(P of T)u.hasOwnProperty(P)&&S.push(P);p.postMessage({cmd:"load",handlers:S,urlOrBlob:u.mainScriptUrlOrBlob||r,wasmMemory:H,wasmModule:re})})};u.PThread=ye;var Zr=p=>{for(;0{var p=xo(),w=l()[p+52>>>2>>>0];p=l()[p+56>>>2>>>0],Qf(w,w-p),So(w)};function Sa(p){if(b)return Ke(1,0,p);$r(p)}u.invokeEntryPoint=(p,w)=>{p=Xf.apply(null,[p,w]),0>>2>>>0]=w},this.rb=function(w){l()[this.gb+8>>>2>>>0]=w},this.hb=function(w,S){this.qb(),this.sb(w),this.rb(S)},this.qb=function(){l()[this.gb+16>>>2>>>0]=0}}var Oi=0;function ho(p,w,S,T){return b?Ke(2,1,p,w,S,T):mo(p,w,S,T)}function mo(p,w,S,T){if(p>>>=0,w>>>=0,S>>>=0,T>>>=0,typeof SharedArrayBuffer>"u")return R("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var P=[];return b&&P.length===0?ho(p,w,S,T):(p={Db:S,Xa:p,tb:T,Jb:P},b?(p.Lb="spawnThread",postMessage(p,P),0):Ii(p))}function go(p,w,S){return b?Ke(3,1,p,w,S):0}function yo(p,w){if(b)return Ke(4,1,p,w)}var Ea=p=>{for(var w=0,S=0;S=T?w++:2047>=T?w+=2:55296<=T&&57343>=T?(w+=4,++S):w+=3}return w},wo=(p,w,S,T)=>{if(S>>>=0,!(0=Y){var ge=p.charCodeAt(++U);Y=65536+((Y&1023)<<10)|ge&1023}if(127>=Y){if(S>=T)break;w[S++>>>0]=Y}else{if(2047>=Y){if(S+1>=T)break;w[S++>>>0]=192|Y>>6}else{if(65535>=Y){if(S+2>=T)break;w[S++>>>0]=224|Y>>12}else{if(S+3>=T)break;w[S++>>>0]=240|Y>>18,w[S++>>>0]=128|Y>>12&63}w[S++>>>0]=128|Y>>6&63}w[S++>>>0]=128|Y&63}}return w[S>>>0]=0,S-P},me=(p,w,S)=>wo(p,s(),w,S);function ka(p,w){if(b)return Ke(5,1,p,w)}function Mi(p,w,S){if(b)return Ke(6,1,p,w,S)}function Ca(p,w,S){return b?Ke(7,1,p,w,S):0}function Ta(p,w){if(b)return Ke(8,1,p,w)}function Ia(p,w,S){if(b)return Ke(9,1,p,w,S)}function Aa(p,w,S,T){if(b)return Ke(10,1,p,w,S,T)}function Oa(p,w,S,T){if(b)return Ke(11,1,p,w,S,T)}function Ma(p,w,S,T){if(b)return Ke(12,1,p,w,S,T)}function za(p){if(b)return Ke(13,1,p)}function Ra(p,w){if(b)return Ke(14,1,p,w)}function Pa(p,w,S){if(b)return Ke(15,1,p,w,S)}var _o=()=>{if(!(0>>=0,typeof Atomics.Kb=="function"&&(Atomics.Kb(o(),p>>>2,p).value.then(Jr),p+=128,Atomics.store(o(),p>>>2,1))}u.__emscripten_thread_mailbox_await=br;var Jr=()=>{var p=xo();if(p&&(br(p),!L))try{Kf(),_o()}catch(w){xa(w)}};u.checkMailbox=Jr;var m=[],x=p=>p%4===0&&(p%100!==0||p%400===0),k=[0,31,60,91,121,152,182,213,244,274,305,335],A=[0,31,59,90,120,151,181,212,243,273,304,334];function F(p,w,S,T,P,U,Y,ge){return b?Ke(16,1,p,w,S,T,P,U,Y,ge):-52}function q(p,w,S,T,P,U,Y){if(b)return Ke(17,1,p,w,S,T,P,U,Y)}var se=p=>{var w=Ea(p)+1,S=Bu(w);return S&&me(p,S,w),S},$e=[],ce=(p,w)=>{$e.length=0;for(var S;S=s()[p++>>>0];){var T=S!=105;T&=S!=112,w+=T&&w%8?4:0,$e.push(S==112?l()[w>>>2>>>0]:S==105?o()[w>>>2>>>0]:c()[w>>>3>>>0]),w+=T?8:4}return $e},pe={},we=()=>{if(!Ie){var p={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:$||"./this.program"},w;for(w in pe)pe[w]===void 0?delete p[w]:p[w]=pe[w];var S=[];for(w in p)S.push(`${w}=${p[w]}`);Ie=S}return Ie},Ie;function Le(p,w){if(b)return Ke(18,1,p,w);p>>>=0,w>>>=0;var S=0;return we().forEach((T,P)=>{var U=w+S;for(P=l()[p+4*P>>>2>>>0]=U,U=0;U>>0>>>0]=T.charCodeAt(U);a()[P>>>0>>>0]=0,S+=T.length+1}),0}function B(p,w){if(b)return Ke(19,1,p,w);p>>>=0,w>>>=0;var S=we();l()[p>>>2>>>0]=S.length;var T=0;return S.forEach(P=>T+=P.length+1),l()[w>>>2>>>0]=T,0}function ve(p){return b?Ke(20,1,p):52}function Me(p,w,S,T){return b?Ke(21,1,p,w,S,T):52}function Vn(p,w,S,T,P){return b?Ke(22,1,p,w,S,T,P):70}var vo=[null,[],[]];function Df(p,w,S,T){if(b)return Ke(23,1,p,w,S,T);w>>>=0,S>>>=0,T>>>=0;for(var P=0,U=0;U>>2>>>0],ge=l()[w+4>>>2>>>0];w+=8;for(var he=0;he>>0],be=vo[p];fe===0||fe===10?((p===1?ue:R)(co(be,0)),be.length=0):be.push(fe)}P+=ge}return l()[T>>>2>>>0]=P,0}var Nf=[31,29,31,30,31,30,31,31,30,31,30,31],Lf=[31,28,31,30,31,30,31,31,30,31,30,31];function Ab(p){var w=Array(Ea(p)+1);return wo(p,w,0,w.length),w}var Ob=(p,w)=>{a().set(p,w>>>0)};function Ff(p,w,S,T){function P(D,Se,Fe){for(D=typeof D=="number"?D.toString():D||"";D.lengthrh?-1:0ei-D.getDate())Se-=ei-D.getDate()+1,D.setDate(1),11>Fe?D.setMonth(Fe+1):(D.setMonth(0),D.setFullYear(D.getFullYear()+1));else{D.setDate(D.getDate()+Se);break}}return Fe=new Date(D.getFullYear()+1,0,4),Se=ge(new Date(D.getFullYear(),0,4)),Fe=ge(Fe),0>=Y(Se,D)?0>=Y(Fe,D)?D.getFullYear()+1:D.getFullYear():D.getFullYear()-1}p>>>=0,w>>>=0,S>>>=0,T>>>=0;var fe=l()[T+40>>>2>>>0];T={Hb:o()[T>>>2>>>0],Gb:o()[T+4>>>2>>>0],eb:o()[T+8>>>2>>>0],jb:o()[T+12>>>2>>>0],fb:o()[T+16>>>2>>>0],ab:o()[T+20>>>2>>>0],Wa:o()[T+24>>>2>>>0],$a:o()[T+28>>>2>>>0],Ob:o()[T+32>>>2>>>0],Fb:o()[T+36>>>2>>>0],Ib:fe?_t(fe):""},S=_t(S),fe={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"};for(var be in fe)S=S.replace(new RegExp(be,"g"),fe[be]);var De="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),Ve="January February March April May June July August September October November December".split(" ");fe={"%a":D=>De[D.Wa].substring(0,3),"%A":D=>De[D.Wa],"%b":D=>Ve[D.fb].substring(0,3),"%B":D=>Ve[D.fb],"%C":D=>U((D.ab+1900)/100|0,2),"%d":D=>U(D.jb,2),"%e":D=>P(D.jb,2," "),"%g":D=>he(D).toString().substring(2),"%G":D=>he(D),"%H":D=>U(D.eb,2),"%I":D=>(D=D.eb,D==0?D=12:12{for(var Se=0,Fe=0;Fe<=D.fb-1;Se+=(x(D.ab+1900)?Nf:Lf)[Fe++]);return U(D.jb+Se,3)},"%m":D=>U(D.fb+1,2),"%M":D=>U(D.Gb,2),"%n":()=>` `,"%p":D=>0<=D.eb&&12>D.eb?"AM":"PM","%S":D=>U(D.Hb,2),"%t":()=>" ","%u":D=>D.Wa||7,"%U":D=>U(Math.floor((D.$a+7-D.Wa)/7),2),"%V":D=>{var Se=Math.floor((D.$a+7-(D.Wa+6)%7)/7);if(2>=(D.Wa+371-D.$a-2)%7&&Se++,Se)Se==53&&(Fe=(D.Wa+371-D.$a)%7,Fe==4||Fe==3&&x(D.ab)||(Se=1));else{Se=52;var Fe=(D.Wa+7-D.$a-1)%7;(Fe==4||Fe==5&&x(D.ab%400-1))&&Se++}return U(Se,2)},"%w":D=>D.Wa,"%W":D=>U(Math.floor((D.$a+7-(D.Wa+6)%7)/7),2),"%y":D=>(D.ab+1900).toString().substring(2),"%Y":D=>D.ab+1900,"%z":D=>{D=D.Fb;var Se=0<=D;return D=Math.abs(D)/60,(Se?"+":"-")+("0000"+(D/60*100+D%60)).slice(-4)},"%Z":D=>D.Ib,"%%":()=>"%"},S=S.replace(/%%/g,"\0\0");for(be in fe)S.includes(be)&&(S=S.replace(new RegExp(be,"g"),fe[be](T)));return S=S.replace(/\0\0/g,"%"),be=Ab(S),be.length>w?0:(Ob(be,p),be.length-1)}var $o=p=>{try{p()}catch(w){vr(w)}};function Mb(){var p=de,w={};for(let[S,T]of Object.entries(p))w[S]=typeof T=="function"?function(){bo.push(S);try{return T.apply(null,arguments)}finally{L||(bo.pop(),jn&&xr===1&&bo.length===0&&(xr=0,Un+=1,$o(Jf),typeof Fibers<"u"&&Fibers.Pb()))}}:T;return w}var xr=0,jn=null,Uf=0,bo=[],Wf={},Vf={},zb=0,Pu=null,Rb=[];function Pb(){return new Promise((p,w)=>{Pu={resolve:p,reject:w}})}function Bb(){var p=Bu(65548),w=p+12;l()[p>>>2>>>0]=w,l()[p+4>>>2>>>0]=w+65536,w=bo[0];var S=Wf[w];return S===void 0&&(S=zb++,Wf[w]=S,Vf[S]=w),w=S,o()[p+8>>>2>>>0]=w,p}function Db(){var p=o()[jn+8>>>2>>>0];return p=de[Vf[p]],--Un,p()}function Nb(p){if(!L){if(xr===0){var w=!1,S=!1;p((T=0)=>{if(!L&&(Uf=T,w=!0,S)){xr=2,$o(()=>eh(jn)),typeof Browser<"u"&&Browser.ib.vb&&Browser.ib.resume(),T=!1;try{var P=Db()}catch(ge){P=ge,T=!0}var U=!1;if(!jn){var Y=Pu;Y&&(Pu=null,(T?Y.reject:Y.resolve)(P),U=!0)}if(T&&!U)throw P}}),S=!0,w||(xr=1,jn=Bb(),typeof Browser<"u"&&Browser.ib.vb&&Browser.ib.pause(),$o(()=>Zf(jn)))}else xr===2?(xr=0,$o(th),Gf(jn),jn=null,Rb.forEach(T=>{if(!L)try{T(),_o()}catch(P){xa(P)}})):vr(`invalid state: ${xr}`);return Uf}}function Lb(p){return Nb(w=>{p().then(w)})}ye.hb();var Fb=[ba,Sa,ho,go,yo,ka,Mi,Ca,Ta,Ia,Aa,Oa,Ma,za,Ra,Pa,F,q,Le,B,ve,Me,Vn,Df],Ub={r:function(p,w,S){return Lb(async()=>{await u.xb(p,w,S)})},b:function(p,w,S){throw p>>>=0,new Ru(p).hb(w>>>0,S>>>0),Oi=p,Oi},N:function(p){Hf(p>>>0,!_,1,!y,131072,!1),ye.ob()},l:function(p){p>>>=0,b?postMessage({cmd:"cleanupThread",thread:p}):ye.mb(ye.Qa[p])},J:mo,i:go,T:yo,F:ka,H:Mi,U:Ca,R:Ta,L:Ia,Q:Aa,p:Oa,G:Ma,D:za,S:Ra,E:Pa,q:()=>1,B:function(p,w){p>>>=0,p==w>>>0?setTimeout(()=>Jr()):b?postMessage({targetThread:p,cmd:"checkMailbox"}):(p=ye.Qa[p])&&p.postMessage({cmd:"checkMailbox"})},K:function(p,w,S,T){w>>>=0,m.length=S,T=T>>>0>>>3;for(var P=0;P>>0];return p=0>p?Ci[-p-1]:Fb[p],ye.ub=w,w=p.apply(null,m),ye.ub=0,w},M:br,W:function(p){v&&ye.Qa[p>>>0].ref()},u:function(p,w,S){p=w+2097152>>>0<4194305-!!p?(p>>>0)+4294967296*w:NaN,S>>>=0,p=new Date(1e3*p),o()[S>>>2>>>0]=p.getUTCSeconds(),o()[S+4>>>2>>>0]=p.getUTCMinutes(),o()[S+8>>>2>>>0]=p.getUTCHours(),o()[S+12>>>2>>>0]=p.getUTCDate(),o()[S+16>>>2>>>0]=p.getUTCMonth(),o()[S+20>>>2>>>0]=p.getUTCFullYear()-1900,o()[S+24>>>2>>>0]=p.getUTCDay(),p=(p.getTime()-Date.UTC(p.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,o()[S+28>>>2>>>0]=p},v:function(p,w,S){p=w+2097152>>>0<4194305-!!p?(p>>>0)+4294967296*w:NaN,S>>>=0,p=new Date(1e3*p),o()[S>>>2>>>0]=p.getSeconds(),o()[S+4>>>2>>>0]=p.getMinutes(),o()[S+8>>>2>>>0]=p.getHours(),o()[S+12>>>2>>>0]=p.getDate(),o()[S+16>>>2>>>0]=p.getMonth(),o()[S+20>>>2>>>0]=p.getFullYear()-1900,o()[S+24>>>2>>>0]=p.getDay(),w=(x(p.getFullYear())?k:A)[p.getMonth()]+p.getDate()-1|0,o()[S+28>>>2>>>0]=w,o()[S+36>>>2>>>0]=-(60*p.getTimezoneOffset()),w=new Date(p.getFullYear(),6,1).getTimezoneOffset();var T=new Date(p.getFullYear(),0,1).getTimezoneOffset();p=(w!=T&&p.getTimezoneOffset()==Math.min(T,w))|0,o()[S+32>>>2>>>0]=p},w:function(p){p>>>=0;var w=new Date(o()[p+20>>>2>>>0]+1900,o()[p+16>>>2>>>0],o()[p+12>>>2>>>0],o()[p+8>>>2>>>0],o()[p+4>>>2>>>0],o()[p>>>2>>>0],0),S=o()[p+32>>>2>>>0],T=w.getTimezoneOffset(),P=new Date(w.getFullYear(),6,1).getTimezoneOffset(),U=new Date(w.getFullYear(),0,1).getTimezoneOffset(),Y=Math.min(U,P);return 0>S?o()[p+32>>>2>>>0]=+(P!=U&&Y==T):0>>2>>>0]=w.getDay(),S=(x(w.getFullYear())?k:A)[w.getMonth()]+w.getDate()-1|0,o()[p+28>>>2>>>0]=S,o()[p>>>2>>>0]=w.getSeconds(),o()[p+4>>>2>>>0]=w.getMinutes(),o()[p+8>>>2>>>0]=w.getHours(),o()[p+12>>>2>>>0]=w.getDate(),o()[p+16>>>2>>>0]=w.getMonth(),o()[p+20>>>2>>>0]=w.getYear(),p=w.getTime(),isNaN(p)?(o()[jf()>>>2>>>0]=61,p=-1):p/=1e3,Yf((nr=p,1<=+Math.abs(nr)?0>>0:~~+Math.ceil((nr-+(~~nr>>>0))/4294967296)>>>0:0)),p>>>0},s:F,t:q,A:function(p,w,S){function T(fe){return(fe=fe.toTimeString().match(/\(([A-Za-z ]+)\)$/))?fe[1]:"GMT"}p>>>=0,w>>>=0,S>>>=0;var P=new Date().getFullYear(),U=new Date(P,0,1),Y=new Date(P,6,1);P=U.getTimezoneOffset();var ge=Y.getTimezoneOffset(),he=Math.max(P,ge);l()[p>>>2>>>0]=60*he,o()[w>>>2>>>0]=+(P!=ge),p=T(U),w=T(Y),p=se(p),w=se(w),ge>>2>>>0]=p,l()[S+4>>>2>>>0]=w):(l()[S>>>2>>>0]=w,l()[S+4>>>2>>>0]=p)},d:()=>{vr("")},c:function(p,w,S){return p>>>=0,w=ce(w>>>0,S>>>0),Ci[p].apply(null,w)},k:function(p,w,S){return p>>>=0,w=ce(w>>>0,S>>>0),Ci[p].apply(null,w)},m:()=>{},j:()=>Date.now(),V:()=>{throw Un+=1,"unwind"},C:function(){return 4294901760},f:()=>performance.timeOrigin+performance.now(),g:()=>v?(JS(),fi(vv)).cpus().length:navigator.hardwareConcurrency,y:function(p){p>>>=0;var w=s().length;if(p<=w||4294901760=S;S*=2){var T=w*(1+.2/S);T=Math.min(T,p+100663296);var P=Math;T=Math.max(p,T);e:{P=(P.min.call(P,4294901760,T+(65536-T%65536)%65536)-H.buffer.byteLength+65535)/65536;try{H.grow(P),qe();var U=1;break e}catch{}U=void 0}if(U)return!0}return!1},O:Le,P:B,I:$r,h:ve,o:Me,x:Vn,n:Df,a:H||u.wasmMemory,z:Ff,e:function(p,w,S,T){return Ff(p>>>0,w>>>0,S>>>0,T>>>0)}},de=function(){function p(S,T){return de=S.exports,de=Mb(),de=Wb(),ye.pb.push(de.Da),ht.unshift(de.X),re=T,Ei(),de}var w={a:Ub};if(Qt++,u.instantiateWasm)try{return u.instantiateWasm(w,p)}catch(S){R(`Module.instantiateWasm callback failed with error: ${S}`),h(S)}return uo(w,function(S){p(S.instance,S.module)}).catch(h),{}}();u._OrtInit=(p,w)=>(u._OrtInit=de.Y)(p,w),u._OrtGetLastError=(p,w)=>(u._OrtGetLastError=de.Z)(p,w),u._OrtCreateSessionOptions=(p,w,S,T,P,U,Y,ge,he,fe)=>(u._OrtCreateSessionOptions=de._)(p,w,S,T,P,U,Y,ge,he,fe),u._OrtAppendExecutionProvider=(p,w)=>(u._OrtAppendExecutionProvider=de.$)(p,w),u._OrtAddFreeDimensionOverride=(p,w,S)=>(u._OrtAddFreeDimensionOverride=de.aa)(p,w,S),u._OrtAddSessionConfigEntry=(p,w,S)=>(u._OrtAddSessionConfigEntry=de.ba)(p,w,S),u._OrtReleaseSessionOptions=p=>(u._OrtReleaseSessionOptions=de.ca)(p),u._OrtCreateSession=(p,w,S)=>(u._OrtCreateSession=de.da)(p,w,S),u._OrtReleaseSession=p=>(u._OrtReleaseSession=de.ea)(p),u._OrtGetInputOutputCount=(p,w,S)=>(u._OrtGetInputOutputCount=de.fa)(p,w,S),u._OrtGetInputName=(p,w)=>(u._OrtGetInputName=de.ga)(p,w),u._OrtGetOutputName=(p,w)=>(u._OrtGetOutputName=de.ha)(p,w),u._OrtFree=p=>(u._OrtFree=de.ia)(p),u._OrtCreateTensor=(p,w,S,T,P,U)=>(u._OrtCreateTensor=de.ja)(p,w,S,T,P,U),u._OrtGetTensorData=(p,w,S,T,P)=>(u._OrtGetTensorData=de.ka)(p,w,S,T,P),u._OrtReleaseTensor=p=>(u._OrtReleaseTensor=de.la)(p),u._OrtCreateRunOptions=(p,w,S,T)=>(u._OrtCreateRunOptions=de.ma)(p,w,S,T),u._OrtAddRunConfigEntry=(p,w,S)=>(u._OrtAddRunConfigEntry=de.na)(p,w,S),u._OrtReleaseRunOptions=p=>(u._OrtReleaseRunOptions=de.oa)(p),u._OrtCreateBinding=p=>(u._OrtCreateBinding=de.pa)(p),u._OrtBindInput=(p,w,S)=>(u._OrtBindInput=de.qa)(p,w,S),u._OrtBindOutput=(p,w,S,T)=>(u._OrtBindOutput=de.ra)(p,w,S,T),u._OrtClearBoundOutputs=p=>(u._OrtClearBoundOutputs=de.sa)(p),u._OrtReleaseBinding=p=>(u._OrtReleaseBinding=de.ta)(p),u._OrtRunWithBinding=(p,w,S,T,P)=>(u._OrtRunWithBinding=de.ua)(p,w,S,T,P),u._OrtRun=(p,w,S,T,P,U,Y,ge)=>(u._OrtRun=de.va)(p,w,S,T,P,U,Y,ge),u._OrtEndProfiling=p=>(u._OrtEndProfiling=de.wa)(p),u._JsepOutput=(p,w,S)=>(u._JsepOutput=de.xa)(p,w,S),u._JsepGetNodeName=p=>(u._JsepGetNodeName=de.ya)(p);var jf=()=>(jf=de.za)(),xo=u._pthread_self=()=>(xo=u._pthread_self=de.Aa)(),Bu=u._malloc=p=>(Bu=u._malloc=de.Ba)(p),Gf=u._free=p=>(Gf=u._free=de.Ca)(p);u.__emscripten_tls_init=()=>(u.__emscripten_tls_init=de.Da)();var Hf=u.__emscripten_thread_init=(p,w,S,T,P,U)=>(Hf=u.__emscripten_thread_init=de.Fa)(p,w,S,T,P,U);u.__emscripten_thread_crashed=()=>(u.__emscripten_thread_crashed=de.Ga)();var qf=(p,w,S,T)=>(qf=de.Ha)(p,w,S,T),Du=p=>(Du=de.Ia)(p),Nu=u.__emscripten_thread_exit=p=>(Nu=u.__emscripten_thread_exit=de.Ja)(p),Kf=()=>(Kf=de.Ka)(),Yf=p=>(Yf=de.La)(p),Qf=(p,w)=>(Qf=de.Ma)(p,w),Lu=()=>(Lu=de.Na)(),So=p=>(So=de.Oa)(p),Fu=p=>(Fu=de.Pa)(p),Xf=u.dynCall_ii=(p,w)=>(Xf=u.dynCall_ii=de.Ra)(p,w),Zf=p=>(Zf=de.Sa)(p),Jf=()=>(Jf=de.Ta)(),eh=p=>(eh=de.Ua)(p),th=()=>(th=de.Va)();u.___start_em_js=944472,u.___stop_em_js=944633;function Wb(){var p=de;p=Object.assign({},p);var w=T=>()=>T()>>>0,S=T=>P=>T(P)>>>0;return p.za=w(p.za),p.Aa=w(p.Aa),p.Ba=S(p.Ba),p.emscripten_main_runtime_thread_id=w(p.emscripten_main_runtime_thread_id),p.Na=w(p.Na),p.Pa=S(p.Pa),p}u.wasmMemory=H,u.stackAlloc=Fu,u.stackSave=Lu,u.stackRestore=So,u.keepRuntimeAlive=()=>0n)}),tE=ma((e,t)=>{t.exports='"use strict";var Module={},ENVIRONMENT_IS_NODE=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string";if(ENVIRONMENT_IS_NODE){var nodeWorkerThreads=require("worker_threads"),parentPort=nodeWorkerThreads.parentPort;parentPort.on("message",e=>onmessage({data:e}));var fs=require("fs"),vm=require("vm");Object.assign(global,{self:global,require,Module,location:{href:__filename},Worker:nodeWorkerThreads.Worker,importScripts:e=>vm.runInThisContext(fs.readFileSync(e,"utf8"),{filename:e}),postMessage:e=>parentPort.postMessage(e),performance:global.performance||{now:Date.now}})}var initializedJS=!1;function threadPrintErr(){var e=Array.prototype.slice.call(arguments).join(" ");if(ENVIRONMENT_IS_NODE){fs.writeSync(2,e+`\n`);return}console.error(e)}function threadAlert(){var e=Array.prototype.slice.call(arguments).join(" ");postMessage({cmd:"alert",text:e,threadId:Module._pthread_self()})}var err=threadPrintErr;self.alert=threadAlert,Module.instantiateWasm=(e,t)=>{var a=Module.wasmModule;Module.wasmModule=null;var r=new WebAssembly.Instance(a,e);return t(r)},self.onunhandledrejection=e=>{throw e.reason||e};function handleMessage(e){try{if(e.data.cmd==="load"){let a=[];self.onmessage=r=>a.push(r),self.startWorker=r=>{Module=r,postMessage({cmd:"loaded"});for(let s of a)handleMessage(s);self.onmessage=handleMessage},Module.wasmModule=e.data.wasmModule;for(const r of e.data.handlers)Module[r]=(...s)=>{postMessage({cmd:"callHandler",handler:r,args:s})};if(Module.wasmMemory=e.data.wasmMemory,Module.buffer=Module.wasmMemory.buffer,Module.ENVIRONMENT_IS_PTHREAD=!0,typeof e.data.urlOrBlob=="string")importScripts(e.data.urlOrBlob);else{var t=URL.createObjectURL(e.data.urlOrBlob);importScripts(t),URL.revokeObjectURL(t)}ortWasmThreaded(Module)}else if(e.data.cmd==="run"){Module.__emscripten_thread_init(e.data.pthread_ptr,0,0,1),Module.__emscripten_thread_mailbox_await(e.data.pthread_ptr),Module.establishStackSpace(),Module.PThread.receiveObjectTransfer(e.data),Module.PThread.threadInitTLS(),initializedJS||(initializedJS=!0);try{Module.invokeEntryPoint(e.data.start_routine,e.data.arg)}catch(a){if(a!="unwind")throw a}}else e.data.cmd==="cancel"?Module._pthread_self()&&Module.__emscripten_thread_exit(-1):e.data.target==="setimmediate"||(e.data.cmd==="checkMailbox"?initializedJS&&Module.checkMailbox():e.data.cmd&&(err(`worker.js received unknown command ${e.data.cmd}`),err(e.data)))}catch(a){throw Module.__emscripten_thread_crashed?.(),a}}self.onmessage=handleMessage;\n'}),ym,wm,gd,Ho,Ha,yd,_m,vm,$m,bv,gt,Hs=ee(()=>{ym=QS(),wm=eE(),Ho=!1,Ha=!1,yd=!1,_m=e=>{if(e===1)return!1;if(typeof SharedArrayBuffer>"u")return typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+e+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),!1;typeof process<"u"&&process.versions&&process.versions.node&&console.warn("env.wasm.numThreads is set to "+e+", however, currently onnxruntime-web does not support multi-threads in Node.js. Please consider using onnxruntime-node for performance critical scenarios.");try{return typeof MessageChannel<"u"&&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}},vm=()=>{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,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch{return!1}},$m=(e,t)=>e?t?"ort-wasm-simd-threaded.wasm":"ort-wasm-simd.wasm":t?"ort-wasm-threaded.wasm":"ort-wasm.wasm",bv=async e=>{if(Ho)return Promise.resolve();if(Ha)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(yd)throw new Error("previous call to 'initializeWebAssembly()' failed.");Ha=!0;let t=e.initTimeout,n=e.numThreads,r=e.simd,i=_m(n),a=r&&vm(),s=e.wasmPaths,o=typeof s=="string"?s:void 0,l=$m(a,i),d=typeof s=="object"?s[l]:void 0,c=!1,u=[];if(t>0&&u.push(new Promise(f=>{setTimeout(()=>{c=!0,f()},t)})),u.push(new Promise((f,h)=>{let g=i?wm:ym,$={locateFile:(E,y)=>{if(i&&E.endsWith(".worker.js")&&typeof Blob<"u")return URL.createObjectURL(new Blob([tE()],{type:"text/javascript"}));if(E.endsWith(".wasm")){if(d)return d;let _=o??y;return l==="ort-wasm-simd.wasm"?_+"ort-wasm-simd.jsep.wasm":l==="ort-wasm-simd-threaded.wasm"?_+"ort-wasm-simd-threaded.jsep.wasm":_+l}return y+E}};if(i)if($.numThreads=n,typeof Blob>"u")$.mainScriptUrlOrBlob=(void 0)(__dirname,"ort-wasm-threaded.js");else{let E=`var ortWasmThreaded=${g.toString()};`;$.mainScriptUrlOrBlob=new Blob([E],{type:"text/javascript"})}g($).then(E=>{Ha=!1,Ho=!0,gd=E,f()},E=>{Ha=!1,yd=!0,h(E)})})),await Promise.race(u),c)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},gt=()=>{if(Ho&&gd)return gd;throw new Error("WebAssembly is not initialized yet.")}}),mt,Hl,Je,uf=ee(()=>{Hs(),mt=(e,t)=>{let n=gt(),r=n.lengthBytesUTF8(e)+1,i=n._malloc(r);return n.stringToUTF8(e,i,r),t.push(i),i},Hl=(e,t,n,r)=>{if(typeof e=="object"&&e!==null){if(n.has(e))throw new Error("Circular reference in options");n.add(e)}Object.entries(e).forEach(([i,a])=>{let s=t?t+i:i;if(typeof a=="object")Hl(a,s+".",n,r);else if(typeof a=="string"||typeof a=="number")r(s,a.toString());else if(typeof a=="boolean")r(s,a?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof a}`)})},Je=e=>{let t=gt(),n=t.stackSave();try{let r=t.stackAlloc(8);t._OrtGetLastError(r,r+4);let i=t.HEAP32[r/4],a=t.HEAPU32[r/4+1],s=a?t.UTF8ToString(a):"";throw new Error(`${e} ERROR_CODE: ${i}, ERROR_MESSAGE: ${s}`)}finally{t.stackRestore(n)}}}),xv,nE=ee(()=>{Hs(),uf(),xv=e=>{let t=gt(),n=0,r=[],i=e||{};try{if((e==null?void 0:e.logSeverityLevel)===void 0)i.logSeverityLevel=2;else if(typeof e.logSeverityLevel!="number"||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${e.logSeverityLevel}`);if((e==null?void 0:e.logVerbosityLevel)===void 0)i.logVerbosityLevel=0;else if(typeof e.logVerbosityLevel!="number"||!Number.isInteger(e.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);(e==null?void 0:e.terminate)===void 0&&(i.terminate=!1);let a=0;return(e==null?void 0:e.tag)!==void 0&&(a=mt(e.tag,r)),n=t._OrtCreateRunOptions(i.logSeverityLevel,i.logVerbosityLevel,!!i.terminate,a),n===0&&Je("Can't create run options."),(e==null?void 0:e.extra)!==void 0&&Hl(e.extra,"",new WeakSet,(s,o)=>{let l=mt(s,r),d=mt(o,r);t._OrtAddRunConfigEntry(n,l,d)!==0&&Je(`Can't set a run config entry: ${s} - ${o}.`)}),[n,r]}catch(a){throw n!==0&&t._OrtReleaseRunOptions(n),r.forEach(s=>t._free(s)),a}}}),bm,xm,Sm,Em,Sv,rE=ee(()=>{Hs(),uf(),bm=e=>{switch(e){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${e}`)}},xm=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},Sm=e=>{e.extra||(e.extra={}),e.extra.session||(e.extra.session={});let t=e.extra.session;t.use_ort_model_bytes_directly||(t.use_ort_model_bytes_directly="1"),e.executionProviders&&e.executionProviders.some(n=>(typeof n=="string"?n:n.name)==="webgpu")&&(e.enableMemPattern=!1)},Em=(e,t,n)=>{for(let r of t){let i=typeof r=="string"?r:r.name;switch(i){case"webnn":if(i="WEBNN",typeof r!="string"){let s=r;if(s!=null&&s.deviceType){let o=mt("deviceType",n),l=mt(s.deviceType,n);gt()._OrtAddSessionConfigEntry(e,o,l)!==0&&Je(`Can't set a session config entry: 'deviceType' - ${s.deviceType}.`)}if(s!=null&&s.numThreads){let o=s.numThreads;(typeof o!="number"||!Number.isInteger(o)||o<0)&&(o=0);let l=mt("numThreads",n),d=mt(o.toString(),n);gt()._OrtAddSessionConfigEntry(e,l,d)!==0&&Je(`Can't set a session config entry: 'numThreads' - ${s.numThreads}.`)}if(s!=null&&s.powerPreference){let o=mt("powerPreference",n),l=mt(s.powerPreference,n);gt()._OrtAddSessionConfigEntry(e,o,l)!==0&&Je(`Can't set a session config entry: 'powerPreference' - ${s.powerPreference}.`)}}break;case"webgpu":if(i="JS",typeof r!="string"){let s=r;if(s!=null&&s.preferredLayout){if(s.preferredLayout!=="NCHW"&&s.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${s.preferredLayout}`);let o=mt("preferredLayout",n),l=mt(s.preferredLayout,n);gt()._OrtAddSessionConfigEntry(e,o,l)!==0&&Je(`Can't set a session config entry: 'preferredLayout' - ${s.preferredLayout}.`)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${i}`)}let a=mt(i,n);gt()._OrtAppendExecutionProvider(e,a)!==0&&Je(`Can't append execution provider: ${i}.`)}},Sv=e=>{let t=gt(),n=0,r=[],i=e||{};Sm(i);try{let a=bm(i.graphOptimizationLevel??"all"),s=xm(i.executionMode??"sequential"),o=typeof i.logId=="string"?mt(i.logId,r):0,l=i.logSeverityLevel??2;if(!Number.isInteger(l)||l<0||l>4)throw new Error(`log serverity level is not valid: ${l}`);let d=i.logVerbosityLevel??0;if(!Number.isInteger(d)||d<0||d>4)throw new Error(`log verbosity level is not valid: ${d}`);let c=typeof i.optimizedModelFilePath=="string"?mt(i.optimizedModelFilePath,r):0;if(n=t._OrtCreateSessionOptions(a,!!i.enableCpuMemArena,!!i.enableMemPattern,s,!!i.enableProfiling,0,o,l,d,c),n===0&&Je("Can't create session options."),i.executionProviders&&Em(n,i.executionProviders,r),i.freeDimensionOverrides)for(let[u,f]of Object.entries(i.freeDimensionOverrides)){if(typeof u!="string")throw new Error(`free dimension override name must be a string: ${u}`);if(typeof f!="number"||!Number.isInteger(f)||f<0)throw new Error(`free dimension override value must be a non-negative integer: ${f}`);let h=mt(u,r);t._OrtAddFreeDimensionOverride(n,h,f)!==0&&Je(`Can't set a free dimension override: ${u} - ${f}.`)}return i.extra!==void 0&&Hl(i.extra,"",new WeakSet,(u,f)=>{let h=mt(u,r),g=mt(f,r);t._OrtAddSessionConfigEntry(n,h,g)!==0&&Je(`Can't set a session config entry: ${u} - ${f}.`)}),[n,r]}catch(a){throw n!==0&&t._OrtReleaseSessionOptions(n),r.forEach(s=>t._free(s)),a}}}),Fc,Kn,ql,df,Kl,cf,Uc,lt=ee(()=>{Fc=e=>{switch(e){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float16":return 10;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;default:throw new Error(`unsupported data type: ${e}`)}},Kn=e=>{switch(e){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 10:return"float16";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";default:throw new Error(`unsupported data type: ${e}`)}},ql=e=>[void 0,4,1,1,2,2,4,8,void 0,1,2,8,4,8,void 0,void 0,void 0][e],df=e=>{switch(e){case"float16":return Uint16Array;case"float32":return Float32Array;case"uint8":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"bool":return Uint8Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${e}`)}},Kl=e=>{switch(e){case"verbose":return 0;case"info":return 1;case"warning":return 2;case"error":return 3;case"fatal":return 4;default:throw new Error(`unsupported logging level: ${e}`)}},cf=e=>e==="float32"||e==="int32"||e==="int64"||e==="bool"||e==="float16"||e==="uint32",Uc=e=>{switch(e){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;default:throw new Error(`unsupported data location: ${e}`)}}}),Yl,Ev=ee(()=>{Yl=async e=>{if(typeof e=="string")if(typeof process<"u"&&process.versions&&process.versions.node)try{return new Uint8Array(await(void 0)(e))}catch(t){if(t.code==="ERR_FS_FILE_TOO_LARGE"){let n=(void 0)(e),r=[];for await(let i of n)r.push(i);return new Uint8Array(Buffer.concat(r))}throw t}else{let t=await fetch(e);if(!t.ok)throw new Error(`failed to load external data file: ${e}`);let n=t.headers.get("Content-Length"),r=n?parseInt(n,10):0;if(r<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw new Error(`failed to load external data file: ${e}, no response body.`);let i=t.body.getReader(),a;try{a=new ArrayBuffer(r)}catch(o){if(o instanceof RangeError){let l=Math.ceil(r/65536);a=new WebAssembly.Memory({initial:l,maximum:l}).buffer}else throw o}let s=0;for(;;){let{done:o,value:l}=await i.read();if(o)break;let d=l.byteLength;new Uint8Array(a,s,d).set(l),s+=d}return new Uint8Array(a,0,r)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),km,Cm,Tm,Im,kv,Am,$t,bi=ee(()=>{lt(),km=["V","I","W","E","F"],Cm=(e,t)=>{console.log(`[${km[e]},${new Date().toISOString()}]${t}`)},kv=(e,t)=>{Tm=e,Im=t},Am=(e,t)=>{let n=Kl(e),r=Kl(Tm);n>=r&&Cm(n,typeof t=="function"?t():t)},$t=(...e)=>{Im&&Am(...e)}}),Cv,iE=ee(()=>{lt(),Cv=(e,t)=>new(df(t))(e)}),pf=ee(()=>{}),qa,Om,wd,Wc,Mm,Tv,aE=ee(()=>{bi(),pf(),qa=e=>Math.ceil(e/16)*16,Om=1,wd=()=>Om++,Wc=async(e,t,n,r)=>{let i=qa(n),a=e.device.createBuffer({size:i,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let s=e.getCommandEncoder();e.endComputePass(),s.copyBufferToBuffer(t,0,a,0,i),e.flush(),await a.mapAsync(GPUMapMode.READ);let o=a.getMappedRange();if(r){let l=r();return l.set(new Uint8Array(o,0,n)),l}else return new Uint8Array(o.slice(0,n))}finally{a.destroy()}},Mm=class{constructor(e){this.backend=e,this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.buffersForUploadingPending=[],this.buffersPending=[],this.externalBuffers=new Map}upload(e,t){let n=t.buffer,r=t.byteOffset,i=t.byteLength,a=qa(i),s=this.storageCache.get(e);if(!s)throw new Error("gpu data for uploading does not exist");if(s.originalSize!==i)throw new Error(`inconsistent data size. gpu data size=${s.originalSize}, data size=${i}`);let o=this.backend.device.createBuffer({mappedAtCreation:!0,size:a,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),l=o.getMappedRange();new Uint8Array(l).set(new Uint8Array(n,r,i)),o.unmap();let d=this.backend.getCommandEncoder();this.backend.endComputePass(),d.copyBufferToBuffer(o,0,s.gpuData.buffer,0,a),$t("verbose",()=>`[WebGPU] GpuDataManager.upload(id=${e})`),this.buffersForUploadingPending.push(o)}memcpy(e,t){let n=this.storageCache.get(e);if(!n)throw new Error("source gpu data for memcpy does not exist");let r=this.storageCache.get(t);if(!r)throw new Error("destination gpu data for memcpy does not exist");if(n.originalSize!==r.originalSize)throw new Error("inconsistent source and destination gpu data size");let i=qa(n.originalSize),a=this.backend.getCommandEncoder();this.backend.endComputePass(),a.copyBufferToBuffer(n.gpuData.buffer,0,r.gpuData.buffer,0,i)}registerExternalBuffer(e,t,n){let r;if(n){if(r=this.externalBuffers.get(n),r===void 0)throw new Error("previous buffer is not registered");if(e===n)return $t("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${r}, buffer is the same, skip.`),r;this.externalBuffers.delete(n)}else r=wd();return this.storageCache.set(r,{gpuData:{id:r,type:0,buffer:e},originalSize:t}),this.externalBuffers.set(e,r),$t("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${r}, registered.`),r}unregisterExternalBuffer(e){let t=this.externalBuffers.get(e);t!==void 0&&(this.storageCache.delete(t),this.externalBuffers.delete(e),$t("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${t}`))}create(e,t=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let n=qa(e),r,i=(t&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,a=(t&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(i||a){let o=i?this.freeBuffers:this.freeUniformBuffers,l=o.get(n);l||(l=[],o.set(n,l)),l.length>0?r=l.pop():r=this.backend.device.createBuffer({size:n,usage:t})}else r=this.backend.device.createBuffer({size:n,usage:t});let s={id:wd(),type:0,buffer:r};return this.storageCache.set(s.id,{gpuData:s,originalSize:e}),$t("verbose",()=>`[WebGPU] GpuDataManager.create(size=${e}) => id=${s.id}`),s}get(e){var t;return(t=this.storageCache.get(e))==null?void 0:t.gpuData}release(e){let t=this.storageCache.get(e);if(!t)throw new Error("releasing data does not exist");return $t("verbose",()=>`[WebGPU] GpuDataManager.release(id=${e}), gpuDataId=${t.gpuData.id}`),this.storageCache.delete(e),this.buffersPending.push(t.gpuData.buffer),t.originalSize}async download(e,t){let n=this.storageCache.get(e);if(!n)throw new Error("data does not exist");await Wc(this.backend,n.gpuData.buffer,n.originalSize,t)}refreshPendingBuffers(){for(let e of this.buffersForUploadingPending)e.destroy();this.buffersForUploadingPending=[];for(let e of this.buffersPending)(e.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE?this.freeBuffers.get(e.size).push(e):(e.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM?this.freeUniformBuffers.get(e.size).push(e):e.destroy();this.buffersPending=[]}dispose(){this.freeBuffers.forEach(e=>{e.forEach(t=>{t.destroy()})}),this.freeUniformBuffers.forEach(e=>{e.forEach(t=>{t.destroy()})}),this.storageCache.forEach(e=>{e.gpuData.buffer.destroy()}),this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map}},Tv=(...e)=>new Mm(...e)}),zm,tt,St=ee(()=>{zm=class{constructor(e){Object.assign(this,e)}get cacheKey(){return this.key||(this.key=Object.getOwnPropertyNames(this).sort().map(e=>`${this[e]}`).join(";")),this.key}},tt=e=>new zm(e)}),Rm,ca,ne,Ql,Iv,ff,hf,ze=ee(()=>{Rm=class{static calcMatMulShape(e,t){return e[1]!==t[0]?void 0:[e[0],t[1]]}},ca=class{static calcShape(e,t,n=!1){let r=e.length,i=t.length;if(r===0)return t;if(i===0)return e;let a=Math.max(e.length,t.length),s=new Array(a);if(n){if(r<2||i<2)return;let o=Rm.calcMatMulShape([e[r-2],e[r-1]],[t[i-2],t[i-1]]);if(o===void 0)return;[s[a-2],s[a-1]]=o}for(let o=n?3:1;o<=a;o++){let l=r-o<0?1:e[r-o],d=i-o<0?1:t[i-o];if(l!==d&&l>1&&d>1)return;s[a-o]=Math.max(l,d)}return s}static isValidBroadcast(e,t){let n=e.length,r=t.length;if(n>r)return!1;for(let i=1;i<=n;i++)if(e[n-i]!==1&&e[n-i]!==t[r-i])return!1;return!0}},ne=class gl{static size(t){return gl.getSizeFromDimensionRange(t,0,t.length)}static sizeFromDimension(t,n){if(n<0||n>t.length)throw new Error(`invalid dimension of ${n} for sizeFromDimension as Tensor has ${t.length} dimensions.`);return gl.getSizeFromDimensionRange(t,n,t.length)}static sizeToDimension(t,n){if(n<0||n>t.length)throw new Error(`invalid dimension of ${n} for sizeToDimension as Tensor has ${t.length} dimensions.`);return gl.getSizeFromDimensionRange(t,0,n)}static getSizeFromDimensionRange(t,n,r){let i=1;for(let a=n;a=0;--i)r[i]=r[i+1]*t[i+1];return r}static normalizeAxis(t,n){if(t<-n&&t>=n)throw new Error("unsupported axis for this operation.");return t<0?t+n:t}static normalizeAxes(t,n){return t.map(r=>this.normalizeAxis(r,n??t.length))}static sortBasedOnPerm(t,n){return n?n.map(r=>t[r]):t.slice().reverse()}static padShape(t,n){let r=t.length;return t.map((i,a)=>i+n[a]+n[a+r])}static areEqual(t,n){return t.length!==n.length?!1:t.every((r,i)=>r===n[i])}},Ql=class as{static adjustPoolAttributes(t,n,r,i,a,s){if(!t&&r.length!==n.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(t)for(let o=0;o=r.length?r.push(n[o+2]):r[o]=n[o+2];for(let o=0;o=r[o]||s[o+r.length]>=r[o])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(t,n,r,i,a,s,o){if(o){if(a.length!==2*(t.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(n.length!==t.length-2)throw new Error("length of strides should be the length of data dimensions");if(i.length!==t.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let l=0;l{lt(),ze(),Pm=64,qo=(e,t)=>{if(t===3)throw new Error("vec3 has same alignment as vec4, use vec4 instead");switch(e){case 10:return t>1?`vec${t}`:"f16";case 1:return t>1?`vec${t}`:"f32";case 6:return t>1?`vec${t}`:"i32";case 12:return t>1?`vec${t}`:"u32";case 7:if(t>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","i32"];case 13:if(t>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","u32"];case 9:if(t!==4)throw new Error("bool must be vec4");return["u32","vec4"];default:throw new Error(`Unknown data type: ${e}`)}},wn=(e,t=1)=>{let n=qo(e,t);return typeof n=="string"?n:n[0]},ar=(e,t=1)=>{let n=qo(e,t);return typeof n=="string"?n:n[1]},le=e=>e.length===0?[]:[{type:"uint32",data:e},{type:"uint32",data:ne.computeStrides(e)}],rn=e=>e%4===0?4:e%2===0?2:1,tn=(e="f32",t,n="0")=>!t||t===1?`${e}(${n})`:`vec${t}<${e}>(${n})`,ur=(e,t,n)=>e==="f32"?n:t===1?`f32(${n})`:`vec${t}f(${n})`,Zn=(e,t)=>t===4?`(${e}.x + ${e}.y + ${e}.z + ${e}.w)`:t===2?`(${e}.x + ${e}.y)`:t===3?`(${e}.x + ${e}.y + ${e}.z)`:e,Ce=(e,t,n)=>e.startsWith("uniforms.")&&n>4?typeof t=="string"?`${e}[(${t}) / 4][(${t}) % 4]`:`${e}[${Math.floor(t/4)}][${t%4}]`:n>1?`${e}[${t}]`:e,Ko=(e,t,n,r,i)=>{let a=typeof n=="number",s=a?n:n.length,o=[...new Array(s).keys()],l=s<2?"u32":s<=4?`vec${s}`:`array`,d=qo(t,i),c=typeof d=="string"?d:d[1],u=typeof d=="string"?d:d[0],f={indices:l,value:c,storage:u,tensor:t},h=V=>typeof V=="string"?V:`${V}u`,g={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},$=a?"uniforms.":"",E=`${$}${e}_shape`,y=`${$}${e}_strides`,_="";for(let V=0;V ${f.indices} { var indices: ${f.indices}; var current = offset; ${_} return indices; }`,b=V=>(g.offsetToIndices=!0,s<2?V:`o2i_${e}(${V})`),C=[];if(s>=2)for(let V=s-1;V>=0;V--)C.push(`${Ce(y,V,s)} * (indices[${V}])`);let I=s<2?"":` fn i2o_${e}(indices: ${f.indices}) -> u32 { return ${C.join("+")}; }`,O=V=>(g.indicesToOffset=!0,s<2?V:`i2o_${e}(${V})`),M=(...V)=>s===0?"0u":`${f.indices}(${V.map(h).join(",")})`,W=(V,ie)=>s<2?`${V}`:`${Ce(V,ie,s)}`,G=(V,ie,xe)=>s<2?`${V}=${xe};`:`${Ce(V,ie,s)}=${xe};`,z={},K=(V,ie)=>{g.broadcastedIndicesToOffset=!0;let xe=`${ie.name}broadcastedIndicesTo${e}Offset`;if(xe in z)return`${xe}(${V})`;let Re=[];for(let He=s-1;He>=0;He--){let qe=ie.indicesGet("outputIndices",He+ie.rank-s);Re.push(`${W(y,He)} * (${qe} % ${W(E,He)})`)}return z[xe]=`fn ${xe}(outputIndices: ${ie.type.indices}) -> u32 { return ${Re.length>0?Re.join("+"):"0u"}; }`,`${xe}(${V})`},ae=(V,ie)=>(()=>{if(f.storage===f.value)return`${e}[${V}]=${ie};`;if(f.storage==="vec2"&&f.value==="i32")return`${e}[${V}]=vec2(u32(${ie}), select(0u, 0xFFFFFFFFu, ${ie} < 0));`;if(f.storage==="vec2"&&f.value==="u32")return`${e}[${V}]=vec2(u32(${ie}), 0u);`;if(f.storage==="u32"&&f.value==="vec4")return`${e}[${V}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${ie}));`;throw new Error(`not supported combination of storage type ${f.storage} and value type ${f.value} yet`)})(),ue=V=>(()=>{if(f.storage===f.value)return`${e}[${V}]`;if(f.storage==="vec2"&&f.value==="i32")return`i32(${e}[${V}].x)`;if(f.storage==="vec2"&&f.value==="u32")return`u32(${e}[${V}].x)`;if(f.storage==="u32"&&f.value==="vec4")return`vec4(bool(${e}[${V}] & 0xFFu), bool(${e}[${V}] & 0xFF00u), bool(${e}[${V}] & 0xFF0000u), bool(${e}[${V}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${f.storage} and value type ${f.value} yet`)})(),R=s<2?"":` fn get_${e}ByIndices(indices: ${f.indices}) -> ${c} { return ${ue(`i2o_${e}(indices)`)}; }`,H=s<2?"":(()=>{let V=o.map(xe=>`d${xe}: u32`).join(", "),ie=o.map(xe=>`d${xe}`).join(", ");return` fn get_${e}(${V}) -> ${c} { return get_${e}ByIndices(${M(ie)}); }`})(),re=(...V)=>{if(V.length!==s)throw new Error(`indices length must be ${s}`);let ie=V.map(h).join(",");return s===0?ue("0u"):s===1?ue(ie[0]):(g.get=!0,g.getByIndices=!0,g.indicesToOffset=!0,`get_${e}(${ie})`)},L=V=>s<2?ue(V):(g.getByIndices=!0,g.indicesToOffset=!0,`get_${e}ByIndices(${V})`),X=s<2?"":` fn set_${e}ByIndices(indices: ${f.indices}, value: ${c}) { ${ae(`i2o_${e}(indices)`,"value")} }`,Z=s<2?"":(()=>{let V=o.map(xe=>`d${xe}: u32`).join(", "),ie=o.map(xe=>`d${xe}`).join(", ");return` fn set_${e}(${V}, value: ${c}) { set_${e}ByIndices(${M(ie)}, value); }`})();return{impl:()=>{let V=[],ie=!1;return g.offsetToIndices&&(V.push(v),ie=!0),g.indicesToOffset&&(V.push(I),ie=!0),g.broadcastedIndicesToOffset&&(Object.values(z).forEach(xe=>V.push(xe)),ie=!0),g.set&&(V.push(Z),ie=!0),g.setByIndices&&(V.push(X),ie=!0),g.get&&(V.push(H),ie=!0),g.getByIndices&&(V.push(R),ie=!0),!a&&ie&&V.unshift(`const ${E} = ${f.indices}(${n.join(",")});`,`const ${y} = ${f.indices}(${ne.computeStrides(n).join(",")});`),V.join(` `)},type:f,offsetToIndices:b,indicesToOffset:O,broadcastedIndicesToOffset:K,indices:M,indicesGet:W,indicesSet:G,set:(...V)=>{if(V.length!==s+1)throw new Error(`indices length must be ${s}`);let ie=V[s];if(typeof ie!="string")throw new Error("value must be string");let xe=V.slice(0,s).map(h).join(",");return s===0?ae("0u",ie):s===1?ae(xe[0],ie):(g.set=!0,g.setByIndices=!0,g.indicesToOffset=!0,`set_${e}(${xe}, ${ie})`)},setByOffset:ae,setByIndices:(V,ie)=>s<2?ae(V,ie):(g.setByIndices=!0,g.indicesToOffset=!0,`set_${e}ByIndices(${V}, ${ie});`),get:re,getByOffset:ue,getByIndices:L,usage:r,name:e,strides:y,shape:E,rank:s}},te=(e,t,n,r=1)=>Ko(e,t,n,"input",r),ke=(e,t,n,r=1)=>Ko(e,t,n,"output",r),mf=(e,t,n,r=1)=>Ko(e,t,n,"internal",r),Bm=class{constructor(e){this.normalizedDispatchGroup=e,this.internalVariables=[],this.variables=[],this.uniforms=[],this.variableIndex=0}guardAgainstOutOfBoundsWorkgroupSizes(e){return`if (global_idx >= ${typeof e=="number"?`${e}u`:e}) { return; }`}mainStart(e=Pm){let t=typeof e=="number"?e:e[0],n=typeof e=="number"?1:e[1],r=typeof e=="number"?1:e[2],i=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1,a=i?`@builtin(global_invocation_id) global_id : vec3, @builtin(workgroup_id) workgroup_id : vec3, @builtin(local_invocation_id) local_id : vec3`:`@builtin(local_invocation_id) local_id : vec3, @builtin(local_invocation_index) local_idx : u32, @builtin(workgroup_id) workgroup_id : vec3, @builtin(num_workgroups) num_workgroups : vec3`,s=i?"let global_idx = global_id.x; let local_idx = local_id.x;":`let global_idx = (workgroup_id.z * num_workgroups[0] * num_workgroups[1] + workgroup_id.y * num_workgroups[0] + workgroup_id.x) * ${t*n*r}u + local_idx;`;return`@compute @workgroup_size(${t}, ${n}, ${r}) fn main(${a}) { ${s} `}appendVariableUniforms(e){e.rank!==0&&(e.shape.startsWith("uniforms.")&&this.uniforms.push({name:e.shape.replace("uniforms.",""),type:"u32",length:e.rank}),e.strides.startsWith("uniforms.")&&this.uniforms.push({name:e.strides.replace("uniforms.",""),type:"u32",length:e.rank}))}declareVariable(e,t){if(e.usage==="internal")throw new Error("cannot use internal variable with declareVariable(). use registerInternalVariables() instead.");this.variables.push(e),this.appendVariableUniforms(e);let n=e.usage==="input"?"read":"read_write",r=e.type.storage;return`@group(0) @binding(${t}) var ${e.name}: array<${r}>;`}declareVariables(...e){return e.map(t=>this.declareVariable(t,this.variableIndex++)).join(` `)}registerInternalVariable(e){if(e.usage!=="internal")throw new Error("cannot use input or output variable with registerInternalVariable(). use declareVariables() instead.");this.internalVariables.push(e),this.appendVariableUniforms(e)}registerInternalVariables(...e){return e.forEach(t=>this.registerInternalVariable(t)),this}registerUniform(e,t,n=1){return this.uniforms.push({name:e,type:t,length:n}),this}registerUniforms(e){return this.uniforms=this.uniforms.concat(e),this}uniformDeclaration(){if(this.uniforms.length===0)return"";let e=[];for(let{name:t,type:n,length:r}of this.uniforms)if(r&&r>4)e.push(`${t}:array, ${Math.ceil(r/4)}>`);else{let i=r==null||r===1?n:`vec${r}<${n}>`;e.push(`${t}:${i}`)}return` struct Uniforms { ${e.join(", ")} }; @group(0) @binding(${this.variableIndex}) var uniforms: Uniforms;`}get additionalImplementations(){return this.uniformDeclaration()+this.variables.map(e=>e.impl()).join(` `)+this.internalVariables.map(e=>e.impl()).join(` `)}},Av=e=>new Bm(e),Ns=(e,t)=>{let n=e.length,r=[];for(let i=0;i1&&s===1&&r.unshift(a)}return r},xt=e=>!0}),Dm,_d,Nm,Lm,Gr,Ov,Mv,qs=ee(()=>{ze(),St(),Oe(),Dm=e=>{if(!e||e.length!==1)throw new Error("Transpose requires 1 input.")},_d=(e,t)=>t&&t.length!==e?[...new Array(e).keys()].reverse():t,Nm=(e,t)=>ne.sortBasedOnPerm(e,_d(e.length,t)),Lm=(e,t,n,r)=>{let i=[];i.push(`fn perm(i: ${r.type.indices}) -> ${n.type.indices} { var a: ${n.type.indices};`);for(let a=0;a{let n=e.dataType,r=e.dims.length,i=_d(r,t),a=xt(r),s=Nm(e.dims,i),o=a?s.length:s,l=a?r:e.dims,d=ke("output",n,o),c=te("a",n,l),u=f=>` ${f.registerUniform("output_size","u32").declareVariables(c,d)} ${Lm(i,r,c,d)} ${f.mainStart()} ${f.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let indices = ${d.offsetToIndices("global_idx")}; let aIndices = perm(indices); ${d.setByOffset("global_idx",c.getByIndices("aIndices"))} }`;return{name:"Transpose",shaderCache:{hint:`${t}`,inputDependencies:a?["rank"]:["dims"]},getRunData:f=>{let h=ne.size(s);return{outputs:[{dims:s,dataType:f[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:a?[{type:"uint32",data:h},...le(f[0].dims),...le(s)]:[{type:"uint32",data:h}]}},getShaderSource:u}},Ov=(e,t)=>{Dm(e.inputs),e.compute(Gr(e.inputs[0],t.perm))},Mv=e=>tt({perm:e.perm})}),Fm,Um,Wm,Vm,jm,Gm,Hm,qm,Km,Ym,bn,zv,Rv,Pv,Bv,Dv,Nv,Lv,Fv,Uv,Wv,sE=ee(()=>{ze(),Oe(),gf(),qs(),Fm={max:"select(bestValue, candidate, candidate > bestValue)",min:"select(bestValue, candidate, candidate < bestValue)",mean:"bestValue + candidate",sum:"bestValue + candidate",prod:"bestValue * candidate",sumSquare:"bestValue + candidate * candidate",logSumExp:"bestValue + exp(candidate)",l1:"bestValue + abs(candidate)",l2:"bestValue + candidate * candidate",logSum:"bestValue + candidate"},Um={max:"select(bestValue, candidate, candidate > bestValue)",min:"select(bestValue, candidate, candidate < bestValue)",mean:"bestValue + candidate",sum:"bestValue + candidate",prod:"bestValue * candidate",sumSquare:"bestValue + candidate",logSumExp:"bestValue + candidate",l1:"bestValue + candidate",l2:"bestValue + candidate",logSum:"bestValue + candidate"},Wm={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},Vm={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},jm=(e,t)=>{let n=[];for(let r=t-e;r{let n=[],r=e.length;for(let a=0;ae[a]);return[n,i]},Hm=(e,t)=>{let n=e.length+t.length,r=[],i=0;for(let a=0;a{for(let n=0;n{let n=[];if(!qm(e,t)){for(let r=0;rn.push(r))}return n},Ym=(e,t,n,r,i,a,s)=>{let o=n[0].dims,l=ne.size(a),d=ne.size(s),c=te("_A",n[0].dataType,o),u=ke("output",i,a),f=32,h=` var aBestValues : array<${u.type.storage}, ${f}>; `;return{name:e,shaderCache:t,getShaderSource:g=>` ${g.registerUniform("reduceSize","u32").declareVariables(c,u)} ${h} fn DIV_CEIL(a : u32, b : u32) -> u32 { return ((a - 1u) / b + 1u); } ${g.mainStart(f)} let outputIndex = global_idx / ${f}; let offset = outputIndex * uniforms.reduceSize; var bestValue = ${u.type.storage}(${Wm[r]}); let Length = uniforms.reduceSize; for (var k = local_idx; k < Length; k = k + ${f}) { let candidate = ${u.type.storage}(${c.getByOffset("offset + k")}); bestValue = ${Fm[r]}; } aBestValues[local_idx] = bestValue; workgroupBarrier(); var reduceSize = min(Length, ${f}u); for (var currentSize = reduceSize / 2u; reduceSize > 1u; currentSize = reduceSize / 2u) { let interval = DIV_CEIL(reduceSize, 2u); if (local_idx < currentSize) { let candidate = aBestValues[local_idx + interval]; bestValue = ${Um[r]}; aBestValues[local_idx] = bestValue; } reduceSize = interval; workgroupBarrier(); } if (local_idx == 0u) { ${u.setByOffset("outputIndex",`${r==="mean"?`bestValue / ${u.type.storage}(uniforms.reduceSize)`:`${Vm[r]}`}`)}; } }`,getRunData:()=>({outputs:[{dims:a,dataType:i}],dispatchGroup:{x:l},programUniforms:[{type:"uint32",data:d}]})}},bn=(e,t,n,r)=>{let i=e.inputs.length===1?n:Vc(e.inputs,n),a=i.axes;a.length===0&&!i.noopWithEmptyAxes&&(a=e.inputs[0].dims.map((h,g)=>g));let s=ne.normalizeAxes(a,e.inputs[0].dims.length),o=s,l=e.inputs[0],d=Km(o,e.inputs[0].dims.length);d.length>0&&(l=e.compute(Gr(e.inputs[0],d),{inputs:[0],outputs:[-1]})[0],o=jm(o.length,l.dims.length));let[c,u]=Gm(l.dims,o),f=c;i.keepDims&&(f=Hm(c,s)),e.compute(Ym(t,{hint:i.cacheKey,inputDependencies:["type"]},[l],r,e.inputs[0].dataType,f,u),{inputs:[l]})},zv=(e,t)=>{bn(e,"ReduceMeanShared",t,"mean")},Rv=(e,t)=>{bn(e,"ReduceL1Shared",t,"l1")},Pv=(e,t)=>{bn(e,"ReduceL2Shared",t,"l2")},Bv=(e,t)=>{bn(e,"ReduceLogSumExpShared",t,"logSumExp")},Dv=(e,t)=>{bn(e,"ReduceMaxShared",t,"max")},Nv=(e,t)=>{bn(e,"ReduceMinShared",t,"min")},Lv=(e,t)=>{bn(e,"ReduceProdShared",t,"prod")},Fv=(e,t)=>{bn(e,"ReduceSumShared",t,"sum")},Uv=(e,t)=>{bn(e,"ReduceSumSquareShared",t,"sumSquare")},Wv=(e,t)=>{bn(e,"ReduceLogSumShared",t,"logSum")}}),xn,Qm,Xl,Vc,Sn,Xm,Zm,Jm,eg,tg,ng,rg,ig,ag,sg,En,Vv,jv,Gv,Hv,qv,Kv,Yv,Qv,Xv,Zv,gf=ee(()=>{ze(),St(),Oe(),sE(),xn=e=>{if(!e||e.length===0||e.length>2)throw new Error("Reduce op requires 1 or 2 inputs.");if(e.length===2&&e[1].dims.length!==1)throw new Error("Invalid axes input dims.")},Qm=e=>["","",`var value = ${e.getByIndices("input_indices")};`,""],Xl=(e,t,n,r,i,a,s=!1,o=!1)=>{let l=[],d=n[0].dims,c=d.length,u=ne.normalizeAxes(i,c),f=!o&&u.length===0;d.forEach(($,E)=>{f||u.indexOf(E)>=0?s&&l.push(1):l.push($)});let h=l.length,g=ne.size(l);return{name:e,shaderCache:t,getShaderSource:$=>{let E=[],y=te("_A",n[0].dataType,c),_=ke("output",a,h),v=r(y,_,u),b=v[2];for(let C=0,I=0;C=0?(s&&I++,b=`for(var j${C}: u32 = 0; j${C} < ${d[C]}; j${C}++) { ${v[2].includes("last_index")?`let last_index = j${C};`:""} ${y.indicesSet("input_indices",C,`j${C}`)} ${b} }`):(E.push(`${y.indicesSet("input_indices",C,_.indicesGet("output_indices",I))};`),I++);return` ${$.registerUniform("output_size","u32").declareVariables(y,_)} ${$.mainStart()} ${$.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} var input_indices: ${y.type.indices}; let output_indices = ${_.offsetToIndices("global_idx")}; ${E.join(` `)} ${v[0]} // init ops for reduce max/min ${v[1]} ${b} ${v[3]} ${v.length===4?_.setByOffset("global_idx","value"):v.slice(4).join(` `)} }`},getRunData:()=>({outputs:[{dims:l,dataType:a}],dispatchGroup:{x:Math.ceil(g/64)},programUniforms:[{type:"uint32",data:g},...le(d),...le(l)]})}},Vc=(e,t)=>{let n=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach(r=>n.push(Number(r))),tt({axes:n,keepDims:t.keepDims,noopWithEmptyAxes:t.noopWithEmptyAxes})},Sn=(e,t,n,r)=>{let i=e.inputs,a=i.length===1?n:Vc(i,n);e.compute(Xl(t,{hint:a.cacheKey,inputDependencies:["rank"]},[i[0]],a.noopWithEmptyAxes&&a.axes.length===0?Qm:r,a.axes,i[0].dataType,a.keepDims,a.noopWithEmptyAxes),{inputs:[0]})},Xm=(e,t)=>{xn(e.inputs),Sn(e,"ReduceLogSum",t,(n,r)=>[`var value = ${r.type.storage}(0);`,"",`value += ${n.getByIndices("input_indices")};`,"value = log(value);"])},Zm=(e,t)=>{xn(e.inputs),Sn(e,"ReduceL1",t,(n,r)=>[`var value = ${r.type.storage}(0);`,"",`value += abs(${n.getByIndices("input_indices")});`,""])},Jm=(e,t)=>{xn(e.inputs),Sn(e,"ReduceL2",t,(n,r)=>[`var t = ${r.type.value}(0); var value = ${r.type.value}(0);`,"",`t = ${n.getByIndices("input_indices")}; value += (t * t);`,"value = sqrt(value);"])},eg=(e,t)=>{xn(e.inputs),Sn(e,"ReduceLogSumExp",t,(n,r)=>[`var value = ${r.type.storage}(0);`,"",`value += exp(${n.getByIndices("input_indices")});`,"value = log(value);"])},tg=(e,t)=>{xn(e.inputs),Sn(e,"ReduceMax",t,(n,r,i)=>{let a=[];for(let s=0;s=0||i.length===0)&&a.push(n.indicesSet("input_indices",s,0));return[`${a.join(` `)}`,`var value = ${n.getByIndices("input_indices")};`,`value = max(value, ${n.getByIndices("input_indices")});`,""]})},ng=(e,t)=>{xn(e.inputs),Sn(e,"ReduceMean",t,(n,r,i)=>{let a=1;for(let s=0;s=0||i.length===0)&&(a*=e.inputs[0].dims[s]);return["var sum = f32(0);","",`sum += f32(${n.getByIndices("input_indices")});`,`let value = ${r.type.value}(sum / ${a});`]})},rg=(e,t)=>{xn(e.inputs),Sn(e,"ReduceMin",t,(n,r,i)=>{let a=[];for(let s=0;s=0||i.length===0)&&a.push(`input_indices[${s}] = 0;`);return[`${a.join(` `)}`,`var value = ${n.getByIndices("input_indices")};`,`value = min(value, ${n.getByIndices("input_indices")});`,""]})},ig=(e,t)=>{xn(e.inputs),Sn(e,"ReduceProd",t,(n,r)=>[`var value = ${r.type.storage}(1);`,"",`value *= ${n.getByIndices("input_indices")};`,""])},ag=(e,t)=>{xn(e.inputs),Sn(e,"ReduceSum",t,(n,r)=>[`var value = ${r.type.storage}(0);`,"",`value += ${n.getByIndices("input_indices")};`,""])},sg=(e,t)=>{xn(e.inputs),Sn(e,"ReduceSumSquare",t,(n,r)=>[`var t = ${r.type.value}(0); var value = ${r.type.value}(0);`,"",`t = ${n.getByIndices("input_indices")}; value += t * t;`,""])},En=(e,t,n)=>{if(t.length===0)return n;let r=1,i=1;for(let a=0;a1024},Vv=(e,t)=>{En(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?ng(e,t):zv(e,t)},jv=(e,t)=>{En(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Zm(e,t):Rv(e,t)},Gv=(e,t)=>{En(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Jm(e,t):Pv(e,t)},Hv=(e,t)=>{En(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?eg(e,t):Bv(e,t)},qv=(e,t)=>{En(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?tg(e,t):Dv(e,t)},Kv=(e,t)=>{En(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?rg(e,t):Nv(e,t)},Yv=(e,t)=>{En(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?ig(e,t):Lv(e,t)},Qv=(e,t)=>{En(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?ag(e,t):Fv(e,t)},Xv=(e,t)=>{En(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?sg(e,t):Uv(e,t)},Zv=(e,t)=>{En(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Xm(e,t):Wv(e,t)}}),vd,Jv,e1,jc,oE=ee(()=>{lt(),St(),gf(),vd=e=>{if(!e||e.length===0||e.length>2)throw new Error("ArgMinMaxOp op requires 1 or 2 inputs.");if(e[0].dataType!==1)throw new Error("Invalid input type.")},Jv=(e,t)=>{vd(e.inputs);let n=(r,i,a)=>{let s=[];for(let o=0;o=0||a.length===0)&&s.push(`input_indices[${o}] = 0;`);return[`${s.join(` `)}`,`var value = ${r.getByIndices("input_indices")}; var best_index : i32 = 0;`,`if (${r.getByIndices("input_indices")} ${t.selectLastIndex>0?"<=":"<"} value) { value = ${r.getByIndices("input_indices")}; best_index = i32(last_index); }`,"",i.setByOffset("global_idx","best_index")]};e.compute(Xl("ArgMin",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],n,[t.axis],7,t.keepDims),{inputs:[0]})},e1=(e,t)=>{vd(e.inputs);let n=(r,i,a)=>{let s=[];for(let o=0;o=0||a.length===0)&&s.push(`input_indices[${o}] = 0;`);return[`${s.join(` `)}`,`var value = ${r.getByIndices("input_indices")}; var best_index : i32 = 0;`,`if (${r.getByIndices("input_indices")} ${t.selectLastIndex>0?">=":">"} value) { value = ${r.getByIndices("input_indices")}; best_index = i32(last_index); }`,"",i.setByOffset("global_idx","best_index")]};e.compute(Xl("argMax",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],n,[t.axis],7,t.keepDims),{inputs:[0]})},jc=e=>tt(e)}),og,lg,ug,dg,Zl,cg,t1,n1=ee(()=>{lt(),pf(),Oe(),og=(e,t)=>{let n=e[0],r=e[1],i=e[2],a=e[3],s=e[4],o=e[5];if(s&&o)throw new Error("Attention cannot have both past and relative_position_bias");if(n.dims.length!==3)throw new Error('Input "input" must have 3 dimensions');let l=n.dims[0],d=n.dims[1],c=n.dims[2];if(i.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimensions');if(r.dims.length!==2)throw new Error('Input "weights" is expected to have 2 dimensions');if(r.dims[0]!==c)throw new Error("Input 1 dimension 0 should have same length as dimension 2 of input 0");if(i.dims[0]!==r.dims[1])throw new Error('Input "bias" dimension 0 should have same length as dimension 1 of input "weights"');let u=i.dims[0]/3,f=u,h=f;if(t.qkvHiddenSizes.length>0){if(t.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let v of t.qkvHiddenSizes)if(v%t.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");u=t.qkvHiddenSizes[0],f=t.qkvHiddenSizes[1],h=t.qkvHiddenSizes[2]}let g=d;if(u!==f)throw new Error("qkv_hidden_sizes first element should be same as the second");if(i.dims[0]!==u+f+h)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let $=0;if(s){if(f!==h)throw new Error('Input "past" expect k_hidden_size == v_hidden_size');if(s.dims.length!==5)throw new Error('Input "past" must have 5 dimensions');if(s.dims[0]!==2)throw new Error('Input "past" first dimension must be 2');if(s.dims[1]!==l)throw new Error('Input "past" second dimension must be batch_size');if(s.dims[2]!==t.numHeads)throw new Error('Input "past" third dimension must be num_heads');if(s.dims[4]!==f/t.numHeads)throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads');t.pastPresentShareBuffer||($=s.dims[3])}let E=g+$,y=-1,_=0;if(a)throw new Error("Mask not supported");if(s)throw new Error("past is not supported");if(o)throw new Error("relativePositionBias is not supported");return{batchSize:l,sequenceLength:d,pastSequenceLength:$,kvSequenceLength:g,totalSequenceLength:E,maxSequenceLength:y,inputHiddenSize:c,hiddenSize:u,vHiddenSize:h,headSize:Math.floor(u/t.numHeads),vHeadSize:Math.floor(h/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:_,scale:t.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},lg=(e,t,n,r)=>{let i=rn(r),a=64,s=r/i;s{let f=ke("x",t.dataType,t.dims,i),h="thread_max_vector";i===2?h="max(thread_max_vector.x, thread_max_vector.y)":i===4&&(h="max(max(thread_max_vector.x, thread_max_vector.y), max(thread_max_vector.z, thread_max_vector.w))");let g=ar(t.dataType),$=[{name:"d_inv",type:g},{name:"d_comp",type:"u32"},{name:"elements_per_wg",type:"u32"}];return` var wgMax: array; var wgSum: array; ${u.registerUniforms($).declareVariables(f)} ${u.mainStart([a,1,1])} let localOffset = local_idx * uniforms.elements_per_wg; let offset: u32 = workgroup_id.x * uniforms.d_comp + localOffset; var thread_max_vector = ${tn("f32",i,"-3.402823e+38f")}; for (var i: u32 = 0; i < uniforms.elements_per_wg && i + localOffset < uniforms.d_comp; i++) { thread_max_vector = max(${ur(g,i,"x[offset + i]")}, thread_max_vector); } wgMax[local_idx] = ${h}; workgroupBarrier(); var maxValue = -3.402823e+38f; for (var i = 0u; i < ${a}; i++) { maxValue = max(wgMax[i], maxValue); } var sumVector = ${tn("f32",i,"0")}; for (var i: u32 = 0; i < uniforms.elements_per_wg && i + localOffset < uniforms.d_comp; i++) { sumVector += exp(${ur(g,i,"x[offset + i]")} - maxValue); } wgSum[local_idx] = ${Zn("sumVector",i)}; workgroupBarrier(); var sum: f32 = 0; for (var i = 0u; i < ${a}; i++) { sum += wgSum[i]; } if (sum == 0) { for (var i: u32 = 0; i < uniforms.elements_per_wg && i + localOffset < uniforms.d_comp; i++) { x[offset + i] = ${tn("f32",i,"uniforms.d_inv")}; } } else { for (var i: u32 = 0; i < uniforms.elements_per_wg && i + localOffset < uniforms.d_comp; i++) { let f32input = ${ur(g,i,"x[offset + i]")}; x[offset + i] = ${f.type.value}(exp(f32input - maxValue) / sum); } } }`};e.compute({name:"AttentionProbsSoftmax",shaderCache:{hint:`${a};${d};${i}`},getShaderSource:c,getRunData:()=>({outputs:[],dispatchGroup:{x:n},programUniforms:l})},{inputs:[t],outputs:[]})},ug=(e,t,n,r,i,a)=>{let s=[i.batchSize,i.numHeads,i.sequenceLength,i.kvSequenceLength+i.pastSequenceLength],o=a.scale===0?1/Math.sqrt(i.headSize):a.scale,l=rn(i.headSize),d=i.headSize/l,c=12,u={x:Math.ceil(i.totalSequenceLength/c),y:Math.ceil(i.sequenceLength/c),z:i.batchSize*i.numHeads},f=Kn(t.dataType),h=[{type:"uint32",data:i.sequenceLength},{type:"uint32",data:d},{type:"uint32",data:i.totalSequenceLength},{type:"uint32",data:i.kvSequenceLength},{type:f,data:o}],g=[t,n],$=y=>{let _=te("q",t.dataType,t.dims,l),v=te("key",n.dataType,n.dims,l),b=ke("output",t.dataType,s),C=wn(t.dataType),I=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"kv_sequence_length",type:"u32"},{name:"alpha",type:C}];return` const beta: ${C} = 1.0; const TILE_SIZE = ${c}u; var tileQ: array<${_.type.storage}, ${c*c}>; var tileK: array<${_.type.storage}, ${c*c}>; ${y.registerUniforms(I).declareVariables(_,v,b)} ${y.mainStart([c,c,1])} // x holds the N and y holds the M let headIdx = workgroup_id.z; let m = workgroup_id.y * TILE_SIZE; let n = workgroup_id.x * TILE_SIZE; let lm = m + local_id.y; let ln = n + local_id.x; let qOffset = uniforms.M * uniforms.K * headIdx + m * uniforms.K; let kOffset = uniforms.kv_sequence_length * uniforms.K * headIdx + n * uniforms.K; var value = ${tn(C,l)}; for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { if (m + local_id.y < uniforms.M && w + local_id.x < uniforms.K) { tileQ[TILE_SIZE * local_id.y + local_id.x] = q[qOffset + local_id.y * uniforms.K + w + local_id.x]; } if (n + local_id.y < uniforms.N && w + local_id.x < uniforms.K) { tileK[TILE_SIZE * local_id.y + local_id.x] = key[kOffset + local_id.y * uniforms.K + w + local_id.x]; } workgroupBarrier(); for (var k: u32 = 0u; k({outputs:[{dims:s,dataType:t.dataType,gpuDataType:0}],dispatchGroup:u,programUniforms:h}),getShaderSource:$},{inputs:g,outputs:[-1]})[0];return lg(e,E,i.batchSize*i.numHeads*i.sequenceLength,i.totalSequenceLength),E},dg=(e,t,n,r)=>{let i=[r.batchSize,r.sequenceLength,r.vHiddenSize],a=12,s={x:Math.ceil(r.vHeadSize/a),y:Math.ceil(r.sequenceLength/a),z:r.batchSize*r.numHeads},o=[{type:"uint32",data:r.sequenceLength},{type:"uint32",data:r.totalSequenceLength},{type:"uint32",data:r.vHeadSize},{type:"uint32",data:r.numHeads},{type:"uint32",data:r.vHiddenSize}],l=d=>{let c=te("probs",t.dataType,t.dims),u=te("v",n.dataType,n.dims),f=ke("output",t.dataType,i),h=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"v_hidden_size",type:"u32"}];return` const TILE_SIZE = ${a}u; var tileQ: array<${c.type.value}, ${a*a}>; var tileK: array<${c.type.value}, ${a*a}>; ${d.registerUniforms(h).declareVariables(c,u,f)} ${d.mainStart([a,a,1])} let headIdx = workgroup_id.z; let m = workgroup_id.y * TILE_SIZE + local_id.y; let n = workgroup_id.x * TILE_SIZE + local_id.x; let offsetA = headIdx * (uniforms.M * uniforms.K) + m * uniforms.K; let offsetB = headIdx * (uniforms.N * uniforms.K) + n; var value = ${c.type.storage}(0); for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { if (m < uniforms.M && w + local_id.x < uniforms.K) { tileQ[TILE_SIZE * local_id.y + local_id.x] = probs[offsetA + w + local_id.x]; } if (n < uniforms.N && w + local_id.y < uniforms.K) { tileK[TILE_SIZE * local_id.y + local_id.x] = v[offsetB + (w + local_id.y) * uniforms.N]; } workgroupBarrier(); for (var k: u32 = 0u; k({outputs:[{dims:i,dataType:t.dataType,gpuDataType:0}],dispatchGroup:s,programUniforms:o}),getShaderSource:l},{inputs:[t,n],outputs:[0]})[0]},Zl=(e,t,n,r,i,a,s,o,l,d,c)=>{let u=ug(e,t,n,l,d,c);dg(e,u,r,d)},cg=(e,t)=>{let n=[t.batchSize,t.numHeads,t.sequenceLength,t.headSize],r=t.sequenceLength,i=t.inputHiddenSize,a=t.headSize,s=12,o={x:Math.ceil(t.headSize/s),y:Math.ceil(t.sequenceLength/s),z:t.batchSize*t.numHeads},l=[e.inputs[0],e.inputs[1],e.inputs[2]],d=[{type:"uint32",data:r},{type:"uint32",data:i},{type:"uint32",data:a},{type:"uint32",data:t.numHeads},{type:"uint32",data:t.headSize},{type:"uint32",data:t.hiddenSize},{type:"uint32",data:t.hiddenSize+t.hiddenSize+t.vHiddenSize}],c=u=>{let f=ke("output_q",l[0].dataType,n),h=ke("output_k",l[0].dataType,n),g=ke("output_v",l[0].dataType,n),$=te("input",l[0].dataType,l[0].dims),E=te("weight",l[1].dataType,l[1].dims),y=te("bias",l[2].dataType,l[2].dims),_=$.type.storage,v=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"hidden_size",type:"u32"},{name:"ldb",type:"u32"}];return` const TILE_SIZE = ${s}u; var tileInput: array<${_}, ${s*s}>; var tileWeightQ: array<${_}, ${s*s}>; var tileWeightK: array<${_}, ${s*s}>; var tileWeightV: array<${_}, ${s*s}>; ${u.registerUniforms(v).declareVariables($,E,y,f,h,g)} ${u.mainStart([s,s,1])} let batchIndex = workgroup_id.z / uniforms.num_heads; let headNumber = workgroup_id.z % uniforms.num_heads; let m = workgroup_id.y * TILE_SIZE + local_id.y; let n = workgroup_id.x * TILE_SIZE + local_id.x; let inputOffset = batchIndex * (uniforms.M * uniforms.K) + m * uniforms.K; let biasOffsetQ = headNumber * uniforms.head_size; let biasOffsetK = uniforms.hidden_size + biasOffsetQ; let biasOffsetV = uniforms.hidden_size + biasOffsetK; var valueQ = ${_}(0); var valueK = ${_}(0); var valueV = ${_}(0); for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { if (m < uniforms.M && w + local_id.x < uniforms.K) { tileInput[TILE_SIZE * local_id.y + local_id.x] = input[inputOffset + w + local_id.x]; } if (n < uniforms.N && w + local_id.y < uniforms.K) { let offset = n + (w + local_id.y) * uniforms.ldb; tileWeightQ[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetQ + offset]; tileWeightK[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetK + offset]; tileWeightV[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetV + offset]; } workgroupBarrier(); for (var k: u32 = 0u; k({outputs:[{dims:n,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:n,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:n,dataType:e.inputs[0].dataType,gpuDataType:0}],dispatchGroup:o,programUniforms:d}),getShaderSource:c},{inputs:l,outputs:[-1,-1,-1]})},t1=(e,t)=>{let n=og(e.inputs,t),[r,i,a]=cg(e,n);return Zl(e,r,i,a,e.inputs[4],void 0,void 0,void 0,e.inputs[5],n,t)}}),pg,fg,hg,r1,lE=ee(()=>{Fn(),ze(),St(),Oe(),pg=(e,t)=>{if(!e||e.length!==5)throw new Error("BatchNormalization requires 5 inputs");let n=(r,i,a)=>{let s=i.length;if(s!==r.length)throw new Error(`${a}: num dimensions != ${s}`);i.forEach((o,l)=>{if(o!==r[l])throw new Error(`${a}: dim[${l}] do not match`)})};if(e[0].dims.length>1){let r=t.format==="NHWC"?t.spatial?e[0].dims.slice(-1):e[0].dims.slice(-1).concat(e[0].dims.slice(1,e[0].dims.length-1)):e[0].dims.slice(1,t.spatial?2:void 0);n(e[1].dims,r,"Invalid input scale"),n(e[2].dims,r,"Invalid input B"),n(e[3].dims,r,"Invalid input mean"),n(e[4].dims,r,"Invalid input var")}else n(e[1].dims,[1],"Invalid input scale"),n(e[2].dims,[1],"Invalid input B"),n(e[3].dims,[1],"Invalid input mean"),n(e[4].dims,[1],"Invalid input var")},fg=(e,t)=>{let{epsilon:n,spatial:r,format:i}=t,a=e[0].dims,s=r?rn(a[a.length-1]):1,o=i==="NHWC"&&a.length>1?s:1,l=ne.size(a)/s,d=xt(a.length)&&r,c=d?a.length:a,u=te("x",e[0].dataType,e[0].dims,s),f=te("scale",e[1].dataType,e[1].dims,o),h=te("bias",e[2].dataType,e[2].dims,o),g=te("inputMean",e[3].dataType,e[3].dims,o),$=te("inputVar",e[4].dataType,e[4].dims,o),E=ke("y",e[0].dataType,c,s),y=()=>{let v="";if(r)v=`let cOffset = ${a.length===1?"0u":i==="NHWC"?`outputIndices[${a.length-1}] / ${s}`:"outputIndices[1]"};`;else if(i==="NCHW")v=` ${E.indicesSet("outputIndices","0","0")} let cOffset = ${E.indicesToOffset("outputIndices")};`;else{v=`var cIndices = ${f.type.indices}(0); cIndices[0] = outputIndices[${a.length-1}];`;for(let b=1;b` const epsilon = ${n}; ${v.registerUniform("outputSize","u32").declareVariables(u,f,h,g,$,E)} ${v.mainStart()} ${v.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var outputIndices = ${E.offsetToIndices(`global_idx * ${s}`)}; ${y()} let scale = ${f.getByOffset("cOffset")}; let bias = ${h.getByOffset("cOffset")}; let inputMean = ${g.getByOffset("cOffset")}; let inputVar = ${$.getByOffset("cOffset")}; let x = ${u.getByOffset("global_idx")}; let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias; ${E.setByOffset("global_idx","value")} }`;return{name:"BatchNormalization",shaderCache:{hint:`${t.epsilon}_${t.format}_${r}_${s}`,inputDependencies:d?["rank","type","type","type","type"]:void 0},getShaderSource:_,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:d?[{type:"uint32",data:l},...le(a)]:[{type:"uint32",data:l}]})}},hg=e=>tt(e),r1=(e,t)=>{let{inputs:n,outputCount:r}=e,i=hg({...t,outputCount:r});if(je.webgpu.validateInputContent&&pg(n,i),t.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");e.compute(fg(n,i))}}),mg,gg,i1,uE=ee(()=>{ze(),Oe(),mg=e=>{if(e[0].dims.length!==3)throw new Error("input should have 3 dimensions");if(![320,640,1280].includes(e[0].dims[2]))throw new Error("number of channels should be 320, 640 or 1280");if(e[1].dims.length!==1)throw new Error("bias is expected to have 1 dimensions");if(e[0].dims[2]!==e[1].dims[0])throw new Error("last dimension of input and bias are not the same")},gg=e=>{let t=e[0].dims,n=e[0].dims[2],r=ne.size(t)/4,i=e[0].dataType,a=te("input",i,t,4),s=te("bias",i,[n],4),o=te("residual",i,t,4),l=ke("output",i,t,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(r/64)}}),getShaderSource:d=>` const channels = ${n}u / 4; ${d.declareVariables(a,s,o,l)} ${d.mainStart()} ${d.guardAgainstOutOfBoundsWorkgroupSizes(r)} let value = ${a.getByOffset("global_idx")} + ${s.getByOffset("global_idx % channels")} + ${o.getByOffset("global_idx")}; ${l.setByOffset("global_idx","value")} }`}},i1=e=>{mg(e.inputs),e.compute(gg(e.inputs))}}),yg,Ue,a1,s1,o1,l1,u1,d1,c1,p1,f1,wg,h1,m1,g1,y1,yl,w1,wl,_1,v1,$1,b1,x1,S1,E1,k1,C1,T1,I1,A1,O1,M1,z1,R1,P1,B1=ee(()=>{lt(),ze(),St(),Oe(),yg=(e,t,n,r,i,a)=>{let s=Math.ceil(t/4),o="";typeof i=="string"?o=`${i}(a)`:o=i("a");let l=te("inputData",n,[s],4),d=ke("outputData",r,[s],4);return` ${e.registerUniform("vec_size","u32").declareVariables(l,d)} ${a??""} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} let a = ${l.getByOffset("global_idx")}; ${d.setByOffset("global_idx",o)} }`},Ue=(e,t,n,r,i,a=e.dataType)=>({name:t,shaderCache:{hint:i,inputDependencies:["type"]},getShaderSource:s=>yg(s,ne.size(e.dims),e.dataType,a,n,r),getRunData:s=>({outputs:[{dims:e.dims,dataType:a}],dispatchGroup:{x:Math.ceil(ne.size(s[0].dims)/64/4)},programUniforms:[{type:"uint32",data:Math.ceil(ne.size(e.dims)/4)}]})}),a1=e=>{e.compute(Ue(e.inputs[0],"Abs","abs"))},s1=e=>{e.compute(Ue(e.inputs[0],"Acos","acos"))},o1=e=>{e.compute(Ue(e.inputs[0],"Acosh","acosh"))},l1=e=>{e.compute(Ue(e.inputs[0],"Asin","asin"))},u1=e=>{e.compute(Ue(e.inputs[0],"Asinh","asinh"))},d1=e=>{e.compute(Ue(e.inputs[0],"Atan","atan"))},c1=e=>{e.compute(Ue(e.inputs[0],"Atanh","atanh"))},p1=e=>tt(e),f1=(e,t)=>{let n;switch(t.to){case 10:n="vec4";break;case 1:n="vec4";break;case 12:n="vec4";break;case 6:n="vec4";break;case 9:n="vec4";break;default:throw new RangeError(`not supported type (specified in attribute 'to' from 'Cast' operator): ${t.to}`)}e.compute(Ue(e.inputs[0],"Cast",n,void 0,t.cacheKey,t.to))},wg=e=>{let t=e.length>=2&&e[1].data!==0?e[1].getFloat32Array()[0]:ff,n=e.length>=3&&e[2].data!==0?e[2].getFloat32Array()[0]:hf;return tt({min:t,max:n})},h1=(e,t)=>{let n=e.inputs.length===1?t:wg(e.inputs),r=ar(e.inputs[0].dataType);e.compute(Ue(e.inputs[0],"Clip",i=>`clamp(${i}, clip_min_, clip_max_)`,` const clip_min_: vec4<${r}> = vec4(${r}(${n.min})); const clip_max_: vec4<${r}> = vec4(${r}(${n.max})); `,n.cacheKey),{inputs:[0]})},m1=e=>{e.compute(Ue(e.inputs[0],"Ceil","ceil"))},g1=e=>{e.compute(Ue(e.inputs[0],"Cos","cos"))},y1=e=>{e.compute(Ue(e.inputs[0],"Cosh","cosh"))},yl=e=>tt(e),w1=(e,t)=>{let n=ar(e.inputs[0].dataType);e.compute(Ue(e.inputs[0],"Elu",r=>`elu_vf32(${r})`,` const elu_alpha_ = ${n}(${t.alpha}); fn elu_f32(a: ${n}) -> ${n} { return select((exp(a) - 1.0) * elu_alpha_, a, a >= 0.0); } fn elu_vf32(v: vec4<${n}>) -> vec4<${n}> { return vec4(elu_f32(v.x), elu_f32(v.y), elu_f32(v.z), elu_f32(v.w)); }`,t.cacheKey))},wl=(e,t="f32")=>` const r0: ${t} = 0.3275911; const r1: ${t} = 0.254829592; const r2: ${t} = -0.284496736; const r3: ${t} = 1.421413741; const r4: ${t} = -1.453152027; const r5: ${t} = 1.061405429; fn erf_vf32(v: ${e}) -> ${e} { let absv = abs(v); let x = 1.0 / (1.0 + r0 * absv); return sign(v) * (1.0 - ((((r5 * x + r4) * x + r3) * x + r2) * x + r1) * x * exp(-absv * absv)); }`,_1=e=>{let t=ar(e.inputs[0].dataType);e.compute(Ue(e.inputs[0],"Erf",n=>`erf_vf32(${n})`,wl(`vec4<${t}>`,t)))},v1=e=>{e.compute(Ue(e.inputs[0],"Exp","exp"))},$1=e=>{e.compute(Ue(e.inputs[0],"Floor","floor"))},b1=e=>{let t=ar(e.inputs[0].dataType);e.compute(Ue(e.inputs[0],"Gelu",n=>`0.5 * ${n} * (1.0 + erf_vf32(${n} * 0.7071067811865475))`,wl(`vec4<${t}>`,t)))},x1=(e,t)=>{let n=ar(e.inputs[0].dataType);e.compute(Ue(e.inputs[0],"LeakyRelu",r=>`select(leaky_relu_alpha_ * ${r}, ${r}, ${r} >= vec4<${n}>(0.0))`,`const leaky_relu_alpha_ = ${n}(${t.alpha});`,t.cacheKey))},S1=e=>{e.compute(Ue(e.inputs[0],"Not",t=>`!${t}`))},E1=e=>{e.compute(Ue(e.inputs[0],"Neg",t=>`-${t}`))},k1=e=>{e.compute(Ue(e.inputs[0],"Reciprocal",t=>`1.0/${t}`))},C1=e=>{let t=ar(e.inputs[0].dataType);e.compute(Ue(e.inputs[0],"Relu",n=>`select(vec4<${t}>(0.0), ${n}, ${n} > vec4<${t}>(0.0))`))},T1=e=>{e.compute(Ue(e.inputs[0],"Sigmoid",t=>`(1.0 / (1.0 + exp(-${t})))`))},I1=e=>{e.compute(Ue(e.inputs[0],"Sin","sin"))},A1=e=>{e.compute(Ue(e.inputs[0],"Sinh","sinh"))},O1=e=>{e.compute(Ue(e.inputs[0],"Sqrt","sqrt"))},M1=e=>{e.compute(Ue(e.inputs[0],"Tan","tan"))},z1=e=>{e.compute(Ue(e.inputs[0],"Tanh","tanh"))},R1=(e,t)=>{let n=ar(e.inputs[0].dataType);return e.compute(Ue(e.inputs[0],"ThresholdedRelu",r=>`select(vec4<${n}>(0.0), ${r}, ${r} > thresholded_relu_alpha_)`,`const thresholded_relu_alpha_ = vec4<${n}>(${t.alpha});`,t.cacheKey)),0},P1=e=>{e.compute(Ue(e.inputs[0],"Log","log"))}}),_g,vg,D1,dE=ee(()=>{ze(),Oe(),B1(),_g=e=>{if(e[0].dims.length!==3)throw new Error("input should have 3 dimensions");if(![2560,5120,10240].includes(e[0].dims[2]))throw new Error("hidden state should be 2560, 5120 or 10240");if(e[1].dims.length!==1)throw new Error("bias is expected to have 1 dimensions");if(e[0].dims[2]!==e[1].dims[0])throw new Error("last dimension of input and bias are not the same")},vg=e=>{let t=e[0].dims.slice();t[2]=t[2]/2;let n=te("input",e[0].dataType,e[0].dims,4),r=te("bias",e[0].dataType,[e[0].dims[2]],4),i=ke("output",e[0].dataType,t,4),a=ne.size(t)/4,s=wn(e[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)}}),getShaderSource:o=>` const M_SQRT2 = sqrt(2.0); const halfChannels = ${e[0].dims[2]/4/2}u; ${o.declareVariables(n,r,i)} ${wl(`vec4<${s}>`,s)} ${o.mainStart()} ${o.guardAgainstOutOfBoundsWorkgroupSizes(a)} let biasIdx = global_idx % halfChannels; let batchIndex = global_idx / halfChannels; let inputOffset = biasIdx + batchIndex * halfChannels * 2; let valueLeft = input[inputOffset] + bias[biasIdx]; let valueRight = input[inputOffset + halfChannels] + bias[biasIdx + halfChannels]; let geluRight = valueRight * 0.5 * (erf_vf32(valueRight / M_SQRT2) + 1); ${i.setByOffset("global_idx","valueLeft * geluRight")} }`}},D1=e=>{_g(e.inputs),e.compute(vg(e.inputs))}}),$g,bg,kn,N1,L1,F1,U1,W1,V1,j1,G1,H1,q1,cE=ee(()=>{lt(),ze(),Oe(),$g=(e,t,n,r,i,a,s,o,l,d,c,u,f)=>{let h,g;typeof o=="string"?h=g=(I,O)=>`${o}((${I}),(${O}))`:typeof o=="function"?h=g=o:(h=o.scalar,g=o.vector);let $=u?t.length:t,E=u?n.length:n,y=u?r.length:r,_=ke("outputData",c,y,4),v=te("aData",l,$,4),b=te("bData",d,E,4),C;if(i)if(a){let I=ne.size(t)===1,O=ne.size(n)===1,M=t.length>0&&t[t.length-1]%4===0,W=n.length>0&&n[n.length-1]%4===0;I||O?C=_.setByOffset("global_idx",g(I?`${v.type.value}(${v.getByOffset("0")}.x)`:v.getByOffset("global_idx"),O?`${b.type.value}(${b.getByOffset("0")}.x)`:b.getByOffset("global_idx"))):C=` let outputIndices = ${_.offsetToIndices("global_idx * 4u")}; let offsetA = ${v.broadcastedIndicesToOffset("outputIndices",_)}; let offsetB = ${b.broadcastedIndicesToOffset("outputIndices",_)}; ${_.setByOffset("global_idx",g(s||M?v.getByOffset("offsetA / 4u"):`${v.type.value}(${v.getByOffset("offsetA / 4u")}[offsetA % 4u])`,s||W?b.getByOffset("offsetB / 4u"):`${b.type.value}(${b.getByOffset("offsetB / 4u")}[offsetB % 4u])`))} `}else C=_.setByOffset("global_idx",g(v.getByOffset("global_idx"),b.getByOffset("global_idx")));else{if(!a)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let I=(O,M,W="")=>{let G=`aData[indexA${M}][componentA${M}]`,z=`bData[indexB${M}][componentB${M}]`;return` let outputIndices${M} = ${_.offsetToIndices(`global_idx * 4u + ${M}u`)}; let offsetA${M} = ${v.broadcastedIndicesToOffset(`outputIndices${M}`,_)}; let offsetB${M} = ${b.broadcastedIndicesToOffset(`outputIndices${M}`,_)}; let indexA${M} = offsetA${M} / 4u; let indexB${M} = offsetB${M} / 4u; let componentA${M} = offsetA${M} % 4u; let componentB${M} = offsetB${M} % 4u; ${O}[${M}] = ${W}(${h(G,z)}); `};c===9?C=` var data = vec4(0); ${I("data",0,"u32")} ${I("data",1,"u32")} ${I("data",2,"u32")} ${I("data",3,"u32")} outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:C=` ${I("outputData[global_idx]",0)} ${I("outputData[global_idx]",1)} ${I("outputData[global_idx]",2)} ${I("outputData[global_idx]",3)} `}return` ${e.registerUniform("vec_size","u32").declareVariables(v,b,_)} ${f??""} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${C} }`},bg=(e,t,n,r,i,a,s=n.dataType)=>{let o=!ne.areEqual(n.dims,r.dims),l=n.dims,d=ne.size(n.dims),c=!1,u=!1,f=[o];if(o){let g=ca.calcShape(n.dims,r.dims,!1);if(!g)throw new Error("Can't perform binary op on the given tensors");l=g,d=ne.size(l);let $=ne.size(n.dims)===1,E=ne.size(r.dims)===1,y=n.dims.length>0&&n.dims[n.dims.length-1]%4===0,_=r.dims.length>0&&r.dims[r.dims.length-1]%4===0;f.push($),f.push(E),f.push(y),f.push(_);let v=1;for(let b=1;bg.toString()).join("_"),inputDependencies:h?["rank","rank"]:["dims","dims"]},getShaderSource:g=>$g(g,n.dims,r.dims,l,c,o,u,i,n.dataType,r.dataType,s,h,a),getRunData:()=>({outputs:[{dims:l,dataType:s}],dispatchGroup:{x:Math.ceil(d/64/4)},programUniforms:h?[{type:"uint32",data:Math.ceil(ne.size(l)/4)},...le(n.dims),...le(r.dims),...le(l)]:[{type:"uint32",data:Math.ceil(ne.size(l)/4)}]})}},kn=(e,t,n,r,i,a)=>{e.compute(bg(t,i??"",e.inputs[0],e.inputs[1],n,r,a))},N1=e=>{kn(e,"Add",(t,n)=>`${t}+${n}`)},L1=e=>{kn(e,"Div",(t,n)=>`${t}/${n}`)},F1=e=>{kn(e,"Equal",{scalar:(t,n)=>`u32(${t}==${n})`,vector:(t,n)=>`vec4(${t}==${n})`},void 0,void 0,9)},U1=e=>{kn(e,"Mul",(t,n)=>`${t}*${n}`)},W1=e=>{let t=te("input",e.inputs[0].dataType,e.inputs[0].dims).type.value;kn(e,"Pow",{scalar:(n,r)=>`pow_custom(${n},${r})`,vector:(n,r)=>`pow_vector_custom(${n},${r})`},` fn pow_custom(a : ${t}, b : ${t}) -> ${t} { if (b == ${t}(0.0)) { return ${t}(1.0); } else if (a < ${t}(0.0) && f32(b) != floor(f32(b))) { return ${t}(pow(f32(a), f32(b))); // NaN } return select(sign(a), ${t}(1.0), round(f32(abs(b) % ${t}(2.0))) != 1.0) * ${t}(${t==="i32"?"round":""}(pow(f32(abs(a)), f32(b)))); } fn pow_vector_custom(a : vec4<${t}>, b : vec4<${t}>) -> vec4<${t}> { // TODO: implement vectorized pow return vec4<${t}>(pow_custom(a.x, b.x), pow_custom(a.y, b.y), pow_custom(a.z, b.z), pow_custom(a.w, b.w)); } `)},V1=e=>{kn(e,"Sub",(t,n)=>`${t}-${n}`)},j1=e=>{kn(e,"Greater",{scalar:(t,n)=>`u32(${t}>${n})`,vector:(t,n)=>`vec4(${t}>${n})`},void 0,void 0,9)},G1=e=>{kn(e,"Less",{scalar:(t,n)=>`u32(${t}<${n})`,vector:(t,n)=>`vec4(${t}<${n})`},void 0,void 0,9)},H1=e=>{kn(e,"GreaterOrEqual",{scalar:(t,n)=>`u32(${t}>=${n})`,vector:(t,n)=>`vec4(${t}>=${n})`},void 0,void 0,9)},q1=e=>{kn(e,"LessOrEqual",{scalar:(t,n)=>`u32(${t}<=${n})`,vector:(t,n)=>`vec4(${t}<=${n})`},void 0,void 0,9)}}),xg,Sg,Eg,kg,K1,Y1,pE=ee(()=>{ze(),St(),Oe(),xg=e=>{if(!e||e.length<1)throw new Error("too few inputs");let t=e[0].dataType,n=e[0].dims.length;for(let r of e){if(r.dataType!==t)throw new Error("input tensors should be one type");if(r.dims.length!==n)throw new Error("input tensors should have the same shape")}},Sg=(e,t)=>` fn calculateInputIndex(index: u32) -> u32 { let sizeInConcatAxis = array(${t}); for (var i: u32 = 0u; i < ${e}; i += 1u ) { if (index < sizeInConcatAxis[i]) { return i; } } return ${e}u; }`,Eg=(e,t)=>{let n=e.length,r=[];for(let i=0;i{let n=e[0].dims.slice();if(t>=n.length||t<-1*n.length)throw new Error("axis specified for concat doesn't match input dimensionality");let r=t<0?n.length+t:t,i=n.slice(0);for(let b=1;b`uniforms.sizeInConcatAxis${b}`).join(","),v=b=>` ${(()=>{b.registerUniform("outputSize","u32");for(let C=0;C(${_}); ${y} -= sizeInConcatAxis[inputIndex - 1u]; } ${Eg(o,E)} }`;return{name:"Concat",shaderCache:{hint:`${t}`,inputDependencies:c},getRunData:()=>({outputs:[{dims:i,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:h}),getShaderSource:v}},K1=(e,t)=>{xg(e.inputs),e.compute(kg(e.inputs,t.axis))},Y1=e=>tt({axis:e.axis})}),ya,yf,xi=ee(()=>{ze(),ya=(e,t)=>{switch(e.activation){case"Relu":return{activationFunction:"",applyActivation:`value = max(value, ${t}(0.0));`};case"Sigmoid":return{activationFunction:"",applyActivation:`value = (${t}(1.0) / (${t}(1.0) + exp(-value)));`};case"Clip":return{activationFunction:`const clip_min_=${t}(${e.clipMin});const clip_max_=${t}(${e.clipMax});`,applyActivation:"value = clamp(value, clip_min_, clip_max_);"};default:return{activationFunction:"",applyActivation:""}}},yf=e=>{let t=(e==null?void 0:e.activation)||"";if(t==="Clip"){let[n,r]=(e==null?void 0:e.activation_params)||[ff,hf];return{activation:t,clipMax:r,clipMin:n,activationCacheKey:`${t}:${n},${r}`}}return{activation:t,activationCacheKey:t}}}),Mt,wf,_f=ee(()=>{Mt=(e,t)=>{switch(e){case 1:return t;case 2:return`vec2<${t}>`;case 3:return`vec3<${t}>`;case 4:return`vec4<${t}>`;default:throw new Error(`${e}-component is not supported.`)}},wf=e=>` ${e?"value = value + getBiasByOutputCoords(coords);":""} `}),vf,Q1=ee(()=>{vf=e=>` fn getIndexFromCoords4D(coords : vec4, shape : vec4) -> i32 { return dot(coords, vec4( shape.y * shape.z * shape.w, shape.z * shape.w, shape.w, 1)); } fn getOutputIndexFromCoords(coords : vec4) -> i32 { return dot(coords, vec4( i32(${e}.x), i32(${e}.y), i32(${e}.z), 1)); } `}),Cg,Tg,Jl,$d,Ig,eu,Ag,$f,xu=ee(()=>{ze(),Oe(),xi(),_f(),Cg=(e,t)=>e?` mm_Asub[inputRow][inputCol] = mm_readA(batch, kStart + inputRow, globalRowStart / innerElementSize + inputCol${t?", batchIndices":""}); `:` mm_Asub[inputRow][inputCol] = mm_readA(batch, globalRow + innerRow, kStart / innerElementSize + inputCol${t?", batchIndices":""}); `,Tg=(e,t)=>e?` let ACached0 = mm_Asub[k * innerElementSize][localRow]; let ACached1 = mm_Asub[k * innerElementSize + 1][localRow]; let ACached2 = mm_Asub[k * innerElementSize + 2][localRow]; ${t===3?"":"let ACached3 = mm_Asub[k * innerElementSize + 3][localRow];"} for (var i = 0; i < rowPerThread; i = i + 1) { acc[i] = BCached0 * ACached0[i] + acc[i]; acc[i] = BCached1 * ACached1[i] + acc[i]; acc[i] = BCached2 * ACached2[i] + acc[i]; ${t===3?"":"acc[i] = BCached3 * ACached3[i] + acc[i];"} }`:` for (var i = 0; i < rowPerThread; i = i + 1) { let ACached = mm_Asub[tileRow + i][k]; acc[i] = BCached0 * ACached.x + acc[i]; acc[i] = BCached1 * ACached.y + acc[i]; acc[i] = BCached2 * ACached.z + acc[i]; ${t===3?"":"acc[i] = BCached3 * ACached.w + acc[i];"} }`,Jl=(e,t,n="f32",r,i=!1,a=32,s=!1,o=32)=>{let l=t[1]*e[1],d=t[0]*e[0],c=i?l:a,u=i?a:l,f=c/t[0],h=a/t[1];if(!((i&&f===4&&e[1]===4||!i&&(f===3||f===4))&&c%t[0]===0&&a%t[1]===0&&e[0]===4))throw new Error(`If transposeA ${i} is true, innerElementSize ${f} and workPerThread[1] ${e[1]} must be 4. Otherwise, innerElementSize ${f} must be 3 or 4. tileAWidth ${c} must be divisible by workgroupSize[0]${t[0]}. tileInner ${a} must be divisible by workgroupSize[1] ${t[1]}. colPerThread ${e[0]} must be 4.`);return` var mm_Asub: array, ${c/f}>, ${u}>; var mm_Bsub: array, ${d/e[0]}>, ${a}>; const rowPerThread = ${e[1]}; const colPerThread = ${e[0]}; const innerElementSize = ${f}; const tileInner = ${a}; @compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]}) fn main(@builtin(local_invocation_id) localId : vec3, @builtin(global_invocation_id) globalId : vec3, @builtin(workgroup_id) workgroupId : vec3) { let localRow = i32(localId.y); let tileRow = localRow * rowPerThread; let tileCol = i32(localId.x); let globalRow =i32(globalId.y) * rowPerThread; let globalCol = i32(globalId.x); let batch = ${s?"0":"i32(globalId.z)"}; ${r?`let batchIndices = ${r.offsetToIndices("u32(batch)")};`:""} let globalRowStart = i32(workgroupId.y) * ${l}; let numTiles = ${s?`${Math.ceil(o/a)}`:"(uniforms.dimInner - 1) / tileInner + 1"}; var kStart = ${s?`i32(globalId.z) * ${o}`:"0"}; var acc: array, rowPerThread>; // Loop over shared dimension. let tileRowB = localRow * ${h}; for (var t = 0; t < numTiles; t = t + 1) { // Load one tile of A into local memory. for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { let inputRow = tileRow + innerRow; let inputCol = tileCol; ${Cg(i,r)} } // Load one tile of B into local memory. for (var innerRow = 0; innerRow < ${h}; innerRow = innerRow + 1) { let inputRow = tileRowB + innerRow; let inputCol = tileCol; mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol${r?", batchIndices":""}); } kStart = kStart + tileInner; workgroupBarrier(); // Compute acc values for a single thread. for (var k = 0; k < tileInner / innerElementSize; k = k + 1) { let BCached0 = mm_Bsub[k * innerElementSize][tileCol]; let BCached1 = mm_Bsub[k * innerElementSize + 1][tileCol]; let BCached2 = mm_Bsub[k * innerElementSize + 2][tileCol]; ${f===3?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"} ${Tg(i,f)} } workgroupBarrier(); } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]); } }`},$d=(e,t)=>e?` mm_Asub[inputRow][inputCol] = mm_readA(batch, kStart + inputRow, globalRowStart + inputCol${t?", batchIndices":""}); `:` mm_Asub[inputRow][inputCol] = mm_readA(batch, globalRowStart + inputRow, kStart + inputCol${t?", batchIndices":""}); `,Ig=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",eu=(e,t,n="f32",r,i=!1,a=32,s=!1,o=32,l=!1)=>{let d=e[1]*t[1],c=e[0]*t[0],u=i?d:a,f=i?a:d;if(!(f%t[1]===0&&u%t[0]===0&&a%t[1]===0))throw new Error(`tileAHight ${f} must be divisible by workgroupSize[1]${t[1]}, tileAWidth ${u} must be divisible by workgroupSize[0]${t[0]}, tileInner ${a} must be divisible by workgroupSize[1]${t[1]}`);let h=f/t[1],g=u/t[0],$=a/t[1],E=l?` let localRow = i32(localId.y); let localCol = i32(localId.x); let globalRowStart = i32(workgroupId.y) * ${d}; let globalColStart = i32(workgroupId.x) * ${c}; // Loop over shared dimension. for (var t = 0; t < numTiles; t = t + 1) { // Load one tile of A into local memory. for (var inputRow = localRow; inputRow < ${f}; inputRow = inputRow + ${t[1]}) { for (var inputCol = localCol; inputCol < ${u}; inputCol = inputCol + ${t[0]}) { ${$d(i,r)} } } // Load one tile of B into local memory. for (var inputRow = localRow; inputRow < ${a}; inputRow = inputRow + ${t[1]}) { for (var inputCol = localCol; inputCol < ${c}; inputCol = inputCol + ${t[0]}) { mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalColStart + inputCol${r?", batchIndices":""}); } } kStart = kStart + tileInner; workgroupBarrier(); // Compute acc values for a single thread. var BCached : array<${n}, colPerThread>; for (var k = 0; k < tileInner; k = k + 1) { for (var inner = 0; inner < colPerThread; inner = inner + 1) { BCached[inner] = mm_Bsub[k][localCol + inner * ${t[0]}]; } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { let ACached = ${i?`mm_Asub[k][localRow + innerRow * ${t[1]}];`:`mm_Asub[localRow + innerRow * ${t[1]}][k];`} for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol]; } } } workgroupBarrier(); } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { let gRow = globalRowStart + localRow + innerRow * ${t[1]}; for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { let gCol = globalColStart + localCol + innerCol * ${t[0]}; mm_write(batch, gRow, gCol, acc[innerRow][innerCol]); } } `:` let tileRow = i32(localId.y) * rowPerThread; let tileCol = i32(localId.x) * colPerThread; let globalRow = i32(globalId.y) * rowPerThread; let globalCol = i32(globalId.x) * colPerThread; let globalRowStart = i32(workgroupId.y) * ${d}; let tileRowA = i32(localId.y) * ${h}; let tileColA = i32(localId.x) * ${g}; let tileRowB = i32(localId.y) * ${$}; // Loop over shared dimension. for (var t = 0; t < numTiles; t = t + 1) { // Load one tile of A into local memory. for (var innerRow = 0; innerRow < ${h}; innerRow = innerRow + 1) { for (var innerCol = 0; innerCol < ${g}; innerCol = innerCol + 1) { let inputRow = tileRowA + innerRow; let inputCol = tileColA + innerCol; ${$d(i,r)} } } // Load one tile of B into local memory. for (var innerRow = 0; innerRow < ${$}; innerRow = innerRow + 1) { for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { let inputRow = tileRowB + innerRow; let inputCol = tileCol + innerCol; mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol + innerCol${r?", batchIndices":""}); } } kStart = kStart + tileInner; workgroupBarrier(); // Compute acc values for a single thread. var BCached : array<${n}, colPerThread>; for (var k = 0; k < tileInner; k = k + 1) { for (var inner = 0; inner < colPerThread; inner = inner + 1) { BCached[inner] = mm_Bsub[k][tileCol + inner]; } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { ${Ig(i)} for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol]; } } } workgroupBarrier(); } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { mm_write(batch, globalRow + innerRow, globalCol + innerCol, acc[innerRow][innerCol]); } } `;return` var mm_Asub : array, ${f}>; var mm_Bsub : array, ${a}>; const rowPerThread = ${e[1]}; const colPerThread = ${e[0]}; const tileInner = ${a}; @compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]}) fn main(@builtin(local_invocation_id) localId : vec3, @builtin(global_invocation_id) globalId : vec3, @builtin(workgroup_id) workgroupId : vec3) { let batch = ${s?"0":"i32(globalId.z)"}; ${r?`let batchIndices = ${r.offsetToIndices("u32(batch)")};`:""} let numTiles = ${s?`${Math.ceil(o/a)}`:"(uniforms.dimInner - 1) / tileInner + 1"}; var kStart = ${s?`i32(globalId.z) * ${o}`:"0"}; var acc : array, rowPerThread>; // Without this initialization strange values show up in acc. for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { acc[innerRow][innerCol] = 0.0; } } ${E} } `},Ag=(e,t,n,r,i,a=!1)=>{let[s,o,l]=i,[d,c,u,f]=r,h=Ns(s,l),g=Ns(o,l),$=wn(r[0].type.tensor),E=()=>{let _=c.rank,v=d.rank,b=`var aIndices: ${c.type.indices};`;for(let C=_-2-1,I=v-1;C>=0;C--,I--)b+=` aIndices[${C}] = ${v>1?`batchIndices[${I}]`:"batchIndices"};`;return h.forEach(C=>{b+=` aIndices[${C}] = 0;`}),b+=` aIndices[${_-2}] = u32(row); aIndices[${_-1}] = u32(colIn);`,b},y=()=>{let _=u.rank,v=d.rank,b=`var bIndices: ${u.type.indices};`;for(let C=_-2-1,I=v-1;C>=0;C--,I--)b+=` bIndices[${C}] = ${v>1?`batchIndices[${I}]`:"batchIndices"};`;return g.forEach(C=>{b+=` bIndices[${C}] = 0;`}),b+=` bIndices[${_-2}] = u32(row); bIndices[${_-1}] = u32(colIn);`,b};return` fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${d.type.indices}) -> ${Mt(e,$)} { var value = ${Mt(e,$)}(0.0); let col = colIn * ${e}; if(row < uniforms.dimAOuter && col < uniforms.dimInner) { ${E()} value = ${c.getByIndices("aIndices")}; } return value; } fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${d.type.indices}) -> ${Mt(e,$)} { var value = ${Mt(e,$)}(0.0); let col = colIn * ${e}; if(row < uniforms.dimInner && col < uniforms.dimBOuter) { ${y()} value = ${u.getByIndices("bIndices")}; } return value; } fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${Mt(e,$)}) { let col = colIn * ${e}; if (row < uniforms.dimAOuter && col < uniforms.dimBOuter) { var value = valueIn; let coords = vec3(batch, row, colIn); ${t?`value = value + ${a?"bias[colIn]":`${Mt(e,$)}(bias[row])`};`:""} ${n} ${f.setByIndices("vec3(coords)","value")} } } `},$f=(e,t,n,r,i=!1)=>{let a=e[0].dims,s=e[1].dims,o=a.slice(0,-2),l=s.slice(0,-2),d=r?r.slice(0,-2):n.slice(0,-2),c=xt(d.length),u=c?d.length:d,f=mf("batchDims",e[0].dataType,u,1),h=ne.size(d),g=a[a.length-2],$=a[a.length-1],E=s[s.length-1],y=$%4===0&&E%4===0,_=g<=8?[4,1,1]:[4,4,1],v=[8,8,1],b=[Math.ceil(E/v[0]/_[0]),Math.ceil(g/v[1]/_[1]),Math.ceil(h/v[2]/_[2])],C=wn(e[0].dataType),I=y?4:1,O=[...o,g,$/I],M=xt(O.length),W=M?O.length:O,G=[...l,$,E/I],z=xt(G.length),K=z?G.length:G,ae=[h,g,E/I],ue=te("a",e[0].dataType,W,I),R=te("b",e[1].dataType,K,I),H=ke("result",e[0].dataType,ae.length,I),re=[ue,R],L=[{type:"int32",data:g},{type:"int32",data:E},{type:"int32",data:$}];c&&L.push(...le(d)),M&&L.push(...le(O)),z&&L.push(...le(G));let X=[];X.push(M?"rank":"dims"),X.push(z?"rank":"dims");let Z=e.length>2,{activationFunction:V,applyActivation:ie}=ya(t,H.type.value),xe=Ag(I,Z,ie,[f,ue,R,H],[o,l,d],i);if(Z){let He=i?I:1;re.push(te("bias",e[2].dataType,e[2].dims.length,He)),L.push(...le(e[2].dims)),X.push("rank")}L.push(...le(ae));let Re=He=>` ${He.registerUniform("dimAOuter","i32").registerUniform("dimBOuter","i32").registerUniform("dimInner","i32").registerInternalVariables(f).declareVariables(...re,H)} ${V} ${xe} ${y?Jl(_,v,C,f):eu(_,v,C,f)} `;return{name:"MatMul",shaderCache:{hint:t.activationCacheKey+`${_}${y}${i}`,inputDependencies:X},getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:b[0],y:b[1],z:b[2]},programUniforms:L}),getShaderSource:Re}}}),Og,X1,fE=ee(()=>{bi(),Oe(),xi(),_f(),Q1(),xu(),Og=(e,t,n,r,i=!1,a,s=4,o=4,l=4,d="f32")=>{let c=G=>{switch(G){case 1:return"resData = x[xIndex];";case 3:return`resData = vec3<${d}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return"resData = x[xIndex / 4];";default:throw new Error(`innerElementSize ${G} is not supported.`)}},u=G=>{switch(G){case 1:return"return w[row * i32(uniforms.w_shape[3]) + colIn];";case 4:return"return w[row * i32(uniforms.w_shape[3]) / 4 + colIn];";default:throw new Error(`innerElementSize ${G} is not supported.`)}},f=e?` let coord = vec4(batch, xRow, xCol, xCh); `:` let coord = vec4(batch, xCh, xRow, xCol); `,h=e?` let coords = vec4( batch, row / outWidth, row % outWidth, col); `:` let coords = vec4( batch, row, col / outWidth, col % outWidth); `,g=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",$=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",E=e?"row":"col",y=e?"col":"row",_=` let inChannels = i32(uniforms.w_shape[2]); let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; let outRow = ${E} / outWidth; let outCol = ${E} % outWidth; let WRow = ${y} / (filterDims[1] * inChannels); let WCol = ${y} / inChannels % filterDims[1]; let xRow = outRow * stride[0] + dilation[0] * WRow - pad[0]; let xCol = outCol * stride[1] + dilation[1] * WCol - pad[1]; let xCh = ${y} % inChannels; var resData = ${Mt(s,d)}(0.0); // The bounds checking is always needed since we use it to pad zero for // the 'same' padding type. if (xRow >= 0 && xRow < ${g} && xCol >= 0 && xCol < ${$}) { ${f} let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape)); ${c(s)} } return resData;`,v=e?t&&r?` let col = colIn * ${s}; ${_}`:` let col = colIn * ${s}; if (row < uniforms.dimAOuter && col < uniforms.dimInner) { ${_} } return ${Mt(s,d)}(0.0);`:r&&n?` let col = colIn * ${s}; ${_}`:` let col = colIn * ${s}; if (row < uniforms.dimInner && col < uniforms.dimBOuter) { ${_} } return ${Mt(s,d)}(0.0);`,b=`${u(o)}`,C=Mt(l,d),I=Mt(e?s:o,d),O=Mt(e?o:s,d),{activationFunction:M,applyActivation:W}=ya(a,C);return` ${M} fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${I} { ${e?v:b} } fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${O} { ${e?b:v} } fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${C}) { let col = colIn * ${l}; if (row < uniforms.dimAOuter && col < uniforms.dimBOuter) { var value = valueIn; let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; ${h} ${wf(i)} ${W} setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); } }`},X1=(e,t,n,r,i,a,s,o)=>{let l=t.format==="NHWC",d=l?e[0].dims[3]:e[0].dims[1],c=n[0],u=l?n[2]:n[3],f=l?n[1]:n[2],h=l?n[3]:n[1],g=l&&(d%4===0||d%3===0)&&h%4===0,$=l?h:u*f,E=l?u*f:h,y=[8,8,1],_=r<=8?[4,1,1]:[4,4,1],v=[Math.ceil($/y[0]/_[0]),Math.ceil(E/y[1]/_[1]),Math.ceil(c/y[2]/_[2])];$t("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${v}`);let b=g?l&&d%4!==0?3:4:1,C=y[1]*_[1],I=y[0]*_[0],O=Math.max(y[0]*b,y[1]),M=r%C===0,W=i%I===0,G=a%O===0,z=g?[b,4,4]:[1,1,1],K=wn(e[0].dataType),ae=g?4:1,ue=[{type:"int32",data:r},{type:"int32",data:i},{type:"int32",data:a}],R=te("x",e[0].dataType,e[0].dims.length,b===3?1:b),H=te("w",e[1].dataType,e[1].dims.length,ae),re=[R,H];ue.push(...le(e[0].dims)),ue.push(...le(e[1].dims));let L=` fn setOutputAtIndex(flatIndex : i32, value : ${g?`vec4<${K}>`:K}) { result[flatIndex] = ${g?`vec4<${K}>`:K}(value); } fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${g?`vec4<${K}>`:K}) { let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3)); setOutputAtIndex(flatIndex ${g?"/ 4":""}, value); }`;if(s){let Z=te("bias",e[2].dataType,e[2].dims.length,ae);re.push(Z),ue.push(...le(e[2].dims)),L+=` fn getBiasByOutputCoords(coords : vec4) -> ${g?`vec4<${K}>`:K} { return bias[coords.${l?"w":"y"}${g?"/ 4":""}]; }`}let X=ke("result",e[0].dataType,n.length,ae);return ue.push(...le(n)),{name:"Conv2DMatMul",shaderCache:{hint:t.cacheKey},getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:v[0],y:v[1],z:v[2]},programUniforms:ue}),getShaderSource:Z=>` ${vf("uniforms.result_strides")} //struct Uniforms { xShape : vec4, wShape : vec4, outShape : vec4, // outShapeStrides: vec3, filterDims : vec2, pad : vec2, stride : vec2, // dilation : vec2, dimAOuter : i32, dimBOuter : i32, dimInner : i32 }; ${Z.registerUniform("dimAOuter","i32").registerUniform("dimBOuter","i32").registerUniform("dimInner","i32").declareVariables(...re,X)} const filterDims : vec2 = vec2(${t.kernelShape[0]}, ${t.kernelShape[1]}); const pad : vec2 = vec2(${t.pads[0]}, ${t.pads[1]}); const stride : vec2 = vec2(${t.strides[0]}, ${t.strides[1]}); const dilation : vec2 = vec2(${t.dilations[0]}, ${t.dilations[1]}); ${L} ${Og(l,M,W,G,s,t,z[0],z[1],z[2],K)} ${g?Jl(_,y,K,void 0,!l,O):eu(_,y,K,void 0,!l,O,!1,void 0,o)}`}}}),Gc,hE=ee(()=>{ze(),Oe(),e2(),xi(),Gc=(e,t,n)=>{let r=e.length>2,i=r?"value += b[output_channel];":"",a=e[0].dims,s=e[1].dims,o=s[0]/t.group,l=t.format==="NHWC",d=qc(a,s,t.dilations,t.pads,t.strides,l),c=ne.size(d),u=ke("output",e[0].dataType,d),{activationFunction:f,applyActivation:h}=ya(t,u.type.value),g=te("x",e[0].dataType,a),$=te("w",e[1].dataType,s),E=[g,$];r&&E.push(te("b",e[2].dataType,e[2].dims));let y=_=>` const strides: vec2 = vec2(${t.strides[0]}u, ${t.strides[1]}u); const pads: vec2 = vec2(${t.pads[0]}u, ${t.pads[1]}u); ${_.declareVariables(...E,u)} ${f} ${_.mainStart()} ${_.guardAgainstOutOfBoundsWorkgroupSizes(c)} let outputIndices = ${u.offsetToIndices("global_idx")}; let batch: u32 = outputIndices[0]; let output_channel: u32 = outputIndices[${l?3:1}]; let xRCCorner: vec2 = vec2(outputIndices[${l?1:2}], outputIndices[${l?2:3}]) * strides - pads; let group_id: u32 = output_channel / ${o}u; var value: ${u.type.value} = ${u.type.value}(0); for (var wInChannel: u32 = 0u; wInChannel < ${s[1]}u; wInChannel++) { let input_channel = group_id * ${s[1]}u + wInChannel; for (var wHeight: u32 = 0u; wHeight < ${s[2]}u; wHeight++) { let xHeight = xRCCorner.x + wHeight * ${t.dilations[0]}u; if (xHeight < 0u || xHeight >= ${a[l?1:2]}u) { continue; } for (var wWidth: u32 = 0u; wWidth < ${s[3]}u; wWidth++) { let xWidth = xRCCorner.y + wWidth * ${t.dilations[1]}u; if (xWidth < 0u || xWidth >= ${a[l?2:3]}u) { continue; } let xVal = ${l?g.get("batch","xHeight","xWidth","input_channel"):g.get("batch","input_channel","xHeight","xWidth")}; let wVal = ${$.get("output_channel","wInChannel","wHeight","wWidth")}; value += xVal*wVal; } } } ${i} ${h} ${u.setByOffset("global_idx","value")} }`;return{name:"GroupedConv",shaderCache:{hint:t.cacheKey},getRunData:()=>({outputs:[{dims:n?n(d):d,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)}}),getShaderSource:y}}}),Hc,Mg,Z1,J1=ee(()=>{ze(),xu(),Oe(),xi(),Hc=(e,t,n,r,i=!1)=>{let a=e[0].dims,s=e[1].dims,o=a[a.length-2],l=s[s.length-1],d=a[a.length-1],c=rn(l),u=rn(d),f=rn(o),h=ne.size(n)/c/f,g=e.length>2,$=r?r.slice(0,-2):n.slice(0,-2),E=[ne.size($),o,l],y=[{type:"uint32",data:h},{type:"uint32",data:o},{type:"uint32",data:l},{type:"uint32",data:d},...le($),...le(a),...le(s)];g&&y.push(...le(e[2].dims)),y.push(...le(E));let _=v=>{let b=mf("batch_dims",e[0].dataType,$.length),C=te("a",e[0].dataType,a.length,u),I=te("b",e[1].dataType,s.length,c),O=ke("output",e[0].dataType,E.length,c),{activationFunction:M,applyActivation:W}=ya(t,O.type.value),G=[C,I],z="";if(g){let L=i?c:1;G.push(te("bias",e[2].dataType,e[2].dims.length,L)),z=`${i?`value += bias[col / ${L}];`:`value += ${O.type.value}(bias[row + i]);`}`}let K=a.slice(0,-2),ae=s.slice(0,-2),ue=Ns(K,$),R=Ns(ae,$),H=(L,X)=>{let Z=L.rank,V=L.name;if(Z===2)return`var ${V}_indices = ${L.type.indices}(0u, 0u);`;let ie=b.rank,xe=`var ${V}_indices: ${L.type.indices};`;for(let Re=Z-2-1,He=ie-1;Re>=0;Re--,He--)xe+=` ${V}_indices[${Re}] = ${ie>1?`batch_indices[${He}]`:"batch_indices"};`;return X.forEach(Re=>{xe+=` ${V}_indices[${Re}] = 0;`}),xe+=`${V}_indices[${Z-2}] = 0u; ${V}_indices[${Z-1}] = 0u;`,xe},re=()=>{let L=`var a_data: ${C.type.value};`;for(let X=0;X; for (var k: u32 = 0u; k < uniforms.K; k = k + ${u}) { ${re()} } for (var i = 0u; i < ${f}u; i++) { var value = values[i]; ${z} ${W} let cur_indices = ${O.type.indices}(batch, row + i, col); let offset = ${O.indicesToOffset("cur_indices")}; ${O.setByOffset(`offset / ${c}`,"value")}; } } `};return{name:"MatMulNaive",shaderCache:{hint:`${t.activationCacheKey}_${c}_${u}_${f}_${i}`,inputDependencies:g?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:y}),getShaderSource:_}},Mg=e=>{if(!e||e.length!==2)throw new Error("MatMul requires 2 inputs.");if(e[0].dims[e[0].dims.length-1]!==e[1].dims[e[1].dims.length-2])throw new Error("shared dimension does not match.")},Z1=e=>{Mg(e.inputs);let t=ca.calcShape(e.inputs[0].dims,e.inputs[1].dims,!0);if(!t)throw new Error("Can't use matmul on the given tensors");let n=t[t.length-1],r=e.inputs[0].dims[e.inputs[0].dims.length-1];n<8&&r<8?e.compute(Hc(e.inputs,{activation:"",activationCacheKey:""},t)):e.compute($f(e.inputs,{activation:"",activationCacheKey:""},t))}}),qc,bd,zg,xd,Kc,Rg,Pg,Yc,e2=ee(()=>{ze(),St(),fE(),xu(),hE(),xi(),J1(),qs(),qc=(e,t,n,r,i,a)=>{let s=e[0],o=e.slice(a?1:2,a?3:4),l=o.length,d=t[0],c=t.slice(2).map((f,h)=>f+(f-1)*(n[h]-1)),u=o.map((f,h)=>f+r[h]+r[h+l]).map((f,h)=>Math.floor((f-c[h]+i[h])/i[h]));return u.splice(0,0,s),u.splice(a?3:1,0,d),u},bd=[2,3,1,0],zg=(e,t)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length!==4&&e[0].dims.length!==3)throw new Error("currently only support conv 1D and 2D");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");let n=e[0].dims[t.format==="NHWC"?e[0].dims.length-1:1],r=e[1].dims[1]*t.group;if(n!==r)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");if(e.length===3&&(e[2].dims.length!==1||e[1].dims[0]!==e[2].dims[0]))throw new Error("invalid bias");let i=e[0].dims.length-2;if(t.dilations.length!==i)throw new Error(`dilations should be ${i}D`);if(t.strides.length!==i)throw new Error(`strides should be ${i}D`);if(t.pads.length!==i*2)throw new Error(`pads should be ${i*2}D`);if(t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape")},xd=(e,t)=>{let n=e.kernelShape.slice();for(let a=2;a{let t=yf(e),n=e.format,r=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],i=e.dilations,a=e.group,s=e.kernel_shape,o=e.pads,l=e.strides,d=e.w_is_const();return tt({autoPad:r,format:n,dilations:i,group:a,kernelShape:s,pads:o,strides:l,wIsConst:d,...t})},Rg=(e,t,n)=>{let r=xd(n,t),i=n.format==="NHWC";if(n.group!==1){e.compute(Gc(t,r));return}let a=t.length===3,s=t[0].dims[i?1:2],o=t[0].dims[i?2:3],l=t[0].dims[i?3:1],d=t[1].dims[2],c=t[1].dims[3],u=qc(t[0].dims,t[1].dims,n.dilations,r.pads,n.strides,i),f=u[i?1:2],h=u[i?2:3],g=u[i?3:1],$=i&&d===s&&c===o&&n.pads[0]===0&&n.pads[1]===0;if($||d===1&&c===1&&n.dilations[0]===1&&n.dilations[1]===1&&n.strides[0]===1&&n.strides[1]===1&&n.pads[0]===0&&n.pads[1]===0){let I=u[0],O,M,W,G=[];if(i){let ae=e.kernelCustomData.wT??e.compute(Gr(t[1],bd),{inputs:[1],outputs:[n.wIsConst?-2:-1]})[0];if(n.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=ae),$){let ue=s*o*l;O=t[0].reshape([1,I,ue]),M=ae.reshape([1,ue,g]),W=[1,I,g]}else O=t[0].reshape([I,s*o,l]),M=ae.reshape([1,l,g]),W=[I,f*h,g];G.push(O),G.push(M)}else O=t[0].reshape([I,l,s*o]),M=t[1].reshape([1,g,l]),W=[I,g,f*h],G.push(M),G.push(O);a&&G.push(t[2]);let z=W[2],K=G[0].dims[G[0].dims.length-1];z<8&&K<8?e.compute(Hc(G,r,u,W,i),{inputs:G}):e.compute($f(G,r,u,W,i),{inputs:G});return}let E=!0,y=e.kernelCustomData.wT??e.compute(Gr(t[1],bd),{inputs:[1],outputs:[n.wIsConst?-2:-1]})[0];n.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=y);let _=[t[0],y];a&&_.push(t[2]);let v=i?f*h:g,b=i?g:f*h,C=d*c*l;e.compute(X1(_,r,u,v,b,C,a,E),{inputs:_})},Pg=(e,t)=>{let n=t.format==="NHWC",r=[e.inputs[0].reshape(n?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&r.push(e.inputs[2]);let i=[0,t.pads[0],0,t.pads[1]],a=[1].concat(t.strides),s=[1].concat(t.dilations),o=[1].concat(t.kernelShape),l=xd({...t,pads:i,strides:a,dilations:s,kernelShape:o},r);e.compute(Gc(r,l,d=>n?[d[0],d[2],d[3]]:[]))},Yc=(e,t)=>{zg(e.inputs,t),e.inputs[0].dims.length===3?Pg(e,t):Rg(e,e.inputs,t)}}),Bg,t2,mE=ee(()=>{bi(),Oe(),xi(),_f(),Q1(),xu(),Bg=(e,t=!1,n,r=4)=>{let i=Mt(r,"f32"),a=y=>{switch(y){case 1:return"return w[getIndexFromCoords4D(coord, vec4(uniforms.w_shape))];";case 4:return` let coord1 = vec4(coordX, coordY, col + 1, rowInner); let coord2 = vec4(coordX, coordY, col + 2, rowInner); let coord3 = vec4(coordX, coordY, col + 3, rowInner); let v0 = w[getIndexFromCoords4D(coord, vec4(uniforms.w_shape))]; let v1 = w[getIndexFromCoords4D(coord1, vec4(uniforms.w_shape))]; let v2 = w[getIndexFromCoords4D(coord2, vec4(uniforms.w_shape))]; let v3 = w[getIndexFromCoords4D(coord3, vec4(uniforms.w_shape))]; return vec4(v0, v1, v2, v3); `;default:throw new Error(`innerElementSize ${y} is not supported.`)}},s=e?` let coord = vec4(batch, iXR, iXC, xCh); `:` let coord = vec4(batch, xCh, iXR, iXC); `,o=e?` let coords = vec4( batch, row / outWidth, row % outWidth, col); `:` let coords = vec4( batch, row, col / outWidth, col % outWidth); `,l=e?"outBackprop[1]":"outBackprop[2]",d=e?"outBackprop[2]":"outBackprop[3]",c=e?"row":"col",u=e?"col":"row",f=` let inChannels = ${e?"outBackprop[3]":"outBackprop[1]"}; let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; let outRow = ${c} / outWidth; let outCol = ${c} % outWidth; let WRow = ${u} / (filterDims[1] * inChannels); let WCol = ${u} / inChannels % filterDims[1]; let xR = f32(outRow - pads[0] + dilation[0] * WRow) / f32(strides[0]); let xC = f32(outCol - pads[1] + dilation[1] * WCol) / f32(strides[1]); if (xR < 0.0 || xR >= f32(${l}) || fract(xR) > 0.0) { return ${i}(0.0); } if (xC < 0.0 || xC >= f32(${d}) || fract(xC) > 0.0) { return ${i}(0.0); } let iXR = i32(xR); let iXC = i32(xC); let xCh = ${u} % inChannels; ${s} return x[getIndexFromCoords4D(coord, vec4(uniforms.x_shape))/${r}];`,h=e?` let col = colIn * ${r}; if (row < uniforms.dimAOuter && col < uniforms.dimInner) { ${f} } return ${i}(0.0);`:` let col = colIn * ${r}; if (row < uniforms.dimInner && col < uniforms.dimBOuter) { ${f} } return ${i}(0.0);`,g=` let col = colIn * ${r}; let inChannels = ${e?"outBackprop[3]":"outBackprop[1]"}; let coordX = filterDims.x - 1 - row / (filterDims[1] * inChannels); let coordY = filterDims.y - 1 - (row / inChannels) % filterDims[1]; if (${e?"row < uniforms.dimInner && col < uniforms.dimBOuter":"row < uniforms.dimInner && col < uniforms.dimAOuter"} && coordX >= 0 && coordY >= 0) { let rowInner = row % inChannels; let coord = vec4(coordX, coordY, col, rowInner); ${a(r)} } return ${i}(0.0); `,{activationFunction:$,applyActivation:E}=ya(n,i);return` ${$} fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${i} { ${e?h:g} } fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${i} { ${e?g:h} } fn mm_write(batch: i32, row : i32, colIn : i32, valueInput : ${i}) { let col = colIn * ${r}; if (row < uniforms.dimAOuter && col < uniforms.dimBOuter) { var value = valueInput; let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; ${o} ${wf(t)} ${E} result[getIndexFromCoords4D(coords, vec4(uniforms.result_shape))/${r}] = value; } }`},t2=(e,t,n,r,i,a,s,o)=>{let l=t.format==="NHWC",d=l?e[0].dims[3]:e[0].dims[1],c=n[0],u=l?n[2]:n[3],f=l?n[1]:n[2],h=l?n[3]:n[1],g=l?d%4===0&&h%4===0:u%4===0&&h%4===0,$=l?h:u*f,E=l?u*f:h,y=g?[8,8,1]:[$<=4||E<=4?4:16,$>4&&E<=4?4:16,1],_=g?[4,4,1]:[$<=4?1:4,$>4&&E<=4?1:4,1],v=[Math.ceil($/y[0]/_[0]),Math.ceil(E/y[1]/_[1]),Math.ceil(c/y[2]/_[2])];$t("verbose",()=>`[conv_backprop_mm_webgpu] dispatch = ${v}`);let b=g?4:1,C=Math.max(y[0]*b,y[1]),I=g?4:1,O=[{type:"int32",data:r},{type:"int32",data:i},{type:"int32",data:a}],M=te("x",e[0].dataType,e[0].dims.length,I),W=te("w",e[1].dataType,e[1].dims.length,1),G=ke("result",e[0].dataType,n.length,I),z=[M,W];O.push(...le(e[0].dims)),O.push(...le(e[1].dims));let K="";if(s){let ae=te("bias",e[2].dataType,e[2].dims.length,I);z.push(ae),O.push(...le(e[2].dims)),K+=` fn getBiasByOutputCoords(coords : vec4) -> ${g?"vec4":"f32"} { return bias[coords.${l?"w":"y"}${g?"/ 4":""}]; }`}return O.push(...le(n)),{name:"Conv2DTransposeMatMul",shaderCache:{hint:t.cacheKey},getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:v[0],y:v[1],z:v[2]},programUniforms:O}),getShaderSource:ae=>` ${vf("uniforms.result_strides")} ${ae.registerUniform("dimAOuter","i32").registerUniform("dimBOuter","i32").registerUniform("dimInner","i32").declareVariables(...z,G)}; const outBackprop : vec4 = vec4(${e[0].dims.join(",")}); const filterDims : vec2 = vec2(${t.kernelShape[l?1:2]}, ${t.kernelShape[l?2:3]}); const effectiveFilterDims : vec2 = filterDims + vec2( ${t.dilations[0]<=1?0:(t.kernelShape[l?1:2]-1)*(t.dilations[0]-1)}, ${t.dilations[1]<=1?0:(t.kernelShape[l?2:3]-1)*(t.dilations[1]-1)}); const pads : vec2 = vec2(i32(effectiveFilterDims[0]) - 1 - (${t.pads[0]+t.pads[2]})/2, i32(effectiveFilterDims[1]) - 1 - (${t.pads[1]+t.pads[3]})/2); const strides : vec2 = vec2(${t.strides[0]}, ${t.strides[1]}); const dilation : vec2 = vec2(${t.dilations[0]}, ${t.dilations[1]}); const dimAOuter : i32 = ${r}; const dimBOuter : i32 = ${i}; const dimInner : i32 = ${a}; ${K} ${Bg(l,s,t,b)} ${g?Jl(_,y,"f32",void 0,!l,C):eu(_,y,"f32",void 0,!l,C,!1,void 0,o)}`}}}),Dg,Qc,gE=ee(()=>{bi(),ze(),Oe(),Dg=(e,t,n,r,i,a,s=!1,o)=>{let l=n.format==="NHWC",d=l?1:2,c=l?2:3,u=l?3:1,f=ne.size(r),h=s?2:1,g=n.group,$=t[1].dims,E=$[0]/g,y=$[1],_=` fn setOutputAtIndex(flatIndex : u32, value : ${s?`vec4<${o}>`:o}) { result[flatIndex] = ${s?`vec4<${o}>`:o}(value); }`;i&&(_+=` fn getBiasByOutputCoords(coords : vec4) -> ${s?`vec4<${o}>`:o} { return bias[coords.${l?"w":"y"}${s?"/ 4":""}]; }`);let v=s?4:1,b=te("W",t[1].dataType,t[1].dims,v),C=te("Dy",t[0].dataType,t[0].dims,v),I=[C,b];i&&I.push(te("bias",t[2].dataType,[r[u]],v));let O=ke("result",t[0].dataType,r,v),M=`{ let batch: u32 = ${a?"global_id.z":"workgroup_id.z"} / outShape[1]; let r = ${a?"global_id.z":"workgroup_id.z"} % outShape[1]; let c = ${a?"global_id.y":"workgroup_id.y"} * ${h}; let d1: u32 = ${a?"global_id.x":"workgroup_id.x"} * 4; let dyCorner = vec2(i32(r), i32(c)) - vec2(pads); // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1). // ? = to be determined. : = across all values in that axis. var dotProd: array, ${h}>; for (var i = 0; i < ${h}; i++) { dotProd[i] = vec4<${o}>(0.0); } for (var wR: u32 = 0; wR < filterDims[0]; wR = wR + 1) { var dyR = (${o}(dyCorner.x) + ${o}(wR)) / ${o}(strides.x); let wRPerm = filterDims[0] - 1 - wR; if (dyR < 0.0 || dyR >= ${o}(outBackprop[1]) || fract(dyR) > 0.0 || wRPerm < 0) { continue; } let idyR: u32 = u32(dyR); for (var wC: u32 = 0; wC < filterDims[1]; wC = wC + 1) { let dyC = (${o}(dyCorner.y) + ${o}(wC)) / ${o}(strides.y); let dyC2 = (${o}(dyCorner.y) + 1.0 + ${o}(wC)) / ${o}(strides.y); let wCPerm = filterDims[1] - 1 - wC; if (wCPerm < 0) { continue; } var bDyCVal = true; var bDyCVal2 = true; if (dyC < 0.0 || dyC >= ${o}(outBackprop[2]) || fract(dyC) > 0.0) { bDyCVal = false; } if (dyC2 < 0.0 || dyC2 >= ${o}(outBackprop[2]) || fract(dyC2) > 0.0) { bDyCVal2 = false; } let idyC: u32 = u32(dyC); let idyC2: u32 = u32(dyC2); if (bDyCVal && bDyCVal2) { let d2Length = outBackprop[3]; for (var d2 :u32 = 0; d2 < d2Length; d2 = d2 + 4) { let wValue0 = ${b.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; let wValue1 = ${b.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; let wValue2 = ${b.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; let wValue3 = ${b.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; var xValue = ${C.get("batch","idyR","idyC","d2")}; let tmpval = vec4<${o}>(dot(xValue, wValue0), dot(xValue, wValue1), dot(xValue, wValue2), dot(xValue, wValue3)); dotProd[0] = dotProd[0] + tmpval; xValue = ${C.get("batch","idyR","idyC2","d2")}; dotProd[1] = dotProd[1] + vec4<${o}>(dot(xValue, wValue0), dot(xValue, wValue1), dot(xValue, wValue2), dot(xValue, wValue3)); } } else if (bDyCVal) { let d2Length = outBackprop[${u}]; for (var d2: u32 = 0; d2 < d2Length; d2 = d2 + 4) { let wValue0 = ${b.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; let wValue1 = ${b.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; let wValue2 = ${b.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; let wValue3 = ${b.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; var xValue = ${C.get("batch","idyR","idyC","d2")}; let tmpval = vec4<${o}>(dot(xValue, wValue0), dot(xValue, wValue1), dot(xValue, wValue2), dot(xValue, wValue3)); dotProd[0] = dotProd[0] + tmpval; } } else if (bDyCVal2) { let d2Length = outBackprop[3]; for (var d2: u32 = 0; d2 < d2Length; d2 = d2 + 4) { let wValue0 = ${b.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; let wValue1 = ${b.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; let wValue2 = ${b.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; let wValue3 = ${b.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; var xValue = ${C.get("batch","idyR","idyC2","d2")}; let tmpval = vec4<${o}>(dot(xValue, wValue0), dot(xValue, wValue1), dot(xValue, wValue2), dot(xValue, wValue3)); dotProd[1] = dotProd[1] + tmpval; } } } } for (var i: u32 = 0; i < ${h}; i = i + 1) { let value = dotProd[i] + ${i?"bias[c+i]":`vec4<${o}>(0.0)`}; ${O.set("batch","r","c + i","d1","value")}; } }`,W=` let outputIndices = ${O.offsetToIndices("global_idx")}; let batch = ${O.indicesGet("outputIndices",0)}; let d1 = ${O.indicesGet("outputIndices",u)}; let r = ${O.indicesGet("outputIndices",d)}; let c = ${O.indicesGet("outputIndices",c)}; let dyCorner = vec2(i32(r), i32(c)) - pads; let dyRCorner = dyCorner.x; let dyCCorner = dyCorner.y; let groupId = d1 / ${y}; let wOutChannel = d1 - groupId * ${y}; // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1). // ? = to be determined. : = across all values in that axis. var dotProd = ${o}(0.0); for (var wR: u32 = 0; wR < effectiveFilterDims.x; wR = wR + 1) { if (wR % dilations.x != 0) { continue; } let dyR = (${o}(dyRCorner) + ${o}(wR)) / ${o}(strides[0]); let wRPerm = filterDims.x - 1 - wR / dilations.x; if (dyR < 0.0 || dyR >= ${o}(outBackprop[${d}]) || fract(dyR) > 0.0 || wRPerm < 0) { continue; } let idyR: u32 = u32(dyR); for (var wC: u32 = 0; wC < effectiveFilterDims.y; wC = wC + 1) { if (wC % dilations.y != 0) { continue; } let dyC = (${o}(dyCCorner) + ${o}(wC)) / ${o}(strides.y); let wCPerm = filterDims.y - 1 - wC / dilations.y; if (dyC < 0.0 || dyC >= ${o}(outBackprop[${c}]) || fract(dyC) > 0.0 || wCPerm < 0) { continue; } let idyC: u32 = u32(dyC); var inputChannel = groupId * ${E}; for (var d2: u32 = 0; d2 < ${E}; d2 = d2 + 1) { let xValue = ${l?C.get("batch","idyR","idyC","inputChannel"):C.get("batch","inputChannel","idyR","idyC")}; let wValue = ${b.get("inputChannel","wOutChannel","u32(wRPerm)","u32(wCPerm)")}; dotProd = dotProd + xValue * wValue; inputChannel = inputChannel + 1; } } } let value = dotProd + ${i?"bias[d1]":`${o}(0.0)`}; ${O.setByOffset("global_idx","value")}; `;return` ${e.declareVariables(...I,O)} ${_} const outShape : vec4 = vec4(${r.join(",")}); const outBackprop : vec4 = vec4(${t[0].dims.join(",")}); const strides : vec2 = vec2(${n.strides[0]}, ${n.strides[1]}); const filterDims : vec2 = vec2(${n.kernelShape[l?1:2]}, ${n.kernelShape[l?2:3]}); const dilations : vec2 = vec2(${n.dilations[0]}, ${n.dilations[1]}); const effectiveFilterDims : vec2 = filterDims + vec2( ${n.dilations[0]<=1?0:(n.kernelShape[l?1:2]-1)*(n.dilations[0]-1)}, ${n.dilations[1]<=1?0:(n.kernelShape[l?2:3]-1)*(n.dilations[1]-1)}); const pads : vec2 = vec2(i32(effectiveFilterDims[0]) - 1 - (${n.pads[0]+n.pads[2]})/2, i32(effectiveFilterDims[1]) - 1 - (${n.pads[1]+n.pads[3]})/2); ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes(f)}; ${s?M:W}}`},Qc=(e,t,n)=>{let r=e.length>2,i=t.outputShape,a=ne.size(i),s=[Math.ceil(a/64),1,1];$t("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${s}`);let o=wn(e[0].dataType);return{name:"ConvTranspose2D",shaderCache:{hint:t.cacheKey},getRunData:()=>({dispatchGroup:{x:s[0],y:s[1],z:s[2]},outputs:[{dims:n?n(i):i,dataType:e[0].dataType}]}),getShaderSource:l=>Dg(l,e,t,i,r,s[1]===1&&s[2]===1,!1,o)}}}),Ng,Lg,Fg,Sd,n2,Ug,Wg,Vg,jg,r2,yE=ee(()=>{St(),mE(),gE(),xi(),qs(),Ng=(e,t,n,r,i,a)=>(e-1)*t+n+(r-1)*i+1-a,Lg=(e,t,n,r,i)=>{let a=Math.floor(e/2);t==="SAME_UPPER"?(n[r]=a,n[i]=e-a):t==="SAME_LOWER"&&(n[r]=e-a,n[i]=a)},Fg=(e,t,n,r,i,a,s,o,l,d)=>{let c=e.length-2,u=d.length===0;if(l.length===0)for(let g=0;g{let n=e.kernelShape.slice();if(e.kernelShape.length===0||e.kernelShape.reduce((f,h)=>f*h,1)===0){n.length=0;for(let f=2;ff+h,0)===0){let f=t[0].dims.length-2;l=new Array(f).fill(1)}let d=e.strides.slice();if(d.reduce((f,h)=>f+h,0)===0){let f=t[0].dims.length-2;d=new Array(f).fill(1)}Fg(o,n,l,e.autoPad,e.group,i,d,r,s,a);let c=Object.assign({},e),u=e.cacheKey+[n.join("n,"),i.join(","),d.join(","),s.join(","),a.join(","),l.join(",")].join("_");return Object.assign(c,{kernelShape:n,pads:i,outputPadding:s,outputShape:a,dilations:l,strides:d,cacheKey:u}),c},n2=e=>{let t=yf(e),n=e.format,r=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof e.autoPad>"u"?0:e.autoPad],i=e.dilations,a=e.group,s=e.kernelShape,o=e.pads,l=e.strides,d=e.wIsConst(),c=e.outputPadding,u=e.outputShape;return tt({autoPad:r,format:n,dilations:i,group:a,kernelShape:s,outputPadding:c,outputShape:u,pads:o,strides:l,wIsConst:d,...t})},Ug=(e,t)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length!==4&&e[0].dims.length!==3)throw new Error("currently only support 2-dimensional conv");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");let n=e[0].dims[t.format==="NHWC"?e[0].dims.length-1:1],r=e[1].dims[0];if(n!==r)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");let i=e[1].dims[1]*t.group;if(e.length===3&&(e[2].dims.length!==1||e[2].dims[0]!==i))throw new Error("invalid bias");let a=e[0].dims.length-2;if(t.dilations.reduce((s,o)=>s+o,0)>0&&t.dilations.length!==a)throw new Error(`dilations should be ${a}D`);if(t.strides.reduce((s,o)=>s+o,0)>0&&t.strides.length!==a)throw new Error(`strides should be ${a}D`);if(t.pads.reduce((s,o)=>s+o,0)>0&&t.pads.length!==a*2)throw new Error(`pads should be ${a*2}D`);if(t.outputPadding.length!==a&&t.outputPadding.length!==0)throw new Error(`output_padding should be ${a}D`);if(t.kernelShape.reduce((s,o)=>s+o,0)>0&&t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape");if(t.outputShape.length!==0&&t.outputShape.length!==e[0].dims.length-2)throw new Error("invalid output shape")},Wg=[2,3,1,0],Vg=(e,t,n)=>{let r=Sd(n,t),i=n.format==="NHWC",a=r.outputShape,s=a[i?3:1],o=t[0].dims[i?3:1];if(r.group!==1||s===1&&o===1){e.compute(Qc(t,r));return}let l=a[i?1:2],d=a[i?2:3],c=t[1].dims[2],u=t[1].dims[3],f=i?l*d:s,h=i?s:l*d,g=c*u*o,$=!0,E=e.kernelCustomData.wT??e.compute(Gr(t[1],Wg),{inputs:[1],outputs:[n.wIsConst?-2:-1]})[0];n.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=E);let y=[t[0],E],_=t.length===3;_&&(!i&&t[2].dims.length===1?y.push(t[2].reshape([t[2].dims[0],1,1])):y.push(t[2])),e.compute(t2(y,r,a,f,h,g,_,$),{inputs:y})},jg=(e,t)=>{let n=t.format==="NHWC",r=[e.inputs[0].reshape(n?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];r.length===3&&r.push(e.inputs[2]);let i=t.kernelShape;(i.length===0||i[0]===0)&&(i=[e.inputs[1].dims[2]]);let a=t.dilations;(a.length===0||a[0]===0)&&(a=[1]);let s=t.strides;(s.length===0||s[0]===0)&&(s=[1]);let o=t.pads;o.length===0&&(o=[0,0]),o=[0,o[0],0,o[1]],s=[1].concat(s),a=[1].concat(a),i=[1].concat(i);let l=Sd({...t,pads:o,strides:s,dilations:a,kernelShape:i},r);e.compute(Qc(r,l,d=>n?[d[0],d[2],d[3]]:[d[0],d[1],d[3]]))},r2=(e,t)=>{Ug(e.inputs,t),e.inputs[0].dims.length===3?jg(e,t):Vg(e,e.inputs,t)}}),Gg,i2,a2,wE=ee(()=>{lt(),ze(),St(),Oe(),Gg=(e,t,n,r)=>{let i=ne.size(t),a=t.length,s=te("input",e,a),o=ke("output",e,a),l=n.dataType===6?n.getInt32Array()[0]:Number(n.getBigInt64Array()[0]),d=ne.normalizeAxis(l,a),c=u=>{let f=` i32(${s.indicesGet("inputIndices","uniforms.axis")}) `,h=Ce("uniforms.input_shape","uniforms.axis",a),g=r.reverse?f+(r.exclusive?" + 1":""):"0",$=r.reverse?h:f+(r.exclusive?"":" + 1");return` ${u.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(s,o)} ${u.mainStart()} ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var inputIndices = ${o.offsetToIndices("global_idx")}; var sum = ${o.type.value}(0); let first : i32 = ${g}; let last : i32 = ${$}; for (var i : i32 = first; i < last; i++) { ${s.indicesSet("inputIndices","uniforms.axis","u32(i)")}; sum = sum + ${s.getByIndices("inputIndices")}; } ${o.setByOffset("global_idx","sum")}; }`};return{name:"CumSum",shaderCache:{hint:r.cacheKey,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:t,dataType:e}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:[{type:"uint32",data:i},{type:"int32",data:d},...le(t),...le(t)]}),getShaderSource:c}},i2=(e,t)=>{let n=e.inputs[0].dims,r=e.inputs[0].dataType,i=e.inputs[1];e.compute(Gg(r,n,i,t),{inputs:[0]})},a2=e=>{let t=e.exclusive===1,n=e.reverse===1;return tt({exclusive:t,reverse:n})}}),Yo,Ka,Ed,Hg,qg,Kg,Yg,kd,Qg,s2,o2,_E=ee(()=>{ze(),St(),Oe(),Yo="[a-zA-Z]|\\.\\.\\.",Ka="("+Yo+")+",Ed="^"+Ka+"$",Hg="("+Ka+",)*"+Ka,qg="^"+Hg+"$",Kg=class{constructor(e=-1){this.symbolToIndices=new Map,this.inputIndex=e}addSymbol(e,t){let n=this.symbolToIndices.get(e);n===void 0?n=[t]:n.push(t),this.symbolToIndices.set(e,n)}},Yg=class{constructor(e,t){var i;this.equation=t,this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=new Array,this.outputDims=[];let[n,r]=t.includes("->")?t.split("->",2):[t,""];if(!n.match(RegExp(qg)))throw new Error("Invalid LHS term");if(n.split(",").forEach((a,s)=>{let o=e[s].dims.slice();if(!a.match(RegExp(Ed)))throw new Error("Invalid LHS term");let l=this.processTerm(a,!0,o,s);this.lhs.push(l)}),r==="")r+=[...this.symbolToInfo.entries()].filter(([a,s])=>s.count===1||a==="...").map(([a])=>a).join("");else if(!r.match(RegExp(Ka)))throw new Error("Invalid RHS");(i=r.match(RegExp(Yo,"g")))==null||i.forEach(a=>{if(a==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let s=this.symbolToInfo.get(a);if(s===void 0)throw new Error("Invalid RHS symbol");this.outputDims.push(s.dimValue)}}),this.rhs=this.processTerm(r,!1,this.outputDims)}addSymbol(e,t,n){let r=this.symbolToInfo.get(e);if(r!==void 0){if(r.dimValue!==t&&r.count!==1)throw new Error("Dimension mismatch");r.count++,r.inputIndices.push(n)}else r={count:1,dimValue:t,inputIndices:[n]};this.symbolToInfo.set(e,r)}processTerm(e,t,n,r=-1){let i=n.length,a=!1,s=[],o=0;if(!e.match(RegExp(Ed))&&!t&&e!=="")throw new Error("Invalid LHS term");let l=e.match(RegExp(Yo,"g")),d=new Kg(r);return l==null||l.forEach((c,u)=>{if(c==="..."){if(a)throw new Error("Only one ellipsis is allowed per input term");a=!0;let f=i-l.length+1;if(f<0)throw new Error("Ellipsis out of bounds");if(s=n.slice(o,o+f),this.hasEllipsis){if(this.ellipsisDims.length!==s.length||this.ellipsisDims.toString()!==s.toString())throw new Error("Ellipsis dimensions mismatch")}else if(t)this.hasEllipsis=!0,this.ellipsisDims=s;else throw new Error("Ellipsis must be specified in the LHS");for(let h=0;he+"_max",Qg=(e,t,n,r,i)=>{let a=t.map((f,h)=>e[h]?f.length:f).map((f,h)=>te(`input${h}`,n,f)),s=ne.size(i),o=xt(i.length),l=o?i.length:i,d=ke("output",n,l),c=[...r.symbolToInfo.keys()].filter(f=>!r.rhs.symbolToIndices.has(f)),u=f=>{let h=[],g="var prod = 1.0;",$="var sum = 0.0;",E="sum += prod;",y=[],_=[],v=[],b=[],C=r.symbolToInfo.size===r.rhs.symbolToIndices.size;r.symbolToInfo.forEach((O,M)=>{var W;if(r.rhs.symbolToIndices.has(M)){let G=(W=r.rhs.symbolToIndices.get(M))==null?void 0:W[0];G!==void 0&&r.lhs.forEach((z,K)=>{if(O.inputIndices.includes(K)){let ae=z.symbolToIndices.get(M);if(ae===void 0)throw new Error("Invalid symbol error");ae.forEach(ue=>{h.push(`${a[K].indicesSet(`input${K}Indices`,ue,d.indicesGet("outputIndices",G))}`)})}})}else r.lhs.forEach((G,z)=>{if(O.inputIndices.includes(z)){let K=G.symbolToIndices.get(M);if(K===void 0)throw new Error("Invalid symbol error");K.forEach(ae=>{y.push(`${a[z].indicesSet(`input${z}Indices`,ae,`${M}`)}`)}),b.push(`prod *= ${a[z].getByIndices(`input${z}Indices`)};`)}}),_.push(`for(var ${M}: u32 = 0; ${M} < uniforms.${kd(M)}; ${M}++) {`),v.push("}")});let I=C?[...h,`let sum = ${a.map((O,M)=>O.getByIndices(`input${M}Indices`)).join(" * ")};`]:[...h,$,..._,...y,g,...b,E,...v];return` ${f.registerUniforms(c.map(O=>({name:`${kd(O)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...a,d)} ${f.mainStart()} ${f.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var outputIndices = ${d.offsetToIndices("global_idx")}; ${a.map((O,M)=>`var input${M}Indices: ${a[M].type.indices};`).join(` `)} ${I.join(` `)}; ${d.setByOffset("global_idx","sum")}; }`};return{name:"Einsum",shaderCache:{hint:r.equation,inputDependencies:e.map(f=>f?"rank":"dims")},getRunData:()=>{let f=c.filter(g=>r.symbolToInfo.has(g)).map(g=>{var $;return{type:"uint32",data:(($=r.symbolToInfo.get(g))==null?void 0:$.dimValue)||0}});f.push({type:"uint32",data:s});let h=t.filter((g,$)=>e[$]).map((g,$)=>[...le(g)]).reduce((g,$)=>g.concat($),f);return o&&h.push(...le(i)),{outputs:[{dims:i,dataType:n}],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:h}},getShaderSource:u}},s2=(e,t)=>{let n=new Yg(e.inputs,t.equation),r=e.inputs.map((s,o)=>xt(s.dims.length)),i=n.outputDims,a=e.inputs.map((s,o)=>s.dims);e.compute(Qg(r,a,e.inputs[0].dataType,n,i))},o2=e=>{let t=e.equation.replace(/\s+/g,"");return tt({equation:t})}}),Xg,Cd,Zg,Jg,l2,vE=ee(()=>{lt(),ze(),Oe(),Xg=e=>{if(!e||e.length!==2)throw new Error("Expand requires 2 input.");let t=e[0].dims,n=Array.from(e[1].getBigInt64Array(),Number),r=n.length{let n=e.length-t.length,r=[];for(let i=0;ie.length>t.length?Cd(e,t):Cd(t,e),Jg=e=>{let t=e[0].dims,n=Array.from(e[1].getBigInt64Array(),Number),r=Zg(t,n),i=e[0].dataType,a=i===9?4:1,s=Math.ceil(ne.size(r)/a),o=xt(t.length),l=xt(r.length),d=u=>{let f=o?t.length:t,h=l?r.length:r,g=te("input",i,f,a),$=ke("output",i,h,a),E;if(i===9){let y=(_,v,b="")=>` let outputIndices${v} = ${$.offsetToIndices(`outputOffset + ${v}u`)}; let offset${v} = ${g.broadcastedIndicesToOffset(`outputIndices${v}`,$)}; let index${v} = offset${v} / 4u; let component${v} = offset${v} % 4u; ${_}[${v}] = ${b}(${g.getByOffset(`index${v}`)}[component${v}]); `;E=` let outputOffset = global_idx * ${a}; var data = vec4(0); ${y("data",0,"u32")} ${y("data",1,"u32")} ${y("data",2,"u32")} ${y("data",3,"u32")} ${$.setByOffset("global_idx","data")} }`}else E=` let outputIndices = ${$.offsetToIndices("global_idx")}; let inputOffset = ${g.broadcastedIndicesToOffset("outputIndices",$)}; ${$.setByOffset("global_idx",g.getByOffset("inputOffset"))} }`;return` ${u.registerUniform("vec_size","u32").declareVariables(g,$)} ${u.mainStart()} ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${E}`},c=[{type:"uint32",data:s}];return o&&c.push(...le(t)),l&&c.push(...le(r)),{name:"Expand",shaderCache:{hint:`${r.length}`,inputDependencies:[o?"rank":"dims"]},getShaderSource:d,getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:c})}},l2=e=>{Xg(e.inputs),e.compute(Jg(e.inputs),{inputs:[0]})}}),e0,t0,u2,d2,$E=ee(()=>{lt(),ze(),St(),Oe(),e0=e=>{if(!e||e.length!==2)throw new Error("Gather requires 2 inputs.")},t0=(e,t)=>{let n=e[0].dims,r=e[1].dims,i=n.length,a=ne.normalizeAxis(t.axis,i),s=n.slice(0);s.splice(a,1,...r);let o=n[a],l=e[0].dataType===9?4:1,d=Math.ceil(ne.size(s)/l),c=xt(e[0].dims.length),u=c?e[0].dims.length:e[0].dims,f=xt(e[1].dims.length),h=f?e[1].dims.length:e[1].dims,g=xt(s.length),$=g?s.length:s,E=[{type:"uint32",data:d},{type:"int32",data:o},{type:"uint32",data:a}];c&&E.push(...le(e[0].dims)),f&&E.push(...le(e[1].dims)),g&&E.push(...le(s));let y=[];y.push(c?"rank":"dims"),y.push(f?"rank":"dims");let _=v=>{let b=te("data",e[0].dataType,u,l),C=te("inputIndices",e[1].dataType,h),I=ke("output",e[0].dataType,$,l),O=W=>{let G=r.length,z=`var indicesIndices${W} = ${C.type.indices}(0);`;for(let K=0;K1?`indicesIndices${W}[${K}]`:`indicesIndices${W}`} = ${s.length>1?`outputIndices${W}[uniforms.axis + ${K}]`:`outputIndices${W}`};`;z+=` var idx${W} = ${C.getByIndices(`indicesIndices${W}`)}; if (idx${W} < 0) { idx${W} = idx${W} + uniforms.axisDimLimit; } var dataIndices${W} = ${b.type.indices}(0); `;for(let K=0,ae=0;K1?`dataIndices${W}[${K}]`:`dataIndices${W}`} = u32(idx${W});`,ae+=G):(z+=`${i>1?`dataIndices${W}[${K}]`:`dataIndices${W}`} = ${s.length>1?`outputIndices${W}[${ae}]`:`outputIndices${W}`};`,ae++);return z},M;if(e[0].dataType===9){let W=(G,z,K="")=>` let outputIndices${z} = ${I.offsetToIndices(`outputOffset + ${z}u`)}; ${O(z)}; let offset${z} = ${b.indicesToOffset(`dataIndices${z}`)}; let index${z} = offset${z} / 4u; let component${z} = offset${z} % 4u; ${G}[${z}] = ${K}(${b.getByOffset(`index${z}`)}[component${z}]); `;M=` let outputOffset = global_idx * ${l}; var value = vec4(0); ${W("value",0,"u32")} ${W("value",1,"u32")} ${W("value",2,"u32")} ${W("value",3,"u32")} ${I.setByOffset("global_idx","value")} `}else M=` let outputIndices = ${I.offsetToIndices("global_idx")}; ${O("")}; let value = ${b.getByIndices("dataIndices")}; ${I.setByOffset("global_idx","value")}; `;return` ${v.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(b,C,I)} ${v.mainStart()} ${v.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} ${M} }`};return{name:"Gather",shaderCache:{hint:t.cacheKey,inputDependencies:y},getRunData:()=>({outputs:[{dims:s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:E}),getShaderSource:_}},u2=e=>tt({axis:e.axis}),d2=(e,t)=>{let n=e.inputs;e0(n),e.compute(t0(e.inputs,t))}}),n0,r0,c2,p2,bE=ee(()=>{ze(),St(),Oe(),n0=e=>{if(!e||e.length!==2)throw new Error("GatherElements requires 2 inputs.");if(e[0].dims.length<1)throw new Error("GatherElements requires that the data input be rank >= 1.");if(e[0].dims.length!==e[1].dims.length)throw new Error(`GatherElements requires that the data input and indices input tensors be of same rank.`)},r0=(e,t)=>{let n=e[0].dims,r=e[0].dataType,i=n.length,a=e[1].dims,s=e[1].dataType,o=ne.normalizeAxis(t.axis,i),l=n[o],d=a.slice(0),c=ne.size(d),u=te("input",r,i),f=te("indicesInput",s,a.length),h=ke("output",r,d.length),g=[{type:"uint32",data:c},{type:"int32",data:l},{type:"uint32",data:o}];return g.push(...le(n)),g.push(...le(a)),g.push(...le(d)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:d,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:g}),getShaderSource:$=>` ${$.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(u,f,h)} ${$.mainStart()} ${$.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let outputIndices = ${h.offsetToIndices("global_idx")}; var idx = ${f.getByOffset("global_idx")}; if (idx < 0) { idx = idx + uniforms.axisDimLimit; } var inputIndices = ${u.type.indices}(outputIndices); ${u.indicesSet("inputIndices","uniforms.axis","u32(idx)")}; let value = ${u.getByIndices("inputIndices")}; ${h.setByOffset("global_idx","value")}; }`}},c2=e=>tt({axis:e.axis}),p2=(e,t)=>{let n=e.inputs;n0(n),e.compute(r0(e.inputs,t))}}),i0,a0,f2,h2,xE=ee(()=>{ze(),Oe(),i0=e=>{if(!e)throw new Error("Input is missing");if(e.length<2||e.length>3)throw new Error("Invaid input number.");if(e.length===3&&e[2].dims.length>2)throw new Error("Invalid input shape of C");if(e[0].dataType!==e[1].dataType||e.length===3&&e[0].dataType!==e[2].dataType)throw new Error("Input types are mismatched")},a0=(e,t)=>{let n=e[0].dims.slice(),r=e[1].dims.slice(),[i,a,s]=Iv.getShapeOfGemmResult(n,t.transA,r,t.transB,e.length===3?e[2].dims:void 0),o=[i,a];if(!o)throw new Error("Can't use gemm on the given tensors");let l=ne.size(o),d=[{type:"uint32",data:l},{type:"uint32",data:i},{type:"uint32",data:a},{type:"uint32",data:s},{type:"float32",data:t.alpha},{type:"float32",data:t.beta}],c=["type","type"];e.length===3&&(d.push(...le(e[2].dims)),c.push("rank")),d.push(...le(o));let u=f=>{let h="";t.transA&&t.transB?h="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":t.transA&&!t.transB?h="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!t.transA&&t.transB?h="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!t.transA&&!t.transB&&(h="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let g=t.alpha===1?"":"value *= uniforms.alpha;",$=te("a",e[0].dataType,e[0].dims),E=te("b",e[1].dataType,e[1].dims),y=$.type.value,_=null,v=[$,E];e.length===3&&(_=te("c",e[2].dataType,e[2].dims.length),v.push(_));let b=ke("output",e[0].dataType,o.length);v.push(b);let C=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"},{name:"alpha",type:"f32"},{name:"beta",type:"f32"}];return` ${f.registerUniforms(C).declareVariables(...v)} ${f.mainStart()} ${f.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let m = global_idx / uniforms.N; let n = global_idx % uniforms.N; var value = ${y}(0); for (var k: u32 = 0u; k < uniforms.K; k++) { ${h} } ${g} ${_!=null?`let cOffset = ${_.broadcastedIndicesToOffset("vec2(m, n)",b)}; value += ${y}(uniforms.beta) * ${_.getByOffset("cOffset")};`:""} output[global_idx] = value; }`};return{name:"Gemm",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:c},getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:d}),getShaderSource:u}},f2=e=>{let t=e.transA,n=e.transB,r=e.alpha,i=e.beta;return{transA:t,transB:n,alpha:r,beta:i,cacheKey:`${e.transA};${e.transB};${e.alpha===1}`}},h2=(e,t)=>{i0(e.inputs),e.compute(a0(e.inputs,t))}}),s0,o0,l0,m2,SE=ee(()=>{lt(),ze(),Oe(),s0=(e,t)=>{let n=e[0].dims,r=n,i=2,a=ne.sizeToDimension(n,i),s=ne.sizeFromDimension(n,i),o=rn(s),l=s/o,d=[n[0],n[1],l],c=["rank","type","type"],u=[{type:"uint32",data:s},{type:"uint32",data:l}];u.push(...le(d),...le(d));let f=h=>{let g=te("x",e[0].dataType,d.length,o),$=te("scale",e[1].dataType,e[1].dims),E=te("bias",e[2].dataType,e[2].dims),y=ke("output",e[0].dataType,d.length,o),_=[g,$,E,y],v=g.type.value,b=o===1?"f32":`vec${o}`,C=64,I=[{name:"normSize",type:"u32"},{name:"normPackedSize",type:"u32"}];return` var meanShared : f32; var squaredNormShared : f32; var workgroupShared : array<${b}, ${C}>; const workgroupSize = ${C}u; ${h.registerUniforms(I).declareVariables(..._)} ${h.mainStart(C)} let norm = global_idx / workgroupSize; let batch = norm / uniforms.x_shape[1]; let channel = norm % uniforms.x_shape[1]; let localIndex = local_id.x; // initialize workgroup memory var initial = ${b}(0); for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) { initial = initial + ${b}(${g.get("batch","channel","h")}); } workgroupShared[localIndex] = initial; workgroupBarrier(); // Calculate the mean of current channel data. for (var currSize = workgroupSize >> 1; currSize > 0; currSize = currSize >> 1) { if (localIndex < currSize) { workgroupShared[localIndex] = workgroupShared[localIndex] + workgroupShared[localIndex + currSize]; } workgroupBarrier(); } if (localIndex == 0) { meanShared = ${Zn("workgroupShared[0]",o)} / f32(uniforms.normSize); } workgroupBarrier(); // reinitialize workgroup memory. initial = ${b}(0); for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) { let deviation = ${b}(${g.get("batch","channel","h")}) - ${b}(meanShared); initial = initial + deviation * deviation; } workgroupShared[localIndex] = initial; workgroupBarrier(); // Calculate the sum of square of deviation of current channel data. for (var currSize = workgroupSize >> 1; currSize > 0; currSize = currSize >> 1) { if (localIndex < currSize) { workgroupShared[localIndex] = workgroupShared[localIndex] + workgroupShared[localIndex + currSize]; } workgroupBarrier(); } if (localIndex == 0) { squaredNormShared = ${Zn("workgroupShared[0]",o)}; } workgroupBarrier(); let invStdDev = inverseSqrt(squaredNormShared / f32(uniforms.normSize) + f32(${t.epsilon})); let channelScale = invStdDev * f32(${$.getByOffset("channel")}); let channelShift = f32(${E.getByOffset("channel")}) - meanShared * channelScale; for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) { let value = ${g.get("batch","channel","h")} * ${v}(${b}(channelScale)) + ${v}(${b}(channelShift)); ${y.set("batch","channel","h","value")}; } }`};return{name:"InstanceNormalization",shaderCache:{hint:`${t.epsilon};${o}`,inputDependencies:c},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:a},programUniforms:u}),getShaderSource:f}},o0=(e,t,n,r,i,a,s,o)=>{let l=rn(s),d=64,c=l===1?"vec2f":`mat2x${l}f`,u=l===1?"f32":`vec${l}f`,f=(I,O)=>`${c}(${I}, ${O})`,h=i*s/l,g=Math.ceil(a/d),$=["type"],E=[{type:"uint32",data:g},{type:"uint32",data:a},{type:"uint32",data:Math.floor(s/l)},{type:"uint32",data:Math.floor(a*s/l)}],y=I=>{let O=te("input",t.dataType,t.dims,l);return` ${I.declareVariables(O)} @group(0) @binding(1) var output : array<${c}>; struct Uniforms {wg_size:u32, H:u32, C:u32, image_size:u32}; @group(0) @binding(2) var uniforms: Uniforms; ${I.mainStart(d)} let currentImageNumber = global_idx / ${d} / uniforms.C; let currentChannelNumber = (global_idx / ${d}) % uniforms.C; let wgId = global_idx % ${d}; let wgOffset = wgId * uniforms.wg_size; if (wgOffset >= uniforms.H) { return; } let wgMax = min(wgOffset + uniforms.wg_size, uniforms.H); let offset = currentImageNumber * uniforms.image_size + currentChannelNumber; var sum = ${tn("f32",l)}; var squaredSum = ${tn("f32",l)}; for (var i: u32 = wgOffset; i < wgMax; i++) { let value = ${u}(input[offset + i * uniforms.C]); sum += value; squaredSum += value * value; } output[global_idx] = ${f("sum","squaredSum")}; }`},_=e.compute({name:"InstanceNormComputeMean",shaderCache:{hint:`${l}`,inputDependencies:$},getRunData:()=>({outputs:[{dims:[i,s,d,2],dataType:1}],dispatchGroup:{x:i*s/l},programUniforms:E}),getShaderSource:y},{inputs:[t],outputs:[-1]})[0],v=[{type:"uint32",data:h},{type:"uint32",data:a},{type:"uint32",data:Math.floor(s/l)},{type:"uint32",data:Math.floor(d*s/l)}],b=["type","type","type"],C=I=>{let O=te("scale",n.dataType,n.dims,l),M=te("bias",r.dataType,r.dims,l);return` @group(0) @binding(0) var input : array<${c}>; @group(0) @binding(1) var scale : array<${O.type.storage}>; @group(0) @binding(2) var bias : array<${M.type.storage}>; @group(0) @binding(3) var output : array<${c}>; struct Uniforms {units_of_work : u32, H: u32, C : u32, image_size : u32}; @group(0) @binding(4) var uniforms: Uniforms; ${I.mainStart()} ${I.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.units_of_work")} let currentImageNumber = global_idx / uniforms.C; let currentChannelNumber = global_idx % uniforms.C; let offset = currentImageNumber * uniforms.image_size; var sum = ${tn("f32",l)}; var squaredSum = ${tn("f32",l)}; for (var i: u32 = 0; i < ${d}; i++) { let value = input[offset + i + currentChannelNumber * ${d}]; sum += value[0]; squaredSum += value[1]; } sum = sum / f32(uniforms.H); squaredSum = squaredSum / f32(uniforms.H); let invStdDev = inverseSqrt(squaredSum - sum * sum + f32(${o})); let channelScale = invStdDev * ${u}(scale[currentChannelNumber]); let channelShift = ${u}(bias[currentChannelNumber]) - sum * channelScale; output[global_idx] = ${f("channelScale","channelShift")}; }`};return e.compute({name:"InstanceNormComputeChannelScaleShift",shaderCache:{hint:`${l};${o}`,inputDependencies:b},getRunData:()=>({outputs:[{dims:[i,s,2],dataType:1}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:v}),getShaderSource:C},{inputs:[_,n,r],outputs:[-1]})[0]},l0=(e,t,n)=>{let r=t[0].dims,i=r,a=r[0],s=r[r.length-1],o=ne.sizeFromDimension(r,1)/s,l=rn(s),d=ne.size(i)/l,c=[{type:"uint32",data:o},{type:"uint32",data:Math.floor(s/l)}],u=["type","type"],f=o0(e,t[0],t[1],t[2],a,o,s,n.epsilon),h=g=>{let $=wn(t[0].dataType),E=l===1?"vec2f":`mat2x${l}f`,y=l===1?$:`vec${l}<${$}>`,_=te("input",t[0].dataType,t[0].dims,l),v=ke("output",t[0].dataType,i,l);return` @group(0) @binding(0) var input : array<${_.type.storage}>; @group(0) @binding(1) var scaleInput : array<${E}>; @group(0) @binding(2) var output : array<${v.type.storage}>; struct Uniforms {H: u32, C : u32}; @group(0) @binding(3) var uniforms: Uniforms; ${g.mainStart()} let currentImageNumber = global_idx / (uniforms.C * uniforms.H); let currentChannelNumber = global_idx % uniforms.C; let scaleOffset = currentImageNumber * uniforms.C + currentChannelNumber; let scale = scaleInput[scaleOffset]; output[global_idx] = fma(input[global_idx], ${y}(scale[0]), ${y}(scale[1])); }`};e.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${l}`,inputDependencies:u},getRunData:()=>({outputs:[{dims:i,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:c}),getShaderSource:h},{inputs:[t[0],f]})},m2=(e,t)=>{t.format==="NHWC"?l0(e,e.inputs,t):e.compute(s0(e.inputs,t))}}),u0,d0,g2,EE=ee(()=>{lt(),ze(),Oe(),u0=e=>{if(!e||e.length<2)throw new Error("layerNorm requires at least 2 inputs.")},d0=(e,t,n)=>{let r=e[0].dims,i=e[1],a=e[2],s=r,o=ne.normalizeAxis(t.axis,r.length),l=ne.sizeToDimension(r,o),d=ne.sizeFromDimension(r,o),c=ne.size(i.dims),u=a?ne.size(a.dims):0;if(c!==d||a&&u!==d)throw new Error(`Size of X.shape()[axis:] == ${d}. Size of scale and bias (if provided) must match this. Got scale size of ${c} and bias size of ${u}`);let f=[];for(let b=0;b1,y=n>2,_=b=>{let C=wn(e[0].dataType),I=[te("x",e[0].dataType,e[0].dims,h),te("scale",i.dataType,i.dims,h)];a&&I.push(te("bias",a.dataType,a.dims,h)),I.push(ke("output",e[0].dataType,s,h)),E&&I.push(ke("mean_data_output",1,f)),y&&I.push(ke("inv_std_output",1,f));let O=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return` ${b.registerUniforms(O).declareVariables(...I)} ${b.mainStart()} ${b.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")} let offset = global_idx * uniforms.norm_size_vectorized; var meanVector = ${tn("f32",h)}; var meanSquareVector = ${tn("f32",h)}; for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) { let value = ${ur(C,h,"x[h + offset]")}; meanVector += value; meanSquareVector += value * value; } let mean = ${Zn("meanVector",h)} / uniforms.norm_size; let invStdDev = inverseSqrt(${Zn("meanSquareVector",h)} / uniforms.norm_size - mean * mean + uniforms.epsilon); for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) { let f32input = ${ur(C,h,"x[j + offset]")}; let f32scale = ${ur(C,h,"scale[j]")}; output[j + offset] = ${I[0].type.value}((f32input - mean) * invStdDev * f32scale ${a?`+ ${ur(C,h,"bias[j]")}`:""} ); } ${E?"mean_data_output[global_idx] = mean":""}; ${y?"inv_std_output[global_idx] = invStdDev":""}; }`},v=[{dims:s,dataType:e[0].dataType}];return E&&v.push({dims:f,dataType:1}),y&&v.push({dims:f,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${h};${n}`,inputDependencies:g},getRunData:()=>({outputs:v,dispatchGroup:{x:Math.ceil(l/64)},programUniforms:$}),getShaderSource:_}},g2=(e,t)=>{u0(e.inputs),e.compute(d0(e.inputs,t,e.outputCount))}}),c0,y2,Td,p0,Qo,w2,kE=ee(()=>{ze(),St(),pf(),n1(),Oe(),qs(),c0=(e,t)=>{let n=e[0],r=e[1],i=e[2],a=e[3],s=e[4],o=e[5],l=e[6],d=e[7];if(n.dims.length!==3&&n.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let c=!1,u=n.dims[0],f=n.dims[1],h=n.dims.length===3?c?n.dims[2]/3:n.dims[2]:t.numHeads*n.dims[4],g=f,$=0,E=0,y=Math.floor(h/t.numHeads);if(l&&d){if(l.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(d.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');$=l.dims[2],E=l.dims[2]}else if(l||d)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let _;if(r){if(n.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(r.dims.length<3||r.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(n.dims[0]!==r.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(r.dims.length===3){if(r.dims[2]!==n.dims[2])throw new Error('Input "query" and "key" shall have same dim 2 (hidden_size)');_=2,g=r.dims[1]}else if(r.dims.length===5){if(r.dims[2]!==t.numHeads||r.dims[3]!==2||r.dims[4]!==y)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(i)throw new Error('Expect "value" be none when "key" has packed kv format.');_=5,g=r.dims[1]}else{if(r.dims[1]!==t.numHeads||r.dims[3]!==y)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');_=0,g=r.dims[2]}}else{if(n.dims.length!==3&&n.dims.length!==5)throw new Error('Input "query" is expected to have 3 or 5 dimensions when key is empty');if(n.dims.length===5&&(n.dims[2]!==t.numHeads||n.dims[3]!==3))throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');_=3}if(a){if(a.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimension');if(i&&n.dims.length===5&&n.dims[3]===2)throw new Error("bias is not allowed for packed kv.")}let v=0;if(s){v=8;let M=s.dims;throw M.length===1?M[0]===u?v=1:M[0]===3*u+2&&(v=3):M.length===2&&M[0]===u&&M[1]===g&&(v=5),v===8?new Error('Input "key_padding_mask" shape shall be (batch_size) or (batch_size, kv_sequence_length)'):new Error("Mask not supported")}let b=!1,C=h;if(i){if(i.dims.length!==3&&i.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(n.dims[0]!==i.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(i.dims.length===3){if(g!==i.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');C=i.dims[2]}else{if(g!==i.dims[2])throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');C=i.dims[1]*i.dims[3],b=!0}}let I=$+g,O=!1;if(s)throw new Error("Key padding mask is not supported");if(o)throw new Error("extraAddQk is not supported");if(l)throw new Error("pastKey is not supported");if(d)throw new Error("pastValue is not supported");return{batchSize:u,sequenceLength:f,pastSequenceLength:$,kvSequenceLength:g,totalSequenceLength:I,maxSequenceLength:E,inputHiddenSize:0,hiddenSize:h,vHiddenSize:C,headSize:y,vHeadSize:Math.floor(C/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:v,scale:t.scale,broadcastResPosBias:O,passPastInKv:b,qkvFormat:_}},y2=e=>tt({...e}),Td=tt({perm:[0,2,1,3]}),p0=(e,t,n,r,i,a,s)=>{let o=[r,i,a],l=ne.size(o),d=[{type:"uint32",data:l},{type:"uint32",data:s},{type:"uint32",data:a}],c=u=>{let f=ke("qkv_with_bias",t.dataType,o),h=te("qkv",t.dataType,o),g=te("bias",n.dataType,o),$=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return` ${u.registerUniforms($).declareVariables(h,g,f)} ${u.mainStart()} ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let bias_offset_idx = (global_idx % uniforms.hidden_size) + uniforms.bias_offset; qkv_with_bias[global_idx] = qkv[global_idx] + bias[bias_offset_idx]; }`};return e.compute({name:"MultiHeadAttentionAddBias",shaderCache:{inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:o,dataType:t.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:d}),getShaderSource:c},{inputs:[t,n],outputs:[-1]})[0]},Qo=(e,t,n,r,i,a,s,o)=>{let l=a;if(s){if(r===1)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return l=p0(e,a,s,t,r,n*i,o),l=l.reshape([t,r,n,i]),e.compute(Gr(l,Td.perm),{inputs:[l],outputs:[-1]})[0]}else return a.dims.length===3&&(l=a.reshape([t,r,n,i])),e.compute(Gr(l,Td.perm),{inputs:[l],outputs:[-1]})[0]},w2=(e,t)=>{var o;let n=c0(e.inputs,t);if(e.inputs[0].dims.length===5)throw new Error("Packed QKV is not implemented");if(((o=e.inputs[1])==null?void 0:o.dims.length)===5)throw new Error("Packed KV is not implemented");let r=e.inputs[1]&&e.inputs[2]&&e.inputs[1].dims.length===4&&e.inputs[2].dims.length===4,i=Qo(e,n.batchSize,n.numHeads,n.sequenceLength,n.headSize,e.inputs[0],e.inputs[3],0);if(r)return Zl(e,i,e.inputs[1],e.inputs[2],e.inputs[4],void 0,void 0,void 0,e.inputs[5],n,t);let a=Qo(e,n.batchSize,n.numHeads,n.kvSequenceLength,n.headSize,e.inputs[1],e.inputs[3],n.hiddenSize),s=Qo(e,n.batchSize,n.numHeads,n.kvSequenceLength,n.vHeadSize,e.inputs[2],e.inputs[3],2*n.hiddenSize);Zl(e,i,a,s,e.inputs[4],void 0,e.inputs[6],e.inputs[7],e.inputs[5],n,t)}}),f0,h0,m0,g0,y0,w0,_0,v0,_2,CE=ee(()=>{lt(),ze(),Oe(),f0=e=>{if(!e||e.length<1)throw new Error("Too few inputs");if(e[0].dataType!==1)throw new Error("Input type must be float.");if(e.length>=2){let t=e[0].dims.length*2===e[1].dims[0];if(e.length===4&&(t=e[3].dims[0]*2===e[1].dims[0]),!t)throw new Error("The pads should be a 1D tensor of shape [2 * input_rank] or [2 * num_axes].")}},h0=(e,t,n)=>{let r="";for(let i=t-1;i>=0;--i)r+=` k = i32(${e.indicesGet("indices",i)}) - ${Ce("uniforms.pads",i,n)}; if (k < 0) { break; } if (k >= i32(${Ce("uniforms.x_shape",i,t)})) { break; } offset += k * i32(${Ce("uniforms.x_strides",i,t)}); `;return` value = ${e.type.value}(uniforms.constant_value); for (var i = 0; i < 1; i++) { var offset = 0; var k = 0; ${r} value = x[offset]; } `},m0=(e,t,n)=>{let r="";for(let i=t-1;i>=0;--i)r+=` k = i32(${e.indicesGet("indices",i)}) - ${Ce("uniforms.pads",i,n)}; if (k < 0) { k = -k; } { let _2n_1 = 2 * (i32(${Ce("uniforms.x_shape",i,t)}) - 1); k = k % _2n_1; if(k >= i32(${Ce("uniforms.x_shape",i,t)})) { k = _2n_1 - k; } } offset += k * i32(${Ce("uniforms.x_strides",i,t)}); `;return` var offset = 0; var k = 0; ${r} value = x[offset]; `},g0=(e,t,n)=>{let r="";for(let i=t-1;i>=0;--i)r+=` k = i32(${e.indicesGet("indices",i)}) - ${Ce("uniforms.pads",i,n)}; if (k < 0) { k = 0; } if (k >= i32(${Ce("uniforms.x_shape",i,t)})) { k = i32(${Ce("uniforms.x_shape",i,t)}) - 1; } offset += k * i32(${Ce("uniforms.x_strides",i,t)}); `;return` var offset = 0; var k = 0; ${r} value = x[offset]; `},y0=(e,t,n)=>{let r="";for(let i=t-1;i>=0;--i)r+=` k = i32(${e.indicesGet("indices",i)}) - ${Ce("uniforms.pads",i,n)}; if (k < 0) { k += i32(${Ce("uniforms.x_shape",i,t)}]); } if (k >= i32(${Ce("uniforms.x_shape",i,t)})) { k -= i32(${Ce("uniforms.x_shape",i,t)}); } offset += k * i32(${Ce("uniforms.x_strides",i,t)}); `;return` var offset = 0; var k = 0; ${r} value = x[offset]; `},w0=(e,t,n)=>{switch(n.mode){case 0:return h0(e,t,n.pads.length);case 1:return m0(e,t,n.pads.length);case 2:return g0(e,t,n.pads.length);case 3:return y0(e,t,n.pads.length);default:throw new Error("Invalid mode")}},_0=(e,t)=>{let n=ne.padShape(e[0].dims.slice(),t.pads),r=e[0].dims,i=[{type:"uint32",data:ne.size(n)},{type:"uint32",data:t.pads}];if(t.mode===0){let o=Kn(e[0].dataType);i.push({type:o,data:t.value})}i.push(...le(e[0].dims),...le(n));let a=["rank"],s=o=>{let l=ke("output",e[0].dataType,n.length),d=te("x",e[0].dataType,r.length),c=d.type.value,u=w0(l,r.length,t),f=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:t.pads.length}];return t.mode===0&&f.push({name:"constant_value",type:c}),` ${o.registerUniforms(f).declareVariables(d,l)} ${o.mainStart()} ${o.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let indices = ${l.offsetToIndices("global_idx")}; var value = ${c}(0); ${u} output[global_idx] = value; }`};return{name:"Pad",shaderCache:{hint:`${t.mode}`,inputDependencies:a},getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(ne.size(n)/64)},programUniforms:i}),getShaderSource:s}},v0=(e,t)=>{if(e.length>1){let n=e[1].getBigInt64Array(),r=e.length>=3&&e[2].data?e[2].getFloat32Array()[0]:0,i=e[0].dims.length,a=new Int32Array(2*i).fill(0);if(e.length>=4){let o=e[3].getBigInt64Array();for(let l=0;la[Number(l)]=Number(o));let s=[];return a.forEach(o=>s.push(o)),{mode:t.mode,value:r,pads:s}}else return t},_2=(e,t)=>{f0(e.inputs);let n=v0(e.inputs,t);e.compute(_0(e.inputs,n),{inputs:[0]})}}),Ya,Id,Ad,Od,Md,$0,b0,zd,Rd,v2,$2,Pd,b2,x2,Bd,S2,E2,k2,C2,TE=ee(()=>{Fn(),ze(),Oe(),Ya=e=>{if(je.webgpu.validateInputContent&&(!e||e.length!==1))throw new Error("Pool ops requires 1 input.")},Id=(e,t,n)=>{let r=t.format==="NHWC",i=e.dims.slice();r&&i.splice(1,0,i.pop());let a=Object.hasOwnProperty.call(t,"dilations"),s=t.kernelShape.slice(),o=t.strides.slice(),l=a?t.dilations.slice():[],d=t.pads.slice();Ql.adjustPoolAttributes(n,i,s,o,l,d);let c=Ql.computePoolOutputShape(n,i,o,l,s,d,t.autoPad),u=Object.assign({},t);a?Object.assign(u,{kernelShape:s,strides:o,pads:d,dilations:l,cacheKey:t.cacheKey}):Object.assign(u,{kernelShape:s,strides:o,pads:d,cacheKey:t.cacheKey});let f=c.slice();return f.push(f.splice(1,1)[0]),[u,r?f:c]},Ad=(e,t)=>{let n=t.format==="NHWC",r=ne.size(e),i=ne.size(t.kernelShape),a=[{type:"uint32",data:r},{type:"uint32",data:i}],s=[{name:"outputSize",type:"u32"},{name:"kernelSize",type:"u32"}];if(t.kernelShape.length<=2){let o=t.kernelShape[t.kernelShape.length-1],l=t.strides[t.strides.length-1],d=t.pads[t.pads.length/2-1],c=t.pads[t.pads.length-1],u=!!(d+c);a.push({type:"uint32",data:o},{type:"uint32",data:l},{type:"uint32",data:d},{type:"uint32",data:c}),s.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let f=!1;if(t.kernelShape.length===2){let h=t.kernelShape[t.kernelShape.length-2],g=t.strides[t.strides.length-2],$=t.pads[t.pads.length/2-2],E=t.pads[t.pads.length-2];f=!!($+E),a.push({type:"uint32",data:h},{type:"uint32",data:g},{type:"uint32",data:$},{type:"uint32",data:E}),s.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[a,s,!0,u,f]}else{if(n)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let o=ne.computeStrides(t.kernelShape);a.push({type:"uint32",data:o},{type:"uint32",data:t.pads},{type:"uint32",data:t.strides}),s.push({name:"kernelStrides",type:"u32",length:o.length},{name:"pads",type:"u32",length:t.pads.length},{name:"strides",type:"u32",length:t.strides.length});let l=t.pads.reduce((d,c)=>d+c);return[a,s,!!l,!1,!1]}},Od=(e,t,n,r,i,a,s,o,l,d,c,u)=>{let f=i.format==="NHWC",h=t.type.value,g=ke("output",t.type.tensor,r);if(i.kernelShape.length<=2){let $="",E="",y="",_=n-(f?2:1);if(c?$=` for (var i: u32 = 0u; i < uniforms.kw; i++) { xIndices[${_}] = indices[${_}] * uniforms.sw - uniforms.pwStart + i; if (xIndices[${_}] < 0 || xIndices[${_}] >= uniforms.x_shape[${_}]) { pad++; continue; } let x_val = x[${t.indicesToOffset("xIndices")}]; ${a} }`:$=` for (var i: u32 = 0u; i < uniforms.kw; i++) { xIndices[${_}] = indices[${_}] * uniforms.sw - uniforms.pwStart + i; let x_val = x[${t.indicesToOffset("xIndices")}]; ${a} }`,i.kernelShape.length===2){let v=n-(f?3:2);u?E=` for (var j: u32 = 0u; j < uniforms.kh; j++) { xIndices[${v}] = indices[${v}] * uniforms.sh - uniforms.phStart + j; if (xIndices[${v}] < 0 || xIndices[${v}] >= uniforms.x_shape[${v}]) { pad += i32(uniforms.kw); continue; } `:E=` for (var j: u32 = 0u; j < uniforms.kh; j++) { xIndices[${v}] = indices[${v}] * uniforms.sh - uniforms.phStart + j; `,y=` } `}return` ${e.registerUniforms(l).declareVariables(t,g)} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let indices = ${g.offsetToIndices("global_idx")}; var xIndices = ${g.offsetToIndices("global_idx")}; var value = ${h}(${o}); var pad = 0; ${E} ${$} ${y} ${s} output[global_idx] = value; }`}else{if(f)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let $=i.kernelShape.length,E=i.pads.length,y="";return d?y=` if (xIndices[j] >= uniforms.x_shape[j]) { pad++; isPad = true; break; } } if (!isPad) { let x_val = x[${t.indicesToOffset("xIndices")}]; ${a} }`:y=` } let x_val = x[${t.indicesToOffset("xIndices")}]; ${a} `,` ${e.registerUniforms(l).declareVariables(t,g)} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let indices = ${g.offsetToIndices("global_idx")}; var xIndices = ${g.offsetToIndices("global_idx")}; var offsets: array; var value = ${h}(${o}); var pad = 0; var isPad = false; for (var i: u32 = 0u; i < uniforms.kernelSize; i++) { var offset = i; for (var j = 0u; j < ${$-1}u; j++) { offsets[j] = offset / ${Ce("uniforms.kernelStrides","j",$)}; offset -= offsets[j] * ${Ce("uniforms.kernelStrides","j",$)}; } offsets[${$-1}] = offset; isPad = false; for (var j = ${n-$}u; j < ${n}u; j++) { xIndices[j] = indices[j] * ${Ce("uniforms.strides",`j - ${n-$}u`,$)} + offsets[j - ${n-$}u] - ${Ce("uniforms.pads","j - 2u",E)}; ${y} } ${s} output[global_idx] = value; }`}},Md=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,$0=e=>`${Md(e)};${e.countIncludePad}`,b0=e=>`${Md(e)};${e.storageOrder};${e.dilations}`,zd=e=>({format:e.format,autoPad:["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],ceilMode:e.ceil_mode,kernelShape:e.kernel_shape,strides:e.strides,pads:e.pads}),Rd=(e,t,n,r)=>{let[i,a]=Id(t,r,n),s=te("x",t.dataType,t.dims.length),o=s.type.value,l="value += x_val;",d="";i.countIncludePad?d+=`value /= ${o}(uniforms.kernelSize);`:d+=`value /= ${o}(i32(uniforms.kernelSize) - pad);`;let[c,u,f,h,g]=Ad(a,i);c.push(...le(t.dims),...le(a));let $=["rank"];return{name:e,shaderCache:{hint:`${r.cacheKey};${f};${h};${g}`,inputDependencies:$},getRunData:()=>({outputs:[{dims:a,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(ne.size(a)/64)},programUniforms:c}),getShaderSource:E=>Od(E,s,t.dims.length,a.length,i,l,d,0,u,f,h,g)}},v2=e=>{let t=e.count_include_pad!==0,n=zd(e);if(n.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");let r={countIncludePad:t,...n,cacheKey:""};return{...r,cacheKey:$0(r)}},$2=(e,t)=>{Ya(e.inputs),e.compute(Rd("AveragePool",e.inputs[0],!1,t))},Pd={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},b2=e=>{let t=e.format;return{format:t,...Pd,cacheKey:t}},x2=(e,t)=>{Ya(e.inputs),e.compute(Rd("GlobalAveragePool",e.inputs[0],!0,t))},Bd=(e,t,n,r)=>{let[i,a]=Id(t,r,n),s=` value = max(x_val, value); `,o="",l=te("x",t.dataType,t.dims.length),d=["rank"],[c,u,f,h,g]=Ad(a,i);return c.push(...le(t.dims),...le(a)),{name:e,shaderCache:{hint:`${r.cacheKey};${f};${h};${g}`,inputDependencies:d},getRunData:()=>({outputs:[{dims:a,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(ne.size(a)/64)},programUniforms:c}),getShaderSource:$=>Od($,l,t.dims.length,a.length,i,s,o,-1e5,u,f,h,g)}},S2=(e,t)=>{Ya(e.inputs),e.compute(Bd("MaxPool",e.inputs[0],!1,t))},E2=e=>{let t=e.storage_order,n=e.dilations,r=zd(e);if(t!==0)throw new Error("column major storage order is not yet supported for MaxPool");if(r.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");let i={storageOrder:t,dilations:n,...r,cacheKey:""};return{...i,cacheKey:b0(i)}},k2=e=>{let t=e.format;return{format:t,...Pd,cacheKey:t}},C2=(e,t)=>{Ya(e.inputs),e.compute(Bd("GlobalMaxPool",e.inputs[0],!0,t))}}),x0,S0,T2,IE=ee(()=>{Fn(),lt(),Oe(),x0=(e,t,n)=>{let r=e===t,i=et&&n>0;if(r||i||a)throw new Error("Range these inputs' contents are invalid.")},S0=(e,t,n,r)=>{let i=Math.abs(Math.ceil((t-e)/n)),a=[i],s=i,o=Kn(r),l=[{type:"uint32",data:s},{type:o,data:e},{type:o,data:n},...le(a)],d=c=>{let u=ke("output",r,a.length),f=u.type.value,h=[{name:"outputSize",type:"u32"},{name:"start",type:f},{name:"delta",type:f}];return` ${c.registerUniforms(h).declareVariables(u)} ${c.mainStart()} ${c.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} output[global_idx] = uniforms.start + ${f}(global_idx) * uniforms.delta; }`};return{name:"Range",shaderCache:{hint:`${r}`},getShaderSource:d,getRunData:()=>({outputs:[{dims:a,dataType:r}],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:l})}},T2=e=>{let t=0,n=0,r=0;e.inputs[0].dataType===6?(t=e.inputs[0].getInt32Array()[0],n=e.inputs[1].getInt32Array()[0],r=e.inputs[2].getInt32Array()[0]):e.inputs[0].dataType===1&&(t=e.inputs[0].getFloat32Array()[0],n=e.inputs[1].getFloat32Array()[0],r=e.inputs[2].getFloat32Array()[0]),je.webgpu.validateInputContent&&x0(t,n,r),e.compute(S0(t,n,r,e.inputs[0].dataType),{inputs:[]})}}),E0,k0,C0,T0,I0,A0,O0,M0,z0,R0,P0,Dd,B0,D0,N0,L0,F0,I2,A2,AE=ee(()=>{ze(),St(),Oe(),E0=(e,t)=>{if(e.every(n=>n>0||(()=>{throw new Error("Resize requires scales input values to be positive")})),e.length>0){if(t.mode==="linear"){if(!(e.length===2||e.length===3||e.length===4&&e[0]===1&&e[1]===1||e.length===4&&e[0]===1&&e[3]===1||e.length===5&&e[0]===1&&e[1]===1))throw new Error(`For linear mode, Resize requires scales to be 2D, 3D, 4D with either two outermost or one innermost and one outermost scale values equal to 1, or 5D with two outermost scale values equal to 1`)}else if(t.mode==="cubic"&&!(e.length===2||e.length===4&&e[0]===1&&e[1]===1||e.length===4&&e[0]===1&&e[3]===1))throw new Error("Resize requires scales input size to be 2 or 4 for cubic mode")}},k0=(e,t,n)=>{t.every(i=>i>=0&&i{throw new Error("Resize requires axes input values to be positive and less than rank")}));let r=new Array(n).fill(1);return t.forEach((i,a)=>r[i]=e[a]),r},C0=(e,t,n,r,i,a)=>{let[s,o,l]=n>10?[1,2,3]:[-1,e.length>1?1:-1,-1],d=e[0].dims.length;if(s>0&&e.length>s&&e[s].dims.length>0)e[s].getFloat32Array().forEach(c=>a.push(c));else if(t.coordinateTransformMode==="tf_crop_and_resize")throw new Error("Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize");if(o>0&&e.length>o&&e[o].dims.length>0){if(e[o].getFloat32Array().forEach(c=>r.push(c)),r.length!==0&&r.length!==d&&n>=18&&r.length!==t.axes.length)throw new Error("Resize requires scales input size to be same as input rank or axes size for opset 18 and up");E0(r,t),t.axes.length>0&&k0(r,t.axes,d).forEach((c,u)=>r[u]=c)}if(l>0&&e.length>l&&(e[l].getBigInt64Array().forEach(c=>i.push(Number(c))),i.length!==d||n>=18&&i.length===t.axes.length))throw new Error("Resize requires sizes input size to be same as input rank or axes size for opset 18 and up");if(t.axes.length>0){if(r.length!==t.axes.length)throw new Error('Resize requires "scales" input size to be of axes rank when axes attributes is specified');if(i.length!==t.axes.length)throw new Error('Resize requires "sizes" input size to be of rank axes rank when axes attributes is specified')}if(typeof r<"u"&&typeof i<"u"&&r.length>0&&i.length>d)throw new Error("Resize requires only of scales or sizes to be specified")},T0=(e,t)=>`fn getOriginalCoordinateFromResizedCoordinate(xResized: u32, xScale: f32, lengthResized: u32, lengthOriginal: u32, roiStart: f32, roiEnd: f32) -> ${t} { `+(()=>{switch(e){case"asymmetric":return`return ${t}(xResized) / ${t}(xScale);`;case"pytorch_half_pixel":return`if (lengthResized > 1) { return (${t}(xResized) + 0.5) / ${t}(xScale) - 0.5; } else { return 0.0; }`;case"tf_half_pixel_for_nn":return`return (${t}(xResized) + 0.5) / ${t}(xScale);`;case"align_corners":return`if (lengthResized == 1) { return 0.0; } else { // The whole part and the fractional part are calculated separately due to inaccuracy of floating // point division. As an example, f32(21) / f32(7) may evaluate to 2.99... instead of 3, causing an // offset-by-one error later in floor(). let whole = ${t}(xResized * (lengthOriginal - 1) / (lengthResized - 1)); let fract = ${t}(xResized * (lengthOriginal - 1) % (lengthResized - 1)) / ${t}(lengthResized - 1); return whole + fract; }`;case"tf_crop_and_resize":return`if (lengthResized > 1) { return ${t}(roiStart) * ${t}(lengthOriginal - 1) + (${t}(xResized) * ${t}(roiEnd - roiStart) * ${t}(lengthOriginal - 1)) / ${t}(lengthResized - 1); } else { return 0.5 * ${t}(roiStart + roiEnd) * ${t}(lengthOriginal - 1); }`;case"half_pixel_symmetric":return`const outputWidth = ${t}xScale * ${t}(lengthResized); const adjustment = ${t}(lengthResized) / outputWidth; const center = ${t}(lengthOriginal) / 2; const offset = center * (1 - adjustment); return offset + ((${t}(xResized) + 0.5) / ${t}(xScale)) - 0.5;`;case"half_pixel":return`return ((${t}(xResized) + 0.5) / ${t}(xScale)) - 0.5;`;default:throw new Error(`Coordinate transform mode ${e} is not supported`)}})()+"}",I0=(e,t,n)=>`fn getNearestPixelFromOriginal(xOriginal: ${n}, isDownSample: bool) -> ${n} {`+(()=>{switch(e){case"round_prefer_ceil":return"if (fract(xOriginal) == 0.5) { return ceil(xOriginal); } else { return round(xOriginal); }";case"floor":return"return floor(xOriginal);";case"ceil":return"return ceil(xOriginal);";case"round_prefer_floor":return"if (fract(xOriginal) == 0.5) { return floor(xOriginal); } else { return round(xOriginal); }";case"simple":default:if(t<11)return"if (isDownSample) { return ceil(xOriginal); } else { return xOriginal; }";throw new Error(`Nearest mode ${e} is not supported`)}})()+"}",A0=(e,t,n)=>{let r=new Array(n).fill(0).concat(new Array(n).fill(1)),i=e.length===0?r:e.slice();return t.length>0?(t.forEach((a,s)=>{r[a]=i[s],r[s+n]=i[t.length+s]}),r):i},O0=(e,t,n,r)=>{let i=[];if(n.length>0)if(r.length>0){if(e.forEach(a=>i.push(a)),Math.max(...r)>e.length)throw new Error("axes is out of bound");r.forEach((a,s)=>i[a]=n[s])}else n.forEach(a=>i.push(a));else{if(t.length===0)throw new Error("Resize requires either scales or sizes.");i=e.map((a,s)=>Math.round(a*t[s]))}return i},M0=(e,t,n)=>{let r=(()=>{switch(n.keepAspectRatioPolicy){case"not_larger":return n.axes.length>0?Math.min(...n.axes.map(a=>t[a]),Number.MAX_VALUE):Math.min(...t,Number.MAX_VALUE);case"not_smaller":return n.axes.length>0?Math.max(...n.axes.map(a=>t[a]),Number.MIN_VALUE):Math.max(...t,Number.MIN_VALUE);default:throw new Error(`Keep aspect ratio policy ${n.keepAspectRatioPolicy} is not supported`)}})();t.fill(1,0,t.length);let i=e.slice();return n.axes.length>0?(n.axes.forEach(a=>t[a]=r),n.axes.forEach(a=>i[a]=Math.round(e[a]*t[a]))):(t.fill(r,0,t.length),i.forEach((a,s)=>i[s]=Math.round(a*t[s]))),i},z0=(e,t,n,r,i)=>` fn calculateOriginalIndicesFromOutputIndices(output_indices: ${e.type.indices}) -> array<${e.type.value}, ${n.length}> { var original_indices: array<${e.type.value}, ${n.length}>; for (var i:u32 = 0; i < ${n.length}; i++) { var output_index = ${e.indicesGet("output_indices","i")}; var scale = ${Ce("uniforms.scales","i",r)}; var roi_low = ${Ce("uniforms.roi","i",i)}; var roi_hi = ${Ce("uniforms.roi",`i + ${t.length}`,i)}; if (scale == 1.0) { original_indices[i] = ${e.type.value}(output_index); } else { var input_shape_i = ${Ce("uniforms.input_shape","i",t.length)}; var output_shape_i = ${Ce("uniforms.output_shape","i",n.length)}; original_indices[i] = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, input_shape_i, roi_low, roi_hi); } } return original_indices; }`,R0=(e,t,n,r,i,a,s)=>` fn calculateInputIndicesFromOutputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} { var input_indices: ${e.type.indices}; for (var i:u32 = 0; i < ${r.length}; i++) { var output_index = ${t.indicesGet("output_indices","i")}; var input_index: u32; var scale = ${Ce("uniforms.scales","i",i)}; if (scale == 1.0) { input_index = output_index; } else { var roi_low = ${Ce("uniforms.roi","i",a)}; var roi_hi = ${Ce("uniforms.roi",`i + ${n.length}`,a)}; var input_shape_i = ${Ce("uniforms.input_shape","i",n.length)}; var output_shape_i = ${Ce("uniforms.output_shape","i",r.length)}; var original_idx = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, input_shape_i, roi_low, roi_hi); if (!${s} || (original_idx >= 0 && original_idx < ${t.type.value}(input_shape_i))) { if (original_idx < 0) { input_index = 0; } else if (original_idx > ${t.type.value}(input_shape_i - 1)) { input_index = input_shape_i - 1; } else { input_index = u32(getNearestPixelFromOriginal(original_idx, scale < 1)); } } else { input_index = u32(original_idx); } } ${e.indicesSet("input_indices","i"," input_index")} } return input_indices; }`,P0=(e,t)=>` fn checkInputIndices(input_indices: ${e.type.indices}) -> bool { for (var i:u32 = 0; i < ${t.length}; i++) { var input_index = ${e.indicesGet("input_indices","i")}; if (input_index < 0 || input_index >= ${Ce("uniforms.input_shape","i",t.length)}) { return false; } } return true; }`,Dd=(e,t,n,r)=>e.rank>r?` ${e.indicesSet("input_indices",t,"channel")}; ${e.indicesSet("input_indices",n,"batch")}; `:"",B0=(e,t,n,r,i)=>{let[a,s,o,l]=n.length===2?[-1,0,1,-1]:[0,2,3,1],d=e.type.value;return` fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${d} { var input_indices: ${e.type.indices}; ${e.indicesSet("input_indices",s,`max(0, min(row, ${n[s]} - 1))`)}; ${e.indicesSet("input_indices",o,`max(0, min(col, ${n[o]} - 1))`)}; ${Dd(e,l,a,2)} return ${e.getByIndices("input_indices")}; } fn bilinearInterpolation(output_indices: ${t.type.indices}) -> ${d} { var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); var row:${d} = originalIndices[${s}]; var col:${d} = originalIndices[${o}]; ${r?`if (row < 0 || row > (${n[s]} - 1) || col < 0 || col > (${n[o]} - 1)) { return ${i}; }`:""}; row = max(0, min(row, ${n[s]} - 1)); col = max(0, min(col, ${n[o]} - 1)); var row1: u32 = u32(row); var col1: u32 = u32(col); var row2: u32 = u32(row + 1); var col2: u32 = u32(col + 1); var channel: u32 = ${n.length>2?`u32(originalIndices[${l}])`:"0"}; var batch: u32 = ${n.length>2?`u32(originalIndices[${a}])`:"0"}; var x11: ${d} = getInputValue(batch, channel, row1, col1); var x12: ${d} = getInputValue(batch, channel, row1, col2); var x21: ${d} = getInputValue(batch, channel, row2, col1); var x22: ${d} = getInputValue(batch, channel, row2, col2); var dx1: ${d} = abs(row - ${d}(row1)); var dx2: ${d} = abs(${d}(row2) - row); var dy1: ${d} = abs(col - ${d}(col1)); var dy2: ${d} = abs(${d}(col2) - col); if (row1 == row2) { dx1 = 0.5; dx2 = 0.5; } if (col1 == col2) { dy1 = 0.5; dy2 = 0.5; } return (x11 * dx2 * dy2 + x12 * dx2 * dy1 + x21 * dx1 * dy2 + x22 * dx1 * dy1); }`},D0=(e,t,n,r,i,a,s,o,l,d)=>{let c=n.length===2,[u,f]=c?[0,1]:[2,3],h=e.type.value,g=$=>{let E=$===u?"row":"col";return` fn ${E}CubicInterpolation(input_indices: ${e.type.indices}, output_indices: ${t.type.indices}) -> ${h} { var output_index = ${t.indicesGet("output_indices",$)}; var originalIdx: ${h} = getOriginalCoordinateFromResizedCoordinate(output_index, ${i[$]}, ${r[$]}, ${n[$]}, ${a[$]}, ${a[$]} + ${n.length}); var fractOriginalIdx: ${h} = originalIdx - floor(originalIdx); var coefs = getCubicInterpolationCoefs(fractOriginalIdx); if (${o} && (originalIdx < 0 || originalIdx > (${n[$]} - 1))) { return ${l}; } var data: array<${h}, 4> = array<${h}, 4>(0.0, 0.0, 0.0, 0.0); for (var i: i32 = -1; i < 3; i++) { var ${E}: ${h} = originalIdx + ${h}(i); if (${E} < 0 || ${E} >= ${n[$]}) { ${d?`coefs[i + 1] = 0.0; continue;`:o?`return ${l};`:`${E} = max(0, min(${E}, ${n[$]} - 1));`}; } var input_indices_copy: ${e.type.indices} = input_indices; ${e.indicesSet("input_indices_copy",$,`u32(${E})`)}; data[i + 1] = ${$===u?e.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"}; } return cubicInterpolation1D(data, coefs); }`};return` ${g(u)}; ${g(f)}; fn getCubicInterpolationCoefs(s: ${h}) -> array<${h}, 4> { var absS = abs(s); var coeffs: array<${h}, 4> = array<${h}, 4>(0.0, 0.0, 0.0, 0.0); var oneMinusAbsS: ${h} = 1.0 - absS; var twoMinusAbsS: ${h} = 2.0 - absS; var onePlusAbsS: ${h} = 1.0 + absS; coeffs[0] = ((${s} * onePlusAbsS - 5 * ${s}) * onePlusAbsS + 8 * ${s}) * onePlusAbsS - 4 * ${s}; coeffs[1] = ((${s} + 2) * absS - (${s} + 3)) * absS * absS + 1; coeffs[2] = ((${s} + 2) * oneMinusAbsS - (${s} + 3)) * oneMinusAbsS * oneMinusAbsS + 1; coeffs[3] = ((${s} * twoMinusAbsS - 5 * ${s}) * twoMinusAbsS + 8 * ${s}) * twoMinusAbsS - 4 * ${s}; return coeffs; } fn cubicInterpolation1D(x: array<${h}, 4>, coefs: array<${h}, 4>) -> ${h} { var coefsSum: ${h} = coefs[0] + coefs[1] + coefs[2] + coefs[3]; return (x[0] * coefs[0] + x[1] * coefs[1]+ x[2] * coefs[2]+ x[3] * coefs[3]) / coefsSum; } fn bicubicInterpolation(output_indices: ${t.type.indices}) -> ${h} { var input_indices: ${e.type.indices} = output_indices; return colCubicInterpolation(input_indices, output_indices); } `},N0=(e,t,n,r,i)=>{let[a,s,o,l,d]=n.length===3?[-1,0,1,2,-1]:[0,2,3,4,1],c=e.type.value;return` fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${c} { var input_indices: ${e.type.indices}; ${e.indicesSet("input_indices",s,`max(0, min(depth, ${n[s]} - 1))`)}; ${e.indicesSet("input_indices",o,`max(0, min(height, ${n[o]} - 1))`)}; ${e.indicesSet("input_indices",l,`max(0, min(width, ${n[l]} - 1))`)}; ${Dd(e,d,a,3)} return ${e.getByIndices("input_indices")}; } fn trilinearInterpolation(output_indices: ${t.type.indices}) -> ${c} { var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); var depth:${c} = originalIndices[${s}]; var height:${c} = originalIndices[${o}]; var width:${c} = originalIndices[${l}]; ${r?`if (depth < 0 || depth > (${n[s]} - 1) || height < 0 || height > (${n[o]} - 1) || width < 0 || (width > ${n[l]} - 1)) { return ${i}; }`:""}; depth = max(0, min(depth, ${n[s]} - 1)); height = max(0, min(height, ${n[o]} - 1)); width = max(0, min(width, ${n[l]} - 1)); var depth1: u32 = u32(depth); var height1: u32 = u32(height); var width1: u32 = u32(width); var depth2: u32 = u32(depth + 1); var height2: u32 = u32(height + 1); var width2: u32 = u32(width + 1); var channel: u32 = ${n.length>3?`u32(originalIndices[${d}])`:"0"}; var batch: u32 = ${n.length>3?`u32(originalIndices[${a}])`:"0"}; var x111: ${c} = getInputValue(batch, channel, depth1, height1, width1); var x112: ${c} = getInputValue(batch, channel, depth1, height1, width2); var x121: ${c} = getInputValue(batch, channel, depth1, height2, width1); var x122: ${c} = getInputValue(batch, channel, depth1, height2, width2); var x211: ${c} = getInputValue(batch, channel, depth2, height1, width1); var x212: ${c} = getInputValue(batch, channel, depth2, height1, width2); var x221: ${c} = getInputValue(batch, channel, depth2, height2, width1); var x222: ${c} = getInputValue(batch, channel, depth2, height2, width2); var dx1: ${c} = abs(depth - ${c}(depth1)); var dx2: ${c} = abs(${c}(depth2) - depth); var dy1: ${c} = abs(height - ${c}(height1)); var dy2: ${c} = abs(${c}(height2) - height); var dz1: ${c} = abs(width - ${c}(width1)); var dz2: ${c} = abs(${c}(width2) - width); if (depth1 == depth2) { dx1 = 0.5; dx2 = 0.5; } if (height1 == height2) { dy1 = 0.5; dy2 = 0.5; } if (width1 == width2) { dz1 = 0.5; dz2 = 0.5; } return (x111 * dx2 * dy2 * dz2 + x112 * dx2 * dy2 * dz1 + x121 * dx2 * dy1 *dz2 + x122 * dx2 * dy1 * dz1 + x211 * dx1 * dy2 * dz2 + x212 * dx1 * dy2 * dz1 + x221 * dx1 * dy1 *dz2 + x222 * dx1 * dy1 * dz1); }`},L0=(e,t,n,r,i,a)=>{let s=e.dims,o=A0(a,t.axes,s.length),l=O0(s,r,i,t.axes),d=r.slice();r.length===0&&(d=s.map((_,v)=>_===0?1:l[v]/_),t.keepAspectRatioPolicy!=="stretch"&&(l=M0(s,d,t)));let c=ke("output",e.dataType,l.length),u=te("input",e.dataType,s.length),f=ne.size(l),h=s.length===l.length&&s.every((_,v)=>_===l[v]),g=t.coordinateTransformMode==="tf_crop_and_resize",$=t.extrapolationValue,E=u.type.value,y=_=>` ${h?"":` ${T0(t.coordinateTransformMode,E)}; ${(()=>{switch(t.mode){case"nearest":return` ${P0(u,s)}; ${I0(t.nearestMode,n,E)}; ${R0(u,c,s,l,d.length,o.length,g)}; `;case"linear":return` ${z0(c,s,l,d.length,o.length)}; ${(()=>{if(s.length===2||s.length===4)return`${B0(u,c,s,g,$)}`;if(s.length===3||s.length===5)return`${N0(u,c,s,g,$)}`;throw Error("Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.")})()}; `;case"cubic":return` ${(()=>{if(s.length===2||s.length===4)return`${D0(u,c,s,l,d,o,t.cubicCoeffA,g,t.extrapolationValue,t.excludeOutside)}`;throw Error("Cubic mode only supports input dims 2 and 4 are supported in linear mode.")})()}; `;default:throw Error("Invalid resize mode")}})()}; `} ${_.registerUniform("output_size","u32").registerUniform("scales","f32",d.length).registerUniform("roi","f32",o.length).declareVariables(u,c)} ${_.mainStart()} ${_.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} ${h?"output[global_idx] = input[global_idx];":` let output_indices = ${c.offsetToIndices("global_idx")}; var input_indices: ${u.type.indices}; ${(()=>{switch(t.mode){case"nearest":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices); if (checkInputIndices(input_indices)) { output[global_idx] = ${u.getByIndices("input_indices")}; } else { output[global_idx] = ${t.extrapolationValue}; }`;case"linear":return`output[global_idx] = ${s.length===2||s.length===4?"bilinearInterpolation":"trilinearInterpolation"}(output_indices);`;case"cubic":return"output[global_idx] = bicubicInterpolation(output_indices);";default:throw Error(`Unsupported resize mode: ${t.mode}`)}})()}; `} }`;return{name:"Resize",shaderCache:{hint:`${t.cacheKey}|${n}|${d.length>0?d:""}|${i.length>0?i:""}|${o.length>0?o:""}|${h}|${s}`,inputDependencies:["rank"]},getShaderSource:y,getRunData:()=>({outputs:[{dims:l,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(f/64)},programUniforms:[{type:"uint32",data:f},{type:"float32",data:d},{type:"float32",data:o},...le(s),...le(l)]})}},F0=e=>{let t=e.customDataBuffer;return new Uint32Array(t,t.byteOffset,1)[0]},I2=(e,t)=>{let n=[],r=[],i=[],a=F0(e);if(t.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");C0(e.inputs,t,a,n,r,i),e.compute(L0(e.inputs[0],t,a,n,r,i),{inputs:[0]})},A2=e=>{let t=e.antialias,n=e.axes,r=e.coordinateTransformMode,i=e.cubicCoeffA,a=e.excludeOutside!==0,s=e.extrapolationValue,o=e.keepAspectRatioPolicy,l=e.mode,d=e.nearestMode===""?"simple":e.nearestMode;return tt({antialias:t,axes:n,coordinateTransformMode:r,cubicCoeffA:i,excludeOutside:a,extrapolationValue:s,keepAspectRatioPolicy:o,mode:l,nearestMode:d})}}),U0,W0,O2,M2,OE=ee(()=>{lt(),ze(),St(),Oe(),U0=e=>{if(!e||e.length<3)throw new Error("layerNorm requires at least 3 inputs.");let t=e[0],n=e[1],r=e[2];if(t.dataType!==n.dataType||t.dataType!==r.dataType)throw new Error("All inputs must have the same data type");if(t.dims.length!==3&&t.dims.length!==2)throw new Error("Input must be 2D or 3D");if(n.dims.length!==3&&n.dims.length!==2)throw new Error("Skip must be 2D or 3D");let i=t.dims[t.dims.length-1],a=t.dims[t.dims.length-2];if(n.dims[n.dims.length-1]!==i)throw new Error("Skip must have the same hidden size as input");if(n.dims[n.dims.length-2]!==a)throw new Error("Skip must have the same sequence length as input");if(r.dims.length!==1)throw new Error("Gamma must be 1D");if(r.dims[r.dims.length-1]!==i)throw new Error("Gamma must have the same hidden size as input");if(e.length>3){let s=e[3];if(s.dims.length!==1)throw new Error("Beta must be 1D");if(s.dims[s.dims.length-1]!==i)throw new Error("Beta must have the same hidden size as input")}if(e.length>4){let s=e[4];if(s.dims.length!==1)throw new Error("Bias must be 1D");if(s.dims[s.dims.length-1]!==i)throw new Error("Bias must have the same hidden size as input")}},W0=(e,t,n,r)=>{let i=e[0].dims,a=ne.size(i),s=i,o=a,l=i.slice(-1)[0],d=r?i.slice(0,-1).concat(1):[],c=e.length>3,u=e.length>4,f=r&&n>1,h=r&&n>2,g=n>3,$=rn(l),E=[te("x",e[0].dataType,e[0].dims,$),te("skip",e[1].dataType,e[1].dims,$),te("gamma",e[2].dataType,e[2].dims,$)];c&&E.push(te("beta",e[3].dataType,e[3].dims,$)),u&&E.push(te("bias",e[4].dataType,e[4].dims,$)),E.push(ke("output",e[0].dataType,s,$)),f&&E.push(ke("meanOutput",1,d)),h&&E.push(ke("invStdOutput",1,d)),g&&E.push(ke("inputSkipBiasSum",e[0].dataType,s,$));let y=wn(e[0].dataType),_=b=>` const hiddenSize: f32 = ${l}; const hiddenSizeVectorized: u32 = ${l/$}; const epsilon: f32 = ${t.epsilon}; ${b.declareVariables(...E)} ${b.mainStart()} ${b.guardAgainstOutOfBoundsWorkgroupSizes(o/l)} let offset = global_idx * hiddenSizeVectorized; var sum = ${tn("f32",$)}; var squareSum = ${tn("f32",$)}; for (var i: u32 = 0; i < hiddenSizeVectorized; i++) { let skipValue = skip[offset + i]; let biasValue = ${u?"bias[i]":"0.0"}; let inputValue = x[offset + i]; let value = inputValue + skipValue + biasValue; ${g?"inputSkipBiasSum[offset + i] = value;":""} output[offset + i] = value; let f32Value = ${ur(y,$,"value")}; sum += f32Value; squareSum += f32Value * f32Value; } let mean = ${Zn("sum",$)} / hiddenSize; let invStdDev = inverseSqrt(${Zn("squareSum",$)} / hiddenSize - mean * mean + epsilon); ${f?"meanOutput[global_idx] = mean;":""} ${h?"invStdOutput[global_idx] = invStdDev;":""} for (var i: u32 = 0; i < hiddenSizeVectorized; i++) { output[offset + i] = (output[offset + i] - ${y}(mean)) * ${y}(invStdDev) * gamma[i] + ${c?"beta[i]":"0.0"}; } }`,v=[{dims:s,dataType:e[0].dataType}];return n>1&&v.push({dims:d,dataType:1}),n>2&&v.push({dims:d,dataType:1}),n>3&&v.push({dims:i,dataType:e[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:t.cacheKey},getShaderSource:_,getRunData:()=>({outputs:v,dispatchGroup:{x:Math.ceil(o/l/64)}})}},O2=(e,t)=>{U0(e.inputs);let n=[0];e.outputCount>1&&n.push(-3),e.outputCount>2&&n.push(-3),e.outputCount>3&&n.push(3),e.compute(W0(e.inputs,t,e.outputCount,!1),{outputs:n})},M2=e=>{let t=e.epsilon;return tt({epsilon:t})}}),V0,Qa,j0,Nd,G0,H0,z2,R2,ME=ee(()=>{lt(),ze(),St(),Oe(),V0=(e,t)=>{if(!e||e.length<1)throw new Error("too few inputs");if(t.axes.length!==0){if(t.axes.length!==t.starts.length||t.axes.length!==t.ends.length)throw new Error("axes, starts and ends must have the same length")}else if(t.starts.length!==t.ends.length)throw new Error("starts and ends must have the same length");e.slice(1).forEach((n,r)=>{if(e[r+1].dataType!==6&&e[r+1].dataType!==7)throw new Error(`Input ${r} must be an array of int32 or int64`)})},Qa=(e,t)=>{let n=[];if(e.length>t)if(e[t].dataType===7)e[t].getBigInt64Array().forEach(r=>n.push(Number(r)));else if(e[t].dataType===6)e[t].getInt32Array().forEach(r=>n.push(Number(r)));else throw new Error(`Input ${t} must be an array of int32 or int64`);return n},j0=(e,t)=>{if(e.length>1){let n=Qa(e,1),r=Qa(e,2),i=Qa(e,3);return i.length===0&&(i=[...Array(e[0].dims.length).keys()]),tt({starts:n,ends:r,axes:i})}else return t},Nd=(e,t,n,r,i)=>{let a=e;return e<0&&(a+=n[r[t]]),i[t]<0?Math.max(0,Math.min(a,n[r[t]]-1)):Math.max(0,Math.min(a,n[r[t]]))},G0=(e,t,n)=>`fn calculateInputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} { var input_indices: ${e.type.indices}; var carry = 0u; for (var i = ${n.length}; i >= 0; i--) { let input_shape_i = ${Ce("uniforms.input_shape","i",n.length)}; let steps_i = ${Ce("uniforms.steps","i",n.length)}; let signs_i = ${Ce("uniforms.signs","i",n.length)}; let starts_i = ${Ce("uniforms.starts","i",n.length)}; var output_index = ${t.indicesGet("output_indices","i")}; var input_index = output_index * steps_i + starts_i + carry; carry = input_index / input_shape_i; input_index = input_index % input_shape_i; if (signs_i < 0) { input_index = input_shape_i - input_index - 1u + starts_i; } ${e.indicesSet("input_indices","i","input_index")}; } return input_indices; }`,H0=(e,t)=>{let n=e[0].dims,r=ne.size(n),i=t.axes.length>0?ne.normalizeAxes(t.axes,n.length):[...Array(n.length).keys()],a=Qa(e,4);a.forEach(y=>y!==0||(()=>{throw new Error("step cannot be 0")})),a.length===0&&(a=Array(i.length).fill(1));let s=t.starts.map((y,_)=>Nd(y,_,n,i,a)),o=t.ends.map((y,_)=>Nd(y,_,n,i,a));if(i.length!==s.length||i.length!==o.length)throw new Error("start, ends and axes should have the same number of elements");if(i.length!==n.length)for(let y=0;yMath.sign(y));a.forEach((y,_,v)=>{if(y<0){let b=(o[_]-s[_])/y,C=s[_],I=C+b*a[_];s[_]=I,o[_]=C,v[_]=-y}});let d=n.slice(0);i.forEach((y,_)=>{d[y]=Math.ceil((o[y]-s[y])/a[y])});let c={dims:d,dataType:e[0].dataType},u=ke("output",e[0].dataType,d.length),f=te("input",e[0].dataType,e[0].dims.length),h=ne.size(d),g=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:s.length},{name:"signs",type:"i32",length:l.length},{name:"steps",type:"u32",length:a.length}],$=[{type:"uint32",data:h},{type:"uint32",data:s},{type:"int32",data:l},{type:"uint32",data:a},...le(e[0].dims),...le(d)],E=y=>` ${y.registerUniforms(g).declareVariables(f,u)} ${G0(f,u,n)} ${y.mainStart()} ${y.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let output_indices = ${u.offsetToIndices("global_idx")}; let input_indices = calculateInputIndices(output_indices); ${u.setByOffset("global_idx",f.getByIndices("input_indices"))} }`;return{name:"Slice",shaderCache:{hint:`${l.length}_${s.length}_${a.length}`,inputDependencies:["rank"]},getShaderSource:E,getRunData:()=>({outputs:[c],dispatchGroup:{x:Math.ceil(r/64)},programUniforms:$})}},z2=(e,t)=>{V0(e.inputs,t);let n=j0(e.inputs,t);e.compute(H0(e.inputs,n),{inputs:[0]})},R2=e=>{let t=e.starts,n=e.ends,r=e.axes;return tt({starts:t,ends:n,axes:r})}}),q0,K0,P2,B2,zE=ee(()=>{ze(),St(),Oe(),q0=e=>{if(!e||e.length!==1)throw new Error("Softmax op requires 1 input.")},K0=(e,t)=>{let n=e.dims,r=ne.size(n),i=64,a=t.axis;if(a<0&&(a=n.length+a),ay===4?`max(max(${E}.x, ${E}.y), max(${E}.z, ${E}.w))`:y===2?`max(${E}.x, ${E}.y)`:y===3?`max(max(${E}.x, ${E}.y), ${E}.z)`:E,u=te("x",e.dataType,e.dims,l),f=ke("result",e.dataType,e.dims,l),h=u.type.value,g=wn(e.dataType)==="f32"?`var threadMax = ${h}(-3.402823e+38f);`:`var threadMax = ${h}(-65504.0h);`,$=E=>` var rowMaxShared : ${h}; var rowSumShared : ${h}; var threadShared : array<${h}, ${i}>; fn getValue(row: i32, col: i32, row_stride: i32) -> ${h} { let index = row * row_stride + col; return x[index]; } fn setValue(row: i32, col: i32, row_stride: i32, value: ${h}) { let index = row * row_stride + col; result[index] = value; } ${E.registerUniform("packedCols","i32").declareVariables(u,f)} ${E.mainStart()} let gindex = i32(global_idx); let lindex = i32(local_idx); const wg = ${i}; let row = gindex / wg; let cols = uniforms.packedCols; let row_stride : i32 = uniforms.packedCols; // find the rows max ${g} for (var col = lindex; col < cols; col += wg) { let value = getValue(row, col, row_stride); threadMax = max(threadMax, value); } if (lindex < cols) { threadShared[lindex] = threadMax; } workgroupBarrier(); var reduceSize = min(cols, wg); for (var currSize = reduceSize >> 1; currSize > 0; currSize = reduceSize >> 1) { reduceSize = currSize + (reduceSize & 1); if (lindex < currSize) { threadShared[lindex] = max(threadShared[lindex], threadShared[lindex + reduceSize]); } workgroupBarrier(); } if (lindex == 0) { rowMaxShared = ${h}(${c("threadShared[0]",l)}); } workgroupBarrier(); // find the rows sum var threadSum = ${h}(0.0); for (var col = lindex; col < cols; col += wg) { let subExp = exp(getValue(row, col, row_stride) - rowMaxShared); threadSum += subExp; } threadShared[lindex] = threadSum; workgroupBarrier(); for (var currSize = wg >> 1; currSize > 0; currSize = currSize >> 1) { if (lindex < currSize) { threadShared[lindex] = threadShared[lindex] + threadShared[lindex + currSize]; } workgroupBarrier(); } if (lindex == 0) { rowSumShared = ${h}(${Zn("threadShared[0]",l)}); } workgroupBarrier(); // calculate final value for each element in the row for (var col = lindex; col < cols; col += wg) { let value = exp(getValue(row, col, row_stride) - rowMaxShared) / rowSumShared; setValue(row, col, row_stride, value); } }`;return{name:"Softmax",shaderCache:{hint:`${l}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:n,dataType:e.dataType}],dispatchGroup:{x:o},programUniforms:[{type:"uint32",data:d}]}),getShaderSource:$}},P2=(e,t)=>{q0(e.inputs),e.compute(K0(e.inputs[0],t))},B2=e=>tt({axis:e.axis})}),Y0,Q0,X0,Z0,J0,D2,N2,RE=ee(()=>{ze(),St(),Oe(),Y0=e=>{if(!e||e.length<1)throw new Error("too few inputs")},Q0=(e,t)=>{let n=[],r=t.numOutputs;return e[1].dims[0]>0&&(e[1].getBigInt64Array().forEach(i=>n.push(Number(i))),r=n.length),tt({numOutputs:r,axis:t.axis,splitSizes:n})},X0=e=>` fn calculateOutputIndex(index: u32) -> u32 { for (var i: u32 = 0u; i < ${e}u; i += 1u ) { if (index < ${Ce("uniforms.size_in_split_axis","i",e)}) { return i; } } return ${e}u; }`,Z0=e=>{let t=e.length,n=[];for(let r=0;r{let n=e[0].dims,r=ne.size(n),i=e[0].dataType,a=ne.normalizeAxis(t.axis,n.length),s=new Array(t.numOutputs),o=te("input",i,n),l=new Array(t.numOutputs),d=[],c=[],u=0,f=[{type:"uint32",data:r}];for(let g=0;gf.push(...le(g)));let h=g=>` ${g.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",l.length).declareVariables(o,...s)} ${X0(l.length)} ${Z0(s)} ${g.mainStart()} ${g.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")} var indices = ${o.offsetToIndices("global_idx")}; var index = ${o.indicesGet("indices",a)}; let output_number = calculateOutputIndex(index); if (output_number != 0) { index -= ${Ce("uniforms.size_in_split_axis","output_number - 1u",l.length)}; ${o.indicesSet("indices",a,"index")}; } writeBufferData(output_number, indices, global_idx); }`;return{name:"Split",shaderCache:{hint:t.cacheKey,inputDependencies:["rank"]},getShaderSource:h,getRunData:()=>({outputs:d,dispatchGroup:{x:Math.ceil(r/64)},programUniforms:f})}},D2=(e,t)=>{Y0(e.inputs);let n=e.inputs.length===1?t:Q0(e.inputs,t);e.compute(J0(e.inputs,n),{inputs:[0]})},N2=e=>{let t=e.axis,n=e.splitSizes,r=e.numOutputs<0?n.length:e.numOutputs;if(r!==n.length)throw new Error("numOutputs and splitSizes lengh must be equal");return tt({axis:t,numOutputs:r,splitSizes:n})}}),Ld,ey,ty,ny,L2,PE=ee(()=>{lt(),ze(),Oe(),Ld=e=>Array.from(e.getBigInt64Array(),Number),ey=e=>{if(!e||e.length!==2)throw new Error("Tile requires 2 inputs.");if(e[0].dataType!==1&&e[0].dataType!==6&&e[0].dataType!==12)throw new Error("Tile only support float, int32, and uint32 data types");if(e[1].dataType!==7)throw new Error("Tile `repeats` input should be of int64 data type");if(e[1].dims.length!==1)throw new Error("Tile `repeats` input should be 1-D");if(Ld(e[1]).length!==e[0].dims.length)throw new Error("Tile `repeats` input should have same number of elements as rank of input data tensor")},ty=(e,t)=>{let n=[];for(let r=0;r{let t=e[0].dims,n=Ld(e[1]),r=ty(t,n),i=ne.size(r),a=e[0].dataType,s=te("input",a,t.length),o=ke("output",a,r.length),l=d=>` const inputShape = ${s.indices(...t)}; ${d.registerUniform("output_size","u32").declareVariables(s,o)} ${d.mainStart()} ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let output_indices = ${o.offsetToIndices("global_idx")}; var input_indices: ${s.type.indices}; for (var i = 0; i < ${t.length}; i++) { let input_dim_i = ${s.indicesGet("uniforms.input_shape","i")}; let input_dim_value = ${o.indicesGet("output_indices","i")} % input_dim_i; ${s.indicesSet("input_indices","i","input_dim_value")} } ${o.setByOffset("global_idx",s.getByIndices("input_indices"))} }`;return{name:"Tile",shaderCache:{hint:`${n}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:[{type:"uint32",data:i},...le(e[0].dims),...le(r)]}),getShaderSource:l}},L2=e=>{ey(e.inputs),e.compute(ny(e.inputs),{inputs:[0]})}}),ry,iy,F2,BE=ee(()=>{lt(),ze(),Oe(),ry=(e,t,n,r,i)=>{let a=ke("output_data",i,n.length,4),s=te("a_data",t[1].dataType,t[1].dims.length,4),o=te("b_data",t[2].dataType,t[2].dims.length,4),l=te("c_data",t[0].dataType,t[0].dims.length,4),d,c=(u,f,h)=>`select(${f}, ${u}, ${h})`;if(!r)d=a.setByOffset("global_idx",c(s.getByOffset("global_idx"),o.getByOffset("global_idx"),l.getByOffset("global_idx")));else{let u=(f,h,g="")=>{let $=`a_data[index_a${h}][component_a${h}]`,E=`b_data[index_b${h}][component_b${h}]`,y=`bool(c_data[index_c${h}] & ${4278190080>>>(3-h)*8}u)`;return` let output_indices${h} = ${a.offsetToIndices(`global_idx * 4u + ${h}u`)}; let offset_a${h} = ${s.broadcastedIndicesToOffset(`output_indices${h}`,a)}; let offset_b${h} = ${o.broadcastedIndicesToOffset(`output_indices${h}`,a)}; let offset_c${h} = ${l.broadcastedIndicesToOffset(`output_indices${h}`,a)}; let index_a${h} = offset_a${h} / 4u; let index_b${h} = offset_b${h} / 4u; let index_c${h} = offset_c${h} / 4u; let component_a${h} = offset_a${h} % 4u; let component_b${h} = offset_b${h} % 4u; ${f}[${h}] = ${g}(${c($,E,y)}); `};i===9?d=` var data = vec4(0); ${u("data",0,"u32")} ${u("data",1,"u32")} ${u("data",2,"u32")} ${u("data",3,"u32")} output_data[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:d=` ${u("output_data[global_idx]",0)} ${u("output_data[global_idx]",1)} ${u("output_data[global_idx]",2)} ${u("output_data[global_idx]",3)} `}return` ${e.registerUniform("vec_size","u32").declareVariables(l,s,o,a)} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${d} }`},iy=e=>{let t=e[1].dims,n=e[2].dims,r=e[0].dims,i=e[1].dataType,a=!(ne.areEqual(t,n)&&ne.areEqual(n,r)),s=t,o=ne.size(t);if(a){let d=ca.calcShape(ca.calcShape(t,n,!1),r,!1);if(!d)throw new Error("Can't perform where op on the given tensors");s=d,o=ne.size(s)}let l=Math.ceil(o/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:d=>ry(d,e,s,a,i),getRunData:()=>({outputs:[{dims:s,dataType:i}],dispatchGroup:{x:Math.ceil(o/64/4)},programUniforms:[{type:"uint32",data:l},...le(r),...le(t),...le(n),...le(s)]})}},F2=e=>{e.compute(iy(e.inputs))}}),U2,DE=ee(()=>{oE(),n1(),lE(),uE(),dE(),cE(),pE(),e2(),yE(),wE(),_E(),vE(),$E(),bE(),xE(),SE(),EE(),J1(),kE(),CE(),TE(),IE(),gf(),AE(),OE(),ME(),zE(),RE(),PE(),qs(),B1(),BE(),U2=new Map([["Abs",[a1]],["Acos",[s1]],["Acosh",[o1]],["Add",[N1]],["ArgMax",[e1,jc]],["ArgMin",[Jv,jc]],["Asin",[l1]],["Asinh",[u1]],["Atan",[d1]],["Atanh",[c1]],["Attention",[t1]],["AveragePool",[$2,v2]],["BatchNormalization",[r1]],["BiasAdd",[i1]],["BiasSplitGelu",[D1]],["Cast",[f1,p1]],["Ceil",[m1]],["Clip",[h1]],["Concat",[K1,Y1]],["Conv",[Yc,Kc]],["ConvTranspose",[r2,n2]],["Cos",[g1]],["Cosh",[y1]],["CumSum",[i2,a2]],["Div",[L1]],["Einsum",[s2,o2]],["Elu",[w1,yl]],["Equal",[F1]],["Erf",[_1]],["Exp",[v1]],["Expand",[l2]],["Floor",[$1]],["FusedConv",[Yc,Kc]],["Gather",[d2,u2]],["GatherElements",[p2,c2]],["Gelu",[b1]],["Gemm",[h2,f2]],["GlobalAveragePool",[x2,b2]],["GlobalMaxPool",[C2,k2]],["Greater",[j1]],["GreaterOrEqual",[H1]],["InstanceNormalization",[m2]],["LayerNormalization",[g2]],["LeakyRelu",[x1,yl]],["Less",[G1]],["LessOrEqual",[q1]],["Log",[P1]],["MatMul",[Z1]],["MaxPool",[S2,E2]],["Mul",[U1]],["MultiHeadAttention",[w2,y2]],["Neg",[E1]],["Not",[S1]],["Pad",[_2]],["Pow",[W1]],["Range",[T2]],["Reciprocal",[k1]],["ReduceMin",[Kv]],["ReduceMean",[Vv]],["ReduceMax",[qv]],["ReduceSum",[Qv]],["ReduceProd",[Yv]],["ReduceL1",[jv]],["ReduceL2",[Gv]],["ReduceLogSum",[Zv]],["ReduceLogSumExp",[Hv]],["ReduceSumSquare",[Xv]],["Relu",[C1]],["Resize",[I2,A2]],["Sigmoid",[T1]],["Sin",[I1]],["Sinh",[A1]],["Slice",[z2,R2]],["SkipLayerNormalization",[O2,M2]],["Split",[D2,N2]],["Sqrt",[O1]],["Softmax",[P2,B2]],["Sub",[V1]],["Tan",[M1]],["Tanh",[z1]],["ThresholdedRelu",[R1,yl]],["Tile",[L2]],["Transpose",[Ov,Mv]],["Where",[F2]]])}),W2,NE=ee(()=>{Fn(),bi(),Oe(),W2=class{constructor(e){this.backend=e,this.repo=new Map,this.attributesBound=!1}getArtifact(e){return this.repo.get(e)}setArtifact(e,t){this.repo.set(e,t)}run(e,t,n,r,i){Nn(e.programInfo.name);let a=this.backend.device,s=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2),s.setPipeline(e.computePipeline);let o=[];for(let d of t)o.push({binding:o.length,resource:{buffer:d.buffer}});for(let d of n)o.push({binding:o.length,resource:{buffer:d.buffer}});i&&o.push({binding:o.length,resource:i});let l=a.createBindGroup({layout:e.computePipeline.getBindGroupLayout(0),entries:o,label:e.programInfo.name});s.setBindGroup(0,l),s.dispatchWorkgroups(...r),this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2+1),this.backend.pendingDispatchNumber++,(this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber||this.backend.queryType==="at-passes")&&this.backend.endComputePass(),this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber&&this.backend.flush(),Ln(e.programInfo.name)}dispose(){}build(e,t){Nn(e.name);let n=this.backend.device,r=[];n.features.has("shader-f16")&&r.push("enable f16;");let i=Av(t),a=e.getShaderSource(i),s=`${r.join(` `)} ${i.additionalImplementations} ${a}`,o=n.createShaderModule({code:s,label:e.name});$t("verbose",()=>`[WebGPU] ${e.name} shader code: ${s}`);let l=n.createComputePipeline({compute:{module:o,entryPoint:"main"},layout:"auto",label:e.name});return Ln(e.name),{programInfo:e,computePipeline:l}}normalizeDispatchGroupSize(e){let t=typeof e=="number"?e:e.x,n=typeof e=="number"?1:e.y||1,r=typeof e=="number"?1:e.z||1,i=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(t<=i&&n<=i&&r<=i)return[t,n,r];let a=t*n*r,s=Math.ceil(Math.sqrt(a));if(s>i){if(s=Math.ceil(Math.cbrt(a)),s>i)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[s,s,s]}else return[s,s,1]}}}),ay,sy,V2,LE=ee(()=>{Fn(),lt(),bi(),iE(),aE(),DE(),NE(),ay=(e,t)=>{if(t.length!==e.length)throw new Error(`inputDependencies length ${t.length} is not equal to inputTensors length ${e.length}.`);let n=[];for(let r=0;r{var i,a;let r=e.name;return(i=e.shaderCache)!=null&&i.hint&&(r+="["+e.shaderCache.hint+"]"),r+=":"+n+`:${ay(t,((a=e.shaderCache)==null?void 0:a.inputDependencies)??new Array(t.length).fill("dims"))}`,r},V2=class{constructor(){this.currentKernelId=null,this.commandEncoder=null,this.computePassEncoder=null,this.maxDispatchNumber=16,this.pendingDispatchNumber=0,this.pendingKernels=[],this.pendingQueries=new Map,this.sessionExternalDataMapping=new Map}get currentKernelCustomData(){if(this.currentKernelId===null)throw new Error("currentKernelCustomData(): currentKernelId is null. (should not happen)");let e=this.kernelCustomData.get(this.currentKernelId);return e||(e={},this.kernelCustomData.set(this.currentKernelId,e)),e}async initialize(e,t){this.env=e;let n=[],r={requiredLimits:{maxComputeWorkgroupStorageSize:t.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:t.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:t.limits.maxStorageBufferBindingSize,maxBufferSize:t.limits.maxBufferSize,maxComputeInvocationsPerWorkgroup:t.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupSizeX:t.limits.maxComputeWorkgroupSizeX,maxComputeWorkgroupSizeY:t.limits.maxComputeWorkgroupSizeY,maxComputeWorkgroupSizeZ:t.limits.maxComputeWorkgroupSizeZ},requiredFeatures:n};t.features.has("chromium-experimental-timestamp-query-inside-passes")?n.push("chromium-experimental-timestamp-query-inside-passes"):t.features.has("timestamp-query")&&n.push("timestamp-query"),t.features.has("shader-f16")&&n.push("shader-f16"),this.device=await t.requestDevice(r),this.gpuDataManager=Tv(this),this.programManager=new W2(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,kv(e.logLevel,!!e.debug),this.device.onuncapturederror=i=>{i.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${i.error.message}`)},Object.defineProperty(this.env.webgpu,"device",{value:this.device}),this.setQueryType()}dispose(){typeof this.querySet<"u"&&this.querySet.destroy(),this.gpuDataManager.dispose()}getCommandEncoder(){return this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder(),this.setQueryType(),this.queryType!=="none"&&typeof this.querySet>"u"&&(this.querySet=this.device.createQuerySet({type:"timestamp",count:this.maxDispatchNumber*2}),this.queryResolveBuffer=this.device.createBuffer({size:this.maxDispatchNumber*2*8,usage:GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE}))),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let e={};this.queryType==="at-passes"&&(e.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=this.getCommandEncoder().beginComputePass(e)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;Nn(),this.endComputePass();let e;this.queryType!=="none"&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),e=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(e,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,e,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!=="none"&&e.mapAsync(GPUMapMode.READ).then(()=>{var r;let t=new BigUint64Array(e.getMappedRange()),n=this.pendingQueries.get(e);for(let i=0;i"u"&&(this.queryTimeBase=h);let $=Number(h-this.queryTimeBase),E=Number(g-this.queryTimeBase);if(!Number.isSafeInteger($)||!Number.isSafeInteger(E))throw new RangeError("incorrect timestamp range");if((r=this.env.webgpu.profiling)!=null&&r.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:u.map(y=>({dims:y.dims,dataType:Kn(y.dataType)})),outputsMetadata:f.map(y=>({dims:y.dims,dataType:Kn(y.dataType)})),kernelId:s,kernelType:l,kernelName:d,programName:c,startTime:$,endTime:E});else{let y="";u.forEach((v,b)=>{y+=`input[${b}]: [${v.dims}] | ${Kn(v.dataType)}, `});let _="";f.forEach((v,b)=>{_+=`output[${b}]: [${v.dims}] | ${Kn(v.dataType)}, `}),console.log(`[profiling] kernel "${s}|${l}|${d}|${c}" ${y}${_}execution time: ${E-$} ns`)}Ds("GPU",`${c}::${h}::${g}`)}e.unmap(),this.pendingQueries.delete(e)}),Ln()}run(e,t,n,r,i){Nn(e.name);let a=[];for(let y=0;y_):n;if(d.length!==s.length)throw new Error(`Output size ${d.length} must be equal to ${s.length}.`);let c=[],u=[];for(let y=0;y=s.length)throw new Error(`Invalid output index: ${d[y]}`);if(d[y]===-3)continue;let _=d[y]===-1,v=d[y]===-2,b=_||v?i(s[y].dataType,s[y].dims):r(d[y],s[y].dataType,s[y].dims),C=this.gpuDataManager.get(b.data);if(!C)throw new Error(`no GPU data for output: ${b.data}`);if(_&&this.temporaryData.push(C),v){let I=this.kernelPersistentData.get(this.currentKernelId);I||(I=[],this.kernelPersistentData.set(this.currentKernelId,I)),I.push(C)}c.push(b),u.push(C)}let f;if(l){let y=0,_=[];l.forEach(I=>{let O=typeof I.data=="number"?[I.data]:I.data;if(O.length===0)return;let M=O.length<=2?O.length*4:16;y=Math.ceil(y/M)*M,_.push(y),y+=O.length>4?Math.ceil(O.length/4)*16:O.length*4});let v=16;y=Math.ceil(y/v)*v;let b=new ArrayBuffer(y);l.forEach((I,O)=>{let M=_[O],W=typeof I.data=="number"?[I.data]:I.data;I.type==="int32"?new Int32Array(b,M,W.length).set(W):I.type==="uint32"?new Uint32Array(b,M,W.length).set(W):new Float32Array(b,M,W.length).set(W)});let C=this.gpuDataManager.create(y,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(C.buffer,0,b,0,y),this.gpuDataManager.release(C.id),f={offset:0,size:y,buffer:C.buffer}}let h=this.programManager.normalizeDispatchGroupSize(o),g=h[1]===1&&h[2]===1,$=sy(e,t,g),E=this.programManager.getArtifact($);if(E||(E=this.programManager.build(e,h),this.programManager.setArtifact($,E),$t("info",()=>`[artifact] key: ${$}, programName: ${e.name}`)),$t("info",()=>`[ProgramManager] run "${e.name}" (key=${$}) with ${h[0]}x${h[1]}x${h[2]}`),this.queryType!=="none"){let y={kernelId:this.currentKernelId,programName:E.programInfo.name,inputTensorViews:t,outputTensorViews:c};this.pendingKernels.push(y)}return this.programManager.run(E,a,u,h,f),Ln(e.name),c}upload(e,t){this.gpuDataManager.upload(e,t)}memcpy(e,t){this.gpuDataManager.memcpy(e,t)}async download(e,t){await this.gpuDataManager.download(e,t)}alloc(e){return this.gpuDataManager.create(e).id}free(e){return this.gpuDataManager.release(e)}createKernel(e,t,n,r){let i=U2.get(e);if(!i)throw new Error(`kernel not implemented: ${e}`);let a={kernelType:e,kernelName:r,kernelEntry:i[0],attributes:[i[1],n]};this.kernels.set(t,a)}releaseKernel(e){let t=this.kernelPersistentData.get(e);if(t){for(let n of t)this.gpuDataManager.release(n.id);this.kernelPersistentData.delete(e)}this.kernelCustomData.delete(e),this.kernels.delete(e)}computeKernel(e,t,n){let r=this.kernels.get(e);if(!r)throw new Error(`kernel not created: ${e}`);let i=r.kernelType,a=r.kernelName,s=r.kernelEntry,o=r.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${i}] ${a}" is not allowed to be called recursively`);this.currentKernelId=e,o[0]&&(o[1]=o[0](o[1]),o[0]=void 0),$t("info",()=>`[WebGPU] Start to run kernel "[${i}] ${a}"...`);let l=this.env.debug;this.temporaryData=[];try{return l&&this.device.pushErrorScope("validation"),s(t,o[1]),0}catch(d){return n.push(Promise.resolve(`[WebGPU] Kernel "[${i}] ${a}" failed. ${d}`)),1}finally{l&&n.push(this.device.popErrorScope().then(d=>d?`GPU validation error for kernel "[${i}] ${a}": ${d.message}`:null));for(let d of this.temporaryData)this.gpuDataManager.release(d.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(e,t,n,r){let i=this.sessionExternalDataMapping.get(e);i||(i=new Map,this.sessionExternalDataMapping.set(e,i));let a=i.get(t),s=this.gpuDataManager.registerExternalBuffer(n,r,a==null?void 0:a[1]);return i.set(t,[s,n]),s}unregisterBuffers(e){let t=this.sessionExternalDataMapping.get(e);t&&(t.forEach(n=>this.gpuDataManager.unregisterExternalBuffer(n[1])),this.sessionExternalDataMapping.delete(e))}getBuffer(e){let t=this.gpuDataManager.get(e);if(!t)throw new Error(`no GPU data for buffer: ${e}`);return t.buffer}createDownloader(e,t,n){return async()=>{let r=await Wc(this,e,t);return Cv(r.buffer,n)}}writeTimestamp(e){this.queryType==="inside-passes"&&this.computePassEncoder.writeTimestamp(this.querySet,e)}setQueryType(){var e;this.queryType="none",(((e=this.env.webgpu.profiling)==null?void 0:e.mode)==="default"||this.env.wasm.trace)&&(this.device.features.has("chromium-experimental-timestamp-query-inside-passes")?this.queryType="inside-passes":this.device.features.has("timestamp-query")&&(this.queryType="at-passes"))}}}),j2={};ga(j2,{init:()=>G2});var Xo,oy,G2,FE=ee(()=>{lt(),LE(),bi(),ze(),Xo=class H2{constructor(t,n,r,i){this.module=t,this.dataType=n,this.data=r,this.dims=i}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let t=ne.size(this.dims);return t===0?new Float32Array:new Float32Array(this.module.HEAP8.buffer,this.data,t)}getBigInt64Array(){if(this.dataType!==7)throw new Error("Invalid data type");let t=ne.size(this.dims);return t===0?new BigInt64Array:new BigInt64Array(this.module.HEAP8.buffer,this.data,t)}getInt32Array(){if(this.dataType!==6)throw new Error("Invalid data type");let t=ne.size(this.dims);return t===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,t)}reshape(t){if(ne.size(t)!==ne.size(this.dims))throw new Error("Invalid new shape");return new H2(this.module,this.dataType,this.data,t)}},oy=class{constructor(e,t,n){this.module=e,this.backend=t,this.customDataOffset=0,this.customDataSize=0;let r=e.HEAPU32,i=n>>>2;this.opKernelContext=r[i++];let a=r[i++];this.outputCount=r[i++],this.customDataOffset=r[i++],this.customDataSize=r[i++];let s=[];for(let o=0;otypeof o=="number"?this.inputs[o]:o))??this.inputs,r=(t==null?void 0:t.outputs)??[],i=(o,l,d)=>new Xo(this.module,l,this.output(o,d),d),a=(o,l)=>{let d=ql(o);if(!d)throw new Error(`Unsupported data type: ${o}`);let c=d*ne.size(l);return new Xo(this.module,o,this.backend.gpuDataManager.create(c).id,l)};return this.backend.run(e,n,r,i,a)}output(e,t){let n=this.module.stackSave();try{let r=this.module.stackAlloc((1+t.length)*4),i=r>>2;this.module.HEAPU32[i++]=t.length;for(let a=0;a{let r=e.jsepInit;if(!r)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");let i=new V2;await i.initialize(t,n),r(i,a=>i.alloc(a),a=>i.free(a),(a,s,o,l=!1)=>{if(l)$t("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${a}, dst=${s}, size=${o}`),i.memcpy(a,s);else{$t("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${a}, gpuDataId=${s}, size=${o}`);let d=e.HEAPU8.subarray(a>>>0,(a>>>0)+o);i.upload(s,d)}},async(a,s,o)=>{$t("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${a}, dataOffset=${s}, size=${o}`),await i.download(a,()=>e.HEAPU8.subarray(s>>>0,(s>>>0)+o))},(a,s,o)=>i.createKernel(a,s,o,e.UTF8ToString(e._JsepGetNodeName(s))),a=>i.releaseKernel(a),(a,s,o,l)=>{$t("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${o}, kernel=${a}, contextDataOffset=${s}`);let d=new oy(e,i,s);return i.computeKernel(a,d,l)})}}),ly,q2,K2,Ri,uy,Xc,Y2,Q2,Fd,X2,Z2,J2,UE=ee(()=>{nE(),rE(),lt(),Hs(),uf(),Ev(),ly=(e,t)=>{gt()._OrtInit(e,t)!==0&&Je("Can't initialize onnxruntime.")},q2=async e=>{ly(e.wasm.numThreads,Kl(e.logLevel))},K2=async(e,t)=>{if(t==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");let n=await navigator.gpu.requestAdapter();if(!n)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.');if(!e.wasm.simd)throw new Error("Not supported for WebGPU=ON and SIMD=OFF. Please set `env.wasm.simd` to true when using `webgpu` EP");let r=(FE(),fi(j2)).init;await r(gt(),e,n)}},Ri=new Map,uy=e=>{let t=gt(),n=t.stackSave();try{let r=t.stackAlloc(8);return t._OrtGetInputOutputCount(e,r,r+4)!==0&&Je("Can't get session input/output count."),[t.HEAP32[r/4],t.HEAP32[r/4+1]]}finally{t.stackRestore(n)}},Xc=e=>{let t=gt(),n=t._malloc(e.byteLength);if(n===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,n),[n,e.byteLength]},Y2=async(e,t)=>{var u,f;let n,r,i=gt();Array.isArray(e)?[n,r]=e:e.buffer===i.HEAPU8.buffer?[n,r]=[e.byteOffset,e.byteLength]:[n,r]=Xc(e);let a=0,s=0,o=0,l=[],d=[],c=[];try{if([s,l]=Sv(t),(t==null?void 0:t.externalData)&&i.mountExternalData){let v=[];for(let b of t.externalData){let C=typeof b=="string"?b:b.path;v.push(Yl(typeof b=="string"?b:b.data).then(I=>{i.mountExternalData(C,I)}))}await Promise.all(v)}a=i._OrtCreateSession(n,r,s),a===0&&Je("Can't create a session.");let[h,g]=uy(a),$=[],E=[],y=[];for(let v=0;vv==="gpu-buffer")&&(o=i._OrtCreateBinding(a),o===0&&Je("Can't create IO binding."),_={handle:o,outputPreferredLocations:y,outputPreferredLocationsEncoded:y.map(v=>Uc(v))}),Ri.set(a,[a,d,c,_]),[a,$,E]}catch(h){throw d.forEach(g=>i._OrtFree(g)),c.forEach(g=>i._OrtFree(g)),o!==0&&i._OrtReleaseBinding(o),a!==0&&i._OrtReleaseSession(a),h}finally{i._free(n),s!==0&&i._OrtReleaseSessionOptions(s),l.forEach(h=>i._free(h)),(f=i.unmountExternalData)==null||f.call(i)}},Q2=e=>{var o;let t=gt(),n=Ri.get(e);if(!n)throw new Error(`cannot release session. invalid session id: ${e}`);let[r,i,a,s]=n;s&&t._OrtReleaseBinding(s.handle),(o=t.jsepUnregisterBuffers)==null||o.call(t,e),i.forEach(l=>t._OrtFree(l)),a.forEach(l=>t._OrtFree(l)),t._OrtReleaseSession(r),Ri.delete(e)},Fd=(e,t,n,r,i)=>{if(!e){t.push(0);return}let a=gt(),s=e[0],o=e[1],l=e[3],d,c;if(s==="string"&&l==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");if(l==="gpu-buffer"){let h=e[2].gpuBuffer,g=ql(Fc(s));c=o.reduce(($,E)=>$*E,1)*g,d=a.jsepRegisterBuffer(r,i,h,c)}else{let h=e[2];if(Array.isArray(h)){c=4*h.length,d=a._malloc(c),n.push(d);let g=d/4;for(let $=0;$a.HEAP32[h++]=$);let g=a._OrtCreateTensor(Fc(s),d,c,f,o.length,Uc(l));g===0&&Je(`Can't create tensor for input/output. session=${r}, index=${i}.`),t.push(g)}finally{a.stackRestore(u)}},X2=async(e,t,n,r,i,a)=>{var M;let s=gt(),o=Ri.get(e);if(!o)throw new Error(`cannot run inference. invalid session id: ${e}`);let[l,d,c,u]=o,f=t.length,h=r.length,g=0,$=[],E=[],y=[],_=[],v=s.stackSave(),b=s.stackAlloc(f*4),C=s.stackAlloc(f*4),I=s.stackAlloc(h*4),O=s.stackAlloc(h*4);try{[g,$]=xv(a);for(let R=0;Rht*at,1);Z=Kn(xe);let er=u==null?void 0:u.outputPreferredLocations[r[R]];if(Z==="string"){if(er==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");let ht=[],at=V/4;for(let Qt=0;Qt0){let ht=s.jsepGetBuffer(V),at=ql(xe);if(at===void 0||!cf(Z))throw new Error(`Unsupported data type: ${Z}`);X=!0,ue.push([Z,qe,{gpuBuffer:ht,download:s.jsepCreateDownloader(ht,Dt*at,Z),dispose:()=>{s._OrtReleaseTensor(H)}},"gpu-buffer"])}else{let ht=df(Z),at=new ht(Dt);new Uint8Array(at.buffer,at.byteOffset,at.byteLength).set(s.HEAPU8.subarray(V,V+at.byteLength)),ue.push([Z,qe,at,"cpu"])}}finally{s.stackRestore(re),Z==="string"&&V&&s._free(V),X||s._OrtReleaseTensor(H)}}return u&&s._OrtClearBoundOutputs(u.handle),ue}finally{s.stackRestore(v),E.forEach(W=>s._OrtReleaseTensor(W)),y.forEach(W=>s._OrtReleaseTensor(W)),_.forEach(W=>s._free(W)),g!==0&&s._OrtReleaseRunOptions(g),$.forEach(W=>s._free(W))}},Z2=e=>{let t=gt(),n=Ri.get(e);if(!n)throw new Error("invalid session id");let r=n[0],i=t._OrtEndProfiling(r);i===0&&Je("Can't get an profile file name."),t._OrtFree(i)},J2=e=>{let t=[];for(let n of e){let r=n[2];!Array.isArray(r)&&"buffer"in r&&t.push(r.buffer)}return t}}),WE=ma((e,t)=>{t.exports='/*!\n * ONNX Runtime Web v1.17.1\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n"use strict";(()=>{var hn=Object.defineProperty;var Lu=Object.getOwnPropertyDescriptor;var Fu=Object.getOwnPropertyNames;var ju=Object.prototype.hasOwnProperty;var j=(e,t)=>()=>(e&&(t=e(e=0)),t);var dr=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Br=(e,t)=>{for(var r in t)hn(e,r,{get:t[r],enumerable:!0})},qu=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Fu(t))!ju.call(e,n)&&n!==r&&hn(e,n,{get:()=>t[n],enumerable:!(o=Lu(t,n))||o.enumerable});return e};var Ht=e=>qu(hn({},"__esModule",{value:!0}),e);var gn={};Br(gn,{createReadStream:()=>xo,readFile:()=>Ku,readFileSync:()=>Yu});var Ku,Yu,xo,yn=j(()=>{Ku=void 0,Yu=void 0,xo=void 0});var bn={};Br(bn,{join:()=>Zu});var Zu,wn=j(()=>{Zu=void 0});var Io=dr((Co,vn)=>{"use strict";var _o=(()=>{var e=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename<"u"&&(e=e||__filename),function(t={}){var r=t,o,n;r.ready=new Promise((d,m)=>{o=d,n=m}),r.mountExternalData=(d,m)=>{(r.Fa||(r.Fa=new Map)).set(d,m)},r.unmountExternalData=()=>{delete r.Fa},r.jsepInit=(d,m,v,C,B,H,q,le)=>{r.ab=d,r.Qa=m,r.Sa=v,r.La=C,r.Ra=B,r.sa=H,r.Ta=q,r.Ua=le,m=(J,re,se)=>(...we)=>{let _e=tt,P=re?.();we=J(...we);let ue=re?.();return P!==ue&&(J=ue,se(P),re=se=null),tt!=_e?xr():we},v=J=>async(...re)=>{try{if(r.Ea)throw Error("Session already started");let se=r.Ea={Va:re[0],errors:[]},we=await J(...re);if(r.Ea!==se)throw Error("Session mismatch");d.flush();let _e=se.errors;if(0<_e.length){let P=await Promise.all(_e);if(P=P.filter(ue=>ue),0r._OrtRun,J=>r._OrtRun=J)),r._OrtRunWithBinding=v(m(r._OrtRunWithBinding,()=>r._OrtRunWithBinding,J=>r._OrtRunWithBinding=J)),r._OrtBindInput=m(r._OrtBindInput,()=>r._OrtBindInput,J=>r._OrtBindInput=J),r.jsepRegisterBuffer=(J,re,se,we)=>d.registerBuffer(J,re,se,we),r.jsepUnregisterBuffers=J=>{d.unregisterBuffers(J)},r.jsepGetBuffer=J=>d.getBuffer(J),r.jsepCreateDownloader=(J,re,se)=>d.createDownloader(J,re,se)};var s=Object.assign({},r),u="./this.program",l=(d,m)=>{throw m},a=typeof window=="object",p=typeof importScripts=="function",h=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",g="",b,w,y;if(h){var _=(yn(),Ht(gn)),I=(wn(),Ht(bn));g=p?I.dirname(g)+"/":__dirname+"/",b=(d,m)=>(d=We(d)?new URL(d):I.normalize(d),_.readFileSync(d,m?void 0:"utf8")),y=d=>(d=b(d,!0),d.buffer||(d=new Uint8Array(d)),d),w=(d,m,v,C=!0)=>{d=We(d)?new URL(d):I.normalize(d),_.readFile(d,C?void 0:"utf8",(B,H)=>{B?v(B):m(C?H.buffer:H)})},!r.thisProgram&&1{throw process.exitCode=d,m},r.inspect=()=>"[Emscripten Module object]"}else(a||p)&&(p?g=self.location.href:typeof document<"u"&&document.currentScript&&(g=document.currentScript.src),e&&(g=e),g.indexOf("blob:")!==0?g=g.substr(0,g.replace(/[?#].*/,"").lastIndexOf("/")+1):g="",b=d=>{var m=new XMLHttpRequest;return m.open("GET",d,!1),m.send(null),m.responseText},p&&(y=d=>{var m=new XMLHttpRequest;return m.open("GET",d,!1),m.responseType="arraybuffer",m.send(null),new Uint8Array(m.response)}),w=(d,m,v)=>{var C=new XMLHttpRequest;C.open("GET",d,!0),C.responseType="arraybuffer",C.onload=()=>{C.status==200||C.status==0&&C.response?m(C.response):v()},C.onerror=v,C.send(null)});var $=console.log.bind(console),x=console.error.bind(console);Object.assign(r,s),s=null,typeof WebAssembly!="object"&&he("no native wasm support detected");var E,A=!1,z,R,V,T,N,te,Y;function K(){var d=E.buffer;r.HEAP8=R=new Int8Array(d),r.HEAP16=new Int16Array(d),r.HEAPU8=V=new Uint8Array(d),r.HEAPU16=new Uint16Array(d),r.HEAP32=T=new Int32Array(d),r.HEAPU32=N=new Uint32Array(d),r.HEAPF32=te=new Float32Array(d),r.HEAPF64=Y=new Float64Array(d)}var Q=[],Z=[],Ee=[],Pe=0,fe=null,Ie=null;function he(d){throw d="Aborted("+d+")",x(d),A=!0,z=1,d=new WebAssembly.RuntimeError(d+". Build with -sASSERTIONS for more info."),n(d),d}var ye=d=>d.startsWith("data:application/octet-stream;base64,"),We=d=>d.startsWith("file://"),De;if(De="ort-wasm-simd.wasm",!ye(De)){var Ge=De;De=r.locateFile?r.locateFile(Ge,g):g+Ge}function G(d){if(y)return y(d);throw"both async and sync fetching of the wasm failed"}function ee(d){if(a||p){if(typeof fetch=="function"&&!We(d))return fetch(d,{credentials:"same-origin"}).then(m=>{if(!m.ok)throw"failed to load wasm binary file at \'"+d+"\'";return m.arrayBuffer()}).catch(()=>G(d));if(w)return new Promise((m,v)=>{w(d,C=>m(new Uint8Array(C)),v)})}return Promise.resolve().then(()=>G(d))}function be(d,m,v){return ee(d).then(C=>WebAssembly.instantiate(C,m)).then(C=>C).then(v,C=>{x(`failed to asynchronously prepare wasm: ${C}`),he(C)})}function et(d,m){var v=De;return typeof WebAssembly.instantiateStreaming!="function"||ye(v)||We(v)||h||typeof fetch!="function"?be(v,d,m):fetch(v,{credentials:"same-origin"}).then(C=>WebAssembly.instantiateStreaming(C,d).then(m,function(B){return x(`wasm streaming compile failed: ${B}`),x("falling back to ArrayBuffer instantiation"),be(v,d,m)}))}var ze,Ue={931056:(d,m,v,C)=>{if(typeof r>"u"||!r.Fa)return 1;if(d=qe(d>>>0),d.startsWith("./")&&(d=d.substring(2)),d=r.Fa.get(d),!d)return 2;if(m>>>=0,v>>>=0,m+v>d.byteLength)return 3;try{return V.set(d.subarray(m,m+v),C>>>0>>>0),0}catch{return 4}},931557:d=>r.Qa(d),931590:d=>r.Sa(d),931622:(d,m,v)=>{r.La(d,m,v,!0)},931661:(d,m,v)=>{r.La(d,m,v)},931694:d=>{r.sa("Abs",d,void 0)},931745:d=>{r.sa("Neg",d,void 0)},931796:d=>{r.sa("Floor",d,void 0)},931849:d=>{r.sa("Ceil",d,void 0)},931901:d=>{r.sa("Reciprocal",d,void 0)},931959:d=>{r.sa("Sqrt",d,void 0)},932011:d=>{r.sa("Exp",d,void 0)},932062:d=>{r.sa("Erf",d,void 0)},932113:d=>{r.sa("Sigmoid",d,void 0)},932168:d=>{r.sa("Log",d,void 0)},932219:d=>{r.sa("Sin",d,void 0)},932270:d=>{r.sa("Cos",d,void 0)},932321:d=>{r.sa("Tan",d,void 0)},932372:d=>{r.sa("Asin",d,void 0)},932424:d=>{r.sa("Acos",d,void 0)},932476:d=>{r.sa("Atan",d,void 0)},932528:d=>{r.sa("Sinh",d,void 0)},932580:d=>{r.sa("Cosh",d,void 0)},932632:d=>{r.sa("Asinh",d,void 0)},932685:d=>{r.sa("Acosh",d,void 0)},932738:d=>{r.sa("Atanh",d,void 0)},932791:d=>{r.sa("Tanh",d,void 0)},932843:d=>{r.sa("Not",d,void 0)},932894:(d,m,v)=>{r.sa("Clip",d,{min:m,max:v})},932963:d=>{r.sa("Clip",d,void 0)},933015:(d,m)=>{r.sa("Elu",d,{alpha:m})},933073:d=>{r.sa("Relu",d,void 0)},933125:(d,m)=>{r.sa("LeakyRelu",d,{alpha:m})},933189:(d,m)=>{r.sa("ThresholdedRelu",d,{alpha:m})},933259:(d,m)=>{r.sa("Cast",d,{to:m})},933317:d=>{r.sa("Add",d,void 0)},933368:d=>{r.sa("Sub",d,void 0)},933419:d=>{r.sa("Mul",d,void 0)},933470:d=>{r.sa("Div",d,void 0)},933521:d=>{r.sa("Pow",d,void 0)},933572:d=>{r.sa("Equal",d,void 0)},933625:d=>{r.sa("Greater",d,void 0)},933680:d=>{r.sa("GreaterOrEqual",d,void 0)},933742:d=>{r.sa("Less",d,void 0)},933794:d=>{r.sa("LessOrEqual",d,void 0)},933853:(d,m,v,C,B)=>{r.sa("ReduceMean",d,{keepDims:!!m,noopWithEmptyAxes:!!v,axes:C?Array.from(T.subarray(C>>>0,B>>>0)):[]})},934012:(d,m,v,C,B)=>{r.sa("ReduceMax",d,{keepDims:!!m,noopWithEmptyAxes:!!v,axes:C?Array.from(T.subarray(C>>>0,B>>>0)):[]})},934170:(d,m,v,C,B)=>{r.sa("ReduceMin",d,{keepDims:!!m,noopWithEmptyAxes:!!v,axes:C?Array.from(T.subarray(C>>>0,B>>>0)):[]})},934328:(d,m,v,C,B)=>{r.sa("ReduceProd",d,{keepDims:!!m,noopWithEmptyAxes:!!v,axes:C?Array.from(T.subarray(C>>>0,B>>>0)):[]})},934487:(d,m,v,C,B)=>{r.sa("ReduceSum",d,{keepDims:!!m,noopWithEmptyAxes:!!v,axes:C?Array.from(T.subarray(C>>>0,B>>>0)):[]})},934645:(d,m,v,C,B)=>{r.sa("ReduceL1",d,{keepDims:!!m,noopWithEmptyAxes:!!v,axes:C?Array.from(T.subarray(C>>>0,B>>>0)):[]})},934802:(d,m,v,C,B)=>{r.sa("ReduceL2",d,{keepDims:!!m,noopWithEmptyAxes:!!v,axes:C?Array.from(T.subarray(C>>>0,B>>>0)):[]})},934959:(d,m,v,C,B)=>{r.sa("ReduceLogSum",d,{keepDims:!!m,noopWithEmptyAxes:!!v,axes:C?Array.from(T.subarray(C>>>0,B>>>0)):[]})},935120:(d,m,v,C,B)=>{r.sa("ReduceSumSquare",d,{keepDims:!!m,noopWithEmptyAxes:!!v,axes:C?Array.from(T.subarray(C>>>0,B>>>0)):[]})},935284:(d,m,v,C,B)=>{r.sa("ReduceLogSumExp",d,{keepDims:!!m,noopWithEmptyAxes:!!v,axes:C?Array.from(T.subarray(C>>>0,B>>>0)):[]})},935448:d=>{r.sa("Where",d,void 0)},935501:(d,m,v)=>{r.sa("Transpose",d,{perm:m?Array.from(T.subarray(m>>>0,v>>>0)):[]})},935609:(d,m,v,C,B,H,q,le,J,re,se,we,_e,P,ue)=>{r.sa("ConvTranspose",d,{format:J?"NHWC":"NCHW",autoPad:m,dilations:[v],group:C,kernel_shape:[B],pads:[H,q],strides:[le],wIsConst:()=>!!R[re>>>0],outputPadding:se?Array.from(T.subarray(se>>>0,we>>>0)):[],outputShape:_e?Array.from(T.subarray(_e>>>0,P>>>0)):[],activation:qe(ue)})},936011:(d,m,v,C,B,H,q,le,J,re,se,we,_e,P)=>{r.sa("ConvTranspose",d,{format:le?"NHWC":"NCHW",autoPad:m,dilations:Array.from(T.subarray(v>>>0,(v>>>0)+2>>>0)),group:C,kernelShape:Array.from(T.subarray(B>>>0,(B>>>0)+2>>>0)),pads:Array.from(T.subarray(H>>>0,(H>>>0)+4>>>0)),strides:Array.from(T.subarray(q>>>0,(q>>>0)+2>>>0)),wIsConst:()=>!!R[J>>>0],outputPadding:re?Array.from(T.subarray(re>>>0,se>>>0)):[],outputShape:we?Array.from(T.subarray(we>>>0,_e>>>0)):[],activation:qe(P)})},936576:(d,m,v,C,B,H,q,le,J,re,se,we,_e,P,ue)=>{r.sa("ConvTranspose",d,{format:J?"NHWC":"NCHW",autoPad:m,dilations:[v],group:C,kernel_shape:[B],pads:[H,q],strides:[le],wIsConst:()=>!!R[re>>>0],outputPadding:se?Array.from(T.subarray(se>>>0,we>>>0)):[],outputShape:_e?Array.from(T.subarray(_e>>>0,P>>>0)):[],activation:qe(ue)})},936978:(d,m,v,C,B,H,q,le,J,re,se,we,_e,P)=>{r.sa("ConvTranspose",d,{format:le?"NHWC":"NCHW",autoPad:m,dilations:Array.from(T.subarray(v>>>0,(v>>>0)+2>>>0)),group:C,kernelShape:Array.from(T.subarray(B>>>0,(B>>>0)+2>>>0)),pads:Array.from(T.subarray(H>>>0,(H>>>0)+4>>>0)),strides:Array.from(T.subarray(q>>>0,(q>>>0)+2>>>0)),wIsConst:()=>!!R[J>>>0],outputPadding:re?Array.from(T.subarray(re>>>0,se>>>0)):[],outputShape:we?Array.from(T.subarray(we>>>0,_e>>>0)):[],activation:qe(P)})},937543:(d,m)=>{r.sa("GlobalAveragePool",d,{format:m?"NHWC":"NCHW"})},937634:(d,m,v,C,B,H,q,le,J,re,se,we,_e,P,ue,Se)=>{r.sa("AveragePool",d,{format:Se?"NHWC":"NCHW",auto_pad:m,ceil_mode:v,count_include_pad:C,storage_order:B,dilations:[H,q],kernel_shape:[le,J],pads:[re,se,we,_e],strides:[P,ue]})},937918:(d,m)=>{r.sa("GlobalAveragePool",d,{format:m?"NHWC":"NCHW"})},938009:(d,m,v,C,B,H,q,le,J,re,se,we,_e,P,ue,Se)=>{r.sa("AveragePool",d,{format:Se?"NHWC":"NCHW",auto_pad:m,ceil_mode:v,count_include_pad:C,storage_order:B,dilations:[H,q],kernel_shape:[le,J],pads:[re,se,we,_e],strides:[P,ue]})},938293:(d,m)=>{r.sa("GlobalMaxPool",d,{format:m?"NHWC":"NCHW"})},938380:(d,m,v,C,B,H,q,le,J,re,se,we,_e,P,ue,Se)=>{r.sa("MaxPool",d,{format:Se?"NHWC":"NCHW",auto_pad:m,ceil_mode:v,count_include_pad:C,storage_order:B,dilations:[H,q],kernel_shape:[le,J],pads:[re,se,we,_e],strides:[P,ue]})},938660:(d,m)=>{r.sa("GlobalMaxPool",d,{format:m?"NHWC":"NCHW"})},938747:(d,m,v,C,B,H,q,le,J,re,se,we,_e,P,ue,Se)=>{r.sa("MaxPool",d,{format:Se?"NHWC":"NCHW",auto_pad:m,ceil_mode:v,count_include_pad:C,storage_order:B,dilations:[H,q],kernel_shape:[le,J],pads:[re,se,we,_e],strides:[P,ue]})},939027:(d,m,v,C,B)=>{r.sa("Gemm",d,{alpha:m,beta:v,transA:C,transB:B})},939131:d=>{r.sa("MatMul",d,void 0)},939185:(d,m,v,C)=>{r.sa("ArgMax",d,{keepDims:!!m,selectLastIndex:!!v,axis:C})},939293:(d,m,v,C)=>{r.sa("ArgMin",d,{keepDims:!!m,selectLastIndex:!!v,axis:C})},939401:(d,m)=>{r.sa("Softmax",d,{axis:m})},939464:(d,m)=>{r.sa("Concat",d,{axis:m})},939524:(d,m,v,C,B)=>{r.sa("Split",d,{axis:m,numOutputs:v,splitSizes:C?Array.from(T.subarray(C>>>0,B>>>0)):[]})},939664:d=>{r.sa("Expand",d,void 0)},939718:(d,m)=>{r.sa("Gather",d,{axis:Number(m)})},939789:(d,m)=>{r.sa("GatherElements",d,{axis:Number(m)})},939868:(d,m,v,C,B,H,q,le,J,re,se)=>{r.sa("Resize",d,{antialias:m,axes:v?Array.from(T.subarray(v>>>0,C>>>0)):[],coordinateTransformMode:qe(B),cubicCoeffA:H,excludeOutside:q,extrapolationValue:le,keepAspectRatioPolicy:qe(J),mode:qe(re),nearestMode:qe(se)})},940214:(d,m,v,C,B,H,q)=>{r.sa("Slice",d,{starts:m?Array.from(T.subarray(m>>>0,v>>>0)):[],ends:C?Array.from(T.subarray(C>>>0,B>>>0)):[],axes:H?Array.from(T.subarray(H>>>0,q>>>0)):[]})},940430:d=>{r.sa("Tile",d,void 0)},940482:(d,m,v)=>{r.sa("LayerNormalization",d,{axis:Number(m),epsilon:Number(v)})},940589:(d,m,v)=>{r.sa("InstanceNormalization",d,{epsilon:m,format:v?"NHWC":"NCHW"})},940703:(d,m,v)=>{r.sa("InstanceNormalization",d,{epsilon:m,format:v?"NHWC":"NCHW"})},940817:d=>{r.sa("Range",d,void 0)},940870:(d,m)=>{r.sa("Einsum",d,{equation:qe(m)})},940951:(d,m,v,C,B)=>{r.sa("Pad",d,{mode:m,value:v,pads:C?Array.from(T.subarray(C>>>0,B>>>0)):[]})},941078:(d,m,v,C,B,H)=>{r.sa("BatchNormalization",d,{epsilon:m,momentum:v,spatial:!!B,trainingMode:!!C,format:H?"NHWC":"NCHW"})},941247:(d,m,v,C,B,H)=>{r.sa("BatchNormalization",d,{epsilon:m,momentum:v,spatial:!!B,trainingMode:!!C,format:H?"NHWC":"NCHW"})},941416:(d,m,v)=>{r.sa("CumSum",d,{exclusive:Number(m),reverse:Number(v)})},941513:(d,m,v,C,B,H,q,le,J)=>{r.sa("Attention",d,{numHeads:m,isUnidirectional:v,maskFilterValue:C,scale:B,doRotary:H,qkvHiddenSizes:q?Array.from(T.subarray(Number(le)>>>0,Number(le)+q>>>0)):[],pastPresentShareBuffer:!!J})},941785:d=>{r.sa("Gelu",d,void 0)},941837:(d,m,v,C,B,H)=>{r.sa("MultiHeadAttention",d,{numHeads:m,isUnidirectional:v,maskFilterValue:C,scale:B,doRotary:H})},941996:d=>{r.sa("BiasAdd",d,void 0)},942051:d=>{r.sa("BiasSplitGelu",d,void 0)},942112:(d,m)=>{r.sa("SkipLayerNormalization",d,{epsilon:m})},942193:(d,m,v,C,B,H,q,le,J,re,se,we,_e)=>{r.sa("Conv",d,{format:J?"NHWC":"NCHW",auto_pad:m,dilations:[v],group:C,kernel_shape:[B],pads:H?Array.from(T.subarray(H>>>0,q>>>0)):[],strides:[le],w_is_const:()=>!!R[re>>>0],activation:qe(se),activation_params:we?Array.from(te.subarray(we>>>0,_e>>>0)):[]})},942563:(d,m,v,C,B,H,q,le,J,re,se,we,_e,P,ue,Se)=>{r.sa("Conv",d,{format:we?"NHWC":"NCHW",auto_pad:m,dilations:[v,C],group:B,kernel_shape:[H,q],pads:le?Array.from(T.subarray(le>>>0,J>>>0)):[],strides:[re,se],w_is_const:()=>!!R[_e>>>0],activation:qe(P),activation_params:ue?Array.from(te.subarray(ue>>>0,Se>>>0)):[]})},942954:d=>{r.Ta(d)},942988:(d,m)=>r.Ua(d,m,r.Ea.Va,r.Ea.errors)};function Me(d){this.name="ExitStatus",this.message=`Program terminated with exit(${d})`,this.status=d}function wt(d){this.Ja=d-24,this.Oa=function(m){N[this.Ja+4>>>2>>>0]=m},this.Na=function(m){N[this.Ja+8>>>2>>>0]=m},this.$a=function(m,v){this.Ma(),this.Oa(m),this.Na(v)},this.Ma=function(){N[this.Ja+16>>>2>>>0]=0}}var rt=0,Dt=0,At=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,vt=(d,m,v)=>{m>>>=0;var C=m+v;for(v=m;d[v]&&!(v>=C);)++v;if(16B?C+=String.fromCharCode(B):(B-=65536,C+=String.fromCharCode(55296|B>>10,56320|B&1023))}}else C+=String.fromCharCode(B)}return C},qe=(d,m)=>(d>>>=0)?vt(V,d,m):"",qt=d=>{for(var m=0,v=0;v=C?m++:2047>=C?m+=2:55296<=C&&57343>=C?(m+=4,++v):m+=3}return m},Mt=(d,m,v,C)=>{if(v>>>=0,!(0=q){var le=d.charCodeAt(++H);q=65536+((q&1023)<<10)|le&1023}if(127>=q){if(v>=C)break;m[v++>>>0]=q}else{if(2047>=q){if(v+1>=C)break;m[v++>>>0]=192|q>>6}else{if(65535>=q){if(v+2>=C)break;m[v++>>>0]=224|q>>12}else{if(v+3>=C)break;m[v++>>>0]=240|q>>18,m[v++>>>0]=128|q>>12&63}m[v++>>>0]=128|q>>6&63}m[v++>>>0]=128|q&63}}return m[v>>>0]=0,v-B},$t=d=>d%4===0&&(d%100!==0||d%400===0),yt=[0,31,60,91,121,152,182,213,244,274,305,335],zt=[0,31,59,90,120,151,181,212,243,273,304,334],Ut=d=>{var m=qt(d)+1,v=Wt(m);return v&&Mt(d,V,v,m),v},Tt=[],Kt=(d,m)=>{Tt.length=0;for(var v;v=V[d++>>>0];){var C=v!=105;C&=v!=112,m+=C&&m%8?4:0,Tt.push(v==112?N[m>>>2>>>0]:v==105?T[m>>>2>>>0]:Y[m>>>3>>>0]),m+=C?8:4}return Tt},nt={},Yt=()=>{if(!Vt){var d={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:u||"./this.program"},m;for(m in nt)nt[m]===void 0?delete d[m]:d[m]=nt[m];var v=[];for(m in d)v.push(`${m}=${d[m]}`);Vt=v}return Vt},Vt,Ye=[null,[],[]],br=[31,29,31,30,31,30,31,31,30,31,30,31],Oe=[31,28,31,30,31,30,31,31,30,31,30,31];function wr(d){var m=Array(qt(d)+1);return Mt(d,m,0,m.length),m}function Nt(d,m,v,C){function B(P,ue,Se){for(P=typeof P=="number"?P.toString():P||"";P.lengthTr?-1:0st-P.getDate())ue-=st-P.getDate()+1,P.setDate(1),11>Se?P.setMonth(Se+1):(P.setMonth(0),P.setFullYear(P.getFullYear()+1));else{P.setDate(P.getDate()+ue);break}}return Se=new Date(P.getFullYear()+1,0,4),ue=le(new Date(P.getFullYear(),0,4)),Se=le(Se),0>=q(ue,P)?0>=q(Se,P)?P.getFullYear()+1:P.getFullYear():P.getFullYear()-1}d>>>=0,m>>>=0,v>>>=0,C>>>=0;var re=N[C+40>>>2>>>0];C={Ya:T[C>>>2>>>0],Xa:T[C+4>>>2>>>0],Ga:T[C+8>>>2>>>0],Ka:T[C+12>>>2>>>0],Ha:T[C+16>>>2>>>0],Da:T[C+20>>>2>>>0],xa:T[C+24>>>2>>>0],Ca:T[C+28>>>2>>>0],bb:T[C+32>>>2>>>0],Wa:T[C+36>>>2>>>0],Za:re?qe(re):""},v=qe(v),re={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"};for(var se in re)v=v.replace(new RegExp(se,"g"),re[se]);var we="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),_e="January February March April May June July August September October November December".split(" ");re={"%a":P=>we[P.xa].substring(0,3),"%A":P=>we[P.xa],"%b":P=>_e[P.Ha].substring(0,3),"%B":P=>_e[P.Ha],"%C":P=>H((P.Da+1900)/100|0,2),"%d":P=>H(P.Ka,2),"%e":P=>B(P.Ka,2," "),"%g":P=>J(P).toString().substring(2),"%G":P=>J(P),"%H":P=>H(P.Ga,2),"%I":P=>(P=P.Ga,P==0?P=12:12{for(var ue=0,Se=0;Se<=P.Ha-1;ue+=($t(P.Da+1900)?br:Oe)[Se++]);return H(P.Ka+ue,3)},"%m":P=>H(P.Ha+1,2),"%M":P=>H(P.Xa,2),"%n":()=>`\n`,"%p":P=>0<=P.Ga&&12>P.Ga?"AM":"PM","%S":P=>H(P.Ya,2),"%t":()=>" ","%u":P=>P.xa||7,"%U":P=>H(Math.floor((P.Ca+7-P.xa)/7),2),"%V":P=>{var ue=Math.floor((P.Ca+7-(P.xa+6)%7)/7);if(2>=(P.xa+371-P.Ca-2)%7&&ue++,ue)ue==53&&(Se=(P.xa+371-P.Ca)%7,Se==4||Se==3&&$t(P.Da)||(ue=1));else{ue=52;var Se=(P.xa+7-P.Ca-1)%7;(Se==4||Se==5&&$t(P.Da%400-1))&&ue++}return H(ue,2)},"%w":P=>P.xa,"%W":P=>H(Math.floor((P.Ca+7-(P.xa+6)%7)/7),2),"%y":P=>(P.Da+1900).toString().substring(2),"%Y":P=>P.Da+1900,"%z":P=>{P=P.Wa;var ue=0<=P;return P=Math.abs(P)/60,(ue?"+":"-")+("0000"+(P/60*100+P%60)).slice(-4)},"%Z":P=>P.Za,"%%":()=>"%"},v=v.replace(/%%/g,"\\0\\0");for(se in re)v.includes(se)&&(v=v.replace(new RegExp(se,"g"),re[se](C)));return v=v.replace(/\\0\\0/g,"%"),se=wr(v),se.length>m?0:(R.set(se,d>>>0),se.length-1)}var St=d=>{try{d()}catch(m){he(m)}};function un(){var d=ae,m={};for(let[v,C]of Object.entries(d))m[v]=typeof C=="function"?function(){bt.push(v);try{return C.apply(null,arguments)}finally{A||(bt.pop(),tt&&ot===1&&bt.length===0&&(ot=0,St(ir),typeof Fibers<"u"&&Fibers.cb()))}}:C;return m}var ot=0,tt=null,de=0,bt=[],Zt={},vr={},$r=0,Qt=null,Sr=[];function xr(){return new Promise((d,m)=>{Qt={resolve:d,reject:m}})}function _r(){var d=Wt(65548),m=d+12;N[d>>>2>>>0]=m,N[d+4>>>2>>>0]=m+65536,m=bt[0];var v=Zt[m];return v===void 0&&(v=$r++,Zt[m]=v,vr[v]=m),T[d+8>>>2>>>0]=v,d}function Cr(d){if(!A){if(ot===0){var m=!1,v=!1;d((C=0)=>{if(!A&&(de=C,m=!0,v)){ot=2,St(()=>sr(tt)),typeof Browser<"u"&&Browser.Ia.Pa&&Browser.Ia.resume(),C=!1;try{var B=(0,ae[vr[T[tt+8>>>2>>>0]]])()}catch(le){B=le,C=!0}var H=!1;if(!tt){var q=Qt;q&&(Qt=null,(C?q.reject:q.resolve)(B),H=!0)}if(C&&!H)throw B}}),v=!0,m||(ot=1,tt=_r(),typeof Browser<"u"&&Browser.Ia.Pa&&Browser.Ia.pause(),St(()=>ar(tt)))}else ot===2?(ot=0,St(ur),er(tt),tt=null,Sr.forEach(C=>{if(!A)try{C();try{z=z=C=z,r.onExit?.(C),A=!0,l(C,new Me(C))}catch(B){B instanceof Me||B=="unwind"||l(1,B)}}catch(B){B instanceof Me||B=="unwind"||l(1,B)}})):he(`invalid state: ${ot}`);return de}}function Xt(d){return Cr(m=>{d().then(m)})}var Ir={n:function(d,m,v){return Xt(async()=>{await r.Ra(d,m,v)})},a:function(d,m,v){throw d>>>=0,new wt(d).$a(m>>>0,v>>>0),rt=d,Dt++,rt},g:function(){return 0},J:function(){},A:function(){},C:function(){},L:function(){return 0},H:function(){},D:function(){},G:function(){},l:function(){},B:function(){},y:function(){},I:function(){},z:function(){},m:()=>1,q:function(d,m,v){d=m+2097152>>>0<4194305-!!d?(d>>>0)+4294967296*m:NaN,v>>>=0,d=new Date(1e3*d),T[v>>>2>>>0]=d.getUTCSeconds(),T[v+4>>>2>>>0]=d.getUTCMinutes(),T[v+8>>>2>>>0]=d.getUTCHours(),T[v+12>>>2>>>0]=d.getUTCDate(),T[v+16>>>2>>>0]=d.getUTCMonth(),T[v+20>>>2>>>0]=d.getUTCFullYear()-1900,T[v+24>>>2>>>0]=d.getUTCDay(),T[v+28>>>2>>>0]=(d.getTime()-Date.UTC(d.getUTCFullYear(),0,1,0,0,0,0))/864e5|0},r:function(d,m,v){d=m+2097152>>>0<4194305-!!d?(d>>>0)+4294967296*m:NaN,v>>>=0,d=new Date(1e3*d),T[v>>>2>>>0]=d.getSeconds(),T[v+4>>>2>>>0]=d.getMinutes(),T[v+8>>>2>>>0]=d.getHours(),T[v+12>>>2>>>0]=d.getDate(),T[v+16>>>2>>>0]=d.getMonth(),T[v+20>>>2>>>0]=d.getFullYear()-1900,T[v+24>>>2>>>0]=d.getDay(),T[v+28>>>2>>>0]=($t(d.getFullYear())?yt:zt)[d.getMonth()]+d.getDate()-1|0,T[v+36>>>2>>>0]=-(60*d.getTimezoneOffset()),m=new Date(d.getFullYear(),6,1).getTimezoneOffset();var C=new Date(d.getFullYear(),0,1).getTimezoneOffset();T[v+32>>>2>>>0]=(m!=C&&d.getTimezoneOffset()==Math.min(C,m))|0},s:function(d){d>>>=0;var m=new Date(T[d+20>>>2>>>0]+1900,T[d+16>>>2>>>0],T[d+12>>>2>>>0],T[d+8>>>2>>>0],T[d+4>>>2>>>0],T[d>>>2>>>0],0),v=T[d+32>>>2>>>0],C=m.getTimezoneOffset(),B=new Date(m.getFullYear(),6,1).getTimezoneOffset(),H=new Date(m.getFullYear(),0,1).getTimezoneOffset(),q=Math.min(H,B);return 0>v?T[d+32>>>2>>>0]=+(B!=H&&q==C):0>>2>>>0]=m.getDay(),T[d+28>>>2>>>0]=($t(m.getFullYear())?yt:zt)[m.getMonth()]+m.getDate()-1|0,T[d>>>2>>>0]=m.getSeconds(),T[d+4>>>2>>>0]=m.getMinutes(),T[d+8>>>2>>>0]=m.getHours(),T[d+12>>>2>>>0]=m.getDate(),T[d+16>>>2>>>0]=m.getMonth(),T[d+20>>>2>>>0]=m.getYear(),d=m.getTime(),isNaN(d)?(T[Jt()>>>2>>>0]=61,d=-1):d/=1e3,tr((ze=d,1<=+Math.abs(ze)?0>>0:~~+Math.ceil((ze-+(~~ze>>>0))/4294967296)>>>0:0)),d>>>0},o:function(){return-52},p:function(){},w:function(d,m,v){function C(J){return(J=J.toTimeString().match(/\\(([A-Za-z ]+)\\)$/))?J[1]:"GMT"}v>>>=0;var B=new Date().getFullYear(),H=new Date(B,0,1),q=new Date(B,6,1);B=H.getTimezoneOffset();var le=q.getTimezoneOffset();N[d>>>0>>>2>>>0]=60*Math.max(B,le),T[m>>>0>>>2>>>0]=+(B!=le),d=C(H),m=C(q),d=Ut(d),m=Ut(m),le>>2>>>0]=d,N[v+4>>>2>>>0]=m):(N[v>>>2>>>0]=m,N[v+4>>>2>>>0]=d)},e:()=>{he("")},b:function(d,m,v){return d>>>=0,m=Kt(m>>>0,v>>>0),Ue[d].apply(null,m)},i:function(d,m,v){return d>>>=0,m=Kt(m>>>0,v>>>0),Ue[d].apply(null,m)},h:()=>Date.now(),x:function(){return 4294901760},c:()=>performance.now(),K:function(d,m,v){return m>>>=0,V.copyWithin(d>>>0>>>0,m>>>0,m+(v>>>0)>>>0)},u:function(d){d>>>=0;var m=V.length;if(4294901760=v;v*=2){var C=m*(1+.2/v);C=Math.min(C,d+100663296);var B=Math;C=Math.max(d,C);e:{B=(B.min.call(B,4294901760,C+(65536-C%65536)%65536)-E.buffer.byteLength+65535)/65536;try{E.grow(B),K();var H=1;break e}catch{}H=void 0}if(H)return!0}return!1},E:function(d,m){d>>>=0,m>>>=0;var v=0;return Yt().forEach((C,B)=>{var H=m+v;for(B=N[d+4*B>>>2>>>0]=H,H=0;H>>0>>>0]=C.charCodeAt(H);R[B>>>0>>>0]=0,v+=C.length+1}),0},F:function(d,m){d>>>=0,m>>>=0;var v=Yt();N[d>>>2>>>0]=v.length;var C=0;return v.forEach(B=>C+=B.length+1),N[m>>>2>>>0]=C,0},f:()=>52,k:function(){return 52},t:function(){return 70},j:function(d,m,v,C){m>>>=0,v>>>=0,C>>>=0;for(var B=0,H=0;H>>2>>>0],le=N[m+4>>>2>>>0];m+=8;for(var J=0;J>>0],se=Ye[d];re===0||re===10?((d===1?$:x)(vt(se,0)),se.length=0):se.push(re)}B+=le}return N[C>>>2>>>0]=B,0},v:Nt,d:function(d,m,v,C){return Nt(d>>>0,m>>>0,v>>>0,C>>>0)}},ae=function(){function d(v){return ae=v.exports,ae=un(),ae=Ar(),E=ae.M,K(),Z.unshift(ae.N),Pe--,Pe==0&&(fe!==null&&(clearInterval(fe),fe=null),Ie&&(v=Ie,Ie=null,v())),ae}var m={a:Ir};if(Pe++,r.instantiateWasm)try{return r.instantiateWasm(m,d)}catch(v){x(`Module.instantiateWasm callback failed with error: ${v}`),n(v)}return et(m,function(v){d(v.instance)}).catch(n),{}}();r._OrtInit=(d,m)=>(r._OrtInit=ae.O)(d,m),r._OrtGetLastError=(d,m)=>(r._OrtGetLastError=ae.P)(d,m),r._OrtCreateSessionOptions=(d,m,v,C,B,H,q,le,J,re)=>(r._OrtCreateSessionOptions=ae.Q)(d,m,v,C,B,H,q,le,J,re),r._OrtAppendExecutionProvider=(d,m)=>(r._OrtAppendExecutionProvider=ae.R)(d,m),r._OrtAddFreeDimensionOverride=(d,m,v)=>(r._OrtAddFreeDimensionOverride=ae.S)(d,m,v),r._OrtAddSessionConfigEntry=(d,m,v)=>(r._OrtAddSessionConfigEntry=ae.T)(d,m,v),r._OrtReleaseSessionOptions=d=>(r._OrtReleaseSessionOptions=ae.U)(d),r._OrtCreateSession=(d,m,v)=>(r._OrtCreateSession=ae.V)(d,m,v),r._OrtReleaseSession=d=>(r._OrtReleaseSession=ae.W)(d),r._OrtGetInputOutputCount=(d,m,v)=>(r._OrtGetInputOutputCount=ae.X)(d,m,v),r._OrtGetInputName=(d,m)=>(r._OrtGetInputName=ae.Y)(d,m),r._OrtGetOutputName=(d,m)=>(r._OrtGetOutputName=ae.Z)(d,m),r._OrtFree=d=>(r._OrtFree=ae._)(d),r._OrtCreateTensor=(d,m,v,C,B,H)=>(r._OrtCreateTensor=ae.$)(d,m,v,C,B,H),r._OrtGetTensorData=(d,m,v,C,B)=>(r._OrtGetTensorData=ae.aa)(d,m,v,C,B),r._OrtReleaseTensor=d=>(r._OrtReleaseTensor=ae.ba)(d),r._OrtCreateRunOptions=(d,m,v,C)=>(r._OrtCreateRunOptions=ae.ca)(d,m,v,C),r._OrtAddRunConfigEntry=(d,m,v)=>(r._OrtAddRunConfigEntry=ae.da)(d,m,v),r._OrtReleaseRunOptions=d=>(r._OrtReleaseRunOptions=ae.ea)(d),r._OrtCreateBinding=d=>(r._OrtCreateBinding=ae.fa)(d),r._OrtBindInput=(d,m,v)=>(r._OrtBindInput=ae.ga)(d,m,v),r._OrtBindOutput=(d,m,v,C)=>(r._OrtBindOutput=ae.ha)(d,m,v,C),r._OrtClearBoundOutputs=d=>(r._OrtClearBoundOutputs=ae.ia)(d),r._OrtReleaseBinding=d=>(r._OrtReleaseBinding=ae.ja)(d),r._OrtRunWithBinding=(d,m,v,C,B)=>(r._OrtRunWithBinding=ae.ka)(d,m,v,C,B),r._OrtRun=(d,m,v,C,B,H,q,le)=>(r._OrtRun=ae.la)(d,m,v,C,B,H,q,le),r._OrtEndProfiling=d=>(r._OrtEndProfiling=ae.ma)(d),r._JsepOutput=(d,m,v)=>(r._JsepOutput=ae.na)(d,m,v),r._JsepGetNodeName=d=>(r._JsepGetNodeName=ae.oa)(d);var Jt=()=>(Jt=ae.pa)(),Wt=r._malloc=d=>(Wt=r._malloc=ae.qa)(d),er=r._free=d=>(er=r._free=ae.ra)(d),tr=d=>(tr=ae.ta)(d),rr=()=>(rr=ae.ua)(),nr=d=>(nr=ae.va)(d),or=d=>(or=ae.wa)(d),ar=d=>(ar=ae.ya)(d),ir=()=>(ir=ae.za)(),sr=d=>(sr=ae.Aa)(d),ur=()=>(ur=ae.Ba)();r.___start_em_js=943100,r.___stop_em_js=943261;function Ar(){var d=ae;d=Object.assign({},d);var m=C=>()=>C()>>>0,v=C=>B=>C(B)>>>0;return d.pa=m(d.pa),d.qa=v(d.qa),d.ua=m(d.ua),d.wa=v(d.wa),d}r.stackAlloc=or,r.stackSave=rr,r.stackRestore=nr,r.UTF8ToString=qe,r.stringToUTF8=(d,m,v)=>Mt(d,V,m,v),r.lengthBytesUTF8=qt;var xt;Ie=function d(){xt||Et(),xt||(Ie=d)};function Et(){if(!(0_o)});var Ao=dr(()=>{});var To=dr(()=>{});var Eo={};Br(Eo,{cpus:()=>Qu});var Qu,Oo=j(()=>{Qu=void 0});var Ro=dr((ko,$n)=>{"use strict";var Po=(()=>{var e=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename<"u"&&(e=e||__filename),function(t={}){function r(){return Q.buffer!=fe.buffer&&Ge(),fe}function o(){return Q.buffer!=fe.buffer&&Ge(),Ie}function n(){return Q.buffer!=fe.buffer&&Ge(),he}function s(){return Q.buffer!=fe.buffer&&Ge(),ye}function u(){return Q.buffer!=fe.buffer&&Ge(),We}function l(){return Q.buffer!=fe.buffer&&Ge(),De}var a=t,p,h;a.ready=new Promise((i,c)=>{p=i,h=c}),a.mountExternalData=(i,c)=>{(a.cb||(a.cb=new Map)).set(i,c)},a.unmountExternalData=()=>{delete a.cb},a.jsepInit=(i,c,f,S,O,D,W,ie)=>{a.Mb=i,a.wb=c,a.yb=f,a.kb=S,a.xb=O,a.Ea=D,a.zb=W,a.Ab=ie,c=(ne,oe,pe)=>(...xe)=>{let Te=ut,k=oe?.();xe=ne(...xe);let me=oe?.();return k!==me&&(ne=me,pe(k),oe=pe=null),ut!=Te?Mu():xe},f=ne=>async(...oe)=>{try{if(a.bb)throw Error("Session already started");let pe=a.bb={Cb:oe[0],errors:[]},xe=await ne(...oe);if(a.bb!==pe)throw Error("Session mismatch");i.flush();let Te=pe.errors;if(0me),0a._OrtRun,ne=>a._OrtRun=ne)),a._OrtRunWithBinding=f(c(a._OrtRunWithBinding,()=>a._OrtRunWithBinding,ne=>a._OrtRunWithBinding=ne)),a._OrtBindInput=c(a._OrtBindInput,()=>a._OrtBindInput,ne=>a._OrtBindInput=ne),a.jsepRegisterBuffer=(ne,oe,pe,xe)=>i.registerBuffer(ne,oe,pe,xe),a.jsepUnregisterBuffers=ne=>{i.unregisterBuffers(ne)},a.jsepGetBuffer=ne=>i.getBuffer(ne),a.jsepCreateDownloader=(ne,oe,pe)=>i.createDownloader(ne,oe,pe)};var g=Object.assign({},a),b="./this.program",w=(i,c)=>{throw c},y=typeof window=="object",_=typeof importScripts=="function",I=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",$=a.ENVIRONMENT_IS_PTHREAD||!1,x="";function E(i){return a.locateFile?a.locateFile(i,x):x+i}var A,z,R;if(I){var V=(yn(),Ht(gn)),T=(wn(),Ht(bn));x=_?T.dirname(x)+"/":__dirname+"/",A=(c,f)=>(c=At(c)?new URL(c):T.normalize(c),V.readFileSync(c,f?void 0:"utf8")),R=c=>(c=A(c,!0),c.buffer||(c=new Uint8Array(c)),c),z=(c,f,S,O=!0)=>{c=At(c)?new URL(c):T.normalize(c),V.readFile(c,O?void 0:"utf8",(D,W)=>{D?S(D):f(O?W.buffer:W)})},!a.thisProgram&&1{throw process.exitCode=c,f},a.inspect=()=>"[Emscripten Module object]";let i;try{i=Ao()}catch(c){throw console.error(\'The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?\'),c}global.Worker=i.Worker}else(y||_)&&(_?x=self.location.href:typeof document<"u"&&document.currentScript&&(x=document.currentScript.src),typeof e<"u"&&e&&(x=e),x.indexOf("blob:")!==0?x=x.substr(0,x.replace(/[?#].*/,"").lastIndexOf("/")+1):x="",I||(A=i=>{var c=new XMLHttpRequest;return c.open("GET",i,!1),c.send(null),c.responseText},_&&(R=i=>{var c=new XMLHttpRequest;return c.open("GET",i,!1),c.responseType="arraybuffer",c.send(null),new Uint8Array(c.response)}),z=(i,c,f)=>{var S=new XMLHttpRequest;S.open("GET",i,!0),S.responseType="arraybuffer",S.onload=()=>{S.status==200||S.status==0&&S.response?c(S.response):f()},S.onerror=f,S.send(null)}));I&&typeof performance>"u"&&(global.performance=To().performance);var N=console.log.bind(console),te=console.error.bind(console);I&&(N=(...i)=>V.writeSync(1,i.join(" ")+`\n`),te=(...i)=>V.writeSync(2,i.join(" ")+`\n`));var Y=N,K=te;Object.assign(a,g),g=null,typeof WebAssembly!="object"&&rt("no native wasm support detected");var Q,Z,Ee=!1,Pe,fe,Ie,he,ye,We,De;function Ge(){var i=Q.buffer;a.HEAP8=fe=new Int8Array(i),a.HEAP16=new Int16Array(i),a.HEAPU8=Ie=new Uint8Array(i),a.HEAPU16=new Uint16Array(i),a.HEAP32=he=new Int32Array(i),a.HEAPU32=ye=new Uint32Array(i),a.HEAPF32=We=new Float32Array(i),a.HEAPF64=De=new Float64Array(i)}var G=16777216;if($)Q=a.wasmMemory;else if(a.wasmMemory)Q=a.wasmMemory;else if(Q=new WebAssembly.Memory({initial:G/65536,maximum:65536,shared:!0}),!(Q.buffer instanceof SharedArrayBuffer))throw K("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"),I&&K("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and/or recent version)"),Error("bad memory");Ge(),G=Q.buffer.byteLength;var ee=[],be=[],et=[],ze=0,Ue=null,Me=null;function wt(){if(ze--,ze==0&&(Ue!==null&&(clearInterval(Ue),Ue=null),Me)){var i=Me;Me=null,i()}}function rt(i){throw i="Aborted("+i+")",K(i),Ee=!0,Pe=1,i=new WebAssembly.RuntimeError(i+". Build with -sASSERTIONS for more info."),h(i),i}var Dt=i=>i.startsWith("data:application/octet-stream;base64,"),At=i=>i.startsWith("file://"),vt;vt="ort-wasm-simd-threaded.wasm",Dt(vt)||(vt=E(vt));function qe(i){if(R)return R(i);throw"both async and sync fetching of the wasm failed"}function qt(i){if(y||_){if(typeof fetch=="function"&&!At(i))return fetch(i,{credentials:"same-origin"}).then(c=>{if(!c.ok)throw"failed to load wasm binary file at \'"+i+"\'";return c.arrayBuffer()}).catch(()=>qe(i));if(z)return new Promise((c,f)=>{z(i,S=>c(new Uint8Array(S)),f)})}return Promise.resolve().then(()=>qe(i))}function Mt(i,c,f){return qt(i).then(S=>WebAssembly.instantiate(S,c)).then(S=>S).then(f,S=>{K(`failed to asynchronously prepare wasm: ${S}`),rt(S)})}function $t(i,c){var f=vt;return typeof WebAssembly.instantiateStreaming!="function"||Dt(f)||At(f)||I||typeof fetch!="function"?Mt(f,i,c):fetch(f,{credentials:"same-origin"}).then(S=>WebAssembly.instantiateStreaming(S,i).then(c,function(O){return K(`wasm streaming compile failed: ${O}`),K("falling back to ArrayBuffer instantiation"),Mt(f,i,c)}))}var yt,zt={932428:(i,c,f,S)=>{if(typeof a>"u"||!a.cb)return 1;if(i=Ye(i>>>0),i.startsWith("./")&&(i=i.substring(2)),i=a.cb.get(i),!i)return 2;if(c>>>=0,f>>>=0,S>>>=0,c+f>i.byteLength)return 3;try{return o().set(i.subarray(c,c+f),S>>>0),0}catch{return 4}},932929:i=>a.wb(i),932962:i=>a.yb(i),932994:(i,c,f)=>{a.kb(i,c,f,!0)},933033:(i,c,f)=>{a.kb(i,c,f)},933066:i=>{a.Ea("Abs",i,void 0)},933117:i=>{a.Ea("Neg",i,void 0)},933168:i=>{a.Ea("Floor",i,void 0)},933221:i=>{a.Ea("Ceil",i,void 0)},933273:i=>{a.Ea("Reciprocal",i,void 0)},933331:i=>{a.Ea("Sqrt",i,void 0)},933383:i=>{a.Ea("Exp",i,void 0)},933434:i=>{a.Ea("Erf",i,void 0)},933485:i=>{a.Ea("Sigmoid",i,void 0)},933540:i=>{a.Ea("Log",i,void 0)},933591:i=>{a.Ea("Sin",i,void 0)},933642:i=>{a.Ea("Cos",i,void 0)},933693:i=>{a.Ea("Tan",i,void 0)},933744:i=>{a.Ea("Asin",i,void 0)},933796:i=>{a.Ea("Acos",i,void 0)},933848:i=>{a.Ea("Atan",i,void 0)},933900:i=>{a.Ea("Sinh",i,void 0)},933952:i=>{a.Ea("Cosh",i,void 0)},934004:i=>{a.Ea("Asinh",i,void 0)},934057:i=>{a.Ea("Acosh",i,void 0)},934110:i=>{a.Ea("Atanh",i,void 0)},934163:i=>{a.Ea("Tanh",i,void 0)},934215:i=>{a.Ea("Not",i,void 0)},934266:(i,c,f)=>{a.Ea("Clip",i,{min:c,max:f})},934335:i=>{a.Ea("Clip",i,void 0)},934387:(i,c)=>{a.Ea("Elu",i,{alpha:c})},934445:i=>{a.Ea("Relu",i,void 0)},934497:(i,c)=>{a.Ea("LeakyRelu",i,{alpha:c})},934561:(i,c)=>{a.Ea("ThresholdedRelu",i,{alpha:c})},934631:(i,c)=>{a.Ea("Cast",i,{to:c})},934689:i=>{a.Ea("Add",i,void 0)},934740:i=>{a.Ea("Sub",i,void 0)},934791:i=>{a.Ea("Mul",i,void 0)},934842:i=>{a.Ea("Div",i,void 0)},934893:i=>{a.Ea("Pow",i,void 0)},934944:i=>{a.Ea("Equal",i,void 0)},934997:i=>{a.Ea("Greater",i,void 0)},935052:i=>{a.Ea("GreaterOrEqual",i,void 0)},935114:i=>{a.Ea("Less",i,void 0)},935166:i=>{a.Ea("LessOrEqual",i,void 0)},935225:(i,c,f,S,O)=>{a.Ea("ReduceMean",i,{keepDims:!!c,noopWithEmptyAxes:!!f,axes:S?Array.from(n().subarray(S>>>0,O>>>0)):[]})},935384:(i,c,f,S,O)=>{a.Ea("ReduceMax",i,{keepDims:!!c,noopWithEmptyAxes:!!f,axes:S?Array.from(n().subarray(S>>>0,O>>>0)):[]})},935542:(i,c,f,S,O)=>{a.Ea("ReduceMin",i,{keepDims:!!c,noopWithEmptyAxes:!!f,axes:S?Array.from(n().subarray(S>>>0,O>>>0)):[]})},935700:(i,c,f,S,O)=>{a.Ea("ReduceProd",i,{keepDims:!!c,noopWithEmptyAxes:!!f,axes:S?Array.from(n().subarray(S>>>0,O>>>0)):[]})},935859:(i,c,f,S,O)=>{a.Ea("ReduceSum",i,{keepDims:!!c,noopWithEmptyAxes:!!f,axes:S?Array.from(n().subarray(S>>>0,O>>>0)):[]})},936017:(i,c,f,S,O)=>{a.Ea("ReduceL1",i,{keepDims:!!c,noopWithEmptyAxes:!!f,axes:S?Array.from(n().subarray(S>>>0,O>>>0)):[]})},936174:(i,c,f,S,O)=>{a.Ea("ReduceL2",i,{keepDims:!!c,noopWithEmptyAxes:!!f,axes:S?Array.from(n().subarray(S>>>0,O>>>0)):[]})},936331:(i,c,f,S,O)=>{a.Ea("ReduceLogSum",i,{keepDims:!!c,noopWithEmptyAxes:!!f,axes:S?Array.from(n().subarray(S>>>0,O>>>0)):[]})},936492:(i,c,f,S,O)=>{a.Ea("ReduceSumSquare",i,{keepDims:!!c,noopWithEmptyAxes:!!f,axes:S?Array.from(n().subarray(S>>>0,O>>>0)):[]})},936656:(i,c,f,S,O)=>{a.Ea("ReduceLogSumExp",i,{keepDims:!!c,noopWithEmptyAxes:!!f,axes:S?Array.from(n().subarray(S>>>0,O>>>0)):[]})},936820:i=>{a.Ea("Where",i,void 0)},936873:(i,c,f)=>{a.Ea("Transpose",i,{perm:c?Array.from(n().subarray(c>>>0,f>>>0)):[]})},936981:(i,c,f,S,O,D,W,ie,ne,oe,pe,xe,Te,k,me)=>{a.Ea("ConvTranspose",i,{format:ne?"NHWC":"NCHW",autoPad:c,dilations:[f],group:S,kernel_shape:[O],pads:[D,W],strides:[ie],wIsConst:()=>!!r()[oe>>>0],outputPadding:pe?Array.from(n().subarray(pe>>>0,xe>>>0)):[],outputShape:Te?Array.from(n().subarray(Te>>>0,k>>>0)):[],activation:Ye(me)})},937383:(i,c,f,S,O,D,W,ie,ne,oe,pe,xe,Te,k)=>{a.Ea("ConvTranspose",i,{format:ie?"NHWC":"NCHW",autoPad:c,dilations:Array.from(n().subarray(f>>>0,(f>>>0)+2>>>0)),group:S,kernelShape:Array.from(n().subarray(O>>>0,(O>>>0)+2>>>0)),pads:Array.from(n().subarray(D>>>0,(D>>>0)+4>>>0)),strides:Array.from(n().subarray(W>>>0,(W>>>0)+2>>>0)),wIsConst:()=>!!r()[ne>>>0],outputPadding:oe?Array.from(n().subarray(oe>>>0,pe>>>0)):[],outputShape:xe?Array.from(n().subarray(xe>>>0,Te>>>0)):[],activation:Ye(k)})},937948:(i,c,f,S,O,D,W,ie,ne,oe,pe,xe,Te,k,me)=>{a.Ea("ConvTranspose",i,{format:ne?"NHWC":"NCHW",autoPad:c,dilations:[f],group:S,kernel_shape:[O],pads:[D,W],strides:[ie],wIsConst:()=>!!r()[oe>>>0],outputPadding:pe?Array.from(n().subarray(pe>>>0,xe>>>0)):[],outputShape:Te?Array.from(n().subarray(Te>>>0,k>>>0)):[],activation:Ye(me)})},938350:(i,c,f,S,O,D,W,ie,ne,oe,pe,xe,Te,k)=>{a.Ea("ConvTranspose",i,{format:ie?"NHWC":"NCHW",autoPad:c,dilations:Array.from(n().subarray(f>>>0,(f>>>0)+2>>>0)),group:S,kernelShape:Array.from(n().subarray(O>>>0,(O>>>0)+2>>>0)),pads:Array.from(n().subarray(D>>>0,(D>>>0)+4>>>0)),strides:Array.from(n().subarray(W>>>0,(W>>>0)+2>>>0)),wIsConst:()=>!!r()[ne>>>0],outputPadding:oe?Array.from(n().subarray(oe>>>0,pe>>>0)):[],outputShape:xe?Array.from(n().subarray(xe>>>0,Te>>>0)):[],activation:Ye(k)})},938915:(i,c)=>{a.Ea("GlobalAveragePool",i,{format:c?"NHWC":"NCHW"})},939006:(i,c,f,S,O,D,W,ie,ne,oe,pe,xe,Te,k,me,Ce)=>{a.Ea("AveragePool",i,{format:Ce?"NHWC":"NCHW",auto_pad:c,ceil_mode:f,count_include_pad:S,storage_order:O,dilations:[D,W],kernel_shape:[ie,ne],pads:[oe,pe,xe,Te],strides:[k,me]})},939290:(i,c)=>{a.Ea("GlobalAveragePool",i,{format:c?"NHWC":"NCHW"})},939381:(i,c,f,S,O,D,W,ie,ne,oe,pe,xe,Te,k,me,Ce)=>{a.Ea("AveragePool",i,{format:Ce?"NHWC":"NCHW",auto_pad:c,ceil_mode:f,count_include_pad:S,storage_order:O,dilations:[D,W],kernel_shape:[ie,ne],pads:[oe,pe,xe,Te],strides:[k,me]})},939665:(i,c)=>{a.Ea("GlobalMaxPool",i,{format:c?"NHWC":"NCHW"})},939752:(i,c,f,S,O,D,W,ie,ne,oe,pe,xe,Te,k,me,Ce)=>{a.Ea("MaxPool",i,{format:Ce?"NHWC":"NCHW",auto_pad:c,ceil_mode:f,count_include_pad:S,storage_order:O,dilations:[D,W],kernel_shape:[ie,ne],pads:[oe,pe,xe,Te],strides:[k,me]})},940032:(i,c)=>{a.Ea("GlobalMaxPool",i,{format:c?"NHWC":"NCHW"})},940119:(i,c,f,S,O,D,W,ie,ne,oe,pe,xe,Te,k,me,Ce)=>{a.Ea("MaxPool",i,{format:Ce?"NHWC":"NCHW",auto_pad:c,ceil_mode:f,count_include_pad:S,storage_order:O,dilations:[D,W],kernel_shape:[ie,ne],pads:[oe,pe,xe,Te],strides:[k,me]})},940399:(i,c,f,S,O)=>{a.Ea("Gemm",i,{alpha:c,beta:f,transA:S,transB:O})},940503:i=>{a.Ea("MatMul",i,void 0)},940557:(i,c,f,S)=>{a.Ea("ArgMax",i,{keepDims:!!c,selectLastIndex:!!f,axis:S})},940665:(i,c,f,S)=>{a.Ea("ArgMin",i,{keepDims:!!c,selectLastIndex:!!f,axis:S})},940773:(i,c)=>{a.Ea("Softmax",i,{axis:c})},940836:(i,c)=>{a.Ea("Concat",i,{axis:c})},940896:(i,c,f,S,O)=>{a.Ea("Split",i,{axis:c,numOutputs:f,splitSizes:S?Array.from(n().subarray(S>>>0,O>>>0)):[]})},941036:i=>{a.Ea("Expand",i,void 0)},941090:(i,c)=>{a.Ea("Gather",i,{axis:Number(c)})},941161:(i,c)=>{a.Ea("GatherElements",i,{axis:Number(c)})},941240:(i,c,f,S,O,D,W,ie,ne,oe,pe)=>{a.Ea("Resize",i,{antialias:c,axes:f?Array.from(n().subarray(f>>>0,S>>>0)):[],coordinateTransformMode:Ye(O),cubicCoeffA:D,excludeOutside:W,extrapolationValue:ie,keepAspectRatioPolicy:Ye(ne),mode:Ye(oe),nearestMode:Ye(pe)})},941586:(i,c,f,S,O,D,W)=>{a.Ea("Slice",i,{starts:c?Array.from(n().subarray(c>>>0,f>>>0)):[],ends:S?Array.from(n().subarray(S>>>0,O>>>0)):[],axes:D?Array.from(n().subarray(D>>>0,W>>>0)):[]})},941802:i=>{a.Ea("Tile",i,void 0)},941854:(i,c,f)=>{a.Ea("LayerNormalization",i,{axis:Number(c),epsilon:Number(f)})},941961:(i,c,f)=>{a.Ea("InstanceNormalization",i,{epsilon:c,format:f?"NHWC":"NCHW"})},942075:(i,c,f)=>{a.Ea("InstanceNormalization",i,{epsilon:c,format:f?"NHWC":"NCHW"})},942189:i=>{a.Ea("Range",i,void 0)},942242:(i,c)=>{a.Ea("Einsum",i,{equation:Ye(c)})},942323:(i,c,f,S,O)=>{a.Ea("Pad",i,{mode:c,value:f,pads:S?Array.from(n().subarray(S>>>0,O>>>0)):[]})},942450:(i,c,f,S,O,D)=>{a.Ea("BatchNormalization",i,{epsilon:c,momentum:f,spatial:!!O,trainingMode:!!S,format:D?"NHWC":"NCHW"})},942619:(i,c,f,S,O,D)=>{a.Ea("BatchNormalization",i,{epsilon:c,momentum:f,spatial:!!O,trainingMode:!!S,format:D?"NHWC":"NCHW"})},942788:(i,c,f)=>{a.Ea("CumSum",i,{exclusive:Number(c),reverse:Number(f)})},942885:(i,c,f,S,O,D,W,ie,ne)=>{a.Ea("Attention",i,{numHeads:c,isUnidirectional:f,maskFilterValue:S,scale:O,doRotary:D,qkvHiddenSizes:W?Array.from(n().subarray(Number(ie)>>>0,Number(ie)+W>>>0)):[],pastPresentShareBuffer:!!ne})},943157:i=>{a.Ea("Gelu",i,void 0)},943209:(i,c,f,S,O,D)=>{a.Ea("MultiHeadAttention",i,{numHeads:c,isUnidirectional:f,maskFilterValue:S,scale:O,doRotary:D})},943368:i=>{a.Ea("BiasAdd",i,void 0)},943423:i=>{a.Ea("BiasSplitGelu",i,void 0)},943484:(i,c)=>{a.Ea("SkipLayerNormalization",i,{epsilon:c})},943565:(i,c,f,S,O,D,W,ie,ne,oe,pe,xe,Te)=>{a.Ea("Conv",i,{format:ne?"NHWC":"NCHW",auto_pad:c,dilations:[f],group:S,kernel_shape:[O],pads:D?Array.from(n().subarray(D>>>0,W>>>0)):[],strides:[ie],w_is_const:()=>!!r()[oe>>>0],activation:Ye(pe),activation_params:xe?Array.from(u().subarray(xe>>>0,Te>>>0)):[]})},943935:(i,c,f,S,O,D,W,ie,ne,oe,pe,xe,Te,k,me,Ce)=>{a.Ea("Conv",i,{format:xe?"NHWC":"NCHW",auto_pad:c,dilations:[f,S],group:O,kernel_shape:[D,W],pads:ie?Array.from(n().subarray(ie>>>0,ne>>>0)):[],strides:[oe,pe],w_is_const:()=>!!r()[Te>>>0],activation:Ye(k),activation_params:me?Array.from(u().subarray(me>>>0,Ce>>>0)):[]})},944326:i=>{a.zb(i)},944360:(i,c)=>a.Ab(i,c,a.bb.Cb,a.bb.errors)};function Ut(i){this.name="ExitStatus",this.message=`Program terminated with exit(${i})`,this.status=i}var Tt=i=>{i.terminate(),i.onmessage=()=>{}},Kt=i=>{de.Ya.length==0&&(ot(),de.lb(de.Ya[0]));var c=de.Ya.pop();if(!c)return 6;de.Za.push(c),de.Qa[i.Xa]=c,c.Xa=i.Xa;var f={cmd:"run",start_routine:i.Db,arg:i.tb,pthread_ptr:i.Xa};return I&&c.unref(),c.postMessage(f,i.Jb),0},nt=0,Yt=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,Vt=(i,c,f)=>{c>>>=0;var S=c+f;for(f=c;i[f]&&!(f>=S);)++f;if(16O?S+=String.fromCharCode(O):(O-=65536,S+=String.fromCharCode(55296|O>>10,56320|O&1023))}}else S+=String.fromCharCode(O)}return S},Ye=(i,c)=>(i>>>=0)?Vt(o(),i,c):"",br=i=>{var c=mn();return i=i(),kr(c),i};function Oe(i,c){var f=arguments.length-2,S=arguments;return br(()=>{for(var O=fn(8*f),D=O>>>3,W=0;W>>0]=ie}return po(i,f,O,c)})}function wr(i){if($)return Oe(0,1,i);Pe=i,0{if(Pe=i,$)throw Zt(i),"unwind";wr(i)},St=i=>{i instanceof Ut||i=="unwind"||w(1,i)};function un(){for(var i=a.numThreads;i--;)ot();ee.unshift(()=>{ze++,tt(()=>wt())})}function ot(){var i=E("ort-wasm-simd-threaded.worker.js");i=new Worker(i),de.Ya.push(i)}function tt(i){$?i():Promise.all(de.Ya.map(de.lb)).then(i)}var de={Ya:[],Za:[],pb:[],Qa:{},hb(){$?(de.receiveObjectTransfer=de.Bb,de.threadInitTLS=de.ob,de.setExitStatus=de.nb):un()},nb:i=>Pe=i,Nb:["$terminateWorker"],Eb:()=>{for(var i of de.Za)Tt(i);for(i of de.Ya)Tt(i);de.Ya=[],de.Za=[],de.Qa=[]},mb:i=>{var c=i.Xa;delete de.Qa[c],de.Ya.push(i),de.Za.splice(de.Za.indexOf(i),1),i.Xa=0,cn(c)},Bb(){},ob(){de.pb.forEach(i=>i())},lb:i=>new Promise(c=>{i.onmessage=D=>{D=D.data;var W=D.cmd;if(D.targetThread&&D.targetThread!=Pr()){var ie=de.Qa[D.targetThread];ie?ie.postMessage(D,D.transferList):K(`Internal error! Worker sent a message "${W}" to target pthread ${D.targetThread}, but that thread no longer exists!`)}else W==="checkMailbox"?Et():W==="spawnThread"?Kt(D):W==="cleanupThread"?de.mb(de.Qa[D.thread]):W==="killThread"?(D=D.thread,W=de.Qa[D],delete de.Qa[D],Tt(W),cn(D),de.Za.splice(de.Za.indexOf(W),1),W.Xa=0):W==="cancelThread"?de.Qa[D.thread].postMessage({cmd:"cancel"}):W==="loaded"?(i.loaded=!0,I&&!i.Xa&&i.unref(),c(i)):W==="alert"?alert(`Thread ${D.threadId}: ${D.text}`):D.target==="setimmediate"?i.postMessage(D):W==="callHandler"?a[D.handler](...D.args):W&&K(`worker sent an unknown command ${W}`)},i.onerror=D=>{throw K(`worker sent an error! ${D.filename}:${D.lineno}: ${D.message}`),D},I&&(i.on("message",D=>i.onmessage({data:D})),i.on("error",D=>i.onerror(D)));var f=[],S=["onExit"],O;for(O of S)a.hasOwnProperty(O)&&f.push(O);i.postMessage({cmd:"load",handlers:f,urlOrBlob:a.mainScriptUrlOrBlob||e,wasmMemory:Q,wasmModule:Z})})};a.PThread=de;var bt=i=>{for(;0{var i=Pr(),c=s()[i+52>>>2>>>0];i=s()[i+56>>>2>>>0],ho(c,c-i),kr(c)};function Zt(i){if($)return Oe(1,0,i);Nt(i)}a.invokeEntryPoint=(i,c)=>{i=go.apply(null,[i,c]),0>>2>>>0]=c},this.rb=function(c){s()[this.gb+8>>>2>>>0]=c},this.hb=function(c,f){this.qb(),this.sb(c),this.rb(f)},this.qb=function(){s()[this.gb+16>>>2>>>0]=0}}var $r=0,Qt=0;function Sr(i,c,f,S){return $?Oe(2,1,i,c,f,S):xr(i,c,f,S)}function xr(i,c,f,S){if(i>>>=0,c>>>=0,f>>>=0,S>>>=0,typeof SharedArrayBuffer>"u")return K("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var O=[];return $&&O.length===0?Sr(i,c,f,S):(i={Db:f,Xa:i,tb:S,Jb:O},$?(i.Lb="spawnThread",postMessage(i,O),0):Kt(i))}function _r(i,c,f){return $?Oe(3,1,i,c,f):0}function Cr(i,c){if($)return Oe(4,1,i,c)}var Xt=i=>{for(var c=0,f=0;f=S?c++:2047>=S?c+=2:55296<=S&&57343>=S?(c+=4,++f):c+=3}return c},Ir=(i,c,f,S)=>{if(f>>>=0,!(0=W){var ie=i.charCodeAt(++D);W=65536+((W&1023)<<10)|ie&1023}if(127>=W){if(f>=S)break;c[f++>>>0]=W}else{if(2047>=W){if(f+1>=S)break;c[f++>>>0]=192|W>>6}else{if(65535>=W){if(f+2>=S)break;c[f++>>>0]=224|W>>12}else{if(f+3>=S)break;c[f++>>>0]=240|W>>18,c[f++>>>0]=128|W>>12&63}c[f++>>>0]=128|W>>6&63}c[f++>>>0]=128|W&63}}return c[f>>>0]=0,f-O},ae=(i,c,f)=>Ir(i,o(),c,f);function Jt(i,c){if($)return Oe(5,1,i,c)}function Wt(i,c,f){if($)return Oe(6,1,i,c,f)}function er(i,c,f){return $?Oe(7,1,i,c,f):0}function tr(i,c){if($)return Oe(8,1,i,c)}function rr(i,c,f){if($)return Oe(9,1,i,c,f)}function nr(i,c,f,S){if($)return Oe(10,1,i,c,f,S)}function or(i,c,f,S){if($)return Oe(11,1,i,c,f,S)}function ar(i,c,f,S){if($)return Oe(12,1,i,c,f,S)}function ir(i){if($)return Oe(13,1,i)}function sr(i,c){if($)return Oe(14,1,i,c)}function ur(i,c,f){if($)return Oe(15,1,i,c,f)}var Ar=()=>{if(!(0>>=0,typeof Atomics.Kb=="function"&&(Atomics.Kb(n(),i>>>2,i).value.then(Et),i+=128,Atomics.store(n(),i>>>2,1))}a.__emscripten_thread_mailbox_await=xt;var Et=()=>{var i=Pr();if(i&&(xt(i),!Ee))try{mo(),Ar()}catch(c){St(c)}};a.checkMailbox=Et;var d=[],m=i=>i%4===0&&(i%100!==0||i%400===0),v=[0,31,60,91,121,152,182,213,244,274,305,335],C=[0,31,59,90,120,151,181,212,243,273,304,334];function B(i,c,f,S,O,D,W,ie){return $?Oe(16,1,i,c,f,S,O,D,W,ie):-52}function H(i,c,f,S,O,D,W){if($)return Oe(17,1,i,c,f,S,O,D,W)}var q=i=>{var c=Xt(i)+1,f=ln(c);return f&&ae(i,f,c),f},le=[],J=(i,c)=>{le.length=0;for(var f;f=o()[i++>>>0];){var S=f!=105;S&=f!=112,c+=S&&c%8?4:0,le.push(f==112?s()[c>>>2>>>0]:f==105?n()[c>>>2>>>0]:l()[c>>>3>>>0]),c+=S?8:4}return le},re={},se=()=>{if(!we){var i={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:b||"./this.program"},c;for(c in re)re[c]===void 0?delete i[c]:i[c]=re[c];var f=[];for(c in i)f.push(`${c}=${i[c]}`);we=f}return we},we;function _e(i,c){if($)return Oe(18,1,i,c);i>>>=0,c>>>=0;var f=0;return se().forEach((S,O)=>{var D=c+f;for(O=s()[i+4*O>>>2>>>0]=D,D=0;D>>0>>>0]=S.charCodeAt(D);r()[O>>>0>>>0]=0,f+=S.length+1}),0}function P(i,c){if($)return Oe(19,1,i,c);i>>>=0,c>>>=0;var f=se();s()[i>>>2>>>0]=f.length;var S=0;return f.forEach(O=>S+=O.length+1),s()[c>>>2>>>0]=S,0}function ue(i){return $?Oe(20,1,i):52}function Se(i,c,f,S){return $?Oe(21,1,i,c,f,S):52}function st(i,c,f,S,O){return $?Oe(22,1,i,c,f,S,O):70}var Tr=[null,[],[]];function to(i,c,f,S){if($)return Oe(23,1,i,c,f,S);c>>>=0,f>>>=0,S>>>=0;for(var O=0,D=0;D>>2>>>0],ie=s()[c+4>>>2>>>0];c+=8;for(var ne=0;ne>>0],pe=Tr[i];oe===0||oe===10?((i===1?Y:K)(Vt(pe,0)),pe.length=0):pe.push(oe)}O+=ie}return s()[S>>>2>>>0]=O,0}var ro=[31,29,31,30,31,30,31,31,30,31,30,31],no=[31,28,31,30,31,30,31,31,30,31,30,31];function Pu(i){var c=Array(Xt(i)+1);return Ir(i,c,0,c.length),c}var ku=(i,c)=>{r().set(i,c>>>0)};function oo(i,c,f,S){function O(k,me,Ce){for(k=typeof k=="number"?k.toString():k||"";k.lengthSo?-1:0Ot-k.getDate())me-=Ot-k.getDate()+1,k.setDate(1),11>Ce?k.setMonth(Ce+1):(k.setMonth(0),k.setFullYear(k.getFullYear()+1));else{k.setDate(k.getDate()+me);break}}return Ce=new Date(k.getFullYear()+1,0,4),me=ie(new Date(k.getFullYear(),0,4)),Ce=ie(Ce),0>=W(me,k)?0>=W(Ce,k)?k.getFullYear()+1:k.getFullYear():k.getFullYear()-1}i>>>=0,c>>>=0,f>>>=0,S>>>=0;var oe=s()[S+40>>>2>>>0];S={Hb:n()[S>>>2>>>0],Gb:n()[S+4>>>2>>>0],eb:n()[S+8>>>2>>>0],jb:n()[S+12>>>2>>>0],fb:n()[S+16>>>2>>>0],ab:n()[S+20>>>2>>>0],Wa:n()[S+24>>>2>>>0],$a:n()[S+28>>>2>>>0],Ob:n()[S+32>>>2>>>0],Fb:n()[S+36>>>2>>>0],Ib:oe?Ye(oe):""},f=Ye(f),oe={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"};for(var pe in oe)f=f.replace(new RegExp(pe,"g"),oe[pe]);var xe="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),Te="January February March April May June July August September October November December".split(" ");oe={"%a":k=>xe[k.Wa].substring(0,3),"%A":k=>xe[k.Wa],"%b":k=>Te[k.fb].substring(0,3),"%B":k=>Te[k.fb],"%C":k=>D((k.ab+1900)/100|0,2),"%d":k=>D(k.jb,2),"%e":k=>O(k.jb,2," "),"%g":k=>ne(k).toString().substring(2),"%G":k=>ne(k),"%H":k=>D(k.eb,2),"%I":k=>(k=k.eb,k==0?k=12:12{for(var me=0,Ce=0;Ce<=k.fb-1;me+=(m(k.ab+1900)?ro:no)[Ce++]);return D(k.jb+me,3)},"%m":k=>D(k.fb+1,2),"%M":k=>D(k.Gb,2),"%n":()=>`\n`,"%p":k=>0<=k.eb&&12>k.eb?"AM":"PM","%S":k=>D(k.Hb,2),"%t":()=>" ","%u":k=>k.Wa||7,"%U":k=>D(Math.floor((k.$a+7-k.Wa)/7),2),"%V":k=>{var me=Math.floor((k.$a+7-(k.Wa+6)%7)/7);if(2>=(k.Wa+371-k.$a-2)%7&&me++,me)me==53&&(Ce=(k.Wa+371-k.$a)%7,Ce==4||Ce==3&&m(k.ab)||(me=1));else{me=52;var Ce=(k.Wa+7-k.$a-1)%7;(Ce==4||Ce==5&&m(k.ab%400-1))&&me++}return D(me,2)},"%w":k=>k.Wa,"%W":k=>D(Math.floor((k.$a+7-(k.Wa+6)%7)/7),2),"%y":k=>(k.ab+1900).toString().substring(2),"%Y":k=>k.ab+1900,"%z":k=>{k=k.Fb;var me=0<=k;return k=Math.abs(k)/60,(me?"+":"-")+("0000"+(k/60*100+k%60)).slice(-4)},"%Z":k=>k.Ib,"%%":()=>"%"},f=f.replace(/%%/g,"\\0\\0");for(pe in oe)f.includes(pe)&&(f=f.replace(new RegExp(pe,"g"),oe[pe](S)));return f=f.replace(/\\0\\0/g,"%"),pe=Pu(f),pe.length>c?0:(ku(pe,i),pe.length-1)}var Er=i=>{try{i()}catch(c){rt(c)}};function Ru(){var i=X,c={};for(let[f,S]of Object.entries(i))c[f]=typeof S=="function"?function(){Or.push(f);try{return S.apply(null,arguments)}finally{Ee||(Or.pop(),ut&&_t===1&&Or.length===0&&(_t=0,nt+=1,Er(bo),typeof Fibers<"u"&&Fibers.Pb()))}}:S;return c}var _t=0,ut=null,ao=0,Or=[],io={},so={},Bu=0,dn=null,Du=[];function Mu(){return new Promise((i,c)=>{dn={resolve:i,reject:c}})}function zu(){var i=ln(65548),c=i+12;s()[i>>>2>>>0]=c,s()[i+4>>>2>>>0]=c+65536,c=Or[0];var f=io[c];return f===void 0&&(f=Bu++,io[c]=f,so[f]=c),c=f,n()[i+8>>>2>>>0]=c,i}function Uu(){var i=n()[ut+8>>>2>>>0];return i=X[so[i]],--nt,i()}function Vu(i){if(!Ee){if(_t===0){var c=!1,f=!1;i((S=0)=>{if(!Ee&&(ao=S,c=!0,f)){_t=2,Er(()=>wo(ut)),typeof Browser<"u"&&Browser.ib.vb&&Browser.ib.resume(),S=!1;try{var O=Uu()}catch(ie){O=ie,S=!0}var D=!1;if(!ut){var W=dn;W&&(dn=null,(S?W.reject:W.resolve)(O),D=!0)}if(S&&!D)throw O}}),f=!0,c||(_t=1,ut=zu(),typeof Browser<"u"&&Browser.ib.vb&&Browser.ib.pause(),Er(()=>yo(ut)))}else _t===2?(_t=0,Er(vo),lo(ut),ut=null,Du.forEach(S=>{if(!Ee)try{S(),Ar()}catch(O){St(O)}})):rt(`invalid state: ${_t}`);return ao}}function Nu(i){return Vu(c=>{i().then(c)})}de.hb();var Wu=[wr,Zt,Sr,_r,Cr,Jt,Wt,er,tr,rr,nr,or,ar,ir,sr,ur,B,H,_e,P,ue,Se,st,to],Hu={r:function(i,c,f){return Nu(async()=>{await a.xb(i,c,f)})},b:function(i,c,f){throw i>>>=0,new vr(i).hb(c>>>0,f>>>0),$r=i,Qt++,$r},N:function(i){co(i>>>0,!_,1,!y,131072,!1),de.ob()},l:function(i){i>>>=0,$?postMessage({cmd:"cleanupThread",thread:i}):de.mb(de.Qa[i])},J:xr,i:_r,T:Cr,F:Jt,H:Wt,U:er,R:tr,L:rr,Q:nr,p:or,G:ar,D:ir,S:sr,E:ur,q:()=>1,B:function(i,c){i>>>=0,i==c>>>0?setTimeout(()=>Et()):$?postMessage({targetThread:i,cmd:"checkMailbox"}):(i=de.Qa[i])&&i.postMessage({cmd:"checkMailbox"})},K:function(i,c,f,S){c>>>=0,d.length=f,S=S>>>0>>>3;for(var O=0;O>>0];return i=0>i?zt[-i-1]:Wu[i],de.ub=c,c=i.apply(null,d),de.ub=0,c},M:xt,W:function(i){I&&de.Qa[i>>>0].ref()},u:function(i,c,f){i=c+2097152>>>0<4194305-!!i?(i>>>0)+4294967296*c:NaN,f>>>=0,i=new Date(1e3*i),n()[f>>>2>>>0]=i.getUTCSeconds(),n()[f+4>>>2>>>0]=i.getUTCMinutes(),n()[f+8>>>2>>>0]=i.getUTCHours(),n()[f+12>>>2>>>0]=i.getUTCDate(),n()[f+16>>>2>>>0]=i.getUTCMonth(),n()[f+20>>>2>>>0]=i.getUTCFullYear()-1900,n()[f+24>>>2>>>0]=i.getUTCDay(),i=(i.getTime()-Date.UTC(i.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,n()[f+28>>>2>>>0]=i},v:function(i,c,f){i=c+2097152>>>0<4194305-!!i?(i>>>0)+4294967296*c:NaN,f>>>=0,i=new Date(1e3*i),n()[f>>>2>>>0]=i.getSeconds(),n()[f+4>>>2>>>0]=i.getMinutes(),n()[f+8>>>2>>>0]=i.getHours(),n()[f+12>>>2>>>0]=i.getDate(),n()[f+16>>>2>>>0]=i.getMonth(),n()[f+20>>>2>>>0]=i.getFullYear()-1900,n()[f+24>>>2>>>0]=i.getDay(),c=(m(i.getFullYear())?v:C)[i.getMonth()]+i.getDate()-1|0,n()[f+28>>>2>>>0]=c,n()[f+36>>>2>>>0]=-(60*i.getTimezoneOffset()),c=new Date(i.getFullYear(),6,1).getTimezoneOffset();var S=new Date(i.getFullYear(),0,1).getTimezoneOffset();i=(c!=S&&i.getTimezoneOffset()==Math.min(S,c))|0,n()[f+32>>>2>>>0]=i},w:function(i){i>>>=0;var c=new Date(n()[i+20>>>2>>>0]+1900,n()[i+16>>>2>>>0],n()[i+12>>>2>>>0],n()[i+8>>>2>>>0],n()[i+4>>>2>>>0],n()[i>>>2>>>0],0),f=n()[i+32>>>2>>>0],S=c.getTimezoneOffset(),O=new Date(c.getFullYear(),6,1).getTimezoneOffset(),D=new Date(c.getFullYear(),0,1).getTimezoneOffset(),W=Math.min(D,O);return 0>f?n()[i+32>>>2>>>0]=+(O!=D&&W==S):0>>2>>>0]=c.getDay(),f=(m(c.getFullYear())?v:C)[c.getMonth()]+c.getDate()-1|0,n()[i+28>>>2>>>0]=f,n()[i>>>2>>>0]=c.getSeconds(),n()[i+4>>>2>>>0]=c.getMinutes(),n()[i+8>>>2>>>0]=c.getHours(),n()[i+12>>>2>>>0]=c.getDate(),n()[i+16>>>2>>>0]=c.getMonth(),n()[i+20>>>2>>>0]=c.getYear(),i=c.getTime(),isNaN(i)?(n()[uo()>>>2>>>0]=61,i=-1):i/=1e3,fo((yt=i,1<=+Math.abs(yt)?0>>0:~~+Math.ceil((yt-+(~~yt>>>0))/4294967296)>>>0:0)),i>>>0},s:B,t:H,A:function(i,c,f){function S(oe){return(oe=oe.toTimeString().match(/\\(([A-Za-z ]+)\\)$/))?oe[1]:"GMT"}i>>>=0,c>>>=0,f>>>=0;var O=new Date().getFullYear(),D=new Date(O,0,1),W=new Date(O,6,1);O=D.getTimezoneOffset();var ie=W.getTimezoneOffset(),ne=Math.max(O,ie);s()[i>>>2>>>0]=60*ne,n()[c>>>2>>>0]=+(O!=ie),i=S(D),c=S(W),i=q(i),c=q(c),ie>>2>>>0]=i,s()[f+4>>>2>>>0]=c):(s()[f>>>2>>>0]=c,s()[f+4>>>2>>>0]=i)},d:()=>{rt("")},c:function(i,c,f){return i>>>=0,c=J(c>>>0,f>>>0),zt[i].apply(null,c)},k:function(i,c,f){return i>>>=0,c=J(c>>>0,f>>>0),zt[i].apply(null,c)},m:()=>{},j:()=>Date.now(),V:()=>{throw nt+=1,"unwind"},C:function(){return 4294901760},f:()=>performance.timeOrigin+performance.now(),g:()=>I?(Oo(),Ht(Eo)).cpus().length:navigator.hardwareConcurrency,y:function(i){i>>>=0;var c=o().length;if(i<=c||4294901760=f;f*=2){var S=c*(1+.2/f);S=Math.min(S,i+100663296);var O=Math;S=Math.max(i,S);e:{O=(O.min.call(O,4294901760,S+(65536-S%65536)%65536)-Q.buffer.byteLength+65535)/65536;try{Q.grow(O),Ge();var D=1;break e}catch{}D=void 0}if(D)return!0}return!1},O:_e,P,I:Nt,h:ue,o:Se,x:st,n:to,a:Q||a.wasmMemory,z:oo,e:function(i,c,f,S){return oo(i>>>0,c>>>0,f>>>0,S>>>0)}},X=function(){function i(f,S){return X=f.exports,X=Ru(),X=Gu(),de.pb.push(X.Da),be.unshift(X.X),Z=S,wt(),X}var c={a:Hu};if(ze++,a.instantiateWasm)try{return a.instantiateWasm(c,i)}catch(f){K(`Module.instantiateWasm callback failed with error: ${f}`),h(f)}return $t(c,function(f){i(f.instance,f.module)}).catch(h),{}}();a._OrtInit=(i,c)=>(a._OrtInit=X.Y)(i,c),a._OrtGetLastError=(i,c)=>(a._OrtGetLastError=X.Z)(i,c),a._OrtCreateSessionOptions=(i,c,f,S,O,D,W,ie,ne,oe)=>(a._OrtCreateSessionOptions=X._)(i,c,f,S,O,D,W,ie,ne,oe),a._OrtAppendExecutionProvider=(i,c)=>(a._OrtAppendExecutionProvider=X.$)(i,c),a._OrtAddFreeDimensionOverride=(i,c,f)=>(a._OrtAddFreeDimensionOverride=X.aa)(i,c,f),a._OrtAddSessionConfigEntry=(i,c,f)=>(a._OrtAddSessionConfigEntry=X.ba)(i,c,f),a._OrtReleaseSessionOptions=i=>(a._OrtReleaseSessionOptions=X.ca)(i),a._OrtCreateSession=(i,c,f)=>(a._OrtCreateSession=X.da)(i,c,f),a._OrtReleaseSession=i=>(a._OrtReleaseSession=X.ea)(i),a._OrtGetInputOutputCount=(i,c,f)=>(a._OrtGetInputOutputCount=X.fa)(i,c,f),a._OrtGetInputName=(i,c)=>(a._OrtGetInputName=X.ga)(i,c),a._OrtGetOutputName=(i,c)=>(a._OrtGetOutputName=X.ha)(i,c),a._OrtFree=i=>(a._OrtFree=X.ia)(i),a._OrtCreateTensor=(i,c,f,S,O,D)=>(a._OrtCreateTensor=X.ja)(i,c,f,S,O,D),a._OrtGetTensorData=(i,c,f,S,O)=>(a._OrtGetTensorData=X.ka)(i,c,f,S,O),a._OrtReleaseTensor=i=>(a._OrtReleaseTensor=X.la)(i),a._OrtCreateRunOptions=(i,c,f,S)=>(a._OrtCreateRunOptions=X.ma)(i,c,f,S),a._OrtAddRunConfigEntry=(i,c,f)=>(a._OrtAddRunConfigEntry=X.na)(i,c,f),a._OrtReleaseRunOptions=i=>(a._OrtReleaseRunOptions=X.oa)(i),a._OrtCreateBinding=i=>(a._OrtCreateBinding=X.pa)(i),a._OrtBindInput=(i,c,f)=>(a._OrtBindInput=X.qa)(i,c,f),a._OrtBindOutput=(i,c,f,S)=>(a._OrtBindOutput=X.ra)(i,c,f,S),a._OrtClearBoundOutputs=i=>(a._OrtClearBoundOutputs=X.sa)(i),a._OrtReleaseBinding=i=>(a._OrtReleaseBinding=X.ta)(i),a._OrtRunWithBinding=(i,c,f,S,O)=>(a._OrtRunWithBinding=X.ua)(i,c,f,S,O),a._OrtRun=(i,c,f,S,O,D,W,ie)=>(a._OrtRun=X.va)(i,c,f,S,O,D,W,ie),a._OrtEndProfiling=i=>(a._OrtEndProfiling=X.wa)(i),a._JsepOutput=(i,c,f)=>(a._JsepOutput=X.xa)(i,c,f),a._JsepGetNodeName=i=>(a._JsepGetNodeName=X.ya)(i);var uo=()=>(uo=X.za)(),Pr=a._pthread_self=()=>(Pr=a._pthread_self=X.Aa)(),ln=a._malloc=i=>(ln=a._malloc=X.Ba)(i),lo=a._free=i=>(lo=a._free=X.Ca)(i);a.__emscripten_tls_init=()=>(a.__emscripten_tls_init=X.Da)();var co=a.__emscripten_thread_init=(i,c,f,S,O,D)=>(co=a.__emscripten_thread_init=X.Fa)(i,c,f,S,O,D);a.__emscripten_thread_crashed=()=>(a.__emscripten_thread_crashed=X.Ga)();var po=(i,c,f,S)=>(po=X.Ha)(i,c,f,S),cn=i=>(cn=X.Ia)(i),pn=a.__emscripten_thread_exit=i=>(pn=a.__emscripten_thread_exit=X.Ja)(i),mo=()=>(mo=X.Ka)(),fo=i=>(fo=X.La)(i),ho=(i,c)=>(ho=X.Ma)(i,c),mn=()=>(mn=X.Na)(),kr=i=>(kr=X.Oa)(i),fn=i=>(fn=X.Pa)(i),go=a.dynCall_ii=(i,c)=>(go=a.dynCall_ii=X.Ra)(i,c),yo=i=>(yo=X.Sa)(i),bo=()=>(bo=X.Ta)(),wo=i=>(wo=X.Ua)(i),vo=()=>(vo=X.Va)();a.___start_em_js=944472,a.___stop_em_js=944633;function Gu(){var i=X;i=Object.assign({},i);var c=S=>()=>S()>>>0,f=S=>O=>S(O)>>>0;return i.za=c(i.za),i.Aa=c(i.Aa),i.Ba=f(i.Ba),i.emscripten_main_runtime_thread_id=c(i.emscripten_main_runtime_thread_id),i.Na=c(i.Na),i.Pa=f(i.Pa),i}a.wasmMemory=Q,a.stackAlloc=fn,a.stackSave=mn,a.stackRestore=kr,a.keepRuntimeAlive=()=>0Po)});var Bo=dr((qc,Xu)=>{Xu.exports=\'"use strict";var Module={},ENVIRONMENT_IS_NODE=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string";if(ENVIRONMENT_IS_NODE){var nodeWorkerThreads=require("worker_threads"),parentPort=nodeWorkerThreads.parentPort;parentPort.on("message",e=>onmessage({data:e}));var fs=require("fs"),vm=require("vm");Object.assign(global,{self:global,require,Module,location:{href:__filename},Worker:nodeWorkerThreads.Worker,importScripts:e=>vm.runInThisContext(fs.readFileSync(e,"utf8"),{filename:e}),postMessage:e=>parentPort.postMessage(e),performance:global.performance||{now:Date.now}})}var initializedJS=!1;function threadPrintErr(){var e=Array.prototype.slice.call(arguments).join(" ");if(ENVIRONMENT_IS_NODE){fs.writeSync(2,e+`\\n`);return}console.error(e)}function threadAlert(){var e=Array.prototype.slice.call(arguments).join(" ");postMessage({cmd:"alert",text:e,threadId:Module._pthread_self()})}var err=threadPrintErr;self.alert=threadAlert,Module.instantiateWasm=(e,t)=>{var a=Module.wasmModule;Module.wasmModule=null;var r=new WebAssembly.Instance(a,e);return t(r)},self.onunhandledrejection=e=>{throw e.reason||e};function handleMessage(e){try{if(e.data.cmd==="load"){let a=[];self.onmessage=r=>a.push(r),self.startWorker=r=>{Module=r,postMessage({cmd:"loaded"});for(let s of a)handleMessage(s);self.onmessage=handleMessage},Module.wasmModule=e.data.wasmModule;for(const r of e.data.handlers)Module[r]=(...s)=>{postMessage({cmd:"callHandler",handler:r,args:s})};if(Module.wasmMemory=e.data.wasmMemory,Module.buffer=Module.wasmMemory.buffer,Module.ENVIRONMENT_IS_PTHREAD=!0,typeof e.data.urlOrBlob=="string")importScripts(e.data.urlOrBlob);else{var t=URL.createObjectURL(e.data.urlOrBlob);importScripts(t),URL.revokeObjectURL(t)}ortWasmThreaded(Module)}else if(e.data.cmd==="run"){Module.__emscripten_thread_init(e.data.pthread_ptr,0,0,1),Module.__emscripten_thread_mailbox_await(e.data.pthread_ptr),Module.establishStackSpace(),Module.PThread.receiveObjectTransfer(e.data),Module.PThread.threadInitTLS(),initializedJS||(initializedJS=!0);try{Module.invokeEntryPoint(e.data.start_routine,e.data.arg)}catch(a){if(a!="unwind")throw a}}else e.data.cmd==="cancel"?Module._pthread_self()&&Module.__emscripten_thread_exit(-1):e.data.target==="setimmediate"||(e.data.cmd==="checkMailbox"?initializedJS&&Module.checkMailbox():e.data.cmd&&(err(`worker.js received unknown command ${e.data.cmd}`),err(e.data)))}catch(a){throw Module.__emscripten_thread_crashed?.(),a}}self.onmessage=handleMessage;\\n\'});var _n,Xe,cr,Mr,pr,No,Cn,Ne=j(()=>{"use strict";_n=e=>{switch(e){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float16":return 10;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;default:throw new Error(`unsupported data type: ${e}`)}},Xe=e=>{switch(e){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 10:return"float16";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";default:throw new Error(`unsupported data type: ${e}`)}},cr=e=>[void 0,4,1,1,2,2,4,8,void 0,1,2,8,4,8,void 0,void 0,void 0][e],Mr=e=>{switch(e){case"float16":return Uint16Array;case"float32":return Float32Array;case"uint8":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"bool":return Uint8Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${e}`)}},pr=e=>{switch(e){case"verbose":return 0;case"info":return 1;case"warning":return 2;case"error":return 3;case"fatal":return 4;default:throw new Error(`unsupported logging level: ${e}`)}},No=e=>e==="float32"||e==="int32"||e==="int64"||e==="bool"||e==="float16"||e==="uint32",Cn=e=>{switch(e){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;default:throw new Error(`unsupported data location: ${e}`)}}});var zr=j(()=>{"use strict"});var Ho=j(()=>{"use strict";zr()});var Go,Lo=j(()=>{"use strict";Go="1.17.1"});var Fo,Pt,In=j(()=>{"use strict";Lo();Fo="warning",Pt={wasm:{},webgl:{},webgpu:{},versions:{common:Go},set logLevel(e){if(e!==void 0){if(typeof e!="string"||["verbose","info","warning","error","fatal"].indexOf(e)===-1)throw new Error(`Unsupported logging level: ${e}`);Fo=e}},get logLevel(){return Fo}};Object.defineProperty(Pt,"logLevel",{enumerable:!0})});var Gt,jo=j(()=>{"use strict";In();Gt=Pt});var qo=j(()=>{"use strict"});var Ko=j(()=>{"use strict";Ur()});var Zo=j(()=>{"use strict"});var Qo=j(()=>{"use strict";Ur()});var Ur=j(()=>{"use strict";qo();Ko();Zo();Qo()});var Vr=j(()=>{"use strict";Ur()});var An,Xo,kt,Rt,Tn=j(()=>{"use strict";In();An=(e,t)=>{Pt.wasm.trace&&console.timeStamp(`${e}::ORT::${t}`)},Xo=(e,t)=>{let r=new Error().stack?.split(/\\r\\n|\\r|\\n/g)||[],o=!1;for(let n=0;n{Pt.wasm.trace&&Xo("BEGIN",e)},Rt=e=>{Pt.wasm.trace&&Xo("END",e)}});var Jo=j(()=>{"use strict";zr();Vr();Tn()});var ea=j(()=>{"use strict";Jo()});var ta=j(()=>{"use strict"});var ra=j(()=>{"use strict";zr();Vr()});var na=j(()=>{"use strict";ra()});var Lt=j(()=>{"use strict";Ho();jo();ea();Vr();Tn();ta();na()});var dd,ld,oa,aa,ia,cd,Be,Ct=j(()=>{"use strict";Ne();dd=["V","I","W","E","F"],ld=(e,t)=>{console.log(`[${dd[e]},${new Date().toISOString()}]${t}`)},ia=(e,t)=>{oa=e,aa=t},cd=(e,t)=>{let r=pr(e),o=pr(oa);r>=o&&ld(r,typeof t=="function"?t():t)},Be=(...e)=>{aa&&cd(...e)}});var sa,ua=j(()=>{"use strict";Ne();sa=(e,t)=>new(Mr(t))(e)});var Nr=j(()=>{"use strict"});var Wr,pd,da,On,En,ca,pa=j(()=>{"use strict";Ct();Nr();Wr=e=>Math.ceil(e/16)*16,pd=1,da=()=>pd++,On=async(e,t,r,o)=>{let n=Wr(r),s=e.device.createBuffer({size:n,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let u=e.getCommandEncoder();e.endComputePass(),u.copyBufferToBuffer(t,0,s,0,n),e.flush(),await s.mapAsync(GPUMapMode.READ);let l=s.getMappedRange();if(o){let a=o();return a.set(new Uint8Array(l,0,r)),a}else return new Uint8Array(l.slice(0,r))}finally{s.destroy()}},En=class{constructor(t){this.backend=t;this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.buffersForUploadingPending=[],this.buffersPending=[],this.externalBuffers=new Map}upload(t,r){let o=r.buffer,n=r.byteOffset,s=r.byteLength,u=Wr(s),l=this.storageCache.get(t);if(!l)throw new Error("gpu data for uploading does not exist");if(l.originalSize!==s)throw new Error(`inconsistent data size. gpu data size=${l.originalSize}, data size=${s}`);let a=this.backend.device.createBuffer({mappedAtCreation:!0,size:u,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),p=a.getMappedRange();new Uint8Array(p).set(new Uint8Array(o,n,s)),a.unmap();let h=this.backend.getCommandEncoder();this.backend.endComputePass(),h.copyBufferToBuffer(a,0,l.gpuData.buffer,0,u),Be("verbose",()=>`[WebGPU] GpuDataManager.upload(id=${t})`),this.buffersForUploadingPending.push(a)}memcpy(t,r){let o=this.storageCache.get(t);if(!o)throw new Error("source gpu data for memcpy does not exist");let n=this.storageCache.get(r);if(!n)throw new Error("destination gpu data for memcpy does not exist");if(o.originalSize!==n.originalSize)throw new Error("inconsistent source and destination gpu data size");let s=Wr(o.originalSize),u=this.backend.getCommandEncoder();this.backend.endComputePass(),u.copyBufferToBuffer(o.gpuData.buffer,0,n.gpuData.buffer,0,s)}registerExternalBuffer(t,r,o){let n;if(o){if(n=this.externalBuffers.get(o),n===void 0)throw new Error("previous buffer is not registered");if(t===o)return Be("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${r}) => id=${n}, buffer is the same, skip.`),n;this.externalBuffers.delete(o)}else n=da();return this.storageCache.set(n,{gpuData:{id:n,type:0,buffer:t},originalSize:r}),this.externalBuffers.set(t,n),Be("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${r}) => id=${n}, registered.`),n}unregisterExternalBuffer(t){let r=this.externalBuffers.get(t);r!==void 0&&(this.storageCache.delete(r),this.externalBuffers.delete(t),Be("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${r}`))}create(t,r=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let o=Wr(t),n,s=(r&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,u=(r&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(s||u){let a=s?this.freeBuffers:this.freeUniformBuffers,p=a.get(o);p||(p=[],a.set(o,p)),p.length>0?n=p.pop():n=this.backend.device.createBuffer({size:o,usage:r})}else n=this.backend.device.createBuffer({size:o,usage:r});let l={id:da(),type:0,buffer:n};return this.storageCache.set(l.id,{gpuData:l,originalSize:t}),Be("verbose",()=>`[WebGPU] GpuDataManager.create(size=${t}) => id=${l.id}`),l}get(t){return this.storageCache.get(t)?.gpuData}release(t){let r=this.storageCache.get(t);if(!r)throw new Error("releasing data does not exist");return Be("verbose",()=>`[WebGPU] GpuDataManager.release(id=${t}), gpuDataId=${r.gpuData.id}`),this.storageCache.delete(t),this.buffersPending.push(r.gpuData.buffer),r.originalSize}async download(t,r){let o=this.storageCache.get(t);if(!o)throw new Error("data does not exist");await On(this.backend,o.gpuData.buffer,o.originalSize,r)}refreshPendingBuffers(){for(let t of this.buffersForUploadingPending)t.destroy();this.buffersForUploadingPending=[];for(let t of this.buffersPending)(t.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE?this.freeBuffers.get(t.size).push(t):(t.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM?this.freeUniformBuffers.get(t.size).push(t):t.destroy();this.buffersPending=[]}dispose(){this.freeBuffers.forEach(t=>{t.forEach(r=>{r.destroy()})}),this.freeUniformBuffers.forEach(t=>{t.forEach(r=>{r.destroy()})}),this.storageCache.forEach(t=>{t.gpuData.buffer.destroy()}),this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map}},ca=(...e)=>new En(...e)});var Pn,ge,je=j(()=>{"use strict";Pn=class{constructor(t){Object.assign(this,t)}get cacheKey(){return this.key||(this.key=Object.getOwnPropertyNames(this).sort().map(t=>`${this[t]}`).join(";")),this.key}},ge=e=>new Pn(e)});var kn,dt,U,Bt,Hr,Gr,Lr,$e=j(()=>{"use strict";kn=class{static calcMatMulShape(t,r){return t[1]!==r[0]?void 0:[t[0],r[1]]}},dt=class{static calcShape(t,r,o=!1){let n=t.length,s=r.length;if(n===0)return r;if(s===0)return t;let u=Math.max(t.length,r.length),l=new Array(u);if(o){if(n<2||s<2)return;let a=kn.calcMatMulShape([t[n-2],t[n-1]],[r[s-2],r[s-1]]);if(a===void 0)return;[l[u-2],l[u-1]]=a}for(let a=o?3:1;a<=u;a++){let p=n-a<0?1:t[n-a],h=s-a<0?1:r[s-a];if(p!==h&&p>1&&h>1)return;l[u-a]=Math.max(p,h)}return l}static isValidBroadcast(t,r){let o=t.length,n=r.length;if(o>n)return!1;for(let s=1;s<=o;s++)if(t[o-s]!==1&&t[o-s]!==r[n-s])return!1;return!0}},U=class e{static size(t){return e.getSizeFromDimensionRange(t,0,t.length)}static sizeFromDimension(t,r){if(r<0||r>t.length)throw new Error(`invalid dimension of ${r} for sizeFromDimension as Tensor has ${t.length} dimensions.`);return e.getSizeFromDimensionRange(t,r,t.length)}static sizeToDimension(t,r){if(r<0||r>t.length)throw new Error(`invalid dimension of ${r} for sizeToDimension as Tensor has ${t.length} dimensions.`);return e.getSizeFromDimensionRange(t,0,r)}static getSizeFromDimensionRange(t,r,o){let n=1;for(let s=r;s=0;--n)o[n]=o[n+1]*t[n+1];return o}static normalizeAxis(t,r){if(t<-r&&t>=r)throw new Error("unsupported axis for this operation.");return t<0?t+r:t}static normalizeAxes(t,r){return t.map(o=>this.normalizeAxis(o,r??t.length))}static sortBasedOnPerm(t,r){return r?r.map(o=>t[o]):t.slice().reverse()}static padShape(t,r){let o=t.length;return t.map((n,s)=>n+r[s]+r[s+o])}static areEqual(t,r){return t.length!==r.length?!1:t.every((o,n)=>o===r[n])}},Bt=class e{static adjustPoolAttributes(t,r,o,n,s,u){if(!t&&o.length!==r.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(t)for(let l=0;l=o.length?o.push(r[l+2]):o[l]=r[l+2];for(let l=0;l=o[l]||u[l+o.length]>=o[l])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(t,r,o,n,s,u,l){if(l){if(s.length!==2*(t.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(r.length!==t.length-2)throw new Error("length of strides should be the length of data dimensions");if(n.length!==t.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let a=0;a{"use strict";Ne();$e();md=64,Bn=(e,t)=>{if(t===3)throw new Error("vec3 has same alignment as vec4, use vec4 instead");switch(e){case 10:return t>1?`vec${t}`:"f16";case 1:return t>1?`vec${t}`:"f32";case 6:return t>1?`vec${t}`:"i32";case 12:return t>1?`vec${t}`:"u32";case 7:if(t>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","i32"];case 13:if(t>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","u32"];case 9:if(t!==4)throw new Error("bool must be vec4");return["u32","vec4"];default:throw new Error(`Unknown data type: ${e}`)}},Le=(e,t=1)=>{let r=Bn(e,t);return typeof r=="string"?r:r[0]},lt=(e,t=1)=>{let r=Bn(e,t);return typeof r=="string"?r:r[1]},L=e=>e.length===0?[]:[{type:"uint32",data:e},{type:"uint32",data:U.computeStrides(e)}],Fe=e=>e%4===0?4:e%2===0?2:1,Ze=(e="f32",t,r="0")=>!t||t===1?`${e}(${r})`:`vec${t}<${e}>(${r})`,at=(e,t,r)=>e==="f32"?r:t===1?`f32(${r})`:`vec${t}f(${r})`,Je=(e,t)=>t===4?`(${e}.x + ${e}.y + ${e}.z + ${e}.w)`:t===2?`(${e}.x + ${e}.y)`:t===3?`(${e}.x + ${e}.y + ${e}.z)`:e,ce=(e,t,r)=>e.startsWith("uniforms.")&&r>4?typeof t=="string"?`${e}[(${t}) / 4][(${t}) % 4]`:`${e}[${Math.floor(t/4)}][${t%4}]`:r>1?`${e}[${t}]`:e,Dn=(e,t,r,o,n)=>{let s=typeof r=="number",u=s?r:r.length,l=[...new Array(u).keys()],a=u<2?"u32":u<=4?`vec${u}`:`array`,p=Bn(t,n),h=typeof p=="string"?p:p[1],g=typeof p=="string"?p:p[0],b={indices:a,value:h,storage:g,tensor:t},w=G=>typeof G=="string"?G:`${G}u`,y={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},_=s?"uniforms.":"",I=`${_}${e}_shape`,$=`${_}${e}_strides`,x="";for(let G=0;G ${b.indices} {\n var indices: ${b.indices};\n var current = offset;\n ${x}\n return indices;\n }`,A=G=>(y.offsetToIndices=!0,u<2?G:`o2i_${e}(${G})`),z=[];if(u>=2)for(let G=u-1;G>=0;G--)z.push(`${ce($,G,u)} * (indices[${G}])`);let R=u<2?"":`\n fn i2o_${e}(indices: ${b.indices}) -> u32 {\n return ${z.join("+")};\n }`,V=G=>(y.indicesToOffset=!0,u<2?G:`i2o_${e}(${G})`),T=(...G)=>u===0?"0u":`${b.indices}(${G.map(w).join(",")})`,N=(G,ee)=>u<2?`${G}`:`${ce(G,ee,u)}`,te=(G,ee,be)=>u<2?`${G}=${be};`:`${ce(G,ee,u)}=${be};`,Y={},K=(G,ee)=>{y.broadcastedIndicesToOffset=!0;let be=`${ee.name}broadcastedIndicesTo${e}Offset`;if(be in Y)return`${be}(${G})`;let et=[];for(let ze=u-1;ze>=0;ze--){let Ue=ee.indicesGet("outputIndices",ze+ee.rank-u);et.push(`${N($,ze)} * (${Ue} % ${N(I,ze)})`)}return Y[be]=`fn ${be}(outputIndices: ${ee.type.indices}) -> u32 {\n return ${et.length>0?et.join("+"):"0u"};\n }`,`${be}(${G})`},Q=(G,ee)=>(()=>{if(b.storage===b.value)return`${e}[${G}]=${ee};`;if(b.storage==="vec2"&&b.value==="i32")return`${e}[${G}]=vec2(u32(${ee}), select(0u, 0xFFFFFFFFu, ${ee} < 0));`;if(b.storage==="vec2"&&b.value==="u32")return`${e}[${G}]=vec2(u32(${ee}), 0u);`;if(b.storage==="u32"&&b.value==="vec4")return`${e}[${G}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${ee}));`;throw new Error(`not supported combination of storage type ${b.storage} and value type ${b.value} yet`)})(),Z=G=>(()=>{if(b.storage===b.value)return`${e}[${G}]`;if(b.storage==="vec2"&&b.value==="i32")return`i32(${e}[${G}].x)`;if(b.storage==="vec2"&&b.value==="u32")return`u32(${e}[${G}].x)`;if(b.storage==="u32"&&b.value==="vec4")return`vec4(bool(${e}[${G}] & 0xFFu), bool(${e}[${G}] & 0xFF00u), bool(${e}[${G}] & 0xFF0000u), bool(${e}[${G}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${b.storage} and value type ${b.value} yet`)})(),Ee=u<2?"":`\n fn get_${e}ByIndices(indices: ${b.indices}) -> ${h} {\n return ${Z(`i2o_${e}(indices)`)};\n }`,Pe=u<2?"":(()=>{let G=l.map(be=>`d${be}: u32`).join(", "),ee=l.map(be=>`d${be}`).join(", ");return`\n fn get_${e}(${G}) -> ${h} {\n return get_${e}ByIndices(${T(ee)});\n }`})(),fe=(...G)=>{if(G.length!==u)throw new Error(`indices length must be ${u}`);let ee=G.map(w).join(",");return u===0?Z("0u"):u===1?Z(ee[0]):(y.get=!0,y.getByIndices=!0,y.indicesToOffset=!0,`get_${e}(${ee})`)},Ie=G=>u<2?Z(G):(y.getByIndices=!0,y.indicesToOffset=!0,`get_${e}ByIndices(${G})`),he=u<2?"":`\n fn set_${e}ByIndices(indices: ${b.indices}, value: ${h}) {\n ${Q(`i2o_${e}(indices)`,"value")}\n }`,ye=u<2?"":(()=>{let G=l.map(be=>`d${be}: u32`).join(", "),ee=l.map(be=>`d${be}`).join(", ");return`\n fn set_${e}(${G}, value: ${h}) {\n set_${e}ByIndices(${T(ee)}, value);\n }`})();return{impl:()=>{let G=[],ee=!1;return y.offsetToIndices&&(G.push(E),ee=!0),y.indicesToOffset&&(G.push(R),ee=!0),y.broadcastedIndicesToOffset&&(Object.values(Y).forEach(be=>G.push(be)),ee=!0),y.set&&(G.push(ye),ee=!0),y.setByIndices&&(G.push(he),ee=!0),y.get&&(G.push(Pe),ee=!0),y.getByIndices&&(G.push(Ee),ee=!0),!s&&ee&&G.unshift(`const ${I} = ${b.indices}(${r.join(",")});`,`const ${$} = ${b.indices}(${U.computeStrides(r).join(",")});`),G.join(`\n`)},type:b,offsetToIndices:A,indicesToOffset:V,broadcastedIndicesToOffset:K,indices:T,indicesGet:N,indicesSet:te,set:(...G)=>{if(G.length!==u+1)throw new Error(`indices length must be ${u}`);let ee=G[u];if(typeof ee!="string")throw new Error("value must be string");let be=G.slice(0,u).map(w).join(",");return u===0?Q("0u",ee):u===1?Q(be[0],ee):(y.set=!0,y.setByIndices=!0,y.indicesToOffset=!0,`set_${e}(${be}, ${ee})`)},setByOffset:Q,setByIndices:(G,ee)=>u<2?Q(G,ee):(y.setByIndices=!0,y.indicesToOffset=!0,`set_${e}ByIndices(${G}, ${ee});`),get:fe,getByOffset:Z,getByIndices:Ie,usage:o,name:e,strides:$,shape:I,rank:u}},M=(e,t,r,o=1)=>Dn(e,t,r,"input",o),F=(e,t,r,o=1)=>Dn(e,t,r,"output",o),Fr=(e,t,r,o=1)=>Dn(e,t,r,"internal",o),Rn=class{constructor(t){this.normalizedDispatchGroup=t;this.internalVariables=[];this.variables=[];this.uniforms=[];this.variableIndex=0}guardAgainstOutOfBoundsWorkgroupSizes(t){return`if (global_idx >= ${typeof t=="number"?`${t}u`:t}) { return; }`}mainStart(t=md){let r=typeof t=="number"?t:t[0],o=typeof t=="number"?1:t[1],n=typeof t=="number"?1:t[2],s=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1,u=s?`@builtin(global_invocation_id) global_id : vec3,\n @builtin(workgroup_id) workgroup_id : vec3,\n @builtin(local_invocation_id) local_id : vec3`:`@builtin(local_invocation_id) local_id : vec3,\n @builtin(local_invocation_index) local_idx : u32,\n @builtin(workgroup_id) workgroup_id : vec3,\n @builtin(num_workgroups) num_workgroups : vec3`,l=s?"let global_idx = global_id.x; let local_idx = local_id.x;":`let global_idx = (workgroup_id.z * num_workgroups[0] * num_workgroups[1] +\n workgroup_id.y * num_workgroups[0] + workgroup_id.x) * ${r*o*n}u + local_idx;`;return`@compute @workgroup_size(${r}, ${o}, ${n})\n fn main(${u}) {\n ${l}\n `}appendVariableUniforms(t){t.rank!==0&&(t.shape.startsWith("uniforms.")&&this.uniforms.push({name:t.shape.replace("uniforms.",""),type:"u32",length:t.rank}),t.strides.startsWith("uniforms.")&&this.uniforms.push({name:t.strides.replace("uniforms.",""),type:"u32",length:t.rank}))}declareVariable(t,r){if(t.usage==="internal")throw new Error("cannot use internal variable with declareVariable(). use registerInternalVariables() instead.");this.variables.push(t),this.appendVariableUniforms(t);let o=t.usage==="input"?"read":"read_write",n=t.type.storage;return`@group(0) @binding(${r}) var ${t.name}: array<${n}>;`}declareVariables(...t){return t.map(r=>this.declareVariable(r,this.variableIndex++)).join(`\n`)}registerInternalVariable(t){if(t.usage!=="internal")throw new Error("cannot use input or output variable with registerInternalVariable(). use declareVariables() instead.");this.internalVariables.push(t),this.appendVariableUniforms(t)}registerInternalVariables(...t){return t.forEach(r=>this.registerInternalVariable(r)),this}registerUniform(t,r,o=1){return this.uniforms.push({name:t,type:r,length:o}),this}registerUniforms(t){return this.uniforms=this.uniforms.concat(t),this}uniformDeclaration(){if(this.uniforms.length===0)return"";let t=[];for(let{name:r,type:o,length:n}of this.uniforms)if(n&&n>4)t.push(`${r}:array, ${Math.ceil(n/4)}>`);else{let s=n==null||n===1?o:`vec${n}<${o}>`;t.push(`${r}:${s}`)}return`\n struct Uniforms { ${t.join(", ")} };\n @group(0) @binding(${this.variableIndex}) var uniforms: Uniforms;`}get additionalImplementations(){return this.uniformDeclaration()+this.variables.map(t=>t.impl()).join(`\n`)+this.internalVariables.map(t=>t.impl()).join(`\n`)}},ma=e=>new Rn(e),Ft=(e,t)=>{let r=e.length,o=[];for(let n=0;n1&&u===1&&o.unshift(s)}return o},Re=e=>!0});var fd,fa,hd,gd,it,ha,ga,jt=j(()=>{"use strict";$e();je();ve();fd=e=>{if(!e||e.length!==1)throw new Error("Transpose requires 1 input.")},fa=(e,t)=>t&&t.length!==e?[...new Array(e).keys()].reverse():t,hd=(e,t)=>U.sortBasedOnPerm(e,fa(e.length,t)),gd=(e,t,r,o)=>{let n=[];n.push(`fn perm(i: ${o.type.indices}) -> ${r.type.indices} {\n var a: ${r.type.indices};`);for(let s=0;s{let r=e.dataType,o=e.dims.length,n=fa(o,t),s=Re(o),u=hd(e.dims,n),l=s?u.length:u,a=s?o:e.dims,p=F("output",r,l),h=M("a",r,a),g=b=>`\n ${b.registerUniform("output_size","u32").declareVariables(h,p)}\n\n ${gd(n,o,h,p)}\n\n ${b.mainStart()}\n ${b.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n\n let indices = ${p.offsetToIndices("global_idx")};\n let aIndices = perm(indices);\n\n ${p.setByOffset("global_idx",h.getByIndices("aIndices"))}\n }`;return{name:"Transpose",shaderCache:{hint:`${t}`,inputDependencies:s?["rank"]:["dims"]},getRunData:b=>{let w=U.size(u);return{outputs:[{dims:u,dataType:b[0].dataType}],dispatchGroup:{x:Math.ceil(w/64)},programUniforms:s?[{type:"uint32",data:w},...L(b[0].dims),...L(u)]:[{type:"uint32",data:w}]}},getShaderSource:g}},ha=(e,t)=>{fd(e.inputs),e.compute(it(e.inputs[0],t.perm))},ga=e=>ge({perm:e.perm})});var yd,bd,wd,vd,$d,Sd,xd,_d,Cd,Id,ct,ya,ba,wa,va,$a,Sa,xa,_a,Ca,Ia,Aa=j(()=>{"use strict";$e();ve();jr();jt();yd={max:"select(bestValue, candidate, candidate > bestValue)",min:"select(bestValue, candidate, candidate < bestValue)",mean:"bestValue + candidate",sum:"bestValue + candidate",prod:"bestValue * candidate",sumSquare:"bestValue + candidate * candidate",logSumExp:"bestValue + exp(candidate)",l1:"bestValue + abs(candidate)",l2:"bestValue + candidate * candidate",logSum:"bestValue + candidate"},bd={max:"select(bestValue, candidate, candidate > bestValue)",min:"select(bestValue, candidate, candidate < bestValue)",mean:"bestValue + candidate",sum:"bestValue + candidate",prod:"bestValue * candidate",sumSquare:"bestValue + candidate",logSumExp:"bestValue + candidate",l1:"bestValue + candidate",l2:"bestValue + candidate",logSum:"bestValue + candidate"},wd={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},vd={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},$d=(e,t)=>{let r=[];for(let o=t-e;o{let r=[],o=e.length;for(let s=0;se[s]);return[r,n]},xd=(e,t)=>{let r=e.length+t.length,o=[],n=0;for(let s=0;s{for(let r=0;r{let r=[];if(!_d(e,t)){for(let o=0;or.push(o))}return r},Id=(e,t,r,o,n,s,u)=>{let l=r[0].dims,a=U.size(s),p=U.size(u),h=M("_A",r[0].dataType,l),g=F("output",n,s),b=32,w=`\n var aBestValues : array<${g.type.storage}, ${b}>;\n `;return{name:e,shaderCache:t,getShaderSource:_=>`\n ${_.registerUniform("reduceSize","u32").declareVariables(h,g)}\n ${w}\n fn DIV_CEIL(a : u32, b : u32) -> u32 {\n return ((a - 1u) / b + 1u);\n }\n ${_.mainStart(b)}\n\n let outputIndex = global_idx / ${b};\n let offset = outputIndex * uniforms.reduceSize;\n\n var bestValue = ${g.type.storage}(${wd[o]});\n let Length = uniforms.reduceSize;\n for (var k = local_idx; k < Length; k = k + ${b}) {\n let candidate = ${g.type.storage}(${h.getByOffset("offset + k")});\n bestValue = ${yd[o]};\n }\n aBestValues[local_idx] = bestValue;\n workgroupBarrier();\n\n var reduceSize = min(Length, ${b}u);\n for (var currentSize = reduceSize / 2u; reduceSize > 1u;\n currentSize = reduceSize / 2u) {\n let interval = DIV_CEIL(reduceSize, 2u);\n if (local_idx < currentSize) {\n let candidate = aBestValues[local_idx + interval];\n bestValue = ${bd[o]};\n aBestValues[local_idx] = bestValue;\n }\n reduceSize = interval;\n workgroupBarrier();\n }\n\n if (local_idx == 0u) {\n ${g.setByOffset("outputIndex",`${o==="mean"?`bestValue / ${g.type.storage}(uniforms.reduceSize)`:`${vd[o]}`}`)};\n }\n }`,getRunData:()=>({outputs:[{dims:s,dataType:n}],dispatchGroup:{x:a},programUniforms:[{type:"uint32",data:p}]})}},ct=(e,t,r,o)=>{let n=e.inputs.length===1?r:Mn(e.inputs,r),s=n.axes;s.length===0&&!n.noopWithEmptyAxes&&(s=e.inputs[0].dims.map((w,y)=>y));let u=U.normalizeAxes(s,e.inputs[0].dims.length),l=u,a=e.inputs[0],p=Cd(l,e.inputs[0].dims.length);p.length>0&&(a=e.compute(it(e.inputs[0],p),{inputs:[0],outputs:[-1]})[0],l=$d(l.length,a.dims.length));let[h,g]=Sd(a.dims,l),b=h;n.keepDims&&(b=xd(h,u)),e.compute(Id(t,{hint:n.cacheKey,inputDependencies:["type"]},[a],o,e.inputs[0].dataType,b,g),{inputs:[a]})},ya=(e,t)=>{ct(e,"ReduceMeanShared",t,"mean")},ba=(e,t)=>{ct(e,"ReduceL1Shared",t,"l1")},wa=(e,t)=>{ct(e,"ReduceL2Shared",t,"l2")},va=(e,t)=>{ct(e,"ReduceLogSumExpShared",t,"logSumExp")},$a=(e,t)=>{ct(e,"ReduceMaxShared",t,"max")},Sa=(e,t)=>{ct(e,"ReduceMinShared",t,"min")},xa=(e,t)=>{ct(e,"ReduceProdShared",t,"prod")},_a=(e,t)=>{ct(e,"ReduceSumShared",t,"sum")},Ca=(e,t)=>{ct(e,"ReduceSumSquareShared",t,"sumSquare")},Ia=(e,t)=>{ct(e,"ReduceLogSumShared",t,"logSum")}});var pt,Ad,qr,Mn,mt,Td,Ed,Od,Pd,kd,Rd,Bd,Dd,Md,zd,ft,Ta,Ea,Oa,Pa,ka,Ra,Ba,Da,Ma,za,jr=j(()=>{"use strict";$e();je();ve();Aa();pt=e=>{if(!e||e.length===0||e.length>2)throw new Error("Reduce op requires 1 or 2 inputs.");if(e.length===2&&e[1].dims.length!==1)throw new Error("Invalid axes input dims.")},Ad=e=>["","",`var value = ${e.getByIndices("input_indices")};`,""],qr=(e,t,r,o,n,s,u=!1,l=!1)=>{let a=[],p=r[0].dims,h=p.length,g=U.normalizeAxes(n,h),b=!l&&g.length===0;p.forEach((I,$)=>{b||g.indexOf($)>=0?u&&a.push(1):a.push(I)});let w=a.length,y=U.size(a);return{name:e,shaderCache:t,getShaderSource:I=>{let $=[],x=M("_A",r[0].dataType,h),E=F("output",s,w),A=o(x,E,g),z=A[2];for(let R=0,V=0;R=0?(u&&V++,z=`for(var j${R}: u32 = 0; j${R} < ${p[R]}; j${R}++) {\n ${A[2].includes("last_index")?`let last_index = j${R};`:""}\n ${x.indicesSet("input_indices",R,`j${R}`)}\n ${z}\n }`):($.push(`${x.indicesSet("input_indices",R,E.indicesGet("output_indices",V))};`),V++);return`\n\n ${I.registerUniform("output_size","u32").declareVariables(x,E)}\n\n ${I.mainStart()}\n ${I.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n var input_indices: ${x.type.indices};\n let output_indices = ${E.offsetToIndices("global_idx")};\n\n ${$.join(`\n`)}\n ${A[0]} // init ops for reduce max/min\n ${A[1]}\n ${z}\n ${A[3]}\n ${A.length===4?E.setByOffset("global_idx","value"):A.slice(4).join(`\n`)}\n }`},getRunData:()=>({outputs:[{dims:a,dataType:s}],dispatchGroup:{x:Math.ceil(y/64)},programUniforms:[{type:"uint32",data:y},...L(p),...L(a)]})}},Mn=(e,t)=>{let r=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach(o=>r.push(Number(o))),ge({axes:r,keepDims:t.keepDims,noopWithEmptyAxes:t.noopWithEmptyAxes})},mt=(e,t,r,o)=>{let n=e.inputs,s=n.length===1?r:Mn(n,r);e.compute(qr(t,{hint:s.cacheKey,inputDependencies:["rank"]},[n[0]],s.noopWithEmptyAxes&&s.axes.length===0?Ad:o,s.axes,n[0].dataType,s.keepDims,s.noopWithEmptyAxes),{inputs:[0]})},Td=(e,t)=>{pt(e.inputs),mt(e,"ReduceLogSum",t,(o,n)=>[`var value = ${n.type.storage}(0);`,"",`value += ${o.getByIndices("input_indices")};`,"value = log(value);"])},Ed=(e,t)=>{pt(e.inputs),mt(e,"ReduceL1",t,(o,n)=>[`var value = ${n.type.storage}(0);`,"",`value += abs(${o.getByIndices("input_indices")});`,""])},Od=(e,t)=>{pt(e.inputs),mt(e,"ReduceL2",t,(o,n)=>[`var t = ${n.type.value}(0); var value = ${n.type.value}(0);`,"",`t = ${o.getByIndices("input_indices")}; value += (t * t);`,"value = sqrt(value);"])},Pd=(e,t)=>{pt(e.inputs),mt(e,"ReduceLogSumExp",t,(o,n)=>[`var value = ${n.type.storage}(0);`,"",`value += exp(${o.getByIndices("input_indices")});`,"value = log(value);"])},kd=(e,t)=>{pt(e.inputs),mt(e,"ReduceMax",t,(o,n,s)=>{let u=[];for(let l=0;l=0||s.length===0)&&u.push(o.indicesSet("input_indices",l,0));return[`${u.join(`\n`)}`,`var value = ${o.getByIndices("input_indices")};`,`value = max(value, ${o.getByIndices("input_indices")});`,""]})},Rd=(e,t)=>{pt(e.inputs),mt(e,"ReduceMean",t,(o,n,s)=>{let u=1;for(let l=0;l=0||s.length===0)&&(u*=e.inputs[0].dims[l]);return["var sum = f32(0);","",`sum += f32(${o.getByIndices("input_indices")});`,`let value = ${n.type.value}(sum / ${u});`]})},Bd=(e,t)=>{pt(e.inputs),mt(e,"ReduceMin",t,(o,n,s)=>{let u=[];for(let l=0;l=0||s.length===0)&&u.push(`input_indices[${l}] = 0;`);return[`${u.join(`\n`)}`,`var value = ${o.getByIndices("input_indices")};`,`value = min(value, ${o.getByIndices("input_indices")});`,""]})},Dd=(e,t)=>{pt(e.inputs),mt(e,"ReduceProd",t,(o,n)=>[`var value = ${n.type.storage}(1);`,"",`value *= ${o.getByIndices("input_indices")};`,""])},Md=(e,t)=>{pt(e.inputs),mt(e,"ReduceSum",t,(o,n)=>[`var value = ${n.type.storage}(0);`,"",`value += ${o.getByIndices("input_indices")};`,""])},zd=(e,t)=>{pt(e.inputs),mt(e,"ReduceSumSquare",t,(o,n)=>[`var t = ${n.type.value}(0); var value = ${n.type.value}(0);`,"",`t = ${o.getByIndices("input_indices")}; value += t * t;`,""])},ft=(e,t,r)=>{if(t.length===0)return r;let o=1,n=1;for(let s=0;s1024},Ta=(e,t)=>{ft(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Rd(e,t):ya(e,t)},Ea=(e,t)=>{ft(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Ed(e,t):ba(e,t)},Oa=(e,t)=>{ft(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Od(e,t):wa(e,t)},Pa=(e,t)=>{ft(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Pd(e,t):va(e,t)},ka=(e,t)=>{ft(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?kd(e,t):$a(e,t)},Ra=(e,t)=>{ft(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Bd(e,t):Sa(e,t)},Ba=(e,t)=>{ft(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Dd(e,t):xa(e,t)},Da=(e,t)=>{ft(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Md(e,t):_a(e,t)},Ma=(e,t)=>{ft(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?zd(e,t):Ca(e,t)},za=(e,t)=>{ft(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Td(e,t):Ia(e,t)}});var Ua,Va,Na,zn,Wa=j(()=>{"use strict";Ne();je();jr();Ua=e=>{if(!e||e.length===0||e.length>2)throw new Error("ArgMinMaxOp op requires 1 or 2 inputs.");if(e[0].dataType!==1)throw new Error("Invalid input type.")},Va=(e,t)=>{Ua(e.inputs);let r=(o,n,s)=>{let u=[];for(let l=0;l=0||s.length===0)&&u.push(`input_indices[${l}] = 0;`);return[`${u.join(`\n`)}`,`var value = ${o.getByIndices("input_indices")};\nvar best_index : i32 = 0;`,`if (${o.getByIndices("input_indices")} ${t.selectLastIndex>0?"<=":"<"} value) {\n value = ${o.getByIndices("input_indices")};\n best_index = i32(last_index);\n }`,"",n.setByOffset("global_idx","best_index")]};e.compute(qr("ArgMin",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],r,[t.axis],7,t.keepDims),{inputs:[0]})},Na=(e,t)=>{Ua(e.inputs);let r=(o,n,s)=>{let u=[];for(let l=0;l=0||s.length===0)&&u.push(`input_indices[${l}] = 0;`);return[`${u.join(`\n`)}`,`var value = ${o.getByIndices("input_indices")};\nvar best_index : i32 = 0;`,`if (${o.getByIndices("input_indices")} ${t.selectLastIndex>0?">=":">"} value) {\n value = ${o.getByIndices("input_indices")};\n best_index = i32(last_index);\n }`,"",n.setByOffset("global_idx","best_index")]};e.compute(qr("argMax",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],r,[t.axis],7,t.keepDims),{inputs:[0]})},zn=e=>ge(e)});var Ud,Vd,Nd,Wd,Kr,Hd,Ha,Un=j(()=>{"use strict";Ne();Nr();ve();Ud=(e,t)=>{let r=e[0],o=e[1],n=e[2],s=e[3],u=e[4],l=e[5];if(u&&l)throw new Error("Attention cannot have both past and relative_position_bias");if(r.dims.length!==3)throw new Error(\'Input "input" must have 3 dimensions\');let a=r.dims[0],p=r.dims[1],h=r.dims[2];if(n.dims.length!==1)throw new Error(\'Input "bias" is expected to have 1 dimensions\');if(o.dims.length!==2)throw new Error(\'Input "weights" is expected to have 2 dimensions\');if(o.dims[0]!==h)throw new Error("Input 1 dimension 0 should have same length as dimension 2 of input 0");if(n.dims[0]!==o.dims[1])throw new Error(\'Input "bias" dimension 0 should have same length as dimension 1 of input "weights"\');let g=n.dims[0]/3,b=g,w=b;if(t.qkvHiddenSizes.length>0){if(t.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let E of t.qkvHiddenSizes)if(E%t.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");g=t.qkvHiddenSizes[0],b=t.qkvHiddenSizes[1],w=t.qkvHiddenSizes[2]}let y=p;if(g!==b)throw new Error("qkv_hidden_sizes first element should be same as the second");if(n.dims[0]!==g+b+w)throw new Error(\'Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes\');let _=0;if(u){if(b!==w)throw new Error(\'Input "past" expect k_hidden_size == v_hidden_size\');if(u.dims.length!==5)throw new Error(\'Input "past" must have 5 dimensions\');if(u.dims[0]!==2)throw new Error(\'Input "past" first dimension must be 2\');if(u.dims[1]!==a)throw new Error(\'Input "past" second dimension must be batch_size\');if(u.dims[2]!==t.numHeads)throw new Error(\'Input "past" third dimension must be num_heads\');if(u.dims[4]!==b/t.numHeads)throw new Error(\'Input "past" fifth dimension must be k_hidden_size / num_heads\');t.pastPresentShareBuffer||(_=u.dims[3])}let I=y+_,$=-1,x=0;if(s)throw new Error("Mask not supported");if(u)throw new Error("past is not supported");if(l)throw new Error("relativePositionBias is not supported");return{batchSize:a,sequenceLength:p,pastSequenceLength:_,kvSequenceLength:y,totalSequenceLength:I,maxSequenceLength:$,inputHiddenSize:h,hiddenSize:g,vHiddenSize:w,headSize:Math.floor(g/t.numHeads),vHeadSize:Math.floor(w/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:x,scale:t.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},Vd=(e,t,r,o)=>{let n=Fe(o),s=64,u=o/n;u{let w=F("x",t.dataType,t.dims,n),y="thread_max_vector";n===2?y="max(thread_max_vector.x, thread_max_vector.y)":n===4&&(y="max(max(thread_max_vector.x, thread_max_vector.y), max(thread_max_vector.z, thread_max_vector.w))");let _=lt(t.dataType),I=[{name:"d_inv",type:_},{name:"d_comp",type:"u32"},{name:"elements_per_wg",type:"u32"}];return`\n var wgMax: array;\n var wgSum: array;\n ${b.registerUniforms(I).declareVariables(w)}\n ${b.mainStart([s,1,1])}\n let localOffset = local_idx * uniforms.elements_per_wg;\n let offset: u32 = workgroup_id.x * uniforms.d_comp + localOffset;\n\n var thread_max_vector = ${Ze("f32",n,"-3.402823e+38f")};\n for (var i: u32 = 0; i < uniforms.elements_per_wg && i + localOffset < uniforms.d_comp; i++) {\n thread_max_vector = max(${at(_,n,"x[offset + i]")}, thread_max_vector);\n }\n wgMax[local_idx] = ${y};\n workgroupBarrier();\n\n var maxValue = -3.402823e+38f;\n for (var i = 0u; i < ${s}; i++) {\n maxValue = max(wgMax[i], maxValue);\n }\n\n var sumVector = ${Ze("f32",n,"0")};\n for (var i: u32 = 0; i < uniforms.elements_per_wg && i + localOffset < uniforms.d_comp; i++) {\n sumVector += exp(${at(_,n,"x[offset + i]")} - maxValue);\n }\n wgSum[local_idx] = ${Je("sumVector",n)};\n workgroupBarrier();\n\n var sum: f32 = 0;\n for (var i = 0u; i < ${s}; i++) {\n sum += wgSum[i];\n }\n\n if (sum == 0) {\n for (var i: u32 = 0; i < uniforms.elements_per_wg && i + localOffset < uniforms.d_comp; i++) {\n x[offset + i] = ${Ze("f32",n,"uniforms.d_inv")};\n }\n } else {\n for (var i: u32 = 0; i < uniforms.elements_per_wg && i + localOffset < uniforms.d_comp; i++) {\n let f32input = ${at(_,n,"x[offset + i]")};\n x[offset + i] = ${w.type.value}(exp(f32input - maxValue) / sum);\n }\n }\n }`};e.compute({name:"AttentionProbsSoftmax",shaderCache:{hint:`${s};${h};${n}`},getShaderSource:g,getRunData:()=>({outputs:[],dispatchGroup:{x:r},programUniforms:p})},{inputs:[t],outputs:[]})},Nd=(e,t,r,o,n,s)=>{let u=[n.batchSize,n.numHeads,n.sequenceLength,n.kvSequenceLength+n.pastSequenceLength],l=s.scale===0?1/Math.sqrt(n.headSize):s.scale,a=Fe(n.headSize),p=n.headSize/a,h=12,g={x:Math.ceil(n.totalSequenceLength/h),y:Math.ceil(n.sequenceLength/h),z:n.batchSize*n.numHeads},b=Xe(t.dataType),w=[{type:"uint32",data:n.sequenceLength},{type:"uint32",data:p},{type:"uint32",data:n.totalSequenceLength},{type:"uint32",data:n.kvSequenceLength},{type:b,data:l}],y=[t,r],_=$=>{let x=M("q",t.dataType,t.dims,a),E=M("key",r.dataType,r.dims,a),A=F("output",t.dataType,u),z=Le(t.dataType),R=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"kv_sequence_length",type:"u32"},{name:"alpha",type:z}];return`\n const beta: ${z} = 1.0;\n const TILE_SIZE = ${h}u;\n\n var tileQ: array<${x.type.storage}, ${h*h}>;\n var tileK: array<${x.type.storage}, ${h*h}>;\n ${$.registerUniforms(R).declareVariables(x,E,A)}\n ${$.mainStart([h,h,1])}\n // x holds the N and y holds the M\n let headIdx = workgroup_id.z;\n let m = workgroup_id.y * TILE_SIZE;\n let n = workgroup_id.x * TILE_SIZE;\n let lm = m + local_id.y;\n let ln = n + local_id.x;\n\n let qOffset = uniforms.M * uniforms.K * headIdx + m * uniforms.K;\n let kOffset = uniforms.kv_sequence_length * uniforms.K * headIdx + n * uniforms.K;\n\n var value = ${Ze(z,a)};\n for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) {\n if (m + local_id.y < uniforms.M && w + local_id.x < uniforms.K) {\n tileQ[TILE_SIZE * local_id.y + local_id.x] = q[qOffset + local_id.y * uniforms.K + w + local_id.x];\n }\n if (n + local_id.y < uniforms.N && w + local_id.x < uniforms.K) {\n tileK[TILE_SIZE * local_id.y + local_id.x] = key[kOffset + local_id.y * uniforms.K + w + local_id.x];\n }\n workgroupBarrier();\n\n for (var k: u32 = 0u; k({outputs:[{dims:u,dataType:t.dataType,gpuDataType:0}],dispatchGroup:g,programUniforms:w}),getShaderSource:_},{inputs:y,outputs:[-1]})[0];return Vd(e,I,n.batchSize*n.numHeads*n.sequenceLength,n.totalSequenceLength),I},Wd=(e,t,r,o)=>{let n=[o.batchSize,o.sequenceLength,o.vHiddenSize],s=12,u={x:Math.ceil(o.vHeadSize/s),y:Math.ceil(o.sequenceLength/s),z:o.batchSize*o.numHeads},l=[{type:"uint32",data:o.sequenceLength},{type:"uint32",data:o.totalSequenceLength},{type:"uint32",data:o.vHeadSize},{type:"uint32",data:o.numHeads},{type:"uint32",data:o.vHiddenSize}],a=p=>{let h=M("probs",t.dataType,t.dims),g=M("v",r.dataType,r.dims),b=F("output",t.dataType,n),w=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"v_hidden_size",type:"u32"}];return`\n const TILE_SIZE = ${s}u;\n var tileQ: array<${h.type.value}, ${s*s}>;\n var tileK: array<${h.type.value}, ${s*s}>;\n ${p.registerUniforms(w).declareVariables(h,g,b)}\n ${p.mainStart([s,s,1])}\n let headIdx = workgroup_id.z;\n let m = workgroup_id.y * TILE_SIZE + local_id.y;\n let n = workgroup_id.x * TILE_SIZE + local_id.x;\n\n let offsetA = headIdx * (uniforms.M * uniforms.K) + m * uniforms.K;\n let offsetB = headIdx * (uniforms.N * uniforms.K) + n;\n\n var value = ${h.type.storage}(0);\n for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) {\n if (m < uniforms.M && w + local_id.x < uniforms.K) {\n tileQ[TILE_SIZE * local_id.y + local_id.x] = probs[offsetA + w + local_id.x];\n }\n if (n < uniforms.N && w + local_id.y < uniforms.K) {\n tileK[TILE_SIZE * local_id.y + local_id.x] = v[offsetB + (w + local_id.y) * uniforms.N];\n }\n workgroupBarrier();\n for (var k: u32 = 0u; k({outputs:[{dims:n,dataType:t.dataType,gpuDataType:0}],dispatchGroup:u,programUniforms:l}),getShaderSource:a},{inputs:[t,r],outputs:[0]})[0]},Kr=(e,t,r,o,n,s,u,l,a,p,h)=>{let g=Nd(e,t,r,a,p,h);Wd(e,g,o,p)},Hd=(e,t)=>{let r=[t.batchSize,t.numHeads,t.sequenceLength,t.headSize],o=t.sequenceLength,n=t.inputHiddenSize,s=t.headSize,u=12,l={x:Math.ceil(t.headSize/u),y:Math.ceil(t.sequenceLength/u),z:t.batchSize*t.numHeads},a=[e.inputs[0],e.inputs[1],e.inputs[2]],p=[{type:"uint32",data:o},{type:"uint32",data:n},{type:"uint32",data:s},{type:"uint32",data:t.numHeads},{type:"uint32",data:t.headSize},{type:"uint32",data:t.hiddenSize},{type:"uint32",data:t.hiddenSize+t.hiddenSize+t.vHiddenSize}],h=g=>{let b=F("output_q",a[0].dataType,r),w=F("output_k",a[0].dataType,r),y=F("output_v",a[0].dataType,r),_=M("input",a[0].dataType,a[0].dims),I=M("weight",a[1].dataType,a[1].dims),$=M("bias",a[2].dataType,a[2].dims),x=_.type.storage,E=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"hidden_size",type:"u32"},{name:"ldb",type:"u32"}];return`\n const TILE_SIZE = ${u}u;\n var tileInput: array<${x}, ${u*u}>;\n var tileWeightQ: array<${x}, ${u*u}>;\n var tileWeightK: array<${x}, ${u*u}>;\n var tileWeightV: array<${x}, ${u*u}>;\n ${g.registerUniforms(E).declareVariables(_,I,$,b,w,y)}\n ${g.mainStart([u,u,1])}\n let batchIndex = workgroup_id.z / uniforms.num_heads;\n let headNumber = workgroup_id.z % uniforms.num_heads;\n let m = workgroup_id.y * TILE_SIZE + local_id.y;\n let n = workgroup_id.x * TILE_SIZE + local_id.x;\n\n let inputOffset = batchIndex * (uniforms.M * uniforms.K) + m * uniforms.K;\n let biasOffsetQ = headNumber * uniforms.head_size;\n let biasOffsetK = uniforms.hidden_size + biasOffsetQ;\n let biasOffsetV = uniforms.hidden_size + biasOffsetK;\n\n var valueQ = ${x}(0);\n var valueK = ${x}(0);\n var valueV = ${x}(0);\n for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) {\n if (m < uniforms.M && w + local_id.x < uniforms.K) {\n tileInput[TILE_SIZE * local_id.y + local_id.x] = input[inputOffset + w + local_id.x];\n }\n if (n < uniforms.N && w + local_id.y < uniforms.K) {\n let offset = n + (w + local_id.y) * uniforms.ldb;\n tileWeightQ[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetQ + offset];\n tileWeightK[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetK + offset];\n tileWeightV[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetV + offset];\n }\n workgroupBarrier();\n for (var k: u32 = 0u; k({outputs:[{dims:r,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:r,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:r,dataType:e.inputs[0].dataType,gpuDataType:0}],dispatchGroup:l,programUniforms:p}),getShaderSource:h},{inputs:a,outputs:[-1,-1,-1]})},Ha=(e,t)=>{let r=Ud(e.inputs,t),[o,n,s]=Hd(e,r);return Kr(e,o,n,s,e.inputs[4],void 0,void 0,void 0,e.inputs[5],r,t)}});var Gd,Ld,Fd,Ga,La=j(()=>{"use strict";Lt();$e();je();ve();Gd=(e,t)=>{if(!e||e.length!==5)throw new Error("BatchNormalization requires 5 inputs");let r=(o,n,s)=>{let u=n.length;if(u!==o.length)throw new Error(`${s}: num dimensions != ${u}`);n.forEach((l,a)=>{if(l!==o[a])throw new Error(`${s}: dim[${a}] do not match`)})};if(e[0].dims.length>1){let o=t.format==="NHWC"?t.spatial?e[0].dims.slice(-1):e[0].dims.slice(-1).concat(e[0].dims.slice(1,e[0].dims.length-1)):e[0].dims.slice(1,t.spatial?2:void 0);r(e[1].dims,o,"Invalid input scale"),r(e[2].dims,o,"Invalid input B"),r(e[3].dims,o,"Invalid input mean"),r(e[4].dims,o,"Invalid input var")}else r(e[1].dims,[1],"Invalid input scale"),r(e[2].dims,[1],"Invalid input B"),r(e[3].dims,[1],"Invalid input mean"),r(e[4].dims,[1],"Invalid input var")},Ld=(e,t)=>{let{epsilon:r,spatial:o,format:n}=t,s=e[0].dims,u=o?Fe(s[s.length-1]):1,l=n==="NHWC"&&s.length>1?u:1,a=U.size(s)/u,p=Re(s.length)&&o,h=p?s.length:s,g=M("x",e[0].dataType,e[0].dims,u),b=M("scale",e[1].dataType,e[1].dims,l),w=M("bias",e[2].dataType,e[2].dims,l),y=M("inputMean",e[3].dataType,e[3].dims,l),_=M("inputVar",e[4].dataType,e[4].dims,l),I=F("y",e[0].dataType,h,u),$=()=>{let E="";if(o)E=`let cOffset = ${s.length===1?"0u":n==="NHWC"?`outputIndices[${s.length-1}] / ${u}`:"outputIndices[1]"};`;else if(n==="NCHW")E=`\n ${I.indicesSet("outputIndices","0","0")}\n let cOffset = ${I.indicesToOffset("outputIndices")};`;else{E=`var cIndices = ${b.type.indices}(0);\n cIndices[0] = outputIndices[${s.length-1}];`;for(let A=1;A`\n const epsilon = ${r};\n ${E.registerUniform("outputSize","u32").declareVariables(g,b,w,y,_,I)}\n ${E.mainStart()}\n ${E.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n var outputIndices = ${I.offsetToIndices(`global_idx * ${u}`)};\n ${$()}\n let scale = ${b.getByOffset("cOffset")};\n let bias = ${w.getByOffset("cOffset")};\n let inputMean = ${y.getByOffset("cOffset")};\n let inputVar = ${_.getByOffset("cOffset")};\n let x = ${g.getByOffset("global_idx")};\n let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias;\n ${I.setByOffset("global_idx","value")}\n }`;return{name:"BatchNormalization",shaderCache:{hint:`${t.epsilon}_${t.format}_${o}_${u}`,inputDependencies:p?["rank","type","type","type","type"]:void 0},getShaderSource:x,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:p?[{type:"uint32",data:a},...L(s)]:[{type:"uint32",data:a}]})}},Fd=e=>ge(e),Ga=(e,t)=>{let{inputs:r,outputCount:o}=e,n=Fd({...t,outputCount:o});if(Gt.webgpu.validateInputContent&&Gd(r,n),t.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");e.compute(Ld(r,n))}});var jd,qd,Fa,ja=j(()=>{"use strict";$e();ve();jd=e=>{if(e[0].dims.length!==3)throw new Error("input should have 3 dimensions");if(![320,640,1280].includes(e[0].dims[2]))throw new Error("number of channels should be 320, 640 or 1280");if(e[1].dims.length!==1)throw new Error("bias is expected to have 1 dimensions");if(e[0].dims[2]!==e[1].dims[0])throw new Error("last dimension of input and bias are not the same")},qd=e=>{let t=e[0].dims,r=e[0].dims[2],o=U.size(t)/4,n=e[0].dataType,s=M("input",n,t,4),u=M("bias",n,[r],4),l=M("residual",n,t,4),a=F("output",n,t,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(o/64)}}),getShaderSource:h=>`\n const channels = ${r}u / 4;\n ${h.declareVariables(s,u,l,a)}\n\n ${h.mainStart()}\n ${h.guardAgainstOutOfBoundsWorkgroupSizes(o)}\n let value = ${s.getByOffset("global_idx")}\n + ${u.getByOffset("global_idx % channels")} + ${l.getByOffset("global_idx")};\n ${a.setByOffset("global_idx","value")}\n }`}},Fa=e=>{jd(e.inputs),e.compute(qd(e.inputs))}});var Kd,Ae,qa,Ka,Ya,Za,Qa,Xa,Ja,ei,ti,Yd,ri,ni,oi,ai,Yr,ii,Zr,si,ui,di,li,ci,pi,mi,fi,hi,gi,yi,bi,wi,vi,$i,Si,xi,Vn=j(()=>{"use strict";Ne();$e();je();ve();Kd=(e,t,r,o,n,s)=>{let u=Math.ceil(t/4),l="";typeof n=="string"?l=`${n}(a)`:l=n("a");let a=M("inputData",r,[u],4),p=F("outputData",o,[u],4);return`\n ${e.registerUniform("vec_size","u32").declareVariables(a,p)}\n\n ${s??""}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}\n\n let a = ${a.getByOffset("global_idx")};\n ${p.setByOffset("global_idx",l)}\n }`},Ae=(e,t,r,o,n,s=e.dataType)=>({name:t,shaderCache:{hint:n,inputDependencies:["type"]},getShaderSource:u=>Kd(u,U.size(e.dims),e.dataType,s,r,o),getRunData:u=>({outputs:[{dims:e.dims,dataType:s}],dispatchGroup:{x:Math.ceil(U.size(u[0].dims)/64/4)},programUniforms:[{type:"uint32",data:Math.ceil(U.size(e.dims)/4)}]})}),qa=e=>{e.compute(Ae(e.inputs[0],"Abs","abs"))},Ka=e=>{e.compute(Ae(e.inputs[0],"Acos","acos"))},Ya=e=>{e.compute(Ae(e.inputs[0],"Acosh","acosh"))},Za=e=>{e.compute(Ae(e.inputs[0],"Asin","asin"))},Qa=e=>{e.compute(Ae(e.inputs[0],"Asinh","asinh"))},Xa=e=>{e.compute(Ae(e.inputs[0],"Atan","atan"))},Ja=e=>{e.compute(Ae(e.inputs[0],"Atanh","atanh"))},ei=e=>ge(e),ti=(e,t)=>{let r;switch(t.to){case 10:r="vec4";break;case 1:r="vec4";break;case 12:r="vec4";break;case 6:r="vec4";break;case 9:r="vec4";break;default:throw new RangeError(`not supported type (specified in attribute \'to\' from \'Cast\' operator): ${t.to}`)}e.compute(Ae(e.inputs[0],"Cast",r,void 0,t.cacheKey,t.to))},Yd=e=>{let t=e.length>=2&&e[1].data!==0?e[1].getFloat32Array()[0]:Gr,r=e.length>=3&&e[2].data!==0?e[2].getFloat32Array()[0]:Lr;return ge({min:t,max:r})},ri=(e,t)=>{let r=e.inputs.length===1?t:Yd(e.inputs),o=lt(e.inputs[0].dataType);e.compute(Ae(e.inputs[0],"Clip",n=>`clamp(${n}, clip_min_, clip_max_)`,`\n const clip_min_: vec4<${o}> = vec4(${o}(${r.min}));\n const clip_max_: vec4<${o}> = vec4(${o}(${r.max}));\n`,r.cacheKey),{inputs:[0]})},ni=e=>{e.compute(Ae(e.inputs[0],"Ceil","ceil"))},oi=e=>{e.compute(Ae(e.inputs[0],"Cos","cos"))},ai=e=>{e.compute(Ae(e.inputs[0],"Cosh","cosh"))},Yr=e=>ge(e),ii=(e,t)=>{let r=lt(e.inputs[0].dataType);e.compute(Ae(e.inputs[0],"Elu",o=>`elu_vf32(${o})`,`\n const elu_alpha_ = ${r}(${t.alpha});\n\n fn elu_f32(a: ${r}) -> ${r} {\n return select((exp(a) - 1.0) * elu_alpha_, a, a >= 0.0);\n }\n\n fn elu_vf32(v: vec4<${r}>) -> vec4<${r}> {\n return vec4(elu_f32(v.x), elu_f32(v.y), elu_f32(v.z), elu_f32(v.w));\n }`,t.cacheKey))},Zr=(e,t="f32")=>`\nconst r0: ${t} = 0.3275911;\nconst r1: ${t} = 0.254829592;\nconst r2: ${t} = -0.284496736;\nconst r3: ${t} = 1.421413741;\nconst r4: ${t} = -1.453152027;\nconst r5: ${t} = 1.061405429;\n\nfn erf_vf32(v: ${e}) -> ${e} {\n let absv = abs(v);\n let x = 1.0 / (1.0 + r0 * absv);\n return sign(v) * (1.0 - ((((r5 * x + r4) * x + r3) * x + r2) * x + r1) * x * exp(-absv * absv));\n}`,si=e=>{let t=lt(e.inputs[0].dataType);e.compute(Ae(e.inputs[0],"Erf",r=>`erf_vf32(${r})`,Zr(`vec4<${t}>`,t)))},ui=e=>{e.compute(Ae(e.inputs[0],"Exp","exp"))},di=e=>{e.compute(Ae(e.inputs[0],"Floor","floor"))},li=e=>{let t=lt(e.inputs[0].dataType);e.compute(Ae(e.inputs[0],"Gelu",r=>`0.5 * ${r} * (1.0 + erf_vf32(${r} * 0.7071067811865475))`,Zr(`vec4<${t}>`,t)))},ci=(e,t)=>{let r=lt(e.inputs[0].dataType);e.compute(Ae(e.inputs[0],"LeakyRelu",o=>`select(leaky_relu_alpha_ * ${o}, ${o}, ${o} >= vec4<${r}>(0.0))`,`const leaky_relu_alpha_ = ${r}(${t.alpha});`,t.cacheKey))},pi=e=>{e.compute(Ae(e.inputs[0],"Not",t=>`!${t}`))},mi=e=>{e.compute(Ae(e.inputs[0],"Neg",t=>`-${t}`))},fi=e=>{e.compute(Ae(e.inputs[0],"Reciprocal",t=>`1.0/${t}`))},hi=e=>{let t=lt(e.inputs[0].dataType);e.compute(Ae(e.inputs[0],"Relu",r=>`select(vec4<${t}>(0.0), ${r}, ${r} > vec4<${t}>(0.0))`))},gi=e=>{e.compute(Ae(e.inputs[0],"Sigmoid",t=>`(1.0 / (1.0 + exp(-${t})))`))},yi=e=>{e.compute(Ae(e.inputs[0],"Sin","sin"))},bi=e=>{e.compute(Ae(e.inputs[0],"Sinh","sinh"))},wi=e=>{e.compute(Ae(e.inputs[0],"Sqrt","sqrt"))},vi=e=>{e.compute(Ae(e.inputs[0],"Tan","tan"))},$i=e=>{e.compute(Ae(e.inputs[0],"Tanh","tanh"))},Si=(e,t)=>{let r=lt(e.inputs[0].dataType);return e.compute(Ae(e.inputs[0],"ThresholdedRelu",o=>`select(vec4<${r}>(0.0), ${o}, ${o} > thresholded_relu_alpha_)`,`const thresholded_relu_alpha_ = vec4<${r}>(${t.alpha});`,t.cacheKey)),0},xi=e=>{e.compute(Ae(e.inputs[0],"Log","log"))}});var Qd,Xd,_i,Ci=j(()=>{"use strict";$e();ve();Vn();Qd=e=>{if(e[0].dims.length!==3)throw new Error("input should have 3 dimensions");if(![2560,5120,10240].includes(e[0].dims[2]))throw new Error("hidden state should be 2560, 5120 or 10240");if(e[1].dims.length!==1)throw new Error("bias is expected to have 1 dimensions");if(e[0].dims[2]!==e[1].dims[0])throw new Error("last dimension of input and bias are not the same")},Xd=e=>{let t=e[0].dims.slice();t[2]=t[2]/2;let r=M("input",e[0].dataType,e[0].dims,4),o=M("bias",e[0].dataType,[e[0].dims[2]],4),n=F("output",e[0].dataType,t,4),s=U.size(t)/4,u=Le(e[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(s/64)}}),getShaderSource:a=>`\n const M_SQRT2 = sqrt(2.0);\n const halfChannels = ${e[0].dims[2]/4/2}u;\n\n ${a.declareVariables(r,o,n)}\n\n ${Zr(`vec4<${u}>`,u)}\n\n ${a.mainStart()}\n ${a.guardAgainstOutOfBoundsWorkgroupSizes(s)}\n let biasIdx = global_idx % halfChannels;\n let batchIndex = global_idx / halfChannels;\n let inputOffset = biasIdx + batchIndex * halfChannels * 2;\n let valueLeft = input[inputOffset] + bias[biasIdx];\n let valueRight = input[inputOffset + halfChannels] + bias[biasIdx + halfChannels];\n let geluRight = valueRight * 0.5 * (erf_vf32(valueRight / M_SQRT2) + 1);\n\n ${n.setByOffset("global_idx","valueLeft * geluRight")}\n }`}},_i=e=>{Qd(e.inputs),e.compute(Xd(e.inputs))}});var Jd,el,ht,Ii,Ai,Ti,Ei,Oi,Pi,ki,Ri,Bi,Di,Mi=j(()=>{"use strict";Ne();$e();ve();Jd=(e,t,r,o,n,s,u,l,a,p,h,g,b)=>{let w,y;typeof l=="string"?w=y=(R,V)=>`${l}((${R}),(${V}))`:typeof l=="function"?w=y=l:(w=l.scalar,y=l.vector);let _=g?t.length:t,I=g?r.length:r,$=g?o.length:o,x=F("outputData",h,$,4),E=M("aData",a,_,4),A=M("bData",p,I,4),z;if(n)if(s){let R=U.size(t)===1,V=U.size(r)===1,T=t.length>0&&t[t.length-1]%4===0,N=r.length>0&&r[r.length-1]%4===0;R||V?z=x.setByOffset("global_idx",y(R?`${E.type.value}(${E.getByOffset("0")}.x)`:E.getByOffset("global_idx"),V?`${A.type.value}(${A.getByOffset("0")}.x)`:A.getByOffset("global_idx"))):z=`\n let outputIndices = ${x.offsetToIndices("global_idx * 4u")};\n let offsetA = ${E.broadcastedIndicesToOffset("outputIndices",x)};\n let offsetB = ${A.broadcastedIndicesToOffset("outputIndices",x)};\n ${x.setByOffset("global_idx",y(u||T?E.getByOffset("offsetA / 4u"):`${E.type.value}(${E.getByOffset("offsetA / 4u")}[offsetA % 4u])`,u||N?A.getByOffset("offsetB / 4u"):`${A.type.value}(${A.getByOffset("offsetB / 4u")}[offsetB % 4u])`))}\n `}else z=x.setByOffset("global_idx",y(E.getByOffset("global_idx"),A.getByOffset("global_idx")));else{if(!s)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let R=(V,T,N="")=>{let te=`aData[indexA${T}][componentA${T}]`,Y=`bData[indexB${T}][componentB${T}]`;return`\n let outputIndices${T} = ${x.offsetToIndices(`global_idx * 4u + ${T}u`)};\n let offsetA${T} = ${E.broadcastedIndicesToOffset(`outputIndices${T}`,x)};\n let offsetB${T} = ${A.broadcastedIndicesToOffset(`outputIndices${T}`,x)};\n let indexA${T} = offsetA${T} / 4u;\n let indexB${T} = offsetB${T} / 4u;\n let componentA${T} = offsetA${T} % 4u;\n let componentB${T} = offsetB${T} % 4u;\n ${V}[${T}] = ${N}(${w(te,Y)});\n `};h===9?z=`\n var data = vec4(0);\n ${R("data",0,"u32")}\n ${R("data",1,"u32")}\n ${R("data",2,"u32")}\n ${R("data",3,"u32")}\n outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:z=`\n ${R("outputData[global_idx]",0)}\n ${R("outputData[global_idx]",1)}\n ${R("outputData[global_idx]",2)}\n ${R("outputData[global_idx]",3)}\n `}return`\n ${e.registerUniform("vec_size","u32").declareVariables(E,A,x)}\n\n ${b??""}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}\n ${z}\n }`},el=(e,t,r,o,n,s,u=r.dataType)=>{let l=!U.areEqual(r.dims,o.dims),a=r.dims,p=U.size(r.dims),h=!1,g=!1,b=[l];if(l){let y=dt.calcShape(r.dims,o.dims,!1);if(!y)throw new Error("Can\'t perform binary op on the given tensors");a=y,p=U.size(a);let _=U.size(r.dims)===1,I=U.size(o.dims)===1,$=r.dims.length>0&&r.dims[r.dims.length-1]%4===0,x=o.dims.length>0&&o.dims[o.dims.length-1]%4===0;b.push(_),b.push(I),b.push($),b.push(x);let E=1;for(let A=1;Ay.toString()).join("_"),inputDependencies:w?["rank","rank"]:["dims","dims"]},getShaderSource:y=>Jd(y,r.dims,o.dims,a,h,l,g,n,r.dataType,o.dataType,u,w,s),getRunData:()=>({outputs:[{dims:a,dataType:u}],dispatchGroup:{x:Math.ceil(p/64/4)},programUniforms:w?[{type:"uint32",data:Math.ceil(U.size(a)/4)},...L(r.dims),...L(o.dims),...L(a)]:[{type:"uint32",data:Math.ceil(U.size(a)/4)}]})}},ht=(e,t,r,o,n,s)=>{e.compute(el(t,n??"",e.inputs[0],e.inputs[1],r,o,s))},Ii=e=>{ht(e,"Add",(t,r)=>`${t}+${r}`)},Ai=e=>{ht(e,"Div",(t,r)=>`${t}/${r}`)},Ti=e=>{ht(e,"Equal",{scalar:(t,r)=>`u32(${t}==${r})`,vector:(t,r)=>`vec4(${t}==${r})`},void 0,void 0,9)},Ei=e=>{ht(e,"Mul",(t,r)=>`${t}*${r}`)},Oi=e=>{let t=M("input",e.inputs[0].dataType,e.inputs[0].dims).type.value;ht(e,"Pow",{scalar:(o,n)=>`pow_custom(${o},${n})`,vector:(o,n)=>`pow_vector_custom(${o},${n})`},`\n fn pow_custom(a : ${t}, b : ${t}) -> ${t} {\n if (b == ${t}(0.0)) {\n return ${t}(1.0);\n } else if (a < ${t}(0.0) && f32(b) != floor(f32(b))) {\n return ${t}(pow(f32(a), f32(b))); // NaN\n }\n return select(sign(a), ${t}(1.0), round(f32(abs(b) % ${t}(2.0))) != 1.0) * ${t}(${t==="i32"?"round":""}(pow(f32(abs(a)), f32(b))));\n }\n fn pow_vector_custom(a : vec4<${t}>, b : vec4<${t}>) -> vec4<${t}> {\n // TODO: implement vectorized pow\n return vec4<${t}>(pow_custom(a.x, b.x), pow_custom(a.y, b.y), pow_custom(a.z, b.z), pow_custom(a.w, b.w));\n }\n `)},Pi=e=>{ht(e,"Sub",(t,r)=>`${t}-${r}`)},ki=e=>{ht(e,"Greater",{scalar:(t,r)=>`u32(${t}>${r})`,vector:(t,r)=>`vec4(${t}>${r})`},void 0,void 0,9)},Ri=e=>{ht(e,"Less",{scalar:(t,r)=>`u32(${t}<${r})`,vector:(t,r)=>`vec4(${t}<${r})`},void 0,void 0,9)},Bi=e=>{ht(e,"GreaterOrEqual",{scalar:(t,r)=>`u32(${t}>=${r})`,vector:(t,r)=>`vec4(${t}>=${r})`},void 0,void 0,9)},Di=e=>{ht(e,"LessOrEqual",{scalar:(t,r)=>`u32(${t}<=${r})`,vector:(t,r)=>`vec4(${t}<=${r})`},void 0,void 0,9)}});var rl,nl,ol,al,zi,Ui,Vi=j(()=>{"use strict";$e();je();ve();rl=e=>{if(!e||e.length<1)throw new Error("too few inputs");let t=e[0].dataType,r=e[0].dims.length;for(let o of e){if(o.dataType!==t)throw new Error("input tensors should be one type");if(o.dims.length!==r)throw new Error("input tensors should have the same shape")}},nl=(e,t)=>`\n fn calculateInputIndex(index: u32) -> u32 {\n let sizeInConcatAxis = array(${t});\n for (var i: u32 = 0u; i < ${e}; i += 1u ) {\n if (index < sizeInConcatAxis[i]) {\n return i;\n }\n }\n return ${e}u;\n }`,ol=(e,t)=>{let r=e.length,o=[];for(let n=0;n{let r=e[0].dims.slice();if(t>=r.length||t<-1*r.length)throw new Error("axis specified for concat doesn\'t match input dimensionality");let o=t<0?r.length+t:t,n=r.slice(0);for(let A=1;A`uniforms.sizeInConcatAxis${A}`).join(","),E=A=>`\n\n ${(()=>{A.registerUniform("outputSize","u32");for(let z=0;z(${x});\n ${$} -= sizeInConcatAxis[inputIndex - 1u];\n }\n\n ${ol(l,I)}\n }`;return{name:"Concat",shaderCache:{hint:`${t}`,inputDependencies:h},getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:w}),getShaderSource:E}},zi=(e,t)=>{rl(e.inputs),e.compute(al(e.inputs,t.axis))},Ui=e=>ge({axis:e.axis})});var gt,Qr,It=j(()=>{"use strict";$e();gt=(e,t)=>{switch(e.activation){case"Relu":return{activationFunction:"",applyActivation:`value = max(value, ${t}(0.0));`};case"Sigmoid":return{activationFunction:"",applyActivation:`value = (${t}(1.0) / (${t}(1.0) + exp(-value)));`};case"Clip":return{activationFunction:`const clip_min_=${t}(${e.clipMin});const clip_max_=${t}(${e.clipMax});`,applyActivation:"value = clamp(value, clip_min_, clip_max_);"};default:return{activationFunction:"",applyActivation:""}}},Qr=e=>{let t=e?.activation||"";if(t==="Clip"){let[r,o]=e?.activation_params||[Gr,Lr];return{activation:t,clipMax:o,clipMin:r,activationCacheKey:`${t}:${r},${o}`}}return{activation:t,activationCacheKey:t}}});var Ke,Xr,Jr=j(()=>{"use strict";Ke=(e,t)=>{switch(e){case 1:return t;case 2:return`vec2<${t}>`;case 3:return`vec3<${t}>`;case 4:return`vec4<${t}>`;default:throw new Error(`${e}-component is not supported.`)}},Xr=e=>`\n ${e?"value = value + getBiasByOutputCoords(coords);":""}\n `});var en,Nn=j(()=>{"use strict";en=e=>`\nfn getIndexFromCoords4D(coords : vec4, shape : vec4) -> i32 {\n return dot(coords, vec4(\n shape.y * shape.z * shape.w, shape.z * shape.w, shape.w, 1));\n}\nfn getOutputIndexFromCoords(coords : vec4) -> i32 {\n return dot(coords, vec4(\n i32(${e}.x), i32(${e}.y), i32(${e}.z), 1));\n}\n`});var il,sl,mr,Ni,ul,fr,dl,tn,hr=j(()=>{"use strict";$e();ve();It();Jr();il=(e,t)=>e?`\n mm_Asub[inputRow][inputCol] = mm_readA(batch,\n kStart + inputRow,\n globalRowStart / innerElementSize + inputCol${t?", batchIndices":""});\n `:`\n mm_Asub[inputRow][inputCol] = mm_readA(batch,\n globalRow + innerRow,\n kStart / innerElementSize + inputCol${t?", batchIndices":""});\n `,sl=(e,t)=>e?`\n let ACached0 = mm_Asub[k * innerElementSize][localRow];\n let ACached1 = mm_Asub[k * innerElementSize + 1][localRow];\n let ACached2 = mm_Asub[k * innerElementSize + 2][localRow];\n ${t===3?"":"let ACached3 = mm_Asub[k * innerElementSize + 3][localRow];"}\n for (var i = 0; i < rowPerThread; i = i + 1) {\n acc[i] = BCached0 * ACached0[i] + acc[i];\n acc[i] = BCached1 * ACached1[i] + acc[i];\n acc[i] = BCached2 * ACached2[i] + acc[i];\n ${t===3?"":"acc[i] = BCached3 * ACached3[i] + acc[i];"}\n }`:`\n for (var i = 0; i < rowPerThread; i = i + 1) {\n let ACached = mm_Asub[tileRow + i][k];\n acc[i] = BCached0 * ACached.x + acc[i];\n acc[i] = BCached1 * ACached.y + acc[i];\n acc[i] = BCached2 * ACached.z + acc[i];\n ${t===3?"":"acc[i] = BCached3 * ACached.w + acc[i];"}\n }`,mr=(e,t,r="f32",o,n=!1,s=32,u=!1,l=32)=>{let a=t[1]*e[1],p=t[0]*e[0],h=n?a:s,g=n?s:a,b=h/t[0],w=s/t[1];if(!((n&&b===4&&e[1]===4||!n&&(b===3||b===4))&&h%t[0]===0&&s%t[1]===0&&e[0]===4))throw new Error(`If transposeA ${n} is true, innerElementSize ${b} and workPerThread[1] ${e[1]} must be 4.\n Otherwise, innerElementSize ${b} must be 3 or 4.\n tileAWidth ${h} must be divisible by workgroupSize[0]${t[0]}. tileInner ${s} must be divisible by workgroupSize[1] ${t[1]}. colPerThread ${e[0]} must be 4.`);return`\nvar mm_Asub: array, ${h/b}>, ${g}>;\nvar mm_Bsub: array, ${p/e[0]}>, ${s}>;\n\nconst rowPerThread = ${e[1]};\nconst colPerThread = ${e[0]};\nconst innerElementSize = ${b};\nconst tileInner = ${s};\n\n@compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]})\nfn main(@builtin(local_invocation_id) localId : vec3,\n @builtin(global_invocation_id) globalId : vec3,\n @builtin(workgroup_id) workgroupId : vec3) {\n let localRow = i32(localId.y);\n let tileRow = localRow * rowPerThread;\n let tileCol = i32(localId.x);\n\n let globalRow =i32(globalId.y) * rowPerThread;\n let globalCol = i32(globalId.x);\n let batch = ${u?"0":"i32(globalId.z)"};\n ${o?`let batchIndices = ${o.offsetToIndices("u32(batch)")};`:""}\n let globalRowStart = i32(workgroupId.y) * ${a};\n\n let numTiles = ${u?`${Math.ceil(l/s)}`:"(uniforms.dimInner - 1) / tileInner + 1"};\n var kStart = ${u?`i32(globalId.z) * ${l}`:"0"};\n\n var acc: array, rowPerThread>;\n\n // Loop over shared dimension.\n let tileRowB = localRow * ${w};\n for (var t = 0; t < numTiles; t = t + 1) {\n // Load one tile of A into local memory.\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n let inputRow = tileRow + innerRow;\n let inputCol = tileCol;\n ${il(n,o)}\n }\n\n // Load one tile of B into local memory.\n for (var innerRow = 0; innerRow < ${w}; innerRow = innerRow + 1) {\n let inputRow = tileRowB + innerRow;\n let inputCol = tileCol;\n mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol${o?", batchIndices":""});\n }\n kStart = kStart + tileInner;\n workgroupBarrier();\n\n // Compute acc values for a single thread.\n for (var k = 0; k < tileInner / innerElementSize; k = k + 1) {\n let BCached0 = mm_Bsub[k * innerElementSize][tileCol];\n let BCached1 = mm_Bsub[k * innerElementSize + 1][tileCol];\n let BCached2 = mm_Bsub[k * innerElementSize + 2][tileCol];\n ${b===3?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"}\n\n ${sl(n,b)}\n }\n\n workgroupBarrier();\n }\n\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]);\n }\n}`},Ni=(e,t)=>e?`\n mm_Asub[inputRow][inputCol] = mm_readA(batch,\n kStart + inputRow,\n globalRowStart + inputCol${t?", batchIndices":""});\n `:`\n mm_Asub[inputRow][inputCol] = mm_readA(batch,\n globalRowStart + inputRow,\n kStart + inputCol${t?", batchIndices":""});\n `,ul=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",fr=(e,t,r="f32",o,n=!1,s=32,u=!1,l=32,a=!1)=>{let p=e[1]*t[1],h=e[0]*t[0],g=n?p:s,b=n?s:p;if(!(b%t[1]===0&&g%t[0]===0&&s%t[1]===0))throw new Error(`tileAHight ${b} must be divisible by workgroupSize[1]${t[1]}, tileAWidth ${g} must be divisible by workgroupSize[0]${t[0]}, tileInner ${s} must be divisible by workgroupSize[1]${t[1]}`);let w=b/t[1],y=g/t[0],_=s/t[1],I=a?`\n let localRow = i32(localId.y);\n let localCol = i32(localId.x);\n let globalRowStart = i32(workgroupId.y) * ${p};\n let globalColStart = i32(workgroupId.x) * ${h};\n\n // Loop over shared dimension.\n for (var t = 0; t < numTiles; t = t + 1) {\n // Load one tile of A into local memory.\n for (var inputRow = localRow; inputRow < ${b}; inputRow = inputRow + ${t[1]}) {\n for (var inputCol = localCol; inputCol < ${g}; inputCol = inputCol + ${t[0]}) {\n ${Ni(n,o)}\n }\n }\n // Load one tile of B into local memory.\n for (var inputRow = localRow; inputRow < ${s}; inputRow = inputRow + ${t[1]}) {\n for (var inputCol = localCol; inputCol < ${h}; inputCol = inputCol + ${t[0]}) {\n mm_Bsub[inputRow][inputCol] = mm_readB(batch,\n kStart + inputRow,\n globalColStart + inputCol${o?", batchIndices":""});\n }\n }\n kStart = kStart + tileInner;\n workgroupBarrier();\n\n // Compute acc values for a single thread.\n var BCached : array<${r}, colPerThread>;\n for (var k = 0; k < tileInner; k = k + 1) {\n for (var inner = 0; inner < colPerThread; inner = inner + 1) {\n BCached[inner] = mm_Bsub[k][localCol + inner * ${t[0]}];\n }\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n let ACached = ${n?`mm_Asub[k][localRow + innerRow * ${t[1]}];`:`mm_Asub[localRow + innerRow * ${t[1]}][k];`}\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n acc[innerRow][innerCol] = acc[innerRow][innerCol] +\n ACached * BCached[innerCol];\n }\n }\n }\n workgroupBarrier();\n }\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n let gRow = globalRowStart + localRow + innerRow * ${t[1]};\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n let gCol = globalColStart + localCol + innerCol * ${t[0]};\n mm_write(batch, gRow, gCol, acc[innerRow][innerCol]);\n }\n }\n `:`\nlet tileRow = i32(localId.y) * rowPerThread;\nlet tileCol = i32(localId.x) * colPerThread;\n\nlet globalRow = i32(globalId.y) * rowPerThread;\nlet globalCol = i32(globalId.x) * colPerThread;\nlet globalRowStart = i32(workgroupId.y) * ${p};\n\nlet tileRowA = i32(localId.y) * ${w};\nlet tileColA = i32(localId.x) * ${y};\nlet tileRowB = i32(localId.y) * ${_};\n// Loop over shared dimension.\nfor (var t = 0; t < numTiles; t = t + 1) {\n // Load one tile of A into local memory.\n for (var innerRow = 0; innerRow < ${w}; innerRow = innerRow + 1) {\n for (var innerCol = 0; innerCol < ${y}; innerCol = innerCol + 1) {\n let inputRow = tileRowA + innerRow;\n let inputCol = tileColA + innerCol;\n ${Ni(n,o)}\n }\n }\n\n // Load one tile of B into local memory.\n for (var innerRow = 0; innerRow < ${_}; innerRow = innerRow + 1) {\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n let inputRow = tileRowB + innerRow;\n let inputCol = tileCol + innerCol;\n mm_Bsub[inputRow][inputCol] = mm_readB(batch,\n kStart + inputRow,\n globalCol + innerCol${o?", batchIndices":""});\n }\n }\n kStart = kStart + tileInner;\n workgroupBarrier();\n\n // Compute acc values for a single thread.\n var BCached : array<${r}, colPerThread>;\n for (var k = 0; k < tileInner; k = k + 1) {\n for (var inner = 0; inner < colPerThread; inner = inner + 1) {\n BCached[inner] = mm_Bsub[k][tileCol + inner];\n }\n\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n ${ul(n)}\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol];\n }\n }\n }\n\n workgroupBarrier();\n}\n\nfor (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n mm_write(batch, globalRow + innerRow, globalCol + innerCol,\n acc[innerRow][innerCol]);\n }\n}\n`;return`\n var mm_Asub : array, ${b}>;\n var mm_Bsub : array, ${s}>;\n const rowPerThread = ${e[1]};\n const colPerThread = ${e[0]};\n const tileInner = ${s};\n\n@compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]})\nfn main(@builtin(local_invocation_id) localId : vec3,\n @builtin(global_invocation_id) globalId : vec3,\n @builtin(workgroup_id) workgroupId : vec3) {\n let batch = ${u?"0":"i32(globalId.z)"};\n ${o?`let batchIndices = ${o.offsetToIndices("u32(batch)")};`:""}\n let numTiles = ${u?`${Math.ceil(l/s)}`:"(uniforms.dimInner - 1) / tileInner + 1"};\n var kStart = ${u?`i32(globalId.z) * ${l}`:"0"};\n\n var acc : array, rowPerThread>;\n\n // Without this initialization strange values show up in acc.\n for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {\n for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {\n acc[innerRow][innerCol] = 0.0;\n }\n }\n ${I}\n }\n`},dl=(e,t,r,o,n,s=!1)=>{let[u,l,a]=n,[p,h,g,b]=o,w=Ft(u,a),y=Ft(l,a),_=Le(o[0].type.tensor),I=()=>{let E=h.rank,A=p.rank,z=`var aIndices: ${h.type.indices};`;for(let R=E-2-1,V=A-1;R>=0;R--,V--)z+=`\naIndices[${R}] = ${A>1?`batchIndices[${V}]`:"batchIndices"};`;return w.forEach(R=>{z+=`\naIndices[${R}] = 0;`}),z+=`\naIndices[${E-2}] = u32(row);\n aIndices[${E-1}] = u32(colIn);`,z},$=()=>{let E=g.rank,A=p.rank,z=`var bIndices: ${g.type.indices};`;for(let R=E-2-1,V=A-1;R>=0;R--,V--)z+=`\nbIndices[${R}] = ${A>1?`batchIndices[${V}]`:"batchIndices"};`;return y.forEach(R=>{z+=`\nbIndices[${R}] = 0;`}),z+=`\nbIndices[${E-2}] = u32(row);\n bIndices[${E-1}] = u32(colIn);`,z};return`\n fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${p.type.indices}) -> ${Ke(e,_)} {\n var value = ${Ke(e,_)}(0.0);\n let col = colIn * ${e};\n if(row < uniforms.dimAOuter && col < uniforms.dimInner)\n {\n ${I()}\n value = ${h.getByIndices("aIndices")};\n }\n return value;\n }\n\n fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${p.type.indices}) -> ${Ke(e,_)} {\n var value = ${Ke(e,_)}(0.0);\n let col = colIn * ${e};\n if(row < uniforms.dimInner && col < uniforms.dimBOuter)\n {\n ${$()}\n value = ${g.getByIndices("bIndices")};\n }\n return value;\n }\n\n fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${Ke(e,_)}) {\n let col = colIn * ${e};\n if (row < uniforms.dimAOuter && col < uniforms.dimBOuter) {\n var value = valueIn;\n let coords = vec3(batch, row, colIn);\n ${t?`value = value + ${s?"bias[colIn]":`${Ke(e,_)}(bias[row])`};`:""}\n ${r}\n ${b.setByIndices("vec3(coords)","value")}\n }\n }\n `},tn=(e,t,r,o,n=!1)=>{let s=e[0].dims,u=e[1].dims,l=s.slice(0,-2),a=u.slice(0,-2),p=o?o.slice(0,-2):r.slice(0,-2),h=Re(p.length),g=h?p.length:p,b=Fr("batchDims",e[0].dataType,g,1),w=U.size(p),y=s[s.length-2],_=s[s.length-1],I=u[u.length-1],$=_%4===0&&I%4===0,x=y<=8?[4,1,1]:[4,4,1],E=[8,8,1],A=[Math.ceil(I/E[0]/x[0]),Math.ceil(y/E[1]/x[1]),Math.ceil(w/E[2]/x[2])],z=Le(e[0].dataType),R=$?4:1,V=[...l,y,_/R],T=Re(V.length),N=T?V.length:V,te=[...a,_,I/R],Y=Re(te.length),K=Y?te.length:te,Q=[w,y,I/R],Z=M("a",e[0].dataType,N,R),Ee=M("b",e[1].dataType,K,R),Pe=F("result",e[0].dataType,Q.length,R),fe=[Z,Ee],Ie=[{type:"int32",data:y},{type:"int32",data:I},{type:"int32",data:_}];h&&Ie.push(...L(p)),T&&Ie.push(...L(V)),Y&&Ie.push(...L(te));let he=[];he.push(T?"rank":"dims"),he.push(Y?"rank":"dims");let ye=e.length>2,{activationFunction:We,applyActivation:De}=gt(t,Pe.type.value),Ge=dl(R,ye,De,[b,Z,Ee,Pe],[l,a,p],n);if(ye){let ee=n?R:1;fe.push(M("bias",e[2].dataType,e[2].dims.length,ee)),Ie.push(...L(e[2].dims)),he.push("rank")}Ie.push(...L(Q));let G=ee=>`\n ${ee.registerUniform("dimAOuter","i32").registerUniform("dimBOuter","i32").registerUniform("dimInner","i32").registerInternalVariables(b).declareVariables(...fe,Pe)}\n ${We}\n ${Ge}\n ${$?mr(x,E,z,b):fr(x,E,z,b)}\n `;return{name:"MatMul",shaderCache:{hint:t.activationCacheKey+`${x}${$}${n}`,inputDependencies:he},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:A[0],y:A[1],z:A[2]},programUniforms:Ie}),getShaderSource:G}}});var ll,Wi,Hi=j(()=>{"use strict";Ct();ve();It();Jr();Nn();hr();ll=(e,t,r,o,n=!1,s,u=4,l=4,a=4,p="f32")=>{let h=Y=>{switch(Y){case 1:return"resData = x[xIndex];";case 3:return`resData = vec3<${p}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return"resData = x[xIndex / 4];";default:throw new Error(`innerElementSize ${Y} is not supported.`)}},g=Y=>{switch(Y){case 1:return"return w[row * i32(uniforms.w_shape[3]) + colIn];";case 4:return"return w[row * i32(uniforms.w_shape[3]) / 4 + colIn];";default:throw new Error(`innerElementSize ${Y} is not supported.`)}},b=e?`\n let coord = vec4(batch, xRow, xCol, xCh);\n `:`\n let coord = vec4(batch, xCh, xRow, xCol);\n `,w=e?`\n let coords = vec4(\n batch,\n row / outWidth,\n row % outWidth,\n col);\n `:`\n let coords = vec4(\n batch,\n row,\n col / outWidth,\n col % outWidth);\n `,y=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",_=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",I=e?"row":"col",$=e?"col":"row",x=`\n let inChannels = i32(uniforms.w_shape[2]);\n let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"};\n let outRow = ${I} / outWidth;\n let outCol = ${I} % outWidth;\n\n let WRow = ${$} / (filterDims[1] * inChannels);\n let WCol = ${$} / inChannels % filterDims[1];\n let xRow = outRow * stride[0] + dilation[0] * WRow - pad[0];\n let xCol = outCol * stride[1] + dilation[1] * WCol - pad[1];\n let xCh = ${$} % inChannels;\n var resData = ${Ke(u,p)}(0.0);\n // The bounds checking is always needed since we use it to pad zero for\n // the \'same\' padding type.\n if (xRow >= 0 && xRow < ${y} && xCol >= 0 && xCol < ${_}) {\n ${b}\n let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape));\n ${h(u)}\n }\n return resData;`,E=e?t&&o?`\n let col = colIn * ${u};\n ${x}`:`\n let col = colIn * ${u};\n if (row < uniforms.dimAOuter && col < uniforms.dimInner) {\n ${x}\n }\n return ${Ke(u,p)}(0.0);`:o&&r?`\n let col = colIn * ${u};\n ${x}`:`\n let col = colIn * ${u};\n if (row < uniforms.dimInner && col < uniforms.dimBOuter) {\n ${x}\n }\n return ${Ke(u,p)}(0.0);`,A=`${g(l)}`,z=Ke(a,p),R=e?Ke(u,p):Ke(l,p),V=e?Ke(l,p):Ke(u,p),{activationFunction:T,applyActivation:N}=gt(s,z);return`\n ${T}\n fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${R} {\n ${e?E:A}\n }\n\n fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${V} {\n ${e?A:E}\n }\n\n fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${z}) {\n let col = colIn * ${a};\n if (row < uniforms.dimAOuter && col < uniforms.dimBOuter)\n {\n var value = valueIn;\n let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"};\n ${w}\n ${Xr(n)}\n ${N}\n setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value);\n }\n }`},Wi=(e,t,r,o,n,s,u,l)=>{let a=t.format==="NHWC",p=a?e[0].dims[3]:e[0].dims[1],h=r[0],g=a?r[2]:r[3],b=a?r[1]:r[2],w=a?r[3]:r[1],y=a&&(p%4===0||p%3===0)&&w%4===0,_=a?w:g*b,I=a?g*b:w,$=[8,8,1],x=o<=8?[4,1,1]:[4,4,1],E=[Math.ceil(_/$[0]/x[0]),Math.ceil(I/$[1]/x[1]),Math.ceil(h/$[2]/x[2])];Be("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${E}`);let A=y?a&&p%4!==0?3:4:1,z=$[1]*x[1],R=$[0]*x[0],V=Math.max($[0]*A,$[1]),T=o%z===0,N=n%R===0,te=s%V===0,Y=y?[A,4,4]:[1,1,1],K=Le(e[0].dataType),Q=y?4:1,Z=[{type:"int32",data:o},{type:"int32",data:n},{type:"int32",data:s}],Ee=M("x",e[0].dataType,e[0].dims.length,A===3?1:A),Pe=M("w",e[1].dataType,e[1].dims.length,Q),fe=[Ee,Pe];Z.push(...L(e[0].dims)),Z.push(...L(e[1].dims));let Ie=`\n fn setOutputAtIndex(flatIndex : i32, value : ${y?`vec4<${K}>`:K}) {\n result[flatIndex] = ${y?`vec4<${K}>`:K}(value);\n }\n fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${y?`vec4<${K}>`:K}) {\n let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3));\n setOutputAtIndex(flatIndex ${y?"/ 4":""}, value);\n }`;if(u){let ye=M("bias",e[2].dataType,e[2].dims.length,Q);fe.push(ye),Z.push(...L(e[2].dims)),Ie+=`\n fn getBiasByOutputCoords(coords : vec4) -> ${y?`vec4<${K}>`:K} {\n return bias[coords.${a?"w":"y"}${y?"/ 4":""}];\n }`}let he=F("result",e[0].dataType,r.length,Q);return Z.push(...L(r)),{name:"Conv2DMatMul",shaderCache:{hint:t.cacheKey},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:E[0],y:E[1],z:E[2]},programUniforms:Z}),getShaderSource:ye=>`\n ${en("uniforms.result_strides")}\n //struct Uniforms { xShape : vec4, wShape : vec4, outShape : vec4,\n // outShapeStrides: vec3, filterDims : vec2, pad : vec2, stride : vec2,\n // dilation : vec2, dimAOuter : i32, dimBOuter : i32, dimInner : i32 };\n ${ye.registerUniform("dimAOuter","i32").registerUniform("dimBOuter","i32").registerUniform("dimInner","i32").declareVariables(...fe,he)}\n const filterDims : vec2 = vec2(${t.kernelShape[0]}, ${t.kernelShape[1]});\n const pad : vec2 = vec2(${t.pads[0]}, ${t.pads[1]});\n const stride : vec2 = vec2(${t.strides[0]}, ${t.strides[1]});\n const dilation : vec2 = vec2(${t.dilations[0]}, ${t.dilations[1]});\n ${Ie}\n ${ll(a,T,N,te,u,t,Y[0],Y[1],Y[2],K)}\n ${y?mr(x,$,K,void 0,!a,V):fr(x,$,K,void 0,!a,V,!1,void 0,l)}`}}});var Wn,Gi=j(()=>{"use strict";$e();ve();Gn();It();Wn=(e,t,r)=>{let o=e.length>2,n=o?"value += b[output_channel];":"",s=e[0].dims,u=e[1].dims,l=u[0]/t.group,a=t.format==="NHWC",p=Hn(s,u,t.dilations,t.pads,t.strides,a),h=U.size(p),g=F("output",e[0].dataType,p),{activationFunction:b,applyActivation:w}=gt(t,g.type.value),y=M("x",e[0].dataType,s),_=M("w",e[1].dataType,u),I=[y,_];o&&I.push(M("b",e[2].dataType,e[2].dims));let $=x=>`\n const strides: vec2 = vec2(${t.strides[0]}u, ${t.strides[1]}u);\n const pads: vec2 = vec2(${t.pads[0]}u, ${t.pads[1]}u);\n\n ${x.declareVariables(...I,g)}\n\n ${b}\n\n ${x.mainStart()}\n ${x.guardAgainstOutOfBoundsWorkgroupSizes(h)}\n\n let outputIndices = ${g.offsetToIndices("global_idx")};\n let batch: u32 = outputIndices[0];\n let output_channel: u32 = outputIndices[${a?3:1}];\n let xRCCorner: vec2 = vec2(outputIndices[${a?1:2}], outputIndices[${a?2:3}]) * strides - pads;\n let group_id: u32 = output_channel / ${l}u;\n\n var value: ${g.type.value} = ${g.type.value}(0);\n for (var wInChannel: u32 = 0u; wInChannel < ${u[1]}u; wInChannel++) {\n let input_channel = group_id * ${u[1]}u + wInChannel;\n for (var wHeight: u32 = 0u; wHeight < ${u[2]}u; wHeight++) {\n let xHeight = xRCCorner.x + wHeight * ${t.dilations[0]}u;\n\n if (xHeight < 0u || xHeight >= ${s[a?1:2]}u) {\n continue;\n }\n\n for (var wWidth: u32 = 0u; wWidth < ${u[3]}u; wWidth++) {\n let xWidth = xRCCorner.y + wWidth * ${t.dilations[1]}u;\n if (xWidth < 0u || xWidth >= ${s[a?2:3]}u) {\n continue;\n }\n\n let xVal = ${a?y.get("batch","xHeight","xWidth","input_channel"):y.get("batch","input_channel","xHeight","xWidth")};\n let wVal = ${_.get("output_channel","wInChannel","wHeight","wWidth")};\n value += xVal*wVal;\n }\n }\n }\n ${n}\n ${w}\n ${g.setByOffset("global_idx","value")}\n }`;return{name:"GroupedConv",shaderCache:{hint:t.cacheKey},getRunData:()=>({outputs:[{dims:r?r(p):p,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)}}),getShaderSource:$}}});var Ln,cl,Li,Fn=j(()=>{"use strict";$e();hr();ve();It();Ln=(e,t,r,o,n=!1)=>{let s=e[0].dims,u=e[1].dims,l=s[s.length-2],a=u[u.length-1],p=s[s.length-1],h=Fe(a),g=Fe(p),b=Fe(l),w=U.size(r)/h/b,y=e.length>2,_=o?o.slice(0,-2):r.slice(0,-2),$=[U.size(_),l,a],x=[{type:"uint32",data:w},{type:"uint32",data:l},{type:"uint32",data:a},{type:"uint32",data:p},...L(_),...L(s),...L(u)];y&&x.push(...L(e[2].dims)),x.push(...L($));let E=A=>{let z=Fr("batch_dims",e[0].dataType,_.length),R=M("a",e[0].dataType,s.length,g),V=M("b",e[1].dataType,u.length,h),T=F("output",e[0].dataType,$.length,h),{activationFunction:N,applyActivation:te}=gt(t,T.type.value),Y=[R,V],K="";if(y){let he=n?h:1;Y.push(M("bias",e[2].dataType,e[2].dims.length,he)),K=`${n?`value += bias[col / ${he}];`:`value += ${T.type.value}(bias[row + i]);`}`}let Q=s.slice(0,-2),Z=u.slice(0,-2),Ee=Ft(Q,_),Pe=Ft(Z,_),fe=(he,ye)=>{let We=he.rank,De=he.name;if(We===2)return`var ${De}_indices = ${he.type.indices}(0u, 0u);`;let Ge=z.rank,G=`var ${De}_indices: ${he.type.indices};`;for(let ee=We-2-1,be=Ge-1;ee>=0;ee--,be--)G+=`\n${De}_indices[${ee}] = ${Ge>1?`batch_indices[${be}]`:"batch_indices"};`;return ye.forEach(ee=>{G+=`\n${De}_indices[${ee}] = 0;`}),G+=`${De}_indices[${We-2}] = 0u;\n ${De}_indices[${We-1}] = 0u;`,G},Ie=()=>{let he=`var a_data: ${R.type.value};`;for(let ye=0;ye;\n for (var k: u32 = 0u; k < uniforms.K; k = k + ${g}) {\n ${Ie()}\n }\n for (var i = 0u; i < ${b}u; i++) {\n var value = values[i];\n ${K}\n ${te}\n let cur_indices = ${T.type.indices}(batch, row + i, col);\n let offset = ${T.indicesToOffset("cur_indices")};\n ${T.setByOffset(`offset / ${h}`,"value")};\n }\n }\n `};return{name:"MatMulNaive",shaderCache:{hint:`${t.activationCacheKey}_${h}_${g}_${b}_${n}`,inputDependencies:y?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(w/64)},programUniforms:x}),getShaderSource:E}},cl=e=>{if(!e||e.length!==2)throw new Error("MatMul requires 2 inputs.");if(e[0].dims[e[0].dims.length-1]!==e[1].dims[e[1].dims.length-2])throw new Error("shared dimension does not match.")},Li=e=>{cl(e.inputs);let t=dt.calcShape(e.inputs[0].dims,e.inputs[1].dims,!0);if(!t)throw new Error("Can\'t use matmul on the given tensors");let r=t[t.length-1],o=e.inputs[0].dims[e.inputs[0].dims.length-1];r<8&&o<8?e.compute(Ln(e.inputs,{activation:"",activationCacheKey:""},t)):e.compute(tn(e.inputs,{activation:"",activationCacheKey:""},t))}});var Hn,Fi,pl,ji,jn,ml,fl,qn,Gn=j(()=>{"use strict";$e();je();Hi();hr();Gi();It();Fn();jt();Hn=(e,t,r,o,n,s)=>{let u=e[0],l=e.slice(s?1:2,s?3:4),a=l.length,p=t[0],g=t.slice(2).map((y,_)=>y+(y-1)*(r[_]-1)),w=l.map((y,_)=>y+o[_]+o[_+a]).map((y,_)=>Math.floor((y-g[_]+n[_])/n[_]));return w.splice(0,0,u),w.splice(s?3:1,0,p),w},Fi=[2,3,1,0],pl=(e,t)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length!==4&&e[0].dims.length!==3)throw new Error("currently only support conv 1D and 2D");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");let r=e[0].dims[t.format==="NHWC"?e[0].dims.length-1:1],o=e[1].dims[1]*t.group;if(r!==o)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");if(e.length===3&&(e[2].dims.length!==1||e[1].dims[0]!==e[2].dims[0]))throw new Error("invalid bias");let n=e[0].dims.length-2;if(t.dilations.length!==n)throw new Error(`dilations should be ${n}D`);if(t.strides.length!==n)throw new Error(`strides should be ${n}D`);if(t.pads.length!==n*2)throw new Error(`pads should be ${n*2}D`);if(t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape")},ji=(e,t)=>{let r=e.kernelShape.slice();for(let s=2;s{let t=Qr(e),r=e.format,o=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],n=e.dilations,s=e.group,u=e.kernel_shape,l=e.pads,a=e.strides,p=e.w_is_const();return ge({autoPad:o,format:r,dilations:n,group:s,kernelShape:u,pads:l,strides:a,wIsConst:p,...t})},ml=(e,t,r)=>{let o=ji(r,t),n=r.format==="NHWC";if(r.group!==1){e.compute(Wn(t,o));return}let s=t.length===3,u=t[0].dims[n?1:2],l=t[0].dims[n?2:3],a=t[0].dims[n?3:1],p=t[1].dims[2],h=t[1].dims[3],g=Hn(t[0].dims,t[1].dims,r.dilations,o.pads,r.strides,n),b=g[n?1:2],w=g[n?2:3],y=g[n?3:1],_=n&&p===u&&h===l&&r.pads[0]===0&&r.pads[1]===0;if(_||p===1&&h===1&&r.dilations[0]===1&&r.dilations[1]===1&&r.strides[0]===1&&r.strides[1]===1&&r.pads[0]===0&&r.pads[1]===0){let R=g[0],V,T,N,te=[];if(n){let Q=e.kernelCustomData.wT??e.compute(it(t[1],Fi),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];if(r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=Q),_){let Z=u*l*a;V=t[0].reshape([1,R,Z]),T=Q.reshape([1,Z,y]),N=[1,R,y]}else V=t[0].reshape([R,u*l,a]),T=Q.reshape([1,a,y]),N=[R,b*w,y];te.push(V),te.push(T)}else V=t[0].reshape([R,a,u*l]),T=t[1].reshape([1,y,a]),N=[R,y,b*w],te.push(T),te.push(V);s&&te.push(t[2]);let Y=N[2],K=te[0].dims[te[0].dims.length-1];Y<8&&K<8?e.compute(Ln(te,o,g,N,n),{inputs:te}):e.compute(tn(te,o,g,N,n),{inputs:te});return}let I=!0,$=e.kernelCustomData.wT??e.compute(it(t[1],Fi),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=$);let x=[t[0],$];s&&x.push(t[2]);let E=n?b*w:y,A=n?y:b*w,z=p*h*a;e.compute(Wi(x,o,g,E,A,z,s,I),{inputs:x})},fl=(e,t)=>{let r=t.format==="NHWC",o=[e.inputs[0].reshape(r?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&o.push(e.inputs[2]);let n=[0,t.pads[0],0,t.pads[1]],s=[1].concat(t.strides),u=[1].concat(t.dilations),l=[1].concat(t.kernelShape),a=ji({...t,pads:n,strides:s,dilations:u,kernelShape:l},o);e.compute(Wn(o,a,p=>r?[p[0],p[2],p[3]]:[]))},qn=(e,t)=>{pl(e.inputs,t),e.inputs[0].dims.length===3?fl(e,t):ml(e,e.inputs,t)}});var hl,qi,Ki=j(()=>{"use strict";Ct();ve();It();Jr();Nn();hr();hl=(e,t=!1,r,o=4)=>{let n=Ke(o,"f32"),s=x=>{switch(x){case 1:return"return w[getIndexFromCoords4D(coord, vec4(uniforms.w_shape))];";case 4:return`\n let coord1 = vec4(coordX, coordY, col + 1, rowInner);\n let coord2 = vec4(coordX, coordY, col + 2, rowInner);\n let coord3 = vec4(coordX, coordY, col + 3, rowInner);\n let v0 = w[getIndexFromCoords4D(coord, vec4(uniforms.w_shape))];\n let v1 = w[getIndexFromCoords4D(coord1, vec4(uniforms.w_shape))];\n let v2 = w[getIndexFromCoords4D(coord2, vec4(uniforms.w_shape))];\n let v3 = w[getIndexFromCoords4D(coord3, vec4(uniforms.w_shape))];\n return vec4(v0, v1, v2, v3);\n `;default:throw new Error(`innerElementSize ${x} is not supported.`)}},u=e?`\n let coord = vec4(batch, iXR, iXC, xCh);\n `:`\n let coord = vec4(batch, xCh, iXR, iXC);\n `,l=e?`\n let coords = vec4(\n batch,\n row / outWidth,\n row % outWidth,\n col);\n `:`\n let coords = vec4(\n batch,\n row,\n col / outWidth,\n col % outWidth);\n `,a=e?"outBackprop[1]":"outBackprop[2]",p=e?"outBackprop[2]":"outBackprop[3]",h=e?"row":"col",g=e?"col":"row",b=`\n let inChannels = ${e?"outBackprop[3]":"outBackprop[1]"};\n let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"};\n let outRow = ${h} / outWidth;\n let outCol = ${h} % outWidth;\n\n let WRow = ${g} / (filterDims[1] * inChannels);\n let WCol = ${g} / inChannels % filterDims[1];\n let xR = f32(outRow - pads[0] + dilation[0] * WRow) / f32(strides[0]);\n let xC = f32(outCol - pads[1] + dilation[1] * WCol) / f32(strides[1]);\n if (xR < 0.0 || xR >= f32(${a}) || fract(xR) > 0.0) {\n return ${n}(0.0);\n }\n if (xC < 0.0 || xC >= f32(${p}) || fract(xC) > 0.0) {\n return ${n}(0.0);\n }\n let iXR = i32(xR);\n let iXC = i32(xC);\n let xCh = ${g} % inChannels;\n ${u}\n return x[getIndexFromCoords4D(coord, vec4(uniforms.x_shape))/${o}];`,w=e?`\n let col = colIn * ${o};\n if (row < uniforms.dimAOuter && col < uniforms.dimInner) {\n ${b}\n }\n return ${n}(0.0);`:`\n let col = colIn * ${o};\n if (row < uniforms.dimInner && col < uniforms.dimBOuter) {\n ${b}\n }\n return ${n}(0.0);`,y=`\n let col = colIn * ${o};\n let inChannels = ${e?"outBackprop[3]":"outBackprop[1]"};\n let coordX = filterDims.x - 1 - row / (filterDims[1] * inChannels);\n let coordY = filterDims.y - 1 - (row / inChannels) % filterDims[1];\n if (${e?"row < uniforms.dimInner && col < uniforms.dimBOuter":"row < uniforms.dimInner && col < uniforms.dimAOuter"} && coordX >= 0 && coordY >= 0) {\n let rowInner = row % inChannels;\n let coord = vec4(coordX, coordY, col, rowInner);\n ${s(o)}\n }\n return ${n}(0.0);\n `,{activationFunction:_,applyActivation:I}=gt(r,n);return`\n ${_}\n fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${n} {\n ${e?w:y}\n }\n\n fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${n} {\n ${e?y:w}\n }\n\n fn mm_write(batch: i32, row : i32, colIn : i32, valueInput : ${n}) {\n let col = colIn * ${o};\n if (row < uniforms.dimAOuter && col < uniforms.dimBOuter) {\n var value = valueInput;\n let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"};\n ${l}\n ${Xr(t)}\n ${I}\n result[getIndexFromCoords4D(coords, vec4(uniforms.result_shape))/${o}] = value;\n }\n }`},qi=(e,t,r,o,n,s,u,l)=>{let a=t.format==="NHWC",p=a?e[0].dims[3]:e[0].dims[1],h=r[0],g=a?r[2]:r[3],b=a?r[1]:r[2],w=a?r[3]:r[1],y=a?p%4===0&&w%4===0:g%4===0&&w%4===0,_=a?w:g*b,I=a?g*b:w,$=y?[8,8,1]:[_<=4||I<=4?4:16,_>4&&I<=4?4:16,1],x=y?[4,4,1]:[_<=4?1:4,_>4&&I<=4?1:4,1],E=[Math.ceil(_/$[0]/x[0]),Math.ceil(I/$[1]/x[1]),Math.ceil(h/$[2]/x[2])];Be("verbose",()=>`[conv_backprop_mm_webgpu] dispatch = ${E}`);let A=y?4:1,z=Math.max($[0]*A,$[1]),R=y?4:1,V=[{type:"int32",data:o},{type:"int32",data:n},{type:"int32",data:s}],T=M("x",e[0].dataType,e[0].dims.length,R),N=M("w",e[1].dataType,e[1].dims.length,1),te=F("result",e[0].dataType,r.length,R),Y=[T,N];V.push(...L(e[0].dims)),V.push(...L(e[1].dims));let K="";if(u){let Q=M("bias",e[2].dataType,e[2].dims.length,R);Y.push(Q),V.push(...L(e[2].dims)),K+=`\n fn getBiasByOutputCoords(coords : vec4) -> ${y?"vec4":"f32"} {\n return bias[coords.${a?"w":"y"}${y?"/ 4":""}];\n }`}return V.push(...L(r)),{name:"Conv2DTransposeMatMul",shaderCache:{hint:t.cacheKey},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:E[0],y:E[1],z:E[2]},programUniforms:V}),getShaderSource:Q=>`\n ${en("uniforms.result_strides")}\n ${Q.registerUniform("dimAOuter","i32").registerUniform("dimBOuter","i32").registerUniform("dimInner","i32").declareVariables(...Y,te)};\n const outBackprop : vec4 = vec4(${e[0].dims.join(",")});\n const filterDims : vec2 = vec2(${t.kernelShape[a?1:2]}, ${t.kernelShape[a?2:3]});\n const effectiveFilterDims : vec2 = filterDims + vec2(\n ${t.dilations[0]<=1?0:(t.kernelShape[a?1:2]-1)*(t.dilations[0]-1)},\n ${t.dilations[1]<=1?0:(t.kernelShape[a?2:3]-1)*(t.dilations[1]-1)});\n const pads : vec2 = vec2(i32(effectiveFilterDims[0]) - 1 - (${t.pads[0]+t.pads[2]})/2,\n i32(effectiveFilterDims[1]) - 1 - (${t.pads[1]+t.pads[3]})/2);\n const strides : vec2 = vec2(${t.strides[0]}, ${t.strides[1]});\n const dilation : vec2 = vec2(${t.dilations[0]}, ${t.dilations[1]});\n const dimAOuter : i32 = ${o};\n const dimBOuter : i32 = ${n};\n const dimInner : i32 = ${s};\n ${K}\n ${hl(a,u,t,A)}\n ${y?mr(x,$,"f32",void 0,!a,z):fr(x,$,"f32",void 0,!a,z,!1,void 0,l)}`}}});var gl,Kn,Yi=j(()=>{"use strict";Ct();$e();ve();gl=(e,t,r,o,n,s,u=!1,l)=>{let a=r.format==="NHWC",p=a?1:2,h=a?2:3,g=a?3:1,b=U.size(o),w=u?2:1,y=r.group,_=t[1].dims,I=_[0]/y,$=_[1],x=`\n fn setOutputAtIndex(flatIndex : u32, value : ${u?`vec4<${l}>`:l}) {\n result[flatIndex] = ${u?`vec4<${l}>`:l}(value);\n }`;n&&(x+=`\n fn getBiasByOutputCoords(coords : vec4) -> ${u?`vec4<${l}>`:l} {\n return bias[coords.${a?"w":"y"}${u?"/ 4":""}];\n }`);let E=u?4:1,A=M("W",t[1].dataType,t[1].dims,E),z=M("Dy",t[0].dataType,t[0].dims,E),R=[z,A];n&&R.push(M("bias",t[2].dataType,[o[g]],E));let V=F("result",t[0].dataType,o,E),T=`{\n let batch: u32 = ${s?"global_id.z":"workgroup_id.z"} / outShape[1];\n let r = ${s?"global_id.z":"workgroup_id.z"} % outShape[1];\n let c = ${s?"global_id.y":"workgroup_id.y"} * ${w};\n let d1: u32 = ${s?"global_id.x":"workgroup_id.x"} * 4;\n\n let dyCorner = vec2(i32(r), i32(c)) - vec2(pads);\n\n // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).\n // ? = to be determined. : = across all values in that axis.\n var dotProd: array, ${w}>;\n for (var i = 0; i < ${w}; i++) {\n dotProd[i] = vec4<${l}>(0.0);\n }\n for (var wR: u32 = 0; wR < filterDims[0]; wR = wR + 1) {\n var dyR = (${l}(dyCorner.x) + ${l}(wR)) / ${l}(strides.x);\n let wRPerm = filterDims[0] - 1 - wR;\n if (dyR < 0.0 || dyR >= ${l}(outBackprop[1]) ||\n fract(dyR) > 0.0 || wRPerm < 0) {\n continue;\n }\n let idyR: u32 = u32(dyR);\n\n for (var wC: u32 = 0; wC < filterDims[1]; wC = wC + 1) {\n let dyC = (${l}(dyCorner.y) + ${l}(wC)) / ${l}(strides.y);\n let dyC2 = (${l}(dyCorner.y) + 1.0 + ${l}(wC)) / ${l}(strides.y);\n let wCPerm = filterDims[1] - 1 - wC;\n if (wCPerm < 0) {\n continue;\n }\n var bDyCVal = true;\n var bDyCVal2 = true;\n if (dyC < 0.0 || dyC >= ${l}(outBackprop[2]) ||\n fract(dyC) > 0.0) {\n bDyCVal = false;\n }\n if (dyC2 < 0.0 || dyC2 >= ${l}(outBackprop[2]) ||\n fract(dyC2) > 0.0) {\n bDyCVal2 = false;\n }\n\n let idyC: u32 = u32(dyC);\n let idyC2: u32 = u32(dyC2);\n if (bDyCVal && bDyCVal2) {\n let d2Length = outBackprop[3];\n for (var d2 :u32 = 0; d2 < d2Length; d2 = d2 + 4) {\n let wValue0 = ${A.get("u32(wRPerm)","u32(wCPerm)","d1","d2")};\n let wValue1 = ${A.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")};\n let wValue2 = ${A.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")};\n let wValue3 = ${A.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")};\n\n var xValue = ${z.get("batch","idyR","idyC","d2")};\n let tmpval = vec4<${l}>(dot(xValue, wValue0),\n dot(xValue, wValue1),\n dot(xValue, wValue2),\n dot(xValue, wValue3));\n dotProd[0] = dotProd[0] + tmpval;\n\n xValue = ${z.get("batch","idyR","idyC2","d2")};\n\n dotProd[1] = dotProd[1] + vec4<${l}>(dot(xValue, wValue0),\n dot(xValue, wValue1),\n dot(xValue, wValue2),\n dot(xValue, wValue3));\n }\n } else if (bDyCVal) {\n let d2Length = outBackprop[${g}];\n for (var d2: u32 = 0; d2 < d2Length; d2 = d2 + 4) {\n let wValue0 = ${A.get("u32(wRPerm)","u32(wCPerm)","d1","d2")};\n let wValue1 = ${A.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")};\n let wValue2 = ${A.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")};\n let wValue3 = ${A.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")};\n\n var xValue = ${z.get("batch","idyR","idyC","d2")};\n let tmpval = vec4<${l}>(dot(xValue, wValue0),\n dot(xValue, wValue1),\n dot(xValue, wValue2),\n dot(xValue, wValue3));\n dotProd[0] = dotProd[0] + tmpval;\n }\n } else if (bDyCVal2) {\n let d2Length = outBackprop[3];\n for (var d2: u32 = 0; d2 < d2Length; d2 = d2 + 4) {\n let wValue0 = ${A.get("u32(wRPerm)","u32(wCPerm)","d1","d2")};\n let wValue1 = ${A.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")};\n let wValue2 = ${A.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")};\n let wValue3 = ${A.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")};\n\n var xValue = ${z.get("batch","idyR","idyC2","d2")};\n let tmpval = vec4<${l}>(dot(xValue, wValue0),\n dot(xValue, wValue1),\n dot(xValue, wValue2),\n dot(xValue, wValue3));\n dotProd[1] = dotProd[1] + tmpval;\n }\n }\n }\n }\n\n for (var i: u32 = 0; i < ${w}; i = i + 1) {\n let value = dotProd[i] + ${n?"bias[c+i]":`vec4<${l}>(0.0)`};\n ${V.set("batch","r","c + i","d1","value")};\n }\n }`,N=`\n let outputIndices = ${V.offsetToIndices("global_idx")};\n let batch = ${V.indicesGet("outputIndices",0)};\n let d1 = ${V.indicesGet("outputIndices",g)};\n let r = ${V.indicesGet("outputIndices",p)};\n let c = ${V.indicesGet("outputIndices",h)};\n let dyCorner = vec2(i32(r), i32(c)) - pads;\n let dyRCorner = dyCorner.x;\n let dyCCorner = dyCorner.y;\n let groupId = d1 / ${$};\n let wOutChannel = d1 - groupId * ${$};\n // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).\n // ? = to be determined. : = across all values in that axis.\n var dotProd = ${l}(0.0);\n for (var wR: u32 = 0; wR < effectiveFilterDims.x; wR = wR + 1) {\n if (wR % dilations.x != 0) {\n continue;\n }\n let dyR = (${l}(dyRCorner) + ${l}(wR)) / ${l}(strides[0]);\n let wRPerm = filterDims.x - 1 - wR / dilations.x;\n if (dyR < 0.0 || dyR >= ${l}(outBackprop[${p}]) || fract(dyR) > 0.0 ||\n wRPerm < 0) {\n continue;\n }\n let idyR: u32 = u32(dyR);\n\n for (var wC: u32 = 0; wC < effectiveFilterDims.y; wC = wC + 1) {\n if (wC % dilations.y != 0) {\n continue;\n }\n let dyC = (${l}(dyCCorner) + ${l}(wC)) / ${l}(strides.y);\n let wCPerm = filterDims.y - 1 - wC / dilations.y;\n if (dyC < 0.0 || dyC >= ${l}(outBackprop[${h}]) ||\n fract(dyC) > 0.0 || wCPerm < 0) {\n continue;\n }\n let idyC: u32 = u32(dyC);\n var inputChannel = groupId * ${I};\n for (var d2: u32 = 0; d2 < ${I}; d2 = d2 + 1) {\n let xValue = ${a?z.get("batch","idyR","idyC","inputChannel"):z.get("batch","inputChannel","idyR","idyC")};\n let wValue = ${A.get("inputChannel","wOutChannel","u32(wRPerm)","u32(wCPerm)")};\n dotProd = dotProd + xValue * wValue;\n inputChannel = inputChannel + 1;\n }\n }\n }\n let value = dotProd + ${n?"bias[d1]":`${l}(0.0)`};\n ${V.setByOffset("global_idx","value")};\n `;return`\n ${e.declareVariables(...R,V)}\n ${x}\n const outShape : vec4 = vec4(${o.join(",")});\n const outBackprop : vec4 = vec4(${t[0].dims.join(",")});\n const strides : vec2 = vec2(${r.strides[0]}, ${r.strides[1]});\n const filterDims : vec2 = vec2(${r.kernelShape[a?1:2]}, ${r.kernelShape[a?2:3]});\n const dilations : vec2 = vec2(${r.dilations[0]}, ${r.dilations[1]});\n const effectiveFilterDims : vec2 = filterDims + vec2(\n ${r.dilations[0]<=1?0:(r.kernelShape[a?1:2]-1)*(r.dilations[0]-1)},\n ${r.dilations[1]<=1?0:(r.kernelShape[a?2:3]-1)*(r.dilations[1]-1)});\n const pads : vec2 = vec2(i32(effectiveFilterDims[0]) - 1 - (${r.pads[0]+r.pads[2]})/2,\n i32(effectiveFilterDims[1]) - 1 - (${r.pads[1]+r.pads[3]})/2);\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes(b)};\n ${u?T:N}}`},Kn=(e,t,r)=>{let o=e.length>2,n=t.outputShape,s=U.size(n),u=[Math.ceil(s/64),1,1];Be("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${u}`);let l=Le(e[0].dataType);return{name:"ConvTranspose2D",shaderCache:{hint:t.cacheKey},getRunData:()=>({dispatchGroup:{x:u[0],y:u[1],z:u[2]},outputs:[{dims:r?r(n):n,dataType:e[0].dataType}]}),getShaderSource:a=>gl(a,e,t,n,o,u[1]===1&&u[2]===1,!1,l)}}});var yl,bl,wl,Zi,Qi,vl,$l,Sl,xl,Xi,Ji=j(()=>{"use strict";je();Ki();Yi();It();jt();yl=(e,t,r,o,n,s)=>(e-1)*t+r+(o-1)*n+1-s,bl=(e,t,r,o,n)=>{let s=Math.floor(e/2);t==="SAME_UPPER"?(r[o]=s,r[n]=e-s):t==="SAME_LOWER"&&(r[o]=e-s,r[n]=s)},wl=(e,t,r,o,n,s,u,l,a,p)=>{let h=e.length-2,g=p.length===0;if(a.length===0)for(let y=0;y{let r=e.kernelShape.slice();if(e.kernelShape.length===0||e.kernelShape.reduce((b,w)=>b*w,1)===0){r.length=0;for(let b=2;bb+w,0)===0){let b=t[0].dims.length-2;a=new Array(b).fill(1)}let p=e.strides.slice();if(p.reduce((b,w)=>b+w,0)===0){let b=t[0].dims.length-2;p=new Array(b).fill(1)}wl(l,r,a,e.autoPad,e.group,n,p,o,u,s);let h=Object.assign({},e),g=e.cacheKey+[r.join("n,"),n.join(","),p.join(","),u.join(","),s.join(","),a.join(",")].join("_");return Object.assign(h,{kernelShape:r,pads:n,outputPadding:u,outputShape:s,dilations:a,strides:p,cacheKey:g}),h},Qi=e=>{let t=Qr(e),r=e.format,o=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof e.autoPad>"u"?0:e.autoPad],n=e.dilations,s=e.group,u=e.kernelShape,l=e.pads,a=e.strides,p=e.wIsConst(),h=e.outputPadding,g=e.outputShape;return ge({autoPad:o,format:r,dilations:n,group:s,kernelShape:u,outputPadding:h,outputShape:g,pads:l,strides:a,wIsConst:p,...t})},vl=(e,t)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length!==4&&e[0].dims.length!==3)throw new Error("currently only support 2-dimensional conv");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");let r=e[0].dims[t.format==="NHWC"?e[0].dims.length-1:1],o=e[1].dims[0];if(r!==o)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");let n=e[1].dims[1]*t.group;if(e.length===3&&(e[2].dims.length!==1||e[2].dims[0]!==n))throw new Error("invalid bias");let s=e[0].dims.length-2;if(t.dilations.reduce((h,g)=>h+g,0)>0&&t.dilations.length!==s)throw new Error(`dilations should be ${s}D`);if(t.strides.reduce((h,g)=>h+g,0)>0&&t.strides.length!==s)throw new Error(`strides should be ${s}D`);if(t.pads.reduce((h,g)=>h+g,0)>0&&t.pads.length!==s*2)throw new Error(`pads should be ${s*2}D`);if(t.outputPadding.length!==s&&t.outputPadding.length!==0)throw new Error(`output_padding should be ${s}D`);if(t.kernelShape.reduce((h,g)=>h+g,0)>0&&t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape");if(t.outputShape.length!==0&&t.outputShape.length!==e[0].dims.length-2)throw new Error("invalid output shape")},$l=[2,3,1,0],Sl=(e,t,r)=>{let o=Zi(r,t),n=r.format==="NHWC",s=o.outputShape,u=s[n?3:1],l=t[0].dims[n?3:1];if(o.group!==1||u===1&&l===1){e.compute(Kn(t,o));return}let a=s[n?1:2],p=s[n?2:3],h=t[1].dims[2],g=t[1].dims[3],b=n?a*p:u,w=n?u:a*p,y=h*g*l,_=!0,I=e.kernelCustomData.wT??e.compute(it(t[1],$l),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=I);let $=[t[0],I],x=t.length===3;x&&(!n&&t[2].dims.length===1?$.push(t[2].reshape([t[2].dims[0],1,1])):$.push(t[2])),e.compute(qi($,o,s,b,w,y,x,_),{inputs:$})},xl=(e,t)=>{let r=t.format==="NHWC",o=[e.inputs[0].reshape(r?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];o.length===3&&o.push(e.inputs[2]);let n=t.kernelShape;(n.length===0||n[0]===0)&&(n=[e.inputs[1].dims[2]]);let s=t.dilations;(s.length===0||s[0]===0)&&(s=[1]);let u=t.strides;(u.length===0||u[0]===0)&&(u=[1]);let l=t.pads;l.length===0&&(l=[0,0]),l=[0,l[0],0,l[1]],u=[1].concat(u),s=[1].concat(s),n=[1].concat(n);let a=Zi({...t,pads:l,strides:u,dilations:s,kernelShape:n},o);e.compute(Kn(o,a,p=>r?[p[0],p[2],p[3]]:[p[0],p[1],p[3]]))},Xi=(e,t)=>{vl(e.inputs,t),e.inputs[0].dims.length===3?xl(e,t):Sl(e,e.inputs,t)}});var _l,es,ts,rs=j(()=>{"use strict";Ne();$e();je();ve();_l=(e,t,r,o)=>{let n=U.size(t),s=t.length,u=M("input",e,s),l=F("output",e,s),a=r.dataType===6?r.getInt32Array()[0]:Number(r.getBigInt64Array()[0]),p=U.normalizeAxis(a,s),h=g=>{let b=` i32(${u.indicesGet("inputIndices","uniforms.axis")}) `,w=ce("uniforms.input_shape","uniforms.axis",s),y=o.reverse?b+(o.exclusive?" + 1":""):"0",_=o.reverse?w:b+(o.exclusive?"":" + 1");return`\n ${g.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(u,l)}\n ${g.mainStart()}\n ${g.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n var inputIndices = ${l.offsetToIndices("global_idx")};\n var sum = ${l.type.value}(0);\n let first : i32 = ${y};\n let last : i32 = ${_};\n for (var i : i32 = first; i < last; i++) {\n ${u.indicesSet("inputIndices","uniforms.axis","u32(i)")};\n sum = sum + ${u.getByIndices("inputIndices")};\n }\n ${l.setByOffset("global_idx","sum")};\n }`};return{name:"CumSum",shaderCache:{hint:o.cacheKey,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:t,dataType:e}],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:[{type:"uint32",data:n},{type:"int32",data:p},...L(t),...L(t)]}),getShaderSource:h}},es=(e,t)=>{let r=e.inputs[0].dims,o=e.inputs[0].dataType,n=e.inputs[1];e.compute(_l(o,r,n,t),{inputs:[0]})},ts=e=>{let t=e.exclusive===1,r=e.reverse===1;return ge({exclusive:t,reverse:r})}});var Yn,rn,ns,Cl,Il,Zn,Qn,os,Al,as,is,ss=j(()=>{"use strict";$e();je();ve();Yn="[a-zA-Z]|\\\\.\\\\.\\\\.",rn="("+Yn+")+",ns="^"+rn+"$",Cl="("+rn+",)*"+rn,Il="^"+Cl+"$",Zn=class{constructor(t=-1){this.symbolToIndices=new Map,this.inputIndex=t}addSymbol(t,r){let o=this.symbolToIndices.get(t);o===void 0?o=[r]:o.push(r),this.symbolToIndices.set(t,o)}},Qn=class{constructor(t,r){this.equation=r;this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=new Array,this.outputDims=[];let[o,n]=r.includes("->")?r.split("->",2):[r,""];if(!o.match(RegExp(Il)))throw new Error("Invalid LHS term");if(o.split(",").forEach((l,a)=>{let p=t[a].dims.slice();if(!l.match(RegExp(ns)))throw new Error("Invalid LHS term");let h=this.processTerm(l,!0,p,a);this.lhs.push(h)}),n==="")n+=[...this.symbolToInfo.entries()].filter(([l,a])=>a.count===1||l==="...").map(([l])=>l).join("");else if(!n.match(RegExp(rn)))throw new Error("Invalid RHS");n.match(RegExp(Yn,"g"))?.forEach(l=>{if(l==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let a=this.symbolToInfo.get(l);if(a===void 0)throw new Error("Invalid RHS symbol");this.outputDims.push(a.dimValue)}}),this.rhs=this.processTerm(n,!1,this.outputDims)}addSymbol(t,r,o){let n=this.symbolToInfo.get(t);if(n!==void 0){if(n.dimValue!==r&&n.count!==1)throw new Error("Dimension mismatch");n.count++,n.inputIndices.push(o)}else n={count:1,dimValue:r,inputIndices:[o]};this.symbolToInfo.set(t,n)}processTerm(t,r,o,n=-1){let s=o.length,u=!1,l=[],a=0;if(!t.match(RegExp(ns))&&!r&&t!=="")throw new Error("Invalid LHS term");let p=t.match(RegExp(Yn,"g")),h=new Zn(n);return p?.forEach((g,b)=>{if(g==="..."){if(u)throw new Error("Only one ellipsis is allowed per input term");u=!0;let w=s-p.length+1;if(w<0)throw new Error("Ellipsis out of bounds");if(l=o.slice(a,a+w),this.hasEllipsis){if(this.ellipsisDims.length!==l.length||this.ellipsisDims.toString()!==l.toString())throw new Error("Ellipsis dimensions mismatch")}else if(r)this.hasEllipsis=!0,this.ellipsisDims=l;else throw new Error("Ellipsis must be specified in the LHS");for(let y=0;ye+"_max",Al=(e,t,r,o,n)=>{let u=t.map((w,y)=>e[y]?w.length:w).map((w,y)=>M(`input${y}`,r,w)),l=U.size(n),a=Re(n.length),p=a?n.length:n,h=F("output",r,p),g=[...o.symbolToInfo.keys()].filter(w=>!o.rhs.symbolToIndices.has(w)),b=w=>{let y=[],_="var prod = 1.0;",I="var sum = 0.0;",$="sum += prod;",x=[],E=[],A=[],z=[],R=o.symbolToInfo.size===o.rhs.symbolToIndices.size;o.symbolToInfo.forEach((T,N)=>{if(o.rhs.symbolToIndices.has(N)){let te=o.rhs.symbolToIndices.get(N)?.[0];te!==void 0&&o.lhs.forEach((Y,K)=>{if(T.inputIndices.includes(K)){let Q=Y.symbolToIndices.get(N);if(Q===void 0)throw new Error("Invalid symbol error");Q.forEach(Z=>{y.push(`${u[K].indicesSet(`input${K}Indices`,Z,h.indicesGet("outputIndices",te))}`)})}})}else o.lhs.forEach((te,Y)=>{if(T.inputIndices.includes(Y)){let K=te.symbolToIndices.get(N);if(K===void 0)throw new Error("Invalid symbol error");K.forEach(Q=>{x.push(`${u[Y].indicesSet(`input${Y}Indices`,Q,`${N}`)}`)}),z.push(`prod *= ${u[Y].getByIndices(`input${Y}Indices`)};`)}}),E.push(`for(var ${N}: u32 = 0; ${N} < uniforms.${os(N)}; ${N}++) {`),A.push("}")});let V=R?[...y,`let sum = ${u.map((T,N)=>T.getByIndices(`input${N}Indices`)).join(" * ")};`]:[...y,I,...E,...x,_,...z,$,...A];return`\n ${w.registerUniforms(g.map(T=>({name:`${os(T)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...u,h)}\n\n ${w.mainStart()}\n ${w.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n var outputIndices = ${h.offsetToIndices("global_idx")};\n ${u.map((T,N)=>`var input${N}Indices: ${u[N].type.indices};`).join(`\n`)}\n ${V.join(`\n`)};\n ${h.setByOffset("global_idx","sum")};\n }`};return{name:"Einsum",shaderCache:{hint:o.equation,inputDependencies:e.map(w=>w?"rank":"dims")},getRunData:()=>{let w=g.filter(_=>o.symbolToInfo.has(_)).map(_=>({type:"uint32",data:o.symbolToInfo.get(_)?.dimValue||0}));w.push({type:"uint32",data:l});let y=t.filter((_,I)=>e[I]).map((_,I)=>[...L(_)]).reduce((_,I)=>_.concat(I),w);return a&&y.push(...L(n)),{outputs:[{dims:n,dataType:r}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:y}},getShaderSource:b}},as=(e,t)=>{let r=new Qn(e.inputs,t.equation),o=e.inputs.map((u,l)=>Re(u.dims.length)),n=r.outputDims,s=e.inputs.map((u,l)=>u.dims);e.compute(Al(o,s,e.inputs[0].dataType,r,n))},is=e=>{let t=e.equation.replace(/\\s+/g,"");return ge({equation:t})}});var Tl,us,El,Ol,ds,ls=j(()=>{"use strict";Ne();$e();ve();Tl=e=>{if(!e||e.length!==2)throw new Error("Expand requires 2 input.");let t=e[0].dims,r=Array.from(e[1].getBigInt64Array(),Number),o=r.length{let r=e.length-t.length,o=[];for(let n=0;ne.length>t.length?us(e,t):us(t,e),Ol=e=>{let t=e[0].dims,r=Array.from(e[1].getBigInt64Array(),Number),o=El(t,r),n=e[0].dataType,s=n===9?4:1,u=Math.ceil(U.size(o)/s),l=Re(t.length),a=Re(o.length),p=g=>{let b=l?t.length:t,w=a?o.length:o,y=M("input",n,b,s),_=F("output",n,w,s),I;if(n===9){let $=(x,E,A="")=>`\n let outputIndices${E} = ${_.offsetToIndices(`outputOffset + ${E}u`)};\n let offset${E} = ${y.broadcastedIndicesToOffset(`outputIndices${E}`,_)};\n let index${E} = offset${E} / 4u;\n let component${E} = offset${E} % 4u;\n ${x}[${E}] = ${A}(${y.getByOffset(`index${E}`)}[component${E}]);\n `;I=`\n let outputOffset = global_idx * ${s};\n var data = vec4(0);\n ${$("data",0,"u32")}\n ${$("data",1,"u32")}\n ${$("data",2,"u32")}\n ${$("data",3,"u32")}\n ${_.setByOffset("global_idx","data")}\n }`}else I=`\n let outputIndices = ${_.offsetToIndices("global_idx")};\n let inputOffset = ${y.broadcastedIndicesToOffset("outputIndices",_)};\n ${_.setByOffset("global_idx",y.getByOffset("inputOffset"))}\n }`;return`\n ${g.registerUniform("vec_size","u32").declareVariables(y,_)}\n ${g.mainStart()}\n ${g.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}\n ${I}`},h=[{type:"uint32",data:u}];return l&&h.push(...L(t)),a&&h.push(...L(o)),{name:"Expand",shaderCache:{hint:`${o.length}`,inputDependencies:[l?"rank":"dims"]},getShaderSource:p,getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:h})}},ds=e=>{Tl(e.inputs),e.compute(Ol(e.inputs),{inputs:[0]})}});var Pl,kl,cs,ps,ms=j(()=>{"use strict";Ne();$e();je();ve();Pl=e=>{if(!e||e.length!==2)throw new Error("Gather requires 2 inputs.")},kl=(e,t)=>{let r=e[0].dims,o=e[1].dims,n=r.length,s=U.normalizeAxis(t.axis,n),u=r.slice(0);u.splice(s,1,...o);let l=r[s],a=e[0].dataType===9?4:1,p=Math.ceil(U.size(u)/a),h=Re(e[0].dims.length),g=h?e[0].dims.length:e[0].dims,b=Re(e[1].dims.length),w=b?e[1].dims.length:e[1].dims,y=Re(u.length),_=y?u.length:u,I=[{type:"uint32",data:p},{type:"int32",data:l},{type:"uint32",data:s}];h&&I.push(...L(e[0].dims)),b&&I.push(...L(e[1].dims)),y&&I.push(...L(u));let $=[];$.push(h?"rank":"dims"),$.push(b?"rank":"dims");let x=E=>{let A=M("data",e[0].dataType,g,a),z=M("inputIndices",e[1].dataType,w),R=F("output",e[0].dataType,_,a),V=N=>{let te=o.length,Y=`var indicesIndices${N} = ${z.type.indices}(0);`;for(let K=0;K1?`indicesIndices${N}[${K}]`:`indicesIndices${N}`} = ${u.length>1?`outputIndices${N}[uniforms.axis + ${K}]`:`outputIndices${N}`};`;Y+=`\n var idx${N} = ${z.getByIndices(`indicesIndices${N}`)};\n if (idx${N} < 0) {\n idx${N} = idx${N} + uniforms.axisDimLimit;\n }\n var dataIndices${N} = ${A.type.indices}(0);\n `;for(let K=0,Q=0;K1?`dataIndices${N}[${K}]`:`dataIndices${N}`} = u32(idx${N});`,Q+=te):(Y+=`${n>1?`dataIndices${N}[${K}]`:`dataIndices${N}`} = ${u.length>1?`outputIndices${N}[${Q}]`:`outputIndices${N}`};`,Q++);return Y},T;if(e[0].dataType===9){let N=(te,Y,K="")=>`\n let outputIndices${Y} = ${R.offsetToIndices(`outputOffset + ${Y}u`)};\n ${V(Y)};\n let offset${Y} = ${A.indicesToOffset(`dataIndices${Y}`)};\n let index${Y} = offset${Y} / 4u;\n let component${Y} = offset${Y} % 4u;\n ${te}[${Y}] = ${K}(${A.getByOffset(`index${Y}`)}[component${Y}]);\n `;T=`\n let outputOffset = global_idx * ${a};\n var value = vec4(0);\n ${N("value",0,"u32")}\n ${N("value",1,"u32")}\n ${N("value",2,"u32")}\n ${N("value",3,"u32")}\n ${R.setByOffset("global_idx","value")}\n `}else T=`\n let outputIndices = ${R.offsetToIndices("global_idx")};\n ${V("")};\n let value = ${A.getByIndices("dataIndices")};\n ${R.setByOffset("global_idx","value")};\n `;return`\n ${E.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(A,z,R)}\n ${E.mainStart()}\n ${E.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n ${T}\n }`};return{name:"Gather",shaderCache:{hint:t.cacheKey,inputDependencies:$},getRunData:()=>({outputs:[{dims:u,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:I}),getShaderSource:x}},cs=e=>ge({axis:e.axis}),ps=(e,t)=>{let r=e.inputs;Pl(r),e.compute(kl(e.inputs,t))}});var Rl,Bl,fs,hs,gs=j(()=>{"use strict";$e();je();ve();Rl=e=>{if(!e||e.length!==2)throw new Error("GatherElements requires 2 inputs.");if(e[0].dims.length<1)throw new Error("GatherElements requires that the data input be rank >= 1.");if(e[0].dims.length!==e[1].dims.length)throw new Error(`GatherElements requires that the data input and\n indices input tensors be of same rank.`)},Bl=(e,t)=>{let r=e[0].dims,o=e[0].dataType,n=r.length,s=e[1].dims,u=e[1].dataType,l=U.normalizeAxis(t.axis,n),a=r[l],p=s.slice(0),h=U.size(p),g=M("input",o,n),b=M("indicesInput",u,s.length),w=F("output",o,p.length),y=[{type:"uint32",data:h},{type:"int32",data:a},{type:"uint32",data:l}];return y.push(...L(r)),y.push(...L(s)),y.push(...L(p)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:p,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:y}),getShaderSource:$=>`\n ${$.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(g,b,w)}\n ${$.mainStart()}\n ${$.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n\n let outputIndices = ${w.offsetToIndices("global_idx")};\n\n var idx = ${b.getByOffset("global_idx")};\n if (idx < 0) {\n idx = idx + uniforms.axisDimLimit;\n }\n var inputIndices = ${g.type.indices}(outputIndices);\n ${g.indicesSet("inputIndices","uniforms.axis","u32(idx)")};\n let value = ${g.getByIndices("inputIndices")};\n\n ${w.setByOffset("global_idx","value")};\n }`}},fs=e=>ge({axis:e.axis}),hs=(e,t)=>{let r=e.inputs;Rl(r),e.compute(Bl(e.inputs,t))}});var Dl,Ml,ys,bs,ws=j(()=>{"use strict";$e();ve();Dl=e=>{if(!e)throw new Error("Input is missing");if(e.length<2||e.length>3)throw new Error("Invaid input number.");if(e.length===3&&e[2].dims.length>2)throw new Error("Invalid input shape of C");if(e[0].dataType!==e[1].dataType||e.length===3&&e[0].dataType!==e[2].dataType)throw new Error("Input types are mismatched")},Ml=(e,t)=>{let r=e[0].dims.slice(),o=e[1].dims.slice(),[n,s,u]=Hr.getShapeOfGemmResult(r,t.transA,o,t.transB,e.length===3?e[2].dims:void 0),l=[n,s];if(!l)throw new Error("Can\'t use gemm on the given tensors");let a=U.size(l),p=[{type:"uint32",data:a},{type:"uint32",data:n},{type:"uint32",data:s},{type:"uint32",data:u},{type:"float32",data:t.alpha},{type:"float32",data:t.beta}],h=["type","type"];e.length===3&&(p.push(...L(e[2].dims)),h.push("rank")),p.push(...L(l));let g=b=>{let w="";t.transA&&t.transB?w="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":t.transA&&!t.transB?w="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!t.transA&&t.transB?w="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!t.transA&&!t.transB&&(w="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let y=t.alpha===1?"":"value *= uniforms.alpha;",_=M("a",e[0].dataType,e[0].dims),I=M("b",e[1].dataType,e[1].dims),$=_.type.value,x=null,E=[_,I];e.length===3&&(x=M("c",e[2].dataType,e[2].dims.length),E.push(x));let A=F("output",e[0].dataType,l.length);E.push(A);let z=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"},{name:"alpha",type:"f32"},{name:"beta",type:"f32"}];return`\n ${b.registerUniforms(z).declareVariables(...E)}\n\n ${b.mainStart()}\n ${b.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n\n let m = global_idx / uniforms.N;\n let n = global_idx % uniforms.N;\n\n var value = ${$}(0);\n for (var k: u32 = 0u; k < uniforms.K; k++) {\n ${w}\n }\n\n ${y}\n ${(()=>x!=null?`let cOffset = ${x.broadcastedIndicesToOffset("vec2(m, n)",A)}; value += ${$}(uniforms.beta) * ${x.getByOffset("cOffset")};`:"")()}\n output[global_idx] = value;\n }`};return{name:"Gemm",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:h},getRunData:()=>({outputs:[{dims:l,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:p}),getShaderSource:g}},ys=e=>{let t=e.transA,r=e.transB,o=e.alpha,n=e.beta;return{transA:t,transB:r,alpha:o,beta:n,cacheKey:`${e.transA};${e.transB};${e.alpha===1}`}},bs=(e,t)=>{Dl(e.inputs),e.compute(Ml(e.inputs,t))}});var zl,Ul,Vl,vs,$s=j(()=>{"use strict";Ne();$e();ve();zl=(e,t)=>{let r=e[0].dims,o=r,n=2,s=U.sizeToDimension(r,n),u=U.sizeFromDimension(r,n),l=Fe(u),a=u/l,p=[r[0],r[1],a],h=["rank","type","type"],g=[{type:"uint32",data:u},{type:"uint32",data:a}];g.push(...L(p),...L(p));let b=w=>{let y=M("x",e[0].dataType,p.length,l),_=M("scale",e[1].dataType,e[1].dims),I=M("bias",e[2].dataType,e[2].dims),$=F("output",e[0].dataType,p.length,l),x=[y,_,I,$],E=y.type.value,A=l===1?"f32":`vec${l}`,z=64,R=[{name:"normSize",type:"u32"},{name:"normPackedSize",type:"u32"}];return`\n var meanShared : f32;\n var squaredNormShared : f32;\n var workgroupShared : array<${A}, ${z}>;\n const workgroupSize = ${z}u;\n ${w.registerUniforms(R).declareVariables(...x)}\n ${w.mainStart(z)}\n let norm = global_idx / workgroupSize;\n let batch = norm / uniforms.x_shape[1];\n let channel = norm % uniforms.x_shape[1];\n let localIndex = local_id.x;\n\n // initialize workgroup memory\n var initial = ${A}(0);\n for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) {\n initial = initial + ${A}(${y.get("batch","channel","h")});\n }\n workgroupShared[localIndex] = initial;\n workgroupBarrier();\n\n // Calculate the mean of current channel data.\n for (var currSize = workgroupSize >> 1; currSize > 0; currSize = currSize >> 1) {\n if (localIndex < currSize) {\n workgroupShared[localIndex] = workgroupShared[localIndex] + workgroupShared[localIndex + currSize];\n }\n workgroupBarrier();\n }\n if (localIndex == 0) {\n meanShared = ${Je("workgroupShared[0]",l)} / f32(uniforms.normSize);\n }\n workgroupBarrier();\n\n // reinitialize workgroup memory.\n initial = ${A}(0);\n for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) {\n let deviation = ${A}(${y.get("batch","channel","h")}) - ${A}(meanShared);\n initial = initial + deviation * deviation;\n }\n workgroupShared[localIndex] = initial;\n workgroupBarrier();\n\n // Calculate the sum of square of deviation of current channel data.\n for (var currSize = workgroupSize >> 1; currSize > 0; currSize = currSize >> 1) {\n if (localIndex < currSize) {\n workgroupShared[localIndex] = workgroupShared[localIndex] + workgroupShared[localIndex + currSize];\n }\n workgroupBarrier();\n }\n if (localIndex == 0) {\n squaredNormShared = ${Je("workgroupShared[0]",l)};\n }\n workgroupBarrier();\n\n let invStdDev = inverseSqrt(squaredNormShared / f32(uniforms.normSize) + f32(${t.epsilon}));\n let channelScale = invStdDev * f32(${_.getByOffset("channel")});\n let channelShift = f32(${I.getByOffset("channel")}) - meanShared * channelScale;\n for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) {\n let value = ${y.get("batch","channel","h")} * ${E}(${A}(channelScale)) + ${E}(${A}(channelShift));\n ${$.set("batch","channel","h","value")};\n }\n }`};return{name:"InstanceNormalization",shaderCache:{hint:`${t.epsilon};${l}`,inputDependencies:h},getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:s},programUniforms:g}),getShaderSource:b}},Ul=(e,t,r,o,n,s,u,l)=>{let a=Fe(u),p=64,h=a===1?"vec2f":`mat2x${a}f`,g=a===1?"f32":`vec${a}f`,b=(R,V)=>`${h}(${R}, ${V})`,w=n*u/a,y=Math.ceil(s/p),_=["type"],I=[{type:"uint32",data:y},{type:"uint32",data:s},{type:"uint32",data:Math.floor(u/a)},{type:"uint32",data:Math.floor(s*u/a)}],$=R=>{let V=M("input",t.dataType,t.dims,a);return`\n ${R.declareVariables(V)}\n @group(0) @binding(1) var output : array<${h}>;\n struct Uniforms {wg_size:u32, H:u32, C:u32, image_size:u32};\n @group(0) @binding(2) var uniforms: Uniforms;\n\n ${R.mainStart(p)}\n let currentImageNumber = global_idx / ${p} / uniforms.C;\n let currentChannelNumber = (global_idx / ${p}) % uniforms.C;\n let wgId = global_idx % ${p};\n let wgOffset = wgId * uniforms.wg_size;\n if (wgOffset >= uniforms.H) {\n return;\n }\n let wgMax = min(wgOffset + uniforms.wg_size, uniforms.H);\n\n let offset = currentImageNumber * uniforms.image_size + currentChannelNumber;\n var sum = ${Ze("f32",a)};\n var squaredSum = ${Ze("f32",a)};\n for (var i: u32 = wgOffset; i < wgMax; i++) {\n let value = ${g}(input[offset + i * uniforms.C]);\n sum += value;\n squaredSum += value * value;\n }\n output[global_idx] = ${b("sum","squaredSum")};\n }`},x=e.compute({name:"InstanceNormComputeMean",shaderCache:{hint:`${a}`,inputDependencies:_},getRunData:()=>({outputs:[{dims:[n,u,p,2],dataType:1}],dispatchGroup:{x:n*u/a},programUniforms:I}),getShaderSource:$},{inputs:[t],outputs:[-1]})[0],E=[{type:"uint32",data:w},{type:"uint32",data:s},{type:"uint32",data:Math.floor(u/a)},{type:"uint32",data:Math.floor(p*u/a)}],A=["type","type","type"],z=R=>{let V=M("scale",r.dataType,r.dims,a),T=M("bias",o.dataType,o.dims,a);return`\n @group(0) @binding(0) var input : array<${h}>;\n @group(0) @binding(1) var scale : array<${V.type.storage}>;\n @group(0) @binding(2) var bias : array<${T.type.storage}>;\n @group(0) @binding(3) var output : array<${h}>;\n struct Uniforms {units_of_work : u32, H: u32, C : u32, image_size : u32};\n @group(0) @binding(4) var uniforms: Uniforms;\n\n ${R.mainStart()}\n ${R.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.units_of_work")}\n let currentImageNumber = global_idx / uniforms.C;\n let currentChannelNumber = global_idx % uniforms.C;\n\n let offset = currentImageNumber * uniforms.image_size;\n var sum = ${Ze("f32",a)};\n var squaredSum = ${Ze("f32",a)};\n for (var i: u32 = 0; i < ${p}; i++) {\n let value = input[offset + i + currentChannelNumber * ${p}];\n sum += value[0];\n squaredSum += value[1];\n }\n sum = sum / f32(uniforms.H);\n squaredSum = squaredSum / f32(uniforms.H);\n let invStdDev = inverseSqrt(squaredSum - sum * sum + f32(${l}));\n let channelScale = invStdDev * ${g}(scale[currentChannelNumber]);\n let channelShift = ${g}(bias[currentChannelNumber]) - sum * channelScale;\n\n output[global_idx] = ${b("channelScale","channelShift")};\n }`};return e.compute({name:"InstanceNormComputeChannelScaleShift",shaderCache:{hint:`${a};${l}`,inputDependencies:A},getRunData:()=>({outputs:[{dims:[n,u,2],dataType:1}],dispatchGroup:{x:Math.ceil(w/64)},programUniforms:E}),getShaderSource:z},{inputs:[x,r,o],outputs:[-1]})[0]},Vl=(e,t,r)=>{let o=t[0].dims,n=o,s=o[0],u=o[o.length-1],l=U.sizeFromDimension(o,1)/u,a=Fe(u),p=U.size(n)/a,h=[{type:"uint32",data:l},{type:"uint32",data:Math.floor(u/a)}],g=["type","type"],b=Ul(e,t[0],t[1],t[2],s,l,u,r.epsilon),w=y=>{let _=Le(t[0].dataType),I=a===1?"vec2f":`mat2x${a}f`,$=a===1?_:`vec${a}<${_}>`,x=M("input",t[0].dataType,t[0].dims,a),E=F("output",t[0].dataType,n,a);return`\n @group(0) @binding(0) var input : array<${x.type.storage}>;\n @group(0) @binding(1) var scaleInput : array<${I}>;\n @group(0) @binding(2) var output : array<${E.type.storage}>;\n struct Uniforms {H: u32, C : u32};\n @group(0) @binding(3) var uniforms: Uniforms;\n\n ${y.mainStart()}\n let currentImageNumber = global_idx / (uniforms.C * uniforms.H);\n let currentChannelNumber = global_idx % uniforms.C;\n\n let scaleOffset = currentImageNumber * uniforms.C + currentChannelNumber;\n let scale = scaleInput[scaleOffset];\n output[global_idx] = fma(input[global_idx], ${$}(scale[0]), ${$}(scale[1]));\n }`};e.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${a}`,inputDependencies:g},getRunData:()=>({outputs:[{dims:n,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:h}),getShaderSource:w},{inputs:[t[0],b]})},vs=(e,t)=>{t.format==="NHWC"?Vl(e,e.inputs,t):e.compute(zl(e.inputs,t))}});var Nl,Wl,Ss,xs=j(()=>{"use strict";Ne();$e();ve();Nl=e=>{if(!e||e.length<2)throw new Error("layerNorm requires at least 2 inputs.")},Wl=(e,t,r)=>{let o=e[0].dims,n=e[1],s=e[2],u=o,l=U.normalizeAxis(t.axis,o.length),a=U.sizeToDimension(o,l),p=U.sizeFromDimension(o,l),h=U.size(n.dims),g=s?U.size(s.dims):0;if(h!==p||s&&g!==p)throw new Error(`Size of X.shape()[axis:] == ${p}.\n Size of scale and bias (if provided) must match this.\n Got scale size of ${h} and bias size of ${g}`);let b=[];for(let A=0;A1,$=r>2,x=A=>{let z=Le(e[0].dataType),R=[M("x",e[0].dataType,e[0].dims,w),M("scale",n.dataType,n.dims,w)];s&&R.push(M("bias",s.dataType,s.dims,w)),R.push(F("output",e[0].dataType,u,w)),I&&R.push(F("mean_data_output",1,b)),$&&R.push(F("inv_std_output",1,b));let V=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return`\n ${A.registerUniforms(V).declareVariables(...R)}\n ${A.mainStart()}\n ${A.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")}\n let offset = global_idx * uniforms.norm_size_vectorized;\n var meanVector = ${Ze("f32",w)};\n var meanSquareVector = ${Ze("f32",w)};\n\n for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) {\n let value = ${at(z,w,"x[h + offset]")};\n meanVector += value;\n meanSquareVector += value * value;\n }\n let mean = ${Je("meanVector",w)} / uniforms.norm_size;\n let invStdDev =\n inverseSqrt(${Je("meanSquareVector",w)} / uniforms.norm_size - mean * mean + uniforms.epsilon);\n\n for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) {\n let f32input = ${at(z,w,"x[j + offset]")};\n let f32scale = ${at(z,w,"scale[j]")};\n output[j + offset] = ${R[0].type.value}((f32input - mean) * invStdDev * f32scale\n ${s?`+ ${at(z,w,"bias[j]")}`:""}\n );\n }\n\n ${I?"mean_data_output[global_idx] = mean":""};\n ${$?"inv_std_output[global_idx] = invStdDev":""};\n }`},E=[{dims:u,dataType:e[0].dataType}];return I&&E.push({dims:b,dataType:1}),$&&E.push({dims:b,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${w};${r}`,inputDependencies:y},getRunData:()=>({outputs:E,dispatchGroup:{x:Math.ceil(a/64)},programUniforms:_}),getShaderSource:x}},Ss=(e,t)=>{Nl(e.inputs),e.compute(Wl(e.inputs,t,e.outputCount))}});var Hl,Cs,_s,Gl,Xn,Is,As=j(()=>{"use strict";$e();je();Nr();Un();ve();jt();Hl=(e,t)=>{let r=e[0],o=e[1],n=e[2],s=e[3],u=e[4],l=e[5],a=e[6],p=e[7];if(r.dims.length!==3&&r.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let h=!1,g=r.dims[0],b=r.dims[1],w=r.dims.length===3?h?r.dims[2]/3:r.dims[2]:t.numHeads*r.dims[4],y=b,_=0,I=0,$=Math.floor(w/t.numHeads);if(a&&p){if(a.dims.length!==4)throw new Error(\'Input "past_key" is expected to have 4 dimensions\');if(p.dims.length!==4)throw new Error(\'Input "past_value" is expected to have 4 dimensions\');_=a.dims[2],I=a.dims[2]}else if(a||p)throw new Error(\'Input "past_key" and "past_value" shall be both present or both absent\');let x;if(o){if(r.dims.length!==3)throw new Error(\'Input "query" is expected to have 3 dimensions when key is given\');if(o.dims.length<3||o.dims.length>5)throw new Error(\'Input "key" is expected to have 3, 4, or 5 dimensions\');if(r.dims[0]!==o.dims[0])throw new Error(\'Input "query" and "key" shall have same dim 0 (batch size)\');if(o.dims.length===3){if(o.dims[2]!==r.dims[2])throw new Error(\'Input "query" and "key" shall have same dim 2 (hidden_size)\');x=2,y=o.dims[1]}else if(o.dims.length===5){if(o.dims[2]!==t.numHeads||o.dims[3]!==2||o.dims[4]!==$)throw new Error(\'Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv\');if(n)throw new Error(\'Expect "value" be none when "key" has packed kv format.\');x=5,y=o.dims[1]}else{if(o.dims[1]!==t.numHeads||o.dims[3]!==$)throw new Error(\'Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key\');x=0,y=o.dims[2]}}else{if(r.dims.length!==3&&r.dims.length!==5)throw new Error(\'Input "query" is expected to have 3 or 5 dimensions when key is empty\');if(r.dims.length===5&&(r.dims[2]!==t.numHeads||r.dims[3]!==3))throw new Error(\'Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv\');x=3}if(s){if(s.dims.length!==1)throw new Error(\'Input "bias" is expected to have 1 dimension\');if(n&&r.dims.length===5&&r.dims[3]===2)throw new Error("bias is not allowed for packed kv.")}let E=0;if(u){E=8;let T=u.dims;throw T.length===1?T[0]===g?E=1:T[0]===3*g+2&&(E=3):T.length===2&&T[0]===g&&T[1]===y&&(E=5),E===8?new Error(\'Input "key_padding_mask" shape shall be (batch_size) or (batch_size, kv_sequence_length)\'):new Error("Mask not supported")}let A=!1,z=w;if(n){if(n.dims.length!==3&&n.dims.length!==4)throw new Error(\'Input "value" is expected to have 3 or 4 dimensions\');if(r.dims[0]!==n.dims[0])throw new Error(\'Input "query" and "value" shall have same dim 0 (batch_size)\');if(n.dims.length===3){if(y!==n.dims[1])throw new Error(\'Input "key" and "value" shall have the same dim 1 (kv_sequence_length)\');z=n.dims[2]}else{if(y!==n.dims[2])throw new Error(\'Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)\');z=n.dims[1]*n.dims[3],A=!0}}let R=_+y,V=!1;if(u)throw new Error("Key padding mask is not supported");if(l)throw new Error("extraAddQk is not supported");if(a)throw new Error("pastKey is not supported");if(p)throw new Error("pastValue is not supported");return{batchSize:g,sequenceLength:b,pastSequenceLength:_,kvSequenceLength:y,totalSequenceLength:R,maxSequenceLength:I,inputHiddenSize:0,hiddenSize:w,vHiddenSize:z,headSize:$,vHeadSize:Math.floor(z/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:E,scale:t.scale,broadcastResPosBias:V,passPastInKv:A,qkvFormat:x}},Cs=e=>ge({...e}),_s=ge({perm:[0,2,1,3]}),Gl=(e,t,r,o,n,s,u)=>{let l=[o,n,s],a=U.size(l),p=[{type:"uint32",data:a},{type:"uint32",data:u},{type:"uint32",data:s}],h=g=>{let b=F("qkv_with_bias",t.dataType,l),w=M("qkv",t.dataType,l),y=M("bias",r.dataType,l),_=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return`\n ${g.registerUniforms(_).declareVariables(w,y,b)}\n ${g.mainStart()}\n ${g.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n let bias_offset_idx = (global_idx % uniforms.hidden_size) + uniforms.bias_offset;\n\n qkv_with_bias[global_idx] = qkv[global_idx] + bias[bias_offset_idx];\n }`};return e.compute({name:"MultiHeadAttentionAddBias",shaderCache:{inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:l,dataType:t.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:p}),getShaderSource:h},{inputs:[t,r],outputs:[-1]})[0]},Xn=(e,t,r,o,n,s,u,l)=>{let a=s;if(u){if(o===1)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return a=Gl(e,s,u,t,o,r*n,l),a=a.reshape([t,o,r,n]),e.compute(it(a,_s.perm),{inputs:[a],outputs:[-1]})[0]}else return s.dims.length===3&&(a=s.reshape([t,o,r,n])),e.compute(it(a,_s.perm),{inputs:[a],outputs:[-1]})[0]},Is=(e,t)=>{let r=Hl(e.inputs,t);if(e.inputs[0].dims.length===5)throw new Error("Packed QKV is not implemented");if(e.inputs[1]?.dims.length===5)throw new Error("Packed KV is not implemented");let o=e.inputs[1]&&e.inputs[2]&&e.inputs[1].dims.length===4&&e.inputs[2].dims.length===4,n=Xn(e,r.batchSize,r.numHeads,r.sequenceLength,r.headSize,e.inputs[0],e.inputs[3],0);if(o)return Kr(e,n,e.inputs[1],e.inputs[2],e.inputs[4],void 0,void 0,void 0,e.inputs[5],r,t);let s=Xn(e,r.batchSize,r.numHeads,r.kvSequenceLength,r.headSize,e.inputs[1],e.inputs[3],r.hiddenSize),u=Xn(e,r.batchSize,r.numHeads,r.kvSequenceLength,r.vHeadSize,e.inputs[2],e.inputs[3],2*r.hiddenSize);Kr(e,n,s,u,e.inputs[4],void 0,e.inputs[6],e.inputs[7],e.inputs[5],r,t)}});var Ll,Fl,jl,ql,Kl,Yl,Zl,Ql,Ts,Es=j(()=>{"use strict";Ne();$e();ve();Ll=e=>{if(!e||e.length<1)throw new Error("Too few inputs");if(e[0].dataType!==1)throw new Error("Input type must be float.");if(e.length>=2){let t=e[0].dims.length*2===e[1].dims[0];if(e.length===4&&(t=e[3].dims[0]*2===e[1].dims[0]),!t)throw new Error("The pads should be a 1D tensor of shape [2 * input_rank] or [2 * num_axes].")}},Fl=(e,t,r)=>{let o="";for(let n=t-1;n>=0;--n)o+=`\n k = i32(${e.indicesGet("indices",n)}) - ${ce("uniforms.pads",n,r)};\n if (k < 0) {\n break;\n }\n if (k >= i32(${ce("uniforms.x_shape",n,t)})) {\n break;\n }\n offset += k * i32(${ce("uniforms.x_strides",n,t)});\n `;return`\n value = ${e.type.value}(uniforms.constant_value);\n for (var i = 0; i < 1; i++) {\n var offset = 0;\n var k = 0;\n ${o}\n value = x[offset];\n }\n `},jl=(e,t,r)=>{let o="";for(let n=t-1;n>=0;--n)o+=`\n k = i32(${e.indicesGet("indices",n)}) - ${ce("uniforms.pads",n,r)};\n if (k < 0) {\n k = -k;\n }\n {\n let _2n_1 = 2 * (i32(${ce("uniforms.x_shape",n,t)}) - 1);\n k = k % _2n_1;\n if(k >= i32(${ce("uniforms.x_shape",n,t)})) {\n k = _2n_1 - k;\n }\n }\n offset += k * i32(${ce("uniforms.x_strides",n,t)});\n `;return`\n var offset = 0;\n var k = 0;\n ${o}\n value = x[offset];\n `},ql=(e,t,r)=>{let o="";for(let n=t-1;n>=0;--n)o+=`\n k = i32(${e.indicesGet("indices",n)}) - ${ce("uniforms.pads",n,r)};\n if (k < 0) {\n k = 0;\n }\n if (k >= i32(${ce("uniforms.x_shape",n,t)})) {\n k = i32(${ce("uniforms.x_shape",n,t)}) - 1;\n }\n offset += k * i32(${ce("uniforms.x_strides",n,t)});\n `;return`\n var offset = 0;\n var k = 0;\n ${o}\n value = x[offset];\n `},Kl=(e,t,r)=>{let o="";for(let n=t-1;n>=0;--n)o+=`\n k = i32(${e.indicesGet("indices",n)}) - ${ce("uniforms.pads",n,r)};\n if (k < 0) {\n k += i32(${ce("uniforms.x_shape",n,t)}]);\n }\n if (k >= i32(${ce("uniforms.x_shape",n,t)})) {\n k -= i32(${ce("uniforms.x_shape",n,t)});\n }\n offset += k * i32(${ce("uniforms.x_strides",n,t)});\n `;return`\n var offset = 0;\n var k = 0;\n ${o}\n value = x[offset];\n `},Yl=(e,t,r)=>{switch(r.mode){case 0:return Fl(e,t,r.pads.length);case 1:return jl(e,t,r.pads.length);case 2:return ql(e,t,r.pads.length);case 3:return Kl(e,t,r.pads.length);default:throw new Error("Invalid mode")}},Zl=(e,t)=>{let r=U.padShape(e[0].dims.slice(),t.pads),o=e[0].dims,s=[{type:"uint32",data:U.size(r)},{type:"uint32",data:t.pads}];if(t.mode===0){let a=Xe(e[0].dataType);s.push({type:a,data:t.value})}s.push(...L(e[0].dims),...L(r));let u=["rank"],l=a=>{let p=F("output",e[0].dataType,r.length),h=M("x",e[0].dataType,o.length),g=h.type.value,b=Yl(p,o.length,t),w=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:t.pads.length}];return t.mode===0&&w.push({name:"constant_value",type:g}),`\n ${a.registerUniforms(w).declareVariables(h,p)}\n ${a.mainStart()}\n ${a.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n\n let indices = ${p.offsetToIndices("global_idx")};\n\n var value = ${g}(0);\n ${b}\n output[global_idx] = value;\n }`};return{name:"Pad",shaderCache:{hint:`${t.mode}`,inputDependencies:u},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(U.size(r)/64)},programUniforms:s}),getShaderSource:l}},Ql=(e,t)=>{if(e.length>1){let r=e[1].getBigInt64Array(),o=e.length>=3&&e[2].data?e[2].getFloat32Array()[0]:0,n=e[0].dims.length,s=new Int32Array(2*n).fill(0);if(e.length>=4){let l=e[3].getBigInt64Array();for(let a=0;as[Number(a)]=Number(l));let u=[];return s.forEach(l=>u.push(l)),{mode:t.mode,value:o,pads:u}}else return t},Ts=(e,t)=>{Ll(e.inputs);let r=Ql(e.inputs,t);e.compute(Zl(e.inputs,r),{inputs:[0]})}});var nn,Os,Ps,ks,Rs,Xl,Jl,Bs,Ds,Ms,zs,Us,Vs,Ns,Ws,Hs,Gs,Ls,Fs,js=j(()=>{"use strict";Lt();$e();ve();nn=e=>{if(Gt.webgpu.validateInputContent&&(!e||e.length!==1))throw new Error("Pool ops requires 1 input.")},Os=(e,t,r)=>{let o=t.format==="NHWC",n=e.dims.slice();o&&n.splice(1,0,n.pop());let s=Object.hasOwnProperty.call(t,"dilations"),u=t.kernelShape.slice(),l=t.strides.slice(),a=s?t.dilations.slice():[],p=t.pads.slice();Bt.adjustPoolAttributes(r,n,u,l,a,p);let h=Bt.computePoolOutputShape(r,n,l,a,u,p,t.autoPad),g=Object.assign({},t);s?Object.assign(g,{kernelShape:u,strides:l,pads:p,dilations:a,cacheKey:t.cacheKey}):Object.assign(g,{kernelShape:u,strides:l,pads:p,cacheKey:t.cacheKey});let b=h.slice();return b.push(b.splice(1,1)[0]),[g,o?b:h]},Ps=(e,t)=>{let r=t.format==="NHWC",o=U.size(e),n=U.size(t.kernelShape),s=[{type:"uint32",data:o},{type:"uint32",data:n}],u=[{name:"outputSize",type:"u32"},{name:"kernelSize",type:"u32"}];if(t.kernelShape.length<=2){let l=t.kernelShape[t.kernelShape.length-1],a=t.strides[t.strides.length-1],p=t.pads[t.pads.length/2-1],h=t.pads[t.pads.length-1],g=!!(p+h);s.push({type:"uint32",data:l},{type:"uint32",data:a},{type:"uint32",data:p},{type:"uint32",data:h}),u.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let b=!1;if(t.kernelShape.length===2){let w=t.kernelShape[t.kernelShape.length-2],y=t.strides[t.strides.length-2],_=t.pads[t.pads.length/2-2],I=t.pads[t.pads.length-2];b=!!(_+I),s.push({type:"uint32",data:w},{type:"uint32",data:y},{type:"uint32",data:_},{type:"uint32",data:I}),u.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[s,u,!0,g,b]}else{if(r)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let l=U.computeStrides(t.kernelShape);s.push({type:"uint32",data:l},{type:"uint32",data:t.pads},{type:"uint32",data:t.strides}),u.push({name:"kernelStrides",type:"u32",length:l.length},{name:"pads",type:"u32",length:t.pads.length},{name:"strides",type:"u32",length:t.strides.length});let a=t.pads.reduce((p,h)=>p+h);return[s,u,!!a,!1,!1]}},ks=(e,t,r,o,n,s,u,l,a,p,h,g)=>{let b=n.format==="NHWC",w=t.type.value,y=F("output",t.type.tensor,o);if(n.kernelShape.length<=2){let _="",I="",$="",x=r-(b?2:1);if(h?_=`\n for (var i: u32 = 0u; i < uniforms.kw; i++) {\n xIndices[${x}] = indices[${x}] * uniforms.sw - uniforms.pwStart + i;\n if (xIndices[${x}] < 0 || xIndices[${x}]\n >= uniforms.x_shape[${x}]) {\n pad++;\n continue;\n }\n let x_val = x[${t.indicesToOffset("xIndices")}];\n ${s}\n }`:_=`\n for (var i: u32 = 0u; i < uniforms.kw; i++) {\n xIndices[${x}] = indices[${x}] * uniforms.sw - uniforms.pwStart + i;\n let x_val = x[${t.indicesToOffset("xIndices")}];\n ${s}\n }`,n.kernelShape.length===2){let A=r-(b?3:2);g?I=`\n for (var j: u32 = 0u; j < uniforms.kh; j++) {\n xIndices[${A}] = indices[${A}] * uniforms.sh - uniforms.phStart + j;\n if (xIndices[${A}] < 0 || xIndices[${A}] >= uniforms.x_shape[${A}]) {\n pad += i32(uniforms.kw);\n continue;\n }\n `:I=`\n for (var j: u32 = 0u; j < uniforms.kh; j++) {\n xIndices[${A}] = indices[${A}] * uniforms.sh - uniforms.phStart + j;\n `,$=`\n }\n `}return`\n ${e.registerUniforms(a).declareVariables(t,y)}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n\n let indices = ${y.offsetToIndices("global_idx")};\n var xIndices = ${y.offsetToIndices("global_idx")};\n\n var value = ${w}(${l});\n var pad = 0;\n ${I}\n ${_}\n ${$}\n ${u}\n\n output[global_idx] = value;\n }`}else{if(b)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let _=n.kernelShape.length,I=n.pads.length,$="";return p?$=`\n if (xIndices[j] >= uniforms.x_shape[j]) {\n pad++;\n isPad = true;\n break;\n }\n }\n if (!isPad) {\n let x_val = x[${t.indicesToOffset("xIndices")}];\n ${s}\n }`:$=`\n }\n let x_val = x[${t.indicesToOffset("xIndices")}];\n ${s}\n `,`\n ${e.registerUniforms(a).declareVariables(t,y)}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n let indices = ${y.offsetToIndices("global_idx")};\n var xIndices = ${y.offsetToIndices("global_idx")};\n\n var offsets: array;\n\n var value = ${w}(${l});\n var pad = 0;\n var isPad = false;\n\n for (var i: u32 = 0u; i < uniforms.kernelSize; i++) {\n var offset = i;\n for (var j = 0u; j < ${_-1}u; j++) {\n offsets[j] = offset / ${ce("uniforms.kernelStrides","j",_)};\n offset -= offsets[j] * ${ce("uniforms.kernelStrides","j",_)};\n }\n offsets[${_-1}] = offset;\n\n isPad = false;\n for (var j = ${r-_}u; j < ${r}u; j++) {\n xIndices[j] = indices[j] * ${ce("uniforms.strides",`j - ${r-_}u`,_)}\n + offsets[j - ${r-_}u] - ${ce("uniforms.pads","j - 2u",I)};\n ${$}\n }\n ${u}\n\n output[global_idx] = value;\n }`}},Rs=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,Xl=e=>`${Rs(e)};${e.countIncludePad}`,Jl=e=>`${Rs(e)};${e.storageOrder};${e.dilations}`,Bs=e=>({format:e.format,autoPad:["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],ceilMode:e.ceil_mode,kernelShape:e.kernel_shape,strides:e.strides,pads:e.pads}),Ds=(e,t,r,o)=>{let[n,s]=Os(t,o,r),u=M("x",t.dataType,t.dims.length),l=u.type.value,a="value += x_val;",p="";n.countIncludePad?p+=`value /= ${l}(uniforms.kernelSize);`:p+=`value /= ${l}(i32(uniforms.kernelSize) - pad);`;let[h,g,b,w,y]=Ps(s,n);h.push(...L(t.dims),...L(s));let _=["rank"];return{name:e,shaderCache:{hint:`${o.cacheKey};${b};${w};${y}`,inputDependencies:_},getRunData:()=>({outputs:[{dims:s,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(U.size(s)/64)},programUniforms:h}),getShaderSource:I=>ks(I,u,t.dims.length,s.length,n,a,p,0,g,b,w,y)}},Ms=e=>{let t=e.count_include_pad!==0,r=Bs(e);if(r.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");let o={countIncludePad:t,...r,cacheKey:""};return{...o,cacheKey:Xl(o)}},zs=(e,t)=>{nn(e.inputs),e.compute(Ds("AveragePool",e.inputs[0],!1,t))},Us={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},Vs=e=>{let t=e.format;return{format:t,...Us,cacheKey:t}},Ns=(e,t)=>{nn(e.inputs),e.compute(Ds("GlobalAveragePool",e.inputs[0],!0,t))},Ws=(e,t,r,o)=>{let[n,s]=Os(t,o,r),u=`\n value = max(x_val, value);\n `,l="",a=M("x",t.dataType,t.dims.length),p=["rank"],[h,g,b,w,y]=Ps(s,n);return h.push(...L(t.dims),...L(s)),{name:e,shaderCache:{hint:`${o.cacheKey};${b};${w};${y}`,inputDependencies:p},getRunData:()=>({outputs:[{dims:s,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(U.size(s)/64)},programUniforms:h}),getShaderSource:_=>ks(_,a,t.dims.length,s.length,n,u,l,-1e5,g,b,w,y)}},Hs=(e,t)=>{nn(e.inputs),e.compute(Ws("MaxPool",e.inputs[0],!1,t))},Gs=e=>{let t=e.storage_order,r=e.dilations,o=Bs(e);if(t!==0)throw new Error("column major storage order is not yet supported for MaxPool");if(o.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");let n={storageOrder:t,dilations:r,...o,cacheKey:""};return{...n,cacheKey:Jl(n)}},Ls=e=>{let t=e.format;return{format:t,...Us,cacheKey:t}},Fs=(e,t)=>{nn(e.inputs),e.compute(Ws("GlobalMaxPool",e.inputs[0],!0,t))}});var tc,rc,qs,Ks=j(()=>{"use strict";Lt();Ne();ve();tc=(e,t,r)=>{let o=e===t,n=et&&r>0;if(o||n||s)throw new Error("Range these inputs\' contents are invalid.")},rc=(e,t,r,o)=>{let n=Math.abs(Math.ceil((t-e)/r)),s=[n],u=n,l=Xe(o),a=[{type:"uint32",data:u},{type:l,data:e},{type:l,data:r},...L(s)],p=h=>{let g=F("output",o,s.length),b=g.type.value,w=[{name:"outputSize",type:"u32"},{name:"start",type:b},{name:"delta",type:b}];return`\n ${h.registerUniforms(w).declareVariables(g)}\n ${h.mainStart()}\n ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n output[global_idx] = uniforms.start + ${b}(global_idx) * uniforms.delta;\n }`};return{name:"Range",shaderCache:{hint:`${o}`},getShaderSource:p,getRunData:()=>({outputs:[{dims:s,dataType:o}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:a})}},qs=e=>{let t=0,r=0,o=0;e.inputs[0].dataType===6?(t=e.inputs[0].getInt32Array()[0],r=e.inputs[1].getInt32Array()[0],o=e.inputs[2].getInt32Array()[0]):e.inputs[0].dataType===1&&(t=e.inputs[0].getFloat32Array()[0],r=e.inputs[1].getFloat32Array()[0],o=e.inputs[2].getFloat32Array()[0]),Gt.webgpu.validateInputContent&&tc(t,r,o),e.compute(rc(t,r,o,e.inputs[0].dataType),{inputs:[]})}});var nc,oc,ac,ic,sc,uc,dc,lc,cc,pc,mc,Ys,fc,hc,gc,yc,bc,Zs,Qs,Xs=j(()=>{"use strict";$e();je();ve();nc=(e,t)=>{if(e.every(r=>r>0||(()=>{throw new Error("Resize requires scales input values to be positive")})),e.length>0){if(t.mode==="linear"){if(!(e.length===2||e.length===3||e.length===4&&e[0]===1&&e[1]===1||e.length===4&&e[0]===1&&e[3]===1||e.length===5&&e[0]===1&&e[1]===1))throw new Error(`For linear mode, Resize requires scales to be 2D, 3D, 4D with either two outermost or one innermost and\n one outermost scale values equal to 1, or 5D with two outermost scale values equal to 1`)}else if(t.mode==="cubic"&&!(e.length===2||e.length===4&&e[0]===1&&e[1]===1||e.length===4&&e[0]===1&&e[3]===1))throw new Error("Resize requires scales input size to be 2 or 4 for cubic mode")}},oc=(e,t,r)=>{t.every(n=>n>=0&&n{throw new Error("Resize requires axes input values to be positive and less than rank")}));let o=new Array(r).fill(1);return t.forEach((n,s)=>o[n]=e[s]),o},ac=(e,t,r,o,n,s)=>{let[u,l,a]=r>10?[1,2,3]:[-1,e.length>1?1:-1,-1],p=e[0].dims.length;if(u>0&&e.length>u&&e[u].dims.length>0)e[u].getFloat32Array().forEach(h=>s.push(h));else if(t.coordinateTransformMode==="tf_crop_and_resize")throw new Error("Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize");if(l>0&&e.length>l&&e[l].dims.length>0){if(e[l].getFloat32Array().forEach(h=>o.push(h)),o.length!==0&&o.length!==p&&r>=18&&o.length!==t.axes.length)throw new Error("Resize requires scales input size to be same as input rank or axes size for opset 18 and up");nc(o,t),t.axes.length>0&&oc(o,t.axes,p).forEach((h,g)=>o[g]=h)}if(a>0&&e.length>a&&(e[a].getBigInt64Array().forEach(h=>n.push(Number(h))),n.length!==p||r>=18&&n.length===t.axes.length))throw new Error("Resize requires sizes input size to be same as input rank or axes size for opset 18 and up");if(t.axes.length>0){if(o.length!==t.axes.length)throw new Error(\'Resize requires "scales" input size to be of axes rank when axes attributes is specified\');if(n.length!==t.axes.length)throw new Error(\'Resize requires "sizes" input size to be of rank axes rank when axes attributes is specified\')}if(typeof o<"u"&&typeof n<"u"&&o.length>0&&n.length>p)throw new Error("Resize requires only of scales or sizes to be specified")},ic=(e,t)=>`fn getOriginalCoordinateFromResizedCoordinate(xResized: u32, xScale: f32, lengthResized: u32,\n lengthOriginal: u32, roiStart: f32, roiEnd: f32) -> ${t} { `+(()=>{switch(e){case"asymmetric":return`return ${t}(xResized) / ${t}(xScale);`;case"pytorch_half_pixel":return`if (lengthResized > 1) {\n return (${t}(xResized) + 0.5) / ${t}(xScale) - 0.5;\n } else {\n return 0.0;\n }`;case"tf_half_pixel_for_nn":return`return (${t}(xResized) + 0.5) / ${t}(xScale);`;case"align_corners":return`if (lengthResized == 1) {\n return 0.0;\n } else {\n // The whole part and the fractional part are calculated separately due to inaccuracy of floating\n // point division. As an example, f32(21) / f32(7) may evaluate to 2.99... instead of 3, causing an\n // offset-by-one error later in floor().\n let whole = ${t}(xResized * (lengthOriginal - 1) / (lengthResized - 1));\n let fract =\n ${t}(xResized * (lengthOriginal - 1) % (lengthResized - 1)) / ${t}(lengthResized - 1);\n return whole + fract;\n }`;case"tf_crop_and_resize":return`if (lengthResized > 1) {\n return ${t}(roiStart) * ${t}(lengthOriginal - 1) +\n (${t}(xResized) * ${t}(roiEnd - roiStart) * ${t}(lengthOriginal - 1)) /\n ${t}(lengthResized - 1);\n } else {\n return 0.5 * ${t}(roiStart + roiEnd) * ${t}(lengthOriginal - 1);\n }`;case"half_pixel_symmetric":return`const outputWidth = ${t}xScale * ${t}(lengthResized);\n const adjustment = ${t}(lengthResized) / outputWidth;\n const center = ${t}(lengthOriginal) / 2;\n const offset = center * (1 - adjustment);\n return offset + ((${t}(xResized) + 0.5) / ${t}(xScale)) - 0.5;`;case"half_pixel":return`return ((${t}(xResized) + 0.5) / ${t}(xScale)) - 0.5;`;default:throw new Error(`Coordinate transform mode ${e} is not supported`)}})()+"}",sc=(e,t,r)=>`fn getNearestPixelFromOriginal(xOriginal: ${r}, isDownSample: bool) -> ${r} {`+(()=>{switch(e){case"round_prefer_ceil":return"if (fract(xOriginal) == 0.5) { return ceil(xOriginal); } else { return round(xOriginal); }";case"floor":return"return floor(xOriginal);";case"ceil":return"return ceil(xOriginal);";case"round_prefer_floor":return"if (fract(xOriginal) == 0.5) { return floor(xOriginal); } else { return round(xOriginal); }";case"simple":default:if(t<11)return"if (isDownSample) { return ceil(xOriginal); } else { return xOriginal; }";throw new Error(`Nearest mode ${e} is not supported`)}})()+"}",uc=(e,t,r)=>{let o=new Array(r).fill(0).concat(new Array(r).fill(1)),n=e.length===0?o:e.slice();return t.length>0?(t.forEach((s,u)=>{o[s]=n[u],o[u+r]=n[t.length+u]}),o):n},dc=(e,t,r,o)=>{let n=[];if(r.length>0)if(o.length>0){if(e.forEach(s=>n.push(s)),Math.max(...o)>e.length)throw new Error("axes is out of bound");o.forEach((s,u)=>n[s]=r[u])}else r.forEach(s=>n.push(s));else{if(t.length===0)throw new Error("Resize requires either scales or sizes.");n=e.map((s,u)=>Math.round(s*t[u]))}return n},lc=(e,t,r)=>{let o=(()=>{switch(r.keepAspectRatioPolicy){case"not_larger":return r.axes.length>0?Math.min(...r.axes.map(s=>t[s]),Number.MAX_VALUE):Math.min(...t,Number.MAX_VALUE);case"not_smaller":return r.axes.length>0?Math.max(...r.axes.map(s=>t[s]),Number.MIN_VALUE):Math.max(...t,Number.MIN_VALUE);default:throw new Error(`Keep aspect ratio policy ${r.keepAspectRatioPolicy} is not supported`)}})();t.fill(1,0,t.length);let n=e.slice();return r.axes.length>0?(r.axes.forEach(s=>t[s]=o),r.axes.forEach(s=>n[s]=Math.round(e[s]*t[s]))):(t.fill(o,0,t.length),n.forEach((s,u)=>n[u]=Math.round(s*t[u]))),n},cc=(e,t,r,o,n)=>`\n fn calculateOriginalIndicesFromOutputIndices(output_indices: ${e.type.indices}) -> array<${e.type.value}, ${r.length}> {\n var original_indices: array<${e.type.value}, ${r.length}>;\n for (var i:u32 = 0; i < ${r.length}; i++) {\n var output_index = ${e.indicesGet("output_indices","i")};\n var scale = ${ce("uniforms.scales","i",o)};\n var roi_low = ${ce("uniforms.roi","i",n)};\n var roi_hi = ${ce("uniforms.roi",`i + ${t.length}`,n)};\n if (scale == 1.0) {\n original_indices[i] = ${e.type.value}(output_index);\n } else {\n var input_shape_i = ${ce("uniforms.input_shape","i",t.length)};\n var output_shape_i = ${ce("uniforms.output_shape","i",r.length)};\n original_indices[i] = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i,\n input_shape_i, roi_low, roi_hi);\n }\n }\n return original_indices;\n }`,pc=(e,t,r,o,n,s,u)=>`\n fn calculateInputIndicesFromOutputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} {\n var input_indices: ${e.type.indices};\n for (var i:u32 = 0; i < ${o.length}; i++) {\n var output_index = ${t.indicesGet("output_indices","i")};\n var input_index: u32;\n var scale = ${ce("uniforms.scales","i",n)};\n if (scale == 1.0) {\n input_index = output_index;\n } else {\n var roi_low = ${ce("uniforms.roi","i",s)};\n var roi_hi = ${ce("uniforms.roi",`i + ${r.length}`,s)};\n var input_shape_i = ${ce("uniforms.input_shape","i",r.length)};\n var output_shape_i = ${ce("uniforms.output_shape","i",o.length)};\n var original_idx = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i,\n input_shape_i, roi_low, roi_hi);\n if (!${u} || (original_idx >= 0 && original_idx < ${t.type.value}(input_shape_i))) {\n if (original_idx < 0) {\n input_index = 0;\n } else if (original_idx > ${t.type.value}(input_shape_i - 1)) {\n input_index = input_shape_i - 1;\n } else {\n input_index = u32(getNearestPixelFromOriginal(original_idx, scale < 1));\n }\n } else {\n input_index = u32(original_idx);\n }\n }\n ${e.indicesSet("input_indices","i"," input_index")}\n }\n return input_indices;\n }`,mc=(e,t)=>`\n fn checkInputIndices(input_indices: ${e.type.indices}) -> bool {\n for (var i:u32 = 0; i < ${t.length}; i++) {\n var input_index = ${e.indicesGet("input_indices","i")};\n if (input_index < 0 || input_index >= ${ce("uniforms.input_shape","i",t.length)}) {\n return false;\n }\n }\n return true;\n }`,Ys=(e,t,r,o)=>e.rank>o?`\n ${e.indicesSet("input_indices",t,"channel")};\n ${e.indicesSet("input_indices",r,"batch")};\n`:"",fc=(e,t,r,o,n)=>{let[u,l,a,p]=r.length===2?[-1,0,1,-1]:[0,2,3,1],h=e.type.value;return`\n fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${h} {\n var input_indices: ${e.type.indices};\n ${e.indicesSet("input_indices",l,`max(0, min(row, ${r[l]} - 1))`)};\n ${e.indicesSet("input_indices",a,`max(0, min(col, ${r[a]} - 1))`)};\n ${Ys(e,p,u,2)}\n return ${e.getByIndices("input_indices")};\n }\n\n fn bilinearInterpolation(output_indices: ${t.type.indices}) -> ${h} {\n var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices);\n var row:${h} = originalIndices[${l}];\n var col:${h} = originalIndices[${a}];\n ${o?`if (row < 0 || row > (${r[l]} - 1) || col < 0 || col > (${r[a]} - 1)) {\n return ${n};\n }`:""};\n row = max(0, min(row, ${r[l]} - 1));\n col = max(0, min(col, ${r[a]} - 1));\n var row1: u32 = u32(row);\n var col1: u32 = u32(col);\n var row2: u32 = u32(row + 1);\n var col2: u32 = u32(col + 1);\n var channel: u32 = ${r.length>2?`u32(originalIndices[${p}])`:"0"};\n var batch: u32 = ${r.length>2?`u32(originalIndices[${u}])`:"0"};\n var x11: ${h} = getInputValue(batch, channel, row1, col1);\n var x12: ${h} = getInputValue(batch, channel, row1, col2);\n var x21: ${h} = getInputValue(batch, channel, row2, col1);\n var x22: ${h} = getInputValue(batch, channel, row2, col2);\n var dx1: ${h} = abs(row - ${h}(row1));\n var dx2: ${h} = abs(${h}(row2) - row);\n var dy1: ${h} = abs(col - ${h}(col1));\n var dy2: ${h} = abs(${h}(col2) - col);\n if (row1 == row2) {\n dx1 = 0.5;\n dx2 = 0.5;\n }\n if (col1 == col2) {\n dy1 = 0.5;\n dy2 = 0.5;\n }\n return (x11 * dx2 * dy2 + x12 * dx2 * dy1 + x21 * dx1 * dy2 + x22 * dx1 * dy1);\n }`},hc=(e,t,r,o,n,s,u,l,a,p)=>{let h=r.length===2,g=!0,[b,w]=h?[0,1]:g?[2,3]:[1,2],y=e.type.value,_=I=>{let $=I===b?"row":"col";return`\n fn ${$}CubicInterpolation(input_indices: ${e.type.indices}, output_indices: ${t.type.indices}) -> ${y} {\n var output_index = ${t.indicesGet("output_indices",I)};\n var originalIdx: ${y} = getOriginalCoordinateFromResizedCoordinate(output_index, ${n[I]},\n ${o[I]}, ${r[I]}, ${s[I]}, ${s[I]} + ${r.length});\n var fractOriginalIdx: ${y} = originalIdx - floor(originalIdx);\n var coefs = getCubicInterpolationCoefs(fractOriginalIdx);\n\n if (${l} && (originalIdx < 0 || originalIdx > (${r[I]} - 1))) {\n return ${a};\n }\n var data: array<${y}, 4> = array<${y}, 4>(0.0, 0.0, 0.0, 0.0);\n for (var i: i32 = -1; i < 3; i++) {\n var ${$}: ${y} = originalIdx + ${y}(i);\n if (${$} < 0 || ${$} >= ${r[I]}) {\n ${(()=>p?`coefs[i + 1] = 0.0;\n continue;`:l?`return ${a};`:`${$} = max(0, min(${$}, ${r[I]} - 1));`)()};\n }\n var input_indices_copy: ${e.type.indices} = input_indices;\n ${e.indicesSet("input_indices_copy",I,`u32(${$})`)};\n data[i + 1] = ${I===b?e.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"};\n }\n return cubicInterpolation1D(data, coefs);\n }`};return`\n ${_(b)};\n ${_(w)};\n fn getCubicInterpolationCoefs(s: ${y}) -> array<${y}, 4> {\n var absS = abs(s);\n var coeffs: array<${y}, 4> = array<${y}, 4>(0.0, 0.0, 0.0, 0.0);\n var oneMinusAbsS: ${y} = 1.0 - absS;\n var twoMinusAbsS: ${y} = 2.0 - absS;\n var onePlusAbsS: ${y} = 1.0 + absS;\n coeffs[0] = ((${u} * onePlusAbsS - 5 * ${u}) * onePlusAbsS + 8 * ${u}) * onePlusAbsS - 4 * ${u};\n coeffs[1] = ((${u} + 2) * absS - (${u} + 3)) * absS * absS + 1;\n coeffs[2] = ((${u} + 2) * oneMinusAbsS - (${u} + 3)) * oneMinusAbsS * oneMinusAbsS + 1;\n coeffs[3] = ((${u} * twoMinusAbsS - 5 * ${u}) * twoMinusAbsS + 8 * ${u}) * twoMinusAbsS - 4 * ${u};\n return coeffs;\n }\n\n fn cubicInterpolation1D(x: array<${y}, 4>, coefs: array<${y}, 4>) -> ${y} {\n var coefsSum: ${y} = coefs[0] + coefs[1] + coefs[2] + coefs[3];\n return (x[0] * coefs[0] + x[1] * coefs[1]+ x[2] * coefs[2]+ x[3] * coefs[3]) / coefsSum;\n }\n\n fn bicubicInterpolation(output_indices: ${t.type.indices}) -> ${y} {\n var input_indices: ${e.type.indices} = output_indices;\n return colCubicInterpolation(input_indices, output_indices);\n }\n `},gc=(e,t,r,o,n)=>{let[u,l,a,p,h]=r.length===3?[-1,0,1,2,-1]:[0,2,3,4,1],g=e.type.value;return`\n fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${g} {\n var input_indices: ${e.type.indices};\n ${e.indicesSet("input_indices",l,`max(0, min(depth, ${r[l]} - 1))`)};\n ${e.indicesSet("input_indices",a,`max(0, min(height, ${r[a]} - 1))`)};\n ${e.indicesSet("input_indices",p,`max(0, min(width, ${r[p]} - 1))`)};\n ${Ys(e,h,u,3)}\n return ${e.getByIndices("input_indices")};\n }\n\n fn trilinearInterpolation(output_indices: ${t.type.indices}) -> ${g} {\n var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices);\n var depth:${g} = originalIndices[${l}];\n var height:${g} = originalIndices[${a}];\n var width:${g} = originalIndices[${p}];\n ${o?`if (depth < 0 || depth > (${r[l]} - 1) || height < 0 || height > (${r[a]} - 1) || width < 0 || (width > ${r[p]} - 1)) {\n return ${n};\n }`:""};\n\n depth = max(0, min(depth, ${r[l]} - 1));\n height = max(0, min(height, ${r[a]} - 1));\n width = max(0, min(width, ${r[p]} - 1));\n var depth1: u32 = u32(depth);\n var height1: u32 = u32(height);\n var width1: u32 = u32(width);\n var depth2: u32 = u32(depth + 1);\n var height2: u32 = u32(height + 1);\n var width2: u32 = u32(width + 1);\n var channel: u32 = ${r.length>3?`u32(originalIndices[${h}])`:"0"};\n var batch: u32 = ${r.length>3?`u32(originalIndices[${u}])`:"0"};\n\n var x111: ${g} = getInputValue(batch, channel, depth1, height1, width1);\n var x112: ${g} = getInputValue(batch, channel, depth1, height1, width2);\n var x121: ${g} = getInputValue(batch, channel, depth1, height2, width1);\n var x122: ${g} = getInputValue(batch, channel, depth1, height2, width2);\n var x211: ${g} = getInputValue(batch, channel, depth2, height1, width1);\n var x212: ${g} = getInputValue(batch, channel, depth2, height1, width2);\n var x221: ${g} = getInputValue(batch, channel, depth2, height2, width1);\n var x222: ${g} = getInputValue(batch, channel, depth2, height2, width2);\n var dx1: ${g} = abs(depth - ${g}(depth1));\n var dx2: ${g} = abs(${g}(depth2) - depth);\n var dy1: ${g} = abs(height - ${g}(height1));\n var dy2: ${g} = abs(${g}(height2) - height);\n var dz1: ${g} = abs(width - ${g}(width1));\n var dz2: ${g} = abs(${g}(width2) - width);\n if (depth1 == depth2) {\n dx1 = 0.5;\n dx2 = 0.5;\n }\n if (height1 == height2) {\n dy1 = 0.5;\n dy2 = 0.5;\n }\n if (width1 == width2) {\n dz1 = 0.5;\n dz2 = 0.5;\n }\n return (x111 * dx2 * dy2 * dz2 + x112 * dx2 * dy2 * dz1 + x121 * dx2 * dy1 *dz2 + x122 * dx2 * dy1 * dz1 +\n x211 * dx1 * dy2 * dz2 + x212 * dx1 * dy2 * dz1 + x221 * dx1 * dy1 *dz2 + x222 * dx1 * dy1 * dz1);\n }`},yc=(e,t,r,o,n,s)=>{let u=e.dims,l=uc(s,t.axes,u.length),a=dc(u,o,n,t.axes),p=o.slice();o.length===0&&(p=u.map((x,E)=>x===0?1:a[E]/x),t.keepAspectRatioPolicy!=="stretch"&&(a=lc(u,p,t)));let h=F("output",e.dataType,a.length),g=M("input",e.dataType,u.length),b=U.size(a),w=u.length===a.length&&u.every((x,E)=>x===a[E]),y=t.coordinateTransformMode==="tf_crop_and_resize",_=t.extrapolationValue,I=g.type.value,$=x=>`\n ${w?"":`\n ${ic(t.coordinateTransformMode,I)};\n ${(()=>{switch(t.mode){case"nearest":return`\n ${mc(g,u)};\n ${sc(t.nearestMode,r,I)};\n ${pc(g,h,u,a,p.length,l.length,y)};\n `;case"linear":return`\n ${cc(h,u,a,p.length,l.length)};\n ${(()=>{if(u.length===2||u.length===4)return`${fc(g,h,u,y,_)}`;if(u.length===3||u.length===5)return`${gc(g,h,u,y,_)}`;throw Error("Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.")})()};\n `;case"cubic":return`\n ${(()=>{if(u.length===2||u.length===4)return`${hc(g,h,u,a,p,l,t.cubicCoeffA,y,t.extrapolationValue,t.excludeOutside)}`;throw Error("Cubic mode only supports input dims 2 and 4 are supported in linear mode.")})()};\n `;default:throw Error("Invalid resize mode")}})()};\n `}\n ${x.registerUniform("output_size","u32").registerUniform("scales","f32",p.length).registerUniform("roi","f32",l.length).declareVariables(g,h)}\n ${x.mainStart()}\n ${x.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n ${w?"output[global_idx] = input[global_idx];":`\n let output_indices = ${h.offsetToIndices("global_idx")};\n var input_indices: ${g.type.indices};\n ${(()=>{switch(t.mode){case"nearest":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices);\n if (checkInputIndices(input_indices)) {\n output[global_idx] = ${g.getByIndices("input_indices")};\n } else {\n output[global_idx] = ${t.extrapolationValue};\n }`;case"linear":return`output[global_idx] = ${u.length===2||u.length===4?"bilinearInterpolation":"trilinearInterpolation"}(output_indices);`;case"cubic":return"output[global_idx] = bicubicInterpolation(output_indices);";default:throw Error(`Unsupported resize mode: ${t.mode}`)}})()};\n`}\n }`;return{name:"Resize",shaderCache:{hint:`${t.cacheKey}|${r}|${p.length>0?p:""}|${n.length>0?n:""}|${l.length>0?l:""}|${w}|${u}`,inputDependencies:["rank"]},getShaderSource:$,getRunData:()=>({outputs:[{dims:a,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(b/64)},programUniforms:[{type:"uint32",data:b},{type:"float32",data:p},{type:"float32",data:l},...L(u),...L(a)]})}},bc=e=>{let t=e.customDataBuffer;return new Uint32Array(t,t.byteOffset,1)[0]},Zs=(e,t)=>{let r=[],o=[],n=[],s=bc(e);if(t.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");ac(e.inputs,t,s,r,o,n),e.compute(yc(e.inputs[0],t,s,r,o,n),{inputs:[0]})},Qs=e=>{let t=e.antialias,r=e.axes,o=e.coordinateTransformMode,n=e.cubicCoeffA,s=e.excludeOutside!==0,u=e.extrapolationValue,l=e.keepAspectRatioPolicy,a=e.mode,p=e.nearestMode===""?"simple":e.nearestMode;return ge({antialias:t,axes:r,coordinateTransformMode:o,cubicCoeffA:n,excludeOutside:s,extrapolationValue:u,keepAspectRatioPolicy:l,mode:a,nearestMode:p})}});var wc,vc,Js,eu,tu=j(()=>{"use strict";Ne();$e();je();ve();wc=e=>{if(!e||e.length<3)throw new Error("layerNorm requires at least 3 inputs.");let t=e[0],r=e[1],o=e[2];if(t.dataType!==r.dataType||t.dataType!==o.dataType)throw new Error("All inputs must have the same data type");if(t.dims.length!==3&&t.dims.length!==2)throw new Error("Input must be 2D or 3D");if(r.dims.length!==3&&r.dims.length!==2)throw new Error("Skip must be 2D or 3D");let n=t.dims[t.dims.length-1],s=t.dims[t.dims.length-2];if(r.dims[r.dims.length-1]!==n)throw new Error("Skip must have the same hidden size as input");if(r.dims[r.dims.length-2]!==s)throw new Error("Skip must have the same sequence length as input");if(o.dims.length!==1)throw new Error("Gamma must be 1D");if(o.dims[o.dims.length-1]!==n)throw new Error("Gamma must have the same hidden size as input");if(e.length>3){let u=e[3];if(u.dims.length!==1)throw new Error("Beta must be 1D");if(u.dims[u.dims.length-1]!==n)throw new Error("Beta must have the same hidden size as input")}if(e.length>4){let u=e[4];if(u.dims.length!==1)throw new Error("Bias must be 1D");if(u.dims[u.dims.length-1]!==n)throw new Error("Bias must have the same hidden size as input")}},vc=(e,t,r,o)=>{let n=e[0].dims,s=U.size(n),u=n,l=s,a=n.slice(-1)[0],p=o?n.slice(0,-1).concat(1):[],h=e.length>3,g=e.length>4,b=o&&r>1,w=o&&r>2,y=r>3,_=Fe(a),I=[M("x",e[0].dataType,e[0].dims,_),M("skip",e[1].dataType,e[1].dims,_),M("gamma",e[2].dataType,e[2].dims,_)];h&&I.push(M("beta",e[3].dataType,e[3].dims,_)),g&&I.push(M("bias",e[4].dataType,e[4].dims,_)),I.push(F("output",e[0].dataType,u,_)),b&&I.push(F("meanOutput",1,p)),w&&I.push(F("invStdOutput",1,p)),y&&I.push(F("inputSkipBiasSum",e[0].dataType,u,_));let $=Le(e[0].dataType),x=A=>`\n const hiddenSize: f32 = ${a};\n const hiddenSizeVectorized: u32 = ${a/_};\n const epsilon: f32 = ${t.epsilon};\n\n ${A.declareVariables(...I)}\n\n ${A.mainStart()}\n ${A.guardAgainstOutOfBoundsWorkgroupSizes(l/a)}\n let offset = global_idx * hiddenSizeVectorized;\n var sum = ${Ze("f32",_)};\n var squareSum = ${Ze("f32",_)};\n for (var i: u32 = 0; i < hiddenSizeVectorized; i++) {\n let skipValue = skip[offset + i];\n let biasValue = ${g?"bias[i]":"0.0"};\n let inputValue = x[offset + i];\n let value = inputValue + skipValue + biasValue;\n ${y?"inputSkipBiasSum[offset + i] = value;":""}\n output[offset + i] = value;\n let f32Value = ${at($,_,"value")};\n sum += f32Value;\n squareSum += f32Value * f32Value;\n }\n let mean = ${Je("sum",_)} / hiddenSize;\n let invStdDev = inverseSqrt(${Je("squareSum",_)} / hiddenSize - mean * mean + epsilon);\n ${b?"meanOutput[global_idx] = mean;":""}\n ${w?"invStdOutput[global_idx] = invStdDev;":""}\n for (var i: u32 = 0; i < hiddenSizeVectorized; i++) {\n output[offset + i] = (output[offset + i] - ${$}(mean)) * ${$}(invStdDev) * gamma[i]\n + ${h?"beta[i]":"0.0"};\n }\n }`,E=[{dims:u,dataType:e[0].dataType}];return r>1&&E.push({dims:p,dataType:1}),r>2&&E.push({dims:p,dataType:1}),r>3&&E.push({dims:n,dataType:e[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:t.cacheKey},getShaderSource:x,getRunData:()=>({outputs:E,dispatchGroup:{x:Math.ceil(l/a/64)}})}},Js=(e,t)=>{wc(e.inputs);let o=[0];e.outputCount>1&&o.push(-3),e.outputCount>2&&o.push(-3),e.outputCount>3&&o.push(3),e.compute(vc(e.inputs,t,e.outputCount,!1),{outputs:o})},eu=e=>{let t=e.epsilon;return ge({epsilon:t})}});var $c,on,Sc,ru,xc,_c,nu,ou,au=j(()=>{"use strict";Ne();$e();je();ve();$c=(e,t)=>{if(!e||e.length<1)throw new Error("too few inputs");if(t.axes.length!==0){if(t.axes.length!==t.starts.length||t.axes.length!==t.ends.length)throw new Error("axes, starts and ends must have the same length")}else if(t.starts.length!==t.ends.length)throw new Error("starts and ends must have the same length");e.slice(1).forEach((r,o)=>{if(e[o+1].dataType!==6&&e[o+1].dataType!==7)throw new Error(`Input ${o} must be an array of int32 or int64`)})},on=(e,t)=>{let r=[];if(e.length>t)if(e[t].dataType===7)e[t].getBigInt64Array().forEach(o=>r.push(Number(o)));else if(e[t].dataType===6)e[t].getInt32Array().forEach(o=>r.push(Number(o)));else throw new Error(`Input ${t} must be an array of int32 or int64`);return r},Sc=(e,t)=>{if(e.length>1){let r=on(e,1),o=on(e,2),n=on(e,3);return n.length===0&&(n=[...Array(e[0].dims.length).keys()]),ge({starts:r,ends:o,axes:n})}else return t},ru=(e,t,r,o,n)=>{let s=e;return e<0&&(s+=r[o[t]]),n[t]<0?Math.max(0,Math.min(s,r[o[t]]-1)):Math.max(0,Math.min(s,r[o[t]]))},xc=(e,t,r)=>`fn calculateInputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} {\n var input_indices: ${e.type.indices};\n var carry = 0u;\n for (var i = ${r.length}; i >= 0; i--) {\n let input_shape_i = ${ce("uniforms.input_shape","i",r.length)};\n let steps_i = ${ce("uniforms.steps","i",r.length)};\n let signs_i = ${ce("uniforms.signs","i",r.length)};\n let starts_i = ${ce("uniforms.starts","i",r.length)};\n var output_index = ${t.indicesGet("output_indices","i")};\n var input_index = output_index * steps_i + starts_i + carry;\n carry = input_index / input_shape_i;\n input_index = input_index % input_shape_i;\n if (signs_i < 0) {\n input_index = input_shape_i - input_index - 1u + starts_i;\n }\n ${e.indicesSet("input_indices","i","input_index")};\n }\n return input_indices;\n }`,_c=(e,t)=>{let r=e[0].dims,o=U.size(r),n=t.axes.length>0?U.normalizeAxes(t.axes,r.length):[...Array(r.length).keys()],s=on(e,4);s.forEach($=>$!==0||(()=>{throw new Error("step cannot be 0")})),s.length===0&&(s=Array(n.length).fill(1));let u=t.starts.map(($,x)=>ru($,x,r,n,s)),l=t.ends.map(($,x)=>ru($,x,r,n,s));if(n.length!==u.length||n.length!==l.length)throw new Error("start, ends and axes should have the same number of elements");if(n.length!==r.length)for(let $=0;$Math.sign($));s.forEach(($,x,E)=>{if($<0){let A=(l[x]-u[x])/$,z=u[x],R=z+A*s[x];u[x]=R,l[x]=z,E[x]=-$}});let p=r.slice(0);n.forEach(($,x)=>{p[$]=Math.ceil((l[$]-u[$])/s[$])});let h={dims:p,dataType:e[0].dataType},g=F("output",e[0].dataType,p.length),b=M("input",e[0].dataType,e[0].dims.length),w=U.size(p),y=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:u.length},{name:"signs",type:"i32",length:a.length},{name:"steps",type:"u32",length:s.length}],_=[{type:"uint32",data:w},{type:"uint32",data:u},{type:"int32",data:a},{type:"uint32",data:s},...L(e[0].dims),...L(p)],I=$=>`\n ${$.registerUniforms(y).declareVariables(b,g)}\n ${xc(b,g,r)}\n ${$.mainStart()}\n ${$.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n let output_indices = ${g.offsetToIndices("global_idx")};\n let input_indices = calculateInputIndices(output_indices);\n ${g.setByOffset("global_idx",b.getByIndices("input_indices"))}\n }`;return{name:"Slice",shaderCache:{hint:`${a.length}_${u.length}_${s.length}`,inputDependencies:["rank"]},getShaderSource:I,getRunData:()=>({outputs:[h],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:_})}},nu=(e,t)=>{$c(e.inputs,t);let r=Sc(e.inputs,t);e.compute(_c(e.inputs,r),{inputs:[0]})},ou=e=>{let t=e.starts,r=e.ends,o=e.axes;return ge({starts:t,ends:r,axes:o})}});var Cc,Ic,iu,su,uu=j(()=>{"use strict";$e();je();ve();Cc=e=>{if(!e||e.length!==1)throw new Error("Softmax op requires 1 input.")},Ic=(e,t)=>{let r=e.dims,o=U.size(r),n=64,s=t.axis;if(s<0&&(s=r.length+s),s$===4?`max(max(${I}.x, ${I}.y), max(${I}.z, ${I}.w))`:$===2?`max(${I}.x, ${I}.y)`:$===3?`max(max(${I}.x, ${I}.y), ${I}.z)`:I,g=M("x",e.dataType,e.dims,a),b=F("result",e.dataType,e.dims,a),w=g.type.value,y=Le(e.dataType)==="f32"?`var threadMax = ${w}(-3.402823e+38f);`:`var threadMax = ${w}(-65504.0h);`,_=I=>`\n var rowMaxShared : ${w};\n var rowSumShared : ${w};\n var threadShared : array<${w}, ${n}>;\n\n fn getValue(row: i32, col: i32, row_stride: i32) -> ${w} {\n let index = row * row_stride + col;\n return x[index];\n }\n\n fn setValue(row: i32, col: i32, row_stride: i32, value: ${w}) {\n let index = row * row_stride + col;\n result[index] = value;\n }\n ${I.registerUniform("packedCols","i32").declareVariables(g,b)}\n ${I.mainStart()}\n let gindex = i32(global_idx);\n let lindex = i32(local_idx);\n const wg = ${n};\n let row = gindex / wg;\n let cols = uniforms.packedCols;\n let row_stride : i32 = uniforms.packedCols;\n\n // find the rows max\n ${y}\n for (var col = lindex; col < cols; col += wg) {\n let value = getValue(row, col, row_stride);\n threadMax = max(threadMax, value);\n }\n if (lindex < cols) {\n threadShared[lindex] = threadMax;\n }\n workgroupBarrier();\n\n var reduceSize = min(cols, wg);\n for (var currSize = reduceSize >> 1; currSize > 0; currSize = reduceSize >> 1) {\n reduceSize = currSize + (reduceSize & 1);\n if (lindex < currSize) {\n threadShared[lindex] = max(threadShared[lindex], threadShared[lindex + reduceSize]);\n }\n workgroupBarrier();\n }\n if (lindex == 0) {\n rowMaxShared = ${w}(${h("threadShared[0]",a)});\n }\n workgroupBarrier();\n\n // find the rows sum\n var threadSum = ${w}(0.0);\n for (var col = lindex; col < cols; col += wg) {\n let subExp = exp(getValue(row, col, row_stride) - rowMaxShared);\n threadSum += subExp;\n }\n threadShared[lindex] = threadSum;\n workgroupBarrier();\n\n for (var currSize = wg >> 1; currSize > 0; currSize = currSize >> 1) {\n if (lindex < currSize) {\n threadShared[lindex] = threadShared[lindex] + threadShared[lindex + currSize];\n }\n workgroupBarrier();\n }\n if (lindex == 0) {\n rowSumShared = ${w}(${Je("threadShared[0]",a)});\n }\n workgroupBarrier();\n\n // calculate final value for each element in the row\n for (var col = lindex; col < cols; col += wg) {\n let value = exp(getValue(row, col, row_stride) - rowMaxShared) / rowSumShared;\n setValue(row, col, row_stride, value);\n }\n }`;return{name:"Softmax",shaderCache:{hint:`${a}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:r,dataType:e.dataType}],dispatchGroup:{x:l},programUniforms:[{type:"uint32",data:p}]}),getShaderSource:_}},iu=(e,t)=>{Cc(e.inputs),e.compute(Ic(e.inputs[0],t))},su=e=>ge({axis:e.axis})});var Ac,Tc,Ec,Oc,Pc,du,lu,cu=j(()=>{"use strict";$e();je();ve();Ac=e=>{if(!e||e.length<1)throw new Error("too few inputs")},Tc=(e,t)=>{let r=[],o=t.numOutputs;return e[1].dims[0]>0&&(e[1].getBigInt64Array().forEach(n=>r.push(Number(n))),o=r.length),ge({numOutputs:o,axis:t.axis,splitSizes:r})},Ec=e=>`\nfn calculateOutputIndex(index: u32) -> u32 {\n for (var i: u32 = 0u; i < ${e}u; i += 1u ) {\n if (index < ${ce("uniforms.size_in_split_axis","i",e)}) {\n return i;\n }\n }\n return ${e}u;\n}`,Oc=e=>{let t=e.length,r=[];for(let o=0;o{let r=e[0].dims,o=U.size(r),n=e[0].dataType,s=U.normalizeAxis(t.axis,r.length),u=new Array(t.numOutputs),l=M("input",n,r),a=new Array(t.numOutputs),p=[],h=[],g=0,b=[{type:"uint32",data:o}];for(let y=0;yb.push(...L(y)));let w=y=>`\n ${y.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",a.length).declareVariables(l,...u)}\n ${Ec(a.length)}\n ${Oc(u)}\n\n ${y.mainStart()}\n ${y.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")}\n\n var indices = ${l.offsetToIndices("global_idx")};\n var index = ${l.indicesGet("indices",s)};\n let output_number = calculateOutputIndex(index);\n if (output_number != 0) {\n index -= ${ce("uniforms.size_in_split_axis","output_number - 1u",a.length)};\n ${l.indicesSet("indices",s,"index")};\n }\n writeBufferData(output_number, indices, global_idx);\n }`;return{name:"Split",shaderCache:{hint:t.cacheKey,inputDependencies:["rank"]},getShaderSource:w,getRunData:()=>({outputs:p,dispatchGroup:{x:Math.ceil(o/64)},programUniforms:b})}},du=(e,t)=>{Ac(e.inputs);let r=e.inputs.length===1?t:Tc(e.inputs,t);e.compute(Pc(e.inputs,r),{inputs:[0]})},lu=e=>{let t=e.axis,r=e.splitSizes,o=e.numOutputs<0?r.length:e.numOutputs;if(o!==r.length)throw new Error("numOutputs and splitSizes lengh must be equal");return ge({axis:t,numOutputs:o,splitSizes:r})}});var pu,kc,Rc,Bc,mu,fu=j(()=>{"use strict";Ne();$e();ve();pu=e=>Array.from(e.getBigInt64Array(),Number),kc=e=>{if(!e||e.length!==2)throw new Error("Tile requires 2 inputs.");if(e[0].dataType!==1&&e[0].dataType!==6&&e[0].dataType!==12)throw new Error("Tile only support float, int32, and uint32 data types");if(e[1].dataType!==7)throw new Error("Tile `repeats` input should be of int64 data type");if(e[1].dims.length!==1)throw new Error("Tile `repeats` input should be 1-D");if(pu(e[1]).length!==e[0].dims.length)throw new Error("Tile `repeats` input should have same number of elements as rank of input data tensor")},Rc=(e,t)=>{let r=[];for(let o=0;o{let t=e[0].dims,r=pu(e[1]),o=Rc(t,r),n=U.size(o),s=e[0].dataType,u=M("input",s,t.length),l=F("output",s,o.length),a=p=>`\n const inputShape = ${u.indices(...t)};\n ${p.registerUniform("output_size","u32").declareVariables(u,l)}\n ${p.mainStart()}\n ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n let output_indices = ${l.offsetToIndices("global_idx")};\n var input_indices: ${u.type.indices};\n for (var i = 0; i < ${t.length}; i++) {\n let input_dim_i = ${u.indicesGet("uniforms.input_shape","i")};\n let input_dim_value = ${l.indicesGet("output_indices","i")} % input_dim_i;\n\n ${u.indicesSet("input_indices","i","input_dim_value")}\n }\n ${l.setByOffset("global_idx",u.getByIndices("input_indices"))}\n }`;return{name:"Tile",shaderCache:{hint:`${r}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:[{type:"uint32",data:n},...L(e[0].dims),...L(o)]}),getShaderSource:a}},mu=e=>{kc(e.inputs),e.compute(Bc(e.inputs),{inputs:[0]})}});var Dc,Mc,hu,gu=j(()=>{"use strict";Ne();$e();ve();Dc=(e,t,r,o,n)=>{let s=F("output_data",n,r.length,4),u=M("a_data",t[1].dataType,t[1].dims.length,4),l=M("b_data",t[2].dataType,t[2].dims.length,4),a=M("c_data",t[0].dataType,t[0].dims.length,4),p,h=(g,b,w)=>`select(${b}, ${g}, ${w})`;if(!o)p=s.setByOffset("global_idx",h(u.getByOffset("global_idx"),l.getByOffset("global_idx"),a.getByOffset("global_idx")));else{let g=(b,w,y="")=>{let _=`a_data[index_a${w}][component_a${w}]`,I=`b_data[index_b${w}][component_b${w}]`,$=`bool(c_data[index_c${w}] & ${4278190080>>>(3-w)*8}u)`;return`\n let output_indices${w} = ${s.offsetToIndices(`global_idx * 4u + ${w}u`)};\n let offset_a${w} = ${u.broadcastedIndicesToOffset(`output_indices${w}`,s)};\n let offset_b${w} = ${l.broadcastedIndicesToOffset(`output_indices${w}`,s)};\n let offset_c${w} = ${a.broadcastedIndicesToOffset(`output_indices${w}`,s)};\n let index_a${w} = offset_a${w} / 4u;\n let index_b${w} = offset_b${w} / 4u;\n let index_c${w} = offset_c${w} / 4u;\n let component_a${w} = offset_a${w} % 4u;\n let component_b${w} = offset_b${w} % 4u;\n ${b}[${w}] = ${y}(${h(_,I,$)});\n `};n===9?p=`\n var data = vec4(0);\n ${g("data",0,"u32")}\n ${g("data",1,"u32")}\n ${g("data",2,"u32")}\n ${g("data",3,"u32")}\n output_data[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:p=`\n ${g("output_data[global_idx]",0)}\n ${g("output_data[global_idx]",1)}\n ${g("output_data[global_idx]",2)}\n ${g("output_data[global_idx]",3)}\n `}return`\n ${e.registerUniform("vec_size","u32").declareVariables(a,u,l,s)}\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}\n ${p}\n }`},Mc=e=>{let t=e[1].dims,r=e[2].dims,o=e[0].dims,n=e[1].dataType,s=!(U.areEqual(t,r)&&U.areEqual(r,o)),u=t,l=U.size(t);if(s){let p=dt.calcShape(dt.calcShape(t,r,!1),o,!1);if(!p)throw new Error("Can\'t perform where op on the given tensors");u=p,l=U.size(u)}let a=Math.ceil(l/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:p=>Dc(p,e,u,s,n),getRunData:()=>({outputs:[{dims:u,dataType:n}],dispatchGroup:{x:Math.ceil(l/64/4)},programUniforms:[{type:"uint32",data:a},...L(o),...L(t),...L(r),...L(u)]})}},hu=e=>{e.compute(Mc(e.inputs))}});var yu,bu=j(()=>{"use strict";Wa();Un();La();ja();Ci();Mi();Vi();Gn();Ji();rs();ss();ls();ms();gs();ws();$s();xs();Fn();As();Es();js();Ks();jr();Xs();tu();au();uu();cu();fu();jt();Vn();gu();yu=new Map([["Abs",[qa]],["Acos",[Ka]],["Acosh",[Ya]],["Add",[Ii]],["ArgMax",[Na,zn]],["ArgMin",[Va,zn]],["Asin",[Za]],["Asinh",[Qa]],["Atan",[Xa]],["Atanh",[Ja]],["Attention",[Ha]],["AveragePool",[zs,Ms]],["BatchNormalization",[Ga]],["BiasAdd",[Fa]],["BiasSplitGelu",[_i]],["Cast",[ti,ei]],["Ceil",[ni]],["Clip",[ri]],["Concat",[zi,Ui]],["Conv",[qn,jn]],["ConvTranspose",[Xi,Qi]],["Cos",[oi]],["Cosh",[ai]],["CumSum",[es,ts]],["Div",[Ai]],["Einsum",[as,is]],["Elu",[ii,Yr]],["Equal",[Ti]],["Erf",[si]],["Exp",[ui]],["Expand",[ds]],["Floor",[di]],["FusedConv",[qn,jn]],["Gather",[ps,cs]],["GatherElements",[hs,fs]],["Gelu",[li]],["Gemm",[bs,ys]],["GlobalAveragePool",[Ns,Vs]],["GlobalMaxPool",[Fs,Ls]],["Greater",[ki]],["GreaterOrEqual",[Bi]],["InstanceNormalization",[vs]],["LayerNormalization",[Ss]],["LeakyRelu",[ci,Yr]],["Less",[Ri]],["LessOrEqual",[Di]],["Log",[xi]],["MatMul",[Li]],["MaxPool",[Hs,Gs]],["Mul",[Ei]],["MultiHeadAttention",[Is,Cs]],["Neg",[mi]],["Not",[pi]],["Pad",[Ts]],["Pow",[Oi]],["Range",[qs]],["Reciprocal",[fi]],["ReduceMin",[Ra]],["ReduceMean",[Ta]],["ReduceMax",[ka]],["ReduceSum",[Da]],["ReduceProd",[Ba]],["ReduceL1",[Ea]],["ReduceL2",[Oa]],["ReduceLogSum",[za]],["ReduceLogSumExp",[Pa]],["ReduceSumSquare",[Ma]],["Relu",[hi]],["Resize",[Zs,Qs]],["Sigmoid",[gi]],["Sin",[yi]],["Sinh",[bi]],["Slice",[nu,ou]],["SkipLayerNormalization",[Js,eu]],["Split",[du,lu]],["Sqrt",[wi]],["Softmax",[iu,su]],["Sub",[Pi]],["Tan",[vi]],["Tanh",[$i]],["ThresholdedRelu",[Si,Yr]],["Tile",[mu]],["Transpose",[ha,ga]],["Where",[hu]]])});var an,wu=j(()=>{"use strict";Lt();Ct();ve();an=class{constructor(t){this.backend=t;this.repo=new Map,this.attributesBound=!1}getArtifact(t){return this.repo.get(t)}setArtifact(t,r){this.repo.set(t,r)}run(t,r,o,n,s){kt(t.programInfo.name);let u=this.backend.device,l=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2),l.setPipeline(t.computePipeline);let a=[];for(let h of r)a.push({binding:a.length,resource:{buffer:h.buffer}});for(let h of o)a.push({binding:a.length,resource:{buffer:h.buffer}});s&&a.push({binding:a.length,resource:s});let p=u.createBindGroup({layout:t.computePipeline.getBindGroupLayout(0),entries:a,label:t.programInfo.name});l.setBindGroup(0,p),l.dispatchWorkgroups(...n),this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2+1),this.backend.pendingDispatchNumber++,(this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber||this.backend.queryType==="at-passes")&&this.backend.endComputePass(),this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber&&this.backend.flush(),Rt(t.programInfo.name)}dispose(){}build(t,r){kt(t.name);let o=this.backend.device,n=[];o.features.has("shader-f16")&&n.push("enable f16;");let s=ma(r),u=t.getShaderSource(s),l=`${n.join(`\n`)}\n${s.additionalImplementations}\n${u}`,a=o.createShaderModule({code:l,label:t.name});Be("verbose",()=>`[WebGPU] ${t.name} shader code: ${l}`);let p=o.createComputePipeline({compute:{module:a,entryPoint:"main"},layout:"auto",label:t.name});return Rt(t.name),{programInfo:t,computePipeline:p}}normalizeDispatchGroupSize(t){let r=typeof t=="number"?t:t.x,o=typeof t=="number"?1:t.y||1,n=typeof t=="number"?1:t.z||1,s=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(r<=s&&o<=s&&n<=s)return[r,o,n];let u=r*o*n,l=Math.ceil(Math.sqrt(u));if(l>s){if(l=Math.ceil(Math.cbrt(u)),l>s)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[l,l,l]}else return[l,l,1]}}});var zc,Uc,sn,vu=j(()=>{"use strict";Lt();Ne();Ct();ua();pa();bu();wu();zc=(e,t)=>{if(t.length!==e.length)throw new Error(`inputDependencies length ${t.length} is not equal to inputTensors length ${e.length}.`);let r=[];for(let o=0;o{let o=e.name;return e.shaderCache?.hint&&(o+="["+e.shaderCache.hint+"]"),o+=":"+r+`:${zc(t,e.shaderCache?.inputDependencies??new Array(t.length).fill("dims"))}`,o},sn=class{constructor(){this.currentKernelId=null;this.commandEncoder=null;this.computePassEncoder=null;this.maxDispatchNumber=16;this.pendingDispatchNumber=0;this.pendingKernels=[];this.pendingQueries=new Map;this.sessionExternalDataMapping=new Map}get currentKernelCustomData(){if(this.currentKernelId===null)throw new Error("currentKernelCustomData(): currentKernelId is null. (should not happen)");let t=this.kernelCustomData.get(this.currentKernelId);return t||(t={},this.kernelCustomData.set(this.currentKernelId,t)),t}async initialize(t,r){this.env=t;let o=[],n={requiredLimits:{maxComputeWorkgroupStorageSize:r.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:r.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:r.limits.maxStorageBufferBindingSize,maxBufferSize:r.limits.maxBufferSize,maxComputeInvocationsPerWorkgroup:r.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupSizeX:r.limits.maxComputeWorkgroupSizeX,maxComputeWorkgroupSizeY:r.limits.maxComputeWorkgroupSizeY,maxComputeWorkgroupSizeZ:r.limits.maxComputeWorkgroupSizeZ},requiredFeatures:o};r.features.has("chromium-experimental-timestamp-query-inside-passes")?o.push("chromium-experimental-timestamp-query-inside-passes"):r.features.has("timestamp-query")&&o.push("timestamp-query"),r.features.has("shader-f16")&&o.push("shader-f16"),this.device=await r.requestDevice(n),this.gpuDataManager=ca(this),this.programManager=new an(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,ia(t.logLevel,!!t.debug),this.device.onuncapturederror=s=>{s.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${s.error.message}`)},Object.defineProperty(this.env.webgpu,"device",{value:this.device}),this.setQueryType()}dispose(){typeof this.querySet<"u"&&this.querySet.destroy(),this.gpuDataManager.dispose()}getCommandEncoder(){return this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder(),this.setQueryType(),this.queryType!=="none"&&typeof this.querySet>"u"&&(this.querySet=this.device.createQuerySet({type:"timestamp",count:this.maxDispatchNumber*2}),this.queryResolveBuffer=this.device.createBuffer({size:this.maxDispatchNumber*2*8,usage:GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE}))),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let t={};this.queryType==="at-passes"&&(t.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=this.getCommandEncoder().beginComputePass(t)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;kt(),this.endComputePass();let t;this.queryType!=="none"&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),t=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(t,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,t,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!=="none"&&t.mapAsync(GPUMapMode.READ).then(()=>{let r=new BigUint64Array(t.getMappedRange()),o=this.pendingQueries.get(t);for(let n=0;n"u"&&(this.queryTimeBase=w);let _=Number(w-this.queryTimeBase),I=Number(y-this.queryTimeBase);if(!Number.isSafeInteger(_)||!Number.isSafeInteger(I))throw new RangeError("incorrect timestamp range");if(this.env.webgpu.profiling?.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:g.map($=>({dims:$.dims,dataType:Xe($.dataType)})),outputsMetadata:b.map($=>({dims:$.dims,dataType:Xe($.dataType)})),kernelId:u,kernelType:a,kernelName:p,programName:h,startTime:_,endTime:I});else{let $="";g.forEach((E,A)=>{$+=`input[${A}]: [${E.dims}] | ${Xe(E.dataType)}, `});let x="";b.forEach((E,A)=>{x+=`output[${A}]: [${E.dims}] | ${Xe(E.dataType)}, `}),console.log(`[profiling] kernel "${u}|${a}|${p}|${h}" ${$}${x}execution time: ${I-_} ns`)}An("GPU",`${h}::${w}::${y}`)}t.unmap(),this.pendingQueries.delete(t)}),Rt()}run(t,r,o,n,s){kt(t.name);let u=[];for(let x=0;xE):o;if(h.length!==l.length)throw new Error(`Output size ${h.length} must be equal to ${l.length}.`);let g=[],b=[];for(let x=0;x=l.length)throw new Error(`Invalid output index: ${h[x]}`);if(h[x]===-3)continue;let E=h[x]===-1,A=h[x]===-2,z=E||A?s(l[x].dataType,l[x].dims):n(h[x],l[x].dataType,l[x].dims),R=this.gpuDataManager.get(z.data);if(!R)throw new Error(`no GPU data for output: ${z.data}`);if(E&&this.temporaryData.push(R),A){let V=this.kernelPersistentData.get(this.currentKernelId);V||(V=[],this.kernelPersistentData.set(this.currentKernelId,V)),V.push(R)}g.push(z),b.push(R)}let w;if(p){let x=0,E=[];p.forEach(V=>{let T=typeof V.data=="number"?[V.data]:V.data;if(T.length===0)return;let N=T.length<=2?T.length*4:16;x=Math.ceil(x/N)*N,E.push(x),x+=T.length>4?Math.ceil(T.length/4)*16:T.length*4});let A=16;x=Math.ceil(x/A)*A;let z=new ArrayBuffer(x);p.forEach((V,T)=>{let N=E[T],te=typeof V.data=="number"?[V.data]:V.data;V.type==="int32"?new Int32Array(z,N,te.length).set(te):V.type==="uint32"?new Uint32Array(z,N,te.length).set(te):new Float32Array(z,N,te.length).set(te)});let R=this.gpuDataManager.create(x,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(R.buffer,0,z,0,x),this.gpuDataManager.release(R.id),w={offset:0,size:x,buffer:R.buffer}}let y=this.programManager.normalizeDispatchGroupSize(a),_=y[1]===1&&y[2]===1,I=Uc(t,r,_),$=this.programManager.getArtifact(I);if($||($=this.programManager.build(t,y),this.programManager.setArtifact(I,$),Be("info",()=>`[artifact] key: ${I}, programName: ${t.name}`)),Be("info",()=>`[ProgramManager] run "${t.name}" (key=${I}) with ${y[0]}x${y[1]}x${y[2]}`),this.queryType!=="none"){let x={kernelId:this.currentKernelId,programName:$.programInfo.name,inputTensorViews:r,outputTensorViews:g};this.pendingKernels.push(x)}return this.programManager.run($,u,b,y,w),Rt(t.name),g}upload(t,r){this.gpuDataManager.upload(t,r)}memcpy(t,r){this.gpuDataManager.memcpy(t,r)}async download(t,r){await this.gpuDataManager.download(t,r)}alloc(t){return this.gpuDataManager.create(t).id}free(t){return this.gpuDataManager.release(t)}createKernel(t,r,o,n){let s=yu.get(t);if(!s)throw new Error(`kernel not implemented: ${t}`);let u={kernelType:t,kernelName:n,kernelEntry:s[0],attributes:[s[1],o]};this.kernels.set(r,u)}releaseKernel(t){let r=this.kernelPersistentData.get(t);if(r){for(let o of r)this.gpuDataManager.release(o.id);this.kernelPersistentData.delete(t)}this.kernelCustomData.delete(t),this.kernels.delete(t)}computeKernel(t,r,o){let n=this.kernels.get(t);if(!n)throw new Error(`kernel not created: ${t}`);let s=n.kernelType,u=n.kernelName,l=n.kernelEntry,a=n.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${s}] ${u}" is not allowed to be called recursively`);this.currentKernelId=t,a[0]&&(a[1]=a[0](a[1]),a[0]=void 0),Be("info",()=>`[WebGPU] Start to run kernel "[${s}] ${u}"...`);let p=this.env.debug;this.temporaryData=[];try{return p&&this.device.pushErrorScope("validation"),l(r,a[1]),0}catch(h){return o.push(Promise.resolve(`[WebGPU] Kernel "[${s}] ${u}" failed. ${h}`)),1}finally{p&&o.push(this.device.popErrorScope().then(h=>h?`GPU validation error for kernel "[${s}] ${u}": ${h.message}`:null));for(let h of this.temporaryData)this.gpuDataManager.release(h.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(t,r,o,n){let s=this.sessionExternalDataMapping.get(t);s||(s=new Map,this.sessionExternalDataMapping.set(t,s));let u=s.get(r),l=this.gpuDataManager.registerExternalBuffer(o,n,u?.[1]);return s.set(r,[l,o]),l}unregisterBuffers(t){let r=this.sessionExternalDataMapping.get(t);r&&(r.forEach(o=>this.gpuDataManager.unregisterExternalBuffer(o[1])),this.sessionExternalDataMapping.delete(t))}getBuffer(t){let r=this.gpuDataManager.get(t);if(!r)throw new Error(`no GPU data for buffer: ${t}`);return r.buffer}createDownloader(t,r,o){return async()=>{let n=await On(this,t,r);return sa(n.buffer,o)}}writeTimestamp(t){this.queryType==="inside-passes"&&this.computePassEncoder.writeTimestamp(this.querySet,t)}setQueryType(){this.queryType="none",(this.env.webgpu.profiling?.mode==="default"||this.env.wasm.trace)&&(this.device.features.has("chromium-experimental-timestamp-query-inside-passes")?this.queryType="inside-passes":this.device.features.has("timestamp-query")&&(this.queryType="at-passes"))}}});var $u={};Br($u,{init:()=>Vc});var gr,Jn,Vc,Su=j(()=>{"use strict";Ne();vu();Ct();$e();gr=class e{constructor(t,r,o,n){this.module=t;this.dataType=r;this.data=o;this.dims=n}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let t=U.size(this.dims);return t===0?new Float32Array:new Float32Array(this.module.HEAP8.buffer,this.data,t)}getBigInt64Array(){if(this.dataType!==7)throw new Error("Invalid data type");let t=U.size(this.dims);return t===0?new BigInt64Array:new BigInt64Array(this.module.HEAP8.buffer,this.data,t)}getInt32Array(){if(this.dataType!==6)throw new Error("Invalid data type");let t=U.size(this.dims);return t===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,t)}reshape(t){if(U.size(t)!==U.size(this.dims))throw new Error("Invalid new shape");return new e(this.module,this.dataType,this.data,t)}},Jn=class{constructor(t,r,o){this.module=t;this.backend=r;this.customDataOffset=0;this.customDataSize=0;let n=t.HEAPU32,s=o>>>2;this.opKernelContext=n[s++];let u=n[s++];this.outputCount=n[s++],this.customDataOffset=n[s++],this.customDataSize=n[s++];let l=[];for(let a=0;atypeof l=="number"?this.inputs[l]:l)??this.inputs,n=r?.outputs??[],s=(l,a,p)=>new gr(this.module,a,this.output(l,p),p),u=(l,a)=>{let p=cr(l);if(!p)throw new Error(`Unsupported data type: ${l}`);let h=p*U.size(a);return new gr(this.module,l,this.backend.gpuDataManager.create(h).id,a)};return this.backend.run(t,o,n,s,u)}output(t,r){let o=this.module.stackSave();try{let n=this.module.stackAlloc((1+r.length)*4),s=n>>2;this.module.HEAPU32[s++]=r.length;for(let u=0;u{let o=e.jsepInit;if(!o)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");let n=new sn;await n.initialize(t,r),o(n,s=>n.alloc(s),s=>n.free(s),(s,u,l,a=!1)=>{if(a)Be("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${s}, dst=${u}, size=${l}`),n.memcpy(s,u);else{Be("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${s}, gpuDataId=${u}, size=${l}`);let p=e.HEAPU8.subarray(s>>>0,(s>>>0)+l);n.upload(u,p)}},async(s,u,l)=>{Be("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${s}, dataOffset=${u}, size=${l}`),await n.download(s,()=>e.HEAPU8.subarray(u>>>0,(u>>>0)+l))},(s,u,l)=>n.createKernel(s,u,l,e.UTF8ToString(e._JsepGetNodeName(u))),s=>n.releaseKernel(s),(s,u,l,a)=>{Be("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${l}, kernel=${s}, contextDataOffset=${u}`);let p=new Jn(e,n,u);return n.computeKernel(s,p,a)})}});var Mo;Mo=Io();var Ju=Ro(),Sn,xn=!1,Dr=!1,Do=!1,ed=e=>{if(e===1)return!1;if(typeof SharedArrayBuffer>"u")return typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+e+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),!1;typeof process<"u"&&process.versions&&process.versions.node&&console.warn("env.wasm.numThreads is set to "+e+", however, currently onnxruntime-web does not support multi-threads in Node.js. Please consider using onnxruntime-node for performance critical scenarios.");try{return typeof MessageChannel<"u"&&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}},td=()=>{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,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch{return!1}},rd=(e,t)=>e?t?"ort-wasm-simd-threaded.wasm":"ort-wasm-simd.wasm":t?"ort-wasm-threaded.wasm":"ort-wasm.wasm",zo=async e=>{if(xn)return Promise.resolve();if(Dr)throw new Error("multiple calls to \'initializeWebAssembly()\' detected.");if(Do)throw new Error("previous call to \'initializeWebAssembly()\' failed.");Dr=!0;let t=e.initTimeout,r=e.numThreads,o=e.simd,n=ed(r),s=o&&td(),u=e.wasmPaths,l=typeof u=="string"?u:void 0,a=rd(s,n),p=typeof u=="object"?u[a]:void 0,h=!1,g=[];if(t>0&&g.push(new Promise(b=>{setTimeout(()=>{h=!0,b()},t)})),g.push(new Promise((b,w)=>{let y=n?Ju:Mo,_={locateFile:(I,$)=>{if(n&&I.endsWith(".worker.js")&&typeof Blob<"u")return URL.createObjectURL(new Blob([Bo()],{type:"text/javascript"}));if(I.endsWith(".wasm")){if(p)return p;let x=l??$;return a==="ort-wasm-simd.wasm"?x+"ort-wasm-simd.jsep.wasm":a==="ort-wasm-simd-threaded.wasm"?x+"ort-wasm-simd-threaded.jsep.wasm":x+a}return $+I}};if(n)if(_.numThreads=r,typeof Blob>"u")_.mainScriptUrlOrBlob=(void 0)(__dirname,"ort-wasm-threaded.js");else{let I=`var ortWasmThreaded=${y.toString()};`;_.mainScriptUrlOrBlob=new Blob([I],{type:"text/javascript"})}y(_).then(I=>{Dr=!1,xn=!0,Sn=I,b()},I=>{Dr=!1,Do=!0,w(I)})})),await Promise.race(g),h)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},Ve=()=>{if(xn&&Sn)return Sn;throw new Error("WebAssembly is not initialized yet.")};var He=(e,t)=>{let r=Ve(),o=r.lengthBytesUTF8(e)+1,n=r._malloc(o);return r.stringToUTF8(e,n,o),t.push(n),n},lr=(e,t,r,o)=>{if(typeof e=="object"&&e!==null){if(r.has(e))throw new Error("Circular reference in options");r.add(e)}Object.entries(e).forEach(([n,s])=>{let u=t?t+n:n;if(typeof s=="object")lr(s,u+".",r,o);else if(typeof s=="string"||typeof s=="number")o(u,s.toString());else if(typeof s=="boolean")o(u,s?"1":"0");else throw new Error(`Can\'t handle extra config type: ${typeof s}`)})},ke=e=>{let t=Ve(),r=t.stackSave();try{let o=t.stackAlloc(8);t._OrtGetLastError(o,o+4);let n=t.HEAP32[o/4],s=t.HEAPU32[o/4+1],u=s?t.UTF8ToString(s):"";throw new Error(`${e} ERROR_CODE: ${n}, ERROR_MESSAGE: ${u}`)}finally{t.stackRestore(r)}};var Uo=e=>{let t=Ve(),r=0,o=[],n=e||{};try{if(e?.logSeverityLevel===void 0)n.logSeverityLevel=2;else if(typeof e.logSeverityLevel!="number"||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${e.logSeverityLevel}`);if(e?.logVerbosityLevel===void 0)n.logVerbosityLevel=0;else if(typeof e.logVerbosityLevel!="number"||!Number.isInteger(e.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);e?.terminate===void 0&&(n.terminate=!1);let s=0;return e?.tag!==void 0&&(s=He(e.tag,o)),r=t._OrtCreateRunOptions(n.logSeverityLevel,n.logVerbosityLevel,!!n.terminate,s),r===0&&ke("Can\'t create run options."),e?.extra!==void 0&&lr(e.extra,"",new WeakSet,(u,l)=>{let a=He(u,o),p=He(l,o);t._OrtAddRunConfigEntry(r,a,p)!==0&&ke(`Can\'t set a run config entry: ${u} - ${l}.`)}),[r,o]}catch(s){throw r!==0&&t._OrtReleaseRunOptions(r),o.forEach(u=>t._free(u)),s}};var nd=e=>{switch(e){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${e}`)}},od=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},ad=e=>{e.extra||(e.extra={}),e.extra.session||(e.extra.session={});let t=e.extra.session;t.use_ort_model_bytes_directly||(t.use_ort_model_bytes_directly="1"),e.executionProviders&&e.executionProviders.some(r=>(typeof r=="string"?r:r.name)==="webgpu")&&(e.enableMemPattern=!1)},id=(e,t,r)=>{for(let o of t){let n=typeof o=="string"?o:o.name;switch(n){case"webnn":if(n="WEBNN",typeof o!="string"){let u=o;if(u?.deviceType){let l=He("deviceType",r),a=He(u.deviceType,r);Ve()._OrtAddSessionConfigEntry(e,l,a)!==0&&ke(`Can\'t set a session config entry: \'deviceType\' - ${u.deviceType}.`)}if(u?.numThreads){let l=u.numThreads;(typeof l!="number"||!Number.isInteger(l)||l<0)&&(l=0);let a=He("numThreads",r),p=He(l.toString(),r);Ve()._OrtAddSessionConfigEntry(e,a,p)!==0&&ke(`Can\'t set a session config entry: \'numThreads\' - ${u.numThreads}.`)}if(u?.powerPreference){let l=He("powerPreference",r),a=He(u.powerPreference,r);Ve()._OrtAddSessionConfigEntry(e,l,a)!==0&&ke(`Can\'t set a session config entry: \'powerPreference\' - ${u.powerPreference}.`)}}break;case"webgpu":if(n="JS",typeof o!="string"){let u=o;if(u?.preferredLayout){if(u.preferredLayout!=="NCHW"&&u.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either \'NCHW\' or \'NHWC\': ${u.preferredLayout}`);let l=He("preferredLayout",r),a=He(u.preferredLayout,r);Ve()._OrtAddSessionConfigEntry(e,l,a)!==0&&ke(`Can\'t set a session config entry: \'preferredLayout\' - ${u.preferredLayout}.`)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${n}`)}let s=He(n,r);Ve()._OrtAppendExecutionProvider(e,s)!==0&&ke(`Can\'t append execution provider: ${n}.`)}},Vo=e=>{let t=Ve(),r=0,o=[],n=e||{};ad(n);try{let s=nd(n.graphOptimizationLevel??"all"),u=od(n.executionMode??"sequential"),l=typeof n.logId=="string"?He(n.logId,o):0,a=n.logSeverityLevel??2;if(!Number.isInteger(a)||a<0||a>4)throw new Error(`log serverity level is not valid: ${a}`);let p=n.logVerbosityLevel??0;if(!Number.isInteger(p)||p<0||p>4)throw new Error(`log verbosity level is not valid: ${p}`);let h=typeof n.optimizedModelFilePath=="string"?He(n.optimizedModelFilePath,o):0;if(r=t._OrtCreateSessionOptions(s,!!n.enableCpuMemArena,!!n.enableMemPattern,u,!!n.enableProfiling,0,l,a,p,h),r===0&&ke("Can\'t create session options."),n.executionProviders&&id(r,n.executionProviders,o),n.freeDimensionOverrides)for(let[g,b]of Object.entries(n.freeDimensionOverrides)){if(typeof g!="string")throw new Error(`free dimension override name must be a string: ${g}`);if(typeof b!="number"||!Number.isInteger(b)||b<0)throw new Error(`free dimension override value must be a non-negative integer: ${b}`);let w=He(g,o);t._OrtAddFreeDimensionOverride(r,w,b)!==0&&ke(`Can\'t set a free dimension override: ${g} - ${b}.`)}return n.extra!==void 0&&lr(n.extra,"",new WeakSet,(g,b)=>{let w=He(g,o),y=He(b,o);t._OrtAddSessionConfigEntry(r,w,y)!==0&&ke(`Can\'t set a session config entry: ${g} - ${b}.`)}),[r,o]}catch(s){throw r!==0&&t._OrtReleaseSessionOptions(r),o.forEach(u=>t._free(u)),s}};Ne();var Wo=async e=>{if(typeof e=="string")if(typeof process<"u"&&process.versions&&process.versions.node)try{return new Uint8Array(await(void 0)(e))}catch(t){if(t.code==="ERR_FS_FILE_TOO_LARGE"){let r=(void 0)(e),o=[];for await(let n of r)o.push(n);return new Uint8Array(Buffer.concat(o))}throw t}else{let t=await fetch(e);if(!t.ok)throw new Error(`failed to load external data file: ${e}`);let r=t.headers.get("Content-Length"),o=r?parseInt(r,10):0;if(o<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw new Error(`failed to load external data file: ${e}, no response body.`);let n=t.body.getReader(),s;try{s=new ArrayBuffer(o)}catch(l){if(l instanceof RangeError){let a=Math.ceil(o/65536);s=new WebAssembly.Memory({initial:a,maximum:a}).buffer}else throw l}let u=0;for(;;){let{done:l,value:a}=await n.read();if(l)break;let p=a.byteLength;new Uint8Array(s,u,p).set(a),u+=p}return new Uint8Array(s,0,o)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)};var Nc=(e,t)=>{Ve()._OrtInit(e,t)!==0&&ke("Can\'t initialize onnxruntime.")},_u=async e=>{Nc(e.wasm.numThreads,pr(e.logLevel))},Cu=async(e,t)=>{if(t==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");let r=await navigator.gpu.requestAdapter();if(!r)throw new Error(\'Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.\');if(!e.wasm.simd)throw new Error("Not supported for WebGPU=ON and SIMD=OFF. Please set `env.wasm.simd` to true when using `webgpu` EP");let o=(Su(),Ht($u)).init;await o(Ve(),e,r)}},yr=new Map,Wc=e=>{let t=Ve(),r=t.stackSave();try{let o=t.stackAlloc(8);return t._OrtGetInputOutputCount(e,o,o+4)!==0&&ke("Can\'t get session input/output count."),[t.HEAP32[o/4],t.HEAP32[o/4+1]]}finally{t.stackRestore(r)}},eo=e=>{let t=Ve(),r=t._malloc(e.byteLength);if(r===0)throw new Error(`Can\'t create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,r),[r,e.byteLength]},Iu=async(e,t)=>{let r,o,n=Ve();Array.isArray(e)?[r,o]=e:e.buffer===n.HEAPU8.buffer?[r,o]=[e.byteOffset,e.byteLength]:[r,o]=eo(e);let s=0,u=0,l=0,a=[],p=[],h=[];try{if([u,a]=Vo(t),t?.externalData&&n.mountExternalData){let $=[];for(let x of t.externalData){let E=typeof x=="string"?x:x.path;$.push(Wo(typeof x=="string"?x:x.data).then(A=>{n.mountExternalData(E,A)}))}await Promise.all($)}s=n._OrtCreateSession(r,o,u),s===0&&ke("Can\'t create a session.");let[g,b]=Wc(s),w=[],y=[],_=[];for(let $=0;$$==="gpu-buffer")&&(l=n._OrtCreateBinding(s),l===0&&ke("Can\'t create IO binding."),I={handle:l,outputPreferredLocations:_,outputPreferredLocationsEncoded:_.map($=>Cn($))}),yr.set(s,[s,p,h,I]),[s,w,y]}catch(g){throw p.forEach(b=>n._OrtFree(b)),h.forEach(b=>n._OrtFree(b)),l!==0&&n._OrtReleaseBinding(l),s!==0&&n._OrtReleaseSession(s),g}finally{n._free(r),u!==0&&n._OrtReleaseSessionOptions(u),a.forEach(g=>n._free(g)),n.unmountExternalData?.()}},Au=e=>{let t=Ve(),r=yr.get(e);if(!r)throw new Error(`cannot release session. invalid session id: ${e}`);let[o,n,s,u]=r;u&&t._OrtReleaseBinding(u.handle),t.jsepUnregisterBuffers?.(e),n.forEach(l=>t._OrtFree(l)),s.forEach(l=>t._OrtFree(l)),t._OrtReleaseSession(o),yr.delete(e)},xu=(e,t,r,o,n)=>{if(!e){t.push(0);return}let s=Ve(),u=e[0],l=e[1],a=e[3],p,h;if(u==="string"&&a==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");if(a==="gpu-buffer"){let w=e[2].gpuBuffer,y=cr(_n(u));h=l.reduce((_,I)=>_*I,1)*y,p=s.jsepRegisterBuffer(o,n,w,h)}else{let w=e[2];if(Array.isArray(w)){h=4*w.length,p=s._malloc(h),r.push(p);let y=p/4;for(let _=0;_s.HEAP32[w++]=_);let y=s._OrtCreateTensor(_n(u),p,h,b,l.length,Cn(a));y===0&&ke(`Can\'t create tensor for input/output. session=${o}, index=${n}.`),t.push(y)}finally{s.stackRestore(g)}},Tu=async(e,t,r,o,n,s)=>{let u=Ve(),l=yr.get(e);if(!l)throw new Error(`cannot run inference. invalid session id: ${e}`);let[a,p,h,g]=l,b=t.length,w=o.length,y=0,_=[],I=[],$=[],x=[],E=u.stackSave(),A=u.stackAlloc(b*4),z=u.stackAlloc(b*4),R=u.stackAlloc(w*4),V=u.stackAlloc(w*4);try{[y,_]=Uo(s);for(let Z=0;ZUe*Me,1);he=Xe(Ge);let ze=g?.outputPreferredLocations[o[Z]];if(he==="string"){if(ze==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");let Ue=[],Me=ye/4;for(let wt=0;wt0){let Ue=u.jsepGetBuffer(ye),Me=cr(Ge);if(Me===void 0||!No(he))throw new Error(`Unsupported data type: ${he}`);Ie=!0,Q.push([he,be,{gpuBuffer:Ue,download:u.jsepCreateDownloader(Ue,et*Me,he),dispose:()=>{u._OrtReleaseTensor(Ee)}},"gpu-buffer"])}else{let Ue=Mr(he),Me=new Ue(et);new Uint8Array(Me.buffer,Me.byteOffset,Me.byteLength).set(u.HEAPU8.subarray(ye,ye+Me.byteLength)),Q.push([he,be,Me,"cpu"])}}finally{u.stackRestore(Pe),he==="string"&&ye&&u._free(ye),Ie||u._OrtReleaseTensor(Ee)}}return g&&u._OrtClearBoundOutputs(g.handle),Q}finally{u.stackRestore(E),I.forEach(T=>u._OrtReleaseTensor(T)),$.forEach(T=>u._OrtReleaseTensor(T)),x.forEach(T=>u._free(T)),y!==0&&u._OrtReleaseRunOptions(y),_.forEach(T=>u._free(T))}},Eu=e=>{let t=Ve(),r=yr.get(e);if(!r)throw new Error("invalid session id");let o=r[0],n=t._OrtEndProfiling(o);n===0&&ke("Can\'t get an profile file name."),t._OrtFree(n)},Ou=e=>{let t=[];for(let r of e){let o=r[2];!Array.isArray(o)&&"buffer"in o&&t.push(o.buffer)}return t};self.onmessage=e=>{let{type:t,in:r}=e.data;try{switch(t){case"init-wasm":zo(r.wasm).then(()=>{_u(r).then(()=>{postMessage({type:t})},o=>{postMessage({type:t,err:o})})},o=>{postMessage({type:t,err:o})});break;case"init-ep":{let{epName:o,env:n}=r;Cu(n,o).then(()=>{postMessage({type:t})},s=>{postMessage({type:t,err:s})});break}case"copy-from":{let{buffer:o}=r,n=eo(o);postMessage({type:t,out:n});break}case"create":{let{model:o,options:n}=r;Iu(o,n).then(s=>{postMessage({type:t,out:s})},s=>{postMessage({type:t,err:s})});break}case"release":Au(r),postMessage({type:t});break;case"run":{let{sessionId:o,inputIndices:n,inputs:s,outputIndices:u,options:l}=r;Tu(o,n,s,u,new Array(u.length).fill(null),l).then(a=>{a.some(p=>p[3]!=="cpu")?postMessage({type:t,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:t,out:a},Ou(a))},a=>{postMessage({type:t,err:a})});break}case"end-profiling":Eu(r),postMessage({type:t});break;default:}}catch(o){postMessage({type:t,err:o})}};})();\n/**\n * @license\n * Copyright 2021 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the "License");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an "AS IS" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the "License");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an "AS IS" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the "License");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an "AS IS" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n'}),kr,jt,Pi,Xa,Za,Ud,Zo,ti,ni,dy,Ja,e$,t$,n$,r$,i$,a$,s$,o$=ee(()=>{var e;Fn(),UE(),Hs(),kr=()=>!!je.wasm.proxy&&typeof document<"u",Pi=!1,Xa=!1,Za=!1,Zo=new Map,ti=(t,n)=>{let r=Zo.get(t);r?r.push(n):Zo.set(t,[n])},ni=()=>{if(Pi||!Xa||Za||!jt)throw new Error("worker not ready")},dy=t=>{switch(t.data.type){case"init-wasm":Pi=!1,t.data.err?(Za=!0,Ud[1](t.data.err)):(Xa=!0,Ud[0]());break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let n=Zo.get(t.data.type);t.data.err?n.shift()[1](t.data.err):n.shift()[0](t.data.out);break}}},Ja=typeof document<"u"?(e=document==null?void 0:document.currentScript)==null?void 0:e.src:void 0,e$=async()=>{if(!Xa){if(Pi)throw new Error("multiple calls to 'initWasm()' detected.");if(Za)throw new Error("previous call to 'initWasm()' failed.");if(Pi=!0,kr())return je.wasm.wasmPaths===void 0&&Ja&&Ja.indexOf("blob:")!==0&&(je.wasm.wasmPaths=Ja.substr(0,+Ja.lastIndexOf("/")+1)),new Promise((t,n)=>{jt==null||jt.terminate();let r=URL.createObjectURL(new Blob([WE()],{type:"text/javascript"}));jt=new Worker(r,{name:"ort-wasm-proxy-worker"}),jt.onerror=a=>n(a),jt.onmessage=dy,URL.revokeObjectURL(r),Ud=[t,n];let i={type:"init-wasm",in:je};jt.postMessage(i)});try{await bv(je.wasm),await q2(je),Xa=!0}catch(t){throw Za=!0,t}finally{Pi=!1}}},t$=async t=>{if(kr())return ni(),new Promise((n,r)=>{ti("init-ep",[n,r]);let i={type:"init-ep",in:{epName:t,env:je}};jt.postMessage(i)});await K2(je,t)},n$=async t=>kr()?(ni(),new Promise((n,r)=>{ti("copy-from",[n,r]);let i={type:"copy-from",in:{buffer:t}};jt.postMessage(i,[t.buffer])})):Xc(t),r$=async(t,n)=>{if(kr()){if(n!=null&&n.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return ni(),new Promise((r,i)=>{ti("create",[r,i]);let a={type:"create",in:{model:t,options:n}},s=[];t instanceof Uint8Array&&s.push(t.buffer),jt.postMessage(a,s)})}else return Y2(t,n)},i$=async t=>{if(kr())return ni(),new Promise((n,r)=>{ti("release",[n,r]);let i={type:"release",in:t};jt.postMessage(i)});Q2(t)},a$=async(t,n,r,i,a,s)=>{if(kr()){if(r.some(o=>o[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(a.some(o=>o))throw new Error("pre-allocated output tensor is not supported for proxy.");return ni(),new Promise((o,l)=>{ti("run",[o,l]);let d=r,c={type:"run",in:{sessionId:t,inputIndices:n,inputs:d,outputIndices:i,options:s}};jt.postMessage(c,J2(d))})}else return X2(t,n,r,i,a,s)},s$=async t=>{if(kr())return ni(),new Promise((n,r)=>{ti("end-profiling",[n,r]);let i={type:"end-profiling",in:t};jt.postMessage(i)});Z2(t)}}),Wd,cy,l$,VE=ee(()=>{Fn(),o$(),lt(),Ev(),Wd=(e,t)=>{switch(e.location){case"cpu":return[e.type,e.dims,e.data,"cpu"];case"gpu-buffer":return[e.type,e.dims,{gpuBuffer:e.gpuBuffer},"gpu-buffer"];default:throw new Error(`invalid data location: ${e.location} for ${t()}`)}},cy=e=>{switch(e[3]){case"cpu":return new Lt(e[0],e[2],e[1]);case"gpu-buffer":{let t=e[0];if(!cf(t))throw new Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:n,download:r,dispose:i}=e[2];return Lt.fromGpuBuffer(n,{dataType:t,dims:e[1],download:r,dispose:i})}default:throw new Error(`invalid data location: ${e[3]}`)}},l$=class{async fetchModelAndCopyToWasmMemory(e){return n$(await Yl(e))}async loadModel(e,t){Nn();let n;typeof e=="string"?typeof process<"u"&&process.versions&&process.versions.node?n=await Yl(e):n=await this.fetchModelAndCopyToWasmMemory(e):n=e,[this.sessionId,this.inputNames,this.outputNames]=await r$(n,t),Ln()}async dispose(){return i$(this.sessionId)}async run(e,t,n){Nn();let r=[],i=[];Object.entries(e).forEach(u=>{let f=u[0],h=u[1],g=this.inputNames.indexOf(f);if(g===-1)throw new Error(`invalid input '${f}'`);r.push(h),i.push(g)});let a=[],s=[];Object.entries(t).forEach(u=>{let f=u[0],h=u[1],g=this.outputNames.indexOf(f);if(g===-1)throw new Error(`invalid output '${f}'`);a.push(h),s.push(g)});let o=r.map((u,f)=>Wd(u,()=>`input "${this.inputNames[i[f]]}"`)),l=a.map((u,f)=>u?Wd(u,()=>`output "${this.outputNames[s[f]]}"`):null),d=await a$(this.sessionId,i,o,s,l,n),c={};for(let u=0;u{Fn(),o$(),VE(),py=()=>{if((typeof je.wasm.initTimeout!="number"||je.wasm.initTimeout<0)&&(je.wasm.initTimeout=0),typeof je.wasm.simd!="boolean"&&(je.wasm.simd=!0),typeof je.wasm.proxy!="boolean"&&(je.wasm.proxy=!1),typeof je.wasm.trace!="boolean"&&(je.wasm.trace=!1),typeof je.wasm.numThreads!="number"||!Number.isInteger(je.wasm.numThreads)||je.wasm.numThreads<=0){(typeof self<"u"&&!self.crossOriginIsolated||typeof process<"u"&&process.versions&&process.versions.node)&&(je.wasm.numThreads=1);let e=typeof navigator>"u"?(void 0)().length:navigator.hardwareConcurrency;je.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},u$=class{async init(e){py(),await e$(),await t$(e)}async createInferenceSessionHandler(e,t){let n=new l$;return await n.loadModel(e,t),Promise.resolve(n)}}}),d$={};ga(d$,{wasmBackend:()=>c$});var c$,GE=ee(()=>{jE(),c$=new u$});Fn();Fn();Fn();var HE="1.17.1",qE=fv;{let e=(GE(),fi(d$)).wasmBackend;na("webgpu",e,5),na("cpu",e,10),na("wasm",e,10)}Object.defineProperty(je.versions,"web",{value:HE,enumerable:!0});/** * @license * Copyright 2021 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= *//** * @license * Copyright 2020 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= *//** * @license * Copyright 2019 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */const KE=Object.freeze(Object.defineProperty({__proto__:null,get InferenceSession(){return af},get TRACE(){return Ds},get TRACE_FUNC_BEGIN(){return Nn},get TRACE_FUNC_END(){return Ln},get Tensor(){return Lt},get TrainingSession(){return sf},default:qE,get env(){return je},get registerBackend(){return na}},Symbol.toStringTag,{value:"Module"})),YE=(e,t)=>{const n=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);n.width=e.dims[3],n.height=e.dims[2];const r=n.getContext("2d");if(r!=null){let i,a;(t==null?void 0:t.tensorLayout)!==void 0&&t.tensorLayout==="NHWC"?(i=e.dims[2],a=e.dims[3]):(i=e.dims[3],a=e.dims[2]);const s=(t==null?void 0:t.format)!==void 0?t.format:"RGB",o=t==null?void 0:t.norm;let l,d;o===void 0||o.mean===void 0?l=[255,255,255,255]:typeof o.mean=="number"?l=[o.mean,o.mean,o.mean,o.mean]:(l=[o.mean[0],o.mean[1],o.mean[2],0],o.mean[3]!==void 0&&(l[3]=o.mean[3])),o===void 0||o.bias===void 0?d=[0,0,0,0]:typeof o.bias=="number"?d=[o.bias,o.bias,o.bias,o.bias]:(d=[o.bias[0],o.bias[1],o.bias[2],0],o.bias[3]!==void 0&&(d[3]=o.bias[3]));const c=a*i;let u=0,f=c,h=c*2,g=-1;s==="RGBA"?(u=0,f=c,h=c*2,g=c*3):s==="RGB"?(u=0,f=c,h=c*2):s==="RBG"&&(u=0,h=c,f=c*2);for(let $=0;${const n=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");let r;if(n!=null){let i,a,s;(t==null?void 0:t.tensorLayout)!==void 0&&t.tensorLayout==="NHWC"?(i=e.dims[2],a=e.dims[1],s=e.dims[3]):(i=e.dims[3],a=e.dims[2],s=e.dims[1]);const o=t!==void 0&&t.format!==void 0?t.format:"RGB",l=t==null?void 0:t.norm;let d,c;l===void 0||l.mean===void 0?d=[255,255,255,255]:typeof l.mean=="number"?d=[l.mean,l.mean,l.mean,l.mean]:(d=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(d[3]=l.mean[3])),l===void 0||l.bias===void 0?c=[0,0,0,0]:typeof l.bias=="number"?c=[l.bias,l.bias,l.bias,l.bias]:(c=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(c[3]=l.bias[3]));const u=a*i;if(t!==void 0&&(t.format!==void 0&&s===4&&t.format!=="RGBA"||s===3&&t.format!=="RGB"&&t.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");const f=4;let h=0,g=1,$=2,E=3,y=0,_=u,v=u*2,b=-1;o==="RGBA"?(y=0,_=u,v=u*2,b=u*3):o==="RGB"?(y=0,_=u,v=u*2):o==="RBG"&&(y=0,v=u,_=u*2),r=n.createImageData(i,a);for(let C=0;C{if(e===void 0)throw new Error("Image buffer must be defined");if(t.height===void 0||t.width===void 0)throw new Error("Image height and width must be defined");if(t.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");const{height:n,width:r}=t,i=t.norm??{mean:255,bias:0};let a,s;typeof i.mean=="number"?a=[i.mean,i.mean,i.mean,i.mean]:a=[i.mean[0],i.mean[1],i.mean[2],i.mean[3]??255],typeof i.bias=="number"?s=[i.bias,i.bias,i.bias,i.bias]:s=[i.bias[0],i.bias[1],i.bias[2],i.bias[3]??0];const o=t.format!==void 0?t.format:"RGBA",l=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:"RGB",d=n*r,c=l==="RGBA"?new Float32Array(d*4):new Float32Array(d*3);let u=4,f=0,h=1,g=2,$=3,E=0,y=d,_=d*2,v=-1;o==="RGB"&&(u=3,f=0,h=1,g=2,$=-1),l==="RGBA"?v=d*3:l==="RBG"?(E=0,_=d,y=d*2):l==="BGR"&&(_=0,y=d,E=d*2);for(let C=0;C{const n=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,r=typeof ImageData<"u"&&e instanceof ImageData,i=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,a=typeof e=="string";let s,o=t??{};const l=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},d=c=>c instanceof HTMLCanvasElement||c instanceof OffscreenCanvas?c.getContext("2d"):null;if(n){const c=l();c.width=e.width,c.height=e.height;const u=d(c);if(u!=null){let f=e.height,h=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(f=t.resizedHeight,h=t.resizedWidth),t!==void 0){if(o=t,t.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");o.tensorFormat="RGBA",o.height=f,o.width=h}else o.tensorFormat="RGBA",o.height=f,o.width=h;u.drawImage(e,0,0),s=u.getImageData(0,0,h,f).data}else throw new Error("Can not access image data")}else if(r){let c,u;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(c=t.resizedHeight,u=t.resizedWidth):(c=e.height,u=e.width),t!==void 0&&(o=t),o.format="RGBA",o.height=c,o.width=u,t!==void 0){const f=l();f.width=u,f.height=c;const h=d(f);if(h!=null)h.putImageData(e,0,0),s=h.getImageData(0,0,u,c).data;else throw new Error("Can not access image data")}else s=e.data}else if(i){if(t===void 0)throw new Error("Please provide image config with format for Imagebitmap");const c=l();c.width=e.width,c.height=e.height;const u=d(c);if(u!=null){const f=e.height,h=e.width;return u.drawImage(e,0,0,h,f),s=u.getImageData(0,0,h,f).data,o.height=f,o.width=h,Vd(s,o)}else throw new Error("Can not access image data")}else{if(a)return new Promise((c,u)=>{const f=l(),h=d(f);if(!e||!h)return u();const g=new Image;g.crossOrigin="Anonymous",g.src=e,g.onload=()=>{f.width=g.width,f.height=g.height,h.drawImage(g,0,0,f.width,f.height);const $=h.getImageData(0,0,f.width,f.height);o.height=f.height,o.width=f.width,c(Vd($.data,o))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(s!==void 0)return Vd(s,o);throw new Error("Input data provided is not supported - aborted tensor creation")},ZE=(e,t)=>{const{width:n,height:r,download:i,dispose:a}=t,s=[1,r,n,4];return new Yn({location:"texture",type:"float32",texture:e,dims:s,download:i,dispose:a})},JE=(e,t)=>{const{dataType:n,dims:r,download:i,dispose:a}=t;return new Yn({location:"gpu-buffer",type:n??"float32",gpuBuffer:e,dims:r,download:i,dispose:a})},ek=(e,t,n)=>new Yn({location:"cpu-pinned",type:e,data:t,dims:n??[t.length]}),tu=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["float16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array]]),Zc=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);let fy=!1;const tk=()=>{if(!fy){fy=!0;const e=typeof BigInt64Array<"u"&&typeof BigInt64Array.from=="function",t=typeof BigUint64Array<"u"&&typeof BigUint64Array.from=="function";e&&(tu.set("int64",BigInt64Array),Zc.set(BigInt64Array,"int64")),t&&(tu.set("uint64",BigUint64Array),Zc.set(BigUint64Array,"uint64"))}},nk=e=>{let t=1;for(let n=0;n{switch(e.location){case"cpu":return new Yn(e.type,e.data,t);case"cpu-pinned":return new Yn({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new Yn({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new Yn({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}};let Yn=class{constructor(t,n,r){tk();let i,a;if(typeof t=="object"&&"location"in t)switch(this.dataLocation=t.location,i=t.type,a=t.dims,t.location){case"cpu-pinned":{const o=tu.get(i);if(!o)throw new TypeError(`unsupported type "${i}" to create tensor from pinned buffer`);if(!(t.data instanceof o))throw new TypeError(`buffer should be of type ${o.name}`);this.cpuData=t.data;break}case"texture":{if(i!=="float32")throw new TypeError(`unsupported type "${i}" to create tensor from texture`);this.gpuTextureData=t.texture,this.downloader=t.download,this.disposer=t.dispose;break}case"gpu-buffer":{if(i!=="float32"&&i!=="float16"&&i!=="int32"&&i!=="int64"&&i!=="uint32"&&i!=="bool")throw new TypeError(`unsupported type "${i}" to create tensor from gpu buffer`);this.gpuBufferData=t.gpuBuffer,this.downloader=t.download,this.disposer=t.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let o,l;if(typeof t=="string")if(i=t,l=r,t==="string"){if(!Array.isArray(n))throw new TypeError("A string tensor's data must be a string array.");o=n}else{const d=tu.get(t);if(d===void 0)throw new TypeError(`Unsupported tensor type: ${t}.`);if(Array.isArray(n)){if(t==="float16")throw new TypeError("Creating a float16 tensor from number array is not supported. Please use Uint16Array as data.");t==="uint64"||t==="int64"?o=d.from(n,BigInt):o=d.from(n)}else if(n instanceof d)o=n;else throw new TypeError(`A ${i} tensor's data must be type of ${d}`)}else if(l=n,Array.isArray(t)){if(t.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");const d=typeof t[0];if(d==="string")i="string",o=t;else if(d==="boolean")i="bool",o=Uint8Array.from(t);else throw new TypeError(`Invalid element type of data array: ${d}.`)}else{const d=Zc.get(t.constructor);if(d===void 0)throw new TypeError(`Unsupported type for tensor data: ${t.constructor}.`);i=d,o=t}if(l===void 0)l=[o.length];else if(!Array.isArray(l))throw new TypeError("A tensor's dims must be a number array");a=l,this.cpuData=o,this.dataLocation="cpu"}const s=nk(a);if(this.cpuData&&s!==this.cpuData.length)throw new Error(`Tensor's size(${s}) does not match data length(${this.cpuData.length}).`);this.type=i,this.dims=a,this.size=s}static async fromImage(t,n){return XE(t,n)}static fromTexture(t,n){return ZE(t,n)}static fromGpuBuffer(t,n){return JE(t,n)}static fromPinnedBuffer(t,n,r){return ek(t,n,r)}toDataURL(t){return YE(this,t)}toImageData(t){return QE(this,t)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}async getData(t){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;const n=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=n,t&&this.disposer&&(this.disposer(),this.disposer=void 0),n}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(t){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return rk(this,t)}};const ik=Yn,gs=[];let Jc,hi;Gl.IS_NODE_ENV?(hi=ft??wS,gs.push("cpu"),Jc=["cpu"]):(hi=KE,Gl.IS_WEBGPU_AVAILABLE&&gs.push("webgpu"),gs.push("wasm"),Jc=["wasm"]);const ak=hi.InferenceSession;function sk(e){let t=Jc;if(e){if(!gs.includes(e))throw new Error(`Unsupported device: "${e}". Should be one of: ${gs.join(", ")}.`);t=[e]}return t}async function ok(e,t){return await ak.create(e,t)}function p$(e){return e instanceof hi.Tensor}const On=hi==null?void 0:hi.env;On!=null&&On.wasm&&(On.wasm.wasmPaths="https://cdn.jsdelivr.net/npm/onnxruntime-web@1.17.1/dist/",On.wasm.proxy=!0,(typeof crossOriginIsolated>"u"||!crossOriginIsolated)&&(On.wasm.numThreads=1),typeof navigator<"u"&&/iP(hone|od|ad).+16_4.+AppleWebKit/.test(navigator.userAgent)&&(On.wasm.simd=!1));function lk(){var e;return(e=On==null?void 0:On.wasm)==null?void 0:e.proxy}Zt.backends.onnx=On;const hy=Object.freeze({float32:Float32Array,float16:Uint16Array,float64:Float64Array,string:Array,int8:Int8Array,uint8:Uint8Array,int16:Int16Array,uint16:Uint16Array,int32:Int32Array,uint32:Uint32Array,int64:BigInt64Array,uint64:BigUint64Array,bool:Uint8Array});class _e{constructor(...t){j(this,"ort_tensor");return p$(t[0])?this.ort_tensor=t[0]:this.ort_tensor=new ik(t[0],t[1],t[2]),new Proxy(this,{get:(n,r)=>{if(typeof r=="string"){let i=Number(r);if(Number.isInteger(i))return n._getitem(i)}return n[r]},set:(n,r,i)=>n[r]=i})}get dims(){return this.ort_tensor.dims}set dims(t){this.ort_tensor.dims=t}get type(){return this.ort_tensor.type}get data(){return this.ort_tensor.data}get size(){return this.ort_tensor.size}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){const[t,...n]=this.dims;if(n.length>0){const r=n.reduce((i,a)=>i*a);for(let i=0;i0){const i=r.reduce((a,s)=>a*s);return this._subarray(t,i,r)}else return new _e(this.type,[this.data[t]],r)}indexOf(t){for(let n=0;nd[1])throw new Error(`Invalid slice: ${d}`);let c=[Math.max(d[0],0),Math.min(d[1],this.dims[l])];r.push(c),n.push(c[1]-c[0])}else throw new Error(`Invalid slice: ${d}`)}let i=r.map(([l,d])=>d-l),a=i.reduce((l,d)=>l*d),s=new this.data.constructor(a);const o=this.stride();for(let l=0;l=0;--c){const f=i[c];d+=(u%f+r[c][0])*o[c],u=Math.floor(u/f)}s[l]=this.data[d]}return new _e(this.type,s,n)}permute(...t){return dk(this,t)}transpose(...t){return this.permute(...t)}sum(t=null,n=!1){return this.norm(1,t,n)}norm(t="fro",n=null,r=!1){if(t==="fro")t=2;else if(typeof t=="string")throw Error(`Unsupported norm: ${t}`);if(n===null){let s=this.data.reduce((o,l)=>o+l**t,0)**(1/t);return new _e(this.type,[s],[])}n=Rr(n,this.dims.length);const i=this.dims.slice();i[n]=1;const a=new this.data.constructor(this.data.length/this.dims[n]);for(let s=0;s=0;--l){const u=this.dims[l];if(l!==n){const f=d%u;o+=f*c,c*=i[l]}d=Math.floor(d/u)}a[o]+=this.data[s]**t}if(t!==1)for(let s=0;s=0;--s){const d=this.dims[s];if(s!==n){const c=o%d;a+=c*l,l*=this.dims[s]}o=Math.floor(o/d)}this.data[i]/=r.data[a]}return this}normalize(t=2,n=1){return this.clone().normalize_(t,n)}stride(){return fk(this.dims)}squeeze(t=null){return new _e(this.type,this.data,my(this.dims,t))}squeeze_(t=null){return this.dims=my(this.dims,t),this}unsqueeze(t=null){return new _e(this.type,this.data,gy(this.dims,t))}unsqueeze_(t=null){return this.dims=gy(this.dims,t),this}flatten_(t=0,n=-1){n=(n+this.dims.length)%this.dims.length;let r=this.dims.slice(0,t),i=this.dims.slice(t,n+1),a=this.dims.slice(n+1);return this.dims=[...r,i.reduce((s,o)=>s*o,1),...a],this}flatten(t=0,n=-1){return this.clone().flatten_(t,n)}view(...t){let n=-1;for(let r=0;rs!==n?i*a:i,1);t[n]=this.data.length/r}return new _e(this.type,this.data,t)}neg_(){for(let t=0;ta*s);if(n!==r)throw Error(`cannot reshape array of size ${n} into shape (${t})`);let i=e;for(let a=t.length-1;a>=0;a--)i=i.reduce((s,o)=>{let l=s[s.length-1];return l.lengthn!==1):typeof t=="number"?e[t]===1&&e.splice(t,1):Array.isArray(t)&&(e=e.filter((n,r)=>n!==1||!t.includes(r))),e}function gy(e,t){return t=Rr(t,e.length+1),e=e.slice(),e.splice(t,0,1),e}function Rr(e,t,n=null){if(e<-t||e>=t)throw new Error(`IndexError: index ${e} is out of bounds for dimension${n===null?"":" "+n} with size ${t}`);return e<0&&(e=(e%t+t)%t),e}function pr(e,t=0){t=Rr(t,e[0].dims.length);const n=e[0].dims.slice();n[t]=e.reduce((s,o)=>s+o.dims[t],0);const r=n.reduce((s,o)=>s*o,1),i=new e[0].data.constructor(r),a=e[0].type;if(t===0){let s=0;for(let o of e)i.set(o.data,s),s+=o.data.length}else{let s=0;for(let o=0;o=0;--u){const g=l.dims[u];let $=f%g;u===t&&($+=s),c+=$*h,h*=n[u],f=Math.floor(f/g)}i[c]=l.data[d]}s+=l.dims[t]}}return new _e(a,i,n)}function ep(e,t=0){return pr(e.map(n=>n.unsqueeze(t)),t)}function ck(e,t=null,n=1,r=!1){if(t===null){const d=e.data.reduce((h,g)=>h+g,0)/e.data.length,c=Math.sqrt(e.data.reduce((h,g)=>h+(g-d)**2,0)/(e.data.length-n)),u=new _e(e.type,[d],[]);return[new _e(e.type,[c],[]),u]}t=Rr(t,e.dims.length);const i=bf(e,t,r),a=e.dims.slice();a[t]=1;const s=new e.data.constructor(e.data.length/e.dims[t]);for(let l=0;l=0;--c){const h=e.dims[c];if(c!==t){const g=u%h;d+=g*f,f*=a[c]}u=Math.floor(u/h)}s[d]+=(e.data[l]-i.data[d])**2}for(let l=0;ls+o,0);return new _e(e.type,[a/e.data.length],[])}t=Rr(t,e.dims.length);const r=e.dims.slice();r[t]=1;const i=new e.data.constructor(e.data.length/e.dims[t]);for(let a=0;a=0;--o){const c=e.dims[o];if(o!==t){const u=l%c;s+=u*d,d*=r[o]}l=Math.floor(l/c)}i[s]+=e.data[a]}if(e.dims[t]!==1)for(let a=0;a0||o>0;)switch(l.push(s-1),d.push(o-1),a[s][o].item()){case 0:--s,--o;break;case 1:--s;break;case 2:--o;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${s}, ${o}]. Please file a bug report.`)}return l.reverse(),d.reverse(),[l,d]}function fk(e){const t=new Array(e.length);for(let n=e.length-1,r=1;n>=0;--n)t[n]=r,r*=e[n];return t}function xf(e,t,n,r){const i=e.reduce((a,s)=>a*s,1);return new _e(n,new r(i).fill(t),e)}function hk(e,t){let n,r;if(typeof t=="number")n="float32",r=Float32Array;else if(typeof t=="bigint")n="int64",r=BigInt64Array;else throw new Error(`Unsupported data type: ${typeof t}`);return xf(e,t,n,r)}function mk(e,t){return hk(e.dims,t)}function nu(e){return xf(e,1n,"int64",BigInt64Array)}function gk(e){return nu(e.dims)}function yk(e){return xf(e,0n,"int64",BigInt64Array)}function wk(e){return yk(e.dims)}class _k{constructor(t=(n,r)=>n>r){this._heap=[],this._comparator=t}get size(){return this._heap.length}isEmpty(){return this.size===0}peek(){return this._heap[0]}push(...t){return this.extend(t)}extend(t){for(const n of t)this._heap.push(n),this._siftUp();return this.size}pop(){const t=this.peek(),n=this.size-1;return n>0&&this._swap(0,n),this._heap.pop(),this._siftDown(),t}replace(t){const n=this.peek();return this._heap[0]=t,this._siftDown(),n}_parent(t){return(t+1>>>1)-1}_left(t){return(t<<1)+1}_right(t){return t+1<<1}_greater(t,n){return this._comparator(this._heap[t],this._heap[n])}_swap(t,n){const r=this._heap[t];this._heap[t]=this._heap[n],this._heap[n]=r}_siftUp(){let t=this.size-1;for(;t>0&&this._greater(t,this._parent(t));)this._swap(t,this._parent(t)),t=this._parent(t)}_siftDown(){let t=0;for(;this._left(t)[]),this.endNodes=Array.from({length:this.len+1},()=>[]);const i=new ys(this.bosTokenId,0,0,0,0),a=new ys(this.eosTokenId,1,this.len,0,0);this.nodes.push(i.clone()),this.nodes.push(a.clone()),this.beginNodes[this.len].push(a),this.endNodes[0].push(i)}insert(t,n,r,i){const a=this.nodes.length,s=new ys(i,a,t,n,r);this.beginNodes[t].push(s),this.endNodes[t+n].push(s),this.nodes.push(s)}viterbi(){const t=this.len;let n=0;for(;n<=t;){if(this.beginNodes[n].length==0)return[];for(let o of this.beginNodes[n]){o.prev=null;let l=0,d=null;for(let c of this.endNodes[n]){const u=c.backtraceScore+o.score;(d===null||u>l)&&(d=c.clone(),l=u)}if(d!==null)o.prev=d,o.backtraceScore=l;else return[]}++n}const r=[],a=this.beginNodes[t][0].prev;if(a===null)return[];let s=a.clone();for(;s.prev!==null;)r.push(s.clone()),s=s.clone().prev.clone();return r.reverse(),r}piece(t){return this.sentence.slice(t.pos,t.pos+t.length)}tokens(){return this.viterbi().map(n=>this.piece(n))}tokenIds(){return this.viterbi().map(n=>n.tokenId)}}class ys{constructor(t,n,r,i,a){this.tokenId=t,this.nodeId=n,this.pos=r,this.length=i,this.score=a,this.prev=null,this.backtraceScore=0}clone(){const t=new ys(this.tokenId,this.nodeId,this.pos,this.length,this.score);return t.prev=this.prev,t.backtraceScore=this.backtraceScore,t}}var N=Object.freeze({Text:"Text",NumericLiteral:"NumericLiteral",BooleanLiteral:"BooleanLiteral",StringLiteral:"StringLiteral",Identifier:"Identifier",Equals:"Equals",OpenParen:"OpenParen",CloseParen:"CloseParen",OpenStatement:"OpenStatement",CloseStatement:"CloseStatement",OpenExpression:"OpenExpression",CloseExpression:"CloseExpression",OpenSquareBracket:"OpenSquareBracket",CloseSquareBracket:"CloseSquareBracket",OpenCurlyBracket:"OpenCurlyBracket",CloseCurlyBracket:"CloseCurlyBracket",Comma:"Comma",Dot:"Dot",Colon:"Colon",Pipe:"Pipe",CallOperator:"CallOperator",AdditiveBinaryOperator:"AdditiveBinaryOperator",MultiplicativeBinaryOperator:"MultiplicativeBinaryOperator",ComparisonBinaryOperator:"ComparisonBinaryOperator",UnaryOperator:"UnaryOperator",Set:"Set",If:"If",For:"For",In:"In",Is:"Is",NotIn:"NotIn",Else:"Else",EndIf:"EndIf",ElseIf:"ElseIf",EndFor:"EndFor",And:"And",Or:"Or",Not:"UnaryOperator"}),yy=Object.freeze({set:N.Set,for:N.For,in:N.In,is:N.Is,if:N.If,else:N.Else,endif:N.EndIf,elif:N.ElseIf,endfor:N.EndFor,and:N.And,or:N.Or,not:N.Not,"not in":N.NotIn,true:N.BooleanLiteral,false:N.BooleanLiteral}),ri=class{constructor(e,t){this.value=e,this.type=t}};function wy(e){return/\w/.test(e)}function jd(e){return/[0-9]/.test(e)}var bk=[["{%",N.OpenStatement],["%}",N.CloseStatement],["{{",N.OpenExpression],["}}",N.CloseExpression],["(",N.OpenParen],[")",N.CloseParen],["{",N.OpenCurlyBracket],["}",N.CloseCurlyBracket],["[",N.OpenSquareBracket],["]",N.CloseSquareBracket],[",",N.Comma],[".",N.Dot],[":",N.Colon],["|",N.Pipe],["<=",N.ComparisonBinaryOperator],[">=",N.ComparisonBinaryOperator],["==",N.ComparisonBinaryOperator],["!=",N.ComparisonBinaryOperator],["<",N.ComparisonBinaryOperator],[">",N.ComparisonBinaryOperator],["+",N.AdditiveBinaryOperator],["-",N.AdditiveBinaryOperator],["*",N.MultiplicativeBinaryOperator],["/",N.MultiplicativeBinaryOperator],["%",N.MultiplicativeBinaryOperator],["=",N.Equals]],xk=new Map([["n",` `],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function Sk(e,t={}){return e.endsWith(` `)&&(e=e.slice(0,-1)),e=e.replace(/{#.*?#}/gs,"{##}"),t.lstrip_blocks&&(e=e.replace(/^[ \t]*({[#%])/gm,"$1")),t.trim_blocks&&(e=e.replace(/([#%]})\n/g,"$1")),e.replace(/{##}/g,"").replace(/-%}\s*/g,"%}").replace(/\s*{%-/g,"{%").replace(/-}}\s*/g,"}}").replace(/\s*{{-/g,"{{")}function Ek(e,t={}){var s,o,l;const n=[],r=Sk(e,t);let i=0;const a=d=>{let c="";for(;d(r[i]);){if(r[i]==="\\"){if(++i,i>=r.length)throw new SyntaxError("Unexpected end of input");const u=r[i++],f=xk.get(u);if(f===void 0)throw new SyntaxError(`Unexpected escaped character: ${u}`);c+=f;continue}if(c+=r[i++],i>=r.length)throw new SyntaxError("Unexpected end of input")}return c};e:for(;i0){n.push(new ri(u,N.Text));continue}}a(u=>/\s/.test(u));const c=r[i];if(c==="-"||c==="+"){const u=(o=n.at(-1))==null?void 0:o.type;if(u===N.Text||u===void 0)throw new SyntaxError(`Unexpected character: ${c}`);switch(u){case N.Identifier:case N.NumericLiteral:case N.BooleanLiteral:case N.StringLiteral:case N.CloseParen:case N.CloseSquareBracket:break;default:{++i;const f=a(jd);n.push(new ri(`${c}${f}`,f.length>0?N.NumericLiteral:N.UnaryOperator));continue}}}for(const[u,f]of bk)if(r.slice(i,i+u.length)===u){n.push(new ri(u,f)),i+=u.length;continue e}if(c==="'"||c==='"'){++i;const u=a(f=>f!==c);n.push(new ri(u,N.StringLiteral)),++i;continue}if(jd(c)){const u=a(jd);n.push(new ri(u,N.NumericLiteral));continue}if(wy(c)){const u=a(wy),f=Object.hasOwn(yy,u)?yy[u]:N.Identifier;f===N.In&&((l=n.at(-1))==null?void 0:l.type)===N.Not?(n.pop(),n.push(new ri("not in",N.NotIn))):n.push(new ri(u,f));continue}throw new SyntaxError(`Unexpected character: ${c}`)}return n}var Ks=class{constructor(){j(this,"type","Statement")}},kk=class extends Ks{constructor(t){super();j(this,"type","Program");this.body=t}},_y=class extends Ks{constructor(t,n,r){super();j(this,"type","If");this.test=t,this.body=n,this.alternate=r}},Ck=class extends Ks{constructor(t,n,r){super();j(this,"type","For");this.loopvar=t,this.iterable=n,this.body=r}},Tk=class extends Ks{constructor(t,n){super();j(this,"type","Set");this.assignee=t,this.value=n}},Jn=class extends Ks{constructor(){super(...arguments);j(this,"type","Expression")}},Ik=class extends Jn{constructor(t,n,r){super();j(this,"type","MemberExpression");this.object=t,this.property=n,this.computed=r}},Ak=class extends Jn{constructor(t,n){super();j(this,"type","CallExpression");this.callee=t,this.args=n}},Bi=class extends Jn{constructor(t){super();j(this,"type","Identifier");this.value=t}},wa=class extends Jn{constructor(t){super();j(this,"type","Literal");this.value=t}},Ok=class extends wa{constructor(){super(...arguments);j(this,"type","NumericLiteral")}},vy=class extends wa{constructor(){super(...arguments);j(this,"type","StringLiteral")}},$y=class extends wa{constructor(){super(...arguments);j(this,"type","BooleanLiteral")}},Mk=class extends wa{constructor(){super(...arguments);j(this,"type","ArrayLiteral")}},by=class extends wa{constructor(){super(...arguments);j(this,"type","TupleLiteral")}},zk=class extends wa{constructor(){super(...arguments);j(this,"type","ObjectLiteral")}},es=class extends Jn{constructor(t,n,r){super();j(this,"type","BinaryExpression");this.operator=t,this.left=n,this.right=r}},Rk=class extends Jn{constructor(t,n){super();j(this,"type","FilterExpression");this.operand=t,this.filter=n}},Pk=class extends Jn{constructor(t,n,r){super();j(this,"type","TestExpression");this.operand=t,this.negate=n,this.test=r}},Bk=class extends Jn{constructor(t,n){super();j(this,"type","UnaryExpression");this.operator=t,this.argument=n}},Dk=class extends Jn{constructor(t=void 0,n=void 0,r=void 0){super();j(this,"type","SliceExpression");this.start=t,this.stop=n,this.step=r}},Nk=class extends Jn{constructor(t,n){super();j(this,"type","KeywordArgumentExpression");this.key=t,this.value=n}};function Lk(e){const t=new kk([]);let n=0;function r(R,H){const re=e[n++];if(!re||re.type!==R)throw new Error(`Parser Error: ${H}. ${re.type} !== ${R}.`);return re}function i(){switch(e[n].type){case N.Text:return o();case N.OpenStatement:return l();case N.OpenExpression:return d();default:throw new SyntaxError(`Unexpected token type: ${e[n].type}`)}}function a(...R){return n+R.length<=e.length&&R.some((H,re)=>H!==e[n+re].type)}function s(...R){return n+R.length<=e.length&&R.every((H,re)=>H===e[n+re].type)}function o(){return new vy(r(N.Text,"Expected text token").value)}function l(){r(N.OpenStatement,"Expected opening statement token");let R;switch(e[n].type){case N.Set:++n,R=c(),r(N.CloseStatement,"Expected closing statement token");break;case N.If:++n,R=u(),r(N.OpenStatement,"Expected {% token"),r(N.EndIf,"Expected endif token"),r(N.CloseStatement,"Expected %} token");break;case N.For:++n,R=h(),r(N.OpenStatement,"Expected {% token"),r(N.EndFor,"Expected endfor token"),r(N.CloseStatement,"Expected %} token");break;default:throw new SyntaxError(`Unknown statement type: ${e[n].type}`)}return R}function d(){r(N.OpenExpression,"Expected opening expression token");const R=g();return r(N.CloseExpression,"Expected closing expression token"),R}function c(){const R=g();if(s(N.Equals)){++n;const H=c();return new Tk(R,H)}return R}function u(){var L,X,Z,V,ie,xe,Re,He;const R=g();r(N.CloseStatement,"Expected closing statement token");const H=[],re=[];for(;!(((L=e[n])==null?void 0:L.type)===N.OpenStatement&&(((X=e[n+1])==null?void 0:X.type)===N.ElseIf||((Z=e[n+1])==null?void 0:Z.type)===N.Else||((V=e[n+1])==null?void 0:V.type)===N.EndIf));)H.push(i());if(((ie=e[n])==null?void 0:ie.type)===N.OpenStatement&&((xe=e[n+1])==null?void 0:xe.type)!==N.EndIf)if(++n,s(N.ElseIf))r(N.ElseIf,"Expected elseif token"),re.push(u());else for(r(N.Else,"Expected else token"),r(N.CloseStatement,"Expected closing statement token");!(((Re=e[n])==null?void 0:Re.type)===N.OpenStatement&&((He=e[n+1])==null?void 0:He.type)===N.EndIf);)re.push(i());return new _y(R,H,re)}function f(R=!1){const H=R?ue:g,re=[H()],L=s(N.Comma);for(;L&&(++n,re.push(H()),!!s(N.Comma)););return L?new by(re):re[0]}function h(){const R=f(!0);if(!(R instanceof Bi||R instanceof by))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${R.type} instead`);r(N.In,"Expected `in` keyword following loop variable");const H=g();r(N.CloseStatement,"Expected closing statement token");const re=[];for(;a(N.OpenStatement,N.EndFor);)re.push(i());return new Ck(R,H,re)}function g(){return $()}function $(){const R=E();if(s(N.If)){++n;const H=E();r(N.Else,"Expected else token");const re=E();return new _y(H,[R],[re])}return R}function E(){let R=y();for(;s(N.Or);){const H=e[n];++n;const re=y();R=new es(H,R,re)}return R}function y(){let R=_();for(;s(N.And);){const H=e[n];++n;const re=_();R=new es(H,R,re)}return R}function _(){let R;for(;s(N.Not);){const H=e[n];++n;const re=_();R=new Bk(H,re)}return R??v()}function v(){let R=b();for(;s(N.ComparisonBinaryOperator)||s(N.In)||s(N.NotIn);){const H=e[n];++n;const re=b();R=new es(H,R,re)}return R}function b(){let R=z();for(;s(N.AdditiveBinaryOperator);){const H=e[n];++n;const re=z();R=new es(H,R,re)}return R}function C(){const R=G();return s(N.OpenParen)?I(R):R}function I(R){let H=new Ak(R,O());return s(N.OpenParen)&&(H=I(H)),H}function O(){r(N.OpenParen,"Expected opening parenthesis for arguments list");const R=M();return r(N.CloseParen,"Expected closing parenthesis for arguments list"),R}function M(){const R=[];for(;!s(N.CloseParen);){let H=g();if(s(N.Equals)){if(++n,!(H instanceof Bi))throw new SyntaxError("Expected identifier for keyword argument");const re=g();H=new Nk(H,re)}R.push(H),s(N.Comma)&&++n}return R}function W(){const R=[];let H=!1;for(;!s(N.CloseSquareBracket);)s(N.Colon)?(R.push(void 0),++n,H=!0):(R.push(g()),s(N.Colon)&&(++n,H=!0));if(R.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(H){if(R.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new Dk(...R)}return R[0]}function G(){let R=ue();for(;s(N.Dot)||s(N.OpenSquareBracket);){const H=e[n];++n;let re;const L=H.type!==N.Dot;if(L)re=W(),r(N.CloseSquareBracket,"Expected closing square bracket");else if(re=ue(),re.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");R=new Ik(R,re,L)}return R}function z(){let R=K();for(;s(N.MultiplicativeBinaryOperator);){const H=e[n];++n;const re=K();R=new es(H,R,re)}return R}function K(){let R=ae();for(;s(N.Is);){++n;const H=s(N.Not);H&&++n;let re=ue();if(re instanceof $y&&(re=new Bi(re.value.toString())),!(re instanceof Bi))throw new SyntaxError("Expected identifier for the test");R=new Pk(R,H,re)}return R}function ae(){let R=C();for(;s(N.Pipe);){++n;let H=ue();if(!(H instanceof Bi))throw new SyntaxError("Expected identifier for the filter");s(N.OpenParen)&&(H=I(H)),R=new Rk(R,H)}return R}function ue(){const R=e[n];switch(R.type){case N.NumericLiteral:return++n,new Ok(Number(R.value));case N.StringLiteral:return++n,new vy(R.value);case N.BooleanLiteral:return++n,new $y(R.value==="true");case N.Identifier:return++n,new Bi(R.value);case N.OpenParen:{++n;const H=f();if(e[n].type!==N.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${e[n].type} instead`);return++n,H}case N.OpenSquareBracket:{++n;const H=[];for(;!s(N.CloseSquareBracket);)H.push(g()),s(N.Comma)&&++n;return++n,new Mk(H)}case N.OpenCurlyBracket:{++n;const H=new Map;for(;!s(N.CloseCurlyBracket);){const re=g();r(N.Colon,"Expected colon between key and value in object literal");const L=g();H.set(re,L),s(N.Comma)&&++n}return++n,new zk(H)}default:throw new SyntaxError(`Unexpected token: ${R.type}`)}}for(;n=0?(t=(t??(t=0))<0?Math.max(e.length+t,0):Math.min(t,e.length),n=(n??(n=e.length))<0?Math.max(e.length+n,0):Math.min(n,e.length)):(t=(t??(t=e.length-1))<0?Math.max(e.length+t,-1):Math.min(t,e.length-1),n=(n??(n=-1))<-1?Math.max(e.length+n,-1):Math.min(n,e.length-1));const a=[];for(let s=t;i*st.toUpperCase())}var wr=class{constructor(e=void 0){j(this,"type","RuntimeValue");j(this,"value");j(this,"builtins",new Map);this.value=e}__bool__(){return new dt(!!this.value)}},Xe=class extends wr{constructor(){super(...arguments);j(this,"type","NumericValue")}},Pe=class extends wr{constructor(){super(...arguments);j(this,"type","StringValue");j(this,"builtins",new Map([["upper",new dr(()=>new Pe(this.value.toUpperCase()))],["lower",new dr(()=>new Pe(this.value.toLowerCase()))],["strip",new dr(()=>new Pe(this.value.trim()))],["title",new dr(()=>new Pe(f$(this.value)))],["length",new Xe(this.value.length)]]))}},dt=class extends wr{constructor(){super(...arguments);j(this,"type","BooleanValue")}},In=class extends wr{constructor(){super(...arguments);j(this,"type","ObjectValue");j(this,"builtins",new Map([["get",new dr(([t,n])=>{if(!(t instanceof Pe))throw new Error(`Object key must be a string: got ${t.type}`);return this.value.get(t.value)??n??new ws})],["items",new dr(()=>new st(Array.from(this.value.entries()).map(([t,n])=>new st([new Pe(t),n]))))]]))}__bool__(){return new dt(this.value.size>0)}},st=class extends wr{constructor(){super(...arguments);j(this,"type","ArrayValue");j(this,"builtins",new Map([["length",new Xe(this.value.length)]]))}__bool__(){return new dt(this.value.length>0)}},Uk=class extends st{constructor(){super(...arguments);j(this,"type","TupleValue")}},dr=class extends wr{constructor(){super(...arguments);j(this,"type","FunctionValue")}},ws=class extends wr{constructor(){super(...arguments);j(this,"type","NullValue")}},Cn=class extends wr{constructor(){super(...arguments);j(this,"type","UndefinedValue")}},tp=class{constructor(e){j(this,"variables",new Map([["namespace",new dr(e=>{if(e.length===0)return new In(new Map);if(e.length!==1||!(e[0]instanceof In))throw new Error("`namespace` expects either zero arguments or a single object argument");return e[0]})]]));j(this,"tests",new Map([["boolean",e=>e.type==="BooleanValue"],["callable",e=>e instanceof dr],["odd",e=>{if(e.type!=="NumericValue")throw new Error(`Cannot apply test "odd" to type: ${e.type}`);return e.value%2!==0}],["even",e=>{if(e.type!=="NumericValue")throw new Error(`Cannot apply test "even" to type: ${e.type}`);return e.value%2===0}],["false",e=>e.type==="BooleanValue"&&!e.value],["true",e=>e.type==="BooleanValue"&&e.value],["number",e=>e.type==="NumericValue"],["integer",e=>e.type==="NumericValue"&&Number.isInteger(e.value)],["iterable",e=>e instanceof st||e instanceof Pe],["lower",e=>{const t=e.value;return e.type==="StringValue"&&t===t.toLowerCase()}],["upper",e=>{const t=e.value;return e.type==="StringValue"&&t===t.toUpperCase()}],["none",e=>e.type==="NullValue"],["defined",e=>e.type!=="UndefinedValue"],["undefined",e=>e.type==="UndefinedValue"],["equalto",(e,t)=>e.value===t.value]]));this.parent=e}set(e,t){return this.declareVariable(e,_l(t))}declareVariable(e,t){if(this.variables.has(e))throw new SyntaxError(`Variable already declared: ${e}`);return this.variables.set(e,t),t}setVariable(e,t){return this.variables.set(e,t),t}resolve(e){if(this.variables.has(e))return this;if(this.parent)return this.parent.resolve(e);throw new Error(`Unknown variable: ${e}`)}lookupVariable(e){try{return this.resolve(e).variables.get(e)??new Cn}catch{return new Cn}}},Wk=class{constructor(e){j(this,"global");this.global=e??new tp}run(e){return this.evaluate(e,this.global)}evaluateBinaryExpression(e,t){const n=this.evaluate(e.left,t);switch(e.operator.value){case"and":return n.__bool__().value?this.evaluate(e.right,t):n;case"or":return n.__bool__().value?n:this.evaluate(e.right,t)}const r=this.evaluate(e.right,t);switch(e.operator.value){case"==":return new dt(n.value==r.value);case"!=":return new dt(n.value!=r.value)}if(n instanceof Cn||r instanceof Cn)throw new Error("Cannot perform operation on undefined values");if(n instanceof ws||r instanceof ws)throw new Error("Cannot perform operation on null values");if(n instanceof Xe&&r instanceof Xe)switch(e.operator.value){case"+":return new Xe(n.value+r.value);case"-":return new Xe(n.value-r.value);case"*":return new Xe(n.value*r.value);case"/":return new Xe(n.value/r.value);case"%":return new Xe(n.value%r.value);case"<":return new dt(n.value":return new dt(n.value>r.value);case">=":return new dt(n.value>=r.value);case"<=":return new dt(n.value<=r.value)}else if(n instanceof st&&r instanceof st)switch(e.operator.value){case"+":return new st(n.value.concat(r.value))}else if(r instanceof st){const i=r.value.find(a=>a.value===n.value)!==void 0;switch(e.operator.value){case"in":return new dt(i);case"not in":return new dt(!i)}}if(n instanceof Pe||r instanceof Pe)switch(e.operator.value){case"+":return new Pe(n.value.toString()+r.value.toString())}if(n instanceof Pe&&r instanceof Pe)switch(e.operator.value){case"in":return new dt(r.value.includes(n.value));case"not in":return new dt(!r.value.includes(n.value))}if(n instanceof Pe&&r instanceof In)switch(e.operator.value){case"in":return new dt(r.value.has(n.value));case"not in":return new dt(!r.value.has(n.value))}throw new SyntaxError(`Unknown operator "${e.operator.value}" between ${n.type} and ${r.type}`)}evaluateFilterExpression(e,t){const n=this.evaluate(e.operand,t);if(e.filter.type==="Identifier"){const r=e.filter;if(n instanceof st)switch(r.value){case"list":return n;case"first":return n.value[0];case"last":return n.value[n.value.length-1];case"length":return new Xe(n.value.length);case"reverse":return new st(n.value.reverse());case"sort":return new st(n.value.sort((i,a)=>{if(i.type!==a.type)throw new Error(`Cannot compare different types: ${i.type} and ${a.type}`);switch(i.type){case"NumericValue":return i.value-a.value;case"StringValue":return i.value.localeCompare(a.value);default:throw new Error(`Cannot compare type: ${i.type}`)}}));default:throw new Error(`Unknown ArrayValue filter: ${r.value}`)}else if(n instanceof Pe)switch(r.value){case"length":return new Xe(n.value.length);case"upper":return new Pe(n.value.toUpperCase());case"lower":return new Pe(n.value.toLowerCase());case"title":return new Pe(f$(n.value));case"capitalize":return new Pe(n.value.charAt(0).toUpperCase()+n.value.slice(1));case"trim":return new Pe(n.value.trim());default:throw new Error(`Unknown StringValue filter: ${r.value}`)}else if(n instanceof Xe)switch(r.value){case"abs":return new Xe(Math.abs(n.value));default:throw new Error(`Unknown NumericValue filter: ${r.value}`)}else if(n instanceof In)switch(r.value){case"items":return new st(Array.from(n.value.entries()).map(([i,a])=>new st([new Pe(i),a])));case"length":return new Xe(n.value.size);default:throw new Error(`Unknown ObjectValue filter: ${r.value}`)}throw new Error(`Cannot apply filter "${r.value}" to type: ${n.type}`)}else if(e.filter.type==="CallExpression"){const r=e.filter;if(r.callee.type!=="Identifier")throw new Error(`Unknown filter: ${r.callee.type}`);const i=r.callee.value;if(n instanceof st){switch(i){case"selectattr":{if(n.value.some(c=>!(c instanceof In)))throw new Error("`selectattr` can only be applied to array of objects");if(r.args.some(c=>c.type!=="StringLiteral"))throw new Error("arguments of `selectattr` must be strings");const[a,s,o]=r.args.map(c=>this.evaluate(c,t));let l;if(s){const c=t.tests.get(s.value);if(!c)throw new Error(`Unknown test: ${s.value}`);l=c}else l=(...c)=>c[0].__bool__().value;const d=n.value.filter(c=>{const u=c.value.get(a.value);return u?l(u,o):!1});return new st(d)}}throw new Error(`Unknown ArrayValue filter: ${i}`)}else throw new Error(`Cannot apply filter "${i}" to type: ${n.type}`)}throw new Error(`Unknown filter: ${e.filter.type}`)}evaluateTestExpression(e,t){const n=this.evaluate(e.operand,t),r=t.tests.get(e.test.value);if(!r)throw new Error(`Unknown test: ${e.test.value}`);const i=r(n);return new dt(e.negate?!i:i)}evaluateUnaryExpression(e,t){const n=this.evaluate(e.argument,t);switch(e.operator.value){case"not":return new dt(!n.value);default:throw new SyntaxError(`Unknown operator: ${e.operator.value}`)}}evalProgram(e,t){return this.evaluateBlock(e.body,t)}evaluateBlock(e,t){let n="";for(const r of e){const i=this.evaluate(r,t);i.type!=="NullValue"&&i.type!=="UndefinedValue"&&(n+=i.value)}return new Pe(n)}evaluateIdentifier(e,t){return t.lookupVariable(e.value)}evaluateCallExpression(e,t){const n=[],r=new Map;for(const a of e.args)if(a.type==="KeywordArgumentExpression"){const s=a;r.set(s.key.value,this.evaluate(s.value,t))}else n.push(this.evaluate(a,t));r.size>0&&n.push(new In(r));const i=this.evaluate(e.callee,t);if(i.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${i.type}`);return i.value(n,t)}evaluateSliceExpression(e,t,n){if(!(e instanceof st||e instanceof Pe))throw new Error("Slice object must be an array or string");const r=this.evaluate(t.start,n),i=this.evaluate(t.stop,n),a=this.evaluate(t.step,n);if(!(r instanceof Xe||r instanceof Cn))throw new Error("Slice start must be numeric or undefined");if(!(i instanceof Xe||i instanceof Cn))throw new Error("Slice stop must be numeric or undefined");if(!(a instanceof Xe||a instanceof Cn))throw new Error("Slice step must be numeric or undefined");return e instanceof st?new st(xy(e.value,r.value,i.value,a.value)):new Pe(xy(Array.from(e.value),r.value,i.value,a.value).join(""))}evaluateMemberExpression(e,t){const n=this.evaluate(e.object,t);let r;if(e.computed){if(e.property.type==="SliceExpression")return this.evaluateSliceExpression(n,e.property,t);r=this.evaluate(e.property,t)}else r=new Pe(e.property.value);let i;if(n instanceof In){if(!(r instanceof Pe))throw new Error(`Cannot access property with non-string: got ${r.type}`);i=n.value.get(r.value)??n.builtins.get(r.value)}else if(n instanceof st||n instanceof Pe)if(r instanceof Xe)i=n.value.at(r.value),n instanceof Pe&&(i=new Pe(n.value.at(r.value)));else if(r instanceof Pe)i=n.builtins.get(r.value);else throw new Error(`Cannot access property with non-string/non-number: got ${r.type}`);else{if(!(r instanceof Pe))throw new Error(`Cannot access property with non-string: got ${r.type}`);i=n.builtins.get(r.value)}return i instanceof wr?i:new Cn}evaluateSet(e,t){const n=this.evaluate(e.value,t);if(e.assignee.type==="Identifier"){const r=e.assignee.value;t.setVariable(r,n)}else if(e.assignee.type==="MemberExpression"){const r=e.assignee,i=this.evaluate(r.object,t);if(!(i instanceof In))throw new Error("Cannot assign to member of non-object");if(r.property.type!=="Identifier")throw new Error("Cannot assign to member with non-identifier property");i.value.set(r.property.value,n)}else throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(e.assignee)}`);return new ws}evaluateIf(e,t){const n=this.evaluate(e.test,t);return this.evaluateBlock(n.__bool__().value?e.body:e.alternate,t)}evaluateFor(e,t){const n=new tp(t),r=this.evaluate(e.iterable,n);if(!(r instanceof st))throw new Error(`Expected iterable type in for loop: got ${r.type}`);let i="";for(let a=0;a0?r.value[a-1]:new Cn],["nextitem",ac.value.length?"few":"many"} items to unpack`);for(let u=0;uthis.evaluate(n,t)));case"TupleLiteral":return new Uk(e.value.map(n=>this.evaluate(n,t)));case"ObjectLiteral":{const n=new Map;for(const[r,i]of e.value){const a=this.evaluate(r,t);if(!(a instanceof Pe))throw new Error(`Object keys must be strings: got ${a.type}`);n.set(a.value,this.evaluate(i,t))}return new In(n)}case"Identifier":return this.evaluateIdentifier(e,t);case"CallExpression":return this.evaluateCallExpression(e,t);case"MemberExpression":return this.evaluateMemberExpression(e,t);case"UnaryExpression":return this.evaluateUnaryExpression(e,t);case"BinaryExpression":return this.evaluateBinaryExpression(e,t);case"FilterExpression":return this.evaluateFilterExpression(e,t);case"TestExpression":return this.evaluateTestExpression(e,t);default:throw new SyntaxError(`Unknown node type: ${e.type}`)}}};function _l(e){switch(typeof e){case"number":return new Xe(e);case"string":return new Pe(e);case"boolean":return new dt(e);case"object":return e===null?new ws:Array.isArray(e)?new st(e.map(_l)):new In(new Map(Object.entries(e).map(([t,n])=>[t,_l(n)])));case"function":return new dr((t,n)=>{const r=e(...t.map(i=>i.value))??null;return _l(r)});default:throw new Error(`Cannot convert to runtime value: ${e}`)}}var Vk=class{constructor(e){j(this,"parsed");const t=Ek(e,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=Lk(t)}render(e){const t=new tp;t.set("false",!1),t.set("true",!0),t.set("raise_exception",i=>{throw new Error(i)}),t.set("range",Fk);for(const[i,a]of Object.entries(e))t.set(i,a);return new Wk(t).run(this.parsed).value}};async function h$(e,t){const n=await Promise.all([di(e,"tokenizer.json",!0,t),di(e,"tokenizer_config.json",!0,t)]);return t.legacy!==null&&(n[1].legacy=t.legacy),n}function jk(e,t){const n=[];let r=0;for(const i of e.matchAll(t)){const a=i[0];r0&&n.push(a),r=i.index+a.length}return rthis.tokens_to_ids.get(n)??this.unk_token_id)}convert_ids_to_tokens(t){return t.map(n=>this.vocab[n]??this.unk_token)}}class Qk extends Ys{constructor(t){super(t),this.tokens_to_ids=Sf(t.vocab),this.unk_token_id=this.tokens_to_ids.get(t.unk_token),this.unk_token=t.unk_token,this.max_input_chars_per_word=t.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(const[n,r]of this.tokens_to_ids)this.vocab[r]=n}encode(t){const n=[];for(const r of t){const i=[...r];if(i.length>this.max_input_chars_per_word){n.push(this.unk_token);continue}let a=!1,s=0;const o=[];for(;s0&&(c=this.config.continuing_subword_prefix+c),this.tokens_to_ids.has(c)){d=c;break}--l}if(d===null){a=!0;break}o.push(d),s=l}a?n.push(this.unk_token):n.push(...o)}return n}}class Xk extends Ys{constructor(t,n){super(t);const r=t.vocab.length;this.vocab=new Array(r),this.scores=new Array(r);for(let i=0;i[i,a])),this.bosToken=" ",this.bosTokenId=this.tokens_to_ids.get(this.bosToken),this.eosToken=n.eos_token,this.eosTokenId=this.tokens_to_ids.get(this.eosToken),this.unkToken=this.vocab[this.unk_token_id],this.minScore=MS(this.scores)[0],this.unkScore=this.minScore-10,this.scores[this.unk_token_id]=this.unkScore,this.trie=new vk,this.trie.extend(this.vocab),this.fuse_unk=!0}populateNodes(t){const n=t.sentence,r=n.length;let i=0;for(;i{const e=[...Array.from({length:94},(i,a)=>a+33),...Array.from({length:12},(i,a)=>a+161),...Array.from({length:82},(i,a)=>a+174)],t=e.slice();let n=0;for(let i=0;i<256;++i)e.includes(i)||(e.push(i),t.push(256+n),n+=1);const r=t.map(i=>String.fromCharCode(i));return Object.fromEntries(e.map((i,a)=>[i,r[a]]))})(),Zk=ES(y$);class Jk extends Ys{constructor(t){super(t),this.BPE_SPLIT_TOKEN=" ",this.tokens_to_ids=Sf(t.vocab),this.unk_token_id=this.tokens_to_ids.get(t.unk_token),this.unk_token=t.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(const[n,r]of this.tokens_to_ids)this.vocab[r]=n;this.bpe_ranks=new Map(t.merges.map((n,r)=>[n,r])),this.merges=t.merges.map(n=>n.split(this.BPE_SPLIT_TOKEN)),this.end_of_word_suffix=t.end_of_word_suffix,this.continuing_subword_suffix=t.continuing_subword_suffix??null,this.byte_fallback=this.config.byte_fallback??!1,this.byte_fallback&&(this.text_encoder=new TextEncoder),this.cache=new Map}bpe(t){if(t.length===0)return[];const n=this.cache.get(t);if(n!==void 0)return n;const r=Array.from(t);this.end_of_word_suffix&&(r[r.length-1]+=this.end_of_word_suffix);let i=[];if(r.length>1){const a=new _k((l,d)=>l.score`<0x${s.toString(16).toUpperCase().padStart(2,"0")}>`)):n.push(this.unk_token)}return n}}class eC extends Ys{constructor(t,n){super(t),this.tokens_to_ids=Sf(n.target_lang?t.vocab[n.target_lang]:t.vocab),this.bos_token=n.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=n.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=n.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=n.unk_token,this.unk_token_id=this.tokens_to_ids.get(this.unk_token),this.vocab=new Array(this.tokens_to_ids.size);for(const[r,i]of this.tokens_to_ids)this.vocab[i]=r}encode(t){return t}}class sn extends dn{constructor(t){super(),this.config=t}static fromConfig(t){if(t===null)return null;switch(t.type){case"BertNormalizer":return new dC(t);case"Precompiled":return new IC(t);case"Sequence":return new uC(t);case"Replace":return new tC(t);case"NFC":return new nC(t);case"NFKC":return new rC(t);case"NFKD":return new iC(t);case"Strip":return new aC(t);case"StripAccents":return new sC(t);case"Lowercase":return new oC(t);case"Prepend":return new lC(t);default:throw new Error(`Unknown Normalizer type: ${t.type}`)}}normalize(t){throw Error("normalize should be implemented in subclass.")}_call(t){return this.normalize(t)}}class tC extends sn{normalize(t){const n=Su(this.config.pattern);return n===null?t:t.replaceAll(n,this.config.content)}}class nC extends sn{normalize(t){return t=t.normalize("NFC"),t}}class rC extends sn{normalize(t){return t=t.normalize("NFKC"),t}}class iC extends sn{normalize(t){return t=t.normalize("NFKD"),t}}class aC extends sn{normalize(t){return this.config.strip_left&&this.config.strip_right?t=t.trim():(this.config.strip_left&&(t=t.trimStart()),this.config.strip_right&&(t=t.trimEnd())),t}}class sC extends sn{normalize(t){return t=g$(t),t}}class oC extends sn{normalize(t){return t=t.toLowerCase(),t}}class lC extends sn{normalize(t){return t=this.config.prepend+t,t}}class uC extends sn{constructor(t){super(t),this.normalizers=t.normalizers.map(n=>sn.fromConfig(n))}normalize(t){return this.normalizers.reduce((n,r)=>r.normalize(n),t)}}class dC extends sn{_tokenize_chinese_chars(t){const n=[];for(let r=0;r=19968&&t<=40959||t>=13312&&t<=19903||t>=131072&&t<=173791||t>=173824&&t<=177983||t>=177984&&t<=178207||t>=178208&&t<=183983||t>=63744&&t<=64255||t>=194560&&t<=195103}stripAccents(t){return t.normalize("NFD").replace(/[\u0300-\u036f]/g,"")}_is_control(t){switch(t){case" ":case` `:case"\r":return!1;default:return new RegExp("^\\p{Cc}|\\p{Cf}|\\p{Co}|\\p{Cs}$","u").test(t)}}_clean_text(t){const n=[];for(const r of t){const i=r.charCodeAt(0);i===0||i===65533||this._is_control(r)||(/^\s$/.test(r)?n.push(" "):n.push(r))}return n.join("")}normalize(t){return this.config.clean_text&&(t=this._clean_text(t)),this.config.handle_chinese_chars&&(t=this._tokenize_chinese_chars(t)),this.config.lowercase?(t=t.toLowerCase(),this.config.strip_accents!==!1&&(t=this.stripAccents(t))):this.config.strip_accents&&(t=this.stripAccents(t)),t}}class _n extends dn{static fromConfig(t){if(t===null)return null;switch(t.type){case"BertPreTokenizer":return new cC(t);case"Sequence":return new AC(t);case"Whitespace":return new OC(t);case"WhitespaceSplit":return new MC(t);case"Metaspace":return new v$(t);case"ByteLevel":return new pC(t);case"Split":return new fC(t);case"Punctuation":return new hC(t);case"Digits":return new mC(t);case"Replace":return new zC(t);default:throw new Error(`Unknown PreTokenizer type: ${t.type}`)}}pre_tokenize_text(t,n){throw Error("pre_tokenize_text should be implemented in subclass.")}pre_tokenize(t,n){return(Array.isArray(t)?t.map(r=>this.pre_tokenize_text(r,n)):this.pre_tokenize_text(t,n)).flat()}_call(t,n){return this.pre_tokenize(t,n)}}class cC extends _n{constructor(t){super(),this.pattern=new RegExp(`[^\\s${Ls}]+|[${Ls}]`,"gu")}pre_tokenize_text(t,n){return t.trim().match(this.pattern)||[]}}class pC extends _n{constructor(t){super(),this.config=t,this.add_prefix_space=this.config.add_prefix_space,this.trim_offsets=this.config.trim_offsets,this.use_regex=this.config.use_regex??!0,this.pattern=new RegExp("'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)|\\s+","gu"),this.byte_encoder=y$,this.text_encoder=new TextEncoder}pre_tokenize_text(t,n){return this.add_prefix_space&&!t.startsWith(" ")&&(t=" "+t),(this.use_regex?t.match(this.pattern)||[]:[t]).map(i=>Array.from(this.text_encoder.encode(i),a=>this.byte_encoder[a]).join(""))}}class fC extends _n{constructor(t){super(),this.config=t,this.pattern=Su(this.config.pattern,this.config.invert)}pre_tokenize_text(t,n){return this.pattern===null?[]:this.config.invert?t.match(this.pattern)||[]:jk(t,this.pattern)}}class hC extends _n{constructor(t){super(),this.config=t,this.pattern=new RegExp(`[^${Ls}]+|[${Ls}]+`,"gu")}pre_tokenize_text(t,n){return t.match(this.pattern)||[]}}class mC extends _n{constructor(t){super(),this.config=t;const n=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(n,"gu")}pre_tokenize_text(t,n){return t.match(this.pattern)||[]}}class Eu extends dn{constructor(t){super(),this.config=t}static fromConfig(t){if(t===null)return null;switch(t.type){case"TemplateProcessing":return new gC(t);case"ByteLevel":return new yC(t);case"RobertaProcessing":return new _$(t);case"BertProcessing":return new w$(t);default:throw new Error(`Unknown PostProcessor type: ${t.type}`)}}post_process(t,...n){throw Error("post_process should be implemented in subclass.")}_call(t,...n){return this.post_process(t,...n)}}class w$ extends Eu{constructor(t){super(t),this.cls=t.cls[0],this.sep=t.sep[0]}post_process(t,n=null,{add_special_tokens:r=!0}={}){r&&(t=kt([this.cls],t,[this.sep]));let i=new Array(t.length).fill(0);if(n!==null){const a=r&&this instanceof _$?[this.sep]:[],s=r?[this.sep]:[];t=kt(t,a,n,s),i=kt(i,new Array(n.length+a.length+s.length).fill(1))}return{tokens:t,token_type_ids:i}}}class _$ extends w${}class gC extends Eu{constructor(t){super(t),this.single=t.single,this.pair=t.pair}post_process(t,n=null,{add_special_tokens:r=!0}={}){const i=n===null?this.single:this.pair;let a=[],s=[];for(const o of i)"SpecialToken"in o?r&&(a.push(o.SpecialToken.id),s.push(o.SpecialToken.type_id)):"Sequence"in o&&(o.Sequence.id==="A"?(a=kt(a,t),s=kt(s,new Array(t.length).fill(o.Sequence.type_id))):o.Sequence.id==="B"&&(a=kt(a,n),s=kt(s,new Array(n.length).fill(o.Sequence.type_id))));return{tokens:a,token_type_ids:s}}}class yC extends Eu{post_process(t,n=null){return n&&(t=kt(t,n)),{tokens:t}}}class on extends dn{constructor(t){super(),this.config=t,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets=t.trim_offsets}static fromConfig(t){if(t===null)return null;switch(t.type){case"WordPiece":return new bC(t);case"Metaspace":return new TC(t);case"ByteLevel":return new xC(t);case"Replace":return new wC(t);case"ByteFallback":return new _C(t);case"Fuse":return new vC(t);case"Strip":return new $C(t);case"Sequence":return new EC(t);case"CTC":return new SC(t);case"BPEDecoder":return new kC(t);default:throw new Error(`Unknown Decoder type: ${t.type}`)}}_call(t){return this.decode(t)}decode(t){return this.decode_chain(t).join("")}decode_chain(t){throw Error("`decode_chain` should be implemented in subclass.")}}class wC extends on{decode_chain(t){const n=Su(this.config.pattern);return n===null?t:t.map(r=>r.replaceAll(n,this.config.content))}}class _C extends on{constructor(t){super(t),this.text_decoder=new TextDecoder}decode_chain(t){const n=[];let r=[];for(const i of t){let a=null;if(i.length===6&&i.startsWith("<0x")&&i.endsWith(">")){const s=parseInt(i.slice(3,5),16);isNaN(s)||(a=s)}if(a!==null)r.push(a);else{if(r.length>0){const s=this.text_decoder.decode(Uint8Array.from(r));n.push(s),r=[]}n.push(i)}}if(r.length>0){const i=this.text_decoder.decode(Uint8Array.from(r));n.push(i),r=[]}return n}}class vC extends on{decode_chain(t){return[t.join("")]}}class $C extends on{constructor(t){super(t),this.content=this.config.content,this.start=this.config.start,this.stop=this.config.stop}decode_chain(t){return t.map(n=>{let r=0;for(let a=0;a(r!==0&&(n.startsWith(this.config.prefix)?n=n.replace(this.config.prefix,""):n=" "+n),this.cleanup&&(n=Ef(n)),n))}}class xC extends on{constructor(t){super(t),this.byte_decoder=Zk,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(t){const n=t.join(""),r=new Uint8Array([...n].map(a=>this.byte_decoder[a]));return this.text_decoder.decode(r)}decode_chain(t){const n=[];let r=[];for(const i of t)this.added_tokens.find(a=>a.content===i)!==void 0?(r.length>0&&(n.push(this.convert_tokens_to_string(r)),r=[]),n.push(i)):r.push(i);return r.length>0&&n.push(this.convert_tokens_to_string(r)),n}}class SC extends on{constructor(t){super(t),this.pad_token=this.config.pad_token,this.word_delimiter_token=this.config.word_delimiter_token,this.cleanup=this.config.cleanup}convert_tokens_to_string(t){if(t.length===0)return"";const n=[t[0]];for(let a=1;aa!==this.pad_token).join("");return this.cleanup&&(i=Ef(i).replaceAll(this.word_delimiter_token," ").trim()),i}decode_chain(t){return[this.convert_tokens_to_string(t)]}}class EC extends on{constructor(t){super(t),this.decoders=t.decoders.map(n=>on.fromConfig(n))}decode_chain(t){return this.decoders.reduce((n,r)=>r.decode_chain(n),t)}}class kC extends on{constructor(t){super(t),this.suffix=this.config.suffix}decode_chain(t){return t.map((n,r)=>n.replaceAll(this.suffix,r===t.length-1?"":" "))}}class CC extends on{decode_chain(t){let n="";for(let r=1;rr.normalize("NFKC")).join("~"):t=t.normalize("NFKC"),t}}class AC extends _n{constructor(t){super(),this.tokenizers=t.pretokenizers.map(n=>_n.fromConfig(n))}pre_tokenize_text(t,n){return this.tokenizers.reduce((r,i)=>i.pre_tokenize(r,n),[t])}}class OC extends _n{constructor(t){super()}pre_tokenize_text(t,n){return t.match(/\w+|[^\w\s]+/g)||[]}}class MC extends _n{constructor(t){super()}pre_tokenize_text(t,n){return qk(t)}}class zC extends _n{constructor(t){super(),this.config=t,this.pattern=Su(this.config.pattern),this.content=this.config.content}pre_tokenize_text(t,n){return this.pattern===null?[t]:[t.replaceAll(this.pattern,this.config.content)]}}const RC=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function PC(e,t,n,r){for(const i of Object.keys(e)){const a=t-e[i].length,s=n(i),o=new Array(a).fill(s);e[i]=r==="right"?kt(e[i],o):kt(o,e[i])}}function BC(e,t){for(const n of Object.keys(e))e[n].length=t}class Te extends dn{constructor(n,r){super();j(this,"return_token_type_ids",!1);j(this,"_default_chat_template",`{% for message in messages %}{{'<|im_start|>' + message['role'] + ' ' + message['content'] + '<|im_end|>' + ' '}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant ' }}{% endif %}`);j(this,"padding_side","right");this._tokenizer_config=r,this.normalizer=sn.fromConfig(n.normalizer),this.pre_tokenizer=_n.fromConfig(n.pre_tokenizer),this.model=Ys.fromConfig(n.model,r),this.post_processor=Eu.fromConfig(n.post_processor),this.decoder=on.fromConfig(n.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];for(const i of n.added_tokens){const a=new Yk(i);this.added_tokens.push(a),this.model.tokens_to_ids.set(a.content,a.id),this.model.vocab[a.id]=a.content,a.special&&(this.special_tokens.push(a.content),this.all_special_ids.push(a.id))}if(this.additional_special_tokens=r.additional_special_tokens??[],this.special_tokens.push(...this.additional_special_tokens),this.special_tokens=[...new Set(this.special_tokens)],this.decoder&&(this.decoder.added_tokens=this.added_tokens,this.decoder.end_of_word_suffix=this.model.end_of_word_suffix),this.added_tokens_regex=this.added_tokens.length>0?new RegExp(this.added_tokens.map(i=>`${i.lstrip?"\\s*":""}(${K_(i.content)})${i.rstrip?"\\s*":""}`).join("|")):null,this.mask_token=this.getToken("mask_token"),this.mask_token_id=this.model.tokens_to_ids.get(this.mask_token),this.pad_token=this.getToken("pad_token","eos_token"),this.pad_token_id=this.model.tokens_to_ids.get(this.pad_token),this.sep_token=this.getToken("sep_token"),this.sep_token_id=this.model.tokens_to_ids.get(this.sep_token),this.unk_token=this.getToken("unk_token"),this.unk_token_id=this.model.tokens_to_ids.get(this.unk_token),this.model_max_length=r.model_max_length,this.remove_space=r.remove_space,this.clean_up_tokenization_spaces=r.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=r.do_lowercase_and_remove_accent??!1,r.padding_side&&(this.padding_side=r.padding_side),this.legacy=!1,this.chat_template=r.chat_template??null,Array.isArray(this.chat_template)){const i=Object.create(null);for(const{name:a,template:s}of this.chat_template){if(typeof a!="string"||typeof s!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');i[a]=s}this.chat_template=i}this._compiled_template_cache=new Map}getToken(...n){for(const r of n){const i=this._tokenizer_config[r];if(i)if(typeof i=="object"){if(i.__type==="AddedToken")return i.content;throw Error(`Unknown token: ${i}`)}else return i}return null}static async from_pretrained(n,{progress_callback:r=null,config:i=null,cache_dir:a=null,local_files_only:s=!1,revision:o="main",legacy:l=null}={}){const d=await h$(n,{progress_callback:r,config:i,cache_dir:a,local_files_only:s,revision:o,legacy:l});return new this(...d)}_call(n,{text_pair:r=null,add_special_tokens:i=!0,padding:a=!1,truncation:s=null,max_length:o=null,return_tensor:l=!0}={}){const d=Array.isArray(n);let c;if(d){if(n.length===0)throw Error("text array must be non-empty");if(r!==null){if(Array.isArray(r)){if(n.length!==r.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");c=n.map((f,h)=>this._encode_plus(f,{text_pair:r[h],add_special_tokens:i}))}else c=n.map(f=>this._encode_plus(f,{add_special_tokens:i}))}else{if(n==null)throw Error("text may not be null or undefined");if(Array.isArray(r))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");c=[this._encode_plus(n,{text_pair:r,add_special_tokens:i})]}if(o===null?a==="max_length"?o=this.model_max_length:o=Zp(c.map(f=>f.input_ids.length))[0]:s||console.warn("Truncation was not explicitly activated but `max_length` is provided a specific value, please use `truncation=true` to explicitly truncate examples to max length."),o=Math.min(o,this.model_max_length),a||s)for(let f=0;fo?s&&BC(c[f],o):a&&PC(c[f],o,h=>h==="input_ids"?this.pad_token_id:0,this.padding_side));const u={};if(l){if(!(a&&s)&&c.some(h=>{var g;for(const $ of Object.keys(h))if(h[$].length!==((g=c[0][$])==null?void 0:g.length))return!0;return!1}))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=true' and 'truncation=true' to have batched tensors with the same length.");const f=[c.length,c[0].input_ids.length];for(const h of Object.keys(c[0]))u[h]=new _e("int64",BigInt64Array.from(c.flatMap(g=>g[h]).map(BigInt)),f)}else{for(const f of Object.keys(c[0]))u[f]=c.map(h=>h[f]);if(!d)for(const f of Object.keys(u))u[f]=u[f][0]}return u}_encode_text(n){return n===null?null:(this.added_tokens_regex?n.split(this.added_tokens_regex).filter(a=>a):[n]).map((a,s)=>{if(this.added_tokens.find(l=>l.content===a)!==void 0)return a;{if(this.remove_space===!0&&(a=a.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(a=Gk(a)),this.normalizer!==null&&(a=this.normalizer(a)),a.length===0)return[];const l=this.pre_tokenizer!==null?this.pre_tokenizer(a,{section_index:s}):[a];return this.model(l)}}).flat()}_encode_plus(n,{text_pair:r=null,add_special_tokens:i=!0}={}){const{tokens:a,token_type_ids:s}=this._tokenize_helper(n,{pair:r,add_special_tokens:i}),o=this.model.convert_tokens_to_ids(a),l={input_ids:o,attention_mask:new Array(o.length).fill(1)};return this.return_token_type_ids&&s&&(l.token_type_ids=s),l}_tokenize_helper(n,{pair:r=null,add_special_tokens:i=!1}={}){const a=this._encode_text(n),s=this._encode_text(r);return this.post_processor?this.post_processor(a,s,{add_special_tokens:i}):{tokens:kt(a??[],s??[])}}tokenize(n,{pair:r=null,add_special_tokens:i=!1}={}){return this._tokenize_helper(n,{pair:r,add_special_tokens:i}).tokens}encode(n,{text_pair:r=null,add_special_tokens:i=!0}={}){return this._encode_plus(n,{text_pair:r,add_special_tokens:i}).input_ids}batch_decode(n,r={}){return n instanceof _e&&(n=n.tolist()),n.map(i=>this.decode(i,r))}decode(n,r={}){if(n instanceof _e&&(n=m$(n)),!Array.isArray(n)||n.length===0||!kS(n[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(n,r)}decode_single(n,{skip_special_tokens:r=!1,clean_up_tokenization_spaces:i=null}){let a=this.model.convert_ids_to_tokens(n);r&&(a=a.filter(o=>!this.special_tokens.includes(o)));let s=this.decoder?this.decoder(a):a.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(s=s.replaceAll(this.decoder.end_of_word_suffix," "),r&&(s=s.trim())),(i??this.clean_up_tokenization_spaces)&&(s=Ef(s)),s}get default_chat_template(){return this._warned_about_chat_template||(console.warn("No chat template is defined for this tokenizer - using a default chat template that implements the ChatML format. If the default is not appropriate for your model, please set `tokenizer.chat_template` to an appropriate template. See https://huggingface.co/docs/transformers/main/chat_templating for more information."),this._warned_about_chat_template=!0),this._default_chat_template}apply_chat_template(n,{chat_template:r=null,add_generation_prompt:i=!1,tokenize:a=!0,padding:s=!1,truncation:o=!1,max_length:l=null,return_tensor:d=!0,tokenizer_kwargs:c={},...u}={}){if(this.chat_template&&typeof this.chat_template=="object"||this.chat_template===null&&this.default_chat_template&&typeof this.default_chat_template=="object"){const $=this.chat_template??this.default_chat_template;if(r!==null&&Object.hasOwn($,r))r=$[r];else if(r===null&&"default"in $)r=$.default;else if(r===null)throw Error(`This model has multiple chat templates with no default specified! Please either pass a chat template or the name of the template you wish to use to the 'chat_template' argument. Available template names are ${Object.keys($).sort()}.`)}else r??(r=this.chat_template??this.default_chat_template);if(typeof r!="string")throw Error(`chat_template must be a string, but got ${typeof r}`);let f=this._compiled_template_cache.get(r);f===void 0&&(f=new Vk(r),this._compiled_template_cache.set(r,f));const h=Object.create(null);for(const $ of RC){const E=this.getToken($);E&&(h[$]=E)}const g=f.render({messages:n,add_generation_prompt:i,...h,...u});return a?this._call(g,{add_special_tokens:!1,padding:s,truncation:o,max_length:l,return_tensor:d,...c}).input_ids:g}}class DC extends Te{constructor(){super(...arguments);j(this,"return_token_type_ids",!0)}}class NC extends Te{constructor(){super(...arguments);j(this,"return_token_type_ids",!0)}}class LC extends Te{constructor(){super(...arguments);j(this,"return_token_type_ids",!0)}}class FC extends Te{constructor(){super(...arguments);j(this,"return_token_type_ids",!0)}}class UC extends Te{constructor(){super(...arguments);j(this,"return_token_type_ids",!0)}}class WC extends Te{constructor(){super(...arguments);j(this,"return_token_type_ids",!0)}}class VC extends Te{constructor(){super(...arguments);j(this,"return_token_type_ids",!0)}}class jC extends Te{constructor(){super(...arguments);j(this,"return_token_type_ids",!0)}}class GC extends Te{constructor(){super(...arguments);j(this,"return_token_type_ids",!0)}}class HC extends Te{}class qC extends Te{}class KC extends Te{constructor(n,r){super(n,r);j(this,"return_token_type_ids",!0);console.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}}class YC extends Te{constructor(){super(...arguments);j(this,"return_token_type_ids",!0)}}class QC extends Te{}class $$ extends Te{constructor(){super(...arguments);j(this,"_default_chat_template",'{% for message in messages %}" "{{ message.content }}{{ eos_token }}" "{% endfor %}')}}class XC extends Te{}class b$ extends Te{constructor(t,n){super(t,n),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.special_tokens.filter(r=>this.languageRegex.test(r)),this.lang_to_token=r=>r}_build_translation_inputs(t,n,r){return kf(this,t,n,r)}}class ZC extends b${}class JC extends Te{}class eT extends $${constructor(t,n){var a,s;const r=".,!?…。,、।۔،",i=(s=(a=t.pre_tokenizer)==null?void 0:a.pretokenizers[0])==null?void 0:s.pattern;i&&i.Regex===` ?[^(\\s|[${r}])]+`&&(i.Regex=` ?[^\\s${r}]+`),super(t,n)}}const Jo="▁";class x$ extends Te{constructor(n,r){super(n,r);j(this,"_default_chat_template",`{% if messages[0]['role'] == 'system' %}{% set loop_messages = messages[1:] %}{% set system_message = messages[0]['content'] %}{% elif USE_DEFAULT_PROMPT == true and not '<>' in messages[0]['content'] %}{% set loop_messages = messages %}{% set system_message = 'DEFAULT_SYSTEM_MESSAGE' %}{% else %}{% set loop_messages = messages %}{% set system_message = false %}{% endif %}{% for message in loop_messages %}{% if (message['role'] == 'user') != (loop.index0 % 2 == 0) %}{{ raise_exception('Conversation roles must alternate user/assistant/user/assistant/...') }}{% endif %}{% if loop.index0 == 0 and system_message != false %}{% set content = '<> ' + system_message + ' <> ' + message['content'] %}{% else %}{% set content = message['content'] %}{% endif %}{% if message['role'] == 'user' %}{{ bos_token + '[INST] ' + content.strip() + ' [/INST]' }}{% elif message['role'] == 'system' %}{{ '<> ' + content.strip() + ' <> ' }}{% elif message['role'] == 'assistant' %}{{ ' ' + content.strip() + ' ' + eos_token }}{% endif %}{% endfor %}`);j(this,"DEFAULT_SYSTEM_PROMPT",`You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure that your responses are socially unbiased and positive in nature. If a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information.`);j(this,"padding_side","left");this.use_default_system_prompt=r.use_default_system_prompt??!1,this.legacy=r.legacy??!0,this.legacy||(this.normalizer=null,this.pre_tokenizer=new v$({replacement:Jo,add_prefix_space:!0,prepend_scheme:"first"}))}_encode_text(n){if(n===null)return null;if(this.legacy||n.length===0)return super._encode_text(n);let r=super._encode_text(Jo+n.replaceAll(Jo," "));return r.length>1&&r[0]===Jo&&this.special_tokens.includes(r[1])&&(r=r.slice(1)),r}get default_chat_template(){return super.default_chat_template.replaceAll("USE_DEFAULT_PROMPT",this.use_default_system_prompt?"true":"false").replaceAll("DEFAULT_SYSTEM_MESSAGE",this.DEFAULT_SYSTEM_PROMPT.replaceAll(` `,"\\n").replaceAll("'","\\'"))}}class tT extends x${}class nT extends Te{}class rT extends Te{}class iT extends Te{}class aT extends Te{}class sT extends Te{}class oT extends Te{}class lT extends Te{constructor(){super(...arguments);j(this,"_default_chat_template",`{% if messages[0]['role'] == 'system' %}{{ raise_exception('System role not supported') }}{% endif %}{% for message in messages %}{% if (message['role'] == 'user') != (loop.index0 % 2 == 0) %}{{ raise_exception('Conversation roles must alternate user/assistant/user/assistant/...') }}{% endif %}{% if (message['role'] == 'assistant') %}{% set role = 'model' %}{% else %}{% set role = message['role'] %}{% endif %}{{ '' + role + ' ' + message['content'] | trim + ' ' }}{% endfor %}{% if add_generation_prompt %}{{'model '}}{% endif %}`)}}class uT extends Te{}function kf(e,t,n,r){if(!("language_codes"in e)||!Array.isArray(e.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in e)||!(e.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in e)||typeof e.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");const i=r.src_lang,a=r.tgt_lang;if(!e.language_codes.includes(a))throw new Error(`Target language code "${a}" is not valid. Must be one of: {${e.language_codes.join(", ")}}`);if(i!==void 0){if(!e.language_codes.includes(i))throw new Error(`Source language code "${i}" is not valid. Must be one of: {${e.language_codes.join(", ")}}`);for(const s of e.post_processor.config.single)if("SpecialToken"in s&&e.languageRegex.test(s.SpecialToken.id)){s.SpecialToken.id=e.lang_to_token(i);break}}return r.forced_bos_token_id=e.model.convert_tokens_to_ids([e.lang_to_token(a)])[0],e._call(t,n)}class dT extends Te{constructor(t,n){super(t,n),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.special_tokens.filter(r=>this.languageRegex.test(r)),this.lang_to_token=r=>r}_build_translation_inputs(t,n,r){return kf(this,t,n,r)}}class cT extends Te{constructor(t,n){super(t,n),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.special_tokens.filter(r=>this.languageRegex.test(r)).map(r=>r.slice(2,-2)),this.lang_to_token=r=>`__${r}__`}_build_translation_inputs(t,n,r){return kf(this,t,n,r)}}const S$=[["en","english"],["zh","chinese"],["de","german"],["es","spanish"],["ru","russian"],["ko","korean"],["fr","french"],["ja","japanese"],["pt","portuguese"],["tr","turkish"],["pl","polish"],["ca","catalan"],["nl","dutch"],["ar","arabic"],["sv","swedish"],["it","italian"],["id","indonesian"],["hi","hindi"],["fi","finnish"],["vi","vietnamese"],["he","hebrew"],["uk","ukrainian"],["el","greek"],["ms","malay"],["cs","czech"],["ro","romanian"],["da","danish"],["hu","hungarian"],["ta","tamil"],["no","norwegian"],["th","thai"],["ur","urdu"],["hr","croatian"],["bg","bulgarian"],["lt","lithuanian"],["la","latin"],["mi","maori"],["ml","malayalam"],["cy","welsh"],["sk","slovak"],["te","telugu"],["fa","persian"],["lv","latvian"],["bn","bengali"],["sr","serbian"],["az","azerbaijani"],["sl","slovenian"],["kn","kannada"],["et","estonian"],["mk","macedonian"],["br","breton"],["eu","basque"],["is","icelandic"],["hy","armenian"],["ne","nepali"],["mn","mongolian"],["bs","bosnian"],["kk","kazakh"],["sq","albanian"],["sw","swahili"],["gl","galician"],["mr","marathi"],["pa","punjabi"],["si","sinhala"],["km","khmer"],["sn","shona"],["yo","yoruba"],["so","somali"],["af","afrikaans"],["oc","occitan"],["ka","georgian"],["be","belarusian"],["tg","tajik"],["sd","sindhi"],["gu","gujarati"],["am","amharic"],["yi","yiddish"],["lo","lao"],["uz","uzbek"],["fo","faroese"],["ht","haitian creole"],["ps","pashto"],["tk","turkmen"],["nn","nynorsk"],["mt","maltese"],["sa","sanskrit"],["lb","luxembourgish"],["my","myanmar"],["bo","tibetan"],["tl","tagalog"],["mg","malagasy"],["as","assamese"],["tt","tatar"],["haw","hawaiian"],["ln","lingala"],["ha","hausa"],["ba","bashkir"],["jw","javanese"],["su","sundanese"]],el=new Map(S$),pT=new Map([...S$.map(([e,t])=>[t,e]),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);class fT extends Te{constructor(){super(...arguments);j(this,"_default_chat_template",'{% for message in messages %}" "{{ message.content }}{{ eos_token }}" "{% endfor %}')}_decode_asr(n,{return_timestamps:r=!1,return_language:i=!1,time_precision:a=null,force_full_sequences:s=!0}={}){if(a===null)throw Error("Must specify time_precision");let o=null;const l=r==="word";function d(){return{language:o,timestamp:[null,null],text:""}}const c=[];let u=d(),f=0;const h=this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0]+1;let g=[],$=[],E=!1,y=null;const _=new Set(this.all_special_ids);for(const C of n){const I=C.tokens,O=l?C.token_timestamps:null;let M=null,W=h;if("stride"in C){const[K,ae,ue]=C.stride;if(f-=ae,y=K-ue,ae&&(W=ae/a+h),ue)for(let R=I.length-1;R>=0;--R){const H=I[R];if(H>=h){if(M!==null&&(H-h)*a=h){const ue=(ae-h)*a+f,R=jo(ue,2);if(M!==null&&ae>=M)E=!0;else if(E||g.length>0&&ae0?(g.push(G),l&&$.push(z)):g.every(K=>K.length===0)&&(u=d(),g=[],G=[],$=[],z=[])}if(g.length>0){if(s&&r)throw new Error("Whisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. Also make sure WhisperTimeStampLogitsProcessor was used during generation.");const[C,I]=this.findLongestCommonSequence(g,$),O=this.decode(C);u.text=O,l&&(u.words=this.collateWordTimestamps(C,I,o)),c.push(u)}let v=Object.create(null);const b=c.map(C=>C.text).join("");if(r||i){for(let C=0;C0;let l=o?[]:null,d=o?r[0]:null;for(let c=1;cR===K[H]).length,ue=ae/C+I;ae>1&&ue>f&&(f=ue,h=[O,M,G,z])}const[$,E,y,_]=h,v=Math.floor((E+$)/2),b=Math.floor((_+y)/2);s.push(...i.slice(0,v)),i=u.slice(b),a=i.length,o&&(l.push(...d.slice(0,v)),d=r[c].slice(b))}return s.push(...i),o?(l.push(...d),[s,l]):[s,[]]}collateWordTimestamps(n,r,i){const[a,s,o]=this.combineTokensIntoWords(n,i),l=[];for(let d=0;d=a){const l=jo((o-a)*i,2);s.push(`<|${l}|>`),s.push([])}else s[s.length-1].push(o);return s=s.map(o=>typeof o=="string"?o:super.decode(o,r)),s.join("")}splitTokensOnUnicode(n){const r=this.decode(n,{decode_with_timestamps:!0}),i="�",a=[],s=[],o=[];let l=[],d=[],c=0;for(let u=0;u=this.model.tokens_to_ids.get("<|endoftext|>"),$=u.startsWith(" "),E=u.trim(),y=d.test(E);if(g||$||y||s.length===0)s.push(u),o.push(f),l.push(h);else{const _=s.length-1;s[_]+=u,o[_].push(...f),l[_].push(...h)}}return[s,o,l]}mergePunctuations(n,r,i,a,s){const o=structuredClone(n),l=structuredClone(r),d=structuredClone(i);let c=o.length-2,u=o.length-1;for(;c>=0;)o[c].startsWith(" ")&&a.includes(o[c].trim())?(o[u]=o[c]+o[u],l[u]=kt(l[c],l[u]),d[u]=kt(d[c],d[u]),o[c]="",l[c]=[],d[c]=[]):u=c,--c;for(c=0,u=1;uf),l.filter(f=>f.length>0),d.filter(f=>f.length>0)]}get_decoder_prompt_ids({language:n=null,task:r=null,no_timestamps:i=!0}={}){const a=[];if(n){n=n.toLowerCase();let s=pT.get(n);if(s===void 0)if(el.has(n))s=n;else{const d=n.length===2?el.keys():el.values();throw new Error(`Language "${n}" is not supported. Must be one of: ${JSON.stringify(d)}`)}const o=this.model.tokens_to_ids.get(`<|${s}|>`);if(o===void 0)throw new Error(`Unable to find language "${s}" in model vocabulary. Please report this issue at https://github.com/xenova/transformers.js/issues/new/choose.`);a.push(o)}else a.push(null);if(r){if(r=r.toLowerCase(),r!=="transcribe"&&r!=="translate")throw new Error(`Task "${r}" is not supported. Must be one of: ["transcribe", "translate"]`);const s=this.model.tokens_to_ids.get(`<|${r}|>`);if(s===void 0)throw new Error(`Unable to find task "${r}" in model vocabulary. Please report this issue at https://github.com/xenova/transformers.js/issues/new/choose.`);a.push(s)}else a.push(null);if(i){const s=this.model.tokens_to_ids.get("<|notimestamps|>");if(s===void 0)throw new Error('Unable to find "<|notimestamps|>" in model vocabulary. Please report this issue at https://github.com/xenova/transformers.js/issues/new/choose.');a.push(s)}return a.map((s,o)=>[o+1,s]).filter(s=>s[1]!==null)}}class hT extends Te{}class mT extends Te{}class gT extends Te{}class yT extends Te{constructor(t,n){super(t,n),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=this.model.vocab.filter(r=>this.languageRegex.test(r)),console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(t){if(t===null)return null;const[n,...r]=t.trim().split(this.languageRegex);if(r.length===0)return super._encode_text(n);if(r.length===2){const[i,a]=r;return this.supported_language_codes.includes(i)||console.warn(`Unsupported language code "${i}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),kt([i],super._encode_text(a))}}}class wT extends Te{}class E$ extends Te{constructor(){super(...arguments);j(this,"_default_chat_template","{% for message in messages %}{% if message['role'] == 'user' %}{{ ' ' }}{% endif %}{{ message['content'] }}{% if not loop.last %}{{ ' ' }}{% endif %}{% endfor %}{{ eos_token }}")}}class _T extends E${}class vT extends Te{}class $T extends Te{}class bT extends Te{constructor(t,n){super(t,n),this.decoder=new CC({})}}class xT extends Te{}class k${static async from_pretrained(t,{progress_callback:n=null,config:r=null,cache_dir:i=null,local_files_only:a=!1,revision:s="main",legacy:o=null}={}){var f;const[l,d]=await h$(t,{progress_callback:n,config:r,cache_dir:i,local_files_only:a,revision:s,legacy:o}),c=((f=d.tokenizer_class)==null?void 0:f.replace(/Fast$/,""))??"PreTrainedTokenizer";let u=this.TOKENIZER_CLASS_MAPPING[c];return u||(console.warn(`Unknown tokenizer class "${c}", attempting to construct from base class.`),u=Te),new u(l,d)}}j(k$,"TOKENIZER_CLASS_MAPPING",{T5Tokenizer:QC,DistilBertTokenizer:HC,CamembertTokenizer:qC,DebertaTokenizer:UC,DebertaV2Tokenizer:WC,BertTokenizer:DC,HerbertTokenizer:VC,ConvBertTokenizer:jC,RoFormerTokenizer:GC,XLMTokenizer:KC,ElectraTokenizer:YC,MobileBertTokenizer:LC,SqueezeBertTokenizer:FC,AlbertTokenizer:NC,GPT2Tokenizer:$$,BartTokenizer:XC,MBartTokenizer:b$,MBart50Tokenizer:ZC,RobertaTokenizer:JC,WhisperTokenizer:fT,CodeGenTokenizer:hT,CLIPTokenizer:mT,SiglipTokenizer:gT,MarianTokenizer:yT,BloomTokenizer:eT,NllbTokenizer:dT,M2M100Tokenizer:cT,LlamaTokenizer:x$,CodeLlamaTokenizer:tT,XLMRobertaTokenizer:nT,MPNetTokenizer:rT,FalconTokenizer:iT,GPTNeoXTokenizer:aT,EsmTokenizer:sT,Wav2Vec2CTCTokenizer:wT,BlenderbotTokenizer:E$,BlenderbotSmallTokenizer:_T,SpeechT5Tokenizer:vT,NougatTokenizer:$T,VitsTokenizer:bT,Qwen2Tokenizer:oT,GemmaTokenizer:lT,Grok1Tokenizer:uT,CohereTokenizer:xT,PreTrainedTokenizer:Te});async function ST(e,t){return await di(e,"config.json",!0,t)}class ET{constructor(t){this.model_type=null,this.is_encoder_decoder=!1,Object.assign(this,t)}static async from_pretrained(t,{progress_callback:n=null,config:r=null,cache_dir:i=null,local_files_only:a=!1,revision:s="main"}={}){let o=r??await ST(t,{progress_callback:n,config:r,cache_dir:i,local_files_only:a,revision:s});return new this(o)}}class Cr{static async from_pretrained(...t){return ET.from_pretrained(...t)}}const tl=Object.freeze({cpu:"cpu",gpu:"gpu",wasm:"wasm",webgpu:"webgpu"}),kT=function(){let e;return async function(){if(e===void 0)if(Gl.IS_NODE_ENV)e=!0;else if(!Gl.IS_WEBGPU_AVAILABLE)e=!1;else try{e=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{e=!1}return e}}(),Rn=Object.freeze({fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8"}),CT=Object.freeze({[tl.cpu]:Rn.q8,[tl.gpu]:Rn.fp32,[tl.wasm]:Rn.q8,[tl.webgpu]:Rn.fp32}),Sy=Object.freeze({[Rn.fp32]:"",[Rn.fp16]:"_fp16",[Rn.int8]:"_int8",[Rn.uint8]:"_uint8",[Rn.q8]:"_quantized"});class _r extends dn{_call(t,n){throw Error("`_call` should be implemented in a subclass")}}class Cf extends dn{_call(t,n){throw Error("`_call` should be implemented in a subclass")}}class Ey extends dn{constructor(){super(),this.processors=[]}push(t){this.processors.push(t)}extend(t){this.processors.push(...t)}_call(t,n){let r=n;for(const i of this.processors)r=i(t,r);return r}[Symbol.iterator](){return this.processors.values()}}class TT extends _r{constructor(t){super(),this.bos_token_id=t}_call(t,n){for(let r=0;r1 to use the classifier free guidance processor, got guidance scale ${t}.`);this.guidance_scale=t}_call(t,n){if(n.dims[0]!==2*t.length)throw new Error(`Logits should have twice the batch size of the input ids, the first half of batches corresponding to the conditional inputs, and the second half of batches corresponding to the unconditional inputs. Got batch size ${n.dims[0]} for the logits and ${t.length} for the input ids.`);const r=t.length,i=n.slice([0,r],null),a=n.slice([r,n.dims[0]],null);for(let s=0;s1)throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${t}`);if(!Number.isInteger(r)||r<1)throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${r}`);this.top_p=t,this.filter_value=n,this.min_tokens_to_keep=r}}class LT extends Cf{constructor(t,{filter_value:n=-1/0,min_tokens_to_keep:r=1}={}){if(super(),!Number.isInteger(t)||t<0)throw new Error(`\`top_k\` must be a positive integer, but is ${t}`);this.top_k=Math.max(t,r),this.filter_value=n}}class FT{constructor(t){j(this,"max_length",20);j(this,"max_new_tokens",null);j(this,"min_length",0);j(this,"min_new_tokens",null);j(this,"early_stopping",!1);j(this,"max_time",null);j(this,"do_sample",!1);j(this,"num_beams",1);j(this,"num_beam_groups",1);j(this,"penalty_alpha",null);j(this,"use_cache",!0);j(this,"temperature",1);j(this,"top_k",50);j(this,"top_p",1);j(this,"typical_p",1);j(this,"epsilon_cutoff",0);j(this,"eta_cutoff",0);j(this,"diversity_penalty",0);j(this,"repetition_penalty",1);j(this,"encoder_repetition_penalty",1);j(this,"length_penalty",1);j(this,"no_repeat_ngram_size",0);j(this,"bad_words_ids",null);j(this,"force_words_ids",null);j(this,"renormalize_logits",!1);j(this,"constraints",null);j(this,"forced_bos_token_id",null);j(this,"forced_eos_token_id",null);j(this,"remove_invalid_values",!1);j(this,"exponential_decay_length_penalty",null);j(this,"suppress_tokens",null);j(this,"begin_suppress_tokens",null);j(this,"forced_decoder_ids",null);j(this,"guidance_scale",null);j(this,"num_return_sequences",1);j(this,"output_attentions",!1);j(this,"output_hidden_states",!1);j(this,"output_scores",!1);j(this,"return_dict_in_generate",!1);j(this,"pad_token_id",null);j(this,"bos_token_id",null);j(this,"eos_token_id",null);j(this,"encoder_no_repeat_ngram_size",0);j(this,"decoder_start_token_id",null);j(this,"generation_kwargs",{});Object.assign(this,ta(t,Object.getOwnPropertyNames(this)))}}class C$ extends dn{_call(t,n){throw Error("StoppingCriteria needs to be subclassed")}}class Tf extends dn{constructor(){super(),this.criteria=[]}push(t){this.criteria.push(t)}extend(t){t instanceof Tf&&(t=t.criteria),this.criteria.push(...t)}_call(t,n){const r=new Array(t.length).fill(!1);for(const i of this.criteria){const a=i(t,n);for(let s=0;sn.length>=this.max_length)}}class WT extends C${constructor(t){super(),Array.isArray(t)||(t=[t]),this.eos_token_id=t}_call(t,n){return t.map(r=>this.eos_token_id.includes(r.at(-1)))}}class ku extends dn{constructor(t){super(),this.generation_config=t}_call(t,n=-1){return this.sample(t,n)}sample(t,n){throw Error("sample should be implemented in subclasses.")}getLogits(t,n){let r=t.dims.at(-1),i=t.data;if(n===-1)i=i.slice(-r);else{let a=n*r;i=i.slice(a,a+r)}return i}randomSelect(t){let n=t.reduce((i,a)=>i+a,0),r=Math.random()*n;for(let i=0;i1)return new GT(t);if(t.num_return_sequences>1)throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${t.num_return_sequences}.`);return new VT(t)}}class VT extends ku{sample(t,n=-1){let r=this.getLogits(t,n);return[[Zp(r)[1],0]]}}class jT extends ku{sample(t,n=-1){let r=t.dims.at(-1);this.generation_config.top_k>0&&(r=Math.min(this.generation_config.top_k,r));const i=this.getLogits(t,n),a=Q_(i,r),s=Y_(a.map(o=>o[1]));return Array.from({length:this.generation_config.num_beams},()=>{const o=this.randomSelect(s);return[a[o][0],Math.log(s[o])]})}}class GT extends ku{sample(t,n=-1){let r=t.dims.at(-1);this.generation_config.top_k>0&&(r=Math.min(this.generation_config.top_k,r));const i=this.getLogits(t,n),a=Q_(i,r),s=Y_(a.map(o=>o[1]));return Array.from({length:this.generation_config.num_beams},(o,l)=>[a[l][0],Math.log(s[l])])}}const Ee={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,MaskGeneration:5,ImageTextToText:6,Musicgen:7},iu=new Map,T$=new Map,_s=new Map;async function HT(e,t,n){let r=n.device;r&&typeof r!="string"&&(r.hasOwnProperty(t)?r=r[t]:(console.warn(`Device not specified for ${t}. Using the default device.`),r=null));const i=sk(r);let a=n.dtype;if(typeof a!="string"&&(a&&a.hasOwnProperty(t)?a=a[t]:(a=CT[i[0]],console.warn(`Dtype not specified for ${t}. Using the default dtype: ${a}.`))),Sy.hasOwnProperty(a)){if(a===Rn.fp16&&!await kT())throw new Error("The device does not support fp16.")}else throw new Error(`Invalid dtype: ${a}. Should be one of: ${Object.keys(Rn).join(", ")}`);const s=Sy[a],o=`${n.subfolder??""}/${t}${s}.onnx`,l=await Lc(e,o,!0,n),d={...n.session_options};if(d.executionProviders??(d.executionProviders=i),d.externalData!==void 0)for(let c=0;cHT(e,t[s],n))),a={};for(let s=0;s0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${r.join(", ")}.`);const i=Object.keys(t).length,a=e.inputNames.length;if(i>a){let s=Object.keys(t).filter(o=>!e.inputNames.includes(o));console.warn(`WARNING: Too many inputs were provided (${i} > ${a}). The following inputs will be ignored: "${s.join(", ")}".`)}return n}async function Hr(e,t){const n=qT(e,t);try{const r=Object.fromEntries(Object.entries(n).map(([a,s])=>[a,s.ort_tensor]));let i=await e.run(r);i=I$(i);for(const[a,s]of Object.entries(n))a.startsWith("past_key_values")&&s.dispose();return i}catch(r){throw console.error(`An error occurred during model execution: "${r}".`),console.error("Inputs given to model:",n),r}}function I$(e){for(let t in e)p$(e[t])?e[t]=new _e(e[t]):typeof e[t]=="object"&&I$(e[t]);return e}function KT(e){if(e instanceof _e)return e;if(e.length===0)throw Error("items must be non-empty");if(Array.isArray(e[0])){if(e.some(t=>t.length!==e[0].length))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=True' and/or 'truncation=True' to have batched tensors with the same length.");return new _e("int64",BigInt64Array.from(e.flat().map(t=>BigInt(t))),[e.length,e[0].length])}else return new _e("int64",BigInt64Array.from(e.map(t=>BigInt(t))),[1,e.length])}function A$(e){return new _e("bool",[e],[1])}async function ky(e,t){let{encoder_outputs:n,past_key_values:r}=t;if(!n){const l=ta(t,e.sessions.model.inputNames);n=(await Fs(e,l)).last_hidden_state}const{input_ids:i,decoder_input_ids:a,...s}=t;return s.input_ids=a,s.encoder_hidden_states=n,e.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(s.encoder_attention_mask=t.attention_mask),await If(e,s,!0)}async function Fs(e,t){const n=e.sessions.model,r=Object.create(null);for(const i of n.inputNames)r[i]=t[i];return n.inputNames.includes("token_type_ids")&&!r.token_type_ids&&(r.token_type_ids=new _e("int64",new BigInt64Array(r.input_ids.data.length),r.input_ids.dims)),await Hr(n,r)}async function If(e,t,n=!1){const r=e.sessions[n?"decoder_model_merged":"model"],{past_key_values:i,...a}=t;r.inputNames.includes("use_cache_branch")&&(a.use_cache_branch=A$(!!i)),e.addPastKeyValues(a,i);const s=ta(a,r.inputNames);return await Hr(r,s)}function YT(e,t,n,r){if(e.sessions.model.inputNames.includes("position_ids")&&n.attention_mask&&!n.position_ids){const[a,s]=n.attention_mask.dims,o=new BigInt64Array(n.attention_mask.data.length);for(let l=0;l[s.at(-1)])),i.decoder_input_ids=KT(t),i}class J extends dn{constructor(n,r){super();j(this,"main_input_name","input_ids");j(this,"forward_params",["input_ids","attention_mask"]);this.config=n,this.sessions=r;const i=_s.get(this.constructor),a=iu.get(i);this.can_generate=!1,this._forward=null,this._prepare_inputs_for_generation=null,a===Ee.DecoderOnly?(this.can_generate=!0,this._forward=If,this._prepare_inputs_for_generation=YT):a===Ee.Seq2Seq||a===Ee.Vision2Seq||a===Ee.Musicgen?(this.can_generate=!0,this._forward=ky,this._prepare_inputs_for_generation=QT):a===Ee.EncoderDecoder?this._forward=ky:a===Ee.ImageTextToText?(this.can_generate=!0,console.warn("TODO: Implement visionDecoderForward")):this._forward=Fs}async dispose(){var r;const n=[];for(let i of Object.keys(this)){let a=this[i];((r=a==null?void 0:a.handler)==null?void 0:r.dispose)!==void 0&&n.push(a.handler.dispose())}return await Promise.all(n)}static async from_pretrained(n,{progress_callback:r=null,config:i=null,cache_dir:a=null,local_files_only:s=!1,revision:o="main",model_file_name:l=null,subfolder:d="onnx",device:c=null,dtype:u=null,session_options:f={}}={}){let h={progress_callback:r,config:i,cache_dir:a,local_files_only:s,revision:o,model_file_name:l,subfolder:d,device:c,dtype:u,session_options:f};const g=_s.get(this),$=iu.get(g);let E;return $===Ee.DecoderOnly?E=await Promise.all([Cr.from_pretrained(n,h),ii(n,{model:h.model_file_name??"model"},h),di(n,"generation_config.json",!1,h)]):$===Ee.Seq2Seq||$===Ee.Vision2Seq?E=await Promise.all([Cr.from_pretrained(n,h),ii(n,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},h),di(n,"generation_config.json",!1,h)]):$===Ee.MaskGeneration?E=await Promise.all([Cr.from_pretrained(n,h),ii(n,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},h)]):$===Ee.EncoderDecoder?E=await Promise.all([Cr.from_pretrained(n,h),ii(n,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},h)]):$===Ee.ImageTextToText?E=await Promise.all([Cr.from_pretrained(n,h),ii(n,{embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"},h),di(n,"generation_config.json",!1,h)]):$===Ee.Musicgen?E=await Promise.all([Cr.from_pretrained(n,h),ii(n,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},h),di(n,"generation_config.json",!1,h)]):($!==Ee.EncoderOnly&&console.warn(`Model type for '${g??(i==null?void 0:i.model_type)}' not found, assuming encoder-only architecture. Please report this at https://github.com/xenova/transformers.js/issues/new/choose.`),E=await Promise.all([Cr.from_pretrained(n,h),ii(n,{model:h.model_file_name??"model"},h)])),new this(...E)}async _call(n){return await this.forward(n)}async forward(n){return await this._forward(this,n)}_get_logits_warper(n){const r=new Ey;return n.temperature!==null&&n.temperature!==1&&r.push(new DT(n.temperature)),n.top_k!==null&&n.top_k!==0&&r.push(new LT(n.top_k)),n.top_p!==null&&n.top_p<1&&r.push(new NT(n.top_p)),r}_get_logits_processor(n,r,i=null){const a=new Ey;if(n.repetition_penalty!==null&&n.repetition_penalty!==1&&a.push(new MT(n.repetition_penalty)),n.no_repeat_ngram_size!==null&&n.no_repeat_ngram_size>0&&a.push(new OT(n.no_repeat_ngram_size)),n.bad_words_ids!==null&&a.push(new PT(n.bad_words_ids,n.eos_token_id)),n.min_length!==null&&n.eos_token_id!==null&&n.min_length>0&&a.push(new zT(n.min_length,n.eos_token_id)),n.min_new_tokens!==null&&n.eos_token_id!==null&&n.min_new_tokens>0&&a.push(new RT(r,n.min_new_tokens,n.eos_token_id)),n.forced_bos_token_id!==null&&a.push(new TT(n.forced_bos_token_id)),n.forced_eos_token_id!==null&&a.push(new IT(n.max_length,n.forced_eos_token_id)),n.begin_suppress_tokens!==null){let s=r>1||n.forced_bos_token_id===null?r:r+1;n.forced_decoder_ids!==null&&(s+=n.forced_decoder_ids[n.forced_decoder_ids.length-1][0]),a.push(new AT(n.begin_suppress_tokens,s))}return n.guidance_scale!==null&&n.guidance_scale>1&&a.push(new BT(n.guidance_scale)),i!==null&&a.extend(i),a}_prepare_generation_config(n,r){const i=new FT(this.config);return"generation_config"in this&&Object.assign(i,this.generation_config),n&&Object.assign(i,n),r&&Object.assign(i,ta(r,Object.getOwnPropertyNames(i))),i}_get_stopping_criteria(n,r=null){const i=new Tf;return n.max_length!==null&&i.push(new UT(n.max_length,this.config.max_position_embeddings??null)),n.eos_token_id!==null&&i.push(new WT(n.eos_token_id)),r&&i.extend(r),i}_validate_model_class(){if(!this.can_generate){const n=[Bf,Tb,Cb,kb],r=_s.get(this.constructor),i=new Set,a=this.config.model_type;for(const o of n){const l=o.get(a);l&&i.add(l[0])}let s=`The current model class (${r}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw i.size>0&&(s+=` Please use the following class instead: ${[...i].join(", ")}`),Error(s)}}prepare_inputs_for_generation(...n){return this._prepare_inputs_for_generation(this,...n)}_update_model_kwargs_for_generation({generated_input_ids:n,outputs:r,model_inputs:i,is_encoder_decoder:a}){return i.past_key_values=this.getPastKeyValues(r,i.past_key_values),i.input_ids=new _e("int64",n,[n.length,1]),a||(i.attention_mask=pr([i.attention_mask,nu([i.attention_mask.dims[0],1])],1)),i.position_ids=null,i}_prepare_model_inputs({inputs:n,bos_token_id:r,model_kwargs:i}){const a=ta(i,this.forward_params),s=this.main_input_name;if(s in a){if(n)throw new Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else a[s]=n;return{inputs_tensor:a[s],model_inputs:a,model_input_name:s}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:n,model_inputs:r,model_input_name:i,generation_config:a}){const s=ta(r,this.sessions.model.inputNames);let{last_hidden_state:o}=await Fs(this,s);return a.guidance_scale!==null&&a.guidance_scale>1&&(o=pr([o,mk(o,0)],0),"attention_mask"in r&&(r.attention_mask=pr([r.attention_mask,wk(r.attention_mask)],0))),r.encoder_outputs=o,r}_prepare_decoder_input_ids_for_generation({batch_size:n,model_input_name:r,model_kwargs:i,decoder_start_token_id:a,bos_token_id:s,generation_config:o}){a=a??s;let l;if(this.config.model_type==="musicgen")l=new Array(n*this.config.decoder.num_codebooks).fill(a);else if(Array.isArray(a)){if(a.length!==n)throw new Error(`\`decoder_start_token_id\` expcted to have length ${n} but got ${a.length}`);l=a}else l=new Array(n).fill(a);const c=new _e("int64",l,[l.length,1]);return i.decoder_attention_mask=gk(c),{input_ids:c,model_inputs:i}}async generate({inputs:n=null,generation_config:r=null,logits_processor:i=null,stopping_criteria:a=null,streamer:s=null,...o}){this._validate_model_class(),r=this._prepare_generation_config(r,o);let{inputs_tensor:l,model_inputs:d,model_input_name:c}=this._prepare_model_inputs({inputs:n,model_kwargs:o});const u=this.config.is_encoder_decoder;u&&("encoder_outputs"in d||(d=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:l,model_inputs:d,model_input_name:c,generation_config:r})));let f;u?{input_ids:f,model_inputs:d}=this._prepare_decoder_input_ids_for_generation({batch_size:d[c].dims.at(0),model_input_name:c,model_kwargs:d,decoder_start_token_id:r.decoder_start_token_id,bos_token_id:r.bos_token_id,generation_config:r}):f=d[c];let h=f.dims.at(-1);r.max_new_tokens!==null&&(r.max_length=h+r.max_new_tokens);const g=this._get_logits_processor(r,h,i),$=this._get_stopping_criteria(r,a),E=d[c].dims.at(0),y=ku.getSampler(r),_=new Array(E).fill(0),v=f.tolist();for(s&&s.put(v);;){d=this.prepare_inputs_for_generation(v,d,r);const b=await this.forward(d),C=b.logits.slice(null,-1,null),I=g(v,C),O=[];for(let W=0;WW))break;d=this._update_model_kwargs_for_generation({generated_input_ids:O,outputs:b,model_inputs:d,is_encoder_decoder:u})}return s&&s.end(),new _e("int64",v.flat(),[v.length,v[0].length])}addAttentionsToBeam(n,r){if(this.config.is_encoder_decoder){if(!r.cross_attentions||r.cross_attentions.length===0)throw Error("`output_attentions` is true, but the model did not produce cross-attentions. This is most likely because the model was not exported with `output_attentions=True`.");n.cross_attentions||(n.cross_attentions=[]),n.cross_attentions.push(r.cross_attentions)}if(!r.decoder_attentions||r.decoder_attentions.length===0)throw Error("`output_attentions` is true, but the model did not produce decoder-attentions. This is most likely because the model was not exported with `output_attentions=True`.");n.decoder_attentions||(n.decoder_attentions=[]),n.decoder_attentions.push(r.decoder_attentions)}groupBeams(n){const r=Object.create(null);for(const i of n)r[i.id]===void 0?r[i.id]=[i]:r[i.id].push(i);return Object.values(r)}getPastKeyValues(n,r){const i=Object.create(null);for(const a in n)if(a.startsWith("present")){let s=a.replace("present","past_key_values");r&&a.includes("encoder")?i[s]=r[s]:i[s]=n[a]}return i}getAttentions(n){const r=Object.create(null);for(const i of["cross_attentions","decoder_attentions"]){const a=[];for(const s in n)if(s.startsWith(i)){const o=s.split(".").pop();a[o]=n[s]}r[i]=a}return r}addPastKeyValues(n,r){if(r)Object.assign(n,r);else{const a="float32",s=[];if(this.config.is_encoder_decoder&&(this.add_encoder_pkv??!0)){let o=[1,this.num_encoder_heads,0,this.encoder_dim_kv],l=[1,this.num_decoder_heads,0,this.decoder_dim_kv];for(let d=0;d{let c=Array.from({length:this.config.decoder_layers},(E,y)=>pr(d.map(_=>_[y]),2)),u=ep(n.map(([E,y])=>r?c[E].slice(null,y,null,[0,r]):c[E].slice(null,y)));u=u.transpose(1,0,2,3);let[f,h]=ck(u,-2,0,!0),g=u.clone();for(let E=0;Eu[y+1]-u[y]),g=kt([1],h).map(E=>!!E),$=[];for(let E=0;Ef.findIndex(h=>h==a)),l=o.every(f=>f===-1),d=o.every(f=>f!==-1);if(!l&&!d)throw new Error("Every input should contain either 0 or 1 image token.");if(l)return{inputs_embeds:t,attention_mask:i,position_ids:null};let c=[],u=[];for(let f=0;fi*a,1);t.input_labels=new _e("int64",new BigInt64Array(r).fill(1n),n)}return await Hr(this.prompt_encoder_mask_decoder,{input_points:t.input_points,input_labels:t.input_labels,image_embeddings:t.image_embeddings,image_positional_embeddings:t.image_positional_embeddings})}async _call(t){return new yM(await super._call(t))}}class yM extends vn{constructor({iou_scores:t,pred_masks:n}){super(),this.iou_scores=t,this.pred_masks=n}}class mb extends J{constructor(t,n,r){super(t,n),this.generation_config=r,this.num_decoder_layers=this.config.decoder_layers,this.num_decoder_heads=this.config.decoder_attention_heads,this.decoder_dim_kv=this.config.d_model/this.num_decoder_heads,this.num_encoder_layers=this.config.encoder_layers,this.num_encoder_heads=this.config.encoder_attention_heads,this.encoder_dim_kv=this.config.d_model/this.num_encoder_heads}}class wM extends mb{}class _M extends mb{}class gb extends J{constructor(t,n,r){super(t,n),this.generation_config=r,this.num_decoder_layers=this.config.decoder_layers,this.num_decoder_heads=this.config.decoder_attention_heads,this.decoder_dim_kv=this.config.d_model/this.num_decoder_heads,this.num_encoder_layers=this.config.encoder_layers,this.num_encoder_heads=this.config.encoder_attention_heads,this.encoder_dim_kv=this.config.d_model/this.num_encoder_heads}}class vM extends gb{}class $M extends gb{}class Si extends J{}class bM extends Si{}class xM extends Si{async _call(t){return new _a(await super._call(t))}}class SM extends Si{async _call(t){return new Be(await super._call(t))}}class EM extends Si{async _call(t){return new Pt(await super._call(t))}}class Mf extends J{}class kM extends Mf{}class CM extends Mf{async _call(t){return new _a(await super._call(t))}}class TM extends Mf{async _call(t){return new Be(await super._call(t))}}class zu extends J{}class IM extends zu{}class AM extends zu{async _call(t){return new _a(await super._call(t))}}class OM extends zu{async _call(t){return new Be(await super._call(t))}}class MM extends zu{async _call(t){return new Pt(await super._call(t))}}class zf extends J{}class zM extends zf{}class RM extends zf{async _call(t){return new _a(await super._call(t))}}class PM extends zf{async _call(t){return new Be(await super._call(t))}}class BM extends Si{}class DM extends Si{async _call(t){return new _a(await super._call(t))}}class NM extends Si{async _call(t){return new Be(await super._call(t))}}class lo extends J{}class LM extends lo{}class FM extends lo{async _call(t){return new _a(await super._call(t))}}class UM extends lo{async _call(t){return new Be(await super._call(t))}}class WM extends lo{async _call(t){return new Rz(await super._call(t))}}class VM extends lo{async _call(t){return new Pt(await super._call(t))}}class yb extends J{constructor(t,n,r){super(t,n),this.generation_config=r,this.num_decoder_layers=this.config.decoder_layers,this.num_decoder_heads=this.config.decoder_attention_heads,this.decoder_dim_kv=this.config.hidden_size/this.num_decoder_heads,this.num_encoder_layers=this.config.encoder_layers,this.num_encoder_heads=this.config.encoder_attention_heads,this.encoder_dim_kv=this.config.hidden_size/this.num_encoder_heads}}class jM extends yb{}class GM extends yb{async generate_speech(t,n,{threshold:r=.5,minlenratio:i=0,maxlenratio:a=20,vocoder:s=null}={}){const o={input_ids:t},{encoder_outputs:l,encoder_attention_mask:d}=await Fs(this,o),c=l.dims[1]/this.config.reduction_factor,u=Math.floor(c*a),f=Math.floor(c*i),h=this.config.num_mel_bins;let g=[],$=null,E=null,y=0;for(;;){++y;const b=A$(!!E);let C;E?C=E.output_sequence_out:C=new _e("float32",new Float32Array(h),[1,1,h]);let I={use_cache_branch:b,output_sequence:C,encoder_attention_mask:d,speaker_embeddings:n,encoder_hidden_states:l};this.addPastKeyValues(I,$),E=await Hr(this.sessions.decoder_model_merged,I),$=this.getPastKeyValues(E,$);const{prob:O,spectrum:M}=E;if(g.push(M),y>=f&&(Array.from(O.data).filter(W=>W>=r).length>0||y>=u))break}const _=pr(g),{waveform:v}=await Hr(s.sessions.model,{spectrogram:_});return{spectrogram:_,waveform:v}}}class HM extends J{constructor(){super(...arguments);j(this,"main_input_name","spectrogram")}}class qM extends J{constructor(t,n,r){super(t,n),this.generation_config=r,this.num_encoder_layers=this.num_decoder_layers=this.config.decoder_layers,this.num_encoder_heads=this.num_decoder_heads=this.config.decoder_attention_heads,this.encoder_dim_kv=this.decoder_dim_kv=this.config.d_model/this.num_decoder_heads}}class KM extends qM{}class wb extends J{constructor(t,n,r){super(t,n),this.generation_config=r,this.num_heads=this.config.num_key_value_heads,this.num_layers=this.config.num_hidden_layers,this.dim_kv=this.config.hidden_size/this.config.num_attention_heads}}class YM extends wb{}class QM extends wb{}class _b extends J{constructor(t,n,r){super(t,n),this.generation_config=r,this.num_heads=this.config.num_key_value_heads,this.num_layers=this.config.num_hidden_layers,this.dim_kv=this.config.hidden_size/this.config.num_attention_heads}}class XM extends _b{}class ZM extends _b{}class vb extends J{constructor(t,n,r){super(t,n),this.generation_config=r,this.num_heads=this.config.num_attention_heads,this.num_layers=this.config.num_hidden_layers,this.dim_kv=this.config.hidden_size/this.config.num_attention_heads}}class JM extends vb{}class ez extends vb{}class Rf extends J{}class tz extends Rf{}class nz extends Rf{static async from_pretrained(t,n={}){return n.model_file_name??(n.model_file_name="text_model"),super.from_pretrained(t,n)}}class rz extends Rf{static async from_pretrained(t,n={}){return n.model_file_name??(n.model_file_name="audio_model"),super.from_pretrained(t,n)}}class iz extends J{}class $b extends iz{async _call(t){return new Bz(await super._call(t))}}class bb extends J{}class az extends bb{}class sz extends bb{}class oz extends J{constructor(t,n,r){super(t,n),this.generation_config=r,this.num_heads=this.config.num_attention_heads,this.num_layers=this.config.num_hidden_layers,this.dim_kv=this.config.hidden_size/this.num_heads}}class lz extends oz{}class xb extends J{}class uz extends xb{}class dz extends xb{async _call(t){return new Be(await super._call(t))}}class Pf extends J{constructor(n,r,i){super(n,r);j(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"]);this.generation_config=i;const a=n.decoder;this.num_encoder_layers=this.num_decoder_layers=a.num_hidden_layers,this.num_encoder_heads=this.num_decoder_heads=a.num_attention_heads,this.encoder_dim_kv=this.decoder_dim_kv=a.hidden_size/this.num_decoder_heads}_apply_and_filter_by_delay_pattern_mask(n){const[r,i]=n.dims,a=this.config.decoder.num_codebooks,s=i-a;let o=0;for(let c=0;c0&&h<=s&&(n.data[o++]=n.data[c])}const l=Math.floor(r/a),d=o/(l*a);return new _e(n.type,n.data.slice(0,o),[l,a,d])}prepare_inputs_for_generation(n,r,i){let a=structuredClone(n);for(let o=0;o=l&&(a[o][l]=BigInt(this.config.decoder.pad_token_id));return i.guidance_scale!==null&&i.guidance_scale>1&&(a=a.concat(a)),super.prepare_inputs_for_generation(a,r,i)}async generate(n){const r=await super.generate(n),i=this._apply_and_filter_by_delay_pattern_mask(r).unsqueeze_(0),{audio_values:a}=await Hr(this.sessions.encodec_decode,{audio_codes:i});return a}}class np{static async from_pretrained(t,{progress_callback:n=null,config:r=null,cache_dir:i=null,local_files_only:a=!1,revision:s="main",model_file_name:o=null,subfolder:l="onnx",device:d=null,dtype:c=null,session_options:u={}}={}){let f={progress_callback:n,config:r,cache_dir:i,local_files_only:a,revision:s,model_file_name:o,subfolder:l,device:d,dtype:c,session_options:u};if(r=await Cr.from_pretrained(t,f),f.config||(f.config=r),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);for(let h of this.MODEL_CLASS_MAPPINGS){const g=h.get(r.model_type);if(g)return await g[1].from_pretrained(t,f)}if(this.BASE_IF_FAIL)return console.warn(`Unknown model class "${r.model_type}", attempting to construct from base class.`),await J.from_pretrained(t,f);throw Error(`Unsupported model type: ${r.model_type}`)}}j(np,"MODEL_CLASS_MAPPINGS",null),j(np,"BASE_IF_FAIL",!1);const Sb=new Map([["bert",["BertModel",XT]],["nomic_bert",["NomicBertModel",rI]],["roformer",["RoFormerModel",iI]],["electra",["ElectraModel",hI]],["esm",["EsmModel",LI]],["convbert",["ConvBertModel",uI]],["camembert",["CamembertModel",_I]],["deberta",["DebertaModel",SI]],["deberta-v2",["DebertaV2Model",II]],["mpnet",["MPNetModel",qI]],["albert",["AlbertModel",nA]],["distilbert",["DistilBertModel",RI]],["roberta",["RobertaModel",xA]],["xlm",["XLMModel",TA]],["xlm-roberta",["XLMRobertaModel",zA]],["clap",["ClapModel",tz]],["clip",["CLIPModel",GA]],["clipseg",["CLIPSegModel",JA]],["chinese_clip",["ChineseCLIPModel",ZA]],["siglip",["SiglipModel",KA]],["mobilebert",["MobileBertModel",VI]],["squeezebert",["SqueezeBertModel",ZI]],["wav2vec2",["Wav2Vec2Model",bM]],["wav2vec2-bert",["Wav2Vec2BertModel",zM]],["unispeech",["UniSpeechModel",kM]],["unispeech-sat",["UniSpeechSatModel",IM]],["hubert",["HubertModel",BM]],["wavlm",["WavLMModel",LM]],["audio-spectrogram-transformer",["ASTModel",NA]],["vits",["VitsModel",$b]],["detr",["DetrModel",DO]],["table-transformer",["TableTransformerModel",UO]],["vit",["ViTModel",EO]],["mobilevit",["MobileViTModel",IO]],["owlvit",["OwlViTModel",OO]],["owlv2",["Owlv2Model",zO]],["beit",["BeitModel",PO]],["deit",["DeiTModel",jO]],["convnext",["ConvNextModel",sM]],["convnextv2",["ConvNextV2Model",lM]],["dinov2",["Dinov2Model",dM]],["resnet",["ResNetModel",HO]],["swin",["SwinModel",KO]],["swin2sr",["Swin2SRModel",QO]],["donut-swin",["DonutSwinModel",aM]],["yolos",["YolosModel",pM]],["dpt",["DPTModel",ZO]],["glpn",["GLPNModel",nM]],["hifigan",["SpeechT5HifiGan",HM]],["efficientnet",["EfficientNetModel",uz]]]),Eb=new Map([["t5",["T5Model",sA]],["longt5",["LongT5Model",lA]],["mt5",["MT5Model",dA]],["bart",["BartModel",pA]],["mbart",["MBartModel",mA]],["marian",["MarianModel",wM]],["whisper",["WhisperModel",FA]],["m2m_100",["M2M100Model",vM]],["blenderbot",["BlenderbotModel",_A]],["blenderbot-small",["BlenderbotSmallModel",$A]]]),cz=new Map([["bloom",["BloomModel",_O]],["gpt2",["GPT2Model",tO]],["gptj",["GPTJModel",oO]],["gpt_bigcode",["GPTBigCodeModel",uO]],["gpt_neo",["GPTNeoModel",rO]],["gpt_neox",["GPTNeoXModel",aO]],["codegen",["CodeGenModel",cO]],["llama",["LlamaModel",fO]],["qwen2",["Qwen2Model",mO]],["phi",["PhiModel",yO]],["mpt",["MptModel",$O]],["opt",["OPTModel",xO]],["mistral",["MistralModel",YM]],["starcoder2",["Starcoder2Model",XM]],["falcon",["FalconModel",JM]]]),kb=new Map([["speecht5",["SpeechT5ForSpeechToText",jM]],["whisper",["WhisperForConditionalGeneration",UA]]]),pz=new Map([["speecht5",["SpeechT5ForTextToSpeech",GM]]]),fz=new Map([["vits",["VitsModel",$b]],["musicgen",["MusicgenForConditionalGeneration",Pf]]]),hz=new Map([["bert",["BertForSequenceClassification",JT]],["roformer",["RoFormerForSequenceClassification",sI]],["electra",["ElectraForSequenceClassification",gI]],["esm",["EsmForSequenceClassification",UI]],["convbert",["ConvBertForSequenceClassification",cI]],["camembert",["CamembertForSequenceClassification",$I]],["deberta",["DebertaForSequenceClassification",kI]],["deberta-v2",["DebertaV2ForSequenceClassification",OI]],["mpnet",["MPNetForSequenceClassification",YI]],["albert",["AlbertForSequenceClassification",rA]],["distilbert",["DistilBertForSequenceClassification",PI]],["roberta",["RobertaForSequenceClassification",EA]],["xlm",["XLMForSequenceClassification",AA]],["xlm-roberta",["XLMRobertaForSequenceClassification",PA]],["bart",["BartForSequenceClassification",hA]],["mbart",["MBartForSequenceClassification",yA]],["mobilebert",["MobileBertForSequenceClassification",GI]],["squeezebert",["SqueezeBertForSequenceClassification",eA]]]),mz=new Map([["bert",["BertForTokenClassification",eI]],["roformer",["RoFormerForTokenClassification",oI]],["electra",["ElectraForTokenClassification",yI]],["esm",["EsmForTokenClassification",WI]],["convbert",["ConvBertForTokenClassification",pI]],["camembert",["CamembertForTokenClassification",bI]],["deberta",["DebertaForTokenClassification",CI]],["deberta-v2",["DebertaV2ForTokenClassification",MI]],["mpnet",["MPNetForTokenClassification",QI]],["distilbert",["DistilBertForTokenClassification",BI]],["roberta",["RobertaForTokenClassification",kA]],["xlm",["XLMForTokenClassification",OA]],["xlm-roberta",["XLMRobertaForTokenClassification",BA]]]),Cb=new Map([["t5",["T5ForConditionalGeneration",oA]],["longt5",["LongT5ForConditionalGeneration",uA]],["mt5",["MT5ForConditionalGeneration",cA]],["bart",["BartForConditionalGeneration",fA]],["mbart",["MBartForConditionalGeneration",gA]],["marian",["MarianMTModel",_M]],["m2m_100",["M2M100ForConditionalGeneration",$M]],["blenderbot",["BlenderbotForConditionalGeneration",vA]],["blenderbot-small",["BlenderbotSmallForConditionalGeneration",bA]]]),Bf=new Map([["bloom",["BloomForCausalLM",vO]],["gpt2",["GPT2LMHeadModel",nO]],["gptj",["GPTJForCausalLM",lO]],["gpt_bigcode",["GPTBigCodeForCausalLM",dO]],["gpt_neo",["GPTNeoForCausalLM",iO]],["gpt_neox",["GPTNeoXForCausalLM",sO]],["codegen",["CodeGenForCausalLM",pO]],["llama",["LlamaForCausalLM",hO]],["qwen2",["Qwen2ForCausalLM",gO]],["phi",["PhiForCausalLM",wO]],["mpt",["MptForCausalLM",bO]],["opt",["OPTForCausalLM",SO]],["mbart",["MBartForCausalLM",wA]],["mistral",["MistralForCausalLM",QM]],["starcoder2",["Starcoder2ForCausalLM",ZM]],["falcon",["FalconForCausalLM",ez]],["trocr",["TrOCRForCausalLM",KM]],["stablelm",["StableLmForCausalLM",lz]]]),gz=new Map([["bert",["BertForMaskedLM",ZT]],["roformer",["RoFormerForMaskedLM",aI]],["electra",["ElectraForMaskedLM",mI]],["esm",["EsmForMaskedLM",FI]],["convbert",["ConvBertForMaskedLM",dI]],["camembert",["CamembertForMaskedLM",vI]],["deberta",["DebertaForMaskedLM",EI]],["deberta-v2",["DebertaV2ForMaskedLM",AI]],["mpnet",["MPNetForMaskedLM",KI]],["albert",["AlbertForMaskedLM",aA]],["distilbert",["DistilBertForMaskedLM",NI]],["roberta",["RobertaForMaskedLM",SA]],["xlm",["XLMWithLMHeadModel",IA]],["xlm-roberta",["XLMRobertaForMaskedLM",RA]],["mobilebert",["MobileBertForMaskedLM",jI]],["squeezebert",["SqueezeBertForMaskedLM",JI]]]),yz=new Map([["bert",["BertForQuestionAnswering",tI]],["roformer",["RoFormerForQuestionAnswering",lI]],["electra",["ElectraForQuestionAnswering",wI]],["convbert",["ConvBertForQuestionAnswering",fI]],["camembert",["CamembertForQuestionAnswering",xI]],["deberta",["DebertaForQuestionAnswering",TI]],["deberta-v2",["DebertaV2ForQuestionAnswering",zI]],["mpnet",["MPNetForQuestionAnswering",XI]],["albert",["AlbertForQuestionAnswering",iA]],["distilbert",["DistilBertForQuestionAnswering",DI]],["roberta",["RobertaForQuestionAnswering",CA]],["xlm",["XLMForQuestionAnswering",MA]],["xlm-roberta",["XLMRobertaForQuestionAnswering",DA]],["mobilebert",["MobileBertForQuestionAnswering",HI]],["squeezebert",["SqueezeBertForQuestionAnswering",tA]]]),Tb=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",WA]]]),wz=new Map([["llava",["LlavaForConditionalGeneration",jA]]]),_z=new Map([["vit",["ViTForImageClassification",kO]],["mobilevit",["MobileViTForImageClassification",AO]],["beit",["BeitForImageClassification",BO]],["deit",["DeiTForImageClassification",GO]],["convnext",["ConvNextForImageClassification",oM]],["convnextv2",["ConvNextV2ForImageClassification",uM]],["dinov2",["Dinov2ForImageClassification",cM]],["resnet",["ResNetForImageClassification",qO]],["swin",["SwinForImageClassification",YO]],["segformer",["SegformerForImageClassification",az]],["efficientnet",["EfficientNetForImageClassification",dz]]]),vz=new Map([["detr",["DetrForObjectDetection",NO]],["table-transformer",["TableTransformerForObjectDetection",WO]],["yolos",["YolosForObjectDetection",fM]]]),$z=new Map([["owlvit",["OwlViTForObjectDetection",MO]],["owlv2",["Owlv2ForObjectDetection",RO]]]),bz=new Map([["detr",["DetrForSegmentation",LO]],["clipseg",["CLIPSegForImageSegmentation",eO]]]),xz=new Map([["segformer",["SegformerForSemanticSegmentation",sz]]]),Sz=new Map([["sam",["SamModel",gM]]]),Ez=new Map([["wav2vec2",["Wav2Vec2ForCTC",xM]],["wav2vec2-bert",["Wav2Vec2BertForCTC",RM]],["unispeech",["UniSpeechForCTC",CM]],["unispeech-sat",["UniSpeechSatForCTC",AM]],["wavlm",["WavLMForCTC",FM]],["hubert",["HubertForCTC",DM]]]),kz=new Map([["wav2vec2",["Wav2Vec2ForSequenceClassification",SM]],["wav2vec2-bert",["Wav2Vec2BertForSequenceClassification",PM]],["unispeech",["UniSpeechForSequenceClassification",TM]],["unispeech-sat",["UniSpeechSatForSequenceClassification",OM]],["wavlm",["WavLMForSequenceClassification",UM]],["hubert",["HubertForSequenceClassification",NM]],["audio-spectrogram-transformer",["ASTForAudioClassification",LA]]]),Cz=new Map([["wavlm",["WavLMForXVector",WM]]]),Tz=new Map([["unispeech-sat",["UniSpeechSatForAudioFrameClassification",MM]],["wavlm",["WavLMForAudioFrameClassification",VM]],["wav2vec2",["Wav2Vec2ForAudioFrameClassification",EM]]]),Iz=new Map([["vitmatte",["VitMatteForImageMatting",TO]]]),Az=new Map([["swin2sr",["Swin2SRForImageSuperResolution",XO]]]),Oz=new Map([["dpt",["DPTForDepthEstimation",JO]],["depth_anything",["DepthAnythingForDepthEstimation",tM]],["glpn",["GLPNForDepthEstimation",rM]]]),Mz=new Map([["clip",["CLIPVisionModelWithProjection",qA]],["siglip",["SiglipVisionModel",QA]]]),Ib=[[Sb,Ee.EncoderOnly],[Eb,Ee.EncoderDecoder],[cz,Ee.DecoderOnly],[hz,Ee.EncoderOnly],[mz,Ee.EncoderOnly],[Cb,Ee.Seq2Seq],[kb,Ee.Seq2Seq],[Bf,Ee.DecoderOnly],[gz,Ee.EncoderOnly],[yz,Ee.EncoderOnly],[Tb,Ee.Vision2Seq],[wz,Ee.ImageTextToText],[_z,Ee.EncoderOnly],[bz,Ee.EncoderOnly],[xz,Ee.EncoderOnly],[Iz,Ee.EncoderOnly],[Az,Ee.EncoderOnly],[Oz,Ee.EncoderOnly],[vz,Ee.EncoderOnly],[$z,Ee.EncoderOnly],[Sz,Ee.MaskGeneration],[Ez,Ee.EncoderOnly],[kz,Ee.EncoderOnly],[pz,Ee.Seq2Seq],[fz,Ee.EncoderOnly],[Cz,Ee.EncoderOnly],[Tz,Ee.EncoderOnly],[Mz,Ee.EncoderOnly]];for(const[e,t]of Ib)for(const[n,r]of e.values())iu.set(n,t),_s.set(r,n),T$.set(n,r);const zz=[["MusicgenForConditionalGeneration",Pf,Ee.Musicgen],["CLIPTextModelWithProjection",HA,Ee.EncoderOnly],["SiglipTextModel",YA,Ee.EncoderOnly],["ClapTextModelWithProjection",nz,Ee.EncoderOnly],["ClapAudioModelWithProjection",rz,Ee.EncoderOnly]];for(const[e,t,n]of zz)iu.set(e,n),_s.set(t,e),T$.set(e,t);class Cy extends np{}j(Cy,"MODEL_CLASS_MAPPINGS",Ib.map(t=>t[0])),j(Cy,"BASE_IF_FAIL",!0);class Be extends vn{constructor({logits:t}){super(),this.logits=t}}class Rz extends vn{constructor({logits:t,embeddings:n}){super(),this.logits=t,this.embeddings=n}}class Pt extends vn{constructor({logits:t}){super(),this.logits=t}}class Bt extends vn{constructor({logits:t}){super(),this.logits=t}}class Vt extends vn{constructor({start_logits:t,end_logits:n}){super(),this.start_logits=t,this.end_logits=n}}class _a extends vn{constructor({logits:t}){super(),this.logits=t}}class Pz extends vn{constructor({alphas:t}){super(),this.alphas=t}}class Bz extends vn{constructor({waveform:t,spectrogram:n}){super(),this.waveform=t,this.spectrogram=n}}const Dz=typeof self<"u";if(!Dz){if(!ft)throw new Error("Unable to load image processing library.")}class Nz{put(t){throw Error("Not implemented")}end(){throw Error("Not implemented")}}function Lz(e,t=16e3){let n=44;const r=new ArrayBuffer(n+e.length*4),i=new DataView(r);nl(i,0,"RIFF"),i.setUint32(4,36+e.length*4,!0),nl(i,8,"WAVE"),nl(i,12,"fmt "),i.setUint32(16,16,!0),i.setUint16(20,3,!0),i.setUint16(22,1,!0),i.setUint32(24,t,!0),i.setUint32(28,t*4,!0),i.setUint16(32,4,!0),i.setUint16(34,32,!0),nl(i,36,"data"),i.setUint32(40,e.length*4,!0);for(let a=0;a ${JSON.stringify(t,null,2)}`}).toString()}`;window.open(a,"_blank")}const Ty="Xenova/musicgen-small",Iy=["80s pop track with bassy drums and synth","90s rock song with loud guitars and heavy drums","a light and cheerly EDM track, with syncopated drums, aery pads, and strong emotions bpm: 130","A cheerful country song with acoustic guitars","lofi slow bpm electro chill with organic samples"],Uz=window.location.host.endsWith(".hf.space");class Wz extends Nz{constructor(t){super(),this.callback_fn=t}put(t){return this.callback_fn(t)}end(){return this.callback_fn()}}const Vz=()=>{const[e,t]=Ot.useState(Iy[0]),[n,r]=Ot.useState(0),[i,a]=Ot.useState({}),[s,o]=Ot.useState("Loading model (656MB)..."),[l,d]=Ot.useState(null),c=Ot.useRef(null),u=Ot.useRef(null),f=Ot.useRef(null),[h,g]=Ot.useState(3),[$,E]=Ot.useState(1),[y,_]=Ot.useState(10);Ot.useEffect(()=>{u.current??(u.current=Pf.from_pretrained(Ty,{progress_callback:b=>{b.status==="progress"&&a(C=>({...C,[b.file]:b}))},dtype:{text_encoder:"q8",decoder_model_merged:"q8",encodec_decode:"fp32"},device:"wasm"})),f.current??(f.current=k$.from_pretrained(Ty))},[]),Ot.useEffect(()=>{if(Object.values(i).length!==5)return;let C=0,I=0;for(const M of Object.values(i))C+=M.loaded,I+=M.total;const O=C/I;r(O),o(O===1?"Ready!":`Loading model (${(O*100).toFixed()}% of 656MB)...`)},[i]);const v=async()=>{c.current.src="",d(null);const b=await f.current,C=await u.current,I=Math.min(Math.max(Math.floor(y*50),1)+4,C.generation_config.max_length??1500),O=new Wz(ae=>{const ue=ae===void 0?1:ae[0].length/I;o(`Generating (${(ue*100).toFixed()}%)...`),r(ue)}),M=b(e),W=await C.generate({...M,max_length:I,guidance_scale:h,temperature:$,streamer:O});o("Encoding audio...");const G=C.config.audio_encoder.sampling_rate,z=Lz(W.data,G),K=new Blob([z],{type:"audio/wav"});d(K),c.current.src=URL.createObjectURL(K),o("Done!")};return We.jsxs("div",{className:"container mx-auto p-8",children:[We.jsx("h1",{className:"text-5xl font-bold mb-2",children:"MusicGen Web"}),We.jsxs("h2",{className:"text-2xl font-semibold mb-4",children:["In-browser text-to-music w/ ",We.jsx("a",{className:"underline",href:"http://github.com/xenova/transformers.js",children:"🤗 Transformers.js!"})]}),We.jsx("input",{type:"text",placeholder:"Describe the music to generate...",value:e,onChange:b=>t(b.target.value),className:"border border-gray-300 p-2 mb-4 w-full rounded"}),We.jsx("div",{className:"mb-4 flex gap-2 justify-center text-sm",children:Iy.map((b,C)=>We.jsx("button",{className:"bg-blue-500 hover:bg-blue-400 transition-colors duration-100 text-white px-2 py-2 rounded",onClick:I=>t(I.target.innerText),children:b},C))}),We.jsxs("div",{className:"flex mb-4 justify-center gap-2",children:[We.jsxs("div",{children:[We.jsx("label",{className:"block text-sm font-semibold mb-1",children:"Duration"}),We.jsx("input",{type:"range",min:1,max:30,value:y,onChange:b=>_(b.target.value)}),We.jsx("p",{className:"text-sm text-center",children:`${y} second${y>1?"s":""}`})]}),We.jsxs("div",{className:"mr-4",children:[We.jsx("label",{className:"block text-sm font-semibold mb-1",children:"Guidance Scale"}),We.jsx("input",{type:"range",min:1,max:10,value:h,onChange:b=>g(b.target.value)}),We.jsx("p",{className:"text-sm text-center",children:h})]}),We.jsxs("div",{children:[We.jsx("label",{className:"block text-sm font-semibold mb-1",children:"Temperature"}),We.jsx("input",{type:"range",min:.1,max:2,step:.1,value:$,onChange:b=>E(b.target.value)}),We.jsx("p",{className:"text-sm text-center",children:$})]})]}),We.jsx("button",{className:"mb-4 bg-green-500 hover:bg-green-400 transition-colors duration-100 text-white px-4 py-3 rounded-lg font-semibold",onClick:v,children:"Generate Music"}),We.jsxs("div",{className:"mb-4",children:[We.jsx("div",{className:"bg-gray-200 h-4 w-full rounded-full",children:We.jsx("div",{className:"bg-blue-500 h-4 rounded-full",style:{width:`${100*n}%`}})}),We.jsx("p",{className:"text-sm text-center mt-1",children:s})]}),We.jsxs("div",{className:"flex justify-center flex-col items-center",children:[We.jsx("audio",{ref:c,controls:!0,type:"audio/wav"}),Uz&&l&&We.jsx("button",{className:"bg-red-500 hover:bg-red-400 transition-colors duration-100 text-white px-2 py-1 my-2 rounded-lg text-sm",onClick:async b=>{b.target.disabled=!0,b.target.innerText="Uploading...",await Fz(l,{prompt:e,duration:y,guidance_scale:h,temperature:$}),b.target.disabled=!1,b.target.innerText="Share"},children:"Share"})]})]})};Gd.createRoot(document.getElementById("root")).render(We.jsx(ox.StrictMode,{children:We.jsx(Vz,{})}));