diff --git a/assets/index-BWoA1BSA.js b/assets/index-BWoA1BSA.js new file mode 100644 index 0000000..80cda41 --- /dev/null +++ b/assets/index-BWoA1BSA.js @@ -0,0 +1,2392 @@ +(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))n(i);new MutationObserver(i=>{for(const o of i)if(o.type==="childList")for(const a of o.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&n(a)}).observe(document,{childList:!0,subtree:!0});function r(i){const o={};return i.integrity&&(o.integrity=i.integrity),i.referrerPolicy&&(o.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?o.credentials="include":i.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function n(i){if(i.ep)return;i.ep=!0;const o=r(i);fetch(i.href,o)}})();function Z2(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var d0={exports:{}},vu={},p0={exports:{}},Te={};/** + * @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 wo=Symbol.for("react.element"),J2=Symbol.for("react.portal"),e$=Symbol.for("react.fragment"),t$=Symbol.for("react.strict_mode"),r$=Symbol.for("react.profiler"),n$=Symbol.for("react.provider"),i$=Symbol.for("react.context"),a$=Symbol.for("react.forward_ref"),o$=Symbol.for("react.suspense"),s$=Symbol.for("react.memo"),u$=Symbol.for("react.lazy"),Kc=Symbol.iterator;function l$(e){return e===null||typeof e!="object"?null:(e=Kc&&e[Kc]||e["@@iterator"],typeof e=="function"?e:null)}var c0={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},f0=Object.assign,h0={};function ta(e,t,r){this.props=e,this.context=t,this.refs=h0,this.updater=r||c0}ta.prototype.isReactComponent={};ta.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")};ta.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function m0(){}m0.prototype=ta.prototype;function ip(e,t,r){this.props=e,this.context=t,this.refs=h0,this.updater=r||c0}var ap=ip.prototype=new m0;ap.constructor=ip;f0(ap,ta.prototype);ap.isPureReactComponent=!0;var Yc=Array.isArray,g0=Object.prototype.hasOwnProperty,op={current:null},y0={key:!0,ref:!0,__self:!0,__source:!0};function v0(e,t,r){var n,i={},o=null,a=null;if(t!=null)for(n in t.ref!==void 0&&(a=t.ref),t.key!==void 0&&(o=""+t.key),t)g0.call(t,n)&&!y0.hasOwnProperty(n)&&(i[n]=t[n]);var u=arguments.length-2;if(u===1)i.children=r;else if(1>>1,ee=U[R];if(0>>1;Ri(Ce,Q))Lei(st,Ce)?(U[R]=st,U[Le]=Q,R=Le):(U[R]=Ce,U[we]=Q,R=we);else if(Lei(st,Q))U[R]=st,U[Le]=Q,R=Le;else break e}}return J}function i(U,J){var Q=U.sortIndex-J.sortIndex;return Q!==0?Q:U.id-J.id}if(typeof performance=="object"&&typeof performance.now=="function"){var o=performance;e.unstable_now=function(){return o.now()}}else{var a=Date,u=a.now();e.unstable_now=function(){return a.now()-u}}var l=[],p=[],f=1,m=null,y=3,$=!1,c=!1,x=!1,T=typeof setTimeout=="function"?setTimeout:null,_=typeof clearTimeout=="function"?clearTimeout:null,v=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function k(U){for(var J=r(p);J!==null;){if(J.callback===null)n(p);else if(J.startTime<=U)n(p),J.sortIndex=J.expirationTime,t(l,J);else break;J=r(p)}}function C(U){if(x=!1,k(U),!c)if(r(l)!==null)c=!0,V(I);else{var J=r(p);J!==null&&le(C,J.startTime-U)}}function I(U,J){c=!1,x&&(x=!1,_(B),B=-1),$=!0;var Q=y;try{for(k(J),m=r(l);m!==null&&(!(m.expirationTime>J)||U&&!me());){var R=m.callback;if(typeof R=="function"){m.callback=null,y=m.priorityLevel;var ee=R(m.expirationTime<=J);J=e.unstable_now(),typeof ee=="function"?m.callback=ee:m===r(l)&&n(l),k(J)}else n(l);m=r(l)}if(m!==null)var oe=!0;else{var we=r(p);we!==null&&le(C,we.startTime-J),oe=!1}return oe}finally{m=null,y=Q,$=!1}}var M=!1,P=null,B=-1,H=5,F=-1;function me(){return!(e.unstable_now()-FU||125R?(U.sortIndex=Q,t(p,U),r(l)===null&&U===r(p)&&(x?(_(B),B=-1):x=!0,le(C,Q-R))):(U.sortIndex=ee,t(l,U),c||$||(c=!0,V(I))),U},e.unstable_shouldYield=me,e.unstable_wrapCallback=function(U){var J=y;return function(){var Q=y;y=J;try{return U.apply(this,arguments)}finally{y=Q}}}})(x0);b0.exports=x0;var _$=b0.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 b$=ir,er=_$;function Y(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,r=1;r"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),Jl=Object.prototype.hasOwnProperty,x$=/^[: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]*$/,Xc={},Zc={};function S$(e){return Jl.call(Zc,e)?!0:Jl.call(Xc,e)?!1:x$.test(e)?Zc[e]=!0:(Xc[e]=!0,!1)}function k$(e,t,r,n){if(r!==null&&r.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return n?!1:r!==null?!r.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function E$(e,t,r,n){if(t===null||typeof t>"u"||k$(e,t,r,n))return!0;if(n)return!1;if(r!==null)switch(r.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 Pt(e,t,r,n,i,o,a){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=n,this.attributeNamespace=i,this.mustUseProperty=r,this.propertyName=e,this.type=t,this.sanitizeURL=o,this.removeEmptyString=a}var $t={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){$t[e]=new Pt(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];$t[t]=new Pt(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){$t[e]=new Pt(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){$t[e]=new Pt(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){$t[e]=new Pt(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){$t[e]=new Pt(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){$t[e]=new Pt(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){$t[e]=new Pt(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){$t[e]=new Pt(e,5,!1,e.toLowerCase(),null,!1,!1)});var up=/[\-:]([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(up,lp);$t[t]=new Pt(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(up,lp);$t[t]=new Pt(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(up,lp);$t[t]=new Pt(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){$t[e]=new Pt(e,1,!1,e.toLowerCase(),null,!1,!1)});$t.xlinkHref=new Pt("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){$t[e]=new Pt(e,1,!1,e.toLowerCase(),null,!0,!0)});function dp(e,t,r,n){var i=$t.hasOwnProperty(t)?$t[t]:null;(i!==null?i.type!==0:n||!(2u||i[a]!==o[u]){var l=` +`+i[a].replace(" at new "," at ");return e.displayName&&l.includes("")&&(l=l.replace("",e.displayName)),l}while(1<=a&&0<=u);break}}}finally{Xu=!1,Error.prepareStackTrace=r}return(e=e?e.displayName||e.name:"")?Na(e):""}function C$(e){switch(e.tag){case 5:return Na(e.type);case 16:return Na("Lazy");case 13:return Na("Suspense");case 19:return Na("SuspenseList");case 0:case 2:case 15:return e=Zu(e.type,!1),e;case 11:return e=Zu(e.type.render,!1),e;case 1:return e=Zu(e.type,!0),e;default:return""}}function nd(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 Ci:return"Fragment";case Ei:return"Portal";case ed:return"Profiler";case pp:return"StrictMode";case td:return"Suspense";case rd:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case E0:return(e.displayName||"Context")+".Consumer";case k0: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 fp:return t=e.displayName||null,t!==null?t:nd(e.type)||"Memo";case cn:t=e._payload,e=e._init;try{return nd(e(t))}catch{}}return null}function T$(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 nd(t);case 8:return t===pp?"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 En(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function T0(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function I$(e){var t=T0(e)?"checked":"value",r=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),n=""+e[t];if(!e.hasOwnProperty(t)&&typeof r<"u"&&typeof r.get=="function"&&typeof r.set=="function"){var i=r.get,o=r.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return i.call(this)},set:function(a){n=""+a,o.call(this,a)}}),Object.defineProperty(e,t,{enumerable:r.enumerable}),{getValue:function(){return n},setValue:function(a){n=""+a},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function Qo(e){e._valueTracker||(e._valueTracker=I$(e))}function I0(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var r=t.getValue(),n="";return e&&(n=T0(e)?e.checked?"true":"false":e.value),e=n,e!==r?(t.setValue(e),!0):!1}function Ns(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 id(e,t){var r=t.checked;return Ze({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:r??e._wrapperState.initialChecked})}function ef(e,t){var r=t.defaultValue==null?"":t.defaultValue,n=t.checked!=null?t.checked:t.defaultChecked;r=En(t.value!=null?t.value:r),e._wrapperState={initialChecked:n,initialValue:r,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function A0(e,t){t=t.checked,t!=null&&dp(e,"checked",t,!1)}function ad(e,t){A0(e,t);var r=En(t.value),n=t.type;if(r!=null)n==="number"?(r===0&&e.value===""||e.value!=r)&&(e.value=""+r):e.value!==""+r&&(e.value=""+r);else if(n==="submit"||n==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?od(e,t.type,r):t.hasOwnProperty("defaultValue")&&od(e,t.type,En(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function tf(e,t,r){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var n=t.type;if(!(n!=="submit"&&n!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,r||t===e.value||(e.value=t),e.defaultValue=t}r=e.name,r!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,r!==""&&(e.name=r)}function od(e,t,r){(t!=="number"||Ns(e.ownerDocument)!==e)&&(r==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+r&&(e.defaultValue=""+r))}var Wa=Array.isArray;function Ui(e,t,r,n){if(e=e.options,t){t={};for(var i=0;i"+t.valueOf().toString()+"",t=Xo.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function eo(e,t){if(t){var r=e.firstChild;if(r&&r===e.lastChild&&r.nodeType===3){r.nodeValue=t;return}}e.textContent=t}var Fa={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},A$=["Webkit","ms","Moz","O"];Object.keys(Fa).forEach(function(e){A$.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),Fa[t]=Fa[e]})});function P0(e,t,r){return t==null||typeof t=="boolean"||t===""?"":r||typeof t!="number"||t===0||Fa.hasOwnProperty(e)&&Fa[e]?(""+t).trim():t+"px"}function M0(e,t){e=e.style;for(var r in t)if(t.hasOwnProperty(r)){var n=r.indexOf("--")===0,i=P0(r,t[r],n);r==="float"&&(r="cssFloat"),n?e.setProperty(r,i):e[r]=i}}var z$=Ze({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 ld(e,t){if(t){if(z$[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(Y(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(Y(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(Y(61))}if(t.style!=null&&typeof t.style!="object")throw Error(Y(62))}}function dd(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 pd=null;function hp(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var cd=null,Li=null,Vi=null;function af(e){if(e=bo(e)){if(typeof cd!="function")throw Error(Y(280));var t=e.stateNode;t&&(t=xu(t),cd(e.stateNode,e.type,t))}}function B0(e){Li?Vi?Vi.push(e):Vi=[e]:Li=e}function D0(){if(Li){var e=Li,t=Vi;if(Vi=Li=null,af(e),t)for(e=0;e>>=0,e===0?32:31-(V$(e)/H$|0)|0}var Zo=64,Jo=4194304;function Ua(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 Vs(e,t){var r=e.pendingLanes;if(r===0)return 0;var n=0,i=e.suspendedLanes,o=e.pingedLanes,a=r&268435455;if(a!==0){var u=a&~i;u!==0?n=Ua(u):(o&=a,o!==0&&(n=Ua(o)))}else a=r&~i,a!==0?n=Ua(a):o!==0&&(n=Ua(o));if(n===0)return 0;if(t!==0&&t!==n&&!(t&i)&&(i=n&-n,o=t&-t,i>=o||i===16&&(o&4194240)!==0))return t;if(n&4&&(n|=r&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=n;0r;r++)t.push(e);return t}function $o(e,t,r){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-Ir(t),e[t]=r}function q$(e,t){var r=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 n=e.eventTimes;for(e=e.expirationTimes;0=Ga),hf=" ",mf=!1;function ny(e,t){switch(e){case"keyup":return __.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function iy(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var Ti=!1;function x_(e,t){switch(e){case"compositionend":return iy(t);case"keypress":return t.which!==32?null:(mf=!0,hf);case"textInput":return e=t.data,e===hf&&mf?null:e;default:return null}}function S_(e,t){if(Ti)return e==="compositionend"||!bp&&ny(e,t)?(e=ty(),ks=wp=gn=null,Ti=!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:r,offset:t-e};e=n}e:{for(;r;){if(r.nextSibling){r=r.nextSibling;break e}r=r.parentNode}r=void 0}r=wf(r)}}function uy(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?uy(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function ly(){for(var e=window,t=Ns();t instanceof e.HTMLIFrameElement;){try{var r=typeof t.contentWindow.location.href=="string"}catch{r=!1}if(r)e=t.contentWindow;else break;t=Ns(e.document)}return t}function xp(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 R_(e){var t=ly(),r=e.focusedElem,n=e.selectionRange;if(t!==r&&r&&r.ownerDocument&&uy(r.ownerDocument.documentElement,r)){if(n!==null&&xp(r)){if(t=n.start,e=n.end,e===void 0&&(e=t),"selectionStart"in r)r.selectionStart=t,r.selectionEnd=Math.min(e,r.value.length);else if(e=(t=r.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var i=r.textContent.length,o=Math.min(n.start,i);n=n.end===void 0?o:Math.min(n.end,i),!e.extend&&o>n&&(i=n,n=o,o=i),i=$f(r,o);var a=$f(r,n);i&&a&&(e.rangeCount!==1||e.anchorNode!==i.node||e.anchorOffset!==i.offset||e.focusNode!==a.node||e.focusOffset!==a.offset)&&(t=t.createRange(),t.setStart(i.node,i.offset),e.removeAllRanges(),o>n?(e.addRange(t),e.extend(a.node,a.offset)):(t.setEnd(a.node,a.offset),e.addRange(t)))}}for(t=[],e=r;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof r.focus=="function"&&r.focus(),r=0;r=document.documentMode,Ii=null,vd=null,Ka=null,wd=!1;function _f(e,t,r){var n=r.window===r?r.document:r.nodeType===9?r:r.ownerDocument;wd||Ii==null||Ii!==Ns(n)||(n=Ii,"selectionStart"in n&&xp(n)?n={start:n.selectionStart,end:n.selectionEnd}:(n=(n.ownerDocument&&n.ownerDocument.defaultView||window).getSelection(),n={anchorNode:n.anchorNode,anchorOffset:n.anchorOffset,focusNode:n.focusNode,focusOffset:n.focusOffset}),Ka&&oo(Ka,n)||(Ka=n,n=js(vd,"onSelect"),0Oi||(e.current=kd[Oi],kd[Oi]=null,Oi--)}function Ve(e,t){Oi++,kd[Oi]=e.current,e.current=t}var Cn={},Et=An(Cn),Ht=An(!1),Xn=Cn;function qi(e,t){var r=e.type.contextTypes;if(!r)return Cn;var n=e.stateNode;if(n&&n.__reactInternalMemoizedUnmaskedChildContext===t)return n.__reactInternalMemoizedMaskedChildContext;var i={},o;for(o in r)i[o]=t[o];return n&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=i),i}function Ft(e){return e=e.childContextTypes,e!=null}function qs(){Ge(Ht),Ge(Et)}function Tf(e,t,r){if(Et.current!==Cn)throw Error(Y(168));Ve(Et,t),Ve(Ht,r)}function vy(e,t,r){var n=e.stateNode;if(t=t.childContextTypes,typeof n.getChildContext!="function")return r;n=n.getChildContext();for(var i in n)if(!(i in t))throw Error(Y(108,T$(e)||"Unknown",i));return Ze({},r,n)}function Ks(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||Cn,Xn=Et.current,Ve(Et,e),Ve(Ht,Ht.current),!0}function If(e,t,r){var n=e.stateNode;if(!n)throw Error(Y(169));r?(e=vy(e,t,Xn),n.__reactInternalMemoizedMergedChildContext=e,Ge(Ht),Ge(Et),Ve(Et,e)):Ge(Ht),Ve(Ht,r)}var qr=null,Su=!1,cl=!1;function wy(e){qr===null?qr=[e]:qr.push(e)}function j_(e){Su=!0,wy(e)}function zn(){if(!cl&&qr!==null){cl=!0;var e=0,t=Ne;try{var r=qr;for(Ne=1;e>=a,i-=a,Kr=1<<32-Ir(t)+i|r<B?(H=P,P=null):H=P.sibling;var F=y(_,P,k[B],C);if(F===null){P===null&&(P=H);break}e&&P&&F.alternate===null&&t(_,P),v=o(F,v,B),M===null?I=F:M.sibling=F,M=F,P=H}if(B===k.length)return r(_,P),Ke&&Ln(_,B),I;if(P===null){for(;BB?(H=P,P=null):H=P.sibling;var me=y(_,P,F.value,C);if(me===null){P===null&&(P=H);break}e&&P&&me.alternate===null&&t(_,P),v=o(me,v,B),M===null?I=me:M.sibling=me,M=me,P=H}if(F.done)return r(_,P),Ke&&Ln(_,B),I;if(P===null){for(;!F.done;B++,F=k.next())F=m(_,F.value,C),F!==null&&(v=o(F,v,B),M===null?I=F:M.sibling=F,M=F);return Ke&&Ln(_,B),I}for(P=n(_,P);!F.done;B++,F=k.next())F=$(P,_,B,F.value,C),F!==null&&(e&&F.alternate!==null&&P.delete(F.key===null?B:F.key),v=o(F,v,B),M===null?I=F:M.sibling=F,M=F);return e&&P.forEach(function(ce){return t(_,ce)}),Ke&&Ln(_,B),I}function T(_,v,k,C){if(typeof k=="object"&&k!==null&&k.type===Ci&&k.key===null&&(k=k.props.children),typeof k=="object"&&k!==null){switch(k.$$typeof){case Yo:e:{for(var I=k.key,M=v;M!==null;){if(M.key===I){if(I=k.type,I===Ci){if(M.tag===7){r(_,M.sibling),v=i(M,k.props.children),v.return=_,_=v;break e}}else if(M.elementType===I||typeof I=="object"&&I!==null&&I.$$typeof===cn&&Of(I)===M.type){r(_,M.sibling),v=i(M,k.props),v.ref=Ca(_,M,k),v.return=_,_=v;break e}r(_,M);break}else t(_,M);M=M.sibling}k.type===Ci?(v=Yn(k.props.children,_.mode,C,k.key),v.return=_,_=v):(C=Rs(k.type,k.key,k.props,null,_.mode,C),C.ref=Ca(_,v,k),C.return=_,_=C)}return a(_);case Ei:e:{for(M=k.key;v!==null;){if(v.key===M)if(v.tag===4&&v.stateNode.containerInfo===k.containerInfo&&v.stateNode.implementation===k.implementation){r(_,v.sibling),v=i(v,k.children||[]),v.return=_,_=v;break e}else{r(_,v);break}else t(_,v);v=v.sibling}v=$l(k,_.mode,C),v.return=_,_=v}return a(_);case cn:return M=k._init,T(_,v,M(k._payload),C)}if(Wa(k))return c(_,v,k,C);if(ba(k))return x(_,v,k,C);os(_,k)}return typeof k=="string"&&k!==""||typeof k=="number"?(k=""+k,v!==null&&v.tag===6?(r(_,v.sibling),v=i(v,k),v.return=_,_=v):(r(_,v),v=wl(k,_.mode,C),v.return=_,_=v),a(_)):r(_,v)}return T}var Yi=xy(!0),Sy=xy(!1),Xs=An(null),Zs=null,Mi=null,Cp=null;function Tp(){Cp=Mi=Zs=null}function Ip(e){var t=Xs.current;Ge(Xs),e._currentValue=t}function Td(e,t,r){for(;e!==null;){var n=e.alternate;if((e.childLanes&t)!==t?(e.childLanes|=t,n!==null&&(n.childLanes|=t)):n!==null&&(n.childLanes&t)!==t&&(n.childLanes|=t),e===r)break;e=e.return}}function Fi(e,t){Zs=e,Cp=Mi=null,e=e.dependencies,e!==null&&e.firstContext!==null&&(e.lanes&t&&(Vt=!0),e.firstContext=null)}function dr(e){var t=e._currentValue;if(Cp!==e)if(e={context:e,memoizedValue:t,next:null},Mi===null){if(Zs===null)throw Error(Y(308));Mi=e,Zs.dependencies={lanes:0,firstContext:e}}else Mi=Mi.next=e;return t}var Gn=null;function Ap(e){Gn===null?Gn=[e]:Gn.push(e)}function ky(e,t,r,n){var i=t.interleaved;return i===null?(r.next=r,Ap(t)):(r.next=i.next,i.next=r),t.interleaved=r,tn(e,n)}function tn(e,t){e.lanes|=t;var r=e.alternate;for(r!==null&&(r.lanes|=t),r=e,e=e.return;e!==null;)e.childLanes|=t,r=e.alternate,r!==null&&(r.childLanes|=t),r=e,e=e.return;return r.tag===3?r.stateNode:null}var fn=!1;function zp(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function Ey(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function Xr(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function bn(e,t,r){var n=e.updateQueue;if(n===null)return null;if(n=n.shared,Pe&2){var i=n.pending;return i===null?t.next=t:(t.next=i.next,i.next=t),n.pending=t,tn(e,r)}return i=n.interleaved,i===null?(t.next=t,Ap(n)):(t.next=i.next,i.next=t),n.interleaved=t,tn(e,r)}function Cs(e,t,r){if(t=t.updateQueue,t!==null&&(t=t.shared,(r&4194240)!==0)){var n=t.lanes;n&=e.pendingLanes,r|=n,t.lanes=r,gp(e,r)}}function Rf(e,t){var r=e.updateQueue,n=e.alternate;if(n!==null&&(n=n.updateQueue,r===n)){var i=null,o=null;if(r=r.firstBaseUpdate,r!==null){do{var a={eventTime:r.eventTime,lane:r.lane,tag:r.tag,payload:r.payload,callback:r.callback,next:null};o===null?i=o=a:o=o.next=a,r=r.next}while(r!==null);o===null?i=o=t:o=o.next=t}else i=o=t;r={baseState:n.baseState,firstBaseUpdate:i,lastBaseUpdate:o,shared:n.shared,effects:n.effects},e.updateQueue=r;return}e=r.lastBaseUpdate,e===null?r.firstBaseUpdate=t:e.next=t,r.lastBaseUpdate=t}function Js(e,t,r,n){var i=e.updateQueue;fn=!1;var o=i.firstBaseUpdate,a=i.lastBaseUpdate,u=i.shared.pending;if(u!==null){i.shared.pending=null;var l=u,p=l.next;l.next=null,a===null?o=p:a.next=p,a=l;var f=e.alternate;f!==null&&(f=f.updateQueue,u=f.lastBaseUpdate,u!==a&&(u===null?f.firstBaseUpdate=p:u.next=p,f.lastBaseUpdate=l))}if(o!==null){var m=i.baseState;a=0,f=p=l=null,u=o;do{var y=u.lane,$=u.eventTime;if((n&y)===y){f!==null&&(f=f.next={eventTime:$,lane:0,tag:u.tag,payload:u.payload,callback:u.callback,next:null});e:{var c=e,x=u;switch(y=t,$=r,x.tag){case 1:if(c=x.payload,typeof c=="function"){m=c.call($,m,y);break e}m=c;break e;case 3:c.flags=c.flags&-65537|128;case 0:if(c=x.payload,y=typeof c=="function"?c.call($,m,y):c,y==null)break e;m=Ze({},m,y);break e;case 2:fn=!0}}u.callback!==null&&u.lane!==0&&(e.flags|=64,y=i.effects,y===null?i.effects=[u]:y.push(u))}else $={eventTime:$,lane:y,tag:u.tag,payload:u.payload,callback:u.callback,next:null},f===null?(p=f=$,l=m):f=f.next=$,a|=y;if(u=u.next,u===null){if(u=i.shared.pending,u===null)break;y=u,u=y.next,y.next=null,i.lastBaseUpdate=y,i.shared.pending=null}}while(!0);if(f===null&&(l=m),i.baseState=l,i.firstBaseUpdate=p,i.lastBaseUpdate=f,t=i.shared.interleaved,t!==null){i=t;do a|=i.lane,i=i.next;while(i!==t)}else o===null&&(i.shared.lanes=0);ei|=a,e.lanes=a,e.memoizedState=m}}function Pf(e,t,r){if(e=t.effects,t.effects=null,e!==null)for(t=0;tr?r:4,e(!0);var n=hl.transition;hl.transition={};try{e(!1),t()}finally{Ne=r,hl.transition=n}}function Hy(){return pr().memoizedState}function Y_(e,t,r){var n=Sn(e);if(r={lane:n,action:r,hasEagerState:!1,eagerState:null,next:null},Fy(e))jy(t,r);else if(r=ky(e,t,r,n),r!==null){var i=Ot();Ar(r,e,n,i),Gy(r,t,n)}}function Q_(e,t,r){var n=Sn(e),i={lane:n,action:r,hasEagerState:!1,eagerState:null,next:null};if(Fy(e))jy(t,i);else{var o=e.alternate;if(e.lanes===0&&(o===null||o.lanes===0)&&(o=t.lastRenderedReducer,o!==null))try{var a=t.lastRenderedState,u=o(a,r);if(i.hasEagerState=!0,i.eagerState=u,Or(u,a)){var l=t.interleaved;l===null?(i.next=i,Ap(t)):(i.next=l.next,l.next=i),t.interleaved=i;return}}catch{}finally{}r=ky(e,t,i,n),r!==null&&(i=Ot(),Ar(r,e,n,i),Gy(r,t,n))}}function Fy(e){var t=e.alternate;return e===Xe||t!==null&&t===Xe}function jy(e,t){Ya=tu=!0;var r=e.pending;r===null?t.next=t:(t.next=r.next,r.next=t),e.pending=t}function Gy(e,t,r){if(r&4194240){var n=t.lanes;n&=e.pendingLanes,r|=n,t.lanes=r,gp(e,r)}}var ru={readContext:dr,useCallback:xt,useContext:xt,useEffect:xt,useImperativeHandle:xt,useInsertionEffect:xt,useLayoutEffect:xt,useMemo:xt,useReducer:xt,useRef:xt,useState:xt,useDebugValue:xt,useDeferredValue:xt,useTransition:xt,useMutableSource:xt,useSyncExternalStore:xt,useId:xt,unstable_isNewReconciler:!1},X_={readContext:dr,useCallback:function(e,t){return Dr().memoizedState=[e,t===void 0?null:t],e},useContext:dr,useEffect:Bf,useImperativeHandle:function(e,t,r){return r=r!=null?r.concat([e]):null,Is(4194308,4,Ny.bind(null,t,e),r)},useLayoutEffect:function(e,t){return Is(4194308,4,e,t)},useInsertionEffect:function(e,t){return Is(4,2,e,t)},useMemo:function(e,t){var r=Dr();return t=t===void 0?null:t,e=e(),r.memoizedState=[e,t],e},useReducer:function(e,t,r){var n=Dr();return t=r!==void 0?r(t):t,n.memoizedState=n.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},n.queue=e,e=e.dispatch=Y_.bind(null,Xe,e),[n.memoizedState,e]},useRef:function(e){var t=Dr();return e={current:e},t.memoizedState=e},useState:Mf,useDebugValue:Wp,useDeferredValue:function(e){return Dr().memoizedState=e},useTransition:function(){var e=Mf(!1),t=e[0];return e=K_.bind(null,e[1]),Dr().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,r){var n=Xe,i=Dr();if(Ke){if(r===void 0)throw Error(Y(407));r=r()}else{if(r=t(),mt===null)throw Error(Y(349));Jn&30||Ay(n,t,r)}i.memoizedState=r;var o={value:r,getSnapshot:t};return i.queue=o,Bf(Oy.bind(null,n,o,e),[e]),n.flags|=2048,mo(9,zy.bind(null,n,o,r,t),void 0,null),r},useId:function(){var e=Dr(),t=mt.identifierPrefix;if(Ke){var r=Yr,n=Kr;r=(n&~(1<<32-Ir(n)-1)).toString(32)+r,t=":"+t+"R"+r,r=fo++,0<\/script>",e=e.removeChild(e.firstChild)):typeof n.is=="string"?e=a.createElement(r,{is:n.is}):(e=a.createElement(r),r==="select"&&(a=e,n.multiple?a.multiple=!0:n.size&&(a.size=n.size))):e=a.createElementNS(e,r),e[Nr]=t,e[lo]=n,rv(e,t,!1,!1),t.stateNode=e;e:{switch(a=dd(r,n),r){case"dialog":Fe("cancel",e),Fe("close",e),i=n;break;case"iframe":case"object":case"embed":Fe("load",e),i=n;break;case"video":case"audio":for(i=0;iZi&&(t.flags|=128,n=!0,Ta(o,!1),t.lanes=4194304)}else{if(!n)if(e=eu(a),e!==null){if(t.flags|=128,n=!0,r=e.updateQueue,r!==null&&(t.updateQueue=r,t.flags|=4),Ta(o,!0),o.tail===null&&o.tailMode==="hidden"&&!a.alternate&&!Ke)return St(t),null}else 2*tt()-o.renderingStartTime>Zi&&r!==1073741824&&(t.flags|=128,n=!0,Ta(o,!1),t.lanes=4194304);o.isBackwards?(a.sibling=t.child,t.child=a):(r=o.last,r!==null?r.sibling=a:t.child=a,o.last=a)}return o.tail!==null?(t=o.tail,o.rendering=t,o.tail=t.sibling,o.renderingStartTime=tt(),t.sibling=null,r=Qe.current,Ve(Qe,n?r&1|2:r&1),t):(St(t),null);case 22:case 23:return jp(),n=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==n&&(t.flags|=8192),n&&t.mode&1?Xt&1073741824&&(St(t),t.subtreeFlags&6&&(t.flags|=8192)):St(t),null;case 24:return null;case 25:return null}throw Error(Y(156,t.tag))}function ab(e,t){switch(kp(t),t.tag){case 1:return Ft(t.type)&&qs(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return Qi(),Ge(Ht),Ge(Et),Pp(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return Rp(t),null;case 13:if(Ge(Qe),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(Y(340));Ki()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return Ge(Qe),null;case 4:return Qi(),null;case 10:return Ip(t.type._context),null;case 22:case 23:return jp(),null;case 24:return null;default:return null}}var us=!1,kt=!1,ob=typeof WeakSet=="function"?WeakSet:Set,ae=null;function Bi(e,t){var r=e.ref;if(r!==null)if(typeof r=="function")try{r(null)}catch(n){Je(e,t,n)}else r.current=null}function Dd(e,t,r){try{r()}catch(n){Je(e,t,n)}}var qf=!1;function sb(e,t){if($d=Hs,e=ly(),xp(e)){if("selectionStart"in e)var r={start:e.selectionStart,end:e.selectionEnd};else e:{r=(r=e.ownerDocument)&&r.defaultView||window;var n=r.getSelection&&r.getSelection();if(n&&n.rangeCount!==0){r=n.anchorNode;var i=n.anchorOffset,o=n.focusNode;n=n.focusOffset;try{r.nodeType,o.nodeType}catch{r=null;break e}var a=0,u=-1,l=-1,p=0,f=0,m=e,y=null;t:for(;;){for(var $;m!==r||i!==0&&m.nodeType!==3||(u=a+i),m!==o||n!==0&&m.nodeType!==3||(l=a+n),m.nodeType===3&&(a+=m.nodeValue.length),($=m.firstChild)!==null;)y=m,m=$;for(;;){if(m===e)break t;if(y===r&&++p===i&&(u=a),y===o&&++f===n&&(l=a),($=m.nextSibling)!==null)break;m=y,y=m.parentNode}m=$}r=u===-1||l===-1?null:{start:u,end:l}}else r=null}r=r||{start:0,end:0}}else r=null;for(_d={focusedElem:e,selectionRange:r},Hs=!1,ae=t;ae!==null;)if(t=ae,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,ae=e;else for(;ae!==null;){t=ae;try{var c=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(c!==null){var x=c.memoizedProps,T=c.memoizedState,_=t.stateNode,v=_.getSnapshotBeforeUpdate(t.elementType===t.type?x:kr(t.type,x),T);_.__reactInternalSnapshotBeforeUpdate=v}break;case 3:var k=t.stateNode.containerInfo;k.nodeType===1?k.textContent="":k.nodeType===9&&k.documentElement&&k.removeChild(k.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(Y(163))}}catch(C){Je(t,t.return,C)}if(e=t.sibling,e!==null){e.return=t.return,ae=e;break}ae=t.return}return c=qf,qf=!1,c}function Qa(e,t,r){var n=t.updateQueue;if(n=n!==null?n.lastEffect:null,n!==null){var i=n=n.next;do{if((i.tag&e)===e){var o=i.destroy;i.destroy=void 0,o!==void 0&&Dd(t,r,o)}i=i.next}while(i!==n)}}function Cu(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var r=t=t.next;do{if((r.tag&e)===e){var n=r.create;r.destroy=n()}r=r.next}while(r!==t)}}function Nd(e){var t=e.ref;if(t!==null){var r=e.stateNode;switch(e.tag){case 5:e=r;break;default:e=r}typeof t=="function"?t(e):t.current=e}}function av(e){var t=e.alternate;t!==null&&(e.alternate=null,av(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[Nr],delete t[lo],delete t[Sd],delete t[H_],delete t[F_])),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 ov(e){return e.tag===5||e.tag===3||e.tag===4}function Kf(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||ov(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 Wd(e,t,r){var n=e.tag;if(n===5||n===6)e=e.stateNode,t?r.nodeType===8?r.parentNode.insertBefore(e,t):r.insertBefore(e,t):(r.nodeType===8?(t=r.parentNode,t.insertBefore(e,r)):(t=r,t.appendChild(e)),r=r._reactRootContainer,r!=null||t.onclick!==null||(t.onclick=Gs));else if(n!==4&&(e=e.child,e!==null))for(Wd(e,t,r),e=e.sibling;e!==null;)Wd(e,t,r),e=e.sibling}function Ud(e,t,r){var n=e.tag;if(n===5||n===6)e=e.stateNode,t?r.insertBefore(e,t):r.appendChild(e);else if(n!==4&&(e=e.child,e!==null))for(Ud(e,t,r),e=e.sibling;e!==null;)Ud(e,t,r),e=e.sibling}var yt=null,Er=!1;function un(e,t,r){for(r=r.child;r!==null;)sv(e,t,r),r=r.sibling}function sv(e,t,r){if(Wr&&typeof Wr.onCommitFiberUnmount=="function")try{Wr.onCommitFiberUnmount(wu,r)}catch{}switch(r.tag){case 5:kt||Bi(r,t);case 6:var n=yt,i=Er;yt=null,un(e,t,r),yt=n,Er=i,yt!==null&&(Er?(e=yt,r=r.stateNode,e.nodeType===8?e.parentNode.removeChild(r):e.removeChild(r)):yt.removeChild(r.stateNode));break;case 18:yt!==null&&(Er?(e=yt,r=r.stateNode,e.nodeType===8?pl(e.parentNode,r):e.nodeType===1&&pl(e,r),io(e)):pl(yt,r.stateNode));break;case 4:n=yt,i=Er,yt=r.stateNode.containerInfo,Er=!0,un(e,t,r),yt=n,Er=i;break;case 0:case 11:case 14:case 15:if(!kt&&(n=r.updateQueue,n!==null&&(n=n.lastEffect,n!==null))){i=n=n.next;do{var o=i,a=o.destroy;o=o.tag,a!==void 0&&(o&2||o&4)&&Dd(r,t,a),i=i.next}while(i!==n)}un(e,t,r);break;case 1:if(!kt&&(Bi(r,t),n=r.stateNode,typeof n.componentWillUnmount=="function"))try{n.props=r.memoizedProps,n.state=r.memoizedState,n.componentWillUnmount()}catch(u){Je(r,t,u)}un(e,t,r);break;case 21:un(e,t,r);break;case 22:r.mode&1?(kt=(n=kt)||r.memoizedState!==null,un(e,t,r),kt=n):un(e,t,r);break;default:un(e,t,r)}}function Yf(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var r=e.stateNode;r===null&&(r=e.stateNode=new ob),t.forEach(function(n){var i=gb.bind(null,e,n);r.has(n)||(r.add(n),n.then(i,i))})}}function wr(e,t){var r=t.deletions;if(r!==null)for(var n=0;ni&&(i=a),n&=~o}if(n=i,n=tt()-n,n=(120>n?120:480>n?480:1080>n?1080:1920>n?1920:3e3>n?3e3:4320>n?4320:1960*lb(n/1960))-n,10e?16:e,yn===null)var n=!1;else{if(e=yn,yn=null,au=0,Pe&6)throw Error(Y(331));var i=Pe;for(Pe|=4,ae=e.current;ae!==null;){var o=ae,a=o.child;if(ae.flags&16){var u=o.deletions;if(u!==null){for(var l=0;ltt()-Hp?Kn(e,0):Vp|=r),jt(e,t)}function mv(e,t){t===0&&(e.mode&1?(t=Jo,Jo<<=1,!(Jo&130023424)&&(Jo=4194304)):t=1);var r=Ot();e=tn(e,t),e!==null&&($o(e,t,r),jt(e,r))}function mb(e){var t=e.memoizedState,r=0;t!==null&&(r=t.retryLane),mv(e,r)}function gb(e,t){var r=0;switch(e.tag){case 13:var n=e.stateNode,i=e.memoizedState;i!==null&&(r=i.retryLane);break;case 19:n=e.stateNode;break;default:throw Error(Y(314))}n!==null&&n.delete(t),mv(e,r)}var gv;gv=function(e,t,r){if(e!==null)if(e.memoizedProps!==t.pendingProps||Ht.current)Vt=!0;else{if(!(e.lanes&r)&&!(t.flags&128))return Vt=!1,nb(e,t,r);Vt=!!(e.flags&131072)}else Vt=!1,Ke&&t.flags&1048576&&$y(t,Qs,t.index);switch(t.lanes=0,t.tag){case 2:var n=t.type;As(e,t),e=t.pendingProps;var i=qi(t,Et.current);Fi(t,r),i=Bp(null,t,n,e,i,r);var o=Dp();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,Ft(n)?(o=!0,Ks(t)):o=!1,t.memoizedState=i.state!==null&&i.state!==void 0?i.state:null,zp(t),i.updater=Eu,t.stateNode=i,i._reactInternals=t,Ad(t,n,e,r),t=Rd(null,t,n,!0,o,r)):(t.tag=0,Ke&&o&&Sp(t),It(null,t,i,r),t=t.child),t;case 16:n=t.elementType;e:{switch(As(e,t),e=t.pendingProps,i=n._init,n=i(n._payload),t.type=n,i=t.tag=vb(n),e=kr(n,e),i){case 0:t=Od(null,t,n,e,r);break e;case 1:t=Ff(null,t,n,e,r);break e;case 11:t=Vf(null,t,n,e,r);break e;case 14:t=Hf(null,t,n,kr(n.type,e),r);break e}throw Error(Y(306,n,""))}return t;case 0:return n=t.type,i=t.pendingProps,i=t.elementType===n?i:kr(n,i),Od(e,t,n,i,r);case 1:return n=t.type,i=t.pendingProps,i=t.elementType===n?i:kr(n,i),Ff(e,t,n,i,r);case 3:e:{if(Jy(t),e===null)throw Error(Y(387));n=t.pendingProps,o=t.memoizedState,i=o.element,Ey(e,t),Js(t,n,null,r);var a=t.memoizedState;if(n=a.element,o.isDehydrated)if(o={element:n,isDehydrated:!1,cache:a.cache,pendingSuspenseBoundaries:a.pendingSuspenseBoundaries,transitions:a.transitions},t.updateQueue.baseState=o,t.memoizedState=o,t.flags&256){i=Xi(Error(Y(423)),t),t=jf(e,t,n,r,i);break e}else if(n!==i){i=Xi(Error(Y(424)),t),t=jf(e,t,n,r,i);break e}else for(Zt=_n(t.stateNode.containerInfo.firstChild),Jt=t,Ke=!0,Cr=null,r=Sy(t,null,n,r),t.child=r;r;)r.flags=r.flags&-3|4096,r=r.sibling;else{if(Ki(),n===i){t=rn(e,t,r);break e}It(e,t,n,r)}t=t.child}return t;case 5:return Cy(t),e===null&&Cd(t),n=t.type,i=t.pendingProps,o=e!==null?e.memoizedProps:null,a=i.children,bd(n,i)?a=null:o!==null&&bd(n,o)&&(t.flags|=32),Zy(e,t),It(e,t,a,r),t.child;case 6:return e===null&&Cd(t),null;case 13:return ev(e,t,r);case 4:return Op(t,t.stateNode.containerInfo),n=t.pendingProps,e===null?t.child=Yi(t,null,n,r):It(e,t,n,r),t.child;case 11:return n=t.type,i=t.pendingProps,i=t.elementType===n?i:kr(n,i),Vf(e,t,n,i,r);case 7:return It(e,t,t.pendingProps,r),t.child;case 8:return It(e,t,t.pendingProps.children,r),t.child;case 12:return It(e,t,t.pendingProps.children,r),t.child;case 10:e:{if(n=t.type._context,i=t.pendingProps,o=t.memoizedProps,a=i.value,Ve(Xs,n._currentValue),n._currentValue=a,o!==null)if(Or(o.value,a)){if(o.children===i.children&&!Ht.current){t=rn(e,t,r);break e}}else for(o=t.child,o!==null&&(o.return=t);o!==null;){var u=o.dependencies;if(u!==null){a=o.child;for(var l=u.firstContext;l!==null;){if(l.context===n){if(o.tag===1){l=Xr(-1,r&-r),l.tag=2;var p=o.updateQueue;if(p!==null){p=p.shared;var f=p.pending;f===null?l.next=l:(l.next=f.next,f.next=l),p.pending=l}}o.lanes|=r,l=o.alternate,l!==null&&(l.lanes|=r),Td(o.return,r,t),u.lanes|=r;break}l=l.next}}else if(o.tag===10)a=o.type===t.type?null:o.child;else if(o.tag===18){if(a=o.return,a===null)throw Error(Y(341));a.lanes|=r,u=a.alternate,u!==null&&(u.lanes|=r),Td(a,r,t),a=o.sibling}else a=o.child;if(a!==null)a.return=o;else for(a=o;a!==null;){if(a===t){a=null;break}if(o=a.sibling,o!==null){o.return=a.return,a=o;break}a=a.return}o=a}It(e,t,i.children,r),t=t.child}return t;case 9:return i=t.type,n=t.pendingProps.children,Fi(t,r),i=dr(i),n=n(i),t.flags|=1,It(e,t,n,r),t.child;case 14:return n=t.type,i=kr(n,t.pendingProps),i=kr(n.type,i),Hf(e,t,n,i,r);case 15:return Qy(e,t,t.type,t.pendingProps,r);case 17:return n=t.type,i=t.pendingProps,i=t.elementType===n?i:kr(n,i),As(e,t),t.tag=1,Ft(n)?(e=!0,Ks(t)):e=!1,Fi(t,r),qy(t,n,i),Ad(t,n,i,r),Rd(null,t,n,!0,e,r);case 19:return tv(e,t,r);case 22:return Xy(e,t,r)}throw Error(Y(156,t.tag))};function yv(e,t){return F0(e,t)}function yb(e,t,r,n){this.tag=e,this.key=r,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=n,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function ur(e,t,r,n){return new yb(e,t,r,n)}function qp(e){return e=e.prototype,!(!e||!e.isReactComponent)}function vb(e){if(typeof e=="function")return qp(e)?1:0;if(e!=null){if(e=e.$$typeof,e===cp)return 11;if(e===fp)return 14}return 2}function kn(e,t){var r=e.alternate;return r===null?(r=ur(e.tag,t,e.key,e.mode),r.elementType=e.elementType,r.type=e.type,r.stateNode=e.stateNode,r.alternate=e,e.alternate=r):(r.pendingProps=t,r.type=e.type,r.flags=0,r.subtreeFlags=0,r.deletions=null),r.flags=e.flags&14680064,r.childLanes=e.childLanes,r.lanes=e.lanes,r.child=e.child,r.memoizedProps=e.memoizedProps,r.memoizedState=e.memoizedState,r.updateQueue=e.updateQueue,t=e.dependencies,r.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},r.sibling=e.sibling,r.index=e.index,r.ref=e.ref,r}function Rs(e,t,r,n,i,o){var a=2;if(n=e,typeof e=="function")qp(e)&&(a=1);else if(typeof e=="string")a=5;else e:switch(e){case Ci:return Yn(r.children,i,o,t);case pp:a=8,i|=8;break;case ed:return e=ur(12,r,t,i|2),e.elementType=ed,e.lanes=o,e;case td:return e=ur(13,r,t,i),e.elementType=td,e.lanes=o,e;case rd:return e=ur(19,r,t,i),e.elementType=rd,e.lanes=o,e;case C0:return Iu(r,i,o,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case k0:a=10;break e;case E0:a=9;break e;case cp:a=11;break e;case fp:a=14;break e;case cn:a=16,n=null;break e}throw Error(Y(130,e==null?e:typeof e,""))}return t=ur(a,r,t,i),t.elementType=e,t.type=n,t.lanes=o,t}function Yn(e,t,r,n){return e=ur(7,e,n,t),e.lanes=r,e}function Iu(e,t,r,n){return e=ur(22,e,n,t),e.elementType=C0,e.lanes=r,e.stateNode={isHidden:!1},e}function wl(e,t,r){return e=ur(6,e,null,t),e.lanes=r,e}function $l(e,t,r){return t=ur(4,e.children!==null?e.children:[],e.key,t),t.lanes=r,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function wb(e,t,r,n,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=el(0),this.expirationTimes=el(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=el(0),this.identifierPrefix=n,this.onRecoverableError=i,this.mutableSourceEagerHydrationData=null}function Kp(e,t,r,n,i,o,a,u,l){return e=new wb(e,t,r,u,l),t===1?(t=1,o===!0&&(t|=8)):t=0,o=ur(3,null,null,t),e.current=o,o.stateNode=e,o.memoizedState={element:n,isDehydrated:r,cache:null,transitions:null,pendingSuspenseBoundaries:null},zp(o),e}function $b(e,t,r){var n=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(_v)}catch(e){console.error(e)}}_v(),_0.exports=tr;var kb=_0.exports,nh=kb;Zl.createRoot=nh.createRoot,Zl.hydrateRoot=nh.hydrateRoot;/*! + * ONNX Runtime Web v1.18.0 + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */var Zp=Object.defineProperty,Eb=Object.getOwnPropertyDescriptor,Cb=Object.getOwnPropertyNames,Tb=Object.prototype.hasOwnProperty,Z=(e,t)=>()=>(e&&(t=e(e=0)),t),ia=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),aa=(e,t)=>{for(var r in t)Zp(e,r,{get:t[r],enumerable:!0})},Ib=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Cb(t))!Tb.call(e,i)&&i!==r&&Zp(e,i,{get:()=>t[i],enumerable:!(n=Eb(t,i))||n.enumerable});return e},Qn=e=>Ib(Zp({},"__esModule",{value:!0}),e),Aa,ln,Ni,ih,Jp,ec=Z(()=>{Aa=new Map,ln=[],Ni=(e,t,r)=>{if(t&&typeof t.init=="function"&&typeof t.createInferenceSessionHandler=="function"){let n=Aa.get(e);if(n===void 0)Aa.set(e,{backend:t,priority:r});else{if(n.priority>r)return;if(n.priority===r&&n.backend!==t)throw new Error(`cannot register backend "${e}" using priority ${r}`)}if(r>=0){let i=ln.indexOf(e);i!==-1&&ln.splice(i,1);for(let o=0;o{let t=Aa.get(e);if(!t)return"backend not found.";if(t.initialized)return t.backend;if(t.aborted)return t.error;{let r=!!t.initPromise;try{return r||(t.initPromise=t.backend.init(e)),await t.initPromise,t.initialized=!0,t.backend}catch(n){return r||(t.error=`${n}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},Jp=async e=>{let t=e.executionProviders||[],r=t.map(l=>typeof l=="string"?l:l.name),n=r.length===0?ln:r,i,o=[],a=new Set;for(let l of n){let p=await ih(l);typeof p=="string"?o.push({name:l,err:p}):(i||(i=p),i===p&&a.add(l))}if(!i)throw new Error(`no available backend found. ERR: ${o.map(l=>`[${l.name}] ${l.err}`).join(", ")}`);for(let{name:l,err:p}of o)r.includes(l)&&console.warn(`removing requested execution provider "${l}" from session options because it is not available: ${p}`);let u=t.filter(l=>a.has(typeof l=="string"?l:l.name));return[i,new Proxy(e,{get:(l,p)=>p==="executionProviders"?u:Reflect.get(l,p)})]}}),Ab=Z(()=>{ec()}),bv,zb=Z(()=>{bv="1.18.0"}),_l,ar,xv=Z(()=>{zb(),_l="warning",ar={wasm:{},webgl:{},webgpu:{},versions:{common:bv},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}`);_l=e}},get logLevel(){return _l}},Object.defineProperty(ar,"logLevel",{enumerable:!0})}),Ue,Ob=Z(()=>{xv(),Ue=ar}),Sv,kv,Rb=Z(()=>{Sv=(e,t)=>{let r=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);r.width=e.dims[3],r.height=e.dims[2];let n=r.getContext("2d");if(n!=null){let i,o;(t==null?void 0:t.tensorLayout)!==void 0&&t.tensorLayout==="NHWC"?(i=e.dims[2],o=e.dims[3]):(i=e.dims[3],o=e.dims[2]);let a=(t==null?void 0:t.format)!==void 0?t.format:"RGB",u=t==null?void 0:t.norm,l,p;u===void 0||u.mean===void 0?l=[255,255,255,255]:typeof u.mean=="number"?l=[u.mean,u.mean,u.mean,u.mean]:(l=[u.mean[0],u.mean[1],u.mean[2],0],u.mean[3]!==void 0&&(l[3]=u.mean[3])),u===void 0||u.bias===void 0?p=[0,0,0,0]:typeof u.bias=="number"?p=[u.bias,u.bias,u.bias,u.bias]:(p=[u.bias[0],u.bias[1],u.bias[2],0],u.bias[3]!==void 0&&(p[3]=u.bias[3]));let f=o*i,m=0,y=f,$=f*2,c=-1;a==="RGBA"?(m=0,y=f,$=f*2,c=f*3):a==="RGB"?(m=0,y=f,$=f*2):a==="RBG"&&(m=0,$=f,y=f*2);for(let x=0;x{let r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),n;if(r!=null){let i,o,a;(t==null?void 0:t.tensorLayout)!==void 0&&t.tensorLayout==="NHWC"?(i=e.dims[2],o=e.dims[1],a=e.dims[3]):(i=e.dims[3],o=e.dims[2],a=e.dims[1]);let u=t!==void 0&&t.format!==void 0?t.format:"RGB",l=t==null?void 0:t.norm,p,f;l===void 0||l.mean===void 0?p=[255,255,255,255]:typeof l.mean=="number"?p=[l.mean,l.mean,l.mean,l.mean]:(p=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(p[3]=l.mean[3])),l===void 0||l.bias===void 0?f=[0,0,0,0]:typeof l.bias=="number"?f=[l.bias,l.bias,l.bias,l.bias]:(f=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(f[3]=l.bias[3]));let m=o*i;if(t!==void 0&&(t.format!==void 0&&a===4&&t.format!=="RGBA"||a===3&&t.format!=="RGB"&&t.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let y=4,$=0,c=1,x=2,T=3,_=0,v=m,k=m*2,C=-1;u==="RGBA"?(_=0,v=m,k=m*2,C=m*3):u==="RGB"?(_=0,v=m,k=m*2):u==="RBG"&&(_=0,k=m,v=m*2),n=r.createImageData(i,o);for(let I=0;I{tc(),ps=(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:r,width:n}=t,i=t.norm??{mean:255,bias:0},o,a;typeof i.mean=="number"?o=[i.mean,i.mean,i.mean,i.mean]:o=[i.mean[0],i.mean[1],i.mean[2],i.mean[3]??255],typeof i.bias=="number"?a=[i.bias,i.bias,i.bias,i.bias]:a=[i.bias[0],i.bias[1],i.bias[2],i.bias[3]??0];let u=t.format!==void 0?t.format:"RGBA",l=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:"RGB",p=r*n,f=l==="RGBA"?new Float32Array(p*4):new Float32Array(p*3),m=4,y=0,$=1,c=2,x=3,T=0,_=p,v=p*2,k=-1;u==="RGB"&&(m=3,y=0,$=1,c=2,x=-1),l==="RGBA"?k=p*3:l==="RBG"?(T=0,v=p,_=p*2):l==="BGR"&&(v=0,_=p,T=p*2);for(let C=0;C{let r=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,n=typeof ImageData<"u"&&e instanceof ImageData,i=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,o=typeof e=="string",a,u=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")},p=f=>f instanceof HTMLCanvasElement||f instanceof OffscreenCanvas?f.getContext("2d"):null;if(r){let f=l();f.width=e.width,f.height=e.height;let m=p(f);if(m!=null){let y=e.height,$=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(y=t.resizedHeight,$=t.resizedWidth),t!==void 0){if(u=t,t.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");u.tensorFormat="RGBA",u.height=y,u.width=$}else u.tensorFormat="RGBA",u.height=y,u.width=$;m.drawImage(e,0,0),a=m.getImageData(0,0,$,y).data}else throw new Error("Can not access image data")}else if(n){let f,m;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(f=t.resizedHeight,m=t.resizedWidth):(f=e.height,m=e.width),t!==void 0&&(u=t),u.format="RGBA",u.height=f,u.width=m,t!==void 0){let y=l();y.width=m,y.height=f;let $=p(y);if($!=null)$.putImageData(e,0,0),a=$.getImageData(0,0,m,f).data;else throw new Error("Can not access image data")}else a=e.data}else if(i){if(t===void 0)throw new Error("Please provide image config with format for Imagebitmap");let f=l();f.width=e.width,f.height=e.height;let m=p(f);if(m!=null){let y=e.height,$=e.width;return m.drawImage(e,0,0,$,y),a=m.getImageData(0,0,$,y).data,u.height=y,u.width=$,ps(a,u)}else throw new Error("Can not access image data")}else{if(o)return new Promise((f,m)=>{let y=l(),$=p(y);if(!e||!$)return m();let c=new Image;c.crossOrigin="Anonymous",c.src=e,c.onload=()=>{y.width=c.width,y.height=c.height,$.drawImage(c,0,0,y.width,y.height);let x=$.getImageData(0,0,y.width,y.height);u.height=y.height,u.width=y.width,f(ps(x.data,u))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(a!==void 0)return ps(a,u);throw new Error("Input data provided is not supported - aborted tensor creation")},Cv=(e,t)=>{let{width:r,height:n,download:i,dispose:o}=t,a=[1,n,r,4];return new Tr({location:"texture",type:"float32",texture:e,dims:a,download:i,dispose:o})},Tv=(e,t)=>{let{dataType:r,dims:n,download:i,dispose:o}=t;return new Tr({location:"gpu-buffer",type:r??"float32",gpuBuffer:e,dims:n,download:i,dispose:o})},Iv=(e,t,r)=>new Tr({location:"cpu-pinned",type:e,data:t,dims:r??[t.length]})}),Hn,Va,bl,Av,Mb=Z(()=>{Hn=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array]]),Va=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),bl=!1,Av=()=>{if(!bl){bl=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,r=typeof Float16Array<"u"&&Float16Array.from;e&&(Hn.set("int64",BigInt64Array),Va.set(BigInt64Array,"int64")),t&&(Hn.set("uint64",BigUint64Array),Va.set(BigUint64Array,"uint64")),r?(Hn.set("float16",Float16Array),Va.set(Float16Array,"float16")):Hn.set("float16",Uint16Array)}}}),zv,Ov,Bb=Z(()=>{tc(),zv=e=>{let t=1;for(let r=0;r{switch(e.location){case"cpu":return new Tr(e.type,e.data,t);case"cpu-pinned":return new Tr({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new Tr({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new Tr({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),Tr,tc=Z(()=>{Rb(),Pb(),Mb(),Bb(),Tr=class{constructor(e,t,r){Av();let n,i;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,n=e.type,i=e.dims,e.location){case"cpu-pinned":{let a=Hn.get(n);if(!a)throw new TypeError(`unsupported type "${n}" to create tensor from pinned buffer`);if(!(e.data instanceof a))throw new TypeError(`buffer should be of type ${a.name}`);this.cpuData=e.data;break}case"texture":{if(n!=="float32")throw new TypeError(`unsupported type "${n}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break}case"gpu-buffer":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint8"&&n!=="bool")throw new TypeError(`unsupported type "${n}" 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 a,u;if(typeof e=="string")if(n=e,u=r,e==="string"){if(!Array.isArray(t))throw new TypeError("A string tensor's data must be a string array.");a=t}else{let l=Hn.get(e);if(l===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if(e==="float16"&&l===Uint16Array)throw new TypeError("Creating a float16 tensor from number array is not supported. Please use Uint16Array as data.");e==="uint64"||e==="int64"?a=l.from(t,BigInt):a=l.from(t)}else if(t instanceof l)a=t;else throw new TypeError(`A ${n} tensor's data must be type of ${l}`)}else if(u=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")n="string",a=e;else if(l==="boolean")n="bool",a=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${l}.`)}else{let l=Va.get(e.constructor);if(l===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);n=l,a=e}if(u===void 0)u=[a.length];else if(!Array.isArray(u))throw new TypeError("A tensor's dims must be a number array");i=u,this.cpuData=a,this.dataLocation="cpu"}let o=zv(i);if(this.cpuData&&o!==this.cpuData.length)throw new Error(`Tensor's size(${o}) does not match data length(${this.cpuData.length}).`);this.type=n,this.dims=i,this.size=o}static async fromImage(e,t){return Ev(e,t)}static fromTexture(e,t){return Cv(e,t)}static fromGpuBuffer(e,t){return Tv(e,t)}static fromPinnedBuffer(e,t,r){return Iv(e,t,r)}toDataURL(e){return Sv(this,e)}toImageData(e){return kv(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)}}}),zt,rc=Z(()=>{tc(),zt=Tr}),uu,xl,Lr,zr,Rv=Z(()=>{xv(),uu=(e,t)=>{(typeof ar.trace>"u"?!ar.wasm.trace:!ar.trace)||console.timeStamp(`${e}::ORT::${t}`)},xl=(e,t)=>{var i;let r=((i=new Error().stack)==null?void 0:i.split(/\r\n|\r|\n/g))||[],n=!1;for(let o=0;o{(typeof ar.trace>"u"?!ar.wasm.trace:!ar.trace)||xl("BEGIN",e)},zr=e=>{(typeof ar.trace>"u"?!ar.wasm.trace:!ar.trace)||xl("END",e)}}),Pv,Db=Z(()=>{ec(),rc(),Rv(),Pv=class Mv{constructor(t){this.handler=t}async run(t,r,n){Lr();let i={},o={};if(typeof t!="object"||t===null||t instanceof zt||Array.isArray(t))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let a=!0;if(typeof r=="object"){if(r===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(r instanceof zt)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(r)){if(r.length===0)throw new TypeError("'fetches' cannot be an empty array.");a=!1;for(let p of r){if(typeof p!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(p)===-1)throw new RangeError(`'fetches' contains invalid output name: ${p}.`);i[p]=null}if(typeof n=="object"&&n!==null)o=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else{let p=!1,f=Object.getOwnPropertyNames(r);for(let m of this.outputNames)if(f.indexOf(m)!==-1){let y=r[m];(y===null||y instanceof zt)&&(p=!0,a=!1,i[m]=y)}if(p){if(typeof n=="object"&&n!==null)o=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else o=r}}else if(typeof r<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let p of this.inputNames)if(typeof t[p]>"u")throw new Error(`input '${p}' is missing in 'feeds'.`);if(a)for(let p of this.outputNames)i[p]=null;let u=await this.handler.run(t,i,o),l={};for(let p in u)if(Object.hasOwnProperty.call(u,p)){let f=u[p];f instanceof zt?l[p]=f:l[p]=new zt(f.type,f.data,f.dims)}return zr(),l}async release(){return this.handler.dispose()}static async create(t,r,n,i){Lr();let o,a={};if(typeof t=="string"){if(o=t,typeof r=="object"&&r!==null)a=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof Uint8Array){if(o=t,typeof r=="object"&&r!==null)a=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer){let f=t,m=0,y=t.byteLength;if(typeof r=="object"&&r!==null)a=r;else if(typeof r=="number"){if(m=r,!Number.isSafeInteger(m))throw new RangeError("'byteOffset' must be an integer.");if(m<0||m>=f.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${f.byteLength}).`);if(y=t.byteLength-m,typeof n=="number"){if(y=n,!Number.isSafeInteger(y))throw new RangeError("'byteLength' must be an integer.");if(y<=0||m+y>f.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${f.byteLength-m}].`);if(typeof i=="object"&&i!==null)a=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else if(typeof n<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof r<"u")throw new TypeError("'options' must be an object.");o=new Uint8Array(f,m,y)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[u,l]=await Jp(a),p=await u.createInferenceSessionHandler(o,l);return zr(),new Mv(p)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}}),nc,Nb=Z(()=>{Db(),nc=Pv}),Wb=Z(()=>{}),Ub=Z(()=>{}),Lb=Z(()=>{}),Vb=Z(()=>{}),ah,Bv,Hb=Z(()=>{ec(),rc(),ah="Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.",Bv=class Dv{constructor(t,r,n){this.handler=t,this.hasOptimizerModel=r,this.hasEvalModel=n}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,r){let n=t.evalModel||"",i=t.optimizerModel||"",o=r||{},[a,u]=await Jp(o);if(a.createTrainingSessionHandler){let l=await a.createTrainingSessionHandler(t.checkpointState,t.trainModel,n,i,u);return new Dv(l,!!t.optimizerModel,!!t.evalModel)}else throw new Error(ah)}typeNarrowingForRunStep(t,r,n,i,o){let a={},u={};if(typeof n!="object"||n===null||n instanceof zt||Array.isArray(n))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 zt)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 p of i){if(typeof p!="string")throw new TypeError("'fetches' must be a string array or an object.");if(r.indexOf(p)===-1)throw new RangeError(`'fetches' contains invalid output name: ${p}.`);a[p]=null}if(typeof o=="object"&&o!==null)u=o;else if(typeof o<"u")throw new TypeError("'options' must be an object.")}else{let p=!1,f=Object.getOwnPropertyNames(i);for(let m of r)if(f.indexOf(m)!==-1){let y=i[m];(y===null||y instanceof zt)&&(p=!0,l=!1,a[m]=y)}if(p){if(typeof o=="object"&&o!==null)u=o;else if(typeof o<"u")throw new TypeError("'options' must be an object.")}else u=i}}else if(typeof i<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let p of t)if(typeof n[p]>"u")throw new Error(`input '${p}' is missing in 'feeds'.`);if(l)for(let p of r)a[p]=null;return[a,u]}convertHandlerReturnTypeToMapOfTensors(t){let r={};for(let n in t)if(Object.hasOwnProperty.call(t,n)){let i=t[n];i instanceof zt?r[n]=i:r[n]=new zt(i.type,i.data,i.dims)}return r}async lazyResetGrad(){await this.handler.lazyResetGrad()}async runTrainStep(t,r,n){let[i,o]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,t,r,n),a=await this.handler.runTrainStep(t,i,o);return this.convertHandlerReturnTypeToMapOfTensors(a)}async runOptimizerStep(t){if(this.hasOptimizerModel)await this.handler.runOptimizerStep(t||{});else throw new Error("This TrainingSession has no OptimizerModel loaded.")}async runEvalStep(t,r,n){if(this.hasEvalModel){let[i,o]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,t,r,n),a=await this.handler.runEvalStep(t,i,o);return this.convertHandlerReturnTypeToMapOfTensors(a)}else throw new Error("This TrainingSession has no EvalModel loaded.")}async getParametersSize(t=!0){return this.handler.getParametersSize(t)}async loadParametersBuffer(t,r=!0){let n=await this.getParametersSize(r);if(t.length!==4*n)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,r)}async getContiguousParameters(t=!0){return this.handler.getContiguousParameters(t)}async release(){return this.handler.dispose()}}}),Nv,Fb=Z(()=>{Hb(),Nv=Bv}),jb={};aa(jb,{InferenceSession:()=>nc,TRACE:()=>uu,TRACE_FUNC_BEGIN:()=>Lr,TRACE_FUNC_END:()=>zr,Tensor:()=>zt,TrainingSession:()=>Nv,env:()=>Ue,registerBackend:()=>Ni});var Rr=Z(()=>{Ab(),Ob(),Nb(),rc(),Wb(),Ub(),Rv(),Lb(),Vb(),Fb()}),ic={};aa(ic,{createReadStream:()=>Lv,readFile:()=>Wv,readFileSync:()=>Uv});var Wv,Uv,Lv,Vv=Z(()=>{Wv=void 0,Uv=void 0,Lv=void 0}),ac={};aa(ac,{join:()=>Hv});var Hv,Fv=Z(()=>{Hv=void 0}),Gb=ia((e,t)=>{var r=(()=>{var i;var n=typeof document<"u"?(i=document.currentScript)==null?void 0:i.src:void 0;return typeof __filename<"u"&&(n||(n=__filename)),function(o={}){var a=o,u,l,p=new Promise((d,g)=>{u=d,l=g});a.mountExternalData=(d,g)=>{(a.eb||(a.eb=new Map)).set(d,g)},a.unmountExternalData=()=>{delete a.eb};let f=()=>{let d=(b,E,z)=>(...D)=>{let j=Dt,X=E==null?void 0:E();D=b(...D);let ne=E==null?void 0:E();return X!==ne&&(b=ne,z(X),E=z=null),Dt!=j?Po():D},g=b=>async(...E)=>{var z;try{if(a.cb)throw Error("Session already started");let D=a.cb={xb:E[0],errors:[]},j=await b(...E);if(a.cb!==D)throw Error("Session mismatch");(z=a.kb)==null||z.flush();let X=D.errors;if(0te),0a._OrtCreateSession,b=>a._OrtCreateSession=b),a._OrtRun=g(d(a._OrtRun,()=>a._OrtRun,b=>a._OrtRun=b)),a._OrtRunWithBinding=g(d(a._OrtRunWithBinding,()=>a._OrtRunWithBinding,b=>a._OrtRunWithBinding=b)),a._OrtBindInput=d(a._OrtBindInput,()=>a._OrtBindInput,b=>a._OrtBindInput=b),f=void 0};a.jsepInit=(d,g)=>{if(f==null||f(),d==="webgpu"){[a.kb,a.pb,a.tb,a.lb,a.sb,a.Ra,a.ub,a.wb,a.qb,a.rb,a.vb]=g;let b=a.kb;a.jsepRegisterBuffer=(E,z,D,j)=>b.registerBuffer(E,z,D,j),a.jsepGetBuffer=E=>b.getBuffer(E),a.jsepCreateDownloader=(E,z,D)=>b.createDownloader(E,z,D),a.jsepOnReleaseSession=E=>{b.onReleaseSession(E)},a.jsepOnRunStart=E=>b.onRunStart(E)}};var m=Object.assign({},a),y="./this.program",$=(d,g)=>{throw g},c=typeof window=="object",x=typeof importScripts=="function",T=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",_="",v,k,C;if(T){var I=(Vv(),Qn(ic)),M=(Fv(),Qn(ac));_=x?M.dirname(_)+"/":__dirname+"/",v=(d,g)=>(d=Gt(d)?new URL(d):M.normalize(d),I.readFileSync(d,g?void 0:"utf8")),C=d=>(d=v(d,!0),d.buffer||(d=new Uint8Array(d)),d),k=(d,g,b,E=!0)=>{d=Gt(d)?new URL(d):M.normalize(d),I.readFile(d,E?void 0:"utf8",(z,D)=>{z?b(z):g(E?D.buffer:D)})},!a.thisProgram&&1{throw process.exitCode=d,g}}else(c||x)&&(x?_=self.location.href:typeof document<"u"&&document.currentScript&&(_=document.currentScript.src),n&&(_=n),_.startsWith("blob:")?_="":_=_.substr(0,_.replace(/[?#].*/,"").lastIndexOf("/")+1),v=d=>{var g=new XMLHttpRequest;return g.open("GET",d,!1),g.send(null),g.responseText},x&&(C=d=>{var g=new XMLHttpRequest;return g.open("GET",d,!1),g.responseType="arraybuffer",g.send(null),new Uint8Array(g.response)}),k=(d,g,b)=>{var E=new XMLHttpRequest;E.open("GET",d,!0),E.responseType="arraybuffer",E.onload=()=>{E.status==200||E.status==0&&E.response?g(E.response):b()},E.onerror=b,E.send(null)});var P=console.log.bind(console),B=console.error.bind(console);Object.assign(a,m),m=null;var H,F=!1,me,ce,se,xe,ze,V,le,U,J,Q,R;function ee(){var d=H.buffer;a.HEAP8=ce=new Int8Array(d),a.HEAP16=xe=new Int16Array(d),a.HEAPU8=se=new Uint8Array(d),a.HEAPU16=ze=new Uint16Array(d),a.HEAP32=V=new Int32Array(d),a.HEAPU32=le=new Uint32Array(d),a.HEAPF32=U=new Float32Array(d),a.HEAPF64=R=new Float64Array(d),a.HEAP64=J=new BigInt64Array(d),a.HEAPU64=Q=new BigUint64Array(d)}var oe=[],we=[],Ce=[],Le=0,st=null;function ut(d){throw d="Aborted("+d+")",B(d),F=!0,me=1,d=new WebAssembly.RuntimeError(d+". Build with -sASSERTIONS for more info."),l(d),d}var cr=d=>d.startsWith("data:application/octet-stream;base64,"),Gt=d=>d.startsWith("file://"),fr;if(fr="ort-wasm-simd.wasm",!cr(fr)){var He=fr;fr=a.locateFile?a.locateFile(He,_):_+He}function lt(d){if(C)return C(d);throw"both async and sync fetching of the wasm failed"}function hr(d){if(c||x){if(typeof fetch=="function"&&!Gt(d))return fetch(d,{credentials:"same-origin"}).then(g=>{if(!g.ok)throw`failed to load wasm binary file at '${d}'`;return g.arrayBuffer()}).catch(()=>lt(d));if(k)return new Promise((g,b)=>{k(d,E=>g(new Uint8Array(E)),b)})}return Promise.resolve().then(()=>lt(d))}function _t(d,g,b){return hr(d).then(E=>WebAssembly.instantiate(E,g)).then(b,E=>{B(`failed to asynchronously prepare wasm: ${E}`),ut(E)})}function li(d,g){var b=fr;return typeof WebAssembly.instantiateStreaming!="function"||cr(b)||Gt(b)||T||typeof fetch!="function"?_t(b,d,g):fetch(b,{credentials:"same-origin"}).then(E=>WebAssembly.instantiateStreaming(E,d).then(g,function(z){return B(`wasm streaming compile failed: ${z}`),B("falling back to ArrayBuffer instantiation"),_t(b,d,g)}))}var di={824920:(d,g,b,E)=>{if(typeof a>"u"||!a.eb)return 1;if(d=Ye(d>>>0),d.startsWith("./")&&(d=d.substring(2)),d=a.eb.get(d),!d)return 2;if(g>>>=0,b>>>=0,g+b>d.byteLength)return 3;try{return se.set(d.subarray(g,g+b),E>>>0>>>0),0}catch{return 4}},825421:()=>{a.qb()},825452:()=>{a.rb()},825481:()=>{a.vb()},825506:d=>a.pb(d),825539:d=>a.tb(d),825571:(d,g,b)=>{a.lb(d,g,b,!0)},825610:(d,g,b)=>{a.lb(d,g,b)},825643:d=>{a.Ra("Abs",d,void 0)},825694:d=>{a.Ra("Neg",d,void 0)},825745:d=>{a.Ra("Floor",d,void 0)},825798:d=>{a.Ra("Ceil",d,void 0)},825850:d=>{a.Ra("Reciprocal",d,void 0)},825908:d=>{a.Ra("Sqrt",d,void 0)},825960:d=>{a.Ra("Exp",d,void 0)},826011:d=>{a.Ra("Erf",d,void 0)},826062:d=>{a.Ra("Sigmoid",d,void 0)},826117:(d,g,b)=>{a.Ra("HardSigmoid",d,{alpha:g,beta:b})},826196:d=>{a.Ra("Log",d,void 0)},826247:d=>{a.Ra("Sin",d,void 0)},826298:d=>{a.Ra("Cos",d,void 0)},826349:d=>{a.Ra("Tan",d,void 0)},826400:d=>{a.Ra("Asin",d,void 0)},826452:d=>{a.Ra("Acos",d,void 0)},826504:d=>{a.Ra("Atan",d,void 0)},826556:d=>{a.Ra("Sinh",d,void 0)},826608:d=>{a.Ra("Cosh",d,void 0)},826660:d=>{a.Ra("Asinh",d,void 0)},826713:d=>{a.Ra("Acosh",d,void 0)},826766:d=>{a.Ra("Atanh",d,void 0)},826819:d=>{a.Ra("Tanh",d,void 0)},826871:d=>{a.Ra("Not",d,void 0)},826922:(d,g,b)=>{a.Ra("Clip",d,{min:g,max:b})},826991:d=>{a.Ra("Clip",d,void 0)},827043:(d,g)=>{a.Ra("Elu",d,{alpha:g})},827101:d=>{a.Ra("Relu",d,void 0)},827153:(d,g)=>{a.Ra("LeakyRelu",d,{alpha:g})},827217:(d,g)=>{a.Ra("ThresholdedRelu",d,{alpha:g})},827287:(d,g)=>{a.Ra("Cast",d,{to:g})},827345:d=>{a.Ra("Add",d,void 0)},827396:d=>{a.Ra("Sub",d,void 0)},827447:d=>{a.Ra("Mul",d,void 0)},827498:d=>{a.Ra("Div",d,void 0)},827549:d=>{a.Ra("Pow",d,void 0)},827600:d=>{a.Ra("Equal",d,void 0)},827653:d=>{a.Ra("Greater",d,void 0)},827708:d=>{a.Ra("GreaterOrEqual",d,void 0)},827770:d=>{a.Ra("Less",d,void 0)},827822:d=>{a.Ra("LessOrEqual",d,void 0)},827881:(d,g,b,E,z)=>{a.Ra("ReduceMean",d,{keepDims:!!g,noopWithEmptyAxes:!!b,axes:E?Array.from(V.subarray(E>>>0,z>>>0)):[]})},828040:(d,g,b,E,z)=>{a.Ra("ReduceMax",d,{keepDims:!!g,noopWithEmptyAxes:!!b,axes:E?Array.from(V.subarray(E>>>0,z>>>0)):[]})},828198:(d,g,b,E,z)=>{a.Ra("ReduceMin",d,{keepDims:!!g,noopWithEmptyAxes:!!b,axes:E?Array.from(V.subarray(E>>>0,z>>>0)):[]})},828356:(d,g,b,E,z)=>{a.Ra("ReduceProd",d,{keepDims:!!g,noopWithEmptyAxes:!!b,axes:E?Array.from(V.subarray(E>>>0,z>>>0)):[]})},828515:(d,g,b,E,z)=>{a.Ra("ReduceSum",d,{keepDims:!!g,noopWithEmptyAxes:!!b,axes:E?Array.from(V.subarray(E>>>0,z>>>0)):[]})},828673:(d,g,b,E,z)=>{a.Ra("ReduceL1",d,{keepDims:!!g,noopWithEmptyAxes:!!b,axes:E?Array.from(V.subarray(E>>>0,z>>>0)):[]})},828830:(d,g,b,E,z)=>{a.Ra("ReduceL2",d,{keepDims:!!g,noopWithEmptyAxes:!!b,axes:E?Array.from(V.subarray(E>>>0,z>>>0)):[]})},828987:(d,g,b,E,z)=>{a.Ra("ReduceLogSum",d,{keepDims:!!g,noopWithEmptyAxes:!!b,axes:E?Array.from(V.subarray(E>>>0,z>>>0)):[]})},829148:(d,g,b,E,z)=>{a.Ra("ReduceSumSquare",d,{keepDims:!!g,noopWithEmptyAxes:!!b,axes:E?Array.from(V.subarray(E>>>0,z>>>0)):[]})},829312:(d,g,b,E,z)=>{a.Ra("ReduceLogSumExp",d,{keepDims:!!g,noopWithEmptyAxes:!!b,axes:E?Array.from(V.subarray(E>>>0,z>>>0)):[]})},829476:d=>{a.Ra("Where",d,void 0)},829529:(d,g,b)=>{a.Ra("Transpose",d,{perm:g?Array.from(V.subarray(g>>>0,b>>>0)):[]})},829637:(d,g,b,E)=>{a.Ra("DepthToSpace",d,{blocksize:g,mode:Ye(b),format:E?"NHWC":"NCHW"})},829770:(d,g,b,E)=>{a.Ra("DepthToSpace",d,{blocksize:g,mode:Ye(b),format:E?"NHWC":"NCHW"})},829903:(d,g,b,E,z,D,j,X,ne,te,de,Ae,Be,N,$e)=>{a.Ra("ConvTranspose",d,{format:ne?"NHWC":"NCHW",autoPad:g,dilations:[b],group:E,kernelShape:[z],pads:[D,j],strides:[X],wIsConst:()=>!!ce[te>>>0],outputPadding:de?Array.from(V.subarray(de>>>0,Ae>>>0)):[],outputShape:Be?Array.from(V.subarray(Be>>>0,N>>>0)):[],activation:Ye($e)})},830304:(d,g,b,E,z,D,j,X,ne,te,de,Ae,Be,N)=>{a.Ra("ConvTranspose",d,{format:X?"NHWC":"NCHW",autoPad:g,dilations:Array.from(V.subarray(b>>>0,(b>>>0)+2>>>0)),group:E,kernelShape:Array.from(V.subarray(z>>>0,(z>>>0)+2>>>0)),pads:Array.from(V.subarray(D>>>0,(D>>>0)+4>>>0)),strides:Array.from(V.subarray(j>>>0,(j>>>0)+2>>>0)),wIsConst:()=>!!ce[ne>>>0],outputPadding:te?Array.from(V.subarray(te>>>0,de>>>0)):[],outputShape:Ae?Array.from(V.subarray(Ae>>>0,Be>>>0)):[],activation:Ye(N)})},830869:(d,g,b,E,z,D,j,X,ne,te,de,Ae,Be,N,$e)=>{a.Ra("ConvTranspose",d,{format:ne?"NHWC":"NCHW",autoPad:g,dilations:[b],group:E,kernelShape:[z],pads:[D,j],strides:[X],wIsConst:()=>!!ce[te>>>0],outputPadding:de?Array.from(V.subarray(de>>>0,Ae>>>0)):[],outputShape:Be?Array.from(V.subarray(Be>>>0,N>>>0)):[],activation:Ye($e)})},831270:(d,g,b,E,z,D,j,X,ne,te,de,Ae,Be,N)=>{a.Ra("ConvTranspose",d,{format:X?"NHWC":"NCHW",autoPad:g,dilations:Array.from(V.subarray(b>>>0,(b>>>0)+2>>>0)),group:E,kernelShape:Array.from(V.subarray(z>>>0,(z>>>0)+2>>>0)),pads:Array.from(V.subarray(D>>>0,(D>>>0)+4>>>0)),strides:Array.from(V.subarray(j>>>0,(j>>>0)+2>>>0)),wIsConst:()=>!!ce[ne>>>0],outputPadding:te?Array.from(V.subarray(te>>>0,de>>>0)):[],outputShape:Ae?Array.from(V.subarray(Ae>>>0,Be>>>0)):[],activation:Ye(N)})},831835:(d,g)=>{a.Ra("GlobalAveragePool",d,{format:g?"NHWC":"NCHW"})},831926:(d,g,b,E,z,D,j,X,ne,te,de,Ae,Be,N,$e,Ie)=>{a.Ra("AveragePool",d,{format:Ie?"NHWC":"NCHW",auto_pad:g,ceil_mode:b,count_include_pad:E,storage_order:z,dilations:[D,j],kernel_shape:[X,ne],pads:[te,de,Ae,Be],strides:[N,$e]})},832210:(d,g)=>{a.Ra("GlobalAveragePool",d,{format:g?"NHWC":"NCHW"})},832301:(d,g,b,E,z,D,j,X,ne,te,de,Ae,Be,N,$e,Ie)=>{a.Ra("AveragePool",d,{format:Ie?"NHWC":"NCHW",auto_pad:g,ceil_mode:b,count_include_pad:E,storage_order:z,dilations:[D,j],kernel_shape:[X,ne],pads:[te,de,Ae,Be],strides:[N,$e]})},832585:(d,g)=>{a.Ra("GlobalMaxPool",d,{format:g?"NHWC":"NCHW"})},832672:(d,g,b,E,z,D,j,X,ne,te,de,Ae,Be,N,$e,Ie)=>{a.Ra("MaxPool",d,{format:Ie?"NHWC":"NCHW",auto_pad:g,ceil_mode:b,count_include_pad:E,storage_order:z,dilations:[D,j],kernel_shape:[X,ne],pads:[te,de,Ae,Be],strides:[N,$e]})},832952:(d,g)=>{a.Ra("GlobalMaxPool",d,{format:g?"NHWC":"NCHW"})},833039:(d,g,b,E,z,D,j,X,ne,te,de,Ae,Be,N,$e,Ie)=>{a.Ra("MaxPool",d,{format:Ie?"NHWC":"NCHW",auto_pad:g,ceil_mode:b,count_include_pad:E,storage_order:z,dilations:[D,j],kernel_shape:[X,ne],pads:[te,de,Ae,Be],strides:[N,$e]})},833319:(d,g,b,E,z)=>{a.Ra("Gemm",d,{alpha:g,beta:b,transA:E,transB:z})},833423:d=>{a.Ra("MatMul",d,void 0)},833477:(d,g,b,E)=>{a.Ra("ArgMax",d,{keepDims:!!g,selectLastIndex:!!b,axis:E})},833585:(d,g,b,E)=>{a.Ra("ArgMin",d,{keepDims:!!g,selectLastIndex:!!b,axis:E})},833693:(d,g)=>{a.Ra("Softmax",d,{axis:g})},833756:(d,g)=>{a.Ra("Concat",d,{axis:g})},833816:(d,g,b,E,z)=>{a.Ra("Split",d,{axis:g,numOutputs:b,splitSizes:E?Array.from(V.subarray(E>>>0,z>>>0)):[]})},833956:d=>{a.Ra("Expand",d,void 0)},834010:(d,g)=>{a.Ra("Gather",d,{axis:Number(g)})},834081:(d,g)=>{a.Ra("GatherElements",d,{axis:Number(g)})},834160:(d,g,b,E,z,D,j,X,ne,te,de)=>{a.Ra("Resize",d,{antialias:g,axes:b?Array.from(V.subarray(b>>>0,E>>>0)):[],coordinateTransformMode:Ye(z),cubicCoeffA:D,excludeOutside:j,extrapolationValue:X,keepAspectRatioPolicy:Ye(ne),mode:Ye(te),nearestMode:Ye(de)})},834506:(d,g,b,E,z,D,j)=>{a.Ra("Slice",d,{starts:g?Array.from(V.subarray(g>>>0,b>>>0)):[],ends:E?Array.from(V.subarray(E>>>0,z>>>0)):[],axes:D?Array.from(V.subarray(D>>>0,j>>>0)):[]})},834722:d=>{a.Ra("Tile",d,void 0)},834774:(d,g,b,E)=>{a.Ra("LayerNormalization",d,{axis:g,epsilon:b,simplified:!!E})},834885:(d,g,b)=>{a.Ra("InstanceNormalization",d,{epsilon:g,format:b?"NHWC":"NCHW"})},834999:(d,g,b)=>{a.Ra("InstanceNormalization",d,{epsilon:g,format:b?"NHWC":"NCHW"})},835113:d=>{a.Ra("Range",d,void 0)},835166:(d,g)=>{a.Ra("Einsum",d,{equation:Ye(g)})},835247:(d,g,b,E,z)=>{a.Ra("Pad",d,{mode:g,value:b,pads:E?Array.from(V.subarray(E>>>0,z>>>0)):[]})},835374:(d,g,b,E,z,D)=>{a.Ra("BatchNormalization",d,{epsilon:g,momentum:b,spatial:!!z,trainingMode:!!E,format:D?"NHWC":"NCHW"})},835543:(d,g,b,E,z,D)=>{a.Ra("BatchNormalization",d,{epsilon:g,momentum:b,spatial:!!z,trainingMode:!!E,format:D?"NHWC":"NCHW"})},835712:(d,g,b)=>{a.Ra("CumSum",d,{exclusive:Number(g),reverse:Number(b)})},835809:(d,g,b,E,z,D,j,X,ne)=>{a.Ra("Attention",d,{numHeads:g,isUnidirectional:b,maskFilterValue:E,scale:z,doRotary:D,qkvHiddenSizes:j?Array.from(V.subarray(Number(X)>>>0,Number(X)+j>>>0)):[],pastPresentShareBuffer:!!ne})},836081:d=>{a.Ra("BiasAdd",d,void 0)},836136:d=>{a.Ra("BiasSplitGelu",d,void 0)},836197:d=>{a.Ra("FastGelu",d,void 0)},836253:(d,g,b,E,z,D,j,X,ne,te,de,Ae,Be)=>{a.Ra("Conv",d,{format:ne?"NHWC":"NCHW",auto_pad:g,dilations:[b],group:E,kernel_shape:[z],pads:D?Array.from(V.subarray(D>>>0,j>>>0)):[],strides:[X],w_is_const:()=>!!ce[te>>>0],activation:Ye(de),activation_params:Ae?Array.from(U.subarray(Ae>>>0,Be>>>0)):[]})},836623:(d,g,b,E,z,D,j,X,ne,te,de,Ae,Be,N,$e,Ie)=>{a.Ra("Conv",d,{format:Ae?"NHWC":"NCHW",auto_pad:g,dilations:[b,E],group:z,kernel_shape:[D,j],pads:X?Array.from(V.subarray(X>>>0,ne>>>0)):[],strides:[te,de],w_is_const:()=>!!ce[Be>>>0],activation:Ye(N),activation_params:$e?Array.from(U.subarray($e>>>0,Ie>>>0)):[]})},837014:d=>{a.Ra("Gelu",d,void 0)},837066:(d,g,b,E,z,D)=>{a.Ra("MatMulNBits",d,{k:g,n:b,accuracyLevel:E,bits:z,blockSize:D})},837193:(d,g,b,E,z,D)=>{a.Ra("MultiHeadAttention",d,{numHeads:g,isUnidirectional:b,maskFilterValue:E,scale:z,doRotary:D})},837352:(d,g,b,E,z)=>{a.Ra("RotaryEmbedding",d,{interleaved:!!g,numHeads:b,rotaryEmbeddingDim:E,scale:z})},837491:(d,g,b)=>{a.Ra("SkipLayerNormalization",d,{epsilon:g,simplified:!!b})},837593:(d,g,b)=>{a.Ra("SkipLayerNormalization",d,{epsilon:g,simplified:!!b})},837695:(d,g,b,E)=>{a.Ra("LayerNormalization",d,{axis:g,epsilon:b,simplified:!!E})},837806:d=>{a.ub(d)},837840:(d,g)=>a.wb(d,g,a.cb.xb,a.cb.errors)};function On(d){this.name="ExitStatus",this.message=`Program terminated with exit(${d})`,this.status=d}class Mu{constructor(g){this.hb=g-24}}var Vr=0,an=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,oa=(d,g,b)=>{g>>>=0;var E=g+b;for(b=g;d[b]&&!(b>=E);)++b;if(16z?E+=String.fromCharCode(z):(z-=65536,E+=String.fromCharCode(55296|z>>10,56320|z&1023))}}else E+=String.fromCharCode(z)}return E},Ye=(d,g)=>(d>>>=0)?oa(se,d,g):"",pi=d=>{for(var g=0,b=0;b=E?g++:2047>=E?g+=2:55296<=E&&57343>=E?(g+=4,++b):g+=3}return g},nr=(d,g,b,E)=>{if(b>>>=0,!(0=j){var X=d.charCodeAt(++D);j=65536+((j&1023)<<10)|X&1023}if(127>=j){if(b>=E)break;g[b++>>>0]=j}else{if(2047>=j){if(b+1>=E)break;g[b++>>>0]=192|j>>6}else{if(65535>=j){if(b+2>=E)break;g[b++>>>0]=224|j>>12}else{if(b+3>=E)break;g[b++>>>0]=240|j>>18,g[b++>>>0]=128|j>>12&63}g[b++>>>0]=128|j>>6&63}g[b++>>>0]=128|j&63}}return g[b>>>0]=0,b-z},on,qt=d=>{for(var g="";se[d>>>0];)g+=on[se[d++>>>0]];return g},sa={},ci={},Pr;function ua(d,g,b={}){var E=g.name;if(!d)throw new Pr(`type "${E}" must have a positive integer typeid pointer`);if(ci.hasOwnProperty(d)){if(b.nb)return;throw new Pr(`Cannot register type '${E}' twice`)}ci[d]=g,sa.hasOwnProperty(d)&&(g=sa[d],delete sa[d],g.forEach(z=>z()))}function Mt(d,g,b={}){if(!("argPackAdvance"in g))throw new TypeError("registerType registeredInstance requires argPackAdvance");return ua(d,g,b)}var fi=(d,g,b)=>{switch(g){case 1:return b?E=>ce[E>>>0]:E=>se[E>>>0];case 2:return b?E=>xe[E>>>1>>>0]:E=>ze[E>>>1>>>0];case 4:return b?E=>V[E>>>2>>>0]:E=>le[E>>>2>>>0];case 8:return b?E=>J[E>>>3]:E=>Q[E>>>3];default:throw new TypeError(`invalid integer width (${g}): ${d}`)}},hi=[],ct=[];function la(d){d>>>=0,9{if(!d)throw new Pr("Cannot use deleted val. handle = "+d);return ct[d]},Bt=d=>{switch(d){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let g=hi.pop()||ct.length;return ct[g]=d,ct[g+1]=1,g}};function Rn(d){return this.fromWireType(le[d>>>2>>>0])}var Bu={name:"emscripten::val",fromWireType:d=>{var g=ke(d);return la(d),g},toWireType:(d,g)=>Bt(g),argPackAdvance:8,readValueFromPointer:Rn,bb:null},Eo=(d,g)=>{switch(g){case 4:return function(b){return this.fromWireType(U[b>>>2>>>0])};case 8:return function(b){return this.fromWireType(R[b>>>3>>>0])};default:throw new TypeError(`invalid float width (${g}): ${d}`)}},Co=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,ye=(d,g)=>{for(var b=d>>1,E=b+g/2;!(b>=E)&&ze[b>>>0];)++b;if(b<<=1,32>>0,b>>>0));for(b="",E=0;!(E>=g/2);++E){var z=xe[d+2*E>>>1>>>0];if(z==0)break;b+=String.fromCharCode(z)}return b},mi=(d,g,b)=>{if(b??(b=2147483647),2>b)return 0;b-=2;var E=g;b=b<2*d.length?b/2:d.length;for(var z=0;z>>1>>>0]=d.charCodeAt(z),g+=2;return xe[g>>>1>>>0]=0,g-E},To=d=>2*d.length,Du=(d,g)=>{for(var b=0,E="";!(b>=g/4);){var z=V[d+4*b>>>2>>>0];if(z==0)break;++b,65536<=z?(z-=65536,E+=String.fromCharCode(55296|z>>10,56320|z&1023)):E+=String.fromCharCode(z)}return E},Io=(d,g,b)=>{if(g>>>=0,b??(b=2147483647),4>b)return 0;var E=g;b=E+b-4;for(var z=0;z=D){var j=d.charCodeAt(++z);D=65536+((D&1023)<<10)|j&1023}if(V[g>>>2>>>0]=D,g+=4,g+4>b)break}return V[g>>>2>>>0]=0,g-E},Ao=d=>{for(var g=0,b=0;b=E&&++b,g+=4}return g},gi=(d,g)=>{var b=ci[d];if(b===void 0)throw d=wa(d),b=qt(d),Ct(d),new Pr(`${g} has unknown type ${b}`);return b},da=(d,g,b)=>{var E=[];return d=d.toWireType(E,b),E.length&&(le[g>>>2>>>0]=Bt(E)),d},Pn=d=>{try{d()}catch(g){ut(g)}},nt=d=>{var g;if(!F)try{d();try{me=me=d=me,(g=a.onExit)==null||g.call(a,d),F=!0,$(d,new On(d))}catch(b){b instanceof On||b=="unwind"||$(1,b)}}catch(b){b instanceof On||b=="unwind"||$(1,b)}};function zo(){var d=ge,g={};for(let[b,E]of Object.entries(d))g[b]=typeof E=="function"?(...z)=>{gr.push(b);try{return E(...z)}finally{F||(gr.pop(),Dt&&mr===1&&gr.length===0&&(mr=0,Pn(Lo),typeof Fibers<"u"&&Fibers.Db()))}}:E;return g}var mr=0,Dt=null,pa=0,gr=[],ca={},fa={},Oo=0,yi=null,Ro=[];function Po(){return new Promise((d,g)=>{yi={resolve:d,reject:g}})}function Mo(){var d=sn(65548),g=d+12;le[d>>>2>>>0]=g,le[d+4>>>2>>>0]=g+65536,g=gr[0];var b=ca[g];return b===void 0&&(b=Oo++,ca[g]=b,fa[b]=g),V[d+8>>>2>>>0]=b,d}function Bo(d){if(!F){if(mr===0){var g=!1,b=!1;d((E=0)=>{if(!F&&(pa=E,g=!0,b)){mr=2,Pn(()=>vr(Dt)),typeof Browser<"u"&&Browser.ib.mb&&Browser.ib.resume(),E=!1;try{var z=(0,ge[fa[V[Dt+8>>>2>>>0]]])()}catch(X){z=X,E=!0}var D=!1;if(!Dt){var j=yi;j&&(yi=null,(E?j.reject:j.resolve)(z),D=!0)}if(E&&!D)throw z}}),b=!0,g||(mr=1,Dt=Mo(),typeof Browser<"u"&&Browser.ib.mb&&Browser.ib.pause(),Pn(()=>Dn(Dt)))}else mr===2?(mr=0,Pn(Qt),Ct(Dt),Dt=null,Ro.forEach(nt)):ut(`invalid state: ${mr}`);return pa}}function ha(d){return Bo(g=>{d().then(g)})}var Mn=[],Do={},vi=d=>{var g=Do[d];return g===void 0?qt(d):g},Kt=()=>typeof globalThis=="object"?globalThis:Function("return this")(),ma=d=>{var g=Mn.length;return Mn.push(d),g},ga=(d,g)=>{for(var b=Array(d),E=0;E>>2>>>0],"parameter "+E);return b},yr=(d,g)=>Object.defineProperty(g,"name",{value:d});function Nu(d){var g=Function;if(!(g instanceof Function))throw new TypeError(`new_ called with constructor type ${typeof g} which is not a function`);var b=yr(g.name||"unknownFunctionName",function(){});return b.prototype=g.prototype,b=new b,d=g.apply(b,d),d instanceof Object?d:b}var bt=d=>d%4===0&&(d%100!==0||d%400===0),ya=[0,31,60,91,121,152,182,213,244,274,305,335],wi=[0,31,59,90,120,151,181,212,243,273,304,334],Yt=[],$i=(d,g)=>{Yt.length=0;for(var b;b=se[d++>>>0];){var E=b!=105;E&=b!=112,g+=E&&g%8?4:0,Yt.push(b==112?le[g>>>2>>>0]:b==106?J[g>>>3]:b==105?V[g>>>2>>>0]:R[g>>>3>>>0]),g+=E?8:4}return Yt},ft={},Nt=()=>{if(!Bn){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",_:y||"./this.program"},g;for(g in ft)ft[g]===void 0?delete d[g]:d[g]=ft[g];var b=[];for(g in d)b.push(`${g}=${d[g]}`);Bn=b}return Bn},Bn,Wu=[null,[],[]],No=[31,29,31,30,31,30,31,31,30,31,30,31],va=[31,28,31,30,31,30,31,31,30,31,30,31];function Uu(d){var g=Array(pi(d)+1);return nr(d,g,0,g.length),g}function Wo(d,g,b,E){function z(N,$e,Ie){for(N=typeof N=="number"?N.toString():N||"";N.length<$e;)N=Ie[0]+N;return N}function D(N,$e){return z(N,$e,"0")}function j(N,$e){function Ie(jr){return 0>jr?-1:0Fr-N.getDate())$e-=Fr-N.getDate()+1,N.setDate(1),11>Ie?N.setMonth(Ie+1):(N.setMonth(0),N.setFullYear(N.getFullYear()+1));else{N.setDate(N.getDate()+$e);break}}return Ie=new Date(N.getFullYear()+1,0,4),$e=X(new Date(N.getFullYear(),0,4)),Ie=X(Ie),0>=j($e,N)?0>=j(Ie,N)?N.getFullYear()+1:N.getFullYear():N.getFullYear()-1}d>>>=0,g>>>=0,b>>>=0,E>>>=0;var te=le[E+40>>>2>>>0];E={Ab:V[E>>>2>>>0],zb:V[E+4>>>2>>>0],fb:V[E+8>>>2>>>0],jb:V[E+12>>>2>>>0],gb:V[E+16>>>2>>>0],ab:V[E+20>>>2>>>0],Va:V[E+24>>>2>>>0],$a:V[E+28>>>2>>>0],Cb:V[E+32>>>2>>>0],yb:V[E+36>>>2>>>0],Bb:te?Ye(te):""},b=Ye(b),te={"%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 de in te)b=b.replace(new RegExp(de,"g"),te[de]);var Ae="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),Be="January February March April May June July August September October November December".split(" ");te={"%a":N=>Ae[N.Va].substring(0,3),"%A":N=>Ae[N.Va],"%b":N=>Be[N.gb].substring(0,3),"%B":N=>Be[N.gb],"%C":N=>D((N.ab+1900)/100|0,2),"%d":N=>D(N.jb,2),"%e":N=>z(N.jb,2," "),"%g":N=>ne(N).toString().substring(2),"%G":ne,"%H":N=>D(N.fb,2),"%I":N=>(N=N.fb,N==0?N=12:12{for(var $e=0,Ie=0;Ie<=N.gb-1;$e+=(bt(N.ab+1900)?No:va)[Ie++]);return D(N.jb+$e,3)},"%m":N=>D(N.gb+1,2),"%M":N=>D(N.zb,2),"%n":()=>` +`,"%p":N=>0<=N.fb&&12>N.fb?"AM":"PM","%S":N=>D(N.Ab,2),"%t":()=>" ","%u":N=>N.Va||7,"%U":N=>D(Math.floor((N.$a+7-N.Va)/7),2),"%V":N=>{var $e=Math.floor((N.$a+7-(N.Va+6)%7)/7);if(2>=(N.Va+371-N.$a-2)%7&&$e++,$e)$e==53&&(Ie=(N.Va+371-N.$a)%7,Ie==4||Ie==3&&bt(N.ab)||($e=1));else{$e=52;var Ie=(N.Va+7-N.$a-1)%7;(Ie==4||Ie==5&&bt(N.ab%400-1))&&$e++}return D($e,2)},"%w":N=>N.Va,"%W":N=>D(Math.floor((N.$a+7-(N.Va+6)%7)/7),2),"%y":N=>(N.ab+1900).toString().substring(2),"%Y":N=>N.ab+1900,"%z":N=>{N=N.yb;var $e=0<=N;return N=Math.abs(N)/60,($e?"+":"-")+("0000"+(N/60*100+N%60)).slice(-4)},"%Z":N=>N.Bb,"%%":()=>"%"},b=b.replace(/%%/g,"\0\0");for(de in te)b.includes(de)&&(b=b.replace(new RegExp(de,"g"),te[de](E)));return b=b.replace(/\0\0/g,"%"),de=Uu(b),de.length>g?0:(ce.set(de,d>>>0),de.length-1)}for(var Uo=Array(256),_i=0;256>_i;++_i)Uo[_i]=String.fromCharCode(_i);on=Uo,Pr=a.BindingError=class extends Error{constructor(d){super(d),this.name="BindingError"}},a.InternalError=class extends Error{constructor(d){super(d),this.name="InternalError"}},ct.push(0,1,void 0,1,null,1,!0,1,!1,1),a.count_emval_handles=()=>ct.length/2-5-hi.length;var Lu={ia:function(d,g,b){return ha(async()=>{await a.sb(d,g,b)})},a:function(d,g,b){d>>>=0;var E=new Mu(d);throw le[E.hb+16>>>2>>>0]=0,le[E.hb+4>>>2>>>0]=g>>>0,le[E.hb+8>>>2>>>0]=b>>>0,Vr=d,Vr},y:function(){return 0},ea:function(){},R:function(){},T:function(){},ga:function(){return 0},ca:function(){},Z:function(){},ba:function(){},G:function(){},S:function(){},P:function(){},da:function(){},Q:function(){},C:function(d,g,b){g=qt(g>>>0),Mt(d>>>0,{name:g,fromWireType:E=>E,toWireType:function(E,z){if(typeof z!="bigint"&&typeof z!="number")throw z===null?z="null":(E=typeof z,z=E==="object"||E==="array"||E==="function"?z.toString():""+z),new TypeError(`Cannot convert "${z}" to ${this.name}`);return typeof z=="number"&&(z=BigInt(z)),z},argPackAdvance:8,readValueFromPointer:fi(g,b>>>0,g.indexOf("u")==-1),bb:null})},K:function(d,g,b,E){g=qt(g>>>0),Mt(d>>>0,{name:g,fromWireType:function(z){return!!z},toWireType:function(z,D){return D?b:E},argPackAdvance:8,readValueFromPointer:function(z){return this.fromWireType(se[z>>>0])},bb:null})},J:function(d){return Mt(d>>>0,Bu)},B:function(d,g,b){g=qt(g>>>0),Mt(d>>>0,{name:g,fromWireType:E=>E,toWireType:(E,z)=>z,argPackAdvance:8,readValueFromPointer:Eo(g,b>>>0),bb:null})},s:function(d,g,b,E,z){if(d>>>=0,b>>>=0,g=qt(g>>>0),z===-1&&(z=4294967295),z=X=>X,E===0){var D=32-8*b;z=X=>X<>>D}var j=g.includes("unsigned")?function(X,ne){return ne>>>0}:function(X,ne){return ne};Mt(d,{name:g,fromWireType:z,toWireType:j,argPackAdvance:8,readValueFromPointer:fi(g,b,E!==0),bb:null})},o:function(d,g,b){function E(D){return new z(ce.buffer,le[D+4>>>2>>>0],le[D>>>2>>>0])}var z=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][g];b=qt(b>>>0),Mt(d>>>0,{name:b,fromWireType:E,argPackAdvance:8,readValueFromPointer:E},{nb:!0})},D:function(d,g){g=qt(g>>>0);var b=g==="std::string";Mt(d>>>0,{name:g,fromWireType:function(E){var z=le[E>>>2>>>0],D=E+4;if(b)for(var j=D,X=0;X<=z;++X){var ne=D+X;if(X==z||se[ne>>>0]==0){if(j=Ye(j,ne-j),te===void 0)var te=j;else te+="\0",te+=j;j=ne+1}}else{for(te=Array(z),X=0;X>>0]);te=te.join("")}return Ct(E),te},toWireType:function(E,z){z instanceof ArrayBuffer&&(z=new Uint8Array(z));var D=typeof z=="string";if(!(D||z instanceof Uint8Array||z instanceof Uint8ClampedArray||z instanceof Int8Array))throw new Pr("Cannot pass non-string to std::string");var j=b&&D?pi(z):z.length,X=sn(4+j+1),ne=X+4;if(le[X>>>2>>>0]=j,b&&D)nr(z,se,ne,j+1);else if(D)for(D=0;D>>0]=te}else for(D=0;D>>0]=z[D];return E!==null&&E.push(Ct,X),X},argPackAdvance:8,readValueFromPointer:Rn,bb(E){Ct(E)}})},x:function(d,g,b){if(g>>>=0,b>>>=0,b=qt(b),g===2)var E=ye,z=mi,D=To,j=X=>ze[X>>>1>>>0];else g===4&&(E=Du,z=Io,D=Ao,j=X=>le[X>>>2>>>0]);Mt(d>>>0,{name:b,fromWireType:X=>{for(var ne=le[X>>>2>>>0],te,de=X+4,Ae=0;Ae<=ne;++Ae){var Be=X+4+Ae*g;(Ae==ne||j(Be)==0)&&(de=E(de,Be-de),te===void 0?te=de:(te+="\0",te+=de),de=Be+g)}return Ct(X),te},toWireType:(X,ne)=>{if(typeof ne!="string")throw new Pr(`Cannot pass non-string to C++ string type ${b}`);var te=D(ne),de=sn(4+te+g);return le[de>>>2>>>0]=te/g,z(ne,de+4,te+g),X!==null&&X.push(Ct,de),de},argPackAdvance:8,readValueFromPointer:Rn,bb(X){Ct(X)}})},L:function(d,g){g=qt(g>>>0),Mt(d>>>0,{ob:!0,name:g,argPackAdvance:0,fromWireType:()=>{},toWireType:()=>{}})},ha:()=>1,u:function(d,g,b){return g>>>=0,b>>>=0,d=ke(d>>>0),g=gi(g,"emval::as"),da(g,b,d)},w:function(d){return d>>>=0,ha(()=>(d=ke(d),d.then(Bt)))},n:function(d,g,b,E){return b>>>=0,E>>>=0,d=Mn[d>>>0],g=ke(g>>>0),d(null,g,b,E)},j:function(d,g,b,E,z){return b>>>=0,E>>>=0,z>>>=0,d=Mn[d>>>0],g=ke(g>>>0),b=vi(b),d(g,g[b],E,z)},b:la,A:function(d,g){return g>>>=0,d=ke(d>>>0),g=ke(g),d==g},m:function(d){return d>>>=0,d===0?Bt(Kt()):(d=vi(d),Bt(Kt()[d]))},i:function(d,g,b){g=ga(d,g>>>0);var E=g.shift();d--;var z=`return function (obj, func, destructorsRef, args) { +`,D=0,j=[];b===0&&j.push("obj");for(var X=["retType"],ne=[E],te=0;tede.name).join(", ")}) => ${E.name}>`,ma(yr(b,d))},r:function(d,g){return g>>>=0,d=ke(d>>>0),g=ke(g),Bt(d[g])},e:function(d){d>>>=0,9>>0);for(var g=Array(d.length),b=0;b>>0))},k:function(){return Bt({})},h:function(d){d>>>=0;for(var g=ke(d);g.length;){var b=g.pop();g.pop()(b)}la(d)},g:function(d,g,b){g>>>=0,b>>>=0,d=ke(d>>>0),g=ke(g),b=ke(b),d[g]=b},c:function(d,g){return g>>>=0,d=gi(d>>>0,"_emval_take_value"),d=d.readValueFromPointer(g),Bt(d)},W:function(d,g){d=-9007199254740992>d||9007199254740992>>=0,d=new Date(1e3*d),V[g>>>2>>>0]=d.getUTCSeconds(),V[g+4>>>2>>>0]=d.getUTCMinutes(),V[g+8>>>2>>>0]=d.getUTCHours(),V[g+12>>>2>>>0]=d.getUTCDate(),V[g+16>>>2>>>0]=d.getUTCMonth(),V[g+20>>>2>>>0]=d.getUTCFullYear()-1900,V[g+24>>>2>>>0]=d.getUTCDay(),V[g+28>>>2>>>0]=(d.getTime()-Date.UTC(d.getUTCFullYear(),0,1,0,0,0,0))/864e5|0},X:function(d,g){d=-9007199254740992>d||9007199254740992>>=0,d=new Date(1e3*d),V[g>>>2>>>0]=d.getSeconds(),V[g+4>>>2>>>0]=d.getMinutes(),V[g+8>>>2>>>0]=d.getHours(),V[g+12>>>2>>>0]=d.getDate(),V[g+16>>>2>>>0]=d.getMonth(),V[g+20>>>2>>>0]=d.getFullYear()-1900,V[g+24>>>2>>>0]=d.getDay(),V[g+28>>>2>>>0]=(bt(d.getFullYear())?ya:wi)[d.getMonth()]+d.getDate()-1|0,V[g+36>>>2>>>0]=-(60*d.getTimezoneOffset());var b=new Date(d.getFullYear(),6,1).getTimezoneOffset(),E=new Date(d.getFullYear(),0,1).getTimezoneOffset();V[g+32>>>2>>>0]=(b!=E&&d.getTimezoneOffset()==Math.min(E,b))|0},Y:function(d){d>>>=0;var g=new Date(V[d+20>>>2>>>0]+1900,V[d+16>>>2>>>0],V[d+12>>>2>>>0],V[d+8>>>2>>>0],V[d+4>>>2>>>0],V[d>>>2>>>0],0),b=V[d+32>>>2>>>0],E=g.getTimezoneOffset(),z=new Date(g.getFullYear(),6,1).getTimezoneOffset(),D=new Date(g.getFullYear(),0,1).getTimezoneOffset(),j=Math.min(D,z);return 0>b?V[d+32>>>2>>>0]=+(z!=D&&j==E):0>>2>>>0]=g.getDay(),V[d+28>>>2>>>0]=(bt(g.getFullYear())?ya:wi)[g.getMonth()]+g.getDate()-1|0,V[d>>>2>>>0]=g.getSeconds(),V[d+4>>>2>>>0]=g.getMinutes(),V[d+8>>>2>>>0]=g.getHours(),V[d+12>>>2>>>0]=g.getDate(),V[d+16>>>2>>>0]=g.getMonth(),V[d+20>>>2>>>0]=g.getYear(),d=g.getTime(),BigInt(isNaN(d)?-1:d/1e3)},U:function(){return-52},V:function(){},N:function(d,g,b,E){b>>>=0,E>>>=0;var z=new Date().getFullYear(),D=new Date(z,0,1),j=new Date(z,6,1);z=D.getTimezoneOffset();var X=j.getTimezoneOffset();le[d>>>0>>>2>>>0]=60*Math.max(z,X),V[g>>>0>>>2>>>0]=+(z!=X),d=ne=>ne.toLocaleTimeString(void 0,{hour12:!1,timeZoneName:"short"}).split(" ")[1],D=d(D),j=d(j),X{ut("")},d:function(d,g,b){return d>>>=0,g=$i(g>>>0,b>>>0),di[d](...g)},I:function(d,g,b){return d>>>=0,g=$i(g>>>0,b>>>0),di[d](...g)},H:()=>Date.now(),O:function(){return 4294901760},q:()=>performance.now(),M:function(d){d>>>=0;var g=se.length;if(4294901760=b;b*=2){var E=g*(1+.2/b);E=Math.min(E,d+100663296);var z=Math;E=Math.max(d,E);e:{z=(z.min.call(z,4294901760,E+(65536-E%65536)%65536)-H.buffer.byteLength+65535)/65536;try{H.grow(z),ee();var D=1;break e}catch{}D=void 0}if(D)return!0}return!1},$:function(d,g){d>>>=0,g>>>=0;var b=0;return Nt().forEach((E,z)=>{var D=g+b;for(z=le[d+4*z>>>2>>>0]=D,D=0;D>>0]=E.charCodeAt(D);ce[z>>>0]=0,b+=E.length+1}),0},aa:function(d,g){d>>>=0,g>>>=0;var b=Nt();le[d>>>2>>>0]=b.length;var E=0;return b.forEach(z=>E+=z.length+1),le[g>>>2>>>0]=E,0},z:()=>52,F:function(){return 52},_:function(){return 70},E:function(d,g,b,E){g>>>=0,b>>>=0,E>>>=0;for(var z=0,D=0;D>>2>>>0],X=le[g+4>>>2>>>0];g+=8;for(var ne=0;ne>>0],de=Wu[d];te===0||te===10?((d===1?P:B)(oa(de,0)),de.length=0):de.push(te)}z+=X}return le[E>>>2>>>0]=z,0},fa:Wo,p:function(d,g,b,E){return Wo(d>>>0,g>>>0,b>>>0,E>>>0)}},ge=function(){function d(b){return ge=b.exports,ge=zo(),ge=Vo(),H=ge.ja,ee(),we.unshift(ge.ka),Le--,Le==0&&st&&(b=st,st=null,b()),ge}var g={a:Lu};if(Le++,a.instantiateWasm)try{return a.instantiateWasm(g,d)}catch(b){B(`Module.instantiateWasm callback failed with error: ${b}`),l(b)}return li(g,function(b){d(b.instance)}).catch(l),{}}(),wa=d=>(wa=ge.la)(d);a._OrtInit=(d,g)=>(a._OrtInit=ge.ma)(d,g),a._OrtGetLastError=(d,g)=>(a._OrtGetLastError=ge.na)(d,g),a._OrtCreateSessionOptions=(d,g,b,E,z,D,j,X,ne,te)=>(a._OrtCreateSessionOptions=ge.oa)(d,g,b,E,z,D,j,X,ne,te),a._OrtAppendExecutionProvider=(d,g)=>(a._OrtAppendExecutionProvider=ge.pa)(d,g),a._OrtAddFreeDimensionOverride=(d,g,b)=>(a._OrtAddFreeDimensionOverride=ge.qa)(d,g,b),a._OrtAddSessionConfigEntry=(d,g,b)=>(a._OrtAddSessionConfigEntry=ge.ra)(d,g,b),a._OrtReleaseSessionOptions=d=>(a._OrtReleaseSessionOptions=ge.sa)(d),a._OrtCreateSession=(d,g,b)=>(a._OrtCreateSession=ge.ta)(d,g,b),a._OrtReleaseSession=d=>(a._OrtReleaseSession=ge.ua)(d),a._OrtGetInputOutputCount=(d,g,b)=>(a._OrtGetInputOutputCount=ge.va)(d,g,b),a._OrtGetInputName=(d,g)=>(a._OrtGetInputName=ge.wa)(d,g),a._OrtGetOutputName=(d,g)=>(a._OrtGetOutputName=ge.xa)(d,g),a._OrtFree=d=>(a._OrtFree=ge.ya)(d),a._OrtCreateTensor=(d,g,b,E,z,D)=>(a._OrtCreateTensor=ge.za)(d,g,b,E,z,D),a._OrtGetTensorData=(d,g,b,E,z)=>(a._OrtGetTensorData=ge.Aa)(d,g,b,E,z),a._OrtReleaseTensor=d=>(a._OrtReleaseTensor=ge.Ba)(d),a._OrtCreateRunOptions=(d,g,b,E)=>(a._OrtCreateRunOptions=ge.Ca)(d,g,b,E),a._OrtAddRunConfigEntry=(d,g,b)=>(a._OrtAddRunConfigEntry=ge.Da)(d,g,b),a._OrtReleaseRunOptions=d=>(a._OrtReleaseRunOptions=ge.Ea)(d),a._OrtCreateBinding=d=>(a._OrtCreateBinding=ge.Fa)(d),a._OrtBindInput=(d,g,b)=>(a._OrtBindInput=ge.Ga)(d,g,b),a._OrtBindOutput=(d,g,b,E)=>(a._OrtBindOutput=ge.Ha)(d,g,b,E),a._OrtClearBoundOutputs=d=>(a._OrtClearBoundOutputs=ge.Ia)(d),a._OrtReleaseBinding=d=>(a._OrtReleaseBinding=ge.Ja)(d),a._OrtRunWithBinding=(d,g,b,E,z)=>(a._OrtRunWithBinding=ge.Ka)(d,g,b,E,z),a._OrtRun=(d,g,b,E,z,D,j,X)=>(a._OrtRun=ge.La)(d,g,b,E,z,D,j,X),a._OrtEndProfiling=d=>(a._OrtEndProfiling=ge.Ma)(d),a._JsepOutput=(d,g,b)=>(a._JsepOutput=ge.Na)(d,g,b),a._JsepGetNodeName=d=>(a._JsepGetNodeName=ge.Oa)(d);var sn=a._malloc=d=>(sn=a._malloc=ge.Pa)(d),Ct=a._free=d=>(Ct=a._free=ge.Qa)(d),bi=d=>(bi=ge.Sa)(d),xi=d=>(xi=ge.Ta)(d),$a=()=>($a=ge.Ua)(),Dn=d=>(Dn=ge.Wa)(d),Lo=()=>(Lo=ge.Xa)(),vr=d=>(vr=ge.Ya)(d),Qt=()=>(Qt=ge.Za)();a.___start_em_js=837952,a.___stop_em_js=838113;function Vo(){var d=ge;d=Object.assign({},d);var g=b=>E=>b(E)>>>0;return d.la=g(d.la),d.Pa=g(d.Pa),d.Ta=g(d.Ta),d.Ua=(b=>()=>b()>>>0)(d.Ua),d}a.stackSave=()=>$a(),a.stackRestore=d=>bi(d),a.stackAlloc=d=>xi(d),a.UTF8ToString=Ye,a.stringToUTF8=(d,g,b)=>nr(d,se,g,b),a.lengthBytesUTF8=pi;var Hr;st=function d(){Hr||_a(),Hr||(st=d)};function _a(){if(!(0r)}),qb=ia(()=>{}),Kb=ia(()=>{}),jv={};aa(jv,{cpus:()=>Gv});var Gv,Yb=Z(()=>{Gv=void 0}),Qb=ia((e,t)=>{var r=(()=>{var i;var n=typeof document<"u"?(i=document.currentScript)==null?void 0:i.src:void 0;return typeof __filename<"u"&&(n||(n=__filename)),function(o={}){function a(){return R.buffer!=Ce.buffer&&_t(),Ce}function u(){return R.buffer!=Ce.buffer&&_t(),Le}function l(){return R.buffer!=Ce.buffer&&_t(),st}function p(){return R.buffer!=Ce.buffer&&_t(),ut}function f(){return R.buffer!=Ce.buffer&&_t(),cr}function m(){return R.buffer!=Ce.buffer&&_t(),Gt}function y(){return R.buffer!=Ce.buffer&&_t(),fr}function $(){return R.buffer!=Ce.buffer&&_t(),hr}var c=o,x,T,_=new Promise((s,h)=>{x=s,T=h});c.mountExternalData=(s,h)=>{(c.Db||(c.Db=new Map)).set(s,h)},c.unmountExternalData=()=>{delete c.Db};let v=()=>{let s=(w,S,A)=>(...O)=>{let L=Qt,K=S==null?void 0:S();O=w(...O);let ie=S==null?void 0:S();return K!==ie&&(w=ie,A(K),S=A=null),Qt!=L?z():O},h=w=>async(...S)=>{var A;try{if(c.Cb)throw Error("Session already started");let O=c.Cb={ec:S[0],errors:[]},L=await w(...S);if(c.Cb!==O)throw Error("Session mismatch");(A=c.Kb)==null||A.flush();let K=O.errors;if(0re),0c._OrtCreateSession,w=>c._OrtCreateSession=w),c._OrtRun=h(s(c._OrtRun,()=>c._OrtRun,w=>c._OrtRun=w)),c._OrtRunWithBinding=h(s(c._OrtRunWithBinding,()=>c._OrtRunWithBinding,w=>c._OrtRunWithBinding=w)),c._OrtBindInput=s(c._OrtBindInput,()=>c._OrtBindInput,w=>c._OrtBindInput=w),v=void 0};c.jsepInit=(s,h)=>{if(v==null||v(),s==="webgpu"){[c.Kb,c.Wb,c.$b,c.Lb,c.Zb,c.ob,c.ac,c.cc,c.Xb,c.Yb,c.bc]=h;let w=c.Kb;c.jsepRegisterBuffer=(S,A,O,L)=>w.registerBuffer(S,A,O,L),c.jsepGetBuffer=S=>w.getBuffer(S),c.jsepCreateDownloader=(S,A,O)=>w.createDownloader(S,A,O),c.jsepOnReleaseSession=S=>{w.onReleaseSession(S)},c.jsepOnRunStart=S=>w.onRunStart(S)}};var k=Object.assign({},c),C="./this.program",I=(s,h)=>{throw h},M=typeof window=="object",P=typeof importScripts=="function",B=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",H=c.ENVIRONMENT_IS_PTHREAD||!1,F="";function me(s){return c.locateFile?c.locateFile(s,F):F+s}var ce,se,xe;if(B){var ze=(Vv(),Qn(ic)),V=(Fv(),Qn(ac));F=P?V.dirname(F)+"/":__dirname+"/",ce=(s,h)=>(s=nr(s)?new URL(s):V.normalize(s),ze.readFileSync(s,h?void 0:"utf8")),xe=s=>(s=ce(s,!0),s.buffer||(s=new Uint8Array(s)),s),se=(s,h,w,S=!0)=>{s=nr(s)?new URL(s):V.normalize(s),ze.readFile(s,S?void 0:"utf8",(A,O)=>{A?w(A):h(S?O.buffer:O)})},!c.thisProgram&&1{throw process.exitCode=s,h},global.Worker=qb().Worker}else(M||P)&&(P?F=self.location.href:typeof document<"u"&&document.currentScript&&(F=document.currentScript.src),typeof n<"u"&&n&&(F=n),F.startsWith("blob:")?F="":F=F.substr(0,F.replace(/[?#].*/,"").lastIndexOf("/")+1),B||(ce=s=>{var h=new XMLHttpRequest;return h.open("GET",s,!1),h.send(null),h.responseText},P&&(xe=s=>{var h=new XMLHttpRequest;return h.open("GET",s,!1),h.responseType="arraybuffer",h.send(null),new Uint8Array(h.response)}),se=(s,h,w)=>{var S=new XMLHttpRequest;S.open("GET",s,!0),S.responseType="arraybuffer",S.onload=()=>{S.status==200||S.status==0&&S.response?h(S.response):w()},S.onerror=w,S.send(null)}));B&&typeof performance>"u"&&(global.performance=Kb().performance);var le=console.log.bind(console),U=console.error.bind(console);B&&(le=(...s)=>ze.writeSync(1,s.join(" ")+` +`),U=(...s)=>ze.writeSync(2,s.join(" ")+` +`));var J=le,Q=U;Object.assign(c,k),k=null;var R,ee,oe=!1,we,Ce,Le,st,ut,cr,Gt,fr,He,lt,hr;function _t(){var s=R.buffer;c.HEAP8=Ce=new Int8Array(s),c.HEAP16=st=new Int16Array(s),c.HEAPU8=Le=new Uint8Array(s),c.HEAPU16=ut=new Uint16Array(s),c.HEAP32=cr=new Int32Array(s),c.HEAPU32=Gt=new Uint32Array(s),c.HEAPF32=fr=new Float32Array(s),c.HEAPF64=hr=new Float64Array(s),c.HEAP64=He=new BigInt64Array(s),c.HEAPU64=lt=new BigUint64Array(s)}var li=16777216;if(H)R=c.wasmMemory;else if(c.wasmMemory)R=c.wasmMemory;else if(R=new WebAssembly.Memory({initial:li/65536,maximum:65536,shared:!0}),!(R.buffer instanceof SharedArrayBuffer))throw Q("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"),B&&Q("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and/or recent version)"),Error("bad memory");_t(),li=R.buffer.byteLength;var di=[],On=[],Mu=[],Vr=0,an=null;function oa(){if(Vr--,Vr==0&&an){var s=an;an=null,s()}}function Ye(s){throw s="Aborted("+s+")",Q(s),oe=!0,we=1,s=new WebAssembly.RuntimeError(s+". Build with -sASSERTIONS for more info."),T(s),s}var pi=s=>s.startsWith("data:application/octet-stream;base64,"),nr=s=>s.startsWith("file://"),on;on="ort-wasm-simd-threaded.wasm",pi(on)||(on=me(on));function qt(s){if(xe)return xe(s);throw"both async and sync fetching of the wasm failed"}function sa(s){if(M||P){if(typeof fetch=="function"&&!nr(s))return fetch(s,{credentials:"same-origin"}).then(h=>{if(!h.ok)throw`failed to load wasm binary file at '${s}'`;return h.arrayBuffer()}).catch(()=>qt(s));if(se)return new Promise((h,w)=>{se(s,S=>h(new Uint8Array(S)),w)})}return Promise.resolve().then(()=>qt(s))}function ci(s,h,w){return sa(s).then(S=>WebAssembly.instantiate(S,h)).then(w,S=>{Q(`failed to asynchronously prepare wasm: ${S}`),Ye(S)})}function Pr(s,h){var w=on;return typeof WebAssembly.instantiateStreaming!="function"||pi(w)||nr(w)||B||typeof fetch!="function"?ci(w,s,h):fetch(w,{credentials:"same-origin"}).then(S=>WebAssembly.instantiateStreaming(S,s).then(h,function(A){return Q(`wasm streaming compile failed: ${A}`),Q("falling back to ArrayBuffer instantiation"),ci(w,s,h)}))}var ua={826468:(s,h,w,S)=>{if(typeof c>"u"||!c.Db)return 1;if(s=nt(s>>>0),s.startsWith("./")&&(s=s.substring(2)),s=c.Db.get(s),!s)return 2;if(h>>>=0,w>>>=0,S>>>=0,h+w>s.byteLength)return 3;try{return u().set(s.subarray(h,h+w),S>>>0),0}catch{return 4}},826969:()=>{c.Xb()},827e3:()=>{c.Yb()},827029:()=>{c.bc()},827054:s=>c.Wb(s),827087:s=>c.$b(s),827119:(s,h,w)=>{c.Lb(s,h,w,!0)},827158:(s,h,w)=>{c.Lb(s,h,w)},827191:s=>{c.ob("Abs",s,void 0)},827242:s=>{c.ob("Neg",s,void 0)},827293:s=>{c.ob("Floor",s,void 0)},827346:s=>{c.ob("Ceil",s,void 0)},827398:s=>{c.ob("Reciprocal",s,void 0)},827456:s=>{c.ob("Sqrt",s,void 0)},827508:s=>{c.ob("Exp",s,void 0)},827559:s=>{c.ob("Erf",s,void 0)},827610:s=>{c.ob("Sigmoid",s,void 0)},827665:(s,h,w)=>{c.ob("HardSigmoid",s,{alpha:h,beta:w})},827744:s=>{c.ob("Log",s,void 0)},827795:s=>{c.ob("Sin",s,void 0)},827846:s=>{c.ob("Cos",s,void 0)},827897:s=>{c.ob("Tan",s,void 0)},827948:s=>{c.ob("Asin",s,void 0)},828e3:s=>{c.ob("Acos",s,void 0)},828052:s=>{c.ob("Atan",s,void 0)},828104:s=>{c.ob("Sinh",s,void 0)},828156:s=>{c.ob("Cosh",s,void 0)},828208:s=>{c.ob("Asinh",s,void 0)},828261:s=>{c.ob("Acosh",s,void 0)},828314:s=>{c.ob("Atanh",s,void 0)},828367:s=>{c.ob("Tanh",s,void 0)},828419:s=>{c.ob("Not",s,void 0)},828470:(s,h,w)=>{c.ob("Clip",s,{min:h,max:w})},828539:s=>{c.ob("Clip",s,void 0)},828591:(s,h)=>{c.ob("Elu",s,{alpha:h})},828649:s=>{c.ob("Relu",s,void 0)},828701:(s,h)=>{c.ob("LeakyRelu",s,{alpha:h})},828765:(s,h)=>{c.ob("ThresholdedRelu",s,{alpha:h})},828835:(s,h)=>{c.ob("Cast",s,{to:h})},828893:s=>{c.ob("Add",s,void 0)},828944:s=>{c.ob("Sub",s,void 0)},828995:s=>{c.ob("Mul",s,void 0)},829046:s=>{c.ob("Div",s,void 0)},829097:s=>{c.ob("Pow",s,void 0)},829148:s=>{c.ob("Equal",s,void 0)},829201:s=>{c.ob("Greater",s,void 0)},829256:s=>{c.ob("GreaterOrEqual",s,void 0)},829318:s=>{c.ob("Less",s,void 0)},829370:s=>{c.ob("LessOrEqual",s,void 0)},829429:(s,h,w,S,A)=>{c.ob("ReduceMean",s,{keepDims:!!h,noopWithEmptyAxes:!!w,axes:S?Array.from(f().subarray(S>>>0,A>>>0)):[]})},829588:(s,h,w,S,A)=>{c.ob("ReduceMax",s,{keepDims:!!h,noopWithEmptyAxes:!!w,axes:S?Array.from(f().subarray(S>>>0,A>>>0)):[]})},829746:(s,h,w,S,A)=>{c.ob("ReduceMin",s,{keepDims:!!h,noopWithEmptyAxes:!!w,axes:S?Array.from(f().subarray(S>>>0,A>>>0)):[]})},829904:(s,h,w,S,A)=>{c.ob("ReduceProd",s,{keepDims:!!h,noopWithEmptyAxes:!!w,axes:S?Array.from(f().subarray(S>>>0,A>>>0)):[]})},830063:(s,h,w,S,A)=>{c.ob("ReduceSum",s,{keepDims:!!h,noopWithEmptyAxes:!!w,axes:S?Array.from(f().subarray(S>>>0,A>>>0)):[]})},830221:(s,h,w,S,A)=>{c.ob("ReduceL1",s,{keepDims:!!h,noopWithEmptyAxes:!!w,axes:S?Array.from(f().subarray(S>>>0,A>>>0)):[]})},830378:(s,h,w,S,A)=>{c.ob("ReduceL2",s,{keepDims:!!h,noopWithEmptyAxes:!!w,axes:S?Array.from(f().subarray(S>>>0,A>>>0)):[]})},830535:(s,h,w,S,A)=>{c.ob("ReduceLogSum",s,{keepDims:!!h,noopWithEmptyAxes:!!w,axes:S?Array.from(f().subarray(S>>>0,A>>>0)):[]})},830696:(s,h,w,S,A)=>{c.ob("ReduceSumSquare",s,{keepDims:!!h,noopWithEmptyAxes:!!w,axes:S?Array.from(f().subarray(S>>>0,A>>>0)):[]})},830860:(s,h,w,S,A)=>{c.ob("ReduceLogSumExp",s,{keepDims:!!h,noopWithEmptyAxes:!!w,axes:S?Array.from(f().subarray(S>>>0,A>>>0)):[]})},831024:s=>{c.ob("Where",s,void 0)},831077:(s,h,w)=>{c.ob("Transpose",s,{perm:h?Array.from(f().subarray(h>>>0,w>>>0)):[]})},831185:(s,h,w,S)=>{c.ob("DepthToSpace",s,{blocksize:h,mode:nt(w),format:S?"NHWC":"NCHW"})},831318:(s,h,w,S)=>{c.ob("DepthToSpace",s,{blocksize:h,mode:nt(w),format:S?"NHWC":"NCHW"})},831451:(s,h,w,S,A,O,L,K,ie,re,fe,De,We,W,be)=>{c.ob("ConvTranspose",s,{format:ie?"NHWC":"NCHW",autoPad:h,dilations:[w],group:S,kernelShape:[A],pads:[O,L],strides:[K],wIsConst:()=>!!a()[re>>>0],outputPadding:fe?Array.from(f().subarray(fe>>>0,De>>>0)):[],outputShape:We?Array.from(f().subarray(We>>>0,W>>>0)):[],activation:nt(be)})},831852:(s,h,w,S,A,O,L,K,ie,re,fe,De,We,W)=>{c.ob("ConvTranspose",s,{format:K?"NHWC":"NCHW",autoPad:h,dilations:Array.from(f().subarray(w>>>0,(w>>>0)+2>>>0)),group:S,kernelShape:Array.from(f().subarray(A>>>0,(A>>>0)+2>>>0)),pads:Array.from(f().subarray(O>>>0,(O>>>0)+4>>>0)),strides:Array.from(f().subarray(L>>>0,(L>>>0)+2>>>0)),wIsConst:()=>!!a()[ie>>>0],outputPadding:re?Array.from(f().subarray(re>>>0,fe>>>0)):[],outputShape:De?Array.from(f().subarray(De>>>0,We>>>0)):[],activation:nt(W)})},832417:(s,h,w,S,A,O,L,K,ie,re,fe,De,We,W,be)=>{c.ob("ConvTranspose",s,{format:ie?"NHWC":"NCHW",autoPad:h,dilations:[w],group:S,kernelShape:[A],pads:[O,L],strides:[K],wIsConst:()=>!!a()[re>>>0],outputPadding:fe?Array.from(f().subarray(fe>>>0,De>>>0)):[],outputShape:We?Array.from(f().subarray(We>>>0,W>>>0)):[],activation:nt(be)})},832818:(s,h,w,S,A,O,L,K,ie,re,fe,De,We,W)=>{c.ob("ConvTranspose",s,{format:K?"NHWC":"NCHW",autoPad:h,dilations:Array.from(f().subarray(w>>>0,(w>>>0)+2>>>0)),group:S,kernelShape:Array.from(f().subarray(A>>>0,(A>>>0)+2>>>0)),pads:Array.from(f().subarray(O>>>0,(O>>>0)+4>>>0)),strides:Array.from(f().subarray(L>>>0,(L>>>0)+2>>>0)),wIsConst:()=>!!a()[ie>>>0],outputPadding:re?Array.from(f().subarray(re>>>0,fe>>>0)):[],outputShape:De?Array.from(f().subarray(De>>>0,We>>>0)):[],activation:nt(W)})},833383:(s,h)=>{c.ob("GlobalAveragePool",s,{format:h?"NHWC":"NCHW"})},833474:(s,h,w,S,A,O,L,K,ie,re,fe,De,We,W,be,Me)=>{c.ob("AveragePool",s,{format:Me?"NHWC":"NCHW",auto_pad:h,ceil_mode:w,count_include_pad:S,storage_order:A,dilations:[O,L],kernel_shape:[K,ie],pads:[re,fe,De,We],strides:[W,be]})},833758:(s,h)=>{c.ob("GlobalAveragePool",s,{format:h?"NHWC":"NCHW"})},833849:(s,h,w,S,A,O,L,K,ie,re,fe,De,We,W,be,Me)=>{c.ob("AveragePool",s,{format:Me?"NHWC":"NCHW",auto_pad:h,ceil_mode:w,count_include_pad:S,storage_order:A,dilations:[O,L],kernel_shape:[K,ie],pads:[re,fe,De,We],strides:[W,be]})},834133:(s,h)=>{c.ob("GlobalMaxPool",s,{format:h?"NHWC":"NCHW"})},834220:(s,h,w,S,A,O,L,K,ie,re,fe,De,We,W,be,Me)=>{c.ob("MaxPool",s,{format:Me?"NHWC":"NCHW",auto_pad:h,ceil_mode:w,count_include_pad:S,storage_order:A,dilations:[O,L],kernel_shape:[K,ie],pads:[re,fe,De,We],strides:[W,be]})},834500:(s,h)=>{c.ob("GlobalMaxPool",s,{format:h?"NHWC":"NCHW"})},834587:(s,h,w,S,A,O,L,K,ie,re,fe,De,We,W,be,Me)=>{c.ob("MaxPool",s,{format:Me?"NHWC":"NCHW",auto_pad:h,ceil_mode:w,count_include_pad:S,storage_order:A,dilations:[O,L],kernel_shape:[K,ie],pads:[re,fe,De,We],strides:[W,be]})},834867:(s,h,w,S,A)=>{c.ob("Gemm",s,{alpha:h,beta:w,transA:S,transB:A})},834971:s=>{c.ob("MatMul",s,void 0)},835025:(s,h,w,S)=>{c.ob("ArgMax",s,{keepDims:!!h,selectLastIndex:!!w,axis:S})},835133:(s,h,w,S)=>{c.ob("ArgMin",s,{keepDims:!!h,selectLastIndex:!!w,axis:S})},835241:(s,h)=>{c.ob("Softmax",s,{axis:h})},835304:(s,h)=>{c.ob("Concat",s,{axis:h})},835364:(s,h,w,S,A)=>{c.ob("Split",s,{axis:h,numOutputs:w,splitSizes:S?Array.from(f().subarray(S>>>0,A>>>0)):[]})},835504:s=>{c.ob("Expand",s,void 0)},835558:(s,h)=>{c.ob("Gather",s,{axis:Number(h)})},835629:(s,h)=>{c.ob("GatherElements",s,{axis:Number(h)})},835708:(s,h,w,S,A,O,L,K,ie,re,fe)=>{c.ob("Resize",s,{antialias:h,axes:w?Array.from(f().subarray(w>>>0,S>>>0)):[],coordinateTransformMode:nt(A),cubicCoeffA:O,excludeOutside:L,extrapolationValue:K,keepAspectRatioPolicy:nt(ie),mode:nt(re),nearestMode:nt(fe)})},836054:(s,h,w,S,A,O,L)=>{c.ob("Slice",s,{starts:h?Array.from(f().subarray(h>>>0,w>>>0)):[],ends:S?Array.from(f().subarray(S>>>0,A>>>0)):[],axes:O?Array.from(f().subarray(O>>>0,L>>>0)):[]})},836270:s=>{c.ob("Tile",s,void 0)},836322:(s,h,w,S)=>{c.ob("LayerNormalization",s,{axis:h,epsilon:w,simplified:!!S})},836433:(s,h,w)=>{c.ob("InstanceNormalization",s,{epsilon:h,format:w?"NHWC":"NCHW"})},836547:(s,h,w)=>{c.ob("InstanceNormalization",s,{epsilon:h,format:w?"NHWC":"NCHW"})},836661:s=>{c.ob("Range",s,void 0)},836714:(s,h)=>{c.ob("Einsum",s,{equation:nt(h)})},836795:(s,h,w,S,A)=>{c.ob("Pad",s,{mode:h,value:w,pads:S?Array.from(f().subarray(S>>>0,A>>>0)):[]})},836922:(s,h,w,S,A,O)=>{c.ob("BatchNormalization",s,{epsilon:h,momentum:w,spatial:!!A,trainingMode:!!S,format:O?"NHWC":"NCHW"})},837091:(s,h,w,S,A,O)=>{c.ob("BatchNormalization",s,{epsilon:h,momentum:w,spatial:!!A,trainingMode:!!S,format:O?"NHWC":"NCHW"})},837260:(s,h,w)=>{c.ob("CumSum",s,{exclusive:Number(h),reverse:Number(w)})},837357:(s,h,w,S,A,O,L,K,ie)=>{c.ob("Attention",s,{numHeads:h,isUnidirectional:w,maskFilterValue:S,scale:A,doRotary:O,qkvHiddenSizes:L?Array.from(f().subarray(Number(K)>>>0,Number(K)+L>>>0)):[],pastPresentShareBuffer:!!ie})},837629:s=>{c.ob("BiasAdd",s,void 0)},837684:s=>{c.ob("BiasSplitGelu",s,void 0)},837745:s=>{c.ob("FastGelu",s,void 0)},837801:(s,h,w,S,A,O,L,K,ie,re,fe,De,We)=>{c.ob("Conv",s,{format:ie?"NHWC":"NCHW",auto_pad:h,dilations:[w],group:S,kernel_shape:[A],pads:O?Array.from(f().subarray(O>>>0,L>>>0)):[],strides:[K],w_is_const:()=>!!a()[re>>>0],activation:nt(fe),activation_params:De?Array.from(y().subarray(De>>>0,We>>>0)):[]})},838171:(s,h,w,S,A,O,L,K,ie,re,fe,De,We,W,be,Me)=>{c.ob("Conv",s,{format:De?"NHWC":"NCHW",auto_pad:h,dilations:[w,S],group:A,kernel_shape:[O,L],pads:K?Array.from(f().subarray(K>>>0,ie>>>0)):[],strides:[re,fe],w_is_const:()=>!!a()[We>>>0],activation:nt(W),activation_params:be?Array.from(y().subarray(be>>>0,Me>>>0)):[]})},838562:s=>{c.ob("Gelu",s,void 0)},838614:(s,h,w,S,A,O)=>{c.ob("MatMulNBits",s,{k:h,n:w,accuracyLevel:S,bits:A,blockSize:O})},838741:(s,h,w,S,A,O)=>{c.ob("MultiHeadAttention",s,{numHeads:h,isUnidirectional:w,maskFilterValue:S,scale:A,doRotary:O})},838900:(s,h,w,S,A)=>{c.ob("RotaryEmbedding",s,{interleaved:!!h,numHeads:w,rotaryEmbeddingDim:S,scale:A})},839039:(s,h,w)=>{c.ob("SkipLayerNormalization",s,{epsilon:h,simplified:!!w})},839141:(s,h,w)=>{c.ob("SkipLayerNormalization",s,{epsilon:h,simplified:!!w})},839243:(s,h,w,S)=>{c.ob("LayerNormalization",s,{axis:h,epsilon:w,simplified:!!S})},839354:s=>{c.ac(s)},839388:(s,h)=>c.cc(s,h,c.Cb.ec,c.Cb.errors)};function Mt(s){this.name="ExitStatus",this.message=`Program terminated with exit(${s})`,this.status=s}var fi=s=>{s.terminate(),s.onmessage=()=>{}},hi=s=>{ye.xb.length==0&&(Eo(),ye.Mb(ye.xb[0]));var h=ye.xb.pop();if(!h)return 6;ye.yb.push(h),ye.ub[s.wb]=h,h.wb=s.wb;var w={cmd:"run",start_routine:s.fc,arg:s.Rb,pthread_ptr:s.wb};return B&&h.unref(),h.postMessage(w,s.mc),0},ct=0,la=s=>{var h=Ku();return s=s(),Go(h),s},ke=(s,h,...w)=>la(()=>{for(var S=2*w.length,A=qu(8*S),O=A>>>3,L=0;L>>0]=K)}return Nc(s,0,S,A,h)});function Bt(s){var h;if(H)return ke(0,1,s);we=s,0{if(we=s,H)throw To(s),"unwind";Bt(s)};function Bu(){for(var s=c.numThreads;s--;)Eo();di.unshift(()=>{Vr++,Co(()=>oa())})}function Eo(){var s=me("ort-wasm-simd-threaded.worker.js");s=new Worker(s),ye.xb.push(s)}function Co(s){H?s():Promise.all(ye.xb.map(ye.Mb)).then(s)}var ye={xb:[],yb:[],Qb:[],ub:{},Gb(){H?(ye.receiveObjectTransfer=ye.dc,ye.threadInitTLS=ye.Pb,ye.setExitStatus=ye.Ob):Bu()},Ob:s=>we=s,pc:["$terminateWorker"],hc:()=>{for(var s of ye.yb)fi(s);for(s of ye.xb)fi(s);ye.xb=[],ye.yb=[],ye.ub=[]},Nb:s=>{var h=s.wb;delete ye.ub[h],ye.xb.push(s),ye.yb.splice(ye.yb.indexOf(s),1),s.wb=0,ju(h)},dc(){},Pb(){ye.Qb.forEach(s=>s())},Mb:s=>new Promise(h=>{s.onmessage=O=>{O=O.data;var L=O.cmd;if(O.targetThread&&O.targetThread!=Fo()){var K=ye.ub[O.targetThread];K?K.postMessage(O,O.transferList):Q(`Internal error! Worker sent a message "${L}" to target pthread ${O.targetThread}, but that thread no longer exists!`)}else L==="checkMailbox"?Ct():L==="spawnThread"?hi(O):L==="cleanupThread"?ye.Nb(ye.ub[O.thread]):L==="killThread"?(O=O.thread,L=ye.ub[O],delete ye.ub[O],fi(L),ju(O),ye.yb.splice(ye.yb.indexOf(L),1),L.wb=0):L==="cancelThread"?ye.ub[O.thread].postMessage({cmd:"cancel"}):L==="loaded"?(s.loaded=!0,B&&!s.wb&&s.unref(),h(s)):L==="alert"?alert(`Thread ${O.threadId}: ${O.text}`):O.target==="setimmediate"?s.postMessage(O):L==="callHandler"?c[O.handler](...O.args):L&&Q(`worker sent an unknown command ${L}`)},s.onerror=O=>{throw Q(`worker sent an error! ${O.filename}:${O.lineno}: ${O.message}`),O},B&&(s.on("message",O=>s.onmessage({data:O})),s.on("error",O=>s.onerror(O)));var w=[],S=["onExit"],A;for(A of S)c.hasOwnProperty(A)&&w.push(A);s.postMessage({cmd:"load",handlers:w,urlOrBlob:c.mainScriptUrlOrBlob||n,wasmMemory:R,wasmModule:ee})})};c.PThread=ye;var mi=s=>{for(;0{var s=Fo(),h=m()[s+52>>>2>>>0];s=m()[s+56>>>2>>>0],Uc(h,h-s),Go(h)};function To(s){if(H)return ke(1,0,s);Rn(s)}c.invokeEntryPoint=(s,h)=>{ct=0,s=Lc(s,h),0>>2>>>0]=0,m()[this.Ib+4>>>2>>>0]=h,m()[this.Ib+8>>>2>>>0]=w}}var Io=0;function Ao(s,h,w,S){return H?ke(2,1,s,h,w,S):gi(s,h,w,S)}function gi(s,h,w,S){if(s>>>=0,h>>>=0,w>>>=0,S>>>=0,typeof SharedArrayBuffer>"u")return Q("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var A=[];return H&&A.length===0?Ao(s,h,w,S):(s={fc:w,wb:s,Rb:S,mc:A},H?(s.oc="spawnThread",postMessage(s,A),0):hi(s))}var da=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,Pn=(s,h,w)=>{h>>>=0;var S=h+w;for(w=h;s[w]&&!(w>=S);)++w;if(16A?S+=String.fromCharCode(A):(A-=65536,S+=String.fromCharCode(55296|A>>10,56320|A&1023))}}else S+=String.fromCharCode(A)}return S},nt=(s,h)=>(s>>>=0)?Pn(u(),s,h):"";function zo(s,h,w){return H?ke(3,1,s,h,w):0}function mr(s,h){if(H)return ke(4,1,s,h)}var Dt=s=>{for(var h=0,w=0;w=S?h++:2047>=S?h+=2:55296<=S&&57343>=S?(h+=4,++w):h+=3}return h},pa=(s,h,w,S)=>{if(w>>>=0,!(0=L){var K=s.charCodeAt(++O);L=65536+((L&1023)<<10)|K&1023}if(127>=L){if(w>=S)break;h[w++>>>0]=L}else{if(2047>=L){if(w+1>=S)break;h[w++>>>0]=192|L>>6}else{if(65535>=L){if(w+2>=S)break;h[w++>>>0]=224|L>>12}else{if(w+3>=S)break;h[w++>>>0]=240|L>>18,h[w++>>>0]=128|L>>12&63}h[w++>>>0]=128|L>>6&63}h[w++>>>0]=128|L&63}}return h[w>>>0]=0,w-A},gr=(s,h,w)=>pa(s,u(),h,w);function ca(s,h){if(H)return ke(5,1,s,h)}function fa(s,h,w){if(H)return ke(6,1,s,h,w)}function Oo(s,h,w){return H?ke(7,1,s,h,w):0}function yi(s,h){if(H)return ke(8,1,s,h)}function Ro(s,h,w){if(H)return ke(9,1,s,h,w)}function Po(s,h,w,S){if(H)return ke(10,1,s,h,w,S)}function Mo(s,h,w,S){if(H)return ke(11,1,s,h,w,S)}function Bo(s,h,w,S){if(H)return ke(12,1,s,h,w,S)}function ha(s){if(H)return ke(13,1,s)}function Mn(s,h){if(H)return ke(14,1,s,h)}function Do(s,h,w){if(H)return ke(15,1,s,h,w)}var vi,Kt=s=>{for(var h="";u()[s>>>0];)h+=vi[u()[s++>>>0]];return h},ma={},ga={},yr;function Nu(s,h,w={}){var S=h.name;if(!s)throw new yr(`type "${S}" must have a positive integer typeid pointer`);if(ga.hasOwnProperty(s)){if(w.Ub)return;throw new yr(`Cannot register type '${S}' twice`)}ga[s]=h,ma.hasOwnProperty(s)&&(h=ma[s],delete ma[s],h.forEach(A=>A()))}function bt(s,h,w={}){if(!("argPackAdvance"in h))throw new TypeError("registerType registeredInstance requires argPackAdvance");return Nu(s,h,w)}var ya=(s,h,w)=>{switch(h){case 1:return w?S=>a()[S>>>0]:S=>u()[S>>>0];case 2:return w?S=>l()[S>>>1>>>0]:S=>p()[S>>>1>>>0];case 4:return w?S=>f()[S>>>2>>>0]:S=>m()[S>>>2>>>0];case 8:return w?S=>He[S>>>3]:S=>lt[S>>>3];default:throw new TypeError(`invalid integer width (${h}): ${s}`)}},wi=[],Yt=[];function $i(s){s>>>=0,9{if(!s)throw new yr("Cannot use deleted val. handle = "+s);return Yt[s]},Nt=s=>{switch(s){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let h=wi.pop()||Yt.length;return Yt[h]=s,Yt[h+1]=1,h}};function Bn(s){return this.fromWireType(m()[s>>>2>>>0])}var Wu={name:"emscripten::val",fromWireType:s=>{var h=ft(s);return $i(s),h},toWireType:(s,h)=>Nt(h),argPackAdvance:8,readValueFromPointer:Bn,Bb:null},No=(s,h)=>{switch(h){case 4:return function(w){return this.fromWireType(y()[w>>>2>>>0])};case 8:return function(w){return this.fromWireType($()[w>>>3>>>0])};default:throw new TypeError(`invalid float width (${h}): ${s}`)}},va=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,Uu=(s,h)=>{for(var w=s>>1,S=w+h/2;!(w>=S)&&p()[w>>>0];)++w;if(w<<=1,32=h/2);++S){var A=l()[s+2*S>>>1>>>0];if(A==0)break;w+=String.fromCharCode(A)}return w},Wo=(s,h,w)=>{if(w??(w=2147483647),2>w)return 0;w-=2;var S=h;w=w<2*s.length?w/2:s.length;for(var A=0;A>>1>>>0]=O,h+=2}return l()[h>>>1>>>0]=0,h-S},Uo=s=>2*s.length,_i=(s,h)=>{for(var w=0,S="";!(w>=h/4);){var A=f()[s+4*w>>>2>>>0];if(A==0)break;++w,65536<=A?(A-=65536,S+=String.fromCharCode(55296|A>>10,56320|A&1023)):S+=String.fromCharCode(A)}return S},Lu=(s,h,w)=>{if(h>>>=0,w??(w=2147483647),4>w)return 0;var S=h;w=S+w-4;for(var A=0;A=O){var L=s.charCodeAt(++A);O=65536+((O&1023)<<10)|L&1023}if(f()[h>>>2>>>0]=O,h+=4,h+4>w)break}return f()[h>>>2>>>0]=0,h-S},ge=s=>{for(var h=0,w=0;w=S&&++w,h+=4}return h},wa=s=>{if(!oe)try{if(s(),!(0>>=0,typeof Atomics.nc=="function"&&(Atomics.nc(f(),s>>>2,s).value.then(Ct),s+=128,Atomics.store(f(),s>>>2,1))}c.__emscripten_thread_mailbox_await=sn;var Ct=()=>{var s=Fo();s&&(sn(s),wa(Wc))};c.checkMailbox=Ct;var bi=[],xi=(s,h)=>{var w=ga[s];if(w===void 0)throw s=Bc(s),w=Kt(s),Mr(s),new yr(`${h} has unknown type ${w}`);return w},$a=(s,h,w)=>{var S=[];return s=s.toWireType(S,w),S.length&&(m()[h>>>2>>>0]=Nt(S)),s},Dn=s=>{try{s()}catch(h){Ye(h)}};function Lo(){var s=ue,h={};for(let[w,S]of Object.entries(s))h[w]=typeof S=="function"?(...A)=>{Hr.push(w);try{return S(...A)}finally{oe||(Hr.pop(),Qt&&vr===1&&Hr.length===0&&(vr=0,ct+=1,Dn(Hc),typeof Fibers<"u"&&Fibers.rc()))}}:S;return h}var vr=0,Qt=null,Vo=0,Hr=[],_a={},d={},g=0,b=null,E=[];function z(){return new Promise((s,h)=>{b={resolve:s,reject:h}})}function D(){var s=jo(65548),h=s+12;m()[s>>>2>>>0]=h,m()[s+4>>>2>>>0]=h+65536,h=Hr[0];var w=_a[h];return w===void 0&&(w=g++,_a[h]=w,d[w]=h),h=w,f()[s+8>>>2>>>0]=h,s}function j(){var s=f()[Qt+8>>>2>>>0];return s=ue[d[s]],--ct,s()}function X(s){if(!oe){if(vr===0){var h=!1,w=!1;s((S=0)=>{if(!oe&&(Vo=S,h=!0,w)){vr=2,Dn(()=>Fc(Qt)),typeof Browser<"u"&&Browser.Hb.Tb&&Browser.Hb.resume(),S=!1;try{var A=j()}catch(K){A=K,S=!0}var O=!1;if(!Qt){var L=b;L&&(b=null,(S?L.reject:L.resolve)(A),O=!0)}if(S&&!O)throw A}}),w=!0,h||(vr=1,Qt=D(),typeof Browser<"u"&&Browser.Hb.Tb&&Browser.Hb.pause(),Dn(()=>Vc(Qt)))}else vr===2?(vr=0,Dn(jc),Mr(Qt),Qt=null,E.forEach(wa)):Ye(`invalid state: ${vr}`);return Vo}}function ne(s){return X(h=>{s().then(h)})}var te=[],de={},Ae=s=>{var h=de[s];return h===void 0?Kt(s):h},Be=()=>typeof globalThis=="object"?globalThis:Function("return this")(),N=s=>{var h=te.length;return te.push(s),h},$e=(s,h)=>{for(var w=Array(s),S=0;S>>2>>>0],"parameter "+S);return w},Ie=(s,h)=>Object.defineProperty(h,"name",{value:s});function Fr(s){var h=Function;if(!(h instanceof Function))throw new TypeError(`new_ called with constructor type ${typeof h} which is not a function`);var w=Ie(h.name||"unknownFunctionName",function(){});return w.prototype=h.prototype,w=new w,s=h.apply(w,s),s instanceof Object?s:w}var jr=s=>s%4===0&&(s%100!==0||s%400===0),$c=[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 bc(s,h,w,S,A,O,L){return H?ke(16,1,s,h,w,S,A,O,L):-52}function xc(s,h,w,S,A,O){if(H)return ke(17,1,s,h,w,S,A,O)}var Vu=[],Sc=(s,h)=>{Vu.length=0;for(var w;w=u()[s++>>>0];){var S=w!=105;S&=w!=112,h+=S&&h%8?4:0,Vu.push(w==112?m()[h>>>2>>>0]:w==106?He[h>>>3]:w==105?f()[h>>>2>>>0]:$()[h>>>3>>>0]),h+=S?8:4}return Vu},Hu={},kc=()=>{if(!Fu){var s={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",_:C||"./this.program"},h;for(h in Hu)Hu[h]===void 0?delete s[h]:s[h]=Hu[h];var w=[];for(h in s)w.push(`${h}=${s[h]}`);Fu=w}return Fu},Fu;function Ec(s,h){if(H)return ke(18,1,s,h);s>>>=0,h>>>=0;var w=0;return kc().forEach((S,A)=>{var O=h+w;for(A=m()[s+4*A>>>2>>>0]=O,O=0;O>>0]=S.charCodeAt(O);a()[A>>>0]=0,w+=S.length+1}),0}function Cc(s,h){if(H)return ke(19,1,s,h);s>>>=0,h>>>=0;var w=kc();m()[s>>>2>>>0]=w.length;var S=0;return w.forEach(A=>S+=A.length+1),m()[h>>>2>>>0]=S,0}function Tc(s){return H?ke(20,1,s):52}function Ic(s,h,w,S){return H?ke(21,1,s,h,w,S):52}function Ac(s,h,w,S){return H?ke(22,1,s,h,w,S):70}var G2=[null,[],[]];function zc(s,h,w,S){if(H)return ke(23,1,s,h,w,S);h>>>=0,w>>>=0,S>>>=0;for(var A=0,O=0;O>>2>>>0],K=m()[h+4>>>2>>>0];h+=8;for(var ie=0;ie>>0],fe=G2[s];re===0||re===10?((s===1?J:Q)(Pn(fe,0)),fe.length=0):fe.push(re)}A+=K}return m()[S>>>2>>>0]=A,0}var Oc=[31,29,31,30,31,30,31,31,30,31,30,31],Rc=[31,28,31,30,31,30,31,31,30,31,30,31];function q2(s){var h=Array(Dt(s)+1);return pa(s,h,0,h.length),h}var K2=(s,h)=>{a().set(s,h>>>0)};function Pc(s,h,w,S){function A(W,be,Me){for(W=typeof W=="number"?W.toString():W||"";W.lengthqc?-1:0Nn-W.getDate())be-=Nn-W.getDate()+1,W.setDate(1),11>Me?W.setMonth(Me+1):(W.setMonth(0),W.setFullYear(W.getFullYear()+1));else{W.setDate(W.getDate()+be);break}}return Me=new Date(W.getFullYear()+1,0,4),be=K(new Date(W.getFullYear(),0,4)),Me=K(Me),0>=L(be,W)?0>=L(Me,W)?W.getFullYear()+1:W.getFullYear():W.getFullYear()-1}s>>>=0,h>>>=0,w>>>=0,S>>>=0;var re=m()[S+40>>>2>>>0];S={kc:f()[S>>>2>>>0],jc:f()[S+4>>>2>>>0],Eb:f()[S+8>>>2>>>0],Jb:f()[S+12>>>2>>>0],Fb:f()[S+16>>>2>>>0],Ab:f()[S+20>>>2>>>0],vb:f()[S+24>>>2>>>0],zb:f()[S+28>>>2>>>0],qc:f()[S+32>>>2>>>0],ic:f()[S+36>>>2>>>0],lc:re?nt(re):""},w=nt(w),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 fe in re)w=w.replace(new RegExp(fe,"g"),re[fe]);var De="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),We="January February March April May June July August September October November December".split(" ");re={"%a":W=>De[W.vb].substring(0,3),"%A":W=>De[W.vb],"%b":W=>We[W.Fb].substring(0,3),"%B":W=>We[W.Fb],"%C":W=>O((W.Ab+1900)/100|0,2),"%d":W=>O(W.Jb,2),"%e":W=>A(W.Jb,2," "),"%g":W=>ie(W).toString().substring(2),"%G":ie,"%H":W=>O(W.Eb,2),"%I":W=>(W=W.Eb,W==0?W=12:12{for(var be=0,Me=0;Me<=W.Fb-1;be+=(jr(W.Ab+1900)?Oc:Rc)[Me++]);return O(W.Jb+be,3)},"%m":W=>O(W.Fb+1,2),"%M":W=>O(W.jc,2),"%n":()=>` +`,"%p":W=>0<=W.Eb&&12>W.Eb?"AM":"PM","%S":W=>O(W.kc,2),"%t":()=>" ","%u":W=>W.vb||7,"%U":W=>O(Math.floor((W.zb+7-W.vb)/7),2),"%V":W=>{var be=Math.floor((W.zb+7-(W.vb+6)%7)/7);if(2>=(W.vb+371-W.zb-2)%7&&be++,be)be==53&&(Me=(W.vb+371-W.zb)%7,Me==4||Me==3&&jr(W.Ab)||(be=1));else{be=52;var Me=(W.vb+7-W.zb-1)%7;(Me==4||Me==5&&jr(W.Ab%400-1))&&be++}return O(be,2)},"%w":W=>W.vb,"%W":W=>O(Math.floor((W.zb+7-(W.vb+6)%7)/7),2),"%y":W=>(W.Ab+1900).toString().substring(2),"%Y":W=>W.Ab+1900,"%z":W=>{W=W.ic;var be=0<=W;return W=Math.abs(W)/60,(be?"+":"-")+("0000"+(W/60*100+W%60)).slice(-4)},"%Z":W=>W.lc,"%%":()=>"%"},w=w.replace(/%%/g,"\0\0");for(fe in re)w.includes(fe)&&(w=w.replace(new RegExp(fe,"g"),re[fe](S)));return w=w.replace(/\0\0/g,"%"),fe=q2(w),fe.length>h?0:(K2(fe,s),fe.length-1)}ye.Gb();for(var Mc=Array(256),Ho=0;256>Ho;++Ho)Mc[Ho]=String.fromCharCode(Ho);vi=Mc,yr=c.BindingError=class extends Error{constructor(s){super(s),this.name="BindingError"}},c.InternalError=class extends Error{constructor(s){super(s),this.name="InternalError"}},Yt.push(0,1,void 0,1,null,1,!0,1,!1,1),c.count_emval_handles=()=>Yt.length/2-5-wi.length;var Y2=[Bt,To,Ao,zo,mr,ca,fa,Oo,yi,Ro,Po,Mo,Bo,ha,Mn,Do,bc,xc,Ec,Cc,Tc,Ic,Ac,zc],Q2={ua:function(s,h,w){return ne(async()=>{await c.Zb(s,h,w)})},b:function(s,h,w){throw s>>>=0,new Du(s).Gb(h>>>0,w>>>0),Io=s,Io},ia:function(s){Dc(s>>>0,!P,1,!M,131072,!1),ye.Pb()},G:function(s){s>>>=0,H?postMessage({cmd:"cleanupThread",thread:s}):ye.Nb(ye.ub[s])},_:gi,A:zo,pa:mr,W:ca,Y:fa,qa:Oo,na:yi,fa:Ro,ma:Po,K:Mo,X:Bo,U:ha,oa:Mn,V:Do,E:function(s,h,w){s>>>=0,w>>>=0,h=Kt(h>>>0),bt(s,{name:h,fromWireType:S=>S,toWireType:function(S,A){if(typeof A!="bigint"&&typeof A!="number")throw A===null?A="null":(S=typeof A,A=S==="object"||S==="array"||S==="function"?A.toString():""+A),new TypeError(`Cannot convert "${A}" to ${this.name}`);return typeof A=="number"&&(A=BigInt(A)),A},argPackAdvance:8,readValueFromPointer:ya(h,w,h.indexOf("u")==-1),Bb:null})},O:function(s,h,w,S){s>>>=0,h=Kt(h>>>0),bt(s,{name:h,fromWireType:function(A){return!!A},toWireType:function(A,O){return O?w:S},argPackAdvance:8,readValueFromPointer:function(A){return this.fromWireType(u()[A>>>0])},Bb:null})},N:function(s){return bt(s>>>0,Wu)},D:function(s,h,w){s>>>=0,w>>>=0,h=Kt(h>>>0),bt(s,{name:h,fromWireType:S=>S,toWireType:(S,A)=>A,argPackAdvance:8,readValueFromPointer:No(h,w),Bb:null})},t:function(s,h,w,S,A){if(s>>>=0,w>>>=0,h=Kt(h>>>0),A===-1&&(A=4294967295),A=K=>K,S===0){var O=32-8*w;A=K=>K<>>O}var L=h.includes("unsigned")?function(K,ie){return ie>>>0}:function(K,ie){return ie};bt(s,{name:h,fromWireType:A,toWireType:L,argPackAdvance:8,readValueFromPointer:ya(h,w,S!==0),Bb:null})},p:function(s,h,w){function S(O){var L=m()[O>>>2>>>0];return O=m()[O+4>>>2>>>0],new A(a().buffer,O,L)}s>>>=0;var A=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][h];w=Kt(w>>>0),bt(s,{name:w,fromWireType:S,argPackAdvance:8,readValueFromPointer:S},{Ub:!0})},F:function(s,h){s>>>=0,h=Kt(h>>>0);var w=h==="std::string";bt(s,{name:h,fromWireType:function(S){var A=m()[S>>>2>>>0],O=S+4;if(w)for(var L=O,K=0;K<=A;++K){var ie=O+K;if(K==A||u()[ie>>>0]==0){if(L=nt(L,ie-L),re===void 0)var re=L;else re+="\0",re+=L;L=ie+1}}else{for(re=Array(A),K=0;K>>0]);re=re.join("")}return Mr(S),re},toWireType:function(S,A){A instanceof ArrayBuffer&&(A=new Uint8Array(A));var O=typeof A=="string";if(!(O||A instanceof Uint8Array||A instanceof Uint8ClampedArray||A instanceof Int8Array))throw new yr("Cannot pass non-string to std::string");var L=w&&O?Dt(A):A.length,K=jo(4+L+1),ie=K+4;if(m()[K>>>2>>>0]=L,w&&O)gr(A,ie,L+1);else if(O)for(O=0;O>>0]=re}else for(O=0;O>>0]=A[O];return S!==null&&S.push(Mr,K),K},argPackAdvance:8,readValueFromPointer:Bn,Bb(S){Mr(S)}})},z:function(s,h,w){if(s>>>=0,h>>>=0,w>>>=0,w=Kt(w),h===2)var S=Uu,A=Wo,O=Uo,L=K=>p()[K>>>1>>>0];else h===4&&(S=_i,A=Lu,O=ge,L=K=>m()[K>>>2>>>0]);bt(s,{name:w,fromWireType:K=>{for(var ie=m()[K>>>2>>>0],re,fe=K+4,De=0;De<=ie;++De){var We=K+4+De*h;(De==ie||L(We)==0)&&(fe=S(fe,We-fe),re===void 0?re=fe:(re+="\0",re+=fe),fe=We+h)}return Mr(K),re},toWireType:(K,ie)=>{if(typeof ie!="string")throw new yr(`Cannot pass non-string to C++ string type ${w}`);var re=O(ie),fe=jo(4+re+h);return m()[fe>>>2>>>0]=re/h,A(ie,fe+4,re+h),K!==null&&K.push(Mr,fe),fe},argPackAdvance:8,readValueFromPointer:Bn,Bb(K){Mr(K)}})},P:function(s,h){s>>>=0,h=Kt(h>>>0),bt(s,{Vb:!0,name:h,argPackAdvance:0,fromWireType:()=>{},toWireType:()=>{}})},ta:()=>1,S:function(s,h){s>>>=0,s==h>>>0?setTimeout(Ct):H?postMessage({targetThread:s,cmd:"checkMailbox"}):(s=ye.ub[s])&&s.postMessage({cmd:"checkMailbox"})},$:function(s,h,w,S,A){h>>>=0,w>>>=0,S/=2,bi.length=S,A=A>>>0>>>3;for(var O=0;O>>0];return s=h?ua[h]:Y2[s],ye.Sb=w,w=s(...bi),ye.Sb=0,w},ha:sn,sa:function(s){B&&ye.ub[s>>>0].ref()},w:function(s,h,w){return h>>>=0,w>>>=0,s=ft(s>>>0),h=xi(h,"emval::as"),$a(h,w,s)},y:function(s){return s>>>=0,ne(()=>(s=ft(s),s.then(Nt)))},o:function(s,h,w,S){return w>>>=0,S>>>=0,s=te[s>>>0],h=ft(h>>>0),s(null,h,w,S)},k:function(s,h,w,S,A){return w>>>=0,S>>>=0,A>>>=0,s=te[s>>>0],h=ft(h>>>0),w=Ae(w),s(h,h[w],S,A)},c:$i,C:function(s,h){return h>>>=0,s=ft(s>>>0),h=ft(h),s==h},n:function(s){return s>>>=0,s===0?Nt(Be()):(s=Ae(s),Nt(Be()[s]))},j:function(s,h,w){h=$e(s,h>>>0);var S=h.shift();s--;var A=`return function (obj, func, destructorsRef, args) { +`,O=0,L=[];w===0&&L.push("obj");for(var K=["retType"],ie=[S],re=0;refe.name).join(", ")}) => ${S.name}>`,N(Ie(w,s))},s:function(s,h){return h>>>=0,s=ft(s>>>0),h=ft(h),Nt(s[h])},d:function(s){s>>>=0,9>>0);for(var h=Array(s.length),w=0;w>>0))},l:function(){return Nt({})},i:function(s){s>>>=0;for(var h=ft(s);h.length;){var w=h.pop();h.pop()(w)}$i(s)},h:function(s,h,w){h>>>=0,w>>>=0,s=ft(s>>>0),h=ft(h),w=ft(w),s[h]=w},e:function(s,h){return h>>>=0,s=xi(s>>>0,"_emval_take_value"),s=s.readValueFromPointer(h),Nt(s)},ca:function(s,h){s=-9007199254740992>s||9007199254740992>>=0,s=new Date(1e3*s),f()[h>>>2>>>0]=s.getUTCSeconds(),f()[h+4>>>2>>>0]=s.getUTCMinutes(),f()[h+8>>>2>>>0]=s.getUTCHours(),f()[h+12>>>2>>>0]=s.getUTCDate(),f()[h+16>>>2>>>0]=s.getUTCMonth(),f()[h+20>>>2>>>0]=s.getUTCFullYear()-1900,f()[h+24>>>2>>>0]=s.getUTCDay(),s=(s.getTime()-Date.UTC(s.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,f()[h+28>>>2>>>0]=s},da:function(s,h){s=-9007199254740992>s||9007199254740992>>=0,s=new Date(1e3*s),f()[h>>>2>>>0]=s.getSeconds(),f()[h+4>>>2>>>0]=s.getMinutes(),f()[h+8>>>2>>>0]=s.getHours(),f()[h+12>>>2>>>0]=s.getDate(),f()[h+16>>>2>>>0]=s.getMonth(),f()[h+20>>>2>>>0]=s.getFullYear()-1900,f()[h+24>>>2>>>0]=s.getDay();var w=(jr(s.getFullYear())?$c:_c)[s.getMonth()]+s.getDate()-1|0;f()[h+28>>>2>>>0]=w,f()[h+36>>>2>>>0]=-(60*s.getTimezoneOffset()),w=new Date(s.getFullYear(),6,1).getTimezoneOffset();var S=new Date(s.getFullYear(),0,1).getTimezoneOffset();s=(w!=S&&s.getTimezoneOffset()==Math.min(S,w))|0,f()[h+32>>>2>>>0]=s},ea:function(s){s>>>=0;var h=new Date(f()[s+20>>>2>>>0]+1900,f()[s+16>>>2>>>0],f()[s+12>>>2>>>0],f()[s+8>>>2>>>0],f()[s+4>>>2>>>0],f()[s>>>2>>>0],0),w=f()[s+32>>>2>>>0],S=h.getTimezoneOffset(),A=new Date(h.getFullYear(),6,1).getTimezoneOffset(),O=new Date(h.getFullYear(),0,1).getTimezoneOffset(),L=Math.min(O,A);return 0>w?f()[s+32>>>2>>>0]=+(A!=O&&L==S):0>>2>>>0]=h.getDay(),w=(jr(h.getFullYear())?$c:_c)[h.getMonth()]+h.getDate()-1|0,f()[s+28>>>2>>>0]=w,f()[s>>>2>>>0]=h.getSeconds(),f()[s+4>>>2>>>0]=h.getMinutes(),f()[s+8>>>2>>>0]=h.getHours(),f()[s+12>>>2>>>0]=h.getDate(),f()[s+16>>>2>>>0]=h.getMonth(),f()[s+20>>>2>>>0]=h.getYear(),s=h.getTime(),BigInt(isNaN(s)?-1:s/1e3)},aa:bc,ba:xc,R:function(s,h,w,S){s>>>=0,h>>>=0,w>>>=0,S>>>=0;var A=new Date().getFullYear(),O=new Date(A,0,1),L=new Date(A,6,1);A=O.getTimezoneOffset();var K=L.getTimezoneOffset(),ie=Math.max(A,K);m()[s>>>2>>>0]=60*ie,f()[h>>>2>>>0]=+(A!=K),s=re=>re.toLocaleTimeString(void 0,{hour12:!1,timeZoneName:"short"}).split(" ")[1],O=s(O),L=s(L),K{Ye("")},f:function(s,h,w){return s>>>=0,h=Sc(h>>>0,w>>>0),ua[s](...h)},M:function(s,h,w){return s>>>=0,h=Sc(h>>>0,w>>>0),ua[s](...h)},H:()=>{},L:()=>Date.now(),ra:()=>{throw ct+=1,"unwind"},T:function(){return 4294901760},u:()=>performance.timeOrigin+performance.now(),x:()=>B?(Yb(),Qn(jv)).cpus().length:navigator.hardwareConcurrency,Q:function(s){s>>>=0;var h=u().length;if(s<=h||4294901760=w;w*=2){var S=h*(1+.2/w);S=Math.min(S,s+100663296);var A=Math;S=Math.max(s,S);e:{A=(A.min.call(A,4294901760,S+(65536-S%65536)%65536)-R.buffer.byteLength+65535)/65536;try{R.grow(A),_t();var O=1;break e}catch{}O=void 0}if(O)return!0}return!1},ja:Ec,la:Cc,Z:Rn,B:Tc,J:Ic,ga:Ac,I:zc,a:R||c.wasmMemory,ka:Pc,r:function(s,h,w,S){return Pc(s>>>0,h>>>0,w>>>0,S>>>0)}},ue=function(){function s(w,S){return ue=w.exports,ue=Lo(),ue=X2(),ye.Qb.push(ue.cb),On.unshift(ue.va),ee=S,oa(),ue}var h={a:Q2};if(Vr++,c.instantiateWasm)try{return c.instantiateWasm(h,s)}catch(w){Q(`Module.instantiateWasm callback failed with error: ${w}`),T(w)}return Pr(h,function(w){s(w.instance,w.module)}).catch(T),{}}(),Bc=s=>(Bc=ue.wa)(s);c.__embind_initialize_bindings=()=>(c.__embind_initialize_bindings=ue.xa)(),c._OrtInit=(s,h)=>(c._OrtInit=ue.ya)(s,h),c._OrtGetLastError=(s,h)=>(c._OrtGetLastError=ue.za)(s,h),c._OrtCreateSessionOptions=(s,h,w,S,A,O,L,K,ie,re)=>(c._OrtCreateSessionOptions=ue.Aa)(s,h,w,S,A,O,L,K,ie,re),c._OrtAppendExecutionProvider=(s,h)=>(c._OrtAppendExecutionProvider=ue.Ba)(s,h),c._OrtAddFreeDimensionOverride=(s,h,w)=>(c._OrtAddFreeDimensionOverride=ue.Ca)(s,h,w),c._OrtAddSessionConfigEntry=(s,h,w)=>(c._OrtAddSessionConfigEntry=ue.Da)(s,h,w),c._OrtReleaseSessionOptions=s=>(c._OrtReleaseSessionOptions=ue.Ea)(s),c._OrtCreateSession=(s,h,w)=>(c._OrtCreateSession=ue.Fa)(s,h,w),c._OrtReleaseSession=s=>(c._OrtReleaseSession=ue.Ga)(s),c._OrtGetInputOutputCount=(s,h,w)=>(c._OrtGetInputOutputCount=ue.Ha)(s,h,w),c._OrtGetInputName=(s,h)=>(c._OrtGetInputName=ue.Ia)(s,h),c._OrtGetOutputName=(s,h)=>(c._OrtGetOutputName=ue.Ja)(s,h),c._OrtFree=s=>(c._OrtFree=ue.Ka)(s),c._OrtCreateTensor=(s,h,w,S,A,O)=>(c._OrtCreateTensor=ue.La)(s,h,w,S,A,O),c._OrtGetTensorData=(s,h,w,S,A)=>(c._OrtGetTensorData=ue.Ma)(s,h,w,S,A),c._OrtReleaseTensor=s=>(c._OrtReleaseTensor=ue.Na)(s),c._OrtCreateRunOptions=(s,h,w,S)=>(c._OrtCreateRunOptions=ue.Oa)(s,h,w,S),c._OrtAddRunConfigEntry=(s,h,w)=>(c._OrtAddRunConfigEntry=ue.Pa)(s,h,w),c._OrtReleaseRunOptions=s=>(c._OrtReleaseRunOptions=ue.Qa)(s),c._OrtCreateBinding=s=>(c._OrtCreateBinding=ue.Ra)(s),c._OrtBindInput=(s,h,w)=>(c._OrtBindInput=ue.Sa)(s,h,w),c._OrtBindOutput=(s,h,w,S)=>(c._OrtBindOutput=ue.Ta)(s,h,w,S),c._OrtClearBoundOutputs=s=>(c._OrtClearBoundOutputs=ue.Ua)(s),c._OrtReleaseBinding=s=>(c._OrtReleaseBinding=ue.Va)(s),c._OrtRunWithBinding=(s,h,w,S,A)=>(c._OrtRunWithBinding=ue.Wa)(s,h,w,S,A),c._OrtRun=(s,h,w,S,A,O,L,K)=>(c._OrtRun=ue.Xa)(s,h,w,S,A,O,L,K),c._OrtEndProfiling=s=>(c._OrtEndProfiling=ue.Ya)(s),c._JsepOutput=(s,h,w)=>(c._JsepOutput=ue.Za)(s,h,w),c._JsepGetNodeName=s=>(c._JsepGetNodeName=ue._a)(s);var Fo=c._pthread_self=()=>(Fo=c._pthread_self=ue.$a)(),jo=c._malloc=s=>(jo=c._malloc=ue.ab)(s),Mr=c._free=s=>(Mr=c._free=ue.bb)(s);c.__emscripten_tls_init=()=>(c.__emscripten_tls_init=ue.cb)();var Dc=c.__emscripten_thread_init=(s,h,w,S,A,O)=>(Dc=c.__emscripten_thread_init=ue.eb)(s,h,w,S,A,O);c.__emscripten_thread_crashed=()=>(c.__emscripten_thread_crashed=ue.fb)();var Nc=(s,h,w,S,A)=>(Nc=ue.gb)(s,h,w,S,A),ju=s=>(ju=ue.hb)(s),Gu=c.__emscripten_thread_exit=s=>(Gu=c.__emscripten_thread_exit=ue.ib)(s),Wc=()=>(Wc=ue.jb)(),Uc=(s,h)=>(Uc=ue.kb)(s,h),Go=s=>(Go=ue.lb)(s),qu=s=>(qu=ue.mb)(s),Ku=()=>(Ku=ue.nb)(),Lc=c.dynCall_ii=(s,h)=>(Lc=c.dynCall_ii=ue.pb)(s,h),Vc=s=>(Vc=ue.qb)(s),Hc=()=>(Hc=ue.rb)(),Fc=s=>(Fc=ue.sb)(s),jc=()=>(jc=ue.tb)();c.___start_em_js=839500,c.___stop_em_js=839661;function X2(){var s=ue;s=Object.assign({},s);var h=S=>A=>S(A)>>>0,w=S=>()=>S()>>>0;return s.wa=h(s.wa),s.$a=w(s.$a),s.ab=h(s.ab),s.emscripten_main_runtime_thread_id=w(s.emscripten_main_runtime_thread_id),s.mb=h(s.mb),s.nb=w(s.nb),s}c.wasmMemory=R,c.stackSave=()=>Ku(),c.stackRestore=s=>Go(s),c.stackAlloc=s=>qu(s),c.keepRuntimeAlive=()=>0r)}),Xb=ia((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(...e){var a=e.join(" ");if(ENVIRONMENT_IS_NODE){fs.writeSync(2,a+`\n`);return}console.error(a)}function threadAlert(...e){var a=e.join(" ");postMessage({cmd:"alert",text:a,threadId:Module._pthread_self()})}var err=threadPrintErr;self.alert=threadAlert,Module.instantiateWasm=(e,a)=>{var r=Module.wasmModule;Module.wasmModule=null;var t=new WebAssembly.Instance(r,e);return a(t)},self.onunhandledrejection=e=>{throw e.reason||e};function handleMessage(e){try{if(e.data.cmd==="load"){let r=[];self.onmessage=t=>r.push(t),self.startWorker=t=>{Module=t,postMessage({cmd:"loaded"});for(let s of r)handleMessage(s);self.onmessage=handleMessage},Module.wasmModule=e.data.wasmModule;for(const t of e.data.handlers)Module[t]=(...s)=>{postMessage({cmd:"callHandler",handler:t,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 a=URL.createObjectURL(e.data.urlOrBlob);importScripts(a),URL.revokeObjectURL(a)}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(r){if(r!="unwind")throw r}}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(r){throw Module.__emscripten_thread_crashed?.(),r}}self.onmessage=handleMessage;\n'}),oh,sh,Sl,cs,za,kl,uh,lh,dh,qv,it,So=Z(()=>{oh=Gb(),sh=Qb(),cs=!1,za=!1,kl=!1,uh=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}},lh=()=>{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}},dh=(e,t)=>e?t?"ort-wasm-simd-threaded.wasm":"ort-wasm-simd.wasm":t?"ort-wasm-threaded.wasm":"ort-wasm.wasm",qv=async e=>{if(cs)return Promise.resolve();if(za)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(kl)throw new Error("previous call to 'initializeWebAssembly()' failed.");za=!0;let t=e.initTimeout,r=e.numThreads,n=e.simd,i=uh(r),o=n&&lh(),a=e.wasmPaths,u=typeof a=="string"?a:void 0,l=dh(o,i),p=typeof a=="object"?a[l]:void 0,f=!1,m=[];if(t>0&&m.push(new Promise(y=>{setTimeout(()=>{f=!0,y()},t)})),m.push(new Promise((y,$)=>{let c=i?sh:oh,x={locateFile:(T,_)=>{if(i&&T.endsWith(".worker.js")&&typeof Blob<"u")return URL.createObjectURL(new Blob([Xb()],{type:"text/javascript"}));if(T.endsWith(".wasm")){if(p)return p;let v=u??_;return l==="ort-wasm-simd.wasm"?v+"ort-wasm-simd.jsep.wasm":l==="ort-wasm-simd-threaded.wasm"?v+"ort-wasm-simd-threaded.jsep.wasm":v+l}return _+T}};if(i)if(x.numThreads=r,typeof Blob>"u")x.mainScriptUrlOrBlob=(void 0)(__dirname,"ort-wasm-threaded.js");else{let T=`var ortWasmThreaded=${c.toString()};`;x.mainScriptUrlOrBlob=new Blob([T],{type:"text/javascript"})}c(x).then(T=>{za=!1,cs=!0,Sl=T,y()},T=>{za=!1,kl=!0,$(T)})})),await Promise.race(m),f)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},it=()=>{if(cs&&Sl)return Sl;throw new Error("WebAssembly is not initialized yet.")}}),et,lu,je,oc=Z(()=>{So(),et=(e,t)=>{let r=it(),n=r.lengthBytesUTF8(e)+1,i=r._malloc(n);return r.stringToUTF8(e,i,n),t.push(i),i},lu=(e,t,r,n)=>{if(typeof e=="object"&&e!==null){if(r.has(e))throw new Error("Circular reference in options");r.add(e)}Object.entries(e).forEach(([i,o])=>{let a=t?t+i:i;if(typeof o=="object")lu(o,a+".",r,n);else if(typeof o=="string"||typeof o=="number")n(a,o.toString());else if(typeof o=="boolean")n(a,o?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof o}`)})},je=e=>{let t=it(),r=t.stackSave();try{let n=t.stackAlloc(8);t._OrtGetLastError(n,n+4);let i=t.HEAP32[n/4],o=t.HEAPU32[n/4+1],a=o?t.UTF8ToString(o):"";throw new Error(`${e} ERROR_CODE: ${i}, ERROR_MESSAGE: ${a}`)}finally{t.stackRestore(r)}}}),Kv,Zb=Z(()=>{So(),oc(),Kv=e=>{let t=it(),r=0,n=[],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 o=0;return(e==null?void 0:e.tag)!==void 0&&(o=et(e.tag,n)),r=t._OrtCreateRunOptions(i.logSeverityLevel,i.logVerbosityLevel,!!i.terminate,o),r===0&&je("Can't create run options."),(e==null?void 0:e.extra)!==void 0&&lu(e.extra,"",new WeakSet,(a,u)=>{let l=et(a,n),p=et(u,n);t._OrtAddRunConfigEntry(r,l,p)!==0&&je(`Can't set a run config entry: ${a} - ${u}.`)}),[r,n]}catch(o){throw r!==0&&t._OrtReleaseRunOptions(r),n.forEach(a=>t._free(a)),o}}}),ph,ch,fh,hh,Yv,Jb=Z(()=>{So(),oc(),ph=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}`)}},ch=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},fh=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)},hh=(e,t,r)=>{for(let n of t){let i=typeof n=="string"?n:n.name;switch(i){case"webnn":if(i="WEBNN",typeof n!="string"){let a=n;if(a!=null&&a.deviceType){let u=et("deviceType",r),l=et(a.deviceType,r);it()._OrtAddSessionConfigEntry(e,u,l)!==0&&je(`Can't set a session config entry: 'deviceType' - ${a.deviceType}.`)}if(a!=null&&a.numThreads){let u=a.numThreads;(typeof u!="number"||!Number.isInteger(u)||u<0)&&(u=0);let l=et("numThreads",r),p=et(u.toString(),r);it()._OrtAddSessionConfigEntry(e,l,p)!==0&&je(`Can't set a session config entry: 'numThreads' - ${a.numThreads}.`)}if(a!=null&&a.powerPreference){let u=et("powerPreference",r),l=et(a.powerPreference,r);it()._OrtAddSessionConfigEntry(e,u,l)!==0&&je(`Can't set a session config entry: 'powerPreference' - ${a.powerPreference}.`)}}break;case"webgpu":if(i="JS",typeof n!="string"){let a=n;if(a!=null&&a.preferredLayout){if(a.preferredLayout!=="NCHW"&&a.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${a.preferredLayout}`);let u=et("preferredLayout",r),l=et(a.preferredLayout,r);it()._OrtAddSessionConfigEntry(e,u,l)!==0&&je(`Can't set a session config entry: 'preferredLayout' - ${a.preferredLayout}.`)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${i}`)}let o=et(i,r);it()._OrtAppendExecutionProvider(e,o)!==0&&je(`Can't append execution provider: ${i}.`)}},Yv=e=>{let t=it(),r=0,n=[],i=e||{};fh(i);try{let o=ph(i.graphOptimizationLevel??"all"),a=ch(i.executionMode??"sequential"),u=typeof i.logId=="string"?et(i.logId,n):0,l=i.logSeverityLevel??2;if(!Number.isInteger(l)||l<0||l>4)throw new Error(`log serverity level is not valid: ${l}`);let p=i.logVerbosityLevel??0;if(!Number.isInteger(p)||p<0||p>4)throw new Error(`log verbosity level is not valid: ${p}`);let f=typeof i.optimizedModelFilePath=="string"?et(i.optimizedModelFilePath,n):0;if(r=t._OrtCreateSessionOptions(o,!!i.enableCpuMemArena,!!i.enableMemPattern,a,!!i.enableProfiling,0,u,l,p,f),r===0&&je("Can't create session options."),i.executionProviders&&hh(r,i.executionProviders,n),i.enableGraphCapture!==void 0){if(typeof i.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${i.enableGraphCapture}`);let m=et("enableGraphCapture",n),y=et(i.enableGraphCapture.toString(),n);t._OrtAddSessionConfigEntry(r,m,y)!==0&&je(`Can't set a session config entry: 'enableGraphCapture' - ${i.enableGraphCapture}.`)}if(i.freeDimensionOverrides)for(let[m,y]of Object.entries(i.freeDimensionOverrides)){if(typeof m!="string")throw new Error(`free dimension override name must be a string: ${m}`);if(typeof y!="number"||!Number.isInteger(y)||y<0)throw new Error(`free dimension override value must be a non-negative integer: ${y}`);let $=et(m,n);t._OrtAddFreeDimensionOverride(r,$,y)!==0&&je(`Can't set a free dimension override: ${m} - ${y}.`)}return i.extra!==void 0&&lu(i.extra,"",new WeakSet,(m,y)=>{let $=et(m,n),c=et(y,n);t._OrtAddSessionConfigEntry(r,$,c)!==0&&je(`Can't set a session config entry: ${m} - ${y}.`)}),[r,n]}catch(o){throw r!==0&&t._OrtReleaseSessionOptions(r),n.forEach(a=>t._free(a)),o}}}),jd,Fn,yo,sc,du,uc,Gd,ve=Z(()=>{jd=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}`)}},Fn=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}`)}},yo=e=>[void 0,4,1,1,2,2,4,8,void 0,1,2,8,4,8,void 0,void 0,void 0][e],sc=e=>{switch(e){case"float16":return typeof Float16Array<"u"&&Float16Array.from?Float16Array: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}`)}},du=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}`)}},uc=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool",Gd=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}`)}}}),pu,Qv=Z(()=>{pu=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),n=[];for await(let i of r)n.push(i);return new Uint8Array(Buffer.concat(n))}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"),n=r?parseInt(r,10):0;if(n<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(),o;try{o=new ArrayBuffer(n)}catch(u){if(u instanceof RangeError){let l=Math.ceil(n/65536);o=new WebAssembly.Memory({initial:l,maximum:l}).buffer}else throw u}let a=0;for(;;){let{done:u,value:l}=await i.read();if(u)break;let p=l.byteLength;new Uint8Array(o,a,p).set(l),a+=p}return new Uint8Array(o,0,n)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),mh,gh,yh,vh,Xv,wh,rt,si=Z(()=>{ve(),mh=["V","I","W","E","F"],gh=(e,t)=>{console.log(`[${mh[e]},${new Date().toISOString()}]${t}`)},Xv=(e,t)=>{yh=e,vh=t},wh=(e,t)=>{let r=du(e),n=du(yh);r>=n&&gh(r,typeof t=="function"?t():t)},rt=(...e)=>{vh&&wh(...e)}}),Zv,ex=Z(()=>{ve(),Zv=(e,t)=>new(sc(t))(e)}),lc=Z(()=>{}),El,fs,hs,$h,_h,Cl,qd,bh,Jv,tx=Z(()=>{si(),lc(),El=new Map([[64,250],[128,200],[256,200],[512,200],[2048,230],[4096,200],[8192,50],[16384,50],[32768,50],[65536,50],[131072,50],[262144,50],[524288,50],[1048576,50],[2097152,30],[4194304,20],[8388608,10],[12582912,10],[16777216,10],[26214400,15],[33554432,22],[44236800,2],[58982400,6],[67108864,6],[134217728,6],[167772160,6]]),fs=[],hs=e=>Math.ceil(e/16)*16,$h=e=>{for(let t=0;t_h++,qd=async(e,t,r,n)=>{let i=hs(r),o=e.device.createBuffer({size:i,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let a=e.getCommandEncoder();e.endComputePass(),a.copyBufferToBuffer(t,0,o,0,i),e.flush(),await o.mapAsync(GPUMapMode.READ);let u=o.getMappedRange();if(n){let l=n();return l.set(new Uint8Array(u,0,r)),l}else return new Uint8Array(u.slice(0,r))}finally{o.destroy()}},bh=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,this.capturedPendingBuffers=new Map;for(let[t]of El)fs.push(t),this.freeBuffers.set(t,[]),this.freeUniformBuffers.set(t,[])}upload(e,t){let r=t.buffer,n=t.byteOffset,i=t.byteLength,o=hs(i),a=this.storageCache.get(e);if(!a)throw new Error("gpu data for uploading does not exist");if(a.originalSize!==i)throw new Error(`inconsistent data size. gpu data size=${a.originalSize}, data size=${i}`);let u=this.backend.device.createBuffer({mappedAtCreation:!0,size:o,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),l=u.getMappedRange();new Uint8Array(l).set(new Uint8Array(r,n,i)),u.unmap();let p=this.backend.getCommandEncoder();this.backend.endComputePass(),p.copyBufferToBuffer(u,0,a.gpuData.buffer,0,o),rt("verbose",()=>`[WebGPU] GpuDataManager.upload(id=${e})`),this.buffersForUploadingPending.push(u)}memcpy(e,t){let r=this.storageCache.get(e);if(!r)throw new Error("source gpu data for memcpy does not exist");let n=this.storageCache.get(t);if(!n)throw new Error("destination gpu data for memcpy does not exist");if(r.originalSize!==n.originalSize)throw new Error("inconsistent source and destination gpu data size");let i=hs(r.originalSize),o=this.backend.getCommandEncoder();this.backend.endComputePass(),o.copyBufferToBuffer(r.gpuData.buffer,0,n.gpuData.buffer,0,i)}registerExternalBuffer(e,t,r){let n;if(r){if(n=this.externalBuffers.get(r),n===void 0)throw new Error("previous buffer is not registered");if(e===r)return rt("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${n}, buffer is the same, skip.`),n;if(this.backend.capturedCommandList.has(this.backend.currentSessionId))throw new Error(`Registering a different external buffer under graph capture mode is not supported yet. + Please use the previous external buffer!`);this.externalBuffers.delete(r)}else n=Cl();return this.storageCache.set(n,{gpuData:{id:n,type:0,buffer:e},originalSize:t}),this.externalBuffers.set(e,n),rt("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${n}, registered.`),n}unregisterExternalBuffer(e){let t=this.externalBuffers.get(e);t!==void 0&&(this.storageCache.delete(t),this.externalBuffers.delete(e),rt("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${t}`))}create(e,t=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let r=$h(e),n,i=(t&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,o=(t&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(i||o){let u=(i?this.freeBuffers:this.freeUniformBuffers).get(r);u?u.length>0?n=u.pop():n=this.backend.device.createBuffer({size:r,usage:t}):n=this.backend.device.createBuffer({size:r,usage:t})}else n=this.backend.device.createBuffer({size:r,usage:t});let a={id:Cl(),type:0,buffer:n};return this.storageCache.set(a.id,{gpuData:a,originalSize:e}),rt("verbose",()=>`[WebGPU] GpuDataManager.create(size=${e}) => id=${a.id}`),a}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 rt("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 r=this.storageCache.get(e);if(!r)throw new Error("data does not exist");await qd(this.backend,r.gpuData.buffer,r.originalSize,t)}refreshPendingBuffers(){for(let e of this.buffersForUploadingPending)e.destroy();if(this.buffersForUploadingPending=[],this.buffersPending.length!==0)if(this.backend.sessionStatus==="default"){for(let e of this.buffersPending){let t=El.get(e.size);if((e.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE){let r=this.freeBuffers.get(e.size)||[];t===void 0||r.length>=t?e.destroy():r.push(e)}else if((e.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM){let r=this.freeUniformBuffers.get(e.size)||[];t===void 0||r.length>=t?e.destroy():r.push(e)}else e.destroy()}this.buffersPending=[]}else{let e=this.capturedPendingBuffers.get(this.backend.currentSessionId);e||(e=[],this.capturedPendingBuffers.set(this.backend.currentSessionId,e));for(let t of this.buffersPending)e.push(t);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.capturedPendingBuffers.forEach(e=>{e.forEach(t=>{t.destroy()})}),this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.capturedPendingBuffers=new Map}onReleaseSession(e){let t=this.capturedPendingBuffers.get(e);t&&(t.forEach(r=>{r.destroy()}),this.capturedPendingBuffers.delete(e))}},Jv=(...e)=>new bh(...e)}),xh,qe,gt=Z(()=>{xh=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}},qe=e=>new xh(e)}),Sh,Ji,G,cu,e1,dc,pc,Ee=Z(()=>{Sh=class{static calcMatMulShape(e,t){return e[1]!==t[0]?void 0:[e[0],t[1]]}},Ji=class{static calcShape(e,t,r=!1){let n=e.length,i=t.length;if(n===0)return t;if(i===0)return e;let o=Math.max(e.length,t.length),a=new Array(o);if(r){if(n<2||i<2)return;let u=Sh.calcMatMulShape([e[n-2],e[n-1]],[t[i-2],t[i-1]]);if(u===void 0)return;[a[o-2],a[o-1]]=u}for(let u=r?3:1;u<=o;u++){let l=n-u<0?1:e[n-u],p=i-u<0?1:t[i-u];if(l!==p&&l>1&&p>1)return;let f=Math.max(l,p);if(l&&p)a[o-u]=Math.max(l,p);else{if(f>1)return;a[o-u]=0}}return a}static isValidBroadcast(e,t){let r=e.length,n=t.length;if(r>n)return!1;for(let i=1;i<=r;i++)if(e[r-i]!==1&&e[r-i]!==t[n-i])return!1;return!0}},G=class Ps{static size(t){return Ps.getSizeFromDimensionRange(t,0,t.length)}static convertShape(t,r=4){let n=t.length;if(n===0)return[];let i=new Array(n),o=n-1;for(;o>=0;){if(t[o]%r===0){i[o]=t[o]/r;break}if(r%t[o]!==0)throw new Error("cannot convert shape");i[o]=1,r/=t[o],o--}for(o--;o>=0;o--)i[o]=t[o];return i}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 Ps.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 Ps.getSizeFromDimensionRange(t,0,r)}static getSizeFromDimensionRange(t,r,n){let i=1;for(let o=r;o=0;--i)n[i]=n[i+1]*t[i+1];return n}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(n=>this.normalizeAxis(n,r??t.length))}static sortBasedOnPerm(t,r){return r?r.map(n=>t[n]):t.slice().reverse()}static padShape(t,r){let n=t.length;return t.map((i,o)=>i+r[o]+r[o+n])}static areEqual(t,r){return t.length!==r.length?!1:t.every((n,i)=>n===r[i])}},cu=class Ha{static adjustPoolAttributes(t,r,n,i,o,a){if(!t&&n.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 u=0;u=n.length?n.push(r[u+2]):n[u]=r[u+2];for(let u=0;u=n[u]||a[u+n.length]>=n[u])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(t,r,n,i,o,a,u){if(u){if(o.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(i.length!==t.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let l=0;l{ve(),Ee(),ea=64,ms=(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}`)}},wt=(e,t=1)=>{let r=ms(e,t);return typeof r=="string"?r:r[0]},Ut=(e,t=1)=>{let r=ms(e,t);return typeof r=="string"?r:r[1]},he=(...e)=>{let t=[];return e.forEach(r=>{r.length!==0&&t.push({type:12,data:r},{type:12,data:G.computeStrides(r)})}),t},ot=e=>e%4===0?4:e%2===0?2:1,Qr=(e="f32",t,r="0")=>!t||t===1?`${e}(${r})`:`vec${t}<${e}>(${r})`,Wi=(e,t,r)=>e==="f32"?r:t===1?`f32(${r})`:`vec${t}(${r})`,Tn=(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,_e=(e,t,r,n)=>e.startsWith("uniforms.")&&r>4?typeof t=="string"?n==="f16"?`${e}[(${t}) / 8][(${t}) % 8 / 4][(${t}) % 8 % 4]`:`${e}[(${t}) / 4][(${t}) % 4]`:n==="f16"?`${e}[${Math.floor(t/8)}][${Math.floor(t%8/4)}][${t%8%4}]`:`${e}[${Math.floor(t/4)}][${t%4}]`:r>1?`${e}[${t}]`:e,gs=(e,t,r,n,i)=>{let o=typeof r=="number",a=o?r:r.length,u=[...new Array(a).keys()],l=a<2?"u32":a<=4?`vec${a}`:`array`,p=ms(t,i),f=typeof p=="string"?p:p[1],m=typeof p=="string"?p:p[0],y={indices:l,value:f,storage:m,tensor:t},$=R=>typeof R=="string"?R:`${R}u`,c={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},x=o?"uniforms.":"",T=`${x}${e}_shape`,_=`${x}${e}_strides`,v="";for(let R=0;R ${y.indices} { + var indices: ${y.indices}; + var current = offset; + ${v} + return indices; + }`,C=R=>(c.offsetToIndices=!0,a<2?R:`o2i_${e}(${R})`),I=[];if(a>=2)for(let R=a-1;R>=0;R--)I.push(`${_e(_,R,a)} * (indices[${R}])`);let M=a<2?"":` + fn i2o_${e}(indices: ${y.indices}) -> u32 { + return ${I.join("+")}; + }`,P=R=>(c.indicesToOffset=!0,a<2?R:`i2o_${e}(${R})`),B=(...R)=>a===0?"0u":`${y.indices}(${R.map($).join(",")})`,H=(R,ee)=>a<2?`${R}`:`${_e(R,ee,a)}`,F=(R,ee,oe)=>a<2?`${R}=${oe};`:`${_e(R,ee,a)}=${oe};`,me={},ce=(R,ee)=>{c.broadcastedIndicesToOffset=!0;let oe=`${ee.name}broadcastedIndicesTo${e}Offset`;if(oe in me)return`${oe}(${R})`;let we=[];for(let Ce=a-1;Ce>=0;Ce--){let Le=ee.indicesGet("outputIndices",Ce+ee.rank-a);we.push(`${H(_,Ce)} * (${Le} % ${H(T,Ce)})`)}return me[oe]=`fn ${oe}(outputIndices: ${ee.type.indices}) -> u32 { + return ${we.length>0?we.join("+"):"0u"}; + }`,`${oe}(${R})`},se=(R,ee)=>(()=>{if(y.storage===y.value)return`${e}[${R}]=${ee};`;if(y.storage==="vec2"&&y.value==="i32")return`${e}[${R}]=vec2(u32(${ee}), select(0u, 0xFFFFFFFFu, ${ee} < 0));`;if(y.storage==="vec2"&&y.value==="u32")return`${e}[${R}]=vec2(u32(${ee}), 0u);`;if(y.storage==="u32"&&y.value==="vec4")return`${e}[${R}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${ee}));`;throw new Error(`not supported combination of storage type ${y.storage} and value type ${y.value} yet`)})(),xe=R=>(()=>{if(y.storage===y.value)return`${e}[${R}]`;if(y.storage==="vec2"&&y.value==="i32")return`i32(${e}[${R}].x)`;if(y.storage==="vec2"&&y.value==="u32")return`u32(${e}[${R}].x)`;if(y.storage==="u32"&&y.value==="vec4")return`vec4(bool(${e}[${R}] & 0xFFu), bool(${e}[${R}] & 0xFF00u), bool(${e}[${R}] & 0xFF0000u), bool(${e}[${R}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${y.storage} and value type ${y.value} yet`)})(),ze=a<2?"":` + fn get_${e}ByIndices(indices: ${y.indices}) -> ${f} { + return ${xe(`i2o_${e}(indices)`)}; + }`,V=a<2?"":(()=>{let R=u.map(oe=>`d${oe}: u32`).join(", "),ee=u.map(oe=>`d${oe}`).join(", ");return` + fn get_${e}(${R}) -> ${f} { + return get_${e}ByIndices(${B(ee)}); + }`})(),le=(...R)=>{if(R.length!==a)throw new Error(`indices length must be ${a}`);let ee=R.map($).join(",");return a===0?xe("0u"):a===1?xe(ee[0]):(c.get=!0,c.getByIndices=!0,c.indicesToOffset=!0,`get_${e}(${ee})`)},U=R=>a<2?xe(R):(c.getByIndices=!0,c.indicesToOffset=!0,`get_${e}ByIndices(${R})`),J=a<2?"":` + fn set_${e}ByIndices(indices: ${y.indices}, value: ${f}) { + ${se(`i2o_${e}(indices)`,"value")} + }`,Q=a<2?"":(()=>{let R=u.map(oe=>`d${oe}: u32`).join(", "),ee=u.map(oe=>`d${oe}`).join(", ");return` + fn set_${e}(${R}, value: ${f}) { + set_${e}ByIndices(${B(ee)}, value); + }`})();return{impl:()=>{let R=[],ee=!1;return c.offsetToIndices&&(R.push(k),ee=!0),c.indicesToOffset&&(R.push(M),ee=!0),c.broadcastedIndicesToOffset&&(Object.values(me).forEach(oe=>R.push(oe)),ee=!0),c.set&&(R.push(Q),ee=!0),c.setByIndices&&(R.push(J),ee=!0),c.get&&(R.push(V),ee=!0),c.getByIndices&&(R.push(ze),ee=!0),!o&&ee&&R.unshift(`const ${T} = ${y.indices}(${r.join(",")});`,`const ${_} = ${y.indices}(${G.computeStrides(r).join(",")});`),R.join(` +`)},type:y,offsetToIndices:C,indicesToOffset:P,broadcastedIndicesToOffset:ce,indices:B,indicesGet:H,indicesSet:F,set:(...R)=>{if(R.length!==a+1)throw new Error(`indices length must be ${a}`);let ee=R[a];if(typeof ee!="string")throw new Error("value must be string");let oe=R.slice(0,a).map($).join(",");return a===0?se("0u",ee):a===1?se(oe[0],ee):(c.set=!0,c.setByIndices=!0,c.indicesToOffset=!0,`set_${e}(${oe}, ${ee})`)},setByOffset:se,setByIndices:(R,ee)=>a<2?se(R,ee):(c.setByIndices=!0,c.indicesToOffset=!0,`set_${e}ByIndices(${R}, ${ee});`),get:le,getByOffset:xe,getByIndices:U,usage:n,name:e,strides:_,shape:T,rank:a}},q=(e,t,r,n=1)=>gs(e,t,r,"input",n),pe=(e,t,r,n=1)=>gs(e,t,r,"output",n),cc=(e,t,r,n=1)=>gs(e,t,r,"internal",n),kh=class{constructor(e,t){this.normalizedDispatchGroup=e,this.limits=t,this.internalVariables=[],this.variables=[],this.uniforms=[],this.variableIndex=0}guardAgainstOutOfBoundsWorkgroupSizes(e){return`if (global_idx >= ${typeof e=="number"?`${e}u`:e}) { return; }`}mainStart(e=ea){let t=typeof e=="number"?e:e[0],r=typeof e=="number"?1:e[1],n=typeof e=="number"?1:e[2];if(t>this.limits.maxComputeWorkgroupSizeX||r>this.limits.maxComputeWorkgroupSizeY||n>this.limits.maxComputeWorkgroupSizeZ)throw new Error(`workgroup size [${t}, ${r}, ${n}] exceeds the maximum workgroup size [${this.limits.maxComputeWorkgroupSizeX}, ${this.limits.maxComputeWorkgroupSizeY}, ${this.limits.maxComputeWorkgroupSizeZ}].`);if(t*r*n>this.limits.maxComputeInvocationsPerWorkgroup)throw new Error(`workgroup size [${t}, ${r}, ${n}] exceeds the maximum workgroup invocations ${this.limits.maxComputeInvocationsPerWorkgroup}.`);let i=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1,o=i?`@builtin(global_invocation_id) global_id : vec3, + @builtin(workgroup_id) workgroup_id : vec3, + @builtin(local_invocation_id) local_id : vec3`:`@builtin(global_invocation_id) global_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`,a=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*r*n}u + local_idx;`;return`@compute @workgroup_size(${t}, ${r}, ${n}) + fn main(${o}) { + ${a} + `}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 r=e.usage==="input"?"read":"read_write",n=e.type.storage;return`@group(0) @binding(${t}) var ${e.name}: array<${n}>;`}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,r=1){return this.uniforms.push({name:e,type:t,length:r}),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:r,length:n}of this.uniforms)if(n&&n>4)r==="f16"?e.push(`@align(16) ${t}:array, ${Math.ceil(n/8)}>`):e.push(`${t}:array, ${Math.ceil(n/4)}>`);else{let i=n==null||n===1?r:`vec${n}<${r}>`;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(` +`)}get variablesInfo(){if(this.uniforms.length===0)return;let e=t=>[12,10,1,6][["u32","f16","f32","i32"].indexOf(t)];return this.uniforms.map(t=>[e(t.type),t.length??1])}},t1=(e,t)=>new kh(e,t),vo=(e,t)=>{let r=e.length,n=[];for(let i=0;i1&&a===1&&n.unshift(o)}return n}}),Eh,Tl,Ch,Th,Zr,r1,n1,ko=Z(()=>{ve(),Ee(),gt(),Se(),Eh=e=>{if(!e||e.length!==1)throw new Error("Transpose requires 1 input.")},Tl=(e,t)=>t&&t.length!==e?[...new Array(e).keys()].reverse():t,Ch=(e,t)=>G.sortBasedOnPerm(e,Tl(e.length,t)),Th=(e,t,r,n)=>{let i=[];i.push(`fn perm(i: ${n.type.indices}) -> ${r.type.indices} { + var a: ${r.type.indices};`);for(let o=0;o{let r=e.dataType,n=e.dims.length,i=Tl(n,t),o=Ch(e.dims,i),a=pe("output",r,o.length),u=q("a",r,n),l=p=>` + ${p.registerUniform("output_size","u32").declareVariables(u,a)} + + ${Th(i,n,u,a)} + + ${p.mainStart()} + ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${a.offsetToIndices("global_idx")}; + let aIndices = perm(indices); + + ${a.setByOffset("global_idx",u.getByIndices("aIndices"))} + }`;return{name:"Transpose",shaderCache:{hint:`${t}`,inputDependencies:["rank"]},getRunData:p=>{let f=G.size(o);return{outputs:[{dims:o,dataType:p[0].dataType}],dispatchGroup:{x:Math.ceil(f/64)},programUniforms:[{type:12,data:f},...he(p[0].dims,o)]}},getShaderSource:l}},r1=(e,t)=>{Eh(e.inputs),e.compute(Zr(e.inputs[0],t.perm))},n1=e=>qe({perm:e.perm})}),Ih,Ah,zh,Oh,Rh,Ph,Mh,Bh,Dh,Nh,$r,i1,a1,o1,s1,u1,l1,d1,p1,c1,f1,rx=Z(()=>{ve(),Ee(),Se(),fc(),ko(),Ih={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"},Ah={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"},zh={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},Oh={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},Rh=(e,t)=>{let r=[];for(let n=t-e;n{let r=[],n=e.length;for(let o=0;oe[o]);return[r,i]},Mh=(e,t)=>{let r=e.length+t.length,n=[],i=0;for(let o=0;o{for(let r=0;r{let r=[];if(!Bh(e,t)){for(let n=0;nr.push(n))}return r},Nh=(e,t,r,n,i,o,a)=>{let u=r[0].dims,l=G.size(o),p=G.size(a),f=q("_A",r[0].dataType,u),m=pe("output",i,o),y=32,$=` + var aBestValues : array; + `;return{name:e,shaderCache:t,getShaderSource:c=>` + ${c.registerUniform("reduceSize","u32").declareVariables(f,m)} + ${$} + fn DIV_CEIL(a : u32, b : u32) -> u32 { + return ((a - 1u) / b + 1u); + } + ${c.mainStart(y)} + + let outputIndex = global_idx / ${y}; + let offset = outputIndex * uniforms.reduceSize; + + var bestValue = f32(${zh[n]}); + let Length = uniforms.reduceSize; + for (var k = local_idx; k < Length; k = k + ${y}) { + let candidate = f32(${f.getByOffset("offset + k")}); + bestValue = ${Ih[n]}; + } + aBestValues[local_idx] = bestValue; + workgroupBarrier(); + + var reduceSize = min(Length, ${y}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 = ${Ah[n]}; + aBestValues[local_idx] = bestValue; + } + reduceSize = interval; + workgroupBarrier(); + } + + if (local_idx == 0u) { + ${m.setByOffset("outputIndex",`${n==="mean"?`${m.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${m.type.storage}(${Oh[n]})`}`)}; + } + }`,getRunData:()=>({outputs:[{dims:o,dataType:i}],dispatchGroup:{x:l},programUniforms:[{type:12,data:p}]})}},$r=(e,t,r,n)=>{let i=e.inputs.length===1?r:Kd(e.inputs,r),o=i.axes;o.length===0&&!i.noopWithEmptyAxes&&(o=e.inputs[0].dims.map(($,c)=>c));let a=G.normalizeAxes(o,e.inputs[0].dims.length),u=a,l=e.inputs[0],p=Dh(u,e.inputs[0].dims.length);p.length>0&&(l=e.compute(Zr(e.inputs[0],p),{inputs:[0],outputs:[-1]})[0],u=Rh(u.length,l.dims.length));let[f,m]=Ph(l.dims,u),y=f;i.keepDims&&(y=Mh(f,a)),e.compute(Nh(t,{hint:i.cacheKey,inputDependencies:["type"]},[l],n,e.inputs[0].dataType,y,m),{inputs:[l]})},i1=(e,t)=>{$r(e,"ReduceMeanShared",t,"mean")},a1=(e,t)=>{$r(e,"ReduceL1Shared",t,"l1")},o1=(e,t)=>{$r(e,"ReduceL2Shared",t,"l2")},s1=(e,t)=>{$r(e,"ReduceLogSumExpShared",t,"logSumExp")},u1=(e,t)=>{$r(e,"ReduceMaxShared",t,"max")},l1=(e,t)=>{$r(e,"ReduceMinShared",t,"min")},d1=(e,t)=>{$r(e,"ReduceProdShared",t,"prod")},p1=(e,t)=>{$r(e,"ReduceSumShared",t,"sum")},c1=(e,t)=>{$r(e,"ReduceSumSquareShared",t,"sumSquare")},f1=(e,t)=>{$r(e,"ReduceLogSumShared",t,"logSum")}}),_r,Wh,fu,Kd,br,Uh,Lh,Vh,Hh,Fh,jh,Gh,qh,Kh,Yh,xr,h1,m1,g1,y1,v1,w1,$1,_1,b1,x1,fc=Z(()=>{ve(),Ee(),gt(),Se(),rx(),_r=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.")},Wh=e=>["","",`var value = ${e.getByIndices("input_indices")};`,""],fu=(e,t,r,n,i,o,a=!1,u=!1)=>{let l=[],p=r[0].dims,f=p.length,m=G.normalizeAxes(i,f),y=!u&&m.length===0;p.forEach((x,T)=>{y||m.indexOf(T)>=0?a&&l.push(1):l.push(x)});let $=l.length,c=G.size(l);return{name:e,shaderCache:t,getShaderSource:x=>{let T=[],_=q("_A",r[0].dataType,f),v=pe("output",o,$),k=n(_,v,m),C=k[2];for(let I=0,M=0;I=0?(a&&M++,C=`for(var j${I}: u32 = 0; j${I} < ${p[I]}; j${I}++) { + ${k[2].includes("last_index")?`let last_index = j${I};`:""} + ${_.indicesSet("input_indices",I,`j${I}`)} + ${C} + }`):(T.push(`${_.indicesSet("input_indices",I,v.indicesGet("output_indices",M))};`),M++);return` + + ${x.registerUniform("output_size","u32").declareVariables(_,v)} + + ${x.mainStart()} + ${x.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + var input_indices: ${_.type.indices}; + let output_indices = ${v.offsetToIndices("global_idx")}; + + ${T.join(` +`)} + ${k[0]} // init ops for reduce max/min + ${k[1]} + ${C} + ${k[3]} + ${k.length===4?v.setByOffset("global_idx","value"):k.slice(4).join(` +`)} + }`},getRunData:()=>({outputs:[{dims:l,dataType:o}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:[{type:12,data:c},...he(p,l)]})}},Kd=(e,t)=>{let r=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach(n=>r.push(Number(n))),qe({axes:r,keepDims:t.keepDims,noopWithEmptyAxes:t.noopWithEmptyAxes})},br=(e,t,r,n)=>{let i=e.inputs,o=i.length===1?r:Kd(i,r);e.compute(fu(t,{hint:o.cacheKey,inputDependencies:["rank"]},[i[0]],o.noopWithEmptyAxes&&o.axes.length===0?Wh:n,o.axes,i[0].dataType,o.keepDims,o.noopWithEmptyAxes),{inputs:[0]})},Uh=(e,t)=>{_r(e.inputs),br(e,"ReduceLogSum",t,(r,n)=>[`var value = ${n.type.storage}(0);`,"",`value += ${r.getByIndices("input_indices")};`,"value = log(value);"])},Lh=(e,t)=>{_r(e.inputs),br(e,"ReduceL1",t,(r,n)=>[`var value = ${n.type.storage}(0);`,"",`value += abs(${r.getByIndices("input_indices")});`,""])},Vh=(e,t)=>{_r(e.inputs),br(e,"ReduceL2",t,(r,n)=>[`var t = ${n.type.value}(0); var value = ${n.type.value}(0);`,"",`t = ${r.getByIndices("input_indices")}; value += (t * t);`,"value = sqrt(value);"])},Hh=(e,t)=>{_r(e.inputs),br(e,"ReduceLogSumExp",t,(r,n)=>[`var value = ${n.type.storage}(0);`,"",`value += exp(${r.getByIndices("input_indices")});`,"value = log(value);"])},Fh=(e,t)=>{_r(e.inputs),br(e,"ReduceMax",t,(r,n,i)=>{let o=[];for(let a=0;a=0||i.length===0)&&o.push(r.indicesSet("input_indices",a,0));return[`${o.join(` +`)}`,`var value = ${r.getByIndices("input_indices")};`,`value = max(value, ${r.getByIndices("input_indices")});`,""]})},jh=(e,t)=>{_r(e.inputs),br(e,"ReduceMean",t,(r,n,i)=>{let o=1;for(let a=0;a=0||i.length===0)&&(o*=e.inputs[0].dims[a]);return["var sum = f32(0);","",`sum += f32(${r.getByIndices("input_indices")});`,`let value = ${n.type.value}(sum / ${o});`]})},Gh=(e,t)=>{_r(e.inputs),br(e,"ReduceMin",t,(r,n,i)=>{let o=[];for(let a=0;a=0||i.length===0)&&o.push(`input_indices[${a}] = 0;`);return[`${o.join(` +`)}`,`var value = ${r.getByIndices("input_indices")};`,`value = min(value, ${r.getByIndices("input_indices")});`,""]})},qh=(e,t)=>{_r(e.inputs),br(e,"ReduceProd",t,(r,n)=>[`var value = ${n.type.storage}(1);`,"",`value *= ${r.getByIndices("input_indices")};`,""])},Kh=(e,t)=>{_r(e.inputs),br(e,"ReduceSum",t,(r,n)=>[`var value = ${n.type.storage}(0);`,"",`value += ${r.getByIndices("input_indices")};`,""])},Yh=(e,t)=>{_r(e.inputs),br(e,"ReduceSumSquare",t,(r,n)=>[`var t = ${n.type.value}(0); var value = ${n.type.value}(0);`,"",`t = ${r.getByIndices("input_indices")}; value += t * t;`,""])},xr=(e,t,r)=>{if(t.length===0)return r;let n=1,i=1;for(let o=0;o1024},h1=(e,t)=>{xr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?jh(e,t):i1(e,t)},m1=(e,t)=>{xr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Lh(e,t):a1(e,t)},g1=(e,t)=>{xr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Vh(e,t):o1(e,t)},y1=(e,t)=>{xr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Hh(e,t):s1(e,t)},v1=(e,t)=>{xr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Fh(e,t):u1(e,t)},w1=(e,t)=>{xr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Gh(e,t):l1(e,t)},$1=(e,t)=>{xr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?qh(e,t):d1(e,t)},_1=(e,t)=>{xr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Kh(e,t):p1(e,t)},b1=(e,t)=>{xr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Yh(e,t):c1(e,t)},x1=(e,t)=>{xr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Uh(e,t):f1(e,t)}}),Il,S1,k1,Yd,nx=Z(()=>{ve(),gt(),fc(),Il=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.")},S1=(e,t)=>{Il(e.inputs);let r=(n,i,o)=>{let a=[];for(let u=0;u=0||o.length===0)&&a.push(`input_indices[${u}] = 0;`);return[`${a.join(` +`)}`,`var value = ${n.getByIndices("input_indices")}; +var best_index : i32 = 0;`,`if (${n.getByIndices("input_indices")} ${t.selectLastIndex>0?"<=":"<"} value) { + value = ${n.getByIndices("input_indices")}; + best_index = i32(last_index); + }`,"",i.setByOffset("global_idx","best_index")]};e.compute(fu("ArgMin",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],r,[t.axis],7,t.keepDims),{inputs:[0]})},k1=(e,t)=>{Il(e.inputs);let r=(n,i,o)=>{let a=[];for(let u=0;u=0||o.length===0)&&a.push(`input_indices[${u}] = 0;`);return[`${a.join(` +`)}`,`var value = ${n.getByIndices("input_indices")}; +var best_index : i32 = 0;`,`if (${n.getByIndices("input_indices")} ${t.selectLastIndex>0?">=":">"} value) { + value = ${n.getByIndices("input_indices")}; + best_index = i32(last_index); + }`,"",i.setByOffset("global_idx","best_index")]};e.compute(fu("argMax",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],r,[t.axis],7,t.keepDims),{inputs:[0]})},Yd=e=>qe(e)}),Qh,Xh,Zh,hu,E1,C1,T1=Z(()=>{ve(),Ee(),gt(),Se(),Qh=(e,t)=>{if(!e||e.length<1)throw new Error("too few inputs");let r=0,n=e[r],i=n.dataType,o=n.dims.length;e.forEach((a,u)=>{if(u!==r){if(a.dataType!==i)throw new Error("input tensors should be one type");if(a.dims.length!==o)throw new Error("input tensors should have the same shape");a.dims.forEach((l,p)=>{if(p!==t&&l!==n.dims[p])throw new Error("non concat dimensions must match")})}})},Xh=(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; + }`,Zh=(e,t)=>{let r=e.length,n=[];for(let i=0;i{let i=G.size(r),o=new Array(e.length),a=new Array(e.length),u=0,l=[],p=[],f=[{type:12,data:i}];for(let x=0;x`uniforms.sizeInConcatAxis${x}`).join(","),c=x=>` + + ${(()=>{x.registerUniform("outputSize","u32");for(let T=0;T(${$}); + ${y} -= sizeInConcatAxis[inputIndex - 1u]; + } + + ${Zh(a,m)} + }`;return{name:"Concat",shaderCache:{hint:`${t}`,inputDependencies:l},getRunData:()=>({outputs:[{dims:r,dataType:n}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:f}),getShaderSource:c}},E1=(e,t)=>{let r=e.inputs,n=r[0].dims,i=G.normalizeAxis(t.axis,n.length);Qh(r,i);let o=n.slice();o[i]=r.reduce((u,l)=>u+(l.dims.length>i?l.dims[i]:0),0);let a=r.filter(u=>G.size(u.dims)>0);e.compute(hu(a,i,o,r[0].dataType),{inputs:a})},C1=e=>qe({axis:e.axis})}),Jh,em,tm,rm,mu,nm,I1,A1=Z(()=>{ve(),lc(),Se(),T1(),Jh=(e,t)=>{let r=e[0],n=e[1],i=e[2],o=e[3],a=e[4],u=e[5];if(a&&u)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 l=r.dims[0],p=r.dims[1],f=r.dims[2];if(i.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimensions');if(n.dims.length!==2)throw new Error('Input "weights" is expected to have 2 dimensions');if(n.dims[0]!==f)throw new Error("Input 1 dimension 0 should have same length as dimension 2 of input 0");if(i.dims[0]!==n.dims[1])throw new Error('Input "bias" dimension 0 should have same length as dimension 1 of input "weights"');let m=i.dims[0]/3,y=m,$=y;if(t.qkvHiddenSizes.length>0){if(t.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let k of t.qkvHiddenSizes)if(k%t.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");m=t.qkvHiddenSizes[0],y=t.qkvHiddenSizes[1],$=t.qkvHiddenSizes[2]}let c=p;if(m!==y)throw new Error("qkv_hidden_sizes first element should be same as the second");if(i.dims[0]!==m+y+$)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let x=0;if(a){if(y!==$)throw new Error('Input "past" expect k_hidden_size == v_hidden_size');if(a.dims.length!==5)throw new Error('Input "past" must have 5 dimensions');if(a.dims[0]!==2)throw new Error('Input "past" first dimension must be 2');if(a.dims[1]!==l)throw new Error('Input "past" second dimension must be batch_size');if(a.dims[2]!==t.numHeads)throw new Error('Input "past" third dimension must be num_heads');if(a.dims[4]!==y/t.numHeads)throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads');t.pastPresentShareBuffer||(x=a.dims[3])}let T=c+x,_=-1,v=0;if(o)throw new Error("Mask not supported");if(a)throw new Error("past is not supported");return{batchSize:l,sequenceLength:p,pastSequenceLength:x,kvSequenceLength:c,totalSequenceLength:T,maxSequenceLength:_,inputHiddenSize:f,hiddenSize:m,vHiddenSize:$,headSize:Math.floor(m/t.numHeads),vHeadSize:Math.floor($/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:v,scale:t.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},em=(e,t,r,n)=>{let i=ot(n),o=64,a=n/i;a{let $=pe("x",t.dataType,t.dims,i),c=[{name:"d_inv",type:Ut(t.dataType)},{name:"d_comp",type:"u32"},{name:"elements_per_thread",type:"u32"}];return` + var thread_max: array; + var thread_sum: array; + ${y.registerUniforms(c).declareVariables($)} + ${y.mainStart([o,1,1])} + let local_offset = local_idx * uniforms.elements_per_thread; + let offset = workgroup_id.x * uniforms.d_comp + local_offset; + + var thread_max_vector = ${f}(-3.402823e+38f); + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { + thread_max_vector = max(${f}(x[offset + i]), thread_max_vector); + } + thread_max[local_idx] = ${(()=>{switch(i){case 1:return"thread_max_vector";case 2:return"max(thread_max_vector.x, thread_max_vector.y)";case 4:return"max(max(thread_max_vector.x, thread_max_vector.y), max(thread_max_vector.z, thread_max_vector.w))";default:throw new Error(`Unsupported components: ${i}`)}})()}; + workgroupBarrier(); + + var max_value = f32(-3.402823e+38f); + for (var i = 0u; i < ${o}; i++) { + max_value = max(thread_max[i], max_value); + } + + var sum_vector = ${f}(0); + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { + sum_vector += exp(${f}(x[offset + i]) - max_value); + } + thread_sum[local_idx] = ${(()=>{switch(i){case 1:return"sum_vector";case 2:return"sum_vector.x + sum_vector.y";case 4:return"sum_vector.x + sum_vector.y + sum_vector.z + sum_vector.w";default:throw new Error(`Unsupported components: ${i}`)}})()}; + workgroupBarrier(); + + var sum: f32 = 0; + for (var i = 0u; i < ${o}; i++) { + sum += thread_sum[i]; + } + + if (sum == 0) { + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { + x[offset + i] = ${$.type.value}(uniforms.d_inv); + } + } else { + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { + var f32input = ${f}(x[offset + i]); + x[offset + i] = ${$.type.value}(exp(f32input - max_value) / sum); + } + } + }`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${o};${p};${i}`},getShaderSource:m,getRunData:()=>({outputs:[],dispatchGroup:{x:r},programUniforms:l})}},tm=(e,t,r,n,i,o,a)=>{let u=a+i.kvSequenceLength,l=[i.batchSize,i.numHeads,i.sequenceLength,u],p=o.scale===0?1/Math.sqrt(i.headSize):o.scale,f=ot(i.headSize),m=i.headSize/f,y=12,$={x:Math.ceil(u/y),y:Math.ceil(i.sequenceLength/y),z:i.batchSize*i.numHeads},c=[{type:12,data:i.sequenceLength},{type:12,data:m},{type:12,data:u},{type:12,data:i.numHeads},{type:1,data:p}],x=n?["type","type","type"]:["type","type"],T=_=>{let v=q("q",t.dataType,t.dims,f),k=q("key",r.dataType,r.dims,f),C=[v,k];n&&C.push(q("relative_position_bias",n.dataType,n.dims));let I=pe("output",t.dataType,l),M=Ut(1,f),P=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"alpha",type:"f32"}];return` + const TILE_SIZE = ${y}u; + + var tileQ: array<${v.type.storage}, ${y*y}>; + var tileK: array<${v.type.storage}, ${y*y}>; + ${_.registerUniforms(P).declareVariables(...C,I)} + ${_.mainStart([y,y,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 qOffset = uniforms.M * uniforms.K * headIdx + m * uniforms.K; + let kOffset = uniforms.N * uniforms.K * headIdx + n * uniforms.K; + + var value = ${M}(0); + for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { + if (global_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 < TILE_SIZE && w+k < uniforms.K; k++) { + value += ${M}(tileQ[TILE_SIZE * local_id.y + k] * tileK[TILE_SIZE * local_id.x + k]); + } + + workgroupBarrier(); + } + + let headOffset = headIdx * uniforms.M * uniforms.N; + if (global_id.y < uniforms.M && global_id.x < uniforms.N) { + let outputIdx = headOffset + global_id.y * uniforms.N + global_id.x; + var sum: f32 = ${(()=>{switch(f){case 1:return"value";case 2:return"value.x + value.y";case 4:return"value.x + value.y + value.z + value.w";default:throw new Error(`Unsupported components: ${f}`)}})()}; + output[outputIdx] = ${I.type.value} (sum * uniforms.alpha) + ${n?"relative_position_bias[outputIdx]":"0.0"}; + } + }`};return{name:"AttentionProbs",shaderCache:{hint:`${f}`,inputDependencies:x},getRunData:()=>({outputs:[{dims:l,dataType:t.dataType,gpuDataType:0}],dispatchGroup:$,programUniforms:c}),getShaderSource:T}},rm=(e,t,r,n,i)=>{let o=i+n.kvSequenceLength,a=[n.batchSize,n.sequenceLength,n.vHiddenSize],u=12,l={x:Math.ceil(n.vHeadSize/u),y:Math.ceil(n.sequenceLength/u),z:n.batchSize*n.numHeads},p=[{type:12,data:n.sequenceLength},{type:12,data:o},{type:12,data:n.vHeadSize},{type:12,data:n.numHeads},{type:12,data:n.vHiddenSize}];return{name:"AttentionScore",shaderCache:{inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:a,dataType:t.dataType,gpuDataType:0}],dispatchGroup:l,programUniforms:p}),getShaderSource:f=>{let m=q("probs",t.dataType,t.dims),y=q("v",r.dataType,r.dims),$=pe("output",t.dataType,a),c=[{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 = ${u}u; + var tileQ: array<${m.type.value}, ${u*u}>; + var tileK: array<${m.type.value}, ${u*u}>; + ${f.registerUniforms(c).declareVariables(m,y,$)} + ${f.mainStart([u,u,1])} + let headIdx = workgroup_id.z; + let m = global_id.y; + let n = global_id.x; + + let offsetA = headIdx * (uniforms.M * uniforms.K) + m * uniforms.K; + let offsetB = headIdx * (uniforms.N * uniforms.K) + n; + + var value = ${m.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 < TILE_SIZE && w+k < uniforms.K; k++) { + value += tileQ[TILE_SIZE * local_id.y + k] * tileK[TILE_SIZE * k + local_id.x]; + } + workgroupBarrier(); + } + + // we need to transpose output from BNSH_v to BSND_v + let batchIdx = workgroup_id.z / uniforms.num_heads; + let currentBatchHeadNumber = workgroup_id.z % uniforms.num_heads; + if (m < uniforms.M && n < uniforms.N) { + let outputIdx = batchIdx * uniforms.M * uniforms.v_hidden_size + m * uniforms.v_hidden_size + + currentBatchHeadNumber * uniforms.N + n; + output[outputIdx] = value; + } + }`}}},mu=(e,t,r,n,i,o,a,u,l,p,f)=>{let m=e.outputCount>1,y=e.outputCount>2,$=m&&y?p.pastSequenceLength:0,c=$+p.kvSequenceLength,x=[p.batchSize,p.numHeads,c,p.headSize],T=a?[a,r]:[r],_=m?e.compute(hu(T,2,x,r.dataType),{inputs:T,outputs:[1]})[0]:r,v=[p.batchSize,p.numHeads,c,p.headSize],k=u?[u,n]:[n],C=y?e.compute(hu(k,2,v,n.dataType),{inputs:k,outputs:[2]})[0]:n,I=[t,_];l&&I.push(l);let M=e.compute(tm(e,t,_,l,p,f,$),{inputs:I,outputs:[-1]})[0];e.compute(em(e,M,p.batchSize*p.numHeads*p.sequenceLength,c),{inputs:[M],outputs:[]});let P=[M,C];e.compute(rm(e,M,C,p,$),{inputs:P,outputs:[0]})},nm=(e,t)=>{let r=[t.batchSize,t.numHeads,t.sequenceLength,t.headSize],n=t.sequenceLength,i=t.inputHiddenSize,o=t.headSize,a=12,u={x:Math.ceil(t.headSize/a),y:Math.ceil(t.sequenceLength/a),z:t.batchSize*t.numHeads},l=[e.inputs[0],e.inputs[1],e.inputs[2]],p=[{type:12,data:n},{type:12,data:i},{type:12,data:o},{type:12,data:t.numHeads},{type:12,data:t.headSize},{type:12,data:t.hiddenSize},{type:12,data:t.hiddenSize+t.hiddenSize+t.vHiddenSize}],f=m=>{let y=pe("output_q",l[0].dataType,r),$=pe("output_k",l[0].dataType,r),c=pe("output_v",l[0].dataType,r),x=q("input",l[0].dataType,l[0].dims),T=q("weight",l[1].dataType,l[1].dims),_=q("bias",l[2].dataType,l[2].dims),v=x.type.storage,k=[{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 = ${a}u; + var tileInput: array<${v}, ${a*a}>; + var tileWeightQ: array<${v}, ${a*a}>; + var tileWeightK: array<${v}, ${a*a}>; + var tileWeightV: array<${v}, ${a*a}>; + ${m.registerUniforms(k).declareVariables(x,T,_,y,$,c)} + ${m.mainStart([a,a,1])} + let batchIndex = workgroup_id.z / uniforms.num_heads; + let headNumber = workgroup_id.z % uniforms.num_heads; + let m = global_id.y; + let n = global_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 = ${v}(0); + var valueK = ${v}(0); + var valueV = ${v}(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: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:u,programUniforms:p}),getShaderSource:f},{inputs:l,outputs:[-1,-1,-1]})},I1=(e,t)=>{let r=Jh(e.inputs,t),[n,i,o]=nm(e,r);return mu(e,n,i,o,e.inputs[4],void 0,void 0,void 0,e.inputs[5],r,t)}}),im,am,om,z1,ix=Z(()=>{Rr(),ve(),Ee(),gt(),Se(),im=(e,t)=>{if(!e||e.length!==5)throw new Error("BatchNormalization requires 5 inputs");let r=(n,i,o)=>{let a=i.length;if(a!==n.length)throw new Error(`${o}: num dimensions != ${a}`);i.forEach((u,l)=>{if(u!==n[l])throw new Error(`${o}: dim[${l}] do not match`)})};if(e[0].dims.length>1){let n=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,n,"Invalid input scale"),r(e[2].dims,n,"Invalid input B"),r(e[3].dims,n,"Invalid input mean"),r(e[4].dims,n,"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")},am=(e,t)=>{let{epsilon:r,spatial:n,format:i}=t,o=e[0].dims,a=n?ot(o[o.length-1]):1,u=i==="NHWC"&&o.length>1?a:1,l=G.size(o)/a,p=n,f=p?o.length:o,m=q("x",e[0].dataType,e[0].dims,a),y=q("scale",e[1].dataType,e[1].dims,u),$=q("bias",e[2].dataType,e[2].dims,u),c=q("inputMean",e[3].dataType,e[3].dims,u),x=q("inputVar",e[4].dataType,e[4].dims,u),T=pe("y",e[0].dataType,f,a),_=()=>{let k="";if(n)k=`let cOffset = ${o.length===1?"0u":i==="NHWC"?`outputIndices[${o.length-1}] / ${a}`:"outputIndices[1]"};`;else if(i==="NCHW")k=` + ${T.indicesSet("outputIndices","0","0")} + let cOffset = ${T.indicesToOffset("outputIndices")};`;else{k=`var cIndices = ${y.type.indices}(0); + cIndices[0] = outputIndices[${o.length-1}];`;for(let C=1;C` + const epsilon = ${r}; + ${k.registerUniform("outputSize","u32").declareVariables(m,y,$,c,x,T)} + ${k.mainStart()} + ${k.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var outputIndices = ${T.offsetToIndices(`global_idx * ${a}`)}; + ${_()} + let scale = ${y.getByOffset("cOffset")}; + let bias = ${$.getByOffset("cOffset")}; + let inputMean = ${c.getByOffset("cOffset")}; + let inputVar = ${x.getByOffset("cOffset")}; + let x = ${m.getByOffset("global_idx")}; + let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias; + ${T.setByOffset("global_idx","value")} + }`;return{name:"BatchNormalization",shaderCache:{hint:`${t.epsilon}_${t.format}_${n}_${a}`,inputDependencies:p?["rank","type","type","type","type"]:void 0},getShaderSource:v,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:p?[{type:12,data:l},...he(o)]:[{type:12,data:l}]})}},om=e=>qe(e),z1=(e,t)=>{let{inputs:r,outputCount:n}=e,i=om({...t,outputCount:n});if(Ue.webgpu.validateInputContent&&im(r,i),t.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");e.compute(am(r,i))}}),sm,um,O1,ax=Z(()=>{Ee(),Se(),sm=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")},um=e=>{let t=e[0].dims,r=e[0].dims[2],n=G.size(t)/4,i=e[0].dataType,o=q("input",i,t,4),a=q("bias",i,[r],4),u=q("residual",i,t,4),l=pe("output",i,t,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(n/64)}}),getShaderSource:p=>` + const channels = ${r}u / 4; + ${p.declareVariables(o,a,u,l)} + + ${p.mainStart()} + ${p.guardAgainstOutOfBoundsWorkgroupSizes(n)} + let value = ${o.getByOffset("global_idx")} + + ${a.getByOffset("global_idx % channels")} + ${u.getByOffset("global_idx")}; + ${l.setByOffset("global_idx","value")} + }`}},O1=e=>{sm(e.inputs),e.compute(um(e.inputs))}}),lm,Oe,R1,P1,M1,B1,D1,N1,W1,U1,L1,dm,V1,H1,F1,j1,Ms,G1,Bs,q1,K1,Y1,Q1,X1,Z1,J1,ew,tw,rw,nw,iw,aw,ow,sw,uw,Al,lw,Qd,Xd,dw,pw,cw,hc=Z(()=>{ve(),Ee(),gt(),Se(),lm=(e,t,r,n,i,o)=>{let a=Math.ceil(t/4),u="";typeof i=="string"?u=`${i}(a)`:u=i("a");let l=q("inputData",r,[a],4),p=pe("outputData",n,[a],4);return` + ${e.registerUniform("vec_size","u32").declareVariables(l,p)} + + ${o??""} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + + let a = ${l.getByOffset("global_idx")}; + ${p.setByOffset("global_idx",u)} + }`},Oe=(e,t,r,n,i,o=e.dataType)=>({name:t,shaderCache:{hint:i,inputDependencies:["type"]},getShaderSource:a=>lm(a,G.size(e.dims),e.dataType,o,r,n),getRunData:a=>({outputs:[{dims:e.dims,dataType:o}],dispatchGroup:{x:Math.ceil(G.size(a[0].dims)/64/4)},programUniforms:[{type:12,data:Math.ceil(G.size(e.dims)/4)}]})}),R1=e=>{e.compute(Oe(e.inputs[0],"Abs","abs"))},P1=e=>{e.compute(Oe(e.inputs[0],"Acos","acos"))},M1=e=>{e.compute(Oe(e.inputs[0],"Acosh","acosh"))},B1=e=>{e.compute(Oe(e.inputs[0],"Asin","asin"))},D1=e=>{e.compute(Oe(e.inputs[0],"Asinh","asinh"))},N1=e=>{e.compute(Oe(e.inputs[0],"Atan","atan"))},W1=e=>{e.compute(Oe(e.inputs[0],"Atanh","atanh"))},U1=e=>qe(e),L1=(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(Oe(e.inputs[0],"Cast",r,void 0,t.cacheKey,t.to))},dm=e=>{let t=e.length>=2&&e[1].data!==0?e[1].getFloat32Array()[0]:dc,r=e.length>=3&&e[2].data!==0?e[2].getFloat32Array()[0]:pc;return qe({min:t,max:r})},V1=(e,t)=>{let r=e.inputs.length===1?t:dm(e.inputs),n=Ut(e.inputs[0].dataType);e.compute(Oe(e.inputs[0],"Clip",i=>`clamp(${i}, clip_min_, clip_max_)`,` + const clip_min_: vec4<${n}> = vec4(${n}(${r.min})); + const clip_max_: vec4<${n}> = vec4(${n}(${r.max})); +`,r.cacheKey),{inputs:[0]})},H1=e=>{e.compute(Oe(e.inputs[0],"Ceil","ceil"))},F1=e=>{e.compute(Oe(e.inputs[0],"Cos","cos"))},j1=e=>{e.compute(Oe(e.inputs[0],"Cosh","cosh"))},Ms=e=>qe(e),G1=(e,t)=>{let r=Ut(e.inputs[0].dataType);e.compute(Oe(e.inputs[0],"Elu",n=>`elu_vf32(${n})`,` + const elu_alpha_ = ${r}(${t.alpha}); + + fn elu_f32(a: ${r}) -> ${r} { + return select((exp(a) - 1.0) * elu_alpha_, a, a >= 0.0); + } + + fn elu_vf32(v: vec4<${r}>) -> vec4<${r}> { + return vec4(elu_f32(v.x), elu_f32(v.y), elu_f32(v.z), elu_f32(v.w)); + }`,t.cacheKey))},Bs=(e="f32")=>` +const r0: ${e} = 0.3275911; +const r1: ${e} = 0.254829592; +const r2: ${e} = -0.284496736; +const r3: ${e} = 1.421413741; +const r4: ${e} = -1.453152027; +const r5: ${e} = 1.061405429; + +fn erf_vf32(v: vec4<${e}>) -> vec4<${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)); +}`,q1=e=>{let t=Ut(e.inputs[0].dataType);e.compute(Oe(e.inputs[0],"Erf",r=>`erf_vf32(${r})`,Bs(t)))},K1=e=>{e.compute(Oe(e.inputs[0],"Exp","exp"))},Y1=e=>{e.compute(Oe(e.inputs[0],"Floor","floor"))},Q1=e=>{let t=Ut(e.inputs[0].dataType);e.compute(Oe(e.inputs[0],"Gelu",r=>`0.5 * ${r} * (1.0 + erf_vf32(${r} * 0.7071067811865475))`,Bs(t)))},X1=(e,t)=>{let r=Ut(e.inputs[0].dataType);e.compute(Oe(e.inputs[0],"LeakyRelu",n=>`select(leaky_relu_alpha_ * ${n}, ${n}, ${n} >= vec4<${r}>(0.0))`,`const leaky_relu_alpha_ = ${r}(${t.alpha});`,t.cacheKey))},Z1=e=>{e.compute(Oe(e.inputs[0],"Not",t=>`!${t}`))},J1=e=>{e.compute(Oe(e.inputs[0],"Neg",t=>`-${t}`))},ew=e=>{e.compute(Oe(e.inputs[0],"Reciprocal",t=>`1.0/${t}`))},tw=e=>{let t=Ut(e.inputs[0].dataType);e.compute(Oe(e.inputs[0],"Relu",r=>`select(vec4<${t}>(0.0), ${r}, ${r} > vec4<${t}>(0.0))`))},rw=e=>{e.compute(Oe(e.inputs[0],"Sigmoid",t=>`(1.0 / (1.0 + exp(-${t})))`))},nw=e=>qe(e),iw=(e,t)=>{let r=Ut(e.inputs[0].dataType);e.compute(Oe(e.inputs[0],"HardSigmoid",n=>`max(vec4<${r}>(0.0), min(vec4<${r}>(1.0), ${t.alpha} * ${n} + vec4<${r}>(${t.beta})))`,void 0,t.cacheKey))},aw=e=>{e.compute(Oe(e.inputs[0],"Sin","sin"))},ow=e=>{e.compute(Oe(e.inputs[0],"Sinh","sinh"))},sw=e=>{e.compute(Oe(e.inputs[0],"Sqrt","sqrt"))},uw=e=>{e.compute(Oe(e.inputs[0],"Tan","tan"))},Al=e=>`sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`,lw=e=>{e.compute(Oe(e.inputs[0],"Tanh",Al))},Qd=(e="f32")=>` +const fast_gelu_a: ${e} = 0.5; +const fast_gelu_b: ${e} = 0.7978845608028654; +const fast_gelu_c: ${e} = 0.035677408136300125; + +fn tanh_v(v: vec4<${e}>) -> vec4<${e}> { + return ${Al("v")}; +} +`,Xd=e=>`(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`,dw=e=>{let t=Ut(e.inputs[0].dataType);e.compute(Oe(e.inputs[0],"FastGelu",Xd,Qd(t),void 0,e.inputs[0].dataType))},pw=(e,t)=>{let r=Ut(e.inputs[0].dataType);return e.compute(Oe(e.inputs[0],"ThresholdedRelu",n=>`select(vec4<${r}>(0.0), ${n}, ${n} > thresholded_relu_alpha_)`,`const thresholded_relu_alpha_ = vec4<${r}>(${t.alpha});`,t.cacheKey)),0},cw=e=>{e.compute(Oe(e.inputs[0],"Log","log"))}}),pm,cm,fw,ox=Z(()=>{Ee(),Se(),hc(),pm=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")},cm=e=>{let t=e[0].dims.slice();t[2]=t[2]/2;let r=q("input",e[0].dataType,e[0].dims,4),n=q("bias",e[0].dataType,[e[0].dims[2]],4),i=pe("output",e[0].dataType,t,4),o=G.size(t)/4,a=wt(e[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(o/64)}}),getShaderSource:u=>` + const M_SQRT2 = sqrt(2.0); + const halfChannels = ${e[0].dims[2]/4/2}u; + + ${u.declareVariables(r,n,i)} + + ${Bs(a)} + + ${u.mainStart()} + ${u.guardAgainstOutOfBoundsWorkgroupSizes(o)} + 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")} + }`}},fw=e=>{pm(e.inputs),e.compute(cm(e.inputs))}}),fm,hm,Sr,hw,mw,gw,yw,vw,ww,$w,_w,bw,xw,sx=Z(()=>{ve(),Ee(),Se(),fm=(e,t,r,n,i,o,a,u,l,p,f,m)=>{let y,$;typeof u=="string"?y=$=(v,k)=>`${u}((${v}),(${k}))`:typeof u=="function"?y=$=u:(y=u.scalar,$=u.vector);let c=pe("outputData",f,n.length,4),x=q("aData",l,t.length,4),T=q("bData",p,r.length,4),_;if(i)if(o){let v=G.size(t)===1,k=G.size(r)===1,C=t.length>0&&t[t.length-1]%4===0,I=r.length>0&&r[r.length-1]%4===0;v||k?_=c.setByOffset("global_idx",$(v?`${x.type.value}(${x.getByOffset("0")}.x)`:x.getByOffset("global_idx"),k?`${T.type.value}(${T.getByOffset("0")}.x)`:T.getByOffset("global_idx"))):_=` + let outputIndices = ${c.offsetToIndices("global_idx * 4u")}; + let offsetA = ${x.broadcastedIndicesToOffset("outputIndices",c)}; + let offsetB = ${T.broadcastedIndicesToOffset("outputIndices",c)}; + ${c.setByOffset("global_idx",$(a||C?x.getByOffset("offsetA / 4u"):`${x.type.value}(${x.getByOffset("offsetA / 4u")}[offsetA % 4u])`,a||I?T.getByOffset("offsetB / 4u"):`${T.type.value}(${T.getByOffset("offsetB / 4u")}[offsetB % 4u])`))} + `}else _=c.setByOffset("global_idx",$(x.getByOffset("global_idx"),T.getByOffset("global_idx")));else{if(!o)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let v=(k,C,I="")=>{let M=`aData[indexA${C}][componentA${C}]`,P=`bData[indexB${C}][componentB${C}]`;return` + let outputIndices${C} = ${c.offsetToIndices(`global_idx * 4u + ${C}u`)}; + let offsetA${C} = ${x.broadcastedIndicesToOffset(`outputIndices${C}`,c)}; + let offsetB${C} = ${T.broadcastedIndicesToOffset(`outputIndices${C}`,c)}; + let indexA${C} = offsetA${C} / 4u; + let indexB${C} = offsetB${C} / 4u; + let componentA${C} = offsetA${C} % 4u; + let componentB${C} = offsetB${C} % 4u; + ${k}[${C}] = ${I}(${y(M,P)}); + `};f===9?_=` + var data = vec4(0); + ${v("data",0,"u32")} + ${v("data",1,"u32")} + ${v("data",2,"u32")} + ${v("data",3,"u32")} + outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:_=` + ${v("outputData[global_idx]",0)} + ${v("outputData[global_idx]",1)} + ${v("outputData[global_idx]",2)} + ${v("outputData[global_idx]",3)} + `}return` + ${e.registerUniform("vec_size","u32").declareVariables(x,T,c)} + + ${m??""} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${_} + }`},hm=(e,t,r,n,i,o,a=r.dataType)=>{let u=!G.areEqual(r.dims,n.dims),l=r.dims,p=G.size(r.dims),f=!1,m=!1,y=[u];if(u){let $=Ji.calcShape(r.dims,n.dims,!1);if(!$)throw new Error("Can't perform binary op on the given tensors");l=$,p=G.size(l);let c=G.size(r.dims)===1,x=G.size(n.dims)===1,T=r.dims.length>0&&r.dims[r.dims.length-1]%4===0,_=n.dims.length>0&&n.dims[n.dims.length-1]%4===0;y.push(c),y.push(x),y.push(T),y.push(_);let v=1;for(let k=1;k$.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:$=>fm($,r.dims,n.dims,l,f,u,m,i,r.dataType,n.dataType,a,o),getRunData:()=>({outputs:[{dims:l,dataType:a}],dispatchGroup:{x:Math.ceil(p/64/4)},programUniforms:[{type:12,data:Math.ceil(G.size(l)/4)},...he(r.dims,n.dims,l)]})}},Sr=(e,t,r,n,i,o)=>{e.compute(hm(t,i??"",e.inputs[0],e.inputs[1],r,n,o))},hw=e=>{Sr(e,"Add",(t,r)=>`${t}+${r}`)},mw=e=>{Sr(e,"Div",(t,r)=>`${t}/${r}`)},gw=e=>{Sr(e,"Equal",{scalar:(t,r)=>`u32(${t}==${r})`,vector:(t,r)=>`vec4(${t}==${r})`},void 0,void 0,9)},yw=e=>{Sr(e,"Mul",(t,r)=>`${t}*${r}`)},vw=e=>{let t=q("input",e.inputs[0].dataType,e.inputs[0].dims).type.value;Sr(e,"Pow",{scalar:(r,n)=>`pow_custom(${r},${n})`,vector:(r,n)=>`pow_vector_custom(${r},${n})`},` + 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)); + } + `)},ww=e=>{Sr(e,"Sub",(t,r)=>`${t}-${r}`)},$w=e=>{Sr(e,"Greater",{scalar:(t,r)=>`u32(${t}>${r})`,vector:(t,r)=>`vec4(${t}>${r})`},void 0,void 0,9)},_w=e=>{Sr(e,"Less",{scalar:(t,r)=>`u32(${t}<${r})`,vector:(t,r)=>`vec4(${t}<${r})`},void 0,void 0,9)},bw=e=>{Sr(e,"GreaterOrEqual",{scalar:(t,r)=>`u32(${t}>=${r})`,vector:(t,r)=>`vec4(${t}>=${r})`},void 0,void 0,9)},xw=e=>{Sr(e,"LessOrEqual",{scalar:(t,r)=>`u32(${t}<=${r})`,vector:(t,r)=>`vec4(${t}<=${r})`},void 0,void 0,9)}}),ri,ni,ii,mc,ui=Z(()=>{ve(),Ee(),ri=(e,t,r="f32")=>{switch(e.activation){case"Relu":return`value = max(value, ${t}(0.0));`;case"Sigmoid":return`value = (${t}(1.0) / (${t}(1.0) + exp(-value)));`;case"Clip":return`value = clamp(value, ${t}(${r}(uniforms.clip_min)), ${t}(${r}(uniforms.clip_max)));`;case"HardSigmoid":return`value = max(${t}(0.0), min(${t}(1.0), ${r}(uniforms.alpha) * value + ${r}(uniforms.beta)));`;case"LeakyRelu":return`value = select(${r}(uniforms.alpha) * value, value, value >= ${t}(0.0));`;case"":return"";default:throw new Error(`Unsupported activation ${e.activation}`)}},ni=(e,t)=>{e.activation==="Clip"?t.push({type:1,data:e.clipMax},{type:1,data:e.clipMin}):e.activation==="HardSigmoid"?t.push({type:1,data:e.alpha},{type:1,data:e.beta}):e.activation==="LeakyRelu"&&t.push({type:1,data:e.alpha})},ii=(e,t)=>{e.activation==="Clip"?t.push({name:"clip_max",type:"f32"},{name:"clip_min",type:"f32"}):e.activation==="HardSigmoid"?t.push({name:"alpha",type:"f32"},{name:"beta",type:"f32"}):e.activation==="LeakyRelu"&&t.push({name:"alpha",type:"f32"})},mc=e=>{let t=(e==null?void 0:e.activation)||"";if(t==="HardSigmoid"){let[r,n]=(e==null?void 0:e.activation_params)||[.2,.5];return{activation:t,alpha:r,beta:n}}else if(t==="Clip"){let[r,n]=(e==null?void 0:e.activation_params)||[dc,pc];return{activation:t,clipMax:n,clipMin:r}}else if(t==="LeakyRelu"){let[r]=(e==null?void 0:e.activation_params)||[.01];return{activation:t,alpha:r}}return{activation:t}}}),At,gc,yc=Z(()=>{At=(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.`)}},gc=e=>` + ${e?"value = value + getBiasByOutputCoords(coords);":""} + `}),vc,Sw=Z(()=>{vc=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)); +} +`}),mm,gm,gu,zl,ym,yu,vm,wc,Pu=Z(()=>{ve(),Ee(),Se(),ui(),yc(),mm=(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":""}); + `,gm=(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];"} + }`,gu=(e,t,r="f32",n,i=!1,o=32,a=!1,u=32)=>{let l=t[1]*e[1],p=t[0]*e[0],f=i?l:o,m=i?o:l,y=f/t[0],$=o/t[1];if(!((i&&y===4&&e[1]===4||!i&&(y===3||y===4))&&f%t[0]===0&&o%t[1]===0&&e[0]===4))throw new Error(`If transposeA ${i} is true, innerElementSize ${y} and workPerThread[1] ${e[1]} must be 4. + Otherwise, innerElementSize ${y} must be 3 or 4. + tileAWidth ${f} must be divisible by workgroupSize[0]${t[0]}. tileInner ${o} must be divisible by workgroupSize[1] ${t[1]}. colPerThread ${e[0]} must be 4.`);return` +var mm_Asub: array, ${f/y}>, ${m}>; +var mm_Bsub: array, ${p/e[0]}>, ${o}>; + +const rowPerThread = ${e[1]}; +const colPerThread = ${e[0]}; +const innerElementSize = ${y}; +const tileInner = ${o}; + +@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 = ${a?"0":"i32(globalId.z)"}; + ${n?`let batchIndices = ${n.offsetToIndices("u32(batch)")};`:""} + let globalRowStart = i32(workgroupId.y) * ${l}; + + let num_tiles = ${a?`${Math.ceil(u/o)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; + var kStart = ${a?`i32(globalId.z) * ${u}`:"0"}; + + var acc: array, rowPerThread>; + + // Loop over shared dimension. + let tileRowB = localRow * ${$}; + for (var t = 0; t < num_tiles; 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; + ${mm(i,n)} + } + + // Load one tile of B into local memory. + for (var innerRow = 0; innerRow < ${$}; innerRow = innerRow + 1) { + let inputRow = tileRowB + innerRow; + let inputCol = tileCol; + mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol${n?", 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]; + ${y===3?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"} + + ${gm(i,y)} + } + + workgroupBarrier(); + } + + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]); + } +}`},zl=(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":""}); + `,ym=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",yu=(e,t,r="f32",n,i=!1,o=32,a=!1,u=32,l=!1)=>{let p=e[1]*t[1],f=e[0]*t[0],m=i?p:o,y=i?o:p;if(!(y%t[1]===0&&m%t[0]===0&&o%t[1]===0))throw new Error(`tileAHight ${y} must be divisible by workgroupSize[1]${t[1]}, tileAWidth ${m} must be divisible by workgroupSize[0]${t[0]}, tileInner ${o} must be divisible by workgroupSize[1]${t[1]}`);let $=y/t[1],c=m/t[0],x=o/t[1],T=l?` + let localRow = i32(localId.y); + let localCol = i32(localId.x); + let globalRowStart = i32(workgroupId.y) * ${p}; + let globalColStart = i32(workgroupId.x) * ${f}; + + // Loop over shared dimension. + for (var t = 0; t < num_tiles; t = t + 1) { + // Load one tile of A into local memory. + for (var inputRow = localRow; inputRow < ${y}; inputRow = inputRow + ${t[1]}) { + for (var inputCol = localCol; inputCol < ${m}; inputCol = inputCol + ${t[0]}) { + ${zl(i,n)} + } + } + // Load one tile of B into local memory. + for (var inputRow = localRow; inputRow < ${o}; inputRow = inputRow + ${t[1]}) { + for (var inputCol = localCol; inputCol < ${f}; inputCol = inputCol + ${t[0]}) { + mm_Bsub[inputRow][inputCol] = mm_readB(batch, + kStart + inputRow, + globalColStart + inputCol${n?", batchIndices":""}); + } + } + kStart = kStart + tileInner; + workgroupBarrier(); + + // Compute acc values for a single thread. + var BCached : array<${r}, 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) * ${p}; + +let tileRowA = i32(localId.y) * ${$}; +let tileColA = i32(localId.x) * ${c}; +let tileRowB = i32(localId.y) * ${x}; +// Loop over shared dimension. +for (var t = 0; t < num_tiles; t = t + 1) { + // Load one tile of A into local memory. + for (var innerRow = 0; innerRow < ${$}; innerRow = innerRow + 1) { + for (var innerCol = 0; innerCol < ${c}; innerCol = innerCol + 1) { + let inputRow = tileRowA + innerRow; + let inputCol = tileColA + innerCol; + ${zl(i,n)} + } + } + + // Load one tile of B into local memory. + for (var innerRow = 0; innerRow < ${x}; 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${n?", batchIndices":""}); + } + } + kStart = kStart + tileInner; + workgroupBarrier(); + + // Compute acc values for a single thread. + var BCached : array<${r}, 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) { + ${ym(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, ${y}>; + var mm_Bsub : array, ${o}>; + const rowPerThread = ${e[1]}; + const colPerThread = ${e[0]}; + const tileInner = ${o}; + +@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 = ${a?"0":"i32(globalId.z)"}; + ${n?`let batchIndices = ${n.offsetToIndices("u32(batch)")};`:""} + let num_tiles = ${a?`${Math.ceil(u/o)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; + var kStart = ${a?`i32(globalId.z) * ${u}`:"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; + } + } + ${T} + } +`},vm=(e,t,r,n,i,o=!1)=>{let[a,u,l]=i,[p,f,m,y]=n,$=vo(a,l),c=vo(u,l),x=wt(n[0].type.tensor),T=()=>{let v=f.rank,k=p.rank,C=`var aIndices: ${f.type.indices};`;for(let I=v-2-1,M=k-1;I>=0;I--,M--)C+=` +aIndices[${I}] = ${k>1?`batchIndices[${M}]`:"batchIndices"};`;return $.forEach(I=>{C+=` +aIndices[${I}] = 0;`}),C+=` +aIndices[${v-2}] = u32(row); + aIndices[${v-1}] = u32(colIn);`,C},_=()=>{let v=m.rank,k=p.rank,C=`var bIndices: ${m.type.indices};`;for(let I=v-2-1,M=k-1;I>=0;I--,M--)C+=` +bIndices[${I}] = ${k>1?`batchIndices[${M}]`:"batchIndices"};`;return c.forEach(I=>{C+=` +bIndices[${I}] = 0;`}),C+=` +bIndices[${v-2}] = u32(row); + bIndices[${v-1}] = u32(colIn);`,C};return` + fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${p.type.indices}) -> ${At(e,x)} { + var value = ${At(e,x)}(0.0); + let col = colIn * ${e}; + if(row < uniforms.dim_a_outer && col < uniforms.dim_inner) + { + ${T()} + value = ${f.getByIndices("aIndices")}; + } + return value; + } + + fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${p.type.indices}) -> ${At(e,x)} { + var value = ${At(e,x)}(0.0); + let col = colIn * ${e}; + if(row < uniforms.dim_inner && col < uniforms.dim_b_outer) + { + ${_()} + value = ${m.getByIndices("bIndices")}; + } + return value; + } + + fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${At(e,x)}) { + let col = colIn * ${e}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) { + var value = valueIn; + let coords = vec3(batch, row, colIn); + ${t?`value = value + ${o?"bias[colIn]":`${At(e,x)}(bias[row])`};`:""} + ${r} + ${y.setByIndices("vec3(coords)","value")} + } + } + `},wc=(e,t,r,n,i=!1)=>{let o=e[0].dims,a=e[1].dims,u=o.slice(0,-2),l=a.slice(0,-2),p=n?n.slice(0,-2):r.slice(0,-2),f=G.size(p),m=o[o.length-2],y=o[o.length-1],$=a[a.length-1],c=y%4===0&&$%4===0,x=m<=8?[4,1,1]:[4,4,1],T=[8,8,1],_=[Math.ceil($/T[0]/x[0]),Math.ceil(m/T[1]/x[1]),Math.ceil(f/T[2]/x[2])],v=c?4:1,k=[...u,m,y/v],C=k.length,I=[...l,y,$/v],M=I.length,P=[f,m,$/v],B=[{type:6,data:m},{type:6,data:$},{type:6,data:y}];ni(t,B),B.push(...he(p,k,I));let H=["rank","rank"],F=e.length>2;F&&(B.push(...he(e[2].dims)),H.push("rank")),B.push(...he(P));let me=ce=>{let se=p.length,xe=cc("batchDims",e[0].dataType,se,1),ze=wt(e[0].dataType),V=q("a",e[0].dataType,C,v),le=q("b",e[1].dataType,M,v),U=pe("result",e[0].dataType,P.length,v),J=[V,le];if(F){let we=i?v:1;J.push(q("bias",e[2].dataType,e[2].dims.length,we))}let Q=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];ii(t,Q);let R=wt(U.type.tensor),ee=ri(t,U.type.value,R),oe=vm(v,F,ee,[xe,V,le,U],[u,l,p],i);return` + ${ce.registerUniforms(Q).registerInternalVariables(xe).declareVariables(...J,U)} + ${oe} + ${c?gu(x,T,ze,xe):yu(x,T,ze,xe)} + `};return{name:"MatMul",shaderCache:{hint:`${x};${t.activation};${c};${i}`,inputDependencies:H},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:_[0],y:_[1],z:_[2]},programUniforms:B}),getShaderSource:me}}}),wm,kw,ux=Z(()=>{ve(),si(),Se(),ui(),yc(),Sw(),Pu(),wm=(e,t,r,n,i=!1,o,a=4,u=4,l=4,p="f32")=>{let f=H=>{switch(H){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 ${H} is not supported.`)}},m=H=>{switch(H){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 ${H} is not supported.`)}},y=e?` + let coord = vec4(batch, xRow, xCol, xCh); + `:` + let coord = vec4(batch, xCh, xRow, xCol); + `,$=e?` + let coords = vec4( + batch, + row / outWidth, + row % outWidth, + col); + `:` + let coords = vec4( + batch, + row, + col / outWidth, + col % outWidth); + `,c=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",x=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",T=e?"row":"col",_=e?"col":"row",v=` + let inChannels = i32(uniforms.w_shape[2]); + let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; + let outRow = ${T} / outWidth; + let outCol = ${T} % outWidth; + + let WRow = ${_} / (i32(uniforms.w_shape[1]) * inChannels); + let WCol = ${_} / inChannels % i32(uniforms.w_shape[1]); + let xRow = outRow * uniforms.stride[0] + uniforms.dilation[0] * WRow - uniforms.pad[0]; + let xCol = outCol * uniforms.stride[1] + uniforms.dilation[1] * WCol - uniforms.pad[1]; + let xCh = ${_} % inChannels; + var resData = ${At(a,p)}(0.0); + // The bounds checking is always needed since we use it to pad zero for + // the 'same' padding type. + if (xRow >= 0 && xRow < ${c} && xCol >= 0 && xCol < ${x}) { + ${y} + let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape)); + ${f(a)} + } + return resData;`,k=e?t&&n?` + let col = colIn * ${a}; + ${v}`:` + let col = colIn * ${a}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { + ${v} + } + return ${At(a,p)}(0.0);`:n&&r?` + let col = colIn * ${a}; + ${v}`:` + let col = colIn * ${a}; + if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { + ${v} + } + return ${At(a,p)}(0.0);`,C=`${m(u)}`,I=At(l,p),M=At(e?a:u,p),P=At(e?u:a,p),B=ri(o,I,p);return` + fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${M} { + ${e?k:C} + } + + fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${P} { + ${e?C:k} + } + + fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${I}) { + let col = colIn * ${l}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) + { + var value = valueIn; + let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; + ${$} + ${gc(i)} + ${B} + setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); + } + }`},kw=(e,t,r,n,i,o,a,u)=>{let l=t.format==="NHWC",p=l?e[0].dims[3]:e[0].dims[1],f=r[0],m=l?r[2]:r[3],y=l?r[1]:r[2],$=l?r[3]:r[1],c=l&&(p%4===0||p%3===0)&&$%4===0,x=l?$:m*y,T=l?m*y:$,_=[8,8,1],v=n<=8?[4,1,1]:[4,4,1],k=[Math.ceil(x/_[0]/v[0]),Math.ceil(T/_[1]/v[1]),Math.ceil(f/_[2]/v[2])];rt("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${k}`);let C=c?l&&p%4!==0?3:4:1,I=_[1]*v[1],M=_[0]*v[0],P=Math.max(_[0]*C,_[1]),B=n%I===0,H=i%M===0,F=o%P===0,me=c?[C,4,4]:[1,1,1],ce=[{type:6,data:n},{type:6,data:i},{type:6,data:o},{type:6,data:[t.pads[0],t.pads[1]]},{type:6,data:t.strides},{type:6,data:t.dilations}];ni(t,ce),ce.push(...he(e[0].dims,e[1].dims));let se=["rank","rank"];a&&(ce.push(...he(e[2].dims)),se.push("rank")),ce.push(...he(r));let xe=ze=>{let V=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"},{name:"pad",type:"i32",length:2},{name:"stride",type:"i32",length:2},{name:"dilation",type:"i32",length:2}];ii(t,V);let le=c?4:1,U=wt(e[0].dataType),J=` + fn setOutputAtIndex(flatIndex : i32, value : ${c?`vec4<${U}>`:U}) { + result[flatIndex] = ${c?`vec4<${U}>`:U}(value); + } + fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${c?`vec4<${U}>`:U}) { + let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3)); + setOutputAtIndex(flatIndex ${c?"/ 4":""}, value); + }`,Q=q("x",e[0].dataType,e[0].dims.length,C===3?1:C),R=q("w",e[1].dataType,e[1].dims.length,le),ee=[Q,R],oe=pe("result",e[0].dataType,r.length,le);if(a){let we=q("bias",e[2].dataType,e[2].dims.length,le);ee.push(we),J+=` + fn getBiasByOutputCoords(coords : vec4) -> ${c?`vec4<${U}>`:U} { + return bias[coords.${l?"w":"y"}${c?"/ 4":""}]; + }`}return` + ${vc("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 }; + ${ze.registerUniforms(V).declareVariables(...ee,oe)} + ${J} + ${wm(l,B,H,F,a,t,me[0],me[1],me[2],U)} + ${c?gu(v,_,U,void 0,!l,P):yu(v,_,U,void 0,!l,P,!1,void 0,u)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${t.cacheKey};${C};${c};${B};${H};${F};${I};${M};${P}`,inputDependencies:se},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:k[0],y:k[1],z:k[2]},programUniforms:ce}),getShaderSource:xe}}}),Zd,Ew,lx=Z(()=>{ve(),Ee(),Se(),Iw(),ui(),Zd=(e,t,r)=>{let n=e.length>2,i=n?"value += b[output_channel];":"",o=e[0].dims,a=e[1].dims,u=a[0]/t.group,l=t.format==="NHWC",p=Ds(o,a,t.dilations,t.pads,t.strides,l),f=G.size(p),m=[{type:12,data:f},{type:12,data:t.dilations},{type:12,data:[t.strides[0],t.strides[1]]},{type:12,data:[t.pads[0],t.pads[1]]},{type:12,data:u}];ni(t,m),m.push(...he(o,a));let y=["rank","rank"];n&&(m.push(...he(e[2].dims)),y.push("rank")),m.push(...he(p));let $=c=>{let x=pe("output",e[0].dataType,p.length),T=wt(x.type.tensor),_=ri(t,x.type.value,T),v=q("x",e[0].dataType,o.length),k=q("w",e[1].dataType,a.length),C=[v,k];n&&C.push(q("b",e[2].dataType,e[2].dims.length));let I=[{name:"output_size",type:"u32"},{name:"dilations",type:"u32",length:t.dilations.length},{name:"strides",type:"u32",length:2},{name:"pads",type:"u32",length:2},{name:"output_channels_per_group",type:"u32"}];return ii(t,I),` + ${c.registerUniforms(I).declareVariables(...C,x)} + + ${c.mainStart()} + ${c.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let outputIndices = ${x.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}]) * uniforms.strides - uniforms.pads; + let group_id: u32 = output_channel / uniforms.output_channels_per_group; + + var value: ${x.type.value} = ${x.type.value}(0); + for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[1]; wInChannel++) { + let input_channel = group_id * uniforms.w_shape[1] + wInChannel; + for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[2]; wHeight++) { + let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0]; + + if (xHeight < 0u || xHeight >= uniforms.x_shape[${l?1:2}]) { + continue; + } + + for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[3]; wWidth++) { + let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1]; + if (xWidth < 0u || xWidth >= uniforms.x_shape[${l?2:3}]) { + continue; + } + + let xVal = ${l?v.get("batch","xHeight","xWidth","input_channel"):v.get("batch","input_channel","xHeight","xWidth")}; + let wVal = ${k.get("output_channel","wInChannel","wHeight","wWidth")}; + value += xVal*wVal; + } + } + } + ${i} + ${_} + ${x.setByOffset("global_idx","value")} + }`};return{name:"GroupedConv",shaderCache:{hint:t.cacheKey,inputDependencies:y},getRunData:()=>({outputs:[{dims:r?r(p):p,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(f/64)},programUniforms:m}),getShaderSource:$}},Ew=(e,t,r)=>{let n=e.length>2,i=ot(r[3]),o=ot(r[2]),a=G.size(r)/i/o,u=[e[0].dims[0],e[0].dims[1],e[0].dims[2],e[0].dims[3]/i],l=[e[1].dims[0],e[1].dims[1],e[1].dims[2],e[1].dims[3]/i],p=[r[0],r[1],r[2],r[3]/i],f=[{type:12,data:a},{type:6,data:[t.strides[0],t.strides[1]]},{type:6,data:[t.pads[0],t.pads[1]]}];ni(t,f),f.push(...he(u,l,p));let m=(o-1)*t.strides[1]+l[1],y=$=>{let c=pe("output",e[0].dataType,p.length,i),x=wt(c.type.tensor),T=ri(t,c.type.value,x),_=q("x",e[0].dataType,u.length,i),v=q("w",e[1].dataType,l.length,i),k=[_,v];n&&k.push(q("b",e[2].dataType,e[2].dims,i));let C=n?"value += b[output_channel];":"",I=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return ii(t,I),` + ${$.registerUniforms(I).declareVariables(...k,c)} + ${$.mainStart()} + ${$.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let width0 = uniforms.output_shape[3]; + let output_channel = global_idx % width0; + var index1 = global_idx / width0; + let width1 = uniforms.output_shape[2] / ${o}u; + let col = (index1 % width1) * ${o}u; + index1 = index1 / width1; + let row = index1 % uniforms.output_shape[1]; + let batch = index1 / uniforms.output_shape[1]; + + let x_corner = vec2(i32(row), i32(col)) * uniforms.strides - uniforms.pads; + + var x_vals: array<${_.type.value}, ${m}>; + var values: array<${c.type.value}, ${o}>; + let input_channel = output_channel; + // Use constant instead of uniform can give better performance for w's height/width. + for (var w_height: u32 = 0u; w_height < ${l[0]}; w_height++) { + let x_height = x_corner.x + i32(w_height); + if (x_height >= 0 && u32(x_height) < uniforms.x_shape[1]) { + for (var i = 0; i < ${m}; i++) { + let x_width = x_corner.y + i; + if (x_width >= 0 && u32(x_width) < uniforms.x_shape[2]) { + x_vals[i] = ${_.get("batch","u32(x_height)","u32(x_width)","input_channel")}; + } else { + x_vals[i] = ${_.type.value}(0); + } + } + for (var w_width: u32 = 0u; w_width < ${l[1]}; w_width++) { + let w_val = ${v.get("w_height","w_width","0","output_channel")}; + for (var i = 0u; i < ${o}u; i++) { + values[i] = fma(x_vals[i * u32(uniforms.strides[1]) + w_width], w_val, values[i]); + } + } + } + } + + for (var i = 0u; i < ${o}u; i++) { + var value = values[i]; + ${C} + ${T} + ${c.set("batch","row","col + i","output_channel","value")}; + } + }`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${t.cacheKey};${i};${o};${m};${l[0]};${l[1]}`,inputDependencies:n?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:f}),getShaderSource:y}}}),Jd,$m,Cw,Tw=Z(()=>{ve(),Ee(),Pu(),Se(),ui(),Jd=(e,t,r,n,i=!1)=>{let o=e[0].dims,a=e[1].dims,u=o[o.length-2],l=a[a.length-1],p=o[o.length-1],f=ot(l),m=ot(p),y=ot(u),$=G.size(r)/f/y,c=e.length>2,x=n?n.slice(0,-2):r.slice(0,-2),T=[G.size(x),u,l],_=[{type:12,data:$},{type:12,data:u},{type:12,data:l},{type:12,data:p}];ni(t,_),_.push(...he(x,o,a)),c&&_.push(...he(e[2].dims)),_.push(...he(T));let v=k=>{let C=cc("batch_dims",e[0].dataType,x.length),I=q("a",e[0].dataType,o.length,m),M=q("b",e[1].dataType,a.length,f),P=pe("output",e[0].dataType,T.length,f),B=wt(P.type.tensor),H=ri(t,P.type.value,B),F=[I,M],me="";if(c){let J=i?f:1;F.push(q("bias",e[2].dataType,e[2].dims.length,J)),me=`${i?`value += bias[col / ${J}];`:`value += ${P.type.value}(bias[row + i]);`}`}let ce=o.slice(0,-2),se=a.slice(0,-2),xe=vo(ce,x),ze=vo(se,x),V=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];ii(t,V);let le=(J,Q)=>{let R=J.rank,ee=J.name;if(R===2)return`var ${ee}_indices = ${J.type.indices}(0u, 0u);`;let oe=C.rank,we=`var ${ee}_indices: ${J.type.indices};`;for(let Ce=R-2-1,Le=oe-1;Ce>=0;Ce--,Le--)we+=` +${ee}_indices[${Ce}] = ${oe>1?`batch_indices[${Le}]`:"batch_indices"};`;return Q.forEach(Ce=>{we+=` +${ee}_indices[${Ce}] = 0;`}),we+=`${ee}_indices[${R-2}] = 0u; + ${ee}_indices[${R-1}] = 0u;`,we},U=()=>{let J=`var a_data: ${I.type.value};`;for(let Q=0;Q; + for (var k: u32 = 0u; k < uniforms.K; k = k + ${m}) { + ${U()} + } + for (var i = 0u; i < ${y}u; i++) { + var value = values[i]; + ${me} + ${H} + let cur_indices = ${P.type.indices}(batch, row + i, col); + let offset = ${P.indicesToOffset("cur_indices")}; + ${P.setByOffset(`offset / ${f}`,"value")}; + } + } + `};return{name:"MatMulNaive",shaderCache:{hint:`${t.activation};${f};${m};${y};${i}`,inputDependencies:c?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil($/64)},programUniforms:_}),getShaderSource:v}},$m=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.")},Cw=e=>{$m(e.inputs);let t=Ji.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],n=e.inputs[0].dims[e.inputs[0].dims.length-1];r<8&&n<8?e.compute(Jd(e.inputs,{activation:""},t)):e.compute(wc(e.inputs,{activation:""},t))}}),Ds,ys,_m,Ol,ep,bm,xm,tp,Iw=Z(()=>{Ee(),ux(),Pu(),lx(),ui(),Tw(),ko(),Ds=(e,t,r,n,i,o)=>{let a=e[0],u=e.slice(o?1:2,o?3:4),l=u.length,p=t[0],f=t.slice(2).map((y,$)=>y+(y-1)*(r[$]-1)),m=u.map((y,$)=>y+n[$]+n[$+l]).map((y,$)=>Math.floor((y-f[$]+i[$])/i[$]));return m.splice(0,0,a),m.splice(o?3:1,0,p),m},ys=[2,3,1,0],_m=(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],n=e[1].dims[1]*t.group;if(r!==n)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")},Ol=(e,t)=>{let r=e.kernelShape.slice();for(let o=2;o{let t=mc(e),r=e.format,n=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],i=e.dilations,o=e.group,a=e.kernel_shape,u=e.pads,l=e.strides,p=e.w_is_const();return{autoPad:n,format:r,dilations:i,group:o,kernelShape:a,pads:u,strides:l,wIsConst:p,...t,cacheKey:`${e.format};${t.activation};`}},bm=(e,t,r)=>{let n=Ol(r,t),i=r.format==="NHWC";if(r.group!==1){if(!e.adapterInfo.isArchitecture("ampere")&&i&&t[1].dims[0]===r.group&&t[1].dims[1]===1&&r.dilations[0]===1&&r.dilations[1]===1){let M=Ds(t[0].dims,t[1].dims,r.dilations,n.pads,r.strides,i),P=e.kernelCustomData.wT??e.compute(Zr(t[1],ys),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=P);let B=[t[0],P];t.length===3&&B.push(t[2]),e.compute(Ew(B,n,M),{inputs:B})}else e.compute(Zd(t,n));return}let o=t.length===3,a=t[0].dims[i?1:2],u=t[0].dims[i?2:3],l=t[0].dims[i?3:1],p=t[1].dims[2],f=t[1].dims[3],m=Ds(t[0].dims,t[1].dims,r.dilations,n.pads,r.strides,i),y=m[i?1:2],$=m[i?2:3],c=m[i?3:1],x=i&&p===a&&f===u&&r.pads[0]===0&&r.pads[1]===0;if(x||p===1&&f===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 M=m[0],P,B,H,F=[];if(i){let se=e.kernelCustomData.wT??e.compute(Zr(t[1],ys),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];if(r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=se),x){let xe=a*u*l;P=t[0].reshape([1,M,xe]),B=se.reshape([1,xe,c]),H=[1,M,c]}else P=t[0].reshape([M,a*u,l]),B=se.reshape([1,l,c]),H=[M,y*$,c];F.push(P),F.push(B)}else P=t[0].reshape([M,l,a*u]),B=t[1].reshape([1,c,l]),H=[M,c,y*$],F.push(B),F.push(P);o&&F.push(t[2]);let me=H[2],ce=F[0].dims[F[0].dims.length-1];me<8&&ce<8?e.compute(Jd(F,n,m,H,i),{inputs:F}):e.compute(wc(F,n,m,H,i),{inputs:F});return}let T=!0,_=e.kernelCustomData.wT??e.compute(Zr(t[1],ys),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=_);let v=[t[0],_];o&&v.push(t[2]);let k=i?y*$:c,C=i?c:y*$,I=p*f*l;e.compute(kw(v,n,m,k,C,I,o,T),{inputs:v})},xm=(e,t)=>{let r=t.format==="NHWC",n=[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&&n.push(e.inputs[2]);let i=[0,t.pads[0],0,t.pads[1]],o=[1].concat(t.strides),a=[1].concat(t.dilations),u=[1].concat(t.kernelShape),l=Ol({...t,pads:i,strides:o,dilations:a,kernelShape:u},n);e.compute(Zd(n,l,p=>r?[p[0],p[2],p[3]]:[]))},tp=(e,t)=>{_m(e.inputs,t),e.inputs[0].dims.length===3?xm(e,t):bm(e,e.inputs,t)}}),Sm,Aw,dx=Z(()=>{ve(),si(),Se(),ui(),yc(),Sw(),Pu(),Sm=(e,t=!1,r,n,i=4)=>{let o=T=>{switch(T){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 ${n}(v0, v1, v2, v3); + `;default:throw new Error(`innerElementSize ${T} is not supported.`)}},a=e?` + let coord = vec4(batch, iXR, iXC, xCh); + `:` + let coord = vec4(batch, xCh, iXR, iXC); + `,u=e?` + let coords = vec4( + batch, + row / outWidth, + row % outWidth, + col); + `:` + let coords = vec4( + batch, + row, + col / outWidth, + col % outWidth); + `,l=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",p=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",f=e?"row":"col",m=e?"col":"row",y=` + let inChannels = ${e?"i32(uniforms.x_shape[3])":"i32(uniforms.x_shape[1])"}; + let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; + let outRow = ${f} / outWidth; + let outCol = ${f} % outWidth; + + let WRow = ${m} / (uniforms.filter_dims[1] * inChannels); + let WCol = ${m} / inChannels % uniforms.filter_dims[1]; + let xR = f32(outRow - uniforms.pads[0] + uniforms.dilations[0] * WRow) / f32(uniforms.strides[0]); + let xC = f32(outCol - uniforms.pads[1] + uniforms.dilations[1] * WCol) / f32(uniforms.strides[1]); + if (xR < 0.0 || xR >= f32(${l}) || fract(xR) > 0.0) { + return ${n}(0.0); + } + if (xC < 0.0 || xC >= f32(${p}) || fract(xC) > 0.0) { + return ${n}(0.0); + } + let iXR = i32(xR); + let iXC = i32(xC); + let xCh = ${m} % inChannels; + ${a} + return x[getIndexFromCoords4D(coord, vec4(uniforms.x_shape))/${i}];`,$=e?` + let col = colIn * ${i}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { + ${y} + } + return ${n}(0.0);`:` + let col = colIn * ${i}; + if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { + ${y} + } + return ${n}(0.0);`,c=` + let col = colIn * ${i}; + let inChannels = ${e?"i32(uniforms.x_shape[3])":"i32(uniforms.x_shape[1])"}; + let coordX = uniforms.filter_dims[0] - 1 - row / (uniforms.filter_dims[1] * inChannels); + let coordY = uniforms.filter_dims[1] - 1 - (row / inChannels) % uniforms.filter_dims[1]; + if (${e?"row < uniforms.dim_inner && col < uniforms.dim_b_outer":"row < uniforms.dim_inner && col < uniforms.dim_a_outer"} && coordX >= 0 && coordY >= 0) { + let rowInner = row % inChannels; + let coord = vec4(coordX, coordY, col, rowInner); + ${o(i)} + } + return ${n}(0.0); + `,x=ri(r,n);return` + fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${n} { + ${e?$:c} + } + + fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${n} { + ${e?c:$} + } + + fn mm_write(batch: i32, row : i32, colIn : i32, valueInput : ${n}) { + let col = colIn * ${i}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) { + var value = valueInput; + let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; + ${u} + ${gc(t)} + ${x} + result[getIndexFromCoords4D(coords, vec4(uniforms.result_shape))/${i}] = value; + } + }`},Aw=(e,t,r,n,i,o,a,u)=>{let l=t.format==="NHWC",p=l?e[0].dims[3]:e[0].dims[1],f=r[0],m=l?r[2]:r[3],y=l?r[1]:r[2],$=l?r[3]:r[1],c=l&&p%4===0&&p%3&&$%4===0,x=l?$:m*y,T=l?m*y:$,_=[8,8,1],v=n<=8?[4,1,1]:[4,4,1],k=[Math.ceil(x/_[0]/v[0]),Math.ceil(T/_[1]/v[1]),Math.ceil(f/_[2]/v[2])];rt("verbose",()=>`[conv_backprop_mm_webgpu] dispatch = ${k}`);let C=c?4:1,I=Math.max(_[0]*C,_[1]),M=c?4:1,P=[t.kernelShape[l?1:2],t.kernelShape[l?2:3]],B=[P[0]+(t.dilations[0]<=1?0:(P[0]-1)*(t.dilations[0]-1)),P[1]+(t.dilations[1]<=1?0:(P[1]-1)*(t.dilations[1]-1))],H=[B[0]-1-Math.floor((t.pads[0]+t.pads[2])/2),B[1]-1-Math.floor((t.pads[1]+t.pads[3])/2)],F=[{type:6,data:n},{type:6,data:i},{type:6,data:o},{type:6,data:t.strides},{type:6,data:t.dilations},{type:6,data:P},{type:6,data:H}];ni(t,F),F.push(...he(e[0].dims,e[1].dims));let me=["rank","rank"];a&&(F.push(...he(e[2].dims)),me.push("rank")),F.push(...he(r));let ce=se=>{let xe=q("x",e[0].dataType,e[0].dims.length,M),ze=q("w",e[1].dataType,e[1].dims.length,1),V=pe("result",e[0].dataType,r.length,M),le=[xe,ze],U="";if(a){let R=q("bias",e[2].dataType,e[2].dims.length,M);le.push(R),U+=` + fn getBiasByOutputCoords(coords : vec4) -> ${R.type.value} { + return bias[coords.${l?"w":"y"}${c?"/ 4":""}]; + }`}let J=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"},{name:"strides",type:"i32",length:2},{name:"dilations",type:"i32",length:2},{name:"filter_dims",type:"i32",length:P.length},{name:"pads",type:"i32",length:H.length}];ii(t,J);let Q=wt(e[0].dataType,1);if(Q!=="f16"&&Q!=="f32")throw new Error(`elemType ${Q} is not supported.`);return` + ${vc("uniforms.result_strides")} + ${se.registerUniforms(J).declareVariables(...le,V)}; + ${U} + ${Sm(l,a,t,xe.type.value,C)} + ${c?gu(v,_,Q,void 0,!l,I):yu(v,_,Q,void 0,!l,I,!1,void 0,u)}`};return{name:"Conv2DTransposeMatMul",shaderCache:{hint:`${t.cacheKey};${v};${_};${c}`,inputDependencies:me},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:k[0],y:k[1],z:k[2]},programUniforms:F}),getShaderSource:ce}}}),km,rp,px=Z(()=>{ve(),si(),Ee(),Se(),km=(e,t,r,n,i,o=!1,a,u,l=!1)=>{let p=l?1:2,f=l?2:3,m=l?3:1,y=o?2:1,$=` + fn setOutputAtIndex(flatIndex : u32, value : ${o?`vec4<${a}>`:a}) { + result[flatIndex] = ${o?`vec4<${a}>`:a}(value); + }`;n&&($+=` + fn getBiasByOutputCoords(coords : vec4) -> ${o?`vec4<${a}>`:a} { + return bias[coords.${l?"w":"y"}${o?"/ 4":""}]; + }`);let c=o?4:1,x=q("W",t[1].dataType,t[1].dims.length,c),T=q("Dy",t[0].dataType,t[0].dims.length,c),_=[T,x];n&&_.push(q("bias",t[2].dataType,[r[m]].length,c));let v=pe("result",t[0].dataType,r.length,c),k=`{ + let batch: u32 = ${i?"global_id.z":"workgroup_id.z"} / uniforms.result_shape[1]; + let r = ${i?"global_id.z":"workgroup_id.z"} % uniforms.result_shape[1]; + let c = ${i?"global_id.y":"workgroup_id.y"} * ${y}; + let d1: u32 = ${i?"global_id.x":"workgroup_id.x"} * 4; + + let dyCorner = vec2(i32(r), i32(c)) - vec2(uniforms.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, ${y}>; + for (var i = 0; i < ${y}; i++) { + dotProd[i] = vec4<${a}>(0.0); + } + for (var wR: u32 = 0; wR < uniforms.filter_dims[0]; wR = wR + 1) { + var dyR = (${a}(dyCorner.x) + ${a}(wR)) / ${a}(uniforms.strides.x); + let wRPerm = uniforms.filter_dims[0] - 1 - wR; + if (dyR < 0.0 || dyR >= ${a}(uniforms.Dy_shape[1]) || + fract(dyR) > 0.0 || wRPerm < 0) { + continue; + } + let idyR: u32 = u32(dyR); + + for (var wC: u32 = 0; wC < uniforms.filter_dims[1]; wC = wC + 1) { + let dyC = (${a}(dyCorner.y) + ${a}(wC)) / ${a}(uniforms.strides.y); + let dyC2 = (${a}(dyCorner.y) + 1.0 + ${a}(wC)) / ${a}(uniforms.strides.y); + let wCPerm = uniforms.filter_dims[1] - 1 - wC; + if (wCPerm < 0) { + continue; + } + var bDyCVal = true; + var bDyCVal2 = true; + if (dyC < 0.0 || dyC >= ${a}(uniforms.Dy_shape[2]) || + fract(dyC) > 0.0) { + bDyCVal = false; + } + if (dyC2 < 0.0 || dyC2 >= ${a}(uniforms.Dy_shape[2]) || + fract(dyC2) > 0.0) { + bDyCVal2 = false; + } + + let idyC: u32 = u32(dyC); + let idyC2: u32 = u32(dyC2); + if (bDyCVal && bDyCVal2) { + let d2Length = uniforms.Dy_shape[3]; + for (var d2 :u32 = 0; d2 < d2Length; d2 = d2 + 4) { + let wValue0 = ${x.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; + let wValue1 = ${x.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; + let wValue2 = ${x.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; + let wValue3 = ${x.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; + + var xValue = ${T.get("batch","idyR","idyC","d2")}; + let tmpval = vec4<${a}>(dot(xValue, wValue0), + dot(xValue, wValue1), + dot(xValue, wValue2), + dot(xValue, wValue3)); + dotProd[0] = dotProd[0] + tmpval; + + xValue = ${T.get("batch","idyR","idyC2","d2")}; + + dotProd[1] = dotProd[1] + vec4<${a}>(dot(xValue, wValue0), + dot(xValue, wValue1), + dot(xValue, wValue2), + dot(xValue, wValue3)); + } + } else if (bDyCVal) { + let d2Length = uniforms.Dy_shape[${m}]; + for (var d2: u32 = 0; d2 < d2Length; d2 = d2 + 4) { + let wValue0 = ${x.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; + let wValue1 = ${x.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; + let wValue2 = ${x.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; + let wValue3 = ${x.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; + + var xValue = ${T.get("batch","idyR","idyC","d2")}; + let tmpval = vec4<${a}>(dot(xValue, wValue0), + dot(xValue, wValue1), + dot(xValue, wValue2), + dot(xValue, wValue3)); + dotProd[0] = dotProd[0] + tmpval; + } + } else if (bDyCVal2) { + let d2Length = uniforms.Dy_shape[3]; + for (var d2: u32 = 0; d2 < d2Length; d2 = d2 + 4) { + let wValue0 = ${x.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; + let wValue1 = ${x.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; + let wValue2 = ${x.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; + let wValue3 = ${x.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; + + var xValue = ${T.get("batch","idyR","idyC2","d2")}; + let tmpval = vec4<${a}>(dot(xValue, wValue0), + dot(xValue, wValue1), + dot(xValue, wValue2), + dot(xValue, wValue3)); + dotProd[1] = dotProd[1] + tmpval; + } + } + } + } + + for (var i: u32 = 0; i < ${y}; i = i + 1) { + let value = dotProd[i] + ${n?"bias[c+i]":`vec4<${a}>(0.0)`}; + ${v.set("batch","r","c + i","d1","value")}; + } + }`,C=` + let outputIndices = ${v.offsetToIndices("global_idx")}; + let batch = ${v.indicesGet("outputIndices",0)}; + let d1 = ${v.indicesGet("outputIndices",m)}; + let r = ${v.indicesGet("outputIndices",p)}; + let c = ${v.indicesGet("outputIndices",f)}; + let dyCorner = vec2(i32(r), i32(c)) - uniforms.pads; + let dyRCorner = dyCorner.x; + let dyCCorner = dyCorner.y; + let groupId = d1 / uniforms.output_channels_per_group; + let wOutChannel = d1 - groupId * uniforms.output_channels_per_group; + // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1). + // ? = to be determined. : = across all values in that axis. + var dotProd = ${a}(0.0); + for (var wR: u32 = 0; wR < uniforms.effective_filter_dims.x; wR = wR + 1) { + if (wR % uniforms.dilations.x != 0) { + continue; + } + let dyR = (${a}(dyRCorner) + ${a}(wR)) / ${a}(uniforms.strides[0]); + let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x; + if (dyR < 0.0 || dyR >= ${a}(uniforms.Dy_shape[${p}]) || fract(dyR) > 0.0 || + wRPerm < 0) { + continue; + } + let idyR: u32 = u32(dyR); + + for (var wC: u32 = 0; wC < uniforms.effective_filter_dims.y; wC = wC + 1) { + if (wC % uniforms.dilations.y != 0) { + continue; + } + let dyC = (${a}(dyCCorner) + ${a}(wC)) / ${a}(uniforms.strides.y); + let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y; + if (dyC < 0.0 || dyC >= ${a}(uniforms.Dy_shape[${f}]) || + fract(dyC) > 0.0 || wCPerm < 0) { + continue; + } + let idyC: u32 = u32(dyC); + var inputChannel = groupId * uniforms.input_channels_per_group; + for (var d2: u32 = 0; d2 < uniforms.input_channels_per_group; d2 = d2 + 1) { + let xValue = ${l?T.get("batch","idyR","idyC","inputChannel"):T.get("batch","inputChannel","idyR","idyC")}; + let wValue = ${x.get("inputChannel","wOutChannel","u32(wRPerm)","u32(wCPerm)")}; + dotProd = dotProd + xValue * wValue; + inputChannel = inputChannel + 1; + } + } + } + let value = dotProd + ${n?"bias[d1]":`${a}(0.0)`}; + ${v.setByOffset("global_idx","value")}; + `;return` + ${e.registerUniforms(u).declareVariables(..._,v)} + ${$} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}; + ${o?k:C}}`},rp=(e,t,r)=>{let n=e.length>2,i=t.outputShape,o=G.size(i),a=[Math.ceil(o/64),1,1];rt("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${a}`);let u=t.format==="NHWC",l=["rank","rank"],p=[t.strides[0],t.strides[1]],f=[t.kernelShape[u?1:2],t.kernelShape[u?2:3]],m=[t.dilations[0],t.dilations[1]],y=[f[0]+(t.dilations[0]<=1?0:(t.kernelShape[u?1:2]-1)*(t.dilations[0]-1)),f[1]+(t.dilations[1]<=1?0:(t.kernelShape[u?2:3]-1)*(t.dilations[1]-1))],$=[y[0]-1-Math.floor((t.pads[0]+t.pads[2])/2),y[1]-1-Math.floor(t.pads[1]+t.pads[3])/2],c=!1,x=t.group,T=e[1].dims,_=T[0]/x,v=T[1],k=[{type:12,data:o},{type:12,data:p},{type:12,data:f},{type:12,data:m},{type:12,data:y},{type:6,data:$},{type:12,data:_},{type:12,data:v},...he(e[0].dims,e[1].dims)];n&&(k.push(...he(e[2].dims)),l.push("rank")),k.push(...he(i));let C=a[1]===1&&a[2]===1,I=M=>{let P=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:p.length},{name:"filter_dims",type:"u32",length:f.length},{name:"dilations",type:"u32",length:f.length},{name:"effective_filter_dims",type:"u32",length:y.length},{name:"pads",type:"i32",length:$.length},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],B=wt(e[0].dataType);return`${km(M,e,i,n,C,c,B,P,u)}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${t.cacheKey};`,inputDependencies:l},getRunData:()=>({dispatchGroup:{x:a[0],y:a[1],z:a[2]},outputs:[{dims:r?r(i):i,dataType:e[0].dataType}],programUniforms:k}),getShaderSource:I}}}),Em,Cm,Tm,Rl,zw,Im,Am,zm,Om,Ow,cx=Z(()=>{dx(),px(),ui(),ko(),Em=(e,t,r,n,i,o)=>(e-1)*t+r+(n-1)*i+1-o,Cm=(e,t,r,n,i)=>{let o=Math.floor(e/2);t==="SAME_UPPER"?(r[n]=o,r[i]=e-o):t==="SAME_LOWER"&&(r[n]=e-o,r[i]=o)},Tm=(e,t,r,n,i,o,a,u,l,p)=>{let f=e.length-2,m=p.length===0;if(l.length===0)for(let c=0;c{let r=e.kernelShape.slice();if(e.kernelShape.length===0||e.kernelShape.reduce((m,y)=>m*y,1)===0){r.length=0;for(let m=2;mm+y,0)===0){let m=t[0].dims.length-2;l=new Array(m).fill(1)}let p=e.strides.slice();if(p.reduce((m,y)=>m+y,0)===0){let m=t[0].dims.length-2;p=new Array(m).fill(1)}Tm(u,r,l,e.autoPad,e.group,i,p,n,a,o);let f=Object.assign({},e);return Object.assign(f,{kernelShape:r,pads:i,outputPadding:a,outputShape:o,dilations:l,strides:p}),f},zw=e=>{let t=mc(e),r=e.format,n=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof e.autoPad>"u"?0:e.autoPad],i=e.dilations,o=e.group,a=e.kernelShape,u=e.pads,l=e.strides,p=e.wIsConst(),f=e.outputPadding,m=e.outputShape;return{autoPad:n,format:r,dilations:i,group:o,kernelShape:a,outputPadding:f,outputShape:m,pads:u,strides:l,wIsConst:p,...t,cacheKey:`${e.format};${t.activation};`}},Im=(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],n=e[1].dims[0];if(r!==n)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 o=e[0].dims.length-2;if(t.dilations.reduce((a,u)=>a+u,0)>0&&t.dilations.length!==o)throw new Error(`dilations should be ${o}D`);if(t.strides.reduce((a,u)=>a+u,0)>0&&t.strides.length!==o)throw new Error(`strides should be ${o}D`);if(t.pads.reduce((a,u)=>a+u,0)>0&&t.pads.length!==o*2)throw new Error(`pads should be ${o*2}D`);if(t.outputPadding.length!==o&&t.outputPadding.length!==0)throw new Error(`output_padding should be ${o}D`);if(t.kernelShape.reduce((a,u)=>a+u,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")},Am=[2,3,1,0],zm=(e,t,r)=>{let n=Rl(r,t),i=r.format==="NHWC",o=n.outputShape,a=o[i?3:1],u=t[0].dims[i?3:1];if(n.group!==1||a===1&&u===1){e.compute(rp(t,n));return}let l=o[i?1:2],p=o[i?2:3],f=t[1].dims[2],m=t[1].dims[3],y=i?l*p:a,$=i?a:l*p,c=f*m*u,x=!0,T=e.kernelCustomData.wT??e.compute(Zr(t[1],Am),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=T);let _=[t[0],T],v=t.length===3;v&&(!i&&t[2].dims.length===1?_.push(t[2].reshape([t[2].dims[0],1,1])):_.push(t[2])),e.compute(Aw(_,n,o,y,$,c,v,x),{inputs:_})},Om=(e,t)=>{let r=t.format==="NHWC",n=[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&&n.push(e.inputs[2]);let i=t.kernelShape;(i.length===0||i[0]===0)&&(i=[e.inputs[1].dims[2]]);let o=t.dilations;(o.length===0||o[0]===0)&&(o=[1]);let a=t.strides;(a.length===0||a[0]===0)&&(a=[1]);let u=t.pads;u.length===0&&(u=[0,0]),u=[0,u[0],0,u[1]],a=[1].concat(a),o=[1].concat(o),i=[1].concat(i);let l=Rl({...t,pads:u,strides:a,dilations:o,kernelShape:i},n);e.compute(rp(n,l,p=>r?[p[0],p[2],p[3]]:[p[0],p[1],p[3]]))},Ow=(e,t)=>{Im(e.inputs,t),e.inputs[0].dims.length===3?Om(e,t):zm(e,e.inputs,t)}}),Rm,Rw,Pw,fx=Z(()=>{ve(),Ee(),gt(),Se(),Rm=(e,t,r,n)=>{let i=G.size(t),o=t.length,a=q("input",e,o),u=pe("output",e,o),l=r.dataType===6?r.getInt32Array()[0]:Number(r.getBigInt64Array()[0]),p=G.normalizeAxis(l,o),f=m=>{let y=` i32(${a.indicesGet("inputIndices","uniforms.axis")}) `,$=_e("uniforms.input_shape","uniforms.axis",o),c=n.reverse?y+(n.exclusive?" + 1":""):"0",x=n.reverse?$:y+(n.exclusive?"":" + 1");return` + ${m.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(a,u)} + ${m.mainStart()} + ${m.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var inputIndices = ${u.offsetToIndices("global_idx")}; + var sum = ${u.type.value}(0); + let first : i32 = ${c}; + let last : i32 = ${x}; + for (var i : i32 = first; i < last; i++) { + ${a.indicesSet("inputIndices","uniforms.axis","u32(i)")}; + sum = sum + ${a.getByIndices("inputIndices")}; + } + ${u.setByOffset("global_idx","sum")}; + }`};return{name:"CumSum",shaderCache:{hint:n.cacheKey,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:t,dataType:e}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:[{type:12,data:i},{type:12,data:p},...he(t,t)]}),getShaderSource:f}},Rw=(e,t)=>{let r=e.inputs[0].dims,n=e.inputs[0].dataType,i=e.inputs[1];e.compute(Rm(n,r,i,t),{inputs:[0]})},Pw=e=>{let t=e.exclusive===1,r=e.reverse===1;return qe({exclusive:t,reverse:r})}}),Pm,Mm,Bm,Mw,Bw,hx=Z(()=>{ve(),Ee(),gt(),Se(),Pm=e=>{if(!e||e.length!==1)throw new Error("DepthToSpace requires 1 input.");if(e[0].dims.length!==4)throw new Error("DepthToSpace requires 4D input.")},Mm=(e,t,r,n)=>{let i=[];i.push(`fn perm(i: ${n.type.indices}) -> ${r.type.indices} { + var a: ${r.type.indices};`);for(let o=0;o{let r,n,i,o,a,u,l=t.format==="NHWC",p=t.blocksize,f=t.mode==="DCR";l?([r,n,i,o]=e.dims,a=f?[r,n,i,p,p,o/p**2]:[r,n,i,o/p**2,p,p],u=f?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([r,n,i,o]=[e.dims[0],e.dims[2],e.dims[3],e.dims[1]],a=f?[r,p,p,o/p**2,n,i]:[r,o/p**2,p,p,n,i],u=f?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let m=e.reshape(a),y=m.dims.length,$=e.dataType,c=q("a",$,y),x=pe("output",$,y),T=_=>` + ${_.registerUniform("output_size","u32").declareVariables(c,x)} + + ${Mm(u,y,c,x)} + + ${_.mainStart()} + ${_.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${x.offsetToIndices("global_idx")}; + let aIndices = perm(indices); + + ${x.setByOffset("global_idx",c.getByIndices("aIndices"))} + }`;return{name:"DepthToSpace",shaderCache:{hint:`${e.dims};${t.blocksize};${t.mode}`,inputDependencies:["rank"]},getRunData:_=>{let v=l?[r,n*p,i*p,o/p**2]:[r,o/p**2,n*p,i*p],k=G.size(v),C=m.dims,I=G.sortBasedOnPerm(C,u);return{outputs:[{dims:v,dataType:_[0].dataType}],dispatchGroup:{x:Math.ceil(k/64)},programUniforms:[{type:12,data:k},...he(C,I)]}},getShaderSource:T}},Mw=(e,t)=>{Pm(e.inputs),e.compute(Bm(e.inputs[0],t))},Bw=e=>qe({blocksize:e.blocksize,mode:e.mode,format:e.format})}),vs,Oa,Pl,Dm,Nm,Wm,Um,Ml,Lm,Dw,Nw,mx=Z(()=>{ve(),Ee(),gt(),Se(),vs="[a-zA-Z]|\\.\\.\\.",Oa="("+vs+")+",Pl="^"+Oa+"$",Dm="("+Oa+",)*"+Oa,Nm="^"+Dm+"$",Wm=class{constructor(e=-1){this.symbolToIndices=new Map,this.inputIndex=e}addSymbol(e,t){let r=this.symbolToIndices.get(e);r===void 0?r=[t]:r.push(t),this.symbolToIndices.set(e,r)}},Um=class{constructor(e,t){var i;this.equation=t,this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=new Array,this.outputDims=[];let[r,n]=t.includes("->")?t.split("->",2):[t,""];if(!r.match(RegExp(Nm)))throw new Error("Invalid LHS term");if(r.split(",").forEach((o,a)=>{let u=e[a].dims.slice();if(!o.match(RegExp(Pl)))throw new Error("Invalid LHS term");let l=this.processTerm(o,!0,u,a);this.lhs.push(l)}),n==="")n+=[...this.symbolToInfo.entries()].filter(([o,a])=>a.count===1||o==="...").map(([o])=>o).join("");else if(!n.match(RegExp(Oa)))throw new Error("Invalid RHS");(i=n.match(RegExp(vs,"g")))==null||i.forEach(o=>{if(o==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let a=this.symbolToInfo.get(o);if(a===void 0)throw new Error("Invalid RHS symbol");this.outputDims.push(a.dimValue)}}),this.rhs=this.processTerm(n,!1,this.outputDims)}addSymbol(e,t,r){let n=this.symbolToInfo.get(e);if(n!==void 0){if(n.dimValue!==t&&n.count!==1)throw new Error("Dimension mismatch");n.count++,n.inputIndices.push(r)}else n={count:1,dimValue:t,inputIndices:[r]};this.symbolToInfo.set(e,n)}processTerm(e,t,r,n=-1){let i=r.length,o=!1,a=[],u=0;if(!e.match(RegExp(Pl))&&!t&&e!=="")throw new Error("Invalid LHS term");let l=e.match(RegExp(vs,"g")),p=new Wm(n);return l==null||l.forEach((f,m)=>{if(f==="..."){if(o)throw new Error("Only one ellipsis is allowed per input term");o=!0;let y=i-l.length+1;if(y<0)throw new Error("Ellipsis out of bounds");if(a=r.slice(u,u+y),this.hasEllipsis){if(this.ellipsisDims.length!==a.length||this.ellipsisDims.toString()!==a.toString())throw new Error("Ellipsis dimensions mismatch")}else if(t)this.hasEllipsis=!0,this.ellipsisDims=a;else throw new Error("Ellipsis must be specified in the LHS");for(let $=0;$e+"_max",Lm=(e,t,r,n)=>{let i=e.map(p=>p.length).map((p,f)=>q(`input${f}`,t,p)),o=G.size(n),a=pe("output",t,n.length),u=[...r.symbolToInfo.keys()].filter(p=>!r.rhs.symbolToIndices.has(p)),l=p=>{let f=[],m="var prod = 1.0;",y="var sum = 0.0;",$="sum += prod;",c=[],x=[],T=[],_=[],v=r.symbolToInfo.size===r.rhs.symbolToIndices.size;r.symbolToInfo.forEach((C,I)=>{var M;if(r.rhs.symbolToIndices.has(I)){let P=(M=r.rhs.symbolToIndices.get(I))==null?void 0:M[0];P!==void 0&&r.lhs.forEach((B,H)=>{if(C.inputIndices.includes(H)){let F=B.symbolToIndices.get(I);if(F===void 0)throw new Error("Invalid symbol error");F.forEach(me=>{f.push(`${i[H].indicesSet(`input${H}Indices`,me,a.indicesGet("outputIndices",P))}`)})}})}else r.lhs.forEach((P,B)=>{if(C.inputIndices.includes(B)){let H=P.symbolToIndices.get(I);if(H===void 0)throw new Error("Invalid symbol error");H.forEach(F=>{c.push(`${i[B].indicesSet(`input${B}Indices`,F,`${I}`)}`)}),_.push(`prod *= ${i[B].getByIndices(`input${B}Indices`)};`)}}),x.push(`for(var ${I}: u32 = 0; ${I} < uniforms.${Ml(I)}; ${I}++) {`),T.push("}")});let k=v?[...f,`let sum = ${i.map((C,I)=>C.getByIndices(`input${I}Indices`)).join(" * ")};`]:[...f,y,...x,...c,m,..._,$,...T];return` + ${p.registerUniforms(u.map(C=>({name:`${Ml(C)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...i,a)} + + ${p.mainStart()} + ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var outputIndices = ${a.offsetToIndices("global_idx")}; + ${i.map((C,I)=>`var input${I}Indices: ${i[I].type.indices};`).join(` +`)} + ${k.join(` +`)}; + ${a.setByOffset("global_idx","sum")}; + }`};return{name:"Einsum",shaderCache:{hint:r.equation,inputDependencies:e.map(()=>"rank")},getRunData:()=>{let p=u.filter(m=>r.symbolToInfo.has(m)).map(m=>{var y;return{type:12,data:((y=r.symbolToInfo.get(m))==null?void 0:y.dimValue)||0}});p.push({type:12,data:o});let f=e.map((m,y)=>[...he(m)]).reduce((m,y)=>m.concat(y),p);return f.push(...he(n)),{outputs:[{dims:n,dataType:t}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:f}},getShaderSource:l}},Dw=(e,t)=>{let r=new Um(e.inputs,t.equation),n=r.outputDims,i=e.inputs.map((o,a)=>o.dims);e.compute(Lm(i,e.inputs[0].dataType,r,n))},Nw=e=>{let t=e.equation.replace(/\s+/g,"");return qe({equation:t})}}),Vm,Bl,Hm,Fm,Ww,gx=Z(()=>{ve(),Ee(),Se(),Vm=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),n=r.length{let r=e.length-t.length,n=[];for(let i=0;ie.length>t.length?Bl(e,t):Bl(t,e),Fm=e=>{let t=e[0].dims,r=Array.from(e[1].getBigInt64Array(),Number),n=Hm(t,r),i=e[0].dataType,o=i===9?4:1,a=Math.ceil(G.size(n)/o),u=p=>{let f=q("input",i,t.length,o),m=pe("output",i,n.length,o),y;if(i===9){let $=(c,x,T="")=>` + let outputIndices${x} = ${m.offsetToIndices(`outputOffset + ${x}u`)}; + let offset${x} = ${f.broadcastedIndicesToOffset(`outputIndices${x}`,m)}; + let index${x} = offset${x} / 4u; + let component${x} = offset${x} % 4u; + ${c}[${x}] = ${T}(${f.getByOffset(`index${x}`)}[component${x}]); + `;y=` + let outputOffset = global_idx * ${o}; + var data = vec4(0); + ${$("data",0,"u32")} + ${$("data",1,"u32")} + ${$("data",2,"u32")} + ${$("data",3,"u32")} + ${m.setByOffset("global_idx","data")} + }`}else y=` + let outputIndices = ${m.offsetToIndices("global_idx")}; + let inputOffset = ${f.broadcastedIndicesToOffset("outputIndices",m)}; + ${m.setByOffset("global_idx",f.getByOffset("inputOffset"))} + }`;return` + ${p.registerUniform("vec_size","u32").declareVariables(f,m)} + ${p.mainStart()} + ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${y}`},l=[{type:12,data:a},...he(t,n)];return{name:"Expand",shaderCache:{hint:`${n.length}`,inputDependencies:["rank"]},getShaderSource:u,getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:l})}},Ww=e=>{Vm(e.inputs),e.compute(Fm(e.inputs),{inputs:[0]})}}),jm,Uw,yx=Z(()=>{ve(),Ee(),Se(),hc(),jm=e=>{let t=e[0].dataType,r=G.size(e[0].dims),n=G.size(e[1].dims),i=n%4===0,o=a=>{let u=q("x",t,[1],4),l=q("bias",t,[1],4),p=pe("y",t,[1],4),f=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],m=$=>` + let bias${$}_offset: u32 = (global_idx * 4 + ${$}) % uniforms.bias_size; + let bias${$} = ${l.getByOffset(`bias${$}_offset / 4`)}[bias${$}_offset % 4];`,y=i?` + let bias = ${l.getByOffset("global_idx % (uniforms.bias_size / 4)")};`:`${m(0)}${m(1)}${m(2)}${m(3)} + let bias = ${u.type.value}(bias0, bias1, bias2, bias3);`;return`${a.registerUniforms(f).declareVariables(u,l,p)} + + ${Qd(Ut(t))} + + ${a.mainStart(ea)} + ${a.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")} + + let x = ${u.getByOffset("global_idx")}; + ${y} + let x_in = x + bias; + ${p.setByOffset("global_idx",Xd("x_in"))} + }`};return{name:"FastGeluWithBias",shaderCache:{hint:`${i}`,inputDependencies:["type","type"]},getShaderSource:o,getRunData:a=>({outputs:[{dims:a[0].dims,dataType:a[0].dataType}],programUniforms:[{type:12,data:Math.ceil(r/4)},{type:12,data:n}],dispatchGroup:{x:Math.ceil(r/ea/4)}})}},Uw=e=>{e.inputs.length<2||G.size(e.inputs[1].dims)===0?dw(e):e.compute(jm(e.inputs))}}),Gm,qm,Lw,Vw,vx=Z(()=>{ve(),Ee(),gt(),Se(),Gm=e=>{if(!e||e.length!==2)throw new Error("Gather requires 2 inputs.")},qm=(e,t)=>{let r=e[0].dims,n=e[1].dims,i=r.length,o=G.normalizeAxis(t.axis,i),a=r.slice(0);a.splice(o,1,...n);let u=r[o],l=e[0].dataType===9?4:1,p=Math.ceil(G.size(a)/l),f=[{type:12,data:p},{type:6,data:u},{type:12,data:o},...he(e[0].dims,e[1].dims,a)],m=y=>{let $=q("data",e[0].dataType,e[0].dims.length,l),c=q("inputIndices",e[1].dataType,e[1].dims.length),x=pe("output",e[0].dataType,a.length,l),T=v=>{let k=n.length,C=`var indicesIndices${v} = ${c.type.indices}(0);`;for(let I=0;I1?`indicesIndices${v}[${I}]`:`indicesIndices${v}`} = ${a.length>1?`outputIndices${v}[uniforms.axis + ${I}]`:`outputIndices${v}`};`;C+=` + var idx${v} = ${c.getByIndices(`indicesIndices${v}`)}; + if (idx${v} < 0) { + idx${v} = idx${v} + uniforms.axisDimLimit; + } + var dataIndices${v} : ${$.type.indices}; + `;for(let I=0,M=0;I1?`dataIndices${v}[${I}]`:`dataIndices${v}`} = u32(idx${v});`,M+=k):(C+=`${i>1?`dataIndices${v}[${I}]`:`dataIndices${v}`} = ${a.length>1?`outputIndices${v}[${M}]`:`outputIndices${v}`};`,M++);return C},_;if(e[0].dataType===9){let v=(k,C,I="")=>` + let outputIndices${C} = ${x.offsetToIndices(`outputOffset + ${C}u`)}; + ${T(C)}; + let offset${C} = ${$.indicesToOffset(`dataIndices${C}`)}; + let index${C} = offset${C} / 4u; + let component${C} = offset${C} % 4u; + ${k}[${C}] = ${I}(${$.getByOffset(`index${C}`)}[component${C}]); + `;_=` + let outputOffset = global_idx * ${l}; + var value = vec4(0); + ${v("value",0,"u32")} + ${v("value",1,"u32")} + ${v("value",2,"u32")} + ${v("value",3,"u32")} + ${x.setByOffset("global_idx","value")} + `}else _=` + let outputIndices = ${x.offsetToIndices("global_idx")}; + ${T("")}; + let value = ${$.getByIndices("dataIndices")}; + ${x.setByOffset("global_idx","value")}; + `;return` + ${y.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables($,c,x)} + ${y.mainStart()} + ${y.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + ${_} + }`};return{name:"Gather",shaderCache:{hint:t.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:a,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:f}),getShaderSource:m}},Lw=e=>qe({axis:e.axis}),Vw=(e,t)=>{let r=e.inputs;Gm(r),e.compute(qm(e.inputs,t))}}),Km,Ym,Hw,Fw,wx=Z(()=>{ve(),Ee(),gt(),Se(),Km=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.`)},Ym=(e,t)=>{let r=e[0].dims,n=e[0].dataType,i=r.length,o=e[1].dims,a=e[1].dataType,u=G.normalizeAxis(t.axis,i),l=r[u],p=o.slice(0),f=G.size(p),m=q("input",n,i),y=q("indicesInput",a,o.length),$=pe("output",n,p.length),c=[{type:12,data:f},{type:6,data:l},{type:12,data:u}];return c.push(...he(r,o,p)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:p,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(f/64)},programUniforms:c}),getShaderSource:x=>` + ${x.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(m,y,$)} + ${x.mainStart()} + ${x.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + + let outputIndices = ${$.offsetToIndices("global_idx")}; + + var idx = ${y.getByOffset("global_idx")}; + if (idx < 0) { + idx = idx + uniforms.axisDimLimit; + } + var inputIndices = ${m.type.indices}(outputIndices); + ${m.indicesSet("inputIndices","uniforms.axis","u32(idx)")}; + let value = ${m.getByIndices("inputIndices")}; + + ${$.setByOffset("global_idx","value")}; + }`}},Hw=e=>qe({axis:e.axis}),Fw=(e,t)=>{let r=e.inputs;Km(r),e.compute(Ym(e.inputs,t))}}),Qm,Xm,jw,Gw,$x=Z(()=>{ve(),Ee(),Se(),Qm=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")},Xm=(e,t)=>{let r=e[0].dims.slice(),n=e[1].dims.slice(),[i,o,a]=e1.getShapeOfGemmResult(r,t.transA,n,t.transB,e.length===3?e[2].dims:void 0),u=[i,o];if(!u)throw new Error("Can't use gemm on the given tensors");let l=G.size(u),p=[{type:12,data:l},{type:12,data:i},{type:12,data:o},{type:12,data:a},{type:1,data:t.alpha},{type:1,data:t.beta}],f=["type","type"];e.length===3&&(p.push(...he(e[2].dims)),f.push("rank")),p.push(...he(u));let m=y=>{let $="";t.transA&&t.transB?$="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":t.transA&&!t.transB?$="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!t.transA&&t.transB?$="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!t.transA&&!t.transB&&($="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let c=t.alpha===1?"":"value *= uniforms.alpha;",x=q("a",e[0].dataType,e[0].dims),T=q("b",e[1].dataType,e[1].dims),_=x.type.value,v=null,k=[x,T];e.length===3&&(v=q("c",e[2].dataType,e[2].dims.length),k.push(v));let C=pe("output",e[0].dataType,u.length);k.push(C);let I=[{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` + ${y.registerUniforms(I).declareVariables(...k)} + + ${y.mainStart()} + ${y.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let m = global_idx / uniforms.N; + let n = global_idx % uniforms.N; + + var value = ${_}(0); + for (var k: u32 = 0u; k < uniforms.K; k++) { + ${$} + } + + ${c} + ${v!=null?`let cOffset = ${v.broadcastedIndicesToOffset("vec2(m, n)",C)}; value += ${_}(uniforms.beta) * ${v.getByOffset("cOffset")};`:""} + output[global_idx] = value; + }`};return{name:"Gemm",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:f},getRunData:()=>({outputs:[{dims:u,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:p}),getShaderSource:m}},jw=e=>{let t=e.transA,r=e.transB,n=e.alpha,i=e.beta;return{transA:t,transB:r,alpha:n,beta:i,cacheKey:`${e.transA};${e.transB};${e.alpha===1}`}},Gw=(e,t)=>{Qm(e.inputs),e.compute(Xm(e.inputs,t))}}),Zm,Jm,eg,qw,_x=Z(()=>{ve(),Ee(),Se(),Zm=(e,t)=>{let r=e[0].dims,n=r,i=2,o=G.sizeToDimension(r,i),a=G.sizeFromDimension(r,i),u=ot(a),l=a/u,p=[r[0],r[1],l],f=["rank","type","type"],m=[{type:12,data:a},{type:12,data:l}];m.push(...he(p,p));let y=$=>{let c=q("x",e[0].dataType,p.length,u),x=q("scale",e[1].dataType,e[1].dims),T=q("bias",e[2].dataType,e[2].dims),_=pe("output",e[0].dataType,p.length,u),v=[c,x,T,_],k=c.type.value,C=u===1?"f32":`vec${u}`,I=64,M=[{name:"normSize",type:"u32"},{name:"normPackedSize",type:"u32"}];return` + var meanShared : f32; + var squaredNormShared : f32; + var workgroupShared : array<${C}, ${I}>; + const workgroupSize = ${I}u; + ${$.registerUniforms(M).declareVariables(...v)} + ${$.mainStart(I)} + 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 = ${C}(0); + for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) { + initial = initial + ${C}(${c.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 = ${Tn("workgroupShared[0]",u)} / f32(uniforms.normSize); + } + workgroupBarrier(); + + // reinitialize workgroup memory. + initial = ${C}(0); + for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) { + let deviation = ${C}(${c.get("batch","channel","h")}) - ${C}(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 = ${Tn("workgroupShared[0]",u)}; + } + workgroupBarrier(); + + let invStdDev = inverseSqrt(squaredNormShared / f32(uniforms.normSize) + f32(${t.epsilon})); + let channelScale = invStdDev * f32(${x.getByOffset("channel")}); + let channelShift = f32(${T.getByOffset("channel")}) - meanShared * channelScale; + for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) { + let value = ${c.get("batch","channel","h")} * ${k}(${C}(channelScale)) + ${k}(${C}(channelShift)); + ${_.set("batch","channel","h","value")}; + } + }`};return{name:"InstanceNormalization",shaderCache:{hint:`${t.epsilon};${u}`,inputDependencies:f},getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:o},programUniforms:m}),getShaderSource:y}},Jm=(e,t,r,n,i,o,a,u)=>{let l=ot(a),p=64,f=l===1?"vec2f":`mat2x${l}f`,m=l===1?"f32":`vec${l}f`,y=(M,P)=>`${f}(${M}, ${P})`,$=i*a/l,c=Math.ceil(o/p),x=["type"],T=[{type:12,data:c},{type:12,data:o},{type:12,data:Math.floor(a/l)},{type:12,data:Math.floor(o*a/l)}],_=M=>{let P=q("input",t.dataType,t.dims,l);return` + ${M.declareVariables(P)} + @group(0) @binding(1) var output : array<${f}>; + struct Uniforms {wg_size:u32, H:u32, C:u32, image_size:u32}; + @group(0) @binding(2) var uniforms: Uniforms; + + ${M.mainStart(p)} + let currentImageNumber = global_idx / ${p} / uniforms.C; + let currentChannelNumber = (global_idx / ${p}) % uniforms.C; + let wgOffset = local_id.x * 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 = ${Qr("f32",l)}; + var squaredSum = ${Qr("f32",l)}; + for (var i: u32 = wgOffset; i < wgMax; i++) { + let value = ${m}(input[offset + i * uniforms.C]); + sum += value; + squaredSum += value * value; + } + output[global_idx] = ${y("sum","squaredSum")}; + }`},v=e.compute({name:"InstanceNormComputeMean",shaderCache:{hint:`${l}`,inputDependencies:x},getRunData:()=>({outputs:[{dims:[i,a,p,2],dataType:1}],dispatchGroup:{x:i*a/l},programUniforms:T}),getShaderSource:_},{inputs:[t],outputs:[-1]})[0],k=[{type:12,data:$},{type:12,data:o},{type:12,data:Math.floor(a/l)},{type:12,data:Math.floor(p*a/l)}],C=["type","type","type"],I=M=>{let P=q("scale",r.dataType,r.dims,l),B=q("bias",n.dataType,n.dims,l);return` + @group(0) @binding(0) var input : array<${f}>; + @group(0) @binding(1) var scale : array<${P.type.storage}>; + @group(0) @binding(2) var bias : array<${B.type.storage}>; + @group(0) @binding(3) var output : array<${f}>; + struct Uniforms {units_of_work : u32, H: u32, C : u32, image_size : u32}; + @group(0) @binding(4) var uniforms: Uniforms; + + ${M.mainStart()} + ${M.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 = ${Qr("f32",l)}; + var squaredSum = ${Qr("f32",l)}; + for (var i: u32 = 0; i < min(${p}, uniforms.H); i++) { + let value = input[offset + i + currentChannelNumber * ${p}]; + sum += value[0]; + squaredSum += value[1]; + } + sum = sum / f32(uniforms.H); + squaredSum = squaredSum / f32(uniforms.H); + let invStdDev = inverseSqrt(squaredSum - sum * sum + f32(${u})); + let channelScale = invStdDev * ${m}(scale[currentChannelNumber]); + let channelShift = ${m}(bias[currentChannelNumber]) - sum * channelScale; + + output[global_idx] = ${y("channelScale","channelShift")}; + }`};return e.compute({name:"InstanceNormComputeChannelScaleShift",shaderCache:{hint:`${l};${u}`,inputDependencies:C},getRunData:()=>({outputs:[{dims:[i,a,2],dataType:1}],dispatchGroup:{x:Math.ceil($/64)},programUniforms:k}),getShaderSource:I},{inputs:[v,r,n],outputs:[-1]})[0]},eg=(e,t,r)=>{let n=t[0].dims,i=n,o=n[0],a=n[n.length-1],u=G.sizeFromDimension(n,1)/a,l=ot(a),p=G.size(i)/l,f=[{type:12,data:u},{type:12,data:Math.floor(a/l)}],m=["type","type"],y=Jm(e,t[0],t[1],t[2],o,u,a,r.epsilon),$=c=>{let x=wt(t[0].dataType),T=l===1?"vec2f":`mat2x${l}f`,_=l===1?x:`vec${l}<${x}>`,v=q("input",t[0].dataType,t[0].dims,l),k=pe("output",t[0].dataType,i,l);return` + @group(0) @binding(0) var input : array<${v.type.storage}>; + @group(0) @binding(1) var scaleInput : array<${T}>; + @group(0) @binding(2) var output : array<${k.type.storage}>; + struct Uniforms {H: u32, C : u32}; + @group(0) @binding(3) var uniforms: Uniforms; + + ${c.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], ${_}(scale[0]), ${_}(scale[1])); + }`};e.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${l}`,inputDependencies:m},getRunData:()=>({outputs:[{dims:i,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:f}),getShaderSource:$},{inputs:[t[0],y]})},qw=(e,t)=>{t.format==="NHWC"?eg(e,e.inputs,t):e.compute(Zm(e.inputs,t))}}),tg,rg,Kw,bx=Z(()=>{ve(),Ee(),Se(),tg=e=>{if(!e||e.length<2)throw new Error("layerNorm requires at least 2 inputs.")},rg=(e,t,r)=>{let n=t.simplified,i=e[0].dims,o=e[1],a=!n&&e[2],u=i,l=G.normalizeAxis(t.axis,i.length),p=G.sizeToDimension(i,l),f=G.sizeFromDimension(i,l),m=G.size(o.dims),y=a?G.size(a.dims):0;if(m!==f||a&&y!==f)throw new Error(`Size of X.shape()[axis:] == ${f}. + Size of scale and bias (if provided) must match this. + Got scale size of ${m} and bias size of ${y}`);let $=[];for(let I=0;I1,v=r>2,k=I=>{let M=wt(e[0].dataType),P=[q("x",e[0].dataType,e[0].dims,c),q("scale",o.dataType,o.dims,c)];a&&P.push(q("bias",a.dataType,a.dims,c)),P.push(pe("output",e[0].dataType,u,c)),_&&P.push(pe("mean_data_output",1,$)),v&&P.push(pe("inv_std_output",1,$));let B=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return` + ${I.registerUniforms(B).declareVariables(...P)} + ${I.mainStart()} + ${I.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")} + let offset = global_idx * uniforms.norm_size_vectorized; + var mean_vector = ${Qr("f32",c)}; + var mean_square_vector = ${Qr("f32",c)}; + + for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) { + let value = ${Wi(M,c,"x[h + offset]")}; + mean_vector += value; + mean_square_vector += value * value; + } + let mean = ${Tn("mean_vector",c)} / uniforms.norm_size; + let inv_std_dev = inverseSqrt(${Tn("mean_square_vector",c)} / uniforms.norm_size ${n?"":"- mean * mean"} + uniforms.epsilon); + + for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) { + let f32input = ${Wi(M,c,"x[j + offset]")}; + let f32scale = ${Wi(M,c,"scale[j]")}; + output[j + offset] = ${P[0].type.value}((f32input ${n?"":"- mean"}) * inv_std_dev * f32scale + ${a?`+ ${Wi(M,c,"bias[j]")}`:""} + ); + } + + ${_?"mean_data_output[global_idx] = mean":""}; + ${v?"inv_std_output[global_idx] = inv_std_dev":""}; + }`},C=[{dims:u,dataType:e[0].dataType}];return _&&C.push({dims:$,dataType:1}),v&&C.push({dims:$,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${c};${r};${n}`,inputDependencies:x},getRunData:()=>({outputs:C,dispatchGroup:{x:Math.ceil(p/64)},programUniforms:T}),getShaderSource:k}},Kw=(e,t)=>{tg(e.inputs),e.compute(rg(e.inputs,t,e.outputCount))}}),ng,ig,Yw,Qw,xx=Z(()=>{ve(),Ee(),gt(),Se(),ng=(e,t)=>{if(e.length<3||e.length>4)throw new Error("MatMulNBits requires 3 or 4 inputs");let r=e[0],n=r.dims.length;if(r.dims[n-1]!==t.k)throw new Error("The last dim of input shape does not match the k value");let i=Math.floor((t.k+t.blockSize-1)/t.blockSize),o=t.blockSize/8*t.bits,a=e[1];if(!G.areEqual(a.dims,[t.n,i,o]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let u=e[2].dims;if(G.size(u)!==t.n*i)throw new Error("scales input size error.");if(e.length===4){let l=e[3].dims,p=t.bits>4?t.n*i:t.n*Math.floor((i+1)/2);if(G.size(l)!==p)throw new Error("zeroPoints input size error.")}},ig=(e,t,r,n)=>{let i=e[0].dims,o=i.length,a=Math.floor((t.k+t.blockSize-1)/t.blockSize),u=i[o-2],l=t.k,p=t.n,f=i.slice(0,o-2),m=G.size(f),y=t.blockSize/8*t.bits/4,$=e[0].dataType,c=ot(u),x=ot(t.k),T=ot(y),_=yo($),v=u*a*_,k=Math.floor(n/v),C=a<=r[0]&&k>0,I=!C||k>=4?ot(p):k>=2&&ot(p)>=2?2:1,M=f.concat([u,p]),P=G.size(M)/I/c,B=C?[]:[{type:12,data:P},{type:12,data:t.blockSize}],H=[m,u,l/x],F=G.convertShape(e[1].dims).slice();F.splice(-1,1,y/T),B.push(...he(H)),B.push(...he(F)),B.push(...he(e[2].dims)),e.length===4&&B.push(...he(G.convertShape(e[3].dims)));let me=[m,u,p/I];B.push(...he(me));let ce=se=>{let xe=H.length,ze=q("a",e[0].dataType,xe,x),V=q("b",12,F.length,T),le=q("scales",e[2].dataType,e[2].dims.length),U=[ze,V,le],J=e.length===4?q("zero_points",12,e[3].dims.length):void 0;J&&U.push(J);let Q=me.length,R=pe("output",e[0].dataType,Q,I),ee=[{name:"output_size",type:"u32"},{name:"block_size",type:"u32"}],oe=wt(e[0].dataType),we=(()=>{switch(x){case 1:return`array<${oe}, 8>`;case 2:return`mat4x2<${oe}>`;case 4:return`mat2x4<${oe}>`;default:throw new Error(`${x}-component is not supported.`)}})(),Ce=` + for (var word: u32 = 0; word < ${y}; word += ${T}) { + ${V.indicesSet("b_indices","2","word")}; + let b_data = ${V.getByIndices("b_indices")}; + for (var i: u32 = 0; i < ${T}; i++) { + let b_value: u32 = ${T===1?"b_data":"b_data[word + i]"}; + let b_mask: u32 = 0x0F0F0F0Fu; + let b_value_lower: vec4 = unpack4xU8(b_value & b_mask); + let b_value_upper: vec4 = unpack4xU8((b_value >> 4) & b_mask); + let b_quantized_values = ${we}(${Array.from({length:4},(st,ut)=>`${oe}(b_value_lower[${ut}]), ${oe}(b_value_upper[${ut}])`).join(", ")}); + let b_dequantized_values = ${x===1?`${we}(${Array.from({length:8},(st,ut)=>`(b_quantized_values[${ut}] - zero_point) * scale`).join(", ")});`:`(b_quantized_values - ${we}(${Array(8).fill("zero_point").join(",")})) * scale;`}; + // Number of B elements per 32-bit word is 32/bits = 32/4 = 8 + for (var m: u32 = 0; m < ${C?u:c}u; m++) { + ${ze.indicesSet("a_indices",xe-2,C?"m":`row * ${c} + m`)}; + ${ze.indicesSet("a_indices",xe-1,"word_offset")}; + var input_offset = ${ze.indicesToOffset("a_indices")}; + var a_data: ${we}; + for (var j: u32 = 0; j < ${8/x}; j++) { + a_data[j] = ${ze.getByOffset("input_offset")}; + input_offset++; + } + ${C?"workgroup_shared[workgroup_shared_offset + m]":"output_values[m]"}${I>1?"[c]":""} += ${Array.from({length:8/x},(st,ut)=>`${x===1?`a_data[${ut}] * b_dequantized_values[${ut}]`:`dot(a_data[${ut}], b_dequantized_values[${ut}])`}`).join(" + ")}; + } + word_offset += ${8/x}; + } + }`,Le=J?` + zero_point_offset += 4; + if (zero_point_offset == 32) { + zero_point_offset = 0; + zero_point_index++; + zero_point_word = ${J.getByOffset("zero_point_index")}; + }`:"";return C?` + var workgroup_shared: array<${R.type.value}, ${u*a}>; + ${se.declareVariables(...U,R)} + ${se.mainStart([a,1,1])} + var a_indices: ${ze.type.indices}; + var block = local_id.x; + var col = workgroup_id.y; + var batch = workgroup_id.z; + ${ze.indicesSet("a_indices","0","batch")}; + // Two zero points are packed into one byte when uniforms.bits is 4. + for (var c: u32 = 0; c < ${I}; c++) { + let col_times_components_plus_c = col * ${I} + c; + ${J?` + var zero_point_bytes_per_col: u32 = (${a} + 1) / 2; + var zero_point_byte_count: u32 = col_times_components_plus_c * zero_point_bytes_per_col + (block >> 0x1u); + var zero_point_word_index: u32 = zero_point_byte_count >> 0x2u; + var zero_point_byte_offset: u32 = zero_point_byte_count & 0x3u; + var zero_point_nibble_offset: u32 = block & 0x1u; + var zero_point_bits_offset: u32 = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2); + var zero_point_word: u32 = ${J.getByOffset("zero_point_word_index")} >> zero_point_bits_offset;`:""} + var b_indices: ${V.type.indices}; + ${V.indicesSet("b_indices","0","col_times_components_plus_c")}; + // The scale and zero points are computed per block. + var scales_index = col_times_components_plus_c * ${a} + block; + let scale = ${le.getByOffset("scales_index")}; + // The default zero point is 8 for unsigned 4-bit quantization. + let zero_point = ${oe}(${J?"(zero_point_word) & 0xFu":8}); + ${V.indicesSet("b_indices","1","block")}; + var word_offset: u32 = block * ${t.blockSize/x}; + var workgroup_shared_offset: u32 = block * ${u}; + ${Ce} + } + workgroupBarrier(); + if (local_id.x == 0u) { + var output_indices: ${R.type.indices}; + ${R.indicesSet("output_indices","0","batch")}; + ${R.indicesSet("output_indices",Q-1,"col")}; + ${R.indicesSet("output_indices",Q-2,"0")}; + var output_offset = ${R.indicesToOffset("output_indices")}; + for (var m: u32 = 0u; m < ${u}u; m++) { + var output_value: ${R.type.value} = ${R.type.value}(0); + var workgroup_shared_offset: u32 = m; + for (var b: u32 = 0u; b < ${a}u; b++) { + output_value += workgroup_shared[workgroup_shared_offset]; + workgroup_shared_offset += ${u}; + } + ${R.setByOffset("output_offset","output_value")}; + output_offset += ${p/I}; + } + } + }`:` + ${se.registerUniforms(ee).declareVariables(...U,R)} + ${se.mainStart()} + ${se.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + var output_values: array<${R.type.value}, ${c}>; + var output_indices = ${R.offsetToIndices("global_idx")}; + var col = ${R.indicesGet("output_indices",Q-1)}; + var row = ${R.indicesGet("output_indices",Q-2)}; + var a_indices: ${ze.type.indices} = output_indices; + // Two zero points are packed into one byte because uniforms.bits <= 4. + // zero_point_offset is either 0 or 4. It is bit offset within one byte. + // TODO support zero_point_offset for bits > 4 + ${J?` + var zero_point_abs_offset = col * ${I} * ((${a} + 1) / 2); + var zero_point_index: u32 = zero_point_abs_offset / 4; + var zero_point_word: u32 = ${J.getByOffset("zero_point_index")}; + var zero_point_offset: u32 = (zero_point_abs_offset % 4) * 8;`:""} + var scale_index = col * ${a*I}; + var b_indices: ${V.type.indices}; + for (var c: u32 = 0; c < ${I}; c++) { + ${V.indicesSet("b_indices","0",`col * ${I} + c`)}; + var block_offset: u32 = 0; + for (var block: u32 = 0; block < ${a}; block++) { + // The scale and zero points are computed per block. + let scale = ${le.getByOffset("scale_index")}; + // The default zero point is 8 for unsigned 4-bit quantization. + let zero_point = ${oe}(${J?"extractBits(zero_point_word, zero_point_offset, 4)":8}); + ${V.indicesSet("b_indices","1","block")}; + var word_offset: u32 = block_offset; + ${Ce} + scale_index++; + ${Le} + block_offset += uniforms.block_size / ${x}; + } + // Drop the trailing 4 bits if the zero_poit_offset is not a byte boundary to align with the next byte. + ${J?`if (zero_point_offset % 8 > 0) { + ${Le} + }`:""} + } + for (var k: u32 = 0u; k < ${c}u; k++) { + ${R.indicesSet("output_indices",Q-2,`${c} * row + k`)}; + ${R.setByIndices("output_indices","output_values[k]")} + } + }`};return{name:C?"BlockwiseMatMulNBits":"MatMulNBits",shaderCache:{hint:`${t.cacheKey};${u};${$};${e.length}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:M,dataType:$}],name:C?"BlockwiseMatMulNBits":"MatMulNBits",dispatchGroup:C?{x:1,y:Math.ceil(p/I),z:m}:{x:Math.ceil(P/64)},programUniforms:B}),getShaderSource:ce}},Yw=(e,t)=>{ng(e.inputs,t);let r=e.getMaxComputeWorkgroupSizes(),n=e.getMaxComputeWorkgroupStoragesize();e.compute(ig(e.inputs,t,r,n))},Qw=e=>qe(e)}),Tt,ag,Xw,Dl,og,ws,Zw,Sx=Z(()=>{ve(),Ee(),gt(),lc(),A1(),Se(),ko(),Tt=(e,t)=>e.length>t&&e[t].dims.length>0&&G.size(e[t].dims)>0?e[t]:void 0,ag=(e,t)=>{let r=e[0],n=Tt(e,1),i=Tt(e,2),o=Tt(e,3),a=Tt(e,4),u=Tt(e,5),l=Tt(e,6),p=Tt(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 f=!1,m=r.dims[0],y=r.dims[1],$=r.dims.length===3?f?r.dims[2]/3:r.dims[2]:t.numHeads*r.dims[4],c=y,x=0,T=0,_=Math.floor($/t.numHeads);if(l&&p){if(l.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(l.dims[0]!==m||l.dims[1]!==t.numHeads||l.dims[3]!==_)throw new Error('Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)');if(p.dims[0]!==m||p.dims[1]!==t.numHeads||p.dims[3]!==_)throw new Error('Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)');if(l.dims[2]!==p.dims[2])throw new Error('Input "past_key" and "past_value" shall have same dim 2 (past_sequence_length)');if(p.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');x=l.dims[2],T=l.dims[2]}else if(l||p)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let v;if(n){if(r.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(n.dims.length<3||n.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(r.dims[0]!==n.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(n.dims.length===3){if(n.dims[2]!==r.dims[2])throw new Error('Input "query" and "key" shall have same dim 2 (hidden_size)');v=2,c=n.dims[1]}else if(n.dims.length===5){if(n.dims[2]!==t.numHeads||n.dims[3]!==2||n.dims[4]!==_)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.');v=5,c=n.dims[1]}else{if(n.dims[1]!==t.numHeads||n.dims[3]!==_)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');v=0,c=n.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');v=3}if(o){if(o.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimension');if(i&&r.dims.length===5&&r.dims[3]===2)throw new Error("bias is not allowed for packed kv.")}let k=0;if(a){k=8;let B=a.dims;throw B.length===1?B[0]===m?k=1:B[0]===3*m+2&&(k=3):B.length===2&&B[0]===m&&B[1]===c&&(k=5),k===8?new Error('Input "key_padding_mask" shape shall be (batch_size) or (batch_size, kv_sequence_length)'):new Error("Mask not supported")}let C=!1,I=$;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(r.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(c!==i.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');I=i.dims[2]}else{if(c!==i.dims[2])throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');I=i.dims[1]*i.dims[3],C=!0}}let M=x+c,P=!1;if(a)throw new Error("Key padding mask is not supported");if(u){if(u.dims.length!==4)throw new Error('Input "relative_position_bias" is expected to have 4 dimensions');if(u.dims[0]!==m&&u.dims[0]!==1||u.dims[1]!==t.numHeads||u.dims[2]!==y||u.dims[3]!==M)throw new Error('Input "relative_position_bias" shape (batch_size, 1, sequence_length, kv_sequence_length)')}return{batchSize:m,sequenceLength:y,pastSequenceLength:x,kvSequenceLength:c,totalSequenceLength:M,maxSequenceLength:T,inputHiddenSize:0,hiddenSize:$,vHiddenSize:I,headSize:_,vHeadSize:Math.floor(I/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:k,scale:t.scale,broadcastResPosBias:P,passPastInKv:C,qkvFormat:v}},Xw=e=>qe({...e}),Dl=qe({perm:[0,2,1,3]}),og=(e,t,r,n,i,o,a)=>{let u=[n,i,o],l=G.size(u),p=[{type:12,data:l},{type:12,data:a},{type:12,data:o}],f=m=>{let y=pe("qkv_with_bias",t.dataType,u),$=q("qkv",t.dataType,u),c=q("bias",r.dataType,u),x=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return` + ${m.registerUniforms(x).declareVariables($,c,y)} + ${m.mainStart()} + ${m.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:u,dataType:t.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:p}),getShaderSource:f},{inputs:[t,r],outputs:[-1]})[0]},ws=(e,t,r,n,i,o,a,u)=>{let l=o;if(a){if(n===1)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return l=og(e,o,a,t,n,r*i,u),l=l.reshape([t,n,r,i]),e.compute(Zr(l,Dl.perm),{inputs:[l],outputs:[-1]})[0]}else return o.dims.length===3&&(l=o.reshape([t,n,r,i])),e.compute(Zr(l,Dl.perm),{inputs:[l],outputs:[-1]})[0]},Zw=(e,t)=>{let r=ag(e.inputs,t),n=e.inputs[0],i=Tt(e.inputs,1),o=Tt(e.inputs,2),a=Tt(e.inputs,3),u=Tt(e.inputs,4),l=Tt(e.inputs,5),p=Tt(e.inputs,6),f=Tt(e.inputs,7);if(n.dims.length===5)throw new Error("Packed QKV is not implemented");if((i==null?void 0:i.dims.length)===5)throw new Error("Packed KV is not implemented");let m=i&&o&&i.dims.length===4&&o.dims.length===4,y=ws(e,r.batchSize,r.numHeads,r.sequenceLength,r.headSize,n,a,0);if(m)return mu(e,y,i,o,u,void 0,p,f,l,r,t);if(!i||!o)throw new Error("key and value must be provided");let $=ws(e,r.batchSize,r.numHeads,r.kvSequenceLength,r.headSize,i,a,r.hiddenSize),c=ws(e,r.batchSize,r.numHeads,r.kvSequenceLength,r.vHeadSize,o,a,2*r.hiddenSize);mu(e,y,$,c,u,void 0,p,f,l,r,t)}}),sg,ug,lg,dg,pg,cg,fg,hg,Jw,kx=Z(()=>{ve(),Ee(),Se(),sg=e=>{if(!e||e.length<1)throw new Error("Too few inputs");if(e[0].dataType!==1&&e[0].dataType!==10)throw new Error("Input type must be float or float16.");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].")}},ug=(e,t,r)=>{let n="";for(let i=t-1;i>=0;--i)n+=` + k = i32(${e.indicesGet("indices",i)}) - ${_e("uniforms.pads",i,r)}; + if (k < 0) { + break; + } + if (k >= i32(${_e("uniforms.x_shape",i,t)})) { + break; + } + offset += k * i32(${_e("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; + ${n} + value = x[offset]; + } + `},lg=(e,t,r)=>{let n="";for(let i=t-1;i>=0;--i)n+=` + k = i32(${e.indicesGet("indices",i)}) - ${_e("uniforms.pads",i,r)}; + if (k < 0) { + k = -k; + } + { + let _2n_1 = 2 * (i32(${_e("uniforms.x_shape",i,t)}) - 1); + k = k % _2n_1; + if(k >= i32(${_e("uniforms.x_shape",i,t)})) { + k = _2n_1 - k; + } + } + offset += k * i32(${_e("uniforms.x_strides",i,t)}); + `;return` + var offset = 0; + var k = 0; + ${n} + value = x[offset]; + `},dg=(e,t,r)=>{let n="";for(let i=t-1;i>=0;--i)n+=` + k = i32(${e.indicesGet("indices",i)}) - ${_e("uniforms.pads",i,r)}; + if (k < 0) { + k = 0; + } + if (k >= i32(${_e("uniforms.x_shape",i,t)})) { + k = i32(${_e("uniforms.x_shape",i,t)}) - 1; + } + offset += k * i32(${_e("uniforms.x_strides",i,t)}); + `;return` + var offset = 0; + var k = 0; + ${n} + value = x[offset]; + `},pg=(e,t,r)=>{let n="";for(let i=t-1;i>=0;--i)n+=` + k = i32(${e.indicesGet("indices",i)}) - ${_e("uniforms.pads",i,r)}; + if (k < 0) { + k += i32(${_e("uniforms.x_shape",i,t)}]); + } + if (k >= i32(${_e("uniforms.x_shape",i,t)})) { + k -= i32(${_e("uniforms.x_shape",i,t)}); + } + offset += k * i32(${_e("uniforms.x_strides",i,t)}); + `;return` + var offset = 0; + var k = 0; + ${n} + value = x[offset]; + `},cg=(e,t,r)=>{switch(r.mode){case 0:return ug(e,t,r.pads.length);case 1:return lg(e,t,r.pads.length);case 2:return dg(e,t,r.pads.length);case 3:return pg(e,t,r.pads.length);default:throw new Error("Invalid mode")}},fg=(e,t)=>{let r=G.padShape(e[0].dims.slice(),t.pads),n=e[0].dims,i=G.size(r),o=[{type:12,data:i},{type:6,data:t.pads}];t.mode===0&&o.push({type:e[0].dataType,data:t.value}),o.push(...he(e[0].dims,r));let a=["rank"],u=l=>{let p=pe("output",e[0].dataType,r.length),f=q("x",e[0].dataType,n.length),m=f.type.value,y=cg(p,n.length,t),$=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:t.pads.length}];return t.mode===0&&$.push({name:"constant_value",type:m}),` + ${l.registerUniforms($).declareVariables(f,p)} + ${l.mainStart()} + ${l.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${p.offsetToIndices("global_idx")}; + + var value = ${m}(0); + ${y} + output[global_idx] = value; + }`};return{name:"Pad",shaderCache:{hint:`${t.mode}`,inputDependencies:a},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(G.size(r)/64)},programUniforms:o}),getShaderSource:u}},hg=(e,t)=>{if(e.length>1){let r=e[1].getBigInt64Array(),n=e.length>=3&&e[2].data?e[2].getFloat32Array()[0]:0,i=e[0].dims.length,o=new Int32Array(2*i).fill(0);if(e.length>=4){let u=e[3].getBigInt64Array();for(let l=0;lo[Number(l)]=Number(u));let a=[];return o.forEach(u=>a.push(u)),{mode:t.mode,value:n,pads:a}}else return t},Jw=(e,t)=>{sg(e.inputs);let r=hg(e.inputs,t);e.compute(fg(e.inputs,r),{inputs:[0]})}}),Ra,Nl,Wl,Ul,Ll,mg,gg,Vl,Hl,e2,t2,Fl,r2,n2,jl,i2,a2,o2,s2,Ex=Z(()=>{Rr(),ve(),Ee(),Se(),Ra=e=>{if(Ue.webgpu.validateInputContent&&(!e||e.length!==1))throw new Error("Pool ops requires 1 input.")},Nl=(e,t,r)=>{let n=t.format==="NHWC",i=e.dims.slice();n&&i.splice(1,0,i.pop());let o=Object.hasOwnProperty.call(t,"dilations"),a=t.kernelShape.slice(),u=t.strides.slice(),l=o?t.dilations.slice():[],p=t.pads.slice();cu.adjustPoolAttributes(r,i,a,u,l,p);let f=cu.computePoolOutputShape(r,i,u,l,a,p,t.autoPad),m=Object.assign({},t);o?Object.assign(m,{kernelShape:a,strides:u,pads:p,dilations:l,cacheKey:t.cacheKey}):Object.assign(m,{kernelShape:a,strides:u,pads:p,cacheKey:t.cacheKey});let y=f.slice();return y.push(y.splice(1,1)[0]),[m,n?y:f]},Wl=(e,t)=>{let r=t.format==="NHWC",n=G.size(e),i=G.size(t.kernelShape),o=[{type:12,data:n},{type:12,data:i}],a=[{name:"outputSize",type:"u32"},{name:"kernelSize",type:"u32"}];if(t.kernelShape.length<=2){let u=t.kernelShape[t.kernelShape.length-1],l=t.strides[t.strides.length-1],p=t.pads[t.pads.length/2-1],f=t.pads[t.pads.length-1],m=!!(p+f);o.push({type:12,data:u},{type:12,data:l},{type:12,data:p},{type:12,data:f}),a.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let y=!1;if(t.kernelShape.length===2){let $=t.kernelShape[t.kernelShape.length-2],c=t.strides[t.strides.length-2],x=t.pads[t.pads.length/2-2],T=t.pads[t.pads.length-2];y=!!(x+T),o.push({type:12,data:$},{type:12,data:c},{type:12,data:x},{type:12,data:T}),a.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[o,a,!0,m,y]}else{if(r)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let u=G.computeStrides(t.kernelShape);o.push({type:12,data:u},{type:12,data:t.pads},{type:12,data:t.strides}),a.push({name:"kernelStrides",type:"u32",length:u.length},{name:"pads",type:"u32",length:t.pads.length},{name:"strides",type:"u32",length:t.strides.length});let l=t.pads.reduce((p,f)=>p+f);return[o,a,!!l,!1,!1]}},Ul=(e,t,r,n,i,o,a,u,l,p,f,m)=>{let y=i.format==="NHWC",$=t.type.value,c=pe("output",t.type.tensor,n);if(i.kernelShape.length<=2){let x="",T="",_="",v=r-(y?2:1);if(f?x=` + for (var i: u32 = 0u; i < uniforms.kw; i++) { + xIndices[${v}] = indices[${v}] * uniforms.sw - uniforms.pwStart + i; + if (xIndices[${v}] < 0 || xIndices[${v}] + >= uniforms.x_shape[${v}]) { + pad++; + continue; + } + let x_val = x[${t.indicesToOffset("xIndices")}]; + ${o} + }`:x=` + for (var i: u32 = 0u; i < uniforms.kw; i++) { + xIndices[${v}] = indices[${v}] * uniforms.sw - uniforms.pwStart + i; + let x_val = x[${t.indicesToOffset("xIndices")}]; + ${o} + }`,i.kernelShape.length===2){let k=r-(y?3:2);m?T=` + for (var j: u32 = 0u; j < uniforms.kh; j++) { + xIndices[${k}] = indices[${k}] * uniforms.sh - uniforms.phStart + j; + if (xIndices[${k}] < 0 || xIndices[${k}] >= uniforms.x_shape[${k}]) { + pad += i32(uniforms.kw); + continue; + } + `:T=` + for (var j: u32 = 0u; j < uniforms.kh; j++) { + xIndices[${k}] = indices[${k}] * uniforms.sh - uniforms.phStart + j; + `,_=` + } + `}return` + ${e.registerUniforms(l).declareVariables(t,c)} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + + let indices = ${c.offsetToIndices("global_idx")}; + var xIndices = ${c.offsetToIndices("global_idx")}; + + var value = ${$}(${u}); + var pad = 0; + ${T} + ${x} + ${_} + ${a} + + output[global_idx] = value; + }`}else{if(y)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let x=i.kernelShape.length,T=i.pads.length,_="";return p?_=` + if (xIndices[j] >= uniforms.x_shape[j]) { + pad++; + isPad = true; + break; + } + } + if (!isPad) { + let x_val = x[${t.indicesToOffset("xIndices")}]; + ${o} + }`:_=` + } + let x_val = x[${t.indicesToOffset("xIndices")}]; + ${o} + `,` + ${e.registerUniforms(l).declareVariables(t,c)} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + let indices = ${c.offsetToIndices("global_idx")}; + var xIndices = ${c.offsetToIndices("global_idx")}; + + var offsets: array; + + var value = ${$}(${u}); + var pad = 0; + var isPad = false; + + for (var i: u32 = 0u; i < uniforms.kernelSize; i++) { + var offset = i; + for (var j = 0u; j < ${x-1}u; j++) { + offsets[j] = offset / ${_e("uniforms.kernelStrides","j",x)}; + offset -= offsets[j] * ${_e("uniforms.kernelStrides","j",x)}; + } + offsets[${x-1}] = offset; + + isPad = false; + for (var j = ${r-x}u; j < ${r}u; j++) { + xIndices[j] = indices[j] * ${_e("uniforms.strides",`j - ${r-x}u`,x)} + + offsets[j - ${r-x}u] - ${_e("uniforms.pads","j - 2u",T)}; + ${_} + } + ${a} + + output[global_idx] = value; + }`}},Ll=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,mg=e=>`${Ll(e)};${e.countIncludePad}`,gg=e=>`${Ll(e)};${e.storageOrder};${e.dilations}`,Vl=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}),Hl=(e,t,r,n)=>{let[i,o]=Nl(t,n,r),a=q("x",t.dataType,t.dims.length),u=a.type.value,l="value += x_val;",p="";i.countIncludePad?p+=`value /= ${u}(uniforms.kernelSize);`:p+=`value /= ${u}(i32(uniforms.kernelSize) - pad);`;let[f,m,y,$,c]=Wl(o,i);f.push(...he(t.dims,o));let x=["rank"];return{name:e,shaderCache:{hint:`${n.cacheKey};${y};${$};${c}`,inputDependencies:x},getRunData:()=>({outputs:[{dims:o,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(G.size(o)/64)},programUniforms:f}),getShaderSource:T=>Ul(T,a,t.dims.length,o.length,i,l,p,0,m,y,$,c)}},e2=e=>{let t=e.count_include_pad!==0,r=Vl(e);if(r.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");let n={countIncludePad:t,...r,cacheKey:""};return{...n,cacheKey:mg(n)}},t2=(e,t)=>{Ra(e.inputs),e.compute(Hl("AveragePool",e.inputs[0],!1,t))},Fl={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},r2=e=>{let t=e.format;return{format:t,...Fl,cacheKey:t}},n2=(e,t)=>{Ra(e.inputs),e.compute(Hl("GlobalAveragePool",e.inputs[0],!0,t))},jl=(e,t,r,n)=>{let[i,o]=Nl(t,n,r),a=` + value = max(x_val, value); + `,u="",l=q("x",t.dataType,t.dims.length),p=["rank"],[f,m,y,$,c]=Wl(o,i);return f.push(...he(t.dims,o)),{name:e,shaderCache:{hint:`${n.cacheKey};${y};${$};${c}`,inputDependencies:p},getRunData:()=>({outputs:[{dims:o,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(G.size(o)/64)},programUniforms:f}),getShaderSource:x=>Ul(x,l,t.dims.length,o.length,i,a,u,t.dataType===10?-65504:-1e5,m,y,$,c)}},i2=(e,t)=>{Ra(e.inputs),e.compute(jl("MaxPool",e.inputs[0],!1,t))},a2=e=>{let t=e.storage_order,r=e.dilations,n=Vl(e);if(t!==0)throw new Error("column major storage order is not yet supported for MaxPool");if(n.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");let i={storageOrder:t,dilations:r,...n,cacheKey:""};return{...i,cacheKey:gg(i)}},o2=e=>{let t=e.format;return{format:t,...Fl,cacheKey:t}},s2=(e,t)=>{Ra(e.inputs),e.compute(jl("GlobalMaxPool",e.inputs[0],!0,t))}}),yg,vg,u2,Cx=Z(()=>{Rr(),ve(),Se(),yg=(e,t,r)=>{let n=e===t,i=et&&r>0;if(n||i||o)throw new Error("Range these inputs' contents are invalid.")},vg=(e,t,r,n)=>{let i=Math.abs(Math.ceil((t-e)/r)),o=[i],a=i,u=[{type:12,data:a},{type:n,data:e},{type:n,data:r},...he(o)],l=p=>{let f=pe("output",n,o.length),m=f.type.value,y=[{name:"outputSize",type:"u32"},{name:"start",type:m},{name:"delta",type:m}];return` + ${p.registerUniforms(y).declareVariables(f)} + ${p.mainStart()} + ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + output[global_idx] = uniforms.start + ${m}(global_idx) * uniforms.delta; + }`};return{name:"Range",shaderCache:{hint:`${n}`},getShaderSource:l,getRunData:()=>({outputs:[{dims:o,dataType:n}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:u})}},u2=e=>{let t=0,r=0,n=0;e.inputs[0].dataType===6?(t=e.inputs[0].getInt32Array()[0],r=e.inputs[1].getInt32Array()[0],n=e.inputs[2].getInt32Array()[0]):e.inputs[0].dataType===1&&(t=e.inputs[0].getFloat32Array()[0],r=e.inputs[1].getFloat32Array()[0],n=e.inputs[2].getFloat32Array()[0]),Ue.webgpu.validateInputContent&&yg(t,r,n),e.compute(vg(t,r,n,e.inputs[0].dataType),{inputs:[]})}}),wg,$g,_g,bg,xg,Sg,kg,Eg,Cg,Tg,Ig,Gl,Ag,zg,Og,Rg,Pg,l2,d2,Tx=Z(()=>{ve(),Ee(),gt(),Se(),wg=(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 + 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")}},$g=(e,t,r)=>{t.every(i=>i>=0&&i{throw new Error("Resize requires axes input values to be positive and less than rank")}));let n=new Array(r).fill(1);return t.forEach((i,o)=>n[i]=e[o]),n},_g=(e,t,r,n,i,o)=>{let[a,u,l]=r>10?[1,2,3]:[-1,e.length>1?1:-1,-1],p=e[0].dims.length;if(a>0&&e.length>a&&e[a].dims.length>0)e[a].getFloat32Array().forEach(f=>o.push(f));else if(t.coordinateTransformMode==="tf_crop_and_resize")throw new Error("Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize");if(u>0&&e.length>u&&e[u].dims.length>0){if(e[u].getFloat32Array().forEach(f=>n.push(f)),n.length!==0&&n.length!==p&&r>=18&&n.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");wg(n,t),t.axes.length>0&&$g(n,t.axes,p).forEach((f,m)=>n[m]=f)}if(l>0&&e.length>l&&(e[l].getBigInt64Array().forEach(f=>i.push(Number(f))),i.length!==p||r>=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(n.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 n<"u"&&typeof i<"u"&&n.length>0&&i.length>p)throw new Error("Resize requires only of scales or sizes to be specified")},bg=(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`)}})()+"}",xg=(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`)}})()+"}",Sg=(e,t,r)=>{let n=new Array(r).fill(0).concat(new Array(r).fill(1)),i=e.length===0?n:e.slice();return t.length>0?(t.forEach((o,a)=>{n[o]=i[a],n[a+r]=i[t.length+a]}),n):i},kg=(e,t,r,n)=>{let i=[];if(r.length>0)if(n.length>0){if(e.forEach(o=>i.push(o)),Math.max(...n)>e.length)throw new Error("axes is out of bound");n.forEach((o,a)=>i[o]=r[a])}else r.forEach(o=>i.push(o));else{if(t.length===0)throw new Error("Resize requires either scales or sizes.");i=e.map((o,a)=>Math.round(o*t[a]))}return i},Eg=(e,t,r)=>{let n=(()=>{switch(r.keepAspectRatioPolicy){case"not_larger":return r.axes.length>0?Math.min(...r.axes.map(o=>t[o]),Number.MAX_VALUE):Math.min(...t,Number.MAX_VALUE);case"not_smaller":return r.axes.length>0?Math.max(...r.axes.map(o=>t[o]),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 i=e.slice();return r.axes.length>0?(r.axes.forEach(o=>t[o]=n),r.axes.forEach(o=>i[o]=Math.round(e[o]*t[o]))):(t.fill(n,0,t.length),i.forEach((o,a)=>i[a]=Math.round(o*t[a]))),i},Cg=(e,t,r,n,i)=>` + fn calculateOriginalIndicesFromOutputIndices(output_indices: ${e.type.indices}) -> array<${e.type.value}, ${r.length}> { + var original_indices: array<${e.type.value}, ${r.length}>; + for (var i:u32 = 0; i < ${r.length}; i++) { + var output_index = ${e.indicesGet("output_indices","i")}; + var scale = ${_e("uniforms.scales","i",n)}; + var roi_low = ${_e("uniforms.roi","i",i)}; + var roi_hi = ${_e("uniforms.roi",`i + ${t.length}`,i)}; + if (scale == 1.0) { + original_indices[i] = ${e.type.value}(output_index); + } else { + var input_shape_i = ${_e("uniforms.input_shape","i",t.length)}; + var output_shape_i = ${_e("uniforms.output_shape","i",r.length)}; + original_indices[i] = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, + input_shape_i, roi_low, roi_hi); + } + } + return original_indices; + }`,Tg=(e,t,r,n,i,o,a)=>` + fn calculateInputIndicesFromOutputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} { + var input_indices: ${e.type.indices}; + for (var i:u32 = 0; i < ${n.length}; i++) { + var output_index = ${t.indicesGet("output_indices","i")}; + var input_index: u32; + var scale = ${_e("uniforms.scales","i",i)}; + if (scale == 1.0) { + input_index = output_index; + } else { + var roi_low = ${_e("uniforms.roi","i",o)}; + var roi_hi = ${_e("uniforms.roi",`i + ${r.length}`,o)}; + var input_shape_i = ${_e("uniforms.input_shape","i",r.length)}; + var output_shape_i = ${_e("uniforms.output_shape","i",n.length)}; + var original_idx = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, + input_shape_i, roi_low, roi_hi); + if (!${a} || (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; + }`,Ig=(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 >= ${_e("uniforms.input_shape","i",t.length)}) { + return false; + } + } + return true; + }`,Gl=(e,t,r,n)=>e.rank>n?` + ${e.indicesSet("input_indices",t,"channel")}; + ${e.indicesSet("input_indices",r,"batch")}; +`:"",Ag=(e,t,r,n,i)=>{let[o,a,u,l]=r.length===2?[-1,0,1,-1]:[0,2,3,1],p=e.type.value;return` + fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${p} { + var input_indices: ${e.type.indices}; + ${e.indicesSet("input_indices",a,`max(0, min(row, ${r[a]} - 1))`)}; + ${e.indicesSet("input_indices",u,`max(0, min(col, ${r[u]} - 1))`)}; + ${Gl(e,l,o,2)} + return ${e.getByIndices("input_indices")}; + } + + fn bilinearInterpolation(output_indices: ${t.type.indices}) -> ${p} { + var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); + var row:${p} = originalIndices[${a}]; + var col:${p} = originalIndices[${u}]; + ${n?`if (row < 0 || row > (${r[a]} - 1) || col < 0 || col > (${r[u]} - 1)) { + return ${i}; + }`:""}; + row = max(0, min(row, ${r[a]} - 1)); + col = max(0, min(col, ${r[u]} - 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 = ${r.length>2?`u32(originalIndices[${l}])`:"0"}; + var batch: u32 = ${r.length>2?`u32(originalIndices[${o}])`:"0"}; + var x11: ${p} = getInputValue(batch, channel, row1, col1); + var x12: ${p} = getInputValue(batch, channel, row1, col2); + var x21: ${p} = getInputValue(batch, channel, row2, col1); + var x22: ${p} = getInputValue(batch, channel, row2, col2); + var dx1: ${p} = abs(row - ${p}(row1)); + var dx2: ${p} = abs(${p}(row2) - row); + var dy1: ${p} = abs(col - ${p}(col1)); + var dy2: ${p} = abs(${p}(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); + }`},zg=(e,t,r,n,i,o,a,u,l,p)=>{let f=r.length===2,[m,y]=f?[0,1]:[2,3],$=e.type.value,c=x=>{let T=x===m?"row":"col";return` + fn ${T}CubicInterpolation(input_indices: ${e.type.indices}, output_indices: ${t.type.indices}) -> ${$} { + var output_index = ${t.indicesGet("output_indices",x)}; + var originalIdx: ${$} = getOriginalCoordinateFromResizedCoordinate(output_index, ${i[x]}, + ${n[x]}, ${r[x]}, ${o[x]}, ${o[x]} + ${r.length}); + var fractOriginalIdx: ${$} = originalIdx - floor(originalIdx); + var coefs = getCubicInterpolationCoefs(fractOriginalIdx); + + if (${u} && (originalIdx < 0 || originalIdx > (${r[x]} - 1))) { + return ${l}; + } + var data: array<${$}, 4> = array<${$}, 4>(0.0, 0.0, 0.0, 0.0); + for (var i: i32 = -1; i < 3; i++) { + var ${T}: ${$} = originalIdx + ${$}(i); + if (${T} < 0 || ${T} >= ${r[x]}) { + ${p?`coefs[i + 1] = 0.0; + continue;`:u?`return ${l};`:`${T} = max(0, min(${T}, ${r[x]} - 1));`}; + } + var input_indices_copy: ${e.type.indices} = input_indices; + ${e.indicesSet("input_indices_copy",x,`u32(${T})`)}; + data[i + 1] = ${x===m?e.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"}; + } + return cubicInterpolation1D(data, coefs); + }`};return` + ${c(m)}; + ${c(y)}; + fn getCubicInterpolationCoefs(s: ${$}) -> array<${$}, 4> { + var absS = abs(s); + var coeffs: array<${$}, 4> = array<${$}, 4>(0.0, 0.0, 0.0, 0.0); + var oneMinusAbsS: ${$} = 1.0 - absS; + var twoMinusAbsS: ${$} = 2.0 - absS; + var onePlusAbsS: ${$} = 1.0 + absS; + coeffs[0] = ((${a} * onePlusAbsS - 5 * ${a}) * onePlusAbsS + 8 * ${a}) * onePlusAbsS - 4 * ${a}; + coeffs[1] = ((${a} + 2) * absS - (${a} + 3)) * absS * absS + 1; + coeffs[2] = ((${a} + 2) * oneMinusAbsS - (${a} + 3)) * oneMinusAbsS * oneMinusAbsS + 1; + coeffs[3] = ((${a} * twoMinusAbsS - 5 * ${a}) * twoMinusAbsS + 8 * ${a}) * twoMinusAbsS - 4 * ${a}; + return coeffs; + } + + fn cubicInterpolation1D(x: array<${$}, 4>, coefs: array<${$}, 4>) -> ${$} { + var coefsSum: ${$} = 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}) -> ${$} { + var input_indices: ${e.type.indices} = output_indices; + return colCubicInterpolation(input_indices, output_indices); + } + `},Og=(e,t,r,n,i)=>{let[o,a,u,l,p]=r.length===3?[-1,0,1,2,-1]:[0,2,3,4,1],f=e.type.value;return` + fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${f} { + var input_indices: ${e.type.indices}; + ${e.indicesSet("input_indices",a,`max(0, min(depth, ${r[a]} - 1))`)}; + ${e.indicesSet("input_indices",u,`max(0, min(height, ${r[u]} - 1))`)}; + ${e.indicesSet("input_indices",l,`max(0, min(width, ${r[l]} - 1))`)}; + ${Gl(e,p,o,3)} + return ${e.getByIndices("input_indices")}; + } + + fn trilinearInterpolation(output_indices: ${t.type.indices}) -> ${f} { + var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); + var depth:${f} = originalIndices[${a}]; + var height:${f} = originalIndices[${u}]; + var width:${f} = originalIndices[${l}]; + ${n?`if (depth < 0 || depth > (${r[a]} - 1) || height < 0 || height > (${r[u]} - 1) || width < 0 || (width > ${r[l]} - 1)) { + return ${i}; + }`:""}; + + depth = max(0, min(depth, ${r[a]} - 1)); + height = max(0, min(height, ${r[u]} - 1)); + width = max(0, min(width, ${r[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 = ${r.length>3?`u32(originalIndices[${p}])`:"0"}; + var batch: u32 = ${r.length>3?`u32(originalIndices[${o}])`:"0"}; + + var x111: ${f} = getInputValue(batch, channel, depth1, height1, width1); + var x112: ${f} = getInputValue(batch, channel, depth1, height1, width2); + var x121: ${f} = getInputValue(batch, channel, depth1, height2, width1); + var x122: ${f} = getInputValue(batch, channel, depth1, height2, width2); + var x211: ${f} = getInputValue(batch, channel, depth2, height1, width1); + var x212: ${f} = getInputValue(batch, channel, depth2, height1, width2); + var x221: ${f} = getInputValue(batch, channel, depth2, height2, width1); + var x222: ${f} = getInputValue(batch, channel, depth2, height2, width2); + var dx1: ${f} = abs(depth - ${f}(depth1)); + var dx2: ${f} = abs(${f}(depth2) - depth); + var dy1: ${f} = abs(height - ${f}(height1)); + var dy2: ${f} = abs(${f}(height2) - height); + var dz1: ${f} = abs(width - ${f}(width1)); + var dz2: ${f} = abs(${f}(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); + }`},Rg=(e,t,r,n,i,o)=>{let a=e.dims,u=Sg(o,t.axes,a.length),l=kg(a,n,i,t.axes),p=n.slice();n.length===0&&(p=a.map((v,k)=>v===0?1:l[k]/v),t.keepAspectRatioPolicy!=="stretch"&&(l=Eg(a,p,t)));let f=pe("output",e.dataType,l.length),m=q("input",e.dataType,a.length),y=G.size(l),$=a.length===l.length&&a.every((v,k)=>v===l[k]),c=t.coordinateTransformMode==="tf_crop_and_resize",x=t.extrapolationValue,T=m.type.value,_=v=>` + ${$?"":` + ${bg(t.coordinateTransformMode,T)}; + ${(()=>{switch(t.mode){case"nearest":return` + ${Ig(m,a)}; + ${xg(t.nearestMode,r,T)}; + ${Tg(m,f,a,l,p.length,u.length,c)}; + `;case"linear":return` + ${Cg(f,a,l,p.length,u.length)}; + ${(()=>{if(a.length===2||a.length===4)return`${Ag(m,f,a,c,x)}`;if(a.length===3||a.length===5)return`${Og(m,f,a,c,x)}`;throw Error("Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.")})()}; + `;case"cubic":return` + ${(()=>{if(a.length===2||a.length===4)return`${zg(m,f,a,l,p,u,t.cubicCoeffA,c,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")}})()}; + `} + ${v.registerUniform("output_size","u32").registerUniform("scales","f32",p.length).registerUniform("roi","f32",u.length).declareVariables(m,f)} + ${v.mainStart()} + ${v.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + ${$?"output[global_idx] = input[global_idx];":` + let output_indices = ${f.offsetToIndices("global_idx")}; + var input_indices: ${m.type.indices}; + ${(()=>{switch(t.mode){case"nearest":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices); + if (checkInputIndices(input_indices)) { + output[global_idx] = ${m.getByIndices("input_indices")}; + } else { + output[global_idx] = ${t.extrapolationValue}; + }`;case"linear":return`output[global_idx] = ${a.length===2||a.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}|${r}|${p.length>0?p:""}|${i.length>0?i:""}|${u.length>0?u:""}|${$}|${a}`,inputDependencies:["rank"]},getShaderSource:_,getRunData:()=>({outputs:[{dims:l,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(y/64)},programUniforms:[{type:12,data:y},{type:1,data:p},{type:1,data:u},...he(a,l)]})}},Pg=e=>{let t=e.customDataBuffer;return new Uint32Array(t,t.byteOffset,1)[0]},l2=(e,t)=>{let r=[],n=[],i=[],o=Pg(e);if(t.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");_g(e.inputs,t,o,r,n,i),e.compute(Rg(e.inputs[0],t,o,r,n,i),{inputs:[0]})},d2=e=>{let t=e.antialias,r=e.axes,n=e.coordinateTransformMode,i=e.cubicCoeffA,o=e.excludeOutside!==0,a=e.extrapolationValue,u=e.keepAspectRatioPolicy,l=e.mode,p=e.nearestMode===""?"simple":e.nearestMode;return qe({antialias:t,axes:r,coordinateTransformMode:n,cubicCoeffA:i,excludeOutside:o,extrapolationValue:a,keepAspectRatioPolicy:u,mode:l,nearestMode:p})}}),Mg,Bg,p2,Ix=Z(()=>{ve(),Ee(),gt(),Se(),Mg=(e,t)=>{let[r,n,i,o]=e,{numHeads:a,rotaryEmbeddingDim:u}=t;if(r.dims.length!==3&&r.dims.length!==4)throw new Error(`Input 'x' is expected to have 3 or 4 dimensions, got ${r.dims.length}`);if(!G.areEqual(n.dims,[])&&!G.areEqual(n.dims,[1])&&n.dims.length!==2)throw new Error(`Input 'position_ids' is expected to have 0, 1, or 2 dimensions, got ${n.dims.length}`);if(i.dims.length!==2)throw new Error(`Input 'cos_cache' is expected to have 2 dimensions, got ${i.dims.length}`);if(o.dims.length!==2)throw new Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${o.dims.length}`);if(!G.areEqual(i.dims,o.dims))throw new Error("Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape");if(u>0&&a===0)throw new Error("num_heads must be provided if rotary_embedding_dim is specified");let l=r.dims[0],p=r.dims[r.dims.length-2],f=i.dims[0],m=G.sizeFromDimension(r.dims,1)/p,y=u===0?i.dims[1]*2:m/a;if(u>y)throw new Error("rotary_embedding_dim must be less than or equal to head_size");if(n.dims.length===2){if(l!==n.dims[0])throw new Error(`Input 'position_ids' dimension 0 should be of size batch_size, got ${n.dims[0]}`);if(p!==n.dims[1])throw new Error(`Input 'position_ids' dimension 1 should be of size sequence_length, got ${n.dims[1]}`)}if(y/2!==i.dims[1]&&u/2!==i.dims[1])throw new Error(`Input 'cos_cache' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${i.dims[1]}`);if(p>f)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported")},Bg=(e,t)=>{let{interleaved:r,numHeads:n,rotaryEmbeddingDim:i,scale:o}=t,a=e[0].dims[0],u=G.sizeFromDimension(e[0].dims,1),l=e[0].dims[e[0].dims.length-2],p=u/l,f=e[2].dims[1],m=i===0?f*2:p/n,y=new Array(a,l,p/m,m-f),$=G.computeStrides(y),c=[{type:1,data:o},{type:12,data:y},{type:12,data:$},...e[0].dims.length===3?new Array({type:12,data:[u,p,m,1]}):[],...e[0].dims.length===4?new Array({type:12,data:[u,m,l*m,1]}):[],...he(e[0].dims,e[1].dims,e[2].dims,e[3].dims,e[0].dims)],x=T=>{let _=q("input",e[0].dataType,e[0].dims.length),v=q("position_ids",e[1].dataType,e[1].dims.length),k=q("cos_cache",e[2].dataType,e[2].dims.length),C=q("sin_cache",e[3].dataType,e[3].dims.length),I=pe("output",e[0].dataType,e[0].dims.length);return T.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:y.length},{name:"global_strides",type:"u32",length:$.length},{name:"input_output_strides",type:"u32",length:$.length}]),` + ${T.declareVariables(_,v,k,C,I)} + + ${T.mainStart(ea)} + let half_rotary_emb_dim = uniforms.${k.name}_shape[1]; + let bsnh = global_idx / uniforms.global_strides % uniforms.global_shape; + let size = uniforms.global_shape[0] * uniforms.global_strides[0]; + ${T.guardAgainstOutOfBoundsWorkgroupSizes("size")} + + if (bsnh[3] < half_rotary_emb_dim) { + let position_ids_idx = + ${v.broadcastedIndicesToOffset("bsnh.xy",pe("",v.type.tensor,2))}; + let position_id = + u32(${v.getByOffset("position_ids_idx")}) + select(0, bsnh[1], position_ids_idx == 0); + let i = dot(bsnh, uniforms.input_output_strides) + select(0, bsnh[3], ${r}); + let j = i + select(half_rotary_emb_dim, 1, ${r}); + let re = ${_.getByOffset("i")} * ${k.get("position_id","bsnh[3]")} - + ${_.getByOffset("j")} * ${C.get("position_id","bsnh[3]")}; + ${I.setByOffset("i","re")} + let im = ${_.getByOffset("i")} * ${C.get("position_id","bsnh[3]")} + + ${_.getByOffset("j")} * ${k.get("position_id","bsnh[3]")}; + ${I.setByOffset("j","im")} + } else { + let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim; + ${I.setByOffset("k",_.getByOffset("k"))} + } + }`};return{name:"RotaryEmbedding",shaderCache:{hint:qe({interleaved:r}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:x,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(G.size(y)/ea)},programUniforms:c})}},p2=(e,t)=>{Mg(e.inputs,t),e.compute(Bg(e.inputs,t))}}),Dg,Ng,c2,Ax=Z(()=>{ve(),Ee(),Se(),Dg=e=>{if(!e||e.length<3)throw new Error("layerNorm requires at least 3 inputs.");let t=e[0],r=e[1],n=e[2];if(t.dataType!==r.dataType||t.dataType!==n.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 i=t.dims[t.dims.length-1],o=t.dims[t.dims.length-2];if(r.dims[r.dims.length-1]!==i)throw new Error("Skip must have the same hidden size as input");if(r.dims[r.dims.length-2]!==o)throw new Error("Skip must have the same sequence length as input");if(n.dims.length!==1)throw new Error("Gamma must be 1D");if(n.dims[n.dims.length-1]!==i)throw new Error("Gamma must have the same hidden size as input");if(e.length>3){let a=e[3];if(a.dims.length!==1)throw new Error("Beta must be 1D");if(a.dims[a.dims.length-1]!==i)throw new Error("Beta must have the same hidden size as input")}if(e.length>4){let a=e[4];if(a.dims.length!==1)throw new Error("Bias must be 1D");if(a.dims[a.dims.length-1]!==i)throw new Error("Bias must have the same hidden size as input")}},Ng=(e,t,r,n)=>{let i=t.simplified,o=e[0].dims,a=G.size(o),u=o,l=a,p=o.slice(-1)[0],f=n?o.slice(0,-1).concat(1):[],m=!i&&e.length>3,y=e.length>4,$=n&&r>1,c=n&&r>2,x=r>3,T=ot(p),_=[{type:12,data:l},{type:12,data:T},{type:12,data:p},{type:1,data:t.epsilon}],v=C=>{let I=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],M=[q("x",e[0].dataType,e[0].dims,T),q("skip",e[1].dataType,e[1].dims,T),q("gamma",e[2].dataType,e[2].dims,T)];m&&M.push(q("beta",e[3].dataType,e[3].dims,T)),y&&M.push(q("bias",e[4].dataType,e[4].dims,T)),M.push(pe("output",e[0].dataType,u,T)),$&&M.push(pe("mean_output",1,f)),c&&M.push(pe("inv_std_output",1,f)),x&&M.push(pe("input_skip_bias_sum",e[0].dataType,u,T));let P=wt(e[0].dataType);return` + + ${C.registerUniforms(I).declareVariables(...M)} + + ${C.mainStart()} + ${C.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size / uniforms.hidden_size")} + let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components; + let offset = global_idx * hidden_size_vectorized; + var sum = ${Qr("f32",T)}; + var squareSum = ${Qr("f32",T)}; + for (var i: u32 = 0; i < hidden_size_vectorized; i++) { + let skip_value = skip[offset + i]; + let bias_value = ${y?"bias[i]":P+"(0.0)"}; + let input_value = x[offset + i]; + let value = input_value + skip_value + bias_value; + ${x?"input_skip_bias_sum[offset + i] = value;":""} + output[offset + i] = value; + let f32_value = ${Wi(P,T,"value")}; + sum += f32_value; + squareSum += f32_value * f32_value; + } + let mean = ${Tn("sum",T)} / f32(uniforms.hidden_size); + let inv_std_dev = inverseSqrt(${Tn("squareSum",T)} / f32(uniforms.hidden_size) ${i?"":"- mean * mean"} + uniforms.epsilon); + ${$?"mean_output[global_idx] = mean;":""} + ${c?"inv_std_output[global_idx] = inv_std_dev;":""} + for (var i: u32 = 0; i < hidden_size_vectorized; i++) { + output[offset + i] = (output[offset + i] ${i?"":`- ${P}(mean)`}) * ${P}(inv_std_dev) * gamma[i] ${m?"+ beta[i]":""}; + } + }`},k=[{dims:u,dataType:e[0].dataType}];return r>1&&k.push({dims:f,dataType:1}),r>2&&k.push({dims:f,dataType:1}),r>3&&k.push({dims:o,dataType:e[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${T};${$};${c};${x}`,inputDependencies:e.map((C,I)=>"type")},getShaderSource:v,getRunData:()=>({outputs:k,dispatchGroup:{x:Math.ceil(l/p/64)},programUniforms:_})}},c2=(e,t)=>{Dg(e.inputs);let r=[0];e.outputCount>1&&r.push(-3),e.outputCount>2&&r.push(-3),e.outputCount>3&&r.push(3),e.compute(Ng(e.inputs,t,e.outputCount,!1),{outputs:r})}}),Wg,Pa,Ug,ql,Lg,Vg,f2,h2,zx=Z(()=>{ve(),Ee(),gt(),Se(),Wg=(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,n)=>{if(e[n+1].dataType!==6&&e[n+1].dataType!==7)throw new Error(`Input ${n} must be an array of int32 or int64`)})},Pa=(e,t)=>{let r=[];if(e.length>t)if(e[t].dataType===7)e[t].getBigInt64Array().forEach(n=>r.push(Number(n)));else if(e[t].dataType===6)e[t].getInt32Array().forEach(n=>r.push(Number(n)));else throw new Error(`Input ${t} must be an array of int32 or int64`);return r},Ug=(e,t)=>{if(e.length>1){let r=Pa(e,1),n=Pa(e,2),i=Pa(e,3);return i.length===0&&(i=[...Array(e[0].dims.length).keys()]),qe({starts:r,ends:n,axes:i})}else return t},ql=(e,t,r,n,i)=>{let o=e;return e<0&&(o+=r[n[t]]),i[t]<0?Math.max(0,Math.min(o,r[n[t]]-1)):Math.max(0,Math.min(o,r[n[t]]))},Lg=(e,t,r)=>`fn calculateInputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} { + var input_indices: ${e.type.indices}; + var carry = 0u; + for (var i = ${r.length}; i >= 0; i--) { + let input_shape_i = ${_e("uniforms.input_shape","i",r.length)}; + let steps_i = ${_e("uniforms.steps","i",r.length)}; + let signs_i = ${_e("uniforms.signs","i",r.length)}; + let starts_i = ${_e("uniforms.starts","i",r.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; + }`,Vg=(e,t)=>{let r=e[0].dims,n=G.size(r),i=t.axes.length>0?G.normalizeAxes(t.axes,r.length):[...Array(r.length).keys()],o=Pa(e,4);o.forEach(_=>_!==0||(()=>{throw new Error("step cannot be 0")})),o.length===0&&(o=Array(i.length).fill(1));let a=t.starts.map((_,v)=>ql(_,v,r,i,o)),u=t.ends.map((_,v)=>ql(_,v,r,i,o));if(i.length!==a.length||i.length!==u.length)throw new Error("start, ends and axes should have the same number of elements");if(i.length!==r.length)for(let _=0;_Math.sign(_));o.forEach((_,v,k)=>{if(_<0){let C=(u[v]-a[v])/_,I=a[v],M=I+C*o[v];a[v]=M,u[v]=I,k[v]=-_}});let p=r.slice(0);i.forEach((_,v)=>{p[_]=Math.ceil((u[_]-a[_])/o[_])});let f={dims:p,dataType:e[0].dataType},m=pe("output",e[0].dataType,p.length),y=q("input",e[0].dataType,e[0].dims.length),$=G.size(p),c=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:a.length},{name:"signs",type:"i32",length:l.length},{name:"steps",type:"u32",length:o.length}],x=[{type:12,data:$},{type:12,data:a},{type:6,data:l},{type:12,data:o},...he(e[0].dims,p)],T=_=>` + ${_.registerUniforms(c).declareVariables(y,m)} + ${Lg(y,m,r)} + ${_.mainStart()} + ${_.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + let output_indices = ${m.offsetToIndices("global_idx")}; + let input_indices = calculateInputIndices(output_indices); + ${m.setByOffset("global_idx",y.getByIndices("input_indices"))} + }`;return{name:"Slice",shaderCache:{hint:`${l.length}_${a.length}_${o.length}`,inputDependencies:["rank"]},getShaderSource:T,getRunData:()=>({outputs:[f],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:x})}},f2=(e,t)=>{Wg(e.inputs,t);let r=Ug(e.inputs,t);e.compute(Vg(e.inputs,r),{inputs:[0]})},h2=e=>{let t=e.starts,r=e.ends,n=e.axes;return qe({starts:t,ends:r,axes:n})}}),Hg,Fg,m2,g2,Ox=Z(()=>{ve(),Ee(),gt(),Se(),Hg=e=>{if(!e||e.length!==1)throw new Error("Softmax op requires 1 input.")},Fg=(e,t)=>{let r=e.dims,n=G.size(r),i=64,o=t.axis;if(o<0&&(o=r.length+o),o_===4?`max(max(${T}.x, ${T}.y), max(${T}.z, ${T}.w))`:_===2?`max(${T}.x, ${T}.y)`:_===3?`max(max(${T}.x, ${T}.y), ${T}.z)`:T,m=q("x",e.dataType,e.dims,l),y=pe("result",e.dataType,e.dims,l),$=m.type.value,c=wt(e.dataType)==="f32"?`var threadMax = ${$}(-3.402823e+38f);`:`var threadMax = ${$}(-65504.0h);`,x=T=>` + var rowMaxShared : ${$}; + var rowSumShared : ${$}; + var threadShared : array<${$}, ${i}>; + + fn getValue(row: i32, col: i32, row_stride: i32) -> ${$} { + let index = row * row_stride + col; + return x[index]; + } + + fn setValue(row: i32, col: i32, row_stride: i32, value: ${$}) { + let index = row * row_stride + col; + result[index] = value; + } + ${T.registerUniform("packedCols","i32").declareVariables(m,y)} + ${T.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 + ${c} + 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 = ${$}(${f("threadShared[0]",l)}); + } + workgroupBarrier(); + + // find the rows sum + var threadSum = ${$}(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 = ${$}(${Tn("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:r,dataType:e.dataType}],dispatchGroup:{x:u},programUniforms:[{type:6,data:p}]}),getShaderSource:x}},m2=(e,t)=>{Hg(e.inputs),e.compute(Fg(e.inputs[0],t))},g2=e=>qe({axis:e.axis})}),jg,Gg,qg,Kg,Yg,y2,v2,Rx=Z(()=>{ve(),Ee(),gt(),Se(),jg=e=>{if(!e||e.length<1)throw new Error("too few inputs")},Gg=(e,t)=>{let r=[],n=t.numOutputs;return e[1].dims[0]>0&&(e[1].getBigInt64Array().forEach(i=>r.push(Number(i))),n=r.length),qe({numOutputs:n,axis:t.axis,splitSizes:r})},qg=e=>` +fn calculateOutputIndex(index: u32) -> u32 { + for (var i: u32 = 0u; i < ${e}u; i += 1u ) { + if (index < ${_e("uniforms.size_in_split_axis","i",e)}) { + return i; + } + } + return ${e}u; +}`,Kg=e=>{let t=e.length,r=[];for(let n=0;n{let r=e[0].dims,n=G.size(r),i=e[0].dataType,o=G.normalizeAxis(t.axis,r.length),a=new Array(t.numOutputs),u=q("input",i,r.length),l=new Array(t.numOutputs),p=[],f=[],m=0,y=[{type:12,data:n}];for(let c=0;c` + ${c.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",l.length).declareVariables(u,...a)} + ${qg(l.length)} + ${Kg(a)} + + ${c.mainStart()} + ${c.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")} + + var indices = ${u.offsetToIndices("global_idx")}; + var index = ${u.indicesGet("indices",o)}; + let output_number = calculateOutputIndex(index); + if (output_number != 0) { + index -= ${_e("uniforms.size_in_split_axis","output_number - 1u",l.length)}; + ${u.indicesSet("indices",o,"index")}; + } + writeBufferData(output_number, indices, global_idx); + }`;return{name:"Split",shaderCache:{hint:t.cacheKey,inputDependencies:["rank"]},getShaderSource:$,getRunData:()=>({outputs:p,dispatchGroup:{x:Math.ceil(n/64)},programUniforms:y})}},y2=(e,t)=>{jg(e.inputs);let r=e.inputs.length===1?t:Gg(e.inputs,t);e.compute(Yg(e.inputs,r),{inputs:[0]})},v2=e=>{let t=e.axis,r=e.splitSizes,n=e.numOutputs<0?r.length:e.numOutputs;if(n!==r.length)throw new Error("numOutputs and splitSizes lengh must be equal");return qe({axis:t,numOutputs:n,splitSizes:r})}}),Kl,Qg,Xg,Zg,w2,Px=Z(()=>{ve(),Ee(),Se(),Kl=e=>Array.from(e.getBigInt64Array(),Number),Qg=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(Kl(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")},Xg=(e,t)=>{let r=[];for(let n=0;n{let t=e[0].dims,r=Kl(e[1]),n=Xg(t,r),i=G.size(n),o=e[0].dataType,a=q("input",o,t.length),u=pe("output",o,n.length),l=p=>` + const inputShape = ${a.indices(...t)}; + ${p.registerUniform("output_size","u32").declareVariables(a,u)} + ${p.mainStart()} + ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let output_indices = ${u.offsetToIndices("global_idx")}; + var input_indices: ${a.type.indices}; + for (var i = 0; i < ${t.length}; i++) { + let input_dim_i = ${a.indicesGet("uniforms.input_shape","i")}; + let input_dim_value = ${u.indicesGet("output_indices","i")} % input_dim_i; + + ${a.indicesSet("input_indices","i","input_dim_value")} + } + ${u.setByOffset("global_idx",a.getByIndices("input_indices"))} + }`;return{name:"Tile",shaderCache:{hint:`${r}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:[{type:12,data:i},...he(e[0].dims,n)]}),getShaderSource:l}},w2=e=>{Qg(e.inputs),e.compute(Zg(e.inputs),{inputs:[0]})}}),Jg,e0,$2,Mx=Z(()=>{ve(),Ee(),Se(),Jg=(e,t,r,n,i)=>{let o=pe("output_data",i,r.length,4),a=q("a_data",t[1].dataType,t[1].dims.length,4),u=q("b_data",t[2].dataType,t[2].dims.length,4),l=q("c_data",t[0].dataType,t[0].dims.length,4),p,f=(m,y,$)=>`select(${y}, ${m}, ${$})`;if(!n)p=o.setByOffset("global_idx",f(a.getByOffset("global_idx"),u.getByOffset("global_idx"),l.getByOffset("global_idx")));else{let m=(y,$,c="")=>{let x=`a_data[index_a${$}][component_a${$}]`,T=`b_data[index_b${$}][component_b${$}]`,_=`bool(c_data[index_c${$}] & (0xffu << (component_c${$} * 8)))`;return` + let output_indices${$} = ${o.offsetToIndices(`global_idx * 4u + ${$}u`)}; + let offset_a${$} = ${a.broadcastedIndicesToOffset(`output_indices${$}`,o)}; + let offset_b${$} = ${u.broadcastedIndicesToOffset(`output_indices${$}`,o)}; + let offset_c${$} = ${l.broadcastedIndicesToOffset(`output_indices${$}`,o)}; + let index_a${$} = offset_a${$} / 4u; + let index_b${$} = offset_b${$} / 4u; + let index_c${$} = offset_c${$} / 4u; + let component_a${$} = offset_a${$} % 4u; + let component_b${$} = offset_b${$} % 4u; + let component_c${$} = offset_c${$} % 4u; + ${y}[${$}] = ${c}(${f(x,T,_)}); + `};i===9?p=` + var data = vec4(0); + ${m("data",0,"u32")} + ${m("data",1,"u32")} + ${m("data",2,"u32")} + ${m("data",3,"u32")} + output_data[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:p=` + ${m("output_data[global_idx]",0)} + ${m("output_data[global_idx]",1)} + ${m("output_data[global_idx]",2)} + ${m("output_data[global_idx]",3)} + `}return` + ${e.registerUniform("vec_size","u32").declareVariables(l,a,u,o)} + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${p} + }`},e0=e=>{let t=e[1].dims,r=e[2].dims,n=e[0].dims,i=e[1].dataType,o=!(G.areEqual(t,r)&&G.areEqual(r,n)),a=t,u=G.size(t);if(o){let p=Ji.calcShape(Ji.calcShape(t,r,!1),n,!1);if(!p)throw new Error("Can't perform where op on the given tensors");a=p,u=G.size(a)}let l=Math.ceil(u/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:p=>Jg(p,e,a,o,i),getRunData:()=>({outputs:[{dims:a,dataType:i}],dispatchGroup:{x:Math.ceil(u/64/4)},programUniforms:[{type:12,data:l},...he(n,t,r,a)]})}},$2=e=>{e.compute(e0(e.inputs))}}),_2,Bx=Z(()=>{nx(),A1(),ix(),ax(),ox(),sx(),T1(),Iw(),cx(),fx(),hx(),mx(),gx(),yx(),vx(),wx(),$x(),_x(),bx(),Tw(),xx(),Sx(),kx(),Ex(),Cx(),fc(),Tx(),Ix(),Ax(),zx(),Ox(),Rx(),Px(),ko(),hc(),Mx(),_2=new Map([["Abs",[R1]],["Acos",[P1]],["Acosh",[M1]],["Add",[hw]],["ArgMax",[k1,Yd]],["ArgMin",[S1,Yd]],["Asin",[B1]],["Asinh",[D1]],["Atan",[N1]],["Atanh",[W1]],["Attention",[I1]],["AveragePool",[t2,e2]],["BatchNormalization",[z1]],["BiasAdd",[O1]],["BiasSplitGelu",[fw]],["Cast",[L1,U1]],["Ceil",[H1]],["Clip",[V1]],["Concat",[E1,C1]],["Conv",[tp,ep]],["ConvTranspose",[Ow,zw]],["Cos",[F1]],["Cosh",[j1]],["CumSum",[Rw,Pw]],["DepthToSpace",[Mw,Bw]],["Div",[mw]],["Einsum",[Dw,Nw]],["Elu",[G1,Ms]],["Equal",[gw]],["Erf",[q1]],["Exp",[K1]],["Expand",[Ww]],["FastGelu",[Uw]],["Floor",[Y1]],["FusedConv",[tp,ep]],["Gather",[Vw,Lw]],["GatherElements",[Fw,Hw]],["Gelu",[Q1]],["Gemm",[Gw,jw]],["GlobalAveragePool",[n2,r2]],["GlobalMaxPool",[s2,o2]],["Greater",[$w]],["GreaterOrEqual",[bw]],["HardSigmoid",[iw,nw]],["InstanceNormalization",[qw]],["LayerNormalization",[Kw]],["LeakyRelu",[X1,Ms]],["Less",[_w]],["LessOrEqual",[xw]],["Log",[cw]],["MatMul",[Cw]],["MatMulNBits",[Yw,Qw]],["MaxPool",[i2,a2]],["Mul",[yw]],["MultiHeadAttention",[Zw,Xw]],["Neg",[J1]],["Not",[Z1]],["Pad",[Jw]],["Pow",[vw]],["Range",[u2]],["Reciprocal",[ew]],["ReduceMin",[w1]],["ReduceMean",[h1]],["ReduceMax",[v1]],["ReduceSum",[_1]],["ReduceProd",[$1]],["ReduceL1",[m1]],["ReduceL2",[g1]],["ReduceLogSum",[x1]],["ReduceLogSumExp",[y1]],["ReduceSumSquare",[b1]],["Relu",[tw]],["Resize",[l2,d2]],["RotaryEmbedding",[p2]],["Sigmoid",[rw]],["Sin",[aw]],["Sinh",[ow]],["Slice",[f2,h2]],["SkipLayerNormalization",[c2]],["Split",[y2,v2]],["Sqrt",[sw]],["Softmax",[m2,g2]],["Sub",[ww]],["Tan",[uw]],["Tanh",[lw]],["ThresholdedRelu",[pw,Ms]],["Tile",[w2]],["Transpose",[r1,n1]],["Where",[$2]]])}),b2,Dx=Z(()=>{Rr(),si(),Se(),b2=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,r,n,i){Lr(e.programInfo.name);let o=this.backend.device,a=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let u=[];for(let p of t)u.push({binding:u.length,resource:{buffer:p.buffer}});for(let p of r)u.push({binding:u.length,resource:{buffer:p.buffer}});i&&u.push({binding:u.length,resource:i});let l=o.createBindGroup({layout:e.computePipeline.getBindGroupLayout(0),entries:u,label:e.programInfo.name});if(this.backend.sessionStatus==="capturing"){let p={kernelId:this.backend.currentKernelId,computePipeline:e.computePipeline,bindGroup:l,dispatchGroup:n};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(p)}a.setPipeline(e.computePipeline),a.setBindGroup(0,l),a.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(),zr(e.programInfo.name)}dispose(){}build(e,t){Lr(e.name);let r=this.backend.device,n=[];r.features.has("shader-f16")&&n.push("enable f16;");let i=t1(t,this.backend.device.limits),o=e.getShaderSource(i),a=`${n.join(` +`)} +${i.additionalImplementations} +${o}`,u=r.createShaderModule({code:a,label:e.name});rt("verbose",()=>`[WebGPU] ${e.name} shader code: ${a}`);let l=r.createComputePipeline({compute:{module:u,entryPoint:"main"},layout:"auto",label:e.name});return zr(e.name),{programInfo:e,computePipeline:l,uniformVariablesInfo:i.variablesInfo}}normalizeDispatchGroupSize(e){let t=typeof e=="number"?e:e.x,r=typeof e=="number"?1:e.y||1,n=typeof e=="number"?1:e.z||1,i=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(t<=i&&r<=i&&n<=i)return[t,r,n];let o=t*r*n,a=Math.ceil(Math.sqrt(o));if(a>i){if(a=Math.ceil(Math.cbrt(o)),a>i)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[a,a,a]}else return[a,a,1]}}}),t0,r0,n0,x2,Nx=Z(()=>{Rr(),ve(),si(),ex(),tx(),Bx(),Dx(),t0=(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 n=0;n{var i,o;let n=e.name;return(i=e.shaderCache)!=null&&i.hint&&(n+="["+e.shaderCache.hint+"]"),n+=":"+r+`:${t0(t,((o=e.shaderCache)==null?void 0:o.inputDependencies)??new Array(t.length).fill("dims"))}`,n},n0=class{constructor(e){e&&(this.architecture=e.architecture,this.vendor=e.vendor)}isArchitecture(e){return this.architecture===e}isVendor(e){return this.vendor===e}},x2=class{constructor(){this.currentSessionId=null,this.currentKernelId=null,this.commandEncoder=null,this.computePassEncoder=null,this.maxDispatchNumber=16,this.pendingDispatchNumber=0,this.pendingKernels=[],this.pendingQueries=new Map,this.sessionStatus="default",this.capturedCommandList=new Map,this.capturedPendingKernels=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 r=[],n={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:r};t.features.has("chromium-experimental-timestamp-query-inside-passes")?r.push("chromium-experimental-timestamp-query-inside-passes"):t.features.has("timestamp-query")&&r.push("timestamp-query"),t.features.has("shader-f16")&&r.push("shader-f16"),this.device=await t.requestDevice(n),this.adapterInfo=new n0(await t.requestAdapterInfo()),this.gpuDataManager=Jv(this),this.programManager=new b2(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,Xv(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,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(this.env.webgpu,"adapter",{value:t,writable:!1,enumerable:!0,configurable:!1}),this.setQueryType()}dispose(){typeof this.querySet<"u"&&this.querySet.destroy(),this.gpuDataManager.dispose()}getCommandEncoder(){return this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder()),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let e=this.getCommandEncoder(),t={};this.queryType==="at-passes"&&(t.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=e.beginComputePass(t)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;Lr(),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 n;let t=new BigUint64Array(e.getMappedRange()),r=this.pendingQueries.get(e);for(let i=0;i"u"&&(this.queryTimeBase=$);let x=Number($-this.queryTimeBase),T=Number(c-this.queryTimeBase);if(!Number.isSafeInteger(x)||!Number.isSafeInteger(T))throw new RangeError("incorrect timestamp range");if((n=this.env.webgpu.profiling)!=null&&n.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:m.map(_=>({dims:_.dims,dataType:Fn(_.dataType)})),outputsMetadata:y.map(_=>({dims:_.dims,dataType:Fn(_.dataType)})),kernelId:a,kernelType:l,kernelName:p,programName:f,startTime:x,endTime:T});else{let _="";m.forEach((k,C)=>{_+=`input[${C}]: [${k.dims}] | ${Fn(k.dataType)}, `});let v="";y.forEach((k,C)=>{v+=`output[${C}]: [${k.dims}] | ${Fn(k.dataType)}, `}),console.log(`[profiling] kernel "${a}|${l}|${p}|${f}" ${_}${v}execution time: ${T-x} ns`)}uu("GPU",`${f}::${$}::${c}`)}e.unmap(),this.pendingQueries.delete(e)}),zr()}run(e,t,r,n,i,o){Lr(e.name);let a=[];for(let v=0;vk):r;if(f.length!==u.length)throw new Error(`Output size ${f.length} must be equal to ${u.length}.`);let m=[],y=[];for(let v=0;v=o)throw new Error(`Invalid output index: ${f[v]}`);if(f[v]===-3)continue;let k=f[v]===-1,C=f[v]===-2,I=k||C?i(u[v].dataType,u[v].dims):n(f[v],u[v].dataType,u[v].dims);if(m.push(I),I.data===0)continue;let M=this.gpuDataManager.get(I.data);if(!M)throw new Error(`no GPU data for output: ${I.data}`);if(k&&this.temporaryData.push(M),C){let P=this.kernelPersistentData.get(this.currentKernelId);P||(P=[],this.kernelPersistentData.set(this.currentKernelId,P)),P.push(M)}y.push(M)}if(a.length!==t.length||y.length!==m.length){if(y.length===0)return zr(e.name),m;throw new Error(`Program ${e.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let $;if(p){let v=0,k=[];p.forEach(P=>{let B=typeof P.data=="number"?[P.data]:P.data;if(B.length===0)return;let H=P.type===10?2:4,F,me;P.type===10?(me=B.length>4?16:B.length>2?8:B.length*H,F=B.length>4?16:H*B.length):(me=B.length<=2?B.length*H:16,F=16),v=Math.ceil(v/me)*me,k.push(v);let ce=P.type===10?8:4;v+=B.length>4?Math.ceil(B.length/ce)*F:B.length*H});let C=16;v=Math.ceil(v/C)*C;let I=new ArrayBuffer(v);p.forEach((P,B)=>{let H=k[B],F=typeof P.data=="number"?[P.data]:P.data;if(P.type===6)new Int32Array(I,H,F.length).set(F);else if(P.type===12)new Uint32Array(I,H,F.length).set(F);else if(P.type===10)new Uint16Array(I,H,F.length).set(F);else if(P.type===1)new Float32Array(I,H,F.length).set(F);else throw new Error(`Unsupported uniform type: ${Fn(P.type)}`)});let M=this.gpuDataManager.create(v,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(M.buffer,0,I,0,v),this.gpuDataManager.release(M.id),$={offset:0,size:v,buffer:M.buffer}}let c=this.programManager.normalizeDispatchGroupSize(l),x=c[1]===1&&c[2]===1,T=r0(e,t,x),_=this.programManager.getArtifact(T);if(_||(_=this.programManager.build(e,c),this.programManager.setArtifact(T,_),rt("info",()=>`[artifact] key: ${T}, programName: ${e.name}`)),p&&_.uniformVariablesInfo){if(p.length!==_.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${_.uniformVariablesInfo.length}, got ${p.length} in program "${_.programInfo.name}".`);for(let v=0;v`[ProgramManager] run "${e.name}" (key=${T}) with ${c[0]}x${c[1]}x${c[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let v={kernelId:this.currentKernelId,programName:_.programInfo.name,inputTensorViews:t,outputTensorViews:m};this.pendingKernels.push(v),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(v)}return this.programManager.run(_,a,y,c,$),zr(e.name),m}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,r,n){let i=_2.get(e);if(!i)throw new Error(`kernel not implemented: ${e}`);let o={kernelType:e,kernelName:n,kernelEntry:i[0],attributes:[i[1],r]};this.kernels.set(t,o)}releaseKernel(e){let t=this.kernelPersistentData.get(e);if(t){for(let r of t)this.gpuDataManager.release(r.id);this.kernelPersistentData.delete(e)}this.kernelCustomData.delete(e),this.kernels.delete(e)}computeKernel(e,t,r){let n=this.kernels.get(e);if(!n)throw new Error(`kernel not created: ${e}`);let i=n.kernelType,o=n.kernelName,a=n.kernelEntry,u=n.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${i}] ${o}" is not allowed to be called recursively`);this.currentKernelId=e,u[0]&&(u[1]=u[0](u[1]),u[0]=void 0),rt("info",()=>`[WebGPU] Start to run kernel "[${i}] ${o}"...`);let l=this.env.debug;this.temporaryData=[];try{return l&&this.device.pushErrorScope("validation"),a(t,u[1]),0}catch(p){return r.push(Promise.resolve(`[WebGPU] Kernel "[${i}] ${o}" failed. ${p}`)),1}finally{l&&r.push(this.device.popErrorScope().then(p=>p?`GPU validation error for kernel "[${i}] ${o}": ${p.message}`:null));for(let p of this.temporaryData)this.gpuDataManager.release(p.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(e,t,r,n){let i=this.sessionExternalDataMapping.get(e);i||(i=new Map,this.sessionExternalDataMapping.set(e,i));let o=i.get(t),a=this.gpuDataManager.registerExternalBuffer(r,n,o==null?void 0:o[1]);return i.set(t,[a,r]),a}unregisterBuffers(e){let t=this.sessionExternalDataMapping.get(e);t&&(t.forEach(r=>this.gpuDataManager.unregisterExternalBuffer(r[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,r){return async()=>{let n=await qd(this,e,t);return Zv(n.buffer,r)}}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"||(typeof this.env.trace>"u"?this.env.wasm.trace:this.env.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"),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})))}captureBegin(){rt("info","captureBegin"),this.capturedCommandList.get(this.currentSessionId)||this.capturedCommandList.set(this.currentSessionId,[]),this.capturedPendingKernels.get(this.currentSessionId)||this.capturedPendingKernels.set(this.currentSessionId,[]),this.flush(),this.sessionStatus="capturing"}captureEnd(){rt("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){rt("info","replay"),this.sessionStatus="replaying";let e=this.capturedCommandList.get(this.currentSessionId),t=this.capturedPendingKernels.get(this.currentSessionId),r=e.length;this.pendingKernels=[];for(let n=0;n=this.maxDispatchNumber||this.queryType==="at-passes")&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus="default"}onReleaseSession(e){this.unregisterBuffers(e),this.capturedCommandList.has(e)&&this.capturedCommandList.delete(e),this.capturedPendingKernels.has(e)&&this.capturedPendingKernels.delete(e),this.gpuDataManager.onReleaseSession(e)}onRunStart(e){this.currentSessionId=e,this.setQueryType()}}}),S2={};aa(S2,{init:()=>k2});var $s,i0,k2,Wx=Z(()=>{ve(),Nx(),si(),Ee(),$s=class E2{constructor(t,r,n,i){this.module=t,this.dataType=r,this.data=n,this.dims=i}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let t=G.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=G.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=G.size(this.dims);return t===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,t)}reshape(t){if(G.size(t)!==G.size(this.dims))throw new Error("Invalid new shape");return new E2(this.module,this.dataType,this.data,t)}},i0=class{constructor(e,t,r){this.module=e,this.backend=t,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=t.adapterInfo;let n=e.HEAPU32,i=r>>>2;this.opKernelContext=n[i++];let o=n[i++];this.outputCount=n[i++],this.customDataOffset=n[i++],this.customDataSize=n[i++];let a=[];for(let u=0;utypeof u=="number"?this.inputs[u]:u))??this.inputs,n=(t==null?void 0:t.outputs)??[],i=(u,l,p)=>new $s(this.module,l,this.output(u,p),p),o=(u,l)=>{let p=yo(u);if(!p)throw new Error(`Unsupported data type: ${u}`);let f=p*G.size(l),m=f>0?this.backend.gpuDataManager.create(f).id:0;return new $s(this.module,u,m,l)};return this.backend.run(e,r,n,i,o,this.outputCount)}output(e,t){let r=this.module.stackSave();try{let n=this.module.stackAlloc((1+t.length)*4),i=n>>2;this.module.HEAPU32[i++]=t.length;for(let o=0;o{let i=t.jsepInit;if(!i)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(e==="webgpu"){let o=new x2;await o.initialize(r,n),i("webgpu",[o,a=>o.alloc(a),a=>o.free(a),(a,u,l,p=!1)=>{if(p)rt("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${a}, dst=${u}, size=${l}`),o.memcpy(a,u);else{rt("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${a}, gpuDataId=${u}, size=${l}`);let f=t.HEAPU8.subarray(a>>>0,(a>>>0)+l);o.upload(u,f)}},async(a,u,l)=>{rt("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${a}, dataOffset=${u}, size=${l}`),await o.download(a,()=>t.HEAPU8.subarray(u>>>0,(u>>>0)+l))},(a,u,l)=>o.createKernel(a,u,l,t.UTF8ToString(t._JsepGetNodeName(u))),a=>o.releaseKernel(a),(a,u,l,p)=>{rt("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${l}, kernel=${a}, contextDataOffset=${u}`);let f=new i0(t,o,u);return o.computeKernel(a,f,p)},()=>o.captureBegin(),()=>o.captureEnd(),()=>o.replay()])}else i("webnn")}}),a0,C2,T2,dn,o0,np,I2,A2,Yl,z2,O2,R2,Ux=Z(()=>{Zb(),Jb(),ve(),So(),oc(),Qv(),a0=(e,t)=>{it()._OrtInit(e,t)!==0&&je("Can't initialize onnxruntime.")},C2=async e=>{a0(e.wasm.numThreads,du(e.logLevel))},T2=async(e,t)=>{{let r=(Wx(),Qn(S2)).init;if(t==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");let n=e.webgpu.adapter;if(n){if(typeof n.limits!="object"||typeof n.features!="object"||typeof n.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let i=e.webgpu.powerPreference;if(i!==void 0&&i!=="low-power"&&i!=="high-performance")throw new Error(`Invalid powerPreference setting: "${i}"`);let o=e.webgpu.forceFallbackAdapter;if(o!==void 0&&typeof o!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${o}"`);if(n=await navigator.gpu.requestAdapter({powerPreference:i,forceFallbackAdapter:o}),!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");await r("webgpu",it(),e,n)}if(t==="webnn"){if(typeof navigator>"u"||!navigator.ml)throw new Error("WebNN is not supported in current environment");await r("webnn",it(),e)}}},dn=new Map,o0=e=>{let t=it(),r=t.stackSave();try{let n=t.stackAlloc(8);return t._OrtGetInputOutputCount(e,n,n+4)!==0&&je("Can't get session input/output count."),[t.HEAP32[n/4],t.HEAP32[n/4+1]]}finally{t.stackRestore(r)}},np=e=>{let t=it(),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]},I2=async(e,t)=>{var m,y;let r,n,i=it();Array.isArray(e)?[r,n]=e:e.buffer===i.HEAPU8.buffer?[r,n]=[e.byteOffset,e.byteLength]:[r,n]=np(e);let o=0,a=0,u=0,l=[],p=[],f=[];try{if([a,l]=Yv(t),(t==null?void 0:t.externalData)&&i.mountExternalData){let C=[];for(let I of t.externalData){let M=typeof I=="string"?I:I.path;C.push(pu(typeof I=="string"?I:I.data).then(P=>{i.mountExternalData(M,P)}))}await Promise.all(C)}o=await i._OrtCreateSession(r,n,a),o===0&&je("Can't create a session.");let[$,c]=o0(o),x=!!(t!=null&&t.enableGraphCapture),T=[],_=[],v=[];for(let C=0;C<$;C++){let I=i._OrtGetInputName(o,C);I===0&&je("Can't get an input name."),p.push(I),T.push(i.UTF8ToString(I))}for(let C=0;CC==="gpu-buffer")&&(u=i._OrtCreateBinding(o),u===0&&je("Can't create IO binding."),k={handle:u,outputPreferredLocations:v,outputPreferredLocationsEncoded:v.map(C=>Gd(C))}),dn.set(o,[o,p,f,k,x,!1]),[o,T,_]}catch($){throw p.forEach(c=>i._OrtFree(c)),f.forEach(c=>i._OrtFree(c)),u!==0&&i._OrtReleaseBinding(u),o!==0&&i._OrtReleaseSession(o),$}finally{i._free(r),a!==0&&i._OrtReleaseSessionOptions(a),l.forEach($=>i._free($)),(y=i.unmountExternalData)==null||y.call(i)}},A2=e=>{var l;let t=it(),r=dn.get(e);if(!r)throw new Error(`cannot release session. invalid session id: ${e}`);let[n,i,o,a,u]=r;a&&(u&&t._OrtClearBoundOutputs(a.handle),t._OrtReleaseBinding(a.handle)),(l=t.jsepOnReleaseSession)==null||l.call(t,e),i.forEach(p=>t._OrtFree(p)),o.forEach(p=>t._OrtFree(p)),t._OrtReleaseSession(n),dn.delete(e)},Yl=(e,t,r,n,i,o=!1)=>{if(!e){t.push(0);return}let a=it(),u=e[0],l=e[1],p=e[3],f,m;if(u==="string"&&p==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");if(o&&p!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${i} when enableGraphCapture is true.`);if(p==="gpu-buffer"){let c=e[2].gpuBuffer,x=yo(jd(u));m=l.reduce((_,v)=>_*v,1)*x;let T=a.jsepRegisterBuffer;if(!T)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');f=T(n,i,c,m)}else{let c=e[2];if(Array.isArray(c)){m=4*c.length,f=a._malloc(m),r.push(f);let x=f/4;for(let T=0;Ta.HEAP32[c++]=T);let x=a._OrtCreateTensor(jd(u),f,m,$,l.length,Gd(p));x===0&&je(`Can't create tensor for input/output. session=${n}, index=${i}.`),t.push(x)}finally{a.stackRestore(y)}},z2=async(e,t,r,n,i,o)=>{var F,me;let a=it(),u=dn.get(e);if(!u)throw new Error(`cannot run inference. invalid session id: ${e}`);let l=u[0],p=u[1],f=u[2],m=u[3],y=u[4],$=u[5],c=t.length,x=n.length,T=0,_=[],v=[],k=[],C=[],I=a.stackSave(),M=a.stackAlloc(c*4),P=a.stackAlloc(c*4),B=a.stackAlloc(x*4),H=a.stackAlloc(x*4);try{[T,_]=Kv(o);for(let U=0;UHe*lt,1);oe=Fn(Le);let fr=m==null?void 0:m.outputPreferredLocations[n[U]];if(oe==="string"){if(fr==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");let He=[],lt=we/4;for(let hr=0;hr0){let He=a.jsepGetBuffer;if(!He)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let lt=He(we),hr=yo(Le);if(hr===void 0||!uc(oe))throw new Error(`Unsupported data type: ${oe}`);ee=!0,le.push([oe,cr,{gpuBuffer:lt,download:a.jsepCreateDownloader(lt,Gt*hr,oe),dispose:()=>{a._OrtReleaseTensor(J)}},"gpu-buffer"])}else{let He=sc(oe),lt=new He(Gt);new Uint8Array(lt.buffer,lt.byteOffset,lt.byteLength).set(a.HEAPU8.subarray(we,we+lt.byteLength)),le.push([oe,cr,lt,"cpu"])}}finally{a.stackRestore(Q),oe==="string"&&we&&a._free(we),ee||a._OrtReleaseTensor(J)}}return m&&!y&&(a._OrtClearBoundOutputs(m.handle),dn.set(e,[l,p,f,m,y,!1])),le}finally{a.stackRestore(I),v.forEach(ce=>a._OrtReleaseTensor(ce)),k.forEach(ce=>a._OrtReleaseTensor(ce)),C.forEach(ce=>a._free(ce)),T!==0&&a._OrtReleaseRunOptions(T),_.forEach(ce=>a._free(ce))}},O2=e=>{let t=it(),r=dn.get(e);if(!r)throw new Error("invalid session id");let n=r[0],i=t._OrtEndProfiling(n);i===0&&je("Can't get an profile file name."),t._OrtFree(i)},R2=e=>{let t=[];for(let r of e){let n=r[2];!Array.isArray(n)&&"buffer"in n&&t.push(n.buffer)}return t}}),Lx=ia((e,t)=>{t.exports='/*!\n * ONNX Runtime Web v1.18.0\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n"use strict";(()=>{var ao=Object.defineProperty;var nl=Object.getOwnPropertyDescriptor;var ol=Object.getOwnPropertyNames;var il=Object.prototype.hasOwnProperty;var Y=(e,t)=>()=>(e&&(t=e(e=0)),t);var Wr=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),gn=(e,t)=>{for(var r in t)ao(e,r,{get:t[r],enumerable:!0})},al=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of ol(t))!il.call(e,i)&&i!==r&&ao(e,i,{get:()=>t[i],enumerable:!(o=nl(t,i))||o.enumerable});return e};var wr=e=>al(ao({},"__esModule",{value:!0}),e);var so={};gn(so,{createReadStream:()=>Ai,readFile:()=>sl,readFileSync:()=>ul});var sl,ul,Ai,uo=Y(()=>{sl=void 0,ul=void 0,Ai=void 0});var lo={};gn(lo,{join:()=>dl});var dl,co=Y(()=>{dl=void 0});var Ei=Wr((Ti,po)=>{"use strict";var Ii=(()=>{var e=typeof document<"u"?document.currentScript?.src:void 0;return typeof __filename<"u"&&(e||=__filename),function(t={}){var r=t,o,i,u=new Promise((s,m)=>{o=s,i=m});r.mountExternalData=(s,m)=>{(r.eb||(r.eb=new Map)).set(s,m)},r.unmountExternalData=()=>{delete r.eb};let a=()=>{let s=(g,$,T)=>(...B)=>{let H=dt,q=$?.();B=g(...B);let te=$?.();return q!==te&&(g=te,T(q),$=T=null),dt!=H?tn():B},m=g=>async(...$)=>{try{if(r.cb)throw Error("Session already started");let T=r.cb={xb:$[0],errors:[]},B=await g(...$);if(r.cb!==T)throw Error("Session mismatch");r.kb?.flush();let H=T.errors;if(0te),0r._OrtCreateSession,g=>r._OrtCreateSession=g),r._OrtRun=m(s(r._OrtRun,()=>r._OrtRun,g=>r._OrtRun=g)),r._OrtRunWithBinding=m(s(r._OrtRunWithBinding,()=>r._OrtRunWithBinding,g=>r._OrtRunWithBinding=g)),r._OrtBindInput=s(r._OrtBindInput,()=>r._OrtBindInput,g=>r._OrtBindInput=g),a=void 0};r.jsepInit=(s,m)=>{if(a?.(),s==="webgpu"){[r.kb,r.pb,r.tb,r.lb,r.sb,r.Ra,r.ub,r.wb,r.qb,r.rb,r.vb]=m;let g=r.kb;r.jsepRegisterBuffer=($,T,B,H)=>g.registerBuffer($,T,B,H),r.jsepGetBuffer=$=>g.getBuffer($),r.jsepCreateDownloader=($,T,B)=>g.createDownloader($,T,B),r.jsepOnReleaseSession=$=>{g.onReleaseSession($)},r.jsepOnRunStart=$=>g.onRunStart($)}};var c=Object.assign({},r),p="./this.program",h=(s,m)=>{throw m},d=typeof window=="object",y=typeof importScripts=="function",w=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",_="",v,S,A;if(w){var I=(uo(),wr(so)),x=(co(),wr(lo));_=y?x.dirname(_)+"/":__dirname+"/",v=(s,m)=>(s=Ke(s)?new URL(s):x.normalize(s),I.readFileSync(s,m?void 0:"utf8")),A=s=>(s=v(s,!0),s.buffer||(s=new Uint8Array(s)),s),S=(s,m,g,$=!0)=>{s=Ke(s)?new URL(s):x.normalize(s),I.readFile(s,$?void 0:"utf8",(T,B)=>{T?g(T):m($?B.buffer:B)})},!r.thisProgram&&1{throw process.exitCode=s,m}}else(d||y)&&(y?_=self.location.href:typeof document<"u"&&document.currentScript&&(_=document.currentScript.src),e&&(_=e),_.startsWith("blob:")?_="":_=_.substr(0,_.replace(/[?#].*/,"").lastIndexOf("/")+1),v=s=>{var m=new XMLHttpRequest;return m.open("GET",s,!1),m.send(null),m.responseText},y&&(A=s=>{var m=new XMLHttpRequest;return m.open("GET",s,!1),m.responseType="arraybuffer",m.send(null),new Uint8Array(m.response)}),S=(s,m,g)=>{var $=new XMLHttpRequest;$.open("GET",s,!0),$.responseType="arraybuffer",$.onload=()=>{$.status==200||$.status==0&&$.response?m($.response):g()},$.onerror=g,$.send(null)});var E=console.log.bind(console),P=console.error.bind(console);Object.assign(r,c),c=null;var O,R=!1,L,N,K,Q,he,W,se,Ce,We,ee,ae;function Ae(){var s=O.buffer;r.HEAP8=N=new Int8Array(s),r.HEAP16=Q=new Int16Array(s),r.HEAPU8=K=new Uint8Array(s),r.HEAPU16=he=new Uint16Array(s),r.HEAP32=W=new Int32Array(s),r.HEAPU32=se=new Uint32Array(s),r.HEAPF32=Ce=new Float32Array(s),r.HEAPF64=ae=new Float64Array(s),r.HEAP64=We=new BigInt64Array(s),r.HEAPU64=ee=new BigUint64Array(s)}var me=[],ie=[],ue=[],le=0,qe=null,G=null;function ne(s){throw s="Aborted("+s+")",P(s),R=!0,L=1,s=new WebAssembly.RuntimeError(s+". Build with -sASSERTIONS for more info."),i(s),s}var xe=s=>s.startsWith("data:application/octet-stream;base64,"),Ke=s=>s.startsWith("file://"),Be;if(Be="ort-wasm-simd.wasm",!xe(Be)){var Ge=Be;Be=r.locateFile?r.locateFile(Ge,_):_+Ge}function Ut(s){if(A)return A(s);throw"both async and sync fetching of the wasm failed"}function Ne(s){if(d||y){if(typeof fetch=="function"&&!Ke(s))return fetch(s,{credentials:"same-origin"}).then(m=>{if(!m.ok)throw`failed to load wasm binary file at \'${s}\'`;return m.arrayBuffer()}).catch(()=>Ut(s));if(S)return new Promise((m,g)=>{S(s,$=>m(new Uint8Array($)),g)})}return Promise.resolve().then(()=>Ut(s))}function Ye(s,m,g){return Ne(s).then($=>WebAssembly.instantiate($,m)).then(g,$=>{P(`failed to asynchronously prepare wasm: ${$}`),ne($)})}function mt(s,m){var g=Be;return typeof WebAssembly.instantiateStreaming!="function"||xe(g)||Ke(g)||w||typeof fetch!="function"?Ye(g,s,m):fetch(g,{credentials:"same-origin"}).then($=>WebAssembly.instantiateStreaming($,s).then(m,function(T){return P(`wasm streaming compile failed: ${T}`),P("falling back to ArrayBuffer instantiation"),Ye(g,s,m)}))}var Rt={824920:(s,m,g,$)=>{if(typeof r>"u"||!r.eb)return 1;if(s=je(s>>>0),s.startsWith("./")&&(s=s.substring(2)),s=r.eb.get(s),!s)return 2;if(m>>>=0,g>>>=0,m+g>s.byteLength)return 3;try{return K.set(s.subarray(m,m+g),$>>>0>>>0),0}catch{return 4}},825421:()=>{r.qb()},825452:()=>{r.rb()},825481:()=>{r.vb()},825506:s=>r.pb(s),825539:s=>r.tb(s),825571:(s,m,g)=>{r.lb(s,m,g,!0)},825610:(s,m,g)=>{r.lb(s,m,g)},825643:s=>{r.Ra("Abs",s,void 0)},825694:s=>{r.Ra("Neg",s,void 0)},825745:s=>{r.Ra("Floor",s,void 0)},825798:s=>{r.Ra("Ceil",s,void 0)},825850:s=>{r.Ra("Reciprocal",s,void 0)},825908:s=>{r.Ra("Sqrt",s,void 0)},825960:s=>{r.Ra("Exp",s,void 0)},826011:s=>{r.Ra("Erf",s,void 0)},826062:s=>{r.Ra("Sigmoid",s,void 0)},826117:(s,m,g)=>{r.Ra("HardSigmoid",s,{alpha:m,beta:g})},826196:s=>{r.Ra("Log",s,void 0)},826247:s=>{r.Ra("Sin",s,void 0)},826298:s=>{r.Ra("Cos",s,void 0)},826349:s=>{r.Ra("Tan",s,void 0)},826400:s=>{r.Ra("Asin",s,void 0)},826452:s=>{r.Ra("Acos",s,void 0)},826504:s=>{r.Ra("Atan",s,void 0)},826556:s=>{r.Ra("Sinh",s,void 0)},826608:s=>{r.Ra("Cosh",s,void 0)},826660:s=>{r.Ra("Asinh",s,void 0)},826713:s=>{r.Ra("Acosh",s,void 0)},826766:s=>{r.Ra("Atanh",s,void 0)},826819:s=>{r.Ra("Tanh",s,void 0)},826871:s=>{r.Ra("Not",s,void 0)},826922:(s,m,g)=>{r.Ra("Clip",s,{min:m,max:g})},826991:s=>{r.Ra("Clip",s,void 0)},827043:(s,m)=>{r.Ra("Elu",s,{alpha:m})},827101:s=>{r.Ra("Relu",s,void 0)},827153:(s,m)=>{r.Ra("LeakyRelu",s,{alpha:m})},827217:(s,m)=>{r.Ra("ThresholdedRelu",s,{alpha:m})},827287:(s,m)=>{r.Ra("Cast",s,{to:m})},827345:s=>{r.Ra("Add",s,void 0)},827396:s=>{r.Ra("Sub",s,void 0)},827447:s=>{r.Ra("Mul",s,void 0)},827498:s=>{r.Ra("Div",s,void 0)},827549:s=>{r.Ra("Pow",s,void 0)},827600:s=>{r.Ra("Equal",s,void 0)},827653:s=>{r.Ra("Greater",s,void 0)},827708:s=>{r.Ra("GreaterOrEqual",s,void 0)},827770:s=>{r.Ra("Less",s,void 0)},827822:s=>{r.Ra("LessOrEqual",s,void 0)},827881:(s,m,g,$,T)=>{r.Ra("ReduceMean",s,{keepDims:!!m,noopWithEmptyAxes:!!g,axes:$?Array.from(W.subarray($>>>0,T>>>0)):[]})},828040:(s,m,g,$,T)=>{r.Ra("ReduceMax",s,{keepDims:!!m,noopWithEmptyAxes:!!g,axes:$?Array.from(W.subarray($>>>0,T>>>0)):[]})},828198:(s,m,g,$,T)=>{r.Ra("ReduceMin",s,{keepDims:!!m,noopWithEmptyAxes:!!g,axes:$?Array.from(W.subarray($>>>0,T>>>0)):[]})},828356:(s,m,g,$,T)=>{r.Ra("ReduceProd",s,{keepDims:!!m,noopWithEmptyAxes:!!g,axes:$?Array.from(W.subarray($>>>0,T>>>0)):[]})},828515:(s,m,g,$,T)=>{r.Ra("ReduceSum",s,{keepDims:!!m,noopWithEmptyAxes:!!g,axes:$?Array.from(W.subarray($>>>0,T>>>0)):[]})},828673:(s,m,g,$,T)=>{r.Ra("ReduceL1",s,{keepDims:!!m,noopWithEmptyAxes:!!g,axes:$?Array.from(W.subarray($>>>0,T>>>0)):[]})},828830:(s,m,g,$,T)=>{r.Ra("ReduceL2",s,{keepDims:!!m,noopWithEmptyAxes:!!g,axes:$?Array.from(W.subarray($>>>0,T>>>0)):[]})},828987:(s,m,g,$,T)=>{r.Ra("ReduceLogSum",s,{keepDims:!!m,noopWithEmptyAxes:!!g,axes:$?Array.from(W.subarray($>>>0,T>>>0)):[]})},829148:(s,m,g,$,T)=>{r.Ra("ReduceSumSquare",s,{keepDims:!!m,noopWithEmptyAxes:!!g,axes:$?Array.from(W.subarray($>>>0,T>>>0)):[]})},829312:(s,m,g,$,T)=>{r.Ra("ReduceLogSumExp",s,{keepDims:!!m,noopWithEmptyAxes:!!g,axes:$?Array.from(W.subarray($>>>0,T>>>0)):[]})},829476:s=>{r.Ra("Where",s,void 0)},829529:(s,m,g)=>{r.Ra("Transpose",s,{perm:m?Array.from(W.subarray(m>>>0,g>>>0)):[]})},829637:(s,m,g,$)=>{r.Ra("DepthToSpace",s,{blocksize:m,mode:je(g),format:$?"NHWC":"NCHW"})},829770:(s,m,g,$)=>{r.Ra("DepthToSpace",s,{blocksize:m,mode:je(g),format:$?"NHWC":"NCHW"})},829903:(s,m,g,$,T,B,H,q,te,X,de,Ee,Oe,D,be)=>{r.Ra("ConvTranspose",s,{format:te?"NHWC":"NCHW",autoPad:m,dilations:[g],group:$,kernelShape:[T],pads:[B,H],strides:[q],wIsConst:()=>!!N[X>>>0],outputPadding:de?Array.from(W.subarray(de>>>0,Ee>>>0)):[],outputShape:Oe?Array.from(W.subarray(Oe>>>0,D>>>0)):[],activation:je(be)})},830304:(s,m,g,$,T,B,H,q,te,X,de,Ee,Oe,D)=>{r.Ra("ConvTranspose",s,{format:q?"NHWC":"NCHW",autoPad:m,dilations:Array.from(W.subarray(g>>>0,(g>>>0)+2>>>0)),group:$,kernelShape:Array.from(W.subarray(T>>>0,(T>>>0)+2>>>0)),pads:Array.from(W.subarray(B>>>0,(B>>>0)+4>>>0)),strides:Array.from(W.subarray(H>>>0,(H>>>0)+2>>>0)),wIsConst:()=>!!N[te>>>0],outputPadding:X?Array.from(W.subarray(X>>>0,de>>>0)):[],outputShape:Ee?Array.from(W.subarray(Ee>>>0,Oe>>>0)):[],activation:je(D)})},830869:(s,m,g,$,T,B,H,q,te,X,de,Ee,Oe,D,be)=>{r.Ra("ConvTranspose",s,{format:te?"NHWC":"NCHW",autoPad:m,dilations:[g],group:$,kernelShape:[T],pads:[B,H],strides:[q],wIsConst:()=>!!N[X>>>0],outputPadding:de?Array.from(W.subarray(de>>>0,Ee>>>0)):[],outputShape:Oe?Array.from(W.subarray(Oe>>>0,D>>>0)):[],activation:je(be)})},831270:(s,m,g,$,T,B,H,q,te,X,de,Ee,Oe,D)=>{r.Ra("ConvTranspose",s,{format:q?"NHWC":"NCHW",autoPad:m,dilations:Array.from(W.subarray(g>>>0,(g>>>0)+2>>>0)),group:$,kernelShape:Array.from(W.subarray(T>>>0,(T>>>0)+2>>>0)),pads:Array.from(W.subarray(B>>>0,(B>>>0)+4>>>0)),strides:Array.from(W.subarray(H>>>0,(H>>>0)+2>>>0)),wIsConst:()=>!!N[te>>>0],outputPadding:X?Array.from(W.subarray(X>>>0,de>>>0)):[],outputShape:Ee?Array.from(W.subarray(Ee>>>0,Oe>>>0)):[],activation:je(D)})},831835:(s,m)=>{r.Ra("GlobalAveragePool",s,{format:m?"NHWC":"NCHW"})},831926:(s,m,g,$,T,B,H,q,te,X,de,Ee,Oe,D,be,Ie)=>{r.Ra("AveragePool",s,{format:Ie?"NHWC":"NCHW",auto_pad:m,ceil_mode:g,count_include_pad:$,storage_order:T,dilations:[B,H],kernel_shape:[q,te],pads:[X,de,Ee,Oe],strides:[D,be]})},832210:(s,m)=>{r.Ra("GlobalAveragePool",s,{format:m?"NHWC":"NCHW"})},832301:(s,m,g,$,T,B,H,q,te,X,de,Ee,Oe,D,be,Ie)=>{r.Ra("AveragePool",s,{format:Ie?"NHWC":"NCHW",auto_pad:m,ceil_mode:g,count_include_pad:$,storage_order:T,dilations:[B,H],kernel_shape:[q,te],pads:[X,de,Ee,Oe],strides:[D,be]})},832585:(s,m)=>{r.Ra("GlobalMaxPool",s,{format:m?"NHWC":"NCHW"})},832672:(s,m,g,$,T,B,H,q,te,X,de,Ee,Oe,D,be,Ie)=>{r.Ra("MaxPool",s,{format:Ie?"NHWC":"NCHW",auto_pad:m,ceil_mode:g,count_include_pad:$,storage_order:T,dilations:[B,H],kernel_shape:[q,te],pads:[X,de,Ee,Oe],strides:[D,be]})},832952:(s,m)=>{r.Ra("GlobalMaxPool",s,{format:m?"NHWC":"NCHW"})},833039:(s,m,g,$,T,B,H,q,te,X,de,Ee,Oe,D,be,Ie)=>{r.Ra("MaxPool",s,{format:Ie?"NHWC":"NCHW",auto_pad:m,ceil_mode:g,count_include_pad:$,storage_order:T,dilations:[B,H],kernel_shape:[q,te],pads:[X,de,Ee,Oe],strides:[D,be]})},833319:(s,m,g,$,T)=>{r.Ra("Gemm",s,{alpha:m,beta:g,transA:$,transB:T})},833423:s=>{r.Ra("MatMul",s,void 0)},833477:(s,m,g,$)=>{r.Ra("ArgMax",s,{keepDims:!!m,selectLastIndex:!!g,axis:$})},833585:(s,m,g,$)=>{r.Ra("ArgMin",s,{keepDims:!!m,selectLastIndex:!!g,axis:$})},833693:(s,m)=>{r.Ra("Softmax",s,{axis:m})},833756:(s,m)=>{r.Ra("Concat",s,{axis:m})},833816:(s,m,g,$,T)=>{r.Ra("Split",s,{axis:m,numOutputs:g,splitSizes:$?Array.from(W.subarray($>>>0,T>>>0)):[]})},833956:s=>{r.Ra("Expand",s,void 0)},834010:(s,m)=>{r.Ra("Gather",s,{axis:Number(m)})},834081:(s,m)=>{r.Ra("GatherElements",s,{axis:Number(m)})},834160:(s,m,g,$,T,B,H,q,te,X,de)=>{r.Ra("Resize",s,{antialias:m,axes:g?Array.from(W.subarray(g>>>0,$>>>0)):[],coordinateTransformMode:je(T),cubicCoeffA:B,excludeOutside:H,extrapolationValue:q,keepAspectRatioPolicy:je(te),mode:je(X),nearestMode:je(de)})},834506:(s,m,g,$,T,B,H)=>{r.Ra("Slice",s,{starts:m?Array.from(W.subarray(m>>>0,g>>>0)):[],ends:$?Array.from(W.subarray($>>>0,T>>>0)):[],axes:B?Array.from(W.subarray(B>>>0,H>>>0)):[]})},834722:s=>{r.Ra("Tile",s,void 0)},834774:(s,m,g,$)=>{r.Ra("LayerNormalization",s,{axis:m,epsilon:g,simplified:!!$})},834885:(s,m,g)=>{r.Ra("InstanceNormalization",s,{epsilon:m,format:g?"NHWC":"NCHW"})},834999:(s,m,g)=>{r.Ra("InstanceNormalization",s,{epsilon:m,format:g?"NHWC":"NCHW"})},835113:s=>{r.Ra("Range",s,void 0)},835166:(s,m)=>{r.Ra("Einsum",s,{equation:je(m)})},835247:(s,m,g,$,T)=>{r.Ra("Pad",s,{mode:m,value:g,pads:$?Array.from(W.subarray($>>>0,T>>>0)):[]})},835374:(s,m,g,$,T,B)=>{r.Ra("BatchNormalization",s,{epsilon:m,momentum:g,spatial:!!T,trainingMode:!!$,format:B?"NHWC":"NCHW"})},835543:(s,m,g,$,T,B)=>{r.Ra("BatchNormalization",s,{epsilon:m,momentum:g,spatial:!!T,trainingMode:!!$,format:B?"NHWC":"NCHW"})},835712:(s,m,g)=>{r.Ra("CumSum",s,{exclusive:Number(m),reverse:Number(g)})},835809:(s,m,g,$,T,B,H,q,te)=>{r.Ra("Attention",s,{numHeads:m,isUnidirectional:g,maskFilterValue:$,scale:T,doRotary:B,qkvHiddenSizes:H?Array.from(W.subarray(Number(q)>>>0,Number(q)+H>>>0)):[],pastPresentShareBuffer:!!te})},836081:s=>{r.Ra("BiasAdd",s,void 0)},836136:s=>{r.Ra("BiasSplitGelu",s,void 0)},836197:s=>{r.Ra("FastGelu",s,void 0)},836253:(s,m,g,$,T,B,H,q,te,X,de,Ee,Oe)=>{r.Ra("Conv",s,{format:te?"NHWC":"NCHW",auto_pad:m,dilations:[g],group:$,kernel_shape:[T],pads:B?Array.from(W.subarray(B>>>0,H>>>0)):[],strides:[q],w_is_const:()=>!!N[X>>>0],activation:je(de),activation_params:Ee?Array.from(Ce.subarray(Ee>>>0,Oe>>>0)):[]})},836623:(s,m,g,$,T,B,H,q,te,X,de,Ee,Oe,D,be,Ie)=>{r.Ra("Conv",s,{format:Ee?"NHWC":"NCHW",auto_pad:m,dilations:[g,$],group:T,kernel_shape:[B,H],pads:q?Array.from(W.subarray(q>>>0,te>>>0)):[],strides:[X,de],w_is_const:()=>!!N[Oe>>>0],activation:je(D),activation_params:be?Array.from(Ce.subarray(be>>>0,Ie>>>0)):[]})},837014:s=>{r.Ra("Gelu",s,void 0)},837066:(s,m,g,$,T,B)=>{r.Ra("MatMulNBits",s,{k:m,n:g,accuracyLevel:$,bits:T,blockSize:B})},837193:(s,m,g,$,T,B)=>{r.Ra("MultiHeadAttention",s,{numHeads:m,isUnidirectional:g,maskFilterValue:$,scale:T,doRotary:B})},837352:(s,m,g,$,T)=>{r.Ra("RotaryEmbedding",s,{interleaved:!!m,numHeads:g,rotaryEmbeddingDim:$,scale:T})},837491:(s,m,g)=>{r.Ra("SkipLayerNormalization",s,{epsilon:m,simplified:!!g})},837593:(s,m,g)=>{r.Ra("SkipLayerNormalization",s,{epsilon:m,simplified:!!g})},837695:(s,m,g,$)=>{r.Ra("LayerNormalization",s,{axis:m,epsilon:g,simplified:!!$})},837806:s=>{r.ub(s)},837840:(s,m)=>r.wb(s,m,r.cb.xb,r.cb.errors)};function qt(s){this.name="ExitStatus",this.message=`Program terminated with exit(${s})`,this.status=s}class Vt{constructor(m){this.hb=m-24}}var sr=0,jt=0,xr=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,Kt=(s,m,g)=>{m>>>=0;var $=m+g;for(g=m;s[g]&&!(g>=$);)++g;if(16T?$+=String.fromCharCode(T):(T-=65536,$+=String.fromCharCode(55296|T>>10,56320|T&1023))}}else $+=String.fromCharCode(T)}return $},je=(s,m)=>(s>>>=0)?Kt(K,s,m):"",Wt=s=>{for(var m=0,g=0;g=$?m++:2047>=$?m+=2:55296<=$&&57343>=$?(m+=4,++g):m+=3}return m},at=(s,m,g,$)=>{if(g>>>=0,!(0<$))return 0;var T=g;$=g+$-1;for(var B=0;B=H){var q=s.charCodeAt(++B);H=65536+((H&1023)<<10)|q&1023}if(127>=H){if(g>=$)break;m[g++>>>0]=H}else{if(2047>=H){if(g+1>=$)break;m[g++>>>0]=192|H>>6}else{if(65535>=H){if(g+2>=$)break;m[g++>>>0]=224|H>>12}else{if(g+3>=$)break;m[g++>>>0]=240|H>>18,m[g++>>>0]=128|H>>12&63}m[g++>>>0]=128|H>>6&63}m[g++>>>0]=128|H&63}}return m[g>>>0]=0,g-T},Cr,ft=s=>{for(var m="";K[s>>>0];)m+=Cr[K[s++>>>0]];return m},ur={},Ar={},Ir={},st;function Tr(s,m,g={}){var $=m.name;if(!s)throw new st(`type "${$}" must have a positive integer typeid pointer`);if(Ar.hasOwnProperty(s)){if(g.nb)return;throw new st(`Cannot register type \'${$}\' twice`)}Ar[s]=m,delete Ir[s],ur.hasOwnProperty(s)&&(m=ur[s],delete ur[s],m.forEach(T=>T()))}function ht(s,m,g={}){if(!("argPackAdvance"in m))throw new TypeError("registerType registeredInstance requires argPackAdvance");return Tr(s,m,g)}var bt=(s,m,g)=>{switch(m){case 1:return g?$=>N[$>>>0]:$=>K[$>>>0];case 2:return g?$=>Q[$>>>1>>>0]:$=>he[$>>>1>>>0];case 4:return g?$=>W[$>>>2>>>0]:$=>se[$>>>2>>>0];case 8:return g?$=>We[$>>>3]:$=>ee[$>>>3];default:throw new TypeError(`invalid integer width (${m}): ${s}`)}},Er=[],Te=[];function dr(s){s>>>=0,9{if(!s)throw new st("Cannot use deleted val. handle = "+s);return Te[s]},ut=s=>{switch(s){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let m=Er.pop()||Te.length;return Te[m]=s,Te[m+1]=1,m}};function lr(s){return this.fromWireType(se[s>>>2>>>0])}var Fn={name:"emscripten::val",fromWireType:s=>{var m=Xe(s);return dr(s),m},toWireType:(s,m)=>ut(m),argPackAdvance:8,readValueFromPointer:lr,bb:null},ge=(s,m)=>{switch(m){case 4:return function(g){return this.fromWireType(Ce[g>>>2>>>0])};case 8:return function(g){return this.fromWireType(ae[g>>>3>>>0])};default:throw new TypeError(`invalid float width (${m}): ${s}`)}},Yt=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,jr=(s,m)=>{for(var g=s>>1,$=g+m/2;!(g>=$)&&he[g>>>0];)++g;if(g<<=1,32>>0,g>>>0));for(g="",$=0;!($>=m/2);++$){var T=Q[s+2*$>>>1>>>0];if(T==0)break;g+=String.fromCharCode(T)}return g},qn=(s,m,g)=>{if(g??=2147483647,2>g)return 0;g-=2;var $=m;g=g<2*s.length?g/2:s.length;for(var T=0;T>>1>>>0]=s.charCodeAt(T),m+=2;return Q[m>>>1>>>0]=0,m-$},Kr=s=>2*s.length,jn=(s,m)=>{for(var g=0,$="";!(g>=m/4);){var T=W[s+4*g>>>2>>>0];if(T==0)break;++g,65536<=T?(T-=65536,$+=String.fromCharCode(55296|T>>10,56320|T&1023)):$+=String.fromCharCode(T)}return $},Yr=(s,m,g)=>{if(m>>>=0,g??=2147483647,4>g)return 0;var $=m;g=$+g-4;for(var T=0;T=B){var H=s.charCodeAt(++T);B=65536+((B&1023)<<10)|H&1023}if(W[m>>>2>>>0]=B,m+=4,m+4>g)break}return W[m>>>2>>>0]=0,m-$},Zr=s=>{for(var m=0,g=0;g=$&&++g,m+=4}return m},cr=(s,m)=>{var g=Ar[s];if(g===void 0)throw s=Mr(s),g=ft(s),rt(s),new st(`${m} has unknown type ${g}`);return g},Pr=(s,m,g)=>{var $=[];return s=s.toWireType($,g),$.length&&(se[m>>>2>>>0]=ut($)),s},He=s=>{try{s()}catch(m){ne(m)}},Xr=s=>{if(!R)try{s();try{L=L=s=L,r.onExit?.(s),R=!0,h(s,new qt(s))}catch(m){m instanceof qt||m=="unwind"||h(1,m)}}catch(m){m instanceof qt||m=="unwind"||h(1,m)}};function Qr(){var s=pe,m={};for(let[g,$]of Object.entries(s))m[g]=typeof $=="function"?(...T)=>{Zt.push(g);try{return $(...T)}finally{R||(Zt.pop(),dt&>===1&&Zt.length===0&&(gt=0,He(dn),typeof Fibers<"u"&&Fibers.Db()))}}:$;return m}var gt=0,dt=null,Bt=0,Zt=[],kr={},Or={},Jr=0,pr=null,en=[];function tn(){return new Promise((s,m)=>{pr={resolve:s,reject:m}})}function rn(){var s=Nt(65548),m=s+12;se[s>>>2>>>0]=m,se[s+4>>>2>>>0]=m+65536,m=Zt[0];var g=kr[m];return g===void 0&&(g=Jr++,kr[m]=g,Or[g]=m),W[s+8>>>2>>>0]=g,s}function nn(s){if(!R){if(gt===0){var m=!1,g=!1;s(($=0)=>{if(!R&&(Bt=$,m=!0,g)){gt=2,He(()=>vt(dt)),typeof Browser<"u"&&Browser.ib.mb&&Browser.ib.resume(),$=!1;try{var T=(0,pe[Or[W[dt+8>>>2>>>0]]])()}catch(q){T=q,$=!0}var B=!1;if(!dt){var H=pr;H&&(pr=null,($?H.reject:H.resolve)(T),B=!0)}if($&&!B)throw T}}),g=!0,m||(gt=1,dt=rn(),typeof Browser<"u"&&Browser.ib.mb&&Browser.ib.pause(),He(()=>Jt(dt)))}else gt===2?(gt=0,He(ct),rt(dt),dt=null,en.forEach(Xr)):ne(`invalid state: ${gt}`);return Bt}}function Rr(s){return nn(m=>{s().then(m)})}var Xt=[],on={},nt=s=>{var m=on[s];return m===void 0?ft(s):m},mr=()=>typeof globalThis=="object"?globalThis:Function("return this")(),Br=s=>{var m=Xt.length;return Xt.push(s),m},Kn=(s,m)=>{for(var g=Array(s),$=0;$>>2>>>0],"parameter "+$);return g},wt=(s,m)=>Object.defineProperty(m,"name",{value:s});function Yn(s){var m=Function;if(!(m instanceof Function))throw new TypeError(`new_ called with constructor type ${typeof m} which is not a function`);var g=wt(m.name||"unknownFunctionName",function(){});return g.prototype=m.prototype,g=new g,s=m.apply(g,s),s instanceof Object?s:g}var Je=s=>s%4===0&&(s%100!==0||s%400===0),Dr=[0,31,60,91,121,152,182,213,244,274,305,335],fr=[0,31,59,90,120,151,181,212,243,273,304,334],lt=[],hr=(s,m)=>{lt.length=0;for(var g;g=K[s++>>>0];){var $=g!=105;$&=g!=112,m+=$&&m%8?4:0,lt.push(g==112?se[m>>>2>>>0]:g==106?We[m>>>3]:g==105?W[m>>>2>>>0]:ae[m>>>3>>>0]),m+=$?8:4}return lt},Qe={},ot=()=>{if(!Qt){var s={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",_:p||"./this.program"},m;for(m in Qe)Qe[m]===void 0?delete s[m]:s[m]=Qe[m];var g=[];for(m in s)g.push(`${m}=${s[m]}`);Qt=g}return Qt},Qt,Zn=[null,[],[]],an=[31,29,31,30,31,30,31,31,30,31,30,31],zr=[31,28,31,30,31,30,31,31,30,31,30,31];function Xn(s){var m=Array(Wt(s)+1);return at(s,m,0,m.length),m}function sn(s,m,g,$){function T(D,be,Ie){for(D=typeof D=="number"?D.toString():D||"";D.lengthMt?-1:0zt-D.getDate())be-=zt-D.getDate()+1,D.setDate(1),11>Ie?D.setMonth(Ie+1):(D.setMonth(0),D.setFullYear(D.getFullYear()+1));else{D.setDate(D.getDate()+be);break}}return Ie=new Date(D.getFullYear()+1,0,4),be=q(new Date(D.getFullYear(),0,4)),Ie=q(Ie),0>=H(be,D)?0>=H(Ie,D)?D.getFullYear()+1:D.getFullYear():D.getFullYear()-1}s>>>=0,m>>>=0,g>>>=0,$>>>=0;var X=se[$+40>>>2>>>0];$={Ab:W[$>>>2>>>0],zb:W[$+4>>>2>>>0],fb:W[$+8>>>2>>>0],jb:W[$+12>>>2>>>0],gb:W[$+16>>>2>>>0],ab:W[$+20>>>2>>>0],Va:W[$+24>>>2>>>0],$a:W[$+28>>>2>>>0],Cb:W[$+32>>>2>>>0],yb:W[$+36>>>2>>>0],Bb:X?je(X):""},g=je(g),X={"%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 de in X)g=g.replace(new RegExp(de,"g"),X[de]);var Ee="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),Oe="January February March April May June July August September October November December".split(" ");X={"%a":D=>Ee[D.Va].substring(0,3),"%A":D=>Ee[D.Va],"%b":D=>Oe[D.gb].substring(0,3),"%B":D=>Oe[D.gb],"%C":D=>B((D.ab+1900)/100|0,2),"%d":D=>B(D.jb,2),"%e":D=>T(D.jb,2," "),"%g":D=>te(D).toString().substring(2),"%G":te,"%H":D=>B(D.fb,2),"%I":D=>(D=D.fb,D==0?D=12:12{for(var be=0,Ie=0;Ie<=D.gb-1;be+=(Je(D.ab+1900)?an:zr)[Ie++]);return B(D.jb+be,3)},"%m":D=>B(D.gb+1,2),"%M":D=>B(D.zb,2),"%n":()=>`\n`,"%p":D=>0<=D.fb&&12>D.fb?"AM":"PM","%S":D=>B(D.Ab,2),"%t":()=>" ","%u":D=>D.Va||7,"%U":D=>B(Math.floor((D.$a+7-D.Va)/7),2),"%V":D=>{var be=Math.floor((D.$a+7-(D.Va+6)%7)/7);if(2>=(D.Va+371-D.$a-2)%7&&be++,be)be==53&&(Ie=(D.Va+371-D.$a)%7,Ie==4||Ie==3&&Je(D.ab)||(be=1));else{be=52;var Ie=(D.Va+7-D.$a-1)%7;(Ie==4||Ie==5&&Je(D.ab%400-1))&&be++}return B(be,2)},"%w":D=>D.Va,"%W":D=>B(Math.floor((D.$a+7-(D.Va+6)%7)/7),2),"%y":D=>(D.ab+1900).toString().substring(2),"%Y":D=>D.ab+1900,"%z":D=>{D=D.yb;var be=0<=D;return D=Math.abs(D)/60,(be?"+":"-")+("0000"+(D/60*100+D%60)).slice(-4)},"%Z":D=>D.Bb,"%%":()=>"%"},g=g.replace(/%%/g,"\\0\\0");for(de in X)g.includes(de)&&(g=g.replace(new RegExp(de,"g"),X[de]($)));return g=g.replace(/\\0\\0/g,"%"),de=Xn(g),de.length>m?0:(N.set(de,s>>>0),de.length-1)}for(var un=Array(256),gr=0;256>gr;++gr)un[gr]=String.fromCharCode(gr);Cr=un,st=r.BindingError=class extends Error{constructor(s){super(s),this.name="BindingError"}},r.InternalError=class extends Error{constructor(s){super(s),this.name="InternalError"}},Te.push(0,1,void 0,1,null,1,!0,1,!1,1),r.count_emval_handles=()=>Te.length/2-5-Er.length;var Qn={ia:function(s,m,g){return Rr(async()=>{await r.sb(s,m,g)})},a:function(s,m,g){s>>>=0;var $=new Vt(s);throw se[$.hb+16>>>2>>>0]=0,se[$.hb+4>>>2>>>0]=m>>>0,se[$.hb+8>>>2>>>0]=g>>>0,sr=s,jt++,sr},y:function(){return 0},ea:function(){},R:function(){},T:function(){},ga:function(){return 0},ca:function(){},Z:function(){},ba:function(){},G:function(){},S:function(){},P:function(){},da:function(){},Q:function(){},C:function(s,m,g){m=ft(m>>>0),ht(s>>>0,{name:m,fromWireType:$=>$,toWireType:function($,T){if(typeof T!="bigint"&&typeof T!="number")throw T===null?T="null":($=typeof T,T=$==="object"||$==="array"||$==="function"?T.toString():""+T),new TypeError(`Cannot convert "${T}" to ${this.name}`);return typeof T=="number"&&(T=BigInt(T)),T},argPackAdvance:8,readValueFromPointer:bt(m,g>>>0,m.indexOf("u")==-1),bb:null})},K:function(s,m,g,$){m=ft(m>>>0),ht(s>>>0,{name:m,fromWireType:function(T){return!!T},toWireType:function(T,B){return B?g:$},argPackAdvance:8,readValueFromPointer:function(T){return this.fromWireType(K[T>>>0])},bb:null})},J:function(s){return ht(s>>>0,Fn)},B:function(s,m,g){m=ft(m>>>0),ht(s>>>0,{name:m,fromWireType:$=>$,toWireType:($,T)=>T,argPackAdvance:8,readValueFromPointer:ge(m,g>>>0),bb:null})},s:function(s,m,g,$,T){if(s>>>=0,g>>>=0,m=ft(m>>>0),T===-1&&(T=4294967295),T=q=>q,$===0){var B=32-8*g;T=q=>q<>>B}var H=m.includes("unsigned")?function(q,te){return te>>>0}:function(q,te){return te};ht(s,{name:m,fromWireType:T,toWireType:H,argPackAdvance:8,readValueFromPointer:bt(m,g,$!==0),bb:null})},o:function(s,m,g){function $(B){return new T(N.buffer,se[B+4>>>2>>>0],se[B>>>2>>>0])}var T=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][m];g=ft(g>>>0),ht(s>>>0,{name:g,fromWireType:$,argPackAdvance:8,readValueFromPointer:$},{nb:!0})},D:function(s,m){m=ft(m>>>0);var g=m==="std::string";ht(s>>>0,{name:m,fromWireType:function($){var T=se[$>>>2>>>0],B=$+4;if(g)for(var H=B,q=0;q<=T;++q){var te=B+q;if(q==T||K[te>>>0]==0){if(H=je(H,te-H),X===void 0)var X=H;else X+=String.fromCharCode(0),X+=H;H=te+1}}else{for(X=Array(T),q=0;q>>0]);X=X.join("")}return rt($),X},toWireType:function($,T){T instanceof ArrayBuffer&&(T=new Uint8Array(T));var B=typeof T=="string";if(!(B||T instanceof Uint8Array||T instanceof Uint8ClampedArray||T instanceof Int8Array))throw new st("Cannot pass non-string to std::string");var H=g&&B?Wt(T):T.length,q=Nt(4+H+1),te=q+4;if(se[q>>>2>>>0]=H,g&&B)at(T,K,te,H+1);else if(B)for(B=0;B>>0]=X}else for(B=0;B>>0]=T[B];return $!==null&&$.push(rt,q),q},argPackAdvance:8,readValueFromPointer:lr,bb($){rt($)}})},x:function(s,m,g){if(m>>>=0,g>>>=0,g=ft(g),m===2)var $=jr,T=qn,B=Kr,H=q=>he[q>>>1>>>0];else m===4&&($=jn,T=Yr,B=Zr,H=q=>se[q>>>2>>>0]);ht(s>>>0,{name:g,fromWireType:q=>{for(var te=se[q>>>2>>>0],X,de=q+4,Ee=0;Ee<=te;++Ee){var Oe=q+4+Ee*m;(Ee==te||H(Oe)==0)&&(de=$(de,Oe-de),X===void 0?X=de:(X+=String.fromCharCode(0),X+=de),de=Oe+m)}return rt(q),X},toWireType:(q,te)=>{if(typeof te!="string")throw new st(`Cannot pass non-string to C++ string type ${g}`);var X=B(te),de=Nt(4+X+m);return se[de>>>2>>>0]=X/m,T(te,de+4,X+m),q!==null&&q.push(rt,de),de},argPackAdvance:8,readValueFromPointer:lr,bb(q){rt(q)}})},L:function(s,m){m=ft(m>>>0),ht(s>>>0,{ob:!0,name:m,argPackAdvance:0,fromWireType:()=>{},toWireType:()=>{}})},ha:()=>1,u:function(s,m,g){return m>>>=0,g>>>=0,s=Xe(s>>>0),m=cr(m,"emval::as"),Pr(m,g,s)},w:function(s){return s>>>=0,Rr(()=>(s=Xe(s),s.then(ut)))},n:function(s,m,g,$){return g>>>=0,$>>>=0,s=Xt[s>>>0],m=Xe(m>>>0),s(null,m,g,$)},j:function(s,m,g,$,T){return g>>>=0,$>>>=0,T>>>=0,s=Xt[s>>>0],m=Xe(m>>>0),g=nt(g),s(m,m[g],$,T)},b:dr,A:function(s,m){return m>>>=0,s=Xe(s>>>0),m=Xe(m),s==m},m:function(s){return s>>>=0,s===0?ut(mr()):(s=nt(s),ut(mr()[s]))},i:function(s,m,g){m=Kn(s,m>>>0);var $=m.shift();s--;var T=`return function (obj, func, destructorsRef, args) {\n`,B=0,H=[];g===0&&H.push("obj");for(var q=["retType"],te=[$],X=0;Xde.name).join(", ")}) => ${$.name}>`,Br(wt(g,s))},r:function(s,m){return m>>>=0,s=Xe(s>>>0),m=Xe(m),ut(s[m])},e:function(s){s>>>=0,9>>0);for(var m=Array(s.length),g=0;g>>0))},k:function(){return ut({})},h:function(s){s>>>=0;for(var m=Xe(s);m.length;){var g=m.pop();m.pop()(g)}dr(s)},g:function(s,m,g){m>>>=0,g>>>=0,s=Xe(s>>>0),m=Xe(m),g=Xe(g),s[m]=g},c:function(s,m){return m>>>=0,s=cr(s>>>0,"_emval_take_value"),s=s.readValueFromPointer(m),ut(s)},W:function(s,m){s=-9007199254740992>s||9007199254740992>>=0,s=new Date(1e3*s),W[m>>>2>>>0]=s.getUTCSeconds(),W[m+4>>>2>>>0]=s.getUTCMinutes(),W[m+8>>>2>>>0]=s.getUTCHours(),W[m+12>>>2>>>0]=s.getUTCDate(),W[m+16>>>2>>>0]=s.getUTCMonth(),W[m+20>>>2>>>0]=s.getUTCFullYear()-1900,W[m+24>>>2>>>0]=s.getUTCDay(),W[m+28>>>2>>>0]=(s.getTime()-Date.UTC(s.getUTCFullYear(),0,1,0,0,0,0))/864e5|0},X:function(s,m){s=-9007199254740992>s||9007199254740992>>=0,s=new Date(1e3*s),W[m>>>2>>>0]=s.getSeconds(),W[m+4>>>2>>>0]=s.getMinutes(),W[m+8>>>2>>>0]=s.getHours(),W[m+12>>>2>>>0]=s.getDate(),W[m+16>>>2>>>0]=s.getMonth(),W[m+20>>>2>>>0]=s.getFullYear()-1900,W[m+24>>>2>>>0]=s.getDay(),W[m+28>>>2>>>0]=(Je(s.getFullYear())?Dr:fr)[s.getMonth()]+s.getDate()-1|0,W[m+36>>>2>>>0]=-(60*s.getTimezoneOffset());var g=new Date(s.getFullYear(),6,1).getTimezoneOffset(),$=new Date(s.getFullYear(),0,1).getTimezoneOffset();W[m+32>>>2>>>0]=(g!=$&&s.getTimezoneOffset()==Math.min($,g))|0},Y:function(s){s>>>=0;var m=new Date(W[s+20>>>2>>>0]+1900,W[s+16>>>2>>>0],W[s+12>>>2>>>0],W[s+8>>>2>>>0],W[s+4>>>2>>>0],W[s>>>2>>>0],0),g=W[s+32>>>2>>>0],$=m.getTimezoneOffset(),T=new Date(m.getFullYear(),6,1).getTimezoneOffset(),B=new Date(m.getFullYear(),0,1).getTimezoneOffset(),H=Math.min(B,T);return 0>g?W[s+32>>>2>>>0]=+(T!=B&&H==$):0>>2>>>0]=m.getDay(),W[s+28>>>2>>>0]=(Je(m.getFullYear())?Dr:fr)[m.getMonth()]+m.getDate()-1|0,W[s>>>2>>>0]=m.getSeconds(),W[s+4>>>2>>>0]=m.getMinutes(),W[s+8>>>2>>>0]=m.getHours(),W[s+12>>>2>>>0]=m.getDate(),W[s+16>>>2>>>0]=m.getMonth(),W[s+20>>>2>>>0]=m.getYear(),s=m.getTime(),BigInt(isNaN(s)?-1:s/1e3)},U:function(){return-52},V:function(){},N:function(s,m,g,$){g>>>=0,$>>>=0;var T=new Date().getFullYear(),B=new Date(T,0,1),H=new Date(T,6,1);T=B.getTimezoneOffset();var q=H.getTimezoneOffset();se[s>>>0>>>2>>>0]=60*Math.max(T,q),W[m>>>0>>>2>>>0]=+(T!=q),s=te=>te.toLocaleTimeString(void 0,{hour12:!1,timeZoneName:"short"}).split(" ")[1],B=s(B),H=s(H),q{ne("")},d:function(s,m,g){return s>>>=0,m=hr(m>>>0,g>>>0),Rt[s](...m)},I:function(s,m,g){return s>>>=0,m=hr(m>>>0,g>>>0),Rt[s](...m)},H:()=>Date.now(),O:function(){return 4294901760},q:()=>performance.now(),M:function(s){s>>>=0;var m=K.length;if(4294901760=g;g*=2){var $=m*(1+.2/g);$=Math.min($,s+100663296);var T=Math;$=Math.max(s,$);e:{T=(T.min.call(T,4294901760,$+(65536-$%65536)%65536)-O.buffer.byteLength+65535)/65536;try{O.grow(T),Ae();var B=1;break e}catch{}B=void 0}if(B)return!0}return!1},$:function(s,m){s>>>=0,m>>>=0;var g=0;return ot().forEach(($,T)=>{var B=m+g;for(T=se[s+4*T>>>2>>>0]=B,B=0;B<$.length;++B)N[T++>>>0]=$.charCodeAt(B);N[T>>>0]=0,g+=$.length+1}),0},aa:function(s,m){s>>>=0,m>>>=0;var g=ot();se[s>>>2>>>0]=g.length;var $=0;return g.forEach(T=>$+=T.length+1),se[m>>>2>>>0]=$,0},z:()=>52,F:function(){return 52},_:function(){return 70},E:function(s,m,g,$){m>>>=0,g>>>=0,$>>>=0;for(var T=0,B=0;B>>2>>>0],q=se[m+4>>>2>>>0];m+=8;for(var te=0;te>>0],de=Zn[s];X===0||X===10?((s===1?E:P)(Kt(de,0)),de.length=0):de.push(X)}T+=q}return se[$>>>2>>>0]=T,0},fa:sn,p:function(s,m,g,$){return sn(s>>>0,m>>>0,g>>>0,$>>>0)}},pe=function(){function s(g){return pe=g.exports,pe=Qr(),pe=ln(),O=pe.ja,Ae(),ie.unshift(pe.ka),le--,le==0&&(qe!==null&&(clearInterval(qe),qe=null),G&&(g=G,G=null,g())),pe}var m={a:Qn};if(le++,r.instantiateWasm)try{return r.instantiateWasm(m,s)}catch(g){P(`Module.instantiateWasm callback failed with error: ${g}`),i(g)}return mt(m,function(g){s(g.instance)}).catch(i),{}}(),Mr=s=>(Mr=pe.la)(s);r._OrtInit=(s,m)=>(r._OrtInit=pe.ma)(s,m),r._OrtGetLastError=(s,m)=>(r._OrtGetLastError=pe.na)(s,m),r._OrtCreateSessionOptions=(s,m,g,$,T,B,H,q,te,X)=>(r._OrtCreateSessionOptions=pe.oa)(s,m,g,$,T,B,H,q,te,X),r._OrtAppendExecutionProvider=(s,m)=>(r._OrtAppendExecutionProvider=pe.pa)(s,m),r._OrtAddFreeDimensionOverride=(s,m,g)=>(r._OrtAddFreeDimensionOverride=pe.qa)(s,m,g),r._OrtAddSessionConfigEntry=(s,m,g)=>(r._OrtAddSessionConfigEntry=pe.ra)(s,m,g),r._OrtReleaseSessionOptions=s=>(r._OrtReleaseSessionOptions=pe.sa)(s),r._OrtCreateSession=(s,m,g)=>(r._OrtCreateSession=pe.ta)(s,m,g),r._OrtReleaseSession=s=>(r._OrtReleaseSession=pe.ua)(s),r._OrtGetInputOutputCount=(s,m,g)=>(r._OrtGetInputOutputCount=pe.va)(s,m,g),r._OrtGetInputName=(s,m)=>(r._OrtGetInputName=pe.wa)(s,m),r._OrtGetOutputName=(s,m)=>(r._OrtGetOutputName=pe.xa)(s,m),r._OrtFree=s=>(r._OrtFree=pe.ya)(s),r._OrtCreateTensor=(s,m,g,$,T,B)=>(r._OrtCreateTensor=pe.za)(s,m,g,$,T,B),r._OrtGetTensorData=(s,m,g,$,T)=>(r._OrtGetTensorData=pe.Aa)(s,m,g,$,T),r._OrtReleaseTensor=s=>(r._OrtReleaseTensor=pe.Ba)(s),r._OrtCreateRunOptions=(s,m,g,$)=>(r._OrtCreateRunOptions=pe.Ca)(s,m,g,$),r._OrtAddRunConfigEntry=(s,m,g)=>(r._OrtAddRunConfigEntry=pe.Da)(s,m,g),r._OrtReleaseRunOptions=s=>(r._OrtReleaseRunOptions=pe.Ea)(s),r._OrtCreateBinding=s=>(r._OrtCreateBinding=pe.Fa)(s),r._OrtBindInput=(s,m,g)=>(r._OrtBindInput=pe.Ga)(s,m,g),r._OrtBindOutput=(s,m,g,$)=>(r._OrtBindOutput=pe.Ha)(s,m,g,$),r._OrtClearBoundOutputs=s=>(r._OrtClearBoundOutputs=pe.Ia)(s),r._OrtReleaseBinding=s=>(r._OrtReleaseBinding=pe.Ja)(s),r._OrtRunWithBinding=(s,m,g,$,T)=>(r._OrtRunWithBinding=pe.Ka)(s,m,g,$,T),r._OrtRun=(s,m,g,$,T,B,H,q)=>(r._OrtRun=pe.La)(s,m,g,$,T,B,H,q),r._OrtEndProfiling=s=>(r._OrtEndProfiling=pe.Ma)(s),r._JsepOutput=(s,m,g)=>(r._JsepOutput=pe.Na)(s,m,g),r._JsepGetNodeName=s=>(r._JsepGetNodeName=pe.Oa)(s);var Nt=r._malloc=s=>(Nt=r._malloc=pe.Pa)(s),rt=r._free=s=>(rt=r._free=pe.Qa)(s),yr=s=>(yr=pe.Sa)(s),br=s=>(br=pe.Ta)(s),Ur=()=>(Ur=pe.Ua)(),Jt=s=>(Jt=pe.Wa)(s),dn=()=>(dn=pe.Xa)(),vt=s=>(vt=pe.Ya)(s),ct=()=>(ct=pe.Za)();r.___start_em_js=837952,r.___stop_em_js=838113;function ln(){var s=pe;s=Object.assign({},s);var m=g=>$=>g($)>>>0;return s.la=m(s.la),s.Pa=m(s.Pa),s.Ta=m(s.Ta),s.Ua=(g=>()=>g()>>>0)(s.Ua),s}r.stackSave=()=>Ur(),r.stackRestore=s=>yr(s),r.stackAlloc=s=>br(s),r.UTF8ToString=je,r.stringToUTF8=(s,m,g)=>at(s,K,m,g),r.lengthBytesUTF8=Wt;var Dt;G=function s(){Dt||Vr(),Dt||(G=s)};function Vr(){if(!(0Ii)});var Pi=Wr(()=>{});var ki=Wr(()=>{});var Oi={};gn(Oi,{cpus:()=>ll});var ll,Ri=Y(()=>{ll=void 0});var zi=Wr((Di,mo)=>{"use strict";var Bi=(()=>{var e=typeof document<"u"?document.currentScript?.src:void 0;return typeof __filename<"u"&&(e||=__filename),function(t={}){function r(){return ae.buffer!=ue.buffer&&Ne(),ue}function o(){return ae.buffer!=ue.buffer&&Ne(),le}function i(){return ae.buffer!=ue.buffer&&Ne(),qe}function u(){return ae.buffer!=ue.buffer&&Ne(),G}function a(){return ae.buffer!=ue.buffer&&Ne(),ne}function c(){return ae.buffer!=ue.buffer&&Ne(),xe}function p(){return ae.buffer!=ue.buffer&&Ne(),Ke}function h(){return ae.buffer!=ue.buffer&&Ne(),Ut}var d=t,y,w,_=new Promise((n,l)=>{y=n,w=l});d.mountExternalData=(n,l)=>{(d.Db||(d.Db=new Map)).set(n,l)},d.unmountExternalData=()=>{delete d.Db};let v=()=>{let n=(f,b,C)=>(...k)=>{let V=ct,F=b?.();k=f(...k);let re=b?.();return F!==re&&(f=re,C(F),b=C=null),ct!=V?T():k},l=f=>async(...b)=>{try{if(d.Cb)throw Error("Session already started");let C=d.Cb={ec:b[0],errors:[]},k=await f(...b);if(d.Cb!==C)throw Error("Session mismatch");d.Kb?.flush();let V=C.errors;if(0re),0d._OrtCreateSession,f=>d._OrtCreateSession=f),d._OrtRun=l(n(d._OrtRun,()=>d._OrtRun,f=>d._OrtRun=f)),d._OrtRunWithBinding=l(n(d._OrtRunWithBinding,()=>d._OrtRunWithBinding,f=>d._OrtRunWithBinding=f)),d._OrtBindInput=n(d._OrtBindInput,()=>d._OrtBindInput,f=>d._OrtBindInput=f),v=void 0};d.jsepInit=(n,l)=>{if(v?.(),n==="webgpu"){[d.Kb,d.Wb,d.$b,d.Lb,d.Zb,d.ob,d.ac,d.cc,d.Xb,d.Yb,d.bc]=l;let f=d.Kb;d.jsepRegisterBuffer=(b,C,k,V)=>f.registerBuffer(b,C,k,V),d.jsepGetBuffer=b=>f.getBuffer(b),d.jsepCreateDownloader=(b,C,k)=>f.createDownloader(b,C,k),d.jsepOnReleaseSession=b=>{f.onReleaseSession(b)},d.jsepOnRunStart=b=>f.onRunStart(b)}};var S=Object.assign({},d),A="./this.program",I=(n,l)=>{throw l},x=typeof window=="object",E=typeof importScripts=="function",P=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",O=d.ENVIRONMENT_IS_PTHREAD||!1,R="";function L(n){return d.locateFile?d.locateFile(n,R):R+n}var N,K,Q;if(P){var he=(uo(),wr(so)),W=(co(),wr(lo));R=E?W.dirname(R)+"/":__dirname+"/",N=(n,l)=>(n=Wt(n)?new URL(n):W.normalize(n),he.readFileSync(n,l?void 0:"utf8")),Q=n=>(n=N(n,!0),n.buffer||(n=new Uint8Array(n)),n),K=(n,l,f,b=!0)=>{n=Wt(n)?new URL(n):W.normalize(n),he.readFile(n,b?void 0:"utf8",(C,k)=>{C?f(C):l(b?k.buffer:k)})},!d.thisProgram&&1{throw process.exitCode=n,l},global.Worker=Pi().Worker}else(x||E)&&(E?R=self.location.href:typeof document<"u"&&document.currentScript&&(R=document.currentScript.src),typeof e<"u"&&e&&(R=e),R.startsWith("blob:")?R="":R=R.substr(0,R.replace(/[?#].*/,"").lastIndexOf("/")+1),P||(N=n=>{var l=new XMLHttpRequest;return l.open("GET",n,!1),l.send(null),l.responseText},E&&(Q=n=>{var l=new XMLHttpRequest;return l.open("GET",n,!1),l.responseType="arraybuffer",l.send(null),new Uint8Array(l.response)}),K=(n,l,f)=>{var b=new XMLHttpRequest;b.open("GET",n,!0),b.responseType="arraybuffer",b.onload=()=>{b.status==200||b.status==0&&b.response?l(b.response):f()},b.onerror=f,b.send(null)}));P&&typeof performance>"u"&&(global.performance=ki().performance);var se=console.log.bind(console),Ce=console.error.bind(console);P&&(se=(...n)=>he.writeSync(1,n.join(" ")+`\n`),Ce=(...n)=>he.writeSync(2,n.join(" ")+`\n`));var We=se,ee=Ce;Object.assign(d,S),S=null;var ae,Ae,me=!1,ie,ue,le,qe,G,ne,xe,Ke,Be,Ge,Ut;function Ne(){var n=ae.buffer;d.HEAP8=ue=new Int8Array(n),d.HEAP16=qe=new Int16Array(n),d.HEAPU8=le=new Uint8Array(n),d.HEAPU16=G=new Uint16Array(n),d.HEAP32=ne=new Int32Array(n),d.HEAPU32=xe=new Uint32Array(n),d.HEAPF32=Ke=new Float32Array(n),d.HEAPF64=Ut=new Float64Array(n),d.HEAP64=Be=new BigInt64Array(n),d.HEAPU64=Ge=new BigUint64Array(n)}var Ye=16777216;if(O)ae=d.wasmMemory;else if(d.wasmMemory)ae=d.wasmMemory;else if(ae=new WebAssembly.Memory({initial:Ye/65536,maximum:65536,shared:!0}),!(ae.buffer instanceof SharedArrayBuffer))throw ee("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"),P&&ee("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and/or recent version)"),Error("bad memory");Ne(),Ye=ae.buffer.byteLength;var mt=[],Rt=[],qt=[],Vt=0,sr=null,jt=null;function xr(){if(Vt--,Vt==0&&(sr!==null&&(clearInterval(sr),sr=null),jt)){var n=jt;jt=null,n()}}function Kt(n){throw n="Aborted("+n+")",ee(n),me=!0,ie=1,n=new WebAssembly.RuntimeError(n+". Build with -sASSERTIONS for more info."),w(n),n}var je=n=>n.startsWith("data:application/octet-stream;base64,"),Wt=n=>n.startsWith("file://"),at;at="ort-wasm-simd-threaded.wasm",je(at)||(at=L(at));function Cr(n){if(Q)return Q(n);throw"both async and sync fetching of the wasm failed"}function ft(n){if(x||E){if(typeof fetch=="function"&&!Wt(n))return fetch(n,{credentials:"same-origin"}).then(l=>{if(!l.ok)throw`failed to load wasm binary file at \'${n}\'`;return l.arrayBuffer()}).catch(()=>Cr(n));if(K)return new Promise((l,f)=>{K(n,b=>l(new Uint8Array(b)),f)})}return Promise.resolve().then(()=>Cr(n))}function ur(n,l,f){return ft(n).then(b=>WebAssembly.instantiate(b,l)).then(f,b=>{ee(`failed to asynchronously prepare wasm: ${b}`),Kt(b)})}function Ar(n,l){var f=at;return typeof WebAssembly.instantiateStreaming!="function"||je(f)||Wt(f)||P||typeof fetch!="function"?ur(f,n,l):fetch(f,{credentials:"same-origin"}).then(b=>WebAssembly.instantiateStreaming(b,n).then(l,function(C){return ee(`wasm streaming compile failed: ${C}`),ee("falling back to ArrayBuffer instantiation"),ur(f,n,l)}))}var Ir={826468:(n,l,f,b)=>{if(typeof d>"u"||!d.Db)return 1;if(n=He(n>>>0),n.startsWith("./")&&(n=n.substring(2)),n=d.Db.get(n),!n)return 2;if(l>>>=0,f>>>=0,b>>>=0,l+f>n.byteLength)return 3;try{return o().set(n.subarray(l,l+f),b>>>0),0}catch{return 4}},826969:()=>{d.Xb()},827e3:()=>{d.Yb()},827029:()=>{d.bc()},827054:n=>d.Wb(n),827087:n=>d.$b(n),827119:(n,l,f)=>{d.Lb(n,l,f,!0)},827158:(n,l,f)=>{d.Lb(n,l,f)},827191:n=>{d.ob("Abs",n,void 0)},827242:n=>{d.ob("Neg",n,void 0)},827293:n=>{d.ob("Floor",n,void 0)},827346:n=>{d.ob("Ceil",n,void 0)},827398:n=>{d.ob("Reciprocal",n,void 0)},827456:n=>{d.ob("Sqrt",n,void 0)},827508:n=>{d.ob("Exp",n,void 0)},827559:n=>{d.ob("Erf",n,void 0)},827610:n=>{d.ob("Sigmoid",n,void 0)},827665:(n,l,f)=>{d.ob("HardSigmoid",n,{alpha:l,beta:f})},827744:n=>{d.ob("Log",n,void 0)},827795:n=>{d.ob("Sin",n,void 0)},827846:n=>{d.ob("Cos",n,void 0)},827897:n=>{d.ob("Tan",n,void 0)},827948:n=>{d.ob("Asin",n,void 0)},828e3:n=>{d.ob("Acos",n,void 0)},828052:n=>{d.ob("Atan",n,void 0)},828104:n=>{d.ob("Sinh",n,void 0)},828156:n=>{d.ob("Cosh",n,void 0)},828208:n=>{d.ob("Asinh",n,void 0)},828261:n=>{d.ob("Acosh",n,void 0)},828314:n=>{d.ob("Atanh",n,void 0)},828367:n=>{d.ob("Tanh",n,void 0)},828419:n=>{d.ob("Not",n,void 0)},828470:(n,l,f)=>{d.ob("Clip",n,{min:l,max:f})},828539:n=>{d.ob("Clip",n,void 0)},828591:(n,l)=>{d.ob("Elu",n,{alpha:l})},828649:n=>{d.ob("Relu",n,void 0)},828701:(n,l)=>{d.ob("LeakyRelu",n,{alpha:l})},828765:(n,l)=>{d.ob("ThresholdedRelu",n,{alpha:l})},828835:(n,l)=>{d.ob("Cast",n,{to:l})},828893:n=>{d.ob("Add",n,void 0)},828944:n=>{d.ob("Sub",n,void 0)},828995:n=>{d.ob("Mul",n,void 0)},829046:n=>{d.ob("Div",n,void 0)},829097:n=>{d.ob("Pow",n,void 0)},829148:n=>{d.ob("Equal",n,void 0)},829201:n=>{d.ob("Greater",n,void 0)},829256:n=>{d.ob("GreaterOrEqual",n,void 0)},829318:n=>{d.ob("Less",n,void 0)},829370:n=>{d.ob("LessOrEqual",n,void 0)},829429:(n,l,f,b,C)=>{d.ob("ReduceMean",n,{keepDims:!!l,noopWithEmptyAxes:!!f,axes:b?Array.from(a().subarray(b>>>0,C>>>0)):[]})},829588:(n,l,f,b,C)=>{d.ob("ReduceMax",n,{keepDims:!!l,noopWithEmptyAxes:!!f,axes:b?Array.from(a().subarray(b>>>0,C>>>0)):[]})},829746:(n,l,f,b,C)=>{d.ob("ReduceMin",n,{keepDims:!!l,noopWithEmptyAxes:!!f,axes:b?Array.from(a().subarray(b>>>0,C>>>0)):[]})},829904:(n,l,f,b,C)=>{d.ob("ReduceProd",n,{keepDims:!!l,noopWithEmptyAxes:!!f,axes:b?Array.from(a().subarray(b>>>0,C>>>0)):[]})},830063:(n,l,f,b,C)=>{d.ob("ReduceSum",n,{keepDims:!!l,noopWithEmptyAxes:!!f,axes:b?Array.from(a().subarray(b>>>0,C>>>0)):[]})},830221:(n,l,f,b,C)=>{d.ob("ReduceL1",n,{keepDims:!!l,noopWithEmptyAxes:!!f,axes:b?Array.from(a().subarray(b>>>0,C>>>0)):[]})},830378:(n,l,f,b,C)=>{d.ob("ReduceL2",n,{keepDims:!!l,noopWithEmptyAxes:!!f,axes:b?Array.from(a().subarray(b>>>0,C>>>0)):[]})},830535:(n,l,f,b,C)=>{d.ob("ReduceLogSum",n,{keepDims:!!l,noopWithEmptyAxes:!!f,axes:b?Array.from(a().subarray(b>>>0,C>>>0)):[]})},830696:(n,l,f,b,C)=>{d.ob("ReduceSumSquare",n,{keepDims:!!l,noopWithEmptyAxes:!!f,axes:b?Array.from(a().subarray(b>>>0,C>>>0)):[]})},830860:(n,l,f,b,C)=>{d.ob("ReduceLogSumExp",n,{keepDims:!!l,noopWithEmptyAxes:!!f,axes:b?Array.from(a().subarray(b>>>0,C>>>0)):[]})},831024:n=>{d.ob("Where",n,void 0)},831077:(n,l,f)=>{d.ob("Transpose",n,{perm:l?Array.from(a().subarray(l>>>0,f>>>0)):[]})},831185:(n,l,f,b)=>{d.ob("DepthToSpace",n,{blocksize:l,mode:He(f),format:b?"NHWC":"NCHW"})},831318:(n,l,f,b)=>{d.ob("DepthToSpace",n,{blocksize:l,mode:He(f),format:b?"NHWC":"NCHW"})},831451:(n,l,f,b,C,k,V,F,re,J,ce,Re,ze,z,we)=>{d.ob("ConvTranspose",n,{format:re?"NHWC":"NCHW",autoPad:l,dilations:[f],group:b,kernelShape:[C],pads:[k,V],strides:[F],wIsConst:()=>!!r()[J>>>0],outputPadding:ce?Array.from(a().subarray(ce>>>0,Re>>>0)):[],outputShape:ze?Array.from(a().subarray(ze>>>0,z>>>0)):[],activation:He(we)})},831852:(n,l,f,b,C,k,V,F,re,J,ce,Re,ze,z)=>{d.ob("ConvTranspose",n,{format:F?"NHWC":"NCHW",autoPad:l,dilations:Array.from(a().subarray(f>>>0,(f>>>0)+2>>>0)),group:b,kernelShape:Array.from(a().subarray(C>>>0,(C>>>0)+2>>>0)),pads:Array.from(a().subarray(k>>>0,(k>>>0)+4>>>0)),strides:Array.from(a().subarray(V>>>0,(V>>>0)+2>>>0)),wIsConst:()=>!!r()[re>>>0],outputPadding:J?Array.from(a().subarray(J>>>0,ce>>>0)):[],outputShape:Re?Array.from(a().subarray(Re>>>0,ze>>>0)):[],activation:He(z)})},832417:(n,l,f,b,C,k,V,F,re,J,ce,Re,ze,z,we)=>{d.ob("ConvTranspose",n,{format:re?"NHWC":"NCHW",autoPad:l,dilations:[f],group:b,kernelShape:[C],pads:[k,V],strides:[F],wIsConst:()=>!!r()[J>>>0],outputPadding:ce?Array.from(a().subarray(ce>>>0,Re>>>0)):[],outputShape:ze?Array.from(a().subarray(ze>>>0,z>>>0)):[],activation:He(we)})},832818:(n,l,f,b,C,k,V,F,re,J,ce,Re,ze,z)=>{d.ob("ConvTranspose",n,{format:F?"NHWC":"NCHW",autoPad:l,dilations:Array.from(a().subarray(f>>>0,(f>>>0)+2>>>0)),group:b,kernelShape:Array.from(a().subarray(C>>>0,(C>>>0)+2>>>0)),pads:Array.from(a().subarray(k>>>0,(k>>>0)+4>>>0)),strides:Array.from(a().subarray(V>>>0,(V>>>0)+2>>>0)),wIsConst:()=>!!r()[re>>>0],outputPadding:J?Array.from(a().subarray(J>>>0,ce>>>0)):[],outputShape:Re?Array.from(a().subarray(Re>>>0,ze>>>0)):[],activation:He(z)})},833383:(n,l)=>{d.ob("GlobalAveragePool",n,{format:l?"NHWC":"NCHW"})},833474:(n,l,f,b,C,k,V,F,re,J,ce,Re,ze,z,we,Pe)=>{d.ob("AveragePool",n,{format:Pe?"NHWC":"NCHW",auto_pad:l,ceil_mode:f,count_include_pad:b,storage_order:C,dilations:[k,V],kernel_shape:[F,re],pads:[J,ce,Re,ze],strides:[z,we]})},833758:(n,l)=>{d.ob("GlobalAveragePool",n,{format:l?"NHWC":"NCHW"})},833849:(n,l,f,b,C,k,V,F,re,J,ce,Re,ze,z,we,Pe)=>{d.ob("AveragePool",n,{format:Pe?"NHWC":"NCHW",auto_pad:l,ceil_mode:f,count_include_pad:b,storage_order:C,dilations:[k,V],kernel_shape:[F,re],pads:[J,ce,Re,ze],strides:[z,we]})},834133:(n,l)=>{d.ob("GlobalMaxPool",n,{format:l?"NHWC":"NCHW"})},834220:(n,l,f,b,C,k,V,F,re,J,ce,Re,ze,z,we,Pe)=>{d.ob("MaxPool",n,{format:Pe?"NHWC":"NCHW",auto_pad:l,ceil_mode:f,count_include_pad:b,storage_order:C,dilations:[k,V],kernel_shape:[F,re],pads:[J,ce,Re,ze],strides:[z,we]})},834500:(n,l)=>{d.ob("GlobalMaxPool",n,{format:l?"NHWC":"NCHW"})},834587:(n,l,f,b,C,k,V,F,re,J,ce,Re,ze,z,we,Pe)=>{d.ob("MaxPool",n,{format:Pe?"NHWC":"NCHW",auto_pad:l,ceil_mode:f,count_include_pad:b,storage_order:C,dilations:[k,V],kernel_shape:[F,re],pads:[J,ce,Re,ze],strides:[z,we]})},834867:(n,l,f,b,C)=>{d.ob("Gemm",n,{alpha:l,beta:f,transA:b,transB:C})},834971:n=>{d.ob("MatMul",n,void 0)},835025:(n,l,f,b)=>{d.ob("ArgMax",n,{keepDims:!!l,selectLastIndex:!!f,axis:b})},835133:(n,l,f,b)=>{d.ob("ArgMin",n,{keepDims:!!l,selectLastIndex:!!f,axis:b})},835241:(n,l)=>{d.ob("Softmax",n,{axis:l})},835304:(n,l)=>{d.ob("Concat",n,{axis:l})},835364:(n,l,f,b,C)=>{d.ob("Split",n,{axis:l,numOutputs:f,splitSizes:b?Array.from(a().subarray(b>>>0,C>>>0)):[]})},835504:n=>{d.ob("Expand",n,void 0)},835558:(n,l)=>{d.ob("Gather",n,{axis:Number(l)})},835629:(n,l)=>{d.ob("GatherElements",n,{axis:Number(l)})},835708:(n,l,f,b,C,k,V,F,re,J,ce)=>{d.ob("Resize",n,{antialias:l,axes:f?Array.from(a().subarray(f>>>0,b>>>0)):[],coordinateTransformMode:He(C),cubicCoeffA:k,excludeOutside:V,extrapolationValue:F,keepAspectRatioPolicy:He(re),mode:He(J),nearestMode:He(ce)})},836054:(n,l,f,b,C,k,V)=>{d.ob("Slice",n,{starts:l?Array.from(a().subarray(l>>>0,f>>>0)):[],ends:b?Array.from(a().subarray(b>>>0,C>>>0)):[],axes:k?Array.from(a().subarray(k>>>0,V>>>0)):[]})},836270:n=>{d.ob("Tile",n,void 0)},836322:(n,l,f,b)=>{d.ob("LayerNormalization",n,{axis:l,epsilon:f,simplified:!!b})},836433:(n,l,f)=>{d.ob("InstanceNormalization",n,{epsilon:l,format:f?"NHWC":"NCHW"})},836547:(n,l,f)=>{d.ob("InstanceNormalization",n,{epsilon:l,format:f?"NHWC":"NCHW"})},836661:n=>{d.ob("Range",n,void 0)},836714:(n,l)=>{d.ob("Einsum",n,{equation:He(l)})},836795:(n,l,f,b,C)=>{d.ob("Pad",n,{mode:l,value:f,pads:b?Array.from(a().subarray(b>>>0,C>>>0)):[]})},836922:(n,l,f,b,C,k)=>{d.ob("BatchNormalization",n,{epsilon:l,momentum:f,spatial:!!C,trainingMode:!!b,format:k?"NHWC":"NCHW"})},837091:(n,l,f,b,C,k)=>{d.ob("BatchNormalization",n,{epsilon:l,momentum:f,spatial:!!C,trainingMode:!!b,format:k?"NHWC":"NCHW"})},837260:(n,l,f)=>{d.ob("CumSum",n,{exclusive:Number(l),reverse:Number(f)})},837357:(n,l,f,b,C,k,V,F,re)=>{d.ob("Attention",n,{numHeads:l,isUnidirectional:f,maskFilterValue:b,scale:C,doRotary:k,qkvHiddenSizes:V?Array.from(a().subarray(Number(F)>>>0,Number(F)+V>>>0)):[],pastPresentShareBuffer:!!re})},837629:n=>{d.ob("BiasAdd",n,void 0)},837684:n=>{d.ob("BiasSplitGelu",n,void 0)},837745:n=>{d.ob("FastGelu",n,void 0)},837801:(n,l,f,b,C,k,V,F,re,J,ce,Re,ze)=>{d.ob("Conv",n,{format:re?"NHWC":"NCHW",auto_pad:l,dilations:[f],group:b,kernel_shape:[C],pads:k?Array.from(a().subarray(k>>>0,V>>>0)):[],strides:[F],w_is_const:()=>!!r()[J>>>0],activation:He(ce),activation_params:Re?Array.from(p().subarray(Re>>>0,ze>>>0)):[]})},838171:(n,l,f,b,C,k,V,F,re,J,ce,Re,ze,z,we,Pe)=>{d.ob("Conv",n,{format:Re?"NHWC":"NCHW",auto_pad:l,dilations:[f,b],group:C,kernel_shape:[k,V],pads:F?Array.from(a().subarray(F>>>0,re>>>0)):[],strides:[J,ce],w_is_const:()=>!!r()[ze>>>0],activation:He(z),activation_params:we?Array.from(p().subarray(we>>>0,Pe>>>0)):[]})},838562:n=>{d.ob("Gelu",n,void 0)},838614:(n,l,f,b,C,k)=>{d.ob("MatMulNBits",n,{k:l,n:f,accuracyLevel:b,bits:C,blockSize:k})},838741:(n,l,f,b,C,k)=>{d.ob("MultiHeadAttention",n,{numHeads:l,isUnidirectional:f,maskFilterValue:b,scale:C,doRotary:k})},838900:(n,l,f,b,C)=>{d.ob("RotaryEmbedding",n,{interleaved:!!l,numHeads:f,rotaryEmbeddingDim:b,scale:C})},839039:(n,l,f)=>{d.ob("SkipLayerNormalization",n,{epsilon:l,simplified:!!f})},839141:(n,l,f)=>{d.ob("SkipLayerNormalization",n,{epsilon:l,simplified:!!f})},839243:(n,l,f,b)=>{d.ob("LayerNormalization",n,{axis:l,epsilon:f,simplified:!!b})},839354:n=>{d.ac(n)},839388:(n,l)=>d.cc(n,l,d.Cb.ec,d.Cb.errors)};function st(n){this.name="ExitStatus",this.message=`Program terminated with exit(${n})`,this.status=n}var Tr=n=>{n.terminate(),n.onmessage=()=>{}},ht=n=>{ge.xb.length==0&&(lr(),ge.Mb(ge.xb[0]));var l=ge.xb.pop();if(!l)return 6;ge.yb.push(l),ge.ub[n.wb]=l,l.wb=n.wb;var f={cmd:"run",start_routine:n.fc,arg:n.Rb,pthread_ptr:n.wb};return P&&l.unref(),l.postMessage(f,n.mc),0},bt=0,Er=n=>{var l=io();return n=n(),fn(l),n},Te=(n,l,...f)=>Er(()=>{for(var b=2*f.length,C=oo(8*b),k=C>>>3,V=0;V>>0]=F)}return gi(n,0,b,C,l)});function dr(n){if(O)return Te(0,1,n);ie=n,0{if(ie=n,O)throw jr(n),"unwind";dr(n)};function ut(){for(var n=d.numThreads;n--;)lr();mt.unshift(()=>{Vt++,Fn(()=>xr())})}function lr(){var n=L("ort-wasm-simd-threaded.worker.js");n=new Worker(n),ge.xb.push(n)}function Fn(n){O?n():Promise.all(ge.xb.map(ge.Mb)).then(n)}var ge={xb:[],yb:[],Qb:[],ub:{},Gb(){O?(ge.receiveObjectTransfer=ge.dc,ge.threadInitTLS=ge.Pb,ge.setExitStatus=ge.Ob):ut()},Ob:n=>ie=n,pc:["$terminateWorker"],hc:()=>{for(var n of ge.yb)Tr(n);for(n of ge.xb)Tr(n);ge.xb=[],ge.yb=[],ge.ub=[]},Nb:n=>{var l=n.wb;delete ge.ub[l],ge.xb.push(n),ge.yb.splice(ge.yb.indexOf(n),1),n.wb=0,ro(l)},dc(){},Pb(){ge.Qb.forEach(n=>n())},Mb:n=>new Promise(l=>{n.onmessage=k=>{k=k.data;var V=k.cmd;if(k.targetThread&&k.targetThread!=pn()){var F=ge.ub[k.targetThread];F?F.postMessage(k,k.transferList):ee(`Internal error! Worker sent a message "${V}" to target pthread ${k.targetThread}, but that thread no longer exists!`)}else V==="checkMailbox"?rt():V==="spawnThread"?ht(k):V==="cleanupThread"?ge.Nb(ge.ub[k.thread]):V==="killThread"?(k=k.thread,V=ge.ub[k],delete ge.ub[k],Tr(V),ro(k),ge.yb.splice(ge.yb.indexOf(V),1),V.wb=0):V==="cancelThread"?ge.ub[k.thread].postMessage({cmd:"cancel"}):V==="loaded"?(n.loaded=!0,P&&!n.wb&&n.unref(),l(n)):V==="alert"?alert(`Thread ${k.threadId}: ${k.text}`):k.target==="setimmediate"?n.postMessage(k):V==="callHandler"?d[k.handler](...k.args):V&&ee(`worker sent an unknown command ${V}`)},n.onerror=k=>{throw ee(`worker sent an error! ${k.filename}:${k.lineno}: ${k.message}`),k},P&&(n.on("message",k=>n.onmessage({data:k})),n.on("error",k=>n.onerror(k)));var f=[],b=["onExit"],C;for(C of b)d.hasOwnProperty(C)&&f.push(C);n.postMessage({cmd:"load",handlers:f,urlOrBlob:d.mainScriptUrlOrBlob||e,wasmMemory:ae,wasmModule:Ae})})};d.PThread=ge;var Yt=n=>{for(;0{var n=pn(),l=c()[n+52>>>2>>>0];n=c()[n+56>>>2>>>0],bi(l,l-n),fn(l)};function jr(n){if(O)return Te(1,0,n);Xe(n)}d.invokeEntryPoint=(n,l)=>{bt=0,n=wi(n,l),0>>2>>>0]=0,c()[this.Ib+4>>>2>>>0]=l,c()[this.Ib+8>>>2>>>0]=f}}var Kr=0,jn=0;function Yr(n,l,f,b){return O?Te(2,1,n,l,f,b):Zr(n,l,f,b)}function Zr(n,l,f,b){if(n>>>=0,l>>>=0,f>>>=0,b>>>=0,typeof SharedArrayBuffer>"u")return ee("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var C=[];return O&&C.length===0?Yr(n,l,f,b):(n={fc:f,wb:n,Rb:b,mc:C},O?(n.oc="spawnThread",postMessage(n,C),0):ht(n))}var cr=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,Pr=(n,l,f)=>{l>>>=0;var b=l+f;for(f=l;n[f]&&!(f>=b);)++f;if(16C?b+=String.fromCharCode(C):(C-=65536,b+=String.fromCharCode(55296|C>>10,56320|C&1023))}}else b+=String.fromCharCode(C)}return b},He=(n,l)=>(n>>>=0)?Pr(o(),n,l):"";function Xr(n,l,f){return O?Te(3,1,n,l,f):0}function Qr(n,l){if(O)return Te(4,1,n,l)}var gt=n=>{for(var l=0,f=0;f=b?l++:2047>=b?l+=2:55296<=b&&57343>=b?(l+=4,++f):l+=3}return l},dt=(n,l,f,b)=>{if(f>>>=0,!(0=V){var F=n.charCodeAt(++k);V=65536+((V&1023)<<10)|F&1023}if(127>=V){if(f>=b)break;l[f++>>>0]=V}else{if(2047>=V){if(f+1>=b)break;l[f++>>>0]=192|V>>6}else{if(65535>=V){if(f+2>=b)break;l[f++>>>0]=224|V>>12}else{if(f+3>=b)break;l[f++>>>0]=240|V>>18,l[f++>>>0]=128|V>>12&63}l[f++>>>0]=128|V>>6&63}l[f++>>>0]=128|V&63}}return l[f>>>0]=0,f-C},Bt=(n,l,f)=>dt(n,o(),l,f);function Zt(n,l){if(O)return Te(5,1,n,l)}function kr(n,l,f){if(O)return Te(6,1,n,l,f)}function Or(n,l,f){return O?Te(7,1,n,l,f):0}function Jr(n,l){if(O)return Te(8,1,n,l)}function pr(n,l,f){if(O)return Te(9,1,n,l,f)}function en(n,l,f,b){if(O)return Te(10,1,n,l,f,b)}function tn(n,l,f,b){if(O)return Te(11,1,n,l,f,b)}function rn(n,l,f,b){if(O)return Te(12,1,n,l,f,b)}function nn(n){if(O)return Te(13,1,n)}function Rr(n,l){if(O)return Te(14,1,n,l)}function Xt(n,l,f){if(O)return Te(15,1,n,l,f)}var on,nt=n=>{for(var l="";o()[n>>>0];)l+=on[o()[n++>>>0]];return l},mr={},Br={},Kn={},wt;function Yn(n,l,f={}){var b=l.name;if(!n)throw new wt(`type "${b}" must have a positive integer typeid pointer`);if(Br.hasOwnProperty(n)){if(f.Ub)return;throw new wt(`Cannot register type \'${b}\' twice`)}Br[n]=l,delete Kn[n],mr.hasOwnProperty(n)&&(l=mr[n],delete mr[n],l.forEach(C=>C()))}function Je(n,l,f={}){if(!("argPackAdvance"in l))throw new TypeError("registerType registeredInstance requires argPackAdvance");return Yn(n,l,f)}var Dr=(n,l,f)=>{switch(l){case 1:return f?b=>r()[b>>>0]:b=>o()[b>>>0];case 2:return f?b=>i()[b>>>1>>>0]:b=>u()[b>>>1>>>0];case 4:return f?b=>a()[b>>>2>>>0]:b=>c()[b>>>2>>>0];case 8:return f?b=>Be[b>>>3]:b=>Ge[b>>>3];default:throw new TypeError(`invalid integer width (${l}): ${n}`)}},fr=[],lt=[];function hr(n){n>>>=0,9{if(!n)throw new wt("Cannot use deleted val. handle = "+n);return lt[n]},ot=n=>{switch(n){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let l=fr.pop()||lt.length;return lt[l]=n,lt[l+1]=1,l}};function Qt(n){return this.fromWireType(c()[n>>>2>>>0])}var Zn={name:"emscripten::val",fromWireType:n=>{var l=Qe(n);return hr(n),l},toWireType:(n,l)=>ot(l),argPackAdvance:8,readValueFromPointer:Qt,Bb:null},an=(n,l)=>{switch(l){case 4:return function(f){return this.fromWireType(p()[f>>>2>>>0])};case 8:return function(f){return this.fromWireType(h()[f>>>3>>>0])};default:throw new TypeError(`invalid float width (${l}): ${n}`)}},zr=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,Xn=(n,l)=>{for(var f=n>>1,b=f+l/2;!(f>=b)&&u()[f>>>0];)++f;if(f<<=1,32=l/2);++b){var C=i()[n+2*b>>>1>>>0];if(C==0)break;f+=String.fromCharCode(C)}return f},sn=(n,l,f)=>{if(f??=2147483647,2>f)return 0;f-=2;var b=l;f=f<2*n.length?f/2:n.length;for(var C=0;C>>1>>>0]=k,l+=2}return i()[l>>>1>>>0]=0,l-b},un=n=>2*n.length,gr=(n,l)=>{for(var f=0,b="";!(f>=l/4);){var C=a()[n+4*f>>>2>>>0];if(C==0)break;++f,65536<=C?(C-=65536,b+=String.fromCharCode(55296|C>>10,56320|C&1023)):b+=String.fromCharCode(C)}return b},Qn=(n,l,f)=>{if(l>>>=0,f??=2147483647,4>f)return 0;var b=l;f=b+f-4;for(var C=0;C=k){var V=n.charCodeAt(++C);k=65536+((k&1023)<<10)|V&1023}if(a()[l>>>2>>>0]=k,l+=4,l+4>f)break}return a()[l>>>2>>>0]=0,l-b},pe=n=>{for(var l=0,f=0;f=b&&++f,l+=4}return l},Mr=n=>{if(!me)try{if(n(),!(0>>=0,typeof Atomics.nc=="function"&&(Atomics.nc(a(),n>>>2,n).value.then(rt),n+=128,Atomics.store(a(),n>>>2,1))}d.__emscripten_thread_mailbox_await=Nt;var rt=()=>{var n=pn();n&&(Nt(n),Mr(yi))};d.checkMailbox=rt;var yr=[],br=(n,l)=>{var f=Br[n];if(f===void 0)throw n=fi(n),f=nt(n),At(n),new wt(`${l} has unknown type ${f}`);return f},Ur=(n,l,f)=>{var b=[];return n=n.toWireType(b,f),b.length&&(c()[l>>>2>>>0]=ot(b)),n},Jt=n=>{try{n()}catch(l){Kt(l)}};function dn(){var n=oe,l={};for(let[f,b]of Object.entries(n))l[f]=typeof b=="function"?(...C)=>{Dt.push(f);try{return b(...C)}finally{me||(Dt.pop(),ct&&vt===1&&Dt.length===0&&(vt=0,bt+=1,Jt($i),typeof Fibers<"u"&&Fibers.rc()))}}:b;return l}var vt=0,ct=null,ln=0,Dt=[],Vr={},s={},m=0,g=null,$=[];function T(){return new Promise((n,l)=>{g={resolve:n,reject:l}})}function B(){var n=mn(65548),l=n+12;c()[n>>>2>>>0]=l,c()[n+4>>>2>>>0]=l+65536,l=Dt[0];var f=Vr[l];return f===void 0&&(f=m++,Vr[l]=f,s[f]=l),l=f,a()[n+8>>>2>>>0]=l,n}function H(){var n=a()[ct+8>>>2>>>0];return n=oe[s[n]],--bt,n()}function q(n){if(!me){if(vt===0){var l=!1,f=!1;n((b=0)=>{if(!me&&(ln=b,l=!0,f)){vt=2,Jt(()=>_i(ct)),typeof Browser<"u"&&Browser.Hb.Tb&&Browser.Hb.resume(),b=!1;try{var C=H()}catch(F){C=F,b=!0}var k=!1;if(!ct){var V=g;V&&(g=null,(b?V.reject:V.resolve)(C),k=!0)}if(b&&!k)throw C}}),f=!0,l||(vt=1,ct=B(),typeof Browser<"u"&&Browser.Hb.Tb&&Browser.Hb.pause(),Jt(()=>vi(ct)))}else vt===2?(vt=0,Jt(Si),At(ct),ct=null,$.forEach(Mr)):Kt(`invalid state: ${vt}`);return ln}}function te(n){return q(l=>{n().then(l)})}var X=[],de={},Ee=n=>{var l=de[n];return l===void 0?nt(n):l},Oe=()=>typeof globalThis=="object"?globalThis:Function("return this")(),D=n=>{var l=X.length;return X.push(n),l},be=(n,l)=>{for(var f=Array(n),b=0;b>>2>>>0],"parameter "+b);return f},Ie=(n,l)=>Object.defineProperty(l,"name",{value:n});function zt(n){var l=Function;if(!(l instanceof Function))throw new TypeError(`new_ called with constructor type ${typeof l} which is not a function`);var f=Ie(l.name||"unknownFunctionName",function(){});return f.prototype=l.prototype,f=new f,n=l.apply(f,n),n instanceof Object?n:f}var Mt=n=>n%4===0&&(n%100!==0||n%400===0),Qo=[0,31,60,91,121,152,182,213,244,274,305,335],Jo=[0,31,59,90,120,151,181,212,243,273,304,334];function ei(n,l,f,b,C,k,V){return O?Te(16,1,n,l,f,b,C,k,V):-52}function ti(n,l,f,b,C,k){if(O)return Te(17,1,n,l,f,b,C,k)}var Jn=[],ri=(n,l)=>{Jn.length=0;for(var f;f=o()[n++>>>0];){var b=f!=105;b&=f!=112,l+=b&&l%8?4:0,Jn.push(f==112?c()[l>>>2>>>0]:f==106?Be[l>>>3]:f==105?a()[l>>>2>>>0]:h()[l>>>3>>>0]),l+=b?8:4}return Jn},eo={},ni=()=>{if(!to){var n={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",_:A||"./this.program"},l;for(l in eo)eo[l]===void 0?delete n[l]:n[l]=eo[l];var f=[];for(l in n)f.push(`${l}=${n[l]}`);to=f}return to},to;function oi(n,l){if(O)return Te(18,1,n,l);n>>>=0,l>>>=0;var f=0;return ni().forEach((b,C)=>{var k=l+f;for(C=c()[n+4*C>>>2>>>0]=k,k=0;k>>0]=b.charCodeAt(k);r()[C>>>0]=0,f+=b.length+1}),0}function ii(n,l){if(O)return Te(19,1,n,l);n>>>=0,l>>>=0;var f=ni();c()[n>>>2>>>0]=f.length;var b=0;return f.forEach(C=>b+=C.length+1),c()[l>>>2>>>0]=b,0}function ai(n){return O?Te(20,1,n):52}function si(n,l,f,b){return O?Te(21,1,n,l,f,b):52}function ui(n,l,f,b){return O?Te(22,1,n,l,f,b):70}var Xd=[null,[],[]];function di(n,l,f,b){if(O)return Te(23,1,n,l,f,b);l>>>=0,f>>>=0,b>>>=0;for(var C=0,k=0;k>>2>>>0],F=c()[l+4>>>2>>>0];l+=8;for(var re=0;re>>0],ce=Xd[n];J===0||J===10?((n===1?We:ee)(Pr(ce,0)),ce.length=0):ce.push(J)}C+=F}return c()[b>>>2>>>0]=C,0}var li=[31,29,31,30,31,30,31,31,30,31,30,31],ci=[31,28,31,30,31,30,31,31,30,31,30,31];function Qd(n){var l=Array(gt(n)+1);return dt(n,l,0,l.length),l}var Jd=(n,l)=>{r().set(n,l>>>0)};function pi(n,l,f,b){function C(z,we,Pe){for(z=typeof z=="number"?z.toString():z||"";z.lengthCi?-1:0er-z.getDate())we-=er-z.getDate()+1,z.setDate(1),11>Pe?z.setMonth(Pe+1):(z.setMonth(0),z.setFullYear(z.getFullYear()+1));else{z.setDate(z.getDate()+we);break}}return Pe=new Date(z.getFullYear()+1,0,4),we=F(new Date(z.getFullYear(),0,4)),Pe=F(Pe),0>=V(we,z)?0>=V(Pe,z)?z.getFullYear()+1:z.getFullYear():z.getFullYear()-1}n>>>=0,l>>>=0,f>>>=0,b>>>=0;var J=c()[b+40>>>2>>>0];b={kc:a()[b>>>2>>>0],jc:a()[b+4>>>2>>>0],Eb:a()[b+8>>>2>>>0],Jb:a()[b+12>>>2>>>0],Fb:a()[b+16>>>2>>>0],Ab:a()[b+20>>>2>>>0],vb:a()[b+24>>>2>>>0],zb:a()[b+28>>>2>>>0],qc:a()[b+32>>>2>>>0],ic:a()[b+36>>>2>>>0],lc:J?He(J):""},f=He(f),J={"%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 ce in J)f=f.replace(new RegExp(ce,"g"),J[ce]);var Re="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),ze="January February March April May June July August September October November December".split(" ");J={"%a":z=>Re[z.vb].substring(0,3),"%A":z=>Re[z.vb],"%b":z=>ze[z.Fb].substring(0,3),"%B":z=>ze[z.Fb],"%C":z=>k((z.Ab+1900)/100|0,2),"%d":z=>k(z.Jb,2),"%e":z=>C(z.Jb,2," "),"%g":z=>re(z).toString().substring(2),"%G":re,"%H":z=>k(z.Eb,2),"%I":z=>(z=z.Eb,z==0?z=12:12{for(var we=0,Pe=0;Pe<=z.Fb-1;we+=(Mt(z.Ab+1900)?li:ci)[Pe++]);return k(z.Jb+we,3)},"%m":z=>k(z.Fb+1,2),"%M":z=>k(z.jc,2),"%n":()=>`\n`,"%p":z=>0<=z.Eb&&12>z.Eb?"AM":"PM","%S":z=>k(z.kc,2),"%t":()=>" ","%u":z=>z.vb||7,"%U":z=>k(Math.floor((z.zb+7-z.vb)/7),2),"%V":z=>{var we=Math.floor((z.zb+7-(z.vb+6)%7)/7);if(2>=(z.vb+371-z.zb-2)%7&&we++,we)we==53&&(Pe=(z.vb+371-z.zb)%7,Pe==4||Pe==3&&Mt(z.Ab)||(we=1));else{we=52;var Pe=(z.vb+7-z.zb-1)%7;(Pe==4||Pe==5&&Mt(z.Ab%400-1))&&we++}return k(we,2)},"%w":z=>z.vb,"%W":z=>k(Math.floor((z.zb+7-(z.vb+6)%7)/7),2),"%y":z=>(z.Ab+1900).toString().substring(2),"%Y":z=>z.Ab+1900,"%z":z=>{z=z.ic;var we=0<=z;return z=Math.abs(z)/60,(we?"+":"-")+("0000"+(z/60*100+z%60)).slice(-4)},"%Z":z=>z.lc,"%%":()=>"%"},f=f.replace(/%%/g,"\\0\\0");for(ce in J)f.includes(ce)&&(f=f.replace(new RegExp(ce,"g"),J[ce](b)));return f=f.replace(/\\0\\0/g,"%"),ce=Qd(f),ce.length>l?0:(Jd(ce,n),ce.length-1)}ge.Gb();for(var mi=Array(256),cn=0;256>cn;++cn)mi[cn]=String.fromCharCode(cn);on=mi,wt=d.BindingError=class extends Error{constructor(n){super(n),this.name="BindingError"}},d.InternalError=class extends Error{constructor(n){super(n),this.name="InternalError"}},lt.push(0,1,void 0,1,null,1,!0,1,!1,1),d.count_emval_handles=()=>lt.length/2-5-fr.length;var el=[dr,jr,Yr,Xr,Qr,Zt,kr,Or,Jr,pr,en,tn,rn,nn,Rr,Xt,ei,ti,oi,ii,ai,si,ui,di],tl={ua:function(n,l,f){return te(async()=>{await d.Zb(n,l,f)})},b:function(n,l,f){throw n>>>=0,new qn(n).Gb(l>>>0,f>>>0),Kr=n,jn++,Kr},ia:function(n){hi(n>>>0,!E,1,!x,131072,!1),ge.Pb()},G:function(n){n>>>=0,O?postMessage({cmd:"cleanupThread",thread:n}):ge.Nb(ge.ub[n])},_:Zr,A:Xr,pa:Qr,W:Zt,Y:kr,qa:Or,na:Jr,fa:pr,ma:en,K:tn,X:rn,U:nn,oa:Rr,V:Xt,E:function(n,l,f){n>>>=0,f>>>=0,l=nt(l>>>0),Je(n,{name:l,fromWireType:b=>b,toWireType:function(b,C){if(typeof C!="bigint"&&typeof C!="number")throw C===null?C="null":(b=typeof C,C=b==="object"||b==="array"||b==="function"?C.toString():""+C),new TypeError(`Cannot convert "${C}" to ${this.name}`);return typeof C=="number"&&(C=BigInt(C)),C},argPackAdvance:8,readValueFromPointer:Dr(l,f,l.indexOf("u")==-1),Bb:null})},O:function(n,l,f,b){n>>>=0,l=nt(l>>>0),Je(n,{name:l,fromWireType:function(C){return!!C},toWireType:function(C,k){return k?f:b},argPackAdvance:8,readValueFromPointer:function(C){return this.fromWireType(o()[C>>>0])},Bb:null})},N:function(n){return Je(n>>>0,Zn)},D:function(n,l,f){n>>>=0,f>>>=0,l=nt(l>>>0),Je(n,{name:l,fromWireType:b=>b,toWireType:(b,C)=>C,argPackAdvance:8,readValueFromPointer:an(l,f),Bb:null})},t:function(n,l,f,b,C){if(n>>>=0,f>>>=0,l=nt(l>>>0),C===-1&&(C=4294967295),C=F=>F,b===0){var k=32-8*f;C=F=>F<>>k}var V=l.includes("unsigned")?function(F,re){return re>>>0}:function(F,re){return re};Je(n,{name:l,fromWireType:C,toWireType:V,argPackAdvance:8,readValueFromPointer:Dr(l,f,b!==0),Bb:null})},p:function(n,l,f){function b(k){var V=c()[k>>>2>>>0];return k=c()[k+4>>>2>>>0],new C(r().buffer,k,V)}n>>>=0;var C=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][l];f=nt(f>>>0),Je(n,{name:f,fromWireType:b,argPackAdvance:8,readValueFromPointer:b},{Ub:!0})},F:function(n,l){n>>>=0,l=nt(l>>>0);var f=l==="std::string";Je(n,{name:l,fromWireType:function(b){var C=c()[b>>>2>>>0],k=b+4;if(f)for(var V=k,F=0;F<=C;++F){var re=k+F;if(F==C||o()[re>>>0]==0){if(V=He(V,re-V),J===void 0)var J=V;else J+=String.fromCharCode(0),J+=V;V=re+1}}else{for(J=Array(C),F=0;F>>0]);J=J.join("")}return At(b),J},toWireType:function(b,C){C instanceof ArrayBuffer&&(C=new Uint8Array(C));var k=typeof C=="string";if(!(k||C instanceof Uint8Array||C instanceof Uint8ClampedArray||C instanceof Int8Array))throw new wt("Cannot pass non-string to std::string");var V=f&&k?gt(C):C.length,F=mn(4+V+1),re=F+4;if(c()[F>>>2>>>0]=V,f&&k)Bt(C,re,V+1);else if(k)for(k=0;k>>0]=J}else for(k=0;k>>0]=C[k];return b!==null&&b.push(At,F),F},argPackAdvance:8,readValueFromPointer:Qt,Bb(b){At(b)}})},z:function(n,l,f){if(n>>>=0,l>>>=0,f>>>=0,f=nt(f),l===2)var b=Xn,C=sn,k=un,V=F=>u()[F>>>1>>>0];else l===4&&(b=gr,C=Qn,k=pe,V=F=>c()[F>>>2>>>0]);Je(n,{name:f,fromWireType:F=>{for(var re=c()[F>>>2>>>0],J,ce=F+4,Re=0;Re<=re;++Re){var ze=F+4+Re*l;(Re==re||V(ze)==0)&&(ce=b(ce,ze-ce),J===void 0?J=ce:(J+=String.fromCharCode(0),J+=ce),ce=ze+l)}return At(F),J},toWireType:(F,re)=>{if(typeof re!="string")throw new wt(`Cannot pass non-string to C++ string type ${f}`);var J=k(re),ce=mn(4+J+l);return c()[ce>>>2>>>0]=J/l,C(re,ce+4,J+l),F!==null&&F.push(At,ce),ce},argPackAdvance:8,readValueFromPointer:Qt,Bb(F){At(F)}})},P:function(n,l){n>>>=0,l=nt(l>>>0),Je(n,{Vb:!0,name:l,argPackAdvance:0,fromWireType:()=>{},toWireType:()=>{}})},ta:()=>1,S:function(n,l){n>>>=0,n==l>>>0?setTimeout(rt):O?postMessage({targetThread:n,cmd:"checkMailbox"}):(n=ge.ub[n])&&n.postMessage({cmd:"checkMailbox"})},$:function(n,l,f,b,C){l>>>=0,f>>>=0,b/=2,yr.length=b,C=C>>>0>>>3;for(var k=0;k>>0];return n=l?Ir[l]:el[n],ge.Sb=f,f=n(...yr),ge.Sb=0,f},ha:Nt,sa:function(n){P&&ge.ub[n>>>0].ref()},w:function(n,l,f){return l>>>=0,f>>>=0,n=Qe(n>>>0),l=br(l,"emval::as"),Ur(l,f,n)},y:function(n){return n>>>=0,te(()=>(n=Qe(n),n.then(ot)))},o:function(n,l,f,b){return f>>>=0,b>>>=0,n=X[n>>>0],l=Qe(l>>>0),n(null,l,f,b)},k:function(n,l,f,b,C){return f>>>=0,b>>>=0,C>>>=0,n=X[n>>>0],l=Qe(l>>>0),f=Ee(f),n(l,l[f],b,C)},c:hr,C:function(n,l){return l>>>=0,n=Qe(n>>>0),l=Qe(l),n==l},n:function(n){return n>>>=0,n===0?ot(Oe()):(n=Ee(n),ot(Oe()[n]))},j:function(n,l,f){l=be(n,l>>>0);var b=l.shift();n--;var C=`return function (obj, func, destructorsRef, args) {\n`,k=0,V=[];f===0&&V.push("obj");for(var F=["retType"],re=[b],J=0;Jce.name).join(", ")}) => ${b.name}>`,D(Ie(f,n))},s:function(n,l){return l>>>=0,n=Qe(n>>>0),l=Qe(l),ot(n[l])},d:function(n){n>>>=0,9>>0);for(var l=Array(n.length),f=0;f>>0))},l:function(){return ot({})},i:function(n){n>>>=0;for(var l=Qe(n);l.length;){var f=l.pop();l.pop()(f)}hr(n)},h:function(n,l,f){l>>>=0,f>>>=0,n=Qe(n>>>0),l=Qe(l),f=Qe(f),n[l]=f},e:function(n,l){return l>>>=0,n=br(n>>>0,"_emval_take_value"),n=n.readValueFromPointer(l),ot(n)},ca:function(n,l){n=-9007199254740992>n||9007199254740992>>=0,n=new Date(1e3*n),a()[l>>>2>>>0]=n.getUTCSeconds(),a()[l+4>>>2>>>0]=n.getUTCMinutes(),a()[l+8>>>2>>>0]=n.getUTCHours(),a()[l+12>>>2>>>0]=n.getUTCDate(),a()[l+16>>>2>>>0]=n.getUTCMonth(),a()[l+20>>>2>>>0]=n.getUTCFullYear()-1900,a()[l+24>>>2>>>0]=n.getUTCDay(),n=(n.getTime()-Date.UTC(n.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,a()[l+28>>>2>>>0]=n},da:function(n,l){n=-9007199254740992>n||9007199254740992>>=0,n=new Date(1e3*n),a()[l>>>2>>>0]=n.getSeconds(),a()[l+4>>>2>>>0]=n.getMinutes(),a()[l+8>>>2>>>0]=n.getHours(),a()[l+12>>>2>>>0]=n.getDate(),a()[l+16>>>2>>>0]=n.getMonth(),a()[l+20>>>2>>>0]=n.getFullYear()-1900,a()[l+24>>>2>>>0]=n.getDay();var f=(Mt(n.getFullYear())?Qo:Jo)[n.getMonth()]+n.getDate()-1|0;a()[l+28>>>2>>>0]=f,a()[l+36>>>2>>>0]=-(60*n.getTimezoneOffset()),f=new Date(n.getFullYear(),6,1).getTimezoneOffset();var b=new Date(n.getFullYear(),0,1).getTimezoneOffset();n=(f!=b&&n.getTimezoneOffset()==Math.min(b,f))|0,a()[l+32>>>2>>>0]=n},ea:function(n){n>>>=0;var l=new Date(a()[n+20>>>2>>>0]+1900,a()[n+16>>>2>>>0],a()[n+12>>>2>>>0],a()[n+8>>>2>>>0],a()[n+4>>>2>>>0],a()[n>>>2>>>0],0),f=a()[n+32>>>2>>>0],b=l.getTimezoneOffset(),C=new Date(l.getFullYear(),6,1).getTimezoneOffset(),k=new Date(l.getFullYear(),0,1).getTimezoneOffset(),V=Math.min(k,C);return 0>f?a()[n+32>>>2>>>0]=+(C!=k&&V==b):0>>2>>>0]=l.getDay(),f=(Mt(l.getFullYear())?Qo:Jo)[l.getMonth()]+l.getDate()-1|0,a()[n+28>>>2>>>0]=f,a()[n>>>2>>>0]=l.getSeconds(),a()[n+4>>>2>>>0]=l.getMinutes(),a()[n+8>>>2>>>0]=l.getHours(),a()[n+12>>>2>>>0]=l.getDate(),a()[n+16>>>2>>>0]=l.getMonth(),a()[n+20>>>2>>>0]=l.getYear(),n=l.getTime(),BigInt(isNaN(n)?-1:n/1e3)},aa:ei,ba:ti,R:function(n,l,f,b){n>>>=0,l>>>=0,f>>>=0,b>>>=0;var C=new Date().getFullYear(),k=new Date(C,0,1),V=new Date(C,6,1);C=k.getTimezoneOffset();var F=V.getTimezoneOffset(),re=Math.max(C,F);c()[n>>>2>>>0]=60*re,a()[l>>>2>>>0]=+(C!=F),n=J=>J.toLocaleTimeString(void 0,{hour12:!1,timeZoneName:"short"}).split(" ")[1],k=n(k),V=n(V),F{Kt("")},f:function(n,l,f){return n>>>=0,l=ri(l>>>0,f>>>0),Ir[n](...l)},M:function(n,l,f){return n>>>=0,l=ri(l>>>0,f>>>0),Ir[n](...l)},H:()=>{},L:()=>Date.now(),ra:()=>{throw bt+=1,"unwind"},T:function(){return 4294901760},u:()=>performance.timeOrigin+performance.now(),x:()=>P?(Ri(),wr(Oi)).cpus().length:navigator.hardwareConcurrency,Q:function(n){n>>>=0;var l=o().length;if(n<=l||4294901760=f;f*=2){var b=l*(1+.2/f);b=Math.min(b,n+100663296);var C=Math;b=Math.max(n,b);e:{C=(C.min.call(C,4294901760,b+(65536-b%65536)%65536)-ae.buffer.byteLength+65535)/65536;try{ae.grow(C),Ne();var k=1;break e}catch{}k=void 0}if(k)return!0}return!1},ja:oi,la:ii,Z:Xe,B:ai,J:si,ga:ui,I:di,a:ae||d.wasmMemory,ka:pi,r:function(n,l,f,b){return pi(n>>>0,l>>>0,f>>>0,b>>>0)}},oe=function(){function n(f,b){return oe=f.exports,oe=dn(),oe=rl(),ge.Qb.push(oe.cb),Rt.unshift(oe.va),Ae=b,xr(),oe}var l={a:tl};if(Vt++,d.instantiateWasm)try{return d.instantiateWasm(l,n)}catch(f){ee(`Module.instantiateWasm callback failed with error: ${f}`),w(f)}return Ar(l,function(f){n(f.instance,f.module)}).catch(w),{}}(),fi=n=>(fi=oe.wa)(n);d.__embind_initialize_bindings=()=>(d.__embind_initialize_bindings=oe.xa)(),d._OrtInit=(n,l)=>(d._OrtInit=oe.ya)(n,l),d._OrtGetLastError=(n,l)=>(d._OrtGetLastError=oe.za)(n,l),d._OrtCreateSessionOptions=(n,l,f,b,C,k,V,F,re,J)=>(d._OrtCreateSessionOptions=oe.Aa)(n,l,f,b,C,k,V,F,re,J),d._OrtAppendExecutionProvider=(n,l)=>(d._OrtAppendExecutionProvider=oe.Ba)(n,l),d._OrtAddFreeDimensionOverride=(n,l,f)=>(d._OrtAddFreeDimensionOverride=oe.Ca)(n,l,f),d._OrtAddSessionConfigEntry=(n,l,f)=>(d._OrtAddSessionConfigEntry=oe.Da)(n,l,f),d._OrtReleaseSessionOptions=n=>(d._OrtReleaseSessionOptions=oe.Ea)(n),d._OrtCreateSession=(n,l,f)=>(d._OrtCreateSession=oe.Fa)(n,l,f),d._OrtReleaseSession=n=>(d._OrtReleaseSession=oe.Ga)(n),d._OrtGetInputOutputCount=(n,l,f)=>(d._OrtGetInputOutputCount=oe.Ha)(n,l,f),d._OrtGetInputName=(n,l)=>(d._OrtGetInputName=oe.Ia)(n,l),d._OrtGetOutputName=(n,l)=>(d._OrtGetOutputName=oe.Ja)(n,l),d._OrtFree=n=>(d._OrtFree=oe.Ka)(n),d._OrtCreateTensor=(n,l,f,b,C,k)=>(d._OrtCreateTensor=oe.La)(n,l,f,b,C,k),d._OrtGetTensorData=(n,l,f,b,C)=>(d._OrtGetTensorData=oe.Ma)(n,l,f,b,C),d._OrtReleaseTensor=n=>(d._OrtReleaseTensor=oe.Na)(n),d._OrtCreateRunOptions=(n,l,f,b)=>(d._OrtCreateRunOptions=oe.Oa)(n,l,f,b),d._OrtAddRunConfigEntry=(n,l,f)=>(d._OrtAddRunConfigEntry=oe.Pa)(n,l,f),d._OrtReleaseRunOptions=n=>(d._OrtReleaseRunOptions=oe.Qa)(n),d._OrtCreateBinding=n=>(d._OrtCreateBinding=oe.Ra)(n),d._OrtBindInput=(n,l,f)=>(d._OrtBindInput=oe.Sa)(n,l,f),d._OrtBindOutput=(n,l,f,b)=>(d._OrtBindOutput=oe.Ta)(n,l,f,b),d._OrtClearBoundOutputs=n=>(d._OrtClearBoundOutputs=oe.Ua)(n),d._OrtReleaseBinding=n=>(d._OrtReleaseBinding=oe.Va)(n),d._OrtRunWithBinding=(n,l,f,b,C)=>(d._OrtRunWithBinding=oe.Wa)(n,l,f,b,C),d._OrtRun=(n,l,f,b,C,k,V,F)=>(d._OrtRun=oe.Xa)(n,l,f,b,C,k,V,F),d._OrtEndProfiling=n=>(d._OrtEndProfiling=oe.Ya)(n),d._JsepOutput=(n,l,f)=>(d._JsepOutput=oe.Za)(n,l,f),d._JsepGetNodeName=n=>(d._JsepGetNodeName=oe._a)(n);var pn=d._pthread_self=()=>(pn=d._pthread_self=oe.$a)(),mn=d._malloc=n=>(mn=d._malloc=oe.ab)(n),At=d._free=n=>(At=d._free=oe.bb)(n);d.__emscripten_tls_init=()=>(d.__emscripten_tls_init=oe.cb)();var hi=d.__emscripten_thread_init=(n,l,f,b,C,k)=>(hi=d.__emscripten_thread_init=oe.eb)(n,l,f,b,C,k);d.__emscripten_thread_crashed=()=>(d.__emscripten_thread_crashed=oe.fb)();var gi=(n,l,f,b,C)=>(gi=oe.gb)(n,l,f,b,C),ro=n=>(ro=oe.hb)(n),no=d.__emscripten_thread_exit=n=>(no=d.__emscripten_thread_exit=oe.ib)(n),yi=()=>(yi=oe.jb)(),bi=(n,l)=>(bi=oe.kb)(n,l),fn=n=>(fn=oe.lb)(n),oo=n=>(oo=oe.mb)(n),io=()=>(io=oe.nb)(),wi=d.dynCall_ii=(n,l)=>(wi=d.dynCall_ii=oe.pb)(n,l),vi=n=>(vi=oe.qb)(n),$i=()=>($i=oe.rb)(),_i=n=>(_i=oe.sb)(n),Si=()=>(Si=oe.tb)();d.___start_em_js=839500,d.___stop_em_js=839661;function rl(){var n=oe;n=Object.assign({},n);var l=b=>C=>b(C)>>>0,f=b=>()=>b()>>>0;return n.wa=l(n.wa),n.$a=f(n.$a),n.ab=l(n.ab),n.emscripten_main_runtime_thread_id=f(n.emscripten_main_runtime_thread_id),n.mb=l(n.mb),n.nb=f(n.nb),n}d.wasmMemory=ae,d.stackSave=()=>io(),d.stackRestore=n=>fn(n),d.stackAlloc=n=>oo(n),d.keepRuntimeAlive=()=>0Bi)});var Mi=Wr((gm,cl)=>{cl.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(...e){var a=e.join(" ");if(ENVIRONMENT_IS_NODE){fs.writeSync(2,a+`\\n`);return}console.error(a)}function threadAlert(...e){var a=e.join(" ");postMessage({cmd:"alert",text:a,threadId:Module._pthread_self()})}var err=threadPrintErr;self.alert=threadAlert,Module.instantiateWasm=(e,a)=>{var r=Module.wasmModule;Module.wasmModule=null;var t=new WebAssembly.Instance(r,e);return a(t)},self.onunhandledrejection=e=>{throw e.reason||e};function handleMessage(e){try{if(e.data.cmd==="load"){let r=[];self.onmessage=t=>r.push(t),self.startWorker=t=>{Module=t,postMessage({cmd:"loaded"});for(let s of r)handleMessage(s);self.onmessage=handleMessage},Module.wasmModule=e.data.wasmModule;for(const t of e.data.handlers)Module[t]=(...s)=>{postMessage({cmd:"callHandler",handler:t,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 a=URL.createObjectURL(e.data.urlOrBlob);importScripts(a),URL.revokeObjectURL(a)}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(r){if(r!="unwind")throw r}}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(r){throw Module.__emscripten_thread_crashed?.(),r}}self.onmessage=handleMessage;\\n\'});var go,Gt,tr,bn,Gr,Hi,yo,ye=Y(()=>{"use strict";go=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}`)}},Gt=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}`)}},tr=e=>[void 0,4,1,1,2,2,4,8,void 0,1,2,8,4,8,void 0,void 0,void 0][e],bn=e=>{switch(e){case"float16":return typeof Float16Array<"u"&&Float16Array.from?Float16Array: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}`)}},Gr=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}`)}},Hi=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool",yo=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 wn=Y(()=>{"use strict"});var Fi=Y(()=>{"use strict";wn()});var qi,ji=Y(()=>{"use strict";qi="1.18.0"});var Ki,pt,bo=Y(()=>{"use strict";ji();Ki="warning",pt={wasm:{},webgl:{},webgpu:{},versions:{common:qi},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}`);Ki=e}},get logLevel(){return Ki}};Object.defineProperty(pt,"logLevel",{enumerable:!0})});var vr,Yi=Y(()=>{"use strict";bo();vr=pt});var Zi=Y(()=>{"use strict"});var Xi=Y(()=>{"use strict";vn()});var Ji=Y(()=>{"use strict"});var ea=Y(()=>{"use strict";vn()});var vn=Y(()=>{"use strict";Zi();Xi();Ji();ea()});var $n=Y(()=>{"use strict";vn()});var wo,ta,rr,Ht,vo=Y(()=>{"use strict";bo();wo=(e,t)=>{(typeof pt.trace>"u"?!pt.wasm.trace:!pt.trace)||console.timeStamp(`${e}::ORT::${t}`)},ta=(e,t)=>{let r=new Error().stack?.split(/\\r\\n|\\r|\\n/g)||[],o=!1;for(let i=0;i{(typeof pt.trace>"u"?!pt.wasm.trace:!pt.trace)||ta("BEGIN",e)},Ht=e=>{(typeof pt.trace>"u"?!pt.wasm.trace:!pt.trace)||ta("END",e)}});var ra=Y(()=>{"use strict";wn();$n();vo()});var na=Y(()=>{"use strict";ra()});var oa=Y(()=>{"use strict"});var ia=Y(()=>{"use strict"});var aa=Y(()=>{"use strict"});var sa=Y(()=>{"use strict"});var ua=Y(()=>{"use strict";wn();$n()});var da=Y(()=>{"use strict";ua()});var $r=Y(()=>{"use strict";Fi();Yi();na();$n();oa();ia();vo();aa();sa();da()});var _l,Sl,la,ca,pa,xl,Ve,Lt=Y(()=>{"use strict";ye();_l=["V","I","W","E","F"],Sl=(e,t)=>{console.log(`[${_l[e]},${new Date().toISOString()}]${t}`)},pa=(e,t)=>{la=e,ca=t},xl=(e,t)=>{let r=Gr(e),o=Gr(la);r>=o&&Sl(r,typeof t=="function"?t():t)},Ve=(...e)=>{ca&&xl(...e)}});var ma,fa=Y(()=>{"use strict";ye();ma=(e,t)=>new(bn(t))(e)});var _n=Y(()=>{"use strict"});var ha,$o,_o,Cl,Al,ga,xo,So,ba,wa=Y(()=>{"use strict";Lt();_n();ha=new Map([[64,250],[128,200],[256,200],[512,200],[2048,230],[4096,200],[8192,50],[16384,50],[32768,50],[65536,50],[131072,50],[262144,50],[524288,50],[1048576,50],[2097152,30],[4194304,20],[8388608,10],[12582912,10],[16777216,10],[26214400,15],[33554432,22],[44236800,2],[58982400,6],[67108864,6],[134217728,6],[167772160,6]]),$o=[],_o=e=>Math.ceil(e/16)*16,Cl=e=>{for(let t=0;t<$o.length;t++){let r=$o[t];if(e<=r)return r}return Math.ceil(e/16)*16},Al=1,ga=()=>Al++,xo=async(e,t,r,o)=>{let i=_o(r),u=e.device.createBuffer({size:i,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let a=e.getCommandEncoder();e.endComputePass(),a.copyBufferToBuffer(t,0,u,0,i),e.flush(),await u.mapAsync(GPUMapMode.READ);let c=u.getMappedRange();if(o){let p=o();return p.set(new Uint8Array(c,0,r)),p}else return new Uint8Array(c.slice(0,r))}finally{u.destroy()}},So=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,this.capturedPendingBuffers=new Map;for(let[r]of ha)$o.push(r),this.freeBuffers.set(r,[]),this.freeUniformBuffers.set(r,[])}upload(t,r){let o=r.buffer,i=r.byteOffset,u=r.byteLength,a=_o(u),c=this.storageCache.get(t);if(!c)throw new Error("gpu data for uploading does not exist");if(c.originalSize!==u)throw new Error(`inconsistent data size. gpu data size=${c.originalSize}, data size=${u}`);let p=this.backend.device.createBuffer({mappedAtCreation:!0,size:a,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),h=p.getMappedRange();new Uint8Array(h).set(new Uint8Array(o,i,u)),p.unmap();let d=this.backend.getCommandEncoder();this.backend.endComputePass(),d.copyBufferToBuffer(p,0,c.gpuData.buffer,0,a),Ve("verbose",()=>`[WebGPU] GpuDataManager.upload(id=${t})`),this.buffersForUploadingPending.push(p)}memcpy(t,r){let o=this.storageCache.get(t);if(!o)throw new Error("source gpu data for memcpy does not exist");let i=this.storageCache.get(r);if(!i)throw new Error("destination gpu data for memcpy does not exist");if(o.originalSize!==i.originalSize)throw new Error("inconsistent source and destination gpu data size");let u=_o(o.originalSize),a=this.backend.getCommandEncoder();this.backend.endComputePass(),a.copyBufferToBuffer(o.gpuData.buffer,0,i.gpuData.buffer,0,u)}registerExternalBuffer(t,r,o){let i;if(o){if(i=this.externalBuffers.get(o),i===void 0)throw new Error("previous buffer is not registered");if(t===o)return Ve("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${r}) => id=${i}, buffer is the same, skip.`),i;if(this.backend.capturedCommandList.has(this.backend.currentSessionId))throw new Error(`Registering a different external buffer under graph capture mode is not supported yet.\n Please use the previous external buffer!`);this.externalBuffers.delete(o)}else i=ga();return this.storageCache.set(i,{gpuData:{id:i,type:0,buffer:t},originalSize:r}),this.externalBuffers.set(t,i),Ve("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${r}) => id=${i}, registered.`),i}unregisterExternalBuffer(t){let r=this.externalBuffers.get(t);r!==void 0&&(this.storageCache.delete(r),this.externalBuffers.delete(t),Ve("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${r}`))}create(t,r=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let o=Cl(t),i,u=(r&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,a=(r&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(u||a){let h=(u?this.freeBuffers:this.freeUniformBuffers).get(o);h?h.length>0?i=h.pop():i=this.backend.device.createBuffer({size:o,usage:r}):i=this.backend.device.createBuffer({size:o,usage:r})}else i=this.backend.device.createBuffer({size:o,usage:r});let c={id:ga(),type:0,buffer:i};return this.storageCache.set(c.id,{gpuData:c,originalSize:t}),Ve("verbose",()=>`[WebGPU] GpuDataManager.create(size=${t}) => id=${c.id}`),c}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 Ve("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 xo(this.backend,o.gpuData.buffer,o.originalSize,r)}refreshPendingBuffers(){for(let t of this.buffersForUploadingPending)t.destroy();if(this.buffersForUploadingPending=[],this.buffersPending.length!==0)if(this.backend.sessionStatus==="default"){for(let t of this.buffersPending){let r=ha.get(t.size);if((t.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE){let o=this.freeBuffers.get(t.size)||[];r===void 0||o.length>=r?t.destroy():o.push(t)}else if((t.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM){let o=this.freeUniformBuffers.get(t.size)||[];r===void 0||o.length>=r?t.destroy():o.push(t)}else t.destroy()}this.buffersPending=[]}else{let t=this.capturedPendingBuffers.get(this.backend.currentSessionId);t||(t=[],this.capturedPendingBuffers.set(this.backend.currentSessionId,t));for(let r of this.buffersPending)t.push(r);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.capturedPendingBuffers.forEach(t=>{t.forEach(r=>{r.destroy()})}),this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.capturedPendingBuffers=new Map}onReleaseSession(t){let r=this.capturedPendingBuffers.get(t);r&&(r.forEach(o=>{o.destroy()}),this.capturedPendingBuffers.delete(t))}},ba=(...e)=>new So(...e)});var Co,ve,Ze=Y(()=>{"use strict";Co=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}},ve=e=>new Co(e)});var Ao,It,M,nr,Sn,xn,Cn,Se=Y(()=>{"use strict";Ao=class{static calcMatMulShape(t,r){return t[1]!==r[0]?void 0:[t[0],r[1]]}},It=class{static calcShape(t,r,o=!1){let i=t.length,u=r.length;if(i===0)return r;if(u===0)return t;let a=Math.max(t.length,r.length),c=new Array(a);if(o){if(i<2||u<2)return;let p=Ao.calcMatMulShape([t[i-2],t[i-1]],[r[u-2],r[u-1]]);if(p===void 0)return;[c[a-2],c[a-1]]=p}for(let p=o?3:1;p<=a;p++){let h=i-p<0?1:t[i-p],d=u-p<0?1:r[u-p];if(h!==d&&h>1&&d>1)return;let y=Math.max(h,d);if(h&&d)c[a-p]=Math.max(h,d);else{if(y>1)return;c[a-p]=0}}return c}static isValidBroadcast(t,r){let o=t.length,i=r.length;if(o>i)return!1;for(let u=1;u<=o;u++)if(t[o-u]!==1&&t[o-u]!==r[i-u])return!1;return!0}},M=class e{static size(t){return e.getSizeFromDimensionRange(t,0,t.length)}static convertShape(t,r=4){let o=t.length;if(o===0)return[];let i=new Array(o),u=o-1;for(;u>=0;){if(t[u]%r===0){i[u]=t[u]/r;break}if(r%t[u]!==0)throw new Error("cannot convert shape");i[u]=1,r/=t[u],u--}for(u--;u>=0;u--)i[u]=t[u];return i}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 i=1;for(let u=r;u=0;--i)o[i]=o[i+1]*t[i+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((i,u)=>i+r[u]+r[u+o])}static areEqual(t,r){return t.length!==r.length?!1:t.every((o,i)=>o===r[i])}},nr=class e{static adjustPoolAttributes(t,r,o,i,u,a){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 c=0;c=o.length?o.push(r[c+2]):o[c]=r[c+2];for(let c=0;c=o[c]||a[c+o.length]>=o[c])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(t,r,o,i,u,a,c){if(c){if(u.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(i.length!==t.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let p=0;p{"use strict";ye();Se();or=64,To=(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}`)}},De=(e,t=1)=>{let r=To(e,t);return typeof r=="string"?r:r[0]},et=(e,t=1)=>{let r=To(e,t);return typeof r=="string"?r:r[1]},Z=(...e)=>{let t=[];return e.forEach(r=>{r.length!==0&&t.push({type:12,data:r},{type:12,data:M.computeStrides(r)})}),t},Me=e=>e%4===0?4:e%2===0?2:1,$t=(e="f32",t,r="0")=>!t||t===1?`${e}(${r})`:`vec${t}<${e}>(${r})`,ir=(e,t,r)=>e==="f32"?r:t===1?`f32(${r})`:`vec${t}(${r})`,_t=(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,fe=(e,t,r,o)=>e.startsWith("uniforms.")&&r>4?typeof t=="string"?o==="f16"?`${e}[(${t}) / 8][(${t}) % 8 / 4][(${t}) % 8 % 4]`:`${e}[(${t}) / 4][(${t}) % 4]`:o==="f16"?`${e}[${Math.floor(t/8)}][${Math.floor(t%8/4)}][${t%8%4}]`:`${e}[${Math.floor(t/4)}][${t%4}]`:r>1?`${e}[${t}]`:e,Eo=(e,t,r,o,i)=>{let u=typeof r=="number",a=u?r:r.length,c=[...new Array(a).keys()],p=a<2?"u32":a<=4?`vec${a}`:`array`,h=To(t,i),d=typeof h=="string"?h:h[1],y=typeof h=="string"?h:h[0],w={indices:p,value:d,storage:y,tensor:t},_=G=>typeof G=="string"?G:`${G}u`,v={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},S=u?"uniforms.":"",A=`${S}${e}_shape`,I=`${S}${e}_strides`,x="";for(let G=0;G ${w.indices} {\n var indices: ${w.indices};\n var current = offset;\n ${x}\n return indices;\n }`,P=G=>(v.offsetToIndices=!0,a<2?G:`o2i_${e}(${G})`),O=[];if(a>=2)for(let G=a-1;G>=0;G--)O.push(`${fe(I,G,a)} * (indices[${G}])`);let R=a<2?"":`\n fn i2o_${e}(indices: ${w.indices}) -> u32 {\n return ${O.join("+")};\n }`,L=G=>(v.indicesToOffset=!0,a<2?G:`i2o_${e}(${G})`),N=(...G)=>a===0?"0u":`${w.indices}(${G.map(_).join(",")})`,K=(G,ne)=>a<2?`${G}`:`${fe(G,ne,a)}`,Q=(G,ne,xe)=>a<2?`${G}=${xe};`:`${fe(G,ne,a)}=${xe};`,he={},W=(G,ne)=>{v.broadcastedIndicesToOffset=!0;let xe=`${ne.name}broadcastedIndicesTo${e}Offset`;if(xe in he)return`${xe}(${G})`;let Ke=[];for(let Be=a-1;Be>=0;Be--){let Ge=ne.indicesGet("outputIndices",Be+ne.rank-a);Ke.push(`${K(I,Be)} * (${Ge} % ${K(A,Be)})`)}return he[xe]=`fn ${xe}(outputIndices: ${ne.type.indices}) -> u32 {\n return ${Ke.length>0?Ke.join("+"):"0u"};\n }`,`${xe}(${G})`},se=(G,ne)=>(()=>{if(w.storage===w.value)return`${e}[${G}]=${ne};`;if(w.storage==="vec2"&&w.value==="i32")return`${e}[${G}]=vec2(u32(${ne}), select(0u, 0xFFFFFFFFu, ${ne} < 0));`;if(w.storage==="vec2"&&w.value==="u32")return`${e}[${G}]=vec2(u32(${ne}), 0u);`;if(w.storage==="u32"&&w.value==="vec4")return`${e}[${G}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${ne}));`;throw new Error(`not supported combination of storage type ${w.storage} and value type ${w.value} yet`)})(),Ce=G=>(()=>{if(w.storage===w.value)return`${e}[${G}]`;if(w.storage==="vec2"&&w.value==="i32")return`i32(${e}[${G}].x)`;if(w.storage==="vec2"&&w.value==="u32")return`u32(${e}[${G}].x)`;if(w.storage==="u32"&&w.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 ${w.storage} and value type ${w.value} yet`)})(),We=a<2?"":`\n fn get_${e}ByIndices(indices: ${w.indices}) -> ${d} {\n return ${Ce(`i2o_${e}(indices)`)};\n }`,ee=a<2?"":(()=>{let G=c.map(xe=>`d${xe}: u32`).join(", "),ne=c.map(xe=>`d${xe}`).join(", ");return`\n fn get_${e}(${G}) -> ${d} {\n return get_${e}ByIndices(${N(ne)});\n }`})(),ae=(...G)=>{if(G.length!==a)throw new Error(`indices length must be ${a}`);let ne=G.map(_).join(",");return a===0?Ce("0u"):a===1?Ce(ne[0]):(v.get=!0,v.getByIndices=!0,v.indicesToOffset=!0,`get_${e}(${ne})`)},Ae=G=>a<2?Ce(G):(v.getByIndices=!0,v.indicesToOffset=!0,`get_${e}ByIndices(${G})`),me=a<2?"":`\n fn set_${e}ByIndices(indices: ${w.indices}, value: ${d}) {\n ${se(`i2o_${e}(indices)`,"value")}\n }`,ie=a<2?"":(()=>{let G=c.map(xe=>`d${xe}: u32`).join(", "),ne=c.map(xe=>`d${xe}`).join(", ");return`\n fn set_${e}(${G}, value: ${d}) {\n set_${e}ByIndices(${N(ne)}, value);\n }`})();return{impl:()=>{let G=[],ne=!1;return v.offsetToIndices&&(G.push(E),ne=!0),v.indicesToOffset&&(G.push(R),ne=!0),v.broadcastedIndicesToOffset&&(Object.values(he).forEach(xe=>G.push(xe)),ne=!0),v.set&&(G.push(ie),ne=!0),v.setByIndices&&(G.push(me),ne=!0),v.get&&(G.push(ee),ne=!0),v.getByIndices&&(G.push(We),ne=!0),!u&&ne&&G.unshift(`const ${A} = ${w.indices}(${r.join(",")});`,`const ${I} = ${w.indices}(${M.computeStrides(r).join(",")});`),G.join(`\n`)},type:w,offsetToIndices:P,indicesToOffset:L,broadcastedIndicesToOffset:W,indices:N,indicesGet:K,indicesSet:Q,set:(...G)=>{if(G.length!==a+1)throw new Error(`indices length must be ${a}`);let ne=G[a];if(typeof ne!="string")throw new Error("value must be string");let xe=G.slice(0,a).map(_).join(",");return a===0?se("0u",ne):a===1?se(xe[0],ne):(v.set=!0,v.setByIndices=!0,v.indicesToOffset=!0,`set_${e}(${xe}, ${ne})`)},setByOffset:se,setByIndices:(G,ne)=>a<2?se(G,ne):(v.setByIndices=!0,v.indicesToOffset=!0,`set_${e}ByIndices(${G}, ${ne});`),get:ae,getByOffset:Ce,getByIndices:Ae,usage:o,name:e,strides:I,shape:A,rank:a}},U=(e,t,r,o=1)=>Eo(e,t,r,"input",o),j=(e,t,r,o=1)=>Eo(e,t,r,"output",o),An=(e,t,r,o=1)=>Eo(e,t,r,"internal",o),Io=class{constructor(t,r){this.normalizedDispatchGroup=t;this.limits=r;this.internalVariables=[];this.variables=[];this.uniforms=[];this.variableIndex=0}guardAgainstOutOfBoundsWorkgroupSizes(t){return`if (global_idx >= ${typeof t=="number"?`${t}u`:t}) { return; }`}mainStart(t=or){let r=typeof t=="number"?t:t[0],o=typeof t=="number"?1:t[1],i=typeof t=="number"?1:t[2];if(r>this.limits.maxComputeWorkgroupSizeX||o>this.limits.maxComputeWorkgroupSizeY||i>this.limits.maxComputeWorkgroupSizeZ)throw new Error(`workgroup size [${r}, ${o}, ${i}] exceeds the maximum workgroup size [${this.limits.maxComputeWorkgroupSizeX}, ${this.limits.maxComputeWorkgroupSizeY}, ${this.limits.maxComputeWorkgroupSizeZ}].`);if(r*o*i>this.limits.maxComputeInvocationsPerWorkgroup)throw new Error(`workgroup size [${r}, ${o}, ${i}] exceeds the maximum workgroup invocations ${this.limits.maxComputeInvocationsPerWorkgroup}.`);let u=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1,a=u?`@builtin(global_invocation_id) global_id : vec3,\n @builtin(workgroup_id) workgroup_id : vec3,\n @builtin(local_invocation_id) local_id : vec3`:`@builtin(global_invocation_id) global_id : vec3,\n @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`,c=u?"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*i}u + local_idx;`;return`@compute @workgroup_size(${r}, ${o}, ${i})\n fn main(${a}) {\n ${c}\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",i=t.type.storage;return`@group(0) @binding(${r}) var ${t.name}: array<${i}>;`}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:i}of this.uniforms)if(i&&i>4)o==="f16"?t.push(`@align(16) ${r}:array, ${Math.ceil(i/8)}>`):t.push(`${r}:array, ${Math.ceil(i/4)}>`);else{let u=i==null||i===1?o:`vec${i}<${o}>`;t.push(`${r}:${u}`)}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`)}get variablesInfo(){if(this.uniforms.length===0)return;let t=r=>[12,10,1,6][["u32","f16","f32","i32"].indexOf(r)];return this.uniforms.map(r=>[t(r.type),r.length??1])}},va=(e,t)=>new Io(e,t),_r=(e,t)=>{let r=e.length,o=[];for(let i=0;i1&&a===1&&o.unshift(u)}return o}});var Il,$a,Tl,El,yt,_a,Sa,Sr=Y(()=>{"use strict";ye();Se();Ze();_e();Il=e=>{if(!e||e.length!==1)throw new Error("Transpose requires 1 input.")},$a=(e,t)=>t&&t.length!==e?[...new Array(e).keys()].reverse():t,Tl=(e,t)=>M.sortBasedOnPerm(e,$a(e.length,t)),El=(e,t,r,o)=>{let i=[];i.push(`fn perm(i: ${o.type.indices}) -> ${r.type.indices} {\n var a: ${r.type.indices};`);for(let u=0;u{let r=e.dataType,o=e.dims.length,i=$a(o,t),u=Tl(e.dims,i),a=j("output",r,u.length),c=U("a",r,o),p=h=>`\n ${h.registerUniform("output_size","u32").declareVariables(c,a)}\n\n ${El(i,o,c,a)}\n\n ${h.mainStart()}\n ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n\n let indices = ${a.offsetToIndices("global_idx")};\n let aIndices = perm(indices);\n\n ${a.setByOffset("global_idx",c.getByIndices("aIndices"))}\n }`;return{name:"Transpose",shaderCache:{hint:`${t}`,inputDependencies:["rank"]},getRunData:h=>{let d=M.size(u);return{outputs:[{dims:u,dataType:h[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:[{type:12,data:d},...Z(h[0].dims,u)]}},getShaderSource:p}},_a=(e,t)=>{Il(e.inputs),e.compute(yt(e.inputs[0],t.perm))},Sa=e=>ve({perm:e.perm})});var Pl,kl,Ol,Rl,Bl,Dl,zl,Ml,Ul,Vl,Tt,xa,Ca,Aa,Ia,Ta,Ea,Pa,ka,Oa,Ra,Ba=Y(()=>{"use strict";ye();Se();_e();In();Sr();Pl={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"},kl={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"},Ol={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},Rl={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},Bl=(e,t)=>{let r=[];for(let o=t-e;o{let r=[],o=e.length;for(let u=0;ue[u]);return[r,i]},zl=(e,t)=>{let r=e.length+t.length,o=[],i=0;for(let u=0;u{for(let r=0;r{let r=[];if(!Ml(e,t)){for(let o=0;or.push(o))}return r},Vl=(e,t,r,o,i,u,a)=>{let c=r[0].dims,p=M.size(u),h=M.size(a),d=U("_A",r[0].dataType,c),y=j("output",i,u),w=32,_=`\n var aBestValues : array;\n `;return{name:e,shaderCache:t,getShaderSource:S=>`\n ${S.registerUniform("reduceSize","u32").declareVariables(d,y)}\n ${_}\n fn DIV_CEIL(a : u32, b : u32) -> u32 {\n return ((a - 1u) / b + 1u);\n }\n ${S.mainStart(w)}\n\n let outputIndex = global_idx / ${w};\n let offset = outputIndex * uniforms.reduceSize;\n\n var bestValue = f32(${Ol[o]});\n let Length = uniforms.reduceSize;\n for (var k = local_idx; k < Length; k = k + ${w}) {\n let candidate = f32(${d.getByOffset("offset + k")});\n bestValue = ${Pl[o]};\n }\n aBestValues[local_idx] = bestValue;\n workgroupBarrier();\n\n var reduceSize = min(Length, ${w}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 = ${kl[o]};\n aBestValues[local_idx] = bestValue;\n }\n reduceSize = interval;\n workgroupBarrier();\n }\n\n if (local_idx == 0u) {\n ${y.setByOffset("outputIndex",`${o==="mean"?`${y.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${y.type.storage}(${Rl[o]})`}`)};\n }\n }`,getRunData:()=>({outputs:[{dims:u,dataType:i}],dispatchGroup:{x:p},programUniforms:[{type:12,data:h}]})}},Tt=(e,t,r,o)=>{let i=e.inputs.length===1?r:Po(e.inputs,r),u=i.axes;u.length===0&&!i.noopWithEmptyAxes&&(u=e.inputs[0].dims.map((_,v)=>v));let a=M.normalizeAxes(u,e.inputs[0].dims.length),c=a,p=e.inputs[0],h=Ul(c,e.inputs[0].dims.length);h.length>0&&(p=e.compute(yt(e.inputs[0],h),{inputs:[0],outputs:[-1]})[0],c=Bl(c.length,p.dims.length));let[d,y]=Dl(p.dims,c),w=d;i.keepDims&&(w=zl(d,a)),e.compute(Vl(t,{hint:i.cacheKey,inputDependencies:["type"]},[p],o,e.inputs[0].dataType,w,y),{inputs:[p]})},xa=(e,t)=>{Tt(e,"ReduceMeanShared",t,"mean")},Ca=(e,t)=>{Tt(e,"ReduceL1Shared",t,"l1")},Aa=(e,t)=>{Tt(e,"ReduceL2Shared",t,"l2")},Ia=(e,t)=>{Tt(e,"ReduceLogSumExpShared",t,"logSumExp")},Ta=(e,t)=>{Tt(e,"ReduceMaxShared",t,"max")},Ea=(e,t)=>{Tt(e,"ReduceMinShared",t,"min")},Pa=(e,t)=>{Tt(e,"ReduceProdShared",t,"prod")},ka=(e,t)=>{Tt(e,"ReduceSumShared",t,"sum")},Oa=(e,t)=>{Tt(e,"ReduceSumSquareShared",t,"sumSquare")},Ra=(e,t)=>{Tt(e,"ReduceLogSumShared",t,"logSum")}});var Et,Wl,Tn,Po,Pt,Nl,Gl,Hl,Ll,Fl,ql,jl,Kl,Yl,Zl,kt,Da,za,Ma,Ua,Va,Wa,Na,Ga,Ha,La,In=Y(()=>{"use strict";ye();Se();Ze();_e();Ba();Et=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.")},Wl=e=>["","",`var value = ${e.getByIndices("input_indices")};`,""],Tn=(e,t,r,o,i,u,a=!1,c=!1)=>{let p=[],h=r[0].dims,d=h.length,y=M.normalizeAxes(i,d),w=!c&&y.length===0;h.forEach((A,I)=>{w||y.indexOf(I)>=0?a&&p.push(1):p.push(A)});let _=p.length,v=M.size(p);return{name:e,shaderCache:t,getShaderSource:A=>{let I=[],x=U("_A",r[0].dataType,d),E=j("output",u,_),P=o(x,E,y),O=P[2];for(let R=0,L=0;R=0?(a&&L++,O=`for(var j${R}: u32 = 0; j${R} < ${h[R]}; j${R}++) {\n ${P[2].includes("last_index")?`let last_index = j${R};`:""}\n ${x.indicesSet("input_indices",R,`j${R}`)}\n ${O}\n }`):(I.push(`${x.indicesSet("input_indices",R,E.indicesGet("output_indices",L))};`),L++);return`\n\n ${A.registerUniform("output_size","u32").declareVariables(x,E)}\n\n ${A.mainStart()}\n ${A.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n var input_indices: ${x.type.indices};\n let output_indices = ${E.offsetToIndices("global_idx")};\n\n ${I.join(`\n`)}\n ${P[0]} // init ops for reduce max/min\n ${P[1]}\n ${O}\n ${P[3]}\n ${P.length===4?E.setByOffset("global_idx","value"):P.slice(4).join(`\n`)}\n }`},getRunData:()=>({outputs:[{dims:p,dataType:u}],dispatchGroup:{x:Math.ceil(v/64)},programUniforms:[{type:12,data:v},...Z(h,p)]})}},Po=(e,t)=>{let r=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach(o=>r.push(Number(o))),ve({axes:r,keepDims:t.keepDims,noopWithEmptyAxes:t.noopWithEmptyAxes})},Pt=(e,t,r,o)=>{let i=e.inputs,u=i.length===1?r:Po(i,r);e.compute(Tn(t,{hint:u.cacheKey,inputDependencies:["rank"]},[i[0]],u.noopWithEmptyAxes&&u.axes.length===0?Wl:o,u.axes,i[0].dataType,u.keepDims,u.noopWithEmptyAxes),{inputs:[0]})},Nl=(e,t)=>{Et(e.inputs),Pt(e,"ReduceLogSum",t,(o,i)=>[`var value = ${i.type.storage}(0);`,"",`value += ${o.getByIndices("input_indices")};`,"value = log(value);"])},Gl=(e,t)=>{Et(e.inputs),Pt(e,"ReduceL1",t,(o,i)=>[`var value = ${i.type.storage}(0);`,"",`value += abs(${o.getByIndices("input_indices")});`,""])},Hl=(e,t)=>{Et(e.inputs),Pt(e,"ReduceL2",t,(o,i)=>[`var t = ${i.type.value}(0); var value = ${i.type.value}(0);`,"",`t = ${o.getByIndices("input_indices")}; value += (t * t);`,"value = sqrt(value);"])},Ll=(e,t)=>{Et(e.inputs),Pt(e,"ReduceLogSumExp",t,(o,i)=>[`var value = ${i.type.storage}(0);`,"",`value += exp(${o.getByIndices("input_indices")});`,"value = log(value);"])},Fl=(e,t)=>{Et(e.inputs),Pt(e,"ReduceMax",t,(o,i,u)=>{let a=[];for(let c=0;c=0||u.length===0)&&a.push(o.indicesSet("input_indices",c,0));return[`${a.join(`\n`)}`,`var value = ${o.getByIndices("input_indices")};`,`value = max(value, ${o.getByIndices("input_indices")});`,""]})},ql=(e,t)=>{Et(e.inputs),Pt(e,"ReduceMean",t,(o,i,u)=>{let a=1;for(let c=0;c=0||u.length===0)&&(a*=e.inputs[0].dims[c]);return["var sum = f32(0);","",`sum += f32(${o.getByIndices("input_indices")});`,`let value = ${i.type.value}(sum / ${a});`]})},jl=(e,t)=>{Et(e.inputs),Pt(e,"ReduceMin",t,(o,i,u)=>{let a=[];for(let c=0;c=0||u.length===0)&&a.push(`input_indices[${c}] = 0;`);return[`${a.join(`\n`)}`,`var value = ${o.getByIndices("input_indices")};`,`value = min(value, ${o.getByIndices("input_indices")});`,""]})},Kl=(e,t)=>{Et(e.inputs),Pt(e,"ReduceProd",t,(o,i)=>[`var value = ${i.type.storage}(1);`,"",`value *= ${o.getByIndices("input_indices")};`,""])},Yl=(e,t)=>{Et(e.inputs),Pt(e,"ReduceSum",t,(o,i)=>[`var value = ${i.type.storage}(0);`,"",`value += ${o.getByIndices("input_indices")};`,""])},Zl=(e,t)=>{Et(e.inputs),Pt(e,"ReduceSumSquare",t,(o,i)=>[`var t = ${i.type.value}(0); var value = ${i.type.value}(0);`,"",`t = ${o.getByIndices("input_indices")}; value += t * t;`,""])},kt=(e,t,r)=>{if(t.length===0)return r;let o=1,i=1;for(let u=0;u1024},Da=(e,t)=>{kt(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?ql(e,t):xa(e,t)},za=(e,t)=>{kt(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Gl(e,t):Ca(e,t)},Ma=(e,t)=>{kt(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Hl(e,t):Aa(e,t)},Ua=(e,t)=>{kt(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Ll(e,t):Ia(e,t)},Va=(e,t)=>{kt(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Fl(e,t):Ta(e,t)},Wa=(e,t)=>{kt(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?jl(e,t):Ea(e,t)},Na=(e,t)=>{kt(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Kl(e,t):Pa(e,t)},Ga=(e,t)=>{kt(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Yl(e,t):ka(e,t)},Ha=(e,t)=>{kt(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Zl(e,t):Oa(e,t)},La=(e,t)=>{kt(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Nl(e,t):Ra(e,t)}});var Fa,qa,ja,ko,Ka=Y(()=>{"use strict";ye();Ze();In();Fa=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.")},qa=(e,t)=>{Fa(e.inputs);let r=(o,i,u)=>{let a=[];for(let c=0;c=0||u.length===0)&&a.push(`input_indices[${c}] = 0;`);return[`${a.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 }`,"",i.setByOffset("global_idx","best_index")]};e.compute(Tn("ArgMin",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],r,[t.axis],7,t.keepDims),{inputs:[0]})},ja=(e,t)=>{Fa(e.inputs);let r=(o,i,u)=>{let a=[];for(let c=0;c=0||u.length===0)&&a.push(`input_indices[${c}] = 0;`);return[`${a.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 }`,"",i.setByOffset("global_idx","best_index")]};e.compute(Tn("argMax",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],r,[t.axis],7,t.keepDims),{inputs:[0]})},ko=e=>ve(e)});var Xl,Ql,Jl,En,Ya,Za,Oo=Y(()=>{"use strict";ye();Se();Ze();_e();Xl=(e,t)=>{if(!e||e.length<1)throw new Error("too few inputs");let r=0,o=e[r],i=o.dataType,u=o.dims.length;e.forEach((a,c)=>{if(c!==r){if(a.dataType!==i)throw new Error("input tensors should be one type");if(a.dims.length!==u)throw new Error("input tensors should have the same shape");a.dims.forEach((p,h)=>{if(h!==t&&p!==o.dims[h])throw new Error("non concat dimensions must match")})}})},Ql=(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 }`,Jl=(e,t)=>{let r=e.length,o=[];for(let i=0;i{let i=M.size(r),u=new Array(e.length),a=new Array(e.length),c=0,p=[],h=[],d=[{type:12,data:i}];for(let S=0;S`uniforms.sizeInConcatAxis${S}`).join(","),v=S=>`\n\n ${(()=>{S.registerUniform("outputSize","u32");for(let A=0;A(${_});\n ${w} -= sizeInConcatAxis[inputIndex - 1u];\n }\n\n ${Jl(a,y)}\n }`;return{name:"Concat",shaderCache:{hint:`${t}`,inputDependencies:p},getRunData:()=>({outputs:[{dims:r,dataType:o}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:d}),getShaderSource:v}},Ya=(e,t)=>{let r=e.inputs,o=r[0].dims,i=M.normalizeAxis(t.axis,o.length);Xl(r,i);let u=o.slice();u[i]=r.reduce((c,p)=>c+(p.dims.length>i?p.dims[i]:0),0);let a=r.filter(c=>M.size(c.dims)>0);e.compute(En(a,i,u,r[0].dataType),{inputs:a})},Za=e=>ve({axis:e.axis})});var ec,tc,rc,nc,Pn,oc,Xa,Ro=Y(()=>{"use strict";ye();_n();_e();Oo();ec=(e,t)=>{let r=e[0],o=e[1],i=e[2],u=e[3],a=e[4],c=e[5];if(a&&c)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 p=r.dims[0],h=r.dims[1],d=r.dims[2];if(i.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]!==d)throw new Error("Input 1 dimension 0 should have same length as dimension 2 of input 0");if(i.dims[0]!==o.dims[1])throw new Error(\'Input "bias" dimension 0 should have same length as dimension 1 of input "weights"\');let y=i.dims[0]/3,w=y,_=w;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");y=t.qkvHiddenSizes[0],w=t.qkvHiddenSizes[1],_=t.qkvHiddenSizes[2]}let v=h;if(y!==w)throw new Error("qkv_hidden_sizes first element should be same as the second");if(i.dims[0]!==y+w+_)throw new Error(\'Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes\');let S=0;if(a){if(w!==_)throw new Error(\'Input "past" expect k_hidden_size == v_hidden_size\');if(a.dims.length!==5)throw new Error(\'Input "past" must have 5 dimensions\');if(a.dims[0]!==2)throw new Error(\'Input "past" first dimension must be 2\');if(a.dims[1]!==p)throw new Error(\'Input "past" second dimension must be batch_size\');if(a.dims[2]!==t.numHeads)throw new Error(\'Input "past" third dimension must be num_heads\');if(a.dims[4]!==w/t.numHeads)throw new Error(\'Input "past" fifth dimension must be k_hidden_size / num_heads\');t.pastPresentShareBuffer||(S=a.dims[3])}let A=v+S,I=-1,x=0;if(u)throw new Error("Mask not supported");if(a)throw new Error("past is not supported");return{batchSize:p,sequenceLength:h,pastSequenceLength:S,kvSequenceLength:v,totalSequenceLength:A,maxSequenceLength:I,inputHiddenSize:d,hiddenSize:y,vHiddenSize:_,headSize:Math.floor(y/t.numHeads),vHeadSize:Math.floor(_/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:x,scale:t.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},tc=(e,t,r,o)=>{let i=Me(o),u=64,a=o/i;a{let _=j("x",t.dataType,t.dims,i),S=[{name:"d_inv",type:et(t.dataType)},{name:"d_comp",type:"u32"},{name:"elements_per_thread",type:"u32"}];return`\n var thread_max: array;\n var thread_sum: array;\n ${w.registerUniforms(S).declareVariables(_)}\n ${w.mainStart([u,1,1])}\n let local_offset = local_idx * uniforms.elements_per_thread;\n let offset = workgroup_id.x * uniforms.d_comp + local_offset;\n\n var thread_max_vector = ${d}(-3.402823e+38f);\n for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) {\n thread_max_vector = max(${d}(x[offset + i]), thread_max_vector);\n }\n thread_max[local_idx] = ${(()=>{switch(i){case 1:return"thread_max_vector";case 2:return"max(thread_max_vector.x, thread_max_vector.y)";case 4:return"max(max(thread_max_vector.x, thread_max_vector.y), max(thread_max_vector.z, thread_max_vector.w))";default:throw new Error(`Unsupported components: ${i}`)}})()};\n workgroupBarrier();\n\n var max_value = f32(-3.402823e+38f);\n for (var i = 0u; i < ${u}; i++) {\n max_value = max(thread_max[i], max_value);\n }\n\n var sum_vector = ${d}(0);\n for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) {\n sum_vector += exp(${d}(x[offset + i]) - max_value);\n }\n thread_sum[local_idx] = ${(()=>{switch(i){case 1:return"sum_vector";case 2:return"sum_vector.x + sum_vector.y";case 4:return"sum_vector.x + sum_vector.y + sum_vector.z + sum_vector.w";default:throw new Error(`Unsupported components: ${i}`)}})()};\n workgroupBarrier();\n\n var sum: f32 = 0;\n for (var i = 0u; i < ${u}; i++) {\n sum += thread_sum[i];\n }\n\n if (sum == 0) {\n for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) {\n x[offset + i] = ${_.type.value}(uniforms.d_inv);\n }\n } else {\n for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) {\n var f32input = ${d}(x[offset + i]);\n x[offset + i] = ${_.type.value}(exp(f32input - max_value) / sum);\n }\n }\n }`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${u};${h};${i}`},getShaderSource:y,getRunData:()=>({outputs:[],dispatchGroup:{x:r},programUniforms:p})}},rc=(e,t,r,o,i,u,a)=>{let c=a+i.kvSequenceLength,p=[i.batchSize,i.numHeads,i.sequenceLength,c],h=u.scale===0?1/Math.sqrt(i.headSize):u.scale,d=Me(i.headSize),y=i.headSize/d,w=12,_={x:Math.ceil(c/w),y:Math.ceil(i.sequenceLength/w),z:i.batchSize*i.numHeads},v=[{type:12,data:i.sequenceLength},{type:12,data:y},{type:12,data:c},{type:12,data:i.numHeads},{type:1,data:h}],S=o?["type","type","type"]:["type","type"],A=I=>{let x=U("q",t.dataType,t.dims,d),E=U("key",r.dataType,r.dims,d),P=[x,E];o&&P.push(U("relative_position_bias",o.dataType,o.dims));let O=j("output",t.dataType,p),R=et(1,d),L=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"alpha",type:"f32"}];return`\n const TILE_SIZE = ${w}u;\n\n var tileQ: array<${x.type.storage}, ${w*w}>;\n var tileK: array<${x.type.storage}, ${w*w}>;\n ${I.registerUniforms(L).declareVariables(...P,O)}\n ${I.mainStart([w,w,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 qOffset = uniforms.M * uniforms.K * headIdx + m * uniforms.K;\n let kOffset = uniforms.N * uniforms.K * headIdx + n * uniforms.K;\n\n var value = ${R}(0);\n for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) {\n if (global_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 < TILE_SIZE && w+k < uniforms.K; k++) {\n value += ${R}(tileQ[TILE_SIZE * local_id.y + k] * tileK[TILE_SIZE * local_id.x + k]);\n }\n\n workgroupBarrier();\n }\n\n let headOffset = headIdx * uniforms.M * uniforms.N;\n if (global_id.y < uniforms.M && global_id.x < uniforms.N) {\n let outputIdx = headOffset + global_id.y * uniforms.N + global_id.x;\n var sum: f32 = ${(()=>{switch(d){case 1:return"value";case 2:return"value.x + value.y";case 4:return"value.x + value.y + value.z + value.w";default:throw new Error(`Unsupported components: ${d}`)}})()};\n output[outputIdx] = ${O.type.value} (sum * uniforms.alpha) + ${o?"relative_position_bias[outputIdx]":"0.0"};\n }\n }`};return{name:"AttentionProbs",shaderCache:{hint:`${d}`,inputDependencies:S},getRunData:()=>({outputs:[{dims:p,dataType:t.dataType,gpuDataType:0}],dispatchGroup:_,programUniforms:v}),getShaderSource:A}},nc=(e,t,r,o,i)=>{let u=i+o.kvSequenceLength,a=[o.batchSize,o.sequenceLength,o.vHiddenSize],c=12,p={x:Math.ceil(o.vHeadSize/c),y:Math.ceil(o.sequenceLength/c),z:o.batchSize*o.numHeads},h=[{type:12,data:o.sequenceLength},{type:12,data:u},{type:12,data:o.vHeadSize},{type:12,data:o.numHeads},{type:12,data:o.vHiddenSize}];return{name:"AttentionScore",shaderCache:{inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:a,dataType:t.dataType,gpuDataType:0}],dispatchGroup:p,programUniforms:h}),getShaderSource:w=>{let _=U("probs",t.dataType,t.dims),v=U("v",r.dataType,r.dims),S=j("output",t.dataType,a),A=[{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 = ${c}u;\n var tileQ: array<${_.type.value}, ${c*c}>;\n var tileK: array<${_.type.value}, ${c*c}>;\n ${w.registerUniforms(A).declareVariables(_,v,S)}\n ${w.mainStart([c,c,1])}\n let headIdx = workgroup_id.z;\n let m = global_id.y;\n let n = global_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 = ${_.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 < TILE_SIZE && w+k < uniforms.K; k++) {\n value += tileQ[TILE_SIZE * local_id.y + k] * tileK[TILE_SIZE * k + local_id.x];\n }\n workgroupBarrier();\n }\n\n // we need to transpose output from BNSH_v to BSND_v\n let batchIdx = workgroup_id.z / uniforms.num_heads;\n let currentBatchHeadNumber = workgroup_id.z % uniforms.num_heads;\n if (m < uniforms.M && n < uniforms.N) {\n let outputIdx = batchIdx * uniforms.M * uniforms.v_hidden_size + m * uniforms.v_hidden_size\n + currentBatchHeadNumber * uniforms.N + n;\n output[outputIdx] = value;\n }\n }`}}},Pn=(e,t,r,o,i,u,a,c,p,h,d)=>{let y=e.outputCount>1,w=e.outputCount>2,_=y&&w?h.pastSequenceLength:0,v=_+h.kvSequenceLength,S=[h.batchSize,h.numHeads,v,h.headSize],A=a?[a,r]:[r],I=y?e.compute(En(A,2,S,r.dataType),{inputs:A,outputs:[1]})[0]:r,x=[h.batchSize,h.numHeads,v,h.headSize],E=c?[c,o]:[o],P=w?e.compute(En(E,2,x,o.dataType),{inputs:E,outputs:[2]})[0]:o,O=[t,I];p&&O.push(p);let R=e.compute(rc(e,t,I,p,h,d,_),{inputs:O,outputs:[-1]})[0];e.compute(tc(e,R,h.batchSize*h.numHeads*h.sequenceLength,v),{inputs:[R],outputs:[]});let L=[R,P];e.compute(nc(e,R,P,h,_),{inputs:L,outputs:[0]})},oc=(e,t)=>{let r=[t.batchSize,t.numHeads,t.sequenceLength,t.headSize],o=t.sequenceLength,i=t.inputHiddenSize,u=t.headSize,a=12,c={x:Math.ceil(t.headSize/a),y:Math.ceil(t.sequenceLength/a),z:t.batchSize*t.numHeads},p=[e.inputs[0],e.inputs[1],e.inputs[2]],h=[{type:12,data:o},{type:12,data:i},{type:12,data:u},{type:12,data:t.numHeads},{type:12,data:t.headSize},{type:12,data:t.hiddenSize},{type:12,data:t.hiddenSize+t.hiddenSize+t.vHiddenSize}],d=y=>{let w=j("output_q",p[0].dataType,r),_=j("output_k",p[0].dataType,r),v=j("output_v",p[0].dataType,r),S=U("input",p[0].dataType,p[0].dims),A=U("weight",p[1].dataType,p[1].dims),I=U("bias",p[2].dataType,p[2].dims),x=S.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 = ${a}u;\n var tileInput: array<${x}, ${a*a}>;\n var tileWeightQ: array<${x}, ${a*a}>;\n var tileWeightK: array<${x}, ${a*a}>;\n var tileWeightV: array<${x}, ${a*a}>;\n ${y.registerUniforms(E).declareVariables(S,A,I,w,_,v)}\n ${y.mainStart([a,a,1])}\n let batchIndex = workgroup_id.z / uniforms.num_heads;\n let headNumber = workgroup_id.z % uniforms.num_heads;\n let m = global_id.y;\n let n = global_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:c,programUniforms:h}),getShaderSource:d},{inputs:p,outputs:[-1,-1,-1]})},Xa=(e,t)=>{let r=ec(e.inputs,t),[o,i,u]=oc(e,r);return Pn(e,o,i,u,e.inputs[4],void 0,void 0,void 0,e.inputs[5],r,t)}});var ic,ac,sc,Qa,Ja=Y(()=>{"use strict";$r();ye();Se();Ze();_e();ic=(e,t)=>{if(!e||e.length!==5)throw new Error("BatchNormalization requires 5 inputs");let r=(o,i,u)=>{let a=i.length;if(a!==o.length)throw new Error(`${u}: num dimensions != ${a}`);i.forEach((c,p)=>{if(c!==o[p])throw new Error(`${u}: dim[${p}] 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")},ac=(e,t)=>{let{epsilon:r,spatial:o,format:i}=t,u=e[0].dims,a=o?Me(u[u.length-1]):1,c=i==="NHWC"&&u.length>1?a:1,p=M.size(u)/a,h=o,d=h?u.length:u,y=U("x",e[0].dataType,e[0].dims,a),w=U("scale",e[1].dataType,e[1].dims,c),_=U("bias",e[2].dataType,e[2].dims,c),v=U("inputMean",e[3].dataType,e[3].dims,c),S=U("inputVar",e[4].dataType,e[4].dims,c),A=j("y",e[0].dataType,d,a),I=()=>{let E="";if(o)E=`let cOffset = ${u.length===1?"0u":i==="NHWC"?`outputIndices[${u.length-1}] / ${a}`:"outputIndices[1]"};`;else if(i==="NCHW")E=`\n ${A.indicesSet("outputIndices","0","0")}\n let cOffset = ${A.indicesToOffset("outputIndices")};`;else{E=`var cIndices = ${w.type.indices}(0);\n cIndices[0] = outputIndices[${u.length-1}];`;for(let P=1;P`\n const epsilon = ${r};\n ${E.registerUniform("outputSize","u32").declareVariables(y,w,_,v,S,A)}\n ${E.mainStart()}\n ${E.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n var outputIndices = ${A.offsetToIndices(`global_idx * ${a}`)};\n ${I()}\n let scale = ${w.getByOffset("cOffset")};\n let bias = ${_.getByOffset("cOffset")};\n let inputMean = ${v.getByOffset("cOffset")};\n let inputVar = ${S.getByOffset("cOffset")};\n let x = ${y.getByOffset("global_idx")};\n let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias;\n ${A.setByOffset("global_idx","value")}\n }`;return{name:"BatchNormalization",shaderCache:{hint:`${t.epsilon}_${t.format}_${o}_${a}`,inputDependencies:h?["rank","type","type","type","type"]:void 0},getShaderSource:x,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:h?[{type:12,data:p},...Z(u)]:[{type:12,data:p}]})}},sc=e=>ve(e),Qa=(e,t)=>{let{inputs:r,outputCount:o}=e,i=sc({...t,outputCount:o});if(vr.webgpu.validateInputContent&&ic(r,i),t.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");e.compute(ac(r,i))}});var uc,dc,es,ts=Y(()=>{"use strict";Se();_e();uc=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")},dc=e=>{let t=e[0].dims,r=e[0].dims[2],o=M.size(t)/4,i=e[0].dataType,u=U("input",i,t,4),a=U("bias",i,[r],4),c=U("residual",i,t,4),p=j("output",i,t,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(o/64)}}),getShaderSource:d=>`\n const channels = ${r}u / 4;\n ${d.declareVariables(u,a,c,p)}\n\n ${d.mainStart()}\n ${d.guardAgainstOutOfBoundsWorkgroupSizes(o)}\n let value = ${u.getByOffset("global_idx")}\n + ${a.getByOffset("global_idx % channels")} + ${c.getByOffset("global_idx")};\n ${p.setByOffset("global_idx","value")}\n }`}},es=e=>{uc(e.inputs),e.compute(dc(e.inputs))}});var lc,ke,rs,ns,os,is,as,ss,us,ds,ls,cc,cs,ps,ms,fs,kn,hs,On,gs,ys,bs,ws,vs,$s,_s,Ss,xs,Cs,As,Is,Ts,Es,Ps,ks,Os,Rs,Bo,Do,Bs,Ds,zs,Rn=Y(()=>{"use strict";ye();Se();Ze();_e();lc=(e,t,r,o,i,u)=>{let a=Math.ceil(t/4),c="";typeof i=="string"?c=`${i}(a)`:c=i("a");let p=U("inputData",r,[a],4),h=j("outputData",o,[a],4);return`\n ${e.registerUniform("vec_size","u32").declareVariables(p,h)}\n\n ${u??""}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}\n\n let a = ${p.getByOffset("global_idx")};\n ${h.setByOffset("global_idx",c)}\n }`},ke=(e,t,r,o,i,u=e.dataType)=>({name:t,shaderCache:{hint:i,inputDependencies:["type"]},getShaderSource:a=>lc(a,M.size(e.dims),e.dataType,u,r,o),getRunData:a=>({outputs:[{dims:e.dims,dataType:u}],dispatchGroup:{x:Math.ceil(M.size(a[0].dims)/64/4)},programUniforms:[{type:12,data:Math.ceil(M.size(e.dims)/4)}]})}),rs=e=>{e.compute(ke(e.inputs[0],"Abs","abs"))},ns=e=>{e.compute(ke(e.inputs[0],"Acos","acos"))},os=e=>{e.compute(ke(e.inputs[0],"Acosh","acosh"))},is=e=>{e.compute(ke(e.inputs[0],"Asin","asin"))},as=e=>{e.compute(ke(e.inputs[0],"Asinh","asinh"))},ss=e=>{e.compute(ke(e.inputs[0],"Atan","atan"))},us=e=>{e.compute(ke(e.inputs[0],"Atanh","atanh"))},ds=e=>ve(e),ls=(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(ke(e.inputs[0],"Cast",r,void 0,t.cacheKey,t.to))},cc=e=>{let t=e.length>=2&&e[1].data!==0?e[1].getFloat32Array()[0]:xn,r=e.length>=3&&e[2].data!==0?e[2].getFloat32Array()[0]:Cn;return ve({min:t,max:r})},cs=(e,t)=>{let r=e.inputs.length===1?t:cc(e.inputs),o=et(e.inputs[0].dataType);e.compute(ke(e.inputs[0],"Clip",i=>`clamp(${i}, 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]})},ps=e=>{e.compute(ke(e.inputs[0],"Ceil","ceil"))},ms=e=>{e.compute(ke(e.inputs[0],"Cos","cos"))},fs=e=>{e.compute(ke(e.inputs[0],"Cosh","cosh"))},kn=e=>ve(e),hs=(e,t)=>{let r=et(e.inputs[0].dataType);e.compute(ke(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))},On=(e="f32")=>`\nconst r0: ${e} = 0.3275911;\nconst r1: ${e} = 0.254829592;\nconst r2: ${e} = -0.284496736;\nconst r3: ${e} = 1.421413741;\nconst r4: ${e} = -1.453152027;\nconst r5: ${e} = 1.061405429;\n\nfn erf_vf32(v: vec4<${e}>) -> vec4<${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}`,gs=e=>{let t=et(e.inputs[0].dataType);e.compute(ke(e.inputs[0],"Erf",r=>`erf_vf32(${r})`,On(t)))},ys=e=>{e.compute(ke(e.inputs[0],"Exp","exp"))},bs=e=>{e.compute(ke(e.inputs[0],"Floor","floor"))},ws=e=>{let t=et(e.inputs[0].dataType);e.compute(ke(e.inputs[0],"Gelu",r=>`0.5 * ${r} * (1.0 + erf_vf32(${r} * 0.7071067811865475))`,On(t)))},vs=(e,t)=>{let r=et(e.inputs[0].dataType);e.compute(ke(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))},$s=e=>{e.compute(ke(e.inputs[0],"Not",t=>`!${t}`))},_s=e=>{e.compute(ke(e.inputs[0],"Neg",t=>`-${t}`))},Ss=e=>{e.compute(ke(e.inputs[0],"Reciprocal",t=>`1.0/${t}`))},xs=e=>{let t=et(e.inputs[0].dataType);e.compute(ke(e.inputs[0],"Relu",r=>`select(vec4<${t}>(0.0), ${r}, ${r} > vec4<${t}>(0.0))`))},Cs=e=>{e.compute(ke(e.inputs[0],"Sigmoid",t=>`(1.0 / (1.0 + exp(-${t})))`))},As=e=>ve(e),Is=(e,t)=>{let r=et(e.inputs[0].dataType);e.compute(ke(e.inputs[0],"HardSigmoid",o=>`max(vec4<${r}>(0.0), min(vec4<${r}>(1.0), ${t.alpha} * ${o} + vec4<${r}>(${t.beta})))`,void 0,t.cacheKey))},Ts=e=>{e.compute(ke(e.inputs[0],"Sin","sin"))},Es=e=>{e.compute(ke(e.inputs[0],"Sinh","sinh"))},Ps=e=>{e.compute(ke(e.inputs[0],"Sqrt","sqrt"))},ks=e=>{e.compute(ke(e.inputs[0],"Tan","tan"))},Os=e=>`sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`,Rs=e=>{e.compute(ke(e.inputs[0],"Tanh",Os))},Bo=(e="f32")=>`\nconst fast_gelu_a: ${e} = 0.5;\nconst fast_gelu_b: ${e} = 0.7978845608028654;\nconst fast_gelu_c: ${e} = 0.035677408136300125;\n\nfn tanh_v(v: vec4<${e}>) -> vec4<${e}> {\n return ${Os("v")};\n}\n`,Do=e=>`(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`,Bs=e=>{let t=et(e.inputs[0].dataType);e.compute(ke(e.inputs[0],"FastGelu",Do,Bo(t),void 0,e.inputs[0].dataType))},Ds=(e,t)=>{let r=et(e.inputs[0].dataType);return e.compute(ke(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},zs=e=>{e.compute(ke(e.inputs[0],"Log","log"))}});var pc,mc,Us,Vs=Y(()=>{"use strict";Se();_e();Rn();pc=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")},mc=e=>{let t=e[0].dims.slice();t[2]=t[2]/2;let r=U("input",e[0].dataType,e[0].dims,4),o=U("bias",e[0].dataType,[e[0].dims[2]],4),i=j("output",e[0].dataType,t,4),u=M.size(t)/4,a=De(e[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)}}),getShaderSource:p=>`\n const M_SQRT2 = sqrt(2.0);\n const halfChannels = ${e[0].dims[2]/4/2}u;\n\n ${p.declareVariables(r,o,i)}\n\n ${On(a)}\n\n ${p.mainStart()}\n ${p.guardAgainstOutOfBoundsWorkgroupSizes(u)}\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 ${i.setByOffset("global_idx","valueLeft * geluRight")}\n }`}},Us=e=>{pc(e.inputs),e.compute(mc(e.inputs))}});var fc,hc,Ot,Ws,Ns,Gs,Hs,Ls,Fs,qs,js,Ks,Ys,Zs=Y(()=>{"use strict";ye();Se();_e();fc=(e,t,r,o,i,u,a,c,p,h,d,y)=>{let w,_;typeof c=="string"?w=_=(x,E)=>`${c}((${x}),(${E}))`:typeof c=="function"?w=_=c:(w=c.scalar,_=c.vector);let v=j("outputData",d,o.length,4),S=U("aData",p,t.length,4),A=U("bData",h,r.length,4),I;if(i)if(u){let x=M.size(t)===1,E=M.size(r)===1,P=t.length>0&&t[t.length-1]%4===0,O=r.length>0&&r[r.length-1]%4===0;x||E?I=v.setByOffset("global_idx",_(x?`${S.type.value}(${S.getByOffset("0")}.x)`:S.getByOffset("global_idx"),E?`${A.type.value}(${A.getByOffset("0")}.x)`:A.getByOffset("global_idx"))):I=`\n let outputIndices = ${v.offsetToIndices("global_idx * 4u")};\n let offsetA = ${S.broadcastedIndicesToOffset("outputIndices",v)};\n let offsetB = ${A.broadcastedIndicesToOffset("outputIndices",v)};\n ${v.setByOffset("global_idx",_(a||P?S.getByOffset("offsetA / 4u"):`${S.type.value}(${S.getByOffset("offsetA / 4u")}[offsetA % 4u])`,a||O?A.getByOffset("offsetB / 4u"):`${A.type.value}(${A.getByOffset("offsetB / 4u")}[offsetB % 4u])`))}\n `}else I=v.setByOffset("global_idx",_(S.getByOffset("global_idx"),A.getByOffset("global_idx")));else{if(!u)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let x=(E,P,O="")=>{let R=`aData[indexA${P}][componentA${P}]`,L=`bData[indexB${P}][componentB${P}]`;return`\n let outputIndices${P} = ${v.offsetToIndices(`global_idx * 4u + ${P}u`)};\n let offsetA${P} = ${S.broadcastedIndicesToOffset(`outputIndices${P}`,v)};\n let offsetB${P} = ${A.broadcastedIndicesToOffset(`outputIndices${P}`,v)};\n let indexA${P} = offsetA${P} / 4u;\n let indexB${P} = offsetB${P} / 4u;\n let componentA${P} = offsetA${P} % 4u;\n let componentB${P} = offsetB${P} % 4u;\n ${E}[${P}] = ${O}(${w(R,L)});\n `};d===9?I=`\n var data = vec4(0);\n ${x("data",0,"u32")}\n ${x("data",1,"u32")}\n ${x("data",2,"u32")}\n ${x("data",3,"u32")}\n outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:I=`\n ${x("outputData[global_idx]",0)}\n ${x("outputData[global_idx]",1)}\n ${x("outputData[global_idx]",2)}\n ${x("outputData[global_idx]",3)}\n `}return`\n ${e.registerUniform("vec_size","u32").declareVariables(S,A,v)}\n\n ${y??""}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}\n ${I}\n }`},hc=(e,t,r,o,i,u,a=r.dataType)=>{let c=!M.areEqual(r.dims,o.dims),p=r.dims,h=M.size(r.dims),d=!1,y=!1,w=[c];if(c){let _=It.calcShape(r.dims,o.dims,!1);if(!_)throw new Error("Can\'t perform binary op on the given tensors");p=_,h=M.size(p);let v=M.size(r.dims)===1,S=M.size(o.dims)===1,A=r.dims.length>0&&r.dims[r.dims.length-1]%4===0,I=o.dims.length>0&&o.dims[o.dims.length-1]%4===0;w.push(v),w.push(S),w.push(A),w.push(I);let x=1;for(let E=1;E_.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:_=>fc(_,r.dims,o.dims,p,d,c,y,i,r.dataType,o.dataType,a,u),getRunData:()=>({outputs:[{dims:p,dataType:a}],dispatchGroup:{x:Math.ceil(h/64/4)},programUniforms:[{type:12,data:Math.ceil(M.size(p)/4)},...Z(r.dims,o.dims,p)]})}},Ot=(e,t,r,o,i,u)=>{e.compute(hc(t,i??"",e.inputs[0],e.inputs[1],r,o,u))},Ws=e=>{Ot(e,"Add",(t,r)=>`${t}+${r}`)},Ns=e=>{Ot(e,"Div",(t,r)=>`${t}/${r}`)},Gs=e=>{Ot(e,"Equal",{scalar:(t,r)=>`u32(${t}==${r})`,vector:(t,r)=>`vec4(${t}==${r})`},void 0,void 0,9)},Hs=e=>{Ot(e,"Mul",(t,r)=>`${t}*${r}`)},Ls=e=>{let t=U("input",e.inputs[0].dataType,e.inputs[0].dims).type.value;Ot(e,"Pow",{scalar:(o,i)=>`pow_custom(${o},${i})`,vector:(o,i)=>`pow_vector_custom(${o},${i})`},`\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 `)},Fs=e=>{Ot(e,"Sub",(t,r)=>`${t}-${r}`)},qs=e=>{Ot(e,"Greater",{scalar:(t,r)=>`u32(${t}>${r})`,vector:(t,r)=>`vec4(${t}>${r})`},void 0,void 0,9)},js=e=>{Ot(e,"Less",{scalar:(t,r)=>`u32(${t}<${r})`,vector:(t,r)=>`vec4(${t}<${r})`},void 0,void 0,9)},Ks=e=>{Ot(e,"GreaterOrEqual",{scalar:(t,r)=>`u32(${t}>=${r})`,vector:(t,r)=>`vec4(${t}>=${r})`},void 0,void 0,9)},Ys=e=>{Ot(e,"LessOrEqual",{scalar:(t,r)=>`u32(${t}<=${r})`,vector:(t,r)=>`vec4(${t}<=${r})`},void 0,void 0,9)}});var St,xt,Ct,Bn,Ft=Y(()=>{"use strict";ye();Se();St=(e,t,r="f32")=>{switch(e.activation){case"Relu":return`value = max(value, ${t}(0.0));`;case"Sigmoid":return`value = (${t}(1.0) / (${t}(1.0) + exp(-value)));`;case"Clip":return`value = clamp(value, ${t}(${r}(uniforms.clip_min)), ${t}(${r}(uniforms.clip_max)));`;case"HardSigmoid":return`value = max(${t}(0.0), min(${t}(1.0), ${r}(uniforms.alpha) * value + ${r}(uniforms.beta)));`;case"LeakyRelu":return`value = select(${r}(uniforms.alpha) * value, value, value >= ${t}(0.0));`;case"":return"";default:throw new Error(`Unsupported activation ${e.activation}`)}},xt=(e,t)=>{e.activation==="Clip"?t.push({type:1,data:e.clipMax},{type:1,data:e.clipMin}):e.activation==="HardSigmoid"?t.push({type:1,data:e.alpha},{type:1,data:e.beta}):e.activation==="LeakyRelu"&&t.push({type:1,data:e.alpha})},Ct=(e,t)=>{e.activation==="Clip"?t.push({name:"clip_max",type:"f32"},{name:"clip_min",type:"f32"}):e.activation==="HardSigmoid"?t.push({name:"alpha",type:"f32"},{name:"beta",type:"f32"}):e.activation==="LeakyRelu"&&t.push({name:"alpha",type:"f32"})},Bn=e=>{let t=e?.activation||"";if(t==="HardSigmoid"){let[r,o]=e?.activation_params||[.2,.5];return{activation:t,alpha:r,beta:o}}else if(t==="Clip"){let[r,o]=e?.activation_params||[xn,Cn];return{activation:t,clipMax:o,clipMin:r}}else if(t==="LeakyRelu"){let[r]=e?.activation_params||[.01];return{activation:t,alpha:r}}return{activation:t}}});var tt,Dn,zn=Y(()=>{"use strict";tt=(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.`)}},Dn=e=>`\n ${e?"value = value + getBiasByOutputCoords(coords);":""}\n `});var Mn,zo=Y(()=>{"use strict";Mn=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 yc,bc,Hr,Xs,wc,Lr,vc,Un,Fr=Y(()=>{"use strict";ye();Se();_e();Ft();zn();yc=(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 `,bc=(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 }`,Hr=(e,t,r="f32",o,i=!1,u=32,a=!1,c=32)=>{let p=t[1]*e[1],h=t[0]*e[0],d=i?p:u,y=i?u:p,w=d/t[0],_=u/t[1];if(!((i&&w===4&&e[1]===4||!i&&(w===3||w===4))&&d%t[0]===0&&u%t[1]===0&&e[0]===4))throw new Error(`If transposeA ${i} is true, innerElementSize ${w} and workPerThread[1] ${e[1]} must be 4.\n Otherwise, innerElementSize ${w} must be 3 or 4.\n tileAWidth ${d} must be divisible by workgroupSize[0]${t[0]}. tileInner ${u} must be divisible by workgroupSize[1] ${t[1]}. colPerThread ${e[0]} must be 4.`);return`\nvar mm_Asub: array, ${d/w}>, ${y}>;\nvar mm_Bsub: array, ${h/e[0]}>, ${u}>;\n\nconst rowPerThread = ${e[1]};\nconst colPerThread = ${e[0]};\nconst innerElementSize = ${w};\nconst tileInner = ${u};\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 = ${a?"0":"i32(globalId.z)"};\n ${o?`let batchIndices = ${o.offsetToIndices("u32(batch)")};`:""}\n let globalRowStart = i32(workgroupId.y) * ${p};\n\n let num_tiles = ${a?`${Math.ceil(c/u)}`:"(uniforms.dim_inner - 1) / tileInner + 1"};\n var kStart = ${a?`i32(globalId.z) * ${c}`:"0"};\n\n var acc: array, rowPerThread>;\n\n // Loop over shared dimension.\n let tileRowB = localRow * ${_};\n for (var t = 0; t < num_tiles; 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 ${yc(i,o)}\n }\n\n // Load one tile of B into local memory.\n for (var innerRow = 0; innerRow < ${_}; 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 ${w===3?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"}\n\n ${bc(i,w)}\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}`},Xs=(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 `,wc=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",Lr=(e,t,r="f32",o,i=!1,u=32,a=!1,c=32,p=!1)=>{let h=e[1]*t[1],d=e[0]*t[0],y=i?h:u,w=i?u:h;if(!(w%t[1]===0&&y%t[0]===0&&u%t[1]===0))throw new Error(`tileAHight ${w} must be divisible by workgroupSize[1]${t[1]}, tileAWidth ${y} must be divisible by workgroupSize[0]${t[0]}, tileInner ${u} must be divisible by workgroupSize[1]${t[1]}`);let _=w/t[1],v=y/t[0],S=u/t[1],A=p?`\n let localRow = i32(localId.y);\n let localCol = i32(localId.x);\n let globalRowStart = i32(workgroupId.y) * ${h};\n let globalColStart = i32(workgroupId.x) * ${d};\n\n // Loop over shared dimension.\n for (var t = 0; t < num_tiles; t = t + 1) {\n // Load one tile of A into local memory.\n for (var inputRow = localRow; inputRow < ${w}; inputRow = inputRow + ${t[1]}) {\n for (var inputCol = localCol; inputCol < ${y}; inputCol = inputCol + ${t[0]}) {\n ${Xs(i,o)}\n }\n }\n // Load one tile of B into local memory.\n for (var inputRow = localRow; inputRow < ${u}; inputRow = inputRow + ${t[1]}) {\n for (var inputCol = localCol; inputCol < ${d}; 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 = ${i?`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) * ${h};\n\nlet tileRowA = i32(localId.y) * ${_};\nlet tileColA = i32(localId.x) * ${v};\nlet tileRowB = i32(localId.y) * ${S};\n// Loop over shared dimension.\nfor (var t = 0; t < num_tiles; t = t + 1) {\n // Load one tile of A into local memory.\n for (var innerRow = 0; innerRow < ${_}; innerRow = innerRow + 1) {\n for (var innerCol = 0; innerCol < ${v}; innerCol = innerCol + 1) {\n let inputRow = tileRowA + innerRow;\n let inputCol = tileColA + innerCol;\n ${Xs(i,o)}\n }\n }\n\n // Load one tile of B into local memory.\n for (var innerRow = 0; innerRow < ${S}; 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 ${wc(i)}\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, ${w}>;\n var mm_Bsub : array, ${u}>;\n const rowPerThread = ${e[1]};\n const colPerThread = ${e[0]};\n const tileInner = ${u};\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 = ${a?"0":"i32(globalId.z)"};\n ${o?`let batchIndices = ${o.offsetToIndices("u32(batch)")};`:""}\n let num_tiles = ${a?`${Math.ceil(c/u)}`:"(uniforms.dim_inner - 1) / tileInner + 1"};\n var kStart = ${a?`i32(globalId.z) * ${c}`:"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 ${A}\n }\n`},vc=(e,t,r,o,i,u=!1)=>{let[a,c,p]=i,[h,d,y,w]=o,_=_r(a,p),v=_r(c,p),S=De(o[0].type.tensor),A=()=>{let E=d.rank,P=h.rank,O=`var aIndices: ${d.type.indices};`;for(let R=E-2-1,L=P-1;R>=0;R--,L--)O+=`\naIndices[${R}] = ${P>1?`batchIndices[${L}]`:"batchIndices"};`;return _.forEach(R=>{O+=`\naIndices[${R}] = 0;`}),O+=`\naIndices[${E-2}] = u32(row);\n aIndices[${E-1}] = u32(colIn);`,O},I=()=>{let E=y.rank,P=h.rank,O=`var bIndices: ${y.type.indices};`;for(let R=E-2-1,L=P-1;R>=0;R--,L--)O+=`\nbIndices[${R}] = ${P>1?`batchIndices[${L}]`:"batchIndices"};`;return v.forEach(R=>{O+=`\nbIndices[${R}] = 0;`}),O+=`\nbIndices[${E-2}] = u32(row);\n bIndices[${E-1}] = u32(colIn);`,O};return`\n fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${h.type.indices}) -> ${tt(e,S)} {\n var value = ${tt(e,S)}(0.0);\n let col = colIn * ${e};\n if(row < uniforms.dim_a_outer && col < uniforms.dim_inner)\n {\n ${A()}\n value = ${d.getByIndices("aIndices")};\n }\n return value;\n }\n\n fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${h.type.indices}) -> ${tt(e,S)} {\n var value = ${tt(e,S)}(0.0);\n let col = colIn * ${e};\n if(row < uniforms.dim_inner && col < uniforms.dim_b_outer)\n {\n ${I()}\n value = ${y.getByIndices("bIndices")};\n }\n return value;\n }\n\n fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${tt(e,S)}) {\n let col = colIn * ${e};\n if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) {\n var value = valueIn;\n let coords = vec3(batch, row, colIn);\n ${t?`value = value + ${u?"bias[colIn]":`${tt(e,S)}(bias[row])`};`:""}\n ${r}\n ${w.setByIndices("vec3(coords)","value")}\n }\n }\n `},Un=(e,t,r,o,i=!1)=>{let u=e[0].dims,a=e[1].dims,c=u.slice(0,-2),p=a.slice(0,-2),h=o?o.slice(0,-2):r.slice(0,-2),d=M.size(h),y=u[u.length-2],w=u[u.length-1],_=a[a.length-1],v=w%4===0&&_%4===0,S=y<=8?[4,1,1]:[4,4,1],A=[8,8,1],I=[Math.ceil(_/A[0]/S[0]),Math.ceil(y/A[1]/S[1]),Math.ceil(d/A[2]/S[2])],x=v?4:1,E=[...c,y,w/x],P=E.length,O=[...p,w,_/x],R=O.length,L=[d,y,_/x],N=[{type:6,data:y},{type:6,data:_},{type:6,data:w}];xt(t,N),N.push(...Z(h,E,O));let K=["rank","rank"],Q=e.length>2;Q&&(N.push(...Z(e[2].dims)),K.push("rank")),N.push(...Z(L));let he=W=>{let se=h.length,Ce=An("batchDims",e[0].dataType,se,1),We=De(e[0].dataType),ee=U("a",e[0].dataType,P,x),ae=U("b",e[1].dataType,R,x),Ae=j("result",e[0].dataType,L.length,x),me=[ee,ae];if(Q){let G=i?x:1;me.push(U("bias",e[2].dataType,e[2].dims.length,G))}let ie=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];Ct(t,ie);let ue=De(Ae.type.tensor),le=St(t,Ae.type.value,ue),qe=vc(x,Q,le,[Ce,ee,ae,Ae],[c,p,h],i);return`\n ${W.registerUniforms(ie).registerInternalVariables(Ce).declareVariables(...me,Ae)}\n ${qe}\n ${v?Hr(S,A,We,Ce):Lr(S,A,We,Ce)}\n `};return{name:"MatMul",shaderCache:{hint:`${S};${t.activation};${v};${i}`,inputDependencies:K},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:I[0],y:I[1],z:I[2]},programUniforms:N}),getShaderSource:he}}});var $c,Qs,Js=Y(()=>{"use strict";ye();Lt();_e();Ft();zn();zo();Fr();$c=(e,t,r,o,i=!1,u,a=4,c=4,p=4,h="f32")=>{let d=Q=>{switch(Q){case 1:return"resData = x[xIndex];";case 3:return`resData = vec3<${h}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return"resData = x[xIndex / 4];";default:throw new Error(`innerElementSize ${Q} is not supported.`)}},y=Q=>{switch(Q){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 ${Q} is not supported.`)}},w=e?`\n let coord = vec4(batch, xRow, xCol, xCh);\n `:`\n let coord = vec4(batch, xCh, xRow, xCol);\n `,_=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 `,v=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",S=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",A=e?"row":"col",I=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 = ${A} / outWidth;\n let outCol = ${A} % outWidth;\n\n let WRow = ${I} / (i32(uniforms.w_shape[1]) * inChannels);\n let WCol = ${I} / inChannels % i32(uniforms.w_shape[1]);\n let xRow = outRow * uniforms.stride[0] + uniforms.dilation[0] * WRow - uniforms.pad[0];\n let xCol = outCol * uniforms.stride[1] + uniforms.dilation[1] * WCol - uniforms.pad[1];\n let xCh = ${I} % inChannels;\n var resData = ${tt(a,h)}(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 < ${v} && xCol >= 0 && xCol < ${S}) {\n ${w}\n let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape));\n ${d(a)}\n }\n return resData;`,E=e?t&&o?`\n let col = colIn * ${a};\n ${x}`:`\n let col = colIn * ${a};\n if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) {\n ${x}\n }\n return ${tt(a,h)}(0.0);`:o&&r?`\n let col = colIn * ${a};\n ${x}`:`\n let col = colIn * ${a};\n if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) {\n ${x}\n }\n return ${tt(a,h)}(0.0);`,P=`${y(c)}`,O=tt(p,h),R=e?tt(a,h):tt(c,h),L=e?tt(c,h):tt(a,h),N=St(u,O,h);return`\n fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${R} {\n ${e?E:P}\n }\n\n fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${L} {\n ${e?P:E}\n }\n\n fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${O}) {\n let col = colIn * ${p};\n if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer)\n {\n var value = valueIn;\n let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"};\n ${_}\n ${Dn(i)}\n ${N}\n setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value);\n }\n }`},Qs=(e,t,r,o,i,u,a,c)=>{let p=t.format==="NHWC",h=p?e[0].dims[3]:e[0].dims[1],d=r[0],y=p?r[2]:r[3],w=p?r[1]:r[2],_=p?r[3]:r[1],v=p&&(h%4===0||h%3===0)&&_%4===0,S=p?_:y*w,A=p?y*w:_,I=[8,8,1],x=o<=8?[4,1,1]:[4,4,1],E=[Math.ceil(S/I[0]/x[0]),Math.ceil(A/I[1]/x[1]),Math.ceil(d/I[2]/x[2])];Ve("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${E}`);let P=v?p&&h%4!==0?3:4:1,O=I[1]*x[1],R=I[0]*x[0],L=Math.max(I[0]*P,I[1]),N=o%O===0,K=i%R===0,Q=u%L===0,he=v?[P,4,4]:[1,1,1],W=[{type:6,data:o},{type:6,data:i},{type:6,data:u},{type:6,data:[t.pads[0],t.pads[1]]},{type:6,data:t.strides},{type:6,data:t.dilations}];xt(t,W),W.push(...Z(e[0].dims,e[1].dims));let se=["rank","rank"];a&&(W.push(...Z(e[2].dims)),se.push("rank")),W.push(...Z(r));let Ce=We=>{let ee=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"},{name:"pad",type:"i32",length:2},{name:"stride",type:"i32",length:2},{name:"dilation",type:"i32",length:2}];Ct(t,ee);let ae=v?4:1,Ae=De(e[0].dataType),me=`\n fn setOutputAtIndex(flatIndex : i32, value : ${v?`vec4<${Ae}>`:Ae}) {\n result[flatIndex] = ${v?`vec4<${Ae}>`:Ae}(value);\n }\n fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${v?`vec4<${Ae}>`:Ae}) {\n let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3));\n setOutputAtIndex(flatIndex ${v?"/ 4":""}, value);\n }`,ie=U("x",e[0].dataType,e[0].dims.length,P===3?1:P),ue=U("w",e[1].dataType,e[1].dims.length,ae),le=[ie,ue],qe=j("result",e[0].dataType,r.length,ae);if(a){let G=U("bias",e[2].dataType,e[2].dims.length,ae);le.push(G),me+=`\n fn getBiasByOutputCoords(coords : vec4) -> ${v?`vec4<${Ae}>`:Ae} {\n return bias[coords.${p?"w":"y"}${v?"/ 4":""}];\n }`}return`\n ${Mn("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 ${We.registerUniforms(ee).declareVariables(...le,qe)}\n ${me}\n ${$c(p,N,K,Q,a,t,he[0],he[1],he[2],Ae)}\n ${v?Hr(x,I,Ae,void 0,!p,L):Lr(x,I,Ae,void 0,!p,L,!1,void 0,c)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${t.cacheKey};${P};${v};${N};${K};${Q};${O};${R};${L}`,inputDependencies:se},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:E[0],y:E[1],z:E[2]},programUniforms:W}),getShaderSource:Ce}}});var Mo,eu,tu=Y(()=>{"use strict";ye();Se();_e();Uo();Ft();Mo=(e,t,r)=>{let o=e.length>2,i=o?"value += b[output_channel];":"",u=e[0].dims,a=e[1].dims,c=a[0]/t.group,p=t.format==="NHWC",h=Vn(u,a,t.dilations,t.pads,t.strides,p),d=M.size(h),y=[{type:12,data:d},{type:12,data:t.dilations},{type:12,data:[t.strides[0],t.strides[1]]},{type:12,data:[t.pads[0],t.pads[1]]},{type:12,data:c}];xt(t,y),y.push(...Z(u,a));let w=["rank","rank"];o&&(y.push(...Z(e[2].dims)),w.push("rank")),y.push(...Z(h));let _=v=>{let S=j("output",e[0].dataType,h.length),A=De(S.type.tensor),I=St(t,S.type.value,A),x=U("x",e[0].dataType,u.length),E=U("w",e[1].dataType,a.length),P=[x,E];o&&P.push(U("b",e[2].dataType,e[2].dims.length));let O=[{name:"output_size",type:"u32"},{name:"dilations",type:"u32",length:t.dilations.length},{name:"strides",type:"u32",length:2},{name:"pads",type:"u32",length:2},{name:"output_channels_per_group",type:"u32"}];return Ct(t,O),`\n ${v.registerUniforms(O).declareVariables(...P,S)}\n\n ${v.mainStart()}\n ${v.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n\n let outputIndices = ${S.offsetToIndices("global_idx")};\n let batch: u32 = outputIndices[0];\n let output_channel: u32 = outputIndices[${p?3:1}];\n let xRCCorner: vec2 = vec2(outputIndices[${p?1:2}], outputIndices[${p?2:3}]) * uniforms.strides - uniforms.pads;\n let group_id: u32 = output_channel / uniforms.output_channels_per_group;\n\n var value: ${S.type.value} = ${S.type.value}(0);\n for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[1]; wInChannel++) {\n let input_channel = group_id * uniforms.w_shape[1] + wInChannel;\n for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[2]; wHeight++) {\n let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0];\n\n if (xHeight < 0u || xHeight >= uniforms.x_shape[${p?1:2}]) {\n continue;\n }\n\n for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[3]; wWidth++) {\n let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1];\n if (xWidth < 0u || xWidth >= uniforms.x_shape[${p?2:3}]) {\n continue;\n }\n\n let xVal = ${p?x.get("batch","xHeight","xWidth","input_channel"):x.get("batch","input_channel","xHeight","xWidth")};\n let wVal = ${E.get("output_channel","wInChannel","wHeight","wWidth")};\n value += xVal*wVal;\n }\n }\n }\n ${i}\n ${I}\n ${S.setByOffset("global_idx","value")}\n }`};return{name:"GroupedConv",shaderCache:{hint:t.cacheKey,inputDependencies:w},getRunData:()=>({outputs:[{dims:r?r(h):h,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:y}),getShaderSource:_}},eu=(e,t,r)=>{let o=e.length>2,i=Me(r[3]),u=Me(r[2]),a=M.size(r)/i/u,c=[e[0].dims[0],e[0].dims[1],e[0].dims[2],e[0].dims[3]/i],p=[e[1].dims[0],e[1].dims[1],e[1].dims[2],e[1].dims[3]/i],h=[r[0],r[1],r[2],r[3]/i],d=[{type:12,data:a},{type:6,data:[t.strides[0],t.strides[1]]},{type:6,data:[t.pads[0],t.pads[1]]}];xt(t,d),d.push(...Z(c,p,h));let y=(u-1)*t.strides[1]+p[1],w=_=>{let v=j("output",e[0].dataType,h.length,i),S=De(v.type.tensor),A=St(t,v.type.value,S),I=U("x",e[0].dataType,c.length,i),x=U("w",e[1].dataType,p.length,i),E=[I,x];o&&E.push(U("b",e[2].dataType,e[2].dims,i));let P=o?"value += b[output_channel];":"",O=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return Ct(t,O),`\n ${_.registerUniforms(O).declareVariables(...E,v)}\n ${_.mainStart()}\n ${_.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n let width0 = uniforms.output_shape[3];\n let output_channel = global_idx % width0;\n var index1 = global_idx / width0;\n let width1 = uniforms.output_shape[2] / ${u}u;\n let col = (index1 % width1) * ${u}u;\n index1 = index1 / width1;\n let row = index1 % uniforms.output_shape[1];\n let batch = index1 / uniforms.output_shape[1];\n\n let x_corner = vec2(i32(row), i32(col)) * uniforms.strides - uniforms.pads;\n\n var x_vals: array<${I.type.value}, ${y}>;\n var values: array<${v.type.value}, ${u}>;\n let input_channel = output_channel;\n // Use constant instead of uniform can give better performance for w\'s height/width.\n for (var w_height: u32 = 0u; w_height < ${p[0]}; w_height++) {\n let x_height = x_corner.x + i32(w_height);\n if (x_height >= 0 && u32(x_height) < uniforms.x_shape[1]) {\n for (var i = 0; i < ${y}; i++) {\n let x_width = x_corner.y + i;\n if (x_width >= 0 && u32(x_width) < uniforms.x_shape[2]) {\n x_vals[i] = ${I.get("batch","u32(x_height)","u32(x_width)","input_channel")};\n } else {\n x_vals[i] = ${I.type.value}(0);\n }\n }\n for (var w_width: u32 = 0u; w_width < ${p[1]}; w_width++) {\n let w_val = ${x.get("w_height","w_width","0","output_channel")};\n for (var i = 0u; i < ${u}u; i++) {\n values[i] = fma(x_vals[i * u32(uniforms.strides[1]) + w_width], w_val, values[i]);\n }\n }\n }\n }\n\n for (var i = 0u; i < ${u}u; i++) {\n var value = values[i];\n ${P}\n ${A}\n ${v.set("batch","row","col + i","output_channel","value")};\n }\n }`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${t.cacheKey};${i};${u};${y};${p[0]};${p[1]}`,inputDependencies:o?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:d}),getShaderSource:w}}});var Vo,_c,ru,Wo=Y(()=>{"use strict";ye();Se();Fr();_e();Ft();Vo=(e,t,r,o,i=!1)=>{let u=e[0].dims,a=e[1].dims,c=u[u.length-2],p=a[a.length-1],h=u[u.length-1],d=Me(p),y=Me(h),w=Me(c),_=M.size(r)/d/w,v=e.length>2,S=o?o.slice(0,-2):r.slice(0,-2),I=[M.size(S),c,p],x=[{type:12,data:_},{type:12,data:c},{type:12,data:p},{type:12,data:h}];xt(t,x),x.push(...Z(S,u,a)),v&&x.push(...Z(e[2].dims)),x.push(...Z(I));let E=P=>{let O=An("batch_dims",e[0].dataType,S.length),R=U("a",e[0].dataType,u.length,y),L=U("b",e[1].dataType,a.length,d),N=j("output",e[0].dataType,I.length,d),K=De(N.type.tensor),Q=St(t,N.type.value,K),he=[R,L],W="";if(v){let ie=i?d:1;he.push(U("bias",e[2].dataType,e[2].dims.length,ie)),W=`${i?`value += bias[col / ${ie}];`:`value += ${N.type.value}(bias[row + i]);`}`}let se=u.slice(0,-2),Ce=a.slice(0,-2),We=_r(se,S),ee=_r(Ce,S),ae=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];Ct(t,ae);let Ae=(ie,ue)=>{let le=ie.rank,qe=ie.name;if(le===2)return`var ${qe}_indices = ${ie.type.indices}(0u, 0u);`;let G=O.rank,ne=`var ${qe}_indices: ${ie.type.indices};`;for(let xe=le-2-1,Ke=G-1;xe>=0;xe--,Ke--)ne+=`\n${qe}_indices[${xe}] = ${G>1?`batch_indices[${Ke}]`:"batch_indices"};`;return ue.forEach(xe=>{ne+=`\n${qe}_indices[${xe}] = 0;`}),ne+=`${qe}_indices[${le-2}] = 0u;\n ${qe}_indices[${le-1}] = 0u;`,ne},me=()=>{let ie=`var a_data: ${R.type.value};`;for(let ue=0;ue;\n for (var k: u32 = 0u; k < uniforms.K; k = k + ${y}) {\n ${me()}\n }\n for (var i = 0u; i < ${w}u; i++) {\n var value = values[i];\n ${W}\n ${Q}\n let cur_indices = ${N.type.indices}(batch, row + i, col);\n let offset = ${N.indicesToOffset("cur_indices")};\n ${N.setByOffset(`offset / ${d}`,"value")};\n }\n }\n `};return{name:"MatMulNaive",shaderCache:{hint:`${t.activation};${d};${y};${w};${i}`,inputDependencies:v?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(_/64)},programUniforms:x}),getShaderSource:E}},_c=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.")},ru=e=>{_c(e.inputs);let t=It.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(Vo(e.inputs,{activation:""},t)):e.compute(Un(e.inputs,{activation:""},t))}});var Vn,No,Sc,nu,Go,xc,Cc,Ho,Uo=Y(()=>{"use strict";Se();Js();Fr();tu();Ft();Wo();Sr();Vn=(e,t,r,o,i,u)=>{let a=e[0],c=e.slice(u?1:2,u?3:4),p=c.length,h=t[0],y=t.slice(2).map((v,S)=>v+(v-1)*(r[S]-1)),_=c.map((v,S)=>v+o[S]+o[S+p]).map((v,S)=>Math.floor((v-y[S]+i[S])/i[S]));return _.splice(0,0,a),_.splice(u?3:1,0,h),_},No=[2,3,1,0],Sc=(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 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")},nu=(e,t)=>{let r=e.kernelShape.slice();for(let u=2;u{let t=Bn(e),r=e.format,o=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],i=e.dilations,u=e.group,a=e.kernel_shape,c=e.pads,p=e.strides,h=e.w_is_const();return{autoPad:o,format:r,dilations:i,group:u,kernelShape:a,pads:c,strides:p,wIsConst:h,...t,cacheKey:`${e.format};${t.activation};`}},xc=(e,t,r)=>{let o=nu(r,t),i=r.format==="NHWC";if(r.group!==1){if(!e.adapterInfo.isArchitecture("ampere")&&i&&t[1].dims[0]===r.group&&t[1].dims[1]===1&&r.dilations[0]===1&&r.dilations[1]===1){let L=Vn(t[0].dims,t[1].dims,r.dilations,o.pads,r.strides,i),N=e.kernelCustomData.wT??e.compute(yt(t[1],No),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=N);let K=[t[0],N];t.length===3&&K.push(t[2]),e.compute(eu(K,o,L),{inputs:K})}else e.compute(Mo(t,o));return}let u=t.length===3,a=t[0].dims[i?1:2],c=t[0].dims[i?2:3],p=t[0].dims[i?3:1],h=t[1].dims[2],d=t[1].dims[3],y=Vn(t[0].dims,t[1].dims,r.dilations,o.pads,r.strides,i),w=y[i?1:2],_=y[i?2:3],v=y[i?3:1],S=i&&h===a&&d===c&&r.pads[0]===0&&r.pads[1]===0;if(S||h===1&&d===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=y[0],L,N,K,Q=[];if(i){let se=e.kernelCustomData.wT??e.compute(yt(t[1],No),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];if(r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=se),S){let Ce=a*c*p;L=t[0].reshape([1,R,Ce]),N=se.reshape([1,Ce,v]),K=[1,R,v]}else L=t[0].reshape([R,a*c,p]),N=se.reshape([1,p,v]),K=[R,w*_,v];Q.push(L),Q.push(N)}else L=t[0].reshape([R,p,a*c]),N=t[1].reshape([1,v,p]),K=[R,v,w*_],Q.push(N),Q.push(L);u&&Q.push(t[2]);let he=K[2],W=Q[0].dims[Q[0].dims.length-1];he<8&&W<8?e.compute(Vo(Q,o,y,K,i),{inputs:Q}):e.compute(Un(Q,o,y,K,i),{inputs:Q});return}let A=!0,I=e.kernelCustomData.wT??e.compute(yt(t[1],No),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=I);let x=[t[0],I];u&&x.push(t[2]);let E=i?w*_:v,P=i?v:w*_,O=h*d*p;e.compute(Qs(x,o,y,E,P,O,u,A),{inputs:x})},Cc=(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 i=[0,t.pads[0],0,t.pads[1]],u=[1].concat(t.strides),a=[1].concat(t.dilations),c=[1].concat(t.kernelShape),p=nu({...t,pads:i,strides:u,dilations:a,kernelShape:c},o);e.compute(Mo(o,p,h=>r?[h[0],h[2],h[3]]:[]))},Ho=(e,t)=>{Sc(e.inputs,t),e.inputs[0].dims.length===3?Cc(e,t):xc(e,e.inputs,t)}});var Ac,ou,iu=Y(()=>{"use strict";ye();Lt();_e();Ft();zn();zo();Fr();Ac=(e,t=!1,r,o,i=4)=>{let u=I=>{switch(I){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 ${o}(v0, v1, v2, v3);\n `;default:throw new Error(`innerElementSize ${I} is not supported.`)}},a=e?`\n let coord = vec4(batch, iXR, iXC, xCh);\n `:`\n let coord = vec4(batch, xCh, iXR, iXC);\n `,c=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 `,p=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",h=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",d=e?"row":"col",y=e?"col":"row",w=`\n let inChannels = ${e?"i32(uniforms.x_shape[3])":"i32(uniforms.x_shape[1])"};\n let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"};\n let outRow = ${d} / outWidth;\n let outCol = ${d} % outWidth;\n\n let WRow = ${y} / (uniforms.filter_dims[1] * inChannels);\n let WCol = ${y} / inChannels % uniforms.filter_dims[1];\n let xR = f32(outRow - uniforms.pads[0] + uniforms.dilations[0] * WRow) / f32(uniforms.strides[0]);\n let xC = f32(outCol - uniforms.pads[1] + uniforms.dilations[1] * WCol) / f32(uniforms.strides[1]);\n if (xR < 0.0 || xR >= f32(${p}) || fract(xR) > 0.0) {\n return ${o}(0.0);\n }\n if (xC < 0.0 || xC >= f32(${h}) || fract(xC) > 0.0) {\n return ${o}(0.0);\n }\n let iXR = i32(xR);\n let iXC = i32(xC);\n let xCh = ${y} % inChannels;\n ${a}\n return x[getIndexFromCoords4D(coord, vec4(uniforms.x_shape))/${i}];`,_=e?`\n let col = colIn * ${i};\n if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) {\n ${w}\n }\n return ${o}(0.0);`:`\n let col = colIn * ${i};\n if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) {\n ${w}\n }\n return ${o}(0.0);`,v=`\n let col = colIn * ${i};\n let inChannels = ${e?"i32(uniforms.x_shape[3])":"i32(uniforms.x_shape[1])"};\n let coordX = uniforms.filter_dims[0] - 1 - row / (uniforms.filter_dims[1] * inChannels);\n let coordY = uniforms.filter_dims[1] - 1 - (row / inChannels) % uniforms.filter_dims[1];\n if (${e?"row < uniforms.dim_inner && col < uniforms.dim_b_outer":"row < uniforms.dim_inner && col < uniforms.dim_a_outer"} && coordX >= 0 && coordY >= 0) {\n let rowInner = row % inChannels;\n let coord = vec4(coordX, coordY, col, rowInner);\n ${u(i)}\n }\n return ${o}(0.0);\n `,S=St(r,o);return`\n fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${o} {\n ${e?_:v}\n }\n\n fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${o} {\n ${e?v:_}\n }\n\n fn mm_write(batch: i32, row : i32, colIn : i32, valueInput : ${o}) {\n let col = colIn * ${i};\n if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) {\n var value = valueInput;\n let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"};\n ${c}\n ${Dn(t)}\n ${S}\n result[getIndexFromCoords4D(coords, vec4(uniforms.result_shape))/${i}] = value;\n }\n }`},ou=(e,t,r,o,i,u,a,c)=>{let p=t.format==="NHWC",h=p?e[0].dims[3]:e[0].dims[1],d=r[0],y=p?r[2]:r[3],w=p?r[1]:r[2],_=p?r[3]:r[1],v=p&&h%4===0&&h%3&&_%4===0,S=p?_:y*w,A=p?y*w:_,I=[8,8,1],x=o<=8?[4,1,1]:[4,4,1],E=[Math.ceil(S/I[0]/x[0]),Math.ceil(A/I[1]/x[1]),Math.ceil(d/I[2]/x[2])];Ve("verbose",()=>`[conv_backprop_mm_webgpu] dispatch = ${E}`);let P=v?4:1,O=Math.max(I[0]*P,I[1]),R=v?4:1,L=[t.kernelShape[p?1:2],t.kernelShape[p?2:3]],N=[L[0]+(t.dilations[0]<=1?0:(L[0]-1)*(t.dilations[0]-1)),L[1]+(t.dilations[1]<=1?0:(L[1]-1)*(t.dilations[1]-1))],K=[N[0]-1-Math.floor((t.pads[0]+t.pads[2])/2),N[1]-1-Math.floor((t.pads[1]+t.pads[3])/2)],Q=[{type:6,data:o},{type:6,data:i},{type:6,data:u},{type:6,data:t.strides},{type:6,data:t.dilations},{type:6,data:L},{type:6,data:K}];xt(t,Q),Q.push(...Z(e[0].dims,e[1].dims));let he=["rank","rank"];a&&(Q.push(...Z(e[2].dims)),he.push("rank")),Q.push(...Z(r));let W=se=>{let Ce=U("x",e[0].dataType,e[0].dims.length,R),We=U("w",e[1].dataType,e[1].dims.length,1),ee=j("result",e[0].dataType,r.length,R),ae=[Ce,We],Ae="";if(a){let ue=U("bias",e[2].dataType,e[2].dims.length,R);ae.push(ue),Ae+=`\n fn getBiasByOutputCoords(coords : vec4) -> ${ue.type.value} {\n return bias[coords.${p?"w":"y"}${v?"/ 4":""}];\n }`}let me=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"},{name:"strides",type:"i32",length:2},{name:"dilations",type:"i32",length:2},{name:"filter_dims",type:"i32",length:L.length},{name:"pads",type:"i32",length:K.length}];Ct(t,me);let ie=De(e[0].dataType,1);if(ie!=="f16"&&ie!=="f32")throw new Error(`elemType ${ie} is not supported.`);return`\n ${Mn("uniforms.result_strides")}\n ${se.registerUniforms(me).declareVariables(...ae,ee)};\n ${Ae}\n ${Ac(p,a,t,Ce.type.value,P)}\n ${v?Hr(x,I,ie,void 0,!p,O):Lr(x,I,ie,void 0,!p,O,!1,void 0,c)}`};return{name:"Conv2DTransposeMatMul",shaderCache:{hint:`${t.cacheKey};${x};${I};${v}`,inputDependencies:he},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:E[0],y:E[1],z:E[2]},programUniforms:Q}),getShaderSource:W}}});var Ic,Lo,au=Y(()=>{"use strict";ye();Lt();Se();_e();Ic=(e,t,r,o,i,u=!1,a,c,p=!1)=>{let h=p?1:2,d=p?2:3,y=p?3:1,w=u?2:1,_=`\n fn setOutputAtIndex(flatIndex : u32, value : ${u?`vec4<${a}>`:a}) {\n result[flatIndex] = ${u?`vec4<${a}>`:a}(value);\n }`;o&&(_+=`\n fn getBiasByOutputCoords(coords : vec4) -> ${u?`vec4<${a}>`:a} {\n return bias[coords.${p?"w":"y"}${u?"/ 4":""}];\n }`);let v=u?4:1,S=U("W",t[1].dataType,t[1].dims.length,v),A=U("Dy",t[0].dataType,t[0].dims.length,v),I=[A,S];o&&I.push(U("bias",t[2].dataType,[r[y]].length,v));let x=j("result",t[0].dataType,r.length,v),E=`{\n let batch: u32 = ${i?"global_id.z":"workgroup_id.z"} / uniforms.result_shape[1];\n let r = ${i?"global_id.z":"workgroup_id.z"} % uniforms.result_shape[1];\n let c = ${i?"global_id.y":"workgroup_id.y"} * ${w};\n let d1: u32 = ${i?"global_id.x":"workgroup_id.x"} * 4;\n\n let dyCorner = vec2(i32(r), i32(c)) - vec2(uniforms.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<${a}>(0.0);\n }\n for (var wR: u32 = 0; wR < uniforms.filter_dims[0]; wR = wR + 1) {\n var dyR = (${a}(dyCorner.x) + ${a}(wR)) / ${a}(uniforms.strides.x);\n let wRPerm = uniforms.filter_dims[0] - 1 - wR;\n if (dyR < 0.0 || dyR >= ${a}(uniforms.Dy_shape[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 < uniforms.filter_dims[1]; wC = wC + 1) {\n let dyC = (${a}(dyCorner.y) + ${a}(wC)) / ${a}(uniforms.strides.y);\n let dyC2 = (${a}(dyCorner.y) + 1.0 + ${a}(wC)) / ${a}(uniforms.strides.y);\n let wCPerm = uniforms.filter_dims[1] - 1 - wC;\n if (wCPerm < 0) {\n continue;\n }\n var bDyCVal = true;\n var bDyCVal2 = true;\n if (dyC < 0.0 || dyC >= ${a}(uniforms.Dy_shape[2]) ||\n fract(dyC) > 0.0) {\n bDyCVal = false;\n }\n if (dyC2 < 0.0 || dyC2 >= ${a}(uniforms.Dy_shape[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 = uniforms.Dy_shape[3];\n for (var d2 :u32 = 0; d2 < d2Length; d2 = d2 + 4) {\n let wValue0 = ${S.get("u32(wRPerm)","u32(wCPerm)","d1","d2")};\n let wValue1 = ${S.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")};\n let wValue2 = ${S.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")};\n let wValue3 = ${S.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")};\n\n var xValue = ${A.get("batch","idyR","idyC","d2")};\n let tmpval = vec4<${a}>(dot(xValue, wValue0),\n dot(xValue, wValue1),\n dot(xValue, wValue2),\n dot(xValue, wValue3));\n dotProd[0] = dotProd[0] + tmpval;\n\n xValue = ${A.get("batch","idyR","idyC2","d2")};\n\n dotProd[1] = dotProd[1] + vec4<${a}>(dot(xValue, wValue0),\n dot(xValue, wValue1),\n dot(xValue, wValue2),\n dot(xValue, wValue3));\n }\n } else if (bDyCVal) {\n let d2Length = uniforms.Dy_shape[${y}];\n for (var d2: u32 = 0; d2 < d2Length; d2 = d2 + 4) {\n let wValue0 = ${S.get("u32(wRPerm)","u32(wCPerm)","d1","d2")};\n let wValue1 = ${S.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")};\n let wValue2 = ${S.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")};\n let wValue3 = ${S.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")};\n\n var xValue = ${A.get("batch","idyR","idyC","d2")};\n let tmpval = vec4<${a}>(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 = uniforms.Dy_shape[3];\n for (var d2: u32 = 0; d2 < d2Length; d2 = d2 + 4) {\n let wValue0 = ${S.get("u32(wRPerm)","u32(wCPerm)","d1","d2")};\n let wValue1 = ${S.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")};\n let wValue2 = ${S.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")};\n let wValue3 = ${S.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")};\n\n var xValue = ${A.get("batch","idyR","idyC2","d2")};\n let tmpval = vec4<${a}>(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] + ${o?"bias[c+i]":`vec4<${a}>(0.0)`};\n ${x.set("batch","r","c + i","d1","value")};\n }\n }`,P=`\n let outputIndices = ${x.offsetToIndices("global_idx")};\n let batch = ${x.indicesGet("outputIndices",0)};\n let d1 = ${x.indicesGet("outputIndices",y)};\n let r = ${x.indicesGet("outputIndices",h)};\n let c = ${x.indicesGet("outputIndices",d)};\n let dyCorner = vec2(i32(r), i32(c)) - uniforms.pads;\n let dyRCorner = dyCorner.x;\n let dyCCorner = dyCorner.y;\n let groupId = d1 / uniforms.output_channels_per_group;\n let wOutChannel = d1 - groupId * uniforms.output_channels_per_group;\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 = ${a}(0.0);\n for (var wR: u32 = 0; wR < uniforms.effective_filter_dims.x; wR = wR + 1) {\n if (wR % uniforms.dilations.x != 0) {\n continue;\n }\n let dyR = (${a}(dyRCorner) + ${a}(wR)) / ${a}(uniforms.strides[0]);\n let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x;\n if (dyR < 0.0 || dyR >= ${a}(uniforms.Dy_shape[${h}]) || fract(dyR) > 0.0 ||\n wRPerm < 0) {\n continue;\n }\n let idyR: u32 = u32(dyR);\n\n for (var wC: u32 = 0; wC < uniforms.effective_filter_dims.y; wC = wC + 1) {\n if (wC % uniforms.dilations.y != 0) {\n continue;\n }\n let dyC = (${a}(dyCCorner) + ${a}(wC)) / ${a}(uniforms.strides.y);\n let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y;\n if (dyC < 0.0 || dyC >= ${a}(uniforms.Dy_shape[${d}]) ||\n fract(dyC) > 0.0 || wCPerm < 0) {\n continue;\n }\n let idyC: u32 = u32(dyC);\n var inputChannel = groupId * uniforms.input_channels_per_group;\n for (var d2: u32 = 0; d2 < uniforms.input_channels_per_group; d2 = d2 + 1) {\n let xValue = ${p?A.get("batch","idyR","idyC","inputChannel"):A.get("batch","inputChannel","idyR","idyC")};\n let wValue = ${S.get("inputChannel","wOutChannel","u32(wRPerm)","u32(wCPerm)")};\n dotProd = dotProd + xValue * wValue;\n inputChannel = inputChannel + 1;\n }\n }\n }\n let value = dotProd + ${o?"bias[d1]":`${a}(0.0)`};\n ${x.setByOffset("global_idx","value")};\n `;return`\n ${e.registerUniforms(c).declareVariables(...I,x)}\n ${_}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")};\n ${u?E:P}}`},Lo=(e,t,r)=>{let o=e.length>2,i=t.outputShape,u=M.size(i),a=[Math.ceil(u/64),1,1];Ve("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${a}`);let c=t.format==="NHWC",p=["rank","rank"],h=[t.strides[0],t.strides[1]],d=[t.kernelShape[c?1:2],t.kernelShape[c?2:3]],y=[t.dilations[0],t.dilations[1]],w=[d[0]+(t.dilations[0]<=1?0:(t.kernelShape[c?1:2]-1)*(t.dilations[0]-1)),d[1]+(t.dilations[1]<=1?0:(t.kernelShape[c?2:3]-1)*(t.dilations[1]-1))],_=[w[0]-1-Math.floor((t.pads[0]+t.pads[2])/2),w[1]-1-Math.floor(t.pads[1]+t.pads[3])/2],v=!1,S=t.group,A=e[1].dims,I=A[0]/S,x=A[1],E=[{type:12,data:u},{type:12,data:h},{type:12,data:d},{type:12,data:y},{type:12,data:w},{type:6,data:_},{type:12,data:I},{type:12,data:x},...Z(e[0].dims,e[1].dims)];o&&(E.push(...Z(e[2].dims)),p.push("rank")),E.push(...Z(i));let P=a[1]===1&&a[2]===1,O=R=>{let L=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:h.length},{name:"filter_dims",type:"u32",length:d.length},{name:"dilations",type:"u32",length:d.length},{name:"effective_filter_dims",type:"u32",length:w.length},{name:"pads",type:"i32",length:_.length},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],N=De(e[0].dataType);return`${Ic(R,e,i,o,P,v,N,L,c)}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${t.cacheKey};`,inputDependencies:p},getRunData:()=>({dispatchGroup:{x:a[0],y:a[1],z:a[2]},outputs:[{dims:r?r(i):i,dataType:e[0].dataType}],programUniforms:E}),getShaderSource:O}}});var Tc,Ec,Pc,su,uu,kc,Oc,Rc,Bc,du,lu=Y(()=>{"use strict";iu();au();Ft();Sr();Tc=(e,t,r,o,i,u)=>(e-1)*t+r+(o-1)*i+1-u,Ec=(e,t,r,o,i)=>{let u=Math.floor(e/2);t==="SAME_UPPER"?(r[o]=u,r[i]=e-u):t==="SAME_LOWER"&&(r[o]=e-u,r[i]=u)},Pc=(e,t,r,o,i,u,a,c,p,h)=>{let d=e.length-2,y=h.length===0;if(p.length===0)for(let v=0;v{let r=e.kernelShape.slice();if(e.kernelShape.length===0||e.kernelShape.reduce((y,w)=>y*w,1)===0){r.length=0;for(let y=2;yy+w,0)===0){let y=t[0].dims.length-2;p=new Array(y).fill(1)}let h=e.strides.slice();if(h.reduce((y,w)=>y+w,0)===0){let y=t[0].dims.length-2;h=new Array(y).fill(1)}Pc(c,r,p,e.autoPad,e.group,i,h,o,a,u);let d=Object.assign({},e);return Object.assign(d,{kernelShape:r,pads:i,outputPadding:a,outputShape:u,dilations:p,strides:h}),d},uu=e=>{let t=Bn(e),r=e.format,o=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof e.autoPad>"u"?0:e.autoPad],i=e.dilations,u=e.group,a=e.kernelShape,c=e.pads,p=e.strides,h=e.wIsConst(),d=e.outputPadding,y=e.outputShape;return{autoPad:o,format:r,dilations:i,group:u,kernelShape:a,outputPadding:d,outputShape:y,pads:c,strides:p,wIsConst:h,...t,cacheKey:`${e.format};${t.activation};`}},kc=(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 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 u=e[0].dims.length-2;if(t.dilations.reduce((d,y)=>d+y,0)>0&&t.dilations.length!==u)throw new Error(`dilations should be ${u}D`);if(t.strides.reduce((d,y)=>d+y,0)>0&&t.strides.length!==u)throw new Error(`strides should be ${u}D`);if(t.pads.reduce((d,y)=>d+y,0)>0&&t.pads.length!==u*2)throw new Error(`pads should be ${u*2}D`);if(t.outputPadding.length!==u&&t.outputPadding.length!==0)throw new Error(`output_padding should be ${u}D`);if(t.kernelShape.reduce((d,y)=>d+y,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")},Oc=[2,3,1,0],Rc=(e,t,r)=>{let o=su(r,t),i=r.format==="NHWC",u=o.outputShape,a=u[i?3:1],c=t[0].dims[i?3:1];if(o.group!==1||a===1&&c===1){e.compute(Lo(t,o));return}let p=u[i?1:2],h=u[i?2:3],d=t[1].dims[2],y=t[1].dims[3],w=i?p*h:a,_=i?a:p*h,v=d*y*c,S=!0,A=e.kernelCustomData.wT??e.compute(yt(t[1],Oc),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=A);let I=[t[0],A],x=t.length===3;x&&(!i&&t[2].dims.length===1?I.push(t[2].reshape([t[2].dims[0],1,1])):I.push(t[2])),e.compute(ou(I,o,u,w,_,v,x,S),{inputs:I})},Bc=(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 i=t.kernelShape;(i.length===0||i[0]===0)&&(i=[e.inputs[1].dims[2]]);let u=t.dilations;(u.length===0||u[0]===0)&&(u=[1]);let a=t.strides;(a.length===0||a[0]===0)&&(a=[1]);let c=t.pads;c.length===0&&(c=[0,0]),c=[0,c[0],0,c[1]],a=[1].concat(a),u=[1].concat(u),i=[1].concat(i);let p=su({...t,pads:c,strides:a,dilations:u,kernelShape:i},o);e.compute(Lo(o,p,h=>r?[h[0],h[2],h[3]]:[h[0],h[1],h[3]]))},du=(e,t)=>{kc(e.inputs,t),e.inputs[0].dims.length===3?Bc(e,t):Rc(e,e.inputs,t)}});var Dc,cu,pu,mu=Y(()=>{"use strict";ye();Se();Ze();_e();Dc=(e,t,r,o)=>{let i=M.size(t),u=t.length,a=U("input",e,u),c=j("output",e,u),p=r.dataType===6?r.getInt32Array()[0]:Number(r.getBigInt64Array()[0]),h=M.normalizeAxis(p,u),d=y=>{let w=` i32(${a.indicesGet("inputIndices","uniforms.axis")}) `,_=fe("uniforms.input_shape","uniforms.axis",u),v=o.reverse?w+(o.exclusive?" + 1":""):"0",S=o.reverse?_:w+(o.exclusive?"":" + 1");return`\n ${y.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(a,c)}\n ${y.mainStart()}\n ${y.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n var inputIndices = ${c.offsetToIndices("global_idx")};\n var sum = ${c.type.value}(0);\n let first : i32 = ${v};\n let last : i32 = ${S};\n for (var i : i32 = first; i < last; i++) {\n ${a.indicesSet("inputIndices","uniforms.axis","u32(i)")};\n sum = sum + ${a.getByIndices("inputIndices")};\n }\n ${c.setByOffset("global_idx","sum")};\n }`};return{name:"CumSum",shaderCache:{hint:o.cacheKey,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:t,dataType:e}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:[{type:12,data:i},{type:12,data:h},...Z(t,t)]}),getShaderSource:d}},cu=(e,t)=>{let r=e.inputs[0].dims,o=e.inputs[0].dataType,i=e.inputs[1];e.compute(Dc(o,r,i,t),{inputs:[0]})},pu=e=>{let t=e.exclusive===1,r=e.reverse===1;return ve({exclusive:t,reverse:r})}});var zc,Mc,Uc,fu,hu,gu=Y(()=>{"use strict";ye();Se();Ze();_e();zc=e=>{if(!e||e.length!==1)throw new Error("DepthToSpace requires 1 input.");if(e[0].dims.length!==4)throw new Error("DepthToSpace requires 4D input.")},Mc=(e,t,r,o)=>{let i=[];i.push(`fn perm(i: ${o.type.indices}) -> ${r.type.indices} {\n var a: ${r.type.indices};`);for(let u=0;u{let r,o,i,u,a,c,p=t.format==="NHWC",h=t.blocksize,d=t.mode==="DCR";p?([r,o,i,u]=e.dims,a=d?[r,o,i,h,h,u/h**2]:[r,o,i,u/h**2,h,h],c=d?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([r,o,i,u]=[e.dims[0],e.dims[2],e.dims[3],e.dims[1]],a=d?[r,h,h,u/h**2,o,i]:[r,u/h**2,h,h,o,i],c=d?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let y=e.reshape(a),w=y.dims.length,_=e.dataType,v=U("a",_,w),S=j("output",_,w),A=I=>`\n ${I.registerUniform("output_size","u32").declareVariables(v,S)}\n\n ${Mc(c,w,v,S)}\n\n ${I.mainStart()}\n ${I.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n\n let indices = ${S.offsetToIndices("global_idx")};\n let aIndices = perm(indices);\n\n ${S.setByOffset("global_idx",v.getByIndices("aIndices"))}\n }`;return{name:"DepthToSpace",shaderCache:{hint:`${e.dims};${t.blocksize};${t.mode}`,inputDependencies:["rank"]},getRunData:I=>{let x=p?[r,o*h,i*h,u/h**2]:[r,u/h**2,o*h,i*h],E=M.size(x),P=y.dims,O=M.sortBasedOnPerm(P,c);return{outputs:[{dims:x,dataType:I[0].dataType}],dispatchGroup:{x:Math.ceil(E/64)},programUniforms:[{type:12,data:E},...Z(P,O)]}},getShaderSource:A}},fu=(e,t)=>{zc(e.inputs),e.compute(Uc(e.inputs[0],t))},hu=e=>ve({blocksize:e.blocksize,mode:e.mode,format:e.format})});var Fo,Wn,yu,Vc,Wc,qo,jo,bu,Nc,wu,vu,$u=Y(()=>{"use strict";ye();Se();Ze();_e();Fo="[a-zA-Z]|\\\\.\\\\.\\\\.",Wn="("+Fo+")+",yu="^"+Wn+"$",Vc="("+Wn+",)*"+Wn,Wc="^"+Vc+"$",qo=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)}},jo=class{constructor(t,r){this.equation=r;this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=new Array,this.outputDims=[];let[o,i]=r.includes("->")?r.split("->",2):[r,""];if(!o.match(RegExp(Wc)))throw new Error("Invalid LHS term");if(o.split(",").forEach((c,p)=>{let h=t[p].dims.slice();if(!c.match(RegExp(yu)))throw new Error("Invalid LHS term");let d=this.processTerm(c,!0,h,p);this.lhs.push(d)}),i==="")i+=[...this.symbolToInfo.entries()].filter(([c,p])=>p.count===1||c==="...").map(([c])=>c).join("");else if(!i.match(RegExp(Wn)))throw new Error("Invalid RHS");i.match(RegExp(Fo,"g"))?.forEach(c=>{if(c==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let p=this.symbolToInfo.get(c);if(p===void 0)throw new Error("Invalid RHS symbol");this.outputDims.push(p.dimValue)}}),this.rhs=this.processTerm(i,!1,this.outputDims)}addSymbol(t,r,o){let i=this.symbolToInfo.get(t);if(i!==void 0){if(i.dimValue!==r&&i.count!==1)throw new Error("Dimension mismatch");i.count++,i.inputIndices.push(o)}else i={count:1,dimValue:r,inputIndices:[o]};this.symbolToInfo.set(t,i)}processTerm(t,r,o,i=-1){let u=o.length,a=!1,c=[],p=0;if(!t.match(RegExp(yu))&&!r&&t!=="")throw new Error("Invalid LHS term");let h=t.match(RegExp(Fo,"g")),d=new qo(i);return h?.forEach((y,w)=>{if(y==="..."){if(a)throw new Error("Only one ellipsis is allowed per input term");a=!0;let _=u-h.length+1;if(_<0)throw new Error("Ellipsis out of bounds");if(c=o.slice(p,p+_),this.hasEllipsis){if(this.ellipsisDims.length!==c.length||this.ellipsisDims.toString()!==c.toString())throw new Error("Ellipsis dimensions mismatch")}else if(r)this.hasEllipsis=!0,this.ellipsisDims=c;else throw new Error("Ellipsis must be specified in the LHS");for(let v=0;ve+"_max",Nc=(e,t,r,o)=>{let u=e.map(d=>d.length).map((d,y)=>U(`input${y}`,t,d)),a=M.size(o),c=j("output",t,o.length),p=[...r.symbolToInfo.keys()].filter(d=>!r.rhs.symbolToIndices.has(d)),h=d=>{let y=[],w="var prod = 1.0;",_="var sum = 0.0;",v="sum += prod;",S=[],A=[],I=[],x=[],E=r.symbolToInfo.size===r.rhs.symbolToIndices.size;r.symbolToInfo.forEach((O,R)=>{if(r.rhs.symbolToIndices.has(R)){let L=r.rhs.symbolToIndices.get(R)?.[0];L!==void 0&&r.lhs.forEach((N,K)=>{if(O.inputIndices.includes(K)){let Q=N.symbolToIndices.get(R);if(Q===void 0)throw new Error("Invalid symbol error");Q.forEach(he=>{y.push(`${u[K].indicesSet(`input${K}Indices`,he,c.indicesGet("outputIndices",L))}`)})}})}else r.lhs.forEach((L,N)=>{if(O.inputIndices.includes(N)){let K=L.symbolToIndices.get(R);if(K===void 0)throw new Error("Invalid symbol error");K.forEach(Q=>{S.push(`${u[N].indicesSet(`input${N}Indices`,Q,`${R}`)}`)}),x.push(`prod *= ${u[N].getByIndices(`input${N}Indices`)};`)}}),A.push(`for(var ${R}: u32 = 0; ${R} < uniforms.${bu(R)}; ${R}++) {`),I.push("}")});let P=E?[...y,`let sum = ${u.map((O,R)=>O.getByIndices(`input${R}Indices`)).join(" * ")};`]:[...y,_,...A,...S,w,...x,v,...I];return`\n ${d.registerUniforms(p.map(O=>({name:`${bu(O)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...u,c)}\n\n ${d.mainStart()}\n ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n var outputIndices = ${c.offsetToIndices("global_idx")};\n ${u.map((O,R)=>`var input${R}Indices: ${u[R].type.indices};`).join(`\n`)}\n ${P.join(`\n`)};\n ${c.setByOffset("global_idx","sum")};\n }`};return{name:"Einsum",shaderCache:{hint:r.equation,inputDependencies:e.map(()=>"rank")},getRunData:()=>{let d=p.filter(w=>r.symbolToInfo.has(w)).map(w=>({type:12,data:r.symbolToInfo.get(w)?.dimValue||0}));d.push({type:12,data:a});let y=e.map((w,_)=>[...Z(w)]).reduce((w,_)=>w.concat(_),d);return y.push(...Z(o)),{outputs:[{dims:o,dataType:t}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:y}},getShaderSource:h}},wu=(e,t)=>{let r=new jo(e.inputs,t.equation),o=r.outputDims,i=e.inputs.map((u,a)=>u.dims);e.compute(Nc(i,e.inputs[0].dataType,r,o))},vu=e=>{let t=e.equation.replace(/\\s+/g,"");return ve({equation:t})}});var Gc,_u,Hc,Lc,Su,xu=Y(()=>{"use strict";ye();Se();_e();Gc=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 i=0;ie.length>t.length?_u(e,t):_u(t,e),Lc=e=>{let t=e[0].dims,r=Array.from(e[1].getBigInt64Array(),Number),o=Hc(t,r),i=e[0].dataType,u=i===9?4:1,a=Math.ceil(M.size(o)/u),c=h=>{let d=U("input",i,t.length,u),y=j("output",i,o.length,u),w;if(i===9){let _=(v,S,A="")=>`\n let outputIndices${S} = ${y.offsetToIndices(`outputOffset + ${S}u`)};\n let offset${S} = ${d.broadcastedIndicesToOffset(`outputIndices${S}`,y)};\n let index${S} = offset${S} / 4u;\n let component${S} = offset${S} % 4u;\n ${v}[${S}] = ${A}(${d.getByOffset(`index${S}`)}[component${S}]);\n `;w=`\n let outputOffset = global_idx * ${u};\n var data = vec4(0);\n ${_("data",0,"u32")}\n ${_("data",1,"u32")}\n ${_("data",2,"u32")}\n ${_("data",3,"u32")}\n ${y.setByOffset("global_idx","data")}\n }`}else w=`\n let outputIndices = ${y.offsetToIndices("global_idx")};\n let inputOffset = ${d.broadcastedIndicesToOffset("outputIndices",y)};\n ${y.setByOffset("global_idx",d.getByOffset("inputOffset"))}\n }`;return`\n ${h.registerUniform("vec_size","u32").declareVariables(d,y)}\n ${h.mainStart()}\n ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}\n ${w}`},p=[{type:12,data:a},...Z(t,o)];return{name:"Expand",shaderCache:{hint:`${o.length}`,inputDependencies:["rank"]},getShaderSource:c,getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:p})}},Su=e=>{Gc(e.inputs),e.compute(Lc(e.inputs),{inputs:[0]})}});var Fc,Cu,Au=Y(()=>{"use strict";ye();Se();_e();Rn();Fc=e=>{let t=e[0].dataType,r=M.size(e[0].dims),o=M.size(e[1].dims),i=o%4===0,u=a=>{let c=U("x",t,[1],4),p=U("bias",t,[1],4),h=j("y",t,[1],4),d=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],y=_=>`\n let bias${_}_offset: u32 = (global_idx * 4 + ${_}) % uniforms.bias_size;\n let bias${_} = ${p.getByOffset(`bias${_}_offset / 4`)}[bias${_}_offset % 4];`,w=i?`\n let bias = ${p.getByOffset("global_idx % (uniforms.bias_size / 4)")};`:`${y(0)}${y(1)}${y(2)}${y(3)}\n let bias = ${c.type.value}(bias0, bias1, bias2, bias3);`;return`${a.registerUniforms(d).declareVariables(c,p,h)}\n\n ${Bo(et(t))}\n\n ${a.mainStart(or)}\n ${a.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")}\n\n let x = ${c.getByOffset("global_idx")};\n ${w}\n let x_in = x + bias;\n ${h.setByOffset("global_idx",Do("x_in"))}\n }`};return{name:"FastGeluWithBias",shaderCache:{hint:`${i}`,inputDependencies:["type","type"]},getShaderSource:u,getRunData:a=>({outputs:[{dims:a[0].dims,dataType:a[0].dataType}],programUniforms:[{type:12,data:Math.ceil(r/4)},{type:12,data:o}],dispatchGroup:{x:Math.ceil(r/or/4)}})}},Cu=e=>{e.inputs.length<2||M.size(e.inputs[1].dims)===0?Bs(e):e.compute(Fc(e.inputs))}});var qc,jc,Iu,Tu,Eu=Y(()=>{"use strict";ye();Se();Ze();_e();qc=e=>{if(!e||e.length!==2)throw new Error("Gather requires 2 inputs.")},jc=(e,t)=>{let r=e[0].dims,o=e[1].dims,i=r.length,u=M.normalizeAxis(t.axis,i),a=r.slice(0);a.splice(u,1,...o);let c=r[u],p=e[0].dataType===9?4:1,h=Math.ceil(M.size(a)/p),d=[{type:12,data:h},{type:6,data:c},{type:12,data:u},...Z(e[0].dims,e[1].dims,a)],y=w=>{let _=U("data",e[0].dataType,e[0].dims.length,p),v=U("inputIndices",e[1].dataType,e[1].dims.length),S=j("output",e[0].dataType,a.length,p),A=x=>{let E=o.length,P=`var indicesIndices${x} = ${v.type.indices}(0);`;for(let O=0;O1?`indicesIndices${x}[${O}]`:`indicesIndices${x}`} = ${a.length>1?`outputIndices${x}[uniforms.axis + ${O}]`:`outputIndices${x}`};`;P+=`\n var idx${x} = ${v.getByIndices(`indicesIndices${x}`)};\n if (idx${x} < 0) {\n idx${x} = idx${x} + uniforms.axisDimLimit;\n }\n var dataIndices${x} : ${_.type.indices};\n `;for(let O=0,R=0;O1?`dataIndices${x}[${O}]`:`dataIndices${x}`} = u32(idx${x});`,R+=E):(P+=`${i>1?`dataIndices${x}[${O}]`:`dataIndices${x}`} = ${a.length>1?`outputIndices${x}[${R}]`:`outputIndices${x}`};`,R++);return P},I;if(e[0].dataType===9){let x=(E,P,O="")=>`\n let outputIndices${P} = ${S.offsetToIndices(`outputOffset + ${P}u`)};\n ${A(P)};\n let offset${P} = ${_.indicesToOffset(`dataIndices${P}`)};\n let index${P} = offset${P} / 4u;\n let component${P} = offset${P} % 4u;\n ${E}[${P}] = ${O}(${_.getByOffset(`index${P}`)}[component${P}]);\n `;I=`\n let outputOffset = global_idx * ${p};\n var value = vec4(0);\n ${x("value",0,"u32")}\n ${x("value",1,"u32")}\n ${x("value",2,"u32")}\n ${x("value",3,"u32")}\n ${S.setByOffset("global_idx","value")}\n `}else I=`\n let outputIndices = ${S.offsetToIndices("global_idx")};\n ${A("")};\n let value = ${_.getByIndices("dataIndices")};\n ${S.setByOffset("global_idx","value")};\n `;return`\n ${w.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(_,v,S)}\n ${w.mainStart()}\n ${w.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n ${I}\n }`};return{name:"Gather",shaderCache:{hint:t.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:a,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:d}),getShaderSource:y}},Iu=e=>ve({axis:e.axis}),Tu=(e,t)=>{let r=e.inputs;qc(r),e.compute(jc(e.inputs,t))}});var Kc,Yc,Pu,ku,Ou=Y(()=>{"use strict";ye();Se();Ze();_e();Kc=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.`)},Yc=(e,t)=>{let r=e[0].dims,o=e[0].dataType,i=r.length,u=e[1].dims,a=e[1].dataType,c=M.normalizeAxis(t.axis,i),p=r[c],h=u.slice(0),d=M.size(h),y=U("input",o,i),w=U("indicesInput",a,u.length),_=j("output",o,h.length),v=[{type:12,data:d},{type:6,data:p},{type:12,data:c}];return v.push(...Z(r,u,h)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:h,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:v}),getShaderSource:I=>`\n ${I.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(y,w,_)}\n ${I.mainStart()}\n ${I.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n\n let outputIndices = ${_.offsetToIndices("global_idx")};\n\n var idx = ${w.getByOffset("global_idx")};\n if (idx < 0) {\n idx = idx + uniforms.axisDimLimit;\n }\n var inputIndices = ${y.type.indices}(outputIndices);\n ${y.indicesSet("inputIndices","uniforms.axis","u32(idx)")};\n let value = ${y.getByIndices("inputIndices")};\n\n ${_.setByOffset("global_idx","value")};\n }`}},Pu=e=>ve({axis:e.axis}),ku=(e,t)=>{let r=e.inputs;Kc(r),e.compute(Yc(e.inputs,t))}});var Zc,Xc,Ru,Bu,Du=Y(()=>{"use strict";ye();Se();_e();Zc=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")},Xc=(e,t)=>{let r=e[0].dims.slice(),o=e[1].dims.slice(),[i,u,a]=Sn.getShapeOfGemmResult(r,t.transA,o,t.transB,e.length===3?e[2].dims:void 0),c=[i,u];if(!c)throw new Error("Can\'t use gemm on the given tensors");let p=M.size(c),h=[{type:12,data:p},{type:12,data:i},{type:12,data:u},{type:12,data:a},{type:1,data:t.alpha},{type:1,data:t.beta}],d=["type","type"];e.length===3&&(h.push(...Z(e[2].dims)),d.push("rank")),h.push(...Z(c));let y=w=>{let _="";t.transA&&t.transB?_="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":t.transA&&!t.transB?_="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!t.transA&&t.transB?_="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!t.transA&&!t.transB&&(_="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let v=t.alpha===1?"":"value *= uniforms.alpha;",S=U("a",e[0].dataType,e[0].dims),A=U("b",e[1].dataType,e[1].dims),I=S.type.value,x=null,E=[S,A];e.length===3&&(x=U("c",e[2].dataType,e[2].dims.length),E.push(x));let P=j("output",e[0].dataType,c.length);E.push(P);let O=[{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 ${w.registerUniforms(O).declareVariables(...E)}\n\n ${w.mainStart()}\n ${w.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n\n let m = global_idx / uniforms.N;\n let n = global_idx % uniforms.N;\n\n var value = ${I}(0);\n for (var k: u32 = 0u; k < uniforms.K; k++) {\n ${_}\n }\n\n ${v}\n ${(()=>x!=null?`let cOffset = ${x.broadcastedIndicesToOffset("vec2(m, n)",P)}; value += ${I}(uniforms.beta) * ${x.getByOffset("cOffset")};`:"")()}\n output[global_idx] = value;\n }`};return{name:"Gemm",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:d},getRunData:()=>({outputs:[{dims:c,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:h}),getShaderSource:y}},Ru=e=>{let t=e.transA,r=e.transB,o=e.alpha,i=e.beta;return{transA:t,transB:r,alpha:o,beta:i,cacheKey:`${e.transA};${e.transB};${e.alpha===1}`}},Bu=(e,t)=>{Zc(e.inputs),e.compute(Xc(e.inputs,t))}});var Qc,Jc,ep,zu,Mu=Y(()=>{"use strict";ye();Se();_e();Qc=(e,t)=>{let r=e[0].dims,o=r,i=2,u=M.sizeToDimension(r,i),a=M.sizeFromDimension(r,i),c=Me(a),p=a/c,h=[r[0],r[1],p],d=["rank","type","type"],y=[{type:12,data:a},{type:12,data:p}];y.push(...Z(h,h));let w=_=>{let v=U("x",e[0].dataType,h.length,c),S=U("scale",e[1].dataType,e[1].dims),A=U("bias",e[2].dataType,e[2].dims),I=j("output",e[0].dataType,h.length,c),x=[v,S,A,I],E=v.type.value,P=c===1?"f32":`vec${c}`,O=64,R=[{name:"normSize",type:"u32"},{name:"normPackedSize",type:"u32"}];return`\n var meanShared : f32;\n var squaredNormShared : f32;\n var workgroupShared : array<${P}, ${O}>;\n const workgroupSize = ${O}u;\n ${_.registerUniforms(R).declareVariables(...x)}\n ${_.mainStart(O)}\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 = ${P}(0);\n for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) {\n initial = initial + ${P}(${v.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 = ${_t("workgroupShared[0]",c)} / f32(uniforms.normSize);\n }\n workgroupBarrier();\n\n // reinitialize workgroup memory.\n initial = ${P}(0);\n for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) {\n let deviation = ${P}(${v.get("batch","channel","h")}) - ${P}(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 = ${_t("workgroupShared[0]",c)};\n }\n workgroupBarrier();\n\n let invStdDev = inverseSqrt(squaredNormShared / f32(uniforms.normSize) + f32(${t.epsilon}));\n let channelScale = invStdDev * f32(${S.getByOffset("channel")});\n let channelShift = f32(${A.getByOffset("channel")}) - meanShared * channelScale;\n for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) {\n let value = ${v.get("batch","channel","h")} * ${E}(${P}(channelScale)) + ${E}(${P}(channelShift));\n ${I.set("batch","channel","h","value")};\n }\n }`};return{name:"InstanceNormalization",shaderCache:{hint:`${t.epsilon};${c}`,inputDependencies:d},getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:u},programUniforms:y}),getShaderSource:w}},Jc=(e,t,r,o,i,u,a,c)=>{let p=Me(a),h=64,d=p===1?"vec2f":`mat2x${p}f`,y=p===1?"f32":`vec${p}f`,w=(R,L)=>`${d}(${R}, ${L})`,_=i*a/p,v=Math.ceil(u/h),S=["type"],A=[{type:12,data:v},{type:12,data:u},{type:12,data:Math.floor(a/p)},{type:12,data:Math.floor(u*a/p)}],I=R=>{let L=U("input",t.dataType,t.dims,p);return`\n ${R.declareVariables(L)}\n @group(0) @binding(1) var output : array<${d}>;\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(h)}\n let currentImageNumber = global_idx / ${h} / uniforms.C;\n let currentChannelNumber = (global_idx / ${h}) % uniforms.C;\n let wgOffset = local_id.x * 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 = ${$t("f32",p)};\n var squaredSum = ${$t("f32",p)};\n for (var i: u32 = wgOffset; i < wgMax; i++) {\n let value = ${y}(input[offset + i * uniforms.C]);\n sum += value;\n squaredSum += value * value;\n }\n output[global_idx] = ${w("sum","squaredSum")};\n }`},x=e.compute({name:"InstanceNormComputeMean",shaderCache:{hint:`${p}`,inputDependencies:S},getRunData:()=>({outputs:[{dims:[i,a,h,2],dataType:1}],dispatchGroup:{x:i*a/p},programUniforms:A}),getShaderSource:I},{inputs:[t],outputs:[-1]})[0],E=[{type:12,data:_},{type:12,data:u},{type:12,data:Math.floor(a/p)},{type:12,data:Math.floor(h*a/p)}],P=["type","type","type"],O=R=>{let L=U("scale",r.dataType,r.dims,p),N=U("bias",o.dataType,o.dims,p);return`\n @group(0) @binding(0) var input : array<${d}>;\n @group(0) @binding(1) var scale : array<${L.type.storage}>;\n @group(0) @binding(2) var bias : array<${N.type.storage}>;\n @group(0) @binding(3) var output : array<${d}>;\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 = ${$t("f32",p)};\n var squaredSum = ${$t("f32",p)};\n for (var i: u32 = 0; i < min(${h}, uniforms.H); i++) {\n let value = input[offset + i + currentChannelNumber * ${h}];\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(${c}));\n let channelScale = invStdDev * ${y}(scale[currentChannelNumber]);\n let channelShift = ${y}(bias[currentChannelNumber]) - sum * channelScale;\n\n output[global_idx] = ${w("channelScale","channelShift")};\n }`};return e.compute({name:"InstanceNormComputeChannelScaleShift",shaderCache:{hint:`${p};${c}`,inputDependencies:P},getRunData:()=>({outputs:[{dims:[i,a,2],dataType:1}],dispatchGroup:{x:Math.ceil(_/64)},programUniforms:E}),getShaderSource:O},{inputs:[x,r,o],outputs:[-1]})[0]},ep=(e,t,r)=>{let o=t[0].dims,i=o,u=o[0],a=o[o.length-1],c=M.sizeFromDimension(o,1)/a,p=Me(a),h=M.size(i)/p,d=[{type:12,data:c},{type:12,data:Math.floor(a/p)}],y=["type","type"],w=Jc(e,t[0],t[1],t[2],u,c,a,r.epsilon),_=v=>{let S=De(t[0].dataType),A=p===1?"vec2f":`mat2x${p}f`,I=p===1?S:`vec${p}<${S}>`,x=U("input",t[0].dataType,t[0].dims,p),E=j("output",t[0].dataType,i,p);return`\n @group(0) @binding(0) var input : array<${x.type.storage}>;\n @group(0) @binding(1) var scaleInput : array<${A}>;\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 ${v.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], ${I}(scale[0]), ${I}(scale[1]));\n }`};e.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${p}`,inputDependencies:y},getRunData:()=>({outputs:[{dims:i,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:d}),getShaderSource:_},{inputs:[t[0],w]})},zu=(e,t)=>{t.format==="NHWC"?ep(e,e.inputs,t):e.compute(Qc(e.inputs,t))}});var tp,rp,Uu,Vu=Y(()=>{"use strict";ye();Se();_e();tp=e=>{if(!e||e.length<2)throw new Error("layerNorm requires at least 2 inputs.")},rp=(e,t,r)=>{let o=t.simplified,i=e[0].dims,u=e[1],a=!o&&e[2],c=i,p=M.normalizeAxis(t.axis,i.length),h=M.sizeToDimension(i,p),d=M.sizeFromDimension(i,p),y=M.size(u.dims),w=a?M.size(a.dims):0;if(y!==d||a&&w!==d)throw new Error(`Size of X.shape()[axis:] == ${d}.\n Size of scale and bias (if provided) must match this.\n Got scale size of ${y} and bias size of ${w}`);let _=[];for(let O=0;O1,x=r>2,E=O=>{let R=De(e[0].dataType),L=[U("x",e[0].dataType,e[0].dims,v),U("scale",u.dataType,u.dims,v)];a&&L.push(U("bias",a.dataType,a.dims,v)),L.push(j("output",e[0].dataType,c,v)),I&&L.push(j("mean_data_output",1,_)),x&&L.push(j("inv_std_output",1,_));let N=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return`\n ${O.registerUniforms(N).declareVariables(...L)}\n ${O.mainStart()}\n ${O.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")}\n let offset = global_idx * uniforms.norm_size_vectorized;\n var mean_vector = ${$t("f32",v)};\n var mean_square_vector = ${$t("f32",v)};\n\n for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) {\n let value = ${ir(R,v,"x[h + offset]")};\n mean_vector += value;\n mean_square_vector += value * value;\n }\n let mean = ${_t("mean_vector",v)} / uniforms.norm_size;\n let inv_std_dev = inverseSqrt(${_t("mean_square_vector",v)} / uniforms.norm_size ${o?"":"- mean * mean"} + uniforms.epsilon);\n\n for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) {\n let f32input = ${ir(R,v,"x[j + offset]")};\n let f32scale = ${ir(R,v,"scale[j]")};\n output[j + offset] = ${L[0].type.value}((f32input ${o?"":"- mean"}) * inv_std_dev * f32scale\n ${a?`+ ${ir(R,v,"bias[j]")}`:""}\n );\n }\n\n ${I?"mean_data_output[global_idx] = mean":""};\n ${x?"inv_std_output[global_idx] = inv_std_dev":""};\n }`},P=[{dims:c,dataType:e[0].dataType}];return I&&P.push({dims:_,dataType:1}),x&&P.push({dims:_,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${v};${r};${o}`,inputDependencies:S},getRunData:()=>({outputs:P,dispatchGroup:{x:Math.ceil(h/64)},programUniforms:A}),getShaderSource:E}},Uu=(e,t)=>{tp(e.inputs),e.compute(rp(e.inputs,t,e.outputCount))}});var np,op,Wu,Nu,Gu=Y(()=>{"use strict";ye();Se();Ze();_e();np=(e,t)=>{if(e.length<3||e.length>4)throw new Error("MatMulNBits requires 3 or 4 inputs");let r=e[0],o=r.dims.length;if(r.dims[o-1]!==t.k)throw new Error("The last dim of input shape does not match the k value");let i=Math.floor((t.k+t.blockSize-1)/t.blockSize),u=t.blockSize/8*t.bits,a=e[1];if(!M.areEqual(a.dims,[t.n,i,u]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let p=e[2].dims;if(M.size(p)!==t.n*i)throw new Error("scales input size error.");if(e.length===4){let d=e[3].dims,y=t.bits>4?t.n*i:t.n*Math.floor((i+1)/2);if(M.size(d)!==y)throw new Error("zeroPoints input size error.")}},op=(e,t,r,o)=>{let i=e[0].dims,u=i.length,a=Math.floor((t.k+t.blockSize-1)/t.blockSize),c=i[u-2],p=t.k,h=t.n,d=i.slice(0,u-2),y=M.size(d),_=t.blockSize/8*t.bits/4,v=e[0].dataType,S=Me(c),A=Me(t.k),I=Me(_),x=tr(v),E=c*a*x,P=Math.floor(o/E),O=a<=r[0]&&P>0,R=!O||P>=4?Me(h):P>=2&&Me(h)>=2?2:1,L=d.concat([c,h]),N=M.size(L)/R/S,K=O?[]:[{type:12,data:N},{type:12,data:t.blockSize}],Q=[y,c,p/A],he=M.convertShape(e[1].dims).slice();he.splice(-1,1,_/I),K.push(...Z(Q)),K.push(...Z(he)),K.push(...Z(e[2].dims)),e.length===4&&K.push(...Z(M.convertShape(e[3].dims)));let W=[y,c,h/R];K.push(...Z(W));let se=Ce=>{let We=Q.length,ee=U("a",e[0].dataType,We,A),ae=U("b",12,he.length,I),Ae=U("scales",e[2].dataType,e[2].dims.length),me=[ee,ae,Ae],ie=e.length===4?U("zero_points",12,e[3].dims.length):void 0;ie&&me.push(ie);let ue=W.length,le=j("output",e[0].dataType,ue,R),qe=[{name:"output_size",type:"u32"},{name:"block_size",type:"u32"}],G=De(e[0].dataType),ne=(()=>{switch(A){case 1:return`array<${G}, 8>`;case 2:return`mat4x2<${G}>`;case 4:return`mat2x4<${G}>`;default:throw new Error(`${A}-component is not supported.`)}})(),xe=`\n for (var word: u32 = 0; word < ${_}; word += ${I}) {\n ${ae.indicesSet("b_indices","2","word")};\n let b_data = ${ae.getByIndices("b_indices")};\n for (var i: u32 = 0; i < ${I}; i++) {\n let b_value: u32 = ${I===1?"b_data":"b_data[word + i]"};\n let b_mask: u32 = 0x0F0F0F0Fu;\n let b_value_lower: vec4 = unpack4xU8(b_value & b_mask);\n let b_value_upper: vec4 = unpack4xU8((b_value >> 4) & b_mask);\n let b_quantized_values = ${ne}(${Array.from({length:4},(Be,Ge)=>`${G}(b_value_lower[${Ge}]), ${G}(b_value_upper[${Ge}])`).join(", ")});\n let b_dequantized_values = ${(()=>A===1?`${ne}(${Array.from({length:8},(Be,Ge)=>`(b_quantized_values[${Ge}] - zero_point) * scale`).join(", ")});`:`(b_quantized_values - ${ne}(${Array(8).fill("zero_point").join(",")})) * scale;`)()};\n // Number of B elements per 32-bit word is 32/bits = 32/4 = 8\n for (var m: u32 = 0; m < ${O?c:S}u; m++) {\n ${ee.indicesSet("a_indices",We-2,O?"m":`row * ${S} + m`)};\n ${ee.indicesSet("a_indices",We-1,"word_offset")};\n var input_offset = ${ee.indicesToOffset("a_indices")};\n var a_data: ${ne};\n for (var j: u32 = 0; j < ${8/A}; j++) {\n a_data[j] = ${ee.getByOffset("input_offset")};\n input_offset++;\n }\n ${O?"workgroup_shared[workgroup_shared_offset + m]":"output_values[m]"}${R>1?"[c]":""} += ${Array.from({length:8/A},(Be,Ge)=>`${A===1?`a_data[${Ge}] * b_dequantized_values[${Ge}]`:`dot(a_data[${Ge}], b_dequantized_values[${Ge}])`}`).join(" + ")};\n }\n word_offset += ${8/A};\n }\n }`,Ke=ie?`\n zero_point_offset += 4;\n if (zero_point_offset == 32) {\n zero_point_offset = 0;\n zero_point_index++;\n zero_point_word = ${ie.getByOffset("zero_point_index")};\n }`:"";return O?`\n var workgroup_shared: array<${le.type.value}, ${c*a}>;\n ${Ce.declareVariables(...me,le)}\n ${Ce.mainStart([a,1,1])}\n var a_indices: ${ee.type.indices};\n var block = local_id.x;\n var col = workgroup_id.y;\n var batch = workgroup_id.z;\n ${ee.indicesSet("a_indices","0","batch")};\n // Two zero points are packed into one byte when uniforms.bits is 4.\n for (var c: u32 = 0; c < ${R}; c++) {\n let col_times_components_plus_c = col * ${R} + c;\n ${ie?`\n var zero_point_bytes_per_col: u32 = (${a} + 1) / 2;\n var zero_point_byte_count: u32 = col_times_components_plus_c * zero_point_bytes_per_col + (block >> 0x1u);\n var zero_point_word_index: u32 = zero_point_byte_count >> 0x2u;\n var zero_point_byte_offset: u32 = zero_point_byte_count & 0x3u;\n var zero_point_nibble_offset: u32 = block & 0x1u;\n var zero_point_bits_offset: u32 = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2);\n var zero_point_word: u32 = ${ie.getByOffset("zero_point_word_index")} >> zero_point_bits_offset;`:""}\n var b_indices: ${ae.type.indices};\n ${ae.indicesSet("b_indices","0","col_times_components_plus_c")};\n // The scale and zero points are computed per block.\n var scales_index = col_times_components_plus_c * ${a} + block;\n let scale = ${Ae.getByOffset("scales_index")};\n // The default zero point is 8 for unsigned 4-bit quantization.\n let zero_point = ${G}(${ie?"(zero_point_word) & 0xFu":8});\n ${ae.indicesSet("b_indices","1","block")};\n var word_offset: u32 = block * ${t.blockSize/A};\n var workgroup_shared_offset: u32 = block * ${c};\n ${xe}\n }\n workgroupBarrier();\n if (local_id.x == 0u) {\n var output_indices: ${le.type.indices};\n ${le.indicesSet("output_indices","0","batch")};\n ${le.indicesSet("output_indices",ue-1,"col")};\n ${le.indicesSet("output_indices",ue-2,"0")};\n var output_offset = ${le.indicesToOffset("output_indices")};\n for (var m: u32 = 0u; m < ${c}u; m++) {\n var output_value: ${le.type.value} = ${le.type.value}(0);\n var workgroup_shared_offset: u32 = m;\n for (var b: u32 = 0u; b < ${a}u; b++) {\n output_value += workgroup_shared[workgroup_shared_offset];\n workgroup_shared_offset += ${c};\n }\n ${le.setByOffset("output_offset","output_value")};\n output_offset += ${h/R};\n }\n }\n }`:`\n ${Ce.registerUniforms(qe).declareVariables(...me,le)}\n ${Ce.mainStart()}\n ${Ce.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n var output_values: array<${le.type.value}, ${S}>;\n var output_indices = ${le.offsetToIndices("global_idx")};\n var col = ${le.indicesGet("output_indices",ue-1)};\n var row = ${le.indicesGet("output_indices",ue-2)};\n var a_indices: ${ee.type.indices} = output_indices;\n // Two zero points are packed into one byte because uniforms.bits <= 4.\n // zero_point_offset is either 0 or 4. It is bit offset within one byte.\n // TODO support zero_point_offset for bits > 4\n ${ie?`\n var zero_point_abs_offset = col * ${R} * ((${a} + 1) / 2);\n var zero_point_index: u32 = zero_point_abs_offset / 4;\n var zero_point_word: u32 = ${ie.getByOffset("zero_point_index")};\n var zero_point_offset: u32 = (zero_point_abs_offset % 4) * 8;`:""}\n var scale_index = col * ${a*R};\n var b_indices: ${ae.type.indices};\n for (var c: u32 = 0; c < ${R}; c++) {\n ${ae.indicesSet("b_indices","0",`col * ${R} + c`)};\n var block_offset: u32 = 0;\n for (var block: u32 = 0; block < ${a}; block++) {\n // The scale and zero points are computed per block.\n let scale = ${Ae.getByOffset("scale_index")};\n // The default zero point is 8 for unsigned 4-bit quantization.\n let zero_point = ${G}(${ie?"extractBits(zero_point_word, zero_point_offset, 4)":8});\n ${ae.indicesSet("b_indices","1","block")};\n var word_offset: u32 = block_offset;\n ${xe}\n scale_index++;\n ${Ke}\n block_offset += uniforms.block_size / ${A};\n }\n // Drop the trailing 4 bits if the zero_poit_offset is not a byte boundary to align with the next byte.\n ${ie?`if (zero_point_offset % 8 > 0) {\n ${Ke}\n }`:""}\n }\n for (var k: u32 = 0u; k < ${S}u; k++) {\n ${le.indicesSet("output_indices",ue-2,`${S} * row + k`)};\n ${le.setByIndices("output_indices","output_values[k]")}\n }\n }`};return{name:O?"BlockwiseMatMulNBits":"MatMulNBits",shaderCache:{hint:`${t.cacheKey};${c};${v};${e.length}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:L,dataType:v}],name:O?"BlockwiseMatMulNBits":"MatMulNBits",dispatchGroup:O?{x:1,y:Math.ceil(h/R),z:y}:{x:Math.ceil(N/64)},programUniforms:K}),getShaderSource:se}},Wu=(e,t)=>{np(e.inputs,t);let r=e.getMaxComputeWorkgroupSizes(),o=e.getMaxComputeWorkgroupStoragesize();e.compute(op(e.inputs,t,r,o))},Nu=e=>ve(e)});var it,ip,Lu,Hu,ap,Ko,Fu,qu=Y(()=>{"use strict";ye();Se();Ze();_n();Ro();_e();Sr();it=(e,t)=>e.length>t&&e[t].dims.length>0&&M.size(e[t].dims)>0?e[t]:void 0,ip=(e,t)=>{let r=e[0],o=it(e,1),i=it(e,2),u=it(e,3),a=it(e,4),c=it(e,5),p=it(e,6),h=it(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 d=!1,y=r.dims[0],w=r.dims[1],_=r.dims.length===3?d?r.dims[2]/3:r.dims[2]:t.numHeads*r.dims[4],v=w,S=0,A=0,I=Math.floor(_/t.numHeads);if(p&&h){if(p.dims.length!==4)throw new Error(\'Input "past_key" is expected to have 4 dimensions\');if(p.dims[0]!==y||p.dims[1]!==t.numHeads||p.dims[3]!==I)throw new Error(\'Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)\');if(h.dims[0]!==y||h.dims[1]!==t.numHeads||h.dims[3]!==I)throw new Error(\'Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)\');if(p.dims[2]!==h.dims[2])throw new Error(\'Input "past_key" and "past_value" shall have same dim 2 (past_sequence_length)\');if(h.dims.length!==4)throw new Error(\'Input "past_value" is expected to have 4 dimensions\');S=p.dims[2],A=p.dims[2]}else if(p||h)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,v=o.dims[1]}else if(o.dims.length===5){if(o.dims[2]!==t.numHeads||o.dims[3]!==2||o.dims[4]!==I)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.\');x=5,v=o.dims[1]}else{if(o.dims[1]!==t.numHeads||o.dims[3]!==I)throw new Error(\'Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key\');x=0,v=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(u){if(u.dims.length!==1)throw new Error(\'Input "bias" is expected to have 1 dimension\');if(i&&r.dims.length===5&&r.dims[3]===2)throw new Error("bias is not allowed for packed kv.")}let E=0;if(a){E=8;let N=a.dims;throw N.length===1?N[0]===y?E=1:N[0]===3*y+2&&(E=3):N.length===2&&N[0]===y&&N[1]===v&&(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 P=!1,O=_;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(r.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(v!==i.dims[1])throw new Error(\'Input "key" and "value" shall have the same dim 1 (kv_sequence_length)\');O=i.dims[2]}else{if(v!==i.dims[2])throw new Error(\'Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)\');O=i.dims[1]*i.dims[3],P=!0}}let R=S+v,L=!1;if(a)throw new Error("Key padding mask is not supported");if(c){if(c.dims.length!==4)throw new Error(\'Input "relative_position_bias" is expected to have 4 dimensions\');if(c.dims[0]!==y&&c.dims[0]!==1||c.dims[1]!==t.numHeads||c.dims[2]!==w||c.dims[3]!==R)throw new Error(\'Input "relative_position_bias" shape (batch_size, 1, sequence_length, kv_sequence_length)\')}return{batchSize:y,sequenceLength:w,pastSequenceLength:S,kvSequenceLength:v,totalSequenceLength:R,maxSequenceLength:A,inputHiddenSize:0,hiddenSize:_,vHiddenSize:O,headSize:I,vHeadSize:Math.floor(O/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:E,scale:t.scale,broadcastResPosBias:L,passPastInKv:P,qkvFormat:x}},Lu=e=>ve({...e}),Hu=ve({perm:[0,2,1,3]}),ap=(e,t,r,o,i,u,a)=>{let c=[o,i,u],p=M.size(c),h=[{type:12,data:p},{type:12,data:a},{type:12,data:u}],d=y=>{let w=j("qkv_with_bias",t.dataType,c),_=U("qkv",t.dataType,c),v=U("bias",r.dataType,c),S=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return`\n ${y.registerUniforms(S).declareVariables(_,v,w)}\n ${y.mainStart()}\n ${y.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:c,dataType:t.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:h}),getShaderSource:d},{inputs:[t,r],outputs:[-1]})[0]},Ko=(e,t,r,o,i,u,a,c)=>{let p=u;if(a){if(o===1)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return p=ap(e,u,a,t,o,r*i,c),p=p.reshape([t,o,r,i]),e.compute(yt(p,Hu.perm),{inputs:[p],outputs:[-1]})[0]}else return u.dims.length===3&&(p=u.reshape([t,o,r,i])),e.compute(yt(p,Hu.perm),{inputs:[p],outputs:[-1]})[0]},Fu=(e,t)=>{let r=ip(e.inputs,t),o=e.inputs[0],i=it(e.inputs,1),u=it(e.inputs,2),a=it(e.inputs,3),c=it(e.inputs,4),p=it(e.inputs,5),h=it(e.inputs,6),d=it(e.inputs,7);if(o.dims.length===5)throw new Error("Packed QKV is not implemented");if(i?.dims.length===5)throw new Error("Packed KV is not implemented");let y=i&&u&&i.dims.length===4&&u.dims.length===4,w=Ko(e,r.batchSize,r.numHeads,r.sequenceLength,r.headSize,o,a,0);if(y)return Pn(e,w,i,u,c,void 0,h,d,p,r,t);if(!i||!u)throw new Error("key and value must be provided");let _=Ko(e,r.batchSize,r.numHeads,r.kvSequenceLength,r.headSize,i,a,r.hiddenSize),v=Ko(e,r.batchSize,r.numHeads,r.kvSequenceLength,r.vHeadSize,u,a,2*r.hiddenSize);Pn(e,w,_,v,c,void 0,h,d,p,r,t)}});var sp,up,dp,lp,cp,pp,mp,fp,ju,Ku=Y(()=>{"use strict";ye();Se();_e();sp=e=>{if(!e||e.length<1)throw new Error("Too few inputs");if(e[0].dataType!==1&&e[0].dataType!==10)throw new Error("Input type must be float or float16.");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].")}},up=(e,t,r)=>{let o="";for(let i=t-1;i>=0;--i)o+=`\n k = i32(${e.indicesGet("indices",i)}) - ${fe("uniforms.pads",i,r)};\n if (k < 0) {\n break;\n }\n if (k >= i32(${fe("uniforms.x_shape",i,t)})) {\n break;\n }\n offset += k * i32(${fe("uniforms.x_strides",i,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 `},dp=(e,t,r)=>{let o="";for(let i=t-1;i>=0;--i)o+=`\n k = i32(${e.indicesGet("indices",i)}) - ${fe("uniforms.pads",i,r)};\n if (k < 0) {\n k = -k;\n }\n {\n let _2n_1 = 2 * (i32(${fe("uniforms.x_shape",i,t)}) - 1);\n k = k % _2n_1;\n if(k >= i32(${fe("uniforms.x_shape",i,t)})) {\n k = _2n_1 - k;\n }\n }\n offset += k * i32(${fe("uniforms.x_strides",i,t)});\n `;return`\n var offset = 0;\n var k = 0;\n ${o}\n value = x[offset];\n `},lp=(e,t,r)=>{let o="";for(let i=t-1;i>=0;--i)o+=`\n k = i32(${e.indicesGet("indices",i)}) - ${fe("uniforms.pads",i,r)};\n if (k < 0) {\n k = 0;\n }\n if (k >= i32(${fe("uniforms.x_shape",i,t)})) {\n k = i32(${fe("uniforms.x_shape",i,t)}) - 1;\n }\n offset += k * i32(${fe("uniforms.x_strides",i,t)});\n `;return`\n var offset = 0;\n var k = 0;\n ${o}\n value = x[offset];\n `},cp=(e,t,r)=>{let o="";for(let i=t-1;i>=0;--i)o+=`\n k = i32(${e.indicesGet("indices",i)}) - ${fe("uniforms.pads",i,r)};\n if (k < 0) {\n k += i32(${fe("uniforms.x_shape",i,t)}]);\n }\n if (k >= i32(${fe("uniforms.x_shape",i,t)})) {\n k -= i32(${fe("uniforms.x_shape",i,t)});\n }\n offset += k * i32(${fe("uniforms.x_strides",i,t)});\n `;return`\n var offset = 0;\n var k = 0;\n ${o}\n value = x[offset];\n `},pp=(e,t,r)=>{switch(r.mode){case 0:return up(e,t,r.pads.length);case 1:return dp(e,t,r.pads.length);case 2:return lp(e,t,r.pads.length);case 3:return cp(e,t,r.pads.length);default:throw new Error("Invalid mode")}},mp=(e,t)=>{let r=M.padShape(e[0].dims.slice(),t.pads),o=e[0].dims,i=M.size(r),u=[{type:12,data:i},{type:6,data:t.pads}];t.mode===0&&u.push({type:e[0].dataType,data:t.value}),u.push(...Z(e[0].dims,r));let a=["rank"],c=p=>{let h=j("output",e[0].dataType,r.length),d=U("x",e[0].dataType,o.length),y=d.type.value,w=pp(h,o.length,t),_=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:t.pads.length}];return t.mode===0&&_.push({name:"constant_value",type:y}),`\n ${p.registerUniforms(_).declareVariables(d,h)}\n ${p.mainStart()}\n ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n\n let indices = ${h.offsetToIndices("global_idx")};\n\n var value = ${y}(0);\n ${w}\n output[global_idx] = value;\n }`};return{name:"Pad",shaderCache:{hint:`${t.mode}`,inputDependencies:a},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(M.size(r)/64)},programUniforms:u}),getShaderSource:c}},fp=(e,t)=>{if(e.length>1){let r=e[1].getBigInt64Array(),o=e.length>=3&&e[2].data?e[2].getFloat32Array()[0]:0,i=e[0].dims.length,u=new Int32Array(2*i).fill(0);if(e.length>=4){let c=e[3].getBigInt64Array();for(let p=0;pu[Number(p)]=Number(c));let a=[];return u.forEach(c=>a.push(c)),{mode:t.mode,value:o,pads:a}}else return t},ju=(e,t)=>{sp(e.inputs);let r=fp(e.inputs,t);e.compute(mp(e.inputs,r),{inputs:[0]})}});var Nn,Yu,Zu,Xu,Qu,hp,gp,Ju,ed,td,rd,nd,od,id,ad,sd,ud,dd,ld,cd=Y(()=>{"use strict";$r();ye();Se();_e();Nn=e=>{if(vr.webgpu.validateInputContent&&(!e||e.length!==1))throw new Error("Pool ops requires 1 input.")},Yu=(e,t,r)=>{let o=t.format==="NHWC",i=e.dims.slice();o&&i.splice(1,0,i.pop());let u=Object.hasOwnProperty.call(t,"dilations"),a=t.kernelShape.slice(),c=t.strides.slice(),p=u?t.dilations.slice():[],h=t.pads.slice();nr.adjustPoolAttributes(r,i,a,c,p,h);let d=nr.computePoolOutputShape(r,i,c,p,a,h,t.autoPad),y=Object.assign({},t);u?Object.assign(y,{kernelShape:a,strides:c,pads:h,dilations:p,cacheKey:t.cacheKey}):Object.assign(y,{kernelShape:a,strides:c,pads:h,cacheKey:t.cacheKey});let w=d.slice();return w.push(w.splice(1,1)[0]),[y,o?w:d]},Zu=(e,t)=>{let r=t.format==="NHWC",o=M.size(e),i=M.size(t.kernelShape),u=[{type:12,data:o},{type:12,data:i}],a=[{name:"outputSize",type:"u32"},{name:"kernelSize",type:"u32"}];if(t.kernelShape.length<=2){let c=t.kernelShape[t.kernelShape.length-1],p=t.strides[t.strides.length-1],h=t.pads[t.pads.length/2-1],d=t.pads[t.pads.length-1],y=!!(h+d);u.push({type:12,data:c},{type:12,data:p},{type:12,data:h},{type:12,data:d}),a.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let w=!1;if(t.kernelShape.length===2){let _=t.kernelShape[t.kernelShape.length-2],v=t.strides[t.strides.length-2],S=t.pads[t.pads.length/2-2],A=t.pads[t.pads.length-2];w=!!(S+A),u.push({type:12,data:_},{type:12,data:v},{type:12,data:S},{type:12,data:A}),a.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[u,a,!0,y,w]}else{if(r)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let c=M.computeStrides(t.kernelShape);u.push({type:12,data:c},{type:12,data:t.pads},{type:12,data:t.strides}),a.push({name:"kernelStrides",type:"u32",length:c.length},{name:"pads",type:"u32",length:t.pads.length},{name:"strides",type:"u32",length:t.strides.length});let p=t.pads.reduce((h,d)=>h+d);return[u,a,!!p,!1,!1]}},Xu=(e,t,r,o,i,u,a,c,p,h,d,y)=>{let w=i.format==="NHWC",_=t.type.value,v=j("output",t.type.tensor,o);if(i.kernelShape.length<=2){let S="",A="",I="",x=r-(w?2:1);if(d?S=`\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 ${u}\n }`:S=`\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 ${u}\n }`,i.kernelShape.length===2){let P=r-(w?3:2);y?A=`\n for (var j: u32 = 0u; j < uniforms.kh; j++) {\n xIndices[${P}] = indices[${P}] * uniforms.sh - uniforms.phStart + j;\n if (xIndices[${P}] < 0 || xIndices[${P}] >= uniforms.x_shape[${P}]) {\n pad += i32(uniforms.kw);\n continue;\n }\n `:A=`\n for (var j: u32 = 0u; j < uniforms.kh; j++) {\n xIndices[${P}] = indices[${P}] * uniforms.sh - uniforms.phStart + j;\n `,I=`\n }\n `}return`\n ${e.registerUniforms(p).declareVariables(t,v)}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n\n let indices = ${v.offsetToIndices("global_idx")};\n var xIndices = ${v.offsetToIndices("global_idx")};\n\n var value = ${_}(${c});\n var pad = 0;\n ${A}\n ${S}\n ${I}\n ${a}\n\n output[global_idx] = value;\n }`}else{if(w)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let S=i.kernelShape.length,A=i.pads.length,I="";return h?I=`\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 ${u}\n }`:I=`\n }\n let x_val = x[${t.indicesToOffset("xIndices")}];\n ${u}\n `,`\n ${e.registerUniforms(p).declareVariables(t,v)}\n\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n let indices = ${v.offsetToIndices("global_idx")};\n var xIndices = ${v.offsetToIndices("global_idx")};\n\n var offsets: array;\n\n var value = ${_}(${c});\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 < ${S-1}u; j++) {\n offsets[j] = offset / ${fe("uniforms.kernelStrides","j",S)};\n offset -= offsets[j] * ${fe("uniforms.kernelStrides","j",S)};\n }\n offsets[${S-1}] = offset;\n\n isPad = false;\n for (var j = ${r-S}u; j < ${r}u; j++) {\n xIndices[j] = indices[j] * ${fe("uniforms.strides",`j - ${r-S}u`,S)}\n + offsets[j - ${r-S}u] - ${fe("uniforms.pads","j - 2u",A)};\n ${I}\n }\n ${a}\n\n output[global_idx] = value;\n }`}},Qu=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,hp=e=>`${Qu(e)};${e.countIncludePad}`,gp=e=>`${Qu(e)};${e.storageOrder};${e.dilations}`,Ju=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}),ed=(e,t,r,o)=>{let[i,u]=Yu(t,o,r),a=U("x",t.dataType,t.dims.length),c=a.type.value,p="value += x_val;",h="";i.countIncludePad?h+=`value /= ${c}(uniforms.kernelSize);`:h+=`value /= ${c}(i32(uniforms.kernelSize) - pad);`;let[d,y,w,_,v]=Zu(u,i);d.push(...Z(t.dims,u));let S=["rank"];return{name:e,shaderCache:{hint:`${o.cacheKey};${w};${_};${v}`,inputDependencies:S},getRunData:()=>({outputs:[{dims:u,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(M.size(u)/64)},programUniforms:d}),getShaderSource:A=>Xu(A,a,t.dims.length,u.length,i,p,h,0,y,w,_,v)}},td=e=>{let t=e.count_include_pad!==0,r=Ju(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:hp(o)}},rd=(e,t)=>{Nn(e.inputs),e.compute(ed("AveragePool",e.inputs[0],!1,t))},nd={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},od=e=>{let t=e.format;return{format:t,...nd,cacheKey:t}},id=(e,t)=>{Nn(e.inputs),e.compute(ed("GlobalAveragePool",e.inputs[0],!0,t))},ad=(e,t,r,o)=>{let[i,u]=Yu(t,o,r),a=`\n value = max(x_val, value);\n `,c="",p=U("x",t.dataType,t.dims.length),h=["rank"],[d,y,w,_,v]=Zu(u,i);return d.push(...Z(t.dims,u)),{name:e,shaderCache:{hint:`${o.cacheKey};${w};${_};${v}`,inputDependencies:h},getRunData:()=>({outputs:[{dims:u,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(M.size(u)/64)},programUniforms:d}),getShaderSource:S=>Xu(S,p,t.dims.length,u.length,i,a,c,t.dataType===10?-65504:-1e5,y,w,_,v)}},sd=(e,t)=>{Nn(e.inputs),e.compute(ad("MaxPool",e.inputs[0],!1,t))},ud=e=>{let t=e.storage_order,r=e.dilations,o=Ju(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 i={storageOrder:t,dilations:r,...o,cacheKey:""};return{...i,cacheKey:gp(i)}},dd=e=>{let t=e.format;return{format:t,...nd,cacheKey:t}},ld=(e,t)=>{Nn(e.inputs),e.compute(ad("GlobalMaxPool",e.inputs[0],!0,t))}});var bp,wp,pd,md=Y(()=>{"use strict";$r();ye();_e();bp=(e,t,r)=>{let o=e===t,i=et&&r>0;if(o||i||u)throw new Error("Range these inputs\' contents are invalid.")},wp=(e,t,r,o)=>{let i=Math.abs(Math.ceil((t-e)/r)),u=[i],a=i,c=[{type:12,data:a},{type:o,data:e},{type:o,data:r},...Z(u)],p=h=>{let d=j("output",o,u.length),y=d.type.value,w=[{name:"outputSize",type:"u32"},{name:"start",type:y},{name:"delta",type:y}];return`\n ${h.registerUniforms(w).declareVariables(d)}\n ${h.mainStart()}\n ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n output[global_idx] = uniforms.start + ${y}(global_idx) * uniforms.delta;\n }`};return{name:"Range",shaderCache:{hint:`${o}`},getShaderSource:p,getRunData:()=>({outputs:[{dims:u,dataType:o}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:c})}},pd=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]),vr.webgpu.validateInputContent&&bp(t,r,o),e.compute(wp(t,r,o,e.inputs[0].dataType),{inputs:[]})}});var vp,$p,_p,Sp,xp,Cp,Ap,Ip,Tp,Ep,Pp,fd,kp,Op,Rp,Bp,Dp,hd,gd,yd=Y(()=>{"use strict";ye();Se();Ze();_e();vp=(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")}},$p=(e,t,r)=>{t.every(i=>i>=0&&i{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((i,u)=>o[i]=e[u]),o},_p=(e,t,r,o,i,u)=>{let[a,c,p]=r>10?[1,2,3]:[-1,e.length>1?1:-1,-1],h=e[0].dims.length;if(a>0&&e.length>a&&e[a].dims.length>0)e[a].getFloat32Array().forEach(d=>u.push(d));else if(t.coordinateTransformMode==="tf_crop_and_resize")throw new Error("Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize");if(c>0&&e.length>c&&e[c].dims.length>0){if(e[c].getFloat32Array().forEach(d=>o.push(d)),o.length!==0&&o.length!==h&&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");vp(o,t),t.axes.length>0&&$p(o,t.axes,h).forEach((d,y)=>o[y]=d)}if(p>0&&e.length>p&&(e[p].getBigInt64Array().forEach(d=>i.push(Number(d))),i.length!==h||r>=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(o.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 o<"u"&&typeof i<"u"&&o.length>0&&i.length>h)throw new Error("Resize requires only of scales or sizes to be specified")},Sp=(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`)}})()+"}",xp=(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`)}})()+"}",Cp=(e,t,r)=>{let o=new Array(r).fill(0).concat(new Array(r).fill(1)),i=e.length===0?o:e.slice();return t.length>0?(t.forEach((u,a)=>{o[u]=i[a],o[a+r]=i[t.length+a]}),o):i},Ap=(e,t,r,o)=>{let i=[];if(r.length>0)if(o.length>0){if(e.forEach(u=>i.push(u)),Math.max(...o)>e.length)throw new Error("axes is out of bound");o.forEach((u,a)=>i[u]=r[a])}else r.forEach(u=>i.push(u));else{if(t.length===0)throw new Error("Resize requires either scales or sizes.");i=e.map((u,a)=>Math.round(u*t[a]))}return i},Ip=(e,t,r)=>{let o=(()=>{switch(r.keepAspectRatioPolicy){case"not_larger":return r.axes.length>0?Math.min(...r.axes.map(u=>t[u]),Number.MAX_VALUE):Math.min(...t,Number.MAX_VALUE);case"not_smaller":return r.axes.length>0?Math.max(...r.axes.map(u=>t[u]),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 i=e.slice();return r.axes.length>0?(r.axes.forEach(u=>t[u]=o),r.axes.forEach(u=>i[u]=Math.round(e[u]*t[u]))):(t.fill(o,0,t.length),i.forEach((u,a)=>i[a]=Math.round(u*t[a]))),i},Tp=(e,t,r,o,i)=>`\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 = ${fe("uniforms.scales","i",o)};\n var roi_low = ${fe("uniforms.roi","i",i)};\n var roi_hi = ${fe("uniforms.roi",`i + ${t.length}`,i)};\n if (scale == 1.0) {\n original_indices[i] = ${e.type.value}(output_index);\n } else {\n var input_shape_i = ${fe("uniforms.input_shape","i",t.length)};\n var output_shape_i = ${fe("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 }`,Ep=(e,t,r,o,i,u,a)=>`\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 = ${fe("uniforms.scales","i",i)};\n if (scale == 1.0) {\n input_index = output_index;\n } else {\n var roi_low = ${fe("uniforms.roi","i",u)};\n var roi_hi = ${fe("uniforms.roi",`i + ${r.length}`,u)};\n var input_shape_i = ${fe("uniforms.input_shape","i",r.length)};\n var output_shape_i = ${fe("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 (!${a} || (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 }`,Pp=(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 >= ${fe("uniforms.input_shape","i",t.length)}) {\n return false;\n }\n }\n return true;\n }`,fd=(e,t,r,o)=>e.rank>o?`\n ${e.indicesSet("input_indices",t,"channel")};\n ${e.indicesSet("input_indices",r,"batch")};\n`:"",kp=(e,t,r,o,i)=>{let[a,c,p,h]=r.length===2?[-1,0,1,-1]:[0,2,3,1],d=e.type.value;return`\n fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${d} {\n var input_indices: ${e.type.indices};\n ${e.indicesSet("input_indices",c,`max(0, min(row, ${r[c]} - 1))`)};\n ${e.indicesSet("input_indices",p,`max(0, min(col, ${r[p]} - 1))`)};\n ${fd(e,h,a,2)}\n return ${e.getByIndices("input_indices")};\n }\n\n fn bilinearInterpolation(output_indices: ${t.type.indices}) -> ${d} {\n var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices);\n var row:${d} = originalIndices[${c}];\n var col:${d} = originalIndices[${p}];\n ${o?`if (row < 0 || row > (${r[c]} - 1) || col < 0 || col > (${r[p]} - 1)) {\n return ${i};\n }`:""};\n row = max(0, min(row, ${r[c]} - 1));\n col = max(0, min(col, ${r[p]} - 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[${h}])`:"0"};\n var batch: u32 = ${r.length>2?`u32(originalIndices[${a}])`:"0"};\n var x11: ${d} = getInputValue(batch, channel, row1, col1);\n var x12: ${d} = getInputValue(batch, channel, row1, col2);\n var x21: ${d} = getInputValue(batch, channel, row2, col1);\n var x22: ${d} = getInputValue(batch, channel, row2, col2);\n var dx1: ${d} = abs(row - ${d}(row1));\n var dx2: ${d} = abs(${d}(row2) - row);\n var dy1: ${d} = abs(col - ${d}(col1));\n var dy2: ${d} = abs(${d}(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 }`},Op=(e,t,r,o,i,u,a,c,p,h)=>{let d=r.length===2,y=!0,[w,_]=d?[0,1]:y?[2,3]:[1,2],v=e.type.value,S=A=>{let I=A===w?"row":"col";return`\n fn ${I}CubicInterpolation(input_indices: ${e.type.indices}, output_indices: ${t.type.indices}) -> ${v} {\n var output_index = ${t.indicesGet("output_indices",A)};\n var originalIdx: ${v} = getOriginalCoordinateFromResizedCoordinate(output_index, ${i[A]},\n ${o[A]}, ${r[A]}, ${u[A]}, ${u[A]} + ${r.length});\n var fractOriginalIdx: ${v} = originalIdx - floor(originalIdx);\n var coefs = getCubicInterpolationCoefs(fractOriginalIdx);\n\n if (${c} && (originalIdx < 0 || originalIdx > (${r[A]} - 1))) {\n return ${p};\n }\n var data: array<${v}, 4> = array<${v}, 4>(0.0, 0.0, 0.0, 0.0);\n for (var i: i32 = -1; i < 3; i++) {\n var ${I}: ${v} = originalIdx + ${v}(i);\n if (${I} < 0 || ${I} >= ${r[A]}) {\n ${(()=>h?`coefs[i + 1] = 0.0;\n continue;`:c?`return ${p};`:`${I} = max(0, min(${I}, ${r[A]} - 1));`)()};\n }\n var input_indices_copy: ${e.type.indices} = input_indices;\n ${e.indicesSet("input_indices_copy",A,`u32(${I})`)};\n data[i + 1] = ${A===w?e.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"};\n }\n return cubicInterpolation1D(data, coefs);\n }`};return`\n ${S(w)};\n ${S(_)};\n fn getCubicInterpolationCoefs(s: ${v}) -> array<${v}, 4> {\n var absS = abs(s);\n var coeffs: array<${v}, 4> = array<${v}, 4>(0.0, 0.0, 0.0, 0.0);\n var oneMinusAbsS: ${v} = 1.0 - absS;\n var twoMinusAbsS: ${v} = 2.0 - absS;\n var onePlusAbsS: ${v} = 1.0 + absS;\n coeffs[0] = ((${a} * onePlusAbsS - 5 * ${a}) * onePlusAbsS + 8 * ${a}) * onePlusAbsS - 4 * ${a};\n coeffs[1] = ((${a} + 2) * absS - (${a} + 3)) * absS * absS + 1;\n coeffs[2] = ((${a} + 2) * oneMinusAbsS - (${a} + 3)) * oneMinusAbsS * oneMinusAbsS + 1;\n coeffs[3] = ((${a} * twoMinusAbsS - 5 * ${a}) * twoMinusAbsS + 8 * ${a}) * twoMinusAbsS - 4 * ${a};\n return coeffs;\n }\n\n fn cubicInterpolation1D(x: array<${v}, 4>, coefs: array<${v}, 4>) -> ${v} {\n var coefsSum: ${v} = 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}) -> ${v} {\n var input_indices: ${e.type.indices} = output_indices;\n return colCubicInterpolation(input_indices, output_indices);\n }\n `},Rp=(e,t,r,o,i)=>{let[a,c,p,h,d]=r.length===3?[-1,0,1,2,-1]:[0,2,3,4,1],y=e.type.value;return`\n fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${y} {\n var input_indices: ${e.type.indices};\n ${e.indicesSet("input_indices",c,`max(0, min(depth, ${r[c]} - 1))`)};\n ${e.indicesSet("input_indices",p,`max(0, min(height, ${r[p]} - 1))`)};\n ${e.indicesSet("input_indices",h,`max(0, min(width, ${r[h]} - 1))`)};\n ${fd(e,d,a,3)}\n return ${e.getByIndices("input_indices")};\n }\n\n fn trilinearInterpolation(output_indices: ${t.type.indices}) -> ${y} {\n var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices);\n var depth:${y} = originalIndices[${c}];\n var height:${y} = originalIndices[${p}];\n var width:${y} = originalIndices[${h}];\n ${o?`if (depth < 0 || depth > (${r[c]} - 1) || height < 0 || height > (${r[p]} - 1) || width < 0 || (width > ${r[h]} - 1)) {\n return ${i};\n }`:""};\n\n depth = max(0, min(depth, ${r[c]} - 1));\n height = max(0, min(height, ${r[p]} - 1));\n width = max(0, min(width, ${r[h]} - 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[${d}])`:"0"};\n var batch: u32 = ${r.length>3?`u32(originalIndices[${a}])`:"0"};\n\n var x111: ${y} = getInputValue(batch, channel, depth1, height1, width1);\n var x112: ${y} = getInputValue(batch, channel, depth1, height1, width2);\n var x121: ${y} = getInputValue(batch, channel, depth1, height2, width1);\n var x122: ${y} = getInputValue(batch, channel, depth1, height2, width2);\n var x211: ${y} = getInputValue(batch, channel, depth2, height1, width1);\n var x212: ${y} = getInputValue(batch, channel, depth2, height1, width2);\n var x221: ${y} = getInputValue(batch, channel, depth2, height2, width1);\n var x222: ${y} = getInputValue(batch, channel, depth2, height2, width2);\n var dx1: ${y} = abs(depth - ${y}(depth1));\n var dx2: ${y} = abs(${y}(depth2) - depth);\n var dy1: ${y} = abs(height - ${y}(height1));\n var dy2: ${y} = abs(${y}(height2) - height);\n var dz1: ${y} = abs(width - ${y}(width1));\n var dz2: ${y} = abs(${y}(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 }`},Bp=(e,t,r,o,i,u)=>{let a=e.dims,c=Cp(u,t.axes,a.length),p=Ap(a,o,i,t.axes),h=o.slice();o.length===0&&(h=a.map((x,E)=>x===0?1:p[E]/x),t.keepAspectRatioPolicy!=="stretch"&&(p=Ip(a,h,t)));let d=j("output",e.dataType,p.length),y=U("input",e.dataType,a.length),w=M.size(p),_=a.length===p.length&&a.every((x,E)=>x===p[E]),v=t.coordinateTransformMode==="tf_crop_and_resize",S=t.extrapolationValue,A=y.type.value,I=x=>`\n ${_?"":`\n ${Sp(t.coordinateTransformMode,A)};\n ${(()=>{switch(t.mode){case"nearest":return`\n ${Pp(y,a)};\n ${xp(t.nearestMode,r,A)};\n ${Ep(y,d,a,p,h.length,c.length,v)};\n `;case"linear":return`\n ${Tp(d,a,p,h.length,c.length)};\n ${(()=>{if(a.length===2||a.length===4)return`${kp(y,d,a,v,S)}`;if(a.length===3||a.length===5)return`${Rp(y,d,a,v,S)}`;throw Error("Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.")})()};\n `;case"cubic":return`\n ${(()=>{if(a.length===2||a.length===4)return`${Op(y,d,a,p,h,c,t.cubicCoeffA,v,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",h.length).registerUniform("roi","f32",c.length).declareVariables(y,d)}\n ${x.mainStart()}\n ${x.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n ${_?"output[global_idx] = input[global_idx];":`\n let output_indices = ${d.offsetToIndices("global_idx")};\n var input_indices: ${y.type.indices};\n ${(()=>{switch(t.mode){case"nearest":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices);\n if (checkInputIndices(input_indices)) {\n output[global_idx] = ${y.getByIndices("input_indices")};\n } else {\n output[global_idx] = ${t.extrapolationValue};\n }`;case"linear":return`output[global_idx] = ${a.length===2||a.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}|${h.length>0?h:""}|${i.length>0?i:""}|${c.length>0?c:""}|${_}|${a}`,inputDependencies:["rank"]},getShaderSource:I,getRunData:()=>({outputs:[{dims:p,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(w/64)},programUniforms:[{type:12,data:w},{type:1,data:h},{type:1,data:c},...Z(a,p)]})}},Dp=e=>{let t=e.customDataBuffer;return new Uint32Array(t,t.byteOffset,1)[0]},hd=(e,t)=>{let r=[],o=[],i=[],u=Dp(e);if(t.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");_p(e.inputs,t,u,r,o,i),e.compute(Bp(e.inputs[0],t,u,r,o,i),{inputs:[0]})},gd=e=>{let t=e.antialias,r=e.axes,o=e.coordinateTransformMode,i=e.cubicCoeffA,u=e.excludeOutside!==0,a=e.extrapolationValue,c=e.keepAspectRatioPolicy,p=e.mode,h=e.nearestMode===""?"simple":e.nearestMode;return ve({antialias:t,axes:r,coordinateTransformMode:o,cubicCoeffA:i,excludeOutside:u,extrapolationValue:a,keepAspectRatioPolicy:c,mode:p,nearestMode:h})}});var zp,Mp,bd,wd=Y(()=>{"use strict";ye();Se();Ze();_e();zp=(e,t)=>{let[r,o,i,u]=e,{numHeads:a,rotaryEmbeddingDim:c}=t;if(r.dims.length!==3&&r.dims.length!==4)throw new Error(`Input \'x\' is expected to have 3 or 4 dimensions, got ${r.dims.length}`);if(!M.areEqual(o.dims,[])&&!M.areEqual(o.dims,[1])&&o.dims.length!==2)throw new Error(`Input \'position_ids\' is expected to have 0, 1, or 2 dimensions, got ${o.dims.length}`);if(i.dims.length!==2)throw new Error(`Input \'cos_cache\' is expected to have 2 dimensions, got ${i.dims.length}`);if(u.dims.length!==2)throw new Error(`Input \'sin_cache\' is expected to have 2 dimensions, got ${u.dims.length}`);if(!M.areEqual(i.dims,u.dims))throw new Error("Inputs \'cos_cache\' and \'sin_cache\' are expected to have the same shape");if(c>0&&a===0)throw new Error("num_heads must be provided if rotary_embedding_dim is specified");let p=r.dims[0],h=r.dims[r.dims.length-2],d=i.dims[0],y=M.sizeFromDimension(r.dims,1)/h,w=c===0?i.dims[1]*2:y/a;if(c>w)throw new Error("rotary_embedding_dim must be less than or equal to head_size");if(o.dims.length===2){if(p!==o.dims[0])throw new Error(`Input \'position_ids\' dimension 0 should be of size batch_size, got ${o.dims[0]}`);if(h!==o.dims[1])throw new Error(`Input \'position_ids\' dimension 1 should be of size sequence_length, got ${o.dims[1]}`)}if(w/2!==i.dims[1]&&c/2!==i.dims[1])throw new Error(`Input \'cos_cache\' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${i.dims[1]}`);if(h>d)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported")},Mp=(e,t)=>{let{interleaved:r,numHeads:o,rotaryEmbeddingDim:i,scale:u}=t,a=e[0].dims[0],c=M.sizeFromDimension(e[0].dims,1),p=e[0].dims[e[0].dims.length-2],h=c/p,d=e[2].dims[1],y=i===0?d*2:h/o,w=new Array(a,p,h/y,y-d),_=M.computeStrides(w),v=[{type:1,data:u},{type:12,data:w},{type:12,data:_},...e[0].dims.length===3?new Array({type:12,data:[c,h,y,1]}):[],...e[0].dims.length===4?new Array({type:12,data:[c,y,p*y,1]}):[],...Z(e[0].dims,e[1].dims,e[2].dims,e[3].dims,e[0].dims)],S=A=>{let I=U("input",e[0].dataType,e[0].dims.length),x=U("position_ids",e[1].dataType,e[1].dims.length),E=U("cos_cache",e[2].dataType,e[2].dims.length),P=U("sin_cache",e[3].dataType,e[3].dims.length),O=j("output",e[0].dataType,e[0].dims.length);return A.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:w.length},{name:"global_strides",type:"u32",length:_.length},{name:"input_output_strides",type:"u32",length:_.length}]),`\n ${A.declareVariables(I,x,E,P,O)}\n\n ${A.mainStart(or)}\n let half_rotary_emb_dim = uniforms.${E.name}_shape[1];\n let bsnh = global_idx / uniforms.global_strides % uniforms.global_shape;\n let size = uniforms.global_shape[0] * uniforms.global_strides[0];\n ${A.guardAgainstOutOfBoundsWorkgroupSizes("size")}\n\n if (bsnh[3] < half_rotary_emb_dim) {\n let position_ids_idx =\n ${x.broadcastedIndicesToOffset("bsnh.xy",j("",x.type.tensor,2))};\n let position_id =\n u32(${x.getByOffset("position_ids_idx")}) + select(0, bsnh[1], position_ids_idx == 0);\n let i = dot(bsnh, uniforms.input_output_strides) + select(0, bsnh[3], ${r});\n let j = i + select(half_rotary_emb_dim, 1, ${r});\n let re = ${I.getByOffset("i")} * ${E.get("position_id","bsnh[3]")} -\n ${I.getByOffset("j")} * ${P.get("position_id","bsnh[3]")};\n ${O.setByOffset("i","re")}\n let im = ${I.getByOffset("i")} * ${P.get("position_id","bsnh[3]")} +\n ${I.getByOffset("j")} * ${E.get("position_id","bsnh[3]")};\n ${O.setByOffset("j","im")}\n } else {\n let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim;\n ${O.setByOffset("k",I.getByOffset("k"))}\n }\n }`};return{name:"RotaryEmbedding",shaderCache:{hint:ve({interleaved:r}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:S,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(M.size(w)/or)},programUniforms:v})}},bd=(e,t)=>{zp(e.inputs,t),e.compute(Mp(e.inputs,t))}});var Up,Vp,vd,$d=Y(()=>{"use strict";ye();Se();_e();Up=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 i=t.dims[t.dims.length-1],u=t.dims[t.dims.length-2];if(r.dims[r.dims.length-1]!==i)throw new Error("Skip must have the same hidden size as input");if(r.dims[r.dims.length-2]!==u)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]!==i)throw new Error("Gamma must have the same hidden size as input");if(e.length>3){let a=e[3];if(a.dims.length!==1)throw new Error("Beta must be 1D");if(a.dims[a.dims.length-1]!==i)throw new Error("Beta must have the same hidden size as input")}if(e.length>4){let a=e[4];if(a.dims.length!==1)throw new Error("Bias must be 1D");if(a.dims[a.dims.length-1]!==i)throw new Error("Bias must have the same hidden size as input")}},Vp=(e,t,r,o)=>{let i=t.simplified,u=e[0].dims,a=M.size(u),c=u,p=a,h=u.slice(-1)[0],d=o?u.slice(0,-1).concat(1):[],y=!i&&e.length>3,w=e.length>4,_=o&&r>1,v=o&&r>2,S=r>3,A=Me(h),I=[{type:12,data:p},{type:12,data:A},{type:12,data:h},{type:1,data:t.epsilon}],x=P=>{let O=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],R=[U("x",e[0].dataType,e[0].dims,A),U("skip",e[1].dataType,e[1].dims,A),U("gamma",e[2].dataType,e[2].dims,A)];y&&R.push(U("beta",e[3].dataType,e[3].dims,A)),w&&R.push(U("bias",e[4].dataType,e[4].dims,A)),R.push(j("output",e[0].dataType,c,A)),_&&R.push(j("mean_output",1,d)),v&&R.push(j("inv_std_output",1,d)),S&&R.push(j("input_skip_bias_sum",e[0].dataType,c,A));let L=De(e[0].dataType);return`\n\n ${P.registerUniforms(O).declareVariables(...R)}\n\n ${P.mainStart()}\n ${P.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size / uniforms.hidden_size")}\n let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components;\n let offset = global_idx * hidden_size_vectorized;\n var sum = ${$t("f32",A)};\n var squareSum = ${$t("f32",A)};\n for (var i: u32 = 0; i < hidden_size_vectorized; i++) {\n let skip_value = skip[offset + i];\n let bias_value = ${w?"bias[i]":L+"(0.0)"};\n let input_value = x[offset + i];\n let value = input_value + skip_value + bias_value;\n ${S?"input_skip_bias_sum[offset + i] = value;":""}\n output[offset + i] = value;\n let f32_value = ${ir(L,A,"value")};\n sum += f32_value;\n squareSum += f32_value * f32_value;\n }\n let mean = ${_t("sum",A)} / f32(uniforms.hidden_size);\n let inv_std_dev = inverseSqrt(${_t("squareSum",A)} / f32(uniforms.hidden_size) ${i?"":"- mean * mean"} + uniforms.epsilon);\n ${_?"mean_output[global_idx] = mean;":""}\n ${v?"inv_std_output[global_idx] = inv_std_dev;":""}\n for (var i: u32 = 0; i < hidden_size_vectorized; i++) {\n output[offset + i] = (output[offset + i] ${i?"":`- ${L}(mean)`}) * ${L}(inv_std_dev) * gamma[i] ${y?"+ beta[i]":""};\n }\n }`},E=[{dims:c,dataType:e[0].dataType}];return r>1&&E.push({dims:d,dataType:1}),r>2&&E.push({dims:d,dataType:1}),r>3&&E.push({dims:u,dataType:e[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${A};${_};${v};${S}`,inputDependencies:e.map((P,O)=>"type")},getShaderSource:x,getRunData:()=>({outputs:E,dispatchGroup:{x:Math.ceil(p/h/64)},programUniforms:I})}},vd=(e,t)=>{Up(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(Vp(e.inputs,t,e.outputCount,!1),{outputs:o})}});var Wp,Gn,Np,_d,Gp,Hp,Sd,xd,Cd=Y(()=>{"use strict";ye();Se();Ze();_e();Wp=(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`)})},Gn=(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},Np=(e,t)=>{if(e.length>1){let r=Gn(e,1),o=Gn(e,2),i=Gn(e,3);return i.length===0&&(i=[...Array(e[0].dims.length).keys()]),ve({starts:r,ends:o,axes:i})}else return t},_d=(e,t,r,o,i)=>{let u=e;return e<0&&(u+=r[o[t]]),i[t]<0?Math.max(0,Math.min(u,r[o[t]]-1)):Math.max(0,Math.min(u,r[o[t]]))},Gp=(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 = ${fe("uniforms.input_shape","i",r.length)};\n let steps_i = ${fe("uniforms.steps","i",r.length)};\n let signs_i = ${fe("uniforms.signs","i",r.length)};\n let starts_i = ${fe("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 }`,Hp=(e,t)=>{let r=e[0].dims,o=M.size(r),i=t.axes.length>0?M.normalizeAxes(t.axes,r.length):[...Array(r.length).keys()],u=Gn(e,4);u.forEach(I=>I!==0||(()=>{throw new Error("step cannot be 0")})),u.length===0&&(u=Array(i.length).fill(1));let a=t.starts.map((I,x)=>_d(I,x,r,i,u)),c=t.ends.map((I,x)=>_d(I,x,r,i,u));if(i.length!==a.length||i.length!==c.length)throw new Error("start, ends and axes should have the same number of elements");if(i.length!==r.length)for(let I=0;IMath.sign(I));u.forEach((I,x,E)=>{if(I<0){let P=(c[x]-a[x])/I,O=a[x],R=O+P*u[x];a[x]=R,c[x]=O,E[x]=-I}});let h=r.slice(0);i.forEach((I,x)=>{h[I]=Math.ceil((c[I]-a[I])/u[I])});let d={dims:h,dataType:e[0].dataType},y=j("output",e[0].dataType,h.length),w=U("input",e[0].dataType,e[0].dims.length),_=M.size(h),v=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:a.length},{name:"signs",type:"i32",length:p.length},{name:"steps",type:"u32",length:u.length}],S=[{type:12,data:_},{type:12,data:a},{type:6,data:p},{type:12,data:u},...Z(e[0].dims,h)],A=I=>`\n ${I.registerUniforms(v).declareVariables(w,y)}\n ${Gp(w,y,r)}\n ${I.mainStart()}\n ${I.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}\n let output_indices = ${y.offsetToIndices("global_idx")};\n let input_indices = calculateInputIndices(output_indices);\n ${y.setByOffset("global_idx",w.getByIndices("input_indices"))}\n }`;return{name:"Slice",shaderCache:{hint:`${p.length}_${a.length}_${u.length}`,inputDependencies:["rank"]},getShaderSource:A,getRunData:()=>({outputs:[d],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:S})}},Sd=(e,t)=>{Wp(e.inputs,t);let r=Np(e.inputs,t);e.compute(Hp(e.inputs,r),{inputs:[0]})},xd=e=>{let t=e.starts,r=e.ends,o=e.axes;return ve({starts:t,ends:r,axes:o})}});var Lp,Fp,Ad,Id,Td=Y(()=>{"use strict";ye();Se();Ze();_e();Lp=e=>{if(!e||e.length!==1)throw new Error("Softmax op requires 1 input.")},Fp=(e,t)=>{let r=e.dims,o=M.size(r),i=64,u=t.axis;if(u<0&&(u=r.length+u),uI===4?`max(max(${A}.x, ${A}.y), max(${A}.z, ${A}.w))`:I===2?`max(${A}.x, ${A}.y)`:I===3?`max(max(${A}.x, ${A}.y), ${A}.z)`:A,y=U("x",e.dataType,e.dims,p),w=j("result",e.dataType,e.dims,p),_=y.type.value,v=De(e.dataType)==="f32"?`var threadMax = ${_}(-3.402823e+38f);`:`var threadMax = ${_}(-65504.0h);`,S=A=>`\n var rowMaxShared : ${_};\n var rowSumShared : ${_};\n var threadShared : array<${_}, ${i}>;\n\n fn getValue(row: i32, col: i32, row_stride: i32) -> ${_} {\n let index = row * row_stride + col;\n return x[index];\n }\n\n fn setValue(row: i32, col: i32, row_stride: i32, value: ${_}) {\n let index = row * row_stride + col;\n result[index] = value;\n }\n ${A.registerUniform("packedCols","i32").declareVariables(y,w)}\n ${A.mainStart()}\n let gindex = i32(global_idx);\n let lindex = i32(local_idx);\n const wg = ${i};\n let row = gindex / wg;\n let cols = uniforms.packedCols;\n let row_stride : i32 = uniforms.packedCols;\n\n // find the rows max\n ${v}\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 = ${_}(${d("threadShared[0]",p)});\n }\n workgroupBarrier();\n\n // find the rows sum\n var threadSum = ${_}(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 = ${_}(${_t("threadShared[0]",p)});\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:`${p}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:r,dataType:e.dataType}],dispatchGroup:{x:c},programUniforms:[{type:6,data:h}]}),getShaderSource:S}},Ad=(e,t)=>{Lp(e.inputs),e.compute(Fp(e.inputs[0],t))},Id=e=>ve({axis:e.axis})});var qp,jp,Kp,Yp,Zp,Ed,Pd,kd=Y(()=>{"use strict";ye();Se();Ze();_e();qp=e=>{if(!e||e.length<1)throw new Error("too few inputs")},jp=(e,t)=>{let r=[],o=t.numOutputs;return e[1].dims[0]>0&&(e[1].getBigInt64Array().forEach(i=>r.push(Number(i))),o=r.length),ve({numOutputs:o,axis:t.axis,splitSizes:r})},Kp=e=>`\nfn calculateOutputIndex(index: u32) -> u32 {\n for (var i: u32 = 0u; i < ${e}u; i += 1u ) {\n if (index < ${fe("uniforms.size_in_split_axis","i",e)}) {\n return i;\n }\n }\n return ${e}u;\n}`,Yp=e=>{let t=e.length,r=[];for(let o=0;o{let r=e[0].dims,o=M.size(r),i=e[0].dataType,u=M.normalizeAxis(t.axis,r.length),a=new Array(t.numOutputs),c=U("input",i,r.length),p=new Array(t.numOutputs),h=[],d=[],y=0,w=[{type:12,data:o}];for(let v=0;v`\n ${v.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",p.length).declareVariables(c,...a)}\n ${Kp(p.length)}\n ${Yp(a)}\n\n ${v.mainStart()}\n ${v.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")}\n\n var indices = ${c.offsetToIndices("global_idx")};\n var index = ${c.indicesGet("indices",u)};\n let output_number = calculateOutputIndex(index);\n if (output_number != 0) {\n index -= ${fe("uniforms.size_in_split_axis","output_number - 1u",p.length)};\n ${c.indicesSet("indices",u,"index")};\n }\n writeBufferData(output_number, indices, global_idx);\n }`;return{name:"Split",shaderCache:{hint:t.cacheKey,inputDependencies:["rank"]},getShaderSource:_,getRunData:()=>({outputs:h,dispatchGroup:{x:Math.ceil(o/64)},programUniforms:w})}},Ed=(e,t)=>{qp(e.inputs);let r=e.inputs.length===1?t:jp(e.inputs,t);e.compute(Zp(e.inputs,r),{inputs:[0]})},Pd=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 ve({axis:t,numOutputs:o,splitSizes:r})}});var Od,Xp,Qp,Jp,Rd,Bd=Y(()=>{"use strict";ye();Se();_e();Od=e=>Array.from(e.getBigInt64Array(),Number),Xp=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(Od(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")},Qp=(e,t)=>{let r=[];for(let o=0;o{let t=e[0].dims,r=Od(e[1]),o=Qp(t,r),i=M.size(o),u=e[0].dataType,a=U("input",u,t.length),c=j("output",u,o.length),p=h=>`\n const inputShape = ${a.indices(...t)};\n ${h.registerUniform("output_size","u32").declareVariables(a,c)}\n ${h.mainStart()}\n ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}\n let output_indices = ${c.offsetToIndices("global_idx")};\n var input_indices: ${a.type.indices};\n for (var i = 0; i < ${t.length}; i++) {\n let input_dim_i = ${a.indicesGet("uniforms.input_shape","i")};\n let input_dim_value = ${c.indicesGet("output_indices","i")} % input_dim_i;\n\n ${a.indicesSet("input_indices","i","input_dim_value")}\n }\n ${c.setByOffset("global_idx",a.getByIndices("input_indices"))}\n }`;return{name:"Tile",shaderCache:{hint:`${r}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:[{type:12,data:i},...Z(e[0].dims,o)]}),getShaderSource:p}},Rd=e=>{Xp(e.inputs),e.compute(Jp(e.inputs),{inputs:[0]})}});var em,tm,Dd,zd=Y(()=>{"use strict";ye();Se();_e();em=(e,t,r,o,i)=>{let u=j("output_data",i,r.length,4),a=U("a_data",t[1].dataType,t[1].dims.length,4),c=U("b_data",t[2].dataType,t[2].dims.length,4),p=U("c_data",t[0].dataType,t[0].dims.length,4),h,d=(y,w,_)=>`select(${w}, ${y}, ${_})`;if(!o)h=u.setByOffset("global_idx",d(a.getByOffset("global_idx"),c.getByOffset("global_idx"),p.getByOffset("global_idx")));else{let y=(w,_,v="")=>{let S=`a_data[index_a${_}][component_a${_}]`,A=`b_data[index_b${_}][component_b${_}]`,I=`bool(c_data[index_c${_}] & (0xffu << (component_c${_} * 8)))`;return`\n let output_indices${_} = ${u.offsetToIndices(`global_idx * 4u + ${_}u`)};\n let offset_a${_} = ${a.broadcastedIndicesToOffset(`output_indices${_}`,u)};\n let offset_b${_} = ${c.broadcastedIndicesToOffset(`output_indices${_}`,u)};\n let offset_c${_} = ${p.broadcastedIndicesToOffset(`output_indices${_}`,u)};\n let index_a${_} = offset_a${_} / 4u;\n let index_b${_} = offset_b${_} / 4u;\n let index_c${_} = offset_c${_} / 4u;\n let component_a${_} = offset_a${_} % 4u;\n let component_b${_} = offset_b${_} % 4u;\n let component_c${_} = offset_c${_} % 4u;\n ${w}[${_}] = ${v}(${d(S,A,I)});\n `};i===9?h=`\n var data = vec4(0);\n ${y("data",0,"u32")}\n ${y("data",1,"u32")}\n ${y("data",2,"u32")}\n ${y("data",3,"u32")}\n output_data[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:h=`\n ${y("output_data[global_idx]",0)}\n ${y("output_data[global_idx]",1)}\n ${y("output_data[global_idx]",2)}\n ${y("output_data[global_idx]",3)}\n `}return`\n ${e.registerUniform("vec_size","u32").declareVariables(p,a,c,u)}\n ${e.mainStart()}\n ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}\n ${h}\n }`},tm=e=>{let t=e[1].dims,r=e[2].dims,o=e[0].dims,i=e[1].dataType,u=!(M.areEqual(t,r)&&M.areEqual(r,o)),a=t,c=M.size(t);if(u){let h=It.calcShape(It.calcShape(t,r,!1),o,!1);if(!h)throw new Error("Can\'t perform where op on the given tensors");a=h,c=M.size(a)}let p=Math.ceil(c/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:h=>em(h,e,a,u,i),getRunData:()=>({outputs:[{dims:a,dataType:i}],dispatchGroup:{x:Math.ceil(c/64/4)},programUniforms:[{type:12,data:p},...Z(o,t,r,a)]})}},Dd=e=>{e.compute(tm(e.inputs))}});var Md,Ud=Y(()=>{"use strict";Ka();Ro();Ja();ts();Vs();Zs();Oo();Uo();lu();mu();gu();$u();xu();Au();Eu();Ou();Du();Mu();Vu();Wo();Gu();qu();Ku();cd();md();In();yd();wd();$d();Cd();Td();kd();Bd();Sr();Rn();zd();Md=new Map([["Abs",[rs]],["Acos",[ns]],["Acosh",[os]],["Add",[Ws]],["ArgMax",[ja,ko]],["ArgMin",[qa,ko]],["Asin",[is]],["Asinh",[as]],["Atan",[ss]],["Atanh",[us]],["Attention",[Xa]],["AveragePool",[rd,td]],["BatchNormalization",[Qa]],["BiasAdd",[es]],["BiasSplitGelu",[Us]],["Cast",[ls,ds]],["Ceil",[ps]],["Clip",[cs]],["Concat",[Ya,Za]],["Conv",[Ho,Go]],["ConvTranspose",[du,uu]],["Cos",[ms]],["Cosh",[fs]],["CumSum",[cu,pu]],["DepthToSpace",[fu,hu]],["Div",[Ns]],["Einsum",[wu,vu]],["Elu",[hs,kn]],["Equal",[Gs]],["Erf",[gs]],["Exp",[ys]],["Expand",[Su]],["FastGelu",[Cu]],["Floor",[bs]],["FusedConv",[Ho,Go]],["Gather",[Tu,Iu]],["GatherElements",[ku,Pu]],["Gelu",[ws]],["Gemm",[Bu,Ru]],["GlobalAveragePool",[id,od]],["GlobalMaxPool",[ld,dd]],["Greater",[qs]],["GreaterOrEqual",[Ks]],["HardSigmoid",[Is,As]],["InstanceNormalization",[zu]],["LayerNormalization",[Uu]],["LeakyRelu",[vs,kn]],["Less",[js]],["LessOrEqual",[Ys]],["Log",[zs]],["MatMul",[ru]],["MatMulNBits",[Wu,Nu]],["MaxPool",[sd,ud]],["Mul",[Hs]],["MultiHeadAttention",[Fu,Lu]],["Neg",[_s]],["Not",[$s]],["Pad",[ju]],["Pow",[Ls]],["Range",[pd]],["Reciprocal",[Ss]],["ReduceMin",[Wa]],["ReduceMean",[Da]],["ReduceMax",[Va]],["ReduceSum",[Ga]],["ReduceProd",[Na]],["ReduceL1",[za]],["ReduceL2",[Ma]],["ReduceLogSum",[La]],["ReduceLogSumExp",[Ua]],["ReduceSumSquare",[Ha]],["Relu",[xs]],["Resize",[hd,gd]],["RotaryEmbedding",[bd]],["Sigmoid",[Cs]],["Sin",[Ts]],["Sinh",[Es]],["Slice",[Sd,xd]],["SkipLayerNormalization",[vd]],["Split",[Ed,Pd]],["Sqrt",[Ps]],["Softmax",[Ad,Id]],["Sub",[Fs]],["Tan",[ks]],["Tanh",[Rs]],["ThresholdedRelu",[Ds,kn]],["Tile",[Rd]],["Transpose",[_a,Sa]],["Where",[Dd]]])});var Hn,Vd=Y(()=>{"use strict";$r();Lt();_e();Hn=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,i,u){rr(t.programInfo.name);let a=this.backend.device,c=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let p=[];for(let d of r)p.push({binding:p.length,resource:{buffer:d.buffer}});for(let d of o)p.push({binding:p.length,resource:{buffer:d.buffer}});u&&p.push({binding:p.length,resource:u});let h=a.createBindGroup({layout:t.computePipeline.getBindGroupLayout(0),entries:p,label:t.programInfo.name});if(this.backend.sessionStatus==="capturing"){let d={kernelId:this.backend.currentKernelId,computePipeline:t.computePipeline,bindGroup:h,dispatchGroup:i};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(d)}c.setPipeline(t.computePipeline),c.setBindGroup(0,h),c.dispatchWorkgroups(...i),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(),Ht(t.programInfo.name)}dispose(){}build(t,r){rr(t.name);let o=this.backend.device,i=[];o.features.has("shader-f16")&&i.push("enable f16;");let u=va(r,this.backend.device.limits),a=t.getShaderSource(u),c=`${i.join(`\n`)}\n${u.additionalImplementations}\n${a}`,p=o.createShaderModule({code:c,label:t.name});Ve("verbose",()=>`[WebGPU] ${t.name} shader code: ${c}`);let h=o.createComputePipeline({compute:{module:p,entryPoint:"main"},layout:"auto",label:t.name});return Ht(t.name),{programInfo:t,computePipeline:h,uniformVariablesInfo:u.variablesInfo}}normalizeDispatchGroupSize(t){let r=typeof t=="number"?t:t.x,o=typeof t=="number"?1:t.y||1,i=typeof t=="number"?1:t.z||1,u=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(r<=u&&o<=u&&i<=u)return[r,o,i];let a=r*o*i,c=Math.ceil(Math.sqrt(a));if(c>u){if(c=Math.ceil(Math.cbrt(a)),c>u)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[c,c,c]}else return[c,c,1]}}});var rm,nm,Yo,Ln,Wd=Y(()=>{"use strict";$r();ye();Lt();fa();wa();Ud();Vd();rm=(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+`:${rm(t,e.shaderCache?.inputDependencies??new Array(t.length).fill("dims"))}`,o},Yo=class{constructor(t){t&&(this.architecture=t.architecture,this.vendor=t.vendor)}isArchitecture(t){return this.architecture===t}isVendor(t){return this.vendor===t}},Ln=class{constructor(){this.currentSessionId=null;this.currentKernelId=null;this.commandEncoder=null;this.computePassEncoder=null;this.maxDispatchNumber=16;this.pendingDispatchNumber=0;this.pendingKernels=[];this.pendingQueries=new Map;this.sessionStatus="default";this.capturedCommandList=new Map;this.capturedPendingKernels=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=[],i={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(i),this.adapterInfo=new Yo(await r.requestAdapterInfo()),this.gpuDataManager=ba(this),this.programManager=new Hn(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,pa(t.logLevel,!!t.debug),this.device.onuncapturederror=u=>{u.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${u.error.message}`)},Object.defineProperty(this.env.webgpu,"device",{value:this.device,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(this.env.webgpu,"adapter",{value:r,writable:!1,enumerable:!0,configurable:!1}),this.setQueryType()}dispose(){typeof this.querySet<"u"&&this.querySet.destroy(),this.gpuDataManager.dispose()}getCommandEncoder(){return this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder()),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let t=this.getCommandEncoder(),r={};this.queryType==="at-passes"&&(r.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=t.beginComputePass(r)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;rr(),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 i=0;i"u"&&(this.queryTimeBase=_);let S=Number(_-this.queryTimeBase),A=Number(v-this.queryTimeBase);if(!Number.isSafeInteger(S)||!Number.isSafeInteger(A))throw new RangeError("incorrect timestamp range");if(this.env.webgpu.profiling?.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:y.map(I=>({dims:I.dims,dataType:Gt(I.dataType)})),outputsMetadata:w.map(I=>({dims:I.dims,dataType:Gt(I.dataType)})),kernelId:a,kernelType:p,kernelName:h,programName:d,startTime:S,endTime:A});else{let I="";y.forEach((E,P)=>{I+=`input[${P}]: [${E.dims}] | ${Gt(E.dataType)}, `});let x="";w.forEach((E,P)=>{x+=`output[${P}]: [${E.dims}] | ${Gt(E.dataType)}, `}),console.log(`[profiling] kernel "${a}|${p}|${h}|${d}" ${I}${x}execution time: ${A-S} ns`)}wo("GPU",`${d}::${_}::${v}`)}t.unmap(),this.pendingQueries.delete(t)}),Ht()}run(t,r,o,i,u,a){rr(t.name);let c=[];for(let E=0;EP):o;if(y.length!==p.length)throw new Error(`Output size ${y.length} must be equal to ${p.length}.`);let w=[],_=[];for(let E=0;E=a)throw new Error(`Invalid output index: ${y[E]}`);if(y[E]===-3)continue;let P=y[E]===-1,O=y[E]===-2,R=P||O?u(p[E].dataType,p[E].dims):i(y[E],p[E].dataType,p[E].dims);if(w.push(R),R.data===0)continue;let L=this.gpuDataManager.get(R.data);if(!L)throw new Error(`no GPU data for output: ${R.data}`);if(P&&this.temporaryData.push(L),O){let N=this.kernelPersistentData.get(this.currentKernelId);N||(N=[],this.kernelPersistentData.set(this.currentKernelId,N)),N.push(L)}_.push(L)}if(c.length!==r.length||_.length!==w.length){if(_.length===0)return Ht(t.name),w;throw new Error(`Program ${t.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let v;if(d){let E=0,P=[];d.forEach(N=>{let K=typeof N.data=="number"?[N.data]:N.data;if(K.length===0)return;let Q=N.type===10?2:4,he,W;N.type===10?(W=K.length>4?16:K.length>2?8:K.length*Q,he=K.length>4?16:Q*K.length):(W=K.length<=2?K.length*Q:16,he=16),E=Math.ceil(E/W)*W,P.push(E);let se=N.type===10?8:4;E+=K.length>4?Math.ceil(K.length/se)*he:K.length*Q});let O=16;E=Math.ceil(E/O)*O;let R=new ArrayBuffer(E);d.forEach((N,K)=>{let Q=P[K],he=typeof N.data=="number"?[N.data]:N.data;if(N.type===6)new Int32Array(R,Q,he.length).set(he);else if(N.type===12)new Uint32Array(R,Q,he.length).set(he);else if(N.type===10)new Uint16Array(R,Q,he.length).set(he);else if(N.type===1)new Float32Array(R,Q,he.length).set(he);else throw new Error(`Unsupported uniform type: ${Gt(N.type)}`)});let L=this.gpuDataManager.create(E,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(L.buffer,0,R,0,E),this.gpuDataManager.release(L.id),v={offset:0,size:E,buffer:L.buffer}}let S=this.programManager.normalizeDispatchGroupSize(h),A=S[1]===1&&S[2]===1,I=nm(t,r,A),x=this.programManager.getArtifact(I);if(x||(x=this.programManager.build(t,S),this.programManager.setArtifact(I,x),Ve("info",()=>`[artifact] key: ${I}, programName: ${t.name}`)),d&&x.uniformVariablesInfo){if(d.length!==x.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${x.uniformVariablesInfo.length}, got ${d.length} in program "${x.programInfo.name}".`);for(let E=0;E`[ProgramManager] run "${t.name}" (key=${I}) with ${S[0]}x${S[1]}x${S[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let E={kernelId:this.currentKernelId,programName:x.programInfo.name,inputTensorViews:r,outputTensorViews:w};this.pendingKernels.push(E),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(E)}return this.programManager.run(x,c,_,S,v),Ht(t.name),w}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,i){let u=Md.get(t);if(!u)throw new Error(`kernel not implemented: ${t}`);let a={kernelType:t,kernelName:i,kernelEntry:u[0],attributes:[u[1],o]};this.kernels.set(r,a)}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 i=this.kernels.get(t);if(!i)throw new Error(`kernel not created: ${t}`);let u=i.kernelType,a=i.kernelName,c=i.kernelEntry,p=i.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${u}] ${a}" is not allowed to be called recursively`);this.currentKernelId=t,p[0]&&(p[1]=p[0](p[1]),p[0]=void 0),Ve("info",()=>`[WebGPU] Start to run kernel "[${u}] ${a}"...`);let h=this.env.debug;this.temporaryData=[];try{return h&&this.device.pushErrorScope("validation"),c(r,p[1]),0}catch(d){return o.push(Promise.resolve(`[WebGPU] Kernel "[${u}] ${a}" failed. ${d}`)),1}finally{h&&o.push(this.device.popErrorScope().then(d=>d?`GPU validation error for kernel "[${u}] ${a}": ${d.message}`:null));for(let d of this.temporaryData)this.gpuDataManager.release(d.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(t,r,o,i){let u=this.sessionExternalDataMapping.get(t);u||(u=new Map,this.sessionExternalDataMapping.set(t,u));let a=u.get(r),c=this.gpuDataManager.registerExternalBuffer(o,i,a?.[1]);return u.set(r,[c,o]),c}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 i=await xo(this,t,r);return ma(i.buffer,o)}}writeTimestamp(t){this.queryType==="inside-passes"&&this.computePassEncoder.writeTimestamp(this.querySet,t)}setQueryType(){this.queryType="none",(this.env.webgpu.profiling?.mode==="default"||(typeof this.env.trace>"u"?this.env.wasm.trace:this.env.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"),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})))}captureBegin(){Ve("info","captureBegin"),this.capturedCommandList.get(this.currentSessionId)||this.capturedCommandList.set(this.currentSessionId,[]),this.capturedPendingKernels.get(this.currentSessionId)||this.capturedPendingKernels.set(this.currentSessionId,[]),this.flush(),this.sessionStatus="capturing"}captureEnd(){Ve("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){Ve("info","replay"),this.sessionStatus="replaying";let t=this.capturedCommandList.get(this.currentSessionId),r=this.capturedPendingKernels.get(this.currentSessionId),o=t.length;this.pendingKernels=[];for(let i=0;i=this.maxDispatchNumber||this.queryType==="at-passes")&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus="default"}onReleaseSession(t){this.unregisterBuffers(t),this.capturedCommandList.has(t)&&this.capturedCommandList.delete(t),this.capturedPendingKernels.has(t)&&this.capturedPendingKernels.delete(t),this.gpuDataManager.onReleaseSession(t)}onRunStart(t){this.currentSessionId=t,this.setQueryType()}}});var Nd={};gn(Nd,{init:()=>om});var qr,Zo,om,Gd=Y(()=>{"use strict";ye();Wd();Lt();Se();qr=class e{constructor(t,r,o,i){this.module=t;this.dataType=r;this.data=o;this.dims=i}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let t=M.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=M.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=M.size(this.dims);return t===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,t)}reshape(t){if(M.size(t)!==M.size(this.dims))throw new Error("Invalid new shape");return new e(this.module,this.dataType,this.data,t)}},Zo=class{constructor(t,r,o){this.module=t;this.backend=r;this.customDataOffset=0;this.customDataSize=0;this.adapterInfo=r.adapterInfo;let i=t.HEAPU32,u=o>>>2;this.opKernelContext=i[u++];let a=i[u++];this.outputCount=i[u++],this.customDataOffset=i[u++],this.customDataSize=i[u++];let c=[];for(let p=0;ptypeof c=="number"?this.inputs[c]:c)??this.inputs,i=r?.outputs??[],u=(c,p,h)=>new qr(this.module,p,this.output(c,h),h),a=(c,p)=>{let h=tr(c);if(!h)throw new Error(`Unsupported data type: ${c}`);let d=h*M.size(p),y=d>0?this.backend.gpuDataManager.create(d).id:0;return new qr(this.module,c,y,p)};return this.backend.run(t,o,i,u,a,this.outputCount)}output(t,r){let o=this.module.stackSave();try{let i=this.module.stackAlloc((1+r.length)*4),u=i>>2;this.module.HEAPU32[u++]=r.length;for(let a=0;a{let i=t.jsepInit;if(!i)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(e==="webgpu"){let u=new Ln;await u.initialize(r,o),i("webgpu",[u,a=>u.alloc(a),a=>u.free(a),(a,c,p,h=!1)=>{if(h)Ve("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${a}, dst=${c}, size=${p}`),u.memcpy(a,c);else{Ve("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${a}, gpuDataId=${c}, size=${p}`);let d=t.HEAPU8.subarray(a>>>0,(a>>>0)+p);u.upload(c,d)}},async(a,c,p)=>{Ve("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${a}, dataOffset=${c}, size=${p}`),await u.download(a,()=>t.HEAPU8.subarray(c>>>0,(c>>>0)+p))},(a,c,p)=>u.createKernel(a,c,p,t.UTF8ToString(t._JsepGetNodeName(c))),a=>u.releaseKernel(a),(a,c,p,h)=>{Ve("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${p}, kernel=${a}, contextDataOffset=${c}`);let d=new Zo(t,u,c);return u.computeKernel(a,d,h)},()=>u.captureBegin(),()=>u.captureEnd(),()=>u.replay()])}else i("webnn")}});var Vi;Vi=Ei();var pl=zi(),fo,ho=!1,yn=!1,Ui=!1,ml=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}},fl=()=>{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}},hl=(e,t)=>e?t?"ort-wasm-simd-threaded.wasm":"ort-wasm-simd.wasm":t?"ort-wasm-threaded.wasm":"ort-wasm.wasm",Wi=async e=>{if(ho)return Promise.resolve();if(yn)throw new Error("multiple calls to \'initializeWebAssembly()\' detected.");if(Ui)throw new Error("previous call to \'initializeWebAssembly()\' failed.");yn=!0;let t=e.initTimeout,r=e.numThreads,o=e.simd,i=ml(r),u=o&&fl(),a=e.wasmPaths,c=typeof a=="string"?a:void 0,p=hl(u,i),h=typeof a=="object"?a[p]:void 0,d=!1,y=[];if(t>0&&y.push(new Promise(w=>{setTimeout(()=>{d=!0,w()},t)})),y.push(new Promise((w,_)=>{let v=i?pl:Vi,S={locateFile:(A,I)=>{if(i&&A.endsWith(".worker.js")&&typeof Blob<"u")return URL.createObjectURL(new Blob([Mi()],{type:"text/javascript"}));if(A.endsWith(".wasm")){if(h)return h;let x=c??I;return p==="ort-wasm-simd.wasm"?x+"ort-wasm-simd.jsep.wasm":p==="ort-wasm-simd-threaded.wasm"?x+"ort-wasm-simd-threaded.jsep.wasm":x+p}return I+A}};if(i)if(S.numThreads=r,typeof Blob>"u")S.mainScriptUrlOrBlob=(void 0)(__dirname,"ort-wasm-threaded.js");else{let A=`var ortWasmThreaded=${v.toString()};`;S.mainScriptUrlOrBlob=new Blob([A],{type:"text/javascript"})}v(S).then(A=>{yn=!1,ho=!0,fo=A,w()},A=>{yn=!1,Ui=!0,_(A)})})),await Promise.race(y),d)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},Le=()=>{if(ho&&fo)return fo;throw new Error("WebAssembly is not initialized yet.")};var Fe=(e,t)=>{let r=Le(),o=r.lengthBytesUTF8(e)+1,i=r._malloc(o);return r.stringToUTF8(e,i,o),t.push(i),i},Nr=(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(([i,u])=>{let a=t?t+i:i;if(typeof u=="object")Nr(u,a+".",r,o);else if(typeof u=="string"||typeof u=="number")o(a,u.toString());else if(typeof u=="boolean")o(a,u?"1":"0");else throw new Error(`Can\'t handle extra config type: ${typeof u}`)})},Ue=e=>{let t=Le(),r=t.stackSave();try{let o=t.stackAlloc(8);t._OrtGetLastError(o,o+4);let i=t.HEAP32[o/4],u=t.HEAPU32[o/4+1],a=u?t.UTF8ToString(u):"";throw new Error(`${e} ERROR_CODE: ${i}, ERROR_MESSAGE: ${a}`)}finally{t.stackRestore(r)}};var Ni=e=>{let t=Le(),r=0,o=[],i=e||{};try{if(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?.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?.terminate===void 0&&(i.terminate=!1);let u=0;return e?.tag!==void 0&&(u=Fe(e.tag,o)),r=t._OrtCreateRunOptions(i.logSeverityLevel,i.logVerbosityLevel,!!i.terminate,u),r===0&&Ue("Can\'t create run options."),e?.extra!==void 0&&Nr(e.extra,"",new WeakSet,(a,c)=>{let p=Fe(a,o),h=Fe(c,o);t._OrtAddRunConfigEntry(r,p,h)!==0&&Ue(`Can\'t set a run config entry: ${a} - ${c}.`)}),[r,o]}catch(u){throw r!==0&&t._OrtReleaseRunOptions(r),o.forEach(a=>t._free(a)),u}};var gl=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}`)}},yl=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},bl=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)},wl=(e,t,r)=>{for(let o of t){let i=typeof o=="string"?o:o.name;switch(i){case"webnn":if(i="WEBNN",typeof o!="string"){let a=o;if(a?.deviceType){let c=Fe("deviceType",r),p=Fe(a.deviceType,r);Le()._OrtAddSessionConfigEntry(e,c,p)!==0&&Ue(`Can\'t set a session config entry: \'deviceType\' - ${a.deviceType}.`)}if(a?.numThreads){let c=a.numThreads;(typeof c!="number"||!Number.isInteger(c)||c<0)&&(c=0);let p=Fe("numThreads",r),h=Fe(c.toString(),r);Le()._OrtAddSessionConfigEntry(e,p,h)!==0&&Ue(`Can\'t set a session config entry: \'numThreads\' - ${a.numThreads}.`)}if(a?.powerPreference){let c=Fe("powerPreference",r),p=Fe(a.powerPreference,r);Le()._OrtAddSessionConfigEntry(e,c,p)!==0&&Ue(`Can\'t set a session config entry: \'powerPreference\' - ${a.powerPreference}.`)}}break;case"webgpu":if(i="JS",typeof o!="string"){let a=o;if(a?.preferredLayout){if(a.preferredLayout!=="NCHW"&&a.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either \'NCHW\' or \'NHWC\': ${a.preferredLayout}`);let c=Fe("preferredLayout",r),p=Fe(a.preferredLayout,r);Le()._OrtAddSessionConfigEntry(e,c,p)!==0&&Ue(`Can\'t set a session config entry: \'preferredLayout\' - ${a.preferredLayout}.`)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${i}`)}let u=Fe(i,r);Le()._OrtAppendExecutionProvider(e,u)!==0&&Ue(`Can\'t append execution provider: ${i}.`)}},Gi=e=>{let t=Le(),r=0,o=[],i=e||{};bl(i);try{let u=gl(i.graphOptimizationLevel??"all"),a=yl(i.executionMode??"sequential"),c=typeof i.logId=="string"?Fe(i.logId,o):0,p=i.logSeverityLevel??2;if(!Number.isInteger(p)||p<0||p>4)throw new Error(`log serverity level is not valid: ${p}`);let h=i.logVerbosityLevel??0;if(!Number.isInteger(h)||h<0||h>4)throw new Error(`log verbosity level is not valid: ${h}`);let d=typeof i.optimizedModelFilePath=="string"?Fe(i.optimizedModelFilePath,o):0;if(r=t._OrtCreateSessionOptions(u,!!i.enableCpuMemArena,!!i.enableMemPattern,a,!!i.enableProfiling,0,c,p,h,d),r===0&&Ue("Can\'t create session options."),i.executionProviders&&wl(r,i.executionProviders,o),i.enableGraphCapture!==void 0){if(typeof i.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${i.enableGraphCapture}`);let y=Fe("enableGraphCapture",o),w=Fe(i.enableGraphCapture.toString(),o);t._OrtAddSessionConfigEntry(r,y,w)!==0&&Ue(`Can\'t set a session config entry: \'enableGraphCapture\' - ${i.enableGraphCapture}.`)}if(i.freeDimensionOverrides)for(let[y,w]of Object.entries(i.freeDimensionOverrides)){if(typeof y!="string")throw new Error(`free dimension override name must be a string: ${y}`);if(typeof w!="number"||!Number.isInteger(w)||w<0)throw new Error(`free dimension override value must be a non-negative integer: ${w}`);let _=Fe(y,o);t._OrtAddFreeDimensionOverride(r,_,w)!==0&&Ue(`Can\'t set a free dimension override: ${y} - ${w}.`)}return i.extra!==void 0&&Nr(i.extra,"",new WeakSet,(y,w)=>{let _=Fe(y,o),v=Fe(w,o);t._OrtAddSessionConfigEntry(r,_,v)!==0&&Ue(`Can\'t set a session config entry: ${y} - ${w}.`)}),[r,o]}catch(u){throw r!==0&&t._OrtReleaseSessionOptions(r),o.forEach(a=>t._free(a)),u}};ye();var Li=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 i of r)o.push(i);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 i=t.body.getReader(),u;try{u=new ArrayBuffer(o)}catch(c){if(c instanceof RangeError){let p=Math.ceil(o/65536);u=new WebAssembly.Memory({initial:p,maximum:p}).buffer}else throw c}let a=0;for(;;){let{done:c,value:p}=await i.read();if(c)break;let h=p.byteLength;new Uint8Array(u,a,h).set(p),a+=h}return new Uint8Array(u,0,o)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)};var im=(e,t)=>{Le()._OrtInit(e,t)!==0&&Ue("Can\'t initialize onnxruntime.")},Ld=async e=>{im(e.wasm.numThreads,Gr(e.logLevel))},Fd=async(e,t)=>{{let r=(Gd(),wr(Nd)).init;if(t==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");let o=e.webgpu.adapter;if(o){if(typeof o.limits!="object"||typeof o.features!="object"||typeof o.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let i=e.webgpu.powerPreference;if(i!==void 0&&i!=="low-power"&&i!=="high-performance")throw new Error(`Invalid powerPreference setting: "${i}"`);let u=e.webgpu.forceFallbackAdapter;if(u!==void 0&&typeof u!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${u}"`);if(o=await navigator.gpu.requestAdapter({powerPreference:i,forceFallbackAdapter:u}),!o)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");await r("webgpu",Le(),e,o)}if(t==="webnn"){if(typeof navigator>"u"||!navigator.ml)throw new Error("WebNN is not supported in current environment");await r("webnn",Le(),e)}}},ar=new Map,am=e=>{let t=Le(),r=t.stackSave();try{let o=t.stackAlloc(8);return t._OrtGetInputOutputCount(e,o,o+4)!==0&&Ue("Can\'t get session input/output count."),[t.HEAP32[o/4],t.HEAP32[o/4+1]]}finally{t.stackRestore(r)}},Xo=e=>{let t=Le(),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]},qd=async(e,t)=>{let r,o,i=Le();Array.isArray(e)?[r,o]=e:e.buffer===i.HEAPU8.buffer?[r,o]=[e.byteOffset,e.byteLength]:[r,o]=Xo(e);let u=0,a=0,c=0,p=[],h=[],d=[];try{if([a,p]=Gi(t),t?.externalData&&i.mountExternalData){let x=[];for(let E of t.externalData){let P=typeof E=="string"?E:E.path;x.push(Li(typeof E=="string"?E:E.data).then(O=>{i.mountExternalData(P,O)}))}await Promise.all(x)}u=await i._OrtCreateSession(r,o,a),u===0&&Ue("Can\'t create a session.");let[y,w]=am(u),_=!!t?.enableGraphCapture,v=[],S=[],A=[];for(let x=0;xx==="gpu-buffer")&&(c=i._OrtCreateBinding(u),c===0&&Ue("Can\'t create IO binding."),I={handle:c,outputPreferredLocations:A,outputPreferredLocationsEncoded:A.map(x=>yo(x))}),ar.set(u,[u,h,d,I,_,!1]),[u,v,S]}catch(y){throw h.forEach(w=>i._OrtFree(w)),d.forEach(w=>i._OrtFree(w)),c!==0&&i._OrtReleaseBinding(c),u!==0&&i._OrtReleaseSession(u),y}finally{i._free(r),a!==0&&i._OrtReleaseSessionOptions(a),p.forEach(y=>i._free(y)),i.unmountExternalData?.()}},jd=e=>{let t=Le(),r=ar.get(e);if(!r)throw new Error(`cannot release session. invalid session id: ${e}`);let[o,i,u,a,c]=r;a&&(c&&t._OrtClearBoundOutputs(a.handle),t._OrtReleaseBinding(a.handle)),t.jsepOnReleaseSession?.(e),i.forEach(p=>t._OrtFree(p)),u.forEach(p=>t._OrtFree(p)),t._OrtReleaseSession(o),ar.delete(e)},Hd=(e,t,r,o,i,u=!1)=>{if(!e){t.push(0);return}let a=Le(),c=e[0],p=e[1],h=e[3],d,y;if(c==="string"&&h==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");if(u&&h!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${i} when enableGraphCapture is true.`);if(h==="gpu-buffer"){let v=e[2].gpuBuffer,S=tr(go(c));y=p.reduce((I,x)=>I*x,1)*S;let A=a.jsepRegisterBuffer;if(!A)throw new Error(\'Tensor location "gpu-buffer" is not supported without using WebGPU.\');d=A(o,i,v,y)}else{let v=e[2];if(Array.isArray(v)){y=4*v.length,d=a._malloc(y),r.push(d);let S=d/4;for(let A=0;Aa.HEAP32[v++]=A);let S=a._OrtCreateTensor(go(c),d,y,_,p.length,yo(h));S===0&&Ue(`Can\'t create tensor for input/output. session=${o}, index=${i}.`),t.push(S)}finally{a.stackRestore(w)}},Kd=async(e,t,r,o,i,u)=>{let a=Le(),c=ar.get(e);if(!c)throw new Error(`cannot run inference. invalid session id: ${e}`);let p=c[0],h=c[1],d=c[2],y=c[3],w=c[4],_=c[5],v=t.length,S=o.length,A=0,I=[],x=[],E=[],P=[],O=a.stackSave(),R=a.stackAlloc(v*4),L=a.stackAlloc(v*4),N=a.stackAlloc(S*4),K=a.stackAlloc(S*4);try{[A,I]=Ni(u);for(let ee=0;eeNe*Ye,1);ue=Gt(ne);let Ut=y?.outputPreferredLocations[o[ee]];if(ue==="string"){if(Ut==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");let Ne=[],Ye=le/4;for(let mt=0;mt0){let Ne=a.jsepGetBuffer;if(!Ne)throw new Error(\'preferredLocation "gpu-buffer" is not supported without using WebGPU.\');let Ye=Ne(le),mt=tr(ne);if(mt===void 0||!Hi(ue))throw new Error(`Unsupported data type: ${ue}`);ie=!0,We.push([ue,Be,{gpuBuffer:Ye,download:a.jsepCreateDownloader(Ye,Ge*mt,ue),dispose:()=>{a._OrtReleaseTensor(ae)}},"gpu-buffer"])}else{let Ne=bn(ue),Ye=new Ne(Ge);new Uint8Array(Ye.buffer,Ye.byteOffset,Ye.byteLength).set(a.HEAPU8.subarray(le,le+Ye.byteLength)),We.push([ue,Be,Ye,"cpu"])}}finally{a.stackRestore(Ae),ue==="string"&&le&&a._free(le),ie||a._OrtReleaseTensor(ae)}}return y&&!w&&(a._OrtClearBoundOutputs(y.handle),ar.set(e,[p,h,d,y,w,!1])),We}finally{a.stackRestore(O),x.forEach(Q=>a._OrtReleaseTensor(Q)),E.forEach(Q=>a._OrtReleaseTensor(Q)),P.forEach(Q=>a._free(Q)),A!==0&&a._OrtReleaseRunOptions(A),I.forEach(Q=>a._free(Q))}},Yd=e=>{let t=Le(),r=ar.get(e);if(!r)throw new Error("invalid session id");let o=r[0],i=t._OrtEndProfiling(o);i===0&&Ue("Can\'t get an profile file name."),t._OrtFree(i)},Zd=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":Wi(r.wasm).then(()=>{Ld(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:i}=r;Fd(i,o).then(()=>{postMessage({type:t})},u=>{postMessage({type:t,err:u})});break}case"copy-from":{let{buffer:o}=r,i=Xo(o);postMessage({type:t,out:i});break}case"create":{let{model:o,options:i}=r;qd(o,i).then(u=>{postMessage({type:t,out:u})},u=>{postMessage({type:t,err:u})});break}case"release":jd(r),postMessage({type:t});break;case"run":{let{sessionId:o,inputIndices:i,inputs:u,outputIndices:a,options:c}=r;Kd(o,i,u,a,new Array(a.length).fill(null),c).then(p=>{p.some(h=>h[3]!=="cpu")?postMessage({type:t,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:t,out:p},Zd([...u,...p]))},p=>{postMessage({type:t,err:p})});break}case"end-profiling":Yd(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'}),pn,Wt,ki,Ma,Ba,Ql,_s,Wn,Un,s0,Da,P2,M2,B2,D2,N2,W2,U2,L2=Z(()=>{var e;Rr(),Ux(),So(),pn=()=>!!Ue.wasm.proxy&&typeof document<"u",ki=!1,Ma=!1,Ba=!1,_s=new Map,Wn=(t,r)=>{let n=_s.get(t);n?n.push(r):_s.set(t,[r])},Un=()=>{if(ki||!Ma||Ba||!Wt)throw new Error("worker not ready")},s0=t=>{switch(t.data.type){case"init-wasm":ki=!1,t.data.err?(Ba=!0,Ql[1](t.data.err)):(Ma=!0,Ql[0]());break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let r=_s.get(t.data.type);t.data.err?r.shift()[1](t.data.err):r.shift()[0](t.data.out);break}}},Da=typeof document<"u"?(e=document==null?void 0:document.currentScript)==null?void 0:e.src:void 0,P2=async()=>{if(!Ma){if(ki)throw new Error("multiple calls to 'initWasm()' detected.");if(Ba)throw new Error("previous call to 'initWasm()' failed.");if(ki=!0,pn())return Ue.wasm.wasmPaths===void 0&&Da&&Da.indexOf("blob:")!==0&&(Ue.wasm.wasmPaths=Da.substr(0,+Da.lastIndexOf("/")+1)),new Promise((t,r)=>{Wt==null||Wt.terminate();let n=URL.createObjectURL(new Blob([Lx()],{type:"text/javascript"}));Wt=new Worker(n,{name:"ort-wasm-proxy-worker"}),Wt.onerror=o=>r(o),Wt.onmessage=s0,URL.revokeObjectURL(n),Ql=[t,r];let i={type:"init-wasm",in:Ue};Wt.postMessage(i)});try{await qv(Ue.wasm),await C2(Ue),Ma=!0}catch(t){throw Ba=!0,t}finally{ki=!1}}},M2=async t=>{if(pn())return Un(),new Promise((r,n)=>{Wn("init-ep",[r,n]);let i={type:"init-ep",in:{epName:t,env:Ue}};Wt.postMessage(i)});await T2(Ue,t)},B2=async t=>pn()?(Un(),new Promise((r,n)=>{Wn("copy-from",[r,n]);let i={type:"copy-from",in:{buffer:t}};Wt.postMessage(i,[t.buffer])})):np(t),D2=async(t,r)=>{if(pn()){if(r!=null&&r.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return Un(),new Promise((n,i)=>{Wn("create",[n,i]);let o={type:"create",in:{model:t,options:{...r}}},a=[];t instanceof Uint8Array&&a.push(t.buffer),Wt.postMessage(o,a)})}else return I2(t,r)},N2=async t=>{if(pn())return Un(),new Promise((r,n)=>{Wn("release",[r,n]);let i={type:"release",in:t};Wt.postMessage(i)});A2(t)},W2=async(t,r,n,i,o,a)=>{if(pn()){if(n.some(u=>u[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(o.some(u=>u))throw new Error("pre-allocated output tensor is not supported for proxy.");return Un(),new Promise((u,l)=>{Wn("run",[u,l]);let p=n,f={type:"run",in:{sessionId:t,inputIndices:r,inputs:p,outputIndices:i,options:a}};Wt.postMessage(f,R2(p))})}else return z2(t,r,n,i,o,a)},U2=async t=>{if(pn())return Un(),new Promise((r,n)=>{Wn("end-profiling",[r,n]);let i={type:"end-profiling",in:t};Wt.postMessage(i)});O2(t)}}),Xl,u0,V2,Vx=Z(()=>{Rr(),L2(),ve(),Qv(),Xl=(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()}`)}},u0=e=>{switch(e[3]){case"cpu":return new zt(e[0],e[2],e[1]);case"gpu-buffer":{let t=e[0];if(!uc(t))throw new Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:r,download:n,dispose:i}=e[2];return zt.fromGpuBuffer(r,{dataType:t,dims:e[1],download:n,dispose:i})}default:throw new Error(`invalid data location: ${e[3]}`)}},V2=class{async fetchModelAndCopyToWasmMemory(e){return B2(await pu(e))}async loadModel(e,t){Lr();let r;typeof e=="string"?typeof process<"u"&&process.versions&&process.versions.node?r=await pu(e):r=await this.fetchModelAndCopyToWasmMemory(e):r=e,[this.sessionId,this.inputNames,this.outputNames]=await D2(r,t),zr()}async dispose(){return N2(this.sessionId)}async run(e,t,r){Lr();let n=[],i=[];Object.entries(e).forEach(m=>{let y=m[0],$=m[1],c=this.inputNames.indexOf(y);if(c===-1)throw new Error(`invalid input '${y}'`);n.push($),i.push(c)});let o=[],a=[];Object.entries(t).forEach(m=>{let y=m[0],$=m[1],c=this.outputNames.indexOf(y);if(c===-1)throw new Error(`invalid output '${y}'`);o.push($),a.push(c)});let u=n.map((m,y)=>Xl(m,()=>`input "${this.inputNames[i[y]]}"`)),l=o.map((m,y)=>m?Xl(m,()=>`output "${this.outputNames[a[y]]}"`):null),p=await W2(this.sessionId,i,u,a,l,r),f={};for(let m=0;m{Rr(),L2(),Vx(),l0=()=>{if((typeof Ue.wasm.initTimeout!="number"||Ue.wasm.initTimeout<0)&&(Ue.wasm.initTimeout=0),typeof Ue.wasm.simd!="boolean"&&(Ue.wasm.simd=!0),typeof Ue.wasm.proxy!="boolean"&&(Ue.wasm.proxy=!1),typeof Ue.wasm.trace!="boolean"&&(Ue.wasm.trace=!1),typeof Ue.wasm.numThreads!="number"||!Number.isInteger(Ue.wasm.numThreads)||Ue.wasm.numThreads<=0){(typeof self<"u"&&!self.crossOriginIsolated||typeof process<"u"&&process.versions&&process.versions.node)&&(Ue.wasm.numThreads=1);let e=typeof navigator>"u"?(void 0)().length:navigator.hardwareConcurrency;Ue.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},H2=class{async init(e){l0(),await P2(),await M2(e)}async createInferenceSessionHandler(e,t){let r=new V2;return await r.loadModel(e,t),Promise.resolve(r)}}}),F2={};aa(F2,{wasmBackend:()=>j2});var j2,Fx=Z(()=>{Hx(),j2=new H2});Rr();Rr();Rr();var jx="1.18.0";{let e=(Fx(),Qn(F2)).wasmBackend;Ni("webgpu",e,5),Ni("webnn",e,5),Ni("cpu",e,10),Ni("wasm",e,10)}Object.defineProperty(Ue.versions,"web",{value:jx,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. + * ============================================================================= + */async function Gx(e,t,r,n,i,o,a,u){let l=0,p=0;const f=await nc.create(e,{executionProviders:[r]});async function m(){const $=new zt("float32",new Float32Array(t.reduce((T,_)=>T*_)).map(()=>Math.random()),t),c=performance.now();return await f.run({images:$}),performance.now()-c}function y($,c){o.data.labels.push($),o.data.datasets[0].data.push(c),o.update()}for(let $=0;${const y=i.current.getContext("2d");a.current=new Chart(y,{type:"line",data:{labels:[],datasets:[{label:"Inference Time (ms)",data:[],borderColor:"lightblue",tension:.1}]},options:{plugins:{legend:{labels:{font:{size:16}}}},scales:{x:{ticks:{font:{size:14}}},y:{ticks:{font:{size:14}}}}}})};const m=async()=>{o.current.disabled=!0,a.current.data.labels=[],a.current.data.datasets[0].data=[],l("0"),f("0");const y=[1,3,640,640],$=`/${t.current.value}.onnx`;await Gx($,y,e.current.value,Number(r.current.value),Number(n.current.value),a.current,l,f),o.current.disabled=!1};return Re.jsxs(Re.Fragment,{children:[Re.jsx("h1",{children:"Model Benchmark - onnxruntime Web"}),Re.jsxs("div",{id:"setting-container",children:[Re.jsxs("div",{children:[Re.jsx("label",{htmlFor:"device-selector",children:"Device:"}),Re.jsxs("select",{name:"device-selector",ref:e,children:[Re.jsx("option",{value:"webgpu",children:"webGPU"}),Re.jsx("option",{value:"wasm",children:"Wasm(cpu)"})]})]}),Re.jsxs("div",{children:[Re.jsx("label",{htmlFor:"model-selector",children:"Model:"}),Re.jsxs("select",{name:"model-selector",ref:t,children:[Re.jsx("option",{value:"yolov9-t-converted-simplify",children:"yolov9-t"}),Re.jsx("option",{value:"yolov9-s-converted-simplify",children:"yolov9-s"}),Re.jsx("option",{value:"gelan-s2",children:"gelan-s2"}),Re.jsx("option",{value:"yolov10n",children:"yolov10-n"}),Re.jsx("option",{value:"yolov10s",children:"yolov10-s"})]}),Re.jsx("p",{children:"Yolov10 only support wasm"})]}),Re.jsxs("div",{children:[Re.jsx("label",{htmlFor:"warmUpFrequency-input",children:"Warm up frequency:"}),Re.jsx("input",{type:"number",id:"warmUpFrequency-input",defaultValue:1,ref:r})]}),Re.jsxs("div",{children:[Re.jsx("label",{htmlFor:"testFrequency-input",children:"Testing frequency:"}),Re.jsx("input",{type:"number",id:"testFrequency-input",defaultValue:100,ref:n})]})]}),Re.jsx("button",{onClick:m,ref:o,children:"Start benchmark"}),Re.jsxs("div",{id:"info-container",children:[Re.jsxs("p",{children:["Warm up Average Time: ",Re.jsxs("span",{className:"info-ms",children:[u,"ms"]})]}),Re.jsxs("p",{children:["Inference Average Time: ",Re.jsxs("span",{className:"info-ms",children:[p,"ms"]})]})]}),Re.jsx("canvas",{ref:i})]})}Zl.createRoot(document.getElementById("root")).render(Re.jsx(h$.StrictMode,{children:Re.jsx(qx,{})})); diff --git a/assets/index-JJFK-1W_.css b/assets/index-JJFK-1W_.css new file mode 100644 index 0000000..65f2e57 --- /dev/null +++ b/assets/index-JJFK-1W_.css @@ -0,0 +1 @@ +#info-container{display:flex;flex-direction:row;justify-content:space-around;align-items:center}#setting-container{display:flex;flex-direction:column;gap:5px;margin-bottom:30px}.info-ms{font-size:1.5em;font-weight:700;color:#add8e6}:root{line-height:1.5;font-weight:700;font-family:Open Sans,sans-serif;font-optical-sizing:auto;font-style:normal;color-scheme:light dark;color:#ffffffde;background-color:#242424;font-synthesis:none;text-rendering:optimizeLegibility;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}body{display:flex;justify-content:center;align-items:flex-start;text-align:center}h1{font-size:2.5em;line-height:1.1}button{border-radius:8px;border:1px solid transparent;padding:.6em 1.2em;font-size:1em;font-weight:500;font-family:inherit;background-color:#1a1a1a;cursor:pointer;transition:border-color .25s}button:hover{border-color:#646cff}button:focus,button:focus-visible{outline:4px auto -webkit-focus-ring-color}@media (prefers-color-scheme: light){:root{color:#213547;background-color:#fff}a:hover{color:#747bff}button{background-color:#f9f9f9}} diff --git a/gelan-s2-simplify.onnx b/gelan-s2-simplify.onnx new file mode 100644 index 0000000..869c5ea Binary files /dev/null and b/gelan-s2-simplify.onnx differ diff --git a/index.html b/index.html new file mode 100644 index 0000000..4a3a3cf --- /dev/null +++ b/index.html @@ -0,0 +1,18 @@ + + + + + + + + + + Model Benchmark + + + + +
+ + + diff --git a/ort-training-wasm-simd.wasm b/ort-training-wasm-simd.wasm new file mode 100644 index 0000000..d3eee7d Binary files /dev/null and b/ort-training-wasm-simd.wasm differ diff --git a/ort-wasm-simd-threaded.jsep.wasm b/ort-wasm-simd-threaded.jsep.wasm new file mode 100644 index 0000000..c8930c0 Binary files /dev/null and b/ort-wasm-simd-threaded.jsep.wasm differ diff --git a/ort-wasm-simd-threaded.wasm b/ort-wasm-simd-threaded.wasm new file mode 100644 index 0000000..dd89be8 Binary files /dev/null and b/ort-wasm-simd-threaded.wasm differ diff --git a/ort-wasm-simd.jsep.wasm b/ort-wasm-simd.jsep.wasm new file mode 100644 index 0000000..d9785c8 Binary files /dev/null and b/ort-wasm-simd.jsep.wasm differ diff --git a/ort-wasm-simd.wasm b/ort-wasm-simd.wasm new file mode 100644 index 0000000..9578c94 Binary files /dev/null and b/ort-wasm-simd.wasm differ diff --git a/ort-wasm-threaded.wasm b/ort-wasm-threaded.wasm new file mode 100644 index 0000000..b2b7bff Binary files /dev/null and b/ort-wasm-threaded.wasm differ diff --git a/ort-wasm.wasm b/ort-wasm.wasm new file mode 100644 index 0000000..e40dabf Binary files /dev/null and b/ort-wasm.wasm differ diff --git a/yolov10n.onnx b/yolov10n.onnx new file mode 100644 index 0000000..d883421 Binary files /dev/null and b/yolov10n.onnx differ diff --git a/yolov10s.onnx b/yolov10s.onnx new file mode 100644 index 0000000..767bca0 Binary files /dev/null and b/yolov10s.onnx differ diff --git a/yolov9-s-converted-simplify.onnx b/yolov9-s-converted-simplify.onnx new file mode 100644 index 0000000..14f1b0f Binary files /dev/null and b/yolov9-s-converted-simplify.onnx differ diff --git a/yolov9-t-converted-simplify.onnx b/yolov9-t-converted-simplify.onnx new file mode 100644 index 0000000..16d49e5 Binary files /dev/null and b/yolov9-t-converted-simplify.onnx differ