diff --git a/.gitattributes b/.gitattributes index a6344aac8c09253b3b630fb776ae94478aa0275b..20abeff563ff175543bf4e9b6f982f9b0b13dd3d 100644 --- a/.gitattributes +++ b/.gitattributes @@ -33,3 +33,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text *.zip filter=lfs diff=lfs merge=lfs -text *.zst filter=lfs diff=lfs merge=lfs -text *tfevents* filter=lfs diff=lfs merge=lfs -text +banner.png filter=lfs diff=lfs merge=lfs -text +logo.png filter=lfs diff=lfs merge=lfs -text diff --git a/assets/index-Cma9kVd_.css b/assets/index-DS3dcEWq.css similarity index 100% rename from assets/index-Cma9kVd_.css rename to assets/index-DS3dcEWq.css diff --git a/assets/index-Eg2tQ_Fl.js b/assets/index-Eg2tQ_Fl.js new file mode 100644 index 0000000000000000000000000000000000000000..f7433c85cdc9cfa6b5c8495bee54d3cbfeede371 --- /dev/null +++ b/assets/index-Eg2tQ_Fl.js @@ -0,0 +1,86 @@ +var up=Object.defineProperty;var Ic=v=>{throw TypeError(v)};var ap=(v,s,o)=>s in v?up(v,s,{enumerable:!0,configurable:!0,writable:!0,value:o}):v[s]=o;var xe=(v,s,o)=>ap(v,typeof s!="symbol"?s+"":s,o),cp=(v,s,o)=>s.has(v)||Ic("Cannot "+o);var Oc=(v,s,o)=>s.has(v)?Ic("Cannot add the same private member more than once"):s instanceof WeakSet?s.add(v):s.set(v,o);var Zi=(v,s,o)=>(cp(v,s,"access private method"),o);(function(){const s=document.createElement("link").relList;if(s&&s.supports&&s.supports("modulepreload"))return;for(const f of document.querySelectorAll('link[rel="modulepreload"]'))a(f);new MutationObserver(f=>{for(const h of f)if(h.type==="childList")for(const d of h.addedNodes)d.tagName==="LINK"&&d.rel==="modulepreload"&&a(d)}).observe(document,{childList:!0,subtree:!0});function o(f){const h={};return f.integrity&&(h.integrity=f.integrity),f.referrerPolicy&&(h.referrerPolicy=f.referrerPolicy),f.crossOrigin==="use-credentials"?h.credentials="include":f.crossOrigin==="anonymous"?h.credentials="omit":h.credentials="same-origin",h}function a(f){if(f.ep)return;f.ep=!0;const h=o(f);fetch(f.href,h)}})();function of(v){return v&&v.__esModule&&Object.prototype.hasOwnProperty.call(v,"default")?v.default:v}var Hs={exports:{}},Ll={},Ws={exports:{}},re={};/** + * @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 Mc;function fp(){if(Mc)return re;Mc=1;var v=Symbol.for("react.element"),s=Symbol.for("react.portal"),o=Symbol.for("react.fragment"),a=Symbol.for("react.strict_mode"),f=Symbol.for("react.profiler"),h=Symbol.for("react.provider"),d=Symbol.for("react.context"),S=Symbol.for("react.forward_ref"),E=Symbol.for("react.suspense"),j=Symbol.for("react.memo"),P=Symbol.for("react.lazy"),O=Symbol.iterator;function z(y){return y===null||typeof y!="object"?null:(y=O&&y[O]||y["@@iterator"],typeof y=="function"?y:null)}var G={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},ce=Object.assign,Z={};function J(y,_,V){this.props=y,this.context=_,this.refs=Z,this.updater=V||G}J.prototype.isReactComponent={},J.prototype.setState=function(y,_){if(typeof y!="object"&&typeof y!="function"&&y!=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,y,_,"setState")},J.prototype.forceUpdate=function(y){this.updater.enqueueForceUpdate(this,y,"forceUpdate")};function De(){}De.prototype=J.prototype;function je(y,_,V){this.props=y,this.context=_,this.refs=Z,this.updater=V||G}var Ne=je.prototype=new De;Ne.constructor=je,ce(Ne,J.prototype),Ne.isPureReactComponent=!0;var le=Array.isArray,ve=Object.prototype.hasOwnProperty,Ae={current:null},He={key:!0,ref:!0,__self:!0,__source:!0};function b(y,_,V){var ee,Q={},ne=null,fe=null;if(_!=null)for(ee in _.ref!==void 0&&(fe=_.ref),_.key!==void 0&&(ne=""+_.key),_)ve.call(_,ee)&&!He.hasOwnProperty(ee)&&(Q[ee]=_[ee]);var ue=arguments.length-2;if(ue===1)Q.children=V;else if(1>>1,_=I[y];if(0>>1;yf(Q,D))ne<_&&0>f(fe,Q)?(I[y]=fe,I[ne]=D,y=ne):(I[y]=Q,I[ee]=D,y=ee);else if(ne<_&&0>f(fe,D))I[y]=fe,I[ne]=D,y=ne;else break e}}return X}function f(I,X){var D=I.sortIndex-X.sortIndex;return D!==0?D:I.id-X.id}if(typeof performance=="object"&&typeof performance.now=="function"){var h=performance;v.unstable_now=function(){return h.now()}}else{var d=Date,S=d.now();v.unstable_now=function(){return d.now()-S}}var E=[],j=[],P=1,O=null,z=3,G=!1,ce=!1,Z=!1,J=typeof setTimeout=="function"?setTimeout:null,De=typeof clearTimeout=="function"?clearTimeout:null,je=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function Ne(I){for(var X=o(j);X!==null;){if(X.callback===null)a(j);else if(X.startTime<=I)a(j),X.sortIndex=X.expirationTime,s(E,X);else break;X=o(j)}}function le(I){if(Z=!1,Ne(I),!ce)if(o(E)!==null)ce=!0,Ue(ve);else{var X=o(j);X!==null&&Ee(le,X.startTime-I)}}function ve(I,X){ce=!1,Z&&(Z=!1,De(b),b=-1),G=!0;var D=z;try{for(Ne(X),O=o(E);O!==null&&(!(O.expirationTime>X)||I&&!oe());){var y=O.callback;if(typeof y=="function"){O.callback=null,z=O.priorityLevel;var _=y(O.expirationTime<=X);X=v.unstable_now(),typeof _=="function"?O.callback=_:O===o(E)&&a(E),Ne(X)}else a(E);O=o(E)}if(O!==null)var V=!0;else{var ee=o(j);ee!==null&&Ee(le,ee.startTime-X),V=!1}return V}finally{O=null,z=D,G=!1}}var Ae=!1,He=null,b=-1,Pe=5,Se=-1;function oe(){return!(v.unstable_now()-SeI||125y?(I.sortIndex=D,s(j,I),o(E)===null&&I===o(j)&&(Z?(De(b),b=-1):Z=!0,Ee(le,D-y))):(I.sortIndex=_,s(E,I),ce||G||(ce=!0,Ue(ve))),I},v.unstable_shouldYield=oe,v.unstable_wrapCallback=function(I){var X=z;return function(){var D=z;z=X;try{return I.apply(this,arguments)}finally{z=D}}}}(Gs)),Gs}var $c;function gp(){return $c||($c=1,Qs.exports=mp()),Qs.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 Bc;function yp(){if(Bc)return mt;Bc=1;var v=nu(),s=gp();function o(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),E=Object.prototype.hasOwnProperty,j=/^[: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]*$/,P={},O={};function z(e){return E.call(O,e)?!0:E.call(P,e)?!1:j.test(e)?O[e]=!0:(P[e]=!0,!1)}function G(e,t,n,r){if(n!==null&&n.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return r?!1:n!==null?!n.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function ce(e,t,n,r){if(t===null||typeof t>"u"||G(e,t,n,r))return!0;if(r)return!1;if(n!==null)switch(n.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function Z(e,t,n,r,l,i,u){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=l,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=i,this.removeEmptyString=u}var J={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){J[e]=new Z(e,0,!1,e,null,!1,!1)}),[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];J[t]=new Z(t,1,!1,e[1],null,!1,!1)}),["contentEditable","draggable","spellCheck","value"].forEach(function(e){J[e]=new Z(e,2,!1,e.toLowerCase(),null,!1,!1)}),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){J[e]=new Z(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){J[e]=new Z(e,3,!1,e.toLowerCase(),null,!1,!1)}),["checked","multiple","muted","selected"].forEach(function(e){J[e]=new Z(e,3,!0,e,null,!1,!1)}),["capture","download"].forEach(function(e){J[e]=new Z(e,4,!1,e,null,!1,!1)}),["cols","rows","size","span"].forEach(function(e){J[e]=new Z(e,6,!1,e,null,!1,!1)}),["rowSpan","start"].forEach(function(e){J[e]=new Z(e,5,!1,e.toLowerCase(),null,!1,!1)});var De=/[\-:]([a-z])/g;function je(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(De,je);J[t]=new Z(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(De,je);J[t]=new Z(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(De,je);J[t]=new Z(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)}),["tabIndex","crossOrigin"].forEach(function(e){J[e]=new Z(e,1,!1,e.toLowerCase(),null,!1,!1)}),J.xlinkHref=new Z("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1),["src","href","action","formAction"].forEach(function(e){J[e]=new Z(e,1,!1,e.toLowerCase(),null,!0,!0)});function Ne(e,t,n,r){var l=J.hasOwnProperty(t)?J[t]:null;(l!==null?l.type!==0:r||!(2c||l[u]!==i[c]){var p=` +`+l[u].replace(" at new "," at ");return e.displayName&&p.includes("")&&(p=p.replace("",e.displayName)),p}while(1<=u&&0<=c);break}}}finally{V=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?_(e):""}function Q(e){switch(e.tag){case 5:return _(e.type);case 16:return _("Lazy");case 13:return _("Suspense");case 19:return _("SuspenseList");case 0:case 2:case 15:return e=ee(e.type,!1),e;case 11:return e=ee(e.type.render,!1),e;case 1:return e=ee(e.type,!0),e;default:return""}}function ne(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 He:return"Fragment";case Ae:return"Portal";case Pe:return"Profiler";case b:return"StrictMode";case Fe:return"Suspense";case Ke:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case oe:return(e.displayName||"Context")+".Consumer";case Se:return(e._context.displayName||"Context")+".Provider";case Re:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case Xe:return t=e.displayName||null,t!==null?t:ne(e.type)||"Memo";case Ue:t=e._payload,e=e._init;try{return ne(e(t))}catch{}}return null}function fe(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 ne(t);case 8:return t===b?"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 ue(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function he(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function Je(e){var t=he(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=""+e[t];if(!e.hasOwnProperty(t)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var l=n.get,i=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return l.call(this)},set:function(u){r=""+u,i.call(this,u)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(u){r=""+u},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function Hn(e){e._valueTracker||(e._valueTracker=Je(e))}function qt(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=he(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function dn(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 Pt(e,t){var n=t.checked;return D({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function hr(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=ue(t.value!=null?t.value:n),e._wrapperState={initialChecked:r,initialValue:n,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function mr(e,t){t=t.checked,t!=null&&Ne(e,"checked",t,!1)}function Bt(e,t){mr(e,t);var n=ue(t.value),r=t.type;if(n!=null)r==="number"?(n===0&&e.value===""||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if(r==="submit"||r==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?pn(e,t.type,n):t.hasOwnProperty("defaultValue")&&pn(e,t.type,ue(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function Wn(e,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var r=t.type;if(!(r!=="submit"&&r!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}n=e.name,n!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,n!==""&&(e.name=n)}function pn(e,t,n){(t!=="number"||dn(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var hn=Array.isArray;function Jt(e,t,n,r){if(e=e.options,t){t={};for(var l=0;l"+t.valueOf().toString()+"",t=Vn.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function tn(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var gn={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},vr=["Webkit","ms","Moz","O"];Object.keys(gn).forEach(function(e){vr.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),gn[t]=gn[e]})});function Qn(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||gn.hasOwnProperty(e)&&gn[e]?(""+t).trim():t+"px"}function xt(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,l=Qn(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,l):e[n]=l}}var yn=D({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 Gn(e,t){if(t){if(yn[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(o(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(o(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(o(61))}if(t.style!=null&&typeof t.style!="object")throw Error(o(62))}}function Yn(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 Gr=null;function vn(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var kn=null,wn=null,St=null;function $l(e){if(e=hl(e)){if(typeof kn!="function")throw Error(o(280));var t=e.stateNode;t&&(t=fi(t),kn(e.stateNode,e.type,t))}}function Bl(e){wn?St?St.push(e):St=[e]:wn=e}function ze(){if(wn){var e=wn,t=St;if(St=wn=null,$l(e),t)for(e=0;e>>=0,e===0?32:31-(_f(e)/Tf|0)|0}var Yl=64,Kl=4194304;function Zr(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 Xl(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,l=e.suspendedLanes,i=e.pingedLanes,u=n&268435455;if(u!==0){var c=u&~l;c!==0?r=Zr(c):(i&=u,i!==0&&(r=Zr(i)))}else u=n&~l,u!==0?r=Zr(u):i!==0&&(r=Zr(i));if(r===0)return 0;if(t!==0&&t!==r&&(t&l)===0&&(l=r&-r,i=t&-t,l>=i||l===16&&(i&4194240)!==0))return t;if((r&4)!==0&&(r|=n&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=r;0n;n++)t.push(e);return t}function qr(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-It(t),e[t]=n}function Lf(e,t){var n=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0=il),Cu=" ",Nu=!1;function Ru(e,t){switch(e){case"keyup":return rd.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Lu(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var _r=!1;function id(e,t){switch(e){case"compositionend":return Lu(t);case"keypress":return t.which!==32?null:(Nu=!0,Cu);case"textInput":return e=t.data,e===Cu&&Nu?null:e;default:return null}}function od(e,t){if(_r)return e==="compositionend"||!So&&Ru(e,t)?(e=wu(),ei=go=Nn=null,_r=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=Du(n)}}function Fu(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?Fu(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function Uu(){for(var e=window,t=dn();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=dn(e.document)}return t}function To(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 md(e){var t=Uu(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&Fu(n.ownerDocument.documentElement,n)){if(r!==null&&To(n)){if(t=r.start,e=r.end,e===void 0&&(e=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(e,n.value.length);else if(e=(t=n.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var l=n.textContent.length,i=Math.min(r.start,l);r=r.end===void 0?i:Math.min(r.end,l),!e.extend&&i>r&&(l=r,r=i,i=l),l=ju(n,i);var u=ju(n,r);l&&u&&(e.rangeCount!==1||e.anchorNode!==l.node||e.anchorOffset!==l.offset||e.focusNode!==u.node||e.focusOffset!==u.offset)&&(t=t.createRange(),t.setStart(l.node,l.offset),e.removeAllRanges(),i>r?(e.addRange(t),e.extend(u.node,u.offset)):(t.setEnd(u.node,u.offset),e.addRange(t)))}}for(t=[],e=n;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n=document.documentMode,Tr=null,Co=null,al=null,No=!1;function $u(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;No||Tr==null||Tr!==dn(r)||(r=Tr,"selectionStart"in r&&To(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),al&&ul(al,r)||(al=r,r=ui(Co,"onSelect"),0Ar||(e.current=Uo[Ar],Uo[Ar]=null,Ar--)}function ye(e,t){Ar++,Uo[Ar]=e.current,e.current=t}var Pn={},et=An(Pn),ct=An(!1),bn=Pn;function Pr(e,t){var n=e.type.contextTypes;if(!n)return Pn;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var l={},i;for(i in n)l[i]=t[i];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=l),l}function ft(e){return e=e.childContextTypes,e!=null}function di(){we(ct),we(et)}function ta(e,t,n){if(et.current!==Pn)throw Error(o(168));ye(et,t),ye(ct,n)}function na(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var l in r)if(!(l in t))throw Error(o(108,fe(e)||"Unknown",l));return D({},n,r)}function pi(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||Pn,bn=et.current,ye(et,e),ye(ct,ct.current),!0}function ra(e,t,n){var r=e.stateNode;if(!r)throw Error(o(169));n?(e=na(e,t,bn),r.__reactInternalMemoizedMergedChildContext=e,we(ct),we(et),ye(et,e)):we(ct),ye(ct,n)}var ln=null,hi=!1,$o=!1;function la(e){ln===null?ln=[e]:ln.push(e)}function Nd(e){hi=!0,la(e)}function zn(){if(!$o&&ln!==null){$o=!0;var e=0,t=de;try{var n=ln;for(de=1;e>=u,l-=u,on=1<<32-It(t)+l|n<q?(Ge=K,K=null):Ge=K.sibling;var ae=T(k,K,w[q],A);if(ae===null){K===null&&(K=Ge);break}e&&K&&ae.alternate===null&&t(k,K),g=i(ae,g,q),Y===null?H=ae:Y.sibling=ae,Y=ae,K=Ge}if(q===w.length)return n(k,K),_e&&tr(k,q),H;if(K===null){for(;qq?(Ge=K,K=null):Ge=K.sibling;var Bn=T(k,K,ae.value,A);if(Bn===null){K===null&&(K=Ge);break}e&&K&&Bn.alternate===null&&t(k,K),g=i(Bn,g,q),Y===null?H=Bn:Y.sibling=Bn,Y=Bn,K=Ge}if(ae.done)return n(k,K),_e&&tr(k,q),H;if(K===null){for(;!ae.done;q++,ae=w.next())ae=N(k,ae.value,A),ae!==null&&(g=i(ae,g,q),Y===null?H=ae:Y.sibling=ae,Y=ae);return _e&&tr(k,q),H}for(K=r(k,K);!ae.done;q++,ae=w.next())ae=M(K,k,q,ae.value,A),ae!==null&&(e&&ae.alternate!==null&&K.delete(ae.key===null?q:ae.key),g=i(ae,g,q),Y===null?H=ae:Y.sibling=ae,Y=ae);return e&&K.forEach(function(sp){return t(k,sp)}),_e&&tr(k,q),H}function Ie(k,g,w,A){if(typeof w=="object"&&w!==null&&w.type===He&&w.key===null&&(w=w.props.children),typeof w=="object"&&w!==null){switch(w.$$typeof){case ve:e:{for(var H=w.key,Y=g;Y!==null;){if(Y.key===H){if(H=w.type,H===He){if(Y.tag===7){n(k,Y.sibling),g=l(Y,w.props.children),g.return=k,k=g;break e}}else if(Y.elementType===H||typeof H=="object"&&H!==null&&H.$$typeof===Ue&&ca(H)===Y.type){n(k,Y.sibling),g=l(Y,w.props),g.ref=ml(k,Y,w),g.return=k,k=g;break e}n(k,Y);break}else t(k,Y);Y=Y.sibling}w.type===He?(g=ar(w.props.children,k.mode,A,w.key),g.return=k,k=g):(A=Hi(w.type,w.key,w.props,null,k.mode,A),A.ref=ml(k,g,w),A.return=k,k=A)}return u(k);case Ae:e:{for(Y=w.key;g!==null;){if(g.key===Y)if(g.tag===4&&g.stateNode.containerInfo===w.containerInfo&&g.stateNode.implementation===w.implementation){n(k,g.sibling),g=l(g,w.children||[]),g.return=k,k=g;break e}else{n(k,g);break}else t(k,g);g=g.sibling}g=js(w,k.mode,A),g.return=k,k=g}return u(k);case Ue:return Y=w._init,Ie(k,g,Y(w._payload),A)}if(hn(w))return U(k,g,w,A);if(X(w))return B(k,g,w,A);vi(k,w)}return typeof w=="string"&&w!==""||typeof w=="number"?(w=""+w,g!==null&&g.tag===6?(n(k,g.sibling),g=l(g,w),g.return=k,k=g):(n(k,g),g=Ds(w,k.mode,A),g.return=k,k=g),u(k)):n(k,g)}return Ie}var Mr=fa(!0),da=fa(!1),ki=An(null),wi=null,Dr=null,Go=null;function Yo(){Go=Dr=wi=null}function Ko(e){var t=ki.current;we(ki),e._currentValue=t}function Xo(e,t,n){for(;e!==null;){var r=e.alternate;if((e.childLanes&t)!==t?(e.childLanes|=t,r!==null&&(r.childLanes|=t)):r!==null&&(r.childLanes&t)!==t&&(r.childLanes|=t),e===n)break;e=e.return}}function jr(e,t){wi=e,Go=Dr=null,e=e.dependencies,e!==null&&e.firstContext!==null&&((e.lanes&t)!==0&&(dt=!0),e.firstContext=null)}function Ct(e){var t=e._currentValue;if(Go!==e)if(e={context:e,memoizedValue:t,next:null},Dr===null){if(wi===null)throw Error(o(308));Dr=e,wi.dependencies={lanes:0,firstContext:e}}else Dr=Dr.next=e;return t}var nr=null;function Zo(e){nr===null?nr=[e]:nr.push(e)}function pa(e,t,n,r){var l=t.interleaved;return l===null?(n.next=n,Zo(t)):(n.next=l.next,l.next=n),t.interleaved=n,un(e,r)}function un(e,t){e.lanes|=t;var n=e.alternate;for(n!==null&&(n.lanes|=t),n=e,e=e.return;e!==null;)e.childLanes|=t,n=e.alternate,n!==null&&(n.childLanes|=t),n=e,e=e.return;return n.tag===3?n.stateNode:null}var In=!1;function qo(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function ha(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 an(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function On(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,(se&2)!==0){var l=r.pending;return l===null?t.next=t:(t.next=l.next,l.next=t),r.pending=t,un(e,n)}return l=r.interleaved,l===null?(t.next=t,Zo(r)):(t.next=l.next,l.next=t),r.interleaved=t,un(e,n)}function xi(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,(n&4194240)!==0)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,co(e,n)}}function ma(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var l=null,i=null;if(n=n.firstBaseUpdate,n!==null){do{var u={eventTime:n.eventTime,lane:n.lane,tag:n.tag,payload:n.payload,callback:n.callback,next:null};i===null?l=i=u:i=i.next=u,n=n.next}while(n!==null);i===null?l=i=t:i=i.next=t}else l=i=t;n={baseState:r.baseState,firstBaseUpdate:l,lastBaseUpdate:i,shared:r.shared,effects:r.effects},e.updateQueue=n;return}e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}function Si(e,t,n,r){var l=e.updateQueue;In=!1;var i=l.firstBaseUpdate,u=l.lastBaseUpdate,c=l.shared.pending;if(c!==null){l.shared.pending=null;var p=c,x=p.next;p.next=null,u===null?i=x:u.next=x,u=p;var C=e.alternate;C!==null&&(C=C.updateQueue,c=C.lastBaseUpdate,c!==u&&(c===null?C.firstBaseUpdate=x:c.next=x,C.lastBaseUpdate=p))}if(i!==null){var N=l.baseState;u=0,C=x=p=null,c=i;do{var T=c.lane,M=c.eventTime;if((r&T)===T){C!==null&&(C=C.next={eventTime:M,lane:0,tag:c.tag,payload:c.payload,callback:c.callback,next:null});e:{var U=e,B=c;switch(T=t,M=n,B.tag){case 1:if(U=B.payload,typeof U=="function"){N=U.call(M,N,T);break e}N=U;break e;case 3:U.flags=U.flags&-65537|128;case 0:if(U=B.payload,T=typeof U=="function"?U.call(M,N,T):U,T==null)break e;N=D({},N,T);break e;case 2:In=!0}}c.callback!==null&&c.lane!==0&&(e.flags|=64,T=l.effects,T===null?l.effects=[c]:T.push(c))}else M={eventTime:M,lane:T,tag:c.tag,payload:c.payload,callback:c.callback,next:null},C===null?(x=C=M,p=N):C=C.next=M,u|=T;if(c=c.next,c===null){if(c=l.shared.pending,c===null)break;T=c,c=T.next,T.next=null,l.lastBaseUpdate=T,l.shared.pending=null}}while(!0);if(C===null&&(p=N),l.baseState=p,l.firstBaseUpdate=x,l.lastBaseUpdate=C,t=l.shared.interleaved,t!==null){l=t;do u|=l.lane,l=l.next;while(l!==t)}else i===null&&(l.shared.lanes=0);ir|=u,e.lanes=u,e.memoizedState=N}}function ga(e,t,n){if(e=t.effects,t.effects=null,e!==null)for(t=0;tn?n:4,e(!0);var r=ns.transition;ns.transition={};try{e(!1),t()}finally{de=n,ns.transition=r}}function Ma(){return Nt().memoizedState}function Pd(e,t,n){var r=Fn(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},Da(e))ja(t,n);else if(n=pa(e,t,n,r),n!==null){var l=it();Ut(n,e,r,l),Fa(n,t,r)}}function zd(e,t,n){var r=Fn(e),l={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(Da(e))ja(t,l);else{var i=e.alternate;if(e.lanes===0&&(i===null||i.lanes===0)&&(i=t.lastRenderedReducer,i!==null))try{var u=t.lastRenderedState,c=i(u,n);if(l.hasEagerState=!0,l.eagerState=c,Ot(c,u)){var p=t.interleaved;p===null?(l.next=l,Zo(t)):(l.next=p.next,p.next=l),t.interleaved=l;return}}catch{}finally{}n=pa(e,t,l,r),n!==null&&(l=it(),Ut(n,e,r,l),Fa(n,t,r))}}function Da(e){var t=e.alternate;return e===Ce||t!==null&&t===Ce}function ja(e,t){kl=Ti=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function Fa(e,t,n){if((n&4194240)!==0){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,co(e,n)}}var Ri={readContext:Ct,useCallback:tt,useContext:tt,useEffect:tt,useImperativeHandle:tt,useInsertionEffect:tt,useLayoutEffect:tt,useMemo:tt,useReducer:tt,useRef:tt,useState:tt,useDebugValue:tt,useDeferredValue:tt,useTransition:tt,useMutableSource:tt,useSyncExternalStore:tt,useId:tt,unstable_isNewReconciler:!1},Id={readContext:Ct,useCallback:function(e,t){return Yt().memoizedState=[e,t===void 0?null:t],e},useContext:Ct,useEffect:Na,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,Ci(4194308,4,Aa.bind(null,t,e),n)},useLayoutEffect:function(e,t){return Ci(4194308,4,e,t)},useInsertionEffect:function(e,t){return Ci(4,2,e,t)},useMemo:function(e,t){var n=Yt();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=Yt();return t=n!==void 0?n(t):t,r.memoizedState=r.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},r.queue=e,e=e.dispatch=Pd.bind(null,Ce,e),[r.memoizedState,e]},useRef:function(e){var t=Yt();return e={current:e},t.memoizedState=e},useState:Ta,useDebugValue:as,useDeferredValue:function(e){return Yt().memoizedState=e},useTransition:function(){var e=Ta(!1),t=e[0];return e=Ad.bind(null,e[1]),Yt().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=Ce,l=Yt();if(_e){if(n===void 0)throw Error(o(407));n=n()}else{if(n=t(),Qe===null)throw Error(o(349));(lr&30)!==0||wa(r,t,n)}l.memoizedState=n;var i={value:n,getSnapshot:t};return l.queue=i,Na(Sa.bind(null,r,i,e),[e]),r.flags|=2048,Sl(9,xa.bind(null,r,i,n,t),void 0,null),n},useId:function(){var e=Yt(),t=Qe.identifierPrefix;if(_e){var n=sn,r=on;n=(r&~(1<<32-It(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=wl++,0<\/script>",e=e.removeChild(e.firstChild)):typeof r.is=="string"?e=u.createElement(n,{is:r.is}):(e=u.createElement(n),n==="select"&&(u=e,r.multiple?u.multiple=!0:r.size&&(u.size=r.size))):e=u.createElementNS(e,n),e[Qt]=t,e[pl]=r,lc(e,t,!1,!1),t.stateNode=e;e:{switch(u=Yn(n,r),n){case"dialog":ke("cancel",e),ke("close",e),l=r;break;case"iframe":case"object":case"embed":ke("load",e),l=r;break;case"video":case"audio":for(l=0;lHr&&(t.flags|=128,r=!0,El(i,!1),t.lanes=4194304)}else{if(!r)if(e=Ei(u),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),El(i,!0),i.tail===null&&i.tailMode==="hidden"&&!u.alternate&&!_e)return nt(t),null}else 2*te()-i.renderingStartTime>Hr&&n!==1073741824&&(t.flags|=128,r=!0,El(i,!1),t.lanes=4194304);i.isBackwards?(u.sibling=t.child,t.child=u):(n=i.last,n!==null?n.sibling=u:t.child=u,i.last=u)}return i.tail!==null?(t=i.tail,i.rendering=t,i.tail=t.sibling,i.renderingStartTime=te(),t.sibling=null,n=Te.current,ye(Te,r?n&1|2:n&1),t):(nt(t),null);case 22:case 23:return Is(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&(t.mode&1)!==0?(kt&1073741824)!==0&&(nt(t),t.subtreeFlags&6&&(t.flags|=8192)):nt(t),null;case 24:return null;case 25:return null}throw Error(o(156,t.tag))}function Bd(e,t){switch(Ho(t),t.tag){case 1:return ft(t.type)&&di(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return Fr(),we(ct),we(et),ts(),e=t.flags,(e&65536)!==0&&(e&128)===0?(t.flags=e&-65537|128,t):null;case 5:return bo(t),null;case 13:if(we(Te),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(o(340));Or()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return we(Te),null;case 4:return Fr(),null;case 10:return Ko(t.type._context),null;case 22:case 23:return Is(),null;case 24:return null;default:return null}}var zi=!1,rt=!1,Hd=typeof WeakSet=="function"?WeakSet:Set,F=null;function $r(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){Le(e,t,r)}else n.current=null}function xs(e,t,n){try{n()}catch(r){Le(e,t,r)}}var sc=!1;function Wd(e,t){if(Io=Jl,e=Uu(),To(e)){if("selectionStart"in e)var n={start:e.selectionStart,end:e.selectionEnd};else e:{n=(n=e.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var l=r.anchorOffset,i=r.focusNode;r=r.focusOffset;try{n.nodeType,i.nodeType}catch{n=null;break e}var u=0,c=-1,p=-1,x=0,C=0,N=e,T=null;t:for(;;){for(var M;N!==n||l!==0&&N.nodeType!==3||(c=u+l),N!==i||r!==0&&N.nodeType!==3||(p=u+r),N.nodeType===3&&(u+=N.nodeValue.length),(M=N.firstChild)!==null;)T=N,N=M;for(;;){if(N===e)break t;if(T===n&&++x===l&&(c=u),T===i&&++C===r&&(p=u),(M=N.nextSibling)!==null)break;N=T,T=N.parentNode}N=M}n=c===-1||p===-1?null:{start:c,end:p}}else n=null}n=n||{start:0,end:0}}else n=null;for(Oo={focusedElem:e,selectionRange:n},Jl=!1,F=t;F!==null;)if(t=F,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,F=e;else for(;F!==null;){t=F;try{var U=t.alternate;if((t.flags&1024)!==0)switch(t.tag){case 0:case 11:case 15:break;case 1:if(U!==null){var B=U.memoizedProps,Ie=U.memoizedState,k=t.stateNode,g=k.getSnapshotBeforeUpdate(t.elementType===t.type?B:Dt(t.type,B),Ie);k.__reactInternalSnapshotBeforeUpdate=g}break;case 3:var w=t.stateNode.containerInfo;w.nodeType===1?w.textContent="":w.nodeType===9&&w.documentElement&&w.removeChild(w.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(o(163))}}catch(A){Le(t,t.return,A)}if(e=t.sibling,e!==null){e.return=t.return,F=e;break}F=t.return}return U=sc,sc=!1,U}function _l(e,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var l=r=r.next;do{if((l.tag&e)===e){var i=l.destroy;l.destroy=void 0,i!==void 0&&xs(t,n,i)}l=l.next}while(l!==r)}}function Ii(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var n=t=t.next;do{if((n.tag&e)===e){var r=n.create;n.destroy=r()}n=n.next}while(n!==t)}}function Ss(e){var t=e.ref;if(t!==null){var n=e.stateNode;switch(e.tag){case 5:e=n;break;default:e=n}typeof t=="function"?t(e):t.current=e}}function uc(e){var t=e.alternate;t!==null&&(e.alternate=null,uc(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[Qt],delete t[pl],delete t[Fo],delete t[Td],delete t[Cd])),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 ac(e){return e.tag===5||e.tag===3||e.tag===4}function cc(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||ac(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 Es(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(e,t):n.insertBefore(e,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(e,n)):(t=n,t.appendChild(e)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=ci));else if(r!==4&&(e=e.child,e!==null))for(Es(e,t,n),e=e.sibling;e!==null;)Es(e,t,n),e=e.sibling}function _s(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(_s(e,t,n),e=e.sibling;e!==null;)_s(e,t,n),e=e.sibling}var Ze=null,jt=!1;function Mn(e,t,n){for(n=n.child;n!==null;)fc(e,t,n),n=n.sibling}function fc(e,t,n){if(Vt&&typeof Vt.onCommitFiberUnmount=="function")try{Vt.onCommitFiberUnmount(Gl,n)}catch{}switch(n.tag){case 5:rt||$r(n,t);case 6:var r=Ze,l=jt;Ze=null,Mn(e,t,n),Ze=r,jt=l,Ze!==null&&(jt?(e=Ze,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):Ze.removeChild(n.stateNode));break;case 18:Ze!==null&&(jt?(e=Ze,n=n.stateNode,e.nodeType===8?jo(e.parentNode,n):e.nodeType===1&&jo(e,n),nl(e)):jo(Ze,n.stateNode));break;case 4:r=Ze,l=jt,Ze=n.stateNode.containerInfo,jt=!0,Mn(e,t,n),Ze=r,jt=l;break;case 0:case 11:case 14:case 15:if(!rt&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){l=r=r.next;do{var i=l,u=i.destroy;i=i.tag,u!==void 0&&((i&2)!==0||(i&4)!==0)&&xs(n,t,u),l=l.next}while(l!==r)}Mn(e,t,n);break;case 1:if(!rt&&($r(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(c){Le(n,t,c)}Mn(e,t,n);break;case 21:Mn(e,t,n);break;case 22:n.mode&1?(rt=(r=rt)||n.memoizedState!==null,Mn(e,t,n),rt=r):Mn(e,t,n);break;default:Mn(e,t,n)}}function dc(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new Hd),t.forEach(function(r){var l=Jd.bind(null,e,r);n.has(r)||(n.add(r),r.then(l,l))})}}function Ft(e,t){var n=t.deletions;if(n!==null)for(var r=0;rl&&(l=u),r&=~i}if(r=l,r=te()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*Qd(r/1960))-r,10e?16:e,jn===null)var r=!1;else{if(e=jn,jn=null,Fi=0,(se&6)!==0)throw Error(o(331));var l=se;for(se|=4,F=e.current;F!==null;){var i=F,u=i.child;if((F.flags&16)!==0){var c=i.deletions;if(c!==null){for(var p=0;pte()-Ns?sr(e,0):Cs|=n),ht(e,t)}function Tc(e,t){t===0&&((e.mode&1)===0?t=1:(t=Kl,Kl<<=1,(Kl&130023424)===0&&(Kl=4194304)));var n=it();e=un(e,t),e!==null&&(qr(e,t,n),ht(e,n))}function qd(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),Tc(e,n)}function Jd(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,l=e.memoizedState;l!==null&&(n=l.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(o(314))}r!==null&&r.delete(t),Tc(e,n)}var Cc;Cc=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||ct.current)dt=!0;else{if((e.lanes&n)===0&&(t.flags&128)===0)return dt=!1,Ud(e,t,n);dt=(e.flags&131072)!==0}else dt=!1,_e&&(t.flags&1048576)!==0&&ia(t,gi,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;Pi(e,t),e=t.pendingProps;var l=Pr(t,et.current);jr(t,n),l=ls(null,t,r,e,l,n);var i=is();return t.flags|=1,typeof l=="object"&&l!==null&&typeof l.render=="function"&&l.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,ft(r)?(i=!0,pi(t)):i=!1,t.memoizedState=l.state!==null&&l.state!==void 0?l.state:null,qo(t),l.updater=Li,t.stateNode=l,l._reactInternals=t,fs(t,r,e,n),t=ms(null,t,r,!0,i,n)):(t.tag=0,_e&&i&&Bo(t),lt(null,t,l,n),t=t.child),t;case 16:r=t.elementType;e:{switch(Pi(e,t),e=t.pendingProps,l=r._init,r=l(r._payload),t.type=r,l=t.tag=ep(r),e=Dt(r,e),l){case 0:t=hs(null,t,r,e,n);break e;case 1:t=Ja(null,t,r,e,n);break e;case 11:t=Ya(null,t,r,e,n);break e;case 14:t=Ka(null,t,r,Dt(r.type,e),n);break e}throw Error(o(306,r,""))}return t;case 0:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Dt(r,l),hs(e,t,r,l,n);case 1:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Dt(r,l),Ja(e,t,r,l,n);case 3:e:{if(ba(t),e===null)throw Error(o(387));r=t.pendingProps,i=t.memoizedState,l=i.element,ha(e,t),Si(t,r,null,n);var u=t.memoizedState;if(r=u.element,i.isDehydrated)if(i={element:r,isDehydrated:!1,cache:u.cache,pendingSuspenseBoundaries:u.pendingSuspenseBoundaries,transitions:u.transitions},t.updateQueue.baseState=i,t.memoizedState=i,t.flags&256){l=Ur(Error(o(423)),t),t=ec(e,t,r,n,l);break e}else if(r!==l){l=Ur(Error(o(424)),t),t=ec(e,t,r,n,l);break e}else for(vt=Ln(t.stateNode.containerInfo.firstChild),yt=t,_e=!0,Mt=null,n=da(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(Or(),r===l){t=cn(e,t,n);break e}lt(e,t,r,n)}t=t.child}return t;case 5:return ya(t),e===null&&Vo(t),r=t.type,l=t.pendingProps,i=e!==null?e.memoizedProps:null,u=l.children,Mo(r,l)?u=null:i!==null&&Mo(r,i)&&(t.flags|=32),qa(e,t),lt(e,t,u,n),t.child;case 6:return e===null&&Vo(t),null;case 13:return tc(e,t,n);case 4:return Jo(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=Mr(t,null,r,n):lt(e,t,r,n),t.child;case 11:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Dt(r,l),Ya(e,t,r,l,n);case 7:return lt(e,t,t.pendingProps,n),t.child;case 8:return lt(e,t,t.pendingProps.children,n),t.child;case 12:return lt(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,l=t.pendingProps,i=t.memoizedProps,u=l.value,ye(ki,r._currentValue),r._currentValue=u,i!==null)if(Ot(i.value,u)){if(i.children===l.children&&!ct.current){t=cn(e,t,n);break e}}else for(i=t.child,i!==null&&(i.return=t);i!==null;){var c=i.dependencies;if(c!==null){u=i.child;for(var p=c.firstContext;p!==null;){if(p.context===r){if(i.tag===1){p=an(-1,n&-n),p.tag=2;var x=i.updateQueue;if(x!==null){x=x.shared;var C=x.pending;C===null?p.next=p:(p.next=C.next,C.next=p),x.pending=p}}i.lanes|=n,p=i.alternate,p!==null&&(p.lanes|=n),Xo(i.return,n,t),c.lanes|=n;break}p=p.next}}else if(i.tag===10)u=i.type===t.type?null:i.child;else if(i.tag===18){if(u=i.return,u===null)throw Error(o(341));u.lanes|=n,c=u.alternate,c!==null&&(c.lanes|=n),Xo(u,n,t),u=i.sibling}else u=i.child;if(u!==null)u.return=i;else for(u=i;u!==null;){if(u===t){u=null;break}if(i=u.sibling,i!==null){i.return=u.return,u=i;break}u=u.return}i=u}lt(e,t,l.children,n),t=t.child}return t;case 9:return l=t.type,r=t.pendingProps.children,jr(t,n),l=Ct(l),r=r(l),t.flags|=1,lt(e,t,r,n),t.child;case 14:return r=t.type,l=Dt(r,t.pendingProps),l=Dt(r.type,l),Ka(e,t,r,l,n);case 15:return Xa(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Dt(r,l),Pi(e,t),t.tag=1,ft(r)?(e=!0,pi(t)):e=!1,jr(t,n),$a(t,r,l),fs(t,r,l,n),ms(null,t,r,!0,e,n);case 19:return rc(e,t,n);case 22:return Za(e,t,n)}throw Error(o(156,t.tag))};function Nc(e,t){return R(e,t)}function bd(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Lt(e,t,n,r){return new bd(e,t,n,r)}function Ms(e){return e=e.prototype,!(!e||!e.isReactComponent)}function ep(e){if(typeof e=="function")return Ms(e)?1:0;if(e!=null){if(e=e.$$typeof,e===Re)return 11;if(e===Xe)return 14}return 2}function $n(e,t){var n=e.alternate;return n===null?(n=Lt(e.tag,t,e.key,e.mode),n.elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=e.flags&14680064,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function Hi(e,t,n,r,l,i){var u=2;if(r=e,typeof e=="function")Ms(e)&&(u=1);else if(typeof e=="string")u=5;else e:switch(e){case He:return ar(n.children,l,i,t);case b:u=8,l|=8;break;case Pe:return e=Lt(12,n,t,l|2),e.elementType=Pe,e.lanes=i,e;case Fe:return e=Lt(13,n,t,l),e.elementType=Fe,e.lanes=i,e;case Ke:return e=Lt(19,n,t,l),e.elementType=Ke,e.lanes=i,e;case Ee:return Wi(n,l,i,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case Se:u=10;break e;case oe:u=9;break e;case Re:u=11;break e;case Xe:u=14;break e;case Ue:u=16,r=null;break e}throw Error(o(130,e==null?e:typeof e,""))}return t=Lt(u,n,t,l),t.elementType=e,t.type=r,t.lanes=i,t}function ar(e,t,n,r){return e=Lt(7,e,r,t),e.lanes=n,e}function Wi(e,t,n,r){return e=Lt(22,e,r,t),e.elementType=Ee,e.lanes=n,e.stateNode={isHidden:!1},e}function Ds(e,t,n){return e=Lt(6,e,null,t),e.lanes=n,e}function js(e,t,n){return t=Lt(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function tp(e,t,n,r,l){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=ao(0),this.expirationTimes=ao(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=ao(0),this.identifierPrefix=r,this.onRecoverableError=l,this.mutableSourceEagerHydrationData=null}function Fs(e,t,n,r,l,i,u,c,p){return e=new tp(e,t,n,c,p),t===1?(t=1,i===!0&&(t|=8)):t=0,i=Lt(3,null,null,t),e.current=i,i.stateNode=e,i.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},qo(i),e}function np(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(v)}catch(s){console.error(s)}}return v(),Vs.exports=yp(),Vs.exports}var Wc;function kp(){if(Wc)return qi;Wc=1;var v=vp();return qi.createRoot=v.createRoot,qi.hydrateRoot=v.hydrateRoot,qi}var wp=kp();const xp=of(wp);function ru(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}let pr=ru();function sf(v){pr=v}const uf=/[&<>"']/,Sp=new RegExp(uf.source,"g"),af=/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,Ep=new RegExp(af.source,"g"),_p={"&":"&","<":"<",">":">",'"':""","'":"'"},Vc=v=>_p[v];function wt(v,s){if(s){if(uf.test(v))return v.replace(Sp,Vc)}else if(af.test(v))return v.replace(Ep,Vc);return v}const Tp=/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig;function Cp(v){return v.replace(Tp,(s,o)=>(o=o.toLowerCase(),o==="colon"?":":o.charAt(0)==="#"?o.charAt(1)==="x"?String.fromCharCode(parseInt(o.substring(2),16)):String.fromCharCode(+o.substring(1)):""))}const Np=/(^|[^\[])\^/g;function me(v,s){let o=typeof v=="string"?v:v.source;s=s||"";const a={replace:(f,h)=>{let d=typeof h=="string"?h:h.source;return d=d.replace(Np,"$1"),o=o.replace(f,d),a},getRegex:()=>new RegExp(o,s)};return a}function Qc(v){try{v=encodeURI(v).replace(/%25/g,"%")}catch{return null}return v}const Dl={exec:()=>null};function Gc(v,s){const o=v.replace(/\|/g,(h,d,S)=>{let E=!1,j=d;for(;--j>=0&&S[j]==="\\";)E=!E;return E?"|":" |"}),a=o.split(/ \|/);let f=0;if(a[0].trim()||a.shift(),a.length>0&&!a[a.length-1].trim()&&a.pop(),s)if(a.length>s)a.splice(s);else for(;a.length{const h=f.match(/^\s+/);if(h===null)return f;const[d]=h;return d.length>=a.length?f.slice(a.length):f}).join(` +`)}class ro{constructor(s){xe(this,"options");xe(this,"rules");xe(this,"lexer");this.options=s||pr}space(s){const o=this.rules.block.newline.exec(s);if(o&&o[0].length>0)return{type:"space",raw:o[0]}}code(s){const o=this.rules.block.code.exec(s);if(o){const a=o[0].replace(/^ {1,4}/gm,"");return{type:"code",raw:o[0],codeBlockStyle:"indented",text:this.options.pedantic?a:Ji(a,` +`)}}}fences(s){const o=this.rules.block.fences.exec(s);if(o){const a=o[0],f=Lp(a,o[3]||"");return{type:"code",raw:a,lang:o[2]?o[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):o[2],text:f}}}heading(s){const o=this.rules.block.heading.exec(s);if(o){let a=o[2].trim();if(/#$/.test(a)){const f=Ji(a,"#");(this.options.pedantic||!f||/ $/.test(f))&&(a=f.trim())}return{type:"heading",raw:o[0],depth:o[1].length,text:a,tokens:this.lexer.inline(a)}}}hr(s){const o=this.rules.block.hr.exec(s);if(o)return{type:"hr",raw:o[0]}}blockquote(s){const o=this.rules.block.blockquote.exec(s);if(o){let a=o[0].replace(/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,` + $1`);a=Ji(a.replace(/^ *>[ \t]?/gm,""),` +`);const f=this.lexer.state.top;this.lexer.state.top=!0;const h=this.lexer.blockTokens(a);return this.lexer.state.top=f,{type:"blockquote",raw:o[0],tokens:h,text:a}}}list(s){let o=this.rules.block.list.exec(s);if(o){let a=o[1].trim();const f=a.length>1,h={type:"list",raw:"",ordered:f,start:f?+a.slice(0,-1):"",loose:!1,items:[]};a=f?`\\d{1,9}\\${a.slice(-1)}`:`\\${a}`,this.options.pedantic&&(a=f?a:"[*+-]");const d=new RegExp(`^( {0,3}${a})((?:[ ][^\\n]*)?(?:\\n|$))`);let S="",E="",j=!1;for(;s;){let P=!1;if(!(o=d.exec(s))||this.rules.block.hr.test(s))break;S=o[0],s=s.substring(S.length);let O=o[2].split(` +`,1)[0].replace(/^\t+/,De=>" ".repeat(3*De.length)),z=s.split(` +`,1)[0],G=0;this.options.pedantic?(G=2,E=O.trimStart()):(G=o[2].search(/[^ ]/),G=G>4?1:G,E=O.slice(G),G+=o[1].length);let ce=!1;if(!O&&/^ *$/.test(z)&&(S+=z+` +`,s=s.substring(z.length+1),P=!0),!P){const De=new RegExp(`^ {0,${Math.min(3,G-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),je=new RegExp(`^ {0,${Math.min(3,G-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),Ne=new RegExp(`^ {0,${Math.min(3,G-1)}}(?:\`\`\`|~~~)`),le=new RegExp(`^ {0,${Math.min(3,G-1)}}#`);for(;s;){const ve=s.split(` +`,1)[0];if(z=ve,this.options.pedantic&&(z=z.replace(/^ {1,4}(?=( {4})*[^ ])/g," ")),Ne.test(z)||le.test(z)||De.test(z)||je.test(s))break;if(z.search(/[^ ]/)>=G||!z.trim())E+=` +`+z.slice(G);else{if(ce||O.search(/[^ ]/)>=4||Ne.test(O)||le.test(O)||je.test(O))break;E+=` +`+z}!ce&&!z.trim()&&(ce=!0),S+=ve+` +`,s=s.substring(ve.length+1),O=z.slice(G)}}h.loose||(j?h.loose=!0:/\n *\n *$/.test(S)&&(j=!0));let Z=null,J;this.options.gfm&&(Z=/^\[[ xX]\] /.exec(E),Z&&(J=Z[0]!=="[ ] ",E=E.replace(/^\[[ xX]\] +/,""))),h.items.push({type:"list_item",raw:S,task:!!Z,checked:J,loose:!1,text:E,tokens:[]}),h.raw+=S}h.items[h.items.length-1].raw=S.trimEnd(),h.items[h.items.length-1].text=E.trimEnd(),h.raw=h.raw.trimEnd();for(let P=0;PG.type==="space"),z=O.length>0&&O.some(G=>/\n.*\n/.test(G.raw));h.loose=z}if(h.loose)for(let P=0;P$/,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",h=o[3]?o[3].substring(1,o[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):o[3];return{type:"def",tag:a,raw:o[0],href:f,title:h}}}table(s){const o=this.rules.block.table.exec(s);if(!o||!/[:|]/.test(o[2]))return;const a=Gc(o[1]),f=o[2].replace(/^\||\| *$/g,"").split("|"),h=o[3]&&o[3].trim()?o[3].replace(/\n[ \t]*$/,"").split(` +`):[],d={type:"table",raw:o[0],header:[],align:[],rows:[]};if(a.length===f.length){for(const S of f)/^ *-+: *$/.test(S)?d.align.push("right"):/^ *:-+: *$/.test(S)?d.align.push("center"):/^ *:-+ *$/.test(S)?d.align.push("left"):d.align.push(null);for(const S of a)d.header.push({text:S,tokens:this.lexer.inline(S)});for(const S of h)d.rows.push(Gc(S,d.header.length).map(E=>({text:E,tokens:this.lexer.inline(E)})));return d}}lheading(s){const o=this.rules.block.lheading.exec(s);if(o)return{type:"heading",raw:o[0],depth:o[2].charAt(0)==="="?1:2,text:o[1],tokens:this.lexer.inline(o[1])}}paragraph(s){const o=this.rules.block.paragraph.exec(s);if(o){const a=o[1].charAt(o[1].length-1)===` +`?o[1].slice(0,-1):o[1];return{type:"paragraph",raw:o[0],text:a,tokens:this.lexer.inline(a)}}}text(s){const o=this.rules.block.text.exec(s);if(o)return{type:"text",raw:o[0],text:o[0],tokens:this.lexer.inline(o[0])}}escape(s){const o=this.rules.inline.escape.exec(s);if(o)return{type:"escape",raw:o[0],text:wt(o[1])}}tag(s){const o=this.rules.inline.tag.exec(s);if(o)return!this.lexer.state.inLink&&/^/i.test(o[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&/^<(pre|code|kbd|script)(\s|>)/i.test(o[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&/^<\/(pre|code|kbd|script)(\s|>)/i.test(o[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:o[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:o[0]}}link(s){const o=this.rules.inline.link.exec(s);if(o){const a=o[2].trim();if(!this.options.pedantic&&/^$/.test(a))return;const d=Ji(a.slice(0,-1),"\\");if((a.length-d.length)%2===0)return}else{const d=Rp(o[2],"()");if(d>-1){const E=(o[0].indexOf("!")===0?5:4)+o[1].length+d;o[2]=o[2].substring(0,d),o[0]=o[0].substring(0,E).trim(),o[3]=""}}let f=o[2],h="";if(this.options.pedantic){const d=/^([^'"]*[^\s])\s+(['"])(.*)\2/.exec(f);d&&(f=d[1],h=d[3])}else h=o[3]?o[3].slice(1,-1):"";return f=f.trim(),/^$/.test(a)?f=f.slice(1):f=f.slice(1,-1)),Yc(o,{href:f&&f.replace(this.rules.inline.anyPunctuation,"$1"),title:h&&h.replace(this.rules.inline.anyPunctuation,"$1")},o[0],this.lexer)}}reflink(s,o){let a;if((a=this.rules.inline.reflink.exec(s))||(a=this.rules.inline.nolink.exec(s))){const f=(a[2]||a[1]).replace(/\s+/g," "),h=o[f.toLowerCase()];if(!h){const d=a[0].charAt(0);return{type:"text",raw:d,text:d}}return Yc(a,h,a[0],this.lexer)}}emStrong(s,o,a=""){let f=this.rules.inline.emStrongLDelim.exec(s);if(!f||f[3]&&a.match(/[\p{L}\p{N}]/u))return;if(!(f[1]||f[2]||"")||!a||this.rules.inline.punctuation.exec(a)){const d=[...f[0]].length-1;let S,E,j=d,P=0;const O=f[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(O.lastIndex=0,o=o.slice(-1*s.length+d);(f=O.exec(o))!=null;){if(S=f[1]||f[2]||f[3]||f[4]||f[5]||f[6],!S)continue;if(E=[...S].length,f[3]||f[4]){j+=E;continue}else if((f[5]||f[6])&&d%3&&!((d+E)%3)){P+=E;continue}if(j-=E,j>0)continue;E=Math.min(E,E+j+P);const z=[...f[0]][0].length,G=s.slice(0,d+f.index+z+E);if(Math.min(d,E)%2){const Z=G.slice(1,-1);return{type:"em",raw:G,text:Z,tokens:this.lexer.inlineTokens(Z)}}const ce=G.slice(2,-2);return{type:"strong",raw:G,text:ce,tokens:this.lexer.inlineTokens(ce)}}}}codespan(s){const o=this.rules.inline.code.exec(s);if(o){let a=o[2].replace(/\n/g," ");const f=/[^ ]/.test(a),h=/^ /.test(a)&&/ $/.test(a);return f&&h&&(a=a.substring(1,a.length-1)),a=wt(a,!0),{type:"codespan",raw:o[0],text:a}}}br(s){const o=this.rules.inline.br.exec(s);if(o)return{type:"br",raw:o[0]}}del(s){const o=this.rules.inline.del.exec(s);if(o)return{type:"del",raw:o[0],text:o[2],tokens:this.lexer.inlineTokens(o[2])}}autolink(s){const o=this.rules.inline.autolink.exec(s);if(o){let a,f;return o[2]==="@"?(a=wt(o[1]),f="mailto:"+a):(a=wt(o[1]),f=a),{type:"link",raw:o[0],text:a,href:f,tokens:[{type:"text",raw:a,text:a}]}}}url(s){var a;let o;if(o=this.rules.inline.url.exec(s)){let f,h;if(o[2]==="@")f=wt(o[0]),h="mailto:"+f;else{let d;do d=o[0],o[0]=((a=this.rules.inline._backpedal.exec(o[0]))==null?void 0:a[0])??"";while(d!==o[0]);f=wt(o[0]),o[1]==="www."?h="http://"+o[0]:h=o[0]}return{type:"link",raw:o[0],text:f,href:h,tokens:[{type:"text",raw:f,text:f}]}}}inlineText(s){const o=this.rules.inline.text.exec(s);if(o){let a;return this.lexer.state.inRawBlock?a=o[0]:a=wt(o[0]),{type:"text",raw:o[0],text:a}}}}const Ap=/^(?: *(?:\n|$))+/,Pp=/^( {4}[^\n]+(?:\n(?: *(?:\n|$))*)?)+/,zp=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,Fl=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Ip=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,cf=/(?:[*+-]|\d{1,9}[.)])/,ff=me(/^(?!bull |blockCode|fences|blockquote|heading|html)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html))+?)\n {0,3}(=+|-+) *(?:\n+|$)/).replace(/bull/g,cf).replace(/blockCode/g,/ {4}/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).getRegex(),lu=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,Op=/^[^\n]+/,iu=/(?!\s*\])(?:\\.|[^\[\]\\])+/,Mp=me(/^ {0,3}\[(label)\]: *(?:\n *)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n *)?| *\n *)(title))? *(?:\n+|$)/).replace("label",iu).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Dp=me(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,cf).getRegex(),oo="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",ou=/|$))/,jp=me("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|\\n*|$)|\\n*|$)|)[\\s\\S]*?(?:(?:\\n *)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$)|(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$))","i").replace("comment",ou).replace("tag",oo).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),df=me(lu).replace("hr",Fl).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",oo).getRegex(),Fp=me(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",df).getRegex(),su={blockquote:Fp,code:Pp,def:Mp,fences:zp,heading:Ip,hr:Fl,html:jp,lheading:ff,list:Dp,newline:Ap,paragraph:df,table:Dl,text:Op},Kc=me("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",Fl).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code"," {4}[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",oo).getRegex(),Up={...su,table:Kc,paragraph:me(lu).replace("hr",Fl).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Kc).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",oo).getRegex()},$p={...su,html:me(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+? *(?:\\n{2,}|\\s*$)|\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",ou).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:Dl,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:me(lu).replace("hr",Fl).replace("heading",` *#{1,6} *[^ +]`).replace("lheading",ff).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},pf=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Bp=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,hf=/^( {2,}|\\)\n(?!\s*$)/,Hp=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\]*?>/g,Qp=me(/^(?:\*+(?:((?!\*)[punct])|[^\s*]))|^_+(?:((?!_)[punct])|([^\s_]))/,"u").replace(/punct/g,Ul).getRegex(),Gp=me("^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)[punct](\\*+)(?=[\\s]|$)|[^punct\\s](\\*+)(?!\\*)(?=[punct\\s]|$)|(?!\\*)[punct\\s](\\*+)(?=[^punct\\s])|[\\s](\\*+)(?!\\*)(?=[punct])|(?!\\*)[punct](\\*+)(?!\\*)(?=[punct])|[^punct\\s](\\*+)(?=[^punct\\s])","gu").replace(/punct/g,Ul).getRegex(),Yp=me("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)[punct](_+)(?=[\\s]|$)|[^punct\\s](_+)(?!_)(?=[punct\\s]|$)|(?!_)[punct\\s](_+)(?=[^punct\\s])|[\\s](_+)(?!_)(?=[punct])|(?!_)[punct](_+)(?!_)(?=[punct])","gu").replace(/punct/g,Ul).getRegex(),Kp=me(/\\([punct])/,"gu").replace(/punct/g,Ul).getRegex(),Xp=me(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),Zp=me(ou).replace("(?:-->|$)","-->").getRegex(),qp=me("^comment|^|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^|^").replace("comment",Zp).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),lo=/(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/,Jp=me(/^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/).replace("label",lo).replace("href",/<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),mf=me(/^!?\[(label)\]\[(ref)\]/).replace("label",lo).replace("ref",iu).getRegex(),gf=me(/^!?\[(ref)\](?:\[\])?/).replace("ref",iu).getRegex(),bp=me("reflink|nolink(?!\\()","g").replace("reflink",mf).replace("nolink",gf).getRegex(),uu={_backpedal:Dl,anyPunctuation:Kp,autolink:Xp,blockSkip:Vp,br:hf,code:Bp,del:Dl,emStrongLDelim:Qp,emStrongRDelimAst:Gp,emStrongRDelimUnd:Yp,escape:pf,link:Jp,nolink:gf,punctuation:Wp,reflink:mf,reflinkSearch:bp,tag:qp,text:Hp,url:Dl},eh={...uu,link:me(/^!?\[(label)\]\((.*?)\)/).replace("label",lo).getRegex(),reflink:me(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",lo).getRegex()},Js={...uu,escape:me(pf).replace("])","~|])").getRegex(),url:me(/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/,"i").replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])([\s\S]*?[^\s~])\1(?=[^~]|$)/,text:/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\E+" ".repeat(j.length));let a,f,h,d;for(;s;)if(!(this.options.extensions&&this.options.extensions.block&&this.options.extensions.block.some(S=>(a=S.call({lexer:this},s,o))?(s=s.substring(a.raw.length),o.push(a),!0):!1))){if(a=this.tokenizer.space(s)){s=s.substring(a.raw.length),a.raw.length===1&&o.length>0?o[o.length-1].raw+=` +`:o.push(a);continue}if(a=this.tokenizer.code(s)){s=s.substring(a.raw.length),f=o[o.length-1],f&&(f.type==="paragraph"||f.type==="text")?(f.raw+=` +`+a.raw,f.text+=` +`+a.text,this.inlineQueue[this.inlineQueue.length-1].src=f.text):o.push(a);continue}if(a=this.tokenizer.fences(s)){s=s.substring(a.raw.length),o.push(a);continue}if(a=this.tokenizer.heading(s)){s=s.substring(a.raw.length),o.push(a);continue}if(a=this.tokenizer.hr(s)){s=s.substring(a.raw.length),o.push(a);continue}if(a=this.tokenizer.blockquote(s)){s=s.substring(a.raw.length),o.push(a);continue}if(a=this.tokenizer.list(s)){s=s.substring(a.raw.length),o.push(a);continue}if(a=this.tokenizer.html(s)){s=s.substring(a.raw.length),o.push(a);continue}if(a=this.tokenizer.def(s)){s=s.substring(a.raw.length),f=o[o.length-1],f&&(f.type==="paragraph"||f.type==="text")?(f.raw+=` +`+a.raw,f.text+=` +`+a.raw,this.inlineQueue[this.inlineQueue.length-1].src=f.text):this.tokens.links[a.tag]||(this.tokens.links[a.tag]={href:a.href,title:a.title});continue}if(a=this.tokenizer.table(s)){s=s.substring(a.raw.length),o.push(a);continue}if(a=this.tokenizer.lheading(s)){s=s.substring(a.raw.length),o.push(a);continue}if(h=s,this.options.extensions&&this.options.extensions.startBlock){let S=1/0;const E=s.slice(1);let j;this.options.extensions.startBlock.forEach(P=>{j=P.call({lexer:this},E),typeof j=="number"&&j>=0&&(S=Math.min(S,j))}),S<1/0&&S>=0&&(h=s.substring(0,S+1))}if(this.state.top&&(a=this.tokenizer.paragraph(h))){f=o[o.length-1],d&&f.type==="paragraph"?(f.raw+=` +`+a.raw,f.text+=` +`+a.text,this.inlineQueue.pop(),this.inlineQueue[this.inlineQueue.length-1].src=f.text):o.push(a),d=h.length!==s.length,s=s.substring(a.raw.length);continue}if(a=this.tokenizer.text(s)){s=s.substring(a.raw.length),f=o[o.length-1],f&&f.type==="text"?(f.raw+=` +`+a.raw,f.text+=` +`+a.text,this.inlineQueue.pop(),this.inlineQueue[this.inlineQueue.length-1].src=f.text):o.push(a);continue}if(s){const S="Infinite loop on byte: "+s.charCodeAt(0);if(this.options.silent){console.error(S);break}else throw new Error(S)}}return this.state.top=!0,o}inline(s,o=[]){return this.inlineQueue.push({src:s,tokens:o}),o}inlineTokens(s,o=[]){let a,f,h,d=s,S,E,j;if(this.tokens.links){const P=Object.keys(this.tokens.links);if(P.length>0)for(;(S=this.tokenizer.rules.inline.reflinkSearch.exec(d))!=null;)P.includes(S[0].slice(S[0].lastIndexOf("[")+1,-1))&&(d=d.slice(0,S.index)+"["+"a".repeat(S[0].length-2)+"]"+d.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(S=this.tokenizer.rules.inline.blockSkip.exec(d))!=null;)d=d.slice(0,S.index)+"["+"a".repeat(S[0].length-2)+"]"+d.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);for(;(S=this.tokenizer.rules.inline.anyPunctuation.exec(d))!=null;)d=d.slice(0,S.index)+"++"+d.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);for(;s;)if(E||(j=""),E=!1,!(this.options.extensions&&this.options.extensions.inline&&this.options.extensions.inline.some(P=>(a=P.call({lexer:this},s,o))?(s=s.substring(a.raw.length),o.push(a),!0):!1))){if(a=this.tokenizer.escape(s)){s=s.substring(a.raw.length),o.push(a);continue}if(a=this.tokenizer.tag(s)){s=s.substring(a.raw.length),f=o[o.length-1],f&&a.type==="text"&&f.type==="text"?(f.raw+=a.raw,f.text+=a.text):o.push(a);continue}if(a=this.tokenizer.link(s)){s=s.substring(a.raw.length),o.push(a);continue}if(a=this.tokenizer.reflink(s,this.tokens.links)){s=s.substring(a.raw.length),f=o[o.length-1],f&&a.type==="text"&&f.type==="text"?(f.raw+=a.raw,f.text+=a.text):o.push(a);continue}if(a=this.tokenizer.emStrong(s,d,j)){s=s.substring(a.raw.length),o.push(a);continue}if(a=this.tokenizer.codespan(s)){s=s.substring(a.raw.length),o.push(a);continue}if(a=this.tokenizer.br(s)){s=s.substring(a.raw.length),o.push(a);continue}if(a=this.tokenizer.del(s)){s=s.substring(a.raw.length),o.push(a);continue}if(a=this.tokenizer.autolink(s)){s=s.substring(a.raw.length),o.push(a);continue}if(!this.state.inLink&&(a=this.tokenizer.url(s))){s=s.substring(a.raw.length),o.push(a);continue}if(h=s,this.options.extensions&&this.options.extensions.startInline){let P=1/0;const O=s.slice(1);let z;this.options.extensions.startInline.forEach(G=>{z=G.call({lexer:this},O),typeof z=="number"&&z>=0&&(P=Math.min(P,z))}),P<1/0&&P>=0&&(h=s.substring(0,P+1))}if(a=this.tokenizer.inlineText(h)){s=s.substring(a.raw.length),a.raw.slice(-1)!=="_"&&(j=a.raw.slice(-1)),E=!0,f=o[o.length-1],f&&f.type==="text"?(f.raw+=a.raw,f.text+=a.text):o.push(a);continue}if(s){const P="Infinite loop on byte: "+s.charCodeAt(0);if(this.options.silent){console.error(P);break}else throw new Error(P)}}return o}}class io{constructor(s){xe(this,"options");this.options=s||pr}code(s,o,a){var h;const f=(h=(o||"").match(/^\S*/))==null?void 0:h[0];return s=s.replace(/\n$/,"")+` +`,f?'
'+(a?s:wt(s,!0))+`
+`:"
"+(a?s:wt(s,!0))+`
+`}blockquote(s){return`
+${s}
+`}html(s,o){return s}heading(s,o,a){return`${s} +`}hr(){return`
+`}list(s,o,a){const f=o?"ol":"ul",h=o&&a!==1?' start="'+a+'"':"";return"<"+f+h+`> +`+s+" +`}listitem(s,o,a){return`
  • ${s}
  • +`}checkbox(s){return"'}paragraph(s){return`

    ${s}

    +`}table(s,o){return o&&(o=`${o}`),` + +`+s+` +`+o+`
    +`}tablerow(s){return` +${s} +`}tablecell(s,o){const a=o.header?"th":"td";return(o.align?`<${a} align="${o.align}">`:`<${a}>`)+s+` +`}strong(s){return`${s}`}em(s){return`${s}`}codespan(s){return`${s}`}br(){return"
    "}del(s){return`${s}`}link(s,o,a){const f=Qc(s);if(f===null)return a;s=f;let h='
    ",h}image(s,o,a){const f=Qc(s);if(f===null)return a;s=f;let h=`${a}0&&z.tokens[0].type==="paragraph"?(z.tokens[0].text=J+" "+z.tokens[0].text,z.tokens[0].tokens&&z.tokens[0].tokens.length>0&&z.tokens[0].tokens[0].type==="text"&&(z.tokens[0].tokens[0].text=J+" "+z.tokens[0].tokens[0].text)):z.tokens.unshift({type:"text",text:J+" "}):Z+=J+" "}Z+=this.parse(z.tokens,j),P+=this.renderer.listitem(Z,ce,!!G)}a+=this.renderer.list(P,S,E);continue}case"html":{const d=h;a+=this.renderer.html(d.text,d.block);continue}case"paragraph":{const d=h;a+=this.renderer.paragraph(this.parseInline(d.tokens));continue}case"text":{let d=h,S=d.tokens?this.parseInline(d.tokens):d.text;for(;f+1{const j=S[E].flat(1/0);a=a.concat(this.walkTokens(j,o))}):S.tokens&&(a=a.concat(this.walkTokens(S.tokens,o)))}}return a}use(...s){const o=this.defaults.extensions||{renderers:{},childTokens:{}};return s.forEach(a=>{const f={...a};if(f.async=this.defaults.async||f.async||!1,a.extensions&&(a.extensions.forEach(h=>{if(!h.name)throw new Error("extension name required");if("renderer"in h){const d=o.renderers[h.name];d?o.renderers[h.name]=function(...S){let E=h.renderer.apply(this,S);return E===!1&&(E=d.apply(this,S)),E}:o.renderers[h.name]=h.renderer}if("tokenizer"in h){if(!h.level||h.level!=="block"&&h.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");const d=o[h.level];d?d.unshift(h.tokenizer):o[h.level]=[h.tokenizer],h.start&&(h.level==="block"?o.startBlock?o.startBlock.push(h.start):o.startBlock=[h.start]:h.level==="inline"&&(o.startInline?o.startInline.push(h.start):o.startInline=[h.start]))}"childTokens"in h&&h.childTokens&&(o.childTokens[h.name]=h.childTokens)}),f.extensions=o),a.renderer){const h=this.defaults.renderer||new io(this.defaults);for(const d in a.renderer){if(!(d in h))throw new Error(`renderer '${d}' does not exist`);if(d==="options")continue;const S=d,E=a.renderer[S],j=h[S];h[S]=(...P)=>{let O=E.apply(h,P);return O===!1&&(O=j.apply(h,P)),O||""}}f.renderer=h}if(a.tokenizer){const h=this.defaults.tokenizer||new ro(this.defaults);for(const d in a.tokenizer){if(!(d in h))throw new Error(`tokenizer '${d}' does not exist`);if(["options","rules","lexer"].includes(d))continue;const S=d,E=a.tokenizer[S],j=h[S];h[S]=(...P)=>{let O=E.apply(h,P);return O===!1&&(O=j.apply(h,P)),O}}f.tokenizer=h}if(a.hooks){const h=this.defaults.hooks||new jl;for(const d in a.hooks){if(!(d in h))throw new Error(`hook '${d}' does not exist`);if(d==="options")continue;const S=d,E=a.hooks[S],j=h[S];jl.passThroughHooks.has(d)?h[S]=P=>{if(this.defaults.async)return Promise.resolve(E.call(h,P)).then(z=>j.call(h,z));const O=E.call(h,P);return j.call(h,O)}:h[S]=(...P)=>{let O=E.apply(h,P);return O===!1&&(O=j.apply(h,P)),O}}f.hooks=h}if(a.walkTokens){const h=this.defaults.walkTokens,d=a.walkTokens;f.walkTokens=function(S){let E=[];return E.push(d.call(this,S)),h&&(E=E.concat(h.call(this,S))),E}}this.defaults={...this.defaults,...f}}),this}setOptions(s){return this.defaults={...this.defaults,...s},this}lexer(s,o){return Xt.lex(s,o??this.defaults)}parser(s,o){return Zt.parse(s,o??this.defaults)}}dr=new WeakSet,bs=function(s,o){return(a,f)=>{const h={...f},d={...this.defaults,...h};this.defaults.async===!0&&h.async===!1&&(d.silent||console.warn("marked(): The async option was set to true by an extension. The async: false option sent to parse will be ignored."),d.async=!0);const S=Zi(this,dr,yf).call(this,!!d.silent,!!d.async);if(typeof a>"u"||a===null)return S(new Error("marked(): input parameter is undefined or null"));if(typeof a!="string")return S(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(a)+", string expected"));if(d.hooks&&(d.hooks.options=d),d.async)return Promise.resolve(d.hooks?d.hooks.preprocess(a):a).then(E=>s(E,d)).then(E=>d.hooks?d.hooks.processAllTokens(E):E).then(E=>d.walkTokens?Promise.all(this.walkTokens(E,d.walkTokens)).then(()=>E):E).then(E=>o(E,d)).then(E=>d.hooks?d.hooks.postprocess(E):E).catch(S);try{d.hooks&&(a=d.hooks.preprocess(a));let E=s(a,d);d.hooks&&(E=d.hooks.processAllTokens(E)),d.walkTokens&&this.walkTokens(E,d.walkTokens);let j=o(E,d);return d.hooks&&(j=d.hooks.postprocess(j)),j}catch(E){return S(E)}}},yf=function(s,o){return a=>{if(a.message+=` +Please report this to https://github.com/markedjs/marked.`,s){const f="

    An error occurred:

    "+wt(a.message+"",!0)+"
    ";return o?Promise.resolve(f):f}if(o)return Promise.reject(a);throw a}};const fr=new nh;function pe(v,s){return fr.parse(v,s)}pe.options=pe.setOptions=function(v){return fr.setOptions(v),pe.defaults=fr.defaults,sf(pe.defaults),pe};pe.getDefaults=ru;pe.defaults=pr;pe.use=function(...v){return fr.use(...v),pe.defaults=fr.defaults,sf(pe.defaults),pe};pe.walkTokens=function(v,s){return fr.walkTokens(v,s)};pe.parseInline=fr.parseInline;pe.Parser=Zt;pe.parser=Zt.parse;pe.Renderer=io;pe.TextRenderer=au;pe.Lexer=Xt;pe.lexer=Xt.lex;pe.Tokenizer=ro;pe.Hooks=jl;pe.parse=pe;pe.options;pe.setOptions;pe.use;pe.walkTokens;pe.parseInline;Zt.parse;Xt.lex;/*! @license DOMPurify 3.2.4 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.2.4/LICENSE */const{entries:vf,setPrototypeOf:Xc,isFrozen:rh,getPrototypeOf:lh,getOwnPropertyDescriptor:ih}=Object;let{freeze:st,seal:At,create:kf}=Object,{apply:eu,construct:tu}=typeof Reflect<"u"&&Reflect;st||(st=function(s){return s});At||(At=function(s){return s});eu||(eu=function(s,o,a){return s.apply(o,a)});tu||(tu=function(s,o){return new s(...o)});const eo=ut(Array.prototype.forEach),oh=ut(Array.prototype.lastIndexOf),Zc=ut(Array.prototype.pop),Pl=ut(Array.prototype.push),sh=ut(Array.prototype.splice),no=ut(String.prototype.toLowerCase),Ys=ut(String.prototype.toString),qc=ut(String.prototype.match),zl=ut(String.prototype.replace),uh=ut(String.prototype.indexOf),ah=ut(String.prototype.trim),$t=ut(Object.prototype.hasOwnProperty),ot=ut(RegExp.prototype.test),Il=ch(TypeError);function ut(v){return function(s){for(var o=arguments.length,a=new Array(o>1?o-1:0),f=1;f2&&arguments[2]!==void 0?arguments[2]:no;Xc&&Xc(v,null);let a=s.length;for(;a--;){let f=s[a];if(typeof f=="string"){const h=o(f);h!==f&&(rh(s)||(s[a]=h),f=h)}v[f]=!0}return v}function fh(v){for(let s=0;s/gm),gh=At(/\$\{[\w\W]*/gm),yh=At(/^data-[\-\w.\u00B7-\uFFFF]+$/),vh=At(/^aria-[\-\w]+$/),wf=At(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),kh=At(/^(?:\w+script|data):/i),wh=At(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),xf=At(/^html$/i),xh=At(/^[a-z][.\w]*(-[.\w]+)+$/i);var nf=Object.freeze({__proto__:null,ARIA_ATTR:vh,ATTR_WHITESPACE:wh,CUSTOM_ELEMENT:xh,DATA_ATTR:yh,DOCTYPE_NAME:xf,ERB_EXPR:mh,IS_ALLOWED_URI:wf,IS_SCRIPT_OR_DATA:kh,MUSTACHE_EXPR:hh,TMPLIT_EXPR:gh});const Ml={element:1,text:3,progressingInstruction:7,comment:8,document:9},Sh=function(){return typeof window>"u"?null:window},Eh=function(s,o){if(typeof s!="object"||typeof s.createPolicy!="function")return null;let a=null;const f="data-tt-policy-suffix";o&&o.hasAttribute(f)&&(a=o.getAttribute(f));const h="dompurify"+(a?"#"+a:"");try{return s.createPolicy(h,{createHTML(d){return d},createScriptURL(d){return d}})}catch{return console.warn("TrustedTypes policy "+h+" could not be created."),null}},rf=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function Sf(){let v=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Sh();const s=W=>Sf(W);if(s.version="3.2.4",s.removed=[],!v||!v.document||v.document.nodeType!==Ml.document||!v.Element)return s.isSupported=!1,s;let{document:o}=v;const a=o,f=a.currentScript,{DocumentFragment:h,HTMLTemplateElement:d,Node:S,Element:E,NodeFilter:j,NamedNodeMap:P=v.NamedNodeMap||v.MozNamedAttrMap,HTMLFormElement:O,DOMParser:z,trustedTypes:G}=v,ce=E.prototype,Z=Ol(ce,"cloneNode"),J=Ol(ce,"remove"),De=Ol(ce,"nextSibling"),je=Ol(ce,"childNodes"),Ne=Ol(ce,"parentNode");if(typeof d=="function"){const W=o.createElement("template");W.content&&W.content.ownerDocument&&(o=W.content.ownerDocument)}let le,ve="";const{implementation:Ae,createNodeIterator:He,createDocumentFragment:b,getElementsByTagName:Pe}=o,{importNode:Se}=a;let oe=rf();s.isSupported=typeof vf=="function"&&typeof Ne=="function"&&Ae&&Ae.createHTMLDocument!==void 0;const{MUSTACHE_EXPR:Re,ERB_EXPR:Fe,TMPLIT_EXPR:Ke,DATA_ATTR:Xe,ARIA_ATTR:Ue,IS_SCRIPT_OR_DATA:Ee,ATTR_WHITESPACE:I,CUSTOM_ELEMENT:X}=nf;let{IS_ALLOWED_URI:D}=nf,y=null;const _=ie({},[...Jc,...Ks,...Xs,...Zs,...bc]);let V=null;const ee=ie({},[...ef,...qs,...tf,...to]);let Q=Object.seal(kf(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),ne=null,fe=null,ue=!0,he=!0,Je=!1,Hn=!0,qt=!1,dn=!0,Pt=!1,hr=!1,mr=!1,Bt=!1,Wn=!1,pn=!1,hn=!0,Jt=!1;const Vr="user-content-";let gr=!0,mn=!1,bt={},en=null;const yr=ie({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let Vn=null;const Qr=ie({},["audio","video","img","source","image","track"]);let tn=null;const gn=ie({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),vr="http://www.w3.org/1998/Math/MathML",Qn="http://www.w3.org/2000/svg",xt="http://www.w3.org/1999/xhtml";let yn=xt,Gn=!1,Yn=null;const Gr=ie({},[vr,Qn,xt],Ys);let vn=ie({},["mi","mo","mn","ms","mtext"]),kn=ie({},["annotation-xml"]);const wn=ie({},["title","style","font","a","script"]);let St=null;const $l=["application/xhtml+xml","text/html"],Bl="text/html";let ze=null,nn=null;const Hl=o.createElement("form"),kr=function(m){return m instanceof RegExp||m instanceof Function},wr=function(){let m=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(nn&&nn===m)){if((!m||typeof m!="object")&&(m={}),m=cr(m),St=$l.indexOf(m.PARSER_MEDIA_TYPE)===-1?Bl:m.PARSER_MEDIA_TYPE,ze=St==="application/xhtml+xml"?Ys:no,y=$t(m,"ALLOWED_TAGS")?ie({},m.ALLOWED_TAGS,ze):_,V=$t(m,"ALLOWED_ATTR")?ie({},m.ALLOWED_ATTR,ze):ee,Yn=$t(m,"ALLOWED_NAMESPACES")?ie({},m.ALLOWED_NAMESPACES,Ys):Gr,tn=$t(m,"ADD_URI_SAFE_ATTR")?ie(cr(gn),m.ADD_URI_SAFE_ATTR,ze):gn,Vn=$t(m,"ADD_DATA_URI_TAGS")?ie(cr(Qr),m.ADD_DATA_URI_TAGS,ze):Qr,en=$t(m,"FORBID_CONTENTS")?ie({},m.FORBID_CONTENTS,ze):yr,ne=$t(m,"FORBID_TAGS")?ie({},m.FORBID_TAGS,ze):{},fe=$t(m,"FORBID_ATTR")?ie({},m.FORBID_ATTR,ze):{},bt=$t(m,"USE_PROFILES")?m.USE_PROFILES:!1,ue=m.ALLOW_ARIA_ATTR!==!1,he=m.ALLOW_DATA_ATTR!==!1,Je=m.ALLOW_UNKNOWN_PROTOCOLS||!1,Hn=m.ALLOW_SELF_CLOSE_IN_ATTR!==!1,qt=m.SAFE_FOR_TEMPLATES||!1,dn=m.SAFE_FOR_XML!==!1,Pt=m.WHOLE_DOCUMENT||!1,Bt=m.RETURN_DOM||!1,Wn=m.RETURN_DOM_FRAGMENT||!1,pn=m.RETURN_TRUSTED_TYPE||!1,mr=m.FORCE_BODY||!1,hn=m.SANITIZE_DOM!==!1,Jt=m.SANITIZE_NAMED_PROPS||!1,gr=m.KEEP_CONTENT!==!1,mn=m.IN_PLACE||!1,D=m.ALLOWED_URI_REGEXP||wf,yn=m.NAMESPACE||xt,vn=m.MATHML_TEXT_INTEGRATION_POINTS||vn,kn=m.HTML_INTEGRATION_POINTS||kn,Q=m.CUSTOM_ELEMENT_HANDLING||{},m.CUSTOM_ELEMENT_HANDLING&&kr(m.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(Q.tagNameCheck=m.CUSTOM_ELEMENT_HANDLING.tagNameCheck),m.CUSTOM_ELEMENT_HANDLING&&kr(m.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(Q.attributeNameCheck=m.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),m.CUSTOM_ELEMENT_HANDLING&&typeof m.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(Q.allowCustomizedBuiltInElements=m.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),qt&&(he=!1),Wn&&(Bt=!0),bt&&(y=ie({},bc),V=[],bt.html===!0&&(ie(y,Jc),ie(V,ef)),bt.svg===!0&&(ie(y,Ks),ie(V,qs),ie(V,to)),bt.svgFilters===!0&&(ie(y,Xs),ie(V,qs),ie(V,to)),bt.mathMl===!0&&(ie(y,Zs),ie(V,tf),ie(V,to))),m.ADD_TAGS&&(y===_&&(y=cr(y)),ie(y,m.ADD_TAGS,ze)),m.ADD_ATTR&&(V===ee&&(V=cr(V)),ie(V,m.ADD_ATTR,ze)),m.ADD_URI_SAFE_ATTR&&ie(tn,m.ADD_URI_SAFE_ATTR,ze),m.FORBID_CONTENTS&&(en===yr&&(en=cr(en)),ie(en,m.FORBID_CONTENTS,ze)),gr&&(y["#text"]=!0),Pt&&ie(y,["html","head","body"]),y.table&&(ie(y,["tbody"]),delete ne.tbody),m.TRUSTED_TYPES_POLICY){if(typeof m.TRUSTED_TYPES_POLICY.createHTML!="function")throw Il('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof m.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw Il('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');le=m.TRUSTED_TYPES_POLICY,ve=le.createHTML("")}else le===void 0&&(le=Eh(G,f)),le!==null&&typeof ve=="string"&&(ve=le.createHTML(""));st&&st(m),nn=m}},xn=ie({},[...Ks,...Xs,...dh]),xr=ie({},[...Zs,...ph]),Kn=function(m){let R=Ne(m);(!R||!R.tagName)&&(R={namespaceURI:yn,tagName:"template"});const $=no(m.tagName),ge=no(R.tagName);return Yn[m.namespaceURI]?m.namespaceURI===Qn?R.namespaceURI===xt?$==="svg":R.namespaceURI===vr?$==="svg"&&(ge==="annotation-xml"||vn[ge]):!!xn[$]:m.namespaceURI===vr?R.namespaceURI===xt?$==="math":R.namespaceURI===Qn?$==="math"&&kn[ge]:!!xr[$]:m.namespaceURI===xt?R.namespaceURI===Qn&&!kn[ge]||R.namespaceURI===vr&&!vn[ge]?!1:!xr[$]&&(wn[$]||!xn[$]):!!(St==="application/xhtml+xml"&&Yn[m.namespaceURI]):!1},Et=function(m){Pl(s.removed,{element:m});try{Ne(m).removeChild(m)}catch{J(m)}},Ht=function(m,R){try{Pl(s.removed,{attribute:R.getAttributeNode(m),from:R})}catch{Pl(s.removed,{attribute:null,from:R})}if(R.removeAttribute(m),m==="is")if(Bt||Wn)try{Et(R)}catch{}else try{R.setAttribute(m,"")}catch{}},Xn=function(m){let R=null,$=null;if(mr)m=""+m;else{const te=qc(m,/^[\r\n\t ]+/);$=te&&te[0]}St==="application/xhtml+xml"&&yn===xt&&(m=''+m+"");const ge=le?le.createHTML(m):m;if(yn===xt)try{R=new z().parseFromString(ge,St)}catch{}if(!R||!R.documentElement){R=Ae.createDocument(yn,"template",null);try{R.documentElement.innerHTML=Gn?ve:ge}catch{}}const We=R.body||R.documentElement;return m&&$&&We.insertBefore(o.createTextNode($),We.childNodes[0]||null),yn===xt?Pe.call(R,Pt?"html":"body")[0]:Pt?R.documentElement:We},Zn=function(m){return He.call(m.ownerDocument||m,m,j.SHOW_ELEMENT|j.SHOW_COMMENT|j.SHOW_TEXT|j.SHOW_PROCESSING_INSTRUCTION|j.SHOW_CDATA_SECTION,null)},qn=function(m){return m instanceof O&&(typeof m.nodeName!="string"||typeof m.textContent!="string"||typeof m.removeChild!="function"||!(m.attributes instanceof P)||typeof m.removeAttribute!="function"||typeof m.setAttribute!="function"||typeof m.namespaceURI!="string"||typeof m.insertBefore!="function"||typeof m.hasChildNodes!="function")},Wl=function(m){return typeof S=="function"&&m instanceof S};function zt(W,m,R){eo(W,$=>{$.call(s,m,R,nn)})}const Vl=function(m){let R=null;if(zt(oe.beforeSanitizeElements,m,null),qn(m))return Et(m),!0;const $=ze(m.nodeName);if(zt(oe.uponSanitizeElement,m,{tagName:$,allowedTags:y}),m.hasChildNodes()&&!Wl(m.firstElementChild)&&ot(/<[/\w]/g,m.innerHTML)&&ot(/<[/\w]/g,m.textContent)||m.nodeType===Ml.progressingInstruction||dn&&m.nodeType===Ml.comment&&ot(/<[/\w]/g,m.data))return Et(m),!0;if(!y[$]||ne[$]){if(!ne[$]&&Yr($)&&(Q.tagNameCheck instanceof RegExp&&ot(Q.tagNameCheck,$)||Q.tagNameCheck instanceof Function&&Q.tagNameCheck($)))return!1;if(gr&&!en[$]){const ge=Ne(m)||m.parentNode,We=je(m)||m.childNodes;if(We&&ge){const te=We.length;for(let be=te-1;be>=0;--be){const at=Z(We[be],!0);at.__removalCount=(m.__removalCount||0)+1,ge.insertBefore(at,De(m))}}}return Et(m),!0}return m instanceof E&&!Kn(m)||($==="noscript"||$==="noembed"||$==="noframes")&&ot(/<\/no(script|embed|frames)/i,m.innerHTML)?(Et(m),!0):(qt&&m.nodeType===Ml.text&&(R=m.textContent,eo([Re,Fe,Ke],ge=>{R=zl(R,ge," ")}),m.textContent!==R&&(Pl(s.removed,{element:m.cloneNode()}),m.textContent=R)),zt(oe.afterSanitizeElements,m,null),!1)},Wt=function(m,R,$){if(hn&&(R==="id"||R==="name")&&($ in o||$ in Hl))return!1;if(!(he&&!fe[R]&&ot(Xe,R))){if(!(ue&&ot(Ue,R))){if(!V[R]||fe[R]){if(!(Yr(m)&&(Q.tagNameCheck instanceof RegExp&&ot(Q.tagNameCheck,m)||Q.tagNameCheck instanceof Function&&Q.tagNameCheck(m))&&(Q.attributeNameCheck instanceof RegExp&&ot(Q.attributeNameCheck,R)||Q.attributeNameCheck instanceof Function&&Q.attributeNameCheck(R))||R==="is"&&Q.allowCustomizedBuiltInElements&&(Q.tagNameCheck instanceof RegExp&&ot(Q.tagNameCheck,$)||Q.tagNameCheck instanceof Function&&Q.tagNameCheck($))))return!1}else if(!tn[R]){if(!ot(D,zl($,I,""))){if(!((R==="src"||R==="xlink:href"||R==="href")&&m!=="script"&&uh($,"data:")===0&&Vn[m])){if(!(Je&&!ot(Ee,zl($,I,"")))){if($)return!1}}}}}}return!0},Yr=function(m){return m!=="annotation-xml"&&qc(m,X)},Kr=function(m){zt(oe.beforeSanitizeAttributes,m,null);const{attributes:R}=m;if(!R||qn(m))return;const $={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:V,forceKeepAttr:void 0};let ge=R.length;for(;ge--;){const We=R[ge],{name:te,namespaceURI:be,value:at}=We,Sn=ze(te);let Oe=te==="value"?at:ah(at);if($.attrName=Sn,$.attrValue=Oe,$.keepAttr=!0,$.forceKeepAttr=void 0,zt(oe.uponSanitizeAttribute,m,$),Oe=$.attrValue,Jt&&(Sn==="id"||Sn==="name")&&(Ht(te,m),Oe=Vr+Oe),dn&&ot(/((--!?|])>)|<\/(style|title)/i,Oe)){Ht(te,m);continue}if($.forceKeepAttr||(Ht(te,m),!$.keepAttr))continue;if(!Hn&&ot(/\/>/i,Oe)){Ht(te,m);continue}qt&&eo([Re,Fe,Ke],Xr=>{Oe=zl(Oe,Xr," ")});const Ql=ze(m.nodeName);if(Wt(Ql,Sn,Oe)){if(le&&typeof G=="object"&&typeof G.getAttributeType=="function"&&!be)switch(G.getAttributeType(Ql,Sn)){case"TrustedHTML":{Oe=le.createHTML(Oe);break}case"TrustedScriptURL":{Oe=le.createScriptURL(Oe);break}}try{be?m.setAttributeNS(be,te,Oe):m.setAttribute(te,Oe),qn(m)?Et(m):Zc(s.removed)}catch{}}}zt(oe.afterSanitizeAttributes,m,null)},so=function W(m){let R=null;const $=Zn(m);for(zt(oe.beforeSanitizeShadowDOM,m,null);R=$.nextNode();)zt(oe.uponSanitizeShadowNode,R,null),Vl(R),Kr(R),R.content instanceof h&&W(R.content);zt(oe.afterSanitizeShadowDOM,m,null)};return s.sanitize=function(W){let m=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},R=null,$=null,ge=null,We=null;if(Gn=!W,Gn&&(W=""),typeof W!="string"&&!Wl(W))if(typeof W.toString=="function"){if(W=W.toString(),typeof W!="string")throw Il("dirty is not a string, aborting")}else throw Il("toString is not a function");if(!s.isSupported)return W;if(hr||wr(m),s.removed=[],typeof W=="string"&&(mn=!1),mn){if(W.nodeName){const at=ze(W.nodeName);if(!y[at]||ne[at])throw Il("root node is forbidden and cannot be sanitized in-place")}}else if(W instanceof S)R=Xn(""),$=R.ownerDocument.importNode(W,!0),$.nodeType===Ml.element&&$.nodeName==="BODY"||$.nodeName==="HTML"?R=$:R.appendChild($);else{if(!Bt&&!qt&&!Pt&&W.indexOf("<")===-1)return le&&pn?le.createHTML(W):W;if(R=Xn(W),!R)return Bt?null:pn?ve:""}R&&mr&&Et(R.firstChild);const te=Zn(mn?W:R);for(;ge=te.nextNode();)Vl(ge),Kr(ge),ge.content instanceof h&&so(ge.content);if(mn)return W;if(Bt){if(Wn)for(We=b.call(R.ownerDocument);R.firstChild;)We.appendChild(R.firstChild);else We=R;return(V.shadowroot||V.shadowrootmode)&&(We=Se.call(a,We,!0)),We}let be=Pt?R.outerHTML:R.innerHTML;return Pt&&y["!doctype"]&&R.ownerDocument&&R.ownerDocument.doctype&&R.ownerDocument.doctype.name&&ot(xf,R.ownerDocument.doctype.name)&&(be=" +`+be),qt&&eo([Re,Fe,Ke],at=>{be=zl(be,at," ")}),le&&pn?le.createHTML(be):be},s.setConfig=function(){let W=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};wr(W),hr=!0},s.clearConfig=function(){nn=null,hr=!1},s.isValidAttribute=function(W,m,R){nn||wr({});const $=ze(W),ge=ze(m);return Wt($,ge,R)},s.addHook=function(W,m){typeof m=="function"&&Pl(oe[W],m)},s.removeHook=function(W,m){if(m!==void 0){const R=oh(oe[W],m);return R===-1?void 0:sh(oe[W],R,1)[0]}return Zc(oe[W])},s.removeHooks=function(W){oe[W]=[]},s.removeAllHooks=function(){oe=rf()},s}var _h=Sf();function Th(v){return L.jsxs("svg",{...v,xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[L.jsx("path",{d:"M12 8V4H8"}),L.jsx("rect",{width:"16",height:"12",x:"4",y:"8",rx:"2"}),L.jsx("path",{d:"M2 14h2"}),L.jsx("path",{d:"M20 14h2"}),L.jsx("path",{d:"M15 13v2"}),L.jsx("path",{d:"M9 13v2"})]})}function Ch(v){return L.jsxs("svg",{...v,xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[L.jsx("path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2"}),L.jsx("circle",{cx:"12",cy:"7",r:"4"})]})}function Nh(v){return _h.sanitize(pe.parse(v))}function Rh({messages:v}){const s=v.length===0;return Ye.useEffect(()=>{window.MathJax.typeset()},[v]),L.jsx("div",{className:`flex-1 p-6 max-w-[960px] w-full ${s?"flex flex-col items-center justify-end":"space-y-4"}`,children:s?L.jsx("div",{className:"text-xl",children:"Ready!"}):v.map((o,a)=>L.jsx("div",{className:"flex items-start space-x-4",children:o.role==="assistant"?L.jsxs(L.Fragment,{children:[L.jsx(Th,{className:"h-6 w-6 min-h-6 min-w-6 my-3 text-gray-500 dark:text-gray-300"}),L.jsx("div",{className:"bg-gray-200 dark:bg-gray-700 rounded-lg p-4",children:L.jsx("p",{className:"min-h-6 text-gray-800 dark:text-gray-200 overflow-wrap-anywhere",children:o.content.length>0?L.jsx("span",{className:"markdown",dangerouslySetInnerHTML:{__html:Nh(o.content)}}):L.jsxs("span",{className:"h-6 flex items-center gap-1",children:[L.jsx("span",{className:"w-2.5 h-2.5 bg-gray-600 dark:bg-gray-300 rounded-full animate-pulse"}),L.jsx("span",{className:"w-2.5 h-2.5 bg-gray-600 dark:bg-gray-300 rounded-full animate-pulse animation-delay-200"}),L.jsx("span",{className:"w-2.5 h-2.5 bg-gray-600 dark:bg-gray-300 rounded-full animate-pulse animation-delay-400"})]})})})]}):L.jsxs(L.Fragment,{children:[L.jsx(Ch,{className:"h-6 w-6 min-h-6 min-w-6 my-3 text-gray-500 dark:text-gray-300"}),L.jsx("div",{className:"bg-blue-500 text-white rounded-lg p-4",children:L.jsx("p",{className:"min-h-6 overflow-wrap-anywhere",children:o.content})})]})},`message-${a}`))})}function lf(v){return L.jsxs("svg",{...v,xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[L.jsx("path",{d:"M5 12h14"}),L.jsx("path",{d:"m12 5 7 7-7 7"})]})}function Lh(v){return L.jsxs("svg",{...v,xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[L.jsx("path",{d:"M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z"}),L.jsx("path",{fill:"currentColor",d:"M9 9.563C9 9.252 9.252 9 9.563 9h4.874c.311 0 .563.252.563.563v4.874c0 .311-.252.563-.563.563H9.564A.562.562 0 0 1 9 14.437V9.564Z"})]})}function Ah(v){const s=v==0?0:Math.floor(Math.log(v)/Math.log(1024));return+(v/Math.pow(1024,s)).toFixed(2)*1+["B","kB","MB","GB","TB"][s]}function Ph({text:v,percentage:s,total:o}){return s??(s=0),L.jsx("div",{className:"w-full bg-gray-100 dark:bg-gray-700 text-left rounded-lg overflow-hidden mb-0.5",children:L.jsxs("div",{className:"bg-blue-400 whitespace-nowrap px-1 text-sm",style:{width:`${s}%`},children:[v," (",s.toFixed(2),"%",isNaN(o)?"":` of ${Ah(o)}`,")"]})})}const zh=!!navigator.gpu,Ih=120,Oh=["Give me some tips to improve my time management skills.","What is the difference between AI and ML?","Write python code to compute the nth fibonacci number."];function Mh(){const v=Ye.useRef(null),s=Ye.useRef(null),o=Ye.useRef(null),[a,f]=Ye.useState(null),[h,d]=Ye.useState(null),[S,E]=Ye.useState(""),[j,P]=Ye.useState([]),[O,z]=Ye.useState(!1),[G,ce]=Ye.useState(""),[Z,J]=Ye.useState([]),[De,je]=Ye.useState(null),[Ne,le]=Ye.useState(null);function ve(b){J(Pe=>[...Pe,{role:"user",content:b}]),je(null),z(!0),ce("")}function Ae(){v.current.postMessage({type:"interrupt"})}Ye.useEffect(()=>{He()},[G]);function He(){if(!s.current)return;const b=s.current;b.style.height="auto";const Pe=Math.min(Math.max(b.scrollHeight,24),200);b.style.height=`${Pe}px`}return Ye.useEffect(()=>{v.current||(v.current=new Worker(new URL("/assets/worker-ZGcka8VC.js",import.meta.url),{type:"module"}),v.current.postMessage({type:"check"}));const b=Se=>{switch(Se.data.status){case"loading":f("loading"),E(Se.data.data);break;case"initiate":P(oe=>[...oe,Se.data]);break;case"progress":P(oe=>oe.map(Re=>Re.file===Se.data.file?{...Re,...Se.data}:Re));break;case"done":P(oe=>oe.filter(Re=>Re.file!==Se.data.file));break;case"ready":f("ready");break;case"start":J(oe=>[...oe,{role:"assistant",content:""}]);break;case"update":{const{output:oe,tps:Re,numTokens:Fe}=Se.data;je(Re),le(Fe),J(Ke=>{const Xe=[...Ke],Ue=Xe.at(-1);return Xe[Xe.length-1]={...Ue,content:Ue.content+oe},Xe})}break;case"complete":z(!1);break;case"error":d(Se.data.data);break}},Pe=Se=>{console.error("Worker error:",Se)};return v.current.addEventListener("message",b),v.current.addEventListener("error",Pe),()=>{v.current.removeEventListener("message",b),v.current.removeEventListener("error",Pe)}},[]),Ye.useEffect(()=>{Z.filter(b=>b.role==="user").length!==0&&Z.at(-1).role!=="assistant"&&(je(null),v.current.postMessage({type:"generate",data:Z}))},[Z,O]),Ye.useEffect(()=>{if(!o.current||!O)return;const b=o.current;b.scrollHeight-b.scrollTop-b.clientHeight{v.current.postMessage({type:"load"}),f("loading")},disabled:a!==null||h!==null,children:"Load model"})]})]}),a==="loading"&&L.jsx(L.Fragment,{children:L.jsxs("div",{className:"w-full max-w-[500px] text-left mx-auto p-4 bottom-0 mt-auto",children:[L.jsx("p",{className:"text-center mb-1",children:S}),j.map(({file:b,progress:Pe,total:Se},oe)=>L.jsx(Ph,{text:b,percentage:Pe,total:Se},oe))]})}),a==="ready"&&L.jsxs("div",{ref:o,className:"overflow-y-auto scrollbar-thin w-full flex flex-col items-center h-full",children:[L.jsx(Rh,{messages:Z}),Z.length===0&&L.jsx("div",{children:Oh.map((b,Pe)=>L.jsx("div",{className:"m-1 border dark:border-gray-600 rounded-md p-2 bg-gray-100 dark:bg-gray-700 cursor-pointer",onClick:()=>ve(b),children:b},Pe))}),L.jsx("p",{className:"text-center text-sm min-h-6 text-gray-500 dark:text-gray-300",children:De&&Z.length>0&&L.jsxs(L.Fragment,{children:[!O&&L.jsxs("span",{children:["Generated ",Ne," tokens in"," ",(Ne/De).toFixed(2)," seconds ("]}),L.jsxs(L.Fragment,{children:[L.jsx("span",{className:"font-medium text-center mr-1 text-black dark:text-white",children:De.toFixed(2)}),L.jsx("span",{className:"text-gray-500 dark:text-gray-300",children:"tokens/second"})]}),!O&&L.jsxs(L.Fragment,{children:[L.jsx("span",{className:"mr-1",children:")."}),L.jsx("span",{className:"underline cursor-pointer",onClick:()=>{v.current.postMessage({type:"reset"}),J([])},children:"Reset"})]})]})})]}),L.jsxs("div",{className:"mt-2 border dark:bg-gray-700 rounded-lg w-[600px] max-w-[80%] max-h-[200px] mx-auto relative mb-3 flex",children:[L.jsx("textarea",{ref:s,className:"scrollbar-thin w-[550px] dark:bg-gray-700 px-3 py-4 rounded-lg bg-transparent border-none outline-none text-gray-800 disabled:text-gray-400 dark:text-gray-200 placeholder-gray-500 dark:placeholder-gray-400 disabled:placeholder-gray-200 resize-none disabled:cursor-not-allowed",placeholder:"Type your message...",type:"text",rows:1,value:G,disabled:a!=="ready",title:a==="ready"?"Model is ready":"Model not loaded yet",onKeyDown:b=>{G.length>0&&!O&&b.key==="Enter"&&!b.shiftKey&&(b.preventDefault(),ve(G))},onInput:b=>ce(b.target.value)}),O?L.jsx("div",{className:"cursor-pointer",onClick:Ae,children:L.jsx(Lh,{className:"h-8 w-8 p-1 rounded-md text-gray-800 dark:text-gray-100 absolute right-3 bottom-3"})}):G.length>0?L.jsx("div",{className:"cursor-pointer",onClick:()=>ve(G),children:L.jsx(lf,{className:"h-8 w-8 p-1 bg-gray-800 dark:bg-gray-100 text-white dark:text-black rounded-md absolute right-3 bottom-3"})}):L.jsx("div",{children:L.jsx(lf,{className:"h-8 w-8 p-1 bg-gray-200 dark:bg-gray-600 text-gray-50 dark:text-gray-800 rounded-md absolute right-3 bottom-3"})})]}),L.jsx("p",{className:"text-xs text-gray-400 text-center mb-3",children:"Disclaimer: Generated content may be inaccurate or false."})]}):L.jsxs("div",{className:"fixed w-screen h-screen bg-black z-10 bg-opacity-[92%] text-white text-2xl font-semibold flex justify-center items-center text-center",children:["WebGPU is not supported",L.jsx("br",{}),"by this browser :("]})}xp.createRoot(document.getElementById("root")).render(L.jsx(hp.StrictMode,{children:L.jsx(Mh,{})})); diff --git a/assets/index-uZh0XHZq.js b/assets/index-uZh0XHZq.js deleted file mode 100644 index fdbc03343778c76c2df324a9af5ad5baf171f98c..0000000000000000000000000000000000000000 --- a/assets/index-uZh0XHZq.js +++ /dev/null @@ -1,86 +0,0 @@ -var Xd=Object.defineProperty;var Bu=e=>{throw TypeError(e)};var Zd=(e,t,n)=>t in e?Xd(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var K=(e,t,n)=>Zd(e,typeof t!="symbol"?t+"":t,n),qd=(e,t,n)=>t.has(e)||Bu("Cannot "+n);var Hu=(e,t,n)=>t.has(e)?Bu("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n);var sl=(e,t,n)=>(qd(e,t,"access private method"),n);(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const l of document.querySelectorAll('link[rel="modulepreload"]'))r(l);new MutationObserver(l=>{for(const i of l)if(i.type==="childList")for(const o of i.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&r(o)}).observe(document,{childList:!0,subtree:!0});function n(l){const i={};return l.integrity&&(i.integrity=l.integrity),l.referrerPolicy&&(i.referrerPolicy=l.referrerPolicy),l.crossOrigin==="use-credentials"?i.credentials="include":l.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(l){if(l.ep)return;l.ep=!0;const i=n(l);fetch(l.href,i)}})();function Jd(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var dc={exports:{}},mi={},pc={exports:{}},F={};/** - * @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 Xr=Symbol.for("react.element"),bd=Symbol.for("react.portal"),ep=Symbol.for("react.fragment"),tp=Symbol.for("react.strict_mode"),np=Symbol.for("react.profiler"),rp=Symbol.for("react.provider"),lp=Symbol.for("react.context"),ip=Symbol.for("react.forward_ref"),op=Symbol.for("react.suspense"),sp=Symbol.for("react.memo"),up=Symbol.for("react.lazy"),Wu=Symbol.iterator;function ap(e){return e===null||typeof e!="object"?null:(e=Wu&&e[Wu]||e["@@iterator"],typeof e=="function"?e:null)}var hc={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},mc=Object.assign,gc={};function Zn(e,t,n){this.props=e,this.context=t,this.refs=gc,this.updater=n||hc}Zn.prototype.isReactComponent={};Zn.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")};Zn.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function yc(){}yc.prototype=Zn.prototype;function gs(e,t,n){this.props=e,this.context=t,this.refs=gc,this.updater=n||hc}var ys=gs.prototype=new yc;ys.constructor=gs;mc(ys,Zn.prototype);ys.isPureReactComponent=!0;var Vu=Array.isArray,vc=Object.prototype.hasOwnProperty,vs={current:null},kc={key:!0,ref:!0,__self:!0,__source:!0};function wc(e,t,n){var r,l={},i=null,o=null;if(t!=null)for(r in t.ref!==void 0&&(o=t.ref),t.key!==void 0&&(i=""+t.key),t)vc.call(t,r)&&!kc.hasOwnProperty(r)&&(l[r]=t[r]);var s=arguments.length-2;if(s===1)l.children=n;else if(1>>1,re=C[O];if(0>>1;Ol(Y,M))Oel(Pt,Y)?(C[O]=Pt,C[Oe]=M,O=Oe):(C[O]=Y,C[ot]=M,O=ot);else if(Oel(Pt,M))C[O]=Pt,C[Oe]=M,O=Oe;else break e}}return I}function l(C,I){var M=C.sortIndex-I.sortIndex;return M!==0?M:C.id-I.id}if(typeof performance=="object"&&typeof performance.now=="function"){var i=performance;e.unstable_now=function(){return i.now()}}else{var o=Date,s=o.now();e.unstable_now=function(){return o.now()-s}}var u=[],a=[],m=1,g=null,p=3,y=!1,x=!1,w=!1,D=typeof setTimeout=="function"?setTimeout:null,d=typeof clearTimeout=="function"?clearTimeout:null,c=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function h(C){for(var I=n(a);I!==null;){if(I.callback===null)r(a);else if(I.startTime<=C)r(a),I.sortIndex=I.expirationTime,t(u,I);else break;I=n(a)}}function v(C){if(w=!1,h(C),!x)if(n(u)!==null)x=!0,At(T);else{var I=n(a);I!==null&&bn(v,I.startTime-C)}}function T(C,I){x=!1,w&&(w=!1,d(_),_=-1),y=!0;var M=p;try{for(h(I),g=n(u);g!==null&&(!(g.expirationTime>I)||C&&!U());){var O=g.callback;if(typeof O=="function"){g.callback=null,p=g.priorityLevel;var re=O(g.expirationTime<=I);I=e.unstable_now(),typeof re=="function"?g.callback=re:g===n(u)&&r(u),h(I)}else r(u);g=n(u)}if(g!==null)var J=!0;else{var ot=n(a);ot!==null&&bn(v,ot.startTime-I),J=!1}return J}finally{g=null,p=M,y=!1}}var R=!1,L=null,_=-1,$=5,z=-1;function U(){return!(e.unstable_now()-z<$)}function de(){if(L!==null){var C=e.unstable_now();z=C;var I=!0;try{I=L(!0,C)}finally{I?qe():(R=!1,L=null)}}else R=!1}var qe;if(typeof c=="function")qe=function(){c(de)};else if(typeof MessageChannel<"u"){var Rt=new MessageChannel,Lt=Rt.port2;Rt.port1.onmessage=de,qe=function(){Lt.postMessage(null)}}else qe=function(){D(de,0)};function At(C){L=C,R||(R=!0,qe())}function bn(C,I){_=D(function(){C(e.unstable_now())},I)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(C){C.callback=null},e.unstable_continueExecution=function(){x||y||(x=!0,At(T))},e.unstable_forceFrameRate=function(C){0>C||125O?(C.sortIndex=M,t(a,C),n(u)===null&&C===n(a)&&(w?(d(_),_=-1):w=!0,bn(v,M-O))):(C.sortIndex=re,t(u,C),x||y||(x=!0,At(T))),C},e.unstable_shouldYield=U,e.unstable_wrapCallback=function(C){var I=p;return function(){var M=p;p=I;try{return C.apply(this,arguments)}finally{p=M}}}})(Tc);_c.exports=Tc;var xp=_c.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 Sp=ie,Ue=xp;function k(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),wo=Object.prototype.hasOwnProperty,Ep=/^[: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]*$/,Gu={},Yu={};function _p(e){return wo.call(Yu,e)?!0:wo.call(Gu,e)?!1:Ep.test(e)?Yu[e]=!0:(Gu[e]=!0,!1)}function Tp(e,t,n,r){if(n!==null&&n.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return r?!1:n!==null?!n.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function Cp(e,t,n,r){if(t===null||typeof t>"u"||Tp(e,t,n,r))return!0;if(r)return!1;if(n!==null)switch(n.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function Re(e,t,n,r,l,i,o){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=l,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=i,this.removeEmptyString=o}var ge={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){ge[e]=new Re(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];ge[t]=new Re(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){ge[e]=new Re(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){ge[e]=new Re(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){ge[e]=new Re(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){ge[e]=new Re(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){ge[e]=new Re(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){ge[e]=new Re(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){ge[e]=new Re(e,5,!1,e.toLowerCase(),null,!1,!1)});var ws=/[\-:]([a-z])/g;function xs(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(ws,xs);ge[t]=new Re(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(ws,xs);ge[t]=new Re(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(ws,xs);ge[t]=new Re(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){ge[e]=new Re(e,1,!1,e.toLowerCase(),null,!1,!1)});ge.xlinkHref=new Re("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){ge[e]=new Re(e,1,!1,e.toLowerCase(),null,!0,!0)});function Ss(e,t,n,r){var l=ge.hasOwnProperty(t)?ge[t]:null;(l!==null?l.type!==0:r||!(2s||l[o]!==i[s]){var u=` -`+l[o].replace(" at new "," at ");return e.displayName&&u.includes("")&&(u=u.replace("",e.displayName)),u}while(1<=o&&0<=s);break}}}finally{Wi=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?yr(e):""}function Np(e){switch(e.tag){case 5:return yr(e.type);case 16:return yr("Lazy");case 13:return yr("Suspense");case 19:return yr("SuspenseList");case 0:case 2:case 15:return e=Vi(e.type,!1),e;case 11:return e=Vi(e.type.render,!1),e;case 1:return e=Vi(e.type,!0),e;default:return""}}function _o(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 Cn:return"Fragment";case Tn:return"Portal";case xo:return"Profiler";case Es:return"StrictMode";case So:return"Suspense";case Eo:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case Rc:return(e.displayName||"Context")+".Consumer";case Nc:return(e._context.displayName||"Context")+".Provider";case _s:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case Ts:return t=e.displayName||null,t!==null?t:_o(e.type)||"Memo";case It:t=e._payload,e=e._init;try{return _o(e(t))}catch{}}return null}function Rp(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 _o(t);case 8:return t===Es?"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 Yt(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function Ac(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function Lp(e){var t=Ac(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=""+e[t];if(!e.hasOwnProperty(t)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var l=n.get,i=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return l.call(this)},set:function(o){r=""+o,i.call(this,o)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(o){r=""+o},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function cl(e){e._valueTracker||(e._valueTracker=Lp(e))}function Pc(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=Ac(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function Hl(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 To(e,t){var n=t.checked;return te({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function Xu(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=Yt(t.value!=null?t.value:n),e._wrapperState={initialChecked:r,initialValue:n,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function zc(e,t){t=t.checked,t!=null&&Ss(e,"checked",t,!1)}function Co(e,t){zc(e,t);var n=Yt(t.value),r=t.type;if(n!=null)r==="number"?(n===0&&e.value===""||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if(r==="submit"||r==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?No(e,t.type,n):t.hasOwnProperty("defaultValue")&&No(e,t.type,Yt(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function Zu(e,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var r=t.type;if(!(r!=="submit"&&r!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}n=e.name,n!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,n!==""&&(e.name=n)}function No(e,t,n){(t!=="number"||Hl(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var vr=Array.isArray;function jn(e,t,n,r){if(e=e.options,t){t={};for(var l=0;l"+t.valueOf().toString()+"",t=fl.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function Ir(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var xr={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},Ap=["Webkit","ms","Moz","O"];Object.keys(xr).forEach(function(e){Ap.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),xr[t]=xr[e]})});function Dc(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||xr.hasOwnProperty(e)&&xr[e]?(""+t).trim():t+"px"}function jc(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,l=Dc(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,l):e[n]=l}}var Pp=te({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 Ao(e,t){if(t){if(Pp[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(k(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(k(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(k(61))}if(t.style!=null&&typeof t.style!="object")throw Error(k(62))}}function Po(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 zo=null;function Cs(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var Io=null,Fn=null,$n=null;function bu(e){if(e=Jr(e)){if(typeof Io!="function")throw Error(k(280));var t=e.stateNode;t&&(t=wi(t),Io(e.stateNode,e.type,t))}}function Fc(e){Fn?$n?$n.push(e):$n=[e]:Fn=e}function $c(){if(Fn){var e=Fn,t=$n;if($n=Fn=null,bu(e),t)for(e=0;e>>=0,e===0?32:31-(Hp(e)/Wp|0)|0}var dl=64,pl=4194304;function kr(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 Gl(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,l=e.suspendedLanes,i=e.pingedLanes,o=n&268435455;if(o!==0){var s=o&~l;s!==0?r=kr(s):(i&=o,i!==0&&(r=kr(i)))}else o=n&~l,o!==0?r=kr(o):i!==0&&(r=kr(i));if(r===0)return 0;if(t!==0&&t!==r&&!(t&l)&&(l=r&-r,i=t&-t,l>=i||l===16&&(i&4194240)!==0))return t;if(r&4&&(r|=n&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=r;0n;n++)t.push(e);return t}function Zr(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-rt(t),e[t]=n}function Yp(e,t){var n=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0=Er),ua=" ",aa=!1;function of(e,t){switch(e){case"keyup":return xh.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function sf(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var Nn=!1;function Eh(e,t){switch(e){case"compositionend":return sf(t);case"keypress":return t.which!==32?null:(aa=!0,ua);case"textInput":return e=t.data,e===ua&&aa?null:e;default:return null}}function _h(e,t){if(Nn)return e==="compositionend"||!Ms&&of(e,t)?(e=rf(),zl=Ps=jt=null,Nn=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=pa(n)}}function ff(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?ff(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function df(){for(var e=window,t=Hl();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=Hl(e.document)}return t}function Os(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 Ih(e){var t=df(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&ff(n.ownerDocument.documentElement,n)){if(r!==null&&Os(n)){if(t=r.start,e=r.end,e===void 0&&(e=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(e,n.value.length);else if(e=(t=n.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var l=n.textContent.length,i=Math.min(r.start,l);r=r.end===void 0?i:Math.min(r.end,l),!e.extend&&i>r&&(l=r,r=i,i=l),l=ha(n,i);var o=ha(n,r);l&&o&&(e.rangeCount!==1||e.anchorNode!==l.node||e.anchorOffset!==l.offset||e.focusNode!==o.node||e.focusOffset!==o.offset)&&(t=t.createRange(),t.setStart(l.node,l.offset),e.removeAllRanges(),i>r?(e.addRange(t),e.extend(o.node,o.offset)):(t.setEnd(o.node,o.offset),e.addRange(t)))}}for(t=[],e=n;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n=document.documentMode,Rn=null,$o=null,Tr=null,Uo=!1;function ma(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;Uo||Rn==null||Rn!==Hl(r)||(r=Rn,"selectionStart"in r&&Os(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),Tr&&$r(Tr,r)||(Tr=r,r=Xl($o,"onSelect"),0Pn||(e.current=Go[Pn],Go[Pn]=null,Pn--)}function G(e,t){Pn++,Go[Pn]=e.current,e.current=t}var Kt={},xe=Zt(Kt),ze=Zt(!1),un=Kt;function Vn(e,t){var n=e.type.contextTypes;if(!n)return Kt;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var l={},i;for(i in n)l[i]=t[i];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=l),l}function Ie(e){return e=e.childContextTypes,e!=null}function ql(){Z(ze),Z(xe)}function Sa(e,t,n){if(xe.current!==Kt)throw Error(k(168));G(xe,t),G(ze,n)}function xf(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var l in r)if(!(l in t))throw Error(k(108,Rp(e)||"Unknown",l));return te({},n,r)}function Jl(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||Kt,un=xe.current,G(xe,e),G(ze,ze.current),!0}function Ea(e,t,n){var r=e.stateNode;if(!r)throw Error(k(169));n?(e=xf(e,t,un),r.__reactInternalMemoizedMergedChildContext=e,Z(ze),Z(xe),G(xe,e)):Z(ze),G(ze,n)}var kt=null,xi=!1,lo=!1;function Sf(e){kt===null?kt=[e]:kt.push(e)}function Qh(e){xi=!0,Sf(e)}function qt(){if(!lo&&kt!==null){lo=!0;var e=0,t=W;try{var n=kt;for(W=1;e>=o,l-=o,wt=1<<32-rt(t)+l|n<_?($=L,L=null):$=L.sibling;var z=p(d,L,h[_],v);if(z===null){L===null&&(L=$);break}e&&L&&z.alternate===null&&t(d,L),c=i(z,c,_),R===null?T=z:R.sibling=z,R=z,L=$}if(_===h.length)return n(d,L),q&&bt(d,_),T;if(L===null){for(;__?($=L,L=null):$=L.sibling;var U=p(d,L,z.value,v);if(U===null){L===null&&(L=$);break}e&&L&&U.alternate===null&&t(d,L),c=i(U,c,_),R===null?T=U:R.sibling=U,R=U,L=$}if(z.done)return n(d,L),q&&bt(d,_),T;if(L===null){for(;!z.done;_++,z=h.next())z=g(d,z.value,v),z!==null&&(c=i(z,c,_),R===null?T=z:R.sibling=z,R=z);return q&&bt(d,_),T}for(L=r(d,L);!z.done;_++,z=h.next())z=y(L,d,_,z.value,v),z!==null&&(e&&z.alternate!==null&&L.delete(z.key===null?_:z.key),c=i(z,c,_),R===null?T=z:R.sibling=z,R=z);return e&&L.forEach(function(de){return t(d,de)}),q&&bt(d,_),T}function D(d,c,h,v){if(typeof h=="object"&&h!==null&&h.type===Cn&&h.key===null&&(h=h.props.children),typeof h=="object"&&h!==null){switch(h.$$typeof){case al:e:{for(var T=h.key,R=c;R!==null;){if(R.key===T){if(T=h.type,T===Cn){if(R.tag===7){n(d,R.sibling),c=l(R,h.props.children),c.return=d,d=c;break e}}else if(R.elementType===T||typeof T=="object"&&T!==null&&T.$$typeof===It&&Ca(T)===R.type){n(d,R.sibling),c=l(R,h.props),c.ref=ur(d,R,h),c.return=d,d=c;break e}n(d,R);break}else t(d,R);R=R.sibling}h.type===Cn?(c=sn(h.props.children,d.mode,v,h.key),c.return=d,d=c):(v=Ul(h.type,h.key,h.props,null,d.mode,v),v.ref=ur(d,c,h),v.return=d,d=v)}return o(d);case Tn:e:{for(R=h.key;c!==null;){if(c.key===R)if(c.tag===4&&c.stateNode.containerInfo===h.containerInfo&&c.stateNode.implementation===h.implementation){n(d,c.sibling),c=l(c,h.children||[]),c.return=d,d=c;break e}else{n(d,c);break}else t(d,c);c=c.sibling}c=po(h,d.mode,v),c.return=d,d=c}return o(d);case It:return R=h._init,D(d,c,R(h._payload),v)}if(vr(h))return x(d,c,h,v);if(rr(h))return w(d,c,h,v);wl(d,h)}return typeof h=="string"&&h!==""||typeof h=="number"?(h=""+h,c!==null&&c.tag===6?(n(d,c.sibling),c=l(c,h),c.return=d,d=c):(n(d,c),c=fo(h,d.mode,v),c.return=d,d=c),o(d)):n(d,c)}return D}var Gn=Cf(!0),Nf=Cf(!1),ti=Zt(null),ni=null,Mn=null,$s=null;function Us(){$s=Mn=ni=null}function Bs(e){var t=ti.current;Z(ti),e._currentValue=t}function Xo(e,t,n){for(;e!==null;){var r=e.alternate;if((e.childLanes&t)!==t?(e.childLanes|=t,r!==null&&(r.childLanes|=t)):r!==null&&(r.childLanes&t)!==t&&(r.childLanes|=t),e===n)break;e=e.return}}function Bn(e,t){ni=e,$s=Mn=null,e=e.dependencies,e!==null&&e.firstContext!==null&&(e.lanes&t&&(Pe=!0),e.firstContext=null)}function Ke(e){var t=e._currentValue;if($s!==e)if(e={context:e,memoizedValue:t,next:null},Mn===null){if(ni===null)throw Error(k(308));Mn=e,ni.dependencies={lanes:0,firstContext:e}}else Mn=Mn.next=e;return t}var rn=null;function Hs(e){rn===null?rn=[e]:rn.push(e)}function Rf(e,t,n,r){var l=t.interleaved;return l===null?(n.next=n,Hs(t)):(n.next=l.next,l.next=n),t.interleaved=n,Tt(e,r)}function Tt(e,t){e.lanes|=t;var n=e.alternate;for(n!==null&&(n.lanes|=t),n=e,e=e.return;e!==null;)e.childLanes|=t,n=e.alternate,n!==null&&(n.childLanes|=t),n=e,e=e.return;return n.tag===3?n.stateNode:null}var Mt=!1;function Ws(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function Lf(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 St(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function Wt(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,B&2){var l=r.pending;return l===null?t.next=t:(t.next=l.next,l.next=t),r.pending=t,Tt(e,n)}return l=r.interleaved,l===null?(t.next=t,Hs(r)):(t.next=l.next,l.next=t),r.interleaved=t,Tt(e,n)}function Ml(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,(n&4194240)!==0)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,Rs(e,n)}}function Na(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var l=null,i=null;if(n=n.firstBaseUpdate,n!==null){do{var o={eventTime:n.eventTime,lane:n.lane,tag:n.tag,payload:n.payload,callback:n.callback,next:null};i===null?l=i=o:i=i.next=o,n=n.next}while(n!==null);i===null?l=i=t:i=i.next=t}else l=i=t;n={baseState:r.baseState,firstBaseUpdate:l,lastBaseUpdate:i,shared:r.shared,effects:r.effects},e.updateQueue=n;return}e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}function ri(e,t,n,r){var l=e.updateQueue;Mt=!1;var i=l.firstBaseUpdate,o=l.lastBaseUpdate,s=l.shared.pending;if(s!==null){l.shared.pending=null;var u=s,a=u.next;u.next=null,o===null?i=a:o.next=a,o=u;var m=e.alternate;m!==null&&(m=m.updateQueue,s=m.lastBaseUpdate,s!==o&&(s===null?m.firstBaseUpdate=a:s.next=a,m.lastBaseUpdate=u))}if(i!==null){var g=l.baseState;o=0,m=a=u=null,s=i;do{var p=s.lane,y=s.eventTime;if((r&p)===p){m!==null&&(m=m.next={eventTime:y,lane:0,tag:s.tag,payload:s.payload,callback:s.callback,next:null});e:{var x=e,w=s;switch(p=t,y=n,w.tag){case 1:if(x=w.payload,typeof x=="function"){g=x.call(y,g,p);break e}g=x;break e;case 3:x.flags=x.flags&-65537|128;case 0:if(x=w.payload,p=typeof x=="function"?x.call(y,g,p):x,p==null)break e;g=te({},g,p);break e;case 2:Mt=!0}}s.callback!==null&&s.lane!==0&&(e.flags|=64,p=l.effects,p===null?l.effects=[s]:p.push(s))}else y={eventTime:y,lane:p,tag:s.tag,payload:s.payload,callback:s.callback,next:null},m===null?(a=m=y,u=g):m=m.next=y,o|=p;if(s=s.next,s===null){if(s=l.shared.pending,s===null)break;p=s,s=p.next,p.next=null,l.lastBaseUpdate=p,l.shared.pending=null}}while(!0);if(m===null&&(u=g),l.baseState=u,l.firstBaseUpdate=a,l.lastBaseUpdate=m,t=l.shared.interleaved,t!==null){l=t;do o|=l.lane,l=l.next;while(l!==t)}else i===null&&(l.shared.lanes=0);fn|=o,e.lanes=o,e.memoizedState=g}}function Ra(e,t,n){if(e=t.effects,t.effects=null,e!==null)for(t=0;tn?n:4,e(!0);var r=oo.transition;oo.transition={};try{e(!1),t()}finally{W=n,oo.transition=r}}function Gf(){return Xe().memoizedState}function Xh(e,t,n){var r=Qt(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},Yf(e))Kf(t,n);else if(n=Rf(e,t,n,r),n!==null){var l=Te();lt(n,e,r,l),Xf(n,t,r)}}function Zh(e,t,n){var r=Qt(e),l={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(Yf(e))Kf(t,l);else{var i=e.alternate;if(e.lanes===0&&(i===null||i.lanes===0)&&(i=t.lastRenderedReducer,i!==null))try{var o=t.lastRenderedState,s=i(o,n);if(l.hasEagerState=!0,l.eagerState=s,it(s,o)){var u=t.interleaved;u===null?(l.next=l,Hs(t)):(l.next=u.next,u.next=l),t.interleaved=l;return}}catch{}finally{}n=Rf(e,t,l,r),n!==null&&(l=Te(),lt(n,e,r,l),Xf(n,t,r))}}function Yf(e){var t=e.alternate;return e===ee||t!==null&&t===ee}function Kf(e,t){Cr=ii=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function Xf(e,t,n){if(n&4194240){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,Rs(e,n)}}var oi={readContext:Ke,useCallback:ve,useContext:ve,useEffect:ve,useImperativeHandle:ve,useInsertionEffect:ve,useLayoutEffect:ve,useMemo:ve,useReducer:ve,useRef:ve,useState:ve,useDebugValue:ve,useDeferredValue:ve,useTransition:ve,useMutableSource:ve,useSyncExternalStore:ve,useId:ve,unstable_isNewReconciler:!1},qh={readContext:Ke,useCallback:function(e,t){return ct().memoizedState=[e,t===void 0?null:t],e},useContext:Ke,useEffect:Aa,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,Dl(4194308,4,Bf.bind(null,t,e),n)},useLayoutEffect:function(e,t){return Dl(4194308,4,e,t)},useInsertionEffect:function(e,t){return Dl(4,2,e,t)},useMemo:function(e,t){var n=ct();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=ct();return t=n!==void 0?n(t):t,r.memoizedState=r.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},r.queue=e,e=e.dispatch=Xh.bind(null,ee,e),[r.memoizedState,e]},useRef:function(e){var t=ct();return e={current:e},t.memoizedState=e},useState:La,useDebugValue:qs,useDeferredValue:function(e){return ct().memoizedState=e},useTransition:function(){var e=La(!1),t=e[0];return e=Kh.bind(null,e[1]),ct().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=ee,l=ct();if(q){if(n===void 0)throw Error(k(407));n=n()}else{if(n=t(),fe===null)throw Error(k(349));cn&30||If(r,t,n)}l.memoizedState=n;var i={value:n,getSnapshot:t};return l.queue=i,Aa(Of.bind(null,r,i,e),[e]),r.flags|=2048,Yr(9,Mf.bind(null,r,i,n,t),void 0,null),n},useId:function(){var e=ct(),t=fe.identifierPrefix;if(q){var n=xt,r=wt;n=(r&~(1<<32-rt(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=Qr++,0<\/script>",e=e.removeChild(e.firstChild)):typeof r.is=="string"?e=o.createElement(n,{is:r.is}):(e=o.createElement(n),n==="select"&&(o=e,r.multiple?o.multiple=!0:r.size&&(o.size=r.size))):e=o.createElementNS(e,n),e[ft]=t,e[Hr]=r,id(e,t,!1,!1),t.stateNode=e;e:{switch(o=Po(n,r),n){case"dialog":X("cancel",e),X("close",e),l=r;break;case"iframe":case"object":case"embed":X("load",e),l=r;break;case"video":case"audio":for(l=0;lXn&&(t.flags|=128,r=!0,ar(i,!1),t.lanes=4194304)}else{if(!r)if(e=li(o),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),ar(i,!0),i.tail===null&&i.tailMode==="hidden"&&!o.alternate&&!q)return ke(t),null}else 2*le()-i.renderingStartTime>Xn&&n!==1073741824&&(t.flags|=128,r=!0,ar(i,!1),t.lanes=4194304);i.isBackwards?(o.sibling=t.child,t.child=o):(n=i.last,n!==null?n.sibling=o:t.child=o,i.last=o)}return i.tail!==null?(t=i.tail,i.rendering=t,i.tail=t.sibling,i.renderingStartTime=le(),t.sibling=null,n=b.current,G(b,r?n&1|2:n&1),t):(ke(t),null);case 22:case 23:return ru(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?De&1073741824&&(ke(t),t.subtreeFlags&6&&(t.flags|=8192)):ke(t),null;case 24:return null;case 25:return null}throw Error(k(156,t.tag))}function im(e,t){switch(js(t),t.tag){case 1:return Ie(t.type)&&ql(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return Yn(),Z(ze),Z(xe),Gs(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return Qs(t),null;case 13:if(Z(b),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(k(340));Qn()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return Z(b),null;case 4:return Yn(),null;case 10:return Bs(t.type._context),null;case 22:case 23:return ru(),null;case 24:return null;default:return null}}var Sl=!1,we=!1,om=typeof WeakSet=="function"?WeakSet:Set,N=null;function On(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){ne(e,t,r)}else n.current=null}function ls(e,t,n){try{n()}catch(r){ne(e,t,r)}}var Ba=!1;function sm(e,t){if(Bo=Yl,e=df(),Os(e)){if("selectionStart"in e)var n={start:e.selectionStart,end:e.selectionEnd};else e:{n=(n=e.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var l=r.anchorOffset,i=r.focusNode;r=r.focusOffset;try{n.nodeType,i.nodeType}catch{n=null;break e}var o=0,s=-1,u=-1,a=0,m=0,g=e,p=null;t:for(;;){for(var y;g!==n||l!==0&&g.nodeType!==3||(s=o+l),g!==i||r!==0&&g.nodeType!==3||(u=o+r),g.nodeType===3&&(o+=g.nodeValue.length),(y=g.firstChild)!==null;)p=g,g=y;for(;;){if(g===e)break t;if(p===n&&++a===l&&(s=o),p===i&&++m===r&&(u=o),(y=g.nextSibling)!==null)break;g=p,p=g.parentNode}g=y}n=s===-1||u===-1?null:{start:s,end:u}}else n=null}n=n||{start:0,end:0}}else n=null;for(Ho={focusedElem:e,selectionRange:n},Yl=!1,N=t;N!==null;)if(t=N,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,N=e;else for(;N!==null;){t=N;try{var x=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(x!==null){var w=x.memoizedProps,D=x.memoizedState,d=t.stateNode,c=d.getSnapshotBeforeUpdate(t.elementType===t.type?w:et(t.type,w),D);d.__reactInternalSnapshotBeforeUpdate=c}break;case 3:var h=t.stateNode.containerInfo;h.nodeType===1?h.textContent="":h.nodeType===9&&h.documentElement&&h.removeChild(h.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(k(163))}}catch(v){ne(t,t.return,v)}if(e=t.sibling,e!==null){e.return=t.return,N=e;break}N=t.return}return x=Ba,Ba=!1,x}function Nr(e,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var l=r=r.next;do{if((l.tag&e)===e){var i=l.destroy;l.destroy=void 0,i!==void 0&&ls(t,n,i)}l=l.next}while(l!==r)}}function _i(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var n=t=t.next;do{if((n.tag&e)===e){var r=n.create;n.destroy=r()}n=n.next}while(n!==t)}}function is(e){var t=e.ref;if(t!==null){var n=e.stateNode;switch(e.tag){case 5:e=n;break;default:e=n}typeof t=="function"?t(e):t.current=e}}function ud(e){var t=e.alternate;t!==null&&(e.alternate=null,ud(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[ft],delete t[Hr],delete t[Qo],delete t[Wh],delete t[Vh])),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 ad(e){return e.tag===5||e.tag===3||e.tag===4}function Ha(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||ad(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 os(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(e,t):n.insertBefore(e,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(e,n)):(t=n,t.appendChild(e)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=Zl));else if(r!==4&&(e=e.child,e!==null))for(os(e,t,n),e=e.sibling;e!==null;)os(e,t,n),e=e.sibling}function ss(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(ss(e,t,n),e=e.sibling;e!==null;)ss(e,t,n),e=e.sibling}var he=null,tt=!1;function zt(e,t,n){for(n=n.child;n!==null;)cd(e,t,n),n=n.sibling}function cd(e,t,n){if(ht&&typeof ht.onCommitFiberUnmount=="function")try{ht.onCommitFiberUnmount(gi,n)}catch{}switch(n.tag){case 5:we||On(n,t);case 6:var r=he,l=tt;he=null,zt(e,t,n),he=r,tt=l,he!==null&&(tt?(e=he,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):he.removeChild(n.stateNode));break;case 18:he!==null&&(tt?(e=he,n=n.stateNode,e.nodeType===8?ro(e.parentNode,n):e.nodeType===1&&ro(e,n),jr(e)):ro(he,n.stateNode));break;case 4:r=he,l=tt,he=n.stateNode.containerInfo,tt=!0,zt(e,t,n),he=r,tt=l;break;case 0:case 11:case 14:case 15:if(!we&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){l=r=r.next;do{var i=l,o=i.destroy;i=i.tag,o!==void 0&&(i&2||i&4)&&ls(n,t,o),l=l.next}while(l!==r)}zt(e,t,n);break;case 1:if(!we&&(On(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(s){ne(n,t,s)}zt(e,t,n);break;case 21:zt(e,t,n);break;case 22:n.mode&1?(we=(r=we)||n.memoizedState!==null,zt(e,t,n),we=r):zt(e,t,n);break;default:zt(e,t,n)}}function Wa(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new om),t.forEach(function(r){var l=gm.bind(null,e,r);n.has(r)||(n.add(r),r.then(l,l))})}}function Je(e,t){var n=t.deletions;if(n!==null)for(var r=0;rl&&(l=o),r&=~i}if(r=l,r=le()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*am(r/1960))-r,10e?16:e,Ft===null)var r=!1;else{if(e=Ft,Ft=null,ai=0,B&6)throw Error(k(331));var l=B;for(B|=4,N=e.current;N!==null;){var i=N,o=i.child;if(N.flags&16){var s=i.deletions;if(s!==null){for(var u=0;ule()-tu?on(e,0):eu|=n),Me(e,t)}function vd(e,t){t===0&&(e.mode&1?(t=pl,pl<<=1,!(pl&130023424)&&(pl=4194304)):t=1);var n=Te();e=Tt(e,t),e!==null&&(Zr(e,t,n),Me(e,n))}function mm(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),vd(e,n)}function gm(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,l=e.memoizedState;l!==null&&(n=l.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(k(314))}r!==null&&r.delete(t),vd(e,n)}var kd;kd=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||ze.current)Pe=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return Pe=!1,rm(e,t,n);Pe=!!(e.flags&131072)}else Pe=!1,q&&t.flags&1048576&&Ef(t,ei,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;jl(e,t),e=t.pendingProps;var l=Vn(t,xe.current);Bn(t,n),l=Ks(null,t,r,e,l,n);var i=Xs();return t.flags|=1,typeof l=="object"&&l!==null&&typeof l.render=="function"&&l.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,Ie(r)?(i=!0,Jl(t)):i=!1,t.memoizedState=l.state!==null&&l.state!==void 0?l.state:null,Ws(t),l.updater=Ei,t.stateNode=l,l._reactInternals=t,qo(t,r,e,n),t=es(null,t,r,!0,i,n)):(t.tag=0,q&&i&&Ds(t),_e(null,t,l,n),t=t.child),t;case 16:r=t.elementType;e:{switch(jl(e,t),e=t.pendingProps,l=r._init,r=l(r._payload),t.type=r,l=t.tag=vm(r),e=et(r,e),l){case 0:t=bo(null,t,r,e,n);break e;case 1:t=Fa(null,t,r,e,n);break e;case 11:t=Da(null,t,r,e,n);break e;case 14:t=ja(null,t,r,et(r.type,e),n);break e}throw Error(k(306,r,""))}return t;case 0:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:et(r,l),bo(e,t,r,l,n);case 1:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:et(r,l),Fa(e,t,r,l,n);case 3:e:{if(nd(t),e===null)throw Error(k(387));r=t.pendingProps,i=t.memoizedState,l=i.element,Lf(e,t),ri(t,r,null,n);var o=t.memoizedState;if(r=o.element,i.isDehydrated)if(i={element:r,isDehydrated:!1,cache:o.cache,pendingSuspenseBoundaries:o.pendingSuspenseBoundaries,transitions:o.transitions},t.updateQueue.baseState=i,t.memoizedState=i,t.flags&256){l=Kn(Error(k(423)),t),t=$a(e,t,r,n,l);break e}else if(r!==l){l=Kn(Error(k(424)),t),t=$a(e,t,r,n,l);break e}else for(Fe=Ht(t.stateNode.containerInfo.firstChild),$e=t,q=!0,nt=null,n=Nf(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(Qn(),r===l){t=Ct(e,t,n);break e}_e(e,t,r,n)}t=t.child}return t;case 5:return Af(t),e===null&&Ko(t),r=t.type,l=t.pendingProps,i=e!==null?e.memoizedProps:null,o=l.children,Wo(r,l)?o=null:i!==null&&Wo(r,i)&&(t.flags|=32),td(e,t),_e(e,t,o,n),t.child;case 6:return e===null&&Ko(t),null;case 13:return rd(e,t,n);case 4:return Vs(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=Gn(t,null,r,n):_e(e,t,r,n),t.child;case 11:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:et(r,l),Da(e,t,r,l,n);case 7:return _e(e,t,t.pendingProps,n),t.child;case 8:return _e(e,t,t.pendingProps.children,n),t.child;case 12:return _e(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,l=t.pendingProps,i=t.memoizedProps,o=l.value,G(ti,r._currentValue),r._currentValue=o,i!==null)if(it(i.value,o)){if(i.children===l.children&&!ze.current){t=Ct(e,t,n);break e}}else for(i=t.child,i!==null&&(i.return=t);i!==null;){var s=i.dependencies;if(s!==null){o=i.child;for(var u=s.firstContext;u!==null;){if(u.context===r){if(i.tag===1){u=St(-1,n&-n),u.tag=2;var a=i.updateQueue;if(a!==null){a=a.shared;var m=a.pending;m===null?u.next=u:(u.next=m.next,m.next=u),a.pending=u}}i.lanes|=n,u=i.alternate,u!==null&&(u.lanes|=n),Xo(i.return,n,t),s.lanes|=n;break}u=u.next}}else if(i.tag===10)o=i.type===t.type?null:i.child;else if(i.tag===18){if(o=i.return,o===null)throw Error(k(341));o.lanes|=n,s=o.alternate,s!==null&&(s.lanes|=n),Xo(o,n,t),o=i.sibling}else o=i.child;if(o!==null)o.return=i;else for(o=i;o!==null;){if(o===t){o=null;break}if(i=o.sibling,i!==null){i.return=o.return,o=i;break}o=o.return}i=o}_e(e,t,l.children,n),t=t.child}return t;case 9:return l=t.type,r=t.pendingProps.children,Bn(t,n),l=Ke(l),r=r(l),t.flags|=1,_e(e,t,r,n),t.child;case 14:return r=t.type,l=et(r,t.pendingProps),l=et(r.type,l),ja(e,t,r,l,n);case 15:return bf(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:et(r,l),jl(e,t),t.tag=1,Ie(r)?(e=!0,Jl(t)):e=!1,Bn(t,n),Zf(t,r,l),qo(t,r,l,n),es(null,t,r,!0,e,n);case 19:return ld(e,t,n);case 22:return ed(e,t,n)}throw Error(k(156,t.tag))};function wd(e,t){return Gc(e,t)}function ym(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Ge(e,t,n,r){return new ym(e,t,n,r)}function iu(e){return e=e.prototype,!(!e||!e.isReactComponent)}function vm(e){if(typeof e=="function")return iu(e)?1:0;if(e!=null){if(e=e.$$typeof,e===_s)return 11;if(e===Ts)return 14}return 2}function Gt(e,t){var n=e.alternate;return n===null?(n=Ge(e.tag,t,e.key,e.mode),n.elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=e.flags&14680064,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function Ul(e,t,n,r,l,i){var o=2;if(r=e,typeof e=="function")iu(e)&&(o=1);else if(typeof e=="string")o=5;else e:switch(e){case Cn:return sn(n.children,l,i,t);case Es:o=8,l|=8;break;case xo:return e=Ge(12,n,t,l|2),e.elementType=xo,e.lanes=i,e;case So:return e=Ge(13,n,t,l),e.elementType=So,e.lanes=i,e;case Eo:return e=Ge(19,n,t,l),e.elementType=Eo,e.lanes=i,e;case Lc:return Ci(n,l,i,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case Nc:o=10;break e;case Rc:o=9;break e;case _s:o=11;break e;case Ts:o=14;break e;case It:o=16,r=null;break e}throw Error(k(130,e==null?e:typeof e,""))}return t=Ge(o,n,t,l),t.elementType=e,t.type=r,t.lanes=i,t}function sn(e,t,n,r){return e=Ge(7,e,r,t),e.lanes=n,e}function Ci(e,t,n,r){return e=Ge(22,e,r,t),e.elementType=Lc,e.lanes=n,e.stateNode={isHidden:!1},e}function fo(e,t,n){return e=Ge(6,e,null,t),e.lanes=n,e}function po(e,t,n){return t=Ge(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function km(e,t,n,r,l){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=Gi(0),this.expirationTimes=Gi(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Gi(0),this.identifierPrefix=r,this.onRecoverableError=l,this.mutableSourceEagerHydrationData=null}function ou(e,t,n,r,l,i,o,s,u){return e=new km(e,t,n,s,u),t===1?(t=1,i===!0&&(t|=8)):t=0,i=Ge(3,null,null,t),e.current=i,i.stateNode=e,i.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},Ws(i),e}function wm(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(_d)}catch(e){console.error(e)}}_d(),Ec.exports=He;var Tm=Ec.exports,qa=Tm;ko.createRoot=qa.createRoot,ko.hydrateRoot=qa.hydrateRoot;function cu(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}let yn=cu();function Td(e){yn=e}const Cd=/[&<>"']/,Cm=new RegExp(Cd.source,"g"),Nd=/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,Nm=new RegExp(Nd.source,"g"),Rm={"&":"&","<":"<",">":">",'"':""","'":"'"},Ja=e=>Rm[e];function je(e,t){if(t){if(Cd.test(e))return e.replace(Cm,Ja)}else if(Nd.test(e))return e.replace(Nm,Ja);return e}const Lm=/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig;function Am(e){return e.replace(Lm,(t,n)=>(n=n.toLowerCase(),n==="colon"?":":n.charAt(0)==="#"?n.charAt(1)==="x"?String.fromCharCode(parseInt(n.substring(2),16)):String.fromCharCode(+n.substring(1)):""))}const Pm=/(^|[^\[])\^/g;function V(e,t){let n=typeof e=="string"?e:e.source;t=t||"";const r={replace:(l,i)=>{let o=typeof i=="string"?i:i.source;return o=o.replace(Pm,"$1"),n=n.replace(l,o),r},getRegex:()=>new RegExp(n,t)};return r}function ba(e){try{e=encodeURI(e).replace(/%25/g,"%")}catch{return null}return e}const Ar={exec:()=>null};function ec(e,t){const n=e.replace(/\|/g,(i,o,s)=>{let u=!1,a=o;for(;--a>=0&&s[a]==="\\";)u=!u;return u?"|":" |"}),r=n.split(/ \|/);let l=0;if(r[0].trim()||r.shift(),r.length>0&&!r[r.length-1].trim()&&r.pop(),t)if(r.length>t)r.splice(t);else for(;r.length{const i=l.match(/^\s+/);if(i===null)return l;const[o]=i;return o.length>=r.length?l.slice(r.length):l}).join(` -`)}class di{constructor(t){K(this,"options");K(this,"rules");K(this,"lexer");this.options=t||yn}space(t){const n=this.rules.block.newline.exec(t);if(n&&n[0].length>0)return{type:"space",raw:n[0]}}code(t){const n=this.rules.block.code.exec(t);if(n){const r=n[0].replace(/^ {1,4}/gm,"");return{type:"code",raw:n[0],codeBlockStyle:"indented",text:this.options.pedantic?r:Tl(r,` -`)}}}fences(t){const n=this.rules.block.fences.exec(t);if(n){const r=n[0],l=Im(r,n[3]||"");return{type:"code",raw:r,lang:n[2]?n[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):n[2],text:l}}}heading(t){const n=this.rules.block.heading.exec(t);if(n){let r=n[2].trim();if(/#$/.test(r)){const l=Tl(r,"#");(this.options.pedantic||!l||/ $/.test(l))&&(r=l.trim())}return{type:"heading",raw:n[0],depth:n[1].length,text:r,tokens:this.lexer.inline(r)}}}hr(t){const n=this.rules.block.hr.exec(t);if(n)return{type:"hr",raw:n[0]}}blockquote(t){const n=this.rules.block.blockquote.exec(t);if(n){let r=n[0].replace(/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,` - $1`);r=Tl(r.replace(/^ *>[ \t]?/gm,""),` -`);const l=this.lexer.state.top;this.lexer.state.top=!0;const i=this.lexer.blockTokens(r);return this.lexer.state.top=l,{type:"blockquote",raw:n[0],tokens:i,text:r}}}list(t){let n=this.rules.block.list.exec(t);if(n){let r=n[1].trim();const l=r.length>1,i={type:"list",raw:"",ordered:l,start:l?+r.slice(0,-1):"",loose:!1,items:[]};r=l?`\\d{1,9}\\${r.slice(-1)}`:`\\${r}`,this.options.pedantic&&(r=l?r:"[*+-]");const o=new RegExp(`^( {0,3}${r})((?:[ ][^\\n]*)?(?:\\n|$))`);let s="",u="",a=!1;for(;t;){let m=!1;if(!(n=o.exec(t))||this.rules.block.hr.test(t))break;s=n[0],t=t.substring(s.length);let g=n[2].split(` -`,1)[0].replace(/^\t+/,d=>" ".repeat(3*d.length)),p=t.split(` -`,1)[0],y=0;this.options.pedantic?(y=2,u=g.trimStart()):(y=n[2].search(/[^ ]/),y=y>4?1:y,u=g.slice(y),y+=n[1].length);let x=!1;if(!g&&/^ *$/.test(p)&&(s+=p+` -`,t=t.substring(p.length+1),m=!0),!m){const d=new RegExp(`^ {0,${Math.min(3,y-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),c=new RegExp(`^ {0,${Math.min(3,y-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),h=new RegExp(`^ {0,${Math.min(3,y-1)}}(?:\`\`\`|~~~)`),v=new RegExp(`^ {0,${Math.min(3,y-1)}}#`);for(;t;){const T=t.split(` -`,1)[0];if(p=T,this.options.pedantic&&(p=p.replace(/^ {1,4}(?=( {4})*[^ ])/g," ")),h.test(p)||v.test(p)||d.test(p)||c.test(t))break;if(p.search(/[^ ]/)>=y||!p.trim())u+=` -`+p.slice(y);else{if(x||g.search(/[^ ]/)>=4||h.test(g)||v.test(g)||c.test(g))break;u+=` -`+p}!x&&!p.trim()&&(x=!0),s+=T+` -`,t=t.substring(T.length+1),g=p.slice(y)}}i.loose||(a?i.loose=!0:/\n *\n *$/.test(s)&&(a=!0));let w=null,D;this.options.gfm&&(w=/^\[[ xX]\] /.exec(u),w&&(D=w[0]!=="[ ] ",u=u.replace(/^\[[ xX]\] +/,""))),i.items.push({type:"list_item",raw:s,task:!!w,checked:D,loose:!1,text:u,tokens:[]}),i.raw+=s}i.items[i.items.length-1].raw=s.trimEnd(),i.items[i.items.length-1].text=u.trimEnd(),i.raw=i.raw.trimEnd();for(let m=0;my.type==="space"),p=g.length>0&&g.some(y=>/\n.*\n/.test(y.raw));i.loose=p}if(i.loose)for(let m=0;m$/,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",i=n[3]?n[3].substring(1,n[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):n[3];return{type:"def",tag:r,raw:n[0],href:l,title:i}}}table(t){const n=this.rules.block.table.exec(t);if(!n||!/[:|]/.test(n[2]))return;const r=ec(n[1]),l=n[2].replace(/^\||\| *$/g,"").split("|"),i=n[3]&&n[3].trim()?n[3].replace(/\n[ \t]*$/,"").split(` -`):[],o={type:"table",raw:n[0],header:[],align:[],rows:[]};if(r.length===l.length){for(const s of l)/^ *-+: *$/.test(s)?o.align.push("right"):/^ *:-+: *$/.test(s)?o.align.push("center"):/^ *:-+ *$/.test(s)?o.align.push("left"):o.align.push(null);for(const s of r)o.header.push({text:s,tokens:this.lexer.inline(s)});for(const s of i)o.rows.push(ec(s,o.header.length).map(u=>({text:u,tokens:this.lexer.inline(u)})));return o}}lheading(t){const n=this.rules.block.lheading.exec(t);if(n)return{type:"heading",raw:n[0],depth:n[2].charAt(0)==="="?1:2,text:n[1],tokens:this.lexer.inline(n[1])}}paragraph(t){const n=this.rules.block.paragraph.exec(t);if(n){const r=n[1].charAt(n[1].length-1)===` -`?n[1].slice(0,-1):n[1];return{type:"paragraph",raw:n[0],text:r,tokens:this.lexer.inline(r)}}}text(t){const n=this.rules.block.text.exec(t);if(n)return{type:"text",raw:n[0],text:n[0],tokens:this.lexer.inline(n[0])}}escape(t){const n=this.rules.inline.escape.exec(t);if(n)return{type:"escape",raw:n[0],text:je(n[1])}}tag(t){const n=this.rules.inline.tag.exec(t);if(n)return!this.lexer.state.inLink&&/^
    /i.test(n[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&/^<(pre|code|kbd|script)(\s|>)/i.test(n[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&/^<\/(pre|code|kbd|script)(\s|>)/i.test(n[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:n[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:n[0]}}link(t){const n=this.rules.inline.link.exec(t);if(n){const r=n[2].trim();if(!this.options.pedantic&&/^$/.test(r))return;const o=Tl(r.slice(0,-1),"\\");if((r.length-o.length)%2===0)return}else{const o=zm(n[2],"()");if(o>-1){const u=(n[0].indexOf("!")===0?5:4)+n[1].length+o;n[2]=n[2].substring(0,o),n[0]=n[0].substring(0,u).trim(),n[3]=""}}let l=n[2],i="";if(this.options.pedantic){const o=/^([^'"]*[^\s])\s+(['"])(.*)\2/.exec(l);o&&(l=o[1],i=o[3])}else i=n[3]?n[3].slice(1,-1):"";return l=l.trim(),/^$/.test(r)?l=l.slice(1):l=l.slice(1,-1)),tc(n,{href:l&&l.replace(this.rules.inline.anyPunctuation,"$1"),title:i&&i.replace(this.rules.inline.anyPunctuation,"$1")},n[0],this.lexer)}}reflink(t,n){let r;if((r=this.rules.inline.reflink.exec(t))||(r=this.rules.inline.nolink.exec(t))){const l=(r[2]||r[1]).replace(/\s+/g," "),i=n[l.toLowerCase()];if(!i){const o=r[0].charAt(0);return{type:"text",raw:o,text:o}}return tc(r,i,r[0],this.lexer)}}emStrong(t,n,r=""){let l=this.rules.inline.emStrongLDelim.exec(t);if(!l||l[3]&&r.match(/[\p{L}\p{N}]/u))return;if(!(l[1]||l[2]||"")||!r||this.rules.inline.punctuation.exec(r)){const o=[...l[0]].length-1;let s,u,a=o,m=0;const g=l[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(g.lastIndex=0,n=n.slice(-1*t.length+o);(l=g.exec(n))!=null;){if(s=l[1]||l[2]||l[3]||l[4]||l[5]||l[6],!s)continue;if(u=[...s].length,l[3]||l[4]){a+=u;continue}else if((l[5]||l[6])&&o%3&&!((o+u)%3)){m+=u;continue}if(a-=u,a>0)continue;u=Math.min(u,u+a+m);const p=[...l[0]][0].length,y=t.slice(0,o+l.index+p+u);if(Math.min(o,u)%2){const w=y.slice(1,-1);return{type:"em",raw:y,text:w,tokens:this.lexer.inlineTokens(w)}}const x=y.slice(2,-2);return{type:"strong",raw:y,text:x,tokens:this.lexer.inlineTokens(x)}}}}codespan(t){const n=this.rules.inline.code.exec(t);if(n){let r=n[2].replace(/\n/g," ");const l=/[^ ]/.test(r),i=/^ /.test(r)&&/ $/.test(r);return l&&i&&(r=r.substring(1,r.length-1)),r=je(r,!0),{type:"codespan",raw:n[0],text:r}}}br(t){const n=this.rules.inline.br.exec(t);if(n)return{type:"br",raw:n[0]}}del(t){const n=this.rules.inline.del.exec(t);if(n)return{type:"del",raw:n[0],text:n[2],tokens:this.lexer.inlineTokens(n[2])}}autolink(t){const n=this.rules.inline.autolink.exec(t);if(n){let r,l;return n[2]==="@"?(r=je(n[1]),l="mailto:"+r):(r=je(n[1]),l=r),{type:"link",raw:n[0],text:r,href:l,tokens:[{type:"text",raw:r,text:r}]}}}url(t){var r;let n;if(n=this.rules.inline.url.exec(t)){let l,i;if(n[2]==="@")l=je(n[0]),i="mailto:"+l;else{let o;do o=n[0],n[0]=((r=this.rules.inline._backpedal.exec(n[0]))==null?void 0:r[0])??"";while(o!==n[0]);l=je(n[0]),n[1]==="www."?i="http://"+n[0]:i=n[0]}return{type:"link",raw:n[0],text:l,href:i,tokens:[{type:"text",raw:l,text:l}]}}}inlineText(t){const n=this.rules.inline.text.exec(t);if(n){let r;return this.lexer.state.inRawBlock?r=n[0]:r=je(n[0]),{type:"text",raw:n[0],text:r}}}}const Mm=/^(?: *(?:\n|$))+/,Om=/^( {4}[^\n]+(?:\n(?: *(?:\n|$))*)?)+/,Dm=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,el=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,jm=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Rd=/(?:[*+-]|\d{1,9}[.)])/,Ld=V(/^(?!bull |blockCode|fences|blockquote|heading|html)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html))+?)\n {0,3}(=+|-+) *(?:\n+|$)/).replace(/bull/g,Rd).replace(/blockCode/g,/ {4}/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).getRegex(),fu=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,Fm=/^[^\n]+/,du=/(?!\s*\])(?:\\.|[^\[\]\\])+/,$m=V(/^ {0,3}\[(label)\]: *(?:\n *)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n *)?| *\n *)(title))? *(?:\n+|$)/).replace("label",du).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Um=V(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,Rd).getRegex(),Pi="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",pu=/|$))/,Bm=V("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|\\n*|$)|\\n*|$)|)[\\s\\S]*?(?:(?:\\n *)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$)|(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$))","i").replace("comment",pu).replace("tag",Pi).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Ad=V(fu).replace("hr",el).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",Pi).getRegex(),Hm=V(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",Ad).getRegex(),hu={blockquote:Hm,code:Om,def:$m,fences:Dm,heading:jm,hr:el,html:Bm,lheading:Ld,list:Um,newline:Mm,paragraph:Ad,table:Ar,text:Fm},nc=V("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",el).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code"," {4}[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",Pi).getRegex(),Wm={...hu,table:nc,paragraph:V(fu).replace("hr",el).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",nc).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",Pi).getRegex()},Vm={...hu,html:V(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+? *(?:\\n{2,}|\\s*$)|\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",pu).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:Ar,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:V(fu).replace("hr",el).replace("heading",` *#{1,6} *[^ -]`).replace("lheading",Ld).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},Pd=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Qm=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,zd=/^( {2,}|\\)\n(?!\s*$)/,Gm=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\]*?>/g,Xm=V(/^(?:\*+(?:((?!\*)[punct])|[^\s*]))|^_+(?:((?!_)[punct])|([^\s_]))/,"u").replace(/punct/g,tl).getRegex(),Zm=V("^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)[punct](\\*+)(?=[\\s]|$)|[^punct\\s](\\*+)(?!\\*)(?=[punct\\s]|$)|(?!\\*)[punct\\s](\\*+)(?=[^punct\\s])|[\\s](\\*+)(?!\\*)(?=[punct])|(?!\\*)[punct](\\*+)(?!\\*)(?=[punct])|[^punct\\s](\\*+)(?=[^punct\\s])","gu").replace(/punct/g,tl).getRegex(),qm=V("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)[punct](_+)(?=[\\s]|$)|[^punct\\s](_+)(?!_)(?=[punct\\s]|$)|(?!_)[punct\\s](_+)(?=[^punct\\s])|[\\s](_+)(?!_)(?=[punct])|(?!_)[punct](_+)(?!_)(?=[punct])","gu").replace(/punct/g,tl).getRegex(),Jm=V(/\\([punct])/,"gu").replace(/punct/g,tl).getRegex(),bm=V(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),eg=V(pu).replace("(?:-->|$)","-->").getRegex(),tg=V("^comment|^|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^|^").replace("comment",eg).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),pi=/(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/,ng=V(/^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/).replace("label",pi).replace("href",/<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Id=V(/^!?\[(label)\]\[(ref)\]/).replace("label",pi).replace("ref",du).getRegex(),Md=V(/^!?\[(ref)\](?:\[\])?/).replace("ref",du).getRegex(),rg=V("reflink|nolink(?!\\()","g").replace("reflink",Id).replace("nolink",Md).getRegex(),mu={_backpedal:Ar,anyPunctuation:Jm,autolink:bm,blockSkip:Km,br:zd,code:Qm,del:Ar,emStrongLDelim:Xm,emStrongRDelimAst:Zm,emStrongRDelimUnd:qm,escape:Pd,link:ng,nolink:Md,punctuation:Ym,reflink:Id,reflinkSearch:rg,tag:tg,text:Gm,url:Ar},lg={...mu,link:V(/^!?\[(label)\]\((.*?)\)/).replace("label",pi).getRegex(),reflink:V(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",pi).getRegex()},ds={...mu,escape:V(Pd).replace("])","~|])").getRegex(),url:V(/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/,"i").replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])([\s\S]*?[^\s~])\1(?=[^~]|$)/,text:/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\u+" ".repeat(a.length));let r,l,i,o;for(;t;)if(!(this.options.extensions&&this.options.extensions.block&&this.options.extensions.block.some(s=>(r=s.call({lexer:this},t,n))?(t=t.substring(r.raw.length),n.push(r),!0):!1))){if(r=this.tokenizer.space(t)){t=t.substring(r.raw.length),r.raw.length===1&&n.length>0?n[n.length-1].raw+=` -`:n.push(r);continue}if(r=this.tokenizer.code(t)){t=t.substring(r.raw.length),l=n[n.length-1],l&&(l.type==="paragraph"||l.type==="text")?(l.raw+=` -`+r.raw,l.text+=` -`+r.text,this.inlineQueue[this.inlineQueue.length-1].src=l.text):n.push(r);continue}if(r=this.tokenizer.fences(t)){t=t.substring(r.raw.length),n.push(r);continue}if(r=this.tokenizer.heading(t)){t=t.substring(r.raw.length),n.push(r);continue}if(r=this.tokenizer.hr(t)){t=t.substring(r.raw.length),n.push(r);continue}if(r=this.tokenizer.blockquote(t)){t=t.substring(r.raw.length),n.push(r);continue}if(r=this.tokenizer.list(t)){t=t.substring(r.raw.length),n.push(r);continue}if(r=this.tokenizer.html(t)){t=t.substring(r.raw.length),n.push(r);continue}if(r=this.tokenizer.def(t)){t=t.substring(r.raw.length),l=n[n.length-1],l&&(l.type==="paragraph"||l.type==="text")?(l.raw+=` -`+r.raw,l.text+=` -`+r.raw,this.inlineQueue[this.inlineQueue.length-1].src=l.text):this.tokens.links[r.tag]||(this.tokens.links[r.tag]={href:r.href,title:r.title});continue}if(r=this.tokenizer.table(t)){t=t.substring(r.raw.length),n.push(r);continue}if(r=this.tokenizer.lheading(t)){t=t.substring(r.raw.length),n.push(r);continue}if(i=t,this.options.extensions&&this.options.extensions.startBlock){let s=1/0;const u=t.slice(1);let a;this.options.extensions.startBlock.forEach(m=>{a=m.call({lexer:this},u),typeof a=="number"&&a>=0&&(s=Math.min(s,a))}),s<1/0&&s>=0&&(i=t.substring(0,s+1))}if(this.state.top&&(r=this.tokenizer.paragraph(i))){l=n[n.length-1],o&&l.type==="paragraph"?(l.raw+=` -`+r.raw,l.text+=` -`+r.text,this.inlineQueue.pop(),this.inlineQueue[this.inlineQueue.length-1].src=l.text):n.push(r),o=i.length!==t.length,t=t.substring(r.raw.length);continue}if(r=this.tokenizer.text(t)){t=t.substring(r.raw.length),l=n[n.length-1],l&&l.type==="text"?(l.raw+=` -`+r.raw,l.text+=` -`+r.text,this.inlineQueue.pop(),this.inlineQueue[this.inlineQueue.length-1].src=l.text):n.push(r);continue}if(t){const s="Infinite loop on byte: "+t.charCodeAt(0);if(this.options.silent){console.error(s);break}else throw new Error(s)}}return this.state.top=!0,n}inline(t,n=[]){return this.inlineQueue.push({src:t,tokens:n}),n}inlineTokens(t,n=[]){let r,l,i,o=t,s,u,a;if(this.tokens.links){const m=Object.keys(this.tokens.links);if(m.length>0)for(;(s=this.tokenizer.rules.inline.reflinkSearch.exec(o))!=null;)m.includes(s[0].slice(s[0].lastIndexOf("[")+1,-1))&&(o=o.slice(0,s.index)+"["+"a".repeat(s[0].length-2)+"]"+o.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(s=this.tokenizer.rules.inline.blockSkip.exec(o))!=null;)o=o.slice(0,s.index)+"["+"a".repeat(s[0].length-2)+"]"+o.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);for(;(s=this.tokenizer.rules.inline.anyPunctuation.exec(o))!=null;)o=o.slice(0,s.index)+"++"+o.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);for(;t;)if(u||(a=""),u=!1,!(this.options.extensions&&this.options.extensions.inline&&this.options.extensions.inline.some(m=>(r=m.call({lexer:this},t,n))?(t=t.substring(r.raw.length),n.push(r),!0):!1))){if(r=this.tokenizer.escape(t)){t=t.substring(r.raw.length),n.push(r);continue}if(r=this.tokenizer.tag(t)){t=t.substring(r.raw.length),l=n[n.length-1],l&&r.type==="text"&&l.type==="text"?(l.raw+=r.raw,l.text+=r.text):n.push(r);continue}if(r=this.tokenizer.link(t)){t=t.substring(r.raw.length),n.push(r);continue}if(r=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(r.raw.length),l=n[n.length-1],l&&r.type==="text"&&l.type==="text"?(l.raw+=r.raw,l.text+=r.text):n.push(r);continue}if(r=this.tokenizer.emStrong(t,o,a)){t=t.substring(r.raw.length),n.push(r);continue}if(r=this.tokenizer.codespan(t)){t=t.substring(r.raw.length),n.push(r);continue}if(r=this.tokenizer.br(t)){t=t.substring(r.raw.length),n.push(r);continue}if(r=this.tokenizer.del(t)){t=t.substring(r.raw.length),n.push(r);continue}if(r=this.tokenizer.autolink(t)){t=t.substring(r.raw.length),n.push(r);continue}if(!this.state.inLink&&(r=this.tokenizer.url(t))){t=t.substring(r.raw.length),n.push(r);continue}if(i=t,this.options.extensions&&this.options.extensions.startInline){let m=1/0;const g=t.slice(1);let p;this.options.extensions.startInline.forEach(y=>{p=y.call({lexer:this},g),typeof p=="number"&&p>=0&&(m=Math.min(m,p))}),m<1/0&&m>=0&&(i=t.substring(0,m+1))}if(r=this.tokenizer.inlineText(i)){t=t.substring(r.raw.length),r.raw.slice(-1)!=="_"&&(a=r.raw.slice(-1)),u=!0,l=n[n.length-1],l&&l.type==="text"?(l.raw+=r.raw,l.text+=r.text):n.push(r);continue}if(t){const m="Infinite loop on byte: "+t.charCodeAt(0);if(this.options.silent){console.error(m);break}else throw new Error(m)}}return n}}class hi{constructor(t){K(this,"options");this.options=t||yn}code(t,n,r){var i;const l=(i=(n||"").match(/^\S*/))==null?void 0:i[0];return t=t.replace(/\n$/,"")+` -`,l?'
    '+(r?t:je(t,!0))+`
    -`:"
    "+(r?t:je(t,!0))+`
    -`}blockquote(t){return`
    -${t}
    -`}html(t,n){return t}heading(t,n,r){return`${t} -`}hr(){return`
    -`}list(t,n,r){const l=n?"ol":"ul",i=n&&r!==1?' start="'+r+'"':"";return"<"+l+i+`> -`+t+" -`}listitem(t,n,r){return`
  • ${t}
  • -`}checkbox(t){return"'}paragraph(t){return`

    ${t}

    -`}table(t,n){return n&&(n=`${n}`),` - -`+t+` -`+n+`
    -`}tablerow(t){return` -${t} -`}tablecell(t,n){const r=n.header?"th":"td";return(n.align?`<${r} align="${n.align}">`:`<${r}>`)+t+` -`}strong(t){return`${t}`}em(t){return`${t}`}codespan(t){return`${t}`}br(){return"
    "}del(t){return`${t}`}link(t,n,r){const l=ba(t);if(l===null)return r;t=l;let i='
    ",i}image(t,n,r){const l=ba(t);if(l===null)return r;t=l;let i=`${r}0&&p.tokens[0].type==="paragraph"?(p.tokens[0].text=D+" "+p.tokens[0].text,p.tokens[0].tokens&&p.tokens[0].tokens.length>0&&p.tokens[0].tokens[0].type==="text"&&(p.tokens[0].tokens[0].text=D+" "+p.tokens[0].tokens[0].text)):p.tokens.unshift({type:"text",text:D+" "}):w+=D+" "}w+=this.parse(p.tokens,a),m+=this.renderer.listitem(w,x,!!y)}r+=this.renderer.list(m,s,u);continue}case"html":{const o=i;r+=this.renderer.html(o.text,o.block);continue}case"paragraph":{const o=i;r+=this.renderer.paragraph(this.parseInline(o.tokens));continue}case"text":{let o=i,s=o.tokens?this.parseInline(o.tokens):o.text;for(;l+1{const a=s[u].flat(1/0);r=r.concat(this.walkTokens(a,n))}):s.tokens&&(r=r.concat(this.walkTokens(s.tokens,n)))}}return r}use(...t){const n=this.defaults.extensions||{renderers:{},childTokens:{}};return t.forEach(r=>{const l={...r};if(l.async=this.defaults.async||l.async||!1,r.extensions&&(r.extensions.forEach(i=>{if(!i.name)throw new Error("extension name required");if("renderer"in i){const o=n.renderers[i.name];o?n.renderers[i.name]=function(...s){let u=i.renderer.apply(this,s);return u===!1&&(u=o.apply(this,s)),u}:n.renderers[i.name]=i.renderer}if("tokenizer"in i){if(!i.level||i.level!=="block"&&i.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");const o=n[i.level];o?o.unshift(i.tokenizer):n[i.level]=[i.tokenizer],i.start&&(i.level==="block"?n.startBlock?n.startBlock.push(i.start):n.startBlock=[i.start]:i.level==="inline"&&(n.startInline?n.startInline.push(i.start):n.startInline=[i.start]))}"childTokens"in i&&i.childTokens&&(n.childTokens[i.name]=i.childTokens)}),l.extensions=n),r.renderer){const i=this.defaults.renderer||new hi(this.defaults);for(const o in r.renderer){if(!(o in i))throw new Error(`renderer '${o}' does not exist`);if(o==="options")continue;const s=o,u=r.renderer[s],a=i[s];i[s]=(...m)=>{let g=u.apply(i,m);return g===!1&&(g=a.apply(i,m)),g||""}}l.renderer=i}if(r.tokenizer){const i=this.defaults.tokenizer||new di(this.defaults);for(const o in r.tokenizer){if(!(o in i))throw new Error(`tokenizer '${o}' does not exist`);if(["options","rules","lexer"].includes(o))continue;const s=o,u=r.tokenizer[s],a=i[s];i[s]=(...m)=>{let g=u.apply(i,m);return g===!1&&(g=a.apply(i,m)),g}}l.tokenizer=i}if(r.hooks){const i=this.defaults.hooks||new Pr;for(const o in r.hooks){if(!(o in i))throw new Error(`hook '${o}' does not exist`);if(o==="options")continue;const s=o,u=r.hooks[s],a=i[s];Pr.passThroughHooks.has(o)?i[s]=m=>{if(this.defaults.async)return Promise.resolve(u.call(i,m)).then(p=>a.call(i,p));const g=u.call(i,m);return a.call(i,g)}:i[s]=(...m)=>{let g=u.apply(i,m);return g===!1&&(g=a.apply(i,m)),g}}l.hooks=i}if(r.walkTokens){const i=this.defaults.walkTokens,o=r.walkTokens;l.walkTokens=function(s){let u=[];return u.push(o.call(this,s)),i&&(u=u.concat(i.call(this,s))),u}}this.defaults={...this.defaults,...l}}),this}setOptions(t){return this.defaults={...this.defaults,...t},this}lexer(t,n){return dt.lex(t,n??this.defaults)}parser(t,n){return pt.parse(t,n??this.defaults)}}hn=new WeakSet,ps=function(t,n){return(r,l)=>{const i={...l},o={...this.defaults,...i};this.defaults.async===!0&&i.async===!1&&(o.silent||console.warn("marked(): The async option was set to true by an extension. The async: false option sent to parse will be ignored."),o.async=!0);const s=sl(this,hn,Od).call(this,!!o.silent,!!o.async);if(typeof r>"u"||r===null)return s(new Error("marked(): input parameter is undefined or null"));if(typeof r!="string")return s(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(r)+", string expected"));if(o.hooks&&(o.hooks.options=o),o.async)return Promise.resolve(o.hooks?o.hooks.preprocess(r):r).then(u=>t(u,o)).then(u=>o.hooks?o.hooks.processAllTokens(u):u).then(u=>o.walkTokens?Promise.all(this.walkTokens(u,o.walkTokens)).then(()=>u):u).then(u=>n(u,o)).then(u=>o.hooks?o.hooks.postprocess(u):u).catch(s);try{o.hooks&&(r=o.hooks.preprocess(r));let u=t(r,o);o.hooks&&(u=o.hooks.processAllTokens(u)),o.walkTokens&&this.walkTokens(u,o.walkTokens);let a=n(u,o);return o.hooks&&(a=o.hooks.postprocess(a)),a}catch(u){return s(u)}}},Od=function(t,n){return r=>{if(r.message+=` -Please report this to https://github.com/markedjs/marked.`,t){const l="

    An error occurred:

    "+je(r.message+"",!0)+"
    ";return n?Promise.resolve(l):l}if(n)return Promise.reject(r);throw r}};const pn=new og;function H(e,t){return pn.parse(e,t)}H.options=H.setOptions=function(e){return pn.setOptions(e),H.defaults=pn.defaults,Td(H.defaults),H};H.getDefaults=cu;H.defaults=yn;H.use=function(...e){return pn.use(...e),H.defaults=pn.defaults,Td(H.defaults),H};H.walkTokens=function(e,t){return pn.walkTokens(e,t)};H.parseInline=pn.parseInline;H.Parser=pt;H.parser=pt.parse;H.Renderer=hi;H.TextRenderer=gu;H.Lexer=dt;H.lexer=dt.lex;H.Tokenizer=di;H.Hooks=Pr;H.parse=H;H.options;H.setOptions;H.use;H.walkTokens;H.parseInline;pt.parse;dt.lex;/*! @license DOMPurify 3.1.6 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.1.6/LICENSE */const{entries:Dd,setPrototypeOf:rc,isFrozen:sg,getPrototypeOf:ug,getOwnPropertyDescriptor:ag}=Object;let{freeze:Ce,seal:Ze,create:jd}=Object,{apply:hs,construct:ms}=typeof Reflect<"u"&&Reflect;Ce||(Ce=function(t){return t});Ze||(Ze=function(t){return t});hs||(hs=function(t,n,r){return t.apply(n,r)});ms||(ms=function(t,n){return new t(...n)});const Nl=Be(Array.prototype.forEach),lc=Be(Array.prototype.pop),dr=Be(Array.prototype.push),Bl=Be(String.prototype.toLowerCase),ho=Be(String.prototype.toString),ic=Be(String.prototype.match),pr=Be(String.prototype.replace),cg=Be(String.prototype.indexOf),fg=Be(String.prototype.trim),be=Be(Object.prototype.hasOwnProperty),Ee=Be(RegExp.prototype.test),hr=dg(TypeError);function Be(e){return function(t){for(var n=arguments.length,r=new Array(n>1?n-1:0),l=1;l2&&arguments[2]!==void 0?arguments[2]:Bl;rc&&rc(e,null);let r=t.length;for(;r--;){let l=t[r];if(typeof l=="string"){const i=n(l);i!==l&&(sg(t)||(t[r]=i),l=i)}e[l]=!0}return e}function pg(e){for(let t=0;t/gm),vg=Ze(/\${[\w\W]*}/gm),kg=Ze(/^data-[\-\w.\u00B7-\uFFFF]/),wg=Ze(/^aria-[\-\w]+$/),Fd=Ze(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),xg=Ze(/^(?:\w+script|data):/i),Sg=Ze(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),$d=Ze(/^html$/i),Eg=Ze(/^[a-z][.\w]*(-[.\w]+)+$/i);var cc=Object.freeze({__proto__:null,MUSTACHE_EXPR:gg,ERB_EXPR:yg,TMPLIT_EXPR:vg,DATA_ATTR:kg,ARIA_ATTR:wg,IS_ALLOWED_URI:Fd,IS_SCRIPT_OR_DATA:xg,ATTR_WHITESPACE:Sg,DOCTYPE_NAME:$d,CUSTOM_ELEMENT:Eg});const gr={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,progressingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},_g=function(){return typeof window>"u"?null:window},Tg=function(t,n){if(typeof t!="object"||typeof t.createPolicy!="function")return null;let r=null;const l="data-tt-policy-suffix";n&&n.hasAttribute(l)&&(r=n.getAttribute(l));const i="dompurify"+(r?"#"+r:"");try{return t.createPolicy(i,{createHTML(o){return o},createScriptURL(o){return o}})}catch{return console.warn("TrustedTypes policy "+i+" could not be created."),null}};function Ud(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:_g();const t=P=>Ud(P);if(t.version="3.1.6",t.removed=[],!e||!e.document||e.document.nodeType!==gr.document)return t.isSupported=!1,t;let{document:n}=e;const r=n,l=r.currentScript,{DocumentFragment:i,HTMLTemplateElement:o,Node:s,Element:u,NodeFilter:a,NamedNodeMap:m=e.NamedNodeMap||e.MozNamedAttrMap,HTMLFormElement:g,DOMParser:p,trustedTypes:y}=e,x=u.prototype,w=mr(x,"cloneNode"),D=mr(x,"remove"),d=mr(x,"nextSibling"),c=mr(x,"childNodes"),h=mr(x,"parentNode");if(typeof o=="function"){const P=n.createElement("template");P.content&&P.content.ownerDocument&&(n=P.content.ownerDocument)}let v,T="";const{implementation:R,createNodeIterator:L,createDocumentFragment:_,getElementsByTagName:$}=n,{importNode:z}=r;let U={};t.isSupported=typeof Dd=="function"&&typeof h=="function"&&R&&R.createHTMLDocument!==void 0;const{MUSTACHE_EXPR:de,ERB_EXPR:qe,TMPLIT_EXPR:Rt,DATA_ATTR:Lt,ARIA_ATTR:At,IS_SCRIPT_OR_DATA:bn,ATTR_WHITESPACE:C,CUSTOM_ELEMENT:I}=cc;let{IS_ALLOWED_URI:M}=cc,O=null;const re=j({},[...oc,...mo,...go,...yo,...sc]);let J=null;const ot=j({},[...uc,...vo,...ac,...Rl]);let Y=Object.seal(jd(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),Oe=null,Pt=null,yu=!0,zi=!0,vu=!1,ku=!0,vn=!1,Ii=!0,Jt=!1,Mi=!1,Oi=!1,kn=!1,nl=!1,rl=!1,wu=!0,xu=!1;const Bd="user-content-";let Di=!0,er=!1,wn={},xn=null;const Su=j({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let Eu=null;const _u=j({},["audio","video","img","source","image","track"]);let ji=null;const Tu=j({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),ll="http://www.w3.org/1998/Math/MathML",il="http://www.w3.org/2000/svg",gt="http://www.w3.org/1999/xhtml";let Sn=gt,Fi=!1,$i=null;const Hd=j({},[ll,il,gt],ho);let tr=null;const Wd=["application/xhtml+xml","text/html"],Vd="text/html";let ae=null,En=null;const Qd=n.createElement("form"),Cu=function(f){return f instanceof RegExp||f instanceof Function},Ui=function(){let f=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(En&&En===f)){if((!f||typeof f!="object")&&(f={}),f=tn(f),tr=Wd.indexOf(f.PARSER_MEDIA_TYPE)===-1?Vd:f.PARSER_MEDIA_TYPE,ae=tr==="application/xhtml+xml"?ho:Bl,O=be(f,"ALLOWED_TAGS")?j({},f.ALLOWED_TAGS,ae):re,J=be(f,"ALLOWED_ATTR")?j({},f.ALLOWED_ATTR,ae):ot,$i=be(f,"ALLOWED_NAMESPACES")?j({},f.ALLOWED_NAMESPACES,ho):Hd,ji=be(f,"ADD_URI_SAFE_ATTR")?j(tn(Tu),f.ADD_URI_SAFE_ATTR,ae):Tu,Eu=be(f,"ADD_DATA_URI_TAGS")?j(tn(_u),f.ADD_DATA_URI_TAGS,ae):_u,xn=be(f,"FORBID_CONTENTS")?j({},f.FORBID_CONTENTS,ae):Su,Oe=be(f,"FORBID_TAGS")?j({},f.FORBID_TAGS,ae):{},Pt=be(f,"FORBID_ATTR")?j({},f.FORBID_ATTR,ae):{},wn=be(f,"USE_PROFILES")?f.USE_PROFILES:!1,yu=f.ALLOW_ARIA_ATTR!==!1,zi=f.ALLOW_DATA_ATTR!==!1,vu=f.ALLOW_UNKNOWN_PROTOCOLS||!1,ku=f.ALLOW_SELF_CLOSE_IN_ATTR!==!1,vn=f.SAFE_FOR_TEMPLATES||!1,Ii=f.SAFE_FOR_XML!==!1,Jt=f.WHOLE_DOCUMENT||!1,kn=f.RETURN_DOM||!1,nl=f.RETURN_DOM_FRAGMENT||!1,rl=f.RETURN_TRUSTED_TYPE||!1,Oi=f.FORCE_BODY||!1,wu=f.SANITIZE_DOM!==!1,xu=f.SANITIZE_NAMED_PROPS||!1,Di=f.KEEP_CONTENT!==!1,er=f.IN_PLACE||!1,M=f.ALLOWED_URI_REGEXP||Fd,Sn=f.NAMESPACE||gt,Y=f.CUSTOM_ELEMENT_HANDLING||{},f.CUSTOM_ELEMENT_HANDLING&&Cu(f.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(Y.tagNameCheck=f.CUSTOM_ELEMENT_HANDLING.tagNameCheck),f.CUSTOM_ELEMENT_HANDLING&&Cu(f.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(Y.attributeNameCheck=f.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),f.CUSTOM_ELEMENT_HANDLING&&typeof f.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(Y.allowCustomizedBuiltInElements=f.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),vn&&(zi=!1),nl&&(kn=!0),wn&&(O=j({},sc),J=[],wn.html===!0&&(j(O,oc),j(J,uc)),wn.svg===!0&&(j(O,mo),j(J,vo),j(J,Rl)),wn.svgFilters===!0&&(j(O,go),j(J,vo),j(J,Rl)),wn.mathMl===!0&&(j(O,yo),j(J,ac),j(J,Rl))),f.ADD_TAGS&&(O===re&&(O=tn(O)),j(O,f.ADD_TAGS,ae)),f.ADD_ATTR&&(J===ot&&(J=tn(J)),j(J,f.ADD_ATTR,ae)),f.ADD_URI_SAFE_ATTR&&j(ji,f.ADD_URI_SAFE_ATTR,ae),f.FORBID_CONTENTS&&(xn===Su&&(xn=tn(xn)),j(xn,f.FORBID_CONTENTS,ae)),Di&&(O["#text"]=!0),Jt&&j(O,["html","head","body"]),O.table&&(j(O,["tbody"]),delete Oe.tbody),f.TRUSTED_TYPES_POLICY){if(typeof f.TRUSTED_TYPES_POLICY.createHTML!="function")throw hr('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof f.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw hr('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');v=f.TRUSTED_TYPES_POLICY,T=v.createHTML("")}else v===void 0&&(v=Tg(y,l)),v!==null&&typeof T=="string"&&(T=v.createHTML(""));Ce&&Ce(f),En=f}},Nu=j({},["mi","mo","mn","ms","mtext"]),Ru=j({},["foreignobject","annotation-xml"]),Gd=j({},["title","style","font","a","script"]),Lu=j({},[...mo,...go,...hg]),Au=j({},[...yo,...mg]),Yd=function(f){let E=h(f);(!E||!E.tagName)&&(E={namespaceURI:Sn,tagName:"template"});const A=Bl(f.tagName),Q=Bl(E.tagName);return $i[f.namespaceURI]?f.namespaceURI===il?E.namespaceURI===gt?A==="svg":E.namespaceURI===ll?A==="svg"&&(Q==="annotation-xml"||Nu[Q]):!!Lu[A]:f.namespaceURI===ll?E.namespaceURI===gt?A==="math":E.namespaceURI===il?A==="math"&&Ru[Q]:!!Au[A]:f.namespaceURI===gt?E.namespaceURI===il&&!Ru[Q]||E.namespaceURI===ll&&!Nu[Q]?!1:!Au[A]&&(Gd[A]||!Lu[A]):!!(tr==="application/xhtml+xml"&&$i[f.namespaceURI]):!1},st=function(f){dr(t.removed,{element:f});try{h(f).removeChild(f)}catch{D(f)}},ol=function(f,E){try{dr(t.removed,{attribute:E.getAttributeNode(f),from:E})}catch{dr(t.removed,{attribute:null,from:E})}if(E.removeAttribute(f),f==="is"&&!J[f])if(kn||nl)try{st(E)}catch{}else try{E.setAttribute(f,"")}catch{}},Pu=function(f){let E=null,A=null;if(Oi)f=""+f;else{const pe=ic(f,/^[\r\n\t ]+/);A=pe&&pe[0]}tr==="application/xhtml+xml"&&Sn===gt&&(f=''+f+"");const Q=v?v.createHTML(f):f;if(Sn===gt)try{E=new p().parseFromString(Q,tr)}catch{}if(!E||!E.documentElement){E=R.createDocument(Sn,"template",null);try{E.documentElement.innerHTML=Fi?T:Q}catch{}}const ye=E.body||E.documentElement;return f&&A&&ye.insertBefore(n.createTextNode(A),ye.childNodes[0]||null),Sn===gt?$.call(E,Jt?"html":"body")[0]:Jt?E.documentElement:ye},zu=function(f){return L.call(f.ownerDocument||f,f,a.SHOW_ELEMENT|a.SHOW_COMMENT|a.SHOW_TEXT|a.SHOW_PROCESSING_INSTRUCTION|a.SHOW_CDATA_SECTION,null)},Iu=function(f){return f instanceof g&&(typeof f.nodeName!="string"||typeof f.textContent!="string"||typeof f.removeChild!="function"||!(f.attributes instanceof m)||typeof f.removeAttribute!="function"||typeof f.setAttribute!="function"||typeof f.namespaceURI!="string"||typeof f.insertBefore!="function"||typeof f.hasChildNodes!="function")},Mu=function(f){return typeof s=="function"&&f instanceof s},yt=function(f,E,A){U[f]&&Nl(U[f],Q=>{Q.call(t,E,A,En)})},Ou=function(f){let E=null;if(yt("beforeSanitizeElements",f,null),Iu(f))return st(f),!0;const A=ae(f.nodeName);if(yt("uponSanitizeElement",f,{tagName:A,allowedTags:O}),f.hasChildNodes()&&!Mu(f.firstElementChild)&&Ee(/<[/\w]/g,f.innerHTML)&&Ee(/<[/\w]/g,f.textContent)||f.nodeType===gr.progressingInstruction||Ii&&f.nodeType===gr.comment&&Ee(/<[/\w]/g,f.data))return st(f),!0;if(!O[A]||Oe[A]){if(!Oe[A]&&ju(A)&&(Y.tagNameCheck instanceof RegExp&&Ee(Y.tagNameCheck,A)||Y.tagNameCheck instanceof Function&&Y.tagNameCheck(A)))return!1;if(Di&&!xn[A]){const Q=h(f)||f.parentNode,ye=c(f)||f.childNodes;if(ye&&Q){const pe=ye.length;for(let Le=pe-1;Le>=0;--Le){const ut=w(ye[Le],!0);ut.__removalCount=(f.__removalCount||0)+1,Q.insertBefore(ut,d(f))}}}return st(f),!0}return f instanceof u&&!Yd(f)||(A==="noscript"||A==="noembed"||A==="noframes")&&Ee(/<\/no(script|embed|frames)/i,f.innerHTML)?(st(f),!0):(vn&&f.nodeType===gr.text&&(E=f.textContent,Nl([de,qe,Rt],Q=>{E=pr(E,Q," ")}),f.textContent!==E&&(dr(t.removed,{element:f.cloneNode()}),f.textContent=E)),yt("afterSanitizeElements",f,null),!1)},Du=function(f,E,A){if(wu&&(E==="id"||E==="name")&&(A in n||A in Qd))return!1;if(!(zi&&!Pt[E]&&Ee(Lt,E))){if(!(yu&&Ee(At,E))){if(!J[E]||Pt[E]){if(!(ju(f)&&(Y.tagNameCheck instanceof RegExp&&Ee(Y.tagNameCheck,f)||Y.tagNameCheck instanceof Function&&Y.tagNameCheck(f))&&(Y.attributeNameCheck instanceof RegExp&&Ee(Y.attributeNameCheck,E)||Y.attributeNameCheck instanceof Function&&Y.attributeNameCheck(E))||E==="is"&&Y.allowCustomizedBuiltInElements&&(Y.tagNameCheck instanceof RegExp&&Ee(Y.tagNameCheck,A)||Y.tagNameCheck instanceof Function&&Y.tagNameCheck(A))))return!1}else if(!ji[E]){if(!Ee(M,pr(A,C,""))){if(!((E==="src"||E==="xlink:href"||E==="href")&&f!=="script"&&cg(A,"data:")===0&&Eu[f])){if(!(vu&&!Ee(bn,pr(A,C,"")))){if(A)return!1}}}}}}return!0},ju=function(f){return f!=="annotation-xml"&&ic(f,I)},Fu=function(f){yt("beforeSanitizeAttributes",f,null);const{attributes:E}=f;if(!E)return;const A={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:J};let Q=E.length;for(;Q--;){const ye=E[Q],{name:pe,namespaceURI:Le,value:ut}=ye,nr=ae(pe);let Se=pe==="value"?ut:fg(ut);if(A.attrName=nr,A.attrValue=Se,A.keepAttr=!0,A.forceKeepAttr=void 0,yt("uponSanitizeAttribute",f,A),Se=A.attrValue,Ii&&Ee(/((--!?|])>)|<\/(style|title)/i,Se)){ol(pe,f);continue}if(A.forceKeepAttr||(ol(pe,f),!A.keepAttr))continue;if(!ku&&Ee(/\/>/i,Se)){ol(pe,f);continue}vn&&Nl([de,qe,Rt],Uu=>{Se=pr(Se,Uu," ")});const $u=ae(f.nodeName);if(Du($u,nr,Se)){if(xu&&(nr==="id"||nr==="name")&&(ol(pe,f),Se=Bd+Se),v&&typeof y=="object"&&typeof y.getAttributeType=="function"&&!Le)switch(y.getAttributeType($u,nr)){case"TrustedHTML":{Se=v.createHTML(Se);break}case"TrustedScriptURL":{Se=v.createScriptURL(Se);break}}try{Le?f.setAttributeNS(Le,pe,Se):f.setAttribute(pe,Se),Iu(f)?st(f):lc(t.removed)}catch{}}}yt("afterSanitizeAttributes",f,null)},Kd=function P(f){let E=null;const A=zu(f);for(yt("beforeSanitizeShadowDOM",f,null);E=A.nextNode();)yt("uponSanitizeShadowNode",E,null),!Ou(E)&&(E.content instanceof i&&P(E.content),Fu(E));yt("afterSanitizeShadowDOM",f,null)};return t.sanitize=function(P){let f=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},E=null,A=null,Q=null,ye=null;if(Fi=!P,Fi&&(P=""),typeof P!="string"&&!Mu(P))if(typeof P.toString=="function"){if(P=P.toString(),typeof P!="string")throw hr("dirty is not a string, aborting")}else throw hr("toString is not a function");if(!t.isSupported)return P;if(Mi||Ui(f),t.removed=[],typeof P=="string"&&(er=!1),er){if(P.nodeName){const ut=ae(P.nodeName);if(!O[ut]||Oe[ut])throw hr("root node is forbidden and cannot be sanitized in-place")}}else if(P instanceof s)E=Pu(""),A=E.ownerDocument.importNode(P,!0),A.nodeType===gr.element&&A.nodeName==="BODY"||A.nodeName==="HTML"?E=A:E.appendChild(A);else{if(!kn&&!vn&&!Jt&&P.indexOf("<")===-1)return v&&rl?v.createHTML(P):P;if(E=Pu(P),!E)return kn?null:rl?T:""}E&&Oi&&st(E.firstChild);const pe=zu(er?P:E);for(;Q=pe.nextNode();)Ou(Q)||(Q.content instanceof i&&Kd(Q.content),Fu(Q));if(er)return P;if(kn){if(nl)for(ye=_.call(E.ownerDocument);E.firstChild;)ye.appendChild(E.firstChild);else ye=E;return(J.shadowroot||J.shadowrootmode)&&(ye=z.call(r,ye,!0)),ye}let Le=Jt?E.outerHTML:E.innerHTML;return Jt&&O["!doctype"]&&E.ownerDocument&&E.ownerDocument.doctype&&E.ownerDocument.doctype.name&&Ee($d,E.ownerDocument.doctype.name)&&(Le=" -`+Le),vn&&Nl([de,qe,Rt],ut=>{Le=pr(Le,ut," ")}),v&&rl?v.createHTML(Le):Le},t.setConfig=function(){let P=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Ui(P),Mi=!0},t.clearConfig=function(){En=null,Mi=!1},t.isValidAttribute=function(P,f,E){En||Ui({});const A=ae(P),Q=ae(f);return Du(A,Q,E)},t.addHook=function(P,f){typeof f=="function"&&(U[P]=U[P]||[],dr(U[P],f))},t.removeHook=function(P){if(U[P])return lc(U[P])},t.removeHooks=function(P){U[P]&&(U[P]=[])},t.removeAllHooks=function(){U={}},t}var Cg=Ud();function Ng(e){return S.jsxs("svg",{...e,xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[S.jsx("path",{d:"M12 8V4H8"}),S.jsx("rect",{width:"16",height:"12",x:"4",y:"8",rx:"2"}),S.jsx("path",{d:"M2 14h2"}),S.jsx("path",{d:"M20 14h2"}),S.jsx("path",{d:"M15 13v2"}),S.jsx("path",{d:"M9 13v2"})]})}function Rg(e){return S.jsxs("svg",{...e,xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[S.jsx("path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2"}),S.jsx("circle",{cx:"12",cy:"7",r:"4"})]})}function Lg(e){return Cg.sanitize(H.parse(e))}function Ag({messages:e}){const t=e.length===0;return ie.useEffect(()=>{window.MathJax.typeset()},[e]),S.jsx("div",{className:`flex-1 p-6 max-w-[960px] w-full ${t?"flex flex-col items-center justify-end":"space-y-4"}`,children:t?S.jsx("div",{className:"text-xl",children:"Ready!"}):e.map((n,r)=>S.jsx("div",{className:"flex items-start space-x-4",children:n.role==="assistant"?S.jsxs(S.Fragment,{children:[S.jsx(Ng,{className:"h-6 w-6 min-h-6 min-w-6 my-3 text-gray-500 dark:text-gray-300"}),S.jsx("div",{className:"bg-gray-200 dark:bg-gray-700 rounded-lg p-4",children:S.jsx("p",{className:"min-h-6 text-gray-800 dark:text-gray-200 overflow-wrap-anywhere",children:n.content.length>0?S.jsx("span",{className:"markdown",dangerouslySetInnerHTML:{__html:Lg(n.content)}}):S.jsxs("span",{className:"h-6 flex items-center gap-1",children:[S.jsx("span",{className:"w-2.5 h-2.5 bg-gray-600 dark:bg-gray-300 rounded-full animate-pulse"}),S.jsx("span",{className:"w-2.5 h-2.5 bg-gray-600 dark:bg-gray-300 rounded-full animate-pulse animation-delay-200"}),S.jsx("span",{className:"w-2.5 h-2.5 bg-gray-600 dark:bg-gray-300 rounded-full animate-pulse animation-delay-400"})]})})})]}):S.jsxs(S.Fragment,{children:[S.jsx(Rg,{className:"h-6 w-6 min-h-6 min-w-6 my-3 text-gray-500 dark:text-gray-300"}),S.jsx("div",{className:"bg-blue-500 text-white rounded-lg p-4",children:S.jsx("p",{className:"min-h-6 overflow-wrap-anywhere",children:n.content})})]})},`message-${r}`))})}function fc(e){return S.jsxs("svg",{...e,xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[S.jsx("path",{d:"M5 12h14"}),S.jsx("path",{d:"m12 5 7 7-7 7"})]})}function Pg(e){return S.jsxs("svg",{...e,xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[S.jsx("path",{d:"M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z"}),S.jsx("path",{fill:"currentColor",d:"M9 9.563C9 9.252 9.252 9 9.563 9h4.874c.311 0 .563.252.563.563v4.874c0 .311-.252.563-.563.563H9.564A.562.562 0 0 1 9 14.437V9.564Z"})]})}function zg(e){const t=e==0?0:Math.floor(Math.log(e)/Math.log(1024));return+(e/Math.pow(1024,t)).toFixed(2)*1+["B","kB","MB","GB","TB"][t]}function Ig({text:e,percentage:t,total:n}){return t??(t=0),S.jsx("div",{className:"w-full bg-gray-100 dark:bg-gray-700 text-left rounded-lg overflow-hidden mb-0.5",children:S.jsxs("div",{className:"bg-blue-400 whitespace-nowrap px-1 text-sm",style:{width:`${t}%`},children:[e," (",t.toFixed(2),"%",isNaN(n)?"":` of ${zg(n)}`,")"]})})}const Mg=!!navigator.gpu,Og=120,Dg=["Give me some tips to improve my time management skills.","What is the difference between AI and ML?","Write python code to compute the nth fibonacci number."];function jg(){const e=ie.useRef(null),t=ie.useRef(null),n=ie.useRef(null),[r,l]=ie.useState(null),[i,o]=ie.useState(null),[s,u]=ie.useState(""),[a,m]=ie.useState([]),[g,p]=ie.useState(!1),[y,x]=ie.useState(""),[w,D]=ie.useState([]),[d,c]=ie.useState(null),[h,v]=ie.useState(null);function T(_){D($=>[...$,{role:"user",content:_}]),c(null),p(!0),x("")}function R(){e.current.postMessage({type:"interrupt"})}ie.useEffect(()=>{L()},[y]);function L(){if(!t.current)return;const _=t.current;_.style.height="auto";const $=Math.min(Math.max(_.scrollHeight,24),200);_.style.height=`${$}px`}return ie.useEffect(()=>{e.current||(e.current=new Worker(new URL("/assets/worker-7HwdCgNb.js",import.meta.url),{type:"module"}),e.current.postMessage({type:"check"}));const _=z=>{switch(z.data.status){case"loading":l("loading"),u(z.data.data);break;case"initiate":m(U=>[...U,z.data]);break;case"progress":m(U=>U.map(de=>de.file===z.data.file?{...de,...z.data}:de));break;case"done":m(U=>U.filter(de=>de.file!==z.data.file));break;case"ready":l("ready");break;case"start":D(U=>[...U,{role:"assistant",content:""}]);break;case"update":{const{output:U,tps:de,numTokens:qe}=z.data;c(de),v(qe),D(Rt=>{const Lt=[...Rt],At=Lt.at(-1);return Lt[Lt.length-1]={...At,content:At.content+U},Lt})}break;case"complete":p(!1);break;case"error":o(z.data.data);break}},$=z=>{console.error("Worker error:",z)};return e.current.addEventListener("message",_),e.current.addEventListener("error",$),()=>{e.current.removeEventListener("message",_),e.current.removeEventListener("error",$)}},[]),ie.useEffect(()=>{w.filter(_=>_.role==="user").length!==0&&w.at(-1).role!=="assistant"&&(c(null),e.current.postMessage({type:"generate",data:w}))},[w,g]),ie.useEffect(()=>{if(!n.current||!g)return;const _=n.current;_.scrollHeight-_.scrollTop-_.clientHeight{e.current.postMessage({type:"load"}),l("loading")},disabled:r!==null||i!==null,children:"Load model"})]})]}),r==="loading"&&S.jsx(S.Fragment,{children:S.jsxs("div",{className:"w-full max-w-[500px] text-left mx-auto p-4 bottom-0 mt-auto",children:[S.jsx("p",{className:"text-center mb-1",children:s}),a.map(({file:_,progress:$,total:z},U)=>S.jsx(Ig,{text:_,percentage:$,total:z},U))]})}),r==="ready"&&S.jsxs("div",{ref:n,className:"overflow-y-auto scrollbar-thin w-full flex flex-col items-center h-full",children:[S.jsx(Ag,{messages:w}),w.length===0&&S.jsx("div",{children:Dg.map((_,$)=>S.jsx("div",{className:"m-1 border dark:border-gray-600 rounded-md p-2 bg-gray-100 dark:bg-gray-700 cursor-pointer",onClick:()=>T(_),children:_},$))}),S.jsx("p",{className:"text-center text-sm min-h-6 text-gray-500 dark:text-gray-300",children:d&&w.length>0&&S.jsxs(S.Fragment,{children:[!g&&S.jsxs("span",{children:["Generated ",h," tokens in"," ",(h/d).toFixed(2)," seconds ("]}),S.jsxs(S.Fragment,{children:[S.jsx("span",{className:"font-medium text-center mr-1 text-black dark:text-white",children:d.toFixed(2)}),S.jsx("span",{className:"text-gray-500 dark:text-gray-300",children:"tokens/second"})]}),!g&&S.jsxs(S.Fragment,{children:[S.jsx("span",{className:"mr-1",children:")."}),S.jsx("span",{className:"underline cursor-pointer",onClick:()=>{e.current.postMessage({type:"reset"}),D([])},children:"Reset"})]})]})})]}),S.jsxs("div",{className:"mt-2 border dark:bg-gray-700 rounded-lg w-[600px] max-w-[80%] max-h-[200px] mx-auto relative mb-3 flex",children:[S.jsx("textarea",{ref:t,className:"scrollbar-thin w-[550px] dark:bg-gray-700 px-3 py-4 rounded-lg bg-transparent border-none outline-none text-gray-800 disabled:text-gray-400 dark:text-gray-200 placeholder-gray-500 dark:placeholder-gray-400 disabled:placeholder-gray-200 resize-none disabled:cursor-not-allowed",placeholder:"Type your message...",type:"text",rows:1,value:y,disabled:r!=="ready",title:r==="ready"?"Model is ready":"Model not loaded yet",onKeyDown:_=>{y.length>0&&!g&&_.key==="Enter"&&!_.shiftKey&&(_.preventDefault(),T(y))},onInput:_=>x(_.target.value)}),g?S.jsx("div",{className:"cursor-pointer",onClick:R,children:S.jsx(Pg,{className:"h-8 w-8 p-1 rounded-md text-gray-800 dark:text-gray-100 absolute right-3 bottom-3"})}):y.length>0?S.jsx("div",{className:"cursor-pointer",onClick:()=>T(y),children:S.jsx(fc,{className:"h-8 w-8 p-1 bg-gray-800 dark:bg-gray-100 text-white dark:text-black rounded-md absolute right-3 bottom-3"})}):S.jsx("div",{children:S.jsx(fc,{className:"h-8 w-8 p-1 bg-gray-200 dark:bg-gray-600 text-gray-50 dark:text-gray-800 rounded-md absolute right-3 bottom-3"})})]}),S.jsx("p",{className:"text-xs text-gray-400 text-center mb-3",children:"Disclaimer: Generated content may be inaccurate or false."})]}):S.jsxs("div",{className:"fixed w-screen h-screen bg-black z-10 bg-opacity-[92%] text-white text-2xl font-semibold flex justify-center items-center text-center",children:["WebGPU is not supported",S.jsx("br",{}),"by this browser :("]})}ko.createRoot(document.getElementById("root")).render(S.jsx(hp.StrictMode,{children:S.jsx(jg,{})})); diff --git a/assets/worker-7HwdCgNb.js b/assets/worker-7HwdCgNb.js deleted file mode 100644 index eaf9eee8b50c5d4b0d10cf3713345aae27ed2c9c..0000000000000000000000000000000000000000 --- a/assets/worker-7HwdCgNb.js +++ /dev/null @@ -1,2585 +0,0 @@ -var w_=Object.defineProperty;var y_=(Tn,es,Ks)=>es in Tn?w_(Tn,es,{enumerable:!0,configurable:!0,writable:!0,value:Ks}):Tn[es]=Ks;var xe=(Tn,es,Ks)=>y_(Tn,typeof es!="symbol"?es+"":es,Ks);(function(){"use strict";var Tn={},es={"./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm":(Pt,Ce,N)=>{Pt.exports=N.p+"ort-wasm-simd-threaded.jsep.wasm"},"?2ce3":()=>{},"?7a2c":()=>{},"?a42a":()=>{},"?2b25":()=>{},"?569f":()=>{},"?3f59":()=>{},"?154a":()=>{},"./node_modules/@huggingface/jinja/dist/index.js":(Pt,Ce,N)=>{N.r(Ce),N.d(Ce,{Environment:()=>je,Interpreter:()=>lt,Template:()=>Et,parse:()=>$e,tokenize:()=>P});var z=Object.freeze({Text:"Text",NumericLiteral:"NumericLiteral",BooleanLiteral:"BooleanLiteral",StringLiteral:"StringLiteral",Identifier:"Identifier",Equals:"Equals",OpenParen:"OpenParen",CloseParen:"CloseParen",OpenStatement:"OpenStatement",CloseStatement:"CloseStatement",OpenExpression:"OpenExpression",CloseExpression:"CloseExpression",OpenSquareBracket:"OpenSquareBracket",CloseSquareBracket:"CloseSquareBracket",OpenCurlyBracket:"OpenCurlyBracket",CloseCurlyBracket:"CloseCurlyBracket",Comma:"Comma",Dot:"Dot",Colon:"Colon",Pipe:"Pipe",CallOperator:"CallOperator",AdditiveBinaryOperator:"AdditiveBinaryOperator",MultiplicativeBinaryOperator:"MultiplicativeBinaryOperator",ComparisonBinaryOperator:"ComparisonBinaryOperator",UnaryOperator:"UnaryOperator",Set:"Set",If:"If",For:"For",In:"In",Is:"Is",NotIn:"NotIn",Else:"Else",EndIf:"EndIf",ElseIf:"ElseIf",EndFor:"EndFor",And:"And",Or:"Or",Not:"UnaryOperator",Macro:"Macro",EndMacro:"EndMacro"}),me=Object.freeze({set:z.Set,for:z.For,in:z.In,is:z.Is,if:z.If,else:z.Else,endif:z.EndIf,elif:z.ElseIf,endfor:z.EndFor,and:z.And,or:z.Or,not:z.Not,"not in":z.NotIn,macro:z.Macro,endmacro:z.EndMacro,true:z.BooleanLiteral,false:z.BooleanLiteral,True:z.BooleanLiteral,False:z.BooleanLiteral}),ye=class{constructor(x,q){this.value=x,this.type=q}};function Te(x){return/\w/.test(x)}function Ee(x){return/[0-9]/.test(x)}var j=[["{%",z.OpenStatement],["%}",z.CloseStatement],["{{",z.OpenExpression],["}}",z.CloseExpression],["(",z.OpenParen],[")",z.CloseParen],["{",z.OpenCurlyBracket],["}",z.CloseCurlyBracket],["[",z.OpenSquareBracket],["]",z.CloseSquareBracket],[",",z.Comma],[".",z.Dot],[":",z.Colon],["|",z.Pipe],["<=",z.ComparisonBinaryOperator],[">=",z.ComparisonBinaryOperator],["==",z.ComparisonBinaryOperator],["!=",z.ComparisonBinaryOperator],["<",z.ComparisonBinaryOperator],[">",z.ComparisonBinaryOperator],["+",z.AdditiveBinaryOperator],["-",z.AdditiveBinaryOperator],["*",z.MultiplicativeBinaryOperator],["/",z.MultiplicativeBinaryOperator],["%",z.MultiplicativeBinaryOperator],["=",z.Equals]],S=new Map([["n",` -`],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function V(x,q={}){return x.endsWith(` -`)&&(x=x.slice(0,-1)),x=x.replace(/{#.*?#}/gs,"{##}"),q.lstrip_blocks&&(x=x.replace(/^[ \t]*({[#%])/gm,"$1")),q.trim_blocks&&(x=x.replace(/([#%]})\n/g,"$1")),x.replace(/{##}/g,"").replace(/-%}\s*/g,"%}").replace(/\s*{%-/g,"{%").replace(/-}}\s*/g,"}}").replace(/\s*{{-/g,"{{")}function P(x,q={}){var Je,Bt,ct;const $=[],Q=V(x,q);let he=0;const Ye=Tt=>{let It="";for(;Tt(Q[he]);){if(Q[he]==="\\"){if(++he,he>=Q.length)throw new SyntaxError("Unexpected end of input");const At=Q[he++],cr=S.get(At);if(cr===void 0)throw new SyntaxError(`Unexpected escaped character: ${At}`);It+=cr;continue}if(It+=Q[he++],he>=Q.length)throw new SyntaxError("Unexpected end of input")}return It};e:for(;he0){$.push(new ye(At,z.Text));continue}}Ye(At=>/\s/.test(At));const It=Q[he];if(It==="-"||It==="+"){const At=(Bt=$.at(-1))==null?void 0:Bt.type;if(At===z.Text||At===void 0)throw new SyntaxError(`Unexpected character: ${It}`);switch(At){case z.Identifier:case z.NumericLiteral:case z.BooleanLiteral:case z.StringLiteral:case z.CloseParen:case z.CloseSquareBracket:break;default:{++he;const cr=Ye(Ee);$.push(new ye(`${It}${cr}`,cr.length>0?z.NumericLiteral:z.UnaryOperator));continue}}}for(const[At,cr]of j)if(Q.slice(he,he+At.length)===At){$.push(new ye(At,cr)),he+=At.length;continue e}if(It==="'"||It==='"'){++he;const At=Ye(cr=>cr!==It);$.push(new ye(At,z.StringLiteral)),++he;continue}if(Ee(It)){const At=Ye(Ee);$.push(new ye(At,z.NumericLiteral));continue}if(Te(It)){const At=Ye(Te),cr=Object.hasOwn(me,At)?me[At]:z.Identifier;cr===z.In&&((ct=$.at(-1))==null?void 0:ct.type)===z.Not?($.pop(),$.push(new ye("not in",z.NotIn))):$.push(new ye(At,cr));continue}throw new SyntaxError(`Unexpected character: ${It}`)}return $}var te=class{constructor(){xe(this,"type","Statement")}},ne=class extends te{constructor(q){super();xe(this,"type","Program");this.body=q}},_e=class extends te{constructor(q,$,Q){super();xe(this,"type","If");this.test=q,this.body=$,this.alternate=Q}},ce=class extends te{constructor(q,$,Q,he){super();xe(this,"type","For");this.loopvar=q,this.iterable=$,this.body=Q,this.defaultBlock=he}},D=class extends te{constructor(q,$){super();xe(this,"type","Set");this.assignee=q,this.value=$}},K=class extends te{constructor(q,$,Q){super();xe(this,"type","Macro");this.name=q,this.args=$,this.body=Q}},re=class extends te{constructor(){super(...arguments);xe(this,"type","Expression")}},ie=class extends re{constructor(q,$,Q){super();xe(this,"type","MemberExpression");this.object=q,this.property=$,this.computed=Q}},X=class extends re{constructor(q,$){super();xe(this,"type","CallExpression");this.callee=q,this.args=$}},R=class extends re{constructor(q){super();xe(this,"type","Identifier");this.value=q}},I=class extends re{constructor(q){super();xe(this,"type","Literal");this.value=q}},L=class extends I{constructor(){super(...arguments);xe(this,"type","NumericLiteral")}},k=class extends I{constructor(){super(...arguments);xe(this,"type","StringLiteral")}},de=class extends I{constructor(){super(...arguments);xe(this,"type","BooleanLiteral")}},Me=class extends I{constructor(){super(...arguments);xe(this,"type","ArrayLiteral")}},ke=class extends I{constructor(){super(...arguments);xe(this,"type","TupleLiteral")}},ze=class extends I{constructor(){super(...arguments);xe(this,"type","ObjectLiteral")}},Ie=class extends re{constructor(q,$,Q){super();xe(this,"type","BinaryExpression");this.operator=q,this.left=$,this.right=Q}},Ze=class extends re{constructor(q,$){super();xe(this,"type","FilterExpression");this.operand=q,this.filter=$}},Ke=class extends re{constructor(q,$){super();xe(this,"type","SelectExpression");this.iterable=q,this.test=$}},ut=class extends re{constructor(q,$,Q){super();xe(this,"type","TestExpression");this.operand=q,this.negate=$,this.test=Q}},we=class extends re{constructor(q,$){super();xe(this,"type","UnaryExpression");this.operator=q,this.argument=$}},W=class extends re{constructor(q=void 0,$=void 0,Q=void 0){super();xe(this,"type","SliceExpression");this.start=q,this.stop=$,this.step=Q}},fe=class extends re{constructor(q,$){super();xe(this,"type","KeywordArgumentExpression");this.key=q,this.value=$}};function $e(x){const q=new ne([]);let $=0;function Q(be,tt){const st=x[$++];if(!st||st.type!==be)throw new Error(`Parser Error: ${tt}. ${st.type} !== ${be}.`);return st}function he(){switch(x[$].type){case z.Text:return Bt();case z.OpenStatement:return ct();case z.OpenExpression:return Tt();default:throw new SyntaxError(`Unexpected token type: ${x[$].type}`)}}function Ye(...be){return $+be.length<=x.length&&be.some((tt,st)=>tt!==x[$+st].type)}function Je(...be){return $+be.length<=x.length&&be.every((tt,st)=>tt===x[$+st].type)}function Bt(){return new k(Q(z.Text,"Expected text token").value)}function ct(){Q(z.OpenStatement,"Expected opening statement token");let be;switch(x[$].type){case z.Set:++$,be=It(),Q(z.CloseStatement,"Expected closing statement token");break;case z.If:++$,be=At(),Q(z.OpenStatement,"Expected {% token"),Q(z.EndIf,"Expected endif token"),Q(z.CloseStatement,"Expected %} token");break;case z.Macro:++$,be=cr(),Q(z.OpenStatement,"Expected {% token"),Q(z.EndMacro,"Expected endmacro token"),Q(z.CloseStatement,"Expected %} token");break;case z.For:++$,be=Qr(),Q(z.OpenStatement,"Expected {% token"),Q(z.EndFor,"Expected endfor token"),Q(z.CloseStatement,"Expected %} token");break;default:throw new SyntaxError(`Unknown statement type: ${x[$].type}`)}return be}function Tt(){Q(z.OpenExpression,"Expected opening expression token");const be=Or();return Q(z.CloseExpression,"Expected closing expression token"),be}function It(){const be=Or();if(Je(z.Equals)){++$;const tt=It();return new D(be,tt)}return be}function At(){var qt,wr,Br,Kr,rr,Wr,Vr,Ln;const be=Or();Q(z.CloseStatement,"Expected closing statement token");const tt=[],st=[];for(;!(((qt=x[$])==null?void 0:qt.type)===z.OpenStatement&&(((wr=x[$+1])==null?void 0:wr.type)===z.ElseIf||((Br=x[$+1])==null?void 0:Br.type)===z.Else||((Kr=x[$+1])==null?void 0:Kr.type)===z.EndIf));)tt.push(he());if(((rr=x[$])==null?void 0:rr.type)===z.OpenStatement&&((Wr=x[$+1])==null?void 0:Wr.type)!==z.EndIf)if(++$,Je(z.ElseIf))Q(z.ElseIf,"Expected elseif token"),st.push(At());else for(Q(z.Else,"Expected else token"),Q(z.CloseStatement,"Expected closing statement token");!(((Vr=x[$])==null?void 0:Vr.type)===z.OpenStatement&&((Ln=x[$+1])==null?void 0:Ln.type)===z.EndIf);)st.push(he());return new _e(be,tt,st)}function cr(){const be=Gt();if(be.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");const tt=gt();Q(z.CloseStatement,"Expected closing statement token");const st=[];for(;Ye(z.OpenStatement,z.EndMacro);)st.push(he());return new K(be,tt,st)}function Er(be=!1){const tt=be?Gt:Or,st=[tt()],qt=Je(z.Comma);for(;qt&&(++$,st.push(tt()),!!Je(z.Comma)););return qt?new ke(st):st[0]}function Qr(){const be=Er(!0);if(!(be instanceof R||be instanceof ke))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${be.type} instead`);Q(z.In,"Expected `in` keyword following loop variable");const tt=Or();Q(z.CloseStatement,"Expected closing statement token");const st=[];for(;Ye(z.OpenStatement,z.EndFor)&&Ye(z.OpenStatement,z.Else);)st.push(he());const qt=[];if(Je(z.OpenStatement,z.Else))for(++$,++$,Q(z.CloseStatement,"Expected closing statement token");Ye(z.OpenStatement,z.EndFor);)qt.push(he());return new ce(be,tt,st,qt)}function Or(){return Ur()}function Ur(){const be=at();if(Je(z.If)){++$;const tt=at();if(Je(z.Else)){++$;const st=at();return new _e(tt,[be],[st])}else return new Ke(be,tt)}return be}function at(){let be=U();for(;Je(z.Or);){const tt=x[$];++$;const st=U();be=new Ie(tt,be,st)}return be}function U(){let be=ge();for(;Je(z.And);){const tt=x[$];++$;const st=ge();be=new Ie(tt,be,st)}return be}function ge(){let be;for(;Je(z.Not);){const tt=x[$];++$;const st=ge();be=new we(tt,st)}return be??Ae()}function Ae(){let be=et();for(;Je(z.ComparisonBinaryOperator)||Je(z.In)||Je(z.NotIn);){const tt=x[$];++$;const st=et();be=new Ie(tt,be,st)}return be}function et(){let be=zt();for(;Je(z.AdditiveBinaryOperator);){const tt=x[$];++$;const st=zt();be=new Ie(tt,be,st)}return be}function ve(){const be=ft();return Je(z.OpenParen)?Xe(be):be}function Xe(be){let tt=new X(be,gt());return Je(z.OpenParen)&&(tt=Xe(tt)),tt}function gt(){Q(z.OpenParen,"Expected opening parenthesis for arguments list");const be=mt();return Q(z.CloseParen,"Expected closing parenthesis for arguments list"),be}function mt(){const be=[];for(;!Je(z.CloseParen);){let tt=Or();if(Je(z.Equals)){if(++$,!(tt instanceof R))throw new SyntaxError("Expected identifier for keyword argument");const st=Or();tt=new fe(tt,st)}be.push(tt),Je(z.Comma)&&++$}return be}function $t(){const be=[];let tt=!1;for(;!Je(z.CloseSquareBracket);)Je(z.Colon)?(be.push(void 0),++$,tt=!0):(be.push(Or()),Je(z.Colon)&&(++$,tt=!0));if(be.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(tt){if(be.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new W(...be)}return be[0]}function ft(){let be=Gt();for(;Je(z.Dot)||Je(z.OpenSquareBracket);){const tt=x[$];++$;let st;const qt=tt.type!==z.Dot;if(qt)st=$t(),Q(z.CloseSquareBracket,"Expected closing square bracket");else if(st=Gt(),st.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");be=new ie(be,st,qt)}return be}function zt(){let be=Nt();for(;Je(z.MultiplicativeBinaryOperator);){const tt=x[$];++$;const st=Nt();be=new Ie(tt,be,st)}return be}function Nt(){let be=Rt();for(;Je(z.Is);){++$;const tt=Je(z.Not);tt&&++$;let st=Gt();if(st instanceof de&&(st=new R(st.value.toString())),!(st instanceof R))throw new SyntaxError("Expected identifier for the test");be=new ut(be,tt,st)}return be}function Rt(){let be=ve();for(;Je(z.Pipe);){++$;let tt=Gt();if(!(tt instanceof R))throw new SyntaxError("Expected identifier for the filter");Je(z.OpenParen)&&(tt=Xe(tt)),be=new Ze(be,tt)}return be}function Gt(){const be=x[$];switch(be.type){case z.NumericLiteral:return++$,new L(Number(be.value));case z.StringLiteral:return++$,new k(be.value);case z.BooleanLiteral:return++$,new de(be.value.toLowerCase()==="true");case z.Identifier:return++$,new R(be.value);case z.OpenParen:{++$;const tt=Er();if(x[$].type!==z.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${x[$].type} instead`);return++$,tt}case z.OpenSquareBracket:{++$;const tt=[];for(;!Je(z.CloseSquareBracket);)tt.push(Or()),Je(z.Comma)&&++$;return++$,new Me(tt)}case z.OpenCurlyBracket:{++$;const tt=new Map;for(;!Je(z.CloseCurlyBracket);){const st=Or();Q(z.Colon,"Expected colon between key and value in object literal");const qt=Or();tt.set(st,qt),Je(z.Comma)&&++$}return++$,new ze(tt)}default:throw new SyntaxError(`Unexpected token: ${be.type}`)}}for(;$=0?(q=(q??(q=0))<0?Math.max(x.length+q,0):Math.min(q,x.length),$=($??($=x.length))<0?Math.max(x.length+$,0):Math.min($,x.length)):(q=(q??(q=x.length-1))<0?Math.max(x.length+q,-1):Math.min(q,x.length-1),$=($??($=-1))<-1?Math.max(x.length+$,-1):Math.min($,x.length-1));const Ye=[];for(let Je=q;he*Jeq.toUpperCase())}var nt=class{constructor(x=void 0){xe(this,"type","RuntimeValue");xe(this,"value");xe(this,"builtins",new Map);this.value=x}__bool__(){return new ht(!!this.value)}},ot=class extends nt{constructor(){super(...arguments);xe(this,"type","NumericValue")}},Re=class extends nt{constructor(){super(...arguments);xe(this,"type","StringValue");xe(this,"builtins",new Map([["upper",new Ne(()=>new Re(this.value.toUpperCase()))],["lower",new Ne(()=>new Re(this.value.toLowerCase()))],["strip",new Ne(()=>new Re(this.value.trim()))],["title",new Ne(()=>new Re(dt(this.value)))],["length",new ot(this.value.length)]]))}},ht=class extends nt{constructor(){super(...arguments);xe(this,"type","BooleanValue")}},bt=class extends nt{constructor(){super(...arguments);xe(this,"type","ObjectValue");xe(this,"builtins",new Map([["get",new Ne(([q,$])=>{if(!(q instanceof Re))throw new Error(`Object key must be a string: got ${q.type}`);return this.value.get(q.value)??$??new Qe})],["items",new Ne(()=>new ee(Array.from(this.value.entries()).map(([q,$])=>new ee([new Re(q),$]))))]]))}__bool__(){return new ht(this.value.size>0)}},qe=class extends bt{constructor(){super(...arguments);xe(this,"type","KeywordArgumentsValue")}},ee=class extends nt{constructor(){super(...arguments);xe(this,"type","ArrayValue");xe(this,"builtins",new Map([["length",new ot(this.value.length)]]))}__bool__(){return new ht(this.value.length>0)}},Pe=class extends ee{constructor(){super(...arguments);xe(this,"type","TupleValue")}},Ne=class extends nt{constructor(){super(...arguments);xe(this,"type","FunctionValue")}},Qe=class extends nt{constructor(){super(...arguments);xe(this,"type","NullValue")}},Ue=class extends nt{constructor(){super(...arguments);xe(this,"type","UndefinedValue")}},je=class{constructor(x){xe(this,"variables",new Map([["namespace",new Ne(x=>{if(x.length===0)return new bt(new Map);if(x.length!==1||!(x[0]instanceof bt))throw new Error("`namespace` expects either zero arguments or a single object argument");return x[0]})]]));xe(this,"tests",new Map([["boolean",x=>x.type==="BooleanValue"],["callable",x=>x instanceof Ne],["odd",x=>{if(x.type!=="NumericValue")throw new Error(`Cannot apply test "odd" to type: ${x.type}`);return x.value%2!==0}],["even",x=>{if(x.type!=="NumericValue")throw new Error(`Cannot apply test "even" to type: ${x.type}`);return x.value%2===0}],["false",x=>x.type==="BooleanValue"&&!x.value],["true",x=>x.type==="BooleanValue"&&x.value],["string",x=>x.type==="StringValue"],["number",x=>x.type==="NumericValue"],["integer",x=>x.type==="NumericValue"&&Number.isInteger(x.value)],["iterable",x=>x instanceof ee||x instanceof Re],["lower",x=>{const q=x.value;return x.type==="StringValue"&&q===q.toLowerCase()}],["upper",x=>{const q=x.value;return x.type==="StringValue"&&q===q.toUpperCase()}],["none",x=>x.type==="NullValue"],["defined",x=>x.type!=="UndefinedValue"],["undefined",x=>x.type==="UndefinedValue"],["equalto",(x,q)=>x.value===q.value],["eq",(x,q)=>x.value===q.value]]));this.parent=x}set(x,q){return this.declareVariable(x,yt(q))}declareVariable(x,q){if(this.variables.has(x))throw new SyntaxError(`Variable already declared: ${x}`);return this.variables.set(x,q),q}setVariable(x,q){return this.variables.set(x,q),q}resolve(x){if(this.variables.has(x))return this;if(this.parent)return this.parent.resolve(x);throw new Error(`Unknown variable: ${x}`)}lookupVariable(x){try{return this.resolve(x).variables.get(x)??new Ue}catch{return new Ue}}},lt=class{constructor(x){xe(this,"global");this.global=x??new je}run(x){return this.evaluate(x,this.global)}evaluateBinaryExpression(x,q){const $=this.evaluate(x.left,q);switch(x.operator.value){case"and":return $.__bool__().value?this.evaluate(x.right,q):$;case"or":return $.__bool__().value?$:this.evaluate(x.right,q)}const Q=this.evaluate(x.right,q);switch(x.operator.value){case"==":return new ht($.value==Q.value);case"!=":return new ht($.value!=Q.value)}if($ instanceof Ue||Q instanceof Ue)throw new Error("Cannot perform operation on undefined values");if($ instanceof Qe||Q instanceof Qe)throw new Error("Cannot perform operation on null values");if($ instanceof ot&&Q instanceof ot)switch(x.operator.value){case"+":return new ot($.value+Q.value);case"-":return new ot($.value-Q.value);case"*":return new ot($.value*Q.value);case"/":return new ot($.value/Q.value);case"%":return new ot($.value%Q.value);case"<":return new ht($.value":return new ht($.value>Q.value);case">=":return new ht($.value>=Q.value);case"<=":return new ht($.value<=Q.value)}else if($ instanceof ee&&Q instanceof ee)switch(x.operator.value){case"+":return new ee($.value.concat(Q.value))}else if(Q instanceof ee){const he=Q.value.find(Ye=>Ye.value===$.value)!==void 0;switch(x.operator.value){case"in":return new ht(he);case"not in":return new ht(!he)}}if($ instanceof Re||Q instanceof Re)switch(x.operator.value){case"+":return new Re($.value.toString()+Q.value.toString())}if($ instanceof Re&&Q instanceof Re)switch(x.operator.value){case"in":return new ht(Q.value.includes($.value));case"not in":return new ht(!Q.value.includes($.value))}if($ instanceof Re&&Q instanceof bt)switch(x.operator.value){case"in":return new ht(Q.value.has($.value));case"not in":return new ht(!Q.value.has($.value))}throw new SyntaxError(`Unknown operator "${x.operator.value}" between ${$.type} and ${Q.type}`)}evaluateArguments(x,q){const $=[],Q=new Map;for(const he of x)if(he.type==="KeywordArgumentExpression"){const Ye=he;Q.set(Ye.key.value,this.evaluate(Ye.value,q))}else{if(Q.size>0)throw new Error("Positional arguments must come before keyword arguments");$.push(this.evaluate(he,q))}return[$,Q]}evaluateFilterExpression(x,q){const $=this.evaluate(x.operand,q);if(x.filter.type==="Identifier"){const Q=x.filter;if(Q.value==="tojson")return new Re(vt($));if($ instanceof ee)switch(Q.value){case"list":return $;case"first":return $.value[0];case"last":return $.value[$.value.length-1];case"length":return new ot($.value.length);case"reverse":return new ee($.value.reverse());case"sort":return new ee($.value.sort((he,Ye)=>{if(he.type!==Ye.type)throw new Error(`Cannot compare different types: ${he.type} and ${Ye.type}`);switch(he.type){case"NumericValue":return he.value-Ye.value;case"StringValue":return he.value.localeCompare(Ye.value);default:throw new Error(`Cannot compare type: ${he.type}`)}}));default:throw new Error(`Unknown ArrayValue filter: ${Q.value}`)}else if($ instanceof Re)switch(Q.value){case"length":return new ot($.value.length);case"upper":return new Re($.value.toUpperCase());case"lower":return new Re($.value.toLowerCase());case"title":return new Re(dt($.value));case"capitalize":return new Re($.value.charAt(0).toUpperCase()+$.value.slice(1));case"trim":return new Re($.value.trim());case"indent":return new Re($.value.split(` -`).map((he,Ye)=>Ye===0||he.length===0?he:" "+he).join(` -`));case"string":return $;default:throw new Error(`Unknown StringValue filter: ${Q.value}`)}else if($ instanceof ot)switch(Q.value){case"abs":return new ot(Math.abs($.value));default:throw new Error(`Unknown NumericValue filter: ${Q.value}`)}else if($ instanceof bt)switch(Q.value){case"items":return new ee(Array.from($.value.entries()).map(([he,Ye])=>new ee([new Re(he),Ye])));case"length":return new ot($.value.size);default:throw new Error(`Unknown ObjectValue filter: ${Q.value}`)}throw new Error(`Cannot apply filter "${Q.value}" to type: ${$.type}`)}else if(x.filter.type==="CallExpression"){const Q=x.filter;if(Q.callee.type!=="Identifier")throw new Error(`Unknown filter: ${Q.callee.type}`);const he=Q.callee.value;if(he==="tojson"){const[,Ye]=this.evaluateArguments(Q.args,q),Je=Ye.get("indent")??new Qe;if(!(Je instanceof ot||Je instanceof Qe))throw new Error("If set, indent must be a number");return new Re(vt($,Je.value))}if($ instanceof ee){switch(he){case"selectattr":{if($.value.some(It=>!(It instanceof bt)))throw new Error("`selectattr` can only be applied to array of objects");if(Q.args.some(It=>It.type!=="StringLiteral"))throw new Error("arguments of `selectattr` must be strings");const[Ye,Je,Bt]=Q.args.map(It=>this.evaluate(It,q));let ct;if(Je){const It=q.tests.get(Je.value);if(!It)throw new Error(`Unknown test: ${Je.value}`);ct=It}else ct=(...It)=>It[0].__bool__().value;const Tt=$.value.filter(It=>{const At=It.value.get(Ye.value);return At?ct(At,Bt):!1});return new ee(Tt)}case"map":{const[,Ye]=this.evaluateArguments(Q.args,q);if(Ye.has("attribute")){const Je=Ye.get("attribute");if(!(Je instanceof Re))throw new Error("attribute must be a string");const Bt=Ye.get("default"),ct=$.value.map(Tt=>{if(!(Tt instanceof bt))throw new Error("items in map must be an object");return Tt.value.get(Je.value)??Bt??new Ue});return new ee(ct)}else throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${he}`)}else if($ instanceof Re){switch(he){case"indent":{const[Ye,Je]=this.evaluateArguments(Q.args,q),Bt=Ye.at(0)??Je.get("width")??new ot(4);if(!(Bt instanceof ot))throw new Error("width must be a number");const ct=Ye.at(1)??Je.get("first")??new ht(!1),Tt=Ye.at(2)??Je.get("blank")??new ht(!1),It=$.value.split(` -`),At=" ".repeat(Bt.value),cr=It.map((Er,Qr)=>!ct.value&&Qr===0||!Tt.value&&Er.length===0?Er:At+Er);return new Re(cr.join(` -`))}}throw new Error(`Unknown StringValue filter: ${he}`)}else throw new Error(`Cannot apply filter "${he}" to type: ${$.type}`)}throw new Error(`Unknown filter: ${x.filter.type}`)}evaluateTestExpression(x,q){const $=this.evaluate(x.operand,q),Q=q.tests.get(x.test.value);if(!Q)throw new Error(`Unknown test: ${x.test.value}`);const he=Q($);return new ht(x.negate?!he:he)}evaluateUnaryExpression(x,q){const $=this.evaluate(x.argument,q);switch(x.operator.value){case"not":return new ht(!$.value);default:throw new SyntaxError(`Unknown operator: ${x.operator.value}`)}}evalProgram(x,q){return this.evaluateBlock(x.body,q)}evaluateBlock(x,q){let $="";for(const Q of x){const he=this.evaluate(Q,q);he.type!=="NullValue"&&he.type!=="UndefinedValue"&&($+=he.value)}return new Re($)}evaluateIdentifier(x,q){return q.lookupVariable(x.value)}evaluateCallExpression(x,q){const[$,Q]=this.evaluateArguments(x.args,q);Q.size>0&&$.push(new qe(Q));const he=this.evaluate(x.callee,q);if(he.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${he.type}`);return he.value($,q)}evaluateSliceExpression(x,q,$){if(!(x instanceof ee||x instanceof Re))throw new Error("Slice object must be an array or string");const Q=this.evaluate(q.start,$),he=this.evaluate(q.stop,$),Ye=this.evaluate(q.step,$);if(!(Q instanceof ot||Q instanceof Ue))throw new Error("Slice start must be numeric or undefined");if(!(he instanceof ot||he instanceof Ue))throw new Error("Slice stop must be numeric or undefined");if(!(Ye instanceof ot||Ye instanceof Ue))throw new Error("Slice step must be numeric or undefined");return x instanceof ee?new ee(He(x.value,Q.value,he.value,Ye.value)):new Re(He(Array.from(x.value),Q.value,he.value,Ye.value).join(""))}evaluateMemberExpression(x,q){const $=this.evaluate(x.object,q);let Q;if(x.computed){if(x.property.type==="SliceExpression")return this.evaluateSliceExpression($,x.property,q);Q=this.evaluate(x.property,q)}else Q=new Re(x.property.value);let he;if($ instanceof bt){if(!(Q instanceof Re))throw new Error(`Cannot access property with non-string: got ${Q.type}`);he=$.value.get(Q.value)??$.builtins.get(Q.value)}else if($ instanceof ee||$ instanceof Re)if(Q instanceof ot)he=$.value.at(Q.value),$ instanceof Re&&(he=new Re($.value.at(Q.value)));else if(Q instanceof Re)he=$.builtins.get(Q.value);else throw new Error(`Cannot access property with non-string/non-number: got ${Q.type}`);else{if(!(Q instanceof Re))throw new Error(`Cannot access property with non-string: got ${Q.type}`);he=$.builtins.get(Q.value)}return he instanceof nt?he:new Ue}evaluateSet(x,q){const $=this.evaluate(x.value,q);if(x.assignee.type==="Identifier"){const Q=x.assignee.value;q.setVariable(Q,$)}else if(x.assignee.type==="MemberExpression"){const Q=x.assignee,he=this.evaluate(Q.object,q);if(!(he instanceof bt))throw new Error("Cannot assign to member of non-object");if(Q.property.type!=="Identifier")throw new Error("Cannot assign to member with non-identifier property");he.value.set(Q.property.value,$)}else throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(x.assignee)}`);return new Qe}evaluateIf(x,q){const $=this.evaluate(x.test,q);return this.evaluateBlock($.__bool__().value?x.body:x.alternate,q)}evaluateFor(x,q){const $=new je(q);let Q,he;if(x.iterable.type==="SelectExpression"){const Tt=x.iterable;he=this.evaluate(Tt.iterable,$),Q=Tt.test}else he=this.evaluate(x.iterable,$);if(!(he instanceof ee))throw new Error(`Expected iterable type in for loop: got ${he.type}`);const Ye=[],Je=[];for(let Tt=0;TtEr.setVariable(x.loopvar.value,At);else if(x.loopvar.type==="TupleLiteral"){const Er=x.loopvar;if(At.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${At.type}`);const Qr=At;if(Er.value.length!==Qr.value.length)throw new Error(`Too ${Er.value.length>Qr.value.length?"few":"many"} items to unpack`);cr=Or=>{for(let Ur=0;Ur0?Ye[Tt-1]:new Ue],["nextitem",Tt{var Je;const he=new je(Q);$=$.slice();let Ye;((Je=$.at(-1))==null?void 0:Je.type)==="KeywordArgumentsValue"&&(Ye=$.pop());for(let Bt=0;Btthis.evaluate($,q)));case"TupleLiteral":return new Pe(x.value.map($=>this.evaluate($,q)));case"ObjectLiteral":{const $=new Map;for(const[Q,he]of x.value){const Ye=this.evaluate(Q,q);if(!(Ye instanceof Re))throw new Error(`Object keys must be strings: got ${Ye.type}`);$.set(Ye.value,this.evaluate(he,q))}return new bt($)}case"Identifier":return this.evaluateIdentifier(x,q);case"CallExpression":return this.evaluateCallExpression(x,q);case"MemberExpression":return this.evaluateMemberExpression(x,q);case"UnaryExpression":return this.evaluateUnaryExpression(x,q);case"BinaryExpression":return this.evaluateBinaryExpression(x,q);case"FilterExpression":return this.evaluateFilterExpression(x,q);case"TestExpression":return this.evaluateTestExpression(x,q);default:throw new SyntaxError(`Unknown node type: ${x.type}`)}}};function yt(x){switch(typeof x){case"number":return new ot(x);case"string":return new Re(x);case"boolean":return new ht(x);case"undefined":return new Ue;case"object":return x===null?new Qe:Array.isArray(x)?new ee(x.map(yt)):new bt(new Map(Object.entries(x).map(([q,$])=>[q,yt($)])));case"function":return new Ne((q,$)=>{const Q=x(...q.map(he=>he.value))??null;return yt(Q)});default:throw new Error(`Cannot convert to runtime value: ${x}`)}}function vt(x,q,$){const Q=$??0;switch(x.type){case"NullValue":case"UndefinedValue":return"null";case"NumericValue":case"StringValue":case"BooleanValue":return JSON.stringify(x.value);case"ArrayValue":case"ObjectValue":{const he=q?" ".repeat(q):"",Ye=` -`+he.repeat(Q),Je=Ye+he;if(x.type==="ArrayValue"){const Bt=x.value.map(ct=>vt(ct,q,Q+1));return q?`[${Je}${Bt.join(`,${Je}`)}${Ye}]`:`[${Bt.join(", ")}]`}else{const Bt=Array.from(x.value.entries()).map(([ct,Tt])=>{const It=`"${ct}": ${vt(Tt,q,Q+1)}`;return q?`${Je}${It}`:It});return q?`{${Bt.join(",")}${Ye}}`:`{${Bt.join(", ")}}`}}default:throw new Error(`Cannot convert to JSON: ${x.type}`)}}var Et=class{constructor(x){xe(this,"parsed");const q=P(x,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=$e(q)}render(x){const q=new je;q.set("false",!1),q.set("true",!0),q.set("raise_exception",he=>{throw new Error(he)}),q.set("range",Y);for(const[he,Ye]of Object.entries(x))q.set(he,Ye);return new lt(q).run(this.parsed).value}}},"./node_modules/onnxruntime-common/dist/esm/backend-impl.js":(Pt,Ce,N)=>{N.r(Ce),N.d(Ce,{registerBackend:()=>ye,resolveBackendAndExecutionProviders:()=>Ee});const z=new Map,me=[],ye=(j,S,V)=>{if(S&&typeof S.init=="function"&&typeof S.createInferenceSessionHandler=="function"){const P=z.get(j);if(P===void 0)z.set(j,{backend:S,priority:V});else{if(P.priority>V)return;if(P.priority===V&&P.backend!==S)throw new Error(`cannot register backend "${j}" using priority ${V}`)}if(V>=0){const te=me.indexOf(j);te!==-1&&me.splice(te,1);for(let ne=0;ne{const S=z.get(j);if(!S)return"backend not found.";if(S.initialized)return S.backend;if(S.aborted)return S.error;{const V=!!S.initPromise;try{return V||(S.initPromise=S.backend.init(j)),await S.initPromise,S.initialized=!0,S.backend}catch(P){return V||(S.error=`${P}`,S.aborted=!0),S.error}finally{delete S.initPromise}}},Ee=async j=>{const S=j.executionProviders||[],V=S.map(D=>typeof D=="string"?D:D.name),P=V.length===0?me:V;let te;const ne=[],_e=new Set;for(const D of P){const K=await Te(D);typeof K=="string"?ne.push({name:D,err:K}):(te||(te=K),te===K&&_e.add(D))}if(!te)throw new Error(`no available backend found. ERR: ${ne.map(D=>`[${D.name}] ${D.err}`).join(", ")}`);for(const{name:D,err:K}of ne)V.includes(D)&&console.warn(`removing requested execution provider "${D}" from session options because it is not available: ${K}`);const ce=S.filter(D=>_e.has(typeof D=="string"?D:D.name));return[te,new Proxy(j,{get:(D,K)=>K==="executionProviders"?ce:Reflect.get(D,K)})]}},"./node_modules/onnxruntime-common/dist/esm/backend.js":(Pt,Ce,N)=>{N.r(Ce),N.d(Ce,{registerBackend:()=>z.registerBackend});var z=N("./node_modules/onnxruntime-common/dist/esm/backend-impl.js")},"./node_modules/onnxruntime-common/dist/esm/env-impl.js":(Pt,Ce,N)=>{N.r(Ce),N.d(Ce,{env:()=>ye});var z=N("./node_modules/onnxruntime-common/dist/esm/version.js");let me="warning";const ye={wasm:{},webgl:{},webgpu:{},versions:{common:z.version},set logLevel(Te){if(Te!==void 0){if(typeof Te!="string"||["verbose","info","warning","error","fatal"].indexOf(Te)===-1)throw new Error(`Unsupported logging level: ${Te}`);me=Te}},get logLevel(){return me}};Object.defineProperty(ye,"logLevel",{enumerable:!0})},"./node_modules/onnxruntime-common/dist/esm/env.js":(Pt,Ce,N)=>{N.r(Ce),N.d(Ce,{env:()=>me});var z=N("./node_modules/onnxruntime-common/dist/esm/env-impl.js");const me=z.env},"./node_modules/onnxruntime-common/dist/esm/index.js":(Pt,Ce,N)=>{N.r(Ce),N.d(Ce,{InferenceSession:()=>ye.InferenceSession,TRACE:()=>Ee.TRACE,TRACE_FUNC_BEGIN:()=>Ee.TRACE_FUNC_BEGIN,TRACE_FUNC_END:()=>Ee.TRACE_FUNC_END,Tensor:()=>Te.Tensor,TrainingSession:()=>j.TrainingSession,env:()=>me.env,registerBackend:()=>z.registerBackend});var z=N("./node_modules/onnxruntime-common/dist/esm/backend.js"),me=N("./node_modules/onnxruntime-common/dist/esm/env.js"),ye=N("./node_modules/onnxruntime-common/dist/esm/inference-session.js"),Te=N("./node_modules/onnxruntime-common/dist/esm/tensor.js");N("./node_modules/onnxruntime-common/dist/esm/tensor-conversion.js"),N("./node_modules/onnxruntime-common/dist/esm/tensor-factory.js");var Ee=N("./node_modules/onnxruntime-common/dist/esm/trace.js");N("./node_modules/onnxruntime-common/dist/esm/onnx-model.js"),N("./node_modules/onnxruntime-common/dist/esm/onnx-value.js");var j=N("./node_modules/onnxruntime-common/dist/esm/training-session.js")},"./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js":(Pt,Ce,N)=>{N.r(Ce),N.d(Ce,{InferenceSession:()=>Te});var z=N("./node_modules/onnxruntime-common/dist/esm/backend-impl.js"),me=N("./node_modules/onnxruntime-common/dist/esm/tensor.js"),ye=N("./node_modules/onnxruntime-common/dist/esm/trace.js");class Te{constructor(j){this.handler=j}async run(j,S,V){(0,ye.TRACE_FUNC_BEGIN)();const P={};let te={};if(typeof j!="object"||j===null||j instanceof me.Tensor||Array.isArray(j))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let ne=!0;if(typeof S=="object"){if(S===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(S instanceof me.Tensor)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(S)){if(S.length===0)throw new TypeError("'fetches' cannot be an empty array.");ne=!1;for(const D of S){if(typeof D!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(D)===-1)throw new RangeError(`'fetches' contains invalid output name: ${D}.`);P[D]=null}if(typeof V=="object"&&V!==null)te=V;else if(typeof V<"u")throw new TypeError("'options' must be an object.")}else{let D=!1;const K=Object.getOwnPropertyNames(S);for(const re of this.outputNames)if(K.indexOf(re)!==-1){const ie=S[re];(ie===null||ie instanceof me.Tensor)&&(D=!0,ne=!1,P[re]=ie)}if(D){if(typeof V=="object"&&V!==null)te=V;else if(typeof V<"u")throw new TypeError("'options' must be an object.")}else te=S}}else if(typeof S<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const D of this.inputNames)if(typeof j[D]>"u")throw new Error(`input '${D}' is missing in 'feeds'.`);if(ne)for(const D of this.outputNames)P[D]=null;const _e=await this.handler.run(j,P,te),ce={};for(const D in _e)if(Object.hasOwnProperty.call(_e,D)){const K=_e[D];K instanceof me.Tensor?ce[D]=K:ce[D]=new me.Tensor(K.type,K.data,K.dims)}return(0,ye.TRACE_FUNC_END)(),ce}async release(){return this.handler.dispose()}static async create(j,S,V,P){(0,ye.TRACE_FUNC_BEGIN)();let te,ne={};if(typeof j=="string"){if(te=j,typeof S=="object"&&S!==null)ne=S;else if(typeof S<"u")throw new TypeError("'options' must be an object.")}else if(j instanceof Uint8Array){if(te=j,typeof S=="object"&&S!==null)ne=S;else if(typeof S<"u")throw new TypeError("'options' must be an object.")}else if(j instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&j instanceof SharedArrayBuffer){const K=j;let re=0,ie=j.byteLength;if(typeof S=="object"&&S!==null)ne=S;else if(typeof S=="number"){if(re=S,!Number.isSafeInteger(re))throw new RangeError("'byteOffset' must be an integer.");if(re<0||re>=K.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${K.byteLength}).`);if(ie=j.byteLength-re,typeof V=="number"){if(ie=V,!Number.isSafeInteger(ie))throw new RangeError("'byteLength' must be an integer.");if(ie<=0||re+ie>K.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${K.byteLength-re}].`);if(typeof P=="object"&&P!==null)ne=P;else if(typeof P<"u")throw new TypeError("'options' must be an object.")}else if(typeof V<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof S<"u")throw new TypeError("'options' must be an object.");te=new Uint8Array(K,re,ie)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");const[_e,ce]=await(0,z.resolveBackendAndExecutionProviders)(ne),D=await _e.createInferenceSessionHandler(te,ce);return(0,ye.TRACE_FUNC_END)(),new Te(D)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}},"./node_modules/onnxruntime-common/dist/esm/inference-session.js":(Pt,Ce,N)=>{N.r(Ce),N.d(Ce,{InferenceSession:()=>me});var z=N("./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js");const me=z.InferenceSession},"./node_modules/onnxruntime-common/dist/esm/onnx-model.js":(Pt,Ce,N)=>{N.r(Ce)},"./node_modules/onnxruntime-common/dist/esm/onnx-value.js":(Pt,Ce,N)=>{N.r(Ce)},"./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js":(Pt,Ce,N)=>{N.r(Ce),N.d(Ce,{tensorToDataURL:()=>z,tensorToImageData:()=>me});const z=(ye,Te)=>{const Ee=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);Ee.width=ye.dims[3],Ee.height=ye.dims[2];const j=Ee.getContext("2d");if(j!=null){let S,V;(Te==null?void 0:Te.tensorLayout)!==void 0&&Te.tensorLayout==="NHWC"?(S=ye.dims[2],V=ye.dims[3]):(S=ye.dims[3],V=ye.dims[2]);const P=(Te==null?void 0:Te.format)!==void 0?Te.format:"RGB",te=Te==null?void 0:Te.norm;let ne,_e;te===void 0||te.mean===void 0?ne=[255,255,255,255]:typeof te.mean=="number"?ne=[te.mean,te.mean,te.mean,te.mean]:(ne=[te.mean[0],te.mean[1],te.mean[2],0],te.mean[3]!==void 0&&(ne[3]=te.mean[3])),te===void 0||te.bias===void 0?_e=[0,0,0,0]:typeof te.bias=="number"?_e=[te.bias,te.bias,te.bias,te.bias]:(_e=[te.bias[0],te.bias[1],te.bias[2],0],te.bias[3]!==void 0&&(_e[3]=te.bias[3]));const ce=V*S;let D=0,K=ce,re=ce*2,ie=-1;P==="RGBA"?(D=0,K=ce,re=ce*2,ie=ce*3):P==="RGB"?(D=0,K=ce,re=ce*2):P==="RBG"&&(D=0,re=ce,K=ce*2);for(let X=0;X{const Ee=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");let j;if(Ee!=null){let S,V,P;(Te==null?void 0:Te.tensorLayout)!==void 0&&Te.tensorLayout==="NHWC"?(S=ye.dims[2],V=ye.dims[1],P=ye.dims[3]):(S=ye.dims[3],V=ye.dims[2],P=ye.dims[1]);const te=Te!==void 0&&Te.format!==void 0?Te.format:"RGB",ne=Te==null?void 0:Te.norm;let _e,ce;ne===void 0||ne.mean===void 0?_e=[255,255,255,255]:typeof ne.mean=="number"?_e=[ne.mean,ne.mean,ne.mean,ne.mean]:(_e=[ne.mean[0],ne.mean[1],ne.mean[2],255],ne.mean[3]!==void 0&&(_e[3]=ne.mean[3])),ne===void 0||ne.bias===void 0?ce=[0,0,0,0]:typeof ne.bias=="number"?ce=[ne.bias,ne.bias,ne.bias,ne.bias]:(ce=[ne.bias[0],ne.bias[1],ne.bias[2],0],ne.bias[3]!==void 0&&(ce[3]=ne.bias[3]));const D=V*S;if(Te!==void 0&&(Te.format!==void 0&&P===4&&Te.format!=="RGBA"||P===3&&Te.format!=="RGB"&&Te.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");const K=4;let re=0,ie=1,X=2,R=3,I=0,L=D,k=D*2,de=-1;te==="RGBA"?(I=0,L=D,k=D*2,de=D*3):te==="RGB"?(I=0,L=D,k=D*2):te==="RBG"&&(I=0,k=D,L=D*2),j=Ee.createImageData(S,V);for(let Me=0;Me{N.r(Ce)},"./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js":(Pt,Ce,N)=>{N.r(Ce),N.d(Ce,{bufferToTensor:()=>me,tensorFromGpuBuffer:()=>Ee,tensorFromImage:()=>ye,tensorFromPinnedBuffer:()=>j,tensorFromTexture:()=>Te});var z=N("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const me=(S,V)=>{if(S===void 0)throw new Error("Image buffer must be defined");if(V.height===void 0||V.width===void 0)throw new Error("Image height and width must be defined");if(V.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");const{height:P,width:te}=V,ne=V.norm??{mean:255,bias:0};let _e,ce;typeof ne.mean=="number"?_e=[ne.mean,ne.mean,ne.mean,ne.mean]:_e=[ne.mean[0],ne.mean[1],ne.mean[2],ne.mean[3]??255],typeof ne.bias=="number"?ce=[ne.bias,ne.bias,ne.bias,ne.bias]:ce=[ne.bias[0],ne.bias[1],ne.bias[2],ne.bias[3]??0];const D=V.format!==void 0?V.format:"RGBA",K=V.tensorFormat!==void 0&&V.tensorFormat!==void 0?V.tensorFormat:"RGB",re=P*te,ie=K==="RGBA"?new Float32Array(re*4):new Float32Array(re*3);let X=4,R=0,I=1,L=2,k=3,de=0,Me=re,ke=re*2,ze=-1;D==="RGB"&&(X=3,R=0,I=1,L=2,k=-1),K==="RGBA"?ze=re*3:K==="RBG"?(de=0,ke=re,Me=re*2):K==="BGR"&&(ke=0,Me=re,de=re*2);for(let Ze=0;Ze{const P=typeof HTMLImageElement<"u"&&S instanceof HTMLImageElement,te=typeof ImageData<"u"&&S instanceof ImageData,ne=typeof ImageBitmap<"u"&&S instanceof ImageBitmap,_e=typeof S=="string";let ce,D=V??{};const K=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},re=ie=>ie instanceof HTMLCanvasElement||ie instanceof OffscreenCanvas?ie.getContext("2d"):null;if(P){const ie=K();ie.width=S.width,ie.height=S.height;const X=re(ie);if(X!=null){let R=S.height,I=S.width;if(V!==void 0&&V.resizedHeight!==void 0&&V.resizedWidth!==void 0&&(R=V.resizedHeight,I=V.resizedWidth),V!==void 0){if(D=V,V.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");D.tensorFormat="RGBA",D.height=R,D.width=I}else D.tensorFormat="RGBA",D.height=R,D.width=I;X.drawImage(S,0,0),ce=X.getImageData(0,0,I,R).data}else throw new Error("Can not access image data")}else if(te){let ie,X;if(V!==void 0&&V.resizedWidth!==void 0&&V.resizedHeight!==void 0?(ie=V.resizedHeight,X=V.resizedWidth):(ie=S.height,X=S.width),V!==void 0&&(D=V),D.format="RGBA",D.height=ie,D.width=X,V!==void 0){const R=K();R.width=X,R.height=ie;const I=re(R);if(I!=null)I.putImageData(S,0,0),ce=I.getImageData(0,0,X,ie).data;else throw new Error("Can not access image data")}else ce=S.data}else if(ne){if(V===void 0)throw new Error("Please provide image config with format for Imagebitmap");const ie=K();ie.width=S.width,ie.height=S.height;const X=re(ie);if(X!=null){const R=S.height,I=S.width;return X.drawImage(S,0,0,I,R),ce=X.getImageData(0,0,I,R).data,D.height=R,D.width=I,me(ce,D)}else throw new Error("Can not access image data")}else{if(_e)return new Promise((ie,X)=>{const R=K(),I=re(R);if(!S||!I)return X();const L=new Image;L.crossOrigin="Anonymous",L.src=S,L.onload=()=>{R.width=L.width,R.height=L.height,I.drawImage(L,0,0,R.width,R.height);const k=I.getImageData(0,0,R.width,R.height);D.height=R.height,D.width=R.width,ie(me(k.data,D))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(ce!==void 0)return me(ce,D);throw new Error("Input data provided is not supported - aborted tensor creation")},Te=(S,V)=>{const{width:P,height:te,download:ne,dispose:_e}=V,ce=[1,te,P,4];return new z.Tensor({location:"texture",type:"float32",texture:S,dims:ce,download:ne,dispose:_e})},Ee=(S,V)=>{const{dataType:P,dims:te,download:ne,dispose:_e}=V;return new z.Tensor({location:"gpu-buffer",type:P??"float32",gpuBuffer:S,dims:te,download:ne,dispose:_e})},j=(S,V,P)=>new z.Tensor({location:"cpu-pinned",type:S,data:V,dims:P??[V.length]})},"./node_modules/onnxruntime-common/dist/esm/tensor-factory.js":(Pt,Ce,N)=>{N.r(Ce)},"./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js":(Pt,Ce,N)=>{N.r(Ce),N.d(Ce,{NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP:()=>me,NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP:()=>z,checkTypedArray:()=>Te});const z=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array]]),me=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);let ye=!1;const Te=()=>{if(!ye){ye=!0;const Ee=typeof BigInt64Array<"u"&&BigInt64Array.from,j=typeof BigUint64Array<"u"&&BigUint64Array.from,S=typeof Float16Array<"u"&&Float16Array.from;Ee&&(z.set("int64",BigInt64Array),me.set(BigInt64Array,"int64")),j&&(z.set("uint64",BigUint64Array),me.set(BigUint64Array,"uint64")),S?(z.set("float16",Float16Array),me.set(Float16Array,"float16")):z.set("float16",Uint16Array)}}},"./node_modules/onnxruntime-common/dist/esm/tensor-impl.js":(Pt,Ce,N)=>{N.r(Ce),N.d(Ce,{Tensor:()=>Ee});var z=N("./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js"),me=N("./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js"),ye=N("./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js"),Te=N("./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js");class Ee{constructor(S,V,P){(0,ye.checkTypedArray)();let te,ne;if(typeof S=="object"&&"location"in S)switch(this.dataLocation=S.location,te=S.type,ne=S.dims,S.location){case"cpu-pinned":{const ce=ye.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(te);if(!ce)throw new TypeError(`unsupported type "${te}" to create tensor from pinned buffer`);if(!(S.data instanceof ce))throw new TypeError(`buffer should be of type ${ce.name}`);this.cpuData=S.data;break}case"texture":{if(te!=="float32")throw new TypeError(`unsupported type "${te}" to create tensor from texture`);this.gpuTextureData=S.texture,this.downloader=S.download,this.disposer=S.dispose;break}case"gpu-buffer":{if(te!=="float32"&&te!=="float16"&&te!=="int32"&&te!=="int64"&&te!=="uint32"&&te!=="uint8"&&te!=="bool")throw new TypeError(`unsupported type "${te}" to create tensor from gpu buffer`);this.gpuBufferData=S.gpuBuffer,this.downloader=S.download,this.disposer=S.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let ce,D;if(typeof S=="string")if(te=S,D=P,S==="string"){if(!Array.isArray(V))throw new TypeError("A string tensor's data must be a string array.");ce=V}else{const K=ye.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(S);if(K===void 0)throw new TypeError(`Unsupported tensor type: ${S}.`);if(Array.isArray(V)){if(S==="float16"&&K===Uint16Array)throw new TypeError("Creating a float16 tensor from number array is not supported. Please use Uint16Array as data.");S==="uint64"||S==="int64"?ce=K.from(V,BigInt):ce=K.from(V)}else if(V instanceof K)ce=V;else throw new TypeError(`A ${te} tensor's data must be type of ${K}`)}else if(D=V,Array.isArray(S)){if(S.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");const K=typeof S[0];if(K==="string")te="string",ce=S;else if(K==="boolean")te="bool",ce=Uint8Array.from(S);else throw new TypeError(`Invalid element type of data array: ${K}.`)}else{const K=ye.NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.get(S.constructor);if(K===void 0)throw new TypeError(`Unsupported type for tensor data: ${S.constructor}.`);te=K,ce=S}if(D===void 0)D=[ce.length];else if(!Array.isArray(D))throw new TypeError("A tensor's dims must be a number array");ne=D,this.cpuData=ce,this.dataLocation="cpu"}const _e=(0,Te.calculateSize)(ne);if(this.cpuData&&_e!==this.cpuData.length)throw new Error(`Tensor's size(${_e}) does not match data length(${this.cpuData.length}).`);this.type=te,this.dims=ne,this.size=_e}static async fromImage(S,V){return(0,me.tensorFromImage)(S,V)}static fromTexture(S,V){return(0,me.tensorFromTexture)(S,V)}static fromGpuBuffer(S,V){return(0,me.tensorFromGpuBuffer)(S,V)}static fromPinnedBuffer(S,V,P){return(0,me.tensorFromPinnedBuffer)(S,V,P)}toDataURL(S){return(0,z.tensorToDataURL)(this,S)}toImageData(S){return(0,z.tensorToImageData)(this,S)}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(S){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;const V=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=V,S&&this.disposer&&(this.disposer(),this.disposer=void 0),V}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(S){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return(0,Te.tensorReshape)(this,S)}}},"./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js":(Pt,Ce,N)=>{N.r(Ce),N.d(Ce,{calculateSize:()=>me,tensorReshape:()=>ye});var z=N("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const me=Te=>{let Ee=1;for(let j=0;j{switch(Te.location){case"cpu":return new z.Tensor(Te.type,Te.data,Ee);case"cpu-pinned":return new z.Tensor({location:"cpu-pinned",data:Te.data,type:Te.type,dims:Ee});case"texture":return new z.Tensor({location:"texture",texture:Te.texture,type:Te.type,dims:Ee});case"gpu-buffer":return new z.Tensor({location:"gpu-buffer",gpuBuffer:Te.gpuBuffer,type:Te.type,dims:Ee});default:throw new Error(`tensorReshape: tensor location ${Te.location} is not supported`)}}},"./node_modules/onnxruntime-common/dist/esm/tensor.js":(Pt,Ce,N)=>{N.r(Ce),N.d(Ce,{Tensor:()=>me});var z=N("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const me=z.Tensor},"./node_modules/onnxruntime-common/dist/esm/trace.js":(Pt,Ce,N)=>{N.r(Ce),N.d(Ce,{TRACE:()=>me,TRACE_FUNC_BEGIN:()=>Te,TRACE_FUNC_END:()=>Ee});var z=N("./node_modules/onnxruntime-common/dist/esm/env-impl.js");const me=(j,S)=>{(typeof z.env.trace>"u"?!z.env.wasm.trace:!z.env.trace)||console.timeStamp(`${j}::ORT::${S}`)},ye=(j,S)=>{var te;const V=((te=new Error().stack)==null?void 0:te.split(/\r\n|\r|\n/g))||[];let P=!1;for(let ne=0;ne{(typeof z.env.trace>"u"?!z.env.wasm.trace:!z.env.trace)||ye("BEGIN",j)},Ee=j=>{(typeof z.env.trace>"u"?!z.env.wasm.trace:!z.env.trace)||ye("END",j)}},"./node_modules/onnxruntime-common/dist/esm/training-session-impl.js":(Pt,Ce,N)=>{N.r(Ce),N.d(Ce,{TrainingSession:()=>Te});var z=N("./node_modules/onnxruntime-common/dist/esm/backend-impl.js"),me=N("./node_modules/onnxruntime-common/dist/esm/tensor.js");const ye="Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.";class Te{constructor(j,S,V){this.handler=j,this.hasOptimizerModel=S,this.hasEvalModel=V}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(j,S){const V=j.evalModel||"",P=j.optimizerModel||"",te=S||{},[ne,_e]=await(0,z.resolveBackendAndExecutionProviders)(te);if(ne.createTrainingSessionHandler){const ce=await ne.createTrainingSessionHandler(j.checkpointState,j.trainModel,V,P,_e);return new Te(ce,!!j.optimizerModel,!!j.evalModel)}else throw new Error(ye)}typeNarrowingForRunStep(j,S,V,P,te){const ne={};let _e={};if(typeof V!="object"||V===null||V instanceof me.Tensor||Array.isArray(V))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let ce=!0;if(typeof P=="object"){if(P===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(P instanceof me.Tensor)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(P)){if(P.length===0)throw new TypeError("'fetches' cannot be an empty array.");ce=!1;for(const D of P){if(typeof D!="string")throw new TypeError("'fetches' must be a string array or an object.");if(S.indexOf(D)===-1)throw new RangeError(`'fetches' contains invalid output name: ${D}.`);ne[D]=null}if(typeof te=="object"&&te!==null)_e=te;else if(typeof te<"u")throw new TypeError("'options' must be an object.")}else{let D=!1;const K=Object.getOwnPropertyNames(P);for(const re of S)if(K.indexOf(re)!==-1){const ie=P[re];(ie===null||ie instanceof me.Tensor)&&(D=!0,ce=!1,ne[re]=ie)}if(D){if(typeof te=="object"&&te!==null)_e=te;else if(typeof te<"u")throw new TypeError("'options' must be an object.")}else _e=P}}else if(typeof P<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const D of j)if(typeof V[D]>"u")throw new Error(`input '${D}' is missing in 'feeds'.`);if(ce)for(const D of S)ne[D]=null;return[ne,_e]}convertHandlerReturnTypeToMapOfTensors(j){const S={};for(const V in j)if(Object.hasOwnProperty.call(j,V)){const P=j[V];P instanceof me.Tensor?S[V]=P:S[V]=new me.Tensor(P.type,P.data,P.dims)}return S}async lazyResetGrad(){await this.handler.lazyResetGrad()}async runTrainStep(j,S,V){const[P,te]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,j,S,V),ne=await this.handler.runTrainStep(j,P,te);return this.convertHandlerReturnTypeToMapOfTensors(ne)}async runOptimizerStep(j){if(this.hasOptimizerModel)await this.handler.runOptimizerStep(j||{});else throw new Error("This TrainingSession has no OptimizerModel loaded.")}async runEvalStep(j,S,V){if(this.hasEvalModel){const[P,te]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,j,S,V),ne=await this.handler.runEvalStep(j,P,te);return this.convertHandlerReturnTypeToMapOfTensors(ne)}else throw new Error("This TrainingSession has no EvalModel loaded.")}async getParametersSize(j=!0){return this.handler.getParametersSize(j)}async loadParametersBuffer(j,S=!0){const V=await this.getParametersSize(S);if(j.length!==4*V)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(j,S)}async getContiguousParameters(j=!0){return this.handler.getContiguousParameters(j)}async release(){return this.handler.dispose()}}},"./node_modules/onnxruntime-common/dist/esm/training-session.js":(Pt,Ce,N)=>{N.r(Ce),N.d(Ce,{TrainingSession:()=>me});var z=N("./node_modules/onnxruntime-common/dist/esm/training-session-impl.js");const me=z.TrainingSession},"./node_modules/onnxruntime-common/dist/esm/version.js":(Pt,Ce,N)=>{N.r(Ce),N.d(Ce,{version:()=>z});const z="1.19.2"},"./node_modules/onnxruntime-web/dist/ort.webgpu.bundle.min.mjs":(Pt,Ce,N)=>{N.r(Ce),N.d(Ce,{InferenceSession:()=>Et,TRACE:()=>Ne,TRACE_FUNC_BEGIN:()=>Ue,TRACE_FUNC_END:()=>je,Tensor:()=>ee,TrainingSession:()=>ct,default:()=>em,env:()=>k,registerBackend:()=>_e});/*! - * ONNX Runtime Web v1.20.0-dev.20240928-1bda91fc57 - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */var z=Object.defineProperty,me=Object.getOwnPropertyDescriptor,ye=Object.getOwnPropertyNames,Te=Object.prototype.hasOwnProperty,Ee=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),j=(e,t)=>()=>(e&&(t=e(e=0)),t),S=(e,t)=>{for(var r in t)z(e,r,{get:t[r],enumerable:!0})},V=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of ye(t))!Te.call(e,s)&&s!==r&&z(e,s,{get:()=>t[s],enumerable:!(n=me(t,s))||n.enumerable});return e},P=e=>V(z({},"__esModule",{value:!0}),e),te,ne,_e,ce,D,K=j(()=>{te=new Map,ne=[],_e=(e,t,r)=>{if(t&&typeof t.init=="function"&&typeof t.createInferenceSessionHandler=="function"){let n=te.get(e);if(n===void 0)te.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 s=ne.indexOf(e);s!==-1&&ne.splice(s,1);for(let a=0;a{let t=te.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}}},D=async e=>{let t=e.executionProviders||[],r=t.map(d=>typeof d=="string"?d:d.name),n=r.length===0?ne:r,s,a=[],i=new Set;for(let d of n){let p=await ce(d);typeof p=="string"?a.push({name:d,err:p}):(s||(s=p),s===p&&i.add(d))}if(!s)throw new Error(`no available backend found. ERR: ${a.map(d=>`[${d.name}] ${d.err}`).join(", ")}`);for(let{name:d,err:p}of a)r.includes(d)&&console.warn(`removing requested execution provider "${d}" from session options because it is not available: ${p}`);let u=t.filter(d=>i.has(typeof d=="string"?d:d.name));return[s,new Proxy(e,{get:(d,p)=>p==="executionProviders"?u:Reflect.get(d,p)})]}}),re=j(()=>{K()}),ie,X=j(()=>{ie="1.20.0-dev.20240928-1bda91fc57"}),R,I,L=j(()=>{X(),R="warning",I={wasm:{},webgl:{},webgpu:{},versions:{common:ie},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}`);R=e}},get logLevel(){return R}},Object.defineProperty(I,"logLevel",{enumerable:!0})}),k,de=j(()=>{L(),k=I}),Me,ke,ze=j(()=>{Me=(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 s,a;(t==null?void 0:t.tensorLayout)!==void 0&&t.tensorLayout==="NHWC"?(s=e.dims[2],a=e.dims[3]):(s=e.dims[3],a=e.dims[2]);let i=(t==null?void 0:t.format)!==void 0?t.format:"RGB",u=t==null?void 0:t.norm,d,p;u===void 0||u.mean===void 0?d=[255,255,255,255]:typeof u.mean=="number"?d=[u.mean,u.mean,u.mean,u.mean]:(d=[u.mean[0],u.mean[1],u.mean[2],0],u.mean[3]!==void 0&&(d[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 g=a*s,w=0,l=g,M=g*2,C=-1;i==="RGBA"?(w=0,l=g,M=g*2,C=g*3):i==="RGB"?(w=0,l=g,M=g*2):i==="RBG"&&(w=0,M=g,l=g*2);for(let E=0;E{let r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),n;if(r!=null){let s,a,i;(t==null?void 0:t.tensorLayout)!==void 0&&t.tensorLayout==="NHWC"?(s=e.dims[2],a=e.dims[1],i=e.dims[3]):(s=e.dims[3],a=e.dims[2],i=e.dims[1]);let u=t!==void 0&&t.format!==void 0?t.format:"RGB",d=t==null?void 0:t.norm,p,g;d===void 0||d.mean===void 0?p=[255,255,255,255]:typeof d.mean=="number"?p=[d.mean,d.mean,d.mean,d.mean]:(p=[d.mean[0],d.mean[1],d.mean[2],255],d.mean[3]!==void 0&&(p[3]=d.mean[3])),d===void 0||d.bias===void 0?g=[0,0,0,0]:typeof d.bias=="number"?g=[d.bias,d.bias,d.bias,d.bias]:(g=[d.bias[0],d.bias[1],d.bias[2],0],d.bias[3]!==void 0&&(g[3]=d.bias[3]));let w=a*s;if(t!==void 0&&(t.format!==void 0&&i===4&&t.format!=="RGBA"||i===3&&t.format!=="RGB"&&t.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let l=4,M=0,C=1,E=2,B=3,G=0,O=w,ae=w*2,Z=-1;u==="RGBA"?(G=0,O=w,ae=w*2,Z=w*3):u==="RGB"?(G=0,O=w,ae=w*2):u==="RBG"&&(G=0,ae=w,O=w*2),n=r.createImageData(s,a);for(let le=0;le{qe(),Ie=(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,s=t.norm??{mean:255,bias:0},a,i;typeof s.mean=="number"?a=[s.mean,s.mean,s.mean,s.mean]:a=[s.mean[0],s.mean[1],s.mean[2],s.mean[3]??255],typeof s.bias=="number"?i=[s.bias,s.bias,s.bias,s.bias]:i=[s.bias[0],s.bias[1],s.bias[2],s.bias[3]??0];let u=t.format!==void 0?t.format:"RGBA",d=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:"RGB",p=r*n,g=d==="RGBA"?new Float32Array(p*4):new Float32Array(p*3),w=4,l=0,M=1,C=2,E=3,B=0,G=p,O=p*2,ae=-1;u==="RGB"&&(w=3,l=0,M=1,C=2,E=-1),d==="RGBA"?ae=p*3:d==="RBG"?(B=0,O=p,G=p*2):d==="BGR"&&(O=0,G=p,B=p*2);for(let Z=0;Z{let r=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,n=typeof ImageData<"u"&&e instanceof ImageData,s=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,a=typeof e=="string",i,u=t??{},d=()=>{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=g=>typeof HTMLCanvasElement<"u"&&g instanceof HTMLCanvasElement||g instanceof OffscreenCanvas?g.getContext("2d"):null;if(r){let g=d();g.width=e.width,g.height=e.height;let w=p(g);if(w!=null){let l=e.height,M=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(l=t.resizedHeight,M=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=l,u.width=M}else u.tensorFormat="RGBA",u.height=l,u.width=M;w.drawImage(e,0,0),i=w.getImageData(0,0,M,l).data}else throw new Error("Can not access image data")}else if(n){let g,w;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(g=t.resizedHeight,w=t.resizedWidth):(g=e.height,w=e.width),t!==void 0&&(u=t),u.format="RGBA",u.height=g,u.width=w,t!==void 0){let l=d();l.width=w,l.height=g;let M=p(l);if(M!=null)M.putImageData(e,0,0),i=M.getImageData(0,0,w,g).data;else throw new Error("Can not access image data")}else i=e.data}else if(s){if(t===void 0)throw new Error("Please provide image config with format for Imagebitmap");let g=d();g.width=e.width,g.height=e.height;let w=p(g);if(w!=null){let l=e.height,M=e.width;return w.drawImage(e,0,0,M,l),i=w.getImageData(0,0,M,l).data,u.height=l,u.width=M,Ie(i,u)}else throw new Error("Can not access image data")}else{if(a)return new Promise((g,w)=>{let l=d(),M=p(l);if(!e||!M)return w();let C=new Image;C.crossOrigin="Anonymous",C.src=e,C.onload=()=>{l.width=C.width,l.height=C.height,M.drawImage(C,0,0,l.width,l.height);let E=M.getImageData(0,0,l.width,l.height);u.height=l.height,u.width=l.width,g(Ie(E.data,u))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(i!==void 0)return Ie(i,u);throw new Error("Input data provided is not supported - aborted tensor creation")},Ke=(e,t)=>{let{width:r,height:n,download:s,dispose:a}=t,i=[1,n,r,4];return new bt({location:"texture",type:"float32",texture:e,dims:i,download:s,dispose:a})},ut=(e,t)=>{let{dataType:r,dims:n,download:s,dispose:a}=t;return new bt({location:"gpu-buffer",type:r??"float32",gpuBuffer:e,dims:n,download:s,dispose:a})},we=(e,t)=>{let{dataType:r,dims:n,download:s,dispose:a}=t;return new bt({location:"ml-tensor",type:r??"float32",mlTensor:e,dims:n,download:s,dispose:a})},W=(e,t,r)=>new bt({location:"cpu-pinned",type:e,data:t,dims:r??[t.length]})}),$e,Y,He,dt,nt=j(()=>{$e=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),Y=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),He=!1,dt=()=>{if(!He){He=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,r=typeof Float16Array<"u"&&Float16Array.from;e&&($e.set("int64",BigInt64Array),Y.set(BigInt64Array,"int64")),t&&($e.set("uint64",BigUint64Array),Y.set(BigUint64Array,"uint64")),r?($e.set("float16",Float16Array),Y.set(Float16Array,"float16")):$e.set("float16",Uint16Array)}}}),ot,Re,ht=j(()=>{qe(),ot=e=>{let t=1;for(let r=0;r{switch(e.location){case"cpu":return new bt(e.type,e.data,t);case"cpu-pinned":return new bt({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new bt({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new bt({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case"ml-tensor":return new bt({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),bt,qe=j(()=>{ze(),fe(),nt(),ht(),bt=class{constructor(e,t,r){dt();let n,s;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,n=e.type,s=e.dims,e.location){case"cpu-pinned":{let i=$e.get(n);if(!i)throw new TypeError(`unsupported type "${n}" to create tensor from pinned buffer`);if(!(e.data instanceof i))throw new TypeError(`buffer should be of type ${i.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"&&n!=="uint4"&&n!=="int4")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}case"ml-tensor":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint64"&&n!=="int8"&&n!=="uint8"&&n!=="bool")throw new TypeError(`unsupported type "${n}" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let i,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.");i=t}else{let d=$e.get(e);if(d===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if(e==="float16"&&d===Uint16Array||e==="uint4"||e==="int4")throw new TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${d.name} as data.`);e==="uint64"||e==="int64"?i=d.from(t,BigInt):i=d.from(t)}else if(t instanceof d)i=t;else if(t instanceof Uint8ClampedArray)if(e==="uint8")i=Uint8Array.from(t);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else throw new TypeError(`A ${n} tensor's data must be type of ${d}`)}else if(u=t,Array.isArray(e)){if(e.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let d=typeof e[0];if(d==="string")n="string",i=e;else if(d==="boolean")n="bool",i=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${d}.`)}else if(e instanceof Uint8ClampedArray)n="uint8",i=Uint8Array.from(e);else{let d=Y.get(e.constructor);if(d===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);n=d,i=e}if(u===void 0)u=[i.length];else if(!Array.isArray(u))throw new TypeError("A tensor's dims must be a number array");s=u,this.cpuData=i,this.dataLocation="cpu"}let a=ot(s);if(this.cpuData&&a!==this.cpuData.length&&!((n==="uint4"||n==="int4")&&Math.ceil(a/2)===this.cpuData.length))throw new Error(`Tensor's size(${a}) does not match data length(${this.cpuData.length}).`);this.type=n,this.dims=s,this.size=a}static async fromImage(e,t){return Ze(e,t)}static fromTexture(e,t){return Ke(e,t)}static fromGpuBuffer(e,t){return ut(e,t)}static fromMLTensor(e,t){return we(e,t)}static fromPinnedBuffer(e,t,r){return W(e,t,r)}toDataURL(e){return Me(this,e)}toImageData(e){return ke(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}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(e){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{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.mlTensorData=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 Re(this,e)}}}),ee,Pe=j(()=>{qe(),ee=bt}),Ne,Qe,Ue,je,lt=j(()=>{L(),Ne=(e,t)=>{(typeof I.trace>"u"?!I.wasm.trace:!I.trace)||console.timeStamp(`${e}::ORT::${t}`)},Qe=(e,t)=>{var s;let r=((s=new Error().stack)==null?void 0:s.split(/\r\n|\r|\n/g))||[],n=!1;for(let a=0;a{(typeof I.trace>"u"?!I.wasm.trace:!I.trace)||Qe("BEGIN",e)},je=e=>{(typeof I.trace>"u"?!I.wasm.trace:!I.trace)||Qe("END",e)}}),yt,vt=j(()=>{K(),Pe(),lt(),yt=class Ef{constructor(t){this.handler=t}async run(t,r,n){Ue();let s={},a={};if(typeof t!="object"||t===null||t instanceof ee||Array.isArray(t))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let i=!0;if(typeof r=="object"){if(r===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(r instanceof ee)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.");i=!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}.`);s[p]=null}if(typeof n=="object"&&n!==null)a=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else{let p=!1,g=Object.getOwnPropertyNames(r);for(let w of this.outputNames)if(g.indexOf(w)!==-1){let l=r[w];(l===null||l instanceof ee)&&(p=!0,i=!1,s[w]=l)}if(p){if(typeof n=="object"&&n!==null)a=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else a=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(i)for(let p of this.outputNames)s[p]=null;let u=await this.handler.run(t,s,a),d={};for(let p in u)if(Object.hasOwnProperty.call(u,p)){let g=u[p];g instanceof ee?d[p]=g:d[p]=new ee(g.type,g.data,g.dims)}return je(),d}async release(){return this.handler.dispose()}static async create(t,r,n,s){Ue();let a,i={};if(typeof t=="string"){if(a=t,typeof r=="object"&&r!==null)i=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof Uint8Array){if(a=t,typeof r=="object"&&r!==null)i=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 g=t,w=0,l=t.byteLength;if(typeof r=="object"&&r!==null)i=r;else if(typeof r=="number"){if(w=r,!Number.isSafeInteger(w))throw new RangeError("'byteOffset' must be an integer.");if(w<0||w>=g.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${g.byteLength}).`);if(l=t.byteLength-w,typeof n=="number"){if(l=n,!Number.isSafeInteger(l))throw new RangeError("'byteLength' must be an integer.");if(l<=0||w+l>g.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${g.byteLength-w}].`);if(typeof s=="object"&&s!==null)i=s;else if(typeof s<"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.");a=new Uint8Array(g,w,l)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[u,d]=await D(i),p=await u.createInferenceSessionHandler(a,d);return je(),new Ef(p)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}}),Et,x=j(()=>{vt(),Et=yt}),q=j(()=>{}),$=j(()=>{}),Q=j(()=>{}),he=j(()=>{}),Ye,Je,Bt=j(()=>{K(),Pe(),Ye="Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.",Je=class $f{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||"",s=t.optimizerModel||"",a=r||{},[i,u]=await D(a);if(i.createTrainingSessionHandler){let d=await i.createTrainingSessionHandler(t.checkpointState,t.trainModel,n,s,u);return new $f(d,!!t.optimizerModel,!!t.evalModel)}else throw new Error(Ye)}typeNarrowingForRunStep(t,r,n,s,a){let i={},u={};if(typeof n!="object"||n===null||n instanceof ee||Array.isArray(n))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let d=!0;if(typeof s=="object"){if(s===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(s instanceof ee)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(s)){if(s.length===0)throw new TypeError("'fetches' cannot be an empty array.");d=!1;for(let p of s){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}.`);i[p]=null}if(typeof a=="object"&&a!==null)u=a;else if(typeof a<"u")throw new TypeError("'options' must be an object.")}else{let p=!1,g=Object.getOwnPropertyNames(s);for(let w of r)if(g.indexOf(w)!==-1){let l=s[w];(l===null||l instanceof ee)&&(p=!0,d=!1,i[w]=l)}if(p){if(typeof a=="object"&&a!==null)u=a;else if(typeof a<"u")throw new TypeError("'options' must be an object.")}else u=s}}else if(typeof s<"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(d)for(let p of r)i[p]=null;return[i,u]}convertHandlerReturnTypeToMapOfTensors(t){let r={};for(let n in t)if(Object.hasOwnProperty.call(t,n)){let s=t[n];s instanceof ee?r[n]=s:r[n]=new ee(s.type,s.data,s.dims)}return r}async lazyResetGrad(){await this.handler.lazyResetGrad()}async runTrainStep(t,r,n){let[s,a]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,t,r,n),i=await this.handler.runTrainStep(t,s,a);return this.convertHandlerReturnTypeToMapOfTensors(i)}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[s,a]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,t,r,n),i=await this.handler.runEvalStep(t,s,a);return this.convertHandlerReturnTypeToMapOfTensors(i)}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()}}}),ct,Tt=j(()=>{Bt(),ct=Je}),It={};S(It,{InferenceSession:()=>Et,TRACE:()=>Ne,TRACE_FUNC_BEGIN:()=>Ue,TRACE_FUNC_END:()=>je,Tensor:()=>ee,TrainingSession:()=>ct,env:()=>k,registerBackend:()=>_e});var At=j(()=>{re(),de(),x(),Pe(),q(),$(),lt(),Q(),he(),Tt()}),cr=j(()=>{}),Er={};S(Er,{default:()=>Ur});var Qr,Or,Ur,at=j(()=>{var e;Hp(),Wr(),Gt(),Qr="ort-wasm-proxy-worker",Or=((e=globalThis.self)==null?void 0:e.name)===Qr,Or&&(self.onmessage=t=>{let{type:r,in:n}=t.data;try{switch(r){case"init-wasm":Kr(n.wasm).then(()=>{Tc(n).then(()=>{postMessage({type:r})},s=>{postMessage({type:r,err:s})})},s=>{postMessage({type:r,err:s})});break;case"init-ep":{let{epName:s,env:a}=n;Cc(a,s).then(()=>{postMessage({type:r})},i=>{postMessage({type:r,err:i})});break}case"copy-from":{let{buffer:s}=n,a=Qd(s);postMessage({type:r,out:a});break}case"create":{let{model:s,options:a}=n;Ec(s,a).then(i=>{postMessage({type:r,out:i})},i=>{postMessage({type:r,err:i})});break}case"release":$c(n),postMessage({type:r});break;case"run":{let{sessionId:s,inputIndices:a,inputs:i,outputIndices:u,options:d}=n;kc(s,a,i,u,new Array(u.length).fill(null),d).then(p=>{p.some(g=>g[3]!=="cpu")?postMessage({type:r,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:r,out:p},Ac([...i,...p]))},p=>{postMessage({type:r,err:p})});break}case"end-profiling":Pc(n),postMessage({type:r});break;default:}}catch(s){postMessage({type:r,err:s})}}),Ur=Or?null:t=>new Worker(t??Xe,{type:"module",name:Qr})}),U={};S(U,{default:()=>et});var ge,Ae,et,ve=j(()=>{var e;Ae=(ge=self.location.href,async function(t={}){function r(){return br.buffer!=dr.buffer&&mn(),dr}function n(){return br.buffer!=dr.buffer&&mn(),Pr}function s(){return br.buffer!=dr.buffer&&mn(),Ve}function a(){return br.buffer!=dr.buffer&&mn(),kt}function i(){return br.buffer!=dr.buffer&&mn(),tr}function u(){return br.buffer!=dr.buffer&&mn(),zr}function d(){return br.buffer!=dr.buffer&&mn(),nn}function p(){return br.buffer!=dr.buffer&&mn(),Zd}var g,w,l=Object.assign({},t),M=new Promise((o,h)=>{g=o,w=h}),C=typeof window=="object",E=typeof importScripts=="function",B=E&&self.name=="em-pthread";l.mountExternalData=(o,h)=>{o.startsWith("./")&&(o=o.substring(2)),(l.Fb||(l.Fb=new Map)).set(o,h)},l.unmountExternalData=()=>{delete l.Fb};var G=globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,shared:!0}).buffer.constructor;let O=()=>{let o=(y,v,F)=>(...oe)=>{let We=ds,it=v==null?void 0:v();oe=y(...oe);let Ft=v==null?void 0:v();return it!==Ft&&(y=Ft,F(it),v=F=null),ds!=We?new Promise((Lt,Qt)=>{Yc={resolve:Lt,reject:Qt}}):oe},h=y=>async(...v)=>{var F;try{if(l.Eb)throw Error("Session already started");let oe=l.Eb={fc:v[0],errors:[]},We=await y(...v);if(l.Eb!==oe)throw Error("Session mismatch");(F=l.Gb)==null||F.flush();let it=oe.errors;if(0Lt),0l._OrtCreateSession,y=>l._OrtCreateSession=y),l._OrtRun=h(o(l._OrtRun,()=>l._OrtRun,y=>l._OrtRun=y)),l._OrtRunWithBinding=h(o(l._OrtRunWithBinding,()=>l._OrtRunWithBinding,y=>l._OrtRunWithBinding=y)),l._OrtBindInput=o(l._OrtBindInput,()=>l._OrtBindInput,y=>l._OrtBindInput=y),O=void 0};l.jsepInit=(o,h)=>{if(O==null||O(),o==="webgpu"){[l.Gb,l.Ub,l.Yb,l.Nb,l.Xb,l.jb,l.Zb,l.bc,l.Vb,l.Wb,l.$b]=h;let y=l.Gb;l.jsepRegisterBuffer=(v,F,oe,We)=>y.registerBuffer(v,F,oe,We),l.jsepGetBuffer=v=>y.getBuffer(v),l.jsepCreateDownloader=(v,F,oe)=>y.createDownloader(v,F,oe),l.jsepOnReleaseSession=v=>{y.onReleaseSession(v)},l.jsepOnRunStart=v=>y.onRunStart(v),l.cc=(v,F)=>{y.upload(v,F)}}else if(o==="webnn"){[l.Gb,l.ac,l.Ob,l.jsepEnsureTensor,l.dc,l.jsepDownloadTensor]=h,l.jsepReleaseTensorId=l.Ob;let y=l.Gb;l.jsepOnRunStart=v=>y.onRunStart(v),l.jsepRegisterMLContext=(v,F)=>{y.registerMLContext(v,F)},l.jsepOnReleaseSession=v=>{y.onReleaseSession(v)},l.jsepCreateMLTensorDownloader=(v,F)=>y.createMLTensorDownloader(v,F),l.jsepRegisterMLTensor=(v,F,oe)=>y.registerMLTensor(v,F,oe)}};var ae,Z,le=Object.assign({},l),Ge="./this.program",Le=(o,h)=>{throw h},pt="";(C||E)&&(E?pt=self.location.href:typeof document<"u"&&document.currentScript&&(pt=document.currentScript.src),ge&&(pt=ge),pt=pt.startsWith("blob:")?"":pt.substr(0,pt.replace(/[?#].*/,"").lastIndexOf("/")+1),E&&(Z=o=>{var h=new XMLHttpRequest;return h.open("GET",o,!1),h.responseType="arraybuffer",h.send(null),new Uint8Array(h.response)}),ae=(o,h,y)=>{var v=new XMLHttpRequest;v.open("GET",o,!0),v.responseType="arraybuffer",v.onload=()=>{v.status==200||v.status==0&&v.response?h(v.response):y()},v.onerror=y,v.send(null)});var Dt,Vt=console.log.bind(console),lr=console.error.bind(console),fr=Vt,er=lr;if(Object.assign(l,le),le=null,B){let o=function(h){try{var y=h.data,v=y.cmd;if(v==="load"){let F=[];self.onmessage=oe=>F.push(oe),self.startWorker=()=>{postMessage({cmd:"loaded"});for(let oe of F)o(oe);self.onmessage=o};for(let oe of y.handlers)l[oe]&&!l[oe].proxy||(l[oe]=(...We)=>{postMessage({Mb:"callHandler",oc:oe,args:We})},oe=="print"&&(fr=l[oe]),oe=="printErr"&&(er=l[oe]));br=y.wasmMemory,mn(),Nr(y.wasmModule)}else if(v==="run"){tp(y.pthread_ptr,0,0,1,0,0),Kc(y.pthread_ptr),nm(),_h(),Hr||(ff(),Hr=!0);try{sm(y.start_routine,y.arg)}catch(F){if(F!="unwind")throw F}}else v==="cancel"?no()&&cc(-1):y.target!=="setimmediate"&&(v==="checkMailbox"?Hr&&rc():v&&(er(`worker: received unknown command ${v}`),er(y)))}catch(F){throw mf(),F}};var Nr,Hr=!1;er=function(...h){h=h.join(" "),console.error(h)},self.alert=function(...h){postMessage({Mb:"alert",text:h.join(" "),qc:no()})},l.instantiateWasm=(h,y)=>new Promise(v=>{Nr=F=>{F=new WebAssembly.Instance(F,ch()),y(F),v()}}),self.onunhandledrejection=h=>{throw h.reason||h},self.onmessage=o}l.wasmBinary&&(Dt=l.wasmBinary);var br,jr,Jt,dr,Pr,Ve,kt,tr,zr,nn,un,Vs,Zd,En=!1;function mn(){var o=br.buffer;l.HEAP8=dr=new Int8Array(o),l.HEAP16=Ve=new Int16Array(o),l.HEAPU8=Pr=new Uint8Array(o),l.HEAPU16=kt=new Uint16Array(o),l.HEAP32=tr=new Int32Array(o),l.HEAPU32=zr=new Uint32Array(o),l.HEAPF32=nn=new Float32Array(o),l.HEAPF64=Zd=new Float64Array(o),l.HEAP64=un=new BigInt64Array(o),l.HEAPU64=Vs=new BigUint64Array(o)}if(!B){if(!((br=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0})).buffer instanceof G))throw er("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"),Error("bad memory");mn()}var yi=[],hn=[],vn=[],Vn=0,Us=null;function ec(){if(--Vn==0&&Us){var o=Us;Us=null,o()}}function eo(o){throw er(o="Aborted("+o+")"),En=!0,Jt=1,o=new WebAssembly.RuntimeError(o+". Build with -sASSERTIONS for more info."),w(o),o}var Dc,oh=o=>o.startsWith("data:application/octet-stream;base64,"),lh=o=>o.startsWith("file://");function uh(o){if(o==Dc&&Dt)return new Uint8Array(Dt);if(Z)return Z(o);throw"both async and sync fetching of the wasm failed"}function dh(o,h,y){return function(v){if(!Dt&&(C||E)){if(typeof fetch=="function"&&!lh(v))return fetch(v,{credentials:"same-origin"}).then(F=>{if(!F.ok)throw`failed to load wasm binary file at '${v}'`;return F.arrayBuffer()}).catch(()=>uh(v));if(ae)return new Promise((F,oe)=>{ae(v,We=>F(new Uint8Array(We)),oe)})}return Promise.resolve().then(()=>uh(v))}(o).then(v=>WebAssembly.instantiate(v,h)).then(y,v=>{er(`failed to asynchronously prepare wasm: ${v}`),eo(v)})}function ch(){return{a:{O:rm,Aa:tm,b:am,aa:bh,B:xh,qa:Th,Y:Eh,_:$h,ra:Sh,oa:kh,ha:Ph,na:Ah,L:Ih,Z:Fh,W:zh,pa:Oh,X:Dh,wa:om,F:lm,Q:um,P:cm,E:hm,u:fm,q:mm,G:_m,A:xm,R:Tm,ua:Cm,ka:Em,U:$m,ba:Sm,H:km,ja:Kc,ta:Pm,t:Am,x:zm,o:Om,l:Lm,c:qc,n:Bm,j:jm,w:Vm,p:Um,g:Wm,s:Gm,m:qm,e:Hm,k:Km,i:Xm,h:Qm,d:Ym,ea:Jm,fa:Zm,ga:e_,ca:Qh,da:Yh,T:t_,f:r_,D:n_,I:s_,M:i_,y:a_,sa:o_,V:l_,v:Zh,z:u_,N:d_,S:c_,za:p_,ya:h_,la:rf,ma:nf,$:jc,C:sf,K:af,ia:of,J:lf,a:br,xa:Nc,va:cf,r:__}}}var Lc={864100:(o,h,y,v,F)=>{if(l===void 0||!l.Fb)return 1;if((o=gn(o>>>0)).startsWith("./")&&(o=o.substring(2)),!(o=l.Fb.get(o)))return 2;if(v>>>=0,(h>>>=0)+(y>>>=0)>o.byteLength)return 3;try{let oe=o.subarray(h,h+y);switch(F){case 0:n().set(oe,v>>>0);break;case 1:l.cc(v,oe);break;default:return 4}return 0}catch{return 4}},864783:(o,h,y)=>{l.dc(o,n().subarray(h>>>0,h+y>>>0))},864846:()=>l.ac(),864887:o=>{l.Ob(o)},864923:()=>{l.Vb()},864954:()=>{l.Wb()},864983:()=>{l.$b()},865008:o=>l.Ub(o),865041:o=>l.Yb(o),865073:(o,h,y)=>{l.Nb(o,h,y,!0)},865112:(o,h,y)=>{l.Nb(o,h,y)},865145:()=>typeof wasmOffsetConverter<"u",865202:o=>{l.jb("Abs",o,void 0)},865253:o=>{l.jb("Neg",o,void 0)},865304:o=>{l.jb("Floor",o,void 0)},865357:o=>{l.jb("Ceil",o,void 0)},865409:o=>{l.jb("Reciprocal",o,void 0)},865467:o=>{l.jb("Sqrt",o,void 0)},865519:o=>{l.jb("Exp",o,void 0)},865570:o=>{l.jb("Erf",o,void 0)},865621:o=>{l.jb("Sigmoid",o,void 0)},865676:(o,h,y)=>{l.jb("HardSigmoid",o,{alpha:h,beta:y})},865755:o=>{l.jb("Log",o,void 0)},865806:o=>{l.jb("Sin",o,void 0)},865857:o=>{l.jb("Cos",o,void 0)},865908:o=>{l.jb("Tan",o,void 0)},865959:o=>{l.jb("Asin",o,void 0)},866011:o=>{l.jb("Acos",o,void 0)},866063:o=>{l.jb("Atan",o,void 0)},866115:o=>{l.jb("Sinh",o,void 0)},866167:o=>{l.jb("Cosh",o,void 0)},866219:o=>{l.jb("Asinh",o,void 0)},866272:o=>{l.jb("Acosh",o,void 0)},866325:o=>{l.jb("Atanh",o,void 0)},866378:o=>{l.jb("Tanh",o,void 0)},866430:o=>{l.jb("Not",o,void 0)},866481:(o,h,y)=>{l.jb("Clip",o,{min:h,max:y})},866550:o=>{l.jb("Clip",o,void 0)},866602:(o,h)=>{l.jb("Elu",o,{alpha:h})},866660:o=>{l.jb("Gelu",o,void 0)},866712:o=>{l.jb("Relu",o,void 0)},866764:(o,h)=>{l.jb("LeakyRelu",o,{alpha:h})},866828:(o,h)=>{l.jb("ThresholdedRelu",o,{alpha:h})},866898:(o,h)=>{l.jb("Cast",o,{to:h})},866956:o=>{l.jb("Add",o,void 0)},867007:o=>{l.jb("Sub",o,void 0)},867058:o=>{l.jb("Mul",o,void 0)},867109:o=>{l.jb("Div",o,void 0)},867160:o=>{l.jb("Pow",o,void 0)},867211:o=>{l.jb("Equal",o,void 0)},867264:o=>{l.jb("Greater",o,void 0)},867319:o=>{l.jb("GreaterOrEqual",o,void 0)},867381:o=>{l.jb("Less",o,void 0)},867433:o=>{l.jb("LessOrEqual",o,void 0)},867492:(o,h,y,v,F)=>{l.jb("ReduceMean",o,{keepDims:!!h,noopWithEmptyAxes:!!y,axes:v?Array.from(i().subarray(v>>>0,F>>>0)):[]})},867651:(o,h,y,v,F)=>{l.jb("ReduceMax",o,{keepDims:!!h,noopWithEmptyAxes:!!y,axes:v?Array.from(i().subarray(v>>>0,F>>>0)):[]})},867809:(o,h,y,v,F)=>{l.jb("ReduceMin",o,{keepDims:!!h,noopWithEmptyAxes:!!y,axes:v?Array.from(i().subarray(v>>>0,F>>>0)):[]})},867967:(o,h,y,v,F)=>{l.jb("ReduceProd",o,{keepDims:!!h,noopWithEmptyAxes:!!y,axes:v?Array.from(i().subarray(v>>>0,F>>>0)):[]})},868126:(o,h,y,v,F)=>{l.jb("ReduceSum",o,{keepDims:!!h,noopWithEmptyAxes:!!y,axes:v?Array.from(i().subarray(v>>>0,F>>>0)):[]})},868284:(o,h,y,v,F)=>{l.jb("ReduceL1",o,{keepDims:!!h,noopWithEmptyAxes:!!y,axes:v?Array.from(i().subarray(v>>>0,F>>>0)):[]})},868441:(o,h,y,v,F)=>{l.jb("ReduceL2",o,{keepDims:!!h,noopWithEmptyAxes:!!y,axes:v?Array.from(i().subarray(v>>>0,F>>>0)):[]})},868598:(o,h,y,v,F)=>{l.jb("ReduceLogSum",o,{keepDims:!!h,noopWithEmptyAxes:!!y,axes:v?Array.from(i().subarray(v>>>0,F>>>0)):[]})},868759:(o,h,y,v,F)=>{l.jb("ReduceSumSquare",o,{keepDims:!!h,noopWithEmptyAxes:!!y,axes:v?Array.from(i().subarray(v>>>0,F>>>0)):[]})},868923:(o,h,y,v,F)=>{l.jb("ReduceLogSumExp",o,{keepDims:!!h,noopWithEmptyAxes:!!y,axes:v?Array.from(i().subarray(v>>>0,F>>>0)):[]})},869087:o=>{l.jb("Where",o,void 0)},869140:(o,h,y)=>{l.jb("Transpose",o,{perm:h?Array.from(i().subarray(h>>>0,y>>>0)):[]})},869248:(o,h,y,v)=>{l.jb("DepthToSpace",o,{blocksize:h,mode:gn(y),format:v?"NHWC":"NCHW"})},869381:(o,h,y,v)=>{l.jb("DepthToSpace",o,{blocksize:h,mode:gn(y),format:v?"NHWC":"NCHW"})},869514:(o,h,y,v,F,oe,We,it,Ft,Lt,Qt,Cr,Lr,Be,Mr)=>{l.jb("ConvTranspose",o,{format:Ft?"NHWC":"NCHW",autoPad:h,dilations:[y],group:v,kernelShape:[F],pads:[oe,We],strides:[it],wIsConst:()=>!!r()[Lt>>>0],outputPadding:Qt?Array.from(i().subarray(Qt>>>0,Cr>>>0)):[],outputShape:Lr?Array.from(i().subarray(Lr>>>0,Be>>>0)):[],activation:gn(Mr)})},869915:(o,h,y,v,F,oe,We,it,Ft,Lt,Qt,Cr,Lr,Be)=>{l.jb("ConvTranspose",o,{format:it?"NHWC":"NCHW",autoPad:h,dilations:Array.from(i().subarray(y>>>0,2+(y>>>0)>>>0)),group:v,kernelShape:Array.from(i().subarray(F>>>0,2+(F>>>0)>>>0)),pads:Array.from(i().subarray(oe>>>0,4+(oe>>>0)>>>0)),strides:Array.from(i().subarray(We>>>0,2+(We>>>0)>>>0)),wIsConst:()=>!!r()[Ft>>>0],outputPadding:Lt?Array.from(i().subarray(Lt>>>0,Qt>>>0)):[],outputShape:Cr?Array.from(i().subarray(Cr>>>0,Lr>>>0)):[],activation:gn(Be)})},870480:(o,h,y,v,F,oe,We,it,Ft,Lt,Qt,Cr,Lr,Be,Mr)=>{l.jb("ConvTranspose",o,{format:Ft?"NHWC":"NCHW",autoPad:h,dilations:[y],group:v,kernelShape:[F],pads:[oe,We],strides:[it],wIsConst:()=>!!r()[Lt>>>0],outputPadding:Qt?Array.from(i().subarray(Qt>>>0,Cr>>>0)):[],outputShape:Lr?Array.from(i().subarray(Lr>>>0,Be>>>0)):[],activation:gn(Mr)})},870881:(o,h,y,v,F,oe,We,it,Ft,Lt,Qt,Cr,Lr,Be)=>{l.jb("ConvTranspose",o,{format:it?"NHWC":"NCHW",autoPad:h,dilations:Array.from(i().subarray(y>>>0,2+(y>>>0)>>>0)),group:v,kernelShape:Array.from(i().subarray(F>>>0,2+(F>>>0)>>>0)),pads:Array.from(i().subarray(oe>>>0,4+(oe>>>0)>>>0)),strides:Array.from(i().subarray(We>>>0,2+(We>>>0)>>>0)),wIsConst:()=>!!r()[Ft>>>0],outputPadding:Lt?Array.from(i().subarray(Lt>>>0,Qt>>>0)):[],outputShape:Cr?Array.from(i().subarray(Cr>>>0,Lr>>>0)):[],activation:gn(Be)})},871446:(o,h)=>{l.jb("GlobalAveragePool",o,{format:h?"NHWC":"NCHW"})},871537:(o,h,y,v,F,oe,We,it,Ft,Lt,Qt,Cr,Lr,Be)=>{l.jb("AveragePool",o,{format:Be?"NHWC":"NCHW",auto_pad:h,ceil_mode:y,count_include_pad:v,storage_order:F,dilations:oe?Array.from(i().subarray(oe>>>0,We>>>0)):[],kernel_shape:it?Array.from(i().subarray(it>>>0,Ft>>>0)):[],pads:Lt?Array.from(i().subarray(Lt>>>0,Qt>>>0)):[],strides:Cr?Array.from(i().subarray(Cr>>>0,Lr>>>0)):[]})},871952:(o,h)=>{l.jb("GlobalAveragePool",o,{format:h?"NHWC":"NCHW"})},872043:(o,h,y,v,F,oe,We,it,Ft,Lt,Qt,Cr,Lr,Be)=>{l.jb("AveragePool",o,{format:Be?"NHWC":"NCHW",auto_pad:h,ceil_mode:y,count_include_pad:v,storage_order:F,dilations:oe?Array.from(i().subarray(oe>>>0,We>>>0)):[],kernel_shape:it?Array.from(i().subarray(it>>>0,Ft>>>0)):[],pads:Lt?Array.from(i().subarray(Lt>>>0,Qt>>>0)):[],strides:Cr?Array.from(i().subarray(Cr>>>0,Lr>>>0)):[]})},872458:(o,h)=>{l.jb("GlobalMaxPool",o,{format:h?"NHWC":"NCHW"})},872545:(o,h,y,v,F,oe,We,it,Ft,Lt,Qt,Cr,Lr,Be)=>{l.jb("MaxPool",o,{format:Be?"NHWC":"NCHW",auto_pad:h,ceil_mode:y,count_include_pad:v,storage_order:F,dilations:oe?Array.from(i().subarray(oe>>>0,We>>>0)):[],kernel_shape:it?Array.from(i().subarray(it>>>0,Ft>>>0)):[],pads:Lt?Array.from(i().subarray(Lt>>>0,Qt>>>0)):[],strides:Cr?Array.from(i().subarray(Cr>>>0,Lr>>>0)):[]})},872956:(o,h)=>{l.jb("GlobalMaxPool",o,{format:h?"NHWC":"NCHW"})},873043:(o,h,y,v,F,oe,We,it,Ft,Lt,Qt,Cr,Lr,Be)=>{l.jb("MaxPool",o,{format:Be?"NHWC":"NCHW",auto_pad:h,ceil_mode:y,count_include_pad:v,storage_order:F,dilations:oe?Array.from(i().subarray(oe>>>0,We>>>0)):[],kernel_shape:it?Array.from(i().subarray(it>>>0,Ft>>>0)):[],pads:Lt?Array.from(i().subarray(Lt>>>0,Qt>>>0)):[],strides:Cr?Array.from(i().subarray(Cr>>>0,Lr>>>0)):[]})},873454:(o,h,y,v,F)=>{l.jb("Gemm",o,{alpha:h,beta:y,transA:v,transB:F})},873558:o=>{l.jb("MatMul",o,void 0)},873612:(o,h,y,v)=>{l.jb("ArgMax",o,{keepDims:!!h,selectLastIndex:!!y,axis:v})},873720:(o,h,y,v)=>{l.jb("ArgMin",o,{keepDims:!!h,selectLastIndex:!!y,axis:v})},873828:(o,h)=>{l.jb("Softmax",o,{axis:h})},873891:(o,h)=>{l.jb("Concat",o,{axis:h})},873951:(o,h,y,v,F)=>{l.jb("Split",o,{axis:h,numOutputs:y,splitSizes:v?Array.from(i().subarray(v>>>0,F>>>0)):[]})},874091:o=>{l.jb("Expand",o,void 0)},874145:(o,h)=>{l.jb("Gather",o,{axis:Number(h)})},874216:(o,h)=>{l.jb("GatherElements",o,{axis:Number(h)})},874295:(o,h,y,v,F,oe,We,it,Ft,Lt,Qt)=>{l.jb("Resize",o,{antialias:h,axes:y?Array.from(i().subarray(y>>>0,v>>>0)):[],coordinateTransformMode:gn(F),cubicCoeffA:oe,excludeOutside:We,extrapolationValue:it,keepAspectRatioPolicy:gn(Ft),mode:gn(Lt),nearestMode:gn(Qt)})},874641:(o,h,y,v,F,oe,We)=>{l.jb("Slice",o,{starts:h?Array.from(i().subarray(h>>>0,y>>>0)):[],ends:v?Array.from(i().subarray(v>>>0,F>>>0)):[],axes:oe?Array.from(i().subarray(oe>>>0,We>>>0)):[]})},874857:o=>{l.jb("Tile",o,void 0)},874909:(o,h,y)=>{l.jb("InstanceNormalization",o,{epsilon:h,format:y?"NHWC":"NCHW"})},875023:(o,h,y)=>{l.jb("InstanceNormalization",o,{epsilon:h,format:y?"NHWC":"NCHW"})},875137:o=>{l.jb("Range",o,void 0)},875190:(o,h)=>{l.jb("Einsum",o,{equation:gn(h)})},875271:(o,h,y,v,F)=>{l.jb("Pad",o,{mode:h,value:y,pads:v?Array.from(i().subarray(v>>>0,F>>>0)):[]})},875398:(o,h,y,v,F,oe)=>{l.jb("BatchNormalization",o,{epsilon:h,momentum:y,spatial:!!F,trainingMode:!!v,format:oe?"NHWC":"NCHW"})},875567:(o,h,y,v,F,oe)=>{l.jb("BatchNormalization",o,{epsilon:h,momentum:y,spatial:!!F,trainingMode:!!v,format:oe?"NHWC":"NCHW"})},875736:(o,h,y)=>{l.jb("CumSum",o,{exclusive:Number(h),reverse:Number(y)})},875833:(o,h,y)=>{l.jb("DequantizeLinear",o,{axis:h,blockSize:y})},875923:(o,h,y,v,F,oe,We,it,Ft)=>{l.jb("Attention",o,{numHeads:h,isUnidirectional:y,maskFilterValue:v,scale:F,doRotary:oe,qkvHiddenSizes:We?Array.from(i().subarray(Number(it)>>>0,Number(it)+We>>>0)):[],pastPresentShareBuffer:!!Ft})},876195:o=>{l.jb("BiasAdd",o,void 0)},876250:o=>{l.jb("BiasSplitGelu",o,void 0)},876311:o=>{l.jb("FastGelu",o,void 0)},876367:(o,h,y,v,F,oe,We,it,Ft,Lt,Qt,Cr,Lr,Be,Mr,tn)=>{l.jb("Conv",o,{format:Cr?"NHWC":"NCHW",auto_pad:h,dilations:y?Array.from(i().subarray(y>>>0,v>>>0)):[],group:F,kernel_shape:oe?Array.from(i().subarray(oe>>>0,We>>>0)):[],pads:it?Array.from(i().subarray(it>>>0,Ft>>>0)):[],strides:Lt?Array.from(i().subarray(Lt>>>0,Qt>>>0)):[],w_is_const:()=>!!r()[Lr>>>0],activation:gn(Be),activation_params:Mr?Array.from(d().subarray(Mr>>>0,tn>>>0)):[]})},876863:o=>{l.jb("Gelu",o,void 0)},876915:(o,h,y,v)=>{l.jb("GroupQueryAttention",o,{numHeads:h,kvNumHeads:y,scale:v})},877028:(o,h,y,v)=>{l.jb("LayerNormalization",o,{axis:h,epsilon:y,simplified:!!v})},877139:(o,h,y,v)=>{l.jb("LayerNormalization",o,{axis:h,epsilon:y,simplified:!!v})},877250:(o,h,y,v,F,oe)=>{l.jb("MatMulNBits",o,{k:h,n:y,accuracyLevel:v,bits:F,blockSize:oe})},877377:(o,h,y,v,F,oe)=>{l.jb("MultiHeadAttention",o,{numHeads:h,isUnidirectional:y,maskFilterValue:v,scale:F,doRotary:oe})},877536:(o,h)=>{l.jb("QuickGelu",o,{alpha:h})},877600:(o,h,y,v,F)=>{l.jb("RotaryEmbedding",o,{interleaved:!!h,numHeads:y,rotaryEmbeddingDim:v,scale:F})},877739:(o,h,y)=>{l.jb("SkipLayerNormalization",o,{epsilon:h,simplified:!!y})},877841:(o,h,y)=>{l.jb("SkipLayerNormalization",o,{epsilon:h,simplified:!!y})},877943:(o,h,y,v)=>{l.jb("GatherBlockQuantized",o,{gatherAxis:h,quantizeAxis:y,blockSize:v})},878064:o=>{l.Zb(o)},878098:(o,h)=>l.bc(o,h,l.Eb.fc,l.Eb.errors)};function tm(o,h,y){return Gh(async()=>{await l.Xb(o,h,y)})}function rm(){return typeof wasmOffsetConverter<"u"}function Bc(o){this.name="ExitStatus",this.message=`Program terminated with exit(${o})`,this.status=o}var Rc=o=>{o.terminate(),o.onmessage=()=>{}},ph=o=>{Ws.length==0&&(wh(),gh(Ws[0]));var h=Ws.pop();if(!h)return 6;Mi.push(h),ls[o.Ab]=h,h.Ab=o.Ab;var y={cmd:"run",start_routine:o.hc,arg:o.Qb,pthread_ptr:o.Ab};return h.postMessage(y,o.mc),0},bi=0,Yr=(o,h,...y)=>{for(var v=2*y.length,F=sp(),oe=np(8*v),We=oe>>>3,it=0;it>>0]=Ft)}return o=_f(o,0,v,oe,h),pc(F),o};function Nc(o){if(B)return Yr(0,1,o);if(Jt=o,!(0{if(Jt=o,B)throw hh(o),"unwind";Nc(o)},Ws=[],Mi=[],fh=[],ls={},mh=o=>{var h=o.Ab;delete ls[h],Ws.push(o),Mi.splice(Mi.indexOf(o),1),o.Ab=0,rp(h)};function _h(){fh.forEach(o=>o())}var gh=o=>new Promise(h=>{o.onmessage=F=>{var oe=(F=F.data).cmd;if(F.targetThread&&F.targetThread!=no()){var We=ls[F.targetThread];We?We.postMessage(F,F.transferList):er(`Internal error! Worker sent a message "${oe}" to target pthread ${F.targetThread}, but that thread no longer exists!`)}else oe==="checkMailbox"?rc():oe==="spawnThread"?ph(F):oe==="cleanupThread"?mh(ls[F.thread]):oe==="killThread"?(F=F.thread,oe=ls[F],delete ls[F],Rc(oe),rp(F),Mi.splice(Mi.indexOf(oe),1),oe.Ab=0):oe==="cancelThread"?ls[F.thread].postMessage({cmd:"cancel"}):oe==="loaded"?(o.loaded=!0,h(o)):oe==="alert"?alert(`Thread ${F.threadId}: ${F.text}`):F.target==="setimmediate"?o.postMessage(F):oe==="callHandler"?l[F.handler](...F.args):oe&&er(`worker sent an unknown command ${oe}`)},o.onerror=F=>{throw er(`worker sent an error! ${F.filename}:${F.lineno}: ${F.message}`),F};var y,v=[];for(y of[])l.hasOwnProperty(y)&&v.push(y);o.postMessage({cmd:"load",handlers:v,wasmMemory:br,wasmModule:jr})});function wh(){var o=new Worker(new URL(self.location.href),{type:"module",workerData:"em-pthread",name:"em-pthread"});Ws.push(o)}var tc=o=>{for(;0{var o=no(),h=u()[o+52>>>2>>>0];o=u()[o+56>>>2>>>0],wf(h,h-o),pc(h)},sm=(o,h)=>{bi=0,o=yf(o,h),0>>=0);throw h>>>=0,y>>>=0,u()[v.Jb+16>>>2>>>0]=0,u()[v.Jb+4>>>2>>>0]=h,u()[v.Jb+8>>>2>>>0]=y,o}function yh(o,h,y,v){return B?Yr(2,1,o,h,y,v):bh(o,h,y,v)}function bh(o,h,y,v){if(o>>>=0,h>>>=0,y>>>=0,v>>>=0,G===void 0)return er("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var F=[];return B&&F.length===0?yh(o,h,y,v):(o={hc:y,Ab:o,Qb:v,mc:F},B?(o.Mb="spawnThread",postMessage(o,F),0):ph(o))}var Mh=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,vh=(o,h,y)=>{var v=(h>>>=0)+y;for(y=h;o[y]&&!(y>=v);)++y;if(16(F=(240&F)==224?(15&F)<<12|oe<<6|We:(7&F)<<18|oe<<12|We<<6|63&o[h++])?v+=String.fromCharCode(F):(F-=65536,v+=String.fromCharCode(55296|F>>10,56320|1023&F))}}else v+=String.fromCharCode(F)}return v},gn=(o,h)=>(o>>>=0)?vh(n(),o,h):"";function xh(o,h,y){return B?Yr(3,1,o,h,y):0}function Th(o,h){if(B)return Yr(4,1,o,h)}var Vc=o=>{for(var h=0,y=0;y=v?h++:2047>=v?h+=2:55296<=v&&57343>=v?(h+=4,++y):h+=3}return h},Ch=(o,h,y,v)=>{if(!(0>>=0;v=y+v-1;for(var oe=0;oe=We&&(We=65536+((1023&We)<<10)|1023&o.charCodeAt(++oe)),127>=We){if(y>=v)break;h[y++>>>0]=We}else{if(2047>=We){if(y+1>=v)break;h[y++>>>0]=192|We>>6}else{if(65535>=We){if(y+2>=v)break;h[y++>>>0]=224|We>>12}else{if(y+3>=v)break;h[y++>>>0]=240|We>>18,h[y++>>>0]=128|We>>12&63}h[y++>>>0]=128|We>>6&63}h[y++>>>0]=128|63&We}}return h[y>>>0]=0,y-F},to=(o,h,y)=>Ch(o,n(),h,y);function Eh(o,h){if(B)return Yr(5,1,o,h)}function $h(o,h,y){if(B)return Yr(6,1,o,h,y)}function Sh(o,h,y){return B?Yr(7,1,o,h,y):0}function kh(o,h){if(B)return Yr(8,1,o,h)}function Ph(o,h,y){if(B)return Yr(9,1,o,h,y)}function Ah(o,h,y,v){if(B)return Yr(10,1,o,h,y,v)}function Ih(o,h,y,v){if(B)return Yr(11,1,o,h,y,v)}function Fh(o,h,y,v){if(B)return Yr(12,1,o,h,y,v)}function zh(o){if(B)return Yr(13,1,o)}function Oh(o,h){if(B)return Yr(14,1,o,h)}function Dh(o,h,y){if(B)return Yr(15,1,o,h,y)}var Lh,Gs,om=()=>{eo("")},us=o=>{for(var h="";n()[o>>>0];)h+=Lh[n()[o++>>>0]];return h},Uc={},Wc={};function xs(o,h,y={}){if(!("argPackAdvance"in h))throw new TypeError("registerType registeredInstance requires argPackAdvance");return function(v,F,oe={}){var We=F.name;if(!v)throw new Gs(`type "${We}" must have a positive integer typeid pointer`);if(Wc.hasOwnProperty(v)){if(oe.Sb)return;throw new Gs(`Cannot register type '${We}' twice`)}Wc[v]=F,Uc.hasOwnProperty(v)&&(F=Uc[v],delete Uc[v],F.forEach(it=>it()))}(o,h,y)}var Bh=(o,h,y)=>{switch(h){case 1:return y?v=>r()[v>>>0]:v=>n()[v>>>0];case 2:return y?v=>s()[v>>>1>>>0]:v=>a()[v>>>1>>>0];case 4:return y?v=>i()[v>>>2>>>0]:v=>u()[v>>>2>>>0];case 8:return y?v=>un[v>>>3]:v=>Vs[v>>>3];default:throw new TypeError(`invalid integer width (${h}): ${o}`)}};function lm(o,h,y){y>>>=0,xs(o>>>=0,{name:h=us(h>>>0),fromWireType:v=>v,toWireType:function(v,F){if(typeof F!="bigint"&&typeof F!="number")throw F=F===null?"null":(v=typeof F)=="object"||v==="array"||v==="function"?F.toString():""+F,new TypeError(`Cannot convert "${F}" to ${this.name}`);return typeof F=="number"&&(F=BigInt(F)),F},argPackAdvance:qs,readValueFromPointer:Bh(h,y,h.indexOf("u")==-1),Db:null})}var qs=8;function um(o,h,y,v){xs(o>>>=0,{name:h=us(h>>>0),fromWireType:function(F){return!!F},toWireType:function(F,oe){return oe?y:v},argPackAdvance:qs,readValueFromPointer:function(F){return this.fromWireType(n()[F>>>0])},Db:null})}var Gc=[],Ts=[];function qc(o){9<(o>>>=0)&&--Ts[o+1]==0&&(Ts[o]=void 0,Gc.push(o))}var Un=o=>{if(!o)throw new Gs("Cannot use deleted val. handle = "+o);return Ts[o]},Wn=o=>{switch(o){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let h=Gc.pop()||Ts.length;return Ts[h]=o,Ts[h+1]=1,h}};function Hc(o){return this.fromWireType(u()[o>>>2>>>0])}var dm={name:"emscripten::val",fromWireType:o=>{var h=Un(o);return qc(o),h},toWireType:(o,h)=>Wn(h),argPackAdvance:qs,readValueFromPointer:Hc,Db:null};function cm(o){return xs(o>>>0,dm)}var pm=(o,h)=>{switch(h){case 4:return function(y){return this.fromWireType(d()[y>>>2>>>0])};case 8:return function(y){return this.fromWireType(p()[y>>>3>>>0])};default:throw new TypeError(`invalid float width (${h}): ${o}`)}};function hm(o,h,y){y>>>=0,xs(o>>>=0,{name:h=us(h>>>0),fromWireType:v=>v,toWireType:(v,F)=>F,argPackAdvance:qs,readValueFromPointer:pm(h,y),Db:null})}function fm(o,h,y,v,F){if(o>>>=0,y>>>=0,h=us(h>>>0),F===-1&&(F=4294967295),F=it=>it,v===0){var oe=32-8*y;F=it=>it<>>oe}var We=h.includes("unsigned")?function(it,Ft){return Ft>>>0}:function(it,Ft){return Ft};xs(o,{name:h,fromWireType:F,toWireType:We,argPackAdvance:qs,readValueFromPointer:Bh(h,y,v!==0),Db:null})}function mm(o,h,y){function v(oe){var We=u()[oe>>>2>>>0];return oe=u()[oe+4>>>2>>>0],new F(r().buffer,oe,We)}var F=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][h];xs(o>>>=0,{name:y=us(y>>>0),fromWireType:v,argPackAdvance:qs,readValueFromPointer:v},{Sb:!0})}function _m(o,h){o>>>=0;var y=(h=us(h>>>0))==="std::string";xs(o,{name:h,fromWireType:function(v){var F=u()[v>>>2>>>0],oe=v+4;if(y)for(var We=oe,it=0;it<=F;++it){var Ft=oe+it;if(it==F||n()[Ft>>>0]==0){if(We=gn(We,Ft-We),Lt===void 0)var Lt=We;else Lt+="\0",Lt+=We;We=Ft+1}}else{for(Lt=Array(F),it=0;it>>0]);Lt=Lt.join("")}return cs(v),Lt},toWireType:function(v,F){F instanceof ArrayBuffer&&(F=new Uint8Array(F));var oe=typeof F=="string";if(!(oe||F instanceof Uint8Array||F instanceof Uint8ClampedArray||F instanceof Int8Array))throw new Gs("Cannot pass non-string to std::string");var We=y&&oe?Vc(F):F.length,it=dc(4+We+1),Ft=it+4;if(u()[it>>>2>>>0]=We,y&&oe)to(F,Ft,We+1);else if(oe)for(oe=0;oe>>0]=Lt}else for(oe=0;oe>>0]=F[oe];return v!==null&&v.push(cs,it),it},argPackAdvance:qs,readValueFromPointer:Hc,Db(v){cs(v)}})}var Rh=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,gm=(o,h)=>{for(var y=o>>1,v=y+h/2;!(y>=v)&&a()[y>>>0];)++y;if(32<(y<<=1)-o&&Rh)return Rh.decode(n().slice(o,y));for(y="",v=0;!(v>=h/2);++v){var F=s()[o+2*v>>>1>>>0];if(F==0)break;y+=String.fromCharCode(F)}return y},wm=(o,h,y)=>{if(y??(y=2147483647),2>y)return 0;var v=h;y=(y-=2)<2*o.length?y/2:o.length;for(var F=0;F>>1>>>0]=oe,h+=2}return s()[h>>>1>>>0]=0,h-v},ym=o=>2*o.length,bm=(o,h)=>{for(var y=0,v="";!(y>=h/4);){var F=i()[o+4*y>>>2>>>0];if(F==0)break;++y,65536<=F?(F-=65536,v+=String.fromCharCode(55296|F>>10,56320|1023&F)):v+=String.fromCharCode(F)}return v},Mm=(o,h,y)=>{if(h>>>=0,y??(y=2147483647),4>y)return 0;var v=h;y=v+y-4;for(var F=0;F=oe&&(oe=65536+((1023&oe)<<10)|1023&o.charCodeAt(++F)),i()[h>>>2>>>0]=oe,(h+=4)+4>y)break}return i()[h>>>2>>>0]=0,h-v},vm=o=>{for(var h=0,y=0;y=v&&++y,h+=4}return h};function xm(o,h,y){if(o>>>=0,h>>>=0,y=us(y>>>=0),h===2)var v=gm,F=wm,oe=ym,We=it=>a()[it>>>1>>>0];else h===4&&(v=bm,F=Mm,oe=vm,We=it=>u()[it>>>2>>>0]);xs(o,{name:y,fromWireType:it=>{for(var Ft,Lt=u()[it>>>2>>>0],Qt=it+4,Cr=0;Cr<=Lt;++Cr){var Lr=it+4+Cr*h;Cr!=Lt&&We(Lr)!=0||(Qt=v(Qt,Lr-Qt),Ft===void 0?Ft=Qt:(Ft+="\0",Ft+=Qt),Qt=Lr+h)}return cs(it),Ft},toWireType:(it,Ft)=>{if(typeof Ft!="string")throw new Gs(`Cannot pass non-string to C++ string type ${y}`);var Lt=oe(Ft),Qt=dc(4+Lt+h);return u()[Qt>>>2>>>0]=Lt/h,F(Ft,Qt+4,Lt+h),it!==null&&it.push(cs,Qt),Qt},argPackAdvance:qs,readValueFromPointer:Hc,Db(it){cs(it)}})}function Tm(o,h){xs(o>>>=0,{Tb:!0,name:h=us(h>>>0),argPackAdvance:0,fromWireType:()=>{},toWireType:()=>{}})}var Cm=()=>1;function Em(o){tp(o>>>0,!E,1,!C,131072,!1),_h()}var Nh=o=>{if(!En)try{if(o(),!(0>>=0,typeof Atomics.nc=="function"&&(Atomics.nc(i(),o>>>2,o).value.then(rc),o+=128,Atomics.store(i(),o>>>2,1))}var rc=()=>{var o=no();o&&(Kc(o),Nh(gf))};function $m(o,h){(o>>>=0)==h>>>0?setTimeout(rc):B?postMessage({targetThread:o,cmd:"checkMailbox"}):(o=ls[o])&&o.postMessage({cmd:"checkMailbox"})}var Xc=[];function Sm(o,h,y,v,F){for(h>>>=0,v/=2,Xc.length=v,y=F>>>0>>>3,F=0;F>>0];return(h?Lc[h]:g_[o])(...Xc)}function km(o){o>>>=0,B?postMessage({cmd:"cleanupThread",thread:o}):mh(ls[o])}function Pm(o){}var Qc=(o,h)=>{var y=Wc[o];if(y===void 0)throw o=hf(o),y=us(o),cs(o),new Gs(`${h} has unknown type ${y}`);return y},jh=(o,h,y)=>{var v=[];return o=o.toWireType(v,y),v.length&&(u()[h>>>2>>>0]=Wn(v)),o};function Am(o,h,y){return h>>>=0,y>>>=0,o=Un(o>>>0),h=Qc(h,"emval::as"),jh(h,y,o)}var nc=o=>{try{o()}catch(h){eo(h)}},Hs=0,ds=null,Vh=0,sc=[],Uh={},Wh={},Im=0,Yc=null,Fm=[];function Gh(o){return function(h){if(!En){if(Hs===0){var y=!1,v=!1;h((F=0)=>{if(!En&&(Vh=F,y=!0,v)){Hs=2,nc(()=>vf(ds)),typeof Browser<"u"&&Browser.Kb.Rb&&Browser.Kb.resume(),F=!1;try{var oe=function(){var Ft=i()[ds+8>>>2>>>0];return Ft=Kt[Wh[Ft]],--bi,Ft()}()}catch(Ft){oe=Ft,F=!0}var We=!1;if(!ds){var it=Yc;it&&(Yc=null,(F?it.reject:it.resolve)(oe),We=!0)}if(F&&!We)throw oe}}),v=!0,y||(Hs=1,ds=function(){var F=dc(65548),oe=F+12;u()[F>>>2>>>0]=oe,u()[F+4>>>2>>>0]=oe+65536,oe=sc[0];var We=Uh[oe];return We===void 0&&(We=Im++,Uh[oe]=We,Wh[We]=oe),oe=We,i()[F+8>>>2>>>0]=oe,F}(),typeof Browser<"u"&&Browser.Kb.Rb&&Browser.Kb.pause(),nc(()=>bf(ds)))}else Hs===2?(Hs=0,nc(xf),cs(ds),ds=null,Fm.forEach(Nh)):eo(`invalid state: ${Hs}`);return Vh}}(h=>{o().then(h)})}function zm(o){return o>>>=0,Gh(()=>(o=Un(o)).then(Wn))}var ic=[];function Om(o,h,y,v){return y>>>=0,v>>>=0,(o=ic[o>>>0])(null,h=Un(h>>>0),y,v)}var Dm={},ac=o=>{var h=Dm[o];return h===void 0?us(o):h};function Lm(o,h,y,v,F){return y>>>=0,v>>>=0,F>>>=0,(o=ic[o>>>0])(h=Un(h>>>0),h[y=ac(y)],v,F)}var qh=()=>typeof globalThis=="object"?globalThis:Function("return this")();function Bm(o){return(o>>>=0)==0?Wn(qh()):(o=ac(o),Wn(qh()[o]))}var Rm=o=>{var h=ic.length;return ic.push(o),h},Nm=(o,h)=>{for(var y=Array(o),v=0;v>>2>>>0],"parameter "+v);return y},Hh=(o,h)=>Object.defineProperty(h,"name",{value:o});function jm(o,h,y){var v=(h=Nm(o,h>>>0)).shift();o--;var F=`return function (obj, func, destructorsRef, args) { -`,oe=0,We=[];y===0&&We.push("obj");for(var it=["retType"],Ft=[v],Lt=0;LtQt.name).join(", ")}) => ${v.name}>`,Rm(Hh(y,o))}function Vm(o){return o=ac(o>>>0),Wn(l[o])}function Um(o,h){return h>>>=0,o=Un(o>>>0),h=Un(h),Wn(o[h])}function Wm(o){9<(o>>>=0)&&(Ts[o+1]+=1)}function Gm(){return Wn([])}function qm(o){o=Un(o>>>0);for(var h=Array(o.length),y=0;y>>0))}function Km(){return Wn({})}function Xm(o){for(var h=Un(o>>>=0);h.length;){var y=h.pop();h.pop()(y)}qc(o)}function Qm(o,h,y){h>>>=0,y>>>=0,o=Un(o>>>0),h=Un(h),y=Un(y),o[h]=y}function Ym(o,h){return h>>>=0,o=(o=Qc(o>>>0,"_emval_take_value")).readValueFromPointer(h),Wn(o)}function Jm(o,h){o=-9007199254740992>o||9007199254740992>>=0,o=new Date(1e3*o),i()[h>>>2>>>0]=o.getUTCSeconds(),i()[h+4>>>2>>>0]=o.getUTCMinutes(),i()[h+8>>>2>>>0]=o.getUTCHours(),i()[h+12>>>2>>>0]=o.getUTCDate(),i()[h+16>>>2>>>0]=o.getUTCMonth(),i()[h+20>>>2>>>0]=o.getUTCFullYear()-1900,i()[h+24>>>2>>>0]=o.getUTCDay(),o=(o.getTime()-Date.UTC(o.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,i()[h+28>>>2>>>0]=o}var ro=o=>o%4==0&&(o%100!=0||o%400==0),Kh=[0,31,60,91,121,152,182,213,244,274,305,335],Xh=[0,31,59,90,120,151,181,212,243,273,304,334];function Zm(o,h){o=-9007199254740992>o||9007199254740992>>=0,o=new Date(1e3*o),i()[h>>>2>>>0]=o.getSeconds(),i()[h+4>>>2>>>0]=o.getMinutes(),i()[h+8>>>2>>>0]=o.getHours(),i()[h+12>>>2>>>0]=o.getDate(),i()[h+16>>>2>>>0]=o.getMonth(),i()[h+20>>>2>>>0]=o.getFullYear()-1900,i()[h+24>>>2>>>0]=o.getDay();var y=(ro(o.getFullYear())?Kh:Xh)[o.getMonth()]+o.getDate()-1|0;i()[h+28>>>2>>>0]=y,i()[h+36>>>2>>>0]=-60*o.getTimezoneOffset(),y=new Date(o.getFullYear(),6,1).getTimezoneOffset();var v=new Date(o.getFullYear(),0,1).getTimezoneOffset();o=0|(y!=v&&o.getTimezoneOffset()==Math.min(v,y)),i()[h+32>>>2>>>0]=o}function e_(o){o>>>=0;var h=new Date(i()[o+20>>>2>>>0]+1900,i()[o+16>>>2>>>0],i()[o+12>>>2>>>0],i()[o+8>>>2>>>0],i()[o+4>>>2>>>0],i()[o>>>2>>>0],0),y=i()[o+32>>>2>>>0],v=h.getTimezoneOffset(),F=new Date(h.getFullYear(),6,1).getTimezoneOffset(),oe=new Date(h.getFullYear(),0,1).getTimezoneOffset(),We=Math.min(oe,F);return 0>y?i()[o+32>>>2>>>0]=+(F!=oe&&We==v):0>>2>>>0]=h.getDay(),y=(ro(h.getFullYear())?Kh:Xh)[h.getMonth()]+h.getDate()-1|0,i()[o+28>>>2>>>0]=y,i()[o>>>2>>>0]=h.getSeconds(),i()[o+4>>>2>>>0]=h.getMinutes(),i()[o+8>>>2>>>0]=h.getHours(),i()[o+12>>>2>>>0]=h.getDate(),i()[o+16>>>2>>>0]=h.getMonth(),i()[o+20>>>2>>>0]=h.getYear(),o=h.getTime(),BigInt(isNaN(o)?-1:o/1e3)}function Qh(o,h,y,v,F,oe,We){return B?Yr(16,1,o,h,y,v,F,oe,We):-52}function Yh(o,h,y,v,F,oe){if(B)return Yr(17,1,o,h,y,v,F,oe)}function t_(o,h,y,v){o>>>=0,h>>>=0,y>>>=0,v>>>=0;var F=new Date().getFullYear(),oe=new Date(F,0,1),We=new Date(F,6,1);F=oe.getTimezoneOffset();var it=We.getTimezoneOffset(),Ft=Math.max(F,it);u()[o>>>2>>>0]=60*Ft,i()[h>>>2>>>0]=+(F!=it),oe=(o=Lt=>Lt.toLocaleTimeString(void 0,{hour12:!1,timeZoneName:"short"}).split(" ")[1])(oe),We=o(We),it{Jc.length=0;for(var y;y=n()[o++>>>0];){var v=y!=105;h+=(v&=y!=112)&&h%8?4:0,Jc.push(y==112?u()[h>>>2>>>0]:y==106?un[h>>>3]:y==105?i()[h>>>2>>>0]:p()[h>>>3>>>0]),h+=v?8:4}return Jc};function r_(o,h,y){return o>>>=0,h=Jh(h>>>0,y>>>0),Lc[o](...h)}function n_(o,h,y){return o>>>=0,h=Jh(h>>>0,y>>>0),Lc[o](...h)}var s_=()=>{},i_=()=>Date.now();function a_(o,h){return er(gn(o>>>0,h>>>0))}var Zh,o_=()=>{throw bi+=1,"unwind"};function l_(){return 4294901760}Zh=()=>performance.timeOrigin+performance.now();var u_=()=>navigator.hardwareConcurrency;function d_(){return eo("Cannot use emscripten_pc_get_function without -sUSE_OFFSET_CONVERTER"),0}function c_(o){o>>>=0;var h=n().length;if(o<=h||4294901760=y;y*=2){var v=h*(1+.2/y);v=Math.min(v,o+100663296);var F=Math;v=Math.max(o,v);e:{F=(F.min.call(F,4294901760,v+(65536-v%65536)%65536)-br.buffer.byteLength+65535)/65536;try{br.grow(F),mn();var oe=1;break e}catch{}oe=void 0}if(oe)return!0}return!1}var oc=()=>(eo("Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER"),0),_d={},ef=o=>{o.forEach(h=>{oc()})};function p_(){var o=Error().stack.toString().split(` -`);return o[0]=="Error"&&o.shift(),ef(o),_d.Pb=oc(),_d.ec=o,_d.Pb}function h_(o,h,y){if(o>>>=0,h>>>=0,_d.Pb==o)var v=_d.ec;else(v=Error().stack.toString().split(` -`))[0]=="Error"&&v.shift(),ef(v);for(var F=3;v[F]&&oc()!=o;)++F;for(o=0;o>>2>>>0]=oc();return o}var Zc,ep={},tf=()=>{if(!Zc){var o,h={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",_:Ge};for(o in ep)ep[o]===void 0?delete h[o]:h[o]=ep[o];var y=[];for(o in h)y.push(`${o}=${h[o]}`);Zc=y}return Zc};function rf(o,h){if(B)return Yr(18,1,o,h);o>>>=0,h>>>=0;var y=0;return tf().forEach((v,F)=>{var oe=h+y;for(F=u()[o+4*F>>>2>>>0]=oe,oe=0;oe>>0]=v.charCodeAt(oe);r()[F>>>0]=0,y+=v.length+1}),0}function nf(o,h){if(B)return Yr(19,1,o,h);o>>>=0,h>>>=0;var y=tf();u()[o>>>2>>>0]=y.length;var v=0;return y.forEach(F=>v+=F.length+1),u()[h>>>2>>>0]=v,0}function sf(o){return B?Yr(20,1,o):52}function af(o,h,y,v){return B?Yr(21,1,o,h,y,v):52}function of(o,h,y,v){return B?Yr(22,1,o,h,y,v):70}var f_=[null,[],[]];function lf(o,h,y,v){if(B)return Yr(23,1,o,h,y,v);h>>>=0,y>>>=0,v>>>=0;for(var F=0,oe=0;oe>>2>>>0],it=u()[h+4>>>2>>>0];h+=8;for(var Ft=0;Ft>>0],Qt=f_[o];Lt===0||Lt===10?((o===1?fr:er)(vh(Qt,0)),Qt.length=0):Qt.push(Lt)}F+=it}return u()[v>>>2>>>0]=F,0}var uf=[31,29,31,30,31,30,31,31,30,31,30,31],df=[31,28,31,30,31,30,31,31,30,31,30,31],m_=(o,h)=>{r().set(o,h>>>0)};function cf(o,h,y,v){function F(Be,Mr,tn){for(Be=typeof Be=="number"?Be.toString():Be||"";Be.lengthCf?-1:0vi-Be.getDate())){Be.setDate(Be.getDate()+Mr);break}Mr-=vi-Be.getDate()+1,Be.setDate(1),11>tn?Be.setMonth(tn+1):(Be.setMonth(0),Be.setFullYear(Be.getFullYear()+1))}return tn=new Date(Be.getFullYear()+1,0,4),Mr=it(new Date(Be.getFullYear(),0,4)),tn=it(tn),0>=We(Mr,Be)?0>=We(tn,Be)?Be.getFullYear()+1:Be.getFullYear():Be.getFullYear()-1}o>>>=0,h>>>=0,y>>>=0,v>>>=0;var Lt=u()[v+40>>>2>>>0];for(var Qt in v={kc:i()[v>>>2>>>0],jc:i()[v+4>>>2>>>0],Hb:i()[v+8>>>2>>>0],Lb:i()[v+12>>>2>>>0],Ib:i()[v+16>>>2>>>0],Cb:i()[v+20>>>2>>>0],ub:i()[v+24>>>2>>>0],Bb:i()[v+28>>>2>>>0],rc:i()[v+32>>>2>>>0],ic:i()[v+36>>>2>>>0],lc:Lt?gn(Lt):""},y=gn(y),Lt={"%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"})y=y.replace(new RegExp(Qt,"g"),Lt[Qt]);var Cr="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),Lr="January February March April May June July August September October November December".split(" ");for(Qt in Lt={"%a":Be=>Cr[Be.ub].substring(0,3),"%A":Be=>Cr[Be.ub],"%b":Be=>Lr[Be.Ib].substring(0,3),"%B":Be=>Lr[Be.Ib],"%C":Be=>oe((Be.Cb+1900)/100|0,2),"%d":Be=>oe(Be.Lb,2),"%e":Be=>F(Be.Lb,2," "),"%g":Be=>Ft(Be).toString().substring(2),"%G":Ft,"%H":Be=>oe(Be.Hb,2),"%I":Be=>((Be=Be.Hb)==0?Be=12:12{for(var Mr=0,tn=0;tn<=Be.Ib-1;Mr+=(ro(Be.Cb+1900)?uf:df)[tn++]);return oe(Be.Lb+Mr,3)},"%m":Be=>oe(Be.Ib+1,2),"%M":Be=>oe(Be.jc,2),"%n":()=>` -`,"%p":Be=>0<=Be.Hb&&12>Be.Hb?"AM":"PM","%S":Be=>oe(Be.kc,2),"%t":()=>" ","%u":Be=>Be.ub||7,"%U":Be=>oe(Math.floor((Be.Bb+7-Be.ub)/7),2),"%V":Be=>{var Mr=Math.floor((Be.Bb+7-(Be.ub+6)%7)/7);if(2>=(Be.ub+371-Be.Bb-2)%7&&Mr++,Mr)Mr==53&&((tn=(Be.ub+371-Be.Bb)%7)==4||tn==3&&ro(Be.Cb)||(Mr=1));else{Mr=52;var tn=(Be.ub+7-Be.Bb-1)%7;(tn==4||tn==5&&ro(Be.Cb%400-1))&&Mr++}return oe(Mr,2)},"%w":Be=>Be.ub,"%W":Be=>oe(Math.floor((Be.Bb+7-(Be.ub+6)%7)/7),2),"%y":Be=>(Be.Cb+1900).toString().substring(2),"%Y":Be=>Be.Cb+1900,"%z":Be=>{var Mr=0<=(Be=Be.ic);return Be=Math.abs(Be)/60,(Mr?"+":"-")+("0000"+(Be/60*100+Be%60)).slice(-4)},"%Z":Be=>Be.lc,"%%":()=>"%"},y=y.replace(/%%/g,"\0\0"),Lt)y.includes(Qt)&&(y=y.replace(new RegExp(Qt,"g"),Lt[Qt](v)));return Qt=function(Be){var Mr=Array(Vc(Be)+1);return Ch(Be,Mr,0,Mr.length),Mr}(y=y.replace(/\0\0/g,"%")),Qt.length>h?0:(m_(Qt,o),Qt.length-1)}function __(o,h,y,v){return cf(o>>>0,h>>>0,y>>>0,v>>>0)}B||function(){for(var o=l.numThreads-1;o--;)wh();yi.unshift(()=>{Vn++,function(h){B?h():Promise.all(Ws.map(gh)).then(h)}(()=>ec())})}();for(var pf=Array(256),lc=0;256>lc;++lc)pf[lc]=String.fromCharCode(lc);Lh=pf,Gs=l.BindingError=class extends Error{constructor(o){super(o),this.name="BindingError"}},l.InternalError=class extends Error{constructor(o){super(o),this.name="InternalError"}},Ts.push(0,1,void 0,1,null,1,!0,1,!1,1),l.count_emval_handles=()=>Ts.length/2-5-Gc.length;var g_=[Nc,hh,yh,xh,Th,Eh,$h,Sh,kh,Ph,Ah,Ih,Fh,zh,Oh,Dh,Qh,Yh,rf,nf,sf,af,of,lf],Kt=function(){function o(y,v){return Kt=y.exports,Kt=function(){var F=Kt,oe={};for(let[We,it]of Object.entries(F))oe[We]=typeof it=="function"?(...Ft)=>{sc.push(We);try{return it(...Ft)}finally{En||(sc.pop(),ds&&Hs===1&&sc.length===0&&(Hs=0,bi+=1,nc(Mf),typeof Fibers<"u"&&Fibers.sc()))}}:it;return oe}(),Kt=function(){var F=Kt,oe=it=>Ft=>it(Ft)>>>0,We=it=>()=>it()>>>0;return(F=Object.assign({},F)).Ca=oe(F.Ca),F.fb=We(F.fb),F.gb=oe(F.gb),F.emscripten_main_runtime_thread_id=We(F.emscripten_main_runtime_thread_id),F.sb=oe(F.sb),F.tb=We(F.tb),F}(),fh.push(Kt.ib),hn.unshift(Kt.Ba),jr=v,ec(),Kt}var h=ch();if(Vn++,l.instantiateWasm)try{return l.instantiateWasm(h,o)}catch(y){er(`Module.instantiateWasm callback failed with error: ${y}`),w(y)}return Dc||(Dc=l.locateFile?oh("ort-wasm-simd-threaded.jsep.wasm")?"ort-wasm-simd-threaded.jsep.wasm":l.locateFile?l.locateFile("ort-wasm-simd-threaded.jsep.wasm",pt):pt+"ort-wasm-simd-threaded.jsep.wasm":new URL(N("./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm"),N.b).href),function(y,v){var F=Dc;return Dt||typeof WebAssembly.instantiateStreaming!="function"||oh(F)||lh(F)||typeof fetch!="function"?dh(F,y,v):fetch(F,{credentials:"same-origin"}).then(oe=>WebAssembly.instantiateStreaming(oe,y).then(v,function(We){return er(`wasm streaming compile failed: ${We}`),er("falling back to ArrayBuffer instantiation"),dh(F,y,v)}))}(h,function(y){o(y.instance,y.module)}).catch(w),{}}(),hf=o=>(hf=Kt.Ca)(o),ff=()=>(ff=Kt.Da)();l._OrtInit=(o,h)=>(l._OrtInit=Kt.Ea)(o,h),l._OrtGetLastError=(o,h)=>(l._OrtGetLastError=Kt.Fa)(o,h),l._OrtCreateSessionOptions=(o,h,y,v,F,oe,We,it,Ft,Lt)=>(l._OrtCreateSessionOptions=Kt.Ga)(o,h,y,v,F,oe,We,it,Ft,Lt),l._OrtAppendExecutionProvider=(o,h)=>(l._OrtAppendExecutionProvider=Kt.Ha)(o,h),l._OrtAddFreeDimensionOverride=(o,h,y)=>(l._OrtAddFreeDimensionOverride=Kt.Ia)(o,h,y),l._OrtAddSessionConfigEntry=(o,h,y)=>(l._OrtAddSessionConfigEntry=Kt.Ja)(o,h,y),l._OrtReleaseSessionOptions=o=>(l._OrtReleaseSessionOptions=Kt.Ka)(o),l._OrtCreateSession=(o,h,y)=>(l._OrtCreateSession=Kt.La)(o,h,y),l._OrtReleaseSession=o=>(l._OrtReleaseSession=Kt.Ma)(o),l._OrtGetInputOutputCount=(o,h,y)=>(l._OrtGetInputOutputCount=Kt.Na)(o,h,y),l._OrtGetInputName=(o,h)=>(l._OrtGetInputName=Kt.Oa)(o,h),l._OrtGetOutputName=(o,h)=>(l._OrtGetOutputName=Kt.Pa)(o,h),l._OrtFree=o=>(l._OrtFree=Kt.Qa)(o),l._OrtCreateTensor=(o,h,y,v,F,oe)=>(l._OrtCreateTensor=Kt.Ra)(o,h,y,v,F,oe),l._OrtGetTensorData=(o,h,y,v,F)=>(l._OrtGetTensorData=Kt.Sa)(o,h,y,v,F),l._OrtReleaseTensor=o=>(l._OrtReleaseTensor=Kt.Ta)(o),l._OrtCreateRunOptions=(o,h,y,v)=>(l._OrtCreateRunOptions=Kt.Ua)(o,h,y,v),l._OrtAddRunConfigEntry=(o,h,y)=>(l._OrtAddRunConfigEntry=Kt.Va)(o,h,y),l._OrtReleaseRunOptions=o=>(l._OrtReleaseRunOptions=Kt.Wa)(o),l._OrtCreateBinding=o=>(l._OrtCreateBinding=Kt.Xa)(o),l._OrtBindInput=(o,h,y)=>(l._OrtBindInput=Kt.Ya)(o,h,y),l._OrtBindOutput=(o,h,y,v)=>(l._OrtBindOutput=Kt.Za)(o,h,y,v),l._OrtClearBoundOutputs=o=>(l._OrtClearBoundOutputs=Kt._a)(o),l._OrtReleaseBinding=o=>(l._OrtReleaseBinding=Kt.$a)(o),l._OrtRunWithBinding=(o,h,y,v,F)=>(l._OrtRunWithBinding=Kt.ab)(o,h,y,v,F),l._OrtRun=(o,h,y,v,F,oe,We,it)=>(l._OrtRun=Kt.bb)(o,h,y,v,F,oe,We,it),l._OrtEndProfiling=o=>(l._OrtEndProfiling=Kt.cb)(o),l._JsepOutput=(o,h,y)=>(l._JsepOutput=Kt.db)(o,h,y),l._JsepGetNodeName=o=>(l._JsepGetNodeName=Kt.eb)(o);var uc,no=()=>(no=Kt.fb)(),dc=l._malloc=o=>(dc=l._malloc=Kt.gb)(o),cs=l._free=o=>(cs=l._free=Kt.hb)(o),tp=(o,h,y,v,F,oe)=>(tp=Kt.kb)(o,h,y,v,F,oe),mf=()=>(mf=Kt.lb)(),_f=(o,h,y,v,F)=>(_f=Kt.mb)(o,h,y,v,F),rp=o=>(rp=Kt.nb)(o),cc=o=>(cc=Kt.ob)(o),gf=()=>(gf=Kt.pb)(),wf=(o,h)=>(wf=Kt.qb)(o,h),pc=o=>(pc=Kt.rb)(o),np=o=>(np=Kt.sb)(o),sp=()=>(sp=Kt.tb)(),yf=l.dynCall_ii=(o,h)=>(yf=l.dynCall_ii=Kt.vb)(o,h),bf=o=>(bf=Kt.wb)(o),Mf=()=>(Mf=Kt.xb)(),vf=o=>(vf=Kt.yb)(o),xf=()=>(xf=Kt.zb)();function Tf(){0sp(),l.stackRestore=o=>pc(o),l.stackAlloc=o=>np(o),l.UTF8ToString=gn,l.stringToUTF8=to,l.lengthBytesUTF8=Vc,Us=function o(){uc||Tf(),uc||(Us=o)},Tf(),M}),et=Ae,((e=globalThis.self)==null?void 0:e.name)==="em-pthread"&&Ae()}),Xe,gt,mt,$t,ft,zt,Nt,Rt,Gt=j(()=>{var e,t;cr(),Xe=self.location.href??(typeof document<"u"?(e=document.currentScript)==null?void 0:e.src:typeof self<"u"?(t=self.location)==null?void 0:t.href:void 0),gt=typeof location>"u"?void 0:location.origin,mt=(r,n)=>{try{let s=n??Xe;return(s?new URL(r,s):new URL(r)).origin===gt}catch{return!1}},$t=async r=>{let n=await(await fetch(r,{credentials:"same-origin"})).blob();return URL.createObjectURL(n)},ft=(at(),P(Er)).default,zt=async()=>{if(!Xe)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(mt(Xe))return[void 0,ft()];let r=await $t(Xe);return[r,ft(r)]},Nt=(ve(),P(U)).default,Rt=async(r,n,s)=>[void 0,Nt]}),be,tt,st,qt,wr,Br,Kr,rr,Wr=j(()=>{Gt(),tt=!1,st=!1,qt=!1,wr=()=>{if(typeof SharedArrayBuffer>"u")return!1;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}},Br=()=>{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}},Kr=async e=>{if(tt)return Promise.resolve();if(st)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(qt)throw new Error("previous call to 'initializeWebAssembly()' failed.");st=!0;let t=e.initTimeout,r=e.numThreads;if(!Br())throw new Error("WebAssembly SIMD is not supported in the current environment.");let n=wr();r>1&&!n&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+r+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),e.numThreads=r=1);let s=e.wasmPaths,a=typeof s=="string"?s:void 0,i=s==null?void 0:s.mjs,u=(i==null?void 0:i.href)??i,d=s==null?void 0:s.wasm,p=(d==null?void 0:d.href)??d,g=e.wasmBinary,[w,l]=await Rt(u,a,r>1),M=!1,C=[];if(t>0&&C.push(new Promise(E=>{setTimeout(()=>{M=!0,E()},t)})),C.push(new Promise((E,B)=>{let G={numThreads:r};g?G.wasmBinary=g:(p||a)&&(G.locateFile=(O,ae)=>p??(a??ae)+O),l(G).then(O=>{st=!1,tt=!0,be=O,E(),w&&URL.revokeObjectURL(w)},O=>{st=!1,qt=!0,B(O)})})),await Promise.race(C),M)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},rr=()=>{if(tt&&be)return be;throw new Error("WebAssembly is not initialized yet.")}}),Vr,Ln,Rr,Bn=j(()=>{Wr(),Vr=(e,t)=>{let r=rr(),n=r.lengthBytesUTF8(e)+1,s=r._malloc(n);return r.stringToUTF8(e,s,n),t.push(s),s},Ln=(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(([s,a])=>{let i=t?t+s:s;if(typeof a=="object")Ln(a,i+".",r,n);else if(typeof a=="string"||typeof a=="number")n(i,a.toString());else if(typeof a=="boolean")n(i,a?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof a}`)})},Rr=e=>{let t=rr(),r=t.stackSave();try{let n=t.stackAlloc(8);t._OrtGetLastError(n,n+4);let s=t.HEAP32[n/4],a=t.HEAPU32[n/4+1],i=a?t.UTF8ToString(a):"";throw new Error(`${e} ERROR_CODE: ${s}, ERROR_MESSAGE: ${i}`)}finally{t.stackRestore(r)}}}),Cs,Xs=j(()=>{Wr(),Bn(),Cs=e=>{let t=rr(),r=0,n=[],s=e||{};try{if((e==null?void 0:e.logSeverityLevel)===void 0)s.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)s.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&&(s.terminate=!1);let a=0;return(e==null?void 0:e.tag)!==void 0&&(a=Vr(e.tag,n)),r=t._OrtCreateRunOptions(s.logSeverityLevel,s.logVerbosityLevel,!!s.terminate,a),r===0&&Rr("Can't create run options."),(e==null?void 0:e.extra)!==void 0&&Ln(e.extra,"",new WeakSet,(i,u)=>{let d=Vr(i,n),p=Vr(u,n);t._OrtAddRunConfigEntry(r,d,p)!==0&&Rr(`Can't set a run config entry: ${i} - ${u}.`)}),[r,n]}catch(a){throw r!==0&&t._OrtReleaseRunOptions(r),n.forEach(i=>t._free(i)),a}}}),Es,$s,Ss,Gn,ks,Qs=j(()=>{Wr(),Bn(),Es=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}`)}},$s=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},Ss=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)},Gn=(e,t,r)=>{for(let n of t){let s=typeof n=="string"?n:n.name;switch(s){case"webnn":if(s="WEBNN",typeof n!="string"){let i=n==null?void 0:n.deviceType;if(i){let u=Vr("deviceType",r),d=Vr(i,r);rr()._OrtAddSessionConfigEntry(e,u,d)!==0&&Rr(`Can't set a session config entry: 'deviceType' - ${i}.`)}}break;case"webgpu":if(s="JS",typeof n!="string"){let i=n;if(i!=null&&i.preferredLayout){if(i.preferredLayout!=="NCHW"&&i.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${i.preferredLayout}`);let u=Vr("preferredLayout",r),d=Vr(i.preferredLayout,r);rr()._OrtAddSessionConfigEntry(e,u,d)!==0&&Rr(`Can't set a session config entry: 'preferredLayout' - ${i.preferredLayout}.`)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${s}`)}let a=Vr(s,r);rr()._OrtAppendExecutionProvider(e,a)!==0&&Rr(`Can't append execution provider: ${s}.`)}},ks=e=>{let t=rr(),r=0,n=[],s=e||{};Ss(s);try{let a=Es(s.graphOptimizationLevel??"all"),i=$s(s.executionMode??"sequential"),u=typeof s.logId=="string"?Vr(s.logId,n):0,d=s.logSeverityLevel??2;if(!Number.isInteger(d)||d<0||d>4)throw new Error(`log serverity level is not valid: ${d}`);let p=s.logVerbosityLevel??0;if(!Number.isInteger(p)||p<0||p>4)throw new Error(`log verbosity level is not valid: ${p}`);let g=typeof s.optimizedModelFilePath=="string"?Vr(s.optimizedModelFilePath,n):0;if(r=t._OrtCreateSessionOptions(a,!!s.enableCpuMemArena,!!s.enableMemPattern,i,!!s.enableProfiling,0,u,d,p,g),r===0&&Rr("Can't create session options."),s.executionProviders&&Gn(r,s.executionProviders,n),s.enableGraphCapture!==void 0){if(typeof s.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${s.enableGraphCapture}`);let w=Vr("enableGraphCapture",n),l=Vr(s.enableGraphCapture.toString(),n);t._OrtAddSessionConfigEntry(r,w,l)!==0&&Rr(`Can't set a session config entry: 'enableGraphCapture' - ${s.enableGraphCapture}.`)}if(s.freeDimensionOverrides)for(let[w,l]of Object.entries(s.freeDimensionOverrides)){if(typeof w!="string")throw new Error(`free dimension override name must be a string: ${w}`);if(typeof l!="number"||!Number.isInteger(l)||l<0)throw new Error(`free dimension override value must be a non-negative integer: ${l}`);let M=Vr(w,n);t._OrtAddFreeDimensionOverride(r,M,l)!==0&&Rr(`Can't set a free dimension override: ${w} - ${l}.`)}return s.extra!==void 0&&Ln(s.extra,"",new WeakSet,(w,l)=>{let M=Vr(w,n),C=Vr(l,n);t._OrtAddSessionConfigEntry(r,M,C)!==0&&Rr(`Can't set a session config entry: ${w} - ${l}.`)}),[r,n]}catch(a){throw r!==0&&t._OrtReleaseSessionOptions(r),n.forEach(i=>t._free(i)),a}}}),qn,Sn,Cn,ps,ts,hs,fs,rs,Xt=j(()=>{qn=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;case"int4":return 22;case"uint4":return 21;default:throw new Error(`unsupported data type: ${e}`)}},Sn=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";case 22:return"int4";case 21:return"uint4";default:throw new Error(`unsupported data type: ${e}`)}},Cn=(e,t)=>{let r=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],n=typeof t=="number"?t:t.reduce((s,a)=>s*a,1);return r>0?Math.ceil(n*r):void 0},ps=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}`)}},ts=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}`)}},hs=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",fs=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint64"||e==="int8"||e==="uint8"||e==="bool",rs=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;case"ml-tensor":return 5;default:throw new Error(`unsupported data location: ${e}`)}}}),ms,_s=j(()=>{cr(),ms=async e=>{if(typeof e=="string"){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 s=t.body.getReader(),a;try{a=new ArrayBuffer(n)}catch(u){if(u instanceof RangeError){let d=Math.ceil(n/65536);a=new WebAssembly.Memory({initial:d,maximum:d}).buffer}else throw u}let i=0;for(;;){let{done:u,value:d}=await s.read();if(u)break;let p=d.byteLength;new Uint8Array(a,i,p).set(d),i+=p}return new Uint8Array(a,0,n)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),Ps,As,gs,Is,ws,ns,ue,m=j(()=>{Xt(),Ps=["V","I","W","E","F"],As=(e,t)=>{console.log(`[${Ps[e]},${new Date().toISOString()}]${t}`)},ws=(e,t)=>{gs=e,Is=t},ns=(e,t)=>{let r=ts(e),n=ts(gs);r>=n&&As(r,typeof t=="function"?t():t)},ue=(...e)=>{Is&&ns(...e)}}),A,H=j(()=>{Xt(),A=(e,t)=>new(ps(t))(e)}),se=j(()=>{}),pe,De,wt,xt,Mt,Ot,Yt,$r,ar,Dr=j(()=>{m(),se(),pe=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]]),De=[],wt=e=>Math.ceil(e/16)*16,xt=e=>{for(let t=0;tMt++,Yt=async(e,t,r,n)=>{let s=wt(r),a=e.device.createBuffer({size:s,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let i=e.getCommandEncoder();e.endComputePass(),i.copyBufferToBuffer(t,0,a,0,s),e.flush(),await a.mapAsync(GPUMapMode.READ);let u=a.getMappedRange();if(n){let d=n();return d.set(new Uint8Array(u,0,r)),d}else return new Uint8Array(u.slice(0,r))}finally{a.destroy()}},$r=class{constructor(e){this.backend=e,this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.buffersForUploadingPending=[],this.buffersPending=[],this.capturedPendingBuffers=new Map;for(let[t]of pe)De.push(t),this.freeBuffers.set(t,[]),this.freeUniformBuffers.set(t,[])}upload(e,t){let r=t.buffer,n=t.byteOffset,s=t.byteLength,a=wt(s),i=this.storageCache.get(e);if(!i)throw new Error("gpu data for uploading does not exist");if(i.originalSize!==s)throw new Error(`inconsistent data size. gpu data size=${i.originalSize}, data size=${s}`);let u=this.backend.device.createBuffer({mappedAtCreation:!0,size:a,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),d=u.getMappedRange();new Uint8Array(d).set(new Uint8Array(r,n,s)),u.unmap();let p=this.backend.getCommandEncoder();this.backend.endComputePass(),p.copyBufferToBuffer(u,0,i.gpuData.buffer,0,a),ue("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 s=wt(r.originalSize),a=this.backend.getCommandEncoder();this.backend.endComputePass(),a.copyBufferToBuffer(r.gpuData.buffer,0,n.gpuData.buffer,0,s)}registerExternalBuffer(e,t,r){let n;if(r){if(n=r[0],e===r[1])return ue("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!`)}else n=Ot();return this.storageCache.set(n,{gpuData:{id:n,type:0,buffer:e},originalSize:t}),ue("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${n}, registered.`),n}unregisterExternalBuffer(e){e!==void 0&&(this.storageCache.delete(e),ue("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${e}`))}create(e,t=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let r=xt(e),n,s=(t&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,a=(t&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(s||a){let u=(s?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 i={id:Ot(),type:0,buffer:n};return this.storageCache.set(i.id,{gpuData:i,originalSize:e}),ue("verbose",()=>`[WebGPU] GpuDataManager.create(size=${e}) => id=${i.id}`),i}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 ue("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 Yt(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=pe.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))}},ar=(...e)=>new $r(...e)}),Jr,ur,Sr=j(()=>{Jr=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}},ur=e=>new Jr(e)}),_n,wn,Se,Zr,xn,kn,Nn,Ht=j(()=>{_n=class{static calcMatMulShape(e,t){return e[1]!==t[0]?void 0:[e[0],t[1]]}},wn=class{static calcShape(e,t,r=!1){let n=e.length,s=t.length;if(n===0)return t;if(s===0)return e;let a=Math.max(e.length,t.length),i=new Array(a);if(r){if(n<2||s<2)return;let u=_n.calcMatMulShape([e[n-2],e[n-1]],[t[s-2],t[s-1]]);if(u===void 0)return;[i[a-2],i[a-1]]=u}for(let u=r?3:1;u<=a;u++){let d=n-u<0?1:e[n-u],p=s-u<0?1:t[s-u];if(d!==p&&d>1&&p>1)return;let g=Math.max(d,p);if(d&&p)i[a-u]=Math.max(d,p);else{if(g>1)return;i[a-u]=0}}return i}static isValidBroadcast(e,t){let r=e.length,n=t.length;if(r>n)return!1;for(let s=1;s<=r;s++)if(e[r-s]!==1&&e[r-s]!==t[n-s])return!1;return!0}},Se=class hc{static size(t){return hc.getSizeFromDimensionRange(t,0,t.length)}static convertShape(t,r=4){let n=t.length;if(n===0)return[];let s=new Array(n),a=n-1;for(;a>=0;){if(t[a]%r===0){s[a]=t[a]/r;break}if(r%t[a]!==0)throw new Error("cannot convert shape");s[a]=1,r/=t[a],a--}for(a--;a>=0;a--)s[a]=t[a];return s}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 hc.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 hc.getSizeFromDimensionRange(t,0,r)}static getSizeFromDimensionRange(t,r,n){let s=1;for(let a=r;a=0;--s)n[s]=n[s+1]*t[s+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((s,a)=>s+r[a]+r[a+n])}static areEqual(t,r){return t.length!==r.length?!1:t.every((n,s)=>n===r[s])}},Zr=class gd{static adjustPoolAttributes(t,r,n,s,a,i){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]||i[u+n.length]>=n[u])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(t,r,n,s,a,i,u){if(u){if(a.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(s.length!==t.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let d=0;d{Xt(),Ht(),en=64,Xr=(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"];case 22:return"i32";case 21:return"u32";default:throw new Error(`Unknown data type: ${e}`)}},yr=(e,t=1)=>{let r=Xr(e,t);return typeof r=="string"?r:r[0]},Ar=(e,t=1)=>{let r=Xr(e,t);return typeof r=="string"?r:r[1]},Ct=(...e)=>{let t=[];return e.forEach(r=>{r.length!==0&&t.push({type:12,data:r},{type:12,data:Se.computeStrides(r)})}),t},mr=e=>e%4===0?4:e%2===0?2:1,Hn=(e="f32",t,r="0")=>!t||t===1?`${e}(${r})`:`vec${t}<${e}>(${r})`,Kn=(e,t,r)=>e==="f32"?r:t===1?`f32(${r})`:`vec${t}(${r})`,Xn=(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,jt=(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,Ys=(e,t,r,n,s)=>{let a=typeof r=="number",i=a?r:r.length,u=[...new Array(i).keys()],d=i<2?"u32":i<=4?`vec${i}`:`array`,p=Xr(t,s),g=typeof p=="string"?p:p[1],w=typeof p=="string"?p:p[0],l={indices:d,value:g,storage:w,tensor:t},M=Ve=>typeof Ve=="string"?Ve:`${Ve}u`,C={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},E=a?"uniforms.":"",B=`${E}${e}_shape`,G=`${E}${e}_strides`,O="";for(let Ve=0;Ve ${l.indices} { - var indices: ${l.indices}; - var current = offset; - ${O} - return indices; - }`,Z=Ve=>(C.offsetToIndices=!0,i<2?Ve:`o2i_${e}(${Ve})`),le=[];if(i>=2)for(let Ve=i-1;Ve>=0;Ve--)le.push(`${jt(G,Ve,i)} * (indices[${Ve}])`);let Ge=i<2?"":` - fn i2o_${e}(indices: ${l.indices}) -> u32 { - return ${le.join("+")}; - }`,Le=Ve=>(C.indicesToOffset=!0,i<2?Ve:`i2o_${e}(${Ve})`),pt=(...Ve)=>i===0?"0u":`${l.indices}(${Ve.map(M).join(",")})`,Dt=(Ve,kt)=>i<2?`${Ve}`:`${jt(Ve,kt,i)}`,Vt=(Ve,kt,tr)=>i<2?`${Ve}=${tr};`:`${jt(Ve,kt,i)}=${tr};`,lr={},fr=(Ve,kt)=>{C.broadcastedIndicesToOffset=!0;let tr=`${kt.name}broadcastedIndicesTo${e}Offset`;if(tr in lr)return`${tr}(${Ve})`;let zr=[];for(let nn=i-1;nn>=0;nn--){let un=kt.indicesGet("outputIndices",nn+kt.rank-i);zr.push(`${Dt(G,nn)} * (${un} % ${Dt(B,nn)})`)}return lr[tr]=`fn ${tr}(outputIndices: ${kt.type.indices}) -> u32 { - return ${zr.length>0?zr.join("+"):"0u"}; - }`,`${tr}(${Ve})`},er=(Ve,kt)=>(()=>{if(l.storage===l.value)return`${e}[${Ve}]=${kt};`;if(l.storage==="vec2"&&l.value==="i32")return`${e}[${Ve}]=vec2(u32(${kt}), select(0u, 0xFFFFFFFFu, ${kt} < 0));`;if(l.storage==="vec2"&&l.value==="u32")return`${e}[${Ve}]=vec2(u32(${kt}), 0u);`;if(l.storage==="u32"&&l.value==="vec4")return`${e}[${Ve}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${kt}));`;throw new Error(`not supported combination of storage type ${l.storage} and value type ${l.value} yet`)})(),Nr=Ve=>(()=>{if(l.storage===l.value)return`${e}[${Ve}]`;if(l.storage==="vec2"&&l.value==="i32")return`i32(${e}[${Ve}].x)`;if(l.storage==="vec2"&&l.value==="u32")return`u32(${e}[${Ve}].x)`;if(l.storage==="u32"&&l.value==="vec4")return`vec4(bool(${e}[${Ve}] & 0xFFu), bool(${e}[${Ve}] & 0xFF00u), bool(${e}[${Ve}] & 0xFF0000u), bool(${e}[${Ve}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${l.storage} and value type ${l.value} yet`)})(),Hr=i<2?"":` - fn get_${e}ByIndices(indices: ${l.indices}) -> ${g} { - return ${Nr(`i2o_${e}(indices)`)}; - }`,br=i<2?"":(()=>{let Ve=u.map(tr=>`d${tr}: u32`).join(", "),kt=u.map(tr=>`d${tr}`).join(", ");return` - fn get_${e}(${Ve}) -> ${g} { - return get_${e}ByIndices(${pt(kt)}); - }`})(),jr=(...Ve)=>{if(Ve.length!==i)throw new Error(`indices length must be ${i}`);let kt=Ve.map(M).join(",");return i===0?Nr("0u"):i===1?Nr(kt[0]):(C.get=!0,C.getByIndices=!0,C.indicesToOffset=!0,`get_${e}(${kt})`)},Jt=Ve=>i<2?Nr(Ve):(C.getByIndices=!0,C.indicesToOffset=!0,`get_${e}ByIndices(${Ve})`),dr=i<2?"":` - fn set_${e}ByIndices(indices: ${l.indices}, value: ${g}) { - ${er(`i2o_${e}(indices)`,"value")} - }`,Pr=i<2?"":(()=>{let Ve=u.map(tr=>`d${tr}: u32`).join(", "),kt=u.map(tr=>`d${tr}`).join(", ");return` - fn set_${e}(${Ve}, value: ${g}) { - set_${e}ByIndices(${pt(kt)}, value); - }`})();return{impl:()=>{let Ve=[],kt=!1;return C.offsetToIndices&&(Ve.push(ae),kt=!0),C.indicesToOffset&&(Ve.push(Ge),kt=!0),C.broadcastedIndicesToOffset&&(Object.values(lr).forEach(tr=>Ve.push(tr)),kt=!0),C.set&&(Ve.push(Pr),kt=!0),C.setByIndices&&(Ve.push(dr),kt=!0),C.get&&(Ve.push(br),kt=!0),C.getByIndices&&(Ve.push(Hr),kt=!0),!a&&kt&&Ve.unshift(`const ${B} = ${l.indices}(${r.join(",")});`,`const ${G} = ${l.indices}(${Se.computeStrides(r).join(",")});`),Ve.join(` -`)},type:l,offsetToIndices:Z,indicesToOffset:Le,broadcastedIndicesToOffset:fr,indices:pt,indicesGet:Dt,indicesSet:Vt,set:(...Ve)=>{if(Ve.length!==i+1)throw new Error(`indices length must be ${i}`);let kt=Ve[i];if(typeof kt!="string")throw new Error("value must be string");let tr=Ve.slice(0,i).map(M).join(",");return i===0?er("0u",kt):i===1?er(tr[0],kt):(C.set=!0,C.setByIndices=!0,C.indicesToOffset=!0,`set_${e}(${tr}, ${kt})`)},setByOffset:er,setByIndices:(Ve,kt)=>i<2?er(Ve,kt):(C.setByIndices=!0,C.indicesToOffset=!0,`set_${e}ByIndices(${Ve}, ${kt});`),get:jr,getByOffset:Nr,getByIndices:Jt,usage:n,name:e,strides:G,shape:B,rank:i}},rt=(e,t,r,n=1)=>Ys(e,t,r,"input",n),Ut=(e,t,r,n=1)=>Ys(e,t,r,"output",n),Ti=(e,t,r,n=1)=>Ys(e,t,r,"internal",n),Ci=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=en){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 s=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1,a=s?`@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`,i=s?`let global_idx = global_id.x; - let local_idx = local_id.x; - let workgroup_index = workgroup_id.x;`:`let workgroup_index = workgroup_id.z * num_workgroups[0] * num_workgroups[1] + - workgroup_id.y * num_workgroups[0] + workgroup_id.x; - let global_idx = workgroup_index * ${t*r*n}u + local_idx;`;return`@compute @workgroup_size(${t}, ${r}, ${n}) - fn main(${a}) { - ${i} - `}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 s=n==null||n===1?r:`vec${n}<${r}>`;e.push(`${t}:${s}`)}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])}},io=(e,t)=>new Ci(e,t),Fs=(e,t)=>{let r=e.length,n=[];for(let s=0;s1&&i===1&&n.unshift(a)}return n}}),ss,Ei,yd,ao,bd,Pn,$i,oo,is=j(()=>{Xt(),Ht(),Sr(),or(),ss=e=>{if(!e||e.length!==1)throw new Error("Transpose requires 1 input.")},Ei=(e,t)=>t&&t.length!==e?[...new Array(e).keys()].reverse():t,yd=(e,t)=>Se.sortBasedOnPerm(e,Ei(e.length,t)),ao=(e,t,r,n)=>{let s=`fn perm(i: ${n.type.indices}) -> ${r.type.indices} { - var a: ${r.type.indices};`;for(let a=0;a{let r=[],n=[];for(let s=0;s{let r=e.dataType,n=e.dims.length,s=Ei(n,t),a=yd(e.dims,s),{newShape:i,newPerm:u}=bd(e.dims,s),d=Se.areEqual(u,[2,3,1]),p=Se.areEqual(u,[3,1,2]),g=i.length===2&&u[0]>u[1]||d||p,w=g?i:e.dims,l=a;g&&(w=d?[i[0],i[1]*i[2]]:p?[i[0]*i[1],i[2]]:i,l=[w[1],w[0]]);let M=rt("a",r,w.length),C=Ut("output",r,l.length),E=16,B;return g?B=G=>` - ${G.registerUniform("output_size","u32").declareVariables(M,C)} - var tile : array, ${E}>; - ${G.mainStart([E,E,1])} - let stride = (uniforms.output_shape[1] - 1) / ${E} + 1; - let workgroup_id_x = workgroup_index % stride; - let workgroup_id_y = workgroup_index / stride; - let input_col = workgroup_id_y * ${E}u + local_id.x; - let input_row = workgroup_id_x * ${E}u + local_id.y; - if (input_row < uniforms.a_shape[0] && input_col < uniforms.a_shape[1]) { - tile[local_id.y][local_id.x] = ${M.getByIndices(`${M.type.indices}(input_row, input_col)`)}; - } - workgroupBarrier(); - - let output_col = workgroup_id_x * ${E}u + local_id.x; - let output_row = workgroup_id_y * ${E}u + local_id.y; - if (output_row < uniforms.output_shape[0] && output_col < uniforms.output_shape[1]) { - ${C.setByIndices(`${C.type.indices}(output_row, output_col)`,"tile[local_id.x][local_id.y]")} - } - }`:B=G=>` - ${G.registerUniform("output_size","u32").declareVariables(M,C)} - - ${ao(s,n,M,C)} - - ${G.mainStart()} - ${G.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - - let indices = ${C.offsetToIndices("global_idx")}; - let aIndices = perm(indices); - - ${C.setByOffset("global_idx",M.getByIndices("aIndices"))} - }`,{name:g?"TransposeShared":"Transpose",shaderCache:{hint:`${t}`,inputDependencies:["rank"]},getRunData:()=>{let G=Se.size(a);return{outputs:[{dims:a,dataType:e.dataType}],dispatchGroup:g?{x:Math.ceil(l[1]/E),y:Math.ceil(l[0]/E)}:{x:Math.ceil(G/64)},programUniforms:[{type:12,data:G},...Ct(w,l)]}},getShaderSource:B}},$i=(e,t)=>{ss(e.inputs),e.compute(Pn(e.inputs[0],t.perm))},oo=e=>ur({perm:e.perm})}),lo,uo,co,Si,po,ho,ki,fo,mo,Pi,An,_o,Ai,go,wo,Ii,yo,bo,Fi,Mo,vo,xo=j(()=>{Xt(),Ht(),or(),Js(),is(),lo={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"},uo={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"},co={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},Si={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},po=(e,t)=>{let r=[];for(let n=t-e;n{let r=[],n=e.length;for(let a=0;ae[a]);return[r,s]},ki=(e,t)=>{let r=e.length+t.length,n=[],s=0;for(let a=0;a{for(let r=0;r{let r=[];if(!fo(e,t)){for(let n=0;nr.push(n))}return r},Pi=(e,t,r,n,s,a,i)=>{let u=r[0].dims,d=Se.size(a),p=Se.size(i),g=rt("_A",r[0].dataType,u),w=Ut("output",s,a),l=32,M=` - var aBestValues : array; - `;return{name:e,shaderCache:t,getShaderSource:C=>` - ${C.registerUniform("reduceSize","u32").declareVariables(g,w)} - ${M} - fn DIV_CEIL(a : u32, b : u32) -> u32 { - return ((a - 1u) / b + 1u); - } - ${C.mainStart(l)} - - let outputIndex = global_idx / ${l}; - let offset = outputIndex * uniforms.reduceSize; - - var bestValue = f32(${co[n]}); - let Length = uniforms.reduceSize; - for (var k = local_idx; k < Length; k = k + ${l}) { - let candidate = f32(${g.getByOffset("offset + k")}); - bestValue = ${lo[n]}; - } - aBestValues[local_idx] = bestValue; - workgroupBarrier(); - - var reduceSize = min(Length, ${l}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 = ${uo[n]}; - aBestValues[local_idx] = bestValue; - } - reduceSize = interval; - workgroupBarrier(); - } - - if (local_idx == 0u) { - ${w.setByOffset("outputIndex",`${n==="mean"?`${w.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${w.type.storage}(${Si[n]})`}`)}; - } - }`,getRunData:()=>({outputs:[{dims:a,dataType:s}],dispatchGroup:{x:d},programUniforms:[{type:12,data:p}]})}},An=(e,t,r,n)=>{let s=e.inputs.length===1?r:zi(e.inputs,r),a=s.axes;a.length===0&&!s.noopWithEmptyAxes&&(a=e.inputs[0].dims.map((M,C)=>C));let i=Se.normalizeAxes(a,e.inputs[0].dims.length),u=i,d=e.inputs[0],p=mo(u,e.inputs[0].dims.length);p.length>0&&(d=e.compute(Pn(e.inputs[0],p),{inputs:[0],outputs:[-1]})[0],u=po(u.length,d.dims.length));let[g,w]=ho(d.dims,u),l=g;s.keepDims&&(l=ki(g,i)),e.compute(Pi(t,{hint:s.cacheKey,inputDependencies:["type"]},[d],n,e.inputs[0].dataType,l,w),{inputs:[d]})},_o=(e,t)=>{An(e,"ReduceMeanShared",t,"mean")},Ai=(e,t)=>{An(e,"ReduceL1Shared",t,"l1")},go=(e,t)=>{An(e,"ReduceL2Shared",t,"l2")},wo=(e,t)=>{An(e,"ReduceLogSumExpShared",t,"logSumExp")},Ii=(e,t)=>{An(e,"ReduceMaxShared",t,"max")},yo=(e,t)=>{An(e,"ReduceMinShared",t,"min")},bo=(e,t)=>{An(e,"ReduceProdShared",t,"prod")},Fi=(e,t)=>{An(e,"ReduceSumShared",t,"sum")},Mo=(e,t)=>{An(e,"ReduceSumSquareShared",t,"sumSquare")},vo=(e,t)=>{An(e,"ReduceLogSumShared",t,"logSum")}}),In,To,zs,zi,Fn,Oi,Co,Eo,Di,$o,So,Li,ko,Po,Bi,zn,Ao,Ri,Io,Fo,Ni,zo,Oo,ji,Do,Lo,Js=j(()=>{Xt(),Ht(),Sr(),or(),xo(),In=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.")},To=e=>["","",`var value = ${e.getByIndices("input_indices")};`,""],zs=(e,t,r,n,s,a,i=!1,u=!1)=>{let d=[],p=r[0].dims,g=p.length,w=Se.normalizeAxes(s,g),l=!u&&w.length===0;p.forEach((E,B)=>{l||w.indexOf(B)>=0?i&&d.push(1):d.push(E)});let M=d.length,C=Se.size(d);return{name:e,shaderCache:t,getShaderSource:E=>{let B=[],G=rt("_A",r[0].dataType,g),O=Ut("output",a,M),ae=n(G,O,w),Z=ae[2];for(let le=0,Ge=0;le=0?(i&&Ge++,Z=`for(var j${le}: u32 = 0; j${le} < ${p[le]}; j${le}++) { - ${ae[2].includes("last_index")?`let last_index = j${le};`:""} - ${G.indicesSet("input_indices",le,`j${le}`)} - ${Z} - }`):(B.push(`${G.indicesSet("input_indices",le,O.indicesGet("output_indices",Ge))};`),Ge++);return` - - ${E.registerUniform("output_size","u32").declareVariables(G,O)} - - ${E.mainStart()} - ${E.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - var input_indices: ${G.type.indices}; - let output_indices = ${O.offsetToIndices("global_idx")}; - - ${B.join(` -`)} - ${ae[0]} // init ops for reduce max/min - ${ae[1]} - ${Z} - ${ae[3]} - ${ae.length===4?O.setByOffset("global_idx","value"):ae.slice(4).join(` -`)} - }`},getRunData:()=>({outputs:[{dims:d,dataType:a}],dispatchGroup:{x:Math.ceil(C/64)},programUniforms:[{type:12,data:C},...Ct(p,d)]})}},zi=(e,t)=>{let r=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach(n=>r.push(Number(n))),ur({axes:r,keepDims:t.keepDims,noopWithEmptyAxes:t.noopWithEmptyAxes})},Fn=(e,t,r,n)=>{let s=e.inputs,a=s.length===1?r:zi(s,r);e.compute(zs(t,{hint:a.cacheKey,inputDependencies:["rank"]},[s[0]],a.noopWithEmptyAxes&&a.axes.length===0?To:n,a.axes,s[0].dataType,a.keepDims,a.noopWithEmptyAxes),{inputs:[0]})},Oi=(e,t)=>{In(e.inputs),Fn(e,"ReduceLogSum",t,(r,n)=>[`var value = ${n.type.storage}(0);`,"",`value += ${r.getByIndices("input_indices")};`,"value = log(value);"])},Co=(e,t)=>{In(e.inputs),Fn(e,"ReduceL1",t,(r,n)=>[`var value = ${n.type.storage}(0);`,"",`value += abs(${r.getByIndices("input_indices")});`,""])},Eo=(e,t)=>{In(e.inputs),Fn(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);"])},Di=(e,t)=>{In(e.inputs),Fn(e,"ReduceLogSumExp",t,(r,n)=>[`var value = ${n.type.storage}(0);`,"",`value += exp(${r.getByIndices("input_indices")});`,"value = log(value);"])},$o=(e,t)=>{In(e.inputs),Fn(e,"ReduceMax",t,(r,n,s)=>{let a=[];for(let i=0;i=0||s.length===0)&&a.push(r.indicesSet("input_indices",i,0));return[`${a.join(` -`)}`,`var value = ${r.getByIndices("input_indices")};`,`value = max(value, ${r.getByIndices("input_indices")});`,""]})},So=(e,t)=>{In(e.inputs),Fn(e,"ReduceMean",t,(r,n,s)=>{let a=1;for(let i=0;i=0||s.length===0)&&(a*=e.inputs[0].dims[i]);return["var sum = f32(0);","",`sum += f32(${r.getByIndices("input_indices")});`,`let value = ${n.type.value}(sum / ${a});`]})},Li=(e,t)=>{In(e.inputs),Fn(e,"ReduceMin",t,(r,n,s)=>{let a=[];for(let i=0;i=0||s.length===0)&&a.push(`input_indices[${i}] = 0;`);return[`${a.join(` -`)}`,`var value = ${r.getByIndices("input_indices")};`,`value = min(value, ${r.getByIndices("input_indices")});`,""]})},ko=(e,t)=>{In(e.inputs),Fn(e,"ReduceProd",t,(r,n)=>[`var value = ${n.type.storage}(1);`,"",`value *= ${r.getByIndices("input_indices")};`,""])},Po=(e,t)=>{In(e.inputs),Fn(e,"ReduceSum",t,(r,n)=>[`var value = ${n.type.storage}(0);`,"",`value += ${r.getByIndices("input_indices")};`,""])},Bi=(e,t)=>{In(e.inputs),Fn(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;`,""])},zn=(e,t,r)=>{if(t.length===0)return r;let n=1,s=1;for(let a=0;a1024},Ao=(e,t)=>{zn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?So(e,t):_o(e,t)},Ri=(e,t)=>{zn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Co(e,t):Ai(e,t)},Io=(e,t)=>{zn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Eo(e,t):go(e,t)},Fo=(e,t)=>{zn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Di(e,t):wo(e,t)},Ni=(e,t)=>{zn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?$o(e,t):Ii(e,t)},zo=(e,t)=>{zn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Li(e,t):yo(e,t)},Oo=(e,t)=>{zn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?ko(e,t):bo(e,t)},ji=(e,t)=>{zn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Po(e,t):Fi(e,t)},Do=(e,t)=>{zn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Bi(e,t):Mo(e,t)},Lo=(e,t)=>{zn(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Oi(e,t):vo(e,t)}}),Vi,Bo,Ui,Wi,Md=j(()=>{Xt(),Sr(),Js(),Vi=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.")},Bo=(e,t)=>{Vi(e.inputs);let r=(n,s,a)=>{let i=[];for(let u=0;u=0||a.length===0)&&i.push(`input_indices[${u}] = 0;`);return[`${i.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); - }`,"",s.setByOffset("global_idx","best_index")]};e.compute(zs("ArgMin",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],r,[t.axis],7,t.keepDims),{inputs:[0]})},Ui=(e,t)=>{Vi(e.inputs);let r=(n,s,a)=>{let i=[];for(let u=0;u=0||a.length===0)&&i.push(`input_indices[${u}] = 0;`);return[`${i.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); - }`,"",s.setByOffset("global_idx","best_index")]};e.compute(zs("argMax",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],r,[t.axis],7,t.keepDims),{inputs:[0]})},Wi=e=>ur(e)}),Gi,Ro,No,qi,Os,jo,Hi,Ki=j(()=>{Xt(),Ht(),se(),or(),Gi=(e,t)=>{let r=e[0],n=e[1],s=e[2],a=e[3],i=e[4],u=e[5];if(i&&u)throw new Error("Attention cannot have both past and attention_bias");if(r.dims.length!==3)throw new Error('Input "input" must have 3 dimensions');let d=r.dims[0],p=r.dims[1],g=r.dims[2];if(s.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]!==g)throw new Error("Input 1 dimension 0 should have same length as dimension 2 of input 0");if(s.dims[0]!==n.dims[1])throw new Error('Input "bias" dimension 0 should have same length as dimension 1 of input "weights"');let w=s.dims[0]/3,l=w,M=l;if(t.qkvHiddenSizes.length>0){if(t.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let ae of t.qkvHiddenSizes)if(ae%t.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");w=t.qkvHiddenSizes[0],l=t.qkvHiddenSizes[1],M=t.qkvHiddenSizes[2]}let C=p;if(w!==l)throw new Error("qkv_hidden_sizes first element should be same as the second");if(s.dims[0]!==w+l+M)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let E=0;if(i){if(l!==M)throw new Error('Input "past" expect k_hidden_size == v_hidden_size');if(i.dims.length!==5)throw new Error('Input "past" must have 5 dimensions');if(i.dims[0]!==2)throw new Error('Input "past" first dimension must be 2');if(i.dims[1]!==d)throw new Error('Input "past" second dimension must be batch_size');if(i.dims[2]!==t.numHeads)throw new Error('Input "past" third dimension must be num_heads');if(i.dims[4]!==l/t.numHeads)throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads');t.pastPresentShareBuffer||(E=i.dims[3])}let B=C+E,G=-1,O=0;if(a)throw new Error("Mask not supported");if(i)throw new Error("past is not supported");if(u){if(u.dims.length!==4)throw new Error('Input "attention_bias" must have 4 dimensions');if(u.dims[0]!==d||u.dims[1]!==t.numHeads||u.dims[2]!==p||u.dims[3]!==B)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:d,sequenceLength:p,pastSequenceLength:E,kvSequenceLength:C,totalSequenceLength:B,maxSequenceLength:G,inputHiddenSize:g,hiddenSize:w,vHiddenSize:M,headSize:Math.floor(w/t.numHeads),vHeadSize:Math.floor(M/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:O,scale:t.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},Ro=(e,t,r)=>{let n=mr(r),s=64,a=r/n;a{let M=Ut("x",e.dataType,e.dims,n),C=Ar(e.dataType),E=[{name:"d_inv",type:"f32"},{name:"d_comp",type:"u32"},{name:"elements_per_thread",type:"u32"}];return` - var thread_max: array; - var thread_sum: array; - ${l.registerUniforms(E).declareVariables(M)} - ${l.mainStart([s,1,1])} - let local_offset = local_idx * uniforms.elements_per_thread; - let offset = (global_idx / ${s}) * uniforms.d_comp + local_offset; - - var thread_max_vector = ${p}(-3.402823e+38f); - for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { - thread_max_vector = max(${p}(x[offset + i]), thread_max_vector); - } - thread_max[local_idx] = ${(()=>{switch(n){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: ${n}`)}})()}; - workgroupBarrier(); - - var max_value = f32(-3.402823e+38f); - for (var i = 0u; i < ${s}; i++) { - max_value = max(thread_max[i], max_value); - } - - var sum_vector = ${p}(0); - for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { - sum_vector += exp(${p}(x[offset + i]) - max_value); - } - thread_sum[local_idx] = ${(()=>{switch(n){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: ${n}`)}})()}; - workgroupBarrier(); - - var sum: f32 = 0; - for (var i = 0u; i < ${s}; 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] = ${M.type.value}(${C}(uniforms.d_inv)); - } - } else { - for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { - var f32input = ${p}(x[offset + i]); - x[offset + i] = ${M.type.value}(exp(f32input - max_value) / sum); - } - } - }`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${s};${d};${n}`,inputDependencies:g},getShaderSource:w,getRunData:()=>({outputs:[],dispatchGroup:{x:t},programUniforms:u})}},No=(e,t,r,n,s,a,i,u)=>{let d=u+a.kvSequenceLength,p=[a.batchSize,a.numHeads,a.sequenceLength,d],g=a.kvNumHeads===void 0&&e>1&&n,w=g?[a.batchSize,a.numHeads,d,a.headSize]:void 0,l=i.scale===0?1/Math.sqrt(a.headSize):i.scale,M=mr(a.headSize),C=a.headSize/M,E=12,B={x:Math.ceil(d/E),y:Math.ceil(a.sequenceLength/E),z:a.batchSize*a.numHeads},G=[{type:12,data:a.sequenceLength},{type:12,data:C},{type:12,data:d},{type:12,data:a.numHeads},{type:1,data:l},{type:12,data:u},{type:12,data:a.kvSequenceLength}],O=g&&n&&Se.size(n.dims)>0,ae=["type","type"];O&&ae.push("type"),s&&ae.push("type");let Z=[{dims:p,dataType:t.dataType,gpuDataType:0}];g&&Z.push({dims:w,dataType:t.dataType,gpuDataType:0});let le=Ge=>{let Le=rt("q",t.dataType,t.dims,M),pt=rt("key",r.dataType,r.dims,M),Dt=[Le,pt];if(O){let Nr=rt("past_key",n.dataType,n.dims,M);Dt.push(Nr)}s&&Dt.push(rt("attention_bias",s.dataType,s.dims));let Vt=Ut("output",t.dataType,p),lr=[Vt];g&&lr.push(Ut("present_key",t.dataType,w,M));let fr=Ar(1,M),er=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"alpha",type:"f32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"}];return` - const TILE_SIZE = ${E}u; - - var tileQ: array<${Le.type.storage}, ${E*E}>; - var tileK: array<${Le.type.storage}, ${E*E}>; - ${Ge.registerUniforms(er).declareVariables(...Dt,...lr)} - ${Ge.mainStart([E,E,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; - ${O&&g?` - let kOffset = uniforms.kv_sequence_length * uniforms.K * headIdx; - let pastKeyOffset = uniforms.past_sequence_length * uniforms.K * headIdx;`:` - let kOffset = uniforms.N * uniforms.K * headIdx + n * uniforms.K;`} - ${g?"let presentKeyOffset = headIdx * uniforms.N * uniforms.K;":""} - var value = ${fr}(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) { - var idx = TILE_SIZE * local_id.y + local_id.x; - ${O&&g?` - if (n + local_id.y < uniforms.past_sequence_length) { - tileK[idx] = past_key[pastKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x]; - } else { - tileK[idx] = - key[kOffset + (n + local_id.y - uniforms.past_sequence_length) * uniforms.K + w + local_id.x]; - }`:"tileK[idx] = key[kOffset + local_id.y * uniforms.K + w + local_id.x];"} - ${g?"present_key[presentKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x] = tileK[idx];":""} - } - workgroupBarrier(); - - for (var k: u32 = 0u; k < TILE_SIZE && w+k < uniforms.K; k++) { - value += ${fr}(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(M){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: ${M}`)}})()}; - output[outputIdx] = ${Vt.type.value} (sum * uniforms.alpha) + ${s?"attention_bias[outputIdx]":"0.0"}; - } - }`};return{name:"AttentionProbs",shaderCache:{hint:`${M};${s!==void 0};${n!==void 0};${e}`,inputDependencies:ae},getRunData:()=>({outputs:Z,dispatchGroup:B,programUniforms:G}),getShaderSource:le}},qi=(e,t,r,n,s,a)=>{let i=a+s.kvSequenceLength,u=s.nReps?s.nReps:1,d=s.vHiddenSize*u,p=s.kvNumHeads==null&&e>1&&n,g=p?[s.batchSize,s.numHeads,i,s.headSize]:void 0,w=[s.batchSize,s.sequenceLength,d],l=12,M={x:Math.ceil(s.vHeadSize/l),y:Math.ceil(s.sequenceLength/l),z:s.batchSize*s.numHeads},C=[{type:12,data:s.sequenceLength},{type:12,data:i},{type:12,data:s.vHeadSize},{type:12,data:s.numHeads},{type:12,data:d},{type:12,data:a},{type:12,data:s.kvSequenceLength}],E=p&&n&&Se.size(n.dims)>0,B=["type","type"];E&&B.push("type");let G=[{dims:w,dataType:t.dataType,gpuDataType:0}];p&&G.push({dims:g,dataType:t.dataType,gpuDataType:0});let O=ae=>{let Z=rt("probs",t.dataType,t.dims),le=rt("v",r.dataType,r.dims),Ge=[Z,le];E&&Ge.push(rt("past_value",n.dataType,n.dims));let Le=[Ut("output",t.dataType,w)];p&&Le.push(Ut("present_value",t.dataType,g));let pt=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"v_hidden_size",type:"u32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"}];return` - const TILE_SIZE = ${l}u; - var tileQ: array<${Z.type.value}, ${l*l}>; - var tileK: array<${Z.type.value}, ${l*l}>; - ${ae.registerUniforms(pt).declareVariables(...Ge,...Le)} - ${ae.mainStart([l,l,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; - ${E&&p?` - let pastValueOffset = headIdx * uniforms.N * uniforms.past_sequence_length + n; - let vOffset = headIdx * uniforms.N * uniforms.kv_sequence_length + n; - `:` - let offsetB = headIdx * uniforms.N * uniforms.K + n; - `} - ${p?"let presentValueOffset = headIdx * uniforms.N * uniforms.K + n;":""} - var value = ${Z.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) { - var idx = TILE_SIZE * local_id.y + local_id.x; - ${E&&p?` - if (w + local_id.y < uniforms.past_sequence_length) { - tileK[idx] = past_value[pastValueOffset + (w + local_id.y) * uniforms.N]; - } else { - tileK[idx] = v[vOffset + (w + local_id.y - uniforms.past_sequence_length) * uniforms.N]; - } - `:` - tileK[idx] = v[offsetB + (w + local_id.y) * uniforms.N]; - `} - ${p?"present_value[presentValueOffset + (w + local_id.y) * uniforms.N] = tileK[idx];":""} - } - 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; - } - }`};return{name:"AttentionScore",shaderCache:{hint:`${n!==void 0};${e}`,inputDependencies:B},getRunData:()=>({outputs:G,dispatchGroup:M,programUniforms:C}),getShaderSource:O}},Os=(e,t,r,n,s,a,i,u,d,p,g)=>{let w=Math.min(e.outputCount,1+(i?1:0)+(u?1:0)),l=p.kvNumHeads!==void 0||w>1?p.pastSequenceLength:0,M=l+p.kvSequenceLength,C=d&&Se.size(d.dims)>0?d:void 0,E=[t,r];p.kvNumHeads===void 0&&w>1&&i&&Se.size(i.dims)>0&&E.push(i),C&&E.push(C);let B=e.compute(No(w,t,r,i,C,p,g,l),{inputs:E,outputs:p.kvNumHeads===void 0&&w>1?[-1,1]:[-1]})[0];e.compute(Ro(B,p.batchSize*p.numHeads*p.sequenceLength,M),{inputs:[B],outputs:[]});let G=[B,n];p.kvNumHeads===void 0&&w>1&&u&&Se.size(u.dims)>0&&G.push(u),e.compute(qi(w,B,n,u,p,l),{inputs:G,outputs:p.kvNumHeads===void 0&&w>1?[0,2]:[0]})},jo=(e,t)=>{let r=[t.batchSize,t.numHeads,t.sequenceLength,t.headSize],n=t.sequenceLength,s=t.inputHiddenSize,a=t.headSize,i=12,u={x:Math.ceil(t.headSize/i),y:Math.ceil(t.sequenceLength/i),z:t.batchSize*t.numHeads},d=[e.inputs[0],e.inputs[1],e.inputs[2]],p=[{type:12,data:n},{type:12,data:s},{type:12,data:a},{type:12,data:t.numHeads},{type:12,data:t.headSize},{type:12,data:t.hiddenSize},{type:12,data:t.hiddenSize+t.hiddenSize+t.vHiddenSize}],g=w=>{let l=Ut("output_q",d[0].dataType,r),M=Ut("output_k",d[0].dataType,r),C=Ut("output_v",d[0].dataType,r),E=rt("input",d[0].dataType,d[0].dims),B=rt("weight",d[1].dataType,d[1].dims),G=rt("bias",d[2].dataType,d[2].dims),O=E.type.storage,ae=[{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 = ${i}u; - var tileInput: array<${O}, ${i*i}>; - var tileWeightQ: array<${O}, ${i*i}>; - var tileWeightK: array<${O}, ${i*i}>; - var tileWeightV: array<${O}, ${i*i}>; - ${w.registerUniforms(ae).declareVariables(E,B,G,l,M,C)} - ${w.mainStart([i,i,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 = ${O}(0); - var valueK = ${O}(0); - var valueV = ${O}(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:g},{inputs:d,outputs:[-1,-1,-1]})},Hi=(e,t)=>{let r=Gi(e.inputs,t),[n,s,a]=jo(e,r);return Os(e,n,s,a,e.inputs[4],void 0,void 0,void 0,e.inputs[5],r,t)}}),Vo,Xi,Uo,Wo,vd=j(()=>{At(),Xt(),Ht(),Sr(),or(),Vo=(e,t)=>{if(!e||e.length!==5)throw new Error("BatchNormalization requires 5 inputs");let r=(n,s,a)=>{let i=s.length;if(i!==n.length)throw new Error(`${a}: num dimensions != ${i}`);s.forEach((u,d)=>{if(u!==n[d])throw new Error(`${a}: dim[${d}] 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")},Xi=(e,t)=>{let{epsilon:r,spatial:n,format:s}=t,a=e[0].dims,i=n?mr(a[a.length-1]):1,u=s==="NHWC"&&a.length>1?i:1,d=Se.size(a)/i,p=n,g=p?a.length:a,w=rt("x",e[0].dataType,e[0].dims,i),l=rt("scale",e[1].dataType,e[1].dims,u),M=rt("bias",e[2].dataType,e[2].dims,u),C=rt("inputMean",e[3].dataType,e[3].dims,u),E=rt("inputVar",e[4].dataType,e[4].dims,u),B=Ut("y",e[0].dataType,g,i),G=()=>{let ae="";if(n)ae=`let cOffset = ${a.length===1?"0u":s==="NHWC"?`outputIndices[${a.length-1}] / ${i}`:"outputIndices[1]"};`;else if(s==="NCHW")ae=` - ${B.indicesSet("outputIndices","0","0")} - let cOffset = ${B.indicesToOffset("outputIndices")};`;else{ae=`var cIndices = ${l.type.indices}(0); - cIndices[0] = outputIndices[${a.length-1}];`;for(let Z=1;Z` - const epsilon = ${r}; - ${ae.registerUniform("outputSize","u32").declareVariables(w,l,M,C,E,B)} - ${ae.mainStart()} - ${ae.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} - var outputIndices = ${B.offsetToIndices(`global_idx * ${i}`)}; - ${G()} - let scale = ${l.getByOffset("cOffset")}; - let bias = ${M.getByOffset("cOffset")}; - let inputMean = ${C.getByOffset("cOffset")}; - let inputVar = ${E.getByOffset("cOffset")}; - let x = ${w.getByOffset("global_idx")}; - let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias; - ${B.setByOffset("global_idx","value")} - }`;return{name:"BatchNormalization",shaderCache:{hint:`${t.epsilon}_${t.format}_${n}_${i}`,inputDependencies:p?["rank","type","type","type","type"]:void 0},getShaderSource:O,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:p?[{type:12,data:d},...Ct(a)]:[{type:12,data:d}]})}},Uo=e=>ur(e),Wo=(e,t)=>{let{inputs:r,outputCount:n}=e,s=Uo({...t,outputCount:n});if(k.webgpu.validateInputContent&&Vo(r,s),t.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");e.compute(Xi(r,s))}}),Go,Qi,qo,xd=j(()=>{Ht(),or(),Go=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")},Qi=e=>{let t=e[0].dims,r=e[0].dims[2],n=Se.size(t)/4,s=e[0].dataType,a=rt("input",s,t,4),i=rt("bias",s,[r],4),u=rt("residual",s,t,4),d=Ut("output",s,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(a,i,u,d)} - - ${p.mainStart()} - ${p.guardAgainstOutOfBoundsWorkgroupSizes(n)} - let value = ${a.getByOffset("global_idx")} - + ${i.getByOffset("global_idx % channels")} + ${u.getByOffset("global_idx")}; - ${d.setByOffset("global_idx","value")} - }`}},qo=e=>{Go(e.inputs),e.compute(Qi(e.inputs))}}),Ho,vr,Yi,Ko,Xo,Qo,Yo,Ji,Jo,Zo,Zi,el,tl,ea,rl,nl,ys,sl,Zs,ta,il,al,ei,ol,ll,ra,na,ul,sa,dl,cl,pl,ia,hl,fl,aa,oa,la,ua,da,ml,_l,ca,gl,wl,ti=j(()=>{Xt(),Ht(),Sr(),or(),Ho=(e,t,r,n,s,a,i)=>{let u=Math.ceil(t/4),d="";typeof s=="string"?d=`${s}(a)`:d=s("a");let p=rt("inputData",r,[u],4),g=Ut("outputData",n,[u],4),w=[{name:"vec_size",type:"u32"}];return i&&w.push(...i),` - ${e.registerUniforms(w).declareVariables(p,g)} - - ${a??""} - - ${e.mainStart()} - ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} - - let a = ${p.getByOffset("global_idx")}; - ${g.setByOffset("global_idx",d)} - }`},vr=(e,t,r,n,s,a=e.dataType,i,u)=>{let d=[{type:12,data:Math.ceil(Se.size(e.dims)/4)}];return i&&d.push(...i),{name:t,shaderCache:{hint:s,inputDependencies:["type"]},getShaderSource:p=>Ho(p,Se.size(e.dims),e.dataType,a,r,n,u),getRunData:p=>({outputs:[{dims:e.dims,dataType:a}],dispatchGroup:{x:Math.ceil(Se.size(p[0].dims)/64/4)},programUniforms:d})}},Yi=e=>{e.compute(vr(e.inputs[0],"Abs","abs"))},Ko=e=>{e.compute(vr(e.inputs[0],"Acos","acos"))},Xo=e=>{e.compute(vr(e.inputs[0],"Acosh","acosh"))},Qo=e=>{e.compute(vr(e.inputs[0],"Asin","asin"))},Yo=e=>{e.compute(vr(e.inputs[0],"Asinh","asinh"))},Ji=e=>{e.compute(vr(e.inputs[0],"Atan","atan"))},Jo=e=>{e.compute(vr(e.inputs[0],"Atanh","atanh"))},Zo=e=>ur(e),Zi=(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(vr(e.inputs[0],"Cast",r,void 0,t.cacheKey,t.to))},el=e=>{let t,r,n=e.length>=2&&e[1].data!==0,s=e.length>=3&&e[2].data!==0;switch(e[0].dataType){case 1:t=n?e[1].getFloat32Array()[0]:-34028234663852886e22,r=s?e[2].getFloat32Array()[0]:34028234663852886e22;break;case 10:t=n?e[1].getUint16Array()[0]:64511,r=s?e[2].getUint16Array()[0]:31743;break;default:throw new Error("Unsupport data type")}return ur({min:t,max:r})},tl=(e,t)=>{let r=t||el(e.inputs),n=Ar(e.inputs[0].dataType);e.compute(vr(e.inputs[0],"Clip",s=>`clamp(${s}, vec4<${n}>(uniforms.min), vec4<${n}>(uniforms.max))`,void 0,r.cacheKey,void 0,[{type:e.inputs[0].dataType,data:r.min},{type:e.inputs[0].dataType,data:r.max}],[{name:"min",type:n},{name:"max",type:n}]),{inputs:[0]})},ea=e=>{e.compute(vr(e.inputs[0],"Ceil","ceil"))},rl=e=>{e.compute(vr(e.inputs[0],"Cos","cos"))},nl=e=>{e.compute(vr(e.inputs[0],"Cosh","cosh"))},ys=e=>ur(e),sl=(e,t)=>{let r=Ar(e.inputs[0].dataType);e.compute(vr(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))},Zs=(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)); -}`,ta=e=>{let t=Ar(e.inputs[0].dataType);e.compute(vr(e.inputs[0],"Erf",r=>`erf_vf32(${r})`,Zs(t)))},il=e=>{e.compute(vr(e.inputs[0],"Exp","exp"))},al=e=>{e.compute(vr(e.inputs[0],"Floor","floor"))},ei=e=>{let t=Ar(e.inputs[0].dataType);e.compute(vr(e.inputs[0],"Gelu",r=>`0.5 * ${r} * (1.0 + erf_vf32(${r} * 0.7071067811865475))`,Zs(t)))},ol=(e,t)=>{let r=Ar(e.inputs[0].dataType);e.compute(vr(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))},ll=e=>{e.compute(vr(e.inputs[0],"Not",t=>`!${t}`))},ra=e=>{e.compute(vr(e.inputs[0],"Neg",t=>`-${t}`))},na=e=>{e.compute(vr(e.inputs[0],"Reciprocal",t=>`1.0/${t}`))},ul=e=>{let t=Ar(e.inputs[0].dataType);e.compute(vr(e.inputs[0],"Relu",r=>`select(vec4<${t}>(0.0), ${r}, ${r} > vec4<${t}>(0.0))`))},sa=e=>{e.compute(vr(e.inputs[0],"Sigmoid",t=>`(1.0 / (1.0 + exp(-${t})))`))},dl=e=>ur(e),cl=(e,t)=>{let r=Ar(e.inputs[0].dataType);e.compute(vr(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))},pl=e=>{e.compute(vr(e.inputs[0],"Sin","sin"))},ia=e=>{e.compute(vr(e.inputs[0],"Sinh","sinh"))},hl=e=>{e.compute(vr(e.inputs[0],"Sqrt","sqrt"))},fl=e=>{e.compute(vr(e.inputs[0],"Tan","tan"))},aa=e=>`sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`,oa=e=>{e.compute(vr(e.inputs[0],"Tanh",aa))},la=(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 ${aa("v")}; -} -`,ua=e=>`(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`,da=e=>{let t=Ar(e.inputs[0].dataType);e.compute(vr(e.inputs[0],"FastGelu",ua,la(t),void 0,e.inputs[0].dataType))},ml=(e,t)=>{let r=Ar(e.inputs[0].dataType);return e.compute(vr(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},_l=e=>{e.compute(vr(e.inputs[0],"Log","log"))},ca=(e,t)=>` -const alpha = vec4<${e}>(${t}); -const one = ${e}(1.0); -const zero = ${e}(0.0); - -fn quick_gelu_impl(x: vec4<${e}>) -> vec4<${e}> { - let v = x *alpha; - var x1 : vec4<${e}>; - for (var i = 0; i < 4; i = i + 1) { - if (v[i] >= zero) { - x1[i] = one / (one + exp(-v[i])); - } else { - x1[i] = one - one / (one + exp(v[i])); - } - } - return x * x1; -} -`,gl=e=>`quick_gelu_impl(${e})`,wl=(e,t)=>{let r=Ar(e.inputs[0].dataType);e.compute(vr(e.inputs[0],"QuickGelu",gl,ca(r,t.alpha),t.cacheKey,e.inputs[0].dataType))}}),yl,bl,pa,Td=j(()=>{Ht(),or(),ti(),yl=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")},bl=e=>{let t=e[0].dims.slice();t[2]=t[2]/2;let r=rt("input",e[0].dataType,e[0].dims,4),n=rt("bias",e[0].dataType,[e[0].dims[2]],4),s=Ut("output",e[0].dataType,t,4),a=Se.size(t)/4,i=yr(e[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)}}),getShaderSource:u=>` - const M_SQRT2 = sqrt(2.0); - const halfChannels = ${e[0].dims[2]/4/2}u; - - ${u.declareVariables(r,n,s)} - - ${Zs(i)} - - ${u.mainStart()} - ${u.guardAgainstOutOfBoundsWorkgroupSizes(a)} - let biasIdx = global_idx % halfChannels; - let batchIndex = global_idx / halfChannels; - let inputOffset = biasIdx + batchIndex * halfChannels * 2; - let valueLeft = input[inputOffset] + bias[biasIdx]; - let valueRight = input[inputOffset + halfChannels] + bias[biasIdx + halfChannels]; - let geluRight = valueRight * 0.5 * (erf_vf32(valueRight / M_SQRT2) + 1); - - ${s.setByOffset("global_idx","valueLeft * geluRight")} - }`}},pa=e=>{yl(e.inputs),e.compute(bl(e.inputs))}}),Ml,ha,On,vl,xl,Tl,ri,Cl,El,$l,fa,Sl,kl,Pl=j(()=>{Xt(),Ht(),or(),Ml=(e,t,r,n,s,a,i,u,d,p,g,w)=>{let l,M;typeof u=="string"?l=M=(O,ae)=>`${u}((${O}),(${ae}))`:typeof u=="function"?l=M=u:(l=u.scalar,M=u.vector);let C=Ut("outputData",g,n.length,4),E=rt("aData",d,t.length,4),B=rt("bData",p,r.length,4),G;if(s)if(a){let O=Se.size(t)===1,ae=Se.size(r)===1,Z=t.length>0&&t[t.length-1]%4===0,le=r.length>0&&r[r.length-1]%4===0;O||ae?G=C.setByOffset("global_idx",M(O?`${E.type.value}(${E.getByOffset("0")}.x)`:E.getByOffset("global_idx"),ae?`${B.type.value}(${B.getByOffset("0")}.x)`:B.getByOffset("global_idx"))):G=` - let outputIndices = ${C.offsetToIndices("global_idx * 4u")}; - let offsetA = ${E.broadcastedIndicesToOffset("outputIndices",C)}; - let offsetB = ${B.broadcastedIndicesToOffset("outputIndices",C)}; - ${C.setByOffset("global_idx",M(i||Z?E.getByOffset("offsetA / 4u"):`${E.type.value}(${E.getByOffset("offsetA / 4u")}[offsetA % 4u])`,i||le?B.getByOffset("offsetB / 4u"):`${B.type.value}(${B.getByOffset("offsetB / 4u")}[offsetB % 4u])`))} - `}else G=C.setByOffset("global_idx",M(E.getByOffset("global_idx"),B.getByOffset("global_idx")));else{if(!a)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let O=(ae,Z,le="")=>{let Ge=`aData[indexA${Z}][componentA${Z}]`,Le=`bData[indexB${Z}][componentB${Z}]`;return` - let outputIndices${Z} = ${C.offsetToIndices(`global_idx * 4u + ${Z}u`)}; - let offsetA${Z} = ${E.broadcastedIndicesToOffset(`outputIndices${Z}`,C)}; - let offsetB${Z} = ${B.broadcastedIndicesToOffset(`outputIndices${Z}`,C)}; - let indexA${Z} = offsetA${Z} / 4u; - let indexB${Z} = offsetB${Z} / 4u; - let componentA${Z} = offsetA${Z} % 4u; - let componentB${Z} = offsetB${Z} % 4u; - ${ae}[${Z}] = ${le}(${l(Ge,Le)}); - `};g===9?G=` - var data = vec4(0); - ${O("data",0,"u32")} - ${O("data",1,"u32")} - ${O("data",2,"u32")} - ${O("data",3,"u32")} - outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:G=` - ${O("outputData[global_idx]",0)} - ${O("outputData[global_idx]",1)} - ${O("outputData[global_idx]",2)} - ${O("outputData[global_idx]",3)} - `}return` - ${e.registerUniform("vec_size","u32").declareVariables(E,B,C)} - - ${w??""} - - ${e.mainStart()} - ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} - ${G} - }`},ha=(e,t,r,n,s,a,i=r.dataType)=>{let u=!Se.areEqual(r.dims,n.dims),d=r.dims,p=Se.size(r.dims),g=!1,w=!1,l=[u];if(u){let M=wn.calcShape(r.dims,n.dims,!1);if(!M)throw new Error("Can't perform binary op on the given tensors");d=M,p=Se.size(d);let C=Se.size(r.dims)===1,E=Se.size(n.dims)===1,B=r.dims.length>0&&r.dims[r.dims.length-1]%4===0,G=n.dims.length>0&&n.dims[n.dims.length-1]%4===0;l.push(C),l.push(E),l.push(B),l.push(G);let O=1;for(let ae=1;aeM.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:M=>Ml(M,r.dims,n.dims,d,g,u,w,s,r.dataType,n.dataType,i,a),getRunData:()=>({outputs:[{dims:d,dataType:i}],dispatchGroup:{x:Math.ceil(p/64/4)},programUniforms:[{type:12,data:Math.ceil(Se.size(d)/4)},...Ct(r.dims,n.dims,d)]})}},On=(e,t,r,n,s,a)=>{e.compute(ha(t,s??"",e.inputs[0],e.inputs[1],r,n,a))},vl=e=>{On(e,"Add",(t,r)=>`${t}+${r}`)},xl=e=>{On(e,"Div",(t,r)=>`${t}/${r}`)},Tl=e=>{On(e,"Equal",{scalar:(t,r)=>`u32(${t}==${r})`,vector:(t,r)=>`vec4(${t}==${r})`},void 0,void 0,9)},ri=e=>{On(e,"Mul",(t,r)=>`${t}*${r}`)},Cl=e=>{let t=rt("input",e.inputs[0].dataType,e.inputs[0].dims).type.value;On(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)); - } - `)},El=e=>{On(e,"Sub",(t,r)=>`${t}-${r}`)},$l=e=>{On(e,"Greater",{scalar:(t,r)=>`u32(${t}>${r})`,vector:(t,r)=>`vec4(${t}>${r})`},void 0,void 0,9)},fa=e=>{On(e,"Less",{scalar:(t,r)=>`u32(${t}<${r})`,vector:(t,r)=>`vec4(${t}<${r})`},void 0,void 0,9)},Sl=e=>{On(e,"GreaterOrEqual",{scalar:(t,r)=>`u32(${t}>=${r})`,vector:(t,r)=>`vec4(${t}>=${r})`},void 0,void 0,9)},kl=e=>{On(e,"LessOrEqual",{scalar:(t,r)=>`u32(${t}<=${r})`,vector:(t,r)=>`vec4(${t}<=${r})`},void 0,void 0,9)}}),Al,Il,Fl,zl,ma,Ol,Cd=j(()=>{Xt(),Ht(),Sr(),or(),Al=(e,t)=>{if(!e||e.length<1)throw new Error("too few inputs");let r=0,n=e[r],s=n.dataType,a=n.dims.length;e.forEach((i,u)=>{if(u!==r){if(i.dataType!==s)throw new Error("input tensors should be one type");if(i.dims.length!==a)throw new Error("input tensors should have the same shape");i.dims.forEach((d,p)=>{if(p!==t&&d!==n.dims[p])throw new Error("non concat dimensions must match")})}})},Il=(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; - }`,Fl=(e,t)=>{let r=e.length,n=[];for(let s=0;s{let s=Se.size(r),a=new Array(e.length),i=new Array(e.length),u=0,d=[],p=[],g=[{type:12,data:s}];for(let E=0;E`uniforms.sizeInConcatAxis${E}`).join(","),C=E=>` - - ${(()=>{E.registerUniform("outputSize","u32");for(let B=0;B(${M}); - ${l} -= sizeInConcatAxis[inputIndex - 1u]; - } - - ${Fl(i,w)} - }`;return{name:"Concat",shaderCache:{hint:`${t}`,inputDependencies:d},getRunData:()=>({outputs:[{dims:r,dataType:n}],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:g}),getShaderSource:C}},ma=(e,t)=>{let r=e.inputs,n=r[0].dims,s=Se.normalizeAxis(t.axis,n.length);Al(r,s);let a=n.slice();a[s]=r.reduce((u,d)=>u+(d.dims.length>s?d.dims[s]:0),0);let i=r.filter(u=>Se.size(u.dims)>0);e.compute(zl(i,s,a,r[0].dataType),{inputs:i})},Ol=e=>ur({axis:e.axis})}),jn,Qn,Yn,ni,Jn=j(()=>{Xt(),Ht(),jn=(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"Tanh":return`let e2x = exp(-2.0 * abs(value)); - value = sign(value) * (1.0 - e2x) / (1.0 + e2x); - `;case"":return"";default:throw new Error(`Unsupported activation ${e.activation}`)}},Qn=(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})},Yn=(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"})},ni=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)||[kn,Nn];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}}}),fn,si,ii=j(()=>{fn=(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.`)}},si=e=>` - ${e?"value = value + getBiasByOutputCoords(coords);":""} - `}),_a,Dl=j(()=>{_a=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)); -} -`}),Ll,Bl,ai,oi,Rl,li,ga,wa,ui=j(()=>{Xt(),Ht(),or(),Jn(),ii(),Ll=(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":""}); - `,Bl=(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];"} - }`,ai=(e,t,r="f32",n,s=!1,a=32,i=!1,u=32)=>{let d=t[1]*e[1],p=t[0]*e[0],g=s?d:a,w=s?a:d,l=g/t[0],M=a/t[1];if(!((s&&l===4&&e[1]===4||!s&&(l===3||l===4))&&g%t[0]===0&&a%t[1]===0&&e[0]===4))throw new Error(`If transposeA ${s} is true, innerElementSize ${l} and workPerThread[1] ${e[1]} must be 4. - Otherwise, innerElementSize ${l} must be 3 or 4. - tileAWidth ${g} must be divisible by workgroupSize[0]${t[0]}. tileInner ${a} must be divisible by workgroupSize[1] ${t[1]}. colPerThread ${e[0]} must be 4.`);return` -var mm_Asub: array, ${g/l}>, ${w}>; -var mm_Bsub: array, ${p/e[0]}>, ${a}>; - -const rowPerThread = ${e[1]}; -const colPerThread = ${e[0]}; -const innerElementSize = ${l}; -const tileInner = ${a}; - -@compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]}) -fn main(@builtin(local_invocation_id) localId : vec3, - @builtin(global_invocation_id) globalId : vec3, - @builtin(workgroup_id) workgroupId : vec3) { - let localRow = i32(localId.y); - let tileRow = localRow * rowPerThread; - let tileCol = i32(localId.x); - - let globalRow =i32(globalId.y) * rowPerThread; - let globalCol = i32(globalId.x); - let batch = ${i?"0":"i32(globalId.z)"}; - ${n?`let batchIndices = ${n.offsetToIndices("u32(batch)")};`:""} - let globalRowStart = i32(workgroupId.y) * ${d}; - - let num_tiles = ${i?`${Math.ceil(u/a)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; - var kStart = ${i?`i32(globalId.z) * ${u}`:"0"}; - - var acc: array, rowPerThread>; - - // Loop over shared dimension. - let tileRowB = localRow * ${M}; - 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; - ${Ll(s,n)} - } - - // Load one tile of B into local memory. - for (var innerRow = 0; innerRow < ${M}; 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]; - ${l===3?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"} - - ${Bl(s,l)} - } - - workgroupBarrier(); - } - - for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { - mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]); - } -}`},oi=(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":""}); - `,Rl=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",li=(e,t,r="f32",n,s=!1,a=32,i=!1,u=32,d=!1)=>{let p=e[1]*t[1],g=e[0]*t[0],w=s?p:a,l=s?a:p;if(!(l%t[1]===0&&w%t[0]===0&&a%t[1]===0))throw new Error(`tileAHight ${l} must be divisible by workgroupSize[1]${t[1]}, tileAWidth ${w} must be divisible by workgroupSize[0]${t[0]}, tileInner ${a} must be divisible by workgroupSize[1]${t[1]}`);let M=l/t[1],C=w/t[0],E=a/t[1],B=d?` - let localRow = i32(localId.y); - let localCol = i32(localId.x); - let globalRowStart = i32(workgroupId.y) * ${p}; - let globalColStart = i32(workgroupId.x) * ${g}; - - // 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 < ${l}; inputRow = inputRow + ${t[1]}) { - for (var inputCol = localCol; inputCol < ${w}; inputCol = inputCol + ${t[0]}) { - ${oi(s,n)} - } - } - // Load one tile of B into local memory. - for (var inputRow = localRow; inputRow < ${a}; inputRow = inputRow + ${t[1]}) { - for (var inputCol = localCol; inputCol < ${g}; 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 = ${s?`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) * ${M}; -let tileColA = i32(localId.x) * ${C}; -let tileRowB = i32(localId.y) * ${E}; -// 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 < ${M}; innerRow = innerRow + 1) { - for (var innerCol = 0; innerCol < ${C}; innerCol = innerCol + 1) { - let inputRow = tileRowA + innerRow; - let inputCol = tileColA + innerCol; - ${oi(s,n)} - } - } - - // Load one tile of B into local memory. - for (var innerRow = 0; innerRow < ${E}; 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) { - ${Rl(s)} - 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, ${l}>; - var mm_Bsub : array, ${a}>; - const rowPerThread = ${e[1]}; - const colPerThread = ${e[0]}; - const tileInner = ${a}; - -@compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]}) -fn main(@builtin(local_invocation_id) localId : vec3, - @builtin(global_invocation_id) globalId : vec3, - @builtin(workgroup_id) workgroupId : vec3) { - let batch = ${i?"0":"i32(globalId.z)"}; - ${n?`let batchIndices = ${n.offsetToIndices("u32(batch)")};`:""} - let num_tiles = ${i?`${Math.ceil(u/a)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; - var kStart = ${i?`i32(globalId.z) * ${u}`:"0"}; - - var acc : array, rowPerThread>; - ${B} - } -`},ga=(e,t,r,n,s,a=!1)=>{let[i,u,d]=s,[p,g,w,l]=n,M=Fs(i,d),C=Fs(u,d),E=yr(n[0].type.tensor),B=()=>{let O=g.rank,ae=p.rank,Z=`var aIndices: ${g.type.indices};`;for(let le=O-2-1,Ge=ae-1;le>=0;le--,Ge--)Z+=` -aIndices[${le}] = ${ae>1?`batchIndices[${Ge}]`:"batchIndices"};`;return M.forEach(le=>{Z+=` -aIndices[${le}] = 0;`}),Z+=` -aIndices[${O-2}] = u32(row); - aIndices[${O-1}] = u32(colIn);`,Z},G=()=>{let O=w.rank,ae=p.rank,Z=`var bIndices: ${w.type.indices};`;for(let le=O-2-1,Ge=ae-1;le>=0;le--,Ge--)Z+=` -bIndices[${le}] = ${ae>1?`batchIndices[${Ge}]`:"batchIndices"};`;return C.forEach(le=>{Z+=` -bIndices[${le}] = 0;`}),Z+=` -bIndices[${O-2}] = u32(row); - bIndices[${O-1}] = u32(colIn);`,Z};return` - fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${p.type.indices}) -> ${fn(e,E)} { - var value = ${fn(e,E)}(0.0); - let col = colIn * ${e}; - if(row < uniforms.dim_a_outer && col < uniforms.dim_inner) - { - ${B()} - value = ${g.getByIndices("aIndices")}; - } - return value; - } - - fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${p.type.indices}) -> ${fn(e,E)} { - var value = ${fn(e,E)}(0.0); - let col = colIn * ${e}; - if(row < uniforms.dim_inner && col < uniforms.dim_b_outer) - { - ${G()} - value = ${w.getByIndices("bIndices")}; - } - return value; - } - - fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${fn(e,E)}) { - 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 + ${a?"bias[colIn]":`${fn(e,E)}(bias[row])`};`:""} - ${r} - ${l.setByIndices("vec3(coords)","value")} - } - } - `},wa=(e,t,r,n,s=!1,a)=>{let i=e[0].dims,u=e[1].dims,d=i.slice(0,-2),p=u.slice(0,-2),g=n?n.slice(0,-2):r.slice(0,-2),w=Se.size(g),l=i[i.length-2],M=i[i.length-1],C=u[u.length-1],E=M%4===0&&C%4===0,B=l<=8?[4,1,1]:[4,4,1],G=[8,8,1],O=[Math.ceil(C/G[0]/B[0]),Math.ceil(l/G[1]/B[1]),Math.ceil(w/G[2]/B[2])],ae=E?4:1,Z=[...d,l,M/ae],le=Z.length,Ge=[...p,M,C/ae],Le=Ge.length,pt=[w,l,C/ae],Dt=[{type:6,data:l},{type:6,data:C},{type:6,data:M}];Qn(t,Dt),Dt.push(...Ct(g,Z,Ge));let Vt=["rank","rank"],lr=e.length>2;lr&&(Dt.push(...Ct(e[2].dims)),Vt.push("rank")),Dt.push(...Ct(pt));let fr=er=>{let Nr=g.length,Hr=Ti("batchDims",e[0].dataType,Nr,1),br=yr(e[0].dataType),jr=rt("a",e[0].dataType,le,ae),Jt=rt("b",e[1].dataType,Le,ae),dr=Ut("result",e[0].dataType,pt.length,ae),Pr=[jr,Jt];if(lr){let nn=s?ae:1;Pr.push(rt("bias",e[2].dataType,e[2].dims.length,nn))}let Ve=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];Yn(t,Ve);let kt=yr(dr.type.tensor),tr=jn(t,dr.type.value,kt),zr=ga(ae,lr,tr,[Hr,jr,Jt,dr],[d,p,g],s);return` - ${er.registerUniforms(Ve).registerInternalVariables(Hr).declareVariables(...Pr,dr)} - ${zr} - ${E?ai(B,G,br,Hr):li(B,G,br,Hr)} - `};return{name:"MatMul",shaderCache:{hint:`${B};${t.activation};${E};${s}`,inputDependencies:Vt},getRunData:()=>({outputs:[{dims:a?a(r):r,dataType:e[0].dataType}],dispatchGroup:{x:O[0],y:O[1],z:O[2]},programUniforms:Dt}),getShaderSource:fr}}}),Zn,Nl,Ed=j(()=>{Xt(),m(),or(),Jn(),ii(),Dl(),ui(),Zn=(e,t,r,n,s=!1,a,i=4,u=4,d=4,p="f32")=>{let g=Dt=>{switch(Dt){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 ${Dt} is not supported.`)}},w=Dt=>{switch(Dt){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 ${Dt} is not supported.`)}},l=e?` - let coord = vec4(batch, xRow, xCol, xCh); - `:` - let coord = vec4(batch, xCh, xRow, xCol); - `,M=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])",E=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",B=e?"row":"col",G=e?"col":"row",O=` - let inChannels = i32(uniforms.w_shape[2]); - let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; - let outRow = ${B} / outWidth; - let outCol = ${B} % outWidth; - - let WRow = ${G} / (i32(uniforms.w_shape[1]) * inChannels); - let WCol = ${G} / 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 = ${G} % inChannels; - var resData = ${fn(i,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 < ${E}) { - ${l} - let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape)); - ${g(i)} - } - return resData;`,ae=e?t&&n?` - let col = colIn * ${i}; - ${O}`:` - let col = colIn * ${i}; - if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { - ${O} - } - return ${fn(i,p)}(0.0);`:n&&r?` - let col = colIn * ${i}; - ${O}`:` - let col = colIn * ${i}; - if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { - ${O} - } - return ${fn(i,p)}(0.0);`,Z=`${w(u)}`,le=fn(d,p),Ge=fn(e?i:u,p),Le=fn(e?u:i,p),pt=jn(a,le,p);return` - fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${Ge} { - ${e?ae:Z} - } - - fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${Le} { - ${e?Z:ae} - } - - fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${le}) { - let col = colIn * ${d}; - 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])"}; - ${M} - ${si(s)} - ${pt} - setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); - } - }`},Nl=(e,t,r,n,s,a,i,u,d)=>{let p=t.format==="NHWC",g=p?e[0].dims[3]:e[0].dims[1],w=r[0],l=p?r[2]:r[3],M=p?r[1]:r[2],C=p?r[3]:r[1],E=p&&(g%4===0||g%3===0)&&C%4===0,B=p?C:l*M,G=p?l*M:C,O=[8,8,1],ae=n<=8?[4,1,1]:[4,4,1],Z=[Math.ceil(B/O[0]/ae[0]),Math.ceil(G/O[1]/ae[1]),Math.ceil(w/O[2]/ae[2])];ue("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${Z}`);let le=E?p&&g%4!==0?3:4:1,Ge=O[1]*ae[1],Le=O[0]*ae[0],pt=Math.max(O[0]*le,O[1]),Dt=n%Ge===0,Vt=s%Le===0,lr=a%pt===0,fr=E?[le,4,4]:[1,1,1],er=[{type:6,data:n},{type:6,data:s},{type:6,data:a},{type:6,data:[t.pads[0],t.pads[1]]},{type:6,data:t.strides},{type:6,data:t.dilations}];Qn(t,er),er.push(...Ct(e[0].dims,e[1].dims));let Nr=["rank","rank"];i&&(er.push(...Ct(e[2].dims)),Nr.push("rank")),er.push(...Ct(r));let Hr=br=>{let jr=[{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}];Yn(t,jr);let Jt=E?4:1,dr=yr(e[0].dataType),Pr=` - fn setOutputAtIndex(flatIndex : i32, value : ${E?`vec4<${dr}>`:dr}) { - result[flatIndex] = ${E?`vec4<${dr}>`:dr}(value); - } - fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${E?`vec4<${dr}>`:dr}) { - let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3)); - setOutputAtIndex(flatIndex ${E?"/ 4":""}, value); - }`,Ve=rt("x",e[0].dataType,e[0].dims.length,le===3?1:le),kt=rt("w",e[1].dataType,e[1].dims.length,Jt),tr=[Ve,kt],zr=Ut("result",e[0].dataType,r.length,Jt);if(i){let nn=rt("bias",e[2].dataType,e[2].dims.length,Jt);tr.push(nn),Pr+=` - fn getBiasByOutputCoords(coords : vec4) -> ${E?`vec4<${dr}>`:dr} { - return bias[coords.${p?"w":"y"}${E?"/ 4":""}]; - }`}return` - ${_a("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 }; - ${br.registerUniforms(jr).declareVariables(...tr,zr)} - ${Pr} - ${Zn(p,Dt,Vt,lr,i,t,fr[0],fr[1],fr[2],dr)} - ${E?ai(ae,O,dr,void 0,!p,pt):li(ae,O,dr,void 0,!p,pt,!1,void 0,u)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${t.cacheKey};${le};${E};${Dt};${Vt};${lr};${Ge};${Le};${pt}`,inputDependencies:Nr},getRunData:()=>({outputs:[{dims:d?d(r):r,dataType:e[0].dataType}],dispatchGroup:{x:Z[0],y:Z[1],z:Z[2]},programUniforms:er}),getShaderSource:Hr}}}),jl,ya,bs,Vl,ba,Ul,Wl,di,$d=j(()=>{Xt(),m(),Ht(),or(),Jn(),ii(),jl=e=>{let t=1;for(let r=0;rtypeof e=="number"?[e,e,e]:e,bs=(e,t)=>t<=1?e:e+(e-1)*(t-1),Vl=(e,t,r,n=1)=>{let s=bs(t,n);return Math.floor((e[0]*(r-1)-r+s)/2)},ba=(e,t,r,n,s)=>{s==null&&(s=Vl(e,t[0],n[0]));let a=[0,0,0,r];for(let i=0;i<3;i++)e[i]+2*s>=t[i]&&(a[i]=Math.trunc((e[i]-t[i]+2*s)/n[i]+1));return a},Ul=(e,t,r,n,s,a,i,u,d,p)=>{let g,w,l,M;if(e==="VALID"&&(e=0),typeof e=="number"){g={top:e,bottom:e,left:e,right:e,front:e,back:e};let C=ba([t,r,n,1],[u,d,p],1,[s,a,i],e);w=C[0],l=C[1],M=C[2]}else if(Array.isArray(e)){if(!e.every((E,B,G)=>E===G[0]))throw Error(`Unsupported padding parameter: ${e}`);g={top:e[0],bottom:e[1],left:e[2],right:e[3],front:e[4],back:e[5]};let C=ba([t,r,n,1],[u,d,p],1,[s,a,i],e[0]);w=C[0],l=C[1],M=C[2]}else if(e==="SAME_UPPER"){w=Math.ceil(t/s),l=Math.ceil(r/a),M=Math.ceil(n/i);let C=(w-1)*s+u-t,E=(l-1)*a+d-r,B=(M-1)*i+p-n,G=Math.floor(C/2),O=C-G,ae=Math.floor(E/2),Z=E-ae,le=Math.floor(B/2),Ge=B-le;g={top:ae,bottom:Z,left:le,right:Ge,front:G,back:O}}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:g,outDepth:w,outHeight:l,outWidth:M}},Wl=(e,t,r,n,s,a=!1,i="channelsLast")=>{let u,d,p,g,w;if(i==="channelsLast")[u,d,p,g,w]=e;else if(i==="channelsFirst")[u,w,d,p,g]=e;else throw new Error(`Unknown dataFormat ${i}`);let[l,,M,C,E]=t,[B,G,O]=ya(r),[ae,Z,le]=ya(n),Ge=bs(M,ae),Le=bs(C,Z),pt=bs(E,le),{padInfo:Dt,outDepth:Vt,outHeight:lr,outWidth:fr}=Ul(s,d,p,g,B,G,O,Ge,Le,pt),er=a?l*w:l,Nr=[0,0,0,0,0];return i==="channelsFirst"?Nr=[u,er,Vt,lr,fr]:i==="channelsLast"&&(Nr=[u,Vt,lr,fr,er]),{batchSize:u,dataFormat:i,inDepth:d,inHeight:p,inWidth:g,inChannels:w,outDepth:Vt,outHeight:lr,outWidth:fr,outChannels:er,padInfo:Dt,strideDepth:B,strideHeight:G,strideWidth:O,filterDepth:M,filterHeight:C,filterWidth:E,effectiveFilterDepth:Ge,effectiveFilterHeight:Le,effectiveFilterWidth:pt,dilationDepth:ae,dilationHeight:Z,dilationWidth:le,inShape:e,outShape:Nr,filterShape:t}},di=(e,t,r,n,s,a)=>{let i=a==="channelsLast";i?e[0].dims[3]:e[0].dims[1];let u=[64,1,1],d={x:r.map((B,G)=>G)},p=[Math.ceil(jl(d.x.map(B=>r[B]))/u[0]),1,1];ue("verbose",()=>`[conv3d_naive_webgpu] dispatch = ${p}`);let g=1,w=Se.size(r),l=[{type:12,data:w},{type:12,data:n},{type:12,data:s},{type:12,data:t.strides},{type:12,data:t.dilations}];Qn(t,l),l.push(...Ct(e[0].dims,e[1].dims));let M=["rank","rank"],C=e.length===3;C&&(l.push(...Ct(e[2].dims)),M.push("rank")),l.push(...Ct(r));let E=B=>{let G=[{name:"output_size",type:"u32"},{name:"filter_dims",type:"u32",length:n.length},{name:"pads",type:"u32",length:s.length},{name:"strides",type:"u32",length:t.strides.length},{name:"dilations",type:"u32",length:t.dilations.length}];Yn(t,G);let O=1,ae=yr(e[0].dataType),Z=rt("x",e[0].dataType,e[0].dims.length,g),le=rt("W",e[1].dataType,e[1].dims.length,O),Ge=[Z,le],Le=Ut("result",e[0].dataType,r.length,O),pt="";if(C){let lr=rt("bias",e[2].dataType,e[2].dims.length,O);Ge.push(lr),pt+=` - fn getBiasByOutputCoords(coords : array) -> ${ae} { - return bias[${i?jt("coords",4,5):jt("coords",1,5)}]; - }`}let Dt=fn(g,ae),Vt=jn(t,Dt,ae);return` - ${pt} - fn getX(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { - let aIndices = array(d0, d1, d2, d3, d4); - return ${Z.getByIndices("aIndices")}; - } - fn getW(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { - let aIndices = array(d0, d1, d2, d3, d4); - return ${le.getByIndices("aIndices")}; - } - ${B.registerUniforms(G).declareVariables(...Ge,Le)} - ${B.mainStart()} - ${B.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - let coords = ${Le.offsetToIndices("global_idx")}; - let batch = ${jt("coords",0,Z.rank)}; - let d2 = ${i?jt("coords",Z.rank-1,Z.rank):jt("coords",1,Z.rank)}; - let xFRCCorner = vec3(${i?jt("coords",1,Z.rank):jt("coords",2,Z.rank)}, - ${i?jt("coords",2,Z.rank):jt("coords",3,Z.rank)}, - ${i?jt("coords",3,Z.rank):jt("coords",4,Z.rank)}) * uniforms.strides - uniforms.pads; - let xFCorner = xFRCCorner.x; - let xRCorner = xFRCCorner.y; - let xCCorner = xFRCCorner.z; - let xShapeY = ${i?jt("uniforms.x_shape",1,Z.rank):jt("uniforms.x_shape",2,Z.rank)}; - let xShapeZ = ${i?jt("uniforms.x_shape",2,Z.rank):jt("uniforms.x_shape",3,Z.rank)}; - let xShapeW = ${i?jt("uniforms.x_shape",3,Z.rank):jt("uniforms.x_shape",4,Z.rank)}; - let xShapeU = ${i?jt("uniforms.x_shape",4,Z.rank):jt("uniforms.x_shape",1,Z.rank)}; - let inputDepthNearestVec4 = (xShapeU / 4) * 4; - let inputDepthVec4Remainder = xShapeU % 4; - - var value = 0.0; - for (var wF = 0u; wF < uniforms.filter_dims[0]; wF++) { - let xF = xFCorner + wF * uniforms.dilations[0]; - if (xF < 0 || xF >= xShapeY) { - continue; - } - - for (var wR = 0u; wR < uniforms.filter_dims[1]; wR++) { - let xR = xRCorner + wR * uniforms.dilations[1]; - if (xR < 0 || xR >= xShapeZ) { - continue; - } - - for (var wC = 0u; wC < uniforms.filter_dims[2]; wC++) { - let xC = xCCorner + wC * uniforms.dilations[2]; - if (xC < 0 || xC >= xShapeW) { - continue; - } - - for (var d1 = 0u; d1 < inputDepthNearestVec4; d1 += 4) { - ${i?`let xValues = vec4( - getX(batch, xF, xR, xC, d1), - getX(batch, xF, xR, xC, d1 + 1), - getX(batch, xF, xR, xC, d1 + 2), - getX(batch, xF, xR, xC, d1 + 3)); - `:`let xValues = vec4( - getX(batch, d1, xF, xR, xC), - getX(batch, d1 + 1, xF, xR, xC), - getX(batch, d1 + 2, xF, xR, xC), - getX(batch, d1 + 3, xF, xR, xC)); - `} - let wValues = vec4( - getW(d2, d1, wF, wR, wC), - getW(d2, d1 + 1, wF, wR, wC), - getW(d2, d1 + 2, wF, wR, wC), - getW(d2, d1 + 3, wF, wR, wC)); - value += dot(xValues, wValues); - } - if (inputDepthVec4Remainder == 1) { - ${i?`value += getX(batch, xF, xR, xC, inputDepthNearestVec4) - * getW(d2, inputDepthNearestVec4, wF, wR, wC);`:`value += getX(batch, inputDepthNearestVec4, xF, xR, xC) - * getW(d2, inputDepthNearestVec4, wF, wR, wC);`} - } else if (inputDepthVec4Remainder == 2) { - ${i?`let xValues = vec2( - getX(batch, xF, xR, xC, inputDepthNearestVec4), - getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1)); - `:`let xValues = vec2( - getX(batch, inputDepthNearestVec4, xF, xR, xC), - getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC)); - `} - let wValues = vec2( - getW(d2, inputDepthNearestVec4, wF, wR, wC), - getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC)); - value += dot(xValues, wValues); - } else if (inputDepthVec4Remainder == 3) { - ${i?`let xValues = vec3( - getX(batch, xF, xR, xC, inputDepthNearestVec4), - getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1), - getX(batch, xF, xR, xC, inputDepthNearestVec4 + 2)); - `:`let xValues = vec3( - getX(batch, inputDepthNearestVec4, xF, xR, xC), - getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC), - getX(batch, inputDepthNearestVec4 + 2, xF, xR, xC)); - `} - let wValues = vec3( - getW(d2, inputDepthNearestVec4, wF, wR, wC), - getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC), - getW(d2, inputDepthNearestVec4 + 2, wF, wR, wC)); - value += dot(xValues, wValues); - } - } - } - } - ${C?"value = value + getBiasByOutputCoords(coords)":""}; - ${Vt} - result[global_idx] = f32(value); - }`};return{name:"Conv3DNaive",shaderCache:{hint:`${t.cacheKey};${i};${g};${C}`,inputDependencies:M},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:p[0],y:p[1],z:p[2]},programUniforms:l}),getShaderSource:E}}}),Gl,ql,ci=j(()=>{Xt(),Ht(),or(),Jn(),Gl=(e,t,r,n)=>{let s=e.length>2,a=s?"value += b[output_channel];":"",i=e[0].dims,u=e[1].dims,d=t.format==="NHWC",p=d?r[3]:r[1],g=p/t.group,w=d&&g>=4?mr(p):1,l=Se.size(r)/w,M=[{type:12,data:l},{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:g}];Qn(t,M),M.push(...Ct(i,[u[0],u[1],u[2],u[3]/w]));let C=s?["rank","rank","rank"]:["rank","rank"];M.push(...Ct([r[0],r[1],r[2],r[3]/w]));let E=B=>{let G=Ut("output",e[0].dataType,r.length,w),O=yr(G.type.tensor),ae=jn(t,G.type.value,O),Z=rt("x",e[0].dataType,i.length),le=rt("w",e[1].dataType,u.length,w),Ge=[Z,le];s&&Ge.push(rt("b",e[2].dataType,e[2].dims,w));let Le=[{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"}];Yn(t,Le);let pt=d?` - for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[0]; wHeight++) { - let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0]; - - if (xHeight < 0u || xHeight >= uniforms.x_shape[1]) { - continue; - } - - for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[1]; wWidth++) { - let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1]; - if (xWidth < 0u || xWidth >= uniforms.x_shape[2]) { - continue; - } - - for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[2]; wInChannel++) { - let input_channel = in_channel_offset + wInChannel; - let xVal = ${Z.get("batch","xHeight","xWidth","input_channel")}; - let wVal = ${le.get("wHeight","wWidth","wInChannel","output_channel")}; - value += xVal * wVal; - } - } - } - `:` - for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[1]; wInChannel++) { - let input_channel = in_channel_offset + 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[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[3]) { - continue; - } - - let xVal = ${Z.get("batch","input_channel","xHeight","xWidth")}; - let wVal = ${le.get("output_channel","wInChannel","wHeight","wWidth")}; - value += xVal * wVal; - } - } - } - `;return` - ${B.registerUniforms(Le).declareVariables(...Ge,G)} - - ${B.mainStart()} - ${B.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - - let outputIndices = ${G.offsetToIndices("global_idx")}; - let batch: u32 = outputIndices[0]; - let output_channel: u32 = outputIndices[${d?3:1}]; - let xRCCorner: vec2 = vec2(outputIndices[${d?1:2}], outputIndices[${d?2:3}]) * uniforms.strides - uniforms.pads; - let group_id: u32 = output_channel * ${w} / uniforms.output_channels_per_group; - var in_channel_offset = group_id * uniforms.w_shape[${d?2:1}]; - - var value: ${G.type.value} = ${G.type.value}(0); - ${pt} - ${a} - ${ae} - ${G.setByOffset("global_idx","value")} - }`};return{name:"GroupedConv",shaderCache:{hint:`${t.cacheKey}_${w}`,inputDependencies:C},getRunData:()=>({outputs:[{dims:n?n(r):r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:M}),getShaderSource:E}},ql=(e,t,r,n)=>{let s=e.length>2,a=mr(r[3]),i=mr(r[2]),u=Se.size(r)/a/i,d=[e[0].dims[0],e[0].dims[1],e[0].dims[2],e[0].dims[3]/a],p=[e[1].dims[0],e[1].dims[1],e[1].dims[2],e[1].dims[3]/a],g=[r[0],r[1],r[2],r[3]/a],w=[{type:12,data:u},{type:6,data:[t.strides[0],t.strides[1]]},{type:6,data:[t.pads[0],t.pads[1]]}];Qn(t,w),w.push(...Ct(d,p,g));let l=(i-1)*t.strides[1]+p[1],M=C=>{let E=Ut("output",e[0].dataType,g.length,a),B=yr(E.type.tensor),G=jn(t,E.type.value,B),O=rt("x",e[0].dataType,d.length,a),ae=rt("w",e[1].dataType,p.length,a),Z=[O,ae];s&&Z.push(rt("b",e[2].dataType,e[2].dims,a));let le=s?"value += b[output_channel];":"",Ge=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return Yn(t,Ge),` - ${C.registerUniforms(Ge).declareVariables(...Z,E)} - ${C.mainStart()} - ${C.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] / ${i}u; - let col = (index1 % width1) * ${i}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<${O.type.value}, ${l}>; - var values: array<${E.type.value}, ${i}>; - 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 < ${p[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 < ${l}; i++) { - let x_width = x_corner.y + i; - if (x_width >= 0 && u32(x_width) < uniforms.x_shape[2]) { - x_vals[i] = ${O.get("batch","u32(x_height)","u32(x_width)","input_channel")}; - } else { - x_vals[i] = ${O.type.value}(0); - } - } - for (var w_width: u32 = 0u; w_width < ${p[1]}; w_width++) { - let w_val = ${ae.get("w_height","w_width","0","output_channel")}; - for (var i = 0u; i < ${i}u; i++) { - values[i] = fma(x_vals[i * u32(uniforms.strides[1]) + w_width], w_val, values[i]); - } - } - } - } - - for (var i = 0u; i < ${i}u; i++) { - var value = values[i]; - ${le} - ${G} - ${E.set("batch","row","col + i","output_channel","value")}; - } - }`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${t.cacheKey};${a};${i};${l};${p[0]};${p[1]}`,inputDependencies:s?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:n?n(r):r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:w}),getShaderSource:M}}}),Ma,Hl,Kl,Xl=j(()=>{Xt(),Ht(),ui(),or(),Jn(),Ma=(e,t,r,n,s=!1,a)=>{let i=e[0].dims,u=e[1].dims,d=i[i.length-2],p=u[u.length-1],g=i[i.length-1],w=mr(p),l=mr(g),M=mr(d),C=Se.size(r)/w/M,E=e.length>2,B=n?n.slice(0,-2):r.slice(0,-2),G=[Se.size(B),d,p],O=[{type:12,data:C},{type:12,data:d},{type:12,data:p},{type:12,data:g}];Qn(t,O),O.push(...Ct(B,i,u)),E&&O.push(...Ct(e[2].dims)),O.push(...Ct(G));let ae=Z=>{let le=Ti("batch_dims",e[0].dataType,B.length),Ge=rt("a",e[0].dataType,i.length,l),Le=rt("b",e[1].dataType,u.length,w),pt=Ut("output",e[0].dataType,G.length,w),Dt=yr(pt.type.tensor),Vt=jn(t,pt.type.value,Dt),lr=[Ge,Le],fr="";if(E){let Pr=s?w:1;lr.push(rt("bias",e[2].dataType,e[2].dims.length,Pr)),fr=`${s?`value += bias[col / ${Pr}];`:`value += ${pt.type.value}(bias[row + i]);`}`}let er=i.slice(0,-2),Nr=u.slice(0,-2),Hr=Fs(er,B),br=Fs(Nr,B),jr=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];Yn(t,jr);let Jt=(Pr,Ve)=>{let kt=Pr.rank,tr=Pr.name;if(kt===2)return`var ${tr}_indices = ${Pr.type.indices}(0u, 0u);`;let zr=le.rank,nn=`var ${tr}_indices: ${Pr.type.indices};`;for(let un=kt-2-1,Vs=zr-1;un>=0;un--,Vs--)nn+=` -${tr}_indices[${un}] = ${zr>1?`batch_indices[${Vs}]`:"batch_indices"};`;return Ve.forEach(un=>{nn+=` -${tr}_indices[${un}] = 0;`}),nn+=`${tr}_indices[${kt-2}] = 0u; - ${tr}_indices[${kt-1}] = 0u;`,nn},dr=()=>{let Pr=`var a_data: ${Ge.type.value};`;for(let Ve=0;Ve; - for (var k: u32 = 0u; k < uniforms.K; k = k + ${l}) { - ${dr()} - } - for (var i = 0u; i < ${M}u; i++) { - var value = values[i]; - ${fr} - ${Vt} - let cur_indices = ${pt.type.indices}(batch, row + i, col); - let offset = ${pt.indicesToOffset("cur_indices")}; - ${pt.setByOffset(`offset / ${w}`,"value")}; - } - } - `};return{name:"MatMulNaive",shaderCache:{hint:`${t.activation};${w};${l};${M};${s}`,inputDependencies:E?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:a?a(r):r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(C/64)},programUniforms:O}),getShaderSource:ae}},Hl=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.")},Kl=e=>{Hl(e.inputs);let t=wn.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(Ma(e.inputs,{activation:""},t)):e.compute(wa(e.inputs,{activation:""},t))}}),pi,hi,Ql,fi,Yl,va,Jl,Zl,as,Sd=j(()=>{Ht(),Ed(),$d(),ui(),ci(),Jn(),Xl(),is(),pi=(e,t,r,n,s,a)=>{let i=e[0],u=e.slice(a?1:2,a?3:4),d=u.length,p=t[0],g=t.slice(2).map((l,M)=>l+(l-1)*(r[M]-1)),w=u.map((l,M)=>l+n[M]+n[M+d]).map((l,M)=>Math.floor((l-g[M]+s[M])/s[M]));return w.splice(0,0,i),w.splice(a?3:1,0,p),w},hi=[2,3,1,0],Ql=(e,t)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length>5)throw new Error("greater than 5D is not supported");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 s=e[0].dims.length-2;if(t.dilations.length!==s)throw new Error(`dilations should be ${s}D`);if(t.strides.length!==s)throw new Error(`strides should be ${s}D`);if(t.pads.length!==s*2)throw new Error(`pads should be ${s*2}D`);if(t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape")},fi=(e,t)=>{let r=e.kernelShape.slice();r.length{let t=ni(e),r=e.format,n=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],s=e.dilations,a=e.group,i=e.kernel_shape,u=e.pads,d=e.strides,p=e.w_is_const();return{autoPad:n,format:r,dilations:s,group:a,kernelShape:i,pads:u,strides:d,wIsConst:p,...t,cacheKey:`${e.format};${t.activation};`}},va=(e,t,r,n)=>{let s=r.format==="NHWC",a=pi(t[0].dims,t[1].dims,r.dilations,r.pads,r.strides,s);if(r.group!==1){let Ge=[t[0]];if(s){let Le=e.kernelCustomData.wT??e.compute(Pn(t[1],hi),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=Le),Ge.push(Le)}else Ge.push(t[1]);t.length===3&&Ge.push(t[2]),!e.adapterInfo.isArchitecture("ampere")&&s&&t[1].dims[0]===r.group&&t[1].dims[1]===1&&r.dilations[0]===1&&r.dilations[1]===1?e.compute(ql(Ge,r,a,n),{inputs:Ge}):e.compute(Gl(Ge,r,a,n),{inputs:Ge});return}let i=t.length===3,u=t[0].dims[s?1:2],d=t[0].dims[s?2:3],p=t[0].dims[s?3:1],g=t[1].dims[2],w=t[1].dims[3],l=a[s?1:2],M=a[s?2:3],C=a[s?3:1],E=s&&g===u&&w===d&&r.pads[0]===0&&r.pads[1]===0;if(E||g===1&&w===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 Ge=a[0],Le,pt,Dt,Vt=[];if(s){let er=e.kernelCustomData.wT??e.compute(Pn(t[1],hi),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];if(r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=er),E){let Nr=u*d*p;Le=t[0].reshape([1,Ge,Nr]),pt=er.reshape([1,Nr,C]),Dt=[1,Ge,C]}else Le=t[0].reshape([Ge,u*d,p]),pt=er.reshape([1,p,C]),Dt=[Ge,l*M,C];Vt.push(Le),Vt.push(pt)}else Le=t[0].reshape([Ge,p,u*d]),pt=t[1].reshape([1,C,p]),Dt=[Ge,C,l*M],Vt.push(pt),Vt.push(Le);i&&Vt.push(t[2]);let lr=Dt[2],fr=Vt[0].dims[Vt[0].dims.length-1];lr<8&&fr<8?e.compute(Ma(Vt,r,a,Dt,s,n),{inputs:Vt}):e.compute(wa(Vt,r,a,Dt,s,n),{inputs:Vt});return}let B=!0,G=e.kernelCustomData.wT??e.compute(Pn(t[1],hi),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=G);let O=[t[0],G];i&&O.push(t[2]);let ae=s?l*M:C,Z=s?C:l*M,le=g*w*p;e.compute(Nl(O,r,a,ae,Z,le,i,B,n),{inputs:O})},Jl=(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 s=[0,t.pads[0],0,t.pads[1]],a=[1].concat(t.strides),i=[1].concat(t.dilations),u=[1].concat(t.kernelShape),d=fi({...t,pads:s,strides:a,dilations:i,kernelShape:u},n);va(e,n,d,p=>r?[p[0],p[2],p[3]]:[p[0],p[1],p[3]])},Zl=(e,t,r)=>{let n=r.format==="NHWC"?"channelsLast":"channelsFirst",s=fi(r,t),a=r.autoPad==="NOTSET"?r.pads:r.autoPad,i=Wl(t[0].dims,t[1].dims,r.strides,r.dilations,a,!1,n);e.compute(di(t,s,i.outShape,[i.filterDepth,i.filterHeight,i.filterWidth],[i.padInfo.front,i.padInfo.top,i.padInfo.left],n))},as=(e,t)=>{if(Ql(e.inputs,t),e.inputs[0].dims.length===3)Jl(e,t);else if(e.inputs[0].dims.length===5)Zl(e,e.inputs,t);else{let r=fi(t,e.inputs);va(e,e.inputs,r)}}}),eu,tu,kd=j(()=>{Xt(),m(),or(),Jn(),ii(),Dl(),ui(),eu=(e,t=!1,r,n,s=4)=>{let a=B=>{switch(B){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 ${B} is not supported.`)}},i=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); - `,d=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",p=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",g=e?"row":"col",w=e?"col":"row",l=` - 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 = ${g} / outWidth; - let outCol = ${g} % outWidth; - - let WRow = ${w} / (uniforms.filter_dims[1] * inChannels); - let WCol = ${w} / 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(${d}) || 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 = ${w} % inChannels; - ${i} - return x[getIndexFromCoords4D(coord, vec4(uniforms.x_shape))/${s}];`,M=e?` - let col = colIn * ${s}; - if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { - ${l} - } - return ${n}(0.0);`:` - let col = colIn * ${s}; - if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { - ${l} - } - return ${n}(0.0);`,C=` - let col = colIn * ${s}; - 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); - ${a(s)} - } - return ${n}(0.0); - `,E=jn(r,n);return` - fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${n} { - ${e?M:C} - } - - fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${n} { - ${e?C:M} - } - - fn mm_write(batch: i32, row : i32, colIn : i32, valueInput : ${n}) { - let col = colIn * ${s}; - 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} - ${si(t)} - ${E} - result[getIndexFromCoords4D(coords, vec4(uniforms.result_shape))/${s}] = value; - } - }`},tu=(e,t,r,n,s,a,i,u)=>{let d=t.format==="NHWC",p=d?e[0].dims[3]:e[0].dims[1],g=r[0],w=d?r[2]:r[3],l=d?r[1]:r[2],M=d?r[3]:r[1],C=d&&p%4===0&&p%3&&M%4===0,E=d?M:w*l,B=d?w*l:M,G=[8,8,1],O=n<=8?[4,1,1]:[4,4,1],ae=[Math.ceil(E/G[0]/O[0]),Math.ceil(B/G[1]/O[1]),Math.ceil(g/G[2]/O[2])];ue("verbose",()=>`[conv_backprop_mm_webgpu] dispatch = ${ae}`);let Z=C?4:1,le=Math.max(G[0]*Z,G[1]),Ge=C?4:1,Le=[t.kernelShape[d?1:2],t.kernelShape[d?2:3]],pt=[Le[0]+(t.dilations[0]<=1?0:(Le[0]-1)*(t.dilations[0]-1)),Le[1]+(t.dilations[1]<=1?0:(Le[1]-1)*(t.dilations[1]-1))],Dt=[pt[0]-1-Math.floor((t.pads[0]+t.pads[2])/2),pt[1]-1-Math.floor((t.pads[1]+t.pads[3])/2)],Vt=[{type:6,data:n},{type:6,data:s},{type:6,data:a},{type:6,data:t.strides},{type:6,data:t.dilations},{type:6,data:Le},{type:6,data:Dt}];Qn(t,Vt),Vt.push(...Ct(e[0].dims,e[1].dims));let lr=["rank","rank"];i&&(Vt.push(...Ct(e[2].dims)),lr.push("rank")),Vt.push(...Ct(r));let fr=er=>{let Nr=rt("x",e[0].dataType,e[0].dims.length,Ge),Hr=rt("w",e[1].dataType,e[1].dims.length,1),br=Ut("result",e[0].dataType,r.length,Ge),jr=[Nr,Hr],Jt="";if(i){let Ve=rt("bias",e[2].dataType,e[2].dims.length,Ge);jr.push(Ve),Jt+=` - fn getBiasByOutputCoords(coords : vec4) -> ${Ve.type.value} { - return bias[coords.${d?"w":"y"}${C?"/ 4":""}]; - }`}let dr=[{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:Le.length},{name:"pads",type:"i32",length:Dt.length}];Yn(t,dr);let Pr=yr(e[0].dataType,1);if(Pr!=="f16"&&Pr!=="f32")throw new Error(`elemType ${Pr} is not supported.`);return` - ${_a("uniforms.result_strides")} - ${er.registerUniforms(dr).declareVariables(...jr,br)}; - ${Jt} - ${eu(d,i,t,Nr.type.value,Z)} - ${C?ai(O,G,Pr,void 0,!d,le):li(O,G,Pr,void 0,!d,le,!1,void 0,u)}`};return{name:"Conv2DTransposeMatMul",shaderCache:{hint:`${t.cacheKey};${O};${G};${C}`,inputDependencies:lr},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:ae[0],y:ae[1],z:ae[2]},programUniforms:Vt}),getShaderSource:fr}}}),ru,Ds,gc=j(()=>{Xt(),m(),Ht(),or(),ru=(e,t,r,n,s,a=!1,i,u,d=!1)=>{let p=d?1:2,g=d?2:3,w=d?3:1,l=a?2:1,M=` - fn setOutputAtIndex(flatIndex : u32, value : ${a?`vec4<${i}>`:i}) { - result[flatIndex] = ${a?`vec4<${i}>`:i}(value); - }`;n&&(M+=` - fn getBiasByOutputCoords(coords : vec4) -> ${a?`vec4<${i}>`:i} { - return bias[coords.${d?"w":"y"}${a?"/ 4":""}]; - }`);let C=a?4:1,E=rt("W",t[1].dataType,t[1].dims.length,C),B=rt("Dy",t[0].dataType,t[0].dims.length,C),G=[B,E];n&&G.push(rt("bias",t[2].dataType,[r[w]].length,C));let O=Ut("result",t[0].dataType,r.length,C),ae=`{ - let batch: u32 = ${s?"global_id.z":"workgroup_id.z"} / uniforms.result_shape[1]; - let r = ${s?"global_id.z":"workgroup_id.z"} % uniforms.result_shape[1]; - let c = ${s?"global_id.y":"workgroup_id.y"} * ${l}; - let d1: u32 = ${s?"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, ${l}>; - for (var i = 0; i < ${l}; i++) { - dotProd[i] = vec4<${i}>(0.0); - } - for (var wR: u32 = 0; wR < uniforms.filter_dims[0]; wR = wR + 1) { - var dyR = (${i}(dyCorner.x) + ${i}(wR)) / ${i}(uniforms.strides.x); - let wRPerm = uniforms.filter_dims[0] - 1 - wR; - if (dyR < 0.0 || dyR >= ${i}(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 = (${i}(dyCorner.y) + ${i}(wC)) / ${i}(uniforms.strides.y); - let dyC2 = (${i}(dyCorner.y) + 1.0 + ${i}(wC)) / ${i}(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 >= ${i}(uniforms.Dy_shape[2]) || - fract(dyC) > 0.0) { - bDyCVal = false; - } - if (dyC2 < 0.0 || dyC2 >= ${i}(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 = ${E.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; - let wValue1 = ${E.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; - let wValue2 = ${E.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; - let wValue3 = ${E.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; - - var xValue = ${B.get("batch","idyR","idyC","d2")}; - let tmpval = vec4<${i}>(dot(xValue, wValue0), - dot(xValue, wValue1), - dot(xValue, wValue2), - dot(xValue, wValue3)); - dotProd[0] = dotProd[0] + tmpval; - - xValue = ${B.get("batch","idyR","idyC2","d2")}; - - dotProd[1] = dotProd[1] + vec4<${i}>(dot(xValue, wValue0), - dot(xValue, wValue1), - dot(xValue, wValue2), - dot(xValue, wValue3)); - } - } else if (bDyCVal) { - let d2Length = uniforms.Dy_shape[${w}]; - for (var d2: u32 = 0; d2 < d2Length; d2 = d2 + 4) { - let wValue0 = ${E.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; - let wValue1 = ${E.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; - let wValue2 = ${E.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; - let wValue3 = ${E.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; - - var xValue = ${B.get("batch","idyR","idyC","d2")}; - let tmpval = vec4<${i}>(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 = ${E.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; - let wValue1 = ${E.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; - let wValue2 = ${E.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; - let wValue3 = ${E.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; - - var xValue = ${B.get("batch","idyR","idyC2","d2")}; - let tmpval = vec4<${i}>(dot(xValue, wValue0), - dot(xValue, wValue1), - dot(xValue, wValue2), - dot(xValue, wValue3)); - dotProd[1] = dotProd[1] + tmpval; - } - } - } - } - - for (var i: u32 = 0; i < ${l}; i = i + 1) { - let value = dotProd[i] + ${n?"bias[c+i]":`vec4<${i}>(0.0)`}; - ${O.set("batch","r","c + i","d1","value")}; - } - }`,Z=` - let outputIndices = ${O.offsetToIndices("global_idx")}; - let batch = ${O.indicesGet("outputIndices",0)}; - let d1 = ${O.indicesGet("outputIndices",w)}; - let r = ${O.indicesGet("outputIndices",p)}; - let c = ${O.indicesGet("outputIndices",g)}; - 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 = ${i}(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 = (${i}(dyRCorner) + ${i}(wR)) / ${i}(uniforms.strides[0]); - let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x; - if (dyR < 0.0 || dyR >= ${i}(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 = (${i}(dyCCorner) + ${i}(wC)) / ${i}(uniforms.strides.y); - let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y; - if (dyC < 0.0 || dyC >= ${i}(uniforms.Dy_shape[${g}]) || - 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 = ${d?B.get("batch","idyR","idyC","inputChannel"):B.get("batch","inputChannel","idyR","idyC")}; - let wValue = ${E.get("inputChannel","wOutChannel","u32(wRPerm)","u32(wCPerm)")}; - dotProd = dotProd + xValue * wValue; - inputChannel = inputChannel + 1; - } - } - } - let value = dotProd + ${n?"bias[d1]":`${i}(0.0)`}; - ${O.setByOffset("global_idx","value")}; - `;return` - ${e.registerUniforms(u).declareVariables(...G,O)} - ${M} - - ${e.mainStart()} - ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}; - ${a?ae:Z}}`},Ds=(e,t,r)=>{let n=e.length>2,s=t.outputShape,a=Se.size(s),i=[Math.ceil(a/64),1,1];ue("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${i}`);let u=t.format==="NHWC",d=["rank","rank"],p=[t.strides[0],t.strides[1]],g=[t.kernelShape[u?1:2],t.kernelShape[u?2:3]],w=[t.dilations[0],t.dilations[1]],l=[g[0]+(t.dilations[0]<=1?0:(t.kernelShape[u?1:2]-1)*(t.dilations[0]-1)),g[1]+(t.dilations[1]<=1?0:(t.kernelShape[u?2:3]-1)*(t.dilations[1]-1))],M=[l[0]-1-Math.floor((t.pads[0]+t.pads[2])/2),l[1]-1-Math.floor(t.pads[1]+t.pads[3])/2],C=!1,E=t.group,B=e[1].dims,G=B[0]/E,O=B[1],ae=[{type:12,data:a},{type:12,data:p},{type:12,data:g},{type:12,data:w},{type:12,data:l},{type:6,data:M},{type:12,data:G},{type:12,data:O},...Ct(e[0].dims,e[1].dims)];n&&(ae.push(...Ct(e[2].dims)),d.push("rank")),ae.push(...Ct(s));let Z=i[1]===1&&i[2]===1,le=Ge=>{let Le=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:p.length},{name:"filter_dims",type:"u32",length:g.length},{name:"dilations",type:"u32",length:g.length},{name:"effective_filter_dims",type:"u32",length:l.length},{name:"pads",type:"i32",length:M.length},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],pt=yr(e[0].dataType);return`${ru(Ge,e,s,n,Z,C,pt,Le,u)}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${t.cacheKey};`,inputDependencies:d},getRunData:()=>({dispatchGroup:{x:i[0],y:i[1],z:i[2]},outputs:[{dims:r?r(s):s,dataType:e[0].dataType}],programUniforms:ae}),getShaderSource:le}}}),nu,su,iu,xa,au,Ta,ou,lu,Ca,uu,Pd=j(()=>{kd(),gc(),Jn(),is(),nu=(e,t,r,n,s,a)=>(e-1)*t+r+(n-1)*s+1-a,su=(e,t,r,n,s)=>{let a=Math.floor(e/2);t==="SAME_UPPER"?(r[n]=a,r[s]=e-a):t==="SAME_LOWER"&&(r[n]=e-a,r[s]=a)},iu=(e,t,r,n,s,a,i,u,d,p)=>{let g=e.length-2,w=p.length===0;d.length{let r=e.kernelShape.slice();if(e.kernelShape.length===0||e.kernelShape.reduce((w,l)=>w*l,1)===0){r.length=0;for(let w=2;ww+l,0)===0){let w=t[0].dims.length-2;d=new Array(w).fill(1)}let p=e.strides.slice();if(p.reduce((w,l)=>w+l,0)===0){let w=t[0].dims.length-2;p=new Array(w).fill(1)}iu(u,r,d,e.autoPad,e.group,s,p,n,i,a);let g=Object.assign({},e);return Object.assign(g,{kernelShape:r,pads:s,outputPadding:i,outputShape:a,dilations:d,strides:p}),g},au=e=>{let t=ni(e),r=e.format,n=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof e.autoPad>"u"?0:e.autoPad],s=e.dilations,a=e.group,i=e.kernelShape,u=e.pads,d=e.strides,p=e.wIsConst(),g=e.outputPadding,w=e.outputShape;return{autoPad:n,format:r,dilations:s,group:a,kernelShape:i,outputPadding:g,outputShape:w,pads:u,strides:d,wIsConst:p,...t,cacheKey:`${e.format};${t.activation};`}},Ta=(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 s=e[1].dims[1]*t.group;if(e.length===3&&(e[2].dims.length!==1||e[2].dims[0]!==s))throw new Error("invalid bias");let a=e[0].dims.length-2;if(t.dilations.reduce((i,u)=>i+u,0)>0&&t.dilations.length!==a)throw new Error(`dilations should be ${a}D`);if(t.strides.reduce((i,u)=>i+u,0)>0&&t.strides.length!==a)throw new Error(`strides should be ${a}D`);if(t.pads.reduce((i,u)=>i+u,0)>0&&t.pads.length!==a*2)throw new Error(`pads should be ${a*2}D`);if(t.outputPadding.length!==a&&t.outputPadding.length!==0)throw new Error(`output_padding should be ${a}D`);if(t.kernelShape.reduce((i,u)=>i+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")},ou=[2,3,1,0],lu=(e,t,r)=>{let n=xa(r,t),s=r.format==="NHWC",a=n.outputShape,i=a[s?3:1],u=t[0].dims[s?3:1];if(n.group!==1||i===1&&u===1){e.compute(Ds(t,n));return}let d=a[s?1:2],p=a[s?2:3],g=t[1].dims[2],w=t[1].dims[3],l=s?d*p:i,M=s?i:d*p,C=g*w*u,E=!0,B=e.kernelCustomData.wT??e.compute(Pn(t[1],ou),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=B);let G=[t[0],B],O=t.length===3;O&&(!s&&t[2].dims.length===1?G.push(t[2].reshape([t[2].dims[0],1,1])):G.push(t[2])),e.compute(tu(G,n,a,l,M,C,O,E),{inputs:G})},Ca=(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 s=t.kernelShape;(s.length===0||s[0]===0)&&(s=[e.inputs[1].dims[2]]);let a=t.dilations;(a.length===0||a[0]===0)&&(a=[1]);let i=t.strides;(i.length===0||i[0]===0)&&(i=[1]);let u=t.pads;u.length===0&&(u=[0,0]),u=[0,u[0],0,u[1]],i=[1].concat(i),a=[1].concat(a),s=[1].concat(s);let d=xa({...t,pads:u,strides:i,dilations:a,kernelShape:s},n);e.compute(Ds(n,d,p=>r?[p[0],p[2],p[3]]:[p[0],p[1],p[3]]))},uu=(e,t)=>{Ta(e.inputs,t),e.inputs[0].dims.length===3?Ca(e,t):lu(e,e.inputs,t)}}),Ea,du,cu,$a=j(()=>{Xt(),Ht(),Sr(),or(),Ea=(e,t,r,n)=>{let s=Se.size(t),a=t.length,i=rt("input",e,a),u=Ut("output",e,a),d=r.dataType===6?r.getInt32Array()[0]:Number(r.getBigInt64Array()[0]),p=Se.normalizeAxis(d,a),g=w=>{let l=` i32(${i.indicesGet("inputIndices","uniforms.axis")}) `,M=jt("uniforms.input_shape","uniforms.axis",a),C=n.reverse?l+(n.exclusive?" + 1":""):"0",E=n.reverse?M:l+(n.exclusive?"":" + 1");return` - ${w.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(i,u)} - ${w.mainStart()} - ${w.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} - var inputIndices = ${u.offsetToIndices("global_idx")}; - var sum = ${u.type.value}(0); - let first : i32 = ${C}; - let last : i32 = ${E}; - for (var i : i32 = first; i < last; i++) { - ${i.indicesSet("inputIndices","uniforms.axis","u32(i)")}; - sum = sum + ${i.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(s/64)},programUniforms:[{type:12,data:s},{type:12,data:p},...Ct(t,t)]}),getShaderSource:g}},du=(e,t)=>{let r=e.inputs[0].dims,n=e.inputs[0].dataType,s=e.inputs[1];e.compute(Ea(n,r,s,t),{inputs:[0]})},cu=e=>{let t=e.exclusive===1,r=e.reverse===1;return ur({exclusive:t,reverse:r})}}),pu,hu,fu,mu,Sa,ka=j(()=>{Xt(),Ht(),Sr(),or(),pu=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.")},hu=(e,t,r,n)=>{let s=[];s.push(`fn perm(i: ${n.type.indices}) -> ${r.type.indices} { - var a: ${r.type.indices};`);for(let a=0;a{let r,n,s,a,i,u,d=t.format==="NHWC",p=t.blocksize,g=t.mode==="DCR";d?([r,n,s,a]=e.dims,i=g?[r,n,s,p,p,a/p**2]:[r,n,s,a/p**2,p,p],u=g?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([r,n,s,a]=[e.dims[0],e.dims[2],e.dims[3],e.dims[1]],i=g?[r,p,p,a/p**2,n,s]:[r,a/p**2,p,p,n,s],u=g?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let w=e.reshape(i),l=w.dims.length,M=e.dataType,C=rt("a",M,l),E=Ut("output",M,l),B=G=>` - ${G.registerUniform("output_size","u32").declareVariables(C,E)} - - ${hu(u,l,C,E)} - - ${G.mainStart()} - ${G.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - - let indices = ${E.offsetToIndices("global_idx")}; - let aIndices = perm(indices); - - ${E.setByOffset("global_idx",C.getByIndices("aIndices"))} - }`;return{name:"DepthToSpace",shaderCache:{hint:`${e.dims};${t.blocksize};${t.mode}`,inputDependencies:["rank"]},getRunData:G=>{let O=d?[r,n*p,s*p,a/p**2]:[r,a/p**2,n*p,s*p],ae=Se.size(O),Z=w.dims,le=Se.sortBasedOnPerm(Z,u);return{outputs:[{dims:O,dataType:G[0].dataType}],dispatchGroup:{x:Math.ceil(ae/64)},programUniforms:[{type:12,data:ae},...Ct(Z,le)]}},getShaderSource:B}},mu=(e,t)=>{pu(e.inputs),e.compute(fu(e.inputs[0],t))},Sa=e=>ur({blocksize:e.blocksize,mode:e.mode,format:e.format})}),Pa,Ls,Aa,Ia,_u,gu,Fa,za,wu,Oa,Ad,wc=j(()=>{Xt(),Ht(),Sr(),or(),Pa="[a-zA-Z]|\\.\\.\\.",Ls="("+Pa+")+",Aa="^"+Ls+"$",Ia="("+Ls+",)*"+Ls,_u="^"+Ia+"$",gu=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)}},Fa=class{constructor(e,t){var s;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(_u)))throw new Error("Invalid LHS term");if(r.split(",").forEach((a,i)=>{let u=e[i].dims.slice();if(!a.match(RegExp(Aa)))throw new Error("Invalid LHS term");let d=this.processTerm(a,!0,u,i);this.lhs.push(d)}),n==="")n+=[...this.symbolToInfo.entries()].filter(([a,i])=>i.count===1||a==="...").map(([a])=>a).join("");else if(!n.match(RegExp(Ls)))throw new Error("Invalid RHS");(s=n.match(RegExp(Pa,"g")))==null||s.forEach(a=>{if(a==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let i=this.symbolToInfo.get(a);if(i===void 0)throw new Error("Invalid RHS symbol");this.outputDims.push(i.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 s=r.length,a=!1,i=[],u=0;if(!e.match(RegExp(Aa))&&!t&&e!=="")throw new Error("Invalid LHS term");let d=e.match(RegExp(Pa,"g")),p=new gu(n);return d==null||d.forEach((g,w)=>{if(g==="..."){if(a)throw new Error("Only one ellipsis is allowed per input term");a=!0;let l=s-d.length+1;if(l<0)throw new Error("Ellipsis out of bounds");if(i=r.slice(u,u+l),this.hasEllipsis){if(this.ellipsisDims.length!==i.length||this.ellipsisDims.toString()!==i.toString())throw new Error("Ellipsis dimensions mismatch")}else if(t)this.hasEllipsis=!0,this.ellipsisDims=i;else throw new Error("Ellipsis must be specified in the LHS");for(let M=0;Me+"_max",wu=(e,t,r,n)=>{let s=e.map(p=>p.length).map((p,g)=>rt(`input${g}`,t,p)),a=Se.size(n),i=Ut("output",t,n.length),u=[...r.symbolToInfo.keys()].filter(p=>!r.rhs.symbolToIndices.has(p)),d=p=>{let g=[],w="var prod = 1.0;",l="var sum = 0.0;",M="sum += prod;",C=[],E=[],B=[],G=[],O=r.symbolToInfo.size===r.rhs.symbolToIndices.size;r.symbolToInfo.forEach((Z,le)=>{var Ge;if(r.rhs.symbolToIndices.has(le)){let Le=(Ge=r.rhs.symbolToIndices.get(le))==null?void 0:Ge[0];Le!==void 0&&r.lhs.forEach((pt,Dt)=>{if(Z.inputIndices.includes(Dt)){let Vt=pt.symbolToIndices.get(le);if(Vt===void 0)throw new Error("Invalid symbol error");Vt.forEach(lr=>{g.push(`${s[Dt].indicesSet(`input${Dt}Indices`,lr,i.indicesGet("outputIndices",Le))}`)})}})}else r.lhs.forEach((Le,pt)=>{if(Z.inputIndices.includes(pt)){let Dt=Le.symbolToIndices.get(le);if(Dt===void 0)throw new Error("Invalid symbol error");Dt.forEach(Vt=>{C.push(`${s[pt].indicesSet(`input${pt}Indices`,Vt,`${le}`)}`)}),G.push(`prod *= ${s[pt].getByIndices(`input${pt}Indices`)};`)}}),E.push(`for(var ${le}: u32 = 0; ${le} < uniforms.${za(le)}; ${le}++) {`),B.push("}")});let ae=O?[...g,`let sum = ${s.map((Z,le)=>Z.getByIndices(`input${le}Indices`)).join(" * ")};`]:[...g,l,...E,...C,w,...G,M,...B];return` - ${p.registerUniforms(u.map(Z=>({name:`${za(Z)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...s,i)} - - ${p.mainStart()} - ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} - var outputIndices = ${i.offsetToIndices("global_idx")}; - ${s.map((Z,le)=>`var input${le}Indices: ${s[le].type.indices};`).join(` -`)} - ${ae.join(` -`)}; - ${i.setByOffset("global_idx","sum")}; - }`};return{name:"Einsum",shaderCache:{hint:r.equation,inputDependencies:e.map(()=>"rank")},getRunData:()=>{let p=u.filter(w=>r.symbolToInfo.has(w)).map(w=>{var l;return{type:12,data:((l=r.symbolToInfo.get(w))==null?void 0:l.dimValue)||0}});p.push({type:12,data:a});let g=e.map((w,l)=>[...Ct(w)]).reduce((w,l)=>w.concat(l),p);return g.push(...Ct(n)),{outputs:[{dims:n,dataType:t}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:g}},getShaderSource:d}},Oa=(e,t)=>{let r=new Fa(e.inputs,t.equation),n=r.outputDims,s=e.inputs.map((a,i)=>a.dims);e.compute(wu(s,e.inputs[0].dataType,r,n))},Ad=e=>{let t=e.equation.replace(/\s+/g,"");return ur({equation:t})}}),Da,mi,yu,bu,La,Id=j(()=>{Xt(),Ht(),or(),Da=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 s=0;se.length>t.length?mi(e,t):mi(t,e),bu=e=>{let t=e[0].dims,r=Array.from(e[1].getBigInt64Array(),Number),n=yu(t,r),s=e[0].dataType,a=s===9?4:1,i=Math.ceil(Se.size(n)/a),u=p=>{let g=rt("input",s,t.length,a),w=Ut("output",s,n.length,a),l;if(s===9){let M=(C,E,B="")=>` - let outputIndices${E} = ${w.offsetToIndices(`outputOffset + ${E}u`)}; - let offset${E} = ${g.broadcastedIndicesToOffset(`outputIndices${E}`,w)}; - let index${E} = offset${E} / 4u; - let component${E} = offset${E} % 4u; - ${C}[${E}] = ${B}(${g.getByOffset(`index${E}`)}[component${E}]); - `;l=` - let outputOffset = global_idx * ${a}; - var data = vec4(0); - ${M("data",0,"u32")} - ${M("data",1,"u32")} - ${M("data",2,"u32")} - ${M("data",3,"u32")} - ${w.setByOffset("global_idx","data")} - }`}else l=` - let outputIndices = ${w.offsetToIndices("global_idx")}; - let inputOffset = ${g.broadcastedIndicesToOffset("outputIndices",w)}; - ${w.setByOffset("global_idx",g.getByOffset("inputOffset"))} - }`;return` - ${p.registerUniform("vec_size","u32").declareVariables(g,w)} - ${p.mainStart()} - ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} - ${l}`},d=[{type:12,data:i},...Ct(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(i/64)},programUniforms:d})}},La=e=>{Da(e.inputs),e.compute(bu(e.inputs),{inputs:[0]})}}),Mu,Ba,Fd=j(()=>{Xt(),Ht(),or(),ti(),Mu=e=>{let t=e[0].dataType,r=Se.size(e[0].dims),n=Se.size(e[1].dims),s=n%4===0,a=i=>{let u=rt("x",t,[1],4),d=rt("bias",t,[1],4),p=Ut("y",t,[1],4),g=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],w=M=>` - let bias${M}_offset: u32 = (global_idx * 4 + ${M}) % uniforms.bias_size; - let bias${M} = ${d.getByOffset(`bias${M}_offset / 4`)}[bias${M}_offset % 4];`,l=s?` - let bias = ${d.getByOffset("global_idx % (uniforms.bias_size / 4)")};`:`${w(0)}${w(1)}${w(2)}${w(3)} - let bias = ${u.type.value}(bias0, bias1, bias2, bias3);`;return`${i.registerUniforms(g).declareVariables(u,d,p)} - - ${la(Ar(t))} - - ${i.mainStart(en)} - ${i.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")} - - let x = ${u.getByOffset("global_idx")}; - ${l} - let x_in = x + bias; - ${p.setByOffset("global_idx",ua("x_in"))} - }`};return{name:"FastGeluWithBias",shaderCache:{hint:`${s}`,inputDependencies:["type","type"]},getShaderSource:a,getRunData:i=>({outputs:[{dims:i[0].dims,dataType:i[0].dataType}],programUniforms:[{type:12,data:Math.ceil(r/4)},{type:12,data:n}],dispatchGroup:{x:Math.ceil(r/en/4)}})}},Ba=e=>{e.inputs.length<2||Se.size(e.inputs[1].dims)===0?da(e):e.compute(Mu(e.inputs))}}),vu,Ra,xu,Tu,zd=j(()=>{Xt(),Ht(),Sr(),or(),vu=e=>{if(!e||e.length!==2)throw new Error("Gather requires 2 inputs.")},Ra=(e,t)=>{let r=e[0].dims,n=e[1].dims,s=r.length,a=Se.normalizeAxis(t.axis,s),i=r.slice(0);i.splice(a,1,...n);let u=r[a],d=e[0].dataType===9?4:1,p=Math.ceil(Se.size(i)/d),g=[{type:12,data:p},{type:6,data:u},{type:12,data:a},...Ct(e[0].dims,e[1].dims,i)],w=l=>{let M=rt("data",e[0].dataType,e[0].dims.length,d),C=rt("inputIndices",e[1].dataType,e[1].dims.length),E=Ut("output",e[0].dataType,i.length,d),B=O=>{let ae=n.length,Z=`var indicesIndices${O} = ${C.type.indices}(0);`;for(let le=0;le1?`indicesIndices${O}[${le}]`:`indicesIndices${O}`} = ${i.length>1?`outputIndices${O}[uniforms.axis + ${le}]`:`outputIndices${O}`};`;Z+=` - var idx${O} = ${C.getByIndices(`indicesIndices${O}`)}; - if (idx${O} < 0) { - idx${O} = idx${O} + uniforms.axisDimLimit; - } - var dataIndices${O} : ${M.type.indices}; - `;for(let le=0,Ge=0;le1?`dataIndices${O}[${le}]`:`dataIndices${O}`} = u32(idx${O});`,Ge+=ae):(Z+=`${s>1?`dataIndices${O}[${le}]`:`dataIndices${O}`} = ${i.length>1?`outputIndices${O}[${Ge}]`:`outputIndices${O}`};`,Ge++);return Z},G;if(e[0].dataType===9){let O=(ae,Z,le="")=>` - let outputIndices${Z} = ${E.offsetToIndices(`outputOffset + ${Z}u`)}; - ${B(Z)}; - let offset${Z} = ${M.indicesToOffset(`dataIndices${Z}`)}; - let index${Z} = offset${Z} / 4u; - let component${Z} = offset${Z} % 4u; - ${ae}[${Z}] = ${le}(${M.getByOffset(`index${Z}`)}[component${Z}]); - `;G=` - let outputOffset = global_idx * ${d}; - var value = vec4(0); - ${O("value",0,"u32")} - ${O("value",1,"u32")} - ${O("value",2,"u32")} - ${O("value",3,"u32")} - ${E.setByOffset("global_idx","value")} - `}else G=` - let outputIndices = ${E.offsetToIndices("global_idx")}; - ${B("")}; - let value = ${M.getByIndices("dataIndices")}; - ${E.setByOffset("global_idx","value")}; - `;return` - ${l.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(M,C,E)} - ${l.mainStart()} - ${l.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} - ${G} - }`};return{name:"Gather",shaderCache:{hint:t.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:i,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:g}),getShaderSource:w}},xu=e=>ur({axis:e.axis}),Tu=(e,t)=>{let r=e.inputs;vu(r),e.compute(Ra(e.inputs,t))}}),Cu,Ir,Od,Dd,yc=j(()=>{Xt(),Ht(),Sr(),or(),Cu=(e,t)=>{if(e.length<3||e.length>4)throw new Error("GatherBlockQuantized requires 3 or 4 inputs.");let r=Se.normalizeAxis(t.quantizeAxis,e[0].dims.length),n=t.blockSize,s=e[0],a=e[2],i=e.length===4?e[3]:void 0;if(a.dims.length!==s.dims.length||!s.dims.map((u,d)=>d===r?Math.ceil(u/n)===a.dims[d]:u===a.dims[d]).reduce((u,d)=>u&&d,!0))throw new Error("Scales must have the same rank as the input tensor and the dims should match except on gatherAxis.");if(i){if(i.dataType!==s.dataType)throw new Error("Zero point must have the same data type as the input tensor.");if(i.dims.length!==a.dims.length||!i.dims.map((u,d)=>u===a.dims[d]).reduce((u,d)=>u&&d,!0))throw new Error("Zero point must have the same rank as the input tensor and the dims should match except on quantizeAxis.")}},Ir=(e,t)=>{let r=e[0].dims,n=e[1].dims,s=r.length,a=Se.normalizeAxis(t.gatherAxis,s),i=Se.normalizeAxis(t.quantizeAxis,s),u=r.slice(0);u.splice(a,1,...n);let d=Se.size(u),p=e[2].dataType,g=e[0].dataType===22,w=[{type:12,data:d},{type:12,data:i},{type:12,data:a},{type:12,data:t.blockSize},...Ct(...e.map((M,C)=>M.dims),u)],l=M=>{let C=rt("data",e[0].dataType,e[0].dims.length),E=rt("inputIndices",e[1].dataType,e[1].dims.length),B=rt("scales",e[2].dataType,e[2].dims.length),G=e.length>3?rt("zeroPoint",e[3].dataType,e[3].dims.length):void 0,O=Ut("output",p,u.length),ae=[C,E,B];G&&ae.push(G);let Z=[{name:"output_size",type:"u32"},{name:"quantize_axis",type:"u32"},{name:"gather_axis",type:"u32"},{name:"block_size",type:"u32"}];return` - ${M.registerUniforms(Z).declareVariables(...ae,O)} - ${M.mainStart()} - let output_indices = ${O.offsetToIndices("global_idx")}; - var indices_indices = ${E.type.indices}(0); - ${n.length>1?` - for (var i: u32 = 0; i < ${n.length}; i++) { - let index = ${O.indicesGet("output_indices","uniforms.gather_axis + i")}; - ${E.indicesSet("indices_indices","i","index")}; - }`:`indices_indices = ${O.indicesGet("output_indices","uniforms.gather_axis")};`}; - var data_indices = ${C.type.indices}(0); - for (var i: u32 = 0; i < uniforms.gather_axis; i++) { - let index = ${O.indicesGet("output_indices","i")}; - ${C.indicesSet("data_indices","i","index")}; - } - var index_from_indices = ${E.getByIndices("indices_indices")}; - if (index_from_indices < 0) { - index_from_indices += ${r[a]}; - } - ${C.indicesSet("data_indices","uniforms.gather_axis","u32(index_from_indices)")}; - for (var i = uniforms.gather_axis + 1; i < ${u.length}; i++) { - let index = ${O.indicesGet("output_indices",`i + ${n.length} - 1`)}; - ${C.indicesSet("data_indices","i","index")}; - } - let data_offset = ${C.indicesToOffset("data_indices")}; - let data_index = data_offset % 8; - // Convert 4-bit packed data to 8-bit packed data. - let packed_4bit_quantized_data = ${C.getByOffset("data_offset / 8")}; - let packed_8bit_quantized_data = (packed_4bit_quantized_data >> (4 * (data_index % 2))) & 0x0f0f0f0f; - let quantized_data_vec = ${g?"unpack4xI8":"unpack4xU8"}(u32(packed_8bit_quantized_data)); - let quantized_data = quantized_data_vec[data_index / 2]; - var scale_indices = data_indices; - let quantize_axis_index = ${B.indicesGet("data_indices","uniforms.quantize_axis")} / uniforms.block_size; - ${B.indicesSet("scale_indices","uniforms.quantize_axis","quantize_axis_index")}; - var scale = ${B.getByIndices("scale_indices")}; - ${G?` - let zero_point_indices = scale_indices; - let zero_point_offset = ${G.indicesToOffset("zero_point_indices")}; - let zero_point_index = zero_point_offset % 8; - let packed_4bit_zero_points = ${G.getByOffset("zero_point_offset / 8")}; - let packed_8bit_zero_points = (packed_4bit_zero_points >> (4 * (zero_point_index % 2))) & 0x0f0f0f0f; - let zero_point_vec = ${g?"unpack4xI8":"unpack4xU8"}(u32(packed_8bit_zero_points)); - let zero_point = zero_point_vec[zero_point_index / 2];`:"var zero_point = 0"}; - let dequantized_data = ${Ar(p)}(quantized_data - zero_point) * scale; - ${O.setByOffset("global_idx","dequantized_data")}; - }`};return{name:"GatherBlockQuantized",shaderCache:{hint:`${t.cacheKey};${e.filter((M,C)=>C!==1).map(M=>M.dims.join("_")).join(";")}`,inputDependencies:Array.from({length:e.length},(M,C)=>"rank")},getRunData:()=>({outputs:[{dims:u,dataType:p}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:w}),getShaderSource:l}},Od=(e,t)=>{let r=e.inputs;Cu(r,t),e.compute(Ir(e.inputs,t))},Dd=e=>ur({blockSize:e.blockSize,gatherAxis:e.gatherAxis,quantizeAxis:e.quantizeAxis})}),Na,Eu,$u,Su,Ld=j(()=>{Xt(),Ht(),Sr(),or(),Na=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.`)},Eu=(e,t)=>{let r=e[0].dims,n=e[0].dataType,s=r.length,a=e[1].dims,i=e[1].dataType,u=Se.normalizeAxis(t.axis,s),d=r[u],p=a.slice(0),g=Se.size(p),w=rt("input",n,s),l=rt("indicesInput",i,a.length),M=Ut("output",n,p.length),C=[{type:12,data:g},{type:6,data:d},{type:12,data:u}];return C.push(...Ct(r,a,p)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:p,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(g/64)},programUniforms:C}),getShaderSource:E=>` - ${E.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(w,l,M)} - ${E.mainStart()} - ${E.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} - - let outputIndices = ${M.offsetToIndices("global_idx")}; - - var idx = ${l.getByOffset("global_idx")}; - if (idx < 0) { - idx = idx + uniforms.axisDimLimit; - } - var inputIndices = ${w.type.indices}(outputIndices); - ${w.indicesSet("inputIndices","uniforms.axis","u32(idx)")}; - let value = ${w.getByIndices("inputIndices")}; - - ${M.setByOffset("global_idx","value")}; - }`}},$u=e=>ur({axis:e.axis}),Su=(e,t)=>{let r=e.inputs;Na(r),e.compute(Eu(e.inputs,t))}}),ja,Va,ku,Pu,Au=j(()=>{Xt(),Ht(),or(),ja=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")},Va=(e,t)=>{let r=e[0].dims.slice(),n=e[1].dims.slice(),[s,a,i]=xn.getShapeOfGemmResult(r,t.transA,n,t.transB,e.length===3?e[2].dims:void 0),u=[s,a];if(!u)throw new Error("Can't use gemm on the given tensors");let d=Se.size(u),p=[{type:12,data:d},{type:12,data:s},{type:12,data:a},{type:12,data:i},{type:1,data:t.alpha},{type:1,data:t.beta}],g=["type","type"];e.length===3&&(p.push(...Ct(e[2].dims)),g.push("rank")),p.push(...Ct(u));let w=l=>{let M="";t.transA&&t.transB?M="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":t.transA&&!t.transB?M="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!t.transA&&t.transB?M="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!t.transA&&!t.transB&&(M="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let C=t.alpha===1?"":"value *= uniforms.alpha;",E=rt("a",e[0].dataType,e[0].dims),B=rt("b",e[1].dataType,e[1].dims),G=E.type.value,O=null,ae=[E,B];e.length===3&&(O=rt("c",e[2].dataType,e[2].dims.length),ae.push(O));let Z=Ut("output",e[0].dataType,u.length);ae.push(Z);let le=[{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` - ${l.registerUniforms(le).declareVariables(...ae)} - - ${l.mainStart()} - ${l.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - - let m = global_idx / uniforms.N; - let n = global_idx % uniforms.N; - - var value = ${G}(0); - for (var k: u32 = 0u; k < uniforms.K; k++) { - ${M} - } - - ${C} - ${O!=null?`let cOffset = ${O.broadcastedIndicesToOffset("vec2(m, n)",Z)}; value += ${G}(uniforms.beta) * ${O.getByOffset("cOffset")};`:""} - output[global_idx] = value; - }`};return{name:"Gemm",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:g},getRunData:()=>({outputs:[{dims:u,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:p}),getShaderSource:w}},ku=e=>{let t=e.transA,r=e.transB,n=e.alpha,s=e.beta;return{transA:t,transB:r,alpha:n,beta:s,cacheKey:`${e.transA};${e.transB};${e.alpha===1}`}},Pu=(e,t)=>{ja(e.inputs),e.compute(Va(e.inputs,t))}}),yn,Bd,Iu,Ua,Fu,Bs,zu,Ou=j(()=>{Xt(),Ht(),Sr(),se(),Ki(),or(),is(),yn=(e,t)=>e.length>t&&e[t].dims.length>0?e[t]:void 0,Bd=(e,t)=>{let r=e[0],n=yn(e,1),s=yn(e,2),a=yn(e,3),i=yn(e,4),u=yn(e,5),d=yn(e,6),p=yn(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 g=r.dims[0],w=r.dims[1],l=r.dims.length===3?r.dims[2]:t.numHeads*r.dims[4],M=w,C=0,E=0,B=Math.floor(l/t.numHeads);if(d&&p&&Se.size(d.dims)&&Se.size(p.dims)){if(d.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(d.dims[0]!==g||d.dims[1]!==t.numHeads||d.dims[3]!==B)throw new Error('Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)');if(p.dims[0]!==g||p.dims[1]!==t.numHeads||p.dims[3]!==B)throw new Error('Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)');if(d.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');C=d.dims[2],E=d.dims[2]}else if(d&&Se.size(d.dims)||p&&Se.size(p.dims))throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let G;if(n&&Se.size(n.dims)>0){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)');G=2,M=n.dims[1]}else if(n.dims.length===5){if(n.dims[2]!==t.numHeads||n.dims[3]!==2||n.dims[4]!==B)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(s)throw new Error('Expect "value" be none when "key" has packed kv format.');G=5,M=n.dims[1]}else{if(n.dims[1]!==t.numHeads||n.dims[3]!==B)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');G=0,M=n.dims[2]}}else{if(r.dims.length!==5)throw new Error('Input "query" is expected to have 5 dimensions when key is empty');if(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');G=3}if(a&&Se.size(a.dims)>0){if(a.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimension');if(n&&n.dims.length===5&&n.dims[3]===2)throw new Error("bias is not allowed for packed kv.")}let O=C+M,ae=0;if(i&&Se.size(i.dims)>0){ae=8;let Le=i.dims;throw Le.length===1?Le[0]===g?ae=1:Le[0]===3*g+2&&(ae=3):Le.length===2&&Le[0]===g&&Le[1]===O&&(ae=5),ae===8?new Error('Input "key_padding_mask" shape shall be (batch_size) or (batch_size, total_sequence_length)'):new Error("Mask not supported")}let Z=!1,le=l;if(s&&Se.size(s.dims)>0){if(s.dims.length!==3&&s.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(r.dims[0]!==s.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(s.dims.length===3){if(M!==s.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');le=s.dims[2]}else{if(M!==s.dims[2])throw new Error('Input "key" and "value" shall have the same dim 2 (kv_sequence_length)');le=s.dims[1]*s.dims[3],Z=!0}}let Ge=!1;if(i&&Se.size(i.dims)>0)throw new Error("Key padding mask is not supported");if(u&&Se.size(u.dims)>0){if(u.dims.length!==4)throw new Error('Input "attention_bias" is expected to have 4 dimensions');if(u.dims[0]!==g||u.dims[1]!==t.numHeads||u.dims[2]!==w||u.dims[3]!==O)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:g,sequenceLength:w,pastSequenceLength:C,kvSequenceLength:M,totalSequenceLength:O,maxSequenceLength:E,inputHiddenSize:0,hiddenSize:l,vHiddenSize:le,headSize:B,vHeadSize:Math.floor(le/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:ae,scale:t.scale,broadcastResPosBias:Ge,passPastInKv:Z,qkvFormat:G}},Iu=e=>ur({...e}),Ua=ur({perm:[0,2,1,3]}),Fu=(e,t,r,n,s,a,i)=>{let u=[n,s,a],d=Se.size(u),p=[{type:12,data:d},{type:12,data:i},{type:12,data:a}],g=w=>{let l=Ut("qkv_with_bias",t.dataType,u),M=rt("qkv",t.dataType,u),C=rt("bias",r.dataType,u),E=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return` - ${w.registerUniforms(E).declareVariables(M,C,l)} - ${w.mainStart()} - ${w.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(d/64)},programUniforms:p}),getShaderSource:g},{inputs:[t,r],outputs:[-1]})[0]},Bs=(e,t,r,n,s,a,i,u)=>{let d=a;if(i&&Se.size(i.dims)>0){if(n===1)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return d=Fu(e,a,i,t,n,r*s,u),d=d.reshape([t,n,r,s]),e.compute(Pn(d,Ua.perm),{inputs:[d],outputs:[-1]})[0]}else return a.dims.length===3&&(d=a.reshape([t,n,r,s])),e.compute(Pn(d,Ua.perm),{inputs:[d],outputs:[-1]})[0]},zu=(e,t)=>{let r=Bd(e.inputs,t),n=e.inputs[0],s=yn(e.inputs,1),a=yn(e.inputs,2),i=yn(e.inputs,3),u=yn(e.inputs,4),d=yn(e.inputs,5),p=yn(e.inputs,6),g=yn(e.inputs,7);if(n.dims.length===5)throw new Error("Packed QKV is not implemented");if((s==null?void 0:s.dims.length)===5)throw new Error("Packed KV is not implemented");let w=s&&a&&s.dims.length===4&&a.dims.length===4,l=Bs(e,r.batchSize,r.numHeads,r.sequenceLength,r.headSize,n,i,0);if(w)return Os(e,l,s,a,u,void 0,p,g,d,r,t);if(!s||!a)throw new Error("key and value must be provided");let M=Bs(e,r.batchSize,r.numHeads,r.kvSequenceLength,r.headSize,s,i,r.hiddenSize),C=Bs(e,r.batchSize,r.numHeads,r.kvSequenceLength,r.vHeadSize,a,i,2*r.hiddenSize);Os(e,l,M,C,u,void 0,p,g,d,r,t)}}),Wa,Du,Lu,Ga,Bu,Ru=j(()=>{Xt(),Ht(),or(),Wa=e=>Array.from(e.getBigInt64Array(),Number),Du=e=>{if(!e||e.length!==2)throw new Error("Tile requires 2 inputs.");if(e[0].dataType!==1&&e[0].dataType!==10&&e[0].dataType!==6&&e[0].dataType!==12)throw new Error("Tile only support float, float16, 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(Wa(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")},Lu=(e,t)=>{let r=[];for(let n=0;n{let r=e[0].dims,n=t??Wa(e[1]),s=Lu(r,n),a=Se.size(s),i=e[0].dataType,u=rt("input",i,r.length),d=Ut("output",i,s.length),p=g=>` - const inputShape = ${u.indices(...r)}; - ${g.registerUniform("output_size","u32").declareVariables(u,d)} - ${g.mainStart()} - ${g.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - let output_indices = ${d.offsetToIndices("global_idx")}; - var input_indices: ${u.type.indices}; - for (var i = 0; i < ${r.length}; i++) { - let input_dim_i = ${u.indicesGet("uniforms.input_shape","i")}; - let input_dim_value = ${d.indicesGet("output_indices","i")} % input_dim_i; - - ${u.indicesSet("input_indices","i","input_dim_value")} - } - ${d.setByOffset("global_idx",u.getByIndices("input_indices"))} - }`;return{name:"Tile",shaderCache:{hint:`${n}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:[{type:12,data:a},...Ct(e[0].dims,s)]}),getShaderSource:p}},Bu=e=>{Du(e.inputs),e.compute(Ga(e.inputs),{inputs:[0]})}}),Nu,qa,ju,Vu,Ha,Rd,Uu=j(()=>{Xt(),Ht(),Sr(),Ki(),or(),Ou(),Ru(),is(),Nu=(e,t)=>{let r=e[0],n=e[1],s=e[2],a=e[3],i=e[4];if(r.dims.length!==3&&r.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let u=!1,d=r.dims[0],p=r.dims[1],g=r.dims.length===3?u?r.dims[2]/3:r.dims[2]:t.numHeads*r.dims[4],w=p,l=0,M=0,C=Math.floor(g/t.numHeads),E=a&&a.dims.length!==0,B=i&&i.dims.length!==0,G=!0;if(E&&B){if(a.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(i.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');l=a.dims[1],M=a.dims[1]}else if(E||B)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let O;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(r.dims[2]%n.dims[2]!==0)throw new Error('Dimension 2 of "query" should be a multiple of "key"');O=2,w=n.dims[1]}else if(n.dims.length===5){if(n.dims[2]!==t.numHeads||n.dims[3]!==2||n.dims[4]!==C)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(s)throw new Error('Expect "value" be none when "key" has packed kv format.');O=5,w=n.dims[1]}else{if(n.dims[1]!==t.numHeads||n.dims[3]!==C)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');O=0,w=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');O=3}let ae=0,Z=!1,le=g;if(s){if(s.dims.length!==3&&s.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(r.dims[0]!==s.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(s.dims.length===3){if(w!==s.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');le=s.dims[2]}else{if(w!==s.dims[2])throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');le=s.dims[1]*s.dims[3],Z=!0}}let Ge=l+w;return{batchSize:d,sequenceLength:p,pastSequenceLength:l,kvSequenceLength:w,totalSequenceLength:Ge,maxSequenceLength:M,inputHiddenSize:0,hiddenSize:g,vHiddenSize:le,headSize:C,vHeadSize:Math.floor(le/t.kvNumHeads),numHeads:t.numHeads,kvNumHeads:t.kvNumHeads,nReps:t.numHeads/t.kvNumHeads,pastPresentShareBuffer:!1,maskType:ae,scale:t.scale,broadcastResPosBias:!1,passPastInKv:Z,qkvFormat:O,isPastkvBSNH:G}},qa=(e,t,r,n)=>{let s=[n.batchSize,n.totalSequenceLength,n.kvNumHeads,n.headSize],a=4,i=Se.size(s)/a,u=n.totalSequenceLength,d=Ut("present_kv",r,s.length,a),p=rt("new_kv",e.dataType,e.dims.length,a),g=t?rt("past_kv",t.dataType,t.dims.length,a):void 0,w=Math.ceil(n.headSize/a),l={x:u,y:e.dims[0],z:1},M=t?["rank","rank"]:["rank"],C=[{type:12,data:i},{type:12,data:n.pastSequenceLength},{type:12,data:n.kvSequenceLength},{type:12,data:n.totalSequenceLength}],E=[p];g?(C.push(...Ct(e.dims),...Ct(t.dims),...Ct(s)),E.push(g)):C.push(...Ct(e.dims),...Ct(s));let B=[{name:"output_size",type:"u32"},{name:"past_seqlen",type:"u32"},{name:"new_seqlen",type:"u32"},{name:"present_seqlen",type:"u32"}],G=` let past_batch_stride = uniforms.past_seqlen * num_heads * H; - var past_head_stride = uniforms.past_seqlen * H; - if (is_bsnh) { - past_head_stride = H; - } - let in_offset = b * past_batch_stride + s * row_stride + n * past_head_stride + h; - present_kv[out_offset] = past_kv[in_offset];`,O=` let new_batch_stride = uniforms.new_seqlen * num_heads * H; - let new_row_stride = num_heads * H; - let new_head_stride = H; - let in_offset = b * new_batch_stride + (s - past_seqlen) * new_row_stride + n * new_head_stride + h; - present_kv[out_offset] = new_kv[in_offset];`,ae=t?`if (s < past_seqlen) { - ${G} - } else if (s < past_seqlen + uniforms.new_seqlen) { - ${O} - }`:`if (s < past_seqlen + uniforms.new_seqlen) { - ${O} - }`,Z=le=>` - - ${le.registerUniforms(B).declareVariables(...E,d)} - ${le.mainStart([w,n.kvNumHeads,1])} - ${le.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - var indices = ${d.offsetToIndices("global_idx")}; - let h = local_id.x; - let n = local_id.y; - let s = workgroup_id.x; - let b = workgroup_id.y; - let num_heads = ${n.kvNumHeads}u; - let H = ${w}u; - - let present_seqlen = uniforms.present_seqlen; - let present_batch_stride = present_seqlen * num_heads * H; - var row_stride = H; - let is_bsnh = ${n.isPastkvBSNH}; - - if (is_bsnh) { - row_stride = num_heads * H; - } - var present_head_stride = present_seqlen * H; - if (is_bsnh) { - present_head_stride = H; - } - - let past_seqlen = uniforms.past_seqlen; - - let out_offset = b * present_batch_stride + s * row_stride + n * present_head_stride + h; - ${ae} - }`;return{name:"ConcatPastNew",shaderCache:{hint:`${n.kvNumHeads}${w}${!!t}`,inputDependencies:M},getRunData:()=>({outputs:[{dims:s,dataType:r}],dispatchGroup:l,programUniforms:C}),getShaderSource:Z}},ju=e=>ur({...e}),Vu=ur({perm:[0,2,1,3]}),Ha=(e,t,r,n,s)=>{let a=t,i=n.kvNumHeads,u=n.nReps;return t.dims.length===3&&n.kvSequenceLength!==0&&(a=t.reshape([n.batchSize,n.kvSequenceLength,i,n.headSize])),r?a=e.compute(qa(a,r,a.dataType,n),{inputs:[a,r],outputs:[n.isPastkvBSNH?s:-1]})[0]:a=e.compute(qa(a,void 0,a.dataType,n),{inputs:[a],outputs:[n.isPastkvBSNH?s:-1]})[0],u!==1&&(a=e.compute(Ga([a],[1,1,1,u]),{inputs:[a],outputs:[-1]})[0],a=a.reshape([n.batchSize,n.totalSequenceLength,i*u,n.headSize])),e.compute(Pn(a,Vu.perm),{inputs:[a],outputs:[-1]})[0]},Rd=(e,t)=>{var d;let r=Nu(e.inputs,t);if(e.inputs[0].dims.length===5)throw new Error("Packed QKV is not implemented");if(((d=e.inputs[1])==null?void 0:d.dims.length)===5)throw new Error("Packed KV is not implemented");let n=Bs(e,r.batchSize,r.numHeads,r.sequenceLength,r.headSize,e.inputs[0],void 0,0),s=e.inputs[3]&&e.inputs[3].dims.length!==0?e.inputs[3]:void 0,a=e.inputs[4]&&e.inputs[4].dims.length!==0?e.inputs[4]:void 0,i=Ha(e,e.inputs[1],s,r,1),u=Ha(e,e.inputs[2],a,r,2);Os(e,n,i,u,void 0,void 0,void 0,void 0,void 0,r,t)}}),Ka,Wu,Gu,qu,Nd=j(()=>{Xt(),Ht(),is(),or(),Ka=(e,t,r,n,s,a,i,u)=>{let d=mr(a),p=d===1?"f32":`vec${d}f`,g=d===1?"vec2f":`mat2x${d}f`,w=s*i,l=[s,i,a/d],M=[s,i,2],C=["rank","type","type"],E=[];E.push(...Ct(l,M));let B=G=>{let O=rt("x",t.dataType,3,d),ae=rt("scale",r.dataType,r.dims),Z=rt("bias",n.dataType,n.dims),le=Ut("output",1,3,2),Ge=[O,ae,Z,le],Le=64;return` - var workgroup_shared : array<${g}, ${Le}>; - const workgroup_size = ${Le}u; - ${G.declareVariables(...Ge)} - ${G.mainStart(Le)} - let batch = workgroup_index / uniforms.x_shape[1]; - let channel = workgroup_index % uniforms.x_shape[1]; - let hight = uniforms.x_shape[2]; - // initialize workgroup memory - var sum = ${p}(0); - var squared_sum = ${p}(0); - for (var h = local_idx; h < hight; h += workgroup_size) { - let value = ${p}(${O.get("batch","channel","h")}); - sum += value; - squared_sum += value * value; - } - workgroup_shared[local_idx] = ${g}(sum, squared_sum); - workgroupBarrier(); - - for (var currSize = workgroup_size >> 1; currSize > 0; currSize = currSize >> 1) { - if (local_idx < currSize) { - workgroup_shared[local_idx] = workgroup_shared[local_idx] + workgroup_shared[local_idx + currSize]; - } - workgroupBarrier(); - } - if (local_idx == 0) { - let sum_final = ${Xn("workgroup_shared[0][0]",d)} / f32(hight * ${d}); - let squared_sum_final = ${Xn("workgroup_shared[0][1]",d)} / f32(hight * ${d}); - - let inv_std_dev = inverseSqrt(squared_sum_final - sum_final * sum_final + f32(${u})); - let channel_scale = inv_std_dev * f32(scale[channel]); - let channel_shift = f32(bias[channel]) - sum_final * channel_scale; - output[workgroup_index] = vec2f(channel_scale, channel_shift); - } - }`};return e.compute({name:"InstanceNormComputeChannelScaleShift",shaderCache:{hint:`${d};${u}`,inputDependencies:C},getRunData:()=>({outputs:[{dims:M,dataType:1}],dispatchGroup:{x:w},programUniforms:E}),getShaderSource:B},{inputs:[t,r,n],outputs:[-1]})[0]},Wu=(e,t,r)=>{let n=t[0].dims,s=n,a=2,i=n[0],u=n[1],d=Se.sizeFromDimension(n,a),p=mr(d),g=Se.size(s)/p,w=Ka(e,t[0],t[1],t[2],i,d,u,r.epsilon),l=[i,u,d/p],M=[i,u],C=["type","none"],E=B=>{let G=rt("x",t[0].dataType,l.length,p),O=rt("scale_shift",1,M.length,2),ae=Ut("output",t[0].dataType,l.length,p),Z=[G,O,ae];return` - ${B.registerUniform("output_size","u32").declareVariables(...Z)} - ${B.mainStart()} - ${B.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - let outputIndices = ${ae.offsetToIndices("global_idx")}; - let batch = outputIndices[0]; - let channel = outputIndices[1]; - let scale_shift = ${O.getByIndices("vec2(batch, channel)")}; - let value = ${G.getByOffset("global_idx")} * ${ae.type.value}(scale_shift.x) + ${ae.type.value}(scale_shift.y); - ${ae.setByOffset("global_idx","value")}; - }`};e.compute({name:"InstanceNormalization",shaderCache:{hint:`${p}`,inputDependencies:C},getRunData:()=>({outputs:[{dims:s,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(g/64)},programUniforms:[{type:12,data:g},...Ct(l,M,l)]}),getShaderSource:E},{inputs:[t[0],w]})},Gu=(e,t,r)=>{let n=t[0].dims,s=n,a=n[0],i=n[n.length-1],u=Se.sizeFromDimension(n,1)/i,d=mr(i),p=Se.size(s)/d,g=[{type:12,data:u},{type:12,data:Math.floor(i/d)}],w=["type","type"],l=[0,n.length-1];for(let B=0;B{let G=yr(t[0].dataType),O=d===1?"vec2f":`mat${d}x2f`,ae=Ge=>{let Le=Ge===0?"x":"y",pt=d===1?"f32":`vec${d}f`;switch(d){case 1:return`${G}(${pt}(scale.${Le}))`;case 2:return`vec2<${G}>(${pt}(scale[0].${Le}, scale[1].${Le}))`;case 4:return`vec4<${G}>(${pt}(scale[0].${Le}, scale[1].${Le}, scale[2].${Le}, scale[3].${Le}))`;default:throw new Error(`Not supported compoents ${d}`)}},Z=rt("input",t[0].dataType,t[0].dims,d),le=Ut("output",t[0].dataType,s,d);return` - @group(0) @binding(0) var input : array<${Z.type.storage}>; - @group(0) @binding(1) var scale_input : array<${O}>; - @group(0) @binding(2) var output : array<${le.type.storage}>; - struct Uniforms {H: u32, C : u32}; - @group(0) @binding(3) var uniforms: Uniforms; - - ${B.mainStart()} - let current_image_number = global_idx / (uniforms.C * uniforms.H); - let current_channel_number = global_idx % uniforms.C; - - let scale_offset = current_image_number * uniforms.C + current_channel_number; - let scale = scale_input[scale_offset]; - output[global_idx] = fma(input[global_idx], ${ae(0)}, ${ae(1)}); - }`};e.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${d}`,inputDependencies:w},getRunData:()=>({outputs:[{dims:s,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:g}),getShaderSource:E},{inputs:[t[0],C]})},qu=(e,t)=>{t.format==="NHWC"?Gu(e,e.inputs,t):Wu(e,e.inputs,t)}}),Hu,Ku,Xu,jd=j(()=>{Xt(),Ht(),or(),Hu=e=>{if(!e||e.length<2)throw new Error("layerNorm requires at least 2 inputs.")},Ku=(e,t,r)=>{let n=t.simplified,s=e[0].dims,a=e[1],i=!n&&e[2],u=s,d=Se.normalizeAxis(t.axis,s.length),p=Se.sizeToDimension(s,d),g=Se.sizeFromDimension(s,d),w=Se.size(a.dims),l=i?Se.size(i.dims):0;if(w!==g||i&&l!==g)throw new Error(`Size of X.shape()[axis:] == ${g}. - Size of scale and bias (if provided) must match this. - Got scale size of ${w} and bias size of ${l}`);let M=[];for(let le=0;le1,O=r>2,ae=le=>{let Ge=yr(e[0].dataType),Le=[rt("x",e[0].dataType,e[0].dims,C),rt("scale",a.dataType,a.dims,C)];i&&Le.push(rt("bias",i.dataType,i.dims,C)),Le.push(Ut("output",e[0].dataType,u,C)),G&&Le.push(Ut("mean_data_output",1,M)),O&&Le.push(Ut("inv_std_output",1,M));let pt=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return` - ${le.registerUniforms(pt).declareVariables(...Le)} - ${le.mainStart()} - ${le.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")} - let offset = global_idx * uniforms.norm_size_vectorized; - var mean_vector = ${Hn("f32",C)}; - var mean_square_vector = ${Hn("f32",C)}; - - for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) { - let value = ${Kn(Ge,C,"x[h + offset]")}; - mean_vector += value; - mean_square_vector += value * value; - } - let mean = ${Xn("mean_vector",C)} / uniforms.norm_size; - let inv_std_dev = inverseSqrt(${Xn("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 = ${Kn(Ge,C,"x[j + offset]")}; - let f32scale = ${Kn(Ge,C,"scale[j]")}; - output[j + offset] = ${Le[0].type.value}((f32input ${n?"":"- mean"}) * inv_std_dev * f32scale - ${i?`+ ${Kn(Ge,C,"bias[j]")}`:""} - ); - } - - ${G?"mean_data_output[global_idx] = mean":""}; - ${O?"inv_std_output[global_idx] = inv_std_dev":""}; - }`},Z=[{dims:u,dataType:e[0].dataType}];return G&&Z.push({dims:M,dataType:1}),O&&Z.push({dims:M,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${C};${r};${n}`,inputDependencies:E},getRunData:()=>({outputs:Z,dispatchGroup:{x:Math.ceil(p/64)},programUniforms:B}),getShaderSource:ae}},Xu=(e,t)=>{Hu(e.inputs),e.compute(Ku(e.inputs,t,e.outputCount))}}),Qu,Yu,Ju,Zu,Vd=j(()=>{Xt(),Ht(),Sr(),or(),Qu=(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 s=Math.floor((t.k+t.blockSize-1)/t.blockSize),a=t.blockSize/8*t.bits,i=e[1];if(!Se.areEqual(i.dims,[t.n,s,a]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let u=e[2].dims;if(Se.size(u)!==t.n*s)throw new Error("scales input size error.");if(e.length===4){let d=e[3].dims,p=t.bits>4?t.n*s:t.n*Math.floor((s+1)/2);if(Se.size(d)!==p)throw new Error("zeroPoints input size error.")}},Yu=(e,t)=>{let r=e[0].dims,n=r.length,s=r[n-2],a=t.k,i=t.n,u=r.slice(0,n-2),d=Se.size(u),p=e[1].dims[2]/4,g=e[0].dataType,w=mr(t.k),l=mr(p),M=mr(i),C=u.concat([s,i]),E=s>1&&i/M%2===0?2:1,B=Se.size(C)/M/E,G=64,O=[],ae=[d,s,a/w],Z=Se.convertShape(e[1].dims).slice();Z.splice(-1,1,p/l),O.push(...Ct(ae)),O.push(...Ct(Z)),O.push(...Ct(e[2].dims)),e.length===4&&O.push(...Ct(Se.convertShape(e[3].dims)));let le=[d,s,i/M];O.push(...Ct(le));let Ge=Le=>{let pt=ae.length,Dt=rt("a",e[0].dataType,pt,w),Vt=rt("b",12,Z.length,l),lr=rt("scales",e[2].dataType,e[2].dims.length),fr=[Dt,Vt,lr],er=e.length===4?rt("zero_points",12,e[3].dims.length):void 0;er&&fr.push(er);let Nr=le.length,Hr=Ut("output",e[0].dataType,Nr,M),br=yr(e[0].dataType),jr=(()=>{switch(w){case 1:return`array<${br}, 8>`;case 2:return`mat4x2<${br}>`;case 4:return`mat2x4<${br}>`;default:throw new Error(`${w}-component is not supported.`)}})(),Jt=()=>{let Ve=` - // reuse a data - var input_offset = ${Dt.indicesToOffset(`${Dt.type.indices}(batch, row, word_offset)`)}; - var a_data: ${jr}; - for (var j: u32 = 0; j < ${8/w}; j++) { - a_data[j] = ${Dt.getByOffset("input_offset")}; - input_offset++; - } - `;for(let kt=0;kt> 4) & b_mask); - b_quantized_values = ${jr}(${Array.from({length:4},(tr,zr)=>`${br}(b_value_lower[${zr}]), ${br}(b_value_upper[${zr}])`).join(", ")}); - b_dequantized_values = ${w===1?`${jr}(${Array.from({length:8},(tr,zr)=>`(b_quantized_values[${zr}] - ${er?`zero_point${kt}`:"zero_point"}) * scale${kt}`).join(", ")});`:`(b_quantized_values - ${jr}(${Array(8).fill(`${er?`zero_point${kt}`:"zero_point"}`).join(",")})) * scale${kt};`}; - workgroup_shared[local_id.x * ${E} + ${Math.floor(kt/M)}]${M>1?`[${kt%M}]`:""} += ${Array.from({length:8/w},(tr,zr)=>`${w===1?`a_data[${zr}] * b_dequantized_values[${zr}]`:`dot(a_data[${zr}], b_dequantized_values[${zr}])`}`).join(" + ")}; - `;return Ve},dr=()=>{let Ve=` - var col_index = col * ${M}; - ${er?` - let zero_point_bytes_per_col = (nBlocksPerCol + 1) / 2; - var zero_point_byte_count: u32; - var zero_point_word_index: u32; - var zero_point_byte_offset: u32; - let zero_point_nibble_offset: u32 = block & 0x1u; - var zero_point_bits_offset: u32; - var zero_point_word: u32;`:` - // The default zero point is 8 for unsigned 4-bit quantization. - let zero_point = ${br}(8);`} - `;for(let kt=0;kt> 0x1u); - zero_point_word_index = zero_point_byte_count >> 0x2u; - zero_point_byte_offset = zero_point_byte_count & 0x3u; - zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2); - zero_point_word = ${er.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; - let zero_point${kt} = ${br}((zero_point_word) & 0xFu);`:""} - col_index += 1;`;return Ve},Pr=()=>{let Ve=`col_index = col * ${M};`;for(let kt=0;kt; - var b_value_upper: vec4; - var b_quantized_values: ${jr}; - var b_dequantized_values: ${jr};`,Ve};return` - var workgroup_shared: array<${Hr.type.value}, ${E*G}>; - ${Le.declareVariables(...fr,Hr)} - ${Le.mainStart([G,1,1])} - let output_indices = ${Hr.offsetToIndices(`(global_idx / ${G}) * ${E}`)}; - let col = output_indices[2]; - let row = output_indices[1]; - let batch = output_indices[0]; - let nBlocksPerCol = uniforms.b_shape[1]; - - for (var block = local_id.x; block < nBlocksPerCol; block += ${G}) { - //process one block - var word_offset: u32 = block * ${t.blockSize/w}; - ${dr()} - for (var word: u32 = 0; word < ${p}; word += ${l}) { - ${Pr()} - for (var i: u32 = 0; i < ${l}; i++) { - ${Jt()} - word_offset += ${8/w}; - } - } - } - workgroupBarrier(); - - if (local_id.x < ${E}) { - var output_value: ${Hr.type.value} = ${Hr.type.value}(0); - var workgroup_shared_offset: u32 = local_id.x; - for (var b: u32 = 0u; b < ${G}u; b++) { - output_value += workgroup_shared[workgroup_shared_offset]; - workgroup_shared_offset += ${E}; - } - ${Hr.setByIndices(`${Hr.type.indices}(batch, row, col + local_id.x)`,"output_value")}; - } - }`};return{name:"MatMulNBits",shaderCache:{hint:`${t.blockSize};${t.bits};${w};${l};${M};${E};${G}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:C,dataType:g}],dispatchGroup:{x:B},programUniforms:O}),getShaderSource:Ge}},Ju=(e,t)=>{Qu(e.inputs,t),e.compute(Yu(e.inputs,t))},Zu=e=>ur(e)}),ed,td,rd,nd,sd,id,ad,od,ld,Ud=j(()=>{Xt(),Ht(),or(),ed=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].")}},td=(e,t,r)=>{let n="";for(let s=t-1;s>=0;--s)n+=` - k = i32(${e.indicesGet("indices",s)}) - ${jt("uniforms.pads",s,r)}; - if (k < 0) { - break; - } - if (k >= i32(${jt("uniforms.x_shape",s,t)})) { - break; - } - offset += k * i32(${jt("uniforms.x_strides",s,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]; - } - `},rd=(e,t,r)=>{let n="";for(let s=t-1;s>=0;--s)n+=` - k = i32(${e.indicesGet("indices",s)}) - ${jt("uniforms.pads",s,r)}; - if (k < 0) { - k = -k; - } - { - let _2n_1 = 2 * (i32(${jt("uniforms.x_shape",s,t)}) - 1); - k = k % _2n_1; - if(k >= i32(${jt("uniforms.x_shape",s,t)})) { - k = _2n_1 - k; - } - } - offset += k * i32(${jt("uniforms.x_strides",s,t)}); - `;return` - var offset = 0; - var k = 0; - ${n} - value = x[offset]; - `},nd=(e,t,r)=>{let n="";for(let s=t-1;s>=0;--s)n+=` - k = i32(${e.indicesGet("indices",s)}) - ${jt("uniforms.pads",s,r)}; - if (k < 0) { - k = 0; - } - if (k >= i32(${jt("uniforms.x_shape",s,t)})) { - k = i32(${jt("uniforms.x_shape",s,t)}) - 1; - } - offset += k * i32(${jt("uniforms.x_strides",s,t)}); - `;return` - var offset = 0; - var k = 0; - ${n} - value = x[offset]; - `},sd=(e,t,r)=>{let n="";for(let s=t-1;s>=0;--s)n+=` - k = i32(${e.indicesGet("indices",s)}) - ${jt("uniforms.pads",s,r)}; - if (k < 0) { - k += i32(${jt("uniforms.x_shape",s,t)}]); - } - if (k >= i32(${jt("uniforms.x_shape",s,t)})) { - k -= i32(${jt("uniforms.x_shape",s,t)}); - } - offset += k * i32(${jt("uniforms.x_strides",s,t)}); - `;return` - var offset = 0; - var k = 0; - ${n} - value = x[offset]; - `},id=(e,t,r)=>{switch(r.mode){case 0:return td(e,t,r.pads.length);case 1:return rd(e,t,r.pads.length);case 2:return nd(e,t,r.pads.length);case 3:return sd(e,t,r.pads.length);default:throw new Error("Invalid mode")}},ad=(e,t)=>{let r=Se.padShape(e[0].dims.slice(),t.pads),n=e[0].dims,s=Se.size(r),a=[{type:12,data:s},{type:6,data:t.pads}],i=e.length>=3&&e[2].data;t.mode===0&&a.push({type:i?e[2].dataType:1,data:t.value}),a.push(...Ct(e[0].dims,r));let u=["rank"],d=p=>{let g=Ut("output",e[0].dataType,r.length),w=rt("x",e[0].dataType,n.length),l=w.type.value,M=id(g,n.length,t),C=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:t.pads.length}];return t.mode===0&&C.push({name:"constant_value",type:i?l:"f32"}),` - ${p.registerUniforms(C).declareVariables(w,g)} - ${p.mainStart()} - ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - - let indices = ${g.offsetToIndices("global_idx")}; - - var value = ${l}(0); - ${M} - output[global_idx] = value; - }`};return{name:"Pad",shaderCache:{hint:`${t.mode}${i}`,inputDependencies:u},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(Se.size(r)/64)},programUniforms:a}),getShaderSource:d}},od=(e,t)=>{if(e.length>1){let r=e[1].getBigInt64Array(),n=e.length>=3&&e[2].data?e[2].dataType===10?e[2].getUint16Array()[0]:e[2].getFloat32Array()[0]:0,s=e[0].dims.length,a=new Int32Array(2*s).fill(0);if(e.length>=4){let u=e[3].getBigInt64Array();for(let d=0;da[Number(d)]=Number(u));let i=[];return a.forEach(u=>i.push(u)),{mode:t.mode,value:n,pads:i}}else return t},ld=(e,t)=>{ed(e.inputs);let r=od(e.inputs,t);e.compute(ad(e.inputs,r),{inputs:[0]})}}),Rs,Xa,Qa,ud,ir,dd,sn,an,cn,os,Wd,Ya,cd,f,_,T,J,Fe,Oe,_t=j(()=>{At(),Xt(),Ht(),or(),Rs=e=>{if(k.webgpu.validateInputContent&&(!e||e.length!==1))throw new Error("Pool ops requires 1 input.")},Xa=(e,t,r)=>{let n=t.format==="NHWC",s=e.dims.slice();n&&s.splice(1,0,s.pop());let a=Object.hasOwnProperty.call(t,"dilations"),i=t.kernelShape.slice(),u=t.strides.slice(),d=a?t.dilations.slice():[],p=t.pads.slice();Zr.adjustPoolAttributes(r,s,i,u,d,p);let g=Zr.computePoolOutputShape(r,s,u,d,i,p,t.autoPad),w=Object.assign({},t);a?Object.assign(w,{kernelShape:i,strides:u,pads:p,dilations:d,cacheKey:t.cacheKey}):Object.assign(w,{kernelShape:i,strides:u,pads:p,cacheKey:t.cacheKey});let l=g.slice();return l.push(l.splice(1,1)[0]),[w,n?l:g]},Qa=(e,t)=>{let r=t.format==="NHWC",n=Se.size(e),s=Se.size(t.kernelShape),a=[{type:12,data:n},{type:12,data:s}],i=[{name:"outputSize",type:"u32"},{name:"kernelSize",type:"u32"}];if(t.kernelShape.length<=2){let u=t.kernelShape[t.kernelShape.length-1],d=t.strides[t.strides.length-1],p=t.pads[t.pads.length/2-1],g=t.pads[t.pads.length-1],w=!!(p+g);a.push({type:12,data:u},{type:12,data:d},{type:12,data:p},{type:12,data:g}),i.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let l=!1;if(t.kernelShape.length===2){let M=t.kernelShape[t.kernelShape.length-2],C=t.strides[t.strides.length-2],E=t.pads[t.pads.length/2-2],B=t.pads[t.pads.length-2];l=!!(E+B),a.push({type:12,data:M},{type:12,data:C},{type:12,data:E},{type:12,data:B}),i.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[a,i,!0,w,l]}else{if(r)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let u=Se.computeStrides(t.kernelShape);a.push({type:12,data:u},{type:12,data:t.pads},{type:12,data:t.strides}),i.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 d=t.pads.reduce((p,g)=>p+g);return[a,i,!!d,!1,!1]}},ud=(e,t,r,n,s,a,i,u,d,p,g,w)=>{let l=s.format==="NHWC",M=t.type.value,C=Ut("output",t.type.tensor,n);if(s.kernelShape.length<=2){let E="",B="",G="",O=r-(l?2:1);if(g?E=` - for (var i: u32 = 0u; i < uniforms.kw; i++) { - xIndices[${O}] = indices[${O}] * uniforms.sw - uniforms.pwStart + i; - if (xIndices[${O}] < 0 || xIndices[${O}] - >= uniforms.x_shape[${O}]) { - pad++; - continue; - } - let x_val = x[${t.indicesToOffset("xIndices")}]; - ${a} - }`:E=` - for (var i: u32 = 0u; i < uniforms.kw; i++) { - xIndices[${O}] = indices[${O}] * uniforms.sw - uniforms.pwStart + i; - let x_val = x[${t.indicesToOffset("xIndices")}]; - ${a} - }`,s.kernelShape.length===2){let ae=r-(l?3:2);w?B=` - for (var j: u32 = 0u; j < uniforms.kh; j++) { - xIndices[${ae}] = indices[${ae}] * uniforms.sh - uniforms.phStart + j; - if (xIndices[${ae}] < 0 || xIndices[${ae}] >= uniforms.x_shape[${ae}]) { - pad += i32(uniforms.kw); - continue; - } - `:B=` - for (var j: u32 = 0u; j < uniforms.kh; j++) { - xIndices[${ae}] = indices[${ae}] * uniforms.sh - uniforms.phStart + j; - `,G=` - } - `}return` - ${e.registerUniforms(d).declareVariables(t,C)} - - ${e.mainStart()} - ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} - - let indices = ${C.offsetToIndices("global_idx")}; - var xIndices = ${C.offsetToIndices("global_idx")}; - - var value = ${M}(${u}); - var pad = 0; - ${B} - ${E} - ${G} - ${i} - - output[global_idx] = value; - }`}else{if(l)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let E=s.kernelShape.length,B=s.pads.length,G="";return p?G=` - if (xIndices[j] >= uniforms.x_shape[j]) { - pad++; - isPad = true; - break; - } - } - if (!isPad) { - let x_val = x[${t.indicesToOffset("xIndices")}]; - ${a} - }`:G=` - } - let x_val = x[${t.indicesToOffset("xIndices")}]; - ${a} - `,` - ${e.registerUniforms(d).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 = ${M}(${u}); - var pad = 0; - var isPad = false; - - for (var i: u32 = 0u; i < uniforms.kernelSize; i++) { - var offset = i; - for (var j = 0u; j < ${E-1}u; j++) { - offsets[j] = offset / ${jt("uniforms.kernelStrides","j",E)}; - offset -= offsets[j] * ${jt("uniforms.kernelStrides","j",E)}; - } - offsets[${E-1}] = offset; - - isPad = false; - for (var j = ${r-E}u; j < ${r}u; j++) { - xIndices[j] = indices[j] * ${jt("uniforms.strides",`j - ${r-E}u`,E)} - + offsets[j - ${r-E}u] - ${jt("uniforms.pads","j - 2u",B)}; - ${G} - } - ${i} - - output[global_idx] = value; - }`}},ir=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,dd=e=>`${ir(e)};${e.countIncludePad}`,sn=e=>`${ir(e)};${e.storageOrder};${e.dilations}`,an=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}),cn=(e,t,r,n)=>{let[s,a]=Xa(t,n,r),i=rt("x",t.dataType,t.dims.length),u=i.type.value,d="value += x_val;",p="";s.countIncludePad?p+=`value /= ${u}(uniforms.kernelSize);`:p+=`value /= ${u}(i32(uniforms.kernelSize) - pad);`;let[g,w,l,M,C]=Qa(a,s);g.push(...Ct(t.dims,a));let E=["rank"];return{name:e,shaderCache:{hint:`${n.cacheKey};${l};${M};${C}`,inputDependencies:E},getRunData:()=>({outputs:[{dims:a,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(Se.size(a)/64)},programUniforms:g}),getShaderSource:B=>ud(B,i,t.dims.length,a.length,s,d,p,0,w,l,M,C)}},os=e=>{let t=e.count_include_pad!==0,r=an(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:dd(n)}},Wd=(e,t)=>{Rs(e.inputs),e.compute(cn("AveragePool",e.inputs[0],!1,t))},Ya={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},cd=e=>{let t=e.format;return{format:t,...Ya,cacheKey:t}},f=(e,t)=>{Rs(e.inputs),e.compute(cn("GlobalAveragePool",e.inputs[0],!0,t))},_=(e,t,r,n)=>{let[s,a]=Xa(t,n,r),i=` - value = max(x_val, value); - `,u="",d=rt("x",t.dataType,t.dims.length),p=["rank"],[g,w,l,M,C]=Qa(a,s);return g.push(...Ct(t.dims,a)),{name:e,shaderCache:{hint:`${n.cacheKey};${l};${M};${C}`,inputDependencies:p},getRunData:()=>({outputs:[{dims:a,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(Se.size(a)/64)},programUniforms:g}),getShaderSource:E=>ud(E,d,t.dims.length,a.length,s,i,u,t.dataType===10?-65504:-1e5,w,l,M,C)}},T=(e,t)=>{Rs(e.inputs),e.compute(_("MaxPool",e.inputs[0],!1,t))},J=e=>{let t=e.storage_order,r=e.dilations,n=an(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 s={storageOrder:t,dilations:r,...n,cacheKey:""};return{...s,cacheKey:sn(s)}},Fe=e=>{let t=e.format;return{format:t,...Ya,cacheKey:t}},Oe=(e,t)=>{Rs(e.inputs),e.compute(_("GlobalMaxPool",e.inputs[0],!0,t))}}),St,Wt,nr,kr,pr=j(()=>{Xt(),Ht(),Sr(),or(),St=(e,t)=>{if(e.length<2||e.length>3)throw new Error("DequantizeLinear requires 2 or 3 inputs.");if(e.length===3&&e[1].dims===e[2].dims)throw new Error("x-scale and x-zero-point must have the same shape.");if(e.length===3&&e[0].dataType!==e[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(e[0].dataType===6&&e.length>2)throw new Error("In the case of dequantizing int32 there is no zero point.");if(e[1].dims.length!==0&&e[1].dims.length!==1&&e[1].dims.length!==e[0].dims.length)throw new Error("scale input must be a scalar, a 1D tensor, or have the same rank as the input tensor.");if(e.length>2){if(e[0].dataType!==e[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(e[1].dims.length!==e[2].dims.length)throw new Error("scale and zero-point inputs must have the same rank.");if(!e[1].dims.map((r,n)=>r===e[2].dims[n]).reduce((r,n)=>r&&n,!0))throw new Error("scale and zero-point inputs must have the same shape.")}if(t.blockSize>0){if(e[1].dims.length===0||e[1].dims.length===1&&e[1].dims[0]===1)throw new Error("blockSize must be set only for block quantization.");if(!e[1].dims.map((s,a)=>a===t.axis||s===e[0].dims[a]).reduce((s,a)=>s&&a,!0))throw new Error("For block qunatization, scale input shape to match the input shape except for the axis");if(e[1].dims.length!==e[0].dims.length)throw new Error("For block qunatization the scale input rank must be the same as the x rank.");let r=e[0].dims[t.axis],n=e[1].dims[t.axis];if(t.blockSizeMath.ceil(r/(n-1)-1))throw new Error("blockSize must be with in the range [ceil(dI / Si), ceil(dI / (Si - 1) - 1)].")}},Wt=(e,t)=>{let r=Se.normalizeAxis(t.axis,e[0].dims.length),n=e[0].dataType,s=n===3,a=e[0].dims,i=e[1].dataType,u=Se.size(a),d=n===3||n===2,p=d?[Math.ceil(Se.size(e[0].dims)/4)]:e[0].dims,g=e[1].dims,w=e.length>2?e[2]:void 0,l=w?d?[Math.ceil(Se.size(w.dims)/4)]:w.dims:void 0,M=g.length===0||g.length===1&&g[0]===1,C=M===!1&&g.length===1,E=mr(u),B=M&&(!d||E===4),G=B?E:1,O=B&&!d?E:1,ae=rt("input",d?12:n,p.length,O),Z=rt("scale",i,g.length),le=w?rt("zero_point",d?12:n,l.length):void 0,Ge=Ut("output",i,a.length,G),Le=[ae,Z];le&&Le.push(le);let pt=[p,g];w&&pt.push(l);let Dt=[{type:12,data:u/G},{type:12,data:r},{type:12,data:t.blockSize},...Ct(...pt,a)],Vt=lr=>{let fr=[{name:"output_size",type:"u32"},{name:"axis",type:"u32"},{name:"block_size",type:"u32"}];return` - ${lr.registerUniforms(fr).declareVariables(...Le,Ge)} - ${lr.mainStart()} - ${lr.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - let output_indices = ${Ge.offsetToIndices("global_idx")}; - - // Set input x - ${d?` - let input = ${ae.getByOffset("global_idx / 4")}; - let x_vec = ${s?"unpack4xI8(input)":"unpack4xU8(input)"}; - let x_value = ${G===1?"x_vec[global_idx % 4]":"x_vec"};`:`let x_value = ${ae.getByOffset("global_idx")};`}; - - // Set scale input - ${M?`let scale_value= ${Z.getByOffset("0")}`:C?` - let scale_index = ${Ge.indicesGet("output_indices","uniforms.axis")}; - let scale_value= ${Z.getByOffset("scale_index")};`:` - var scale_indices: ${Z.type.indices} = output_indices; - let index = ${Z.indicesGet("scale_indices","uniforms.axis")} / uniforms.block_size; - ${Z.indicesSet("scale_indices","uniforms.axis","index")}; - let scale_value= ${Z.getByIndices("scale_indices")};`}; - - // Set zero-point input - ${le?M?d?` - let zero_point_input = ${le.getByOffset("0")}; - let zero_point_vec = ${s?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; - let zero_point_value= zero_point_vec[0]`:`let zero_point_value = ${le.getByOffset("0")}`:C?d?` - let zero_point_index = ${Ge.indicesGet("output_indices","uniforms.axis")}; - let zero_point_input = ${le.getByOffset("zero_point_index / 4")}; - let zero_point_vec = ${s?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; - let zero_point_value = zero_point_vec[zero_point_index % 4]`:` - let zero_point_index = ${Ge.indicesGet("output_indices","uniforms.axis")}; - let zero_point_value = ${le.getByOffset("zero_point_index")};`:d?` - let zero_point_offset = ${Z.indicesToOffset("scale_indices")}; - let zero_point_input = ${le.getByOffset("zero_point_offset / 4")}; - let zero_point_vec = ${s?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; - let zero_point_value = zero_point_vec[zero_point_offset % 4];`:`let zero_point_value = ${le.getByIndices("scale_indices")};`:`let zero_point_value = ${d?s?"i32":"u32":ae.type.value}(0);`}; - // Compute and write output - ${Ge.setByOffset("global_idx",`${Ge.type.value}(x_value - zero_point_value) * scale_value`)}; - }`};return{name:"DequantizeLinear",shaderCache:{hint:t.cacheKey,inputDependencies:le?["rank","rank","rank"]:["rank","rank"]},getShaderSource:Vt,getRunData:()=>({outputs:[{dims:a,dataType:i}],dispatchGroup:{x:Math.ceil(u/G/64),y:1,z:1},programUniforms:Dt})}},nr=(e,t)=>{St(e.inputs,t),e.compute(Wt(e.inputs,t))},kr=e=>ur({axis:e.axis,blockSize:e.blockSize})}),hr,_r,xr,Fr=j(()=>{At(),Xt(),or(),hr=(e,t,r)=>{let n=e===t,s=et&&r>0;if(n||s||a)throw new Error("Range these inputs' contents are invalid.")},_r=(e,t,r,n)=>{let s=Math.abs(Math.ceil((t-e)/r)),a=[s],i=s,u=[{type:12,data:i},{type:n,data:e},{type:n,data:r},...Ct(a)],d=p=>{let g=Ut("output",n,a.length),w=g.type.value,l=[{name:"outputSize",type:"u32"},{name:"start",type:w},{name:"delta",type:w}];return` - ${p.registerUniforms(l).declareVariables(g)} - ${p.mainStart()} - ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} - output[global_idx] = uniforms.start + ${w}(global_idx) * uniforms.delta; - }`};return{name:"Range",shaderCache:{hint:`${n}`},getShaderSource:d,getRunData:()=>({outputs:[{dims:a,dataType:n}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:u})}},xr=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]),k.webgpu.validateInputContent&&hr(t,r,n),e.compute(_r(t,r,n,e.inputs[0].dataType),{inputs:[]})}}),Tr,gr,rn,on,bn,pn,ln,Mn,Ms,_i,Ja,Gd,Rn,vs,qd,Hd,Kd,pd,ip,Bf=j(()=>{Xt(),Ht(),Sr(),or(),Tr=(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")}},gr=(e,t,r)=>{t.every(s=>s>=0&&s{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((s,a)=>n[s]=e[a]),n},rn=(e,t,r,n,s,a)=>{let[i,u,d]=r>10?[1,2,3]:[-1,e.length>1?1:-1,-1],p=e[0].dims.length;if(i>0&&e.length>i&&e[i].dims.length>0)e[i].getFloat32Array().forEach(g=>a.push(g));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(g=>n.push(g)),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");Tr(n,t),t.axes.length>0&&gr(n,t.axes,p).forEach((g,w)=>n[w]=g)}if(d>0&&e.length>d&&(e[d].getBigInt64Array().forEach(g=>s.push(Number(g))),s.length!==p||r>=18&&s.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(s.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 s<"u"&&n.length>0&&s.length>p)throw new Error("Resize requires only of scales or sizes to be specified")},on=(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`)}})()+"}",bn=(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`)}})()+"}",pn=(e,t,r)=>{let n=new Array(r).fill(0).concat(new Array(r).fill(1)),s=e.length===0?n:e.slice();return t.length>0?(t.forEach((a,i)=>{n[a]=s[i],n[i+r]=s[t.length+i]}),n):s},ln=(e,t,r,n)=>{let s=[];if(r.length>0)if(n.length>0){if(e.forEach(a=>s.push(a)),Math.max(...n)>e.length)throw new Error("axes is out of bound");n.forEach((a,i)=>s[a]=r[i])}else r.forEach(a=>s.push(a));else{if(t.length===0)throw new Error("Resize requires either scales or sizes.");s=e.map((a,i)=>Math.round(a*t[i]))}return s},Mn=(e,t,r)=>{let n=(()=>{switch(r.keepAspectRatioPolicy){case"not_larger":return r.axes.length>0?Math.min(...r.axes.map(a=>t[a]),Number.MAX_VALUE):Math.min(...t,Number.MAX_VALUE);case"not_smaller":return r.axes.length>0?Math.max(...r.axes.map(a=>t[a]),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 s=e.slice();return r.axes.length>0?(r.axes.forEach(a=>t[a]=n),r.axes.forEach(a=>s[a]=Math.round(e[a]*t[a]))):(t.fill(n,0,t.length),s.forEach((a,i)=>s[i]=Math.round(a*t[i]))),s},Ms=(e,t,r,n,s)=>` - 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 = ${jt("uniforms.scales","i",n)}; - var roi_low = ${jt("uniforms.roi","i",s)}; - var roi_hi = ${jt("uniforms.roi",`i + ${t.length}`,s)}; - if (scale == 1.0) { - original_indices[i] = ${e.type.value}(output_index); - } else { - var input_shape_i = ${jt("uniforms.input_shape","i",t.length)}; - var output_shape_i = ${jt("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; - }`,_i=(e,t,r,n,s,a,i)=>` - 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 = ${jt("uniforms.scales","i",s)}; - if (scale == 1.0) { - input_index = output_index; - } else { - var roi_low = ${jt("uniforms.roi","i",a)}; - var roi_hi = ${jt("uniforms.roi",`i + ${r.length}`,a)}; - var input_shape_i = ${jt("uniforms.input_shape","i",r.length)}; - var output_shape_i = ${jt("uniforms.output_shape","i",n.length)}; - var original_idx = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, - input_shape_i, roi_low, roi_hi); - if (!${i} || (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; - }`,Ja=(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 >= ${jt("uniforms.input_shape","i",t.length)}) { - return false; - } - } - return true; - }`,Gd=(e,t,r,n)=>e.rank>n?` - ${e.indicesSet("input_indices",t,"channel")}; - ${e.indicesSet("input_indices",r,"batch")}; -`:"",Rn=(e,t,r,n,s)=>{let[a,i,u,d]=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",i,`max(0, min(row, ${r[i]} - 1))`)}; - ${e.indicesSet("input_indices",u,`max(0, min(col, ${r[u]} - 1))`)}; - ${Gd(e,d,a,2)} - return ${e.getByIndices("input_indices")}; - } - - fn bilinearInterpolation(output_indices: ${t.type.indices}) -> ${p} { - var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); - var row:${p} = originalIndices[${i}]; - var col:${p} = originalIndices[${u}]; - ${n?`if (row < 0 || row > (${r[i]} - 1) || col < 0 || col > (${r[u]} - 1)) { - return ${s}; - }`:""}; - row = max(0, min(row, ${r[i]} - 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[${d}])`:"0"}; - var batch: u32 = ${r.length>2?`u32(originalIndices[${a}])`:"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); - }`},vs=(e,t,r,n,s,a,i,u,d,p)=>{let g=r.length===2,[w,l]=g?[0,1]:[2,3],M=e.type.value,C=E=>{let B=E===w?"row":"col";return` - fn ${B}CubicInterpolation(input_indices: ${e.type.indices}, output_indices: ${t.type.indices}) -> ${M} { - var output_index = ${t.indicesGet("output_indices",E)}; - var originalIdx: ${M} = getOriginalCoordinateFromResizedCoordinate(output_index, ${s[E]}, - ${n[E]}, ${r[E]}, ${a[E]}, ${a[E]} + ${r.length}); - var fractOriginalIdx: ${M} = originalIdx - floor(originalIdx); - var coefs = getCubicInterpolationCoefs(fractOriginalIdx); - - if (${u} && (originalIdx < 0 || originalIdx > (${r[E]} - 1))) { - return ${d}; - } - var data: array<${M}, 4> = array<${M}, 4>(0.0, 0.0, 0.0, 0.0); - for (var i: i32 = -1; i < 3; i++) { - var ${B}: ${M} = originalIdx + ${M}(i); - if (${B} < 0 || ${B} >= ${r[E]}) { - ${p?`coefs[i + 1] = 0.0; - continue;`:u?`return ${d};`:`${B} = max(0, min(${B}, ${r[E]} - 1));`}; - } - var input_indices_copy: ${e.type.indices} = input_indices; - ${e.indicesSet("input_indices_copy",E,`u32(${B})`)}; - data[i + 1] = ${E===w?e.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"}; - } - return cubicInterpolation1D(data, coefs); - }`};return` - ${C(w)}; - ${C(l)}; - fn getCubicInterpolationCoefs(s: ${M}) -> array<${M}, 4> { - var absS = abs(s); - var coeffs: array<${M}, 4> = array<${M}, 4>(0.0, 0.0, 0.0, 0.0); - var oneMinusAbsS: ${M} = 1.0 - absS; - var twoMinusAbsS: ${M} = 2.0 - absS; - var onePlusAbsS: ${M} = 1.0 + absS; - coeffs[0] = ((${i} * onePlusAbsS - 5 * ${i}) * onePlusAbsS + 8 * ${i}) * onePlusAbsS - 4 * ${i}; - coeffs[1] = ((${i} + 2) * absS - (${i} + 3)) * absS * absS + 1; - coeffs[2] = ((${i} + 2) * oneMinusAbsS - (${i} + 3)) * oneMinusAbsS * oneMinusAbsS + 1; - coeffs[3] = ((${i} * twoMinusAbsS - 5 * ${i}) * twoMinusAbsS + 8 * ${i}) * twoMinusAbsS - 4 * ${i}; - return coeffs; - } - - fn cubicInterpolation1D(x: array<${M}, 4>, coefs: array<${M}, 4>) -> ${M} { - var coefsSum: ${M} = 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}) -> ${M} { - var input_indices: ${e.type.indices} = output_indices; - return colCubicInterpolation(input_indices, output_indices); - } - `},qd=(e,t,r,n,s)=>{let[a,i,u,d,p]=r.length===3?[-1,0,1,2,-1]:[0,2,3,4,1],g=e.type.value;return` - fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${g} { - var input_indices: ${e.type.indices}; - ${e.indicesSet("input_indices",i,`max(0, min(depth, ${r[i]} - 1))`)}; - ${e.indicesSet("input_indices",u,`max(0, min(height, ${r[u]} - 1))`)}; - ${e.indicesSet("input_indices",d,`max(0, min(width, ${r[d]} - 1))`)}; - ${Gd(e,p,a,3)} - return ${e.getByIndices("input_indices")}; - } - - fn trilinearInterpolation(output_indices: ${t.type.indices}) -> ${g} { - var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); - var depth:${g} = originalIndices[${i}]; - var height:${g} = originalIndices[${u}]; - var width:${g} = originalIndices[${d}]; - ${n?`if (depth < 0 || depth > (${r[i]} - 1) || height < 0 || height > (${r[u]} - 1) || width < 0 || (width > ${r[d]} - 1)) { - return ${s}; - }`:""}; - - depth = max(0, min(depth, ${r[i]} - 1)); - height = max(0, min(height, ${r[u]} - 1)); - width = max(0, min(width, ${r[d]} - 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[${a}])`:"0"}; - - var x111: ${g} = getInputValue(batch, channel, depth1, height1, width1); - var x112: ${g} = getInputValue(batch, channel, depth1, height1, width2); - var x121: ${g} = getInputValue(batch, channel, depth1, height2, width1); - var x122: ${g} = getInputValue(batch, channel, depth1, height2, width2); - var x211: ${g} = getInputValue(batch, channel, depth2, height1, width1); - var x212: ${g} = getInputValue(batch, channel, depth2, height1, width2); - var x221: ${g} = getInputValue(batch, channel, depth2, height2, width1); - var x222: ${g} = getInputValue(batch, channel, depth2, height2, width2); - var dx1: ${g} = abs(depth - ${g}(depth1)); - var dx2: ${g} = abs(${g}(depth2) - depth); - var dy1: ${g} = abs(height - ${g}(height1)); - var dy2: ${g} = abs(${g}(height2) - height); - var dz1: ${g} = abs(width - ${g}(width1)); - var dz2: ${g} = abs(${g}(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); - }`},Hd=(e,t,r,n,s,a)=>{let i=e.dims,u=pn(a,t.axes,i.length),d=ln(i,n,s,t.axes),p=n.slice();n.length===0&&(p=i.map((O,ae)=>O===0?1:d[ae]/O),t.keepAspectRatioPolicy!=="stretch"&&(d=Mn(i,p,t)));let g=Ut("output",e.dataType,d.length),w=rt("input",e.dataType,i.length),l=Se.size(d),M=i.length===d.length&&i.every((O,ae)=>O===d[ae]),C=t.coordinateTransformMode==="tf_crop_and_resize",E=t.extrapolationValue,B=w.type.value,G=O=>` - ${M?"":` - ${on(t.coordinateTransformMode,B)}; - ${(()=>{switch(t.mode){case"nearest":return` - ${Ja(w,i)}; - ${bn(t.nearestMode,r,B)}; - ${_i(w,g,i,d,p.length,u.length,C)}; - `;case"linear":return` - ${Ms(g,i,d,p.length,u.length)}; - ${(()=>{if(i.length===2||i.length===4)return`${Rn(w,g,i,C,E)}`;if(i.length===3||i.length===5)return`${qd(w,g,i,C,E)}`;throw Error("Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.")})()}; - `;case"cubic":return` - ${(()=>{if(i.length===2||i.length===4)return`${vs(w,g,i,d,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")}})()}; - `} - ${O.registerUniform("output_size","u32").registerUniform("scales","f32",p.length).registerUniform("roi","f32",u.length).declareVariables(w,g)} - ${O.mainStart()} - ${O.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - ${M?"output[global_idx] = input[global_idx];":` - let output_indices = ${g.offsetToIndices("global_idx")}; - var input_indices: ${w.type.indices}; - ${(()=>{switch(t.mode){case"nearest":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices); - if (checkInputIndices(input_indices)) { - output[global_idx] = ${w.getByIndices("input_indices")}; - } else { - output[global_idx] = ${t.extrapolationValue}; - }`;case"linear":return`output[global_idx] = ${i.length===2||i.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:""}|${s.length>0?s:""}|${u.length>0?u:""}|${M}|${i}`,inputDependencies:["rank"]},getShaderSource:G,getRunData:()=>({outputs:[{dims:d,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:[{type:12,data:l},{type:1,data:p},{type:1,data:u},...Ct(i,d)]})}},Kd=e=>{let t=e.customDataBuffer;return new Uint32Array(t,t.byteOffset,1)[0]},pd=(e,t)=>{let r=[],n=[],s=[],a=Kd(e);if(t.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");rn(e.inputs,t,a,r,n,s),e.compute(Hd(e.inputs[0],t,a,r,n,s),{inputs:[0]})},ip=e=>{let t=e.antialias,r=e.axes,n=e.coordinateTransformMode,s=e.cubicCoeffA,a=e.excludeOutside!==0,i=e.extrapolationValue,u=e.keepAspectRatioPolicy,d=e.mode,p=e.nearestMode===""?"simple":e.nearestMode;return ur({antialias:t,axes:r,coordinateTransformMode:n,cubicCoeffA:s,excludeOutside:a,extrapolationValue:i,keepAspectRatioPolicy:u,mode:d,nearestMode:p})}}),ap,op,lp,Rf=j(()=>{Xt(),Ht(),Sr(),or(),ap=(e,t)=>{let[r,n,s,a]=e,{numHeads:i,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(!Se.areEqual(n.dims,[])&&!Se.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(s.dims.length!==2)throw new Error(`Input 'cos_cache' is expected to have 2 dimensions, got ${s.dims.length}`);if(a.dims.length!==2)throw new Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${a.dims.length}`);if(!Se.areEqual(s.dims,a.dims))throw new Error("Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape");if(u>0&&i===0)throw new Error("num_heads must be provided if rotary_embedding_dim is specified");let d=r.dims[0],p=r.dims[r.dims.length-2],g=s.dims[0],w=Se.sizeFromDimension(r.dims,1)/p,l=u===0?s.dims[1]*2:w/i;if(u>l)throw new Error("rotary_embedding_dim must be less than or equal to head_size");if(n.dims.length===2){if(d!==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(l/2!==s.dims[1]&&u/2!==s.dims[1])throw new Error(`Input 'cos_cache' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${s.dims[1]}`);if(p>g)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported")},op=(e,t)=>{let{interleaved:r,numHeads:n,rotaryEmbeddingDim:s,scale:a}=t,i=e[0].dims[0],u=Se.sizeFromDimension(e[0].dims,1),d=e[0].dims[e[0].dims.length-2],p=u/d,g=e[2].dims[1],w=s===0?g*2:p/n,l=new Array(i,d,p/w,w-g),M=Se.computeStrides(l),C=[{type:1,data:a},{type:12,data:l},{type:12,data:M},...e[0].dims.length===3?new Array({type:12,data:[u,p,w,1]}):[],...e[0].dims.length===4?new Array({type:12,data:[u,w,d*w,1]}):[],...Ct(e[0].dims,e[1].dims,e[2].dims,e[3].dims,e[0].dims)],E=B=>{let G=rt("input",e[0].dataType,e[0].dims.length),O=rt("position_ids",e[1].dataType,e[1].dims.length),ae=rt("cos_cache",e[2].dataType,e[2].dims.length),Z=rt("sin_cache",e[3].dataType,e[3].dims.length),le=Ut("output",e[0].dataType,e[0].dims.length);return B.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:l.length},{name:"global_strides",type:"u32",length:M.length},{name:"input_output_strides",type:"u32",length:M.length}]),` - ${B.declareVariables(G,O,ae,Z,le)} - - ${B.mainStart(en)} - let half_rotary_emb_dim = uniforms.${ae.name}_shape[1]; - let bsnh = global_idx / uniforms.global_strides % uniforms.global_shape; - let size = uniforms.global_shape[0] * uniforms.global_strides[0]; - ${B.guardAgainstOutOfBoundsWorkgroupSizes("size")} - - if (bsnh[3] < half_rotary_emb_dim) { - let position_ids_idx = - ${O.broadcastedIndicesToOffset("bsnh.xy",Ut("",O.type.tensor,2))}; - let position_id = - u32(${O.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 = ${G.getByOffset("i")} * ${ae.get("position_id","bsnh[3]")} - - ${G.getByOffset("j")} * ${Z.get("position_id","bsnh[3]")}; - ${le.setByOffset("i","re")} - let im = ${G.getByOffset("i")} * ${Z.get("position_id","bsnh[3]")} + - ${G.getByOffset("j")} * ${ae.get("position_id","bsnh[3]")}; - ${le.setByOffset("j","im")} - } else { - let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim; - ${le.setByOffset("k",G.getByOffset("k"))} - } - }`};return{name:"RotaryEmbedding",shaderCache:{hint:ur({interleaved:r}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:E,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(Se.size(l)/en)},programUniforms:C})}},lp=(e,t)=>{ap(e.inputs,t),e.compute(op(e.inputs,t))}}),up,dp,cp,Nf=j(()=>{Xt(),Ht(),or(),up=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 s=t.dims[t.dims.length-1],a=t.dims[t.dims.length-2];if(r.dims[r.dims.length-1]!==s)throw new Error("Skip must have the same hidden size as input");if(r.dims[r.dims.length-2]!==a)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]!==s)throw new Error("Gamma must have the same hidden size as input");if(e.length>3){let i=e[3];if(i.dims.length!==1)throw new Error("Beta must be 1D");if(i.dims[i.dims.length-1]!==s)throw new Error("Beta must have the same hidden size as input")}if(e.length>4){let i=e[4];if(i.dims.length!==1)throw new Error("Bias must be 1D");if(i.dims[i.dims.length-1]!==s)throw new Error("Bias must have the same hidden size as input")}},dp=(e,t,r,n)=>{let s=t.simplified,a=e[0].dims,i=Se.size(a),u=a,d=i,p=a.slice(-1)[0],g=n?a.slice(0,-1).concat(1):[],w=!s&&e.length>3,l=e.length>4,M=n&&r>1,C=n&&r>2,E=r>3,B=64,G=mr(p),O=[{type:12,data:d},{type:12,data:G},{type:12,data:p},{type:1,data:t.epsilon}],ae=le=>{let Ge=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],Le=[rt("x",e[0].dataType,e[0].dims,G),rt("skip",e[1].dataType,e[1].dims,G),rt("gamma",e[2].dataType,e[2].dims,G)];w&&Le.push(rt("beta",e[3].dataType,e[3].dims,G)),l&&Le.push(rt("bias",e[4].dataType,e[4].dims,G)),Le.push(Ut("output",e[0].dataType,u,G)),M&&Le.push(Ut("mean_output",1,g)),C&&Le.push(Ut("inv_std_output",1,g)),E&&Le.push(Ut("input_skip_bias_sum",e[0].dataType,u,G));let pt=yr(e[0].dataType),Dt=yr(1,G);return` - - ${le.registerUniforms(Ge).declareVariables(...Le)} - var sum_shared : array<${Dt}, ${B}>; - var sum_squared_shared : array<${Dt}, ${B}>; - - ${le.mainStart([B,1,1])} - let ix = local_id.x; - let iy = global_id.x / ${B}; - - let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components; - var stride = hidden_size_vectorized / ${B}; - let offset = ix * stride + iy * hidden_size_vectorized; - let offset1d = stride * ix; - if (ix == ${B-1}) { - stride = hidden_size_vectorized - stride * ix; - } - for (var i: u32 = 0; i < stride; i++) { - let skip_value = skip[offset + i]; - let bias_value = ${l?"bias[offset1d + i]":pt+"(0.0)"}; - let input_value = x[offset + i]; - let value = input_value + skip_value + bias_value; - ${E?"input_skip_bias_sum[offset + i] = value;":""} - output[offset + i] = value; - let f32_value = ${Kn(pt,G,"value")}; - sum_shared[ix] += f32_value; - sum_squared_shared[ix] += f32_value * f32_value; - } - workgroupBarrier(); - - var reduce_size : u32 = ${B}; - for (var curr_size = reduce_size >> 1; curr_size > 0; curr_size = reduce_size >> 1) { - reduce_size = curr_size + (reduce_size & 1); - if (ix < curr_size) { - sum_shared[ix] += sum_shared[ix + reduce_size]; - sum_squared_shared[ix] += sum_squared_shared[ix + reduce_size]; - } - workgroupBarrier(); - } - - let sum = sum_shared[0]; - let square_sum = sum_squared_shared[0]; - let mean = ${Xn("sum",G)} / f32(uniforms.hidden_size); - let inv_std_dev = inverseSqrt(${Xn("square_sum",G)} / f32(uniforms.hidden_size) ${s?"":"- mean * mean"} + uniforms.epsilon); - ${M?"mean_output[global_idx] = mean;":""} - ${C?"inv_std_output[global_idx] = inv_std_dev;":""} - - for (var i: u32 = 0; i < stride; i++) { - output[offset + i] = (output[offset + i] ${s?"":`- ${pt}(mean)`}) * - ${pt}(inv_std_dev) * gamma[offset1d + i] - ${w?"+ beta[offset1d + i]":""}; - } - }`},Z=[{dims:u,dataType:e[0].dataType}];return r>1&&Z.push({dims:g,dataType:1}),r>2&&Z.push({dims:g,dataType:1}),r>3&&Z.push({dims:a,dataType:e[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${G};${M};${C};${E}`,inputDependencies:e.map((le,Ge)=>"type")},getShaderSource:ae,getRunData:()=>({outputs:Z,dispatchGroup:{x:Math.ceil(d/p)},programUniforms:O})}},cp=(e,t)=>{up(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(dp(e.inputs,t,e.outputCount,!1),{outputs:r})}}),pp,hd,hp,bc,fp,mp,_p,gp,jf=j(()=>{Xt(),Ht(),Sr(),or(),pp=(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`)})},hd=(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},hp=(e,t)=>{if(e.length>1){let r=hd(e,1),n=hd(e,2),s=hd(e,3);return s.length===0&&(s=[...Array(e[0].dims.length).keys()]),ur({starts:r,ends:n,axes:s})}else return t},bc=(e,t,r,n,s)=>{let a=e;return e<0&&(a+=r[n[t]]),s[t]<0?Math.max(0,Math.min(a,r[n[t]]-1)):Math.max(0,Math.min(a,r[n[t]]))},fp=(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 = ${jt("uniforms.input_shape","i",r.length)}; - let steps_i = ${jt("uniforms.steps","i",r.length)}; - let signs_i = ${jt("uniforms.signs","i",r.length)}; - let starts_i = ${jt("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; - }`,mp=(e,t)=>{let r=e[0].dims,n=Se.size(r),s=t.axes.length>0?Se.normalizeAxes(t.axes,r.length):[...Array(r.length).keys()],a=hd(e,4);a.forEach(G=>G!==0||(()=>{throw new Error("step cannot be 0")})),a.length===0&&(a=Array(s.length).fill(1));let i=t.starts.map((G,O)=>bc(G,O,r,s,a)),u=t.ends.map((G,O)=>bc(G,O,r,s,a));if(s.length!==i.length||s.length!==u.length)throw new Error("start, ends and axes should have the same number of elements");if(s.length!==r.length)for(let G=0;GMath.sign(G));a.forEach((G,O,ae)=>{if(G<0){let Z=(u[O]-i[O])/G,le=i[O],Ge=le+Z*a[O];i[O]=Ge,u[O]=le,ae[O]=-G}});let p=r.slice(0);s.forEach((G,O)=>{p[G]=Math.ceil((u[G]-i[G])/a[G])});let g={dims:p,dataType:e[0].dataType},w=Ut("output",e[0].dataType,p.length),l=rt("input",e[0].dataType,e[0].dims.length),M=Se.size(p),C=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:i.length},{name:"signs",type:"i32",length:d.length},{name:"steps",type:"u32",length:a.length}],E=[{type:12,data:M},{type:12,data:i},{type:6,data:d},{type:12,data:a},...Ct(e[0].dims,p)],B=G=>` - ${G.registerUniforms(C).declareVariables(l,w)} - ${fp(l,w,r)} - ${G.mainStart()} - ${G.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} - let output_indices = ${w.offsetToIndices("global_idx")}; - let input_indices = calculateInputIndices(output_indices); - ${w.setByOffset("global_idx",l.getByIndices("input_indices"))} - }`;return{name:"Slice",shaderCache:{hint:`${d.length}_${i.length}_${a.length}`,inputDependencies:["rank"]},getShaderSource:B,getRunData:()=>({outputs:[g],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:E})}},_p=(e,t)=>{pp(e.inputs,t);let r=hp(e.inputs,t);e.compute(mp(e.inputs,r),{inputs:[0]})},gp=e=>{let t=e.starts,r=e.ends,n=e.axes;return ur({starts:t,ends:r,axes:n})}}),wp,yp,bp,Mp,Vf=j(()=>{Xt(),Ht(),Sr(),or(),wp=e=>{if(!e||e.length!==1)throw new Error("Softmax op requires 1 input.")},yp=(e,t)=>{let r=e.dims,n=Se.size(r),s=64,a=t.axis;if(a<0&&(a=r.length+a),aG===4?`max(max(${B}.x, ${B}.y), max(${B}.z, ${B}.w))`:G===2?`max(${B}.x, ${B}.y)`:G===3?`max(max(${B}.x, ${B}.y), ${B}.z)`:B,w=rt("x",e.dataType,e.dims,d),l=Ut("result",e.dataType,e.dims,d),M=w.type.value,C=yr(e.dataType)==="f32"?`var threadMax = ${M}(-3.402823e+38f);`:`var threadMax = ${M}(-65504.0h);`,E=B=>` - var rowMaxShared : ${M}; - var rowSumShared : ${M}; - var threadShared : array<${M}, ${s}>; - - fn getValue(row: i32, col: i32, row_stride: i32) -> ${M} { - let index = row * row_stride + col; - return x[index]; - } - - fn setValue(row: i32, col: i32, row_stride: i32, value: ${M}) { - let index = row * row_stride + col; - result[index] = value; - } - ${B.registerUniform("packedCols","i32").declareVariables(w,l)} - ${B.mainStart()} - let gindex = i32(global_idx); - let lindex = i32(local_idx); - const wg = ${s}; - 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 = ${M}(${g("threadShared[0]",d)}); - } - workgroupBarrier(); - - // find the rows sum - var threadSum = ${M}(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 = ${M}(${Xn("threadShared[0]",d)}); - } - 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:`${d}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:r,dataType:e.dataType}],dispatchGroup:{x:u},programUniforms:[{type:6,data:p}]}),getShaderSource:E}},bp=(e,t)=>{wp(e.inputs),e.compute(yp(e.inputs[0],t))},Mp=e=>ur({axis:e.axis})}),vp,xp,Tp,Cp,Ep,$p,Sp,Uf=j(()=>{Xt(),Ht(),Sr(),or(),vp=e=>{if(!e||e.length<1)throw new Error("too few inputs")},xp=(e,t)=>{let r=[],n=t.numOutputs;return e[1].dims[0]>0&&(e[1].getBigInt64Array().forEach(s=>r.push(Number(s))),n=r.length),ur({numOutputs:n,axis:t.axis,splitSizes:r})},Tp=e=>` -fn calculateOutputIndex(index: u32) -> u32 { - for (var i: u32 = 0u; i < ${e}u; i += 1u ) { - if (index < ${jt("uniforms.size_in_split_axis","i",e)}) { - return i; - } - } - return ${e}u; -}`,Cp=e=>{let t=e.length,r=[];for(let n=0;n{let r=e[0].dims,n=Se.size(r),s=e[0].dataType,a=Se.normalizeAxis(t.axis,r.length),i=new Array(t.numOutputs),u=rt("input",s,r.length),d=new Array(t.numOutputs),p=[],g=[],w=0,l=[{type:12,data:n}];for(let C=0;C` - ${C.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",d.length).declareVariables(u,...i)} - ${Tp(d.length)} - ${Cp(i)} - - ${C.mainStart()} - ${C.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")} - - var indices = ${u.offsetToIndices("global_idx")}; - var index = ${u.indicesGet("indices",a)}; - let output_number = calculateOutputIndex(index); - if (output_number != 0) { - index -= ${jt("uniforms.size_in_split_axis","output_number - 1u",d.length)}; - ${u.indicesSet("indices",a,"index")}; - } - writeBufferData(output_number, indices, global_idx); - }`;return{name:"Split",shaderCache:{hint:t.cacheKey,inputDependencies:["rank"]},getShaderSource:M,getRunData:()=>({outputs:p,dispatchGroup:{x:Math.ceil(n/64)},programUniforms:l})}},$p=(e,t)=>{vp(e.inputs);let r=e.inputs.length===1?t:xp(e.inputs,t);e.compute(Ep(e.inputs,r),{inputs:[0]})},Sp=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 ur({axis:t,numOutputs:n,splitSizes:r})}}),kp,Pp,Ap,Wf=j(()=>{Xt(),Ht(),or(),kp=(e,t,r,n,s)=>{let a=Ut("output_data",s,r.length,4),i=rt("a_data",t[1].dataType,t[1].dims.length,4),u=rt("b_data",t[2].dataType,t[2].dims.length,4),d=rt("c_data",t[0].dataType,t[0].dims.length,4),p,g=(w,l,M)=>`select(${l}, ${w}, ${M})`;if(!n)p=a.setByOffset("global_idx",g(i.getByOffset("global_idx"),u.getByOffset("global_idx"),d.getByOffset("global_idx")));else{let w=(l,M,C="")=>{let E=`a_data[index_a${M}][component_a${M}]`,B=`b_data[index_b${M}][component_b${M}]`,G=`bool(c_data[index_c${M}] & (0xffu << (component_c${M} * 8)))`;return` - let output_indices${M} = ${a.offsetToIndices(`global_idx * 4u + ${M}u`)}; - let offset_a${M} = ${i.broadcastedIndicesToOffset(`output_indices${M}`,a)}; - let offset_b${M} = ${u.broadcastedIndicesToOffset(`output_indices${M}`,a)}; - let offset_c${M} = ${d.broadcastedIndicesToOffset(`output_indices${M}`,a)}; - let index_a${M} = offset_a${M} / 4u; - let index_b${M} = offset_b${M} / 4u; - let index_c${M} = offset_c${M} / 4u; - let component_a${M} = offset_a${M} % 4u; - let component_b${M} = offset_b${M} % 4u; - let component_c${M} = offset_c${M} % 4u; - ${l}[${M}] = ${C}(${g(E,B,G)}); - `};s===9?p=` - var data = vec4(0); - ${w("data",0,"u32")} - ${w("data",1,"u32")} - ${w("data",2,"u32")} - ${w("data",3,"u32")} - output_data[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:p=` - ${w("output_data[global_idx]",0)} - ${w("output_data[global_idx]",1)} - ${w("output_data[global_idx]",2)} - ${w("output_data[global_idx]",3)} - `}return` - ${e.registerUniform("vec_size","u32").declareVariables(d,i,u,a)} - ${e.mainStart()} - ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} - ${p} - }`},Pp=e=>{let t=e[1].dims,r=e[2].dims,n=e[0].dims,s=e[1].dataType,a=!(Se.areEqual(t,r)&&Se.areEqual(r,n)),i=t,u=Se.size(t);if(a){let p=wn.calcShape(wn.calcShape(t,r,!1),n,!1);if(!p)throw new Error("Can't perform where op on the given tensors");i=p,u=Se.size(i)}let d=Math.ceil(u/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:p=>kp(p,e,i,a,s),getRunData:()=>({outputs:[{dims:i,dataType:s}],dispatchGroup:{x:Math.ceil(u/64/4)},programUniforms:[{type:12,data:d},...Ct(n,t,r,i)]})}},Ap=e=>{e.compute(Pp(e.inputs))}}),Ip,Gf=j(()=>{Md(),Ki(),vd(),xd(),Td(),Pl(),Cd(),Sd(),Pd(),$a(),ka(),wc(),Id(),Fd(),zd(),yc(),Ld(),Au(),Uu(),Nd(),jd(),Xl(),Vd(),Ou(),Ud(),_t(),pr(),Fr(),Js(),Bf(),Rf(),Nf(),jf(),Vf(),Uf(),Ru(),is(),ti(),Wf(),Ip=new Map([["Abs",[Yi]],["Acos",[Ko]],["Acosh",[Xo]],["Add",[vl]],["ArgMax",[Ui,Wi]],["ArgMin",[Bo,Wi]],["Asin",[Qo]],["Asinh",[Yo]],["Atan",[Ji]],["Atanh",[Jo]],["Attention",[Hi]],["AveragePool",[Wd,os]],["BatchNormalization",[Wo]],["BiasAdd",[qo]],["BiasSplitGelu",[pa]],["Cast",[Zi,Zo]],["Ceil",[ea]],["Clip",[tl]],["Concat",[ma,Ol]],["Conv",[as,Yl]],["ConvTranspose",[uu,au]],["Cos",[rl]],["Cosh",[nl]],["CumSum",[du,cu]],["DepthToSpace",[mu,Sa]],["DequantizeLinear",[nr,kr]],["Div",[xl]],["Einsum",[Oa,Ad]],["Elu",[sl,ys]],["Equal",[Tl]],["Erf",[ta]],["Exp",[il]],["Expand",[La]],["FastGelu",[Ba]],["Floor",[al]],["FusedConv",[as,Yl]],["Gather",[Tu,xu]],["GatherElements",[Su,$u]],["GatherBlockQuantized",[Od,Dd]],["Gelu",[ei]],["Gemm",[Pu,ku]],["GlobalAveragePool",[f,cd]],["GlobalMaxPool",[Oe,Fe]],["Greater",[$l]],["GreaterOrEqual",[Sl]],["GroupQueryAttention",[Rd,ju]],["HardSigmoid",[cl,dl]],["InstanceNormalization",[qu]],["LayerNormalization",[Xu]],["LeakyRelu",[ol,ys]],["Less",[fa]],["LessOrEqual",[kl]],["Log",[_l]],["MatMul",[Kl]],["MatMulNBits",[Ju,Zu]],["MaxPool",[T,J]],["Mul",[ri]],["MultiHeadAttention",[zu,Iu]],["Neg",[ra]],["Not",[ll]],["Pad",[ld]],["Pow",[Cl]],["QuickGelu",[wl,ys]],["Range",[xr]],["Reciprocal",[na]],["ReduceMin",[zo]],["ReduceMean",[Ao]],["ReduceMax",[Ni]],["ReduceSum",[ji]],["ReduceProd",[Oo]],["ReduceL1",[Ri]],["ReduceL2",[Io]],["ReduceLogSum",[Lo]],["ReduceLogSumExp",[Fo]],["ReduceSumSquare",[Do]],["Relu",[ul]],["Resize",[pd,ip]],["RotaryEmbedding",[lp]],["Sigmoid",[sa]],["Sin",[pl]],["Sinh",[ia]],["Slice",[_p,gp]],["SkipLayerNormalization",[cp]],["Split",[$p,Sp]],["Sqrt",[hl]],["Softmax",[bp,Mp]],["Sub",[El]],["Tan",[fl]],["Tanh",[oa]],["ThresholdedRelu",[ml,ys]],["Tile",[Bu]],["Transpose",[$i,oo]],["Where",[Ap]]])}),Fp,qf=j(()=>{At(),m(),or(),Fp=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,s){Ue(e.programInfo.name);let a=this.backend.device,i=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}});s&&u.push({binding:u.length,resource:s});let d=a.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:d,dispatchGroup:n};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(p)}i.setPipeline(e.computePipeline),i.setBindGroup(0,d),i.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(),je(e.programInfo.name)}dispose(){}build(e,t){Ue(e.name);let r=this.backend.device,n=[];r.features.has("shader-f16")&&n.push("enable f16;");let s=io(t,this.backend.device.limits),a=e.getShaderSource(s),i=`${n.join(` -`)} -${s.additionalImplementations} -${a}`,u=r.createShaderModule({code:i,label:e.name});ue("verbose",()=>`[WebGPU] ${e.name} shader code: ${i}`);let d=r.createComputePipeline({compute:{module:u,entryPoint:"main"},layout:"auto",label:e.name});return je(e.name),{programInfo:e,computePipeline:d,uniformVariablesInfo:s.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,s=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(t<=s&&r<=s&&n<=s)return[t,r,n];let a=t*r*n,i=Math.ceil(Math.sqrt(a));if(i>s){if(i=Math.ceil(Math.cbrt(a)),i>s)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[i,i,i]}else return[i,i,1]}}}),zp,Op,Dp,Lp,Hf=j(()=>{At(),Xt(),m(),H(),Dr(),Gf(),qf(),zp=(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 s,a;let n=e.name;return(s=e.shaderCache)!=null&&s.hint&&(n+="["+e.shaderCache.hint+"]"),n+=":"+r+`:${zp(t,((a=e.shaderCache)==null?void 0:a.inputDependencies)??new Array(t.length).fill("dims"))}`,n},Dp=class{constructor(e){e&&(this.architecture=e.architecture,this.vendor=e.vendor)}isArchitecture(e){return this.architecture===e}isVendor(e){return this.vendor===e}},Lp=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 Dp(t.info||await t.requestAdapterInfo()),this.gpuDataManager=ar(this),this.programManager=new Fp(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,ws(e.logLevel,!!e.debug),this.device.onuncapturederror=s=>{s.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${s.error.message}`)},Object.defineProperty(this.env.webgpu,"device",{value:this.device,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;Ue(),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 s=0;s"u"&&(this.queryTimeBase=M);let E=Number(M-this.queryTimeBase),B=Number(C-this.queryTimeBase);if(!Number.isSafeInteger(E)||!Number.isSafeInteger(B))throw new RangeError("incorrect timestamp range");if((n=this.env.webgpu.profiling)!=null&&n.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:w.map(G=>({dims:G.dims,dataType:Sn(G.dataType)})),outputsMetadata:l.map(G=>({dims:G.dims,dataType:Sn(G.dataType)})),kernelId:i,kernelType:d,kernelName:p,programName:g,startTime:E,endTime:B});else{let G="";w.forEach((ae,Z)=>{G+=`input[${Z}]: [${ae.dims}] | ${Sn(ae.dataType)}, `});let O="";l.forEach((ae,Z)=>{O+=`output[${Z}]: [${ae.dims}] | ${Sn(ae.dataType)}, `}),console.log(`[profiling] kernel "${i}|${d}|${p}|${g}" ${G}${O}execution time: ${B-E} ns`)}Ne("GPU",`${g}::${M}::${C}`)}e.unmap(),this.pendingQueries.delete(e)}),je()}run(e,t,r,n,s,a){Ue(e.name);let i=[];for(let O=0;Oae):r;if(g.length!==u.length)throw new Error(`Output size ${g.length} must be equal to ${u.length}.`);let w=[],l=[];for(let O=0;O=a)throw new Error(`Invalid output index: ${g[O]}`);if(g[O]===-3)continue;let ae=g[O]===-1,Z=g[O]===-2,le=ae||Z?s(u[O].dataType,u[O].dims):n(g[O],u[O].dataType,u[O].dims);if(w.push(le),le.data===0)continue;let Ge=this.gpuDataManager.get(le.data);if(!Ge)throw new Error(`no GPU data for output: ${le.data}`);if(ae&&this.temporaryData.push(Ge),Z){let Le=this.kernelPersistentData.get(this.currentKernelId);Le||(Le=[],this.kernelPersistentData.set(this.currentKernelId,Le)),Le.push(Ge)}l.push(Ge)}if(i.length!==t.length||l.length!==w.length){if(l.length===0)return je(e.name),w;throw new Error(`Program ${e.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let M;if(p){let O=0,ae=[];p.forEach(Le=>{let pt=typeof Le.data=="number"?[Le.data]:Le.data;if(pt.length===0)return;let Dt=Le.type===10?2:4,Vt,lr;Le.type===10?(lr=pt.length>4?16:pt.length>2?8:pt.length*Dt,Vt=pt.length>4?16:Dt*pt.length):(lr=pt.length<=2?pt.length*Dt:16,Vt=16),O=Math.ceil(O/lr)*lr,ae.push(O);let fr=Le.type===10?8:4;O+=pt.length>4?Math.ceil(pt.length/fr)*Vt:pt.length*Dt});let Z=16;O=Math.ceil(O/Z)*Z;let le=new ArrayBuffer(O);p.forEach((Le,pt)=>{let Dt=ae[pt],Vt=typeof Le.data=="number"?[Le.data]:Le.data;if(Le.type===6)new Int32Array(le,Dt,Vt.length).set(Vt);else if(Le.type===12)new Uint32Array(le,Dt,Vt.length).set(Vt);else if(Le.type===10)new Uint16Array(le,Dt,Vt.length).set(Vt);else if(Le.type===1)new Float32Array(le,Dt,Vt.length).set(Vt);else throw new Error(`Unsupported uniform type: ${Sn(Le.type)}`)});let Ge=this.gpuDataManager.create(O,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(Ge.buffer,0,le,0,O),this.gpuDataManager.release(Ge.id),M={offset:0,size:O,buffer:Ge.buffer}}let C=this.programManager.normalizeDispatchGroupSize(d),E=C[1]===1&&C[2]===1,B=Op(e,t,E),G=this.programManager.getArtifact(B);if(G||(G=this.programManager.build(e,C),this.programManager.setArtifact(B,G),ue("info",()=>`[artifact] key: ${B}, programName: ${e.name}`)),p&&G.uniformVariablesInfo){if(p.length!==G.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${G.uniformVariablesInfo.length}, got ${p.length} in program "${G.programInfo.name}".`);for(let O=0;O`[ProgramManager] run "${e.name}" (key=${B}) with ${C[0]}x${C[1]}x${C[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let O={kernelId:this.currentKernelId,programName:G.programInfo.name,inputTensorViews:t,outputTensorViews:w};this.pendingKernels.push(O),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(O)}return this.programManager.run(G,i,l,C,M),je(e.name),w}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 s=Ip.get(e);if(!s)throw new Error(`kernel not implemented: ${e}`);let a={kernelType:e,kernelName:n,kernelEntry:s[0],attributes:[s[1],r]};this.kernels.set(t,a)}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 s=n.kernelType,a=n.kernelName,i=n.kernelEntry,u=n.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${s}] ${a}" is not allowed to be called recursively`);this.currentKernelId=e,u[0]&&(u[1]=u[0](u[1]),u[0]=void 0),ue("info",()=>`[WebGPU] Start to run kernel "[${s}] ${a}"...`);let d=this.env.debug;this.temporaryData=[];try{return d&&this.device.pushErrorScope("validation"),i(t,u[1]),0}catch(p){return r.push(Promise.resolve(`[WebGPU] Kernel "[${s}] ${a}" failed. ${p}`)),1}finally{d&&r.push(this.device.popErrorScope().then(p=>p?`GPU validation error for kernel "[${s}] ${a}": ${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 s=this.sessionExternalDataMapping.get(e);s||(s=new Map,this.sessionExternalDataMapping.set(e,s));let a=s.get(t),i=this.gpuDataManager.registerExternalBuffer(r,n,a);return s.set(t,[i,r]),i}unregisterBuffers(e){let t=this.sessionExternalDataMapping.get(e);t&&(t.forEach(r=>this.gpuDataManager.unregisterExternalBuffer(r[0])),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 Yt(this,e,t);return A(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(){ue("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(){ue("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){ue("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()}}}),Bp,Mc,vc,Rp,Np,Kf=j(()=>{m(),Bp=1,Mc=()=>Bp++,vc=class{constructor(e,t){this.mlContext=e,this.tensorEntry=t,this.tensorCache=t?[t]:[]}get tensor(){var e;return(e=this.tensorEntry)==null?void 0:e[0]}get context(){if(!this.mlContext)throw new Error("MLContext has not been set.");return this.mlContext}set context(e){if(this.mlContext&&this.mlContext!==e)throw new Error("MLTensor in use in a different MLContext.");this.mlContext=e}destroy(){for(let[e]of this.tensorCache)e.destroy();this.tensorCache=[],this.tensorEntry=void 0}trySelectTensor(e,t){for(let[r,n,s]of this.tensorCache)if(t===r){if(this.context!==e)throw new Error("MLTensor cannot be registered with a different MLContext.");return this.tensorEntry=[r,n,s],!0}return!1}async ensureTensor(e,t,r){var a;if(this.tensorEntry){let[i,u,d]=this.tensorEntry;if(u===e&&d.every((p,g)=>p===t[g]))return i}for(let[i,u,d]of this.tensorCache)if(u===e&&d.every((p,g)=>p===t[g])){if(r&&this.tensorEntry){ue("verbose",()=>`[WebNN] Slowdown may occur, having to copy existing tensor {dataType: ${e}, shape: ${t}}`);let p=await this.context.readTensor(this.tensorEntry[0]);this.context.writeTensor(i,p)}return this.tensorEntry=[i,u,d],i}ue("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${e}, shape: ${t}}`);let n=MLTensorUsage.READ|MLTensorUsage.WRITE,s=await this.context.createTensor({dataType:e,shape:t,dimensions:t,usage:n});return this.tensorEntry=[s,e,t],this.tensorCache.push(this.tensorEntry),this.activeUpload&&((a=this.mlContext)==null||a.writeTensor(s,this.activeUpload),this.activeUpload=void 0),s}upload(e){var t;if(!this.tensorEntry){this.activeUpload=new Uint8Array(e);return}(t=this.mlContext)==null||t.writeTensor(this.tensorEntry[0],e)}async download(e){if(this.activeUpload)if(e){e instanceof ArrayBuffer?new Uint8Array(e).set(this.activeUpload):new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(this.activeUpload);return}else return this.activeUpload.buffer;if(!this.tensorEntry)throw new Error("Tensor has not been created.");return e?this.context.readTensor(this.tensorEntry[0],e):this.context.readTensor(this.tensorEntry[0])}},Rp=class{constructor(e){this.backend=e,this.tensorsById=new Map,this.tensorIdsByContext=new Map}reserveTensorId(){let e=Mc();return this.tensorsById.set(e,new vc),e}releaseTensorId(e){let t=this.tensorsById.get(e);if(t){t.destroy(),this.tensorsById.delete(e);for(let[r,n]of this.tensorIdsByContext)if(n.has(e)){n.delete(e),n.size===0&&this.tensorIdsByContext.delete(r);break}}}async ensureTensor(e,t,r,n){var a;ue("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${e}, dataType: ${t}, shape: ${r}, copyOld: ${n}}`);let s=this.tensorsById.get(e);if(!s)throw new Error("Tensor not found.");return s.context=this.backend.currentContext,this.tensorIdsByContext.has(this.backend.currentContext)||this.tensorIdsByContext.set(this.backend.currentContext,new Set),(a=this.tensorIdsByContext.get(this.backend.currentContext))==null||a.add(e),s.ensureTensor(t,r,n)}upload(e,t){this.tensorsById.get(e).upload(t)}async download(e,t){return ue("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${e}, dstBuffer: ${t==null?void 0:t.byteLength}}`),this.tensorsById.get(e).download(t)}releaseTensorsForContext(e){let t=this.tensorIdsByContext.get(e);if(t){for(let r of t)this.tensorsById.get(r).destroy(),this.tensorsById.delete(r);this.tensorIdsByContext.delete(e)}}registerTensor(e,t,r,n){for(let[i,u]of this.tensorsById)if(u.trySelectTensor(e,t))return i;let s=Mc();this.tensorsById.set(s,new vc(e,[t,r,n]));let a=this.tensorIdsByContext.get(e);return a||(a=new Set,this.tensorIdsByContext.set(e,a)),a.add(s),s}},Np=(...e)=>new Rp(...e)}),xc,jp,Xf=j(()=>{Xt(),Wr(),H(),Kf(),m(),xc=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),jp=class{constructor(e){this.tensorManager=Np(this),this.mlContextBySessionId=new Map,this.sessionIdsByMLContext=new Map,ws(e.logLevel,!!e.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(e){this.activeSessionId=e}get currentContext(){let e=this.getMLContext(this.currentSessionId);if(!e)throw new Error(`No MLContext found for session ${this.currentSessionId}`);return e}registerMLContext(e,t){this.mlContextBySessionId.set(e,t);let r=this.sessionIdsByMLContext.get(t);r||(r=new Set,this.sessionIdsByMLContext.set(t,r)),r.add(e)}onReleaseSession(e){let t=this.mlContextBySessionId.get(e);if(!t)return;this.mlContextBySessionId.delete(e);let r=this.sessionIdsByMLContext.get(t);r.delete(e),r.size===0&&(this.sessionIdsByMLContext.delete(t),this.tensorManager.releaseTensorsForContext(t))}getMLContext(e){return this.mlContextBySessionId.get(e)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(e){ue("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,t,r,n){let s=xc.get(t);if(!s)throw new Error(`Unsupported ONNX data type: ${t}`);return this.tensorManager.ensureTensor(e,s,r,n)}uploadTensor(e,t){if(!rr().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");ue("verbose",()=>`[WebNN] uploadTensor {tensorId: ${e}, data: ${t.byteLength}}`),this.tensorManager.upload(e,t)}async downloadTensor(e,t){return this.tensorManager.download(e,t)}createMLTensorDownloader(e,t){return async()=>{let r=await this.tensorManager.download(e);return A(r,t)}}registerMLTensor(e,t,r){let n=xc.get(t);if(!n)throw new Error(`Unsupported ONNX data type: ${t}`);let s=this.tensorManager.registerTensor(this.currentContext,e,n,r);return ue("verbose",()=>`[WebNN] registerMLTensor {tensor: ${e}, dataType: ${n}, dimensions: ${r}} -> {tensorId: ${s}}`),s}flush(){}}}),Vp={};S(Vp,{init:()=>Wp});var Xd,Up,Wp,Qf=j(()=>{Xt(),Hf(),m(),Ht(),Xf(),Xd=class Sf{constructor(t,r,n,s){this.module=t,this.dataType=r,this.data=n,this.dims=s}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let t=Se.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=Se.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=Se.size(this.dims);return t===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,t)}getUint16Array(){if(this.dataType!==10&&this.dataType!==4)throw new Error("Invalid data type");let t=Se.size(this.dims);return t===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,t)}reshape(t){if(Se.size(t)!==Se.size(this.dims))throw new Error("Invalid new shape");return new Sf(this.module,this.dataType,this.data,t)}},Up=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,s=r>>>2;this.opKernelContext=n[s++];let a=n[s++];this.outputCount=n[s++],this.customDataOffset=n[s++],this.customDataSize=n[s++];let i=[];for(let u=0;utypeof u=="number"?this.inputs[u]:u))??this.inputs,n=(t==null?void 0:t.outputs)??[],s=(u,d,p)=>new Xd(this.module,d,this.output(u,p),p),a=(u,d)=>{let p=Cn(u,d);if(!p)throw new Error(`Unsupported data type: ${u}`);let g=p>0?this.backend.gpuDataManager.create(p).id:0;return new Xd(this.module,u,g,d)};return this.backend.run(e,r,n,s,a,this.outputCount)}output(e,t){let r=this.module.stackSave();try{let n=this.module.stackAlloc((1+t.length)*4),s=n>>2;this.module.HEAPU32[s++]=t.length;for(let a=0;a{let s=t.jsepInit;if(!s)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(e==="webgpu"){let a=new Lp;await a.initialize(r,n),s("webgpu",[a,i=>a.alloc(i),i=>a.free(i),(i,u,d,p=!1)=>{if(p)ue("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${i}, dst=${u}, size=${d}`),a.memcpy(i,u);else{ue("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${i}, gpuDataId=${u}, size=${d}`);let g=t.HEAPU8.subarray(i>>>0,(i>>>0)+d);a.upload(u,g)}},async(i,u,d)=>{ue("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${i}, dataOffset=${u}, size=${d}`),await a.download(i,()=>t.HEAPU8.subarray(u>>>0,(u>>>0)+d))},(i,u,d)=>a.createKernel(i,u,d,t.UTF8ToString(t._JsepGetNodeName(u))),i=>a.releaseKernel(i),(i,u,d,p)=>{ue("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${d}, kernel=${i}, contextDataOffset=${u}`);let g=new Up(t,a,u);return a.computeKernel(i,g,p)},()=>a.captureBegin(),()=>a.captureEnd(),()=>a.replay()])}else{let a=new jp(r);s("webnn",[a,()=>a.reserveTensorId(),i=>a.releaseTensorId(i),async(i,u,d,p)=>a.ensureTensor(i,u,d,p),(i,u)=>{a.uploadTensor(i,u)},async(i,u)=>a.downloadTensor(i,u)])}}}),Gp,Tc,Cc,Ns,qp,Qd,Ec,$c,Sc,kc,Pc,Ac,Hp=j(()=>{Xs(),Qs(),Xt(),Wr(),Bn(),_s(),Gp=(e,t)=>{rr()._OrtInit(e,t)!==0&&Rr("Can't initialize onnxruntime.")},Tc=async e=>{Gp(e.wasm.numThreads,ts(e.logLevel))},Cc=async(e,t)=>{{let r=(Qf(),P(Vp)).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 s=e.webgpu.powerPreference;if(s!==void 0&&s!=="low-power"&&s!=="high-performance")throw new Error(`Invalid powerPreference setting: "${s}"`);let a=e.webgpu.forceFallbackAdapter;if(a!==void 0&&typeof a!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${a}"`);if(n=await navigator.gpu.requestAdapter({powerPreference:s,forceFallbackAdapter:a}),!n)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}await r("webgpu",rr(),e,n)}if(t==="webnn"){if(typeof navigator>"u"||!navigator.ml)throw new Error("WebNN is not supported in current environment");await r("webnn",rr(),e)}}},Ns=new Map,qp=e=>{let t=rr(),r=t.stackSave();try{let n=t.stackAlloc(8);return t._OrtGetInputOutputCount(e,n,n+4)!==0&&Rr("Can't get session input/output count."),[t.HEAP32[n/4],t.HEAP32[n/4+1]]}finally{t.stackRestore(r)}},Qd=e=>{let t=rr(),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]},Ec=async(e,t)=>{var w,l;let r,n,s=rr();Array.isArray(e)?[r,n]=e:e.buffer===s.HEAPU8.buffer?[r,n]=[e.byteOffset,e.byteLength]:[r,n]=Qd(e);let a=0,i=0,u=0,d=[],p=[],g=[];try{if([i,d]=ks(t),(t==null?void 0:t.externalData)&&s.mountExternalData){let Z=[];for(let le of t.externalData){let Ge=typeof le=="string"?le:le.path;Z.push(ms(typeof le=="string"?le:le.data).then(Le=>{s.mountExternalData(Ge,Le)}))}await Promise.all(Z)}for(let Z of(t==null?void 0:t.executionProviders)??[])if((typeof Z=="string"?Z:Z.name)==="webnn"){if(s.shouldTransferToMLTensor=!1,s.currentContext)throw new Error("WebNN execution provider is already set.");if(typeof Z!="string"){let le=Z,Ge=le==null?void 0:le.context,Le=le==null?void 0:le.gpuDevice,pt=le==null?void 0:le.deviceType,Dt=le==null?void 0:le.numThreads,Vt=le==null?void 0:le.powerPreference;Ge?s.currentContext=Ge:Le?s.currentContext=await navigator.ml.createContext(Le):s.currentContext=await navigator.ml.createContext({deviceType:pt,numThreads:Dt,powerPreference:Vt})}else s.currentContext=await navigator.ml.createContext();break}a=await s._OrtCreateSession(r,n,i),a===0&&Rr("Can't create a session."),s.currentContext&&(s.jsepRegisterMLContext(a,s.currentContext),s.currentContext=void 0,s.shouldTransferToMLTensor=!0);let[M,C]=qp(a),E=!!(t!=null&&t.enableGraphCapture),B=[],G=[],O=[];for(let Z=0;ZZ==="gpu-buffer"||Z==="ml-tensor")&&(u=s._OrtCreateBinding(a),u===0&&Rr("Can't create IO binding."),ae={handle:u,outputPreferredLocations:O,outputPreferredLocationsEncoded:O.map(Z=>rs(Z))}),Ns.set(a,[a,p,g,ae,E,!1]),[a,B,G]}catch(M){throw p.forEach(C=>s._OrtFree(C)),g.forEach(C=>s._OrtFree(C)),u!==0&&s._OrtReleaseBinding(u),a!==0&&s._OrtReleaseSession(a),M}finally{s._free(r),i!==0&&s._OrtReleaseSessionOptions(i),d.forEach(M=>s._free(M)),(l=s.unmountExternalData)==null||l.call(s)}},$c=e=>{var d;let t=rr(),r=Ns.get(e);if(!r)throw new Error(`cannot release session. invalid session id: ${e}`);let[n,s,a,i,u]=r;i&&(u&&t._OrtClearBoundOutputs(i.handle),t._OrtReleaseBinding(i.handle)),(d=t.jsepOnReleaseSession)==null||d.call(t,e),s.forEach(p=>t._OrtFree(p)),a.forEach(p=>t._OrtFree(p)),t._OrtReleaseSession(n),Ns.delete(e)},Sc=(e,t,r,n,s,a=!1)=>{if(!e){t.push(0);return}let i=rr(),u=e[0],d=e[1],p=e[3],g,w;if(u==="string"&&(p==="gpu-buffer"||p==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(a&&p!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${s} when enableGraphCapture is true.`);if(p==="gpu-buffer"){let C=e[2].gpuBuffer;w=Cn(qn(u),d);let E=i.jsepRegisterBuffer;if(!E)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');g=E(n,s,C,w)}else if(p==="ml-tensor"){let C=e[2].mlTensor;w=Cn(qn(u),d);let E=i.jsepRegisterMLTensor;if(!E)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');g=E(C,qn(u),d)}else{let C=e[2];if(Array.isArray(C)){w=4*C.length,g=i._malloc(w),r.push(g);let E=g/4;for(let B=0;Bi.HEAP32[C++]=B);let E=i._OrtCreateTensor(qn(u),g,w,M,d.length,rs(p));E===0&&Rr(`Can't create tensor for input/output. session=${n}, index=${s}.`),t.push(E)}finally{i.stackRestore(l)}},kc=async(e,t,r,n,s,a)=>{var Vt,lr;let i=rr(),u=Ns.get(e);if(!u)throw new Error(`cannot run inference. invalid session id: ${e}`);let d=u[0],p=u[1],g=u[2],w=u[3],l=u[4],M=u[5],C=t.length,E=n.length,B=0,G=[],O=[],ae=[],Z=[],le=i.stackSave(),Ge=i.stackAlloc(C*4),Le=i.stackAlloc(C*4),pt=i.stackAlloc(E*4),Dt=i.stackAlloc(E*4);try{(Vt=i.jsepOnRunStart)==null||Vt.call(i,d),[B,G]=Cs(a);for(let Jt=0;Jthn*vn,1);tr=Sn(un);let yi=w==null?void 0:w.outputPreferredLocations[n[Jt]];if(tr==="string"){if(yi==="gpu-buffer"||yi==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let hn=[],vn=zr/4;for(let Vn=0;Vn0){let hn=i.jsepGetBuffer;if(!hn)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let vn=hn(zr),Vn=Cn(un,mn);if(Vn===void 0||!hs(tr))throw new Error(`Unsupported data type: ${tr}`);kt=!0,jr.push([tr,En,{gpuBuffer:vn,download:i.jsepCreateDownloader(vn,Vn,tr),dispose:()=>{i._OrtReleaseTensor(dr)}},"gpu-buffer"])}else if(yi==="ml-tensor"&&mn>0){let hn=i.jsepEnsureTensor;if(!hn)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(Cn(un,mn)===void 0||!fs(tr))throw new Error(`Unsupported data type: ${tr}`);let vn=await hn(zr,un,En,!1);kt=!0,jr.push([tr,En,{mlTensor:vn,download:i.jsepCreateMLTensorDownloader(zr,tr),dispose:()=>{i.jsepReleaseTensorId(zr),i._OrtReleaseTensor(dr)}},"ml-tensor"])}else{let hn=ps(tr),vn=new hn(mn);new Uint8Array(vn.buffer,vn.byteOffset,vn.byteLength).set(i.HEAPU8.subarray(zr,zr+vn.byteLength)),jr.push([tr,En,vn,"cpu"])}}finally{i.stackRestore(Pr),tr==="string"&&zr&&i._free(zr),kt||i._OrtReleaseTensor(dr)}}return w&&!l&&(i._OrtClearBoundOutputs(w.handle),Ns.set(e,[d,p,g,w,l,!1])),jr}finally{i.stackRestore(le),O.forEach(fr=>i._OrtReleaseTensor(fr)),ae.forEach(fr=>i._OrtReleaseTensor(fr)),Z.forEach(fr=>i._free(fr)),B!==0&&i._OrtReleaseRunOptions(B),G.forEach(fr=>i._free(fr))}},Pc=e=>{let t=rr(),r=Ns.get(e);if(!r)throw new Error("invalid session id");let n=r[0],s=t._OrtEndProfiling(n);s===0&&Rr("Can't get an profile file name."),t._OrtFree(s)},Ac=e=>{let t=[];for(let r of e){let n=r[2];!Array.isArray(n)&&"buffer"in n&&t.push(n.buffer)}return t}}),js,Dn,Za,fd,md,Yd,Ic,Jd,gi,wi,Kp,Xp,Qp,Yp,Jp,Zp,eh,th,rh=j(()=>{At(),Hp(),Wr(),Gt(),js=()=>!!k.wasm.proxy&&typeof document<"u",Za=!1,fd=!1,md=!1,Jd=new Map,gi=(e,t)=>{let r=Jd.get(e);r?r.push(t):Jd.set(e,[t])},wi=()=>{if(Za||!fd||md||!Dn)throw new Error("worker not ready")},Kp=e=>{switch(e.data.type){case"init-wasm":Za=!1,e.data.err?(md=!0,Ic[1](e.data.err)):(fd=!0,Ic[0]()),Yd&&(URL.revokeObjectURL(Yd),Yd=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let t=Jd.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}}},Xp=async()=>{if(!fd){if(Za)throw new Error("multiple calls to 'initWasm()' detected.");if(md)throw new Error("previous call to 'initWasm()' failed.");if(Za=!0,js())return new Promise((e,t)=>{Dn==null||Dn.terminate(),zt().then(([r,n])=>{try{Dn=n,Dn.onerror=a=>t(a),Dn.onmessage=Kp,Ic=[e,t];let s={type:"init-wasm",in:k};Dn.postMessage(s),Yd=r}catch(s){t(s)}},t)});try{await Kr(k.wasm),await Tc(k),fd=!0}catch(e){throw md=!0,e}finally{Za=!1}}},Qp=async e=>{if(js())return wi(),new Promise((t,r)=>{gi("init-ep",[t,r]);let n={type:"init-ep",in:{epName:e,env:k}};Dn.postMessage(n)});await Cc(k,e)},Yp=async e=>js()?(wi(),new Promise((t,r)=>{gi("copy-from",[t,r]);let n={type:"copy-from",in:{buffer:e}};Dn.postMessage(n,[e.buffer])})):Qd(e),Jp=async(e,t)=>{if(js()){if(t!=null&&t.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return wi(),new Promise((r,n)=>{gi("create",[r,n]);let s={type:"create",in:{model:e,options:{...t}}},a=[];e instanceof Uint8Array&&a.push(e.buffer),Dn.postMessage(s,a)})}else return Ec(e,t)},Zp=async e=>{if(js())return wi(),new Promise((t,r)=>{gi("release",[t,r]);let n={type:"release",in:e};Dn.postMessage(n)});$c(e)},eh=async(e,t,r,n,s,a)=>{if(js()){if(r.some(i=>i[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(s.some(i=>i))throw new Error("pre-allocated output tensor is not supported for proxy.");return wi(),new Promise((i,u)=>{gi("run",[i,u]);let d=r,p={type:"run",in:{sessionId:e,inputIndices:t,inputs:d,outputIndices:n,options:a}};Dn.postMessage(p,Ac(d))})}else return kc(e,t,r,n,s,a)},th=async e=>{if(js())return wi(),new Promise((t,r)=>{gi("end-profiling",[t,r]);let n={type:"end-profiling",in:e};Dn.postMessage(n)});Pc(e)}}),Fc,nh,sh,Yf=j(()=>{At(),rh(),Xt(),cr(),_s(),Fc=(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"];case"ml-tensor":return[e.type,e.dims,{mlTensor:e.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${e.location} for ${t()}`)}},nh=e=>{switch(e[3]){case"cpu":return new ee(e[0],e[2],e[1]);case"gpu-buffer":{let t=e[0];if(!hs(t))throw new Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:r,download:n,dispose:s}=e[2];return ee.fromGpuBuffer(r,{dataType:t,dims:e[1],download:n,dispose:s})}case"ml-tensor":{let t=e[0];if(!fs(t))throw new Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:r,download:n,dispose:s}=e[2];return ee.fromMLTensor(r,{dataType:t,dims:e[1],download:n,dispose:s})}default:throw new Error(`invalid data location: ${e[3]}`)}},sh=class{async fetchModelAndCopyToWasmMemory(e){return Yp(await ms(e))}async loadModel(e,t){Ue();let r;typeof e=="string"?r=await this.fetchModelAndCopyToWasmMemory(e):r=e,[this.sessionId,this.inputNames,this.outputNames]=await Jp(r,t),je()}async dispose(){return Zp(this.sessionId)}async run(e,t,r){Ue();let n=[],s=[];Object.entries(e).forEach(w=>{let l=w[0],M=w[1],C=this.inputNames.indexOf(l);if(C===-1)throw new Error(`invalid input '${l}'`);n.push(M),s.push(C)});let a=[],i=[];Object.entries(t).forEach(w=>{let l=w[0],M=w[1],C=this.outputNames.indexOf(l);if(C===-1)throw new Error(`invalid output '${l}'`);a.push(M),i.push(C)});let u=n.map((w,l)=>Fc(w,()=>`input "${this.inputNames[s[l]]}"`)),d=a.map((w,l)=>w?Fc(w,()=>`output "${this.outputNames[i[l]]}"`):null),p=await eh(this.sessionId,s,u,i,d,r),g={};for(let w=0;wOc,initializeFlags:()=>zc,wasmBackend:()=>ah});var zc,Oc,ah,Jf=j(()=>{At(),rh(),Yf(),Gt(),zc=()=>{if((typeof k.wasm.initTimeout!="number"||k.wasm.initTimeout<0)&&(k.wasm.initTimeout=0),k.wasm.simd===!1&&console.warn('Deprecated property "env.wasm.simd" is set to false. non-SIMD build is no longer provided, and this setting will be ignored.'),typeof k.wasm.proxy!="boolean"&&(k.wasm.proxy=!1),typeof k.wasm.trace!="boolean"&&(k.wasm.trace=!1),typeof k.wasm.numThreads!="number"||!Number.isInteger(k.wasm.numThreads)||k.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)k.wasm.numThreads=1;else{let e=typeof navigator>"u"?Ee("node:os").cpus().length:navigator.hardwareConcurrency;k.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},Oc=class{async init(e){zc(),await Xp(),await Qp(e)}async createInferenceSessionHandler(e,t){let r=new sh;return await r.loadModel(e,t),Promise.resolve(r)}},ah=new Oc});At(),At(),At();var Zf="1.20.0-dev.20240928-1bda91fc57",em=It;{let e=(Jf(),P(ih)).wasmBackend;_e("webgpu",e,5),_e("webnn",e,5),_e("cpu",e,10),_e("wasm",e,10)}Object.defineProperty(k.versions,"web",{value:Zf,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. - * ============================================================================= - */},"./src/backends/onnx.js":(Pt,Ce,N)=>{var z;N.r(Ce),N.d(Ce,{Tensor:()=>Ee.Tensor,createInferenceSession:()=>ce,deviceToExecutionProviders:()=>ne,isONNXProxy:()=>re,isONNXTensor:()=>D});var me=N("./src/env.js"),ye=N("?2ce3"),Te=N("./node_modules/onnxruntime-web/dist/ort.webgpu.bundle.min.mjs"),Ee=N("./node_modules/onnxruntime-common/dist/esm/index.js");const j=Object.freeze({auto:null,gpu:null,cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",webnn:{name:"webnn",deviceType:"cpu"},"webnn-npu":{name:"webnn",deviceType:"npu"},"webnn-gpu":{name:"webnn",deviceType:"gpu"},"webnn-cpu":{name:"webnn",deviceType:"cpu"}}),S=[];let V,P;if(me.apis.IS_NODE_ENV){switch(P=ye??(z||(z=N.t(ye,2))),process.platform){case"win32":S.push("dml");break;case"linux":process.arch==="x64"&&S.push("cuda");break}S.push("cpu"),V=["cpu"]}else P=Te,me.apis.IS_WEBNN_AVAILABLE&&S.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),me.apis.IS_WEBGPU_AVAILABLE&&S.push("webgpu"),S.push("wasm"),V=["wasm"];const te=P.InferenceSession;function ne(ie=null){if(!ie)return V;switch(ie){case"auto":return S;case"gpu":return S.filter(X=>["webgpu","cuda","dml","webnn-gpu"].includes(X))}if(S.includes(ie))return[j[ie]??ie];throw new Error(`Unsupported device: "${ie}". Should be one of: ${S.join(", ")}.`)}let _e=null;async function ce(ie,X){_e&&await _e;const R=te.create(ie,X);return _e??(_e=R),await R}function D(ie){return ie instanceof P.Tensor}const K=P==null?void 0:P.env;K!=null&&K.wasm&&(K.wasm.wasmPaths=`https://cdn.jsdelivr.net/npm/@huggingface/transformers@${me.env.version}/dist/`,K.wasm.proxy=!1,(typeof crossOriginIsolated>"u"||!crossOriginIsolated)&&(K.wasm.numThreads=1)),K!=null&&K.webgpu&&(K.webgpu.powerPreference="high-performance");function re(){var ie;return(ie=K==null?void 0:K.wasm)==null?void 0:ie.proxy}me.env.backends.onnx=K},"./src/configs.js":(Pt,Ce,N)=>{N.r(Ce),N.d(Ce,{AutoConfig:()=>S,PretrainedConfig:()=>j,getKeyValueShapes:()=>Ee});var z=N("./src/utils/core.js"),me=N("./src/utils/hub.js");async function ye(V,P){return await(0,me.getModelJSON)(V,"config.json",!0,P)}function Te(V){const P={};let te={};switch(V.model_type){case"llava":case"paligemma":case"florence2":te=Te(V.text_config);break;case"moondream1":te=Te(V.phi_config);break;case"musicgen":te=Te(V.decoder);break;case"gpt2":case"gptj":case"jais":case"codegen":case"gpt_bigcode":P.num_heads="n_head",P.num_layers="n_layer",P.hidden_size="n_embd";break;case"gpt_neox":case"stablelm":case"opt":case"phi":case"phi3":case"falcon":P.num_heads="num_attention_heads",P.num_layers="num_hidden_layers",P.hidden_size="hidden_size";break;case"llama":case"cohere":case"mistral":case"starcoder2":case"qwen2":P.num_heads="num_key_value_heads",P.num_layers="num_hidden_layers",P.hidden_size="hidden_size",P.num_attention_heads="num_attention_heads";break;case"gemma":case"gemma2":P.num_heads="num_key_value_heads",P.num_layers="num_hidden_layers",P.dim_kv="head_dim";break;case"openelm":P.num_heads="num_kv_heads",P.num_layers="num_transformer_layers",P.dim_kv="head_dim";break;case"gpt_neo":case"donut-swin":P.num_heads="num_heads",P.num_layers="num_layers",P.hidden_size="hidden_size";break;case"bloom":P.num_heads="n_head",P.num_layers="n_layer",P.hidden_size="hidden_size";break;case"mpt":P.num_heads="n_heads",P.num_layers="n_layers",P.hidden_size="d_model";break;case"t5":case"mt5":case"longt5":P.num_decoder_layers="num_decoder_layers",P.num_decoder_heads="num_heads",P.decoder_dim_kv="d_kv",P.num_encoder_layers="num_layers",P.num_encoder_heads="num_heads",P.encoder_dim_kv="d_kv";break;case"bart":case"mbart":case"marian":case"whisper":case"m2m_100":case"blenderbot":case"blenderbot-small":case"florence2_language":P.num_decoder_layers="decoder_layers",P.num_decoder_heads="decoder_attention_heads",P.decoder_hidden_size="d_model",P.num_encoder_layers="encoder_layers",P.num_encoder_heads="encoder_attention_heads",P.encoder_hidden_size="d_model";break;case"speecht5":P.num_decoder_layers="decoder_layers",P.num_decoder_heads="decoder_attention_heads",P.decoder_hidden_size="hidden_size",P.num_encoder_layers="encoder_layers",P.num_encoder_heads="encoder_attention_heads",P.encoder_hidden_size="hidden_size";break;case"trocr":P.num_encoder_layers=P.num_decoder_layers="decoder_layers",P.num_encoder_heads=P.num_decoder_heads="decoder_attention_heads",P.encoder_hidden_size=P.decoder_hidden_size="d_model";break;case"musicgen_decoder":P.num_encoder_layers=P.num_decoder_layers="num_hidden_layers",P.num_encoder_heads=P.num_decoder_heads="num_attention_heads",P.encoder_hidden_size=P.decoder_hidden_size="hidden_size";break;case"vision-encoder-decoder":const _e=Te(V.decoder),ce="num_decoder_layers"in _e,D=(0,z.pick)(V,["model_type","is_encoder_decoder"]);return ce?(D.num_decoder_layers=_e.num_decoder_layers,D.num_decoder_heads=_e.num_decoder_heads,D.decoder_hidden_size=_e.decoder_hidden_size,D.num_encoder_layers=_e.num_encoder_layers,D.num_encoder_heads=_e.num_encoder_heads,D.encoder_hidden_size=_e.encoder_hidden_size):(D.num_layers=_e.num_layers,D.num_heads=_e.num_heads,D.hidden_size=_e.hidden_size),D}const ne={...te,...(0,z.pick)(V,["model_type","multi_query","is_encoder_decoder"])};for(const _e in P)ne[_e]=V[P[_e]];return ne}function Ee(V,{prefix:P="past_key_values"}={}){const te={},ne=V.normalized_config,_e=1;if(ne.is_encoder_decoder&&"num_encoder_heads"in ne&&"num_decoder_heads"in ne){const ce=ne.encoder_dim_kv??ne.encoder_hidden_size/ne.num_encoder_heads,D=ne.decoder_dim_kv??ne.decoder_hidden_size/ne.num_decoder_heads,K=[_e,ne.num_encoder_heads,0,ce],re=[_e,ne.num_decoder_heads,0,D];for(let ie=0;ie{var k;N.r(Ce),N.d(Ce,{apis:()=>D,env:()=>I});var z=N("?569f"),me=N("?3f59"),ye=N("?154a");const Te="3.0.0-alpha.19",Ee=typeof self<"u",j=Ee&&self.constructor.name==="DedicatedWorkerGlobalScope",S=Ee&&"caches"in self,V=typeof navigator<"u"&&"gpu"in navigator,P=typeof navigator<"u"&&"ml"in navigator,te=typeof process<"u",ne=te&&((k=process==null?void 0:process.release)==null?void 0:k.name)==="node",_e=!L(z),ce=!L(me),D=Object.freeze({IS_BROWSER_ENV:Ee,IS_WEBWORKER_ENV:j,IS_WEB_CACHE_AVAILABLE:S,IS_WEBGPU_AVAILABLE:V,IS_WEBNN_AVAILABLE:P,IS_PROCESS_AVAILABLE:te,IS_NODE_ENV:ne,IS_FS_AVAILABLE:_e,IS_PATH_AVAILABLE:ce}),K=_e&&ce,re=K?me.dirname(me.dirname(ye.fileURLToPath(self.location.href))):"./",ie=K?me.join(re,"/.cache/"):null,X="/models/",R=K?me.join(re,X):X,I={version:Te,backends:{onnx:{}},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!Ee,localModelPath:R,useFS:_e,useBrowserCache:S,useFSCache:_e,cacheDir:ie,useCustomCache:!1,customCache:null};function L(de){return Object.keys(de).length===0}},"./src/generation/configuration_utils.js":(Pt,Ce,N)=>{N.r(Ce),N.d(Ce,{GenerationConfig:()=>me});var z=N("./src/utils/core.js");class me{constructor(Te){xe(this,"max_length",20);xe(this,"max_new_tokens",null);xe(this,"min_length",0);xe(this,"min_new_tokens",null);xe(this,"early_stopping",!1);xe(this,"max_time",null);xe(this,"do_sample",!1);xe(this,"num_beams",1);xe(this,"num_beam_groups",1);xe(this,"penalty_alpha",null);xe(this,"use_cache",!0);xe(this,"temperature",1);xe(this,"top_k",50);xe(this,"top_p",1);xe(this,"typical_p",1);xe(this,"epsilon_cutoff",0);xe(this,"eta_cutoff",0);xe(this,"diversity_penalty",0);xe(this,"repetition_penalty",1);xe(this,"encoder_repetition_penalty",1);xe(this,"length_penalty",1);xe(this,"no_repeat_ngram_size",0);xe(this,"bad_words_ids",null);xe(this,"force_words_ids",null);xe(this,"renormalize_logits",!1);xe(this,"constraints",null);xe(this,"forced_bos_token_id",null);xe(this,"forced_eos_token_id",null);xe(this,"remove_invalid_values",!1);xe(this,"exponential_decay_length_penalty",null);xe(this,"suppress_tokens",null);xe(this,"begin_suppress_tokens",null);xe(this,"forced_decoder_ids",null);xe(this,"guidance_scale",null);xe(this,"num_return_sequences",1);xe(this,"output_attentions",!1);xe(this,"output_hidden_states",!1);xe(this,"output_scores",!1);xe(this,"return_dict_in_generate",!1);xe(this,"pad_token_id",null);xe(this,"bos_token_id",null);xe(this,"eos_token_id",null);xe(this,"encoder_no_repeat_ngram_size",0);xe(this,"decoder_start_token_id",null);xe(this,"generation_kwargs",{});Object.assign(this,(0,z.pick)(Te,Object.getOwnPropertyNames(this)))}}},"./src/generation/logits_process.js":(Pt,Ce,N)=>{N.r(Ce),N.d(Ce,{ClassifierFreeGuidanceLogitsProcessor:()=>K,ForcedBOSTokenLogitsProcessor:()=>j,ForcedEOSTokenLogitsProcessor:()=>S,LogitsProcessor:()=>ye,LogitsProcessorList:()=>Ee,LogitsWarper:()=>Te,MinLengthLogitsProcessor:()=>_e,MinNewTokensLengthLogitsProcessor:()=>ce,NoBadWordsLogitsProcessor:()=>D,NoRepeatNGramLogitsProcessor:()=>te,RepetitionPenaltyLogitsProcessor:()=>ne,SuppressTokensAtBeginLogitsProcessor:()=>V,TemperatureLogitsWarper:()=>re,TopKLogitsWarper:()=>X,TopPLogitsWarper:()=>ie,WhisperTimeStampLogitsProcessor:()=>P});var z=N("./src/utils/generic.js");N("./src/utils/tensor.js");var me=N("./src/utils/maths.js");class ye extends z.Callable{_call(I,L){throw Error("`_call` should be implemented in a subclass")}}class Te extends z.Callable{_call(I,L){throw Error("`_call` should be implemented in a subclass")}}class Ee extends z.Callable{constructor(){super(),this.processors=[]}push(I){this.processors.push(I)}extend(I){this.processors.push(...I)}_call(I,L){let k=L;for(const de of this.processors)k=de(I,k);return k}[Symbol.iterator](){return this.processors.values()}}class j extends ye{constructor(I){super(),this.bos_token_id=I}_call(I,L){for(let k=0;k=1&&Me[Me.length-1]>=this.timestamp_begin,ze=Me.length<2||Me[Me.length-2]>=this.timestamp_begin;if(ke&&(ze?de.subarray(this.timestamp_begin).fill(-1/0):de.subarray(0,this.eos_token_id).fill(-1/0)),I[k].length===this.begin_index&&this.max_initial_timestamp_index!==null){const ut=this.timestamp_begin+this.max_initial_timestamp_index;de.subarray(ut+1).fill(-1/0)}const Ie=(0,me.log_softmax)(de),Ze=Math.log(Ie.subarray(this.timestamp_begin).map(Math.exp).reduce((ut,we)=>ut+we)),Ke=(0,me.max)(Ie.subarray(0,this.timestamp_begin))[0];Ze>Ke&&de.subarray(0,this.timestamp_begin).fill(-1/0)}return L}}class te extends ye{constructor(I){super(),this.no_repeat_ngram_size=I}getNgrams(I){const L=I.length,k=[];for(let Me=0;Me1 to use the classifier free guidance processor, got guidance scale ${I}.`);this.guidance_scale=I}_call(I,L){if(L.dims[0]!==2*I.length)throw new Error(`Logits should have twice the batch size of the input ids, the first half of batches corresponding to the conditional inputs, and the second half of batches corresponding to the unconditional inputs. Got batch size ${L.dims[0]} for the logits and ${I.length} for the input ids.`);const k=I.length,de=L.slice([0,k],null),Me=L.slice([k,L.dims[0]],null);for(let ke=0;ke1)throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${I}`);if(!Number.isInteger(k)||k<1)throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${k}`);this.top_p=I,this.filter_value=L,this.min_tokens_to_keep=k}}class X extends Te{constructor(I,{filter_value:L=-1/0,min_tokens_to_keep:k=1}={}){if(super(),!Number.isInteger(I)||I<0)throw new Error(`\`top_k\` must be a positive integer, but is ${I}`);this.top_k=Math.max(I,k),this.filter_value=L}}},"./src/generation/logits_sampler.js":(Pt,Ce,N)=>{N.r(Ce),N.d(Ce,{LogitsSampler:()=>Te});var z=N("./src/utils/generic.js"),me=N("./src/utils/tensor.js"),ye=N("./src/utils/maths.js");N("./src/generation/configuration_utils.js");class Te extends z.Callable{constructor(P){super(),this.generation_config=P}async _call(P){return this.sample(P)}async sample(P){throw Error("sample should be implemented in subclasses.")}getLogits(P,te){let ne=P.dims.at(-1),_e=P.data;if(te===-1)_e=_e.slice(-ne);else{let ce=te*ne;_e=_e.slice(ce,ce+ne)}return _e}randomSelect(P){let te=0;for(let _e=0;_e1)return new S(P);if(P.num_return_sequences>1)throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${P.num_return_sequences}.`);return new Ee(P)}}class Ee extends Te{async sample(P){const te=(0,ye.max)(P.data)[1];return[[BigInt(te),0]]}}class j extends Te{async sample(P){let te=P.dims.at(-1);this.generation_config.top_k>0&&(te=Math.min(this.generation_config.top_k,te));const[ne,_e]=await(0,me.topk)(P,te),ce=(0,ye.softmax)(ne.data);return Array.from({length:this.generation_config.num_beams},()=>{const D=this.randomSelect(ce);return[_e.data[D],Math.log(ce[D])]})}}class S extends Te{async sample(P){let te=P.dims.at(-1);this.generation_config.top_k>0&&(te=Math.min(this.generation_config.top_k,te));const[ne,_e]=await(0,me.topk)(P,te),ce=(0,ye.softmax)(ne.data);return Array.from({length:this.generation_config.num_beams},(D,K)=>[_e.data[K],Math.log(ce[K])])}}},"./src/generation/stopping_criteria.js":(Pt,Ce,N)=>{N.r(Ce),N.d(Ce,{EosTokenCriteria:()=>Ee,InterruptableStoppingCriteria:()=>j,MaxLengthCriteria:()=>Te,StoppingCriteria:()=>me,StoppingCriteriaList:()=>ye});var z=N("./src/utils/generic.js");class me extends z.Callable{_call(V,P){throw Error("StoppingCriteria needs to be subclassed")}}class ye extends z.Callable{constructor(){super(),this.criteria=[]}push(V){this.criteria.push(V)}extend(V){V instanceof ye?V=V.criteria:V instanceof me&&(V=[V]),this.criteria.push(...V)}_call(V,P){const te=new Array(V.length).fill(!1);for(const ne of this.criteria){const _e=ne(V,P);for(let ce=0;ceP.length>=this.max_length)}}class Ee extends me{constructor(V){super(),Array.isArray(V)||(V=[V]),this.eos_token_id=V}_call(V,P){return V.map(te=>{const ne=te.at(-1);return this.eos_token_id.some(_e=>ne==_e)})}}class j extends me{constructor(){super(),this.interrupted=!1}interrupt(){this.interrupted=!0}reset(){this.interrupted=!1}_call(V,P){return new Array(V.length).fill(this.interrupted)}}},"./src/generation/streamers.js":(Pt,Ce,N)=>{N.r(Ce),N.d(Ce,{BaseStreamer:()=>Te,TextStreamer:()=>j,WhisperTextStreamer:()=>S});var z=N("./src/utils/core.js"),me=N("./src/tokenizers.js"),ye=N("./src/env.js");class Te{put(P){throw Error("Not implemented")}end(){throw Error("Not implemented")}}const Ee=ye.apis.IS_PROCESS_AVAILABLE?V=>process.stdout.write(V):V=>console.log(V);class j extends Te{constructor(P,{skip_prompt:te=!1,callback_function:ne=null,token_callback_function:_e=null,decode_kwargs:ce={},...D}={}){super(),this.tokenizer=P,this.skip_prompt=te,this.callback_function=ne??Ee,this.token_callback_function=_e,this.decode_kwargs={...ce,...D},this.token_cache=[],this.print_len=0,this.next_tokens_are_prompt=!0}put(P){var ce;if(P.length>1)throw Error("TextStreamer only supports batch size of 1");if(this.skip_prompt&&this.next_tokens_are_prompt){this.next_tokens_are_prompt=!1;return}const te=P[0];(ce=this.token_callback_function)==null||ce.call(this,te),this.token_cache=(0,z.mergeArrays)(this.token_cache,te);const ne=this.tokenizer.decode(this.token_cache,this.decode_kwargs);let _e;ne.endsWith(` -`)?(_e=ne.slice(this.print_len),this.token_cache=[],this.print_len=0):ne.length>0&&(0,me.is_chinese_char)(ne.charCodeAt(ne.length-1))?(_e=ne.slice(this.print_len),this.print_len+=_e.length):(_e=ne.slice(this.print_len,ne.lastIndexOf(" ")+1),this.print_len+=_e.length),this.on_finalized_text(_e,!1)}end(){let P;this.token_cache.length>0?(P=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len),this.token_cache=[],this.print_len=0):P="",this.next_tokens_are_prompt=!0,this.on_finalized_text(P,!0)}on_finalized_text(P,te){var ne,_e;P.length>0&&((ne=this.callback_function)==null||ne.call(this,P)),te&&this.callback_function===Ee&&ye.apis.IS_PROCESS_AVAILABLE&&((_e=this.callback_function)==null||_e.call(this,` -`))}}class S extends j{constructor(P,{skip_prompt:te=!1,callback_function:ne=null,token_callback_function:_e=null,on_chunk_start:ce=null,on_chunk_end:D=null,on_finalize:K=null,time_precision:re=.02,skip_special_tokens:ie=!0,decode_kwargs:X={}}={}){super(P,{skip_prompt:te,callback_function:ne,token_callback_function:_e,decode_kwargs:{skip_special_tokens:ie,...X}}),this.timestamp_begin=P.timestamp_begin,this.on_chunk_start=ce,this.on_chunk_end=D,this.on_finalize=K,this.time_precision=re,this.waiting_for_timestamp=!1}put(P){var ne,_e;if(P.length>1)throw Error("WhisperTextStreamer only supports batch size of 1");const te=P[0];if(te.length===1){const ce=Number(te[0])-this.timestamp_begin;if(ce>=0){const D=ce*this.time_precision;this.waiting_for_timestamp?(ne=this.on_chunk_end)==null||ne.call(this,D):(_e=this.on_chunk_start)==null||_e.call(this,D),this.waiting_for_timestamp=!this.waiting_for_timestamp,P=[[]]}}return super.put(P)}end(){var P;super.end(),(P=this.on_finalize)==null||P.call(this)}}},"./src/models.js":(Pt,Ce,N)=>{N.r(Ce),N.d(Ce,{ASTForAudioClassification:()=>Xn,ASTModel:()=>Kn,ASTPreTrainedModel:()=>Hn,AlbertForMaskedLM:()=>fs,AlbertForQuestionAnswering:()=>hs,AlbertForSequenceClassification:()=>ts,AlbertModel:()=>ps,AlbertPreTrainedModel:()=>Cn,AutoModel:()=>Uu,AutoModelForAudioClassification:()=>sd,AutoModelForAudioFrameClassification:()=>ad,AutoModelForCTC:()=>nd,AutoModelForCausalLM:()=>Ku,AutoModelForDepthEstimation:()=>Rs,AutoModelForDocumentQuestionAnswering:()=>od,AutoModelForImageClassification:()=>Yu,AutoModelForImageFeatureExtraction:()=>Qa,AutoModelForImageMatting:()=>ld,AutoModelForImageSegmentation:()=>Ju,AutoModelForImageToImage:()=>Ud,AutoModelForMaskGeneration:()=>rd,AutoModelForMaskedLM:()=>Xu,AutoModelForNormalEstimation:()=>Xa,AutoModelForObjectDetection:()=>ed,AutoModelForQuestionAnswering:()=>jd,AutoModelForSemanticSegmentation:()=>Zu,AutoModelForSeq2SeqLM:()=>Gu,AutoModelForSequenceClassification:()=>Ka,AutoModelForSpeechSeq2Seq:()=>qu,AutoModelForTextToSpectrogram:()=>Nd,AutoModelForTextToWaveform:()=>Hu,AutoModelForTokenClassification:()=>Wu,AutoModelForUniversalSegmentation:()=>Vd,AutoModelForVision2Seq:()=>Qu,AutoModelForXVector:()=>id,AutoModelForZeroShotObjectDetection:()=>td,BartForConditionalGeneration:()=>m,BartForSequenceClassification:()=>A,BartModel:()=>ue,BartPretrainedModel:()=>ns,BaseModelOutput:()=>dt,BeitForImageClassification:()=>al,BeitModel:()=>il,BeitPreTrainedModel:()=>ta,BertForMaskedLM:()=>Re,BertForQuestionAnswering:()=>qe,BertForSequenceClassification:()=>ht,BertForTokenClassification:()=>bt,BertModel:()=>ot,BertPreTrainedModel:()=>nt,BlenderbotForConditionalGeneration:()=>Ot,BlenderbotModel:()=>Mt,BlenderbotPreTrainedModel:()=>xt,BlenderbotSmallForConditionalGeneration:()=>ar,BlenderbotSmallModel:()=>$r,BlenderbotSmallPreTrainedModel:()=>Yt,BloomForCausalLM:()=>Md,BloomModel:()=>Wi,BloomPreTrainedModel:()=>Ui,CLIPModel:()=>Ei,CLIPPreTrainedModel:()=>ss,CLIPSegForImageSegmentation:()=>ho,CLIPSegModel:()=>po,CLIPSegPreTrainedModel:()=>Si,CLIPTextModel:()=>yd,CLIPTextModelWithProjection:()=>ao,CLIPVisionModel:()=>bd,CLIPVisionModelWithProjection:()=>Pn,CamembertForMaskedLM:()=>cr,CamembertForQuestionAnswering:()=>Or,CamembertForSequenceClassification:()=>Er,CamembertForTokenClassification:()=>Qr,CamembertModel:()=>At,CamembertPreTrainedModel:()=>It,CausalLMOutput:()=>os,CausalLMOutputWithPast:()=>Wd,ChineseCLIPModel:()=>co,ChineseCLIPPreTrainedModel:()=>uo,ClapAudioModelWithProjection:()=>fu,ClapModel:()=>pu,ClapPreTrainedModel:()=>$a,ClapTextModelWithProjection:()=>hu,CodeGenForCausalLM:()=>Fn,CodeGenModel:()=>zi,CodeGenPreTrainedModel:()=>zs,CohereForCausalLM:()=>So,CohereModel:()=>$o,CoherePreTrainedModel:()=>Di,ConvBertForMaskedLM:()=>x,ConvBertForQuestionAnswering:()=>Q,ConvBertForSequenceClassification:()=>q,ConvBertForTokenClassification:()=>$,ConvBertModel:()=>Et,ConvBertPreTrainedModel:()=>vt,ConvNextForImageClassification:()=>Cd,ConvNextModel:()=>Ol,ConvNextPreTrainedModel:()=>ma,ConvNextV2ForImageClassification:()=>Yn,ConvNextV2Model:()=>Qn,ConvNextV2PreTrainedModel:()=>jn,DPTForDepthEstimation:()=>vl,DPTModel:()=>On,DPTPreTrainedModel:()=>ha,DebertaForMaskedLM:()=>U,DebertaForQuestionAnswering:()=>et,DebertaForSequenceClassification:()=>ge,DebertaForTokenClassification:()=>Ae,DebertaModel:()=>at,DebertaPreTrainedModel:()=>Ur,DebertaV2ForMaskedLM:()=>gt,DebertaV2ForQuestionAnswering:()=>ft,DebertaV2ForSequenceClassification:()=>mt,DebertaV2ForTokenClassification:()=>$t,DebertaV2Model:()=>Xe,DebertaV2PreTrainedModel:()=>ve,DecisionTransformerModel:()=>Cu,DecisionTransformerPreTrainedModel:()=>zd,DeiTForImageClassification:()=>ua,DeiTModel:()=>la,DeiTPreTrainedModel:()=>oa,DepthAnythingForDepthEstimation:()=>Tl,DepthAnythingPreTrainedModel:()=>xl,DetrForObjectDetection:()=>ll,DetrForSegmentation:()=>ra,DetrModel:()=>ol,DetrObjectDetectionOutput:()=>na,DetrPreTrainedModel:()=>ei,DetrSegmentationOutput:()=>ul,Dinov2ForImageClassification:()=>fn,Dinov2Model:()=>Jn,Dinov2PreTrainedModel:()=>ni,DistilBertForMaskedLM:()=>tt,DistilBertForQuestionAnswering:()=>be,DistilBertForSequenceClassification:()=>Rt,DistilBertForTokenClassification:()=>Gt,DistilBertModel:()=>Nt,DistilBertPreTrainedModel:()=>zt,DonutSwinModel:()=>zl,DonutSwinPreTrainedModel:()=>Fl,EfficientNetForImageClassification:()=>wu,EfficientNetModel:()=>za,EfficientNetPreTrainedModel:()=>Fa,ElectraForMaskedLM:()=>Je,ElectraForQuestionAnswering:()=>Tt,ElectraForSequenceClassification:()=>Bt,ElectraForTokenClassification:()=>ct,ElectraModel:()=>Ye,ElectraPreTrainedModel:()=>he,EsmForMaskedLM:()=>wr,EsmForSequenceClassification:()=>Br,EsmForTokenClassification:()=>Kr,EsmModel:()=>qt,EsmPreTrainedModel:()=>st,FalconForCausalLM:()=>cu,FalconModel:()=>du,FalconPreTrainedModel:()=>Ea,FastViTForImageClassification:()=>Xo,FastViTModel:()=>Ko,FastViTPreTrainedModel:()=>Yi,Florence2ForConditionalGeneration:()=>or,Florence2PreTrainedModel:()=>Fs,GLPNForDepthEstimation:()=>Il,GLPNModel:()=>Al,GLPNPreTrainedModel:()=>Pl,GPT2LMHeadModel:()=>mo,GPT2Model:()=>fo,GPT2PreTrainedModel:()=>ki,GPTBigCodeForCausalLM:()=>To,GPTBigCodeModel:()=>In,GPTBigCodePreTrainedModel:()=>xo,GPTJForCausalLM:()=>vo,GPTJModel:()=>Mo,GPTJPreTrainedModel:()=>Fi,GPTNeoForCausalLM:()=>wo,GPTNeoModel:()=>go,GPTNeoPreTrainedModel:()=>Ai,GPTNeoXForCausalLM:()=>bo,GPTNeoXModel:()=>yo,GPTNeoXPreTrainedModel:()=>Ii,Gemma2ForCausalLM:()=>Ao,Gemma2Model:()=>zn,Gemma2PreTrainedModel:()=>Bi,GemmaForCausalLM:()=>Po,GemmaModel:()=>ko,GemmaPreTrainedModel:()=>Li,GroupViTModel:()=>vr,GroupViTPreTrainedModel:()=>Ho,HieraForImageClassification:()=>_l,HieraModel:()=>ml,HieraPreTrainedModel:()=>da,HubertForCTC:()=>Jl,HubertForSequenceClassification:()=>Zl,HubertModel:()=>va,HubertPreTrainedModel:()=>Yl,ImageMattingOutput:()=>Ya,JAISLMHeadModel:()=>_o,JAISModel:()=>An,JAISPreTrainedModel:()=>Pi,LlamaForCausalLM:()=>Eo,LlamaModel:()=>Co,LlamaPreTrainedModel:()=>Oi,LlavaForConditionalGeneration:()=>Ci,LlavaPreTrainedModel:()=>Ti,LongT5ForConditionalGeneration:()=>As,LongT5Model:()=>Ps,LongT5PreTrainedModel:()=>_s,M2M100ForConditionalGeneration:()=>ui,M2M100Model:()=>wa,M2M100PreTrainedModel:()=>ga,MBartForCausalLM:()=>wt,MBartForConditionalGeneration:()=>pe,MBartForSequenceClassification:()=>De,MBartModel:()=>se,MBartPreTrainedModel:()=>H,MPNetForMaskedLM:()=>Xs,MPNetForQuestionAnswering:()=>Ss,MPNetForSequenceClassification:()=>Es,MPNetForTokenClassification:()=>$s,MPNetModel:()=>Cs,MPNetPreTrainedModel:()=>Bn,MT5ForConditionalGeneration:()=>ws,MT5Model:()=>Is,MT5PreTrainedModel:()=>gs,MarianMTModel:()=>li,MarianModel:()=>Rl,MarianPreTrainedModel:()=>oi,MaskFormerForInstanceSegmentation:()=>kl,MaskFormerModel:()=>Sl,MaskFormerPreTrainedModel:()=>fa,MaskedLMOutput:()=>an,MistralForCausalLM:()=>lu,MistralModel:()=>ou,MistralPreTrainedModel:()=>Ta,MobileBertForMaskedLM:()=>Vr,MobileBertForQuestionAnswering:()=>Rr,MobileBertForSequenceClassification:()=>Ln,MobileBertModel:()=>Wr,MobileBertPreTrainedModel:()=>rr,MobileNetV1ForImageClassification:()=>bu,MobileNetV1Model:()=>yu,MobileNetV1PreTrainedModel:()=>mi,MobileNetV2ForImageClassification:()=>Mu,MobileNetV2Model:()=>Id,MobileNetV2PreTrainedModel:()=>La,MobileNetV3ForImageClassification:()=>vu,MobileNetV3Model:()=>Fd,MobileNetV3PreTrainedModel:()=>Ba,MobileNetV4ForImageClassification:()=>Tu,MobileNetV4Model:()=>xu,MobileNetV4PreTrainedModel:()=>Ra,MobileViTForImageClassification:()=>Zo,MobileViTModel:()=>Jo,MobileViTPreTrainedModel:()=>Ji,MobileViTV2ForImageClassification:()=>tl,MobileViTV2Model:()=>el,MobileViTV2PreTrainedModel:()=>Zi,ModelOutput:()=>He,Moondream1ForConditionalGeneration:()=>io,MptForCausalLM:()=>No,MptModel:()=>Ro,MptPreTrainedModel:()=>Gi,MusicgenForCausalLM:()=>wc,MusicgenForConditionalGeneration:()=>Da,MusicgenModel:()=>Ad,MusicgenPreTrainedModel:()=>Oa,NomicBertModel:()=>Pe,NomicBertPreTrainedModel:()=>ee,OPTForCausalLM:()=>jo,OPTModel:()=>Os,OPTPreTrainedModel:()=>qi,OpenELMForCausalLM:()=>Fo,OpenELMModel:()=>Io,OpenELMPreTrainedModel:()=>Ri,OwlViTForObjectDetection:()=>nl,OwlViTModel:()=>rl,OwlViTPreTrainedModel:()=>ea,Owlv2ForObjectDetection:()=>Zs,Owlv2Model:()=>sl,Owlv2PreTrainedModel:()=>ys,Phi3ForCausalLM:()=>Bo,Phi3Model:()=>Vi,Phi3PreTrainedModel:()=>Js,PhiForCausalLM:()=>Lo,PhiModel:()=>Do,PhiPreTrainedModel:()=>ji,PreTrainedModel:()=>Y,PretrainedMixin:()=>Ir,PvtForImageClassification:()=>Wo,PvtModel:()=>Uo,PvtPreTrainedModel:()=>Xi,PyAnnoteForAudioFrameClassification:()=>ba,PyAnnoteModel:()=>Vl,PyAnnotePreTrainedModel:()=>bs,QuestionAnsweringModelOutput:()=>cn,Qwen2ForCausalLM:()=>Oo,Qwen2Model:()=>zo,Qwen2PreTrainedModel:()=>Ni,RTDetrForObjectDetection:()=>cl,RTDetrModel:()=>dl,RTDetrObjectDetectionOutput:()=>pl,RTDetrPreTrainedModel:()=>sa,ResNetForImageClassification:()=>wl,ResNetModel:()=>gl,ResNetPreTrainedModel:()=>ca,RoFormerForMaskedLM:()=>Ue,RoFormerForQuestionAnswering:()=>yt,RoFormerForSequenceClassification:()=>je,RoFormerForTokenClassification:()=>lt,RoFormerModel:()=>Qe,RoFormerPreTrainedModel:()=>Ne,RobertaForMaskedLM:()=>ur,RobertaForQuestionAnswering:()=>wn,RobertaForSequenceClassification:()=>Sr,RobertaForTokenClassification:()=>_n,RobertaModel:()=>Jr,RobertaPreTrainedModel:()=>Dr,SamImageSegmentationOutput:()=>ai,SamModel:()=>Bl,SamPreTrainedModel:()=>Ll,SapiensForDepthEstimation:()=>El,SapiensForNormalEstimation:()=>$l,SapiensForSemanticSegmentation:()=>Cl,SapiensPreTrainedModel:()=>ri,SegformerForImageClassification:()=>Ls,SegformerForSemanticSegmentation:()=>Aa,SegformerModel:()=>Pa,SegformerPreTrainedModel:()=>ka,Seq2SeqLMOutput:()=>ud,SequenceClassifierOutput:()=>ir,SiglipModel:()=>oo,SiglipPreTrainedModel:()=>$i,SiglipTextModel:()=>is,SiglipVisionModel:()=>lo,SpeechT5ForSpeechToText:()=>nu,SpeechT5ForTextToSpeech:()=>su,SpeechT5HifiGan:()=>iu,SpeechT5Model:()=>gc,SpeechT5PreTrainedModel:()=>Ds,SqueezeBertForMaskedLM:()=>Qs,SqueezeBertForQuestionAnswering:()=>Sn,SqueezeBertForSequenceClassification:()=>qn,SqueezeBertModel:()=>ks,SqueezeBertPreTrainedModel:()=>Gn,StableLmForCausalLM:()=>gu,StableLmModel:()=>_u,StableLmPreTrainedModel:()=>Ia,Starcoder2ForCausalLM:()=>Pd,Starcoder2Model:()=>uu,Starcoder2PreTrainedModel:()=>Ca,Swin2SRForImageSuperResolution:()=>Ml,Swin2SRModel:()=>Td,Swin2SRPreTrainedModel:()=>pa,SwinForImageClassification:()=>bl,SwinModel:()=>yl,SwinPreTrainedModel:()=>ti,T5ForConditionalGeneration:()=>ms,T5Model:()=>Xt,T5PreTrainedModel:()=>rs,TableTransformerForObjectDetection:()=>fl,TableTransformerModel:()=>hl,TableTransformerObjectDetectionOutput:()=>aa,TableTransformerPreTrainedModel:()=>ia,TokenClassifierOutput:()=>sn,TrOCRForCausalLM:()=>au,TrOCRPreTrainedModel:()=>xa,UniSpeechForCTC:()=>Gl,UniSpeechForSequenceClassification:()=>ql,UniSpeechModel:()=>$d,UniSpeechPreTrainedModel:()=>di,UniSpeechSatForAudioFrameClassification:()=>Xl,UniSpeechSatForCTC:()=>Hl,UniSpeechSatForSequenceClassification:()=>Kl,UniSpeechSatModel:()=>Ma,UniSpeechSatPreTrainedModel:()=>ci,ViTForImageClassification:()=>Vo,ViTMAEModel:()=>Go,ViTMAEPreTrainedModel:()=>vd,ViTMSNForImageClassification:()=>xd,ViTMSNModel:()=>qo,ViTMSNPreTrainedModel:()=>Qi,ViTModel:()=>Ki,ViTPreTrainedModel:()=>Hi,VisionEncoderDecoderModel:()=>Ut,VitMatteForImageMatting:()=>Yo,VitMattePreTrainedModel:()=>Qo,VitsModel:()=>Sa,VitsModelOutput:()=>cd,VitsPreTrainedModel:()=>mu,Wav2Vec2BertForCTC:()=>Ql,Wav2Vec2BertForSequenceClassification:()=>fi,Wav2Vec2BertModel:()=>hi,Wav2Vec2BertPreTrainedModel:()=>pi,Wav2Vec2ForAudioFrameClassification:()=>ya,Wav2Vec2ForCTC:()=>Ed,Wav2Vec2ForSequenceClassification:()=>jl,Wav2Vec2Model:()=>Nl,Wav2Vec2PreTrainedModel:()=>Zn,WavLMForAudioFrameClassification:()=>ru,WavLMForCTC:()=>eu,WavLMForSequenceClassification:()=>tu,WavLMForXVector:()=>kd,WavLMModel:()=>Sd,WavLMPreTrainedModel:()=>as,WeSpeakerResNetModel:()=>Wl,WeSpeakerResNetPreTrainedModel:()=>Ul,WhisperForConditionalGeneration:()=>rt,WhisperModel:()=>Ys,WhisperPreTrainedModel:()=>jt,XLMForQuestionAnswering:()=>Ht,XLMForSequenceClassification:()=>kn,XLMForTokenClassification:()=>Nn,XLMModel:()=>Zr,XLMPreTrainedModel:()=>Se,XLMRobertaForMaskedLM:()=>yr,XLMRobertaForQuestionAnswering:()=>mr,XLMRobertaForSequenceClassification:()=>Ar,XLMRobertaForTokenClassification:()=>Ct,XLMRobertaModel:()=>Xr,XLMRobertaPreTrainedModel:()=>en,XLMWithLMHeadModel:()=>xn,XVectorOutput:()=>dd,YolosForObjectDetection:()=>_a,YolosModel:()=>ii,YolosObjectDetectionOutput:()=>Dl,YolosPreTrainedModel:()=>si});var z=N("./src/configs.js"),me=N("./src/backends/onnx.js"),ye=N("./src/utils/dtypes.js"),Te=N("./src/utils/generic.js"),Ee=N("./src/utils/core.js"),j=N("./src/utils/hub.js"),S=N("./src/generation/logits_process.js"),V=N("./src/generation/configuration_utils.js"),P=N("./src/utils/tensor.js"),te=N("./src/utils/maths.js"),ne=N("./src/generation/stopping_criteria.js"),_e=N("./src/generation/logits_sampler.js"),ce=N("./src/env.js"),D=N("./src/models/whisper/generation_whisper.js"),K=N("./src/models/whisper/common_whisper.js");const re={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,MaskGeneration:5,ImageTextToText:6,Musicgen:7},ie=new Map,X=new Map,R=new Map;async function I(f,_,T){var Tr;const J=((Tr=T.config)==null?void 0:Tr["transformers.js_config"])??{};let Fe=T.device??J.device;Fe&&typeof Fe!="string"&&(Fe.hasOwnProperty(_)?Fe=Fe[_]:(console.warn(`device not specified for "${_}". Using the default device.`),Fe=null));const Oe=Fe??(ce.apis.IS_NODE_ENV?"cpu":"wasm"),_t=(0,me.deviceToExecutionProviders)(Oe);let St=T.dtype??J.dtype;typeof St!="string"&&(St&&St.hasOwnProperty(_)?St=St[_]:(St=ye.DEFAULT_DEVICE_DTYPE_MAPPING[Oe]??ye.DATA_TYPES.fp32,console.warn(`dtype not specified for "${_}". Using the default dtype (${St}) for this device (${Oe}).`)));const Wt=St;if(ye.DEFAULT_DTYPE_SUFFIX_MAPPING.hasOwnProperty(Wt)){if(Wt===ye.DATA_TYPES.fp16&&Oe==="webgpu"&&!await(0,ye.isWebGpuFp16Supported)())throw new Error(`The device (${Oe}) does not support fp16.`)}else throw new Error(`Invalid dtype: ${Wt}. Should be one of: ${Object.keys(ye.DATA_TYPES).join(", ")}`);const nr=ye.DEFAULT_DTYPE_SUFFIX_MAPPING[Wt],kr=`${T.subfolder??""}/${_}${nr}.onnx`,pr={...T.session_options};pr.executionProviders??(pr.executionProviders=_t);const hr=J.free_dimension_overrides;hr?pr.freeDimensionOverrides??(pr.freeDimensionOverrides=hr):Oe.startsWith("webnn")&&!pr.freeDimensionOverrides&&console.warn('WebNN does not currently support dynamic shapes and requires `free_dimension_overrides` to be set in config.json as a field within "transformers.js_config". When `free_dimension_overrides` is not set, you may experience significant performance degradation.');const _r=(0,j.getModelFile)(f,kr,!0,T);let xr=[];if(T.use_external_data_format&&(T.use_external_data_format===!0||typeof T.use_external_data_format=="object"&&T.use_external_data_format.hasOwnProperty(_)&&T.use_external_data_format[_]===!0)){if(ce.apis.IS_NODE_ENV)throw new Error("External data format is not yet supported in Node.js");const gr=`${_}${nr}.onnx_data`,rn=`${T.subfolder??""}/${gr}`;xr.push(new Promise(async(on,bn)=>{const pn=await(0,j.getModelFile)(f,rn,!0,T);on({path:gr,data:pn})}))}else pr.externalData!==void 0&&(xr=pr.externalData.map(async gr=>{if(typeof gr.data=="string"){const rn=await(0,j.getModelFile)(f,gr.data,!0,T);return{...gr,data:rn}}return gr}));if(xr.length>0&&(pr.externalData=await Promise.all(xr)),Oe==="webgpu"){const gr=(0,z.getKeyValueShapes)(T.config,{prefix:"present"});if(Object.keys(gr).length>0&&!(0,me.isONNXProxy)()){const rn={};for(const on in gr)rn[on]="gpu-buffer";pr.preferredOutputLocation=rn}}return{buffer:await _r,session_options:pr}}async function L(f,_,T){return Object.fromEntries(await Promise.all(Object.keys(_).map(async J=>{const{buffer:Fe,session_options:Oe}=await I(f,_[J],T),_t=await(0,me.createInferenceSession)(Fe,Oe);return[J,_t]})))}function k(f,_){const T=Object.create(null),J=[];for(const _t of f.inputNames){const St=_[_t];if(!(St instanceof P.Tensor)){J.push(_t);continue}T[_t]=(0,me.isONNXProxy)()?St.clone():St}if(J.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${J.join(", ")}.`);const Fe=Object.keys(_).length,Oe=f.inputNames.length;if(Fe>Oe){let _t=Object.keys(_).filter(St=>!f.inputNames.includes(St));console.warn(`WARNING: Too many inputs were provided (${Fe} > ${Oe}). The following inputs will be ignored: "${_t.join(", ")}".`)}return T}async function de(f,_){const T=k(f,_);try{const J=Object.fromEntries(Object.entries(T).map(([Oe,_t])=>[Oe,_t.ort_tensor]));let Fe=await f.run(J);return Fe=Me(Fe),Fe}catch(J){throw console.error(`An error occurred during model execution: "${J}".`),console.error("Inputs given to model:",T),J}}function Me(f){for(let _ in f)(0,me.isONNXTensor)(f[_])?f[_]=new P.Tensor(f[_]):typeof f[_]=="object"&&Me(f[_]);return f}function ke(f){if(f instanceof P.Tensor)return f;if(f.length===0)throw Error("items must be non-empty");if(Array.isArray(f[0])){if(f.some(_=>_.length!==f[0].length))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=True' and/or 'truncation=True' to have batched tensors with the same length.");return new P.Tensor("int64",BigInt64Array.from(f.flat().map(_=>BigInt(_))),[f.length,f[0].length])}else return new P.Tensor("int64",BigInt64Array.from(f.map(_=>BigInt(_))),[1,f.length])}function ze(f){return new P.Tensor("bool",[f],[1])}async function Ie(f,_){let{encoder_outputs:T,input_ids:J,decoder_input_ids:Fe,...Oe}=_;if(!T){const St=(0,Ee.pick)(_,f.sessions.model.inputNames);T=(await Ze(f,St)).last_hidden_state}return Oe.input_ids=Fe,Oe.encoder_hidden_states=T,f.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(Oe.encoder_attention_mask=_.attention_mask),await Ke(f,Oe,!0)}async function Ze(f,_){const T=f.sessions.model,J=(0,Ee.pick)(_,T.inputNames);if(T.inputNames.includes("inputs_embeds")&&!J.inputs_embeds){if(!_.input_ids)throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");J.inputs_embeds=await f.encode_text({input_ids:_.input_ids})}return T.inputNames.includes("token_type_ids")&&!J.token_type_ids&&(J.token_type_ids=new P.Tensor("int64",new BigInt64Array(J.input_ids.data.length),J.input_ids.dims)),await de(T,J)}async function Ke(f,_,T=!1){const J=f.sessions[T?"decoder_model_merged":"model"],{past_key_values:Fe,...Oe}=_;J.inputNames.includes("use_cache_branch")&&(Oe.use_cache_branch=ze(!!Fe)),J.inputNames.includes("position_ids")&&Oe.attention_mask&&!Oe.position_ids&&(Oe.position_ids=we(Oe,Fe)),f.addPastKeyValues(Oe,Fe);const _t=(0,Ee.pick)(Oe,J.inputNames);return await de(J,_t)}async function ut(f,{input_ids:_=null,attention_mask:T=null,pixel_values:J=null,position_ids:Fe=null,inputs_embeds:Oe=null,past_key_values:_t=null,generation_config:St=null,logits_processor:Wt=null,...nr}){if(!Oe){if(Oe=await f.encode_text({input_ids:_}),J&&_.dims[1]!==1){const pr=await f.encode_image({pixel_values:J});({inputs_embeds:Oe,attention_mask:T}=f._merge_input_ids_with_image_features({image_features:pr,inputs_embeds:Oe,input_ids:_,attention_mask:T}))}else if(_t&&J&&_.dims[1]===1){const pr=_.dims[1],hr=Object.values(_t)[0].dims.at(-2);T=(0,P.cat)([(0,P.ones)([_.dims[0],hr]),T.slice(null,[T.dims[1]-pr,T.dims[1]])],1)}}return await Ke(f,{inputs_embeds:Oe,past_key_values:_t,attention_mask:T,position_ids:Fe,generation_config:St,logits_processor:Wt},!0)}function we(f,_=null){const{input_ids:T,inputs_embeds:J,attention_mask:Fe}=f,[Oe,_t]=Fe.dims,St=new BigInt64Array(Fe.data.length);for(let nr=0;nrOe.dims[1])){if(FeSt==f.config.image_token_index)){const St=f.config.num_image_tokens;if(!St)throw new Error("`num_image_tokens` is missing in the model configuration.");const Wt=Oe.dims[1]-(Fe-St);T.input_ids=Oe.slice(null,[-Wt,null]),T.attention_mask=(0,P.ones)([1,Fe+Wt])}}}return T}function fe(f,_,T,J){return T.past_key_values&&(_=_.map(Fe=>[Fe.at(-1)])),{...T,decoder_input_ids:ke(_)}}function $e(f,..._){return f.config.is_encoder_decoder?fe(f,..._):W(f,..._)}class Y extends Te.Callable{constructor(T,J){super();xe(this,"main_input_name","input_ids");xe(this,"forward_params",["input_ids","attention_mask"]);this.config=T,this.sessions=J;const Fe=R.get(this.constructor),Oe=ie.get(Fe);switch(this.can_generate=!1,this._forward=null,this._prepare_inputs_for_generation=null,Oe){case re.DecoderOnly:this.can_generate=!0,this._forward=Ke,this._prepare_inputs_for_generation=W;break;case re.Seq2Seq:case re.Vision2Seq:case re.Musicgen:this.can_generate=!0,this._forward=Ie,this._prepare_inputs_for_generation=fe;break;case re.EncoderDecoder:this._forward=Ie;break;case re.ImageTextToText:this.can_generate=!0,this._forward=ut,this._prepare_inputs_for_generation=$e;break;default:this._forward=Ze;break}this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){var J;const T=[];for(const Fe of Object.values(this.sessions))(J=Fe==null?void 0:Fe.handler)!=null&&J.dispose&&T.push(Fe.handler.dispose());return await Promise.all(T)}static async from_pretrained(T,{progress_callback:J=null,config:Fe=null,cache_dir:Oe=null,local_files_only:_t=!1,revision:St="main",model_file_name:Wt=null,subfolder:nr="onnx",device:kr=null,dtype:pr=null,use_external_data_format:hr=null,session_options:_r={}}={}){let xr={progress_callback:J,config:Fe,cache_dir:Oe,local_files_only:_t,revision:St,model_file_name:Wt,subfolder:nr,device:kr,dtype:pr,use_external_data_format:hr,session_options:_r};const Fr=R.get(this),Tr=ie.get(Fr);Fe=xr.config=await z.AutoConfig.from_pretrained(T,xr);let gr;if(Tr===re.DecoderOnly)gr=await Promise.all([L(T,{model:xr.model_file_name??"model"},xr),(0,j.getModelJSON)(T,"generation_config.json",!1,xr)]);else if(Tr===re.Seq2Seq||Tr===re.Vision2Seq)gr=await Promise.all([L(T,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},xr),(0,j.getModelJSON)(T,"generation_config.json",!1,xr)]);else if(Tr===re.MaskGeneration)gr=await Promise.all([L(T,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},xr)]);else if(Tr===re.EncoderDecoder)gr=await Promise.all([L(T,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},xr)]);else if(Tr===re.ImageTextToText){const rn={embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};Fe.is_encoder_decoder&&(rn.model="encoder_model"),gr=await Promise.all([L(T,rn,xr),(0,j.getModelJSON)(T,"generation_config.json",!1,xr)])}else Tr===re.Musicgen?gr=await Promise.all([L(T,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},xr),(0,j.getModelJSON)(T,"generation_config.json",!1,xr)]):(Tr!==re.EncoderOnly&&console.warn(`Model type for '${Fr??(Fe==null?void 0:Fe.model_type)}' not found, assuming encoder-only architecture. Please report this at https://github.com/xenova/transformers.js/issues/new/choose.`),gr=await Promise.all([L(T,{model:xr.model_file_name??"model"},xr)]));return new this(Fe,...gr)}async _call(T){return await this.forward(T)}async forward(T){return await this._forward(this,T)}_get_logits_warper(T){const J=new S.LogitsProcessorList;return T.temperature!==null&&T.temperature!==1&&J.push(new S.TemperatureLogitsWarper(T.temperature)),T.top_k!==null&&T.top_k!==0&&J.push(new S.TopKLogitsWarper(T.top_k)),T.top_p!==null&&T.top_p<1&&J.push(new S.TopPLogitsWarper(T.top_p)),J}_get_logits_processor(T,J,Fe=null){const Oe=new S.LogitsProcessorList;if(T.repetition_penalty!==null&&T.repetition_penalty!==1&&Oe.push(new S.RepetitionPenaltyLogitsProcessor(T.repetition_penalty)),T.no_repeat_ngram_size!==null&&T.no_repeat_ngram_size>0&&Oe.push(new S.NoRepeatNGramLogitsProcessor(T.no_repeat_ngram_size)),T.bad_words_ids!==null&&Oe.push(new S.NoBadWordsLogitsProcessor(T.bad_words_ids,T.eos_token_id)),T.min_length!==null&&T.eos_token_id!==null&&T.min_length>0&&Oe.push(new S.MinLengthLogitsProcessor(T.min_length,T.eos_token_id)),T.min_new_tokens!==null&&T.eos_token_id!==null&&T.min_new_tokens>0&&Oe.push(new S.MinNewTokensLengthLogitsProcessor(J,T.min_new_tokens,T.eos_token_id)),T.forced_bos_token_id!==null&&Oe.push(new S.ForcedBOSTokenLogitsProcessor(T.forced_bos_token_id)),T.forced_eos_token_id!==null&&Oe.push(new S.ForcedEOSTokenLogitsProcessor(T.max_length,T.forced_eos_token_id)),T.begin_suppress_tokens!==null){const _t=J>1||T.forced_bos_token_id===null?J:J+1;Oe.push(new S.SuppressTokensAtBeginLogitsProcessor(T.begin_suppress_tokens,_t))}return T.guidance_scale!==null&&T.guidance_scale>1&&Oe.push(new S.ClassifierFreeGuidanceLogitsProcessor(T.guidance_scale)),Fe!==null&&Oe.extend(Fe),Oe}_prepare_generation_config(T,J,Fe=V.GenerationConfig){const Oe={...this.config};for(const St of["decoder","generator","text_config"])St in Oe&&Object.assign(Oe,Oe[St]);const _t=new Fe(Oe);return"generation_config"in this&&Object.assign(_t,this.generation_config),T&&Object.assign(_t,T),J&&Object.assign(_t,(0,Ee.pick)(J,Object.getOwnPropertyNames(_t))),_t}_get_stopping_criteria(T,J=null){const Fe=new ne.StoppingCriteriaList;return T.max_length!==null&&Fe.push(new ne.MaxLengthCriteria(T.max_length,this.config.max_position_embeddings??null)),T.eos_token_id!==null&&Fe.push(new ne.EosTokenCriteria(T.eos_token_id)),J&&Fe.extend(J),Fe}_validate_model_class(){if(!this.can_generate){const T=[Va,Au,ja,Na],J=R.get(this.constructor),Fe=new Set,Oe=this.config.model_type;for(const St of T){const Wt=St.get(Oe);Wt&&Fe.add(Wt[0])}let _t=`The current model class (${J}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw Fe.size>0&&(_t+=` Please use the following class instead: ${[...Fe].join(", ")}`),Error(_t)}}prepare_inputs_for_generation(...T){return this._prepare_inputs_for_generation(this,...T)}_update_model_kwargs_for_generation({generated_input_ids:T,outputs:J,model_inputs:Fe,is_encoder_decoder:Oe}){return Fe.past_key_values=this.getPastKeyValues(J,Fe.past_key_values),Fe.input_ids=new P.Tensor("int64",T.flat(),[T.length,1]),Oe||(Fe.attention_mask=(0,P.cat)([Fe.attention_mask,(0,P.ones)([Fe.attention_mask.dims[0],1])],1)),Fe.position_ids=null,Fe}_prepare_model_inputs({inputs:T,bos_token_id:J,model_kwargs:Fe}){const Oe=(0,Ee.pick)(Fe,this.forward_params),_t=this.main_input_name;if(_t in Oe){if(T)throw new Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else Oe[_t]=T;return{inputs_tensor:Oe[_t],model_inputs:Oe,model_input_name:_t}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:T,model_inputs:J,model_input_name:Fe,generation_config:Oe}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!J.inputs_embeds&&"_prepare_inputs_embeds"in this){const{input_ids:St,pixel_values:Wt,attention_mask:nr,...kr}=J,pr=await this._prepare_inputs_embeds(J);J={...kr,...(0,Ee.pick)(pr,["inputs_embeds","attention_mask"])}}let{last_hidden_state:_t}=await Ze(this,J);if(Oe.guidance_scale!==null&&Oe.guidance_scale>1)_t=(0,P.cat)([_t,(0,P.full_like)(_t,0)],0),"attention_mask"in J&&(J.attention_mask=(0,P.cat)([J.attention_mask,(0,P.zeros_like)(J.attention_mask)],0));else if(J.decoder_input_ids){const St=ke(J.decoder_input_ids).dims[0];if(St!==_t.dims[0]){if(_t.dims[0]!==1)throw new Error(`The encoder outputs have a different batch size (${_t.dims[0]}) than the decoder inputs (${St}).`);_t=(0,P.cat)(Array.from({length:St},()=>_t),0)}}return J.encoder_outputs=_t,J}_prepare_decoder_input_ids_for_generation({batch_size:T,model_input_name:J,model_kwargs:Fe,decoder_start_token_id:Oe,bos_token_id:_t,generation_config:St}){let{decoder_input_ids:Wt,...nr}=Fe;if(Wt)Array.isArray(Wt[0])||(Wt=Array.from({length:T},()=>Wt));else if(Oe??(Oe=_t),this.config.model_type==="musicgen")Wt=Array.from({length:T*this.config.decoder.num_codebooks},()=>[Oe]);else if(Array.isArray(Oe)){if(Oe.length!==T)throw new Error(`\`decoder_start_token_id\` expcted to have length ${T} but got ${Oe.length}`);Wt=Oe}else Wt=Array.from({length:T},()=>[Oe]);return Wt=ke(Wt),Fe.decoder_attention_mask=(0,P.ones_like)(Wt),{input_ids:Wt,model_inputs:nr}}async generate({inputs:T=null,generation_config:J=null,logits_processor:Fe=null,stopping_criteria:Oe=null,streamer:_t=null,...St}){this._validate_model_class(),J=this._prepare_generation_config(J,St);let{inputs_tensor:Wt,model_inputs:nr,model_input_name:kr}=this._prepare_model_inputs({inputs:T,model_kwargs:St});const pr=this.config.is_encoder_decoder;pr&&("encoder_outputs"in nr||(nr=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:Wt,model_inputs:nr,model_input_name:kr,generation_config:J})));let hr;pr?{input_ids:hr,model_inputs:nr}=this._prepare_decoder_input_ids_for_generation({batch_size:nr[kr].dims.at(0),model_input_name:kr,model_kwargs:nr,decoder_start_token_id:J.decoder_start_token_id,bos_token_id:J.bos_token_id,generation_config:J}):hr=nr[kr];let _r=hr.dims.at(-1);J.max_new_tokens!==null&&(J.max_length=_r+J.max_new_tokens);const xr=this._get_logits_processor(J,_r,Fe),Fr=this._get_stopping_criteria(J,Oe),Tr=nr[kr].dims.at(0),gr=_e.LogitsSampler.getSampler(J),rn=new Array(Tr).fill(0),on=hr.tolist();_t&&_t.put(on);let bn,pn={};for(;;){if(nr=this.prepare_inputs_for_generation(on,nr,J),bn=await this.forward(nr),J.output_attentions&&J.return_dict_in_generate){const Rn=this.getAttentions(bn);for(const vs in Rn)vs in pn||(pn[vs]=[]),pn[vs].push(Rn[vs])}const Ms=bn.logits.slice(null,-1,null),_i=xr(on,Ms),Ja=[];for(let Rn=0;Rn<_i.dims.at(0);++Rn){const vs=_i[Rn],qd=await gr(vs);for(const[Hd,Kd]of qd){const pd=BigInt(Hd);rn[Rn]+=Kd,on[Rn].push(pd),Ja.push([pd]);break}}if(_t&&_t.put(Ja),Fr(on).every(Rn=>Rn))break;nr=this._update_model_kwargs_for_generation({generated_input_ids:Ja,outputs:bn,model_inputs:nr,is_encoder_decoder:pr})}_t&&_t.end();const ln=this.getPastKeyValues(bn,nr.past_key_values,!0),Mn=new P.Tensor("int64",on.flat(),[on.length,on[0].length]);if(J.return_dict_in_generate)return{sequences:Mn,past_key_values:ln,...pn};for(const Ms of Object.values(bn))Ms.location==="gpu-buffer"&&Ms.dispose();return Mn}getPastKeyValues(T,J,Fe=!1){const Oe=Object.create(null);for(const _t in T)if(_t.startsWith("present")){const St=_t.replace("present","past_key_values"),Wt=_t.includes("encoder");if(Wt&&J?Oe[St]=J[St]:Oe[St]=T[_t],J&&(!Wt||Fe)){const nr=J[St];nr.location==="gpu-buffer"&&nr.dispose()}}return Oe}getAttentions(T){const J={};for(const Fe of["cross_attentions","encoder_attentions","decoder_attentions"])for(const Oe in T)Oe.startsWith(Fe)&&(Fe in J||(J[Fe]=[]),J[Fe].push(T[Oe]));return J}addPastKeyValues(T,J){if(J)Object.assign(T,J);else{const Fe=this.custom_config.kv_cache_dtype??"float32",Oe=Fe==="float16"?new Uint16Array:[],_t=(0,z.getKeyValueShapes)(this.config);for(const St in _t)T[St]=new P.Tensor(Fe,Oe,_t[St])}}async encode_image({pixel_values:T}){const J=(await de(this.sessions.vision_encoder,{pixel_values:T})).image_features;return this.config.num_image_tokens||(console.warn(`The number of image tokens was not set in the model configuration. Setting it to the number of features detected by the vision encoder (${J.dims[1]}).`),this.config.num_image_tokens=J.dims[1]),J}async encode_text({input_ids:T}){return(await de(this.sessions.embed_tokens,{input_ids:T})).inputs_embeds}}class He{}class dt extends He{constructor({last_hidden_state:_,hidden_states:T=null,attentions:J=null}){super(),this.last_hidden_state=_,this.hidden_states=T,this.attentions=J}}class nt extends Y{}class ot extends nt{}class Re extends nt{async _call(_){return new an(await super._call(_))}}class ht extends nt{async _call(_){return new ir(await super._call(_))}}class bt extends nt{async _call(_){return new sn(await super._call(_))}}class qe extends nt{async _call(_){return new cn(await super._call(_))}}class ee extends Y{}class Pe extends ee{}class Ne extends Y{}class Qe extends Ne{}class Ue extends Ne{async _call(_){return new an(await super._call(_))}}class je extends Ne{async _call(_){return new ir(await super._call(_))}}class lt extends Ne{async _call(_){return new sn(await super._call(_))}}class yt extends Ne{async _call(_){return new cn(await super._call(_))}}class vt extends Y{}class Et extends vt{}class x extends vt{async _call(_){return new an(await super._call(_))}}class q extends vt{async _call(_){return new ir(await super._call(_))}}class $ extends vt{async _call(_){return new sn(await super._call(_))}}class Q extends vt{async _call(_){return new cn(await super._call(_))}}class he extends Y{}class Ye extends he{}class Je extends he{async _call(_){return new an(await super._call(_))}}class Bt extends he{async _call(_){return new ir(await super._call(_))}}class ct extends he{async _call(_){return new sn(await super._call(_))}}class Tt extends he{async _call(_){return new cn(await super._call(_))}}class It extends Y{}class At extends It{}class cr extends It{async _call(_){return new an(await super._call(_))}}class Er extends It{async _call(_){return new ir(await super._call(_))}}class Qr extends It{async _call(_){return new sn(await super._call(_))}}class Or extends It{async _call(_){return new cn(await super._call(_))}}class Ur extends Y{}class at extends Ur{}class U extends Ur{async _call(_){return new an(await super._call(_))}}class ge extends Ur{async _call(_){return new ir(await super._call(_))}}class Ae extends Ur{async _call(_){return new sn(await super._call(_))}}class et extends Ur{async _call(_){return new cn(await super._call(_))}}class ve extends Y{}class Xe extends ve{}class gt extends ve{async _call(_){return new an(await super._call(_))}}class mt extends ve{async _call(_){return new ir(await super._call(_))}}class $t extends ve{async _call(_){return new sn(await super._call(_))}}class ft extends ve{async _call(_){return new cn(await super._call(_))}}class zt extends Y{}class Nt extends zt{}class Rt extends zt{async _call(_){return new ir(await super._call(_))}}class Gt extends zt{async _call(_){return new sn(await super._call(_))}}class be extends zt{async _call(_){return new cn(await super._call(_))}}class tt extends zt{async _call(_){return new an(await super._call(_))}}class st extends Y{}class qt extends st{}class wr extends st{async _call(_){return new an(await super._call(_))}}class Br extends st{async _call(_){return new ir(await super._call(_))}}class Kr extends st{async _call(_){return new sn(await super._call(_))}}class rr extends Y{}class Wr extends rr{}class Vr extends rr{async _call(_){return new an(await super._call(_))}}class Ln extends rr{async _call(_){return new ir(await super._call(_))}}class Rr extends rr{async _call(_){return new cn(await super._call(_))}}class Bn extends Y{}class Cs extends Bn{}class Xs extends Bn{async _call(_){return new an(await super._call(_))}}class Es extends Bn{async _call(_){return new ir(await super._call(_))}}class $s extends Bn{async _call(_){return new sn(await super._call(_))}}class Ss extends Bn{async _call(_){return new cn(await super._call(_))}}class Gn extends Y{}class ks extends Gn{}class Qs extends Gn{async _call(_){return new an(await super._call(_))}}class qn extends Gn{async _call(_){return new ir(await super._call(_))}}class Sn extends Gn{async _call(_){return new cn(await super._call(_))}}class Cn extends Y{}class ps extends Cn{}class ts extends Cn{async _call(_){return new ir(await super._call(_))}}class hs extends Cn{async _call(_){return new cn(await super._call(_))}}class fs extends Cn{async _call(_){return new an(await super._call(_))}}class rs extends Y{constructor(T,J,Fe){super(T,J);xe(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"]);this.generation_config=Fe}}class Xt extends rs{}class ms extends rs{}class _s extends Y{constructor(_,T,J){super(_,T),this.generation_config=J}}class Ps extends _s{}class As extends _s{}class gs extends Y{constructor(_,T,J){super(_,T),this.generation_config=J}}class Is extends gs{}class ws extends gs{}class ns extends Y{constructor(_,T,J){super(_,T),this.generation_config=J}}class ue extends ns{}class m extends ns{}class A extends ns{async _call(_){return new ir(await super._call(_))}}class H extends Y{constructor(_,T,J){super(_,T),this.generation_config=J}}class se extends H{}class pe extends H{}class De extends H{async _call(_){return new ir(await super._call(_))}}class wt extends H{}class xt extends Y{constructor(_,T,J){super(_,T),this.generation_config=J}}class Mt extends xt{}class Ot extends xt{}class Yt extends Y{constructor(_,T,J){super(_,T),this.generation_config=J}}class $r extends Yt{}class ar extends Yt{}class Dr extends Y{}class Jr extends Dr{}class ur extends Dr{async _call(_){return new an(await super._call(_))}}class Sr extends Dr{async _call(_){return new ir(await super._call(_))}}class _n extends Dr{async _call(_){return new sn(await super._call(_))}}class wn extends Dr{async _call(_){return new cn(await super._call(_))}}class Se extends Y{}class Zr extends Se{}class xn extends Se{async _call(_){return new an(await super._call(_))}}class kn extends Se{async _call(_){return new ir(await super._call(_))}}class Nn extends Se{async _call(_){return new sn(await super._call(_))}}class Ht extends Se{async _call(_){return new cn(await super._call(_))}}class en extends Y{}class Xr extends en{}class yr extends en{async _call(_){return new an(await super._call(_))}}class Ar extends en{async _call(_){return new ir(await super._call(_))}}class Ct extends en{async _call(_){return new sn(await super._call(_))}}class mr extends en{async _call(_){return new cn(await super._call(_))}}class Hn extends Y{}class Kn extends Hn{}class Xn extends Hn{}class jt extends Y{constructor(T,J,Fe){super(T,J);xe(this,"requires_attention_mask",!1);xe(this,"main_input_name","input_features");xe(this,"forward_params",["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"]);this.generation_config=Fe}}class Ys extends jt{}class rt extends jt{_prepare_generation_config(_,T){return super._prepare_generation_config(_,T,D.WhisperGenerationConfig)}_retrieve_init_tokens(_){const T=[_.decoder_start_token_id];let J=_.language;const Fe=_.task;if(_.is_multilingual){J||(console.warn("No language specified - defaulting to English (en)."),J="en");const _t=`<|${(0,K.whisper_language_to_code)(J)}|>`;T.push(_.lang_to_id[_t]),T.push(_.task_to_id[Fe??"transcribe"])}else if(J||Fe)throw new Error("Cannot specify `task` or `language` for an English-only model. If the model is intended to be multilingual, pass `is_multilingual=true` to generate, or update the generation config.");return!_.return_timestamps&&_.no_timestamps_token_id&&T.at(-1)!==_.no_timestamps_token_id?T.push(_.no_timestamps_token_id):_.return_timestamps&&T.at(-1)===_.no_timestamps_token_id&&(console.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),T.pop()),T.filter(Oe=>Oe!=null)}async generate({inputs:_=null,generation_config:T=null,logits_processor:J=null,stopping_criteria:Fe=null,...Oe}){T=this._prepare_generation_config(T,Oe);const _t=Oe.decoder_input_ids??this._retrieve_init_tokens(T);if(T.return_timestamps&&(J??(J=new S.LogitsProcessorList),J.push(new S.WhisperTimeStampLogitsProcessor(T,_t))),T.begin_suppress_tokens&&(J??(J=new S.LogitsProcessorList),J.push(new S.SuppressTokensAtBeginLogitsProcessor(T.begin_suppress_tokens,_t.length))),T.return_token_timestamps){if(!T.alignment_heads)throw new Error("Model generation config has no `alignment_heads`, token-level timestamps not available. See https://gist.github.com/hollance/42e32852f24243b748ae6bc1f985b13a on how to add this property to the generation config.");T.task==="translate"&&console.warn("Token-level timestamps may not be reliable for task 'translate'."),T.output_attentions=!0,T.return_dict_in_generate=!0}const St=await super.generate({inputs:_,generation_config:T,logits_processor:J,decoder_input_ids:_t,...Oe});return T.return_token_timestamps&&(St.token_timestamps=this._extract_token_timestamps(St,T.alignment_heads,T.num_frames)),St}_extract_token_timestamps(_,T,J=null,Fe=.02){if(!_.cross_attentions)throw new Error("Model outputs must contain cross attentions to extract timestamps. This is most likely because the model was not exported with `output_attentions=True`.");J==null&&console.warn("`num_frames` has not been set, meaning the entire audio will be analyzed. This may lead to inaccurate token-level timestamps for short audios (< 30 seconds).");let Oe=this.config.median_filter_width;Oe===void 0&&(console.warn("Model config has no `median_filter_width`, using default value of 7."),Oe=7);const _t=_.cross_attentions,St=Array.from({length:this.config.decoder_layers},(Fr,Tr)=>(0,P.cat)(_t.map(gr=>gr[Tr]),2)),Wt=(0,P.stack)(T.map(([Fr,Tr])=>{if(Fr>=St.length)throw new Error(`Layer index ${Fr} is out of bounds for cross attentions (length ${St.length}).`);return J?St[Fr].slice(null,Tr,null,[0,J]):St[Fr].slice(null,Tr)})).transpose(1,0,2,3),[nr,kr]=(0,P.std_mean)(Wt,-2,0,!0),pr=Wt.clone();for(let Fr=0;Frgr[Mn+1]-gr[Mn]),bn=(0,Ee.mergeArrays)([1],on).map(ln=>!!ln),pn=[];for(let ln=0;lnhr.findIndex(_r=>_r==Oe)),Wt=St.every(hr=>hr===-1),nr=St.every(hr=>hr!==-1);if(!Wt&&!nr)throw new Error("Every input should contain either 0 or 1 image token.");if(Wt)return{inputs_embeds:_,attention_mask:Fe};const kr=[],pr=[];for(let hr=0;hrOe*_t,1);_.input_labels=new P.Tensor("int64",new BigInt64Array(Fe).fill(1n),J)}const T={image_embeddings:_.image_embeddings,image_positional_embeddings:_.image_positional_embeddings};return _.input_points&&(T.input_points=_.input_points),_.input_labels&&(T.input_labels=_.input_labels),_.input_boxes&&(T.input_boxes=_.input_boxes),await de(this.sessions.prompt_encoder_mask_decoder,T)}async _call(_){return new ai(await super._call(_))}}class ai extends He{constructor({iou_scores:_,pred_masks:T}){super(),this.iou_scores=_,this.pred_masks=T}}class oi extends Y{constructor(_,T,J){super(_,T),this.generation_config=J}}class Rl extends oi{}class li extends oi{}class ga extends Y{constructor(_,T,J){super(_,T),this.generation_config=J}}class wa extends ga{}class ui extends ga{}class Zn extends Y{}class Nl extends Zn{}class Ed extends Zn{async _call(_){return new os(await super._call(_))}}class jl extends Zn{async _call(_){return new ir(await super._call(_))}}class ya extends Zn{async _call(_){return new sn(await super._call(_))}}class bs extends Y{}class Vl extends bs{}class ba extends bs{async _call(_){return new sn(await super._call(_))}}class Ul extends Y{}class Wl extends Ul{}class di extends Y{}class $d extends di{}class Gl extends di{async _call(_){return new os(await super._call(_))}}class ql extends di{async _call(_){return new ir(await super._call(_))}}class ci extends Y{}class Ma extends ci{}class Hl extends ci{async _call(_){return new os(await super._call(_))}}class Kl extends ci{async _call(_){return new ir(await super._call(_))}}class Xl extends ci{async _call(_){return new sn(await super._call(_))}}class pi extends Y{}class hi extends pi{}class Ql extends pi{async _call(_){return new os(await super._call(_))}}class fi extends pi{async _call(_){return new ir(await super._call(_))}}class Yl extends Y{}class va extends Zn{}class Jl extends Zn{async _call(_){return new os(await super._call(_))}}class Zl extends Zn{async _call(_){return new ir(await super._call(_))}}class as extends Y{}class Sd extends as{}class eu extends as{async _call(_){return new os(await super._call(_))}}class tu extends as{async _call(_){return new ir(await super._call(_))}}class kd extends as{async _call(_){return new dd(await super._call(_))}}class ru extends as{async _call(_){return new sn(await super._call(_))}}class Ds extends Y{constructor(_,T,J){super(_,T),this.generation_config=J}}class gc extends Ds{}class nu extends Ds{}class su extends Ds{async generate_speech(_,T,{threshold:J=.5,minlenratio:Fe=0,maxlenratio:Oe=20,vocoder:_t=null}={}){const St={input_ids:_},{encoder_outputs:Wt,encoder_attention_mask:nr}=await Ze(this,St),kr=Wt.dims[1]/this.config.reduction_factor,pr=Math.floor(kr*Oe),hr=Math.floor(kr*Fe),_r=this.config.num_mel_bins;let xr=[],Fr=null,Tr=null,gr=0;for(;;){++gr;const bn=ze(!!Tr);let pn;Tr?pn=Tr.output_sequence_out:pn=new P.Tensor("float32",new Float32Array(_r),[1,1,_r]);let ln={use_cache_branch:bn,output_sequence:pn,encoder_attention_mask:nr,speaker_embeddings:T,encoder_hidden_states:Wt};this.addPastKeyValues(ln,Fr),Tr=await de(this.sessions.decoder_model_merged,ln),Fr=this.getPastKeyValues(Tr,Fr);const{prob:Mn,spectrum:Ms}=Tr;if(xr.push(Ms),gr>=hr&&(Array.from(Mn.data).filter(_i=>_i>=J).length>0||gr>=pr))break}const rn=(0,P.cat)(xr),{waveform:on}=await de(_t.sessions.model,{spectrogram:rn});return{spectrogram:rn,waveform:on}}}class iu extends Y{constructor(){super(...arguments);xe(this,"main_input_name","spectrogram")}}class xa extends Y{constructor(_,T,J){super(_,T),this.generation_config=J}}class au extends xa{}class Ta extends Y{constructor(_,T,J){super(_,T),this.generation_config=J}}class ou extends Ta{}class lu extends Ta{}class Ca extends Y{constructor(_,T,J){super(_,T),this.generation_config=J}}class uu extends Ca{}class Pd extends Ca{}class Ea extends Y{constructor(_,T,J){super(_,T),this.generation_config=J}}class du extends Ea{}class cu extends Ea{}class $a extends Y{}class pu extends $a{}class hu extends $a{static async from_pretrained(_,T={}){return T.model_file_name??(T.model_file_name="text_model"),super.from_pretrained(_,T)}}class fu extends $a{static async from_pretrained(_,T={}){return T.model_file_name??(T.model_file_name="audio_model"),super.from_pretrained(_,T)}}class mu extends Y{}class Sa extends mu{async _call(_){return new cd(await super._call(_))}}class ka extends Y{}class Pa extends ka{}class Ls extends ka{}class Aa extends ka{}class Ia extends Y{constructor(_,T,J){super(_,T),this.generation_config=J}}class _u extends Ia{}class gu extends Ia{}class Fa extends Y{}class za extends Fa{}class wu extends Fa{async _call(_){return new ir(await super._call(_))}}class Oa extends Y{}class Ad extends Oa{}class wc extends Oa{}class Da extends Y{constructor(T,J,Fe){super(T,J);xe(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"]);this.generation_config=Fe}_apply_and_filter_by_delay_pattern_mask(T){const[J,Fe]=T.dims,Oe=this.config.decoder.num_codebooks,_t=Fe-Oe;let St=0;for(let kr=0;kr0&&_r<=_t&&(T.data[St++]=T.data[kr])}const Wt=Math.floor(J/Oe),nr=St/(Wt*Oe);return new P.Tensor(T.type,T.data.slice(0,St),[Wt,Oe,nr])}prepare_inputs_for_generation(T,J,Fe){let Oe=structuredClone(T);for(let St=0;St=Wt&&(Oe[St][Wt]=BigInt(this.config.decoder.pad_token_id));return Fe.guidance_scale!==null&&Fe.guidance_scale>1&&(Oe=Oe.concat(Oe)),super.prepare_inputs_for_generation(Oe,J,Fe)}async generate(T){const J=await super.generate(T),Fe=this._apply_and_filter_by_delay_pattern_mask(J).unsqueeze_(0),{audio_values:Oe}=await de(this.sessions.encodec_decode,{audio_codes:Fe});return Oe}}class mi extends Y{}class yu extends mi{}class bu extends mi{async _call(_){return new ir(await super._call(_))}}class La extends Y{}class Id extends La{}class Mu extends La{async _call(_){return new ir(await super._call(_))}}class Ba extends Y{}class Fd extends Ba{}class vu extends Ba{async _call(_){return new ir(await super._call(_))}}class Ra extends Y{}class xu extends Ra{}class Tu extends Ra{async _call(_){return new ir(await super._call(_))}}class zd extends Y{}class Cu extends zd{}class Ir{static async from_pretrained(_,{progress_callback:T=null,config:J=null,cache_dir:Fe=null,local_files_only:Oe=!1,revision:_t="main",model_file_name:St=null,subfolder:Wt="onnx",device:nr=null,dtype:kr=null,use_external_data_format:pr=null,session_options:hr={}}={}){const _r={progress_callback:T,config:J,cache_dir:Fe,local_files_only:Oe,revision:_t,model_file_name:St,subfolder:Wt,device:nr,dtype:kr,use_external_data_format:pr,session_options:hr};if(_r.config=await z.AutoConfig.from_pretrained(_,_r),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);for(const xr of this.MODEL_CLASS_MAPPINGS){const Fr=xr.get(_r.config.model_type);if(Fr)return await Fr[1].from_pretrained(_,_r)}if(this.BASE_IF_FAIL)return console.warn(`Unknown model class "${_r.config.model_type}", attempting to construct from base class.`),await Y.from_pretrained(_,_r);throw Error(`Unsupported model type: ${_r.config.model_type}`)}}xe(Ir,"MODEL_CLASS_MAPPINGS",null),xe(Ir,"BASE_IF_FAIL",!1);const Od=new Map([["bert",["BertModel",ot]],["nomic_bert",["NomicBertModel",Pe]],["roformer",["RoFormerModel",Qe]],["electra",["ElectraModel",Ye]],["esm",["EsmModel",qt]],["convbert",["ConvBertModel",Et]],["camembert",["CamembertModel",At]],["deberta",["DebertaModel",at]],["deberta-v2",["DebertaV2Model",Xe]],["mpnet",["MPNetModel",Cs]],["albert",["AlbertModel",ps]],["distilbert",["DistilBertModel",Nt]],["roberta",["RobertaModel",Jr]],["xlm",["XLMModel",Zr]],["xlm-roberta",["XLMRobertaModel",Xr]],["clap",["ClapModel",pu]],["clip",["CLIPModel",Ei]],["clipseg",["CLIPSegModel",po]],["chinese_clip",["ChineseCLIPModel",co]],["siglip",["SiglipModel",oo]],["mobilebert",["MobileBertModel",Wr]],["squeezebert",["SqueezeBertModel",ks]],["wav2vec2",["Wav2Vec2Model",Nl]],["wav2vec2-bert",["Wav2Vec2BertModel",hi]],["unispeech",["UniSpeechModel",$d]],["unispeech-sat",["UniSpeechSatModel",Ma]],["hubert",["HubertModel",va]],["wavlm",["WavLMModel",Sd]],["audio-spectrogram-transformer",["ASTModel",Kn]],["vits",["VitsModel",Sa]],["pyannote",["PyAnnoteModel",Vl]],["wespeaker-resnet",["WeSpeakerResNetModel",Wl]],["detr",["DetrModel",ol]],["rt_detr",["RTDetrModel",dl]],["table-transformer",["TableTransformerModel",hl]],["vit",["ViTModel",Ki]],["pvt",["PvtModel",Uo]],["vit_msn",["ViTMSNModel",qo]],["vit_mae",["ViTMAEModel",Go]],["groupvit",["GroupViTModel",vr]],["fastvit",["FastViTModel",Ko]],["mobilevit",["MobileViTModel",Jo]],["mobilevitv2",["MobileViTV2Model",el]],["owlvit",["OwlViTModel",rl]],["owlv2",["Owlv2Model",sl]],["beit",["BeitModel",il]],["deit",["DeiTModel",la]],["hiera",["HieraModel",ml]],["convnext",["ConvNextModel",Ol]],["convnextv2",["ConvNextV2Model",Qn]],["dinov2",["Dinov2Model",Jn]],["resnet",["ResNetModel",gl]],["swin",["SwinModel",yl]],["swin2sr",["Swin2SRModel",Td]],["donut-swin",["DonutSwinModel",zl]],["yolos",["YolosModel",ii]],["dpt",["DPTModel",On]],["glpn",["GLPNModel",Al]],["hifigan",["SpeechT5HifiGan",iu]],["efficientnet",["EfficientNetModel",za]],["decision_transformer",["DecisionTransformerModel",Cu]],["mobilenet_v1",["MobileNetV1Model",yu]],["mobilenet_v2",["MobileNetV2Model",Id]],["mobilenet_v3",["MobileNetV3Model",Fd]],["mobilenet_v4",["MobileNetV4Model",xu]],["maskformer",["MaskFormerModel",Sl]]]),Dd=new Map([["t5",["T5Model",Xt]],["longt5",["LongT5Model",Ps]],["mt5",["MT5Model",Is]],["bart",["BartModel",ue]],["mbart",["MBartModel",se]],["marian",["MarianModel",Rl]],["whisper",["WhisperModel",Ys]],["m2m_100",["M2M100Model",wa]],["blenderbot",["BlenderbotModel",Mt]],["blenderbot-small",["BlenderbotSmallModel",$r]]]),yc=new Map([["bloom",["BloomModel",Wi]],["jais",["JAISModel",An]],["gpt2",["GPT2Model",fo]],["gptj",["GPTJModel",Mo]],["gpt_bigcode",["GPTBigCodeModel",In]],["gpt_neo",["GPTNeoModel",go]],["gpt_neox",["GPTNeoXModel",yo]],["codegen",["CodeGenModel",zi]],["llama",["LlamaModel",Co]],["cohere",["CohereModel",$o]],["gemma",["GemmaModel",ko]],["gemma2",["Gemma2Model",zn]],["openelm",["OpenELMModel",Io]],["qwen2",["Qwen2Model",zo]],["phi",["PhiModel",Do]],["phi3",["Phi3Model",Vi]],["mpt",["MptModel",Ro]],["opt",["OPTModel",Os]],["mistral",["MistralModel",ou]],["starcoder2",["Starcoder2Model",uu]],["falcon",["FalconModel",du]],["stablelm",["StableLmModel",_u]]]),Na=new Map([["speecht5",["SpeechT5ForSpeechToText",nu]],["whisper",["WhisperForConditionalGeneration",rt]]]),Eu=new Map([["speecht5",["SpeechT5ForTextToSpeech",su]]]),$u=new Map([["vits",["VitsModel",Sa]],["musicgen",["MusicgenForConditionalGeneration",Da]]]),Su=new Map([["bert",["BertForSequenceClassification",ht]],["roformer",["RoFormerForSequenceClassification",je]],["electra",["ElectraForSequenceClassification",Bt]],["esm",["EsmForSequenceClassification",Br]],["convbert",["ConvBertForSequenceClassification",q]],["camembert",["CamembertForSequenceClassification",Er]],["deberta",["DebertaForSequenceClassification",ge]],["deberta-v2",["DebertaV2ForSequenceClassification",mt]],["mpnet",["MPNetForSequenceClassification",Es]],["albert",["AlbertForSequenceClassification",ts]],["distilbert",["DistilBertForSequenceClassification",Rt]],["roberta",["RobertaForSequenceClassification",Sr]],["xlm",["XLMForSequenceClassification",kn]],["xlm-roberta",["XLMRobertaForSequenceClassification",Ar]],["bart",["BartForSequenceClassification",A]],["mbart",["MBartForSequenceClassification",De]],["mobilebert",["MobileBertForSequenceClassification",Ln]],["squeezebert",["SqueezeBertForSequenceClassification",qn]]]),Ld=new Map([["bert",["BertForTokenClassification",bt]],["roformer",["RoFormerForTokenClassification",lt]],["electra",["ElectraForTokenClassification",ct]],["esm",["EsmForTokenClassification",Kr]],["convbert",["ConvBertForTokenClassification",$]],["camembert",["CamembertForTokenClassification",Qr]],["deberta",["DebertaForTokenClassification",Ae]],["deberta-v2",["DebertaV2ForTokenClassification",$t]],["mpnet",["MPNetForTokenClassification",$s]],["distilbert",["DistilBertForTokenClassification",Gt]],["roberta",["RobertaForTokenClassification",_n]],["xlm",["XLMForTokenClassification",Nn]],["xlm-roberta",["XLMRobertaForTokenClassification",Ct]]]),ja=new Map([["t5",["T5ForConditionalGeneration",ms]],["longt5",["LongT5ForConditionalGeneration",As]],["mt5",["MT5ForConditionalGeneration",ws]],["bart",["BartForConditionalGeneration",m]],["mbart",["MBartForConditionalGeneration",pe]],["marian",["MarianMTModel",li]],["m2m_100",["M2M100ForConditionalGeneration",ui]],["blenderbot",["BlenderbotForConditionalGeneration",Ot]],["blenderbot-small",["BlenderbotSmallForConditionalGeneration",ar]]]),Va=new Map([["bloom",["BloomForCausalLM",Md]],["gpt2",["GPT2LMHeadModel",mo]],["jais",["JAISLMHeadModel",_o]],["gptj",["GPTJForCausalLM",vo]],["gpt_bigcode",["GPTBigCodeForCausalLM",To]],["gpt_neo",["GPTNeoForCausalLM",wo]],["gpt_neox",["GPTNeoXForCausalLM",bo]],["codegen",["CodeGenForCausalLM",Fn]],["llama",["LlamaForCausalLM",Eo]],["cohere",["CohereForCausalLM",So]],["gemma",["GemmaForCausalLM",Po]],["gemma2",["Gemma2ForCausalLM",Ao]],["openelm",["OpenELMForCausalLM",Fo]],["qwen2",["Qwen2ForCausalLM",Oo]],["phi",["PhiForCausalLM",Lo]],["phi3",["Phi3ForCausalLM",Bo]],["mpt",["MptForCausalLM",No]],["opt",["OPTForCausalLM",jo]],["mbart",["MBartForCausalLM",wt]],["mistral",["MistralForCausalLM",lu]],["starcoder2",["Starcoder2ForCausalLM",Pd]],["falcon",["FalconForCausalLM",cu]],["trocr",["TrOCRForCausalLM",au]],["stablelm",["StableLmForCausalLM",gu]]]),ku=new Map([["bert",["BertForMaskedLM",Re]],["roformer",["RoFormerForMaskedLM",Ue]],["electra",["ElectraForMaskedLM",Je]],["esm",["EsmForMaskedLM",wr]],["convbert",["ConvBertForMaskedLM",x]],["camembert",["CamembertForMaskedLM",cr]],["deberta",["DebertaForMaskedLM",U]],["deberta-v2",["DebertaV2ForMaskedLM",gt]],["mpnet",["MPNetForMaskedLM",Xs]],["albert",["AlbertForMaskedLM",fs]],["distilbert",["DistilBertForMaskedLM",tt]],["roberta",["RobertaForMaskedLM",ur]],["xlm",["XLMWithLMHeadModel",xn]],["xlm-roberta",["XLMRobertaForMaskedLM",yr]],["mobilebert",["MobileBertForMaskedLM",Vr]],["squeezebert",["SqueezeBertForMaskedLM",Qs]]]),Pu=new Map([["bert",["BertForQuestionAnswering",qe]],["roformer",["RoFormerForQuestionAnswering",yt]],["electra",["ElectraForQuestionAnswering",Tt]],["convbert",["ConvBertForQuestionAnswering",Q]],["camembert",["CamembertForQuestionAnswering",Or]],["deberta",["DebertaForQuestionAnswering",et]],["deberta-v2",["DebertaV2ForQuestionAnswering",ft]],["mpnet",["MPNetForQuestionAnswering",Ss]],["albert",["AlbertForQuestionAnswering",hs]],["distilbert",["DistilBertForQuestionAnswering",be]],["roberta",["RobertaForQuestionAnswering",wn]],["xlm",["XLMForQuestionAnswering",Ht]],["xlm-roberta",["XLMRobertaForQuestionAnswering",mr]],["mobilebert",["MobileBertForQuestionAnswering",Rr]],["squeezebert",["SqueezeBertForQuestionAnswering",Sn]]]),Au=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",Ut]]]),yn=new Map([["llava",["LlavaForConditionalGeneration",Ci]],["moondream1",["Moondream1ForConditionalGeneration",io]],["florence2",["Florence2ForConditionalGeneration",or]]]),Bd=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",Ut]]]),Iu=new Map([["vit",["ViTForImageClassification",Vo]],["pvt",["PvtForImageClassification",Wo]],["vit_msn",["ViTMSNForImageClassification",xd]],["fastvit",["FastViTForImageClassification",Xo]],["mobilevit",["MobileViTForImageClassification",Zo]],["mobilevitv2",["MobileViTV2ForImageClassification",tl]],["beit",["BeitForImageClassification",al]],["deit",["DeiTForImageClassification",ua]],["hiera",["HieraForImageClassification",_l]],["convnext",["ConvNextForImageClassification",Cd]],["convnextv2",["ConvNextV2ForImageClassification",Yn]],["dinov2",["Dinov2ForImageClassification",fn]],["resnet",["ResNetForImageClassification",wl]],["swin",["SwinForImageClassification",bl]],["segformer",["SegformerForImageClassification",Ls]],["efficientnet",["EfficientNetForImageClassification",wu]],["mobilenet_v1",["MobileNetV1ForImageClassification",bu]],["mobilenet_v2",["MobileNetV2ForImageClassification",Mu]],["mobilenet_v3",["MobileNetV3ForImageClassification",vu]],["mobilenet_v4",["MobileNetV4ForImageClassification",Tu]]]),Ua=new Map([["detr",["DetrForObjectDetection",ll]],["rt_detr",["RTDetrForObjectDetection",cl]],["table-transformer",["TableTransformerForObjectDetection",fl]],["yolos",["YolosForObjectDetection",_a]]]),Fu=new Map([["owlvit",["OwlViTForObjectDetection",nl]],["owlv2",["Owlv2ForObjectDetection",Zs]]]),Bs=new Map([["detr",["DetrForSegmentation",ra]],["clipseg",["CLIPSegForImageSegmentation",ho]]]),zu=new Map([["segformer",["SegformerForSemanticSegmentation",Aa]],["sapiens",["SapiensForSemanticSegmentation",Cl]]]),Ou=new Map([["detr",["DetrForSegmentation",ra]],["maskformer",["MaskFormerForInstanceSegmentation",kl]]]),Wa=new Map([["sam",["SamModel",Bl]]]),Du=new Map([["wav2vec2",["Wav2Vec2ForCTC",Ed]],["wav2vec2-bert",["Wav2Vec2BertForCTC",Ql]],["unispeech",["UniSpeechForCTC",Gl]],["unispeech-sat",["UniSpeechSatForCTC",Hl]],["wavlm",["WavLMForCTC",eu]],["hubert",["HubertForCTC",Jl]]]),Lu=new Map([["wav2vec2",["Wav2Vec2ForSequenceClassification",jl]],["wav2vec2-bert",["Wav2Vec2BertForSequenceClassification",fi]],["unispeech",["UniSpeechForSequenceClassification",ql]],["unispeech-sat",["UniSpeechSatForSequenceClassification",Kl]],["wavlm",["WavLMForSequenceClassification",tu]],["hubert",["HubertForSequenceClassification",Zl]],["audio-spectrogram-transformer",["ASTForAudioClassification",Xn]]]),Ga=new Map([["wavlm",["WavLMForXVector",kd]]]),Bu=new Map([["unispeech-sat",["UniSpeechSatForAudioFrameClassification",Xl]],["wavlm",["WavLMForAudioFrameClassification",ru]],["wav2vec2",["Wav2Vec2ForAudioFrameClassification",ya]],["pyannote",["PyAnnoteForAudioFrameClassification",ba]]]),Ru=new Map([["vitmatte",["VitMatteForImageMatting",Yo]]]),Nu=new Map([["swin2sr",["Swin2SRForImageSuperResolution",Ml]]]),qa=new Map([["dpt",["DPTForDepthEstimation",vl]],["depth_anything",["DepthAnythingForDepthEstimation",Tl]],["glpn",["GLPNForDepthEstimation",Il]],["sapiens",["SapiensForDepthEstimation",El]]]),ju=new Map([["sapiens",["SapiensForNormalEstimation",$l]]]),Vu=new Map([["clip",["CLIPVisionModelWithProjection",Pn]],["siglip",["SiglipVisionModel",lo]]]),Ha=[[Od,re.EncoderOnly],[Dd,re.EncoderDecoder],[yc,re.DecoderOnly],[Su,re.EncoderOnly],[Ld,re.EncoderOnly],[ja,re.Seq2Seq],[Na,re.Seq2Seq],[Va,re.DecoderOnly],[ku,re.EncoderOnly],[Pu,re.EncoderOnly],[Au,re.Vision2Seq],[yn,re.ImageTextToText],[Iu,re.EncoderOnly],[Bs,re.EncoderOnly],[Ou,re.EncoderOnly],[zu,re.EncoderOnly],[Ru,re.EncoderOnly],[Nu,re.EncoderOnly],[qa,re.EncoderOnly],[ju,re.EncoderOnly],[Ua,re.EncoderOnly],[Fu,re.EncoderOnly],[Wa,re.MaskGeneration],[Du,re.EncoderOnly],[Lu,re.EncoderOnly],[Eu,re.Seq2Seq],[$u,re.EncoderOnly],[Ga,re.EncoderOnly],[Bu,re.EncoderOnly],[Vu,re.EncoderOnly]];for(const[f,_]of Ha)for(const[T,J]of f.values())ie.set(T,_),R.set(J,T),X.set(T,J);const Rd=[["MusicgenForConditionalGeneration",Da,re.Musicgen],["CLIPTextModelWithProjection",ao,re.EncoderOnly],["SiglipTextModel",is,re.EncoderOnly],["ClapTextModelWithProjection",hu,re.EncoderOnly],["ClapAudioModelWithProjection",fu,re.EncoderOnly]];for(const[f,_,T]of Rd)ie.set(f,T),R.set(_,f),X.set(f,_);class Uu extends Ir{}xe(Uu,"MODEL_CLASS_MAPPINGS",Ha.map(_=>_[0])),xe(Uu,"BASE_IF_FAIL",!0);class Ka extends Ir{}xe(Ka,"MODEL_CLASS_MAPPINGS",[Su]);class Wu extends Ir{}xe(Wu,"MODEL_CLASS_MAPPINGS",[Ld]);class Gu extends Ir{}xe(Gu,"MODEL_CLASS_MAPPINGS",[ja]);class qu extends Ir{}xe(qu,"MODEL_CLASS_MAPPINGS",[Na]);class Nd extends Ir{}xe(Nd,"MODEL_CLASS_MAPPINGS",[Eu]);class Hu extends Ir{}xe(Hu,"MODEL_CLASS_MAPPINGS",[$u]);class Ku extends Ir{}xe(Ku,"MODEL_CLASS_MAPPINGS",[Va]);class Xu extends Ir{}xe(Xu,"MODEL_CLASS_MAPPINGS",[ku]);class jd extends Ir{}xe(jd,"MODEL_CLASS_MAPPINGS",[Pu]);class Qu extends Ir{}xe(Qu,"MODEL_CLASS_MAPPINGS",[Au]);class Yu extends Ir{}xe(Yu,"MODEL_CLASS_MAPPINGS",[Iu]);class Ju extends Ir{}xe(Ju,"MODEL_CLASS_MAPPINGS",[Bs]);class Zu extends Ir{}xe(Zu,"MODEL_CLASS_MAPPINGS",[zu]);class Vd extends Ir{}xe(Vd,"MODEL_CLASS_MAPPINGS",[Ou]);class ed extends Ir{}xe(ed,"MODEL_CLASS_MAPPINGS",[Ua]);class td extends Ir{}xe(td,"MODEL_CLASS_MAPPINGS",[Fu]);class rd extends Ir{}xe(rd,"MODEL_CLASS_MAPPINGS",[Wa]);class nd extends Ir{}xe(nd,"MODEL_CLASS_MAPPINGS",[Du]);class sd extends Ir{}xe(sd,"MODEL_CLASS_MAPPINGS",[Lu]);class id extends Ir{}xe(id,"MODEL_CLASS_MAPPINGS",[Ga]);class ad extends Ir{}xe(ad,"MODEL_CLASS_MAPPINGS",[Bu]);class od extends Ir{}xe(od,"MODEL_CLASS_MAPPINGS",[Bd]);class ld extends Ir{}xe(ld,"MODEL_CLASS_MAPPINGS",[Ru]);class Ud extends Ir{}xe(Ud,"MODEL_CLASS_MAPPINGS",[Nu]);class Rs extends Ir{}xe(Rs,"MODEL_CLASS_MAPPINGS",[qa]);class Xa extends Ir{}xe(Xa,"MODEL_CLASS_MAPPINGS",[ju]);class Qa extends Ir{}xe(Qa,"MODEL_CLASS_MAPPINGS",[Vu]);class ud extends He{constructor({logits:_,past_key_values:T,encoder_outputs:J,decoder_attentions:Fe=null,cross_attentions:Oe=null}){super(),this.logits=_,this.past_key_values=T,this.encoder_outputs=J,this.decoder_attentions=Fe,this.cross_attentions=Oe}}class ir extends He{constructor({logits:_}){super(),this.logits=_}}class dd extends He{constructor({logits:_,embeddings:T}){super(),this.logits=_,this.embeddings=T}}class sn extends He{constructor({logits:_}){super(),this.logits=_}}class an extends He{constructor({logits:_}){super(),this.logits=_}}class cn extends He{constructor({start_logits:_,end_logits:T}){super(),this.start_logits=_,this.end_logits=T}}class os extends He{constructor({logits:_}){super(),this.logits=_}}class Wd extends He{constructor({logits:_,past_key_values:T}){super(),this.logits=_,this.past_key_values=T}}class Ya extends He{constructor({alphas:_}){super(),this.alphas=_}}class cd extends He{constructor({waveform:_,spectrogram:T}){super(),this.waveform=_,this.spectrogram=T}}},"./src/models/whisper/common_whisper.js":(Pt,Ce,N)=>{N.r(Ce),N.d(Ce,{WHISPER_LANGUAGE_MAPPING:()=>me,WHISPER_TO_LANGUAGE_CODE_MAPPING:()=>ye,whisper_language_to_code:()=>Te});const z=[["en","english"],["zh","chinese"],["de","german"],["es","spanish"],["ru","russian"],["ko","korean"],["fr","french"],["ja","japanese"],["pt","portuguese"],["tr","turkish"],["pl","polish"],["ca","catalan"],["nl","dutch"],["ar","arabic"],["sv","swedish"],["it","italian"],["id","indonesian"],["hi","hindi"],["fi","finnish"],["vi","vietnamese"],["he","hebrew"],["uk","ukrainian"],["el","greek"],["ms","malay"],["cs","czech"],["ro","romanian"],["da","danish"],["hu","hungarian"],["ta","tamil"],["no","norwegian"],["th","thai"],["ur","urdu"],["hr","croatian"],["bg","bulgarian"],["lt","lithuanian"],["la","latin"],["mi","maori"],["ml","malayalam"],["cy","welsh"],["sk","slovak"],["te","telugu"],["fa","persian"],["lv","latvian"],["bn","bengali"],["sr","serbian"],["az","azerbaijani"],["sl","slovenian"],["kn","kannada"],["et","estonian"],["mk","macedonian"],["br","breton"],["eu","basque"],["is","icelandic"],["hy","armenian"],["ne","nepali"],["mn","mongolian"],["bs","bosnian"],["kk","kazakh"],["sq","albanian"],["sw","swahili"],["gl","galician"],["mr","marathi"],["pa","punjabi"],["si","sinhala"],["km","khmer"],["sn","shona"],["yo","yoruba"],["so","somali"],["af","afrikaans"],["oc","occitan"],["ka","georgian"],["be","belarusian"],["tg","tajik"],["sd","sindhi"],["gu","gujarati"],["am","amharic"],["yi","yiddish"],["lo","lao"],["uz","uzbek"],["fo","faroese"],["ht","haitian creole"],["ps","pashto"],["tk","turkmen"],["nn","nynorsk"],["mt","maltese"],["sa","sanskrit"],["lb","luxembourgish"],["my","myanmar"],["bo","tibetan"],["tl","tagalog"],["mg","malagasy"],["as","assamese"],["tt","tatar"],["haw","hawaiian"],["ln","lingala"],["ha","hausa"],["ba","bashkir"],["jw","javanese"],["su","sundanese"]],me=new Map(z),ye=new Map([...z.map(([Ee,j])=>[j,Ee]),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);function Te(Ee){Ee=Ee.toLowerCase();let j=ye.get(Ee);if(j===void 0)if(me.has(Ee))j=Ee;else{const V=Ee.length===2?me.keys():me.values();throw new Error(`Language "${Ee}" is not supported. Must be one of: ${JSON.stringify(V)}`)}return j}},"./src/models/whisper/generation_whisper.js":(Pt,Ce,N)=>{N.r(Ce),N.d(Ce,{WhisperGenerationConfig:()=>me});var z=N("./src/generation/configuration_utils.js");class me extends z.GenerationConfig{constructor(){super(...arguments);xe(this,"return_timestamps",null);xe(this,"return_token_timestamps",null);xe(this,"num_frames",null);xe(this,"alignment_heads",null);xe(this,"task",null);xe(this,"language",null);xe(this,"no_timestamps_token_id",null);xe(this,"prompt_ids",null);xe(this,"is_multilingual",null);xe(this,"lang_to_id",null);xe(this,"task_to_id",null);xe(this,"max_initial_timestamp_index",1)}}},"./src/ops/registry.js":(Pt,Ce,N)=>{N.r(Ce),N.d(Ce,{TensorOpRegistry:()=>Te});var z=N("./src/backends/onnx.js"),me=N("./src/utils/tensor.js");const ye=async(Ee,j,S)=>{const V=await(0,z.createInferenceSession)(new Uint8Array(Ee),j);return async P=>{const te=Object.fromEntries(Object.entries(P).map(([_e,ce])=>[_e,ce.ort_tensor])),ne=await V.run(te);return Array.isArray(S)?S.map(_e=>new me.Tensor(ne[_e])):new me.Tensor(ne[S])}};class Te{static get bilinear_interpolate_4d(){return this._bilinear_interpolate_4d||(this._bilinear_interpolate_4d=ye([8,9,18,0,58,128,1,10,40,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,17,10,4,109,111,100,101,34,6,108,105,110,101,97,114,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bilinear_interpolate_4d}static get bicubic_interpolate_4d(){return this._bicubic_interpolate_4d||(this._bicubic_interpolate_4d=ye([8,9,18,0,58,127,10,39,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,16,10,4,109,111,100,101,34,5,99,117,98,105,99,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bicubic_interpolate_4d}static get matmul(){return this._matmul||(this._matmul=ye([8,9,18,0,58,55,10,17,10,1,97,10,1,98,18,1,99,34,6,77,97,116,77,117,108,18,1,114,90,9,10,1,97,18,4,10,2,8,1,90,9,10,1,98,18,4,10,2,8,1,98,9,10,1,99,18,4,10,2,8,1,66,2,16,20],this.session_options,"c")),this._matmul}static get stft(){return this._stft||(this._stft=ye([8,7,18,0,58,148,1,10,38,10,1,115,10,1,106,10,1,119,10,1,108,18,1,111,34,4,83,84,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,115,90,26,10,1,115,18,21,10,19,8,1,18,15,10,3,18,1,98,10,3,18,1,115,10,3,18,1,99,90,11,10,1,106,18,6,10,4,8,7,18,0,90,16,10,1,119,18,11,10,9,8,1,18,5,10,3,18,1,119,90,11,10,1,108,18,6,10,4,8,7,18,0,98,31,10,1,111,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,102,10,3,18,1,100,10,3,18,1,99,66,2,16,17],this.session_options,"o")),this._stft}static get rfft(){return this._rfft||(this._rfft=ye([8,9,18,0,58,97,10,33,10,1,120,10,0,10,1,97,18,1,121,34,3,68,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,100,90,21,10,1,120,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,90,11,10,1,97,18,6,10,4,8,7,18,0,98,21,10,1,121,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,66,2,16,20],this.session_options,"y")),this._rfft}static get top_k(){return this._top_k||(this._top_k=ye([8,10,18,0,58,73,10,18,10,1,120,10,1,107,18,1,118,18,1,105,34,4,84,111,112,75,18,1,116,90,9,10,1,120,18,4,10,2,8,1,90,15,10,1,107,18,10,10,8,8,7,18,4,10,2,8,1,98,9,10,1,118,18,4,10,2,8,1,98,9,10,1,105,18,4,10,2,8,7,66,2,16,21],this.session_options,["v","i"])),this._top_k}}xe(Te,"session_options",{})},"./src/pipelines.js":(Pt,Ce,N)=>{N.r(Ce),N.d(Ce,{AudioClassificationPipeline:()=>ze,AutomaticSpeechRecognitionPipeline:()=>Ze,DepthEstimationPipeline:()=>nt,DocumentQuestionAnsweringPipeline:()=>Y,FeatureExtractionPipeline:()=>Me,FillMaskPipeline:()=>ie,ImageClassificationPipeline:()=>ut,ImageFeatureExtractionPipeline:()=>ke,ImageSegmentationPipeline:()=>we,ImageToImagePipeline:()=>dt,ImageToTextPipeline:()=>Ke,ObjectDetectionPipeline:()=>fe,Pipeline:()=>ce,QuestionAnsweringPipeline:()=>re,SummarizationPipeline:()=>R,Text2TextGenerationPipeline:()=>X,TextClassificationPipeline:()=>D,TextGenerationPipeline:()=>k,TextToAudioPipeline:()=>He,TokenClassificationPipeline:()=>K,TranslationPipeline:()=>I,ZeroShotAudioClassificationPipeline:()=>Ie,ZeroShotClassificationPipeline:()=>de,ZeroShotImageClassificationPipeline:()=>W,ZeroShotObjectDetectionPipeline:()=>$e,pipeline:()=>ht});var z=N("./src/tokenizers.js"),me=N("./src/models.js"),ye=N("./src/processors.js"),Te=N("./src/utils/generic.js"),Ee=N("./src/utils/core.js"),j=N("./src/utils/maths.js"),S=N("./src/utils/audio.js"),V=N("./src/utils/tensor.js"),P=N("./src/utils/image.js");async function te(qe){return Array.isArray(qe)||(qe=[qe]),await Promise.all(qe.map(ee=>P.RawImage.read(ee)))}async function ne(qe,ee){return Array.isArray(qe)||(qe=[qe]),await Promise.all(qe.map(Pe=>typeof Pe=="string"||Pe instanceof URL?(0,S.read_audio)(Pe,ee):Pe instanceof Float64Array?new Float32Array(Pe):Pe))}function _e(qe,ee){ee&&(qe=qe.map(je=>je|0));const[Pe,Ne,Qe,Ue]=qe;return{xmin:Pe,ymin:Ne,xmax:Qe,ymax:Ue}}class ce extends Te.Callable{constructor({task:ee,model:Pe,tokenizer:Ne=null,processor:Qe=null}){super(),this.task=ee,this.model=Pe,this.tokenizer=Ne,this.processor=Qe}async dispose(){await this.model.dispose()}}class D extends ce{constructor(ee){super(ee)}async _call(ee,{top_k:Pe=1}={}){const Ne=this.tokenizer(ee,{padding:!0,truncation:!0}),Qe=await this.model(Ne),Ue=this.model.config.problem_type==="multi_label_classification"?yt=>yt.sigmoid():yt=>new V.Tensor("float32",(0,j.softmax)(yt.data),yt.dims),je=this.model.config.id2label,lt=[];for(const yt of Qe.logits){const vt=Ue(yt),Et=await(0,V.topk)(vt,Pe),x=Et[0].tolist(),$=Et[1].tolist().map((Q,he)=>({label:je?je[Q]:`LABEL_${Q}`,score:x[he]}));Pe===1?lt.push(...$):lt.push($)}return Array.isArray(ee)||Pe===1?lt:lt[0]}}class K extends ce{constructor(ee){super(ee)}async _call(ee,{ignore_labels:Pe=["O"]}={}){const Ne=Array.isArray(ee),Qe=this.tokenizer(Ne?ee:[ee],{padding:!0,truncation:!0}),je=(await this.model(Qe)).logits,lt=this.model.config.id2label,yt=[];for(let vt=0;vtct==this.tokenizer.sep_token_id);yt[x].map((ct,Tt)=>ct==1&&(Tt===0||Tt>$&&vt.findIndex(It=>It==q[Tt])===-1));const Q=Ue[x].tolist(),he=je[x].tolist();for(let ct=1;ctTt==q[ct])!==-1)&&(Q[ct]=-1/0,he[ct]=-1/0);const Ye=(0,j.softmax)(Q).map((ct,Tt)=>[ct,Tt]),Je=(0,j.softmax)(he).map((ct,Tt)=>[ct,Tt]);Ye[0][0]=0,Je[0][0]=0;const Bt=(0,Ee.product)(Ye,Je).filter(ct=>ct[0][1]<=ct[1][1]).map(ct=>[ct[0][1],ct[1][1],ct[0][0]*ct[1][0]]).sort((ct,Tt)=>Tt[2]-ct[2]);for(let ct=0;ctQ==this.tokenizer.mask_token_id);if(vt===-1)throw Error(`Mask token (${this.tokenizer.mask_token}) not found in text.`);const Et=Qe[lt][vt],x=await(0,V.topk)(new V.Tensor("float32",(0,j.softmax)(Et.data),Et.dims),Pe),q=x[0].tolist(),$=x[1].tolist();Ue.push($.map((Q,he)=>{const Ye=yt.slice();return Ye[vt]=Q,{score:q[he],token:Number(Q),token_str:this.tokenizer.model.vocab[Q],sequence:this.tokenizer.decode(Ye,{skip_special_tokens:!0})}}))}return Array.isArray(ee)?Ue:Ue[0]}}class X extends ce{constructor(Pe){super(Pe);xe(this,"_key","generated_text")}async _call(Pe,Ne={}){Array.isArray(Pe)||(Pe=[Pe]),this.model.config.prefix&&(Pe=Pe.map(vt=>this.model.config.prefix+vt));const Qe=this.model.config.task_specific_params;Qe&&Qe[this.task]&&Qe[this.task].prefix&&(Pe=Pe.map(vt=>Qe[this.task].prefix+vt));const Ue=this.tokenizer,je={padding:!0,truncation:!0};let lt;this instanceof I&&"_build_translation_inputs"in Ue?lt=Ue._build_translation_inputs(Pe,je,Ne):lt=Ue(Pe,je);const yt=await this.model.generate({...lt,...Ne});return Ue.batch_decode(yt,{skip_special_tokens:!0}).map(vt=>({[this._key]:vt}))}}class R extends X{constructor(Pe){super(Pe);xe(this,"_key","summary_text")}}class I extends X{constructor(Pe){super(Pe);xe(this,"_key","translation_text")}}function L(qe){return Array.isArray(qe)&&qe.every(ee=>"role"in ee&&"content"in ee)}class k extends ce{constructor(ee){super(ee)}async _call(ee,Pe={}){let Ne=!1,Qe=!1,Ue;if(typeof ee=="string")Ue=ee=[ee];else if(Array.isArray(ee)&&ee.every($=>typeof $=="string"))Ne=!0,Ue=ee;else{if(L(ee))ee=[ee];else if(Array.isArray(ee)&&ee.every(L))Ne=!0;else throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats");Qe=!0,Ue=ee.map($=>this.tokenizer.apply_chat_template($,{tokenize:!1,add_generation_prompt:!0}))}const je=Pe.add_special_tokens??!1,lt=Qe?!1:Pe.return_full_text??!0;this.tokenizer.padding_side="left";const yt=this.tokenizer(Ue,{add_special_tokens:je,padding:!0,truncation:!0}),vt=await this.model.generate({...yt,...Pe}),Et=this.tokenizer.batch_decode(vt,{skip_special_tokens:!0});let x;!lt&&yt.input_ids.dims.at(-1)>0&&(x=this.tokenizer.batch_decode(yt.input_ids,{skip_special_tokens:!0}).map($=>$.length));const q=Array.from({length:ee.length},$=>[]);for(let $=0;$[Pe.toLowerCase(),Ne])),this.entailment_id=this.label2id.entailment,this.entailment_id===void 0&&(console.warn("Could not find 'entailment' in label2id mapping. Using 2 as entailment_id."),this.entailment_id=2),this.contradiction_id=this.label2id.contradiction??this.label2id.not_entailment,this.contradiction_id===void 0&&(console.warn("Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id."),this.contradiction_id=0)}async _call(ee,Pe,{hypothesis_template:Ne="This example is {}.",multi_label:Qe=!1}={}){const Ue=Array.isArray(ee);Ue||(ee=[ee]),Array.isArray(Pe)||(Pe=[Pe]);const je=Pe.map(vt=>Ne.replace("{}",vt)),lt=Qe||Pe.length===1,yt=[];for(const vt of ee){const Et=[];for(const $ of je){const Q=this.tokenizer(vt,{text_pair:$,padding:!0,truncation:!0}),he=await this.model(Q);lt?Et.push([he.logits.data[this.contradiction_id],he.logits.data[this.entailment_id]]):Et.push(he.logits.data[this.entailment_id])}const q=(lt?Et.map($=>(0,j.softmax)($)[1]):(0,j.softmax)(Et)).map(($,Q)=>[$,Q]).sort(($,Q)=>Q[0]-$[0]);yt.push({sequence:vt,labels:q.map($=>Pe[$[1]]),scores:q.map($=>$[0])})}return Ue?yt:yt[0]}}class Me extends ce{constructor(ee){super(ee)}async _call(ee,{pooling:Pe="none",normalize:Ne=!1,quantize:Qe=!1,precision:Ue="binary"}={}){const je=this.tokenizer(ee,{padding:!0,truncation:!0}),lt=await this.model(je);let yt=lt.last_hidden_state??lt.logits??lt.token_embeddings;if(Pe!=="none")if(Pe==="mean")yt=(0,V.mean_pooling)(yt,je.attention_mask);else if(Pe==="cls")yt=yt.slice(null,0);else throw Error(`Pooling method '${Pe}' not supported.`);return Ne&&(yt=yt.normalize(2,-1)),Qe&&(yt=(0,V.quantize_embeddings)(yt,Ue)),yt}}class ke extends ce{constructor(ee){super(ee)}async _call(ee,{pool:Pe=null}={}){const Ne=await te(ee),{pixel_values:Qe}=await this.processor(Ne),Ue=await this.model({pixel_values:Qe});let je;if(Pe){if(!("pooler_output"in Ue))throw Error("No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.");je=Ue.pooler_output}else je=Ue.last_hidden_state??Ue.logits??Ue.image_embeds;return je}}class ze extends ce{constructor(ee){super(ee)}async _call(ee,{top_k:Pe=5}={}){const Ne=this.processor.feature_extractor.config.sampling_rate,Qe=await ne(ee,Ne),Ue=this.model.config.id2label,je=[];for(const lt of Qe){const yt=await this.processor(lt),Et=(await this.model(yt)).logits[0],x=await(0,V.topk)(new V.Tensor("float32",(0,j.softmax)(Et.data),Et.dims),Pe),q=x[0].tolist(),Q=x[1].tolist().map((he,Ye)=>({label:Ue?Ue[he]:`LABEL_${he}`,score:q[Ye]}));je.push(Q)}return Array.isArray(ee)?je:je[0]}}class Ie extends ce{constructor(ee){super(ee)}async _call(ee,Pe,{hypothesis_template:Ne="This is a sound of {}."}={}){const Qe=!Array.isArray(ee);Qe&&(ee=[ee]);const Ue=Pe.map(Et=>Ne.replace("{}",Et)),je=this.tokenizer(Ue,{padding:!0,truncation:!0}),lt=this.processor.feature_extractor.config.sampling_rate,yt=await ne(ee,lt),vt=[];for(const Et of yt){const x=await this.processor(Et),q=await this.model({...je,...x}),$=(0,j.softmax)(q.logits_per_audio.data);vt.push([...$].map((Q,he)=>({score:Q,label:Pe[he]})))}return Qe?vt[0]:vt}}class Ze extends ce{constructor(ee){super(ee)}async _call(ee,Pe={}){switch(this.model.config.model_type){case"whisper":return this._call_whisper(ee,Pe);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":return this._call_wav2vec2(ee,Pe);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(ee,Pe){Pe.language&&console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),Pe.task&&console.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');const Ne=!Array.isArray(ee);Ne&&(ee=[ee]);const Qe=this.processor.feature_extractor.config.sampling_rate,Ue=await ne(ee,Qe),je=[];for(const lt of Ue){const yt=await this.processor(lt),Et=(await this.model(yt)).logits[0],x=[];for(const $ of Et)x.push((0,j.max)($.data)[1]);const q=this.tokenizer.decode(x);je.push({text:q})}return Ne?je[0]:je}async _call_whisper(ee,Pe){const Ne=Pe.return_timestamps??!1,Qe=Pe.chunk_length_s??0,Ue=Pe.force_full_sequences??!1;let je=Pe.stride_length_s??null;const lt={...Pe};Ne==="word"&&(lt.return_token_timestamps=!0,lt.return_timestamps=!1);const yt=!Array.isArray(ee);yt&&(ee=[ee]);const vt=this.processor.feature_extractor.config.chunk_length/this.model.config.max_source_positions,Et=this.processor.feature_extractor.config.hop_length,x=this.processor.feature_extractor.config.sampling_rate,q=await ne(ee,x),$=[];for(const Q of q){let he=[];if(Qe>0){if(je===null)je=Qe/6;else if(Qe<=je)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");const Bt=x*Qe,ct=x*je,Tt=Bt-2*ct;let It=0;for(;;){const At=It+Bt,cr=Q.subarray(It,At),Er=await this.processor(cr),Qr=It===0,Or=At>=Q.length;if(he.push({stride:[cr.length,Qr?0:ct,Or?0:ct],input_features:Er.input_features,is_last:Or}),Or)break;It+=Tt}}else he=[{stride:[Q.length,0,0],input_features:(await this.processor(Q)).input_features,is_last:!0}];for(const Bt of he){lt.num_frames=Math.floor(Bt.stride[0]/Et);const ct=await this.model.generate({inputs:Bt.input_features,...lt});Ne==="word"?(Bt.tokens=ct.sequences.tolist()[0],Bt.token_timestamps=ct.token_timestamps.tolist()[0].map(Tt=>(0,j.round)(Tt,2))):Bt.tokens=ct[0].tolist(),Bt.stride=Bt.stride.map(Tt=>Tt/x)}const[Ye,Je]=this.tokenizer._decode_asr(he,{time_precision:vt,return_timestamps:Ne,force_full_sequences:Ue});$.push({text:Ye,...Je})}return yt?$[0]:$}}class Ke extends ce{constructor(ee){super(ee)}async _call(ee,Pe={}){const Ne=Array.isArray(ee),Qe=await te(ee),{pixel_values:Ue}=await this.processor(Qe),je=[];for(const lt of Ue){lt.dims=[1,...lt.dims];const yt=await this.model.generate({inputs:lt,...Pe}),vt=this.tokenizer.batch_decode(yt,{skip_special_tokens:!0}).map(Et=>({generated_text:Et.trim()}));je.push(vt)}return Ne?je:je[0]}}class ut extends ce{constructor(ee){super(ee)}async _call(ee,{top_k:Pe=5}={}){const Ne=await te(ee),{pixel_values:Qe}=await this.processor(Ne),Ue=await this.model({pixel_values:Qe}),je=this.model.config.id2label,lt=[];for(const yt of Ue.logits){const vt=await(0,V.topk)(new V.Tensor("float32",(0,j.softmax)(yt.data),yt.dims),Pe),Et=vt[0].tolist(),q=vt[1].tolist().map(($,Q)=>({label:je?je[$]:`LABEL_${$}`,score:Et[Q]}));lt.push(q)}return Array.isArray(ee)?lt:lt[0]}}class we extends ce{constructor(ee){super(ee),this.subtasks_mapping={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"}}async _call(ee,{threshold:Pe=.5,mask_threshold:Ne=.5,overlap_mask_area_threshold:Qe=.8,label_ids_to_fuse:Ue=null,target_sizes:je=null,subtask:lt=null}={}){if(Array.isArray(ee)&&ee.length!==1)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");const vt=await te(ee),Et=vt.map(Je=>[Je.height,Je.width]),{pixel_values:x,pixel_mask:q}=await this.processor(vt),$=await this.model({pixel_values:x,pixel_mask:q});let Q=null;if(lt!==null)Q=this.subtasks_mapping[lt];else for(let[Je,Bt]of Object.entries(this.subtasks_mapping))if(Bt in this.processor.feature_extractor){Q=this.processor.feature_extractor[Bt].bind(this.processor.feature_extractor),lt=Je;break}const he=this.model.config.id2label,Ye=[];if(lt==="panoptic"||lt==="instance"){const Je=Q($,Pe,Ne,Qe,Ue,je??Et)[0],Bt=Je.segmentation;for(const ct of Je.segments_info){const Tt=new Uint8ClampedArray(Bt.data.length);for(let At=0;AtNe.replace("{}",q)),lt=this.tokenizer(je,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:yt}=await this.processor(Ue),vt=await this.model({...lt,pixel_values:yt}),Et=this.model.config.model_type==="siglip"?q=>q.sigmoid().data:q=>(0,j.softmax)(q.data),x=[];for(const q of vt.logits_per_image){const Q=[...Et(q)].map((he,Ye)=>({score:he,label:Pe[Ye]}));Q.sort((he,Ye)=>Ye.score-he.score),x.push(Q)}return Qe?x:x[0]}}class fe extends ce{constructor(ee){super(ee)}async _call(ee,{threshold:Pe=.9,percentage:Ne=!1}={}){const Qe=Array.isArray(ee);if(Qe&&ee.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");const Ue=await te(ee),je=Ne?null:Ue.map($=>[$.height,$.width]),{pixel_values:lt,pixel_mask:yt}=await this.processor(Ue),vt=await this.model({pixel_values:lt,pixel_mask:yt}),Et=this.processor.feature_extractor.post_process_object_detection(vt,Pe,je),x=this.model.config.id2label,q=Et.map($=>$.boxes.map((Q,he)=>({score:$.scores[he],label:x[$.classes[he]],box:_e(Q,!Ne)})));return Qe?q:q[0]}}class $e extends ce{constructor(ee){super(ee)}async _call(ee,Pe,{threshold:Ne=.1,top_k:Qe=null,percentage:Ue=!1}={}){const je=Array.isArray(ee),lt=await te(ee),yt=this.tokenizer(Pe,{padding:!0,truncation:!0}),vt=await this.processor(lt),Et=[];for(let x=0;x({score:Ye.scores[ct],label:Pe[Ye.classes[ct]],box:_e(Bt,!Ue)})).sort((Bt,ct)=>ct.score-Bt.score);Qe!==null&&(Je=Je.slice(0,Qe)),Et.push(Je)}return je?Et:Et[0]}}class Y extends ce{constructor(ee){super(ee)}async _call(ee,Pe,Ne={}){throw new Error("This pipeline is not yet supported in Transformers.js v3.")}}class He extends ce{constructor(Pe){super(Pe);xe(this,"DEFAULT_VOCODER_ID","Xenova/speecht5_hifigan");this.vocoder=Pe.vocoder??null}async _call(Pe,{speaker_embeddings:Ne=null}={}){return this.processor?this._call_text_to_spectrogram(Pe,{speaker_embeddings:Ne}):this._call_text_to_waveform(Pe)}async _call_text_to_waveform(Pe){const Ne=this.tokenizer(Pe,{padding:!0,truncation:!0}),{waveform:Qe}=await this.model(Ne),Ue=this.model.config.sampling_rate;return{audio:Qe.data,sampling_rate:Ue}}async _call_text_to_spectrogram(Pe,{speaker_embeddings:Ne}){if(this.vocoder||(console.log("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await me.AutoModel.from_pretrained(this.DEFAULT_VOCODER_ID,{dtype:"fp32"})),(typeof Ne=="string"||Ne instanceof URL)&&(Ne=new Float32Array(await(await fetch(Ne)).arrayBuffer())),Ne instanceof Float32Array)Ne=new V.Tensor("float32",Ne,[1,Ne.length]);else if(!(Ne instanceof V.Tensor))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");const{input_ids:Qe}=this.tokenizer(Pe,{padding:!0,truncation:!0}),{waveform:Ue}=await this.model.generate_speech(Qe,Ne,{vocoder:this.vocoder}),je=this.processor.feature_extractor.config.sampling_rate;return{audio:Ue.data,sampling_rate:je}}}class dt extends ce{constructor(ee){super(ee)}async _call(ee){const Pe=await te(ee),Ne=await this.processor(Pe),Qe=await this.model(Ne),Ue=[];for(const je of Qe.reconstruction){const lt=je.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");Ue.push(P.RawImage.fromTensor(lt))}return Ue.length>1?Ue:Ue[0]}}class nt extends ce{constructor(ee){super(ee)}async _call(ee){const Pe=await te(ee),Ne=await this.processor(Pe),{predicted_depth:Qe}=await this.model(Ne),Ue=[];for(let je=0;je1?Ue:Ue[0]}}const ot=Object.freeze({"text-classification":{tokenizer:z.AutoTokenizer,pipeline:D,model:me.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{tokenizer:z.AutoTokenizer,pipeline:K,model:me.AutoModelForTokenClassification,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{tokenizer:z.AutoTokenizer,pipeline:re,model:me.AutoModelForQuestionAnswering,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{tokenizer:z.AutoTokenizer,pipeline:ie,model:me.AutoModelForMaskedLM,default:{model:"Xenova/bert-base-uncased"},type:"text"},summarization:{tokenizer:z.AutoTokenizer,pipeline:R,model:me.AutoModelForSeq2SeqLM,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{tokenizer:z.AutoTokenizer,pipeline:I,model:me.AutoModelForSeq2SeqLM,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{tokenizer:z.AutoTokenizer,pipeline:X,model:me.AutoModelForSeq2SeqLM,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{tokenizer:z.AutoTokenizer,pipeline:k,model:me.AutoModelForCausalLM,default:{model:"Xenova/gpt2"},type:"text"},"zero-shot-classification":{tokenizer:z.AutoTokenizer,pipeline:de,model:me.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:ze,model:me.AutoModelForAudioClassification,processor:ye.AutoProcessor,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{tokenizer:z.AutoTokenizer,pipeline:Ie,model:me.AutoModel,processor:ye.AutoProcessor,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{tokenizer:z.AutoTokenizer,pipeline:Ze,model:[me.AutoModelForSpeechSeq2Seq,me.AutoModelForCTC],processor:ye.AutoProcessor,default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{tokenizer:z.AutoTokenizer,pipeline:He,model:[me.AutoModelForTextToWaveform,me.AutoModelForTextToSpectrogram],processor:[ye.AutoProcessor,null],default:{model:"Xenova/speecht5_tts"},type:"text"},"image-to-text":{tokenizer:z.AutoTokenizer,pipeline:Ke,model:me.AutoModelForVision2Seq,processor:ye.AutoProcessor,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:ut,model:me.AutoModelForImageClassification,processor:ye.AutoProcessor,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:we,model:[me.AutoModelForImageSegmentation,me.AutoModelForSemanticSegmentation,me.AutoModelForUniversalSegmentation],processor:ye.AutoProcessor,default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"zero-shot-image-classification":{tokenizer:z.AutoTokenizer,pipeline:W,model:me.AutoModel,processor:ye.AutoProcessor,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:fe,model:me.AutoModelForObjectDetection,processor:ye.AutoProcessor,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{tokenizer:z.AutoTokenizer,pipeline:$e,model:me.AutoModelForZeroShotObjectDetection,processor:ye.AutoProcessor,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{tokenizer:z.AutoTokenizer,pipeline:Y,model:me.AutoModelForDocumentQuestionAnswering,processor:ye.AutoProcessor,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:dt,model:me.AutoModelForImageToImage,processor:ye.AutoProcessor,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:nt,model:me.AutoModelForDepthEstimation,processor:ye.AutoProcessor,default:{model:"Xenova/dpt-large"},type:"image"},"feature-extraction":{tokenizer:z.AutoTokenizer,pipeline:Me,model:me.AutoModel,default:{model:"Xenova/all-MiniLM-L6-v2"},type:"text"},"image-feature-extraction":{processor:ye.AutoProcessor,pipeline:ke,model:[me.AutoModelForImageFeatureExtraction,me.AutoModel],default:{model:"Xenova/vit-base-patch16-224-in21k"},type:"image"}}),Re=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});async function ht(qe,ee=null,{progress_callback:Pe=null,config:Ne=null,cache_dir:Qe=null,local_files_only:Ue=!1,revision:je="main",device:lt=null,dtype:yt=null,model_file_name:vt=null,session_options:Et={}}={}){qe=Re[qe]??qe;const x=ot[qe.split("_",1)[0]];if(!x)throw Error(`Unsupported pipeline: ${qe}. Must be one of [${Object.keys(ot)}]`);ee||(ee=x.default.model,console.log(`No model specified. Using default model: "${ee}".`));const q={progress_callback:Pe,config:Ne,cache_dir:Qe,local_files_only:Ue,revision:je,device:lt,dtype:yt,model_file_name:vt,session_options:Et},$=new Map([["tokenizer",x.tokenizer],["model",x.model],["processor",x.processor]]),Q=await bt($,ee,q);Q.task=qe,(0,Ee.dispatchCallback)(Pe,{status:"ready",task:qe,model:ee});const he=x.pipeline;return new he(Q)}async function bt(qe,ee,Pe){const Ne=Object.create(null),Qe=[];for(const[Ue,je]of qe.entries()){if(!je)continue;let lt;Array.isArray(je)?lt=new Promise(async(yt,vt)=>{var x,q;let Et;for(const $ of je){if($===null){yt(null);return}try{yt(await $.from_pretrained(ee,Pe));return}catch(Q){if((x=Q.message)!=null&&x.includes("Unsupported model type"))Et=Q;else if((q=Q.message)!=null&&q.includes("Could not locate file"))Et=Q;else{vt(Q);return}}}vt(Et)}):lt=je.from_pretrained(ee,Pe),Ne[Ue]=lt,Qe.push(lt)}await Promise.all(Qe);for(const[Ue,je]of Object.entries(Ne))Ne[Ue]=await je;return Ne}},"./src/processors.js":(Pt,Ce,N)=>{N.r(Ce),N.d(Ce,{ASTFeatureExtractor:()=>Q,AutoProcessor:()=>Ur,BeitFeatureExtractor:()=>Pe,BitImageProcessor:()=>Me,CLIPFeatureExtractor:()=>ze,CLIPImageProcessor:()=>Ie,ChineseCLIPFeatureExtractor:()=>Ze,ClapFeatureExtractor:()=>he,ConvNextFeatureExtractor:()=>ut,ConvNextImageProcessor:()=>we,DPTFeatureExtractor:()=>k,DPTImageProcessor:()=>de,DeiTFeatureExtractor:()=>ee,DetrFeatureExtractor:()=>Ue,DonutFeatureExtractor:()=>Ne,EfficientNetImageProcessor:()=>$e,FeatureExtractor:()=>ie,Florence2Processor:()=>Or,GLPNFeatureExtractor:()=>ke,ImageFeatureExtractor:()=>X,MaskFormerFeatureExtractor:()=>je,MobileNetV1FeatureExtractor:()=>Y,MobileNetV2FeatureExtractor:()=>He,MobileNetV3FeatureExtractor:()=>dt,MobileNetV4FeatureExtractor:()=>nt,MobileViTFeatureExtractor:()=>ot,MobileViTImageProcessor:()=>Re,NougatImageProcessor:()=>Qe,OwlViTFeatureExtractor:()=>ht,OwlViTProcessor:()=>Qr,Owlv2ImageProcessor:()=>bt,Processor:()=>ct,PvtImageProcessor:()=>L,PyAnnoteFeatureExtractor:()=>Ye,PyAnnoteProcessor:()=>cr,RTDetrImageProcessor:()=>qe,SamImageProcessor:()=>yt,SamProcessor:()=>Tt,SapiensFeatureExtractor:()=>R,SeamlessM4TFeatureExtractor:()=>$,SegformerFeatureExtractor:()=>I,SiglipImageProcessor:()=>Ke,SpeechT5FeatureExtractor:()=>Bt,SpeechT5Processor:()=>Er,Swin2SRImageProcessor:()=>vt,ViTFeatureExtractor:()=>W,ViTImageProcessor:()=>fe,VitMatteImageProcessor:()=>Et,Wav2Vec2FeatureExtractor:()=>q,Wav2Vec2ProcessorWithLM:()=>At,WeSpeakerFeatureExtractor:()=>Je,WhisperFeatureExtractor:()=>x,WhisperProcessor:()=>It,YolosFeatureExtractor:()=>lt});var z=N("./src/utils/generic.js"),me=N("./src/utils/core.js"),ye=N("./src/utils/hub.js"),Te=N("./src/utils/maths.js"),Ee=N("./src/utils/tensor.js");N("./src/utils/image.js");var j=N("./src/utils/audio.js");function S([at,U,ge,Ae]){return[at-ge/2,U-Ae/2,at+ge/2,U+Ae/2]}function V(at,U=.5,ge=null,Ae=!1){const et=at.logits,ve=at.pred_boxes,[Xe,gt,mt]=et.dims;if(ge!==null&&ge.length!==Xe)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let $t=[];for(let ft=0;ftU&&st.push(wr)}else{let wr=(0,Te.max)(tt.data)[1];if(wr===mt-1||(qt=(0,Te.softmax)(tt.data),qt[wr]Kr*zt[(rr+1)%2])),Nt.boxes.push(Br),Nt.classes.push(wr),Nt.scores.push(qt[wr])}}$t.push(Nt)}return $t}function P(at,U=null){const ge=at.logits,Ae=ge.dims[0];if(U!==null&&U.length!==Ae)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const et=[];for(let ve=0;vezt[st]&&(zt[st]=tt[st],Nt[st]=be)}const Rt=new Array(gt.dims[0]);for(let be=0;bebe!==void 0);et.push({segmentation:ft,labels:Gt})}return et}function te(at,U,ge,Ae){const et=[],ve=[],Xe=[];for(let gt=0;gtge&&(et.push($t),ve.push(Nt),Xe.push(ft))}return[et,ve,Xe]}function ne(at,U,ge,Ae=.5,et=.8){const ve=[];let Xe=0,gt=0;const mt=U[ge].data;for(let ft=0;ft=Ae&&++gt;let $t=Xe>0&>>0;return $t&&($t=Xe/gt>et),[$t,ve]}function _e(at,U,ge,Ae,et,ve=null,Xe=null){const[gt,mt]=Xe??at[0].dims,$t=new Ee.Tensor("int32",new Int32Array(gt*mt),[gt,mt]),ft=[];if(Xe!==null)for(let be=0;beNt[qt]&&(zt[qt]=be,Nt[qt]=st[qt])}let Rt=0;const Gt=$t.data;for(let be=0;beAe&&(ve=Math.floor(et)*U),veve?$t=Math.floor(ve*mt/et):ve>et&&(mt=Math.floor(et*$t/ve)),await U.resize($t,mt,{resample:Ae}))}async crop_margin(U,ge=200){const Ae=U.clone().grayscale(),et=(0,Te.min)(Ae.data)[0],Xe=(0,Te.max)(Ae.data)[0]-et;if(Xe===0)return U;const gt=ge/255;let mt=Ae.width,$t=Ae.height,ft=0,zt=0;const Nt=Ae.data;for(let Rt=0;Rtthis.preprocess(ve)));return{pixel_values:(0,Ee.stack)(Ae.map(ve=>ve.pixel_values),0),original_sizes:Ae.map(ve=>ve.original_size),reshaped_input_sizes:Ae.map(ve=>ve.reshaped_input_size)}}}class R extends X{post_process_semantic_segmentation(...U){return P(...U)}}class I extends X{post_process_semantic_segmentation(...U){return P(...U)}}class L extends X{}class k extends X{}class de extends k{}class Me extends X{}class ke extends X{}class ze extends X{}class Ie extends ze{}class Ze extends X{}class Ke extends X{}class ut extends X{constructor(U){super(U),this.crop_pct=this.config.crop_pct??.875}async resize(U){var Ae;const ge=(Ae=this.size)==null?void 0:Ae.shortest_edge;if(ge===void 0)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(ge<384){const et=Math.floor(ge/this.crop_pct),[ve,Xe]=this.get_resize_output_image_size(U,{shortest_edge:et});U=await U.resize(ve,Xe,{resample:this.resample}),U=await U.center_crop(ge,ge)}else U=await U.resize(ge,ge,{resample:this.resample});return U}}class we extends ut{}class W extends X{}class fe extends X{}class $e extends X{constructor(U){super(U),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map(ge=>ge*ge))}}class Y extends X{}class He extends X{}class dt extends X{}class nt extends X{}class ot extends X{}class Re extends ot{}class ht extends X{post_process_object_detection(...U){return V(...U)}}class bt extends ht{}class qe extends X{post_process_object_detection(...U){return V(...U)}}class ee extends X{}class Pe extends X{}class Ne extends X{pad_image(U,ge,Ae,et={}){const[ve,Xe,gt]=ge;let mt=this.image_mean;Array.isArray(this.image_mean)||(mt=new Array(gt).fill(mt));let $t=this.image_std;Array.isArray($t)||($t=new Array(gt).fill(mt));const ft=mt.map((zt,Nt)=>-zt/$t[Nt]);return super.pad_image(U,ge,Ae,{center:!0,constant_values:ft,...et})}}class Qe extends Ne{}class Ue extends X{async _call(U){const ge=await super._call(U),Ae=[ge.pixel_values.dims[0],64,64],et=(0,Ee.full)(Ae,1n);return{...ge,pixel_mask:et}}post_process_object_detection(...U){return V(...U)}post_process_panoptic_segmentation(...U){return ce(...U)}post_process_instance_segmentation(){throw Error("Not implemented yet")}}class je extends X{post_process_panoptic_segmentation(...U){return ce(...U)}post_process_instance_segmentation(){throw Error("Not implemented yet")}}class lt extends X{post_process_object_detection(...U){return V(...U)}}class yt extends X{reshape_input_points(U,ge,Ae,et=!1){U=structuredClone(U);let ve=(0,me.calculateDimensions)(U);if(ve.length===3)et||(ve=[1,...ve]),U=[U];else if(ve.length!==4)throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.");for(let Xe=0;Xeet!==ge.dims[ve]))throw Error(`The first ${Ae.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new Ee.Tensor("int64",U.flat(1/0).map(BigInt),Ae)}async _call(U,{input_points:ge=null,input_labels:Ae=null,input_boxes:et=null}={}){const ve=await super._call(U);if(ge&&(ve.input_points=this.reshape_input_points(ge,ve.original_sizes,ve.reshaped_input_sizes)),Ae){if(!ve.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");ve.input_labels=this.add_input_labels(Ae,ve.input_points)}return et&&(ve.input_boxes=this.reshape_input_points(et,ve.original_sizes,ve.reshaped_input_sizes,!0)),ve}async post_process_masks(U,ge,Ae,{mask_threshold:et=0,binarize:ve=!0,pad_size:Xe=null}={}){const gt=[];Xe=Xe??this.pad_size;const mt=[Xe.height,Xe.width];for(let $t=0;$tet&&(Gt[be]=1);Nt=new Ee.Tensor("bool",Gt,Nt.dims)}gt.push(Nt)}return gt}generate_crop_boxes(U,ge,{crop_n_layers:Ae=0,overlap_ratio:et=.3413333333333333,points_per_crop:ve=32,crop_n_points_downscale_factor:Xe=1}={}){}}class vt extends X{pad_image(U,ge,Ae,et={}){const[ve,Xe,gt]=ge;return super.pad_image(U,ge,{width:Xe+(Ae-Xe%Ae)%Ae,height:ve+(Ae-ve%Ae)%Ae},{mode:"symmetric",center:!1,constant_values:-1,...et})}}class Et extends X{async _call(U,ge){Array.isArray(U)||(U=[U]),Array.isArray(ge)||(ge=[ge]);const Ae=await Promise.all(U.map(Xe=>this.preprocess(Xe))),et=await Promise.all(ge.map(Xe=>this.preprocess(Xe,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:(0,Ee.stack)(Ae.map((Xe,gt)=>(0,Ee.cat)([Xe.pixel_values,et[gt].pixel_values],0)),0),original_sizes:Ae.map(Xe=>Xe.original_size),reshaped_input_sizes:Ae.map(Xe=>Xe.reshaped_input_size)}}}class x extends ie{constructor(U){var ge;super(U),(ge=this.config).mel_filters??(ge.mel_filters=(0,j.mel_filter_bank)(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,8e3,this.config.sampling_rate,"slaney","slaney")),this.window=(0,j.window_function)(this.config.n_fft,"hann")}async _extract_fbank_features(U){const ge=await(0,j.spectrogram)(U,this.window,this.config.n_fft,this.config.hop_length,{power:2,mel_filters:this.config.mel_filters,log_mel:"log10",max_num_frames:this.config.nb_max_frames}),Ae=ge.data,et=(0,Te.max)(Ae)[0];for(let ve=0;vethis.config.n_samples?(console.warn("Attempting to extract features for audio longer than 30 seconds. If using a pipeline to extract transcript from a long audio clip, remember to specify `chunk_length_s` and/or `stride_length_s`."),ge=U.slice(0,this.config.n_samples)):(ge=new Float32Array(this.config.n_samples),ge.set(U)),{input_features:(await this._extract_fbank_features(ge)).unsqueeze_(0)}}}class q extends ie{_zero_mean_unit_var_norm(U){const Ae=U.reduce((ve,Xe)=>ve+Xe,0)/U.length,et=U.reduce((ve,Xe)=>ve+(Xe-Ae)**2,0)/U.length;return U.map(ve=>(ve-Ae)/Math.sqrt(et+1e-7))}async _call(U){D(U,"Wav2Vec2FeatureExtractor"),U instanceof Float64Array&&(U=new Float32Array(U));let ge=U;this.config.do_normalize&&(ge=this._zero_mean_unit_var_norm(ge));const Ae=[1,ge.length];return{input_values:new Ee.Tensor("float32",ge,Ae),attention_mask:new Ee.Tensor("int64",new BigInt64Array(ge.length).fill(1n),Ae)}}}class $ extends ie{constructor(U){super(U);const ge=this.config.sampling_rate,Ae=(0,j.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(ge/2),ge,null,"kaldi",!0);for(let et=0;etAe*32768),(0,j.spectrogram)(U,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:ge,transpose:!0})}async _call(U,{padding:ge=!0,pad_to_multiple_of:Ae=2,do_normalize_per_mel_bins:et=!0,return_attention_mask:ve=!0}={}){D(U,"SeamlessM4TFeatureExtractor");let Xe=await this._extract_fbank_features(U,this.config.max_length);if(et){const[Gt,be]=Xe.dims,tt=Xe.data;for(let st=0;st0){const qt=new Float32Array(be*(Gt+st));qt.set(tt),qt.fill(this.config.padding_value,tt.length);const wr=Gt+st;Xe=new Ee.Tensor(Xe.type,qt,[wr,be]),ve&&(gt=new Ee.Tensor("int64",new BigInt64Array(wr),[1,wr]),gt.data.fill(1n,0,Gt))}}const[mt,$t]=Xe.dims,ft=this.config.stride;if(mt%ft!==0)throw new Error(`The number of frames (${mt}) must be a multiple of the stride (${ft}).`);const Nt=Xe.view(1,Math.floor(mt/ft),$t*ft),Rt={input_features:Nt};if(ve){const Gt=Nt.dims[1],be=new BigInt64Array(Gt);if(gt){const tt=gt.data;for(let st=1,qt=0;st0)if(Ae==="rand_trunc"){const gt=Math.floor(Math.random()*(Xe+1));U=U.subarray(gt,gt+ge),ve=await this._extract_fbank_features(U,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${Ae}" not implemented`);else{if(Xe<0){let gt=new Float64Array(ge);if(gt.set(U),et==="repeat")for(let mt=U.length;mt({id:mt,start:$t*Ae,end:ft*Ae,confidence:zt/(ft-$t)})))}return et}}class Je extends ie{constructor(U){super(U);const ge=this.config.sampling_rate,Ae=(0,j.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(ge/2),ge,null,"kaldi",!0);for(let et=0;etge*32768),(0,j.spectrogram)(U,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,transpose:!0,min_num_frames:this.min_num_frames})}async _call(U){D(U,"WeSpeakerFeatureExtractor");const ge=(await this._extract_fbank_features(U)).unsqueeze_(0);if(this.config.fbank_centering_span===null){const Ae=ge.mean(1).data,et=ge.data,[ve,Xe,gt]=ge.dims;for(let mt=0;mt/gm,bboxes:/([^<]+)?/gm},this.size_per_bin=1e3}construct_prompts(U){typeof U=="string"&&(U=[U]);const ge=[];for(const Ae of U)if(this.task_prompts_without_inputs.has(Ae))ge.push(this.task_prompts_without_inputs.get(Ae));else{for(const[et,ve]of this.task_prompts_with_input)if(Ae.includes(et)){ge.push(ve.replaceAll("{input}",Ae).replaceAll(et,""));break}ge.length!==U.length&&ge.push(Ae)}return ge}post_process_generation(U,ge,Ae){const et=this.tasks_answer_post_processing_type.get(ge)??"pure_text";U=U.replaceAll("","").replaceAll("","");let ve;switch(et){case"pure_text":ve=U;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":const Xe=et==="ocr"?"quad_boxes":"bboxes",gt=U.matchAll(this.regexes[Xe]),mt=[],$t=[];for(const[ft,zt,...Nt]of gt)mt.push(zt?zt.trim():mt.at(-1)??""),$t.push(Nt.map((Rt,Gt)=>(Number(Rt)+.5)/this.size_per_bin*Ae[Gt%2]));ve={labels:mt,[Xe]:$t};break;default:throw new Error(`Task "${ge}" (of type "${et}") not yet implemented.`)}return{[ge]:ve}}}class Ur{static async from_pretrained(U,{progress_callback:ge=null,config:Ae=null,cache_dir:et=null,local_files_only:ve=!1,revision:Xe="main"}={}){let gt=Ae??await(0,ye.getModelJSON)(U,"preprocessor_config.json",!0,{progress_callback:ge,config:Ae,cache_dir:et,local_files_only:ve,revision:Xe}),mt=gt.feature_extractor_type??gt.image_processor_type,$t=this.FEATURE_EXTRACTOR_CLASS_MAPPING[mt];if(!$t)if(gt.size!==void 0)console.warn(`Feature extractor type "${mt}" not found, assuming ImageFeatureExtractor due to size parameter in config.`),$t=X;else throw new Error(`Unknown Feature Extractor type: ${mt}`);let ft=this.PROCESSOR_CLASS_MAPPING[gt.processor_class]??ct,zt=new $t(gt);return new ft(zt)}}xe(Ur,"FEATURE_EXTRACTOR_CLASS_MAPPING",{ImageFeatureExtractor:X,WhisperFeatureExtractor:x,ViTFeatureExtractor:W,MobileViTFeatureExtractor:ot,MobileViTImageProcessor:Re,MobileNetV1FeatureExtractor:Y,MobileNetV2FeatureExtractor:He,MobileNetV3FeatureExtractor:dt,MobileNetV4FeatureExtractor:nt,OwlViTFeatureExtractor:ht,Owlv2ImageProcessor:bt,CLIPFeatureExtractor:ze,CLIPImageProcessor:Ie,Florence2Processor:Or,ChineseCLIPFeatureExtractor:Ze,SiglipImageProcessor:Ke,ConvNextFeatureExtractor:ut,ConvNextImageProcessor:we,SegformerFeatureExtractor:I,SapiensFeatureExtractor:R,BitImageProcessor:Me,DPTImageProcessor:de,DPTFeatureExtractor:k,PvtImageProcessor:L,GLPNFeatureExtractor:ke,BeitFeatureExtractor:Pe,DeiTFeatureExtractor:ee,DetrFeatureExtractor:Ue,RTDetrImageProcessor:qe,MaskFormerFeatureExtractor:je,YolosFeatureExtractor:lt,DonutFeatureExtractor:Ne,NougatImageProcessor:Qe,EfficientNetImageProcessor:$e,ViTImageProcessor:fe,VitMatteImageProcessor:Et,SamImageProcessor:yt,Swin2SRImageProcessor:vt,Wav2Vec2FeatureExtractor:q,SeamlessM4TFeatureExtractor:$,SpeechT5FeatureExtractor:Bt,ASTFeatureExtractor:Q,ClapFeatureExtractor:he,PyAnnoteFeatureExtractor:Ye,WeSpeakerFeatureExtractor:Je}),xe(Ur,"PROCESSOR_CLASS_MAPPING",{WhisperProcessor:It,Wav2Vec2ProcessorWithLM:At,PyAnnoteProcessor:cr,SamProcessor:Tt,SpeechT5Processor:Er,OwlViTProcessor:Qr,Florence2Processor:Or})},"./src/tokenizers.js":(Pt,Ce,N)=>{N.r(Ce),N.d(Ce,{AlbertTokenizer:()=>gt,AutoTokenizer:()=>ns,BartTokenizer:()=>Kr,BertTokenizer:()=>Xe,BlenderbotSmallTokenizer:()=>Ps,BlenderbotTokenizer:()=>_s,BloomTokenizer:()=>Ln,CLIPTokenizer:()=>fs,CamembertTokenizer:()=>tt,CodeGenTokenizer:()=>hs,CodeLlamaTokenizer:()=>Cs,CohereTokenizer:()=>ws,ConvBertTokenizer:()=>Rt,DebertaTokenizer:()=>ft,DebertaV2Tokenizer:()=>zt,DistilBertTokenizer:()=>be,ElectraTokenizer:()=>qt,EsmTokenizer:()=>Gn,FalconTokenizer:()=>$s,GPT2Tokenizer:()=>Br,GPTNeoXTokenizer:()=>Ss,GemmaTokenizer:()=>Qs,Grok1Tokenizer:()=>qn,HerbertTokenizer:()=>Nt,LlamaTokenizer:()=>Bn,M2M100Tokenizer:()=>ps,MBart50Tokenizer:()=>Wr,MBartTokenizer:()=>rr,MPNetTokenizer:()=>Es,MarianTokenizer:()=>Xt,MobileBertTokenizer:()=>mt,NllbTokenizer:()=>Cn,NougatTokenizer:()=>gs,PreTrainedTokenizer:()=>ve,Qwen2Tokenizer:()=>ks,RoFormerTokenizer:()=>Gt,RobertaTokenizer:()=>Vr,SiglipTokenizer:()=>rs,SpeechT5Tokenizer:()=>As,SqueezeBertTokenizer:()=>$t,T5Tokenizer:()=>wr,TokenizerModel:()=>ke,VitsTokenizer:()=>Is,Wav2Vec2CTCTokenizer:()=>ms,WhisperTokenizer:()=>ts,XLMRobertaTokenizer:()=>Xs,XLMTokenizer:()=>st,is_chinese_char:()=>X});var z=N("./src/utils/generic.js"),me=N("./src/utils/core.js"),ye=N("./src/utils/hub.js"),Te=N("./src/utils/maths.js"),Ee=N("./src/utils/tensor.js"),j=N("./src/utils/data-structures.js"),S=N("./node_modules/@huggingface/jinja/dist/index.js"),V=N("./src/models/whisper/common_whisper.js"),P=N("./src/utils/constants.js");async function te(ue,m){const A=await Promise.all([(0,ye.getModelJSON)(ue,"tokenizer.json",!0,m),(0,ye.getModelJSON)(ue,"tokenizer_config.json",!0,m)]);return m.legacy!==null&&(A[1].legacy=m.legacy),A}function ne(ue,m){const A=[];let H=0;for(const se of ue.matchAll(m)){const pe=se[0];H0&&A.push(pe),H=se.index+pe.length}return H=19968&&ue<=40959||ue>=13312&&ue<=19903||ue>=131072&&ue<=173791||ue>=173824&&ue<=177983||ue>=177984&&ue<=178207||ue>=178208&&ue<=183983||ue>=63744&&ue<=64255||ue>=194560&&ue<=195103}function R(ue,m,A){const H=[];let se=0;for(;sethis.tokens_to_ids.get(A)??this.unk_token_id)}convert_ids_to_tokens(m){return m.map(A=>this.vocab[A]??this.unk_token)}}class ze extends ke{constructor(m){super(m),this.tokens_to_ids=ce(m.vocab),this.unk_token_id=this.tokens_to_ids.get(m.unk_token),this.unk_token=m.unk_token,this.max_input_chars_per_word=m.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(const[A,H]of this.tokens_to_ids)this.vocab[H]=A}encode(m){const A=[];for(const H of m){const se=[...H];if(se.length>this.max_input_chars_per_word){A.push(this.unk_token);continue}let pe=!1,De=0;const wt=[];for(;De0&&(Ot=this.config.continuing_subword_prefix+Ot),this.tokens_to_ids.has(Ot)){Mt=Ot;break}--xt}if(Mt===null){pe=!0;break}wt.push(Mt),De=xt}pe?A.push(this.unk_token):A.push(...wt)}return A}}class Ie extends ke{constructor(m,A){super(m);const H=m.vocab.length;this.vocab=new Array(H),this.scores=new Array(H);for(let se=0;se[se,pe])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=A.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.unk_token=this.vocab[this.unk_token_id],this.minScore=(0,Te.min)(this.scores)[0],this.unk_score=this.minScore-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new j.CharTrie,this.trie.extend(this.vocab),this.fuse_unk=!0}populateNodes(m){const A=m.chars,H=1;let se=0;for(;se{const ue=[...Array.from({length:94},(se,pe)=>pe+33),...Array.from({length:12},(se,pe)=>pe+161),...Array.from({length:82},(se,pe)=>pe+174)],m=ue.slice();let A=0;for(let se=0;se<256;++se)ue.includes(se)||(ue.push(se),m.push(256+A),A+=1);const H=m.map(se=>String.fromCharCode(se));return Object.fromEntries(ue.map((se,pe)=>[se,H[pe]]))})(),Ke=(0,me.reverseDictionary)(Ze);class ut extends ke{constructor(m){super(m),this.tokens_to_ids=ce(m.vocab),this.unk_token_id=this.tokens_to_ids.get(m.unk_token),this.unk_token=m.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(const[H,se]of this.tokens_to_ids)this.vocab[se]=H;const A=Array.isArray(m.merges[0]);this.merges=A?m.merges:m.merges.map(H=>H.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((H,se)=>[JSON.stringify(H),se])),this.end_of_word_suffix=m.end_of_word_suffix,this.continuing_subword_suffix=m.continuing_subword_suffix??null,this.byte_fallback=this.config.byte_fallback??!1,this.byte_fallback&&(this.text_encoder=new TextEncoder),this.ignore_merges=this.config.ignore_merges??!1,this.cache=new Map}bpe(m){if(m.length===0)return[];const A=this.cache.get(m);if(A!==void 0)return A;const H=Array.from(m);this.end_of_word_suffix&&(H[H.length-1]+=this.end_of_word_suffix);let se=[];if(H.length>1){const pe=new j.PriorityQueue((xt,Mt)=>xt.score`<0x${wt.toString(16).toUpperCase().padStart(2,"0")}>`);De.every(wt=>this.tokens_to_ids.has(wt))?A.push(...De):A.push(this.unk_token)}else A.push(this.unk_token)}return A}}class we extends ke{constructor(m,A){super(m),this.tokens_to_ids=ce(A.target_lang?m.vocab[A.target_lang]:m.vocab),this.bos_token=A.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=A.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=A.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=A.unk_token,this.unk_token_id=this.tokens_to_ids.get(this.unk_token),this.vocab=new Array(this.tokens_to_ids.size);for(const[H,se]of this.tokens_to_ids)this.vocab[se]=H}encode(m){return m}}class W extends z.Callable{constructor(m){super(),this.config=m}static fromConfig(m){if(m===null)return null;switch(m.type){case"BertNormalizer":return new bt(m);case"Precompiled":return new Qr(m);case"Sequence":return new ht(m);case"Replace":return new fe(m);case"NFC":return new $e(m);case"NFKC":return new Y(m);case"NFKD":return new He(m);case"Strip":return new dt(m);case"StripAccents":return new nt(m);case"Lowercase":return new ot(m);case"Prepend":return new Re(m);default:throw new Error(`Unknown Normalizer type: ${m.type}`)}}normalize(m){throw Error("normalize should be implemented in subclass.")}_call(m){return this.normalize(m)}}class fe extends W{normalize(m){const A=_e(this.config.pattern);return A===null?m:m.replaceAll(A,this.config.content)}}class $e extends W{normalize(m){return m=m.normalize("NFC"),m}}class Y extends W{normalize(m){return m=m.normalize("NFKC"),m}}class He extends W{normalize(m){return m=m.normalize("NFKD"),m}}class dt extends W{normalize(m){return this.config.strip_left&&this.config.strip_right?m=m.trim():(this.config.strip_left&&(m=m.trimStart()),this.config.strip_right&&(m=m.trimEnd())),m}}class nt extends W{normalize(m){return m=re(m),m}}class ot extends W{normalize(m){return m=m.toLowerCase(),m}}class Re extends W{normalize(m){return m=this.config.prepend+m,m}}class ht extends W{constructor(m){super(m),this.normalizers=m.normalizers.map(A=>W.fromConfig(A))}normalize(m){return this.normalizers.reduce((A,H)=>H.normalize(A),m)}}class bt extends W{_tokenize_chinese_chars(m){const A=[];for(let H=0;Hthis.pre_tokenize_text(H,A)):this.pre_tokenize_text(m,A)).flat()}_call(m,A){return this.pre_tokenize(m,A)}}class ee extends qe{constructor(m){super(),this.pattern=new RegExp(`[^\\s${L}]+|[${L}]`,"gu")}pre_tokenize_text(m,A){return m.trim().match(this.pattern)||[]}}class Pe extends qe{constructor(m){super(),this.config=m,this.add_prefix_space=this.config.add_prefix_space,this.trim_offsets=this.config.trim_offsets,this.use_regex=this.config.use_regex??!0,this.pattern=new RegExp("'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)|\\s+","gu"),this.byte_encoder=Ze,this.text_encoder=new TextEncoder}pre_tokenize_text(m,A){return this.add_prefix_space&&!m.startsWith(" ")&&(m=" "+m),(this.use_regex?m.match(this.pattern)||[]:[m]).map(se=>Array.from(this.text_encoder.encode(se),pe=>this.byte_encoder[pe]).join(""))}}class Ne extends qe{constructor(m){super(),this.config=m,this.pattern=_e(this.config.pattern,this.config.invert)}pre_tokenize_text(m,A){return this.pattern===null?[]:this.config.invert?m.match(this.pattern)||[]:ne(m,this.pattern)}}class Qe extends qe{constructor(m){super(),this.config=m,this.pattern=new RegExp(`[^${L}]+|[${L}]+`,"gu")}pre_tokenize_text(m,A){return m.match(this.pattern)||[]}}class Ue extends qe{constructor(m){super(),this.config=m;const A=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(A,"gu")}pre_tokenize_text(m,A){return m.match(this.pattern)||[]}}class je extends z.Callable{constructor(m){super(),this.config=m}static fromConfig(m){if(m===null)return null;switch(m.type){case"TemplateProcessing":return new vt(m);case"ByteLevel":return new Et(m);case"RobertaProcessing":return new yt(m);case"BertProcessing":return new lt(m);case"Sequence":return new x(m);default:throw new Error(`Unknown PostProcessor type: ${m.type}`)}}post_process(m,...A){throw Error("post_process should be implemented in subclass.")}_call(m,...A){return this.post_process(m,...A)}}class lt extends je{constructor(m){super(m),this.cls=m.cls[0],this.sep=m.sep[0]}post_process(m,A=null,{add_special_tokens:H=!0}={}){H&&(m=(0,me.mergeArrays)([this.cls],m,[this.sep]));let se=new Array(m.length).fill(0);if(A!==null){const pe=H&&this instanceof yt?[this.sep]:[],De=H?[this.sep]:[];m=(0,me.mergeArrays)(m,pe,A,De),se=(0,me.mergeArrays)(se,new Array(A.length+pe.length+De.length).fill(1))}return{tokens:m,token_type_ids:se}}}class yt extends lt{}class vt extends je{constructor(m){super(m),this.single=m.single,this.pair=m.pair}post_process(m,A=null,{add_special_tokens:H=!0}={}){const se=A===null?this.single:this.pair;let pe=[],De=[];for(const wt of se)"SpecialToken"in wt?H&&(pe.push(wt.SpecialToken.id),De.push(wt.SpecialToken.type_id)):"Sequence"in wt&&(wt.Sequence.id==="A"?(pe=(0,me.mergeArrays)(pe,m),De=(0,me.mergeArrays)(De,new Array(m.length).fill(wt.Sequence.type_id))):wt.Sequence.id==="B"&&(pe=(0,me.mergeArrays)(pe,A),De=(0,me.mergeArrays)(De,new Array(A.length).fill(wt.Sequence.type_id))));return{tokens:pe,token_type_ids:De}}}class Et extends je{post_process(m,A=null){return A&&(m=(0,me.mergeArrays)(m,A)),{tokens:m}}}class x extends je{constructor(m){super(m),this.processors=m.processors.map(A=>je.fromConfig(A))}post_process(m,A=null,H={}){let se;for(const pe of this.processors)if(pe instanceof Et)m=pe.post_process(m).tokens,A&&(A=pe.post_process(A).tokens);else{const De=pe.post_process(m,A,H);m=De.tokens,se=De.token_type_ids}return{tokens:m,token_type_ids:se}}}class q extends z.Callable{constructor(m){super(),this.config=m,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets=m.trim_offsets}static fromConfig(m){if(m===null)return null;switch(m.type){case"WordPiece":return new Je(m);case"Metaspace":return new Er(m);case"ByteLevel":return new Bt(m);case"Replace":return new $(m);case"ByteFallback":return new Q(m);case"Fuse":return new he(m);case"Strip":return new Ye(m);case"Sequence":return new Tt(m);case"CTC":return new ct(m);case"BPEDecoder":return new It(m);default:throw new Error(`Unknown Decoder type: ${m.type}`)}}_call(m){return this.decode(m)}decode(m){return this.decode_chain(m).join("")}decode_chain(m){throw Error("`decode_chain` should be implemented in subclass.")}}class $ extends q{decode_chain(m){const A=_e(this.config.pattern);return A===null?m:m.map(H=>H.replaceAll(A,this.config.content))}}class Q extends q{constructor(m){super(m),this.text_decoder=new TextDecoder}decode_chain(m){const A=[];let H=[];for(const se of m){let pe=null;if(se.length===6&&se.startsWith("<0x")&&se.endsWith(">")){const De=parseInt(se.slice(3,5),16);isNaN(De)||(pe=De)}if(pe!==null)H.push(pe);else{if(H.length>0){const De=this.text_decoder.decode(Uint8Array.from(H));A.push(De),H=[]}A.push(se)}}if(H.length>0){const se=this.text_decoder.decode(Uint8Array.from(H));A.push(se),H=[]}return A}}class he extends q{decode_chain(m){return[m.join("")]}}class Ye extends q{constructor(m){super(m),this.content=this.config.content,this.start=this.config.start,this.stop=this.config.stop}decode_chain(m){return m.map(A=>{let H=0;for(let pe=0;pe(H!==0&&(A.startsWith(this.config.prefix)?A=A.replace(this.config.prefix,""):A=" "+A),this.cleanup&&(A=K(A)),A))}}class Bt extends q{constructor(m){super(m),this.byte_decoder=Ke,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(m){const A=m.join(""),H=new Uint8Array([...A].map(pe=>this.byte_decoder[pe]));return this.text_decoder.decode(H)}decode_chain(m){const A=[];let H=[];for(const se of m)this.added_tokens.find(pe=>pe.content===se)!==void 0?(H.length>0&&(A.push(this.convert_tokens_to_string(H)),H=[]),A.push(se)):H.push(se);return H.length>0&&A.push(this.convert_tokens_to_string(H)),A}}class ct extends q{constructor(m){super(m),this.pad_token=this.config.pad_token,this.word_delimiter_token=this.config.word_delimiter_token,this.cleanup=this.config.cleanup}convert_tokens_to_string(m){if(m.length===0)return"";const A=[m[0]];for(let pe=1;pepe!==this.pad_token).join("");return this.cleanup&&(se=K(se).replaceAll(this.word_delimiter_token," ").trim()),se}decode_chain(m){return[this.convert_tokens_to_string(m)]}}class Tt extends q{constructor(m){super(m),this.decoders=m.decoders.map(A=>q.fromConfig(A))}decode_chain(m){return this.decoders.reduce((A,H)=>H.decode_chain(A),m)}}class It extends q{constructor(m){super(m),this.suffix=this.config.suffix}decode_chain(m){return m.map((A,H)=>A.replaceAll(this.suffix,H===m.length-1?"":" "))}}class At extends q{decode_chain(m){let A="";for(let H=1;HH.normalize("NFKC")).join("~"):m=m.normalize("NFKC"),m}}class Or extends qe{constructor(m){super(),this.tokenizers=m.pretokenizers.map(A=>qe.fromConfig(A))}pre_tokenize_text(m,A){return this.tokenizers.reduce((H,se)=>se.pre_tokenize(H,A),[m])}}class Ur extends qe{constructor(m){super()}pre_tokenize_text(m,A){return m.match(/\w+|[^\w\s]+/g)||[]}}class at extends qe{constructor(m){super()}pre_tokenize_text(m,A){return I(m)}}class U extends qe{constructor(m){super(),this.config=m,this.pattern=_e(this.config.pattern),this.content=this.config.content}pre_tokenize_text(m,A){return this.pattern===null?[m]:[m.replaceAll(this.pattern,this.config.content)]}}const ge=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function Ae(ue,m,A,H){for(const se of Object.keys(ue)){const pe=m-ue[se].length,De=A(se),wt=new Array(pe).fill(De);ue[se]=H==="right"?(0,me.mergeArrays)(ue[se],wt):(0,me.mergeArrays)(wt,ue[se])}}function et(ue,m){for(const A of Object.keys(ue))ue[A].length=m}class ve extends z.Callable{constructor(A,H){super();xe(this,"return_token_type_ids",!1);xe(this,"padding_side","right");this._tokenizer_config=H,this.normalizer=W.fromConfig(A.normalizer),this.pre_tokenizer=qe.fromConfig(A.pre_tokenizer),this.model=ke.fromConfig(A.model,H),this.post_processor=je.fromConfig(A.post_processor),this.decoder=q.fromConfig(A.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];for(const se of A.added_tokens){const pe=new Me(se);this.added_tokens.push(pe),this.model.tokens_to_ids.set(pe.content,pe.id),this.model.vocab[pe.id]=pe.content,pe.special&&(this.special_tokens.push(pe.content),this.all_special_ids.push(pe.id))}if(this.additional_special_tokens=H.additional_special_tokens??[],this.special_tokens.push(...this.additional_special_tokens),this.special_tokens=[...new Set(this.special_tokens)],this.decoder&&(this.decoder.added_tokens=this.added_tokens,this.decoder.end_of_word_suffix=this.model.end_of_word_suffix),this.added_tokens_regex=this.added_tokens.length>0?new RegExp(this.added_tokens.slice().sort((se,pe)=>pe.content.length-se.content.length).map(se=>`${se.lstrip?"\\s*":""}(${(0,me.escapeRegExp)(se.content)})${se.rstrip?"\\s*":""}`).join("|")):null,this.mask_token=this.getToken("mask_token"),this.mask_token_id=this.model.tokens_to_ids.get(this.mask_token),this.pad_token=this.getToken("pad_token","eos_token"),this.pad_token_id=this.model.tokens_to_ids.get(this.pad_token),this.sep_token=this.getToken("sep_token"),this.sep_token_id=this.model.tokens_to_ids.get(this.sep_token),this.unk_token=this.getToken("unk_token"),this.unk_token_id=this.model.tokens_to_ids.get(this.unk_token),this.model_max_length=H.model_max_length,this.remove_space=H.remove_space,this.clean_up_tokenization_spaces=H.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=H.do_lowercase_and_remove_accent??!1,H.padding_side&&(this.padding_side=H.padding_side),this.legacy=!1,this.chat_template=H.chat_template??null,Array.isArray(this.chat_template)){const se=Object.create(null);for(const{name:pe,template:De}of this.chat_template){if(typeof pe!="string"||typeof De!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');se[pe]=De}this.chat_template=se}this._compiled_template_cache=new Map}getToken(...A){for(const H of A){const se=this._tokenizer_config[H];if(se)if(typeof se=="object"){if(se.__type==="AddedToken")return se.content;throw Error(`Unknown token: ${se}`)}else return se}return null}static async from_pretrained(A,{progress_callback:H=null,config:se=null,cache_dir:pe=null,local_files_only:De=!1,revision:wt="main",legacy:xt=null}={}){const Mt=await te(A,{progress_callback:H,config:se,cache_dir:pe,local_files_only:De,revision:wt,legacy:xt});return new this(...Mt)}_call(A,{text_pair:H=null,add_special_tokens:se=!0,padding:pe=!1,truncation:De=null,max_length:wt=null,return_tensor:xt=!0,return_token_type_ids:Mt=null}={}){const Ot=Array.isArray(A);let Yt;if(Ot){if(A.length===0)throw Error("text array must be non-empty");if(H!==null){if(Array.isArray(H)){if(A.length!==H.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");Yt=A.map((ar,Dr)=>this._encode_plus(ar,{text_pair:H[Dr],add_special_tokens:se,return_token_type_ids:Mt}))}else Yt=A.map(ar=>this._encode_plus(ar,{add_special_tokens:se,return_token_type_ids:Mt}))}else{if(A==null)throw Error("text may not be null or undefined");if(Array.isArray(H))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");Yt=[this._encode_plus(A,{text_pair:H,add_special_tokens:se,return_token_type_ids:Mt})]}if(wt===null?pe==="max_length"?wt=this.model_max_length:wt=(0,Te.max)(Yt.map(ar=>ar.input_ids.length))[0]:De||console.warn("Truncation was not explicitly activated but `max_length` is provided a specific value, please use `truncation=true` to explicitly truncate examples to max length."),wt=Math.min(wt,this.model_max_length??1/0),pe||De)for(let ar=0;arwt?De&&et(Yt[ar],wt):pe&&Ae(Yt[ar],wt,Dr=>Dr==="input_ids"?this.pad_token_id:0,this.padding_side));const $r={};if(xt){if(!(pe&&De)&&Yt.some(Dr=>{var Jr;for(const ur of Object.keys(Dr))if(Dr[ur].length!==((Jr=Yt[0][ur])==null?void 0:Jr.length))return!0;return!1}))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=true' and 'truncation=true' to have batched tensors with the same length.");const ar=[Yt.length,Yt[0].input_ids.length];for(const Dr of Object.keys(Yt[0]))$r[Dr]=new Ee.Tensor("int64",BigInt64Array.from(Yt.flatMap(Jr=>Jr[Dr]).map(BigInt)),ar)}else{for(const ar of Object.keys(Yt[0]))$r[ar]=Yt.map(Dr=>Dr[ar]);if(!Ot)for(const ar of Object.keys($r))$r[ar]=$r[ar][0]}return $r}_encode_text(A){return A===null?null:(this.added_tokens_regex?A.split(this.added_tokens_regex).filter(pe=>pe):[A]).map((pe,De)=>{if(this.added_tokens.find(xt=>xt.content===pe)!==void 0)return pe;{if(this.remove_space===!0&&(pe=pe.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(pe=ie(pe)),this.normalizer!==null&&(pe=this.normalizer(pe)),pe.length===0)return[];const xt=this.pre_tokenizer!==null?this.pre_tokenizer(pe,{section_index:De}):[pe];return this.model(xt)}}).flat()}_encode_plus(A,{text_pair:H=null,add_special_tokens:se=!0,return_token_type_ids:pe=null}={}){const{tokens:De,token_type_ids:wt}=this._tokenize_helper(A,{pair:H,add_special_tokens:se}),xt=this.model.convert_tokens_to_ids(De),Mt={input_ids:xt,attention_mask:new Array(xt.length).fill(1)};return(pe??this.return_token_type_ids)&&wt&&(Mt.token_type_ids=wt),Mt}_tokenize_helper(A,{pair:H=null,add_special_tokens:se=!1}={}){const pe=this._encode_text(A),De=this._encode_text(H);return this.post_processor?this.post_processor(pe,De,{add_special_tokens:se}):{tokens:(0,me.mergeArrays)(pe??[],De??[])}}tokenize(A,{pair:H=null,add_special_tokens:se=!1}={}){return this._tokenize_helper(A,{pair:H,add_special_tokens:se}).tokens}encode(A,{text_pair:H=null,add_special_tokens:se=!0,return_token_type_ids:pe=null}={}){return this._encode_plus(A,{text_pair:H,add_special_tokens:se,return_token_type_ids:pe}).input_ids}batch_decode(A,H={}){return A instanceof Ee.Tensor&&(A=A.tolist()),A.map(se=>this.decode(se,H))}decode(A,H={}){if(A instanceof Ee.Tensor&&(A=D(A)),!Array.isArray(A)||A.length===0||!(0,me.isIntegralNumber)(A[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(A,H)}decode_single(A,{skip_special_tokens:H=!1,clean_up_tokenization_spaces:se=null}){let pe=this.model.convert_ids_to_tokens(A);H&&(pe=pe.filter(wt=>!this.special_tokens.includes(wt)));let De=this.decoder?this.decoder(pe):pe.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(De=De.replaceAll(this.decoder.end_of_word_suffix," "),H&&(De=De.trim())),(se??this.clean_up_tokenization_spaces)&&(De=K(De)),De}get_chat_template({chat_template:A=null,tools:H=null}={}){if(this.chat_template&&typeof this.chat_template=="object"){const se=this.chat_template;if(A!==null&&Object.hasOwn(se,A))A=se[A];else if(A===null)if(H!==null&&"tool_use"in se)A=se.tool_use;else if("default"in se)A=se.default;else throw Error(`This model has multiple chat templates with no default specified! Please either pass a chat template or the name of the template you wish to use to the 'chat_template' argument. Available template names are ${Object.keys(se).sort()}.`)}else if(A===null)if(this.chat_template)A=this.chat_template;else throw Error("Cannot use apply_chat_template() because tokenizer.chat_template is not set and no template argument was passed! For information about writing templates and setting the tokenizer.chat_template attribute, please see the documentation at https://huggingface.co/docs/transformers/main/en/chat_templating");return A}apply_chat_template(A,{tools:H=null,documents:se=null,chat_template:pe=null,add_generation_prompt:De=!1,tokenize:wt=!0,padding:xt=!1,truncation:Mt=!1,max_length:Ot=null,return_tensor:Yt=!0,return_dict:$r=!1,tokenizer_kwargs:ar={},...Dr}={}){if(pe=this.get_chat_template({chat_template:pe,tools:H}),typeof pe!="string")throw Error(`chat_template must be a string, but got ${typeof pe}`);let Jr=this._compiled_template_cache.get(pe);Jr===void 0&&(Jr=new S.Template(pe),this._compiled_template_cache.set(pe,Jr));const ur=Object.create(null);for(const _n of ge){const wn=this.getToken(_n);wn&&(ur[_n]=wn)}const Sr=Jr.render({messages:A,add_generation_prompt:De,tools:H,documents:se,...ur,...Dr});if(wt){const _n=this._call(Sr,{add_special_tokens:!1,padding:xt,truncation:Mt,max_length:Ot,return_tensor:Yt,...ar});return $r?_n:_n.input_ids}return Sr}}class Xe extends ve{constructor(){super(...arguments);xe(this,"return_token_type_ids",!0)}}class gt extends ve{constructor(){super(...arguments);xe(this,"return_token_type_ids",!0)}}class mt extends ve{constructor(){super(...arguments);xe(this,"return_token_type_ids",!0)}}class $t extends ve{constructor(){super(...arguments);xe(this,"return_token_type_ids",!0)}}class ft extends ve{constructor(){super(...arguments);xe(this,"return_token_type_ids",!0)}}class zt extends ve{constructor(){super(...arguments);xe(this,"return_token_type_ids",!0)}}class Nt extends ve{constructor(){super(...arguments);xe(this,"return_token_type_ids",!0)}}class Rt extends ve{constructor(){super(...arguments);xe(this,"return_token_type_ids",!0)}}class Gt extends ve{constructor(){super(...arguments);xe(this,"return_token_type_ids",!0)}}class be extends ve{}class tt extends ve{}class st extends ve{constructor(A,H){super(A,H);xe(this,"return_token_type_ids",!0);console.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}}class qt extends ve{constructor(){super(...arguments);xe(this,"return_token_type_ids",!0)}}class wr extends ve{}class Br extends ve{}class Kr extends ve{}class rr extends ve{constructor(m,A){super(m,A),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.special_tokens.filter(H=>this.languageRegex.test(H)),this.lang_to_token=H=>H}_build_translation_inputs(m,A,H){return Sn(this,m,A,H)}}class Wr extends rr{}class Vr extends ve{}class Ln extends ve{constructor(m,A){var pe,De;const H=".,!?…。,、।۔،",se=(De=(pe=m.pre_tokenizer)==null?void 0:pe.pretokenizers[0])==null?void 0:De.pattern;se&&se.Regex===` ?[^(\\s|[${H}])]+`&&(se.Regex=` ?[^\\s${H}]+`),super(m,A)}}const Rr="▁";class Bn extends ve{constructor(A,H){super(A,H);xe(this,"padding_side","left");this.legacy=H.legacy??!0,this.legacy||(this.normalizer=null,this.pre_tokenizer=new cr({replacement:Rr,add_prefix_space:!0,prepend_scheme:"first"}))}_encode_text(A){if(A===null)return null;if(this.legacy||A.length===0)return super._encode_text(A);let H=super._encode_text(Rr+A.replaceAll(Rr," "));return H.length>1&&H[0]===Rr&&this.special_tokens.includes(H[1])&&(H=H.slice(1)),H}}class Cs extends ve{}class Xs extends ve{}class Es extends ve{}class $s extends ve{}class Ss extends ve{}class Gn extends ve{}class ks extends ve{}class Qs extends ve{}class qn extends ve{}function Sn(ue,m,A,H){if(!("language_codes"in ue)||!Array.isArray(ue.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in ue)||!(ue.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in ue)||typeof ue.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");const se=H.src_lang,pe=H.tgt_lang;if(!ue.language_codes.includes(pe))throw new Error(`Target language code "${pe}" is not valid. Must be one of: {${ue.language_codes.join(", ")}}`);if(se!==void 0){if(!ue.language_codes.includes(se))throw new Error(`Source language code "${se}" is not valid. Must be one of: {${ue.language_codes.join(", ")}}`);for(const De of ue.post_processor.config.single)if("SpecialToken"in De&&ue.languageRegex.test(De.SpecialToken.id)){De.SpecialToken.id=ue.lang_to_token(se);break}}return H.forced_bos_token_id=ue.model.convert_tokens_to_ids([ue.lang_to_token(pe)])[0],ue._call(m,A)}class Cn extends ve{constructor(m,A){super(m,A),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.special_tokens.filter(H=>this.languageRegex.test(H)),this.lang_to_token=H=>H}_build_translation_inputs(m,A,H){return Sn(this,m,A,H)}}class ps extends ve{constructor(m,A){super(m,A),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.special_tokens.filter(H=>this.languageRegex.test(H)).map(H=>H.slice(2,-2)),this.lang_to_token=H=>`__${H}__`}_build_translation_inputs(m,A,H){return Sn(this,m,A,H)}}class ts extends ve{get timestamp_begin(){return this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0]+1}_decode_asr(m,{return_timestamps:A=!1,return_language:H=!1,time_precision:se=null,force_full_sequences:pe=!0}={}){if(se===null)throw Error("Must specify time_precision");let De=null;const wt=A==="word";function xt(){return{language:De,timestamp:[null,null],text:""}}const Mt=[];let Ot=xt(),Yt=0;const $r=this.timestamp_begin;let ar=[],Dr=[],Jr=!1,ur=null;const Sr=new Set(this.all_special_ids);for(const Se of m){const Zr=Se.tokens,xn=wt?Se.token_timestamps:null;let kn=null,Nn=$r;if("stride"in Se){const[Xr,yr,Ar]=Se.stride;if(Yt-=yr,ur=Xr-Ar,yr&&(Nn=yr/se+$r),Ar)for(let Ct=Zr.length-1;Ct>=0;--Ct){const mr=Number(Zr[Ct]);if(mr>=$r){if(kn!==null&&(mr-$r)*se=$r){const Ar=(yr-$r)*se+Yt,Ct=(0,Te.round)(Ar,2);if(kn!==null&&yr>=kn)Jr=!0;else if(Jr||ar.length>0&&yr0?(ar.push(Ht),wt&&Dr.push(en)):ar.every(Xr=>Xr.length===0)&&(Ot=xt(),ar=[],Ht=[],Dr=[],en=[])}if(ar.length>0){if(pe&&A)throw new Error("Whisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. Also make sure WhisperTimeStampLogitsProcessor was used during generation.");const[Se,Zr]=this.findLongestCommonSequence(ar,Dr),xn=this.decode(Se);Ot.text=xn,wt&&(Ot.words=this.collateWordTimestamps(Se,Zr,De)),Mt.push(Ot)}let _n=Object.create(null);const wn=Mt.map(Se=>Se.text).join("");if(A||H){for(let Se=0;Se0;let wt=De?[]:null,xt=De?A[0]:null;for(let Mt=1;MtCt===en[mr]&&xt[Zr+mr]<=A[Mt][Nn+mr]).length:Xr=kn.filter((Ct,mr)=>Ct===en[mr]).length;const yr=Se/1e4,Ar=Xr/Se+yr;Xr>1&&Ar>Yt&&(Yt=Ar,$r=[Zr,xn,Nn,Ht])}const[Dr,Jr,ur,Sr]=$r,_n=Math.floor((Jr+Dr)/2),wn=Math.floor((Sr+ur)/2);pe.push(...H.slice(0,_n)),H=Ot.slice(wn),se=H.length,De&&(wt.push(...xt.slice(0,_n)),xt=A[Mt].slice(wn))}return pe.push(...H),De?(wt.push(...xt),[pe,wt]):[pe,[]]}collateWordTimestamps(m,A,H){const[se,pe,De]=this.combineTokensIntoWords(m,H),wt=[];for(let xt=0;xt=se){const wt=((De-se)*H).toFixed(2);pe.push(`<|${wt}|>`),pe.push([])}else pe[pe.length-1].push(De);return pe=pe.map(De=>typeof De=="string"?De:super.decode(De,A)),pe.join("")}splitTokensOnUnicode(m){const A=this.decode(m,{decode_with_timestamps:!0}),H="�",se=[],pe=[],De=[];let wt=[],xt=[],Mt=0;for(let Ot=0;Ot=this.model.tokens_to_ids.get("<|endoftext|>"),Dr=Ot.startsWith(" "),Jr=Ot.trim(),ur=xt.test(Jr);if(ar||Dr||ur||pe.length===0)pe.push(Ot),De.push(Yt),wt.push($r);else{const Sr=pe.length-1;pe[Sr]+=Ot,De[Sr].push(...Yt),wt[Sr].push(...$r)}}return[pe,De,wt]}mergePunctuations(m,A,H,se,pe){const De=structuredClone(m),wt=structuredClone(A),xt=structuredClone(H);let Mt=De.length-2,Ot=De.length-1;for(;Mt>=0;)De[Mt].startsWith(" ")&&se.includes(De[Mt].trim())?(De[Ot]=De[Mt]+De[Ot],wt[Ot]=(0,me.mergeArrays)(wt[Mt],wt[Ot]),xt[Ot]=(0,me.mergeArrays)(xt[Mt],xt[Ot]),De[Mt]="",wt[Mt]=[],xt[Mt]=[]):Ot=Mt,--Mt;for(Mt=0,Ot=1;OtYt),wt.filter(Yt=>Yt.length>0),xt.filter(Yt=>Yt.length>0)]}get_decoder_prompt_ids({language:m=null,task:A=null,no_timestamps:H=!0}={}){const se=[];if(m){const pe=(0,V.whisper_language_to_code)(m),De=this.model.tokens_to_ids.get(`<|${pe}|>`);if(De===void 0)throw new Error(`Unable to find language "${pe}" in model vocabulary. Please report this issue at ${P.GITHUB_ISSUE_URL}.`);se.push(De)}else se.push(null);if(A){if(A=A.toLowerCase(),A!=="transcribe"&&A!=="translate")throw new Error(`Task "${A}" is not supported. Must be one of: ["transcribe", "translate"]`);const pe=this.model.tokens_to_ids.get(`<|${A}|>`);if(pe===void 0)throw new Error(`Unable to find task "${A}" in model vocabulary. Please report this issue at ${P.GITHUB_ISSUE_URL}.`);se.push(pe)}else se.push(null);if(H){const pe=this.model.tokens_to_ids.get("<|notimestamps|>");if(pe===void 0)throw new Error(`Unable to find "<|notimestamps|>" in model vocabulary. Please report this issue at ${P.GITHUB_ISSUE_URL}.`);se.push(pe)}return se.map((pe,De)=>[De+1,pe]).filter(pe=>pe[1]!==null)}}class hs extends ve{}class fs extends ve{}class rs extends ve{}class Xt extends ve{constructor(m,A){super(m,A),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=this.model.vocab.filter(H=>this.languageRegex.test(H)),console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(m){if(m===null)return null;const[A,...H]=m.trim().split(this.languageRegex);if(H.length===0)return super._encode_text(A);if(H.length===2){const[se,pe]=H;return this.supported_language_codes.includes(se)||console.warn(`Unsupported language code "${se}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),(0,me.mergeArrays)([se],super._encode_text(pe))}}}class ms extends ve{}class _s extends ve{}class Ps extends ve{}class As extends ve{}class gs extends ve{}class Is extends ve{constructor(m,A){super(m,A),this.decoder=new At({})}}class ws extends ve{}class ns{static async from_pretrained(m,{progress_callback:A=null,config:H=null,cache_dir:se=null,local_files_only:pe=!1,revision:De="main",legacy:wt=null}={}){var $r;const[xt,Mt]=await te(m,{progress_callback:A,config:H,cache_dir:se,local_files_only:pe,revision:De,legacy:wt}),Ot=(($r=Mt.tokenizer_class)==null?void 0:$r.replace(/Fast$/,""))??"PreTrainedTokenizer";let Yt=this.TOKENIZER_CLASS_MAPPING[Ot];return Yt||(console.warn(`Unknown tokenizer class "${Ot}", attempting to construct from base class.`),Yt=ve),new Yt(xt,Mt)}}xe(ns,"TOKENIZER_CLASS_MAPPING",{T5Tokenizer:wr,DistilBertTokenizer:be,CamembertTokenizer:tt,DebertaTokenizer:ft,DebertaV2Tokenizer:zt,BertTokenizer:Xe,HerbertTokenizer:Nt,ConvBertTokenizer:Rt,RoFormerTokenizer:Gt,XLMTokenizer:st,ElectraTokenizer:qt,MobileBertTokenizer:mt,SqueezeBertTokenizer:$t,AlbertTokenizer:gt,GPT2Tokenizer:Br,BartTokenizer:Kr,MBartTokenizer:rr,MBart50Tokenizer:Wr,RobertaTokenizer:Vr,WhisperTokenizer:ts,CodeGenTokenizer:hs,CLIPTokenizer:fs,SiglipTokenizer:rs,MarianTokenizer:Xt,BloomTokenizer:Ln,NllbTokenizer:Cn,M2M100Tokenizer:ps,LlamaTokenizer:Bn,CodeLlamaTokenizer:Cs,XLMRobertaTokenizer:Xs,MPNetTokenizer:Es,FalconTokenizer:$s,GPTNeoXTokenizer:Ss,EsmTokenizer:Gn,Wav2Vec2CTCTokenizer:ms,BlenderbotTokenizer:_s,BlenderbotSmallTokenizer:Ps,SpeechT5Tokenizer:As,NougatTokenizer:gs,VitsTokenizer:Is,Qwen2Tokenizer:ks,GemmaTokenizer:Qs,Grok1Tokenizer:qn,CohereTokenizer:ws,PreTrainedTokenizer:ve})},"./src/utils/audio.js":(Pt,Ce,N)=>{N.r(Ce),N.d(Ce,{hamming:()=>V,hanning:()=>S,mel_filter_bank:()=>K,read_audio:()=>Ee,spectrogram:()=>I,window_function:()=>L});var z=N("./src/utils/hub.js"),me=N("./src/utils/maths.js"),ye=N("./src/utils/core.js"),Te=N("./src/utils/tensor.js");async function Ee(k,de){if(typeof AudioContext>"u")throw Error("Unable to load audio from path/URL since `AudioContext` is not available in your environment. Instead, audio data should be passed directly to the pipeline/processor. For more information and some example code, see https://huggingface.co/docs/transformers.js/guides/node-audio-processing.");const Me=await(await(0,z.getFile)(k)).arrayBuffer(),ke=new AudioContext({sampleRate:de});typeof de>"u"&&console.warn(`No sampling rate provided, using default of ${ke.sampleRate}Hz.`);const ze=await ke.decodeAudioData(Me);let Ie;if(ze.numberOfChannels===2){const Ze=Math.sqrt(2),Ke=ze.getChannelData(0),ut=ze.getChannelData(1);Ie=new Float32Array(Ke.length);for(let we=0;we2595*Math.log10(1+k/700),kaldi:k=>1127*Math.log(1+k/700),slaney:(k,de=1e3,Me=15,ke=27/Math.log(6.4))=>k>=de?Me+Math.log(k/de)*ke:3*k/200};function te(k,de="htk"){const Me=P[de];if(!Me)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof k=="number"?Me(k):k.map(ke=>Me(ke))}const ne={htk:k=>700*(10**(k/2595)-1),kaldi:k=>700*(Math.exp(k/1127)-1),slaney:(k,de=1e3,Me=15,ke=Math.log(6.4)/27)=>k>=Me?de*Math.exp(ke*(k-Me)):200*k/3};function _e(k,de="htk"){const Me=ne[de];if(!Me)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof k=="number"?Me(k):k.map(ke=>Me(ke))}function ce(k,de){const Me=Float64Array.from({length:de.length-1},(Ze,Ke)=>de[Ke+1]-de[Ke]),ke=Array.from({length:k.length},()=>new Array(de.length));for(let Ze=0;Zenew Array(k.length));for(let Ze=0;Zek+ke*Ie)}function K(k,de,Me,ke,ze,Ie=null,Ze="htk",Ke=!1){if(Ie!==null&&Ie!=="slaney")throw new Error('norm must be one of null or "slaney"');const ut=te(Me,Ze),we=te(ke,Ze),W=D(ut,we,de+2);let fe=_e(W,Ze),$e;if(Ke){const He=ze/(k*2);$e=te(Float64Array.from({length:k},(dt,nt)=>nt*He),Ze),fe=W}else $e=D(0,Math.floor(ze/2),k);const Y=ce($e,fe);if(Ie!==null&&Ie==="slaney")for(let He=0;Heze)throw Error(`frame_length (${Me}) may not be larger than fft_length (${ze})`);if(qe!==Me)throw new Error(`Length of the window (${qe}) must equal frame_length (${Me})`);if(ke<=0)throw new Error("hop_length must be greater than zero");if(Ie===null&&W!==null)throw new Error("You have provided `mel_filters` but `power` is `None`. Mel spectrogram computation is not yet supported for complex-valued spectrogram. Specify `power` to fix this issue.");if(Ze){if(Ke!=="reflect")throw new Error(`pad_mode="${Ke}" not implemented yet.`);const q=Math.floor((ze-1)/2)+1;k=re(k,q,q)}let ee=Math.floor(1+Math.floor((k.length-Me)/ke));ot!==null&&eeee?ht&&(Qe=Re):Qe=Ne=Re);const Ue=new me.FFT(ze),je=new Float64Array(ze),lt=new Float64Array(Ue.outputBufferSize),yt=new Float32Array(Pe*Qe);for(let q=0;q=1;--he)je[he]-=we*je[he-1];je[0]*=1-we}for(let he=0;heMath.pow(Ke,.85));break;default:throw new Error(`Unknown window type ${de}.`)}if(Me&&(Ze=Ze.subarray(0,k)),ke===null)return Ze;if(k>ke)throw new Error(`Length of the window (${k}) may not be larger than frame_length (${ke})`);return Ze}},"./src/utils/constants.js":(Pt,Ce,N)=>{N.r(Ce),N.d(Ce,{GITHUB_ISSUE_URL:()=>z});const z="https://github.com/xenova/transformers.js/issues/new/choose"},"./src/utils/core.js":(Pt,Ce,N)=>{N.r(Ce),N.d(Ce,{calculateDimensions:()=>j,calculateReflectOffset:()=>te,dispatchCallback:()=>z,escapeRegExp:()=>ye,isIntegralNumber:()=>Ee,isTypedArray:()=>Te,len:()=>_e,mergeArrays:()=>V,pick:()=>ne,pop:()=>S,product:()=>P,reverseDictionary:()=>me});function z(ce,D){ce&&ce(D)}function me(ce){return Object.fromEntries(Object.entries(ce).map(([D,K])=>[K,D]))}function ye(ce){return ce.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Te(ce){var D,K,re;return((re=(K=(D=ce==null?void 0:ce.prototype)==null?void 0:D.__proto__)==null?void 0:K.constructor)==null?void 0:re.name)==="TypedArray"}function Ee(ce){return Number.isInteger(ce)||typeof ce=="bigint"}function j(ce){const D=[];let K=ce;for(;Array.isArray(K);)D.push(K.length),K=K[0];return D}function S(ce,D,K=void 0){const re=ce[D];if(re!==void 0)return delete ce[D],re;if(K===void 0)throw Error(`Key ${D} does not exist in object.`);return K}function V(...ce){return Array.prototype.concat.apply([],ce)}function P(...ce){return ce.reduce((D,K)=>D.flatMap(re=>K.map(ie=>[re,ie])))}function te(ce,D){return Math.abs((ce+D)%(2*D)-D)}function ne(ce,D){return Object.assign({},...D.map(K=>{if(ce[K]!==void 0)return{[K]:ce[K]}}))}function _e(ce){let D=0;for(const K of ce)++D;return D}},"./src/utils/data-structures.js":(Pt,Ce,N)=>{N.r(Ce),N.d(Ce,{CharTrie:()=>me,PriorityQueue:()=>z,TokenLattice:()=>Te});class z{constructor(S=(P,te)=>P>te,V=1/0){this._heap=[],this._comparator=S,this._maxSize=V}get size(){return this._heap.length}isEmpty(){return this.size===0}peek(){return this._heap[0]}push(...S){return this.extend(S)}extend(S){for(const V of S)if(this.size0&&this._swap(0,V),this._heap.pop(),this._siftDown(),S}replace(S){const V=this.peek();return this._heap[0]=S,this._siftDown(),V}_parent(S){return(S+1>>>1)-1}_left(S){return(S<<1)+1}_right(S){return S+1<<1}_greater(S,V){return this._comparator(this._heap[S],this._heap[V])}_swap(S,V){const P=this._heap[S];this._heap[S]=this._heap[V],this._heap[V]=P}_siftUp(){this._siftUpFrom(this.size-1)}_siftUpFrom(S){for(;S>0&&this._greater(S,this._parent(S));)this._swap(S,this._parent(S)),S=this._parent(S)}_siftDown(){let S=0;for(;this._left(S)[]),this.endNodes=Array.from({length:this.len+1},()=>[]);const te=new Ee(this.bosTokenId,0,0,0,0),ne=new Ee(this.eosTokenId,1,this.len,0,0);this.nodes.push(te.clone()),this.nodes.push(ne.clone()),this.beginNodes[this.len].push(ne),this.endNodes[0].push(te)}insert(S,V,P,te){const ne=this.nodes.length,_e=new Ee(te,ne,S,V,P);this.beginNodes[S].push(_e),this.endNodes[S+V].push(_e),this.nodes.push(_e)}viterbi(){const S=this.len;let V=0;for(;V<=S;){if(this.beginNodes[V].length==0)return[];for(let ce of this.beginNodes[V]){ce.prev=null;let D=0,K=null;for(let re of this.endNodes[V]){const ie=re.backtraceScore+ce.score;(K===null||ie>D)&&(K=re.clone(),D=ie)}if(K!==null)ce.prev=K,ce.backtraceScore=D;else return[]}++V}const P=[],ne=this.beginNodes[S][0].prev;if(ne===null)return[];let _e=ne.clone();for(;_e.prev!==null;)P.push(_e.clone()),_e=_e.clone().prev.clone();return P.reverse(),P}piece(S){return this.chars.slice(S.pos,S.pos+S.length).join("")}tokens(){return this.viterbi().map(V=>this.piece(V))}tokenIds(){return this.viterbi().map(V=>V.tokenId)}}class Ee{constructor(S,V,P,te,ne){this.tokenId=S,this.nodeId=V,this.pos=P,this.length=te,this.score=ne,this.prev=null,this.backtraceScore=0}clone(){const S=new Ee(this.tokenId,this.nodeId,this.pos,this.length,this.score);return S.prev=this.prev,S.backtraceScore=this.backtraceScore,S}}},"./src/utils/devices.js":(Pt,Ce,N)=>{N.r(Ce),N.d(Ce,{DEVICE_TYPES:()=>z});const z=Object.freeze({auto:"auto",gpu:"gpu",cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",webnn:"webnn","webnn-npu":"webnn-npu","webnn-gpu":"webnn-gpu","webnn-cpu":"webnn-cpu"})},"./src/utils/dtypes.js":(Pt,Ce,N)=>{N.r(Ce),N.d(Ce,{DATA_TYPES:()=>Te,DEFAULT_DEVICE_DTYPE_MAPPING:()=>Ee,DEFAULT_DTYPE_SUFFIX_MAPPING:()=>j,isWebGpuFp16Supported:()=>ye});var z=N("./src/env.js"),me=N("./src/utils/devices.js");const ye=function(){let S;return async function(){if(S===void 0)if(!z.apis.IS_WEBGPU_AVAILABLE)S=!1;else try{S=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{S=!1}return S}}(),Te=Object.freeze({fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16"}),Ee=Object.freeze({[me.DEVICE_TYPES.wasm]:Te.q8}),j=Object.freeze({[Te.fp32]:"",[Te.fp16]:"_fp16",[Te.int8]:"_int8",[Te.uint8]:"_uint8",[Te.q8]:"_quantized",[Te.q4]:"_q4",[Te.q4f16]:"_q4f16",[Te.bnb4]:"_bnb4"})},"./src/utils/generic.js":(Pt,Ce,N)=>{N.r(Ce),N.d(Ce,{Callable:()=>z});const z=class{constructor(){let me=function(...ye){return me._call(...ye)};return Object.setPrototypeOf(me,new.target.prototype)}_call(...me){throw Error("Must implement _call method in subclass")}}},"./src/utils/hub.js":(Pt,Ce,N)=>{N.r(Ce),N.d(Ce,{getFile:()=>V,getModelFile:()=>ce,getModelJSON:()=>D});var z=N("?7a2c"),me=N("?a42a"),ye=N("./src/env.js"),Te=N("./src/utils/core.js");const Ee={txt:"text/plain",html:"text/html",css:"text/css",js:"text/javascript",json:"application/json",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif"};class j{constructor(X){if(this.filePath=X,this.headers=new Headers,this.exists=z.existsSync(X),this.exists){this.status=200,this.statusText="OK";let R=z.statSync(X);this.headers.set("content-length",R.size.toString()),this.updateContentType();let I=this;this.body=new ReadableStream({start(L){I.arrayBuffer().then(k=>{L.enqueue(new Uint8Array(k)),L.close()})}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){const X=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",Ee[X]??"application/octet-stream")}clone(){let X=new j(this.filePath);return X.exists=this.exists,X.status=this.status,X.statusText=this.statusText,X.headers=new Headers(this.headers),X}async arrayBuffer(){return(await z.promises.readFile(this.filePath)).buffer}async blob(){const X=await z.promises.readFile(this.filePath);return new Blob([X],{type:this.headers.get("content-type")})}async text(){return await z.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}}function S(ie,X=null,R=null){let I;try{I=new URL(ie)}catch{return!1}return!(X&&!X.includes(I.protocol)||R&&!R.includes(I.hostname))}async function V(ie){var X;if(ye.env.useFS&&!S(ie,["http:","https:","blob:"]))return new j(ie);if(typeof process<"u"&&((X=process==null?void 0:process.release)==null?void 0:X.name)==="node"){const R=!!(Tn!=null&&Tn.TESTING_REMOTELY),I=ye.env.version,L=new Headers;if(L.set("User-Agent",`transformers.js/${I}; is_ci/${R};`),S(ie,["http:","https:"],["huggingface.co","hf.co"])){const de=(Tn==null?void 0:Tn.HF_TOKEN)??(Tn==null?void 0:Tn.HF_ACCESS_TOKEN);de&&L.set("Authorization",`Bearer ${de}`)}return fetch(ie,{headers:L})}else return fetch(ie)}const P={400:"Bad request error occurred while trying to load file",401:"Unauthorized access to file",403:"Forbidden access to file",404:"Could not locate file",408:"Request timeout error occurred while trying to load file",500:"Internal server error error occurred while trying to load file",502:"Bad gateway error occurred while trying to load file",503:"Service unavailable error occurred while trying to load file",504:"Gateway timeout error occurred while trying to load file"};function te(ie,X,R){if(!R)return null;const I=P[ie]??`Error (${ie}) occurred while trying to load file`;throw Error(`${I}: "${X}".`)}class ne{constructor(X){this.path=X}async match(X){let R=me.join(this.path,X),I=new j(R);if(I.exists)return I}async put(X,R){const I=Buffer.from(await R.arrayBuffer());let L=me.join(this.path,X);try{await z.promises.mkdir(me.dirname(L),{recursive:!0}),await z.promises.writeFile(L,I)}catch(k){console.warn("An error occurred while writing the file to cache:",k)}}}async function _e(ie,...X){for(let R of X)try{let I=await ie.match(R);if(I)return I}catch{continue}}async function ce(ie,X,R=!0,I={}){if(!ye.env.allowLocalModels){if(I.local_files_only)throw Error("Invalid configuration detected: local models are disabled (`env.allowLocalModels=false`) but you have requested to only use local models (`local_files_only=true`).");if(!ye.env.allowRemoteModels)throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.")}(0,Te.dispatchCallback)(I.progress_callback,{status:"initiate",name:ie,file:X});let L;if(!L&&ye.env.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{L=await caches.open("transformers-cache")}catch($e){console.warn("An error occurred while opening the browser cache:",$e)}}if(!L&&ye.env.useFSCache&&(L=new ne(I.cache_dir??ye.env.cacheDir)),!L&&ye.env.useCustomCache){if(!ye.env.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!ye.env.customCache.match||!ye.env.customCache.put)throw new Error("`env.customCache` must be an object which implements the `match` and `put` functions of the Web Cache API. For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache");L=ye.env.customCache}const k=I.revision??"main";let de=re(ie,X),Me=re(ye.env.localModelPath,de),ke=re(ye.env.remoteHost,ye.env.remotePathTemplate.replaceAll("{model}",ie).replaceAll("{revision}",encodeURIComponent(k)),X),ze=k==="main"?de:re(ie,k,X),Ie,Ze=L instanceof ne?ze:ke,Ke=!1,ut;L&&(ut=await _e(L,Me,Ze));const we=ut!==void 0;if(ut===void 0){if(ye.env.allowLocalModels)if(S(de,["http:","https:"])){if(I.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${de}.`);if(!ye.env.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${de}.`)}else try{ut=await V(Me),Ie=Me}catch(Y){console.warn(`Unable to load from local path "${Me}": "${Y}"`)}if(ut===void 0||ut.status===404){if(I.local_files_only||!ye.env.allowRemoteModels){if(R)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${Me}".`);return null}if(ut=await V(ke),ut.status!==200)return te(ut.status,ke,R);Ie=Ze}Ke=L&&typeof Response<"u"&&ut instanceof Response&&ut.status===200}(0,Te.dispatchCallback)(I.progress_callback,{status:"download",name:ie,file:X});const W={status:"progress",name:ie,file:X};let fe;return I.progress_callback?we&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent)?(fe=new Uint8Array(await ut.arrayBuffer()),(0,Te.dispatchCallback)(I.progress_callback,{...W,progress:100,loaded:fe.length,total:fe.length})):fe=await K(ut,$e=>{(0,Te.dispatchCallback)(I.progress_callback,{...W,...$e})}):fe=new Uint8Array(await ut.arrayBuffer()),Ke&&Ie&&await L.match(Ie)===void 0&&await L.put(Ie,new Response(fe,{headers:ut.headers})).catch($e=>{console.warn(`Unable to add response to browser cache: ${$e}.`)}),(0,Te.dispatchCallback)(I.progress_callback,{status:"done",name:ie,file:X}),fe}async function D(ie,X,R=!0,I={}){let L=await ce(ie,X,R,I);if(L===null)return{};let de=new TextDecoder("utf-8").decode(L);return JSON.parse(de)}async function K(ie,X){const R=ie.headers.get("Content-Length");R===null&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let I=parseInt(R??"0"),L=new Uint8Array(I),k=0;const de=ie.body.getReader();async function Me(){const{done:ke,value:ze}=await de.read();if(ke)return;let Ie=k+ze.length;if(Ie>I){I=Ie;let Ke=new Uint8Array(I);Ke.set(L),L=Ke}L.set(ze,k),k=Ie;const Ze=k/I*100;return X({progress:Ze,loaded:k,total:I}),Me()}return await Me(),L}function re(...ie){return ie=ie.map((X,R)=>(R&&(X=X.replace(new RegExp("^/"),"")),R!==ie.length-1&&(X=X.replace(new RegExp("/$"),"")),X)),ie.join("/")}},"./src/utils/image.js":(Pt,Ce,N)=>{N.r(Ce),N.d(Ce,{RawImage:()=>_e});var z=N("./src/utils/hub.js"),me=N("./src/env.js"),ye=N("./src/utils/tensor.js"),Te=N("?2b25");const Ee=typeof self<"u",j=Ee&&self.constructor.name==="DedicatedWorkerGlobalScope";let S,V,P;if(Ee)S=(ce,D)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(ce,D)},P=self.createImageBitmap,V=self.ImageData;else if(Te)P=async ce=>{const K=(await ce.metadata()).channels,{data:re,info:ie}=await ce.rotate().raw().toBuffer({resolveWithObject:!0}),X=new _e(new Uint8ClampedArray(re),ie.width,ie.height,ie.channels);return K!==void 0&&K!==ie.channels&&X.convert(K),X};else throw new Error("Unable to load image processing library.");const te={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},ne=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]);class _e{constructor(D,K,re,ie){this.data=D,this.width=K,this.height=re,this.channels=ie}get size(){return[this.width,this.height]}static async read(D){if(D instanceof _e)return D;if(typeof D=="string"||D instanceof URL)return await this.fromURL(D);throw new Error(`Unsupported input type: ${typeof D}`)}static fromCanvas(D){if(!Ee)throw new Error("fromCanvas() is only supported in browser environments.");const re=D.getContext("2d").getImageData(0,0,D.width,D.height).data;return new _e(re,D.width,D.height,4)}static async fromURL(D){const K=await(0,z.getFile)(D);if(K.status!==200)throw new Error(`Unable to read image from "${D}" (${K.status} ${K.statusText})`);const re=await K.blob();return this.fromBlob(re)}static async fromBlob(D){if(Ee){const K=await P(D),re=S(K.width,K.height).getContext("2d");return re.drawImage(K,0,0),new this(re.getImageData(0,0,K.width,K.height).data,K.width,K.height,4)}else{const K=Te(await D.arrayBuffer());return await P(K)}}static fromTensor(D,K="CHW"){if(D.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${D.dims.length} dimensions.`);if(K==="CHW")D=D.transpose(1,2,0);else if(K!=="HWC")throw new Error(`Unsupported channel format: ${K}`);if(!(D.data instanceof Uint8ClampedArray||D.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${D.type}`);switch(D.dims[2]){case 1:case 2:case 3:case 4:return new _e(D.data,D.dims[1],D.dims[0],D.dims[2]);default:throw new Error(`Unsupported number of channels: ${D.dims[2]}`)}}grayscale(){if(this.channels===1)return this;const D=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let K=0,re=0;K=0?L=re:de=-re,ie>=0?k=ie:Me=-ie,I.drawImage(R,L,k,D,K,de,Me,D,K),new _e(I.getImageData(0,0,D,K).data,D,K,4).convert(X)}else{let X=this.toSharp();if(re>=0&&ie>=0)X=X.extract({left:Math.floor(re),top:Math.floor(ie),width:D,height:K});else if(re<=0&&ie<=0){const R=Math.floor(-ie),I=Math.floor(-re);X=X.extend({top:R,left:I,right:D-this.width-I,bottom:K-this.height-R})}else{let R=[0,0],I=0;ie<0?(R[0]=Math.floor(-ie),R[1]=K-this.height-R[0]):I=Math.floor(ie);let L=[0,0],k=0;re<0?(L[0]=Math.floor(-re),L[1]=D-this.width-L[0]):k=Math.floor(re),X=X.extend({top:R[0],bottom:R[1],left:L[0],right:L[1]}).extract({left:k,top:I,width:D,height:K})}return await P(X)}}async toBlob(D="image/png",K=1){if(!Ee)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:D,quality:K})}toTensor(D="CHW"){let K=new ye.Tensor("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(D!=="HWC")if(D==="CHW")K=K.permute(2,0,1);else throw new Error(`Unsupported channel format: ${D}`);return K}toCanvas(){if(!Ee)throw new Error("toCanvas() is only supported in browser environments.");const D=this.clone().rgba(),K=S(D.width,D.height),re=new V(D.data,D.width,D.height);return K.getContext("2d").putImageData(re,0,0),K}_update(D,K,re,ie=null){return this.data=D,this.width=K,this.height=re,ie!==null&&(this.channels=ie),this}clone(){return new _e(this.data.slice(),this.width,this.height,this.channels)}convert(D){if(this.channels===D)return this;switch(D){case 1:this.grayscale();break;case 3:this.rgb();break;case 4:this.rgba();break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this}async save(D){if(Ee){if(j)throw new Error("Unable to save an image from a Web Worker.");const K=D.split(".").pop().toLowerCase(),re=ne.get(K)??"image/png",ie=await this.toBlob(re),X=URL.createObjectURL(ie),R=document.createElement("a");R.href=X,R.download=D,R.click(),R.remove()}else{if(me.env.useFS)return await this.toSharp().toFile(D);throw new Error("Unable to save the image because filesystem is disabled in this environment.")}}toSharp(){if(Ee)throw new Error("toSharp() is only supported in server-side environments.");return Te(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}}},"./src/utils/maths.js":(Pt,Ce,N)=>{N.r(Ce),N.d(Ce,{FFT:()=>ce,bankers_round:()=>re,cos_sim:()=>j,dot:()=>Ee,dynamic_time_warping:()=>ie,interpolate_data:()=>z,log_softmax:()=>Te,magnitude:()=>S,max:()=>P,medianFilter:()=>D,min:()=>V,permute_data:()=>me,round:()=>K,softmax:()=>ye});function z(X,[R,I,L],[k,de],Me="bilinear",ke=!1){const ze=de/L,Ie=k/I,Ze=new X.constructor(k*de*R),Ke=I*L,ut=k*de;for(let we=0;we=0;--ke)k[ke]=ze,L[ke]=R[I[ke]],ze*=L[ke];const de=I.map((ke,ze)=>k[I.indexOf(ze)]),Me=new X.constructor(X.length);for(let ke=0;ke=0;--Ie)ze+=Ze%R[Ie]*de[Ie],Ze=Math.floor(Ze/R[Ie]);Me[ze]=X[ke]}return[Me,L]}function ye(X){const R=P(X)[0],I=X.map(de=>Math.exp(de-R)),L=I.reduce((de,Me)=>de+Me,0);return I.map(de=>de/L)}function Te(X){const R=P(X)[0];let I=0;for(let de=0;dede-R-L)}function Ee(X,R){let I=0;for(let L=0;LR+I*I,0))}function V(X){if(X.length===0)throw Error("Array must not be empty");let R=X[0],I=0;for(let L=1;LR&&(R=X[L],I=L);return[Number(R),I]}function te(X){return X>0&&(X&X-1)===0}class ne{constructor(R){if(this.size=R|0,this.size<=1||!te(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=R<<1,this.table=new Float64Array(this.size*2);for(let L=0;LL;L<<=1)++I;this._width=I%2===0?I-1:I,this._bitrev=new Int32Array(1<>>k&3)<>>1);for(let k=0;k>>1]=R[k];return L}toComplexArray(R,I){const L=I||this.createComplexArray();for(let k=0;k>>1],L[k+1]=0;return L}transform(R,I){if(R===I)throw new Error("Input and output buffers must be different");this._transform4(R,I,1)}realTransform(R,I){if(R===I)throw new Error("Input and output buffers must be different");this._realTransform4(R,I,1)}inverseTransform(R,I){if(R===I)throw new Error("Input and output buffers must be different");this._transform4(R,I,-1);for(let L=0;L>=2;Me>=2;Me>>=2){ke=k/Me<<1;const ut=ke>>>2;for(ze=0;ze>>1,Me>>>1)}else for(ze=0,Ie=0;ze>>1,Me>>>1,L)}const Ke=this.table;for(Me>>=2;Me>=2;Me>>=2){ke=k/Me<<1;const we=ke>>>1,W=we>>>1,fe=W>>>1;for(ze=0;ze>>1;for(let we=2;we>1;++Ze){const Ke=(Ze+1-R)**2/2,ut=Math.sqrt(ze**2+Ie**2)**Ke,we=Ke*Math.atan2(Ie,ze),W=2*Ze;de[W]=ut*Math.cos(we),de[W+1]=ut*Math.sin(we),Me[W]=de[W],Me[W+1]=-de[W+1]}this._slicedChirpBuffer=de.subarray(I,L),this._f=new ne(k>>1),this._f.transform(this._chirpBuffer,Me)}_transform(R,I,L){const k=this._buffer1,de=this._buffer2,Me=this._outBuffer1,ke=this._outBuffer2,ze=this._chirpBuffer,Ie=this._slicedChirpBuffer,Ze=this._a;if(L)for(let Ke=0;Ke>1,W=I[we];k[Ke]=W*Ie[Ke],k[ut]=W*Ie[ut]}else for(let Ke=0;Ke=X.length&&(ze=2*(X.length-1)-ze),L[Me++]=X[ze]}L.sort(),I[de]=L[k]}return I}function K(X,R){const I=Math.pow(10,R);return Math.round(X*I)/I}function re(X){const R=Math.round(X);return Math.abs(X)%1===.5?R%2===0?R:R-1:R}function ie(X){const R=X.length,I=X[0].length,L=[R+1,I+1],k=Array.from({length:L[0]},()=>Array(L[1]).fill(1/0));k[0][0]=0;const de=Array.from({length:L[0]},()=>Array(L[1]).fill(-1));for(let Ze=1;Ze0||ke>0;)switch(ze.push(Me-1),Ie.push(ke-1),de[Me][ke]){case 0:--Me,--ke;break;case 1:--Me;break;case 2:--ke;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${Me}, ${ke}]. Please file a bug report.`)}return ze.reverse(),Ie.reverse(),[ze,Ie]}},"./src/utils/tensor.js":(Pt,Ce,N)=>{N.r(Ce),N.d(Ce,{Tensor:()=>Ee,cat:()=>X,full:()=>Me,full_like:()=>ke,interpolate:()=>V,interpolate_4d:()=>P,layer_norm:()=>D,matmul:()=>te,mean:()=>L,mean_pooling:()=>ce,ones:()=>ze,ones_like:()=>Ie,permute:()=>S,quantize_embeddings:()=>ut,rfft:()=>ne,stack:()=>R,std_mean:()=>I,topk:()=>_e,zeros:()=>Ze,zeros_like:()=>Ke});var z=N("./src/utils/maths.js"),me=N("./src/backends/onnx.js"),ye=N("./src/ops/registry.js");const Te=Object.freeze({float32:Float32Array,float16:Uint16Array,float64:Float64Array,string:Array,int8:Int8Array,uint8:Uint8Array,int16:Int16Array,uint16:Uint16Array,int32:Int32Array,uint32:Uint32Array,int64:BigInt64Array,uint64:BigUint64Array,bool:Uint8Array});class Ee{constructor(...W){xe(this,"ort_tensor");return(0,me.isONNXTensor)(W[0])?this.ort_tensor=W[0]:this.ort_tensor=new me.Tensor(W[0],W[1],W[2]),new Proxy(this,{get:(fe,$e)=>{if(typeof $e=="string"){let Y=Number($e);if(Number.isInteger(Y))return fe._getitem(Y)}return fe[$e]},set:(fe,$e,Y)=>fe[$e]=Y})}get dims(){return this.ort_tensor.dims}set dims(W){this.ort_tensor.dims=W}get type(){return this.ort_tensor.type}get data(){return this.ort_tensor.data}get size(){return this.ort_tensor.size}get location(){return this.ort_tensor.location}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){const[W,...fe]=this.dims;if(fe.length>0){const $e=fe.reduce((Y,He)=>Y*He);for(let Y=0;Y0){const Y=$e.reduce((He,dt)=>He*dt);return this._subarray(W,Y,$e)}else return new Ee(this.type,[this.data[W]],$e)}indexOf(W){const fe=this.data;for(let $e=0;$eqe)throw new Error(`Invalid slice: ${ht}`);const ee=[Math.max(bt,0),Math.min(qe,this.dims[Re])];$e.push(ee),fe.push(ee[1]-ee[0])}else throw new Error(`Invalid slice: ${ht}`)}const Y=$e.map(([Re,ht])=>ht-Re),He=Y.reduce((Re,ht)=>Re*ht),dt=this.data,nt=new dt.constructor(He),ot=this.stride();for(let Re=0;Re=0;--bt){const ee=Y[bt];ht+=(qe%ee+$e[bt][0])*ot[bt],qe=Math.floor(qe/ee)}nt[Re]=dt[ht]}return new Ee(this.type,nt,fe)}permute(...W){return S(this,W)}transpose(...W){return this.permute(...W)}sum(W=null,fe=!1){return this.norm(1,W,fe)}norm(W="fro",fe=null,$e=!1){if(W==="fro")W=2;else if(typeof W=="string")throw Error(`Unsupported norm: ${W}`);const Y=this.data;if(fe===null){let nt=Y.reduce((ot,Re)=>ot+Re**W,0)**(1/W);return new Ee(this.type,[nt],[])}fe=ie(fe,this.dims.length);const He=this.dims.slice();He[fe]=1;const dt=new Y.constructor(Y.length/this.dims[fe]);for(let nt=0;nt=0;--Re){const qe=this.dims[Re];if(Re!==fe){const ee=ht%qe;ot+=ee*bt,bt*=He[Re]}ht=Math.floor(ht/qe)}dt[ot]+=Y[nt]**W}if(W!==1)for(let nt=0;nt=0;--ot){const bt=this.dims[ot];if(ot!==fe){const qe=Re%bt;nt+=qe*ht,ht*=this.dims[ot]}Re=Math.floor(Re/bt)}Y[dt]/=He[nt]}return this}normalize(W=2,fe=1){return this.clone().normalize_(W,fe)}stride(){return k(this.dims)}squeeze(W=null){return new Ee(this.type,this.data,K(this.dims,W))}squeeze_(W=null){return this.dims=K(this.dims,W),this}unsqueeze(W=null){return new Ee(this.type,this.data,re(this.dims,W))}unsqueeze_(W=null){return this.dims=re(this.dims,W),this}flatten_(W=0,fe=-1){fe=(fe+this.dims.length)%this.dims.length;let $e=this.dims.slice(0,W),Y=this.dims.slice(W,fe+1),He=this.dims.slice(fe+1);return this.dims=[...$e,Y.reduce((dt,nt)=>dt*nt,1),...He],this}flatten(W=0,fe=-1){return this.clone().flatten_(W,fe)}view(...W){let fe=-1;for(let Y=0;Ynt!==fe?He*dt:He,1);W[fe]=$e.length/Y}return new Ee(this.type,$e,W)}neg_(){const W=this.data;for(let fe=0;feHe*dt);if(fe!==$e)throw Error(`cannot reshape array of size ${fe} into shape (${W})`);let Y=we;for(let He=W.length-1;He>=0;He--)Y=Y.reduce((dt,nt)=>{let ot=dt[dt.length-1];return ot.lengthfe!==1):typeof W=="number"?we[W]===1&&we.splice(W,1):Array.isArray(W)&&(we=we.filter((fe,$e)=>fe!==1||!W.includes($e))),we}function re(we,W){return W=ie(W,we.length+1),we=we.slice(),we.splice(W,0,1),we}function ie(we,W,fe=null,$e=!0){if($e&&(we<-W||we>=W))throw new Error(`IndexError: index ${we} is out of bounds for dimension${fe===null?"":" "+fe} with size ${W}`);return we<0&&(we=(we%W+W)%W),we}function X(we,W=0){W=ie(W,we[0].dims.length);const fe=we[0].dims.slice();fe[W]=we.reduce((dt,nt)=>dt+nt.dims[W],0);const $e=fe.reduce((dt,nt)=>dt*nt,1),Y=new we[0].data.constructor($e),He=we[0].type;if(W===0){let dt=0;for(const nt of we){const ot=nt.data;Y.set(ot,dt),dt+=ot.length}}else{let dt=0;for(let nt=0;nt=0;--qe){const Ne=Re[qe];let Qe=ee%Ne;qe===W&&(Qe+=dt),bt+=Qe*Pe,Pe*=fe[qe],ee=Math.floor(ee/Ne)}Y[bt]=ot[ht]}dt+=Re[W]}}return new Ee(He,Y,fe)}function R(we,W=0){return X(we.map(fe=>fe.unsqueeze(W)),W)}function I(we,W=null,fe=1,$e=!1){const Y=we.data,He=we.dims;if(W===null){const qe=Y.reduce((Qe,Ue)=>Qe+Ue,0)/Y.length,ee=Math.sqrt(Y.reduce((Qe,Ue)=>Qe+(Ue-qe)**2,0)/(Y.length-fe)),Pe=new Ee(we.type,[qe],[]);return[new Ee(we.type,[ee],[]),Pe]}W=ie(W,He.length);const dt=L(we,W,$e),nt=dt.data,ot=He.slice();ot[W]=1;const Re=new Y.constructor(Y.length/He[W]);for(let bt=0;bt=0;--ee){const Qe=He[ee];if(ee!==W){const Ue=Pe%Qe;qe+=Ue*Ne,Ne*=ot[ee]}Pe=Math.floor(Pe/Qe)}Re[qe]+=(Y[bt]-nt[qe])**2}for(let bt=0;btot+Re,0);return new Ee(we.type,[nt/$e.length],[])}const Y=we.dims;W=ie(W,Y.length);const He=Y.slice();He[W]=1;const dt=new $e.constructor($e.length/Y[W]);for(let nt=0;nt<$e.length;++nt){let ot=0;for(let Re=Y.length-1,ht=nt,bt=1;Re>=0;--Re){const qe=Y[Re];if(Re!==W){const ee=ht%qe;ot+=ee*bt,bt*=He[Re]}ht=Math.floor(ht/qe)}dt[ot]+=$e[nt]}if(Y[W]!==1)for(let nt=0;nt=0;--fe)W[fe]=$e,$e*=we[fe];return W}function de(we,W,fe,$e){const Y=we.reduce((He,dt)=>He*dt,1);return new Ee(fe,new $e(Y).fill(W),we)}function Me(we,W){let fe,$e;if(typeof W=="number")fe="float32",$e=Float32Array;else if(typeof W=="bigint")fe="int64",$e=BigInt64Array;else throw new Error(`Unsupported data type: ${typeof W}`);return de(we,W,fe,$e)}function ke(we,W){return Me(we.dims,W)}function ze(we){return de(we,1n,"int64",BigInt64Array)}function Ie(we){return ze(we.dims)}function Ze(we){return de(we,0n,"int64",BigInt64Array)}function Ke(we){return Ze(we.dims)}function ut(we,W){if(we.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(we.dims.at(-1)%8!==0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(W))throw new Error("The precision must be either 'binary' or 'ubinary'");const fe=W==="binary",$e=fe?"int8":"uint8",Y=fe?Int8Array:Uint8Array,He=we.data,dt=new Y(He.length/8);for(let nt=0;nt0?1:0,Re=Math.floor(nt/8),ht=nt%8;dt[Re]|=ot<<7-ht,fe&&ht===0&&(dt[Re]-=128)}return new Ee($e,dt,[we.dims[0],we.dims[1]/8])}}},Ks={};function Gr(Pt){var Ce=Ks[Pt];if(Ce!==void 0)return Ce.exports;var N=Ks[Pt]={exports:{}};return es[Pt](N,N.exports,Gr),N.exports}Gr.m=es,(()=>{var Pt=Object.getPrototypeOf?N=>Object.getPrototypeOf(N):N=>N.__proto__,Ce;Gr.t=function(N,z){if(z&1&&(N=this(N)),z&8||typeof N=="object"&&N&&(z&4&&N.__esModule||z&16&&typeof N.then=="function"))return N;var me=Object.create(null);Gr.r(me);var ye={};Ce=Ce||[null,Pt({}),Pt([]),Pt(Pt)];for(var Te=z&2&&N;typeof Te=="object"&&!~Ce.indexOf(Te);Te=Pt(Te))Object.getOwnPropertyNames(Te).forEach(Ee=>ye[Ee]=()=>N[Ee]);return ye.default=()=>N,Gr.d(me,ye),me}})(),Gr.d=(Pt,Ce)=>{for(var N in Ce)Gr.o(Ce,N)&&!Gr.o(Pt,N)&&Object.defineProperty(Pt,N,{enumerable:!0,get:Ce[N]})},Gr.o=(Pt,Ce)=>Object.prototype.hasOwnProperty.call(Pt,Ce),Gr.r=Pt=>{typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(Pt,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(Pt,"__esModule",{value:!0})},(()=>{var Pt;if(typeof self.location.href=="string"&&(Pt=self.location.href),!Pt)throw new Error("Automatic publicPath is not supported in this browser");Pt=Pt.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),Gr.p=Pt})(),Gr.b=new URL("./",self.location.href);var c={};/*!*****************************!*\ - !*** ./src/transformers.js ***! - \*****************************/Gr.r(c),Gr.d(c,{ASTFeatureExtractor:()=>Zt.ASTFeatureExtractor,ASTForAudioClassification:()=>b.ASTForAudioClassification,ASTModel:()=>b.ASTModel,ASTPreTrainedModel:()=>b.ASTPreTrainedModel,AlbertForMaskedLM:()=>b.AlbertForMaskedLM,AlbertForQuestionAnswering:()=>b.AlbertForQuestionAnswering,AlbertForSequenceClassification:()=>b.AlbertForSequenceClassification,AlbertModel:()=>b.AlbertModel,AlbertPreTrainedModel:()=>b.AlbertPreTrainedModel,AlbertTokenizer:()=>sr.AlbertTokenizer,AudioClassificationPipeline:()=>qr.AudioClassificationPipeline,AutoConfig:()=>fc.AutoConfig,AutoModel:()=>b.AutoModel,AutoModelForAudioClassification:()=>b.AutoModelForAudioClassification,AutoModelForAudioFrameClassification:()=>b.AutoModelForAudioFrameClassification,AutoModelForCTC:()=>b.AutoModelForCTC,AutoModelForCausalLM:()=>b.AutoModelForCausalLM,AutoModelForDepthEstimation:()=>b.AutoModelForDepthEstimation,AutoModelForDocumentQuestionAnswering:()=>b.AutoModelForDocumentQuestionAnswering,AutoModelForImageClassification:()=>b.AutoModelForImageClassification,AutoModelForImageFeatureExtraction:()=>b.AutoModelForImageFeatureExtraction,AutoModelForImageMatting:()=>b.AutoModelForImageMatting,AutoModelForImageSegmentation:()=>b.AutoModelForImageSegmentation,AutoModelForImageToImage:()=>b.AutoModelForImageToImage,AutoModelForMaskGeneration:()=>b.AutoModelForMaskGeneration,AutoModelForMaskedLM:()=>b.AutoModelForMaskedLM,AutoModelForNormalEstimation:()=>b.AutoModelForNormalEstimation,AutoModelForObjectDetection:()=>b.AutoModelForObjectDetection,AutoModelForQuestionAnswering:()=>b.AutoModelForQuestionAnswering,AutoModelForSemanticSegmentation:()=>b.AutoModelForSemanticSegmentation,AutoModelForSeq2SeqLM:()=>b.AutoModelForSeq2SeqLM,AutoModelForSequenceClassification:()=>b.AutoModelForSequenceClassification,AutoModelForSpeechSeq2Seq:()=>b.AutoModelForSpeechSeq2Seq,AutoModelForTextToSpectrogram:()=>b.AutoModelForTextToSpectrogram,AutoModelForTextToWaveform:()=>b.AutoModelForTextToWaveform,AutoModelForTokenClassification:()=>b.AutoModelForTokenClassification,AutoModelForUniversalSegmentation:()=>b.AutoModelForUniversalSegmentation,AutoModelForVision2Seq:()=>b.AutoModelForVision2Seq,AutoModelForXVector:()=>b.AutoModelForXVector,AutoModelForZeroShotObjectDetection:()=>b.AutoModelForZeroShotObjectDetection,AutoProcessor:()=>Zt.AutoProcessor,AutoTokenizer:()=>sr.AutoTokenizer,AutomaticSpeechRecognitionPipeline:()=>qr.AutomaticSpeechRecognitionPipeline,BartForConditionalGeneration:()=>b.BartForConditionalGeneration,BartForSequenceClassification:()=>b.BartForSequenceClassification,BartModel:()=>b.BartModel,BartPretrainedModel:()=>b.BartPretrainedModel,BartTokenizer:()=>sr.BartTokenizer,BaseModelOutput:()=>b.BaseModelOutput,BaseStreamer:()=>mc.BaseStreamer,BeitFeatureExtractor:()=>Zt.BeitFeatureExtractor,BeitForImageClassification:()=>b.BeitForImageClassification,BeitModel:()=>b.BeitModel,BeitPreTrainedModel:()=>b.BeitPreTrainedModel,BertForMaskedLM:()=>b.BertForMaskedLM,BertForQuestionAnswering:()=>b.BertForQuestionAnswering,BertForSequenceClassification:()=>b.BertForSequenceClassification,BertForTokenClassification:()=>b.BertForTokenClassification,BertModel:()=>b.BertModel,BertPreTrainedModel:()=>b.BertPreTrainedModel,BertTokenizer:()=>sr.BertTokenizer,BitImageProcessor:()=>Zt.BitImageProcessor,BlenderbotForConditionalGeneration:()=>b.BlenderbotForConditionalGeneration,BlenderbotModel:()=>b.BlenderbotModel,BlenderbotPreTrainedModel:()=>b.BlenderbotPreTrainedModel,BlenderbotSmallForConditionalGeneration:()=>b.BlenderbotSmallForConditionalGeneration,BlenderbotSmallModel:()=>b.BlenderbotSmallModel,BlenderbotSmallPreTrainedModel:()=>b.BlenderbotSmallPreTrainedModel,BlenderbotSmallTokenizer:()=>sr.BlenderbotSmallTokenizer,BlenderbotTokenizer:()=>sr.BlenderbotTokenizer,BloomForCausalLM:()=>b.BloomForCausalLM,BloomModel:()=>b.BloomModel,BloomPreTrainedModel:()=>b.BloomPreTrainedModel,BloomTokenizer:()=>sr.BloomTokenizer,CLIPFeatureExtractor:()=>Zt.CLIPFeatureExtractor,CLIPImageProcessor:()=>Zt.CLIPImageProcessor,CLIPModel:()=>b.CLIPModel,CLIPPreTrainedModel:()=>b.CLIPPreTrainedModel,CLIPSegForImageSegmentation:()=>b.CLIPSegForImageSegmentation,CLIPSegModel:()=>b.CLIPSegModel,CLIPSegPreTrainedModel:()=>b.CLIPSegPreTrainedModel,CLIPTextModel:()=>b.CLIPTextModel,CLIPTextModelWithProjection:()=>b.CLIPTextModelWithProjection,CLIPTokenizer:()=>sr.CLIPTokenizer,CLIPVisionModel:()=>b.CLIPVisionModel,CLIPVisionModelWithProjection:()=>b.CLIPVisionModelWithProjection,CamembertForMaskedLM:()=>b.CamembertForMaskedLM,CamembertForQuestionAnswering:()=>b.CamembertForQuestionAnswering,CamembertForSequenceClassification:()=>b.CamembertForSequenceClassification,CamembertForTokenClassification:()=>b.CamembertForTokenClassification,CamembertModel:()=>b.CamembertModel,CamembertPreTrainedModel:()=>b.CamembertPreTrainedModel,CamembertTokenizer:()=>sr.CamembertTokenizer,CausalLMOutput:()=>b.CausalLMOutput,CausalLMOutputWithPast:()=>b.CausalLMOutputWithPast,ChineseCLIPFeatureExtractor:()=>Zt.ChineseCLIPFeatureExtractor,ChineseCLIPModel:()=>b.ChineseCLIPModel,ChineseCLIPPreTrainedModel:()=>b.ChineseCLIPPreTrainedModel,ClapAudioModelWithProjection:()=>b.ClapAudioModelWithProjection,ClapFeatureExtractor:()=>Zt.ClapFeatureExtractor,ClapModel:()=>b.ClapModel,ClapPreTrainedModel:()=>b.ClapPreTrainedModel,ClapTextModelWithProjection:()=>b.ClapTextModelWithProjection,CodeGenForCausalLM:()=>b.CodeGenForCausalLM,CodeGenModel:()=>b.CodeGenModel,CodeGenPreTrainedModel:()=>b.CodeGenPreTrainedModel,CodeGenTokenizer:()=>sr.CodeGenTokenizer,CodeLlamaTokenizer:()=>sr.CodeLlamaTokenizer,CohereForCausalLM:()=>b.CohereForCausalLM,CohereModel:()=>b.CohereModel,CoherePreTrainedModel:()=>b.CoherePreTrainedModel,CohereTokenizer:()=>sr.CohereTokenizer,ConvBertForMaskedLM:()=>b.ConvBertForMaskedLM,ConvBertForQuestionAnswering:()=>b.ConvBertForQuestionAnswering,ConvBertForSequenceClassification:()=>b.ConvBertForSequenceClassification,ConvBertForTokenClassification:()=>b.ConvBertForTokenClassification,ConvBertModel:()=>b.ConvBertModel,ConvBertPreTrainedModel:()=>b.ConvBertPreTrainedModel,ConvBertTokenizer:()=>sr.ConvBertTokenizer,ConvNextFeatureExtractor:()=>Zt.ConvNextFeatureExtractor,ConvNextForImageClassification:()=>b.ConvNextForImageClassification,ConvNextImageProcessor:()=>Zt.ConvNextImageProcessor,ConvNextModel:()=>b.ConvNextModel,ConvNextPreTrainedModel:()=>b.ConvNextPreTrainedModel,ConvNextV2ForImageClassification:()=>b.ConvNextV2ForImageClassification,ConvNextV2Model:()=>b.ConvNextV2Model,ConvNextV2PreTrainedModel:()=>b.ConvNextV2PreTrainedModel,DPTFeatureExtractor:()=>Zt.DPTFeatureExtractor,DPTForDepthEstimation:()=>b.DPTForDepthEstimation,DPTImageProcessor:()=>Zt.DPTImageProcessor,DPTModel:()=>b.DPTModel,DPTPreTrainedModel:()=>b.DPTPreTrainedModel,DebertaForMaskedLM:()=>b.DebertaForMaskedLM,DebertaForQuestionAnswering:()=>b.DebertaForQuestionAnswering,DebertaForSequenceClassification:()=>b.DebertaForSequenceClassification,DebertaForTokenClassification:()=>b.DebertaForTokenClassification,DebertaModel:()=>b.DebertaModel,DebertaPreTrainedModel:()=>b.DebertaPreTrainedModel,DebertaTokenizer:()=>sr.DebertaTokenizer,DebertaV2ForMaskedLM:()=>b.DebertaV2ForMaskedLM,DebertaV2ForQuestionAnswering:()=>b.DebertaV2ForQuestionAnswering,DebertaV2ForSequenceClassification:()=>b.DebertaV2ForSequenceClassification,DebertaV2ForTokenClassification:()=>b.DebertaV2ForTokenClassification,DebertaV2Model:()=>b.DebertaV2Model,DebertaV2PreTrainedModel:()=>b.DebertaV2PreTrainedModel,DebertaV2Tokenizer:()=>sr.DebertaV2Tokenizer,DecisionTransformerModel:()=>b.DecisionTransformerModel,DecisionTransformerPreTrainedModel:()=>b.DecisionTransformerPreTrainedModel,DeiTFeatureExtractor:()=>Zt.DeiTFeatureExtractor,DeiTForImageClassification:()=>b.DeiTForImageClassification,DeiTModel:()=>b.DeiTModel,DeiTPreTrainedModel:()=>b.DeiTPreTrainedModel,DepthAnythingForDepthEstimation:()=>b.DepthAnythingForDepthEstimation,DepthAnythingPreTrainedModel:()=>b.DepthAnythingPreTrainedModel,DepthEstimationPipeline:()=>qr.DepthEstimationPipeline,DetrFeatureExtractor:()=>Zt.DetrFeatureExtractor,DetrForObjectDetection:()=>b.DetrForObjectDetection,DetrForSegmentation:()=>b.DetrForSegmentation,DetrModel:()=>b.DetrModel,DetrObjectDetectionOutput:()=>b.DetrObjectDetectionOutput,DetrPreTrainedModel:()=>b.DetrPreTrainedModel,DetrSegmentationOutput:()=>b.DetrSegmentationOutput,Dinov2ForImageClassification:()=>b.Dinov2ForImageClassification,Dinov2Model:()=>b.Dinov2Model,Dinov2PreTrainedModel:()=>b.Dinov2PreTrainedModel,DistilBertForMaskedLM:()=>b.DistilBertForMaskedLM,DistilBertForQuestionAnswering:()=>b.DistilBertForQuestionAnswering,DistilBertForSequenceClassification:()=>b.DistilBertForSequenceClassification,DistilBertForTokenClassification:()=>b.DistilBertForTokenClassification,DistilBertModel:()=>b.DistilBertModel,DistilBertPreTrainedModel:()=>b.DistilBertPreTrainedModel,DistilBertTokenizer:()=>sr.DistilBertTokenizer,DocumentQuestionAnsweringPipeline:()=>qr.DocumentQuestionAnsweringPipeline,DonutFeatureExtractor:()=>Zt.DonutFeatureExtractor,DonutSwinModel:()=>b.DonutSwinModel,DonutSwinPreTrainedModel:()=>b.DonutSwinPreTrainedModel,EfficientNetForImageClassification:()=>b.EfficientNetForImageClassification,EfficientNetImageProcessor:()=>Zt.EfficientNetImageProcessor,EfficientNetModel:()=>b.EfficientNetModel,EfficientNetPreTrainedModel:()=>b.EfficientNetPreTrainedModel,ElectraForMaskedLM:()=>b.ElectraForMaskedLM,ElectraForQuestionAnswering:()=>b.ElectraForQuestionAnswering,ElectraForSequenceClassification:()=>b.ElectraForSequenceClassification,ElectraForTokenClassification:()=>b.ElectraForTokenClassification,ElectraModel:()=>b.ElectraModel,ElectraPreTrainedModel:()=>b.ElectraPreTrainedModel,ElectraTokenizer:()=>sr.ElectraTokenizer,EosTokenCriteria:()=>so.EosTokenCriteria,EsmForMaskedLM:()=>b.EsmForMaskedLM,EsmForSequenceClassification:()=>b.EsmForSequenceClassification,EsmForTokenClassification:()=>b.EsmForTokenClassification,EsmModel:()=>b.EsmModel,EsmPreTrainedModel:()=>b.EsmPreTrainedModel,EsmTokenizer:()=>sr.EsmTokenizer,FFT:()=>$n.FFT,FalconForCausalLM:()=>b.FalconForCausalLM,FalconModel:()=>b.FalconModel,FalconPreTrainedModel:()=>b.FalconPreTrainedModel,FalconTokenizer:()=>sr.FalconTokenizer,FastViTForImageClassification:()=>b.FastViTForImageClassification,FastViTModel:()=>b.FastViTModel,FastViTPreTrainedModel:()=>b.FastViTPreTrainedModel,FeatureExtractionPipeline:()=>qr.FeatureExtractionPipeline,FeatureExtractor:()=>Zt.FeatureExtractor,FillMaskPipeline:()=>qr.FillMaskPipeline,Florence2ForConditionalGeneration:()=>b.Florence2ForConditionalGeneration,Florence2PreTrainedModel:()=>b.Florence2PreTrainedModel,Florence2Processor:()=>Zt.Florence2Processor,GLPNFeatureExtractor:()=>Zt.GLPNFeatureExtractor,GLPNForDepthEstimation:()=>b.GLPNForDepthEstimation,GLPNModel:()=>b.GLPNModel,GLPNPreTrainedModel:()=>b.GLPNPreTrainedModel,GPT2LMHeadModel:()=>b.GPT2LMHeadModel,GPT2Model:()=>b.GPT2Model,GPT2PreTrainedModel:()=>b.GPT2PreTrainedModel,GPT2Tokenizer:()=>sr.GPT2Tokenizer,GPTBigCodeForCausalLM:()=>b.GPTBigCodeForCausalLM,GPTBigCodeModel:()=>b.GPTBigCodeModel,GPTBigCodePreTrainedModel:()=>b.GPTBigCodePreTrainedModel,GPTJForCausalLM:()=>b.GPTJForCausalLM,GPTJModel:()=>b.GPTJModel,GPTJPreTrainedModel:()=>b.GPTJPreTrainedModel,GPTNeoForCausalLM:()=>b.GPTNeoForCausalLM,GPTNeoModel:()=>b.GPTNeoModel,GPTNeoPreTrainedModel:()=>b.GPTNeoPreTrainedModel,GPTNeoXForCausalLM:()=>b.GPTNeoXForCausalLM,GPTNeoXModel:()=>b.GPTNeoXModel,GPTNeoXPreTrainedModel:()=>b.GPTNeoXPreTrainedModel,GPTNeoXTokenizer:()=>sr.GPTNeoXTokenizer,Gemma2ForCausalLM:()=>b.Gemma2ForCausalLM,Gemma2Model:()=>b.Gemma2Model,Gemma2PreTrainedModel:()=>b.Gemma2PreTrainedModel,GemmaForCausalLM:()=>b.GemmaForCausalLM,GemmaModel:()=>b.GemmaModel,GemmaPreTrainedModel:()=>b.GemmaPreTrainedModel,GemmaTokenizer:()=>sr.GemmaTokenizer,Grok1Tokenizer:()=>sr.Grok1Tokenizer,GroupViTModel:()=>b.GroupViTModel,GroupViTPreTrainedModel:()=>b.GroupViTPreTrainedModel,HerbertTokenizer:()=>sr.HerbertTokenizer,HieraForImageClassification:()=>b.HieraForImageClassification,HieraModel:()=>b.HieraModel,HieraPreTrainedModel:()=>b.HieraPreTrainedModel,HubertForCTC:()=>b.HubertForCTC,HubertForSequenceClassification:()=>b.HubertForSequenceClassification,HubertModel:()=>b.HubertModel,HubertPreTrainedModel:()=>b.HubertPreTrainedModel,ImageClassificationPipeline:()=>qr.ImageClassificationPipeline,ImageFeatureExtractionPipeline:()=>qr.ImageFeatureExtractionPipeline,ImageFeatureExtractor:()=>Zt.ImageFeatureExtractor,ImageMattingOutput:()=>b.ImageMattingOutput,ImageSegmentationPipeline:()=>qr.ImageSegmentationPipeline,ImageToImagePipeline:()=>qr.ImageToImagePipeline,ImageToTextPipeline:()=>qr.ImageToTextPipeline,InterruptableStoppingCriteria:()=>so.InterruptableStoppingCriteria,JAISLMHeadModel:()=>b.JAISLMHeadModel,JAISModel:()=>b.JAISModel,JAISPreTrainedModel:()=>b.JAISPreTrainedModel,LlamaForCausalLM:()=>b.LlamaForCausalLM,LlamaModel:()=>b.LlamaModel,LlamaPreTrainedModel:()=>b.LlamaPreTrainedModel,LlamaTokenizer:()=>sr.LlamaTokenizer,LlavaForConditionalGeneration:()=>b.LlavaForConditionalGeneration,LlavaPreTrainedModel:()=>b.LlavaPreTrainedModel,LongT5ForConditionalGeneration:()=>b.LongT5ForConditionalGeneration,LongT5Model:()=>b.LongT5Model,LongT5PreTrainedModel:()=>b.LongT5PreTrainedModel,M2M100ForConditionalGeneration:()=>b.M2M100ForConditionalGeneration,M2M100Model:()=>b.M2M100Model,M2M100PreTrainedModel:()=>b.M2M100PreTrainedModel,M2M100Tokenizer:()=>sr.M2M100Tokenizer,MBart50Tokenizer:()=>sr.MBart50Tokenizer,MBartForCausalLM:()=>b.MBartForCausalLM,MBartForConditionalGeneration:()=>b.MBartForConditionalGeneration,MBartForSequenceClassification:()=>b.MBartForSequenceClassification,MBartModel:()=>b.MBartModel,MBartPreTrainedModel:()=>b.MBartPreTrainedModel,MBartTokenizer:()=>sr.MBartTokenizer,MPNetForMaskedLM:()=>b.MPNetForMaskedLM,MPNetForQuestionAnswering:()=>b.MPNetForQuestionAnswering,MPNetForSequenceClassification:()=>b.MPNetForSequenceClassification,MPNetForTokenClassification:()=>b.MPNetForTokenClassification,MPNetModel:()=>b.MPNetModel,MPNetPreTrainedModel:()=>b.MPNetPreTrainedModel,MPNetTokenizer:()=>sr.MPNetTokenizer,MT5ForConditionalGeneration:()=>b.MT5ForConditionalGeneration,MT5Model:()=>b.MT5Model,MT5PreTrainedModel:()=>b.MT5PreTrainedModel,MarianMTModel:()=>b.MarianMTModel,MarianModel:()=>b.MarianModel,MarianPreTrainedModel:()=>b.MarianPreTrainedModel,MarianTokenizer:()=>sr.MarianTokenizer,MaskFormerFeatureExtractor:()=>Zt.MaskFormerFeatureExtractor,MaskFormerForInstanceSegmentation:()=>b.MaskFormerForInstanceSegmentation,MaskFormerModel:()=>b.MaskFormerModel,MaskFormerPreTrainedModel:()=>b.MaskFormerPreTrainedModel,MaskedLMOutput:()=>b.MaskedLMOutput,MaxLengthCriteria:()=>so.MaxLengthCriteria,MistralForCausalLM:()=>b.MistralForCausalLM,MistralModel:()=>b.MistralModel,MistralPreTrainedModel:()=>b.MistralPreTrainedModel,MobileBertForMaskedLM:()=>b.MobileBertForMaskedLM,MobileBertForQuestionAnswering:()=>b.MobileBertForQuestionAnswering,MobileBertForSequenceClassification:()=>b.MobileBertForSequenceClassification,MobileBertModel:()=>b.MobileBertModel,MobileBertPreTrainedModel:()=>b.MobileBertPreTrainedModel,MobileBertTokenizer:()=>sr.MobileBertTokenizer,MobileNetV1FeatureExtractor:()=>Zt.MobileNetV1FeatureExtractor,MobileNetV1ForImageClassification:()=>b.MobileNetV1ForImageClassification,MobileNetV1Model:()=>b.MobileNetV1Model,MobileNetV1PreTrainedModel:()=>b.MobileNetV1PreTrainedModel,MobileNetV2FeatureExtractor:()=>Zt.MobileNetV2FeatureExtractor,MobileNetV2ForImageClassification:()=>b.MobileNetV2ForImageClassification,MobileNetV2Model:()=>b.MobileNetV2Model,MobileNetV2PreTrainedModel:()=>b.MobileNetV2PreTrainedModel,MobileNetV3FeatureExtractor:()=>Zt.MobileNetV3FeatureExtractor,MobileNetV3ForImageClassification:()=>b.MobileNetV3ForImageClassification,MobileNetV3Model:()=>b.MobileNetV3Model,MobileNetV3PreTrainedModel:()=>b.MobileNetV3PreTrainedModel,MobileNetV4FeatureExtractor:()=>Zt.MobileNetV4FeatureExtractor,MobileNetV4ForImageClassification:()=>b.MobileNetV4ForImageClassification,MobileNetV4Model:()=>b.MobileNetV4Model,MobileNetV4PreTrainedModel:()=>b.MobileNetV4PreTrainedModel,MobileViTFeatureExtractor:()=>Zt.MobileViTFeatureExtractor,MobileViTForImageClassification:()=>b.MobileViTForImageClassification,MobileViTImageProcessor:()=>Zt.MobileViTImageProcessor,MobileViTModel:()=>b.MobileViTModel,MobileViTPreTrainedModel:()=>b.MobileViTPreTrainedModel,MobileViTV2ForImageClassification:()=>b.MobileViTV2ForImageClassification,MobileViTV2Model:()=>b.MobileViTV2Model,MobileViTV2PreTrainedModel:()=>b.MobileViTV2PreTrainedModel,ModelOutput:()=>b.ModelOutput,Moondream1ForConditionalGeneration:()=>b.Moondream1ForConditionalGeneration,MptForCausalLM:()=>b.MptForCausalLM,MptModel:()=>b.MptModel,MptPreTrainedModel:()=>b.MptPreTrainedModel,MusicgenForCausalLM:()=>b.MusicgenForCausalLM,MusicgenForConditionalGeneration:()=>b.MusicgenForConditionalGeneration,MusicgenModel:()=>b.MusicgenModel,MusicgenPreTrainedModel:()=>b.MusicgenPreTrainedModel,NllbTokenizer:()=>sr.NllbTokenizer,NomicBertModel:()=>b.NomicBertModel,NomicBertPreTrainedModel:()=>b.NomicBertPreTrainedModel,NougatImageProcessor:()=>Zt.NougatImageProcessor,NougatTokenizer:()=>sr.NougatTokenizer,OPTForCausalLM:()=>b.OPTForCausalLM,OPTModel:()=>b.OPTModel,OPTPreTrainedModel:()=>b.OPTPreTrainedModel,ObjectDetectionPipeline:()=>qr.ObjectDetectionPipeline,OpenELMForCausalLM:()=>b.OpenELMForCausalLM,OpenELMModel:()=>b.OpenELMModel,OpenELMPreTrainedModel:()=>b.OpenELMPreTrainedModel,OwlViTFeatureExtractor:()=>Zt.OwlViTFeatureExtractor,OwlViTForObjectDetection:()=>b.OwlViTForObjectDetection,OwlViTModel:()=>b.OwlViTModel,OwlViTPreTrainedModel:()=>b.OwlViTPreTrainedModel,OwlViTProcessor:()=>Zt.OwlViTProcessor,Owlv2ForObjectDetection:()=>b.Owlv2ForObjectDetection,Owlv2ImageProcessor:()=>Zt.Owlv2ImageProcessor,Owlv2Model:()=>b.Owlv2Model,Owlv2PreTrainedModel:()=>b.Owlv2PreTrainedModel,Phi3ForCausalLM:()=>b.Phi3ForCausalLM,Phi3Model:()=>b.Phi3Model,Phi3PreTrainedModel:()=>b.Phi3PreTrainedModel,PhiForCausalLM:()=>b.PhiForCausalLM,PhiModel:()=>b.PhiModel,PhiPreTrainedModel:()=>b.PhiPreTrainedModel,Pipeline:()=>qr.Pipeline,PreTrainedModel:()=>b.PreTrainedModel,PreTrainedTokenizer:()=>sr.PreTrainedTokenizer,PretrainedConfig:()=>fc.PretrainedConfig,PretrainedMixin:()=>b.PretrainedMixin,Processor:()=>Zt.Processor,PvtForImageClassification:()=>b.PvtForImageClassification,PvtImageProcessor:()=>Zt.PvtImageProcessor,PvtModel:()=>b.PvtModel,PvtPreTrainedModel:()=>b.PvtPreTrainedModel,PyAnnoteFeatureExtractor:()=>Zt.PyAnnoteFeatureExtractor,PyAnnoteForAudioFrameClassification:()=>b.PyAnnoteForAudioFrameClassification,PyAnnoteModel:()=>b.PyAnnoteModel,PyAnnotePreTrainedModel:()=>b.PyAnnotePreTrainedModel,PyAnnoteProcessor:()=>Zt.PyAnnoteProcessor,QuestionAnsweringModelOutput:()=>b.QuestionAnsweringModelOutput,QuestionAnsweringPipeline:()=>qr.QuestionAnsweringPipeline,Qwen2ForCausalLM:()=>b.Qwen2ForCausalLM,Qwen2Model:()=>b.Qwen2Model,Qwen2PreTrainedModel:()=>b.Qwen2PreTrainedModel,Qwen2Tokenizer:()=>sr.Qwen2Tokenizer,RTDetrForObjectDetection:()=>b.RTDetrForObjectDetection,RTDetrImageProcessor:()=>Zt.RTDetrImageProcessor,RTDetrModel:()=>b.RTDetrModel,RTDetrObjectDetectionOutput:()=>b.RTDetrObjectDetectionOutput,RTDetrPreTrainedModel:()=>b.RTDetrPreTrainedModel,RawImage:()=>Pf.RawImage,ResNetForImageClassification:()=>b.ResNetForImageClassification,ResNetModel:()=>b.ResNetModel,ResNetPreTrainedModel:()=>b.ResNetPreTrainedModel,RoFormerForMaskedLM:()=>b.RoFormerForMaskedLM,RoFormerForQuestionAnswering:()=>b.RoFormerForQuestionAnswering,RoFormerForSequenceClassification:()=>b.RoFormerForSequenceClassification,RoFormerForTokenClassification:()=>b.RoFormerForTokenClassification,RoFormerModel:()=>b.RoFormerModel,RoFormerPreTrainedModel:()=>b.RoFormerPreTrainedModel,RoFormerTokenizer:()=>sr.RoFormerTokenizer,RobertaForMaskedLM:()=>b.RobertaForMaskedLM,RobertaForQuestionAnswering:()=>b.RobertaForQuestionAnswering,RobertaForSequenceClassification:()=>b.RobertaForSequenceClassification,RobertaForTokenClassification:()=>b.RobertaForTokenClassification,RobertaModel:()=>b.RobertaModel,RobertaPreTrainedModel:()=>b.RobertaPreTrainedModel,RobertaTokenizer:()=>sr.RobertaTokenizer,SamImageProcessor:()=>Zt.SamImageProcessor,SamImageSegmentationOutput:()=>b.SamImageSegmentationOutput,SamModel:()=>b.SamModel,SamPreTrainedModel:()=>b.SamPreTrainedModel,SamProcessor:()=>Zt.SamProcessor,SapiensFeatureExtractor:()=>Zt.SapiensFeatureExtractor,SapiensForDepthEstimation:()=>b.SapiensForDepthEstimation,SapiensForNormalEstimation:()=>b.SapiensForNormalEstimation,SapiensForSemanticSegmentation:()=>b.SapiensForSemanticSegmentation,SapiensPreTrainedModel:()=>b.SapiensPreTrainedModel,SeamlessM4TFeatureExtractor:()=>Zt.SeamlessM4TFeatureExtractor,SegformerFeatureExtractor:()=>Zt.SegformerFeatureExtractor,SegformerForImageClassification:()=>b.SegformerForImageClassification,SegformerForSemanticSegmentation:()=>b.SegformerForSemanticSegmentation,SegformerModel:()=>b.SegformerModel,SegformerPreTrainedModel:()=>b.SegformerPreTrainedModel,Seq2SeqLMOutput:()=>b.Seq2SeqLMOutput,SequenceClassifierOutput:()=>b.SequenceClassifierOutput,SiglipImageProcessor:()=>Zt.SiglipImageProcessor,SiglipModel:()=>b.SiglipModel,SiglipPreTrainedModel:()=>b.SiglipPreTrainedModel,SiglipTextModel:()=>b.SiglipTextModel,SiglipTokenizer:()=>sr.SiglipTokenizer,SiglipVisionModel:()=>b.SiglipVisionModel,SpeechT5FeatureExtractor:()=>Zt.SpeechT5FeatureExtractor,SpeechT5ForSpeechToText:()=>b.SpeechT5ForSpeechToText,SpeechT5ForTextToSpeech:()=>b.SpeechT5ForTextToSpeech,SpeechT5HifiGan:()=>b.SpeechT5HifiGan,SpeechT5Model:()=>b.SpeechT5Model,SpeechT5PreTrainedModel:()=>b.SpeechT5PreTrainedModel,SpeechT5Processor:()=>Zt.SpeechT5Processor,SpeechT5Tokenizer:()=>sr.SpeechT5Tokenizer,SqueezeBertForMaskedLM:()=>b.SqueezeBertForMaskedLM,SqueezeBertForQuestionAnswering:()=>b.SqueezeBertForQuestionAnswering,SqueezeBertForSequenceClassification:()=>b.SqueezeBertForSequenceClassification,SqueezeBertModel:()=>b.SqueezeBertModel,SqueezeBertPreTrainedModel:()=>b.SqueezeBertPreTrainedModel,SqueezeBertTokenizer:()=>sr.SqueezeBertTokenizer,StableLmForCausalLM:()=>b.StableLmForCausalLM,StableLmModel:()=>b.StableLmModel,StableLmPreTrainedModel:()=>b.StableLmPreTrainedModel,Starcoder2ForCausalLM:()=>b.Starcoder2ForCausalLM,Starcoder2Model:()=>b.Starcoder2Model,Starcoder2PreTrainedModel:()=>b.Starcoder2PreTrainedModel,StoppingCriteria:()=>so.StoppingCriteria,StoppingCriteriaList:()=>so.StoppingCriteriaList,SummarizationPipeline:()=>qr.SummarizationPipeline,Swin2SRForImageSuperResolution:()=>b.Swin2SRForImageSuperResolution,Swin2SRImageProcessor:()=>Zt.Swin2SRImageProcessor,Swin2SRModel:()=>b.Swin2SRModel,Swin2SRPreTrainedModel:()=>b.Swin2SRPreTrainedModel,SwinForImageClassification:()=>b.SwinForImageClassification,SwinModel:()=>b.SwinModel,SwinPreTrainedModel:()=>b.SwinPreTrainedModel,T5ForConditionalGeneration:()=>b.T5ForConditionalGeneration,T5Model:()=>b.T5Model,T5PreTrainedModel:()=>b.T5PreTrainedModel,T5Tokenizer:()=>sr.T5Tokenizer,TableTransformerForObjectDetection:()=>b.TableTransformerForObjectDetection,TableTransformerModel:()=>b.TableTransformerModel,TableTransformerObjectDetectionOutput:()=>b.TableTransformerObjectDetectionOutput,TableTransformerPreTrainedModel:()=>b.TableTransformerPreTrainedModel,Tensor:()=>dn.Tensor,Text2TextGenerationPipeline:()=>qr.Text2TextGenerationPipeline,TextClassificationPipeline:()=>qr.TextClassificationPipeline,TextGenerationPipeline:()=>qr.TextGenerationPipeline,TextStreamer:()=>mc.TextStreamer,TextToAudioPipeline:()=>qr.TextToAudioPipeline,TokenClassificationPipeline:()=>qr.TokenClassificationPipeline,TokenClassifierOutput:()=>b.TokenClassifierOutput,TokenizerModel:()=>sr.TokenizerModel,TrOCRForCausalLM:()=>b.TrOCRForCausalLM,TrOCRPreTrainedModel:()=>b.TrOCRPreTrainedModel,TranslationPipeline:()=>qr.TranslationPipeline,UniSpeechForCTC:()=>b.UniSpeechForCTC,UniSpeechForSequenceClassification:()=>b.UniSpeechForSequenceClassification,UniSpeechModel:()=>b.UniSpeechModel,UniSpeechPreTrainedModel:()=>b.UniSpeechPreTrainedModel,UniSpeechSatForAudioFrameClassification:()=>b.UniSpeechSatForAudioFrameClassification,UniSpeechSatForCTC:()=>b.UniSpeechSatForCTC,UniSpeechSatForSequenceClassification:()=>b.UniSpeechSatForSequenceClassification,UniSpeechSatModel:()=>b.UniSpeechSatModel,UniSpeechSatPreTrainedModel:()=>b.UniSpeechSatPreTrainedModel,ViTFeatureExtractor:()=>Zt.ViTFeatureExtractor,ViTForImageClassification:()=>b.ViTForImageClassification,ViTImageProcessor:()=>Zt.ViTImageProcessor,ViTMAEModel:()=>b.ViTMAEModel,ViTMAEPreTrainedModel:()=>b.ViTMAEPreTrainedModel,ViTMSNForImageClassification:()=>b.ViTMSNForImageClassification,ViTMSNModel:()=>b.ViTMSNModel,ViTMSNPreTrainedModel:()=>b.ViTMSNPreTrainedModel,ViTModel:()=>b.ViTModel,ViTPreTrainedModel:()=>b.ViTPreTrainedModel,VisionEncoderDecoderModel:()=>b.VisionEncoderDecoderModel,VitMatteForImageMatting:()=>b.VitMatteForImageMatting,VitMatteImageProcessor:()=>Zt.VitMatteImageProcessor,VitMattePreTrainedModel:()=>b.VitMattePreTrainedModel,VitsModel:()=>b.VitsModel,VitsModelOutput:()=>b.VitsModelOutput,VitsPreTrainedModel:()=>b.VitsPreTrainedModel,VitsTokenizer:()=>sr.VitsTokenizer,Wav2Vec2BertForCTC:()=>b.Wav2Vec2BertForCTC,Wav2Vec2BertForSequenceClassification:()=>b.Wav2Vec2BertForSequenceClassification,Wav2Vec2BertModel:()=>b.Wav2Vec2BertModel,Wav2Vec2BertPreTrainedModel:()=>b.Wav2Vec2BertPreTrainedModel,Wav2Vec2CTCTokenizer:()=>sr.Wav2Vec2CTCTokenizer,Wav2Vec2FeatureExtractor:()=>Zt.Wav2Vec2FeatureExtractor,Wav2Vec2ForAudioFrameClassification:()=>b.Wav2Vec2ForAudioFrameClassification,Wav2Vec2ForCTC:()=>b.Wav2Vec2ForCTC,Wav2Vec2ForSequenceClassification:()=>b.Wav2Vec2ForSequenceClassification,Wav2Vec2Model:()=>b.Wav2Vec2Model,Wav2Vec2PreTrainedModel:()=>b.Wav2Vec2PreTrainedModel,Wav2Vec2ProcessorWithLM:()=>Zt.Wav2Vec2ProcessorWithLM,WavLMForAudioFrameClassification:()=>b.WavLMForAudioFrameClassification,WavLMForCTC:()=>b.WavLMForCTC,WavLMForSequenceClassification:()=>b.WavLMForSequenceClassification,WavLMForXVector:()=>b.WavLMForXVector,WavLMModel:()=>b.WavLMModel,WavLMPreTrainedModel:()=>b.WavLMPreTrainedModel,WeSpeakerFeatureExtractor:()=>Zt.WeSpeakerFeatureExtractor,WeSpeakerResNetModel:()=>b.WeSpeakerResNetModel,WeSpeakerResNetPreTrainedModel:()=>b.WeSpeakerResNetPreTrainedModel,WhisperFeatureExtractor:()=>Zt.WhisperFeatureExtractor,WhisperForConditionalGeneration:()=>b.WhisperForConditionalGeneration,WhisperModel:()=>b.WhisperModel,WhisperPreTrainedModel:()=>b.WhisperPreTrainedModel,WhisperProcessor:()=>Zt.WhisperProcessor,WhisperTextStreamer:()=>mc.WhisperTextStreamer,WhisperTokenizer:()=>sr.WhisperTokenizer,XLMForQuestionAnswering:()=>b.XLMForQuestionAnswering,XLMForSequenceClassification:()=>b.XLMForSequenceClassification,XLMForTokenClassification:()=>b.XLMForTokenClassification,XLMModel:()=>b.XLMModel,XLMPreTrainedModel:()=>b.XLMPreTrainedModel,XLMRobertaForMaskedLM:()=>b.XLMRobertaForMaskedLM,XLMRobertaForQuestionAnswering:()=>b.XLMRobertaForQuestionAnswering,XLMRobertaForSequenceClassification:()=>b.XLMRobertaForSequenceClassification,XLMRobertaForTokenClassification:()=>b.XLMRobertaForTokenClassification,XLMRobertaModel:()=>b.XLMRobertaModel,XLMRobertaPreTrainedModel:()=>b.XLMRobertaPreTrainedModel,XLMRobertaTokenizer:()=>sr.XLMRobertaTokenizer,XLMTokenizer:()=>sr.XLMTokenizer,XLMWithLMHeadModel:()=>b.XLMWithLMHeadModel,XVectorOutput:()=>b.XVectorOutput,YolosFeatureExtractor:()=>Zt.YolosFeatureExtractor,YolosForObjectDetection:()=>b.YolosForObjectDetection,YolosModel:()=>b.YolosModel,YolosObjectDetectionOutput:()=>b.YolosObjectDetectionOutput,YolosPreTrainedModel:()=>b.YolosPreTrainedModel,ZeroShotAudioClassificationPipeline:()=>qr.ZeroShotAudioClassificationPipeline,ZeroShotClassificationPipeline:()=>qr.ZeroShotClassificationPipeline,ZeroShotImageClassificationPipeline:()=>qr.ZeroShotImageClassificationPipeline,ZeroShotObjectDetectionPipeline:()=>qr.ZeroShotObjectDetectionPipeline,bankers_round:()=>$n.bankers_round,cat:()=>dn.cat,cos_sim:()=>$n.cos_sim,dot:()=>$n.dot,dynamic_time_warping:()=>$n.dynamic_time_warping,env:()=>kf.env,full:()=>dn.full,full_like:()=>dn.full_like,getKeyValueShapes:()=>fc.getKeyValueShapes,hamming:()=>xi.hamming,hanning:()=>xi.hanning,interpolate:()=>dn.interpolate,interpolate_4d:()=>dn.interpolate_4d,interpolate_data:()=>$n.interpolate_data,is_chinese_char:()=>sr.is_chinese_char,layer_norm:()=>dn.layer_norm,log_softmax:()=>$n.log_softmax,magnitude:()=>$n.magnitude,matmul:()=>dn.matmul,max:()=>$n.max,mean:()=>dn.mean,mean_pooling:()=>dn.mean_pooling,medianFilter:()=>$n.medianFilter,mel_filter_bank:()=>xi.mel_filter_bank,min:()=>$n.min,ones:()=>dn.ones,ones_like:()=>dn.ones_like,permute:()=>dn.permute,permute_data:()=>$n.permute_data,pipeline:()=>qr.pipeline,quantize_embeddings:()=>dn.quantize_embeddings,read_audio:()=>xi.read_audio,rfft:()=>dn.rfft,round:()=>$n.round,softmax:()=>$n.softmax,spectrogram:()=>xi.spectrogram,stack:()=>dn.stack,std_mean:()=>dn.std_mean,topk:()=>dn.topk,window_function:()=>xi.window_function,zeros:()=>dn.zeros,zeros_like:()=>dn.zeros_like});var kf=Gr("./src/env.js"),qr=Gr("./src/pipelines.js"),b=Gr("./src/models.js"),sr=Gr("./src/tokenizers.js"),Zt=Gr("./src/processors.js"),fc=Gr("./src/configs.js"),xi=Gr("./src/utils/audio.js"),Pf=Gr("./src/utils/image.js"),dn=Gr("./src/utils/tensor.js"),$n=Gr("./src/utils/maths.js"),mc=Gr("./src/generation/streamers.js"),so=Gr("./src/generation/stopping_criteria.js");c.ASTFeatureExtractor,c.ASTForAudioClassification,c.ASTModel,c.ASTPreTrainedModel,c.AlbertForMaskedLM,c.AlbertForQuestionAnswering,c.AlbertForSequenceClassification,c.AlbertModel,c.AlbertPreTrainedModel,c.AlbertTokenizer,c.AudioClassificationPipeline,c.AutoConfig,c.AutoModel,c.AutoModelForAudioClassification,c.AutoModelForAudioFrameClassification,c.AutoModelForCTC;var Af=c.AutoModelForCausalLM;c.AutoModelForDepthEstimation,c.AutoModelForDocumentQuestionAnswering,c.AutoModelForImageClassification,c.AutoModelForImageFeatureExtraction,c.AutoModelForImageMatting,c.AutoModelForImageSegmentation,c.AutoModelForImageToImage,c.AutoModelForMaskGeneration,c.AutoModelForMaskedLM,c.AutoModelForNormalEstimation,c.AutoModelForObjectDetection,c.AutoModelForQuestionAnswering,c.AutoModelForSemanticSegmentation,c.AutoModelForSeq2SeqLM,c.AutoModelForSequenceClassification,c.AutoModelForSpeechSeq2Seq,c.AutoModelForTextToSpectrogram,c.AutoModelForTextToWaveform,c.AutoModelForTokenClassification,c.AutoModelForUniversalSegmentation,c.AutoModelForVision2Seq,c.AutoModelForXVector,c.AutoModelForZeroShotObjectDetection,c.AutoProcessor;var If=c.AutoTokenizer;c.AutomaticSpeechRecognitionPipeline,c.BartForConditionalGeneration,c.BartForSequenceClassification,c.BartModel,c.BartPretrainedModel,c.BartTokenizer,c.BaseModelOutput,c.BaseStreamer,c.BeitFeatureExtractor,c.BeitForImageClassification,c.BeitModel,c.BeitPreTrainedModel,c.BertForMaskedLM,c.BertForQuestionAnswering,c.BertForSequenceClassification,c.BertForTokenClassification,c.BertModel,c.BertPreTrainedModel,c.BertTokenizer,c.BitImageProcessor,c.BlenderbotForConditionalGeneration,c.BlenderbotModel,c.BlenderbotPreTrainedModel,c.BlenderbotSmallForConditionalGeneration,c.BlenderbotSmallModel,c.BlenderbotSmallPreTrainedModel,c.BlenderbotSmallTokenizer,c.BlenderbotTokenizer,c.BloomForCausalLM,c.BloomModel,c.BloomPreTrainedModel,c.BloomTokenizer,c.CLIPFeatureExtractor,c.CLIPImageProcessor,c.CLIPModel,c.CLIPPreTrainedModel,c.CLIPSegForImageSegmentation,c.CLIPSegModel,c.CLIPSegPreTrainedModel,c.CLIPTextModel,c.CLIPTextModelWithProjection,c.CLIPTokenizer,c.CLIPVisionModel,c.CLIPVisionModelWithProjection,c.CamembertForMaskedLM,c.CamembertForQuestionAnswering,c.CamembertForSequenceClassification,c.CamembertForTokenClassification,c.CamembertModel,c.CamembertPreTrainedModel,c.CamembertTokenizer,c.CausalLMOutput,c.CausalLMOutputWithPast,c.ChineseCLIPFeatureExtractor,c.ChineseCLIPModel,c.ChineseCLIPPreTrainedModel,c.ClapAudioModelWithProjection,c.ClapFeatureExtractor,c.ClapModel,c.ClapPreTrainedModel,c.ClapTextModelWithProjection,c.CodeGenForCausalLM,c.CodeGenModel,c.CodeGenPreTrainedModel,c.CodeGenTokenizer,c.CodeLlamaTokenizer,c.CohereForCausalLM,c.CohereModel,c.CoherePreTrainedModel,c.CohereTokenizer,c.ConvBertForMaskedLM,c.ConvBertForQuestionAnswering,c.ConvBertForSequenceClassification,c.ConvBertForTokenClassification,c.ConvBertModel,c.ConvBertPreTrainedModel,c.ConvBertTokenizer,c.ConvNextFeatureExtractor,c.ConvNextForImageClassification,c.ConvNextImageProcessor,c.ConvNextModel,c.ConvNextPreTrainedModel,c.ConvNextV2ForImageClassification,c.ConvNextV2Model,c.ConvNextV2PreTrainedModel,c.DPTFeatureExtractor,c.DPTForDepthEstimation,c.DPTImageProcessor,c.DPTModel,c.DPTPreTrainedModel,c.DebertaForMaskedLM,c.DebertaForQuestionAnswering,c.DebertaForSequenceClassification,c.DebertaForTokenClassification,c.DebertaModel,c.DebertaPreTrainedModel,c.DebertaTokenizer,c.DebertaV2ForMaskedLM,c.DebertaV2ForQuestionAnswering,c.DebertaV2ForSequenceClassification,c.DebertaV2ForTokenClassification,c.DebertaV2Model,c.DebertaV2PreTrainedModel,c.DebertaV2Tokenizer,c.DecisionTransformerModel,c.DecisionTransformerPreTrainedModel,c.DeiTFeatureExtractor,c.DeiTForImageClassification,c.DeiTModel,c.DeiTPreTrainedModel,c.DepthAnythingForDepthEstimation,c.DepthAnythingPreTrainedModel,c.DepthEstimationPipeline,c.DetrFeatureExtractor,c.DetrForObjectDetection,c.DetrForSegmentation,c.DetrModel,c.DetrObjectDetectionOutput,c.DetrPreTrainedModel,c.DetrSegmentationOutput,c.Dinov2ForImageClassification,c.Dinov2Model,c.Dinov2PreTrainedModel,c.DistilBertForMaskedLM,c.DistilBertForQuestionAnswering,c.DistilBertForSequenceClassification,c.DistilBertForTokenClassification,c.DistilBertModel,c.DistilBertPreTrainedModel,c.DistilBertTokenizer,c.DocumentQuestionAnsweringPipeline,c.DonutFeatureExtractor,c.DonutSwinModel,c.DonutSwinPreTrainedModel,c.EfficientNetForImageClassification,c.EfficientNetImageProcessor,c.EfficientNetModel,c.EfficientNetPreTrainedModel,c.ElectraForMaskedLM,c.ElectraForQuestionAnswering,c.ElectraForSequenceClassification,c.ElectraForTokenClassification,c.ElectraModel,c.ElectraPreTrainedModel,c.ElectraTokenizer,c.EosTokenCriteria,c.EsmForMaskedLM,c.EsmForSequenceClassification,c.EsmForTokenClassification,c.EsmModel,c.EsmPreTrainedModel,c.EsmTokenizer,c.FFT,c.FalconForCausalLM,c.FalconModel,c.FalconPreTrainedModel,c.FalconTokenizer,c.FastViTForImageClassification,c.FastViTModel,c.FastViTPreTrainedModel,c.FeatureExtractionPipeline,c.FeatureExtractor,c.FillMaskPipeline,c.Florence2ForConditionalGeneration,c.Florence2PreTrainedModel,c.Florence2Processor,c.GLPNFeatureExtractor,c.GLPNForDepthEstimation,c.GLPNModel,c.GLPNPreTrainedModel,c.GPT2LMHeadModel,c.GPT2Model,c.GPT2PreTrainedModel,c.GPT2Tokenizer,c.GPTBigCodeForCausalLM,c.GPTBigCodeModel,c.GPTBigCodePreTrainedModel,c.GPTJForCausalLM,c.GPTJModel,c.GPTJPreTrainedModel,c.GPTNeoForCausalLM,c.GPTNeoModel,c.GPTNeoPreTrainedModel,c.GPTNeoXForCausalLM,c.GPTNeoXModel,c.GPTNeoXPreTrainedModel,c.GPTNeoXTokenizer,c.Gemma2ForCausalLM,c.Gemma2Model,c.Gemma2PreTrainedModel,c.GemmaForCausalLM,c.GemmaModel,c.GemmaPreTrainedModel,c.GemmaTokenizer,c.Grok1Tokenizer,c.GroupViTModel,c.GroupViTPreTrainedModel,c.HerbertTokenizer,c.HieraForImageClassification,c.HieraModel,c.HieraPreTrainedModel,c.HubertForCTC,c.HubertForSequenceClassification,c.HubertModel,c.HubertPreTrainedModel,c.ImageClassificationPipeline,c.ImageFeatureExtractionPipeline,c.ImageFeatureExtractor,c.ImageMattingOutput,c.ImageSegmentationPipeline,c.ImageToImagePipeline,c.ImageToTextPipeline;var Ff=c.InterruptableStoppingCriteria;c.JAISLMHeadModel,c.JAISModel,c.JAISPreTrainedModel,c.LlamaForCausalLM,c.LlamaModel,c.LlamaPreTrainedModel,c.LlamaTokenizer,c.LlavaForConditionalGeneration,c.LlavaPreTrainedModel,c.LongT5ForConditionalGeneration,c.LongT5Model,c.LongT5PreTrainedModel,c.M2M100ForConditionalGeneration,c.M2M100Model,c.M2M100PreTrainedModel,c.M2M100Tokenizer,c.MBart50Tokenizer,c.MBartForCausalLM,c.MBartForConditionalGeneration,c.MBartForSequenceClassification,c.MBartModel,c.MBartPreTrainedModel,c.MBartTokenizer,c.MPNetForMaskedLM,c.MPNetForQuestionAnswering,c.MPNetForSequenceClassification,c.MPNetForTokenClassification,c.MPNetModel,c.MPNetPreTrainedModel,c.MPNetTokenizer,c.MT5ForConditionalGeneration,c.MT5Model,c.MT5PreTrainedModel,c.MarianMTModel,c.MarianModel,c.MarianPreTrainedModel,c.MarianTokenizer,c.MaskFormerFeatureExtractor,c.MaskFormerForInstanceSegmentation,c.MaskFormerModel,c.MaskFormerPreTrainedModel,c.MaskedLMOutput,c.MaxLengthCriteria,c.MistralForCausalLM,c.MistralModel,c.MistralPreTrainedModel,c.MobileBertForMaskedLM,c.MobileBertForQuestionAnswering,c.MobileBertForSequenceClassification,c.MobileBertModel,c.MobileBertPreTrainedModel,c.MobileBertTokenizer,c.MobileNetV1FeatureExtractor,c.MobileNetV1ForImageClassification,c.MobileNetV1Model,c.MobileNetV1PreTrainedModel,c.MobileNetV2FeatureExtractor,c.MobileNetV2ForImageClassification,c.MobileNetV2Model,c.MobileNetV2PreTrainedModel,c.MobileNetV3FeatureExtractor,c.MobileNetV3ForImageClassification,c.MobileNetV3Model,c.MobileNetV3PreTrainedModel,c.MobileNetV4FeatureExtractor,c.MobileNetV4ForImageClassification,c.MobileNetV4Model,c.MobileNetV4PreTrainedModel,c.MobileViTFeatureExtractor,c.MobileViTForImageClassification,c.MobileViTImageProcessor,c.MobileViTModel,c.MobileViTPreTrainedModel,c.MobileViTV2ForImageClassification,c.MobileViTV2Model,c.MobileViTV2PreTrainedModel,c.ModelOutput,c.Moondream1ForConditionalGeneration,c.MptForCausalLM,c.MptModel,c.MptPreTrainedModel,c.MusicgenForCausalLM,c.MusicgenForConditionalGeneration,c.MusicgenModel,c.MusicgenPreTrainedModel,c.NllbTokenizer,c.NomicBertModel,c.NomicBertPreTrainedModel,c.NougatImageProcessor,c.NougatTokenizer,c.OPTForCausalLM,c.OPTModel,c.OPTPreTrainedModel,c.ObjectDetectionPipeline,c.OpenELMForCausalLM,c.OpenELMModel,c.OpenELMPreTrainedModel,c.OwlViTFeatureExtractor,c.OwlViTForObjectDetection,c.OwlViTModel,c.OwlViTPreTrainedModel,c.OwlViTProcessor,c.Owlv2ForObjectDetection,c.Owlv2ImageProcessor,c.Owlv2Model,c.Owlv2PreTrainedModel,c.Phi3ForCausalLM,c.Phi3Model,c.Phi3PreTrainedModel,c.PhiForCausalLM,c.PhiModel,c.PhiPreTrainedModel,c.Pipeline,c.PreTrainedModel,c.PreTrainedTokenizer,c.PretrainedConfig,c.PretrainedMixin,c.Processor,c.PvtForImageClassification,c.PvtImageProcessor,c.PvtModel,c.PvtPreTrainedModel,c.PyAnnoteFeatureExtractor,c.PyAnnoteForAudioFrameClassification,c.PyAnnoteModel,c.PyAnnotePreTrainedModel,c.PyAnnoteProcessor,c.QuestionAnsweringModelOutput,c.QuestionAnsweringPipeline,c.Qwen2ForCausalLM,c.Qwen2Model,c.Qwen2PreTrainedModel,c.Qwen2Tokenizer,c.RTDetrForObjectDetection,c.RTDetrImageProcessor,c.RTDetrModel,c.RTDetrObjectDetectionOutput,c.RTDetrPreTrainedModel,c.RawImage,c.ResNetForImageClassification,c.ResNetModel,c.ResNetPreTrainedModel,c.RoFormerForMaskedLM,c.RoFormerForQuestionAnswering,c.RoFormerForSequenceClassification,c.RoFormerForTokenClassification,c.RoFormerModel,c.RoFormerPreTrainedModel,c.RoFormerTokenizer,c.RobertaForMaskedLM,c.RobertaForQuestionAnswering,c.RobertaForSequenceClassification,c.RobertaForTokenClassification,c.RobertaModel,c.RobertaPreTrainedModel,c.RobertaTokenizer,c.SamImageProcessor,c.SamImageSegmentationOutput,c.SamModel,c.SamPreTrainedModel,c.SamProcessor,c.SapiensFeatureExtractor,c.SapiensForDepthEstimation,c.SapiensForNormalEstimation,c.SapiensForSemanticSegmentation,c.SapiensPreTrainedModel,c.SeamlessM4TFeatureExtractor,c.SegformerFeatureExtractor,c.SegformerForImageClassification,c.SegformerForSemanticSegmentation,c.SegformerModel,c.SegformerPreTrainedModel,c.Seq2SeqLMOutput,c.SequenceClassifierOutput,c.SiglipImageProcessor,c.SiglipModel,c.SiglipPreTrainedModel,c.SiglipTextModel,c.SiglipTokenizer,c.SiglipVisionModel,c.SpeechT5FeatureExtractor,c.SpeechT5ForSpeechToText,c.SpeechT5ForTextToSpeech,c.SpeechT5HifiGan,c.SpeechT5Model,c.SpeechT5PreTrainedModel,c.SpeechT5Processor,c.SpeechT5Tokenizer,c.SqueezeBertForMaskedLM,c.SqueezeBertForQuestionAnswering,c.SqueezeBertForSequenceClassification,c.SqueezeBertModel,c.SqueezeBertPreTrainedModel,c.SqueezeBertTokenizer,c.StableLmForCausalLM,c.StableLmModel,c.StableLmPreTrainedModel,c.Starcoder2ForCausalLM,c.Starcoder2Model,c.Starcoder2PreTrainedModel,c.StoppingCriteria,c.StoppingCriteriaList,c.SummarizationPipeline,c.Swin2SRForImageSuperResolution,c.Swin2SRImageProcessor,c.Swin2SRModel,c.Swin2SRPreTrainedModel,c.SwinForImageClassification,c.SwinModel,c.SwinPreTrainedModel,c.T5ForConditionalGeneration,c.T5Model,c.T5PreTrainedModel,c.T5Tokenizer,c.TableTransformerForObjectDetection,c.TableTransformerModel,c.TableTransformerObjectDetectionOutput,c.TableTransformerPreTrainedModel,c.Tensor,c.Text2TextGenerationPipeline,c.TextClassificationPipeline,c.TextGenerationPipeline;var zf=c.TextStreamer;c.TextToAudioPipeline,c.TokenClassificationPipeline,c.TokenClassifierOutput,c.TokenizerModel,c.TrOCRForCausalLM,c.TrOCRPreTrainedModel,c.TranslationPipeline,c.UniSpeechForCTC,c.UniSpeechForSequenceClassification,c.UniSpeechModel,c.UniSpeechPreTrainedModel,c.UniSpeechSatForAudioFrameClassification,c.UniSpeechSatForCTC,c.UniSpeechSatForSequenceClassification,c.UniSpeechSatModel,c.UniSpeechSatPreTrainedModel,c.ViTFeatureExtractor,c.ViTForImageClassification,c.ViTImageProcessor,c.ViTMAEModel,c.ViTMAEPreTrainedModel,c.ViTMSNForImageClassification,c.ViTMSNModel,c.ViTMSNPreTrainedModel,c.ViTModel,c.ViTPreTrainedModel,c.VisionEncoderDecoderModel,c.VitMatteForImageMatting,c.VitMatteImageProcessor,c.VitMattePreTrainedModel,c.VitsModel,c.VitsModelOutput,c.VitsPreTrainedModel,c.VitsTokenizer,c.Wav2Vec2BertForCTC,c.Wav2Vec2BertForSequenceClassification,c.Wav2Vec2BertModel,c.Wav2Vec2BertPreTrainedModel,c.Wav2Vec2CTCTokenizer,c.Wav2Vec2FeatureExtractor,c.Wav2Vec2ForAudioFrameClassification,c.Wav2Vec2ForCTC,c.Wav2Vec2ForSequenceClassification,c.Wav2Vec2Model,c.Wav2Vec2PreTrainedModel,c.Wav2Vec2ProcessorWithLM,c.WavLMForAudioFrameClassification,c.WavLMForCTC,c.WavLMForSequenceClassification,c.WavLMForXVector,c.WavLMModel,c.WavLMPreTrainedModel,c.WeSpeakerFeatureExtractor,c.WeSpeakerResNetModel,c.WeSpeakerResNetPreTrainedModel,c.WhisperFeatureExtractor,c.WhisperForConditionalGeneration,c.WhisperModel,c.WhisperPreTrainedModel,c.WhisperProcessor,c.WhisperTextStreamer,c.WhisperTokenizer,c.XLMForQuestionAnswering,c.XLMForSequenceClassification,c.XLMForTokenClassification,c.XLMModel,c.XLMPreTrainedModel,c.XLMRobertaForMaskedLM,c.XLMRobertaForQuestionAnswering,c.XLMRobertaForSequenceClassification,c.XLMRobertaForTokenClassification,c.XLMRobertaModel,c.XLMRobertaPreTrainedModel,c.XLMRobertaTokenizer,c.XLMTokenizer,c.XLMWithLMHeadModel,c.XVectorOutput,c.YolosFeatureExtractor,c.YolosForObjectDetection,c.YolosModel,c.YolosObjectDetectionOutput,c.YolosPreTrainedModel,c.ZeroShotAudioClassificationPipeline,c.ZeroShotClassificationPipeline,c.ZeroShotImageClassificationPipeline,c.ZeroShotObjectDetectionPipeline,c.bankers_round,c.cat,c.cos_sim,c.dot,c.dynamic_time_warping,c.env,c.full,c.full_like,c.getKeyValueShapes,c.hamming,c.hanning,c.interpolate,c.interpolate_4d,c.interpolate_data,c.is_chinese_char,c.layer_norm,c.log_softmax,c.magnitude,c.matmul,c.max,c.mean,c.mean_pooling,c.medianFilter,c.mel_filter_bank,c.min,c.ones,c.ones_like,c.permute,c.permute_data,c.pipeline,c.quantize_embeddings,c.read_audio,c.rfft,c.round,c.softmax,c.spectrogram,c.stack,c.std_mean,c.topk,c.window_function,c.zeros,c.zeros_like;class _c{static async getInstance(Ce=null){return this.tokenizer??(this.tokenizer=If.from_pretrained(this.model_id,{progress_callback:Ce})),this.model??(this.model=Af.from_pretrained(this.model_id,{dtype:"q4f16",device:"webgpu",progress_callback:Ce})),Promise.all([this.tokenizer,this.model])}}xe(_c,"model_id","onnx-community/Llama-3.2-1B-Instruct-q4f16");const wd=new Ff;async function Of(Pt){const[Ce,N]=await _c.getInstance(),z=Ce.apply_chat_template(Pt,{add_generation_prompt:!0,return_dict:!0});let me,ye=0,Te;const Ee=()=>{me??(me=performance.now()),ye++>0&&(Te=ye/(performance.now()-me)*1e3)},j=ne=>{self.postMessage({status:"update",output:ne,tps:Te,numTokens:ye})},S=new zf(Ce,{skip_prompt:!0,skip_special_tokens:!0,callback_function:j,token_callback_function:Ee});self.postMessage({status:"start"});const{past_key_values:V,sequences:P}=await N.generate({...z,do_sample:!1,max_new_tokens:1024,streamer:S,stopping_criteria:wd,return_dict_in_generate:!0}),te=Ce.batch_decode(P,{skip_special_tokens:!0});self.postMessage({status:"complete",output:te})}async function Df(){try{if(!await navigator.gpu.requestAdapter())throw new Error("WebGPU is not supported (no adapter found)")}catch(Pt){self.postMessage({status:"error",data:Pt.toString()})}}async function Lf(){self.postMessage({status:"loading",data:"Loading model..."});const[Pt,Ce]=await _c.getInstance(z=>{self.postMessage(z)});self.postMessage({status:"loading",data:"Compiling shaders and warming up model..."});const N=Pt("a");await Ce.generate({...N,max_new_tokens:1}),self.postMessage({status:"ready"})}self.addEventListener("message",async Pt=>{const{type:Ce,data:N}=Pt.data;switch(Ce){case"check":Df();break;case"load":Lf();break;case"generate":wd.reset(),Of(N);break;case"interrupt":wd.interrupt();break;case"reset":wd.reset();break}})})(); diff --git a/assets/worker-ZGcka8VC.js b/assets/worker-ZGcka8VC.js new file mode 100644 index 0000000000000000000000000000000000000000..d0b2e9b026fecb9c86d908db740f13a889edb644 --- /dev/null +++ b/assets/worker-ZGcka8VC.js @@ -0,0 +1,2887 @@ +var Hx=Object.defineProperty;var qx=(gs,Pr,Ln)=>Pr in gs?Hx(gs,Pr,{enumerable:!0,configurable:!0,writable:!0,value:Ln}):gs[Pr]=Ln;var te=(gs,Pr,Ln)=>qx(gs,typeof Pr!="symbol"?Pr+"":Pr,Ln);(function(){"use strict";const gs=new Map,Pr=[],Ln=(e,r,t)=>{if(r&&typeof r.init=="function"&&typeof r.createInferenceSessionHandler=="function"){const s=gs.get(e);if(s===void 0)gs.set(e,{backend:r,priority:t});else{if(s.priority>t)return;if(s.priority===t&&s.backend!==r)throw new Error(`cannot register backend "${e}" using priority ${t}`)}if(t>=0){const o=Pr.indexOf(e);o!==-1&&Pr.splice(o,1);for(let n=0;n{const r=gs.get(e);if(!r)return"backend not found.";if(r.initialized)return r.backend;if(r.aborted)return r.error;{const t=!!r.initPromise;try{return t||(r.initPromise=r.backend.init(e)),await r.initPromise,r.initialized=!0,r.backend}catch(s){return t||(r.error=`${s}`,r.aborted=!0),r.error}finally{delete r.initPromise}}},R0=async e=>{const r=e.executionProviders||[],t=r.map(l=>typeof l=="string"?l:l.name),s=t.length===0?Pr:t;let o;const n=[],i=new Set;for(const l of s){const u=await B0(l);typeof u=="string"?n.push({name:l,err:u}):(o||(o=u),o===u&&i.add(l))}if(!o)throw new Error(`no available backend found. ERR: ${n.map(l=>`[${l.name}] ${l.err}`).join(", ")}`);for(const{name:l,err:u}of n)t.includes(l)&&console.warn(`removing requested execution provider "${l}" from session options because it is not available: ${u}`);const a=r.filter(l=>i.has(typeof l=="string"?l:l.name));return[o,new Proxy(e,{get:(l,u)=>u==="executionProviders"?a:Reflect.get(l,u)})]},j0="1.21.0";let xd="warning";const Yr={wasm:{},webgl:{},webgpu:{},versions:{common:j0},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}`);xd=e}},get logLevel(){return xd}};Object.defineProperty(Yr,"logLevel",{enumerable:!0});const N0=Yr,V0=(e,r)=>{const t=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);t.width=e.dims[3],t.height=e.dims[2];const s=t.getContext("2d");if(s!=null){let o,n;(r==null?void 0:r.tensorLayout)!==void 0&&r.tensorLayout==="NHWC"?(o=e.dims[2],n=e.dims[3]):(o=e.dims[3],n=e.dims[2]);const i=(r==null?void 0:r.format)!==void 0?r.format:"RGB",a=r==null?void 0:r.norm;let l,u;a===void 0||a.mean===void 0?l=[255,255,255,255]:typeof a.mean=="number"?l=[a.mean,a.mean,a.mean,a.mean]:(l=[a.mean[0],a.mean[1],a.mean[2],0],a.mean[3]!==void 0&&(l[3]=a.mean[3])),a===void 0||a.bias===void 0?u=[0,0,0,0]:typeof a.bias=="number"?u=[a.bias,a.bias,a.bias,a.bias]:(u=[a.bias[0],a.bias[1],a.bias[2],0],a.bias[3]!==void 0&&(u[3]=a.bias[3]));const p=n*o;let d=0,c=p,f=p*2,_=-1;i==="RGBA"?(d=0,c=p,f=p*2,_=p*3):i==="RGB"?(d=0,c=p,f=p*2):i==="RBG"&&(d=0,f=p,c=p*2);for(let T=0;T{const t=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");let s;if(t!=null){let o,n,i;(r==null?void 0:r.tensorLayout)!==void 0&&r.tensorLayout==="NHWC"?(o=e.dims[2],n=e.dims[1],i=e.dims[3]):(o=e.dims[3],n=e.dims[2],i=e.dims[1]);const a=r!==void 0&&r.format!==void 0?r.format:"RGB",l=r==null?void 0:r.norm;let u,p;l===void 0||l.mean===void 0?u=[255,255,255,255]:typeof l.mean=="number"?u=[l.mean,l.mean,l.mean,l.mean]:(u=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(u[3]=l.mean[3])),l===void 0||l.bias===void 0?p=[0,0,0,0]:typeof l.bias=="number"?p=[l.bias,l.bias,l.bias,l.bias]:(p=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(p[3]=l.bias[3]));const d=n*o;if(r!==void 0&&(r.format!==void 0&&i===4&&r.format!=="RGBA"||i===3&&r.format!=="RGB"&&r.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");const c=4;let f=0,_=1,T=2,k=3,w=0,g=d,S=d*2,E=-1;a==="RGBA"?(w=0,g=d,S=d*2,E=d*3):a==="RGB"?(w=0,g=d,S=d*2):a==="RBG"&&(w=0,S=d,g=d*2),s=t.createImageData(o,n);for(let y=0;y{if(e===void 0)throw new Error("Image buffer must be defined");if(r.height===void 0||r.width===void 0)throw new Error("Image height and width must be defined");if(r.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");const{height:t,width:s}=r,o=r.norm??{mean:255,bias:0};let n,i;typeof o.mean=="number"?n=[o.mean,o.mean,o.mean,o.mean]:n=[o.mean[0],o.mean[1],o.mean[2],o.mean[3]??255],typeof o.bias=="number"?i=[o.bias,o.bias,o.bias,o.bias]:i=[o.bias[0],o.bias[1],o.bias[2],o.bias[3]??0];const a=r.format!==void 0?r.format:"RGBA",l=r.tensorFormat!==void 0&&r.tensorFormat!==void 0?r.tensorFormat:"RGB",u=t*s,p=l==="RGBA"?new Float32Array(u*4):new Float32Array(u*3);let d=4,c=0,f=1,_=2,T=3,k=0,w=u,g=u*2,S=-1;a==="RGB"&&(d=3,c=0,f=1,_=2,T=-1),l==="RGBA"?S=u*3:l==="RBG"?(k=0,g=u,w=u*2):l==="BGR"&&(g=0,w=u,k=u*2);for(let y=0;y{const t=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,s=typeof ImageData<"u"&&e instanceof ImageData,o=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,n=typeof e=="string";let i,a=r??{};const l=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},u=p=>typeof HTMLCanvasElement<"u"&&p instanceof HTMLCanvasElement||p instanceof OffscreenCanvas?p.getContext("2d"):null;if(t){const p=l();p.width=e.width,p.height=e.height;const d=u(p);if(d!=null){let c=e.height,f=e.width;if(r!==void 0&&r.resizedHeight!==void 0&&r.resizedWidth!==void 0&&(c=r.resizedHeight,f=r.resizedWidth),r!==void 0){if(a=r,r.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");a.tensorFormat="RGBA",a.height=c,a.width=f}else a.tensorFormat="RGBA",a.height=c,a.width=f;d.drawImage(e,0,0),i=d.getImageData(0,0,f,c).data}else throw new Error("Can not access image data")}else if(s){let p,d;if(r!==void 0&&r.resizedWidth!==void 0&&r.resizedHeight!==void 0?(p=r.resizedHeight,d=r.resizedWidth):(p=e.height,d=e.width),r!==void 0&&(a=r),a.format="RGBA",a.height=p,a.width=d,r!==void 0){const c=l();c.width=d,c.height=p;const f=u(c);if(f!=null)f.putImageData(e,0,0),i=f.getImageData(0,0,d,p).data;else throw new Error("Can not access image data")}else i=e.data}else if(o){if(r===void 0)throw new Error("Please provide image config with format for Imagebitmap");const p=l();p.width=e.width,p.height=e.height;const d=u(p);if(d!=null){const c=e.height,f=e.width;return d.drawImage(e,0,0,f,c),i=d.getImageData(0,0,f,c).data,a.height=c,a.width=f,ga(i,a)}else throw new Error("Can not access image data")}else{if(n)return new Promise((p,d)=>{const c=l(),f=u(c);if(!e||!f)return d();const _=new Image;_.crossOrigin="Anonymous",_.src=e,_.onload=()=>{c.width=_.width,c.height=_.height,f.drawImage(_,0,0,c.width,c.height);const T=f.getImageData(0,0,c.width,c.height);a.height=c.height,a.width=c.width,p(ga(T.data,a))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(i!==void 0)return ga(i,a);throw new Error("Input data provided is not supported - aborted tensor creation")},G0=(e,r)=>{const{width:t,height:s,download:o,dispose:n}=r,i=[1,s,t,4];return new Ur({location:"texture",type:"float32",texture:e,dims:i,download:o,dispose:n})},K0=(e,r)=>{const{dataType:t,dims:s,download:o,dispose:n}=r;return new Ur({location:"gpu-buffer",type:t??"float32",gpuBuffer:e,dims:s,download:o,dispose:n})},H0=(e,r)=>{const{dataType:t,dims:s,download:o,dispose:n}=r;return new Ur({location:"ml-tensor",type:t??"float32",mlTensor:e,dims:s,download:o,dispose:n})},q0=(e,r,t)=>new Ur({location:"cpu-pinned",type:e,data:r,dims:t??[r.length]}),zn=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),Yo=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);let Td=!1;const X0=()=>{if(!Td){Td=!0;const e=typeof BigInt64Array<"u"&&BigInt64Array.from,r=typeof BigUint64Array<"u"&&BigUint64Array.from,t=globalThis.Float16Array,s=typeof t<"u"&&t.from;e&&(zn.set("int64",BigInt64Array),Yo.set(BigInt64Array,"int64")),r&&(zn.set("uint64",BigUint64Array),Yo.set(BigUint64Array,"uint64")),s?(zn.set("float16",t),Yo.set(t,"float16")):zn.set("float16",Uint16Array)}},Q0=e=>{let r=1;for(let t=0;t{switch(e.location){case"cpu":return new Ur(e.type,e.data,r);case"cpu-pinned":return new Ur({location:"cpu-pinned",data:e.data,type:e.type,dims:r});case"texture":return new Ur({location:"texture",texture:e.texture,type:e.type,dims:r});case"gpu-buffer":return new Ur({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:r});case"ml-tensor":return new Ur({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:r});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}};let Ur=class{constructor(r,t,s){X0();let o,n;if(typeof r=="object"&&"location"in r)switch(this.dataLocation=r.location,o=r.type,n=r.dims,r.location){case"cpu-pinned":{const a=zn.get(o);if(!a)throw new TypeError(`unsupported type "${o}" to create tensor from pinned buffer`);if(!(r.data instanceof a))throw new TypeError(`buffer should be of type ${a.name}`);this.cpuData=r.data;break}case"texture":{if(o!=="float32")throw new TypeError(`unsupported type "${o}" to create tensor from texture`);this.gpuTextureData=r.texture,this.downloader=r.download,this.disposer=r.dispose;break}case"gpu-buffer":{if(o!=="float32"&&o!=="float16"&&o!=="int32"&&o!=="int64"&&o!=="uint32"&&o!=="uint8"&&o!=="bool"&&o!=="uint4"&&o!=="int4")throw new TypeError(`unsupported type "${o}" to create tensor from gpu buffer`);this.gpuBufferData=r.gpuBuffer,this.downloader=r.download,this.disposer=r.dispose;break}case"ml-tensor":{if(o!=="float32"&&o!=="float16"&&o!=="int32"&&o!=="int64"&&o!=="uint32"&&o!=="uint64"&&o!=="int8"&&o!=="uint8"&&o!=="bool"&&o!=="uint4"&&o!=="int4")throw new TypeError(`unsupported type "${o}" to create tensor from MLTensor`);this.mlTensorData=r.mlTensor,this.downloader=r.download,this.disposer=r.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let a,l;if(typeof r=="string")if(o=r,l=s,r==="string"){if(!Array.isArray(t))throw new TypeError("A string tensor's data must be a string array.");a=t}else{const u=zn.get(r);if(u===void 0)throw new TypeError(`Unsupported tensor type: ${r}.`);if(Array.isArray(t)){if(r==="float16"&&u===Uint16Array||r==="uint4"||r==="int4")throw new TypeError(`Creating a ${r} tensor from number array is not supported. Please use ${u.name} as data.`);r==="uint64"||r==="int64"?a=u.from(t,BigInt):a=u.from(t)}else if(t instanceof u)a=t;else if(t instanceof Uint8ClampedArray)if(r==="uint8")a=Uint8Array.from(t);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(r==="float16"&&t instanceof Uint16Array&&u!==Uint16Array)a=new globalThis.Float16Array(t.buffer,t.byteOffset,t.length);else throw new TypeError(`A ${o} tensor's data must be type of ${u}`)}else if(l=t,Array.isArray(r)){if(r.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");const u=typeof r[0];if(u==="string")o="string",a=r;else if(u==="boolean")o="bool",a=Uint8Array.from(r);else throw new TypeError(`Invalid element type of data array: ${u}.`)}else if(r instanceof Uint8ClampedArray)o="uint8",a=Uint8Array.from(r);else{const u=Yo.get(r.constructor);if(u===void 0)throw new TypeError(`Unsupported type for tensor data: ${r.constructor}.`);o=u,a=r}if(l===void 0)l=[a.length];else if(!Array.isArray(l))throw new TypeError("A tensor's dims must be a number array");n=l,this.cpuData=a,this.dataLocation="cpu"}const i=Q0(n);if(this.cpuData&&i!==this.cpuData.length&&!((o==="uint4"||o==="int4")&&Math.ceil(i/2)===this.cpuData.length))throw new Error(`Tensor's size(${i}) does not match data length(${this.cpuData.length}).`);this.type=o,this.dims=n,this.size=i}static async fromImage(r,t){return W0(r,t)}static fromTexture(r,t){return G0(r,t)}static fromGpuBuffer(r,t){return K0(r,t)}static fromMLTensor(r,t){return H0(r,t)}static fromPinnedBuffer(r,t,s){return q0(r,t,s)}toDataURL(r){return V0(this,r)}toImageData(r){return U0(this,r)}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}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(r){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;const t=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=t,r&&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.mlTensorData=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(r){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return J0(this,r)}};const Bn=Ur,Ed=(e,r)=>{(typeof Yr.trace>"u"?!Yr.wasm.trace:!Yr.trace)||console.timeStamp(`${e}::ORT::${r}`)},Pd=(e,r)=>{var o;const t=((o=new Error().stack)==null?void 0:o.split(/\r\n|\r|\n/g))||[];let s=!1;for(let n=0;n{(typeof Yr.trace>"u"?!Yr.wasm.trace:!Yr.trace)||Pd("BEGIN",e)},Ma=e=>{(typeof Yr.trace>"u"?!Yr.wasm.trace:!Yr.trace)||Pd("END",e)};var Y0=Object.freeze({__proto__:null,InferenceSession:class D0{constructor(r){this.handler=r}async run(r,t,s){wa();const o={};let n={};if(typeof r!="object"||r===null||r instanceof Bn||Array.isArray(r))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let i=!0;if(typeof t=="object"){if(t===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(t instanceof Bn)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(t)){if(t.length===0)throw new TypeError("'fetches' cannot be an empty array.");i=!1;for(const u of t){if(typeof u!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(u)===-1)throw new RangeError(`'fetches' contains invalid output name: ${u}.`);o[u]=null}if(typeof s=="object"&&s!==null)n=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else{let u=!1;const p=Object.getOwnPropertyNames(t);for(const d of this.outputNames)if(p.indexOf(d)!==-1){const c=t[d];(c===null||c instanceof Bn)&&(u=!0,i=!1,o[d]=c)}if(u){if(typeof s=="object"&&s!==null)n=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else n=t}}else if(typeof t<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const u of this.inputNames)if(typeof r[u]>"u")throw new Error(`input '${u}' is missing in 'feeds'.`);if(i)for(const u of this.outputNames)o[u]=null;const a=await this.handler.run(r,o,n),l={};for(const u in a)if(Object.hasOwnProperty.call(a,u)){const p=a[u];p instanceof Bn?l[u]=p:l[u]=new Bn(p.type,p.data,p.dims)}return Ma(),l}async release(){return this.handler.dispose()}static async create(r,t,s,o){wa();let n,i={};if(typeof r=="string"){if(n=r,typeof t=="object"&&t!==null)i=t;else if(typeof t<"u")throw new TypeError("'options' must be an object.")}else if(r instanceof Uint8Array){if(n=r,typeof t=="object"&&t!==null)i=t;else if(typeof t<"u")throw new TypeError("'options' must be an object.")}else if(r instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&r instanceof SharedArrayBuffer){const p=r;let d=0,c=r.byteLength;if(typeof t=="object"&&t!==null)i=t;else if(typeof t=="number"){if(d=t,!Number.isSafeInteger(d))throw new RangeError("'byteOffset' must be an integer.");if(d<0||d>=p.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${p.byteLength}).`);if(c=r.byteLength-d,typeof s=="number"){if(c=s,!Number.isSafeInteger(c))throw new RangeError("'byteLength' must be an integer.");if(c<=0||d+c>p.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${p.byteLength-d}].`);if(typeof o=="object"&&o!==null)i=o;else if(typeof o<"u")throw new TypeError("'options' must be an object.")}else if(typeof s<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof t<"u")throw new TypeError("'options' must be an object.");n=new Uint8Array(p,d,c)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");const[a,l]=await R0(i),u=await a.createInferenceSessionHandler(n,l);return Ma(),new D0(u)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}},TRACE:Ed,TRACE_FUNC_BEGIN:wa,TRACE_FUNC_END:Ma,Tensor:Bn,env:N0,registerBackend:Ln});/*! + * ONNX Runtime Web v1.22.0-dev.20250409-89f8206ba4 + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */var ba=Object.defineProperty,Z0=Object.getOwnPropertyDescriptor,ev=Object.getOwnPropertyNames,tv=Object.prototype.hasOwnProperty,rv=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(r,t)=>(typeof require<"u"?require:r)[t]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),Be=(e,r)=>()=>(e&&(r=e(e=0)),r),Rn=(e,r)=>{for(var t in r)ba(e,t,{get:r[t],enumerable:!0})},sv=(e,r,t,s)=>{if(r&&typeof r=="object"||typeof r=="function")for(let o of ev(r))!tv.call(e,o)&&o!==t&&ba(e,o,{get:()=>r[o],enumerable:!(s=Z0(r,o))||s.enumerable});return e},io=e=>sv(ba({},"__esModule",{value:!0}),e),ao,Ds,Ys,Cd,Sd,$d=Be(()=>{ao=new Map,Ds=[],Ys=(e,r,t)=>{if(r&&typeof r.init=="function"&&typeof r.createInferenceSessionHandler=="function"){let s=ao.get(e);if(s===void 0)ao.set(e,{backend:r,priority:t});else{if(s.priority>t)return;if(s.priority===t&&s.backend!==r)throw new Error(`cannot register backend "${e}" using priority ${t}`)}if(t>=0){let o=Ds.indexOf(e);o!==-1&&Ds.splice(o,1);for(let n=0;n{let r=ao.get(e);if(!r)return"backend not found.";if(r.initialized)return r.backend;if(r.aborted)return r.error;{let t=!!r.initPromise;try{return t||(r.initPromise=r.backend.init(e)),await r.initPromise,r.initialized=!0,r.backend}catch(s){return t||(r.error=`${s}`,r.aborted=!0),r.error}finally{delete r.initPromise}}},Sd=async e=>{let r=e.executionProviders||[],t=r.map(l=>typeof l=="string"?l:l.name),s=t.length===0?Ds:t,o,n=[],i=new Set;for(let l of s){let u=await Cd(l);typeof u=="string"?n.push({name:l,err:u}):(o||(o=u),o===u&&i.add(l))}if(!o)throw new Error(`no available backend found. ERR: ${n.map(l=>`[${l.name}] ${l.err}`).join(", ")}`);for(let{name:l,err:u}of n)t.includes(l)&&console.warn(`removing requested execution provider "${l}" from session options because it is not available: ${u}`);let a=r.filter(l=>i.has(typeof l=="string"?l:l.name));return[o,new Proxy(e,{get:(l,u)=>u==="executionProviders"?a:Reflect.get(l,u)})]}}),nv=Be(()=>{$d()}),kd,ov=Be(()=>{kd="1.22.0-dev.20250409-89f8206ba4"}),ya,Wr,Id=Be(()=>{ov(),ya="warning",Wr={wasm:{},webgl:{},webgpu:{},versions:{common:kd},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}`);ya=e}},get logLevel(){return ya}},Object.defineProperty(Wr,"logLevel",{enumerable:!0})}),Bt,iv=Be(()=>{Id(),Bt=Wr}),Ad,Fd,av=Be(()=>{Ad=(e,r)=>{let t=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);t.width=e.dims[3],t.height=e.dims[2];let s=t.getContext("2d");if(s!=null){let o,n;(r==null?void 0:r.tensorLayout)!==void 0&&r.tensorLayout==="NHWC"?(o=e.dims[2],n=e.dims[3]):(o=e.dims[3],n=e.dims[2]);let i=(r==null?void 0:r.format)!==void 0?r.format:"RGB",a=r==null?void 0:r.norm,l,u;a===void 0||a.mean===void 0?l=[255,255,255,255]:typeof a.mean=="number"?l=[a.mean,a.mean,a.mean,a.mean]:(l=[a.mean[0],a.mean[1],a.mean[2],0],a.mean[3]!==void 0&&(l[3]=a.mean[3])),a===void 0||a.bias===void 0?u=[0,0,0,0]:typeof a.bias=="number"?u=[a.bias,a.bias,a.bias,a.bias]:(u=[a.bias[0],a.bias[1],a.bias[2],0],a.bias[3]!==void 0&&(u[3]=a.bias[3]));let p=n*o,d=0,c=p,f=p*2,_=-1;i==="RGBA"?(d=0,c=p,f=p*2,_=p*3):i==="RGB"?(d=0,c=p,f=p*2):i==="RBG"&&(d=0,f=p,c=p*2);for(let T=0;T{let t=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),s;if(t!=null){let o,n,i;(r==null?void 0:r.tensorLayout)!==void 0&&r.tensorLayout==="NHWC"?(o=e.dims[2],n=e.dims[1],i=e.dims[3]):(o=e.dims[3],n=e.dims[2],i=e.dims[1]);let a=r!==void 0&&r.format!==void 0?r.format:"RGB",l=r==null?void 0:r.norm,u,p;l===void 0||l.mean===void 0?u=[255,255,255,255]:typeof l.mean=="number"?u=[l.mean,l.mean,l.mean,l.mean]:(u=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(u[3]=l.mean[3])),l===void 0||l.bias===void 0?p=[0,0,0,0]:typeof l.bias=="number"?p=[l.bias,l.bias,l.bias,l.bias]:(p=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(p[3]=l.bias[3]));let d=n*o;if(r!==void 0&&(r.format!==void 0&&i===4&&r.format!=="RGBA"||i===3&&r.format!=="RGB"&&r.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let c=4,f=0,_=1,T=2,k=3,w=0,g=d,S=d*2,E=-1;a==="RGBA"?(w=0,g=d,S=d*2,E=d*3):a==="RGB"?(w=0,g=d,S=d*2):a==="RBG"&&(w=0,S=d,g=d*2),s=t.createImageData(o,n);for(let y=0;y{xa(),Zo=(e,r)=>{if(e===void 0)throw new Error("Image buffer must be defined");if(r.height===void 0||r.width===void 0)throw new Error("Image height and width must be defined");if(r.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:t,width:s}=r,o=r.norm??{mean:255,bias:0},n,i;typeof o.mean=="number"?n=[o.mean,o.mean,o.mean,o.mean]:n=[o.mean[0],o.mean[1],o.mean[2],o.mean[3]??255],typeof o.bias=="number"?i=[o.bias,o.bias,o.bias,o.bias]:i=[o.bias[0],o.bias[1],o.bias[2],o.bias[3]??0];let a=r.format!==void 0?r.format:"RGBA",l=r.tensorFormat!==void 0&&r.tensorFormat!==void 0?r.tensorFormat:"RGB",u=t*s,p=l==="RGBA"?new Float32Array(u*4):new Float32Array(u*3),d=4,c=0,f=1,_=2,T=3,k=0,w=u,g=u*2,S=-1;a==="RGB"&&(d=3,c=0,f=1,_=2,T=-1),l==="RGBA"?S=u*3:l==="RBG"?(k=0,g=u,w=u*2):l==="BGR"&&(g=0,w=u,k=u*2);for(let E=0;E{let t=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,s=typeof ImageData<"u"&&e instanceof ImageData,o=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,n=typeof e=="string",i,a=r??{},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")},u=p=>typeof HTMLCanvasElement<"u"&&p instanceof HTMLCanvasElement||p instanceof OffscreenCanvas?p.getContext("2d"):null;if(t){let p=l();p.width=e.width,p.height=e.height;let d=u(p);if(d!=null){let c=e.height,f=e.width;if(r!==void 0&&r.resizedHeight!==void 0&&r.resizedWidth!==void 0&&(c=r.resizedHeight,f=r.resizedWidth),r!==void 0){if(a=r,r.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");a.tensorFormat="RGBA",a.height=c,a.width=f}else a.tensorFormat="RGBA",a.height=c,a.width=f;d.drawImage(e,0,0),i=d.getImageData(0,0,f,c).data}else throw new Error("Can not access image data")}else if(s){let p,d;if(r!==void 0&&r.resizedWidth!==void 0&&r.resizedHeight!==void 0?(p=r.resizedHeight,d=r.resizedWidth):(p=e.height,d=e.width),r!==void 0&&(a=r),a.format="RGBA",a.height=p,a.width=d,r!==void 0){let c=l();c.width=d,c.height=p;let f=u(c);if(f!=null)f.putImageData(e,0,0),i=f.getImageData(0,0,d,p).data;else throw new Error("Can not access image data")}else i=e.data}else if(o){if(r===void 0)throw new Error("Please provide image config with format for Imagebitmap");let p=l();p.width=e.width,p.height=e.height;let d=u(p);if(d!=null){let c=e.height,f=e.width;return d.drawImage(e,0,0,f,c),i=d.getImageData(0,0,f,c).data,a.height=c,a.width=f,Zo(i,a)}else throw new Error("Can not access image data")}else{if(n)return new Promise((p,d)=>{let c=l(),f=u(c);if(!e||!f)return d();let _=new Image;_.crossOrigin="Anonymous",_.src=e,_.onload=()=>{c.width=_.width,c.height=_.height,f.drawImage(_,0,0,c.width,c.height);let T=f.getImageData(0,0,c.width,c.height);a.height=c.height,a.width=c.width,p(Zo(T.data,a))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(i!==void 0)return Zo(i,a);throw new Error("Input data provided is not supported - aborted tensor creation")},Dd=(e,r)=>{let{width:t,height:s,download:o,dispose:n}=r,i=[1,s,t,4];return new Or({location:"texture",type:"float32",texture:e,dims:i,download:o,dispose:n})},Ld=(e,r)=>{let{dataType:t,dims:s,download:o,dispose:n}=r;return new Or({location:"gpu-buffer",type:t??"float32",gpuBuffer:e,dims:s,download:o,dispose:n})},zd=(e,r)=>{let{dataType:t,dims:s,download:o,dispose:n}=r;return new Or({location:"ml-tensor",type:t??"float32",mlTensor:e,dims:s,download:o,dispose:n})},Bd=(e,r,t)=>new Or({location:"cpu-pinned",type:e,data:r,dims:t??[r.length]})}),Zs,lo,va,Rd,uv=Be(()=>{Zs=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),lo=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),va=!1,Rd=()=>{if(!va){va=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,r=typeof BigUint64Array<"u"&&BigUint64Array.from,t=globalThis.Float16Array,s=typeof t<"u"&&t.from;e&&(Zs.set("int64",BigInt64Array),lo.set(BigInt64Array,"int64")),r&&(Zs.set("uint64",BigUint64Array),lo.set(BigUint64Array,"uint64")),s?(Zs.set("float16",t),lo.set(t,"float16")):Zs.set("float16",Uint16Array)}}}),jd,Nd,dv=Be(()=>{xa(),jd=e=>{let r=1;for(let t=0;t{switch(e.location){case"cpu":return new Or(e.type,e.data,r);case"cpu-pinned":return new Or({location:"cpu-pinned",data:e.data,type:e.type,dims:r});case"texture":return new Or({location:"texture",texture:e.texture,type:e.type,dims:r});case"gpu-buffer":return new Or({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:r});case"ml-tensor":return new Or({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:r});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),Or,xa=Be(()=>{av(),lv(),uv(),dv(),Or=class{constructor(e,r,t){Rd();let s,o;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,s=e.type,o=e.dims,e.location){case"cpu-pinned":{let i=Zs.get(s);if(!i)throw new TypeError(`unsupported type "${s}" to create tensor from pinned buffer`);if(!(e.data instanceof i))throw new TypeError(`buffer should be of type ${i.name}`);this.cpuData=e.data;break}case"texture":{if(s!=="float32")throw new TypeError(`unsupported type "${s}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break}case"gpu-buffer":{if(s!=="float32"&&s!=="float16"&&s!=="int32"&&s!=="int64"&&s!=="uint32"&&s!=="uint8"&&s!=="bool"&&s!=="uint4"&&s!=="int4")throw new TypeError(`unsupported type "${s}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break}case"ml-tensor":{if(s!=="float32"&&s!=="float16"&&s!=="int32"&&s!=="int64"&&s!=="uint32"&&s!=="uint64"&&s!=="int8"&&s!=="uint8"&&s!=="bool"&&s!=="uint4"&&s!=="int4")throw new TypeError(`unsupported type "${s}" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let i,a;if(typeof e=="string")if(s=e,a=t,e==="string"){if(!Array.isArray(r))throw new TypeError("A string tensor's data must be a string array.");i=r}else{let l=Zs.get(e);if(l===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(r)){if(e==="float16"&&l===Uint16Array||e==="uint4"||e==="int4")throw new TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${l.name} as data.`);e==="uint64"||e==="int64"?i=l.from(r,BigInt):i=l.from(r)}else if(r instanceof l)i=r;else if(r instanceof Uint8ClampedArray)if(e==="uint8")i=Uint8Array.from(r);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(e==="float16"&&r instanceof Uint16Array&&l!==Uint16Array)i=new globalThis.Float16Array(r.buffer,r.byteOffset,r.length);else throw new TypeError(`A ${s} tensor's data must be type of ${l}`)}else if(a=r,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")s="string",i=e;else if(l==="boolean")s="bool",i=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${l}.`)}else if(e instanceof Uint8ClampedArray)s="uint8",i=Uint8Array.from(e);else{let l=lo.get(e.constructor);if(l===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);s=l,i=e}if(a===void 0)a=[i.length];else if(!Array.isArray(a))throw new TypeError("A tensor's dims must be a number array");o=a,this.cpuData=i,this.dataLocation="cpu"}let n=jd(o);if(this.cpuData&&n!==this.cpuData.length&&!((s==="uint4"||s==="int4")&&Math.ceil(n/2)===this.cpuData.length))throw new Error(`Tensor's size(${n}) does not match data length(${this.cpuData.length}).`);this.type=s,this.dims=o,this.size=n}static async fromImage(e,r){return Od(e,r)}static fromTexture(e,r){return Dd(e,r)}static fromGpuBuffer(e,r){return Ld(e,r)}static fromMLTensor(e,r){return zd(e,r)}static fromPinnedBuffer(e,r,t){return Bd(e,r,t)}toDataURL(e){return Ad(this,e)}toImageData(e){return Fd(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}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(e){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{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 r=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=r,e&&this.disposer&&(this.disposer(),this.disposer=void 0),r}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.mlTensorData=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 Nd(this,e)}}}),Zr,Vd=Be(()=>{xa(),Zr=Or}),uo,Ta,es,Gr,Ud=Be(()=>{Id(),uo=(e,r)=>{(typeof Wr.trace>"u"?!Wr.wasm.trace:!Wr.trace)||console.timeStamp(`${e}::ORT::${r}`)},Ta=(e,r)=>{var o;let t=((o=new Error().stack)==null?void 0:o.split(/\r\n|\r|\n/g))||[],s=!1;for(let n=0;n{(typeof Wr.trace>"u"?!Wr.wasm.trace:!Wr.trace)||Ta("BEGIN",e)},Gr=e=>{(typeof Wr.trace>"u"?!Wr.wasm.trace:!Wr.trace)||Ta("END",e)}}),Wd,cv=Be(()=>{$d(),Vd(),Ud(),Wd=class L0{constructor(r){this.handler=r}async run(r,t,s){es();let o={},n={};if(typeof r!="object"||r===null||r instanceof Zr||Array.isArray(r))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let i=!0;if(typeof t=="object"){if(t===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(t instanceof Zr)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(t)){if(t.length===0)throw new TypeError("'fetches' cannot be an empty array.");i=!1;for(let u of t){if(typeof u!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(u)===-1)throw new RangeError(`'fetches' contains invalid output name: ${u}.`);o[u]=null}if(typeof s=="object"&&s!==null)n=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else{let u=!1,p=Object.getOwnPropertyNames(t);for(let d of this.outputNames)if(p.indexOf(d)!==-1){let c=t[d];(c===null||c instanceof Zr)&&(u=!0,i=!1,o[d]=c)}if(u){if(typeof s=="object"&&s!==null)n=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else n=t}}else if(typeof t<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let u of this.inputNames)if(typeof r[u]>"u")throw new Error(`input '${u}' is missing in 'feeds'.`);if(i)for(let u of this.outputNames)o[u]=null;let a=await this.handler.run(r,o,n),l={};for(let u in a)if(Object.hasOwnProperty.call(a,u)){let p=a[u];p instanceof Zr?l[u]=p:l[u]=new Zr(p.type,p.data,p.dims)}return Gr(),l}async release(){return this.handler.dispose()}static async create(r,t,s,o){es();let n,i={};if(typeof r=="string"){if(n=r,typeof t=="object"&&t!==null)i=t;else if(typeof t<"u")throw new TypeError("'options' must be an object.")}else if(r instanceof Uint8Array){if(n=r,typeof t=="object"&&t!==null)i=t;else if(typeof t<"u")throw new TypeError("'options' must be an object.")}else if(r instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&r instanceof SharedArrayBuffer){let p=r,d=0,c=r.byteLength;if(typeof t=="object"&&t!==null)i=t;else if(typeof t=="number"){if(d=t,!Number.isSafeInteger(d))throw new RangeError("'byteOffset' must be an integer.");if(d<0||d>=p.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${p.byteLength}).`);if(c=r.byteLength-d,typeof s=="number"){if(c=s,!Number.isSafeInteger(c))throw new RangeError("'byteLength' must be an integer.");if(c<=0||d+c>p.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${p.byteLength-d}].`);if(typeof o=="object"&&o!==null)i=o;else if(typeof o<"u")throw new TypeError("'options' must be an object.")}else if(typeof s<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof t<"u")throw new TypeError("'options' must be an object.");n=new Uint8Array(p,d,c)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[a,l]=await Sd(i),u=await a.createInferenceSessionHandler(n,l);return Gr(),new L0(u)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}get inputMetadata(){return this.handler.inputMetadata}get outputMetadata(){return this.handler.outputMetadata}}}),Ea,pv=Be(()=>{cv(),Ea=Wd}),hv=Be(()=>{}),mv=Be(()=>{}),_v=Be(()=>{}),fv=Be(()=>{}),Gd={};Rn(Gd,{InferenceSession:()=>Ea,TRACE:()=>uo,TRACE_FUNC_BEGIN:()=>es,TRACE_FUNC_END:()=>Gr,Tensor:()=>Zr,env:()=>Bt,registerBackend:()=>Ys});var ts=Be(()=>{nv(),iv(),pv(),Vd(),hv(),mv(),Ud(),_v(),fv()}),Pa=Be(()=>{}),Kd={};Rn(Kd,{default:()=>Hd});var Ca,Sa,Hd,gv=Be(()=>{var e;Cg(),en(),La(),Ca="ort-wasm-proxy-worker",Sa=((e=globalThis.self)==null?void 0:e.name)===Ca,Sa&&(self.onmessage=r=>{let{type:t,in:s}=r.data;try{switch(t){case"init-wasm":Ra(s.wasm).then(()=>{Yl(s).then(()=>{postMessage({type:t})},o=>{postMessage({type:t,err:o})})},o=>{postMessage({type:t,err:o})});break;case"init-ep":{let{epName:o,env:n}=s;Zl(n,o).then(()=>{postMessage({type:t})},i=>{postMessage({type:t,err:i})});break}case"copy-from":{let{buffer:o}=s,n=wi(o);postMessage({type:t,out:n});break}case"create":{let{model:o,options:n}=s;tu(o,n).then(i=>{postMessage({type:t,out:i})},i=>{postMessage({type:t,err:i})});break}case"release":ru(s),postMessage({type:t});break;case"run":{let{sessionId:o,inputIndices:n,inputs:i,outputIndices:a,options:l}=s;nu(o,n,i,a,new Array(a.length).fill(null),l).then(u=>{u.some(p=>p[3]!=="cpu")?postMessage({type:t,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:t,out:u},iu([...i,...u]))},u=>{postMessage({type:t,err:u})});break}case"end-profiling":ou(s),postMessage({type:t});break;default:}}catch(o){postMessage({type:t,err:o})}}),Hd=Sa?null:r=>new Worker(r??Dr,{type:"module",name:Ca})}),qd={};Rn(qd,{default:()=>Xd});var $a,ka,Xd,Qd,wv=Be(()=>{var e,r;ka=($a=self.location.href,async function(t={}){var Xo;var s,o,n=t,i=new Promise((h,x)=>{s=h,o=x}),a=typeof window=="object",l=typeof WorkerGlobalScope<"u",u=l&&((Xo=self.name)==null?void 0:Xo.startsWith("em-pthread"));n.mountExternalData=(h,x)=>{h.startsWith("./")&&(h=h.substring(2)),(n.Eb||(n.Eb=new Map)).set(h,x)},n.unmountExternalData=()=>{delete n.Eb};var p=globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,pc:!0}).buffer.constructor;let d=h=>async(...x)=>{var I;try{if(n.Fb)throw Error("Session already started");let L=n.Fb={dc:x[0],errors:[]},U=await h(...x);if(n.Fb!==L)throw Error("Session mismatch");(I=n.Jb)==null||I.flush();let ue=L.errors;if(0Oe),0{if(h==="webgpu"){[n.Jb,n.Ub,n.Yb,n.Kb,n.Xb,n.jb,n.Zb,n.ac,n.Vb,n.Wb,n.$b]=x;let I=n.Jb;n.jsepRegisterBuffer=(L,U,ue,Te)=>I.registerBuffer(L,U,ue,Te),n.jsepGetBuffer=L=>I.getBuffer(L),n.jsepCreateDownloader=(L,U,ue)=>I.createDownloader(L,U,ue),n.jsepOnCreateSession=L=>{I.onCreateSession(L)},n.jsepOnReleaseSession=L=>{I.onReleaseSession(L)},n.jsepOnRunStart=L=>I.onRunStart(L),n.bc=(L,U)=>{I.upload(L,U)}}else if(h==="webnn"){let I=x[0];[n.nc,n.Nb,n.webnnEnsureTensor,n.Ob,n.webnnDownloadTensor]=x.slice(1),n.webnnReleaseTensorId=n.Nb,n.webnnUploadTensor=n.Ob,n.webnnOnRunStart=L=>I.onRunStart(L),n.webnnOnRunEnd=I.onRunEnd.bind(I),n.webnnRegisterMLContext=(L,U)=>{I.registerMLContext(L,U)},n.webnnOnReleaseSession=L=>{I.onReleaseSession(L)},n.webnnCreateMLTensorDownloader=(L,U)=>I.createMLTensorDownloader(L,U),n.webnnRegisterMLTensor=(L,U,ue,Te)=>I.registerMLTensor(L,U,ue,Te),n.webnnCreateMLContext=L=>I.createMLContext(L),n.webnnRegisterMLConstant=(L,U,ue,Te,Oe,Ke)=>I.registerMLConstant(L,U,ue,Te,Oe,n.Eb,Ke),n.webnnRegisterGraphInput=I.registerGraphInput.bind(I),n.webnnIsGraphInput=I.isGraphInput.bind(I),n.webnnCreateTemporaryTensor=I.createTemporaryTensor.bind(I),n.webnnIsInt64Supported=I.isInt64Supported.bind(I)}};let c=()=>{let h=(x,I,L)=>(...U)=>{let ue=Nt,Te=I==null?void 0:I();U=x(...U);let Oe=I==null?void 0:I();return Te!==Oe&&(x=Oe,L(Te),I=L=null),Nt!=ue?new Promise((Ke,Ze)=>{Rr={resolve:Ke,reject:Ze}}):U};(()=>{for(let x of["_OrtAppendExecutionProvider","_OrtCreateSession","_OrtRun","_OrtRunWithBinding","_OrtBindInput"])n[x]=h(n[x],()=>n[x],I=>n[x]=I)})(),d!==void 0&&(n._OrtRun=d(n._OrtRun),n._OrtRunWithBinding=d(n._OrtRunWithBinding)),c=void 0};n.asyncInit=()=>{c==null||c()};var f,_,T=Object.assign({},n),k=(h,x)=>{throw x},w="";(a||l)&&(l?w=self.location.href:typeof document<"u"&&document.currentScript&&(w=document.currentScript.src),$a&&(w=$a),w=w.startsWith("blob:")?"":w.slice(0,w.replace(/[?#].*/,"").lastIndexOf("/")+1),l&&(_=h=>{var x=new XMLHttpRequest;return x.open("GET",h,!1),x.responseType="arraybuffer",x.send(null),new Uint8Array(x.response)}),f=async h=>{if(V(h))return new Promise((I,L)=>{var U=new XMLHttpRequest;U.open("GET",h,!0),U.responseType="arraybuffer",U.onload=()=>{U.status==200||U.status==0&&U.response?I(U.response):L(U.status)},U.onerror=L,U.send(null)});var x=await fetch(h,{credentials:"same-origin"});if(x.ok)return x.arrayBuffer();throw Error(x.status+" : "+x.url)});var g=console.log.bind(console),S=console.error.bind(console),E=g,y=S;Object.assign(n,T),T=null;var M,v,C,A,B,K,G,j,ee,H,Z,X,oe,me=n.wasmBinary,ae=!1,V=h=>h.startsWith("file://");function F(){return M.buffer!=A.buffer&&R(),A}function W(){return M.buffer!=A.buffer&&R(),B}function re(){return M.buffer!=A.buffer&&R(),K}function _e(){return M.buffer!=A.buffer&&R(),G}function se(){return M.buffer!=A.buffer&&R(),j}function ce(){return M.buffer!=A.buffer&&R(),ee}function $e(){return M.buffer!=A.buffer&&R(),H}function Ue(){return M.buffer!=A.buffer&&R(),oe}if(u){let h=function(x){try{var I=x.data,L=I.Bb;if(L==="load"){let U=[];self.onmessage=ue=>U.push(ue),self.startWorker=()=>{postMessage({Bb:"loaded"});for(let ue of U)h(ue);self.onmessage=h};for(let ue of I.Rb)n[ue]&&!n[ue].proxy||(n[ue]=(...Te)=>{postMessage({Bb:"callHandler",Qb:ue,args:Te})},ue=="print"&&(E=n[ue]),ue=="printErr"&&(y=n[ue]));M=I.kc,R(),we(I.lc)}else if(L==="run"){Ir(I.Ab),Sn(I.Ab,0,0,1,0,0),ur(),ve(I.Ab),q||(No(),q=!0);try{js(I.fc,I.Hb)}catch(U){if(U!="unwind")throw U}}else I.target!=="setimmediate"&&(L==="checkMailbox"?q&&je():L&&(y(`worker: received unknown command ${L}`),y(I)))}catch(U){throw Vo(),U}};var we,q=!1;y=function(...x){x=x.join(" "),console.error(x)},self.alert=function(...x){postMessage({Bb:"alert",text:x.join(" "),ic:Xs()})},self.onunhandledrejection=x=>{throw x.reason||x},self.onmessage=h}function R(){var h=M.buffer;n.HEAP8=A=new Int8Array(h),n.HEAP16=K=new Int16Array(h),n.HEAPU8=B=new Uint8Array(h),n.HEAPU16=G=new Uint16Array(h),n.HEAP32=j=new Int32Array(h),n.HEAPU32=ee=new Uint32Array(h),n.HEAPF32=H=new Float32Array(h),n.HEAPF64=oe=new Float64Array(h),n.HEAP64=Z=new BigInt64Array(h),n.HEAPU64=X=new BigUint64Array(h)}function pe(){u?startWorker(n):nt.Ca()}u||(M=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),R());var xe,be=0,Se=null;function Ae(){if(--be==0&&Se){var h=Se;Se=null,h()}}function Fe(h){throw y(h="Aborted("+h+")"),ae=!0,h=new WebAssembly.RuntimeError(h+". Build with -sASSERTIONS for more info."),o(h),h}function ze(){return{a:{L:Y,Aa:O,b:Ns,$:us,A:ds,pa:cs,X:De,Z:Qe,qa:tt,na:Rt,ga:zr,ma:Sr,J:ps,Y:hs,V:Kr,oa:ms,W:_s,va:cn,E:pn,Q:hn,O:_n,D:gn,u:wn,r:vs,P:Mn,z:N,R:Q,ja:ie,T:He,aa:Je,M:dt,F:xt,ia:ve,sa:Pt,t:Ht,Ba:br,w:or,o:Zt,l:Ws,c:Is,n:vi,j:Ei,v:Pi,p:Ci,f:Si,s:$i,m:To,e:ki,k:Ii,i:Eo,g:Ai,d:Po,da:Fi,ea:So,fa:Di,ba:Tn,ca:$o,N:ko,xa:zi,ua:Ri,h:ji,C:Io,G:Fs,ta:Bi,x:Ni,ra:pu,U:Vi,q:Li,y:hu,K:Ui,S:Ao,za:Wi,ya:Gi,ka:Do,la:qn,_:Xe,B:Lo,I:zo,ha:Xn,H:Bo,a:M,wa:Ie}}}var Ve={829644:(h,x,I,L,U)=>{if(n===void 0||!n.Eb)return 1;if((h=Ft(Number(h>>>0))).startsWith("./")&&(h=h.substring(2)),!(h=n.Eb.get(h)))return 2;if(x=Number(x>>>0),I=Number(I>>>0),L=Number(L>>>0),x+I>h.byteLength)return 3;try{let ue=h.subarray(x,x+I);switch(U){case 0:W().set(ue,L>>>0);break;case 1:n.mc?n.mc(L,ue):n.bc(L,ue);break;default:return 4}return 0}catch{return 4}},830468:(h,x,I)=>{n.Ob(h,W().subarray(x>>>0,x+I>>>0))},830532:()=>n.nc(),830574:h=>{n.Nb(h)},830611:()=>{n.Vb()},830642:()=>{n.Wb()},830671:()=>{n.$b()},830696:h=>n.Ub(h),830729:h=>n.Yb(h),830761:(h,x,I)=>{n.Kb(Number(h),Number(x),Number(I),!0)},830824:(h,x,I)=>{n.Kb(Number(h),Number(x),Number(I))},830881:()=>typeof wasmOffsetConverter<"u",830938:h=>{n.jb("Abs",h,void 0)},830989:h=>{n.jb("Neg",h,void 0)},831040:h=>{n.jb("Floor",h,void 0)},831093:h=>{n.jb("Ceil",h,void 0)},831145:h=>{n.jb("Reciprocal",h,void 0)},831203:h=>{n.jb("Sqrt",h,void 0)},831255:h=>{n.jb("Exp",h,void 0)},831306:h=>{n.jb("Erf",h,void 0)},831357:h=>{n.jb("Sigmoid",h,void 0)},831412:(h,x,I)=>{n.jb("HardSigmoid",h,{alpha:x,beta:I})},831491:h=>{n.jb("Log",h,void 0)},831542:h=>{n.jb("Sin",h,void 0)},831593:h=>{n.jb("Cos",h,void 0)},831644:h=>{n.jb("Tan",h,void 0)},831695:h=>{n.jb("Asin",h,void 0)},831747:h=>{n.jb("Acos",h,void 0)},831799:h=>{n.jb("Atan",h,void 0)},831851:h=>{n.jb("Sinh",h,void 0)},831903:h=>{n.jb("Cosh",h,void 0)},831955:h=>{n.jb("Asinh",h,void 0)},832008:h=>{n.jb("Acosh",h,void 0)},832061:h=>{n.jb("Atanh",h,void 0)},832114:h=>{n.jb("Tanh",h,void 0)},832166:h=>{n.jb("Not",h,void 0)},832217:(h,x,I)=>{n.jb("Clip",h,{min:x,max:I})},832286:h=>{n.jb("Clip",h,void 0)},832338:(h,x)=>{n.jb("Elu",h,{alpha:x})},832396:h=>{n.jb("Gelu",h,void 0)},832448:h=>{n.jb("Relu",h,void 0)},832500:(h,x)=>{n.jb("LeakyRelu",h,{alpha:x})},832564:(h,x)=>{n.jb("ThresholdedRelu",h,{alpha:x})},832634:(h,x)=>{n.jb("Cast",h,{to:x})},832692:h=>{n.jb("Add",h,void 0)},832743:h=>{n.jb("Sub",h,void 0)},832794:h=>{n.jb("Mul",h,void 0)},832845:h=>{n.jb("Div",h,void 0)},832896:h=>{n.jb("Pow",h,void 0)},832947:h=>{n.jb("Equal",h,void 0)},833e3:h=>{n.jb("Greater",h,void 0)},833055:h=>{n.jb("GreaterOrEqual",h,void 0)},833117:h=>{n.jb("Less",h,void 0)},833169:h=>{n.jb("LessOrEqual",h,void 0)},833228:(h,x,I,L,U)=>{n.jb("ReduceMean",h,{keepDims:!!x,noopWithEmptyAxes:!!I,axes:L?Array.from(se().subarray(Number(L)>>>0,Number(U)>>>0)):[]})},833403:(h,x,I,L,U)=>{n.jb("ReduceMax",h,{keepDims:!!x,noopWithEmptyAxes:!!I,axes:L?Array.from(se().subarray(Number(L)>>>0,Number(U)>>>0)):[]})},833577:(h,x,I,L,U)=>{n.jb("ReduceMin",h,{keepDims:!!x,noopWithEmptyAxes:!!I,axes:L?Array.from(se().subarray(Number(L)>>>0,Number(U)>>>0)):[]})},833751:(h,x,I,L,U)=>{n.jb("ReduceProd",h,{keepDims:!!x,noopWithEmptyAxes:!!I,axes:L?Array.from(se().subarray(Number(L)>>>0,Number(U)>>>0)):[]})},833926:(h,x,I,L,U)=>{n.jb("ReduceSum",h,{keepDims:!!x,noopWithEmptyAxes:!!I,axes:L?Array.from(se().subarray(Number(L)>>>0,Number(U)>>>0)):[]})},834100:(h,x,I,L,U)=>{n.jb("ReduceL1",h,{keepDims:!!x,noopWithEmptyAxes:!!I,axes:L?Array.from(se().subarray(Number(L)>>>0,Number(U)>>>0)):[]})},834273:(h,x,I,L,U)=>{n.jb("ReduceL2",h,{keepDims:!!x,noopWithEmptyAxes:!!I,axes:L?Array.from(se().subarray(Number(L)>>>0,Number(U)>>>0)):[]})},834446:(h,x,I,L,U)=>{n.jb("ReduceLogSum",h,{keepDims:!!x,noopWithEmptyAxes:!!I,axes:L?Array.from(se().subarray(Number(L)>>>0,Number(U)>>>0)):[]})},834623:(h,x,I,L,U)=>{n.jb("ReduceSumSquare",h,{keepDims:!!x,noopWithEmptyAxes:!!I,axes:L?Array.from(se().subarray(Number(L)>>>0,Number(U)>>>0)):[]})},834803:(h,x,I,L,U)=>{n.jb("ReduceLogSumExp",h,{keepDims:!!x,noopWithEmptyAxes:!!I,axes:L?Array.from(se().subarray(Number(L)>>>0,Number(U)>>>0)):[]})},834983:h=>{n.jb("Where",h,void 0)},835036:(h,x,I)=>{n.jb("Transpose",h,{perm:x?Array.from(se().subarray(Number(x)>>>0,Number(I)>>>0)):[]})},835160:(h,x,I,L)=>{n.jb("DepthToSpace",h,{blocksize:x,mode:Ft(I),format:L?"NHWC":"NCHW"})},835293:(h,x,I,L)=>{n.jb("DepthToSpace",h,{blocksize:x,mode:Ft(I),format:L?"NHWC":"NCHW"})},835426:(h,x,I,L,U,ue,Te,Oe,Ke,Ze,ht,Tt,It,sr,Os)=>{n.jb("ConvTranspose",h,{format:Ke?"NHWC":"NCHW",autoPad:x,dilations:[I],group:L,kernelShape:[U],pads:[ue,Te],strides:[Oe],wIsConst:()=>!!F()[Ze>>>0],outputPadding:ht?Array.from(se().subarray(Number(ht)>>>0,Number(Tt)>>>0)):[],outputShape:It?Array.from(se().subarray(Number(It)>>>0,Number(sr)>>>0)):[],activation:Ft(Os)})},835859:(h,x,I,L,U,ue,Te,Oe,Ke,Ze,ht,Tt,It,sr)=>{n.jb("ConvTranspose",h,{format:Oe?"NHWC":"NCHW",autoPad:x,dilations:Array.from(se().subarray(Number(I)>>>0,2+(Number(I)>>>0)>>>0)),group:L,kernelShape:Array.from(se().subarray(Number(U)>>>0,2+(Number(U)>>>0)>>>0)),pads:Array.from(se().subarray(Number(ue)>>>0,4+(Number(ue)>>>0)>>>0)),strides:Array.from(se().subarray(Number(Te)>>>0,2+(Number(Te)>>>0)>>>0)),wIsConst:()=>!!F()[Ke>>>0],outputPadding:Ze?Array.from(se().subarray(Number(Ze)>>>0,Number(ht)>>>0)):[],outputShape:Tt?Array.from(se().subarray(Number(Tt)>>>0,Number(It)>>>0)):[],activation:Ft(sr)})},836520:(h,x,I,L,U,ue,Te,Oe,Ke,Ze,ht,Tt,It,sr,Os)=>{n.jb("ConvTranspose",h,{format:Ke?"NHWC":"NCHW",autoPad:x,dilations:[I],group:L,kernelShape:[U],pads:[ue,Te],strides:[Oe],wIsConst:()=>!!F()[Ze>>>0],outputPadding:ht?Array.from(se().subarray(Number(ht)>>>0,Number(Tt)>>>0)):[],outputShape:It?Array.from(se().subarray(Number(It)>>>0,Number(sr)>>>0)):[],activation:Ft(Os)})},836953:(h,x,I,L,U,ue,Te,Oe,Ke,Ze,ht,Tt,It,sr)=>{n.jb("ConvTranspose",h,{format:Oe?"NHWC":"NCHW",autoPad:x,dilations:Array.from(se().subarray(Number(I)>>>0,2+(Number(I)>>>0)>>>0)),group:L,kernelShape:Array.from(se().subarray(Number(U)>>>0,2+(Number(U)>>>0)>>>0)),pads:Array.from(se().subarray(Number(ue)>>>0,4+(Number(ue)>>>0)>>>0)),strides:Array.from(se().subarray(Number(Te)>>>0,2+(Number(Te)>>>0)>>>0)),wIsConst:()=>!!F()[Ke>>>0],outputPadding:Ze?Array.from(se().subarray(Number(Ze)>>>0,Number(ht)>>>0)):[],outputShape:Tt?Array.from(se().subarray(Number(Tt)>>>0,Number(It)>>>0)):[],activation:Ft(sr)})},837614:(h,x)=>{n.jb("GlobalAveragePool",h,{format:x?"NHWC":"NCHW"})},837705:(h,x,I,L,U,ue,Te,Oe,Ke,Ze,ht,Tt,It,sr)=>{n.jb("AveragePool",h,{format:sr?"NHWC":"NCHW",auto_pad:x,ceil_mode:I,count_include_pad:L,storage_order:U,dilations:ue?Array.from(se().subarray(Number(ue)>>>0,Number(Te)>>>0)):[],kernel_shape:Oe?Array.from(se().subarray(Number(Oe)>>>0,Number(Ke)>>>0)):[],pads:Ze?Array.from(se().subarray(Number(Ze)>>>0,Number(ht)>>>0)):[],strides:Tt?Array.from(se().subarray(Number(Tt)>>>0,Number(It)>>>0)):[]})},838184:(h,x)=>{n.jb("GlobalAveragePool",h,{format:x?"NHWC":"NCHW"})},838275:(h,x,I,L,U,ue,Te,Oe,Ke,Ze,ht,Tt,It,sr)=>{n.jb("AveragePool",h,{format:sr?"NHWC":"NCHW",auto_pad:x,ceil_mode:I,count_include_pad:L,storage_order:U,dilations:ue?Array.from(se().subarray(Number(ue)>>>0,Number(Te)>>>0)):[],kernel_shape:Oe?Array.from(se().subarray(Number(Oe)>>>0,Number(Ke)>>>0)):[],pads:Ze?Array.from(se().subarray(Number(Ze)>>>0,Number(ht)>>>0)):[],strides:Tt?Array.from(se().subarray(Number(Tt)>>>0,Number(It)>>>0)):[]})},838754:(h,x)=>{n.jb("GlobalMaxPool",h,{format:x?"NHWC":"NCHW"})},838841:(h,x,I,L,U,ue,Te,Oe,Ke,Ze,ht,Tt,It,sr)=>{n.jb("MaxPool",h,{format:sr?"NHWC":"NCHW",auto_pad:x,ceil_mode:I,count_include_pad:L,storage_order:U,dilations:ue?Array.from(se().subarray(Number(ue)>>>0,Number(Te)>>>0)):[],kernel_shape:Oe?Array.from(se().subarray(Number(Oe)>>>0,Number(Ke)>>>0)):[],pads:Ze?Array.from(se().subarray(Number(Ze)>>>0,Number(ht)>>>0)):[],strides:Tt?Array.from(se().subarray(Number(Tt)>>>0,Number(It)>>>0)):[]})},839316:(h,x)=>{n.jb("GlobalMaxPool",h,{format:x?"NHWC":"NCHW"})},839403:(h,x,I,L,U,ue,Te,Oe,Ke,Ze,ht,Tt,It,sr)=>{n.jb("MaxPool",h,{format:sr?"NHWC":"NCHW",auto_pad:x,ceil_mode:I,count_include_pad:L,storage_order:U,dilations:ue?Array.from(se().subarray(Number(ue)>>>0,Number(Te)>>>0)):[],kernel_shape:Oe?Array.from(se().subarray(Number(Oe)>>>0,Number(Ke)>>>0)):[],pads:Ze?Array.from(se().subarray(Number(Ze)>>>0,Number(ht)>>>0)):[],strides:Tt?Array.from(se().subarray(Number(Tt)>>>0,Number(It)>>>0)):[]})},839878:(h,x,I,L,U)=>{n.jb("Gemm",h,{alpha:x,beta:I,transA:L,transB:U})},839982:h=>{n.jb("MatMul",h,void 0)},840036:(h,x,I,L)=>{n.jb("ArgMax",h,{keepDims:!!x,selectLastIndex:!!I,axis:L})},840144:(h,x,I,L)=>{n.jb("ArgMin",h,{keepDims:!!x,selectLastIndex:!!I,axis:L})},840252:(h,x)=>{n.jb("Softmax",h,{axis:x})},840315:(h,x)=>{n.jb("Concat",h,{axis:x})},840375:(h,x,I,L,U)=>{n.jb("Split",h,{axis:x,numOutputs:I,splitSizes:L?Array.from(se().subarray(Number(L)>>>0,Number(U)>>>0)):[]})},840531:h=>{n.jb("Expand",h,void 0)},840585:(h,x)=>{n.jb("Gather",h,{axis:Number(x)})},840656:(h,x)=>{n.jb("GatherElements",h,{axis:Number(x)})},840735:(h,x)=>{n.jb("GatherND",h,{batch_dims:Number(x)})},840814:(h,x,I,L,U,ue,Te,Oe,Ke,Ze,ht)=>{n.jb("Resize",h,{antialias:x,axes:I?Array.from(se().subarray(Number(I)>>>0,Number(L)>>>0)):[],coordinateTransformMode:Ft(U),cubicCoeffA:ue,excludeOutside:Te,extrapolationValue:Oe,keepAspectRatioPolicy:Ft(Ke),mode:Ft(Ze),nearestMode:Ft(ht)})},841176:(h,x,I,L,U,ue,Te)=>{n.jb("Slice",h,{starts:x?Array.from(se().subarray(Number(x)>>>0,Number(I)>>>0)):[],ends:L?Array.from(se().subarray(Number(L)>>>0,Number(U)>>>0)):[],axes:ue?Array.from(se().subarray(Number(ue)>>>0,Number(Te)>>>0)):[]})},841440:h=>{n.jb("Tile",h,void 0)},841492:(h,x,I)=>{n.jb("InstanceNormalization",h,{epsilon:x,format:I?"NHWC":"NCHW"})},841606:(h,x,I)=>{n.jb("InstanceNormalization",h,{epsilon:x,format:I?"NHWC":"NCHW"})},841720:h=>{n.jb("Range",h,void 0)},841773:(h,x)=>{n.jb("Einsum",h,{equation:Ft(x)})},841854:(h,x,I,L,U)=>{n.jb("Pad",h,{mode:x,value:I,pads:L?Array.from(se().subarray(Number(L)>>>0,Number(U)>>>0)):[]})},841997:(h,x,I,L,U,ue)=>{n.jb("BatchNormalization",h,{epsilon:x,momentum:I,spatial:!!U,trainingMode:!!L,format:ue?"NHWC":"NCHW"})},842166:(h,x,I,L,U,ue)=>{n.jb("BatchNormalization",h,{epsilon:x,momentum:I,spatial:!!U,trainingMode:!!L,format:ue?"NHWC":"NCHW"})},842335:(h,x,I)=>{n.jb("CumSum",h,{exclusive:Number(x),reverse:Number(I)})},842432:(h,x,I)=>{n.jb("DequantizeLinear",h,{axis:x,blockSize:I})},842522:(h,x,I,L,U)=>{n.jb("GridSample",h,{align_corners:x,mode:Ft(I),padding_mode:Ft(L),format:U?"NHWC":"NCHW"})},842692:(h,x,I,L,U)=>{n.jb("GridSample",h,{align_corners:x,mode:Ft(I),padding_mode:Ft(L),format:U?"NHWC":"NCHW"})},842862:(h,x)=>{n.jb("ScatterND",h,{reduction:Ft(x)})},842947:(h,x,I,L,U,ue,Te,Oe,Ke)=>{n.jb("Attention",h,{numHeads:x,isUnidirectional:I,maskFilterValue:L,scale:U,doRotary:ue,qkvHiddenSizes:Te?Array.from(se().subarray(Number(Oe)>>>0,Number(Oe)+Te>>>0)):[],pastPresentShareBuffer:!!Ke})},843219:h=>{n.jb("BiasAdd",h,void 0)},843274:h=>{n.jb("BiasSplitGelu",h,void 0)},843335:h=>{n.jb("FastGelu",h,void 0)},843391:(h,x,I,L,U,ue,Te,Oe,Ke,Ze,ht,Tt,It,sr,Os,Hi)=>{n.jb("Conv",h,{format:Tt?"NHWC":"NCHW",auto_pad:x,dilations:I?Array.from(se().subarray(Number(I)>>>0,Number(L)>>>0)):[],group:U,kernel_shape:ue?Array.from(se().subarray(Number(ue)>>>0,Number(Te)>>>0)):[],pads:Oe?Array.from(se().subarray(Number(Oe)>>>0,Number(Ke)>>>0)):[],strides:Ze?Array.from(se().subarray(Number(Ze)>>>0,Number(ht)>>>0)):[],w_is_const:()=>!!F()[Number(It)>>>0],activation:Ft(sr),activation_params:Os?Array.from($e().subarray(Number(Os)>>>0,Number(Hi)>>>0)):[]})},843975:h=>{n.jb("Gelu",h,void 0)},844027:(h,x,I,L,U,ue,Te,Oe,Ke)=>{n.jb("GroupQueryAttention",h,{numHeads:x,kvNumHeads:I,scale:L,softcap:U,doRotary:ue,rotaryInterleaved:Te,smoothSoftmax:Oe,localWindowSize:Ke})},844244:(h,x,I,L)=>{n.jb("LayerNormalization",h,{axis:x,epsilon:I,simplified:!!L})},844355:(h,x,I,L)=>{n.jb("LayerNormalization",h,{axis:x,epsilon:I,simplified:!!L})},844466:(h,x,I,L,U,ue)=>{n.jb("MatMulNBits",h,{k:x,n:I,accuracyLevel:L,bits:U,blockSize:ue})},844593:(h,x,I,L,U,ue)=>{n.jb("MultiHeadAttention",h,{numHeads:x,isUnidirectional:I,maskFilterValue:L,scale:U,doRotary:ue})},844752:(h,x)=>{n.jb("QuickGelu",h,{alpha:x})},844816:(h,x,I,L,U)=>{n.jb("RotaryEmbedding",h,{interleaved:!!x,numHeads:I,rotaryEmbeddingDim:L,scale:U})},844955:(h,x,I)=>{n.jb("SkipLayerNormalization",h,{epsilon:x,simplified:!!I})},845057:(h,x,I)=>{n.jb("SkipLayerNormalization",h,{epsilon:x,simplified:!!I})},845159:(h,x,I,L)=>{n.jb("GatherBlockQuantized",h,{gatherAxis:x,quantizeAxis:I,blockSize:L})},845280:h=>{n.Zb(h)},845314:(h,x)=>n.ac(Number(h),Number(x),n.Fb.dc,n.Fb.errors)};function O(h,x,I){return jr(async()=>{await n.Xb(Number(h),Number(x),Number(I))})}function Y(){return typeof wasmOffsetConverter<"u"}class z{constructor(x){te(this,"name","ExitStatus");this.message=`Program terminated with exit(${x})`,this.status=x}}var J=h=>{h.terminate(),h.onmessage=()=>{}},le=[],ye=h=>{Ge.length==0&&(Ms(),ls(Ge[0]));var x=Ge.pop();if(!x)return 6;lt.push(x),Gt[h.Ab]=x,x.Ab=h.Ab;var I={Bb:"run",fc:h.ec,Hb:h.Hb,Ab:h.Ab};return x.postMessage(I,h.Mb),0},Ee=0,ke=(h,x,...I)=>{for(var L=2*I.length,U=eo(),ue=kn(8*L),Te=ue>>>3,Oe=0;Oe>>0]=Ke)}return h=Uo(h,0,L,ue,x),$n(U),h};function Ie(h){if(u)return ke(0,1,h);if(C=h,!(0{if(C=h,u)throw Re(h),"unwind";Ie(h)},Ge=[],lt=[],wt=[],Gt={},Ot=h=>{var x=h.Ab;delete Gt[x],Ge.push(h),lt.splice(lt.indexOf(h),1),h.Ab=0,Jn(x)};function ur(){wt.forEach(h=>h())}var ls=h=>new Promise(x=>{h.onmessage=U=>{var ue=(U=U.data).Bb;if(U.Gb&&U.Gb!=Xs()){var Te=Gt[U.Gb];Te?Te.postMessage(U,U.Mb):y(`Internal error! Worker sent a message "${ue}" to target pthread ${U.Gb}, but that thread no longer exists!`)}else ue==="checkMailbox"?je():ue==="spawnThread"?ye(U):ue==="cleanupThread"?Ot(Gt[U.hc]):ue==="loaded"?(h.loaded=!0,x(h)):ue==="alert"?alert(`Thread ${U.ic}: ${U.text}`):U.target==="setimmediate"?h.postMessage(U):ue==="callHandler"?n[U.Qb](...U.args):ue&&y(`worker sent an unknown command ${ue}`)},h.onerror=U=>{throw y(`worker sent an error! ${U.filename}:${U.lineno}: ${U.message}`),U};var I,L=[];for(I of[])n.propertyIsEnumerable(I)&&L.push(I);h.postMessage({Bb:"load",Rb:L,kc:M,lc:v})});function Ms(){var h=new Worker((()=>{let x=URL;return self.location.href>"file:"&&self.location.href<"file;"?new x("ort.bundle.min.mjs",self.location.href):new URL(self.location.href)})(),{type:"module",workerData:"em-pthread",name:"em-pthread"});Ge.push(h)}var Ir=h=>{R();var x=ce()[h+52>>>2>>>0];h=ce()[h+56>>>2>>>0],Go(x,x-h),$n(x)},js=(h,x)=>{Ee=0,h=Ko(h,x),0>>=0);throw x>>>=0,I>>>=0,ce()[L.Ib+16>>>2>>>0]=0,ce()[L.Ib+4>>>2>>>0]=x,ce()[L.Ib+8>>>2>>>0]=I,h}function at(h,x,I,L){return u?ke(2,1,h,x,I,L):us(h,x,I,L)}function us(h,x,I,L){if(h>>>=0,I>>>=0,L>>>=0,p===void 0)return 6;var U=[];return u&&U.length===0?at(h,x>>>=0,I,L):(h={ec:I,Ab:h,Hb:L,Mb:U},u?(h.Bb="spawnThread",postMessage(h,U),0):ye(h))}var Ar=typeof TextDecoder<"u"?new TextDecoder:void 0,bs=(h,x=0,I=NaN)=>{var L=(x>>>=0)+I;for(I=x;h[I]&&!(I>=L);)++I;if(16(U=(240&U)==224?(15&U)<<12|ue<<6|Te:(7&U)<<18|ue<<12|Te<<6|63&h[x++])?L+=String.fromCharCode(U):(U-=65536,L+=String.fromCharCode(55296|U>>10,56320|1023&U))}}else L+=String.fromCharCode(U)}return L},Ft=(h,x)=>(h>>>=0)?bs(W(),h,x):"";function ds(h,x,I){return u?ke(3,1,h,x,I):0}function cs(h,x){if(u)return ke(4,1,h,x)}var ys=h=>{for(var x=0,I=0;I=L?x++:2047>=L?x+=2:55296<=L&&57343>=L?(x+=4,++I):x+=3}return x},Qt=(h,x,I)=>{var L=W();if(x>>>=0,0=Te&&(Te=65536+((1023&Te)<<10)|1023&h.charCodeAt(++ue)),127>=Te){if(x>=I)break;L[x++>>>0]=Te}else{if(2047>=Te){if(x+1>=I)break;L[x++>>>0]=192|Te>>6}else{if(65535>=Te){if(x+2>=I)break;L[x++>>>0]=224|Te>>12}else{if(x+3>=I)break;L[x++>>>0]=240|Te>>18,L[x++>>>0]=128|Te>>12&63}L[x++>>>0]=128|Te>>6&63}L[x++>>>0]=128|63&Te}}L[x>>>0]=0,h=x-U}else h=0;return h};function De(h,x){if(u)return ke(5,1,h,x)}function Qe(h,x,I){if(u)return ke(6,1,h,x,I)}function tt(h,x,I){return u?ke(7,1,h,x,I):0}function Rt(h,x){if(u)return ke(8,1,h,x)}function zr(h,x,I){if(u)return ke(9,1,h,x,I)}function Sr(h,x,I,L){if(u)return ke(10,1,h,x,I,L)}function ps(h,x,I,L){if(u)return ke(11,1,h,x,I,L)}function hs(h,x,I,L){if(u)return ke(12,1,h,x,I,L)}function Kr(h){if(u)return ke(13,1,h)}function ms(h,x){if(u)return ke(14,1,h,x)}function _s(h,x,I){if(u)return ke(15,1,h,x,I)}var Hr,vr,cn=()=>Fe(""),xr=h=>{for(var x="";W()[h>>>0];)x+=Hr[W()[h++>>>0]];return x},$s={},ks={};function fr(h,x,I={}){return function(L,U,ue={}){var Te=U.name;if(!L)throw new vr(`type "${Te}" must have a positive integer typeid pointer`);if(ks.hasOwnProperty(L)){if(ue.Sb)return;throw new vr(`Cannot register type '${Te}' twice`)}ks[L]=U,$s.hasOwnProperty(L)&&(U=$s[L],delete $s[L],U.forEach(Oe=>Oe()))}(h,x,I)}var Vs=(h,x,I)=>{switch(x){case 1:return I?L=>F()[L>>>0]:L=>W()[L>>>0];case 2:return I?L=>re()[L>>>1>>>0]:L=>_e()[L>>>1>>>0];case 4:return I?L=>se()[L>>>2>>>0]:L=>ce()[L>>>2>>>0];case 8:return I?L=>Z[L>>>3]:L=>X[L>>>3];default:throw new TypeError(`invalid integer width (${x}): ${h}`)}};function pn(h,x,I){I>>>=0,fr(h>>>=0,{name:x=xr(x>>>0),fromWireType:L=>L,toWireType:function(L,U){if(typeof U!="bigint"&&typeof U!="number")throw U=U===null?"null":(L=typeof U)=="object"||L==="array"||L==="function"?U.toString():""+U,new TypeError(`Cannot convert "${U}" to ${this.name}`);return typeof U=="number"&&(U=BigInt(U)),U},Cb:Fr,readValueFromPointer:Vs(x,I,x.indexOf("u")==-1),Db:null})}var Fr=8;function hn(h,x,I,L){fr(h>>>=0,{name:x=xr(x>>>0),fromWireType:function(U){return!!U},toWireType:function(U,ue){return ue?I:L},Cb:Fr,readValueFromPointer:function(U){return this.fromWireType(W()[U>>>0])},Db:null})}var qr=[],Tr=[];function Is(h){9<(h>>>=0)&&--Tr[h+1]==0&&(Tr[h]=void 0,qr.push(h))}var dr=h=>{if(!h)throw new vr("Cannot use deleted val. handle = "+h);return Tr[h]},gr=h=>{switch(h){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let x=qr.pop()||Tr.length;return Tr[x]=h,Tr[x+1]=1,x}};function Br(h){return this.fromWireType(ce()[h>>>2>>>0])}var mn={name:"emscripten::val",fromWireType:h=>{var x=dr(h);return Is(h),x},toWireType:(h,x)=>gr(x),Cb:Fr,readValueFromPointer:Br,Db:null};function _n(h){return fr(h>>>0,mn)}var fn=(h,x)=>{switch(x){case 4:return function(I){return this.fromWireType($e()[I>>>2>>>0])};case 8:return function(I){return this.fromWireType(Ue()[I>>>3>>>0])};default:throw new TypeError(`invalid float width (${x}): ${h}`)}};function gn(h,x,I){I>>>=0,fr(h>>>=0,{name:x=xr(x>>>0),fromWireType:L=>L,toWireType:(L,U)=>U,Cb:Fr,readValueFromPointer:fn(x,I),Db:null})}function wn(h,x,I,L,U){if(h>>>=0,I>>>=0,x=xr(x>>>0),U===-1&&(U=4294967295),U=Oe=>Oe,L===0){var ue=32-8*I;U=Oe=>Oe<>>ue}var Te=x.includes("unsigned")?function(Oe,Ke){return Ke>>>0}:function(Oe,Ke){return Ke};fr(h,{name:x,fromWireType:U,toWireType:Te,Cb:Fr,readValueFromPointer:Vs(x,I,L!==0),Db:null})}function vs(h,x,I){function L(ue){var Te=ce()[ue>>>2>>>0];return ue=ce()[ue+4>>>2>>>0],new U(F().buffer,ue,Te)}var U=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][x];fr(h>>>=0,{name:I=xr(I>>>0),fromWireType:L,Cb:Fr,readValueFromPointer:L},{Sb:!0})}function Mn(h,x){fr(h>>>=0,{name:x=xr(x>>>0),fromWireType:function(I){for(var L,U=ce()[I>>>2>>>0],ue=I+4,Te=ue,Oe=0;Oe<=U;++Oe){var Ke=ue+Oe;Oe!=U&&W()[Ke>>>0]!=0||(Te=Ft(Te,Ke-Te),L===void 0?L=Te:(L+="\0",L+=Te),Te=Ke+1)}return Nr(I),L},toWireType:function(I,L){L instanceof ArrayBuffer&&(L=new Uint8Array(L));var U=typeof L=="string";if(!(U||L instanceof Uint8Array||L instanceof Uint8ClampedArray||L instanceof Int8Array))throw new vr("Cannot pass non-string to std::string");var ue=U?ys(L):L.length,Te=Cn(4+ue+1),Oe=Te+4;if(ce()[Te>>>2>>>0]=ue,U)Qt(L,Oe,ue+1);else if(U)for(U=0;U>>0]=Ke}else for(U=0;U>>0]=L[U];return I!==null&&I.push(Nr,Te),Te},Cb:Fr,readValueFromPointer:Br,Db(I){Nr(I)}})}var Us=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,bn=(h,x)=>{for(var I=h>>1,L=I+x/2;!(I>=L)&&_e()[I>>>0];)++I;if(32<(I<<=1)-h&&Us)return Us.decode(W().slice(h,I));for(I="",L=0;!(L>=x/2);++L){var U=re()[h+2*L>>>1>>>0];if(U==0)break;I+=String.fromCharCode(U)}return I},yn=(h,x,I)=>{if(I??(I=2147483647),2>I)return 0;var L=x;I=(I-=2)<2*h.length?I/2:h.length;for(var U=0;U>>1>>>0]=ue,x+=2}return re()[x>>>1>>>0]=0,x-L},xs=h=>2*h.length,vn=(h,x)=>{for(var I=0,L="";!(I>=x/4);){var U=se()[h+4*I>>>2>>>0];if(U==0)break;++I,65536<=U?(U-=65536,L+=String.fromCharCode(55296|U>>10,56320|1023&U)):L+=String.fromCharCode(U)}return L},he=(h,x,I)=>{if(x>>>=0,I??(I=2147483647),4>I)return 0;var L=x;I=L+I-4;for(var U=0;U=ue&&(ue=65536+((1023&ue)<<10)|1023&h.charCodeAt(++U)),se()[x>>>2>>>0]=ue,(x+=4)+4>I)break}return se()[x>>>2>>>0]=0,x-L},$=h=>{for(var x=0,I=0;I=L&&++I,x+=4}return x};function N(h,x,I){if(h>>>=0,x>>>=0,I=xr(I>>>=0),x===2)var L=bn,U=yn,ue=xs,Te=Oe=>_e()[Oe>>>1>>>0];else x===4&&(L=vn,U=he,ue=$,Te=Oe=>ce()[Oe>>>2>>>0]);fr(h,{name:I,fromWireType:Oe=>{for(var Ke,Ze=ce()[Oe>>>2>>>0],ht=Oe+4,Tt=0;Tt<=Ze;++Tt){var It=Oe+4+Tt*x;Tt!=Ze&&Te(It)!=0||(ht=L(ht,It-ht),Ke===void 0?Ke=ht:(Ke+="\0",Ke+=ht),ht=It+x)}return Nr(Oe),Ke},toWireType:(Oe,Ke)=>{if(typeof Ke!="string")throw new vr(`Cannot pass non-string to C++ string type ${I}`);var Ze=ue(Ke),ht=Cn(4+Ze+x);return ce()[ht>>>2>>>0]=Ze/x,U(Ke,ht+4,Ze+x),Oe!==null&&Oe.push(Nr,ht),ht},Cb:Fr,readValueFromPointer:Br,Db(Oe){Nr(Oe)}})}function Q(h,x){fr(h>>>=0,{Tb:!0,name:x=xr(x>>>0),Cb:0,fromWireType:()=>{},toWireType:()=>{}})}function ie(h){Sn(h>>>0,!l,1,!a,131072,!1),ur()}var de=h=>{if(!ae)try{if(h(),!(0>>=0,typeof Atomics.jc=="function"&&(Atomics.jc(se(),h>>>2,h).value.then(je),h+=128,Atomics.store(se(),h>>>2,1))}var je=()=>{var h=Xs();h&&(ve(h),de(Zn))};function He(h,x){(h>>>=0)==x>>>0?setTimeout(je):u?postMessage({Gb:h,Bb:"checkMailbox"}):(h=Gt[h])&&h.postMessage({Bb:"checkMailbox"})}var We=[];function Je(h,x,I,L,U){for(x>>>=0,L/=2,We.length=L,I=U>>>0>>>3,U=0;U>>0];return(x?Ve[x]:Ro[h])(...We)}var dt=()=>{Ee=0};function xt(h){h>>>=0,u?postMessage({Bb:"cleanupThread",hc:h}):Ot(Gt[h])}function Pt(h){}var jt=(h,x)=>{var I=ks[h];if(I===void 0)throw h=jo(h),I=xr(h),Nr(h),new vr(`${x} has unknown type ${I}`);return I},kt=(h,x,I)=>{var L=[];return h=h.toWireType(L,I),L.length&&(ce()[x>>>2>>>0]=gr(L)),h};function Ht(h,x,I){return x>>>=0,I>>>=0,h=dr(h>>>0),x=jt(x,"emval::as"),kt(x,I,h)}function br(h,x){return x>>>=0,h=dr(h>>>0),(x=jt(x,"emval::as")).toWireType(null,h)}var cr=h=>{try{h()}catch(x){Fe(x)}},pr=0,Nt=null,Xr=0,Dt=[],rr={},wr={},Qr=0,Rr=null,Yt=[];function jr(h){return function(x){if(!ae){if(pr===0){var I=!1,L=!1;x((U=0)=>{if(!ae&&(Xr=U,I=!0,L)){pr=2,cr(()=>qo(Nt)),typeof MainLoop<"u"&&MainLoop.Pb&&MainLoop.resume(),U=!1;try{var ue=function(){var Ke=se()[Nt+8>>>2>>>0];return Ke=nt[wr[Ke]],--Ee,Ke()}()}catch(Ke){ue=Ke,U=!0}var Te=!1;if(!Nt){var Oe=Rr;Oe&&(Rr=null,(U?Oe.reject:Oe.resolve)(ue),Te=!0)}if(U&&!Te)throw ue}}),L=!0,I||(pr=1,Nt=function(){var U=Cn(65548),ue=U+12;ce()[U>>>2>>>0]=ue,ce()[U+4>>>2>>>0]=ue+65536,ue=Dt[0];var Te=rr[ue];return Te===void 0&&(Te=Qr++,rr[ue]=Te,wr[Te]=ue),ue=Te,se()[U+8>>>2>>>0]=ue,U}(),typeof MainLoop<"u"&&MainLoop.Pb&&MainLoop.pause(),cr(()=>to(Nt)))}else pr===2?(pr=0,cr(ro),Nr(Nt),Nt=null,Yt.forEach(de)):Fe(`invalid state: ${pr}`);return Xr}}(x=>{h().then(x)})}function or(h){return h>>>=0,jr(async()=>{var x=await dr(h);return gr(x)})}var Vt=[];function Zt(h,x,I,L){return I>>>=0,L>>>=0,(h=Vt[h>>>0])(null,x=dr(x>>>0),I,L)}var er={},tr=h=>{var x=er[h];return x===void 0?xr(h):x};function Ws(h,x,I,L,U){return I>>>=0,L>>>=0,U>>>=0,(h=Vt[h>>>0])(x=dr(x>>>0),x[I=tr(I)],L,U)}var xn=()=>typeof globalThis=="object"?globalThis:Function("return this")();function vi(h){return(h>>>=0)==0?gr(xn()):(h=tr(h),gr(xn()[h]))}var xi=h=>{var x=Vt.length;return Vt.push(h),x},Ti=(h,x)=>{for(var I=Array(h),L=0;L>>2>>>0],"parameter "+L);return I},As=(h,x)=>Object.defineProperty(x,"name",{value:h});function Ei(h,x,I){var L=(x=Ti(h,x>>>0)).shift();h--;var U=`return function (obj, func, destructorsRef, args) { +`,ue=0,Te=[];I===0&&Te.push("obj");for(var Oe=["retType"],Ke=[L],Ze=0;Zeht.name).join(", ")}) => ${L.name}>`,xi(As(I,h))}function Pi(h){return h=tr(h>>>0),gr(n[h])}function Ci(h,x){return x>>>=0,h=dr(h>>>0),x=dr(x),gr(h[x])}function Si(h){9<(h>>>=0)&&(Tr[h+1]+=1)}function $i(){return gr([])}function To(h){h=dr(h>>>0);for(var x=Array(h.length),I=0;I>>0))}function Ii(){return gr({})}function Eo(h){for(var x=dr(h>>>=0);x.length;){var I=x.pop();x.pop()(I)}Is(h)}function Ai(h,x,I){x>>>=0,I>>>=0,h=dr(h>>>0),x=dr(x),I=dr(I),h[x]=I}function Po(h,x){return x>>>=0,h=(h=jt(h>>>0,"_emval_take_value")).readValueFromPointer(x),gr(h)}function Fi(h,x){h=-9007199254740992>h||9007199254740992>>=0,h=new Date(1e3*h),se()[x>>>2>>>0]=h.getUTCSeconds(),se()[x+4>>>2>>>0]=h.getUTCMinutes(),se()[x+8>>>2>>>0]=h.getUTCHours(),se()[x+12>>>2>>>0]=h.getUTCDate(),se()[x+16>>>2>>>0]=h.getUTCMonth(),se()[x+20>>>2>>>0]=h.getUTCFullYear()-1900,se()[x+24>>>2>>>0]=h.getUTCDay(),h=(h.getTime()-Date.UTC(h.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,se()[x+28>>>2>>>0]=h}var Gn=h=>h%4==0&&(h%100!=0||h%400==0),Oi=[0,31,60,91,121,152,182,213,244,274,305,335],Co=[0,31,59,90,120,151,181,212,243,273,304,334];function So(h,x){h=-9007199254740992>h||9007199254740992>>=0,h=new Date(1e3*h),se()[x>>>2>>>0]=h.getSeconds(),se()[x+4>>>2>>>0]=h.getMinutes(),se()[x+8>>>2>>>0]=h.getHours(),se()[x+12>>>2>>>0]=h.getDate(),se()[x+16>>>2>>>0]=h.getMonth(),se()[x+20>>>2>>>0]=h.getFullYear()-1900,se()[x+24>>>2>>>0]=h.getDay();var I=(Gn(h.getFullYear())?Oi:Co)[h.getMonth()]+h.getDate()-1|0;se()[x+28>>>2>>>0]=I,se()[x+36>>>2>>>0]=-60*h.getTimezoneOffset(),I=new Date(h.getFullYear(),6,1).getTimezoneOffset();var L=new Date(h.getFullYear(),0,1).getTimezoneOffset();h=0|(I!=L&&h.getTimezoneOffset()==Math.min(L,I)),se()[x+32>>>2>>>0]=h}function Di(h){h>>>=0;var x=new Date(se()[h+20>>>2>>>0]+1900,se()[h+16>>>2>>>0],se()[h+12>>>2>>>0],se()[h+8>>>2>>>0],se()[h+4>>>2>>>0],se()[h>>>2>>>0],0),I=se()[h+32>>>2>>>0],L=x.getTimezoneOffset(),U=new Date(x.getFullYear(),6,1).getTimezoneOffset(),ue=new Date(x.getFullYear(),0,1).getTimezoneOffset(),Te=Math.min(ue,U);return 0>I?se()[h+32>>>2>>>0]=+(U!=ue&&Te==L):0>>2>>>0]=x.getDay(),I=(Gn(x.getFullYear())?Oi:Co)[x.getMonth()]+x.getDate()-1|0,se()[h+28>>>2>>>0]=I,se()[h>>>2>>>0]=x.getSeconds(),se()[h+4>>>2>>>0]=x.getMinutes(),se()[h+8>>>2>>>0]=x.getHours(),se()[h+12>>>2>>>0]=x.getDate(),se()[h+16>>>2>>>0]=x.getMonth(),se()[h+20>>>2>>>0]=x.getYear(),h=x.getTime(),BigInt(isNaN(h)?-1:h/1e3)}function Tn(h,x,I,L,U,ue,Te){return u?ke(16,1,h,x,I,L,U,ue,Te):-52}function $o(h,x,I,L,U,ue){if(u)return ke(17,1,h,x,I,L,U,ue)}var Gs={},Li=()=>performance.timeOrigin+performance.now();function ko(h,x){if(u)return ke(18,1,h,x);if(Gs[h]&&(clearTimeout(Gs[h].id),delete Gs[h]),!x)return 0;var I=setTimeout(()=>{delete Gs[h],de(()=>Wo(h,performance.timeOrigin+performance.now()))},x);return Gs[h]={id:I,qc:x},0}function zi(h,x,I,L){h>>>=0,x>>>=0,I>>>=0,L>>>=0;var U=new Date().getFullYear(),ue=new Date(U,0,1).getTimezoneOffset();U=new Date(U,6,1).getTimezoneOffset();var Te=Math.max(ue,U);ce()[h>>>2>>>0]=60*Te,se()[x>>>2>>>0]=+(ue!=U),h=(x=Oe=>{var Ke=Math.abs(Oe);return`UTC${0<=Oe?"-":"+"}${String(Math.floor(Ke/60)).padStart(2,"0")}${String(Ke%60).padStart(2,"0")}`})(ue),x=x(U),UDate.now();function Ri(h,x,I){return 0<=h&&3>=h?(h===0?h=Date.now():h=performance.timeOrigin+performance.now(),Z[I>>>0>>>3]=BigInt(Math.round(1e6*h)),0):28}var Ks=[],Kn=(h,x)=>{Ks.length=0;for(var I;I=W()[h++>>>0];){var L=I!=105;x+=(L&=I!=112)&&x%8?4:0,Ks.push(I==112?ce()[x>>>2>>>0]:I==106?Z[x>>>3]:I==105?se()[x>>>2>>>0]:Ue()[x>>>3>>>0]),x+=L?8:4}return Ks};function ji(h,x,I){return h>>>=0,x=Kn(x>>>0,I>>>0),Ve[h](...x)}function Io(h,x,I){return h>>>=0,x=Kn(x>>>0,I>>>0),Ve[h](...x)}var Fs=()=>{};function Ni(h,x){return y(Ft(h>>>0,x>>>0))}var pu=()=>{throw Ee+=1,"unwind"};function Vi(){return 4294901760}var hu=()=>navigator.hardwareConcurrency;function Ui(){return Fe("Cannot use emscripten_pc_get_function without -sUSE_OFFSET_CONVERTER"),0}function Ao(h){h>>>=0;var x=W().length;if(h<=x||4294901760=I;I*=2){var L=x*(1+.2/I);L=Math.min(L,h+100663296);e:{L=(Math.min(4294901760,65536*Math.ceil(Math.max(h,L)/65536))-M.buffer.byteLength+65535)/65536|0;try{M.grow(L),R();var U=1;break e}catch{}U=void 0}if(U)return!0}return!1}var En=()=>(Fe("Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER"),0),Hs={},Fo=h=>{h.forEach(x=>{En()})};function Wi(){var h=Error().stack.toString().split(` +`);return h[0]=="Error"&&h.shift(),Fo(h),Hs.Lb=En(),Hs.cc=h,Hs.Lb}function Gi(h,x,I){if(h>>>=0,x>>>=0,Hs.Lb==h)var L=Hs.cc;else(L=Error().stack.toString().split(` +`))[0]=="Error"&&L.shift(),Fo(L);for(var U=3;L[U]&&En()!=h;)++U;for(h=0;h>>2>>>0]=En();return h}var qs,Hn={},Oo=()=>{if(!qs){var h,x={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:"./this.program"};for(h in Hn)Hn[h]===void 0?delete x[h]:x[h]=Hn[h];var I=[];for(h in x)I.push(`${h}=${x[h]}`);qs=I}return qs};function Do(h,x){if(u)return ke(19,1,h,x);h>>>=0,x>>>=0;var I=0;return Oo().forEach((L,U)=>{var ue=x+I;for(U=ce()[h+4*U>>>2>>>0]=ue,ue=0;ue>>0]=L.charCodeAt(ue);F()[U>>>0]=0,I+=L.length+1}),0}function qn(h,x){if(u)return ke(20,1,h,x);h>>>=0,x>>>=0;var I=Oo();ce()[h>>>2>>>0]=I.length;var L=0;return I.forEach(U=>L+=U.length+1),ce()[x>>>2>>>0]=L,0}function Lo(h){return u?ke(21,1,h):52}function zo(h,x,I,L){return u?ke(22,1,h,x,I,L):52}function Xn(h,x,I,L){return u?ke(23,1,h,x,I,L):70}var Ki=[null,[],[]];function Bo(h,x,I,L){if(u)return ke(24,1,h,x,I,L);x>>>=0,I>>>=0,L>>>=0;for(var U=0,ue=0;ue>>2>>>0],Oe=ce()[x+4>>>2>>>0];x+=8;for(var Ke=0;Ke>>0],ht=Ki[h];Ze===0||Ze===10?((h===1?E:y)(bs(ht)),ht.length=0):ht.push(Ze)}U+=Oe}return ce()[L>>>2>>>0]=U,0}u||function(){for(var h=n.numThreads-1;h--;)Ms();le.unshift(()=>{be++,function(x){u?x():Promise.all(Ge.map(ls)).then(x)}(()=>Ae())})}();for(var Qn=Array(256),Pn=0;256>Pn;++Pn)Qn[Pn]=String.fromCharCode(Pn);Hr=Qn,vr=n.BindingError=class extends Error{constructor(h){super(h),this.name="BindingError"}},n.InternalError=class extends Error{constructor(h){super(h),this.name="InternalError"}},Tr.push(0,1,void 0,1,null,1,!0,1,!1,1),n.count_emval_handles=()=>Tr.length/2-5-qr.length;var nt,Ro=[Ie,Re,at,ds,cs,De,Qe,tt,Rt,zr,Sr,ps,hs,Kr,ms,_s,Tn,$o,ko,Do,qn,Lo,zo,Xn,Bo];(async function(){function h(L,U){return nt=L.exports,nt=function(){var ue=nt,Te={};for(let[Oe,Ke]of Object.entries(ue))Te[Oe]=typeof Ke=="function"?(...Ze)=>{Dt.push(Oe);try{return Ke(...Ze)}finally{ae||(Dt.pop(),Nt&&pr===1&&Dt.length===0&&(pr=0,Ee+=1,cr(Ho),typeof Fibers<"u"&&Fibers.rc()))}}:Ke;return Te}(),nt=function(){var ue=nt,Te=Ke=>Ze=>Ke(Ze)>>>0,Oe=Ke=>()=>Ke()>>>0;return(ue=Object.assign({},ue)).Da=Te(ue.Da),ue.fb=Oe(ue.fb),ue.hb=Te(ue.hb),ue.tb=Te(ue.tb),ue.ub=Oe(ue.ub),ue.__cxa_get_exception_ptr=Te(ue.__cxa_get_exception_ptr),ue}(),wt.push(nt.ib),v=U,Ae(),nt}be++;var x=ze();if(n.instantiateWasm)return new Promise(L=>{n.instantiateWasm(x,(U,ue)=>{h(U,ue),L(U.exports)})});if(u)return new Promise(L=>{we=U=>{var ue=new WebAssembly.Instance(U,ze());L(h(ue,U))}});xe??(xe=n.locateFile?n.locateFile?n.locateFile("ort-wasm-simd-threaded.jsep.wasm",w):w+"ort-wasm-simd-threaded.jsep.wasm":new URL("/assets/ort-wasm-simd-threaded.jsep-B0T3yYHD.wasm",self.location.href).href);try{var I=await async function(L){var U=xe;if(!me&&typeof WebAssembly.instantiateStreaming=="function"&&!V(U))try{var ue=fetch(U,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(ue,L)}catch(Te){y(`wasm streaming compile failed: ${Te}`),y("falling back to ArrayBuffer instantiation")}return async function(Te,Oe){try{var Ke=await async function(Ze){if(!me)try{var ht=await f(Ze);return new Uint8Array(ht)}catch{}if(Ze==xe&&me)Ze=new Uint8Array(me);else{if(!_)throw"both async and sync fetching of the wasm failed";Ze=_(Ze)}return Ze}(Te);return await WebAssembly.instantiate(Ke,Oe)}catch(Ze){y(`failed to asynchronously prepare wasm: ${Ze}`),Fe(Ze)}}(U,L)}(x);return h(I.instance,I.module)}catch(L){return o(L),Promise.reject(L)}})();var jo=h=>(jo=nt.Da)(h),No=()=>(No=nt.Ea)();n._OrtInit=(h,x)=>(n._OrtInit=nt.Fa)(h,x),n._OrtGetLastError=(h,x)=>(n._OrtGetLastError=nt.Ga)(h,x),n._OrtCreateSessionOptions=(h,x,I,L,U,ue,Te,Oe,Ke,Ze)=>(n._OrtCreateSessionOptions=nt.Ha)(h,x,I,L,U,ue,Te,Oe,Ke,Ze),n._OrtAppendExecutionProvider=(h,x,I,L,U)=>(n._OrtAppendExecutionProvider=nt.Ia)(h,x,I,L,U),n._OrtAddFreeDimensionOverride=(h,x,I)=>(n._OrtAddFreeDimensionOverride=nt.Ja)(h,x,I),n._OrtAddSessionConfigEntry=(h,x,I)=>(n._OrtAddSessionConfigEntry=nt.Ka)(h,x,I),n._OrtReleaseSessionOptions=h=>(n._OrtReleaseSessionOptions=nt.La)(h),n._OrtCreateSession=(h,x,I)=>(n._OrtCreateSession=nt.Ma)(h,x,I),n._OrtReleaseSession=h=>(n._OrtReleaseSession=nt.Na)(h),n._OrtGetInputOutputCount=(h,x,I)=>(n._OrtGetInputOutputCount=nt.Oa)(h,x,I),n._OrtGetInputOutputMetadata=(h,x,I,L)=>(n._OrtGetInputOutputMetadata=nt.Pa)(h,x,I,L),n._OrtFree=h=>(n._OrtFree=nt.Qa)(h),n._OrtCreateTensor=(h,x,I,L,U,ue)=>(n._OrtCreateTensor=nt.Ra)(h,x,I,L,U,ue),n._OrtGetTensorData=(h,x,I,L,U)=>(n._OrtGetTensorData=nt.Sa)(h,x,I,L,U),n._OrtReleaseTensor=h=>(n._OrtReleaseTensor=nt.Ta)(h),n._OrtCreateRunOptions=(h,x,I,L)=>(n._OrtCreateRunOptions=nt.Ua)(h,x,I,L),n._OrtAddRunConfigEntry=(h,x,I)=>(n._OrtAddRunConfigEntry=nt.Va)(h,x,I),n._OrtReleaseRunOptions=h=>(n._OrtReleaseRunOptions=nt.Wa)(h),n._OrtCreateBinding=h=>(n._OrtCreateBinding=nt.Xa)(h),n._OrtBindInput=(h,x,I)=>(n._OrtBindInput=nt.Ya)(h,x,I),n._OrtBindOutput=(h,x,I,L)=>(n._OrtBindOutput=nt.Za)(h,x,I,L),n._OrtClearBoundOutputs=h=>(n._OrtClearBoundOutputs=nt._a)(h),n._OrtReleaseBinding=h=>(n._OrtReleaseBinding=nt.$a)(h),n._OrtRunWithBinding=(h,x,I,L,U)=>(n._OrtRunWithBinding=nt.ab)(h,x,I,L,U),n._OrtRun=(h,x,I,L,U,ue,Te,Oe)=>(n._OrtRun=nt.bb)(h,x,I,L,U,ue,Te,Oe),n._OrtEndProfiling=h=>(n._OrtEndProfiling=nt.cb)(h),n._JsepOutput=(h,x,I)=>(n._JsepOutput=nt.db)(h,x,I),n._JsepGetNodeName=h=>(n._JsepGetNodeName=nt.eb)(h);var Xs=()=>(Xs=nt.fb)(),Nr=n._free=h=>(Nr=n._free=nt.gb)(h),Cn=n._malloc=h=>(Cn=n._malloc=nt.hb)(h),Sn=(h,x,I,L,U,ue)=>(Sn=nt.kb)(h,x,I,L,U,ue),Vo=()=>(Vo=nt.lb)(),Uo=(h,x,I,L,U)=>(Uo=nt.mb)(h,x,I,L,U),Jn=h=>(Jn=nt.nb)(h),Yn=h=>(Yn=nt.ob)(h),Wo=(h,x)=>(Wo=nt.pb)(h,x),Zn=()=>(Zn=nt.qb)(),Go=(h,x)=>(Go=nt.rb)(h,x),$n=h=>($n=nt.sb)(h),kn=h=>(kn=nt.tb)(h),eo=()=>(eo=nt.ub)(),Ko=n.dynCall_ii=(h,x)=>(Ko=n.dynCall_ii=nt.vb)(h,x),to=h=>(to=nt.wb)(h),Ho=()=>(Ho=nt.xb)(),qo=h=>(qo=nt.yb)(h),ro=()=>(ro=nt.zb)();return n.stackSave=()=>eo(),n.stackRestore=h=>$n(h),n.stackAlloc=h=>kn(h),n.setValue=function(h,x,I="i8"){switch(I.endsWith("*")&&(I="*"),I){case"i1":case"i8":F()[h>>>0]=x;break;case"i16":re()[h>>>1>>>0]=x;break;case"i32":se()[h>>>2>>>0]=x;break;case"i64":Z[h>>>3]=BigInt(x);break;case"float":$e()[h>>>2>>>0]=x;break;case"double":Ue()[h>>>3>>>0]=x;break;case"*":ce()[h>>>2>>>0]=x;break;default:Fe(`invalid type for setValue: ${I}`)}},n.getValue=function(h,x="i8"){switch(x.endsWith("*")&&(x="*"),x){case"i1":case"i8":return F()[h>>>0];case"i16":return re()[h>>>1>>>0];case"i32":return se()[h>>>2>>>0];case"i64":return Z[h>>>3];case"float":return $e()[h>>>2>>>0];case"double":return Ue()[h>>>3>>>0];case"*":return ce()[h>>>2>>>0];default:Fe(`invalid type for getValue: ${x}`)}},n.UTF8ToString=Ft,n.stringToUTF8=Qt,n.lengthBytesUTF8=ys,function h(){if(0{Pa(),Ia=typeof location>"u"?void 0:location.origin,Aa=self.location.href>"file:"&&self.location.href<"file;",Jd=()=>{{if(Aa){let e=URL;return new URL(new e("ort.bundle.min.mjs",self.location.href).href,Ia).href}return self.location.href}},Dr=Jd(),Yd=()=>{if(Dr&&!Dr.startsWith("blob:"))return Dr.substring(0,Dr.lastIndexOf("/")+1)},ei=(e,r)=>{try{let t=r??Dr;return(t?new URL(e,t):new URL(e)).origin===Ia}catch{return!1}},Zd=(e,r)=>{let t=r??Dr;try{return(t?new URL(e,t):new URL(e)).href}catch{return}},ec=(e,r)=>`${r??"./"}${e}`,Fa=async e=>{let r=await(await fetch(e,{credentials:"same-origin"})).blob();return URL.createObjectURL(r)},tc=async e=>(await import(e)).default,Oa=(gv(),io(Kd)).default,rc=async()=>{if(!Dr)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(ei(Dr))return[void 0,Oa()];let e=await Fa(Dr);return[e,Oa(e)]},Da=(wv(),io(qd)).default,sc=async(e,r,t)=>{if(!e&&!r&&Da&&Dr&&ei(Dr))return[void 0,Da];{let s="ort-wasm-simd-threaded.jsep.mjs",o=e??Zd(s,r),n=t&&o&&!ei(o,r),i=n?await Fa(o):o??ec(s,r);return[n?i:void 0,await tc(i)]}}}),za,ti,co,Ba,nc,oc,ic,Ra,zt,en=Be(()=>{La(),ti=!1,co=!1,Ba=!1,nc=()=>{if(typeof SharedArrayBuffer>"u")return!1;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}},oc=()=>{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}},ic=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,19,1,17,0,65,1,253,15,65,2,253,15,65,3,253,15,253,147,2,11]))}catch{return!1}},Ra=async e=>{if(ti)return Promise.resolve();if(co)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Ba)throw new Error("previous call to 'initializeWebAssembly()' failed.");co=!0;let r=e.initTimeout,t=e.numThreads;if(e.simd!==!1){if(e.simd==="relaxed"){if(!ic())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!oc())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let s=nc();t>1&&!s&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+t+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),e.numThreads=t=1);let o=e.wasmPaths,n=typeof o=="string"?o:void 0,i=o==null?void 0:o.mjs,a=(i==null?void 0:i.href)??i,l=o==null?void 0:o.wasm,u=(l==null?void 0:l.href)??l,p=e.wasmBinary,[d,c]=await sc(a,n,t>1),f=!1,_=[];if(r>0&&_.push(new Promise(T=>{setTimeout(()=>{f=!0,T()},r)})),_.push(new Promise((T,k)=>{let w={numThreads:t};if(p)w.wasmBinary=p;else if(u||n)w.locateFile=g=>u??n+g;else if(a&&a.indexOf("blob:")!==0)w.locateFile=g=>new URL(g,a).href;else if(d){let g=Yd();g&&(w.locateFile=S=>g+S)}c(w).then(g=>{co=!1,ti=!0,za=g,T(),d&&URL.revokeObjectURL(d)},g=>{co=!1,Ba=!0,k(g)})})),await Promise.race(_),f)throw new Error(`WebAssembly backend initializing failed due to timeout: ${r}ms`)},zt=()=>{if(ti&&za)return za;throw new Error("WebAssembly is not initialized yet.")}}),rs,ri,At,ja=Be(()=>{en(),rs=(e,r)=>{let t=zt(),s=t.lengthBytesUTF8(e)+1,o=t._malloc(s);return t.stringToUTF8(e,o,s),r.push(o),o},ri=(e,r,t,s)=>{if(typeof e=="object"&&e!==null){if(t.has(e))throw new Error("Circular reference in options");t.add(e)}Object.entries(e).forEach(([o,n])=>{let i=r?r+o:o;if(typeof n=="object")ri(n,i+".",t,s);else if(typeof n=="string"||typeof n=="number")s(i,n.toString());else if(typeof n=="boolean")s(i,n?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof n}`)})},At=e=>{let r=zt(),t=r.stackSave();try{let s=r.PTR_SIZE,o=r.stackAlloc(2*s);r._OrtGetLastError(o,o+s);let n=Number(r.getValue(o,s===4?"i32":"i64")),i=r.getValue(o+s,"*"),a=i?r.UTF8ToString(i):"";throw new Error(`${e} ERROR_CODE: ${n}, ERROR_MESSAGE: ${a}`)}finally{r.stackRestore(t)}}}),ac,Mv=Be(()=>{en(),ja(),ac=e=>{let r=zt(),t=0,s=[],o=e||{};try{if((e==null?void 0:e.logSeverityLevel)===void 0)o.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)o.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&&(o.terminate=!1);let n=0;return(e==null?void 0:e.tag)!==void 0&&(n=rs(e.tag,s)),t=r._OrtCreateRunOptions(o.logSeverityLevel,o.logVerbosityLevel,!!o.terminate,n),t===0&&At("Can't create run options."),(e==null?void 0:e.extra)!==void 0&&ri(e.extra,"",new WeakSet,(i,a)=>{let l=rs(i,s),u=rs(a,s);r._OrtAddRunConfigEntry(t,l,u)!==0&&At(`Can't set a run config entry: ${i} - ${a}.`)}),[t,s]}catch(n){throw t!==0&&r._OrtReleaseRunOptions(t),s.forEach(i=>r._free(i)),n}}}),lc,uc,dc,po,cc,pc,bv=Be(()=>{en(),ja(),lc=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}`)}},uc=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},dc=e=>{e.extra||(e.extra={}),e.extra.session||(e.extra.session={});let r=e.extra.session;r.use_ort_model_bytes_directly||(r.use_ort_model_bytes_directly="1"),e.executionProviders&&e.executionProviders.some(t=>(typeof t=="string"?t:t.name)==="webgpu")&&(e.enableMemPattern=!1)},po=(e,r,t,s)=>{let o=rs(r,s),n=rs(t,s);zt()._OrtAddSessionConfigEntry(e,o,n)!==0&&At(`Can't set a session config entry: ${r} - ${t}.`)},cc=async(e,r,t)=>{for(let s of r){let o=typeof s=="string"?s:s.name,n=[];switch(o){case"webnn":if(o="WEBNN",typeof s!="string"){let p=s==null?void 0:s.deviceType;p&&po(e,"deviceType",p,t)}break;case"webgpu":if(o="JS",typeof s!="string"){let p=s;if(p!=null&&p.preferredLayout){if(p.preferredLayout!=="NCHW"&&p.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${p.preferredLayout}`);po(e,"preferredLayout",p.preferredLayout,t)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${o}`)}let i=rs(o,t),a=n.length,l=0,u=0;if(a>0){l=zt()._malloc(a*zt().PTR_SIZE),t.push(l),u=zt()._malloc(a*zt().PTR_SIZE),t.push(u);for(let p=0;p{let r=zt(),t=0,s=[],o=e||{};dc(o);try{let n=lc(o.graphOptimizationLevel??"all"),i=uc(o.executionMode??"sequential"),a=typeof o.logId=="string"?rs(o.logId,s):0,l=o.logSeverityLevel??2;if(!Number.isInteger(l)||l<0||l>4)throw new Error(`log serverity level is not valid: ${l}`);let u=o.logVerbosityLevel??0;if(!Number.isInteger(u)||u<0||u>4)throw new Error(`log verbosity level is not valid: ${u}`);let p=typeof o.optimizedModelFilePath=="string"?rs(o.optimizedModelFilePath,s):0;if(t=r._OrtCreateSessionOptions(n,!!o.enableCpuMemArena,!!o.enableMemPattern,i,!!o.enableProfiling,0,a,l,u,p),t===0&&At("Can't create session options."),o.executionProviders&&await cc(t,o.executionProviders,s),o.enableGraphCapture!==void 0){if(typeof o.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${o.enableGraphCapture}`);po(t,"enableGraphCapture",o.enableGraphCapture.toString(),s)}if(o.freeDimensionOverrides)for(let[d,c]of Object.entries(o.freeDimensionOverrides)){if(typeof d!="string")throw new Error(`free dimension override name must be a string: ${d}`);if(typeof c!="number"||!Number.isInteger(c)||c<0)throw new Error(`free dimension override value must be a non-negative integer: ${c}`);let f=rs(d,s);r._OrtAddFreeDimensionOverride(t,f,c)!==0&&At(`Can't set a free dimension override: ${d} - ${c}.`)}return o.extra!==void 0&&ri(o.extra,"",new WeakSet,(d,c)=>{po(t,d,c,s)}),[t,s]}catch(n){throw t!==0&&r._OrtReleaseSessionOptions(t)!==0&&At("Can't release session options."),s.forEach(i=>r._free(i)),n}}}),jn,Ts,tn,Na,si,Va,Ua,Wa,ut=Be(()=>{jn=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;case"int4":return 22;case"uint4":return 21;default:throw new Error(`unsupported data type: ${e}`)}},Ts=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";case 22:return"int4";case 21:return"uint4";default:throw new Error(`unsupported data type: ${e}`)}},tn=(e,r)=>{let t=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],s=typeof r=="number"?r:r.reduce((o,n)=>o*n,1);return t>0?Math.ceil(s*t):void 0},Na=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}`)}},si=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}`)}},Va=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",Ua=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint64"||e==="int8"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",Wa=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;case"ml-tensor":return 5;default:throw new Error(`unsupported data location: ${e}`)}}}),Ga,hc=Be(()=>{Pa(),Ga=async e=>{if(typeof e=="string"){let r=await fetch(e);if(!r.ok)throw new Error(`failed to load external data file: ${e}`);let t=r.headers.get("Content-Length"),s=t?parseInt(t,10):0;if(s<1073741824)return new Uint8Array(await r.arrayBuffer());{if(!r.body)throw new Error(`failed to load external data file: ${e}, no response body.`);let o=r.body.getReader(),n;try{n=new ArrayBuffer(s)}catch(a){if(a instanceof RangeError){let l=Math.ceil(s/65536);n=new WebAssembly.Memory({initial:l,maximum:l}).buffer}else throw a}let i=0;for(;;){let{done:a,value:l}=await o.read();if(a)break;let u=l.byteLength;new Uint8Array(n,i,u).set(l),i+=u}return new Uint8Array(n,0,s)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),mc,_c,fc,gc,Ka,wc,vt,Es=Be(()=>{ut(),mc=["V","I","W","E","F"],_c=(e,r)=>{console.log(`[${mc[e]},${new Date().toISOString()}]${r}`)},Ka=(e,r)=>{fc=e,gc=r},wc=(e,r)=>{let t=si(e),s=si(fc);t>=s&&_c(t,typeof r=="function"?r():r)},vt=(...e)=>{gc&&wc(...e)}}),Mc,Nn,Me,ni,bc,yc,vc,mt=Be(()=>{Mc=class{static calcMatMulShape(e,r){return e[1]!==r[0]?void 0:[e[0],r[1]]}},Nn=class{static calcShape(e,r,t=!1){let s=e.length,o=r.length;if(s===0)return r;if(o===0)return e;let n=Math.max(e.length,r.length),i=new Array(n);if(t){if(s<2||o<2)return;let a=Mc.calcMatMulShape([e[s-2],e[s-1]],[r[o-2],r[o-1]]);if(a===void 0)return;[i[n-2],i[n-1]]=a}for(let a=t?3:1;a<=n;a++){let l=s-a<0?1:e[s-a],u=o-a<0?1:r[o-a];if(l!==u&&l>1&&u>1)return;let p=Math.max(l,u);if(l&&u)i[n-a]=Math.max(l,u);else{if(p>1)return;i[n-a]=0}}return i}static isValidBroadcast(e,r){let t=e.length,s=r.length;if(t>s)return!1;for(let o=1;o<=t;o++)if(e[t-o]!==1&&e[t-o]!==r[s-o])return!1;return!0}},Me=class fa{static size(r){return fa.getSizeFromDimensionRange(r,0,r.length)}static convertShape(r,t=4){let s=r.length;if(s===0)return[];let o=new Array(s),n=s-1;for(;n>=0;){if(r[n]%t===0){o[n]=r[n]/t;break}if(t%r[n]!==0)throw new Error("cannot convert shape");o[n]=1,t/=r[n],n--}for(n--;n>=0;n--)o[n]=r[n];return o}static sizeFromDimension(r,t){if(t<0||t>r.length)throw new Error(`invalid dimension of ${t} for sizeFromDimension as Tensor has ${r.length} dimensions.`);return fa.getSizeFromDimensionRange(r,t,r.length)}static sizeToDimension(r,t){if(t<0||t>r.length)throw new Error(`invalid dimension of ${t} for sizeToDimension as Tensor has ${r.length} dimensions.`);return fa.getSizeFromDimensionRange(r,0,t)}static getSizeFromDimensionRange(r,t,s){let o=1;for(let n=t;n=0;--o)s[o]=s[o+1]*r[o+1];return s}static normalizeAxis(r,t){if(r<-t&&r>=t)throw new Error("unsupported axis for this operation.");return r<0?r+t:r}static normalizeAxes(r,t){return r.map(s=>this.normalizeAxis(s,t??r.length))}static sortBasedOnPerm(r,t){return t?t.map(s=>r[s]):r.slice().reverse()}static padShape(r,t){let s=r.length;return r.map((o,n)=>o+t[n]+t[n+s])}static areEqual(r,t){return r.length!==t.length?!1:r.every((s,o)=>s===t[o])}},ni=class Jo{static adjustPoolAttributes(r,t,s,o,n,i){if(!r&&s.length!==t.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(r)for(let a=0;a=s.length?s.push(t[a+2]):s[a]=t[a+2];for(let a=0;a=s[a]||i[a+s.length]>=s[a])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(r,t,s,o,n,i,a){if(a){if(n.length!==2*(r.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(t.length!==r.length-2)throw new Error("length of strides should be the length of data dimensions");if(o.length!==r.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let l=0;l{ut(),Ha=(e,r)=>new(Na(r))(e)}),qa,Xa,Tc,Qa,Ec,Ja,Ya,Za,Pc,Cc,yv=Be(()=>{Es(),qa=(e,r=!0)=>{if(e.byteLength%8!==0)throw new Error("Invalid Uint8Array length - must be a multiple of 8 (BigInt).");let t=e.byteLength/8,s=new BigInt64Array(e.buffer,e.byteOffset,t),o=new Int32Array(t);for(let n=0;n2147483647n||i<-2147483648n)throw new Error(`Overflow occurred when converting BigInt to Int32 at index ${n}: ${i}`);o[n]=Number(i)}return r?new Uint8Array(o.buffer):o},Xa=(e,r=!0)=>{if(e.byteLength%4!==0)throw new Error("Invalid Uint8Array length - must be a multiple of 4 (Int32).");let t=e.byteLength/4,s=new Int32Array(e.buffer,e.byteOffset,t),o=BigInt64Array.from(s,BigInt);return r?new Uint8Array(o.buffer):o},Tc=1,Qa=()=>Tc++,Ec=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),Ja=(e,r)=>{let t=Ec.get(e);if(!t)throw new Error("Unsupported data type.");return r.length>0?Math.ceil(r.reduce((s,o)=>s*o)*t/8):0},Ya=class{constructor(e){this.shouldConvertInt64toInt32=!1,this.isInt64ToInt32Converted=!1;let{sessionId:r,context:t,tensor:s,dataType:o,shape:n,shouldConvertInt64toInt32:i=!1}=e;this.sessionId=r,this.mlContext=t,this.mlTensor=s,this.dataType=o,this.tensorShape=n,this.shouldConvertInt64toInt32=i}get tensor(){return this.mlTensor}get type(){return this.dataType}get shape(){return this.tensorShape}get byteLength(){return Ja(this.dataType,this.tensorShape)}destroy(){vt("verbose",()=>"[WebNN] TensorWrapper.destroy"),this.mlTensor.destroy()}write(e){this.mlContext.writeTensor(this.mlTensor,e)}async read(e,r){if(e){let t=await this.mlContext.readTensor(this.mlTensor),s=Xa(new Uint8Array(t));if(r){(r instanceof ArrayBuffer?new Uint8Array(r):new Uint8Array(r.buffer,r.byteOffset,r.byteLength)).set(s);return}else return s.buffer}else return r?this.mlContext.readTensor(this.mlTensor,r):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(e,r,t){return this.mlContext===e&&this.dataType===r&&this.tensorShape.length===t.length&&this.tensorShape.every((s,o)=>s===t[o])}setIsInt64ToInt32Converted(e){this.isInt64ToInt32Converted=e}},Za=class{constructor(e,r){this.tensorManager=e,this.wrapper=r}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(e,r,t,s){let o=r,n=this.tensorManager.getMLContext(e),i=o==="int64"&&!n.opSupportLimits().input.dataTypes.includes("int64");if(i&&(o="int32",vt("verbose",()=>"[WebNN] TensorIdTracker.ensureTensor: convert dataType from int64 to int32")),this.wrapper){if(this.wrapper.canReuseTensor(n,o,t))return this.wrapper.tensor;if(s){if(this.wrapper.byteLength!==Ja(o,t))throw new Error("Unable to copy data to tensor with different size.");this.activeUpload=new Uint8Array(await this.wrapper.read())}this.tensorManager.releaseTensor(this.wrapper)}let a=typeof MLTensorUsage>"u"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(e,o,t,a,!0,!0,i),s&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(e){let r=e;if(this.wrapper)if(this.wrapper.shouldConvertInt64toInt32&&(r=qa(e,!0),this.wrapper.setIsInt64ToInt32Converted(!0)),r.byteLength===this.wrapper.byteLength){this.wrapper.write(r);return}else vt("verbose",()=>"Data size does not match tensor size. Releasing tensor."),this.releaseTensor();this.activeUpload?this.activeUpload.set(r):this.activeUpload=new Uint8Array(r)}async download(e){var r,t,s;if(this.activeUpload){let o=(r=this.wrapper)!=null&&r.isInt64ToInt32Converted?Xa(this.activeUpload):this.activeUpload;if(e){e instanceof ArrayBuffer?new Uint8Array(e).set(o):new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(o);return}else return o.buffer}if(!this.wrapper)throw new Error("Tensor has not been created.");return e?this.wrapper.read((t=this.wrapper)==null?void 0:t.shouldConvertInt64toInt32,e):this.wrapper.read((s=this.wrapper)==null?void 0:s.shouldConvertInt64toInt32)}},Pc=class{constructor(e){this.backend=e,this.tensorTrackersById=new Map,this.freeTensors=[],this.externalTensors=new Set}getMLContext(e){let r=this.backend.getMLContext(e);if(!r)throw new Error("MLContext not found for session.");return r}reserveTensorId(){let e=Qa();return this.tensorTrackersById.set(e,new Za(this)),e}releaseTensorId(e){let r=this.tensorTrackersById.get(e);r&&(this.tensorTrackersById.delete(e),r.tensorWrapper&&this.releaseTensor(r.tensorWrapper))}async ensureTensor(e,r,t,s,o){vt("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${r}, dataType: ${t}, shape: ${s}, copyOld: ${o}}`);let n=this.tensorTrackersById.get(r);if(!n)throw new Error("Tensor not found.");return n.ensureTensor(e,t,s,o)}upload(e,r){let t=this.tensorTrackersById.get(e);if(!t)throw new Error("Tensor not found.");t.upload(r)}async download(e,r){vt("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${e}, dstBuffer: ${r==null?void 0:r.byteLength}}`);let t=this.tensorTrackersById.get(e);if(!t)throw new Error("Tensor not found.");return t.download(r)}releaseTensorsForSession(e){for(let r of this.freeTensors)r.sessionId===e&&r.destroy();this.freeTensors=this.freeTensors.filter(r=>r.sessionId!==e)}registerTensor(e,r,t,s){let o=this.getMLContext(e),n=Qa(),i=new Ya({sessionId:e,context:o,tensor:r,dataType:t,shape:s});return this.tensorTrackersById.set(n,new Za(this,i)),this.externalTensors.add(i),n}async getCachedTensor(e,r,t,s,o,n,i=!1){let a=this.getMLContext(e);for(let[u,p]of this.freeTensors.entries())if(p.canReuseTensor(a,r,t)){vt("verbose",()=>`[WebNN] Reusing tensor {dataType: ${r}, shape: ${t}}`);let d=this.freeTensors.splice(u,1)[0];return d.sessionId=e,d}vt("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${r}, shape: ${t}}`);let l=await a.createTensor({dataType:r,shape:t,dimensions:t,usage:s,writable:o,readable:n});return new Ya({sessionId:e,context:a,tensor:l,dataType:r,shape:t,shouldConvertInt64toInt32:i})}releaseTensor(e){this.externalTensors.has(e)&&this.externalTensors.delete(e),this.freeTensors.push(e)}},Cc=(...e)=>new Pc(...e)}),oi,Sc,$c,vv=Be(()=>{ut(),en(),xc(),yv(),Es(),oi=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),Sc=(e,r)=>{if(e===r)return!0;if(e===void 0||r===void 0)return!1;let t=Object.keys(e).sort(),s=Object.keys(r).sort();return t.length===s.length&&t.every((o,n)=>o===s[n]&&e[o]===r[o])},$c=class{constructor(e){this.tensorManager=Cc(this),this.mlContextBySessionId=new Map,this.sessionIdsByMLContext=new Map,this.mlContextCache=[],this.sessionGraphInputs=new Map,this.temporaryGraphInputs=[],this.temporarySessionTensorIds=new Map,Ka(e.logLevel,!!e.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(e){vt("verbose",()=>`[WebNN] onRunStart {sessionId: ${e}}`),this.activeSessionId=e}onRunEnd(e){vt("verbose",()=>`[WebNN] onRunEnd {sessionId: ${e}}`);let r=this.temporarySessionTensorIds.get(e);if(r){for(let t of r)vt("verbose",()=>`[WebNN] releasing temporary tensor {tensorId: ${t}}`),this.tensorManager.releaseTensorId(t);this.temporarySessionTensorIds.delete(e),this.activeSessionId=void 0}}async createMLContext(e){if(e instanceof GPUDevice){let t=this.mlContextCache.findIndex(s=>s.gpuDevice===e);if(t!==-1)return this.mlContextCache[t].mlContext;{let s=await navigator.ml.createContext(e);return this.mlContextCache.push({gpuDevice:e,mlContext:s}),s}}else if(e===void 0){let t=this.mlContextCache.findIndex(s=>s.options===void 0&&s.gpuDevice===void 0);if(t!==-1)return this.mlContextCache[t].mlContext;{let s=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:s}),s}}let r=this.mlContextCache.findIndex(t=>Sc(t.options,e));if(r!==-1)return this.mlContextCache[r].mlContext;{let t=await navigator.ml.createContext(e);return this.mlContextCache.push({options:e,mlContext:t}),t}}registerMLContext(e,r){this.mlContextBySessionId.set(e,r);let t=this.sessionIdsByMLContext.get(r);t||(t=new Set,this.sessionIdsByMLContext.set(r,t)),t.add(e),this.temporaryGraphInputs.length>0&&(this.sessionGraphInputs.set(e,this.temporaryGraphInputs),this.temporaryGraphInputs=[])}onReleaseSession(e){this.sessionGraphInputs.delete(e);let r=this.mlContextBySessionId.get(e);if(!r)return;this.tensorManager.releaseTensorsForSession(e),this.mlContextBySessionId.delete(e);let t=this.sessionIdsByMLContext.get(r);if(t.delete(e),t.size===0){this.sessionIdsByMLContext.delete(r);let s=this.mlContextCache.findIndex(o=>o.mlContext===r);s!==-1&&this.mlContextCache.splice(s,1)}}getMLContext(e){return this.mlContextBySessionId.get(e)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(e){vt("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,r,t,s,o){let n=oi.get(t);if(!n)throw new Error(`Unsupported ONNX data type: ${t}`);return this.tensorManager.ensureTensor(e??this.currentSessionId,r,n,s,o)}async createTemporaryTensor(e,r,t){vt("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${r}, shape: ${t}}`);let s=oi.get(r);if(!s)throw new Error(`Unsupported ONNX data type: ${r}`);let o=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(e,o,s,t,!1);let n=this.temporarySessionTensorIds.get(e);return n?n.push(o):this.temporarySessionTensorIds.set(e,[o]),o}uploadTensor(e,r){if(!zt().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");vt("verbose",()=>`[WebNN] uploadTensor {tensorId: ${e}, data: ${r.byteLength}}`),this.tensorManager.upload(e,r)}async downloadTensor(e,r){return this.tensorManager.download(e,r)}createMLTensorDownloader(e,r){return async()=>{let t=await this.tensorManager.download(e);return Ha(t,r)}}registerMLTensor(e,r,t,s){let o=oi.get(t);if(!o)throw new Error(`Unsupported ONNX data type: ${t}`);let n=this.tensorManager.registerTensor(e,r,o,s);return vt("verbose",()=>`[WebNN] registerMLTensor {tensor: ${r}, dataType: ${o}, dimensions: ${s}} -> {tensorId: ${n}}`),n}registerMLConstant(e,r,t,s,o,n,i=!1){if(!n)throw new Error("External mounted files are not available.");let a=e;e.startsWith("./")&&(a=e.substring(2));let l=n.get(a);if(!l)throw new Error(`File with name ${a} not found in preloaded files.`);if(r+t>l.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let u=l.slice(r,r+t).buffer,p;switch(o.dataType){case"float32":p=new Float32Array(u);break;case"float16":p=typeof Float16Array<"u"&&Float16Array.from?new Float16Array(u):new Uint16Array(u);break;case"int32":p=new Int32Array(u);break;case"uint32":p=new Uint32Array(u);break;case"int64":i?(p=qa(new Uint8Array(u),!1),o.dataType="int32"):p=new BigInt64Array(u);break;case"uint64":p=new BigUint64Array(u);break;case"int8":p=new Int8Array(u);break;case"int4":case"uint4":case"uint8":p=new Uint8Array(u);break;default:throw new Error(`Unsupported data type: ${o.dataType} in creating WebNN Constant from external data.`)}return vt("verbose",()=>`[WebNN] registerMLConstant {dataType: ${o.dataType}, shape: ${o.shape}}} ${i?"(Note: it was int64 data type and registered to int32 as workaround)":""}`),s.constant(o,p)}registerGraphInput(e){this.temporaryGraphInputs.push(e)}isGraphInput(e,r){let t=this.sessionGraphInputs.get(e);return t?t.includes(r):!1}isInt64Supported(e){var r;return!!((r=this.mlContextBySessionId.get(e))!=null&&r.opSupportLimits().input.dataTypes.includes("int64"))}flush(){}}}),el=Be(()=>{}),tl,ii,ai,kc,Ic,rl,sl,Ac,Fc,xv=Be(()=>{Es(),el(),tl=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]]),ii=[],ai=e=>Math.ceil(Number(e)/16)*16,kc=e=>{for(let r=0;rIc++,sl=async(e,r,t,s)=>{let o=ai(t),n=e.device.createBuffer({size:o,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let i=e.getCommandEncoder();e.endComputePass(),i.copyBufferToBuffer(r,0,n,0,o),e.flush(),await n.mapAsync(GPUMapMode.READ);let a=n.getMappedRange();if(s){let l=s();return l.set(new Uint8Array(a,0,t)),l}else return new Uint8Array(a.slice(0,t))}finally{n.destroy()}},Ac=class{constructor(e){this.backend=e,this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.buffersPending=[],this.capturedPendingBuffers=new Map;for(let[r]of tl)ii.push(r),this.freeBuffers.set(r,[]),this.freeUniformBuffers.set(r,[]);this.sessionCount=0}upload(e,r){let t=r.buffer,s=r.byteOffset,o=r.byteLength,n=ai(o),i=this.storageCache.get(e);if(!i)throw new Error("gpu data for uploading does not exist");if(Number(i.originalSize)!==o)throw new Error(`inconsistent data size. gpu data size=${i.originalSize}, data size=${o}`);let a=this.backend.device.createBuffer({mappedAtCreation:!0,size:n,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),l=a.getMappedRange();new Uint8Array(l).set(new Uint8Array(t,s,o)),a.unmap();let u=this.backend.device.createCommandEncoder();u.copyBufferToBuffer(a,0,i.gpuData.buffer,0,n),this.backend.device.queue.submit([u.finish()]),a.destroy(),vt("verbose",()=>`[WebGPU] GpuDataManager.upload(id=${e})`)}memcpy(e,r){let t=this.storageCache.get(e);if(!t)throw new Error("source gpu data for memcpy does not exist");let s=this.storageCache.get(r);if(!s)throw new Error("destination gpu data for memcpy does not exist");if(t.originalSize!==s.originalSize)throw new Error("inconsistent source and destination gpu data size");let o=ai(t.originalSize),n=this.backend.getCommandEncoder();this.backend.endComputePass(),n.copyBufferToBuffer(t.gpuData.buffer,0,s.gpuData.buffer,0,o)}registerExternalBuffer(e,r,t){let s;if(t){if(s=t[0],e===t[1])return vt("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${r}) => id=${s}, buffer is the same, skip.`),s;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!`)}else s=rl();return this.storageCache.set(s,{gpuData:{id:s,type:0,buffer:e},originalSize:r}),vt("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${r}) => id=${s}, registered.`),s}unregisterExternalBuffer(e){e!==void 0&&(this.storageCache.delete(e),vt("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${e}`))}create(e,r=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let t=kc(e),s,o=(r&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,n=(r&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(o||n){let a=(o?this.freeBuffers:this.freeUniformBuffers).get(t);a?a.length>0?s=a.pop():s=this.backend.device.createBuffer({size:t,usage:r}):s=this.backend.device.createBuffer({size:t,usage:r})}else s=this.backend.device.createBuffer({size:t,usage:r});let i={id:rl(),type:0,buffer:s};return this.storageCache.set(i.id,{gpuData:i,originalSize:Number(e)}),vt("verbose",()=>`[WebGPU] GpuDataManager.create(size=${e}) => id=${i.id}`),i}get(e){var r;return(r=this.storageCache.get(e))==null?void 0:r.gpuData}release(e){let r=typeof e=="bigint"?Number(e):e,t=this.storageCache.get(r);if(!t){if(this.storageCache.size===0)return 0;throw new Error("releasing data does not exist")}return vt("verbose",()=>`[WebGPU] GpuDataManager.release(id=${r}), gpuDataId=${t.gpuData.id}`),this.storageCache.delete(r),this.buffersPending.push(t.gpuData.buffer),t.originalSize}async download(e,r){let t=this.storageCache.get(Number(e));if(!t)throw new Error("data does not exist");await sl(this.backend,t.gpuData.buffer,t.originalSize,r)}refreshPendingBuffers(){if(this.buffersPending.length!==0)if(this.backend.sessionStatus==="default"){for(let e of this.buffersPending){let r=tl.get(e.size);if((e.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE){let t=this.freeBuffers.get(e.size)||[];r===void 0||t.length>=r?e.destroy():t.push(e)}else if((e.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM){let t=this.freeUniformBuffers.get(e.size)||[];r===void 0||t.length>=r?e.destroy():t.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 r of this.buffersPending)e.push(r);this.buffersPending=[]}}dispose(){this.freeBuffers.forEach(e=>{e.forEach(r=>{r.destroy()})}),this.freeUniformBuffers.forEach(e=>{e.forEach(r=>{r.destroy()})}),this.storageCache.forEach(e=>{e.gpuData.buffer.destroy()}),this.capturedPendingBuffers.forEach(e=>{e.forEach(r=>{r.destroy()})}),this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.capturedPendingBuffers=new Map}onCreateSession(){this.sessionCount+=1}onReleaseSession(e){let r=this.capturedPendingBuffers.get(e);r&&(r.forEach(t=>{t.destroy()}),this.capturedPendingBuffers.delete(e)),this.sessionCount-=1,this.sessionCount===0&&(vt("warning",()=>"[WebGPU] Clearing webgpu buffer cache"),this.storageCache.forEach(t=>{t.gpuData.buffer.destroy()}),this.storageCache=new Map)}},Fc=(...e)=>new Ac(...e)}),Oc,St,Xt=Be(()=>{Oc=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}},St=e=>new Oc(e)}),Vn,li,lr,yr,st,Kt,nl,Un,Ls,et,ho,Pe,Ye,Dc,ol,Lc,zc,ft=Be(()=>{ut(),mt(),Vn=64,li=(e,r)=>{if(r===3)throw new Error("vec3 has same alignment as vec4, use vec4 instead");switch(Number(e)){case 10:return r>1?`vec${r}`:"f16";case 1:return r>1?`vec${r}`:"f32";case 6:return r>1?`vec${r}`:"i32";case 12:return r>1?`vec${r}`:"u32";case 7:if(r>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","i32"];case 13:if(r>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","u32"];case 9:if(r!==4)throw new Error("bool must be vec4");return["u32","vec4"];case 22:return"i32";case 21:return"u32";default:throw new Error(`Unknown data type: ${e}`)}},lr=(e,r=1)=>{let t=li(e,r);return typeof t=="string"?t:t[0]},yr=(e,r=1)=>{let t=li(e,r);return typeof t=="string"?t:t[1]},st=(...e)=>{let r=[];return e.forEach(t=>{t.length!==0&&r.push({type:12,data:t},{type:12,data:Me.computeStrides(t)})}),r},Kt=e=>e%4===0?4:e%2===0?2:1,nl=(e="f32",r,t="0")=>!r||r===1?`${e}(${t})`:`vec${r}<${e}>(${t})`,Un=(e,r,t)=>e==="f32"?t:r===1?`f32(${t})`:`vec${r}(${t})`,Ls=(e,r)=>r===4?`(${e}.x + ${e}.y + ${e}.z + ${e}.w)`:r===2?`(${e}.x + ${e}.y)`:r===3?`(${e}.x + ${e}.y + ${e}.z)`:e,et=(e,r,t,s)=>e.startsWith("uniforms.")&&t>4?typeof r=="string"?s==="f16"?`${e}[(${r}) / 8][(${r}) % 8 / 4][(${r}) % 8 % 4]`:`${e}[(${r}) / 4][(${r}) % 4]`:s==="f16"?`${e}[${Math.floor(r/8)}][${Math.floor(r%8/4)}][${r%8%4}]`:`${e}[${Math.floor(r/4)}][${r%4}]`:t>1?`${e}[${r}]`:e,ho=(e,r,t,s,o)=>{let n=typeof t=="number",i=n?t:t.length,a=[...new Array(i).keys()],l=i<2?"u32":i<=4?`vec${i}`:`array`,u=li(r,o),p=typeof u=="string"?u:u[1],d=typeof u=="string"?u:u[0],c={indices:l,value:p,storage:d,tensor:r},f=V=>typeof V=="string"?V:`${V}u`,_={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},T=n?"uniforms.":"",k=`${T}${e}_shape`,w=`${T}${e}_strides`,g="";for(let V=0;V ${c.indices} { + var indices: ${c.indices}; + var current = offset; + ${g} + return indices; + }`,E=V=>(_.offsetToIndices=!0,i<2?V:`o2i_${e}(${V})`),y=[];if(i>=2)for(let V=i-1;V>=0;V--)y.push(`${et(w,V,i)} * (indices[${V}])`);let M=i<2?"":` + fn i2o_${e}(indices: ${c.indices}) -> u32 { + return ${y.join("+")}; + }`,v=V=>(_.indicesToOffset=!0,i<2?V:`i2o_${e}(${V})`),C=(...V)=>i===0?"0u":`${c.indices}(${V.map(f).join(",")})`,A=(V,F)=>i<2?`${V}`:`${et(V,F,i)}`,B=(V,F,W)=>i<2?`${V}=${W};`:`${et(V,F,i)}=${W};`,K={},G=(V,F)=>{_.broadcastedIndicesToOffset=!0;let W=`${F.name}broadcastedIndicesTo${e}Offset`;if(W in K)return`${W}(${V})`;let re=[];for(let _e=i-1;_e>=0;_e--){let se=F.indicesGet("outputIndices",_e+F.rank-i);re.push(`${A(w,_e)} * (${se} % ${A(k,_e)})`)}return K[W]=`fn ${W}(outputIndices: ${F.type.indices}) -> u32 { + return ${re.length>0?re.join("+"):"0u"}; + }`,`${W}(${V})`},j=(V,F)=>(()=>{if(c.storage===c.value)return`${e}[${V}]=${F};`;if(c.storage==="vec2"&&c.value==="i32")return`${e}[${V}]=vec2(u32(${F}), select(0u, 0xFFFFFFFFu, ${F} < 0));`;if(c.storage==="vec2"&&c.value==="u32")return`${e}[${V}]=vec2(u32(${F}), 0u);`;if(c.storage==="u32"&&c.value==="vec4")return`${e}[${V}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${F}));`;throw new Error(`not supported combination of storage type ${c.storage} and value type ${c.value} yet`)})(),ee=V=>(()=>{if(c.storage===c.value)return`${e}[${V}]`;if(c.storage==="vec2"&&c.value==="i32")return`i32(${e}[${V}].x)`;if(c.storage==="vec2"&&c.value==="u32")return`u32(${e}[${V}].x)`;if(c.storage==="u32"&&c.value==="vec4")return`vec4(bool(${e}[${V}] & 0xFFu), bool(${e}[${V}] & 0xFF00u), bool(${e}[${V}] & 0xFF0000u), bool(${e}[${V}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${c.storage} and value type ${c.value} yet`)})(),H=i<2?"":` + fn get_${e}ByIndices(indices: ${c.indices}) -> ${p} { + return ${ee(`i2o_${e}(indices)`)}; + }`,Z=i<2?"":(()=>{let V=a.map(W=>`d${W}: u32`).join(", "),F=a.map(W=>`d${W}`).join(", ");return` + fn get_${e}(${V}) -> ${p} { + return get_${e}ByIndices(${C(F)}); + }`})(),X=(...V)=>{if(V.length!==i)throw new Error(`indices length must be ${i}`);let F=V.map(f).join(",");return i===0?ee("0u"):i===1?ee(F[0]):(_.get=!0,_.getByIndices=!0,_.indicesToOffset=!0,`get_${e}(${F})`)},oe=V=>i<2?ee(V):(_.getByIndices=!0,_.indicesToOffset=!0,`get_${e}ByIndices(${V})`),me=i<2?"":` + fn set_${e}ByIndices(indices: ${c.indices}, value: ${p}) { + ${j(`i2o_${e}(indices)`,"value")} + }`,ae=i<2?"":(()=>{let V=a.map(W=>`d${W}: u32`).join(", "),F=a.map(W=>`d${W}`).join(", ");return` + fn set_${e}(${V}, value: ${p}) { + set_${e}ByIndices(${C(F)}, value); + }`})();return{impl:()=>{let V=[],F=!1;return _.offsetToIndices&&(V.push(S),F=!0),_.indicesToOffset&&(V.push(M),F=!0),_.broadcastedIndicesToOffset&&(Object.values(K).forEach(W=>V.push(W)),F=!0),_.set&&(V.push(ae),F=!0),_.setByIndices&&(V.push(me),F=!0),_.get&&(V.push(Z),F=!0),_.getByIndices&&(V.push(H),F=!0),!n&&F&&V.unshift(`const ${k} = ${c.indices}(${t.join(",")});`,`const ${w} = ${c.indices}(${Me.computeStrides(t).join(",")});`),V.join(` +`)},type:c,offsetToIndices:E,indicesToOffset:v,broadcastedIndicesToOffset:G,indices:C,indicesGet:A,indicesSet:B,set:(...V)=>{if(V.length!==i+1)throw new Error(`indices length must be ${i}`);let F=V[i];if(typeof F!="string")throw new Error("value must be string");let W=V.slice(0,i).map(f).join(",");return i===0?j("0u",F):i===1?j(W[0],F):(_.set=!0,_.setByIndices=!0,_.indicesToOffset=!0,`set_${e}(${W}, ${F})`)},setByOffset:j,setByIndices:(V,F)=>i<2?j(V,F):(_.setByIndices=!0,_.indicesToOffset=!0,`set_${e}ByIndices(${V}, ${F});`),get:X,getByOffset:ee,getByIndices:oe,usage:s,name:e,strides:w,shape:k,rank:i}},Pe=(e,r,t,s=1)=>ho(e,r,t,"input",s),Ye=(e,r,t,s=1)=>ho(e,r,t,"output",s),Dc=(e,r,t)=>ho(e,r,t,"atomicOutput",1),ol=(e,r,t,s=1)=>ho(e,r,t,"internal",s),Lc=class{constructor(e,r){this.normalizedDispatchGroup=e,this.limits=r,this.internalVariables=[],this.variables=[],this.uniforms=[],this.variableIndex=0}guardAgainstOutOfBoundsWorkgroupSizes(e){return`if (global_idx >= ${typeof e=="number"?`${e}u`:e}) { return; }`}mainStart(e=Vn){let r=typeof e=="number"?e:e[0],t=typeof e=="number"?1:e[1],s=typeof e=="number"?1:e[2];if(r>this.limits.maxComputeWorkgroupSizeX||t>this.limits.maxComputeWorkgroupSizeY||s>this.limits.maxComputeWorkgroupSizeZ)throw new Error(`workgroup size [${r}, ${t}, ${s}] exceeds the maximum workgroup size [${this.limits.maxComputeWorkgroupSizeX}, ${this.limits.maxComputeWorkgroupSizeY}, ${this.limits.maxComputeWorkgroupSizeZ}].`);if(r*t*s>this.limits.maxComputeInvocationsPerWorkgroup)throw new Error(`workgroup size [${r}, ${t}, ${s}] exceeds the maximum workgroup invocations ${this.limits.maxComputeInvocationsPerWorkgroup}.`);let o=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1,n=o?`@builtin(global_invocation_id) global_id : vec3, + @builtin(workgroup_id) workgroup_id : vec3, + @builtin(local_invocation_index) local_idx : u32, + @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`,i=o?`let global_idx = global_id.x; + let workgroup_index = workgroup_id.x;`:`let workgroup_index = workgroup_id.z * num_workgroups[0] * num_workgroups[1] + + workgroup_id.y * num_workgroups[0] + workgroup_id.x; + let global_idx = workgroup_index * ${r*t*s}u + local_idx;`;return`@compute @workgroup_size(${r}, ${t}, ${s}) + fn main(${n}) { + ${i} + `}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,r){if(e.usage==="internal")throw new Error("cannot use internal variable with declareVariable(). use registerInternalVariables() instead.");this.variables.push(e),this.appendVariableUniforms(e);let t=e.usage==="input"?"read":"read_write",s=e.usage==="atomicOutput"?"atomic":e.type.storage;return`@group(0) @binding(${r}) var ${e.name}: array<${s}>;`}declareVariables(...e){return e.map(r=>this.declareVariable(r,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(r=>this.registerInternalVariable(r)),this}registerUniform(e,r,t=1){return this.uniforms.push({name:e,type:r,length:t}),this}registerUniforms(e){return this.uniforms=this.uniforms.concat(e),this}uniformDeclaration(){if(this.uniforms.length===0)return"";let e=[];for(let{name:r,type:t,length:s}of this.uniforms)if(s&&s>4)t==="f16"?e.push(`@align(16) ${r}:array, ${Math.ceil(s/8)}>`):e.push(`${r}:array, ${Math.ceil(s/4)}>`);else{let o=s==null||s===1?t:`vec${s}<${t}>`;e.push(`${r}:${o}`)}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=r=>[12,10,1,6][["u32","f16","f32","i32"].indexOf(r)];return this.uniforms.map(r=>[e(r.type),r.length??1])}},zc=(e,r)=>new Lc(e,r)}),Bc,il,Rc,jc,Nc,Vc,Lr,Uc,Wc,zs=Be(()=>{ut(),mt(),Xt(),ft(),Bc=(e,r)=>{if(!e||e.length!==1)throw new Error("Transpose requires 1 input.");if(r.length!==0&&r.length!==e[0].dims.length)throw new Error(`perm size ${r.length} does not match input rank ${e[0].dims.length}`)},il=(e,r)=>r.length!==0?r:[...new Array(e).keys()].reverse(),Rc=(e,r)=>Me.sortBasedOnPerm(e,il(e.length,r)),jc=(e,r,t,s)=>{let o=`fn perm(i: ${s.type.indices}) -> ${t.type.indices} { + var a: ${t.type.indices};`;for(let n=0;n{let t=[],s=[];for(let o=0;o{let t=0;for(let s=0;s{let t=e.dataType,s=e.dims.length,o=il(s,r),n=Rc(e.dims,o),i=e.dims,a=n,l=s<2||Vc(o,e.dims),u;if(l)return u=_=>{let T=Pe("input",t,i,4),k=Ye("output",t,a,4);return` + ${_.registerUniform("output_size","u32").declareVariables(T,k)} + ${_.mainStart()} + ${_.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + output[global_idx] = input[global_idx]; + }`},{name:"TransposeCopy",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let _=Me.size(n);return{outputs:[{dims:n,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(_/64/4)},programUniforms:[{type:12,data:Math.ceil(_/4)}]}},getShaderSource:u};let{newShape:p,newPerm:d}=Nc(e.dims,o),c=Me.areEqual(d,[2,3,1]),f=Me.areEqual(d,[3,1,2]);if(p.length===2||c||f){i=c?[p[0],p[1]*p[2]]:f?[p[0]*p[1],p[2]]:p,a=[i[1],i[0]];let _=16;return u=T=>{let k=Pe("a",t,i.length),w=Ye("output",t,a.length);return` + ${T.registerUniform("output_size","u32").declareVariables(k,w)} + var tile : array, ${_}>; + ${T.mainStart([_,_,1])} + let stride = (uniforms.output_shape[1] - 1) / ${_} + 1; + let workgroup_id_x = workgroup_index % stride; + let workgroup_id_y = workgroup_index / stride; + let input_col = workgroup_id_y * ${_}u + local_id.x; + let input_row = workgroup_id_x * ${_}u + local_id.y; + if (input_row < uniforms.a_shape[0] && input_col < uniforms.a_shape[1]) { + tile[local_id.y][local_id.x] = ${k.getByIndices(`${k.type.indices}(input_row, input_col)`)}; + } + workgroupBarrier(); + + let output_col = workgroup_id_x * ${_}u + local_id.x; + let output_row = workgroup_id_y * ${_}u + local_id.y; + if (output_row < uniforms.output_shape[0] && output_col < uniforms.output_shape[1]) { + ${w.setByIndices(`${w.type.indices}(output_row, output_col)`,"tile[local_id.x][local_id.y]")} + } + }`},{name:"TransposeShared",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let T=Me.size(n);return{outputs:[{dims:n,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(a[1]/_),y:Math.ceil(a[0]/_)},programUniforms:[{type:12,data:T},...st(i,a)]}},getShaderSource:u}}return u=_=>{let T=Pe("a",t,i.length),k=Ye("output",t,a.length);return` + ${_.registerUniform("output_size","u32").declareVariables(T,k)} + + ${jc(o,s,T,k)} + + ${_.mainStart()} + ${_.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${k.offsetToIndices("global_idx")}; + let aIndices = perm(indices); + + ${k.setByOffset("global_idx",T.getByIndices("aIndices"))} + }`},{name:"Transpose",shaderCache:{hint:`${r}`,inputDependencies:["rank"]},getRunData:()=>{let _=Me.size(n);return{outputs:[{dims:n,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(_/64)},programUniforms:[{type:12,data:_},...st(i,a)]}},getShaderSource:u}},Uc=(e,r)=>{Bc(e.inputs,r.perm),e.compute(Lr(e.inputs[0],r.perm))},Wc=e=>St({perm:e.perm})}),Gc,Kc,Hc,qc,Xc,Qc,Jc,Yc,Zc,ep,ss,tp,rp,sp,np,op,ip,ap,lp,up,dp,Tv=Be(()=>{ut(),mt(),ft(),ll(),zs(),Gc={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"},Kc={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"},Hc={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},qc={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},Xc=(e,r)=>{let t=[];for(let s=r-e;s{let t=[],s=e.length;for(let n=0;ne[n]);return[t,o]},Jc=(e,r)=>{let t=e.length+r.length,s=[],o=0;for(let n=0;n{for(let t=0;t{let t=[];if(!Yc(e,r)){for(let s=0;st.push(s))}return t},ep=(e,r,t,s,o,n,i)=>{let a=t[0].dims,l=Me.size(n),u=Me.size(i),p=Pe("_A",t[0].dataType,a),d=Ye("output",o,n),c=64;l===1&&(c=256);let f=` + var aBestValues : array; + `,_=T=>` + ${T.registerUniform("reduceSize","u32").declareVariables(p,d)} + ${f} + fn DIV_CEIL(a : u32, b : u32) -> u32 { + return ((a - 1u) / b + 1u); + } + ${T.mainStart(c)} + + let outputIndex = global_idx / ${c}; + let offset = outputIndex * uniforms.reduceSize; + + var bestValue = f32(${Hc[s]}); + let Length = uniforms.reduceSize; + for (var k = local_idx; k < Length; k = k + ${c}) { + let candidate = f32(${p.getByOffset("offset + k")}); + bestValue = ${Gc[s]}; + } + aBestValues[local_idx] = bestValue; + workgroupBarrier(); + + var reduceSize = min(Length, ${c}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 = ${Kc[s]}; + aBestValues[local_idx] = bestValue; + } + reduceSize = interval; + workgroupBarrier(); + } + + if (local_idx == 0u) { + ${d.setByOffset("outputIndex",`${s==="mean"?`${d.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${d.type.storage}(${qc[s]})`}`)}; + } + }`;return{name:e,shaderCache:{hint:`${r};${c}`,inputDependencies:["type"]},getShaderSource:_,getRunData:()=>({outputs:[{dims:n,dataType:o}],dispatchGroup:{x:l},programUniforms:[{type:12,data:u}]})}},ss=(e,r,t,s)=>{let o=e.inputs.length===1?t:al(e.inputs,t),n=o.axes;n.length===0&&!o.noopWithEmptyAxes&&(n=e.inputs[0].dims.map((f,_)=>_));let i=Me.normalizeAxes(n,e.inputs[0].dims.length),a=i,l=e.inputs[0],u=Zc(a,e.inputs[0].dims.length);u.length>0&&(l=e.compute(Lr(e.inputs[0],u),{inputs:[0],outputs:[-1]})[0],a=Xc(a.length,l.dims.length));let[p,d]=Qc(l.dims,a),c=p;o.keepDims&&(c=Jc(p,i)),e.compute(ep(r,o.cacheKey,[l],s,e.inputs[0].dataType,c,d),{inputs:[l]})},tp=(e,r)=>{ss(e,"ReduceMeanShared",r,"mean")},rp=(e,r)=>{ss(e,"ReduceL1Shared",r,"l1")},sp=(e,r)=>{ss(e,"ReduceL2Shared",r,"l2")},np=(e,r)=>{ss(e,"ReduceLogSumExpShared",r,"logSumExp")},op=(e,r)=>{ss(e,"ReduceMaxShared",r,"max")},ip=(e,r)=>{ss(e,"ReduceMinShared",r,"min")},ap=(e,r)=>{ss(e,"ReduceProdShared",r,"prod")},lp=(e,r)=>{ss(e,"ReduceSumShared",r,"sum")},up=(e,r)=>{ss(e,"ReduceSumSquareShared",r,"sumSquare")},dp=(e,r)=>{ss(e,"ReduceLogSumShared",r,"logSum")}}),ns,cp,ui,al,os,pp,hp,mp,_p,fp,gp,wp,Mp,bp,yp,is,vp,xp,Tp,Ep,Pp,Cp,Sp,$p,kp,Ip,ll=Be(()=>{ut(),mt(),Xt(),ft(),Tv(),ns=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.")},cp=e=>["","",`var value = ${e.getByIndices("input_indices")};`,""],ui=(e,r,t,s,o,n,i=!1,a=!1)=>{let l=[],u=t[0].dims,p=u.length,d=Me.normalizeAxes(o,p),c=!a&&d.length===0;u.forEach((T,k)=>{c||d.indexOf(k)>=0?i&&l.push(1):l.push(T)});let f=l.length,_=Me.size(l);return{name:e,shaderCache:r,getShaderSource:T=>{let k=[],w=Pe("_A",t[0].dataType,p),g=Ye("output",n,f),S=s(w,g,d),E=S[2];for(let y=0,M=0;y=0?(i&&M++,E=`for(var j${y}: u32 = 0; j${y} < ${u[y]}; j${y}++) { + ${S[2].includes("last_index")?`let last_index = j${y};`:""} + ${w.indicesSet("input_indices",y,`j${y}`)} + ${E} + }`):(k.push(`${w.indicesSet("input_indices",y,g.indicesGet("output_indices",M))};`),M++);return` + + ${T.registerUniform("output_size","u32").declareVariables(w,g)} + + ${T.mainStart()} + ${T.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + var input_indices: ${w.type.indices}; + let output_indices = ${g.offsetToIndices("global_idx")}; + + ${k.join(` +`)} + ${S[0]} // init ops for reduce max/min + ${S[1]} + ${E} + ${S[3]} + ${S.length===4?g.setByOffset("global_idx","value"):S.slice(4).join(` +`)} + }`},getRunData:()=>({outputs:[{dims:l,dataType:n}],dispatchGroup:{x:Math.ceil(_/64)},programUniforms:[{type:12,data:_},...st(u,l)]})}},al=(e,r)=>{let t=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach(s=>t.push(Number(s))),St({axes:t,keepDims:r.keepDims,noopWithEmptyAxes:r.noopWithEmptyAxes})},os=(e,r,t,s)=>{let o=e.inputs,n=o.length===1?t:al(o,t);e.compute(ui(r,{hint:n.cacheKey,inputDependencies:["rank"]},[o[0]],n.noopWithEmptyAxes&&n.axes.length===0?cp:s,n.axes,o[0].dataType,n.keepDims,n.noopWithEmptyAxes),{inputs:[0]})},pp=(e,r)=>{ns(e.inputs),os(e,"ReduceLogSum",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += ${t.getByIndices("input_indices")};`,"value = log(value);"])},hp=(e,r)=>{ns(e.inputs),os(e,"ReduceL1",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += abs(${t.getByIndices("input_indices")});`,""])},mp=(e,r)=>{ns(e.inputs),os(e,"ReduceL2",r,(t,s)=>[`var t = ${s.type.value}(0); var value = ${s.type.value}(0);`,"",`t = ${t.getByIndices("input_indices")}; value += (t * t);`,"value = sqrt(value);"])},_p=(e,r)=>{ns(e.inputs),os(e,"ReduceLogSumExp",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += exp(${t.getByIndices("input_indices")});`,"value = log(value);"])},fp=(e,r)=>{ns(e.inputs),os(e,"ReduceMax",r,(t,s,o)=>{let n=[];for(let i=0;i=0||o.length===0)&&n.push(t.indicesSet("input_indices",i,0));return[`${n.join(` +`)}`,`var value = ${t.getByIndices("input_indices")};`,`value = max(value, ${t.getByIndices("input_indices")});`,""]})},gp=(e,r)=>{ns(e.inputs),os(e,"ReduceMean",r,(t,s,o)=>{let n=1;for(let i=0;i=0||o.length===0)&&(n*=e.inputs[0].dims[i]);return["var sum = f32(0);","",`sum += f32(${t.getByIndices("input_indices")});`,`let value = ${s.type.value}(sum / ${n});`]})},wp=(e,r)=>{ns(e.inputs),os(e,"ReduceMin",r,(t,s,o)=>{let n=[];for(let i=0;i=0||o.length===0)&&n.push(`input_indices[${i}] = 0;`);return[`${n.join(` +`)}`,`var value = ${t.getByIndices("input_indices")};`,`value = min(value, ${t.getByIndices("input_indices")});`,""]})},Mp=(e,r)=>{ns(e.inputs),os(e,"ReduceProd",r,(t,s)=>[`var value = ${s.type.storage}(1);`,"",`value *= ${t.getByIndices("input_indices")};`,""])},bp=(e,r)=>{ns(e.inputs),os(e,"ReduceSum",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += ${t.getByIndices("input_indices")};`,""])},yp=(e,r)=>{ns(e.inputs),os(e,"ReduceSumSquare",r,(t,s)=>[`var t = ${s.type.value}(0); var value = ${s.type.value}(0);`,"",`t = ${t.getByIndices("input_indices")}; value += t * t;`,""])},is=(e,r,t)=>{if(r.length===0)return t;let s=1,o=1;for(let n=0;n1024},vp=(e,r)=>{is(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?gp(e,r):tp(e,r)},xp=(e,r)=>{is(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?hp(e,r):rp(e,r)},Tp=(e,r)=>{is(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?mp(e,r):sp(e,r)},Ep=(e,r)=>{is(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?_p(e,r):np(e,r)},Pp=(e,r)=>{is(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?fp(e,r):op(e,r)},Cp=(e,r)=>{is(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?wp(e,r):ip(e,r)},Sp=(e,r)=>{is(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Mp(e,r):ap(e,r)},$p=(e,r)=>{is(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?bp(e,r):lp(e,r)},kp=(e,r)=>{is(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?yp(e,r):up(e,r)},Ip=(e,r)=>{is(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?pp(e,r):dp(e,r)}}),ul,Ap,Fp,dl,Ev=Be(()=>{ut(),Xt(),ll(),ul=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.")},Ap=(e,r)=>{ul(e.inputs);let t=(s,o,n)=>{let i=[];for(let a=0;a=0||n.length===0)&&i.push(`input_indices[${a}] = 0;`);return[`${i.join(` +`)}`,`var value = ${s.getByIndices("input_indices")}; +var best_index : i32 = 0;`,`if (${s.getByIndices("input_indices")} ${r.selectLastIndex>0?"<=":"<"} value) { + value = ${s.getByIndices("input_indices")}; + best_index = i32(last_index); + }`,"",o.setByOffset("global_idx","best_index")]};e.compute(ui("ArgMin",{hint:r.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],t,[r.axis],7,r.keepDims),{inputs:[0]})},Fp=(e,r)=>{ul(e.inputs);let t=(s,o,n)=>{let i=[];for(let a=0;a=0||n.length===0)&&i.push(`input_indices[${a}] = 0;`);return[`${i.join(` +`)}`,`var value = ${s.getByIndices("input_indices")}; +var best_index : i32 = 0;`,`if (${s.getByIndices("input_indices")} ${r.selectLastIndex>0?">=":">"} value) { + value = ${s.getByIndices("input_indices")}; + best_index = i32(last_index); + }`,"",o.setByOffset("global_idx","best_index")]};e.compute(ui("argMax",{hint:r.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],t,[r.axis],7,r.keepDims),{inputs:[0]})},dl=e=>St(e)}),Op,di,Dp,Lp,zp,mo,Bp,Rp,cl=Be(()=>{ut(),mt(),el(),ft(),Op=(e,r)=>{let t=e[0],s=e[1],o=e[2],n=e[3],i=e[4],a=e[5];if(i&&a)throw new Error("Attention cannot have both past and attention_bias");if(t.dims.length!==3)throw new Error('Input "input" must have 3 dimensions');let l=t.dims[0],u=t.dims[1],p=t.dims[2];if(o.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimensions');if(s.dims.length!==2)throw new Error('Input "weights" is expected to have 2 dimensions');if(s.dims[0]!==p)throw new Error("Input 1 dimension 0 should have same length as dimension 2 of input 0");if(o.dims[0]!==s.dims[1])throw new Error('Input "bias" dimension 0 should have same length as dimension 1 of input "weights"');let d=o.dims[0]/3,c=d,f=c;if(r.qkvHiddenSizes.length>0){if(r.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let S of r.qkvHiddenSizes)if(S%r.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");d=r.qkvHiddenSizes[0],c=r.qkvHiddenSizes[1],f=r.qkvHiddenSizes[2]}let _=u;if(d!==c)throw new Error("qkv_hidden_sizes first element should be same as the second");if(o.dims[0]!==d+c+f)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let T=0;if(i){if(c!==f)throw new Error('Input "past" expect k_hidden_size == v_hidden_size');if(i.dims.length!==5)throw new Error('Input "past" must have 5 dimensions');if(i.dims[0]!==2)throw new Error('Input "past" first dimension must be 2');if(i.dims[1]!==l)throw new Error('Input "past" second dimension must be batch_size');if(i.dims[2]!==r.numHeads)throw new Error('Input "past" third dimension must be num_heads');if(i.dims[4]!==c/r.numHeads)throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads');r.pastPresentShareBuffer||(T=i.dims[3])}let k=_+T,w=-1,g=0;if(n)throw new Error("Mask not supported");if(i)throw new Error("past is not supported");if(a){if(a.dims.length!==4)throw new Error('Input "attention_bias" must have 4 dimensions');if(a.dims[0]!==l||a.dims[1]!==r.numHeads||a.dims[2]!==u||a.dims[3]!==k)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:l,sequenceLength:u,pastSequenceLength:T,kvSequenceLength:_,totalSequenceLength:k,maxSequenceLength:w,inputHiddenSize:p,hiddenSize:d,vHiddenSize:f,headSize:Math.floor(d/r.numHeads),vHeadSize:Math.floor(f/r.numHeads),numHeads:r.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:r.maskFilterValue,maskType:g,scale:r.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},di=(e,r,t)=>r&&e?` + let total_sequence_length_input = u32(${r.getByOffset("0")}); + let present_sequence_length = max(total_sequence_length_input, uniforms.past_sequence_length); + let is_subsequent_prompt: bool = sequence_length > 1 && sequence_length != total_sequence_length_input; + let is_first_prompt: bool = is_subsequent_prompt == false && sequence_length == total_sequence_length_input; + total_sequence_length = u32(${e==null?void 0:e.getByOffset("batchIdx")}) + 1; + var past_sequence_length: u32 = 0; + if (is_first_prompt == false) { + past_sequence_length = total_sequence_length - sequence_length; + } + `:` + ${t?"let past_sequence_length = uniforms.past_sequence_length":""}; + let present_sequence_length = total_sequence_length; + `,Dp=(e,r,t,s,o,n,i,a)=>{let l=Kt(i?1:n),u=64,p=n/l;p{let g=Ye("x",e.dataType,e.dims,l),S=[g],E=i?Pe("seq_lens",i.dataType,i.dims):void 0;E&&S.push(E);let y=a?Pe("total_sequence_length_input",a.dataType,a.dims):void 0;y&&S.push(y);let M=yr(e.dataType),v=[{name:"batch_size",type:"u32"},{name:"num_heads",type:"u32"},{name:"past_sequence_length",type:"u32"},{name:"sequence_length",type:"u32"},{name:"total_sequence_length",type:"u32"},{name:"elements_per_thread",type:"u32"}];return` + var thread_max: array; + var thread_sum: array; + ${w.registerUniforms(v).declareVariables(...S)} + ${w.mainStart([u,1,1])} + let batchIdx = workgroup_id.z / uniforms.num_heads; + let headIdx = workgroup_id.z % uniforms.num_heads; + let sequence_length = uniforms.sequence_length; + var total_sequence_length = uniforms.total_sequence_length; + ${di(E,y,!1)} + let local_offset = local_idx * uniforms.elements_per_thread; + let offset = (global_idx / ${u}) * uniforms.total_sequence_length + local_offset; + let seq_causal_length = ${i?"u32(past_sequence_length + workgroup_id.y + 1)":"total_sequence_length"}; + var thread_max_vector = ${_}(-3.402823e+38f); + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { + thread_max_vector = max(${_}(x[offset + i]), thread_max_vector); + } + thread_max[local_idx] = ${(()=>{switch(l){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: ${l}`)}})()}; + workgroupBarrier(); + + var max_value = f32(-3.402823e+38f); + for (var i = 0u; i < ${u}; i++) { + max_value = max(thread_max[i], max_value); + } + + var sum_vector = ${_}(0); + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { + sum_vector += exp(${_}(x[offset + i]) - max_value); + } + thread_sum[local_idx] = ${(()=>{switch(l){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: ${l}`)}})()}; + workgroupBarrier(); + + var sum: f32 = 0; + for (var i = 0u; i < ${u}; i++) { + sum += thread_sum[i]; + } + + if (sum == 0) { + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { + x[offset + i] = ${g.type.value}(${M}(1.0) / ${M}(seq_causal_length)); + } + } else { + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { + var f32input = ${_}(x[offset + i]); + x[offset + i] = ${g.type.value}(exp(f32input - max_value) / sum); + } + } + ${i?` + for (var total_seq_id: u32 = seq_causal_length; total_seq_id + local_offset < uniforms.total_sequence_length; total_seq_id++) { + x[offset + total_seq_id] = ${g.type.value}(${M}(0)); + }`:""}; + }`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${u};${f};${l}`,inputDependencies:T},getShaderSource:k,getRunData:()=>({outputs:[],dispatchGroup:{x:1,y:o,z:r*t},programUniforms:c})}},Lp=(e,r,t,s,o,n,i,a,l)=>{let u=i+n.kvSequenceLength,p=[n.batchSize,n.numHeads,n.sequenceLength,u],d=e>1&&s,c=n.kvNumHeads?n.kvNumHeads:n.numHeads,f=d?[n.batchSize,c,u,n.headSize]:void 0,_=n.nReps?n.nReps:1,T=n.scale===0?1/Math.sqrt(n.headSize):n.scale,k=Kt(n.headSize),w=n.headSize/k,g=12,S={x:Math.ceil(u/g),y:Math.ceil(n.sequenceLength/g),z:n.batchSize*n.numHeads},E=[{type:12,data:n.sequenceLength},{type:12,data:w},{type:12,data:u},{type:12,data:n.numHeads},{type:12,data:n.headSize},{type:1,data:T},{type:12,data:i},{type:12,data:n.kvSequenceLength},{type:12,data:_}],y=d&&s&&Me.size(s.dims)>0,M=["type","type"];y&&M.push("type"),o&&M.push("type"),a&&M.push("type"),l&&M.push("type");let v=[{dims:p,dataType:r.dataType,gpuDataType:0}];d&&v.push({dims:f,dataType:r.dataType,gpuDataType:0});let C=A=>{let B=Pe("q",r.dataType,r.dims,k),K=Pe("key",t.dataType,t.dims,k),G=[B,K];if(y){let me=Pe("past_key",s.dataType,s.dims,k);G.push(me)}o&&G.push(Pe("attention_bias",o.dataType,o.dims));let j=a?Pe("seq_lens",a.dataType,a.dims):void 0;j&&G.push(j);let ee=l?Pe("total_sequence_length_input",l.dataType,l.dims):void 0;ee&&G.push(ee);let H=Ye("output",r.dataType,p),Z=[H];d&&Z.push(Ye("present_key",r.dataType,f,k));let X=yr(1,k),oe=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"alpha",type:"f32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"},{name:"n_reps",type:"u32"}];return` + const TILE_SIZE = ${g}u; + + var tileQ: array<${B.type.storage}, ${g*g}>; + var tileK: array<${B.type.storage}, ${g*g}>; + ${A.registerUniforms(oe).declareVariables(...G,...Z)} + ${A.mainStart([g,g,1])} + // x holds the N and y holds the M + let headIdx = workgroup_id.z % uniforms.num_heads; + let kvHeadIdx = ${_===1?"headIdx":"headIdx / uniforms.n_reps"}; + let kv_num_heads = ${_===1?"uniforms.num_heads":"uniforms.num_heads / uniforms.n_reps"}; + let batchIdx = workgroup_id.z / uniforms.num_heads; + let m = workgroup_id.y * TILE_SIZE; + let n = workgroup_id.x * TILE_SIZE; + let sequence_length = uniforms.M; + var total_sequence_length = uniforms.N; + ${di(j,ee,!0)} + let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx; + let qOffset = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K; + ${y&&d?"let pastKeyOffset = absKvHeadIdx * uniforms.past_sequence_length * uniforms.K;":""}; + let kOffset = absKvHeadIdx * uniforms.kv_sequence_length * uniforms.K; + ${d?"let presentKeyOffset = absKvHeadIdx * uniforms.N * uniforms.K;":""} + var value = ${X}(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) { + var idx = TILE_SIZE * local_id.y + local_id.x; + ${y&&d?` + if (n + local_id.y < past_sequence_length) { + tileK[idx] = past_key[pastKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x]; + } else if (n + local_id.y - past_sequence_length < uniforms.kv_sequence_length) { + tileK[idx] = key[kOffset + (n + local_id.y - past_sequence_length) * uniforms.K + w + local_id.x]; + }`:` + if (n + local_id.y < uniforms.kv_sequence_length) { + tileK[idx] = key[kOffset + (n + local_id.y) * uniforms.K + w + local_id.x]; + }`} + ${d?`if (n + local_id.y < present_sequence_length) { + present_key[presentKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x] = tileK[idx]; + }`:""} + } + workgroupBarrier(); + + for (var k: u32 = 0u; k < TILE_SIZE && w+k < uniforms.K; k++) { + value += ${X}(tileQ[TILE_SIZE * local_id.y + k] * tileK[TILE_SIZE * local_id.x + k]); + } + + workgroupBarrier(); + } + + if (global_id.y < uniforms.M && global_id.x < total_sequence_length) { + let headOffset = workgroup_id.z * uniforms.M * uniforms.N; + let outputIdx = headOffset + global_id.y * uniforms.N + global_id.x; + var sum: f32 = ${(()=>{switch(k){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: ${k}`)}})()}; + output[outputIdx] = ${H.type.value} (sum * uniforms.alpha) + ${o?"attention_bias[outputIdx]":"0.0"}; + } + }`};return{name:"AttentionProbs",shaderCache:{hint:`${k};${o!==void 0};${s!==void 0};${e}`,inputDependencies:M},getRunData:()=>({outputs:v,dispatchGroup:S,programUniforms:E}),getShaderSource:C}},zp=(e,r,t,s,o,n,i=void 0,a=void 0)=>{let l=n+o.kvSequenceLength,u=o.nReps?o.nReps:1,p=o.vHiddenSize*u,d=e>1&&s,c=o.kvNumHeads?o.kvNumHeads:o.numHeads,f=d?[o.batchSize,c,l,o.headSize]:void 0,_=[o.batchSize,o.sequenceLength,p],T=12,k={x:Math.ceil(o.vHeadSize/T),y:Math.ceil(o.sequenceLength/T),z:o.batchSize*o.numHeads},w=[{type:12,data:o.sequenceLength},{type:12,data:l},{type:12,data:o.vHeadSize},{type:12,data:o.numHeads},{type:12,data:o.headSize},{type:12,data:p},{type:12,data:n},{type:12,data:o.kvSequenceLength},{type:12,data:u}],g=d&&s&&Me.size(s.dims)>0,S=["type","type"];g&&S.push("type"),i&&S.push("type"),a&&S.push("type");let E=[{dims:_,dataType:r.dataType,gpuDataType:0}];d&&E.push({dims:f,dataType:r.dataType,gpuDataType:0});let y=M=>{let v=Pe("probs",r.dataType,r.dims),C=Pe("v",t.dataType,t.dims),A=[v,C];g&&A.push(Pe("past_value",s.dataType,s.dims));let B=i?Pe("seq_lens",i.dataType,i.dims):void 0;i&&A.push(B);let K=a?Pe("total_sequence_length_input",a.dataType,a.dims):void 0;a&&A.push(K);let G=[Ye("output",r.dataType,_)];d&&G.push(Ye("present_value",r.dataType,f));let j=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"v_hidden_size",type:"u32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"},{name:"n_reps",type:"u32"}];return` + const TILE_SIZE = ${T}u; + var tileQ: array<${v.type.value}, ${T*T}>; + var tileV: array<${v.type.value}, ${T*T}>; + ${M.registerUniforms(j).declareVariables(...A,...G)} + ${M.mainStart([T,T,1])} + let headIdx = workgroup_id.z % uniforms.num_heads; + let batchIdx = workgroup_id.z / uniforms.num_heads; + let kvHeadIdx = ${u===1?"headIdx":"headIdx / uniforms.n_reps"}; + let kv_num_heads = ${u===1?"uniforms.num_heads":"uniforms.num_heads / uniforms.n_reps"}; + let m = global_id.y; + let n = global_id.x; + let sequence_length = uniforms.M; + var total_sequence_length = uniforms.K; + ${di(B,K,!0)} + let offsetA = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K; + let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx; // kvHeadIdx is relative to the batch + ${g&&d?"let pastValueOffset = absKvHeadIdx * uniforms.N * uniforms.past_sequence_length + n;":""}; + let vOffset = absKvHeadIdx * uniforms.N * uniforms.kv_sequence_length + n; + ${d?"let presentValueOffset = absKvHeadIdx * uniforms.N * uniforms.K + n;":""} + var value = ${v.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) { + var idx = TILE_SIZE * local_id.y + local_id.x; + ${g&&d?` + if (w + local_id.y < past_sequence_length) { + tileV[idx] = past_value[pastValueOffset + (w + local_id.y) * uniforms.N]; + } else if (w + local_id.y - past_sequence_length < uniforms.kv_sequence_length) { + tileV[idx] = v[vOffset + (w + local_id.y - past_sequence_length) * uniforms.N]; + } + `:` + if (w + local_id.y < uniforms.kv_sequence_length) { + tileV[idx] = v[vOffset + (w + local_id.y) * uniforms.N]; + }`} + ${d?` + if (w + local_id.y < present_sequence_length) { + present_value[presentValueOffset + (w + local_id.y) * uniforms.N] = tileV[idx]; + }`:""} + } + workgroupBarrier(); + for (var k: u32 = 0u; k < TILE_SIZE && w+k < total_sequence_length; k++) { + value += tileQ[TILE_SIZE * local_id.y + k] * tileV[TILE_SIZE * k + local_id.x]; + } + workgroupBarrier(); + } + + // we need to transpose output from BNSH_v to BSND_v + if (m < uniforms.M && n < uniforms.N) { + let outputIdx = batchIdx * uniforms.M * uniforms.v_hidden_size + m * uniforms.v_hidden_size + + headIdx * uniforms.N + n; + output[outputIdx] = value; + } + }`};return{name:"AttentionScore",shaderCache:{hint:`${s!==void 0};${e}`,inputDependencies:S},getRunData:()=>({outputs:E,dispatchGroup:k,programUniforms:w}),getShaderSource:y}},mo=(e,r,t,s,o,n,i,a,l,u,p=void 0,d=void 0)=>{let c=Math.min(e.outputCount,1+(i?1:0)+(a?1:0)),f=c>1?u.pastSequenceLength:0,_=f+u.kvSequenceLength,T=l&&Me.size(l.dims)>0?l:void 0,k=[r,t];c>1&&i&&Me.size(i.dims)>0&&k.push(i),T&&k.push(T),p&&k.push(p),d&&k.push(d);let w=e.compute(Lp(c,r,t,i,T,u,f,p,d),{inputs:k,outputs:c>1?[-1,1]:[-1]})[0];e.compute(Dp(w,u.batchSize,u.numHeads,f,u.sequenceLength,_,p,d),{inputs:p&&d?[w,p,d]:[w],outputs:[]});let g=[w,s];c>1&&a&&Me.size(a.dims)>0&&g.push(a),p&&g.push(p),d&&g.push(d),e.compute(zp(c,w,s,a,u,f,p,d),{inputs:g,outputs:c>1?[0,2]:[0]})},Bp=(e,r)=>{let t=[r.batchSize,r.numHeads,r.sequenceLength,r.headSize],s=r.sequenceLength,o=r.inputHiddenSize,n=r.headSize,i=12,a={x:Math.ceil(r.headSize/i),y:Math.ceil(r.sequenceLength/i),z:r.batchSize*r.numHeads},l=[e.inputs[0],e.inputs[1],e.inputs[2]],u=[{type:12,data:s},{type:12,data:o},{type:12,data:n},{type:12,data:r.numHeads},{type:12,data:r.headSize},{type:12,data:r.hiddenSize},{type:12,data:r.hiddenSize+r.hiddenSize+r.vHiddenSize}],p=d=>{let c=Ye("output_q",l[0].dataType,t),f=Ye("output_k",l[0].dataType,t),_=Ye("output_v",l[0].dataType,t),T=Pe("input",l[0].dataType,l[0].dims),k=Pe("weight",l[1].dataType,l[1].dims),w=Pe("bias",l[2].dataType,l[2].dims),g=T.type.storage,S=[{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 = ${i}u; + var tileInput: array<${g}, ${i*i}>; + var tileWeightQ: array<${g}, ${i*i}>; + var tileWeightK: array<${g}, ${i*i}>; + var tileWeightV: array<${g}, ${i*i}>; + ${d.registerUniforms(S).declareVariables(T,k,w,c,f,_)} + ${d.mainStart([i,i,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 = ${g}(0); + var valueK = ${g}(0); + var valueV = ${g}(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:t,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:t,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:t,dataType:e.inputs[0].dataType,gpuDataType:0}],dispatchGroup:a,programUniforms:u}),getShaderSource:p},{inputs:l,outputs:[-1,-1,-1]})},Rp=(e,r)=>{let t=Op(e.inputs,r),[s,o,n]=Bp(e,t);return mo(e,s,o,n,e.inputs[4],void 0,void 0,void 0,e.inputs[5],t)}}),jp,Np,Vp,Up,Pv=Be(()=>{ts(),ut(),mt(),Xt(),ft(),jp=(e,r)=>{if(!e||e.length!==5)throw new Error("BatchNormalization requires 5 inputs");let t=(s,o,n)=>{let i=o.length;if(i!==s.length)throw new Error(`${n}: num dimensions != ${i}`);o.forEach((a,l)=>{if(a!==s[l])throw new Error(`${n}: dim[${l}] do not match`)})};if(e[0].dims.length>1){let s=r.format==="NHWC"?r.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,r.spatial?2:void 0);t(e[1].dims,s,"Invalid input scale"),t(e[2].dims,s,"Invalid input B"),t(e[3].dims,s,"Invalid input mean"),t(e[4].dims,s,"Invalid input var")}else t(e[1].dims,[1],"Invalid input scale"),t(e[2].dims,[1],"Invalid input B"),t(e[3].dims,[1],"Invalid input mean"),t(e[4].dims,[1],"Invalid input var")},Np=(e,r)=>{let{epsilon:t,spatial:s,format:o}=r,n=e[0].dims,i=s?Kt(n[n.length-1]):1,a=o==="NHWC"&&n.length>1?i:1,l=Me.size(n)/i,u=s,p=u?n.length:n,d=Pe("x",e[0].dataType,e[0].dims,i),c=Pe("scale",e[1].dataType,e[1].dims,a),f=Pe("bias",e[2].dataType,e[2].dims,a),_=Pe("inputMean",e[3].dataType,e[3].dims,a),T=Pe("inputVar",e[4].dataType,e[4].dims,a),k=Ye("y",e[0].dataType,p,i),w=()=>{let S="";if(s)S=`let cOffset = ${n.length===1?"0u":o==="NHWC"?`outputIndices[${n.length-1}] / ${i}`:"outputIndices[1]"};`;else if(o==="NCHW")S=` + ${k.indicesSet("outputIndices","0","0")} + let cOffset = ${k.indicesToOffset("outputIndices")};`;else{S=`var cIndices = ${c.type.indices}(0); + cIndices[0] = outputIndices[${n.length-1}];`;for(let E=1;E` + const epsilon = ${t}; + ${S.registerUniform("outputSize","u32").declareVariables(d,c,f,_,T,k)} + ${S.mainStart()} + ${S.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var outputIndices = ${k.offsetToIndices(`global_idx * ${i}`)}; + ${w()} + let scale = ${c.getByOffset("cOffset")}; + let bias = ${f.getByOffset("cOffset")}; + let inputMean = ${_.getByOffset("cOffset")}; + let inputVar = ${T.getByOffset("cOffset")}; + let x = ${d.getByOffset("global_idx")}; + let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias; + ${k.setByOffset("global_idx","value")} + }`;return{name:"BatchNormalization",shaderCache:{hint:`${r.epsilon}_${r.format}_${s}_${i}`,inputDependencies:u?["rank","type","type","type","type"]:void 0},getShaderSource:g,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:u?[{type:12,data:l},...st(n)]:[{type:12,data:l}]})}},Vp=e=>St(e),Up=(e,r)=>{let{inputs:t,outputCount:s}=e,o=Vp({...r,outputCount:s});if(Bt.webgpu.validateInputContent&&jp(t,o),r.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");e.compute(Np(t,o))}}),Wp,Gp,Kp,Cv=Be(()=>{mt(),ft(),Wp=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")},Gp=e=>{let r=e[0].dims,t=e[0].dims[2],s=Me.size(r)/4,o=e[0].dataType,n=Pe("input",o,r,4),i=Pe("bias",o,[t],4),a=Pe("residual",o,r,4),l=Ye("output",o,r,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(s/64)}}),getShaderSource:u=>` + const channels = ${t}u / 4; + ${u.declareVariables(n,i,a,l)} + + ${u.mainStart()} + ${u.guardAgainstOutOfBoundsWorkgroupSizes(s)} + let value = ${n.getByOffset("global_idx")} + + ${i.getByOffset("global_idx % channels")} + ${a.getByOffset("global_idx")}; + ${l.setByOffset("global_idx","value")} + }`}},Kp=e=>{Wp(e.inputs),e.compute(Gp(e.inputs))}}),Hp,Et,qp,Xp,Qp,Jp,Yp,Zp,eh,th,rh,sh,nh,oh,ih,ah,_o,lh,ci,uh,dh,ch,ph,hh,mh,_h,fh,gh,wh,Mh,bh,yh,vh,xh,Th,pl,Eh,hl,ml,Ph,Ch,Sh,$h,kh,Ih,_l=Be(()=>{ut(),mt(),Xt(),ft(),Hp=(e,r,t,s,o,n,i)=>{let a=Math.ceil(r/4),l="";typeof o=="string"?l=`${o}(a)`:l=o("a");let u=Pe("inputData",t,[a],4),p=Ye("outputData",s,[a],4),d=[{name:"vec_size",type:"u32"}];return i&&d.push(...i),` + ${e.registerUniforms(d).declareVariables(u,p)} + + ${n??""} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + + let a = ${u.getByOffset("global_idx")}; + ${p.setByOffset("global_idx",l)} + }`},Et=(e,r,t,s,o,n=e.dataType,i,a)=>{let l=[{type:12,data:Math.ceil(Me.size(e.dims)/4)}];return i&&l.push(...i),{name:r,shaderCache:{hint:o,inputDependencies:["type"]},getShaderSource:u=>Hp(u,Me.size(e.dims),e.dataType,n,t,s,a),getRunData:u=>({outputs:[{dims:e.dims,dataType:n}],dispatchGroup:{x:Math.ceil(Me.size(u[0].dims)/64/4)},programUniforms:l})}},qp=e=>{e.compute(Et(e.inputs[0],"Abs","abs"))},Xp=e=>{e.compute(Et(e.inputs[0],"Acos","acos"))},Qp=e=>{e.compute(Et(e.inputs[0],"Acosh","acosh"))},Jp=e=>{e.compute(Et(e.inputs[0],"Asin","asin"))},Yp=e=>{e.compute(Et(e.inputs[0],"Asinh","asinh"))},Zp=e=>{e.compute(Et(e.inputs[0],"Atan","atan"))},eh=e=>{e.compute(Et(e.inputs[0],"Atanh","atanh"))},th=e=>St(e),rh=(e,r)=>{let t;switch(r.to){case 10:t="vec4";break;case 1:t="vec4";break;case 12:t="vec4";break;case 6:t="vec4";break;case 9:t="vec4";break;default:throw new RangeError(`not supported type (specified in attribute 'to' from 'Cast' operator): ${r.to}`)}e.compute(Et(e.inputs[0],"Cast",t,void 0,r.cacheKey,r.to))},sh=e=>{let r,t,s=e.length>=2&&e[1].data!==0,o=e.length>=3&&e[2].data!==0;switch(e[0].dataType){case 1:r=s?e[1].getFloat32Array()[0]:-34028234663852886e22,t=o?e[2].getFloat32Array()[0]:34028234663852886e22;break;case 10:r=s?e[1].getUint16Array()[0]:64511,t=o?e[2].getUint16Array()[0]:31743;break;default:throw new Error("Unsupport data type")}return St({min:r,max:t})},nh=(e,r)=>{let t=r||sh(e.inputs),s=yr(e.inputs[0].dataType);e.compute(Et(e.inputs[0],"Clip",o=>`clamp(${o}, vec4<${s}>(uniforms.min), vec4<${s}>(uniforms.max))`,void 0,t.cacheKey,void 0,[{type:e.inputs[0].dataType,data:t.min},{type:e.inputs[0].dataType,data:t.max}],[{name:"min",type:s},{name:"max",type:s}]),{inputs:[0]})},oh=e=>{e.compute(Et(e.inputs[0],"Ceil","ceil"))},ih=e=>{e.compute(Et(e.inputs[0],"Cos","cos"))},ah=e=>{e.compute(Et(e.inputs[0],"Cosh","cosh"))},_o=e=>St(e),lh=(e,r)=>{let t=yr(e.inputs[0].dataType);e.compute(Et(e.inputs[0],"Elu",s=>`elu_vf32(${s})`,` + const elu_alpha_ = ${t}(${r.alpha}); + + fn elu_f32(a: ${t}) -> ${t} { + return select((exp(a) - 1.0) * elu_alpha_, a, a >= 0.0); + } + + fn elu_vf32(v: vec4<${t}>) -> vec4<${t}> { + return vec4(elu_f32(v.x), elu_f32(v.y), elu_f32(v.z), elu_f32(v.w)); + }`,r.cacheKey))},ci=(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)); +}`,uh=e=>{let r=yr(e.inputs[0].dataType);e.compute(Et(e.inputs[0],"Erf",t=>`erf_vf32(${t})`,ci(r)))},dh=e=>{e.compute(Et(e.inputs[0],"Exp","exp"))},ch=e=>{e.compute(Et(e.inputs[0],"Floor","floor"))},ph=e=>{let r=yr(e.inputs[0].dataType);e.compute(Et(e.inputs[0],"Gelu",t=>`0.5 * ${t} * (1.0 + erf_vf32(${t} * 0.7071067811865475))`,ci(r)))},hh=(e,r)=>{let t=yr(e.inputs[0].dataType);e.compute(Et(e.inputs[0],"LeakyRelu",s=>`select(leaky_relu_alpha_ * ${s}, ${s}, ${s} >= vec4<${t}>(0.0))`,`const leaky_relu_alpha_ = ${t}(${r.alpha});`,r.cacheKey))},mh=e=>{e.compute(Et(e.inputs[0],"Not",r=>`!${r}`))},_h=e=>{e.compute(Et(e.inputs[0],"Neg",r=>`-${r}`))},fh=e=>{e.compute(Et(e.inputs[0],"Reciprocal",r=>`1.0/${r}`))},gh=e=>{let r=yr(e.inputs[0].dataType);e.compute(Et(e.inputs[0],"Relu",t=>`select(vec4<${r}>(0.0), ${t}, ${t} > vec4<${r}>(0.0))`))},wh=e=>{e.compute(Et(e.inputs[0],"Sigmoid",r=>`(1.0 / (1.0 + exp(-${r})))`))},Mh=e=>St(e),bh=(e,r)=>{let t=yr(e.inputs[0].dataType);e.compute(Et(e.inputs[0],"HardSigmoid",s=>`max(vec4<${t}>(0.0), min(vec4<${t}>(1.0), ${r.alpha} * ${s} + vec4<${t}>(${r.beta})))`,void 0,r.cacheKey))},yh=e=>{e.compute(Et(e.inputs[0],"Sin","sin"))},vh=e=>{e.compute(Et(e.inputs[0],"Sinh","sinh"))},xh=e=>{e.compute(Et(e.inputs[0],"Sqrt","sqrt"))},Th=e=>{e.compute(Et(e.inputs[0],"Tan","tan"))},pl=e=>`sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`,Eh=e=>{e.compute(Et(e.inputs[0],"Tanh",pl))},hl=(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 ${pl("v")}; +} +`,ml=e=>`(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`,Ph=e=>{let r=yr(e.inputs[0].dataType);e.compute(Et(e.inputs[0],"FastGelu",ml,hl(r),void 0,e.inputs[0].dataType))},Ch=(e,r)=>{let t=yr(e.inputs[0].dataType);return e.compute(Et(e.inputs[0],"ThresholdedRelu",s=>`select(vec4<${t}>(0.0), ${s}, ${s} > thresholded_relu_alpha_)`,`const thresholded_relu_alpha_ = vec4<${t}>(${r.alpha});`,r.cacheKey)),0},Sh=e=>{e.compute(Et(e.inputs[0],"Log","log"))},$h=(e,r)=>` +const alpha = vec4<${e}>(${r}); +const one = ${e}(1.0); +const zero = ${e}(0.0); + +fn quick_gelu_impl(x: vec4<${e}>) -> vec4<${e}> { + let v = x *alpha; + var x1 : vec4<${e}>; + for (var i = 0; i < 4; i = i + 1) { + if (v[i] >= zero) { + x1[i] = one / (one + exp(-v[i])); + } else { + x1[i] = one - one / (one + exp(v[i])); + } + } + return x * x1; +} +`,kh=e=>`quick_gelu_impl(${e})`,Ih=(e,r)=>{let t=yr(e.inputs[0].dataType);e.compute(Et(e.inputs[0],"QuickGelu",kh,$h(t,r.alpha),r.cacheKey,e.inputs[0].dataType))}}),Ah,Fh,Oh,Sv=Be(()=>{mt(),ft(),_l(),Ah=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")},Fh=e=>{let r=e[0].dims.slice();r[2]=r[2]/2;let t=Pe("input",e[0].dataType,e[0].dims,4),s=Pe("bias",e[0].dataType,[e[0].dims[2]],4),o=Ye("output",e[0].dataType,r,4),n=Me.size(r)/4,i=lr(e[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(n/64)}}),getShaderSource:a=>` + const M_SQRT2 = sqrt(2.0); + const halfChannels = ${e[0].dims[2]/4/2}u; + + ${a.declareVariables(t,s,o)} + + ${ci(i)} + + ${a.mainStart()} + ${a.guardAgainstOutOfBoundsWorkgroupSizes(n)} + 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); + + ${o.setByOffset("global_idx","valueLeft * geluRight")} + }`}},Oh=e=>{Ah(e.inputs),e.compute(Fh(e.inputs))}}),Dh,Lh,as,zh,Bh,Rh,jh,Nh,Vh,Uh,Wh,Gh,Kh,$v=Be(()=>{ut(),mt(),ft(),Dh=(e,r,t,s,o,n,i,a,l,u,p,d)=>{let c,f;typeof a=="string"?c=f=(g,S)=>`${a}((${g}),(${S}))`:typeof a=="function"?c=f=a:(c=a.scalar,f=a.vector);let _=Ye("outputData",p,s.length,4),T=Pe("aData",l,r.length,4),k=Pe("bData",u,t.length,4),w;if(o)if(n){let g=Me.size(r)===1,S=Me.size(t)===1,E=r.length>0&&r[r.length-1]%4===0,y=t.length>0&&t[t.length-1]%4===0;g||S?w=_.setByOffset("global_idx",f(g?`${T.type.value}(${T.getByOffset("0")}.x)`:T.getByOffset("global_idx"),S?`${k.type.value}(${k.getByOffset("0")}.x)`:k.getByOffset("global_idx"))):w=` + let outputIndices = ${_.offsetToIndices("global_idx * 4u")}; + let offsetA = ${T.broadcastedIndicesToOffset("outputIndices",_)}; + let offsetB = ${k.broadcastedIndicesToOffset("outputIndices",_)}; + ${_.setByOffset("global_idx",f(i||E?T.getByOffset("offsetA / 4u"):`${T.type.value}(${T.getByOffset("offsetA / 4u")}[offsetA % 4u])`,i||y?k.getByOffset("offsetB / 4u"):`${k.type.value}(${k.getByOffset("offsetB / 4u")}[offsetB % 4u])`))} + `}else w=_.setByOffset("global_idx",f(T.getByOffset("global_idx"),k.getByOffset("global_idx")));else{if(!n)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let g=(S,E,y="")=>{let M=`aData[indexA${E}][componentA${E}]`,v=`bData[indexB${E}][componentB${E}]`;return` + let outputIndices${E} = ${_.offsetToIndices(`global_idx * 4u + ${E}u`)}; + let offsetA${E} = ${T.broadcastedIndicesToOffset(`outputIndices${E}`,_)}; + let offsetB${E} = ${k.broadcastedIndicesToOffset(`outputIndices${E}`,_)}; + let indexA${E} = offsetA${E} / 4u; + let indexB${E} = offsetB${E} / 4u; + let componentA${E} = offsetA${E} % 4u; + let componentB${E} = offsetB${E} % 4u; + ${S}[${E}] = ${y}(${c(M,v)}); + `};p===9?w=` + var data = vec4(0); + ${g("data",0,"u32")} + ${g("data",1,"u32")} + ${g("data",2,"u32")} + ${g("data",3,"u32")} + outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:w=` + ${g("outputData[global_idx]",0)} + ${g("outputData[global_idx]",1)} + ${g("outputData[global_idx]",2)} + ${g("outputData[global_idx]",3)} + `}return` + ${e.registerUniform("vec_size","u32").declareVariables(T,k,_)} + + ${d??""} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${w} + }`},Lh=(e,r,t,s,o,n,i=t.dataType)=>{let a=t.dims.map(T=>Number(T)??1),l=s.dims.map(T=>Number(T)??1),u=!Me.areEqual(a,l),p=a,d=Me.size(a),c=!1,f=!1,_=[u];if(u){let T=Nn.calcShape(a,l,!1);if(!T)throw new Error("Can't perform binary op on the given tensors");p=T.slice(),d=Me.size(p);let k=Me.size(a)===1,w=Me.size(l)===1,g=a.length>0&&a[a.length-1]%4===0,S=l.length>0&&l[l.length-1]%4===0;_.push(k),_.push(w),_.push(g),_.push(S);let E=1;for(let y=1;yT.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:T=>Dh(T,a,l,p,c,u,f,o,t.dataType,s.dataType,i,n),getRunData:()=>({outputs:[{dims:p,dataType:i}],dispatchGroup:{x:Math.ceil(d/64/4)},programUniforms:[{type:12,data:Math.ceil(Me.size(p)/4)},...st(a,l,p)]})}},as=(e,r,t,s,o,n)=>{e.compute(Lh(r,o??"",e.inputs[0],e.inputs[1],t,s,n))},zh=e=>{as(e,"Add",(r,t)=>`${r}+${t}`)},Bh=e=>{as(e,"Div",(r,t)=>`${r}/${t}`)},Rh=e=>{as(e,"Equal",{scalar:(r,t)=>`u32(${r}==${t})`,vector:(r,t)=>`vec4(${r}==${t})`},void 0,void 0,9)},jh=e=>{as(e,"Mul",(r,t)=>`${r}*${t}`)},Nh=e=>{let r=Pe("input",e.inputs[0].dataType,e.inputs[0].dims).type.value;as(e,"Pow",{scalar:(t,s)=>`pow_custom(${t},${s})`,vector:(t,s)=>`pow_vector_custom(${t},${s})`},` + fn pow_custom(a : ${r}, b : ${r}) -> ${r} { + if (b == ${r}(0.0)) { + return ${r}(1.0); + } else if (a < ${r}(0.0) && f32(b) != floor(f32(b))) { + return ${r}(pow(f32(a), f32(b))); // NaN + } + return select(sign(a), ${r}(1.0), round(f32(abs(b) % ${r}(2.0))) != 1.0) * ${r}(${r==="i32"?"round":""}(pow(f32(abs(a)), f32(b)))); + } + fn pow_vector_custom(a : vec4<${r}>, b : vec4<${r}>) -> vec4<${r}> { + // TODO: implement vectorized pow + return vec4<${r}>(pow_custom(a.x, b.x), pow_custom(a.y, b.y), pow_custom(a.z, b.z), pow_custom(a.w, b.w)); + } + `)},Vh=e=>{as(e,"Sub",(r,t)=>`${r}-${t}`)},Uh=e=>{as(e,"Greater",{scalar:(r,t)=>`u32(${r}>${t})`,vector:(r,t)=>`vec4(${r}>${t})`},void 0,void 0,9)},Wh=e=>{as(e,"Less",{scalar:(r,t)=>`u32(${r}<${t})`,vector:(r,t)=>`vec4(${r}<${t})`},void 0,void 0,9)},Gh=e=>{as(e,"GreaterOrEqual",{scalar:(r,t)=>`u32(${r}>=${t})`,vector:(r,t)=>`vec4(${r}>=${t})`},void 0,void 0,9)},Kh=e=>{as(e,"LessOrEqual",{scalar:(r,t)=>`u32(${r}<=${t})`,vector:(r,t)=>`vec4(${r}<=${t})`},void 0,void 0,9)}}),Hh,qh,Xh,Qh,Jh,Yh,kv=Be(()=>{ut(),mt(),Xt(),ft(),Hh=(e,r)=>{if(!e||e.length<1)throw new Error("too few inputs");let t=0,s=e[t],o=s.dataType,n=s.dims.length;e.forEach((i,a)=>{if(a!==t){if(i.dataType!==o)throw new Error("input tensors should be one type");if(i.dims.length!==n)throw new Error("input tensors should have the same shape");i.dims.forEach((l,u)=>{if(u!==r&&l!==s.dims[u])throw new Error("non concat dimensions must match")})}})},qh=(e,r)=>` + fn calculateInputIndex(index: u32) -> u32 { + let sizeInConcatAxis = array(${r}); + for (var i: u32 = 0u; i < ${e}; i += 1u ) { + if (index < sizeInConcatAxis[i]) { + return i; + } + } + return ${e}u; + }`,Xh=(e,r)=>{let t=e.length,s=[];for(let o=0;o{let o=Me.size(t),n=new Array(e.length),i=new Array(e.length),a=0,l=[],u=[],p=[{type:12,data:o}];for(let T=0;T`uniforms.sizeInConcatAxis${T}`).join(","),_=T=>` + + ${(()=>{T.registerUniform("outputSize","u32");for(let k=0;k(${f}); + ${c} -= sizeInConcatAxis[inputIndex - 1u]; + } + + ${Xh(i,d)} + }`;return{name:"Concat",shaderCache:{hint:`${r}`,inputDependencies:l},getRunData:()=>({outputs:[{dims:t,dataType:s}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:p}),getShaderSource:_}},Jh=(e,r)=>{let t=e.inputs,s=t[0].dims,o=Me.normalizeAxis(r.axis,s.length);Hh(t,o);let n=s.slice();n[o]=t.reduce((a,l)=>a+(l.dims.length>o?l.dims[o]:0),0);let i=t.filter(a=>Me.size(a.dims)>0);e.compute(Qh(i,o,n,t[0].dataType),{inputs:i})},Yh=e=>St({axis:e.axis})}),rn,sn,nn,fl,on=Be(()=>{ut(),mt(),rn=(e,r,t="f32")=>{switch(e.activation){case"Relu":return`value = max(value, ${r}(0.0));`;case"Sigmoid":return`value = (${r}(1.0) / (${r}(1.0) + exp(-value)));`;case"Clip":return`value = clamp(value, ${r}(${t}(uniforms.clip_min)), ${r}(${t}(uniforms.clip_max)));`;case"HardSigmoid":return`value = max(${r}(0.0), min(${r}(1.0), ${t}(uniforms.alpha) * value + ${t}(uniforms.beta)));`;case"LeakyRelu":return`value = select(${t}(uniforms.alpha) * value, value, value >= ${r}(0.0));`;case"Tanh":return`let e2x = exp(-2.0 * abs(value)); + value = sign(value) * (1.0 - e2x) / (1.0 + e2x); + `;case"":return"";default:throw new Error(`Unsupported activation ${e.activation}`)}},sn=(e,r)=>{e.activation==="Clip"?r.push({type:1,data:e.clipMax},{type:1,data:e.clipMin}):e.activation==="HardSigmoid"?r.push({type:1,data:e.alpha},{type:1,data:e.beta}):e.activation==="LeakyRelu"&&r.push({type:1,data:e.alpha})},nn=(e,r)=>{e.activation==="Clip"?r.push({name:"clip_max",type:"f32"},{name:"clip_min",type:"f32"}):e.activation==="HardSigmoid"?r.push({name:"alpha",type:"f32"},{name:"beta",type:"f32"}):e.activation==="LeakyRelu"&&r.push({name:"alpha",type:"f32"})},fl=e=>{let r=(e==null?void 0:e.activation)||"";if(r==="HardSigmoid"){let[t,s]=(e==null?void 0:e.activation_params)||[.2,.5];return{activation:r,alpha:t,beta:s}}else if(r==="Clip"){let[t,s]=(e==null?void 0:e.activation_params)||[yc,vc];return{activation:r,clipMax:s,clipMin:t}}else if(r==="LeakyRelu"){let[t]=(e==null?void 0:e.activation_params)||[.01];return{activation:r,alpha:t}}return{activation:r}}}),_r,Zh,gl=Be(()=>{_r=(e,r)=>{switch(e){case 1:return r;case 2:return`vec2<${r}>`;case 3:return`vec3<${r}>`;case 4:return`vec4<${r}>`;default:throw new Error(`${e}-component is not supported.`)}},Zh=e=>` + ${e?"value = value + getBiasByOutputCoords(coords);":""} + `}),em,Iv=Be(()=>{em=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)); +} +`}),fo,wl,Ml=Be(()=>{ut(),mt(),ft(),on(),fo=(e,r,t,s,o)=>{let n=s-t;return` + ${Array.from({length:t}).map((i,a)=>` + if (${et(r.shape,a,r.rank)} != 1) { + ${r.indicesSet(e,a,et(o,a+n,s))} + } else { + ${r.indicesSet(e,a,0)} + }`).join("")} +`},wl=(e,r,t,s,o=!1,n)=>{let i=e[0].dims,a=e[1].dims,l=i[i.length-2],u=a[a.length-1],p=i[i.length-1],d=Kt(u),c=Kt(p),f=Kt(l),_=Me.size(t)/d/f,T=e.length>2,k=s?s.slice(0,-2):t.slice(0,-2),w=[Me.size(k),l,u],g=[{type:12,data:_},{type:12,data:l},{type:12,data:u},{type:12,data:p}];sn(r,g),g.push(...st(k,i,a)),T&&g.push(...st(e[2].dims)),g.push(...st(w));let S=E=>{let y=ol("batch_dims",e[0].dataType,k.length),M=Pe("a",e[0].dataType,i.length,c),v=Pe("b",e[1].dataType,a.length,d),C=Ye("output",e[0].dataType,w.length,d),A=lr(C.type.tensor),B=rn(r,C.type.value,A),K=[M,v],G="";if(T){let H=o?d:1;K.push(Pe("bias",e[2].dataType,e[2].dims.length,H)),G=`${o?`value += bias[col / ${H}];`:`value += ${C.type.value}(bias[row + i]);`}`}let j=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];nn(r,j);let ee=()=>{let H=`var a_data: ${M.type.value};`;for(let Z=0;Z; + for (var k: u32 = 0u; k < uniforms.K; k = k + ${c}) { + ${ee()} + } + for (var i = 0u; i < ${f}u; i++) { + var value = values[i]; + ${G} + ${B} + let cur_indices = ${C.type.indices}(batch, row + i, col); + let offset = ${C.indicesToOffset("cur_indices")}; + ${C.setByOffset(`offset / ${d}`,"value")}; + } + } + `};return{name:"MatMulNaive",shaderCache:{hint:`${r.activation};${d};${c};${f};${o}`,inputDependencies:T?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:n?n(t):t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(_/64)},programUniforms:g}),getShaderSource:S}}}),tm,rm,bl,yl,sm,vl,nm,pi,xl=Be(()=>{ut(),mt(),ft(),on(),Ml(),gl(),tm=(e,r)=>e?` + mm_Asub[inputRow][inputCol] = mm_readA(batch, + kStart + inputRow, + globalRowStart / innerElementSize + inputCol${r?", batchIndices":""}); + `:` + mm_Asub[inputRow][inputCol] = mm_readA(batch, + globalRow + innerRow, + kStart / innerElementSize + inputCol${r?", batchIndices":""}); + `,rm=(e,r)=>e?` + let ACached0 = mm_Asub[k * innerElementSize][localRow]; + let ACached1 = mm_Asub[k * innerElementSize + 1][localRow]; + let ACached2 = mm_Asub[k * innerElementSize + 2][localRow]; + ${r===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]; + ${r===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]; + ${r===3?"":"acc[i] = BCached3 * ACached.w + acc[i];"} + }`,bl=(e,r,t="f32",s,o=!1,n=32,i=!1,a=32)=>{let l=r[1]*e[1],u=r[0]*e[0],p=o?l:n,d=o?n:l,c=p/r[0],f=n/r[1];if(!((o&&c===4&&e[1]===4||!o&&(c===3||c===4))&&p%r[0]===0&&n%r[1]===0&&e[0]===4))throw new Error(`If transposeA ${o} is true, innerElementSize ${c} and workPerThread[1] ${e[1]} must be 4. + Otherwise, innerElementSize ${c} must be 3 or 4. + tileAWidth ${p} must be divisible by workgroupSize[0]${r[0]}. tileInner ${n} must be divisible by workgroupSize[1] ${r[1]}. colPerThread ${e[0]} must be 4.`);return` +var mm_Asub: array, ${p/c}>, ${d}>; +var mm_Bsub: array, ${u/e[0]}>, ${n}>; + +const rowPerThread = ${e[1]}; +const colPerThread = ${e[0]}; +const innerElementSize = ${c}; +const tileInner = ${n}; + +@compute @workgroup_size(${r[0]}, ${r[1]}, ${r[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 = ${i?"0":"i32(globalId.z)"}; + ${s?`let batchIndices = ${s.offsetToIndices("u32(batch)")};`:""} + let globalRowStart = i32(workgroupId.y) * ${l}; + + let num_tiles = ${i?`${Math.ceil(a/n)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; + var kStart = ${i?`i32(globalId.z) * ${a}`:"0"}; + + var acc: array, rowPerThread>; + + // Loop over shared dimension. + let tileRowB = localRow * ${f}; + 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; + ${tm(o,s)} + } + + // Load one tile of B into local memory. + for (var innerRow = 0; innerRow < ${f}; innerRow = innerRow + 1) { + let inputRow = tileRowB + innerRow; + let inputCol = tileCol; + mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol${s?", 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]; + ${c===3?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"} + + ${rm(o,c)} + } + + workgroupBarrier(); + } + + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]); + } +}`},yl=(e,r)=>e?` + mm_Asub[inputRow][inputCol] = mm_readA(batch, + kStart + inputRow, + globalRowStart + inputCol${r?", batchIndices":""}); + `:` + mm_Asub[inputRow][inputCol] = mm_readA(batch, + globalRowStart + inputRow, + kStart + inputCol${r?", batchIndices":""}); + `,sm=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",vl=(e,r,t="f32",s,o=!1,n=32,i=!1,a=32,l=!1)=>{let u=e[1]*r[1],p=e[0]*r[0],d=o?u:n,c=o?n:u;if(!(c%r[1]===0&&d%r[0]===0&&n%r[1]===0))throw new Error(`tileAHight ${c} must be divisible by workgroupSize[1]${r[1]}, tileAWidth ${d} must be divisible by workgroupSize[0]${r[0]}, tileInner ${n} must be divisible by workgroupSize[1]${r[1]}`);let f=c/r[1],_=d/r[0],T=n/r[1],k=l?` + let localRow = i32(localId.y); + let localCol = i32(localId.x); + let globalRowStart = i32(workgroupId.y) * ${u}; + let globalColStart = i32(workgroupId.x) * ${p}; + + // 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 < ${c}; inputRow = inputRow + ${r[1]}) { + for (var inputCol = localCol; inputCol < ${d}; inputCol = inputCol + ${r[0]}) { + ${yl(o,s)} + } + } + // Load one tile of B into local memory. + for (var inputRow = localRow; inputRow < ${n}; inputRow = inputRow + ${r[1]}) { + for (var inputCol = localCol; inputCol < ${p}; inputCol = inputCol + ${r[0]}) { + mm_Bsub[inputRow][inputCol] = mm_readB(batch, + kStart + inputRow, + globalColStart + inputCol${s?", batchIndices":""}); + } + } + kStart = kStart + tileInner; + workgroupBarrier(); + + // Compute acc values for a single thread. + var BCached : array<${t}, 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 * ${r[0]}]; + } + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + let ACached = ${o?`mm_Asub[k][localRow + innerRow * ${r[1]}];`:`mm_Asub[localRow + innerRow * ${r[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 * ${r[1]}; + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + let gCol = globalColStart + localCol + innerCol * ${r[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) * ${u}; + +let tileRowA = i32(localId.y) * ${f}; +let tileColA = i32(localId.x) * ${_}; +let tileRowB = i32(localId.y) * ${T}; +// 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 < ${f}; innerRow = innerRow + 1) { + for (var innerCol = 0; innerCol < ${_}; innerCol = innerCol + 1) { + let inputRow = tileRowA + innerRow; + let inputCol = tileColA + innerCol; + ${yl(o,s)} + } + } + + // Load one tile of B into local memory. + for (var innerRow = 0; innerRow < ${T}; 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${s?", batchIndices":""}); + } + } + kStart = kStart + tileInner; + workgroupBarrier(); + + // Compute acc values for a single thread. + var BCached : array<${t}, 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) { + ${sm(o)} + 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, ${c}>; + var mm_Bsub : array, ${n}>; + const rowPerThread = ${e[1]}; + const colPerThread = ${e[0]}; + const tileInner = ${n}; + +@compute @workgroup_size(${r[0]}, ${r[1]}, ${r[2]}) +fn main(@builtin(local_invocation_id) localId : vec3, + @builtin(global_invocation_id) globalId : vec3, + @builtin(workgroup_id) workgroupId : vec3) { + let batch = ${i?"0":"i32(globalId.z)"}; + ${s?`let batchIndices = ${s.offsetToIndices("u32(batch)")};`:""} + let num_tiles = ${i?`${Math.ceil(a/n)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; + var kStart = ${i?`i32(globalId.z) * ${a}`:"0"}; + + var acc : array, rowPerThread>; + ${k} + } +`},nm=(e,r,t,s,o=!1)=>{let[n,i,a,l]=s,u=lr(s[0].type.tensor);return` + fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${n.type.indices}) -> ${_r(e,u)} { + var value = ${_r(e,u)}(0.0); + let col = colIn * ${e}; + if(row < uniforms.dim_a_outer && col < uniforms.dim_inner) + { + var aIndices: ${i.type.indices}; + ${fo("aIndices",i,i.rank-2,n.rank,"batchIndices")} + ${i.indicesSet("aIndices",i.rank-2,"u32(row)")} + ${i.indicesSet("aIndices",i.rank-1,"u32(colIn)")} + value = ${i.getByIndices("aIndices")}; + } + return value; + } + + fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${n.type.indices}) -> ${_r(e,u)} { + var value = ${_r(e,u)}(0.0); + let col = colIn * ${e}; + if(row < uniforms.dim_inner && col < uniforms.dim_b_outer) + { + var bIndices: ${a.type.indices}; + ${fo("bIndices",a,a.rank-2,n.rank,"batchIndices")} + ${a.indicesSet("bIndices",a.rank-2,"u32(row)")} + ${a.indicesSet("bIndices",a.rank-1,"u32(colIn)")} + value = ${a.getByIndices("bIndices")}; + } + return value; + } + + fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${_r(e,u)}) { + let col = colIn * ${e}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) { + var value = valueIn; + let coords = vec3(batch, row, colIn); + ${r?`value = value + ${o?"bias[colIn]":`${_r(e,u)}(bias[row])`};`:""} + ${t} + ${l.setByIndices("vec3(coords)","value")} + } + } + `},pi=(e,r,t,s,o=!1,n)=>{let i=e[0].dims,a=e[1].dims,l=i.slice(0,-2),u=a.slice(0,-2),p=s?s.slice(0,-2):t.slice(0,-2),d=Me.size(p),c=i[i.length-2],f=i[i.length-1],_=a[a.length-1],T=f%4===0&&_%4===0,k=c<=8?[4,1,1]:[4,4,1],w=[8,8,1],g=[Math.ceil(_/w[0]/k[0]),Math.ceil(c/w[1]/k[1]),Math.ceil(d/w[2]/k[2])],S=T?4:1,E=[...l,c,f/S],y=E.length,M=[...u,f,_/S],v=M.length,C=[d,c,_/S],A=[{type:6,data:c},{type:6,data:_},{type:6,data:f}];sn(r,A),A.push(...st(p,E,M));let B=["rank","rank"],K=e.length>2;K&&(A.push(...st(e[2].dims)),B.push("rank")),A.push(...st(C));let G=j=>{let ee=p.length,H=ol("batchDims",e[0].dataType,ee,1),Z=lr(e[0].dataType),X=Pe("a",e[0].dataType,y,S),oe=Pe("b",e[1].dataType,v,S),me=Ye("result",e[0].dataType,C.length,S),ae=[X,oe];if(K){let _e=o?S:1;ae.push(Pe("bias",e[2].dataType,e[2].dims.length,_e))}let V=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];nn(r,V);let F=lr(me.type.tensor),W=rn(r,me.type.value,F),re=nm(S,K,W,[H,X,oe,me],o);return` + ${j.registerUniforms(V).registerInternalVariables(H).declareVariables(...ae,me)} + ${re} + ${T?bl(k,w,Z,H):vl(k,w,Z,H)} + `};return{name:"MatMul",shaderCache:{hint:`${k};${r.activation};${T};${o}`,inputDependencies:B},getRunData:()=>({outputs:[{dims:n?n(t):t,dataType:e[0].dataType}],dispatchGroup:{x:g[0],y:g[1],z:g[2]},programUniforms:A}),getShaderSource:G}}}),om,im,Av=Be(()=>{ut(),Es(),ft(),on(),gl(),Iv(),xl(),om=(e,r,t,s,o=!1,n,i=4,a=4,l=4,u="f32")=>{let p=A=>{switch(A){case 1:return"resData = x[xIndex];";case 3:return`resData = vec3<${u}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return"resData = x[xIndex / 4];";default:throw new Error(`innerElementSize ${A} is not supported.`)}},d=A=>{switch(A){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 ${A} is not supported.`)}},c=e?` + let coord = vec4(batch, xRow, xCol, xCh); + `:` + let coord = vec4(batch, xCh, xRow, xCol); + `,f=e?` + let coords = vec4( + batch, + row / outWidth, + row % outWidth, + col); + `:` + let coords = vec4( + batch, + row, + col / outWidth, + col % outWidth); + `,_=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",T=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",k=e?"row":"col",w=e?"col":"row",g=` + let inChannels = i32(uniforms.w_shape[2]); + let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; + let outRow = ${k} / outWidth; + let outCol = ${k} % outWidth; + + let WRow = ${w} / (i32(uniforms.w_shape[1]) * inChannels); + let WCol = ${w} / 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 = ${w} % inChannels; + var resData = ${_r(i,u)}(0.0); + // The bounds checking is always needed since we use it to pad zero for + // the 'same' padding type. + if (xRow >= 0 && xRow < ${_} && xCol >= 0 && xCol < ${T}) { + ${c} + let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape)); + ${p(i)} + } + return resData;`,S=e?r&&s?` + let col = colIn * ${i}; + ${g}`:` + let col = colIn * ${i}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { + ${g} + } + return ${_r(i,u)}(0.0);`:s&&t?` + let col = colIn * ${i}; + ${g}`:` + let col = colIn * ${i}; + if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { + ${g} + } + return ${_r(i,u)}(0.0);`,E=e?s&&t?d(a):` + let col = colIn * ${a}; + if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { + ${d(a)} + } + return ${_r(a,u)}(0.0);`:` + let col = colIn * ${a}; + if (row < uniforms.dim_inner && col < uniforms.dim_a_outer) { + ${d(a)} + } + return ${_r(a,u)}(0.0);`,y=_r(l,u),M=_r(e?i:a,u),v=_r(e?a:i,u),C=rn(n,y,u);return` + fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${M} { + ${e?S:E} + } + + fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${v} { + ${e?E:S} + } + + fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${y}) { + 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])"}; + ${f} + ${Zh(o)} + ${C} + setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); + } + }`},im=(e,r,t,s,o,n,i,a,l)=>{let u=r.format==="NHWC",p=u?e[0].dims[3]:e[0].dims[1],d=t[0],c=u?t[2]:t[3],f=u?t[1]:t[2],_=u?t[3]:t[1],T=u&&(p%4===0||p%3===0)&&_%4===0,k=u?_:c*f,w=u?c*f:_,g=[8,8,1],S=s<=8?[4,1,1]:[4,4,1],E=[Math.ceil(k/g[0]/S[0]),Math.ceil(w/g[1]/S[1]),Math.ceil(d/g[2]/S[2])];vt("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${E}`);let y=T?u&&p%4!==0?3:4:1,M=g[1]*S[1],v=g[0]*S[0],C=Math.max(g[0]*y,g[1]),A=s%M===0,B=o%v===0,K=n%C===0,G=T?[y,4,4]:[1,1,1],j=[{type:6,data:s},{type:6,data:o},{type:6,data:n},{type:6,data:[r.pads[0],r.pads[1]]},{type:6,data:r.strides},{type:6,data:r.dilations}];sn(r,j),j.push(...st(e[0].dims,e[1].dims));let ee=["rank","rank"];i&&(j.push(...st(e[2].dims)),ee.push("rank")),j.push(...st(t));let H=Z=>{let X=[{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}];nn(r,X);let oe=T?4:1,me=lr(e[0].dataType),ae=` + fn setOutputAtIndex(flatIndex : i32, value : ${T?`vec4<${me}>`:me}) { + result[flatIndex] = ${T?`vec4<${me}>`:me}(value); + } + fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${T?`vec4<${me}>`:me}) { + let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3)); + setOutputAtIndex(flatIndex ${T?"/ 4":""}, value); + }`,V=Pe("x",e[0].dataType,e[0].dims.length,y===3?1:y),F=Pe("w",e[1].dataType,e[1].dims.length,oe),W=[V,F],re=Ye("result",e[0].dataType,t.length,oe);if(i){let _e=Pe("bias",e[2].dataType,e[2].dims.length,oe);W.push(_e),ae+=` + fn getBiasByOutputCoords(coords : vec4) -> ${T?`vec4<${me}>`:me} { + return bias[coords.${u?"w":"y"}${T?"/ 4":""}]; + }`}return` + ${em("uniforms.result_strides")} + //struct Uniforms { xShape : vec4, wShape : vec4, outShape : vec4, + // outShapeStrides: vec3, filterDims : vec2, pad : vec2, stride : vec2, + // dilation : vec2, dimAOuter : i32, dimBOuter : i32, dimInner : i32 }; + ${Z.registerUniforms(X).declareVariables(...W,re)} + ${ae} + ${om(u,A,B,K,i,r,G[0],G[1],G[2],me)} + ${T?bl(S,g,me,void 0,!u,C):vl(S,g,me,void 0,!u,C,!1,void 0,a)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${r.cacheKey};${y};${T};${A};${B};${K};${M};${v};${C}`,inputDependencies:ee},getRunData:()=>({outputs:[{dims:l?l(t):t,dataType:e[0].dataType}],dispatchGroup:{x:E[0],y:E[1],z:E[2]},programUniforms:j}),getShaderSource:H}}}),am,Tl,go,lm,El,um,dm,cm,Fv=Be(()=>{ut(),Es(),mt(),ft(),on(),gl(),am=e=>{let r=1;for(let t=0;ttypeof e=="number"?[e,e,e]:e,go=(e,r)=>r<=1?e:e+(e-1)*(r-1),lm=(e,r,t,s=1)=>{let o=go(r,s);return Math.floor((e[0]*(t-1)-t+o)/2)},El=(e,r,t,s,o)=>{o==null&&(o=lm(e,r[0],s[0]));let n=[0,0,0,t];for(let i=0;i<3;i++)e[i]+2*o>=r[i]&&(n[i]=Math.trunc((e[i]-r[i]+2*o)/s[i]+1));return n},um=(e,r,t,s,o,n,i,a,l,u)=>{let p,d,c,f;if(e==="VALID"&&(e=0),typeof e=="number"){p={top:e,bottom:e,left:e,right:e,front:e,back:e};let _=El([r,t,s,1],[a,l,u],1,[o,n,i],e);d=_[0],c=_[1],f=_[2]}else if(Array.isArray(e)){if(!e.every((T,k,w)=>T===w[0]))throw Error(`Unsupported padding parameter: ${e}`);p={top:e[0],bottom:e[1],left:e[2],right:e[3],front:e[4],back:e[5]};let _=El([r,t,s,1],[a,l,u],1,[o,n,i],e[0]);d=_[0],c=_[1],f=_[2]}else if(e==="SAME_UPPER"){d=Math.ceil(r/o),c=Math.ceil(t/n),f=Math.ceil(s/i);let _=(d-1)*o+a-r,T=(c-1)*n+l-t,k=(f-1)*i+u-s,w=Math.floor(_/2),g=_-w,S=Math.floor(T/2),E=T-S,y=Math.floor(k/2),M=k-y;p={top:S,bottom:E,left:y,right:M,front:w,back:g}}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:p,outDepth:d,outHeight:c,outWidth:f}},dm=(e,r,t,s,o,n=!1,i="channelsLast")=>{let a,l,u,p,d;if(i==="channelsLast")[a,l,u,p,d]=e;else if(i==="channelsFirst")[a,d,l,u,p]=e;else throw new Error(`Unknown dataFormat ${i}`);let[c,,f,_,T]=r,[k,w,g]=Tl(t),[S,E,y]=Tl(s),M=go(f,S),v=go(_,E),C=go(T,y),{padInfo:A,outDepth:B,outHeight:K,outWidth:G}=um(o,l,u,p,k,w,g,M,v,C),j=n?c*d:c,ee=[0,0,0,0,0];return i==="channelsFirst"?ee=[a,j,B,K,G]:i==="channelsLast"&&(ee=[a,B,K,G,j]),{batchSize:a,dataFormat:i,inDepth:l,inHeight:u,inWidth:p,inChannels:d,outDepth:B,outHeight:K,outWidth:G,outChannels:j,padInfo:A,strideDepth:k,strideHeight:w,strideWidth:g,filterDepth:f,filterHeight:_,filterWidth:T,effectiveFilterDepth:M,effectiveFilterHeight:v,effectiveFilterWidth:C,dilationDepth:S,dilationHeight:E,dilationWidth:y,inShape:e,outShape:ee,filterShape:r}},cm=(e,r,t,s,o,n)=>{let i=n==="channelsLast";i?e[0].dims[3]:e[0].dims[1];let a=[64,1,1],l={x:t.map((k,w)=>w)},u=[Math.ceil(am(l.x.map(k=>t[k]))/a[0]),1,1];vt("verbose",()=>`[conv3d_naive_webgpu] dispatch = ${u}`);let p=1,d=Me.size(t),c=[{type:12,data:d},{type:12,data:s},{type:12,data:o},{type:12,data:r.strides},{type:12,data:r.dilations}];sn(r,c),c.push(...st(e[0].dims,e[1].dims));let f=["rank","rank"],_=e.length===3;_&&(c.push(...st(e[2].dims)),f.push("rank")),c.push(...st(t));let T=k=>{let w=[{name:"output_size",type:"u32"},{name:"filter_dims",type:"u32",length:s.length},{name:"pads",type:"u32",length:o.length},{name:"strides",type:"u32",length:r.strides.length},{name:"dilations",type:"u32",length:r.dilations.length}];nn(r,w);let g=1,S=lr(e[0].dataType),E=Pe("x",e[0].dataType,e[0].dims.length,p),y=Pe("W",e[1].dataType,e[1].dims.length,g),M=[E,y],v=Ye("result",e[0].dataType,t.length,g),C="";if(_){let K=Pe("bias",e[2].dataType,e[2].dims.length,g);M.push(K),C+=` + fn getBiasByOutputCoords(coords : array) -> ${S} { + return bias[${i?et("coords",4,5):et("coords",1,5)}]; + }`}let A=_r(p,S),B=rn(r,A,S);return` + ${C} + fn getX(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { + let aIndices = array(d0, d1, d2, d3, d4); + return ${E.getByIndices("aIndices")}; + } + fn getW(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { + let aIndices = array(d0, d1, d2, d3, d4); + return ${y.getByIndices("aIndices")}; + } + ${k.registerUniforms(w).declareVariables(...M,v)} + ${k.mainStart()} + ${k.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let coords = ${v.offsetToIndices("global_idx")}; + let batch = ${et("coords",0,E.rank)}; + let d2 = ${i?et("coords",E.rank-1,E.rank):et("coords",1,E.rank)}; + let xFRCCorner = vec3(${i?et("coords",1,E.rank):et("coords",2,E.rank)}, + ${i?et("coords",2,E.rank):et("coords",3,E.rank)}, + ${i?et("coords",3,E.rank):et("coords",4,E.rank)}) * uniforms.strides - uniforms.pads; + let xFCorner = xFRCCorner.x; + let xRCorner = xFRCCorner.y; + let xCCorner = xFRCCorner.z; + let xShapeY = ${i?et("uniforms.x_shape",1,E.rank):et("uniforms.x_shape",2,E.rank)}; + let xShapeZ = ${i?et("uniforms.x_shape",2,E.rank):et("uniforms.x_shape",3,E.rank)}; + let xShapeW = ${i?et("uniforms.x_shape",3,E.rank):et("uniforms.x_shape",4,E.rank)}; + let xShapeU = ${i?et("uniforms.x_shape",4,E.rank):et("uniforms.x_shape",1,E.rank)}; + let inputDepthNearestVec4 = (xShapeU / 4) * 4; + let inputDepthVec4Remainder = xShapeU % 4; + + var value = 0.0; + for (var wF = 0u; wF < uniforms.filter_dims[0]; wF++) { + let xF = xFCorner + wF * uniforms.dilations[0]; + if (xF < 0 || xF >= xShapeY) { + continue; + } + + for (var wR = 0u; wR < uniforms.filter_dims[1]; wR++) { + let xR = xRCorner + wR * uniforms.dilations[1]; + if (xR < 0 || xR >= xShapeZ) { + continue; + } + + for (var wC = 0u; wC < uniforms.filter_dims[2]; wC++) { + let xC = xCCorner + wC * uniforms.dilations[2]; + if (xC < 0 || xC >= xShapeW) { + continue; + } + + for (var d1 = 0u; d1 < inputDepthNearestVec4; d1 += 4) { + ${i?`let xValues = vec4( + getX(batch, xF, xR, xC, d1), + getX(batch, xF, xR, xC, d1 + 1), + getX(batch, xF, xR, xC, d1 + 2), + getX(batch, xF, xR, xC, d1 + 3)); + `:`let xValues = vec4( + getX(batch, d1, xF, xR, xC), + getX(batch, d1 + 1, xF, xR, xC), + getX(batch, d1 + 2, xF, xR, xC), + getX(batch, d1 + 3, xF, xR, xC)); + `} + let wValues = vec4( + getW(d2, d1, wF, wR, wC), + getW(d2, d1 + 1, wF, wR, wC), + getW(d2, d1 + 2, wF, wR, wC), + getW(d2, d1 + 3, wF, wR, wC)); + value += dot(xValues, wValues); + } + if (inputDepthVec4Remainder == 1) { + ${i?`value += getX(batch, xF, xR, xC, inputDepthNearestVec4) + * getW(d2, inputDepthNearestVec4, wF, wR, wC);`:`value += getX(batch, inputDepthNearestVec4, xF, xR, xC) + * getW(d2, inputDepthNearestVec4, wF, wR, wC);`} + } else if (inputDepthVec4Remainder == 2) { + ${i?`let xValues = vec2( + getX(batch, xF, xR, xC, inputDepthNearestVec4), + getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1)); + `:`let xValues = vec2( + getX(batch, inputDepthNearestVec4, xF, xR, xC), + getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC)); + `} + let wValues = vec2( + getW(d2, inputDepthNearestVec4, wF, wR, wC), + getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC)); + value += dot(xValues, wValues); + } else if (inputDepthVec4Remainder == 3) { + ${i?`let xValues = vec3( + getX(batch, xF, xR, xC, inputDepthNearestVec4), + getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1), + getX(batch, xF, xR, xC, inputDepthNearestVec4 + 2)); + `:`let xValues = vec3( + getX(batch, inputDepthNearestVec4, xF, xR, xC), + getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC), + getX(batch, inputDepthNearestVec4 + 2, xF, xR, xC)); + `} + let wValues = vec3( + getW(d2, inputDepthNearestVec4, wF, wR, wC), + getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC), + getW(d2, inputDepthNearestVec4 + 2, wF, wR, wC)); + value += dot(xValues, wValues); + } + } + } + } + ${_?"value = value + getBiasByOutputCoords(coords)":""}; + ${B} + result[global_idx] = f32(value); + }`};return{name:"Conv3DNaive",shaderCache:{hint:`${r.cacheKey};${i};${p};${_}`,inputDependencies:f},getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:u[0],y:u[1],z:u[2]},programUniforms:c}),getShaderSource:T}}}),pm,hm,Ov=Be(()=>{ut(),mt(),ft(),on(),pm=(e,r,t,s)=>{let o=e.length>2,n=o?"value += b[output_channel];":"",i=e[0].dims,a=e[1].dims,l=r.format==="NHWC",u=l?t[3]:t[1],p=u/r.group,d=l&&p>=4?Kt(u):1,c=Me.size(t)/d,f=[{type:12,data:c},{type:12,data:r.dilations},{type:12,data:[r.strides[0],r.strides[1]]},{type:12,data:[r.pads[0],r.pads[1]]},{type:12,data:p}];sn(r,f),f.push(...st(i,[a[0],a[1],a[2],a[3]/d]));let _=o?["rank","rank","rank"]:["rank","rank"];f.push(...st([t[0],t[1],t[2],t[3]/d]));let T=k=>{let w=Ye("output",e[0].dataType,t.length,d),g=lr(w.type.tensor),S=rn(r,w.type.value,g),E=Pe("x",e[0].dataType,i.length),y=Pe("w",e[1].dataType,a.length,d),M=[E,y];o&&M.push(Pe("b",e[2].dataType,e[2].dims,d));let v=[{name:"output_size",type:"u32"},{name:"dilations",type:"u32",length:r.dilations.length},{name:"strides",type:"u32",length:2},{name:"pads",type:"u32",length:2},{name:"output_channels_per_group",type:"u32"}];nn(r,v);let C=l?` + for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[0]; wHeight++) { + let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0]; + + if (xHeight < 0u || xHeight >= uniforms.x_shape[1]) { + continue; + } + + for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[1]; wWidth++) { + let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1]; + if (xWidth < 0u || xWidth >= uniforms.x_shape[2]) { + continue; + } + + for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[2]; wInChannel++) { + let input_channel = in_channel_offset + wInChannel; + let xVal = ${E.get("batch","xHeight","xWidth","input_channel")}; + let wVal = ${y.get("wHeight","wWidth","wInChannel","output_channel")}; + value += xVal * wVal; + } + } + } + `:` + for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[1]; wInChannel++) { + let input_channel = in_channel_offset + 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[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[3]) { + continue; + } + + let xVal = ${E.get("batch","input_channel","xHeight","xWidth")}; + let wVal = ${y.get("output_channel","wInChannel","wHeight","wWidth")}; + value += xVal * wVal; + } + } + } + `;return` + ${k.registerUniforms(v).declareVariables(...M,w)} + + ${k.mainStart()} + ${k.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let outputIndices = ${w.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 * ${d} / uniforms.output_channels_per_group; + var in_channel_offset = group_id * uniforms.w_shape[${l?2:1}]; + + var value: ${w.type.value} = ${w.type.value}(0); + ${C} + ${n} + ${S} + ${w.setByOffset("global_idx","value")} + }`};return{name:"GroupedConv",shaderCache:{hint:`${r.cacheKey}_${d}`,inputDependencies:_},getRunData:()=>({outputs:[{dims:s?s(t):t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:f}),getShaderSource:T}},hm=(e,r,t,s)=>{let o=e.length>2,n=Kt(t[3]),i=Kt(t[2]),a=Me.size(t)/n/i,l=[e[0].dims[0],e[0].dims[1],e[0].dims[2],e[0].dims[3]/n],u=[e[1].dims[0],e[1].dims[1],e[1].dims[2],e[1].dims[3]/n],p=[t[0],t[1],t[2],t[3]/n],d=[{type:12,data:a},{type:6,data:[r.strides[0],r.strides[1]]},{type:6,data:[r.pads[0],r.pads[1]]}];sn(r,d),d.push(...st(l,u,p));let c=(i-1)*r.strides[1]+u[1],f=_=>{let T=Ye("output",e[0].dataType,p.length,n),k=lr(T.type.tensor),w=rn(r,T.type.value,k),g=Pe("x",e[0].dataType,l.length,n),S=Pe("w",e[1].dataType,u.length,n),E=[g,S];o&&E.push(Pe("b",e[2].dataType,e[2].dims,n));let y=o?"value += b[output_channel];":"",M=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return nn(r,M),` + ${_.registerUniforms(M).declareVariables(...E,T)} + ${_.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] / ${i}u; + let col = (index1 % width1) * ${i}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<${g.type.value}, ${c}>; + var values: array<${T.type.value}, ${i}>; + 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 < ${u[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 < ${c}; i++) { + let x_width = x_corner.y + i; + if (x_width >= 0 && u32(x_width) < uniforms.x_shape[2]) { + x_vals[i] = ${g.get("batch","u32(x_height)","u32(x_width)","input_channel")}; + } else { + x_vals[i] = ${g.type.value}(0); + } + } + for (var w_width: u32 = 0u; w_width < ${u[1]}; w_width++) { + let w_val = ${S.get("w_height","w_width","0","output_channel")}; + for (var i = 0u; i < ${i}u; i++) { + values[i] = fma(x_vals[i * u32(uniforms.strides[1]) + w_width], w_val, values[i]); + } + } + } + } + + for (var i = 0u; i < ${i}u; i++) { + var value = values[i]; + ${y} + ${w} + ${T.set("batch","row","col + i","output_channel","value")}; + } + }`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${r.cacheKey};${n};${i};${c};${u[0]};${u[1]}`,inputDependencies:o?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:s?s(t):t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:d}),getShaderSource:f}}}),mm,hi,_m,mi,Pl,Cl,fm,gm,Sl,Dv=Be(()=>{mt(),Av(),Fv(),xl(),Ov(),on(),Ml(),zs(),mm=(e,r,t,s,o,n)=>{let i=e[0],a=e.slice(n?1:2,n?3:4),l=a.length,u=r[0],p=r.slice(2).map((c,f)=>c+(c-1)*(t[f]-1)),d=a.map((c,f)=>c+s[f]+s[f+l]).map((c,f)=>Math.floor((c-p[f]+o[f])/o[f]));return d.splice(0,0,i),d.splice(n?3:1,0,u),d},hi=[2,3,1,0],_m=(e,r)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length>5)throw new Error("greater than 5D is not supported");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");let t=e[0].dims[r.format==="NHWC"?e[0].dims.length-1:1],s=e[1].dims[1]*r.group;if(t!==s)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 o=e[0].dims.length-2;if(r.dilations.length!==o)throw new Error(`dilations should be ${o}D`);if(r.strides.length!==o)throw new Error(`strides should be ${o}D`);if(r.pads.length!==o*2)throw new Error(`pads should be ${o*2}D`);if(r.kernelShape.length!==0&&r.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape")},mi=(e,r)=>{let t=e.kernelShape.slice();t.length{let r=fl(e),t=e.format,s=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],o=e.dilations,n=e.group,i=e.kernel_shape,a=e.pads,l=e.strides,u=e.w_is_const();return{autoPad:s,format:t,dilations:o,group:n,kernelShape:i,pads:a,strides:l,wIsConst:u,...r,cacheKey:`${e.format};${r.activation};`}},Cl=(e,r,t,s)=>{let o=t.format==="NHWC",n=mm(r[0].dims,r[1].dims,t.dilations,t.pads,t.strides,o);if(t.group!==1){let M=[r[0]];if(o){let v=e.kernelCustomData.wT??e.compute(Lr(r[1],hi),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=v),M.push(v)}else M.push(r[1]);r.length===3&&M.push(r[2]),!e.adapterInfo.isArchitecture("ampere")&&o&&r[1].dims[0]===t.group&&r[1].dims[1]===1&&t.dilations[0]===1&&t.dilations[1]===1?e.compute(hm(M,t,n,s),{inputs:M}):e.compute(pm(M,t,n,s),{inputs:M});return}let i=r.length===3,a=r[0].dims[o?1:2],l=r[0].dims[o?2:3],u=r[0].dims[o?3:1],p=r[1].dims[2],d=r[1].dims[3],c=n[o?1:2],f=n[o?2:3],_=n[o?3:1],T=o&&p===a&&d===l&&t.pads[0]===0&&t.pads[1]===0;if(T||p===1&&d===1&&t.dilations[0]===1&&t.dilations[1]===1&&t.strides[0]===1&&t.strides[1]===1&&t.pads[0]===0&&t.pads[1]===0){let M=n[0],v,C,A,B=[];if(o){let j=e.kernelCustomData.wT??e.compute(Lr(r[1],hi),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];if(t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=j),T){let ee=a*l*u;v=r[0].reshape([1,M,ee]),C=j.reshape([1,ee,_]),A=[1,M,_]}else v=r[0].reshape([M,a*l,u]),C=j.reshape([1,u,_]),A=[M,c*f,_];B.push(v),B.push(C)}else v=r[0].reshape([M,u,a*l]),C=r[1].reshape([1,_,u]),A=[M,_,c*f],B.push(C),B.push(v);i&&B.push(r[2]);let K=A[2],G=B[0].dims[B[0].dims.length-1];K<8&&G<8?e.compute(wl(B,t,n,A,o,s),{inputs:B}):e.compute(pi(B,t,n,A,o,s),{inputs:B});return}let k=!0,w=e.kernelCustomData.wT??e.compute(Lr(r[1],hi),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=w);let g=[r[0],w];i&&g.push(r[2]);let S=o?c*f:_,E=o?_:c*f,y=p*d*u;e.compute(im(g,t,n,S,E,y,i,k,s),{inputs:g})},fm=(e,r)=>{let t=r.format==="NHWC",s=[e.inputs[0].reshape(t?[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&&s.push(e.inputs[2]);let o=[0,r.pads[0],0,r.pads[1]],n=[1].concat(r.strides),i=[1].concat(r.dilations),a=[1].concat(r.kernelShape),l=mi({...r,pads:o,strides:n,dilations:i,kernelShape:a},s);Cl(e,s,l,u=>t?[u[0],u[2],u[3]]:[u[0],u[1],u[3]])},gm=(e,r,t)=>{let s=t.format==="NHWC"?"channelsLast":"channelsFirst",o=mi(t,r),n=t.autoPad==="NOTSET"?t.pads:t.autoPad,i=dm(r[0].dims,r[1].dims,t.strides,t.dilations,n,!1,s);e.compute(cm(r,o,i.outShape,[i.filterDepth,i.filterHeight,i.filterWidth],[i.padInfo.front,i.padInfo.top,i.padInfo.left],s))},Sl=(e,r)=>{if(_m(e.inputs,r),e.inputs[0].dims.length===3)fm(e,r);else if(e.inputs[0].dims.length===5)gm(e,e.inputs,r);else{let t=mi(r,e.inputs);Cl(e,e.inputs,t)}}}),wm,Lv=Be(()=>{ut(),Es(),mt(),ft(),wm=(e,r,t)=>{let s=e.length>2,o=r.outputShape,n=r.format==="NHWC",i=r.group,a=e[1].dims,l=a[2]/i,u=a[3],p=n?Kt(l):1,d=n&&u===1&&l>=4,c=d?Math.floor(l/4)*4:Math.floor(l/p)*p,f=l-c,_=n?Kt(u):1,T=n?u===1?p:_:1,k=Me.size(o)/_,w=[Math.ceil(k/64),1,1];vt("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${w}`);let g=["rank","rank"],S=[r.strides[0],r.strides[1]],E=[r.kernelShape[n?1:2],r.kernelShape[n?2:3]],y=[r.dilations[0],r.dilations[1]],M=[E[0]+(r.dilations[0]<=1?0:(r.kernelShape[n?1:2]-1)*(r.dilations[0]-1)),E[1]+(r.dilations[1]<=1?0:(r.kernelShape[n?2:3]-1)*(r.dilations[1]-1))],v=[M[0]-1-Math.floor((r.pads[0]+r.pads[2])/2),M[1]-1-Math.floor((r.pads[1]+r.pads[3])/2)],C=[{type:12,data:k},{type:12,data:S},{type:12,data:E},{type:12,data:y},{type:12,data:M},{type:6,data:v},{type:12,data:c},{type:12,data:l},{type:12,data:u},...st(e[0].dims,e[1].dims)];s&&(C.push(...st(e[2].dims)),g.push("rank")),C.push(...st(o));let A=B=>{let K=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:S.length},{name:"filter_dims",type:"u32",length:E.length},{name:"dilations",type:"u32",length:E.length},{name:"effective_filter_dims",type:"u32",length:M.length},{name:"pads",type:"i32",length:v.length},{name:"input_channels_per_group_int",type:"u32"},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],G=lr(e[0].dataType),j=n?1:2,ee=n?2:3,H=n?3:1,Z=Pe("W",e[1].dataType,e[1].dims.length,T),X=Pe("Dy",e[0].dataType,e[0].dims.length,p),oe=[X,Z];s&&oe.push(Pe("bias",e[2].dataType,[o[H]].length,_));let me=Ye("result",e[0].dataType,o.length,_),ae=()=>{let W="";if(d)p===4?W+=` + let xValue = ${X.getByOffset("x_offset")}; + let wValue = ${Z.getByOffset("w_offset")}; + dotProd = dotProd + dot(xValue, wValue); + x_offset += 1u; + w_offset += 1u;`:p===2?W+=` + dotProd = dotProd + dot(vec4<${G}>(${X.getByOffset("x_offset")}, ${X.getByOffset("x_offset + 1u")}), vec4<${G}>(${Z.getByOffset("w_offset")}, ${Z.getByOffset("w_offset + 1u")})); + x_offset += 2u; + w_offset += 2u;`:p===1&&(W+=` + dotProd = dotProd + dot(vec4<${G}>(${X.getByOffset("x_offset")}, ${X.getByOffset("x_offset + 1u")}, ${X.getByOffset("x_offset + 2u")}, ${X.getByOffset("x_offset + 3u")}), vec4<${G}>(${Z.getByOffset("w_offset")}, ${Z.getByOffset("w_offset + 1u")}, ${Z.getByOffset("w_offset + 2u")}, ${Z.getByOffset("w_offset + 3u")})); + x_offset += 4u; + w_offset += 4u;`);else if(W+=` + let xValue = ${n?X.getByOffset(`${X.indicesToOffset(`${X.type.indices}(batch, idyR, idyC, inputChannel)`)} / ${p}`):X.get("batch","inputChannel","idyR","idyC")}; + `,p===1)W+=` + let w_offset = ${Z.indicesToOffset(`${Z.type.indices}(u32(wRPerm), u32(wCPerm), inputChannel, wOutChannel)`)}; + let wValue = ${Z.getByOffset(`w_offset / ${T}`)}; + dotProd = dotProd + xValue * wValue;`;else for(let re=0;re{if(f===0)return"";if(!d)throw new Error(`packInputAs4 ${d} is not true.`);let W="";if(p===1){W+="dotProd = dotProd";for(let re=0;re(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 = ${me.type.value}(0.0); + var wR: u32 = 0; + if (uniforms.dilations.x == 1) { + // Minimum wR >= 0 that satisfies (dyRCorner + wR) % (uniforms.strides.x) == 0 + wR = u32(((dyRCorner + i32(uniforms.strides.x) - 1) / i32(uniforms.strides.x)) * i32(uniforms.strides.x) - dyRCorner); + } + for (; wR < uniforms.effective_filter_dims.x; wR = wR + 1) { + if (wR % uniforms.dilations.x != 0) { + continue; + } + let dyR = (${G}(dyRCorner) + ${G}(wR)) / ${G}(uniforms.strides[0]); + let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x; + if (dyR < 0.0 || dyR >= ${G}(uniforms.Dy_shape[${j}]) || fract(dyR) > 0.0 || + wRPerm < 0) { + continue; + } + let idyR: u32 = u32(dyR); + var wC: u32 = 0; + if (uniforms.dilations.y == 1) { + // Minimum wC >= 0 that satisfies (dyCCorner + wC) % (uniforms.strides.y) == 0 + wC = u32(((dyCCorner + i32(uniforms.strides.y) - 1) / i32(uniforms.strides.y)) * i32(uniforms.strides.y) - dyCCorner); + } + for (; wC < uniforms.effective_filter_dims.y; wC = wC + 1) { + if (wC % uniforms.dilations.y != 0) { + continue; + } + let dyC = (${G}(dyCCorner) + ${G}(wC)) / ${G}(uniforms.strides.y); + let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y; + if (dyC < 0.0 || dyC >= ${G}(uniforms.Dy_shape[${ee}]) || + fract(dyC) > 0.0 || wCPerm < 0) { + continue; + } + let idyC: u32 = u32(dyC); + var inputChannel = groupId * uniforms.input_channels_per_group; + ${d?` + var x_offset = ${X.indicesToOffset(`${X.type.indices}(batch, idyR, idyC, inputChannel)`)} / ${p}; + var w_offset = ${Z.indicesToOffset(`${Z.type.indices}(wRPerm, wCPerm, inputChannel, wOutChannel)`)} / ${T}; + `:""} + for (var d2: u32 = 0; d2 < uniforms.input_channels_per_group_int; d2 = d2 + ${d?4:p}) { + ${ae()} + inputChannel = inputChannel + ${d?4:p}; + } + ${V()} + wC = wC + uniforms.strides.y - 1; + } + wR = wR + uniforms.strides[0] - 1; + } + let value = dotProd${s?` + bias[d1 / ${_}]`:""}; + ${me.setByOffset("global_idx","value")}; + `;return` + ${B.registerUniforms(K).declareVariables(...oe,me)} + ${B.mainStart()} + ${B.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}; + ${F}}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${r.cacheKey};${p}${T}${_}${d}${f}`,inputDependencies:g},getRunData:()=>({dispatchGroup:{x:w[0],y:w[1],z:w[2]},outputs:[{dims:t?t(o):o,dataType:e[0].dataType}],programUniforms:C}),getShaderSource:A}}}),Mm,bm,ym,$l,vm,xm,kl,Tm,Em,zv=Be(()=>{Lv(),on(),zs(),Mm=(e,r,t,s,o,n)=>(e-1)*r+t+(s-1)*o+1-n,bm=(e,r,t,s,o)=>{let n=Math.floor(e/2);r==="SAME_UPPER"?(t[s]=n,t[o]=e-n):r==="SAME_LOWER"&&(t[s]=e-n,t[o]=n)},ym=(e,r,t,s,o,n,i,a,l,u)=>{let p=e.length-2,d=u.length===0;l.length{let t=e.kernelShape.slice();if(e.kernelShape.length===0||e.kernelShape.reduce((d,c)=>d*c,1)===0){t.length=0;for(let d=2;dd+c,0)===0){let d=r[0].dims.length-2;l=new Array(d).fill(1)}let u=e.strides.slice();if(u.reduce((d,c)=>d+c,0)===0){let d=r[0].dims.length-2;u=new Array(d).fill(1)}ym(a,t,l,e.autoPad,e.group,o,u,s,i,n);let p=Object.assign({},e);return Object.assign(p,{kernelShape:t,pads:o,outputPadding:i,outputShape:n,dilations:l,strides:u}),p},vm=e=>{let r=fl(e),t=e.format,s=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof e.autoPad>"u"?0:e.autoPad],o=e.dilations,n=e.group,i=e.kernelShape,a=e.pads,l=e.strides,u=e.wIsConst(),p=e.outputPadding,d=e.outputShape;return{autoPad:s,format:t,dilations:o,group:n,kernelShape:i,outputPadding:p,outputShape:d,pads:a,strides:l,wIsConst:u,...r,cacheKey:`${e.format};${r.activation};`}},xm=(e,r)=>{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 t=e[0].dims[r.format==="NHWC"?e[0].dims.length-1:1],s=e[1].dims[0];if(t!==s)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");let o=e[1].dims[1]*r.group;if(e.length===3&&(e[2].dims.length!==1||e[2].dims[0]!==o))throw new Error("invalid bias");let n=e[0].dims.length-2;if(r.dilations.reduce((i,a)=>i+a,0)>0&&r.dilations.length!==n)throw new Error(`dilations should be ${n}D`);if(r.strides.reduce((i,a)=>i+a,0)>0&&r.strides.length!==n)throw new Error(`strides should be ${n}D`);if(r.pads.reduce((i,a)=>i+a,0)>0&&r.pads.length!==n*2)throw new Error(`pads should be ${n*2}D`);if(r.outputPadding.length!==n&&r.outputPadding.length!==0)throw new Error(`output_padding should be ${n}D`);if(r.kernelShape.reduce((i,a)=>i+a,0)>0&&r.kernelShape.length!==0&&r.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape");if(r.outputShape.length!==0&&r.outputShape.length!==e[0].dims.length-2)throw new Error("invalid output shape")},kl=(e,r,t,s)=>{let o=e.kernelCustomData.wT??e.compute(Lr(r[1],[2,3,0,1]),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=o);let n=[r[0],o];r.length===3&&n.push(r[2]),e.compute(wm(n,t,s),{inputs:n})},Tm=(e,r)=>{let t=r.format==="NHWC",s=[e.inputs[0].reshape(t?[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&&s.push(e.inputs[2]);let o=r.kernelShape;(o.length===0||o[0]===0)&&(o=[e.inputs[1].dims[2]]);let n=r.dilations;(n.length===0||n[0]===0)&&(n=[1]);let i=r.strides;(i.length===0||i[0]===0)&&(i=[1]);let a=r.pads;a.length===0&&(a=[0,0]),a=[0,a[0],0,a[1]],i=[1].concat(i),n=[1].concat(n),o=[1].concat(o);let l=r.outputPadding;l=[0].concat(l);let u=$l({...r,pads:a,strides:i,dilations:n,kernelShape:o,outputPadding:l},s);kl(e,s,u,p=>t?[p[0],p[2],p[3]]:[p[0],p[1],p[3]])},Em=(e,r)=>{if(xm(e.inputs,r),e.inputs[0].dims.length===3)Tm(e,r);else{let t=$l(r,e.inputs);kl(e,e.inputs,t)}}}),Pm,Cm,Sm,Bv=Be(()=>{ut(),mt(),Xt(),ft(),Pm=(e,r,t,s)=>{let o=Me.size(r),n=r.length,i=Pe("input",e,n),a=Ye("output",e,n),l=t.dataType===6?t.getInt32Array()[0]:Number(t.getBigInt64Array()[0]),u=Me.normalizeAxis(l,n),p=d=>{let c=` i32(${i.indicesGet("inputIndices","uniforms.axis")}) `,f=et("uniforms.input_shape","uniforms.axis",n),_=s.reverse?c+(s.exclusive?" + 1":""):"0",T=s.reverse?f:c+(s.exclusive?"":" + 1");return` + ${d.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(i,a)} + ${d.mainStart()} + ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var inputIndices = ${a.offsetToIndices("global_idx")}; + var sum = ${a.type.value}(0); + let first : i32 = ${_}; + let last : i32 = ${T}; + for (var i : i32 = first; i < last; i++) { + ${i.indicesSet("inputIndices","uniforms.axis","u32(i)")}; + sum = sum + ${i.getByIndices("inputIndices")}; + } + ${a.setByOffset("global_idx","sum")}; + }`};return{name:"CumSum",shaderCache:{hint:s.cacheKey,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:r,dataType:e}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:[{type:12,data:o},{type:12,data:u},...st(r,r)]}),getShaderSource:p}},Cm=(e,r)=>{let t=e.inputs[0].dims,s=e.inputs[0].dataType,o=e.inputs[1];e.compute(Pm(s,t,o,r),{inputs:[0]})},Sm=e=>{let r=e.exclusive===1,t=e.reverse===1;return St({exclusive:r,reverse:t})}}),$m,km,Im,Am,Fm,Rv=Be(()=>{ut(),mt(),Xt(),ft(),$m=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.")},km=(e,r,t,s)=>{let o=[];o.push(`fn perm(i: ${s.type.indices}) -> ${t.type.indices} { + var a: ${t.type.indices};`);for(let n=0;n{let t,s,o,n,i,a,l=r.format==="NHWC",u=r.blocksize,p=r.mode==="DCR";l?([t,s,o,n]=e.dims,i=p?[t,s,o,u,u,n/u**2]:[t,s,o,n/u**2,u,u],a=p?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([t,s,o,n]=[e.dims[0],e.dims[2],e.dims[3],e.dims[1]],i=p?[t,u,u,n/u**2,s,o]:[t,n/u**2,u,u,s,o],a=p?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let d=e.reshape(i),c=d.dims.length,f=e.dataType,_=Pe("a",f,c),T=Ye("output",f,c),k=w=>` + ${w.registerUniform("output_size","u32").declareVariables(_,T)} + + ${km(a,c,_,T)} + + ${w.mainStart()} + ${w.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${T.offsetToIndices("global_idx")}; + let aIndices = perm(indices); + + ${T.setByOffset("global_idx",_.getByIndices("aIndices"))} + }`;return{name:"DepthToSpace",shaderCache:{hint:`${e.dims};${r.blocksize};${r.mode}`,inputDependencies:["rank"]},getRunData:w=>{let g=l?[t,s*u,o*u,n/u**2]:[t,n/u**2,s*u,o*u],S=Me.size(g),E=d.dims,y=Me.sortBasedOnPerm(E,a);return{outputs:[{dims:g,dataType:w[0].dataType}],dispatchGroup:{x:Math.ceil(S/64)},programUniforms:[{type:12,data:S},...st(E,y)]}},getShaderSource:k}},Am=(e,r)=>{$m(e.inputs),e.compute(Im(e.inputs[0],r))},Fm=e=>St({blocksize:e.blocksize,mode:e.mode,format:e.format})}),_i,wo,Il,Om,Dm,Lm,zm,Al,Bm,Rm,jm,jv=Be(()=>{ut(),mt(),Xt(),ft(),_i="[a-zA-Z]|\\.\\.\\.",wo="("+_i+")+",Il="^"+wo+"$",Om="("+wo+",)*"+wo,Dm="^"+Om+"$",Lm=class{constructor(e=-1){this.symbolToIndices=new Map,this.inputIndex=e}addSymbol(e,r){let t=this.symbolToIndices.get(e);t===void 0?t=[r]:t.push(r),this.symbolToIndices.set(e,t)}},zm=class{constructor(e,r){var o;this.equation=r,this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=new Array,this.outputDims=[];let[t,s]=r.includes("->")?r.split("->",2):[r,""];if(!t.match(RegExp(Dm)))throw new Error("Invalid LHS term");if(t.split(",").forEach((n,i)=>{let a=e[i].dims.slice();if(!n.match(RegExp(Il)))throw new Error("Invalid LHS term");let l=this.processTerm(n,!0,a,i);this.lhs.push(l)}),s==="")s+=[...this.symbolToInfo.entries()].filter(([n,i])=>i.count===1||n==="...").map(([n])=>n).join("");else if(!s.match(RegExp(wo)))throw new Error("Invalid RHS");(o=s.match(RegExp(_i,"g")))==null||o.forEach(n=>{if(n==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let i=this.symbolToInfo.get(n);if(i===void 0)throw new Error("Invalid RHS symbol");this.outputDims.push(i.dimValue)}}),this.rhs=this.processTerm(s,!1,this.outputDims)}addSymbol(e,r,t){let s=this.symbolToInfo.get(e);if(s!==void 0){if(s.dimValue!==r&&s.count!==1)throw new Error("Dimension mismatch");s.count++,s.inputIndices.push(t)}else s={count:1,dimValue:r,inputIndices:[t]};this.symbolToInfo.set(e,s)}processTerm(e,r,t,s=-1){let o=t.length,n=!1,i=[],a=0;if(!e.match(RegExp(Il))&&!r&&e!=="")throw new Error("Invalid LHS term");let l=e.match(RegExp(_i,"g")),u=new Lm(s);return l==null||l.forEach((p,d)=>{if(p==="..."){if(n)throw new Error("Only one ellipsis is allowed per input term");n=!0;let c=o-l.length+1;if(c<0)throw new Error("Ellipsis out of bounds");if(i=t.slice(a,a+c),this.hasEllipsis){if(this.ellipsisDims.length!==i.length||this.ellipsisDims.toString()!==i.toString())throw new Error("Ellipsis dimensions mismatch")}else if(r)this.hasEllipsis=!0,this.ellipsisDims=i;else throw new Error("Ellipsis must be specified in the LHS");for(let f=0;fe+"_max",Bm=(e,r,t,s)=>{let o=e.map(u=>u.length).map((u,p)=>Pe(`input${p}`,r,u)),n=Me.size(s),i=Ye("output",r,s.length),a=[...t.symbolToInfo.keys()].filter(u=>!t.rhs.symbolToIndices.has(u)),l=u=>{let p=[],d="var prod = 1.0;",c="var sum = 0.0;",f="sum += prod;",_=[],T=[],k=[],w=[],g=t.symbolToInfo.size===t.rhs.symbolToIndices.size;t.symbolToInfo.forEach((E,y)=>{var M;if(t.rhs.symbolToIndices.has(y)){let v=(M=t.rhs.symbolToIndices.get(y))==null?void 0:M[0];v!==void 0&&t.lhs.forEach((C,A)=>{if(E.inputIndices.includes(A)){let B=C.symbolToIndices.get(y);if(B===void 0)throw new Error("Invalid symbol error");B.forEach(K=>{p.push(`${o[A].indicesSet(`input${A}Indices`,K,i.indicesGet("outputIndices",v))}`)})}})}else t.lhs.forEach((v,C)=>{if(E.inputIndices.includes(C)){let A=v.symbolToIndices.get(y);if(A===void 0)throw new Error("Invalid symbol error");A.forEach(B=>{_.push(`${o[C].indicesSet(`input${C}Indices`,B,`${y}`)}`)}),w.push(`prod *= ${o[C].getByIndices(`input${C}Indices`)};`)}}),T.push(`for(var ${y}: u32 = 0; ${y} < uniforms.${Al(y)}; ${y}++) {`),k.push("}")});let S=g?[...p,`let sum = ${o.map((E,y)=>E.getByIndices(`input${y}Indices`)).join(" * ")};`]:[...p,c,...T,..._,d,...w,f,...k];return` + ${u.registerUniforms(a.map(E=>({name:`${Al(E)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...o,i)} + + ${u.mainStart()} + ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var outputIndices = ${i.offsetToIndices("global_idx")}; + ${o.map((E,y)=>`var input${y}Indices: ${o[y].type.indices};`).join(` +`)} + ${S.join(` +`)}; + ${i.setByOffset("global_idx","sum")}; + }`};return{name:"Einsum",shaderCache:{hint:t.equation,inputDependencies:e.map(()=>"rank")},getRunData:()=>{let u=a.filter(d=>t.symbolToInfo.has(d)).map(d=>{var c;return{type:12,data:((c=t.symbolToInfo.get(d))==null?void 0:c.dimValue)||0}});u.push({type:12,data:n});let p=e.map((d,c)=>[...st(d)]).reduce((d,c)=>d.concat(c),u);return p.push(...st(s)),{outputs:[{dims:s,dataType:r}],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:p}},getShaderSource:l}},Rm=(e,r)=>{let t=new zm(e.inputs,r.equation),s=t.outputDims,o=e.inputs.map((n,i)=>n.dims);e.compute(Bm(o,e.inputs[0].dataType,t,s))},jm=e=>{let r=e.equation.replace(/\s+/g,"");return St({equation:r})}}),Nm,Fl,Vm,Um,Wm,Nv=Be(()=>{ut(),mt(),ft(),Nm=e=>{if(!e||e.length!==2)throw new Error("Expand requires 2 input.");let r=e[0].dims,t=Array.from(e[1].getBigInt64Array(),Number),s=t.length{let t=e.length-r.length,s=[];for(let o=0;oe.length>r.length?Fl(e,r):Fl(r,e),Um=e=>{let r=e[0].dims,t=Array.from(e[1].getBigInt64Array(),Number),s=Vm(r,t),o=e[0].dataType,n=o===9||Me.size(r)===1,i=o===9||r.length>0&&r[r.length-1]%4===0?4:1,a=n||s.length>0&&s[s.length-1]%4===0?4:1,l=Math.ceil(Me.size(s)/a),u=d=>{let c=Pe("input",o,r.length,i),f=Ye("output",o,s.length,a),_;if(o===9){let T=(k,w,g="")=>` + let outputIndices${w} = ${f.offsetToIndices(`outputOffset + ${w}u`)}; + let offset${w} = ${c.broadcastedIndicesToOffset(`outputIndices${w}`,f)}; + let index${w} = offset${w} / 4u; + let component${w} = offset${w} % 4u; + ${k}[${w}] = ${g}(${c.getByOffset(`index${w}`)}[component${w}]); + `;_=` + let outputOffset = global_idx * ${a}; + var data = vec4(0); + ${T("data",0,"u32")} + ${T("data",1,"u32")} + ${T("data",2,"u32")} + ${T("data",3,"u32")} + ${f.setByOffset("global_idx","data")} + }`}else _=` + let outputIndices = ${f.offsetToIndices(`global_idx * ${a}`)}; + let inputOffset = ${c.broadcastedIndicesToOffset("outputIndices",f)}; + let data = ${f.type.value}(${c.getByOffset(`inputOffset / ${i}`)}); + ${f.setByOffset("global_idx","data")} + }`;return` + ${d.registerUniform("vec_size","u32").declareVariables(c,f)} + ${d.mainStart()} + ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${_}`},p=[{type:12,data:l},...st(r,s)];return{name:"Expand",shaderCache:{hint:`${s.length};${i}${a}`,inputDependencies:["rank"]},getShaderSource:u,getRunData:()=>({outputs:[{dims:s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:p})}},Wm=e=>{Nm(e.inputs),e.compute(Um(e.inputs),{inputs:[0]})}}),Gm,Km,Vv=Be(()=>{ut(),mt(),ft(),_l(),Gm=e=>{let r=e[0].dataType,t=Me.size(e[0].dims),s=Me.size(e[1].dims),o=s%4===0,n=i=>{let a=Pe("x",r,[1],4),l=Pe("bias",r,[1],4),u=Ye("y",r,[1],4),p=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],d=f=>` + let bias${f}_offset: u32 = (global_idx * 4 + ${f}) % uniforms.bias_size; + let bias${f} = ${l.getByOffset(`bias${f}_offset / 4`)}[bias${f}_offset % 4];`,c=o?` + let bias = ${l.getByOffset("global_idx % (uniforms.bias_size / 4)")};`:`${d(0)}${d(1)}${d(2)}${d(3)} + let bias = ${a.type.value}(bias0, bias1, bias2, bias3);`;return`${i.registerUniforms(p).declareVariables(a,l,u)} + + ${hl(yr(r))} + + ${i.mainStart(Vn)} + ${i.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")} + + let x = ${a.getByOffset("global_idx")}; + ${c} + let x_in = x + bias; + ${u.setByOffset("global_idx",ml("x_in"))} + }`};return{name:"FastGeluWithBias",shaderCache:{hint:`${o}`,inputDependencies:["type","type"]},getShaderSource:n,getRunData:i=>({outputs:[{dims:i[0].dims,dataType:i[0].dataType}],programUniforms:[{type:12,data:Math.ceil(t/4)},{type:12,data:s}],dispatchGroup:{x:Math.ceil(t/Vn/4)}})}},Km=e=>{e.inputs.length<2||Me.size(e.inputs[1].dims)===0?Ph(e):e.compute(Gm(e.inputs))}}),Hm,qm,Xm,Qm,Uv=Be(()=>{ut(),mt(),Xt(),ft(),Hm=e=>{if(!e||e.length!==2)throw new Error("Gather requires 2 inputs.")},qm=(e,r)=>{let t=e[0].dims,s=e[1].dims,o=t.length,n=Me.normalizeAxis(r.axis,o),i=t.slice(0);i.splice(n,1,...s);let a=t[n],l=e[0].dataType===9?4:1,u=Math.ceil(Me.size(i)/l),p=[{type:12,data:u},{type:6,data:a},{type:12,data:n},...st(e[0].dims,e[1].dims,i)],d=c=>{let f=Pe("data",e[0].dataType,e[0].dims.length,l),_=Pe("inputIndices",e[1].dataType,e[1].dims.length),T=Ye("output",e[0].dataType,i.length,l),k=g=>{let S=s.length,E=`var indicesIndices${g} = ${_.type.indices}(0);`;for(let y=0;y1?`indicesIndices${g}[${y}]`:`indicesIndices${g}`} = ${i.length>1?`outputIndices${g}[uniforms.axis + ${y}]`:`outputIndices${g}`};`;E+=` + var idx${g} = ${_.getByIndices(`indicesIndices${g}`)}; + if (idx${g} < 0) { + idx${g} = idx${g} + uniforms.axisDimLimit; + } + var dataIndices${g} : ${f.type.indices}; + `;for(let y=0,M=0;y1?`dataIndices${g}[${y}]`:`dataIndices${g}`} = u32(idx${g});`,M+=S):(E+=`${o>1?`dataIndices${g}[${y}]`:`dataIndices${g}`} = ${i.length>1?`outputIndices${g}[${M}]`:`outputIndices${g}`};`,M++);return E},w;if(e[0].dataType===9){let g=(S,E,y="")=>` + let outputIndices${E} = ${T.offsetToIndices(`outputOffset + ${E}u`)}; + ${k(E)}; + let offset${E} = ${f.indicesToOffset(`dataIndices${E}`)}; + let index${E} = offset${E} / 4u; + let component${E} = offset${E} % 4u; + ${S}[${E}] = ${y}(${f.getByOffset(`index${E}`)}[component${E}]); + `;w=` + let outputOffset = global_idx * ${l}; + var value = vec4(0); + ${g("value",0,"u32")} + ${g("value",1,"u32")} + ${g("value",2,"u32")} + ${g("value",3,"u32")} + ${T.setByOffset("global_idx","value")} + `}else w=` + let outputIndices = ${T.offsetToIndices("global_idx")}; + ${k("")}; + let value = ${f.getByIndices("dataIndices")}; + ${T.setByOffset("global_idx","value")}; + `;return` + ${c.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(f,_,T)} + ${c.mainStart()} + ${c.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + ${w} + }`};return{name:"Gather",shaderCache:{hint:r.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:i,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:p}),getShaderSource:d}},Xm=e=>St({axis:e.axis}),Qm=(e,r)=>{let t=e.inputs;Hm(t),e.compute(qm(e.inputs,r))}}),Jm,Ym,Zm,Wv=Be(()=>{ut(),mt(),ft(),Jm=(e,r,t,s,o,n,i,a,l)=>{let u=[{type:12,data:n},{type:12,data:s},{type:12,data:o},{type:12,data:t},{type:12,data:i},{type:12,data:a},{type:12,data:l}],p=[n];u.push(...st(r.dims,p));let d=c=>{let f=Pe("indices_data",r.dataType,r.dims.length),_=Ye("input_slice_offsets_data",12,1,1),T=[f,_],k=[{name:"output_size",type:"u32"},{name:"batch_dims",type:"u32"},{name:"input_dims",type:"u32",length:o.length},{name:"sizes_from_slice_dims_data",type:"u32",length:t.length},{name:"num_slices_per_batch",type:"u32"},{name:"input_batch_stride",type:"u32"},{name:"num_slice_dims",type:"u32"}];return` + ${c.registerUniforms(k).declareVariables(...T)} + ${c.mainStart()} + ${c.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let batch_idx = global_idx / uniforms.num_slices_per_batch; + let base_offset = batch_idx * uniforms.input_batch_stride; + + let slice_indices_base_offset = global_idx * uniforms.num_slice_dims; + var relative_slice_offset = 0; + for (var dim_idx = 0u; dim_idx < uniforms.num_slice_dims; dim_idx ++) { + var index = i32(indices_data[dim_idx + slice_indices_base_offset].x); + let input_dim_idx = uniforms.batch_dims + dim_idx; + if (index < 0) { + ${o.length===1?"index += i32(uniforms.input_dims);":"index += i32(uniforms.input_dims[input_dim_idx]);"} + } + ${t.length===1?"relative_slice_offset += index * i32(uniforms.sizes_from_slice_dims_data);":"relative_slice_offset += index * i32(uniforms.sizes_from_slice_dims_data[dim_idx]);"} + } + + input_slice_offsets_data[global_idx] = base_offset + u32(relative_slice_offset); + }`};return e.compute({name:"computeSliceOffsets",shaderCache:{hint:`${o.length}_${t.length}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:p,dataType:e.inputs[1].dataType}],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:u}),getShaderSource:d},{inputs:[r],outputs:[-1]})[0]},Ym=(e,r)=>{let t=e.inputs,s=t[0].dims,o=t[0].dataType,n=t[1].dims,i=n[n.length-1],a=Me.sizeToDimension(n,n.length-1),l=Me.sizeFromDimension(s,r.batchDims+i),u=Me.sizeToDimension(s,r.batchDims),p=Me.sizeFromDimension(s,r.batchDims),d=a/u,c=new Array(i),f=l;for(let E=0;Es.length)throw new Error("last dimension of indices must not be larger than rank of input tensor");let k=n.slice(0,-1).concat(s.slice(T)),w=Me.size(k),g=[{type:12,data:w},{type:12,data:l},...st(t[0].dims,_.dims,k)],S=E=>{let y=Pe("data",t[0].dataType,t[0].dims.length),M=Pe("slice_offsets",12,_.dims.length),v=Ye("output",t[0].dataType,k.length);return` + ${E.registerUniform("output_size","u32").registerUniform("slice_size","u32").declareVariables(y,M,v)} + ${E.mainStart()} + ${E.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let slice_offset = slice_offsets[global_idx / uniforms.slice_size]; + output[global_idx] = data[u32(slice_offset) + global_idx % uniforms.slice_size]; + }`};e.compute({name:"GatherND",shaderCache:{hint:r.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:k,dataType:o}],dispatchGroup:{x:Math.ceil(w/64)},programUniforms:g}),getShaderSource:S},{inputs:[t[0],_]})},Zm=e=>({batchDims:e.batch_dims,cacheKey:""})}),e_,t_,r_,s_,Gv=Be(()=>{ut(),mt(),Xt(),ft(),e_=(e,r)=>{if(e.length<3||e.length>4)throw new Error("GatherBlockQuantized requires 3 or 4 inputs.");let t=Me.normalizeAxis(r.quantizeAxis,e[0].dims.length),s=r.blockSize,o=e[0],n=e[2],i=e.length===4?e[3]:void 0;if(n.dims.length!==o.dims.length||!o.dims.map((a,l)=>l===t?Math.ceil(a/s)===n.dims[l]:a===n.dims[l]).reduce((a,l)=>a&&l,!0))throw new Error("Scales must have the same rank as the input tensor and the dims should match except on gatherAxis.");if(i){if(i.dataType!==o.dataType)throw new Error("Zero point must have the same data type as the input tensor.");if(i.dims.length!==n.dims.length||!i.dims.map((a,l)=>a===n.dims[l]).reduce((a,l)=>a&&l,!0))throw new Error("Zero point must have the same rank as the input tensor and the dims should match except on quantizeAxis.")}},t_=(e,r)=>{let t=e[0].dims,s=e[1].dims,o=t.length,n=Me.normalizeAxis(r.gatherAxis,o),i=Me.normalizeAxis(r.quantizeAxis,o),a=t.slice(0);a.splice(n,1,...s);let l=Me.size(a),u=e[2].dataType,p=e[0].dataType===22,d=[{type:12,data:l},{type:12,data:i},{type:12,data:n},{type:12,data:r.blockSize},...st(...e.map((f,_)=>f.dims),a)],c=f=>{let _=Pe("data",e[0].dataType,e[0].dims.length),T=Pe("inputIndices",e[1].dataType,e[1].dims.length),k=Pe("scales",e[2].dataType,e[2].dims.length),w=e.length>3?Pe("zeroPoint",e[3].dataType,e[3].dims.length):void 0,g=Ye("output",u,a.length),S=[_,T,k];w&&S.push(w);let E=[{name:"output_size",type:"u32"},{name:"quantize_axis",type:"u32"},{name:"gather_axis",type:"u32"},{name:"block_size",type:"u32"}];return` + ${f.registerUniforms(E).declareVariables(...S,g)} + ${f.mainStart()} + let output_indices = ${g.offsetToIndices("global_idx")}; + var indices_indices = ${T.type.indices}(0); + ${s.length>1?` + for (var i: u32 = 0; i < ${s.length}; i++) { + let index = ${g.indicesGet("output_indices","uniforms.gather_axis + i")}; + ${T.indicesSet("indices_indices","i","index")}; + }`:`indices_indices = ${g.indicesGet("output_indices","uniforms.gather_axis")};`}; + var data_indices = ${_.type.indices}(0); + for (var i: u32 = 0; i < uniforms.gather_axis; i++) { + let index = ${g.indicesGet("output_indices","i")}; + ${_.indicesSet("data_indices","i","index")}; + } + var index_from_indices = ${T.getByIndices("indices_indices")}; + if (index_from_indices < 0) { + index_from_indices += ${t[n]}; + } + ${_.indicesSet("data_indices","uniforms.gather_axis","u32(index_from_indices)")}; + for (var i = uniforms.gather_axis + 1; i < ${a.length}; i++) { + let index = ${g.indicesGet("output_indices",`i + ${s.length} - 1`)}; + ${_.indicesSet("data_indices","i","index")}; + } + let data_offset = ${_.indicesToOffset("data_indices")}; + let data_index = data_offset % 8; + // Convert 4-bit packed data to 8-bit packed data. + let packed_4bit_quantized_data = ${_.getByOffset("data_offset / 8")}; + let packed_8bit_quantized_data = (packed_4bit_quantized_data >> (4 * (data_index % 2))) & 0x0f0f0f0f; + let quantized_data_vec = ${p?"unpack4xI8":"unpack4xU8"}(u32(packed_8bit_quantized_data)); + let quantized_data = quantized_data_vec[data_index / 2]; + var scale_indices = data_indices; + let quantize_axis_index = ${k.indicesGet("data_indices","uniforms.quantize_axis")} / uniforms.block_size; + ${k.indicesSet("scale_indices","uniforms.quantize_axis","quantize_axis_index")}; + var scale = ${k.getByIndices("scale_indices")}; + ${w?` + let zero_point_indices = scale_indices; + let zero_point_offset = ${w.indicesToOffset("zero_point_indices")}; + let zero_point_index = zero_point_offset % 8; + let packed_4bit_zero_points = ${w.getByOffset("zero_point_offset / 8")}; + let packed_8bit_zero_points = (packed_4bit_zero_points >> (4 * (zero_point_index % 2))) & 0x0f0f0f0f; + let zero_point_vec = ${p?"unpack4xI8":"unpack4xU8"}(u32(packed_8bit_zero_points)); + let zero_point = zero_point_vec[zero_point_index / 2];`:"var zero_point = 0"}; + let dequantized_data = ${yr(u)}(quantized_data - zero_point) * scale; + ${g.setByOffset("global_idx","dequantized_data")}; + }`};return{name:"GatherBlockQuantized",shaderCache:{hint:`${r.cacheKey};${e.filter((f,_)=>_!==1).map(f=>f.dims.join("_")).join(";")}`,inputDependencies:Array.from({length:e.length},(f,_)=>"rank")},getRunData:()=>({outputs:[{dims:a,dataType:u}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:d}),getShaderSource:c}},r_=(e,r)=>{let t=e.inputs;e_(t,r),e.compute(t_(e.inputs,r))},s_=e=>St({blockSize:e.blockSize,gatherAxis:e.gatherAxis,quantizeAxis:e.quantizeAxis})}),n_,o_,i_,a_,Kv=Be(()=>{ut(),mt(),Xt(),ft(),n_=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.`)},o_=(e,r)=>{let t=e[0].dims,s=e[0].dataType,o=t.length,n=e[1].dims,i=e[1].dataType,a=Me.normalizeAxis(r.axis,o),l=t[a],u=n.slice(0),p=Me.size(u),d=Pe("input",s,o),c=Pe("indicesInput",i,n.length),f=Ye("output",s,u.length),_=[{type:12,data:p},{type:6,data:l},{type:12,data:a}];return _.push(...st(t,n,u)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:u,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:_}),getShaderSource:T=>` + ${T.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(d,c,f)} + ${T.mainStart()} + ${T.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + + let outputIndices = ${f.offsetToIndices("global_idx")}; + + var idx = ${c.getByOffset("global_idx")}; + if (idx < 0) { + idx = idx + uniforms.axisDimLimit; + } + var inputIndices = ${d.type.indices}(outputIndices); + ${d.indicesSet("inputIndices","uniforms.axis","u32(idx)")}; + let value = ${d.getByIndices("inputIndices")}; + + ${f.setByOffset("global_idx","value")}; + }`}},i_=e=>St({axis:e.axis}),a_=(e,r)=>{let t=e.inputs;n_(t),e.compute(o_(e.inputs,r))}}),l_,u_,d_,c_,Hv=Be(()=>{ut(),mt(),ft(),l_=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")},u_=(e,r)=>{let t=e[0].dims.slice(),s=e[1].dims.slice(),[o,n,i]=bc.getShapeOfGemmResult(t,r.transA,s,r.transB,e.length===3?e[2].dims:void 0),a=[o,n];if(!a)throw new Error("Can't use gemm on the given tensors");let l=16,u=Math.ceil(n/l),p=Math.ceil(o/l),d=!0,c=Me.size(a),f=[{type:12,data:d?u:c},{type:12,data:o},{type:12,data:n},{type:12,data:i},{type:1,data:r.alpha},{type:1,data:r.beta}],_=["type","type"];e.length===3&&(f.push(...st(e[2].dims)),_.push("rank")),f.push(...st(a));let T=w=>{let g="";r.transA&&r.transB?g="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":r.transA&&!r.transB?g="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!r.transA&&r.transB?g="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!r.transA&&!r.transB&&(g="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let S=r.alpha===1?"":"value *= uniforms.alpha;",E=Pe("a",e[0].dataType,e[0].dims),y=Pe("b",e[1].dataType,e[1].dims),M=E.type.value,v=null,C=[E,y];e.length===3&&(v=Pe("c",e[2].dataType,e[2].dims.length),C.push(v));let A=Ye("output",e[0].dataType,a.length);C.push(A);let B=[{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` + ${w.registerUniforms(B).declareVariables(...C)} + + ${w.mainStart()} + ${w.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let m = global_idx / uniforms.N; + let n = global_idx % uniforms.N; + + var value = ${M}(0); + for (var k: u32 = 0u; k < uniforms.K; k++) { + ${g} + } + + ${S} + ${v!=null?`let cOffset = ${v.broadcastedIndicesToOffset("vec2(m, n)",A)}; value += ${M}(uniforms.beta) * ${v.getByOffset("cOffset")};`:""} + output[global_idx] = value; + }`},k=w=>{let g=Pe("a",e[0].dataType,e[0].dims),S=Pe("b",e[1].dataType,e[1].dims),E=null,y=[g,S];e.length===3&&(E=Pe("c",e[2].dataType,e[2].dims.length),y.push(E));let M=Ye("output",e[0].dataType,a.length);y.push(M);let v=[{name:"num_tile_n",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"},{name:"alpha",type:"f32"},{name:"beta",type:"f32"}],C="",A="";r.transA&&r.transB?(A=` + var col = tile_row_start + local_id.x; + var row = k_start + local_id.y; + if (col < uniforms.M && row < uniforms.K) { + tile_a[local_id.y][local_id.x] = a[row * uniforms.M + col]; + } else { + tile_a[local_id.y][local_id.x] = ${g.type.value}(0); + } + + col = k_start + local_id.x; + row = tile_col_start + local_id.y; + if (col < uniforms.K && row < uniforms.N) { + tile_b[local_id.y][local_id.x] = b[row * uniforms.K + col]; + } else { + tile_b[local_id.y][local_id.x] = ${S.type.value}(0); + } + `,C="value += tile_a[k][local_id.y] * tile_b[local_id.x][k];"):r.transA&&!r.transB?(A=` + var col = tile_row_start + local_id.x; + var row = k_start + local_id.y; + if (col < uniforms.M && row < uniforms.K) { + tile_a[local_id.y][local_id.x] = a[row * uniforms.M + col]; + } else { + tile_a[local_id.y][local_id.x] = ${g.type.value}(0); + } + + col = tile_col_start + local_id.x; + row = k_start + local_id.y; + if (col < uniforms.N && row < uniforms.K) { + tile_b[local_id.y][local_id.x] = b[row * uniforms.N + col]; + } else { + tile_b[local_id.y][local_id.x] = ${S.type.value}(0); + } + `,C="value += tile_a[k][local_id.y] * tile_b[k][local_id.x];"):!r.transA&&r.transB?(A=` + var col = k_start + local_id.x; + var row = tile_row_start + local_id.y; + if (col < uniforms.K && row < uniforms.M) { + tile_a[local_id.y][local_id.x] = a[row * uniforms.K + col]; + } else { + tile_a[local_id.y][local_id.x] = ${g.type.value}(0); + } + + col = k_start + local_id.x; + row = tile_col_start + local_id.y; + if (col < uniforms.K && row < uniforms.N) { + tile_b[local_id.y][local_id.x] = b[row * uniforms.K + col]; + } else { + tile_b[local_id.y][local_id.x] = ${S.type.value}(0); + } + `,C="value += tile_a[local_id.y][k] * tile_b[local_id.x][k];"):!r.transA&&!r.transB&&(A=` + var col = k_start + local_id.x; + var row = tile_row_start + local_id.y; + if (col < uniforms.K && row < uniforms.M) { + tile_a[local_id.y][local_id.x] = a[row * uniforms.K + col]; + } else { + tile_a[local_id.y][local_id.x] = ${g.type.value}(0); + } + + col = tile_col_start + local_id.x; + row = k_start + local_id.y; + if (col < uniforms.N && row < uniforms.K) { + tile_b[local_id.y][local_id.x] = b[row * uniforms.N + col]; + } else { + tile_b[local_id.y][local_id.x] = ${S.type.value}(0); + } + `,C="value += tile_a[local_id.y][k] * tile_b[k][local_id.x];");let B=r.alpha===1?"":"value *= uniforms.alpha;";return` + ${w.registerUniforms(v).declareVariables(...y)} + var tile_a: array, ${l}>; + var tile_b: array, ${l}>; + ${w.mainStart([l,l,1])} + let tile_col_start = (workgroup_index % uniforms.num_tile_n) * ${l}; + let tile_row_start = (workgroup_index / uniforms.num_tile_n) * ${l}; + let num_tiles = (uniforms.K - 1) / ${l} + 1; + var k_start = 0u; + var value = ${M.type.value}(0); + for (var t: u32 = 0u; t < num_tiles; t++) { + ${A} + k_start = k_start + ${l}; + workgroupBarrier(); + + for (var k: u32 = 0u; k < ${l}; k++) { + ${C} + } + workgroupBarrier(); + } + + ${B} + let m = tile_row_start + local_id.y; + let n = tile_col_start + local_id.x; + ${E!=null?`let cOffset = ${E.broadcastedIndicesToOffset("vec2(m, n)",M)}; value += ${M.type.value}(uniforms.beta) * ${E.getByOffset("cOffset")};`:""} + if (m < uniforms.M && n < uniforms.N) { + output[m * uniforms.N + n] = value; + } + }`};return d?{name:"GemmShared",shaderCache:{hint:`${r.cacheKey}`,inputDependencies:_},getRunData:()=>({outputs:[{dims:a,dataType:e[0].dataType}],dispatchGroup:{x:u*p},programUniforms:f}),getShaderSource:k}:{name:"Gemm",shaderCache:{hint:`${r.cacheKey}`,inputDependencies:_},getRunData:()=>({outputs:[{dims:a,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:f}),getShaderSource:T}},d_=e=>{let r=e.transA,t=e.transB,s=e.alpha,o=e.beta;return{transA:r,transB:t,alpha:s,beta:o,cacheKey:`${e.transA};${e.transB};${e.alpha===1}`}},c_=(e,r)=>{l_(e.inputs),e.compute(u_(e.inputs,r))}}),ws,Ps,an,ln,p_,h_,m_,__,f_,g_,w_,M_,b_,y_,qv=Be(()=>{ut(),mt(),Xt(),ft(),[ws,Ps,an,ln]=[0,1,2,3],p_=e=>{if(e[0].dims.length!==4)throw new Error("only 4-D tensor is supported.");if(e[0].dims.length!==e[1].dims.length)throw new Error("input dimensions must be equal to grid dimensions");if(e[0].dims.length-2!==e[1].dims[e[1].dims.length-1])throw new Error(`last dimension of grid must be equal to ${e[0].dims.length-2}`);if(e[0].dims[0]!==e[1].dims[0])throw new Error("grid batch size must match input batch size")},h_=` + fn gs_get_cubic_coeffs(x: f32) -> vec4 { + let cubic_alpha = -0.75f; + let x_abs = abs(x); + var coeffs: vec4; + coeffs[0] = (((cubic_alpha * (x_abs + 1) - 5 * cubic_alpha) * (x_abs + 1) + 8 * cubic_alpha) * (x_abs + 1) - 4 * cubic_alpha); + coeffs[1] = (((cubic_alpha + 2) * x_abs - (cubic_alpha + 3)) * x_abs * x_abs + 1); + coeffs[2] = (((cubic_alpha + 2) * (1 - x_abs) - (cubic_alpha + 3)) * (1 - x_abs) * (1 - x_abs) + 1); + coeffs[3] = (((cubic_alpha * (2 - x_abs) - 5 * cubic_alpha) * (2 - x_abs) + 8 * cubic_alpha) * (2 - x_abs) - 4 * cubic_alpha); + return coeffs; + } +`,m_=e=>` + fn gs_bicubic_interpolate(p: mat4x4<${e}>, x: f32, y: f32) -> ${e} { + var v: vec4; + var coeffs = gs_get_cubic_coeffs(x); + for (var i = 0; i < 4; i++) { + v[i] = coeffs[0] * p[i][0] + coeffs[1] * p[i][1] + coeffs[2] * p[i][2] + coeffs[3] * p[i][3]; + } + coeffs = gs_get_cubic_coeffs(y); + let pixel = ${e}(coeffs[0] * v[0] + coeffs[1] * v[1] + coeffs[2] * v[2] + coeffs[3] * v[3]); + return pixel; + } +`,__=e=>` + fn gs_denormalize(n: f32, length: i32) -> f32 { + ${e.alignCorners===0?` + // alignCorners: false => [-1, 1] to [-0.5, length - 0.5] + return ((n + 1.0) * f32(length) - 1.0) / 2.0; + `:` + // alignCorners: true => [-1, 1] to [0, length - 1] + return (n + 1.0) / 2.0 * (f32(length - 1)); + `} + } +`,f_=e=>` + ${e.paddingMode==="reflection"?` + fn gs_reflect(x: i32, x_min: f32, x_max: f32) -> u32 { + var dx = 0.0; + var fx = f32(x); + let range = x_max - x_min; + if (fx < x_min) { + dx = x_min - fx; + let n = u32(dx / range); + let r = dx - f32(n) * range; + if (n % 2 == 0) { + fx = x_min + r; + } else { + fx = x_max - r; + } + } else if (fx > x_max) { + dx = fx - x_max; + let n = u32(dx / range); + let r = dx - f32(n) * range; + if (n % 2 == 0) { + fx = x_max - r; + } else { + fx = x_min + r; + } + } + return u32(fx); + }`:""} +`,g_=(e,r,t)=>` + fn pixel_at_grid(r: i32, c: i32, H: i32, W: i32, batch: u32, channel: u32, border: vec4) -> ${r} { + var pixel = ${r}(0); + var indices = vec4(0); + indices[${ws}] = batch; + indices[${Ps}] = channel;`+(()=>{switch(t.paddingMode){case"zeros":return` + if (r >= 0 && r < H && c >=0 && c < W) { + indices[${an}] = u32(r); + indices[${ln}] = u32(c); + } else { + return ${r}(0); + } + `;case"border":return` + indices[${an}] = u32(clamp(r, 0, H - 1)); + indices[${ln}] = u32(clamp(c, 0, W - 1)); + `;case"reflection":return` + indices[${an}] = gs_reflect(r, border[1], border[3]); + indices[${ln}] = gs_reflect(c, border[0], border[2]); + `;default:throw new Error(`padding mode ${t.paddingMode} is not supported`)}})()+` + return ${e.getByIndices("indices")}; + } +`,w_=(e,r,t)=>(()=>{switch(t.mode){case"nearest":return` + let result = pixel_at_grid(i32(round(y)), i32(round(x)), H_in, W_in, indices[${ws}], indices[${Ps}], border); + `;case"bilinear":return` + let x1 = i32(floor(x)); + let y1 = i32(floor(y)); + let x2 = x1 + 1; + let y2 = y1 + 1; + + let p11 = pixel_at_grid(y1, x1, H_in, W_in, indices[${ws}], indices[${Ps}], border); + let p12 = pixel_at_grid(y1, x2, H_in, W_in, indices[${ws}], indices[${Ps}], border); + let p21 = pixel_at_grid(y2, x1, H_in, W_in, indices[${ws}], indices[${Ps}], border); + let p22 = pixel_at_grid(y2, x2, H_in, W_in, indices[${ws}], indices[${Ps}], border); + + let dx2 = ${r}(f32(x2) - x); + let dx1 = ${r}(x - f32(x1)); + let dy2 = ${r}(f32(y2) - y); + let dy1 = ${r}(y - f32(y1)); + let result = dy2 * (dx2 * p11 + dx1 * p12) + dy1 * (dx2 * p21 + dx1 * p22); + `;case"bicubic":return` + let x0 = i32(floor(x)) - 1; + let y0 = i32(floor(y)) - 1; + var p: mat4x4<${r}>; + for (var h = 0; h < 4; h++) { + for (var w = 0; w < 4; w++) { + p[h][w] = pixel_at_grid(h + y0, w + x0, H_in, W_in, indices[${ws}], indices[${Ps}], border); + } + } + + let dx = x - f32(x0 + 1); + let dy = y - f32(y0 + 1); + let result = gs_bicubic_interpolate(p, dx, dy); + `;default:throw new Error(`mode ${t.mode} is not supported`)}})()+`${e.setByOffset("global_idx","result")}`,M_=(e,r)=>{let t=Pe("x",e[0].dataType,e[0].dims.length),s=[e[1].dims[0],e[1].dims[1],e[1].dims[2]],o=Pe("grid",e[1].dataType,s.length,2),n=[e[0].dims[0],e[0].dims[1],e[1].dims[1],e[1].dims[2]];r.format==="NHWC"&&(n=[e[0].dims[0],e[1].dims[1],e[1].dims[2],e[0].dims[3]],[ws,Ps,an,ln]=[0,3,1,2]);let i=Ye("output",e[0].dataType,n.length),a=t.type.value,l=Me.size(n),u=[{type:12,data:l},...st(e[0].dims,s,n)],p=d=>` + ${d.registerUniform("output_size","u32").declareVariables(t,o,i)} + ${h_} + ${m_(a)} + ${__(r)} + ${f_(r)} + ${g_(t,a,r)} + + ${d.mainStart()} + ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let H_in = i32(uniforms.x_shape[${an}]); + let W_in = i32(uniforms.x_shape[${ln}]); + + ${r.alignCorners===0?` + let x_min = -0.5; + let x_max = f32(W_in) - 0.5; + let y_min = -0.5; + let y_max = f32(H_in) - 0.5; + `:` + let x_min = 0.0; + let x_max = f32(W_in) - 1.0; + let y_min = 0.0; + let y_max = f32(H_in) - 1.0; + `}; + let border = vec4(x_min, y_min, x_max, y_max); + + let indices = ${i.offsetToIndices("global_idx")}; + var grid_indices = vec3(indices[${ws}], indices[${an}], indices[${ln}]); + let nxy = ${o.getByIndices("grid_indices")}; + var x = gs_denormalize(f32(nxy[0]), W_in); + var y = gs_denormalize(f32(nxy[1]), H_in); + + ${w_(i,a,r)} + }`;return{name:"GridSample",shaderCache:{hint:`${r.cacheKey}`,inputDependencies:["type","type"]},getRunData:d=>{let c=Me.size(n);return{outputs:[{dims:n,dataType:d[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:u}},getShaderSource:p}},b_=(e,r)=>{p_(e.inputs),e.compute(M_(e.inputs,r))},y_=e=>St({alignCorners:e.align_corners,mode:e.mode,paddingMode:e.padding_mode,format:e.format})}),Cr,v_,x_,Ol,T_,Mo,E_,P_=Be(()=>{ut(),mt(),Xt(),el(),cl(),ft(),zs(),Cr=(e,r)=>e.length>r&&e[r].dims.length>0?e[r]:void 0,v_=(e,r)=>{let t=e[0],s=Cr(e,1),o=Cr(e,2),n=Cr(e,3),i=Cr(e,4),a=Cr(e,5),l=Cr(e,6),u=Cr(e,7);if(t.dims.length!==3&&t.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let p=t.dims[0],d=t.dims[1],c=t.dims.length===3?t.dims[2]:r.numHeads*t.dims[4],f=d,_=0,T=0,k=Math.floor(c/r.numHeads);if(l&&u&&Me.size(l.dims)&&Me.size(u.dims)){if(l.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(l.dims[0]!==p||l.dims[1]!==r.numHeads||l.dims[3]!==k)throw new Error('Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)');if(u.dims[0]!==p||u.dims[1]!==r.numHeads||u.dims[3]!==k)throw new Error('Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)');if(l.dims[2]!==u.dims[2])throw new Error('Input "past_key" and "past_value" shall have same dim 2 (past_sequence_length)');if(u.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');_=l.dims[2],T=l.dims[2]}else if(l&&Me.size(l.dims)||u&&Me.size(u.dims))throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let w;if(s&&Me.size(s.dims)>0){if(t.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(s.dims.length<3||s.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(t.dims[0]!==s.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(s.dims.length===3){if(s.dims[2]!==t.dims[2])throw new Error('Input "query" and "key" shall have same dim 2 (hidden_size)');w=2,f=s.dims[1]}else if(s.dims.length===5){if(s.dims[2]!==r.numHeads||s.dims[3]!==2||s.dims[4]!==k)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(o)throw new Error('Expect "value" be none when "key" has packed kv format.');w=5,f=s.dims[1]}else{if(s.dims[1]!==r.numHeads||s.dims[3]!==k)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');w=0,f=s.dims[2]}}else{if(t.dims.length!==5)throw new Error('Input "query" is expected to have 5 dimensions when key is empty');if(t.dims[2]!==r.numHeads||t.dims[3]!==3)throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');w=3}if(n&&Me.size(n.dims)>0){if(n.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimension');if(s&&s.dims.length===5&&s.dims[3]===2)throw new Error("bias is not allowed for packed kv.")}let g=_+f,S=0;if(i&&Me.size(i.dims)>0){S=8;let v=i.dims;throw v.length===1?v[0]===p?S=1:v[0]===3*p+2&&(S=3):v.length===2&&v[0]===p&&v[1]===g&&(S=5),S===8?new Error('Input "key_padding_mask" shape shall be (batch_size) or (batch_size, total_sequence_length)'):new Error("Mask not supported")}let E=!1,y=c;if(o&&Me.size(o.dims)>0){if(o.dims.length!==3&&o.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(t.dims[0]!==o.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(o.dims.length===3){if(f!==o.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');y=o.dims[2]}else{if(f!==o.dims[2])throw new Error('Input "key" and "value" shall have the same dim 2 (kv_sequence_length)');y=o.dims[1]*o.dims[3],E=!0}}let M=!1;if(i&&Me.size(i.dims)>0)throw new Error("Key padding mask is not supported");if(a&&Me.size(a.dims)>0){if(a.dims.length!==4)throw new Error('Input "attention_bias" is expected to have 4 dimensions');if(a.dims[0]!==p||a.dims[1]!==r.numHeads||a.dims[2]!==d||a.dims[3]!==g)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:p,sequenceLength:d,pastSequenceLength:_,kvSequenceLength:f,totalSequenceLength:g,maxSequenceLength:T,inputHiddenSize:0,hiddenSize:c,vHiddenSize:y,headSize:k,vHeadSize:Math.floor(y/r.numHeads),numHeads:r.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:r.maskFilterValue,maskType:S,scale:r.scale,broadcastResPosBias:M,passPastInKv:E,qkvFormat:w}},x_=e=>St({...e}),Ol=St({perm:[0,2,1,3]}),T_=(e,r,t,s,o,n,i)=>{let a=[s,o,n],l=Me.size(a),u=[{type:12,data:l},{type:12,data:i},{type:12,data:n}],p=d=>{let c=Ye("qkv_with_bias",r.dataType,a),f=Pe("qkv",r.dataType,a),_=Pe("bias",t.dataType,a),T=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return` + ${d.registerUniforms(T).declareVariables(f,_,c)} + ${d.mainStart()} + ${d.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:a,dataType:r.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:u}),getShaderSource:p},{inputs:[r,t],outputs:[-1]})[0]},Mo=(e,r,t,s,o,n,i,a)=>{let l=n;if(i&&Me.size(i.dims)>0){if(s===1)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return l=T_(e,n,i,r,s,t*o,a),l=l.reshape([r,s,t,o]),t===1||s===1?l:e.compute(Lr(l,Ol.perm),{inputs:[l],outputs:[-1]})[0]}else return n.dims.length===3&&(l=n.reshape([r,s,t,o])),t===1||s===1?l:e.compute(Lr(l,Ol.perm),{inputs:[l],outputs:[-1]})[0]},E_=(e,r)=>{let t=v_(e.inputs,r),s=e.inputs[0],o=Cr(e.inputs,1),n=Cr(e.inputs,2),i=Cr(e.inputs,3),a=Cr(e.inputs,4),l=Cr(e.inputs,5),u=Cr(e.inputs,6),p=Cr(e.inputs,7);if(s.dims.length===5)throw new Error("Packed QKV is not implemented");if((o==null?void 0:o.dims.length)===5)throw new Error("Packed KV is not implemented");let d=o&&n&&o.dims.length===4&&n.dims.length===4,c=Mo(e,t.batchSize,t.numHeads,t.sequenceLength,t.headSize,s,i,0);if(d)return mo(e,c,o,n,a,void 0,u,p,l,t);if(!o||!n)throw new Error("key and value must be provided");let f=Mo(e,t.batchSize,t.numHeads,t.kvSequenceLength,t.headSize,o,i,t.hiddenSize),_=Mo(e,t.batchSize,t.numHeads,t.kvSequenceLength,t.vHeadSize,n,i,2*t.hiddenSize);mo(e,c,f,_,a,void 0,u,p,l,t)}}),C_,S_,$_,k_,Dl,I_,A_,F_=Be(()=>{ut(),mt(),Xt(),ft(),C_=e=>{if(!e||e.length<1)throw new Error("too few inputs")},S_=(e,r)=>{let t=[],s=r.numOutputs;return e[1].dims[0]>0&&(e[1].getBigInt64Array().forEach(o=>t.push(Number(o))),s=t.length),St({numOutputs:s,axis:r.axis,splitSizes:t})},$_=e=>` +fn calculateOutputIndex(index: u32) -> u32 { + for (var i: u32 = 0u; i < ${e}u; i += 1u ) { + if (index < ${et("uniforms.size_in_split_axis","i",e)}) { + return i; + } + } + return ${e}u; +}`,k_=e=>{let r=e.length,t=[];for(let s=0;s{let t=e[0].dims,s=Me.size(t),o=e[0].dataType,n=Me.normalizeAxis(r.axis,t.length),i=new Array(r.numOutputs),a=Pe("input",o,t.length),l=new Array(r.numOutputs),u=[],p=[],d=0,c=[{type:12,data:s}];for(let _=0;_` + ${_.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",l.length).declareVariables(a,...i)} + ${$_(l.length)} + ${k_(i)} + + ${_.mainStart()} + ${_.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")} + + var indices = ${a.offsetToIndices("global_idx")}; + var index = ${a.indicesGet("indices",n)}; + let output_number = calculateOutputIndex(index); + if (output_number != 0) { + index -= ${et("uniforms.size_in_split_axis","output_number - 1u",l.length)}; + ${a.indicesSet("indices",n,"index")}; + } + writeBufferData(output_number, indices, global_idx); + }`;return{name:"Split",shaderCache:{hint:r.cacheKey,inputDependencies:["rank"]},getShaderSource:f,getRunData:()=>({outputs:u,dispatchGroup:{x:Math.ceil(s/64)},programUniforms:c})}},I_=(e,r)=>{C_(e.inputs);let t=e.inputs.length===1?r:S_(e.inputs,r);e.compute(Dl(e.inputs,t),{inputs:[0]})},A_=e=>{let r=e.axis,t=e.splitSizes,s=e.numOutputs<0?t.length:e.numOutputs;if(s!==t.length)throw new Error("numOutputs and splitSizes lengh must be equal");return St({axis:r,numOutputs:s,splitSizes:t})}}),O_,fi,D_,L_=Be(()=>{ut(),mt(),Xt(),ft(),O_=(e,r)=>{let[t,s,o,n]=e,{numHeads:i,rotaryEmbeddingDim:a}=r;if(t.dims.length!==3&&t.dims.length!==4)throw new Error(`Input 'x' is expected to have 3 or 4 dimensions, got ${t.dims.length}`);if(!Me.areEqual(s.dims,[])&&!Me.areEqual(s.dims,[1])&&s.dims.length!==2)throw new Error(`Input 'position_ids' is expected to have 0, 1, or 2 dimensions, got ${s.dims.length}`);if(o.dims.length!==2)throw new Error(`Input 'cos_cache' is expected to have 2 dimensions, got ${o.dims.length}`);if(n.dims.length!==2)throw new Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${n.dims.length}`);if(!Me.areEqual(o.dims,n.dims))throw new Error("Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape");if(a>0&&i===0)throw new Error("num_heads must be provided if rotary_embedding_dim is specified");let l=t.dims[0],u=t.dims[t.dims.length-2],p=o.dims[0],d=Me.sizeFromDimension(t.dims,1)/u,c=a===0?o.dims[1]*2:d/i;if(a>c)throw new Error("rotary_embedding_dim must be less than or equal to head_size");if(s.dims.length===2){if(l!==s.dims[0])throw new Error(`Input 'position_ids' dimension 0 should be of size batch_size, got ${s.dims[0]}`);if(u!==s.dims[1])throw new Error(`Input 'position_ids' dimension 1 should be of size sequence_length, got ${s.dims[1]}`)}if(c/2!==o.dims[1]&&a/2!==o.dims[1])throw new Error(`Input 'cos_cache' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${o.dims[1]}`);if(u>p)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported")},fi=(e,r)=>{let{interleaved:t,numHeads:s,rotaryEmbeddingDim:o,scale:n}=r,i=e[0].dims[0],a=Me.sizeFromDimension(e[0].dims,1),l=e[0].dims[e[0].dims.length-2],u=a/l,p=e[2].dims[1],d=o===0?p*2:u/s,c=new Array(i,l,u/d,d-p),f=Me.computeStrides(c),_=[{type:1,data:n},{type:12,data:c},{type:12,data:f},...e[0].dims.length===3?new Array({type:12,data:[a,u,d,1]}):[],...e[0].dims.length===4?new Array({type:12,data:[a,d,l*d,1]}):[],...st(e[0].dims,e[1].dims,e[2].dims,e[3].dims,e[0].dims)],T=k=>{let w=Pe("input",e[0].dataType,e[0].dims.length),g=Pe("position_ids",e[1].dataType,e[1].dims.length),S=Pe("cos_cache",e[2].dataType,e[2].dims.length),E=Pe("sin_cache",e[3].dataType,e[3].dims.length),y=Ye("output",e[0].dataType,e[0].dims.length);return k.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:c.length},{name:"global_strides",type:"u32",length:f.length},{name:"input_output_strides",type:"u32",length:f.length}]),` + ${k.declareVariables(w,g,S,E,y)} + + ${k.mainStart(Vn)} + let half_rotary_emb_dim = uniforms.${S.name}_shape[1]; + let bsnh = global_idx / uniforms.global_strides % uniforms.global_shape; + let size = uniforms.global_shape[0] * uniforms.global_strides[0]; + ${k.guardAgainstOutOfBoundsWorkgroupSizes("size")} + + if (bsnh[3] < half_rotary_emb_dim) { + let position_ids_idx = + ${g.broadcastedIndicesToOffset("bsnh.xy",Ye("",g.type.tensor,2))}; + let position_id = + u32(${g.getByOffset("position_ids_idx")}) + select(0, bsnh[1], position_ids_idx == 0); + let i = dot(bsnh, uniforms.input_output_strides) + select(0, bsnh[3], ${t}); + let j = i + select(half_rotary_emb_dim, 1, ${t}); + let re = ${w.getByOffset("i")} * ${S.get("position_id","bsnh[3]")} - + ${w.getByOffset("j")} * ${E.get("position_id","bsnh[3]")}; + ${y.setByOffset("i","re")} + let im = ${w.getByOffset("i")} * ${E.get("position_id","bsnh[3]")} + + ${w.getByOffset("j")} * ${S.get("position_id","bsnh[3]")}; + ${y.setByOffset("j","im")} + } else { + let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim; + ${y.setByOffset("k",w.getByOffset("k"))} + } + }`};return{name:"RotaryEmbedding",shaderCache:{hint:St({interleaved:t}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:T,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(Me.size(c)/Vn)},programUniforms:_})}},D_=(e,r)=>{O_(e.inputs,r),e.compute(fi(e.inputs,r))}}),z_,B_,Ll,R_,j_,Xv=Be(()=>{Xt(),ut(),cl(),P_(),F_(),zs(),L_(),ft(),z_=(e,r)=>{if(r.doRotary&&e.length<=7)throw new Error("cos_cache and sin_cache inputs are required if do_rotary is specified");let t=e[0],s=e[1],o=e[2],n=e[3],i=e[4];if(r.doRotary!==0&&e.length<=7)throw new Error("cos_cast and sin_cache are expected if do_rotary attribute is non-zero");if(r.localWindowSize!==-1)throw new Error("Local attention is not supported");if(r.softcap!==0)throw new Error("Softcap is not supported");if(r.rotaryInterleaved!==0)throw new Error("Rotary interleaved is not supported");if(r.smoothSoftmax)throw new Error("Smooth softmax is not supported");if(t.dims.length!==3&&t.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let a=!1,l=t.dims[0],u=t.dims[1],p=t.dims.length===3?a?t.dims[2]/3:t.dims[2]:r.numHeads*t.dims[4],d=u,c=0,f=!s||s.dims.length===0,_=Math.floor(f?p/(r.numHeads+2*r.kvNumHeads):p/r.numHeads);f&&(p=_*r.numHeads);let T=n&&n.dims.length!==0,k=i&&i.dims.length!==0;if(T&&n.dims.length===4&&n.dims[0]===l&&n.dims[1]!==r.kvNumHeads&&n.dims[2]===r.kvNumHeads&&n.dims[3]===_)throw new Error("BSNH pastKey/pastValue is not supported");if(T&&k){if(n.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(i.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');c=n.dims[2]}else if(T||k)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let w=1;if(s&&s.dims.length>0){if(t.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(s.dims.length<3||s.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(t.dims[0]!==s.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(s.dims.length===3){if(t.dims[2]%s.dims[2]!==0)throw new Error('Dimension 2 of "query" should be a multiple of "key"');d=s.dims[1]}else if(s.dims.length===5){if(s.dims[2]!==r.numHeads||s.dims[3]!==2||s.dims[4]!==_)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(o)throw new Error('Expect "value" be none when "key" has packed kv format.');d=s.dims[1]}else{if(s.dims[1]!==r.numHeads||s.dims[3]!==_)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');d=s.dims[2]}}else{if(t.dims.length!==3&&t.dims.length!==5)throw new Error('Input "query" is expected to have 3 or 5 dimensions when key is empty');if(t.dims.length===5&&(t.dims[2]!==r.numHeads||t.dims[3]!==3))throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');w=3}let g=0,S=!1,E=r.kvNumHeads?_*r.kvNumHeads:p;if(o&&o.dims.length>0){if(o.dims.length!==3&&o.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(t.dims[0]!==o.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(o.dims.length===3){if(d!==o.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');E=o.dims[2]}else{if(d!==o.dims[2])throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');E=o.dims[1]*o.dims[3],S=!0}}let y=e.length>4?e[5]:void 0;if(y&&y.dims.length!==1&&y.dims[0]!==l)throw new Error('Input "seqlens" is expected to have 1 dimension and the same dim 0 as batch_size');return{batchSize:l,sequenceLength:u,pastSequenceLength:c,kvSequenceLength:d,totalSequenceLength:-1,maxSequenceLength:-1,inputHiddenSize:0,hiddenSize:p,vHiddenSize:E,headSize:_,vHeadSize:Math.floor(E/r.kvNumHeads),numHeads:r.numHeads,kvNumHeads:r.kvNumHeads,nReps:r.numHeads/r.kvNumHeads,pastPresentShareBuffer:!1,maskType:g,scale:r.scale,broadcastResPosBias:!1,passPastInKv:S,qkvFormat:w}},B_=St({perm:[0,2,1,3]}),Ll=(e,r,t)=>{let s=r,o=t.kvNumHeads;return r.dims.length===3&&t.kvSequenceLength!==0&&(s=r.reshape([t.batchSize,t.kvSequenceLength,o,t.headSize]),s=e.compute(Lr(s,B_.perm),{inputs:[s],outputs:[-1]})[0]),s},R_=(e,r,t,s)=>{let o=7,n=["type","type"],i=[e*r],a=e*r,l=[{type:12,data:a},{type:12,data:r},{type:12,data:e}],u=p=>{let d=Pe("seq_lens",t.dataType,t.dims),c=Pe("total_seq_lens",s.dataType,s.dims),f=Ye("pos_ids",o,i),_=[{name:"output_size",type:"u32"},{name:"sequence_length",type:"u32"},{name:"batch_size",type:"u32"}];return` + ${p.registerUniforms(_).declareVariables(d,c,f)} + ${p.mainStart()} + ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let total_sequence_length = u32(${c.getByOffset("0")}); + let is_subsequent_prompt = uniforms.sequence_length > 1 && uniforms.sequence_length != total_sequence_length; + let is_first_prompt = !is_subsequent_prompt && uniforms.sequence_length == total_sequence_length; + let batch_idx = global_idx / uniforms.sequence_length; + let sequence_idx = i32(global_idx % uniforms.sequence_length); + var pos_id: i32 = 0; + let seqlen = ${d.getByOffset("batch_idx")}; + let total_seqlen = seqlen + 1; + if (is_first_prompt) { + if (sequence_idx < total_seqlen) { + pos_id = sequence_idx; + } else { + pos_id = 1; + } + ${f.setByOffset("global_idx","pos_id")} + } else if (is_subsequent_prompt) { + let past_seqlen = total_seqlen - i32(uniforms.sequence_length); + if (past_seqlen + sequence_idx < total_seqlen) { + pos_id = past_seqlen + sequence_idx; + } else { + pos_id = 1; + } + ${f.setByOffset("global_idx","pos_id")} + } else if (global_idx < uniforms.batch_size) { + ${f.setByOffset("global_idx","seqlen")} + }; + } + `};return{name:"GeneratePositionIds",shaderCache:{hint:`${e};${r}`,inputDependencies:n},getRunData:()=>({outputs:[{dims:i,dataType:o}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:l}),getShaderSource:u}},j_=(e,r)=>{var E;let t=z_(e.inputs,r);if(e.inputs[0].dims.length===5)throw new Error("Packed QKV is not implemented");if(((E=e.inputs[1])==null?void 0:E.dims.length)===5)throw new Error("Packed KV is not implemented");let s=e.inputs[0],o=e.inputs[1]&&e.inputs[1].dims.length>0?e.inputs[1]:void 0,n=e.inputs[2]&&e.inputs[2].dims.length>0?e.inputs[2]:void 0,i=e.inputs[3]&&e.inputs[3].dims.length!==0?e.inputs[3]:void 0,a=e.inputs[4]&&e.inputs[4].dims.length!==0?e.inputs[4]:void 0,l=e.inputs.length>4?e.inputs[5]:void 0,u=e.inputs.length>5?e.inputs[6]:void 0,p=t.kvNumHeads?t.kvNumHeads:t.numHeads,d=St({axis:2,numOutputs:3,splitSizes:[t.numHeads*t.headSize,p*t.headSize,p*t.headSize]}),[c,f,_]=!o&&!n?e.compute(Dl([s],d),{inputs:[s],outputs:[-1,-1,-1]}):[s,o,n],T,k;if(r.doRotary){let y=e.compute(R_(t.batchSize,t.sequenceLength,l,u),{inputs:[l,u],outputs:[-1]})[0],M=e.inputs[7],v=e.inputs[8],C=St({interleaved:r.rotaryInterleaved!==0,numHeads:t.numHeads,rotaryEmbeddingDim:0,scale:r.scale}),A=[c,y,M,v],B=[-1];T=e.compute(fi(A,C),{inputs:A,outputs:B})[0],A.splice(0,1,f);let K=St({interleaved:r.rotaryInterleaved!==0,numHeads:t.kvNumHeads,rotaryEmbeddingDim:0,scale:r.scale});k=e.compute(fi(A,K),{inputs:A,outputs:B})[0]}let w=Mo(e,t.batchSize,t.numHeads,t.sequenceLength,t.headSize,r.doRotary?T:c,void 0,0),g=Ll(e,r.doRotary?k:f,t),S=Ll(e,_,t);mo(e,w,g,S,void 0,void 0,i,a,void 0,t,l,u)}}),zl,N_,V_,U_,Qv=Be(()=>{ut(),mt(),zs(),ft(),zl=(e,r,t,s,o,n,i,a)=>{let l=Kt(n),u=l===1?"f32":`vec${l}f`,p=l===1?"vec2f":`mat2x${l}f`,d=o*i,c=64;d===1&&(c=256);let f=[o,i,n/l],_=[o,i,2],T=["rank","type","type"],k=[];k.push(...st(f,_));let w=g=>{let S=Pe("x",r.dataType,3,l),E=Pe("scale",t.dataType,t.dims),y=Pe("bias",s.dataType,s.dims),M=Ye("output",1,3,2),v=[S,E,y,M];return` + var workgroup_shared : array<${p}, ${c}>; + const workgroup_size = ${c}u; + ${g.declareVariables(...v)} + ${g.mainStart(c)} + let batch = workgroup_index / uniforms.x_shape[1]; + let channel = workgroup_index % uniforms.x_shape[1]; + let hight = uniforms.x_shape[2]; + // initialize workgroup memory + var sum = ${u}(0); + var squared_sum = ${u}(0); + for (var h = local_idx; h < hight; h += workgroup_size) { + let value = ${u}(${S.get("batch","channel","h")}); + sum += value; + squared_sum += value * value; + } + workgroup_shared[local_idx] = ${p}(sum, squared_sum); + workgroupBarrier(); + + for (var currSize = workgroup_size >> 1; currSize > 0; currSize = currSize >> 1) { + if (local_idx < currSize) { + workgroup_shared[local_idx] = workgroup_shared[local_idx] + workgroup_shared[local_idx + currSize]; + } + workgroupBarrier(); + } + if (local_idx == 0) { + let sum_final = ${Ls("workgroup_shared[0][0]",l)} / f32(hight * ${l}); + let squared_sum_final = ${Ls("workgroup_shared[0][1]",l)} / f32(hight * ${l}); + + let inv_std_dev = inverseSqrt(squared_sum_final - sum_final * sum_final + f32(${a})); + let channel_scale = inv_std_dev * f32(scale[channel]); + let channel_shift = f32(bias[channel]) - sum_final * channel_scale; + output[workgroup_index] = vec2f(channel_scale, channel_shift); + } + }`};return e.compute({name:"InstanceNormComputeChannelScaleShift",shaderCache:{hint:`${l};${a};${c}`,inputDependencies:T},getRunData:()=>({outputs:[{dims:_,dataType:1}],dispatchGroup:{x:d},programUniforms:k}),getShaderSource:w},{inputs:[r,t,s],outputs:[-1]})[0]},N_=(e,r,t)=>{let s=r[0].dims,o=s,n=2,i=s[0],a=s[1],l=Me.sizeFromDimension(s,n),u=Kt(l),p=Me.size(o)/u,d=zl(e,r[0],r[1],r[2],i,l,a,t.epsilon),c=[i,a,l/u],f=[i,a],_=["type","none"],T=k=>{let w=Pe("x",r[0].dataType,c.length,u),g=Pe("scale_shift",1,f.length,2),S=Ye("output",r[0].dataType,c.length,u),E=[w,g,S];return` + ${k.registerUniform("output_size","u32").declareVariables(...E)} + ${k.mainStart()} + ${k.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let outputIndices = ${S.offsetToIndices("global_idx")}; + let batch = outputIndices[0]; + let channel = outputIndices[1]; + let scale_shift = ${g.getByIndices("vec2(batch, channel)")}; + let value = ${w.getByOffset("global_idx")} * ${S.type.value}(scale_shift.x) + ${S.type.value}(scale_shift.y); + ${S.setByOffset("global_idx","value")}; + }`};e.compute({name:"InstanceNormalization",shaderCache:{hint:`${u}`,inputDependencies:_},getRunData:()=>({outputs:[{dims:o,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:[{type:12,data:p},...st(c,f,c)]}),getShaderSource:T},{inputs:[r[0],d]})},V_=(e,r,t)=>{let s=r[0].dims,o=s,n=s[0],i=s[s.length-1],a=Me.sizeFromDimension(s,1)/i,l=Kt(i),u=Me.size(o)/l,p=[{type:12,data:a},{type:12,data:Math.floor(i/l)}],d=["type","type"],c=!1,f=[0,s.length-1];for(let w=0;ws[f[g]])),T=zl(e,_,r[1],r[2],n,a,i,t.epsilon),k=w=>{let g=lr(r[0].dataType),S=l===1?"vec2f":`mat${l}x2f`,E=v=>{let C=v===0?"x":"y",A=l===1?"f32":`vec${l}f`;switch(l){case 1:return`${g}(${A}(scale.${C}))`;case 2:return`vec2<${g}>(${A}(scale[0].${C}, scale[1].${C}))`;case 4:return`vec4<${g}>(${A}(scale[0].${C}, scale[1].${C}, scale[2].${C}, scale[3].${C}))`;default:throw new Error(`Not supported compoents ${l}`)}},y=Pe("input",r[0].dataType,r[0].dims,l),M=Ye("output",r[0].dataType,o,l);return` + @group(0) @binding(0) var input : array<${y.type.storage}>; + @group(0) @binding(1) var scale_input : array<${S}>; + @group(0) @binding(2) var output : array<${M.type.storage}>; + struct Uniforms {H: u32, C : u32}; + @group(0) @binding(3) var uniforms: Uniforms; + + ${w.mainStart()} + let current_image_number = global_idx / (uniforms.C * uniforms.H); + let current_channel_number = global_idx % uniforms.C; + + let scale_offset = current_image_number * uniforms.C + current_channel_number; + let scale = scale_input[scale_offset]; + output[global_idx] = fma(input[global_idx], ${E(0)}, ${E(1)}); + }`};e.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${l}`,inputDependencies:d},getRunData:()=>({outputs:[{dims:o,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:p}),getShaderSource:k},{inputs:[r[0],T]})},U_=(e,r)=>{r.format==="NHWC"?V_(e,e.inputs,r):N_(e,e.inputs,r)}}),W_,G_,K_,Jv=Be(()=>{ut(),mt(),ft(),W_=e=>{if(!e||e.length<2)throw new Error("layerNorm requires at least 2 inputs.")},G_=(e,r,t)=>{let s=r.simplified,o=e[0].dims,n=e[1],i=!s&&e[2],a=o,l=Me.normalizeAxis(r.axis,o.length),u=Me.sizeToDimension(o,l),p=Me.sizeFromDimension(o,l),d=Me.size(n.dims),c=i?Me.size(i.dims):0;if(d!==p||i&&c!==p)throw new Error(`Size of X.shape()[axis:] == ${p}. + Size of scale and bias (if provided) must match this. + Got scale size of ${d} and bias size of ${c}`);let f=[];for(let y=0;y1,g=t>2,S=y=>{let M=lr(e[0].dataType),v=[Pe("x",e[0].dataType,e[0].dims,_),Pe("scale",n.dataType,n.dims,_)];i&&v.push(Pe("bias",i.dataType,i.dims,_)),v.push(Ye("output",e[0].dataType,a,_)),w&&v.push(Ye("mean_data_output",1,f)),g&&v.push(Ye("inv_std_output",1,f));let C=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return` + ${y.registerUniforms(C).declareVariables(...v)} + ${y.mainStart()} + ${y.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")} + let offset = global_idx * uniforms.norm_size_vectorized; + var mean_vector = ${nl("f32",_)}; + var mean_square_vector = ${nl("f32",_)}; + + for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) { + let value = ${Un(M,_,"x[h + offset]")}; + mean_vector += value; + mean_square_vector += value * value; + } + let mean = ${Ls("mean_vector",_)} / uniforms.norm_size; + let inv_std_dev = inverseSqrt(${Ls("mean_square_vector",_)} / uniforms.norm_size ${s?"":"- mean * mean"} + uniforms.epsilon); + + for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) { + let f32input = ${Un(M,_,"x[j + offset]")}; + let f32scale = ${Un(M,_,"scale[j]")}; + output[j + offset] = ${v[0].type.value}((f32input ${s?"":"- mean"}) * inv_std_dev * f32scale + ${i?`+ ${Un(M,_,"bias[j]")}`:""} + ); + } + + ${w?"mean_data_output[global_idx] = mean":""}; + ${g?"inv_std_output[global_idx] = inv_std_dev":""}; + }`},E=[{dims:a,dataType:e[0].dataType}];return w&&E.push({dims:f,dataType:1}),g&&E.push({dims:f,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${_};${t};${s}`,inputDependencies:T},getRunData:()=>({outputs:E,dispatchGroup:{x:Math.ceil(u/64)},programUniforms:k}),getShaderSource:S}},K_=(e,r)=>{W_(e.inputs),e.compute(G_(e.inputs,r,e.outputCount))}}),H_,q_,Yv=Be(()=>{mt(),Ml(),xl(),H_=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.")},q_=e=>{H_(e.inputs);let r=Nn.calcShape(e.inputs[0].dims,e.inputs[1].dims,!0);if(!r)throw new Error("Can't use matmul on the given tensors");let t=r[r.length-1],s=e.inputs[0].dims[e.inputs[0].dims.length-1];if(t<8&&s<8)e.compute(wl(e.inputs,{activation:""},r));else{let o=r[r.length-2],n=Me.size(e.inputs[0].dims.slice(0,-2)),i=Me.size(e.inputs[1].dims.slice(0,-2));if(n!==1&&o===1&&i===1){let a=e.inputs[0].reshape([1,n,s]),l=e.inputs[1].reshape([1,s,t]),u=[1,n,t],p=[a,l];e.compute(pi(p,{activation:""},r,u),{inputs:p})}else e.compute(pi(e.inputs,{activation:""},r))}}}),X_,Q_,J_,Y_,Z_,Zv=Be(()=>{ut(),mt(),Xt(),ft(),X_=(e,r)=>{if(e.length<3||e.length>4)throw new Error("MatMulNBits requires 3 or 4 inputs");let t=e[0],s=t.dims.length;if(t.dims[s-1]!==r.k)throw new Error("The last dim of input shape does not match the k value");let o=Math.floor((r.k+r.blockSize-1)/r.blockSize),n=r.blockSize/8*r.bits,i=e[1];if(!Me.areEqual(i.dims,[r.n,o,n]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let a=e[2].dims;if(Me.size(a)!==r.n*o)throw new Error("scales input size error.");if(e.length===4){let l=e[3].dims,u=r.bits>4?r.n*o:r.n*Math.floor((o+1)/2);if(Me.size(l)!==u)throw new Error("zeroPoints input size error.")}},Q_=(e,r)=>{let t=e[0].dims,s=t.length,o=t[s-2],n=r.k,i=r.n,a=t.slice(0,s-2),l=Me.size(a),u=e[1].dims[2]/4,p=e[0].dataType,d=Kt(r.k),c=Kt(u),f=Kt(i),_=a.concat([o,i]),T=o>1&&i/f%2===0?2:1,k=Me.size(_)/f/T,w=64,g=[],S=[l,o,n/d],E=Me.convertShape(e[1].dims).slice();E.splice(-1,1,u/c),g.push(...st(S)),g.push(...st(E)),g.push(...st(e[2].dims)),e.length===4&&g.push(...st(Me.convertShape(e[3].dims)));let y=[l,o,i/f];g.push(...st(y));let M=v=>{let C=S.length,A=Pe("a",e[0].dataType,C,d),B=Pe("b",12,E.length,c),K=Pe("scales",e[2].dataType,e[2].dims.length),G=[A,B,K],j=e.length===4?Pe("zero_points",12,e[3].dims.length):void 0;j&&G.push(j);let ee=y.length,H=Ye("output",e[0].dataType,ee,f),Z=lr(e[0].dataType),X=(()=>{switch(d){case 1:return`array<${Z}, 8>`;case 2:return`mat4x2<${Z}>`;case 4:return`mat2x4<${Z}>`;default:throw new Error(`${d}-component is not supported.`)}})(),oe=()=>{let V=` + // reuse a data + var input_offset = ${A.indicesToOffset(`${A.type.indices}(batch, row, word_offset)`)}; + var a_data: ${X}; + for (var j: u32 = 0; j < ${8/d}; j++) { + a_data[j] = ${A.getByOffset("input_offset")}; + input_offset++; + } + `;for(let F=0;F> 4) & b_mask); + b_quantized_values = ${X}(${Array.from({length:4},(W,re)=>`${Z}(b_value_lower[${re}]), ${Z}(b_value_upper[${re}])`).join(", ")}); + b_dequantized_values = ${d===1?`${X}(${Array.from({length:8},(W,re)=>`(b_quantized_values[${re}] - ${j?`zero_point${F}`:"zero_point"}) * scale${F}`).join(", ")});`:`(b_quantized_values - ${X}(${Array(8).fill(`${j?`zero_point${F}`:"zero_point"}`).join(",")})) * scale${F};`}; + workgroup_shared[local_id.x * ${T} + ${Math.floor(F/f)}]${f>1?`[${F%f}]`:""} += ${Array.from({length:8/d},(W,re)=>`${d===1?`a_data[${re}] * b_dequantized_values[${re}]`:`dot(a_data[${re}], b_dequantized_values[${re}])`}`).join(" + ")}; + `;return V},me=()=>{let V=` + var col_index = col * ${f}; + ${j?` + let zero_point_bytes_per_col = (nBlocksPerCol + 1) / 2; + var zero_point_byte_count: u32; + var zero_point_word_index: u32; + var zero_point_byte_offset: u32; + let zero_point_nibble_offset: u32 = block & 0x1u; + var zero_point_bits_offset: u32; + var zero_point_word: u32;`:` + // The default zero point is 8 for unsigned 4-bit quantization. + let zero_point = ${Z}(8);`} + `;for(let F=0;F> 0x1u); + zero_point_word_index = zero_point_byte_count >> 0x2u; + zero_point_byte_offset = zero_point_byte_count & 0x3u; + zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2); + zero_point_word = ${j.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; + let zero_point${F} = ${Z}((zero_point_word) & 0xFu);`:""} + col_index += 1;`;return V},ae=()=>{let V=`col_index = col * ${f};`;for(let F=0;F; + var b_value_upper: vec4; + var b_quantized_values: ${X}; + var b_dequantized_values: ${X};`,V};return` + var workgroup_shared: array<${H.type.value}, ${T*w}>; + ${v.declareVariables(...G,H)} + ${v.mainStart([w,1,1])} + let output_indices = ${H.offsetToIndices(`(global_idx / ${w}) * ${T}`)}; + let col = output_indices[2]; + let row = output_indices[1]; + let batch = output_indices[0]; + let nBlocksPerCol = uniforms.b_shape[1]; + + for (var block = local_id.x; block < nBlocksPerCol; block += ${w}) { + //process one block + var word_offset: u32 = block * ${r.blockSize/d}; + ${me()} + for (var word: u32 = 0; word < ${u}; word += ${c}) { + ${ae()} + for (var i: u32 = 0; i < ${c}; i++) { + ${oe()} + word_offset += ${8/d}; + } + } + } + workgroupBarrier(); + + if (local_id.x < ${T}) { + var output_value: ${H.type.value} = ${H.type.value}(0); + var workgroup_shared_offset: u32 = local_id.x; + for (var b: u32 = 0u; b < ${w}u; b++) { + output_value += workgroup_shared[workgroup_shared_offset]; + workgroup_shared_offset += ${T}; + } + ${H.setByIndices(`${H.type.indices}(batch, row, col + local_id.x)`,"output_value")}; + } + }`};return{name:"MatMulNBits",shaderCache:{hint:`${r.blockSize};${r.bits};${d};${c};${f};${T};${w}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:_,dataType:p}],dispatchGroup:{x:k},programUniforms:g}),getShaderSource:M}},J_=(e,r)=>{let t=e[0].dims,s=t.length,o=t[s-2],n=r.k,i=r.n,a=t.slice(0,s-2),l=Me.size(a),u=e[1].dims[2]/4,p=e[0].dataType,d=Kt(r.k),c=Kt(u),f=a.concat([o,i]),_=128,T=i%8===0?8:i%4===0?4:1,k=_/T,w=k*c*8,g=w/d,S=w/r.blockSize,E=Me.size(f)/T,y=[],M=[l,o,n/d],v=Me.convertShape(e[1].dims).slice();v.splice(-1,1,u/c),y.push(...st(M)),y.push(...st(v)),y.push(...st(e[2].dims)),e.length===4&&y.push(...st(Me.convertShape(e[3].dims)));let C=[l,o,i];y.push(...st(C));let A=B=>{let K=M.length,G=Pe("a",e[0].dataType,K,d),j=Pe("b",12,v.length,c),ee=Pe("scales",e[2].dataType,e[2].dims.length),H=[G,j,ee],Z=e.length===4?Pe("zero_points",12,e[3].dims.length):void 0;Z&&H.push(Z);let X=C.length,oe=Ye("output",e[0].dataType,X),me=lr(e[0].dataType),ae=()=>{switch(d){case 1:return` + let a_data0 = vec4<${me}>(sub_a[word_offset], sub_a[word_offset + 1], sub_a[word_offset + 2], sub_a[word_offset + 3]); + let a_data1 = vec4<${me}>(sub_a[word_offset + 4], sub_a[word_offset + 5], sub_a[word_offset + 6], sub_a[word_offset + 7]);`;case 2:return` + let a_data0 = vec4<${me}>(sub_a[word_offset], sub_a[word_offset + 1]); + let a_data1 = vec4<${me}>(sub_a[word_offset + 2], sub_a[word_offset + 3]);`;case 4:return` + let a_data0 = sub_a[word_offset]; + let a_data1 = sub_a[word_offset + 1];`;default:throw new Error(`${d}-component is not supported.`)}};return` + var sub_a: array<${G.type.value}, ${g}>; + var inter_results: array, ${T}>; + ${B.declareVariables(...H,oe)} + ${B.mainStart([k,T,1])} + let output_indices = ${oe.offsetToIndices(`workgroup_index * ${T}`)}; + let col = output_indices[2]; + let row = output_indices[1]; + let batch = output_indices[0]; + let n_blocks_per_col = uniforms.b_shape[1]; + let num_tiles = (n_blocks_per_col - 1) / ${S} + 1; + + // Loop over shared dimension. + for (var tile: u32 = 0; tile < num_tiles; tile += 1) { + let a_col_start = tile * ${g}; + // load one tile A data into shared memory. + for (var a_offset = local_idx; a_offset < ${g}; a_offset += ${_}) + { + let a_col = a_col_start + a_offset; + if (a_col < uniforms.a_shape[2]) + { + sub_a[a_offset] = ${G.getByIndices(`${G.type.indices}(batch, row, a_col)`)}; + } else { + sub_a[a_offset] = ${G.type.value}(0); + } + } + workgroupBarrier(); + + // each thread process one block + let b_row = col + local_id.y; + let block = tile * ${S} + local_id.x; + ${Z?` + let zero_point_bytes_per_col = (n_blocks_per_col + 1) / 2; + let zero_point_byte_count = b_row * zero_point_bytes_per_col + (block >> 0x1u); + let zero_point_word_index = zero_point_byte_count >> 0x2u; + let zero_point_byte_offset = zero_point_byte_count & 0x3u; + let zero_point_nibble_offset: u32 = block & 0x1u; + let zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2); + let zero_point_word = ${Z.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; + let zero_point = ${me}((zero_point_word) & 0xFu);`:` + // The default zero point is 8 for unsigned 4-bit quantization. + let zero_point = ${me}(8);`} + let scale = ${ee.getByOffset("b_row * n_blocks_per_col + block")}; + let b_data = ${j.getByIndices(`${j.type.indices}(b_row, block, 0)`)}; + var word_offset = local_id.x * ${r.blockSize/d}; + for (var i: u32 = 0; i < ${c}; i++) { + ${ae()} + let b_value = ${c===1?"b_data":"b_data[i]"}; + let b_value_lower = unpack4xU8(b_value & 0x0F0F0F0Fu); + let b_value_upper = unpack4xU8((b_value >> 4) & 0x0F0F0F0Fu); + let b_quantized_values = mat2x4<${me}>(${Array.from({length:4},(V,F)=>`${me}(b_value_lower[${F}]), ${me}(b_value_upper[${F}])`).join(", ")}); + let b_dequantized_values = (b_quantized_values - mat2x4<${me}>(${Array(8).fill("zero_point").join(",")})) * scale; + inter_results[local_id.y][local_id.x] += ${Array.from({length:2},(V,F)=>`${`dot(a_data${F}, b_dequantized_values[${F}])`}`).join(" + ")}; + word_offset += ${8/d}; + } + workgroupBarrier(); + } + + if (local_idx < ${T}) { + var output_value: ${oe.type.value} = ${oe.type.value}(0); + for (var b = 0u; b < ${k}; b++) { + output_value += inter_results[local_idx][b]; + } + if (col + local_idx < uniforms.output_shape[2]) + { + ${oe.setByIndices(`${oe.type.indices}(batch, row, col + local_idx)`,"output_value")} + } + } + }`};return{name:"BlockwiseMatMulNBits32",shaderCache:{hint:`${r.blockSize};${d};${c};${k};${T}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:f,dataType:p}],dispatchGroup:{x:E},programUniforms:y}),getShaderSource:A}},Y_=(e,r)=>{X_(e.inputs,r),r.blockSize===32&&e.adapterInfo.isVendor("intel")&&e.adapterInfo.isArchitecture("gen-12lp")?e.compute(J_(e.inputs,r)):e.compute(Q_(e.inputs,r))},Z_=e=>St(e)}),ef,tf,rf,sf,nf,of,af,lf,uf,ex=Be(()=>{ut(),mt(),ft(),ef=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 r=e[0].dims.length*2===e[1].dims[0];if(e.length===4&&(r=e[3].dims[0]*2===e[1].dims[0]),!r)throw new Error("The pads should be a 1D tensor of shape [2 * input_rank] or [2 * num_axes].")}},tf=(e,r,t)=>{let s="";for(let o=r-1;o>=0;--o)s+=` + k = i32(${e.indicesGet("indices",o)}) - ${et("uniforms.pads",o,t)}; + if (k < 0) { + break; + } + if (k >= i32(${et("uniforms.x_shape",o,r)})) { + break; + } + offset += k * i32(${et("uniforms.x_strides",o,r)}); + `;return` + value = ${e.type.value}(uniforms.constant_value); + for (var i = 0; i < 1; i++) { + var offset = 0; + var k = 0; + ${s} + value = x[offset]; + } + `},rf=(e,r,t)=>{let s="";for(let o=r-1;o>=0;--o)s+=` + k = i32(${e.indicesGet("indices",o)}) - ${et("uniforms.pads",o,t)}; + if (k < 0) { + k = -k; + } + { + let _2n_1 = 2 * (i32(${et("uniforms.x_shape",o,r)}) - 1); + k = k % _2n_1; + if(k >= i32(${et("uniforms.x_shape",o,r)})) { + k = _2n_1 - k; + } + } + offset += k * i32(${et("uniforms.x_strides",o,r)}); + `;return` + var offset = 0; + var k = 0; + ${s} + value = x[offset]; + `},sf=(e,r,t)=>{let s="";for(let o=r-1;o>=0;--o)s+=` + k = i32(${e.indicesGet("indices",o)}) - ${et("uniforms.pads",o,t)}; + if (k < 0) { + k = 0; + } + if (k >= i32(${et("uniforms.x_shape",o,r)})) { + k = i32(${et("uniforms.x_shape",o,r)}) - 1; + } + offset += k * i32(${et("uniforms.x_strides",o,r)}); + `;return` + var offset = 0; + var k = 0; + ${s} + value = x[offset]; + `},nf=(e,r,t)=>{let s="";for(let o=r-1;o>=0;--o)s+=` + k = i32(${e.indicesGet("indices",o)}) - ${et("uniforms.pads",o,t)}; + if (k < 0) { + k += i32(${et("uniforms.x_shape",o,r)}]); + } + if (k >= i32(${et("uniforms.x_shape",o,r)})) { + k -= i32(${et("uniforms.x_shape",o,r)}); + } + offset += k * i32(${et("uniforms.x_strides",o,r)}); + `;return` + var offset = 0; + var k = 0; + ${s} + value = x[offset]; + `},of=(e,r,t)=>{switch(t.mode){case 0:return tf(e,r,t.pads.length);case 1:return rf(e,r,t.pads.length);case 2:return sf(e,r,t.pads.length);case 3:return nf(e,r,t.pads.length);default:throw new Error("Invalid mode")}},af=(e,r)=>{let t=Me.padShape(e[0].dims.slice(),r.pads),s=e[0].dims,o=Me.size(t),n=[{type:12,data:o},{type:6,data:r.pads}],i=e.length>=3&&e[2].data;r.mode===0&&n.push({type:i?e[2].dataType:1,data:r.value}),n.push(...st(e[0].dims,t));let a=["rank"],l=u=>{let p=Ye("output",e[0].dataType,t.length),d=Pe("x",e[0].dataType,s.length),c=d.type.value,f=of(p,s.length,r),_=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:r.pads.length}];return r.mode===0&&_.push({name:"constant_value",type:i?c:"f32"}),` + ${u.registerUniforms(_).declareVariables(d,p)} + ${u.mainStart()} + ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${p.offsetToIndices("global_idx")}; + + var value = ${c}(0); + ${f} + output[global_idx] = value; + }`};return{name:"Pad",shaderCache:{hint:`${r.mode}${i}`,inputDependencies:a},getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(Me.size(t)/64)},programUniforms:n}),getShaderSource:l}},lf=(e,r)=>{if(e.length>1){let t=e[1].getBigInt64Array(),s=e.length>=3&&e[2].data?e[2].dataType===10?e[2].getUint16Array()[0]:e[2].getFloat32Array()[0]:0,o=e[0].dims.length,n=new Int32Array(2*o).fill(0);if(e.length>=4){let a=e[3].getBigInt64Array();for(let l=0;ln[Number(l)]=Number(a));let i=[];return n.forEach(a=>i.push(a)),{mode:r.mode,value:s,pads:i}}else return r},uf=(e,r)=>{ef(e.inputs);let t=lf(e.inputs,r);e.compute(af(e.inputs,t),{inputs:[0]})}}),bo,Bl,Rl,jl,Nl,df,cf,Vl,Ul,pf,hf,Wl,mf,_f,Gl,ff,gf,wf,Mf,tx=Be(()=>{ts(),ut(),mt(),ft(),bo=e=>{if(Bt.webgpu.validateInputContent&&(!e||e.length!==1))throw new Error("Pool ops requires 1 input.")},Bl=(e,r,t)=>{let s=r.format==="NHWC",o=e.dims.slice();s&&o.splice(1,0,o.pop());let n=Object.hasOwnProperty.call(r,"dilations"),i=r.kernelShape.slice(),a=r.strides.slice(),l=n?r.dilations.slice():[],u=r.pads.slice();ni.adjustPoolAttributes(t,o,i,a,l,u);let p=ni.computePoolOutputShape(t,o,a,l,i,u,r.autoPad),d=Object.assign({},r);n?Object.assign(d,{kernelShape:i,strides:a,pads:u,dilations:l,cacheKey:r.cacheKey}):Object.assign(d,{kernelShape:i,strides:a,pads:u,cacheKey:r.cacheKey});let c=p.slice();return c.push(c.splice(1,1)[0]),[d,s?c:p]},Rl=(e,r)=>{let t=r.format==="NHWC",s=Me.size(e),o=Me.size(r.kernelShape),n=[{type:12,data:s},{type:12,data:o}],i=[{name:"outputSize",type:"u32"},{name:"kernelSize",type:"u32"}];if(r.kernelShape.length<=2){let a=r.kernelShape[r.kernelShape.length-1],l=r.strides[r.strides.length-1],u=r.pads[r.pads.length/2-1],p=r.pads[r.pads.length-1],d=!!(u+p);n.push({type:12,data:a},{type:12,data:l},{type:12,data:u},{type:12,data:p}),i.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let c=!1;if(r.kernelShape.length===2){let f=r.kernelShape[r.kernelShape.length-2],_=r.strides[r.strides.length-2],T=r.pads[r.pads.length/2-2],k=r.pads[r.pads.length-2];c=!!(T+k),n.push({type:12,data:f},{type:12,data:_},{type:12,data:T},{type:12,data:k}),i.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[n,i,!0,d,c]}else{if(t)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let a=Me.computeStrides(r.kernelShape);n.push({type:12,data:a},{type:12,data:r.pads},{type:12,data:r.strides}),i.push({name:"kernelStrides",type:"u32",length:a.length},{name:"pads",type:"u32",length:r.pads.length},{name:"strides",type:"u32",length:r.strides.length});let l=r.pads.reduce((u,p)=>u+p);return[n,i,!!l,!1,!1]}},jl=(e,r,t,s,o,n,i,a,l,u,p,d)=>{let c=o.format==="NHWC",f=r.type.value,_=Ye("output",r.type.tensor,s);if(o.kernelShape.length<=2){let T="",k="",w="",g=t-(c?2:1);if(p?T=` + for (var i: u32 = 0u; i < uniforms.kw; i++) { + xIndices[${g}] = indices[${g}] * uniforms.sw - uniforms.pwStart + i; + if (xIndices[${g}] < 0 || xIndices[${g}] + >= uniforms.x_shape[${g}]) { + pad++; + continue; + } + let x_val = x[${r.indicesToOffset("xIndices")}]; + ${n} + }`:T=` + for (var i: u32 = 0u; i < uniforms.kw; i++) { + xIndices[${g}] = indices[${g}] * uniforms.sw - uniforms.pwStart + i; + let x_val = x[${r.indicesToOffset("xIndices")}]; + ${n} + }`,o.kernelShape.length===2){let S=t-(c?3:2);d?k=` + for (var j: u32 = 0u; j < uniforms.kh; j++) { + xIndices[${S}] = indices[${S}] * uniforms.sh - uniforms.phStart + j; + if (xIndices[${S}] < 0 || xIndices[${S}] >= uniforms.x_shape[${S}]) { + pad += i32(uniforms.kw); + continue; + } + `:k=` + for (var j: u32 = 0u; j < uniforms.kh; j++) { + xIndices[${S}] = indices[${S}] * uniforms.sh - uniforms.phStart + j; + `,w=` + } + `}return` + ${e.registerUniforms(l).declareVariables(r,_)} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + + let indices = ${_.offsetToIndices("global_idx")}; + var xIndices = ${_.offsetToIndices("global_idx")}; + + var value = ${f}(${a}); + var pad = 0; + ${k} + ${T} + ${w} + ${i} + + output[global_idx] = value; + }`}else{if(c)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let T=o.kernelShape.length,k=o.pads.length,w="";return u?w=` + if (xIndices[j] >= uniforms.x_shape[j]) { + pad++; + isPad = true; + break; + } + } + if (!isPad) { + let x_val = x[${r.indicesToOffset("xIndices")}]; + ${n} + }`:w=` + } + let x_val = x[${r.indicesToOffset("xIndices")}]; + ${n} + `,` + ${e.registerUniforms(l).declareVariables(r,_)} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + let indices = ${_.offsetToIndices("global_idx")}; + var xIndices = ${_.offsetToIndices("global_idx")}; + + var offsets: array; + + var value = ${f}(${a}); + var pad = 0; + var isPad = false; + + for (var i: u32 = 0u; i < uniforms.kernelSize; i++) { + var offset = i; + for (var j = 0u; j < ${T-1}u; j++) { + offsets[j] = offset / ${et("uniforms.kernelStrides","j",T)}; + offset -= offsets[j] * ${et("uniforms.kernelStrides","j",T)}; + } + offsets[${T-1}] = offset; + + isPad = false; + for (var j = ${t-T}u; j < ${t}u; j++) { + xIndices[j] = indices[j] * ${et("uniforms.strides",`j - ${t-T}u`,T)} + + offsets[j - ${t-T}u] - ${et("uniforms.pads","j - 2u",k)}; + ${w} + } + ${i} + + output[global_idx] = value; + }`}},Nl=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,df=e=>`${Nl(e)};${e.countIncludePad}`,cf=e=>`${Nl(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}),Ul=(e,r,t,s)=>{let[o,n]=Bl(r,s,t),i=Pe("x",r.dataType,r.dims.length),a=i.type.value,l="value += x_val;",u="";o.countIncludePad?u+=`value /= ${a}(uniforms.kernelSize);`:u+=`value /= ${a}(i32(uniforms.kernelSize) - pad);`;let[p,d,c,f,_]=Rl(n,o);p.push(...st(r.dims,n));let T=["rank"];return{name:e,shaderCache:{hint:`${s.cacheKey};${c};${f};${_}`,inputDependencies:T},getRunData:()=>({outputs:[{dims:n,dataType:r.dataType}],dispatchGroup:{x:Math.ceil(Me.size(n)/64)},programUniforms:p}),getShaderSource:k=>jl(k,i,r.dims.length,n.length,o,l,u,0,d,c,f,_)}},pf=e=>{let r=e.count_include_pad!==0,t=Vl(e);if(t.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");let s={countIncludePad:r,...t,cacheKey:""};return{...s,cacheKey:df(s)}},hf=(e,r)=>{bo(e.inputs),e.compute(Ul("AveragePool",e.inputs[0],!1,r))},Wl={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},mf=e=>{let r=e.format;return{format:r,...Wl,cacheKey:r}},_f=(e,r)=>{bo(e.inputs),e.compute(Ul("GlobalAveragePool",e.inputs[0],!0,r))},Gl=(e,r,t,s)=>{let[o,n]=Bl(r,s,t),i=` + value = max(x_val, value); + `,a="",l=Pe("x",r.dataType,r.dims.length),u=["rank"],[p,d,c,f,_]=Rl(n,o);return p.push(...st(r.dims,n)),{name:e,shaderCache:{hint:`${s.cacheKey};${c};${f};${_}`,inputDependencies:u},getRunData:()=>({outputs:[{dims:n,dataType:r.dataType}],dispatchGroup:{x:Math.ceil(Me.size(n)/64)},programUniforms:p}),getShaderSource:T=>jl(T,l,r.dims.length,n.length,o,i,a,r.dataType===10?-65504:-1e5,d,c,f,_)}},ff=(e,r)=>{bo(e.inputs),e.compute(Gl("MaxPool",e.inputs[0],!1,r))},gf=e=>{let r=e.storage_order,t=e.dilations,s=Vl(e);if(r!==0)throw new Error("column major storage order is not yet supported for MaxPool");if(s.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");let o={storageOrder:r,dilations:t,...s,cacheKey:""};return{...o,cacheKey:cf(o)}},wf=e=>{let r=e.format;return{format:r,...Wl,cacheKey:r}},Mf=(e,r)=>{bo(e.inputs),e.compute(Gl("GlobalMaxPool",e.inputs[0],!0,r))}}),bf,yf,vf,xf,rx=Be(()=>{ut(),mt(),Xt(),ft(),bf=(e,r)=>{if(e.length<2||e.length>3)throw new Error("DequantizeLinear requires 2 or 3 inputs.");if(e.length===3&&e[1].dims===e[2].dims)throw new Error("x-scale and x-zero-point must have the same shape.");if(e.length===3&&e[0].dataType!==e[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(e[0].dataType===6&&e.length>2)throw new Error("In the case of dequantizing int32 there is no zero point.");if(e[1].dims.length!==0&&e[1].dims.length!==1&&e[1].dims.length!==e[0].dims.length)throw new Error("scale input must be a scalar, a 1D tensor, or have the same rank as the input tensor.");if(e.length>2){if(e[0].dataType!==e[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(e[1].dims.length!==e[2].dims.length)throw new Error("scale and zero-point inputs must have the same rank.");if(!e[1].dims.map((t,s)=>t===e[2].dims[s]).reduce((t,s)=>t&&s,!0))throw new Error("scale and zero-point inputs must have the same shape.")}if(r.blockSize>0){if(e[1].dims.length===0||e[1].dims.length===1&&e[1].dims[0]===1)throw new Error("blockSize must be set only for block quantization.");if(!e[1].dims.map((o,n)=>n===r.axis||o===e[0].dims[n]).reduce((o,n)=>o&&n,!0))throw new Error("For block qunatization, scale input shape to match the input shape except for the axis");if(e[1].dims.length!==e[0].dims.length)throw new Error("For block qunatization the scale input rank must be the same as the x rank.");let t=e[0].dims[r.axis],s=e[1].dims[r.axis];if(r.blockSizeMath.ceil(t/(s-1)-1))throw new Error("blockSize must be with in the range [ceil(dI / Si), ceil(dI / (Si - 1) - 1)].")}},yf=(e,r)=>{let t=Me.normalizeAxis(r.axis,e[0].dims.length),s=e[0].dataType,o=s===3,n=e[0].dims,i=e[1].dataType,a=Me.size(n),l=s===3||s===2,u=l?[Math.ceil(Me.size(e[0].dims)/4)]:e[0].dims,p=e[1].dims,d=e.length>2?e[2]:void 0,c=d?l?[Math.ceil(Me.size(d.dims)/4)]:d.dims:void 0,f=p.length===0||p.length===1&&p[0]===1,_=f===!1&&p.length===1,T=Kt(a),k=f&&(!l||T===4),w=k?T:1,g=k&&!l?T:1,S=Pe("input",l?12:s,u.length,g),E=Pe("scale",i,p.length),y=d?Pe("zero_point",l?12:s,c.length):void 0,M=Ye("output",i,n.length,w),v=[S,E];y&&v.push(y);let C=[u,p];d&&C.push(c);let A=[{type:12,data:a/w},{type:12,data:t},{type:12,data:r.blockSize},...st(...C,n)],B=K=>{let G=[{name:"output_size",type:"u32"},{name:"axis",type:"u32"},{name:"block_size",type:"u32"}];return` + ${K.registerUniforms(G).declareVariables(...v,M)} + ${K.mainStart()} + ${K.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let output_indices = ${M.offsetToIndices("global_idx")}; + + // Set input x + ${l?` + let input = ${S.getByOffset("global_idx / 4")}; + let x_vec = ${o?"unpack4xI8(input)":"unpack4xU8(input)"}; + let x_value = ${w===1?"x_vec[global_idx % 4]":"x_vec"};`:`let x_value = ${S.getByOffset("global_idx")};`}; + + // Set scale input + ${f?`let scale_value= ${E.getByOffset("0")}`:_?` + let scale_index = ${M.indicesGet("output_indices","uniforms.axis")}; + let scale_value= ${E.getByOffset("scale_index")};`:` + var scale_indices: ${E.type.indices} = output_indices; + let index = ${E.indicesGet("scale_indices","uniforms.axis")} / uniforms.block_size; + ${E.indicesSet("scale_indices","uniforms.axis","index")}; + let scale_value= ${E.getByIndices("scale_indices")};`}; + + // Set zero-point input + ${y?f?l?` + let zero_point_input = ${y.getByOffset("0")}; + let zero_point_vec = ${o?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; + let zero_point_value= zero_point_vec[0]`:`let zero_point_value = ${y.getByOffset("0")}`:_?l?` + let zero_point_index = ${M.indicesGet("output_indices","uniforms.axis")}; + let zero_point_input = ${y.getByOffset("zero_point_index / 4")}; + let zero_point_vec = ${o?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; + let zero_point_value = zero_point_vec[zero_point_index % 4]`:` + let zero_point_index = ${M.indicesGet("output_indices","uniforms.axis")}; + let zero_point_value = ${y.getByOffset("zero_point_index")};`:l?` + let zero_point_offset = ${E.indicesToOffset("scale_indices")}; + let zero_point_input = ${y.getByOffset("zero_point_offset / 4")}; + let zero_point_vec = ${o?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; + let zero_point_value = zero_point_vec[zero_point_offset % 4];`:`let zero_point_value = ${y.getByIndices("scale_indices")};`:`let zero_point_value = ${l?o?"i32":"u32":S.type.value}(0);`}; + // Compute and write output + ${M.setByOffset("global_idx",`${M.type.value}(x_value - zero_point_value) * scale_value`)}; + }`};return{name:"DequantizeLinear",shaderCache:{hint:r.cacheKey,inputDependencies:y?["rank","rank","rank"]:["rank","rank"]},getShaderSource:B,getRunData:()=>({outputs:[{dims:n,dataType:i}],dispatchGroup:{x:Math.ceil(a/w/64),y:1,z:1},programUniforms:A})}},vf=(e,r)=>{bf(e.inputs,r),e.compute(yf(e.inputs,r))},xf=e=>St({axis:e.axis,blockSize:e.blockSize})}),Tf,Ef,Pf,sx=Be(()=>{ts(),ut(),ft(),Tf=(e,r,t)=>{let s=e===r,o=er&&t>0;if(s||o||n)throw new Error("Range these inputs' contents are invalid.")},Ef=(e,r,t,s)=>{let o=Math.abs(Math.ceil((r-e)/t)),n=[o],i=o,a=[{type:12,data:i},{type:s,data:e},{type:s,data:t},...st(n)],l=u=>{let p=Ye("output",s,n.length),d=p.type.value,c=[{name:"outputSize",type:"u32"},{name:"start",type:d},{name:"delta",type:d}];return` + ${u.registerUniforms(c).declareVariables(p)} + ${u.mainStart()} + ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + output[global_idx] = uniforms.start + ${d}(global_idx) * uniforms.delta; + }`};return{name:"Range",shaderCache:{hint:`${s}`},getShaderSource:l,getRunData:()=>({outputs:[{dims:n,dataType:s}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:a})}},Pf=e=>{let r=0,t=0,s=0;e.inputs[0].dataType===6?(r=e.inputs[0].getInt32Array()[0],t=e.inputs[1].getInt32Array()[0],s=e.inputs[2].getInt32Array()[0]):e.inputs[0].dataType===1&&(r=e.inputs[0].getFloat32Array()[0],t=e.inputs[1].getFloat32Array()[0],s=e.inputs[2].getFloat32Array()[0]),Bt.webgpu.validateInputContent&&Tf(r,t,s),e.compute(Ef(r,t,s,e.inputs[0].dataType),{inputs:[]})}}),Cf,Kl,Hl,Sf,$f,kf,nx=Be(()=>{ut(),mt(),Xt(),ft(),Cf=(e,r,t,s)=>{if(e!=="none"&&s!=="i32"&&s!=="u32"&&s!=="f32")throw new Error(`Input ${s} is not supported with reduction ${e}.`);let o=`{ + var oldValue = 0; + loop { + let newValueF32 =`,n=`; + let newValue = bitcast(newValueF32); + let res = atomicCompareExchangeWeak(&${r}, oldValue, newValue); + if res.exchanged { + break; + } + oldValue = res.old_value; + } + }`;switch(e){case"none":return`${r}=${t};`;case"add":return s==="i32"||s==="u32"?`atomicAdd(&${r}, bitcast<${s}>(${t}));`:` + ${o}bitcast<${s}>(oldValue) + (${t})${n}`;case"max":return s==="i32"||s==="u32"?`atomicMax(&${r}, bitcast<${s}>(${t}));`:` + ${o}max(bitcast(oldValue), (${t}))${n}`;case"min":return s==="i32"||s==="u32"?`atomicMin(&${r}, bitcast<${s}>(${t}));`:`${o}min(bitcast<${s}>(oldValue), (${t}))${n}`;case"mul":return`${o}(bitcast<${s}>(oldValue) * (${t}))${n}`;default:throw new Error(`Reduction ${e} is not supported.`)}},Kl=(e,r)=>`${e===1?` + let element_count_dim = uniforms.output_strides; + let dim_value = uniforms.output_shape;`:` + let element_count_dim = uniforms.output_strides[${r?"i - indices_start":"i"}]; + let dim_value = uniforms.output_shape[${r?"i - indices_start":"i"} + uniforms.last_index_dimension];`} + + if (index >= 0) { + if (index >= i32(dim_value)) { + index = i32(dim_value - 1); + } + } else { + if (index < -i32(dim_value)) { + index = 0; + } else { + index += i32(dim_value); + } + } + data_offset += u32((u32(index) * element_count_dim));`,Hl=(e,r,t)=>`for (var i = 0u; i < uniforms.num_updates_elements; i++) { + let value = updates[uniforms.num_updates_elements * ${t?"global_idx":"idx"} + i]; + ${Cf(e.reduction,"output[data_offset + i]","value",r)} + }`,Sf=(e,r)=>{let t=e[0].dims,s=e[1].dims,o=t,n=1,i=Math.ceil(Me.size(s)/n),a=s[s.length-1],l=Me.sizeFromDimension(t,a),u=Me.sizeFromDimension(s,0)/a,p=[{type:12,data:i},{type:12,data:a},{type:12,data:l},...st(e[1].dims,e[2].dims,o)],d=c=>{let f=Pe("indices",e[1].dataType,e[1].dims.length),_=Pe("updates",e[2].dataType,e[2].dims.length,n),T=r.reduction!=="none"&&r.reduction!==""?Dc("output",e[0].dataType,o.length):Ye("output",e[0].dataType,o.length,n);return` + ${c.registerUniform("output_size","u32").registerUniform("last_index_dimension","u32").registerUniform("num_updates_elements","u32").declareVariables(f,_,T)} + ${c.mainStart()} + ${c.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + var hasDuplicates = false; + if (${r.reduction==="none"}) { + for (var i = 0; i < ${u}; i = i + 1) { + for (var j = i + 1; j < ${u}; j = j + 1) { + var index_i = i32(indices[i].x); + var index_j = i32(indices[j].x); + if (index_i == index_j) { + hasDuplicates = true; + break; + } + } + if (hasDuplicates) { + break; + } + } + } + + if (${r.reduction==="none"} && hasDuplicates) { + if (global_idx != 0u) { + return; + } + // Process each index-update pair individually when duplicates exist + for (var idx = 0u; idx < ${u}u; idx++) { + var data_offset = 0u; + for (var i = 0u; i < uniforms.last_index_dimension; i++) { + var index = i32(indices[idx * uniforms.last_index_dimension + i].x); + ${Kl(t.length,!1)} + } + ${Hl(r,T.type.value,!1)} + } + return; + } + + var data_offset = 0u; + var indices_start = uniforms.last_index_dimension * global_idx; + var indices_end = indices_start + uniforms.last_index_dimension; + for (var i = indices_start; i < indices_end; i++) { + var index = i32(indices[i].x); + ${Kl(t.length,!0)} + } + ${Hl(r,T.type.value,!0)} + }`};return{name:"ScatterND",shaderCache:{hint:`${r.cacheKey}_${r.reduction}`,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:p}),getShaderSource:d}},$f=e=>St({reduction:e.reduction}),kf=(e,r)=>{e.compute(Sf(e.inputs,r),{inputs:[e.inputs[1],e.inputs[2]],outputs:[]})}}),If,Af,Ff,ql,Of,Df,Lf,zf,Bf,Rf,jf,Nf,Xl,Vf,Uf,Wf,Gf,Kf,Hf,qf,ox=Be(()=>{ut(),mt(),Xt(),ft(),If=(e,r)=>{if(e.every(t=>t>0||(()=>{throw new Error("Resize requires scales input values to be positive")})),e.length>0){if(r.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(r.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")}},Af=(e,r,t)=>{r.every(o=>o>=0&&o{throw new Error("Resize requires axes input values to be positive and less than rank")}));let s=new Array(t).fill(1);return r.forEach((o,n)=>s[o]=e[n]),s},Ff=(e,r,t,s,o,n)=>{let[i,a,l]=t>10?[1,2,3]:[-1,e.length>1?1:-1,-1],u=e[0].dims.length;if(i>0&&e.length>i&&e[i].dims.length>0)e[i].getFloat32Array().forEach(p=>n.push(p));else if(r.coordinateTransformMode==="tf_crop_and_resize")throw new Error("Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize");if(a>0&&e.length>a&&e[a].dims.length===1&&e[a].dims[0]>0){if(e[a].getFloat32Array().forEach(p=>s.push(p)),s.length!==0&&s.length!==u&&t>=18&&s.length!==r.axes.length)throw new Error("Resize requires scales input size to be same as input rank or axes size for opset 18 and up");If(s,r),r.axes.length>0&&Af(s,r.axes,u).forEach((p,d)=>s[d]=p)}if(l>0&&e.length>l&&e[l].dims.length===1&&e[l].dims[0]>0&&(e[l].getBigInt64Array().forEach(p=>o.push(Number(p))),o.length!==0&&o.length!==u&&t>=18&&o.length!==r.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(r.axes.length>0){if(s.length!==0&&s.length!==r.axes.length)throw new Error('Resize requires "scales" input size to be of axes rank when axes attributes is specified');if(o.length!==0&&o.length!==r.axes.length)throw new Error('Resize requires "sizes" input size to be of rank axes rank when axes attributes is specified')}if(typeof s<"u"&&typeof o<"u"&&s.length>0&&o.length>u)throw new Error("Resize requires only of scales or sizes to be specified")},ql=(e,r,t,s)=>` + // 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 big = (${e}) * (${r}); + let whole = ${s}(big / (${t})); + let fract = ${s}(big % (${t})) / ${s}(${t}); + return whole + fract; +`,Of=(e,r)=>`fn getOriginalCoordinateFromResizedCoordinate(xResized: u32, xScale: f32, lengthResized: u32, + lengthOriginal: u32, roiStart: f32, roiEnd: f32) -> ${r} { `+(()=>{switch(e){case"asymmetric":return` + if (xScale < 1.0 || floor(xScale) != xScale) { + return ${r}(xResized) / ${r}(xScale); + } else { + ${ql("xResized","lengthOriginal","lengthResized",r)} + } + `;case"pytorch_half_pixel":return`if (lengthResized > 1) { + return (${r}(xResized) + 0.5) / ${r}(xScale) - 0.5; + } else { + return 0.0; + }`;case"tf_half_pixel_for_nn":return`return (${r}(xResized) + 0.5) / ${r}(xScale);`;case"align_corners":return`if (lengthResized == 1) { + return 0.0; + } else { + ${ql("xResized","lengthOriginal - 1","lengthResized - 1",r)} + }`;case"tf_crop_and_resize":return`if (lengthResized > 1) { + return ${r}(roiStart) * ${r}(lengthOriginal - 1) + + (${r}(xResized) * ${r}(roiEnd - roiStart) * ${r}(lengthOriginal - 1)) / + ${r}(lengthResized - 1); + } else { + return 0.5 * ${r}(roiStart + roiEnd) * ${r}(lengthOriginal - 1); + }`;case"half_pixel_symmetric":return`const outputWidth = ${r}xScale * ${r}(lengthResized); + const adjustment = ${r}(lengthResized) / outputWidth; + const center = ${r}(lengthOriginal) / 2; + const offset = center * (1 - adjustment); + return offset + ((${r}(xResized) + 0.5) / ${r}(xScale)) - 0.5;`;case"half_pixel":return`return ((${r}(xResized) + 0.5) / ${r}(xScale)) - 0.5;`;default:throw new Error(`Coordinate transform mode ${e} is not supported`)}})()+"}",Df=(e,r,t)=>`fn getNearestPixelFromOriginal(xOriginal: ${t}, isDownSample: bool) -> ${t} {`+(()=>{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(r<11)return"if (isDownSample) { return ceil(xOriginal); } else { return xOriginal; }";throw new Error(`Nearest mode ${e} is not supported`)}})()+"}",Lf=(e,r,t)=>{let s=new Array(t).fill(0).concat(new Array(t).fill(1)),o=e.length===0?s:e.slice();return r.length>0?(r.forEach((n,i)=>{s[n]=o[i],s[i+t]=o[r.length+i]}),s):o},zf=(e,r,t,s)=>{let o=[];if(t.length>0)if(s.length>0){if(e.forEach(n=>o.push(n)),Math.max(...s)>e.length)throw new Error("axes is out of bound");s.forEach((n,i)=>o[n]=t[i])}else t.forEach(n=>o.push(n));else{if(r.length===0)throw new Error("Resize requires either scales or sizes.");o=e.map((n,i)=>Math.round(n*r[i]))}return o},Bf=(e,r,t)=>{let s=(()=>{switch(t.keepAspectRatioPolicy){case"not_larger":return t.axes.length>0?Math.min(...t.axes.map(n=>r[n]),Number.MAX_VALUE):Math.min(...r,Number.MAX_VALUE);case"not_smaller":return t.axes.length>0?Math.max(...t.axes.map(n=>r[n]),Number.MIN_VALUE):Math.max(...r,Number.MIN_VALUE);default:throw new Error(`Keep aspect ratio policy ${t.keepAspectRatioPolicy} is not supported`)}})();r.fill(1,0,r.length);let o=e.slice();return t.axes.length>0?(t.axes.forEach(n=>r[n]=s),t.axes.forEach(n=>o[n]=Math.round(e[n]*r[n]))):(r.fill(s,0,r.length),o.forEach((n,i)=>o[i]=Math.round(n*r[i]))),o},Rf=(e,r,t,s,o)=>` + fn calculateOriginalIndicesFromOutputIndices(output_indices: ${e.type.indices}) -> array<${e.type.value}, ${t.length}> { + var original_indices: array<${e.type.value}, ${t.length}>; + for (var i:u32 = 0; i < ${t.length}; i++) { + var output_index = ${e.indicesGet("output_indices","i")}; + var scale = ${et("uniforms.scales","i",s)}; + var roi_low = ${et("uniforms.roi","i",o)}; + var roi_hi = ${et("uniforms.roi",`i + ${r.length}`,o)}; + if (scale == 1.0) { + original_indices[i] = ${e.type.value}(output_index); + } else { + var input_shape_i = ${et("uniforms.input_shape","i",r.length)}; + var output_shape_i = ${et("uniforms.output_shape","i",t.length)}; + original_indices[i] = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, + input_shape_i, roi_low, roi_hi); + } + } + return original_indices; + }`,jf=(e,r,t,s,o,n,i)=>` + fn calculateInputIndicesFromOutputIndices(output_indices: ${r.type.indices}) -> ${e.type.indices} { + var input_indices: ${e.type.indices}; + for (var i:u32 = 0; i < ${s.length}; i++) { + var output_index = ${r.indicesGet("output_indices","i")}; + var input_index: u32; + var scale = ${et("uniforms.scales","i",o)}; + if (scale == 1.0) { + input_index = output_index; + } else { + var roi_low = ${et("uniforms.roi","i",n)}; + var roi_hi = ${et("uniforms.roi",`i + ${t.length}`,n)}; + var input_shape_i = ${et("uniforms.input_shape","i",t.length)}; + var output_shape_i = ${et("uniforms.output_shape","i",s.length)}; + var original_idx = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, + input_shape_i, roi_low, roi_hi); + if (!${i} || (original_idx >= 0 && original_idx < ${r.type.value}(input_shape_i))) { + if (original_idx < 0) { + input_index = 0; + } else if (original_idx > ${r.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; + }`,Nf=(e,r)=>` + fn checkInputIndices(input_indices: ${e.type.indices}) -> bool { + for (var i:u32 = 0; i < ${r.length}; i++) { + var input_index = ${e.indicesGet("input_indices","i")}; + if (input_index < 0 || input_index >= ${et("uniforms.input_shape","i",r.length)}) { + return false; + } + } + return true; + }`,Xl=(e,r,t,s)=>e.rank>s?` + ${e.indicesSet("input_indices",r,"channel")}; + ${e.indicesSet("input_indices",t,"batch")}; +`:"",Vf=(e,r,t,s,o)=>{let[n,i,a,l]=t.length===2?[-1,0,1,-1]:[0,2,3,1],u=e.type.value;return` + fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${u} { + var input_indices: ${e.type.indices}; + ${e.indicesSet("input_indices",i,`max(0, min(row, ${t[i]} - 1))`)}; + ${e.indicesSet("input_indices",a,`max(0, min(col, ${t[a]} - 1))`)}; + ${Xl(e,l,n,2)} + return ${e.getByIndices("input_indices")}; + } + + fn bilinearInterpolation(output_indices: ${r.type.indices}) -> ${u} { + var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); + var row:${u} = originalIndices[${i}]; + var col:${u} = originalIndices[${a}]; + ${s?`if (row < 0 || row > (${t[i]} - 1) || col < 0 || col > (${t[a]} - 1)) { + return ${o}; + }`:""}; + row = max(0, min(row, ${t[i]} - 1)); + col = max(0, min(col, ${t[a]} - 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 = ${t.length>2?`u32(originalIndices[${l}])`:"0"}; + var batch: u32 = ${t.length>2?`u32(originalIndices[${n}])`:"0"}; + var x11: ${u} = getInputValue(batch, channel, row1, col1); + var x12: ${u} = getInputValue(batch, channel, row1, col2); + var x21: ${u} = getInputValue(batch, channel, row2, col1); + var x22: ${u} = getInputValue(batch, channel, row2, col2); + var dx1: ${u} = abs(row - ${u}(row1)); + var dx2: ${u} = abs(${u}(row2) - row); + var dy1: ${u} = abs(col - ${u}(col1)); + var dy2: ${u} = abs(${u}(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); + }`},Uf=(e,r,t,s,o,n,i,a,l,u)=>{let p=t.length===2,[d,c]=p?[0,1]:[2,3],f=e.type.value,_=T=>{let k=T===d?"row":"col";return` + fn ${k}CubicInterpolation(input_indices: ${e.type.indices}, output_indices: ${r.type.indices}) -> ${f} { + var output_index = ${r.indicesGet("output_indices",T)}; + var originalIdx: ${f} = getOriginalCoordinateFromResizedCoordinate(output_index, ${o[T]}, + ${s[T]}, ${t[T]}, ${n[T]}, ${n[T]} + ${t.length}); + var fractOriginalIdx: ${f} = originalIdx - floor(originalIdx); + var coefs = getCubicInterpolationCoefs(fractOriginalIdx); + + if (${a} && (originalIdx < 0 || originalIdx > (${t[T]} - 1))) { + return ${l}; + } + var data: array<${f}, 4> = array<${f}, 4>(0.0, 0.0, 0.0, 0.0); + for (var i: i32 = -1; i < 3; i++) { + var ${k}: ${f} = originalIdx + ${f}(i); + if (${k} < 0 || ${k} >= ${t[T]}) { + ${u?`coefs[i + 1] = 0.0; + continue;`:a?`return ${l};`:`${k} = max(0, min(${k}, ${t[T]} - 1));`}; + } + var input_indices_copy: ${e.type.indices} = input_indices; + ${e.indicesSet("input_indices_copy",T,`u32(${k})`)}; + data[i + 1] = ${T===d?e.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"}; + } + return cubicInterpolation1D(data, coefs); + }`};return` + ${_(d)}; + ${_(c)}; + fn getCubicInterpolationCoefs(s: ${f}) -> array<${f}, 4> { + var absS = abs(s); + var coeffs: array<${f}, 4> = array<${f}, 4>(0.0, 0.0, 0.0, 0.0); + var oneMinusAbsS: ${f} = 1.0 - absS; + var twoMinusAbsS: ${f} = 2.0 - absS; + var onePlusAbsS: ${f} = 1.0 + absS; + coeffs[0] = ((${i} * onePlusAbsS - 5 * ${i}) * onePlusAbsS + 8 * ${i}) * onePlusAbsS - 4 * ${i}; + coeffs[1] = ((${i} + 2) * absS - (${i} + 3)) * absS * absS + 1; + coeffs[2] = ((${i} + 2) * oneMinusAbsS - (${i} + 3)) * oneMinusAbsS * oneMinusAbsS + 1; + coeffs[3] = ((${i} * twoMinusAbsS - 5 * ${i}) * twoMinusAbsS + 8 * ${i}) * twoMinusAbsS - 4 * ${i}; + return coeffs; + } + + fn cubicInterpolation1D(x: array<${f}, 4>, coefs: array<${f}, 4>) -> ${f} { + var coefsSum: ${f} = 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: ${r.type.indices}) -> ${f} { + var input_indices: ${e.type.indices} = output_indices; + return colCubicInterpolation(input_indices, output_indices); + } + `},Wf=(e,r,t,s,o)=>{let[n,i,a,l,u]=t.length===3?[-1,0,1,2,-1]:[0,2,3,4,1],p=e.type.value;return` + fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${p} { + var input_indices: ${e.type.indices}; + ${e.indicesSet("input_indices",i,`max(0, min(depth, ${t[i]} - 1))`)}; + ${e.indicesSet("input_indices",a,`max(0, min(height, ${t[a]} - 1))`)}; + ${e.indicesSet("input_indices",l,`max(0, min(width, ${t[l]} - 1))`)}; + ${Xl(e,u,n,3)} + return ${e.getByIndices("input_indices")}; + } + + fn trilinearInterpolation(output_indices: ${r.type.indices}) -> ${p} { + var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); + var depth:${p} = originalIndices[${i}]; + var height:${p} = originalIndices[${a}]; + var width:${p} = originalIndices[${l}]; + ${s?`if (depth < 0 || depth > (${t[i]} - 1) || height < 0 || height > (${t[a]} - 1) || width < 0 || (width > ${t[l]} - 1)) { + return ${o}; + }`:""}; + + depth = max(0, min(depth, ${t[i]} - 1)); + height = max(0, min(height, ${t[a]} - 1)); + width = max(0, min(width, ${t[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 = ${t.length>3?`u32(originalIndices[${u}])`:"0"}; + var batch: u32 = ${t.length>3?`u32(originalIndices[${n}])`:"0"}; + + var x111: ${p} = getInputValue(batch, channel, depth1, height1, width1); + var x112: ${p} = getInputValue(batch, channel, depth1, height1, width2); + var x121: ${p} = getInputValue(batch, channel, depth1, height2, width1); + var x122: ${p} = getInputValue(batch, channel, depth1, height2, width2); + var x211: ${p} = getInputValue(batch, channel, depth2, height1, width1); + var x212: ${p} = getInputValue(batch, channel, depth2, height1, width2); + var x221: ${p} = getInputValue(batch, channel, depth2, height2, width1); + var x222: ${p} = getInputValue(batch, channel, depth2, height2, width2); + var dx1: ${p} = abs(depth - ${p}(depth1)); + var dx2: ${p} = abs(${p}(depth2) - depth); + var dy1: ${p} = abs(height - ${p}(height1)); + var dy2: ${p} = abs(${p}(height2) - height); + var dz1: ${p} = abs(width - ${p}(width1)); + var dz2: ${p} = abs(${p}(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); + }`},Gf=(e,r,t,s,o,n)=>{let i=e.dims,a=Lf(n,r.axes,i.length),l=zf(i,s,o,r.axes),u=s.slice();s.length===0&&(u=i.map((g,S)=>g===0?1:l[S]/g),r.keepAspectRatioPolicy!=="stretch"&&(l=Bf(i,u,r)));let p=Ye("output",e.dataType,l.length),d=Pe("input",e.dataType,i.length),c=Me.size(l),f=i.length===l.length&&i.every((g,S)=>g===l[S]),_=r.coordinateTransformMode==="tf_crop_and_resize",T=r.extrapolationValue,k=d.type.value,w=g=>` + ${f?"":` + ${Of(r.coordinateTransformMode,k)}; + ${(()=>{switch(r.mode){case"nearest":return` + ${Nf(d,i)}; + ${Df(r.nearestMode,t,k)}; + ${jf(d,p,i,l,u.length,a.length,_)}; + `;case"linear":return` + ${Rf(p,i,l,u.length,a.length)}; + ${(()=>{if(i.length===2||i.length===4)return`${Vf(d,p,i,_,T)}`;if(i.length===3||i.length===5)return`${Wf(d,p,i,_,T)}`;throw Error("Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.")})()}; + `;case"cubic":return` + ${(()=>{if(i.length===2||i.length===4)return`${Uf(d,p,i,l,u,a,r.cubicCoeffA,_,r.extrapolationValue,r.excludeOutside)}`;throw Error("Cubic mode only supports input dims 2 and 4 are supported in linear mode.")})()}; + `;default:throw Error("Invalid resize mode")}})()}; + `} + ${g.registerUniform("output_size","u32").registerUniform("scales","f32",u.length).registerUniform("roi","f32",a.length).declareVariables(d,p)} + ${g.mainStart()} + ${g.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + ${f?"output[global_idx] = input[global_idx];":` + let output_indices = ${p.offsetToIndices("global_idx")}; + var input_indices: ${d.type.indices}; + ${(()=>{switch(r.mode){case"nearest":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices); + if (checkInputIndices(input_indices)) { + output[global_idx] = ${d.getByIndices("input_indices")}; + } else { + output[global_idx] = ${r.extrapolationValue}; + }`;case"linear":return`output[global_idx] = ${i.length===2||i.length===4?"bilinearInterpolation":"trilinearInterpolation"}(output_indices);`;case"cubic":return"output[global_idx] = bicubicInterpolation(output_indices);";default:throw Error(`Unsupported resize mode: ${r.mode}`)}})()}; +`} + }`;return{name:"Resize",shaderCache:{hint:`${r.cacheKey}|${t}|${u.length>0?r.mode==="cubic"?u:u.length:""}|${o.length>0?o:""}|${a.length>0?a:""}|${f}|${r.mode==="nearest"?i.length:i}`,inputDependencies:["rank"]},getShaderSource:w,getRunData:()=>({outputs:[{dims:l,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:[{type:12,data:c},{type:1,data:u},{type:1,data:a},...st(i,l)]})}},Kf=e=>{let r=e.customDataBuffer;return new Uint32Array(r,r.byteOffset,1)[0]},Hf=(e,r)=>{let t=[],s=[],o=[],n=Kf(e);if(r.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");Ff(e.inputs,r,n,t,s,o),e.compute(Gf(e.inputs[0],r,n,t,s,o),{inputs:[0]})},qf=e=>{let r=e.antialias,t=e.axes,s=e.coordinateTransformMode,o=e.cubicCoeffA,n=e.excludeOutside!==0,i=e.extrapolationValue,a=e.keepAspectRatioPolicy,l=e.mode,u=e.nearestMode===""?"simple":e.nearestMode;return St({antialias:r,axes:t,coordinateTransformMode:s,cubicCoeffA:o,excludeOutside:n,extrapolationValue:i,keepAspectRatioPolicy:a,mode:l,nearestMode:u})}}),Xf,Qf,Jf,ix=Be(()=>{ut(),mt(),ft(),Xf=e=>{if(!e||e.length<3)throw new Error("layerNorm requires at least 3 inputs.");let r=e[0],t=e[1],s=e[2];if(r.dataType!==t.dataType||r.dataType!==s.dataType)throw new Error("All inputs must have the same data type");if(r.dims.length!==3&&r.dims.length!==2)throw new Error("Input must be 2D or 3D");if(t.dims.length!==3&&t.dims.length!==2)throw new Error("Skip must be 2D or 3D");let o=r.dims[r.dims.length-1],n=r.dims[r.dims.length-2];if(t.dims[t.dims.length-1]!==o)throw new Error("Skip must have the same hidden size as input");if(t.dims[t.dims.length-2]!==n)throw new Error("Skip must have the same sequence length as input");if(s.dims.length!==1)throw new Error("Gamma must be 1D");if(s.dims[s.dims.length-1]!==o)throw new Error("Gamma must have the same hidden size as input");if(e.length>3){let i=e[3];if(i.dims.length!==1)throw new Error("Beta must be 1D");if(i.dims[i.dims.length-1]!==o)throw new Error("Beta must have the same hidden size as input")}if(e.length>4){let i=e[4];if(i.dims.length!==1)throw new Error("Bias must be 1D");if(i.dims[i.dims.length-1]!==o)throw new Error("Bias must have the same hidden size as input")}},Qf=(e,r,t,s)=>{let o=r.simplified,n=e[0].dims,i=Me.size(n),a=n,l=i,u=n.slice(-1)[0],p=s?n.slice(0,-1).concat(1):[],d=!o&&e.length>3,c=e.length>4,f=s&&t>1,_=s&&t>2,T=t>3,k=64,w=Kt(u),g=[{type:12,data:l},{type:12,data:w},{type:12,data:u},{type:1,data:r.epsilon}],S=y=>{let M=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],v=[Pe("x",e[0].dataType,e[0].dims,w),Pe("skip",e[1].dataType,e[1].dims,w),Pe("gamma",e[2].dataType,e[2].dims,w)];d&&v.push(Pe("beta",e[3].dataType,e[3].dims,w)),c&&v.push(Pe("bias",e[4].dataType,e[4].dims,w)),v.push(Ye("output",e[0].dataType,a,w)),f&&v.push(Ye("mean_output",1,p)),_&&v.push(Ye("inv_std_output",1,p)),T&&v.push(Ye("input_skip_bias_sum",e[0].dataType,a,w));let C=lr(e[0].dataType),A=lr(1,w);return` + + ${y.registerUniforms(M).declareVariables(...v)} + var sum_shared : array<${A}, ${k}>; + var sum_squared_shared : array<${A}, ${k}>; + + ${y.mainStart([k,1,1])} + let ix = local_id.x; + let iy = global_id.x / ${k}; + + let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components; + var stride = hidden_size_vectorized / ${k}; + let offset = ix * stride + iy * hidden_size_vectorized; + let offset1d = stride * ix; + if (ix == ${k-1}) { + stride = hidden_size_vectorized - stride * ix; + } + for (var i: u32 = 0; i < stride; i++) { + let skip_value = skip[offset + i]; + let bias_value = ${c?"bias[offset1d + i]":C+"(0.0)"}; + let input_value = x[offset + i]; + let value = input_value + skip_value + bias_value; + ${T?"input_skip_bias_sum[offset + i] = value;":""} + output[offset + i] = value; + let f32_value = ${Un(C,w,"value")}; + sum_shared[ix] += f32_value; + sum_squared_shared[ix] += f32_value * f32_value; + } + workgroupBarrier(); + + var reduce_size : u32 = ${k}; + for (var curr_size = reduce_size >> 1; curr_size > 0; curr_size = reduce_size >> 1) { + reduce_size = curr_size + (reduce_size & 1); + if (ix < curr_size) { + sum_shared[ix] += sum_shared[ix + reduce_size]; + sum_squared_shared[ix] += sum_squared_shared[ix + reduce_size]; + } + workgroupBarrier(); + } + + let sum = sum_shared[0]; + let square_sum = sum_squared_shared[0]; + let mean = ${Ls("sum",w)} / f32(uniforms.hidden_size); + let inv_std_dev = inverseSqrt(${Ls("square_sum",w)} / f32(uniforms.hidden_size) ${o?"":"- mean * mean"} + uniforms.epsilon); + ${f?"mean_output[global_idx] = mean;":""} + ${_?"inv_std_output[global_idx] = inv_std_dev;":""} + + for (var i: u32 = 0; i < stride; i++) { + output[offset + i] = (output[offset + i] ${o?"":`- ${C}(mean)`}) * + ${C}(inv_std_dev) * gamma[offset1d + i] + ${d?"+ beta[offset1d + i]":""}; + } + }`},E=[{dims:a,dataType:e[0].dataType}];return t>1&&E.push({dims:p,dataType:1}),t>2&&E.push({dims:p,dataType:1}),t>3&&E.push({dims:n,dataType:e[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${w};${f};${_};${T}`,inputDependencies:e.map((y,M)=>"type")},getShaderSource:S,getRunData:()=>({outputs:E,dispatchGroup:{x:Math.ceil(l/u)},programUniforms:g})}},Jf=(e,r)=>{Xf(e.inputs);let t=[0];e.outputCount>1&&t.push(-3),e.outputCount>2&&t.push(-3),e.outputCount>3&&t.push(3),e.compute(Qf(e.inputs,r,e.outputCount,!1),{outputs:t})}}),Yf,yo,Zf,Ql,eg,tg,rg,sg,ax=Be(()=>{ut(),mt(),Xt(),ft(),Yf=(e,r)=>{if(!e||e.length<1)throw new Error("too few inputs");if(r.axes.length!==0){if(r.axes.length!==r.starts.length||r.axes.length!==r.ends.length)throw new Error("axes, starts and ends must have the same length")}else if(r.starts.length!==r.ends.length)throw new Error("starts and ends must have the same length");e.slice(1).forEach((t,s)=>{if(e[s+1].dataType!==6&&e[s+1].dataType!==7)throw new Error(`Input ${s} must be an array of int32 or int64`)})},yo=(e,r)=>{let t=[];if(e.length>r)if(e[r].dataType===7)e[r].getBigInt64Array().forEach(s=>t.push(Number(s)));else if(e[r].dataType===6)e[r].getInt32Array().forEach(s=>t.push(Number(s)));else throw new Error(`Input ${r} must be an array of int32 or int64`);return t},Zf=(e,r)=>{if(e.length>1){let t=yo(e,1),s=yo(e,2),o=yo(e,3);return o.length===0&&(o=[...Array(e[0].dims.length).keys()]),St({starts:t,ends:s,axes:o})}else return r},Ql=(e,r,t,s,o)=>{let n=e;return e<0&&(n+=t[s[r]]),o[r]<0?Math.max(0,Math.min(n,t[s[r]]-1)):Math.max(0,Math.min(n,t[s[r]]))},eg=(e,r,t)=>`fn calculateInputIndices(output_indices: ${r.type.indices}) -> ${e.type.indices} { + var input_indices: ${e.type.indices}; + var carry = 0u; + for (var i = ${t.length}; i >= 0; i--) { + let input_shape_i = ${et("uniforms.input_shape","i",t.length)}; + let steps_i = ${et("uniforms.steps","i",t.length)}; + let signs_i = ${et("uniforms.signs","i",t.length)}; + let starts_i = ${et("uniforms.starts","i",t.length)}; + var output_index = ${r.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; + }`,tg=(e,r)=>{let t=e[0].dims,s=Me.size(t),o=r.axes.length>0?Me.normalizeAxes(r.axes,t.length):[...Array(t.length).keys()],n=yo(e,4);n.forEach(w=>w!==0||(()=>{throw new Error("step cannot be 0")})),n.length===0&&(n=Array(o.length).fill(1));let i=r.starts.map((w,g)=>Ql(w,g,t,o,n)),a=r.ends.map((w,g)=>Ql(w,g,t,o,n));if(o.length!==i.length||o.length!==a.length)throw new Error("start, ends and axes should have the same number of elements");if(o.length!==t.length)for(let w=0;wMath.sign(w));n.forEach((w,g,S)=>{if(w<0){let E=(a[g]-i[g])/w,y=i[g],M=y+E*n[g];i[g]=M,a[g]=y,S[g]=-w}});let u=t.slice(0);o.forEach((w,g)=>{u[w]=Math.ceil((a[w]-i[w])/n[w])});let p={dims:u,dataType:e[0].dataType},d=Ye("output",e[0].dataType,u.length),c=Pe("input",e[0].dataType,e[0].dims.length),f=Me.size(u),_=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:i.length},{name:"signs",type:"i32",length:l.length},{name:"steps",type:"u32",length:n.length}],T=[{type:12,data:f},{type:12,data:i},{type:6,data:l},{type:12,data:n},...st(e[0].dims,u)],k=w=>` + ${w.registerUniforms(_).declareVariables(c,d)} + ${eg(c,d,t)} + ${w.mainStart()} + ${w.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + let output_indices = ${d.offsetToIndices("global_idx")}; + let input_indices = calculateInputIndices(output_indices); + ${d.setByOffset("global_idx",c.getByIndices("input_indices"))} + }`;return{name:"Slice",shaderCache:{hint:`${l.length}_${i.length}_${n.length}`,inputDependencies:["rank"]},getShaderSource:k,getRunData:()=>({outputs:[p],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:T})}},rg=(e,r)=>{Yf(e.inputs,r);let t=Zf(e.inputs,r);e.compute(tg(e.inputs,t),{inputs:[0]})},sg=e=>{let r=e.starts,t=e.ends,s=e.axes;return St({starts:r,ends:t,axes:s})}}),ng,og,ig,ag,lx=Be(()=>{ut(),mt(),Xt(),zs(),ft(),ng=e=>{if(!e||e.length!==1)throw new Error("Softmax op requires 1 input.")},og=(e,r)=>{let t=e.inputs[0],s=t.dims,o=Me.size(s),n=s.length,i=Me.normalizeAxis(r.axis,n),a=iC),u[i]=n-1,u[n-1]=i,l=e.compute(Lr(t,u),{inputs:[t],outputs:[-1]})[0]):l=t;let p=l.dims,d=p[n-1],c=o/d,f=Kt(d),_=d/f,T=64;c===1&&(T=256);let k=(v,C)=>C===4?`max(max(${v}.x, ${v}.y), max(${v}.z, ${v}.w))`:C===2?`max(${v}.x, ${v}.y)`:C===3?`max(max(${v}.x, ${v}.y), ${v}.z)`:v,w=Pe("x",l.dataType,l.dims,f),g=Ye("result",l.dataType,l.dims,f),S=w.type.value,E=lr(l.dataType)==="f32"?`var threadMax = ${S}(-3.402823e+38f);`:`var threadMax = ${S}(-65504.0h);`,y=v=>` + var rowMaxShared : ${S}; + var rowSumShared : ${S}; + var threadShared : array<${S}, ${T}>; + + fn getValue(row: i32, col: i32, row_stride: i32) -> ${S} { + let index = row * row_stride + col; + return x[index]; + } + + fn setValue(row: i32, col: i32, row_stride: i32, value: ${S}) { + let index = row * row_stride + col; + result[index] = value; + } + ${v.registerUniform("packedCols","i32").declareVariables(w,g)} + ${v.mainStart(T)} + let gindex = i32(global_idx); + let lindex = i32(local_idx); + const wg = ${T}; + let row = gindex / wg; + let cols = uniforms.packedCols; + let row_stride : i32 = uniforms.packedCols; + + // find the rows max + ${E} + 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 = ${S}(${k("threadShared[0]",f)}); + } + workgroupBarrier(); + + // find the rows sum + var threadSum = ${S}(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 = ${S}(${Ls("threadShared[0]",f)}); + } + 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); + } + }`,M=e.compute({name:"Softmax",shaderCache:{hint:`${f};${T}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:p,dataType:l.dataType}],dispatchGroup:{x:c},programUniforms:[{type:6,data:_}]}),getShaderSource:y},{inputs:[l],outputs:[a?-1:0]})[0];a&&e.compute(Lr(M,u),{inputs:[M]})},ig=(e,r)=>{ng(e.inputs),og(e,r)},ag=e=>St({axis:e.axis})}),Jl,lg,ug,dg,cg,ux=Be(()=>{ut(),mt(),ft(),Jl=e=>Array.from(e.getBigInt64Array(),Number),lg=e=>{if(!e||e.length!==2)throw new Error("Tile requires 2 inputs.");if(e[0].dataType!==1&&e[0].dataType!==10&&e[0].dataType!==6&&e[0].dataType!==12)throw new Error("Tile only support float, float16, 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(Jl(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")},ug=(e,r)=>{let t=[];for(let s=0;s{let t=e[0].dims,s=r??Jl(e[1]),o=ug(t,s),n=Me.size(o),i=e[0].dataType,a=Pe("input",i,t.length),l=Ye("output",i,o.length),u=p=>` + const inputShape = ${a.indices(...t)}; + ${p.registerUniform("output_size","u32").declareVariables(a,l)} + ${p.mainStart()} + ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let output_indices = ${l.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 = ${l.indicesGet("output_indices","i")} % input_dim_i; + + ${a.indicesSet("input_indices","i","input_dim_value")} + } + ${l.setByOffset("global_idx",a.getByIndices("input_indices"))} + }`;return{name:"Tile",shaderCache:{hint:`${s}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:[{type:12,data:n},...st(e[0].dims,o)]}),getShaderSource:u}},cg=e=>{lg(e.inputs),e.compute(dg(e.inputs),{inputs:[0]})}}),pg,hg,mg,dx=Be(()=>{ut(),mt(),ft(),pg=(e,r,t,s,o)=>{let n=Ye("output_data",o,t.length,4),i=Pe("a_data",r[1].dataType,r[1].dims.length,4),a=Pe("b_data",r[2].dataType,r[2].dims.length,4),l=Pe("c_data",r[0].dataType,r[0].dims.length,4),u,p=(d,c,f)=>`select(${c}, ${d}, ${f})`;if(!s)u=n.setByOffset("global_idx",p(i.getByOffset("global_idx"),a.getByOffset("global_idx"),l.getByOffset("global_idx")));else{let d=(c,f,_="")=>{let T=`a_data[index_a${f}][component_a${f}]`,k=`b_data[index_b${f}][component_b${f}]`,w=`bool(c_data[index_c${f}] & (0xffu << (component_c${f} * 8)))`;return` + let output_indices${f} = ${n.offsetToIndices(`global_idx * 4u + ${f}u`)}; + let offset_a${f} = ${i.broadcastedIndicesToOffset(`output_indices${f}`,n)}; + let offset_b${f} = ${a.broadcastedIndicesToOffset(`output_indices${f}`,n)}; + let offset_c${f} = ${l.broadcastedIndicesToOffset(`output_indices${f}`,n)}; + let index_a${f} = offset_a${f} / 4u; + let index_b${f} = offset_b${f} / 4u; + let index_c${f} = offset_c${f} / 4u; + let component_a${f} = offset_a${f} % 4u; + let component_b${f} = offset_b${f} % 4u; + let component_c${f} = offset_c${f} % 4u; + ${c}[${f}] = ${_}(${p(T,k,w)}); + `};o===9?u=` + var data = vec4(0); + ${d("data",0,"u32")} + ${d("data",1,"u32")} + ${d("data",2,"u32")} + ${d("data",3,"u32")} + output_data[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:u=` + ${d("output_data[global_idx]",0)} + ${d("output_data[global_idx]",1)} + ${d("output_data[global_idx]",2)} + ${d("output_data[global_idx]",3)} + `}return` + ${e.registerUniform("vec_size","u32").declareVariables(l,i,a,n)} + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${u} + }`},hg=e=>{let r=e[1].dims,t=e[2].dims,s=e[0].dims,o=e[1].dataType,n=!(Me.areEqual(r,t)&&Me.areEqual(t,s)),i=r,a=Me.size(r);if(n){let u=Nn.calcShape(Nn.calcShape(r,t,!1),s,!1);if(!u)throw new Error("Can't perform where op on the given tensors");i=u,a=Me.size(i)}let l=Math.ceil(a/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:u=>pg(u,e,i,n,o),getRunData:()=>({outputs:[{dims:i,dataType:o}],dispatchGroup:{x:Math.ceil(a/64/4)},programUniforms:[{type:12,data:l},...st(s,r,t,i)]})}},mg=e=>{e.compute(hg(e.inputs))}}),_g,cx=Be(()=>{Ev(),cl(),Pv(),Cv(),Sv(),$v(),kv(),Dv(),zv(),Bv(),Rv(),jv(),Nv(),Vv(),Uv(),Wv(),Gv(),Kv(),Hv(),qv(),Xv(),Qv(),Jv(),Yv(),Zv(),P_(),ex(),tx(),rx(),sx(),nx(),ll(),ox(),L_(),ix(),ax(),lx(),F_(),ux(),zs(),_l(),dx(),_g=new Map([["Abs",[qp]],["Acos",[Xp]],["Acosh",[Qp]],["Add",[zh]],["ArgMax",[Fp,dl]],["ArgMin",[Ap,dl]],["Asin",[Jp]],["Asinh",[Yp]],["Atan",[Zp]],["Atanh",[eh]],["Attention",[Rp]],["AveragePool",[hf,pf]],["BatchNormalization",[Up]],["BiasAdd",[Kp]],["BiasSplitGelu",[Oh]],["Cast",[rh,th]],["Ceil",[oh]],["Clip",[nh]],["Concat",[Jh,Yh]],["Conv",[Sl,Pl]],["ConvTranspose",[Em,vm]],["Cos",[ih]],["Cosh",[ah]],["CumSum",[Cm,Sm]],["DepthToSpace",[Am,Fm]],["DequantizeLinear",[vf,xf]],["Div",[Bh]],["Einsum",[Rm,jm]],["Elu",[lh,_o]],["Equal",[Rh]],["Erf",[uh]],["Exp",[dh]],["Expand",[Wm]],["FastGelu",[Km]],["Floor",[ch]],["FusedConv",[Sl,Pl]],["Gather",[Qm,Xm]],["GatherElements",[a_,i_]],["GatherBlockQuantized",[r_,s_]],["GatherND",[Ym,Zm]],["Gelu",[ph]],["Gemm",[c_,d_]],["GlobalAveragePool",[_f,mf]],["GlobalMaxPool",[Mf,wf]],["Greater",[Uh]],["GreaterOrEqual",[Gh]],["GridSample",[b_,y_]],["GroupQueryAttention",[j_]],["HardSigmoid",[bh,Mh]],["InstanceNormalization",[U_]],["LayerNormalization",[K_]],["LeakyRelu",[hh,_o]],["Less",[Wh]],["LessOrEqual",[Kh]],["Log",[Sh]],["MatMul",[q_]],["MatMulNBits",[Y_,Z_]],["MaxPool",[ff,gf]],["Mul",[jh]],["MultiHeadAttention",[E_,x_]],["Neg",[_h]],["Not",[mh]],["Pad",[uf]],["Pow",[Nh]],["QuickGelu",[Ih,_o]],["Range",[Pf]],["Reciprocal",[fh]],["ReduceMin",[Cp]],["ReduceMean",[vp]],["ReduceMax",[Pp]],["ReduceSum",[$p]],["ReduceProd",[Sp]],["ReduceL1",[xp]],["ReduceL2",[Tp]],["ReduceLogSum",[Ip]],["ReduceLogSumExp",[Ep]],["ReduceSumSquare",[kp]],["Relu",[gh]],["Resize",[Hf,qf]],["RotaryEmbedding",[D_]],["ScatterND",[kf,$f]],["Sigmoid",[wh]],["Sin",[yh]],["Sinh",[vh]],["Slice",[rg,sg]],["SkipLayerNormalization",[Jf]],["Split",[I_,A_]],["Sqrt",[xh]],["Softmax",[ig,ag]],["Sub",[Vh]],["Tan",[Th]],["Tanh",[Eh]],["ThresholdedRelu",[Ch,_o]],["Tile",[cg]],["Transpose",[Uc,Wc]],["Where",[mg]]])}),fg,px=Be(()=>{ts(),Es(),ft(),fg=class{constructor(e){this.backend=e,this.repo=new Map,this.attributesBound=!1}getArtifact(e){return this.repo.get(e)}setArtifact(e,r){this.repo.set(e,r)}run(e,r,t,s,o){es(e.programInfo.name);let n=this.backend.device,i=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let a=[];for(let u of r)a.push({binding:a.length,resource:{buffer:u.buffer}});for(let u of t)a.push({binding:a.length,resource:{buffer:u.buffer}});o&&a.push({binding:a.length,resource:o});let l=n.createBindGroup({layout:e.computePipeline.getBindGroupLayout(0),entries:a,label:e.programInfo.name});if(this.backend.sessionStatus==="capturing"){let u={kernelId:this.backend.currentKernelId,computePipeline:e.computePipeline,bindGroup:l,dispatchGroup:s};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(u)}i.setPipeline(e.computePipeline),i.setBindGroup(0,l),i.dispatchWorkgroups(...s),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(),Gr(e.programInfo.name)}dispose(){}build(e,r){es(e.name);let t=this.backend.device,s=[];[{feature:"shader-f16",extension:"f16"},{feature:"subgroups",extension:"subgroups"}].forEach(u=>{t.features.has(u.feature)&&s.push(`enable ${u.extension};`)});let o=zc(r,this.backend.device.limits),n=e.getShaderSource(o),i=`${s.join(` +`)} +${o.additionalImplementations} +${n}`,a=t.createShaderModule({code:i,label:e.name});vt("verbose",()=>`[WebGPU] ${e.name} shader code: ${i}`);let l=t.createComputePipeline({compute:{module:a,entryPoint:"main"},layout:"auto",label:e.name});return Gr(e.name),{programInfo:e,computePipeline:l,uniformVariablesInfo:o.variablesInfo}}normalizeDispatchGroupSize(e){let r=typeof e=="number"?e:e.x,t=typeof e=="number"?1:e.y||1,s=typeof e=="number"?1:e.z||1,o=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(r<=o&&t<=o&&s<=o)return[r,t,s];let n=r*t*s,i=Math.ceil(Math.sqrt(n));if(i>o){if(i=Math.ceil(Math.cbrt(n)),i>o)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[i,i,i]}else return[i,i,1]}}}),gg={};Rn(gg,{WebGpuBackend:()=>yg});var wg,Mg,bg,yg,hx=Be(()=>{ts(),ut(),Es(),xc(),xv(),cx(),px(),wg=(e,r)=>{if(r.length!==e.length)throw new Error(`inputDependencies length ${r.length} is not equal to inputTensors length ${e.length}.`);let t=[];for(let s=0;s{var o,n;let s=e.name;return(o=e.shaderCache)!=null&&o.hint&&(s+="["+e.shaderCache.hint+"]"),s+=":"+t+`:${wg(r,((n=e.shaderCache)==null?void 0:n.inputDependencies)??new Array(r.length).fill("dims"))}`,s},bg=class{constructor(e){e&&(this.architecture=e.architecture,this.vendor=e.vendor)}isArchitecture(e){return this.architecture===e}isVendor(e){return this.vendor===e}},yg=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,r){this.env=e;let t=[],s={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:t},o=n=>r.features.has(n)&&t.push(n)&&!0;o("chromium-experimental-timestamp-query-inside-passes")||o("timestamp-query"),o("shader-f16"),o("subgroups"),this.device=await r.requestDevice(s),this.adapterInfo=new bg(r.info||await r.requestAdapterInfo()),this.gpuDataManager=Fc(this),this.programManager=new fg(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,Ka(e.logLevel,!!e.debug),this.device.onuncapturederror=n=>{n.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${n.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 e=this.getCommandEncoder(),r={};this.queryType==="at-passes"&&(r.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=e.beginComputePass(r)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;es(),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 s;let r=new BigUint64Array(e.getMappedRange()),t=this.pendingQueries.get(e);for(let o=0;o"u"&&(this.queryTimeBase=f);let T=Number(f-this.queryTimeBase),k=Number(_-this.queryTimeBase);if(!Number.isSafeInteger(T)||!Number.isSafeInteger(k))throw new RangeError("incorrect timestamp range");if((s=this.env.webgpu.profiling)!=null&&s.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:d.map(w=>({dims:w.dims,dataType:Ts(w.dataType)})),outputsMetadata:c.map(w=>({dims:w.dims,dataType:Ts(w.dataType)})),kernelId:i,kernelType:l,kernelName:u,programName:p,startTime:T,endTime:k});else{let w="";d.forEach((S,E)=>{w+=`input[${E}]: [${S.dims}] | ${Ts(S.dataType)}, `});let g="";c.forEach((S,E)=>{g+=`output[${E}]: [${S.dims}] | ${Ts(S.dataType)}, `}),console.log(`[profiling] kernel "${i}|${l}|${u}|${p}" ${w}${g}execution time: ${k-T} ns`)}uo("GPU",`${p}::${f}::${_}`)}e.unmap(),this.pendingQueries.delete(e)}),Gr()}run(e,r,t,s,o,n){es(e.name);let i=[];for(let g=0;gS):t;if(p.length!==a.length)throw new Error(`Output size ${p.length} must be equal to ${a.length}.`);let d=[],c=[];for(let g=0;g=n)throw new Error(`Invalid output index: ${p[g]}`);if(p[g]===-3)continue;let S=p[g]===-1,E=p[g]===-2,y=S||E?o(a[g].dataType,a[g].dims):s(p[g],a[g].dataType,a[g].dims);if(d.push(y),y.data===0)continue;let M=this.gpuDataManager.get(y.data);if(!M)throw new Error(`no GPU data for output: ${y.data}`);if(S&&this.temporaryData.push(M),E){let v=this.kernelPersistentData.get(this.currentKernelId);v||(v=[],this.kernelPersistentData.set(this.currentKernelId,v)),v.push(M)}c.push(M)}if(i.length!==r.length||c.length!==d.length){if(c.length===0)return Gr(e.name),d;throw new Error(`Program ${e.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let f;if(u){let g=0,S=[];u.forEach(v=>{let C=typeof v.data=="number"?[v.data]:v.data;if(C.length===0)return;let A=v.type===10?2:4,B,K;v.type===10?(K=C.length>4?16:C.length>2?8:C.length*A,B=C.length>4?16:A*C.length):(K=C.length<=2?C.length*A:16,B=16),g=Math.ceil(g/K)*K,S.push(g);let G=v.type===10?8:4;g+=C.length>4?Math.ceil(C.length/G)*B:C.length*A});let E=16;g=Math.ceil(g/E)*E;let y=new ArrayBuffer(g);u.forEach((v,C)=>{let A=S[C],B=typeof v.data=="number"?[v.data]:v.data;if(v.type===6)new Int32Array(y,A,B.length).set(B);else if(v.type===12)new Uint32Array(y,A,B.length).set(B);else if(v.type===10)new Uint16Array(y,A,B.length).set(B);else if(v.type===1)new Float32Array(y,A,B.length).set(B);else throw new Error(`Unsupported uniform type: ${Ts(v.type)}`)});let M=this.gpuDataManager.create(g,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(M.buffer,0,y,0,g),this.gpuDataManager.release(M.id),f={offset:0,size:g,buffer:M.buffer}}let _=this.programManager.normalizeDispatchGroupSize(l),T=_[1]===1&&_[2]===1,k=Mg(e,r,T),w=this.programManager.getArtifact(k);if(w||(w=this.programManager.build(e,_),this.programManager.setArtifact(k,w),vt("info",()=>`[artifact] key: ${k}, programName: ${e.name}`)),u&&w.uniformVariablesInfo){if(u.length!==w.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${w.uniformVariablesInfo.length}, got ${u.length} in program "${w.programInfo.name}".`);for(let g=0;g`[ProgramManager] run "${e.name}" (key=${k}) with ${_[0]}x${_[1]}x${_[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let g={kernelId:this.currentKernelId,programName:w.programInfo.name,inputTensorViews:r,outputTensorViews:d};this.pendingKernels.push(g),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(g)}return this.programManager.run(w,i,c,_,f),Gr(e.name),d}upload(e,r){this.gpuDataManager.upload(e,r)}memcpy(e,r){this.gpuDataManager.memcpy(e,r)}async download(e,r){await this.gpuDataManager.download(e,r)}alloc(e){return this.gpuDataManager.create(e).id}free(e){return this.gpuDataManager.release(e)}createKernel(e,r,t,s){let o=_g.get(e);if(!o)throw new Error(`kernel not implemented: ${e}`);let n={kernelType:e,kernelName:s,kernelEntry:o[0],attributes:[o[1],t]};this.kernels.set(r,n)}releaseKernel(e){let r=this.kernelPersistentData.get(e);if(r){for(let t of r)this.gpuDataManager.release(t.id);this.kernelPersistentData.delete(e)}this.kernelCustomData.delete(e),this.kernels.delete(e)}computeKernel(e,r,t){let s=this.kernels.get(e);if(!s)throw new Error(`kernel not created: ${e}`);let o=s.kernelType,n=s.kernelName,i=s.kernelEntry,a=s.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${o}] ${n}" is not allowed to be called recursively`);this.currentKernelId=e,a[0]&&(a[1]=a[0](a[1]),a[0]=void 0),vt("info",()=>`[WebGPU] Start to run kernel "[${o}] ${n}"...`);let l=this.env.debug;this.temporaryData=[];try{return l&&this.device.pushErrorScope("validation"),i(r,a[1]),0}catch(u){return t.push(Promise.resolve(`[WebGPU] Kernel "[${o}] ${n}" failed. ${u}`)),1}finally{l&&t.push(this.device.popErrorScope().then(u=>u?`GPU validation error for kernel "[${o}] ${n}": ${u.message}`:null));for(let u of this.temporaryData)this.gpuDataManager.release(u.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(e,r,t,s){let o=this.sessionExternalDataMapping.get(e);o||(o=new Map,this.sessionExternalDataMapping.set(e,o));let n=o.get(r),i=this.gpuDataManager.registerExternalBuffer(t,s,n);return o.set(r,[i,t]),i}unregisterBuffers(e){let r=this.sessionExternalDataMapping.get(e);r&&(r.forEach(t=>this.gpuDataManager.unregisterExternalBuffer(t[0])),this.sessionExternalDataMapping.delete(e))}getBuffer(e){let r=this.gpuDataManager.get(e);if(!r)throw new Error(`no GPU data for buffer: ${e}`);return r.buffer}createDownloader(e,r,t){return async()=>{let s=await sl(this,e,r);return Ha(s.buffer,t)}}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(){vt("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(){vt("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){vt("info","replay"),this.sessionStatus="replaying";let e=this.capturedCommandList.get(this.currentSessionId),r=this.capturedPendingKernels.get(this.currentSessionId),t=e.length;this.pendingKernels=[];for(let s=0;s=this.maxDispatchNumber||this.queryType==="at-passes")&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus="default"}onCreateSession(){this.gpuDataManager.onCreateSession()}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()}}}),vg={};Rn(vg,{init:()=>Tg});var gi,xg,Tg,mx=Be(()=>{ut(),Es(),mt(),vv(),gi=class z0{constructor(r,t,s,o){this.module=r,this.dataType=t,this.data=s,this.dims=o}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let r=Me.size(this.dims);return r===0?new Float32Array:new Float32Array(this.module.HEAP8.buffer,this.data,r)}getBigInt64Array(){if(this.dataType!==7)throw new Error("Invalid data type");let r=Me.size(this.dims);return r===0?new BigInt64Array:new BigInt64Array(this.module.HEAP8.buffer,this.data,r)}getInt32Array(){if(this.dataType!==6)throw new Error("Invalid data type");let r=Me.size(this.dims);return r===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,r)}getUint16Array(){if(this.dataType!==10&&this.dataType!==4)throw new Error("Invalid data type");let r=Me.size(this.dims);return r===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,r)}reshape(r){if(Me.size(r)!==Me.size(this.dims))throw new Error("Invalid new shape");return new z0(this.module,this.dataType,this.data,r)}},xg=class{constructor(e,r,t){this.module=e,this.backend=r,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=r.adapterInfo;let s=e.PTR_SIZE,o=t/e.PTR_SIZE,n=s===4?"i32":"i64";this.opKernelContext=Number(e.getValue(s*o++,n));let i=Number(e.getValue(s*o++,n));this.outputCount=Number(e.getValue(s*o++,n)),this.customDataOffset=Number(e.getValue(s*o++,"*")),this.customDataSize=Number(e.getValue(s*o++,n));let a=[];for(let l=0;ltypeof a=="number"?this.inputs[a]:a))??this.inputs,s=(r==null?void 0:r.outputs)??[],o=(a,l,u)=>new gi(this.module,l,this.output(a,u),u),n=(a,l)=>{let u=tn(a,l);if(!u)throw new Error(`Unsupported data type: ${a}`);let p=u>0?this.backend.gpuDataManager.create(u).id:0;return new gi(this.module,a,p,l)};return this.backend.run(e,t,s,o,n,this.outputCount)}output(e,r){let t=this.module.stackSave();try{let s=this.module.PTR_SIZE,o=s===4?"i32":"i64",n=this.module.stackAlloc((1+r.length)*s);this.module.setValue(n,r.length,o);for(let i=0;i{let o=r.jsepInit;if(!o)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(e==="webgpu"){let n=(hx(),io(gg)).WebGpuBackend,i=new n;await i.initialize(t,s),o("webgpu",[i,a=>i.alloc(Number(a)),a=>i.free(a),(a,l,u,p=!1)=>{if(p)vt("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${Number(a)}, dst=${Number(l)}, size=${Number(u)}`),i.memcpy(Number(a),Number(l));else{vt("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(a)}, gpuDataId=${Number(l)}, size=${Number(u)}`);let d=r.HEAPU8.subarray(Number(a>>>0),Number(a>>>0)+Number(u));i.upload(Number(l),d)}},async(a,l,u)=>{vt("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${a}, dataOffset=${l}, size=${u}`),await i.download(Number(a),()=>r.HEAPU8.subarray(Number(l)>>>0,Number(l+u)>>>0))},(a,l,u)=>i.createKernel(a,Number(l),u,r.UTF8ToString(r._JsepGetNodeName(Number(l)))),a=>i.releaseKernel(a),(a,l,u,p)=>{vt("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${u}, kernel=${a}, contextDataOffset=${l}`);let d=new xg(r,i,Number(l));return i.computeKernel(Number(a),d,p)},()=>i.captureBegin(),()=>i.captureEnd(),()=>i.replay()])}else{let n=new $c(t);o("webnn",[n,()=>n.reserveTensorId(),i=>n.releaseTensorId(i),async(i,a,l,u,p)=>n.ensureTensor(i,a,l,u,p),(i,a)=>{n.uploadTensor(i,a)},async(i,a)=>n.downloadTensor(i,a)])}}}),Eg,Yl,Zl,Bs,Pg,eu,wi,tu,ru,su,nu,ou,iu,Cg=Be(()=>{Mv(),bv(),ut(),en(),ja(),hc(),Eg=(e,r)=>{zt()._OrtInit(e,r)!==0&&At("Can't initialize onnxruntime.")},Yl=async e=>{Eg(e.wasm.numThreads,si(e.logLevel))},Zl=async(e,r)=>{var t,s;(s=(t=zt()).asyncInit)==null||s.call(t);{let o=(mx(),io(vg)).init;if(r==="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 a=e.webgpu.forceFallbackAdapter;if(a!==void 0&&typeof a!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${a}"`);if(n=await navigator.gpu.requestAdapter({powerPreference:i,forceFallbackAdapter:a}),!n)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}await o("webgpu",zt(),e,n)}if(r==="webnn"){if(typeof navigator>"u"||!navigator.ml)throw new Error("WebNN is not supported in current environment");await o("webnn",zt(),e)}}},Bs=new Map,Pg=e=>{let r=zt(),t=r.stackSave();try{let s=r.PTR_SIZE,o=r.stackAlloc(2*s);r._OrtGetInputOutputCount(e,o,o+s)!==0&&At("Can't get session input/output count.");let n=s===4?"i32":"i64";return[Number(r.getValue(o,n)),Number(r.getValue(o+s,n))]}finally{r.stackRestore(t)}},eu=(e,r)=>{let t=zt(),s=t.stackSave(),o=0;try{let n=t.PTR_SIZE,i=t.stackAlloc(2*n);t._OrtGetInputOutputMetadata(e,r,i,i+n)!==0&&At("Can't get session input/output metadata.");let a=Number(t.getValue(i,"*"));o=Number(t.getValue(i+n,"*"));let l=t.HEAP32[o/4];if(l===0)return[a,0];let u=t.HEAPU32[o/4+1],p=[];for(let d=0;d{let r=zt(),t=r._malloc(e.byteLength);if(t===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return r.HEAPU8.set(e,t),[t,e.byteLength]},tu=async(e,r)=>{var d,c,f,_;let t,s,o=zt();Array.isArray(e)?[t,s]=e:e.buffer===o.HEAPU8.buffer?[t,s]=[e.byteOffset,e.byteLength]:[t,s]=wi(e);let n=0,i=0,a=0,l=[],u=[],p=[];try{if([i,l]=await pc(r),(r==null?void 0:r.externalData)&&o.mountExternalData){let C=[];for(let A of r.externalData){let B=typeof A=="string"?A:A.path;C.push(Ga(typeof A=="string"?A:A.data).then(K=>{o.mountExternalData(B,K)}))}await Promise.all(C)}for(let C of(r==null?void 0:r.executionProviders)??[])if((typeof C=="string"?C:C.name)==="webnn"){if(o.shouldTransferToMLTensor=!1,typeof C!="string"){let A=C,B=A==null?void 0:A.context,K=A==null?void 0:A.gpuDevice,G=A==null?void 0:A.deviceType,j=A==null?void 0:A.powerPreference;B?o.currentContext=B:K?o.currentContext=await o.webnnCreateMLContext(K):o.currentContext=await o.webnnCreateMLContext({deviceType:G,powerPreference:j})}else o.currentContext=await o.webnnCreateMLContext();break}n=await o._OrtCreateSession(t,s,i),(d=o.webgpuOnCreateSession)==null||d.call(o,n),n===0&&At("Can't create a session."),(c=o.jsepOnCreateSession)==null||c.call(o),o.currentContext&&(o.webnnRegisterMLContext(n,o.currentContext),o.currentContext=void 0,o.shouldTransferToMLTensor=!0);let[T,k]=Pg(n),w=!!(r!=null&&r.enableGraphCapture),g=[],S=[],E=[],y=[],M=[];for(let C=0;CC==="gpu-buffer"||C==="ml-tensor")&&(a=o._OrtCreateBinding(n),a===0&&At("Can't create IO binding."),v={handle:a,outputPreferredLocations:M,outputPreferredLocationsEncoded:M.map(C=>Wa(C))}),Bs.set(n,[n,u,p,v,w,!1]),[n,g,S,E,y]}catch(T){throw u.forEach(k=>o._OrtFree(k)),p.forEach(k=>o._OrtFree(k)),a!==0&&o._OrtReleaseBinding(a)!==0&&At("Can't release IO binding."),n!==0&&o._OrtReleaseSession(n)!==0&&At("Can't release session."),T}finally{o._free(t),i!==0&&o._OrtReleaseSessionOptions(i)!==0&&At("Can't release session options."),l.forEach(T=>o._free(T)),(_=o.unmountExternalData)==null||_.call(o)}},ru=e=>{var l,u,p;let r=zt(),t=Bs.get(e);if(!t)throw new Error(`cannot release session. invalid session id: ${e}`);let[s,o,n,i,a]=t;i&&(a&&r._OrtClearBoundOutputs(i.handle)!==0&&At("Can't clear bound outputs."),r._OrtReleaseBinding(i.handle)!==0&&At("Can't release IO binding.")),(l=r.jsepOnReleaseSession)==null||l.call(r,e),(u=r.webnnOnReleaseSession)==null||u.call(r,e),(p=r.webgpuOnReleaseSession)==null||p.call(r,e),o.forEach(d=>r._OrtFree(d)),n.forEach(d=>r._OrtFree(d)),r._OrtReleaseSession(s)!==0&&At("Can't release session."),Bs.delete(e)},su=async(e,r,t,s,o,n,i=!1)=>{if(!e){r.push(0);return}let a=zt(),l=a.PTR_SIZE,u=e[0],p=e[1],d=e[3],c=d,f,_;if(u==="string"&&(d==="gpu-buffer"||d==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(i&&d!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${n} when enableGraphCapture is true.`);if(d==="gpu-buffer"){let w=e[2].gpuBuffer;_=tn(jn(u),p);{let g=a.jsepRegisterBuffer;if(!g)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');f=g(s,n,w,_)}}else if(d==="ml-tensor"){let w=e[2].mlTensor;_=tn(jn(u),p);let g=a.webnnRegisterMLTensor;if(!g)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');f=g(s,w,jn(u),p)}else{let w=e[2];if(Array.isArray(w)){_=l*w.length,f=a._malloc(_),t.push(f);for(let g=0;ga.setValue(k+S*l,g,l===4?"i32":"i64"));let w=a._OrtCreateTensor(jn(u),f,_,k,p.length,Wa(c));w===0&&At(`Can't create tensor for input/output. session=${s}, index=${n}.`),r.push(w)}finally{a.stackRestore(T)}},nu=async(e,r,t,s,o,n)=>{var K,G,j,ee;let i=zt(),a=i.PTR_SIZE,l=Bs.get(e);if(!l)throw new Error(`cannot run inference. invalid session id: ${e}`);let u=l[0],p=l[1],d=l[2],c=l[3],f=l[4],_=l[5],T=r.length,k=s.length,w=0,g=[],S=[],E=[],y=[],M=i.stackSave(),v=i.stackAlloc(T*a),C=i.stackAlloc(T*a),A=i.stackAlloc(k*a),B=i.stackAlloc(k*a);try{[w,g]=ac(n);for(let X=0;Xq*R,1);F=Ts(_e);let we=c==null?void 0:c.outputPreferredLocations[s[X]];if(F==="string"){if(we==="gpu-buffer"||we==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let q=[];for(let R=0;R0){let q=i.jsepGetBuffer;if(!q)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let R=q(W),pe=tn(_e,Ue);if(pe===void 0||!Va(F))throw new Error(`Unsupported data type: ${F}`);V=!0,Z.push([F,$e,{gpuBuffer:R,download:i.jsepCreateDownloader(R,pe,F),dispose:()=>{i._OrtReleaseTensor(oe)!==0&&At("Can't release tensor.")}},"gpu-buffer"])}else if(we==="ml-tensor"&&Ue>0){let q=i.webnnEnsureTensor,R=i.webnnIsInt64Supported;if(!q||!R)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(tn(_e,Ue)===void 0||!Ua(F))throw new Error(`Unsupported data type: ${F}`);if(F==="int64"&&!R(e))throw new Error('preferredLocation "ml-tensor" for int64 output is not supported by current WebNN Context.');let pe=await q(e,W,_e,$e,!1);V=!0,Z.push([F,$e,{mlTensor:pe,download:i.webnnCreateMLTensorDownloader(W,F),dispose:()=>{i.webnnReleaseTensorId(W),i._OrtReleaseTensor(oe)}},"ml-tensor"])}else{let q=Na(F),R=new q(Ue);new Uint8Array(R.buffer,R.byteOffset,R.byteLength).set(i.HEAPU8.subarray(W,W+R.byteLength)),Z.push([F,$e,R,"cpu"])}}finally{i.stackRestore(me),F==="string"&&W&&i._free(W),V||i._OrtReleaseTensor(oe),(ee=i.webnnOnRunEnd)==null||ee.call(i,u)}}return c&&!f&&(i._OrtClearBoundOutputs(c.handle)!==0&&At("Can't clear bound outputs."),Bs.set(e,[u,p,d,c,f,!1])),Z}finally{i.stackRestore(M),S.forEach(H=>i._OrtReleaseTensor(H)),E.forEach(H=>i._OrtReleaseTensor(H)),y.forEach(H=>i._free(H)),w!==0&&i._OrtReleaseRunOptions(w),g.forEach(H=>i._free(H))}},ou=e=>{let r=zt(),t=Bs.get(e);if(!t)throw new Error("invalid session id");let s=t[0],o=r._OrtEndProfiling(s);o===0&&At("Can't get an profile file name."),r._OrtFree(o)},iu=e=>{let r=[];for(let t of e){let s=t[2];!Array.isArray(s)&&"buffer"in s&&r.push(s.buffer)}return r}}),Rs,kr,Wn,vo,xo,Mi,au,bi,un,dn,Sg,$g,kg,Ig,Ag,Fg,Og,Dg,Lg=Be(()=>{ts(),Cg(),en(),La(),Rs=()=>!!Bt.wasm.proxy&&typeof document<"u",Wn=!1,vo=!1,xo=!1,bi=new Map,un=(e,r)=>{let t=bi.get(e);t?t.push(r):bi.set(e,[r])},dn=()=>{if(Wn||!vo||xo||!kr)throw new Error("worker not ready")},Sg=e=>{switch(e.data.type){case"init-wasm":Wn=!1,e.data.err?(xo=!0,au[1](e.data.err)):(vo=!0,au[0]()),Mi&&(URL.revokeObjectURL(Mi),Mi=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let r=bi.get(e.data.type);e.data.err?r.shift()[1](e.data.err):r.shift()[0](e.data.out);break}}},$g=async()=>{if(!vo){if(Wn)throw new Error("multiple calls to 'initWasm()' detected.");if(xo)throw new Error("previous call to 'initWasm()' failed.");if(Wn=!0,Rs())return new Promise((e,r)=>{kr==null||kr.terminate(),rc().then(([t,s])=>{try{kr=s,kr.onerror=n=>r(n),kr.onmessage=Sg,au=[e,r];let o={type:"init-wasm",in:Bt};!o.in.wasm.wasmPaths&&(t||Aa)&&(o.in.wasm.wasmPaths={wasm:new URL("/assets/ort-wasm-simd-threaded.jsep-B0T3yYHD.wasm",self.location.href).href}),kr.postMessage(o),Mi=t}catch(o){r(o)}},r)});try{await Ra(Bt.wasm),await Yl(Bt),vo=!0}catch(e){throw xo=!0,e}finally{Wn=!1}}},kg=async e=>{if(Rs())return dn(),new Promise((r,t)=>{un("init-ep",[r,t]);let s={type:"init-ep",in:{epName:e,env:Bt}};kr.postMessage(s)});await Zl(Bt,e)},Ig=async e=>Rs()?(dn(),new Promise((r,t)=>{un("copy-from",[r,t]);let s={type:"copy-from",in:{buffer:e}};kr.postMessage(s,[e.buffer])})):wi(e),Ag=async(e,r)=>{if(Rs()){if(r!=null&&r.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return dn(),new Promise((t,s)=>{un("create",[t,s]);let o={type:"create",in:{model:e,options:{...r}}},n=[];e instanceof Uint8Array&&n.push(e.buffer),kr.postMessage(o,n)})}else return tu(e,r)},Fg=async e=>{if(Rs())return dn(),new Promise((r,t)=>{un("release",[r,t]);let s={type:"release",in:e};kr.postMessage(s)});ru(e)},Og=async(e,r,t,s,o,n)=>{if(Rs()){if(t.some(i=>i[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(o.some(i=>i))throw new Error("pre-allocated output tensor is not supported for proxy.");return dn(),new Promise((i,a)=>{un("run",[i,a]);let l=t,u={type:"run",in:{sessionId:e,inputIndices:r,inputs:l,outputIndices:s,options:n}};kr.postMessage(u,iu(l))})}else return nu(e,r,t,s,o,n)},Dg=async e=>{if(Rs())return dn(),new Promise((r,t)=>{un("end-profiling",[r,t]);let s={type:"end-profiling",in:e};kr.postMessage(s)});ou(e)}}),lu,zg,Bg,_x=Be(()=>{ts(),Lg(),ut(),Pa(),hc(),lu=(e,r)=>{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"];case"ml-tensor":return[e.type,e.dims,{mlTensor:e.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${e.location} for ${r()}`)}},zg=e=>{switch(e[3]){case"cpu":return new Zr(e[0],e[2],e[1]);case"gpu-buffer":{let r=e[0];if(!Va(r))throw new Error(`not supported data type: ${r} for deserializing GPU tensor`);let{gpuBuffer:t,download:s,dispose:o}=e[2];return Zr.fromGpuBuffer(t,{dataType:r,dims:e[1],download:s,dispose:o})}case"ml-tensor":{let r=e[0];if(!Ua(r))throw new Error(`not supported data type: ${r} for deserializing MLTensor tensor`);let{mlTensor:t,download:s,dispose:o}=e[2];return Zr.fromMLTensor(t,{dataType:r,dims:e[1],download:s,dispose:o})}default:throw new Error(`invalid data location: ${e[3]}`)}},Bg=class{async fetchModelAndCopyToWasmMemory(e){return Ig(await Ga(e))}async loadModel(e,r){es();let t;typeof e=="string"?t=await this.fetchModelAndCopyToWasmMemory(e):t=e,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await Ag(t,r),Gr()}async dispose(){return Fg(this.sessionId)}async run(e,r,t){es();let s=[],o=[];Object.entries(e).forEach(d=>{let c=d[0],f=d[1],_=this.inputNames.indexOf(c);if(_===-1)throw new Error(`invalid input '${c}'`);s.push(f),o.push(_)});let n=[],i=[];Object.entries(r).forEach(d=>{let c=d[0],f=d[1],_=this.outputNames.indexOf(c);if(_===-1)throw new Error(`invalid output '${c}'`);n.push(f),i.push(_)});let a=s.map((d,c)=>lu(d,()=>`input "${this.inputNames[o[c]]}"`)),l=n.map((d,c)=>d?lu(d,()=>`output "${this.outputNames[i[c]]}"`):null),u=await Og(this.sessionId,o,a,i,l,t),p={};for(let d=0;ddu,initializeFlags:()=>uu,wasmBackend:()=>jg});var uu,du,jg,fx=Be(()=>{ts(),Lg(),_x(),uu=()=>{(typeof Bt.wasm.initTimeout!="number"||Bt.wasm.initTimeout<0)&&(Bt.wasm.initTimeout=0);let e=Bt.wasm.simd;if(typeof e!="boolean"&&e!==void 0&&e!=="fixed"&&e!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${e}". Reset it to \`false\` and ignore SIMD feature checking.`),Bt.wasm.simd=!1),typeof Bt.wasm.proxy!="boolean"&&(Bt.wasm.proxy=!1),typeof Bt.wasm.trace!="boolean"&&(Bt.wasm.trace=!1),typeof Bt.wasm.numThreads!="number"||!Number.isInteger(Bt.wasm.numThreads)||Bt.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)Bt.wasm.numThreads=1;else{let r=typeof navigator>"u"?rv("node:os").cpus().length:navigator.hardwareConcurrency;Bt.wasm.numThreads=Math.min(4,Math.ceil((r||1)/2))}},du=class{async init(e){uu(),await $g(),await kg(e)}async createInferenceSessionHandler(e,r){let t=new Bg;return await t.loadModel(e,r),t}},jg=new du});ts(),ts(),ts();var gx="1.22.0-dev.20250409-89f8206ba4",wx=Gd;{let e=(fx(),io(Rg)).wasmBackend;Ys("webgpu",e,5),Ys("webnn",e,5),Ys("cpu",e,10),Ys("wasm",e,10)}Object.defineProperty(Bt.versions,"web",{value:gx,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. + * ============================================================================= + */var Mx=Object.freeze({__proto__:null,get InferenceSession(){return Ea},get TRACE(){return uo},get TRACE_FUNC_BEGIN(){return es},get TRACE_FUNC_END(){return Gr},get Tensor(){return Zr},default:wx,get env(){return Bt},get registerBackend(){return Ys}}),Cs={},bx={"onnxruntime-common":e=>{e.exports=Y0},"onnxruntime-web":e=>{e.exports=Mx},"?2ce3":()=>{},"?7a2c":()=>{},"?a42a":()=>{},"?2b25":()=>{},"?569f":()=>{},"?3f59":()=>{},"?154a":()=>{},"./node_modules/@huggingface/jinja/dist/index.js":(e,r,t)=>{t.r(r),t.d(r,{Environment:()=>Se,Interpreter:()=>Ae,Template:()=>Ve,parse:()=>V,tokenize:()=>d});var s=Object.freeze({Text:"Text",NumericLiteral:"NumericLiteral",BooleanLiteral:"BooleanLiteral",NullLiteral:"NullLiteral",StringLiteral:"StringLiteral",Identifier:"Identifier",Equals:"Equals",OpenParen:"OpenParen",CloseParen:"CloseParen",OpenStatement:"OpenStatement",CloseStatement:"CloseStatement",OpenExpression:"OpenExpression",CloseExpression:"CloseExpression",OpenSquareBracket:"OpenSquareBracket",CloseSquareBracket:"CloseSquareBracket",OpenCurlyBracket:"OpenCurlyBracket",CloseCurlyBracket:"CloseCurlyBracket",Comma:"Comma",Dot:"Dot",Colon:"Colon",Pipe:"Pipe",CallOperator:"CallOperator",AdditiveBinaryOperator:"AdditiveBinaryOperator",MultiplicativeBinaryOperator:"MultiplicativeBinaryOperator",ComparisonBinaryOperator:"ComparisonBinaryOperator",UnaryOperator:"UnaryOperator",Set:"Set",If:"If",For:"For",In:"In",Is:"Is",NotIn:"NotIn",Else:"Else",EndSet:"EndSet",EndIf:"EndIf",ElseIf:"ElseIf",EndFor:"EndFor",And:"And",Or:"Or",Not:"UnaryOperator",Macro:"Macro",EndMacro:"EndMacro"}),o=Object.freeze({set:s.Set,for:s.For,in:s.In,is:s.Is,if:s.If,else:s.Else,endset:s.EndSet,endif:s.EndIf,elif:s.ElseIf,endfor:s.EndFor,and:s.And,or:s.Or,not:s.Not,"not in":s.NotIn,macro:s.Macro,endmacro:s.EndMacro,true:s.BooleanLiteral,false:s.BooleanLiteral,none:s.NullLiteral,True:s.BooleanLiteral,False:s.BooleanLiteral,None:s.NullLiteral}),n=class{constructor(O,Y){this.value=O,this.type=Y}};function i(O){return/\w/.test(O)}function a(O){return/[0-9]/.test(O)}var l=[["{%",s.OpenStatement],["%}",s.CloseStatement],["{{",s.OpenExpression],["}}",s.CloseExpression],["(",s.OpenParen],[")",s.CloseParen],["{",s.OpenCurlyBracket],["}",s.CloseCurlyBracket],["[",s.OpenSquareBracket],["]",s.CloseSquareBracket],[",",s.Comma],[".",s.Dot],[":",s.Colon],["|",s.Pipe],["<=",s.ComparisonBinaryOperator],[">=",s.ComparisonBinaryOperator],["==",s.ComparisonBinaryOperator],["!=",s.ComparisonBinaryOperator],["<",s.ComparisonBinaryOperator],[">",s.ComparisonBinaryOperator],["+",s.AdditiveBinaryOperator],["-",s.AdditiveBinaryOperator],["*",s.MultiplicativeBinaryOperator],["/",s.MultiplicativeBinaryOperator],["%",s.MultiplicativeBinaryOperator],["=",s.Equals]],u=new Map([["n",` +`],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function p(O,Y={}){return O.endsWith(` +`)&&(O=O.slice(0,-1)),O=O.replace(/{#.*?#}/gs,"{##}"),Y.lstrip_blocks&&(O=O.replace(/^[ \t]*({[#%])/gm,"$1")),Y.trim_blocks&&(O=O.replace(/([#%]})\n/g,"$1")),O.replace(/{##}/g,"").replace(/-%}\s*/g,"%}").replace(/\s*{%-/g,"{%").replace(/-}}\s*/g,"}}").replace(/\s*{{-/g,"{{")}function d(O,Y={}){var Ee,ke,Ie;const z=[],J=p(O,Y);let le=0;const ye=Re=>{let Xe="";for(;Re(J[le]);){if(J[le]==="\\"){if(++le,le>=J.length)throw new SyntaxError("Unexpected end of input");const Ge=J[le++],lt=u.get(Ge);if(lt===void 0)throw new SyntaxError(`Unexpected escaped character: ${Ge}`);Xe+=lt;continue}if(Xe+=J[le++],le>=J.length)throw new SyntaxError("Unexpected end of input")}return Xe};e:for(;le0){z.push(new n(Ge,s.Text));continue}}ye(Ge=>/\s/.test(Ge));const Xe=J[le];if(Xe==="-"||Xe==="+"){const Ge=(ke=z.at(-1))==null?void 0:ke.type;if(Ge===s.Text||Ge===void 0)throw new SyntaxError(`Unexpected character: ${Xe}`);switch(Ge){case s.Identifier:case s.NumericLiteral:case s.BooleanLiteral:case s.NullLiteral:case s.StringLiteral:case s.CloseParen:case s.CloseSquareBracket:break;default:{++le;const lt=ye(a);z.push(new n(`${Xe}${lt}`,lt.length>0?s.NumericLiteral:s.UnaryOperator));continue}}}for(const[Ge,lt]of l)if(J.slice(le,le+Ge.length)===Ge){z.push(new n(Ge,lt)),le+=Ge.length;continue e}if(Xe==="'"||Xe==='"'){++le;const Ge=ye(lt=>lt!==Xe);z.push(new n(Ge,s.StringLiteral)),++le;continue}if(a(Xe)){const Ge=ye(a);z.push(new n(Ge,s.NumericLiteral));continue}if(i(Xe)){const Ge=ye(i),lt=Object.hasOwn(o,Ge)?o[Ge]:s.Identifier;lt===s.In&&((Ie=z.at(-1))==null?void 0:Ie.type)===s.Not?(z.pop(),z.push(new n("not in",s.NotIn))):z.push(new n(Ge,lt));continue}throw new SyntaxError(`Unexpected character: ${Xe}`)}return z}var c=class{constructor(){te(this,"type","Statement")}},f=class extends c{constructor(Y){super();te(this,"type","Program");this.body=Y}},_=class extends c{constructor(Y,z,J){super();te(this,"type","If");this.test=Y,this.body=z,this.alternate=J}},T=class extends c{constructor(Y,z,J,le){super();te(this,"type","For");this.loopvar=Y,this.iterable=z,this.body=J,this.defaultBlock=le}},k=class extends c{constructor(Y,z,J){super();te(this,"type","Set");this.assignee=Y,this.value=z,this.body=J}},w=class extends c{constructor(Y,z,J){super();te(this,"type","Macro");this.name=Y,this.args=z,this.body=J}},g=class extends c{constructor(){super(...arguments);te(this,"type","Expression")}},S=class extends g{constructor(Y,z,J){super();te(this,"type","MemberExpression");this.object=Y,this.property=z,this.computed=J}},E=class extends g{constructor(Y,z){super();te(this,"type","CallExpression");this.callee=Y,this.args=z}},y=class extends g{constructor(Y){super();te(this,"type","Identifier");this.value=Y}},M=class extends g{constructor(Y){super();te(this,"type","Literal");this.value=Y}},v=class extends M{constructor(){super(...arguments);te(this,"type","NumericLiteral")}},C=class extends M{constructor(){super(...arguments);te(this,"type","StringLiteral")}},A=class extends M{constructor(){super(...arguments);te(this,"type","BooleanLiteral")}},B=class extends M{constructor(){super(...arguments);te(this,"type","NullLiteral")}},K=class extends M{constructor(){super(...arguments);te(this,"type","ArrayLiteral")}},G=class extends M{constructor(){super(...arguments);te(this,"type","TupleLiteral")}},j=class extends M{constructor(){super(...arguments);te(this,"type","ObjectLiteral")}},ee=class extends g{constructor(Y,z,J){super();te(this,"type","BinaryExpression");this.operator=Y,this.left=z,this.right=J}},H=class extends g{constructor(Y,z){super();te(this,"type","FilterExpression");this.operand=Y,this.filter=z}},Z=class extends g{constructor(Y,z){super();te(this,"type","SelectExpression");this.iterable=Y,this.test=z}},X=class extends g{constructor(Y,z,J){super();te(this,"type","TestExpression");this.operand=Y,this.negate=z,this.test=J}},oe=class extends g{constructor(Y,z){super();te(this,"type","UnaryExpression");this.operator=Y,this.argument=z}},me=class extends g{constructor(Y=void 0,z=void 0,J=void 0){super();te(this,"type","SliceExpression");this.start=Y,this.stop=z,this.step=J}},ae=class extends g{constructor(Y,z){super();te(this,"type","KeywordArgumentExpression");this.key=Y,this.value=z}};function V(O){const Y=new f([]);let z=0;function J(De,Qe){const tt=O[z++];if(!tt||tt.type!==De)throw new Error(`Parser Error: ${Qe}. ${tt.type} !== ${De}.`);return tt}function le(){switch(O[z].type){case s.Text:return ke();case s.OpenStatement:return Ie();case s.OpenExpression:return Re();default:throw new SyntaxError(`Unexpected token type: ${O[z].type}`)}}function ye(...De){return z+De.length<=O.length&&De.some((Qe,tt)=>Qe!==O[z+tt].type)}function Ee(...De){return z+De.length<=O.length&&De.every((Qe,tt)=>Qe===O[z+tt].type)}function ke(){return new C(J(s.Text,"Expected text token").value)}function Ie(){J(s.OpenStatement,"Expected opening statement token");let De;switch(O[z].type){case s.Set:++z,De=Xe(),J(s.CloseStatement,"Expected closing statement token");break;case s.If:++z,De=Ge(),J(s.OpenStatement,"Expected {% token"),J(s.EndIf,"Expected endif token"),J(s.CloseStatement,"Expected %} token");break;case s.Macro:++z,De=lt(),J(s.OpenStatement,"Expected {% token"),J(s.EndMacro,"Expected endmacro token"),J(s.CloseStatement,"Expected %} token");break;case s.For:++z,De=Gt(),J(s.OpenStatement,"Expected {% token"),J(s.EndFor,"Expected endfor token"),J(s.CloseStatement,"Expected %} token");break;default:throw new SyntaxError(`Unknown statement type: ${O[z].type}`)}return De}function Re(){J(s.OpenExpression,"Expected opening expression token");const De=Ot();return J(s.CloseExpression,"Expected closing expression token"),De}function Xe(){var Qe,tt;const De=Ot();if(Ee(s.Equals)){++z;const Rt=Ot();return new k(De,Rt,[])}else{const Rt=[];for(J(s.CloseStatement,"Expected %} token");!(((Qe=O[z])==null?void 0:Qe.type)===s.OpenStatement&&((tt=O[z+1])==null?void 0:tt.type)===s.EndSet);){const zr=le();Rt.push(zr)}return J(s.OpenStatement,"Expected {% token"),J(s.EndSet,"Expected endset token"),new k(De,null,Rt)}}function Ge(){var Rt,zr,Sr,ps,hs,Kr,ms,_s;const De=Ot();J(s.CloseStatement,"Expected closing statement token");const Qe=[],tt=[];for(;!(((Rt=O[z])==null?void 0:Rt.type)===s.OpenStatement&&(((zr=O[z+1])==null?void 0:zr.type)===s.ElseIf||((Sr=O[z+1])==null?void 0:Sr.type)===s.Else||((ps=O[z+1])==null?void 0:ps.type)===s.EndIf));)Qe.push(le());if(((hs=O[z])==null?void 0:hs.type)===s.OpenStatement&&((Kr=O[z+1])==null?void 0:Kr.type)!==s.EndIf)if(++z,Ee(s.ElseIf))J(s.ElseIf,"Expected elseif token"),tt.push(Ge());else for(J(s.Else,"Expected else token"),J(s.CloseStatement,"Expected closing statement token");!(((ms=O[z])==null?void 0:ms.type)===s.OpenStatement&&((_s=O[z+1])==null?void 0:_s.type)===s.EndIf);)tt.push(le());return new _(De,Qe,tt)}function lt(){const De=Qt();if(De.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");const Qe=us();J(s.CloseStatement,"Expected closing statement token");const tt=[];for(;ye(s.OpenStatement,s.EndMacro);)tt.push(le());return new w(De,Qe,tt)}function wt(De=!1){const Qe=De?Qt:Ot,tt=[Qe()],Rt=Ee(s.Comma);for(;Rt&&(++z,tt.push(Qe()),!!Ee(s.Comma)););return Rt?new G(tt):tt[0]}function Gt(){const De=wt(!0);if(!(De instanceof y||De instanceof G))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${De.type} instead`);J(s.In,"Expected `in` keyword following loop variable");const Qe=Ot();J(s.CloseStatement,"Expected closing statement token");const tt=[];for(;ye(s.OpenStatement,s.EndFor)&&ye(s.OpenStatement,s.Else);)tt.push(le());const Rt=[];if(Ee(s.OpenStatement,s.Else))for(++z,++z,J(s.CloseStatement,"Expected closing statement token");ye(s.OpenStatement,s.EndFor);)Rt.push(le());return new T(De,Qe,tt,Rt)}function Ot(){return ur()}function ur(){const De=ls();if(Ee(s.If)){++z;const Qe=ls();if(Ee(s.Else)){++z;const tt=ls();return new _(Qe,[De],[tt])}else return new Z(De,Qe)}return De}function ls(){let De=Ms();for(;Ee(s.Or);){const Qe=O[z];++z;const tt=Ms();De=new ee(Qe,De,tt)}return De}function Ms(){let De=Ir();for(;Ee(s.And);){const Qe=O[z];++z;const tt=Ir();De=new ee(Qe,De,tt)}return De}function Ir(){let De;for(;Ee(s.Not);){const Qe=O[z];++z;const tt=Ir();De=new oe(Qe,tt)}return De??js()}function js(){let De=Ss();for(;Ee(s.ComparisonBinaryOperator)||Ee(s.In)||Ee(s.NotIn);){const Qe=O[z];++z;const tt=Ss();De=new ee(Qe,De,tt)}return De}function Ss(){let De=ds();for(;Ee(s.AdditiveBinaryOperator);){const Qe=O[z];++z;const tt=ds();De=new ee(Qe,De,tt)}return De}function Ns(){const De=Ft(Qt());return Ee(s.OpenParen)?at(De):De}function at(De){let Qe=new E(De,us());return Qe=Ft(Qe),Ee(s.OpenParen)&&(Qe=at(Qe)),Qe}function us(){J(s.OpenParen,"Expected opening parenthesis for arguments list");const De=Ar();return J(s.CloseParen,"Expected closing parenthesis for arguments list"),De}function Ar(){const De=[];for(;!Ee(s.CloseParen);){let Qe=Ot();if(Ee(s.Equals)){if(++z,!(Qe instanceof y))throw new SyntaxError("Expected identifier for keyword argument");const tt=Ot();Qe=new ae(Qe,tt)}De.push(Qe),Ee(s.Comma)&&++z}return De}function bs(){const De=[];let Qe=!1;for(;!Ee(s.CloseSquareBracket);)Ee(s.Colon)?(De.push(void 0),++z,Qe=!0):(De.push(Ot()),Ee(s.Colon)&&(++z,Qe=!0));if(De.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(Qe){if(De.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new me(...De)}return De[0]}function Ft(De){for(;Ee(s.Dot)||Ee(s.OpenSquareBracket);){const Qe=O[z];++z;let tt;const Rt=Qe.type!==s.Dot;if(Rt)tt=bs(),J(s.CloseSquareBracket,"Expected closing square bracket");else if(tt=Qt(),tt.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");De=new S(De,tt,Rt)}return De}function ds(){let De=cs();for(;Ee(s.MultiplicativeBinaryOperator);){const Qe=O[z];++z;const tt=cs();De=new ee(Qe,De,tt)}return De}function cs(){let De=ys();for(;Ee(s.Is);){++z;const Qe=Ee(s.Not);Qe&&++z;let tt=Qt();if(tt instanceof A?tt=new y(tt.value.toString()):tt instanceof B&&(tt=new y("none")),!(tt instanceof y))throw new SyntaxError("Expected identifier for the test");De=new X(De,Qe,tt)}return De}function ys(){let De=Ns();for(;Ee(s.Pipe);){++z;let Qe=Qt();if(!(Qe instanceof y))throw new SyntaxError("Expected identifier for the filter");Ee(s.OpenParen)&&(Qe=at(Qe)),De=new H(De,Qe)}return De}function Qt(){const De=O[z];switch(De.type){case s.NumericLiteral:return++z,new v(Number(De.value));case s.StringLiteral:return++z,new C(De.value);case s.BooleanLiteral:return++z,new A(De.value.toLowerCase()==="true");case s.NullLiteral:return++z,new B(null);case s.Identifier:return++z,new y(De.value);case s.OpenParen:{++z;const Qe=wt();if(O[z].type!==s.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${O[z].type} instead`);return++z,Qe}case s.OpenSquareBracket:{++z;const Qe=[];for(;!Ee(s.CloseSquareBracket);)Qe.push(Ot()),Ee(s.Comma)&&++z;return++z,new K(Qe)}case s.OpenCurlyBracket:{++z;const Qe=new Map;for(;!Ee(s.CloseCurlyBracket);){const tt=Ot();J(s.Colon,"Expected colon between key and value in object literal");const Rt=Ot();Qe.set(tt,Rt),Ee(s.Comma)&&++z}return++z,new j(Qe)}default:throw new SyntaxError(`Unexpected token: ${De.type}`)}}for(;z=0?(Y=(Y??(Y=0))<0?Math.max(O.length+Y,0):Math.min(Y,O.length),z=(z??(z=O.length))<0?Math.max(O.length+z,0):Math.min(z,O.length)):(Y=(Y??(Y=O.length-1))<0?Math.max(O.length+Y,-1):Math.min(Y,O.length-1),z=(z??(z=-1))<-1?Math.max(O.length+z,-1):Math.min(z,O.length-1));const ye=[];for(let Ee=Y;le*EeY.toUpperCase())}var _e=class{constructor(O=void 0){te(this,"type","RuntimeValue");te(this,"value");te(this,"builtins",new Map);this.value=O}__bool__(){return new $e(!!this.value)}},se=class extends _e{constructor(){super(...arguments);te(this,"type","NumericValue")}},ce=class extends _e{constructor(){super(...arguments);te(this,"type","StringValue");te(this,"builtins",new Map([["upper",new pe(()=>new ce(this.value.toUpperCase()))],["lower",new pe(()=>new ce(this.value.toLowerCase()))],["strip",new pe(()=>new ce(this.value.trim()))],["title",new pe(()=>new ce(re(this.value)))],["length",new se(this.value.length)],["rstrip",new pe(()=>new ce(this.value.trimEnd()))],["lstrip",new pe(()=>new ce(this.value.trimStart()))],["split",new pe(Y=>{const z=Y[0]??new xe;if(!(z instanceof ce||z instanceof xe))throw new Error("sep argument must be a string or null");const J=Y[1]??new se(-1);if(!(J instanceof se))throw new Error("maxsplit argument must be a number");let le=[];if(z instanceof xe){const ye=this.value.trimStart();for(const{0:Ee,index:ke}of ye.matchAll(/\S+/g)){if(J.value!==-1&&le.length>=J.value&&ke!==void 0){le.push(Ee+ye.slice(ke+Ee.length));break}le.push(Ee)}}else{if(z.value==="")throw new Error("empty separator");le=this.value.split(z.value),J.value!==-1&&le.length>J.value&&le.push(le.splice(J.value).join(z.value))}return new q(le.map(ye=>new ce(ye)))})]]))}},$e=class extends _e{constructor(){super(...arguments);te(this,"type","BooleanValue")}},Ue=class extends _e{constructor(){super(...arguments);te(this,"type","ObjectValue");te(this,"builtins",new Map([["get",new pe(([Y,z])=>{if(!(Y instanceof ce))throw new Error(`Object key must be a string: got ${Y.type}`);return this.value.get(Y.value)??z??new xe})],["items",new pe(()=>new q(Array.from(this.value.entries()).map(([Y,z])=>new q([new ce(Y),z]))))]]))}__bool__(){return new $e(this.value.size>0)}},we=class extends Ue{constructor(){super(...arguments);te(this,"type","KeywordArgumentsValue")}},q=class extends _e{constructor(){super(...arguments);te(this,"type","ArrayValue");te(this,"builtins",new Map([["length",new se(this.value.length)]]))}__bool__(){return new $e(this.value.length>0)}},R=class extends q{constructor(){super(...arguments);te(this,"type","TupleValue")}},pe=class extends _e{constructor(){super(...arguments);te(this,"type","FunctionValue")}},xe=class extends _e{constructor(){super(...arguments);te(this,"type","NullValue")}},be=class extends _e{constructor(){super(...arguments);te(this,"type","UndefinedValue")}},Se=class{constructor(O){te(this,"variables",new Map([["namespace",new pe(O=>{if(O.length===0)return new Ue(new Map);if(O.length!==1||!(O[0]instanceof Ue))throw new Error("`namespace` expects either zero arguments or a single object argument");return O[0]})]]));te(this,"tests",new Map([["boolean",O=>O.type==="BooleanValue"],["callable",O=>O instanceof pe],["odd",O=>{if(O.type!=="NumericValue")throw new Error(`Cannot apply test "odd" to type: ${O.type}`);return O.value%2!==0}],["even",O=>{if(O.type!=="NumericValue")throw new Error(`Cannot apply test "even" to type: ${O.type}`);return O.value%2===0}],["false",O=>O.type==="BooleanValue"&&!O.value],["true",O=>O.type==="BooleanValue"&&O.value],["none",O=>O.type==="NullValue"],["string",O=>O.type==="StringValue"],["number",O=>O.type==="NumericValue"],["integer",O=>O.type==="NumericValue"&&Number.isInteger(O.value)],["iterable",O=>O.type==="ArrayValue"||O.type==="StringValue"],["mapping",O=>O.type==="ObjectValue"],["lower",O=>{const Y=O.value;return O.type==="StringValue"&&Y===Y.toLowerCase()}],["upper",O=>{const Y=O.value;return O.type==="StringValue"&&Y===Y.toUpperCase()}],["none",O=>O.type==="NullValue"],["defined",O=>O.type!=="UndefinedValue"],["undefined",O=>O.type==="UndefinedValue"],["equalto",(O,Y)=>O.value===Y.value],["eq",(O,Y)=>O.value===Y.value]]));this.parent=O}set(O,Y){return this.declareVariable(O,Fe(Y))}declareVariable(O,Y){if(this.variables.has(O))throw new SyntaxError(`Variable already declared: ${O}`);return this.variables.set(O,Y),Y}setVariable(O,Y){return this.variables.set(O,Y),Y}resolve(O){if(this.variables.has(O))return this;if(this.parent)return this.parent.resolve(O);throw new Error(`Unknown variable: ${O}`)}lookupVariable(O){try{return this.resolve(O).variables.get(O)??new be}catch{return new be}}},Ae=class{constructor(O){te(this,"global");this.global=O??new Se}run(O){return this.evaluate(O,this.global)}evaluateBinaryExpression(O,Y){const z=this.evaluate(O.left,Y);switch(O.operator.value){case"and":return z.__bool__().value?this.evaluate(O.right,Y):z;case"or":return z.__bool__().value?z:this.evaluate(O.right,Y)}const J=this.evaluate(O.right,Y);switch(O.operator.value){case"==":return new $e(z.value==J.value);case"!=":return new $e(z.value!=J.value)}if(z instanceof be||J instanceof be)throw new Error("Cannot perform operation on undefined values");if(z instanceof xe||J instanceof xe)throw new Error("Cannot perform operation on null values");if(z instanceof se&&J instanceof se)switch(O.operator.value){case"+":return new se(z.value+J.value);case"-":return new se(z.value-J.value);case"*":return new se(z.value*J.value);case"/":return new se(z.value/J.value);case"%":return new se(z.value%J.value);case"<":return new $e(z.value":return new $e(z.value>J.value);case">=":return new $e(z.value>=J.value);case"<=":return new $e(z.value<=J.value)}else if(z instanceof q&&J instanceof q)switch(O.operator.value){case"+":return new q(z.value.concat(J.value))}else if(J instanceof q){const le=J.value.find(ye=>ye.value===z.value)!==void 0;switch(O.operator.value){case"in":return new $e(le);case"not in":return new $e(!le)}}if(z instanceof ce||J instanceof ce)switch(O.operator.value){case"+":return new ce(z.value.toString()+J.value.toString())}if(z instanceof ce&&J instanceof ce)switch(O.operator.value){case"in":return new $e(J.value.includes(z.value));case"not in":return new $e(!J.value.includes(z.value))}if(z instanceof ce&&J instanceof Ue)switch(O.operator.value){case"in":return new $e(J.value.has(z.value));case"not in":return new $e(!J.value.has(z.value))}throw new SyntaxError(`Unknown operator "${O.operator.value}" between ${z.type} and ${J.type}`)}evaluateArguments(O,Y){const z=[],J=new Map;for(const le of O)if(le.type==="KeywordArgumentExpression"){const ye=le;J.set(ye.key.value,this.evaluate(ye.value,Y))}else{if(J.size>0)throw new Error("Positional arguments must come before keyword arguments");z.push(this.evaluate(le,Y))}return[z,J]}evaluateFilterExpression(O,Y){const z=this.evaluate(O.operand,Y);if(O.filter.type==="Identifier"){const J=O.filter;if(J.value==="tojson")return new ce(ze(z));if(z instanceof q)switch(J.value){case"list":return z;case"first":return z.value[0];case"last":return z.value[z.value.length-1];case"length":return new se(z.value.length);case"reverse":return new q(z.value.reverse());case"sort":return new q(z.value.sort((le,ye)=>{if(le.type!==ye.type)throw new Error(`Cannot compare different types: ${le.type} and ${ye.type}`);switch(le.type){case"NumericValue":return le.value-ye.value;case"StringValue":return le.value.localeCompare(ye.value);default:throw new Error(`Cannot compare type: ${le.type}`)}}));case"join":return new ce(z.value.map(le=>le.value).join(""));case"string":return new ce(ze(z));default:throw new Error(`Unknown ArrayValue filter: ${J.value}`)}else if(z instanceof ce)switch(J.value){case"length":return new se(z.value.length);case"upper":return new ce(z.value.toUpperCase());case"lower":return new ce(z.value.toLowerCase());case"title":return new ce(re(z.value));case"capitalize":return new ce(z.value.charAt(0).toUpperCase()+z.value.slice(1));case"trim":return new ce(z.value.trim());case"indent":return new ce(z.value.split(` +`).map((le,ye)=>ye===0||le.length===0?le:" "+le).join(` +`));case"join":case"string":return z;default:throw new Error(`Unknown StringValue filter: ${J.value}`)}else if(z instanceof se)switch(J.value){case"abs":return new se(Math.abs(z.value));default:throw new Error(`Unknown NumericValue filter: ${J.value}`)}else if(z instanceof Ue)switch(J.value){case"items":return new q(Array.from(z.value.entries()).map(([le,ye])=>new q([new ce(le),ye])));case"length":return new se(z.value.size);default:throw new Error(`Unknown ObjectValue filter: ${J.value}`)}throw new Error(`Cannot apply filter "${J.value}" to type: ${z.type}`)}else if(O.filter.type==="CallExpression"){const J=O.filter;if(J.callee.type!=="Identifier")throw new Error(`Unknown filter: ${J.callee.type}`);const le=J.callee.value;if(le==="tojson"){const[,ye]=this.evaluateArguments(J.args,Y),Ee=ye.get("indent")??new xe;if(!(Ee instanceof se||Ee instanceof xe))throw new Error("If set, indent must be a number");return new ce(ze(z,Ee.value))}else if(le==="join"){let ye;if(z instanceof ce)ye=Array.from(z.value);else if(z instanceof q)ye=z.value.map(Re=>Re.value);else throw new Error(`Cannot apply filter "${le}" to type: ${z.type}`);const[Ee,ke]=this.evaluateArguments(J.args,Y),Ie=Ee.at(0)??ke.get("separator")??new ce("");if(!(Ie instanceof ce))throw new Error("separator must be a string");return new ce(ye.join(Ie.value))}if(z instanceof q){switch(le){case"selectattr":case"rejectattr":{const ye=le==="selectattr";if(z.value.some(Ge=>!(Ge instanceof Ue)))throw new Error(`\`${le}\` can only be applied to array of objects`);if(J.args.some(Ge=>Ge.type!=="StringLiteral"))throw new Error(`arguments of \`${le}\` must be strings`);const[Ee,ke,Ie]=J.args.map(Ge=>this.evaluate(Ge,Y));let Re;if(ke){const Ge=Y.tests.get(ke.value);if(!Ge)throw new Error(`Unknown test: ${ke.value}`);Re=Ge}else Re=(...Ge)=>Ge[0].__bool__().value;const Xe=z.value.filter(Ge=>{const lt=Ge.value.get(Ee.value),wt=lt?Re(lt,Ie):!1;return ye?wt:!wt});return new q(Xe)}case"map":{const[,ye]=this.evaluateArguments(J.args,Y);if(ye.has("attribute")){const Ee=ye.get("attribute");if(!(Ee instanceof ce))throw new Error("attribute must be a string");const ke=ye.get("default"),Ie=z.value.map(Re=>{if(!(Re instanceof Ue))throw new Error("items in map must be an object");return Re.value.get(Ee.value)??ke??new be});return new q(Ie)}else throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${le}`)}else if(z instanceof ce){switch(le){case"indent":{const[ye,Ee]=this.evaluateArguments(J.args,Y),ke=ye.at(0)??Ee.get("width")??new se(4);if(!(ke instanceof se))throw new Error("width must be a number");const Ie=ye.at(1)??Ee.get("first")??new $e(!1),Re=ye.at(2)??Ee.get("blank")??new $e(!1),Xe=z.value.split(` +`),Ge=" ".repeat(ke.value),lt=Xe.map((wt,Gt)=>!Ie.value&&Gt===0||!Re.value&&wt.length===0?wt:Ge+wt);return new ce(lt.join(` +`))}}throw new Error(`Unknown StringValue filter: ${le}`)}else throw new Error(`Cannot apply filter "${le}" to type: ${z.type}`)}throw new Error(`Unknown filter: ${O.filter.type}`)}evaluateTestExpression(O,Y){const z=this.evaluate(O.operand,Y),J=Y.tests.get(O.test.value);if(!J)throw new Error(`Unknown test: ${O.test.value}`);const le=J(z);return new $e(O.negate?!le:le)}evaluateUnaryExpression(O,Y){const z=this.evaluate(O.argument,Y);switch(O.operator.value){case"not":return new $e(!z.value);default:throw new SyntaxError(`Unknown operator: ${O.operator.value}`)}}evalProgram(O,Y){return this.evaluateBlock(O.body,Y)}evaluateBlock(O,Y){let z="";for(const J of O){const le=this.evaluate(J,Y);le.type!=="NullValue"&&le.type!=="UndefinedValue"&&(z+=le.value)}return new ce(z)}evaluateIdentifier(O,Y){return Y.lookupVariable(O.value)}evaluateCallExpression(O,Y){const[z,J]=this.evaluateArguments(O.args,Y);J.size>0&&z.push(new we(J));const le=this.evaluate(O.callee,Y);if(le.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${le.type}`);return le.value(z,Y)}evaluateSliceExpression(O,Y,z){if(!(O instanceof q||O instanceof ce))throw new Error("Slice object must be an array or string");const J=this.evaluate(Y.start,z),le=this.evaluate(Y.stop,z),ye=this.evaluate(Y.step,z);if(!(J instanceof se||J instanceof be))throw new Error("Slice start must be numeric or undefined");if(!(le instanceof se||le instanceof be))throw new Error("Slice stop must be numeric or undefined");if(!(ye instanceof se||ye instanceof be))throw new Error("Slice step must be numeric or undefined");return O instanceof q?new q(W(O.value,J.value,le.value,ye.value)):new ce(W(Array.from(O.value),J.value,le.value,ye.value).join(""))}evaluateMemberExpression(O,Y){const z=this.evaluate(O.object,Y);let J;if(O.computed){if(O.property.type==="SliceExpression")return this.evaluateSliceExpression(z,O.property,Y);J=this.evaluate(O.property,Y)}else J=new ce(O.property.value);let le;if(z instanceof Ue){if(!(J instanceof ce))throw new Error(`Cannot access property with non-string: got ${J.type}`);le=z.value.get(J.value)??z.builtins.get(J.value)}else if(z instanceof q||z instanceof ce)if(J instanceof se)le=z.value.at(J.value),z instanceof ce&&(le=new ce(z.value.at(J.value)));else if(J instanceof ce)le=z.builtins.get(J.value);else throw new Error(`Cannot access property with non-string/non-number: got ${J.type}`);else{if(!(J instanceof ce))throw new Error(`Cannot access property with non-string: got ${J.type}`);le=z.builtins.get(J.value)}return le instanceof _e?le:new be}evaluateSet(O,Y){const z=O.value?this.evaluate(O.value,Y):this.evaluateBlock(O.body,Y);if(O.assignee.type==="Identifier"){const J=O.assignee.value;Y.setVariable(J,z)}else if(O.assignee.type==="MemberExpression"){const J=O.assignee,le=this.evaluate(J.object,Y);if(!(le instanceof Ue))throw new Error("Cannot assign to member of non-object");if(J.property.type!=="Identifier")throw new Error("Cannot assign to member with non-identifier property");le.value.set(J.property.value,z)}else throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(O.assignee)}`);return new xe}evaluateIf(O,Y){const z=this.evaluate(O.test,Y);return this.evaluateBlock(z.__bool__().value?O.body:O.alternate,Y)}evaluateFor(O,Y){const z=new Se(Y);let J,le;if(O.iterable.type==="SelectExpression"){const Re=O.iterable;le=this.evaluate(Re.iterable,z),J=Re.test}else le=this.evaluate(O.iterable,z);if(!(le instanceof q))throw new Error(`Expected iterable type in for loop: got ${le.type}`);const ye=[],Ee=[];for(let Re=0;Rewt.setVariable(O.loopvar.value,Ge);else if(O.loopvar.type==="TupleLiteral"){const wt=O.loopvar;if(Ge.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${Ge.type}`);const Gt=Ge;if(wt.value.length!==Gt.value.length)throw new Error(`Too ${wt.value.length>Gt.value.length?"few":"many"} items to unpack`);lt=Ot=>{for(let ur=0;ur0?ye[Re-1]:new be],["nextitem",Re{var Ee;const le=new Se(J);z=z.slice();let ye;((Ee=z.at(-1))==null?void 0:Ee.type)==="KeywordArgumentsValue"&&(ye=z.pop());for(let ke=0;kethis.evaluate(z,Y)));case"TupleLiteral":return new R(O.value.map(z=>this.evaluate(z,Y)));case"ObjectLiteral":{const z=new Map;for(const[J,le]of O.value){const ye=this.evaluate(J,Y);if(!(ye instanceof ce))throw new Error(`Object keys must be strings: got ${ye.type}`);z.set(ye.value,this.evaluate(le,Y))}return new Ue(z)}case"Identifier":return this.evaluateIdentifier(O,Y);case"CallExpression":return this.evaluateCallExpression(O,Y);case"MemberExpression":return this.evaluateMemberExpression(O,Y);case"UnaryExpression":return this.evaluateUnaryExpression(O,Y);case"BinaryExpression":return this.evaluateBinaryExpression(O,Y);case"FilterExpression":return this.evaluateFilterExpression(O,Y);case"TestExpression":return this.evaluateTestExpression(O,Y);default:throw new SyntaxError(`Unknown node type: ${O.type}`)}}};function Fe(O){switch(typeof O){case"number":return new se(O);case"string":return new ce(O);case"boolean":return new $e(O);case"undefined":return new be;case"object":return O===null?new xe:Array.isArray(O)?new q(O.map(Fe)):new Ue(new Map(Object.entries(O).map(([Y,z])=>[Y,Fe(z)])));case"function":return new pe((Y,z)=>{const J=O(...Y.map(le=>le.value))??null;return Fe(J)});default:throw new Error(`Cannot convert to runtime value: ${O}`)}}function ze(O,Y,z){const J=z??0;switch(O.type){case"NullValue":case"UndefinedValue":return"null";case"NumericValue":case"StringValue":case"BooleanValue":return JSON.stringify(O.value);case"ArrayValue":case"ObjectValue":{const le=Y?" ".repeat(Y):"",ye=` +`+le.repeat(J),Ee=ye+le;if(O.type==="ArrayValue"){const ke=O.value.map(Ie=>ze(Ie,Y,J+1));return Y?`[${Ee}${ke.join(`,${Ee}`)}${ye}]`:`[${ke.join(", ")}]`}else{const ke=Array.from(O.value.entries()).map(([Ie,Re])=>{const Xe=`"${Ie}": ${ze(Re,Y,J+1)}`;return Y?`${Ee}${Xe}`:Xe});return Y?`{${ke.join(",")}${ye}}`:`{${ke.join(", ")}}`}}default:throw new Error(`Cannot convert to JSON: ${O.type}`)}}var Ve=class{constructor(O){te(this,"parsed");const Y=d(O,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=V(Y)}render(O){const Y=new Se;if(Y.set("false",!1),Y.set("true",!0),Y.set("raise_exception",le=>{throw new Error(le)}),Y.set("range",F),O)for(const[le,ye]of Object.entries(O))Y.set(le,ye);return new Ae(Y).run(this.parsed).value}}},"./src/backends/onnx.js":(e,r,t)=>{var s;t.r(r),t.d(r,{Tensor:()=>a.Tensor,createInferenceSession:()=>k,deviceToExecutionProviders:()=>_,isONNXProxy:()=>S,isONNXTensor:()=>w});var o=t("./src/env.js"),n=t("?2ce3"),i=t("onnxruntime-web"),a=t("onnxruntime-common");const l=Object.freeze({auto:null,gpu:null,cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",webnn:{name:"webnn",deviceType:"cpu"},"webnn-npu":{name:"webnn",deviceType:"npu"},"webnn-gpu":{name:"webnn",deviceType:"gpu"},"webnn-cpu":{name:"webnn",deviceType:"cpu"}}),u=[];let p,d;const c=Symbol.for("onnxruntime");if(c in globalThis)d=globalThis[c];else if(o.apis.IS_NODE_ENV){switch(d=n??(s||(s=t.t(n,2))),process.platform){case"win32":u.push("dml");break;case"linux":process.arch==="x64"&&u.push("cuda");break}u.push("cpu"),p=["cpu"]}else d=i,o.apis.IS_WEBNN_AVAILABLE&&u.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),o.apis.IS_WEBGPU_AVAILABLE&&u.push("webgpu"),u.push("wasm"),p=["wasm"];const f=d.InferenceSession;function _(E=null){if(!E)return p;switch(E){case"auto":return u;case"gpu":return u.filter(y=>["webgpu","cuda","dml","webnn-gpu"].includes(y))}if(u.includes(E))return[l[E]??E];throw new Error(`Unsupported device: "${E}". Should be one of: ${u.join(", ")}.`)}let T=null;async function k(E,y,M){T&&await T;const v=f.create(E,y);T??(T=v);const C=await v;return C.config=M,C}function w(E){return E instanceof d.Tensor}const g=d==null?void 0:d.env;g!=null&&g.wasm&&(!(typeof ServiceWorkerGlobalScope<"u"&&self instanceof ServiceWorkerGlobalScope)&&!g.wasm.wasmPaths&&(g.wasm.wasmPaths=`https://cdn.jsdelivr.net/npm/@huggingface/transformers@${o.env.version}/dist/`),g.wasm.proxy=!1),g!=null&&g.webgpu&&(g.webgpu.powerPreference="high-performance");function S(){var E;return(E=g==null?void 0:g.wasm)==null?void 0:E.proxy}o.env.backends.onnx=g},"./src/base/feature_extraction_utils.js":(e,r,t)=>{t.r(r),t.d(r,{FeatureExtractor:()=>i,validate_audio_inputs:()=>a});var s=t("./src/utils/constants.js"),o=t("./src/utils/generic.js"),n=t("./src/utils/hub.js");class i extends o.Callable{constructor(u){super(),this.config=u}static async from_pretrained(u,p){const d=await(0,n.getModelJSON)(u,s.FEATURE_EXTRACTOR_NAME,!0,p);return new this(d)}}function a(l,u){var p;if(!(l instanceof Float32Array||l instanceof Float64Array))throw new Error(`${u} expects input to be a Float32Array or a Float64Array, but got ${((p=l==null?void 0:l.constructor)==null?void 0:p.name)??typeof l} instead. If using the feature extractor directly, remember to use \`read_audio(url, sampling_rate)\` to obtain the raw audio data of the file/url.`)}},"./src/base/image_processors_utils.js":(e,r,t)=>{t.r(r),t.d(r,{ImageProcessor:()=>E,center_to_corners_format:()=>d,post_process_instance_segmentation:()=>S,post_process_object_detection:()=>c,post_process_panoptic_segmentation:()=>g,post_process_semantic_segmentation:()=>f});var s=t("./src/utils/generic.js"),o=t("./src/utils/tensor.js"),n=t("./src/utils/maths.js");t("./src/utils/image.js");var i=t("./src/utils/core.js"),a=t("./src/utils/hub.js"),l=t("./src/utils/constants.js");function u(y,M,v=0,C=null){const A=y/M;let B=(0,n.bankers_round)(A)*M;return C!==null&&B>C&&(B=Math.floor(A)*M),BM&&F.push(re)}else{let re=(0,n.max)(V.data)[1];if(re===j-1||(W=(0,n.softmax)(V.data),W[re]se*Z[(ce+1)%2])),X.boxes.push(_e),X.classes.push(re),X.scores.push(W[re])}}ee.push(X)}return ee}function f(y,M=null){const v=y.logits,C=v.dims[0];if(M!==null&&M.length!==C)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const A=[];for(let B=0;BZ[F]&&(Z[F]=V[F],X[F]=ae)}const oe=new Array(G.dims[0]);for(let ae=0;aeae!==void 0);A.push({segmentation:H,labels:me})}return A}function _(y,M,v,C){const A=[],B=[],K=[];for(let G=0;Gv&&(A.push(ee),B.push(X),K.push(H))}return[A,B,K]}function T(y,M,v,C=.5,A=.8){const B=[];let K=0,G=0;const j=M[v].data;for(let H=0;H=C&&++G;let ee=K>0&&G>0;return ee&&(ee=K/G>A),[ee,B]}function k(y,M,v,C,A,B=null,K=null){const[G,j]=K??y[0].dims,ee=new o.Tensor("int32",new Int32Array(G*j),[G,j]),H=[];if(K!==null)for(let ae=0;aeX[W]&&(Z[W]=ae,X[W]=F[W])}let oe=0;const me=ee.data;for(let ae=0;ae200)throw new Error(`absolute aspect ratio must be smaller than 200, got ${Math.max(y,M)/Math.min(y,M)}`);let B=Math.round(y/v)*v,K=Math.round(M/v)*v;if(B*K>A){const G=Math.sqrt(y*M/A);B=Math.floor(y/G/v)*v,K=Math.floor(M/G/v)*v}else if(B*KB?ee=Math.floor(B*j/A):B>A&&(j=Math.floor(A*ee/B)),await M.resize(ee,j,{resample:C}))}async crop_margin(M,v=200){const C=M.clone().grayscale(),A=(0,n.min)(C.data)[0],K=(0,n.max)(C.data)[0]-A;if(K===0)return M;const G=v/255;let j=C.width,ee=C.height,H=0,Z=0;const X=C.data;for(let oe=0;oethis.preprocess(B)));return{pixel_values:(0,o.stack)(C.map(B=>B.pixel_values),0),original_sizes:C.map(B=>B.original_size),reshaped_input_sizes:C.map(B=>B.reshaped_input_size)}}static async from_pretrained(M,v){const C=await(0,a.getModelJSON)(M,l.IMAGE_PROCESSOR_NAME,!0,v);return new this(C)}}},"./src/base/processing_utils.js":(e,r,t)=>{t.r(r),t.d(r,{Processor:()=>i});var s=t("./src/utils/constants.js"),o=t("./src/utils/generic.js"),n=t("./src/utils/hub.js");class i extends o.Callable{constructor(l,u){super(),this.config=l,this.components=u}get image_processor(){return this.components.image_processor}get tokenizer(){return this.components.tokenizer}get feature_extractor(){return this.components.feature_extractor}apply_chat_template(l,u={}){if(!this.tokenizer)throw new Error("Unable to apply chat template without a tokenizer.");return this.tokenizer.apply_chat_template(l,{tokenize:!1,...u})}batch_decode(...l){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.batch_decode(...l)}decode(...l){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.decode(...l)}async _call(l,...u){for(const p of[this.image_processor,this.feature_extractor,this.tokenizer])if(p)return p(l,...u);throw new Error("No image processor, feature extractor, or tokenizer found.")}static async from_pretrained(l,u){const[p,d]=await Promise.all([this.uses_processor_config?(0,n.getModelJSON)(l,s.PROCESSOR_NAME,!0,u):{},Promise.all(this.classes.filter(c=>c in this).map(async c=>{const f=await this[c].from_pretrained(l,u);return[c.replace(/_class$/,""),f]})).then(Object.fromEntries)]);return new this(p,d)}}te(i,"classes",["image_processor_class","tokenizer_class","feature_extractor_class"]),te(i,"uses_processor_config",!1)},"./src/configs.js":(e,r,t)=>{t.r(r),t.d(r,{AutoConfig:()=>u,PretrainedConfig:()=>l,getKeyValueShapes:()=>a});var s=t("./src/utils/core.js"),o=t("./src/utils/hub.js");async function n(p,d){return await(0,o.getModelJSON)(p,"config.json",!0,d)}function i(p){const d={};let c={};switch(p.model_type){case"llava":case"paligemma":case"gemma3":case"florence2":case"llava_onevision":case"idefics3":case"ultravox":case"smolvlm":c=i(p.text_config);break;case"moondream1":c=i(p.phi_config);break;case"musicgen":c=i(p.decoder);break;case"multi_modality":c=i(p.language_config);break;case"gpt2":case"gptj":case"jais":case"codegen":case"gpt_bigcode":d.num_heads="n_head",d.num_layers="n_layer",d.hidden_size="n_embd";break;case"gpt_neox":case"stablelm":case"opt":case"falcon":d.num_heads="num_attention_heads",d.num_layers="num_hidden_layers",d.hidden_size="hidden_size";break;case"llama":case"olmo":case"olmo2":case"mobilellm":case"granite":case"cohere":case"mistral":case"starcoder2":case"qwen2":case"qwen2_vl":case"phi":case"phi3":case"phi3_v":d.num_heads="num_key_value_heads",d.num_layers="num_hidden_layers",d.hidden_size="hidden_size",d.num_attention_heads="num_attention_heads";break;case"gemma":case"gemma2":case"gemma3_text":case"glm":case"helium":d.num_heads="num_key_value_heads",d.num_layers="num_hidden_layers",d.dim_kv="head_dim";break;case"openelm":d.num_heads="num_kv_heads",d.num_layers="num_transformer_layers",d.dim_kv="head_dim";break;case"gpt_neo":case"donut-swin":d.num_heads="num_heads",d.num_layers="num_layers",d.hidden_size="hidden_size";break;case"bloom":d.num_heads="n_head",d.num_layers="n_layer",d.hidden_size="hidden_size";break;case"mpt":d.num_heads="n_heads",d.num_layers="n_layers",d.hidden_size="d_model";break;case"exaone":d.num_heads="num_key_value_heads",d.num_layers="num_layers",d.dim_kv="head_dim",d.num_attention_heads="num_attention_heads";break;case"t5":case"mt5":case"longt5":d.num_decoder_layers="num_decoder_layers",d.num_decoder_heads="num_heads",d.decoder_dim_kv="d_kv",d.num_encoder_layers="num_layers",d.num_encoder_heads="num_heads",d.encoder_dim_kv="d_kv";break;case"bart":case"mbart":case"marian":case"whisper":case"lite-whisper":case"m2m_100":case"blenderbot":case"blenderbot-small":case"florence2_language":d.num_decoder_layers="decoder_layers",d.num_decoder_heads="decoder_attention_heads",d.decoder_hidden_size="d_model",d.num_encoder_layers="encoder_layers",d.num_encoder_heads="encoder_attention_heads",d.encoder_hidden_size="d_model";break;case"speecht5":d.num_decoder_layers="decoder_layers",d.num_decoder_heads="decoder_attention_heads",d.decoder_hidden_size="hidden_size",d.num_encoder_layers="encoder_layers",d.num_encoder_heads="encoder_attention_heads",d.encoder_hidden_size="hidden_size";break;case"trocr":d.num_encoder_layers=d.num_decoder_layers="decoder_layers",d.num_encoder_heads=d.num_decoder_heads="decoder_attention_heads",d.encoder_hidden_size=d.decoder_hidden_size="d_model";break;case"musicgen_decoder":d.num_encoder_layers=d.num_decoder_layers="num_hidden_layers",d.num_encoder_heads=d.num_decoder_heads="num_attention_heads",d.encoder_hidden_size=d.decoder_hidden_size="hidden_size";break;case"moonshine":d.num_decoder_layers="decoder_num_hidden_layers",d.num_decoder_heads="decoder_num_key_value_heads",d.num_encoder_layers="encoder_num_hidden_layers",d.num_encoder_heads="encoder_num_key_value_heads",d.encoder_hidden_size=d.decoder_hidden_size="hidden_size";break;case"vision-encoder-decoder":const _=i(p.decoder),T="num_decoder_layers"in _,k=(0,s.pick)(p,["model_type","is_encoder_decoder"]);return T?(k.num_decoder_layers=_.num_decoder_layers,k.num_decoder_heads=_.num_decoder_heads,k.decoder_hidden_size=_.decoder_hidden_size,k.num_encoder_layers=_.num_encoder_layers,k.num_encoder_heads=_.num_encoder_heads,k.encoder_hidden_size=_.encoder_hidden_size):(k.num_layers=_.num_layers,k.num_heads=_.num_heads,k.hidden_size=_.hidden_size),k}const f={...c,...(0,s.pick)(p,["model_type","multi_query","is_encoder_decoder"])};for(const _ in d)f[_]=p[d[_]];return f}function a(p,{prefix:d="past_key_values",batch_size:c=1}={}){const f={},_=p.normalized_config;if(_.is_encoder_decoder&&"num_encoder_heads"in _&&"num_decoder_heads"in _){const T=_.encoder_dim_kv??_.encoder_hidden_size/_.num_encoder_heads,k=_.decoder_dim_kv??_.decoder_hidden_size/_.num_decoder_heads,w=[c,_.num_encoder_heads,0,T],g=[c,_.num_decoder_heads,0,k];for(let S=0;S<_.num_decoder_layers;++S)f[`${d}.${S}.encoder.key`]=w,f[`${d}.${S}.encoder.value`]=w,f[`${d}.${S}.decoder.key`]=g,f[`${d}.${S}.decoder.value`]=g}else{const T=_.num_heads,k=_.num_layers,w=_.dim_kv??_.hidden_size/(_.num_attention_heads??T);if(_.model_type==="falcon"){const g=[c*T,0,w];for(let S=0;S{var C,A;t.r(r),t.d(r,{apis:()=>k,env:()=>M});var s=t("?569f"),o=t("?3f59"),n=t("?154a");const i="3.5.0",a=typeof window<"u"&&typeof window.document<"u",l=typeof self<"u"&&((C=self.constructor)==null?void 0:C.name)==="DedicatedWorkerGlobalScope",u=typeof self<"u"&&"caches"in self,p=typeof navigator<"u"&&"gpu"in navigator,d=typeof navigator<"u"&&"ml"in navigator,c=typeof process<"u",f=c&&((A=process==null?void 0:process.release)==null?void 0:A.name)==="node",_=!v(s),T=!v(o),k=Object.freeze({IS_BROWSER_ENV:a,IS_WEBWORKER_ENV:l,IS_WEB_CACHE_AVAILABLE:u,IS_WEBGPU_AVAILABLE:p,IS_WEBNN_AVAILABLE:d,IS_PROCESS_AVAILABLE:c,IS_NODE_ENV:f,IS_FS_AVAILABLE:_,IS_PATH_AVAILABLE:T}),w=_&&T;let g="./";if(w){const B=Object({url:self.location.href}).url;B?g=o.dirname(o.dirname(n.fileURLToPath(B))):typeof __dirname<"u"&&(g=o.dirname(__dirname))}const S=w?o.join(g,"/.cache/"):null,E="/models/",y=w?o.join(g,E):E,M={version:i,backends:{onnx:{}},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!(a||l),localModelPath:y,useFS:_,useBrowserCache:u,useFSCache:_,cacheDir:S,useCustomCache:!1,customCache:null};function v(B){return Object.keys(B).length===0}},"./src/generation/configuration_utils.js":(e,r,t)=>{t.r(r),t.d(r,{GenerationConfig:()=>o});var s=t("./src/utils/core.js");class o{constructor(i){te(this,"max_length",20);te(this,"max_new_tokens",null);te(this,"min_length",0);te(this,"min_new_tokens",null);te(this,"early_stopping",!1);te(this,"max_time",null);te(this,"do_sample",!1);te(this,"num_beams",1);te(this,"num_beam_groups",1);te(this,"penalty_alpha",null);te(this,"use_cache",!0);te(this,"temperature",1);te(this,"top_k",50);te(this,"top_p",1);te(this,"typical_p",1);te(this,"epsilon_cutoff",0);te(this,"eta_cutoff",0);te(this,"diversity_penalty",0);te(this,"repetition_penalty",1);te(this,"encoder_repetition_penalty",1);te(this,"length_penalty",1);te(this,"no_repeat_ngram_size",0);te(this,"bad_words_ids",null);te(this,"force_words_ids",null);te(this,"renormalize_logits",!1);te(this,"constraints",null);te(this,"forced_bos_token_id",null);te(this,"forced_eos_token_id",null);te(this,"remove_invalid_values",!1);te(this,"exponential_decay_length_penalty",null);te(this,"suppress_tokens",null);te(this,"streamer",null);te(this,"begin_suppress_tokens",null);te(this,"forced_decoder_ids",null);te(this,"guidance_scale",null);te(this,"num_return_sequences",1);te(this,"output_attentions",!1);te(this,"output_hidden_states",!1);te(this,"output_scores",!1);te(this,"return_dict_in_generate",!1);te(this,"pad_token_id",null);te(this,"bos_token_id",null);te(this,"eos_token_id",null);te(this,"encoder_no_repeat_ngram_size",0);te(this,"decoder_start_token_id",null);te(this,"generation_kwargs",{});Object.assign(this,(0,s.pick)(i,Object.getOwnPropertyNames(this)))}}},"./src/generation/logits_process.js":(e,r,t)=>{t.r(r),t.d(r,{ClassifierFreeGuidanceLogitsProcessor:()=>w,ForcedBOSTokenLogitsProcessor:()=>l,ForcedEOSTokenLogitsProcessor:()=>u,LogitsProcessor:()=>n,LogitsProcessorList:()=>a,LogitsWarper:()=>i,MinLengthLogitsProcessor:()=>_,MinNewTokensLengthLogitsProcessor:()=>T,NoBadWordsLogitsProcessor:()=>k,NoRepeatNGramLogitsProcessor:()=>c,RepetitionPenaltyLogitsProcessor:()=>f,SuppressTokensAtBeginLogitsProcessor:()=>p,TemperatureLogitsWarper:()=>g,TopKLogitsWarper:()=>E,TopPLogitsWarper:()=>S,WhisperTimeStampLogitsProcessor:()=>d});var s=t("./src/utils/generic.js");t("./src/utils/tensor.js");var o=t("./src/utils/maths.js");class n extends s.Callable{_call(M,v){throw Error("`_call` should be implemented in a subclass")}}class i extends s.Callable{_call(M,v){throw Error("`_call` should be implemented in a subclass")}}class a extends s.Callable{constructor(){super(),this.processors=[]}push(M){this.processors.push(M)}extend(M){this.processors.push(...M)}_call(M,v){let C=v;for(const A of this.processors)C=A(M,C);return C}[Symbol.iterator](){return this.processors.values()}}class l extends n{constructor(M){super(),this.bos_token_id=M}_call(M,v){for(let C=0;C=1&&B[B.length-1]>=this.timestamp_begin,G=B.length<2||B[B.length-2]>=this.timestamp_begin;if(K&&(G?A.subarray(this.timestamp_begin).fill(-1/0):A.subarray(0,this.eos_token_id).fill(-1/0)),M[C].length===this.begin_index&&this.max_initial_timestamp_index!==null){const Z=this.timestamp_begin+this.max_initial_timestamp_index;A.subarray(Z+1).fill(-1/0)}const j=(0,o.log_softmax)(A),ee=Math.log(j.subarray(this.timestamp_begin).map(Math.exp).reduce((Z,X)=>Z+X)),H=(0,o.max)(j.subarray(0,this.timestamp_begin))[0];ee>H&&A.subarray(0,this.timestamp_begin).fill(-1/0)}return v}}class c extends n{constructor(M){super(),this.no_repeat_ngram_size=M}getNgrams(M){const v=M.length,C=[];for(let B=0;B1 to use the classifier free guidance processor, got guidance scale ${M}.`);this.guidance_scale=M}_call(M,v){if(v.dims[0]!==2*M.length)throw new Error(`Logits should have twice the batch size of the input ids, the first half of batches corresponding to the conditional inputs, and the second half of batches corresponding to the unconditional inputs. Got batch size ${v.dims[0]} for the logits and ${M.length} for the input ids.`);const C=M.length,A=v.slice([0,C],null),B=v.slice([C,v.dims[0]],null);for(let K=0;K1)throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${M}`);if(!Number.isInteger(C)||C<1)throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${C}`);this.top_p=M,this.filter_value=v,this.min_tokens_to_keep=C}}class E extends i{constructor(M,{filter_value:v=-1/0,min_tokens_to_keep:C=1}={}){if(super(),!Number.isInteger(M)||M<0)throw new Error(`\`top_k\` must be a positive integer, but is ${M}`);this.top_k=Math.max(M,C),this.filter_value=v}}},"./src/generation/logits_sampler.js":(e,r,t)=>{t.r(r),t.d(r,{LogitsSampler:()=>i});var s=t("./src/utils/generic.js"),o=t("./src/utils/tensor.js"),n=t("./src/utils/maths.js");t("./src/generation/configuration_utils.js");class i extends s.Callable{constructor(d){super(),this.generation_config=d}async _call(d){return this.sample(d)}async sample(d){throw Error("sample should be implemented in subclasses.")}getLogits(d,c){let f=d.dims.at(-1),_=d.data;if(c===-1)_=_.slice(-f);else{let T=c*f;_=_.slice(T,T+f)}return _}randomSelect(d){let c=0;for(let _=0;_1)return new u(d);if(d.num_return_sequences>1)throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${d.num_return_sequences}.`);return new a(d)}}class a extends i{async sample(d){const c=(0,n.max)(d.data)[1];return[[BigInt(c),0]]}}class l extends i{async sample(d){let c=d.dims.at(-1);this.generation_config.top_k>0&&(c=Math.min(this.generation_config.top_k,c));const[f,_]=await(0,o.topk)(d,c),T=(0,n.softmax)(f.data);return Array.from({length:this.generation_config.num_beams},()=>{const k=this.randomSelect(T);return[_.data[k],Math.log(T[k])]})}}class u extends i{async sample(d){let c=d.dims.at(-1);this.generation_config.top_k>0&&(c=Math.min(this.generation_config.top_k,c));const[f,_]=await(0,o.topk)(d,c),T=(0,n.softmax)(f.data);return Array.from({length:this.generation_config.num_beams},(k,w)=>[_.data[w],Math.log(T[w])])}}},"./src/generation/stopping_criteria.js":(e,r,t)=>{t.r(r),t.d(r,{EosTokenCriteria:()=>a,InterruptableStoppingCriteria:()=>l,MaxLengthCriteria:()=>i,StoppingCriteria:()=>o,StoppingCriteriaList:()=>n});var s=t("./src/utils/generic.js");class o extends s.Callable{_call(p,d){throw Error("StoppingCriteria needs to be subclassed")}}class n extends s.Callable{constructor(){super(),this.criteria=[]}push(p){this.criteria.push(p)}extend(p){p instanceof n?p=p.criteria:p instanceof o&&(p=[p]),this.criteria.push(...p)}_call(p,d){const c=new Array(p.length).fill(!1);for(const f of this.criteria){const _=f(p,d);for(let T=0;Td.length>=this.max_length)}}class a extends o{constructor(p){super(),Array.isArray(p)||(p=[p]),this.eos_token_id=p}_call(p,d){return p.map(c=>{const f=c.at(-1);return this.eos_token_id.some(_=>f==_)})}}class l extends o{constructor(){super(),this.interrupted=!1}interrupt(){this.interrupted=!0}reset(){this.interrupted=!1}_call(p,d){return new Array(p.length).fill(this.interrupted)}}},"./src/generation/streamers.js":(e,r,t)=>{t.r(r),t.d(r,{BaseStreamer:()=>i,TextStreamer:()=>l,WhisperTextStreamer:()=>u});var s=t("./src/utils/core.js"),o=t("./src/tokenizers.js"),n=t("./src/env.js");class i{put(d){throw Error("Not implemented")}end(){throw Error("Not implemented")}}const a=n.apis.IS_PROCESS_AVAILABLE?p=>process.stdout.write(p):p=>console.log(p);class l extends i{constructor(d,{skip_prompt:c=!1,callback_function:f=null,token_callback_function:_=null,skip_special_tokens:T=!0,decode_kwargs:k={},...w}={}){super(),this.tokenizer=d,this.skip_prompt=c,this.callback_function=f??a,this.token_callback_function=_,this.decode_kwargs={skip_special_tokens:T,...k,...w},this.token_cache=[],this.print_len=0,this.next_tokens_are_prompt=!0}put(d){var k;if(d.length>1)throw Error("TextStreamer only supports batch size of 1");const c=this.next_tokens_are_prompt;if(c&&(this.next_tokens_are_prompt=!1,this.skip_prompt))return;const f=d[0];(k=this.token_callback_function)==null||k.call(this,f),this.token_cache=(0,s.mergeArrays)(this.token_cache,f);const _=this.tokenizer.decode(this.token_cache,this.decode_kwargs);let T;c||_.endsWith(` +`)?(T=_.slice(this.print_len),this.token_cache=[],this.print_len=0):_.length>0&&(0,o.is_chinese_char)(_.charCodeAt(_.length-1))?(T=_.slice(this.print_len),this.print_len+=T.length):(T=_.slice(this.print_len,_.lastIndexOf(" ")+1),this.print_len+=T.length),this.on_finalized_text(T,!1)}end(){let d;this.token_cache.length>0?(d=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len),this.token_cache=[],this.print_len=0):d="",this.next_tokens_are_prompt=!0,this.on_finalized_text(d,!0)}on_finalized_text(d,c){var f,_;d.length>0&&((f=this.callback_function)==null||f.call(this,d)),c&&this.callback_function===a&&n.apis.IS_PROCESS_AVAILABLE&&((_=this.callback_function)==null||_.call(this,` +`))}}class u extends l{constructor(d,{skip_prompt:c=!1,callback_function:f=null,token_callback_function:_=null,on_chunk_start:T=null,on_chunk_end:k=null,on_finalize:w=null,time_precision:g=.02,skip_special_tokens:S=!0,decode_kwargs:E={}}={}){super(d,{skip_prompt:c,skip_special_tokens:S,callback_function:f,token_callback_function:_,decode_kwargs:E}),this.timestamp_begin=d.timestamp_begin,this.on_chunk_start=T,this.on_chunk_end=k,this.on_finalize=w,this.time_precision=g,this.waiting_for_timestamp=!1}put(d){var f,_;if(d.length>1)throw Error("WhisperTextStreamer only supports batch size of 1");const c=d[0];if(c.length===1){const T=Number(c[0])-this.timestamp_begin;if(T>=0){const k=T*this.time_precision;this.waiting_for_timestamp?(f=this.on_chunk_end)==null||f.call(this,k):(_=this.on_chunk_start)==null||_.call(this,k),this.waiting_for_timestamp=!this.waiting_for_timestamp,d=[[]]}}return super.put(d)}end(){var d;super.end(),(d=this.on_finalize)==null||d.call(this)}}},"./src/models.js":(e,r,t)=>{t.r(r),t.d(r,{ASTForAudioClassification:()=>Ii,ASTModel:()=>ki,ASTPreTrainedModel:()=>To,AlbertForMaskedLM:()=>N,AlbertForQuestionAnswering:()=>$,AlbertForSequenceClassification:()=>he,AlbertModel:()=>vn,AlbertPreTrainedModel:()=>xs,AutoModel:()=>fd,AutoModelForAudioClassification:()=>M0,AutoModelForAudioFrameClassification:()=>y0,AutoModelForAudioTextToText:()=>k0,AutoModelForCTC:()=>w0,AutoModelForCausalLM:()=>a0,AutoModelForDepthEstimation:()=>E0,AutoModelForDocumentQuestionAnswering:()=>v0,AutoModelForImageClassification:()=>c0,AutoModelForImageFeatureExtraction:()=>S0,AutoModelForImageMatting:()=>x0,AutoModelForImageSegmentation:()=>p0,AutoModelForImageTextToText:()=>$0,AutoModelForImageToImage:()=>T0,AutoModelForMaskGeneration:()=>g0,AutoModelForMaskedLM:()=>l0,AutoModelForNormalEstimation:()=>P0,AutoModelForObjectDetection:()=>_0,AutoModelForPoseEstimation:()=>C0,AutoModelForQuestionAnswering:()=>u0,AutoModelForSemanticSegmentation:()=>h0,AutoModelForSeq2SeqLM:()=>s0,AutoModelForSequenceClassification:()=>t0,AutoModelForSpeechSeq2Seq:()=>n0,AutoModelForTextToSpectrogram:()=>o0,AutoModelForTextToWaveform:()=>i0,AutoModelForTokenClassification:()=>r0,AutoModelForUniversalSegmentation:()=>m0,AutoModelForVision2Seq:()=>d0,AutoModelForXVector:()=>b0,AutoModelForZeroShotObjectDetection:()=>f0,BartForConditionalGeneration:()=>jt,BartForSequenceClassification:()=>kt,BartModel:()=>Pt,BartPretrainedModel:()=>xt,BaseModelOutput:()=>xe,BeitForImageClassification:()=>Rw,BeitModel:()=>Bw,BeitPreTrainedModel:()=>Ou,BertForMaskedLM:()=>Ae,BertForQuestionAnswering:()=>Ve,BertForSequenceClassification:()=>Fe,BertForTokenClassification:()=>ze,BertModel:()=>Se,BertPreTrainedModel:()=>be,BlenderbotForConditionalGeneration:()=>rr,BlenderbotModel:()=>Dt,BlenderbotPreTrainedModel:()=>Xr,BlenderbotSmallForConditionalGeneration:()=>Rr,BlenderbotSmallModel:()=>Qr,BlenderbotSmallPreTrainedModel:()=>wr,BloomForCausalLM:()=>aw,BloomModel:()=>iw,BloomPreTrainedModel:()=>vu,CLIPModel:()=>Ni,CLIPPreTrainedModel:()=>Fs,CLIPSegForImageSegmentation:()=>zo,CLIPSegModel:()=>Lo,CLIPSegPreTrainedModel:()=>qn,CLIPTextModel:()=>pu,CLIPTextModelWithProjection:()=>Vi,CLIPVisionModel:()=>hu,CLIPVisionModelWithProjection:()=>Ui,CamembertForMaskedLM:()=>Ft,CamembertForQuestionAnswering:()=>ys,CamembertForSequenceClassification:()=>ds,CamembertForTokenClassification:()=>cs,CamembertModel:()=>bs,CamembertPreTrainedModel:()=>Ar,CausalLMOutput:()=>In,CausalLMOutputWithPast:()=>Vx,ChineseCLIPModel:()=>Gi,ChineseCLIPPreTrainedModel:()=>Wi,ClapAudioModelWithProjection:()=>zb,ClapModel:()=>Db,ClapPreTrainedModel:()=>ta,ClapTextModelWithProjection:()=>Lb,CodeGenForCausalLM:()=>$n,CodeGenModel:()=>Go,CodeGenPreTrainedModel:()=>Zn,CohereForCausalLM:()=>Ug,CohereModel:()=>Vg,CoherePreTrainedModel:()=>mu,ConvBertForMaskedLM:()=>Ot,ConvBertForQuestionAnswering:()=>Ms,ConvBertForSequenceClassification:()=>ur,ConvBertForTokenClassification:()=>ls,ConvBertModel:()=>Gt,ConvBertPreTrainedModel:()=>wt,ConvNextForImageClassification:()=>IM,ConvNextModel:()=>kM,ConvNextPreTrainedModel:()=>qu,ConvNextV2ForImageClassification:()=>FM,ConvNextV2Model:()=>AM,ConvNextV2PreTrainedModel:()=>Xu,DPTForDepthEstimation:()=>pM,DPTModel:()=>cM,DPTPreTrainedModel:()=>Gu,DacDecoderModel:()=>Ey,DacDecoderOutput:()=>vy,DacEncoderModel:()=>Ty,DacEncoderOutput:()=>yy,DacModel:()=>xy,DacPreTrainedModel:()=>la,DebertaForMaskedLM:()=>Qe,DebertaForQuestionAnswering:()=>zr,DebertaForSequenceClassification:()=>tt,DebertaForTokenClassification:()=>Rt,DebertaModel:()=>De,DebertaPreTrainedModel:()=>Qt,DebertaV2ForMaskedLM:()=>hs,DebertaV2ForQuestionAnswering:()=>_s,DebertaV2ForSequenceClassification:()=>Kr,DebertaV2ForTokenClassification:()=>ms,DebertaV2Model:()=>ps,DebertaV2PreTrainedModel:()=>Sr,DecisionTransformerModel:()=>ny,DecisionTransformerPreTrainedModel:()=>sy,DeiTForImageClassification:()=>tM,DeiTModel:()=>eM,DeiTPreTrainedModel:()=>Nu,DepthAnythingForDepthEstimation:()=>mM,DepthAnythingPreTrainedModel:()=>hM,DepthProForDepthEstimation:()=>MM,DepthProPreTrainedModel:()=>wM,DetrForObjectDetection:()=>Nw,DetrForSegmentation:()=>Du,DetrModel:()=>jw,DetrObjectDetectionOutput:()=>Lu,DetrPreTrainedModel:()=>qi,DetrSegmentationOutput:()=>Vw,Dinov2ForImageClassification:()=>DM,Dinov2Model:()=>OM,Dinov2PreTrainedModel:()=>Qu,Dinov2WithRegistersForImageClassification:()=>zM,Dinov2WithRegistersModel:()=>LM,Dinov2WithRegistersPreTrainedModel:()=>Ju,DistilBertForMaskedLM:()=>ks,DistilBertForQuestionAnswering:()=>$s,DistilBertForSequenceClassification:()=>cn,DistilBertForTokenClassification:()=>xr,DistilBertModel:()=>vr,DistilBertPreTrainedModel:()=>Hr,DonutSwinModel:()=>$M,DonutSwinPreTrainedModel:()=>SM,EfficientNetForImageClassification:()=>Wb,EfficientNetModel:()=>Ub,EfficientNetPreTrainedModel:()=>ad,ElectraForMaskedLM:()=>Ss,ElectraForQuestionAnswering:()=>us,ElectraForSequenceClassification:()=>Ns,ElectraForTokenClassification:()=>at,ElectraModel:()=>js,ElectraPreTrainedModel:()=>Ir,EsmForMaskedLM:()=>pn,EsmForSequenceClassification:()=>Fr,EsmForTokenClassification:()=>hn,EsmModel:()=>Vs,EsmPreTrainedModel:()=>fr,ExaoneForCausalLM:()=>L,ExaoneModel:()=>I,ExaonePreTrainedModel:()=>x,FalconForCausalLM:()=>Ob,FalconModel:()=>Fb,FalconPreTrainedModel:()=>nd,FastViTForImageClassification:()=>Cw,FastViTModel:()=>Pw,FastViTPreTrainedModel:()=>$u,Florence2ForConditionalGeneration:()=>ko,Florence2PreTrainedModel:()=>Li,GLPNForDepthEstimation:()=>CM,GLPNModel:()=>PM,GLPNPreTrainedModel:()=>Hu,GPT2LMHeadModel:()=>Bo,GPT2Model:()=>Ki,GPT2PreTrainedModel:()=>Xn,GPTBigCodeForCausalLM:()=>Wo,GPTBigCodeModel:()=>Yn,GPTBigCodePreTrainedModel:()=>Jn,GPTJForCausalLM:()=>Uo,GPTJModel:()=>Vo,GPTJPreTrainedModel:()=>Sn,GPTNeoForCausalLM:()=>No,GPTNeoModel:()=>jo,GPTNeoPreTrainedModel:()=>Ro,GPTNeoXForCausalLM:()=>Cn,GPTNeoXModel:()=>Nr,GPTNeoXPreTrainedModel:()=>Xs,Gemma2ForCausalLM:()=>Hg,Gemma2Model:()=>Kg,Gemma2PreTrainedModel:()=>fu,Gemma3ForCausalLM:()=>Xg,Gemma3Model:()=>qg,Gemma3PreTrainedModel:()=>gu,GemmaForCausalLM:()=>Gg,GemmaModel:()=>Wg,GemmaPreTrainedModel:()=>_u,GlmForCausalLM:()=>h,GlmModel:()=>Xo,GlmPreTrainedModel:()=>ro,GraniteForCausalLM:()=>Hi,GraniteModel:()=>Os,GranitePreTrainedModel:()=>sr,GroundingDinoForObjectDetection:()=>RM,GroundingDinoPreTrainedModel:()=>BM,GroupViTModel:()=>Ew,GroupViTPreTrainedModel:()=>Tw,HeliumForCausalLM:()=>qo,HeliumModel:()=>Ho,HeliumPreTrainedModel:()=>to,HieraForImageClassification:()=>sM,HieraModel:()=>rM,HieraPreTrainedModel:()=>Vu,HubertForCTC:()=>_b,HubertForSequenceClassification:()=>fb,HubertModel:()=>mb,HubertPreTrainedModel:()=>Sx,IJepaForImageClassification:()=>_w,IJepaModel:()=>mw,IJepaPreTrainedModel:()=>Pu,Idefics3ForConditionalGeneration:()=>Ks,Idefics3PreTrainedModel:()=>Ri,ImageMattingOutput:()=>A0,JAISLMHeadModel:()=>nt,JAISModel:()=>Pn,JAISPreTrainedModel:()=>Qn,JinaCLIPModel:()=>Hn,JinaCLIPPreTrainedModel:()=>qs,JinaCLIPTextModel:()=>Oo,JinaCLIPVisionModel:()=>Do,LiteWhisperForConditionalGeneration:()=>Fi,LlamaForCausalLM:()=>Ko,LlamaModel:()=>eo,LlamaPreTrainedModel:()=>kn,LlavaForConditionalGeneration:()=>Tn,LlavaOnevisionForConditionalGeneration:()=>$o,LlavaPreTrainedModel:()=>Di,LongT5ForConditionalGeneration:()=>He,LongT5Model:()=>je,LongT5PreTrainedModel:()=>ve,M2M100ForConditionalGeneration:()=>XM,M2M100Model:()=>qM,M2M100PreTrainedModel:()=>ed,MBartForCausalLM:()=>Nt,MBartForConditionalGeneration:()=>cr,MBartForSequenceClassification:()=>pr,MBartModel:()=>br,MBartPreTrainedModel:()=>Ht,MPNetForMaskedLM:()=>_n,MPNetForQuestionAnswering:()=>wn,MPNetForSequenceClassification:()=>fn,MPNetForTokenClassification:()=>gn,MPNetModel:()=>mn,MPNetPreTrainedModel:()=>Br,MT5ForConditionalGeneration:()=>dt,MT5Model:()=>Je,MT5PreTrainedModel:()=>We,MarianMTModel:()=>HM,MarianModel:()=>KM,MarianPreTrainedModel:()=>Zu,MaskFormerForInstanceSegmentation:()=>EM,MaskFormerModel:()=>TM,MaskFormerPreTrainedModel:()=>Ku,MaskedLMOutput:()=>Mr,Metric3DForDepthEstimation:()=>yM,Metric3DPreTrainedModel:()=>bM,Metric3Dv2ForDepthEstimation:()=>xM,Metric3Dv2PreTrainedModel:()=>vM,MgpstrForSceneTextRecognition:()=>uy,MgpstrModelOutput:()=>ay,MgpstrPreTrainedModel:()=>ly,MimiDecoderModel:()=>by,MimiDecoderOutput:()=>gy,MimiEncoderModel:()=>My,MimiEncoderOutput:()=>fy,MimiModel:()=>wy,MimiPreTrainedModel:()=>aa,MistralForCausalLM:()=>kb,MistralModel:()=>$b,MistralPreTrainedModel:()=>rd,MobileBertForMaskedLM:()=>Is,MobileBertForQuestionAnswering:()=>gr,MobileBertForSequenceClassification:()=>dr,MobileBertModel:()=>Tr,MobileBertPreTrainedModel:()=>qr,MobileLLMForCausalLM:()=>Te,MobileLLMModel:()=>ue,MobileLLMPreTrainedModel:()=>U,MobileNetV1ForImageClassification:()=>Kb,MobileNetV1ForSemanticSegmentation:()=>Hb,MobileNetV1Model:()=>Gb,MobileNetV1PreTrainedModel:()=>sa,MobileNetV2ForImageClassification:()=>Xb,MobileNetV2ForSemanticSegmentation:()=>Qb,MobileNetV2Model:()=>qb,MobileNetV2PreTrainedModel:()=>na,MobileNetV3ForImageClassification:()=>Yb,MobileNetV3ForSemanticSegmentation:()=>Zb,MobileNetV3Model:()=>Jb,MobileNetV3PreTrainedModel:()=>oa,MobileNetV4ForImageClassification:()=>ty,MobileNetV4ForSemanticSegmentation:()=>ry,MobileNetV4Model:()=>ey,MobileNetV4PreTrainedModel:()=>ia,MobileViTForImageClassification:()=>Iw,MobileViTModel:()=>kw,MobileViTPreTrainedModel:()=>ku,MobileViTV2ForImageClassification:()=>Fw,MobileViTV2Model:()=>Aw,MobileViTV2PreTrainedModel:()=>Iu,ModelOutput:()=>pe,ModernBertForMaskedLM:()=>z,ModernBertForSequenceClassification:()=>J,ModernBertForTokenClassification:()=>le,ModernBertModel:()=>Y,ModernBertPreTrainedModel:()=>O,Moondream1ForConditionalGeneration:()=>Gs,MoonshineForConditionalGeneration:()=>Co,MoonshineModel:()=>Oi,MoonshinePreTrainedModel:()=>Gn,MptForCausalLM:()=>uw,MptModel:()=>lw,MptPreTrainedModel:()=>xu,MultiModalityCausalLM:()=>iy,MultiModalityPreTrainedModel:()=>oy,MusicgenForCausalLM:()=>Ax,MusicgenForConditionalGeneration:()=>ud,MusicgenModel:()=>Ix,MusicgenPreTrainedModel:()=>ld,NomicBertModel:()=>Ee,NomicBertPreTrainedModel:()=>ye,OPTForCausalLM:()=>cw,OPTModel:()=>dw,OPTPreTrainedModel:()=>Tu,Olmo2ForCausalLM:()=>It,Olmo2Model:()=>Tt,Olmo2PreTrainedModel:()=>ht,OlmoForCausalLM:()=>Ze,OlmoModel:()=>Ke,OlmoPreTrainedModel:()=>Oe,OpenELMForCausalLM:()=>Jg,OpenELMModel:()=>Qg,OpenELMPreTrainedModel:()=>wu,OwlViTForObjectDetection:()=>Dw,OwlViTModel:()=>Ow,OwlViTPreTrainedModel:()=>Au,Owlv2ForObjectDetection:()=>zw,Owlv2Model:()=>Lw,Owlv2PreTrainedModel:()=>Fu,PaliGemmaForConditionalGeneration:()=>Bi,PaliGemmaPreTrainedModel:()=>zi,PatchTSMixerForPrediction:()=>hy,PatchTSMixerModel:()=>py,PatchTSMixerPreTrainedModel:()=>cd,PatchTSTForPrediction:()=>cy,PatchTSTModel:()=>dy,PatchTSTPreTrainedModel:()=>dd,Phi3ForCausalLM:()=>ow,Phi3Model:()=>nw,Phi3PreTrainedModel:()=>yu,Phi3VForCausalLM:()=>Io,Phi3VPreTrainedModel:()=>ji,PhiForCausalLM:()=>sw,PhiModel:()=>rw,PhiPreTrainedModel:()=>bu,PreTrainedModel:()=>R,PretrainedMixin:()=>Ct,PvtForImageClassification:()=>Mw,PvtModel:()=>ww,PvtPreTrainedModel:()=>Cu,PyAnnoteForAudioFrameClassification:()=>tb,PyAnnoteModel:()=>eb,PyAnnotePreTrainedModel:()=>td,QuestionAnsweringModelOutput:()=>Er,Qwen2ForCausalLM:()=>Zg,Qwen2Model:()=>Yg,Qwen2PreTrainedModel:()=>Mu,Qwen2VLForConditionalGeneration:()=>tw,Qwen2VLPreTrainedModel:()=>ew,RFDetrForObjectDetection:()=>Xw,RFDetrModel:()=>qw,RFDetrObjectDetectionOutput:()=>Qw,RFDetrPreTrainedModel:()=>Ru,RTDetrForObjectDetection:()=>Ww,RTDetrModel:()=>Uw,RTDetrObjectDetectionOutput:()=>Xi,RTDetrPreTrainedModel:()=>zu,RTDetrV2ForObjectDetection:()=>Kw,RTDetrV2Model:()=>Gw,RTDetrV2ObjectDetectionOutput:()=>Hw,RTDetrV2PreTrainedModel:()=>Bu,ResNetForImageClassification:()=>oM,ResNetModel:()=>nM,ResNetPreTrainedModel:()=>Uu,RoFormerForMaskedLM:()=>Re,RoFormerForQuestionAnswering:()=>lt,RoFormerForSequenceClassification:()=>Xe,RoFormerForTokenClassification:()=>Ge,RoFormerModel:()=>Ie,RoFormerPreTrainedModel:()=>ke,RobertaForMaskedLM:()=>or,RobertaForQuestionAnswering:()=>er,RobertaForSequenceClassification:()=>Vt,RobertaForTokenClassification:()=>Zt,RobertaModel:()=>jr,RobertaPreTrainedModel:()=>Yt,SamImageSegmentationOutput:()=>GM,SamModel:()=>WM,SamPreTrainedModel:()=>UM,SapiensForDepthEstimation:()=>fM,SapiensForNormalEstimation:()=>gM,SapiensForSemanticSegmentation:()=>_M,SapiensPreTrainedModel:()=>Ji,SegformerForImageClassification:()=>Rb,SegformerForSemanticSegmentation:()=>jb,SegformerModel:()=>kx,SegformerPreTrainedModel:()=>ra,Seq2SeqLMOutput:()=>Nx,SequenceClassifierOutput:()=>_t,SiglipModel:()=>En,SiglipPreTrainedModel:()=>Ao,SiglipTextModel:()=>Hs,SiglipVisionModel:()=>Fo,SmolVLMForConditionalGeneration:()=>Kn,SnacDecoderModel:()=>Sy,SnacEncoderModel:()=>Cy,SnacModel:()=>Py,SnacPreTrainedModel:()=>ua,SpeechT5ForSpeechToText:()=>Tb,SpeechT5ForTextToSpeech:()=>Eb,SpeechT5HifiGan:()=>Pb,SpeechT5Model:()=>$x,SpeechT5PreTrainedModel:()=>ea,SqueezeBertForMaskedLM:()=>Us,SqueezeBertForQuestionAnswering:()=>yn,SqueezeBertForSequenceClassification:()=>bn,SqueezeBertModel:()=>Mn,SqueezeBertPreTrainedModel:()=>vs,StableLmForCausalLM:()=>Vb,StableLmModel:()=>Nb,StableLmPreTrainedModel:()=>id,Starcoder2ForCausalLM:()=>Ab,Starcoder2Model:()=>Ib,Starcoder2PreTrainedModel:()=>sd,StyleTextToSpeech2Model:()=>xb,StyleTextToSpeech2PreTrainedModel:()=>vb,Swin2SRForImageSuperResolution:()=>dM,Swin2SRModel:()=>uM,Swin2SRPreTrainedModel:()=>Wu,SwinForImageClassification:()=>aM,SwinForSemanticSegmentation:()=>lM,SwinModel:()=>iM,SwinPreTrainedModel:()=>Qi,T5ForConditionalGeneration:()=>de,T5Model:()=>ie,T5PreTrainedModel:()=>Q,TableTransformerForObjectDetection:()=>Yw,TableTransformerModel:()=>Jw,TableTransformerObjectDetectionOutput:()=>Zw,TableTransformerPreTrainedModel:()=>ju,TokenClassifierOutput:()=>hr,TrOCRForCausalLM:()=>Sb,TrOCRPreTrainedModel:()=>Cb,UltravoxModel:()=>_y,UltravoxPreTrainedModel:()=>my,UniSpeechForCTC:()=>ob,UniSpeechForSequenceClassification:()=>ib,UniSpeechModel:()=>nb,UniSpeechPreTrainedModel:()=>Yi,UniSpeechSatForAudioFrameClassification:()=>db,UniSpeechSatForCTC:()=>lb,UniSpeechSatForSequenceClassification:()=>ub,UniSpeechSatModel:()=>ab,UniSpeechSatPreTrainedModel:()=>Qo,ViTForImageClassification:()=>hw,ViTMAEModel:()=>yw,ViTMAEPreTrainedModel:()=>bw,ViTMSNForImageClassification:()=>xw,ViTMSNModel:()=>vw,ViTMSNPreTrainedModel:()=>Su,ViTModel:()=>pw,ViTPreTrainedModel:()=>Eu,VisionEncoderDecoderModel:()=>So,VitMatteForImageMatting:()=>$w,VitMattePreTrainedModel:()=>Sw,VitPoseForPoseEstimation:()=>gw,VitPosePreTrainedModel:()=>fw,VitsModel:()=>od,VitsModelOutput:()=>F0,VitsPreTrainedModel:()=>Bb,Wav2Vec2BertForCTC:()=>pb,Wav2Vec2BertForSequenceClassification:()=>hb,Wav2Vec2BertModel:()=>cb,Wav2Vec2BertPreTrainedModel:()=>Zi,Wav2Vec2ForAudioFrameClassification:()=>ZM,Wav2Vec2ForCTC:()=>JM,Wav2Vec2ForSequenceClassification:()=>YM,Wav2Vec2Model:()=>QM,Wav2Vec2PreTrainedModel:()=>Qs,WavLMForAudioFrameClassification:()=>yb,WavLMForCTC:()=>wb,WavLMForSequenceClassification:()=>Mb,WavLMForXVector:()=>bb,WavLMModel:()=>gb,WavLMPreTrainedModel:()=>so,WeSpeakerResNetModel:()=>sb,WeSpeakerResNetPreTrainedModel:()=>rb,WhisperForConditionalGeneration:()=>Po,WhisperModel:()=>Ai,WhisperPreTrainedModel:()=>Eo,XLMForQuestionAnswering:()=>Ti,XLMForSequenceClassification:()=>vi,XLMForTokenClassification:()=>xi,XLMModel:()=>Ws,XLMPreTrainedModel:()=>tr,XLMRobertaForMaskedLM:()=>Pi,XLMRobertaForQuestionAnswering:()=>$i,XLMRobertaForSequenceClassification:()=>Ci,XLMRobertaForTokenClassification:()=>Si,XLMRobertaModel:()=>Ei,XLMRobertaPreTrainedModel:()=>As,XLMWithLMHeadModel:()=>xn,XVectorOutput:()=>I0,YolosForObjectDetection:()=>NM,YolosModel:()=>jM,YolosObjectDetectionOutput:()=>VM,YolosPreTrainedModel:()=>Yu});var s=t("./src/configs.js"),o=t("./src/backends/onnx.js"),n=t("./src/utils/dtypes.js"),i=t("./src/utils/generic.js"),a=t("./src/utils/core.js"),l=t("./src/utils/hub.js"),u=t("./src/utils/constants.js"),p=t("./src/generation/logits_process.js"),d=t("./src/generation/configuration_utils.js"),c=t("./src/utils/tensor.js"),f=t("./src/utils/image.js"),_=t("./src/utils/maths.js"),T=t("./src/generation/stopping_criteria.js"),k=t("./src/generation/logits_sampler.js"),w=t("./src/env.js"),g=t("./src/models/whisper/generation_whisper.js"),S=t("./src/models/whisper/common_whisper.js");const E={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,MaskGeneration:5,ImageTextToText:6,Musicgen:7,MultiModality:8,Phi3V:9,AudioTextToText:10,AutoEncoder:11},y=new Map,M=new Map,v=new Map;async function C(b,P,D){var mr;let ne=((mr=D.config)==null?void 0:mr["transformers.js_config"])??{},ge=D.device??ne.device;ge&&typeof ge!="string"&&(ge.hasOwnProperty(P)?ge=ge[P]:(console.warn(`device not specified for "${P}". Using the default device.`),ge=null));const fe=ge??(w.apis.IS_NODE_ENV?"cpu":"wasm"),Ce=(0,o.deviceToExecutionProviders)(fe),Le=ne.device_config??{};Le.hasOwnProperty(fe)&&(ne={...ne,...Le[fe]});let Ne=D.dtype??ne.dtype;if(typeof Ne!="string"&&(Ne&&Ne.hasOwnProperty(P)?Ne=Ne[P]:(Ne=n.DEFAULT_DEVICE_DTYPE_MAPPING[fe]??n.DATA_TYPES.fp32,console.warn(`dtype not specified for "${P}". Using the default dtype (${Ne}) for this device (${fe}).`))),Ne===n.DATA_TYPES.auto){let bt=ne.dtype;typeof bt!="string"&&(bt=bt==null?void 0:bt[P]),bt&&bt!==n.DATA_TYPES.auto&&n.DATA_TYPES.hasOwnProperty(bt)?Ne=bt:Ne=n.DEFAULT_DEVICE_DTYPE_MAPPING[fe]??n.DATA_TYPES.fp32}const qe=Ne;if(n.DEFAULT_DTYPE_SUFFIX_MAPPING.hasOwnProperty(qe)){if(qe===n.DATA_TYPES.fp16&&fe==="webgpu"&&!await(0,n.isWebGpuFp16Supported)())throw new Error(`The device (${fe}) does not support fp16.`)}else throw new Error(`Invalid dtype: ${qe}. Should be one of: ${Object.keys(n.DATA_TYPES).join(", ")}`);const it=ne.kv_cache_dtype,pt=it?typeof it=="string"?it:it[qe]??"float32":void 0;if(pt&&!["float32","float16"].includes(pt))throw new Error(`Invalid kv_cache_dtype: ${pt}. Should be one of: float32, float16`);const ot={dtype:qe,kv_cache_dtype:pt},Mt=n.DEFAULT_DTYPE_SUFFIX_MAPPING[qe],ct=`${P}${Mt}.onnx`,gt=`${D.subfolder??""}/${ct}`,rt={...D.session_options};rt.executionProviders??(rt.executionProviders=Ce);const yt=ne.free_dimension_overrides;yt?rt.freeDimensionOverrides??(rt.freeDimensionOverrides=yt):fe.startsWith("webnn")&&!rt.freeDimensionOverrides&&console.warn(`WebNN does not currently support dynamic shapes and requires 'free_dimension_overrides' to be set in config.json, preferably as a field within config["transformers.js_config"]["device_config"]["${fe}"]. When 'free_dimension_overrides' is not set, you may experience significant performance degradation.`);const Lt=w.apis.IS_NODE_ENV&&w.env.useFSCache,Ut=(0,l.getModelFile)(b,gt,!0,D,Lt),Jt=D.use_external_data_format??ne.use_external_data_format;let qt=[];if(Jt){let bt;typeof Jt=="object"?Jt.hasOwnProperty(ct)?bt=Jt[ct]:Jt.hasOwnProperty(P)?bt=Jt[P]:bt=!1:bt=Jt;const ir=+bt;if(ir>l.MAX_EXTERNAL_DATA_CHUNKS)throw new Error(`The number of external data chunks (${ir}) exceeds the maximum allowed value (${l.MAX_EXTERNAL_DATA_CHUNKS}).`);for(let Vr=0;Vr{const Fn=await(0,l.getModelFile)(b,$r,!0,D,Lt);Jr(Fn instanceof Uint8Array?{path:An,data:Fn}:An)}))}}else rt.externalData!==void 0&&(qt=rt.externalData.map(async bt=>{if(typeof bt.data=="string"){const ir=await(0,l.getModelFile)(b,bt.data,!0,D);return{...bt,data:ir}}return bt}));if(qt.length>0){const bt=await Promise.all(qt);w.apis.IS_NODE_ENV||(rt.externalData=bt)}if(fe==="webgpu"){const bt=(0,s.getKeyValueShapes)(D.config,{prefix:"present"});if(Object.keys(bt).length>0&&!(0,o.isONNXProxy)()){const ir={};for(const Vr in bt)ir[Vr]="gpu-buffer";rt.preferredOutputLocation=ir}}return{buffer_or_path:await Ut,session_options:rt,session_config:ot}}async function A(b,P,D){return Object.fromEntries(await Promise.all(Object.keys(P).map(async ne=>{const{buffer_or_path:ge,session_options:fe,session_config:Ce}=await C(b,P[ne],D),Le=await(0,o.createInferenceSession)(ge,fe,Ce);return[ne,Le]})))}async function B(b,P,D){return Object.fromEntries(await Promise.all(Object.keys(P).map(async ne=>{const ge=await(0,l.getModelJSON)(b,P[ne],!1,D);return[ne,ge]})))}function K(b,P){const D=Object.create(null),ne=[];for(const Ce of b.inputNames){const Le=P[Ce];if(!(Le instanceof c.Tensor)){ne.push(Ce);continue}D[Ce]=(0,o.isONNXProxy)()?Le.clone():Le}if(ne.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${ne.join(", ")}.`);const ge=Object.keys(P).length,fe=b.inputNames.length;if(ge>fe){let Ce=Object.keys(P).filter(Le=>!b.inputNames.includes(Le));console.warn(`WARNING: Too many inputs were provided (${ge} > ${fe}). The following inputs will be ignored: "${Ce.join(", ")}".`)}return D}async function G(b,P){const D=K(b,P);try{const ne=Object.fromEntries(Object.entries(D).map(([fe,Ce])=>[fe,Ce.ort_tensor]));let ge=await b.run(ne);return ge=j(ge),ge}catch(ne){const ge=Object.fromEntries(Object.entries(D).map(([fe,{type:Ce,dims:Le,data:Ne}])=>[fe,{type:Ce,dims:Le,data:Ne}]));throw console.error(`An error occurred during model execution: "${ne}".`),console.error("Inputs given to model:",ge),ne}}function j(b){for(let P in b)(0,o.isONNXTensor)(b[P])?b[P]=new c.Tensor(b[P]):typeof b[P]=="object"&&j(b[P]);return b}function ee(b){if(b instanceof c.Tensor)return b;if(b.length===0)throw Error("items must be non-empty");if(Array.isArray(b[0])){if(b.some(P=>P.length!==b[0].length))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=True' and/or 'truncation=True' to have batched tensors with the same length.");return new c.Tensor("int64",BigInt64Array.from(b.flat().map(P=>BigInt(P))),[b.length,b[0].length])}else return new c.Tensor("int64",BigInt64Array.from(b.map(P=>BigInt(P))),[1,b.length])}function H(b){return new c.Tensor("bool",[b],[1])}async function Z(b,P){let{encoder_outputs:D,input_ids:ne,decoder_input_ids:ge,...fe}=P;if(!D){const Le=(0,a.pick)(P,b.sessions.model.inputNames);D=(await X(b,Le)).last_hidden_state}return fe.input_ids=ge,fe.encoder_hidden_states=D,b.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(fe.encoder_attention_mask=P.attention_mask),await me(b,fe,!0)}async function X(b,P){const D=b.sessions.model,ne=(0,a.pick)(P,D.inputNames);if(D.inputNames.includes("inputs_embeds")&&!ne.inputs_embeds){if(!P.input_ids)throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");ne.inputs_embeds=await b.encode_text({input_ids:P.input_ids})}if(D.inputNames.includes("token_type_ids")&&!ne.token_type_ids){if(!ne.input_ids)throw new Error("Both `input_ids` and `token_type_ids` are missing in the model inputs.");ne.token_type_ids=(0,c.zeros_like)(ne.input_ids)}if(D.inputNames.includes("pixel_mask")&&!ne.pixel_mask){if(!ne.pixel_values)throw new Error("Both `pixel_values` and `pixel_mask` are missing in the model inputs.");const ge=ne.pixel_values.dims;ne.pixel_mask=(0,c.ones)([ge[0],ge[2],ge[3]])}return await G(D,ne)}async function oe(b,P){const D=await b.encode(P);return await b.decode(D)}async function me(b,P,D=!1){const ne=b.sessions[D?"decoder_model_merged":"model"],{past_key_values:ge,...fe}=P;if(ne.inputNames.includes("use_cache_branch")&&(fe.use_cache_branch=H(!!ge)),ne.inputNames.includes("position_ids")&&fe.attention_mask&&!fe.position_ids){const Le=["paligemma","gemma3_text","gemma3"].includes(b.config.model_type)?1:0;fe.position_ids=ce(fe,ge,Le)}b.addPastKeyValues(fe,ge);const Ce=(0,a.pick)(fe,ne.inputNames);return await G(ne,Ce)}function ae({modality_token_id:b,inputs_embeds:P,modality_features:D,input_ids:ne,attention_mask:ge}){const fe=ne.tolist().map(qe=>qe.reduce((it,pt,ot)=>(pt==b&&it.push(ot),it),[])),Ce=fe.reduce((qe,it)=>qe+it.length,0),Le=D.dims[0];if(Ce!==Le)throw new Error(`Number of tokens and features do not match: tokens: ${Ce}, features ${Le}`);let Ne=0;for(let qe=0;qefe.dims[1])){if(geLe==b.config.image_token_index)){const Le=b.config.num_image_tokens;if(!Le)throw new Error("`num_image_tokens` is missing in the model configuration.");const Ne=fe.dims[1]-(ge-Le);D.input_ids=fe.slice(null,[-Ne,null]),D.attention_mask=(0,c.ones)([1,ge+Ne])}}}return D}function Ue(b,P,D,ne){return D.past_key_values&&(P=P.map(ge=>[ge.at(-1)])),{...D,decoder_input_ids:ee(P)}}function we(b,...P){return b.config.is_encoder_decoder?Ue(b,...P):$e(b,...P)}function q(b,P,D,ne){const ge=!!D.past_key_values;return ne.guidance_scale!==null&&ne.guidance_scale>1&&(ge?D.input_ids=(0,c.cat)([D.input_ids,D.input_ids],0):(D.input_ids=(0,c.cat)([D.input_ids,(0,c.full_like)(D.input_ids,BigInt(ne.pad_token_id))],0),D.attention_mask=(0,c.cat)([D.attention_mask,(0,c.full_like)(D.attention_mask,0n)],0))),(ge||!D.pixel_values)&&(D.pixel_values=(0,c.full)([0,0,3,384,384],1)),ge&&(D.images_seq_mask=new c.Tensor("bool",new Array(1).fill(!0).fill(!1,0,1),[1,1]),D.images_emb_mask=new c.Tensor("bool",new Array(0).fill(!1),[1,1,0])),D}class R extends i.Callable{constructor(D,ne,ge){super();te(this,"main_input_name","input_ids");te(this,"forward_params",["input_ids","attention_mask"]);this.config=D,this.sessions=ne,this.configs=ge;const fe=v.get(this.constructor),Ce=y.get(fe);switch(this.can_generate=!1,this._forward=null,this._prepare_inputs_for_generation=null,Ce){case E.DecoderOnly:this.can_generate=!0,this._forward=me,this._prepare_inputs_for_generation=$e;break;case E.Seq2Seq:case E.Vision2Seq:case E.Musicgen:this.can_generate=!0,this._forward=Z,this._prepare_inputs_for_generation=Ue;break;case E.EncoderDecoder:this._forward=Z;break;case E.ImageTextToText:this.can_generate=!0,this._forward=_e,this._prepare_inputs_for_generation=we;break;case E.AudioTextToText:this.can_generate=!0,this._forward=re,this._prepare_inputs_for_generation=we;break;case E.Phi3V:this.can_generate=!0,this._prepare_inputs_for_generation=we;break;case E.MultiModality:this.can_generate=!0,this._prepare_inputs_for_generation=q;break;case E.AutoEncoder:this._forward=oe;break;default:this._forward=X;break}this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){var ne;const D=[];for(const ge of Object.values(this.sessions))(ne=ge==null?void 0:ge.handler)!=null&&ne.dispose&&D.push(ge.handler.dispose());return await Promise.all(D)}static async from_pretrained(D,{progress_callback:ne=null,config:ge=null,cache_dir:fe=null,local_files_only:Ce=!1,revision:Le="main",model_file_name:Ne=null,subfolder:qe="onnx",device:it=null,dtype:pt=null,use_external_data_format:ot=null,session_options:Mt={}}={}){let ct={progress_callback:ne,config:ge,cache_dir:fe,local_files_only:Ce,revision:Le,model_file_name:Ne,subfolder:qe,device:it,dtype:pt,use_external_data_format:ot,session_options:Mt};const gt=v.get(this),rt=y.get(gt);ge=ct.config=await s.AutoConfig.from_pretrained(D,ct);let yt;if(rt===E.DecoderOnly)yt=await Promise.all([A(D,{model:ct.model_file_name??"model"},ct),B(D,{generation_config:"generation_config.json"},ct)]);else if(rt===E.Seq2Seq||rt===E.Vision2Seq)yt=await Promise.all([A(D,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},ct),B(D,{generation_config:"generation_config.json"},ct)]);else if(rt===E.MaskGeneration)yt=await Promise.all([A(D,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},ct)]);else if(rt===E.EncoderDecoder)yt=await Promise.all([A(D,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},ct)]);else if(rt===E.ImageTextToText){const Lt={embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};ge.is_encoder_decoder&&(Lt.model="encoder_model"),yt=await Promise.all([A(D,Lt,ct),B(D,{generation_config:"generation_config.json"},ct)])}else if(rt===E.AudioTextToText){const Lt={embed_tokens:"embed_tokens",audio_encoder:"audio_encoder",decoder_model_merged:"decoder_model_merged"};yt=await Promise.all([A(D,Lt,ct),B(D,{generation_config:"generation_config.json"},ct)])}else if(rt===E.Musicgen)yt=await Promise.all([A(D,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},ct),B(D,{generation_config:"generation_config.json"},ct)]);else if(rt===E.MultiModality)yt=await Promise.all([A(D,{prepare_inputs_embeds:"prepare_inputs_embeds",model:"language_model",lm_head:"lm_head",gen_head:"gen_head",gen_img_embeds:"gen_img_embeds",image_decode:"image_decode"},ct),B(D,{generation_config:"generation_config.json"},ct)]);else if(rt===E.Phi3V)yt=await Promise.all([A(D,{prepare_inputs_embeds:"prepare_inputs_embeds",model:"model",vision_encoder:"vision_encoder"},ct),B(D,{generation_config:"generation_config.json"},ct)]);else if(rt===E.AutoEncoder)yt=await Promise.all([A(D,{encoder_model:"encoder_model",decoder_model:"decoder_model"},ct)]);else{if(rt!==E.EncoderOnly){const Lt=gt??(ge==null?void 0:ge.model_type);Lt!=="custom"&&console.warn(`Model type for '${Lt}' not found, assuming encoder-only architecture. Please report this at ${u.GITHUB_ISSUE_URL}.`)}yt=await Promise.all([A(D,{model:ct.model_file_name??"model"},ct)])}return new this(ge,...yt)}async _call(D){return await this.forward(D)}async forward(D){return await this._forward(this,D)}get generation_config(){var D;return((D=this.configs)==null?void 0:D.generation_config)??null}_get_logits_warper(D){const ne=new p.LogitsProcessorList;return D.temperature!==null&&D.temperature!==1&&ne.push(new p.TemperatureLogitsWarper(D.temperature)),D.top_k!==null&&D.top_k!==0&&ne.push(new p.TopKLogitsWarper(D.top_k)),D.top_p!==null&&D.top_p<1&&ne.push(new p.TopPLogitsWarper(D.top_p)),ne}_get_logits_processor(D,ne,ge=null){const fe=new p.LogitsProcessorList;if(D.repetition_penalty!==null&&D.repetition_penalty!==1&&fe.push(new p.RepetitionPenaltyLogitsProcessor(D.repetition_penalty)),D.no_repeat_ngram_size!==null&&D.no_repeat_ngram_size>0&&fe.push(new p.NoRepeatNGramLogitsProcessor(D.no_repeat_ngram_size)),D.bad_words_ids!==null&&fe.push(new p.NoBadWordsLogitsProcessor(D.bad_words_ids,D.eos_token_id)),D.min_length!==null&&D.eos_token_id!==null&&D.min_length>0&&fe.push(new p.MinLengthLogitsProcessor(D.min_length,D.eos_token_id)),D.min_new_tokens!==null&&D.eos_token_id!==null&&D.min_new_tokens>0&&fe.push(new p.MinNewTokensLengthLogitsProcessor(ne,D.min_new_tokens,D.eos_token_id)),D.forced_bos_token_id!==null&&fe.push(new p.ForcedBOSTokenLogitsProcessor(D.forced_bos_token_id)),D.forced_eos_token_id!==null&&fe.push(new p.ForcedEOSTokenLogitsProcessor(D.max_length,D.forced_eos_token_id)),D.begin_suppress_tokens!==null){const Ce=ne>1||D.forced_bos_token_id===null?ne:ne+1;fe.push(new p.SuppressTokensAtBeginLogitsProcessor(D.begin_suppress_tokens,Ce))}return D.guidance_scale!==null&&D.guidance_scale>1&&fe.push(new p.ClassifierFreeGuidanceLogitsProcessor(D.guidance_scale)),ge!==null&&fe.extend(ge),fe}_prepare_generation_config(D,ne,ge=d.GenerationConfig){const fe={...this.config};for(const Le of["decoder","generator","text_config"])Le in fe&&Object.assign(fe,fe[Le]);const Ce=new ge(fe);return Object.assign(Ce,this.generation_config??{}),D&&Object.assign(Ce,D),ne&&Object.assign(Ce,(0,a.pick)(ne,Object.getOwnPropertyNames(Ce))),Ce}_get_stopping_criteria(D,ne=null){const ge=new T.StoppingCriteriaList;return D.max_length!==null&&ge.push(new T.MaxLengthCriteria(D.max_length,this.config.max_position_embeddings??null)),D.eos_token_id!==null&&ge.push(new T.EosTokenCriteria(D.eos_token_id)),ne&&ge.extend(ne),ge}_validate_model_class(){if(!this.can_generate){const D=[md,_d,hd,pd],ne=v.get(this.constructor),ge=new Set,fe=this.config.model_type;for(const Le of D){const Ne=Le.get(fe);Ne&&ge.add(Ne[0])}let Ce=`The current model class (${ne}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw ge.size>0&&(Ce+=` Please use the following class instead: ${[...ge].join(", ")}`),Error(Ce)}}prepare_inputs_for_generation(...D){return this._prepare_inputs_for_generation(this,...D)}_update_model_kwargs_for_generation({generated_input_ids:D,outputs:ne,model_inputs:ge,is_encoder_decoder:fe}){return ge.past_key_values=this.getPastKeyValues(ne,ge.past_key_values),ge.input_ids=new c.Tensor("int64",D.flat(),[D.length,1]),fe||(ge.attention_mask=(0,c.cat)([ge.attention_mask,(0,c.ones)([ge.attention_mask.dims[0],1])],1)),ge.position_ids=null,ge}_prepare_model_inputs({inputs:D,bos_token_id:ne,model_kwargs:ge}){const fe=(0,a.pick)(ge,this.forward_params),Ce=this.main_input_name;if(Ce in fe){if(D)throw new Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else fe[Ce]=D;return{inputs_tensor:fe[Ce],model_inputs:fe,model_input_name:Ce}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:D,model_inputs:ne,model_input_name:ge,generation_config:fe}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!ne.inputs_embeds&&"_prepare_inputs_embeds"in this){const{input_ids:Le,pixel_values:Ne,attention_mask:qe,...it}=ne,pt=await this._prepare_inputs_embeds(ne);ne={...it,...(0,a.pick)(pt,["inputs_embeds","attention_mask"])}}let{last_hidden_state:Ce}=await X(this,ne);if(fe.guidance_scale!==null&&fe.guidance_scale>1)Ce=(0,c.cat)([Ce,(0,c.full_like)(Ce,0)],0),"attention_mask"in ne&&(ne.attention_mask=(0,c.cat)([ne.attention_mask,(0,c.zeros_like)(ne.attention_mask)],0));else if(ne.decoder_input_ids){const Le=ee(ne.decoder_input_ids).dims[0];if(Le!==Ce.dims[0]){if(Ce.dims[0]!==1)throw new Error(`The encoder outputs have a different batch size (${Ce.dims[0]}) than the decoder inputs (${Le}).`);Ce=(0,c.cat)(Array.from({length:Le},()=>Ce),0)}}return ne.encoder_outputs=Ce,ne}_prepare_decoder_input_ids_for_generation({batch_size:D,model_input_name:ne,model_kwargs:ge,decoder_start_token_id:fe,bos_token_id:Ce,generation_config:Le}){let{decoder_input_ids:Ne,...qe}=ge;if(!(Ne instanceof c.Tensor)){if(Ne)Array.isArray(Ne[0])||(Ne=Array.from({length:D},()=>Ne));else if(fe??(fe=Ce),this.config.model_type==="musicgen")Ne=Array.from({length:D*this.config.decoder.num_codebooks},()=>[fe]);else if(Array.isArray(fe)){if(fe.length!==D)throw new Error(`\`decoder_start_token_id\` expcted to have length ${D} but got ${fe.length}`);Ne=fe}else Ne=Array.from({length:D},()=>[fe]);Ne=ee(Ne)}return ge.decoder_attention_mask=(0,c.ones_like)(Ne),{input_ids:Ne,model_inputs:qe}}async generate({inputs:D=null,generation_config:ne=null,logits_processor:ge=null,stopping_criteria:fe=null,streamer:Ce=null,...Le}){this._validate_model_class(),ne=this._prepare_generation_config(ne,Le);let{inputs_tensor:Ne,model_inputs:qe,model_input_name:it}=this._prepare_model_inputs({inputs:D,model_kwargs:Le});const pt=this.config.is_encoder_decoder;pt&&("encoder_outputs"in qe||(qe=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:Ne,model_inputs:qe,model_input_name:it,generation_config:ne})));let ot;pt?{input_ids:ot,model_inputs:qe}=this._prepare_decoder_input_ids_for_generation({batch_size:qe[it].dims.at(0),model_input_name:it,model_kwargs:qe,decoder_start_token_id:ne.decoder_start_token_id,bos_token_id:ne.bos_token_id,generation_config:ne}):ot=qe[it];let Mt=ot.dims.at(-1);ne.max_new_tokens!==null&&(ne.max_length=Mt+ne.max_new_tokens);const ct=this._get_logits_processor(ne,Mt,ge),gt=this._get_stopping_criteria(ne,fe),rt=qe[it].dims.at(0),yt=k.LogitsSampler.getSampler(ne),Lt=new Array(rt).fill(0),Ut=ot.tolist();Ce&&Ce.put(Ut);let Jt,qt={};for(;;){if(qe=this.prepare_inputs_for_generation(Ut,qe,ne),Jt=await this.forward(qe),ne.output_attentions&&ne.return_dict_in_generate){const $r=this.getAttentions(Jt);for(const Jr in $r)Jr in qt||(qt[Jr]=[]),qt[Jr].push($r[Jr])}const bt=Jt.logits.slice(null,-1,null),ir=ct(Ut,bt),Vr=[];for(let $r=0;$r$r))break;qe=this._update_model_kwargs_for_generation({generated_input_ids:Vr,outputs:Jt,model_inputs:qe,is_encoder_decoder:pt})}Ce&&Ce.end();const nr=this.getPastKeyValues(Jt,qe.past_key_values,!0),mr=new c.Tensor("int64",Ut.flat(),[Ut.length,Ut[0].length]);if(ne.return_dict_in_generate)return{sequences:mr,past_key_values:nr,...qt};for(const bt of Object.values(Jt))bt.location==="gpu-buffer"&&bt.dispose();return mr}getPastKeyValues(D,ne,ge=!1){const fe=Object.create(null);for(const Ce in D)if(Ce.startsWith("present")){const Le=Ce.replace("present","past_key_values"),Ne=Ce.includes("encoder");if(Ne&&ne?fe[Le]=ne[Le]:fe[Le]=D[Ce],ne&&(!Ne||ge)){const qe=ne[Le];qe.location==="gpu-buffer"&&qe.dispose()}}return fe}getAttentions(D){const ne={};for(const ge of["cross_attentions","encoder_attentions","decoder_attentions"])for(const fe in D)fe.startsWith(ge)&&(ge in ne||(ne[ge]=[]),ne[ge].push(D[fe]));return ne}addPastKeyValues(D,ne){var ge,fe,Ce;if(ne)Object.assign(D,ne);else{const Le=this.sessions.decoder_model_merged??this.sessions.model,Ne=((ge=Le==null?void 0:Le.config)==null?void 0:ge.kv_cache_dtype)??"float32",qe=Ne==="float16"?new c.DataTypeMap.float16:[],it=((Ce=(fe=D[this.main_input_name]??D.attention_mask)==null?void 0:fe.dims)==null?void 0:Ce[0])??1,pt=(0,s.getKeyValueShapes)(this.config,{batch_size:it});for(const ot in pt)D[ot]=new c.Tensor(Ne,qe,pt[ot])}}async encode_image({pixel_values:D}){const ne=(await G(this.sessions.vision_encoder,{pixel_values:D})).image_features;return this.config.num_image_tokens||(console.warn(`The number of image tokens was not set in the model configuration. Setting it to the number of features detected by the vision encoder (${ne.dims[1]}).`),this.config.num_image_tokens=ne.dims[1]),ne}async encode_text({input_ids:D}){return(await G(this.sessions.embed_tokens,{input_ids:D})).inputs_embeds}async encode_audio({audio_values:D}){return(await G(this.sessions.audio_encoder,{audio_values:D})).audio_features}}class pe{}class xe extends pe{constructor({last_hidden_state:P,hidden_states:D=null,attentions:ne=null}){super(),this.last_hidden_state=P,this.hidden_states=D,this.attentions=ne}}class be extends R{}class Se extends be{}class Ae extends be{async _call(P){return new Mr(await super._call(P))}}class Fe extends be{async _call(P){return new _t(await super._call(P))}}class ze extends be{async _call(P){return new hr(await super._call(P))}}class Ve extends be{async _call(P){return new Er(await super._call(P))}}class O extends R{}class Y extends O{}class z extends O{async _call(P){return new Mr(await super._call(P))}}class J extends O{async _call(P){return new _t(await super._call(P))}}class le extends O{async _call(P){return new hr(await super._call(P))}}class ye extends R{}class Ee extends ye{}class ke extends R{}class Ie extends ke{}class Re extends ke{async _call(P){return new Mr(await super._call(P))}}class Xe extends ke{async _call(P){return new _t(await super._call(P))}}class Ge extends ke{async _call(P){return new hr(await super._call(P))}}class lt extends ke{async _call(P){return new Er(await super._call(P))}}class wt extends R{}class Gt extends wt{}class Ot extends wt{async _call(P){return new Mr(await super._call(P))}}class ur extends wt{async _call(P){return new _t(await super._call(P))}}class ls extends wt{async _call(P){return new hr(await super._call(P))}}class Ms extends wt{async _call(P){return new Er(await super._call(P))}}class Ir extends R{}class js extends Ir{}class Ss extends Ir{async _call(P){return new Mr(await super._call(P))}}class Ns extends Ir{async _call(P){return new _t(await super._call(P))}}class at extends Ir{async _call(P){return new hr(await super._call(P))}}class us extends Ir{async _call(P){return new Er(await super._call(P))}}class Ar extends R{}class bs extends Ar{}class Ft extends Ar{async _call(P){return new Mr(await super._call(P))}}class ds extends Ar{async _call(P){return new _t(await super._call(P))}}class cs extends Ar{async _call(P){return new hr(await super._call(P))}}class ys extends Ar{async _call(P){return new Er(await super._call(P))}}class Qt extends R{}class De extends Qt{}class Qe extends Qt{async _call(P){return new Mr(await super._call(P))}}class tt extends Qt{async _call(P){return new _t(await super._call(P))}}class Rt extends Qt{async _call(P){return new hr(await super._call(P))}}class zr extends Qt{async _call(P){return new Er(await super._call(P))}}class Sr extends R{}class ps extends Sr{}class hs extends Sr{async _call(P){return new Mr(await super._call(P))}}class Kr extends Sr{async _call(P){return new _t(await super._call(P))}}class ms extends Sr{async _call(P){return new hr(await super._call(P))}}class _s extends Sr{async _call(P){return new Er(await super._call(P))}}class Hr extends R{}class vr extends Hr{}class cn extends Hr{async _call(P){return new _t(await super._call(P))}}class xr extends Hr{async _call(P){return new hr(await super._call(P))}}class $s extends Hr{async _call(P){return new Er(await super._call(P))}}class ks extends Hr{async _call(P){return new Mr(await super._call(P))}}class fr extends R{}class Vs extends fr{}class pn extends fr{async _call(P){return new Mr(await super._call(P))}}class Fr extends fr{async _call(P){return new _t(await super._call(P))}}class hn extends fr{async _call(P){return new hr(await super._call(P))}}class qr extends R{}class Tr extends qr{}class Is extends qr{async _call(P){return new Mr(await super._call(P))}}class dr extends qr{async _call(P){return new _t(await super._call(P))}}class gr extends qr{async _call(P){return new Er(await super._call(P))}}class Br extends R{}class mn extends Br{}class _n extends Br{async _call(P){return new Mr(await super._call(P))}}class fn extends Br{async _call(P){return new _t(await super._call(P))}}class gn extends Br{async _call(P){return new hr(await super._call(P))}}class wn extends Br{async _call(P){return new Er(await super._call(P))}}class vs extends R{}class Mn extends vs{}class Us extends vs{async _call(P){return new Mr(await super._call(P))}}class bn extends vs{async _call(P){return new _t(await super._call(P))}}class yn extends vs{async _call(P){return new Er(await super._call(P))}}class xs extends R{}class vn extends xs{}class he extends xs{async _call(P){return new _t(await super._call(P))}}class $ extends xs{async _call(P){return new Er(await super._call(P))}}class N extends xs{async _call(P){return new Mr(await super._call(P))}}class Q extends R{constructor(){super(...arguments);te(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"])}}class ie extends Q{}class de extends Q{}class ve extends R{}class je extends ve{}class He extends ve{}class We extends R{}class Je extends We{}class dt extends We{}class xt extends R{}class Pt extends xt{}class jt extends xt{}class kt extends xt{async _call(P){return new _t(await super._call(P))}}class Ht extends R{}class br extends Ht{}class cr extends Ht{}class pr extends Ht{async _call(P){return new _t(await super._call(P))}}class Nt extends Ht{}class Xr extends R{}class Dt extends Xr{}class rr extends Xr{}class wr extends R{}class Qr extends wr{}class Rr extends wr{}class Yt extends R{}class jr extends Yt{}class or extends Yt{async _call(P){return new Mr(await super._call(P))}}class Vt extends Yt{async _call(P){return new _t(await super._call(P))}}class Zt extends Yt{async _call(P){return new hr(await super._call(P))}}class er extends Yt{async _call(P){return new Er(await super._call(P))}}class tr extends R{}class Ws extends tr{}class xn extends tr{async _call(P){return new Mr(await super._call(P))}}class vi extends tr{async _call(P){return new _t(await super._call(P))}}class xi extends tr{async _call(P){return new hr(await super._call(P))}}class Ti extends tr{async _call(P){return new Er(await super._call(P))}}class As extends R{}class Ei extends As{}class Pi extends As{async _call(P){return new Mr(await super._call(P))}}class Ci extends As{async _call(P){return new _t(await super._call(P))}}class Si extends As{async _call(P){return new hr(await super._call(P))}}class $i extends As{async _call(P){return new Er(await super._call(P))}}class To extends R{}class ki extends To{}class Ii extends To{}class Eo extends R{constructor(){super(...arguments);te(this,"requires_attention_mask",!1);te(this,"main_input_name","input_features");te(this,"forward_params",["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"])}}class Ai extends Eo{}class Po extends Eo{_prepare_generation_config(P,D){return super._prepare_generation_config(P,D,g.WhisperGenerationConfig)}_retrieve_init_tokens(P){const D=[P.decoder_start_token_id];let ne=P.language;const ge=P.task;if(P.is_multilingual){ne||(console.warn("No language specified - defaulting to English (en)."),ne="en");const Ce=`<|${(0,S.whisper_language_to_code)(ne)}|>`;D.push(P.lang_to_id[Ce]),D.push(P.task_to_id[ge??"transcribe"])}else if(ne||ge)throw new Error("Cannot specify `task` or `language` for an English-only model. If the model is intended to be multilingual, pass `is_multilingual=true` to generate, or update the generation config.");return!P.return_timestamps&&P.no_timestamps_token_id&&D.at(-1)!==P.no_timestamps_token_id?D.push(P.no_timestamps_token_id):P.return_timestamps&&D.at(-1)===P.no_timestamps_token_id&&(console.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),D.pop()),D.filter(fe=>fe!=null)}async generate({inputs:P=null,generation_config:D=null,logits_processor:ne=null,stopping_criteria:ge=null,...fe}){D=this._prepare_generation_config(D,fe);const Ce=fe.decoder_input_ids??this._retrieve_init_tokens(D);if(D.return_timestamps&&(ne??(ne=new p.LogitsProcessorList),ne.push(new p.WhisperTimeStampLogitsProcessor(D,Ce))),D.begin_suppress_tokens&&(ne??(ne=new p.LogitsProcessorList),ne.push(new p.SuppressTokensAtBeginLogitsProcessor(D.begin_suppress_tokens,Ce.length))),D.return_token_timestamps){if(!D.alignment_heads)throw new Error("Model generation config has no `alignment_heads`, token-level timestamps not available. See https://gist.github.com/hollance/42e32852f24243b748ae6bc1f985b13a on how to add this property to the generation config.");D.task==="translate"&&console.warn("Token-level timestamps may not be reliable for task 'translate'."),D.output_attentions=!0,D.return_dict_in_generate=!0}const Le=await super.generate({inputs:P,generation_config:D,logits_processor:ne,decoder_input_ids:Ce,...fe});return D.return_token_timestamps&&(Le.token_timestamps=this._extract_token_timestamps(Le,D.alignment_heads,D.num_frames)),Le}_extract_token_timestamps(P,D,ne=null,ge=.02){if(!P.cross_attentions)throw new Error("Model outputs must contain cross attentions to extract timestamps. This is most likely because the model was not exported with `output_attentions=True`.");ne==null&&console.warn("`num_frames` has not been set, meaning the entire audio will be analyzed. This may lead to inaccurate token-level timestamps for short audios (< 30 seconds).");let fe=this.config.median_filter_width;fe===void 0&&(console.warn("Model config has no `median_filter_width`, using default value of 7."),fe=7);const Ce=P.cross_attentions,Le=Array.from({length:this.config.decoder_layers},(gt,rt)=>(0,c.cat)(Ce.map(yt=>yt[rt]),2)),Ne=(0,c.stack)(D.map(([gt,rt])=>{if(gt>=Le.length)throw new Error(`Layer index ${gt} is out of bounds for cross attentions (length ${Le.length}).`);return ne?Le[gt].slice(null,rt,null,[0,ne]):Le[gt].slice(null,rt)})).transpose(1,0,2,3),[qe,it]=(0,c.std_mean)(Ne,-2,0,!0),pt=Ne.clone();for(let gt=0;gtyt[mr+1]-yt[mr]),Jt=(0,a.mergeArrays)([1],Ut).map(nr=>!!nr),qt=[];for(let nr=0;nrot.findIndex(Mt=>Mt==fe)),Ne=Le.every(ot=>ot===-1),qe=Le.every(ot=>ot!==-1);if(!Ne&&!qe)throw new Error("Every input should contain either 0 or 1 image token.");if(Ne)return{inputs_embeds:P,attention_mask:ge};const it=[],pt=[];for(let ot=0;otArray.from({length:P.dims[0]},Ut=>Array.from({length:P.dims[1]},Jt=>1))),ct=D?D.tolist():[],gt=ne?ne.tolist():[];let rt=0,yt=0;for(let Lt=0;Ltot[Lt][ar]==1),qt=Ut.reduce((Wt,ar,Js)=>(ar==Ne&&Wt.push(Js),Wt),[]).map(Wt=>Ut[Wt+1]),nr=qt.filter(Wt=>Wt==Ce).length,mr=qt.filter(Wt=>Wt==Le).length;let bt=[],ir=0,Vr=nr,An=mr;for(let Wt=0;Wtfs>ir&&Dn==Ce),Js=Ut.findIndex((Dn,fs)=>fs>ir&&Dn==Le),On=Vr>0&&ar!==-1?ar:Ut.length+1,oo=An>0&&Js!==-1?Js:Ut.length+1;let ha,gd,wd,Md;On0?(0,_.max)(bt.at(-1))[0]+1:0;bt.push(Array.from({length:3*yd},(Dn,fs)=>O0+fs%yd));const vd=yd+O0,_a=Ux*bd*ma,Wx=Array.from({length:_a},(Dn,fs)=>vd+Math.floor(fs/(bd*ma))),Gx=Array.from({length:_a},(Dn,fs)=>vd+Math.floor(fs/ma)%bd),Kx=Array.from({length:_a},(Dn,fs)=>vd+fs%ma);bt.push([Wx,Gx,Kx].flat()),ir=ha+_a}if(ir0?(0,_.max)(bt.at(-1))[0]+1:0,ar=Ut.length-ir;bt.push(Array.from({length:3*ar},(Js,On)=>Wt+On%ar))}const $r=bt.reduce((Wt,ar)=>Wt+ar.length,0),Jr=new Array($r);let da=0;for(let Wt=0;Wt<3;++Wt)for(let ar=0;arpt[rt%pt.length]),ct=Array.from({length:ot[0]},(gt,rt)=>(0,_.max)(pt.subarray(ot[1]*rt,ot[1]*(rt+1)))[0]+1n+BigInt(ot[1]));return[new c.Tensor("int64",Mt,[3,...ot]),new c.Tensor("int64",ct,[ct.length,1])]}else{const[pt,ot]=P.dims,Mt=BigInt64Array.from({length:3*pt*ot},(ct,gt)=>BigInt(Math.floor(gt%ot/pt)));return[new c.Tensor("int64",Mt,[3,...P.dims]),(0,c.zeros)([pt,1])]}}async encode_image({pixel_values:P,image_grid_thw:D}){return(await G(this.sessions.vision_encoder,{pixel_values:P,grid_thw:D})).image_features}_merge_input_ids_with_image_features(P){return V({image_token_id:this.config.image_token_id,...P})}prepare_inputs_for_generation(P,D,ne){if(D.attention_mask&&!D.position_ids)if(!D.past_key_values)[D.position_ids,D.rope_deltas]=this.get_rope_index(D.input_ids,D.image_grid_thw,D.video_grid_thw,D.attention_mask);else{D.pixel_values=null;const ge=BigInt(Object.values(D.past_key_values)[0].dims.at(-2)),fe=D.rope_deltas.map(Ce=>ge+Ce);D.position_ids=(0,c.stack)([fe,fe,fe],0)}return D}}class bu extends R{}class rw extends bu{}class sw extends bu{}class yu extends R{}class nw extends yu{}class ow extends yu{}class vu extends R{}class iw extends vu{}class aw extends vu{}class xu extends R{}class lw extends xu{}class uw extends xu{}class Tu extends R{}class dw extends Tu{}class cw extends Tu{}class Eu extends R{}class pw extends Eu{}class hw extends Eu{async _call(P){return new _t(await super._call(P))}}class Pu extends R{}class mw extends Pu{}class _w extends Pu{async _call(P){return new _t(await super._call(P))}}class fw extends R{}class gw extends fw{}class Cu extends R{}class ww extends Cu{}class Mw extends Cu{async _call(P){return new _t(await super._call(P))}}class bw extends R{}class yw extends bw{}class Su extends R{}class vw extends Su{}class xw extends Su{async _call(P){return new _t(await super._call(P))}}class Tw extends R{}class Ew extends Tw{}class $u extends R{}class Pw extends $u{}class Cw extends $u{async _call(P){return new _t(await super._call(P))}}class Sw extends R{}class $w extends Sw{async _call(P){return new A0(await super._call(P))}}class ku extends R{}class kw extends ku{}class Iw extends ku{async _call(P){return new _t(await super._call(P))}}class Iu extends R{}class Aw extends Iu{}class Fw extends Iu{async _call(P){return new _t(await super._call(P))}}class Au extends R{}class Ow extends Au{}class Dw extends Au{}class Fu extends R{}class Lw extends Fu{}class zw extends Fu{}class Ou extends R{}class Bw extends Ou{}class Rw extends Ou{async _call(P){return new _t(await super._call(P))}}class qi extends R{}class jw extends qi{}class Nw extends qi{async _call(P){return new Lu(await super._call(P))}}class Du extends qi{async _call(P){return new Vw(await super._call(P))}}class Lu extends pe{constructor({logits:P,pred_boxes:D}){super(),this.logits=P,this.pred_boxes=D}}class Vw extends pe{constructor({logits:P,pred_boxes:D,pred_masks:ne}){super(),this.logits=P,this.pred_boxes=D,this.pred_masks=ne}}class zu extends R{}class Uw extends zu{}class Ww extends zu{async _call(P){return new Xi(await super._call(P))}}class Xi extends pe{constructor({logits:P,pred_boxes:D}){super(),this.logits=P,this.pred_boxes=D}}class Bu extends R{}class Gw extends Bu{}class Kw extends Bu{async _call(P){return new Hw(await super._call(P))}}class Hw extends Xi{}class Ru extends R{}class qw extends Ru{}class Xw extends Ru{async _call(P){return new Qw(await super._call(P))}}class Qw extends Xi{}class ju extends R{}class Jw extends ju{}class Yw extends ju{async _call(P){return new Zw(await super._call(P))}}class Zw extends Lu{}class Nu extends R{}class eM extends Nu{}class tM extends Nu{async _call(P){return new _t(await super._call(P))}}class Vu extends R{}class rM extends Vu{}class sM extends Vu{async _call(P){return new _t(await super._call(P))}}class Uu extends R{}class nM extends Uu{}class oM extends Uu{async _call(P){return new _t(await super._call(P))}}class Qi extends R{}class iM extends Qi{}class aM extends Qi{async _call(P){return new _t(await super._call(P))}}class lM extends Qi{}class Wu extends R{}class uM extends Wu{}class dM extends Wu{}class Gu extends R{}class cM extends Gu{}class pM extends Gu{}class hM extends R{}class mM extends hM{}class Ji extends R{}class _M extends Ji{}class fM extends Ji{}class gM extends Ji{}class wM extends R{}class MM extends wM{}class bM extends R{}class yM extends bM{}class vM extends R{}class xM extends vM{}class Ku extends R{}class TM extends Ku{}class EM extends Ku{}class Hu extends R{}class PM extends Hu{}class CM extends Hu{}class SM extends R{}class $M extends SM{}class qu extends R{}class kM extends qu{}class IM extends qu{async _call(P){return new _t(await super._call(P))}}class Xu extends R{}class AM extends Xu{}class FM extends Xu{async _call(P){return new _t(await super._call(P))}}class Qu extends R{}class OM extends Qu{}class DM extends Qu{async _call(P){return new _t(await super._call(P))}}class Ju extends R{}class LM extends Ju{}class zM extends Ju{async _call(P){return new _t(await super._call(P))}}class BM extends R{}class RM extends BM{}class Yu extends R{}class jM extends Yu{}class NM extends Yu{async _call(P){return new VM(await super._call(P))}}class VM extends pe{constructor({logits:P,pred_boxes:D}){super(),this.logits=P,this.pred_boxes=D}}class UM extends R{}class WM extends UM{async get_image_embeddings({pixel_values:P}){return await X(this,{pixel_values:P})}async forward(P){if((!P.image_embeddings||!P.image_positional_embeddings)&&(P={...P,...await this.get_image_embeddings(P)}),!P.input_labels&&P.input_points){const ne=P.input_points.dims.slice(0,-1),ge=ne.reduce((fe,Ce)=>fe*Ce,1);P.input_labels=new c.Tensor("int64",new BigInt64Array(ge).fill(1n),ne)}const D={image_embeddings:P.image_embeddings,image_positional_embeddings:P.image_positional_embeddings};return P.input_points&&(D.input_points=P.input_points),P.input_labels&&(D.input_labels=P.input_labels),P.input_boxes&&(D.input_boxes=P.input_boxes),await G(this.sessions.prompt_encoder_mask_decoder,D)}async _call(P){return new GM(await super._call(P))}}class GM extends pe{constructor({iou_scores:P,pred_masks:D}){super(),this.iou_scores=P,this.pred_masks=D}}class Zu extends R{}class KM extends Zu{}class HM extends Zu{}class ed extends R{}class qM extends ed{}class XM extends ed{}class Qs extends R{}class QM extends Qs{}class JM extends Qs{async _call(P){return new In(await super._call(P))}}class YM extends Qs{async _call(P){return new _t(await super._call(P))}}class ZM extends Qs{async _call(P){return new hr(await super._call(P))}}class td extends R{}class eb extends td{}class tb extends td{async _call(P){return new hr(await super._call(P))}}class rb extends R{}class sb extends rb{}class Yi extends R{}class nb extends Yi{}class ob extends Yi{async _call(P){return new In(await super._call(P))}}class ib extends Yi{async _call(P){return new _t(await super._call(P))}}class Qo extends R{}class ab extends Qo{}class lb extends Qo{async _call(P){return new In(await super._call(P))}}class ub extends Qo{async _call(P){return new _t(await super._call(P))}}class db extends Qo{async _call(P){return new hr(await super._call(P))}}class Zi extends R{}class cb extends Zi{}class pb extends Zi{async _call(P){return new In(await super._call(P))}}class hb extends Zi{async _call(P){return new _t(await super._call(P))}}class Sx extends R{}class mb extends Qs{}class _b extends Qs{async _call(P){return new In(await super._call(P))}}class fb extends Qs{async _call(P){return new _t(await super._call(P))}}class so extends R{}class gb extends so{}class wb extends so{async _call(P){return new In(await super._call(P))}}class Mb extends so{async _call(P){return new _t(await super._call(P))}}class bb extends so{async _call(P){return new I0(await super._call(P))}}class yb extends so{async _call(P){return new hr(await super._call(P))}}class vb extends R{}class xb extends vb{}class ea extends R{}class $x extends ea{}class Tb extends ea{}class Eb extends ea{async generate_speech(P,D,{threshold:ne=.5,minlenratio:ge=0,maxlenratio:fe=20,vocoder:Ce=null}={}){const Le={input_ids:P},{encoder_outputs:Ne,encoder_attention_mask:qe}=await X(this,Le),it=Ne.dims[1]/this.config.reduction_factor,pt=Math.floor(it*fe),ot=Math.floor(it*ge),Mt=this.config.num_mel_bins;let ct=[],gt=null,rt=null,yt=0;for(;;){++yt;const Jt=H(!!rt);let qt;rt?qt=rt.output_sequence_out:qt=new c.Tensor("float32",new Float32Array(Mt),[1,1,Mt]);let nr={use_cache_branch:Jt,output_sequence:qt,encoder_attention_mask:qe,speaker_embeddings:D,encoder_hidden_states:Ne};this.addPastKeyValues(nr,gt),rt=await G(this.sessions.decoder_model_merged,nr),gt=this.getPastKeyValues(rt,gt);const{prob:mr,spectrum:bt}=rt;if(ct.push(bt),yt>=ot&&(Array.from(mr.data).filter(ir=>ir>=ne).length>0||yt>=pt))break}const Lt=(0,c.cat)(ct),{waveform:Ut}=await G(Ce.sessions.model,{spectrogram:Lt});return{spectrogram:Lt,waveform:Ut}}}class Pb extends R{constructor(){super(...arguments);te(this,"main_input_name","spectrogram")}}class Cb extends R{}class Sb extends Cb{}class rd extends R{}class $b extends rd{}class kb extends rd{}class sd extends R{}class Ib extends sd{}class Ab extends sd{}class nd extends R{}class Fb extends nd{}class Ob extends nd{}class ta extends R{}class Db extends ta{}class Lb extends ta{static async from_pretrained(P,D={}){return super.from_pretrained(P,{...D,model_file_name:D.model_file_name??"text_model"})}}class zb extends ta{static async from_pretrained(P,D={}){return super.from_pretrained(P,{...D,model_file_name:D.model_file_name??"audio_model"})}}class Bb extends R{}class od extends Bb{async _call(P){return new F0(await super._call(P))}}class ra extends R{}class kx extends ra{}class Rb extends ra{}class jb extends ra{}class id extends R{}class Nb extends id{}class Vb extends id{}class ad extends R{}class Ub extends ad{}class Wb extends ad{async _call(P){return new _t(await super._call(P))}}class ld extends R{}class Ix extends ld{}class Ax extends ld{}class ud extends R{constructor(){super(...arguments);te(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"])}_apply_and_filter_by_delay_pattern_mask(D){const[ne,ge]=D.dims,fe=this.config.decoder.num_codebooks,Ce=ge-fe;let Le=0;for(let it=0;it0&&Mt<=Ce&&(D.data[Le++]=D.data[it])}const Ne=Math.floor(ne/fe),qe=Le/(Ne*fe);return new c.Tensor(D.type,D.data.slice(0,Le),[Ne,fe,qe])}prepare_inputs_for_generation(D,ne,ge){let fe=structuredClone(D);for(let Le=0;Le=Ne&&(fe[Le][Ne]=BigInt(this.config.decoder.pad_token_id));return ge.guidance_scale!==null&&ge.guidance_scale>1&&(fe=fe.concat(fe)),super.prepare_inputs_for_generation(fe,ne,ge)}async generate(D){const ne=await super.generate(D),ge=this._apply_and_filter_by_delay_pattern_mask(ne).unsqueeze_(0),{audio_values:fe}=await G(this.sessions.encodec_decode,{audio_codes:ge});return fe}}class sa extends R{}class Gb extends sa{}class Kb extends sa{async _call(P){return new _t(await super._call(P))}}class Hb extends sa{}class na extends R{}class qb extends na{}class Xb extends na{async _call(P){return new _t(await super._call(P))}}class Qb extends na{}class oa extends R{}class Jb extends oa{}class Yb extends oa{async _call(P){return new _t(await super._call(P))}}class Zb extends oa{}class ia extends R{}class ey extends ia{}class ty extends ia{async _call(P){return new _t(await super._call(P))}}class ry extends ia{}class sy extends R{}class ny extends sy{}class oy extends R{}class iy extends oy{constructor(...D){super(...D);te(this,"forward_params",["input_ids","pixel_values","images_seq_mask","images_emb_mask","attention_mask","position_ids","past_key_values"]);this._generation_mode="text"}async forward(D){const ne=this._generation_mode??"text";let ge;if(ne==="text"||!D.past_key_values){const qe=this.sessions.prepare_inputs_embeds,it=(0,a.pick)(D,qe.inputNames);ge=await G(qe,it)}else{const qe=this.sessions.gen_img_embeds,it=(0,a.pick)({image_ids:D.input_ids},qe.inputNames);ge=await G(qe,it)}const fe={...D,...ge},Ce=await me(this,fe),Le=this.sessions[ne==="text"?"lm_head":"gen_head"];if(!Le)throw new Error(`Unable to find "${Le}" generation head`);const Ne=await G(Le,(0,a.pick)(Ce,Le.inputNames));return{...ge,...Ce,...Ne}}async generate(D){return this._generation_mode="text",super.generate(D)}async generate_images(D){this._generation_mode="image";const ne=(D.inputs??D[this.main_input_name]).dims[1],fe=(await super.generate(D)).slice(null,[ne,null]),Ce=this.sessions.image_decode,{decoded_image:Le}=await G(Ce,{generated_tokens:fe}),Ne=Le.add_(1).mul_(255/2).clamp_(0,255).to("uint8"),qe=[];for(const it of Ne){const pt=f.RawImage.fromTensor(it);qe.push(pt)}return qe}}class ay extends pe{constructor({char_logits:P,bpe_logits:D,wp_logits:ne}){super(),this.char_logits=P,this.bpe_logits=D,this.wp_logits=ne}get logits(){return[this.char_logits,this.bpe_logits,this.wp_logits]}}class ly extends R{}class uy extends ly{async _call(P){return new ay(await super._call(P))}}class dd extends R{}class dy extends dd{}class cy extends dd{}class cd extends R{}class py extends cd{}class hy extends cd{}class my extends R{constructor(){super(...arguments);te(this,"forward_params",["input_ids","attention_mask","position_ids","audio_values","past_key_values"])}}class _y extends my{_merge_input_ids_with_audio_features(P){const D=P.audio_features.dims.at(-1),ne=P.audio_features.view(-1,D);return F({audio_token_id:this.config.ignore_index,...P,audio_features:ne})}}class aa extends R{constructor(){super(...arguments);te(this,"main_input_name","input_values");te(this,"forward_params",["input_values"])}}class fy extends pe{constructor({audio_codes:P}){super(),this.audio_codes=P}}class gy extends pe{constructor({audio_values:P}){super(),this.audio_values=P}}class wy extends aa{async encode(P){return new fy(await G(this.sessions.encoder_model,P))}async decode(P){return new gy(await G(this.sessions.decoder_model,P))}}class My extends aa{static async from_pretrained(P,D={}){return super.from_pretrained(P,{...D,model_file_name:D.model_file_name??"encoder_model"})}}class by extends aa{static async from_pretrained(P,D={}){return super.from_pretrained(P,{...D,model_file_name:D.model_file_name??"decoder_model"})}}class la extends R{constructor(){super(...arguments);te(this,"main_input_name","input_values");te(this,"forward_params",["input_values"])}}class yy extends pe{constructor({audio_codes:P}){super(),this.audio_codes=P}}class vy extends pe{constructor({audio_values:P}){super(),this.audio_values=P}}class xy extends la{async encode(P){return new yy(await G(this.sessions.encoder_model,P))}async decode(P){return new vy(await G(this.sessions.decoder_model,P))}}class Ty extends la{static async from_pretrained(P,D={}){return super.from_pretrained(P,{...D,model_file_name:D.model_file_name??"encoder_model"})}}class Ey extends la{static async from_pretrained(P,D={}){return super.from_pretrained(P,{...D,model_file_name:D.model_file_name??"decoder_model"})}}class ua extends R{constructor(){super(...arguments);te(this,"main_input_name","input_values");te(this,"forward_params",["input_values"])}}class Py extends ua{async encode(P){return await G(this.sessions.encoder_model,P)}async decode(P){return await G(this.sessions.decoder_model,P)}}class Cy extends ua{static async from_pretrained(P,D={}){return super.from_pretrained(P,{...D,model_file_name:D.model_file_name??"encoder_model"})}}class Sy extends ua{static async from_pretrained(P,D={}){return super.from_pretrained(P,{...D,model_file_name:D.model_file_name??"decoder_model"})}}class Ct{static async from_pretrained(P,{progress_callback:D=null,config:ne=null,cache_dir:ge=null,local_files_only:fe=!1,revision:Ce="main",model_file_name:Le=null,subfolder:Ne="onnx",device:qe=null,dtype:it=null,use_external_data_format:pt=null,session_options:ot={}}={}){const Mt={progress_callback:D,config:ne,cache_dir:ge,local_files_only:fe,revision:Ce,model_file_name:Le,subfolder:Ne,device:qe,dtype:it,use_external_data_format:pt,session_options:ot};if(Mt.config=await s.AutoConfig.from_pretrained(P,Mt),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);const ct=Mt.config.model_type;for(const gt of this.MODEL_CLASS_MAPPINGS){let rt=gt.get(ct);if(!rt){for(const yt of gt.values())if(yt[0]===ct){rt=yt;break}if(!rt)continue}return await rt[1].from_pretrained(P,Mt)}if(this.BASE_IF_FAIL)return e0.has(ct)||console.warn(`Unknown model class "${ct}", attempting to construct from base class.`),await R.from_pretrained(P,Mt);throw Error(`Unsupported model type: ${ct}`)}}te(Ct,"MODEL_CLASS_MAPPINGS",null),te(Ct,"BASE_IF_FAIL",!1);const Fx=new Map([["bert",["BertModel",Se]],["modernbert",["ModernBertModel",Y]],["nomic_bert",["NomicBertModel",Ee]],["roformer",["RoFormerModel",Ie]],["electra",["ElectraModel",js]],["esm",["EsmModel",Vs]],["convbert",["ConvBertModel",Gt]],["camembert",["CamembertModel",bs]],["deberta",["DebertaModel",De]],["deberta-v2",["DebertaV2Model",ps]],["mpnet",["MPNetModel",mn]],["albert",["AlbertModel",vn]],["distilbert",["DistilBertModel",vr]],["roberta",["RobertaModel",jr]],["xlm",["XLMModel",Ws]],["xlm-roberta",["XLMRobertaModel",Ei]],["clap",["ClapModel",Db]],["clip",["CLIPModel",Ni]],["clipseg",["CLIPSegModel",Lo]],["chinese_clip",["ChineseCLIPModel",Gi]],["siglip",["SiglipModel",En]],["jina_clip",["JinaCLIPModel",Hn]],["mobilebert",["MobileBertModel",Tr]],["squeezebert",["SqueezeBertModel",Mn]],["wav2vec2",["Wav2Vec2Model",QM]],["wav2vec2-bert",["Wav2Vec2BertModel",cb]],["unispeech",["UniSpeechModel",nb]],["unispeech-sat",["UniSpeechSatModel",ab]],["hubert",["HubertModel",mb]],["wavlm",["WavLMModel",gb]],["audio-spectrogram-transformer",["ASTModel",ki]],["vits",["VitsModel",od]],["pyannote",["PyAnnoteModel",eb]],["wespeaker-resnet",["WeSpeakerResNetModel",sb]],["detr",["DetrModel",jw]],["rt_detr",["RTDetrModel",Uw]],["rt_detr_v2",["RTDetrV2Model",Gw]],["rf_detr",["RFDetrModel",qw]],["table-transformer",["TableTransformerModel",Jw]],["vit",["ViTModel",pw]],["ijepa",["IJepaModel",mw]],["pvt",["PvtModel",ww]],["vit_msn",["ViTMSNModel",vw]],["vit_mae",["ViTMAEModel",yw]],["groupvit",["GroupViTModel",Ew]],["fastvit",["FastViTModel",Pw]],["mobilevit",["MobileViTModel",kw]],["mobilevitv2",["MobileViTV2Model",Aw]],["owlvit",["OwlViTModel",Ow]],["owlv2",["Owlv2Model",Lw]],["beit",["BeitModel",Bw]],["deit",["DeiTModel",eM]],["hiera",["HieraModel",rM]],["convnext",["ConvNextModel",kM]],["convnextv2",["ConvNextV2Model",AM]],["dinov2",["Dinov2Model",OM]],["dinov2_with_registers",["Dinov2WithRegistersModel",LM]],["resnet",["ResNetModel",nM]],["swin",["SwinModel",iM]],["swin2sr",["Swin2SRModel",uM]],["donut-swin",["DonutSwinModel",$M]],["yolos",["YolosModel",jM]],["dpt",["DPTModel",cM]],["glpn",["GLPNModel",PM]],["hifigan",["SpeechT5HifiGan",Pb]],["efficientnet",["EfficientNetModel",Ub]],["decision_transformer",["DecisionTransformerModel",ny]],["patchtst",["PatchTSTForPrediction",dy]],["patchtsmixer",["PatchTSMixerForPrediction",py]],["mobilenet_v1",["MobileNetV1Model",Gb]],["mobilenet_v2",["MobileNetV2Model",qb]],["mobilenet_v3",["MobileNetV3Model",Jb]],["mobilenet_v4",["MobileNetV4Model",ey]],["maskformer",["MaskFormerModel",TM]],["mgp-str",["MgpstrForSceneTextRecognition",uy]],["style_text_to_speech_2",["StyleTextToSpeech2Model",xb]]]),Ox=new Map([["t5",["T5Model",ie]],["longt5",["LongT5Model",je]],["mt5",["MT5Model",Je]],["bart",["BartModel",Pt]],["mbart",["MBartModel",br]],["marian",["MarianModel",KM]],["whisper",["WhisperModel",Ai]],["m2m_100",["M2M100Model",qM]],["blenderbot",["BlenderbotModel",Dt]],["blenderbot-small",["BlenderbotSmallModel",Qr]]]),Dx=new Map([["mimi",["MimiModel",wy]],["dac",["DacModel",xy]],["snac",["SnacModel",Py]]]),Lx=new Map([["bloom",["BloomModel",iw]],["jais",["JAISModel",Pn]],["gpt2",["GPT2Model",Ki]],["gptj",["GPTJModel",Vo]],["gpt_bigcode",["GPTBigCodeModel",Yn]],["gpt_neo",["GPTNeoModel",jo]],["gpt_neox",["GPTNeoXModel",Nr]],["codegen",["CodeGenModel",Go]],["llama",["LlamaModel",eo]],["exaone",["ExaoneModel",I]],["olmo",["OlmoModel",Ke]],["olmo2",["Olmo2Model",Tt]],["mobilellm",["MobileLLMModel",ue]],["granite",["GraniteModel",Os]],["cohere",["CohereModel",Vg]],["gemma",["GemmaModel",Wg]],["gemma2",["Gemma2Model",Kg]],["gemma3_text",["Gemma3Model",qg]],["helium",["HeliumModel",Ho]],["glm",["GlmModel",Xo]],["openelm",["OpenELMModel",Qg]],["qwen2",["Qwen2Model",Yg]],["phi",["PhiModel",rw]],["phi3",["Phi3Model",nw]],["mpt",["MptModel",lw]],["opt",["OPTModel",dw]],["mistral",["MistralModel",$b]],["starcoder2",["Starcoder2Model",Ib]],["falcon",["FalconModel",Fb]],["stablelm",["StableLmModel",Nb]]]),pd=new Map([["speecht5",["SpeechT5ForSpeechToText",Tb]],["whisper",["WhisperForConditionalGeneration",Po]],["lite-whisper",["LiteWhisperForConditionalGeneration",Fi]],["moonshine",["MoonshineForConditionalGeneration",Co]]]),$y=new Map([["speecht5",["SpeechT5ForTextToSpeech",Eb]]]),ky=new Map([["vits",["VitsModel",od]],["musicgen",["MusicgenForConditionalGeneration",ud]]]),Iy=new Map([["bert",["BertForSequenceClassification",Fe]],["modernbert",["ModernBertForSequenceClassification",J]],["roformer",["RoFormerForSequenceClassification",Xe]],["electra",["ElectraForSequenceClassification",Ns]],["esm",["EsmForSequenceClassification",Fr]],["convbert",["ConvBertForSequenceClassification",ur]],["camembert",["CamembertForSequenceClassification",ds]],["deberta",["DebertaForSequenceClassification",tt]],["deberta-v2",["DebertaV2ForSequenceClassification",Kr]],["mpnet",["MPNetForSequenceClassification",fn]],["albert",["AlbertForSequenceClassification",he]],["distilbert",["DistilBertForSequenceClassification",cn]],["roberta",["RobertaForSequenceClassification",Vt]],["xlm",["XLMForSequenceClassification",vi]],["xlm-roberta",["XLMRobertaForSequenceClassification",Ci]],["bart",["BartForSequenceClassification",kt]],["mbart",["MBartForSequenceClassification",pr]],["mobilebert",["MobileBertForSequenceClassification",dr]],["squeezebert",["SqueezeBertForSequenceClassification",bn]]]),Ay=new Map([["bert",["BertForTokenClassification",ze]],["modernbert",["ModernBertForTokenClassification",le]],["roformer",["RoFormerForTokenClassification",Ge]],["electra",["ElectraForTokenClassification",at]],["esm",["EsmForTokenClassification",hn]],["convbert",["ConvBertForTokenClassification",ls]],["camembert",["CamembertForTokenClassification",cs]],["deberta",["DebertaForTokenClassification",Rt]],["deberta-v2",["DebertaV2ForTokenClassification",ms]],["mpnet",["MPNetForTokenClassification",gn]],["distilbert",["DistilBertForTokenClassification",xr]],["roberta",["RobertaForTokenClassification",Zt]],["xlm",["XLMForTokenClassification",xi]],["xlm-roberta",["XLMRobertaForTokenClassification",Si]]]),hd=new Map([["t5",["T5ForConditionalGeneration",de]],["longt5",["LongT5ForConditionalGeneration",He]],["mt5",["MT5ForConditionalGeneration",dt]],["bart",["BartForConditionalGeneration",jt]],["mbart",["MBartForConditionalGeneration",cr]],["marian",["MarianMTModel",HM]],["m2m_100",["M2M100ForConditionalGeneration",XM]],["blenderbot",["BlenderbotForConditionalGeneration",rr]],["blenderbot-small",["BlenderbotSmallForConditionalGeneration",Rr]]]),md=new Map([["bloom",["BloomForCausalLM",aw]],["gpt2",["GPT2LMHeadModel",Bo]],["jais",["JAISLMHeadModel",nt]],["gptj",["GPTJForCausalLM",Uo]],["gpt_bigcode",["GPTBigCodeForCausalLM",Wo]],["gpt_neo",["GPTNeoForCausalLM",No]],["gpt_neox",["GPTNeoXForCausalLM",Cn]],["codegen",["CodeGenForCausalLM",$n]],["llama",["LlamaForCausalLM",Ko]],["exaone",["ExaoneForCausalLM",L]],["olmo",["OlmoForCausalLM",Ze]],["olmo2",["Olmo2ForCausalLM",It]],["mobilellm",["MobileLLMForCausalLM",Te]],["granite",["GraniteForCausalLM",Hi]],["cohere",["CohereForCausalLM",Ug]],["gemma",["GemmaForCausalLM",Gg]],["gemma2",["Gemma2ForCausalLM",Hg]],["gemma3_text",["Gemma3ForCausalLM",Xg]],["helium",["HeliumForCausalLM",qo]],["glm",["GlmForCausalLM",h]],["openelm",["OpenELMForCausalLM",Jg]],["qwen2",["Qwen2ForCausalLM",Zg]],["phi",["PhiForCausalLM",sw]],["phi3",["Phi3ForCausalLM",ow]],["mpt",["MptForCausalLM",uw]],["opt",["OPTForCausalLM",cw]],["mbart",["MBartForCausalLM",Nt]],["mistral",["MistralForCausalLM",kb]],["starcoder2",["Starcoder2ForCausalLM",Ab]],["falcon",["FalconForCausalLM",Ob]],["trocr",["TrOCRForCausalLM",Sb]],["stablelm",["StableLmForCausalLM",Vb]],["phi3_v",["Phi3VForCausalLM",Io]]]),zx=new Map([["multi_modality",["MultiModalityCausalLM",iy]]]),Fy=new Map([["bert",["BertForMaskedLM",Ae]],["modernbert",["ModernBertForMaskedLM",z]],["roformer",["RoFormerForMaskedLM",Re]],["electra",["ElectraForMaskedLM",Ss]],["esm",["EsmForMaskedLM",pn]],["convbert",["ConvBertForMaskedLM",Ot]],["camembert",["CamembertForMaskedLM",Ft]],["deberta",["DebertaForMaskedLM",Qe]],["deberta-v2",["DebertaV2ForMaskedLM",hs]],["mpnet",["MPNetForMaskedLM",_n]],["albert",["AlbertForMaskedLM",N]],["distilbert",["DistilBertForMaskedLM",ks]],["roberta",["RobertaForMaskedLM",or]],["xlm",["XLMWithLMHeadModel",xn]],["xlm-roberta",["XLMRobertaForMaskedLM",Pi]],["mobilebert",["MobileBertForMaskedLM",Is]],["squeezebert",["SqueezeBertForMaskedLM",Us]]]),Oy=new Map([["bert",["BertForQuestionAnswering",Ve]],["roformer",["RoFormerForQuestionAnswering",lt]],["electra",["ElectraForQuestionAnswering",us]],["convbert",["ConvBertForQuestionAnswering",Ms]],["camembert",["CamembertForQuestionAnswering",ys]],["deberta",["DebertaForQuestionAnswering",zr]],["deberta-v2",["DebertaV2ForQuestionAnswering",_s]],["mpnet",["MPNetForQuestionAnswering",wn]],["albert",["AlbertForQuestionAnswering",$]],["distilbert",["DistilBertForQuestionAnswering",$s]],["roberta",["RobertaForQuestionAnswering",er]],["xlm",["XLMForQuestionAnswering",Ti]],["xlm-roberta",["XLMRobertaForQuestionAnswering",$i]],["mobilebert",["MobileBertForQuestionAnswering",gr]],["squeezebert",["SqueezeBertForQuestionAnswering",yn]]]),_d=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",So]],["idefics3",["Idefics3ForConditionalGeneration",Ks]],["smolvlm",["SmolVLMForConditionalGeneration",Kn]]]),Dy=new Map([["llava",["LlavaForConditionalGeneration",Tn]],["llava_onevision",["LlavaOnevisionForConditionalGeneration",$o]],["moondream1",["Moondream1ForConditionalGeneration",Gs]],["florence2",["Florence2ForConditionalGeneration",ko]],["qwen2-vl",["Qwen2VLForConditionalGeneration",tw]],["idefics3",["Idefics3ForConditionalGeneration",Ks]],["smolvlm",["SmolVLMForConditionalGeneration",Kn]],["paligemma",["PaliGemmaForConditionalGeneration",Bi]]]),Ly=new Map([["ultravox",["UltravoxModel",_y]]]),Bx=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",So]]]),zy=new Map([["vit",["ViTForImageClassification",hw]],["ijepa",["IJepaForImageClassification",_w]],["pvt",["PvtForImageClassification",Mw]],["vit_msn",["ViTMSNForImageClassification",xw]],["fastvit",["FastViTForImageClassification",Cw]],["mobilevit",["MobileViTForImageClassification",Iw]],["mobilevitv2",["MobileViTV2ForImageClassification",Fw]],["beit",["BeitForImageClassification",Rw]],["deit",["DeiTForImageClassification",tM]],["hiera",["HieraForImageClassification",sM]],["convnext",["ConvNextForImageClassification",IM]],["convnextv2",["ConvNextV2ForImageClassification",FM]],["dinov2",["Dinov2ForImageClassification",DM]],["dinov2_with_registers",["Dinov2WithRegistersForImageClassification",zM]],["resnet",["ResNetForImageClassification",oM]],["swin",["SwinForImageClassification",aM]],["segformer",["SegformerForImageClassification",Rb]],["efficientnet",["EfficientNetForImageClassification",Wb]],["mobilenet_v1",["MobileNetV1ForImageClassification",Kb]],["mobilenet_v2",["MobileNetV2ForImageClassification",Xb]],["mobilenet_v3",["MobileNetV3ForImageClassification",Yb]],["mobilenet_v4",["MobileNetV4ForImageClassification",ty]]]),By=new Map([["detr",["DetrForObjectDetection",Nw]],["rt_detr",["RTDetrForObjectDetection",Ww]],["rt_detr_v2",["RTDetrV2ForObjectDetection",Kw]],["rf_detr",["RFDetrForObjectDetection",Xw]],["table-transformer",["TableTransformerForObjectDetection",Yw]],["yolos",["YolosForObjectDetection",NM]]]),Ry=new Map([["owlvit",["OwlViTForObjectDetection",Dw]],["owlv2",["Owlv2ForObjectDetection",zw]],["grounding-dino",["GroundingDinoForObjectDetection",RM]]]),no=new Map([["detr",["DetrForSegmentation",Du]],["clipseg",["CLIPSegForImageSegmentation",zo]]]),jy=new Map([["segformer",["SegformerForSemanticSegmentation",jb]],["sapiens",["SapiensForSemanticSegmentation",_M]],["swin",["SwinForSemanticSegmentation",lM]],["mobilenet_v1",["MobileNetV1ForSemanticSegmentation",Hb]],["mobilenet_v2",["MobileNetV2ForSemanticSegmentation",Qb]],["mobilenet_v3",["MobileNetV3ForSemanticSegmentation",Zb]],["mobilenet_v4",["MobileNetV4ForSemanticSegmentation",ry]]]),Ny=new Map([["detr",["DetrForSegmentation",Du]],["maskformer",["MaskFormerForInstanceSegmentation",EM]]]),Vy=new Map([["sam",["SamModel",WM]]]),Uy=new Map([["wav2vec2",["Wav2Vec2ForCTC",JM]],["wav2vec2-bert",["Wav2Vec2BertForCTC",pb]],["unispeech",["UniSpeechForCTC",ob]],["unispeech-sat",["UniSpeechSatForCTC",lb]],["wavlm",["WavLMForCTC",wb]],["hubert",["HubertForCTC",_b]]]),Wy=new Map([["wav2vec2",["Wav2Vec2ForSequenceClassification",YM]],["wav2vec2-bert",["Wav2Vec2BertForSequenceClassification",hb]],["unispeech",["UniSpeechForSequenceClassification",ib]],["unispeech-sat",["UniSpeechSatForSequenceClassification",ub]],["wavlm",["WavLMForSequenceClassification",Mb]],["hubert",["HubertForSequenceClassification",fb]],["audio-spectrogram-transformer",["ASTForAudioClassification",Ii]]]),Gy=new Map([["wavlm",["WavLMForXVector",bb]]]),Ky=new Map([["unispeech-sat",["UniSpeechSatForAudioFrameClassification",db]],["wavlm",["WavLMForAudioFrameClassification",yb]],["wav2vec2",["Wav2Vec2ForAudioFrameClassification",ZM]],["pyannote",["PyAnnoteForAudioFrameClassification",tb]]]),Hy=new Map([["vitmatte",["VitMatteForImageMatting",$w]]]),Rx=new Map([["patchtst",["PatchTSTForPrediction",cy]],["patchtsmixer",["PatchTSMixerForPrediction",hy]]]),qy=new Map([["swin2sr",["Swin2SRForImageSuperResolution",dM]]]),Xy=new Map([["dpt",["DPTForDepthEstimation",pM]],["depth_anything",["DepthAnythingForDepthEstimation",mM]],["glpn",["GLPNForDepthEstimation",CM]],["sapiens",["SapiensForDepthEstimation",fM]],["depth_pro",["DepthProForDepthEstimation",MM]],["metric3d",["Metric3DForDepthEstimation",yM]],["metric3dv2",["Metric3Dv2ForDepthEstimation",xM]]]),Qy=new Map([["sapiens",["SapiensForNormalEstimation",gM]]]),Jy=new Map([["vitpose",["VitPoseForPoseEstimation",gw]]]),Yy=new Map([["clip",["CLIPVisionModelWithProjection",Ui]],["siglip",["SiglipVisionModel",Fo]],["jina_clip",["JinaCLIPVisionModel",Do]]]),Zy=[[Fx,E.EncoderOnly],[Ox,E.EncoderDecoder],[Lx,E.DecoderOnly],[Dx,E.AutoEncoder],[Iy,E.EncoderOnly],[Ay,E.EncoderOnly],[hd,E.Seq2Seq],[pd,E.Seq2Seq],[md,E.DecoderOnly],[zx,E.MultiModality],[Fy,E.EncoderOnly],[Oy,E.EncoderOnly],[_d,E.Vision2Seq],[Dy,E.ImageTextToText],[Ly,E.AudioTextToText],[zy,E.EncoderOnly],[no,E.EncoderOnly],[Ny,E.EncoderOnly],[jy,E.EncoderOnly],[Hy,E.EncoderOnly],[Rx,E.EncoderOnly],[qy,E.EncoderOnly],[Xy,E.EncoderOnly],[Qy,E.EncoderOnly],[Jy,E.EncoderOnly],[By,E.EncoderOnly],[Ry,E.EncoderOnly],[Vy,E.MaskGeneration],[Uy,E.EncoderOnly],[Wy,E.EncoderOnly],[$y,E.Seq2Seq],[ky,E.EncoderOnly],[Gy,E.EncoderOnly],[Ky,E.EncoderOnly],[Yy,E.EncoderOnly]];for(const[b,P]of Zy)for(const[D,ne]of b.values())y.set(D,P),v.set(ne,D),M.set(D,ne);const jx=[["MusicgenForConditionalGeneration",ud,E.Musicgen],["Phi3VForCausalLM",Io,E.Phi3V],["CLIPTextModelWithProjection",Vi,E.EncoderOnly],["SiglipTextModel",Hs,E.EncoderOnly],["JinaCLIPTextModel",Oo,E.EncoderOnly],["ClapTextModelWithProjection",Lb,E.EncoderOnly],["ClapAudioModelWithProjection",zb,E.EncoderOnly],["DacEncoderModel",Ty,E.EncoderOnly],["DacDecoderModel",Ey,E.EncoderOnly],["MimiEncoderModel",My,E.EncoderOnly],["MimiDecoderModel",by,E.EncoderOnly],["SnacEncoderModel",Cy,E.EncoderOnly],["SnacDecoderModel",Sy,E.EncoderOnly]];for(const[b,P,D]of jx)y.set(b,D),v.set(P,b),M.set(b,P);const e0=new Map([["modnet",no],["birefnet",no],["isnet",no],["ben",no]]);for(const[b,P]of e0.entries())P.set(b,["PreTrainedModel",R]),y.set(b,E.EncoderOnly),v.set(R,b),M.set(b,R);class fd extends Ct{}te(fd,"MODEL_CLASS_MAPPINGS",Zy.map(P=>P[0])),te(fd,"BASE_IF_FAIL",!0);class t0 extends Ct{}te(t0,"MODEL_CLASS_MAPPINGS",[Iy]);class r0 extends Ct{}te(r0,"MODEL_CLASS_MAPPINGS",[Ay]);class s0 extends Ct{}te(s0,"MODEL_CLASS_MAPPINGS",[hd]);class n0 extends Ct{}te(n0,"MODEL_CLASS_MAPPINGS",[pd]);class o0 extends Ct{}te(o0,"MODEL_CLASS_MAPPINGS",[$y]);class i0 extends Ct{}te(i0,"MODEL_CLASS_MAPPINGS",[ky]);class a0 extends Ct{}te(a0,"MODEL_CLASS_MAPPINGS",[md]);class l0 extends Ct{}te(l0,"MODEL_CLASS_MAPPINGS",[Fy]);class u0 extends Ct{}te(u0,"MODEL_CLASS_MAPPINGS",[Oy]);class d0 extends Ct{}te(d0,"MODEL_CLASS_MAPPINGS",[_d]);class c0 extends Ct{}te(c0,"MODEL_CLASS_MAPPINGS",[zy]);class p0 extends Ct{}te(p0,"MODEL_CLASS_MAPPINGS",[no]);class h0 extends Ct{}te(h0,"MODEL_CLASS_MAPPINGS",[jy]);class m0 extends Ct{}te(m0,"MODEL_CLASS_MAPPINGS",[Ny]);class _0 extends Ct{}te(_0,"MODEL_CLASS_MAPPINGS",[By]);class f0 extends Ct{}te(f0,"MODEL_CLASS_MAPPINGS",[Ry]);class g0 extends Ct{}te(g0,"MODEL_CLASS_MAPPINGS",[Vy]);class w0 extends Ct{}te(w0,"MODEL_CLASS_MAPPINGS",[Uy]);class M0 extends Ct{}te(M0,"MODEL_CLASS_MAPPINGS",[Wy]);class b0 extends Ct{}te(b0,"MODEL_CLASS_MAPPINGS",[Gy]);class y0 extends Ct{}te(y0,"MODEL_CLASS_MAPPINGS",[Ky]);class v0 extends Ct{}te(v0,"MODEL_CLASS_MAPPINGS",[Bx]);class x0 extends Ct{}te(x0,"MODEL_CLASS_MAPPINGS",[Hy]);class T0 extends Ct{}te(T0,"MODEL_CLASS_MAPPINGS",[qy]);class E0 extends Ct{}te(E0,"MODEL_CLASS_MAPPINGS",[Xy]);class P0 extends Ct{}te(P0,"MODEL_CLASS_MAPPINGS",[Qy]);class C0 extends Ct{}te(C0,"MODEL_CLASS_MAPPINGS",[Jy]);class S0 extends Ct{}te(S0,"MODEL_CLASS_MAPPINGS",[Yy]);class $0 extends Ct{}te($0,"MODEL_CLASS_MAPPINGS",[Dy]);class k0 extends Ct{}te(k0,"MODEL_CLASS_MAPPINGS",[Ly]);class Nx extends pe{constructor({logits:P,past_key_values:D,encoder_outputs:ne,decoder_attentions:ge=null,cross_attentions:fe=null}){super(),this.logits=P,this.past_key_values=D,this.encoder_outputs=ne,this.decoder_attentions=ge,this.cross_attentions=fe}}class _t extends pe{constructor({logits:P,...D}){super(),this.logits=P;const ne=Object.values(D);ne.length>0&&(this.attentions=ne)}}class I0 extends pe{constructor({logits:P,embeddings:D}){super(),this.logits=P,this.embeddings=D}}class hr extends pe{constructor({logits:P}){super(),this.logits=P}}class Mr extends pe{constructor({logits:P}){super(),this.logits=P}}class Er extends pe{constructor({start_logits:P,end_logits:D}){super(),this.start_logits=P,this.end_logits=D}}class In extends pe{constructor({logits:P}){super(),this.logits=P}}class Vx extends pe{constructor({logits:P,past_key_values:D}){super(),this.logits=P,this.past_key_values=D}}class A0 extends pe{constructor({alphas:P}){super(),this.alphas=P}}class F0 extends pe{constructor({waveform:P,spectrogram:D}){super(),this.waveform=P,this.spectrogram=D}}},"./src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js":(e,r,t)=>{t.r(r),t.d(r,{ASTFeatureExtractor:()=>n});var s=t("./src/base/feature_extraction_utils.js");t("./src/utils/tensor.js");var o=t("./src/utils/audio.js");class n extends s.FeatureExtractor{constructor(a){super(a);const l=this.config.sampling_rate,u=(0,o.mel_filter_bank)(257,this.config.num_mel_bins,20,Math.floor(l/2),l,null,"kaldi",!0);this.mel_filters=u,this.window=(0,o.window_function)(400,"hann",{periodic:!1}),this.mean=this.config.mean,this.std=this.config.std}async _extract_fbank_features(a,l){return(0,o.spectrogram)(a,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:l,transpose:!0})}async _call(a){(0,s.validate_audio_inputs)(a,"ASTFeatureExtractor");const l=await this._extract_fbank_features(a,this.config.max_length);if(this.config.do_normalize){const u=this.std*2,p=l.data;for(let d=0;d{t.r(r),t.d(r,{AutoFeatureExtractor:()=>i});var s=t("./src/utils/constants.js"),o=t("./src/utils/hub.js");t("./src/base/feature_extraction_utils.js");var n=t("./src/models/feature_extractors.js");class i{static async from_pretrained(l,u={}){const p=await(0,o.getModelJSON)(l,s.FEATURE_EXTRACTOR_NAME,!0,u),d=p.feature_extractor_type,c=n[d];if(!c)throw new Error(`Unknown feature_extractor_type: '${d}'. Please report this at ${s.GITHUB_ISSUE_URL}.`);return new c(p)}}},"./src/models/auto/image_processing_auto.js":(e,r,t)=>{t.r(r),t.d(r,{AutoImageProcessor:()=>a});var s=t("./src/utils/constants.js"),o=t("./src/utils/hub.js"),n=t("./src/base/image_processors_utils.js"),i=t("./src/models/image_processors.js");class a{static async from_pretrained(u,p={}){const d=await(0,o.getModelJSON)(u,s.IMAGE_PROCESSOR_NAME,!0,p),c=d.image_processor_type??d.feature_extractor_type;let f=i[c];return f||(c!==void 0&&console.warn(`Image processor type '${c}' not found, assuming base ImageProcessor. Please report this at ${s.GITHUB_ISSUE_URL}.`),f=n.ImageProcessor),new f(d)}}},"./src/models/auto/processing_auto.js":(e,r,t)=>{t.r(r),t.d(r,{AutoProcessor:()=>u});var s=t("./src/utils/constants.js"),o=t("./src/utils/hub.js"),n=t("./src/base/processing_utils.js"),i=t("./src/models/processors.js"),a=t("./src/models/image_processors.js"),l=t("./src/models/feature_extractors.js");class u{static async from_pretrained(d,c={}){const f=await(0,o.getModelJSON)(d,s.IMAGE_PROCESSOR_NAME,!0,c),{image_processor_type:_,feature_extractor_type:T,processor_class:k}=f;if(k&&i[k])return i[k].from_pretrained(d,c);if(!_&&!T)throw new Error("No `image_processor_type` or `feature_extractor_type` found in the config.");const w={};if(_){const S=a[_];if(!S)throw new Error(`Unknown image_processor_type: '${_}'.`);w.image_processor=new S(f)}if(T){const S=a[T];if(S)w.image_processor=new S(f);else{const E=l[T];if(!E)throw new Error(`Unknown feature_extractor_type: '${T}'.`);w.feature_extractor=new E(f)}}const g={};return new n.Processor(g,w)}}},"./src/models/beit/image_processing_beit.js":(e,r,t)=>{t.r(r),t.d(r,{BeitFeatureExtractor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}},"./src/models/bit/image_processing_bit.js":(e,r,t)=>{t.r(r),t.d(r,{BitImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}},"./src/models/chinese_clip/image_processing_chinese_clip.js":(e,r,t)=>{t.r(r),t.d(r,{ChineseCLIPFeatureExtractor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}},"./src/models/clap/feature_extraction_clap.js":(e,r,t)=>{t.r(r),t.d(r,{ClapFeatureExtractor:()=>n});var s=t("./src/base/feature_extraction_utils.js");t("./src/utils/tensor.js");var o=t("./src/utils/audio.js");class n extends s.FeatureExtractor{constructor(a){super(a),this.mel_filters=(0,o.mel_filter_bank)(this.config.nb_frequency_bins,this.config.feature_size,this.config.frequency_min,this.config.frequency_max,this.config.sampling_rate,null,"htk"),this.mel_filters_slaney=(0,o.mel_filter_bank)(this.config.nb_frequency_bins,this.config.feature_size,this.config.frequency_min,this.config.frequency_max,this.config.sampling_rate,"slaney","slaney"),this.window=(0,o.window_function)(this.config.fft_window_size,"hann")}async _get_input_mel(a,l,u,p){let d;const c=a.length-l;if(c>0)if(u==="rand_trunc"){const f=Math.floor(Math.random()*(c+1));a=a.subarray(f,f+l),d=await this._extract_fbank_features(a,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${u}" not implemented`);else{if(c<0){let f=new Float64Array(l);if(f.set(a),p==="repeat")for(let _=a.length;_{t.r(r),t.d(r,{CLIPFeatureExtractor:()=>n,CLIPImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}class n extends o{}},"./src/models/convnext/image_processing_convnext.js":(e,r,t)=>{t.r(r),t.d(r,{ConvNextFeatureExtractor:()=>n,ConvNextImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{constructor(a){super(a),this.crop_pct=this.config.crop_pct??224/256}async resize(a){var u;const l=(u=this.size)==null?void 0:u.shortest_edge;if(l===void 0)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(l<384){const p=Math.floor(l/this.crop_pct),[d,c]=this.get_resize_output_image_size(a,{shortest_edge:p});a=await a.resize(d,c,{resample:this.resample}),a=await a.center_crop(l,l)}else a=await a.resize(l,l,{resample:this.resample});return a}}class n extends o{}},"./src/models/dac/feature_extraction_dac.js":(e,r,t)=>{t.r(r),t.d(r,{DacFeatureExtractor:()=>o});var s=t("./src/models/encodec/feature_extraction_encodec.js");class o extends s.EncodecFeatureExtractor{}},"./src/models/deit/image_processing_deit.js":(e,r,t)=>{t.r(r),t.d(r,{DeiTFeatureExtractor:()=>n,DeiTImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}class n extends o{}},"./src/models/detr/image_processing_detr.js":(e,r,t)=>{t.r(r),t.d(r,{DetrFeatureExtractor:()=>i,DetrImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js"),o=t("./src/utils/tensor.js");class n extends s.ImageProcessor{async _call(l){const u=await super._call(l),p=[u.pixel_values.dims[0],64,64],d=(0,o.full)(p,1n);return{...u,pixel_mask:d}}post_process_object_detection(...l){return(0,s.post_process_object_detection)(...l)}post_process_panoptic_segmentation(...l){return(0,s.post_process_panoptic_segmentation)(...l)}post_process_instance_segmentation(...l){return(0,s.post_process_instance_segmentation)(...l)}}class i extends n{}},"./src/models/donut/image_processing_donut.js":(e,r,t)=>{t.r(r),t.d(r,{DonutFeatureExtractor:()=>n,DonutImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{pad_image(a,l,u,p={}){const[d,c,f]=l;let _=this.image_mean;Array.isArray(this.image_mean)||(_=new Array(f).fill(_));let T=this.image_std;Array.isArray(T)||(T=new Array(f).fill(_));const k=_.map((w,g)=>-w/T[g]);return super.pad_image(a,l,u,{center:!0,constant_values:k,...p})}}class n extends o{}},"./src/models/dpt/image_processing_dpt.js":(e,r,t)=>{t.r(r),t.d(r,{DPTFeatureExtractor:()=>n,DPTImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}class n extends o{}},"./src/models/efficientnet/image_processing_efficientnet.js":(e,r,t)=>{t.r(r),t.d(r,{EfficientNetImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{constructor(i){super(i),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map(a=>a*a))}}},"./src/models/encodec/feature_extraction_encodec.js":(e,r,t)=>{t.r(r),t.d(r,{EncodecFeatureExtractor:()=>n});var s=t("./src/base/feature_extraction_utils.js"),o=t("./src/utils/tensor.js");class n extends s.FeatureExtractor{async _call(a){(0,s.validate_audio_inputs)(a,"EncodecFeatureExtractor"),a instanceof Float64Array&&(a=new Float32Array(a));const l=this.config.feature_size;if(a.length%l!==0)throw new Error(`The length of the audio data must be a multiple of the number of channels (${l}).`);const u=[1,l,a.length/l];return{input_values:new o.Tensor("float32",a,u)}}}},"./src/models/feature_extractors.js":(e,r,t)=>{t.r(r),t.d(r,{ASTFeatureExtractor:()=>s.ASTFeatureExtractor,ClapFeatureExtractor:()=>n.ClapFeatureExtractor,DacFeatureExtractor:()=>i.DacFeatureExtractor,EncodecFeatureExtractor:()=>o.EncodecFeatureExtractor,ImageFeatureExtractor:()=>T.ImageProcessor,MoonshineFeatureExtractor:()=>a.MoonshineFeatureExtractor,PyAnnoteFeatureExtractor:()=>l.PyAnnoteFeatureExtractor,SeamlessM4TFeatureExtractor:()=>u.SeamlessM4TFeatureExtractor,SnacFeatureExtractor:()=>p.SnacFeatureExtractor,SpeechT5FeatureExtractor:()=>d.SpeechT5FeatureExtractor,Wav2Vec2FeatureExtractor:()=>c.Wav2Vec2FeatureExtractor,WeSpeakerFeatureExtractor:()=>f.WeSpeakerFeatureExtractor,WhisperFeatureExtractor:()=>_.WhisperFeatureExtractor});var s=t("./src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js"),o=t("./src/models/encodec/feature_extraction_encodec.js"),n=t("./src/models/clap/feature_extraction_clap.js"),i=t("./src/models/dac/feature_extraction_dac.js"),a=t("./src/models/moonshine/feature_extraction_moonshine.js"),l=t("./src/models/pyannote/feature_extraction_pyannote.js"),u=t("./src/models/seamless_m4t/feature_extraction_seamless_m4t.js"),p=t("./src/models/snac/feature_extraction_snac.js"),d=t("./src/models/speecht5/feature_extraction_speecht5.js"),c=t("./src/models/wav2vec2/feature_extraction_wav2vec2.js"),f=t("./src/models/wespeaker/feature_extraction_wespeaker.js"),_=t("./src/models/whisper/feature_extraction_whisper.js"),T=t("./src/base/image_processors_utils.js")},"./src/models/florence2/processing_florence2.js":(e,r,t)=>{t.r(r),t.d(r,{Florence2Processor:()=>i});var s=t("./src/base/processing_utils.js"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");class i extends s.Processor{constructor(l,u){super(l,u);const{tasks_answer_post_processing_type:p,task_prompts_without_inputs:d,task_prompts_with_input:c}=this.image_processor.config;this.tasks_answer_post_processing_type=new Map(Object.entries(p??{})),this.task_prompts_without_inputs=new Map(Object.entries(d??{})),this.task_prompts_with_input=new Map(Object.entries(c??{})),this.regexes={quad_boxes:/(.+?)/gm,bboxes:/([^<]+)?/gm},this.size_per_bin=1e3}construct_prompts(l){typeof l=="string"&&(l=[l]);const u=[];for(const p of l)if(this.task_prompts_without_inputs.has(p))u.push(this.task_prompts_without_inputs.get(p));else{for(const[d,c]of this.task_prompts_with_input)if(p.includes(d)){u.push(c.replaceAll("{input}",p).replaceAll(d,""));break}u.length!==l.length&&u.push(p)}return u}post_process_generation(l,u,p){const d=this.tasks_answer_post_processing_type.get(u)??"pure_text";l=l.replaceAll("","").replaceAll("","");let c;switch(d){case"pure_text":c=l;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":const f=d==="ocr"?"quad_boxes":"bboxes",_=l.matchAll(this.regexes[f]),T=[],k=[];for(const[w,g,...S]of _)T.push(g?g.trim():T.at(-1)??""),k.push(S.map((E,y)=>(Number(E)+.5)/this.size_per_bin*p[y%2]));c={labels:T,[f]:k};break;default:throw new Error(`Task "${u}" (of type "${d}") not yet implemented.`)}return{[u]:c}}async _call(l,u=null,p={}){if(!l&&!u)throw new Error("Either text or images must be provided");const d=await this.image_processor(l,p),c=u?this.tokenizer(u,p):{};return{...d,...c}}}te(i,"tokenizer_class",n.AutoTokenizer),te(i,"image_processor_class",o.AutoImageProcessor)},"./src/models/glpn/image_processing_glpn.js":(e,r,t)=>{t.r(r),t.d(r,{GLPNFeatureExtractor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}},"./src/models/grounding_dino/image_processing_grounding_dino.js":(e,r,t)=>{t.r(r),t.d(r,{GroundingDinoImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js"),o=t("./src/utils/tensor.js");class n extends s.ImageProcessor{async _call(a){const l=await super._call(a),u=l.pixel_values.dims,p=(0,o.ones)([u[0],u[2],u[3]]);return{...l,pixel_mask:p}}}},"./src/models/grounding_dino/processing_grounding_dino.js":(e,r,t)=>{t.r(r),t.d(r,{GroundingDinoProcessor:()=>l});var s=t("./src/base/processing_utils.js"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js"),i=t("./src/base/image_processors_utils.js");function a(u,p){const c=u.dims.at(-1)-1,f=u.tolist();f.fill(!1,0,1),f.fill(!1,c);const _=p.tolist();return f.map((T,k)=>T?k:null).filter(T=>T!==null).map(T=>_[T])}class l extends s.Processor{async _call(p,d,c={}){const f=p?await this.image_processor(p,c):{};return{...d?this.tokenizer(d,c):{},...f}}post_process_grounded_object_detection(p,d,{box_threshold:c=.25,text_threshold:f=.25,target_sizes:_=null}={}){const{logits:T,pred_boxes:k}=p,w=T.dims[0];if(_!==null&&_.length!==w)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const g=T.dims.at(1),S=T.sigmoid(),E=S.max(-1).tolist(),y=k.tolist().map(v=>v.map(C=>(0,i.center_to_corners_format)(C))),M=[];for(let v=0;vj.map((ee,H)=>ee*C[(H+1)%2])));const A=E[v],B=[],K=[],G=[];for(let j=0;j{t.r(r),t.d(r,{Idefics3ImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js"),o=t("./src/utils/tensor.js");class n extends s.ImageProcessor{constructor(a){super(a),this.do_image_splitting=a.do_image_splitting??!0,this.max_image_size=a.max_image_size}get_resize_for_vision_encoder(a,l){let[u,p]=a.dims.slice(-2);const d=p/u;return p>=u?(p=Math.ceil(p/l)*l,u=Math.floor(p/d),u=Math.ceil(u/l)*l):(u=Math.ceil(u/l)*l,p=Math.floor(u*d),p=Math.ceil(p/l)*l),{height:u,width:p}}async _call(a,{do_image_splitting:l=null,return_row_col_info:u=!1}={}){let p;if(!Array.isArray(a))p=[[a]];else{if(a.length===0||!a[0])throw new Error("No images provided.");Array.isArray(a[0])?p=a:p=[a]}let d=[],c=[],f=[];const _=[],T=[];for(const v of p){let C=await Promise.all(v.map(K=>this.preprocess(K)));_.push(...C.map(K=>K.original_size)),T.push(...C.map(K=>K.reshaped_input_size)),C.forEach(K=>K.pixel_values.unsqueeze_(0));const{longest_edge:A}=this.max_image_size;let B;if(l??this.do_image_splitting){let K=new Array(C.length),G=new Array(C.length);B=await Promise.all(C.map(async(j,ee)=>{const H=this.get_resize_for_vision_encoder(j.pixel_values,A),Z=await(0,o.interpolate_4d)(j.pixel_values,{size:[H.height,H.width]}),{frames:X,num_splits_h:oe,num_splits_w:me}=await this.split_image(Z,this.max_image_size);return K[ee]=oe,G[ee]=me,(0,o.cat)(X,0)})),c.push(K),f.push(G)}else{const K=[A,A];B=await Promise.all(C.map(G=>(0,o.interpolate_4d)(G.pixel_values,{size:K}))),c.push(new Array(C.length).fill(0)),f.push(new Array(C.length).fill(0))}d.push((0,o.cat)(B,0))}const k=d.length,[w,g,S,E]=d[0].dims;let y,M;if(k===1)y=d[0].unsqueeze_(0),M=(0,o.full)([k,w,S,E],!0);else{const v=Math.max(...d.map(B=>B.dims.at(0)));M=(0,o.full)([k,v,S,E],!0);const C=M.data,A=v*S*E;for(let B=0;Bu||f>p){_=Math.ceil(c/u),T=Math.ceil(f/p);const k=Math.ceil(c/_),w=Math.ceil(f/T);for(let E=0;E<_;++E)for(let y=0;y{t.r(r),t.d(r,{Idefics3Processor:()=>p});var s=t("./src/base/processing_utils.js"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");t("./src/utils/image.js");var i=t("./src/utils/core.js");function a(d,c,f,_,T,k){let w="";for(let g=0;g`+T.repeat(d);w+=` +`}return w+=` +${_}${k}`+T.repeat(d)+`${_}`,w}function l(d,c,f,_){return`${c}${_}`+f.repeat(d)+`${c}`}function u(d,c,f,_,T,k){return d===0&&c===0?l(f,_,T,k):a(f,d,c,_,T,k)}class p extends s.Processor{constructor(){super(...arguments);te(this,"fake_image_token","");te(this,"image_token","");te(this,"global_img_token","")}async _call(f,_=null,T={}){T.return_row_col_info??(T.return_row_col_info=!0);let k;_&&(k=await this.image_processor(_,T)),Array.isArray(f)||(f=[f]);const w=k.rows??[new Array(f.length).fill(0)],g=k.cols??[new Array(f.length).fill(0)],S=this.config.image_seq_len,E=[],y=[];for(let v=0;vu(ee,B[H],S,this.fake_image_token,this.image_token,this.global_img_token)),G=C.split(this.image_token);if(G.length===0)throw new Error("The image token should be present in the text.");let j=G[0];for(let ee=0;ee{t.r(r),t.d(r,{BeitFeatureExtractor:()=>s.BeitFeatureExtractor,BitImageProcessor:()=>o.BitImageProcessor,CLIPFeatureExtractor:()=>i.CLIPFeatureExtractor,CLIPImageProcessor:()=>i.CLIPImageProcessor,ChineseCLIPFeatureExtractor:()=>n.ChineseCLIPFeatureExtractor,ConvNextFeatureExtractor:()=>a.ConvNextFeatureExtractor,ConvNextImageProcessor:()=>a.ConvNextImageProcessor,DPTFeatureExtractor:()=>d.DPTFeatureExtractor,DPTImageProcessor:()=>d.DPTImageProcessor,DeiTFeatureExtractor:()=>l.DeiTFeatureExtractor,DeiTImageProcessor:()=>l.DeiTImageProcessor,DetrFeatureExtractor:()=>u.DetrFeatureExtractor,DetrImageProcessor:()=>u.DetrImageProcessor,DonutFeatureExtractor:()=>p.DonutFeatureExtractor,DonutImageProcessor:()=>p.DonutImageProcessor,EfficientNetImageProcessor:()=>c.EfficientNetImageProcessor,GLPNFeatureExtractor:()=>f.GLPNFeatureExtractor,GroundingDinoImageProcessor:()=>_.GroundingDinoImageProcessor,Idefics3ImageProcessor:()=>T.Idefics3ImageProcessor,JinaCLIPImageProcessor:()=>w.JinaCLIPImageProcessor,LlavaOnevisionImageProcessor:()=>g.LlavaOnevisionImageProcessor,Mask2FormerImageProcessor:()=>S.Mask2FormerImageProcessor,MaskFormerFeatureExtractor:()=>E.MaskFormerFeatureExtractor,MaskFormerImageProcessor:()=>E.MaskFormerImageProcessor,MobileNetV1FeatureExtractor:()=>y.MobileNetV1FeatureExtractor,MobileNetV1ImageProcessor:()=>y.MobileNetV1ImageProcessor,MobileNetV2FeatureExtractor:()=>M.MobileNetV2FeatureExtractor,MobileNetV2ImageProcessor:()=>M.MobileNetV2ImageProcessor,MobileNetV3FeatureExtractor:()=>v.MobileNetV3FeatureExtractor,MobileNetV3ImageProcessor:()=>v.MobileNetV3ImageProcessor,MobileNetV4FeatureExtractor:()=>C.MobileNetV4FeatureExtractor,MobileNetV4ImageProcessor:()=>C.MobileNetV4ImageProcessor,MobileViTFeatureExtractor:()=>A.MobileViTFeatureExtractor,MobileViTImageProcessor:()=>A.MobileViTImageProcessor,NougatImageProcessor:()=>B.NougatImageProcessor,OwlViTFeatureExtractor:()=>G.OwlViTFeatureExtractor,OwlViTImageProcessor:()=>G.OwlViTImageProcessor,Owlv2ImageProcessor:()=>K.Owlv2ImageProcessor,Phi3VImageProcessor:()=>j.Phi3VImageProcessor,PvtImageProcessor:()=>ee.PvtImageProcessor,Qwen2VLImageProcessor:()=>H.Qwen2VLImageProcessor,RTDetrImageProcessor:()=>Z.RTDetrImageProcessor,SamImageProcessor:()=>X.SamImageProcessor,SegformerFeatureExtractor:()=>oe.SegformerFeatureExtractor,SegformerImageProcessor:()=>oe.SegformerImageProcessor,SiglipImageProcessor:()=>me.SiglipImageProcessor,SmolVLMImageProcessor:()=>ae.SmolVLMImageProcessor,Swin2SRImageProcessor:()=>V.Swin2SRImageProcessor,VLMImageProcessor:()=>k.VLMImageProcessor,ViTFeatureExtractor:()=>F.ViTFeatureExtractor,ViTImageProcessor:()=>F.ViTImageProcessor,VitMatteImageProcessor:()=>W.VitMatteImageProcessor,VitPoseImageProcessor:()=>re.VitPoseImageProcessor,YolosFeatureExtractor:()=>_e.YolosFeatureExtractor,YolosImageProcessor:()=>_e.YolosImageProcessor});var s=t("./src/models/beit/image_processing_beit.js"),o=t("./src/models/bit/image_processing_bit.js"),n=t("./src/models/chinese_clip/image_processing_chinese_clip.js"),i=t("./src/models/clip/image_processing_clip.js"),a=t("./src/models/convnext/image_processing_convnext.js"),l=t("./src/models/deit/image_processing_deit.js"),u=t("./src/models/detr/image_processing_detr.js"),p=t("./src/models/donut/image_processing_donut.js"),d=t("./src/models/dpt/image_processing_dpt.js"),c=t("./src/models/efficientnet/image_processing_efficientnet.js"),f=t("./src/models/glpn/image_processing_glpn.js"),_=t("./src/models/grounding_dino/image_processing_grounding_dino.js"),T=t("./src/models/idefics3/image_processing_idefics3.js"),k=t("./src/models/janus/image_processing_janus.js"),w=t("./src/models/jina_clip/image_processing_jina_clip.js"),g=t("./src/models/llava_onevision/image_processing_llava_onevision.js"),S=t("./src/models/mask2former/image_processing_mask2former.js"),E=t("./src/models/maskformer/image_processing_maskformer.js"),y=t("./src/models/mobilenet_v1/image_processing_mobilenet_v1.js"),M=t("./src/models/mobilenet_v2/image_processing_mobilenet_v2.js"),v=t("./src/models/mobilenet_v3/image_processing_mobilenet_v3.js"),C=t("./src/models/mobilenet_v4/image_processing_mobilenet_v4.js"),A=t("./src/models/mobilevit/image_processing_mobilevit.js"),B=t("./src/models/nougat/image_processing_nougat.js"),K=t("./src/models/owlv2/image_processing_owlv2.js"),G=t("./src/models/owlvit/image_processing_owlvit.js"),j=t("./src/models/phi3_v/image_processing_phi3_v.js"),ee=t("./src/models/pvt/image_processing_pvt.js"),H=t("./src/models/qwen2_vl/image_processing_qwen2_vl.js"),Z=t("./src/models/rt_detr/image_processing_rt_detr.js"),X=t("./src/models/sam/image_processing_sam.js"),oe=t("./src/models/segformer/image_processing_segformer.js"),me=t("./src/models/siglip/image_processing_siglip.js"),ae=t("./src/models/smolvlm/image_processing_smolvlm.js"),V=t("./src/models/swin2sr/image_processing_swin2sr.js"),F=t("./src/models/vit/image_processing_vit.js"),W=t("./src/models/vitmatte/image_processing_vitmatte.js"),re=t("./src/models/vitpose/image_processing_vitpose.js"),_e=t("./src/models/yolos/image_processing_yolos.js")},"./src/models/janus/image_processing_janus.js":(e,r,t)=>{t.r(r),t.d(r,{VLMImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{constructor(i){super({do_pad:!0,pad_size:{width:i.image_size,height:i.image_size},...i}),this.constant_values=this.config.background_color.map(a=>a*this.rescale_factor)}pad_image(i,a,l,u){return super.pad_image(i,a,l,{constant_values:this.constant_values,center:!0,...u})}}},"./src/models/janus/processing_janus.js":(e,r,t)=>{t.r(r),t.d(r,{VLChatProcessor:()=>u});var s=t("./src/base/processing_utils.js"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js"),i=t("./src/utils/core.js"),a=t("./src/utils/tensor.js"),l=t("./src/utils/image.js");class u extends s.Processor{constructor(d,c){super(d,c),this.image_tag=this.config.image_tag,this.image_start_tag=this.config.image_start_tag,this.image_end_tag=this.config.image_end_tag,this.num_image_tokens=this.config.num_image_tokens}async _call(d,{images:c=null,chat_template:f="default"}={}){c?Array.isArray(c)||(c=[c]):c=await Promise.all(d.filter(B=>B.images).flatMap(B=>B.images).map(B=>l.RawImage.read(B)));const _=this.tokenizer,T=_.apply_chat_template(d,{tokenize:!1,add_generation_prompt:!0,chat_template:f}),k=B=>_.encode(B,{add_special_tokens:!1}),w=T.split(this.image_tag),g=w.length-1;if(c.length!==g)throw new Error(`Number of images provided (${c.length}) does not match number of "${this.image_tag}" image tags (${g})`);const[S,E,y]=_.model.convert_tokens_to_ids([this.image_tag,this.image_start_tag,this.image_end_tag]);let M=k(w[0]),v=new Array(M.length).fill(!1);for(let B=1;B0){const B=await this.image_processor(c);return B.pixel_values.unsqueeze_(0),{...A,...B}}return A}}te(u,"image_processor_class",o.AutoImageProcessor),te(u,"tokenizer_class",n.AutoTokenizer),te(u,"uses_processor_config",!0)},"./src/models/jina_clip/image_processing_jina_clip.js":(e,r,t)=>{t.r(r),t.d(r,{JinaCLIPImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{constructor(i){const{resize_mode:a,fill_color:l,interpolation:u,size:p,...d}=i,c=a==="squash"?{width:p,height:p}:a==="shortest"?{shortest_edge:p}:{longest_edge:p},f=u==="bicubic"?3:2;super({...d,size:c,resample:f,do_center_crop:!0,crop_size:p,do_normalize:!0})}}},"./src/models/jina_clip/processing_jina_clip.js":(e,r,t)=>{t.r(r),t.d(r,{JinaCLIPProcessor:()=>i});var s=t("./src/base/processing_utils.js"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");class i extends s.Processor{async _call(l=null,u=null,p={}){if(!l&&!u)throw new Error("Either text or images must be provided");const d=l?this.tokenizer(l,p):{},c=u?await this.image_processor(u,p):{};return{...d,...c}}}te(i,"tokenizer_class",n.AutoTokenizer),te(i,"image_processor_class",o.AutoImageProcessor)},"./src/models/llava_onevision/image_processing_llava_onevision.js":(e,r,t)=>{t.r(r),t.d(r,{LlavaOnevisionImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}},"./src/models/mask2former/image_processing_mask2former.js":(e,r,t)=>{t.r(r),t.d(r,{Mask2FormerImageProcessor:()=>o});var s=t("./src/models/maskformer/image_processing_maskformer.js");class o extends s.MaskFormerImageProcessor{}},"./src/models/maskformer/image_processing_maskformer.js":(e,r,t)=>{t.r(r),t.d(r,{MaskFormerFeatureExtractor:()=>n,MaskFormerImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{post_process_panoptic_segmentation(...a){return(0,s.post_process_panoptic_segmentation)(...a)}post_process_instance_segmentation(...a){return(0,s.post_process_instance_segmentation)(...a)}}class n extends o{}},"./src/models/mgp_str/processing_mgp_str.js":(e,r,t)=>{t.r(r),t.d(r,{MgpstrProcessor:()=>l});var s=t("./src/base/processing_utils.js"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js"),i=t("./src/utils/maths.js");const a={char:["char_decode",1],bpe:["bpe_decode",2],wp:["wp_decode",102]};class l extends s.Processor{get char_tokenizer(){return this.components.char_tokenizer}get bpe_tokenizer(){return this.components.bpe_tokenizer}get wp_tokenizer(){return this.components.wp_tokenizer}_decode_helper(p,d){if(!a.hasOwnProperty(d))throw new Error(`Format ${d} is not supported.`);const[c,f]=a[d],_=this[c].bind(this),[T,k]=p.dims,w=[],g=[],S=p.tolist();for(let y=0;y0?C.reduce((B,K)=>B*K,1):0;g.push(v),w.push(A)}return[_(g),w]}char_decode(p){return this.char_tokenizer.batch_decode(p).map(d=>d.replaceAll(" ",""))}bpe_decode(p){return this.bpe_tokenizer.batch_decode(p)}wp_decode(p){return this.wp_tokenizer.batch_decode(p).map(d=>d.replaceAll(" ",""))}batch_decode([p,d,c]){const[f,_]=this._decode_helper(p,"char"),[T,k]=this._decode_helper(d,"bpe"),[w,g]=this._decode_helper(c,"wp"),S=[],E=[];for(let y=0;y{t.r(r),t.d(r,{MobileNetV1FeatureExtractor:()=>n,MobileNetV1ImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}class n extends o{}},"./src/models/mobilenet_v2/image_processing_mobilenet_v2.js":(e,r,t)=>{t.r(r),t.d(r,{MobileNetV2FeatureExtractor:()=>n,MobileNetV2ImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}class n extends o{}},"./src/models/mobilenet_v3/image_processing_mobilenet_v3.js":(e,r,t)=>{t.r(r),t.d(r,{MobileNetV3FeatureExtractor:()=>n,MobileNetV3ImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}class n extends o{}},"./src/models/mobilenet_v4/image_processing_mobilenet_v4.js":(e,r,t)=>{t.r(r),t.d(r,{MobileNetV4FeatureExtractor:()=>n,MobileNetV4ImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}class n extends o{}},"./src/models/mobilevit/image_processing_mobilevit.js":(e,r,t)=>{t.r(r),t.d(r,{MobileViTFeatureExtractor:()=>n,MobileViTImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}class n extends o{}},"./src/models/moonshine/feature_extraction_moonshine.js":(e,r,t)=>{t.r(r),t.d(r,{MoonshineFeatureExtractor:()=>n});var s=t("./src/base/feature_extraction_utils.js"),o=t("./src/utils/tensor.js");class n extends s.FeatureExtractor{async _call(a){(0,s.validate_audio_inputs)(a,"MoonshineFeatureExtractor"),a instanceof Float64Array&&(a=new Float32Array(a));const l=[1,a.length];return{input_values:new o.Tensor("float32",a,l)}}}},"./src/models/moonshine/processing_moonshine.js":(e,r,t)=>{t.r(r),t.d(r,{MoonshineProcessor:()=>i});var s=t("./src/models/auto/feature_extraction_auto.js"),o=t("./src/tokenizers.js"),n=t("./src/base/processing_utils.js");class i extends n.Processor{async _call(l){return await this.feature_extractor(l)}}te(i,"tokenizer_class",o.AutoTokenizer),te(i,"feature_extractor_class",s.AutoFeatureExtractor)},"./src/models/nougat/image_processing_nougat.js":(e,r,t)=>{t.r(r),t.d(r,{NougatImageProcessor:()=>o});var s=t("./src/models/donut/image_processing_donut.js");class o extends s.DonutImageProcessor{}},"./src/models/owlv2/image_processing_owlv2.js":(e,r,t)=>{t.r(r),t.d(r,{Owlv2ImageProcessor:()=>o});var s=t("./src/models/owlvit/image_processing_owlvit.js");class o extends s.OwlViTImageProcessor{}},"./src/models/owlvit/image_processing_owlvit.js":(e,r,t)=>{t.r(r),t.d(r,{OwlViTFeatureExtractor:()=>n,OwlViTImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{post_process_object_detection(...a){return(0,s.post_process_object_detection)(...a)}}class n extends o{}},"./src/models/owlvit/processing_owlvit.js":(e,r,t)=>{t.r(r),t.d(r,{OwlViTProcessor:()=>i});var s=t("./src/base/processing_utils.js"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");class i extends s.Processor{}te(i,"tokenizer_class",n.AutoTokenizer),te(i,"image_processor_class",o.AutoImageProcessor)},"./src/models/paligemma/processing_paligemma.js":(e,r,t)=>{t.r(r),t.d(r,{PaliGemmaProcessor:()=>l});var s=t("./src/base/processing_utils.js"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");const i="";function a(u,p,d,c,f){return`${c.repeat(d*f)}${p}${u} +`}class l extends s.Processor{async _call(p,d=null,c={}){d||(console.warn("You are using PaliGemma without a text prefix. It will perform as a picture-captioning model."),d=""),Array.isArray(p)||(p=[p]),Array.isArray(d)||(d=[d]);const f=this.tokenizer.bos_token,_=this.image_processor.config.image_seq_length;let T;d.some(g=>g.includes(i))?T=d.map(g=>{const S=g.replaceAll(i,i.repeat(_)),E=S.lastIndexOf(i),y=E===-1?0:E+i.length;return S.slice(0,y)+f+S.slice(y)+` +`}):(console.warn("You are passing both `text` and `images` to `PaliGemmaProcessor`. The processor expects special image tokens in the text, as many tokens as there are images per each text. It is recommended to add `` tokens in the very beginning of your text. For this call, we will infer how many images each text has and add special tokens."),T=d.map(g=>a(g,f,_,i,p.length)));const k=this.tokenizer(T,c);return{...await this.image_processor(p,c),...k}}}te(l,"tokenizer_class",n.AutoTokenizer),te(l,"image_processor_class",o.AutoImageProcessor),te(l,"uses_processor_config",!1)},"./src/models/phi3_v/image_processing_phi3_v.js":(e,r,t)=>{t.r(r),t.d(r,{Phi3VImageProcessor:()=>p});var s=t("./src/base/image_processors_utils.js"),o=t("./src/utils/tensor.js");const n=336,i=[2,3],{ceil:a,floor:l,sqrt:u}=Math;class p extends s.ImageProcessor{constructor(c){super({...c,do_normalize:!0,do_pad:!0,pad_size:"custom",do_convert_rgb:!0,do_resize:!0}),this._num_crops=c.num_crops}calc_num_image_tokens_from_image_size(c,f){const{num_img_tokens:_}=this.config;return l((l(f/n)*l(c/n)+1)*_+1+(l(f/n)+1)*u(_))}get_resize_output_image_size(c,f){const _=this._num_crops,[T,k]=c.size;let w=T/k,g=1;for(;g*Math.ceil(g/w)<=_;)g+=1;g-=1;const S=Math.floor(g*336),E=Math.floor(S/w);return[S,E]}pad_image(c,f,_,T={}){const[k,w]=f,g=n*a(k/n),S=n*a(w/n),E=[1,1,1].map((y,M)=>(y-this.image_mean[M])/this.image_std[M]);return super.pad_image(c,f,{width:S,height:g},{center:!0,constant_values:E,...T})}async _call(c,{num_crops:f=null}={}){if(this._num_crops=f??(f=this.config.num_crops),f<4||u(f)%1!==0)throw new Error("num_crops must be a square number >= 4");Array.isArray(c)||(c=[c]);const _=c.length,T=await Promise.all(c.map(v=>this.preprocess(v))),k=T.map(v=>v.original_size),w=T.map(v=>v.reshaped_input_size),g=[];for(const{pixel_values:v}of T){v.unsqueeze_(0);const[C,A]=v.dims.slice(-2),B=await(0,o.interpolate_4d)(v,{size:[n,n],mode:"bicubic"});if(f>0){const K=[],G=u(f),j=l(A/G),ee=l(C/G);for(let Z=0;Zv.map(C=>n*a(C/n))),y=new o.Tensor("int64",E.flat(),[_,2]),M=E.map(([v,C])=>this.calc_num_image_tokens_from_image_size(C,v));return{pixel_values:S,original_sizes:k,reshaped_input_sizes:w,image_sizes:y,num_img_tokens:M}}}},"./src/models/phi3_v/processing_phi3_v.js":(e,r,t)=>{t.r(r),t.d(r,{Phi3VProcessor:()=>l});var s=t("./src/base/processing_utils.js"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");t("./src/utils/image.js");const i="<|image|>",a=/<\|image_\d+\|>/g;class l extends s.Processor{async _call(p,d=null,{padding:c=!0,truncation:f=!0,num_crops:_=null}={}){Array.isArray(p)||(p=[p]);let T,k;if(d){k=await this.image_processor(d,{num_crops:_});const{num_img_tokens:w}=k,g=p.map((E,y)=>E.split(a).join(i.repeat(w[y])));T=this.tokenizer(g,{padding:c,truncation:f});const S=this.tokenizer.model.convert_tokens_to_ids([i])[0];T.input_ids.map_(E=>E==S?-E:E)}else T=this.tokenizer(p);return{...T,...k}}}te(l,"image_processor_class",o.AutoImageProcessor),te(l,"tokenizer_class",n.AutoTokenizer)},"./src/models/processors.js":(e,r,t)=>{t.r(r),t.d(r,{Florence2Processor:()=>s.Florence2Processor,GroundingDinoProcessor:()=>o.GroundingDinoProcessor,Idefics3Processor:()=>n.Idefics3Processor,JinaCLIPProcessor:()=>a.JinaCLIPProcessor,MgpstrProcessor:()=>l.MgpstrProcessor,MoonshineProcessor:()=>u.MoonshineProcessor,OwlViTProcessor:()=>p.OwlViTProcessor,PaliGemmaProcessor:()=>c.PaliGemmaProcessor,Phi3VProcessor:()=>d.Phi3VProcessor,PyAnnoteProcessor:()=>f.PyAnnoteProcessor,Qwen2VLProcessor:()=>_.Qwen2VLProcessor,SamProcessor:()=>T.SamProcessor,SmolVLMProcessor:()=>k.SmolVLMProcessor,SpeechT5Processor:()=>w.SpeechT5Processor,UltravoxProcessor:()=>g.UltravoxProcessor,VLChatProcessor:()=>i.VLChatProcessor,Wav2Vec2Processor:()=>S.Wav2Vec2Processor,Wav2Vec2ProcessorWithLM:()=>E.Wav2Vec2ProcessorWithLM,WhisperProcessor:()=>y.WhisperProcessor});var s=t("./src/models/florence2/processing_florence2.js"),o=t("./src/models/grounding_dino/processing_grounding_dino.js"),n=t("./src/models/idefics3/processing_idefics3.js"),i=t("./src/models/janus/processing_janus.js"),a=t("./src/models/jina_clip/processing_jina_clip.js"),l=t("./src/models/mgp_str/processing_mgp_str.js"),u=t("./src/models/moonshine/processing_moonshine.js"),p=t("./src/models/owlvit/processing_owlvit.js"),d=t("./src/models/phi3_v/processing_phi3_v.js"),c=t("./src/models/paligemma/processing_paligemma.js"),f=t("./src/models/pyannote/processing_pyannote.js"),_=t("./src/models/qwen2_vl/processing_qwen2_vl.js"),T=t("./src/models/sam/processing_sam.js"),k=t("./src/models/smolvlm/processing_smolvlm.js"),w=t("./src/models/speecht5/processing_speecht5.js"),g=t("./src/models/ultravox/processing_ultravox.js"),S=t("./src/models/wav2vec2/processing_wav2vec2.js"),E=t("./src/models/wav2vec2_with_lm/processing_wav2vec2_with_lm.js"),y=t("./src/models/whisper/processing_whisper.js")},"./src/models/pvt/image_processing_pvt.js":(e,r,t)=>{t.r(r),t.d(r,{PvtImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}},"./src/models/pyannote/feature_extraction_pyannote.js":(e,r,t)=>{t.r(r),t.d(r,{PyAnnoteFeatureExtractor:()=>i});var s=t("./src/base/feature_extraction_utils.js"),o=t("./src/utils/tensor.js"),n=t("./src/utils/maths.js");class i extends s.FeatureExtractor{async _call(l){(0,s.validate_audio_inputs)(l,"PyAnnoteFeatureExtractor"),l instanceof Float64Array&&(l=new Float32Array(l));const u=[1,1,l.length];return{input_values:new o.Tensor("float32",l,u)}}samples_to_frames(l){return(l-this.config.offset)/this.config.step}post_process_speaker_diarization(l,u){const p=u/this.samples_to_frames(u)/this.config.sampling_rate,d=[];for(const c of l.tolist()){const f=[];let _=-1;for(let T=0;T({id:T,start:k*p,end:w*p,confidence:g/(w-k)})))}return d}}},"./src/models/pyannote/processing_pyannote.js":(e,r,t)=>{t.r(r),t.d(r,{PyAnnoteProcessor:()=>n});var s=t("./src/base/processing_utils.js"),o=t("./src/models/pyannote/feature_extraction_pyannote.js");class n extends s.Processor{async _call(a){return await this.feature_extractor(a)}post_process_speaker_diarization(...a){return this.feature_extractor.post_process_speaker_diarization(...a)}get sampling_rate(){return this.feature_extractor.config.sampling_rate}}te(n,"feature_extractor_class",o.PyAnnoteFeatureExtractor)},"./src/models/qwen2_vl/image_processing_qwen2_vl.js":(e,r,t)=>{t.r(r),t.d(r,{Qwen2VLImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js"),o=t("./src/utils/tensor.js");class n extends s.ImageProcessor{async _call(a,...l){const{pixel_values:u,original_sizes:p,reshaped_input_sizes:d}=await super._call(a,...l);let c=u;const{temporal_patch_size:f,merge_size:_,patch_size:T}=this.config;c.dims[0]===1&&(c=(0,o.cat)(Array.from({length:f},()=>c),0));const k=c.dims[0]/f,w=c.dims[1],g=Math.floor(c.dims[2]/T),S=Math.floor(c.dims[3]/T),E=c.view(k,f,w,Math.floor(g/_),_,T,Math.floor(S/_),_,T).permute(0,3,6,4,7,2,1,5,8).view(k*g*S,w*f*T*T),y=new o.Tensor("int64",[k,g,S],[1,3]);return{pixel_values:E,image_grid_thw:y,original_sizes:p,reshaped_input_sizes:d}}}},"./src/models/qwen2_vl/processing_qwen2_vl.js":(e,r,t)=>{t.r(r),t.d(r,{Qwen2VLProcessor:()=>i});var s=t("./src/base/processing_utils.js"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");t("./src/utils/image.js");class i extends s.Processor{async _call(l,u=null,...p){Array.isArray(l)||(l=[l]);let d,c;if(u&&(d=await this.image_processor(u),c=d.image_grid_thw),c){let _=this.image_processor.config.merge_size**2,T=0;const k=c.tolist();l=l.map(w=>{for(;w.includes("<|image_pad|>");){const g=Number(k[T++].reduce((S,E)=>S*E,1n));w=w.replace("<|image_pad|>","<|placeholder|>".repeat(Math.floor(g/_)))}return w.replaceAll("<|placeholder|>","<|image_pad|>")})}return{...this.tokenizer(l),...d}}}te(i,"image_processor_class",o.AutoImageProcessor),te(i,"tokenizer_class",n.AutoTokenizer)},"./src/models/rt_detr/image_processing_rt_detr.js":(e,r,t)=>{t.r(r),t.d(r,{RTDetrImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{post_process_object_detection(...i){return(0,s.post_process_object_detection)(...i)}}},"./src/models/sam/image_processing_sam.js":(e,r,t)=>{t.r(r),t.d(r,{SamImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js"),o=t("./src/utils/core.js"),n=t("./src/utils/tensor.js");class i extends s.ImageProcessor{reshape_input_points(l,u,p,d=!1){l=structuredClone(l);let c=(0,o.calculateDimensions)(l);if(c.length===3)d||(c=[1,...c]),l=[l];else if(c.length!==4)throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.");for(let f=0;fd!==u.dims[c]))throw Error(`The first ${p.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new n.Tensor("int64",l.flat(1/0).map(BigInt),p)}async _call(l,{input_points:u=null,input_labels:p=null,input_boxes:d=null}={}){const c=await super._call(l);if(u&&(c.input_points=this.reshape_input_points(u,c.original_sizes,c.reshaped_input_sizes)),p){if(!c.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");c.input_labels=this.add_input_labels(p,c.input_points)}return d&&(c.input_boxes=this.reshape_input_points(d,c.original_sizes,c.reshaped_input_sizes,!0)),c}async post_process_masks(l,u,p,{mask_threshold:d=0,binarize:c=!0,pad_size:f=null}={}){const _=[];f=f??this.pad_size;const T=[f.height,f.width];for(let k=0;kd&&(y[M]=1);S=new n.Tensor("bool",y,S.dims)}_.push(S)}return _}generate_crop_boxes(l,u,{crop_n_layers:p=0,overlap_ratio:d=512/1500,points_per_crop:c=32,crop_n_points_downscale_factor:f=1}={}){}}},"./src/models/sam/processing_sam.js":(e,r,t)=>{t.r(r),t.d(r,{SamProcessor:()=>n});var s=t("./src/base/processing_utils.js"),o=t("./src/models/auto/image_processing_auto.js");class n extends s.Processor{async _call(...a){return await this.image_processor(...a)}post_process_masks(...a){return this.image_processor.post_process_masks(...a)}reshape_input_points(...a){return this.image_processor.reshape_input_points(...a)}}te(n,"image_processor_class",o.AutoImageProcessor)},"./src/models/seamless_m4t/feature_extraction_seamless_m4t.js":(e,r,t)=>{t.r(r),t.d(r,{SeamlessM4TFeatureExtractor:()=>i});var s=t("./src/base/feature_extraction_utils.js"),o=t("./src/utils/tensor.js"),n=t("./src/utils/audio.js");class i extends s.FeatureExtractor{constructor(l){super(l);const u=this.config.sampling_rate,p=(0,n.mel_filter_bank)(257,this.config.num_mel_bins,20,Math.floor(u/2),u,null,"kaldi",!0);this.mel_filters=p,this.window=(0,n.window_function)(400,"povey",{periodic:!1})}async _extract_fbank_features(l,u){return l=l.map(p=>p*32768),(0,n.spectrogram)(l,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:u,transpose:!0})}async _call(l,{padding:u=!0,pad_to_multiple_of:p=2,do_normalize_per_mel_bins:d=!0,return_attention_mask:c=!0}={}){(0,s.validate_audio_inputs)(l,"SeamlessM4TFeatureExtractor");let f=await this._extract_fbank_features(l,this.config.max_length);if(d){const[y,M]=f.dims,v=f.data;for(let C=0;C0){const A=new Float32Array(M*(y+C));A.set(v),A.fill(this.config.padding_value,v.length);const B=y+C;f=new o.Tensor(f.type,A,[B,M]),c&&(_=new o.Tensor("int64",new BigInt64Array(B),[1,B]),_.data.fill(1n,0,y))}}const[T,k]=f.dims,w=this.config.stride;if(T%w!==0)throw new Error(`The number of frames (${T}) must be a multiple of the stride (${w}).`);const S=f.view(1,Math.floor(T/w),k*w),E={input_features:S};if(c){const y=S.dims[1],M=new BigInt64Array(y);if(_){const v=_.data;for(let C=1,A=0;C{t.r(r),t.d(r,{SegformerFeatureExtractor:()=>n,SegformerImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{post_process_semantic_segmentation(...a){return(0,s.post_process_semantic_segmentation)(...a)}}class n extends o{}},"./src/models/siglip/image_processing_siglip.js":(e,r,t)=>{t.r(r),t.d(r,{SiglipImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}},"./src/models/smolvlm/image_processing_smolvlm.js":(e,r,t)=>{t.r(r),t.d(r,{SmolVLMImageProcessor:()=>s.Idefics3ImageProcessor});var s=t("./src/models/idefics3/image_processing_idefics3.js")},"./src/models/smolvlm/processing_smolvlm.js":(e,r,t)=>{t.r(r),t.d(r,{SmolVLMProcessor:()=>s.Idefics3Processor});var s=t("./src/models/idefics3/processing_idefics3.js")},"./src/models/snac/feature_extraction_snac.js":(e,r,t)=>{t.r(r),t.d(r,{SnacFeatureExtractor:()=>o});var s=t("./src/models/dac/feature_extraction_dac.js");class o extends s.DacFeatureExtractor{}},"./src/models/speecht5/feature_extraction_speecht5.js":(e,r,t)=>{t.r(r),t.d(r,{SpeechT5FeatureExtractor:()=>o});var s=t("./src/base/feature_extraction_utils.js");class o extends s.FeatureExtractor{}},"./src/models/speecht5/processing_speecht5.js":(e,r,t)=>{t.r(r),t.d(r,{SpeechT5Processor:()=>i});var s=t("./src/base/processing_utils.js"),o=t("./src/tokenizers.js"),n=t("./src/models/auto/feature_extraction_auto.js");class i extends s.Processor{async _call(l){return await this.feature_extractor(l)}}te(i,"tokenizer_class",o.AutoTokenizer),te(i,"feature_extractor_class",n.AutoFeatureExtractor)},"./src/models/swin2sr/image_processing_swin2sr.js":(e,r,t)=>{t.r(r),t.d(r,{Swin2SRImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{pad_image(i,a,l,u={}){const[p,d,c]=a;return super.pad_image(i,a,{width:d+(l-d%l)%l,height:p+(l-p%l)%l},{mode:"symmetric",center:!1,constant_values:-1,...u})}}},"./src/models/ultravox/processing_ultravox.js":(e,r,t)=>{t.r(r),t.d(r,{UltravoxProcessor:()=>i});var s=t("./src/models/auto/feature_extraction_auto.js"),o=t("./src/tokenizers.js"),n=t("./src/base/processing_utils.js");class i extends n.Processor{async _call(l,u=null,p={}){if(Array.isArray(l))throw new Error("Batched inputs are not supported yet.");let d={};if(u){const f=u.length,{input_features:_}=await this.feature_extractor(u,{...p,max_length:f}),T=Math.round(f/this.config.encoder_ds_factor+1e-4),k=1+Math.ceil(T/this.config.stack_factor);d.audio_token_len=[k],d.audio_values=_;const w=this.config.audio_placeholder;if(!l.includes(w))throw new Error(`The input text does not contain the image token ${w}.`);l=l.replaceAll(w,w.repeat(k))}return{...this.tokenizer(l,{add_special_tokens:!1,...p}),...d}}}te(i,"tokenizer_class",o.AutoTokenizer),te(i,"feature_extractor_class",s.AutoFeatureExtractor),te(i,"uses_processor_config",!0)},"./src/models/vit/image_processing_vit.js":(e,r,t)=>{t.r(r),t.d(r,{ViTFeatureExtractor:()=>n,ViTImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}class n extends o{}},"./src/models/vitmatte/image_processing_vitmatte.js":(e,r,t)=>{t.r(r),t.d(r,{VitMatteImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js"),o=t("./src/utils/tensor.js");class n extends s.ImageProcessor{async _call(a,l){Array.isArray(a)||(a=[a]),Array.isArray(l)||(l=[l]);const u=await Promise.all(a.map(c=>this.preprocess(c))),p=await Promise.all(l.map(c=>this.preprocess(c,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:(0,o.stack)(u.map((c,f)=>(0,o.cat)([c.pixel_values,p[f].pixel_values],0)),0),original_sizes:u.map(c=>c.original_size),reshaped_input_sizes:u.map(c=>c.reshaped_input_size)}}}},"./src/models/vitpose/image_processing_vitpose.js":(e,r,t)=>{t.r(r),t.d(r,{VitPoseImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{post_process_pose_estimation(i,a,{threshold:l=null}={}){const u=i.tolist(),[p,d,c,f]=i.dims,_=[];for(let T=0;T{t.r(r),t.d(r,{Wav2Vec2FeatureExtractor:()=>n});var s=t("./src/base/feature_extraction_utils.js"),o=t("./src/utils/tensor.js");class n extends s.FeatureExtractor{_zero_mean_unit_var_norm(a){const u=a.reduce((d,c)=>d+c,0)/a.length,p=a.reduce((d,c)=>d+(c-u)**2,0)/a.length;return a.map(d=>(d-u)/Math.sqrt(p+1e-7))}async _call(a){(0,s.validate_audio_inputs)(a,"Wav2Vec2FeatureExtractor"),a instanceof Float64Array&&(a=new Float32Array(a));let l=a;this.config.do_normalize&&(l=this._zero_mean_unit_var_norm(l));const u=[1,l.length];return{input_values:new o.Tensor("float32",l,u),attention_mask:new o.Tensor("int64",new BigInt64Array(l.length).fill(1n),u)}}}},"./src/models/wav2vec2/processing_wav2vec2.js":(e,r,t)=>{t.r(r),t.d(r,{Wav2Vec2Processor:()=>i});var s=t("./src/tokenizers.js"),o=t("./src/models/auto/feature_extraction_auto.js"),n=t("./src/base/processing_utils.js");class i extends n.Processor{async _call(l){return await this.feature_extractor(l)}}te(i,"tokenizer_class",s.AutoTokenizer),te(i,"feature_extractor_class",o.AutoFeatureExtractor)},"./src/models/wav2vec2_with_lm/processing_wav2vec2_with_lm.js":(e,r,t)=>{t.r(r),t.d(r,{Wav2Vec2ProcessorWithLM:()=>i});var s=t("./src/tokenizers.js"),o=t("./src/models/auto/feature_extraction_auto.js"),n=t("./src/base/processing_utils.js");class i extends n.Processor{async _call(l){return await this.feature_extractor(l)}}te(i,"tokenizer_class",s.AutoTokenizer),te(i,"feature_extractor_class",o.AutoFeatureExtractor)},"./src/models/wespeaker/feature_extraction_wespeaker.js":(e,r,t)=>{t.r(r),t.d(r,{WeSpeakerFeatureExtractor:()=>n});var s=t("./src/base/feature_extraction_utils.js");t("./src/utils/tensor.js");var o=t("./src/utils/audio.js");class n extends s.FeatureExtractor{constructor(a){super(a);const l=this.config.sampling_rate,u=(0,o.mel_filter_bank)(257,this.config.num_mel_bins,20,Math.floor(l/2),l,null,"kaldi",!0);this.mel_filters=u,this.window=(0,o.window_function)(400,"hamming",{periodic:!1}),this.min_num_frames=this.config.min_num_frames}async _extract_fbank_features(a){return a=a.map(l=>l*32768),(0,o.spectrogram)(a,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,transpose:!0,min_num_frames:this.min_num_frames})}async _call(a){(0,s.validate_audio_inputs)(a,"WeSpeakerFeatureExtractor");const l=(await this._extract_fbank_features(a)).unsqueeze_(0);if(this.config.fbank_centering_span===null){const u=l.mean(1).data,p=l.data,[d,c,f]=l.dims;for(let _=0;_{t.r(r),t.d(r,{WHISPER_LANGUAGE_MAPPING:()=>o,WHISPER_TO_LANGUAGE_CODE_MAPPING:()=>n,whisper_language_to_code:()=>i});const s=[["en","english"],["zh","chinese"],["de","german"],["es","spanish"],["ru","russian"],["ko","korean"],["fr","french"],["ja","japanese"],["pt","portuguese"],["tr","turkish"],["pl","polish"],["ca","catalan"],["nl","dutch"],["ar","arabic"],["sv","swedish"],["it","italian"],["id","indonesian"],["hi","hindi"],["fi","finnish"],["vi","vietnamese"],["he","hebrew"],["uk","ukrainian"],["el","greek"],["ms","malay"],["cs","czech"],["ro","romanian"],["da","danish"],["hu","hungarian"],["ta","tamil"],["no","norwegian"],["th","thai"],["ur","urdu"],["hr","croatian"],["bg","bulgarian"],["lt","lithuanian"],["la","latin"],["mi","maori"],["ml","malayalam"],["cy","welsh"],["sk","slovak"],["te","telugu"],["fa","persian"],["lv","latvian"],["bn","bengali"],["sr","serbian"],["az","azerbaijani"],["sl","slovenian"],["kn","kannada"],["et","estonian"],["mk","macedonian"],["br","breton"],["eu","basque"],["is","icelandic"],["hy","armenian"],["ne","nepali"],["mn","mongolian"],["bs","bosnian"],["kk","kazakh"],["sq","albanian"],["sw","swahili"],["gl","galician"],["mr","marathi"],["pa","punjabi"],["si","sinhala"],["km","khmer"],["sn","shona"],["yo","yoruba"],["so","somali"],["af","afrikaans"],["oc","occitan"],["ka","georgian"],["be","belarusian"],["tg","tajik"],["sd","sindhi"],["gu","gujarati"],["am","amharic"],["yi","yiddish"],["lo","lao"],["uz","uzbek"],["fo","faroese"],["ht","haitian creole"],["ps","pashto"],["tk","turkmen"],["nn","nynorsk"],["mt","maltese"],["sa","sanskrit"],["lb","luxembourgish"],["my","myanmar"],["bo","tibetan"],["tl","tagalog"],["mg","malagasy"],["as","assamese"],["tt","tatar"],["haw","hawaiian"],["ln","lingala"],["ha","hausa"],["ba","bashkir"],["jw","javanese"],["su","sundanese"]],o=new Map(s),n=new Map([...s.map(([a,l])=>[l,a]),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);function i(a){a=a.toLowerCase();let l=n.get(a);if(l===void 0){const u=a.match(/^<\|([a-z]{2})\|>$/);if(u&&(a=u[1]),o.has(a))l=a;else{const d=a.length===2?o.keys():o.values();throw new Error(`Language "${a}" is not supported. Must be one of: ${JSON.stringify(Array.from(d))}`)}}return l}},"./src/models/whisper/feature_extraction_whisper.js":(e,r,t)=>{t.r(r),t.d(r,{WhisperFeatureExtractor:()=>i});var s=t("./src/base/feature_extraction_utils.js");t("./src/utils/tensor.js");var o=t("./src/utils/audio.js"),n=t("./src/utils/maths.js");class i extends s.FeatureExtractor{constructor(l){var u;super(l),(u=this.config).mel_filters??(u.mel_filters=(0,o.mel_filter_bank)(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,8e3,this.config.sampling_rate,"slaney","slaney")),this.window=(0,o.window_function)(this.config.n_fft,"hann")}async _extract_fbank_features(l){const u=await(0,o.spectrogram)(l,this.window,this.config.n_fft,this.config.hop_length,{power:2,mel_filters:this.config.mel_filters,log_mel:"log10",max_num_frames:Math.min(Math.floor(l.length/this.config.hop_length),this.config.nb_max_frames)}),p=u.data,d=(0,n.max)(p)[0];for(let c=0;cd?(l.length>this.config.n_samples&&console.warn("Attempting to extract features for audio longer than 30 seconds. If using a pipeline to extract transcript from a long audio clip, remember to specify `chunk_length_s` and/or `stride_length_s`."),p=l.slice(0,d)):(p=new Float32Array(d),p.set(l)),{input_features:(await this._extract_fbank_features(p)).unsqueeze_(0)}}}},"./src/models/whisper/generation_whisper.js":(e,r,t)=>{t.r(r),t.d(r,{WhisperGenerationConfig:()=>o});var s=t("./src/generation/configuration_utils.js");class o extends s.GenerationConfig{constructor(){super(...arguments);te(this,"return_timestamps",null);te(this,"return_token_timestamps",null);te(this,"num_frames",null);te(this,"alignment_heads",null);te(this,"task",null);te(this,"language",null);te(this,"no_timestamps_token_id",null);te(this,"prompt_ids",null);te(this,"is_multilingual",null);te(this,"lang_to_id",null);te(this,"task_to_id",null);te(this,"max_initial_timestamp_index",1)}}},"./src/models/whisper/processing_whisper.js":(e,r,t)=>{t.r(r),t.d(r,{WhisperProcessor:()=>i});var s=t("./src/models/auto/feature_extraction_auto.js"),o=t("./src/tokenizers.js"),n=t("./src/base/processing_utils.js");class i extends n.Processor{async _call(l){return await this.feature_extractor(l)}}te(i,"tokenizer_class",o.AutoTokenizer),te(i,"feature_extractor_class",s.AutoFeatureExtractor)},"./src/models/yolos/image_processing_yolos.js":(e,r,t)=>{t.r(r),t.d(r,{YolosFeatureExtractor:()=>n,YolosImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{post_process_object_detection(...a){return(0,s.post_process_object_detection)(...a)}}class n extends o{}},"./src/ops/registry.js":(e,r,t)=>{t.r(r),t.d(r,{TensorOpRegistry:()=>l});var s=t("./src/backends/onnx.js"),o=t("./src/utils/tensor.js"),n=t("./src/env.js");const i=n.apis.IS_BROWSER_ENV||n.apis.IS_WEBWORKER_ENV,a=async(u,p,d)=>{const c=await(0,s.createInferenceSession)(new Uint8Array(u),p);let f=Promise.resolve();return async _=>{const T=(0,s.isONNXProxy)(),k=Object.fromEntries(Object.entries(_).map(([g,S])=>[g,(T?S.clone():S).ort_tensor])),w=await(f=i?f.then(()=>c.run(k)):c.run(k));return Array.isArray(d)?d.map(g=>new o.Tensor(w[g])):new o.Tensor(w[d])}};class l{static get nearest_interpolate_4d(){return this._nearest_interpolate_4d||(this._nearest_interpolate_4d=a([8,10,18,0,58,129,1,10,41,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,18,10,4,109,111,100,101,34,7,110,101,97,114,101,115,116,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,21],this.session_options,"y")),this._nearest_interpolate_4d}static get bilinear_interpolate_4d(){return this._bilinear_interpolate_4d||(this._bilinear_interpolate_4d=a([8,9,18,0,58,128,1,10,40,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,17,10,4,109,111,100,101,34,6,108,105,110,101,97,114,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bilinear_interpolate_4d}static get bicubic_interpolate_4d(){return this._bicubic_interpolate_4d||(this._bicubic_interpolate_4d=a([8,9,18,0,58,127,10,39,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,16,10,4,109,111,100,101,34,5,99,117,98,105,99,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bicubic_interpolate_4d}static get matmul(){return this._matmul||(this._matmul=a([8,9,18,0,58,55,10,17,10,1,97,10,1,98,18,1,99,34,6,77,97,116,77,117,108,18,1,114,90,9,10,1,97,18,4,10,2,8,1,90,9,10,1,98,18,4,10,2,8,1,98,9,10,1,99,18,4,10,2,8,1,66,2,16,20],this.session_options,"c")),this._matmul}static get stft(){return this._stft||(this._stft=a([8,7,18,0,58,148,1,10,38,10,1,115,10,1,106,10,1,119,10,1,108,18,1,111,34,4,83,84,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,115,90,26,10,1,115,18,21,10,19,8,1,18,15,10,3,18,1,98,10,3,18,1,115,10,3,18,1,99,90,11,10,1,106,18,6,10,4,8,7,18,0,90,16,10,1,119,18,11,10,9,8,1,18,5,10,3,18,1,119,90,11,10,1,108,18,6,10,4,8,7,18,0,98,31,10,1,111,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,102,10,3,18,1,100,10,3,18,1,99,66,2,16,17],this.session_options,"o")),this._stft}static get rfft(){return this._rfft||(this._rfft=a([8,9,18,0,58,97,10,33,10,1,120,10,0,10,1,97,18,1,121,34,3,68,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,100,90,21,10,1,120,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,90,11,10,1,97,18,6,10,4,8,7,18,0,98,21,10,1,121,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,66,2,16,20],this.session_options,"y")),this._rfft}static get top_k(){return this._top_k||(this._top_k=a([8,10,18,0,58,73,10,18,10,1,120,10,1,107,18,1,118,18,1,105,34,4,84,111,112,75,18,1,116,90,9,10,1,120,18,4,10,2,8,1,90,15,10,1,107,18,10,10,8,8,7,18,4,10,2,8,1,98,9,10,1,118,18,4,10,2,8,1,98,9,10,1,105,18,4,10,2,8,7,66,2,16,21],this.session_options,["v","i"])),this._top_k}static get slice(){return this._slice||(this._slice=a([8,7,18,0,58,96,10,25,10,1,120,10,1,115,10,1,101,10,1,97,10,1,116,18,1,121,34,5,83,108,105,99,101,18,1,114,90,9,10,1,120,18,4,10,2,8,1,90,9,10,1,115,18,4,10,2,8,7,90,9,10,1,101,18,4,10,2,8,7,90,9,10,1,97,18,4,10,2,8,7,90,9,10,1,116,18,4,10,2,8,7,98,9,10,1,121,18,4,10,2,8,1,66,2,16,13],this.session_options,"y")),this._slice}}te(l,"session_options",{})},"./src/pipelines.js":(e,r,t)=>{t.r(r),t.d(r,{AudioClassificationPipeline:()=>G,AutomaticSpeechRecognitionPipeline:()=>ee,BackgroundRemovalPipeline:()=>oe,DepthEstimationPipeline:()=>_e,DocumentQuestionAnsweringPipeline:()=>F,FeatureExtractionPipeline:()=>B,FillMaskPipeline:()=>S,ImageClassificationPipeline:()=>Z,ImageFeatureExtractionPipeline:()=>K,ImageSegmentationPipeline:()=>X,ImageToImagePipeline:()=>re,ImageToTextPipeline:()=>H,ObjectDetectionPipeline:()=>ae,Pipeline:()=>T,QuestionAnsweringPipeline:()=>g,SummarizationPipeline:()=>y,Text2TextGenerationPipeline:()=>E,TextClassificationPipeline:()=>k,TextGenerationPipeline:()=>C,TextToAudioPipeline:()=>W,TokenClassificationPipeline:()=>w,TranslationPipeline:()=>M,ZeroShotAudioClassificationPipeline:()=>j,ZeroShotClassificationPipeline:()=>A,ZeroShotImageClassificationPipeline:()=>me,ZeroShotObjectDetectionPipeline:()=>V,pipeline:()=>$e});var s=t("./src/tokenizers.js"),o=t("./src/models.js"),n=t("./src/models/auto/processing_auto.js");t("./src/base/processing_utils.js");var i=t("./src/utils/generic.js"),a=t("./src/utils/core.js"),l=t("./src/utils/maths.js"),u=t("./src/utils/audio.js"),p=t("./src/utils/tensor.js"),d=t("./src/utils/image.js");async function c(we){return Array.isArray(we)||(we=[we]),await Promise.all(we.map(q=>d.RawImage.read(q)))}async function f(we,q){return Array.isArray(we)||(we=[we]),await Promise.all(we.map(R=>typeof R=="string"||R instanceof URL?(0,u.read_audio)(R,q):R instanceof Float64Array?new Float32Array(R):R))}function _(we,q){q&&(we=we.map(Se=>Se|0));const[R,pe,xe,be]=we;return{xmin:R,ymin:pe,xmax:xe,ymax:be}}class T extends i.Callable{constructor({task:q,model:R,tokenizer:pe=null,processor:xe=null}){super(),this.task=q,this.model=R,this.tokenizer=pe,this.processor=xe}async dispose(){await this.model.dispose()}}class k extends T{constructor(q){super(q)}async _call(q,{top_k:R=1}={}){const pe=this.tokenizer(q,{padding:!0,truncation:!0}),xe=await this.model(pe),be=this.model.config.problem_type==="multi_label_classification"?Fe=>Fe.sigmoid():Fe=>new p.Tensor("float32",(0,l.softmax)(Fe.data),Fe.dims),Se=this.model.config.id2label,Ae=[];for(const Fe of xe.logits){const ze=be(Fe),Ve=await(0,p.topk)(ze,R),O=Ve[0].tolist(),z=Ve[1].tolist().map((J,le)=>({label:Se?Se[J]:`LABEL_${J}`,score:O[le]}));R===1?Ae.push(...z):Ae.push(z)}return Array.isArray(q)||R===1?Ae:Ae[0]}}class w extends T{constructor(q){super(q)}async _call(q,{ignore_labels:R=["O"]}={}){const pe=Array.isArray(q),xe=this.tokenizer(pe?q:[q],{padding:!0,truncation:!0}),Se=(await this.model(xe)).logits,Ae=this.model.config.id2label,Fe=[];for(let ze=0;zeIe==this.tokenizer.sep_token_id);Fe[O].map((Ie,Re)=>Ie==1&&(Re===0||Re>z&&ze.findIndex(Xe=>Xe==Y[Re])===-1));const J=be[O].tolist(),le=Se[O].tolist();for(let Ie=1;IeRe==Y[Ie])!==-1)&&(J[Ie]=-1/0,le[Ie]=-1/0);const ye=(0,l.softmax)(J).map((Ie,Re)=>[Ie,Re]),Ee=(0,l.softmax)(le).map((Ie,Re)=>[Ie,Re]);ye[0][0]=0,Ee[0][0]=0;const ke=(0,a.product)(ye,Ee).filter(Ie=>Ie[0][1]<=Ie[1][1]).map(Ie=>[Ie[0][1],Ie[1][1],Ie[0][0]*Ie[1][0]]).sort((Ie,Re)=>Re[2]-Ie[2]);for(let Ie=0;IeJ==this.tokenizer.mask_token_id);if(ze===-1)throw Error(`Mask token (${this.tokenizer.mask_token}) not found in text.`);const Ve=xe[Ae][ze],O=await(0,p.topk)(new p.Tensor("float32",(0,l.softmax)(Ve.data),Ve.dims),R),Y=O[0].tolist(),z=O[1].tolist();be.push(z.map((J,le)=>{const ye=Fe.slice();return ye[ze]=J,{score:Y[le],token:Number(J),token_str:this.tokenizer.decode([J]),sequence:this.tokenizer.decode(ye,{skip_special_tokens:!0})}}))}return Array.isArray(q)?be:be[0]}}class E extends T{constructor(R){super(R);te(this,"_key","generated_text")}async _call(R,pe={}){Array.isArray(R)||(R=[R]),this.model.config.prefix&&(R=R.map(ze=>this.model.config.prefix+ze));const xe=this.model.config.task_specific_params;xe&&xe[this.task]&&xe[this.task].prefix&&(R=R.map(ze=>xe[this.task].prefix+ze));const be=this.tokenizer,Se={padding:!0,truncation:!0};let Ae;this instanceof M&&"_build_translation_inputs"in be?Ae=be._build_translation_inputs(R,Se,pe):Ae=be(R,Se);const Fe=await this.model.generate({...Ae,...pe});return be.batch_decode(Fe,{skip_special_tokens:!0}).map(ze=>({[this._key]:ze}))}}class y extends E{constructor(R){super(R);te(this,"_key","summary_text")}}class M extends E{constructor(R){super(R);te(this,"_key","translation_text")}}function v(we){return Array.isArray(we)&&we.every(q=>"role"in q&&"content"in q)}class C extends T{constructor(q){super(q)}async _call(q,R={}){let pe=!1,xe=!1,be;if(typeof q=="string")be=q=[q];else if(Array.isArray(q)&&q.every(z=>typeof z=="string"))pe=!0,be=q;else{if(v(q))q=[q];else if(Array.isArray(q)&&q.every(v))pe=!0;else throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats");xe=!0,be=q.map(z=>this.tokenizer.apply_chat_template(z,{tokenize:!1,add_generation_prompt:!0}))}const Se=R.add_special_tokens??!1,Ae=xe?!1:R.return_full_text??!0;this.tokenizer.padding_side="left";const Fe=this.tokenizer(be,{add_special_tokens:Se,padding:!0,truncation:!0}),ze=await this.model.generate({...Fe,...R}),Ve=this.tokenizer.batch_decode(ze,{skip_special_tokens:!0});let O;!Ae&&Fe.input_ids.dims.at(-1)>0&&(O=this.tokenizer.batch_decode(Fe.input_ids,{skip_special_tokens:!0}).map(z=>z.length));const Y=Array.from({length:q.length},z=>[]);for(let z=0;z[R.toLowerCase(),pe])),this.entailment_id=this.label2id.entailment,this.entailment_id===void 0&&(console.warn("Could not find 'entailment' in label2id mapping. Using 2 as entailment_id."),this.entailment_id=2),this.contradiction_id=this.label2id.contradiction??this.label2id.not_entailment,this.contradiction_id===void 0&&(console.warn("Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id."),this.contradiction_id=0)}async _call(q,R,{hypothesis_template:pe="This example is {}.",multi_label:xe=!1}={}){const be=Array.isArray(q);be||(q=[q]),Array.isArray(R)||(R=[R]);const Se=R.map(ze=>pe.replace("{}",ze)),Ae=xe||R.length===1,Fe=[];for(const ze of q){const Ve=[];for(const z of Se){const J=this.tokenizer(ze,{text_pair:z,padding:!0,truncation:!0}),le=await this.model(J);Ae?Ve.push([le.logits.data[this.contradiction_id],le.logits.data[this.entailment_id]]):Ve.push(le.logits.data[this.entailment_id])}const Y=(Ae?Ve.map(z=>(0,l.softmax)(z)[1]):(0,l.softmax)(Ve)).map((z,J)=>[z,J]).sort((z,J)=>J[0]-z[0]);Fe.push({sequence:ze,labels:Y.map(z=>R[z[1]]),scores:Y.map(z=>z[0])})}return be?Fe:Fe[0]}}class B extends T{constructor(q){super(q)}async _call(q,{pooling:R="none",normalize:pe=!1,quantize:xe=!1,precision:be="binary"}={}){const Se=this.tokenizer(q,{padding:!0,truncation:!0}),Ae=await this.model(Se);let Fe=Ae.last_hidden_state??Ae.logits??Ae.token_embeddings;if(R!=="none")if(R==="mean")Fe=(0,p.mean_pooling)(Fe,Se.attention_mask);else if(R==="cls")Fe=Fe.slice(null,0);else throw Error(`Pooling method '${R}' not supported.`);return pe&&(Fe=Fe.normalize(2,-1)),xe&&(Fe=(0,p.quantize_embeddings)(Fe,be)),Fe}}class K extends T{constructor(q){super(q)}async _call(q,{pool:R=null}={}){const pe=await c(q),{pixel_values:xe}=await this.processor(pe),be=await this.model({pixel_values:xe});let Se;if(R){if(!("pooler_output"in be))throw Error("No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.");Se=be.pooler_output}else Se=be.last_hidden_state??be.logits??be.image_embeds;return Se}}class G extends T{constructor(q){super(q)}async _call(q,{top_k:R=5}={}){const pe=this.processor.feature_extractor.config.sampling_rate,xe=await f(q,pe),be=this.model.config.id2label,Se=[];for(const Ae of xe){const Fe=await this.processor(Ae),Ve=(await this.model(Fe)).logits[0],O=await(0,p.topk)(new p.Tensor("float32",(0,l.softmax)(Ve.data),Ve.dims),R),Y=O[0].tolist(),J=O[1].tolist().map((le,ye)=>({label:be?be[le]:`LABEL_${le}`,score:Y[ye]}));Se.push(J)}return Array.isArray(q)?Se:Se[0]}}class j extends T{constructor(q){super(q)}async _call(q,R,{hypothesis_template:pe="This is a sound of {}."}={}){const xe=!Array.isArray(q);xe&&(q=[q]);const be=R.map(Ve=>pe.replace("{}",Ve)),Se=this.tokenizer(be,{padding:!0,truncation:!0}),Ae=this.processor.feature_extractor.config.sampling_rate,Fe=await f(q,Ae),ze=[];for(const Ve of Fe){const O=await this.processor(Ve),Y=await this.model({...Se,...O}),z=(0,l.softmax)(Y.logits_per_audio.data);ze.push([...z].map((J,le)=>({score:J,label:R[le]})))}return xe?ze[0]:ze}}class ee extends T{constructor(q){super(q)}async _call(q,R={}){switch(this.model.config.model_type){case"whisper":case"lite-whisper":return this._call_whisper(q,R);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":return this._call_wav2vec2(q,R);case"moonshine":return this._call_moonshine(q,R);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(q,R){R.language&&console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),R.task&&console.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');const pe=!Array.isArray(q);pe&&(q=[q]);const xe=this.processor.feature_extractor.config.sampling_rate,be=await f(q,xe),Se=[];for(const Ae of be){const Fe=await this.processor(Ae),Ve=(await this.model(Fe)).logits[0],O=[];for(const z of Ve)O.push((0,l.max)(z.data)[1]);const Y=this.tokenizer.decode(O);Se.push({text:Y})}return pe?Se[0]:Se}async _call_whisper(q,R){const pe=R.return_timestamps??!1,xe=R.chunk_length_s??0,be=R.force_full_sequences??!1;let Se=R.stride_length_s??null;const Ae={...R};pe==="word"&&(Ae.return_token_timestamps=!0,Ae.return_timestamps=!1);const Fe=!Array.isArray(q);Fe&&(q=[q]);const ze=this.processor.feature_extractor.config.chunk_length/this.model.config.max_source_positions,Ve=this.processor.feature_extractor.config.hop_length,O=this.processor.feature_extractor.config.sampling_rate,Y=await f(q,O),z=[];for(const J of Y){let le=[];if(xe>0){if(Se===null)Se=xe/6;else if(xe<=Se)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");const ke=O*xe,Ie=O*Se,Re=ke-2*Ie;let Xe=0;for(;;){const Ge=Xe+ke,lt=J.subarray(Xe,Ge),wt=await this.processor(lt),Gt=Xe===0,Ot=Ge>=J.length;if(le.push({stride:[lt.length,Gt?0:Ie,Ot?0:Ie],input_features:wt.input_features,is_last:Ot}),Ot)break;Xe+=Re}}else le=[{stride:[J.length,0,0],input_features:(await this.processor(J)).input_features,is_last:!0}];for(const ke of le){Ae.num_frames=Math.floor(ke.stride[0]/Ve);const Ie=await this.model.generate({inputs:ke.input_features,...Ae});pe==="word"?(ke.tokens=Ie.sequences.tolist()[0],ke.token_timestamps=Ie.token_timestamps.tolist()[0].map(Re=>(0,l.round)(Re,2))):ke.tokens=Ie[0].tolist(),ke.stride=ke.stride.map(Re=>Re/O)}const[ye,Ee]=this.tokenizer._decode_asr(le,{time_precision:ze,return_timestamps:pe,force_full_sequences:be});z.push({text:ye,...Ee})}return Fe?z[0]:z}async _call_moonshine(q,R){const pe=!Array.isArray(q);pe&&(q=[q]);const xe=this.processor.feature_extractor.config.sampling_rate,be=await f(q,xe),Se=[];for(const Ae of be){const Fe=await this.processor(Ae),ze=Math.floor(Ae.length/xe)*6,Ve=await this.model.generate({max_new_tokens:ze,...R,...Fe}),O=this.processor.batch_decode(Ve,{skip_special_tokens:!0})[0];Se.push({text:O})}return pe?Se[0]:Se}}class H extends T{constructor(q){super(q)}async _call(q,R={}){const pe=Array.isArray(q),xe=await c(q),{pixel_values:be}=await this.processor(xe),Se=[];for(const Ae of be){Ae.dims=[1,...Ae.dims];const Fe=await this.model.generate({inputs:Ae,...R}),ze=this.tokenizer.batch_decode(Fe,{skip_special_tokens:!0}).map(Ve=>({generated_text:Ve.trim()}));Se.push(ze)}return pe?Se:Se[0]}}class Z extends T{constructor(q){super(q)}async _call(q,{top_k:R=5}={}){const pe=await c(q),{pixel_values:xe}=await this.processor(pe),be=await this.model({pixel_values:xe}),Se=this.model.config.id2label,Ae=[];for(const Fe of be.logits){const ze=await(0,p.topk)(new p.Tensor("float32",(0,l.softmax)(Fe.data),Fe.dims),R),Ve=ze[0].tolist(),Y=ze[1].tolist().map((z,J)=>({label:Se?Se[z]:`LABEL_${z}`,score:Ve[J]}));Ae.push(Y)}return Array.isArray(q)?Ae:Ae[0]}}class X extends T{constructor(q){super(q),this.subtasks_mapping={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"}}async _call(q,{threshold:R=.5,mask_threshold:pe=.5,overlap_mask_area_threshold:xe=.8,label_ids_to_fuse:be=null,target_sizes:Se=null,subtask:Ae=null}={}){if(Array.isArray(q)&&q.length!==1)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");const ze=await c(q),Ve=ze.map(ke=>[ke.height,ke.width]),O=await this.processor(ze),{inputNames:Y,outputNames:z}=this.model.sessions.model;if(!Y.includes("pixel_values")){if(Y.length!==1)throw Error(`Expected a single input name, but got ${Y.length} inputs: ${Y}.`);const ke=Y[0];if(ke in O)throw Error(`Input name ${ke} already exists in the inputs.`);O[ke]=O.pixel_values}const J=await this.model(O);let le=null;if(Ae!==null)le=this.subtasks_mapping[Ae];else if(this.processor.image_processor){for(const[ke,Ie]of Object.entries(this.subtasks_mapping))if(Ie in this.processor.image_processor){le=this.processor.image_processor[Ie].bind(this.processor.image_processor),Ae=ke;break}}const ye=this.model.config.id2label,Ee=[];if(Ae)if(Ae==="panoptic"||Ae==="instance"){const ke=le(J,R,pe,xe,be,Se??Ve)[0],Ie=ke.segmentation;for(const Re of ke.segments_info){const Xe=new Uint8ClampedArray(Ie.data.length);for(let lt=0;ltwt<-1e-5||wt>1+1e-5)&&Ge.sigmoid_();const lt=await d.RawImage.fromTensor(Ge.mul_(255).to("uint8")).resize(Xe[1],Xe[0]);Ee.push({label:null,score:null,mask:lt})}}return Ee}}class oe extends X{constructor(q){super(q)}async _call(q,R={}){if(Array.isArray(q)&&q.length!==1)throw Error("Background removal pipeline currently only supports a batch size of 1.");const xe=await c(q),be=await super._call(q,R);return xe.map((Ae,Fe)=>{const ze=Ae.clone();return ze.putAlpha(be[Fe].mask),ze})}}class me extends T{constructor(q){super(q)}async _call(q,R,{hypothesis_template:pe="This is a photo of {}"}={}){const xe=Array.isArray(q),be=await c(q),Se=R.map(Y=>pe.replace("{}",Y)),Ae=this.tokenizer(Se,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:Fe}=await this.processor(be),ze=await this.model({...Ae,pixel_values:Fe}),Ve=this.model.config.model_type==="siglip"?Y=>Y.sigmoid().data:Y=>(0,l.softmax)(Y.data),O=[];for(const Y of ze.logits_per_image){const J=[...Ve(Y)].map((le,ye)=>({score:le,label:R[ye]}));J.sort((le,ye)=>ye.score-le.score),O.push(J)}return xe?O:O[0]}}class ae extends T{constructor(q){super(q)}async _call(q,{threshold:R=.9,percentage:pe=!1}={}){const xe=Array.isArray(q);if(xe&&q.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");const be=await c(q),Se=pe?null:be.map(z=>[z.height,z.width]),{pixel_values:Ae,pixel_mask:Fe}=await this.processor(be),ze=await this.model({pixel_values:Ae,pixel_mask:Fe}),Ve=this.processor.image_processor.post_process_object_detection(ze,R,Se),O=this.model.config.id2label,Y=Ve.map(z=>z.boxes.map((J,le)=>({score:z.scores[le],label:O[z.classes[le]],box:_(J,!pe)})));return xe?Y:Y[0]}}class V extends T{constructor(q){super(q)}async _call(q,R,{threshold:pe=.1,top_k:xe=null,percentage:be=!1}={}){const Se=Array.isArray(q),Ae=await c(q),Fe=this.tokenizer(R,{padding:!0,truncation:!0}),ze=await this.processor(Ae),Ve=[];for(let O=0;O({score:Ee.scores[Ie],label:Ee.labels[Ie],box:_(ke,!be)}))}else{const Ee=this.processor.image_processor.post_process_object_detection(le,pe,z,!0)[0];ye=Ee.boxes.map((ke,Ie)=>({score:Ee.scores[Ie],label:R[Ee.classes[Ie]],box:_(ke,!be)}))}ye.sort((Ee,ke)=>ke.score-Ee.score),xe!==null&&(ye=ye.slice(0,xe)),Ve.push(ye)}return Se?Ve:Ve[0]}}class F extends T{constructor(q){super(q)}async _call(q,R,pe={}){const xe=(await c(q))[0],{pixel_values:be}=await this.processor(xe),Se=`${R}`,Ae=this.tokenizer(Se,{add_special_tokens:!1,padding:!0,truncation:!0}).input_ids,Fe=await this.model.generate({inputs:be,max_length:this.model.config.decoder.max_position_embeddings,decoder_input_ids:Ae,...pe}),Ve=this.tokenizer.batch_decode(Fe)[0].match(/(.*?)<\/s_answer>/);let O=null;return Ve&&Ve.length>=2&&(O=Ve[1].trim()),[{answer:O}]}}class W extends T{constructor(R){super(R);te(this,"DEFAULT_VOCODER_ID","Xenova/speecht5_hifigan");this.vocoder=R.vocoder??null}async _call(R,{speaker_embeddings:pe=null}={}){return this.processor?this._call_text_to_spectrogram(R,{speaker_embeddings:pe}):this._call_text_to_waveform(R)}async _call_text_to_waveform(R){const pe=this.tokenizer(R,{padding:!0,truncation:!0}),{waveform:xe}=await this.model(pe),be=this.model.config.sampling_rate;return new u.RawAudio(xe.data,be)}async _call_text_to_spectrogram(R,{speaker_embeddings:pe}){if(this.vocoder||(console.log("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await o.AutoModel.from_pretrained(this.DEFAULT_VOCODER_ID,{dtype:"fp32"})),(typeof pe=="string"||pe instanceof URL)&&(pe=new Float32Array(await(await fetch(pe)).arrayBuffer())),pe instanceof Float32Array)pe=new p.Tensor("float32",pe,[1,pe.length]);else if(!(pe instanceof p.Tensor))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");const{input_ids:xe}=this.tokenizer(R,{padding:!0,truncation:!0}),{waveform:be}=await this.model.generate_speech(xe,pe,{vocoder:this.vocoder}),Se=this.processor.feature_extractor.config.sampling_rate;return new u.RawAudio(be.data,Se)}}class re extends T{constructor(q){super(q)}async _call(q){const R=await c(q),pe=await this.processor(R),xe=await this.model(pe),be=[];for(const Se of xe.reconstruction){const Ae=Se.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");be.push(d.RawImage.fromTensor(Ae))}return be.length>1?be:be[0]}}class _e extends T{constructor(q){super(q)}async _call(q){const R=await c(q),pe=await this.processor(R),{predicted_depth:xe}=await this.model(pe),be=[];for(let Se=0;Se1?be:be[0]}}const se=Object.freeze({"text-classification":{tokenizer:s.AutoTokenizer,pipeline:k,model:o.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{tokenizer:s.AutoTokenizer,pipeline:w,model:o.AutoModelForTokenClassification,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{tokenizer:s.AutoTokenizer,pipeline:g,model:o.AutoModelForQuestionAnswering,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{tokenizer:s.AutoTokenizer,pipeline:S,model:o.AutoModelForMaskedLM,default:{model:"Xenova/bert-base-uncased"},type:"text"},summarization:{tokenizer:s.AutoTokenizer,pipeline:y,model:o.AutoModelForSeq2SeqLM,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{tokenizer:s.AutoTokenizer,pipeline:M,model:o.AutoModelForSeq2SeqLM,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{tokenizer:s.AutoTokenizer,pipeline:E,model:o.AutoModelForSeq2SeqLM,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{tokenizer:s.AutoTokenizer,pipeline:C,model:o.AutoModelForCausalLM,default:{model:"Xenova/gpt2"},type:"text"},"zero-shot-classification":{tokenizer:s.AutoTokenizer,pipeline:A,model:o.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:G,model:o.AutoModelForAudioClassification,processor:n.AutoProcessor,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{tokenizer:s.AutoTokenizer,pipeline:j,model:o.AutoModel,processor:n.AutoProcessor,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{tokenizer:s.AutoTokenizer,pipeline:ee,model:[o.AutoModelForSpeechSeq2Seq,o.AutoModelForCTC],processor:n.AutoProcessor,default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{tokenizer:s.AutoTokenizer,pipeline:W,model:[o.AutoModelForTextToWaveform,o.AutoModelForTextToSpectrogram],processor:[n.AutoProcessor,null],default:{model:"Xenova/speecht5_tts"},type:"text"},"image-to-text":{tokenizer:s.AutoTokenizer,pipeline:H,model:o.AutoModelForVision2Seq,processor:n.AutoProcessor,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:Z,model:o.AutoModelForImageClassification,processor:n.AutoProcessor,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:X,model:[o.AutoModelForImageSegmentation,o.AutoModelForSemanticSegmentation,o.AutoModelForUniversalSegmentation],processor:n.AutoProcessor,default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"background-removal":{pipeline:oe,model:[o.AutoModelForImageSegmentation,o.AutoModelForSemanticSegmentation,o.AutoModelForUniversalSegmentation],processor:n.AutoProcessor,default:{model:"Xenova/modnet"},type:"image"},"zero-shot-image-classification":{tokenizer:s.AutoTokenizer,pipeline:me,model:o.AutoModel,processor:n.AutoProcessor,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:ae,model:o.AutoModelForObjectDetection,processor:n.AutoProcessor,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{tokenizer:s.AutoTokenizer,pipeline:V,model:o.AutoModelForZeroShotObjectDetection,processor:n.AutoProcessor,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{tokenizer:s.AutoTokenizer,pipeline:F,model:o.AutoModelForDocumentQuestionAnswering,processor:n.AutoProcessor,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:re,model:o.AutoModelForImageToImage,processor:n.AutoProcessor,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:_e,model:o.AutoModelForDepthEstimation,processor:n.AutoProcessor,default:{model:"Xenova/dpt-large"},type:"image"},"feature-extraction":{tokenizer:s.AutoTokenizer,pipeline:B,model:o.AutoModel,default:{model:"Xenova/all-MiniLM-L6-v2"},type:"text"},"image-feature-extraction":{processor:n.AutoProcessor,pipeline:K,model:[o.AutoModelForImageFeatureExtraction,o.AutoModel],default:{model:"Xenova/vit-base-patch16-224-in21k"},type:"image"}}),ce=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});async function $e(we,q=null,{progress_callback:R=null,config:pe=null,cache_dir:xe=null,local_files_only:be=!1,revision:Se="main",device:Ae=null,dtype:Fe=null,subfolder:ze="onnx",use_external_data_format:Ve=null,model_file_name:O=null,session_options:Y={}}={}){we=ce[we]??we;const z=se[we.split("_",1)[0]];if(!z)throw Error(`Unsupported pipeline: ${we}. Must be one of [${Object.keys(se)}]`);q||(q=z.default.model,console.log(`No model specified. Using default model: "${q}".`));const J={progress_callback:R,config:pe,cache_dir:xe,local_files_only:be,revision:Se,device:Ae,dtype:Fe,subfolder:ze,use_external_data_format:Ve,model_file_name:O,session_options:Y},le=new Map([["tokenizer",z.tokenizer],["model",z.model],["processor",z.processor]]),ye=await Ue(le,q,J);ye.task=we,(0,a.dispatchCallback)(R,{status:"ready",task:we,model:q});const Ee=z.pipeline;return new Ee(ye)}async function Ue(we,q,R){const pe=Object.create(null),xe=[];for(const[be,Se]of we.entries()){if(!Se)continue;let Ae;Array.isArray(Se)?Ae=new Promise(async(Fe,ze)=>{var O,Y;let Ve;for(const z of Se){if(z===null){Fe(null);return}try{Fe(await z.from_pretrained(q,R));return}catch(J){if((O=J.message)!=null&&O.includes("Unsupported model type"))Ve=J;else if((Y=J.message)!=null&&Y.includes("Could not locate file"))Ve=J;else{ze(J);return}}}ze(Ve)}):Ae=Se.from_pretrained(q,R),pe[be]=Ae,xe.push(Ae)}await Promise.all(xe);for(const[be,Se]of Object.entries(pe))pe[be]=await Se;return pe}},"./src/tokenizers.js":(e,r,t)=>{t.r(r),t.d(r,{AlbertTokenizer:()=>Ar,AutoTokenizer:()=>vn,BartTokenizer:()=>hs,BertTokenizer:()=>us,BlenderbotSmallTokenizer:()=>vs,BlenderbotTokenizer:()=>wn,BloomTokenizer:()=>Hr,CLIPTokenizer:()=>mn,CamembertTokenizer:()=>tt,CodeGenTokenizer:()=>Br,CodeLlamaTokenizer:()=>xr,CohereTokenizer:()=>yn,ConvBertTokenizer:()=>Qt,DebertaTokenizer:()=>ds,DebertaV2Tokenizer:()=>cs,DistilBertTokenizer:()=>Qe,ElectraTokenizer:()=>zr,EsmTokenizer:()=>pn,FalconTokenizer:()=>fr,GPT2Tokenizer:()=>ps,GPTNeoXTokenizer:()=>Vs,GemmaTokenizer:()=>hn,Grok1Tokenizer:()=>qr,HerbertTokenizer:()=>ys,LlamaTokenizer:()=>cn,M2M100Tokenizer:()=>dr,MBart50Tokenizer:()=>ms,MBartTokenizer:()=>Kr,MPNetTokenizer:()=>ks,MarianTokenizer:()=>fn,MgpstrTokenizer:()=>xs,MobileBertTokenizer:()=>bs,NllbTokenizer:()=>Is,NougatTokenizer:()=>Us,PreTrainedTokenizer:()=>at,Qwen2Tokenizer:()=>Fr,RoFormerTokenizer:()=>De,RobertaTokenizer:()=>_s,SiglipTokenizer:()=>_n,SpeechT5Tokenizer:()=>Mn,SqueezeBertTokenizer:()=>Ft,T5Tokenizer:()=>Sr,TokenizerModel:()=>K,VitsTokenizer:()=>bn,Wav2Vec2CTCTokenizer:()=>gn,WhisperTokenizer:()=>gr,XLMRobertaTokenizer:()=>$s,XLMTokenizer:()=>Rt,is_chinese_char:()=>S});var s=t("./src/utils/generic.js"),o=t("./src/utils/core.js"),n=t("./src/utils/hub.js"),i=t("./src/utils/maths.js"),a=t("./src/utils/tensor.js"),l=t("./src/utils/data-structures.js"),u=t("./node_modules/@huggingface/jinja/dist/index.js"),p=t("./src/models/whisper/common_whisper.js");async function d(he,$){const N=await Promise.all([(0,n.getModelJSON)(he,"tokenizer.json",!0,$),(0,n.getModelJSON)(he,"tokenizer_config.json",!0,$)]);return $.legacy!==null&&(N[1].legacy=$.legacy),N}function c(he,$){const N=[];let Q=0;for(const ie of he.matchAll($)){const de=ie[0];Q0&&N.push(de),Q=ie.index+de.length}return Q=19968&&he<=40959||he>=13312&&he<=19903||he>=131072&&he<=173791||he>=173824&&he<=177983||he>=177984&&he<=178207||he>=178208&&he<=183983||he>=63744&&he<=64255||he>=194560&&he<=195103}function E(he,$,N){const Q=[];let ie=0;for(;iethis.tokens_to_ids.get(N)??this.unk_token_id)}convert_ids_to_tokens($){return $.map(N=>this.vocab[N]??this.unk_token)}}class G extends K{constructor($){super($),this.tokens_to_ids=_($.vocab),this.unk_token_id=this.tokens_to_ids.get($.unk_token),this.unk_token=$.unk_token,this.max_input_chars_per_word=$.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(const[N,Q]of this.tokens_to_ids)this.vocab[Q]=N}encode($){const N=[];for(const Q of $){const ie=[...Q];if(ie.length>this.max_input_chars_per_word){N.push(this.unk_token);continue}let de=!1,ve=0;const je=[];for(;ve0&&(Je=this.config.continuing_subword_prefix+Je),this.tokens_to_ids.has(Je)){We=Je;break}--He}if(We===null){de=!0;break}je.push(We),ve=He}de?N.push(this.unk_token):N.push(...je)}return N}}class j extends K{constructor($,N){super($);const Q=$.vocab.length;this.vocab=new Array(Q),this.scores=new Array(Q);for(let ie=0;ie[ie,de])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=N.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.unk_token=this.vocab[this.unk_token_id],this.minScore=(0,i.min)(this.scores)[0],this.unk_score=this.minScore-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new l.CharTrie,this.trie.extend(this.vocab),this.fuse_unk=!0}populateNodes($){const N=$.chars,Q=1;let ie=0;for(;ie{const he=[...Array.from({length:94},(ie,de)=>de+33),...Array.from({length:12},(ie,de)=>de+161),...Array.from({length:82},(ie,de)=>de+174)],$=he.slice();let N=0;for(let ie=0;ie<256;++ie)he.includes(ie)||(he.push(ie),$.push(256+N),N+=1);const Q=$.map(ie=>String.fromCharCode(ie));return Object.fromEntries(he.map((ie,de)=>[ie,Q[de]]))})(),H=(0,o.reverseDictionary)(ee);class Z extends K{constructor($){super($),this.tokens_to_ids=_($.vocab),this.unk_token_id=this.tokens_to_ids.get($.unk_token),this.unk_token=$.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(const[Q,ie]of this.tokens_to_ids)this.vocab[ie]=Q;const N=Array.isArray($.merges[0]);this.merges=N?$.merges:$.merges.map(Q=>Q.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((Q,ie)=>[JSON.stringify(Q),ie])),this.end_of_word_suffix=$.end_of_word_suffix,this.continuing_subword_suffix=$.continuing_subword_suffix??null,this.byte_fallback=this.config.byte_fallback??!1,this.byte_fallback&&(this.text_encoder=new TextEncoder),this.ignore_merges=this.config.ignore_merges??!1,this.max_length_to_cache=256,this.cache_capacity=1e4,this.cache=new l.LRUCache(this.cache_capacity)}clear_cache(){this.cache.clear()}bpe($){if($.length===0)return[];const N=this.cache.get($);if(N!==void 0)return N;const Q=Array.from($);this.end_of_word_suffix&&(Q[Q.length-1]+=this.end_of_word_suffix);let ie=[];if(Q.length>1){const de=new l.PriorityQueue((He,We)=>He.score`<0x${je.toString(16).toUpperCase().padStart(2,"0")}>`);ve.every(je=>this.tokens_to_ids.has(je))?N.push(...ve):N.push(this.unk_token)}else N.push(this.unk_token)}return N}}class X extends K{constructor($,N){super($),this.tokens_to_ids=_(N.target_lang?$.vocab[N.target_lang]:$.vocab),this.bos_token=N.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=N.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=N.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=N.unk_token,this.unk_token_id=this.tokens_to_ids.get(this.unk_token),this.vocab=new Array(this.tokens_to_ids.size);for(const[Q,ie]of this.tokens_to_ids)this.vocab[ie]=Q}encode($){return $}}class oe extends s.Callable{constructor($){super(),this.config=$}static fromConfig($){if($===null)return null;switch($.type){case"BertNormalizer":return new we($);case"Precompiled":return new Ot($);case"Sequence":return new Ue($);case"Replace":return new me($);case"NFC":return new V($);case"NFD":return new F($);case"NFKC":return new W($);case"NFKD":return new re($);case"Strip":return new _e($);case"StripAccents":return new se($);case"Lowercase":return new ce($);case"Prepend":return new $e($);default:throw new Error(`Unknown Normalizer type: ${$.type}`)}}normalize($){throw Error("normalize should be implemented in subclass.")}_call($){return this.normalize($)}}class me extends oe{normalize($){const N=f(this.config.pattern);return N===null?$:$.replaceAll(N,this.config.content)}}class ae extends oe{constructor(){super(...arguments);te(this,"form")}normalize(N){return N=N.normalize(this.form),N}}class V extends ae{constructor(){super(...arguments);te(this,"form","NFC")}}class F extends ae{constructor(){super(...arguments);te(this,"form","NFD")}}class W extends ae{constructor(){super(...arguments);te(this,"form","NFKC")}}class re extends ae{constructor(){super(...arguments);te(this,"form","NFKD")}}class _e extends oe{normalize($){return this.config.strip_left&&this.config.strip_right?$=$.trim():(this.config.strip_left&&($=$.trimStart()),this.config.strip_right&&($=$.trimEnd())),$}}class se extends oe{normalize($){return $=w($),$}}class ce extends oe{normalize($){return $=$.toLowerCase(),$}}class $e extends oe{normalize($){return $=this.config.prepend+$,$}}class Ue extends oe{constructor($){super($),this.normalizers=$.normalizers.map(N=>oe.fromConfig(N))}normalize($){return this.normalizers.reduce((N,Q)=>Q.normalize(N),$)}}class we extends oe{_tokenize_chinese_chars($){const N=[];for(let Q=0;Q<$.length;++Q){const ie=$[Q],de=ie.charCodeAt(0);S(de)?(N.push(" "),N.push(ie),N.push(" ")):N.push(ie)}return N.join("")}stripAccents($){return $.normalize("NFD").replace(new RegExp("\\p{Mn}","gu"),"")}_is_control($){switch($){case" ":case` +`:case"\r":return!1;default:return new RegExp("^\\p{Cc}|\\p{Cf}|\\p{Co}|\\p{Cs}$","u").test($)}}_clean_text($){const N=[];for(const Q of $){const ie=Q.charCodeAt(0);ie===0||ie===65533||this._is_control(Q)||(/^\s$/.test(Q)?N.push(" "):N.push(Q))}return N.join("")}normalize($){return this.config.clean_text&&($=this._clean_text($)),this.config.handle_chinese_chars&&($=this._tokenize_chinese_chars($)),this.config.lowercase?($=$.toLowerCase(),this.config.strip_accents!==!1&&($=this.stripAccents($))):this.config.strip_accents&&($=this.stripAccents($)),$}}class q extends s.Callable{static fromConfig($){if($===null)return null;switch($.type){case"BertPreTokenizer":return new R($);case"Sequence":return new ur($);case"Whitespace":return new ls($);case"WhitespaceSplit":return new Ms($);case"Metaspace":return new wt($);case"ByteLevel":return new pe($);case"Split":return new xe($);case"Punctuation":return new be($);case"Digits":return new Se($);case"Replace":return new Ir($);default:throw new Error(`Unknown PreTokenizer type: ${$.type}`)}}pre_tokenize_text($,N){throw Error("pre_tokenize_text should be implemented in subclass.")}pre_tokenize($,N){return(Array.isArray($)?$.map(Q=>this.pre_tokenize_text(Q,N)):this.pre_tokenize_text($,N)).flat()}_call($,N){return this.pre_tokenize($,N)}}class R extends q{constructor($){super(),this.pattern=new RegExp(`[^\\s${M}]+|[${M}]`,"gu")}pre_tokenize_text($,N){return $.trim().match(this.pattern)||[]}}class pe extends q{constructor($){super(),this.config=$,this.add_prefix_space=this.config.add_prefix_space,this.trim_offsets=this.config.trim_offsets,this.use_regex=this.config.use_regex??!0,this.pattern=new RegExp("'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)|\\s+","gu"),this.byte_encoder=ee,this.text_encoder=new TextEncoder}pre_tokenize_text($,N){return this.add_prefix_space&&!$.startsWith(" ")&&($=" "+$),(this.use_regex?$.match(this.pattern)||[]:[$]).map(ie=>Array.from(this.text_encoder.encode(ie),de=>this.byte_encoder[de]).join(""))}}class xe extends q{constructor($){super(),this.config=$,this.pattern=f(this.config.pattern,this.config.invert)}pre_tokenize_text($,N){var Q;return this.pattern===null?[]:this.config.invert?$.match(this.pattern)||[]:((Q=this.config.behavior)==null?void 0:Q.toLowerCase())==="removed"?$.split(this.pattern).filter(ie=>ie):c($,this.pattern)}}class be extends q{constructor($){super(),this.config=$,this.pattern=new RegExp(`[^${M}]+|[${M}]+`,"gu")}pre_tokenize_text($,N){return $.match(this.pattern)||[]}}class Se extends q{constructor($){super(),this.config=$;const N=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(N,"gu")}pre_tokenize_text($,N){return $.match(this.pattern)||[]}}class Ae extends s.Callable{constructor($){super(),this.config=$}static fromConfig($){if($===null)return null;switch($.type){case"TemplateProcessing":return new Ve($);case"ByteLevel":return new O($);case"RobertaProcessing":return new ze($);case"BertProcessing":return new Fe($);case"Sequence":return new Y($);default:throw new Error(`Unknown PostProcessor type: ${$.type}`)}}post_process($,...N){throw Error("post_process should be implemented in subclass.")}_call($,...N){return this.post_process($,...N)}}class Fe extends Ae{constructor($){super($),this.cls=$.cls[0],this.sep=$.sep[0]}post_process($,N=null,{add_special_tokens:Q=!0}={}){Q&&($=(0,o.mergeArrays)([this.cls],$,[this.sep]));let ie=new Array($.length).fill(0);if(N!==null){const de=Q&&this instanceof ze?[this.sep]:[],ve=Q?[this.sep]:[];$=(0,o.mergeArrays)($,de,N,ve),ie=(0,o.mergeArrays)(ie,new Array(N.length+de.length+ve.length).fill(1))}return{tokens:$,token_type_ids:ie}}}class ze extends Fe{}class Ve extends Ae{constructor($){super($),this.single=$.single,this.pair=$.pair}post_process($,N=null,{add_special_tokens:Q=!0}={}){const ie=N===null?this.single:this.pair;let de=[],ve=[];for(const je of ie)"SpecialToken"in je?Q&&(de.push(je.SpecialToken.id),ve.push(je.SpecialToken.type_id)):"Sequence"in je&&(je.Sequence.id==="A"?(de=(0,o.mergeArrays)(de,$),ve=(0,o.mergeArrays)(ve,new Array($.length).fill(je.Sequence.type_id))):je.Sequence.id==="B"&&(de=(0,o.mergeArrays)(de,N),ve=(0,o.mergeArrays)(ve,new Array(N.length).fill(je.Sequence.type_id))));return{tokens:de,token_type_ids:ve}}}class O extends Ae{post_process($,N=null){return N&&($=(0,o.mergeArrays)($,N)),{tokens:$}}}class Y extends Ae{constructor($){super($),this.processors=$.processors.map(N=>Ae.fromConfig(N))}post_process($,N=null,Q={}){let ie;for(const de of this.processors)if(de instanceof O)$=de.post_process($).tokens,N&&(N=de.post_process(N).tokens);else{const ve=de.post_process($,N,Q);$=ve.tokens,ie=ve.token_type_ids}return{tokens:$,token_type_ids:ie}}}class z extends s.Callable{constructor($){super(),this.config=$,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets=$.trim_offsets}static fromConfig($){if($===null)return null;switch($.type){case"WordPiece":return new ke($);case"Metaspace":return new Gt($);case"ByteLevel":return new Ie($);case"Replace":return new J($);case"ByteFallback":return new le($);case"Fuse":return new ye($);case"Strip":return new Ee($);case"Sequence":return new Xe($);case"CTC":return new Re($);case"BPEDecoder":return new Ge($);default:throw new Error(`Unknown Decoder type: ${$.type}`)}}_call($){return this.decode($)}decode($){return this.decode_chain($).join("")}decode_chain($){throw Error("`decode_chain` should be implemented in subclass.")}}class J extends z{decode_chain($){const N=f(this.config.pattern);return N===null?$:$.map(Q=>Q.replaceAll(N,this.config.content))}}class le extends z{constructor($){super($),this.text_decoder=new TextDecoder}decode_chain($){const N=[];let Q=[];for(const ie of $){let de=null;if(ie.length===6&&ie.startsWith("<0x")&&ie.endsWith(">")){const ve=parseInt(ie.slice(3,5),16);isNaN(ve)||(de=ve)}if(de!==null)Q.push(de);else{if(Q.length>0){const ve=this.text_decoder.decode(Uint8Array.from(Q));N.push(ve),Q=[]}N.push(ie)}}if(Q.length>0){const ie=this.text_decoder.decode(Uint8Array.from(Q));N.push(ie),Q=[]}return N}}class ye extends z{decode_chain($){return[$.join("")]}}class Ee extends z{constructor($){super($),this.content=this.config.content,this.start=this.config.start,this.stop=this.config.stop}decode_chain($){return $.map(N=>{let Q=0;for(let de=0;de(Q!==0&&(N.startsWith(this.config.prefix)?N=N.replace(this.config.prefix,""):N=" "+N),this.cleanup&&(N=k(N)),N))}}class Ie extends z{constructor($){super($),this.byte_decoder=H,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string($){const N=$.join(""),Q=new Uint8Array([...N].map(de=>this.byte_decoder[de]));return this.text_decoder.decode(Q)}decode_chain($){const N=[];let Q=[];for(const ie of $)this.added_tokens.find(de=>de.content===ie)!==void 0?(Q.length>0&&(N.push(this.convert_tokens_to_string(Q)),Q=[]),N.push(ie)):Q.push(ie);return Q.length>0&&N.push(this.convert_tokens_to_string(Q)),N}}class Re extends z{constructor($){super($),this.pad_token=this.config.pad_token,this.word_delimiter_token=this.config.word_delimiter_token,this.cleanup=this.config.cleanup}convert_tokens_to_string($){if($.length===0)return"";const N=[$[0]];for(let de=1;de<$.length;++de)$[de]!==N.at(-1)&&N.push($[de]);let ie=N.filter(de=>de!==this.pad_token).join("");return this.cleanup&&(ie=k(ie).replaceAll(this.word_delimiter_token," ").trim()),ie}decode_chain($){return[this.convert_tokens_to_string($)]}}class Xe extends z{constructor($){super($),this.decoders=$.decoders.map(N=>z.fromConfig(N))}decode_chain($){return this.decoders.reduce((N,Q)=>Q.decode_chain(N),$)}}class Ge extends z{constructor($){super($),this.suffix=this.config.suffix}decode_chain($){return $.map((N,Q)=>N.replaceAll(this.suffix,Q===$.length-1?"":" "))}}class lt extends z{decode_chain($){let N="";for(let Q=1;Q<$.length;Q+=2)N+=$[Q];return[N]}}class wt extends q{constructor($){super(),this.addPrefixSpace=$.add_prefix_space,this.replacement=$.replacement,this.strRep=$.str_rep||this.replacement,this.prepend_scheme=$.prepend_scheme??"always"}pre_tokenize_text($,{section_index:N=void 0}={}){let Q=$.replaceAll(" ",this.strRep);return this.addPrefixSpace&&!Q.startsWith(this.replacement)&&(this.prepend_scheme==="always"||this.prepend_scheme==="first"&&N===0)&&(Q=this.strRep+Q),[Q]}}class Gt extends z{constructor($){super($),this.addPrefixSpace=$.add_prefix_space,this.replacement=$.replacement}decode_chain($){const N=[];for(let Q=0;Q<$.length;++Q){let ie=$[Q].replaceAll(this.replacement," ");this.addPrefixSpace&&Q==0&&ie.startsWith(" ")&&(ie=ie.substring(1)),N.push(ie)}return N}}class Ot extends oe{constructor($){super($),this.charsmap=$.precompiled_charsmap}normalize($){return $=$.replace(/[\u0001-\u0008\u000B\u000E-\u001F\u007F\u008F\u009F]/gm,""),$=$.replace(/[\u0009\u000A\u000C\u000D\u00A0\u1680\u2000-\u200F\u2028\u2029\u202F\u205F\u2581\u3000\uFEFF\uFFFD]/gm," "),$.includes("~")?$=$.split("~").map(Q=>Q.normalize("NFKC")).join("~"):$=$.normalize("NFKC"),$}}class ur extends q{constructor($){super(),this.tokenizers=$.pretokenizers.map(N=>q.fromConfig(N))}pre_tokenize_text($,N){return this.tokenizers.reduce((Q,ie)=>ie.pre_tokenize(Q,N),[$])}}class ls extends q{constructor($){super()}pre_tokenize_text($,N){return $.match(/\w+|[^\w\s]+/g)||[]}}class Ms extends q{constructor($){super()}pre_tokenize_text($,N){return y($)}}class Ir extends q{constructor($){super(),this.config=$,this.pattern=f(this.config.pattern),this.content=this.config.content}pre_tokenize_text($,N){return this.pattern===null?[$]:[$.replaceAll(this.pattern,this.config.content)]}}const js=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function Ss(he,$,N,Q){for(const ie of Object.keys(he)){const de=$-he[ie].length,ve=N(ie),je=new Array(de).fill(ve);he[ie]=Q==="right"?(0,o.mergeArrays)(he[ie],je):(0,o.mergeArrays)(je,he[ie])}}function Ns(he,$){for(const N of Object.keys(he))he[N].length=$}class at extends s.Callable{constructor(N,Q){super();te(this,"return_token_type_ids",!1);te(this,"padding_side","right");this._tokenizer_config=Q,this.normalizer=oe.fromConfig(N.normalizer),this.pre_tokenizer=q.fromConfig(N.pre_tokenizer),this.model=K.fromConfig(N.model,Q),this.post_processor=Ae.fromConfig(N.post_processor),this.decoder=z.fromConfig(N.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];for(const ie of N.added_tokens){const de=new B(ie);this.added_tokens.push(de),this.model.tokens_to_ids.set(de.content,de.id),this.model.vocab[de.id]=de.content,de.special&&(this.special_tokens.push(de.content),this.all_special_ids.push(de.id))}if(this.additional_special_tokens=Q.additional_special_tokens??[],this.special_tokens.push(...this.additional_special_tokens),this.special_tokens=[...new Set(this.special_tokens)],this.decoder&&(this.decoder.added_tokens=this.added_tokens,this.decoder.end_of_word_suffix=this.model.end_of_word_suffix),this.added_tokens_splitter=new l.DictionarySplitter(this.added_tokens.map(ie=>ie.content)),this.added_tokens_map=new Map(this.added_tokens.map(ie=>[ie.content,ie])),this.mask_token=this.getToken("mask_token"),this.mask_token_id=this.model.tokens_to_ids.get(this.mask_token),this.pad_token=this.getToken("pad_token","eos_token"),this.pad_token_id=this.model.tokens_to_ids.get(this.pad_token),this.sep_token=this.getToken("sep_token"),this.sep_token_id=this.model.tokens_to_ids.get(this.sep_token),this.unk_token=this.getToken("unk_token"),this.unk_token_id=this.model.tokens_to_ids.get(this.unk_token),this.bos_token=this.getToken("bos_token"),this.bos_token_id=this.model.tokens_to_ids.get(this.bos_token),this.eos_token=this.getToken("eos_token"),this.eos_token_id=this.model.tokens_to_ids.get(this.eos_token),this.model_max_length=Q.model_max_length,this.remove_space=Q.remove_space,this.clean_up_tokenization_spaces=Q.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=Q.do_lowercase_and_remove_accent??!1,Q.padding_side&&(this.padding_side=Q.padding_side),this.legacy=!1,this.chat_template=Q.chat_template??null,Array.isArray(this.chat_template)){const ie=Object.create(null);for(const{name:de,template:ve}of this.chat_template){if(typeof de!="string"||typeof ve!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');ie[de]=ve}this.chat_template=ie}this._compiled_template_cache=new Map}getToken(...N){for(const Q of N){const ie=this._tokenizer_config[Q];if(ie)if(typeof ie=="object"){if(ie.__type==="AddedToken")return ie.content;throw Error(`Unknown token: ${ie}`)}else return ie}return null}static async from_pretrained(N,{progress_callback:Q=null,config:ie=null,cache_dir:de=null,local_files_only:ve=!1,revision:je="main",legacy:He=null}={}){const We=await d(N,{progress_callback:Q,config:ie,cache_dir:de,local_files_only:ve,revision:je,legacy:He});return new this(...We)}_call(N,{text_pair:Q=null,add_special_tokens:ie=!0,padding:de=!1,truncation:ve=null,max_length:je=null,return_tensor:He=!0,return_token_type_ids:We=null}={}){const Je=Array.isArray(N);let dt;if(Je){if(N.length===0)throw Error("text array must be non-empty");if(Q!==null){if(Array.isArray(Q)){if(N.length!==Q.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");dt=N.map((Pt,jt)=>this._encode_plus(Pt,{text_pair:Q[jt],add_special_tokens:ie,return_token_type_ids:We}))}else dt=N.map(Pt=>this._encode_plus(Pt,{add_special_tokens:ie,return_token_type_ids:We}))}else{if(N==null)throw Error("text may not be null or undefined");if(Array.isArray(Q))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");dt=[this._encode_plus(N,{text_pair:Q,add_special_tokens:ie,return_token_type_ids:We})]}if(je===null?de==="max_length"?je=this.model_max_length:je=(0,i.max)(dt.map(Pt=>Pt.input_ids.length))[0]:ve||console.warn("Truncation was not explicitly activated but `max_length` is provided a specific value, please use `truncation=true` to explicitly truncate examples to max length."),je=Math.min(je,this.model_max_length??1/0),de||ve)for(let Pt=0;Ptje?ve&&Ns(dt[Pt],je):de&&Ss(dt[Pt],je,jt=>jt==="input_ids"?this.pad_token_id:0,this.padding_side));const xt={};if(He){if(!(de&&ve)&&dt.some(jt=>{var kt;for(const Ht of Object.keys(jt))if(jt[Ht].length!==((kt=dt[0][Ht])==null?void 0:kt.length))return!0;return!1}))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=true' and 'truncation=true' to have batched tensors with the same length.");const Pt=[dt.length,dt[0].input_ids.length];for(const jt of Object.keys(dt[0]))xt[jt]=new a.Tensor("int64",BigInt64Array.from(dt.flatMap(kt=>kt[jt]).map(BigInt)),Pt)}else{for(const Pt of Object.keys(dt[0]))xt[Pt]=dt.map(jt=>jt[Pt]);if(!Je)for(const Pt of Object.keys(xt))xt[Pt]=xt[Pt][0]}return xt}_encode_text(N){if(N===null)return null;const Q=this.added_tokens_splitter.split(N);for(let de=0;de0&&(Q[de-1]=Q[de-1].trimEnd()),ve.rstrip&&de{if(de.length===0)return[];if(this.added_tokens_map.has(de))return[de];if(this.remove_space===!0&&(de=de.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(de=g(de)),this.normalizer!==null&&(de=this.normalizer(de)),de.length===0)return[];const je=this.pre_tokenizer!==null?this.pre_tokenizer(de,{section_index:ve}):[de];return this.model(je)})}_encode_plus(N,{text_pair:Q=null,add_special_tokens:ie=!0,return_token_type_ids:de=null}={}){const{tokens:ve,token_type_ids:je}=this._tokenize_helper(N,{pair:Q,add_special_tokens:ie}),He=this.model.convert_tokens_to_ids(ve),We={input_ids:He,attention_mask:new Array(He.length).fill(1)};return(de??this.return_token_type_ids)&&je&&(We.token_type_ids=je),We}_tokenize_helper(N,{pair:Q=null,add_special_tokens:ie=!1}={}){const de=this._encode_text(N),ve=this._encode_text(Q);return this.post_processor?this.post_processor(de,ve,{add_special_tokens:ie}):{tokens:(0,o.mergeArrays)(de??[],ve??[])}}tokenize(N,{pair:Q=null,add_special_tokens:ie=!1}={}){return this._tokenize_helper(N,{pair:Q,add_special_tokens:ie}).tokens}encode(N,{text_pair:Q=null,add_special_tokens:ie=!0,return_token_type_ids:de=null}={}){return this._encode_plus(N,{text_pair:Q,add_special_tokens:ie,return_token_type_ids:de}).input_ids}batch_decode(N,Q={}){return N instanceof a.Tensor&&(N=N.tolist()),N.map(ie=>this.decode(ie,Q))}decode(N,Q={}){if(N instanceof a.Tensor&&(N=T(N)),!Array.isArray(N)||N.length===0||!(0,o.isIntegralNumber)(N[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(N,Q)}decode_single(N,{skip_special_tokens:Q=!1,clean_up_tokenization_spaces:ie=null}){let de=this.model.convert_ids_to_tokens(N);Q&&(de=de.filter(je=>!this.special_tokens.includes(je)));let ve=this.decoder?this.decoder(de):de.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(ve=ve.replaceAll(this.decoder.end_of_word_suffix," "),Q&&(ve=ve.trim())),(ie??this.clean_up_tokenization_spaces)&&(ve=k(ve)),ve}get_chat_template({chat_template:N=null,tools:Q=null}={}){if(this.chat_template&&typeof this.chat_template=="object"){const ie=this.chat_template;if(N!==null&&Object.hasOwn(ie,N))N=ie[N];else if(N===null)if(Q!==null&&"tool_use"in ie)N=ie.tool_use;else if("default"in ie)N=ie.default;else throw Error(`This model has multiple chat templates with no default specified! Please either pass a chat template or the name of the template you wish to use to the 'chat_template' argument. Available template names are ${Object.keys(ie).sort()}.`)}else if(N===null)if(this.chat_template)N=this.chat_template;else throw Error("Cannot use apply_chat_template() because tokenizer.chat_template is not set and no template argument was passed! For information about writing templates and setting the tokenizer.chat_template attribute, please see the documentation at https://huggingface.co/docs/transformers/main/en/chat_templating");return N}apply_chat_template(N,{tools:Q=null,documents:ie=null,chat_template:de=null,add_generation_prompt:ve=!1,tokenize:je=!0,padding:He=!1,truncation:We=!1,max_length:Je=null,return_tensor:dt=!0,return_dict:xt=!1,tokenizer_kwargs:Pt={},...jt}={}){if(de=this.get_chat_template({chat_template:de,tools:Q}),typeof de!="string")throw Error(`chat_template must be a string, but got ${typeof de}`);let kt=this._compiled_template_cache.get(de);kt===void 0&&(kt=new u.Template(de),this._compiled_template_cache.set(de,kt));const Ht=Object.create(null);for(const cr of js){const pr=this.getToken(cr);pr&&(Ht[cr]=pr)}const br=kt.render({messages:N,add_generation_prompt:ve,tools:Q,documents:ie,...Ht,...jt});if(je){const cr=this._call(br,{add_special_tokens:!1,padding:He,truncation:We,max_length:Je,return_tensor:dt,...Pt});return xt?cr:cr.input_ids}return br}}class us extends at{constructor(){super(...arguments);te(this,"return_token_type_ids",!0)}}class Ar extends at{constructor(){super(...arguments);te(this,"return_token_type_ids",!0)}}class bs extends at{constructor(){super(...arguments);te(this,"return_token_type_ids",!0)}}class Ft extends at{constructor(){super(...arguments);te(this,"return_token_type_ids",!0)}}class ds extends at{constructor(){super(...arguments);te(this,"return_token_type_ids",!0)}}class cs extends at{constructor(){super(...arguments);te(this,"return_token_type_ids",!0)}}class ys extends at{constructor(){super(...arguments);te(this,"return_token_type_ids",!0)}}class Qt extends at{constructor(){super(...arguments);te(this,"return_token_type_ids",!0)}}class De extends at{constructor(){super(...arguments);te(this,"return_token_type_ids",!0)}}class Qe extends at{}class tt extends at{}class Rt extends at{constructor(N,Q){super(N,Q);te(this,"return_token_type_ids",!0);console.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}}class zr extends at{constructor(){super(...arguments);te(this,"return_token_type_ids",!0)}}class Sr extends at{}class ps extends at{}class hs extends at{}class Kr extends at{constructor($,N){super($,N),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.special_tokens.filter(Q=>this.languageRegex.test(Q)),this.lang_to_token=Q=>Q}_build_translation_inputs($,N,Q){return Tr(this,$,N,Q)}}class ms extends Kr{}class _s extends at{}class Hr extends at{}const vr="▁";class cn extends at{constructor(N,Q){super(N,Q);te(this,"padding_side","left");this.legacy=Q.legacy??!0,this.legacy||(this.normalizer=null,this.pre_tokenizer=new wt({replacement:vr,add_prefix_space:!0,prepend_scheme:"first"}))}_encode_text(N){if(N===null)return null;if(this.legacy||N.length===0)return super._encode_text(N);let Q=super._encode_text(vr+N.replaceAll(vr," "));return Q.length>1&&Q[0]===vr&&this.special_tokens.includes(Q[1])&&(Q=Q.slice(1)),Q}}class xr extends at{}class $s extends at{}class ks extends at{}class fr extends at{}class Vs extends at{}class pn extends at{}class Fr extends at{}class hn extends at{}class qr extends at{}function Tr(he,$,N,Q){if(!("language_codes"in he)||!Array.isArray(he.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in he)||!(he.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in he)||typeof he.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");const ie=Q.src_lang,de=Q.tgt_lang;if(!he.language_codes.includes(de))throw new Error(`Target language code "${de}" is not valid. Must be one of: {${he.language_codes.join(", ")}}`);if(ie!==void 0){if(!he.language_codes.includes(ie))throw new Error(`Source language code "${ie}" is not valid. Must be one of: {${he.language_codes.join(", ")}}`);for(const ve of he.post_processor.config.single)if("SpecialToken"in ve&&he.languageRegex.test(ve.SpecialToken.id)){ve.SpecialToken.id=he.lang_to_token(ie);break}}return Q.forced_bos_token_id=he.model.convert_tokens_to_ids([he.lang_to_token(de)])[0],he._call($,N)}class Is extends at{constructor($,N){super($,N),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.special_tokens.filter(Q=>this.languageRegex.test(Q)),this.lang_to_token=Q=>Q}_build_translation_inputs($,N,Q){return Tr(this,$,N,Q)}}class dr extends at{constructor($,N){super($,N),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.special_tokens.filter(Q=>this.languageRegex.test(Q)).map(Q=>Q.slice(2,-2)),this.lang_to_token=Q=>`__${Q}__`}_build_translation_inputs($,N,Q){return Tr(this,$,N,Q)}}class gr extends at{get timestamp_begin(){return this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0]+1}_decode_asr($,{return_timestamps:N=!1,return_language:Q=!1,time_precision:ie=null,force_full_sequences:de=!0}={}){if(ie===null)throw Error("Must specify time_precision");let ve=null;const je=N==="word";function He(){return{language:ve,timestamp:[null,null],text:""}}const We=[];let Je=He(),dt=0;const xt=this.timestamp_begin,jt=xt+1500;let kt=[],Ht=[],br=!1,cr=null;const pr=new Set(this.all_special_ids);for(const Dt of $){const rr=Dt.tokens,wr=je?Dt.token_timestamps:null;let Qr=null,Rr=xt;if("stride"in Dt){const[or,Vt,Zt]=Dt.stride;if(dt-=Vt,cr=or-Zt,Vt&&(Rr=Vt/ie+xt),Zt)for(let er=rr.length-1;er>=0;--er){const tr=Number(rr[er]);if(tr>=xt){if(Qr!==null&&(tr-xt)*ie=xt&&Vt<=jt){const Zt=(Vt-xt)*ie+dt,er=(0,i.round)(Zt,2);if(Qr!==null&&Vt>=Qr)br=!0;else if(br||kt.length>0&&Vt0?(kt.push(Yt),je&&Ht.push(jr)):kt.every(or=>or.length===0)&&(Je=He(),kt=[],Yt=[],Ht=[],jr=[])}if(kt.length>0){if(de&&N)throw new Error("Whisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. Also make sure WhisperTimeStampLogitsProcessor was used during generation.");const[Dt,rr]=this.findLongestCommonSequence(kt,Ht),wr=this.decode(Dt);Je.text=wr,je&&(Je.words=this.collateWordTimestamps(Dt,rr,ve)),We.push(Je)}let Nt=Object.create(null);const Xr=We.map(Dt=>Dt.text).join("");if(N||Q){for(let Dt=0;Dt0;let je=ve?[]:null,He=ve?N[0]:null;for(let We=1;We<$.length;++We){const Je=$[We];let dt=0,xt=[ie,ie,0,0];const Pt=Je.length;for(let Nt=1;NtVt===Rr[Zt]&&He[Xr+Zt]<=N[We][wr+Zt]).length:Yt=rr.filter((Vt,Zt)=>Vt===Rr[Zt]).length;const jr=Nt/1e4,or=Yt/Nt+jr;Yt>1&&or>dt&&(dt=or,xt=[Xr,Dt,wr,Qr])}const[jt,kt,Ht,br]=xt,cr=Math.floor((kt+jt)/2),pr=Math.floor((br+Ht)/2);de.push(...Q.slice(0,cr)),Q=Je.slice(pr),ie=Q.length,ve&&(je.push(...He.slice(0,cr)),He=N[We].slice(pr))}return de.push(...Q),ve?(je.push(...He),[de,je]):[de,[]]}collateWordTimestamps($,N,Q){const[ie,de,ve]=this.combineTokensIntoWords($,Q),je=[];for(let He=0;He=ie){const je=((ve-ie)*Q).toFixed(2);de.push(`<|${je}|>`),de.push([])}else de[de.length-1].push(ve);return de=de.map(ve=>typeof ve=="string"?ve:super.decode(ve,N)),de.join("")}splitTokensOnUnicode($){const N=this.decode($,{decode_with_timestamps:!0}),Q="�",ie=[],de=[],ve=[];let je=[],He=[],We=0;for(let Je=0;Je<$.length;++Je){const dt=$[Je];je.push(dt),He.push(Je);const xt=this.decode(je,{decode_with_timestamps:!0});(!xt.includes(Q)||N[We+xt.indexOf(Q)]===Q)&&(ie.push(xt),de.push(je),ve.push(He),je=[],He=[],We+=xt.length)}return[ie,de,ve]}splitTokensOnSpaces($){const[N,Q,ie]=this.splitTokensOnUnicode($),de=[],ve=[],je=[],He=new RegExp(`^[${M}]$`,"gu");for(let We=0;We=this.model.tokens_to_ids.get("<|endoftext|>"),jt=Je.startsWith(" "),kt=Je.trim(),Ht=He.test(kt);if(Pt||jt||Ht||de.length===0)de.push(Je),ve.push(dt),je.push(xt);else{const br=de.length-1;de[br]+=Je,ve[br].push(...dt),je[br].push(...xt)}}return[de,ve,je]}mergePunctuations($,N,Q,ie,de){const ve=structuredClone($),je=structuredClone(N),He=structuredClone(Q);let We=ve.length-2,Je=ve.length-1;for(;We>=0;)ve[We].startsWith(" ")&&ie.includes(ve[We].trim())?(ve[Je]=ve[We]+ve[Je],je[Je]=(0,o.mergeArrays)(je[We],je[Je]),He[Je]=(0,o.mergeArrays)(He[We],He[Je]),ve[We]="",je[We]=[],He[We]=[]):Je=We,--We;for(We=0,Je=1;Jedt),je.filter(dt=>dt.length>0),He.filter(dt=>dt.length>0)]}}class Br extends at{}class mn extends at{}class _n extends at{}class fn extends at{constructor($,N){super($,N),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=this.model.vocab.filter(Q=>this.languageRegex.test(Q)),console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text($){if($===null)return null;const[N,...Q]=$.trim().split(this.languageRegex);if(Q.length===0)return super._encode_text(N);if(Q.length===2){const[ie,de]=Q;return this.supported_language_codes.includes(ie)||console.warn(`Unsupported language code "${ie}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),(0,o.mergeArrays)([ie],super._encode_text(de))}}}class gn extends at{}class wn extends at{}class vs extends at{}class Mn extends at{}class Us extends at{}class bn extends at{constructor($,N){super($,N),this.decoder=new lt({})}}class yn extends at{}class xs extends at{}class vn{static async from_pretrained($,{progress_callback:N=null,config:Q=null,cache_dir:ie=null,local_files_only:de=!1,revision:ve="main",legacy:je=null}={}){var xt;const[He,We]=await d($,{progress_callback:N,config:Q,cache_dir:ie,local_files_only:de,revision:ve,legacy:je}),Je=((xt=We.tokenizer_class)==null?void 0:xt.replace(/Fast$/,""))??"PreTrainedTokenizer";let dt=this.TOKENIZER_CLASS_MAPPING[Je];return dt||(console.warn(`Unknown tokenizer class "${Je}", attempting to construct from base class.`),dt=at),new dt(He,We)}}te(vn,"TOKENIZER_CLASS_MAPPING",{T5Tokenizer:Sr,DistilBertTokenizer:Qe,CamembertTokenizer:tt,DebertaTokenizer:ds,DebertaV2Tokenizer:cs,BertTokenizer:us,HerbertTokenizer:ys,ConvBertTokenizer:Qt,RoFormerTokenizer:De,XLMTokenizer:Rt,ElectraTokenizer:zr,MobileBertTokenizer:bs,SqueezeBertTokenizer:Ft,AlbertTokenizer:Ar,GPT2Tokenizer:ps,BartTokenizer:hs,MBartTokenizer:Kr,MBart50Tokenizer:ms,RobertaTokenizer:_s,WhisperTokenizer:gr,CodeGenTokenizer:Br,CLIPTokenizer:mn,SiglipTokenizer:_n,MarianTokenizer:fn,BloomTokenizer:Hr,NllbTokenizer:Is,M2M100Tokenizer:dr,LlamaTokenizer:cn,CodeLlamaTokenizer:xr,XLMRobertaTokenizer:$s,MPNetTokenizer:ks,FalconTokenizer:fr,GPTNeoXTokenizer:Vs,EsmTokenizer:pn,Wav2Vec2CTCTokenizer:gn,BlenderbotTokenizer:wn,BlenderbotSmallTokenizer:vs,SpeechT5Tokenizer:Mn,NougatTokenizer:Us,VitsTokenizer:bn,Qwen2Tokenizer:Fr,GemmaTokenizer:hn,Grok1Tokenizer:qr,CohereTokenizer:yn,MgpstrTokenizer:xs,PreTrainedTokenizer:at})},"./src/utils/audio.js":(e,r,t)=>{t.r(r),t.d(r,{RawAudio:()=>G,hamming:()=>c,hanning:()=>d,mel_filter_bank:()=>S,read_audio:()=>u,spectrogram:()=>C,window_function:()=>A});var s=t("./src/utils/hub.js"),o=t("./src/utils/maths.js"),n=t("./src/utils/core.js"),i=t("./src/env.js"),a=t("?7a2c"),l=t("./src/utils/tensor.js");async function u(j,ee){if(typeof AudioContext>"u")throw Error("Unable to load audio from path/URL since `AudioContext` is not available in your environment. Instead, audio data should be passed directly to the pipeline/processor. For more information and some example code, see https://huggingface.co/docs/transformers.js/guides/node-audio-processing.");const H=await(await(0,s.getFile)(j)).arrayBuffer(),Z=new AudioContext({sampleRate:ee});typeof ee>"u"&&console.warn(`No sampling rate provided, using default of ${Z.sampleRate}Hz.`);const X=await Z.decodeAudioData(H);let oe;if(X.numberOfChannels===2){const me=Math.sqrt(2),ae=X.getChannelData(0),V=X.getChannelData(1);oe=new Float32Array(ae.length);for(let F=0;F2595*Math.log10(1+j/700),kaldi:j=>1127*Math.log(1+j/700),slaney:(j,ee=1e3,H=15,Z=27/Math.log(6.4))=>j>=ee?H+Math.log(j/ee)*Z:3*j/200};function _(j,ee="htk"){const H=f[ee];if(!H)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof j=="number"?H(j):j.map(Z=>H(Z))}const T={htk:j=>700*(10**(j/2595)-1),kaldi:j=>700*(Math.exp(j/1127)-1),slaney:(j,ee=1e3,H=15,Z=Math.log(6.4)/27)=>j>=H?ee*Math.exp(Z*(j-H)):200*j/3};function k(j,ee="htk"){const H=T[ee];if(!H)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof j=="number"?H(j):j.map(Z=>H(Z))}function w(j,ee){const H=Float64Array.from({length:ee.length-1},(me,ae)=>ee[ae+1]-ee[ae]),Z=Array.from({length:j.length},()=>new Array(ee.length));for(let me=0;menew Array(j.length));for(let me=0;mej+Z*oe)}function S(j,ee,H,Z,X,oe=null,me="htk",ae=!1){if(oe!==null&&oe!=="slaney")throw new Error('norm must be one of null or "slaney"');if(j<2)throw new Error(`Require num_frequency_bins: ${j} >= 2`);if(H>Z)throw new Error(`Require min_frequency: ${H} <= max_frequency: ${Z}`);const V=_(H,me),F=_(Z,me),W=g(V,F,ee+2);let re=k(W,me),_e;if(ae){const ce=X/((j-1)*2);_e=_(Float64Array.from({length:j},($e,Ue)=>Ue*ce),me),re=W}else _e=g(0,Math.floor(X/2),j);const se=w(_e,re);if(oe!==null&&oe==="slaney")for(let ce=0;ceX)throw Error(`frame_length (${H}) may not be larger than fft_length (${X})`);if(xe!==H)throw new Error(`Length of the window (${xe}) must equal frame_length (${H})`);if(Z<=0)throw new Error("hop_length must be greater than zero");if(oe===null&&W!==null)throw new Error("You have provided `mel_filters` but `power` is `None`. Mel spectrogram computation is not yet supported for complex-valued spectrogram. Specify `power` to fix this issue.");if(me){if(ae!=="reflect")throw new Error(`pad_mode="${ae}" not implemented yet.`);const ye=Math.floor((X-1)/2)+1;j=E(j,ye,ye)}let be=Math.floor(1+Math.floor((j.length-H)/Z));we!==null&&bebe?R&&(Fe=q):Fe=Ae=q);const ze=new o.FFT(X),Ve=new Float64Array(X),O=new Float64Array(ze.outputBufferSize),Y=new Float32Array(Se*Fe);for(let ye=0;ye=1;--Ie)Ve[Ie]-=F*Ve[Ie-1];Ve[0]*=1-F}for(let Ie=0;IeMath.pow(ae,.85));break;default:throw new Error(`Unknown window type ${ee}.`)}if(H&&(me=me.subarray(0,j)),Z===null)return me;if(j>Z)throw new Error(`Length of the window (${j}) may not be larger than frame_length (${Z})`);return me}function B(j,ee){let H=44;const Z=new ArrayBuffer(H+j.length*4),X=new DataView(Z);K(X,0,"RIFF"),X.setUint32(4,36+j.length*4,!0),K(X,8,"WAVE"),K(X,12,"fmt "),X.setUint32(16,16,!0),X.setUint16(20,3,!0),X.setUint16(22,1,!0),X.setUint32(24,ee,!0),X.setUint32(28,ee*4,!0),X.setUint16(32,4,!0),X.setUint16(34,32,!0),K(X,36,"data"),X.setUint32(40,j.length*4,!0);for(let oe=0;oe{let oe=await X.arrayBuffer();a.writeFileSync(Z,Buffer.from(oe))};else throw new Error("Unable to save because filesystem is disabled in this environment.");await H(ee,this.toBlob())}}},"./src/utils/constants.js":(e,r,t)=>{t.r(r),t.d(r,{CHAT_TEMPLATE_NAME:()=>l,CONFIG_NAME:()=>o,FEATURE_EXTRACTOR_NAME:()=>n,GENERATION_CONFIG_NAME:()=>u,GITHUB_ISSUE_URL:()=>s,IMAGE_PROCESSOR_NAME:()=>i,PROCESSOR_NAME:()=>a});const s="https://github.com/huggingface/transformers.js/issues/new/choose",o="config.json",n="preprocessor_config.json",i=n,a="processor_config.json",l="chat_template.json",u="generation_config.json"},"./src/utils/core.js":(e,r,t)=>{t.r(r),t.d(r,{calculateDimensions:()=>u,calculateReflectOffset:()=>f,count:()=>w,dispatchCallback:()=>s,escapeRegExp:()=>n,isIntegralNumber:()=>a,isNullishDimension:()=>l,isTypedArray:()=>i,len:()=>k,mergeArrays:()=>d,pick:()=>T,pop:()=>p,product:()=>c,reverseDictionary:()=>o,saveBlob:()=>_});function s(g,S){g&&g(S)}function o(g){return Object.fromEntries(Object.entries(g).map(([S,E])=>[E,S]))}function n(g){return g.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function i(g){var S,E,y;return((y=(E=(S=g==null?void 0:g.prototype)==null?void 0:S.__proto__)==null?void 0:E.constructor)==null?void 0:y.name)==="TypedArray"}function a(g){return Number.isInteger(g)||typeof g=="bigint"}function l(g){return g==null||g===-1}function u(g){const S=[];let E=g;for(;Array.isArray(E);)S.push(E.length),E=E[0];return S}function p(g,S,E=void 0){const y=g[S];if(y!==void 0)return delete g[S],y;if(E===void 0)throw Error(`Key ${S} does not exist in object.`);return E}function d(...g){return Array.prototype.concat.apply([],g)}function c(...g){return g.reduce((S,E)=>S.flatMap(y=>E.map(M=>[y,M])))}function f(g,S){return Math.abs((g+S)%(2*S)-S)}function _(g,S){const E=URL.createObjectURL(S),y=document.createElement("a");y.href=E,y.download=g,y.click(),y.remove(),URL.revokeObjectURL(E)}function T(g,S){return Object.assign({},...S.map(E=>{if(g[E]!==void 0)return{[E]:g[E]}}))}function k(g){let S=0;for(const E of g)++S;return S}function w(g,S){let E=0;for(const y of g)y===S&&++E;return E}},"./src/utils/data-structures.js":(e,r,t)=>{t.r(r),t.d(r,{CharTrie:()=>o,DictionarySplitter:()=>l,LRUCache:()=>u,PriorityQueue:()=>s,TokenLattice:()=>i});class s{constructor(d=(f,_)=>f>_,c=1/0){this._heap=[],this._comparator=d,this._maxSize=c}get size(){return this._heap.length}isEmpty(){return this.size===0}peek(){return this._heap[0]}push(...d){return this.extend(d)}extend(d){for(const c of d)if(this.size0&&this._swap(0,c),this._heap.pop(),this._siftDown(),d}replace(d){const c=this.peek();return this._heap[0]=d,this._siftDown(),c}_parent(d){return(d+1>>>1)-1}_left(d){return(d<<1)+1}_right(d){return d+1<<1}_greater(d,c){return this._comparator(this._heap[d],this._heap[c])}_swap(d,c){const f=this._heap[d];this._heap[d]=this._heap[c],this._heap[c]=f}_siftUp(){this._siftUpFrom(this.size-1)}_siftUpFrom(d){for(;d>0&&this._greater(d,this._parent(d));)this._swap(d,this._parent(d)),d=this._parent(d)}_siftDown(){let d=0;for(;this._left(d)[]),this.endNodes=Array.from({length:this.len+1},()=>[]);const _=new a(this.bosTokenId,0,0,0,0),T=new a(this.eosTokenId,1,this.len,0,0);this.nodes.push(_.clone()),this.nodes.push(T.clone()),this.beginNodes[this.len].push(T),this.endNodes[0].push(_)}insert(d,c,f,_){const T=this.nodes.length,k=new a(_,T,d,c,f);this.beginNodes[d].push(k),this.endNodes[d+c].push(k),this.nodes.push(k)}viterbi(){const d=this.len;let c=0;for(;c<=d;){if(this.beginNodes[c].length==0)return[];for(let w of this.beginNodes[c]){w.prev=null;let g=0,S=null;for(let E of this.endNodes[c]){const y=E.backtraceScore+w.score;(S===null||y>g)&&(S=E.clone(),g=y)}if(S!==null)w.prev=S,w.backtraceScore=g;else return[]}++c}const f=[],T=this.beginNodes[d][0].prev;if(T===null)return[];let k=T.clone();for(;k.prev!==null;)f.push(k.clone()),k=k.clone().prev.clone();return f.reverse(),f}piece(d){return this.chars.slice(d.pos,d.pos+d.length).join("")}tokens(){return this.viterbi().map(c=>this.piece(c))}tokenIds(){return this.viterbi().map(c=>c.tokenId)}}class a{constructor(d,c,f,_,T){this.tokenId=d,this.nodeId=c,this.pos=f,this.length=_,this.score=T,this.prev=null,this.backtraceScore=0}clone(){const d=new a(this.tokenId,this.nodeId,this.pos,this.length,this.score);return d.prev=this.prev,d.backtraceScore=this.backtraceScore,d}}class l{constructor(d){this.trie=this._buildTrie(d)}_buildTrie(d){var f;const c=Object.create(null);for(const _ of d){let T=c;for(let k=0;k<_.length;++k)T=T[f=_[k]]??(T[f]=Object.create(null));T.end=_}return c}split(d){const c=[],f=d.length;let _=0,T=0;for(;T_&&c.push(d.slice(_,T)),c.push(w),T+=w.length,_=T):++T}return _this.capacity&&this.cache.delete(this.cache.keys().next().value)}clear(){this.cache.clear()}}},"./src/utils/devices.js":(e,r,t)=>{t.r(r),t.d(r,{DEVICE_TYPES:()=>s});const s=Object.freeze({auto:"auto",gpu:"gpu",cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",webnn:"webnn","webnn-npu":"webnn-npu","webnn-gpu":"webnn-gpu","webnn-cpu":"webnn-cpu"})},"./src/utils/dtypes.js":(e,r,t)=>{t.r(r),t.d(r,{DATA_TYPES:()=>i,DEFAULT_DEVICE_DTYPE_MAPPING:()=>a,DEFAULT_DTYPE_SUFFIX_MAPPING:()=>l,isWebGpuFp16Supported:()=>n});var s=t("./src/env.js"),o=t("./src/utils/devices.js");const n=function(){let u;return async function(){if(u===void 0)if(!s.apis.IS_WEBGPU_AVAILABLE)u=!1;else try{u=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{u=!1}return u}}(),i=Object.freeze({auto:"auto",fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16"}),a=Object.freeze({[o.DEVICE_TYPES.wasm]:i.q8}),l=Object.freeze({[i.fp32]:"",[i.fp16]:"_fp16",[i.int8]:"_int8",[i.uint8]:"_uint8",[i.q8]:"_quantized",[i.q4]:"_q4",[i.q4f16]:"_q4f16",[i.bnb4]:"_bnb4"})},"./src/utils/generic.js":(e,r,t)=>{t.r(r),t.d(r,{Callable:()=>s});const s=class{constructor(){let o=function(...n){return o._call(...n)};return Object.setPrototypeOf(o,new.target.prototype)}_call(...o){throw Error("Must implement _call method in subclass")}}},"./src/utils/hub.js":(e,r,t)=>{t.r(r),t.d(r,{MAX_EXTERNAL_DATA_CHUNKS:()=>a,getFile:()=>f,getModelFile:()=>g,getModelJSON:()=>S});var s=t("?7a2c"),o=t("?a42a"),n=t("./src/env.js"),i=t("./src/utils/core.js");const a=100,l={txt:"text/plain",html:"text/html",css:"text/css",js:"text/javascript",json:"application/json",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif"};class u{constructor(v){if(this.filePath=v,this.headers=new Headers,this.exists=s.existsSync(v),this.exists){this.status=200,this.statusText="OK";let C=s.statSync(v);this.headers.set("content-length",C.size.toString()),this.updateContentType();const A=s.createReadStream(v);this.body=new ReadableStream({start(B){A.on("data",K=>B.enqueue(K)),A.on("end",()=>B.close()),A.on("error",K=>B.error(K))},cancel(){A.destroy()}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){const v=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",l[v]??"application/octet-stream")}clone(){let v=new u(this.filePath);return v.exists=this.exists,v.status=this.status,v.statusText=this.statusText,v.headers=new Headers(this.headers),v}async arrayBuffer(){return(await s.promises.readFile(this.filePath)).buffer}async blob(){const v=await s.promises.readFile(this.filePath);return new Blob([v],{type:this.headers.get("content-type")})}async text(){return await s.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}}function p(M,v=null,C=null){let A;try{A=new URL(M)}catch{return!1}return!(v&&!v.includes(A.protocol)||C&&!C.includes(A.hostname))}const d=/^(\b[\w\-.]+\b\/)?\b[\w\-.]{1,96}\b$/;function c(M){return!(!d.test(M)||M.includes("..")||M.includes("--")||M.endsWith(".git")||M.endsWith(".ipynb"))}async function f(M){var v;if(n.env.useFS&&!p(M,["http:","https:","blob:"]))return new u(M.toString());if(typeof process<"u"&&((v=process==null?void 0:process.release)==null?void 0:v.name)==="node"){const C=!!(Cs!=null&&Cs.TESTING_REMOTELY),A=n.env.version,B=new Headers;if(B.set("User-Agent",`transformers.js/${A}; is_ci/${C};`),p(M,["http:","https:"],["huggingface.co","hf.co"])){const G=(Cs==null?void 0:Cs.HF_TOKEN)??(Cs==null?void 0:Cs.HF_ACCESS_TOKEN);G&&B.set("Authorization",`Bearer ${G}`)}return fetch(M,{headers:B})}else return fetch(M)}const _={400:"Bad request error occurred while trying to load file",401:"Unauthorized access to file",403:"Forbidden access to file",404:"Could not locate file",408:"Request timeout error occurred while trying to load file",500:"Internal server error error occurred while trying to load file",502:"Bad gateway error occurred while trying to load file",503:"Service unavailable error occurred while trying to load file",504:"Gateway timeout error occurred while trying to load file"};function T(M,v,C){if(!C)return null;const A=_[M]??`Error (${M}) occurred while trying to load file`;throw Error(`${A}: "${v}".`)}class k{constructor(v){this.path=v}async match(v){let C=o.join(this.path,v),A=new u(C);if(A.exists)return A}async put(v,C,A=void 0){let B=o.join(this.path,v);try{const K=C.headers.get("Content-Length"),G=parseInt(K??"0");let j=0;await s.promises.mkdir(o.dirname(B),{recursive:!0});const ee=s.createWriteStream(B),H=C.body.getReader();for(;;){const{done:Z,value:X}=await H.read();if(Z)break;await new Promise((me,ae)=>{ee.write(X,V=>{if(V){ae(V);return}me()})}),j+=X.length;const oe=G?j/G*100:0;A==null||A({progress:oe,loaded:j,total:G})}ee.close()}catch(K){try{await s.promises.unlink(B)}catch{}throw K}}}async function w(M,...v){for(let C of v)try{let A=await M.match(C);if(A)return A}catch{continue}}async function g(M,v,C=!0,A={},B=!1){if(!n.env.allowLocalModels){if(A.local_files_only)throw Error("Invalid configuration detected: local models are disabled (`env.allowLocalModels=false`) but you have requested to only use local models (`local_files_only=true`).");if(!n.env.allowRemoteModels)throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.")}(0,i.dispatchCallback)(A.progress_callback,{status:"initiate",name:M,file:v});let K;if(!K&&n.env.useCustomCache){if(!n.env.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!n.env.customCache.match||!n.env.customCache.put)throw new Error("`env.customCache` must be an object which implements the `match` and `put` functions of the Web Cache API. For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache");K=n.env.customCache}if(!K&&n.env.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{K=await caches.open("transformers-cache")}catch(re){console.warn("An error occurred while opening the browser cache:",re)}}if(!K&&n.env.useFSCache){if(!n.apis.IS_FS_AVAILABLE)throw Error("File System Cache is not available in this environment.");K=new k(A.cache_dir??n.env.cacheDir)}const G=A.revision??"main",j=y(M,v),ee=c(M),H=ee?y(n.env.localModelPath,j):j,Z=y(n.env.remoteHost,n.env.remotePathTemplate.replaceAll("{model}",M).replaceAll("{revision}",encodeURIComponent(G)),v);let X;const oe=K instanceof k?G==="main"?j:y(M,G,v):Z;let me=!1,ae;K&&(ae=await w(K,H,oe));const V=ae!==void 0;if(ae===void 0){if(n.env.allowLocalModels)if(p(j,["http:","https:"])){if(A.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${j}.`);if(!n.env.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${j}.`)}else try{ae=await f(H),X=H}catch(_e){console.warn(`Unable to load from local path "${H}": "${_e}"`)}if(ae===void 0||ae.status===404){if(A.local_files_only||!n.env.allowRemoteModels){if(C)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${H}".`);return null}if(!ee)throw Error(`Local file missing at "${H}" and download aborted due to invalid model ID "${M}".`);if(ae=await f(Z),ae.status!==200)return T(ae.status,Z,C);X=oe}me=K&&typeof Response<"u"&&ae instanceof Response&&ae.status===200}(0,i.dispatchCallback)(A.progress_callback,{status:"download",name:M,file:v});let F;if(!(n.apis.IS_NODE_ENV&&B)){let re;A.progress_callback?V&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent)?(re=new Uint8Array(await ae.arrayBuffer()),(0,i.dispatchCallback)(A.progress_callback,{status:"progress",name:M,file:v,progress:100,loaded:re.length,total:re.length})):re=await E(ae,_e=>{(0,i.dispatchCallback)(A.progress_callback,{status:"progress",name:M,file:v,..._e})}):re=new Uint8Array(await ae.arrayBuffer()),F=re}if(me&&X&&await K.match(X)===void 0&&(F?await K.put(X,new Response(F,{headers:ae.headers})).catch(re=>{console.warn(`Unable to add response to browser cache: ${re}.`)}):await K.put(X,ae,A.progress_callback)),(0,i.dispatchCallback)(A.progress_callback,{status:"done",name:M,file:v}),F){if(!n.apis.IS_NODE_ENV&&B)throw new Error("Cannot return path in a browser environment.");return F}if(ae instanceof u)return ae.filePath;const W=await(K==null?void 0:K.match(X));if(W instanceof u)return W.filePath;if(W instanceof Response)return new Uint8Array(await W.arrayBuffer());if(typeof W=="string")return W;throw new Error("Unable to get model file path or buffer.")}async function S(M,v,C=!0,A={}){const B=await g(M,v,C,A,!1);if(B===null)return{};const G=new TextDecoder("utf-8").decode(B);return JSON.parse(G)}async function E(M,v){const C=M.headers.get("Content-Length");C===null&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let A=parseInt(C??"0"),B=new Uint8Array(A),K=0;const G=M.body.getReader();async function j(){const{done:ee,value:H}=await G.read();if(ee)return;const Z=K+H.length;if(Z>A){A=Z;const oe=new Uint8Array(A);oe.set(B),B=oe}B.set(H,K),K=Z;const X=K/A*100;return v({progress:X,loaded:K,total:A}),j()}return await j(),B}function y(...M){return M=M.map((v,C)=>(C&&(v=v.replace(new RegExp("^/"),"")),C!==M.length-1&&(v=v.replace(new RegExp("/$"),"")),v)),M.join("/")}},"./src/utils/image.js":(e,r,t)=>{t.r(r),t.d(r,{RawImage:()=>_,load_image:()=>T});var s=t("./src/utils/core.js"),o=t("./src/utils/hub.js"),n=t("./src/env.js"),i=t("./src/utils/tensor.js"),a=t("?2b25");let l,u,p;const d=n.apis.IS_BROWSER_ENV||n.apis.IS_WEBWORKER_ENV;if(d)l=(k,w)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(k,w)},p=self.createImageBitmap,u=self.ImageData;else if(a)p=async k=>{const g=(await k.metadata()).channels,{data:S,info:E}=await k.rotate().raw().toBuffer({resolveWithObject:!0}),y=new _(new Uint8ClampedArray(S),E.width,E.height,E.channels);return g!==void 0&&g!==E.channels&&y.convert(g),y};else throw new Error("Unable to load image processing library.");const c={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},f=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]);class _{constructor(w,g,S,E){this.data=w,this.width=g,this.height=S,this.channels=E}get size(){return[this.width,this.height]}static async read(w){if(w instanceof _)return w;if(typeof w=="string"||w instanceof URL)return await this.fromURL(w);if(w instanceof Blob)return await this.fromBlob(w);if(typeof HTMLCanvasElement<"u"&&w instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&w instanceof OffscreenCanvas)return this.fromCanvas(w);throw new Error(`Unsupported input type: ${typeof w}`)}static fromCanvas(w){if(!d)throw new Error("fromCanvas() is only supported in browser environments.");const S=w.getContext("2d").getImageData(0,0,w.width,w.height).data;return new _(S,w.width,w.height,4)}static async fromURL(w){const g=await(0,o.getFile)(w);if(g.status!==200)throw new Error(`Unable to read image from "${w}" (${g.status} ${g.statusText})`);const S=await g.blob();return this.fromBlob(S)}static async fromBlob(w){if(d){const g=await p(w),S=l(g.width,g.height).getContext("2d");return S.drawImage(g,0,0),new this(S.getImageData(0,0,g.width,g.height).data,g.width,g.height,4)}else{const g=a(await w.arrayBuffer());return await p(g)}}static fromTensor(w,g="CHW"){if(w.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${w.dims.length} dimensions.`);if(g==="CHW")w=w.transpose(1,2,0);else if(g!=="HWC")throw new Error(`Unsupported channel format: ${g}`);if(!(w.data instanceof Uint8ClampedArray||w.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${w.type}`);switch(w.dims[2]){case 1:case 2:case 3:case 4:return new _(w.data,w.dims[1],w.dims[0],w.dims[2]);default:throw new Error(`Unsupported number of channels: ${w.dims[2]}`)}}grayscale(){if(this.channels===1)return this;const w=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let g=0,S=0;g=0?C=S:B=-S,E>=0?A=E:K=-E,v.drawImage(M,C,A,w,g,B,K,w,g),new _(v.getImageData(0,0,w,g).data,w,g,4).convert(y)}else{let y=this.toSharp();if(S>=0&&E>=0)y=y.extract({left:Math.floor(S),top:Math.floor(E),width:w,height:g});else if(S<=0&&E<=0){const M=Math.floor(-E),v=Math.floor(-S);y=y.extend({top:M,left:v,right:w-this.width-v,bottom:g-this.height-M})}else{let M=[0,0],v=0;E<0?(M[0]=Math.floor(-E),M[1]=g-this.height-M[0]):v=Math.floor(E);let C=[0,0],A=0;S<0?(C[0]=Math.floor(-S),C[1]=w-this.width-C[0]):A=Math.floor(S),y=y.extend({top:M[0],bottom:M[1],left:C[0],right:C[1]}).extract({left:A,top:v,width:w,height:g})}return await p(y)}}async toBlob(w="image/png",g=1){if(!d)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:w,quality:g})}toTensor(w="CHW"){let g=new i.Tensor("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(w!=="HWC")if(w==="CHW")g=g.permute(2,0,1);else throw new Error(`Unsupported channel format: ${w}`);return g}toCanvas(){if(!d)throw new Error("toCanvas() is only supported in browser environments.");const w=this.clone().rgba(),g=l(w.width,w.height),S=new u(w.data,w.width,w.height);return g.getContext("2d").putImageData(S,0,0),g}split(){const{data:w,width:g,height:S,channels:E}=this,y=w.constructor,M=w.length/E,v=Array.from({length:E},()=>new y(M));for(let C=0;Cnew _(C,g,S,1))}_update(w,g,S,E=null){return this.data=w,this.width=g,this.height=S,E!==null&&(this.channels=E),this}clone(){return new _(this.data.slice(),this.width,this.height,this.channels)}convert(w){if(this.channels===w)return this;switch(w){case 1:this.grayscale();break;case 3:this.rgb();break;case 4:this.rgba();break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this}async save(w){if(d){if(n.apis.IS_WEBWORKER_ENV)throw new Error("Unable to save an image from a Web Worker.");const g=w.split(".").pop().toLowerCase(),S=f.get(g)??"image/png",E=await this.toBlob(S);(0,s.saveBlob)(w,E)}else{if(n.apis.IS_FS_AVAILABLE)return await this.toSharp().toFile(w);throw new Error("Unable to save the image because filesystem is disabled in this environment.")}}toSharp(){if(d)throw new Error("toSharp() is only supported in server-side environments.");return a(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}}const T=_.read.bind(_)},"./src/utils/maths.js":(e,r,t)=>{t.r(r),t.d(r,{FFT:()=>T,bankers_round:()=>g,cos_sim:()=>l,dot:()=>a,dynamic_time_warping:()=>S,interpolate_data:()=>s,log_softmax:()=>i,magnitude:()=>u,max:()=>d,medianFilter:()=>k,min:()=>p,permute_data:()=>o,round:()=>w,softmax:()=>n});function s(E,[y,M,v],[C,A],B="bilinear",K=!1){const G=A/v,j=C/M,ee=new E.constructor(C*A*y),H=M*v,Z=C*A;for(let X=0;X=0;--K)C[K]=G,v[K]=y[M[K]],G*=v[K];const A=M.map((K,G)=>C[M.indexOf(G)]),B=new E.constructor(E.length);for(let K=0;K=0;--j)G+=ee%y[j]*A[j],ee=Math.floor(ee/y[j]);B[G]=E[K]}return[B,v]}function n(E){const y=d(E)[0],M=E.map(A=>Math.exp(A-y)),v=M.reduce((A,B)=>A+B,0);return M.map(A=>A/v)}function i(E){const y=d(E)[0];let M=0;for(let A=0;AA-y-v)}function a(E,y){let M=0;for(let v=0;vy+M*M,0))}function p(E){if(E.length===0)throw Error("Array must not be empty");let y=E[0],M=0;for(let v=1;vy&&(y=E[v],M=v);return[y,M]}function c(E){return E>0&&(E&E-1)===0}class f{constructor(y){if(this.size=y|0,this.size<=1||!c(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=y<<1,this.table=new Float64Array(this.size*2);for(let v=0;vv;v<<=1)++M;this._width=M%2===0?M-1:M,this._bitrev=new Int32Array(1<>>C&3)<>>1);for(let C=0;C>>1]=y[C];return v}toComplexArray(y,M){const v=M||this.createComplexArray();for(let C=0;C>>1],v[C+1]=0;return v}transform(y,M){if(y===M)throw new Error("Input and output buffers must be different");this._transform4(y,M,1)}realTransform(y,M){if(y===M)throw new Error("Input and output buffers must be different");this._realTransform4(y,M,1)}inverseTransform(y,M){if(y===M)throw new Error("Input and output buffers must be different");this._transform4(y,M,-1);for(let v=0;v>=2;B>=2;B>>=2){K=C/B<<1;const Z=K>>>2;for(G=0;G>>1,B>>>1)}else for(G=0,j=0;G>>1,B>>>1,v)}const H=this.table;for(B>>=2;B>=2;B>>=2){K=C/B<<1;const X=K>>>1,oe=X>>>1,me=oe>>>1;for(G=0;G>>1;for(let X=2;X>1;++ee){const H=(ee+1-y)**2/2,Z=Math.sqrt(G**2+j**2)**H,X=H*Math.atan2(j,G),oe=2*ee;A[oe]=Z*Math.cos(X),A[oe+1]=Z*Math.sin(X),B[oe]=A[oe],B[oe+1]=-A[oe+1]}this._slicedChirpBuffer=A.subarray(M,v),this._f=new f(C>>1),this._f.transform(this._chirpBuffer,B)}_transform(y,M,v){const C=this._buffer1,A=this._buffer2,B=this._outBuffer1,K=this._outBuffer2,G=this._chirpBuffer,j=this._slicedChirpBuffer,ee=this._a;if(v)for(let H=0;H>1,oe=M[X];C[H]=oe*j[H],C[Z]=oe*j[Z]}else for(let H=0;H=E.length&&(G=2*(E.length-1)-G),v[B++]=E[G]}v.sort(),M[A]=v[C]}return M}function w(E,y){const M=Math.pow(10,y);return Math.round(E*M)/M}function g(E){const y=Math.round(E);return Math.abs(E)%1===.5?y%2===0?y:y-1:y}function S(E){const y=E.length,M=E[0].length,v=[y+1,M+1],C=Array.from({length:v[0]},()=>Array(v[1]).fill(1/0));C[0][0]=0;const A=Array.from({length:v[0]},()=>Array(v[1]).fill(-1));for(let ee=1;ee0||K>0;)switch(G.push(B-1),j.push(K-1),A[B][K]){case 0:--B,--K;break;case 1:--B;break;case 2:--K;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${B}, ${K}]. Please file a bug report.`)}return G.reverse(),j.reverse(),[G,j]}},"./src/utils/tensor.js":(e,r,t)=>{t.r(r),t.d(r,{DataTypeMap:()=>i,Tensor:()=>a,cat:()=>M,full:()=>j,full_like:()=>ee,interpolate:()=>p,interpolate_4d:()=>d,layer_norm:()=>g,matmul:()=>c,mean:()=>B,mean_pooling:()=>w,ones:()=>H,ones_like:()=>Z,permute:()=>u,quantize_embeddings:()=>ae,rand:()=>me,rfft:()=>f,slice:()=>k,stack:()=>v,std_mean:()=>A,topk:()=>_,zeros:()=>X,zeros_like:()=>oe});var s=t("./src/utils/maths.js"),o=t("./src/backends/onnx.js"),n=t("./src/ops/registry.js");const i=Object.freeze({float32:Float32Array,float16:typeof Float16Array<"u"?Float16Array:Uint16Array,float64:Float64Array,string:Array,int8:Int8Array,uint8:Uint8Array,int16:Int16Array,uint16:Uint16Array,int32:Int32Array,uint32:Uint32Array,int64:BigInt64Array,uint64:BigUint64Array,bool:Uint8Array,uint4:Uint8Array,int4:Int8Array});class a{constructor(...F){te(this,"ort_tensor");return(0,o.isONNXTensor)(F[0])?this.ort_tensor=F[0]:this.ort_tensor=new o.Tensor(F[0],F[1],F[2]),new Proxy(this,{get:(W,re)=>{if(typeof re=="string"){let _e=Number(re);if(Number.isInteger(_e))return W._getitem(_e)}return W[re]},set:(W,re,_e)=>W[re]=_e})}get dims(){return this.ort_tensor.dims}set dims(F){this.ort_tensor.dims=F}get type(){return this.ort_tensor.type}get data(){return this.ort_tensor.data}get size(){return this.ort_tensor.size}get location(){return this.ort_tensor.location}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){const[F,...W]=this.dims;if(W.length>0){const re=W.reduce((_e,se)=>_e*se);for(let _e=0;_e0){const _e=re.reduce((se,ce)=>se*ce);return this._subarray(F,_e,re)}else return new a(this.type,[this.data[F]],re)}indexOf(F){const W=this.data;for(let re=0;repe)throw new Error(`Invalid slice: ${q}`);const xe=[Math.max(R,0),Math.min(pe,this.dims[we])];re.push(xe),W.push(xe[1]-xe[0])}else throw new Error(`Invalid slice: ${q}`)}const _e=re.map(([we,q])=>q-we),se=_e.reduce((we,q)=>we*q),ce=this.data,$e=new ce.constructor(se),Ue=this.stride();for(let we=0;we=0;--R){const xe=_e[R];q+=(pe%xe+re[R][0])*Ue[R],pe=Math.floor(pe/xe)}$e[we]=ce[q]}return new a(this.type,$e,W)}permute(...F){return u(this,F)}transpose(...F){return this.permute(...F)}sum(F=null,W=!1){return this.norm(1,F,W)}norm(F="fro",W=null,re=!1){if(F==="fro")F=2;else if(typeof F=="string")throw Error(`Unsupported norm: ${F}`);const _e=this.data,se=(we,q)=>we+q**F;if(W===null){const we=_e.reduce(se,0)**(1/F);return new a(this.type,[we],[])}const[ce,$e,Ue]=C(se,this,W,re);if(F!==1)for(let we=0;we<$e.length;++we)$e[we]=$e[we]**(1/F);return new a(ce,$e,Ue)}normalize_(F=2,W=1){W=y(W,this.dims.length);const re=this.norm(F,W,!0),_e=this.data,se=re.data;for(let ce=0;ce<_e.length;++ce){let $e=0;for(let Ue=this.dims.length-1,we=ce,q=1;Ue>=0;--Ue){const R=this.dims[Ue];if(Ue!==W){const pe=we%R;$e+=pe*q,q*=this.dims[Ue]}we=Math.floor(we/R)}_e[ce]/=se[$e]}return this}normalize(F=2,W=1){return this.clone().normalize_(F,W)}stride(){return K(this.dims)}squeeze(F=null){return new a(this.type,this.data,S(this.dims,F))}squeeze_(F=null){return this.dims=S(this.dims,F),this}unsqueeze(F=null){return new a(this.type,this.data,E(this.dims,F))}unsqueeze_(F=null){return this.dims=E(this.dims,F),this}flatten_(F=0,W=-1){W=(W+this.dims.length)%this.dims.length;let re=this.dims.slice(0,F),_e=this.dims.slice(F,W+1),se=this.dims.slice(W+1);return this.dims=[...re,_e.reduce((ce,$e)=>ce*$e,1),...se],this}flatten(F=0,W=-1){return this.clone().flatten_(F,W)}view(...F){let W=-1;for(let _e=0;_e$e!==W?se*ce:se,1);F[W]=re.length/_e}return new a(this.type,re,F)}neg_(){const F=this.data;for(let W=0;WF?1:0;return new a("bool",W,this.dims)}lt(F){const W=new Uint8Array(this.data.length),re=this.data;for(let _e=0;_eMath.min(ce,$e),this,F,W,1/0);return new a(re,_e,se)}max(F=null,W=!1){if(F===null){const ce=(0,s.max)(this.data)[0];return new a(this.type,[ce],[])}const[re,_e,se]=C((ce,$e)=>Math.max(ce,$e),this,F,W,-1/0);return new a(re,_e,se)}argmin(F=null,W=!1){if(F!==null)throw new Error("`dim !== null` not yet implemented.");const re=(0,s.min)(this.data)[1];return new a("int64",[BigInt(re)],[])}argmax(F=null,W=!1){if(F!==null)throw new Error("`dim !== null` not yet implemented.");const re=(0,s.max)(this.data)[1];return new a("int64",[BigInt(re)],[])}to(F){if(this.type===F)return this;if(!i.hasOwnProperty(F))throw new Error(`Unsupported type: ${F}`);let W;const re=["int64","uint64"].includes(this.type),_e=["int64","uint64"].includes(F);return re&&!_e?W=Number:!re&&_e&&(W=BigInt),new a(F,i[F].from(this.data,W),this.dims)}}function l(V,F){const W=V.length,re=F.reduce((se,ce)=>se*ce);if(W!==re)throw Error(`cannot reshape array of size ${W} into shape (${F})`);let _e=V;for(let se=F.length-1;se>=0;se--)_e=_e.reduce((ce,$e)=>{let Ue=ce[ce.length-1];return Ue.lengthnew a("int64",V,[V.length]);async function k(V,F,W,re,_e){return await(await n.TensorOpRegistry.slice)({x:V,s:T(F),e:T(W),a:T(re),t:T(_e??new Array(re.length).fill(1))})}function w(V,F){const W=V.data,re=F.data,_e=[V.dims[0],V.dims[2]],se=new W.constructor(_e[0]*_e[1]),[ce,$e,Ue]=V.dims;let we=0;for(let q=0;qW!==1):typeof F=="number"?V[F]===1&&V.splice(F,1):Array.isArray(F)&&(V=V.filter((W,re)=>W!==1||!F.includes(re))),V}function E(V,F){return F=y(F,V.length+1),V=V.slice(),V.splice(F,0,1),V}function y(V,F,W=null,re=!0){if(V<-F||V>=F){if(re)throw new Error(`IndexError: index ${V} is out of bounds for dimension${W===null?"":" "+W} with size ${F}`);return V<-F?0:F}return V<0&&(V=(V%F+F)%F),V}function M(V,F=0){F=y(F,V[0].dims.length);const W=V[0].dims.slice();W[F]=V.reduce((ce,$e)=>ce+$e.dims[F],0);const re=W.reduce((ce,$e)=>ce*$e,1),_e=new V[0].data.constructor(re),se=V[0].type;if(F===0){let ce=0;for(const $e of V){const Ue=$e.data;_e.set(Ue,ce),ce+=Ue.length}}else{let ce=0;for(let $e=0;$e=0;--pe){const Se=we[pe];let Ae=xe%Se;pe===F&&(Ae+=ce),R+=Ae*be,be*=W[pe],xe=Math.floor(xe/Se)}_e[R]=Ue[q]}ce+=we[F]}}return new a(se,_e,W)}function v(V,F=0){return M(V.map(W=>W.unsqueeze(F)),F)}function C(V,F,W=null,re=!1,_e=null){const se=F.data,ce=F.dims;W=y(W,ce.length);const $e=ce.slice();$e[W]=1;const Ue=new se.constructor(se.length/ce[W]);_e!==null&&Ue.fill(_e);for(let we=0;we=0;--R){const be=ce[R];if(R!==W){const Se=pe%be;q+=Se*xe,xe*=$e[R]}pe=Math.floor(pe/be)}Ue[q]=V(Ue[q],se[we],we,q)}return re||$e.splice(W,1),[F.type,Ue,$e]}function A(V,F=null,W=1,re=!1){const _e=V.data,se=V.dims;if(F===null){const xe=_e.reduce((Fe,ze)=>Fe+ze,0)/_e.length,be=Math.sqrt(_e.reduce((Fe,ze)=>Fe+(ze-xe)**2,0)/(_e.length-W)),Se=new a(V.type,[xe],[]);return[new a(V.type,[be],[]),Se]}F=y(F,se.length);const ce=B(V,F,re),$e=ce.data,[Ue,we,q]=C((pe,xe,be,Se)=>pe+(xe-$e[Se])**2,V,F,re);for(let pe=0;pewe+q,0);return new a(V.type,[Ue/_e.length],[])}F=y(F,re.length);const[se,ce,$e]=C((Ue,we)=>Ue+we,V,F,W);if(re[F]!==1)for(let Ue=0;Ue=0;--W)F[W]=re,re*=V[W];return F}function G(V,F,W,re){const _e=V.reduce((se,ce)=>se*ce,1);return new a(W,new re(_e).fill(F),V)}function j(V,F){let W,re;if(typeof F=="number")W="float32",re=Float32Array;else if(typeof F=="bigint")W="int64",re=BigInt64Array;else if(typeof F=="boolean")W="bool",re=Uint8Array;else throw new Error(`Unsupported data type: ${typeof F}`);return G(V,F,W,re)}function ee(V,F){return j(V.dims,F)}function H(V){return G(V,1n,"int64",BigInt64Array)}function Z(V){return H(V.dims)}function X(V){return G(V,0n,"int64",BigInt64Array)}function oe(V){return X(V.dims)}function me(V){const F=V.reduce((W,re)=>W*re,1);return new a("float32",Float32Array.from({length:F},()=>Math.random()),V)}function ae(V,F){if(V.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(V.dims.at(-1)%8!==0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(F))throw new Error("The precision must be either 'binary' or 'ubinary'");const W=F==="binary",re=W?"int8":"uint8",_e=W?Int8Array:Uint8Array,se=V.data,ce=new _e(se.length/8);for(let $e=0;$e0?1:0,we=Math.floor($e/8),q=$e%8;ce[we]|=Ue<<7-q,W&&q===0&&(ce[we]-=128)}return new a(re,ce,[V.dims[0],V.dims[1]/8])}},"./src/utils/video.js":(e,r,t)=>{t.r(r),t.d(r,{RawVideo:()=>i,RawVideoFrame:()=>n,load_video:()=>a});var s=t("./src/utils/image.js"),o=t("./src/env.js");class n{constructor(u,p){this.image=u,this.timestamp=p}}class i{constructor(u,p){u.length>0&&u[0]instanceof s.RawImage&&(u=u.map((d,c)=>new n(d,(c+1)/(u.length+1)*p))),this.frames=u,this.duration=p}get width(){return this.frames[0].image.width}get height(){return this.frames[0].image.height}get fps(){return this.frames.length/this.duration}}async function a(l,{num_frames:u=null,fps:p=null}={}){if(!o.apis.IS_BROWSER_ENV)throw new Error("`load_video` is currently only supported in browser environments.");if(u==null&&p==null)throw new Error("Either num_frames or fps must be provided.");const d=[],c=document.createElement("video");if(c.crossOrigin="anonymous",c.muted=!0,typeof l=="string")c.src=l;else if(l instanceof Blob)c.src=URL.createObjectURL(l);else if(l instanceof HTMLVideoElement)c.src=l.src;else throw new Error("Invalid URL or video element provided.");if(await new Promise(S=>c.onloadedmetadata=S),c.seekable.start(0)===c.seekable.end(0)){const E=await(await fetch(c.src)).blob();c.src=URL.createObjectURL(E),await new Promise(y=>c.onloadedmetadata=y)}const f=c.duration;let _,T;u!=null?(_=u,T=u===1?0:f/(u-1)):(T=1/p,_=Math.floor(f/T));let k=[];for(let S=0;S<_;++S)k.push(u===1?f/2:S*T);const w=document.createElement("canvas");w.width=c.videoWidth,w.height=c.videoHeight;const g=w.getContext("2d",{willReadFrequently:!0});for(const S of k){c.currentTime=S,await new Promise(v=>{c.onseeked=v}),g.drawImage(c,0,0,w.width,w.height);const E=g.getImageData(0,0,w.width,w.height),y=new s.RawImage(E.data,w.width,w.height,4),M=new n(y,S);d.push(M)}return c.remove(),new i(d,f)}}},Ng={};function $t(e){var r=Ng[e];if(r!==void 0)return r.exports;var t=Ng[e]={exports:{}};return bx[e](t,t.exports,$t),t.exports}(()=>{var e=Object.getPrototypeOf?t=>Object.getPrototypeOf(t):t=>t.__proto__,r;$t.t=function(t,s){if(s&1&&(t=this(t)),s&8||typeof t=="object"&&t&&(s&4&&t.__esModule||s&16&&typeof t.then=="function"))return t;var o=Object.create(null);$t.r(o);var n={};r=r||[null,e({}),e([]),e(e)];for(var i=s&2&&t;typeof i=="object"&&!~r.indexOf(i);i=e(i))Object.getOwnPropertyNames(i).forEach(a=>n[a]=()=>t[a]);return n.default=()=>t,$t.d(o,n),o}})(),$t.d=(e,r)=>{for(var t in r)$t.o(r,t)&&!$t.o(e,t)&&Object.defineProperty(e,t,{enumerable:!0,get:r[t]})},$t.o=(e,r)=>Object.prototype.hasOwnProperty.call(e,r),$t.r=e=>{typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var m={};(()=>{/*!*****************************!*\ + !*** ./src/transformers.js ***! + \*****************************/$t.r(m),$t.d(m,{ASTFeatureExtractor:()=>d.ASTFeatureExtractor,ASTForAudioClassification:()=>t.ASTForAudioClassification,ASTModel:()=>t.ASTModel,ASTPreTrainedModel:()=>t.ASTPreTrainedModel,AlbertForMaskedLM:()=>t.AlbertForMaskedLM,AlbertForQuestionAnswering:()=>t.AlbertForQuestionAnswering,AlbertForSequenceClassification:()=>t.AlbertForSequenceClassification,AlbertModel:()=>t.AlbertModel,AlbertPreTrainedModel:()=>t.AlbertPreTrainedModel,AlbertTokenizer:()=>s.AlbertTokenizer,AudioClassificationPipeline:()=>r.AudioClassificationPipeline,AutoConfig:()=>o.AutoConfig,AutoFeatureExtractor:()=>c.AutoFeatureExtractor,AutoImageProcessor:()=>T.AutoImageProcessor,AutoModel:()=>t.AutoModel,AutoModelForAudioClassification:()=>t.AutoModelForAudioClassification,AutoModelForAudioFrameClassification:()=>t.AutoModelForAudioFrameClassification,AutoModelForAudioTextToText:()=>t.AutoModelForAudioTextToText,AutoModelForCTC:()=>t.AutoModelForCTC,AutoModelForCausalLM:()=>t.AutoModelForCausalLM,AutoModelForDepthEstimation:()=>t.AutoModelForDepthEstimation,AutoModelForDocumentQuestionAnswering:()=>t.AutoModelForDocumentQuestionAnswering,AutoModelForImageClassification:()=>t.AutoModelForImageClassification,AutoModelForImageFeatureExtraction:()=>t.AutoModelForImageFeatureExtraction,AutoModelForImageMatting:()=>t.AutoModelForImageMatting,AutoModelForImageSegmentation:()=>t.AutoModelForImageSegmentation,AutoModelForImageTextToText:()=>t.AutoModelForImageTextToText,AutoModelForImageToImage:()=>t.AutoModelForImageToImage,AutoModelForMaskGeneration:()=>t.AutoModelForMaskGeneration,AutoModelForMaskedLM:()=>t.AutoModelForMaskedLM,AutoModelForNormalEstimation:()=>t.AutoModelForNormalEstimation,AutoModelForObjectDetection:()=>t.AutoModelForObjectDetection,AutoModelForPoseEstimation:()=>t.AutoModelForPoseEstimation,AutoModelForQuestionAnswering:()=>t.AutoModelForQuestionAnswering,AutoModelForSemanticSegmentation:()=>t.AutoModelForSemanticSegmentation,AutoModelForSeq2SeqLM:()=>t.AutoModelForSeq2SeqLM,AutoModelForSequenceClassification:()=>t.AutoModelForSequenceClassification,AutoModelForSpeechSeq2Seq:()=>t.AutoModelForSpeechSeq2Seq,AutoModelForTextToSpectrogram:()=>t.AutoModelForTextToSpectrogram,AutoModelForTextToWaveform:()=>t.AutoModelForTextToWaveform,AutoModelForTokenClassification:()=>t.AutoModelForTokenClassification,AutoModelForUniversalSegmentation:()=>t.AutoModelForUniversalSegmentation,AutoModelForVision2Seq:()=>t.AutoModelForVision2Seq,AutoModelForXVector:()=>t.AutoModelForXVector,AutoModelForZeroShotObjectDetection:()=>t.AutoModelForZeroShotObjectDetection,AutoProcessor:()=>g.AutoProcessor,AutoTokenizer:()=>s.AutoTokenizer,AutomaticSpeechRecognitionPipeline:()=>r.AutomaticSpeechRecognitionPipeline,BackgroundRemovalPipeline:()=>r.BackgroundRemovalPipeline,BartForConditionalGeneration:()=>t.BartForConditionalGeneration,BartForSequenceClassification:()=>t.BartForSequenceClassification,BartModel:()=>t.BartModel,BartPretrainedModel:()=>t.BartPretrainedModel,BartTokenizer:()=>s.BartTokenizer,BaseModelOutput:()=>t.BaseModelOutput,BaseStreamer:()=>S.BaseStreamer,BeitFeatureExtractor:()=>_.BeitFeatureExtractor,BeitForImageClassification:()=>t.BeitForImageClassification,BeitModel:()=>t.BeitModel,BeitPreTrainedModel:()=>t.BeitPreTrainedModel,BertForMaskedLM:()=>t.BertForMaskedLM,BertForQuestionAnswering:()=>t.BertForQuestionAnswering,BertForSequenceClassification:()=>t.BertForSequenceClassification,BertForTokenClassification:()=>t.BertForTokenClassification,BertModel:()=>t.BertModel,BertPreTrainedModel:()=>t.BertPreTrainedModel,BertTokenizer:()=>s.BertTokenizer,BitImageProcessor:()=>_.BitImageProcessor,BlenderbotForConditionalGeneration:()=>t.BlenderbotForConditionalGeneration,BlenderbotModel:()=>t.BlenderbotModel,BlenderbotPreTrainedModel:()=>t.BlenderbotPreTrainedModel,BlenderbotSmallForConditionalGeneration:()=>t.BlenderbotSmallForConditionalGeneration,BlenderbotSmallModel:()=>t.BlenderbotSmallModel,BlenderbotSmallPreTrainedModel:()=>t.BlenderbotSmallPreTrainedModel,BlenderbotSmallTokenizer:()=>s.BlenderbotSmallTokenizer,BlenderbotTokenizer:()=>s.BlenderbotTokenizer,BloomForCausalLM:()=>t.BloomForCausalLM,BloomModel:()=>t.BloomModel,BloomPreTrainedModel:()=>t.BloomPreTrainedModel,BloomTokenizer:()=>s.BloomTokenizer,CLIPFeatureExtractor:()=>_.CLIPFeatureExtractor,CLIPImageProcessor:()=>_.CLIPImageProcessor,CLIPModel:()=>t.CLIPModel,CLIPPreTrainedModel:()=>t.CLIPPreTrainedModel,CLIPSegForImageSegmentation:()=>t.CLIPSegForImageSegmentation,CLIPSegModel:()=>t.CLIPSegModel,CLIPSegPreTrainedModel:()=>t.CLIPSegPreTrainedModel,CLIPTextModel:()=>t.CLIPTextModel,CLIPTextModelWithProjection:()=>t.CLIPTextModelWithProjection,CLIPTokenizer:()=>s.CLIPTokenizer,CLIPVisionModel:()=>t.CLIPVisionModel,CLIPVisionModelWithProjection:()=>t.CLIPVisionModelWithProjection,CamembertForMaskedLM:()=>t.CamembertForMaskedLM,CamembertForQuestionAnswering:()=>t.CamembertForQuestionAnswering,CamembertForSequenceClassification:()=>t.CamembertForSequenceClassification,CamembertForTokenClassification:()=>t.CamembertForTokenClassification,CamembertModel:()=>t.CamembertModel,CamembertPreTrainedModel:()=>t.CamembertPreTrainedModel,CamembertTokenizer:()=>s.CamembertTokenizer,CausalLMOutput:()=>t.CausalLMOutput,CausalLMOutputWithPast:()=>t.CausalLMOutputWithPast,ChineseCLIPFeatureExtractor:()=>_.ChineseCLIPFeatureExtractor,ChineseCLIPModel:()=>t.ChineseCLIPModel,ChineseCLIPPreTrainedModel:()=>t.ChineseCLIPPreTrainedModel,ClapAudioModelWithProjection:()=>t.ClapAudioModelWithProjection,ClapFeatureExtractor:()=>d.ClapFeatureExtractor,ClapModel:()=>t.ClapModel,ClapPreTrainedModel:()=>t.ClapPreTrainedModel,ClapTextModelWithProjection:()=>t.ClapTextModelWithProjection,ClassifierFreeGuidanceLogitsProcessor:()=>y.ClassifierFreeGuidanceLogitsProcessor,CodeGenForCausalLM:()=>t.CodeGenForCausalLM,CodeGenModel:()=>t.CodeGenModel,CodeGenPreTrainedModel:()=>t.CodeGenPreTrainedModel,CodeGenTokenizer:()=>s.CodeGenTokenizer,CodeLlamaTokenizer:()=>s.CodeLlamaTokenizer,CohereForCausalLM:()=>t.CohereForCausalLM,CohereModel:()=>t.CohereModel,CoherePreTrainedModel:()=>t.CoherePreTrainedModel,CohereTokenizer:()=>s.CohereTokenizer,ConvBertForMaskedLM:()=>t.ConvBertForMaskedLM,ConvBertForQuestionAnswering:()=>t.ConvBertForQuestionAnswering,ConvBertForSequenceClassification:()=>t.ConvBertForSequenceClassification,ConvBertForTokenClassification:()=>t.ConvBertForTokenClassification,ConvBertModel:()=>t.ConvBertModel,ConvBertPreTrainedModel:()=>t.ConvBertPreTrainedModel,ConvBertTokenizer:()=>s.ConvBertTokenizer,ConvNextFeatureExtractor:()=>_.ConvNextFeatureExtractor,ConvNextForImageClassification:()=>t.ConvNextForImageClassification,ConvNextImageProcessor:()=>_.ConvNextImageProcessor,ConvNextModel:()=>t.ConvNextModel,ConvNextPreTrainedModel:()=>t.ConvNextPreTrainedModel,ConvNextV2ForImageClassification:()=>t.ConvNextV2ForImageClassification,ConvNextV2Model:()=>t.ConvNextV2Model,ConvNextV2PreTrainedModel:()=>t.ConvNextV2PreTrainedModel,DPTFeatureExtractor:()=>_.DPTFeatureExtractor,DPTForDepthEstimation:()=>t.DPTForDepthEstimation,DPTImageProcessor:()=>_.DPTImageProcessor,DPTModel:()=>t.DPTModel,DPTPreTrainedModel:()=>t.DPTPreTrainedModel,DacDecoderModel:()=>t.DacDecoderModel,DacDecoderOutput:()=>t.DacDecoderOutput,DacEncoderModel:()=>t.DacEncoderModel,DacEncoderOutput:()=>t.DacEncoderOutput,DacFeatureExtractor:()=>d.DacFeatureExtractor,DacModel:()=>t.DacModel,DacPreTrainedModel:()=>t.DacPreTrainedModel,DataTypeMap:()=>l.DataTypeMap,DebertaForMaskedLM:()=>t.DebertaForMaskedLM,DebertaForQuestionAnswering:()=>t.DebertaForQuestionAnswering,DebertaForSequenceClassification:()=>t.DebertaForSequenceClassification,DebertaForTokenClassification:()=>t.DebertaForTokenClassification,DebertaModel:()=>t.DebertaModel,DebertaPreTrainedModel:()=>t.DebertaPreTrainedModel,DebertaTokenizer:()=>s.DebertaTokenizer,DebertaV2ForMaskedLM:()=>t.DebertaV2ForMaskedLM,DebertaV2ForQuestionAnswering:()=>t.DebertaV2ForQuestionAnswering,DebertaV2ForSequenceClassification:()=>t.DebertaV2ForSequenceClassification,DebertaV2ForTokenClassification:()=>t.DebertaV2ForTokenClassification,DebertaV2Model:()=>t.DebertaV2Model,DebertaV2PreTrainedModel:()=>t.DebertaV2PreTrainedModel,DebertaV2Tokenizer:()=>s.DebertaV2Tokenizer,DecisionTransformerModel:()=>t.DecisionTransformerModel,DecisionTransformerPreTrainedModel:()=>t.DecisionTransformerPreTrainedModel,DeiTFeatureExtractor:()=>_.DeiTFeatureExtractor,DeiTForImageClassification:()=>t.DeiTForImageClassification,DeiTImageProcessor:()=>_.DeiTImageProcessor,DeiTModel:()=>t.DeiTModel,DeiTPreTrainedModel:()=>t.DeiTPreTrainedModel,DepthAnythingForDepthEstimation:()=>t.DepthAnythingForDepthEstimation,DepthAnythingPreTrainedModel:()=>t.DepthAnythingPreTrainedModel,DepthEstimationPipeline:()=>r.DepthEstimationPipeline,DepthProForDepthEstimation:()=>t.DepthProForDepthEstimation,DepthProPreTrainedModel:()=>t.DepthProPreTrainedModel,DetrFeatureExtractor:()=>_.DetrFeatureExtractor,DetrForObjectDetection:()=>t.DetrForObjectDetection,DetrForSegmentation:()=>t.DetrForSegmentation,DetrImageProcessor:()=>_.DetrImageProcessor,DetrModel:()=>t.DetrModel,DetrObjectDetectionOutput:()=>t.DetrObjectDetectionOutput,DetrPreTrainedModel:()=>t.DetrPreTrainedModel,DetrSegmentationOutput:()=>t.DetrSegmentationOutput,Dinov2ForImageClassification:()=>t.Dinov2ForImageClassification,Dinov2Model:()=>t.Dinov2Model,Dinov2PreTrainedModel:()=>t.Dinov2PreTrainedModel,Dinov2WithRegistersForImageClassification:()=>t.Dinov2WithRegistersForImageClassification,Dinov2WithRegistersModel:()=>t.Dinov2WithRegistersModel,Dinov2WithRegistersPreTrainedModel:()=>t.Dinov2WithRegistersPreTrainedModel,DistilBertForMaskedLM:()=>t.DistilBertForMaskedLM,DistilBertForQuestionAnswering:()=>t.DistilBertForQuestionAnswering,DistilBertForSequenceClassification:()=>t.DistilBertForSequenceClassification,DistilBertForTokenClassification:()=>t.DistilBertForTokenClassification,DistilBertModel:()=>t.DistilBertModel,DistilBertPreTrainedModel:()=>t.DistilBertPreTrainedModel,DistilBertTokenizer:()=>s.DistilBertTokenizer,DocumentQuestionAnsweringPipeline:()=>r.DocumentQuestionAnsweringPipeline,DonutFeatureExtractor:()=>_.DonutFeatureExtractor,DonutImageProcessor:()=>_.DonutImageProcessor,DonutSwinModel:()=>t.DonutSwinModel,DonutSwinPreTrainedModel:()=>t.DonutSwinPreTrainedModel,EfficientNetForImageClassification:()=>t.EfficientNetForImageClassification,EfficientNetImageProcessor:()=>_.EfficientNetImageProcessor,EfficientNetModel:()=>t.EfficientNetModel,EfficientNetPreTrainedModel:()=>t.EfficientNetPreTrainedModel,ElectraForMaskedLM:()=>t.ElectraForMaskedLM,ElectraForQuestionAnswering:()=>t.ElectraForQuestionAnswering,ElectraForSequenceClassification:()=>t.ElectraForSequenceClassification,ElectraForTokenClassification:()=>t.ElectraForTokenClassification,ElectraModel:()=>t.ElectraModel,ElectraPreTrainedModel:()=>t.ElectraPreTrainedModel,ElectraTokenizer:()=>s.ElectraTokenizer,EncodecFeatureExtractor:()=>d.EncodecFeatureExtractor,EosTokenCriteria:()=>E.EosTokenCriteria,EsmForMaskedLM:()=>t.EsmForMaskedLM,EsmForSequenceClassification:()=>t.EsmForSequenceClassification,EsmForTokenClassification:()=>t.EsmForTokenClassification,EsmModel:()=>t.EsmModel,EsmPreTrainedModel:()=>t.EsmPreTrainedModel,EsmTokenizer:()=>s.EsmTokenizer,ExaoneForCausalLM:()=>t.ExaoneForCausalLM,ExaoneModel:()=>t.ExaoneModel,ExaonePreTrainedModel:()=>t.ExaonePreTrainedModel,FFT:()=>u.FFT,FalconForCausalLM:()=>t.FalconForCausalLM,FalconModel:()=>t.FalconModel,FalconPreTrainedModel:()=>t.FalconPreTrainedModel,FalconTokenizer:()=>s.FalconTokenizer,FastViTForImageClassification:()=>t.FastViTForImageClassification,FastViTModel:()=>t.FastViTModel,FastViTPreTrainedModel:()=>t.FastViTPreTrainedModel,FeatureExtractionPipeline:()=>r.FeatureExtractionPipeline,FeatureExtractor:()=>p.FeatureExtractor,FillMaskPipeline:()=>r.FillMaskPipeline,Florence2ForConditionalGeneration:()=>t.Florence2ForConditionalGeneration,Florence2PreTrainedModel:()=>t.Florence2PreTrainedModel,Florence2Processor:()=>w.Florence2Processor,ForcedBOSTokenLogitsProcessor:()=>y.ForcedBOSTokenLogitsProcessor,ForcedEOSTokenLogitsProcessor:()=>y.ForcedEOSTokenLogitsProcessor,GLPNFeatureExtractor:()=>_.GLPNFeatureExtractor,GLPNForDepthEstimation:()=>t.GLPNForDepthEstimation,GLPNModel:()=>t.GLPNModel,GLPNPreTrainedModel:()=>t.GLPNPreTrainedModel,GPT2LMHeadModel:()=>t.GPT2LMHeadModel,GPT2Model:()=>t.GPT2Model,GPT2PreTrainedModel:()=>t.GPT2PreTrainedModel,GPT2Tokenizer:()=>s.GPT2Tokenizer,GPTBigCodeForCausalLM:()=>t.GPTBigCodeForCausalLM,GPTBigCodeModel:()=>t.GPTBigCodeModel,GPTBigCodePreTrainedModel:()=>t.GPTBigCodePreTrainedModel,GPTJForCausalLM:()=>t.GPTJForCausalLM,GPTJModel:()=>t.GPTJModel,GPTJPreTrainedModel:()=>t.GPTJPreTrainedModel,GPTNeoForCausalLM:()=>t.GPTNeoForCausalLM,GPTNeoModel:()=>t.GPTNeoModel,GPTNeoPreTrainedModel:()=>t.GPTNeoPreTrainedModel,GPTNeoXForCausalLM:()=>t.GPTNeoXForCausalLM,GPTNeoXModel:()=>t.GPTNeoXModel,GPTNeoXPreTrainedModel:()=>t.GPTNeoXPreTrainedModel,GPTNeoXTokenizer:()=>s.GPTNeoXTokenizer,Gemma2ForCausalLM:()=>t.Gemma2ForCausalLM,Gemma2Model:()=>t.Gemma2Model,Gemma2PreTrainedModel:()=>t.Gemma2PreTrainedModel,Gemma3ForCausalLM:()=>t.Gemma3ForCausalLM,Gemma3Model:()=>t.Gemma3Model,Gemma3PreTrainedModel:()=>t.Gemma3PreTrainedModel,GemmaForCausalLM:()=>t.GemmaForCausalLM,GemmaModel:()=>t.GemmaModel,GemmaPreTrainedModel:()=>t.GemmaPreTrainedModel,GemmaTokenizer:()=>s.GemmaTokenizer,GlmForCausalLM:()=>t.GlmForCausalLM,GlmModel:()=>t.GlmModel,GlmPreTrainedModel:()=>t.GlmPreTrainedModel,GraniteForCausalLM:()=>t.GraniteForCausalLM,GraniteModel:()=>t.GraniteModel,GranitePreTrainedModel:()=>t.GranitePreTrainedModel,Grok1Tokenizer:()=>s.Grok1Tokenizer,GroundingDinoForObjectDetection:()=>t.GroundingDinoForObjectDetection,GroundingDinoImageProcessor:()=>_.GroundingDinoImageProcessor,GroundingDinoPreTrainedModel:()=>t.GroundingDinoPreTrainedModel,GroundingDinoProcessor:()=>w.GroundingDinoProcessor,GroupViTModel:()=>t.GroupViTModel,GroupViTPreTrainedModel:()=>t.GroupViTPreTrainedModel,HeliumForCausalLM:()=>t.HeliumForCausalLM,HeliumModel:()=>t.HeliumModel,HeliumPreTrainedModel:()=>t.HeliumPreTrainedModel,HerbertTokenizer:()=>s.HerbertTokenizer,HieraForImageClassification:()=>t.HieraForImageClassification,HieraModel:()=>t.HieraModel,HieraPreTrainedModel:()=>t.HieraPreTrainedModel,HubertForCTC:()=>t.HubertForCTC,HubertForSequenceClassification:()=>t.HubertForSequenceClassification,HubertModel:()=>t.HubertModel,HubertPreTrainedModel:()=>t.HubertPreTrainedModel,IJepaForImageClassification:()=>t.IJepaForImageClassification,IJepaModel:()=>t.IJepaModel,IJepaPreTrainedModel:()=>t.IJepaPreTrainedModel,Idefics3ForConditionalGeneration:()=>t.Idefics3ForConditionalGeneration,Idefics3ImageProcessor:()=>_.Idefics3ImageProcessor,Idefics3PreTrainedModel:()=>t.Idefics3PreTrainedModel,Idefics3Processor:()=>w.Idefics3Processor,ImageClassificationPipeline:()=>r.ImageClassificationPipeline,ImageFeatureExtractionPipeline:()=>r.ImageFeatureExtractionPipeline,ImageFeatureExtractor:()=>d.ImageFeatureExtractor,ImageMattingOutput:()=>t.ImageMattingOutput,ImageProcessor:()=>f.ImageProcessor,ImageSegmentationPipeline:()=>r.ImageSegmentationPipeline,ImageToImagePipeline:()=>r.ImageToImagePipeline,ImageToTextPipeline:()=>r.ImageToTextPipeline,InterruptableStoppingCriteria:()=>E.InterruptableStoppingCriteria,JAISLMHeadModel:()=>t.JAISLMHeadModel,JAISModel:()=>t.JAISModel,JAISPreTrainedModel:()=>t.JAISPreTrainedModel,JinaCLIPImageProcessor:()=>_.JinaCLIPImageProcessor,JinaCLIPModel:()=>t.JinaCLIPModel,JinaCLIPPreTrainedModel:()=>t.JinaCLIPPreTrainedModel,JinaCLIPProcessor:()=>w.JinaCLIPProcessor,JinaCLIPTextModel:()=>t.JinaCLIPTextModel,JinaCLIPVisionModel:()=>t.JinaCLIPVisionModel,LiteWhisperForConditionalGeneration:()=>t.LiteWhisperForConditionalGeneration,LlamaForCausalLM:()=>t.LlamaForCausalLM,LlamaModel:()=>t.LlamaModel,LlamaPreTrainedModel:()=>t.LlamaPreTrainedModel,LlamaTokenizer:()=>s.LlamaTokenizer,LlavaForConditionalGeneration:()=>t.LlavaForConditionalGeneration,LlavaOnevisionForConditionalGeneration:()=>t.LlavaOnevisionForConditionalGeneration,LlavaOnevisionImageProcessor:()=>_.LlavaOnevisionImageProcessor,LlavaPreTrainedModel:()=>t.LlavaPreTrainedModel,LogitsProcessor:()=>y.LogitsProcessor,LogitsProcessorList:()=>y.LogitsProcessorList,LogitsWarper:()=>y.LogitsWarper,LongT5ForConditionalGeneration:()=>t.LongT5ForConditionalGeneration,LongT5Model:()=>t.LongT5Model,LongT5PreTrainedModel:()=>t.LongT5PreTrainedModel,M2M100ForConditionalGeneration:()=>t.M2M100ForConditionalGeneration,M2M100Model:()=>t.M2M100Model,M2M100PreTrainedModel:()=>t.M2M100PreTrainedModel,M2M100Tokenizer:()=>s.M2M100Tokenizer,MBart50Tokenizer:()=>s.MBart50Tokenizer,MBartForCausalLM:()=>t.MBartForCausalLM,MBartForConditionalGeneration:()=>t.MBartForConditionalGeneration,MBartForSequenceClassification:()=>t.MBartForSequenceClassification,MBartModel:()=>t.MBartModel,MBartPreTrainedModel:()=>t.MBartPreTrainedModel,MBartTokenizer:()=>s.MBartTokenizer,MPNetForMaskedLM:()=>t.MPNetForMaskedLM,MPNetForQuestionAnswering:()=>t.MPNetForQuestionAnswering,MPNetForSequenceClassification:()=>t.MPNetForSequenceClassification,MPNetForTokenClassification:()=>t.MPNetForTokenClassification,MPNetModel:()=>t.MPNetModel,MPNetPreTrainedModel:()=>t.MPNetPreTrainedModel,MPNetTokenizer:()=>s.MPNetTokenizer,MT5ForConditionalGeneration:()=>t.MT5ForConditionalGeneration,MT5Model:()=>t.MT5Model,MT5PreTrainedModel:()=>t.MT5PreTrainedModel,MarianMTModel:()=>t.MarianMTModel,MarianModel:()=>t.MarianModel,MarianPreTrainedModel:()=>t.MarianPreTrainedModel,MarianTokenizer:()=>s.MarianTokenizer,Mask2FormerImageProcessor:()=>_.Mask2FormerImageProcessor,MaskFormerFeatureExtractor:()=>_.MaskFormerFeatureExtractor,MaskFormerForInstanceSegmentation:()=>t.MaskFormerForInstanceSegmentation,MaskFormerImageProcessor:()=>_.MaskFormerImageProcessor,MaskFormerModel:()=>t.MaskFormerModel,MaskFormerPreTrainedModel:()=>t.MaskFormerPreTrainedModel,MaskedLMOutput:()=>t.MaskedLMOutput,MaxLengthCriteria:()=>E.MaxLengthCriteria,Metric3DForDepthEstimation:()=>t.Metric3DForDepthEstimation,Metric3DPreTrainedModel:()=>t.Metric3DPreTrainedModel,Metric3Dv2ForDepthEstimation:()=>t.Metric3Dv2ForDepthEstimation,Metric3Dv2PreTrainedModel:()=>t.Metric3Dv2PreTrainedModel,MgpstrForSceneTextRecognition:()=>t.MgpstrForSceneTextRecognition,MgpstrModelOutput:()=>t.MgpstrModelOutput,MgpstrPreTrainedModel:()=>t.MgpstrPreTrainedModel,MgpstrProcessor:()=>w.MgpstrProcessor,MgpstrTokenizer:()=>s.MgpstrTokenizer,MimiDecoderModel:()=>t.MimiDecoderModel,MimiDecoderOutput:()=>t.MimiDecoderOutput,MimiEncoderModel:()=>t.MimiEncoderModel,MimiEncoderOutput:()=>t.MimiEncoderOutput,MimiModel:()=>t.MimiModel,MimiPreTrainedModel:()=>t.MimiPreTrainedModel,MinLengthLogitsProcessor:()=>y.MinLengthLogitsProcessor,MinNewTokensLengthLogitsProcessor:()=>y.MinNewTokensLengthLogitsProcessor,MistralForCausalLM:()=>t.MistralForCausalLM,MistralModel:()=>t.MistralModel,MistralPreTrainedModel:()=>t.MistralPreTrainedModel,MobileBertForMaskedLM:()=>t.MobileBertForMaskedLM,MobileBertForQuestionAnswering:()=>t.MobileBertForQuestionAnswering,MobileBertForSequenceClassification:()=>t.MobileBertForSequenceClassification,MobileBertModel:()=>t.MobileBertModel,MobileBertPreTrainedModel:()=>t.MobileBertPreTrainedModel,MobileBertTokenizer:()=>s.MobileBertTokenizer,MobileLLMForCausalLM:()=>t.MobileLLMForCausalLM,MobileLLMModel:()=>t.MobileLLMModel,MobileLLMPreTrainedModel:()=>t.MobileLLMPreTrainedModel,MobileNetV1FeatureExtractor:()=>_.MobileNetV1FeatureExtractor,MobileNetV1ForImageClassification:()=>t.MobileNetV1ForImageClassification,MobileNetV1ForSemanticSegmentation:()=>t.MobileNetV1ForSemanticSegmentation,MobileNetV1ImageProcessor:()=>_.MobileNetV1ImageProcessor,MobileNetV1Model:()=>t.MobileNetV1Model,MobileNetV1PreTrainedModel:()=>t.MobileNetV1PreTrainedModel,MobileNetV2FeatureExtractor:()=>_.MobileNetV2FeatureExtractor,MobileNetV2ForImageClassification:()=>t.MobileNetV2ForImageClassification,MobileNetV2ForSemanticSegmentation:()=>t.MobileNetV2ForSemanticSegmentation,MobileNetV2ImageProcessor:()=>_.MobileNetV2ImageProcessor,MobileNetV2Model:()=>t.MobileNetV2Model,MobileNetV2PreTrainedModel:()=>t.MobileNetV2PreTrainedModel,MobileNetV3FeatureExtractor:()=>_.MobileNetV3FeatureExtractor,MobileNetV3ForImageClassification:()=>t.MobileNetV3ForImageClassification,MobileNetV3ForSemanticSegmentation:()=>t.MobileNetV3ForSemanticSegmentation,MobileNetV3ImageProcessor:()=>_.MobileNetV3ImageProcessor,MobileNetV3Model:()=>t.MobileNetV3Model,MobileNetV3PreTrainedModel:()=>t.MobileNetV3PreTrainedModel,MobileNetV4FeatureExtractor:()=>_.MobileNetV4FeatureExtractor,MobileNetV4ForImageClassification:()=>t.MobileNetV4ForImageClassification,MobileNetV4ForSemanticSegmentation:()=>t.MobileNetV4ForSemanticSegmentation,MobileNetV4ImageProcessor:()=>_.MobileNetV4ImageProcessor,MobileNetV4Model:()=>t.MobileNetV4Model,MobileNetV4PreTrainedModel:()=>t.MobileNetV4PreTrainedModel,MobileViTFeatureExtractor:()=>_.MobileViTFeatureExtractor,MobileViTForImageClassification:()=>t.MobileViTForImageClassification,MobileViTImageProcessor:()=>_.MobileViTImageProcessor,MobileViTModel:()=>t.MobileViTModel,MobileViTPreTrainedModel:()=>t.MobileViTPreTrainedModel,MobileViTV2ForImageClassification:()=>t.MobileViTV2ForImageClassification,MobileViTV2Model:()=>t.MobileViTV2Model,MobileViTV2PreTrainedModel:()=>t.MobileViTV2PreTrainedModel,ModelOutput:()=>t.ModelOutput,ModernBertForMaskedLM:()=>t.ModernBertForMaskedLM,ModernBertForSequenceClassification:()=>t.ModernBertForSequenceClassification,ModernBertForTokenClassification:()=>t.ModernBertForTokenClassification,ModernBertModel:()=>t.ModernBertModel,ModernBertPreTrainedModel:()=>t.ModernBertPreTrainedModel,Moondream1ForConditionalGeneration:()=>t.Moondream1ForConditionalGeneration,MoonshineFeatureExtractor:()=>d.MoonshineFeatureExtractor,MoonshineForConditionalGeneration:()=>t.MoonshineForConditionalGeneration,MoonshineModel:()=>t.MoonshineModel,MoonshinePreTrainedModel:()=>t.MoonshinePreTrainedModel,MoonshineProcessor:()=>w.MoonshineProcessor,MptForCausalLM:()=>t.MptForCausalLM,MptModel:()=>t.MptModel,MptPreTrainedModel:()=>t.MptPreTrainedModel,MultiModalityCausalLM:()=>t.MultiModalityCausalLM,MultiModalityPreTrainedModel:()=>t.MultiModalityPreTrainedModel,MusicgenForCausalLM:()=>t.MusicgenForCausalLM,MusicgenForConditionalGeneration:()=>t.MusicgenForConditionalGeneration,MusicgenModel:()=>t.MusicgenModel,MusicgenPreTrainedModel:()=>t.MusicgenPreTrainedModel,NllbTokenizer:()=>s.NllbTokenizer,NoBadWordsLogitsProcessor:()=>y.NoBadWordsLogitsProcessor,NoRepeatNGramLogitsProcessor:()=>y.NoRepeatNGramLogitsProcessor,NomicBertModel:()=>t.NomicBertModel,NomicBertPreTrainedModel:()=>t.NomicBertPreTrainedModel,NougatImageProcessor:()=>_.NougatImageProcessor,NougatTokenizer:()=>s.NougatTokenizer,OPTForCausalLM:()=>t.OPTForCausalLM,OPTModel:()=>t.OPTModel,OPTPreTrainedModel:()=>t.OPTPreTrainedModel,ObjectDetectionPipeline:()=>r.ObjectDetectionPipeline,Olmo2ForCausalLM:()=>t.Olmo2ForCausalLM,Olmo2Model:()=>t.Olmo2Model,Olmo2PreTrainedModel:()=>t.Olmo2PreTrainedModel,OlmoForCausalLM:()=>t.OlmoForCausalLM,OlmoModel:()=>t.OlmoModel,OlmoPreTrainedModel:()=>t.OlmoPreTrainedModel,OpenELMForCausalLM:()=>t.OpenELMForCausalLM,OpenELMModel:()=>t.OpenELMModel,OpenELMPreTrainedModel:()=>t.OpenELMPreTrainedModel,OwlViTFeatureExtractor:()=>_.OwlViTFeatureExtractor,OwlViTForObjectDetection:()=>t.OwlViTForObjectDetection,OwlViTImageProcessor:()=>_.OwlViTImageProcessor,OwlViTModel:()=>t.OwlViTModel,OwlViTPreTrainedModel:()=>t.OwlViTPreTrainedModel,OwlViTProcessor:()=>w.OwlViTProcessor,Owlv2ForObjectDetection:()=>t.Owlv2ForObjectDetection,Owlv2ImageProcessor:()=>_.Owlv2ImageProcessor,Owlv2Model:()=>t.Owlv2Model,Owlv2PreTrainedModel:()=>t.Owlv2PreTrainedModel,PaliGemmaForConditionalGeneration:()=>t.PaliGemmaForConditionalGeneration,PaliGemmaPreTrainedModel:()=>t.PaliGemmaPreTrainedModel,PaliGemmaProcessor:()=>w.PaliGemmaProcessor,PatchTSMixerForPrediction:()=>t.PatchTSMixerForPrediction,PatchTSMixerModel:()=>t.PatchTSMixerModel,PatchTSMixerPreTrainedModel:()=>t.PatchTSMixerPreTrainedModel,PatchTSTForPrediction:()=>t.PatchTSTForPrediction,PatchTSTModel:()=>t.PatchTSTModel,PatchTSTPreTrainedModel:()=>t.PatchTSTPreTrainedModel,Phi3ForCausalLM:()=>t.Phi3ForCausalLM,Phi3Model:()=>t.Phi3Model,Phi3PreTrainedModel:()=>t.Phi3PreTrainedModel,Phi3VForCausalLM:()=>t.Phi3VForCausalLM,Phi3VImageProcessor:()=>_.Phi3VImageProcessor,Phi3VPreTrainedModel:()=>t.Phi3VPreTrainedModel,Phi3VProcessor:()=>w.Phi3VProcessor,PhiForCausalLM:()=>t.PhiForCausalLM,PhiModel:()=>t.PhiModel,PhiPreTrainedModel:()=>t.PhiPreTrainedModel,Pipeline:()=>r.Pipeline,PreTrainedModel:()=>t.PreTrainedModel,PreTrainedTokenizer:()=>s.PreTrainedTokenizer,PretrainedConfig:()=>o.PretrainedConfig,PretrainedMixin:()=>t.PretrainedMixin,Processor:()=>k.Processor,PvtForImageClassification:()=>t.PvtForImageClassification,PvtImageProcessor:()=>_.PvtImageProcessor,PvtModel:()=>t.PvtModel,PvtPreTrainedModel:()=>t.PvtPreTrainedModel,PyAnnoteFeatureExtractor:()=>d.PyAnnoteFeatureExtractor,PyAnnoteForAudioFrameClassification:()=>t.PyAnnoteForAudioFrameClassification,PyAnnoteModel:()=>t.PyAnnoteModel,PyAnnotePreTrainedModel:()=>t.PyAnnotePreTrainedModel,PyAnnoteProcessor:()=>w.PyAnnoteProcessor,QuestionAnsweringModelOutput:()=>t.QuestionAnsweringModelOutput,QuestionAnsweringPipeline:()=>r.QuestionAnsweringPipeline,Qwen2ForCausalLM:()=>t.Qwen2ForCausalLM,Qwen2Model:()=>t.Qwen2Model,Qwen2PreTrainedModel:()=>t.Qwen2PreTrainedModel,Qwen2Tokenizer:()=>s.Qwen2Tokenizer,Qwen2VLForConditionalGeneration:()=>t.Qwen2VLForConditionalGeneration,Qwen2VLImageProcessor:()=>_.Qwen2VLImageProcessor,Qwen2VLPreTrainedModel:()=>t.Qwen2VLPreTrainedModel,Qwen2VLProcessor:()=>w.Qwen2VLProcessor,RFDetrForObjectDetection:()=>t.RFDetrForObjectDetection,RFDetrModel:()=>t.RFDetrModel,RFDetrObjectDetectionOutput:()=>t.RFDetrObjectDetectionOutput,RFDetrPreTrainedModel:()=>t.RFDetrPreTrainedModel,RTDetrForObjectDetection:()=>t.RTDetrForObjectDetection,RTDetrImageProcessor:()=>_.RTDetrImageProcessor,RTDetrModel:()=>t.RTDetrModel,RTDetrObjectDetectionOutput:()=>t.RTDetrObjectDetectionOutput,RTDetrPreTrainedModel:()=>t.RTDetrPreTrainedModel,RTDetrV2ForObjectDetection:()=>t.RTDetrV2ForObjectDetection,RTDetrV2Model:()=>t.RTDetrV2Model,RTDetrV2ObjectDetectionOutput:()=>t.RTDetrV2ObjectDetectionOutput,RTDetrV2PreTrainedModel:()=>t.RTDetrV2PreTrainedModel,RawAudio:()=>n.RawAudio,RawImage:()=>i.RawImage,RawVideo:()=>a.RawVideo,RawVideoFrame:()=>a.RawVideoFrame,RepetitionPenaltyLogitsProcessor:()=>y.RepetitionPenaltyLogitsProcessor,ResNetForImageClassification:()=>t.ResNetForImageClassification,ResNetModel:()=>t.ResNetModel,ResNetPreTrainedModel:()=>t.ResNetPreTrainedModel,RoFormerForMaskedLM:()=>t.RoFormerForMaskedLM,RoFormerForQuestionAnswering:()=>t.RoFormerForQuestionAnswering,RoFormerForSequenceClassification:()=>t.RoFormerForSequenceClassification,RoFormerForTokenClassification:()=>t.RoFormerForTokenClassification,RoFormerModel:()=>t.RoFormerModel,RoFormerPreTrainedModel:()=>t.RoFormerPreTrainedModel,RoFormerTokenizer:()=>s.RoFormerTokenizer,RobertaForMaskedLM:()=>t.RobertaForMaskedLM,RobertaForQuestionAnswering:()=>t.RobertaForQuestionAnswering,RobertaForSequenceClassification:()=>t.RobertaForSequenceClassification,RobertaForTokenClassification:()=>t.RobertaForTokenClassification,RobertaModel:()=>t.RobertaModel,RobertaPreTrainedModel:()=>t.RobertaPreTrainedModel,RobertaTokenizer:()=>s.RobertaTokenizer,SamImageProcessor:()=>_.SamImageProcessor,SamImageSegmentationOutput:()=>t.SamImageSegmentationOutput,SamModel:()=>t.SamModel,SamPreTrainedModel:()=>t.SamPreTrainedModel,SamProcessor:()=>w.SamProcessor,SapiensForDepthEstimation:()=>t.SapiensForDepthEstimation,SapiensForNormalEstimation:()=>t.SapiensForNormalEstimation,SapiensForSemanticSegmentation:()=>t.SapiensForSemanticSegmentation,SapiensPreTrainedModel:()=>t.SapiensPreTrainedModel,SeamlessM4TFeatureExtractor:()=>d.SeamlessM4TFeatureExtractor,SegformerFeatureExtractor:()=>_.SegformerFeatureExtractor,SegformerForImageClassification:()=>t.SegformerForImageClassification,SegformerForSemanticSegmentation:()=>t.SegformerForSemanticSegmentation,SegformerImageProcessor:()=>_.SegformerImageProcessor,SegformerModel:()=>t.SegformerModel,SegformerPreTrainedModel:()=>t.SegformerPreTrainedModel,Seq2SeqLMOutput:()=>t.Seq2SeqLMOutput,SequenceClassifierOutput:()=>t.SequenceClassifierOutput,SiglipImageProcessor:()=>_.SiglipImageProcessor,SiglipModel:()=>t.SiglipModel,SiglipPreTrainedModel:()=>t.SiglipPreTrainedModel,SiglipTextModel:()=>t.SiglipTextModel,SiglipTokenizer:()=>s.SiglipTokenizer,SiglipVisionModel:()=>t.SiglipVisionModel,SmolVLMForConditionalGeneration:()=>t.SmolVLMForConditionalGeneration,SmolVLMImageProcessor:()=>_.SmolVLMImageProcessor,SmolVLMProcessor:()=>w.SmolVLMProcessor,SnacDecoderModel:()=>t.SnacDecoderModel,SnacEncoderModel:()=>t.SnacEncoderModel,SnacFeatureExtractor:()=>d.SnacFeatureExtractor,SnacModel:()=>t.SnacModel,SnacPreTrainedModel:()=>t.SnacPreTrainedModel,SpeechT5FeatureExtractor:()=>d.SpeechT5FeatureExtractor,SpeechT5ForSpeechToText:()=>t.SpeechT5ForSpeechToText,SpeechT5ForTextToSpeech:()=>t.SpeechT5ForTextToSpeech,SpeechT5HifiGan:()=>t.SpeechT5HifiGan,SpeechT5Model:()=>t.SpeechT5Model,SpeechT5PreTrainedModel:()=>t.SpeechT5PreTrainedModel,SpeechT5Processor:()=>w.SpeechT5Processor,SpeechT5Tokenizer:()=>s.SpeechT5Tokenizer,SqueezeBertForMaskedLM:()=>t.SqueezeBertForMaskedLM,SqueezeBertForQuestionAnswering:()=>t.SqueezeBertForQuestionAnswering,SqueezeBertForSequenceClassification:()=>t.SqueezeBertForSequenceClassification,SqueezeBertModel:()=>t.SqueezeBertModel,SqueezeBertPreTrainedModel:()=>t.SqueezeBertPreTrainedModel,SqueezeBertTokenizer:()=>s.SqueezeBertTokenizer,StableLmForCausalLM:()=>t.StableLmForCausalLM,StableLmModel:()=>t.StableLmModel,StableLmPreTrainedModel:()=>t.StableLmPreTrainedModel,Starcoder2ForCausalLM:()=>t.Starcoder2ForCausalLM,Starcoder2Model:()=>t.Starcoder2Model,Starcoder2PreTrainedModel:()=>t.Starcoder2PreTrainedModel,StoppingCriteria:()=>E.StoppingCriteria,StoppingCriteriaList:()=>E.StoppingCriteriaList,StyleTextToSpeech2Model:()=>t.StyleTextToSpeech2Model,StyleTextToSpeech2PreTrainedModel:()=>t.StyleTextToSpeech2PreTrainedModel,SummarizationPipeline:()=>r.SummarizationPipeline,SuppressTokensAtBeginLogitsProcessor:()=>y.SuppressTokensAtBeginLogitsProcessor,Swin2SRForImageSuperResolution:()=>t.Swin2SRForImageSuperResolution,Swin2SRImageProcessor:()=>_.Swin2SRImageProcessor,Swin2SRModel:()=>t.Swin2SRModel,Swin2SRPreTrainedModel:()=>t.Swin2SRPreTrainedModel,SwinForImageClassification:()=>t.SwinForImageClassification,SwinForSemanticSegmentation:()=>t.SwinForSemanticSegmentation,SwinModel:()=>t.SwinModel,SwinPreTrainedModel:()=>t.SwinPreTrainedModel,T5ForConditionalGeneration:()=>t.T5ForConditionalGeneration,T5Model:()=>t.T5Model,T5PreTrainedModel:()=>t.T5PreTrainedModel,T5Tokenizer:()=>s.T5Tokenizer,TableTransformerForObjectDetection:()=>t.TableTransformerForObjectDetection,TableTransformerModel:()=>t.TableTransformerModel,TableTransformerObjectDetectionOutput:()=>t.TableTransformerObjectDetectionOutput,TableTransformerPreTrainedModel:()=>t.TableTransformerPreTrainedModel,TemperatureLogitsWarper:()=>y.TemperatureLogitsWarper,Tensor:()=>l.Tensor,Text2TextGenerationPipeline:()=>r.Text2TextGenerationPipeline,TextClassificationPipeline:()=>r.TextClassificationPipeline,TextGenerationPipeline:()=>r.TextGenerationPipeline,TextStreamer:()=>S.TextStreamer,TextToAudioPipeline:()=>r.TextToAudioPipeline,TokenClassificationPipeline:()=>r.TokenClassificationPipeline,TokenClassifierOutput:()=>t.TokenClassifierOutput,TokenizerModel:()=>s.TokenizerModel,TopKLogitsWarper:()=>y.TopKLogitsWarper,TopPLogitsWarper:()=>y.TopPLogitsWarper,TrOCRForCausalLM:()=>t.TrOCRForCausalLM,TrOCRPreTrainedModel:()=>t.TrOCRPreTrainedModel,TranslationPipeline:()=>r.TranslationPipeline,UltravoxModel:()=>t.UltravoxModel,UltravoxPreTrainedModel:()=>t.UltravoxPreTrainedModel,UltravoxProcessor:()=>w.UltravoxProcessor,UniSpeechForCTC:()=>t.UniSpeechForCTC,UniSpeechForSequenceClassification:()=>t.UniSpeechForSequenceClassification,UniSpeechModel:()=>t.UniSpeechModel,UniSpeechPreTrainedModel:()=>t.UniSpeechPreTrainedModel,UniSpeechSatForAudioFrameClassification:()=>t.UniSpeechSatForAudioFrameClassification,UniSpeechSatForCTC:()=>t.UniSpeechSatForCTC,UniSpeechSatForSequenceClassification:()=>t.UniSpeechSatForSequenceClassification,UniSpeechSatModel:()=>t.UniSpeechSatModel,UniSpeechSatPreTrainedModel:()=>t.UniSpeechSatPreTrainedModel,VLChatProcessor:()=>w.VLChatProcessor,VLMImageProcessor:()=>_.VLMImageProcessor,ViTFeatureExtractor:()=>_.ViTFeatureExtractor,ViTForImageClassification:()=>t.ViTForImageClassification,ViTImageProcessor:()=>_.ViTImageProcessor,ViTMAEModel:()=>t.ViTMAEModel,ViTMAEPreTrainedModel:()=>t.ViTMAEPreTrainedModel,ViTMSNForImageClassification:()=>t.ViTMSNForImageClassification,ViTMSNModel:()=>t.ViTMSNModel,ViTMSNPreTrainedModel:()=>t.ViTMSNPreTrainedModel,ViTModel:()=>t.ViTModel,ViTPreTrainedModel:()=>t.ViTPreTrainedModel,VisionEncoderDecoderModel:()=>t.VisionEncoderDecoderModel,VitMatteForImageMatting:()=>t.VitMatteForImageMatting,VitMatteImageProcessor:()=>_.VitMatteImageProcessor,VitMattePreTrainedModel:()=>t.VitMattePreTrainedModel,VitPoseForPoseEstimation:()=>t.VitPoseForPoseEstimation,VitPoseImageProcessor:()=>_.VitPoseImageProcessor,VitPosePreTrainedModel:()=>t.VitPosePreTrainedModel,VitsModel:()=>t.VitsModel,VitsModelOutput:()=>t.VitsModelOutput,VitsPreTrainedModel:()=>t.VitsPreTrainedModel,VitsTokenizer:()=>s.VitsTokenizer,Wav2Vec2BertForCTC:()=>t.Wav2Vec2BertForCTC,Wav2Vec2BertForSequenceClassification:()=>t.Wav2Vec2BertForSequenceClassification,Wav2Vec2BertModel:()=>t.Wav2Vec2BertModel,Wav2Vec2BertPreTrainedModel:()=>t.Wav2Vec2BertPreTrainedModel,Wav2Vec2CTCTokenizer:()=>s.Wav2Vec2CTCTokenizer,Wav2Vec2FeatureExtractor:()=>d.Wav2Vec2FeatureExtractor,Wav2Vec2ForAudioFrameClassification:()=>t.Wav2Vec2ForAudioFrameClassification,Wav2Vec2ForCTC:()=>t.Wav2Vec2ForCTC,Wav2Vec2ForSequenceClassification:()=>t.Wav2Vec2ForSequenceClassification,Wav2Vec2Model:()=>t.Wav2Vec2Model,Wav2Vec2PreTrainedModel:()=>t.Wav2Vec2PreTrainedModel,Wav2Vec2Processor:()=>w.Wav2Vec2Processor,Wav2Vec2ProcessorWithLM:()=>w.Wav2Vec2ProcessorWithLM,WavLMForAudioFrameClassification:()=>t.WavLMForAudioFrameClassification,WavLMForCTC:()=>t.WavLMForCTC,WavLMForSequenceClassification:()=>t.WavLMForSequenceClassification,WavLMForXVector:()=>t.WavLMForXVector,WavLMModel:()=>t.WavLMModel,WavLMPreTrainedModel:()=>t.WavLMPreTrainedModel,WeSpeakerFeatureExtractor:()=>d.WeSpeakerFeatureExtractor,WeSpeakerResNetModel:()=>t.WeSpeakerResNetModel,WeSpeakerResNetPreTrainedModel:()=>t.WeSpeakerResNetPreTrainedModel,WhisperFeatureExtractor:()=>d.WhisperFeatureExtractor,WhisperForConditionalGeneration:()=>t.WhisperForConditionalGeneration,WhisperModel:()=>t.WhisperModel,WhisperPreTrainedModel:()=>t.WhisperPreTrainedModel,WhisperProcessor:()=>w.WhisperProcessor,WhisperTextStreamer:()=>S.WhisperTextStreamer,WhisperTimeStampLogitsProcessor:()=>y.WhisperTimeStampLogitsProcessor,WhisperTokenizer:()=>s.WhisperTokenizer,XLMForQuestionAnswering:()=>t.XLMForQuestionAnswering,XLMForSequenceClassification:()=>t.XLMForSequenceClassification,XLMForTokenClassification:()=>t.XLMForTokenClassification,XLMModel:()=>t.XLMModel,XLMPreTrainedModel:()=>t.XLMPreTrainedModel,XLMRobertaForMaskedLM:()=>t.XLMRobertaForMaskedLM,XLMRobertaForQuestionAnswering:()=>t.XLMRobertaForQuestionAnswering,XLMRobertaForSequenceClassification:()=>t.XLMRobertaForSequenceClassification,XLMRobertaForTokenClassification:()=>t.XLMRobertaForTokenClassification,XLMRobertaModel:()=>t.XLMRobertaModel,XLMRobertaPreTrainedModel:()=>t.XLMRobertaPreTrainedModel,XLMRobertaTokenizer:()=>s.XLMRobertaTokenizer,XLMTokenizer:()=>s.XLMTokenizer,XLMWithLMHeadModel:()=>t.XLMWithLMHeadModel,XVectorOutput:()=>t.XVectorOutput,YolosFeatureExtractor:()=>_.YolosFeatureExtractor,YolosForObjectDetection:()=>t.YolosForObjectDetection,YolosImageProcessor:()=>_.YolosImageProcessor,YolosModel:()=>t.YolosModel,YolosObjectDetectionOutput:()=>t.YolosObjectDetectionOutput,YolosPreTrainedModel:()=>t.YolosPreTrainedModel,ZeroShotAudioClassificationPipeline:()=>r.ZeroShotAudioClassificationPipeline,ZeroShotClassificationPipeline:()=>r.ZeroShotClassificationPipeline,ZeroShotImageClassificationPipeline:()=>r.ZeroShotImageClassificationPipeline,ZeroShotObjectDetectionPipeline:()=>r.ZeroShotObjectDetectionPipeline,bankers_round:()=>u.bankers_round,cat:()=>l.cat,cos_sim:()=>u.cos_sim,dot:()=>u.dot,dynamic_time_warping:()=>u.dynamic_time_warping,env:()=>e.env,full:()=>l.full,full_like:()=>l.full_like,getKeyValueShapes:()=>o.getKeyValueShapes,hamming:()=>n.hamming,hanning:()=>n.hanning,interpolate:()=>l.interpolate,interpolate_4d:()=>l.interpolate_4d,interpolate_data:()=>u.interpolate_data,is_chinese_char:()=>s.is_chinese_char,layer_norm:()=>l.layer_norm,load_image:()=>i.load_image,load_video:()=>a.load_video,log_softmax:()=>u.log_softmax,magnitude:()=>u.magnitude,matmul:()=>l.matmul,max:()=>u.max,mean:()=>l.mean,mean_pooling:()=>l.mean_pooling,medianFilter:()=>u.medianFilter,mel_filter_bank:()=>n.mel_filter_bank,min:()=>u.min,ones:()=>l.ones,ones_like:()=>l.ones_like,permute:()=>l.permute,permute_data:()=>u.permute_data,pipeline:()=>r.pipeline,quantize_embeddings:()=>l.quantize_embeddings,rand:()=>l.rand,read_audio:()=>n.read_audio,rfft:()=>l.rfft,round:()=>u.round,slice:()=>l.slice,softmax:()=>u.softmax,spectrogram:()=>n.spectrogram,stack:()=>l.stack,std_mean:()=>l.std_mean,topk:()=>l.topk,window_function:()=>n.window_function,zeros:()=>l.zeros,zeros_like:()=>l.zeros_like});var e=$t("./src/env.js"),r=$t("./src/pipelines.js"),t=$t("./src/models.js"),s=$t("./src/tokenizers.js"),o=$t("./src/configs.js"),n=$t("./src/utils/audio.js"),i=$t("./src/utils/image.js"),a=$t("./src/utils/video.js"),l=$t("./src/utils/tensor.js"),u=$t("./src/utils/maths.js"),p=$t("./src/base/feature_extraction_utils.js"),d=$t("./src/models/feature_extractors.js"),c=$t("./src/models/auto/feature_extraction_auto.js"),f=$t("./src/base/image_processors_utils.js"),_=$t("./src/models/image_processors.js"),T=$t("./src/models/auto/image_processing_auto.js"),k=$t("./src/base/processing_utils.js"),w=$t("./src/models/processors.js"),g=$t("./src/models/auto/processing_auto.js"),S=$t("./src/generation/streamers.js"),E=$t("./src/generation/stopping_criteria.js"),y=$t("./src/generation/logits_process.js")})(),m.ASTFeatureExtractor,m.ASTForAudioClassification,m.ASTModel,m.ASTPreTrainedModel,m.AlbertForMaskedLM,m.AlbertForQuestionAnswering,m.AlbertForSequenceClassification,m.AlbertModel,m.AlbertPreTrainedModel,m.AlbertTokenizer,m.AudioClassificationPipeline,m.AutoConfig,m.AutoFeatureExtractor,m.AutoImageProcessor,m.AutoModel,m.AutoModelForAudioClassification,m.AutoModelForAudioFrameClassification,m.AutoModelForAudioTextToText,m.AutoModelForCTC;var yx=m.AutoModelForCausalLM;m.AutoModelForDepthEstimation,m.AutoModelForDocumentQuestionAnswering,m.AutoModelForImageClassification,m.AutoModelForImageFeatureExtraction,m.AutoModelForImageMatting,m.AutoModelForImageSegmentation,m.AutoModelForImageTextToText,m.AutoModelForImageToImage,m.AutoModelForMaskGeneration,m.AutoModelForMaskedLM,m.AutoModelForNormalEstimation,m.AutoModelForObjectDetection,m.AutoModelForPoseEstimation,m.AutoModelForQuestionAnswering,m.AutoModelForSemanticSegmentation,m.AutoModelForSeq2SeqLM,m.AutoModelForSequenceClassification,m.AutoModelForSpeechSeq2Seq,m.AutoModelForTextToSpectrogram,m.AutoModelForTextToWaveform,m.AutoModelForTokenClassification,m.AutoModelForUniversalSegmentation,m.AutoModelForVision2Seq,m.AutoModelForXVector,m.AutoModelForZeroShotObjectDetection,m.AutoProcessor;var vx=m.AutoTokenizer;m.AutomaticSpeechRecognitionPipeline,m.BackgroundRemovalPipeline,m.BartForConditionalGeneration,m.BartForSequenceClassification,m.BartModel,m.BartPretrainedModel,m.BartTokenizer,m.BaseModelOutput,m.BaseStreamer,m.BeitFeatureExtractor,m.BeitForImageClassification,m.BeitModel,m.BeitPreTrainedModel,m.BertForMaskedLM,m.BertForQuestionAnswering,m.BertForSequenceClassification,m.BertForTokenClassification,m.BertModel,m.BertPreTrainedModel,m.BertTokenizer,m.BitImageProcessor,m.BlenderbotForConditionalGeneration,m.BlenderbotModel,m.BlenderbotPreTrainedModel,m.BlenderbotSmallForConditionalGeneration,m.BlenderbotSmallModel,m.BlenderbotSmallPreTrainedModel,m.BlenderbotSmallTokenizer,m.BlenderbotTokenizer,m.BloomForCausalLM,m.BloomModel,m.BloomPreTrainedModel,m.BloomTokenizer,m.CLIPFeatureExtractor,m.CLIPImageProcessor,m.CLIPModel,m.CLIPPreTrainedModel,m.CLIPSegForImageSegmentation,m.CLIPSegModel,m.CLIPSegPreTrainedModel,m.CLIPTextModel,m.CLIPTextModelWithProjection,m.CLIPTokenizer,m.CLIPVisionModel,m.CLIPVisionModelWithProjection,m.CamembertForMaskedLM,m.CamembertForQuestionAnswering,m.CamembertForSequenceClassification,m.CamembertForTokenClassification,m.CamembertModel,m.CamembertPreTrainedModel,m.CamembertTokenizer,m.CausalLMOutput,m.CausalLMOutputWithPast,m.ChineseCLIPFeatureExtractor,m.ChineseCLIPModel,m.ChineseCLIPPreTrainedModel,m.ClapAudioModelWithProjection,m.ClapFeatureExtractor,m.ClapModel,m.ClapPreTrainedModel,m.ClapTextModelWithProjection,m.ClassifierFreeGuidanceLogitsProcessor,m.CodeGenForCausalLM,m.CodeGenModel,m.CodeGenPreTrainedModel,m.CodeGenTokenizer,m.CodeLlamaTokenizer,m.CohereForCausalLM,m.CohereModel,m.CoherePreTrainedModel,m.CohereTokenizer,m.ConvBertForMaskedLM,m.ConvBertForQuestionAnswering,m.ConvBertForSequenceClassification,m.ConvBertForTokenClassification,m.ConvBertModel,m.ConvBertPreTrainedModel,m.ConvBertTokenizer,m.ConvNextFeatureExtractor,m.ConvNextForImageClassification,m.ConvNextImageProcessor,m.ConvNextModel,m.ConvNextPreTrainedModel,m.ConvNextV2ForImageClassification,m.ConvNextV2Model,m.ConvNextV2PreTrainedModel,m.DPTFeatureExtractor,m.DPTForDepthEstimation,m.DPTImageProcessor,m.DPTModel,m.DPTPreTrainedModel,m.DacDecoderModel,m.DacDecoderOutput,m.DacEncoderModel,m.DacEncoderOutput,m.DacFeatureExtractor,m.DacModel,m.DacPreTrainedModel,m.DataTypeMap,m.DebertaForMaskedLM,m.DebertaForQuestionAnswering,m.DebertaForSequenceClassification,m.DebertaForTokenClassification,m.DebertaModel,m.DebertaPreTrainedModel,m.DebertaTokenizer,m.DebertaV2ForMaskedLM,m.DebertaV2ForQuestionAnswering,m.DebertaV2ForSequenceClassification,m.DebertaV2ForTokenClassification,m.DebertaV2Model,m.DebertaV2PreTrainedModel,m.DebertaV2Tokenizer,m.DecisionTransformerModel,m.DecisionTransformerPreTrainedModel,m.DeiTFeatureExtractor,m.DeiTForImageClassification,m.DeiTImageProcessor,m.DeiTModel,m.DeiTPreTrainedModel,m.DepthAnythingForDepthEstimation,m.DepthAnythingPreTrainedModel,m.DepthEstimationPipeline,m.DepthProForDepthEstimation,m.DepthProPreTrainedModel,m.DetrFeatureExtractor,m.DetrForObjectDetection,m.DetrForSegmentation,m.DetrImageProcessor,m.DetrModel,m.DetrObjectDetectionOutput,m.DetrPreTrainedModel,m.DetrSegmentationOutput,m.Dinov2ForImageClassification,m.Dinov2Model,m.Dinov2PreTrainedModel,m.Dinov2WithRegistersForImageClassification,m.Dinov2WithRegistersModel,m.Dinov2WithRegistersPreTrainedModel,m.DistilBertForMaskedLM,m.DistilBertForQuestionAnswering,m.DistilBertForSequenceClassification,m.DistilBertForTokenClassification,m.DistilBertModel,m.DistilBertPreTrainedModel,m.DistilBertTokenizer,m.DocumentQuestionAnsweringPipeline,m.DonutFeatureExtractor,m.DonutImageProcessor,m.DonutSwinModel,m.DonutSwinPreTrainedModel,m.EfficientNetForImageClassification,m.EfficientNetImageProcessor,m.EfficientNetModel,m.EfficientNetPreTrainedModel,m.ElectraForMaskedLM,m.ElectraForQuestionAnswering,m.ElectraForSequenceClassification,m.ElectraForTokenClassification,m.ElectraModel,m.ElectraPreTrainedModel,m.ElectraTokenizer,m.EncodecFeatureExtractor,m.EosTokenCriteria,m.EsmForMaskedLM,m.EsmForSequenceClassification,m.EsmForTokenClassification,m.EsmModel,m.EsmPreTrainedModel,m.EsmTokenizer,m.ExaoneForCausalLM,m.ExaoneModel,m.ExaonePreTrainedModel,m.FFT,m.FalconForCausalLM,m.FalconModel,m.FalconPreTrainedModel,m.FalconTokenizer,m.FastViTForImageClassification,m.FastViTModel,m.FastViTPreTrainedModel,m.FeatureExtractionPipeline,m.FeatureExtractor,m.FillMaskPipeline,m.Florence2ForConditionalGeneration,m.Florence2PreTrainedModel,m.Florence2Processor,m.ForcedBOSTokenLogitsProcessor,m.ForcedEOSTokenLogitsProcessor,m.GLPNFeatureExtractor,m.GLPNForDepthEstimation,m.GLPNModel,m.GLPNPreTrainedModel,m.GPT2LMHeadModel,m.GPT2Model,m.GPT2PreTrainedModel,m.GPT2Tokenizer,m.GPTBigCodeForCausalLM,m.GPTBigCodeModel,m.GPTBigCodePreTrainedModel,m.GPTJForCausalLM,m.GPTJModel,m.GPTJPreTrainedModel,m.GPTNeoForCausalLM,m.GPTNeoModel,m.GPTNeoPreTrainedModel,m.GPTNeoXForCausalLM,m.GPTNeoXModel,m.GPTNeoXPreTrainedModel,m.GPTNeoXTokenizer,m.Gemma2ForCausalLM,m.Gemma2Model,m.Gemma2PreTrainedModel,m.Gemma3ForCausalLM,m.Gemma3Model,m.Gemma3PreTrainedModel,m.GemmaForCausalLM,m.GemmaModel,m.GemmaPreTrainedModel,m.GemmaTokenizer,m.GlmForCausalLM,m.GlmModel,m.GlmPreTrainedModel,m.GraniteForCausalLM,m.GraniteModel,m.GranitePreTrainedModel,m.Grok1Tokenizer,m.GroundingDinoForObjectDetection,m.GroundingDinoImageProcessor,m.GroundingDinoPreTrainedModel,m.GroundingDinoProcessor,m.GroupViTModel,m.GroupViTPreTrainedModel,m.HeliumForCausalLM,m.HeliumModel,m.HeliumPreTrainedModel,m.HerbertTokenizer,m.HieraForImageClassification,m.HieraModel,m.HieraPreTrainedModel,m.HubertForCTC,m.HubertForSequenceClassification,m.HubertModel,m.HubertPreTrainedModel,m.IJepaForImageClassification,m.IJepaModel,m.IJepaPreTrainedModel,m.Idefics3ForConditionalGeneration,m.Idefics3ImageProcessor,m.Idefics3PreTrainedModel,m.Idefics3Processor,m.ImageClassificationPipeline,m.ImageFeatureExtractionPipeline,m.ImageFeatureExtractor,m.ImageMattingOutput,m.ImageProcessor,m.ImageSegmentationPipeline,m.ImageToImagePipeline,m.ImageToTextPipeline;var xx=m.InterruptableStoppingCriteria;m.JAISLMHeadModel,m.JAISModel,m.JAISPreTrainedModel,m.JinaCLIPImageProcessor,m.JinaCLIPModel,m.JinaCLIPPreTrainedModel,m.JinaCLIPProcessor,m.JinaCLIPTextModel,m.JinaCLIPVisionModel,m.LiteWhisperForConditionalGeneration,m.LlamaForCausalLM,m.LlamaModel,m.LlamaPreTrainedModel,m.LlamaTokenizer,m.LlavaForConditionalGeneration,m.LlavaOnevisionForConditionalGeneration,m.LlavaOnevisionImageProcessor,m.LlavaPreTrainedModel,m.LogitsProcessor,m.LogitsProcessorList,m.LogitsWarper,m.LongT5ForConditionalGeneration,m.LongT5Model,m.LongT5PreTrainedModel,m.M2M100ForConditionalGeneration,m.M2M100Model,m.M2M100PreTrainedModel,m.M2M100Tokenizer,m.MBart50Tokenizer,m.MBartForCausalLM,m.MBartForConditionalGeneration,m.MBartForSequenceClassification,m.MBartModel,m.MBartPreTrainedModel,m.MBartTokenizer,m.MPNetForMaskedLM,m.MPNetForQuestionAnswering,m.MPNetForSequenceClassification,m.MPNetForTokenClassification,m.MPNetModel,m.MPNetPreTrainedModel,m.MPNetTokenizer,m.MT5ForConditionalGeneration,m.MT5Model,m.MT5PreTrainedModel,m.MarianMTModel,m.MarianModel,m.MarianPreTrainedModel,m.MarianTokenizer,m.Mask2FormerImageProcessor,m.MaskFormerFeatureExtractor,m.MaskFormerForInstanceSegmentation,m.MaskFormerImageProcessor,m.MaskFormerModel,m.MaskFormerPreTrainedModel,m.MaskedLMOutput,m.MaxLengthCriteria,m.Metric3DForDepthEstimation,m.Metric3DPreTrainedModel,m.Metric3Dv2ForDepthEstimation,m.Metric3Dv2PreTrainedModel,m.MgpstrForSceneTextRecognition,m.MgpstrModelOutput,m.MgpstrPreTrainedModel,m.MgpstrProcessor,m.MgpstrTokenizer,m.MimiDecoderModel,m.MimiDecoderOutput,m.MimiEncoderModel,m.MimiEncoderOutput,m.MimiModel,m.MimiPreTrainedModel,m.MinLengthLogitsProcessor,m.MinNewTokensLengthLogitsProcessor,m.MistralForCausalLM,m.MistralModel,m.MistralPreTrainedModel,m.MobileBertForMaskedLM,m.MobileBertForQuestionAnswering,m.MobileBertForSequenceClassification,m.MobileBertModel,m.MobileBertPreTrainedModel,m.MobileBertTokenizer,m.MobileLLMForCausalLM,m.MobileLLMModel,m.MobileLLMPreTrainedModel,m.MobileNetV1FeatureExtractor,m.MobileNetV1ForImageClassification,m.MobileNetV1ForSemanticSegmentation,m.MobileNetV1ImageProcessor,m.MobileNetV1Model,m.MobileNetV1PreTrainedModel,m.MobileNetV2FeatureExtractor,m.MobileNetV2ForImageClassification,m.MobileNetV2ForSemanticSegmentation,m.MobileNetV2ImageProcessor,m.MobileNetV2Model,m.MobileNetV2PreTrainedModel,m.MobileNetV3FeatureExtractor,m.MobileNetV3ForImageClassification,m.MobileNetV3ForSemanticSegmentation,m.MobileNetV3ImageProcessor,m.MobileNetV3Model,m.MobileNetV3PreTrainedModel,m.MobileNetV4FeatureExtractor,m.MobileNetV4ForImageClassification,m.MobileNetV4ForSemanticSegmentation,m.MobileNetV4ImageProcessor,m.MobileNetV4Model,m.MobileNetV4PreTrainedModel,m.MobileViTFeatureExtractor,m.MobileViTForImageClassification,m.MobileViTImageProcessor,m.MobileViTModel,m.MobileViTPreTrainedModel,m.MobileViTV2ForImageClassification,m.MobileViTV2Model,m.MobileViTV2PreTrainedModel,m.ModelOutput,m.ModernBertForMaskedLM,m.ModernBertForSequenceClassification,m.ModernBertForTokenClassification,m.ModernBertModel,m.ModernBertPreTrainedModel,m.Moondream1ForConditionalGeneration,m.MoonshineFeatureExtractor,m.MoonshineForConditionalGeneration,m.MoonshineModel,m.MoonshinePreTrainedModel,m.MoonshineProcessor,m.MptForCausalLM,m.MptModel,m.MptPreTrainedModel,m.MultiModalityCausalLM,m.MultiModalityPreTrainedModel,m.MusicgenForCausalLM,m.MusicgenForConditionalGeneration,m.MusicgenModel,m.MusicgenPreTrainedModel,m.NllbTokenizer,m.NoBadWordsLogitsProcessor,m.NoRepeatNGramLogitsProcessor,m.NomicBertModel,m.NomicBertPreTrainedModel,m.NougatImageProcessor,m.NougatTokenizer,m.OPTForCausalLM,m.OPTModel,m.OPTPreTrainedModel,m.ObjectDetectionPipeline,m.Olmo2ForCausalLM,m.Olmo2Model,m.Olmo2PreTrainedModel,m.OlmoForCausalLM,m.OlmoModel,m.OlmoPreTrainedModel,m.OpenELMForCausalLM,m.OpenELMModel,m.OpenELMPreTrainedModel,m.OwlViTFeatureExtractor,m.OwlViTForObjectDetection,m.OwlViTImageProcessor,m.OwlViTModel,m.OwlViTPreTrainedModel,m.OwlViTProcessor,m.Owlv2ForObjectDetection,m.Owlv2ImageProcessor,m.Owlv2Model,m.Owlv2PreTrainedModel,m.PaliGemmaForConditionalGeneration,m.PaliGemmaPreTrainedModel,m.PaliGemmaProcessor,m.PatchTSMixerForPrediction,m.PatchTSMixerModel,m.PatchTSMixerPreTrainedModel,m.PatchTSTForPrediction,m.PatchTSTModel,m.PatchTSTPreTrainedModel,m.Phi3ForCausalLM,m.Phi3Model,m.Phi3PreTrainedModel,m.Phi3VForCausalLM,m.Phi3VImageProcessor,m.Phi3VPreTrainedModel,m.Phi3VProcessor,m.PhiForCausalLM,m.PhiModel,m.PhiPreTrainedModel,m.Pipeline,m.PreTrainedModel,m.PreTrainedTokenizer,m.PretrainedConfig,m.PretrainedMixin,m.Processor,m.PvtForImageClassification,m.PvtImageProcessor,m.PvtModel,m.PvtPreTrainedModel,m.PyAnnoteFeatureExtractor,m.PyAnnoteForAudioFrameClassification,m.PyAnnoteModel,m.PyAnnotePreTrainedModel,m.PyAnnoteProcessor,m.QuestionAnsweringModelOutput,m.QuestionAnsweringPipeline,m.Qwen2ForCausalLM,m.Qwen2Model,m.Qwen2PreTrainedModel,m.Qwen2Tokenizer,m.Qwen2VLForConditionalGeneration,m.Qwen2VLImageProcessor,m.Qwen2VLPreTrainedModel,m.Qwen2VLProcessor,m.RFDetrForObjectDetection,m.RFDetrModel,m.RFDetrObjectDetectionOutput,m.RFDetrPreTrainedModel,m.RTDetrForObjectDetection,m.RTDetrImageProcessor,m.RTDetrModel,m.RTDetrObjectDetectionOutput,m.RTDetrPreTrainedModel,m.RTDetrV2ForObjectDetection,m.RTDetrV2Model,m.RTDetrV2ObjectDetectionOutput,m.RTDetrV2PreTrainedModel,m.RawAudio,m.RawImage,m.RawVideo,m.RawVideoFrame,m.RepetitionPenaltyLogitsProcessor,m.ResNetForImageClassification,m.ResNetModel,m.ResNetPreTrainedModel,m.RoFormerForMaskedLM,m.RoFormerForQuestionAnswering,m.RoFormerForSequenceClassification,m.RoFormerForTokenClassification,m.RoFormerModel,m.RoFormerPreTrainedModel,m.RoFormerTokenizer,m.RobertaForMaskedLM,m.RobertaForQuestionAnswering,m.RobertaForSequenceClassification,m.RobertaForTokenClassification,m.RobertaModel,m.RobertaPreTrainedModel,m.RobertaTokenizer,m.SamImageProcessor,m.SamImageSegmentationOutput,m.SamModel,m.SamPreTrainedModel,m.SamProcessor,m.SapiensForDepthEstimation,m.SapiensForNormalEstimation,m.SapiensForSemanticSegmentation,m.SapiensPreTrainedModel,m.SeamlessM4TFeatureExtractor,m.SegformerFeatureExtractor,m.SegformerForImageClassification,m.SegformerForSemanticSegmentation,m.SegformerImageProcessor,m.SegformerModel,m.SegformerPreTrainedModel,m.Seq2SeqLMOutput,m.SequenceClassifierOutput,m.SiglipImageProcessor,m.SiglipModel,m.SiglipPreTrainedModel,m.SiglipTextModel,m.SiglipTokenizer,m.SiglipVisionModel,m.SmolVLMForConditionalGeneration,m.SmolVLMImageProcessor,m.SmolVLMProcessor,m.SnacDecoderModel,m.SnacEncoderModel,m.SnacFeatureExtractor,m.SnacModel,m.SnacPreTrainedModel,m.SpeechT5FeatureExtractor,m.SpeechT5ForSpeechToText,m.SpeechT5ForTextToSpeech,m.SpeechT5HifiGan,m.SpeechT5Model,m.SpeechT5PreTrainedModel,m.SpeechT5Processor,m.SpeechT5Tokenizer,m.SqueezeBertForMaskedLM,m.SqueezeBertForQuestionAnswering,m.SqueezeBertForSequenceClassification,m.SqueezeBertModel,m.SqueezeBertPreTrainedModel,m.SqueezeBertTokenizer,m.StableLmForCausalLM,m.StableLmModel,m.StableLmPreTrainedModel,m.Starcoder2ForCausalLM,m.Starcoder2Model,m.Starcoder2PreTrainedModel,m.StoppingCriteria,m.StoppingCriteriaList,m.StyleTextToSpeech2Model,m.StyleTextToSpeech2PreTrainedModel,m.SummarizationPipeline,m.SuppressTokensAtBeginLogitsProcessor,m.Swin2SRForImageSuperResolution,m.Swin2SRImageProcessor,m.Swin2SRModel,m.Swin2SRPreTrainedModel,m.SwinForImageClassification,m.SwinForSemanticSegmentation,m.SwinModel,m.SwinPreTrainedModel,m.T5ForConditionalGeneration,m.T5Model,m.T5PreTrainedModel,m.T5Tokenizer,m.TableTransformerForObjectDetection,m.TableTransformerModel,m.TableTransformerObjectDetectionOutput,m.TableTransformerPreTrainedModel,m.TemperatureLogitsWarper,m.Tensor,m.Text2TextGenerationPipeline,m.TextClassificationPipeline,m.TextGenerationPipeline;var Tx=m.TextStreamer;m.TextToAudioPipeline,m.TokenClassificationPipeline,m.TokenClassifierOutput,m.TokenizerModel,m.TopKLogitsWarper,m.TopPLogitsWarper,m.TrOCRForCausalLM,m.TrOCRPreTrainedModel,m.TranslationPipeline,m.UltravoxModel,m.UltravoxPreTrainedModel,m.UltravoxProcessor,m.UniSpeechForCTC,m.UniSpeechForSequenceClassification,m.UniSpeechModel,m.UniSpeechPreTrainedModel,m.UniSpeechSatForAudioFrameClassification,m.UniSpeechSatForCTC,m.UniSpeechSatForSequenceClassification,m.UniSpeechSatModel,m.UniSpeechSatPreTrainedModel,m.VLChatProcessor,m.VLMImageProcessor,m.ViTFeatureExtractor,m.ViTForImageClassification,m.ViTImageProcessor,m.ViTMAEModel,m.ViTMAEPreTrainedModel,m.ViTMSNForImageClassification,m.ViTMSNModel,m.ViTMSNPreTrainedModel,m.ViTModel,m.ViTPreTrainedModel,m.VisionEncoderDecoderModel,m.VitMatteForImageMatting,m.VitMatteImageProcessor,m.VitMattePreTrainedModel,m.VitPoseForPoseEstimation,m.VitPoseImageProcessor,m.VitPosePreTrainedModel,m.VitsModel,m.VitsModelOutput,m.VitsPreTrainedModel,m.VitsTokenizer,m.Wav2Vec2BertForCTC,m.Wav2Vec2BertForSequenceClassification,m.Wav2Vec2BertModel,m.Wav2Vec2BertPreTrainedModel,m.Wav2Vec2CTCTokenizer,m.Wav2Vec2FeatureExtractor,m.Wav2Vec2ForAudioFrameClassification,m.Wav2Vec2ForCTC,m.Wav2Vec2ForSequenceClassification,m.Wav2Vec2Model,m.Wav2Vec2PreTrainedModel,m.Wav2Vec2Processor,m.Wav2Vec2ProcessorWithLM,m.WavLMForAudioFrameClassification,m.WavLMForCTC,m.WavLMForSequenceClassification,m.WavLMForXVector,m.WavLMModel,m.WavLMPreTrainedModel,m.WeSpeakerFeatureExtractor,m.WeSpeakerResNetModel,m.WeSpeakerResNetPreTrainedModel,m.WhisperFeatureExtractor,m.WhisperForConditionalGeneration,m.WhisperModel,m.WhisperPreTrainedModel,m.WhisperProcessor,m.WhisperTextStreamer,m.WhisperTimeStampLogitsProcessor,m.WhisperTokenizer,m.XLMForQuestionAnswering,m.XLMForSequenceClassification,m.XLMForTokenClassification,m.XLMModel,m.XLMPreTrainedModel,m.XLMRobertaForMaskedLM,m.XLMRobertaForQuestionAnswering,m.XLMRobertaForSequenceClassification,m.XLMRobertaForTokenClassification,m.XLMRobertaModel,m.XLMRobertaPreTrainedModel,m.XLMRobertaTokenizer,m.XLMTokenizer,m.XLMWithLMHeadModel,m.XVectorOutput,m.YolosFeatureExtractor,m.YolosForObjectDetection,m.YolosImageProcessor,m.YolosModel,m.YolosObjectDetectionOutput,m.YolosPreTrainedModel,m.ZeroShotAudioClassificationPipeline,m.ZeroShotClassificationPipeline,m.ZeroShotImageClassificationPipeline,m.ZeroShotObjectDetectionPipeline,m.bankers_round,m.cat,m.cos_sim,m.dot,m.dynamic_time_warping,m.env,m.full,m.full_like,m.getKeyValueShapes,m.hamming,m.hanning,m.interpolate,m.interpolate_4d,m.interpolate_data,m.is_chinese_char,m.layer_norm,m.load_image,m.load_video,m.log_softmax,m.magnitude,m.matmul,m.max,m.mean,m.mean_pooling,m.medianFilter,m.mel_filter_bank,m.min,m.ones,m.ones_like,m.permute,m.permute_data,m.pipeline,m.quantize_embeddings,m.rand,m.read_audio,m.rfft,m.round,m.slice,m.softmax,m.spectrogram,m.stack,m.std_mean,m.topk,m.window_function,m.zeros,m.zeros_like;class cu{static async getInstance(r=null){return this.tokenizer??(this.tokenizer=vx.from_pretrained(this.model_id,{progress_callback:r})),this.model??(this.model=yx.from_pretrained(this.model_id,{dtype:"q4f16",device:"webgpu",progress_callback:r})),Promise.all([this.tokenizer,this.model])}}te(cu,"model_id","onnx-community/Llama-3.2-1B-Instruct-q4f16");const yi=new xx;async function Ex(e){const[r,t]=await cu.getInstance(),s=r.apply_chat_template(e,{add_generation_prompt:!0,return_dict:!0});let o,n=0,i;const a=()=>{o??(o=performance.now()),n++>0&&(i=n/(performance.now()-o)*1e3)},l=f=>{self.postMessage({status:"update",output:f,tps:i,numTokens:n})},u=new Tx(r,{skip_prompt:!0,skip_special_tokens:!0,callback_function:l,token_callback_function:a});self.postMessage({status:"start"});const{past_key_values:p,sequences:d}=await t.generate({...s,do_sample:!1,max_new_tokens:1024,streamer:u,stopping_criteria:yi,return_dict_in_generate:!0}),c=r.batch_decode(d,{skip_special_tokens:!0});self.postMessage({status:"complete",output:c})}async function Px(){try{if(!await navigator.gpu.requestAdapter())throw new Error("WebGPU is not supported (no adapter found)")}catch(e){self.postMessage({status:"error",data:e.toString()})}}async function Cx(){self.postMessage({status:"loading",data:"Loading model..."});const[e,r]=await cu.getInstance(s=>{self.postMessage(s)});self.postMessage({status:"loading",data:"Compiling shaders and warming up model..."});const t=e("a");await r.generate({...t,max_new_tokens:1}),self.postMessage({status:"ready"})}self.addEventListener("message",async e=>{const{type:r,data:t}=e.data;switch(r){case"check":Px();break;case"load":Cx();break;case"generate":yi.reset(),Ex(t);break;case"interrupt":yi.interrupt();break;case"reset":yi.reset();break}})})(); diff --git a/banner.png b/banner.png index 570234c7f68d47dc912ef29ac1d60564490633a1..b0f2981b87bfc65c096ae7081e0aeb86e67f3016 100644 Binary files a/banner.png and b/banner.png differ diff --git a/index.html b/index.html index 54320a7e2b85d1e406637b053b669dbd18831028..87729212f7f2a63f75880017709fe18cc10d34f7 100644 --- a/index.html +++ b/index.html @@ -5,8 +5,8 @@ Llama-3.2 WebGPU - - + + diff --git a/logo.png b/logo.png index 15b46b7f1849bb3089e73bf21fc46d021b72ba5a..a52475e7294ca5f07b8d3f9e83a04258f9cc7fa8 100644 Binary files a/logo.png and b/logo.png differ