diff --git a/assets/index-0KCISaPa.js b/assets/index-0KCISaPa.js deleted file mode 100644 index 2ad4b4c75d9211d12b6be4762e09e2e5aa92a56e..0000000000000000000000000000000000000000 --- a/assets/index-0KCISaPa.js +++ /dev/null @@ -1,96 +0,0 @@ -var cp=Object.defineProperty;var fp=(d,s,o)=>s in d?cp(d,s,{enumerable:!0,configurable:!0,writable:!0,value:o}):d[s]=o;var Re=(d,s,o)=>fp(d,typeof s!="symbol"?s+"":s,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 p of f)if(p.type==="childList")for(const y of p.addedNodes)y.tagName==="LINK"&&y.rel==="modulepreload"&&a(y)}).observe(document,{childList:!0,subtree:!0});function o(f){const p={};return f.integrity&&(p.integrity=f.integrity),f.referrerPolicy&&(p.referrerPolicy=f.referrerPolicy),f.crossOrigin==="use-credentials"?p.credentials="include":f.crossOrigin==="anonymous"?p.credentials="omit":p.credentials="same-origin",p}function a(f){if(f.ep)return;f.ep=!0;const p=o(f);fetch(f.href,p)}})();function dp(d){return d&&d.__esModule&&Object.prototype.hasOwnProperty.call(d,"default")?d.default:d}var Qs={exports:{}},Pl={},Gs={exports:{}},oe={};/** - * @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 Fc;function pp(){if(Fc)return oe;Fc=1;var d=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"),p=Symbol.for("react.provider"),y=Symbol.for("react.context"),k=Symbol.for("react.forward_ref"),T=Symbol.for("react.suspense"),_=Symbol.for("react.memo"),S=Symbol.for("react.lazy"),I=Symbol.iterator;function A(v){return v===null||typeof v!="object"?null:(v=I&&v[I]||v["@@iterator"],typeof v=="function"?v:null)}var D={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},V=Object.assign,F={};function K(v,C,Y){this.props=v,this.context=C,this.refs=F,this.updater=Y||D}K.prototype.isReactComponent={},K.prototype.setState=function(v,C){if(typeof v!="object"&&typeof v!="function"&&v!=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,v,C,"setState")},K.prototype.forceUpdate=function(v){this.updater.enqueueForceUpdate(this,v,"forceUpdate")};function he(){}he.prototype=K.prototype;function ae(v,C,Y){this.props=v,this.context=C,this.refs=F,this.updater=Y||D}var Ee=ae.prototype=new he;Ee.constructor=ae,V(Ee,K.prototype),Ee.isPureReactComponent=!0;var te=Array.isArray,me=Object.prototype.hasOwnProperty,ne={current:null},Ne={key:!0,ref:!0,__self:!0,__source:!0};function ce(v,C,Y){var re,Z={},ie=null,ke=null;if(C!=null)for(re in C.ref!==void 0&&(ke=C.ref),C.key!==void 0&&(ie=""+C.key),C)me.call(C,re)&&!Ne.hasOwnProperty(re)&&(Z[re]=C[re]);var ge=arguments.length-2;if(ge===1)Z.children=Y;else if(1>>1,C=O[v];if(0>>1;vf(Z,j))ief(ke,Z)?(O[v]=ke,O[ie]=j,v=ie):(O[v]=Z,O[re]=j,v=re);else if(ief(ke,j))O[v]=ke,O[ie]=j,v=ie;else break e}}return Q}function f(O,Q){var j=O.sortIndex-Q.sortIndex;return j!==0?j:O.id-Q.id}if(typeof performance=="object"&&typeof performance.now=="function"){var p=performance;d.unstable_now=function(){return p.now()}}else{var y=Date,k=y.now();d.unstable_now=function(){return y.now()-k}}var T=[],_=[],S=1,I=null,A=3,D=!1,V=!1,F=!1,K=typeof setTimeout=="function"?setTimeout:null,he=typeof clearTimeout=="function"?clearTimeout:null,ae=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function Ee(O){for(var Q=o(_);Q!==null;){if(Q.callback===null)a(_);else if(Q.startTime<=O)a(_),Q.sortIndex=Q.expirationTime,s(T,Q);else break;Q=o(_)}}function te(O){if(F=!1,Ee(O),!V)if(o(T)!==null)V=!0,we(me);else{var Q=o(_);Q!==null&&_e(te,Q.startTime-O)}}function me(O,Q){V=!1,F&&(F=!1,he(ce),ce=-1),D=!0;var j=A;try{for(Ee(Q),I=o(T);I!==null&&(!(I.expirationTime>Q)||O&&!ze());){var v=I.callback;if(typeof v=="function"){I.callback=null,A=I.priorityLevel;var C=v(I.expirationTime<=Q);Q=d.unstable_now(),typeof C=="function"?I.callback=C:I===o(T)&&a(T),Ee(Q)}else a(T);I=o(T)}if(I!==null)var Y=!0;else{var re=o(_);re!==null&&_e(te,re.startTime-Q),Y=!1}return Y}finally{I=null,A=j,D=!1}}var ne=!1,Ne=null,ce=-1,kt=5,nt=-1;function ze(){return!(d.unstable_now()-ntO||125v?(O.sortIndex=j,s(_,O),o(T)===null&&O===o(_)&&(F?(he(ce),ce=-1):F=!0,_e(te,j-v))):(O.sortIndex=C,s(T,O),V||D||(V=!0,we(me))),O},d.unstable_shouldYield=ze,d.unstable_wrapCallback=function(O){var Q=A;return function(){var j=A;A=Q;try{return O.apply(this,arguments)}finally{A=j}}}}(Ks)),Ks}var Wc;function yp(){return Wc||(Wc=1,Xs.exports=gp()),Xs.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 Vc;function vp(){if(Vc)return ht;Vc=1;var d=ou(),s=yp();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"),T=Object.prototype.hasOwnProperty,_=/^[: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]*$/,S={},I={};function A(e){return T.call(I,e)?!0:T.call(S,e)?!1:_.test(e)?I[e]=!0:(S[e]=!0,!1)}function D(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 V(e,t,n,r){if(t===null||typeof t>"u"||D(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 F(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 K={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){K[e]=new F(e,0,!1,e,null,!1,!1)}),[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];K[t]=new F(t,1,!1,e[1],null,!1,!1)}),["contentEditable","draggable","spellCheck","value"].forEach(function(e){K[e]=new F(e,2,!1,e.toLowerCase(),null,!1,!1)}),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){K[e]=new F(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){K[e]=new F(e,3,!1,e.toLowerCase(),null,!1,!1)}),["checked","multiple","muted","selected"].forEach(function(e){K[e]=new F(e,3,!0,e,null,!1,!1)}),["capture","download"].forEach(function(e){K[e]=new F(e,4,!1,e,null,!1,!1)}),["cols","rows","size","span"].forEach(function(e){K[e]=new F(e,6,!1,e,null,!1,!1)}),["rowSpan","start"].forEach(function(e){K[e]=new F(e,5,!1,e.toLowerCase(),null,!1,!1)});var he=/[\-:]([a-z])/g;function ae(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(he,ae);K[t]=new F(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(he,ae);K[t]=new F(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(he,ae);K[t]=new F(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)}),["tabIndex","crossOrigin"].forEach(function(e){K[e]=new F(e,1,!1,e.toLowerCase(),null,!1,!1)}),K.xlinkHref=new F("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1),["src","href","action","formAction"].forEach(function(e){K[e]=new F(e,1,!1,e.toLowerCase(),null,!0,!0)});function Ee(e,t,n,r){var l=K.hasOwnProperty(t)?K[t]:null;(l!==null?l.type!==0:r||!(2c||l[u]!==i[c]){var h=` -`+l[u].replace(" at new "," at ");return e.displayName&&h.includes("")&&(h=h.replace("",e.displayName)),h}while(1<=u&&0<=c);break}}}finally{Y=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?C(e):""}function Z(e){switch(e.tag){case 5:return C(e.type);case 16:return C("Lazy");case 13:return C("Suspense");case 19:return C("SuspenseList");case 0:case 2:case 15:return e=re(e.type,!1),e;case 11:return e=re(e.type.render,!1),e;case 1:return e=re(e.type,!0),e;default:return""}}function ie(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 Ne:return"Fragment";case ne:return"Portal";case kt:return"Profiler";case ce:return"StrictMode";case fe:return"Suspense";case ue:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case ze:return(e.displayName||"Context")+".Consumer";case nt:return(e._context.displayName||"Context")+".Provider";case J:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case de:return t=e.displayName||null,t!==null?t:ie(e.type)||"Memo";case we:t=e._payload,e=e._init;try{return ie(e(t))}catch{}}return null}function ke(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 ie(t);case 8:return t===ce?"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 ge(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function Te(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function Ze(e){var t=Te(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 Vn(e){e._valueTracker||(e._valueTracker=Ze(e))}function qt(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=Te(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function pn(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 zt(e,t){var n=t.checked;return j({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function mr(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=ge(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 gr(e,t){t=t.checked,t!=null&&Ee(e,"checked",t,!1)}function Wt(e,t){gr(e,t);var n=ge(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")?hn(e,t.type,n):t.hasOwnProperty("defaultValue")&&hn(e,t.type,ge(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function Qn(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 hn(e,t,n){(t!=="number"||pn(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var mn=Array.isArray;function Jt(e,t,n,r){if(e=e.options,t){t={};for(var l=0;l"+t.valueOf().toString()+"",t=Gn.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function nn(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var yn={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},wr=["Webkit","ms","Moz","O"];Object.keys(yn).forEach(function(e){wr.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),yn[t]=yn[e]})});function Yn(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||yn.hasOwnProperty(e)&&yn[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=Yn(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,l):e[n]=l}}var vn=j({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 Xn(e,t){if(t){if(vn[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 Kn(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 Yr=null;function wn(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var kn=null,xn=null,St=null;function Vl(e){if(e=ml(e)){if(typeof kn!="function")throw Error(o(280));var t=e.stateNode;t&&(t=mi(t),kn(e.stateNode,e.type,t))}}function Ql(e){xn?St?St.push(e):St=[e]:xn=e}function Fe(){if(xn){var e=xn,t=St;if(St=xn=null,Vl(e),t)for(e=0;e>>=0,e===0?32:31-(Rf(e)/Nf|0)|0}var bl=64,ql=4194304;function br(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 Jl(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=br(c):(i&=u,i!==0&&(r=br(i)))}else u=n&~l,u!==0?r=br(u):i!==0&&(r=br(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 qr(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-Ot(t),e[t]=n}function Mf(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=ol),Au=" ",Mu=!1;function zu(e,t){switch(e){case"keyup":return od.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Iu(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var Tr=!1;function ud(e,t){switch(e){case"compositionend":return Iu(t);case"keypress":return t.which!==32?null:(Mu=!0,Au);case"textInput":return e=t.data,e===Au&&Mu?null:e;default:return null}}function ad(e,t){if(Tr)return e==="compositionend"||!To&&zu(e,t)?(e=Tu(),li=wo=Nn=null,Tr=!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=Bu(n)}}function Wu(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?Wu(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function Vu(){for(var e=window,t=pn();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=pn(e.document)}return t}function No(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 vd(e){var t=Vu(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&Wu(n.ownerDocument.documentElement,n)){if(r!==null&&No(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=Hu(n,i);var u=Hu(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,Cr=null,Lo=null,cl=null,Po=!1;function Qu(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;Po||Cr==null||Cr!==pn(r)||(r=Cr,"selectionStart"in r&&No(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}),cl&&al(cl,r)||(cl=r,r=di(Lo,"onSelect"),0Ar||(e.current=Ho[Ar],Ho[Ar]=null,Ar--)}function Pe(e,t){Ar++,Ho[Ar]=e.current,e.current=t}var Mn={},qe=An(Mn),at=An(!1),tr=Mn;function Mr(e,t){var n=e.type.contextTypes;if(!n)return Mn;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 ct(e){return e=e.childContextTypes,e!=null}function gi(){Me(at),Me(qe)}function oa(e,t,n){if(qe.current!==Mn)throw Error(o(168));Pe(qe,t),Pe(at,n)}function sa(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,ke(e)||"Unknown",l));return j({},n,r)}function yi(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||Mn,tr=qe.current,Pe(qe,e),Pe(at,at.current),!0}function ua(e,t,n){var r=e.stateNode;if(!r)throw Error(o(169));n?(e=sa(e,t,tr),r.__reactInternalMemoizedMergedChildContext=e,Me(at),Me(qe),Pe(qe,e)):Me(at),Pe(at,n)}var on=null,vi=!1,Wo=!1;function aa(e){on===null?on=[e]:on.push(e)}function Pd(e){vi=!0,aa(e)}function zn(){if(!Wo&&on!==null){Wo=!0;var e=0,t=xe;try{var n=on;for(xe=1;e>=u,l-=u,sn=1<<32-Ot(t)+l|n<ee?(Ye=q,q=null):Ye=q.sibling;var ye=R(w,q,x[ee],z);if(ye===null){q===null&&(q=Ye);break}e&&q&&ye.alternate===null&&t(w,q),m=i(ye,m,ee),b===null?G=ye:b.sibling=ye,b=ye,q=Ye}if(ee===x.length)return n(w,q),Ie&&rr(w,ee),G;if(q===null){for(;eeee?(Ye=q,q=null):Ye=q.sibling;var Hn=R(w,q,ye.value,z);if(Hn===null){q===null&&(q=Ye);break}e&&q&&Hn.alternate===null&&t(w,q),m=i(Hn,m,ee),b===null?G=Hn:b.sibling=Hn,b=Hn,q=Ye}if(ye.done)return n(w,q),Ie&&rr(w,ee),G;if(q===null){for(;!ye.done;ee++,ye=x.next())ye=P(w,ye.value,z),ye!==null&&(m=i(ye,m,ee),b===null?G=ye:b.sibling=ye,b=ye);return Ie&&rr(w,ee),G}for(q=r(w,q);!ye.done;ee++,ye=x.next())ye=U(q,w,ee,ye.value,z),ye!==null&&(e&&ye.alternate!==null&&q.delete(ye.key===null?ee:ye.key),m=i(ye,m,ee),b===null?G=ye:b.sibling=ye,b=ye);return e&&q.forEach(function(ap){return t(w,ap)}),Ie&&rr(w,ee),G}function Ue(w,m,x,z){if(typeof x=="object"&&x!==null&&x.type===Ne&&x.key===null&&(x=x.props.children),typeof x=="object"&&x!==null){switch(x.$$typeof){case me:e:{for(var G=x.key,b=m;b!==null;){if(b.key===G){if(G=x.type,G===Ne){if(b.tag===7){n(w,b.sibling),m=l(b,x.props.children),m.return=w,w=m;break e}}else if(b.elementType===G||typeof G=="object"&&G!==null&&G.$$typeof===we&&ma(G)===b.type){n(w,b.sibling),m=l(b,x.props),m.ref=gl(w,b,x),m.return=w,w=m;break e}n(w,b);break}else t(w,b);b=b.sibling}x.type===Ne?(m=fr(x.props.children,w.mode,z,x.key),m.return=w,w=m):(z=Gi(x.type,x.key,x.props,null,w.mode,z),z.ref=gl(w,m,x),z.return=w,w=z)}return u(w);case ne:e:{for(b=x.key;m!==null;){if(m.key===b)if(m.tag===4&&m.stateNode.containerInfo===x.containerInfo&&m.stateNode.implementation===x.implementation){n(w,m.sibling),m=l(m,x.children||[]),m.return=w,w=m;break e}else{n(w,m);break}else t(w,m);m=m.sibling}m=$s(x,w.mode,z),m.return=w,w=m}return u(w);case we:return b=x._init,Ue(w,m,b(x._payload),z)}if(mn(x))return B(w,m,x,z);if(Q(x))return W(w,m,x,z);Si(w,x)}return typeof x=="string"&&x!==""||typeof x=="number"?(x=""+x,m!==null&&m.tag===6?(n(w,m.sibling),m=l(m,x),m.return=w,w=m):(n(w,m),m=Us(x,w.mode,z),m.return=w,w=m),u(w)):n(w,m)}return Ue}var Dr=ga(!0),ya=ga(!1),Ei=An(null),_i=null,jr=null,Ko=null;function Zo(){Ko=jr=_i=null}function bo(e){var t=Ei.current;Me(Ei),e._currentValue=t}function qo(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 Fr(e,t){_i=e,Ko=jr=null,e=e.dependencies,e!==null&&e.firstContext!==null&&(e.lanes&t&&(ft=!0),e.firstContext=null)}function Ct(e){var t=e._currentValue;if(Ko!==e)if(e={context:e,memoizedValue:t,next:null},jr===null){if(_i===null)throw Error(o(308));jr=e,_i.dependencies={lanes:0,firstContext:e}}else jr=jr.next=e;return t}var lr=null;function Jo(e){lr===null?lr=[e]:lr.push(e)}function va(e,t,n,r){var l=t.interleaved;return l===null?(n.next=n,Jo(t)):(n.next=l.next,l.next=n),t.interleaved=n,an(e,r)}function an(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 es(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function wa(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 cn(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,pe&2){var l=r.pending;return l===null?t.next=t:(t.next=l.next,l.next=t),r.pending=t,an(e,n)}return l=r.interleaved,l===null?(t.next=t,Jo(r)):(t.next=l.next,l.next=t),r.interleaved=t,an(e,n)}function Ti(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,ho(e,n)}}function ka(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 Ci(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 h=c,E=h.next;h.next=null,u===null?i=E:u.next=E,u=h;var N=e.alternate;N!==null&&(N=N.updateQueue,c=N.lastBaseUpdate,c!==u&&(c===null?N.firstBaseUpdate=E:c.next=E,N.lastBaseUpdate=h))}if(i!==null){var P=l.baseState;u=0,N=E=h=null,c=i;do{var R=c.lane,U=c.eventTime;if((r&R)===R){N!==null&&(N=N.next={eventTime:U,lane:0,tag:c.tag,payload:c.payload,callback:c.callback,next:null});e:{var B=e,W=c;switch(R=t,U=n,W.tag){case 1:if(B=W.payload,typeof B=="function"){P=B.call(U,P,R);break e}P=B;break e;case 3:B.flags=B.flags&-65537|128;case 0:if(B=W.payload,R=typeof B=="function"?B.call(U,P,R):B,R==null)break e;P=j({},P,R);break e;case 2:In=!0}}c.callback!==null&&c.lane!==0&&(e.flags|=64,R=l.effects,R===null?l.effects=[c]:R.push(c))}else U={eventTime:U,lane:R,tag:c.tag,payload:c.payload,callback:c.callback,next:null},N===null?(E=N=U,h=P):N=N.next=U,u|=R;if(c=c.next,c===null){if(c=l.shared.pending,c===null)break;R=c,c=R.next,R.next=null,l.lastBaseUpdate=R,l.shared.pending=null}}while(!0);if(N===null&&(h=P),l.baseState=h,l.firstBaseUpdate=E,l.lastBaseUpdate=N,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);sr|=u,e.lanes=u,e.memoizedState=P}}function xa(e,t,n){if(e=t.effects,t.effects=null,e!==null)for(t=0;tn?n:4,e(!0);var r=is.transition;is.transition={};try{e(!1),t()}finally{xe=n,is.transition=r}}function $a(){return Rt().memoizedState}function Id(e,t,n){var r=Un(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},Ba(e))Ha(t,n);else if(n=va(e,t,n,r),n!==null){var l=lt();Bt(n,e,r,l),Wa(n,t,r)}}function Od(e,t,n){var r=Un(e),l={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(Ba(e))Ha(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,Dt(c,u)){var h=t.interleaved;h===null?(l.next=l,Jo(t)):(l.next=h.next,h.next=l),t.interleaved=l;return}}catch{}finally{}n=va(e,t,l,r),n!==null&&(l=lt(),Bt(n,e,r,l),Wa(n,t,r))}}function Ba(e){var t=e.alternate;return e===De||t!==null&&t===De}function Ha(e,t){kl=Li=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function Wa(e,t,n){if(n&4194240){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,ho(e,n)}}var Mi={readContext:Ct,useCallback:Je,useContext:Je,useEffect:Je,useImperativeHandle:Je,useInsertionEffect:Je,useLayoutEffect:Je,useMemo:Je,useReducer:Je,useRef:Je,useState:Je,useDebugValue:Je,useDeferredValue:Je,useTransition:Je,useMutableSource:Je,useSyncExternalStore:Je,useId:Je,unstable_isNewReconciler:!1},Dd={readContext:Ct,useCallback:function(e,t){return Kt().memoizedState=[e,t===void 0?null:t],e},useContext:Ct,useEffect:Ma,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,Pi(4194308,4,Oa.bind(null,t,e),n)},useLayoutEffect:function(e,t){return Pi(4194308,4,e,t)},useInsertionEffect:function(e,t){return Pi(4,2,e,t)},useMemo:function(e,t){var n=Kt();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=Kt();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=Id.bind(null,De,e),[r.memoizedState,e]},useRef:function(e){var t=Kt();return e={current:e},t.memoizedState=e},useState:Pa,useDebugValue:ds,useDeferredValue:function(e){return Kt().memoizedState=e},useTransition:function(){var e=Pa(!1),t=e[0];return e=zd.bind(null,e[1]),Kt().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=De,l=Kt();if(Ie){if(n===void 0)throw Error(o(407));n=n()}else{if(n=t(),Ge===null)throw Error(o(349));or&30||Ta(r,t,n)}l.memoizedState=n;var i={value:n,getSnapshot:t};return l.queue=i,Ma(Ra.bind(null,r,i,e),[e]),r.flags|=2048,El(9,Ca.bind(null,r,i,n,t),void 0,null),n},useId:function(){var e=Kt(),t=Ge.identifierPrefix;if(Ie){var n=un,r=sn;n=(r&~(1<<32-Ot(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=xl++,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[Yt]=t,e[hl]=r,ac(e,t,!1,!1),t.stateNode=e;e:{switch(u=Kn(n,r),n){case"dialog":Ae("cancel",e),Ae("close",e),l=r;break;case"iframe":case"object":case"embed":Ae("load",e),l=r;break;case"video":case"audio":for(l=0;lWr&&(t.flags|=128,r=!0,_l(i,!1),t.lanes=4194304)}else{if(!r)if(e=Ri(u),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),_l(i,!0),i.tail===null&&i.tailMode==="hidden"&&!u.alternate&&!Ie)return et(t),null}else 2*le()-i.renderingStartTime>Wr&&n!==1073741824&&(t.flags|=128,r=!0,_l(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=le(),t.sibling=null,n=Oe.current,Pe(Oe,r?n&1|2:n&1),t):(et(t),null);case 22:case 23:return Ds(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?vt&1073741824&&(et(t),t.subtreeFlags&6&&(t.flags|=8192)):et(t),null;case 24:return null;case 25:return null}throw Error(o(156,t.tag))}function Vd(e,t){switch(Qo(t),t.tag){case 1:return ct(t.type)&&gi(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return Ur(),Me(at),Me(qe),ls(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return ns(t),null;case 13:if(Me(Oe),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 Me(Oe),null;case 4:return Ur(),null;case 10:return bo(t.type._context),null;case 22:case 23:return Ds(),null;case 24:return null;default:return null}}var Di=!1,tt=!1,Qd=typeof WeakSet=="function"?WeakSet:Set,$=null;function Br(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){je(e,t,r)}else n.current=null}function _s(e,t,n){try{n()}catch(r){je(e,t,r)}}var dc=!1;function Gd(e,t){if(Do=ni,e=Vu(),No(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,h=-1,E=0,N=0,P=e,R=null;t:for(;;){for(var U;P!==n||l!==0&&P.nodeType!==3||(c=u+l),P!==i||r!==0&&P.nodeType!==3||(h=u+r),P.nodeType===3&&(u+=P.nodeValue.length),(U=P.firstChild)!==null;)R=P,P=U;for(;;){if(P===e)break t;if(R===n&&++E===l&&(c=u),R===i&&++N===r&&(h=u),(U=P.nextSibling)!==null)break;P=R,R=P.parentNode}P=U}n=c===-1||h===-1?null:{start:c,end:h}}else n=null}n=n||{start:0,end:0}}else n=null;for(jo={focusedElem:e,selectionRange:n},ni=!1,$=t;$!==null;)if(t=$,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,$=e;else for(;$!==null;){t=$;try{var B=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(B!==null){var W=B.memoizedProps,Ue=B.memoizedState,w=t.stateNode,m=w.getSnapshotBeforeUpdate(t.elementType===t.type?W:Ft(t.type,W),Ue);w.__reactInternalSnapshotBeforeUpdate=m}break;case 3:var x=t.stateNode.containerInfo;x.nodeType===1?x.textContent="":x.nodeType===9&&x.documentElement&&x.removeChild(x.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(o(163))}}catch(z){je(t,t.return,z)}if(e=t.sibling,e!==null){e.return=t.return,$=e;break}$=t.return}return B=dc,dc=!1,B}function Tl(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&&_s(t,n,i)}l=l.next}while(l!==r)}}function ji(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 Ts(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 pc(e){var t=e.alternate;t!==null&&(e.alternate=null,pc(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[Yt],delete t[hl],delete t[Bo],delete t[Nd],delete t[Ld])),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 hc(e){return e.tag===5||e.tag===3||e.tag===4}function mc(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||hc(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 Cs(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=hi));else if(r!==4&&(e=e.child,e!==null))for(Cs(e,t,n),e=e.sibling;e!==null;)Cs(e,t,n),e=e.sibling}function Rs(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(Rs(e,t,n),e=e.sibling;e!==null;)Rs(e,t,n),e=e.sibling}var Xe=null,Ut=!1;function Dn(e,t,n){for(n=n.child;n!==null;)gc(e,t,n),n=n.sibling}function gc(e,t,n){if(Gt&&typeof Gt.onCommitFiberUnmount=="function")try{Gt.onCommitFiberUnmount(Zl,n)}catch{}switch(n.tag){case 5:tt||Br(n,t);case 6:var r=Xe,l=Ut;Xe=null,Dn(e,t,n),Xe=r,Ut=l,Xe!==null&&(Ut?(e=Xe,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):Xe.removeChild(n.stateNode));break;case 18:Xe!==null&&(Ut?(e=Xe,n=n.stateNode,e.nodeType===8?$o(e.parentNode,n):e.nodeType===1&&$o(e,n),rl(e)):$o(Xe,n.stateNode));break;case 4:r=Xe,l=Ut,Xe=n.stateNode.containerInfo,Ut=!0,Dn(e,t,n),Xe=r,Ut=l;break;case 0:case 11:case 14:case 15:if(!tt&&(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||i&4)&&_s(n,t,u),l=l.next}while(l!==r)}Dn(e,t,n);break;case 1:if(!tt&&(Br(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(c){je(n,t,c)}Dn(e,t,n);break;case 21:Dn(e,t,n);break;case 22:n.mode&1?(tt=(r=tt)||n.memoizedState!==null,Dn(e,t,n),tt=r):Dn(e,t,n);break;default:Dn(e,t,n)}}function yc(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new Qd),t.forEach(function(r){var l=tp.bind(null,e,r);n.has(r)||(n.add(r),r.then(l,l))})}}function $t(e,t){var n=t.deletions;if(n!==null)for(var r=0;rl&&(l=u),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*Xd(r/1960))-r,10e?16:e,Fn===null)var r=!1;else{if(e=Fn,Fn=null,Hi=0,pe&6)throw Error(o(331));var l=pe;for(pe|=4,$=e.current;$!==null;){var i=$,u=i.child;if($.flags&16){var c=i.deletions;if(c!==null){for(var h=0;hle()-Ps?ar(e,0):Ls|=n),pt(e,t)}function Pc(e,t){t===0&&(e.mode&1?(t=ql,ql<<=1,!(ql&130023424)&&(ql=4194304)):t=1);var n=lt();e=an(e,t),e!==null&&(qr(e,t,n),pt(e,n))}function ep(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),Pc(e,n)}function tp(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),Pc(e,n)}var Ac;Ac=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||at.current)ft=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return ft=!1,Hd(e,t,n);ft=!!(e.flags&131072)}else ft=!1,Ie&&t.flags&1048576&&ca(t,ki,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;Oi(e,t),e=t.pendingProps;var l=Mr(t,qe.current);Fr(t,n),l=ss(null,t,r,e,l,n);var i=us();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,ct(r)?(i=!0,yi(t)):i=!1,t.memoizedState=l.state!==null&&l.state!==void 0?l.state:null,es(t),l.updater=zi,t.stateNode=l,l._reactInternals=t,hs(t,r,e,n),t=vs(null,t,r,!0,i,n)):(t.tag=0,Ie&&i&&Vo(t),rt(null,t,l,n),t=t.child),t;case 16:r=t.elementType;e:{switch(Oi(e,t),e=t.pendingProps,l=r._init,r=l(r._payload),t.type=r,l=t.tag=rp(r),e=Ft(r,e),l){case 0:t=ys(null,t,r,e,n);break e;case 1:t=rc(null,t,r,e,n);break e;case 11:t=qa(null,t,r,e,n);break e;case 14:t=Ja(null,t,r,Ft(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:Ft(r,l),ys(e,t,r,l,n);case 1:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Ft(r,l),rc(e,t,r,l,n);case 3:e:{if(lc(t),e===null)throw Error(o(387));r=t.pendingProps,i=t.memoizedState,l=i.element,wa(e,t),Ci(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=$r(Error(o(423)),t),t=ic(e,t,r,n,l);break e}else if(r!==l){l=$r(Error(o(424)),t),t=ic(e,t,r,n,l);break e}else for(yt=Pn(t.stateNode.containerInfo.firstChild),gt=t,Ie=!0,jt=null,n=ya(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(Or(),r===l){t=fn(e,t,n);break e}rt(e,t,r,n)}t=t.child}return t;case 5:return Sa(t),e===null&&Yo(t),r=t.type,l=t.pendingProps,i=e!==null?e.memoizedProps:null,u=l.children,Fo(r,l)?u=null:i!==null&&Fo(r,i)&&(t.flags|=32),nc(e,t),rt(e,t,u,n),t.child;case 6:return e===null&&Yo(t),null;case 13:return oc(e,t,n);case 4:return ts(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=Dr(t,null,r,n):rt(e,t,r,n),t.child;case 11:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Ft(r,l),qa(e,t,r,l,n);case 7:return rt(e,t,t.pendingProps,n),t.child;case 8:return rt(e,t,t.pendingProps.children,n),t.child;case 12:return rt(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,Pe(Ei,r._currentValue),r._currentValue=u,i!==null)if(Dt(i.value,u)){if(i.children===l.children&&!at.current){t=fn(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 h=c.firstContext;h!==null;){if(h.context===r){if(i.tag===1){h=cn(-1,n&-n),h.tag=2;var E=i.updateQueue;if(E!==null){E=E.shared;var N=E.pending;N===null?h.next=h:(h.next=N.next,N.next=h),E.pending=h}}i.lanes|=n,h=i.alternate,h!==null&&(h.lanes|=n),qo(i.return,n,t),c.lanes|=n;break}h=h.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),qo(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}rt(e,t,l.children,n),t=t.child}return t;case 9:return l=t.type,r=t.pendingProps.children,Fr(t,n),l=Ct(l),r=r(l),t.flags|=1,rt(e,t,r,n),t.child;case 14:return r=t.type,l=Ft(r,t.pendingProps),l=Ft(r.type,l),Ja(e,t,r,l,n);case 15:return ec(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Ft(r,l),Oi(e,t),t.tag=1,ct(r)?(e=!0,yi(t)):e=!1,Fr(t,n),Qa(t,r,l),hs(t,r,l,n),vs(null,t,r,!0,e,n);case 19:return uc(e,t,n);case 22:return tc(e,t,n)}throw Error(o(156,t.tag))};function Mc(e,t){return M(e,t)}function np(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 np(e,t,n,r)}function Fs(e){return e=e.prototype,!(!e||!e.isReactComponent)}function rp(e){if(typeof e=="function")return Fs(e)?1:0;if(e!=null){if(e=e.$$typeof,e===J)return 11;if(e===de)return 14}return 2}function Bn(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 Gi(e,t,n,r,l,i){var u=2;if(r=e,typeof e=="function")Fs(e)&&(u=1);else if(typeof e=="string")u=5;else e:switch(e){case Ne:return fr(n.children,l,i,t);case ce:u=8,l|=8;break;case kt:return e=Lt(12,n,t,l|2),e.elementType=kt,e.lanes=i,e;case fe:return e=Lt(13,n,t,l),e.elementType=fe,e.lanes=i,e;case ue:return e=Lt(19,n,t,l),e.elementType=ue,e.lanes=i,e;case _e:return Yi(n,l,i,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case nt:u=10;break e;case ze:u=9;break e;case J:u=11;break e;case de:u=14;break e;case we: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 fr(e,t,n,r){return e=Lt(7,e,r,t),e.lanes=n,e}function Yi(e,t,n,r){return e=Lt(22,e,r,t),e.elementType=_e,e.lanes=n,e.stateNode={isHidden:!1},e}function Us(e,t,n){return e=Lt(6,e,null,t),e.lanes=n,e}function $s(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 lp(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=po(0),this.expirationTimes=po(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=po(0),this.identifierPrefix=r,this.onRecoverableError=l,this.mutableSourceEagerHydrationData=null}function Bs(e,t,n,r,l,i,u,c,h){return e=new lp(e,t,n,c,h),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},es(i),e}function ip(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(d)}catch(s){console.error(s)}}return d(),Ys.exports=vp(),Ys.exports}var Gc;function kp(){if(Gc)return eo;Gc=1;var d=wp();return eo.createRoot=d.createRoot,eo.hydrateRoot=d.hydrateRoot,eo}var xp=kp();function su(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}let hr=su();function df(d){hr=d}const Bl={exec:()=>null};function Ce(d,s=""){let o=typeof d=="string"?d:d.source;const a={replace:(f,p)=>{let y=typeof p=="string"?p:p.source;return y=y.replace(ot.caret,"$1"),o=o.replace(f,y),a},getRegex:()=>new RegExp(o,s)};return a}const ot={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceTabs:/^\t+/,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] /,listReplaceTask:/^\[[ xX]\] +/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,unescapeTest:/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:d=>new RegExp(`^( {0,3}${d})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:d=>new RegExp(`^ {0,${Math.min(3,d-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),hrRegex:d=>new RegExp(`^ {0,${Math.min(3,d-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:d=>new RegExp(`^ {0,${Math.min(3,d-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:d=>new RegExp(`^ {0,${Math.min(3,d-1)}}#`),htmlBeginRegex:d=>new RegExp(`^ {0,${Math.min(3,d-1)}}<(?:[a-z].*>|!--)`,"i")},Sp=/^(?:[ \t]*(?:\n|$))+/,Ep=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,_p=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,Wl=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Tp=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,pf=/(?:[*+-]|\d{1,9}[.)])/,hf=Ce(/^(?!bull |blockCode|fences|blockquote|heading|html)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html))+?)\n {0,3}(=+|-+) *(?:\n+|$)/).replace(/bull/g,pf).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).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(),uu=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,Cp=/^[^\n]+/,au=/(?!\s*\])(?:\\.|[^\[\]\\])+/,Rp=Ce(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",au).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Np=Ce(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,pf).getRegex(),uo="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",cu=/|$))/,Lp=Ce("^ {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",cu).replace("tag",uo).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),mf=Ce(uu).replace("hr",Wl).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",uo).getRegex(),Pp=Ce(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",mf).getRegex(),fu={blockquote:Pp,code:Ep,def:Rp,fences:_p,heading:Tp,hr:Wl,html:Lp,lheading:hf,list:Np,newline:Sp,paragraph:mf,table:Bl,text:Cp},Yc=Ce("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",Wl).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",uo).getRegex(),Ap={...fu,table:Yc,paragraph:Ce(uu).replace("hr",Wl).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Yc).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",uo).getRegex()},Mp={...fu,html:Ce(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+? *(?:\\n{2,}|\\s*$)|\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",cu).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:Bl,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:Ce(uu).replace("hr",Wl).replace("heading",` *#{1,6} *[^ -]`).replace("lheading",hf).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},zp=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Ip=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,gf=/^( {2,}|\\)\n(?!\s*$)/,Op=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\]*?>/g,Bp=Ce(/^(?:\*+(?:((?!\*)punct)|[^\s*]))|^_+(?:((?!_)punct)|([^\s_]))/,"u").replace(/punct/g,ao).getRegex(),vf="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",Hp=Ce(vf,"gu").replace(/notPunctSpace/g,yf).replace(/punctSpace/g,du).replace(/punct/g,ao).getRegex(),Wp=Ce(vf,"gu").replace(/notPunctSpace/g,Up).replace(/punctSpace/g,Fp).replace(/punct/g,jp).getRegex(),Vp=Ce("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,yf).replace(/punctSpace/g,du).replace(/punct/g,ao).getRegex(),Qp=Ce(/\\(punct)/,"gu").replace(/punct/g,ao).getRegex(),Gp=Ce(/^<(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(),Yp=Ce(cu).replace("(?:-->|$)","-->").getRegex(),Xp=Ce("^comment|^|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^|^").replace("comment",Yp).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),io=/(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/,Kp=Ce(/^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/).replace("label",io).replace("href",/<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),wf=Ce(/^!?\[(label)\]\[(ref)\]/).replace("label",io).replace("ref",au).getRegex(),kf=Ce(/^!?\[(ref)\](?:\[\])?/).replace("ref",au).getRegex(),Zp=Ce("reflink|nolink(?!\\()","g").replace("reflink",wf).replace("nolink",kf).getRegex(),pu={_backpedal:Bl,anyPunctuation:Qp,autolink:Gp,blockSkip:$p,br:gf,code:Ip,del:Bl,emStrongLDelim:Bp,emStrongRDelimAst:Hp,emStrongRDelimUnd:Vp,escape:zp,link:Kp,nolink:kf,punctuation:Dp,reflink:wf,reflinkSearch:Zp,tag:Xp,text:Op,url:Bl},bp={...pu,link:Ce(/^!?\[(label)\]\((.*?)\)/).replace("label",io).getRegex(),reflink:Ce(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",io).getRegex()},tu={...pu,emStrongRDelimAst:Wp,url:Ce(/^((?: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~\\]))\1(?=[^~]|$)/,text:/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\":">",'"':""","'":"'"},Xc=d=>Jp[d];function bt(d,s){if(s){if(ot.escapeTest.test(d))return d.replace(ot.escapeReplace,Xc)}else if(ot.escapeTestNoEncode.test(d))return d.replace(ot.escapeReplaceNoEncode,Xc);return d}function Kc(d){try{d=encodeURI(d).replace(ot.percentDecode,"%")}catch{return null}return d}function Zc(d,s){var p;const o=d.replace(ot.findPipe,(y,k,T)=>{let _=!1,S=k;for(;--S>=0&&T[S]==="\\";)_=!_;return _?"|":" |"}),a=o.split(ot.splitPipe);let f=0;if(a[0].trim()||a.shift(),a.length>0&&!((p=a.at(-1))!=null&&p.trim())&&a.pop(),s)if(a.length>s)a.splice(s);else for(;a.length{const y=p.match(o.other.beginningSpace);if(y===null)return p;const[k]=y;return k.length>=f.length?p.slice(f.length):p}).join(` -`)}class oo{constructor(s){Re(this,"options");Re(this,"rules");Re(this,"lexer");this.options=s||hr}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(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:o[0],codeBlockStyle:"indented",text:this.options.pedantic?a:Ml(a,` -`)}}}fences(s){const o=this.rules.block.fences.exec(s);if(o){const a=o[0],f=th(a,o[3]||"",this.rules);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(this.rules.other.endingHash.test(a)){const f=Ml(a,"#");(this.options.pedantic||!f||this.rules.other.endingSpaceChar.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:Ml(o[0],` -`)}}blockquote(s){const o=this.rules.block.blockquote.exec(s);if(o){let a=Ml(o[0],` -`).split(` -`),f="",p="";const y=[];for(;a.length>0;){let k=!1;const T=[];let _;for(_=0;_1,p={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 y=this.rules.other.listItemRegex(a);let k=!1;for(;s;){let _=!1,S="",I="";if(!(o=y.exec(s))||this.rules.block.hr.test(s))break;S=o[0],s=s.substring(S.length);let A=o[2].split(` -`,1)[0].replace(this.rules.other.listReplaceTabs,ae=>" ".repeat(3*ae.length)),D=s.split(` -`,1)[0],V=!A.trim(),F=0;if(this.options.pedantic?(F=2,I=A.trimStart()):V?F=o[1].length+1:(F=o[2].search(this.rules.other.nonSpaceChar),F=F>4?1:F,I=A.slice(F),F+=o[1].length),V&&this.rules.other.blankLine.test(D)&&(S+=D+` -`,s=s.substring(D.length+1),_=!0),!_){const ae=this.rules.other.nextBulletRegex(F),Ee=this.rules.other.hrRegex(F),te=this.rules.other.fencesBeginRegex(F),me=this.rules.other.headingBeginRegex(F),ne=this.rules.other.htmlBeginRegex(F);for(;s;){const Ne=s.split(` -`,1)[0];let ce;if(D=Ne,this.options.pedantic?(D=D.replace(this.rules.other.listReplaceNesting," "),ce=D):ce=D.replace(this.rules.other.tabCharGlobal," "),te.test(D)||me.test(D)||ne.test(D)||ae.test(D)||Ee.test(D))break;if(ce.search(this.rules.other.nonSpaceChar)>=F||!D.trim())I+=` -`+ce.slice(F);else{if(V||A.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||te.test(A)||me.test(A)||Ee.test(A))break;I+=` -`+D}!V&&!D.trim()&&(V=!0),S+=Ne+` -`,s=s.substring(Ne.length+1),A=ce.slice(F)}}p.loose||(k?p.loose=!0:this.rules.other.doubleBlankLine.test(S)&&(k=!0));let K=null,he;this.options.gfm&&(K=this.rules.other.listIsTask.exec(I),K&&(he=K[0]!=="[ ] ",I=I.replace(this.rules.other.listReplaceTask,""))),p.items.push({type:"list_item",raw:S,task:!!K,checked:he,loose:!1,text:I,tokens:[]}),p.raw+=S}const T=p.items.at(-1);if(T)T.raw=T.raw.trimEnd(),T.text=T.text.trimEnd();else return;p.raw=p.raw.trimEnd();for(let _=0;_A.type==="space"),I=S.length>0&&S.some(A=>this.rules.other.anyLine.test(A.raw));p.loose=I}if(p.loose)for(let _=0;_({text:_,tokens:this.lexer.inline(_),header:!1,align:y.align[S]})));return y}}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:o[1]}}tag(s){const o=this.rules.inline.tag.exec(s);if(o)return!this.lexer.state.inLink&&this.rules.other.startATag.test(o[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(o[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(o[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.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&&this.rules.other.startAngleBracket.test(a)){if(!this.rules.other.endAngleBracket.test(a))return;const y=Ml(a.slice(0,-1),"\\");if((a.length-y.length)%2===0)return}else{const y=eh(o[2],"()");if(y>-1){const T=(o[0].indexOf("!")===0?5:4)+o[1].length+y;o[2]=o[2].substring(0,y),o[0]=o[0].substring(0,T).trim(),o[3]=""}}let f=o[2],p="";if(this.options.pedantic){const y=this.rules.other.pedanticHrefTitle.exec(f);y&&(f=y[1],p=y[3])}else p=o[3]?o[3].slice(1,-1):"";return f=f.trim(),this.rules.other.startAngleBracket.test(f)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(a)?f=f.slice(1):f=f.slice(1,-1)),bc(o,{href:f&&f.replace(this.rules.inline.anyPunctuation,"$1"),title:p&&p.replace(this.rules.inline.anyPunctuation,"$1")},o[0],this.lexer,this.rules)}}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(this.rules.other.multipleSpaceGlobal," "),p=o[f.toLowerCase()];if(!p){const y=a[0].charAt(0);return{type:"text",raw:y,text:y}}return bc(a,p,a[0],this.lexer,this.rules)}}emStrong(s,o,a=""){let f=this.rules.inline.emStrongLDelim.exec(s);if(!f||f[3]&&a.match(this.rules.other.unicodeAlphaNumeric))return;if(!(f[1]||f[2]||"")||!a||this.rules.inline.punctuation.exec(a)){const y=[...f[0]].length-1;let k,T,_=y,S=0;const I=f[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(I.lastIndex=0,o=o.slice(-1*s.length+y);(f=I.exec(o))!=null;){if(k=f[1]||f[2]||f[3]||f[4]||f[5]||f[6],!k)continue;if(T=[...k].length,f[3]||f[4]){_+=T;continue}else if((f[5]||f[6])&&y%3&&!((y+T)%3)){S+=T;continue}if(_-=T,_>0)continue;T=Math.min(T,T+_+S);const A=[...f[0]][0].length,D=s.slice(0,y+f.index+A+T);if(Math.min(y,T)%2){const F=D.slice(1,-1);return{type:"em",raw:D,text:F,tokens:this.lexer.inlineTokens(F)}}const V=D.slice(2,-2);return{type:"strong",raw:D,text:V,tokens:this.lexer.inlineTokens(V)}}}}codespan(s){const o=this.rules.inline.code.exec(s);if(o){let a=o[2].replace(this.rules.other.newLineCharGlobal," ");const f=this.rules.other.nonSpaceChar.test(a),p=this.rules.other.startingSpaceChar.test(a)&&this.rules.other.endingSpaceChar.test(a);return f&&p&&(a=a.substring(1,a.length-1)),{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=o[1],f="mailto:"+a):(a=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,p;if(o[2]==="@")f=o[0],p="mailto:"+f;else{let y;do y=o[0],o[0]=((a=this.rules.inline._backpedal.exec(o[0]))==null?void 0:a[0])??"";while(y!==o[0]);f=o[0],o[1]==="www."?p="http://"+o[0]:p=o[0]}return{type:"link",raw:o[0],text:f,href:p,tokens:[{type:"text",raw:f,text:f}]}}}inlineText(s){const o=this.rules.inline.text.exec(s);if(o){const a=this.lexer.state.inRawBlock;return{type:"text",raw:o[0],text:o[0],escaped:a}}}}class Pt{constructor(s){Re(this,"tokens");Re(this,"options");Re(this,"state");Re(this,"tokenizer");Re(this,"inlineQueue");this.tokens=[],this.tokens.links=Object.create(null),this.options=s||hr,this.options.tokenizer=this.options.tokenizer||new oo,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};const o={other:ot,block:to.normal,inline:Al.normal};this.options.pedantic?(o.block=to.pedantic,o.inline=Al.pedantic):this.options.gfm&&(o.block=to.gfm,this.options.breaks?o.inline=Al.breaks:o.inline=Al.gfm),this.tokenizer.rules=o}static get rules(){return{block:to,inline:Al}}static lex(s,o){return new Pt(o).lex(s)}static lexInline(s,o){return new Pt(o).inlineTokens(s)}lex(s){s=s.replace(ot.carriageReturn,` -`),this.blockTokens(s,this.tokens);for(let o=0;o(k=_.call({lexer:this},s,o))?(s=s.substring(k.raw.length),o.push(k),!0):!1))continue;if(k=this.tokenizer.space(s)){s=s.substring(k.raw.length);const _=o.at(-1);k.raw.length===1&&_!==void 0?_.raw+=` -`:o.push(k);continue}if(k=this.tokenizer.code(s)){s=s.substring(k.raw.length);const _=o.at(-1);(_==null?void 0:_.type)==="paragraph"||(_==null?void 0:_.type)==="text"?(_.raw+=` -`+k.raw,_.text+=` -`+k.text,this.inlineQueue.at(-1).src=_.text):o.push(k);continue}if(k=this.tokenizer.fences(s)){s=s.substring(k.raw.length),o.push(k);continue}if(k=this.tokenizer.heading(s)){s=s.substring(k.raw.length),o.push(k);continue}if(k=this.tokenizer.hr(s)){s=s.substring(k.raw.length),o.push(k);continue}if(k=this.tokenizer.blockquote(s)){s=s.substring(k.raw.length),o.push(k);continue}if(k=this.tokenizer.list(s)){s=s.substring(k.raw.length),o.push(k);continue}if(k=this.tokenizer.html(s)){s=s.substring(k.raw.length),o.push(k);continue}if(k=this.tokenizer.def(s)){s=s.substring(k.raw.length);const _=o.at(-1);(_==null?void 0:_.type)==="paragraph"||(_==null?void 0:_.type)==="text"?(_.raw+=` -`+k.raw,_.text+=` -`+k.raw,this.inlineQueue.at(-1).src=_.text):this.tokens.links[k.tag]||(this.tokens.links[k.tag]={href:k.href,title:k.title});continue}if(k=this.tokenizer.table(s)){s=s.substring(k.raw.length),o.push(k);continue}if(k=this.tokenizer.lheading(s)){s=s.substring(k.raw.length),o.push(k);continue}let T=s;if((y=this.options.extensions)!=null&&y.startBlock){let _=1/0;const S=s.slice(1);let I;this.options.extensions.startBlock.forEach(A=>{I=A.call({lexer:this},S),typeof I=="number"&&I>=0&&(_=Math.min(_,I))}),_<1/0&&_>=0&&(T=s.substring(0,_+1))}if(this.state.top&&(k=this.tokenizer.paragraph(T))){const _=o.at(-1);a&&(_==null?void 0:_.type)==="paragraph"?(_.raw+=` -`+k.raw,_.text+=` -`+k.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=_.text):o.push(k),a=T.length!==s.length,s=s.substring(k.raw.length);continue}if(k=this.tokenizer.text(s)){s=s.substring(k.raw.length);const _=o.at(-1);(_==null?void 0:_.type)==="text"?(_.raw+=` -`+k.raw,_.text+=` -`+k.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=_.text):o.push(k);continue}if(s){const _="Infinite loop on byte: "+s.charCodeAt(0);if(this.options.silent){console.error(_);break}else throw new Error(_)}}return this.state.top=!0,o}inline(s,o=[]){return this.inlineQueue.push({src:s,tokens:o}),o}inlineTokens(s,o=[]){var k,T,_;let a=s,f=null;if(this.tokens.links){const S=Object.keys(this.tokens.links);if(S.length>0)for(;(f=this.tokenizer.rules.inline.reflinkSearch.exec(a))!=null;)S.includes(f[0].slice(f[0].lastIndexOf("[")+1,-1))&&(a=a.slice(0,f.index)+"["+"a".repeat(f[0].length-2)+"]"+a.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(f=this.tokenizer.rules.inline.blockSkip.exec(a))!=null;)a=a.slice(0,f.index)+"["+"a".repeat(f[0].length-2)+"]"+a.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);for(;(f=this.tokenizer.rules.inline.anyPunctuation.exec(a))!=null;)a=a.slice(0,f.index)+"++"+a.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let p=!1,y="";for(;s;){p||(y=""),p=!1;let S;if((T=(k=this.options.extensions)==null?void 0:k.inline)!=null&&T.some(A=>(S=A.call({lexer:this},s,o))?(s=s.substring(S.raw.length),o.push(S),!0):!1))continue;if(S=this.tokenizer.escape(s)){s=s.substring(S.raw.length),o.push(S);continue}if(S=this.tokenizer.tag(s)){s=s.substring(S.raw.length),o.push(S);continue}if(S=this.tokenizer.link(s)){s=s.substring(S.raw.length),o.push(S);continue}if(S=this.tokenizer.reflink(s,this.tokens.links)){s=s.substring(S.raw.length);const A=o.at(-1);S.type==="text"&&(A==null?void 0:A.type)==="text"?(A.raw+=S.raw,A.text+=S.text):o.push(S);continue}if(S=this.tokenizer.emStrong(s,a,y)){s=s.substring(S.raw.length),o.push(S);continue}if(S=this.tokenizer.codespan(s)){s=s.substring(S.raw.length),o.push(S);continue}if(S=this.tokenizer.br(s)){s=s.substring(S.raw.length),o.push(S);continue}if(S=this.tokenizer.del(s)){s=s.substring(S.raw.length),o.push(S);continue}if(S=this.tokenizer.autolink(s)){s=s.substring(S.raw.length),o.push(S);continue}if(!this.state.inLink&&(S=this.tokenizer.url(s))){s=s.substring(S.raw.length),o.push(S);continue}let I=s;if((_=this.options.extensions)!=null&&_.startInline){let A=1/0;const D=s.slice(1);let V;this.options.extensions.startInline.forEach(F=>{V=F.call({lexer:this},D),typeof V=="number"&&V>=0&&(A=Math.min(A,V))}),A<1/0&&A>=0&&(I=s.substring(0,A+1))}if(S=this.tokenizer.inlineText(I)){s=s.substring(S.raw.length),S.raw.slice(-1)!=="_"&&(y=S.raw.slice(-1)),p=!0;const A=o.at(-1);(A==null?void 0:A.type)==="text"?(A.raw+=S.raw,A.text+=S.text):o.push(S);continue}if(s){const A="Infinite loop on byte: "+s.charCodeAt(0);if(this.options.silent){console.error(A);break}else throw new Error(A)}}return o}}class so{constructor(s){Re(this,"options");Re(this,"parser");this.options=s||hr}space(s){return""}code({text:s,lang:o,escaped:a}){var y;const f=(y=(o||"").match(ot.notSpaceStart))==null?void 0:y[0],p=s.replace(ot.endingNewline,"")+` -`;return f?'
'+(a?p:bt(p,!0))+`
-`:"
"+(a?p:bt(p,!0))+`
-`}blockquote({tokens:s}){return`
-${this.parser.parse(s)}
-`}html({text:s}){return s}heading({tokens:s,depth:o}){return`${this.parser.parseInline(s)} -`}hr(s){return`
-`}list(s){const o=s.ordered,a=s.start;let f="";for(let k=0;k -`+f+" -`}listitem(s){var a;let o="";if(s.task){const f=this.checkbox({checked:!!s.checked});s.loose?((a=s.tokens[0])==null?void 0:a.type)==="paragraph"?(s.tokens[0].text=f+" "+s.tokens[0].text,s.tokens[0].tokens&&s.tokens[0].tokens.length>0&&s.tokens[0].tokens[0].type==="text"&&(s.tokens[0].tokens[0].text=f+" "+bt(s.tokens[0].tokens[0].text),s.tokens[0].tokens[0].escaped=!0)):s.tokens.unshift({type:"text",raw:f+" ",text:f+" ",escaped:!0}):o+=f+" "}return o+=this.parser.parse(s.tokens,!!s.loose),`
  • ${o}
  • -`}checkbox({checked:s}){return"'}paragraph({tokens:s}){return`

    ${this.parser.parseInline(s)}

    -`}table(s){let o="",a="";for(let p=0;p${f}`),` - -`+o+` -`+f+`
    -`}tablerow({text:s}){return` -${s} -`}tablecell(s){const o=this.parser.parseInline(s.tokens),a=s.header?"th":"td";return(s.align?`<${a} align="${s.align}">`:`<${a}>`)+o+` -`}strong({tokens:s}){return`${this.parser.parseInline(s)}`}em({tokens:s}){return`${this.parser.parseInline(s)}`}codespan({text:s}){return`${bt(s,!0)}`}br(s){return"
    "}del({tokens:s}){return`${this.parser.parseInline(s)}`}link({href:s,title:o,tokens:a}){const f=this.parser.parseInline(a),p=Kc(s);if(p===null)return f;s=p;let y='
    ",y}image({href:s,title:o,text:a}){const f=Kc(s);if(f===null)return bt(a);s=f;let p=`${a}{const _=k[T].flat(1/0);a=a.concat(this.walkTokens(_,o))}):k.tokens&&(a=a.concat(this.walkTokens(k.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(p=>{if(!p.name)throw new Error("extension name required");if("renderer"in p){const y=o.renderers[p.name];y?o.renderers[p.name]=function(...k){let T=p.renderer.apply(this,k);return T===!1&&(T=y.apply(this,k)),T}:o.renderers[p.name]=p.renderer}if("tokenizer"in p){if(!p.level||p.level!=="block"&&p.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");const y=o[p.level];y?y.unshift(p.tokenizer):o[p.level]=[p.tokenizer],p.start&&(p.level==="block"?o.startBlock?o.startBlock.push(p.start):o.startBlock=[p.start]:p.level==="inline"&&(o.startInline?o.startInline.push(p.start):o.startInline=[p.start]))}"childTokens"in p&&p.childTokens&&(o.childTokens[p.name]=p.childTokens)}),f.extensions=o),a.renderer){const p=this.defaults.renderer||new so(this.defaults);for(const y in a.renderer){if(!(y in p))throw new Error(`renderer '${y}' does not exist`);if(["options","parser"].includes(y))continue;const k=y,T=a.renderer[k],_=p[k];p[k]=(...S)=>{let I=T.apply(p,S);return I===!1&&(I=_.apply(p,S)),I||""}}f.renderer=p}if(a.tokenizer){const p=this.defaults.tokenizer||new oo(this.defaults);for(const y in a.tokenizer){if(!(y in p))throw new Error(`tokenizer '${y}' does not exist`);if(["options","rules","lexer"].includes(y))continue;const k=y,T=a.tokenizer[k],_=p[k];p[k]=(...S)=>{let I=T.apply(p,S);return I===!1&&(I=_.apply(p,S)),I}}f.tokenizer=p}if(a.hooks){const p=this.defaults.hooks||new Hl;for(const y in a.hooks){if(!(y in p))throw new Error(`hook '${y}' does not exist`);if(["options","block"].includes(y))continue;const k=y,T=a.hooks[k],_=p[k];Hl.passThroughHooks.has(y)?p[k]=S=>{if(this.defaults.async)return Promise.resolve(T.call(p,S)).then(A=>_.call(p,A));const I=T.call(p,S);return _.call(p,I)}:p[k]=(...S)=>{let I=T.apply(p,S);return I===!1&&(I=_.apply(p,S)),I}}f.hooks=p}if(a.walkTokens){const p=this.defaults.walkTokens,y=a.walkTokens;f.walkTokens=function(k){let T=[];return T.push(y.call(this,k)),p&&(T=T.concat(p.call(this,k))),T}}this.defaults={...this.defaults,...f}}),this}setOptions(s){return this.defaults={...this.defaults,...s},this}lexer(s,o){return Pt.lex(s,o??this.defaults)}parser(s,o){return At.parse(s,o??this.defaults)}parseMarkdown(s){return(a,f)=>{const p={...f},y={...this.defaults,...p},k=this.onError(!!y.silent,!!y.async);if(this.defaults.async===!0&&p.async===!1)return k(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof a>"u"||a===null)return k(new Error("marked(): input parameter is undefined or null"));if(typeof a!="string")return k(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(a)+", string expected"));y.hooks&&(y.hooks.options=y,y.hooks.block=s);const T=y.hooks?y.hooks.provideLexer():s?Pt.lex:Pt.lexInline,_=y.hooks?y.hooks.provideParser():s?At.parse:At.parseInline;if(y.async)return Promise.resolve(y.hooks?y.hooks.preprocess(a):a).then(S=>T(S,y)).then(S=>y.hooks?y.hooks.processAllTokens(S):S).then(S=>y.walkTokens?Promise.all(this.walkTokens(S,y.walkTokens)).then(()=>S):S).then(S=>_(S,y)).then(S=>y.hooks?y.hooks.postprocess(S):S).catch(k);try{y.hooks&&(a=y.hooks.preprocess(a));let S=T(a,y);y.hooks&&(S=y.hooks.processAllTokens(S)),y.walkTokens&&this.walkTokens(S,y.walkTokens);let I=_(S,y);return y.hooks&&(I=y.hooks.postprocess(I)),I}catch(S){return k(S)}}}onError(s,o){return a=>{if(a.message+=` -Please report this to https://github.com/markedjs/marked.`,s){const f="

    An error occurred:

    "+bt(a.message+"",!0)+"
    ";return o?Promise.resolve(f):f}if(o)return Promise.reject(a);throw a}}}const pr=new nh;function Se(d,s){return pr.parse(d,s)}Se.options=Se.setOptions=function(d){return pr.setOptions(d),Se.defaults=pr.defaults,df(Se.defaults),Se};Se.getDefaults=su;Se.defaults=hr;Se.use=function(...d){return pr.use(...d),Se.defaults=pr.defaults,df(Se.defaults),Se};Se.walkTokens=function(d,s){return pr.walkTokens(d,s)};Se.parseInline=pr.parseInline;Se.Parser=At;Se.parser=At.parse;Se.Renderer=so;Se.TextRenderer=hu;Se.Lexer=Pt;Se.lexer=Pt.lex;Se.Tokenizer=oo;Se.Hooks=Hl;Se.parse=Se;Se.options;Se.setOptions;Se.use;Se.walkTokens;Se.parseInline;At.parse;Pt.lex;/*! @license DOMPurify 3.2.3 | (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.3/LICENSE */const{entries:xf,setPrototypeOf:qc,isFrozen:rh,getPrototypeOf:lh,getOwnPropertyDescriptor:ih}=Object;let{freeze:st,seal:Mt,create:Sf}=Object,{apply:nu,construct:ru}=typeof Reflect<"u"&&Reflect;st||(st=function(s){return s});Mt||(Mt=function(s){return s});nu||(nu=function(s,o,a){return s.apply(o,a)});ru||(ru=function(s,o){return new s(...o)});const no=wt(Array.prototype.forEach),Jc=wt(Array.prototype.pop),zl=wt(Array.prototype.push),lo=wt(String.prototype.toLowerCase),Zs=wt(String.prototype.toString),ef=wt(String.prototype.match),Il=wt(String.prototype.replace),oh=wt(String.prototype.indexOf),sh=wt(String.prototype.trim),Ht=wt(Object.prototype.hasOwnProperty),it=wt(RegExp.prototype.test),Ol=uh(TypeError);function wt(d){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]:lo;qc&&qc(d,null);let a=s.length;for(;a--;){let f=s[a];if(typeof f=="string"){const p=o(f);p!==f&&(rh(s)||(s[a]=p),f=p)}d[f]=!0}return d}function ah(d){for(let s=0;s/gm),hh=Mt(/\$\{[\w\W]*}/gm),mh=Mt(/^data-[\-\w.\u00B7-\uFFFF]+$/),gh=Mt(/^aria-[\-\w]+$/),Ef=Mt(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),yh=Mt(/^(?:\w+script|data):/i),vh=Mt(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),_f=Mt(/^html$/i),wh=Mt(/^[a-z][.\w]*(-[.\w]+)+$/i);var of=Object.freeze({__proto__:null,ARIA_ATTR:gh,ATTR_WHITESPACE:vh,CUSTOM_ELEMENT:wh,DATA_ATTR:mh,DOCTYPE_NAME:_f,ERB_EXPR:ph,IS_ALLOWED_URI:Ef,IS_SCRIPT_OR_DATA:yh,MUSTACHE_EXPR:dh,TMPLIT_EXPR:hh});const jl={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,progressingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},kh=function(){return typeof window>"u"?null:window},xh=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 p="dompurify"+(a?"#"+a:"");try{return s.createPolicy(p,{createHTML(y){return y},createScriptURL(y){return y}})}catch{return console.warn("TrustedTypes policy "+p+" could not be created."),null}},sf=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function Tf(){let d=arguments.length>0&&arguments[0]!==void 0?arguments[0]:kh();const s=X=>Tf(X);if(s.version="3.2.3",s.removed=[],!d||!d.document||d.document.nodeType!==jl.document)return s.isSupported=!1,s;let{document:o}=d;const a=o,f=a.currentScript,{DocumentFragment:p,HTMLTemplateElement:y,Node:k,Element:T,NodeFilter:_,NamedNodeMap:S=d.NamedNodeMap||d.MozNamedAttrMap,HTMLFormElement:I,DOMParser:A,trustedTypes:D}=d,V=T.prototype,F=Dl(V,"cloneNode"),K=Dl(V,"remove"),he=Dl(V,"nextSibling"),ae=Dl(V,"childNodes"),Ee=Dl(V,"parentNode");if(typeof y=="function"){const X=o.createElement("template");X.content&&X.content.ownerDocument&&(o=X.content.ownerDocument)}let te,me="";const{implementation:ne,createNodeIterator:Ne,createDocumentFragment:ce,getElementsByTagName:kt}=o,{importNode:nt}=a;let ze=sf();s.isSupported=typeof xf=="function"&&typeof Ee=="function"&&ne&&ne.createHTMLDocument!==void 0;const{MUSTACHE_EXPR:J,ERB_EXPR:fe,TMPLIT_EXPR:ue,DATA_ATTR:de,ARIA_ATTR:we,IS_SCRIPT_OR_DATA:_e,ATTR_WHITESPACE:O,CUSTOM_ELEMENT:Q}=of;let{IS_ALLOWED_URI:j}=of,v=null;const C=se({},[...tf,...bs,...qs,...Js,...nf]);let Y=null;const re=se({},[...rf,...eu,...lf,...ro]);let Z=Object.seal(Sf(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}})),ie=null,ke=null,ge=!0,Te=!0,Ze=!1,Vn=!0,qt=!1,pn=!0,zt=!1,mr=!1,gr=!1,Wt=!1,Qn=!1,hn=!1,mn=!0,Jt=!1;const Qr="user-content-";let yr=!0,gn=!1,en={},tn=null;const vr=se({},["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 Gn=null;const Gr=se({},["audio","video","img","source","image","track"]);let nn=null;const yn=se({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),wr="http://www.w3.org/1998/Math/MathML",Yn="http://www.w3.org/2000/svg",xt="http://www.w3.org/1999/xhtml";let vn=xt,Xn=!1,Kn=null;const Yr=se({},[wr,Yn,xt],Zs);let wn=se({},["mi","mo","mn","ms","mtext"]),kn=se({},["annotation-xml"]);const xn=se({},["title","style","font","a","script"]);let St=null;const Vl=["application/xhtml+xml","text/html"],Ql="text/html";let Fe=null,rn=null;const Gl=o.createElement("form"),kr=function(g){return g instanceof RegExp||g instanceof Function},xr=function(){let g=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(rn&&rn===g)){if((!g||typeof g!="object")&&(g={}),g=dr(g),St=Vl.indexOf(g.PARSER_MEDIA_TYPE)===-1?Ql:g.PARSER_MEDIA_TYPE,Fe=St==="application/xhtml+xml"?Zs:lo,v=Ht(g,"ALLOWED_TAGS")?se({},g.ALLOWED_TAGS,Fe):C,Y=Ht(g,"ALLOWED_ATTR")?se({},g.ALLOWED_ATTR,Fe):re,Kn=Ht(g,"ALLOWED_NAMESPACES")?se({},g.ALLOWED_NAMESPACES,Zs):Yr,nn=Ht(g,"ADD_URI_SAFE_ATTR")?se(dr(yn),g.ADD_URI_SAFE_ATTR,Fe):yn,Gn=Ht(g,"ADD_DATA_URI_TAGS")?se(dr(Gr),g.ADD_DATA_URI_TAGS,Fe):Gr,tn=Ht(g,"FORBID_CONTENTS")?se({},g.FORBID_CONTENTS,Fe):vr,ie=Ht(g,"FORBID_TAGS")?se({},g.FORBID_TAGS,Fe):{},ke=Ht(g,"FORBID_ATTR")?se({},g.FORBID_ATTR,Fe):{},en=Ht(g,"USE_PROFILES")?g.USE_PROFILES:!1,ge=g.ALLOW_ARIA_ATTR!==!1,Te=g.ALLOW_DATA_ATTR!==!1,Ze=g.ALLOW_UNKNOWN_PROTOCOLS||!1,Vn=g.ALLOW_SELF_CLOSE_IN_ATTR!==!1,qt=g.SAFE_FOR_TEMPLATES||!1,pn=g.SAFE_FOR_XML!==!1,zt=g.WHOLE_DOCUMENT||!1,Wt=g.RETURN_DOM||!1,Qn=g.RETURN_DOM_FRAGMENT||!1,hn=g.RETURN_TRUSTED_TYPE||!1,gr=g.FORCE_BODY||!1,mn=g.SANITIZE_DOM!==!1,Jt=g.SANITIZE_NAMED_PROPS||!1,yr=g.KEEP_CONTENT!==!1,gn=g.IN_PLACE||!1,j=g.ALLOWED_URI_REGEXP||Ef,vn=g.NAMESPACE||xt,wn=g.MATHML_TEXT_INTEGRATION_POINTS||wn,kn=g.HTML_INTEGRATION_POINTS||kn,Z=g.CUSTOM_ELEMENT_HANDLING||{},g.CUSTOM_ELEMENT_HANDLING&&kr(g.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(Z.tagNameCheck=g.CUSTOM_ELEMENT_HANDLING.tagNameCheck),g.CUSTOM_ELEMENT_HANDLING&&kr(g.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(Z.attributeNameCheck=g.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),g.CUSTOM_ELEMENT_HANDLING&&typeof g.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(Z.allowCustomizedBuiltInElements=g.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),qt&&(Te=!1),Qn&&(Wt=!0),en&&(v=se({},nf),Y=[],en.html===!0&&(se(v,tf),se(Y,rf)),en.svg===!0&&(se(v,bs),se(Y,eu),se(Y,ro)),en.svgFilters===!0&&(se(v,qs),se(Y,eu),se(Y,ro)),en.mathMl===!0&&(se(v,Js),se(Y,lf),se(Y,ro))),g.ADD_TAGS&&(v===C&&(v=dr(v)),se(v,g.ADD_TAGS,Fe)),g.ADD_ATTR&&(Y===re&&(Y=dr(Y)),se(Y,g.ADD_ATTR,Fe)),g.ADD_URI_SAFE_ATTR&&se(nn,g.ADD_URI_SAFE_ATTR,Fe),g.FORBID_CONTENTS&&(tn===vr&&(tn=dr(tn)),se(tn,g.FORBID_CONTENTS,Fe)),yr&&(v["#text"]=!0),zt&&se(v,["html","head","body"]),v.table&&(se(v,["tbody"]),delete ie.tbody),g.TRUSTED_TYPES_POLICY){if(typeof g.TRUSTED_TYPES_POLICY.createHTML!="function")throw Ol('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof g.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw Ol('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');te=g.TRUSTED_TYPES_POLICY,me=te.createHTML("")}else te===void 0&&(te=xh(D,f)),te!==null&&typeof me=="string"&&(me=te.createHTML(""));st&&st(g),rn=g}},Sn=se({},[...bs,...qs,...ch]),Sr=se({},[...Js,...fh]),Zn=function(g){let M=Ee(g);(!M||!M.tagName)&&(M={namespaceURI:vn,tagName:"template"});const H=lo(g.tagName),Le=lo(M.tagName);return Kn[g.namespaceURI]?g.namespaceURI===Yn?M.namespaceURI===xt?H==="svg":M.namespaceURI===wr?H==="svg"&&(Le==="annotation-xml"||wn[Le]):!!Sn[H]:g.namespaceURI===wr?M.namespaceURI===xt?H==="math":M.namespaceURI===Yn?H==="math"&&kn[Le]:!!Sr[H]:g.namespaceURI===xt?M.namespaceURI===Yn&&!kn[Le]||M.namespaceURI===wr&&!wn[Le]?!1:!Sr[H]&&(xn[H]||!Sn[H]):!!(St==="application/xhtml+xml"&&Kn[g.namespaceURI]):!1},Et=function(g){zl(s.removed,{element:g});try{Ee(g).removeChild(g)}catch{K(g)}},Vt=function(g,M){try{zl(s.removed,{attribute:M.getAttributeNode(g),from:M})}catch{zl(s.removed,{attribute:null,from:M})}if(M.removeAttribute(g),g==="is")if(Wt||Qn)try{Et(M)}catch{}else try{M.setAttribute(g,"")}catch{}},bn=function(g){let M=null,H=null;if(gr)g=""+g;else{const le=ef(g,/^[\r\n\t ]+/);H=le&&le[0]}St==="application/xhtml+xml"&&vn===xt&&(g=''+g+"");const Le=te?te.createHTML(g):g;if(vn===xt)try{M=new A().parseFromString(Le,St)}catch{}if(!M||!M.documentElement){M=ne.createDocument(vn,"template",null);try{M.documentElement.innerHTML=Xn?me:Le}catch{}}const Ve=M.body||M.documentElement;return g&&H&&Ve.insertBefore(o.createTextNode(H),Ve.childNodes[0]||null),vn===xt?kt.call(M,zt?"html":"body")[0]:zt?M.documentElement:Ve},qn=function(g){return Ne.call(g.ownerDocument||g,g,_.SHOW_ELEMENT|_.SHOW_COMMENT|_.SHOW_TEXT|_.SHOW_PROCESSING_INSTRUCTION|_.SHOW_CDATA_SECTION,null)},Jn=function(g){return g instanceof I&&(typeof g.nodeName!="string"||typeof g.textContent!="string"||typeof g.removeChild!="function"||!(g.attributes instanceof S)||typeof g.removeAttribute!="function"||typeof g.setAttribute!="function"||typeof g.namespaceURI!="string"||typeof g.insertBefore!="function"||typeof g.hasChildNodes!="function")},Yl=function(g){return typeof k=="function"&&g instanceof k};function It(X,g,M){no(X,H=>{H.call(s,g,M,rn)})}const Xl=function(g){let M=null;if(It(ze.beforeSanitizeElements,g,null),Jn(g))return Et(g),!0;const H=Fe(g.nodeName);if(It(ze.uponSanitizeElement,g,{tagName:H,allowedTags:v}),g.hasChildNodes()&&!Yl(g.firstElementChild)&&it(/<[/\w]/g,g.innerHTML)&&it(/<[/\w]/g,g.textContent)||g.nodeType===jl.progressingInstruction||pn&&g.nodeType===jl.comment&&it(/<[/\w]/g,g.data))return Et(g),!0;if(!v[H]||ie[H]){if(!ie[H]&&Xr(H)&&(Z.tagNameCheck instanceof RegExp&&it(Z.tagNameCheck,H)||Z.tagNameCheck instanceof Function&&Z.tagNameCheck(H)))return!1;if(yr&&!tn[H]){const Le=Ee(g)||g.parentNode,Ve=ae(g)||g.childNodes;if(Ve&&Le){const le=Ve.length;for(let be=le-1;be>=0;--be){const ut=F(Ve[be],!0);ut.__removalCount=(g.__removalCount||0)+1,Le.insertBefore(ut,he(g))}}}return Et(g),!0}return g instanceof T&&!Zn(g)||(H==="noscript"||H==="noembed"||H==="noframes")&&it(/<\/no(script|embed|frames)/i,g.innerHTML)?(Et(g),!0):(qt&&g.nodeType===jl.text&&(M=g.textContent,no([J,fe,ue],Le=>{M=Il(M,Le," ")}),g.textContent!==M&&(zl(s.removed,{element:g.cloneNode()}),g.textContent=M)),It(ze.afterSanitizeElements,g,null),!1)},Qt=function(g,M,H){if(mn&&(M==="id"||M==="name")&&(H in o||H in Gl))return!1;if(!(Te&&!ke[M]&&it(de,M))){if(!(ge&&it(we,M))){if(!Y[M]||ke[M]){if(!(Xr(g)&&(Z.tagNameCheck instanceof RegExp&&it(Z.tagNameCheck,g)||Z.tagNameCheck instanceof Function&&Z.tagNameCheck(g))&&(Z.attributeNameCheck instanceof RegExp&&it(Z.attributeNameCheck,M)||Z.attributeNameCheck instanceof Function&&Z.attributeNameCheck(M))||M==="is"&&Z.allowCustomizedBuiltInElements&&(Z.tagNameCheck instanceof RegExp&&it(Z.tagNameCheck,H)||Z.tagNameCheck instanceof Function&&Z.tagNameCheck(H))))return!1}else if(!nn[M]){if(!it(j,Il(H,O,""))){if(!((M==="src"||M==="xlink:href"||M==="href")&&g!=="script"&&oh(H,"data:")===0&&Gn[g])){if(!(Ze&&!it(_e,Il(H,O,"")))){if(H)return!1}}}}}}return!0},Xr=function(g){return g!=="annotation-xml"&&ef(g,Q)},Kr=function(g){It(ze.beforeSanitizeAttributes,g,null);const{attributes:M}=g;if(!M||Jn(g))return;const H={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:Y,forceKeepAttr:void 0};let Le=M.length;for(;Le--;){const Ve=M[Le],{name:le,namespaceURI:be,value:ut}=Ve,En=Fe(le);let $e=le==="value"?ut:sh(ut);if(H.attrName=En,H.attrValue=$e,H.keepAttr=!0,H.forceKeepAttr=void 0,It(ze.uponSanitizeAttribute,g,H),$e=H.attrValue,Jt&&(En==="id"||En==="name")&&(Vt(le,g),$e=Qr+$e),pn&&it(/((--!?|])>)|<\/(style|title)/i,$e)){Vt(le,g);continue}if(H.forceKeepAttr||(Vt(le,g),!H.keepAttr))continue;if(!Vn&&it(/\/>/i,$e)){Vt(le,g);continue}qt&&no([J,fe,ue],Zr=>{$e=Il($e,Zr," ")});const Kl=Fe(g.nodeName);if(Qt(Kl,En,$e)){if(te&&typeof D=="object"&&typeof D.getAttributeType=="function"&&!be)switch(D.getAttributeType(Kl,En)){case"TrustedHTML":{$e=te.createHTML($e);break}case"TrustedScriptURL":{$e=te.createScriptURL($e);break}}try{be?g.setAttributeNS(be,le,$e):g.setAttribute(le,$e),Jn(g)?Et(g):Jc(s.removed)}catch{}}}It(ze.afterSanitizeAttributes,g,null)},co=function X(g){let M=null;const H=qn(g);for(It(ze.beforeSanitizeShadowDOM,g,null);M=H.nextNode();)It(ze.uponSanitizeShadowNode,M,null),Xl(M),Kr(M),M.content instanceof p&&X(M.content);It(ze.afterSanitizeShadowDOM,g,null)};return s.sanitize=function(X){let g=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},M=null,H=null,Le=null,Ve=null;if(Xn=!X,Xn&&(X=""),typeof X!="string"&&!Yl(X))if(typeof X.toString=="function"){if(X=X.toString(),typeof X!="string")throw Ol("dirty is not a string, aborting")}else throw Ol("toString is not a function");if(!s.isSupported)return X;if(mr||xr(g),s.removed=[],typeof X=="string"&&(gn=!1),gn){if(X.nodeName){const ut=Fe(X.nodeName);if(!v[ut]||ie[ut])throw Ol("root node is forbidden and cannot be sanitized in-place")}}else if(X instanceof k)M=bn(""),H=M.ownerDocument.importNode(X,!0),H.nodeType===jl.element&&H.nodeName==="BODY"||H.nodeName==="HTML"?M=H:M.appendChild(H);else{if(!Wt&&!qt&&!zt&&X.indexOf("<")===-1)return te&&hn?te.createHTML(X):X;if(M=bn(X),!M)return Wt?null:hn?me:""}M&&gr&&Et(M.firstChild);const le=qn(gn?X:M);for(;Le=le.nextNode();)Xl(Le),Kr(Le),Le.content instanceof p&&co(Le.content);if(gn)return X;if(Wt){if(Qn)for(Ve=ce.call(M.ownerDocument);M.firstChild;)Ve.appendChild(M.firstChild);else Ve=M;return(Y.shadowroot||Y.shadowrootmode)&&(Ve=nt.call(a,Ve,!0)),Ve}let be=zt?M.outerHTML:M.innerHTML;return zt&&v["!doctype"]&&M.ownerDocument&&M.ownerDocument.doctype&&M.ownerDocument.doctype.name&&it(_f,M.ownerDocument.doctype.name)&&(be=" -`+be),qt&&no([J,fe,ue],ut=>{be=Il(be,ut," ")}),te&&hn?te.createHTML(be):be},s.setConfig=function(){let X=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};xr(X),mr=!0},s.clearConfig=function(){rn=null,mr=!1},s.isValidAttribute=function(X,g,M){rn||xr({});const H=Fe(X),Le=Fe(g);return Qt(H,Le,M)},s.addHook=function(X,g){typeof g=="function"&&zl(ze[X],g)},s.removeHook=function(X){return Jc(ze[X])},s.removeHooks=function(X){ze[X]=[]},s.removeAllHooks=function(){ze=sf()},s}var Sh=Tf();function Eh(d){return L.jsxs("svg",{...d,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 _h(d){return L.jsxs("svg",{...d,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"})]})}var lu=function(){return(lu=Object.assign||function(d){for(var s,o=1,a=arguments.length;of.type==="text"?f.text.length>0?L.jsx(Rh,{dynamic:!0,children:L.jsx("span",{className:"markdown",dangerouslySetInnerHTML:{__html:Nh(f.text)}})},p):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"})]},p):f.type==="image"?L.jsx("img",{src:f.image,className:"w-full max-w-[384px] h-auto max-h-[300px] object-contain rounded-md"},p):null)})})]})}function Ph({messages:d}){const s=d.length===0;return 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:L.jsx(Th,{children:s?L.jsx("div",{className:"text-xl",children:"Ready!"}):d.map((o,a)=>L.jsx(Lh,{...o},`message-${a}`))})})}function cf(d){return L.jsxs("svg",{...d,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 Ah(d){return L.jsxs("svg",{...d,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 Mh(d){const s=d==0?0:Math.floor(Math.log(d)/Math.log(1024));return+(d/Math.pow(1024,s)).toFixed(2)*1+["B","kB","MB","GB","TB"][s]}function zh({text:d,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:[d," (",s.toFixed(2),"%",isNaN(o)?"":` of ${Mh(o)}`,")"]})})}function Ih(d){return L.jsx("svg",{...d,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:"m2.25 15.75 5.159-5.159a2.25 2.25 0 0 1 3.182 0l5.159 5.159m-1.5-1.5 1.409-1.409a2.25 2.25 0 0 1 3.182 0l2.909 2.909m-18 3.75h16.5a1.5 1.5 0 0 0 1.5-1.5V6a1.5 1.5 0 0 0-1.5-1.5H3.75A1.5 1.5 0 0 0 2.25 6v12a1.5 1.5 0 0 0 1.5 1.5Zm10.5-11.25h.008v.008h-.008V8.25Zm.375 0a.375.375 0 1 1-.75 0 .375.375 0 0 1 .75 0Z"})})}function Oh(d){return L.jsx("svg",{...d,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:"m9.75 9.75 4.5 4.5m0-4.5-4.5 4.5M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z"})})}function Dh({src:d,onRemove:s,...o}){const[a,f]=ve.useState(!1);return L.jsxs("div",{...o,onMouseEnter:()=>f(!0),onMouseLeave:()=>f(!1),children:[L.jsx(Oh,{onClick:s,className:`absolute top-0 right-0 cursor-pointer dark:fill-gray-400 dark:text-gray-100 fill-gray-200 text-gray-800 ${a?"":"hidden"}`}),L.jsx("img",{src:d,alt:"Upload preview",className:"w-full h-full object-cover rounded-md"})]})}const jh=!!navigator.gpu,Fh=120,Uh=[{title:"Describe this image",text:"Can you describe this image?",images:["https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/new-york.jpg"]},{title:"Handwriting recognition",text:"What does this say?",images:["https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/handwritten-math.jpg"]},{title:"Chart analysis",text:"Where do the severe droughts happen according to this diagram?",images:["https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/weather-events-diagram.png"]}];function $h(){const d=ve.useRef(null),s=ve.useRef(null),o=ve.useRef(null),a=ve.useRef(null),[f,p]=ve.useState(null),[y,k]=ve.useState(null),[T,_]=ve.useState(""),[S,I]=ve.useState([]),[A,D]=ve.useState(!1),[V,F]=ve.useState(""),[K,he]=ve.useState([]),[ae,Ee]=ve.useState([]),[te,me]=ve.useState(null),[ne,Ne]=ve.useState(null);function ce(J,fe){const ue=[...fe.map(de=>({type:"image",image:de})),{type:"text",text:J}];Ee(de=>[...de,{role:"user",content:ue}]),me(null),D(!0),F(""),he([])}function kt(){d.current.postMessage({type:"interrupt"})}ve.useEffect(()=>{nt()},[V]);function nt(){if(!s.current)return;const J=s.current;J.style.height="auto";const fe=Math.min(Math.max(J.scrollHeight,24),200);J.style.height=`${fe}px`}ve.useEffect(()=>{d.current||(d.current=new Worker(new URL("/assets/worker-y4d95NqO.js",import.meta.url),{type:"module"}),d.current.postMessage({type:"check"}));const J=ue=>{switch(ue.data.status){case"loading":p("loading"),_(ue.data.data);break;case"initiate":I(de=>[...de,ue.data]);break;case"progress":I(de=>de.map(we=>we.file===ue.data.file?{...we,...ue.data}:we));break;case"done":I(de=>de.filter(we=>we.file!==ue.data.file));break;case"ready":p("ready");break;case"start":Ee(de=>[...de,{role:"assistant",content:[{type:"text",text:""}]}]);break;case"update":{const{output:de,tps:we,numTokens:_e}=ue.data;me(we),Ne(_e),Ee(O=>{const Q=[...O],j=Q.at(-1);return Q[Q.length-1]={...j,content:[{type:"text",text:j.content[0].text+de}]},Q})}break;case"complete":D(!1);break;case"error":k(ue.data.data);break}},fe=ue=>{console.error("Worker error:",ue)};return d.current.addEventListener("message",J),d.current.addEventListener("error",fe),window.addEventListener("resize",nt),()=>{d.current.removeEventListener("message",J),d.current.removeEventListener("error",fe),window.removeEventListener("resize",nt)}},[]),ve.useEffect(()=>{ae.filter(J=>J.role==="user").length!==0&&ae.at(-1).role!=="assistant"&&(me(null),d.current.postMessage({type:"generate",data:ae}))},[ae,A]),ve.useEffect(()=>{if(!o.current||!A)return;const J=o.current;J.scrollHeight-J.scrollTop-J.clientHeight0&&K.length>0;return jh?L.jsxs("div",{className:"flex flex-col h-screen mx-auto items justify-end text-gray-800 dark:text-gray-200 bg-white dark:bg-gray-900",children:[f===null&&ae.length===0&&L.jsxs("div",{className:"h-full overflow-auto scrollbar-thin flex justify-center items-center flex-col relative",children:[L.jsxs("div",{className:"flex flex-col items-center mb-1 max-w-[360px] text-center",children:[L.jsx("img",{src:"logo.png",width:"100%",height:"auto",className:"block drop-shadow-lg bg-transparent"}),L.jsx("h1",{className:"text-4xl font-bold mb-1",children:"SmolVLM WebGPU"}),L.jsxs("h2",{className:"font-semibold",children:["The smallest multimodal model in the world.",L.jsx("br",{}),"Designed for efficiency."]})]}),L.jsxs("div",{className:"flex flex-col items-center px-4",children:[L.jsxs("p",{className:"max-w-[500px] mb-4",children:[L.jsx("br",{}),"You are about to load"," ",L.jsx("a",{href:"https://huggingface.co/HuggingFaceTB/SmolVLM-256M-Instruct",target:"_blank",rel:"noreferrer",className:"font-medium underline",children:"SmolVLM-256M-Instruct"}),", a 256M parameter multimodal model optimized for in-browser inference. Everything runs entirely in your browser with"," ",L.jsx("a",{href:"https://huggingface.co/docs/transformers.js",target:"_blank",rel:"noreferrer",className:"underline",children:"🤗 Transformers.js"})," ","and ONNX Runtime Web, meaning no data is sent to a server. Once loaded, it can even be used offline. The source code for the demo is available on"," ",L.jsx("a",{href:"https://github.com/huggingface/transformers.js-examples/tree/main/smolvlm-webgpu",target:"_blank",rel:"noreferrer",className:"font-medium underline",children:"GitHub"}),"."]}),y&&L.jsxs("div",{className:"text-red-500 text-center mb-2",children:[L.jsx("p",{className:"mb-1",children:"Unable to load model due to the following error:"}),L.jsx("p",{className:"text-sm",children:y})]}),L.jsx("button",{className:"border border-gray-300 dark:border-gray-600 px-4 py-2 rounded-lg bg-blue-400 text-white hover:bg-blue-500 disabled:bg-blue-100 cursor-pointer disabled:cursor-not-allowed select-none",onClick:()=>{d.current.postMessage({type:"load"}),p("loading")},disabled:f!==null||y!==null,children:"Load model"})]})]}),f==="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:T}),S.map(({file:J,progress:fe,total:ue},de)=>L.jsx(zh,{text:J,percentage:fe,total:ue},de))]})}),f==="ready"&&L.jsxs("div",{ref:o,className:"overflow-y-auto scrollbar-thin w-full flex flex-col items-center h-full",children:[L.jsx(Ph,{messages:ae}),ae.length===0&&L.jsx("div",{className:"flex",children:Uh.map((J,fe)=>L.jsxs("div",{className:"max-w-[250px] m-1 border border-gray-300 dark:border-gray-600 rounded-md p-2 bg-gray-100 dark:bg-gray-700 cursor-pointer",onClick:()=>ce(J.text,J.images),children:[J.text,J.images.map((ue,de)=>L.jsx("img",{src:ue,className:"w-full h-auto mt-2",alt:"Example"},de))]},fe))}),L.jsx("p",{className:"text-center text-sm min-h-6 text-gray-500 dark:text-gray-300",children:te&&ae.length>0&&L.jsxs(L.Fragment,{children:[!A&&L.jsxs("span",{children:["Generated ",ne," tokens in"," ",(ne/te).toFixed(2)," seconds ("]}),L.jsxs(L.Fragment,{children:[L.jsx("span",{className:"font-medium text-center mr-1 text-black dark:text-white",children:te.toFixed(2)}),L.jsx("span",{className:"text-gray-500 dark:text-gray-300",children:"tokens/second"})]}),!A&&L.jsxs(L.Fragment,{children:[L.jsx("span",{className:"mr-1",children:")."}),L.jsx("span",{className:"underline cursor-pointer",onClick:()=>{d.current.postMessage({type:"reset"}),Ee([])},children:"Reset"})]})]})})]}),L.jsxs("div",{className:"mt-2 border border-gray-300 dark:bg-gray-700 rounded-lg w-[600px] max-w-[80%] max-h-[200px] mx-auto relative mb-3 flex",children:[L.jsxs("label",{htmlFor:"file-upload",className:f==="ready"?"cursor-pointer":"cursor-not-allowed pointer-events-none",children:[L.jsx(Ih,{className:`h-8 w-8 p-1 rounded-md ${f==="ready"?"text-gray-800 dark:text-gray-100":"text-gray-400 dark:text-gray-500"} absolute bottom-3 left-1.5`}),L.jsx("input",{ref:a,id:"file-upload",type:"file",accept:"image/*",className:"hidden",multiple:!0,onInput:async J=>{const fe=Array.from(J.target.files);if(fe.length===0)return;const ue=fe.map(we=>new Promise((_e,O)=>{const Q=new FileReader;Q.onload=j=>_e(j.target.result),Q.onerror=O,Q.readAsDataURL(we)})),de=await Promise.all(ue);he(we=>[...we,...de]),J.target.value=""}})]}),L.jsxs("div",{className:"w-full flex flex-col",children:[L.jsx("div",{className:"flex w-full",children:K.map((J,fe)=>L.jsx(Dh,{onRemove:()=>{he(ue=>ue.filter((de,we)=>we!==fe))},src:J,className:"w-20 h-20 min-w-20 min-h-20 relative p-2"},fe))}),L.jsx("textarea",{ref:s,className:"scrollbar-thin w-full pl-11 pr-12 dark:bg-gray-700 py-4 rounded-lg bg-transparent border-none outline-none text-gray-800 disabled:text-gray-400 dark:text-gray-100 placeholder-gray-500 disabled:placeholder-gray-200 dark:placeholder-gray-300 dark:disabled:placeholder-gray-500 resize-none disabled:cursor-not-allowed",placeholder:"Select at least one image and enter message here...",type:"text",rows:1,value:V,disabled:f!=="ready",title:f==="ready"?"Model is ready":"Model not loaded yet",onKeyDown:J=>{ze&&!A&&J.key==="Enter"&&!J.shiftKey&&(J.preventDefault(),ce(V,K))},onInput:J=>F(J.target.value)})]}),A?L.jsx("div",{className:"cursor-pointer",onClick:kt,children:L.jsx(Ah,{className:"h-8 w-8 p-1 rounded-md text-gray-800 dark:text-gray-100 absolute right-3 bottom-3"})}):ze?L.jsx("div",{className:"cursor-pointer",onClick:()=>ce(V,K),children:L.jsx(cf,{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(cf,{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(ve.StrictMode,{children:L.jsx($h,{})})); diff --git a/assets/index-DKPNWo-8.js b/assets/index-DKPNWo-8.js new file mode 100644 index 0000000000000000000000000000000000000000..5580fd09eaa47233b2b400940de917662565512f --- /dev/null +++ b/assets/index-DKPNWo-8.js @@ -0,0 +1,96 @@ +var fp=Object.defineProperty;var dp=(d,s,o)=>s in d?fp(d,s,{enumerable:!0,configurable:!0,writable:!0,value:o}):d[s]=o;var Re=(d,s,o)=>dp(d,typeof s!="symbol"?s+"":s,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 p of f)if(p.type==="childList")for(const y of p.addedNodes)y.tagName==="LINK"&&y.rel==="modulepreload"&&a(y)}).observe(document,{childList:!0,subtree:!0});function o(f){const p={};return f.integrity&&(p.integrity=f.integrity),f.referrerPolicy&&(p.referrerPolicy=f.referrerPolicy),f.crossOrigin==="use-credentials"?p.credentials="include":f.crossOrigin==="anonymous"?p.credentials="omit":p.credentials="same-origin",p}function a(f){if(f.ep)return;f.ep=!0;const p=o(f);fetch(f.href,p)}})();function pp(d){return d&&d.__esModule&&Object.prototype.hasOwnProperty.call(d,"default")?d.default:d}var Qs={exports:{}},Pl={},Gs={exports:{}},oe={};/** + * @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 Fc;function hp(){if(Fc)return oe;Fc=1;var d=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"),p=Symbol.for("react.provider"),y=Symbol.for("react.context"),k=Symbol.for("react.forward_ref"),T=Symbol.for("react.suspense"),_=Symbol.for("react.memo"),S=Symbol.for("react.lazy"),I=Symbol.iterator;function A(v){return v===null||typeof v!="object"?null:(v=I&&v[I]||v["@@iterator"],typeof v=="function"?v:null)}var D={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},V=Object.assign,F={};function K(v,C,X){this.props=v,this.context=C,this.refs=F,this.updater=X||D}K.prototype.isReactComponent={},K.prototype.setState=function(v,C){if(typeof v!="object"&&typeof v!="function"&&v!=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,v,C,"setState")},K.prototype.forceUpdate=function(v){this.updater.enqueueForceUpdate(this,v,"forceUpdate")};function he(){}he.prototype=K.prototype;function ae(v,C,X){this.props=v,this.context=C,this.refs=F,this.updater=X||D}var Ee=ae.prototype=new he;Ee.constructor=ae,V(Ee,K.prototype),Ee.isPureReactComponent=!0;var te=Array.isArray,me=Object.prototype.hasOwnProperty,ne={current:null},Ne={key:!0,ref:!0,__self:!0,__source:!0};function ce(v,C,X){var re,Z={},ie=null,ke=null;if(C!=null)for(re in C.ref!==void 0&&(ke=C.ref),C.key!==void 0&&(ie=""+C.key),C)me.call(C,re)&&!Ne.hasOwnProperty(re)&&(Z[re]=C[re]);var ge=arguments.length-2;if(ge===1)Z.children=X;else if(1>>1,C=O[v];if(0>>1;vf(Z,j))ief(ke,Z)?(O[v]=ke,O[ie]=j,v=ie):(O[v]=Z,O[re]=j,v=re);else if(ief(ke,j))O[v]=ke,O[ie]=j,v=ie;else break e}}return Q}function f(O,Q){var j=O.sortIndex-Q.sortIndex;return j!==0?j:O.id-Q.id}if(typeof performance=="object"&&typeof performance.now=="function"){var p=performance;d.unstable_now=function(){return p.now()}}else{var y=Date,k=y.now();d.unstable_now=function(){return y.now()-k}}var T=[],_=[],S=1,I=null,A=3,D=!1,V=!1,F=!1,K=typeof setTimeout=="function"?setTimeout:null,he=typeof clearTimeout=="function"?clearTimeout:null,ae=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function Ee(O){for(var Q=o(_);Q!==null;){if(Q.callback===null)a(_);else if(Q.startTime<=O)a(_),Q.sortIndex=Q.expirationTime,s(T,Q);else break;Q=o(_)}}function te(O){if(F=!1,Ee(O),!V)if(o(T)!==null)V=!0,we(me);else{var Q=o(_);Q!==null&&_e(te,Q.startTime-O)}}function me(O,Q){V=!1,F&&(F=!1,he(ce),ce=-1),D=!0;var j=A;try{for(Ee(Q),I=o(T);I!==null&&(!(I.expirationTime>Q)||O&&!Le());){var v=I.callback;if(typeof v=="function"){I.callback=null,A=I.priorityLevel;var C=v(I.expirationTime<=Q);Q=d.unstable_now(),typeof C=="function"?I.callback=C:I===o(T)&&a(T),Ee(Q)}else a(T);I=o(T)}if(I!==null)var X=!0;else{var re=o(_);re!==null&&_e(te,re.startTime-Q),X=!1}return X}finally{I=null,A=j,D=!1}}var ne=!1,Ne=null,ce=-1,kt=5,nt=-1;function Le(){return!(d.unstable_now()-ntO||125v?(O.sortIndex=j,s(_,O),o(T)===null&&O===o(_)&&(F?(he(ce),ce=-1):F=!0,_e(te,j-v))):(O.sortIndex=C,s(T,O),V||D||(V=!0,we(me))),O},d.unstable_shouldYield=Le,d.unstable_wrapCallback=function(O){var Q=A;return function(){var j=A;A=Q;try{return O.apply(this,arguments)}finally{A=j}}}}(Ks)),Ks}var Wc;function vp(){return Wc||(Wc=1,Xs.exports=yp()),Xs.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 Vc;function wp(){if(Vc)return mt;Vc=1;var d=ou(),s=vp();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"),T=Object.prototype.hasOwnProperty,_=/^[: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]*$/,S={},I={};function A(e){return T.call(I,e)?!0:T.call(S,e)?!1:_.test(e)?I[e]=!0:(S[e]=!0,!1)}function D(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 V(e,t,n,r){if(t===null||typeof t>"u"||D(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 F(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 K={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){K[e]=new F(e,0,!1,e,null,!1,!1)}),[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];K[t]=new F(t,1,!1,e[1],null,!1,!1)}),["contentEditable","draggable","spellCheck","value"].forEach(function(e){K[e]=new F(e,2,!1,e.toLowerCase(),null,!1,!1)}),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){K[e]=new F(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){K[e]=new F(e,3,!1,e.toLowerCase(),null,!1,!1)}),["checked","multiple","muted","selected"].forEach(function(e){K[e]=new F(e,3,!0,e,null,!1,!1)}),["capture","download"].forEach(function(e){K[e]=new F(e,4,!1,e,null,!1,!1)}),["cols","rows","size","span"].forEach(function(e){K[e]=new F(e,6,!1,e,null,!1,!1)}),["rowSpan","start"].forEach(function(e){K[e]=new F(e,5,!1,e.toLowerCase(),null,!1,!1)});var he=/[\-:]([a-z])/g;function ae(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(he,ae);K[t]=new F(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(he,ae);K[t]=new F(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(he,ae);K[t]=new F(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)}),["tabIndex","crossOrigin"].forEach(function(e){K[e]=new F(e,1,!1,e.toLowerCase(),null,!1,!1)}),K.xlinkHref=new F("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1),["src","href","action","formAction"].forEach(function(e){K[e]=new F(e,1,!1,e.toLowerCase(),null,!0,!0)});function Ee(e,t,n,r){var l=K.hasOwnProperty(t)?K[t]:null;(l!==null?l.type!==0:r||!(2c||l[u]!==i[c]){var h=` +`+l[u].replace(" at new "," at ");return e.displayName&&h.includes("")&&(h=h.replace("",e.displayName)),h}while(1<=u&&0<=c);break}}}finally{X=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?C(e):""}function Z(e){switch(e.tag){case 5:return C(e.type);case 16:return C("Lazy");case 13:return C("Suspense");case 19:return C("SuspenseList");case 0:case 2:case 15:return e=re(e.type,!1),e;case 11:return e=re(e.type.render,!1),e;case 1:return e=re(e.type,!0),e;default:return""}}function ie(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 Ne:return"Fragment";case ne:return"Portal";case kt:return"Profiler";case ce:return"StrictMode";case fe:return"Suspense";case ue:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case Le:return(e.displayName||"Context")+".Consumer";case nt:return(e._context.displayName||"Context")+".Provider";case J:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case de:return t=e.displayName||null,t!==null?t:ie(e.type)||"Memo";case we:t=e._payload,e=e._init;try{return ie(e(t))}catch{}}return null}function ke(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 ie(t);case 8:return t===ce?"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 ge(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function Te(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function Ze(e){var t=Te(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 Vn(e){e._valueTracker||(e._valueTracker=Ze(e))}function qt(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=Te(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function pn(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 zt(e,t){var n=t.checked;return j({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function mr(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=ge(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 gr(e,t){t=t.checked,t!=null&&Ee(e,"checked",t,!1)}function Wt(e,t){gr(e,t);var n=ge(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")?hn(e,t.type,n):t.hasOwnProperty("defaultValue")&&hn(e,t.type,ge(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function Qn(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 hn(e,t,n){(t!=="number"||pn(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var mn=Array.isArray;function Jt(e,t,n,r){if(e=e.options,t){t={};for(var l=0;l"+t.valueOf().toString()+"",t=Gn.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function nn(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var yn={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},wr=["Webkit","ms","Moz","O"];Object.keys(yn).forEach(function(e){wr.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),yn[t]=yn[e]})});function Yn(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||yn.hasOwnProperty(e)&&yn[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=Yn(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,l):e[n]=l}}var vn=j({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 Xn(e,t){if(t){if(vn[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 Kn(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 Yr=null;function wn(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var kn=null,xn=null,St=null;function Vl(e){if(e=ml(e)){if(typeof kn!="function")throw Error(o(280));var t=e.stateNode;t&&(t=mi(t),kn(e.stateNode,e.type,t))}}function Ql(e){xn?St?St.push(e):St=[e]:xn=e}function Fe(){if(xn){var e=xn,t=St;if(St=xn=null,Vl(e),t)for(e=0;e>>=0,e===0?32:31-(Rf(e)/Nf|0)|0}var bl=64,ql=4194304;function br(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 Jl(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=br(c):(i&=u,i!==0&&(r=br(i)))}else u=n&~l,u!==0?r=br(u):i!==0&&(r=br(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-Ot(t),e[t]=n}function Mf(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=ol),Au=" ",Mu=!1;function zu(e,t){switch(e){case"keyup":return od.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Iu(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var Tr=!1;function ud(e,t){switch(e){case"compositionend":return Iu(t);case"keypress":return t.which!==32?null:(Mu=!0,Au);case"textInput":return e=t.data,e===Au&&Mu?null:e;default:return null}}function ad(e,t){if(Tr)return e==="compositionend"||!To&&zu(e,t)?(e=Tu(),li=wo=Nn=null,Tr=!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=Bu(n)}}function Wu(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?Wu(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function Vu(){for(var e=window,t=pn();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=pn(e.document)}return t}function No(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 vd(e){var t=Vu(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&Wu(n.ownerDocument.documentElement,n)){if(r!==null&&No(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=Hu(n,i);var u=Hu(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,Cr=null,Lo=null,cl=null,Po=!1;function Qu(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;Po||Cr==null||Cr!==pn(r)||(r=Cr,"selectionStart"in r&&No(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}),cl&&al(cl,r)||(cl=r,r=di(Lo,"onSelect"),0Ar||(e.current=Ho[Ar],Ho[Ar]=null,Ar--)}function Ae(e,t){Ar++,Ho[Ar]=e.current,e.current=t}var Mn={},qe=An(Mn),ct=An(!1),tr=Mn;function Mr(e,t){var n=e.type.contextTypes;if(!n)return Mn;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 gi(){ze(ct),ze(qe)}function oa(e,t,n){if(qe.current!==Mn)throw Error(o(168));Ae(qe,t),Ae(ct,n)}function sa(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,ke(e)||"Unknown",l));return j({},n,r)}function yi(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||Mn,tr=qe.current,Ae(qe,e),Ae(ct,ct.current),!0}function ua(e,t,n){var r=e.stateNode;if(!r)throw Error(o(169));n?(e=sa(e,t,tr),r.__reactInternalMemoizedMergedChildContext=e,ze(ct),ze(qe),Ae(qe,e)):ze(ct),Ae(ct,n)}var on=null,vi=!1,Wo=!1;function aa(e){on===null?on=[e]:on.push(e)}function Pd(e){vi=!0,aa(e)}function zn(){if(!Wo&&on!==null){Wo=!0;var e=0,t=xe;try{var n=on;for(xe=1;e>=u,l-=u,sn=1<<32-Ot(t)+l|n<ee?(Ye=q,q=null):Ye=q.sibling;var ye=R(w,q,x[ee],z);if(ye===null){q===null&&(q=Ye);break}e&&q&&ye.alternate===null&&t(w,q),g=i(ye,g,ee),b===null?G=ye:b.sibling=ye,b=ye,q=Ye}if(ee===x.length)return n(w,q),Ie&&rr(w,ee),G;if(q===null){for(;eeee?(Ye=q,q=null):Ye=q.sibling;var Hn=R(w,q,ye.value,z);if(Hn===null){q===null&&(q=Ye);break}e&&q&&Hn.alternate===null&&t(w,q),g=i(Hn,g,ee),b===null?G=Hn:b.sibling=Hn,b=Hn,q=Ye}if(ye.done)return n(w,q),Ie&&rr(w,ee),G;if(q===null){for(;!ye.done;ee++,ye=x.next())ye=P(w,ye.value,z),ye!==null&&(g=i(ye,g,ee),b===null?G=ye:b.sibling=ye,b=ye);return Ie&&rr(w,ee),G}for(q=r(w,q);!ye.done;ee++,ye=x.next())ye=U(q,w,ee,ye.value,z),ye!==null&&(e&&ye.alternate!==null&&q.delete(ye.key===null?ee:ye.key),g=i(ye,g,ee),b===null?G=ye:b.sibling=ye,b=ye);return e&&q.forEach(function(cp){return t(w,cp)}),Ie&&rr(w,ee),G}function Ue(w,g,x,z){if(typeof x=="object"&&x!==null&&x.type===Ne&&x.key===null&&(x=x.props.children),typeof x=="object"&&x!==null){switch(x.$$typeof){case me:e:{for(var G=x.key,b=g;b!==null;){if(b.key===G){if(G=x.type,G===Ne){if(b.tag===7){n(w,b.sibling),g=l(b,x.props.children),g.return=w,w=g;break e}}else if(b.elementType===G||typeof G=="object"&&G!==null&&G.$$typeof===we&&ma(G)===b.type){n(w,b.sibling),g=l(b,x.props),g.ref=gl(w,b,x),g.return=w,w=g;break e}n(w,b);break}else t(w,b);b=b.sibling}x.type===Ne?(g=fr(x.props.children,w.mode,z,x.key),g.return=w,w=g):(z=Gi(x.type,x.key,x.props,null,w.mode,z),z.ref=gl(w,g,x),z.return=w,w=z)}return u(w);case ne:e:{for(b=x.key;g!==null;){if(g.key===b)if(g.tag===4&&g.stateNode.containerInfo===x.containerInfo&&g.stateNode.implementation===x.implementation){n(w,g.sibling),g=l(g,x.children||[]),g.return=w,w=g;break e}else{n(w,g);break}else t(w,g);g=g.sibling}g=$s(x,w.mode,z),g.return=w,w=g}return u(w);case we:return b=x._init,Ue(w,g,b(x._payload),z)}if(mn(x))return B(w,g,x,z);if(Q(x))return W(w,g,x,z);Si(w,x)}return typeof x=="string"&&x!==""||typeof x=="number"?(x=""+x,g!==null&&g.tag===6?(n(w,g.sibling),g=l(g,x),g.return=w,w=g):(n(w,g),g=Us(x,w.mode,z),g.return=w,w=g),u(w)):n(w,g)}return Ue}var Dr=ga(!0),ya=ga(!1),Ei=An(null),_i=null,jr=null,Ko=null;function Zo(){Ko=jr=_i=null}function bo(e){var t=Ei.current;ze(Ei),e._currentValue=t}function qo(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 Fr(e,t){_i=e,Ko=jr=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(Ko!==e)if(e={context:e,memoizedValue:t,next:null},jr===null){if(_i===null)throw Error(o(308));jr=e,_i.dependencies={lanes:0,firstContext:e}}else jr=jr.next=e;return t}var lr=null;function Jo(e){lr===null?lr=[e]:lr.push(e)}function va(e,t,n,r){var l=t.interleaved;return l===null?(n.next=n,Jo(t)):(n.next=l.next,l.next=n),t.interleaved=n,an(e,r)}function an(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 es(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function wa(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 cn(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,(pe&2)!==0){var l=r.pending;return l===null?t.next=t:(t.next=l.next,l.next=t),r.pending=t,an(e,n)}return l=r.interleaved,l===null?(t.next=t,Jo(r)):(t.next=l.next,l.next=t),r.interleaved=t,an(e,n)}function Ti(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,ho(e,n)}}function ka(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 Ci(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 h=c,E=h.next;h.next=null,u===null?i=E:u.next=E,u=h;var N=e.alternate;N!==null&&(N=N.updateQueue,c=N.lastBaseUpdate,c!==u&&(c===null?N.firstBaseUpdate=E:c.next=E,N.lastBaseUpdate=h))}if(i!==null){var P=l.baseState;u=0,N=E=h=null,c=i;do{var R=c.lane,U=c.eventTime;if((r&R)===R){N!==null&&(N=N.next={eventTime:U,lane:0,tag:c.tag,payload:c.payload,callback:c.callback,next:null});e:{var B=e,W=c;switch(R=t,U=n,W.tag){case 1:if(B=W.payload,typeof B=="function"){P=B.call(U,P,R);break e}P=B;break e;case 3:B.flags=B.flags&-65537|128;case 0:if(B=W.payload,R=typeof B=="function"?B.call(U,P,R):B,R==null)break e;P=j({},P,R);break e;case 2:In=!0}}c.callback!==null&&c.lane!==0&&(e.flags|=64,R=l.effects,R===null?l.effects=[c]:R.push(c))}else U={eventTime:U,lane:R,tag:c.tag,payload:c.payload,callback:c.callback,next:null},N===null?(E=N=U,h=P):N=N.next=U,u|=R;if(c=c.next,c===null){if(c=l.shared.pending,c===null)break;R=c,c=R.next,R.next=null,l.lastBaseUpdate=R,l.shared.pending=null}}while(!0);if(N===null&&(h=P),l.baseState=h,l.firstBaseUpdate=E,l.lastBaseUpdate=N,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);sr|=u,e.lanes=u,e.memoizedState=P}}function xa(e,t,n){if(e=t.effects,t.effects=null,e!==null)for(t=0;tn?n:4,e(!0);var r=is.transition;is.transition={};try{e(!1),t()}finally{xe=n,is.transition=r}}function $a(){return Rt().memoizedState}function Id(e,t,n){var r=Un(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},Ba(e))Ha(t,n);else if(n=va(e,t,n,r),n!==null){var l=lt();Bt(n,e,r,l),Wa(n,t,r)}}function Od(e,t,n){var r=Un(e),l={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(Ba(e))Ha(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,Dt(c,u)){var h=t.interleaved;h===null?(l.next=l,Jo(t)):(l.next=h.next,h.next=l),t.interleaved=l;return}}catch{}finally{}n=va(e,t,l,r),n!==null&&(l=lt(),Bt(n,e,r,l),Wa(n,t,r))}}function Ba(e){var t=e.alternate;return e===De||t!==null&&t===De}function Ha(e,t){kl=Li=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function Wa(e,t,n){if((n&4194240)!==0){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,ho(e,n)}}var Mi={readContext:Ct,useCallback:Je,useContext:Je,useEffect:Je,useImperativeHandle:Je,useInsertionEffect:Je,useLayoutEffect:Je,useMemo:Je,useReducer:Je,useRef:Je,useState:Je,useDebugValue:Je,useDeferredValue:Je,useTransition:Je,useMutableSource:Je,useSyncExternalStore:Je,useId:Je,unstable_isNewReconciler:!1},Dd={readContext:Ct,useCallback:function(e,t){return Kt().memoizedState=[e,t===void 0?null:t],e},useContext:Ct,useEffect:Ma,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,Pi(4194308,4,Oa.bind(null,t,e),n)},useLayoutEffect:function(e,t){return Pi(4194308,4,e,t)},useInsertionEffect:function(e,t){return Pi(4,2,e,t)},useMemo:function(e,t){var n=Kt();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=Kt();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=Id.bind(null,De,e),[r.memoizedState,e]},useRef:function(e){var t=Kt();return e={current:e},t.memoizedState=e},useState:Pa,useDebugValue:ds,useDeferredValue:function(e){return Kt().memoizedState=e},useTransition:function(){var e=Pa(!1),t=e[0];return e=zd.bind(null,e[1]),Kt().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=De,l=Kt();if(Ie){if(n===void 0)throw Error(o(407));n=n()}else{if(n=t(),Ge===null)throw Error(o(349));(or&30)!==0||Ta(r,t,n)}l.memoizedState=n;var i={value:n,getSnapshot:t};return l.queue=i,Ma(Ra.bind(null,r,i,e),[e]),r.flags|=2048,El(9,Ca.bind(null,r,i,n,t),void 0,null),n},useId:function(){var e=Kt(),t=Ge.identifierPrefix;if(Ie){var n=un,r=sn;n=(r&~(1<<32-Ot(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=xl++,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[Yt]=t,e[hl]=r,ac(e,t,!1,!1),t.stateNode=e;e:{switch(u=Kn(n,r),n){case"dialog":Me("cancel",e),Me("close",e),l=r;break;case"iframe":case"object":case"embed":Me("load",e),l=r;break;case"video":case"audio":for(l=0;lWr&&(t.flags|=128,r=!0,_l(i,!1),t.lanes=4194304)}else{if(!r)if(e=Ri(u),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),_l(i,!0),i.tail===null&&i.tailMode==="hidden"&&!u.alternate&&!Ie)return et(t),null}else 2*le()-i.renderingStartTime>Wr&&n!==1073741824&&(t.flags|=128,r=!0,_l(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=le(),t.sibling=null,n=Oe.current,Ae(Oe,r?n&1|2:n&1),t):(et(t),null);case 22:case 23:return Ds(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&(t.mode&1)!==0?(wt&1073741824)!==0&&(et(t),t.subtreeFlags&6&&(t.flags|=8192)):et(t),null;case 24:return null;case 25:return null}throw Error(o(156,t.tag))}function Vd(e,t){switch(Qo(t),t.tag){case 1:return ft(t.type)&&gi(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return Ur(),ze(ct),ze(qe),ls(),e=t.flags,(e&65536)!==0&&(e&128)===0?(t.flags=e&-65537|128,t):null;case 5:return ns(t),null;case 13:if(ze(Oe),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 ze(Oe),null;case 4:return Ur(),null;case 10:return bo(t.type._context),null;case 22:case 23:return Ds(),null;case 24:return null;default:return null}}var Di=!1,tt=!1,Qd=typeof WeakSet=="function"?WeakSet:Set,$=null;function Br(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){je(e,t,r)}else n.current=null}function _s(e,t,n){try{n()}catch(r){je(e,t,r)}}var dc=!1;function Gd(e,t){if(Do=ni,e=Vu(),No(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,h=-1,E=0,N=0,P=e,R=null;t:for(;;){for(var U;P!==n||l!==0&&P.nodeType!==3||(c=u+l),P!==i||r!==0&&P.nodeType!==3||(h=u+r),P.nodeType===3&&(u+=P.nodeValue.length),(U=P.firstChild)!==null;)R=P,P=U;for(;;){if(P===e)break t;if(R===n&&++E===l&&(c=u),R===i&&++N===r&&(h=u),(U=P.nextSibling)!==null)break;P=R,R=P.parentNode}P=U}n=c===-1||h===-1?null:{start:c,end:h}}else n=null}n=n||{start:0,end:0}}else n=null;for(jo={focusedElem:e,selectionRange:n},ni=!1,$=t;$!==null;)if(t=$,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,$=e;else for(;$!==null;){t=$;try{var B=t.alternate;if((t.flags&1024)!==0)switch(t.tag){case 0:case 11:case 15:break;case 1:if(B!==null){var W=B.memoizedProps,Ue=B.memoizedState,w=t.stateNode,g=w.getSnapshotBeforeUpdate(t.elementType===t.type?W:Ft(t.type,W),Ue);w.__reactInternalSnapshotBeforeUpdate=g}break;case 3:var x=t.stateNode.containerInfo;x.nodeType===1?x.textContent="":x.nodeType===9&&x.documentElement&&x.removeChild(x.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(o(163))}}catch(z){je(t,t.return,z)}if(e=t.sibling,e!==null){e.return=t.return,$=e;break}$=t.return}return B=dc,dc=!1,B}function Tl(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&&_s(t,n,i)}l=l.next}while(l!==r)}}function ji(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 Ts(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 pc(e){var t=e.alternate;t!==null&&(e.alternate=null,pc(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[Yt],delete t[hl],delete t[Bo],delete t[Nd],delete t[Ld])),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 hc(e){return e.tag===5||e.tag===3||e.tag===4}function mc(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||hc(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 Cs(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=hi));else if(r!==4&&(e=e.child,e!==null))for(Cs(e,t,n),e=e.sibling;e!==null;)Cs(e,t,n),e=e.sibling}function Rs(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(Rs(e,t,n),e=e.sibling;e!==null;)Rs(e,t,n),e=e.sibling}var Xe=null,Ut=!1;function Dn(e,t,n){for(n=n.child;n!==null;)gc(e,t,n),n=n.sibling}function gc(e,t,n){if(Gt&&typeof Gt.onCommitFiberUnmount=="function")try{Gt.onCommitFiberUnmount(Zl,n)}catch{}switch(n.tag){case 5:tt||Br(n,t);case 6:var r=Xe,l=Ut;Xe=null,Dn(e,t,n),Xe=r,Ut=l,Xe!==null&&(Ut?(e=Xe,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):Xe.removeChild(n.stateNode));break;case 18:Xe!==null&&(Ut?(e=Xe,n=n.stateNode,e.nodeType===8?$o(e.parentNode,n):e.nodeType===1&&$o(e,n),rl(e)):$o(Xe,n.stateNode));break;case 4:r=Xe,l=Ut,Xe=n.stateNode.containerInfo,Ut=!0,Dn(e,t,n),Xe=r,Ut=l;break;case 0:case 11:case 14:case 15:if(!tt&&(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)&&_s(n,t,u),l=l.next}while(l!==r)}Dn(e,t,n);break;case 1:if(!tt&&(Br(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(c){je(n,t,c)}Dn(e,t,n);break;case 21:Dn(e,t,n);break;case 22:n.mode&1?(tt=(r=tt)||n.memoizedState!==null,Dn(e,t,n),tt=r):Dn(e,t,n);break;default:Dn(e,t,n)}}function yc(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new Qd),t.forEach(function(r){var l=tp.bind(null,e,r);n.has(r)||(n.add(r),r.then(l,l))})}}function $t(e,t){var n=t.deletions;if(n!==null)for(var r=0;rl&&(l=u),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*Xd(r/1960))-r,10e?16:e,Fn===null)var r=!1;else{if(e=Fn,Fn=null,Hi=0,(pe&6)!==0)throw Error(o(331));var l=pe;for(pe|=4,$=e.current;$!==null;){var i=$,u=i.child;if(($.flags&16)!==0){var c=i.deletions;if(c!==null){for(var h=0;hle()-Ps?ar(e,0):Ls|=n),ht(e,t)}function Pc(e,t){t===0&&((e.mode&1)===0?t=1:(t=ql,ql<<=1,(ql&130023424)===0&&(ql=4194304)));var n=lt();e=an(e,t),e!==null&&(qr(e,t,n),ht(e,n))}function ep(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),Pc(e,n)}function tp(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),Pc(e,n)}var Ac;Ac=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,Hd(e,t,n);dt=(e.flags&131072)!==0}else dt=!1,Ie&&(t.flags&1048576)!==0&&ca(t,ki,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;Oi(e,t),e=t.pendingProps;var l=Mr(t,qe.current);Fr(t,n),l=ss(null,t,r,e,l,n);var i=us();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,yi(t)):i=!1,t.memoizedState=l.state!==null&&l.state!==void 0?l.state:null,es(t),l.updater=zi,t.stateNode=l,l._reactInternals=t,hs(t,r,e,n),t=vs(null,t,r,!0,i,n)):(t.tag=0,Ie&&i&&Vo(t),rt(null,t,l,n),t=t.child),t;case 16:r=t.elementType;e:{switch(Oi(e,t),e=t.pendingProps,l=r._init,r=l(r._payload),t.type=r,l=t.tag=rp(r),e=Ft(r,e),l){case 0:t=ys(null,t,r,e,n);break e;case 1:t=rc(null,t,r,e,n);break e;case 11:t=qa(null,t,r,e,n);break e;case 14:t=Ja(null,t,r,Ft(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:Ft(r,l),ys(e,t,r,l,n);case 1:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Ft(r,l),rc(e,t,r,l,n);case 3:e:{if(lc(t),e===null)throw Error(o(387));r=t.pendingProps,i=t.memoizedState,l=i.element,wa(e,t),Ci(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=$r(Error(o(423)),t),t=ic(e,t,r,n,l);break e}else if(r!==l){l=$r(Error(o(424)),t),t=ic(e,t,r,n,l);break e}else for(vt=Pn(t.stateNode.containerInfo.firstChild),yt=t,Ie=!0,jt=null,n=ya(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(Or(),r===l){t=fn(e,t,n);break e}rt(e,t,r,n)}t=t.child}return t;case 5:return Sa(t),e===null&&Yo(t),r=t.type,l=t.pendingProps,i=e!==null?e.memoizedProps:null,u=l.children,Fo(r,l)?u=null:i!==null&&Fo(r,i)&&(t.flags|=32),nc(e,t),rt(e,t,u,n),t.child;case 6:return e===null&&Yo(t),null;case 13:return oc(e,t,n);case 4:return ts(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=Dr(t,null,r,n):rt(e,t,r,n),t.child;case 11:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Ft(r,l),qa(e,t,r,l,n);case 7:return rt(e,t,t.pendingProps,n),t.child;case 8:return rt(e,t,t.pendingProps.children,n),t.child;case 12:return rt(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,Ae(Ei,r._currentValue),r._currentValue=u,i!==null)if(Dt(i.value,u)){if(i.children===l.children&&!ct.current){t=fn(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 h=c.firstContext;h!==null;){if(h.context===r){if(i.tag===1){h=cn(-1,n&-n),h.tag=2;var E=i.updateQueue;if(E!==null){E=E.shared;var N=E.pending;N===null?h.next=h:(h.next=N.next,N.next=h),E.pending=h}}i.lanes|=n,h=i.alternate,h!==null&&(h.lanes|=n),qo(i.return,n,t),c.lanes|=n;break}h=h.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),qo(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}rt(e,t,l.children,n),t=t.child}return t;case 9:return l=t.type,r=t.pendingProps.children,Fr(t,n),l=Ct(l),r=r(l),t.flags|=1,rt(e,t,r,n),t.child;case 14:return r=t.type,l=Ft(r,t.pendingProps),l=Ft(r.type,l),Ja(e,t,r,l,n);case 15:return ec(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,l=t.pendingProps,l=t.elementType===r?l:Ft(r,l),Oi(e,t),t.tag=1,ft(r)?(e=!0,yi(t)):e=!1,Fr(t,n),Qa(t,r,l),hs(t,r,l,n),vs(null,t,r,!0,e,n);case 19:return uc(e,t,n);case 22:return tc(e,t,n)}throw Error(o(156,t.tag))};function Mc(e,t){return M(e,t)}function np(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 np(e,t,n,r)}function Fs(e){return e=e.prototype,!(!e||!e.isReactComponent)}function rp(e){if(typeof e=="function")return Fs(e)?1:0;if(e!=null){if(e=e.$$typeof,e===J)return 11;if(e===de)return 14}return 2}function Bn(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 Gi(e,t,n,r,l,i){var u=2;if(r=e,typeof e=="function")Fs(e)&&(u=1);else if(typeof e=="string")u=5;else e:switch(e){case Ne:return fr(n.children,l,i,t);case ce:u=8,l|=8;break;case kt:return e=Lt(12,n,t,l|2),e.elementType=kt,e.lanes=i,e;case fe:return e=Lt(13,n,t,l),e.elementType=fe,e.lanes=i,e;case ue:return e=Lt(19,n,t,l),e.elementType=ue,e.lanes=i,e;case _e:return Yi(n,l,i,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case nt:u=10;break e;case Le:u=9;break e;case J:u=11;break e;case de:u=14;break e;case we: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 fr(e,t,n,r){return e=Lt(7,e,r,t),e.lanes=n,e}function Yi(e,t,n,r){return e=Lt(22,e,r,t),e.elementType=_e,e.lanes=n,e.stateNode={isHidden:!1},e}function Us(e,t,n){return e=Lt(6,e,null,t),e.lanes=n,e}function $s(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 lp(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=po(0),this.expirationTimes=po(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=po(0),this.identifierPrefix=r,this.onRecoverableError=l,this.mutableSourceEagerHydrationData=null}function Bs(e,t,n,r,l,i,u,c,h){return e=new lp(e,t,n,c,h),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},es(i),e}function ip(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(d)}catch(s){console.error(s)}}return d(),Ys.exports=wp(),Ys.exports}var Gc;function xp(){if(Gc)return eo;Gc=1;var d=kp();return eo.createRoot=d.createRoot,eo.hydrateRoot=d.hydrateRoot,eo}var Sp=xp();function su(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}let hr=su();function df(d){hr=d}const Bl={exec:()=>null};function Ce(d,s=""){let o=typeof d=="string"?d:d.source;const a={replace:(f,p)=>{let y=typeof p=="string"?p:p.source;return y=y.replace(ot.caret,"$1"),o=o.replace(f,y),a},getRegex:()=>new RegExp(o,s)};return a}const ot={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceTabs:/^\t+/,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] /,listReplaceTask:/^\[[ xX]\] +/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^
    /i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,unescapeTest:/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:d=>new RegExp(`^( {0,3}${d})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:d=>new RegExp(`^ {0,${Math.min(3,d-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),hrRegex:d=>new RegExp(`^ {0,${Math.min(3,d-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:d=>new RegExp(`^ {0,${Math.min(3,d-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:d=>new RegExp(`^ {0,${Math.min(3,d-1)}}#`),htmlBeginRegex:d=>new RegExp(`^ {0,${Math.min(3,d-1)}}<(?:[a-z].*>|!--)`,"i")},Ep=/^(?:[ \t]*(?:\n|$))+/,_p=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Tp=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,Wl=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Cp=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,pf=/(?:[*+-]|\d{1,9}[.)])/,hf=Ce(/^(?!bull |blockCode|fences|blockquote|heading|html)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html))+?)\n {0,3}(=+|-+) *(?:\n+|$)/).replace(/bull/g,pf).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).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(),uu=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,Rp=/^[^\n]+/,au=/(?!\s*\])(?:\\.|[^\[\]\\])+/,Np=Ce(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",au).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Lp=Ce(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,pf).getRegex(),uo="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",cu=/|$))/,Pp=Ce("^ {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",cu).replace("tag",uo).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),mf=Ce(uu).replace("hr",Wl).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",uo).getRegex(),Ap=Ce(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",mf).getRegex(),fu={blockquote:Ap,code:_p,def:Np,fences:Tp,heading:Cp,hr:Wl,html:Pp,lheading:hf,list:Lp,newline:Ep,paragraph:mf,table:Bl,text:Rp},Yc=Ce("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",Wl).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",uo).getRegex(),Mp={...fu,table:Yc,paragraph:Ce(uu).replace("hr",Wl).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Yc).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",uo).getRegex()},zp={...fu,html:Ce(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+? *(?:\\n{2,}|\\s*$)|\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",cu).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:Bl,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:Ce(uu).replace("hr",Wl).replace("heading",` *#{1,6} *[^ +]`).replace("lheading",hf).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},Ip=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Op=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,gf=/^( {2,}|\\)\n(?!\s*$)/,Dp=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\]*?>/g,Hp=Ce(/^(?:\*+(?:((?!\*)punct)|[^\s*]))|^_+(?:((?!_)punct)|([^\s_]))/,"u").replace(/punct/g,ao).getRegex(),vf="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",Wp=Ce(vf,"gu").replace(/notPunctSpace/g,yf).replace(/punctSpace/g,du).replace(/punct/g,ao).getRegex(),Vp=Ce(vf,"gu").replace(/notPunctSpace/g,$p).replace(/punctSpace/g,Up).replace(/punct/g,Fp).getRegex(),Qp=Ce("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,yf).replace(/punctSpace/g,du).replace(/punct/g,ao).getRegex(),Gp=Ce(/\\(punct)/,"gu").replace(/punct/g,ao).getRegex(),Yp=Ce(/^<(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(),Xp=Ce(cu).replace("(?:-->|$)","-->").getRegex(),Kp=Ce("^comment|^|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^|^").replace("comment",Xp).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),io=/(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/,Zp=Ce(/^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/).replace("label",io).replace("href",/<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),wf=Ce(/^!?\[(label)\]\[(ref)\]/).replace("label",io).replace("ref",au).getRegex(),kf=Ce(/^!?\[(ref)\](?:\[\])?/).replace("ref",au).getRegex(),bp=Ce("reflink|nolink(?!\\()","g").replace("reflink",wf).replace("nolink",kf).getRegex(),pu={_backpedal:Bl,anyPunctuation:Gp,autolink:Yp,blockSkip:Bp,br:gf,code:Op,del:Bl,emStrongLDelim:Hp,emStrongRDelimAst:Wp,emStrongRDelimUnd:Qp,escape:Ip,link:Zp,nolink:kf,punctuation:jp,reflink:wf,reflinkSearch:bp,tag:Kp,text:Dp,url:Bl},qp={...pu,link:Ce(/^!?\[(label)\]\((.*?)\)/).replace("label",io).getRegex(),reflink:Ce(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",io).getRegex()},tu={...pu,emStrongRDelimAst:Vp,url:Ce(/^((?: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~\\]))\1(?=[^~]|$)/,text:/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\":">",'"':""","'":"'"},Xc=d=>eh[d];function bt(d,s){if(s){if(ot.escapeTest.test(d))return d.replace(ot.escapeReplace,Xc)}else if(ot.escapeTestNoEncode.test(d))return d.replace(ot.escapeReplaceNoEncode,Xc);return d}function Kc(d){try{d=encodeURI(d).replace(ot.percentDecode,"%")}catch{return null}return d}function Zc(d,s){var p;const o=d.replace(ot.findPipe,(y,k,T)=>{let _=!1,S=k;for(;--S>=0&&T[S]==="\\";)_=!_;return _?"|":" |"}),a=o.split(ot.splitPipe);let f=0;if(a[0].trim()||a.shift(),a.length>0&&!((p=a.at(-1))!=null&&p.trim())&&a.pop(),s)if(a.length>s)a.splice(s);else for(;a.length{const y=p.match(o.other.beginningSpace);if(y===null)return p;const[k]=y;return k.length>=f.length?p.slice(f.length):p}).join(` +`)}class oo{constructor(s){Re(this,"options");Re(this,"rules");Re(this,"lexer");this.options=s||hr}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(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:o[0],codeBlockStyle:"indented",text:this.options.pedantic?a:Ml(a,` +`)}}}fences(s){const o=this.rules.block.fences.exec(s);if(o){const a=o[0],f=nh(a,o[3]||"",this.rules);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(this.rules.other.endingHash.test(a)){const f=Ml(a,"#");(this.options.pedantic||!f||this.rules.other.endingSpaceChar.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:Ml(o[0],` +`)}}blockquote(s){const o=this.rules.block.blockquote.exec(s);if(o){let a=Ml(o[0],` +`).split(` +`),f="",p="";const y=[];for(;a.length>0;){let k=!1;const T=[];let _;for(_=0;_1,p={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 y=this.rules.other.listItemRegex(a);let k=!1;for(;s;){let _=!1,S="",I="";if(!(o=y.exec(s))||this.rules.block.hr.test(s))break;S=o[0],s=s.substring(S.length);let A=o[2].split(` +`,1)[0].replace(this.rules.other.listReplaceTabs,ae=>" ".repeat(3*ae.length)),D=s.split(` +`,1)[0],V=!A.trim(),F=0;if(this.options.pedantic?(F=2,I=A.trimStart()):V?F=o[1].length+1:(F=o[2].search(this.rules.other.nonSpaceChar),F=F>4?1:F,I=A.slice(F),F+=o[1].length),V&&this.rules.other.blankLine.test(D)&&(S+=D+` +`,s=s.substring(D.length+1),_=!0),!_){const ae=this.rules.other.nextBulletRegex(F),Ee=this.rules.other.hrRegex(F),te=this.rules.other.fencesBeginRegex(F),me=this.rules.other.headingBeginRegex(F),ne=this.rules.other.htmlBeginRegex(F);for(;s;){const Ne=s.split(` +`,1)[0];let ce;if(D=Ne,this.options.pedantic?(D=D.replace(this.rules.other.listReplaceNesting," "),ce=D):ce=D.replace(this.rules.other.tabCharGlobal," "),te.test(D)||me.test(D)||ne.test(D)||ae.test(D)||Ee.test(D))break;if(ce.search(this.rules.other.nonSpaceChar)>=F||!D.trim())I+=` +`+ce.slice(F);else{if(V||A.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||te.test(A)||me.test(A)||Ee.test(A))break;I+=` +`+D}!V&&!D.trim()&&(V=!0),S+=Ne+` +`,s=s.substring(Ne.length+1),A=ce.slice(F)}}p.loose||(k?p.loose=!0:this.rules.other.doubleBlankLine.test(S)&&(k=!0));let K=null,he;this.options.gfm&&(K=this.rules.other.listIsTask.exec(I),K&&(he=K[0]!=="[ ] ",I=I.replace(this.rules.other.listReplaceTask,""))),p.items.push({type:"list_item",raw:S,task:!!K,checked:he,loose:!1,text:I,tokens:[]}),p.raw+=S}const T=p.items.at(-1);if(T)T.raw=T.raw.trimEnd(),T.text=T.text.trimEnd();else return;p.raw=p.raw.trimEnd();for(let _=0;_A.type==="space"),I=S.length>0&&S.some(A=>this.rules.other.anyLine.test(A.raw));p.loose=I}if(p.loose)for(let _=0;_({text:_,tokens:this.lexer.inline(_),header:!1,align:y.align[S]})));return y}}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:o[1]}}tag(s){const o=this.rules.inline.tag.exec(s);if(o)return!this.lexer.state.inLink&&this.rules.other.startATag.test(o[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(o[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(o[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.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&&this.rules.other.startAngleBracket.test(a)){if(!this.rules.other.endAngleBracket.test(a))return;const y=Ml(a.slice(0,-1),"\\");if((a.length-y.length)%2===0)return}else{const y=th(o[2],"()");if(y>-1){const T=(o[0].indexOf("!")===0?5:4)+o[1].length+y;o[2]=o[2].substring(0,y),o[0]=o[0].substring(0,T).trim(),o[3]=""}}let f=o[2],p="";if(this.options.pedantic){const y=this.rules.other.pedanticHrefTitle.exec(f);y&&(f=y[1],p=y[3])}else p=o[3]?o[3].slice(1,-1):"";return f=f.trim(),this.rules.other.startAngleBracket.test(f)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(a)?f=f.slice(1):f=f.slice(1,-1)),bc(o,{href:f&&f.replace(this.rules.inline.anyPunctuation,"$1"),title:p&&p.replace(this.rules.inline.anyPunctuation,"$1")},o[0],this.lexer,this.rules)}}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(this.rules.other.multipleSpaceGlobal," "),p=o[f.toLowerCase()];if(!p){const y=a[0].charAt(0);return{type:"text",raw:y,text:y}}return bc(a,p,a[0],this.lexer,this.rules)}}emStrong(s,o,a=""){let f=this.rules.inline.emStrongLDelim.exec(s);if(!f||f[3]&&a.match(this.rules.other.unicodeAlphaNumeric))return;if(!(f[1]||f[2]||"")||!a||this.rules.inline.punctuation.exec(a)){const y=[...f[0]].length-1;let k,T,_=y,S=0;const I=f[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(I.lastIndex=0,o=o.slice(-1*s.length+y);(f=I.exec(o))!=null;){if(k=f[1]||f[2]||f[3]||f[4]||f[5]||f[6],!k)continue;if(T=[...k].length,f[3]||f[4]){_+=T;continue}else if((f[5]||f[6])&&y%3&&!((y+T)%3)){S+=T;continue}if(_-=T,_>0)continue;T=Math.min(T,T+_+S);const A=[...f[0]][0].length,D=s.slice(0,y+f.index+A+T);if(Math.min(y,T)%2){const F=D.slice(1,-1);return{type:"em",raw:D,text:F,tokens:this.lexer.inlineTokens(F)}}const V=D.slice(2,-2);return{type:"strong",raw:D,text:V,tokens:this.lexer.inlineTokens(V)}}}}codespan(s){const o=this.rules.inline.code.exec(s);if(o){let a=o[2].replace(this.rules.other.newLineCharGlobal," ");const f=this.rules.other.nonSpaceChar.test(a),p=this.rules.other.startingSpaceChar.test(a)&&this.rules.other.endingSpaceChar.test(a);return f&&p&&(a=a.substring(1,a.length-1)),{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=o[1],f="mailto:"+a):(a=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,p;if(o[2]==="@")f=o[0],p="mailto:"+f;else{let y;do y=o[0],o[0]=((a=this.rules.inline._backpedal.exec(o[0]))==null?void 0:a[0])??"";while(y!==o[0]);f=o[0],o[1]==="www."?p="http://"+o[0]:p=o[0]}return{type:"link",raw:o[0],text:f,href:p,tokens:[{type:"text",raw:f,text:f}]}}}inlineText(s){const o=this.rules.inline.text.exec(s);if(o){const a=this.lexer.state.inRawBlock;return{type:"text",raw:o[0],text:o[0],escaped:a}}}}class Pt{constructor(s){Re(this,"tokens");Re(this,"options");Re(this,"state");Re(this,"tokenizer");Re(this,"inlineQueue");this.tokens=[],this.tokens.links=Object.create(null),this.options=s||hr,this.options.tokenizer=this.options.tokenizer||new oo,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};const o={other:ot,block:to.normal,inline:Al.normal};this.options.pedantic?(o.block=to.pedantic,o.inline=Al.pedantic):this.options.gfm&&(o.block=to.gfm,this.options.breaks?o.inline=Al.breaks:o.inline=Al.gfm),this.tokenizer.rules=o}static get rules(){return{block:to,inline:Al}}static lex(s,o){return new Pt(o).lex(s)}static lexInline(s,o){return new Pt(o).inlineTokens(s)}lex(s){s=s.replace(ot.carriageReturn,` +`),this.blockTokens(s,this.tokens);for(let o=0;o(k=_.call({lexer:this},s,o))?(s=s.substring(k.raw.length),o.push(k),!0):!1))continue;if(k=this.tokenizer.space(s)){s=s.substring(k.raw.length);const _=o.at(-1);k.raw.length===1&&_!==void 0?_.raw+=` +`:o.push(k);continue}if(k=this.tokenizer.code(s)){s=s.substring(k.raw.length);const _=o.at(-1);(_==null?void 0:_.type)==="paragraph"||(_==null?void 0:_.type)==="text"?(_.raw+=` +`+k.raw,_.text+=` +`+k.text,this.inlineQueue.at(-1).src=_.text):o.push(k);continue}if(k=this.tokenizer.fences(s)){s=s.substring(k.raw.length),o.push(k);continue}if(k=this.tokenizer.heading(s)){s=s.substring(k.raw.length),o.push(k);continue}if(k=this.tokenizer.hr(s)){s=s.substring(k.raw.length),o.push(k);continue}if(k=this.tokenizer.blockquote(s)){s=s.substring(k.raw.length),o.push(k);continue}if(k=this.tokenizer.list(s)){s=s.substring(k.raw.length),o.push(k);continue}if(k=this.tokenizer.html(s)){s=s.substring(k.raw.length),o.push(k);continue}if(k=this.tokenizer.def(s)){s=s.substring(k.raw.length);const _=o.at(-1);(_==null?void 0:_.type)==="paragraph"||(_==null?void 0:_.type)==="text"?(_.raw+=` +`+k.raw,_.text+=` +`+k.raw,this.inlineQueue.at(-1).src=_.text):this.tokens.links[k.tag]||(this.tokens.links[k.tag]={href:k.href,title:k.title});continue}if(k=this.tokenizer.table(s)){s=s.substring(k.raw.length),o.push(k);continue}if(k=this.tokenizer.lheading(s)){s=s.substring(k.raw.length),o.push(k);continue}let T=s;if((y=this.options.extensions)!=null&&y.startBlock){let _=1/0;const S=s.slice(1);let I;this.options.extensions.startBlock.forEach(A=>{I=A.call({lexer:this},S),typeof I=="number"&&I>=0&&(_=Math.min(_,I))}),_<1/0&&_>=0&&(T=s.substring(0,_+1))}if(this.state.top&&(k=this.tokenizer.paragraph(T))){const _=o.at(-1);a&&(_==null?void 0:_.type)==="paragraph"?(_.raw+=` +`+k.raw,_.text+=` +`+k.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=_.text):o.push(k),a=T.length!==s.length,s=s.substring(k.raw.length);continue}if(k=this.tokenizer.text(s)){s=s.substring(k.raw.length);const _=o.at(-1);(_==null?void 0:_.type)==="text"?(_.raw+=` +`+k.raw,_.text+=` +`+k.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=_.text):o.push(k);continue}if(s){const _="Infinite loop on byte: "+s.charCodeAt(0);if(this.options.silent){console.error(_);break}else throw new Error(_)}}return this.state.top=!0,o}inline(s,o=[]){return this.inlineQueue.push({src:s,tokens:o}),o}inlineTokens(s,o=[]){var k,T,_;let a=s,f=null;if(this.tokens.links){const S=Object.keys(this.tokens.links);if(S.length>0)for(;(f=this.tokenizer.rules.inline.reflinkSearch.exec(a))!=null;)S.includes(f[0].slice(f[0].lastIndexOf("[")+1,-1))&&(a=a.slice(0,f.index)+"["+"a".repeat(f[0].length-2)+"]"+a.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(f=this.tokenizer.rules.inline.blockSkip.exec(a))!=null;)a=a.slice(0,f.index)+"["+"a".repeat(f[0].length-2)+"]"+a.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);for(;(f=this.tokenizer.rules.inline.anyPunctuation.exec(a))!=null;)a=a.slice(0,f.index)+"++"+a.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let p=!1,y="";for(;s;){p||(y=""),p=!1;let S;if((T=(k=this.options.extensions)==null?void 0:k.inline)!=null&&T.some(A=>(S=A.call({lexer:this},s,o))?(s=s.substring(S.raw.length),o.push(S),!0):!1))continue;if(S=this.tokenizer.escape(s)){s=s.substring(S.raw.length),o.push(S);continue}if(S=this.tokenizer.tag(s)){s=s.substring(S.raw.length),o.push(S);continue}if(S=this.tokenizer.link(s)){s=s.substring(S.raw.length),o.push(S);continue}if(S=this.tokenizer.reflink(s,this.tokens.links)){s=s.substring(S.raw.length);const A=o.at(-1);S.type==="text"&&(A==null?void 0:A.type)==="text"?(A.raw+=S.raw,A.text+=S.text):o.push(S);continue}if(S=this.tokenizer.emStrong(s,a,y)){s=s.substring(S.raw.length),o.push(S);continue}if(S=this.tokenizer.codespan(s)){s=s.substring(S.raw.length),o.push(S);continue}if(S=this.tokenizer.br(s)){s=s.substring(S.raw.length),o.push(S);continue}if(S=this.tokenizer.del(s)){s=s.substring(S.raw.length),o.push(S);continue}if(S=this.tokenizer.autolink(s)){s=s.substring(S.raw.length),o.push(S);continue}if(!this.state.inLink&&(S=this.tokenizer.url(s))){s=s.substring(S.raw.length),o.push(S);continue}let I=s;if((_=this.options.extensions)!=null&&_.startInline){let A=1/0;const D=s.slice(1);let V;this.options.extensions.startInline.forEach(F=>{V=F.call({lexer:this},D),typeof V=="number"&&V>=0&&(A=Math.min(A,V))}),A<1/0&&A>=0&&(I=s.substring(0,A+1))}if(S=this.tokenizer.inlineText(I)){s=s.substring(S.raw.length),S.raw.slice(-1)!=="_"&&(y=S.raw.slice(-1)),p=!0;const A=o.at(-1);(A==null?void 0:A.type)==="text"?(A.raw+=S.raw,A.text+=S.text):o.push(S);continue}if(s){const A="Infinite loop on byte: "+s.charCodeAt(0);if(this.options.silent){console.error(A);break}else throw new Error(A)}}return o}}class so{constructor(s){Re(this,"options");Re(this,"parser");this.options=s||hr}space(s){return""}code({text:s,lang:o,escaped:a}){var y;const f=(y=(o||"").match(ot.notSpaceStart))==null?void 0:y[0],p=s.replace(ot.endingNewline,"")+` +`;return f?'
    '+(a?p:bt(p,!0))+`
    +`:"
    "+(a?p:bt(p,!0))+`
    +`}blockquote({tokens:s}){return`
    +${this.parser.parse(s)}
    +`}html({text:s}){return s}heading({tokens:s,depth:o}){return`${this.parser.parseInline(s)} +`}hr(s){return`
    +`}list(s){const o=s.ordered,a=s.start;let f="";for(let k=0;k +`+f+" +`}listitem(s){var a;let o="";if(s.task){const f=this.checkbox({checked:!!s.checked});s.loose?((a=s.tokens[0])==null?void 0:a.type)==="paragraph"?(s.tokens[0].text=f+" "+s.tokens[0].text,s.tokens[0].tokens&&s.tokens[0].tokens.length>0&&s.tokens[0].tokens[0].type==="text"&&(s.tokens[0].tokens[0].text=f+" "+bt(s.tokens[0].tokens[0].text),s.tokens[0].tokens[0].escaped=!0)):s.tokens.unshift({type:"text",raw:f+" ",text:f+" ",escaped:!0}):o+=f+" "}return o+=this.parser.parse(s.tokens,!!s.loose),`
  • ${o}
  • +`}checkbox({checked:s}){return"'}paragraph({tokens:s}){return`

    ${this.parser.parseInline(s)}

    +`}table(s){let o="",a="";for(let p=0;p${f}`),` + +`+o+` +`+f+`
    +`}tablerow({text:s}){return` +${s} +`}tablecell(s){const o=this.parser.parseInline(s.tokens),a=s.header?"th":"td";return(s.align?`<${a} align="${s.align}">`:`<${a}>`)+o+` +`}strong({tokens:s}){return`${this.parser.parseInline(s)}`}em({tokens:s}){return`${this.parser.parseInline(s)}`}codespan({text:s}){return`${bt(s,!0)}`}br(s){return"
    "}del({tokens:s}){return`${this.parser.parseInline(s)}`}link({href:s,title:o,tokens:a}){const f=this.parser.parseInline(a),p=Kc(s);if(p===null)return f;s=p;let y='
    ",y}image({href:s,title:o,text:a}){const f=Kc(s);if(f===null)return bt(a);s=f;let p=`${a}{const _=k[T].flat(1/0);a=a.concat(this.walkTokens(_,o))}):k.tokens&&(a=a.concat(this.walkTokens(k.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(p=>{if(!p.name)throw new Error("extension name required");if("renderer"in p){const y=o.renderers[p.name];y?o.renderers[p.name]=function(...k){let T=p.renderer.apply(this,k);return T===!1&&(T=y.apply(this,k)),T}:o.renderers[p.name]=p.renderer}if("tokenizer"in p){if(!p.level||p.level!=="block"&&p.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");const y=o[p.level];y?y.unshift(p.tokenizer):o[p.level]=[p.tokenizer],p.start&&(p.level==="block"?o.startBlock?o.startBlock.push(p.start):o.startBlock=[p.start]:p.level==="inline"&&(o.startInline?o.startInline.push(p.start):o.startInline=[p.start]))}"childTokens"in p&&p.childTokens&&(o.childTokens[p.name]=p.childTokens)}),f.extensions=o),a.renderer){const p=this.defaults.renderer||new so(this.defaults);for(const y in a.renderer){if(!(y in p))throw new Error(`renderer '${y}' does not exist`);if(["options","parser"].includes(y))continue;const k=y,T=a.renderer[k],_=p[k];p[k]=(...S)=>{let I=T.apply(p,S);return I===!1&&(I=_.apply(p,S)),I||""}}f.renderer=p}if(a.tokenizer){const p=this.defaults.tokenizer||new oo(this.defaults);for(const y in a.tokenizer){if(!(y in p))throw new Error(`tokenizer '${y}' does not exist`);if(["options","rules","lexer"].includes(y))continue;const k=y,T=a.tokenizer[k],_=p[k];p[k]=(...S)=>{let I=T.apply(p,S);return I===!1&&(I=_.apply(p,S)),I}}f.tokenizer=p}if(a.hooks){const p=this.defaults.hooks||new Hl;for(const y in a.hooks){if(!(y in p))throw new Error(`hook '${y}' does not exist`);if(["options","block"].includes(y))continue;const k=y,T=a.hooks[k],_=p[k];Hl.passThroughHooks.has(y)?p[k]=S=>{if(this.defaults.async)return Promise.resolve(T.call(p,S)).then(A=>_.call(p,A));const I=T.call(p,S);return _.call(p,I)}:p[k]=(...S)=>{let I=T.apply(p,S);return I===!1&&(I=_.apply(p,S)),I}}f.hooks=p}if(a.walkTokens){const p=this.defaults.walkTokens,y=a.walkTokens;f.walkTokens=function(k){let T=[];return T.push(y.call(this,k)),p&&(T=T.concat(p.call(this,k))),T}}this.defaults={...this.defaults,...f}}),this}setOptions(s){return this.defaults={...this.defaults,...s},this}lexer(s,o){return Pt.lex(s,o??this.defaults)}parser(s,o){return At.parse(s,o??this.defaults)}parseMarkdown(s){return(a,f)=>{const p={...f},y={...this.defaults,...p},k=this.onError(!!y.silent,!!y.async);if(this.defaults.async===!0&&p.async===!1)return k(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof a>"u"||a===null)return k(new Error("marked(): input parameter is undefined or null"));if(typeof a!="string")return k(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(a)+", string expected"));y.hooks&&(y.hooks.options=y,y.hooks.block=s);const T=y.hooks?y.hooks.provideLexer():s?Pt.lex:Pt.lexInline,_=y.hooks?y.hooks.provideParser():s?At.parse:At.parseInline;if(y.async)return Promise.resolve(y.hooks?y.hooks.preprocess(a):a).then(S=>T(S,y)).then(S=>y.hooks?y.hooks.processAllTokens(S):S).then(S=>y.walkTokens?Promise.all(this.walkTokens(S,y.walkTokens)).then(()=>S):S).then(S=>_(S,y)).then(S=>y.hooks?y.hooks.postprocess(S):S).catch(k);try{y.hooks&&(a=y.hooks.preprocess(a));let S=T(a,y);y.hooks&&(S=y.hooks.processAllTokens(S)),y.walkTokens&&this.walkTokens(S,y.walkTokens);let I=_(S,y);return y.hooks&&(I=y.hooks.postprocess(I)),I}catch(S){return k(S)}}}onError(s,o){return a=>{if(a.message+=` +Please report this to https://github.com/markedjs/marked.`,s){const f="

    An error occurred:

    "+bt(a.message+"",!0)+"
    ";return o?Promise.resolve(f):f}if(o)return Promise.reject(a);throw a}}}const pr=new rh;function Se(d,s){return pr.parse(d,s)}Se.options=Se.setOptions=function(d){return pr.setOptions(d),Se.defaults=pr.defaults,df(Se.defaults),Se};Se.getDefaults=su;Se.defaults=hr;Se.use=function(...d){return pr.use(...d),Se.defaults=pr.defaults,df(Se.defaults),Se};Se.walkTokens=function(d,s){return pr.walkTokens(d,s)};Se.parseInline=pr.parseInline;Se.Parser=At;Se.parser=At.parse;Se.Renderer=so;Se.TextRenderer=hu;Se.Lexer=Pt;Se.lexer=Pt.lex;Se.Tokenizer=oo;Se.Hooks=Hl;Se.parse=Se;Se.options;Se.setOptions;Se.use;Se.walkTokens;Se.parseInline;At.parse;Pt.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:xf,setPrototypeOf:qc,isFrozen:lh,getPrototypeOf:ih,getOwnPropertyDescriptor:oh}=Object;let{freeze:st,seal:Mt,create:Sf}=Object,{apply:nu,construct:ru}=typeof Reflect<"u"&&Reflect;st||(st=function(s){return s});Mt||(Mt=function(s){return s});nu||(nu=function(s,o,a){return s.apply(o,a)});ru||(ru=function(s,o){return new s(...o)});const no=ut(Array.prototype.forEach),sh=ut(Array.prototype.lastIndexOf),Jc=ut(Array.prototype.pop),zl=ut(Array.prototype.push),uh=ut(Array.prototype.splice),lo=ut(String.prototype.toLowerCase),Zs=ut(String.prototype.toString),ef=ut(String.prototype.match),Il=ut(String.prototype.replace),ah=ut(String.prototype.indexOf),ch=ut(String.prototype.trim),Ht=ut(Object.prototype.hasOwnProperty),it=ut(RegExp.prototype.test),Ol=fh(TypeError);function ut(d){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]:lo;qc&&qc(d,null);let a=s.length;for(;a--;){let f=s[a];if(typeof f=="string"){const p=o(f);p!==f&&(lh(s)||(s[a]=p),f=p)}d[f]=!0}return d}function dh(d){for(let s=0;s/gm),yh=Mt(/\$\{[\w\W]*/gm),vh=Mt(/^data-[\-\w.\u00B7-\uFFFF]+$/),wh=Mt(/^aria-[\-\w]+$/),Ef=Mt(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),kh=Mt(/^(?:\w+script|data):/i),xh=Mt(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),_f=Mt(/^html$/i),Sh=Mt(/^[a-z][.\w]*(-[.\w]+)+$/i);var of=Object.freeze({__proto__:null,ARIA_ATTR:wh,ATTR_WHITESPACE:xh,CUSTOM_ELEMENT:Sh,DATA_ATTR:vh,DOCTYPE_NAME:_f,ERB_EXPR:gh,IS_ALLOWED_URI:Ef,IS_SCRIPT_OR_DATA:kh,MUSTACHE_EXPR:mh,TMPLIT_EXPR:yh});const jl={element:1,text:3,progressingInstruction:7,comment:8,document:9},Eh=function(){return typeof window>"u"?null:window},_h=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 p="dompurify"+(a?"#"+a:"");try{return s.createPolicy(p,{createHTML(y){return y},createScriptURL(y){return y}})}catch{return console.warn("TrustedTypes policy "+p+" could not be created."),null}},sf=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function Tf(){let d=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Eh();const s=Y=>Tf(Y);if(s.version="3.2.4",s.removed=[],!d||!d.document||d.document.nodeType!==jl.document||!d.Element)return s.isSupported=!1,s;let{document:o}=d;const a=o,f=a.currentScript,{DocumentFragment:p,HTMLTemplateElement:y,Node:k,Element:T,NodeFilter:_,NamedNodeMap:S=d.NamedNodeMap||d.MozNamedAttrMap,HTMLFormElement:I,DOMParser:A,trustedTypes:D}=d,V=T.prototype,F=Dl(V,"cloneNode"),K=Dl(V,"remove"),he=Dl(V,"nextSibling"),ae=Dl(V,"childNodes"),Ee=Dl(V,"parentNode");if(typeof y=="function"){const Y=o.createElement("template");Y.content&&Y.content.ownerDocument&&(o=Y.content.ownerDocument)}let te,me="";const{implementation:ne,createNodeIterator:Ne,createDocumentFragment:ce,getElementsByTagName:kt}=o,{importNode:nt}=a;let Le=sf();s.isSupported=typeof xf=="function"&&typeof Ee=="function"&&ne&&ne.createHTMLDocument!==void 0;const{MUSTACHE_EXPR:J,ERB_EXPR:fe,TMPLIT_EXPR:ue,DATA_ATTR:de,ARIA_ATTR:we,IS_SCRIPT_OR_DATA:_e,ATTR_WHITESPACE:O,CUSTOM_ELEMENT:Q}=of;let{IS_ALLOWED_URI:j}=of,v=null;const C=se({},[...tf,...bs,...qs,...Js,...nf]);let X=null;const re=se({},[...rf,...eu,...lf,...ro]);let Z=Object.seal(Sf(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}})),ie=null,ke=null,ge=!0,Te=!0,Ze=!1,Vn=!0,qt=!1,pn=!0,zt=!1,mr=!1,gr=!1,Wt=!1,Qn=!1,hn=!1,mn=!0,Jt=!1;const Qr="user-content-";let yr=!0,gn=!1,en={},tn=null;const vr=se({},["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 Gn=null;const Gr=se({},["audio","video","img","source","image","track"]);let nn=null;const yn=se({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),wr="http://www.w3.org/1998/Math/MathML",Yn="http://www.w3.org/2000/svg",xt="http://www.w3.org/1999/xhtml";let vn=xt,Xn=!1,Kn=null;const Yr=se({},[wr,Yn,xt],Zs);let wn=se({},["mi","mo","mn","ms","mtext"]),kn=se({},["annotation-xml"]);const xn=se({},["title","style","font","a","script"]);let St=null;const Vl=["application/xhtml+xml","text/html"],Ql="text/html";let Fe=null,rn=null;const Gl=o.createElement("form"),kr=function(m){return m instanceof RegExp||m instanceof Function},xr=function(){let m=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(rn&&rn===m)){if((!m||typeof m!="object")&&(m={}),m=dr(m),St=Vl.indexOf(m.PARSER_MEDIA_TYPE)===-1?Ql:m.PARSER_MEDIA_TYPE,Fe=St==="application/xhtml+xml"?Zs:lo,v=Ht(m,"ALLOWED_TAGS")?se({},m.ALLOWED_TAGS,Fe):C,X=Ht(m,"ALLOWED_ATTR")?se({},m.ALLOWED_ATTR,Fe):re,Kn=Ht(m,"ALLOWED_NAMESPACES")?se({},m.ALLOWED_NAMESPACES,Zs):Yr,nn=Ht(m,"ADD_URI_SAFE_ATTR")?se(dr(yn),m.ADD_URI_SAFE_ATTR,Fe):yn,Gn=Ht(m,"ADD_DATA_URI_TAGS")?se(dr(Gr),m.ADD_DATA_URI_TAGS,Fe):Gr,tn=Ht(m,"FORBID_CONTENTS")?se({},m.FORBID_CONTENTS,Fe):vr,ie=Ht(m,"FORBID_TAGS")?se({},m.FORBID_TAGS,Fe):{},ke=Ht(m,"FORBID_ATTR")?se({},m.FORBID_ATTR,Fe):{},en=Ht(m,"USE_PROFILES")?m.USE_PROFILES:!1,ge=m.ALLOW_ARIA_ATTR!==!1,Te=m.ALLOW_DATA_ATTR!==!1,Ze=m.ALLOW_UNKNOWN_PROTOCOLS||!1,Vn=m.ALLOW_SELF_CLOSE_IN_ATTR!==!1,qt=m.SAFE_FOR_TEMPLATES||!1,pn=m.SAFE_FOR_XML!==!1,zt=m.WHOLE_DOCUMENT||!1,Wt=m.RETURN_DOM||!1,Qn=m.RETURN_DOM_FRAGMENT||!1,hn=m.RETURN_TRUSTED_TYPE||!1,gr=m.FORCE_BODY||!1,mn=m.SANITIZE_DOM!==!1,Jt=m.SANITIZE_NAMED_PROPS||!1,yr=m.KEEP_CONTENT!==!1,gn=m.IN_PLACE||!1,j=m.ALLOWED_URI_REGEXP||Ef,vn=m.NAMESPACE||xt,wn=m.MATHML_TEXT_INTEGRATION_POINTS||wn,kn=m.HTML_INTEGRATION_POINTS||kn,Z=m.CUSTOM_ELEMENT_HANDLING||{},m.CUSTOM_ELEMENT_HANDLING&&kr(m.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(Z.tagNameCheck=m.CUSTOM_ELEMENT_HANDLING.tagNameCheck),m.CUSTOM_ELEMENT_HANDLING&&kr(m.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(Z.attributeNameCheck=m.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),m.CUSTOM_ELEMENT_HANDLING&&typeof m.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(Z.allowCustomizedBuiltInElements=m.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),qt&&(Te=!1),Qn&&(Wt=!0),en&&(v=se({},nf),X=[],en.html===!0&&(se(v,tf),se(X,rf)),en.svg===!0&&(se(v,bs),se(X,eu),se(X,ro)),en.svgFilters===!0&&(se(v,qs),se(X,eu),se(X,ro)),en.mathMl===!0&&(se(v,Js),se(X,lf),se(X,ro))),m.ADD_TAGS&&(v===C&&(v=dr(v)),se(v,m.ADD_TAGS,Fe)),m.ADD_ATTR&&(X===re&&(X=dr(X)),se(X,m.ADD_ATTR,Fe)),m.ADD_URI_SAFE_ATTR&&se(nn,m.ADD_URI_SAFE_ATTR,Fe),m.FORBID_CONTENTS&&(tn===vr&&(tn=dr(tn)),se(tn,m.FORBID_CONTENTS,Fe)),yr&&(v["#text"]=!0),zt&&se(v,["html","head","body"]),v.table&&(se(v,["tbody"]),delete ie.tbody),m.TRUSTED_TYPES_POLICY){if(typeof m.TRUSTED_TYPES_POLICY.createHTML!="function")throw Ol('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof m.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw Ol('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');te=m.TRUSTED_TYPES_POLICY,me=te.createHTML("")}else te===void 0&&(te=_h(D,f)),te!==null&&typeof me=="string"&&(me=te.createHTML(""));st&&st(m),rn=m}},Sn=se({},[...bs,...qs,...ph]),Sr=se({},[...Js,...hh]),Zn=function(m){let M=Ee(m);(!M||!M.tagName)&&(M={namespaceURI:vn,tagName:"template"});const H=lo(m.tagName),Pe=lo(M.tagName);return Kn[m.namespaceURI]?m.namespaceURI===Yn?M.namespaceURI===xt?H==="svg":M.namespaceURI===wr?H==="svg"&&(Pe==="annotation-xml"||wn[Pe]):!!Sn[H]:m.namespaceURI===wr?M.namespaceURI===xt?H==="math":M.namespaceURI===Yn?H==="math"&&kn[Pe]:!!Sr[H]:m.namespaceURI===xt?M.namespaceURI===Yn&&!kn[Pe]||M.namespaceURI===wr&&!wn[Pe]?!1:!Sr[H]&&(xn[H]||!Sn[H]):!!(St==="application/xhtml+xml"&&Kn[m.namespaceURI]):!1},Et=function(m){zl(s.removed,{element:m});try{Ee(m).removeChild(m)}catch{K(m)}},Vt=function(m,M){try{zl(s.removed,{attribute:M.getAttributeNode(m),from:M})}catch{zl(s.removed,{attribute:null,from:M})}if(M.removeAttribute(m),m==="is")if(Wt||Qn)try{Et(M)}catch{}else try{M.setAttribute(m,"")}catch{}},bn=function(m){let M=null,H=null;if(gr)m=""+m;else{const le=ef(m,/^[\r\n\t ]+/);H=le&&le[0]}St==="application/xhtml+xml"&&vn===xt&&(m=''+m+"");const Pe=te?te.createHTML(m):m;if(vn===xt)try{M=new A().parseFromString(Pe,St)}catch{}if(!M||!M.documentElement){M=ne.createDocument(vn,"template",null);try{M.documentElement.innerHTML=Xn?me:Pe}catch{}}const Ve=M.body||M.documentElement;return m&&H&&Ve.insertBefore(o.createTextNode(H),Ve.childNodes[0]||null),vn===xt?kt.call(M,zt?"html":"body")[0]:zt?M.documentElement:Ve},qn=function(m){return Ne.call(m.ownerDocument||m,m,_.SHOW_ELEMENT|_.SHOW_COMMENT|_.SHOW_TEXT|_.SHOW_PROCESSING_INSTRUCTION|_.SHOW_CDATA_SECTION,null)},Jn=function(m){return m instanceof I&&(typeof m.nodeName!="string"||typeof m.textContent!="string"||typeof m.removeChild!="function"||!(m.attributes instanceof S)||typeof m.removeAttribute!="function"||typeof m.setAttribute!="function"||typeof m.namespaceURI!="string"||typeof m.insertBefore!="function"||typeof m.hasChildNodes!="function")},Yl=function(m){return typeof k=="function"&&m instanceof k};function It(Y,m,M){no(Y,H=>{H.call(s,m,M,rn)})}const Xl=function(m){let M=null;if(It(Le.beforeSanitizeElements,m,null),Jn(m))return Et(m),!0;const H=Fe(m.nodeName);if(It(Le.uponSanitizeElement,m,{tagName:H,allowedTags:v}),m.hasChildNodes()&&!Yl(m.firstElementChild)&&it(/<[/\w]/g,m.innerHTML)&&it(/<[/\w]/g,m.textContent)||m.nodeType===jl.progressingInstruction||pn&&m.nodeType===jl.comment&&it(/<[/\w]/g,m.data))return Et(m),!0;if(!v[H]||ie[H]){if(!ie[H]&&Xr(H)&&(Z.tagNameCheck instanceof RegExp&&it(Z.tagNameCheck,H)||Z.tagNameCheck instanceof Function&&Z.tagNameCheck(H)))return!1;if(yr&&!tn[H]){const Pe=Ee(m)||m.parentNode,Ve=ae(m)||m.childNodes;if(Ve&&Pe){const le=Ve.length;for(let be=le-1;be>=0;--be){const at=F(Ve[be],!0);at.__removalCount=(m.__removalCount||0)+1,Pe.insertBefore(at,he(m))}}}return Et(m),!0}return m instanceof T&&!Zn(m)||(H==="noscript"||H==="noembed"||H==="noframes")&&it(/<\/no(script|embed|frames)/i,m.innerHTML)?(Et(m),!0):(qt&&m.nodeType===jl.text&&(M=m.textContent,no([J,fe,ue],Pe=>{M=Il(M,Pe," ")}),m.textContent!==M&&(zl(s.removed,{element:m.cloneNode()}),m.textContent=M)),It(Le.afterSanitizeElements,m,null),!1)},Qt=function(m,M,H){if(mn&&(M==="id"||M==="name")&&(H in o||H in Gl))return!1;if(!(Te&&!ke[M]&&it(de,M))){if(!(ge&&it(we,M))){if(!X[M]||ke[M]){if(!(Xr(m)&&(Z.tagNameCheck instanceof RegExp&&it(Z.tagNameCheck,m)||Z.tagNameCheck instanceof Function&&Z.tagNameCheck(m))&&(Z.attributeNameCheck instanceof RegExp&&it(Z.attributeNameCheck,M)||Z.attributeNameCheck instanceof Function&&Z.attributeNameCheck(M))||M==="is"&&Z.allowCustomizedBuiltInElements&&(Z.tagNameCheck instanceof RegExp&&it(Z.tagNameCheck,H)||Z.tagNameCheck instanceof Function&&Z.tagNameCheck(H))))return!1}else if(!nn[M]){if(!it(j,Il(H,O,""))){if(!((M==="src"||M==="xlink:href"||M==="href")&&m!=="script"&&ah(H,"data:")===0&&Gn[m])){if(!(Ze&&!it(_e,Il(H,O,"")))){if(H)return!1}}}}}}return!0},Xr=function(m){return m!=="annotation-xml"&&ef(m,Q)},Kr=function(m){It(Le.beforeSanitizeAttributes,m,null);const{attributes:M}=m;if(!M||Jn(m))return;const H={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:X,forceKeepAttr:void 0};let Pe=M.length;for(;Pe--;){const Ve=M[Pe],{name:le,namespaceURI:be,value:at}=Ve,En=Fe(le);let $e=le==="value"?at:ch(at);if(H.attrName=En,H.attrValue=$e,H.keepAttr=!0,H.forceKeepAttr=void 0,It(Le.uponSanitizeAttribute,m,H),$e=H.attrValue,Jt&&(En==="id"||En==="name")&&(Vt(le,m),$e=Qr+$e),pn&&it(/((--!?|])>)|<\/(style|title)/i,$e)){Vt(le,m);continue}if(H.forceKeepAttr||(Vt(le,m),!H.keepAttr))continue;if(!Vn&&it(/\/>/i,$e)){Vt(le,m);continue}qt&&no([J,fe,ue],Zr=>{$e=Il($e,Zr," ")});const Kl=Fe(m.nodeName);if(Qt(Kl,En,$e)){if(te&&typeof D=="object"&&typeof D.getAttributeType=="function"&&!be)switch(D.getAttributeType(Kl,En)){case"TrustedHTML":{$e=te.createHTML($e);break}case"TrustedScriptURL":{$e=te.createScriptURL($e);break}}try{be?m.setAttributeNS(be,le,$e):m.setAttribute(le,$e),Jn(m)?Et(m):Jc(s.removed)}catch{}}}It(Le.afterSanitizeAttributes,m,null)},co=function Y(m){let M=null;const H=qn(m);for(It(Le.beforeSanitizeShadowDOM,m,null);M=H.nextNode();)It(Le.uponSanitizeShadowNode,M,null),Xl(M),Kr(M),M.content instanceof p&&Y(M.content);It(Le.afterSanitizeShadowDOM,m,null)};return s.sanitize=function(Y){let m=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},M=null,H=null,Pe=null,Ve=null;if(Xn=!Y,Xn&&(Y=""),typeof Y!="string"&&!Yl(Y))if(typeof Y.toString=="function"){if(Y=Y.toString(),typeof Y!="string")throw Ol("dirty is not a string, aborting")}else throw Ol("toString is not a function");if(!s.isSupported)return Y;if(mr||xr(m),s.removed=[],typeof Y=="string"&&(gn=!1),gn){if(Y.nodeName){const at=Fe(Y.nodeName);if(!v[at]||ie[at])throw Ol("root node is forbidden and cannot be sanitized in-place")}}else if(Y instanceof k)M=bn(""),H=M.ownerDocument.importNode(Y,!0),H.nodeType===jl.element&&H.nodeName==="BODY"||H.nodeName==="HTML"?M=H:M.appendChild(H);else{if(!Wt&&!qt&&!zt&&Y.indexOf("<")===-1)return te&&hn?te.createHTML(Y):Y;if(M=bn(Y),!M)return Wt?null:hn?me:""}M&&gr&&Et(M.firstChild);const le=qn(gn?Y:M);for(;Pe=le.nextNode();)Xl(Pe),Kr(Pe),Pe.content instanceof p&&co(Pe.content);if(gn)return Y;if(Wt){if(Qn)for(Ve=ce.call(M.ownerDocument);M.firstChild;)Ve.appendChild(M.firstChild);else Ve=M;return(X.shadowroot||X.shadowrootmode)&&(Ve=nt.call(a,Ve,!0)),Ve}let be=zt?M.outerHTML:M.innerHTML;return zt&&v["!doctype"]&&M.ownerDocument&&M.ownerDocument.doctype&&M.ownerDocument.doctype.name&&it(_f,M.ownerDocument.doctype.name)&&(be=" +`+be),qt&&no([J,fe,ue],at=>{be=Il(be,at," ")}),te&&hn?te.createHTML(be):be},s.setConfig=function(){let Y=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};xr(Y),mr=!0},s.clearConfig=function(){rn=null,mr=!1},s.isValidAttribute=function(Y,m,M){rn||xr({});const H=Fe(Y),Pe=Fe(m);return Qt(H,Pe,M)},s.addHook=function(Y,m){typeof m=="function"&&zl(Le[Y],m)},s.removeHook=function(Y,m){if(m!==void 0){const M=sh(Le[Y],m);return M===-1?void 0:uh(Le[Y],M,1)[0]}return Jc(Le[Y])},s.removeHooks=function(Y){Le[Y]=[]},s.removeAllHooks=function(){Le=sf()},s}var Th=Tf();function Ch(d){return L.jsxs("svg",{...d,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 Rh(d){return L.jsxs("svg",{...d,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"})]})}var lu=function(){return(lu=Object.assign||function(d){for(var s,o=1,a=arguments.length;of.type==="text"?f.text.length>0?L.jsx(Ph,{dynamic:!0,children:L.jsx("span",{className:"markdown",dangerouslySetInnerHTML:{__html:Ah(f.text)}})},p):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"})]},p):f.type==="image"?L.jsx("img",{src:f.image,className:"w-full max-w-[384px] h-auto max-h-[300px] object-contain rounded-md"},p):null)})})]})}function zh({messages:d}){const s=d.length===0;return 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:L.jsx(Nh,{children:s?L.jsx("div",{className:"text-xl",children:"Ready!"}):d.map((o,a)=>L.jsx(Mh,{...o},`message-${a}`))})})}function cf(d){return L.jsxs("svg",{...d,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 Ih(d){return L.jsxs("svg",{...d,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 Oh(d){const s=d==0?0:Math.floor(Math.log(d)/Math.log(1024));return+(d/Math.pow(1024,s)).toFixed(2)*1+["B","kB","MB","GB","TB"][s]}function Dh({text:d,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:[d," (",s.toFixed(2),"%",isNaN(o)?"":` of ${Oh(o)}`,")"]})})}function jh(d){return L.jsx("svg",{...d,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:"m2.25 15.75 5.159-5.159a2.25 2.25 0 0 1 3.182 0l5.159 5.159m-1.5-1.5 1.409-1.409a2.25 2.25 0 0 1 3.182 0l2.909 2.909m-18 3.75h16.5a1.5 1.5 0 0 0 1.5-1.5V6a1.5 1.5 0 0 0-1.5-1.5H3.75A1.5 1.5 0 0 0 2.25 6v12a1.5 1.5 0 0 0 1.5 1.5Zm10.5-11.25h.008v.008h-.008V8.25Zm.375 0a.375.375 0 1 1-.75 0 .375.375 0 0 1 .75 0Z"})})}function Fh(d){return L.jsx("svg",{...d,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:"m9.75 9.75 4.5 4.5m0-4.5-4.5 4.5M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z"})})}function Uh({src:d,onRemove:s,...o}){const[a,f]=ve.useState(!1);return L.jsxs("div",{...o,onMouseEnter:()=>f(!0),onMouseLeave:()=>f(!1),children:[L.jsx(Fh,{onClick:s,className:`absolute top-0 right-0 cursor-pointer dark:fill-gray-400 dark:text-gray-100 fill-gray-200 text-gray-800 ${a?"":"hidden"}`}),L.jsx("img",{src:d,alt:"Upload preview",className:"w-full h-full object-cover rounded-md"})]})}const $h=!!navigator.gpu,Bh=120,Hh=[{title:"Describe this image",text:"Can you describe this image?",images:["https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/new-york.jpg"]},{title:"Handwriting recognition",text:"What does this say?",images:["https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/handwritten-math.jpg"]},{title:"Chart analysis",text:"Where do the severe droughts happen according to this diagram?",images:["https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/weather-events-diagram.png"]}];function Wh(){const d=ve.useRef(null),s=ve.useRef(null),o=ve.useRef(null),a=ve.useRef(null),[f,p]=ve.useState(null),[y,k]=ve.useState(null),[T,_]=ve.useState(""),[S,I]=ve.useState([]),[A,D]=ve.useState(!1),[V,F]=ve.useState(""),[K,he]=ve.useState([]),[ae,Ee]=ve.useState([]),[te,me]=ve.useState(null),[ne,Ne]=ve.useState(null);function ce(J,fe){const ue=[...fe.map(de=>({type:"image",image:de})),{type:"text",text:J}];Ee(de=>[...de,{role:"user",content:ue}]),me(null),D(!0),F(""),he([])}function kt(){d.current.postMessage({type:"interrupt"})}ve.useEffect(()=>{nt()},[V]);function nt(){if(!s.current)return;const J=s.current;J.style.height="auto";const fe=Math.min(Math.max(J.scrollHeight,24),200);J.style.height=`${fe}px`}ve.useEffect(()=>{d.current||(d.current=new Worker(new URL("/assets/worker-SSVLpBh2.js",import.meta.url),{type:"module"}),d.current.postMessage({type:"check"}));const J=ue=>{switch(ue.data.status){case"loading":p("loading"),_(ue.data.data);break;case"initiate":I(de=>[...de,ue.data]);break;case"progress":I(de=>de.map(we=>we.file===ue.data.file?{...we,...ue.data}:we));break;case"done":I(de=>de.filter(we=>we.file!==ue.data.file));break;case"ready":p("ready");break;case"start":Ee(de=>[...de,{role:"assistant",content:[{type:"text",text:""}]}]);break;case"update":{const{output:de,tps:we,numTokens:_e}=ue.data;me(we),Ne(_e),Ee(O=>{const Q=[...O],j=Q.at(-1);return Q[Q.length-1]={...j,content:[{type:"text",text:j.content[0].text+de}]},Q})}break;case"complete":D(!1);break;case"error":k(ue.data.data);break}},fe=ue=>{console.error("Worker error:",ue)};return d.current.addEventListener("message",J),d.current.addEventListener("error",fe),window.addEventListener("resize",nt),()=>{d.current.removeEventListener("message",J),d.current.removeEventListener("error",fe),window.removeEventListener("resize",nt)}},[]),ve.useEffect(()=>{ae.filter(J=>J.role==="user").length!==0&&ae.at(-1).role!=="assistant"&&(me(null),d.current.postMessage({type:"generate",data:ae}))},[ae,A]),ve.useEffect(()=>{if(!o.current||!A)return;const J=o.current;J.scrollHeight-J.scrollTop-J.clientHeight0&&K.length>0;return $h?L.jsxs("div",{className:"flex flex-col h-screen mx-auto items justify-end text-gray-800 dark:text-gray-200 bg-white dark:bg-gray-900",children:[f===null&&ae.length===0&&L.jsxs("div",{className:"h-full overflow-auto scrollbar-thin flex justify-center items-center flex-col relative",children:[L.jsxs("div",{className:"flex flex-col items-center mb-1 max-w-[360px] text-center",children:[L.jsx("img",{src:"logo.png",width:"100%",height:"auto",className:"block drop-shadow-lg bg-transparent"}),L.jsx("h1",{className:"text-4xl font-bold mb-1",children:"SmolVLM WebGPU"}),L.jsxs("h2",{className:"font-semibold",children:["The smallest multimodal model in the world.",L.jsx("br",{}),"Designed for efficiency."]})]}),L.jsxs("div",{className:"flex flex-col items-center px-4",children:[L.jsxs("p",{className:"max-w-[500px] mb-4",children:[L.jsx("br",{}),"You are about to load"," ",L.jsx("a",{href:"https://huggingface.co/HuggingFaceTB/SmolVLM-256M-Instruct",target:"_blank",rel:"noreferrer",className:"font-medium underline",children:"SmolVLM-256M-Instruct"}),", a 256M parameter multimodal model optimized for in-browser inference. Everything runs entirely in your browser with"," ",L.jsx("a",{href:"https://huggingface.co/docs/transformers.js",target:"_blank",rel:"noreferrer",className:"underline",children:"🤗 Transformers.js"})," ","and ONNX Runtime Web, meaning no data is sent to a server. Once loaded, it can even be used offline. The source code for the demo is available on"," ",L.jsx("a",{href:"https://github.com/huggingface/transformers.js-examples/tree/main/smolvlm-webgpu",target:"_blank",rel:"noreferrer",className:"font-medium underline",children:"GitHub"}),"."]}),y&&L.jsxs("div",{className:"text-red-500 text-center mb-2",children:[L.jsx("p",{className:"mb-1",children:"Unable to load model due to the following error:"}),L.jsx("p",{className:"text-sm",children:y})]}),L.jsx("button",{className:"border border-gray-300 dark:border-gray-600 px-4 py-2 rounded-lg bg-blue-400 text-white hover:bg-blue-500 disabled:bg-blue-100 cursor-pointer disabled:cursor-not-allowed select-none",onClick:()=>{d.current.postMessage({type:"load"}),p("loading")},disabled:f!==null||y!==null,children:"Load model"})]})]}),f==="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:T}),S.map(({file:J,progress:fe,total:ue},de)=>L.jsx(Dh,{text:J,percentage:fe,total:ue},de))]})}),f==="ready"&&L.jsxs("div",{ref:o,className:"overflow-y-auto scrollbar-thin w-full flex flex-col items-center h-full",children:[L.jsx(zh,{messages:ae}),ae.length===0&&L.jsx("div",{className:"flex",children:Hh.map((J,fe)=>L.jsxs("div",{className:"max-w-[250px] m-1 border border-gray-300 dark:border-gray-600 rounded-md p-2 bg-gray-100 dark:bg-gray-700 cursor-pointer",onClick:()=>ce(J.text,J.images),children:[J.text,J.images.map((ue,de)=>L.jsx("img",{src:ue,className:"w-full h-auto mt-2",alt:"Example"},de))]},fe))}),L.jsx("p",{className:"text-center text-sm min-h-6 text-gray-500 dark:text-gray-300",children:te&&ae.length>0&&L.jsxs(L.Fragment,{children:[!A&&L.jsxs("span",{children:["Generated ",ne," tokens in"," ",(ne/te).toFixed(2)," seconds ("]}),L.jsxs(L.Fragment,{children:[L.jsx("span",{className:"font-medium text-center mr-1 text-black dark:text-white",children:te.toFixed(2)}),L.jsx("span",{className:"text-gray-500 dark:text-gray-300",children:"tokens/second"})]}),!A&&L.jsxs(L.Fragment,{children:[L.jsx("span",{className:"mr-1",children:")."}),L.jsx("span",{className:"underline cursor-pointer",onClick:()=>{d.current.postMessage({type:"reset"}),Ee([])},children:"Reset"})]})]})})]}),L.jsxs("div",{className:"mt-2 border border-gray-300 dark:bg-gray-700 rounded-lg w-[600px] max-w-[80%] max-h-[200px] mx-auto relative mb-3 flex",children:[L.jsxs("label",{htmlFor:"file-upload",className:f==="ready"?"cursor-pointer":"cursor-not-allowed pointer-events-none",children:[L.jsx(jh,{className:`h-8 w-8 p-1 rounded-md ${f==="ready"?"text-gray-800 dark:text-gray-100":"text-gray-400 dark:text-gray-500"} absolute bottom-3 left-1.5`}),L.jsx("input",{ref:a,id:"file-upload",type:"file",accept:"image/*",className:"hidden",multiple:!0,onInput:async J=>{const fe=Array.from(J.target.files);if(fe.length===0)return;const ue=fe.map(we=>new Promise((_e,O)=>{const Q=new FileReader;Q.onload=j=>_e(j.target.result),Q.onerror=O,Q.readAsDataURL(we)})),de=await Promise.all(ue);he(we=>[...we,...de]),J.target.value=""}})]}),L.jsxs("div",{className:"w-full flex flex-col",children:[L.jsx("div",{className:"flex w-full",children:K.map((J,fe)=>L.jsx(Uh,{onRemove:()=>{he(ue=>ue.filter((de,we)=>we!==fe))},src:J,className:"w-20 h-20 min-w-20 min-h-20 relative p-2"},fe))}),L.jsx("textarea",{ref:s,className:"scrollbar-thin w-full pl-11 pr-12 dark:bg-gray-700 py-4 rounded-lg bg-transparent border-none outline-none text-gray-800 disabled:text-gray-400 dark:text-gray-100 placeholder-gray-500 disabled:placeholder-gray-200 dark:placeholder-gray-300 dark:disabled:placeholder-gray-500 resize-none disabled:cursor-not-allowed",placeholder:"Select at least one image and enter message here...",type:"text",rows:1,value:V,disabled:f!=="ready",title:f==="ready"?"Model is ready":"Model not loaded yet",onKeyDown:J=>{Le&&!A&&J.key==="Enter"&&!J.shiftKey&&(J.preventDefault(),ce(V,K))},onInput:J=>F(J.target.value)})]}),A?L.jsx("div",{className:"cursor-pointer",onClick:kt,children:L.jsx(Ih,{className:"h-8 w-8 p-1 rounded-md text-gray-800 dark:text-gray-100 absolute right-3 bottom-3"})}):Le?L.jsx("div",{className:"cursor-pointer",onClick:()=>ce(V,K),children:L.jsx(cf,{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(cf,{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 :("]})}Sp.createRoot(document.getElementById("root")).render(L.jsx(ve.StrictMode,{children:L.jsx(Wh,{})})); diff --git a/assets/worker-SSVLpBh2.js b/assets/worker-SSVLpBh2.js new file mode 100644 index 0000000000000000000000000000000000000000..a0dec74529e039d9a13cf95b11f87c325e2cc86c --- /dev/null +++ b/assets/worker-SSVLpBh2.js @@ -0,0 +1,2846 @@ +var WT=Object.defineProperty;var GT=(vs,Sr,zn)=>Sr in vs?WT(vs,Sr,{enumerable:!0,configurable:!0,writable:!0,value:zn}):vs[Sr]=zn;var re=(vs,Sr,zn)=>GT(vs,typeof Sr!="symbol"?Sr+"":Sr,zn);(function(){"use strict";const vs=new Map,Sr=[],zn=(e,r,t)=>{if(r&&typeof r.init=="function"&&typeof r.createInferenceSessionHandler=="function"){const s=vs.get(e);if(s===void 0)vs.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 i=Sr.indexOf(e);i!==-1&&Sr.splice(i,1);for(let n=0;n{const r=vs.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}}},Oc=async e=>{const r=e.executionProviders||[],t=r.map(l=>typeof l=="string"?l:l.name),s=t.length===0?Sr:t;let i;const n=[],o=new Set;for(const l of s){const u=await k0(l);typeof u=="string"?n.push({name:l,err:u}):(i||(i=u),i===u&&o.add(l))}if(!i)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=>o.has(typeof l=="string"?l:l.name));return[i,new Proxy(e,{get:(l,u)=>u==="executionProviders"?a:Reflect.get(l,u)})]},I0="1.20.1";let Dc="warning";const es={wasm:{},webgl:{},webgpu:{},versions:{common:I0},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}`);Dc=e}},get logLevel(){return Dc}};Object.defineProperty(es,"logLevel",{enumerable:!0});const A0=es,F0=(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 i,n;(r==null?void 0:r.tensorLayout)!==void 0&&r.tensorLayout==="NHWC"?(i=e.dims[2],n=e.dims[3]):(i=e.dims[3],n=e.dims[2]);const o=(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*i;let c=0,h=p,g=p*2,_=-1;o==="RGBA"?(c=0,h=p,g=p*2,_=p*3):o==="RGB"?(c=0,h=p,g=p*2):o==="RBG"&&(c=0,g=p,h=p*2);for(let E=0;E{const t=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");let s;if(t!=null){let i,n,o;(r==null?void 0:r.tensorLayout)!==void 0&&r.tensorLayout==="NHWC"?(i=e.dims[2],n=e.dims[1],o=e.dims[3]):(i=e.dims[3],n=e.dims[2],o=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 c=n*i;if(r!==void 0&&(r.format!==void 0&&o===4&&r.format!=="RGBA"||o===3&&r.format!=="RGB"&&r.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");const h=4;let g=0,_=1,E=2,A=3,v=0,y=c,k=c*2,P=-1;a==="RGBA"?(v=0,y=c,k=c*2,P=c*3):a==="RGB"?(v=0,y=c,k=c*2):a==="RBG"&&(v=0,k=c,y=c*2),s=t.createImageData(i,n);for(let M=0;M{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,i=r.norm??{mean:255,bias:0};let n,o;typeof i.mean=="number"?n=[i.mean,i.mean,i.mean,i.mean]:n=[i.mean[0],i.mean[1],i.mean[2],i.mean[3]??255],typeof i.bias=="number"?o=[i.bias,i.bias,i.bias,i.bias]:o=[i.bias[0],i.bias[1],i.bias[2],i.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 c=4,h=0,g=1,_=2,E=3,A=0,v=u,y=u*2,k=-1;a==="RGB"&&(c=3,h=0,g=1,_=2,E=-1),l==="RGBA"?k=u*3:l==="RBG"?(A=0,y=u,v=u*2):l==="BGR"&&(y=0,v=u,A=u*2);for(let M=0;M{const t=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,s=typeof ImageData<"u"&&e instanceof ImageData,i=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,n=typeof e=="string";let o,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 c=u(p);if(c!=null){let h=e.height,g=e.width;if(r!==void 0&&r.resizedHeight!==void 0&&r.resizedWidth!==void 0&&(h=r.resizedHeight,g=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=h,a.width=g}else a.tensorFormat="RGBA",a.height=h,a.width=g;c.drawImage(e,0,0),o=c.getImageData(0,0,g,h).data}else throw new Error("Can not access image data")}else if(s){let p,c;if(r!==void 0&&r.resizedWidth!==void 0&&r.resizedHeight!==void 0?(p=r.resizedHeight,c=r.resizedWidth):(p=e.height,c=e.width),r!==void 0&&(a=r),a.format="RGBA",a.height=p,a.width=c,r!==void 0){const h=l();h.width=c,h.height=p;const g=u(h);if(g!=null)g.putImageData(e,0,0),o=g.getImageData(0,0,c,p).data;else throw new Error("Can not access image data")}else o=e.data}else if(i){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 c=u(p);if(c!=null){const h=e.height,g=e.width;return c.drawImage(e,0,0,g,h),o=c.getImageData(0,0,g,h).data,a.height=h,a.width=g,ad(o,a)}else throw new Error("Can not access image data")}else{if(n)return new Promise((p,c)=>{const h=l(),g=u(h);if(!e||!g)return c();const _=new Image;_.crossOrigin="Anonymous",_.src=e,_.onload=()=>{h.width=_.width,h.height=_.height,g.drawImage(_,0,0,h.width,h.height);const E=g.getImageData(0,0,h.width,h.height);a.height=h.height,a.width=h.width,p(ad(E.data,a))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(o!==void 0)return ad(o,a);throw new Error("Input data provided is not supported - aborted tensor creation")},L0=(e,r)=>{const{width:t,height:s,download:i,dispose:n}=r,o=[1,s,t,4];return new Gr({location:"texture",type:"float32",texture:e,dims:o,download:i,dispose:n})},z0=(e,r)=>{const{dataType:t,dims:s,download:i,dispose:n}=r;return new Gr({location:"gpu-buffer",type:t??"float32",gpuBuffer:e,dims:s,download:i,dispose:n})},B0=(e,r)=>{const{dataType:t,dims:s,download:i,dispose:n}=r;return new Gr({location:"ml-tensor",type:t??"float32",mlTensor:e,dims:s,download:i,dispose:n})},R0=(e,r,t)=>new Gr({location:"cpu-pinned",type:e,data:r,dims:t??[r.length]}),Bn=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),ha=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);let Lc=!1;const N0=()=>{if(!Lc){Lc=!0;const e=typeof BigInt64Array<"u"&&BigInt64Array.from,r=typeof BigUint64Array<"u"&&BigUint64Array.from,t=typeof Float16Array<"u"&&Float16Array.from;e&&(Bn.set("int64",BigInt64Array),ha.set(BigInt64Array,"int64")),r&&(Bn.set("uint64",BigUint64Array),ha.set(BigUint64Array,"uint64")),t?(Bn.set("float16",Float16Array),ha.set(Float16Array,"float16")):Bn.set("float16",Uint16Array)}},j0=e=>{let r=1;for(let t=0;t{switch(e.location){case"cpu":return new Gr(e.type,e.data,r);case"cpu-pinned":return new Gr({location:"cpu-pinned",data:e.data,type:e.type,dims:r});case"texture":return new Gr({location:"texture",texture:e.texture,type:e.type,dims:r});case"gpu-buffer":return new Gr({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:r});case"ml-tensor":return new Gr({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:r});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}};let Gr=class{constructor(r,t,s){N0();let i,n;if(typeof r=="object"&&"location"in r)switch(this.dataLocation=r.location,i=r.type,n=r.dims,r.location){case"cpu-pinned":{const a=Bn.get(i);if(!a)throw new TypeError(`unsupported type "${i}" 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(i!=="float32")throw new TypeError(`unsupported type "${i}" to create tensor from texture`);this.gpuTextureData=r.texture,this.downloader=r.download,this.disposer=r.dispose;break}case"gpu-buffer":{if(i!=="float32"&&i!=="float16"&&i!=="int32"&&i!=="int64"&&i!=="uint32"&&i!=="uint8"&&i!=="bool"&&i!=="uint4"&&i!=="int4")throw new TypeError(`unsupported type "${i}" to create tensor from gpu buffer`);this.gpuBufferData=r.gpuBuffer,this.downloader=r.download,this.disposer=r.dispose;break}case"ml-tensor":{if(i!=="float32"&&i!=="float16"&&i!=="int32"&&i!=="int64"&&i!=="uint32"&&i!=="uint64"&&i!=="int8"&&i!=="uint8"&&i!=="bool")throw new TypeError(`unsupported type "${i}" 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(i=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=Bn.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 throw new TypeError(`A ${i} 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")i="string",a=r;else if(u==="boolean")i="bool",a=Uint8Array.from(r);else throw new TypeError(`Invalid element type of data array: ${u}.`)}else if(r instanceof Uint8ClampedArray)i="uint8",a=Uint8Array.from(r);else{const u=ha.get(r.constructor);if(u===void 0)throw new TypeError(`Unsupported type for tensor data: ${r.constructor}.`);i=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 o=j0(n);if(this.cpuData&&o!==this.cpuData.length&&!((i==="uint4"||i==="int4")&&Math.ceil(o/2)===this.cpuData.length))throw new Error(`Tensor's size(${o}) does not match data length(${this.cpuData.length}).`);this.type=i,this.dims=n,this.size=o}static async fromImage(r,t){return D0(r,t)}static fromTexture(r,t){return L0(r,t)}static fromGpuBuffer(r,t){return z0(r,t)}static fromMLTensor(r,t){return B0(r,t)}static fromPinnedBuffer(r,t,s){return R0(r,t,s)}toDataURL(r){return F0(this,r)}toImageData(r){return O0(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 V0(this,r)}};const ts=Gr,zc=(e,r)=>{(typeof es.trace>"u"?!es.wasm.trace:!es.trace)||console.timeStamp(`${e}::ORT::${r}`)},Bc=(e,r)=>{var i;const t=((i=new Error().stack)==null?void 0:i.split(/\r\n|\r|\n/g))||[];let s=!1;for(let n=0;n{(typeof es.trace>"u"?!es.wasm.trace:!es.trace)||Bc("BEGIN",e)},dd=e=>{(typeof es.trace>"u"?!es.wasm.trace:!es.trace)||Bc("END",e)},U0=class P0{constructor(r){this.handler=r}async run(r,t,s){ld();const i={};let n={};if(typeof r!="object"||r===null||r instanceof ts||Array.isArray(r))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let o=!0;if(typeof t=="object"){if(t===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(t instanceof ts)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.");o=!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}.`);i[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 c of this.outputNames)if(p.indexOf(c)!==-1){const h=t[c];(h===null||h instanceof ts)&&(u=!0,o=!1,i[c]=h)}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(o)for(const u of this.outputNames)i[u]=null;const a=await this.handler.run(r,i,n),l={};for(const u in a)if(Object.hasOwnProperty.call(a,u)){const p=a[u];p instanceof ts?l[u]=p:l[u]=new ts(p.type,p.data,p.dims)}return dd(),l}async release(){return this.handler.dispose()}static async create(r,t,s,i){ld();let n,o={};if(typeof r=="string"){if(n=r,typeof t=="object"&&t!==null)o=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)o=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 c=0,h=r.byteLength;if(typeof t=="object"&&t!==null)o=t;else if(typeof t=="number"){if(c=t,!Number.isSafeInteger(c))throw new RangeError("'byteOffset' must be an integer.");if(c<0||c>=p.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${p.byteLength}).`);if(h=r.byteLength-c,typeof s=="number"){if(h=s,!Number.isSafeInteger(h))throw new RangeError("'byteLength' must be an integer.");if(h<=0||c+h>p.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${p.byteLength-c}].`);if(typeof i=="object"&&i!==null)o=i;else if(typeof i<"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,c,h)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");const[a,l]=await Oc(o),u=await a.createInferenceSessionHandler(n,l);return dd(),new P0(u)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}},W0="Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.";var G0=Object.freeze({__proto__:null,InferenceSession:U0,TRACE:zc,TRACE_FUNC_BEGIN:ld,TRACE_FUNC_END:dd,Tensor:ts,TrainingSession:class C0{constructor(r,t,s){this.handler=r,this.hasOptimizerModel=t,this.hasEvalModel=s}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(r,t){const s=r.evalModel||"",i=r.optimizerModel||"",n=t||{},[o,a]=await Oc(n);if(o.createTrainingSessionHandler){const l=await o.createTrainingSessionHandler(r.checkpointState,r.trainModel,s,i,a);return new C0(l,!!r.optimizerModel,!!r.evalModel)}else throw new Error(W0)}typeNarrowingForRunStep(r,t,s,i,n){const o={};let a={};if(typeof s!="object"||s===null||s instanceof ts||Array.isArray(s))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let l=!0;if(typeof i=="object"){if(i===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(i instanceof ts)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(i)){if(i.length===0)throw new TypeError("'fetches' cannot be an empty array.");l=!1;for(const u of i){if(typeof u!="string")throw new TypeError("'fetches' must be a string array or an object.");if(t.indexOf(u)===-1)throw new RangeError(`'fetches' contains invalid output name: ${u}.`);o[u]=null}if(typeof n=="object"&&n!==null)a=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else{let u=!1;const p=Object.getOwnPropertyNames(i);for(const c of t)if(p.indexOf(c)!==-1){const h=i[c];(h===null||h instanceof ts)&&(u=!0,l=!1,o[c]=h)}if(u){if(typeof n=="object"&&n!==null)a=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else a=i}}else if(typeof i<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const u of r)if(typeof s[u]>"u")throw new Error(`input '${u}' is missing in 'feeds'.`);if(l)for(const u of t)o[u]=null;return[o,a]}convertHandlerReturnTypeToMapOfTensors(r){const t={};for(const s in r)if(Object.hasOwnProperty.call(r,s)){const i=r[s];i instanceof ts?t[s]=i:t[s]=new ts(i.type,i.data,i.dims)}return t}async lazyResetGrad(){await this.handler.lazyResetGrad()}async runTrainStep(r,t,s){const[i,n]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,r,t,s),o=await this.handler.runTrainStep(r,i,n);return this.convertHandlerReturnTypeToMapOfTensors(o)}async runOptimizerStep(r){if(this.hasOptimizerModel)await this.handler.runOptimizerStep(r||{});else throw new Error("This TrainingSession has no OptimizerModel loaded.")}async runEvalStep(r,t,s){if(this.hasEvalModel){const[i,n]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,r,t,s),o=await this.handler.runEvalStep(r,i,n);return this.convertHandlerReturnTypeToMapOfTensors(o)}else throw new Error("This TrainingSession has no EvalModel loaded.")}async getParametersSize(r=!0){return this.handler.getParametersSize(r)}async loadParametersBuffer(r,t=!0){const s=await this.getParametersSize(t);if(r.length!==4*s)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(r,t)}async getContiguousParameters(r=!0){return this.handler.getContiguousParameters(r)}async release(){return this.handler.dispose()}},env:A0,registerBackend:zn});/*! + * ONNX Runtime Web v1.22.0-dev.20250306-ccf8fdd9ea + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */var ud=Object.defineProperty,K0=Object.getOwnPropertyDescriptor,H0=Object.getOwnPropertyNames,q0=Object.prototype.hasOwnProperty,Q0=(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')}),Ve=(e,r)=>()=>(e&&(r=e(e=0)),r),Ci=(e,r)=>{for(var t in r)ud(e,t,{get:r[t],enumerable:!0})},X0=(e,r,t,s)=>{if(r&&typeof r=="object"||typeof r=="function")for(let i of H0(r))!q0.call(e,i)&&i!==t&&ud(e,i,{get:()=>r[i],enumerable:!(s=K0(r,i))||s.enumerable});return e},fa=e=>X0(ud({},"__esModule",{value:!0}),e),Si,Gs,pn,Rc,Nc,jc=Ve(()=>{Si=new Map,Gs=[],pn=(e,r,t)=>{if(r&&typeof r.init=="function"&&typeof r.createInferenceSessionHandler=="function"){let s=Si.get(e);if(s===void 0)Si.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 i=Gs.indexOf(e);i!==-1&&Gs.splice(i,1);for(let n=0;n{let r=Si.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}}},Nc=async e=>{let r=e.executionProviders||[],t=r.map(l=>typeof l=="string"?l:l.name),s=t.length===0?Gs:t,i,n=[],o=new Set;for(let l of s){let u=await Rc(l);typeof u=="string"?n.push({name:l,err:u}):(i||(i=u),i===u&&o.add(l))}if(!i)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=>o.has(typeof l=="string"?l:l.name));return[i,new Proxy(e,{get:(l,u)=>u==="executionProviders"?a:Reflect.get(l,u)})]}}),J0=Ve(()=>{jc()}),Vc,Y0=Ve(()=>{Vc="1.22.0-dev.20250306-aafa8d170a"}),cd,Kr,Uc=Ve(()=>{Y0(),cd="warning",Kr={wasm:{},webgl:{},webgpu:{},versions:{common:Vc},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}`);cd=e}},get logLevel(){return cd}},Object.defineProperty(Kr,"logLevel",{enumerable:!0})}),Ut,Z0=Ve(()=>{Uc(),Ut=Kr}),Wc,Gc,ev=Ve(()=>{Wc=(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 i,n;(r==null?void 0:r.tensorLayout)!==void 0&&r.tensorLayout==="NHWC"?(i=e.dims[2],n=e.dims[3]):(i=e.dims[3],n=e.dims[2]);let o=(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*i,c=0,h=p,g=p*2,_=-1;o==="RGBA"?(c=0,h=p,g=p*2,_=p*3):o==="RGB"?(c=0,h=p,g=p*2):o==="RBG"&&(c=0,g=p,h=p*2);for(let E=0;E{let t=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),s;if(t!=null){let i,n,o;(r==null?void 0:r.tensorLayout)!==void 0&&r.tensorLayout==="NHWC"?(i=e.dims[2],n=e.dims[1],o=e.dims[3]):(i=e.dims[3],n=e.dims[2],o=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 c=n*i;if(r!==void 0&&(r.format!==void 0&&o===4&&r.format!=="RGBA"||o===3&&r.format!=="RGB"&&r.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let h=4,g=0,_=1,E=2,A=3,v=0,y=c,k=c*2,P=-1;a==="RGBA"?(v=0,y=c,k=c*2,P=c*3):a==="RGB"?(v=0,y=c,k=c*2):a==="RBG"&&(v=0,k=c,y=c*2),s=t.createImageData(i,n);for(let M=0;M{hd(),ma=(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,i=r.norm??{mean:255,bias:0},n,o;typeof i.mean=="number"?n=[i.mean,i.mean,i.mean,i.mean]:n=[i.mean[0],i.mean[1],i.mean[2],i.mean[3]??255],typeof i.bias=="number"?o=[i.bias,i.bias,i.bias,i.bias]:o=[i.bias[0],i.bias[1],i.bias[2],i.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),c=4,h=0,g=1,_=2,E=3,A=0,v=u,y=u*2,k=-1;a==="RGB"&&(c=3,h=0,g=1,_=2,E=-1),l==="RGBA"?k=u*3:l==="RBG"?(A=0,y=u,v=u*2):l==="BGR"&&(y=0,v=u,A=u*2);for(let P=0;P{let t=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,s=typeof ImageData<"u"&&e instanceof ImageData,i=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,n=typeof e=="string",o,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 c=u(p);if(c!=null){let h=e.height,g=e.width;if(r!==void 0&&r.resizedHeight!==void 0&&r.resizedWidth!==void 0&&(h=r.resizedHeight,g=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=h,a.width=g}else a.tensorFormat="RGBA",a.height=h,a.width=g;c.drawImage(e,0,0),o=c.getImageData(0,0,g,h).data}else throw new Error("Can not access image data")}else if(s){let p,c;if(r!==void 0&&r.resizedWidth!==void 0&&r.resizedHeight!==void 0?(p=r.resizedHeight,c=r.resizedWidth):(p=e.height,c=e.width),r!==void 0&&(a=r),a.format="RGBA",a.height=p,a.width=c,r!==void 0){let h=l();h.width=c,h.height=p;let g=u(h);if(g!=null)g.putImageData(e,0,0),o=g.getImageData(0,0,c,p).data;else throw new Error("Can not access image data")}else o=e.data}else if(i){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 c=u(p);if(c!=null){let h=e.height,g=e.width;return c.drawImage(e,0,0,g,h),o=c.getImageData(0,0,g,h).data,a.height=h,a.width=g,ma(o,a)}else throw new Error("Can not access image data")}else{if(n)return new Promise((p,c)=>{let h=l(),g=u(h);if(!e||!g)return c();let _=new Image;_.crossOrigin="Anonymous",_.src=e,_.onload=()=>{h.width=_.width,h.height=_.height,g.drawImage(_,0,0,h.width,h.height);let E=g.getImageData(0,0,h.width,h.height);a.height=h.height,a.width=h.width,p(ma(E.data,a))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(o!==void 0)return ma(o,a);throw new Error("Input data provided is not supported - aborted tensor creation")},Hc=(e,r)=>{let{width:t,height:s,download:i,dispose:n}=r,o=[1,s,t,4];return new Br({location:"texture",type:"float32",texture:e,dims:o,download:i,dispose:n})},qc=(e,r)=>{let{dataType:t,dims:s,download:i,dispose:n}=r;return new Br({location:"gpu-buffer",type:t??"float32",gpuBuffer:e,dims:s,download:i,dispose:n})},Qc=(e,r)=>{let{dataType:t,dims:s,download:i,dispose:n}=r;return new Br({location:"ml-tensor",type:t??"float32",mlTensor:e,dims:s,download:i,dispose:n})},Xc=(e,r,t)=>new Br({location:"cpu-pinned",type:e,data:r,dims:t??[r.length]})}),hn,$i,pd,Jc,rv=Ve(()=>{hn=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),$i=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),pd=!1,Jc=()=>{if(!pd){pd=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,r=typeof BigUint64Array<"u"&&BigUint64Array.from,t=globalThis.Float16Array,s=typeof t<"u"&&t.from;e&&(hn.set("int64",BigInt64Array),$i.set(BigInt64Array,"int64")),r&&(hn.set("uint64",BigUint64Array),$i.set(BigUint64Array,"uint64")),s?(hn.set("float16",t),$i.set(t,"float16")):hn.set("float16",Uint16Array)}}}),Yc,Zc,sv=Ve(()=>{hd(),Yc=e=>{let r=1;for(let t=0;t{switch(e.location){case"cpu":return new Br(e.type,e.data,r);case"cpu-pinned":return new Br({location:"cpu-pinned",data:e.data,type:e.type,dims:r});case"texture":return new Br({location:"texture",texture:e.texture,type:e.type,dims:r});case"gpu-buffer":return new Br({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:r});case"ml-tensor":return new Br({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:r});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),Br,hd=Ve(()=>{ev(),tv(),rv(),sv(),Br=class{constructor(e,r,t){Jc();let s,i;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,s=e.type,i=e.dims,e.location){case"cpu-pinned":{let o=hn.get(s);if(!o)throw new TypeError(`unsupported type "${s}" to create tensor from pinned buffer`);if(!(e.data instanceof o))throw new TypeError(`buffer should be of type ${o.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 o,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.");o=r}else{let l=hn.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"?o=l.from(r,BigInt):o=l.from(r)}else if(r instanceof l)o=r;else if(r instanceof Uint8ClampedArray)if(e==="uint8")o=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)o=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",o=e;else if(l==="boolean")s="bool",o=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${l}.`)}else if(e instanceof Uint8ClampedArray)s="uint8",o=Uint8Array.from(e);else{let l=$i.get(e.constructor);if(l===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);s=l,o=e}if(a===void 0)a=[o.length];else if(!Array.isArray(a))throw new TypeError("A tensor's dims must be a number array");i=a,this.cpuData=o,this.dataLocation="cpu"}let n=Yc(i);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=i,this.size=n}static async fromImage(e,r){return Kc(e,r)}static fromTexture(e,r){return Hc(e,r)}static fromGpuBuffer(e,r){return qc(e,r)}static fromMLTensor(e,r){return Qc(e,r)}static fromPinnedBuffer(e,r,t){return Xc(e,r,t)}toDataURL(e){return Wc(this,e)}toImageData(e){return Gc(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 Zc(this,e)}}}),rs,ep=Ve(()=>{hd(),rs=Br}),ki,fd,ss,Hr,tp=Ve(()=>{Uc(),ki=(e,r)=>{(typeof Kr.trace>"u"?!Kr.wasm.trace:!Kr.trace)||console.timeStamp(`${e}::ORT::${r}`)},fd=(e,r)=>{var i;let t=((i=new Error().stack)==null?void 0:i.split(/\r\n|\r|\n/g))||[],s=!1;for(let n=0;n{(typeof Kr.trace>"u"?!Kr.wasm.trace:!Kr.trace)||fd("BEGIN",e)},Hr=e=>{(typeof Kr.trace>"u"?!Kr.wasm.trace:!Kr.trace)||fd("END",e)}}),rp,nv=Ve(()=>{jc(),ep(),tp(),rp=class S0{constructor(r){this.handler=r}async run(r,t,s){ss();let i={},n={};if(typeof r!="object"||r===null||r instanceof rs||Array.isArray(r))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let o=!0;if(typeof t=="object"){if(t===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(t instanceof rs)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.");o=!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}.`);i[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 c of this.outputNames)if(p.indexOf(c)!==-1){let h=t[c];(h===null||h instanceof rs)&&(u=!0,o=!1,i[c]=h)}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(o)for(let u of this.outputNames)i[u]=null;let a=await this.handler.run(r,i,n),l={};for(let u in a)if(Object.hasOwnProperty.call(a,u)){let p=a[u];p instanceof rs?l[u]=p:l[u]=new rs(p.type,p.data,p.dims)}return Hr(),l}async release(){return this.handler.dispose()}static async create(r,t,s,i){ss();let n,o={};if(typeof r=="string"){if(n=r,typeof t=="object"&&t!==null)o=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)o=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,c=0,h=r.byteLength;if(typeof t=="object"&&t!==null)o=t;else if(typeof t=="number"){if(c=t,!Number.isSafeInteger(c))throw new RangeError("'byteOffset' must be an integer.");if(c<0||c>=p.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${p.byteLength}).`);if(h=r.byteLength-c,typeof s=="number"){if(h=s,!Number.isSafeInteger(h))throw new RangeError("'byteLength' must be an integer.");if(h<=0||c+h>p.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${p.byteLength-c}].`);if(typeof i=="object"&&i!==null)o=i;else if(typeof i<"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,c,h)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[a,l]=await Nc(o),u=await a.createInferenceSessionHandler(n,l);return Hr(),new S0(u)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}}),md,iv=Ve(()=>{nv(),md=rp}),ov=Ve(()=>{}),av=Ve(()=>{}),lv=Ve(()=>{}),dv=Ve(()=>{}),sp={};Ci(sp,{InferenceSession:()=>md,TRACE:()=>ki,TRACE_FUNC_BEGIN:()=>ss,TRACE_FUNC_END:()=>Hr,Tensor:()=>rs,env:()=>Ut,registerBackend:()=>pn});var ns=Ve(()=>{J0(),Z0(),iv(),ep(),ov(),av(),tp(),lv(),dv()}),_d=Ve(()=>{}),np={};Ci(np,{default:()=>ip});var gd,wd,ip,uv=Ve(()=>{var e;Lw(),fn(),Pd(),gd="ort-wasm-proxy-worker",wd=((e=globalThis.self)==null?void 0:e.name)===gd,wd&&(self.onmessage=r=>{let{type:t,in:s}=r.data;try{switch(t){case"init-wasm":$d(s.wasm).then(()=>{Bu(s).then(()=>{postMessage({type:t})},i=>{postMessage({type:t,err:i})})},i=>{postMessage({type:t,err:i})});break;case"init-ep":{let{epName:i,env:n}=s;Ru(n,i).then(()=>{postMessage({type:t})},o=>{postMessage({type:t,err:o})});break}case"copy-from":{let{buffer:i}=s,n=Fa(i);postMessage({type:t,out:n});break}case"create":{let{model:i,options:n}=s;Nu(i,n).then(o=>{postMessage({type:t,out:o})},o=>{postMessage({type:t,err:o})});break}case"release":ju(s),postMessage({type:t});break;case"run":{let{sessionId:i,inputIndices:n,inputs:o,outputIndices:a,options:l}=s;Uu(i,n,o,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},Gu([...o,...u]))},u=>{postMessage({type:t,err:u})});break}case"end-profiling":Wu(s),postMessage({type:t});break;default:}}catch(i){postMessage({type:t,err:i})}}),ip=wd?null:r=>new Worker(r??Rr,{type:"module",name:gd})}),op={};Ci(op,{default:()=>ap});var yd,Md,ap,lp,cv=Ve(()=>{var e,r;Md=(yd=self.location.href,async function(t={}){var ua;var s,i,n=t,o=new Promise((d,f)=>{s=d,i=f}),a=typeof window=="object",l=typeof WorkerGlobalScope<"u",u=l&&((ua=self.name)==null?void 0:ua.startsWith("em-pthread"));n.mountExternalData=(d,f)=>{d.startsWith("./")&&(d=d.substring(2)),(n.Bd||(n.Bd=new Map)).set(d,f)},n.unmountExternalData=()=>{delete n.Bd};var p=globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,shared:!0}).buffer.constructor;let c=()=>{let d=(T,C,I)=>(...W)=>{let ne=Rt,ye=C==null?void 0:C();W=T(...W);let Ee=C==null?void 0:C();return ye!==Ee&&(T=Ee,I(ye),C=I=null),Rt!=ne?new Promise((ze,Ye)=>{nn={resolve:ze,reject:Ye}}):W},f=T=>async(...C)=>{var I;try{if(n.Cd)throw Error("Session already started");let W=n.Cd={be:C[0],errors:[]},ne=await T(...C);if(n.Cd!==W)throw Error("Session mismatch");(I=n.Dd)==null||I.flush();let ye=W.errors;if(0ze),0n._OrtCreateSession,T=>n._OrtCreateSession=T),n._OrtRun=f(d(n._OrtRun,()=>n._OrtRun,T=>n._OrtRun=T)),n._OrtRunWithBinding=f(d(n._OrtRunWithBinding,()=>n._OrtRunWithBinding,T=>n._OrtRunWithBinding=T)),n._OrtBindInput=d(n._OrtBindInput,()=>n._OrtBindInput,T=>n._OrtBindInput=T),c=void 0};n.jsepInit=(d,f)=>{if(c==null||c(),d==="webgpu"){[n.Dd,n.Rd,n.Vd,n.Hd,n.Ud,n.hc,n.Wd,n.Zd,n.Sd,n.Td,n.Xd]=f;let T=n.Dd;n.jsepRegisterBuffer=(C,I,W,ne)=>T.registerBuffer(C,I,W,ne),n.jsepGetBuffer=C=>T.getBuffer(C),n.jsepCreateDownloader=(C,I,W)=>T.createDownloader(C,I,W),n.jsepOnCreateSession=C=>{T.onCreateSession(C)},n.jsepOnReleaseSession=C=>{T.onReleaseSession(C)},n.jsepOnRunStart=C=>T.onRunStart(C),n.$d=(C,I)=>{T.upload(C,I)}}else if(d==="webnn"){[n.Dd,n.Yd,n.Id,n.jsepEnsureTensor,n.Jd,n.jsepDownloadTensor]=f,n.jsepReleaseTensorId=n.Id,n.jsepUploadTensor=n.Jd;let T=n.Dd;n.jsepOnRunStart=C=>T.onRunStart(C),n.jsepOnRunEnd=T.onRunEnd.bind(T),n.jsepRegisterMLContext=(C,I)=>{T.registerMLContext(C,I)},n.jsepOnReleaseSession=C=>{T.onReleaseSession(C)},n.jsepCreateMLTensorDownloader=(C,I)=>T.createMLTensorDownloader(C,I),n.jsepRegisterMLTensor=(C,I,W,ne)=>T.registerMLTensor(C,I,W,ne),n.jsepCreateMLContext=C=>T.createMLContext(C),n.jsepRegisterMLConstant=(C,I,W,ne,ye)=>T.registerMLConstant(C,I,W,ne,ye,n.Bd),n.jsepRegisterGraphInput=T.registerGraphInput.bind(T),n.jsepIsGraphInput=T.isGraphInput.bind(T),n.jsepCreateTemporaryTensor=T.createTemporaryTensor.bind(T)}};var h,g,_=Object.assign({},n),E=(d,f)=>{throw f},A="";(a||l)&&(l?A=self.location.href:typeof document<"u"&&document.currentScript&&(A=document.currentScript.src),yd&&(A=yd),A=A.startsWith("blob:")?"":A.slice(0,A.replace(/[?#].*/,"").lastIndexOf("/")+1),l&&(g=d=>{var f=new XMLHttpRequest;return f.open("GET",d,!1),f.responseType="arraybuffer",f.send(null),new Uint8Array(f.response)}),h=async d=>{if(he(d))return new Promise((T,C)=>{var I=new XMLHttpRequest;I.open("GET",d,!0),I.responseType="arraybuffer",I.onload=()=>{I.status==200||I.status==0&&I.response?T(I.response):C(I.status)},I.onerror=C,I.send(null)});var f=await fetch(d,{credentials:"same-origin"});if(f.ok)return f.arrayBuffer();throw Error(f.status+" : "+f.url)});var v=console.log.bind(console),y=console.error.bind(console),k=v,P=y;Object.assign(n,_),_=null;var M,w,x,$,z,R,Q,q,U,Z,H,J,ie,ae=n.wasmBinary,ue=!1,he=d=>d.startsWith("file://");function N(){return M.buffer!=$.buffer&&K(),$}function O(){return M.buffer!=$.buffer&&K(),z}function G(){return M.buffer!=$.buffer&&K(),R}function se(){return M.buffer!=$.buffer&&K(),Q}function X(){return M.buffer!=$.buffer&&K(),q}function we(){return M.buffer!=$.buffer&&K(),U}function _e(){return M.buffer!=$.buffer&&K(),Z}function ke(){return M.buffer!=$.buffer&&K(),ie}if(u){let d=function(f){try{var T=f.data,C=T.yd;if(C==="load"){let I=[];self.onmessage=W=>I.push(W),self.startWorker=()=>{postMessage({yd:"loaded"});for(let W of I)d(W);self.onmessage=d};for(let W of T.Od)n[W]&&!n[W].proxy||(n[W]=(...ne)=>{postMessage({yd:"callHandler",Nd:W,args:ne})},W=="print"&&(k=n[W]),W=="printErr"&&(P=n[W]));M=T.he,K(),He(T.ie)}else if(C==="run"){Ds(T.xd),ti(T.xd,0,0,1,0,0),jt(),Ot(T.xd),Me||(ei(),Me=!0);try{Dr(T.de,T.Fd)}catch(I){if(I!="unwind")throw I}}else T.target!=="setimmediate"&&(C==="checkMailbox"?Me&&Vt():C&&(P(`worker: received unknown command ${C}`),P(T)))}catch(I){throw co(),I}};var He,Me=!1;P=function(...f){f=f.join(" "),console.error(f)},self.alert=function(...f){postMessage({yd:"alert",text:f.join(" "),fe:An()})},self.onunhandledrejection=f=>{throw f.reason||f},self.onmessage=d}function K(){var d=M.buffer;n.HEAP8=$=new Int8Array(d),n.HEAP16=R=new Int16Array(d),n.HEAPU8=z=new Uint8Array(d),n.HEAPU16=Q=new Uint16Array(d),n.HEAP32=q=new Int32Array(d),n.HEAPU32=U=new Uint32Array(d),n.HEAPF32=Z=new Float32Array(d),n.HEAPF64=ie=new Float64Array(d),n.HEAP64=H=new BigInt64Array(d),n.HEAPU64=J=new BigUint64Array(d)}function j(){u?startWorker(n):Oe.Bb()}u||(M=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),K());var fe,Pe=0,xe=null;function Ae(){if(--Pe==0&&xe){var d=xe;xe=null,d()}}function Ie(d){throw P(d="Aborted("+d+")"),ue=!0,d=new WebAssembly.RuntimeError(d+". Build with -sASSERTIONS for more info."),i(d),d}function Le(){return{a:{Ta:D,Va:We,W:Ls,la:dt,b:xs,u:Es,R:Ps,Za:zs,d:fr,pb:et,g:Vr,T:kr,Ga:hs,lb:ms,nb:_s,Ha:Qr,Ea:Cs,wb:Xs,Da:Js,pa:Ys,mb:Zs,jb:gs,Fa:en,kb:tn,Ma:Ss,za:En,eb:Pn,cb:$s,ya:pe,V:F,N:V,db:Y,ma:ht,fb:Ct,zb:kt,hb:vr,qb:Yr,ab:Tr,Aa:ws,yb:Ot,Ja:Gt,S:Zr,Wa:ys,$:Ba,H:Ra,E:ja,l:Jr,F:Gi,B:Wa,X:Ki,J:Ga,v:Hi,O:Ju,D:Ka,t:qi,A:Ha,z:Gn,w:qa,r:Qa,tb:Xa,ub:Ja,vb:Kn,rb:Hn,sb:Yi,bb:Zi,Oa:Yu,La:Zu,y:Za,ja:el,Ba:tl,Ka:Ya,qa:rl,Ia:sl,ib:Xn,U:Us,fa:nl,Sa:il,gb:ol,Qa:to,Pa:al,Ab:so,Ca:Yn,ob:je,aa:no,oa:io,xb:Zn,na:oo,$a:Cl,ia:aa,sa:zl,ga:ra,da:Il,ua:Ti,p:xl,e:pl,c:ul,ea:na,f:hl,n:fl,k:ea,Y:_l,ka:vl,j:El,wa:$l,Ra:da,ca:oa,Ua:Rl,P:kl,K:Zo,_:ia,Q:Pl,Z:Dl,x:gl,m:cl,va:Fl,i:Jo,h:ml,ra:Bl,ta:la,o:Yo,q:wl,s:Ml,I:bl,C:ta,L:Tl,xa:Sl,_a:sa,G:Ol,Ya:vi,ba:Ll,M:yl,Xa:Al,ha:ao,a:M,Na:Re}}}var Ne={1320978:()=>typeof wasmOffsetConverter<"u",1321035:(d,f,T,C,I)=>{if(n===void 0||!n.Bd)return 1;if((d=zt(Number(d>>>0))).startsWith("./")&&(d=d.substring(2)),!(d=n.Bd.get(d)))return 2;if(f=Number(f>>>0),T=Number(T>>>0),C=Number(C>>>0),f+T>d.byteLength)return 3;try{let W=d.subarray(f,f+T);switch(I){case 0:O().set(W,C>>>0);break;case 1:n.$d(C,W);break;default:return 4}return 0}catch{return 4}},1321750:(d,f,T)=>{n.Jd(d,O().subarray(f>>>0,f+T>>>0))},1321813:()=>n.Yd(),1321854:d=>{n.Id(d)},1321890:()=>{n.Sd()},1321921:()=>{n.Td()},1321950:()=>{n.Xd()},1321975:d=>n.Rd(d),1322008:d=>n.Vd(d),1322040:(d,f,T)=>{n.Hd(Number(d),Number(f),Number(T),!0)},1322103:(d,f,T)=>{n.Hd(Number(d),Number(f),Number(T))},1322160:d=>{n.hc("Abs",d,void 0)},1322211:d=>{n.hc("Neg",d,void 0)},1322262:d=>{n.hc("Floor",d,void 0)},1322315:d=>{n.hc("Ceil",d,void 0)},1322367:d=>{n.hc("Reciprocal",d,void 0)},1322425:d=>{n.hc("Sqrt",d,void 0)},1322477:d=>{n.hc("Exp",d,void 0)},1322528:d=>{n.hc("Erf",d,void 0)},1322579:d=>{n.hc("Sigmoid",d,void 0)},1322634:(d,f,T)=>{n.hc("HardSigmoid",d,{alpha:f,beta:T})},1322713:d=>{n.hc("Log",d,void 0)},1322764:d=>{n.hc("Sin",d,void 0)},1322815:d=>{n.hc("Cos",d,void 0)},1322866:d=>{n.hc("Tan",d,void 0)},1322917:d=>{n.hc("Asin",d,void 0)},1322969:d=>{n.hc("Acos",d,void 0)},1323021:d=>{n.hc("Atan",d,void 0)},1323073:d=>{n.hc("Sinh",d,void 0)},1323125:d=>{n.hc("Cosh",d,void 0)},1323177:d=>{n.hc("Asinh",d,void 0)},1323230:d=>{n.hc("Acosh",d,void 0)},1323283:d=>{n.hc("Atanh",d,void 0)},1323336:d=>{n.hc("Tanh",d,void 0)},1323388:d=>{n.hc("Not",d,void 0)},1323439:(d,f,T)=>{n.hc("Clip",d,{min:f,max:T})},1323508:d=>{n.hc("Clip",d,void 0)},1323560:(d,f)=>{n.hc("Elu",d,{alpha:f})},1323618:d=>{n.hc("Gelu",d,void 0)},1323670:d=>{n.hc("Relu",d,void 0)},1323722:(d,f)=>{n.hc("LeakyRelu",d,{alpha:f})},1323786:(d,f)=>{n.hc("ThresholdedRelu",d,{alpha:f})},1323856:(d,f)=>{n.hc("Cast",d,{to:f})},1323914:d=>{n.hc("Add",d,void 0)},1323965:d=>{n.hc("Sub",d,void 0)},1324016:d=>{n.hc("Mul",d,void 0)},1324067:d=>{n.hc("Div",d,void 0)},1324118:d=>{n.hc("Pow",d,void 0)},1324169:d=>{n.hc("Equal",d,void 0)},1324222:d=>{n.hc("Greater",d,void 0)},1324277:d=>{n.hc("GreaterOrEqual",d,void 0)},1324339:d=>{n.hc("Less",d,void 0)},1324391:d=>{n.hc("LessOrEqual",d,void 0)},1324450:(d,f,T,C,I)=>{n.hc("ReduceMean",d,{keepDims:!!f,noopWithEmptyAxes:!!T,axes:C?Array.from(X().subarray(Number(C)>>>0,Number(I)>>>0)):[]})},1324625:(d,f,T,C,I)=>{n.hc("ReduceMax",d,{keepDims:!!f,noopWithEmptyAxes:!!T,axes:C?Array.from(X().subarray(Number(C)>>>0,Number(I)>>>0)):[]})},1324799:(d,f,T,C,I)=>{n.hc("ReduceMin",d,{keepDims:!!f,noopWithEmptyAxes:!!T,axes:C?Array.from(X().subarray(Number(C)>>>0,Number(I)>>>0)):[]})},1324973:(d,f,T,C,I)=>{n.hc("ReduceProd",d,{keepDims:!!f,noopWithEmptyAxes:!!T,axes:C?Array.from(X().subarray(Number(C)>>>0,Number(I)>>>0)):[]})},1325148:(d,f,T,C,I)=>{n.hc("ReduceSum",d,{keepDims:!!f,noopWithEmptyAxes:!!T,axes:C?Array.from(X().subarray(Number(C)>>>0,Number(I)>>>0)):[]})},1325322:(d,f,T,C,I)=>{n.hc("ReduceL1",d,{keepDims:!!f,noopWithEmptyAxes:!!T,axes:C?Array.from(X().subarray(Number(C)>>>0,Number(I)>>>0)):[]})},1325495:(d,f,T,C,I)=>{n.hc("ReduceL2",d,{keepDims:!!f,noopWithEmptyAxes:!!T,axes:C?Array.from(X().subarray(Number(C)>>>0,Number(I)>>>0)):[]})},1325668:(d,f,T,C,I)=>{n.hc("ReduceLogSum",d,{keepDims:!!f,noopWithEmptyAxes:!!T,axes:C?Array.from(X().subarray(Number(C)>>>0,Number(I)>>>0)):[]})},1325845:(d,f,T,C,I)=>{n.hc("ReduceSumSquare",d,{keepDims:!!f,noopWithEmptyAxes:!!T,axes:C?Array.from(X().subarray(Number(C)>>>0,Number(I)>>>0)):[]})},1326025:(d,f,T,C,I)=>{n.hc("ReduceLogSumExp",d,{keepDims:!!f,noopWithEmptyAxes:!!T,axes:C?Array.from(X().subarray(Number(C)>>>0,Number(I)>>>0)):[]})},1326205:d=>{n.hc("Where",d,void 0)},1326258:(d,f,T)=>{n.hc("Transpose",d,{perm:f?Array.from(X().subarray(Number(f)>>>0,Number(T)>>>0)):[]})},1326382:(d,f,T,C)=>{n.hc("DepthToSpace",d,{blocksize:f,mode:zt(T),format:C?"NHWC":"NCHW"})},1326515:(d,f,T,C)=>{n.hc("DepthToSpace",d,{blocksize:f,mode:zt(T),format:C?"NHWC":"NCHW"})},1326648:(d,f,T,C,I,W,ne,ye,Ee,ze,Ye,ot,_t,Bt,Fr)=>{n.hc("ConvTranspose",d,{format:Ee?"NHWC":"NCHW",autoPad:f,dilations:[T],group:C,kernelShape:[I],pads:[W,ne],strides:[ye],wIsConst:()=>!!N()[ze>>>0],outputPadding:Ye?Array.from(X().subarray(Number(Ye)>>>0,Number(ot)>>>0)):[],outputShape:_t?Array.from(X().subarray(Number(_t)>>>0,Number(Bt)>>>0)):[],activation:zt(Fr)})},1327081:(d,f,T,C,I,W,ne,ye,Ee,ze,Ye,ot,_t,Bt)=>{n.hc("ConvTranspose",d,{format:ye?"NHWC":"NCHW",autoPad:f,dilations:Array.from(X().subarray(Number(T)>>>0,2+(Number(T)>>>0)>>>0)),group:C,kernelShape:Array.from(X().subarray(Number(I)>>>0,2+(Number(I)>>>0)>>>0)),pads:Array.from(X().subarray(Number(W)>>>0,4+(Number(W)>>>0)>>>0)),strides:Array.from(X().subarray(Number(ne)>>>0,2+(Number(ne)>>>0)>>>0)),wIsConst:()=>!!N()[Ee>>>0],outputPadding:ze?Array.from(X().subarray(Number(ze)>>>0,Number(Ye)>>>0)):[],outputShape:ot?Array.from(X().subarray(Number(ot)>>>0,Number(_t)>>>0)):[],activation:zt(Bt)})},1327742:(d,f,T,C,I,W,ne,ye,Ee,ze,Ye,ot,_t,Bt,Fr)=>{n.hc("ConvTranspose",d,{format:Ee?"NHWC":"NCHW",autoPad:f,dilations:[T],group:C,kernelShape:[I],pads:[W,ne],strides:[ye],wIsConst:()=>!!N()[ze>>>0],outputPadding:Ye?Array.from(X().subarray(Number(Ye)>>>0,Number(ot)>>>0)):[],outputShape:_t?Array.from(X().subarray(Number(_t)>>>0,Number(Bt)>>>0)):[],activation:zt(Fr)})},1328175:(d,f,T,C,I,W,ne,ye,Ee,ze,Ye,ot,_t,Bt)=>{n.hc("ConvTranspose",d,{format:ye?"NHWC":"NCHW",autoPad:f,dilations:Array.from(X().subarray(Number(T)>>>0,2+(Number(T)>>>0)>>>0)),group:C,kernelShape:Array.from(X().subarray(Number(I)>>>0,2+(Number(I)>>>0)>>>0)),pads:Array.from(X().subarray(Number(W)>>>0,4+(Number(W)>>>0)>>>0)),strides:Array.from(X().subarray(Number(ne)>>>0,2+(Number(ne)>>>0)>>>0)),wIsConst:()=>!!N()[Ee>>>0],outputPadding:ze?Array.from(X().subarray(Number(ze)>>>0,Number(Ye)>>>0)):[],outputShape:ot?Array.from(X().subarray(Number(ot)>>>0,Number(_t)>>>0)):[],activation:zt(Bt)})},1328836:(d,f)=>{n.hc("GlobalAveragePool",d,{format:f?"NHWC":"NCHW"})},1328927:(d,f,T,C,I,W,ne,ye,Ee,ze,Ye,ot,_t,Bt)=>{n.hc("AveragePool",d,{format:Bt?"NHWC":"NCHW",auto_pad:f,ceil_mode:T,count_include_pad:C,storage_order:I,dilations:W?Array.from(X().subarray(Number(W)>>>0,Number(ne)>>>0)):[],kernel_shape:ye?Array.from(X().subarray(Number(ye)>>>0,Number(Ee)>>>0)):[],pads:ze?Array.from(X().subarray(Number(ze)>>>0,Number(Ye)>>>0)):[],strides:ot?Array.from(X().subarray(Number(ot)>>>0,Number(_t)>>>0)):[]})},1329406:(d,f)=>{n.hc("GlobalAveragePool",d,{format:f?"NHWC":"NCHW"})},1329497:(d,f,T,C,I,W,ne,ye,Ee,ze,Ye,ot,_t,Bt)=>{n.hc("AveragePool",d,{format:Bt?"NHWC":"NCHW",auto_pad:f,ceil_mode:T,count_include_pad:C,storage_order:I,dilations:W?Array.from(X().subarray(Number(W)>>>0,Number(ne)>>>0)):[],kernel_shape:ye?Array.from(X().subarray(Number(ye)>>>0,Number(Ee)>>>0)):[],pads:ze?Array.from(X().subarray(Number(ze)>>>0,Number(Ye)>>>0)):[],strides:ot?Array.from(X().subarray(Number(ot)>>>0,Number(_t)>>>0)):[]})},1329976:(d,f)=>{n.hc("GlobalMaxPool",d,{format:f?"NHWC":"NCHW"})},1330063:(d,f,T,C,I,W,ne,ye,Ee,ze,Ye,ot,_t,Bt)=>{n.hc("MaxPool",d,{format:Bt?"NHWC":"NCHW",auto_pad:f,ceil_mode:T,count_include_pad:C,storage_order:I,dilations:W?Array.from(X().subarray(Number(W)>>>0,Number(ne)>>>0)):[],kernel_shape:ye?Array.from(X().subarray(Number(ye)>>>0,Number(Ee)>>>0)):[],pads:ze?Array.from(X().subarray(Number(ze)>>>0,Number(Ye)>>>0)):[],strides:ot?Array.from(X().subarray(Number(ot)>>>0,Number(_t)>>>0)):[]})},1330538:(d,f)=>{n.hc("GlobalMaxPool",d,{format:f?"NHWC":"NCHW"})},1330625:(d,f,T,C,I,W,ne,ye,Ee,ze,Ye,ot,_t,Bt)=>{n.hc("MaxPool",d,{format:Bt?"NHWC":"NCHW",auto_pad:f,ceil_mode:T,count_include_pad:C,storage_order:I,dilations:W?Array.from(X().subarray(Number(W)>>>0,Number(ne)>>>0)):[],kernel_shape:ye?Array.from(X().subarray(Number(ye)>>>0,Number(Ee)>>>0)):[],pads:ze?Array.from(X().subarray(Number(ze)>>>0,Number(Ye)>>>0)):[],strides:ot?Array.from(X().subarray(Number(ot)>>>0,Number(_t)>>>0)):[]})},1331100:(d,f,T,C,I)=>{n.hc("Gemm",d,{alpha:f,beta:T,transA:C,transB:I})},1331204:d=>{n.hc("MatMul",d,void 0)},1331258:(d,f,T,C)=>{n.hc("ArgMax",d,{keepDims:!!f,selectLastIndex:!!T,axis:C})},1331366:(d,f,T,C)=>{n.hc("ArgMin",d,{keepDims:!!f,selectLastIndex:!!T,axis:C})},1331474:(d,f)=>{n.hc("Softmax",d,{axis:f})},1331537:(d,f)=>{n.hc("Concat",d,{axis:f})},1331597:(d,f,T,C,I)=>{n.hc("Split",d,{axis:f,numOutputs:T,splitSizes:C?Array.from(X().subarray(Number(C)>>>0,Number(I)>>>0)):[]})},1331753:d=>{n.hc("Expand",d,void 0)},1331807:(d,f)=>{n.hc("Gather",d,{axis:Number(f)})},1331878:(d,f)=>{n.hc("GatherElements",d,{axis:Number(f)})},1331957:(d,f)=>{n.hc("GatherND",d,{batch_dims:Number(f)})},1332036:(d,f,T,C,I,W,ne,ye,Ee,ze,Ye)=>{n.hc("Resize",d,{antialias:f,axes:T?Array.from(X().subarray(Number(T)>>>0,Number(C)>>>0)):[],coordinateTransformMode:zt(I),cubicCoeffA:W,excludeOutside:ne,extrapolationValue:ye,keepAspectRatioPolicy:zt(Ee),mode:zt(ze),nearestMode:zt(Ye)})},1332398:(d,f,T,C,I,W,ne)=>{n.hc("Slice",d,{starts:f?Array.from(X().subarray(Number(f)>>>0,Number(T)>>>0)):[],ends:C?Array.from(X().subarray(Number(C)>>>0,Number(I)>>>0)):[],axes:W?Array.from(X().subarray(Number(W)>>>0,Number(ne)>>>0)):[]})},1332662:d=>{n.hc("Tile",d,void 0)},1332714:(d,f,T)=>{n.hc("InstanceNormalization",d,{epsilon:f,format:T?"NHWC":"NCHW"})},1332828:(d,f,T)=>{n.hc("InstanceNormalization",d,{epsilon:f,format:T?"NHWC":"NCHW"})},1332942:d=>{n.hc("Range",d,void 0)},1332995:(d,f)=>{n.hc("Einsum",d,{equation:zt(f)})},1333076:(d,f,T,C,I)=>{n.hc("Pad",d,{mode:f,value:T,pads:C?Array.from(X().subarray(Number(C)>>>0,Number(I)>>>0)):[]})},1333219:(d,f,T,C,I,W)=>{n.hc("BatchNormalization",d,{epsilon:f,momentum:T,spatial:!!I,trainingMode:!!C,format:W?"NHWC":"NCHW"})},1333388:(d,f,T,C,I,W)=>{n.hc("BatchNormalization",d,{epsilon:f,momentum:T,spatial:!!I,trainingMode:!!C,format:W?"NHWC":"NCHW"})},1333557:(d,f,T)=>{n.hc("CumSum",d,{exclusive:Number(f),reverse:Number(T)})},1333654:(d,f,T)=>{n.hc("DequantizeLinear",d,{axis:f,blockSize:T})},1333744:(d,f,T,C,I)=>{n.hc("GridSample",d,{align_corners:f,mode:zt(T),padding_mode:zt(C),format:I?"NHWC":"NCHW"})},1333914:(d,f,T,C,I)=>{n.hc("GridSample",d,{align_corners:f,mode:zt(T),padding_mode:zt(C),format:I?"NHWC":"NCHW"})},1334084:(d,f)=>{n.hc("ScatterND",d,{reduction:zt(f)})},1334169:(d,f,T,C,I,W,ne,ye,Ee)=>{n.hc("Attention",d,{numHeads:f,isUnidirectional:T,maskFilterValue:C,scale:I,doRotary:W,qkvHiddenSizes:ne?Array.from(X().subarray(Number(ye)>>>0,Number(ye)+ne>>>0)):[],pastPresentShareBuffer:!!Ee})},1334441:d=>{n.hc("BiasAdd",d,void 0)},1334496:d=>{n.hc("BiasSplitGelu",d,void 0)},1334557:d=>{n.hc("FastGelu",d,void 0)},1334613:(d,f,T,C,I,W,ne,ye,Ee,ze,Ye,ot,_t,Bt,Fr,ks)=>{n.hc("Conv",d,{format:ot?"NHWC":"NCHW",auto_pad:f,dilations:T?Array.from(X().subarray(Number(T)>>>0,Number(C)>>>0)):[],group:I,kernel_shape:W?Array.from(X().subarray(Number(W)>>>0,Number(ne)>>>0)):[],pads:ye?Array.from(X().subarray(Number(ye)>>>0,Number(Ee)>>>0)):[],strides:ze?Array.from(X().subarray(Number(ze)>>>0,Number(Ye)>>>0)):[],w_is_const:()=>!!N()[Number(_t)>>>0],activation:zt(Bt),activation_params:Fr?Array.from(_e().subarray(Number(Fr)>>>0,Number(ks)>>>0)):[]})},1335197:d=>{n.hc("Gelu",d,void 0)},1335249:(d,f,T,C,I,W,ne,ye,Ee)=>{n.hc("GroupQueryAttention",d,{numHeads:f,kvNumHeads:T,scale:C,softcap:I,doRotary:W,rotaryInterleaved:ne,smoothSoftmax:ye,localWindowSize:Ee})},1335466:(d,f,T,C)=>{n.hc("LayerNormalization",d,{axis:f,epsilon:T,simplified:!!C})},1335577:(d,f,T,C)=>{n.hc("LayerNormalization",d,{axis:f,epsilon:T,simplified:!!C})},1335688:(d,f,T,C,I,W)=>{n.hc("MatMulNBits",d,{k:f,n:T,accuracyLevel:C,bits:I,blockSize:W})},1335815:(d,f,T,C,I,W)=>{n.hc("MultiHeadAttention",d,{numHeads:f,isUnidirectional:T,maskFilterValue:C,scale:I,doRotary:W})},1335974:(d,f)=>{n.hc("QuickGelu",d,{alpha:f})},1336038:(d,f,T,C,I)=>{n.hc("RotaryEmbedding",d,{interleaved:!!f,numHeads:T,rotaryEmbeddingDim:C,scale:I})},1336177:(d,f,T)=>{n.hc("SkipLayerNormalization",d,{epsilon:f,simplified:!!T})},1336279:(d,f,T)=>{n.hc("SkipLayerNormalization",d,{epsilon:f,simplified:!!T})},1336381:(d,f,T,C)=>{n.hc("GatherBlockQuantized",d,{gatherAxis:f,quantizeAxis:T,blockSize:C})},1336502:d=>{n.Wd(d)},1336536:(d,f)=>n.Zd(Number(d),Number(f),n.Cd.be,n.Cd.errors)};function We(d,f,T){return Ui(async()=>{await n.Ud(Number(d),Number(f),Number(T))})}function D(){return typeof wasmOffsetConverter<"u"}class ee{constructor(f){re(this,"name","ExitStatus");this.message=`Program terminated with exit(${f})`,this.status=f}}var B=d=>{d.terminate(),d.onmessage=()=>{}},te=[],de=d=>{qe.length==0&&(us(),dr(qe[0]));var f=qe.pop();if(!f)return 6;Xe.push(f),wt[d.xd]=f,f.xd=d.xd;var T={yd:"run",de:d.ce,Fd:d.Fd,xd:d.xd};return f.postMessage(T,d.Ld),0},be=0,ve=(d,f,...T)=>{for(var C=2*T.length,I=mt(),W=Fn(8*C),ne=W>>>3,ye=0;ye>>0]=Ee)}return d=ri(d,0,C,W,f),ft(I),d};function Re(d){if(u)return ve(0,1,d);if(x=d,!(0{if(x=d,u)throw Fe(d),"unwind";Re(d)},qe=[],Xe=[],ct=[],wt={},nr=d=>{var f=d.xd;delete wt[f],qe.push(d),Xe.splice(Xe.indexOf(d),1),d.xd=0,po(f)};function jt(){ct.forEach(d=>d())}var dr=d=>new Promise(f=>{d.onmessage=I=>{var W=(I=I.data).yd;if(I.Ed&&I.Ed!=An()){var ne=wt[I.Ed];ne?ne.postMessage(I,I.Ld):P(`Internal error! Worker sent a message "${W}" to target pthread ${I.Ed}, but that thread no longer exists!`)}else W==="checkMailbox"?Vt():W==="spawnThread"?de(I):W==="cleanupThread"?nr(wt[I.ee]):W==="loaded"?(d.loaded=!0,f(d)):W==="alert"?alert(`Thread ${I.fe}: ${I.text}`):I.target==="setimmediate"?d.postMessage(I):W==="callHandler"?n[I.Nd](...I.args):W&&P(`worker sent an unknown command ${W}`)},d.onerror=I=>{throw P(`worker sent an error! ${I.filename}:${I.lineno}: ${I.message}`),I};var T,C=[];for(T of[])n.propertyIsEnumerable(T)&&C.push(T);d.postMessage({yd:"load",Od:C,he:M,ie:w})});function us(){var d=new Worker((()=>{let f=URL;return self.location.href>"file:"&&self.location.href<"file;"?new f("ort.bundle.min.mjs",self.location.href):new URL(self.location.href)})(),{type:"module",workerData:"em-pthread",name:"em-pthread"});qe.push(d)}var Ds=d=>{K();var f=we()[d+52>>>2>>>0];d=we()[d+56>>>2>>>0],fo(f,f-d),ft(f)},Dr=(d,f)=>{be=0,d=ai(d,f),0>>=0);if(N()[f.wd+12>>>0]==0){var T=1;N()[f.wd+12>>>0]=T}return T=0,N()[f.wd+13>>>0]=T,cs.push(f),ii(d),go(d)}var jr=0,dt=()=>{gt(0,0);var d=cs.pop();mo(d.Gd),jr=0};class qr{constructor(f){this.Gd=f,this.wd=f-24}}function Vr(d){throw jr||(jr=d>>>0),jr}var ps=d=>{var f=jr;if(!f)return Ws(0),0;var T=new qr(f);we()[T.wd+16>>>2>>>0]=f;var C=we()[T.wd+4>>>2>>>0];if(!C)return Ws(0),f;for(var I of d){if(I===0||I===C)break;if(_o(I,C,T.wd+16))return Ws(I),f}return Ws(C),f};function xs(){return ps([])}function Es(d){return ps([d>>>0])}function Ps(d,f){return ps([d>>>0,f>>>0])}var zs=()=>{var d=cs.pop();d||Ie("no exception to throw");var f=d.Gd;if(N()[d.wd+13>>>0]==0){cs.push(d);var T=1;N()[d.wd+13>>>0]=T,T=0,N()[d.wd+12>>>0]=T}throw jr=f};function fr(d,f,T){var C=new qr(d>>>=0);throw f>>>=0,T>>>=0,we()[C.wd+16>>>2>>>0]=0,we()[C.wd+4>>>2>>>0]=f,we()[C.wd+8>>>2>>>0]=T,jr=d}function Be(d,f,T,C){return u?ve(2,1,d,f,T,C):et(d,f,T,C)}function et(d,f,T,C){if(d>>>=0,T>>>=0,C>>>=0,p===void 0)return 6;var I=[];return u&&I.length===0?Be(d,f>>>=0,T,C):(d={ce:T,xd:d,Fd:C,Ld:I},u?(d.yd="spawnThread",postMessage(d,I),0):de(d))}var it=typeof TextDecoder<"u"?new TextDecoder:void 0,rr=(d,f=0,T=NaN)=>{var C=(f>>>=0)+T;for(T=f;d[T]&&!(T>=C);)++T;if(16(I=(240&I)==224?(15&I)<<12|W<<6|ne:(7&I)<<18|W<<12|ne<<6|63&d[f++])?C+=String.fromCharCode(I):(I-=65536,C+=String.fromCharCode(55296|I>>10,56320|1023&I))}}else C+=String.fromCharCode(I)}return C},zt=(d,f)=>(d>>>=0)?rr(O(),d,f):"";function kr(d,f,T){return u?ve(3,1,d,f,T):0}function hs(d,f){if(u)return ve(4,1,d,f)}var fs=d=>{for(var f=0,T=0;T=C?f++:2047>=C?f+=2:55296<=C&&57343>=C?(f+=4,++T):f+=3}return f},Er=(d,f,T)=>{var C=O();if(f>>>=0,0=ne&&(ne=65536+((1023&ne)<<10)|1023&d.charCodeAt(++W)),127>=ne){if(f>=T)break;C[f++>>>0]=ne}else{if(2047>=ne){if(f+1>=T)break;C[f++>>>0]=192|ne>>6}else{if(65535>=ne){if(f+2>=T)break;C[f++>>>0]=224|ne>>12}else{if(f+3>=T)break;C[f++>>>0]=240|ne>>18,C[f++>>>0]=128|ne>>12&63}C[f++>>>0]=128|ne>>6&63}C[f++>>>0]=128|63&ne}}C[f>>>0]=0,d=f-I}else d=0;return d};function ms(d,f){if(u)return ve(5,1,d,f)}function _s(d,f,T){if(u)return ve(6,1,d,f,T)}function Qr(d,f,T){return u?ve(7,1,d,f,T):0}function Cs(d,f){if(u)return ve(8,1,d,f)}function Xs(d,f,T){if(u)return ve(9,1,d,f,T)}function Js(d,f,T,C){if(u)return ve(10,1,d,f,T,C)}function Ys(d,f,T,C){if(u)return ve(11,1,d,f,T,C)}function Zs(d,f,T,C){if(u)return ve(12,1,d,f,T,C)}function gs(d){if(u)return ve(13,1,d)}function en(d,f){if(u)return ve(14,1,d,f)}function tn(d,f,T){if(u)return ve(15,1,d,f,T)}var rn,Lr,Ss=()=>Ie(""),br=d=>{for(var f="";O()[d>>>0];)f+=rn[O()[d++>>>0]];return f},Bs={},Rs={};function Ir(d,f,T={}){return function(C,I,W={}){var ne=I.name;if(!C)throw new Lr(`type "${ne}" must have a positive integer typeid pointer`);if(Rs.hasOwnProperty(C)){if(W.Pd)return;throw new Lr(`Cannot register type '${ne}' twice`)}Rs[C]=I,Bs.hasOwnProperty(C)&&(I=Bs[C],delete Bs[C],I.forEach(ye=>ye()))}(d,f,T)}var Xr=(d,f,T)=>{switch(f){case 1:return T?C=>N()[C>>>0]:C=>O()[C>>>0];case 2:return T?C=>G()[C>>>1>>>0]:C=>se()[C>>>1>>>0];case 4:return T?C=>X()[C>>>2>>>0]:C=>we()[C>>>2>>>0];case 8:return T?C=>H[C>>>3]:C=>J[C>>>3];default:throw new TypeError(`invalid integer width (${f}): ${d}`)}};function En(d,f,T){T>>>=0,Ir(d>>>=0,{name:f=br(f>>>0),fromWireType:C=>C,toWireType:function(C,I){if(typeof I!="bigint"&&typeof I!="number")throw I=I===null?"null":(C=typeof I)=="object"||C==="array"||C==="function"?I.toString():""+I,new TypeError(`Cannot convert "${I}" to ${this.name}`);return typeof I=="number"&&(I=BigInt(I)),I},zd:zr,readValueFromPointer:Xr(f,T,f.indexOf("u")==-1),Ad:null})}var zr=8;function Pn(d,f,T,C){Ir(d>>>=0,{name:f=br(f>>>0),fromWireType:function(I){return!!I},toWireType:function(I,W){return W?T:C},zd:zr,readValueFromPointer:function(I){return this.fromWireType(O()[I>>>0])},Ad:null})}var Ns=[],Ar=[];function Jr(d){9<(d>>>=0)&&--Ar[d+1]==0&&(Ar[d]=void 0,Ns.push(d))}var ur=d=>{if(!d)throw new Lr("Cannot use deleted val. handle = "+d);return Ar[d]},mr=d=>{switch(d){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let f=Ns.pop()||Ar.length;return Ar[f]=d,Ar[f+1]=1,f}};function js(d){return this.fromWireType(we()[d>>>2>>>0])}var Cn={name:"emscripten::val",fromWireType:d=>{var f=ur(d);return Jr(d),f},toWireType:(d,f)=>mr(f),zd:zr,readValueFromPointer:js,Ad:null};function $s(d){return Ir(d>>>0,Cn)}var Sn=(d,f)=>{switch(f){case 4:return function(T){return this.fromWireType(_e()[T>>>2>>>0])};case 8:return function(T){return this.fromWireType(ke()[T>>>3>>>0])};default:throw new TypeError(`invalid float width (${f}): ${d}`)}};function pe(d,f,T){T>>>=0,Ir(d>>>=0,{name:f=br(f>>>0),fromWireType:C=>C,toWireType:(C,I)=>I,zd:zr,readValueFromPointer:Sn(f,T),Ad:null})}function F(d,f,T,C,I){if(d>>>=0,T>>>=0,f=br(f>>>0),I===-1&&(I=4294967295),I=ye=>ye,C===0){var W=32-8*T;I=ye=>ye<>>W}var ne=f.includes("unsigned")?function(ye,Ee){return Ee>>>0}:function(ye,Ee){return Ee};Ir(d,{name:f,fromWireType:I,toWireType:ne,zd:zr,readValueFromPointer:Xr(f,T,C!==0),Ad:null})}function V(d,f,T){function C(W){var ne=we()[W>>>2>>>0];return W=we()[W+4>>>2>>>0],new I(N().buffer,W,ne)}var I=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][f];Ir(d>>>=0,{name:T=br(T>>>0),fromWireType:C,zd:zr,readValueFromPointer:C},{Pd:!0})}function Y(d,f){Ir(d>>>=0,{name:f=br(f>>>0),fromWireType:function(T){for(var C,I=we()[T>>>2>>>0],W=T+4,ne=W,ye=0;ye<=I;++ye){var Ee=W+ye;ye!=I&&O()[Ee>>>0]!=0||(ne=zt(ne,Ee-ne),C===void 0?C=ne:(C+="\0",C+=ne),ne=Ee+1)}return Ur(T),C},toWireType:function(T,C){C instanceof ArrayBuffer&&(C=new Uint8Array(C));var I=typeof C=="string";if(!(I||C instanceof Uint8Array||C instanceof Uint8ClampedArray||C instanceof Int8Array))throw new Lr("Cannot pass non-string to std::string");var W=I?fs(C):C.length,ne=ln(4+W+1),ye=ne+4;if(we()[ne>>>2>>>0]=W,I)Er(C,ye,W+1);else if(I)for(I=0;I>>0]=Ee}else for(I=0;I>>0]=C[I];return T!==null&&T.push(Ur,ne),ne},zd:zr,readValueFromPointer:js,Ad(T){Ur(T)}})}var le=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,ce=(d,f)=>{for(var T=d>>1,C=T+f/2;!(T>=C)&&se()[T>>>0];)++T;if(32<(T<<=1)-d&&le)return le.decode(O().slice(d,T));for(T="",C=0;!(C>=f/2);++C){var I=G()[d+2*C>>>1>>>0];if(I==0)break;T+=String.fromCharCode(I)}return T},Ce=(d,f,T)=>{if(T??(T=2147483647),2>T)return 0;var C=f;T=(T-=2)<2*d.length?T/2:d.length;for(var I=0;I>>1>>>0]=W,f+=2}return G()[f>>>1>>>0]=0,f-C},Ue=d=>2*d.length,Qe=(d,f)=>{for(var T=0,C="";!(T>=f/4);){var I=X()[d+4*T>>>2>>>0];if(I==0)break;++T,65536<=I?(I-=65536,C+=String.fromCharCode(55296|I>>10,56320|1023&I)):C+=String.fromCharCode(I)}return C},Ke=(d,f,T)=>{if(f>>>=0,T??(T=2147483647),4>T)return 0;var C=f;T=C+T-4;for(var I=0;I=W&&(W=65536+((1023&W)<<10)|1023&d.charCodeAt(++I)),X()[f>>>2>>>0]=W,(f+=4)+4>T)break}return X()[f>>>2>>>0]=0,f-C},Ze=d=>{for(var f=0,T=0;T=C&&++T,f+=4}return f};function ht(d,f,T){if(d>>>=0,f>>>=0,T=br(T>>>=0),f===2)var C=ce,I=Ce,W=Ue,ne=ye=>se()[ye>>>1>>>0];else f===4&&(C=Qe,I=Ke,W=Ze,ne=ye=>we()[ye>>>2>>>0]);Ir(d,{name:T,fromWireType:ye=>{for(var Ee,ze=we()[ye>>>2>>>0],Ye=ye+4,ot=0;ot<=ze;++ot){var _t=ye+4+ot*f;ot!=ze&&ne(_t)!=0||(Ye=C(Ye,_t-Ye),Ee===void 0?Ee=Ye:(Ee+="\0",Ee+=Ye),Ye=_t+f)}return Ur(ye),Ee},toWireType:(ye,Ee)=>{if(typeof Ee!="string")throw new Lr(`Cannot pass non-string to C++ string type ${T}`);var ze=W(Ee),Ye=ln(4+ze+f);return we()[Ye>>>2>>>0]=ze/f,I(Ee,Ye+4,ze+f),ye!==null&&ye.push(Ur,Ye),Ye},zd:zr,readValueFromPointer:js,Ad(ye){Ur(ye)}})}function Ct(d,f){Ir(d>>>=0,{Qd:!0,name:f=br(f>>>0),zd:0,fromWireType:()=>{},toWireType:()=>{}})}function kt(d){ti(d>>>0,!l,1,!a,131072,!1),jt()}var Wt=d=>{if(!ue)try{if(d(),!(0>>=0,typeof Atomics.ge=="function"&&(Atomics.ge(X(),d>>>2,d).value.then(Vt),d+=128,Atomics.store(X(),d>>>2,1))}var Vt=()=>{var d=An();d&&(Ot(d),Wt(ho))};function vr(d,f){(d>>>=0)==f>>>0?setTimeout(Vt):u?postMessage({Ed:d,yd:"checkMailbox"}):(d=wt[d])&&d.postMessage({yd:"checkMailbox"})}var _r=[];function Yr(d,f,T,C,I){for(f>>>=0,C/=2,_r.length=C,T=I>>>0>>>3,I=0;I>>0];return(f?Ne[f]:dl[d])(..._r)}var Tr=()=>{be=0};function ws(d){d>>>=0,u?postMessage({yd:"cleanupThread",ee:d}):nr(wt[d])}function Gt(d){}var Zt=(d,f)=>{var T=Rs[d];if(T===void 0)throw d=uo(d),T=br(d),Ur(d),new Lr(`${f} has unknown type ${T}`);return T},gr=(d,f,T)=>{var C=[];return d=d.toWireType(C,T),C.length&&(we()[f>>>2>>>0]=mr(C)),d};function Zr(d,f,T){return f>>>=0,T>>>=0,d=ur(d>>>0),f=Zt(f,"emval::as"),gr(f,T,d)}function ys(d,f){return f>>>=0,d=ur(d>>>0),(f=Zt(f,"emval::as")).toWireType(null,d)}var Ht=d=>{try{d()}catch(f){Ie(f)}},cr=0,Rt=null,Jt=0,qt=[],er={},ir={},sn=0,nn=null,za=[];function Ui(d){return function(f){if(!ue){if(cr===0){var T=!1,C=!1;f((I=0)=>{if(!ue&&(Jt=I,T=!0,C)){cr=2,Ht(()=>Qo(Rt)),typeof MainLoop<"u"&&MainLoop.Md&&MainLoop.resume(),I=!1;try{var W=function(){var Ee=X()[Rt+8>>>2>>>0];return Ee=Oe[ir[Ee]],--be,Ee()}()}catch(Ee){W=Ee,I=!0}var ne=!1;if(!Rt){var ye=nn;ye&&(nn=null,(I?ye.reject:ye.resolve)(W),ne=!0)}if(I&&!ne)throw W}}),C=!0,T||(cr=1,Rt=function(){var I=ln(65548),W=I+12;we()[I>>>2>>>0]=W,we()[I+4>>>2>>>0]=W+65536,W=qt[0];var ne=er[W];return ne===void 0&&(ne=sn++,er[W]=ne,ir[ne]=W),W=ne,X()[I+8>>>2>>>0]=W,I}(),typeof MainLoop<"u"&&MainLoop.Md&&MainLoop.pause(),Ht(()=>Ho(Rt)))}else cr===2?(cr=0,Ht(Xo),Ur(Rt),Rt=null,za.forEach(Wt)):Ie(`invalid state: ${cr}`);return Jt}}(f=>{d().then(f)})}function Ba(d){return d>>>=0,Ui(async()=>{var f=await ur(d);return mr(f)})}var Ms=[];function Ra(d,f,T,C){return T>>>=0,C>>>=0,(d=Ms[d>>>0])(null,f=ur(f>>>0),T,C)}var Na={},$n=d=>{var f=Na[d];return f===void 0?br(d):f};function ja(d,f,T,C,I){return T>>>=0,C>>>=0,I>>>=0,(d=Ms[d>>>0])(f=ur(f>>>0),f[T=$n(T)],C,I)}var Wi=()=>typeof globalThis=="object"?globalThis:Function("return this")();function Gi(d){return(d>>>=0)==0?mr(Wi()):(d=$n(d),mr(Wi()[d]))}var Va=d=>{var f=Ms.length;return Ms.push(d),f},Ua=(d,f)=>{for(var T=Array(d),C=0;C>>2>>>0],"parameter "+C);return T},Wn=(d,f)=>Object.defineProperty(f,"name",{value:d});function Wa(d,f,T){var C=(f=Ua(d,f>>>0)).shift();d--;var I=`return function (obj, func, destructorsRef, args) { +`,W=0,ne=[];T===0&&ne.push("obj");for(var ye=["retType"],Ee=[C],ze=0;zeYe.name).join(", ")}) => ${C.name}>`,Va(Wn(T,d))}function Ki(d){return d=$n(d>>>0),mr(n[d])}function Ga(d,f){return f>>>=0,d=ur(d>>>0),f=ur(f),mr(d[f])}function Hi(d){9<(d>>>=0)&&(Ar[d+1]+=1)}function Ju(){return mr([])}function Ka(d){d=ur(d>>>0);for(var f=Array(d.length),T=0;T>>0))}function Ha(){return mr({})}function Gn(d){for(var f=ur(d>>>=0);f.length;){var T=f.pop();f.pop()(T)}Jr(d)}function qa(d,f,T){f>>>=0,T>>>=0,d=ur(d>>>0),f=ur(f),T=ur(T),d[f]=T}function Qa(d,f){return f>>>=0,d=(d=Zt(d>>>0,"_emval_take_value")).readValueFromPointer(f),mr(d)}function Xa(d,f){d=-9007199254740992>d||9007199254740992>>=0,d=new Date(1e3*d),X()[f>>>2>>>0]=d.getUTCSeconds(),X()[f+4>>>2>>>0]=d.getUTCMinutes(),X()[f+8>>>2>>>0]=d.getUTCHours(),X()[f+12>>>2>>>0]=d.getUTCDate(),X()[f+16>>>2>>>0]=d.getUTCMonth(),X()[f+20>>>2>>>0]=d.getUTCFullYear()-1900,X()[f+24>>>2>>>0]=d.getUTCDay(),d=(d.getTime()-Date.UTC(d.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,X()[f+28>>>2>>>0]=d}var Qi=d=>d%4==0&&(d%100!=0||d%400==0),Xi=[0,31,60,91,121,152,182,213,244,274,305,335],Ji=[0,31,59,90,120,151,181,212,243,273,304,334];function Ja(d,f){d=-9007199254740992>d||9007199254740992>>=0,d=new Date(1e3*d),X()[f>>>2>>>0]=d.getSeconds(),X()[f+4>>>2>>>0]=d.getMinutes(),X()[f+8>>>2>>>0]=d.getHours(),X()[f+12>>>2>>>0]=d.getDate(),X()[f+16>>>2>>>0]=d.getMonth(),X()[f+20>>>2>>>0]=d.getFullYear()-1900,X()[f+24>>>2>>>0]=d.getDay();var T=(Qi(d.getFullYear())?Xi:Ji)[d.getMonth()]+d.getDate()-1|0;X()[f+28>>>2>>>0]=T,X()[f+36>>>2>>>0]=-60*d.getTimezoneOffset(),T=new Date(d.getFullYear(),6,1).getTimezoneOffset();var C=new Date(d.getFullYear(),0,1).getTimezoneOffset();d=0|(T!=C&&d.getTimezoneOffset()==Math.min(C,T)),X()[f+32>>>2>>>0]=d}function Kn(d){d>>>=0;var f=new Date(X()[d+20>>>2>>>0]+1900,X()[d+16>>>2>>>0],X()[d+12>>>2>>>0],X()[d+8>>>2>>>0],X()[d+4>>>2>>>0],X()[d>>>2>>>0],0),T=X()[d+32>>>2>>>0],C=f.getTimezoneOffset(),I=new Date(f.getFullYear(),6,1).getTimezoneOffset(),W=new Date(f.getFullYear(),0,1).getTimezoneOffset(),ne=Math.min(W,I);return 0>T?X()[d+32>>>2>>>0]=+(I!=W&&ne==C):0>>2>>>0]=f.getDay(),T=(Qi(f.getFullYear())?Xi:Ji)[f.getMonth()]+f.getDate()-1|0,X()[d+28>>>2>>>0]=T,X()[d>>>2>>>0]=f.getSeconds(),X()[d+4>>>2>>>0]=f.getMinutes(),X()[d+8>>>2>>>0]=f.getHours(),X()[d+12>>>2>>>0]=f.getDate(),X()[d+16>>>2>>>0]=f.getMonth(),X()[d+20>>>2>>>0]=f.getYear(),d=f.getTime(),BigInt(isNaN(d)?-1:d/1e3)}function Hn(d,f,T,C,I,W,ne){return u?ve(16,1,d,f,T,C,I,W,ne):-52}function Yi(d,f,T,C,I,W){if(u)return ve(17,1,d,f,T,C,I,W)}var Vs={},Us=()=>performance.timeOrigin+performance.now();function Zi(d,f){if(u)return ve(18,1,d,f);if(Vs[d]&&(clearTimeout(Vs[d].id),delete Vs[d]),!f)return 0;var T=setTimeout(()=>{delete Vs[d],Wt(()=>ni(d,performance.timeOrigin+performance.now()))},f);return Vs[d]={id:T,ke:f},0}function Yu(d,f,T,C){d>>>=0,f>>>=0,T>>>=0,C>>>=0;var I=new Date().getFullYear(),W=new Date(I,0,1).getTimezoneOffset();I=new Date(I,6,1).getTimezoneOffset();var ne=Math.max(W,I);we()[d>>>2>>>0]=60*ne,X()[f>>>2>>>0]=+(W!=I),d=(f=ye=>{var Ee=Math.abs(ye);return`UTC${0<=ye?"-":"+"}${String(Math.floor(Ee/60)).padStart(2,"0")}${String(Ee%60).padStart(2,"0")}`})(W),f=f(I),IDate.now();function Zu(d,f,T){return 0<=d&&3>=d?(d===0?d=Date.now():d=performance.timeOrigin+performance.now(),H[T>>>0>>>3]=BigInt(Math.round(1e6*d)),0):28}var qn=[],Qn=(d,f)=>{qn.length=0;for(var T;T=O()[d++>>>0];){var C=T!=105;f+=(C&=T!=112)&&f%8?4:0,qn.push(T==112?we()[f>>>2>>>0]:T==106?H[f>>>3]:T==105?X()[f>>>2>>>0]:ke()[f>>>3>>>0]),f+=C?8:4}return qn};function Za(d,f,T){return d>>>=0,f=Qn(f>>>0,T>>>0),Ne[d](...f)}function el(d,f,T){return d>>>=0,f=Qn(f>>>0,T>>>0),Ne[d](...f)}var tl=()=>{};function rl(d,f){return P(zt(d>>>0,f>>>0))}var sl=()=>{throw be+=1,"unwind"};function Xn(){return 4294901760}var nl=()=>navigator.hardwareConcurrency;function il(){return Ie("Cannot use emscripten_pc_get_function without -sUSE_OFFSET_CONVERTER"),0}function ol(d){d>>>=0;var f=O().length;if(d<=f||4294901760=T;T*=2){var C=f*(1+.2/T);C=Math.min(C,d+100663296);e:{C=(Math.min(4294901760,65536*Math.ceil(Math.max(d,C)/65536))-M.buffer.byteLength+65535)/65536|0;try{M.grow(C),K();var I=1;break e}catch{}I=void 0}if(I)return!0}return!1}var on=()=>(Ie("Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER"),0),an={},eo=d=>{d.forEach(f=>{on()})};function to(){var d=Error().stack.toString().split(` +`);return d[0]=="Error"&&d.shift(),eo(d),an.Kd=on(),an.ae=d,an.Kd}function al(d,f,T){if(d>>>=0,f>>>=0,an.Kd==d)var C=an.ae;else(C=Error().stack.toString().split(` +`))[0]=="Error"&&C.shift(),eo(C);for(var I=3;C[I]&&on()!=d;)++I;for(d=0;d>>2>>>0]=on();return d}var Jn,kn={},ro=()=>{if(!Jn){var d,f={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(d in kn)kn[d]===void 0?delete f[d]:f[d]=kn[d];var T=[];for(d in f)T.push(`${d}=${f[d]}`);Jn=T}return Jn};function so(d,f){if(u)return ve(19,1,d,f);d>>>=0,f>>>=0;var T=0;return ro().forEach((C,I)=>{var W=f+T;for(I=we()[d+4*I>>>2>>>0]=W,W=0;W>>0]=C.charCodeAt(W);N()[I>>>0]=0,T+=C.length+1}),0}function Yn(d,f){if(u)return ve(20,1,d,f);d>>>=0,f>>>=0;var T=ro();we()[d>>>2>>>0]=T.length;var C=0;return T.forEach(I=>C+=I.length+1),we()[f>>>2>>>0]=C,0}function no(d){return u?ve(21,1,d):52}function io(d,f,T,C){return u?ve(22,1,d,f,T,C):52}function Zn(d,f,T,C){return u?ve(23,1,d,f,T,C):70}var ll=[null,[],[]];function oo(d,f,T,C){if(u)return ve(24,1,d,f,T,C);f>>>=0,T>>>=0,C>>>=0;for(var I=0,W=0;W>>2>>>0],ye=we()[f+4>>>2>>>0];f+=8;for(var Ee=0;Ee>>0],Ye=ll[d];ze===0||ze===10?((d===1?k:P)(rr(Ye)),Ye.length=0):Ye.push(ze)}I+=ye}return we()[C>>>2>>>0]=I,0}function ao(d){return d>>>0}u||function(){for(var d=n.numThreads-1;d--;)us();te.unshift(()=>{Pe++,function(f){u?f():Promise.all(qe.map(dr)).then(f)}(()=>Ae())})}();for(var lo=Array(256),In=0;256>In;++In)lo[In]=String.fromCharCode(In);rn=lo,Lr=n.BindingError=class extends Error{constructor(d){super(d),this.name="BindingError"}},n.InternalError=class extends Error{constructor(d){super(d),this.name="InternalError"}},Ar.push(0,1,void 0,1,null,1,!0,1,!1,1),n.count_emval_handles=()=>Ar.length/2-5-Ns.length;var Oe,dl=[Re,Fe,Be,kr,hs,ms,_s,Qr,Cs,Xs,Js,Ys,Zs,gs,en,tn,Hn,Yi,Zi,so,Yn,no,io,Zn,oo];(async function(){function d(C,I){return Oe=C.exports,Oe=function(){var W=Oe,ne={};for(let[ye,Ee]of Object.entries(W))ne[ye]=typeof Ee=="function"?(...ze)=>{qt.push(ye);try{return Ee(...ze)}finally{ue||(qt.pop(),Rt&&cr===1&&qt.length===0&&(cr=0,be+=1,Ht(qo),typeof Fibers<"u"&&Fibers.le()))}}:Ee;return ne}(),Oe=function(){var W=Oe,ne=Ee=>ze=>Ee(ze)>>>0,ye=Ee=>()=>Ee()>>>0;return(W=Object.assign({},W)).Cb=ne(W.Cb),W.fc=ye(W.fc),W.ic=ne(W.ic),W.vc=ne(W.vc),W.wc=ye(W.wc),W.Ac=ne(W.Ac),W}(),ct.push(Oe.jc),w=I,Ae(),Oe}Pe++;var f=Le();if(n.instantiateWasm)return new Promise(C=>{n.instantiateWasm(f,(I,W)=>{d(I,W),C(I.exports)})});if(u)return new Promise(C=>{He=I=>{var W=new WebAssembly.Instance(I,Le());C(d(W,I))}});fe??(fe=n.locateFile?n.locateFile?n.locateFile("ort-wasm-simd-threaded.jsep.wasm",A):A+"ort-wasm-simd-threaded.jsep.wasm":new URL("/assets/ort-wasm-simd-threaded.jsep-BAR87mbD.wasm",self.location.href).href);try{var T=await async function(C){var I=fe;if(!ae&&typeof WebAssembly.instantiateStreaming=="function"&&!he(I))try{var W=fetch(I,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(W,C)}catch(ne){P(`wasm streaming compile failed: ${ne}`),P("falling back to ArrayBuffer instantiation")}return async function(ne,ye){try{var Ee=await async function(ze){if(!ae)try{var Ye=await h(ze);return new Uint8Array(Ye)}catch{}if(ze==fe&&ae)ze=new Uint8Array(ae);else{if(!g)throw"both async and sync fetching of the wasm failed";ze=g(ze)}return ze}(ne);return await WebAssembly.instantiate(Ee,ye)}catch(ze){P(`failed to asynchronously prepare wasm: ${ze}`),Ie(ze)}}(I,C)}(f);return d(T.instance,T.module)}catch(C){return i(C),Promise.reject(C)}})();var uo=d=>(uo=Oe.Cb)(d),ei=()=>(ei=Oe.Db)();n._OrtInit=(d,f)=>(n._OrtInit=Oe.Eb)(d,f),n._OrtGetLastError=(d,f)=>(n._OrtGetLastError=Oe.Fb)(d,f),n._OrtCreateSessionOptions=(d,f,T,C,I,W,ne,ye,Ee,ze)=>(n._OrtCreateSessionOptions=Oe.Gb)(d,f,T,C,I,W,ne,ye,Ee,ze),n._OrtAppendExecutionProvider=(d,f)=>(n._OrtAppendExecutionProvider=Oe.Hb)(d,f),n._OrtAddFreeDimensionOverride=(d,f,T)=>(n._OrtAddFreeDimensionOverride=Oe.Ib)(d,f,T),n._OrtAddSessionConfigEntry=(d,f,T)=>(n._OrtAddSessionConfigEntry=Oe.Jb)(d,f,T),n._OrtReleaseSessionOptions=d=>(n._OrtReleaseSessionOptions=Oe.Kb)(d),n._OrtCreateSession=(d,f,T)=>(n._OrtCreateSession=Oe.Lb)(d,f,T),n._OrtReleaseSession=d=>(n._OrtReleaseSession=Oe.Mb)(d),n._OrtGetInputOutputCount=(d,f,T)=>(n._OrtGetInputOutputCount=Oe.Nb)(d,f,T),n._OrtGetInputName=(d,f)=>(n._OrtGetInputName=Oe.Ob)(d,f),n._OrtGetOutputName=(d,f)=>(n._OrtGetOutputName=Oe.Pb)(d,f),n._OrtFree=d=>(n._OrtFree=Oe.Qb)(d),n._OrtCreateTensor=(d,f,T,C,I,W)=>(n._OrtCreateTensor=Oe.Rb)(d,f,T,C,I,W),n._OrtGetTensorData=(d,f,T,C,I)=>(n._OrtGetTensorData=Oe.Sb)(d,f,T,C,I),n._OrtReleaseTensor=d=>(n._OrtReleaseTensor=Oe.Tb)(d),n._OrtCreateRunOptions=(d,f,T,C)=>(n._OrtCreateRunOptions=Oe.Ub)(d,f,T,C),n._OrtAddRunConfigEntry=(d,f,T)=>(n._OrtAddRunConfigEntry=Oe.Vb)(d,f,T),n._OrtReleaseRunOptions=d=>(n._OrtReleaseRunOptions=Oe.Wb)(d),n._OrtCreateBinding=d=>(n._OrtCreateBinding=Oe.Xb)(d),n._OrtBindInput=(d,f,T)=>(n._OrtBindInput=Oe.Yb)(d,f,T),n._OrtBindOutput=(d,f,T,C)=>(n._OrtBindOutput=Oe.Zb)(d,f,T,C),n._OrtClearBoundOutputs=d=>(n._OrtClearBoundOutputs=Oe._b)(d),n._OrtReleaseBinding=d=>(n._OrtReleaseBinding=Oe.$b)(d),n._OrtRunWithBinding=(d,f,T,C,I)=>(n._OrtRunWithBinding=Oe.ac)(d,f,T,C,I),n._OrtRun=(d,f,T,C,I,W,ne,ye)=>(n._OrtRun=Oe.bc)(d,f,T,C,I,W,ne,ye),n._OrtEndProfiling=d=>(n._OrtEndProfiling=Oe.cc)(d),n._JsepOutput=(d,f,T)=>(n._JsepOutput=Oe.dc)(d,f,T),n._JsepGetNodeName=d=>(n._JsepGetNodeName=Oe.ec)(d);var An=()=>(An=Oe.fc)(),Ur=n._free=d=>(Ur=n._free=Oe.gc)(d),ln=n._malloc=d=>(ln=n._malloc=Oe.ic)(d),ti=(d,f,T,C,I,W)=>(ti=Oe.kc)(d,f,T,C,I,W),co=()=>(co=Oe.lc)(),ri=(d,f,T,C,I)=>(ri=Oe.mc)(d,f,T,C,I),po=d=>(po=Oe.nc)(d),si=d=>(si=Oe.oc)(d),ni=(d,f)=>(ni=Oe.pc)(d,f),ho=()=>(ho=Oe.qc)(),gt=(d,f)=>(gt=Oe.rc)(d,f),Ws=d=>(Ws=Oe.sc)(d),fo=(d,f)=>(fo=Oe.tc)(d,f),ft=d=>(ft=Oe.uc)(d),Fn=d=>(Fn=Oe.vc)(d),mt=()=>(mt=Oe.wc)(),mo=d=>(mo=Oe.xc)(d),ii=d=>(ii=Oe.yc)(d),_o=(d,f,T)=>(_o=Oe.zc)(d,f,T),go=d=>(go=Oe.Ac)(d),oi=n.dynCall_iii=(d,f,T)=>(oi=n.dynCall_iii=Oe.Bc)(d,f,T),wo=n.dynCall_vi=(d,f)=>(wo=n.dynCall_vi=Oe.Cc)(d,f),ai=n.dynCall_ii=(d,f)=>(ai=n.dynCall_ii=Oe.Dc)(d,f),li=n.dynCall_vii=(d,f,T)=>(li=n.dynCall_vii=Oe.Ec)(d,f,T),yo=n.dynCall_iiii=(d,f,T,C)=>(yo=n.dynCall_iiii=Oe.Fc)(d,f,T,C),Mo=n.dynCall_viii=(d,f,T,C)=>(Mo=n.dynCall_viii=Oe.Gc)(d,f,T,C),di=n.dynCall_iiiii=(d,f,T,C,I)=>(di=n.dynCall_iiiii=Oe.Hc)(d,f,T,C,I),bo=n.dynCall_viiii=(d,f,T,C,I)=>(bo=n.dynCall_viiii=Oe.Ic)(d,f,T,C,I),vo=n.dynCall_viiiiii=(d,f,T,C,I,W,ne)=>(vo=n.dynCall_viiiiii=Oe.Jc)(d,f,T,C,I,W,ne),ui=n.dynCall_viiiiiii=(d,f,T,C,I,W,ne,ye)=>(ui=n.dynCall_viiiiiii=Oe.Kc)(d,f,T,C,I,W,ne,ye),To=n.dynCall_ji=(d,f)=>(To=n.dynCall_ji=Oe.Lc)(d,f),xo=n.dynCall_v=d=>(xo=n.dynCall_v=Oe.Mc)(d),ci=n.dynCall_viiiii=(d,f,T,C,I,W)=>(ci=n.dynCall_viiiii=Oe.Nc)(d,f,T,C,I,W),Eo=n.dynCall_i=d=>(Eo=n.dynCall_i=Oe.Oc)(d),Po=n.dynCall_fii=(d,f,T)=>(Po=n.dynCall_fii=Oe.Pc)(d,f,T),pi=n.dynCall_viiiiiiii=(d,f,T,C,I,W,ne,ye,Ee)=>(pi=n.dynCall_viiiiiiii=Oe.Qc)(d,f,T,C,I,W,ne,ye,Ee),Co=n.dynCall_viiiiiiiiii=(d,f,T,C,I,W,ne,ye,Ee,ze,Ye)=>(Co=n.dynCall_viiiiiiiiii=Oe.Rc)(d,f,T,C,I,W,ne,ye,Ee,ze,Ye),So=n.dynCall_jiii=(d,f,T,C)=>(So=n.dynCall_jiii=Oe.Sc)(d,f,T,C),hi=n.dynCall_dii=(d,f,T)=>(hi=n.dynCall_dii=Oe.Tc)(d,f,T),$o=n.dynCall_viiiiiiiii=(d,f,T,C,I,W,ne,ye,Ee,ze)=>($o=n.dynCall_viiiiiiiii=Oe.Uc)(d,f,T,C,I,W,ne,ye,Ee,ze),ko=n.dynCall_viiiiiiiiiii=(d,f,T,C,I,W,ne,ye,Ee,ze,Ye,ot)=>(ko=n.dynCall_viiiiiiiiiii=Oe.Vc)(d,f,T,C,I,W,ne,ye,Ee,ze,Ye,ot),fi=n.dynCall_iiiiii=(d,f,T,C,I,W)=>(fi=n.dynCall_iiiiii=Oe.Wc)(d,f,T,C,I,W),Io=n.dynCall_iij=(d,f,T)=>(Io=n.dynCall_iij=Oe.Xc)(d,f,T),Ao=n.dynCall_iiiiiiiiii=(d,f,T,C,I,W,ne,ye,Ee,ze)=>(Ao=n.dynCall_iiiiiiiiii=Oe.Yc)(d,f,T,C,I,W,ne,ye,Ee,ze),Fo=n.dynCall_iiiiiiiiiii=(d,f,T,C,I,W,ne,ye,Ee,ze,Ye)=>(Fo=n.dynCall_iiiiiiiiiii=Oe.Zc)(d,f,T,C,I,W,ne,ye,Ee,ze,Ye),Oo=n.dynCall_vij=(d,f,T)=>(Oo=n.dynCall_vij=Oe._c)(d,f,T),mi=n.dynCall_iiif=(d,f,T,C)=>(mi=n.dynCall_iiif=Oe.$c)(d,f,T,C),Do=n.dynCall_iiij=(d,f,T,C)=>(Do=n.dynCall_iiij=Oe.ad)(d,f,T,C),Lo=n.dynCall_fiii=(d,f,T,C)=>(Lo=n.dynCall_fiii=Oe.bd)(d,f,T,C),_i=n.dynCall_viiiiiiiiiiiii=(d,f,T,C,I,W,ne,ye,Ee,ze,Ye,ot,_t,Bt)=>(_i=n.dynCall_viiiiiiiiiiiii=Oe.cd)(d,f,T,C,I,W,ne,ye,Ee,ze,Ye,ot,_t,Bt),zo=n.dynCall_vjiii=(d,f,T,C,I)=>(zo=n.dynCall_vjiii=Oe.dd)(d,f,T,C,I),Bo=n.dynCall_vif=(d,f,T)=>(Bo=n.dynCall_vif=Oe.ed)(d,f,T),gi=n.dynCall_iiiiiii=(d,f,T,C,I,W,ne)=>(gi=n.dynCall_iiiiiii=Oe.fd)(d,f,T,C,I,W,ne),Ro=n.dynCall_iiiij=(d,f,T,C,I)=>(Ro=n.dynCall_iiiij=Oe.gd)(d,f,T,C,I),No=n.dynCall_iiiiiiii=(d,f,T,C,I,W,ne,ye)=>(No=n.dynCall_iiiiiiii=Oe.hd)(d,f,T,C,I,W,ne,ye),wi=n.dynCall_viiiiiiiiiiii=(d,f,T,C,I,W,ne,ye,Ee,ze,Ye,ot,_t)=>(wi=n.dynCall_viiiiiiiiiiii=Oe.id)(d,f,T,C,I,W,ne,ye,Ee,ze,Ye,ot,_t),jo=n.dynCall_diii=(d,f,T,C)=>(jo=n.dynCall_diii=Oe.jd)(d,f,T,C),Vo=n.dynCall_jiiii=(d,f,T,C,I)=>(Vo=n.dynCall_jiiii=Oe.kd)(d,f,T,C,I),yi=n.dynCall_viiij=(d,f,T,C,I)=>(yi=n.dynCall_viiij=Oe.ld)(d,f,T,C,I),Uo=n.dynCall_fiiii=(d,f,T,C,I)=>(Uo=n.dynCall_fiiii=Oe.md)(d,f,T,C,I),Wo=n.dynCall_viiif=(d,f,T,C,I)=>(Wo=n.dynCall_viiif=Oe.nd)(d,f,T,C,I),Mi=n.dynCall_diiii=(d,f,T,C,I)=>(Mi=n.dynCall_diiii=Oe.od)(d,f,T,C,I),Go=n.dynCall_viiid=(d,f,T,C,I)=>(Go=n.dynCall_viiid=Oe.pd)(d,f,T,C,I),Ko=n.dynCall_iiiijii=(d,f,T,C,I,W,ne)=>(Ko=n.dynCall_iiiijii=Oe.qd)(d,f,T,C,I,W,ne),bi=n.dynCall_iiiiiij=(d,f,T,C,I,W,ne)=>(bi=n.dynCall_iiiiiij=Oe.rd)(d,f,T,C,I,W,ne),Ho=d=>(Ho=Oe.sd)(d),qo=()=>(qo=Oe.td)(),Qo=d=>(Qo=Oe.ud)(d),Xo=()=>(Xo=Oe.vd)();function Jo(d,f,T){var C=mt();try{li(d,f,T)}catch(I){if(ft(C),I!==I+0)throw I;gt(1,0)}}function ul(d,f,T){var C=mt();try{return oi(d,f,T)}catch(I){if(ft(C),I!==I+0)throw I;gt(1,0)}}function cl(d,f){var T=mt();try{wo(d,f)}catch(C){if(ft(T),C!==C+0)throw C;gt(1,0)}}function pl(d,f){var T=mt();try{return ai(d,f)}catch(C){if(ft(T),C!==C+0)throw C;gt(1,0)}}function hl(d,f,T,C){var I=mt();try{return yo(d,f,T,C)}catch(W){if(ft(I),W!==W+0)throw W;gt(1,0)}}function Yo(d,f,T,C,I){var W=mt();try{bo(d,f,T,C,I)}catch(ne){if(ft(W),ne!==ne+0)throw ne;gt(1,0)}}function fl(d,f,T,C,I){var W=mt();try{return di(d,f,T,C,I)}catch(ne){if(ft(W),ne!==ne+0)throw ne;gt(1,0)}}function ml(d,f,T,C){var I=mt();try{Mo(d,f,T,C)}catch(W){if(ft(I),W!==W+0)throw W;gt(1,0)}}function _l(d,f,T,C,I,W,ne){var ye=mt();try{return gi(d,f,T,C,I,W,ne)}catch(Ee){if(ft(ye),Ee!==Ee+0)throw Ee;gt(1,0)}}function gl(d){var f=mt();try{xo(d)}catch(T){if(ft(f),T!==T+0)throw T;gt(1,0)}}function Zo(d,f,T){var C=mt();try{return Io(d,f,T)}catch(I){if(ft(C),I!==I+0)throw I;gt(1,0)}}function wl(d,f,T,C,I,W){var ne=mt();try{ci(d,f,T,C,I,W)}catch(ye){if(ft(ne),ye!==ye+0)throw ye;gt(1,0)}}function yl(d,f,T){var C=mt();try{Oo(d,f,T)}catch(I){if(ft(C),I!==I+0)throw I;gt(1,0)}}function Ml(d,f,T,C,I,W,ne){var ye=mt();try{vo(d,f,T,C,I,W,ne)}catch(Ee){if(ft(ye),Ee!==Ee+0)throw Ee;gt(1,0)}}function bl(d,f,T,C,I,W,ne,ye){var Ee=mt();try{ui(d,f,T,C,I,W,ne,ye)}catch(ze){if(ft(Ee),ze!==ze+0)throw ze;gt(1,0)}}function ea(d,f,T,C,I,W){var ne=mt();try{return fi(d,f,T,C,I,W)}catch(ye){if(ft(ne),ye!==ye+0)throw ye;gt(1,0)}}function vl(d,f,T,C,I,W,ne,ye){var Ee=mt();try{return No(d,f,T,C,I,W,ne,ye)}catch(ze){if(ft(Ee),ze!==ze+0)throw ze;gt(1,0)}}function Tl(d,f,T,C,I,W,ne,ye,Ee,ze){var Ye=mt();try{$o(d,f,T,C,I,W,ne,ye,Ee,ze)}catch(ot){if(ft(Ye),ot!==ot+0)throw ot;gt(1,0)}}function ta(d,f,T,C,I,W,ne,ye,Ee){var ze=mt();try{pi(d,f,T,C,I,W,ne,ye,Ee)}catch(Ye){if(ft(ze),Ye!==Ye+0)throw Ye;gt(1,0)}}function xl(d){var f=mt();try{return Eo(d)}catch(T){if(ft(f),T!==T+0)throw T;gt(1,0)}}function El(d,f,T,C,I,W,ne,ye,Ee,ze){var Ye=mt();try{return Ao(d,f,T,C,I,W,ne,ye,Ee,ze)}catch(ot){if(ft(Ye),ot!==ot+0)throw ot;gt(1,0)}}function ra(d,f,T){var C=mt();try{return Po(d,f,T)}catch(I){if(ft(C),I!==I+0)throw I;gt(1,0)}}function Pl(d,f,T,C){var I=mt();try{return So(d,f,T,C)}catch(W){if(ft(I),W!==W+0)throw W;return gt(1,0),0n}}function Cl(d,f,T){var C=mt();try{return hi(d,f,T)}catch(I){if(ft(C),I!==I+0)throw I;gt(1,0)}}function sa(d,f,T,C,I,W,ne,ye,Ee,ze,Ye,ot){var _t=mt();try{ko(d,f,T,C,I,W,ne,ye,Ee,ze,Ye,ot)}catch(Bt){if(ft(_t),Bt!==Bt+0)throw Bt;gt(1,0)}}function Sl(d,f,T,C,I,W,ne,ye,Ee,ze,Ye){var ot=mt();try{Co(d,f,T,C,I,W,ne,ye,Ee,ze,Ye)}catch(_t){if(ft(ot),_t!==_t+0)throw _t;gt(1,0)}}function $l(d,f,T,C,I,W,ne,ye,Ee,ze,Ye){var ot=mt();try{return Fo(d,f,T,C,I,W,ne,ye,Ee,ze,Ye)}catch(_t){if(ft(ot),_t!==_t+0)throw _t;gt(1,0)}}function na(d,f,T,C){var I=mt();try{return mi(d,f,T,C)}catch(W){if(ft(I),W!==W+0)throw W;gt(1,0)}}function kl(d,f,T,C){var I=mt();try{return Do(d,f,T,C)}catch(W){if(ft(I),W!==W+0)throw W;gt(1,0)}}function Il(d,f,T,C){var I=mt();try{return Lo(d,f,T,C)}catch(W){if(ft(I),W!==W+0)throw W;gt(1,0)}}function vi(d,f,T,C,I,W,ne,ye,Ee,ze,Ye,ot,_t,Bt){var Fr=mt();try{_i(d,f,T,C,I,W,ne,ye,Ee,ze,Ye,ot,_t,Bt)}catch(ks){if(ft(Fr),ks!==ks+0)throw ks;gt(1,0)}}function Al(d,f,T,C,I){var W=mt();try{zo(d,f,T,C,I)}catch(ne){if(ft(W),ne!==ne+0)throw ne;gt(1,0)}}function Fl(d,f,T){var C=mt();try{Bo(d,f,T)}catch(I){if(ft(C),I!==I+0)throw I;gt(1,0)}}function ia(d,f){var T=mt();try{return To(d,f)}catch(C){if(ft(T),C!==C+0)throw C;return gt(1,0),0n}}function oa(d,f,T,C,I){var W=mt();try{return Ro(d,f,T,C,I)}catch(ne){if(ft(W),ne!==ne+0)throw ne;gt(1,0)}}function Ol(d,f,T,C,I,W,ne,ye,Ee,ze,Ye,ot,_t){var Bt=mt();try{wi(d,f,T,C,I,W,ne,ye,Ee,ze,Ye,ot,_t)}catch(Fr){if(ft(Bt),Fr!==Fr+0)throw Fr;gt(1,0)}}function aa(d,f,T,C){var I=mt();try{return jo(d,f,T,C)}catch(W){if(ft(I),W!==W+0)throw W;gt(1,0)}}function Dl(d,f,T,C,I){var W=mt();try{return Vo(d,f,T,C,I)}catch(ne){if(ft(W),ne!==ne+0)throw ne;return gt(1,0),0n}}function Ll(d,f,T,C,I){var W=mt();try{yi(d,f,T,C,I)}catch(ne){if(ft(W),ne!==ne+0)throw ne;gt(1,0)}}function Ti(d,f,T,C,I){var W=mt();try{return Uo(d,f,T,C,I)}catch(ne){if(ft(W),ne!==ne+0)throw ne;gt(1,0)}}function la(d,f,T,C,I){var W=mt();try{Wo(d,f,T,C,I)}catch(ne){if(ft(W),ne!==ne+0)throw ne;gt(1,0)}}function zl(d,f,T,C,I){var W=mt();try{return Mi(d,f,T,C,I)}catch(ne){if(ft(W),ne!==ne+0)throw ne;gt(1,0)}}function Bl(d,f,T,C,I){var W=mt();try{Go(d,f,T,C,I)}catch(ne){if(ft(W),ne!==ne+0)throw ne;gt(1,0)}}function Rl(d,f,T,C,I,W,ne){var ye=mt();try{return Ko(d,f,T,C,I,W,ne)}catch(Ee){if(ft(ye),Ee!==Ee+0)throw Ee;gt(1,0)}}function da(d,f,T,C,I,W,ne){var ye=mt();try{return bi(d,f,T,C,I,W,ne)}catch(Ee){if(ft(ye),Ee!==Ee+0)throw Ee;gt(1,0)}}return n.stackSave=()=>mt(),n.stackRestore=d=>ft(d),n.stackAlloc=d=>Fn(d),n.setValue=function(d,f,T="i8"){switch(T.endsWith("*")&&(T="*"),T){case"i1":case"i8":N()[d>>>0]=f;break;case"i16":G()[d>>>1>>>0]=f;break;case"i32":X()[d>>>2>>>0]=f;break;case"i64":H[d>>>3]=BigInt(f);break;case"float":_e()[d>>>2>>>0]=f;break;case"double":ke()[d>>>3>>>0]=f;break;case"*":we()[d>>>2>>>0]=f;break;default:Ie(`invalid type for setValue: ${T}`)}},n.getValue=function(d,f="i8"){switch(f.endsWith("*")&&(f="*"),f){case"i1":case"i8":return N()[d>>>0];case"i16":return G()[d>>>1>>>0];case"i32":return X()[d>>>2>>>0];case"i64":return H[d>>>3];case"float":return _e()[d>>>2>>>0];case"double":return ke()[d>>>3>>>0];case"*":return we()[d>>>2>>>0];default:Ie(`invalid type for getValue: ${f}`)}},n.UTF8ToString=zt,n.stringToUTF8=Er,n.lengthBytesUTF8=fs,function d(){if(0{_d(),bd=typeof location>"u"?void 0:location.origin,vd=self.location.href>"file:"&&self.location.href<"file;",dp=()=>{{if(vd){let e=URL;return new URL(new e("ort.bundle.min.mjs",self.location.href).href,bd).href}return self.location.href}},Rr=dp(),up=()=>{if(Rr&&!Rr.startsWith("blob:"))return Rr.substring(0,Rr.lastIndexOf("/")+1)},_a=(e,r)=>{try{let t=r??Rr;return(t?new URL(e,t):new URL(e)).origin===bd}catch{return!1}},cp=(e,r)=>{let t=r??Rr;try{return(t?new URL(e,t):new URL(e)).href}catch{return}},pp=(e,r)=>`${r??"./"}${e}`,Td=async e=>{let r=await(await fetch(e,{credentials:"same-origin"})).blob();return URL.createObjectURL(r)},hp=async e=>(await import(e)).default,xd=(uv(),fa(np)).default,fp=async()=>{if(!Rr)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(_a(Rr))return[void 0,xd()];let e=await Td(Rr);return[e,xd(e)]},Ed=(cv(),fa(op)).default,mp=async(e,r,t)=>{if(!e&&!r&&Ed&&Rr&&_a(Rr))return[void 0,Ed];{let s="ort-wasm-simd-threaded.jsep.mjs",i=e??cp(s,r),n=t&&i&&!_a(i,r),o=n?await Td(i):i??pp(s,r);return[n?o:void 0,await hp(o)]}}}),Cd,ga,Ii,Sd,_p,gp,$d,ar,fn=Ve(()=>{Pd(),ga=!1,Ii=!1,Sd=!1,_p=()=>{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}},gp=()=>{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}},$d=async e=>{if(ga)return Promise.resolve();if(Ii)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Sd)throw new Error("previous call to 'initializeWebAssembly()' failed.");Ii=!0;let r=e.initTimeout,t=e.numThreads;if(!gp())throw new Error("WebAssembly SIMD is not supported in the current environment.");let s=_p();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 i=e.wasmPaths,n=typeof i=="string"?i:void 0,o=i==null?void 0:i.mjs,a=(o==null?void 0:o.href)??o,l=i==null?void 0:i.wasm,u=(l==null?void 0:l.href)??l,p=e.wasmBinary,[c,h]=await mp(a,n,t>1),g=!1,_=[];if(r>0&&_.push(new Promise(E=>{setTimeout(()=>{g=!0,E()},r)})),_.push(new Promise((E,A)=>{let v={numThreads:t};if(p)v.wasmBinary=p;else if(u||n)v.locateFile=y=>u??n+y;else if(a&&a.indexOf("blob:")!==0)v.locateFile=y=>new URL(y,a).href;else if(c){let y=up();y&&(v.locateFile=k=>y+k)}h(v).then(y=>{Ii=!1,ga=!0,Cd=y,E(),c&&URL.revokeObjectURL(c)},y=>{Ii=!1,Sd=!0,A(y)})})),await Promise.race(_),g)throw new Error(`WebAssembly backend initializing failed due to timeout: ${r}ms`)},ar=()=>{if(ga&&Cd)return Cd;throw new Error("WebAssembly is not initialized yet.")}}),Mr,wa,At,kd=Ve(()=>{fn(),Mr=(e,r)=>{let t=ar(),s=t.lengthBytesUTF8(e)+1,i=t._malloc(s);return t.stringToUTF8(e,i,s),r.push(i),i},wa=(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(([i,n])=>{let o=r?r+i:i;if(typeof n=="object")wa(n,o+".",t,s);else if(typeof n=="string"||typeof n=="number")s(o,n.toString());else if(typeof n=="boolean")s(o,n?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof n}`)})},At=e=>{let r=ar(),t=r.stackSave();try{let s=r.PTR_SIZE,i=r.stackAlloc(2*s);r._OrtGetLastError(i,i+s);let n=Number(r.getValue(i,s===4?"i32":"i64")),o=r.getValue(i+s,"*"),a=o?r.UTF8ToString(o):"";throw new Error(`${e} ERROR_CODE: ${n}, ERROR_MESSAGE: ${a}`)}finally{r.stackRestore(t)}}}),wp,pv=Ve(()=>{fn(),kd(),wp=e=>{let r=ar(),t=0,s=[],i=e||{};try{if((e==null?void 0:e.logSeverityLevel)===void 0)i.logSeverityLevel=2;else if(typeof e.logSeverityLevel!="number"||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${e.logSeverityLevel}`);if((e==null?void 0:e.logVerbosityLevel)===void 0)i.logVerbosityLevel=0;else if(typeof e.logVerbosityLevel!="number"||!Number.isInteger(e.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);(e==null?void 0:e.terminate)===void 0&&(i.terminate=!1);let n=0;return(e==null?void 0:e.tag)!==void 0&&(n=Mr(e.tag,s)),t=r._OrtCreateRunOptions(i.logSeverityLevel,i.logVerbosityLevel,!!i.terminate,n),t===0&&At("Can't create run options."),(e==null?void 0:e.extra)!==void 0&&wa(e.extra,"",new WeakSet,(o,a)=>{let l=Mr(o,s),u=Mr(a,s);r._OrtAddRunConfigEntry(t,l,u)!==0&&At(`Can't set a run config entry: ${o} - ${a}.`)}),[t,s]}catch(n){throw t!==0&&r._OrtReleaseRunOptions(t),s.forEach(o=>r._free(o)),n}}}),yp,Mp,bp,vp,Tp,hv=Ve(()=>{fn(),kd(),yp=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}`)}},Mp=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},bp=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)},vp=(e,r,t)=>{for(let s of r){let i=typeof s=="string"?s:s.name;switch(i){case"webnn":if(i="WEBNN",typeof s!="string"){let o=s==null?void 0:s.deviceType;if(o){let a=Mr("deviceType",t),l=Mr(o,t);ar()._OrtAddSessionConfigEntry(e,a,l)!==0&&At(`Can't set a session config entry: 'deviceType' - ${o}.`)}}break;case"webgpu":if(i="JS",typeof s!="string"){let o=s;if(o!=null&&o.preferredLayout){if(o.preferredLayout!=="NCHW"&&o.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${o.preferredLayout}`);let a=Mr("preferredLayout",t),l=Mr(o.preferredLayout,t);ar()._OrtAddSessionConfigEntry(e,a,l)!==0&&At(`Can't set a session config entry: 'preferredLayout' - ${o.preferredLayout}.`)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${i}`)}let n=Mr(i,t);ar()._OrtAppendExecutionProvider(e,n)!==0&&At(`Can't append execution provider: ${i}.`)}},Tp=e=>{let r=ar(),t=0,s=[],i=e||{};bp(i);try{let n=yp(i.graphOptimizationLevel??"all"),o=Mp(i.executionMode??"sequential"),a=typeof i.logId=="string"?Mr(i.logId,s):0,l=i.logSeverityLevel??2;if(!Number.isInteger(l)||l<0||l>4)throw new Error(`log serverity level is not valid: ${l}`);let u=i.logVerbosityLevel??0;if(!Number.isInteger(u)||u<0||u>4)throw new Error(`log verbosity level is not valid: ${u}`);let p=typeof i.optimizedModelFilePath=="string"?Mr(i.optimizedModelFilePath,s):0;if(t=r._OrtCreateSessionOptions(n,!!i.enableCpuMemArena,!!i.enableMemPattern,o,!!i.enableProfiling,0,a,l,u,p),t===0&&At("Can't create session options."),i.executionProviders&&vp(t,i.executionProviders,s),i.enableGraphCapture!==void 0){if(typeof i.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${i.enableGraphCapture}`);let c=Mr("enableGraphCapture",s),h=Mr(i.enableGraphCapture.toString(),s);r._OrtAddSessionConfigEntry(t,c,h)!==0&&At(`Can't set a session config entry: 'enableGraphCapture' - ${i.enableGraphCapture}.`)}if(i.freeDimensionOverrides)for(let[c,h]of Object.entries(i.freeDimensionOverrides)){if(typeof c!="string")throw new Error(`free dimension override name must be a string: ${c}`);if(typeof h!="number"||!Number.isInteger(h)||h<0)throw new Error(`free dimension override value must be a non-negative integer: ${h}`);let g=Mr(c,s);r._OrtAddFreeDimensionOverride(t,g,h)!==0&&At(`Can't set a free dimension override: ${c} - ${h}.`)}return i.extra!==void 0&&wa(i.extra,"",new WeakSet,(c,h)=>{let g=Mr(c,s),_=Mr(h,s);r._OrtAddSessionConfigEntry(t,g,_)!==0&&At(`Can't set a session config entry: ${c} - ${h}.`)}),[t,s]}catch(n){throw t!==0&&r._OrtReleaseSessionOptions(t)!==0&&At("Can't release session options."),s.forEach(o=>r._free(o)),n}}}),Rn,mn,_n,Id,ya,Ad,Fd,Od,pt=Ve(()=>{Rn=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}`)}},mn=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}`)}},_n=(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((i,n)=>i*n,1);return t>0?Math.ceil(s*t):void 0},Id=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}`)}},ya=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}`)}},Ad=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",Fd=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint64"||e==="int8"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",Od=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}`)}}}),Dd,xp=Ve(()=>{_d(),Dd=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 i=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 o=0;for(;;){let{done:a,value:l}=await i.read();if(a)break;let u=l.byteLength;new Uint8Array(n,o,u).set(l),o+=u}return new Uint8Array(n,0,s)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),Ep,Pp,Cp,Sp,Ld,$p,St,As=Ve(()=>{pt(),Ep=["V","I","W","E","F"],Pp=(e,r)=>{console.log(`[${Ep[e]},${new Date().toISOString()}]${r}`)},Ld=(e,r)=>{Cp=e,Sp=r},$p=(e,r)=>{let t=ya(e),s=ya(Cp);t>=s&&Pp(t,typeof r=="function"?r():r)},St=(...e)=>{Sp&&$p(...e)}}),zd,kp=Ve(()=>{pt(),zd=(e,r)=>new(Id(r))(e)}),Bd=Ve(()=>{}),Rd,Ma,ba,Ip,Ap,Nd,jd,Fp,Op,fv=Ve(()=>{As(),Bd(),Rd=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]]),Ma=[],ba=e=>Math.ceil(Number(e)/16)*16,Ip=e=>{for(let r=0;rAp++,jd=async(e,r,t,s)=>{let i=ba(t),n=e.device.createBuffer({size:i,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let o=e.getCommandEncoder();e.endComputePass(),o.copyBufferToBuffer(r,0,n,0,i),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()}},Fp=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 Rd)Ma.push(r),this.freeBuffers.set(r,[]),this.freeUniformBuffers.set(r,[]);this.sessionCount=0}upload(e,r){let t=r.buffer,s=r.byteOffset,i=r.byteLength,n=ba(i),o=this.storageCache.get(e);if(!o)throw new Error("gpu data for uploading does not exist");if(Number(o.originalSize)!==i)throw new Error(`inconsistent data size. gpu data size=${o.originalSize}, data size=${i}`);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,i)),a.unmap();let u=this.backend.device.createCommandEncoder();u.copyBufferToBuffer(a,0,o.gpuData.buffer,0,n),this.backend.device.queue.submit([u.finish()]),a.destroy(),St("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 i=ba(t.originalSize),n=this.backend.getCommandEncoder();this.backend.endComputePass(),n.copyBufferToBuffer(t.gpuData.buffer,0,s.gpuData.buffer,0,i)}registerExternalBuffer(e,r,t){let s;if(t){if(s=t[0],e===t[1])return St("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=Nd();return this.storageCache.set(s,{gpuData:{id:s,type:0,buffer:e},originalSize:r}),St("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${r}) => id=${s}, registered.`),s}unregisterExternalBuffer(e){e!==void 0&&(this.storageCache.delete(e),St("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${e}`))}create(e,r=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let t=Ip(e),s,i=(r&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,n=(r&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(i||n){let a=(i?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 o={id:Nd(),type:0,buffer:s};return this.storageCache.set(o.id,{gpuData:o,originalSize:Number(e)}),St("verbose",()=>`[WebGPU] GpuDataManager.create(size=${e}) => id=${o.id}`),o}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 St("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 jd(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=Rd.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&&(St("warning",()=>"[WebGPU] Clearing webgpu buffer cache"),this.storageCache.forEach(t=>{t.gpuData.buffer.destroy()}),this.storageCache=new Map)}},Op=(...e)=>new Fp(...e)}),Dp,Dt,Yt=Ve(()=>{Dp=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}},Dt=e=>new Dp(e)}),Lp,Nn,Te,va,zp,Bp,Rp,Mt=Ve(()=>{Lp=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,i=r.length;if(s===0)return r;if(i===0)return e;let n=Math.max(e.length,r.length),o=new Array(n);if(t){if(s<2||i<2)return;let a=Lp.calcMatMulShape([e[s-2],e[s-1]],[r[i-2],r[i-1]]);if(a===void 0)return;[o[n-2],o[n-1]]=a}for(let a=t?3:1;a<=n;a++){let l=s-a<0?1:e[s-a],u=i-a<0?1:r[i-a];if(l!==u&&l>1&&u>1)return;let p=Math.max(l,u);if(l&&u)o[n-a]=Math.max(l,u);else{if(p>1)return;o[n-a]=0}}return o}static isValidBroadcast(e,r){let t=e.length,s=r.length;if(t>s)return!1;for(let i=1;i<=t;i++)if(e[t-i]!==1&&e[t-i]!==r[s-i])return!1;return!0}},Te=class od{static size(r){return od.getSizeFromDimensionRange(r,0,r.length)}static convertShape(r,t=4){let s=r.length;if(s===0)return[];let i=new Array(s),n=s-1;for(;n>=0;){if(r[n]%t===0){i[n]=r[n]/t;break}if(t%r[n]!==0)throw new Error("cannot convert shape");i[n]=1,t/=r[n],n--}for(n--;n>=0;n--)i[n]=r[n];return i}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 od.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 od.getSizeFromDimensionRange(r,0,t)}static getSizeFromDimensionRange(r,t,s){let i=1;for(let n=t;n=0;--i)s[i]=s[i+1]*r[i+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((i,n)=>i+t[n]+t[n+s])}static areEqual(r,t){return r.length!==t.length?!1:r.every((s,i)=>s===t[i])}},va=class pa{static adjustPoolAttributes(r,t,s,i,n,o){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]||o[a+s.length]>=s[a])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(r,t,s,i,n,o,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(i.length!==r.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let l=0;l{pt(),Mt(),jn=64,Ta=(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=Ta(e,r);return typeof t=="string"?t:t[0]},xr=(e,r=1)=>{let t=Ta(e,r);return typeof t=="string"?t:t[1]},nt=(...e)=>{let r=[];return e.forEach(t=>{t.length!==0&&r.push({type:12,data:t},{type:12,data:Te.computeStrides(t)})}),r},Xt=e=>e%4===0?4:e%2===0?2:1,Vd=(e="f32",r,t="0")=>!r||r===1?`${e}(${t})`:`vec${r}<${e}>(${t})`,Vn=(e,r,t)=>e==="f32"?t:r===1?`f32(${t})`:`vec${r}(${t})`,Ks=(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,rt=(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,Ai=(e,r,t,s,i)=>{let n=typeof t=="number",o=n?t:t.length,a=[...new Array(o).keys()],l=o<2?"u32":o<=4?`vec${o}`:`array`,u=Ta(r,i),p=typeof u=="string"?u:u[1],c=typeof u=="string"?u:u[0],h={indices:l,value:p,storage:c,tensor:r},g=N=>typeof N=="string"?N:`${N}u`,_={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},E=n?"uniforms.":"",A=`${E}${e}_shape`,v=`${E}${e}_strides`,y="";for(let N=0;N ${h.indices} { + var indices: ${h.indices}; + var current = offset; + ${y} + return indices; + }`,P=N=>(_.offsetToIndices=!0,o<2?N:`o2i_${e}(${N})`),M=[];if(o>=2)for(let N=o-1;N>=0;N--)M.push(`${rt(v,N,o)} * (indices[${N}])`);let w=o<2?"":` + fn i2o_${e}(indices: ${h.indices}) -> u32 { + return ${M.join("+")}; + }`,x=N=>(_.indicesToOffset=!0,o<2?N:`i2o_${e}(${N})`),$=(...N)=>o===0?"0u":`${h.indices}(${N.map(g).join(",")})`,z=(N,O)=>o<2?`${N}`:`${rt(N,O,o)}`,R=(N,O,G)=>o<2?`${N}=${G};`:`${rt(N,O,o)}=${G};`,Q={},q=(N,O)=>{_.broadcastedIndicesToOffset=!0;let G=`${O.name}broadcastedIndicesTo${e}Offset`;if(G in Q)return`${G}(${N})`;let se=[];for(let X=o-1;X>=0;X--){let we=O.indicesGet("outputIndices",X+O.rank-o);se.push(`${z(v,X)} * (${we} % ${z(A,X)})`)}return Q[G]=`fn ${G}(outputIndices: ${O.type.indices}) -> u32 { + return ${se.length>0?se.join("+"):"0u"}; + }`,`${G}(${N})`},U=(N,O)=>(()=>{if(h.storage===h.value)return`${e}[${N}]=${O};`;if(h.storage==="vec2"&&h.value==="i32")return`${e}[${N}]=vec2(u32(${O}), select(0u, 0xFFFFFFFFu, ${O} < 0));`;if(h.storage==="vec2"&&h.value==="u32")return`${e}[${N}]=vec2(u32(${O}), 0u);`;if(h.storage==="u32"&&h.value==="vec4")return`${e}[${N}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${O}));`;throw new Error(`not supported combination of storage type ${h.storage} and value type ${h.value} yet`)})(),Z=N=>(()=>{if(h.storage===h.value)return`${e}[${N}]`;if(h.storage==="vec2"&&h.value==="i32")return`i32(${e}[${N}].x)`;if(h.storage==="vec2"&&h.value==="u32")return`u32(${e}[${N}].x)`;if(h.storage==="u32"&&h.value==="vec4")return`vec4(bool(${e}[${N}] & 0xFFu), bool(${e}[${N}] & 0xFF00u), bool(${e}[${N}] & 0xFF0000u), bool(${e}[${N}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${h.storage} and value type ${h.value} yet`)})(),H=o<2?"":` + fn get_${e}ByIndices(indices: ${h.indices}) -> ${p} { + return ${Z(`i2o_${e}(indices)`)}; + }`,J=o<2?"":(()=>{let N=a.map(G=>`d${G}: u32`).join(", "),O=a.map(G=>`d${G}`).join(", ");return` + fn get_${e}(${N}) -> ${p} { + return get_${e}ByIndices(${$(O)}); + }`})(),ie=(...N)=>{if(N.length!==o)throw new Error(`indices length must be ${o}`);let O=N.map(g).join(",");return o===0?Z("0u"):o===1?Z(O[0]):(_.get=!0,_.getByIndices=!0,_.indicesToOffset=!0,`get_${e}(${O})`)},ae=N=>o<2?Z(N):(_.getByIndices=!0,_.indicesToOffset=!0,`get_${e}ByIndices(${N})`),ue=o<2?"":` + fn set_${e}ByIndices(indices: ${h.indices}, value: ${p}) { + ${U(`i2o_${e}(indices)`,"value")} + }`,he=o<2?"":(()=>{let N=a.map(G=>`d${G}: u32`).join(", "),O=a.map(G=>`d${G}`).join(", ");return` + fn set_${e}(${N}, value: ${p}) { + set_${e}ByIndices(${$(O)}, value); + }`})();return{impl:()=>{let N=[],O=!1;return _.offsetToIndices&&(N.push(k),O=!0),_.indicesToOffset&&(N.push(w),O=!0),_.broadcastedIndicesToOffset&&(Object.values(Q).forEach(G=>N.push(G)),O=!0),_.set&&(N.push(he),O=!0),_.setByIndices&&(N.push(ue),O=!0),_.get&&(N.push(J),O=!0),_.getByIndices&&(N.push(H),O=!0),!n&&O&&N.unshift(`const ${A} = ${h.indices}(${t.join(",")});`,`const ${v} = ${h.indices}(${Te.computeStrides(t).join(",")});`),N.join(` +`)},type:h,offsetToIndices:P,indicesToOffset:x,broadcastedIndicesToOffset:q,indices:$,indicesGet:z,indicesSet:R,set:(...N)=>{if(N.length!==o+1)throw new Error(`indices length must be ${o}`);let O=N[o];if(typeof O!="string")throw new Error("value must be string");let G=N.slice(0,o).map(g).join(",");return o===0?U("0u",O):o===1?U(G[0],O):(_.set=!0,_.setByIndices=!0,_.indicesToOffset=!0,`set_${e}(${G}, ${O})`)},setByOffset:U,setByIndices:(N,O)=>o<2?U(N,O):(_.setByIndices=!0,_.indicesToOffset=!0,`set_${e}ByIndices(${N}, ${O});`),get:ie,getByOffset:Z,getByIndices:ae,usage:s,name:e,strides:v,shape:A,rank:o}},$e=(e,r,t,s=1)=>Ai(e,r,t,"input",s),tt=(e,r,t,s=1)=>Ai(e,r,t,"output",s),Np=(e,r,t)=>Ai(e,r,t,"atomicOutput",1),Ud=(e,r,t,s=1)=>Ai(e,r,t,"internal",s),jp=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=jn){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 i=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1,n=i?`@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`,o=i?`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}) { + ${o} + `}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 i=s==null||s===1?t:`vec${s}<${t}>`;e.push(`${r}:${i}`)}return` + struct Uniforms { ${e.join(", ")} }; + @group(0) @binding(${this.variableIndex}) var uniforms: Uniforms;`}get additionalImplementations(){return this.uniformDeclaration()+this.variables.map(e=>e.impl()).join(` +`)+this.internalVariables.map(e=>e.impl()).join(` +`)}get variablesInfo(){if(this.uniforms.length===0)return;let e=r=>[12,10,1,6][["u32","f16","f32","i32"].indexOf(r)];return this.uniforms.map(r=>[e(r.type),r.length??1])}},Vp=(e,r)=>new jp(e,r)}),Up,Wd,Wp,Gp,Kp,Hp,Nr,qp,Qp,Hs=Ve(()=>{pt(),Mt(),Yt(),Tt(),Up=(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}`)},Wd=(e,r)=>r.length!==0?r:[...new Array(e).keys()].reverse(),Wp=(e,r)=>Te.sortBasedOnPerm(e,Wd(e.length,r)),Gp=(e,r,t,s)=>{let i=`fn perm(i: ${s.type.indices}) -> ${t.type.indices} { + var a: ${t.type.indices};`;for(let n=0;n{let t=[],s=[];for(let i=0;i{let t=0;for(let s=0;s{let t=e.dataType,s=e.dims.length,i=Wd(s,r),n=Wp(e.dims,i),o=e.dims,a=n,l=s<2||Hp(i,e.dims),u;if(l)return u=_=>{let E=$e("input",t,o,4),A=tt("output",t,a,4);return` + ${_.registerUniform("output_size","u32").declareVariables(E,A)} + ${_.mainStart()} + ${_.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + output[global_idx] = input[global_idx]; + }`},{name:"TransposeCopy",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let _=Te.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:c}=Kp(e.dims,i),h=Te.areEqual(c,[2,3,1]),g=Te.areEqual(c,[3,1,2]);if(p.length===2||h||g){o=h?[p[0],p[1]*p[2]]:g?[p[0]*p[1],p[2]]:p,a=[o[1],o[0]];let _=16;return u=E=>{let A=$e("a",t,o.length),v=tt("output",t,a.length);return` + ${E.registerUniform("output_size","u32").declareVariables(A,v)} + var tile : array, ${_}>; + ${E.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] = ${A.getByIndices(`${A.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]) { + ${v.setByIndices(`${v.type.indices}(output_row, output_col)`,"tile[local_id.x][local_id.y]")} + } + }`},{name:"TransposeShared",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let E=Te.size(n);return{outputs:[{dims:n,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(a[1]/_),y:Math.ceil(a[0]/_)},programUniforms:[{type:12,data:E},...nt(o,a)]}},getShaderSource:u}}return u=_=>{let E=$e("a",t,o.length),A=tt("output",t,a.length);return` + ${_.registerUniform("output_size","u32").declareVariables(E,A)} + + ${Gp(i,s,E,A)} + + ${_.mainStart()} + ${_.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${A.offsetToIndices("global_idx")}; + let aIndices = perm(indices); + + ${A.setByOffset("global_idx",E.getByIndices("aIndices"))} + }`},{name:"Transpose",shaderCache:{hint:`${r}`,inputDependencies:["rank"]},getRunData:()=>{let _=Te.size(n);return{outputs:[{dims:n,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(_/64)},programUniforms:[{type:12,data:_},...nt(o,a)]}},getShaderSource:u}},qp=(e,r)=>{Up(e.inputs,r.perm),e.compute(Nr(e.inputs[0],r.perm))},Qp=e=>Dt({perm:e.perm})}),Xp,Jp,Yp,Zp,eh,th,rh,sh,nh,ih,is,oh,ah,lh,dh,uh,ch,ph,hh,fh,mh,mv=Ve(()=>{pt(),Mt(),Tt(),Kd(),Hs(),Xp={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"},Jp={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"},Yp={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},Zp={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},eh=(e,r)=>{let t=[];for(let s=r-e;s{let t=[],s=e.length;for(let n=0;ne[n]);return[t,i]},rh=(e,r)=>{let t=e.length+r.length,s=[],i=0;for(let n=0;n{for(let t=0;t{let t=[];if(!sh(e,r)){for(let s=0;st.push(s))}return t},ih=(e,r,t,s,i,n,o)=>{let a=t[0].dims,l=Te.size(n),u=Te.size(o),p=$e("_A",t[0].dataType,a),c=tt("output",i,n),h=64;l===1&&(h=256);let g=` + var aBestValues : array; + `,_=E=>` + ${E.registerUniform("reduceSize","u32").declareVariables(p,c)} + ${g} + fn DIV_CEIL(a : u32, b : u32) -> u32 { + return ((a - 1u) / b + 1u); + } + ${E.mainStart(h)} + + let outputIndex = global_idx / ${h}; + let offset = outputIndex * uniforms.reduceSize; + + var bestValue = f32(${Yp[s]}); + let Length = uniforms.reduceSize; + for (var k = local_idx; k < Length; k = k + ${h}) { + let candidate = f32(${p.getByOffset("offset + k")}); + bestValue = ${Xp[s]}; + } + aBestValues[local_idx] = bestValue; + workgroupBarrier(); + + var reduceSize = min(Length, ${h}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 = ${Jp[s]}; + aBestValues[local_idx] = bestValue; + } + reduceSize = interval; + workgroupBarrier(); + } + + if (local_idx == 0u) { + ${c.setByOffset("outputIndex",`${s==="mean"?`${c.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${c.type.storage}(${Zp[s]})`}`)}; + } + }`;return{name:e,shaderCache:{hint:`${r};${h}`,inputDependencies:["type"]},getShaderSource:_,getRunData:()=>({outputs:[{dims:n,dataType:i}],dispatchGroup:{x:l},programUniforms:[{type:12,data:u}]})}},is=(e,r,t,s)=>{let i=e.inputs.length===1?t:Gd(e.inputs,t),n=i.axes;n.length===0&&!i.noopWithEmptyAxes&&(n=e.inputs[0].dims.map((g,_)=>_));let o=Te.normalizeAxes(n,e.inputs[0].dims.length),a=o,l=e.inputs[0],u=nh(a,e.inputs[0].dims.length);u.length>0&&(l=e.compute(Nr(e.inputs[0],u),{inputs:[0],outputs:[-1]})[0],a=eh(a.length,l.dims.length));let[p,c]=th(l.dims,a),h=p;i.keepDims&&(h=rh(p,o)),e.compute(ih(r,i.cacheKey,[l],s,e.inputs[0].dataType,h,c),{inputs:[l]})},oh=(e,r)=>{is(e,"ReduceMeanShared",r,"mean")},ah=(e,r)=>{is(e,"ReduceL1Shared",r,"l1")},lh=(e,r)=>{is(e,"ReduceL2Shared",r,"l2")},dh=(e,r)=>{is(e,"ReduceLogSumExpShared",r,"logSumExp")},uh=(e,r)=>{is(e,"ReduceMaxShared",r,"max")},ch=(e,r)=>{is(e,"ReduceMinShared",r,"min")},ph=(e,r)=>{is(e,"ReduceProdShared",r,"prod")},hh=(e,r)=>{is(e,"ReduceSumShared",r,"sum")},fh=(e,r)=>{is(e,"ReduceSumSquareShared",r,"sumSquare")},mh=(e,r)=>{is(e,"ReduceLogSumShared",r,"logSum")}}),os,_h,xa,Gd,as,gh,wh,yh,Mh,bh,vh,Th,xh,Eh,Ph,ls,Ch,Sh,$h,kh,Ih,Ah,Fh,Oh,Dh,Lh,Kd=Ve(()=>{pt(),Mt(),Yt(),Tt(),mv(),os=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.")},_h=e=>["","",`var value = ${e.getByIndices("input_indices")};`,""],xa=(e,r,t,s,i,n,o=!1,a=!1)=>{let l=[],u=t[0].dims,p=u.length,c=Te.normalizeAxes(i,p),h=!a&&c.length===0;u.forEach((E,A)=>{h||c.indexOf(A)>=0?o&&l.push(1):l.push(E)});let g=l.length,_=Te.size(l);return{name:e,shaderCache:r,getShaderSource:E=>{let A=[],v=$e("_A",t[0].dataType,p),y=tt("output",n,g),k=s(v,y,c),P=k[2];for(let M=0,w=0;M=0?(o&&w++,P=`for(var j${M}: u32 = 0; j${M} < ${u[M]}; j${M}++) { + ${k[2].includes("last_index")?`let last_index = j${M};`:""} + ${v.indicesSet("input_indices",M,`j${M}`)} + ${P} + }`):(A.push(`${v.indicesSet("input_indices",M,y.indicesGet("output_indices",w))};`),w++);return` + + ${E.registerUniform("output_size","u32").declareVariables(v,y)} + + ${E.mainStart()} + ${E.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + var input_indices: ${v.type.indices}; + let output_indices = ${y.offsetToIndices("global_idx")}; + + ${A.join(` +`)} + ${k[0]} // init ops for reduce max/min + ${k[1]} + ${P} + ${k[3]} + ${k.length===4?y.setByOffset("global_idx","value"):k.slice(4).join(` +`)} + }`},getRunData:()=>({outputs:[{dims:l,dataType:n}],dispatchGroup:{x:Math.ceil(_/64)},programUniforms:[{type:12,data:_},...nt(u,l)]})}},Gd=(e,r)=>{let t=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach(s=>t.push(Number(s))),Dt({axes:t,keepDims:r.keepDims,noopWithEmptyAxes:r.noopWithEmptyAxes})},as=(e,r,t,s)=>{let i=e.inputs,n=i.length===1?t:Gd(i,t);e.compute(xa(r,{hint:n.cacheKey,inputDependencies:["rank"]},[i[0]],n.noopWithEmptyAxes&&n.axes.length===0?_h:s,n.axes,i[0].dataType,n.keepDims,n.noopWithEmptyAxes),{inputs:[0]})},gh=(e,r)=>{os(e.inputs),as(e,"ReduceLogSum",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += ${t.getByIndices("input_indices")};`,"value = log(value);"])},wh=(e,r)=>{os(e.inputs),as(e,"ReduceL1",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += abs(${t.getByIndices("input_indices")});`,""])},yh=(e,r)=>{os(e.inputs),as(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);"])},Mh=(e,r)=>{os(e.inputs),as(e,"ReduceLogSumExp",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += exp(${t.getByIndices("input_indices")});`,"value = log(value);"])},bh=(e,r)=>{os(e.inputs),as(e,"ReduceMax",r,(t,s,i)=>{let n=[];for(let o=0;o=0||i.length===0)&&n.push(t.indicesSet("input_indices",o,0));return[`${n.join(` +`)}`,`var value = ${t.getByIndices("input_indices")};`,`value = max(value, ${t.getByIndices("input_indices")});`,""]})},vh=(e,r)=>{os(e.inputs),as(e,"ReduceMean",r,(t,s,i)=>{let n=1;for(let o=0;o=0||i.length===0)&&(n*=e.inputs[0].dims[o]);return["var sum = f32(0);","",`sum += f32(${t.getByIndices("input_indices")});`,`let value = ${s.type.value}(sum / ${n});`]})},Th=(e,r)=>{os(e.inputs),as(e,"ReduceMin",r,(t,s,i)=>{let n=[];for(let o=0;o=0||i.length===0)&&n.push(`input_indices[${o}] = 0;`);return[`${n.join(` +`)}`,`var value = ${t.getByIndices("input_indices")};`,`value = min(value, ${t.getByIndices("input_indices")});`,""]})},xh=(e,r)=>{os(e.inputs),as(e,"ReduceProd",r,(t,s)=>[`var value = ${s.type.storage}(1);`,"",`value *= ${t.getByIndices("input_indices")};`,""])},Eh=(e,r)=>{os(e.inputs),as(e,"ReduceSum",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += ${t.getByIndices("input_indices")};`,""])},Ph=(e,r)=>{os(e.inputs),as(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;`,""])},ls=(e,r,t)=>{if(r.length===0)return t;let s=1,i=1;for(let n=0;n1024},Ch=(e,r)=>{ls(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?vh(e,r):oh(e,r)},Sh=(e,r)=>{ls(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?wh(e,r):ah(e,r)},$h=(e,r)=>{ls(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?yh(e,r):lh(e,r)},kh=(e,r)=>{ls(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Mh(e,r):dh(e,r)},Ih=(e,r)=>{ls(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?bh(e,r):uh(e,r)},Ah=(e,r)=>{ls(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Th(e,r):ch(e,r)},Fh=(e,r)=>{ls(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?xh(e,r):ph(e,r)},Oh=(e,r)=>{ls(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Eh(e,r):hh(e,r)},Dh=(e,r)=>{ls(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Ph(e,r):fh(e,r)},Lh=(e,r)=>{ls(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?gh(e,r):mh(e,r)}}),Hd,zh,Bh,qd,_v=Ve(()=>{pt(),Yt(),Kd(),Hd=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.")},zh=(e,r)=>{Hd(e.inputs);let t=(s,i,n)=>{let o=[];for(let a=0;a=0||n.length===0)&&o.push(`input_indices[${a}] = 0;`);return[`${o.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); + }`,"",i.setByOffset("global_idx","best_index")]};e.compute(xa("ArgMin",{hint:r.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],t,[r.axis],7,r.keepDims),{inputs:[0]})},Bh=(e,r)=>{Hd(e.inputs);let t=(s,i,n)=>{let o=[];for(let a=0;a=0||n.length===0)&&o.push(`input_indices[${a}] = 0;`);return[`${o.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); + }`,"",i.setByOffset("global_idx","best_index")]};e.compute(xa("argMax",{hint:r.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],t,[r.axis],7,r.keepDims),{inputs:[0]})},qd=e=>Dt(e)}),Rh,Ea,Nh,jh,Vh,Fi,Uh,Wh,Qd=Ve(()=>{pt(),Mt(),Bd(),Tt(),Rh=(e,r)=>{let t=e[0],s=e[1],i=e[2],n=e[3],o=e[4],a=e[5];if(o&&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(i.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(i.dims[0]!==s.dims[1])throw new Error('Input "bias" dimension 0 should have same length as dimension 1 of input "weights"');let c=i.dims[0]/3,h=c,g=h;if(r.qkvHiddenSizes.length>0){if(r.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let k of r.qkvHiddenSizes)if(k%r.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");c=r.qkvHiddenSizes[0],h=r.qkvHiddenSizes[1],g=r.qkvHiddenSizes[2]}let _=u;if(c!==h)throw new Error("qkv_hidden_sizes first element should be same as the second");if(i.dims[0]!==c+h+g)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let E=0;if(o){if(h!==g)throw new Error('Input "past" expect k_hidden_size == v_hidden_size');if(o.dims.length!==5)throw new Error('Input "past" must have 5 dimensions');if(o.dims[0]!==2)throw new Error('Input "past" first dimension must be 2');if(o.dims[1]!==l)throw new Error('Input "past" second dimension must be batch_size');if(o.dims[2]!==r.numHeads)throw new Error('Input "past" third dimension must be num_heads');if(o.dims[4]!==h/r.numHeads)throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads');r.pastPresentShareBuffer||(E=o.dims[3])}let A=_+E,v=-1,y=0;if(n)throw new Error("Mask not supported");if(o)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]!==A)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:l,sequenceLength:u,pastSequenceLength:E,kvSequenceLength:_,totalSequenceLength:A,maxSequenceLength:v,inputHiddenSize:p,hiddenSize:c,vHiddenSize:g,headSize:Math.floor(c/r.numHeads),vHeadSize:Math.floor(g/r.numHeads),numHeads:r.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:r.maskFilterValue,maskType:y,scale:r.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},Ea=(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; + `,Nh=(e,r,t,s,i,n,o,a)=>{let l=Xt(o?1:n),u=64,p=n/l;p{let y=tt("x",e.dataType,e.dims,l),k=[y],P=o?$e("seq_lens",o.dataType,o.dims):void 0;P&&k.push(P);let M=a?$e("total_sequence_length_input",a.dataType,a.dims):void 0;M&&k.push(M);let w=xr(e.dataType),x=[{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; + ${v.registerUniforms(x).declareVariables(...k)} + ${v.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; + ${Ea(P,M,!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 = ${o?"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] = ${y.type.value}(${w}(1.0) / ${w}(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] = ${y.type.value}(exp(f32input - max_value) / sum); + } + } + ${o?` + 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] = ${y.type.value}(${w}(0)); + }`:""}; + }`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${u};${g};${l}`,inputDependencies:E},getShaderSource:A,getRunData:()=>({outputs:[],dispatchGroup:{x:1,y:i,z:r*t},programUniforms:h})}},jh=(e,r,t,s,i,n,o,a,l)=>{let u=o+n.kvSequenceLength,p=[n.batchSize,n.numHeads,n.sequenceLength,u],c=e>1&&s,h=n.kvNumHeads?n.kvNumHeads:n.numHeads,g=c?[n.batchSize,h,u,n.headSize]:void 0,_=n.nReps?n.nReps:1,E=n.scale===0?1/Math.sqrt(n.headSize):n.scale,A=Xt(n.headSize),v=n.headSize/A,y=12,k={x:Math.ceil(u/y),y:Math.ceil(n.sequenceLength/y),z:n.batchSize*n.numHeads},P=[{type:12,data:n.sequenceLength},{type:12,data:v},{type:12,data:u},{type:12,data:n.numHeads},{type:12,data:n.headSize},{type:1,data:E},{type:12,data:o},{type:12,data:n.kvSequenceLength},{type:12,data:_}],M=c&&s&&Te.size(s.dims)>0,w=["type","type"];M&&w.push("type"),i&&w.push("type"),a&&w.push("type"),l&&w.push("type");let x=[{dims:p,dataType:r.dataType,gpuDataType:0}];c&&x.push({dims:g,dataType:r.dataType,gpuDataType:0});let $=z=>{let R=$e("q",r.dataType,r.dims,A),Q=$e("key",t.dataType,t.dims,A),q=[R,Q];if(M){let ue=$e("past_key",s.dataType,s.dims,A);q.push(ue)}i&&q.push($e("attention_bias",i.dataType,i.dims));let U=a?$e("seq_lens",a.dataType,a.dims):void 0;U&&q.push(U);let Z=l?$e("total_sequence_length_input",l.dataType,l.dims):void 0;Z&&q.push(Z);let H=tt("output",r.dataType,p),J=[H];c&&J.push(tt("present_key",r.dataType,g,A));let ie=xr(1,A),ae=[{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 = ${y}u; + + var tileQ: array<${R.type.storage}, ${y*y}>; + var tileK: array<${R.type.storage}, ${y*y}>; + ${z.registerUniforms(ae).declareVariables(...q,...J)} + ${z.mainStart([y,y,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; + ${Ea(U,Z,!0)} + let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx; + let qOffset = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K; + ${M&&c?"let pastKeyOffset = absKvHeadIdx * uniforms.past_sequence_length * uniforms.K;":""}; + let kOffset = absKvHeadIdx * uniforms.kv_sequence_length * uniforms.K; + ${c?"let presentKeyOffset = absKvHeadIdx * uniforms.N * uniforms.K;":""} + var value = ${ie}(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; + ${M&&c?` + 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]; + }`} + ${c?`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 += ${ie}(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(A){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: ${A}`)}})()}; + output[outputIdx] = ${H.type.value} (sum * uniforms.alpha) + ${i?"attention_bias[outputIdx]":"0.0"}; + } + }`};return{name:"AttentionProbs",shaderCache:{hint:`${A};${i!==void 0};${s!==void 0};${e}`,inputDependencies:w},getRunData:()=>({outputs:x,dispatchGroup:k,programUniforms:P}),getShaderSource:$}},Vh=(e,r,t,s,i,n,o=void 0,a=void 0)=>{let l=n+i.kvSequenceLength,u=i.nReps?i.nReps:1,p=i.vHiddenSize*u,c=e>1&&s,h=i.kvNumHeads?i.kvNumHeads:i.numHeads,g=c?[i.batchSize,h,l,i.headSize]:void 0,_=[i.batchSize,i.sequenceLength,p],E=12,A={x:Math.ceil(i.vHeadSize/E),y:Math.ceil(i.sequenceLength/E),z:i.batchSize*i.numHeads},v=[{type:12,data:i.sequenceLength},{type:12,data:l},{type:12,data:i.vHeadSize},{type:12,data:i.numHeads},{type:12,data:i.headSize},{type:12,data:p},{type:12,data:n},{type:12,data:i.kvSequenceLength},{type:12,data:u}],y=c&&s&&Te.size(s.dims)>0,k=["type","type"];y&&k.push("type"),o&&k.push("type"),a&&k.push("type");let P=[{dims:_,dataType:r.dataType,gpuDataType:0}];c&&P.push({dims:g,dataType:r.dataType,gpuDataType:0});let M=w=>{let x=$e("probs",r.dataType,r.dims),$=$e("v",t.dataType,t.dims),z=[x,$];y&&z.push($e("past_value",s.dataType,s.dims));let R=o?$e("seq_lens",o.dataType,o.dims):void 0;o&&z.push(R);let Q=a?$e("total_sequence_length_input",a.dataType,a.dims):void 0;a&&z.push(Q);let q=[tt("output",r.dataType,_)];c&&q.push(tt("present_value",r.dataType,g));let U=[{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 = ${E}u; + var tileQ: array<${x.type.value}, ${E*E}>; + var tileV: array<${x.type.value}, ${E*E}>; + ${w.registerUniforms(U).declareVariables(...z,...q)} + ${w.mainStart([E,E,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; + ${Ea(R,Q,!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 + ${y&&c?"let pastValueOffset = absKvHeadIdx * uniforms.N * uniforms.past_sequence_length + n;":""}; + let vOffset = absKvHeadIdx * uniforms.N * uniforms.kv_sequence_length + n; + ${c?"let presentValueOffset = absKvHeadIdx * uniforms.N * uniforms.K + n;":""} + var value = ${x.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; + ${y&&c?` + 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]; + }`} + ${c?` + 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:k},getRunData:()=>({outputs:P,dispatchGroup:A,programUniforms:v}),getShaderSource:M}},Fi=(e,r,t,s,i,n,o,a,l,u,p=void 0,c=void 0)=>{let h=Math.min(e.outputCount,1+(o?1:0)+(a?1:0)),g=h>1?u.pastSequenceLength:0,_=g+u.kvSequenceLength,E=l&&Te.size(l.dims)>0?l:void 0,A=[r,t];h>1&&o&&Te.size(o.dims)>0&&A.push(o),E&&A.push(E),p&&A.push(p),c&&A.push(c);let v=e.compute(jh(h,r,t,o,E,u,g,p,c),{inputs:A,outputs:h>1?[-1,1]:[-1]})[0];e.compute(Nh(v,u.batchSize,u.numHeads,g,u.sequenceLength,_,p,c),{inputs:p&&c?[v,p,c]:[v],outputs:[]});let y=[v,s];h>1&&a&&Te.size(a.dims)>0&&y.push(a),p&&y.push(p),c&&y.push(c),e.compute(Vh(h,v,s,a,u,g,p,c),{inputs:y,outputs:h>1?[0,2]:[0]})},Uh=(e,r)=>{let t=[r.batchSize,r.numHeads,r.sequenceLength,r.headSize],s=r.sequenceLength,i=r.inputHiddenSize,n=r.headSize,o=12,a={x:Math.ceil(r.headSize/o),y:Math.ceil(r.sequenceLength/o),z:r.batchSize*r.numHeads},l=[e.inputs[0],e.inputs[1],e.inputs[2]],u=[{type:12,data:s},{type:12,data:i},{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=c=>{let h=tt("output_q",l[0].dataType,t),g=tt("output_k",l[0].dataType,t),_=tt("output_v",l[0].dataType,t),E=$e("input",l[0].dataType,l[0].dims),A=$e("weight",l[1].dataType,l[1].dims),v=$e("bias",l[2].dataType,l[2].dims),y=E.type.storage,k=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"hidden_size",type:"u32"},{name:"ldb",type:"u32"}];return` + const TILE_SIZE = ${o}u; + var tileInput: array<${y}, ${o*o}>; + var tileWeightQ: array<${y}, ${o*o}>; + var tileWeightK: array<${y}, ${o*o}>; + var tileWeightV: array<${y}, ${o*o}>; + ${c.registerUniforms(k).declareVariables(E,A,v,h,g,_)} + ${c.mainStart([o,o,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 = ${y}(0); + var valueK = ${y}(0); + var valueV = ${y}(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]})},Wh=(e,r)=>{let t=Rh(e.inputs,r),[s,i,n]=Uh(e,t);return Fi(e,s,i,n,e.inputs[4],void 0,void 0,void 0,e.inputs[5],t)}}),Gh,Kh,Hh,qh,gv=Ve(()=>{ns(),pt(),Mt(),Yt(),Tt(),Gh=(e,r)=>{if(!e||e.length!==5)throw new Error("BatchNormalization requires 5 inputs");let t=(s,i,n)=>{let o=i.length;if(o!==s.length)throw new Error(`${n}: num dimensions != ${o}`);i.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")},Kh=(e,r)=>{let{epsilon:t,spatial:s,format:i}=r,n=e[0].dims,o=s?Xt(n[n.length-1]):1,a=i==="NHWC"&&n.length>1?o:1,l=Te.size(n)/o,u=s,p=u?n.length:n,c=$e("x",e[0].dataType,e[0].dims,o),h=$e("scale",e[1].dataType,e[1].dims,a),g=$e("bias",e[2].dataType,e[2].dims,a),_=$e("inputMean",e[3].dataType,e[3].dims,a),E=$e("inputVar",e[4].dataType,e[4].dims,a),A=tt("y",e[0].dataType,p,o),v=()=>{let k="";if(s)k=`let cOffset = ${n.length===1?"0u":i==="NHWC"?`outputIndices[${n.length-1}] / ${o}`:"outputIndices[1]"};`;else if(i==="NCHW")k=` + ${A.indicesSet("outputIndices","0","0")} + let cOffset = ${A.indicesToOffset("outputIndices")};`;else{k=`var cIndices = ${h.type.indices}(0); + cIndices[0] = outputIndices[${n.length-1}];`;for(let P=1;P` + const epsilon = ${t}; + ${k.registerUniform("outputSize","u32").declareVariables(c,h,g,_,E,A)} + ${k.mainStart()} + ${k.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var outputIndices = ${A.offsetToIndices(`global_idx * ${o}`)}; + ${v()} + let scale = ${h.getByOffset("cOffset")}; + let bias = ${g.getByOffset("cOffset")}; + let inputMean = ${_.getByOffset("cOffset")}; + let inputVar = ${E.getByOffset("cOffset")}; + let x = ${c.getByOffset("global_idx")}; + let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias; + ${A.setByOffset("global_idx","value")} + }`;return{name:"BatchNormalization",shaderCache:{hint:`${r.epsilon}_${r.format}_${s}_${o}`,inputDependencies:u?["rank","type","type","type","type"]:void 0},getShaderSource:y,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:u?[{type:12,data:l},...nt(n)]:[{type:12,data:l}]})}},Hh=e=>Dt(e),qh=(e,r)=>{let{inputs:t,outputCount:s}=e,i=Hh({...r,outputCount:s});if(Ut.webgpu.validateInputContent&&Gh(t,i),r.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");e.compute(Kh(t,i))}}),Qh,Xh,Jh,wv=Ve(()=>{Mt(),Tt(),Qh=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")},Xh=e=>{let r=e[0].dims,t=e[0].dims[2],s=Te.size(r)/4,i=e[0].dataType,n=$e("input",i,r,4),o=$e("bias",i,[t],4),a=$e("residual",i,r,4),l=tt("output",i,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,o,a,l)} + + ${u.mainStart()} + ${u.guardAgainstOutOfBoundsWorkgroupSizes(s)} + let value = ${n.getByOffset("global_idx")} + + ${o.getByOffset("global_idx % channels")} + ${a.getByOffset("global_idx")}; + ${l.setByOffset("global_idx","value")} + }`}},Jh=e=>{Qh(e.inputs),e.compute(Xh(e.inputs))}}),Yh,$t,Zh,ef,tf,rf,sf,nf,of,af,lf,df,uf,cf,pf,hf,Oi,ff,Pa,mf,_f,gf,wf,yf,Mf,bf,vf,Tf,xf,Ef,Pf,Cf,Sf,$f,kf,Xd,If,Jd,Yd,Af,Ff,Of,Df,Lf,zf,Zd=Ve(()=>{pt(),Mt(),Yt(),Tt(),Yh=(e,r,t,s,i,n,o)=>{let a=Math.ceil(r/4),l="";typeof i=="string"?l=`${i}(a)`:l=i("a");let u=$e("inputData",t,[a],4),p=tt("outputData",s,[a],4),c=[{name:"vec_size",type:"u32"}];return o&&c.push(...o),` + ${e.registerUniforms(c).declareVariables(u,p)} + + ${n??""} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + + let a = ${u.getByOffset("global_idx")}; + ${p.setByOffset("global_idx",l)} + }`},$t=(e,r,t,s,i,n=e.dataType,o,a)=>{let l=[{type:12,data:Math.ceil(Te.size(e.dims)/4)}];return o&&l.push(...o),{name:r,shaderCache:{hint:i,inputDependencies:["type"]},getShaderSource:u=>Yh(u,Te.size(e.dims),e.dataType,n,t,s,a),getRunData:u=>({outputs:[{dims:e.dims,dataType:n}],dispatchGroup:{x:Math.ceil(Te.size(u[0].dims)/64/4)},programUniforms:l})}},Zh=e=>{e.compute($t(e.inputs[0],"Abs","abs"))},ef=e=>{e.compute($t(e.inputs[0],"Acos","acos"))},tf=e=>{e.compute($t(e.inputs[0],"Acosh","acosh"))},rf=e=>{e.compute($t(e.inputs[0],"Asin","asin"))},sf=e=>{e.compute($t(e.inputs[0],"Asinh","asinh"))},nf=e=>{e.compute($t(e.inputs[0],"Atan","atan"))},of=e=>{e.compute($t(e.inputs[0],"Atanh","atanh"))},af=e=>Dt(e),lf=(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($t(e.inputs[0],"Cast",t,void 0,r.cacheKey,r.to))},df=e=>{let r,t,s=e.length>=2&&e[1].data!==0,i=e.length>=3&&e[2].data!==0;switch(e[0].dataType){case 1:r=s?e[1].getFloat32Array()[0]:-34028234663852886e22,t=i?e[2].getFloat32Array()[0]:34028234663852886e22;break;case 10:r=s?e[1].getUint16Array()[0]:64511,t=i?e[2].getUint16Array()[0]:31743;break;default:throw new Error("Unsupport data type")}return Dt({min:r,max:t})},uf=(e,r)=>{let t=r||df(e.inputs),s=xr(e.inputs[0].dataType);e.compute($t(e.inputs[0],"Clip",i=>`clamp(${i}, 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]})},cf=e=>{e.compute($t(e.inputs[0],"Ceil","ceil"))},pf=e=>{e.compute($t(e.inputs[0],"Cos","cos"))},hf=e=>{e.compute($t(e.inputs[0],"Cosh","cosh"))},Oi=e=>Dt(e),ff=(e,r)=>{let t=xr(e.inputs[0].dataType);e.compute($t(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))},Pa=(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)); +}`,mf=e=>{let r=xr(e.inputs[0].dataType);e.compute($t(e.inputs[0],"Erf",t=>`erf_vf32(${t})`,Pa(r)))},_f=e=>{e.compute($t(e.inputs[0],"Exp","exp"))},gf=e=>{e.compute($t(e.inputs[0],"Floor","floor"))},wf=e=>{let r=xr(e.inputs[0].dataType);e.compute($t(e.inputs[0],"Gelu",t=>`0.5 * ${t} * (1.0 + erf_vf32(${t} * 0.7071067811865475))`,Pa(r)))},yf=(e,r)=>{let t=xr(e.inputs[0].dataType);e.compute($t(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))},Mf=e=>{e.compute($t(e.inputs[0],"Not",r=>`!${r}`))},bf=e=>{e.compute($t(e.inputs[0],"Neg",r=>`-${r}`))},vf=e=>{e.compute($t(e.inputs[0],"Reciprocal",r=>`1.0/${r}`))},Tf=e=>{let r=xr(e.inputs[0].dataType);e.compute($t(e.inputs[0],"Relu",t=>`select(vec4<${r}>(0.0), ${t}, ${t} > vec4<${r}>(0.0))`))},xf=e=>{e.compute($t(e.inputs[0],"Sigmoid",r=>`(1.0 / (1.0 + exp(-${r})))`))},Ef=e=>Dt(e),Pf=(e,r)=>{let t=xr(e.inputs[0].dataType);e.compute($t(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))},Cf=e=>{e.compute($t(e.inputs[0],"Sin","sin"))},Sf=e=>{e.compute($t(e.inputs[0],"Sinh","sinh"))},$f=e=>{e.compute($t(e.inputs[0],"Sqrt","sqrt"))},kf=e=>{e.compute($t(e.inputs[0],"Tan","tan"))},Xd=e=>`sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`,If=e=>{e.compute($t(e.inputs[0],"Tanh",Xd))},Jd=(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 ${Xd("v")}; +} +`,Yd=e=>`(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`,Af=e=>{let r=xr(e.inputs[0].dataType);e.compute($t(e.inputs[0],"FastGelu",Yd,Jd(r),void 0,e.inputs[0].dataType))},Ff=(e,r)=>{let t=xr(e.inputs[0].dataType);return e.compute($t(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},Of=e=>{e.compute($t(e.inputs[0],"Log","log"))},Df=(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; +} +`,Lf=e=>`quick_gelu_impl(${e})`,zf=(e,r)=>{let t=xr(e.inputs[0].dataType);e.compute($t(e.inputs[0],"QuickGelu",Lf,Df(t,r.alpha),r.cacheKey,e.inputs[0].dataType))}}),Bf,Rf,Nf,yv=Ve(()=>{Mt(),Tt(),Zd(),Bf=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")},Rf=e=>{let r=e[0].dims.slice();r[2]=r[2]/2;let t=$e("input",e[0].dataType,e[0].dims,4),s=$e("bias",e[0].dataType,[e[0].dims[2]],4),i=tt("output",e[0].dataType,r,4),n=Te.size(r)/4,o=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,i)} + + ${Pa(o)} + + ${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); + + ${i.setByOffset("global_idx","valueLeft * geluRight")} + }`}},Nf=e=>{Bf(e.inputs),e.compute(Rf(e.inputs))}}),jf,Vf,ds,Uf,Wf,Gf,Kf,Hf,qf,Qf,Xf,Jf,Yf,Mv=Ve(()=>{pt(),Mt(),Tt(),jf=(e,r,t,s,i,n,o,a,l,u,p,c)=>{let h,g;typeof a=="string"?h=g=(y,k)=>`${a}((${y}),(${k}))`:typeof a=="function"?h=g=a:(h=a.scalar,g=a.vector);let _=tt("outputData",p,s.length,4),E=$e("aData",l,r.length,4),A=$e("bData",u,t.length,4),v;if(i)if(n){let y=Te.size(r)===1,k=Te.size(t)===1,P=r.length>0&&r[r.length-1]%4===0,M=t.length>0&&t[t.length-1]%4===0;y||k?v=_.setByOffset("global_idx",g(y?`${E.type.value}(${E.getByOffset("0")}.x)`:E.getByOffset("global_idx"),k?`${A.type.value}(${A.getByOffset("0")}.x)`:A.getByOffset("global_idx"))):v=` + let outputIndices = ${_.offsetToIndices("global_idx * 4u")}; + let offsetA = ${E.broadcastedIndicesToOffset("outputIndices",_)}; + let offsetB = ${A.broadcastedIndicesToOffset("outputIndices",_)}; + ${_.setByOffset("global_idx",g(o||P?E.getByOffset("offsetA / 4u"):`${E.type.value}(${E.getByOffset("offsetA / 4u")}[offsetA % 4u])`,o||M?A.getByOffset("offsetB / 4u"):`${A.type.value}(${A.getByOffset("offsetB / 4u")}[offsetB % 4u])`))} + `}else v=_.setByOffset("global_idx",g(E.getByOffset("global_idx"),A.getByOffset("global_idx")));else{if(!n)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let y=(k,P,M="")=>{let w=`aData[indexA${P}][componentA${P}]`,x=`bData[indexB${P}][componentB${P}]`;return` + let outputIndices${P} = ${_.offsetToIndices(`global_idx * 4u + ${P}u`)}; + let offsetA${P} = ${E.broadcastedIndicesToOffset(`outputIndices${P}`,_)}; + let offsetB${P} = ${A.broadcastedIndicesToOffset(`outputIndices${P}`,_)}; + let indexA${P} = offsetA${P} / 4u; + let indexB${P} = offsetB${P} / 4u; + let componentA${P} = offsetA${P} % 4u; + let componentB${P} = offsetB${P} % 4u; + ${k}[${P}] = ${M}(${h(w,x)}); + `};p===9?v=` + var data = vec4(0); + ${y("data",0,"u32")} + ${y("data",1,"u32")} + ${y("data",2,"u32")} + ${y("data",3,"u32")} + outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:v=` + ${y("outputData[global_idx]",0)} + ${y("outputData[global_idx]",1)} + ${y("outputData[global_idx]",2)} + ${y("outputData[global_idx]",3)} + `}return` + ${e.registerUniform("vec_size","u32").declareVariables(E,A,_)} + + ${c??""} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${v} + }`},Vf=(e,r,t,s,i,n,o=t.dataType)=>{let a=t.dims.map(E=>Number(E)??1),l=s.dims.map(E=>Number(E)??1),u=!Te.areEqual(a,l),p=a,c=Te.size(a),h=!1,g=!1,_=[u];if(u){let E=Nn.calcShape(a,l,!1);if(!E)throw new Error("Can't perform binary op on the given tensors");p=E.slice(),c=Te.size(p);let A=Te.size(a)===1,v=Te.size(l)===1,y=a.length>0&&a[a.length-1]%4===0,k=l.length>0&&l[l.length-1]%4===0;_.push(A),_.push(v),_.push(y),_.push(k);let P=1;for(let M=1;ME.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:E=>jf(E,a,l,p,h,u,g,i,t.dataType,s.dataType,o,n),getRunData:()=>({outputs:[{dims:p,dataType:o}],dispatchGroup:{x:Math.ceil(c/64/4)},programUniforms:[{type:12,data:Math.ceil(Te.size(p)/4)},...nt(a,l,p)]})}},ds=(e,r,t,s,i,n)=>{e.compute(Vf(r,i??"",e.inputs[0],e.inputs[1],t,s,n))},Uf=e=>{ds(e,"Add",(r,t)=>`${r}+${t}`)},Wf=e=>{ds(e,"Div",(r,t)=>`${r}/${t}`)},Gf=e=>{ds(e,"Equal",{scalar:(r,t)=>`u32(${r}==${t})`,vector:(r,t)=>`vec4(${r}==${t})`},void 0,void 0,9)},Kf=e=>{ds(e,"Mul",(r,t)=>`${r}*${t}`)},Hf=e=>{let r=$e("input",e.inputs[0].dataType,e.inputs[0].dims).type.value;ds(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)); + } + `)},qf=e=>{ds(e,"Sub",(r,t)=>`${r}-${t}`)},Qf=e=>{ds(e,"Greater",{scalar:(r,t)=>`u32(${r}>${t})`,vector:(r,t)=>`vec4(${r}>${t})`},void 0,void 0,9)},Xf=e=>{ds(e,"Less",{scalar:(r,t)=>`u32(${r}<${t})`,vector:(r,t)=>`vec4(${r}<${t})`},void 0,void 0,9)},Jf=e=>{ds(e,"GreaterOrEqual",{scalar:(r,t)=>`u32(${r}>=${t})`,vector:(r,t)=>`vec4(${r}>=${t})`},void 0,void 0,9)},Yf=e=>{ds(e,"LessOrEqual",{scalar:(r,t)=>`u32(${r}<=${t})`,vector:(r,t)=>`vec4(${r}<=${t})`},void 0,void 0,9)}}),Zf,em,tm,rm,sm,nm,bv=Ve(()=>{pt(),Mt(),Yt(),Tt(),Zf=(e,r)=>{if(!e||e.length<1)throw new Error("too few inputs");let t=0,s=e[t],i=s.dataType,n=s.dims.length;e.forEach((o,a)=>{if(a!==t){if(o.dataType!==i)throw new Error("input tensors should be one type");if(o.dims.length!==n)throw new Error("input tensors should have the same shape");o.dims.forEach((l,u)=>{if(u!==r&&l!==s.dims[u])throw new Error("non concat dimensions must match")})}})},em=(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; + }`,tm=(e,r)=>{let t=e.length,s=[];for(let i=0;i{let i=Te.size(t),n=new Array(e.length),o=new Array(e.length),a=0,l=[],u=[],p=[{type:12,data:i}];for(let E=0;E`uniforms.sizeInConcatAxis${E}`).join(","),_=E=>` + + ${(()=>{E.registerUniform("outputSize","u32");for(let A=0;A(${g}); + ${h} -= sizeInConcatAxis[inputIndex - 1u]; + } + + ${tm(o,c)} + }`;return{name:"Concat",shaderCache:{hint:`${r}`,inputDependencies:l},getRunData:()=>({outputs:[{dims:t,dataType:s}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:p}),getShaderSource:_}},sm=(e,r)=>{let t=e.inputs,s=t[0].dims,i=Te.normalizeAxis(r.axis,s.length);Zf(t,i);let n=s.slice();n[i]=t.reduce((a,l)=>a+(l.dims.length>i?l.dims[i]:0),0);let o=t.filter(a=>Te.size(a.dims)>0);e.compute(rm(o,i,n,t[0].dataType),{inputs:o})},nm=e=>Dt({axis:e.axis})}),gn,wn,yn,eu,Mn=Ve(()=>{pt(),Mt(),gn=(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}`)}},wn=(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})},yn=(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"})},eu=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)||[Bp,Rp];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}}}),hr,im,tu=Ve(()=>{hr=(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.`)}},im=e=>` + ${e?"value = value + getBiasByOutputCoords(coords);":""} + `}),om,vv=Ve(()=>{om=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)); +} +`}),Di,ru,su=Ve(()=>{pt(),Mt(),Tt(),Mn(),Di=(e,r,t,s,i)=>{let n=s-t;return` + ${Array.from({length:t}).map((o,a)=>` + if (${rt(r.shape,a,r.rank)} != 1) { + ${r.indicesSet(e,a,rt(i,a+n,s))} + } else { + ${r.indicesSet(e,a,0)} + }`).join("")} +`},ru=(e,r,t,s,i=!1,n)=>{let o=e[0].dims,a=e[1].dims,l=o[o.length-2],u=a[a.length-1],p=o[o.length-1],c=Xt(u),h=Xt(p),g=Xt(l),_=Te.size(t)/c/g,E=e.length>2,A=s?s.slice(0,-2):t.slice(0,-2),v=[Te.size(A),l,u],y=[{type:12,data:_},{type:12,data:l},{type:12,data:u},{type:12,data:p}];wn(r,y),y.push(...nt(A,o,a)),E&&y.push(...nt(e[2].dims)),y.push(...nt(v));let k=P=>{let M=Ud("batch_dims",e[0].dataType,A.length),w=$e("a",e[0].dataType,o.length,h),x=$e("b",e[1].dataType,a.length,c),$=tt("output",e[0].dataType,v.length,c),z=lr($.type.tensor),R=gn(r,$.type.value,z),Q=[w,x],q="";if(E){let H=i?c:1;Q.push($e("bias",e[2].dataType,e[2].dims.length,H)),q=`${i?`value += bias[col / ${H}];`:`value += ${$.type.value}(bias[row + i]);`}`}let U=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];yn(r,U);let Z=()=>{let H=`var a_data: ${w.type.value};`;for(let J=0;J; + for (var k: u32 = 0u; k < uniforms.K; k = k + ${h}) { + ${Z()} + } + for (var i = 0u; i < ${g}u; i++) { + var value = values[i]; + ${q} + ${R} + let cur_indices = ${$.type.indices}(batch, row + i, col); + let offset = ${$.indicesToOffset("cur_indices")}; + ${$.setByOffset(`offset / ${c}`,"value")}; + } + } + `};return{name:"MatMulNaive",shaderCache:{hint:`${r.activation};${c};${h};${g};${i}`,inputDependencies:E?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:n?n(t):t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(_/64)},programUniforms:y}),getShaderSource:k}}}),am,lm,nu,iu,dm,ou,um,Ca,au=Ve(()=>{pt(),Mt(),Tt(),Mn(),su(),tu(),am=(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":""}); + `,lm=(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];"} + }`,nu=(e,r,t="f32",s,i=!1,n=32,o=!1,a=32)=>{let l=r[1]*e[1],u=r[0]*e[0],p=i?l:n,c=i?n:l,h=p/r[0],g=n/r[1];if(!((i&&h===4&&e[1]===4||!i&&(h===3||h===4))&&p%r[0]===0&&n%r[1]===0&&e[0]===4))throw new Error(`If transposeA ${i} is true, innerElementSize ${h} and workPerThread[1] ${e[1]} must be 4. + Otherwise, innerElementSize ${h} 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/h}>, ${c}>; +var mm_Bsub: array, ${u/e[0]}>, ${n}>; + +const rowPerThread = ${e[1]}; +const colPerThread = ${e[0]}; +const innerElementSize = ${h}; +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 = ${o?"0":"i32(globalId.z)"}; + ${s?`let batchIndices = ${s.offsetToIndices("u32(batch)")};`:""} + let globalRowStart = i32(workgroupId.y) * ${l}; + + let num_tiles = ${o?`${Math.ceil(a/n)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; + var kStart = ${o?`i32(globalId.z) * ${a}`:"0"}; + + var acc: array, rowPerThread>; + + // Loop over shared dimension. + let tileRowB = localRow * ${g}; + 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; + ${am(i,s)} + } + + // Load one tile of B into local memory. + for (var innerRow = 0; innerRow < ${g}; 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]; + ${h===3?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"} + + ${lm(i,h)} + } + + workgroupBarrier(); + } + + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]); + } +}`},iu=(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":""}); + `,dm=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",ou=(e,r,t="f32",s,i=!1,n=32,o=!1,a=32,l=!1)=>{let u=e[1]*r[1],p=e[0]*r[0],c=i?u:n,h=i?n:u;if(!(h%r[1]===0&&c%r[0]===0&&n%r[1]===0))throw new Error(`tileAHight ${h} must be divisible by workgroupSize[1]${r[1]}, tileAWidth ${c} must be divisible by workgroupSize[0]${r[0]}, tileInner ${n} must be divisible by workgroupSize[1]${r[1]}`);let g=h/r[1],_=c/r[0],E=n/r[1],A=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 < ${h}; inputRow = inputRow + ${r[1]}) { + for (var inputCol = localCol; inputCol < ${c}; inputCol = inputCol + ${r[0]}) { + ${iu(i,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 = ${i?`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) * ${g}; +let tileColA = i32(localId.x) * ${_}; +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 < ${g}; innerRow = innerRow + 1) { + for (var innerCol = 0; innerCol < ${_}; innerCol = innerCol + 1) { + let inputRow = tileRowA + innerRow; + let inputCol = tileColA + innerCol; + ${iu(i,s)} + } + } + + // 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${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) { + ${dm(i)} + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol]; + } + } + } + + workgroupBarrier(); +} + +for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + mm_write(batch, globalRow + innerRow, globalCol + innerCol, + acc[innerRow][innerCol]); + } +} +`;return` + var mm_Asub : array, ${h}>; + 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 = ${o?"0":"i32(globalId.z)"}; + ${s?`let batchIndices = ${s.offsetToIndices("u32(batch)")};`:""} + let num_tiles = ${o?`${Math.ceil(a/n)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; + var kStart = ${o?`i32(globalId.z) * ${a}`:"0"}; + + var acc : array, rowPerThread>; + ${A} + } +`},um=(e,r,t,s,i=!1)=>{let[n,o,a,l]=s,u=lr(s[0].type.tensor);return` + fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${n.type.indices}) -> ${hr(e,u)} { + var value = ${hr(e,u)}(0.0); + let col = colIn * ${e}; + if(row < uniforms.dim_a_outer && col < uniforms.dim_inner) + { + var aIndices: ${o.type.indices}; + ${Di("aIndices",o,o.rank-2,n.rank,"batchIndices")} + ${o.indicesSet("aIndices",o.rank-2,"u32(row)")} + ${o.indicesSet("aIndices",o.rank-1,"u32(colIn)")} + value = ${o.getByIndices("aIndices")}; + } + return value; + } + + fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${n.type.indices}) -> ${hr(e,u)} { + var value = ${hr(e,u)}(0.0); + let col = colIn * ${e}; + if(row < uniforms.dim_inner && col < uniforms.dim_b_outer) + { + var bIndices: ${a.type.indices}; + ${Di("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: ${hr(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 + ${i?"bias[colIn]":`${hr(e,u)}(bias[row])`};`:""} + ${t} + ${l.setByIndices("vec3(coords)","value")} + } + } + `},Ca=(e,r,t,s,i=!1,n)=>{let o=e[0].dims,a=e[1].dims,l=o.slice(0,-2),u=a.slice(0,-2),p=s?s.slice(0,-2):t.slice(0,-2),c=Te.size(p),h=o[o.length-2],g=o[o.length-1],_=a[a.length-1],E=g%4===0&&_%4===0,A=h<=8?[4,1,1]:[4,4,1],v=[8,8,1],y=[Math.ceil(_/v[0]/A[0]),Math.ceil(h/v[1]/A[1]),Math.ceil(c/v[2]/A[2])],k=E?4:1,P=[...l,h,g/k],M=P.length,w=[...u,g,_/k],x=w.length,$=[c,h,_/k],z=[{type:6,data:h},{type:6,data:_},{type:6,data:g}];wn(r,z),z.push(...nt(p,P,w));let R=["rank","rank"],Q=e.length>2;Q&&(z.push(...nt(e[2].dims)),R.push("rank")),z.push(...nt($));let q=U=>{let Z=p.length,H=Ud("batchDims",e[0].dataType,Z,1),J=lr(e[0].dataType),ie=$e("a",e[0].dataType,M,k),ae=$e("b",e[1].dataType,x,k),ue=tt("result",e[0].dataType,$.length,k),he=[ie,ae];if(Q){let X=i?k:1;he.push($e("bias",e[2].dataType,e[2].dims.length,X))}let N=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];yn(r,N);let O=lr(ue.type.tensor),G=gn(r,ue.type.value,O),se=um(k,Q,G,[H,ie,ae,ue],i);return` + ${U.registerUniforms(N).registerInternalVariables(H).declareVariables(...he,ue)} + ${se} + ${E?nu(A,v,J,H):ou(A,v,J,H)} + `};return{name:"MatMul",shaderCache:{hint:`${A};${r.activation};${E};${i}`,inputDependencies:R},getRunData:()=>({outputs:[{dims:n?n(t):t,dataType:e[0].dataType}],dispatchGroup:{x:y[0],y:y[1],z:y[2]},programUniforms:z}),getShaderSource:q}}}),cm,pm,Tv=Ve(()=>{pt(),As(),Tt(),Mn(),tu(),vv(),au(),cm=(e,r,t,s,i=!1,n,o=4,a=4,l=4,u="f32")=>{let p=z=>{switch(z){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 ${z} is not supported.`)}},c=z=>{switch(z){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 ${z} is not supported.`)}},h=e?` + let coord = vec4(batch, xRow, xCol, xCh); + `:` + let coord = vec4(batch, xCh, xRow, xCol); + `,g=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])",E=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",A=e?"row":"col",v=e?"col":"row",y=` + let inChannels = i32(uniforms.w_shape[2]); + let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; + let outRow = ${A} / outWidth; + let outCol = ${A} % outWidth; + + let WRow = ${v} / (i32(uniforms.w_shape[1]) * inChannels); + let WCol = ${v} / 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 = ${v} % inChannels; + var resData = ${hr(o,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 < ${E}) { + ${h} + let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape)); + ${p(o)} + } + return resData;`,k=e?r&&s?` + let col = colIn * ${o}; + ${y}`:` + let col = colIn * ${o}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { + ${y} + } + return ${hr(o,u)}(0.0);`:s&&t?` + let col = colIn * ${o}; + ${y}`:` + let col = colIn * ${o}; + if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { + ${y} + } + return ${hr(o,u)}(0.0);`,P=e?s&&t?c(a):` + let col = colIn * ${a}; + if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { + ${c(a)} + } + return ${hr(a,u)}(0.0);`:` + let col = colIn * ${a}; + if (row < uniforms.dim_inner && col < uniforms.dim_a_outer) { + ${c(a)} + } + return ${hr(a,u)}(0.0);`,M=hr(l,u),w=hr(e?o:a,u),x=hr(e?a:o,u),$=gn(n,M,u);return` + fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${w} { + ${e?k:P} + } + + fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${x} { + ${e?P:k} + } + + fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${M}) { + 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])"}; + ${g} + ${im(i)} + ${$} + setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); + } + }`},pm=(e,r,t,s,i,n,o,a,l)=>{let u=r.format==="NHWC",p=u?e[0].dims[3]:e[0].dims[1],c=t[0],h=u?t[2]:t[3],g=u?t[1]:t[2],_=u?t[3]:t[1],E=u&&(p%4===0||p%3===0)&&_%4===0,A=u?_:h*g,v=u?h*g:_,y=[8,8,1],k=s<=8?[4,1,1]:[4,4,1],P=[Math.ceil(A/y[0]/k[0]),Math.ceil(v/y[1]/k[1]),Math.ceil(c/y[2]/k[2])];St("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${P}`);let M=E?u&&p%4!==0?3:4:1,w=y[1]*k[1],x=y[0]*k[0],$=Math.max(y[0]*M,y[1]),z=s%w===0,R=i%x===0,Q=n%$===0,q=E?[M,4,4]:[1,1,1],U=[{type:6,data:s},{type:6,data:i},{type:6,data:n},{type:6,data:[r.pads[0],r.pads[1]]},{type:6,data:r.strides},{type:6,data:r.dilations}];wn(r,U),U.push(...nt(e[0].dims,e[1].dims));let Z=["rank","rank"];o&&(U.push(...nt(e[2].dims)),Z.push("rank")),U.push(...nt(t));let H=J=>{let ie=[{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(r,ie);let ae=E?4:1,ue=lr(e[0].dataType),he=` + fn setOutputAtIndex(flatIndex : i32, value : ${E?`vec4<${ue}>`:ue}) { + result[flatIndex] = ${E?`vec4<${ue}>`:ue}(value); + } + fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${E?`vec4<${ue}>`:ue}) { + let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3)); + setOutputAtIndex(flatIndex ${E?"/ 4":""}, value); + }`,N=$e("x",e[0].dataType,e[0].dims.length,M===3?1:M),O=$e("w",e[1].dataType,e[1].dims.length,ae),G=[N,O],se=tt("result",e[0].dataType,t.length,ae);if(o){let X=$e("bias",e[2].dataType,e[2].dims.length,ae);G.push(X),he+=` + fn getBiasByOutputCoords(coords : vec4) -> ${E?`vec4<${ue}>`:ue} { + return bias[coords.${u?"w":"y"}${E?"/ 4":""}]; + }`}return` + ${om("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 }; + ${J.registerUniforms(ie).declareVariables(...G,se)} + ${he} + ${cm(u,z,R,Q,o,r,q[0],q[1],q[2],ue)} + ${E?nu(k,y,ue,void 0,!u,$):ou(k,y,ue,void 0,!u,$,!1,void 0,a)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${r.cacheKey};${M};${E};${z};${R};${Q};${w};${x};${$}`,inputDependencies:Z},getRunData:()=>({outputs:[{dims:l?l(t):t,dataType:e[0].dataType}],dispatchGroup:{x:P[0],y:P[1],z:P[2]},programUniforms:U}),getShaderSource:H}}}),hm,lu,Li,fm,du,mm,_m,gm,xv=Ve(()=>{pt(),As(),Mt(),Tt(),Mn(),tu(),hm=e=>{let r=1;for(let t=0;ttypeof e=="number"?[e,e,e]:e,Li=(e,r)=>r<=1?e:e+(e-1)*(r-1),fm=(e,r,t,s=1)=>{let i=Li(r,s);return Math.floor((e[0]*(t-1)-t+i)/2)},du=(e,r,t,s,i)=>{i==null&&(i=fm(e,r[0],s[0]));let n=[0,0,0,t];for(let o=0;o<3;o++)e[o]+2*i>=r[o]&&(n[o]=Math.trunc((e[o]-r[o]+2*i)/s[o]+1));return n},mm=(e,r,t,s,i,n,o,a,l,u)=>{let p,c,h,g;if(e==="VALID"&&(e=0),typeof e=="number"){p={top:e,bottom:e,left:e,right:e,front:e,back:e};let _=du([r,t,s,1],[a,l,u],1,[i,n,o],e);c=_[0],h=_[1],g=_[2]}else if(Array.isArray(e)){if(!e.every((E,A,v)=>E===v[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 _=du([r,t,s,1],[a,l,u],1,[i,n,o],e[0]);c=_[0],h=_[1],g=_[2]}else if(e==="SAME_UPPER"){c=Math.ceil(r/i),h=Math.ceil(t/n),g=Math.ceil(s/o);let _=(c-1)*i+a-r,E=(h-1)*n+l-t,A=(g-1)*o+u-s,v=Math.floor(_/2),y=_-v,k=Math.floor(E/2),P=E-k,M=Math.floor(A/2),w=A-M;p={top:k,bottom:P,left:M,right:w,front:v,back:y}}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:p,outDepth:c,outHeight:h,outWidth:g}},_m=(e,r,t,s,i,n=!1,o="channelsLast")=>{let a,l,u,p,c;if(o==="channelsLast")[a,l,u,p,c]=e;else if(o==="channelsFirst")[a,c,l,u,p]=e;else throw new Error(`Unknown dataFormat ${o}`);let[h,,g,_,E]=r,[A,v,y]=lu(t),[k,P,M]=lu(s),w=Li(g,k),x=Li(_,P),$=Li(E,M),{padInfo:z,outDepth:R,outHeight:Q,outWidth:q}=mm(i,l,u,p,A,v,y,w,x,$),U=n?h*c:h,Z=[0,0,0,0,0];return o==="channelsFirst"?Z=[a,U,R,Q,q]:o==="channelsLast"&&(Z=[a,R,Q,q,U]),{batchSize:a,dataFormat:o,inDepth:l,inHeight:u,inWidth:p,inChannels:c,outDepth:R,outHeight:Q,outWidth:q,outChannels:U,padInfo:z,strideDepth:A,strideHeight:v,strideWidth:y,filterDepth:g,filterHeight:_,filterWidth:E,effectiveFilterDepth:w,effectiveFilterHeight:x,effectiveFilterWidth:$,dilationDepth:k,dilationHeight:P,dilationWidth:M,inShape:e,outShape:Z,filterShape:r}},gm=(e,r,t,s,i,n)=>{let o=n==="channelsLast";o?e[0].dims[3]:e[0].dims[1];let a=[64,1,1],l={x:t.map((A,v)=>v)},u=[Math.ceil(hm(l.x.map(A=>t[A]))/a[0]),1,1];St("verbose",()=>`[conv3d_naive_webgpu] dispatch = ${u}`);let p=1,c=Te.size(t),h=[{type:12,data:c},{type:12,data:s},{type:12,data:i},{type:12,data:r.strides},{type:12,data:r.dilations}];wn(r,h),h.push(...nt(e[0].dims,e[1].dims));let g=["rank","rank"],_=e.length===3;_&&(h.push(...nt(e[2].dims)),g.push("rank")),h.push(...nt(t));let E=A=>{let v=[{name:"output_size",type:"u32"},{name:"filter_dims",type:"u32",length:s.length},{name:"pads",type:"u32",length:i.length},{name:"strides",type:"u32",length:r.strides.length},{name:"dilations",type:"u32",length:r.dilations.length}];yn(r,v);let y=1,k=lr(e[0].dataType),P=$e("x",e[0].dataType,e[0].dims.length,p),M=$e("W",e[1].dataType,e[1].dims.length,y),w=[P,M],x=tt("result",e[0].dataType,t.length,y),$="";if(_){let Q=$e("bias",e[2].dataType,e[2].dims.length,y);w.push(Q),$+=` + fn getBiasByOutputCoords(coords : array) -> ${k} { + return bias[${o?rt("coords",4,5):rt("coords",1,5)}]; + }`}let z=hr(p,k),R=gn(r,z,k);return` + ${$} + fn getX(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { + let aIndices = array(d0, d1, d2, d3, d4); + return ${P.getByIndices("aIndices")}; + } + fn getW(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { + let aIndices = array(d0, d1, d2, d3, d4); + return ${M.getByIndices("aIndices")}; + } + ${A.registerUniforms(v).declareVariables(...w,x)} + ${A.mainStart()} + ${A.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let coords = ${x.offsetToIndices("global_idx")}; + let batch = ${rt("coords",0,P.rank)}; + let d2 = ${o?rt("coords",P.rank-1,P.rank):rt("coords",1,P.rank)}; + let xFRCCorner = vec3(${o?rt("coords",1,P.rank):rt("coords",2,P.rank)}, + ${o?rt("coords",2,P.rank):rt("coords",3,P.rank)}, + ${o?rt("coords",3,P.rank):rt("coords",4,P.rank)}) * uniforms.strides - uniforms.pads; + let xFCorner = xFRCCorner.x; + let xRCorner = xFRCCorner.y; + let xCCorner = xFRCCorner.z; + let xShapeY = ${o?rt("uniforms.x_shape",1,P.rank):rt("uniforms.x_shape",2,P.rank)}; + let xShapeZ = ${o?rt("uniforms.x_shape",2,P.rank):rt("uniforms.x_shape",3,P.rank)}; + let xShapeW = ${o?rt("uniforms.x_shape",3,P.rank):rt("uniforms.x_shape",4,P.rank)}; + let xShapeU = ${o?rt("uniforms.x_shape",4,P.rank):rt("uniforms.x_shape",1,P.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) { + ${o?`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) { + ${o?`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) { + ${o?`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) { + ${o?`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)":""}; + ${R} + result[global_idx] = f32(value); + }`};return{name:"Conv3DNaive",shaderCache:{hint:`${r.cacheKey};${o};${p};${_}`,inputDependencies:g},getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:u[0],y:u[1],z:u[2]},programUniforms:h}),getShaderSource:E}}}),wm,ym,Ev=Ve(()=>{pt(),Mt(),Tt(),Mn(),wm=(e,r,t,s)=>{let i=e.length>2,n=i?"value += b[output_channel];":"",o=e[0].dims,a=e[1].dims,l=r.format==="NHWC",u=l?t[3]:t[1],p=u/r.group,c=l&&p>=4?Xt(u):1,h=Te.size(t)/c,g=[{type:12,data:h},{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}];wn(r,g),g.push(...nt(o,[a[0],a[1],a[2],a[3]/c]));let _=i?["rank","rank","rank"]:["rank","rank"];g.push(...nt([t[0],t[1],t[2],t[3]/c]));let E=A=>{let v=tt("output",e[0].dataType,t.length,c),y=lr(v.type.tensor),k=gn(r,v.type.value,y),P=$e("x",e[0].dataType,o.length),M=$e("w",e[1].dataType,a.length,c),w=[P,M];i&&w.push($e("b",e[2].dataType,e[2].dims,c));let x=[{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"}];yn(r,x);let $=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 = ${P.get("batch","xHeight","xWidth","input_channel")}; + let wVal = ${M.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 = ${P.get("batch","input_channel","xHeight","xWidth")}; + let wVal = ${M.get("output_channel","wInChannel","wHeight","wWidth")}; + value += xVal * wVal; + } + } + } + `;return` + ${A.registerUniforms(x).declareVariables(...w,v)} + + ${A.mainStart()} + ${A.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let outputIndices = ${v.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 * ${c} / uniforms.output_channels_per_group; + var in_channel_offset = group_id * uniforms.w_shape[${l?2:1}]; + + var value: ${v.type.value} = ${v.type.value}(0); + ${$} + ${n} + ${k} + ${v.setByOffset("global_idx","value")} + }`};return{name:"GroupedConv",shaderCache:{hint:`${r.cacheKey}_${c}`,inputDependencies:_},getRunData:()=>({outputs:[{dims:s?s(t):t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:g}),getShaderSource:E}},ym=(e,r,t,s)=>{let i=e.length>2,n=Xt(t[3]),o=Xt(t[2]),a=Te.size(t)/n/o,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],c=[{type:12,data:a},{type:6,data:[r.strides[0],r.strides[1]]},{type:6,data:[r.pads[0],r.pads[1]]}];wn(r,c),c.push(...nt(l,u,p));let h=(o-1)*r.strides[1]+u[1],g=_=>{let E=tt("output",e[0].dataType,p.length,n),A=lr(E.type.tensor),v=gn(r,E.type.value,A),y=$e("x",e[0].dataType,l.length,n),k=$e("w",e[1].dataType,u.length,n),P=[y,k];i&&P.push($e("b",e[2].dataType,e[2].dims,n));let M=i?"value += b[output_channel];":"",w=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return yn(r,w),` + ${_.registerUniforms(w).declareVariables(...P,E)} + ${_.mainStart()} + ${_.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let width0 = uniforms.output_shape[3]; + let output_channel = global_idx % width0; + var index1 = global_idx / width0; + let width1 = uniforms.output_shape[2] / ${o}u; + let col = (index1 % width1) * ${o}u; + index1 = index1 / width1; + let row = index1 % uniforms.output_shape[1]; + let batch = index1 / uniforms.output_shape[1]; + + let x_corner = vec2(i32(row), i32(col)) * uniforms.strides - uniforms.pads; + + var x_vals: array<${y.type.value}, ${h}>; + var values: array<${E.type.value}, ${o}>; + let input_channel = output_channel; + // Use constant instead of uniform can give better performance for w's height/width. + for (var w_height: u32 = 0u; w_height < ${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 < ${h}; i++) { + let x_width = x_corner.y + i; + if (x_width >= 0 && u32(x_width) < uniforms.x_shape[2]) { + x_vals[i] = ${y.get("batch","u32(x_height)","u32(x_width)","input_channel")}; + } else { + x_vals[i] = ${y.type.value}(0); + } + } + for (var w_width: u32 = 0u; w_width < ${u[1]}; w_width++) { + let w_val = ${k.get("w_height","w_width","0","output_channel")}; + for (var i = 0u; i < ${o}u; i++) { + values[i] = fma(x_vals[i * u32(uniforms.strides[1]) + w_width], w_val, values[i]); + } + } + } + } + + for (var i = 0u; i < ${o}u; i++) { + var value = values[i]; + ${M} + ${v} + ${E.set("batch","row","col + i","output_channel","value")}; + } + }`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${r.cacheKey};${n};${o};${h};${u[0]};${u[1]}`,inputDependencies:i?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:s?s(t):t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:c}),getShaderSource:g}}}),Mm,Sa,bm,$a,uu,cu,vm,Tm,pu,Pv=Ve(()=>{Mt(),Tv(),xv(),au(),Ev(),Mn(),su(),Hs(),Mm=(e,r,t,s,i,n)=>{let o=e[0],a=e.slice(n?1:2,n?3:4),l=a.length,u=r[0],p=r.slice(2).map((h,g)=>h+(h-1)*(t[g]-1)),c=a.map((h,g)=>h+s[g]+s[g+l]).map((h,g)=>Math.floor((h-p[g]+i[g])/i[g]));return c.splice(0,0,o),c.splice(n?3:1,0,u),c},Sa=[2,3,1,0],bm=(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 i=e[0].dims.length-2;if(r.dilations.length!==i)throw new Error(`dilations should be ${i}D`);if(r.strides.length!==i)throw new Error(`strides should be ${i}D`);if(r.pads.length!==i*2)throw new Error(`pads should be ${i*2}D`);if(r.kernelShape.length!==0&&r.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape")},$a=(e,r)=>{let t=e.kernelShape.slice();t.length{let r=eu(e),t=e.format,s=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],i=e.dilations,n=e.group,o=e.kernel_shape,a=e.pads,l=e.strides,u=e.w_is_const();return{autoPad:s,format:t,dilations:i,group:n,kernelShape:o,pads:a,strides:l,wIsConst:u,...r,cacheKey:`${e.format};${r.activation};`}},cu=(e,r,t,s)=>{let i=t.format==="NHWC",n=Mm(r[0].dims,r[1].dims,t.dilations,t.pads,t.strides,i);if(t.group!==1){let w=[r[0]];if(i){let x=e.kernelCustomData.wT??e.compute(Nr(r[1],Sa),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=x),w.push(x)}else w.push(r[1]);r.length===3&&w.push(r[2]),!e.adapterInfo.isArchitecture("ampere")&&i&&r[1].dims[0]===t.group&&r[1].dims[1]===1&&t.dilations[0]===1&&t.dilations[1]===1?e.compute(ym(w,t,n,s),{inputs:w}):e.compute(wm(w,t,n,s),{inputs:w});return}let o=r.length===3,a=r[0].dims[i?1:2],l=r[0].dims[i?2:3],u=r[0].dims[i?3:1],p=r[1].dims[2],c=r[1].dims[3],h=n[i?1:2],g=n[i?2:3],_=n[i?3:1],E=i&&p===a&&c===l&&t.pads[0]===0&&t.pads[1]===0;if(E||p===1&&c===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 w=n[0],x,$,z,R=[];if(i){let U=e.kernelCustomData.wT??e.compute(Nr(r[1],Sa),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];if(t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=U),E){let Z=a*l*u;x=r[0].reshape([1,w,Z]),$=U.reshape([1,Z,_]),z=[1,w,_]}else x=r[0].reshape([w,a*l,u]),$=U.reshape([1,u,_]),z=[w,h*g,_];R.push(x),R.push($)}else x=r[0].reshape([w,u,a*l]),$=r[1].reshape([1,_,u]),z=[w,_,h*g],R.push($),R.push(x);o&&R.push(r[2]);let Q=z[2],q=R[0].dims[R[0].dims.length-1];Q<8&&q<8?e.compute(ru(R,t,n,z,i,s),{inputs:R}):e.compute(Ca(R,t,n,z,i,s),{inputs:R});return}let A=!0,v=e.kernelCustomData.wT??e.compute(Nr(r[1],Sa),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=v);let y=[r[0],v];o&&y.push(r[2]);let k=i?h*g:_,P=i?_:h*g,M=p*c*u;e.compute(pm(y,t,n,k,P,M,o,A,s),{inputs:y})},vm=(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 i=[0,r.pads[0],0,r.pads[1]],n=[1].concat(r.strides),o=[1].concat(r.dilations),a=[1].concat(r.kernelShape),l=$a({...r,pads:i,strides:n,dilations:o,kernelShape:a},s);cu(e,s,l,u=>t?[u[0],u[2],u[3]]:[u[0],u[1],u[3]])},Tm=(e,r,t)=>{let s=t.format==="NHWC"?"channelsLast":"channelsFirst",i=$a(t,r),n=t.autoPad==="NOTSET"?t.pads:t.autoPad,o=_m(r[0].dims,r[1].dims,t.strides,t.dilations,n,!1,s);e.compute(gm(r,i,o.outShape,[o.filterDepth,o.filterHeight,o.filterWidth],[o.padInfo.front,o.padInfo.top,o.padInfo.left],s))},pu=(e,r)=>{if(bm(e.inputs,r),e.inputs[0].dims.length===3)vm(e,r);else if(e.inputs[0].dims.length===5)Tm(e,e.inputs,r);else{let t=$a(r,e.inputs);cu(e,e.inputs,t)}}}),xm,Cv=Ve(()=>{pt(),As(),Mt(),Tt(),xm=(e,r,t)=>{let s=e.length>2,i=r.outputShape,n=r.format==="NHWC",o=r.group,a=e[1].dims,l=a[2]/o,u=a[3],p=n?Xt(l):1,c=n&&u===1&&l>=4,h=c?Math.floor(l/4)*4:Math.floor(l/p)*p,g=l-h,_=n?Xt(u):1,E=n?u===1?p:_:1,A=Te.size(i)/_,v=[Math.ceil(A/64),1,1];St("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${v}`);let y=["rank","rank"],k=[r.strides[0],r.strides[1]],P=[r.kernelShape[n?1:2],r.kernelShape[n?2:3]],M=[r.dilations[0],r.dilations[1]],w=[P[0]+(r.dilations[0]<=1?0:(r.kernelShape[n?1:2]-1)*(r.dilations[0]-1)),P[1]+(r.dilations[1]<=1?0:(r.kernelShape[n?2:3]-1)*(r.dilations[1]-1))],x=[w[0]-1-Math.floor((r.pads[0]+r.pads[2])/2),w[1]-1-Math.floor((r.pads[1]+r.pads[3])/2)],$=[{type:12,data:A},{type:12,data:k},{type:12,data:P},{type:12,data:M},{type:12,data:w},{type:6,data:x},{type:12,data:h},{type:12,data:l},{type:12,data:u},...nt(e[0].dims,e[1].dims)];s&&($.push(...nt(e[2].dims)),y.push("rank")),$.push(...nt(i));let z=R=>{let Q=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:k.length},{name:"filter_dims",type:"u32",length:P.length},{name:"dilations",type:"u32",length:P.length},{name:"effective_filter_dims",type:"u32",length:w.length},{name:"pads",type:"i32",length:x.length},{name:"input_channels_per_group_int",type:"u32"},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],q=lr(e[0].dataType),U=n?1:2,Z=n?2:3,H=n?3:1,J=$e("W",e[1].dataType,e[1].dims.length,E),ie=$e("Dy",e[0].dataType,e[0].dims.length,p),ae=[ie,J];s&&ae.push($e("bias",e[2].dataType,[i[H]].length,_));let ue=tt("result",e[0].dataType,i.length,_),he=()=>{let G="";if(c)p===4?G+=` + let xValue = ${ie.getByOffset("x_offset")}; + let wValue = ${J.getByOffset("w_offset")}; + dotProd = dotProd + dot(xValue, wValue); + x_offset += 1u; + w_offset += 1u;`:p===2?G+=` + dotProd = dotProd + dot(vec4<${q}>(${ie.getByOffset("x_offset")}, ${ie.getByOffset("x_offset + 1u")}), vec4<${q}>(${J.getByOffset("w_offset")}, ${J.getByOffset("w_offset + 1u")})); + x_offset += 2u; + w_offset += 2u;`:p===1&&(G+=` + dotProd = dotProd + dot(vec4<${q}>(${ie.getByOffset("x_offset")}, ${ie.getByOffset("x_offset + 1u")}, ${ie.getByOffset("x_offset + 2u")}, ${ie.getByOffset("x_offset + 3u")}), vec4<${q}>(${J.getByOffset("w_offset")}, ${J.getByOffset("w_offset + 1u")}, ${J.getByOffset("w_offset + 2u")}, ${J.getByOffset("w_offset + 3u")})); + x_offset += 4u; + w_offset += 4u;`);else if(G+=` + let xValue = ${n?ie.getByOffset(`${ie.indicesToOffset(`${ie.type.indices}(batch, idyR, idyC, inputChannel)`)} / ${p}`):ie.get("batch","inputChannel","idyR","idyC")}; + `,p===1)G+=` + let w_offset = ${J.indicesToOffset(`${J.type.indices}(u32(wRPerm), u32(wCPerm), inputChannel, wOutChannel)`)}; + let wValue = ${J.getByOffset(`w_offset / ${E}`)}; + dotProd = dotProd + xValue * wValue;`;else for(let se=0;se{if(g===0)return"";if(!c)throw new Error(`packInputAs4 ${c} is not true.`);let G="";if(p===1){G+="dotProd = dotProd";for(let se=0;se(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 = ${ue.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 = (${q}(dyRCorner) + ${q}(wR)) / ${q}(uniforms.strides[0]); + let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x; + if (dyR < 0.0 || dyR >= ${q}(uniforms.Dy_shape[${U}]) || 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 = (${q}(dyCCorner) + ${q}(wC)) / ${q}(uniforms.strides.y); + let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y; + if (dyC < 0.0 || dyC >= ${q}(uniforms.Dy_shape[${Z}]) || + fract(dyC) > 0.0 || wCPerm < 0) { + continue; + } + let idyC: u32 = u32(dyC); + var inputChannel = groupId * uniforms.input_channels_per_group; + ${c?` + var x_offset = ${ie.indicesToOffset(`${ie.type.indices}(batch, idyR, idyC, inputChannel)`)} / ${p}; + var w_offset = ${J.indicesToOffset(`${J.type.indices}(wRPerm, wCPerm, inputChannel, wOutChannel)`)} / ${E}; + `:""} + for (var d2: u32 = 0; d2 < uniforms.input_channels_per_group_int; d2 = d2 + ${c?4:p}) { + ${he()} + inputChannel = inputChannel + ${c?4:p}; + } + ${N()} + wC = wC + uniforms.strides.y - 1; + } + wR = wR + uniforms.strides[0] - 1; + } + let value = dotProd${s?` + bias[d1 / ${_}]`:""}; + ${ue.setByOffset("global_idx","value")}; + `;return` + ${R.registerUniforms(Q).declareVariables(...ae,ue)} + ${R.mainStart()} + ${R.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}; + ${O}}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${r.cacheKey};${p}${E}${_}${c}${g}`,inputDependencies:y},getRunData:()=>({dispatchGroup:{x:v[0],y:v[1],z:v[2]},outputs:[{dims:t?t(i):i,dataType:e[0].dataType}],programUniforms:$}),getShaderSource:z}}}),Em,Pm,Cm,hu,Sm,$m,fu,km,Im,Sv=Ve(()=>{Cv(),Mn(),Hs(),Em=(e,r,t,s,i,n)=>(e-1)*r+t+(s-1)*i+1-n,Pm=(e,r,t,s,i)=>{let n=Math.floor(e/2);r==="SAME_UPPER"?(t[s]=n,t[i]=e-n):r==="SAME_LOWER"&&(t[s]=e-n,t[i]=n)},Cm=(e,r,t,s,i,n,o,a,l,u)=>{let p=e.length-2,c=u.length===0;l.length{let t=e.kernelShape.slice();if(e.kernelShape.length===0||e.kernelShape.reduce((c,h)=>c*h,1)===0){t.length=0;for(let c=2;cc+h,0)===0){let c=r[0].dims.length-2;l=new Array(c).fill(1)}let u=e.strides.slice();if(u.reduce((c,h)=>c+h,0)===0){let c=r[0].dims.length-2;u=new Array(c).fill(1)}Cm(a,t,l,e.autoPad,e.group,i,u,s,o,n);let p=Object.assign({},e);return Object.assign(p,{kernelShape:t,pads:i,outputPadding:o,outputShape:n,dilations:l,strides:u}),p},Sm=e=>{let r=eu(e),t=e.format,s=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof e.autoPad>"u"?0:e.autoPad],i=e.dilations,n=e.group,o=e.kernelShape,a=e.pads,l=e.strides,u=e.wIsConst(),p=e.outputPadding,c=e.outputShape;return{autoPad:s,format:t,dilations:i,group:n,kernelShape:o,outputPadding:p,outputShape:c,pads:a,strides:l,wIsConst:u,...r,cacheKey:`${e.format};${r.activation};`}},$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!==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 i=e[1].dims[1]*r.group;if(e.length===3&&(e[2].dims.length!==1||e[2].dims[0]!==i))throw new Error("invalid bias");let n=e[0].dims.length-2;if(r.dilations.reduce((o,a)=>o+a,0)>0&&r.dilations.length!==n)throw new Error(`dilations should be ${n}D`);if(r.strides.reduce((o,a)=>o+a,0)>0&&r.strides.length!==n)throw new Error(`strides should be ${n}D`);if(r.pads.reduce((o,a)=>o+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((o,a)=>o+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")},fu=(e,r,t,s)=>{let i=e.kernelCustomData.wT??e.compute(Nr(r[1],[2,3,0,1]),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=i);let n=[r[0],i];r.length===3&&n.push(r[2]),e.compute(xm(n,t,s),{inputs:n})},km=(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 i=r.kernelShape;(i.length===0||i[0]===0)&&(i=[e.inputs[1].dims[2]]);let n=r.dilations;(n.length===0||n[0]===0)&&(n=[1]);let o=r.strides;(o.length===0||o[0]===0)&&(o=[1]);let a=r.pads;a.length===0&&(a=[0,0]),a=[0,a[0],0,a[1]],o=[1].concat(o),n=[1].concat(n),i=[1].concat(i);let l=r.outputPadding;l=[0].concat(l);let u=hu({...r,pads:a,strides:o,dilations:n,kernelShape:i,outputPadding:l},s);fu(e,s,u,p=>t?[p[0],p[2],p[3]]:[p[0],p[1],p[3]])},Im=(e,r)=>{if($m(e.inputs,r),e.inputs[0].dims.length===3)km(e,r);else{let t=hu(r,e.inputs);fu(e,e.inputs,t)}}}),Am,Fm,Om,$v=Ve(()=>{pt(),Mt(),Yt(),Tt(),Am=(e,r,t,s)=>{let i=Te.size(r),n=r.length,o=$e("input",e,n),a=tt("output",e,n),l=t.dataType===6?t.getInt32Array()[0]:Number(t.getBigInt64Array()[0]),u=Te.normalizeAxis(l,n),p=c=>{let h=` i32(${o.indicesGet("inputIndices","uniforms.axis")}) `,g=rt("uniforms.input_shape","uniforms.axis",n),_=s.reverse?h+(s.exclusive?" + 1":""):"0",E=s.reverse?g:h+(s.exclusive?"":" + 1");return` + ${c.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(o,a)} + ${c.mainStart()} + ${c.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var inputIndices = ${a.offsetToIndices("global_idx")}; + var sum = ${a.type.value}(0); + let first : i32 = ${_}; + let last : i32 = ${E}; + for (var i : i32 = first; i < last; i++) { + ${o.indicesSet("inputIndices","uniforms.axis","u32(i)")}; + sum = sum + ${o.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(i/64)},programUniforms:[{type:12,data:i},{type:12,data:u},...nt(r,r)]}),getShaderSource:p}},Fm=(e,r)=>{let t=e.inputs[0].dims,s=e.inputs[0].dataType,i=e.inputs[1];e.compute(Am(s,t,i,r),{inputs:[0]})},Om=e=>{let r=e.exclusive===1,t=e.reverse===1;return Dt({exclusive:r,reverse:t})}}),Dm,Lm,zm,Bm,Rm,kv=Ve(()=>{pt(),Mt(),Yt(),Tt(),Dm=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.")},Lm=(e,r,t,s)=>{let i=[];i.push(`fn perm(i: ${s.type.indices}) -> ${t.type.indices} { + var a: ${t.type.indices};`);for(let n=0;n{let t,s,i,n,o,a,l=r.format==="NHWC",u=r.blocksize,p=r.mode==="DCR";l?([t,s,i,n]=e.dims,o=p?[t,s,i,u,u,n/u**2]:[t,s,i,n/u**2,u,u],a=p?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([t,s,i,n]=[e.dims[0],e.dims[2],e.dims[3],e.dims[1]],o=p?[t,u,u,n/u**2,s,i]:[t,n/u**2,u,u,s,i],a=p?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let c=e.reshape(o),h=c.dims.length,g=e.dataType,_=$e("a",g,h),E=tt("output",g,h),A=v=>` + ${v.registerUniform("output_size","u32").declareVariables(_,E)} + + ${Lm(a,h,_,E)} + + ${v.mainStart()} + ${v.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${E.offsetToIndices("global_idx")}; + let aIndices = perm(indices); + + ${E.setByOffset("global_idx",_.getByIndices("aIndices"))} + }`;return{name:"DepthToSpace",shaderCache:{hint:`${e.dims};${r.blocksize};${r.mode}`,inputDependencies:["rank"]},getRunData:v=>{let y=l?[t,s*u,i*u,n/u**2]:[t,n/u**2,s*u,i*u],k=Te.size(y),P=c.dims,M=Te.sortBasedOnPerm(P,a);return{outputs:[{dims:y,dataType:v[0].dataType}],dispatchGroup:{x:Math.ceil(k/64)},programUniforms:[{type:12,data:k},...nt(P,M)]}},getShaderSource:A}},Bm=(e,r)=>{Dm(e.inputs),e.compute(zm(e.inputs[0],r))},Rm=e=>Dt({blocksize:e.blocksize,mode:e.mode,format:e.format})}),ka,zi,mu,Nm,jm,Vm,Um,_u,Wm,Gm,Km,Iv=Ve(()=>{pt(),Mt(),Yt(),Tt(),ka="[a-zA-Z]|\\.\\.\\.",zi="("+ka+")+",mu="^"+zi+"$",Nm="("+zi+",)*"+zi,jm="^"+Nm+"$",Vm=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)}},Um=class{constructor(e,r){var i;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(jm)))throw new Error("Invalid LHS term");if(t.split(",").forEach((n,o)=>{let a=e[o].dims.slice();if(!n.match(RegExp(mu)))throw new Error("Invalid LHS term");let l=this.processTerm(n,!0,a,o);this.lhs.push(l)}),s==="")s+=[...this.symbolToInfo.entries()].filter(([n,o])=>o.count===1||n==="...").map(([n])=>n).join("");else if(!s.match(RegExp(zi)))throw new Error("Invalid RHS");(i=s.match(RegExp(ka,"g")))==null||i.forEach(n=>{if(n==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let o=this.symbolToInfo.get(n);if(o===void 0)throw new Error("Invalid RHS symbol");this.outputDims.push(o.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 i=t.length,n=!1,o=[],a=0;if(!e.match(RegExp(mu))&&!r&&e!=="")throw new Error("Invalid LHS term");let l=e.match(RegExp(ka,"g")),u=new Vm(s);return l==null||l.forEach((p,c)=>{if(p==="..."){if(n)throw new Error("Only one ellipsis is allowed per input term");n=!0;let h=i-l.length+1;if(h<0)throw new Error("Ellipsis out of bounds");if(o=t.slice(a,a+h),this.hasEllipsis){if(this.ellipsisDims.length!==o.length||this.ellipsisDims.toString()!==o.toString())throw new Error("Ellipsis dimensions mismatch")}else if(r)this.hasEllipsis=!0,this.ellipsisDims=o;else throw new Error("Ellipsis must be specified in the LHS");for(let g=0;ge+"_max",Wm=(e,r,t,s)=>{let i=e.map(u=>u.length).map((u,p)=>$e(`input${p}`,r,u)),n=Te.size(s),o=tt("output",r,s.length),a=[...t.symbolToInfo.keys()].filter(u=>!t.rhs.symbolToIndices.has(u)),l=u=>{let p=[],c="var prod = 1.0;",h="var sum = 0.0;",g="sum += prod;",_=[],E=[],A=[],v=[],y=t.symbolToInfo.size===t.rhs.symbolToIndices.size;t.symbolToInfo.forEach((P,M)=>{var w;if(t.rhs.symbolToIndices.has(M)){let x=(w=t.rhs.symbolToIndices.get(M))==null?void 0:w[0];x!==void 0&&t.lhs.forEach(($,z)=>{if(P.inputIndices.includes(z)){let R=$.symbolToIndices.get(M);if(R===void 0)throw new Error("Invalid symbol error");R.forEach(Q=>{p.push(`${i[z].indicesSet(`input${z}Indices`,Q,o.indicesGet("outputIndices",x))}`)})}})}else t.lhs.forEach((x,$)=>{if(P.inputIndices.includes($)){let z=x.symbolToIndices.get(M);if(z===void 0)throw new Error("Invalid symbol error");z.forEach(R=>{_.push(`${i[$].indicesSet(`input${$}Indices`,R,`${M}`)}`)}),v.push(`prod *= ${i[$].getByIndices(`input${$}Indices`)};`)}}),E.push(`for(var ${M}: u32 = 0; ${M} < uniforms.${_u(M)}; ${M}++) {`),A.push("}")});let k=y?[...p,`let sum = ${i.map((P,M)=>P.getByIndices(`input${M}Indices`)).join(" * ")};`]:[...p,h,...E,..._,c,...v,g,...A];return` + ${u.registerUniforms(a.map(P=>({name:`${_u(P)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...i,o)} + + ${u.mainStart()} + ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var outputIndices = ${o.offsetToIndices("global_idx")}; + ${i.map((P,M)=>`var input${M}Indices: ${i[M].type.indices};`).join(` +`)} + ${k.join(` +`)}; + ${o.setByOffset("global_idx","sum")}; + }`};return{name:"Einsum",shaderCache:{hint:t.equation,inputDependencies:e.map(()=>"rank")},getRunData:()=>{let u=a.filter(c=>t.symbolToInfo.has(c)).map(c=>{var h;return{type:12,data:((h=t.symbolToInfo.get(c))==null?void 0:h.dimValue)||0}});u.push({type:12,data:n});let p=e.map((c,h)=>[...nt(c)]).reduce((c,h)=>c.concat(h),u);return p.push(...nt(s)),{outputs:[{dims:s,dataType:r}],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:p}},getShaderSource:l}},Gm=(e,r)=>{let t=new Um(e.inputs,r.equation),s=t.outputDims,i=e.inputs.map((n,o)=>n.dims);e.compute(Wm(i,e.inputs[0].dataType,t,s))},Km=e=>{let r=e.equation.replace(/\s+/g,"");return Dt({equation:r})}}),Hm,gu,qm,Qm,Xm,Av=Ve(()=>{pt(),Mt(),Tt(),Hm=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 i=0;ie.length>r.length?gu(e,r):gu(r,e),Qm=e=>{let r=e[0].dims,t=Array.from(e[1].getBigInt64Array(),Number),s=qm(r,t),i=e[0].dataType,n=i===9||Te.size(r)===1,o=i===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(Te.size(s)/a),u=c=>{let h=$e("input",i,r.length,o),g=tt("output",i,s.length,a),_;if(i===9){let E=(A,v,y="")=>` + let outputIndices${v} = ${g.offsetToIndices(`outputOffset + ${v}u`)}; + let offset${v} = ${h.broadcastedIndicesToOffset(`outputIndices${v}`,g)}; + let index${v} = offset${v} / 4u; + let component${v} = offset${v} % 4u; + ${A}[${v}] = ${y}(${h.getByOffset(`index${v}`)}[component${v}]); + `;_=` + let outputOffset = global_idx * ${a}; + var data = vec4(0); + ${E("data",0,"u32")} + ${E("data",1,"u32")} + ${E("data",2,"u32")} + ${E("data",3,"u32")} + ${g.setByOffset("global_idx","data")} + }`}else _=` + let outputIndices = ${g.offsetToIndices(`global_idx * ${a}`)}; + let inputOffset = ${h.broadcastedIndicesToOffset("outputIndices",g)}; + let data = ${g.type.value}(${h.getByOffset(`inputOffset / ${o}`)}); + ${g.setByOffset("global_idx","data")} + }`;return` + ${c.registerUniform("vec_size","u32").declareVariables(h,g)} + ${c.mainStart()} + ${c.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${_}`},p=[{type:12,data:l},...nt(r,s)];return{name:"Expand",shaderCache:{hint:`${s.length};${o}${a}`,inputDependencies:["rank"]},getShaderSource:u,getRunData:()=>({outputs:[{dims:s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:p})}},Xm=e=>{Hm(e.inputs),e.compute(Qm(e.inputs),{inputs:[0]})}}),Jm,Ym,Fv=Ve(()=>{pt(),Mt(),Tt(),Zd(),Jm=e=>{let r=e[0].dataType,t=Te.size(e[0].dims),s=Te.size(e[1].dims),i=s%4===0,n=o=>{let a=$e("x",r,[1],4),l=$e("bias",r,[1],4),u=tt("y",r,[1],4),p=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],c=g=>` + let bias${g}_offset: u32 = (global_idx * 4 + ${g}) % uniforms.bias_size; + let bias${g} = ${l.getByOffset(`bias${g}_offset / 4`)}[bias${g}_offset % 4];`,h=i?` + let bias = ${l.getByOffset("global_idx % (uniforms.bias_size / 4)")};`:`${c(0)}${c(1)}${c(2)}${c(3)} + let bias = ${a.type.value}(bias0, bias1, bias2, bias3);`;return`${o.registerUniforms(p).declareVariables(a,l,u)} + + ${Jd(xr(r))} + + ${o.mainStart(jn)} + ${o.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")} + + let x = ${a.getByOffset("global_idx")}; + ${h} + let x_in = x + bias; + ${u.setByOffset("global_idx",Yd("x_in"))} + }`};return{name:"FastGeluWithBias",shaderCache:{hint:`${i}`,inputDependencies:["type","type"]},getShaderSource:n,getRunData:o=>({outputs:[{dims:o[0].dims,dataType:o[0].dataType}],programUniforms:[{type:12,data:Math.ceil(t/4)},{type:12,data:s}],dispatchGroup:{x:Math.ceil(t/jn/4)}})}},Ym=e=>{e.inputs.length<2||Te.size(e.inputs[1].dims)===0?Af(e):e.compute(Jm(e.inputs))}}),Zm,e_,t_,r_,Ov=Ve(()=>{pt(),Mt(),Yt(),Tt(),Zm=e=>{if(!e||e.length!==2)throw new Error("Gather requires 2 inputs.")},e_=(e,r)=>{let t=e[0].dims,s=e[1].dims,i=t.length,n=Te.normalizeAxis(r.axis,i),o=t.slice(0);o.splice(n,1,...s);let a=t[n],l=e[0].dataType===9?4:1,u=Math.ceil(Te.size(o)/l),p=[{type:12,data:u},{type:6,data:a},{type:12,data:n},...nt(e[0].dims,e[1].dims,o)],c=h=>{let g=$e("data",e[0].dataType,e[0].dims.length,l),_=$e("inputIndices",e[1].dataType,e[1].dims.length),E=tt("output",e[0].dataType,o.length,l),A=y=>{let k=s.length,P=`var indicesIndices${y} = ${_.type.indices}(0);`;for(let M=0;M1?`indicesIndices${y}[${M}]`:`indicesIndices${y}`} = ${o.length>1?`outputIndices${y}[uniforms.axis + ${M}]`:`outputIndices${y}`};`;P+=` + var idx${y} = ${_.getByIndices(`indicesIndices${y}`)}; + if (idx${y} < 0) { + idx${y} = idx${y} + uniforms.axisDimLimit; + } + var dataIndices${y} : ${g.type.indices}; + `;for(let M=0,w=0;M1?`dataIndices${y}[${M}]`:`dataIndices${y}`} = u32(idx${y});`,w+=k):(P+=`${i>1?`dataIndices${y}[${M}]`:`dataIndices${y}`} = ${o.length>1?`outputIndices${y}[${w}]`:`outputIndices${y}`};`,w++);return P},v;if(e[0].dataType===9){let y=(k,P,M="")=>` + let outputIndices${P} = ${E.offsetToIndices(`outputOffset + ${P}u`)}; + ${A(P)}; + let offset${P} = ${g.indicesToOffset(`dataIndices${P}`)}; + let index${P} = offset${P} / 4u; + let component${P} = offset${P} % 4u; + ${k}[${P}] = ${M}(${g.getByOffset(`index${P}`)}[component${P}]); + `;v=` + let outputOffset = global_idx * ${l}; + var value = vec4(0); + ${y("value",0,"u32")} + ${y("value",1,"u32")} + ${y("value",2,"u32")} + ${y("value",3,"u32")} + ${E.setByOffset("global_idx","value")} + `}else v=` + let outputIndices = ${E.offsetToIndices("global_idx")}; + ${A("")}; + let value = ${g.getByIndices("dataIndices")}; + ${E.setByOffset("global_idx","value")}; + `;return` + ${h.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(g,_,E)} + ${h.mainStart()} + ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + ${v} + }`};return{name:"Gather",shaderCache:{hint:r.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:p}),getShaderSource:c}},t_=e=>Dt({axis:e.axis}),r_=(e,r)=>{let t=e.inputs;Zm(t),e.compute(e_(e.inputs,r))}}),s_,n_,i_,Dv=Ve(()=>{pt(),Mt(),Tt(),s_=(e,r,t,s,i,n,o,a,l)=>{let u=[{type:12,data:n},{type:12,data:s},{type:12,data:i},{type:12,data:t},{type:12,data:o},{type:12,data:a},{type:12,data:l}],p=[n];u.push(...nt(r.dims,p));let c=h=>{let g=$e("indices_data",r.dataType,r.dims.length),_=tt("input_slice_offsets_data",12,1,1),E=[g,_],A=[{name:"output_size",type:"u32"},{name:"batch_dims",type:"u32"},{name:"input_dims",type:"u32",length:i.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` + ${h.registerUniforms(A).declareVariables(...E)} + ${h.mainStart()} + ${h.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) { + ${i.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:`${i.length}_${t.length}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:p,dataType:e.inputs[1].dataType}],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:u}),getShaderSource:c},{inputs:[r],outputs:[-1]})[0]},n_=(e,r)=>{let t=e.inputs,s=t[0].dims,i=t[0].dataType,n=t[1].dims,o=n[n.length-1],a=Te.sizeToDimension(n,n.length-1),l=Te.sizeFromDimension(s,r.batchDims+o),u=Te.sizeToDimension(s,r.batchDims),p=Te.sizeFromDimension(s,r.batchDims),c=a/u,h=new Array(o),g=l;for(let P=0;Ps.length)throw new Error("last dimension of indices must not be larger than rank of input tensor");let A=n.slice(0,-1).concat(s.slice(E)),v=Te.size(A),y=[{type:12,data:v},{type:12,data:l},...nt(t[0].dims,_.dims,A)],k=P=>{let M=$e("data",t[0].dataType,t[0].dims.length),w=$e("slice_offsets",12,_.dims.length),x=tt("output",t[0].dataType,A.length);return` + ${P.registerUniform("output_size","u32").registerUniform("slice_size","u32").declareVariables(M,w,x)} + ${P.mainStart()} + ${P.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:A,dataType:i}],dispatchGroup:{x:Math.ceil(v/64)},programUniforms:y}),getShaderSource:k},{inputs:[t[0],_]})},i_=e=>({batchDims:e.batch_dims,cacheKey:""})}),o_,a_,l_,d_,Lv=Ve(()=>{pt(),Mt(),Yt(),Tt(),o_=(e,r)=>{if(e.length<3||e.length>4)throw new Error("GatherBlockQuantized requires 3 or 4 inputs.");let t=Te.normalizeAxis(r.quantizeAxis,e[0].dims.length),s=r.blockSize,i=e[0],n=e[2],o=e.length===4?e[3]:void 0;if(n.dims.length!==i.dims.length||!i.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(o){if(o.dataType!==i.dataType)throw new Error("Zero point must have the same data type as the input tensor.");if(o.dims.length!==n.dims.length||!o.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.")}},a_=(e,r)=>{let t=e[0].dims,s=e[1].dims,i=t.length,n=Te.normalizeAxis(r.gatherAxis,i),o=Te.normalizeAxis(r.quantizeAxis,i),a=t.slice(0);a.splice(n,1,...s);let l=Te.size(a),u=e[2].dataType,p=e[0].dataType===22,c=[{type:12,data:l},{type:12,data:o},{type:12,data:n},{type:12,data:r.blockSize},...nt(...e.map((g,_)=>g.dims),a)],h=g=>{let _=$e("data",e[0].dataType,e[0].dims.length),E=$e("inputIndices",e[1].dataType,e[1].dims.length),A=$e("scales",e[2].dataType,e[2].dims.length),v=e.length>3?$e("zeroPoint",e[3].dataType,e[3].dims.length):void 0,y=tt("output",u,a.length),k=[_,E,A];v&&k.push(v);let P=[{name:"output_size",type:"u32"},{name:"quantize_axis",type:"u32"},{name:"gather_axis",type:"u32"},{name:"block_size",type:"u32"}];return` + ${g.registerUniforms(P).declareVariables(...k,y)} + ${g.mainStart()} + let output_indices = ${y.offsetToIndices("global_idx")}; + var indices_indices = ${E.type.indices}(0); + ${s.length>1?` + for (var i: u32 = 0; i < ${s.length}; i++) { + let index = ${y.indicesGet("output_indices","uniforms.gather_axis + i")}; + ${E.indicesSet("indices_indices","i","index")}; + }`:`indices_indices = ${y.indicesGet("output_indices","uniforms.gather_axis")};`}; + var data_indices = ${_.type.indices}(0); + for (var i: u32 = 0; i < uniforms.gather_axis; i++) { + let index = ${y.indicesGet("output_indices","i")}; + ${_.indicesSet("data_indices","i","index")}; + } + var index_from_indices = ${E.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 = ${y.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 = ${A.indicesGet("data_indices","uniforms.quantize_axis")} / uniforms.block_size; + ${A.indicesSet("scale_indices","uniforms.quantize_axis","quantize_axis_index")}; + var scale = ${A.getByIndices("scale_indices")}; + ${v?` + let zero_point_indices = scale_indices; + let zero_point_offset = ${v.indicesToOffset("zero_point_indices")}; + let zero_point_index = zero_point_offset % 8; + let packed_4bit_zero_points = ${v.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 = ${xr(u)}(quantized_data - zero_point) * scale; + ${y.setByOffset("global_idx","dequantized_data")}; + }`};return{name:"GatherBlockQuantized",shaderCache:{hint:`${r.cacheKey};${e.filter((g,_)=>_!==1).map(g=>g.dims.join("_")).join(";")}`,inputDependencies:Array.from({length:e.length},(g,_)=>"rank")},getRunData:()=>({outputs:[{dims:a,dataType:u}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:c}),getShaderSource:h}},l_=(e,r)=>{let t=e.inputs;o_(t,r),e.compute(a_(e.inputs,r))},d_=e=>Dt({blockSize:e.blockSize,gatherAxis:e.gatherAxis,quantizeAxis:e.quantizeAxis})}),u_,c_,p_,h_,zv=Ve(()=>{pt(),Mt(),Yt(),Tt(),u_=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.`)},c_=(e,r)=>{let t=e[0].dims,s=e[0].dataType,i=t.length,n=e[1].dims,o=e[1].dataType,a=Te.normalizeAxis(r.axis,i),l=t[a],u=n.slice(0),p=Te.size(u),c=$e("input",s,i),h=$e("indicesInput",o,n.length),g=tt("output",s,u.length),_=[{type:12,data:p},{type:6,data:l},{type:12,data:a}];return _.push(...nt(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:E=>` + ${E.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(c,h,g)} + ${E.mainStart()} + ${E.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + + let outputIndices = ${g.offsetToIndices("global_idx")}; + + var idx = ${h.getByOffset("global_idx")}; + if (idx < 0) { + idx = idx + uniforms.axisDimLimit; + } + var inputIndices = ${c.type.indices}(outputIndices); + ${c.indicesSet("inputIndices","uniforms.axis","u32(idx)")}; + let value = ${c.getByIndices("inputIndices")}; + + ${g.setByOffset("global_idx","value")}; + }`}},p_=e=>Dt({axis:e.axis}),h_=(e,r)=>{let t=e.inputs;u_(t),e.compute(c_(e.inputs,r))}}),f_,m_,__,g_,Bv=Ve(()=>{pt(),Mt(),Tt(),f_=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")},m_=(e,r)=>{let t=e[0].dims.slice(),s=e[1].dims.slice(),[i,n,o]=zp.getShapeOfGemmResult(t,r.transA,s,r.transB,e.length===3?e[2].dims:void 0),a=[i,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(i/l),c=!0,h=Te.size(a),g=[{type:12,data:c?u:h},{type:12,data:i},{type:12,data:n},{type:12,data:o},{type:1,data:r.alpha},{type:1,data:r.beta}],_=["type","type"];e.length===3&&(g.push(...nt(e[2].dims)),_.push("rank")),g.push(...nt(a));let E=v=>{let y="";r.transA&&r.transB?y="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":r.transA&&!r.transB?y="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!r.transA&&r.transB?y="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!r.transA&&!r.transB&&(y="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let k=r.alpha===1?"":"value *= uniforms.alpha;",P=$e("a",e[0].dataType,e[0].dims),M=$e("b",e[1].dataType,e[1].dims),w=P.type.value,x=null,$=[P,M];e.length===3&&(x=$e("c",e[2].dataType,e[2].dims.length),$.push(x));let z=tt("output",e[0].dataType,a.length);$.push(z);let R=[{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` + ${v.registerUniforms(R).declareVariables(...$)} + + ${v.mainStart()} + ${v.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let m = global_idx / uniforms.N; + let n = global_idx % uniforms.N; + + var value = ${w}(0); + for (var k: u32 = 0u; k < uniforms.K; k++) { + ${y} + } + + ${k} + ${x!=null?`let cOffset = ${x.broadcastedIndicesToOffset("vec2(m, n)",z)}; value += ${w}(uniforms.beta) * ${x.getByOffset("cOffset")};`:""} + output[global_idx] = value; + }`},A=v=>{let y=$e("a",e[0].dataType,e[0].dims),k=$e("b",e[1].dataType,e[1].dims),P=null,M=[y,k];e.length===3&&(P=$e("c",e[2].dataType,e[2].dims.length),M.push(P));let w=tt("output",e[0].dataType,a.length);M.push(w);let x=[{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"}],$="",z="";r.transA&&r.transB?(z=` + 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] = ${y.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] = ${k.type.value}(0); + } + `,$="value += tile_a[k][local_id.y] * tile_b[local_id.x][k];"):r.transA&&!r.transB?(z=` + 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] = ${y.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] = ${k.type.value}(0); + } + `,$="value += tile_a[k][local_id.y] * tile_b[k][local_id.x];"):!r.transA&&r.transB?(z=` + 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] = ${y.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] = ${k.type.value}(0); + } + `,$="value += tile_a[local_id.y][k] * tile_b[local_id.x][k];"):!r.transA&&!r.transB&&(z=` + 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] = ${y.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] = ${k.type.value}(0); + } + `,$="value += tile_a[local_id.y][k] * tile_b[k][local_id.x];");let R=r.alpha===1?"":"value *= uniforms.alpha;";return` + ${v.registerUniforms(x).declareVariables(...M)} + var tile_a: array, ${l}>; + var tile_b: array, ${l}>; + ${v.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 = ${w.type.value}(0); + for (var t: u32 = 0u; t < num_tiles; t++) { + ${z} + k_start = k_start + ${l}; + workgroupBarrier(); + + for (var k: u32 = 0u; k < ${l}; k++) { + ${$} + } + workgroupBarrier(); + } + + ${R} + let m = tile_row_start + local_id.y; + let n = tile_col_start + local_id.x; + ${P!=null?`let cOffset = ${P.broadcastedIndicesToOffset("vec2(m, n)",w)}; value += ${w.type.value}(uniforms.beta) * ${P.getByOffset("cOffset")};`:""} + if (m < uniforms.M && n < uniforms.N) { + output[m * uniforms.N + n] = value; + } + }`};return c?{name:"GemmShared",shaderCache:{hint:`${r.cacheKey}`,inputDependencies:_},getRunData:()=>({outputs:[{dims:a,dataType:e[0].dataType}],dispatchGroup:{x:u*p},programUniforms:g}),getShaderSource:A}:{name:"Gemm",shaderCache:{hint:`${r.cacheKey}`,inputDependencies:_},getRunData:()=>({outputs:[{dims:a,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:g}),getShaderSource:E}},__=e=>{let r=e.transA,t=e.transB,s=e.alpha,i=e.beta;return{transA:r,transB:t,alpha:s,beta:i,cacheKey:`${e.transA};${e.transB};${e.alpha===1}`}},g_=(e,r)=>{f_(e.inputs),e.compute(m_(e.inputs,r))}}),Ts,Fs,bn,vn,w_,y_,M_,b_,v_,T_,x_,E_,P_,C_,Rv=Ve(()=>{pt(),Mt(),Yt(),Tt(),[Ts,Fs,bn,vn]=[0,1,2,3],w_=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")},y_=` + 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; + } +`,b_=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)); + `} + } +`,v_=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); + }`:""} +`,T_=(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[${Ts}] = batch; + indices[${Fs}] = channel;`+(()=>{switch(t.paddingMode){case"zeros":return` + if (r >= 0 && r < H && c >=0 && c < W) { + indices[${bn}] = u32(r); + indices[${vn}] = u32(c); + } + `;case"border":return` + indices[${bn}] = u32(clamp(r, 0, H - 1)); + indices[${vn}] = u32(clamp(c, 0, W - 1)); + `;case"reflection":return` + indices[${bn}] = gs_reflect(r, border[1], border[3]); + indices[${vn}] = gs_reflect(c, border[0], border[2]); + `;default:throw new Error(`padding mode ${t.paddingMode} is not supported`)}})()+` + return ${e.getByIndices("indices")}; + } +`,x_=(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[${Ts}], indices[${Fs}], 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[${Ts}], indices[${Fs}], border); + let p12 = pixel_at_grid(y1, x2, H_in, W_in, indices[${Ts}], indices[${Fs}], border); + let p21 = pixel_at_grid(y2, x1, H_in, W_in, indices[${Ts}], indices[${Fs}], border); + let p22 = pixel_at_grid(y2, x2, H_in, W_in, indices[${Ts}], indices[${Fs}], 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[${Ts}], indices[${Fs}], 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")}`,E_=(e,r)=>{let t=$e("x",e[0].dataType,e[0].dims.length),s=[e[1].dims[0],e[1].dims[1],e[1].dims[2]],i=$e("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]],[Ts,Fs,bn,vn]=[0,3,1,2]);let o=tt("output",e[0].dataType,n.length),a=t.type.value,l=Te.size(n),u=[{type:12,data:l},...nt(e[0].dims,s,n)],p=c=>` + ${c.registerUniform("output_size","u32").declareVariables(t,i,o)} + ${y_} + ${M_(a)} + ${b_(r)} + ${v_(r)} + ${T_(t,a,r)} + + ${c.mainStart()} + ${c.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let H_in = i32(uniforms.x_shape[${bn}]); + let W_in = i32(uniforms.x_shape[${vn}]); + + ${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 = ${o.offsetToIndices("global_idx")}; + var grid_indices = vec3(indices[${Ts}], indices[${bn}], indices[${vn}]); + let nxy = ${i.getByIndices("grid_indices")}; + var x = gs_denormalize(f32(nxy[0]), W_in); + var y = gs_denormalize(f32(nxy[1]), H_in); + + ${x_(o,a,r)} + }`;return{name:"GridSample",shaderCache:{hint:`${r.cacheKey}`,inputDependencies:["type","type"]},getRunData:c=>{let h=Te.size(n);return{outputs:[{dims:n,dataType:c[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:u}},getShaderSource:p}},P_=(e,r)=>{w_(e.inputs),e.compute(E_(e.inputs,r))},C_=e=>Dt({alignCorners:e.align_corners,mode:e.mode,paddingMode:e.padding_mode,format:e.format})}),$r,S_,$_,wu,k_,Bi,I_,A_=Ve(()=>{pt(),Mt(),Yt(),Bd(),Qd(),Tt(),Hs(),$r=(e,r)=>e.length>r&&e[r].dims.length>0?e[r]:void 0,S_=(e,r)=>{let t=e[0],s=$r(e,1),i=$r(e,2),n=$r(e,3),o=$r(e,4),a=$r(e,5),l=$r(e,6),u=$r(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],c=t.dims[1],h=t.dims.length===3?t.dims[2]:r.numHeads*t.dims[4],g=c,_=0,E=0,A=Math.floor(h/r.numHeads);if(l&&u&&Te.size(l.dims)&&Te.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]!==A)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]!==A)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],E=l.dims[2]}else if(l&&Te.size(l.dims)||u&&Te.size(u.dims))throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let v;if(s&&Te.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)');v=2,g=s.dims[1]}else if(s.dims.length===5){if(s.dims[2]!==r.numHeads||s.dims[3]!==2||s.dims[4]!==A)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(i)throw new Error('Expect "value" be none when "key" has packed kv format.');v=5,g=s.dims[1]}else{if(s.dims[1]!==r.numHeads||s.dims[3]!==A)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');v=0,g=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');v=3}if(n&&Te.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 y=_+g,k=0;if(o&&Te.size(o.dims)>0){k=8;let x=o.dims;throw x.length===1?x[0]===p?k=1:x[0]===3*p+2&&(k=3):x.length===2&&x[0]===p&&x[1]===y&&(k=5),k===8?new Error('Input "key_padding_mask" shape shall be (batch_size) or (batch_size, total_sequence_length)'):new Error("Mask not supported")}let P=!1,M=h;if(i&&Te.size(i.dims)>0){if(i.dims.length!==3&&i.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(t.dims[0]!==i.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(i.dims.length===3){if(g!==i.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');M=i.dims[2]}else{if(g!==i.dims[2])throw new Error('Input "key" and "value" shall have the same dim 2 (kv_sequence_length)');M=i.dims[1]*i.dims[3],P=!0}}let w=!1;if(o&&Te.size(o.dims)>0)throw new Error("Key padding mask is not supported");if(a&&Te.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]!==c||a.dims[3]!==y)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:p,sequenceLength:c,pastSequenceLength:_,kvSequenceLength:g,totalSequenceLength:y,maxSequenceLength:E,inputHiddenSize:0,hiddenSize:h,vHiddenSize:M,headSize:A,vHeadSize:Math.floor(M/r.numHeads),numHeads:r.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:r.maskFilterValue,maskType:k,scale:r.scale,broadcastResPosBias:w,passPastInKv:P,qkvFormat:v}},$_=e=>Dt({...e}),wu=Dt({perm:[0,2,1,3]}),k_=(e,r,t,s,i,n,o)=>{let a=[s,i,n],l=Te.size(a),u=[{type:12,data:l},{type:12,data:o},{type:12,data:n}],p=c=>{let h=tt("qkv_with_bias",r.dataType,a),g=$e("qkv",r.dataType,a),_=$e("bias",t.dataType,a),E=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return` + ${c.registerUniforms(E).declareVariables(g,_,h)} + ${c.mainStart()} + ${c.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]},Bi=(e,r,t,s,i,n,o,a)=>{let l=n;if(o&&Te.size(o.dims)>0){if(s===1)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return l=k_(e,n,o,r,s,t*i,a),l=l.reshape([r,s,t,i]),t===1||s===1?l:e.compute(Nr(l,wu.perm),{inputs:[l],outputs:[-1]})[0]}else return n.dims.length===3&&(l=n.reshape([r,s,t,i])),t===1||s===1?l:e.compute(Nr(l,wu.perm),{inputs:[l],outputs:[-1]})[0]},I_=(e,r)=>{let t=S_(e.inputs,r),s=e.inputs[0],i=$r(e.inputs,1),n=$r(e.inputs,2),o=$r(e.inputs,3),a=$r(e.inputs,4),l=$r(e.inputs,5),u=$r(e.inputs,6),p=$r(e.inputs,7);if(s.dims.length===5)throw new Error("Packed QKV is not implemented");if((i==null?void 0:i.dims.length)===5)throw new Error("Packed KV is not implemented");let c=i&&n&&i.dims.length===4&&n.dims.length===4,h=Bi(e,t.batchSize,t.numHeads,t.sequenceLength,t.headSize,s,o,0);if(c)return Fi(e,h,i,n,a,void 0,u,p,l,t);if(!i||!n)throw new Error("key and value must be provided");let g=Bi(e,t.batchSize,t.numHeads,t.kvSequenceLength,t.headSize,i,o,t.hiddenSize),_=Bi(e,t.batchSize,t.numHeads,t.kvSequenceLength,t.vHeadSize,n,o,2*t.hiddenSize);Fi(e,h,g,_,a,void 0,u,p,l,t)}}),F_,O_,D_,L_,yu,z_,B_,R_=Ve(()=>{pt(),Mt(),Yt(),Tt(),F_=e=>{if(!e||e.length<1)throw new Error("too few inputs")},O_=(e,r)=>{let t=[],s=r.numOutputs;return e[1].dims[0]>0&&(e[1].getBigInt64Array().forEach(i=>t.push(Number(i))),s=t.length),Dt({numOutputs:s,axis:r.axis,splitSizes:t})},D_=e=>` +fn calculateOutputIndex(index: u32) -> u32 { + for (var i: u32 = 0u; i < ${e}u; i += 1u ) { + if (index < ${rt("uniforms.size_in_split_axis","i",e)}) { + return i; + } + } + return ${e}u; +}`,L_=e=>{let r=e.length,t=[];for(let s=0;s{let t=e[0].dims,s=Te.size(t),i=e[0].dataType,n=Te.normalizeAxis(r.axis,t.length),o=new Array(r.numOutputs),a=$e("input",i,t.length),l=new Array(r.numOutputs),u=[],p=[],c=0,h=[{type:12,data:s}];for(let _=0;_` + ${_.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",l.length).declareVariables(a,...o)} + ${D_(l.length)} + ${L_(o)} + + ${_.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 -= ${rt("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:g,getRunData:()=>({outputs:u,dispatchGroup:{x:Math.ceil(s/64)},programUniforms:h})}},z_=(e,r)=>{F_(e.inputs);let t=e.inputs.length===1?r:O_(e.inputs,r);e.compute(yu(e.inputs,t),{inputs:[0]})},B_=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 Dt({axis:r,numOutputs:s,splitSizes:t})}}),N_,j_,Mu,V_,Nv=Ve(()=>{Yt(),Qd(),A_(),R_(),Hs(),N_=(e,r)=>{if(r.doRotary)throw new Error("GroupQuerryAttention do_rotary attribute is not supported");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],i=e[2],n=e[3],o=e[4];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],c=u,h=0,g=!s||s.dims.length===0,_=Math.floor(g?p/(r.numHeads+2*r.kvNumHeads):p/r.numHeads);g&&(p=_*r.numHeads);let E=n&&n.dims.length!==0,A=o&&o.dims.length!==0;if(E&&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(E&&A){if(n.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(o.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');h=n.dims[2]}else if(E||A)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let v=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"');c=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(i)throw new Error('Expect "value" be none when "key" has packed kv format.');c=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');c=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');v=3}let y=0,k=!1,P=r.kvNumHeads?_*r.kvNumHeads:p;if(i&&i.dims.length>0){if(i.dims.length!==3&&i.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(t.dims[0]!==i.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(i.dims.length===3){if(c!==i.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');P=i.dims[2]}else{if(c!==i.dims[2])throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');P=i.dims[1]*i.dims[3],k=!0}}let M=e.length>4?e[5]:void 0;if(M&&M.dims.length!==1&&M.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:h,kvSequenceLength:c,totalSequenceLength:-1,maxSequenceLength:-1,inputHiddenSize:0,hiddenSize:p,vHiddenSize:P,headSize:_,vHeadSize:Math.floor(P/r.kvNumHeads),numHeads:r.numHeads,kvNumHeads:r.kvNumHeads,nReps:r.numHeads/r.kvNumHeads,pastPresentShareBuffer:!1,maskType:y,scale:r.scale,broadcastResPosBias:!1,passPastInKv:k,qkvFormat:v}},j_=Dt({perm:[0,2,1,3]}),Mu=(e,r,t)=>{let s=r,i=t.kvNumHeads;return r.dims.length===3&&t.kvSequenceLength!==0&&(s=r.reshape([t.batchSize,t.kvSequenceLength,i,t.headSize]),s=e.compute(Nr(s,j_.perm),{inputs:[s],outputs:[-1]})[0]),s},V_=(e,r)=>{var A;let t=N_(e.inputs,r);if(e.inputs[0].dims.length===5)throw new Error("Packed QKV is not implemented");if(((A=e.inputs[1])==null?void 0:A.dims.length)===5)throw new Error("Packed KV is not implemented");let s=e.inputs[0],i=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,o=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,c=Dt({axis:2,numOutputs:3,splitSizes:[t.numHeads*t.headSize,p*t.headSize,p*t.headSize]}),[h,g,_]=!i&&!n?e.compute(yu([s],c),{inputs:[s],outputs:[-1,-1,-1]}):[s,i,n],E=Bi(e,t.batchSize,t.numHeads,t.sequenceLength,t.headSize,h,void 0,0);Fi(e,E,Mu(e,g,t),Mu(e,_,t),void 0,void 0,o,a,void 0,t,l,u)}}),bu,U_,W_,G_,jv=Ve(()=>{pt(),Mt(),Hs(),Tt(),bu=(e,r,t,s,i,n,o,a)=>{let l=Xt(n),u=l===1?"f32":`vec${l}f`,p=l===1?"vec2f":`mat2x${l}f`,c=i*o,h=64;c===1&&(h=256);let g=[i,o,n/l],_=[i,o,2],E=["rank","type","type"],A=[];A.push(...nt(g,_));let v=y=>{let k=$e("x",r.dataType,3,l),P=$e("scale",t.dataType,t.dims),M=$e("bias",s.dataType,s.dims),w=tt("output",1,3,2),x=[k,P,M,w];return` + var workgroup_shared : array<${p}, ${h}>; + const workgroup_size = ${h}u; + ${y.declareVariables(...x)} + ${y.mainStart(h)} + 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}(${k.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 = ${Ks("workgroup_shared[0][0]",l)} / f32(hight * ${l}); + let squared_sum_final = ${Ks("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};${h}`,inputDependencies:E},getRunData:()=>({outputs:[{dims:_,dataType:1}],dispatchGroup:{x:c},programUniforms:A}),getShaderSource:v},{inputs:[r,t,s],outputs:[-1]})[0]},U_=(e,r,t)=>{let s=r[0].dims,i=s,n=2,o=s[0],a=s[1],l=Te.sizeFromDimension(s,n),u=Xt(l),p=Te.size(i)/u,c=bu(e,r[0],r[1],r[2],o,l,a,t.epsilon),h=[o,a,l/u],g=[o,a],_=["type","none"],E=A=>{let v=$e("x",r[0].dataType,h.length,u),y=$e("scale_shift",1,g.length,2),k=tt("output",r[0].dataType,h.length,u),P=[v,y,k];return` + ${A.registerUniform("output_size","u32").declareVariables(...P)} + ${A.mainStart()} + ${A.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let outputIndices = ${k.offsetToIndices("global_idx")}; + let batch = outputIndices[0]; + let channel = outputIndices[1]; + let scale_shift = ${y.getByIndices("vec2(batch, channel)")}; + let value = ${v.getByOffset("global_idx")} * ${k.type.value}(scale_shift.x) + ${k.type.value}(scale_shift.y); + ${k.setByOffset("global_idx","value")}; + }`};e.compute({name:"InstanceNormalization",shaderCache:{hint:`${u}`,inputDependencies:_},getRunData:()=>({outputs:[{dims:i,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:[{type:12,data:p},...nt(h,g,h)]}),getShaderSource:E},{inputs:[r[0],c]})},W_=(e,r,t)=>{let s=r[0].dims,i=s,n=s[0],o=s[s.length-1],a=Te.sizeFromDimension(s,1)/o,l=Xt(o),u=Te.size(i)/l,p=[{type:12,data:a},{type:12,data:Math.floor(o/l)}],c=["type","type"],h=!1,g=[0,s.length-1];for(let v=0;vs[g[y]])),E=bu(e,_,r[1],r[2],n,a,o,t.epsilon),A=v=>{let y=lr(r[0].dataType),k=l===1?"vec2f":`mat${l}x2f`,P=x=>{let $=x===0?"x":"y",z=l===1?"f32":`vec${l}f`;switch(l){case 1:return`${y}(${z}(scale.${$}))`;case 2:return`vec2<${y}>(${z}(scale[0].${$}, scale[1].${$}))`;case 4:return`vec4<${y}>(${z}(scale[0].${$}, scale[1].${$}, scale[2].${$}, scale[3].${$}))`;default:throw new Error(`Not supported compoents ${l}`)}},M=$e("input",r[0].dataType,r[0].dims,l),w=tt("output",r[0].dataType,i,l);return` + @group(0) @binding(0) var input : array<${M.type.storage}>; + @group(0) @binding(1) var scale_input : array<${k}>; + @group(0) @binding(2) var output : array<${w.type.storage}>; + struct Uniforms {H: u32, C : u32}; + @group(0) @binding(3) var uniforms: Uniforms; + + ${v.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], ${P(0)}, ${P(1)}); + }`};e.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${l}`,inputDependencies:c},getRunData:()=>({outputs:[{dims:i,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:p}),getShaderSource:A},{inputs:[r[0],E]})},G_=(e,r)=>{r.format==="NHWC"?W_(e,e.inputs,r):U_(e,e.inputs,r)}}),K_,H_,q_,Vv=Ve(()=>{pt(),Mt(),Tt(),K_=e=>{if(!e||e.length<2)throw new Error("layerNorm requires at least 2 inputs.")},H_=(e,r,t)=>{let s=r.simplified,i=e[0].dims,n=e[1],o=!s&&e[2],a=i,l=Te.normalizeAxis(r.axis,i.length),u=Te.sizeToDimension(i,l),p=Te.sizeFromDimension(i,l),c=Te.size(n.dims),h=o?Te.size(o.dims):0;if(c!==p||o&&h!==p)throw new Error(`Size of X.shape()[axis:] == ${p}. + Size of scale and bias (if provided) must match this. + Got scale size of ${c} and bias size of ${h}`);let g=[];for(let M=0;M1,y=t>2,k=M=>{let w=lr(e[0].dataType),x=[$e("x",e[0].dataType,e[0].dims,_),$e("scale",n.dataType,n.dims,_)];o&&x.push($e("bias",o.dataType,o.dims,_)),x.push(tt("output",e[0].dataType,a,_)),v&&x.push(tt("mean_data_output",1,g)),y&&x.push(tt("inv_std_output",1,g));let $=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return` + ${M.registerUniforms($).declareVariables(...x)} + ${M.mainStart()} + ${M.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")} + let offset = global_idx * uniforms.norm_size_vectorized; + var mean_vector = ${Vd("f32",_)}; + var mean_square_vector = ${Vd("f32",_)}; + + for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) { + let value = ${Vn(w,_,"x[h + offset]")}; + mean_vector += value; + mean_square_vector += value * value; + } + let mean = ${Ks("mean_vector",_)} / uniforms.norm_size; + let inv_std_dev = inverseSqrt(${Ks("mean_square_vector",_)} / uniforms.norm_size ${s?"":"- mean * mean"} + uniforms.epsilon); + + for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) { + let f32input = ${Vn(w,_,"x[j + offset]")}; + let f32scale = ${Vn(w,_,"scale[j]")}; + output[j + offset] = ${x[0].type.value}((f32input ${s?"":"- mean"}) * inv_std_dev * f32scale + ${o?`+ ${Vn(w,_,"bias[j]")}`:""} + ); + } + + ${v?"mean_data_output[global_idx] = mean":""}; + ${y?"inv_std_output[global_idx] = inv_std_dev":""}; + }`},P=[{dims:a,dataType:e[0].dataType}];return v&&P.push({dims:g,dataType:1}),y&&P.push({dims:g,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${_};${t};${s}`,inputDependencies:E},getRunData:()=>({outputs:P,dispatchGroup:{x:Math.ceil(u/64)},programUniforms:A}),getShaderSource:k}},q_=(e,r)=>{K_(e.inputs),e.compute(H_(e.inputs,r,e.outputCount))}}),Q_,X_,Uv=Ve(()=>{Mt(),su(),au(),Q_=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.")},X_=e=>{Q_(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(ru(e.inputs,{activation:""},r));else{let i=r[r.length-2],n=Te.size(e.inputs[0].dims.slice(0,-2)),o=Te.size(e.inputs[1].dims.slice(0,-2));if(n!==1&&i===1&&o===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(Ca(p,{activation:""},r,u),{inputs:p})}else e.compute(Ca(e.inputs,{activation:""},r))}}}),J_,Y_,Z_,eg,tg,Wv=Ve(()=>{pt(),Mt(),Yt(),Tt(),J_=(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 i=Math.floor((r.k+r.blockSize-1)/r.blockSize),n=r.blockSize/8*r.bits,o=e[1];if(!Te.areEqual(o.dims,[r.n,i,n]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let a=e[2].dims;if(Te.size(a)!==r.n*i)throw new Error("scales input size error.");if(e.length===4){let l=e[3].dims,u=r.bits>4?r.n*i:r.n*Math.floor((i+1)/2);if(Te.size(l)!==u)throw new Error("zeroPoints input size error.")}},Y_=(e,r)=>{let t=e[0].dims,s=t.length,i=t[s-2],n=r.k,o=r.n,a=t.slice(0,s-2),l=Te.size(a),u=e[1].dims[2]/4,p=e[0].dataType,c=Xt(r.k),h=Xt(u),g=Xt(o),_=a.concat([i,o]),E=i>1&&o/g%2===0?2:1,A=Te.size(_)/g/E,v=64,y=[],k=[l,i,n/c],P=Te.convertShape(e[1].dims).slice();P.splice(-1,1,u/h),y.push(...nt(k)),y.push(...nt(P)),y.push(...nt(e[2].dims)),e.length===4&&y.push(...nt(Te.convertShape(e[3].dims)));let M=[l,i,o/g];y.push(...nt(M));let w=x=>{let $=k.length,z=$e("a",e[0].dataType,$,c),R=$e("b",12,P.length,h),Q=$e("scales",e[2].dataType,e[2].dims.length),q=[z,R,Q],U=e.length===4?$e("zero_points",12,e[3].dims.length):void 0;U&&q.push(U);let Z=M.length,H=tt("output",e[0].dataType,Z,g),J=lr(e[0].dataType),ie=(()=>{switch(c){case 1:return`array<${J}, 8>`;case 2:return`mat4x2<${J}>`;case 4:return`mat2x4<${J}>`;default:throw new Error(`${c}-component is not supported.`)}})(),ae=()=>{let N=` + // reuse a data + var input_offset = ${z.indicesToOffset(`${z.type.indices}(batch, row, word_offset)`)}; + var a_data: ${ie}; + for (var j: u32 = 0; j < ${8/c}; j++) { + a_data[j] = ${z.getByOffset("input_offset")}; + input_offset++; + } + `;for(let O=0;O> 4) & b_mask); + b_quantized_values = ${ie}(${Array.from({length:4},(G,se)=>`${J}(b_value_lower[${se}]), ${J}(b_value_upper[${se}])`).join(", ")}); + b_dequantized_values = ${c===1?`${ie}(${Array.from({length:8},(G,se)=>`(b_quantized_values[${se}] - ${U?`zero_point${O}`:"zero_point"}) * scale${O}`).join(", ")});`:`(b_quantized_values - ${ie}(${Array(8).fill(`${U?`zero_point${O}`:"zero_point"}`).join(",")})) * scale${O};`}; + workgroup_shared[local_id.x * ${E} + ${Math.floor(O/g)}]${g>1?`[${O%g}]`:""} += ${Array.from({length:8/c},(G,se)=>`${c===1?`a_data[${se}] * b_dequantized_values[${se}]`:`dot(a_data[${se}], b_dequantized_values[${se}])`}`).join(" + ")}; + `;return N},ue=()=>{let N=` + var col_index = col * ${g}; + ${U?` + 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 = ${J}(8);`} + `;for(let O=0;O> 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 = ${U.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; + let zero_point${O} = ${J}((zero_point_word) & 0xFu);`:""} + col_index += 1;`;return N},he=()=>{let N=`col_index = col * ${g};`;for(let O=0;O; + var b_value_upper: vec4; + var b_quantized_values: ${ie}; + var b_dequantized_values: ${ie};`,N};return` + var workgroup_shared: array<${H.type.value}, ${E*v}>; + ${x.declareVariables(...q,H)} + ${x.mainStart([v,1,1])} + let output_indices = ${H.offsetToIndices(`(global_idx / ${v}) * ${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 += ${v}) { + //process one block + var word_offset: u32 = block * ${r.blockSize/c}; + ${ue()} + for (var word: u32 = 0; word < ${u}; word += ${h}) { + ${he()} + for (var i: u32 = 0; i < ${h}; i++) { + ${ae()} + word_offset += ${8/c}; + } + } + } + workgroupBarrier(); + + if (local_id.x < ${E}) { + var output_value: ${H.type.value} = ${H.type.value}(0); + var workgroup_shared_offset: u32 = local_id.x; + for (var b: u32 = 0u; b < ${v}u; b++) { + output_value += workgroup_shared[workgroup_shared_offset]; + workgroup_shared_offset += ${E}; + } + ${H.setByIndices(`${H.type.indices}(batch, row, col + local_id.x)`,"output_value")}; + } + }`};return{name:"MatMulNBits",shaderCache:{hint:`${r.blockSize};${r.bits};${c};${h};${g};${E};${v}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:_,dataType:p}],dispatchGroup:{x:A},programUniforms:y}),getShaderSource:w}},Z_=(e,r)=>{let t=e[0].dims,s=t.length,i=t[s-2],n=r.k,o=r.n,a=t.slice(0,s-2),l=Te.size(a),u=e[1].dims[2]/4,p=e[0].dataType,c=Xt(r.k),h=Xt(u),g=a.concat([i,o]),_=128,E=o%8===0?8:o%4===0?4:1,A=_/E,v=A*h*8,y=v/c,k=v/r.blockSize,P=Te.size(g)/E,M=[],w=[l,i,n/c],x=Te.convertShape(e[1].dims).slice();x.splice(-1,1,u/h),M.push(...nt(w)),M.push(...nt(x)),M.push(...nt(e[2].dims)),e.length===4&&M.push(...nt(Te.convertShape(e[3].dims)));let $=[l,i,o];M.push(...nt($));let z=R=>{let Q=w.length,q=$e("a",e[0].dataType,Q,c),U=$e("b",12,x.length,h),Z=$e("scales",e[2].dataType,e[2].dims.length),H=[q,U,Z],J=e.length===4?$e("zero_points",12,e[3].dims.length):void 0;J&&H.push(J);let ie=$.length,ae=tt("output",e[0].dataType,ie),ue=lr(e[0].dataType),he=()=>{switch(c){case 1:return` + let a_data0 = vec4<${ue}>(sub_a[word_offset], sub_a[word_offset + 1], sub_a[word_offset + 2], sub_a[word_offset + 3]); + let a_data1 = vec4<${ue}>(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<${ue}>(sub_a[word_offset], sub_a[word_offset + 1]); + let a_data1 = vec4<${ue}>(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(`${c}-component is not supported.`)}};return` + var sub_a: array<${q.type.value}, ${y}>; + var inter_results: array, ${E}>; + ${R.declareVariables(...H,ae)} + ${R.mainStart([A,E,1])} + let output_indices = ${ae.offsetToIndices(`workgroup_index * ${E}`)}; + 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) / ${k} + 1; + + // Loop over shared dimension. + for (var tile: u32 = 0; tile < num_tiles; tile += 1) { + let a_col_start = tile * ${y}; + // load one tile A data into shared memory. + for (var a_offset = local_idx; a_offset < ${y}; a_offset += ${_}) + { + let a_col = a_col_start + a_offset; + if (a_col < uniforms.a_shape[2]) + { + sub_a[a_offset] = ${q.getByIndices(`${q.type.indices}(batch, row, a_col)`)}; + } else { + sub_a[a_offset] = ${q.type.value}(0); + } + } + workgroupBarrier(); + + // each thread process one block + let b_row = col + local_id.y; + let block = tile * ${k} + local_id.x; + ${J?` + 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 = ${J.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; + let zero_point = ${ue}((zero_point_word) & 0xFu);`:` + // The default zero point is 8 for unsigned 4-bit quantization. + let zero_point = ${ue}(8);`} + let scale = ${Z.getByOffset("b_row * n_blocks_per_col + block")}; + let b_data = ${U.getByIndices(`${U.type.indices}(b_row, block, 0)`)}; + var word_offset = local_id.x * ${r.blockSize/c}; + for (var i: u32 = 0; i < ${h}; i++) { + ${he()} + let b_value = ${h===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<${ue}>(${Array.from({length:4},(N,O)=>`${ue}(b_value_lower[${O}]), ${ue}(b_value_upper[${O}])`).join(", ")}); + let b_dequantized_values = (b_quantized_values - mat2x4<${ue}>(${Array(8).fill("zero_point").join(",")})) * scale; + inter_results[local_id.y][local_id.x] += ${Array.from({length:2},(N,O)=>`${`dot(a_data${O}, b_dequantized_values[${O}])`}`).join(" + ")}; + word_offset += ${8/c}; + } + workgroupBarrier(); + } + + if (local_idx < ${E}) { + var output_value: ${ae.type.value} = ${ae.type.value}(0); + for (var b = 0u; b < ${A}; b++) { + output_value += inter_results[local_idx][b]; + } + if (col + local_idx < uniforms.output_shape[2]) + { + ${ae.setByIndices(`${ae.type.indices}(batch, row, col + local_idx)`,"output_value")} + } + } + }`};return{name:"BlockwiseMatMulNBits32",shaderCache:{hint:`${r.blockSize};${c};${h};${A};${E}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:g,dataType:p}],dispatchGroup:{x:P},programUniforms:M}),getShaderSource:z}},eg=(e,r)=>{J_(e.inputs,r),r.blockSize===32&&e.adapterInfo.isVendor("intel")&&e.adapterInfo.isArchitecture("gen-12lp")?e.compute(Z_(e.inputs,r)):e.compute(Y_(e.inputs,r))},tg=e=>Dt(e)}),rg,sg,ng,ig,og,ag,lg,dg,ug,Gv=Ve(()=>{pt(),Mt(),Tt(),rg=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].")}},sg=(e,r,t)=>{let s="";for(let i=r-1;i>=0;--i)s+=` + k = i32(${e.indicesGet("indices",i)}) - ${rt("uniforms.pads",i,t)}; + if (k < 0) { + break; + } + if (k >= i32(${rt("uniforms.x_shape",i,r)})) { + break; + } + offset += k * i32(${rt("uniforms.x_strides",i,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]; + } + `},ng=(e,r,t)=>{let s="";for(let i=r-1;i>=0;--i)s+=` + k = i32(${e.indicesGet("indices",i)}) - ${rt("uniforms.pads",i,t)}; + if (k < 0) { + k = -k; + } + { + let _2n_1 = 2 * (i32(${rt("uniforms.x_shape",i,r)}) - 1); + k = k % _2n_1; + if(k >= i32(${rt("uniforms.x_shape",i,r)})) { + k = _2n_1 - k; + } + } + offset += k * i32(${rt("uniforms.x_strides",i,r)}); + `;return` + var offset = 0; + var k = 0; + ${s} + value = x[offset]; + `},ig=(e,r,t)=>{let s="";for(let i=r-1;i>=0;--i)s+=` + k = i32(${e.indicesGet("indices",i)}) - ${rt("uniforms.pads",i,t)}; + if (k < 0) { + k = 0; + } + if (k >= i32(${rt("uniforms.x_shape",i,r)})) { + k = i32(${rt("uniforms.x_shape",i,r)}) - 1; + } + offset += k * i32(${rt("uniforms.x_strides",i,r)}); + `;return` + var offset = 0; + var k = 0; + ${s} + value = x[offset]; + `},og=(e,r,t)=>{let s="";for(let i=r-1;i>=0;--i)s+=` + k = i32(${e.indicesGet("indices",i)}) - ${rt("uniforms.pads",i,t)}; + if (k < 0) { + k += i32(${rt("uniforms.x_shape",i,r)}]); + } + if (k >= i32(${rt("uniforms.x_shape",i,r)})) { + k -= i32(${rt("uniforms.x_shape",i,r)}); + } + offset += k * i32(${rt("uniforms.x_strides",i,r)}); + `;return` + var offset = 0; + var k = 0; + ${s} + value = x[offset]; + `},ag=(e,r,t)=>{switch(t.mode){case 0:return sg(e,r,t.pads.length);case 1:return ng(e,r,t.pads.length);case 2:return ig(e,r,t.pads.length);case 3:return og(e,r,t.pads.length);default:throw new Error("Invalid mode")}},lg=(e,r)=>{let t=Te.padShape(e[0].dims.slice(),r.pads),s=e[0].dims,i=Te.size(t),n=[{type:12,data:i},{type:6,data:r.pads}],o=e.length>=3&&e[2].data;r.mode===0&&n.push({type:o?e[2].dataType:1,data:r.value}),n.push(...nt(e[0].dims,t));let a=["rank"],l=u=>{let p=tt("output",e[0].dataType,t.length),c=$e("x",e[0].dataType,s.length),h=c.type.value,g=ag(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:o?h:"f32"}),` + ${u.registerUniforms(_).declareVariables(c,p)} + ${u.mainStart()} + ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${p.offsetToIndices("global_idx")}; + + var value = ${h}(0); + ${g} + output[global_idx] = value; + }`};return{name:"Pad",shaderCache:{hint:`${r.mode}${o}`,inputDependencies:a},getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(Te.size(t)/64)},programUniforms:n}),getShaderSource:l}},dg=(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,i=e[0].dims.length,n=new Int32Array(2*i).fill(0);if(e.length>=4){let a=e[3].getBigInt64Array();for(let l=0;ln[Number(l)]=Number(a));let o=[];return n.forEach(a=>o.push(a)),{mode:r.mode,value:s,pads:o}}else return r},ug=(e,r)=>{rg(e.inputs);let t=dg(e.inputs,r);e.compute(lg(e.inputs,t),{inputs:[0]})}}),Ri,vu,Tu,xu,Eu,cg,pg,Pu,Cu,hg,fg,Su,mg,_g,$u,gg,wg,yg,Mg,Kv=Ve(()=>{ns(),pt(),Mt(),Tt(),Ri=e=>{if(Ut.webgpu.validateInputContent&&(!e||e.length!==1))throw new Error("Pool ops requires 1 input.")},vu=(e,r,t)=>{let s=r.format==="NHWC",i=e.dims.slice();s&&i.splice(1,0,i.pop());let n=Object.hasOwnProperty.call(r,"dilations"),o=r.kernelShape.slice(),a=r.strides.slice(),l=n?r.dilations.slice():[],u=r.pads.slice();va.adjustPoolAttributes(t,i,o,a,l,u);let p=va.computePoolOutputShape(t,i,a,l,o,u,r.autoPad),c=Object.assign({},r);n?Object.assign(c,{kernelShape:o,strides:a,pads:u,dilations:l,cacheKey:r.cacheKey}):Object.assign(c,{kernelShape:o,strides:a,pads:u,cacheKey:r.cacheKey});let h=p.slice();return h.push(h.splice(1,1)[0]),[c,s?h:p]},Tu=(e,r)=>{let t=r.format==="NHWC",s=Te.size(e),i=Te.size(r.kernelShape),n=[{type:12,data:s},{type:12,data:i}],o=[{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],c=!!(u+p);n.push({type:12,data:a},{type:12,data:l},{type:12,data:u},{type:12,data:p}),o.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let h=!1;if(r.kernelShape.length===2){let g=r.kernelShape[r.kernelShape.length-2],_=r.strides[r.strides.length-2],E=r.pads[r.pads.length/2-2],A=r.pads[r.pads.length-2];h=!!(E+A),n.push({type:12,data:g},{type:12,data:_},{type:12,data:E},{type:12,data:A}),o.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[n,o,!0,c,h]}else{if(t)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let a=Te.computeStrides(r.kernelShape);n.push({type:12,data:a},{type:12,data:r.pads},{type:12,data:r.strides}),o.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,o,!!l,!1,!1]}},xu=(e,r,t,s,i,n,o,a,l,u,p,c)=>{let h=i.format==="NHWC",g=r.type.value,_=tt("output",r.type.tensor,s);if(i.kernelShape.length<=2){let E="",A="",v="",y=t-(h?2:1);if(p?E=` + for (var i: u32 = 0u; i < uniforms.kw; i++) { + xIndices[${y}] = indices[${y}] * uniforms.sw - uniforms.pwStart + i; + if (xIndices[${y}] < 0 || xIndices[${y}] + >= uniforms.x_shape[${y}]) { + pad++; + continue; + } + let x_val = x[${r.indicesToOffset("xIndices")}]; + ${n} + }`:E=` + for (var i: u32 = 0u; i < uniforms.kw; i++) { + xIndices[${y}] = indices[${y}] * uniforms.sw - uniforms.pwStart + i; + let x_val = x[${r.indicesToOffset("xIndices")}]; + ${n} + }`,i.kernelShape.length===2){let k=t-(h?3:2);c?A=` + for (var j: u32 = 0u; j < uniforms.kh; j++) { + xIndices[${k}] = indices[${k}] * uniforms.sh - uniforms.phStart + j; + if (xIndices[${k}] < 0 || xIndices[${k}] >= uniforms.x_shape[${k}]) { + pad += i32(uniforms.kw); + continue; + } + `:A=` + for (var j: u32 = 0u; j < uniforms.kh; j++) { + xIndices[${k}] = indices[${k}] * uniforms.sh - uniforms.phStart + j; + `,v=` + } + `}return` + ${e.registerUniforms(l).declareVariables(r,_)} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + + let indices = ${_.offsetToIndices("global_idx")}; + var xIndices = ${_.offsetToIndices("global_idx")}; + + var value = ${g}(${a}); + var pad = 0; + ${A} + ${E} + ${v} + ${o} + + output[global_idx] = value; + }`}else{if(h)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let E=i.kernelShape.length,A=i.pads.length,v="";return u?v=` + if (xIndices[j] >= uniforms.x_shape[j]) { + pad++; + isPad = true; + break; + } + } + if (!isPad) { + let x_val = x[${r.indicesToOffset("xIndices")}]; + ${n} + }`:v=` + } + 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 = ${g}(${a}); + 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 / ${rt("uniforms.kernelStrides","j",E)}; + offset -= offsets[j] * ${rt("uniforms.kernelStrides","j",E)}; + } + offsets[${E-1}] = offset; + + isPad = false; + for (var j = ${t-E}u; j < ${t}u; j++) { + xIndices[j] = indices[j] * ${rt("uniforms.strides",`j - ${t-E}u`,E)} + + offsets[j - ${t-E}u] - ${rt("uniforms.pads","j - 2u",A)}; + ${v} + } + ${o} + + output[global_idx] = value; + }`}},Eu=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,cg=e=>`${Eu(e)};${e.countIncludePad}`,pg=e=>`${Eu(e)};${e.storageOrder};${e.dilations}`,Pu=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}),Cu=(e,r,t,s)=>{let[i,n]=vu(r,s,t),o=$e("x",r.dataType,r.dims.length),a=o.type.value,l="value += x_val;",u="";i.countIncludePad?u+=`value /= ${a}(uniforms.kernelSize);`:u+=`value /= ${a}(i32(uniforms.kernelSize) - pad);`;let[p,c,h,g,_]=Tu(n,i);p.push(...nt(r.dims,n));let E=["rank"];return{name:e,shaderCache:{hint:`${s.cacheKey};${h};${g};${_}`,inputDependencies:E},getRunData:()=>({outputs:[{dims:n,dataType:r.dataType}],dispatchGroup:{x:Math.ceil(Te.size(n)/64)},programUniforms:p}),getShaderSource:A=>xu(A,o,r.dims.length,n.length,i,l,u,0,c,h,g,_)}},hg=e=>{let r=e.count_include_pad!==0,t=Pu(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:cg(s)}},fg=(e,r)=>{Ri(e.inputs),e.compute(Cu("AveragePool",e.inputs[0],!1,r))},Su={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},mg=e=>{let r=e.format;return{format:r,...Su,cacheKey:r}},_g=(e,r)=>{Ri(e.inputs),e.compute(Cu("GlobalAveragePool",e.inputs[0],!0,r))},$u=(e,r,t,s)=>{let[i,n]=vu(r,s,t),o=` + value = max(x_val, value); + `,a="",l=$e("x",r.dataType,r.dims.length),u=["rank"],[p,c,h,g,_]=Tu(n,i);return p.push(...nt(r.dims,n)),{name:e,shaderCache:{hint:`${s.cacheKey};${h};${g};${_}`,inputDependencies:u},getRunData:()=>({outputs:[{dims:n,dataType:r.dataType}],dispatchGroup:{x:Math.ceil(Te.size(n)/64)},programUniforms:p}),getShaderSource:E=>xu(E,l,r.dims.length,n.length,i,o,a,r.dataType===10?-65504:-1e5,c,h,g,_)}},gg=(e,r)=>{Ri(e.inputs),e.compute($u("MaxPool",e.inputs[0],!1,r))},wg=e=>{let r=e.storage_order,t=e.dilations,s=Pu(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 i={storageOrder:r,dilations:t,...s,cacheKey:""};return{...i,cacheKey:pg(i)}},yg=e=>{let r=e.format;return{format:r,...Su,cacheKey:r}},Mg=(e,r)=>{Ri(e.inputs),e.compute($u("GlobalMaxPool",e.inputs[0],!0,r))}}),bg,vg,Tg,xg,Hv=Ve(()=>{pt(),Mt(),Yt(),Tt(),bg=(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((i,n)=>n===r.axis||i===e[0].dims[n]).reduce((i,n)=>i&&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)].")}},vg=(e,r)=>{let t=Te.normalizeAxis(r.axis,e[0].dims.length),s=e[0].dataType,i=s===3,n=e[0].dims,o=e[1].dataType,a=Te.size(n),l=s===3||s===2,u=l?[Math.ceil(Te.size(e[0].dims)/4)]:e[0].dims,p=e[1].dims,c=e.length>2?e[2]:void 0,h=c?l?[Math.ceil(Te.size(c.dims)/4)]:c.dims:void 0,g=p.length===0||p.length===1&&p[0]===1,_=g===!1&&p.length===1,E=Xt(a),A=g&&(!l||E===4),v=A?E:1,y=A&&!l?E:1,k=$e("input",l?12:s,u.length,y),P=$e("scale",o,p.length),M=c?$e("zero_point",l?12:s,h.length):void 0,w=tt("output",o,n.length,v),x=[k,P];M&&x.push(M);let $=[u,p];c&&$.push(h);let z=[{type:12,data:a/v},{type:12,data:t},{type:12,data:r.blockSize},...nt(...$,n)],R=Q=>{let q=[{name:"output_size",type:"u32"},{name:"axis",type:"u32"},{name:"block_size",type:"u32"}];return` + ${Q.registerUniforms(q).declareVariables(...x,w)} + ${Q.mainStart()} + ${Q.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let output_indices = ${w.offsetToIndices("global_idx")}; + + // Set input x + ${l?` + let input = ${k.getByOffset("global_idx / 4")}; + let x_vec = ${i?"unpack4xI8(input)":"unpack4xU8(input)"}; + let x_value = ${v===1?"x_vec[global_idx % 4]":"x_vec"};`:`let x_value = ${k.getByOffset("global_idx")};`}; + + // Set scale input + ${g?`let scale_value= ${P.getByOffset("0")}`:_?` + let scale_index = ${w.indicesGet("output_indices","uniforms.axis")}; + let scale_value= ${P.getByOffset("scale_index")};`:` + var scale_indices: ${P.type.indices} = output_indices; + let index = ${P.indicesGet("scale_indices","uniforms.axis")} / uniforms.block_size; + ${P.indicesSet("scale_indices","uniforms.axis","index")}; + let scale_value= ${P.getByIndices("scale_indices")};`}; + + // Set zero-point input + ${M?g?l?` + let zero_point_input = ${M.getByOffset("0")}; + let zero_point_vec = ${i?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; + let zero_point_value= zero_point_vec[0]`:`let zero_point_value = ${M.getByOffset("0")}`:_?l?` + let zero_point_index = ${w.indicesGet("output_indices","uniforms.axis")}; + let zero_point_input = ${M.getByOffset("zero_point_index / 4")}; + let zero_point_vec = ${i?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; + let zero_point_value = zero_point_vec[zero_point_index % 4]`:` + let zero_point_index = ${w.indicesGet("output_indices","uniforms.axis")}; + let zero_point_value = ${M.getByOffset("zero_point_index")};`:l?` + let zero_point_offset = ${P.indicesToOffset("scale_indices")}; + let zero_point_input = ${M.getByOffset("zero_point_offset / 4")}; + let zero_point_vec = ${i?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; + let zero_point_value = zero_point_vec[zero_point_offset % 4];`:`let zero_point_value = ${M.getByIndices("scale_indices")};`:`let zero_point_value = ${l?i?"i32":"u32":k.type.value}(0);`}; + // Compute and write output + ${w.setByOffset("global_idx",`${w.type.value}(x_value - zero_point_value) * scale_value`)}; + }`};return{name:"DequantizeLinear",shaderCache:{hint:r.cacheKey,inputDependencies:M?["rank","rank","rank"]:["rank","rank"]},getShaderSource:R,getRunData:()=>({outputs:[{dims:n,dataType:o}],dispatchGroup:{x:Math.ceil(a/v/64),y:1,z:1},programUniforms:z})}},Tg=(e,r)=>{bg(e.inputs,r),e.compute(vg(e.inputs,r))},xg=e=>Dt({axis:e.axis,blockSize:e.blockSize})}),Eg,Pg,Cg,qv=Ve(()=>{ns(),pt(),Tt(),Eg=(e,r,t)=>{let s=e===r,i=er&&t>0;if(s||i||n)throw new Error("Range these inputs' contents are invalid.")},Pg=(e,r,t,s)=>{let i=Math.abs(Math.ceil((r-e)/t)),n=[i],o=i,a=[{type:12,data:o},{type:s,data:e},{type:s,data:t},...nt(n)],l=u=>{let p=tt("output",s,n.length),c=p.type.value,h=[{name:"outputSize",type:"u32"},{name:"start",type:c},{name:"delta",type:c}];return` + ${u.registerUniforms(h).declareVariables(p)} + ${u.mainStart()} + ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + output[global_idx] = uniforms.start + ${c}(global_idx) * uniforms.delta; + }`};return{name:"Range",shaderCache:{hint:`${s}`},getShaderSource:l,getRunData:()=>({outputs:[{dims:n,dataType:s}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:a})}},Cg=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]),Ut.webgpu.validateInputContent&&Eg(r,t,s),e.compute(Pg(r,t,s,e.inputs[0].dataType),{inputs:[]})}}),Sg,$g,kg,Ig,Qv=Ve(()=>{pt(),Mt(),Yt(),Tt(),Sg=(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 i=`{ + 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}));`:` + ${i}bitcast<${s}>(oldValue) + (${t})${n}`;case"max":return s==="i32"||s==="u32"?`atomicMax(&${r}, bitcast<${s}>(${t}));`:` + ${i}max(bitcast(oldValue), (${t}))${n}`;case"min":return s==="i32"||s==="u32"?`atomicMin(&${r}, bitcast<${s}>(${t}));`:`${i}min(bitcast<${s}>(oldValue), (${t}))${n}`;case"mul":return`${i}(bitcast<${s}>(oldValue) * (${t}))${n}`;default:throw new Error(`Reduction ${e} is not supported.`)}},$g=(e,r)=>{let t=e[0].dims,s=e[1].dims,i=t,n=1,o=Math.ceil(Te.size(s)/n),a=s[s.length-1],l=Te.sizeFromDimension(t,a),u=[{type:12,data:o},{type:12,data:a},{type:12,data:l},...nt(e[1].dims,e[2].dims,i)],p=c=>{let h=$e("indices",e[1].dataType,e[1].dims.length),g=$e("updates",e[2].dataType,e[2].dims.length,n),_=r.reduction!=="none"&&r.reduction!==""?Np("output",e[0].dataType,i.length):tt("output",e[0].dataType,i.length,n);return` + ${c.registerUniform("output_size","u32").registerUniform("last_index_dimension","u32").registerUniform("num_updates_elements","u32").declareVariables(h,g,_)} + ${c.mainStart()} + ${c.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + var hasDuplicates = false; + if (${r.reduction==="none"}) { + let n = ${Te.size(s)}; + for (var i = 0; i < n; i = i + 1) { + for (var j = i + 1; j < n; 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; + } + } + } + + var data_offset = 0u; + var indices_start = uniforms.last_index_dimension * global_idx; + if (${r.reduction==="none"} && hasDuplicates) { + if (global_idx != 0u) { + return; + } + indices_start = 0u; + } + let indices_end = indices_start + uniforms.last_index_dimension; + for (var i = indices_start; i < indices_end; i++) { + var index = i32(indices[i].x); + ${e[0].dims.length===1?` + let element_count_dim = uniforms.output_strides; + let dim_value = uniforms.output_shape;`:` + let element_count_dim = uniforms.output_strides[i - indices_start]; + let dim_value = uniforms.output_shape[i - indices_start + 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)); + } + + for (var i = 0u; i < uniforms.num_updates_elements; i++) { + let value = updates[uniforms.num_updates_elements * global_idx + i]; + ${Sg(r.reduction,"output[data_offset + i]","value",_.type.value)} + } + + }`};return{name:"ScatterND",shaderCache:{hint:`${r.cacheKey}_${r.reduction}`,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:i,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:u}),getShaderSource:p}},kg=e=>Dt({reduction:e.reduction}),Ig=(e,r)=>{e.compute($g(e.inputs,r),{inputs:[e.inputs[1],e.inputs[2]],outputs:[]})}}),Ag,Fg,Og,ku,Dg,Lg,zg,Bg,Rg,Ng,jg,Vg,Iu,Ug,Wg,Gg,Kg,Hg,qg,Qg,Xv=Ve(()=>{pt(),Mt(),Yt(),Tt(),Ag=(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")}},Fg=(e,r,t)=>{r.every(i=>i>=0&&i{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((i,n)=>s[i]=e[n]),s},Og=(e,r,t,s,i,n)=>{let[o,a,l]=t>10?[1,2,3]:[-1,e.length>1?1:-1,-1],u=e[0].dims.length;if(o>0&&e.length>o&&e[o].dims.length>0)e[o].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");Ag(s,r),r.axes.length>0&&Fg(s,r.axes,u).forEach((p,c)=>s[c]=p)}if(l>0&&e.length>l&&e[l].dims.length===1&&e[l].dims[0]>0&&(e[l].getBigInt64Array().forEach(p=>i.push(Number(p))),i.length!==0&&i.length!==u&&t>=18&&i.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(i.length!==0&&i.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 i<"u"&&s.length>0&&i.length>u)throw new Error("Resize requires only of scales or sizes to be specified")},ku=(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; +`,Dg=(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 { + ${ku("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 { + ${ku("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`)}})()+"}",Lg=(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`)}})()+"}",zg=(e,r,t)=>{let s=new Array(t).fill(0).concat(new Array(t).fill(1)),i=e.length===0?s:e.slice();return r.length>0?(r.forEach((n,o)=>{s[n]=i[o],s[o+t]=i[r.length+o]}),s):i},Bg=(e,r,t,s)=>{let i=[];if(t.length>0)if(s.length>0){if(e.forEach(n=>i.push(n)),Math.max(...s)>e.length)throw new Error("axes is out of bound");s.forEach((n,o)=>i[n]=t[o])}else t.forEach(n=>i.push(n));else{if(r.length===0)throw new Error("Resize requires either scales or sizes.");i=e.map((n,o)=>Math.round(n*r[o]))}return i},Rg=(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 i=e.slice();return t.axes.length>0?(t.axes.forEach(n=>r[n]=s),t.axes.forEach(n=>i[n]=Math.round(e[n]*r[n]))):(r.fill(s,0,r.length),i.forEach((n,o)=>i[o]=Math.round(n*r[o]))),i},Ng=(e,r,t,s,i)=>` + 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 = ${rt("uniforms.scales","i",s)}; + var roi_low = ${rt("uniforms.roi","i",i)}; + var roi_hi = ${rt("uniforms.roi",`i + ${r.length}`,i)}; + if (scale == 1.0) { + original_indices[i] = ${e.type.value}(output_index); + } else { + var input_shape_i = ${rt("uniforms.input_shape","i",r.length)}; + var output_shape_i = ${rt("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; + }`,jg=(e,r,t,s,i,n,o)=>` + 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 = ${rt("uniforms.scales","i",i)}; + if (scale == 1.0) { + input_index = output_index; + } else { + var roi_low = ${rt("uniforms.roi","i",n)}; + var roi_hi = ${rt("uniforms.roi",`i + ${t.length}`,n)}; + var input_shape_i = ${rt("uniforms.input_shape","i",t.length)}; + var output_shape_i = ${rt("uniforms.output_shape","i",s.length)}; + var original_idx = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, + input_shape_i, roi_low, roi_hi); + if (!${o} || (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; + }`,Vg=(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 >= ${rt("uniforms.input_shape","i",r.length)}) { + return false; + } + } + return true; + }`,Iu=(e,r,t,s)=>e.rank>s?` + ${e.indicesSet("input_indices",r,"channel")}; + ${e.indicesSet("input_indices",t,"batch")}; +`:"",Ug=(e,r,t,s,i)=>{let[n,o,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",o,`max(0, min(row, ${t[o]} - 1))`)}; + ${e.indicesSet("input_indices",a,`max(0, min(col, ${t[a]} - 1))`)}; + ${Iu(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[${o}]; + var col:${u} = originalIndices[${a}]; + ${s?`if (row < 0 || row > (${t[o]} - 1) || col < 0 || col > (${t[a]} - 1)) { + return ${i}; + }`:""}; + row = max(0, min(row, ${t[o]} - 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); + }`},Wg=(e,r,t,s,i,n,o,a,l,u)=>{let p=t.length===2,[c,h]=p?[0,1]:[2,3],g=e.type.value,_=E=>{let A=E===c?"row":"col";return` + fn ${A}CubicInterpolation(input_indices: ${e.type.indices}, output_indices: ${r.type.indices}) -> ${g} { + var output_index = ${r.indicesGet("output_indices",E)}; + var originalIdx: ${g} = getOriginalCoordinateFromResizedCoordinate(output_index, ${i[E]}, + ${s[E]}, ${t[E]}, ${n[E]}, ${n[E]} + ${t.length}); + var fractOriginalIdx: ${g} = originalIdx - floor(originalIdx); + var coefs = getCubicInterpolationCoefs(fractOriginalIdx); + + if (${a} && (originalIdx < 0 || originalIdx > (${t[E]} - 1))) { + return ${l}; + } + var data: array<${g}, 4> = array<${g}, 4>(0.0, 0.0, 0.0, 0.0); + for (var i: i32 = -1; i < 3; i++) { + var ${A}: ${g} = originalIdx + ${g}(i); + if (${A} < 0 || ${A} >= ${t[E]}) { + ${u?`coefs[i + 1] = 0.0; + continue;`:a?`return ${l};`:`${A} = max(0, min(${A}, ${t[E]} - 1));`}; + } + var input_indices_copy: ${e.type.indices} = input_indices; + ${e.indicesSet("input_indices_copy",E,`u32(${A})`)}; + data[i + 1] = ${E===c?e.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"}; + } + return cubicInterpolation1D(data, coefs); + }`};return` + ${_(c)}; + ${_(h)}; + fn getCubicInterpolationCoefs(s: ${g}) -> array<${g}, 4> { + var absS = abs(s); + var coeffs: array<${g}, 4> = array<${g}, 4>(0.0, 0.0, 0.0, 0.0); + var oneMinusAbsS: ${g} = 1.0 - absS; + var twoMinusAbsS: ${g} = 2.0 - absS; + var onePlusAbsS: ${g} = 1.0 + absS; + coeffs[0] = ((${o} * onePlusAbsS - 5 * ${o}) * onePlusAbsS + 8 * ${o}) * onePlusAbsS - 4 * ${o}; + coeffs[1] = ((${o} + 2) * absS - (${o} + 3)) * absS * absS + 1; + coeffs[2] = ((${o} + 2) * oneMinusAbsS - (${o} + 3)) * oneMinusAbsS * oneMinusAbsS + 1; + coeffs[3] = ((${o} * twoMinusAbsS - 5 * ${o}) * twoMinusAbsS + 8 * ${o}) * twoMinusAbsS - 4 * ${o}; + return coeffs; + } + + fn cubicInterpolation1D(x: array<${g}, 4>, coefs: array<${g}, 4>) -> ${g} { + var coefsSum: ${g} = 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}) -> ${g} { + var input_indices: ${e.type.indices} = output_indices; + return colCubicInterpolation(input_indices, output_indices); + } + `},Gg=(e,r,t,s,i)=>{let[n,o,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",o,`max(0, min(depth, ${t[o]} - 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))`)}; + ${Iu(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[${o}]; + var height:${p} = originalIndices[${a}]; + var width:${p} = originalIndices[${l}]; + ${s?`if (depth < 0 || depth > (${t[o]} - 1) || height < 0 || height > (${t[a]} - 1) || width < 0 || (width > ${t[l]} - 1)) { + return ${i}; + }`:""}; + + depth = max(0, min(depth, ${t[o]} - 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); + }`},Kg=(e,r,t,s,i,n)=>{let o=e.dims,a=zg(n,r.axes,o.length),l=Bg(o,s,i,r.axes),u=s.slice();s.length===0&&(u=o.map((y,k)=>y===0?1:l[k]/y),r.keepAspectRatioPolicy!=="stretch"&&(l=Rg(o,u,r)));let p=tt("output",e.dataType,l.length),c=$e("input",e.dataType,o.length),h=Te.size(l),g=o.length===l.length&&o.every((y,k)=>y===l[k]),_=r.coordinateTransformMode==="tf_crop_and_resize",E=r.extrapolationValue,A=c.type.value,v=y=>` + ${g?"":` + ${Dg(r.coordinateTransformMode,A)}; + ${(()=>{switch(r.mode){case"nearest":return` + ${Vg(c,o)}; + ${Lg(r.nearestMode,t,A)}; + ${jg(c,p,o,l,u.length,a.length,_)}; + `;case"linear":return` + ${Ng(p,o,l,u.length,a.length)}; + ${(()=>{if(o.length===2||o.length===4)return`${Ug(c,p,o,_,E)}`;if(o.length===3||o.length===5)return`${Gg(c,p,o,_,E)}`;throw Error("Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.")})()}; + `;case"cubic":return` + ${(()=>{if(o.length===2||o.length===4)return`${Wg(c,p,o,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")}})()}; + `} + ${y.registerUniform("output_size","u32").registerUniform("scales","f32",u.length).registerUniform("roi","f32",a.length).declareVariables(c,p)} + ${y.mainStart()} + ${y.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + ${g?"output[global_idx] = input[global_idx];":` + let output_indices = ${p.offsetToIndices("global_idx")}; + var input_indices: ${c.type.indices}; + ${(()=>{switch(r.mode){case"nearest":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices); + if (checkInputIndices(input_indices)) { + output[global_idx] = ${c.getByIndices("input_indices")}; + } else { + output[global_idx] = ${r.extrapolationValue}; + }`;case"linear":return`output[global_idx] = ${o.length===2||o.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:""}|${i.length>0?i:""}|${a.length>0?a:""}|${g}|${r.mode==="nearest"?o.length:o}`,inputDependencies:["rank"]},getShaderSource:v,getRunData:()=>({outputs:[{dims:l,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:[{type:12,data:h},{type:1,data:u},{type:1,data:a},...nt(o,l)]})}},Hg=e=>{let r=e.customDataBuffer;return new Uint32Array(r,r.byteOffset,1)[0]},qg=(e,r)=>{let t=[],s=[],i=[],n=Hg(e);if(r.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");Og(e.inputs,r,n,t,s,i),e.compute(Kg(e.inputs[0],r,n,t,s,i),{inputs:[0]})},Qg=e=>{let r=e.antialias,t=e.axes,s=e.coordinateTransformMode,i=e.cubicCoeffA,n=e.excludeOutside!==0,o=e.extrapolationValue,a=e.keepAspectRatioPolicy,l=e.mode,u=e.nearestMode===""?"simple":e.nearestMode;return Dt({antialias:r,axes:t,coordinateTransformMode:s,cubicCoeffA:i,excludeOutside:n,extrapolationValue:o,keepAspectRatioPolicy:a,mode:l,nearestMode:u})}}),Xg,Jg,Yg,Jv=Ve(()=>{pt(),Mt(),Yt(),Tt(),Xg=(e,r)=>{let[t,s,i,n]=e,{numHeads:o,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(!Te.areEqual(s.dims,[])&&!Te.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(i.dims.length!==2)throw new Error(`Input 'cos_cache' is expected to have 2 dimensions, got ${i.dims.length}`);if(n.dims.length!==2)throw new Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${n.dims.length}`);if(!Te.areEqual(i.dims,n.dims))throw new Error("Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape");if(a>0&&o===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=i.dims[0],c=Te.sizeFromDimension(t.dims,1)/u,h=a===0?i.dims[1]*2:c/o;if(a>h)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(h/2!==i.dims[1]&&a/2!==i.dims[1])throw new Error(`Input 'cos_cache' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${i.dims[1]}`);if(u>p)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported")},Jg=(e,r)=>{let{interleaved:t,numHeads:s,rotaryEmbeddingDim:i,scale:n}=r,o=e[0].dims[0],a=Te.sizeFromDimension(e[0].dims,1),l=e[0].dims[e[0].dims.length-2],u=a/l,p=e[2].dims[1],c=i===0?p*2:u/s,h=new Array(o,l,u/c,c-p),g=Te.computeStrides(h),_=[{type:1,data:n},{type:12,data:h},{type:12,data:g},...e[0].dims.length===3?new Array({type:12,data:[a,u,c,1]}):[],...e[0].dims.length===4?new Array({type:12,data:[a,c,l*c,1]}):[],...nt(e[0].dims,e[1].dims,e[2].dims,e[3].dims,e[0].dims)],E=A=>{let v=$e("input",e[0].dataType,e[0].dims.length),y=$e("position_ids",e[1].dataType,e[1].dims.length),k=$e("cos_cache",e[2].dataType,e[2].dims.length),P=$e("sin_cache",e[3].dataType,e[3].dims.length),M=tt("output",e[0].dataType,e[0].dims.length);return A.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:h.length},{name:"global_strides",type:"u32",length:g.length},{name:"input_output_strides",type:"u32",length:g.length}]),` + ${A.declareVariables(v,y,k,P,M)} + + ${A.mainStart(jn)} + let half_rotary_emb_dim = uniforms.${k.name}_shape[1]; + let bsnh = global_idx / uniforms.global_strides % uniforms.global_shape; + let size = uniforms.global_shape[0] * uniforms.global_strides[0]; + ${A.guardAgainstOutOfBoundsWorkgroupSizes("size")} + + if (bsnh[3] < half_rotary_emb_dim) { + let position_ids_idx = + ${y.broadcastedIndicesToOffset("bsnh.xy",tt("",y.type.tensor,2))}; + let position_id = + u32(${y.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 = ${v.getByOffset("i")} * ${k.get("position_id","bsnh[3]")} - + ${v.getByOffset("j")} * ${P.get("position_id","bsnh[3]")}; + ${M.setByOffset("i","re")} + let im = ${v.getByOffset("i")} * ${P.get("position_id","bsnh[3]")} + + ${v.getByOffset("j")} * ${k.get("position_id","bsnh[3]")}; + ${M.setByOffset("j","im")} + } else { + let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim; + ${M.setByOffset("k",v.getByOffset("k"))} + } + }`};return{name:"RotaryEmbedding",shaderCache:{hint:Dt({interleaved:t}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:E,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(Te.size(h)/jn)},programUniforms:_})}},Yg=(e,r)=>{Xg(e.inputs,r),e.compute(Jg(e.inputs,r))}}),Zg,ew,tw,Yv=Ve(()=>{pt(),Mt(),Tt(),Zg=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 i=r.dims[r.dims.length-1],n=r.dims[r.dims.length-2];if(t.dims[t.dims.length-1]!==i)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]!==i)throw new Error("Gamma must have the same hidden size as input");if(e.length>3){let o=e[3];if(o.dims.length!==1)throw new Error("Beta must be 1D");if(o.dims[o.dims.length-1]!==i)throw new Error("Beta must have the same hidden size as input")}if(e.length>4){let o=e[4];if(o.dims.length!==1)throw new Error("Bias must be 1D");if(o.dims[o.dims.length-1]!==i)throw new Error("Bias must have the same hidden size as input")}},ew=(e,r,t,s)=>{let i=r.simplified,n=e[0].dims,o=Te.size(n),a=n,l=o,u=n.slice(-1)[0],p=s?n.slice(0,-1).concat(1):[],c=!i&&e.length>3,h=e.length>4,g=s&&t>1,_=s&&t>2,E=t>3,A=64,v=Xt(u),y=[{type:12,data:l},{type:12,data:v},{type:12,data:u},{type:1,data:r.epsilon}],k=M=>{let w=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],x=[$e("x",e[0].dataType,e[0].dims,v),$e("skip",e[1].dataType,e[1].dims,v),$e("gamma",e[2].dataType,e[2].dims,v)];c&&x.push($e("beta",e[3].dataType,e[3].dims,v)),h&&x.push($e("bias",e[4].dataType,e[4].dims,v)),x.push(tt("output",e[0].dataType,a,v)),g&&x.push(tt("mean_output",1,p)),_&&x.push(tt("inv_std_output",1,p)),E&&x.push(tt("input_skip_bias_sum",e[0].dataType,a,v));let $=lr(e[0].dataType),z=lr(1,v);return` + + ${M.registerUniforms(w).declareVariables(...x)} + var sum_shared : array<${z}, ${A}>; + var sum_squared_shared : array<${z}, ${A}>; + + ${M.mainStart([A,1,1])} + let ix = local_id.x; + let iy = global_id.x / ${A}; + + let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components; + var stride = hidden_size_vectorized / ${A}; + let offset = ix * stride + iy * hidden_size_vectorized; + let offset1d = stride * ix; + if (ix == ${A-1}) { + stride = hidden_size_vectorized - stride * ix; + } + for (var i: u32 = 0; i < stride; i++) { + let skip_value = skip[offset + i]; + let bias_value = ${h?"bias[offset1d + i]":$+"(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 = ${Vn($,v,"value")}; + sum_shared[ix] += f32_value; + sum_squared_shared[ix] += f32_value * f32_value; + } + workgroupBarrier(); + + var reduce_size : u32 = ${A}; + 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 = ${Ks("sum",v)} / f32(uniforms.hidden_size); + let inv_std_dev = inverseSqrt(${Ks("square_sum",v)} / f32(uniforms.hidden_size) ${i?"":"- mean * mean"} + uniforms.epsilon); + ${g?"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] ${i?"":`- ${$}(mean)`}) * + ${$}(inv_std_dev) * gamma[offset1d + i] + ${c?"+ beta[offset1d + i]":""}; + } + }`},P=[{dims:a,dataType:e[0].dataType}];return t>1&&P.push({dims:p,dataType:1}),t>2&&P.push({dims:p,dataType:1}),t>3&&P.push({dims:n,dataType:e[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${v};${g};${_};${E}`,inputDependencies:e.map((M,w)=>"type")},getShaderSource:k,getRunData:()=>({outputs:P,dispatchGroup:{x:Math.ceil(l/u)},programUniforms:y})}},tw=(e,r)=>{Zg(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(ew(e.inputs,r,e.outputCount,!1),{outputs:t})}}),rw,Ni,sw,Au,nw,iw,ow,aw,Zv=Ve(()=>{pt(),Mt(),Yt(),Tt(),rw=(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`)})},Ni=(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},sw=(e,r)=>{if(e.length>1){let t=Ni(e,1),s=Ni(e,2),i=Ni(e,3);return i.length===0&&(i=[...Array(e[0].dims.length).keys()]),Dt({starts:t,ends:s,axes:i})}else return r},Au=(e,r,t,s,i)=>{let n=e;return e<0&&(n+=t[s[r]]),i[r]<0?Math.max(0,Math.min(n,t[s[r]]-1)):Math.max(0,Math.min(n,t[s[r]]))},nw=(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 = ${rt("uniforms.input_shape","i",t.length)}; + let steps_i = ${rt("uniforms.steps","i",t.length)}; + let signs_i = ${rt("uniforms.signs","i",t.length)}; + let starts_i = ${rt("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; + }`,iw=(e,r)=>{let t=e[0].dims,s=Te.size(t),i=r.axes.length>0?Te.normalizeAxes(r.axes,t.length):[...Array(t.length).keys()],n=Ni(e,4);n.forEach(v=>v!==0||(()=>{throw new Error("step cannot be 0")})),n.length===0&&(n=Array(i.length).fill(1));let o=r.starts.map((v,y)=>Au(v,y,t,i,n)),a=r.ends.map((v,y)=>Au(v,y,t,i,n));if(i.length!==o.length||i.length!==a.length)throw new Error("start, ends and axes should have the same number of elements");if(i.length!==t.length)for(let v=0;vMath.sign(v));n.forEach((v,y,k)=>{if(v<0){let P=(a[y]-o[y])/v,M=o[y],w=M+P*n[y];o[y]=w,a[y]=M,k[y]=-v}});let u=t.slice(0);i.forEach((v,y)=>{u[v]=Math.ceil((a[v]-o[v])/n[v])});let p={dims:u,dataType:e[0].dataType},c=tt("output",e[0].dataType,u.length),h=$e("input",e[0].dataType,e[0].dims.length),g=Te.size(u),_=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:o.length},{name:"signs",type:"i32",length:l.length},{name:"steps",type:"u32",length:n.length}],E=[{type:12,data:g},{type:12,data:o},{type:6,data:l},{type:12,data:n},...nt(e[0].dims,u)],A=v=>` + ${v.registerUniforms(_).declareVariables(h,c)} + ${nw(h,c,t)} + ${v.mainStart()} + ${v.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + let output_indices = ${c.offsetToIndices("global_idx")}; + let input_indices = calculateInputIndices(output_indices); + ${c.setByOffset("global_idx",h.getByIndices("input_indices"))} + }`;return{name:"Slice",shaderCache:{hint:`${l.length}_${o.length}_${n.length}`,inputDependencies:["rank"]},getShaderSource:A,getRunData:()=>({outputs:[p],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:E})}},ow=(e,r)=>{rw(e.inputs,r);let t=sw(e.inputs,r);e.compute(iw(e.inputs,t),{inputs:[0]})},aw=e=>{let r=e.starts,t=e.ends,s=e.axes;return Dt({starts:r,ends:t,axes:s})}}),lw,dw,uw,cw,eT=Ve(()=>{pt(),Mt(),Yt(),Hs(),Tt(),lw=e=>{if(!e||e.length!==1)throw new Error("Softmax op requires 1 input.")},dw=(e,r)=>{let t=e.inputs[0],s=t.dims,i=Te.size(s),n=s.length,o=Te.normalizeAxis(r.axis,n),a=o$),u[o]=n-1,u[n-1]=o,l=e.compute(Nr(t,u),{inputs:[t],outputs:[-1]})[0]):l=t;let p=l.dims,c=p[n-1],h=i/c,g=Xt(c),_=c/g,E=64;h===1&&(E=256);let A=(x,$)=>$===4?`max(max(${x}.x, ${x}.y), max(${x}.z, ${x}.w))`:$===2?`max(${x}.x, ${x}.y)`:$===3?`max(max(${x}.x, ${x}.y), ${x}.z)`:x,v=$e("x",l.dataType,l.dims,g),y=tt("result",l.dataType,l.dims,g),k=v.type.value,P=lr(l.dataType)==="f32"?`var threadMax = ${k}(-3.402823e+38f);`:`var threadMax = ${k}(-65504.0h);`,M=x=>` + var rowMaxShared : ${k}; + var rowSumShared : ${k}; + var threadShared : array<${k}, ${E}>; + + fn getValue(row: i32, col: i32, row_stride: i32) -> ${k} { + let index = row * row_stride + col; + return x[index]; + } + + fn setValue(row: i32, col: i32, row_stride: i32, value: ${k}) { + let index = row * row_stride + col; + result[index] = value; + } + ${x.registerUniform("packedCols","i32").declareVariables(v,y)} + ${x.mainStart(E)} + let gindex = i32(global_idx); + let lindex = i32(local_idx); + const wg = ${E}; + let row = gindex / wg; + let cols = uniforms.packedCols; + let row_stride : i32 = uniforms.packedCols; + + // find the rows max + ${P} + 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 = ${k}(${A("threadShared[0]",g)}); + } + workgroupBarrier(); + + // find the rows sum + var threadSum = ${k}(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 = ${k}(${Ks("threadShared[0]",g)}); + } + 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); + } + }`,w=e.compute({name:"Softmax",shaderCache:{hint:`${g};${E}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:p,dataType:l.dataType}],dispatchGroup:{x:h},programUniforms:[{type:6,data:_}]}),getShaderSource:M},{inputs:[l],outputs:[a?-1:0]})[0];a&&e.compute(Nr(w,u),{inputs:[w]})},uw=(e,r)=>{lw(e.inputs),dw(e,r)},cw=e=>Dt({axis:e.axis})}),Fu,pw,hw,fw,mw,tT=Ve(()=>{pt(),Mt(),Tt(),Fu=e=>Array.from(e.getBigInt64Array(),Number),pw=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(Fu(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")},hw=(e,r)=>{let t=[];for(let s=0;s{let t=e[0].dims,s=r??Fu(e[1]),i=hw(t,s),n=Te.size(i),o=e[0].dataType,a=$e("input",o,t.length),l=tt("output",o,i.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:i,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:[{type:12,data:n},...nt(e[0].dims,i)]}),getShaderSource:u}},mw=e=>{pw(e.inputs),e.compute(fw(e.inputs),{inputs:[0]})}}),_w,gw,ww,rT=Ve(()=>{pt(),Mt(),Tt(),_w=(e,r,t,s,i)=>{let n=tt("output_data",i,t.length,4),o=$e("a_data",r[1].dataType,r[1].dims.length,4),a=$e("b_data",r[2].dataType,r[2].dims.length,4),l=$e("c_data",r[0].dataType,r[0].dims.length,4),u,p=(c,h,g)=>`select(${h}, ${c}, ${g})`;if(!s)u=n.setByOffset("global_idx",p(o.getByOffset("global_idx"),a.getByOffset("global_idx"),l.getByOffset("global_idx")));else{let c=(h,g,_="")=>{let E=`a_data[index_a${g}][component_a${g}]`,A=`b_data[index_b${g}][component_b${g}]`,v=`bool(c_data[index_c${g}] & (0xffu << (component_c${g} * 8)))`;return` + let output_indices${g} = ${n.offsetToIndices(`global_idx * 4u + ${g}u`)}; + let offset_a${g} = ${o.broadcastedIndicesToOffset(`output_indices${g}`,n)}; + let offset_b${g} = ${a.broadcastedIndicesToOffset(`output_indices${g}`,n)}; + let offset_c${g} = ${l.broadcastedIndicesToOffset(`output_indices${g}`,n)}; + let index_a${g} = offset_a${g} / 4u; + let index_b${g} = offset_b${g} / 4u; + let index_c${g} = offset_c${g} / 4u; + let component_a${g} = offset_a${g} % 4u; + let component_b${g} = offset_b${g} % 4u; + let component_c${g} = offset_c${g} % 4u; + ${h}[${g}] = ${_}(${p(E,A,v)}); + `};i===9?u=` + var data = vec4(0); + ${c("data",0,"u32")} + ${c("data",1,"u32")} + ${c("data",2,"u32")} + ${c("data",3,"u32")} + output_data[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:u=` + ${c("output_data[global_idx]",0)} + ${c("output_data[global_idx]",1)} + ${c("output_data[global_idx]",2)} + ${c("output_data[global_idx]",3)} + `}return` + ${e.registerUniform("vec_size","u32").declareVariables(l,o,a,n)} + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${u} + }`},gw=e=>{let r=e[1].dims,t=e[2].dims,s=e[0].dims,i=e[1].dataType,n=!(Te.areEqual(r,t)&&Te.areEqual(t,s)),o=r,a=Te.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");o=u,a=Te.size(o)}let l=Math.ceil(a/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:u=>_w(u,e,o,n,i),getRunData:()=>({outputs:[{dims:o,dataType:i}],dispatchGroup:{x:Math.ceil(a/64/4)},programUniforms:[{type:12,data:l},...nt(s,r,t,o)]})}},ww=e=>{e.compute(gw(e.inputs))}}),yw,sT=Ve(()=>{_v(),Qd(),gv(),wv(),yv(),Mv(),bv(),Pv(),Sv(),$v(),kv(),Iv(),Av(),Fv(),Ov(),Dv(),Lv(),zv(),Bv(),Rv(),Nv(),jv(),Vv(),Uv(),Wv(),A_(),Gv(),Kv(),Hv(),qv(),Qv(),Kd(),Xv(),Jv(),Yv(),Zv(),eT(),R_(),tT(),Hs(),Zd(),rT(),yw=new Map([["Abs",[Zh]],["Acos",[ef]],["Acosh",[tf]],["Add",[Uf]],["ArgMax",[Bh,qd]],["ArgMin",[zh,qd]],["Asin",[rf]],["Asinh",[sf]],["Atan",[nf]],["Atanh",[of]],["Attention",[Wh]],["AveragePool",[fg,hg]],["BatchNormalization",[qh]],["BiasAdd",[Jh]],["BiasSplitGelu",[Nf]],["Cast",[lf,af]],["Ceil",[cf]],["Clip",[uf]],["Concat",[sm,nm]],["Conv",[pu,uu]],["ConvTranspose",[Im,Sm]],["Cos",[pf]],["Cosh",[hf]],["CumSum",[Fm,Om]],["DepthToSpace",[Bm,Rm]],["DequantizeLinear",[Tg,xg]],["Div",[Wf]],["Einsum",[Gm,Km]],["Elu",[ff,Oi]],["Equal",[Gf]],["Erf",[mf]],["Exp",[_f]],["Expand",[Xm]],["FastGelu",[Ym]],["Floor",[gf]],["FusedConv",[pu,uu]],["Gather",[r_,t_]],["GatherElements",[h_,p_]],["GatherBlockQuantized",[l_,d_]],["GatherND",[n_,i_]],["Gelu",[wf]],["Gemm",[g_,__]],["GlobalAveragePool",[_g,mg]],["GlobalMaxPool",[Mg,yg]],["Greater",[Qf]],["GreaterOrEqual",[Jf]],["GridSample",[P_,C_]],["GroupQueryAttention",[V_]],["HardSigmoid",[Pf,Ef]],["InstanceNormalization",[G_]],["LayerNormalization",[q_]],["LeakyRelu",[yf,Oi]],["Less",[Xf]],["LessOrEqual",[Yf]],["Log",[Of]],["MatMul",[X_]],["MatMulNBits",[eg,tg]],["MaxPool",[gg,wg]],["Mul",[Kf]],["MultiHeadAttention",[I_,$_]],["Neg",[bf]],["Not",[Mf]],["Pad",[ug]],["Pow",[Hf]],["QuickGelu",[zf,Oi]],["Range",[Cg]],["Reciprocal",[vf]],["ReduceMin",[Ah]],["ReduceMean",[Ch]],["ReduceMax",[Ih]],["ReduceSum",[Oh]],["ReduceProd",[Fh]],["ReduceL1",[Sh]],["ReduceL2",[$h]],["ReduceLogSum",[Lh]],["ReduceLogSumExp",[kh]],["ReduceSumSquare",[Dh]],["Relu",[Tf]],["Resize",[qg,Qg]],["RotaryEmbedding",[Yg]],["ScatterND",[Ig,kg]],["Sigmoid",[xf]],["Sin",[Cf]],["Sinh",[Sf]],["Slice",[ow,aw]],["SkipLayerNormalization",[tw]],["Split",[z_,B_]],["Sqrt",[$f]],["Softmax",[uw,cw]],["Sub",[qf]],["Tan",[kf]],["Tanh",[If]],["ThresholdedRelu",[Ff,Oi]],["Tile",[mw]],["Transpose",[qp,Qp]],["Where",[ww]]])}),Mw,nT=Ve(()=>{ns(),As(),Tt(),Mw=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,i){ss(e.programInfo.name);let n=this.backend.device,o=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}});i&&a.push({binding:a.length,resource:i});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)}o.setPipeline(e.computePipeline),o.setBindGroup(0,l),o.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(),Hr(e.programInfo.name)}dispose(){}build(e,r){ss(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 i=Vp(r,this.backend.device.limits),n=e.getShaderSource(i),o=`${s.join(` +`)} +${i.additionalImplementations} +${n}`,a=t.createShaderModule({code:o,label:e.name});St("verbose",()=>`[WebGPU] ${e.name} shader code: ${o}`);let l=t.createComputePipeline({compute:{module:a,entryPoint:"main"},layout:"auto",label:e.name});return Hr(e.name),{programInfo:e,computePipeline:l,uniformVariablesInfo:i.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,i=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(r<=i&&t<=i&&s<=i)return[r,t,s];let n=r*t*s,o=Math.ceil(Math.sqrt(n));if(o>i){if(o=Math.ceil(Math.cbrt(n)),o>i)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[o,o,o]}else return[o,o,1]}}}),bw,vw,Tw,xw,iT=Ve(()=>{ns(),pt(),As(),kp(),fv(),sT(),nT(),bw=(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 i,n;let s=e.name;return(i=e.shaderCache)!=null&&i.hint&&(s+="["+e.shaderCache.hint+"]"),s+=":"+t+`:${bw(r,((n=e.shaderCache)==null?void 0:n.inputDependencies)??new Array(r.length).fill("dims"))}`,s},Tw=class{constructor(e){e&&(this.architecture=e.architecture,this.vendor=e.vendor)}isArchitecture(e){return this.architecture===e}isVendor(e){return this.vendor===e}},xw=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},i=n=>r.features.has(n)&&t.push(n)&&!0;i("chromium-experimental-timestamp-query-inside-passes")||i("timestamp-query"),i("shader-f16"),i("subgroups"),this.device=await r.requestDevice(s),this.adapterInfo=new Tw(r.info||await r.requestAdapterInfo()),this.gpuDataManager=Op(this),this.programManager=new Mw(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,Ld(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;ss(),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 i=0;i"u"&&(this.queryTimeBase=g);let E=Number(g-this.queryTimeBase),A=Number(_-this.queryTimeBase);if(!Number.isSafeInteger(E)||!Number.isSafeInteger(A))throw new RangeError("incorrect timestamp range");if((s=this.env.webgpu.profiling)!=null&&s.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:c.map(v=>({dims:v.dims,dataType:mn(v.dataType)})),outputsMetadata:h.map(v=>({dims:v.dims,dataType:mn(v.dataType)})),kernelId:o,kernelType:l,kernelName:u,programName:p,startTime:E,endTime:A});else{let v="";c.forEach((k,P)=>{v+=`input[${P}]: [${k.dims}] | ${mn(k.dataType)}, `});let y="";h.forEach((k,P)=>{y+=`output[${P}]: [${k.dims}] | ${mn(k.dataType)}, `}),console.log(`[profiling] kernel "${o}|${l}|${u}|${p}" ${v}${y}execution time: ${A-E} ns`)}ki("GPU",`${p}::${g}::${_}`)}e.unmap(),this.pendingQueries.delete(e)}),Hr()}run(e,r,t,s,i,n){ss(e.name);let o=[];for(let y=0;yk):t;if(p.length!==a.length)throw new Error(`Output size ${p.length} must be equal to ${a.length}.`);let c=[],h=[];for(let y=0;y=n)throw new Error(`Invalid output index: ${p[y]}`);if(p[y]===-3)continue;let k=p[y]===-1,P=p[y]===-2,M=k||P?i(a[y].dataType,a[y].dims):s(p[y],a[y].dataType,a[y].dims);if(c.push(M),M.data===0)continue;let w=this.gpuDataManager.get(M.data);if(!w)throw new Error(`no GPU data for output: ${M.data}`);if(k&&this.temporaryData.push(w),P){let x=this.kernelPersistentData.get(this.currentKernelId);x||(x=[],this.kernelPersistentData.set(this.currentKernelId,x)),x.push(w)}h.push(w)}if(o.length!==r.length||h.length!==c.length){if(h.length===0)return Hr(e.name),c;throw new Error(`Program ${e.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let g;if(u){let y=0,k=[];u.forEach(x=>{let $=typeof x.data=="number"?[x.data]:x.data;if($.length===0)return;let z=x.type===10?2:4,R,Q;x.type===10?(Q=$.length>4?16:$.length>2?8:$.length*z,R=$.length>4?16:z*$.length):(Q=$.length<=2?$.length*z:16,R=16),y=Math.ceil(y/Q)*Q,k.push(y);let q=x.type===10?8:4;y+=$.length>4?Math.ceil($.length/q)*R:$.length*z});let P=16;y=Math.ceil(y/P)*P;let M=new ArrayBuffer(y);u.forEach((x,$)=>{let z=k[$],R=typeof x.data=="number"?[x.data]:x.data;if(x.type===6)new Int32Array(M,z,R.length).set(R);else if(x.type===12)new Uint32Array(M,z,R.length).set(R);else if(x.type===10)new Uint16Array(M,z,R.length).set(R);else if(x.type===1)new Float32Array(M,z,R.length).set(R);else throw new Error(`Unsupported uniform type: ${mn(x.type)}`)});let w=this.gpuDataManager.create(y,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(w.buffer,0,M,0,y),this.gpuDataManager.release(w.id),g={offset:0,size:y,buffer:w.buffer}}let _=this.programManager.normalizeDispatchGroupSize(l),E=_[1]===1&&_[2]===1,A=vw(e,r,E),v=this.programManager.getArtifact(A);if(v||(v=this.programManager.build(e,_),this.programManager.setArtifact(A,v),St("info",()=>`[artifact] key: ${A}, programName: ${e.name}`)),u&&v.uniformVariablesInfo){if(u.length!==v.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${v.uniformVariablesInfo.length}, got ${u.length} in program "${v.programInfo.name}".`);for(let y=0;y`[ProgramManager] run "${e.name}" (key=${A}) with ${_[0]}x${_[1]}x${_[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let y={kernelId:this.currentKernelId,programName:v.programInfo.name,inputTensorViews:r,outputTensorViews:c};this.pendingKernels.push(y),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(y)}return this.programManager.run(v,o,h,_,g),Hr(e.name),c}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 i=yw.get(e);if(!i)throw new Error(`kernel not implemented: ${e}`);let n={kernelType:e,kernelName:s,kernelEntry:i[0],attributes:[i[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 i=s.kernelType,n=s.kernelName,o=s.kernelEntry,a=s.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${i}] ${n}" is not allowed to be called recursively`);this.currentKernelId=e,a[0]&&(a[1]=a[0](a[1]),a[0]=void 0),St("info",()=>`[WebGPU] Start to run kernel "[${i}] ${n}"...`);let l=this.env.debug;this.temporaryData=[];try{return l&&this.device.pushErrorScope("validation"),o(r,a[1]),0}catch(u){return t.push(Promise.resolve(`[WebGPU] Kernel "[${i}] ${n}" failed. ${u}`)),1}finally{l&&t.push(this.device.popErrorScope().then(u=>u?`GPU validation error for kernel "[${i}] ${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 i=this.sessionExternalDataMapping.get(e);i||(i=new Map,this.sessionExternalDataMapping.set(e,i));let n=i.get(r),o=this.gpuDataManager.registerExternalBuffer(t,s,n);return i.set(r,[o,t]),o}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 jd(this,e,r);return zd(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(){St("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(){St("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){St("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()}}}),Ew,Ou,Pw,Du,Lu,zu,Cw,Sw,oT=Ve(()=>{As(),Ew=1,Ou=()=>Ew++,Pw=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),Du=(e,r)=>{let t=Pw.get(e);if(!t)throw new Error("Unsupported data type.");return r.length>0?Math.ceil(r.reduce((s,i)=>s*i)*t/8):0},Lu=class{constructor(e){this.sessionId=e.sessionId,this.mlContext=e.context,this.mlTensor=e.tensor,this.dataType=e.dataType,this.tensorShape=e.shape}get tensor(){return this.mlTensor}get type(){return this.dataType}get shape(){return this.tensorShape}get byteLength(){return Du(this.dataType,this.tensorShape)}destroy(){St("verbose",()=>"[WebNN] TensorWrapper.destroy"),this.mlTensor.destroy()}write(e){this.mlContext.writeTensor(this.mlTensor,e)}async read(e){return e?this.mlContext.readTensor(this.mlTensor,e):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,i)=>s===t[i])}},zu=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 i=this.tensorManager.getMLContext(e);if(this.wrapper){if(this.wrapper.canReuseTensor(i,r,t))return this.wrapper.tensor;if(s){if(this.wrapper.byteLength!==Du(r,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 n=typeof MLTensorUsage>"u"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(e,r,t,n,!0,!0),s&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(e){if(this.wrapper)if(e.byteLength===this.wrapper.byteLength){this.wrapper.write(e);return}else St("verbose",()=>"Data size does not match tensor size. Releasing tensor."),this.releaseTensor();this.activeUpload?this.activeUpload.set(e):this.activeUpload=new Uint8Array(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.wrapper)throw new Error("Tensor has not been created.");return e?this.wrapper.read(e):this.wrapper.read()}},Cw=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=Ou();return this.tensorTrackersById.set(e,new zu(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,i){St("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${r}, dataType: ${t}, shape: ${s}, copyOld: ${i}}`);let n=this.tensorTrackersById.get(r);if(!n)throw new Error("Tensor not found.");return n.ensureTensor(e,t,s,i)}upload(e,r){let t=this.tensorTrackersById.get(e);if(!t)throw new Error("Tensor not found.");t.upload(r)}async download(e,r){St("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 i=this.getMLContext(e),n=Ou(),o=new Lu({sessionId:e,context:i,tensor:r,dataType:t,shape:s});return this.tensorTrackersById.set(n,new zu(this,o)),this.externalTensors.add(o),n}async getCachedTensor(e,r,t,s,i,n){let o=this.getMLContext(e);for(let[l,u]of this.freeTensors.entries())if(u.canReuseTensor(o,r,t)){St("verbose",()=>`[WebNN] Reusing tensor {dataType: ${r}, shape: ${t}}`);let p=this.freeTensors.splice(l,1)[0];return p.sessionId=e,p}St("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${r}, shape: ${t}}`);let a=await o.createTensor({dataType:r,shape:t,dimensions:t,usage:s,writable:i,readable:n});return new Lu({sessionId:e,context:o,tensor:a,dataType:r,shape:t})}releaseTensor(e){this.externalTensors.has(e)&&this.externalTensors.delete(e),this.freeTensors.push(e)}},Sw=(...e)=>new Cw(...e)}),Ia,$w,kw,aT=Ve(()=>{pt(),fn(),kp(),oT(),As(),Ia=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),$w=(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((i,n)=>i===s[n]&&e[i]===r[i])},kw=class{constructor(e){this.tensorManager=Sw(this),this.mlContextBySessionId=new Map,this.sessionIdsByMLContext=new Map,this.mlContextCache=[],this.sessionGraphInputs=new Map,this.temporaryGraphInputs=[],this.temporarySessionTensorIds=new Map,Ld(e.logLevel,!!e.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(e){St("verbose",()=>`[WebNN] onRunStart {sessionId: ${e}}`),this.activeSessionId=e}onRunEnd(e){St("verbose",()=>`[WebNN] onRunEnd {sessionId: ${e}}`);let r=this.temporarySessionTensorIds.get(e);if(r){for(let t of r)St("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=>$w(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(i=>i.mlContext===r);s!==-1&&this.mlContextCache.splice(s,1)}}getMLContext(e){return this.mlContextBySessionId.get(e)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(e){St("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,r,t,s,i){let n=Ia.get(t);if(!n)throw new Error(`Unsupported ONNX data type: ${t}`);return this.tensorManager.ensureTensor(e??this.currentSessionId,r,n,s,i)}async createTemporaryTensor(e,r,t){St("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${r}, shape: ${t}}`);let s=Ia.get(r);if(!s)throw new Error(`Unsupported ONNX data type: ${r}`);let i=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(e,i,s,t,!1);let n=this.temporarySessionTensorIds.get(e);return n?n.push(i):this.temporarySessionTensorIds.set(e,[i]),i}uploadTensor(e,r){if(!ar().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");St("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 zd(t,r)}}registerMLTensor(e,r,t,s){let i=Ia.get(t);if(!i)throw new Error(`Unsupported ONNX data type: ${t}`);let n=this.tensorManager.registerTensor(e,r,i,s);return St("verbose",()=>`[WebNN] registerMLTensor {tensor: ${r}, dataType: ${i}, dimensions: ${s}} -> {tensorId: ${n}}`),n}registerMLConstant(e,r,t,s,i,n){if(!n)throw new Error("External mounted files are not available.");let o=e;e.startsWith("./")&&(o=e.substring(2));let a=n.get(o);if(!a)throw new Error(`File with name ${o} not found in preloaded files.`);if(r+t>a.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let l=a.slice(r,r+t).buffer,u;switch(i.dataType){case"float32":u=new Float32Array(l);break;case"float16":u=typeof Float16Array<"u"&&Float16Array.from?new Float16Array(l):new Uint16Array(l);break;case"int32":u=new Int32Array(l);break;case"uint32":u=new Uint32Array(l);break;case"int64":u=new BigInt64Array(l);break;case"uint64":u=new BigUint64Array(l);break;case"int8":u=new Int8Array(l);break;case"int4":case"uint4":case"uint8":u=new Uint8Array(l);break;default:throw new Error(`Unsupported data type: ${i.dataType} in creating WebNN Constant from external data.`)}return St("verbose",()=>`[WebNN] registerMLConstant {dataType: ${i.dataType}, shape: ${i.shape}}}`),s.constant(i,u)}registerGraphInput(e){this.temporaryGraphInputs.push(e)}isGraphInput(e,r){let t=this.sessionGraphInputs.get(e);return t?t.includes(r):!1}flush(){}}}),Iw={};Ci(Iw,{init:()=>Fw});var Aa,Aw,Fw,lT=Ve(()=>{pt(),iT(),As(),Mt(),aT(),Aa=class $0{constructor(r,t,s,i){this.module=r,this.dataType=t,this.data=s,this.dims=i}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let r=Te.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=Te.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=Te.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=Te.size(this.dims);return r===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,r)}reshape(r){if(Te.size(r)!==Te.size(this.dims))throw new Error("Invalid new shape");return new $0(this.module,this.dataType,this.data,r)}},Aw=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,i=t/e.PTR_SIZE,n=s===4?"i32":"i64";this.opKernelContext=Number(e.getValue(s*i++,n));let o=Number(e.getValue(s*i++,n));this.outputCount=Number(e.getValue(s*i++,n)),this.customDataOffset=Number(e.getValue(s*i++,"*")),this.customDataSize=Number(e.getValue(s*i++,n));let a=[];for(let l=0;ltypeof a=="number"?this.inputs[a]:a))??this.inputs,s=(r==null?void 0:r.outputs)??[],i=(a,l,u)=>new Aa(this.module,l,this.output(a,u),u),n=(a,l)=>{let u=_n(a,l);if(!u)throw new Error(`Unsupported data type: ${a}`);let p=u>0?this.backend.gpuDataManager.create(u).id:0;return new Aa(this.module,a,p,l)};return this.backend.run(e,t,s,i,n,this.outputCount)}output(e,r){let t=this.module.stackSave();try{let s=this.module.PTR_SIZE,i=s===4?"i32":"i64",n=this.module.stackAlloc((1+r.length)*s);this.module.setValue(n,r.length,i);for(let o=0;o{let i=r.jsepInit;if(!i)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(e==="webgpu"){let n=new xw;await n.initialize(t,s),i("webgpu",[n,o=>n.alloc(Number(o)),o=>n.free(o),(o,a,l,u=!1)=>{if(u)St("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${Number(o)}, dst=${Number(a)}, size=${Number(l)}`),n.memcpy(Number(o),Number(a));else{St("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(o)}, gpuDataId=${Number(a)}, size=${Number(l)}`);let p=r.HEAPU8.subarray(Number(o>>>0),Number(o>>>0)+Number(l));n.upload(Number(a),p)}},async(o,a,l)=>{St("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${o}, dataOffset=${a}, size=${l}`),await n.download(Number(o),()=>r.HEAPU8.subarray(Number(a)>>>0,Number(a+l)>>>0))},(o,a,l)=>n.createKernel(o,Number(a),l,r.UTF8ToString(r._JsepGetNodeName(Number(a)))),o=>n.releaseKernel(o),(o,a,l,u)=>{St("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${l}, kernel=${o}, contextDataOffset=${a}`);let p=new Aw(r,n,Number(a));return n.computeKernel(Number(o),p,u)},()=>n.captureBegin(),()=>n.captureEnd(),()=>n.replay()])}else{let n=new kw(t);i("webnn",[n,()=>n.reserveTensorId(),o=>n.releaseTensorId(o),async(o,a,l,u,p)=>n.ensureTensor(o,a,l,u,p),(o,a)=>{n.uploadTensor(o,a)},async(o,a)=>n.downloadTensor(o,a)])}}}),Ow,Bu,Ru,qs,Dw,Fa,Nu,ju,Vu,Uu,Wu,Gu,Lw=Ve(()=>{pv(),hv(),pt(),fn(),kd(),xp(),Ow=(e,r)=>{ar()._OrtInit(e,r)!==0&&At("Can't initialize onnxruntime.")},Bu=async e=>{Ow(e.wasm.numThreads,ya(e.logLevel))},Ru=async(e,r)=>{{let t=(lT(),fa(Iw)).init;if(r==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");let s=e.webgpu.adapter;if(s){if(typeof s.limits!="object"||typeof s.features!="object"||typeof s.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 n=e.webgpu.forceFallbackAdapter;if(n!==void 0&&typeof n!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${n}"`);if(s=await navigator.gpu.requestAdapter({powerPreference:i,forceFallbackAdapter:n}),!s)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}await t("webgpu",ar(),e,s)}if(r==="webnn"){if(typeof navigator>"u"||!navigator.ml)throw new Error("WebNN is not supported in current environment");await t("webnn",ar(),e)}}},qs=new Map,Dw=e=>{let r=ar(),t=r.stackSave();try{let s=r.PTR_SIZE,i=r.stackAlloc(2*s);r._OrtGetInputOutputCount(e,i,i+s)!==0&&At("Can't get session input/output count.");let n=s===4?"i32":"i64";return[Number(r.getValue(i,n)),Number(r.getValue(i+s,n))]}finally{r.stackRestore(t)}},Fa=e=>{let r=ar(),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]},Nu=async(e,r)=>{var c,h,g;let t,s,i=ar();Array.isArray(e)?[t,s]=e:e.buffer===i.HEAPU8.buffer?[t,s]=[e.byteOffset,e.byteLength]:[t,s]=Fa(e);let n=0,o=0,a=0,l=[],u=[],p=[];try{if([o,l]=Tp(r),(r==null?void 0:r.externalData)&&i.mountExternalData){let M=[];for(let w of r.externalData){let x=typeof w=="string"?w:w.path;M.push(Dd(typeof w=="string"?w:w.data).then($=>{i.mountExternalData(x,$)}))}await Promise.all(M)}for(let M of(r==null?void 0:r.executionProviders)??[])if((typeof M=="string"?M:M.name)==="webnn"){if(i.shouldTransferToMLTensor=!1,typeof M!="string"){let w=M,x=w==null?void 0:w.context,$=w==null?void 0:w.gpuDevice,z=w==null?void 0:w.deviceType,R=w==null?void 0:w.powerPreference;x?i.currentContext=x:$?i.currentContext=await i.jsepCreateMLContext($):i.currentContext=await i.jsepCreateMLContext({deviceType:z,powerPreference:R})}else i.currentContext=await i.jsepCreateMLContext();break}n=await i._OrtCreateSession(t,s,o),n===0&&At("Can't create a session."),(c=i.jsepOnCreateSession)==null||c.call(i),i.currentContext&&(i.jsepRegisterMLContext(n,i.currentContext),i.currentContext=void 0,i.shouldTransferToMLTensor=!0);let[_,E]=Dw(n),A=!!(r!=null&&r.enableGraphCapture),v=[],y=[],k=[];for(let M=0;M<_;M++){let w=i._OrtGetInputName(n,M);w===0&&At("Can't get an input name."),u.push(w),v.push(i.UTF8ToString(w))}for(let M=0;MM==="gpu-buffer"||M==="ml-tensor")&&(a=i._OrtCreateBinding(n),a===0&&At("Can't create IO binding."),P={handle:a,outputPreferredLocations:k,outputPreferredLocationsEncoded:k.map(M=>Od(M))}),qs.set(n,[n,u,p,P,A,!1]),[n,v,y]}catch(_){throw u.forEach(E=>i._OrtFree(E)),p.forEach(E=>i._OrtFree(E)),a!==0&&i._OrtReleaseBinding(a)!==0&&At("Can't release IO binding."),n!==0&&i._OrtReleaseSession(n)!==0&&At("Can't release session."),_}finally{i._free(t),o!==0&&i._OrtReleaseSessionOptions(o)!==0&&At("Can't release session options."),l.forEach(_=>i._free(_)),(g=i.unmountExternalData)==null||g.call(i)}},ju=e=>{var l;let r=ar(),t=qs.get(e);if(!t)throw new Error(`cannot release session. invalid session id: ${e}`);let[s,i,n,o,a]=t;o&&(a&&r._OrtClearBoundOutputs(o.handle)!==0&&At("Can't clear bound outputs."),r._OrtReleaseBinding(o.handle)!==0&&At("Can't release IO binding.")),(l=r.jsepOnReleaseSession)==null||l.call(r,e),i.forEach(u=>r._OrtFree(u)),n.forEach(u=>r._OrtFree(u)),r._OrtReleaseSession(s)!==0&&At("Can't release session."),qs.delete(e)},Vu=async(e,r,t,s,i,n=!1)=>{if(!e){r.push(0);return}let o=ar(),a=o.PTR_SIZE,l=e[0],u=e[1],p=e[3],c=p,h,g;if(l==="string"&&(p==="gpu-buffer"||p==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(n&&p!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${i} when enableGraphCapture is true.`);if(p==="gpu-buffer"){let A=e[2].gpuBuffer;g=_n(Rn(l),u);let v=o.jsepRegisterBuffer;if(!v)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');h=v(s,i,A,g)}else if(p==="ml-tensor"){let A=e[2].mlTensor;g=_n(Rn(l),u);let v=o.jsepRegisterMLTensor;if(!v)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');h=v(s,A,Rn(l),u)}else{let A=e[2];if(Array.isArray(A)){g=a*A.length,h=o._malloc(g),t.push(h);for(let v=0;vo.setValue(E+y*a,v,a===4?"i32":"i64"));let A=o._OrtCreateTensor(Rn(l),h,g,E,u.length,Od(c));A===0&&At(`Can't create tensor for input/output. session=${s}, index=${i}.`),r.push(A)}finally{o.stackRestore(_)}},Uu=async(e,r,t,s,i,n)=>{var Q,q,U;let o=ar(),a=o.PTR_SIZE,l=qs.get(e);if(!l)throw new Error(`cannot run inference. invalid session id: ${e}`);let u=l[0],p=l[1],c=l[2],h=l[3],g=l[4],_=l[5],E=r.length,A=s.length,v=0,y=[],k=[],P=[],M=[],w=o.stackSave(),x=o.stackAlloc(E*a),$=o.stackAlloc(E*a),z=o.stackAlloc(A*a),R=o.stackAlloc(A*a);try{[v,y]=wp(n);for(let J=0;JMe*K,1);N=mn(se);let He=h==null?void 0:h.outputPreferredLocations[s[J]];if(N==="string"){if(He==="gpu-buffer"||He==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let Me=[];for(let K=0;K0){let Me=o.jsepGetBuffer;if(!Me)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let K=Me(O),j=_n(se,ke);if(j===void 0||!Ad(N))throw new Error(`Unsupported data type: ${N}`);he=!0,H.push([N,_e,{gpuBuffer:K,download:o.jsepCreateDownloader(K,j,N),dispose:()=>{o._OrtReleaseTensor(ie)!==0&&At("Can't release tensor.")}},"gpu-buffer"])}else if(He==="ml-tensor"&&ke>0){let Me=o.jsepEnsureTensor;if(!Me)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(_n(se,ke)===void 0||!Fd(N))throw new Error(`Unsupported data type: ${N}`);let K=await Me(e,O,se,_e,!1);he=!0,H.push([N,_e,{mlTensor:K,download:o.jsepCreateMLTensorDownloader(O,N),dispose:()=>{o.jsepReleaseTensorId(O),o._OrtReleaseTensor(ie)}},"ml-tensor"])}else{let Me=Id(N),K=new Me(ke);new Uint8Array(K.buffer,K.byteOffset,K.byteLength).set(o.HEAPU8.subarray(O,O+K.byteLength)),H.push([N,_e,K,"cpu"])}}finally{o.stackRestore(ae),N==="string"&&O&&o._free(O),he||o._OrtReleaseTensor(ie),(U=o.jsepOnRunEnd)==null||U.call(o,u)}}return h&&!g&&(o._OrtClearBoundOutputs(h.handle)!==0&&At("Can't clear bound outputs."),qs.set(e,[u,p,c,h,g,!1])),H}finally{o.stackRestore(w),k.forEach(Z=>o._OrtReleaseTensor(Z)),P.forEach(Z=>o._OrtReleaseTensor(Z)),M.forEach(Z=>o._free(Z)),v!==0&&o._OrtReleaseRunOptions(v),y.forEach(Z=>o._free(Z))}},Wu=e=>{let r=ar(),t=qs.get(e);if(!t)throw new Error("invalid session id");let s=t[0],i=r._OrtEndProfiling(s);i===0&&At("Can't get an profile file name."),r._OrtFree(i)},Gu=e=>{let r=[];for(let t of e){let s=t[2];!Array.isArray(s)&&"buffer"in s&&r.push(s.buffer)}return r}}),Qs,Or,Un,ji,Vi,Oa,Ku,Da,Tn,xn,zw,Bw,Rw,Nw,jw,Vw,Uw,Ww,Gw=Ve(()=>{ns(),Lw(),fn(),Pd(),Qs=()=>!!Ut.wasm.proxy&&typeof document<"u",Un=!1,ji=!1,Vi=!1,Da=new Map,Tn=(e,r)=>{let t=Da.get(e);t?t.push(r):Da.set(e,[r])},xn=()=>{if(Un||!ji||Vi||!Or)throw new Error("worker not ready")},zw=e=>{switch(e.data.type){case"init-wasm":Un=!1,e.data.err?(Vi=!0,Ku[1](e.data.err)):(ji=!0,Ku[0]()),Oa&&(URL.revokeObjectURL(Oa),Oa=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let r=Da.get(e.data.type);e.data.err?r.shift()[1](e.data.err):r.shift()[0](e.data.out);break}}},Bw=async()=>{if(!ji){if(Un)throw new Error("multiple calls to 'initWasm()' detected.");if(Vi)throw new Error("previous call to 'initWasm()' failed.");if(Un=!0,Qs())return new Promise((e,r)=>{Or==null||Or.terminate(),fp().then(([t,s])=>{try{Or=s,Or.onerror=n=>r(n),Or.onmessage=zw,Ku=[e,r];let i={type:"init-wasm",in:Ut};!i.in.wasm.wasmPaths&&(t||vd)&&(i.in.wasm.wasmPaths={wasm:new URL("/assets/ort-wasm-simd-threaded.jsep-BAR87mbD.wasm",self.location.href).href}),Or.postMessage(i),Oa=t}catch(i){r(i)}},r)});try{await $d(Ut.wasm),await Bu(Ut),ji=!0}catch(e){throw Vi=!0,e}finally{Un=!1}}},Rw=async e=>{if(Qs())return xn(),new Promise((r,t)=>{Tn("init-ep",[r,t]);let s={type:"init-ep",in:{epName:e,env:Ut}};Or.postMessage(s)});await Ru(Ut,e)},Nw=async e=>Qs()?(xn(),new Promise((r,t)=>{Tn("copy-from",[r,t]);let s={type:"copy-from",in:{buffer:e}};Or.postMessage(s,[e.buffer])})):Fa(e),jw=async(e,r)=>{if(Qs()){if(r!=null&&r.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return xn(),new Promise((t,s)=>{Tn("create",[t,s]);let i={type:"create",in:{model:e,options:{...r}}},n=[];e instanceof Uint8Array&&n.push(e.buffer),Or.postMessage(i,n)})}else return Nu(e,r)},Vw=async e=>{if(Qs())return xn(),new Promise((r,t)=>{Tn("release",[r,t]);let s={type:"release",in:e};Or.postMessage(s)});ju(e)},Uw=async(e,r,t,s,i,n)=>{if(Qs()){if(t.some(o=>o[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(i.some(o=>o))throw new Error("pre-allocated output tensor is not supported for proxy.");return xn(),new Promise((o,a)=>{Tn("run",[o,a]);let l=t,u={type:"run",in:{sessionId:e,inputIndices:r,inputs:l,outputIndices:s,options:n}};Or.postMessage(u,Gu(l))})}else return Uu(e,r,t,s,i,n)},Ww=async e=>{if(Qs())return xn(),new Promise((r,t)=>{Tn("end-profiling",[r,t]);let s={type:"end-profiling",in:e};Or.postMessage(s)});Wu(e)}}),Hu,Kw,Hw,dT=Ve(()=>{ns(),Gw(),pt(),_d(),xp(),Hu=(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()}`)}},Kw=e=>{switch(e[3]){case"cpu":return new rs(e[0],e[2],e[1]);case"gpu-buffer":{let r=e[0];if(!Ad(r))throw new Error(`not supported data type: ${r} for deserializing GPU tensor`);let{gpuBuffer:t,download:s,dispose:i}=e[2];return rs.fromGpuBuffer(t,{dataType:r,dims:e[1],download:s,dispose:i})}case"ml-tensor":{let r=e[0];if(!Fd(r))throw new Error(`not supported data type: ${r} for deserializing MLTensor tensor`);let{mlTensor:t,download:s,dispose:i}=e[2];return rs.fromMLTensor(t,{dataType:r,dims:e[1],download:s,dispose:i})}default:throw new Error(`invalid data location: ${e[3]}`)}},Hw=class{async fetchModelAndCopyToWasmMemory(e){return Nw(await Dd(e))}async loadModel(e,r){ss();let t;typeof e=="string"?t=await this.fetchModelAndCopyToWasmMemory(e):t=e,[this.sessionId,this.inputNames,this.outputNames]=await jw(t,r),Hr()}async dispose(){return Vw(this.sessionId)}async run(e,r,t){ss();let s=[],i=[];Object.entries(e).forEach(c=>{let h=c[0],g=c[1],_=this.inputNames.indexOf(h);if(_===-1)throw new Error(`invalid input '${h}'`);s.push(g),i.push(_)});let n=[],o=[];Object.entries(r).forEach(c=>{let h=c[0],g=c[1],_=this.outputNames.indexOf(h);if(_===-1)throw new Error(`invalid output '${h}'`);n.push(g),o.push(_)});let a=s.map((c,h)=>Hu(c,()=>`input "${this.inputNames[i[h]]}"`)),l=n.map((c,h)=>c?Hu(c,()=>`output "${this.outputNames[o[h]]}"`):null),u=await Uw(this.sessionId,i,a,o,l,t),p={};for(let c=0;cQu,initializeFlags:()=>qu,wasmBackend:()=>Qw});var qu,Qu,Qw,uT=Ve(()=>{ns(),Gw(),dT(),qu=()=>{if((typeof Ut.wasm.initTimeout!="number"||Ut.wasm.initTimeout<0)&&(Ut.wasm.initTimeout=0),Ut.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 Ut.wasm.proxy!="boolean"&&(Ut.wasm.proxy=!1),typeof Ut.wasm.trace!="boolean"&&(Ut.wasm.trace=!1),typeof Ut.wasm.numThreads!="number"||!Number.isInteger(Ut.wasm.numThreads)||Ut.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)Ut.wasm.numThreads=1;else{let e=typeof navigator>"u"?Q0("node:os").cpus().length:navigator.hardwareConcurrency;Ut.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},Qu=class{async init(e){qu(),await Bw(),await Rw(e)}async createInferenceSessionHandler(e,r){let t=new Hw;return await t.loadModel(e,r),Promise.resolve(t)}},Qw=new Qu});ns(),ns(),ns();var cT="1.22.0-dev.20250306-ccf8fdd9ea",pT=sp;{let e=(uT(),fa(qw)).wasmBackend;pn("webgpu",e,5),pn("webnn",e,5),pn("cpu",e,10),pn("wasm",e,10)}Object.defineProperty(Ut.versions,"web",{value:cT,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 hT=Object.freeze({__proto__:null,get InferenceSession(){return md},get TRACE(){return ki},get TRACE_FUNC_BEGIN(){return ss},get TRACE_FUNC_END(){return Hr},get Tensor(){return rs},default:pT,get env(){return Ut},get registerBackend(){return pn}}),Os={},fT={"onnxruntime-common":e=>{e.exports=G0},"onnxruntime-web":e=>{e.exports=hT},"?2ce3":()=>{},"?7a2c":()=>{},"?a42a":()=>{},"?2b25":()=>{},"?569f":()=>{},"?3f59":()=>{},"?154a":()=>{},"./node_modules/@huggingface/jinja/dist/index.js":(e,r,t)=>{t.r(r),t.d(r,{Environment:()=>Ae,Interpreter:()=>Ie,Template:()=>We,parse:()=>N,tokenize:()=>c});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",EndIf:"EndIf",ElseIf:"ElseIf",EndFor:"EndFor",And:"And",Or:"Or",Not:"UnaryOperator",Macro:"Macro",EndMacro:"EndMacro"}),i=Object.freeze({set:s.Set,for:s.For,in:s.In,is:s.Is,if:s.If,else:s.Else,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(D,ee){this.value=D,this.type=ee}};function o(D){return/\w/.test(D)}function a(D){return/[0-9]/.test(D)}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(D,ee={}){return D.endsWith(` +`)&&(D=D.slice(0,-1)),D=D.replace(/{#.*?#}/gs,"{##}"),ee.lstrip_blocks&&(D=D.replace(/^[ \t]*({[#%])/gm,"$1")),ee.trim_blocks&&(D=D.replace(/([#%]})\n/g,"$1")),D.replace(/{##}/g,"").replace(/-%}\s*/g,"%}").replace(/\s*{%-/g,"{%").replace(/-}}\s*/g,"}}").replace(/\s*{{-/g,"{{")}function c(D,ee={}){var ve,Re,Fe;const B=[],te=p(D,ee);let de=0;const be=je=>{let qe="";for(;je(te[de]);){if(te[de]==="\\"){if(++de,de>=te.length)throw new SyntaxError("Unexpected end of input");const Xe=te[de++],ct=u.get(Xe);if(ct===void 0)throw new SyntaxError(`Unexpected escaped character: ${Xe}`);qe+=ct;continue}if(qe+=te[de++],de>=te.length)throw new SyntaxError("Unexpected end of input")}return qe};e:for(;de0){B.push(new n(Xe,s.Text));continue}}be(Xe=>/\s/.test(Xe));const qe=te[de];if(qe==="-"||qe==="+"){const Xe=(Re=B.at(-1))==null?void 0:Re.type;if(Xe===s.Text||Xe===void 0)throw new SyntaxError(`Unexpected character: ${qe}`);switch(Xe){case s.Identifier:case s.NumericLiteral:case s.BooleanLiteral:case s.NullLiteral:case s.StringLiteral:case s.CloseParen:case s.CloseSquareBracket:break;default:{++de;const ct=be(a);B.push(new n(`${qe}${ct}`,ct.length>0?s.NumericLiteral:s.UnaryOperator));continue}}}for(const[Xe,ct]of l)if(te.slice(de,de+Xe.length)===Xe){B.push(new n(Xe,ct)),de+=Xe.length;continue e}if(qe==="'"||qe==='"'){++de;const Xe=be(ct=>ct!==qe);B.push(new n(Xe,s.StringLiteral)),++de;continue}if(a(qe)){const Xe=be(a);B.push(new n(Xe,s.NumericLiteral));continue}if(o(qe)){const Xe=be(o),ct=Object.hasOwn(i,Xe)?i[Xe]:s.Identifier;ct===s.In&&((Fe=B.at(-1))==null?void 0:Fe.type)===s.Not?(B.pop(),B.push(new n("not in",s.NotIn))):B.push(new n(Xe,ct));continue}throw new SyntaxError(`Unexpected character: ${qe}`)}return B}var h=class{constructor(){re(this,"type","Statement")}},g=class extends h{constructor(ee){super();re(this,"type","Program");this.body=ee}},_=class extends h{constructor(ee,B,te){super();re(this,"type","If");this.test=ee,this.body=B,this.alternate=te}},E=class extends h{constructor(ee,B,te,de){super();re(this,"type","For");this.loopvar=ee,this.iterable=B,this.body=te,this.defaultBlock=de}},A=class extends h{constructor(ee,B){super();re(this,"type","Set");this.assignee=ee,this.value=B}},v=class extends h{constructor(ee,B,te){super();re(this,"type","Macro");this.name=ee,this.args=B,this.body=te}},y=class extends h{constructor(){super(...arguments);re(this,"type","Expression")}},k=class extends y{constructor(ee,B,te){super();re(this,"type","MemberExpression");this.object=ee,this.property=B,this.computed=te}},P=class extends y{constructor(ee,B){super();re(this,"type","CallExpression");this.callee=ee,this.args=B}},M=class extends y{constructor(ee){super();re(this,"type","Identifier");this.value=ee}},w=class extends y{constructor(ee){super();re(this,"type","Literal");this.value=ee}},x=class extends w{constructor(){super(...arguments);re(this,"type","NumericLiteral")}},$=class extends w{constructor(){super(...arguments);re(this,"type","StringLiteral")}},z=class extends w{constructor(){super(...arguments);re(this,"type","BooleanLiteral")}},R=class extends w{constructor(){super(...arguments);re(this,"type","NullLiteral")}},Q=class extends w{constructor(){super(...arguments);re(this,"type","ArrayLiteral")}},q=class extends w{constructor(){super(...arguments);re(this,"type","TupleLiteral")}},U=class extends w{constructor(){super(...arguments);re(this,"type","ObjectLiteral")}},Z=class extends y{constructor(ee,B,te){super();re(this,"type","BinaryExpression");this.operator=ee,this.left=B,this.right=te}},H=class extends y{constructor(ee,B){super();re(this,"type","FilterExpression");this.operand=ee,this.filter=B}},J=class extends y{constructor(ee,B){super();re(this,"type","SelectExpression");this.iterable=ee,this.test=B}},ie=class extends y{constructor(ee,B,te){super();re(this,"type","TestExpression");this.operand=ee,this.negate=B,this.test=te}},ae=class extends y{constructor(ee,B){super();re(this,"type","UnaryExpression");this.operator=ee,this.argument=B}},ue=class extends y{constructor(ee=void 0,B=void 0,te=void 0){super();re(this,"type","SliceExpression");this.start=ee,this.stop=B,this.step=te}},he=class extends y{constructor(ee,B){super();re(this,"type","KeywordArgumentExpression");this.key=ee,this.value=B}};function N(D){const ee=new g([]);let B=0;function te(Be,et){const it=D[B++];if(!it||it.type!==Be)throw new Error(`Parser Error: ${et}. ${it.type} !== ${Be}.`);return it}function de(){switch(D[B].type){case s.Text:return Re();case s.OpenStatement:return Fe();case s.OpenExpression:return je();default:throw new SyntaxError(`Unexpected token type: ${D[B].type}`)}}function be(...Be){return B+Be.length<=D.length&&Be.some((et,it)=>et!==D[B+it].type)}function ve(...Be){return B+Be.length<=D.length&&Be.every((et,it)=>et===D[B+it].type)}function Re(){return new $(te(s.Text,"Expected text token").value)}function Fe(){te(s.OpenStatement,"Expected opening statement token");let Be;switch(D[B].type){case s.Set:++B,Be=qe(),te(s.CloseStatement,"Expected closing statement token");break;case s.If:++B,Be=Xe(),te(s.OpenStatement,"Expected {% token"),te(s.EndIf,"Expected endif token"),te(s.CloseStatement,"Expected %} token");break;case s.Macro:++B,Be=ct(),te(s.OpenStatement,"Expected {% token"),te(s.EndMacro,"Expected endmacro token"),te(s.CloseStatement,"Expected %} token");break;case s.For:++B,Be=nr(),te(s.OpenStatement,"Expected {% token"),te(s.EndFor,"Expected endfor token"),te(s.CloseStatement,"Expected %} token");break;default:throw new SyntaxError(`Unknown statement type: ${D[B].type}`)}return Be}function je(){te(s.OpenExpression,"Expected opening expression token");const Be=jt();return te(s.CloseExpression,"Expected closing expression token"),Be}function qe(){const Be=jt();if(ve(s.Equals)){++B;const et=qe();return new A(Be,et)}return Be}function Xe(){var rr,zt,kr,hs,fs,Er,ms,_s;const Be=jt();te(s.CloseStatement,"Expected closing statement token");const et=[],it=[];for(;!(((rr=D[B])==null?void 0:rr.type)===s.OpenStatement&&(((zt=D[B+1])==null?void 0:zt.type)===s.ElseIf||((kr=D[B+1])==null?void 0:kr.type)===s.Else||((hs=D[B+1])==null?void 0:hs.type)===s.EndIf));)et.push(de());if(((fs=D[B])==null?void 0:fs.type)===s.OpenStatement&&((Er=D[B+1])==null?void 0:Er.type)!==s.EndIf)if(++B,ve(s.ElseIf))te(s.ElseIf,"Expected elseif token"),it.push(Xe());else for(te(s.Else,"Expected else token"),te(s.CloseStatement,"Expected closing statement token");!(((ms=D[B])==null?void 0:ms.type)===s.OpenStatement&&((_s=D[B+1])==null?void 0:_s.type)===s.EndIf);)it.push(de());return new _(Be,et,it)}function ct(){const Be=fr();if(Be.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");const et=qr();te(s.CloseStatement,"Expected closing statement token");const it=[];for(;be(s.OpenStatement,s.EndMacro);)it.push(de());return new v(Be,et,it)}function wt(Be=!1){const et=Be?fr:jt,it=[et()],rr=ve(s.Comma);for(;rr&&(++B,it.push(et()),!!ve(s.Comma)););return rr?new q(it):it[0]}function nr(){const Be=wt(!0);if(!(Be instanceof M||Be instanceof q))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${Be.type} instead`);te(s.In,"Expected `in` keyword following loop variable");const et=jt();te(s.CloseStatement,"Expected closing statement token");const it=[];for(;be(s.OpenStatement,s.EndFor)&&be(s.OpenStatement,s.Else);)it.push(de());const rr=[];if(ve(s.OpenStatement,s.Else))for(++B,++B,te(s.CloseStatement,"Expected closing statement token");be(s.OpenStatement,s.EndFor);)rr.push(de());return new E(Be,et,it,rr)}function jt(){return dr()}function dr(){const Be=us();if(ve(s.If)){++B;const et=us();if(ve(s.Else)){++B;const it=us();return new _(et,[Be],[it])}else return new J(Be,et)}return Be}function us(){let Be=Ds();for(;ve(s.Or);){const et=D[B];++B;const it=Ds();Be=new Z(et,Be,it)}return Be}function Ds(){let Be=Dr();for(;ve(s.And);){const et=D[B];++B;const it=Dr();Be=new Z(et,Be,it)}return Be}function Dr(){let Be;for(;ve(s.Not);){const et=D[B];++B;const it=Dr();Be=new ae(et,it)}return Be??cs()}function cs(){let Be=Ls();for(;ve(s.ComparisonBinaryOperator)||ve(s.In)||ve(s.NotIn);){const et=D[B];++B;const it=Ls();Be=new Z(et,Be,it)}return Be}function Ls(){let Be=Es();for(;ve(s.AdditiveBinaryOperator);){const et=D[B];++B;const it=Es();Be=new Z(et,Be,it)}return Be}function jr(){const Be=xs(fr());return ve(s.OpenParen)?dt(Be):Be}function dt(Be){let et=new P(Be,qr());return et=xs(et),ve(s.OpenParen)&&(et=dt(et)),et}function qr(){te(s.OpenParen,"Expected opening parenthesis for arguments list");const Be=Vr();return te(s.CloseParen,"Expected closing parenthesis for arguments list"),Be}function Vr(){const Be=[];for(;!ve(s.CloseParen);){let et=jt();if(ve(s.Equals)){if(++B,!(et instanceof M))throw new SyntaxError("Expected identifier for keyword argument");const it=jt();et=new he(et,it)}Be.push(et),ve(s.Comma)&&++B}return Be}function ps(){const Be=[];let et=!1;for(;!ve(s.CloseSquareBracket);)ve(s.Colon)?(Be.push(void 0),++B,et=!0):(Be.push(jt()),ve(s.Colon)&&(++B,et=!0));if(Be.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(et){if(Be.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new ue(...Be)}return Be[0]}function xs(Be){for(;ve(s.Dot)||ve(s.OpenSquareBracket);){const et=D[B];++B;let it;const rr=et.type!==s.Dot;if(rr)it=ps(),te(s.CloseSquareBracket,"Expected closing square bracket");else if(it=fr(),it.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");Be=new k(Be,it,rr)}return Be}function Es(){let Be=Ps();for(;ve(s.MultiplicativeBinaryOperator);){const et=D[B];++B;const it=Ps();Be=new Z(et,Be,it)}return Be}function Ps(){let Be=zs();for(;ve(s.Is);){++B;const et=ve(s.Not);et&&++B;let it=fr();if(it instanceof z?it=new M(it.value.toString()):it instanceof R&&(it=new M("none")),!(it instanceof M))throw new SyntaxError("Expected identifier for the test");Be=new ie(Be,et,it)}return Be}function zs(){let Be=jr();for(;ve(s.Pipe);){++B;let et=fr();if(!(et instanceof M))throw new SyntaxError("Expected identifier for the filter");ve(s.OpenParen)&&(et=dt(et)),Be=new H(Be,et)}return Be}function fr(){const Be=D[B];switch(Be.type){case s.NumericLiteral:return++B,new x(Number(Be.value));case s.StringLiteral:return++B,new $(Be.value);case s.BooleanLiteral:return++B,new z(Be.value.toLowerCase()==="true");case s.NullLiteral:return++B,new R(null);case s.Identifier:return++B,new M(Be.value);case s.OpenParen:{++B;const et=wt();if(D[B].type!==s.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${D[B].type} instead`);return++B,et}case s.OpenSquareBracket:{++B;const et=[];for(;!ve(s.CloseSquareBracket);)et.push(jt()),ve(s.Comma)&&++B;return++B,new Q(et)}case s.OpenCurlyBracket:{++B;const et=new Map;for(;!ve(s.CloseCurlyBracket);){const it=jt();te(s.Colon,"Expected colon between key and value in object literal");const rr=jt();et.set(it,rr),ve(s.Comma)&&++B}return++B,new U(et)}default:throw new SyntaxError(`Unexpected token: ${Be.type}`)}}for(;B=0?(ee=(ee??(ee=0))<0?Math.max(D.length+ee,0):Math.min(ee,D.length),B=(B??(B=D.length))<0?Math.max(D.length+B,0):Math.min(B,D.length)):(ee=(ee??(ee=D.length-1))<0?Math.max(D.length+ee,-1):Math.min(ee,D.length-1),B=(B??(B=-1))<-1?Math.max(D.length+B,-1):Math.min(B,D.length-1));const be=[];for(let ve=ee;de*veee.toUpperCase())}var X=class{constructor(D=void 0){re(this,"type","RuntimeValue");re(this,"value");re(this,"builtins",new Map);this.value=D}__bool__(){return new ke(!!this.value)}},we=class extends X{constructor(){super(...arguments);re(this,"type","NumericValue")}},_e=class extends X{constructor(){super(...arguments);re(this,"type","StringValue");re(this,"builtins",new Map([["upper",new fe(()=>new _e(this.value.toUpperCase()))],["lower",new fe(()=>new _e(this.value.toLowerCase()))],["strip",new fe(()=>new _e(this.value.trim()))],["title",new fe(()=>new _e(se(this.value)))],["length",new we(this.value.length)],["rstrip",new fe(()=>new _e(this.value.trimEnd()))],["lstrip",new fe(()=>new _e(this.value.trimStart()))],["split",new fe(ee=>{const B=ee[0]??new Pe;if(!(B instanceof _e||B instanceof Pe))throw new Error("sep argument must be a string or null");const te=ee[1]??new we(-1);if(!(te instanceof we))throw new Error("maxsplit argument must be a number");let de=[];if(B instanceof Pe){const be=this.value.trimStart();for(const{0:ve,index:Re}of be.matchAll(/\S+/g)){if(te.value!==-1&&de.length>=te.value&&Re!==void 0){de.push(ve+be.slice(Re+ve.length));break}de.push(ve)}}else{if(B.value==="")throw new Error("empty separator");de=this.value.split(B.value),te.value!==-1&&de.length>te.value&&de.push(de.splice(te.value).join(B.value))}return new K(de.map(be=>new _e(be)))})]]))}},ke=class extends X{constructor(){super(...arguments);re(this,"type","BooleanValue")}},He=class extends X{constructor(){super(...arguments);re(this,"type","ObjectValue");re(this,"builtins",new Map([["get",new fe(([ee,B])=>{if(!(ee instanceof _e))throw new Error(`Object key must be a string: got ${ee.type}`);return this.value.get(ee.value)??B??new Pe})],["items",new fe(()=>new K(Array.from(this.value.entries()).map(([ee,B])=>new K([new _e(ee),B]))))]]))}__bool__(){return new ke(this.value.size>0)}},Me=class extends He{constructor(){super(...arguments);re(this,"type","KeywordArgumentsValue")}},K=class extends X{constructor(){super(...arguments);re(this,"type","ArrayValue");re(this,"builtins",new Map([["length",new we(this.value.length)]]))}__bool__(){return new ke(this.value.length>0)}},j=class extends K{constructor(){super(...arguments);re(this,"type","TupleValue")}},fe=class extends X{constructor(){super(...arguments);re(this,"type","FunctionValue")}},Pe=class extends X{constructor(){super(...arguments);re(this,"type","NullValue")}},xe=class extends X{constructor(){super(...arguments);re(this,"type","UndefinedValue")}},Ae=class{constructor(D){re(this,"variables",new Map([["namespace",new fe(D=>{if(D.length===0)return new He(new Map);if(D.length!==1||!(D[0]instanceof He))throw new Error("`namespace` expects either zero arguments or a single object argument");return D[0]})]]));re(this,"tests",new Map([["boolean",D=>D.type==="BooleanValue"],["callable",D=>D instanceof fe],["odd",D=>{if(D.type!=="NumericValue")throw new Error(`Cannot apply test "odd" to type: ${D.type}`);return D.value%2!==0}],["even",D=>{if(D.type!=="NumericValue")throw new Error(`Cannot apply test "even" to type: ${D.type}`);return D.value%2===0}],["false",D=>D.type==="BooleanValue"&&!D.value],["true",D=>D.type==="BooleanValue"&&D.value],["none",D=>D.type==="NullValue"],["string",D=>D.type==="StringValue"],["number",D=>D.type==="NumericValue"],["integer",D=>D.type==="NumericValue"&&Number.isInteger(D.value)],["iterable",D=>D.type==="ArrayValue"||D.type==="StringValue"],["mapping",D=>D.type==="ObjectValue"],["lower",D=>{const ee=D.value;return D.type==="StringValue"&&ee===ee.toLowerCase()}],["upper",D=>{const ee=D.value;return D.type==="StringValue"&&ee===ee.toUpperCase()}],["none",D=>D.type==="NullValue"],["defined",D=>D.type!=="UndefinedValue"],["undefined",D=>D.type==="UndefinedValue"],["equalto",(D,ee)=>D.value===ee.value],["eq",(D,ee)=>D.value===ee.value]]));this.parent=D}set(D,ee){return this.declareVariable(D,Le(ee))}declareVariable(D,ee){if(this.variables.has(D))throw new SyntaxError(`Variable already declared: ${D}`);return this.variables.set(D,ee),ee}setVariable(D,ee){return this.variables.set(D,ee),ee}resolve(D){if(this.variables.has(D))return this;if(this.parent)return this.parent.resolve(D);throw new Error(`Unknown variable: ${D}`)}lookupVariable(D){try{return this.resolve(D).variables.get(D)??new xe}catch{return new xe}}},Ie=class{constructor(D){re(this,"global");this.global=D??new Ae}run(D){return this.evaluate(D,this.global)}evaluateBinaryExpression(D,ee){const B=this.evaluate(D.left,ee);switch(D.operator.value){case"and":return B.__bool__().value?this.evaluate(D.right,ee):B;case"or":return B.__bool__().value?B:this.evaluate(D.right,ee)}const te=this.evaluate(D.right,ee);switch(D.operator.value){case"==":return new ke(B.value==te.value);case"!=":return new ke(B.value!=te.value)}if(B instanceof xe||te instanceof xe)throw new Error("Cannot perform operation on undefined values");if(B instanceof Pe||te instanceof Pe)throw new Error("Cannot perform operation on null values");if(B instanceof we&&te instanceof we)switch(D.operator.value){case"+":return new we(B.value+te.value);case"-":return new we(B.value-te.value);case"*":return new we(B.value*te.value);case"/":return new we(B.value/te.value);case"%":return new we(B.value%te.value);case"<":return new ke(B.value":return new ke(B.value>te.value);case">=":return new ke(B.value>=te.value);case"<=":return new ke(B.value<=te.value)}else if(B instanceof K&&te instanceof K)switch(D.operator.value){case"+":return new K(B.value.concat(te.value))}else if(te instanceof K){const de=te.value.find(be=>be.value===B.value)!==void 0;switch(D.operator.value){case"in":return new ke(de);case"not in":return new ke(!de)}}if(B instanceof _e||te instanceof _e)switch(D.operator.value){case"+":return new _e(B.value.toString()+te.value.toString())}if(B instanceof _e&&te instanceof _e)switch(D.operator.value){case"in":return new ke(te.value.includes(B.value));case"not in":return new ke(!te.value.includes(B.value))}if(B instanceof _e&&te instanceof He)switch(D.operator.value){case"in":return new ke(te.value.has(B.value));case"not in":return new ke(!te.value.has(B.value))}throw new SyntaxError(`Unknown operator "${D.operator.value}" between ${B.type} and ${te.type}`)}evaluateArguments(D,ee){const B=[],te=new Map;for(const de of D)if(de.type==="KeywordArgumentExpression"){const be=de;te.set(be.key.value,this.evaluate(be.value,ee))}else{if(te.size>0)throw new Error("Positional arguments must come before keyword arguments");B.push(this.evaluate(de,ee))}return[B,te]}evaluateFilterExpression(D,ee){const B=this.evaluate(D.operand,ee);if(D.filter.type==="Identifier"){const te=D.filter;if(te.value==="tojson")return new _e(Ne(B));if(B instanceof K)switch(te.value){case"list":return B;case"first":return B.value[0];case"last":return B.value[B.value.length-1];case"length":return new we(B.value.length);case"reverse":return new K(B.value.reverse());case"sort":return new K(B.value.sort((de,be)=>{if(de.type!==be.type)throw new Error(`Cannot compare different types: ${de.type} and ${be.type}`);switch(de.type){case"NumericValue":return de.value-be.value;case"StringValue":return de.value.localeCompare(be.value);default:throw new Error(`Cannot compare type: ${de.type}`)}}));case"join":return new _e(B.value.map(de=>de.value).join(""));default:throw new Error(`Unknown ArrayValue filter: ${te.value}`)}else if(B instanceof _e)switch(te.value){case"length":return new we(B.value.length);case"upper":return new _e(B.value.toUpperCase());case"lower":return new _e(B.value.toLowerCase());case"title":return new _e(se(B.value));case"capitalize":return new _e(B.value.charAt(0).toUpperCase()+B.value.slice(1));case"trim":return new _e(B.value.trim());case"indent":return new _e(B.value.split(` +`).map((de,be)=>be===0||de.length===0?de:" "+de).join(` +`));case"join":case"string":return B;default:throw new Error(`Unknown StringValue filter: ${te.value}`)}else if(B instanceof we)switch(te.value){case"abs":return new we(Math.abs(B.value));default:throw new Error(`Unknown NumericValue filter: ${te.value}`)}else if(B instanceof He)switch(te.value){case"items":return new K(Array.from(B.value.entries()).map(([de,be])=>new K([new _e(de),be])));case"length":return new we(B.value.size);default:throw new Error(`Unknown ObjectValue filter: ${te.value}`)}throw new Error(`Cannot apply filter "${te.value}" to type: ${B.type}`)}else if(D.filter.type==="CallExpression"){const te=D.filter;if(te.callee.type!=="Identifier")throw new Error(`Unknown filter: ${te.callee.type}`);const de=te.callee.value;if(de==="tojson"){const[,be]=this.evaluateArguments(te.args,ee),ve=be.get("indent")??new Pe;if(!(ve instanceof we||ve instanceof Pe))throw new Error("If set, indent must be a number");return new _e(Ne(B,ve.value))}else if(de==="join"){let be;if(B instanceof _e)be=Array.from(B.value);else if(B instanceof K)be=B.value.map(je=>je.value);else throw new Error(`Cannot apply filter "${de}" to type: ${B.type}`);const[ve,Re]=this.evaluateArguments(te.args,ee),Fe=ve.at(0)??Re.get("separator")??new _e("");if(!(Fe instanceof _e))throw new Error("separator must be a string");return new _e(be.join(Fe.value))}if(B instanceof K){switch(de){case"selectattr":case"rejectattr":{const be=de==="selectattr";if(B.value.some(Xe=>!(Xe instanceof He)))throw new Error(`\`${de}\` can only be applied to array of objects`);if(te.args.some(Xe=>Xe.type!=="StringLiteral"))throw new Error(`arguments of \`${de}\` must be strings`);const[ve,Re,Fe]=te.args.map(Xe=>this.evaluate(Xe,ee));let je;if(Re){const Xe=ee.tests.get(Re.value);if(!Xe)throw new Error(`Unknown test: ${Re.value}`);je=Xe}else je=(...Xe)=>Xe[0].__bool__().value;const qe=B.value.filter(Xe=>{const ct=Xe.value.get(ve.value),wt=ct?je(ct,Fe):!1;return be?wt:!wt});return new K(qe)}case"map":{const[,be]=this.evaluateArguments(te.args,ee);if(be.has("attribute")){const ve=be.get("attribute");if(!(ve instanceof _e))throw new Error("attribute must be a string");const Re=be.get("default"),Fe=B.value.map(je=>{if(!(je instanceof He))throw new Error("items in map must be an object");return je.value.get(ve.value)??Re??new xe});return new K(Fe)}else throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${de}`)}else if(B instanceof _e){switch(de){case"indent":{const[be,ve]=this.evaluateArguments(te.args,ee),Re=be.at(0)??ve.get("width")??new we(4);if(!(Re instanceof we))throw new Error("width must be a number");const Fe=be.at(1)??ve.get("first")??new ke(!1),je=be.at(2)??ve.get("blank")??new ke(!1),qe=B.value.split(` +`),Xe=" ".repeat(Re.value),ct=qe.map((wt,nr)=>!Fe.value&&nr===0||!je.value&&wt.length===0?wt:Xe+wt);return new _e(ct.join(` +`))}}throw new Error(`Unknown StringValue filter: ${de}`)}else throw new Error(`Cannot apply filter "${de}" to type: ${B.type}`)}throw new Error(`Unknown filter: ${D.filter.type}`)}evaluateTestExpression(D,ee){const B=this.evaluate(D.operand,ee),te=ee.tests.get(D.test.value);if(!te)throw new Error(`Unknown test: ${D.test.value}`);const de=te(B);return new ke(D.negate?!de:de)}evaluateUnaryExpression(D,ee){const B=this.evaluate(D.argument,ee);switch(D.operator.value){case"not":return new ke(!B.value);default:throw new SyntaxError(`Unknown operator: ${D.operator.value}`)}}evalProgram(D,ee){return this.evaluateBlock(D.body,ee)}evaluateBlock(D,ee){let B="";for(const te of D){const de=this.evaluate(te,ee);de.type!=="NullValue"&&de.type!=="UndefinedValue"&&(B+=de.value)}return new _e(B)}evaluateIdentifier(D,ee){return ee.lookupVariable(D.value)}evaluateCallExpression(D,ee){const[B,te]=this.evaluateArguments(D.args,ee);te.size>0&&B.push(new Me(te));const de=this.evaluate(D.callee,ee);if(de.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${de.type}`);return de.value(B,ee)}evaluateSliceExpression(D,ee,B){if(!(D instanceof K||D instanceof _e))throw new Error("Slice object must be an array or string");const te=this.evaluate(ee.start,B),de=this.evaluate(ee.stop,B),be=this.evaluate(ee.step,B);if(!(te instanceof we||te instanceof xe))throw new Error("Slice start must be numeric or undefined");if(!(de instanceof we||de instanceof xe))throw new Error("Slice stop must be numeric or undefined");if(!(be instanceof we||be instanceof xe))throw new Error("Slice step must be numeric or undefined");return D instanceof K?new K(G(D.value,te.value,de.value,be.value)):new _e(G(Array.from(D.value),te.value,de.value,be.value).join(""))}evaluateMemberExpression(D,ee){const B=this.evaluate(D.object,ee);let te;if(D.computed){if(D.property.type==="SliceExpression")return this.evaluateSliceExpression(B,D.property,ee);te=this.evaluate(D.property,ee)}else te=new _e(D.property.value);let de;if(B instanceof He){if(!(te instanceof _e))throw new Error(`Cannot access property with non-string: got ${te.type}`);de=B.value.get(te.value)??B.builtins.get(te.value)}else if(B instanceof K||B instanceof _e)if(te instanceof we)de=B.value.at(te.value),B instanceof _e&&(de=new _e(B.value.at(te.value)));else if(te instanceof _e)de=B.builtins.get(te.value);else throw new Error(`Cannot access property with non-string/non-number: got ${te.type}`);else{if(!(te instanceof _e))throw new Error(`Cannot access property with non-string: got ${te.type}`);de=B.builtins.get(te.value)}return de instanceof X?de:new xe}evaluateSet(D,ee){const B=this.evaluate(D.value,ee);if(D.assignee.type==="Identifier"){const te=D.assignee.value;ee.setVariable(te,B)}else if(D.assignee.type==="MemberExpression"){const te=D.assignee,de=this.evaluate(te.object,ee);if(!(de instanceof He))throw new Error("Cannot assign to member of non-object");if(te.property.type!=="Identifier")throw new Error("Cannot assign to member with non-identifier property");de.value.set(te.property.value,B)}else throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(D.assignee)}`);return new Pe}evaluateIf(D,ee){const B=this.evaluate(D.test,ee);return this.evaluateBlock(B.__bool__().value?D.body:D.alternate,ee)}evaluateFor(D,ee){const B=new Ae(ee);let te,de;if(D.iterable.type==="SelectExpression"){const je=D.iterable;de=this.evaluate(je.iterable,B),te=je.test}else de=this.evaluate(D.iterable,B);if(!(de instanceof K))throw new Error(`Expected iterable type in for loop: got ${de.type}`);const be=[],ve=[];for(let je=0;jewt.setVariable(D.loopvar.value,Xe);else if(D.loopvar.type==="TupleLiteral"){const wt=D.loopvar;if(Xe.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${Xe.type}`);const nr=Xe;if(wt.value.length!==nr.value.length)throw new Error(`Too ${wt.value.length>nr.value.length?"few":"many"} items to unpack`);ct=jt=>{for(let dr=0;dr0?be[je-1]:new xe],["nextitem",je{var ve;const de=new Ae(te);B=B.slice();let be;((ve=B.at(-1))==null?void 0:ve.type)==="KeywordArgumentsValue"&&(be=B.pop());for(let Re=0;Rethis.evaluate(B,ee)));case"TupleLiteral":return new j(D.value.map(B=>this.evaluate(B,ee)));case"ObjectLiteral":{const B=new Map;for(const[te,de]of D.value){const be=this.evaluate(te,ee);if(!(be instanceof _e))throw new Error(`Object keys must be strings: got ${be.type}`);B.set(be.value,this.evaluate(de,ee))}return new He(B)}case"Identifier":return this.evaluateIdentifier(D,ee);case"CallExpression":return this.evaluateCallExpression(D,ee);case"MemberExpression":return this.evaluateMemberExpression(D,ee);case"UnaryExpression":return this.evaluateUnaryExpression(D,ee);case"BinaryExpression":return this.evaluateBinaryExpression(D,ee);case"FilterExpression":return this.evaluateFilterExpression(D,ee);case"TestExpression":return this.evaluateTestExpression(D,ee);default:throw new SyntaxError(`Unknown node type: ${D.type}`)}}};function Le(D){switch(typeof D){case"number":return new we(D);case"string":return new _e(D);case"boolean":return new ke(D);case"undefined":return new xe;case"object":return D===null?new Pe:Array.isArray(D)?new K(D.map(Le)):new He(new Map(Object.entries(D).map(([ee,B])=>[ee,Le(B)])));case"function":return new fe((ee,B)=>{const te=D(...ee.map(de=>de.value))??null;return Le(te)});default:throw new Error(`Cannot convert to runtime value: ${D}`)}}function Ne(D,ee,B){const te=B??0;switch(D.type){case"NullValue":case"UndefinedValue":return"null";case"NumericValue":case"StringValue":case"BooleanValue":return JSON.stringify(D.value);case"ArrayValue":case"ObjectValue":{const de=ee?" ".repeat(ee):"",be=` +`+de.repeat(te),ve=be+de;if(D.type==="ArrayValue"){const Re=D.value.map(Fe=>Ne(Fe,ee,te+1));return ee?`[${ve}${Re.join(`,${ve}`)}${be}]`:`[${Re.join(", ")}]`}else{const Re=Array.from(D.value.entries()).map(([Fe,je])=>{const qe=`"${Fe}": ${Ne(je,ee,te+1)}`;return ee?`${ve}${qe}`:qe});return ee?`{${Re.join(",")}${be}}`:`{${Re.join(", ")}}`}}default:throw new Error(`Cannot convert to JSON: ${D.type}`)}}var We=class{constructor(D){re(this,"parsed");const ee=c(D,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=N(ee)}render(D){const ee=new Ae;if(ee.set("false",!1),ee.set("true",!0),ee.set("raise_exception",de=>{throw new Error(de)}),ee.set("range",O),D)for(const[de,be]of Object.entries(D))ee.set(de,be);return new Ie(ee).run(this.parsed).value}}},"./src/backends/onnx.js":(e,r,t)=>{var s;t.r(r),t.d(r,{Tensor:()=>a.Tensor,createInferenceSession:()=>A,deviceToExecutionProviders:()=>_,isONNXProxy:()=>k,isONNXTensor:()=>v});var i=t("./src/env.js"),n=t("?2ce3"),o=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,c;const h=Symbol.for("onnxruntime");if(h in globalThis)c=globalThis[h];else if(i.apis.IS_NODE_ENV){switch(c=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 c=o,i.apis.IS_WEBNN_AVAILABLE&&u.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),i.apis.IS_WEBGPU_AVAILABLE&&u.push("webgpu"),u.push("wasm"),p=["wasm"];const g=c.InferenceSession;function _(P=null){if(!P)return p;switch(P){case"auto":return u;case"gpu":return u.filter(M=>["webgpu","cuda","dml","webnn-gpu"].includes(M))}if(u.includes(P))return[l[P]??P];throw new Error(`Unsupported device: "${P}". Should be one of: ${u.join(", ")}.`)}let E=null;async function A(P,M,w){E&&await E;const x=g.create(P,M);E??(E=x);const $=await x;return $.config=w,$}function v(P){return P instanceof c.Tensor}const y=c==null?void 0:c.env;y!=null&&y.wasm&&(!(typeof ServiceWorkerGlobalScope<"u"&&self instanceof ServiceWorkerGlobalScope)&&!y.wasm.wasmPaths&&(y.wasm.wasmPaths=`https://cdn.jsdelivr.net/npm/@huggingface/transformers@${i.env.version}/dist/`),y.wasm.proxy=!1),y!=null&&y.webgpu&&(y.webgpu.powerPreference="high-performance");function k(){var P;return(P=y==null?void 0:y.wasm)==null?void 0:P.proxy}i.env.backends.onnx=y},"./src/base/feature_extraction_utils.js":(e,r,t)=>{t.r(r),t.d(r,{FeatureExtractor:()=>o,validate_audio_inputs:()=>a});var s=t("./src/utils/constants.js"),i=t("./src/utils/generic.js"),n=t("./src/utils/hub.js");class o extends i.Callable{constructor(u){super(),this.config=u}static async from_pretrained(u,p){const c=await(0,n.getModelJSON)(u,s.FEATURE_EXTRACTOR_NAME,!0,p);return new this(c)}}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:()=>P,center_to_corners_format:()=>c,post_process_instance_segmentation:()=>k,post_process_object_detection:()=>h,post_process_panoptic_segmentation:()=>y,post_process_semantic_segmentation:()=>g});var s=t("./src/utils/generic.js"),i=t("./src/utils/tensor.js"),n=t("./src/utils/maths.js");t("./src/utils/image.js");var o=t("./src/utils/core.js"),a=t("./src/utils/hub.js"),l=t("./src/utils/constants.js");function u(M,w,x=0,$=null){const z=M/w;let R=(0,n.bankers_round)(z)*w;return $!==null&&R>$&&(R=Math.floor(z)*w),Rw&&O.push(se)}else{let se=(0,n.max)(N.data)[1];if(se===U-1||(G=(0,n.softmax)(N.data),G[se]we*J[(_e+1)%2])),ie.boxes.push(X),ie.classes.push(se),ie.scores.push(G[se])}}Z.push(ie)}return Z}function g(M,w=null){const x=M.logits,$=x.dims[0];if(w!==null&&w.length!==$)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const z=[];for(let R=0;R<$;++R){const Q=w!==null?w[R]:null;let q=x[R];Q!==null&&(q=(0,i.interpolate)(q,Q,"bilinear",!1));const[U,Z]=Q??q.dims.slice(-2),H=new i.Tensor("int32",new Int32Array(U*Z),[U,Z]),J=q[0].data,ie=H.data;for(let he=1;heJ[O]&&(J[O]=N[O],ie[O]=he)}const ae=new Array(q.dims[0]);for(let he=0;hehe!==void 0);z.push({segmentation:H,labels:ue})}return z}function _(M,w,x,$){const z=[],R=[],Q=[];for(let q=0;qx&&(z.push(Z),R.push(ie),Q.push(H))}return[z,R,Q]}function E(M,w,x,$=.5,z=.8){const R=[];let Q=0,q=0;const U=w[x].data;for(let H=0;H=$&&++q;let Z=Q>0&&q>0;return Z&&(Z=Q/q>z),[Z,R]}function A(M,w,x,$,z,R=null,Q=null){const[q,U]=Q??M[0].dims,Z=new i.Tensor("int32",new Int32Array(q*U),[q,U]),H=[];if(Q!==null)for(let he=0;heie[G]&&(J[G]=he,ie[G]=O[G])}let ae=0;const ue=Z.data;for(let he=0;he200)throw new Error(`absolute aspect ratio must be smaller than 200, got ${Math.max(M,w)/Math.min(M,w)}`);let R=Math.round(M/x)*x,Q=Math.round(w/x)*x;if(R*Q>z){const q=Math.sqrt(M*w/z);R=Math.floor(M/q/x)*x,Q=Math.floor(w/q/x)*x}else if(R*Q<$){const q=Math.sqrt($/(M*w));R=Math.ceil(M*q/x)*x,Q=Math.ceil(w*q/x)*x}return[R,Q]}function y(M,w=.5,x=.5,$=.8,z=null,R=null){z===null&&(console.warn("`label_ids_to_fuse` unset. No instance will be fused."),z=new Set);const Q=M.class_queries_logits??M.logits,U=(M.masks_queries_logits??M.pred_masks).sigmoid();let[Z,H,J]=Q.dims;if(J-=1,R!==null&&R.length!==Z)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let ie=[];for(let ae=0;aeR?Z=Math.floor(R*U/z):R>z&&(U=Math.floor(z*Z/R)),await w.resize(Z,U,{resample:$}))}async crop_margin(w,x=200){const $=w.clone().grayscale(),z=(0,n.min)($.data)[0],Q=(0,n.max)($.data)[0]-z;if(Q===0)return w;const q=x/255;let U=$.width,Z=$.height,H=0,J=0;const ie=$.data;for(let ae=0;ae<$.height;++ae){const ue=ae*$.width;for(let he=0;he<$.width;++he)(ie[ue+he]-z)/Qthis.preprocess(R)));return{pixel_values:(0,i.stack)($.map(R=>R.pixel_values),0),original_sizes:$.map(R=>R.original_size),reshaped_input_sizes:$.map(R=>R.reshaped_input_size)}}static async from_pretrained(w,x){const $=await(0,a.getModelJSON)(w,l.IMAGE_PROCESSOR_NAME,!0,x);return new this($)}}},"./src/base/processing_utils.js":(e,r,t)=>{t.r(r),t.d(r,{Processor:()=>o});var s=t("./src/utils/constants.js"),i=t("./src/utils/generic.js"),n=t("./src/utils/hub.js");class o extends i.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,c]=await Promise.all([this.uses_processor_config?(0,n.getModelJSON)(l,s.PROCESSOR_NAME,!0,u):{},Promise.all(this.classes.filter(h=>h in this).map(async h=>{const g=await this[h].from_pretrained(l,u);return[h.replace(/_class$/,""),g]})).then(Object.fromEntries)]);return new this(p,c)}}re(o,"classes",["image_processor_class","tokenizer_class","feature_extractor_class"]),re(o,"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"),i=t("./src/utils/hub.js");async function n(p,c){return await(0,i.getModelJSON)(p,"config.json",!0,c)}function o(p){const c={};let h={};switch(p.model_type){case"llava":case"paligemma":case"gemma3":case"florence2":case"llava_onevision":case"idefics3":case"ultravox":case"smolvlm":h=o(p.text_config);break;case"moondream1":h=o(p.phi_config);break;case"musicgen":h=o(p.decoder);break;case"multi_modality":h=o(p.language_config);break;case"gpt2":case"gptj":case"jais":case"codegen":case"gpt_bigcode":c.num_heads="n_head",c.num_layers="n_layer",c.hidden_size="n_embd";break;case"gpt_neox":case"stablelm":case"opt":case"falcon":c.num_heads="num_attention_heads",c.num_layers="num_hidden_layers",c.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":c.num_heads="num_key_value_heads",c.num_layers="num_hidden_layers",c.hidden_size="hidden_size",c.num_attention_heads="num_attention_heads";break;case"gemma":case"gemma2":case"gemma3_text":case"glm":case"helium":c.num_heads="num_key_value_heads",c.num_layers="num_hidden_layers",c.dim_kv="head_dim";break;case"openelm":c.num_heads="num_kv_heads",c.num_layers="num_transformer_layers",c.dim_kv="head_dim";break;case"gpt_neo":case"donut-swin":c.num_heads="num_heads",c.num_layers="num_layers",c.hidden_size="hidden_size";break;case"bloom":c.num_heads="n_head",c.num_layers="n_layer",c.hidden_size="hidden_size";break;case"mpt":c.num_heads="n_heads",c.num_layers="n_layers",c.hidden_size="d_model";break;case"exaone":c.num_heads="num_key_value_heads",c.num_layers="num_layers",c.dim_kv="head_dim",c.num_attention_heads="num_attention_heads";break;case"t5":case"mt5":case"longt5":c.num_decoder_layers="num_decoder_layers",c.num_decoder_heads="num_heads",c.decoder_dim_kv="d_kv",c.num_encoder_layers="num_layers",c.num_encoder_heads="num_heads",c.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":c.num_decoder_layers="decoder_layers",c.num_decoder_heads="decoder_attention_heads",c.decoder_hidden_size="d_model",c.num_encoder_layers="encoder_layers",c.num_encoder_heads="encoder_attention_heads",c.encoder_hidden_size="d_model";break;case"speecht5":c.num_decoder_layers="decoder_layers",c.num_decoder_heads="decoder_attention_heads",c.decoder_hidden_size="hidden_size",c.num_encoder_layers="encoder_layers",c.num_encoder_heads="encoder_attention_heads",c.encoder_hidden_size="hidden_size";break;case"trocr":c.num_encoder_layers=c.num_decoder_layers="decoder_layers",c.num_encoder_heads=c.num_decoder_heads="decoder_attention_heads",c.encoder_hidden_size=c.decoder_hidden_size="d_model";break;case"musicgen_decoder":c.num_encoder_layers=c.num_decoder_layers="num_hidden_layers",c.num_encoder_heads=c.num_decoder_heads="num_attention_heads",c.encoder_hidden_size=c.decoder_hidden_size="hidden_size";break;case"moonshine":c.num_decoder_layers="decoder_num_hidden_layers",c.num_decoder_heads="decoder_num_key_value_heads",c.num_encoder_layers="encoder_num_hidden_layers",c.num_encoder_heads="encoder_num_key_value_heads",c.encoder_hidden_size=c.decoder_hidden_size="hidden_size";break;case"vision-encoder-decoder":const _=o(p.decoder),E="num_decoder_layers"in _,A=(0,s.pick)(p,["model_type","is_encoder_decoder"]);return E?(A.num_decoder_layers=_.num_decoder_layers,A.num_decoder_heads=_.num_decoder_heads,A.decoder_hidden_size=_.decoder_hidden_size,A.num_encoder_layers=_.num_encoder_layers,A.num_encoder_heads=_.num_encoder_heads,A.encoder_hidden_size=_.encoder_hidden_size):(A.num_layers=_.num_layers,A.num_heads=_.num_heads,A.hidden_size=_.hidden_size),A}const g={...h,...(0,s.pick)(p,["model_type","multi_query","is_encoder_decoder"])};for(const _ in c)g[_]=p[c[_]];return g}function a(p,{prefix:c="past_key_values",batch_size:h=1}={}){const g={},_=p.normalized_config;if(_.is_encoder_decoder&&"num_encoder_heads"in _&&"num_decoder_heads"in _){const E=_.encoder_dim_kv??_.encoder_hidden_size/_.num_encoder_heads,A=_.decoder_dim_kv??_.decoder_hidden_size/_.num_decoder_heads,v=[h,_.num_encoder_heads,0,E],y=[h,_.num_decoder_heads,0,A];for(let k=0;k<_.num_decoder_layers;++k)g[`${c}.${k}.encoder.key`]=v,g[`${c}.${k}.encoder.value`]=v,g[`${c}.${k}.decoder.key`]=y,g[`${c}.${k}.decoder.value`]=y}else{const E=_.num_heads,A=_.num_layers,v=_.dim_kv??_.hidden_size/(_.num_attention_heads??E);if(_.model_type==="falcon"){const y=[h*E,0,v];for(let k=0;k{var $,z;t.r(r),t.d(r,{apis:()=>A,env:()=>w});var s=t("?569f"),i=t("?3f59"),n=t("?154a");const o="3.4.2",a=typeof window<"u"&&typeof window.document<"u",l=typeof self<"u"&&(($=self.constructor)==null?void 0:$.name)==="DedicatedWorkerGlobalScope",u=typeof self<"u"&&"caches"in self,p=typeof navigator<"u"&&"gpu"in navigator,c=typeof navigator<"u"&&"ml"in navigator,h=typeof process<"u",g=h&&((z=process==null?void 0:process.release)==null?void 0:z.name)==="node",_=!x(s),E=!x(i),A=Object.freeze({IS_BROWSER_ENV:a,IS_WEBWORKER_ENV:l,IS_WEB_CACHE_AVAILABLE:u,IS_WEBGPU_AVAILABLE:p,IS_WEBNN_AVAILABLE:c,IS_PROCESS_AVAILABLE:h,IS_NODE_ENV:g,IS_FS_AVAILABLE:_,IS_PATH_AVAILABLE:E}),v=_&&E;let y="./";if(v){const R=Object({url:self.location.href}).url;R?y=i.dirname(i.dirname(n.fileURLToPath(R))):typeof __dirname<"u"&&(y=i.dirname(__dirname))}const k=v?i.join(y,"/.cache/"):null,P="/models/",M=v?i.join(y,P):P,w={version:o,backends:{onnx:{}},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!(a||l),localModelPath:M,useFS:_,useBrowserCache:u,useFSCache:_,cacheDir:k,useCustomCache:!1,customCache:null};function x(R){return Object.keys(R).length===0}},"./src/generation/configuration_utils.js":(e,r,t)=>{t.r(r),t.d(r,{GenerationConfig:()=>i});var s=t("./src/utils/core.js");class i{constructor(o){re(this,"max_length",20);re(this,"max_new_tokens",null);re(this,"min_length",0);re(this,"min_new_tokens",null);re(this,"early_stopping",!1);re(this,"max_time",null);re(this,"do_sample",!1);re(this,"num_beams",1);re(this,"num_beam_groups",1);re(this,"penalty_alpha",null);re(this,"use_cache",!0);re(this,"temperature",1);re(this,"top_k",50);re(this,"top_p",1);re(this,"typical_p",1);re(this,"epsilon_cutoff",0);re(this,"eta_cutoff",0);re(this,"diversity_penalty",0);re(this,"repetition_penalty",1);re(this,"encoder_repetition_penalty",1);re(this,"length_penalty",1);re(this,"no_repeat_ngram_size",0);re(this,"bad_words_ids",null);re(this,"force_words_ids",null);re(this,"renormalize_logits",!1);re(this,"constraints",null);re(this,"forced_bos_token_id",null);re(this,"forced_eos_token_id",null);re(this,"remove_invalid_values",!1);re(this,"exponential_decay_length_penalty",null);re(this,"suppress_tokens",null);re(this,"streamer",null);re(this,"begin_suppress_tokens",null);re(this,"forced_decoder_ids",null);re(this,"guidance_scale",null);re(this,"num_return_sequences",1);re(this,"output_attentions",!1);re(this,"output_hidden_states",!1);re(this,"output_scores",!1);re(this,"return_dict_in_generate",!1);re(this,"pad_token_id",null);re(this,"bos_token_id",null);re(this,"eos_token_id",null);re(this,"encoder_no_repeat_ngram_size",0);re(this,"decoder_start_token_id",null);re(this,"generation_kwargs",{});Object.assign(this,(0,s.pick)(o,Object.getOwnPropertyNames(this)))}}},"./src/generation/logits_process.js":(e,r,t)=>{t.r(r),t.d(r,{ClassifierFreeGuidanceLogitsProcessor:()=>v,ForcedBOSTokenLogitsProcessor:()=>l,ForcedEOSTokenLogitsProcessor:()=>u,LogitsProcessor:()=>n,LogitsProcessorList:()=>a,LogitsWarper:()=>o,MinLengthLogitsProcessor:()=>_,MinNewTokensLengthLogitsProcessor:()=>E,NoBadWordsLogitsProcessor:()=>A,NoRepeatNGramLogitsProcessor:()=>h,RepetitionPenaltyLogitsProcessor:()=>g,SuppressTokensAtBeginLogitsProcessor:()=>p,TemperatureLogitsWarper:()=>y,TopKLogitsWarper:()=>P,TopPLogitsWarper:()=>k,WhisperTimeStampLogitsProcessor:()=>c});var s=t("./src/utils/generic.js");t("./src/utils/tensor.js");var i=t("./src/utils/maths.js");class n extends s.Callable{_call(w,x){throw Error("`_call` should be implemented in a subclass")}}class o extends s.Callable{_call(w,x){throw Error("`_call` should be implemented in a subclass")}}class a extends s.Callable{constructor(){super(),this.processors=[]}push(w){this.processors.push(w)}extend(w){this.processors.push(...w)}_call(w,x){let $=x;for(const z of this.processors)$=z(w,$);return $}[Symbol.iterator](){return this.processors.values()}}class l extends n{constructor(w){super(),this.bos_token_id=w}_call(w,x){for(let $=0;$=1&&R[R.length-1]>=this.timestamp_begin,q=R.length<2||R[R.length-2]>=this.timestamp_begin;if(Q&&(q?z.subarray(this.timestamp_begin).fill(-1/0):z.subarray(0,this.eos_token_id).fill(-1/0)),w[$].length===this.begin_index&&this.max_initial_timestamp_index!==null){const J=this.timestamp_begin+this.max_initial_timestamp_index;z.subarray(J+1).fill(-1/0)}const U=(0,i.log_softmax)(z),Z=Math.log(U.subarray(this.timestamp_begin).map(Math.exp).reduce((J,ie)=>J+ie)),H=(0,i.max)(U.subarray(0,this.timestamp_begin))[0];Z>H&&z.subarray(0,this.timestamp_begin).fill(-1/0)}return x}}class h extends n{constructor(w){super(),this.no_repeat_ngram_size=w}getNgrams(w){const x=w.length,$=[];for(let R=0;R1 to use the classifier free guidance processor, got guidance scale ${w}.`);this.guidance_scale=w}_call(w,x){if(x.dims[0]!==2*w.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 ${x.dims[0]} for the logits and ${w.length} for the input ids.`);const $=w.length,z=x.slice([0,$],null),R=x.slice([$,x.dims[0]],null);for(let Q=0;Q1)throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${w}`);if(!Number.isInteger($)||$<1)throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${$}`);this.top_p=w,this.filter_value=x,this.min_tokens_to_keep=$}}class P extends o{constructor(w,{filter_value:x=-1/0,min_tokens_to_keep:$=1}={}){if(super(),!Number.isInteger(w)||w<0)throw new Error(`\`top_k\` must be a positive integer, but is ${w}`);this.top_k=Math.max(w,$),this.filter_value=x}}},"./src/generation/logits_sampler.js":(e,r,t)=>{t.r(r),t.d(r,{LogitsSampler:()=>o});var s=t("./src/utils/generic.js"),i=t("./src/utils/tensor.js"),n=t("./src/utils/maths.js");t("./src/generation/configuration_utils.js");class o extends s.Callable{constructor(c){super(),this.generation_config=c}async _call(c){return this.sample(c)}async sample(c){throw Error("sample should be implemented in subclasses.")}getLogits(c,h){let g=c.dims.at(-1),_=c.data;if(h===-1)_=_.slice(-g);else{let E=h*g;_=_.slice(E,E+g)}return _}randomSelect(c){let h=0;for(let _=0;_1)return new u(c);if(c.num_return_sequences>1)throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${c.num_return_sequences}.`);return new a(c)}}class a extends o{async sample(c){const h=(0,n.max)(c.data)[1];return[[BigInt(h),0]]}}class l extends o{async sample(c){let h=c.dims.at(-1);this.generation_config.top_k>0&&(h=Math.min(this.generation_config.top_k,h));const[g,_]=await(0,i.topk)(c,h),E=(0,n.softmax)(g.data);return Array.from({length:this.generation_config.num_beams},()=>{const A=this.randomSelect(E);return[_.data[A],Math.log(E[A])]})}}class u extends o{async sample(c){let h=c.dims.at(-1);this.generation_config.top_k>0&&(h=Math.min(this.generation_config.top_k,h));const[g,_]=await(0,i.topk)(c,h),E=(0,n.softmax)(g.data);return Array.from({length:this.generation_config.num_beams},(A,v)=>[_.data[v],Math.log(E[v])])}}},"./src/generation/stopping_criteria.js":(e,r,t)=>{t.r(r),t.d(r,{EosTokenCriteria:()=>a,InterruptableStoppingCriteria:()=>l,MaxLengthCriteria:()=>o,StoppingCriteria:()=>i,StoppingCriteriaList:()=>n});var s=t("./src/utils/generic.js");class i extends s.Callable{_call(p,c){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 i&&(p=[p]),this.criteria.push(...p)}_call(p,c){const h=new Array(p.length).fill(!1);for(const g of this.criteria){const _=g(p,c);for(let E=0;Ec.length>=this.max_length)}}class a extends i{constructor(p){super(),Array.isArray(p)||(p=[p]),this.eos_token_id=p}_call(p,c){return p.map(h=>{const g=h.at(-1);return this.eos_token_id.some(_=>g==_)})}}class l extends i{constructor(){super(),this.interrupted=!1}interrupt(){this.interrupted=!0}reset(){this.interrupted=!1}_call(p,c){return new Array(p.length).fill(this.interrupted)}}},"./src/generation/streamers.js":(e,r,t)=>{t.r(r),t.d(r,{BaseStreamer:()=>o,TextStreamer:()=>l,WhisperTextStreamer:()=>u});var s=t("./src/utils/core.js"),i=t("./src/tokenizers.js"),n=t("./src/env.js");class o{put(c){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 o{constructor(c,{skip_prompt:h=!1,callback_function:g=null,token_callback_function:_=null,skip_special_tokens:E=!0,decode_kwargs:A={},...v}={}){super(),this.tokenizer=c,this.skip_prompt=h,this.callback_function=g??a,this.token_callback_function=_,this.decode_kwargs={skip_special_tokens:E,...A,...v},this.token_cache=[],this.print_len=0,this.next_tokens_are_prompt=!0}put(c){var A;if(c.length>1)throw Error("TextStreamer only supports batch size of 1");const h=this.next_tokens_are_prompt;if(h&&(this.next_tokens_are_prompt=!1,this.skip_prompt))return;const g=c[0];(A=this.token_callback_function)==null||A.call(this,g),this.token_cache=(0,s.mergeArrays)(this.token_cache,g);const _=this.tokenizer.decode(this.token_cache,this.decode_kwargs);let E;h||_.endsWith(` +`)?(E=_.slice(this.print_len),this.token_cache=[],this.print_len=0):_.length>0&&(0,i.is_chinese_char)(_.charCodeAt(_.length-1))?(E=_.slice(this.print_len),this.print_len+=E.length):(E=_.slice(this.print_len,_.lastIndexOf(" ")+1),this.print_len+=E.length),this.on_finalized_text(E,!1)}end(){let c;this.token_cache.length>0?(c=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len),this.token_cache=[],this.print_len=0):c="",this.next_tokens_are_prompt=!0,this.on_finalized_text(c,!0)}on_finalized_text(c,h){var g,_;c.length>0&&((g=this.callback_function)==null||g.call(this,c)),h&&this.callback_function===a&&n.apis.IS_PROCESS_AVAILABLE&&((_=this.callback_function)==null||_.call(this,` +`))}}class u extends l{constructor(c,{skip_prompt:h=!1,callback_function:g=null,token_callback_function:_=null,on_chunk_start:E=null,on_chunk_end:A=null,on_finalize:v=null,time_precision:y=.02,skip_special_tokens:k=!0,decode_kwargs:P={}}={}){super(c,{skip_prompt:h,skip_special_tokens:k,callback_function:g,token_callback_function:_,decode_kwargs:P}),this.timestamp_begin=c.timestamp_begin,this.on_chunk_start=E,this.on_chunk_end=A,this.on_finalize=v,this.time_precision=y,this.waiting_for_timestamp=!1}put(c){var g,_;if(c.length>1)throw Error("WhisperTextStreamer only supports batch size of 1");const h=c[0];if(h.length===1){const E=Number(h[0])-this.timestamp_begin;if(E>=0){const A=E*this.time_precision;this.waiting_for_timestamp?(g=this.on_chunk_end)==null||g.call(this,A):(_=this.on_chunk_start)==null||_.call(this,A),this.waiting_for_timestamp=!this.waiting_for_timestamp,c=[[]]}}return super.put(c)}end(){var c;super.end(),(c=this.on_finalize)==null||c.call(this)}}},"./src/models.js":(e,r,t)=>{t.r(r),t.d(r,{ASTForAudioClassification:()=>Ua,ASTModel:()=>Va,ASTPreTrainedModel:()=>Gi,AlbertForMaskedLM:()=>V,AlbertForQuestionAnswering:()=>F,AlbertForSequenceClassification:()=>pe,AlbertModel:()=>Sn,AlbertPreTrainedModel:()=>$s,AutoModel:()=>Pc,AutoModelForAudioClassification:()=>u0,AutoModelForAudioFrameClassification:()=>p0,AutoModelForAudioTextToText:()=>b0,AutoModelForCTC:()=>d0,AutoModelForCausalLM:()=>Yb,AutoModelForDepthEstimation:()=>_0,AutoModelForDocumentQuestionAnswering:()=>h0,AutoModelForImageClassification:()=>r0,AutoModelForImageFeatureExtraction:()=>y0,AutoModelForImageMatting:()=>f0,AutoModelForImageSegmentation:()=>s0,AutoModelForImageTextToText:()=>M0,AutoModelForImageToImage:()=>m0,AutoModelForMaskGeneration:()=>l0,AutoModelForMaskedLM:()=>Zb,AutoModelForNormalEstimation:()=>g0,AutoModelForObjectDetection:()=>o0,AutoModelForPoseEstimation:()=>w0,AutoModelForQuestionAnswering:()=>e0,AutoModelForSemanticSegmentation:()=>n0,AutoModelForSeq2SeqLM:()=>qb,AutoModelForSequenceClassification:()=>Kb,AutoModelForSpeechSeq2Seq:()=>Qb,AutoModelForTextToSpectrogram:()=>Xb,AutoModelForTextToWaveform:()=>Jb,AutoModelForTokenClassification:()=>Hb,AutoModelForUniversalSegmentation:()=>i0,AutoModelForVision2Seq:()=>t0,AutoModelForXVector:()=>c0,AutoModelForZeroShotObjectDetection:()=>a0,BartForConditionalGeneration:()=>Wt,BartForSequenceClassification:()=>Ot,BartModel:()=>kt,BartPretrainedModel:()=>Ct,BaseModelOutput:()=>Pe,BeitForImageClassification:()=>Il,BeitModel:()=>kl,BeitPreTrainedModel:()=>na,BertForMaskedLM:()=>Ie,BertForQuestionAnswering:()=>We,BertForSequenceClassification:()=>Le,BertForTokenClassification:()=>Ne,BertModel:()=>Ae,BertPreTrainedModel:()=>xe,BlenderbotForConditionalGeneration:()=>Zt,BlenderbotModel:()=>Gt,BlenderbotPreTrainedModel:()=>ws,BlenderbotSmallForConditionalGeneration:()=>ys,BlenderbotSmallModel:()=>Zr,BlenderbotSmallPreTrainedModel:()=>gr,BloomForCausalLM:()=>No,BloomModel:()=>Ro,BloomPreTrainedModel:()=>gi,CLIPModel:()=>Zi,CLIPPreTrainedModel:()=>Us,CLIPSegForImageSegmentation:()=>eo,CLIPSegModel:()=>an,CLIPSegPreTrainedModel:()=>on,CLIPTextModel:()=>Yu,CLIPTextModelWithProjection:()=>Ya,CLIPVisionModel:()=>Zu,CLIPVisionModelWithProjection:()=>qn,CamembertForMaskedLM:()=>xs,CamembertForQuestionAnswering:()=>zs,CamembertForSequenceClassification:()=>Es,CamembertForTokenClassification:()=>Ps,CamembertModel:()=>ps,CamembertPreTrainedModel:()=>Vr,CausalLMOutput:()=>On,CausalLMOutputWithPast:()=>RT,ChineseCLIPModel:()=>sl,ChineseCLIPPreTrainedModel:()=>rl,ClapAudioModelWithProjection:()=>SM,ClapModel:()=>PM,ClapPreTrainedModel:()=>Wl,ClapTextModelWithProjection:()=>CM,CodeGenForCausalLM:()=>Ur,CodeGenModel:()=>An,CodeGenPreTrainedModel:()=>ei,CohereForCausalLM:()=>vo,CohereModel:()=>bo,CoherePreTrainedModel:()=>di,ConvBertForMaskedLM:()=>jt,ConvBertForQuestionAnswering:()=>Ds,ConvBertForSequenceClassification:()=>dr,ConvBertForTokenClassification:()=>us,ConvBertModel:()=>nr,ConvBertPreTrainedModel:()=>wt,ConvNextForImageClassification:()=>vy,ConvNextModel:()=>by,ConvNextPreTrainedModel:()=>nc,ConvNextV2ForImageClassification:()=>xy,ConvNextV2Model:()=>Ty,ConvNextV2PreTrainedModel:()=>ic,DPTForDepthEstimation:()=>sy,DPTModel:()=>ry,DPTPreTrainedModel:()=>tc,DacDecoderModel:()=>_b,DacDecoderOutput:()=>hb,DacEncoderModel:()=>mb,DacEncoderOutput:()=>pb,DacModel:()=>fb,DacPreTrainedModel:()=>Jl,DebertaForMaskedLM:()=>et,DebertaForQuestionAnswering:()=>zt,DebertaForSequenceClassification:()=>it,DebertaForTokenClassification:()=>rr,DebertaModel:()=>Be,DebertaPreTrainedModel:()=>fr,DebertaV2ForMaskedLM:()=>fs,DebertaV2ForQuestionAnswering:()=>_s,DebertaV2ForSequenceClassification:()=>Er,DebertaV2ForTokenClassification:()=>ms,DebertaV2Model:()=>hs,DebertaV2PreTrainedModel:()=>kr,DecisionTransformerModel:()=>QM,DecisionTransformerPreTrainedModel:()=>qM,DeiTForImageClassification:()=>Ee,DeiTModel:()=>ye,DeiTPreTrainedModel:()=>ne,DepthAnythingForDepthEstimation:()=>iy,DepthAnythingPreTrainedModel:()=>ny,DepthProForDepthEstimation:()=>uy,DepthProPreTrainedModel:()=>dy,DetrForObjectDetection:()=>Fl,DetrForSegmentation:()=>ia,DetrModel:()=>Al,DetrObjectDetectionOutput:()=>oa,DetrPreTrainedModel:()=>vi,DetrSegmentationOutput:()=>Ol,Dinov2ForImageClassification:()=>Py,Dinov2Model:()=>Ey,Dinov2PreTrainedModel:()=>oc,Dinov2WithRegistersForImageClassification:()=>Sy,Dinov2WithRegistersModel:()=>Cy,Dinov2WithRegistersPreTrainedModel:()=>ac,DistilBertForMaskedLM:()=>Zs,DistilBertForQuestionAnswering:()=>Ys,DistilBertForSequenceClassification:()=>Xs,DistilBertForTokenClassification:()=>Js,DistilBertModel:()=>Cs,DistilBertPreTrainedModel:()=>Qr,DonutSwinModel:()=>My,DonutSwinPreTrainedModel:()=>yy,EfficientNetForImageClassification:()=>DM,EfficientNetModel:()=>OM,EfficientNetPreTrainedModel:()=>gc,ElectraForMaskedLM:()=>Ls,ElectraForQuestionAnswering:()=>qr,ElectraForSequenceClassification:()=>jr,ElectraForTokenClassification:()=>dt,ElectraModel:()=>cs,ElectraPreTrainedModel:()=>Dr,EsmForMaskedLM:()=>tn,EsmForSequenceClassification:()=>rn,EsmForTokenClassification:()=>Lr,EsmModel:()=>en,EsmPreTrainedModel:()=>gs,ExaoneForCausalLM:()=>ft,ExaoneModel:()=>fo,ExaonePreTrainedModel:()=>Ws,FalconForCausalLM:()=>EM,FalconModel:()=>xM,FalconPreTrainedModel:()=>fc,FastViTForImageClassification:()=>yl,FastViTModel:()=>wl,FastViTPreTrainedModel:()=>Zo,Florence2ForConditionalGeneration:()=>Qi,Florence2PreTrainedModel:()=>Xa,GLPNForDepthEstimation:()=>wy,GLPNModel:()=>gy,GLPNPreTrainedModel:()=>sc,GPT2LMHeadModel:()=>Jn,GPT2Model:()=>al,GPT2PreTrainedModel:()=>to,GPTBigCodeForCausalLM:()=>uo,GPTBigCodeModel:()=>dl,GPTBigCodePreTrainedModel:()=>Oe,GPTJForCausalLM:()=>In,GPTJModel:()=>lo,GPTJPreTrainedModel:()=>ao,GPTNeoForCausalLM:()=>io,GPTNeoModel:()=>no,GPTNeoPreTrainedModel:()=>Yn,GPTNeoXForCausalLM:()=>oo,GPTNeoXModel:()=>ll,GPTNeoXPreTrainedModel:()=>Zn,Gemma2ForCausalLM:()=>Po,Gemma2Model:()=>Eo,Gemma2PreTrainedModel:()=>ci,Gemma3ForCausalLM:()=>So,Gemma3Model:()=>Co,Gemma3PreTrainedModel:()=>pi,GemmaForCausalLM:()=>xo,GemmaModel:()=>To,GemmaPreTrainedModel:()=>ui,GlmForCausalLM:()=>gt,GlmModel:()=>ho,GlmPreTrainedModel:()=>ni,GraniteForCausalLM:()=>Mo,GraniteModel:()=>yo,GranitePreTrainedModel:()=>li,GroundingDinoForObjectDetection:()=>ky,GroundingDinoPreTrainedModel:()=>$y,GroupViTModel:()=>gl,GroupViTPreTrainedModel:()=>_l,HeliumForCausalLM:()=>si,HeliumModel:()=>po,HeliumPreTrainedModel:()=>ri,HieraForImageClassification:()=>ot,HieraModel:()=>Ye,HieraPreTrainedModel:()=>ze,HubertForCTC:()=>oM,HubertForSequenceClassification:()=>aM,HubertModel:()=>iM,HubertPreTrainedModel:()=>ET,IJepaForImageClassification:()=>qo,IJepaModel:()=>Ho,IJepaPreTrainedModel:()=>bi,Idefics3ForConditionalGeneration:()=>Kn,Idefics3PreTrainedModel:()=>Ja,ImageMattingOutput:()=>T0,JAISLMHeadModel:()=>so,JAISModel:()=>ro,JAISPreTrainedModel:()=>kn,JinaCLIPModel:()=>nl,JinaCLIPPreTrainedModel:()=>Xn,JinaCLIPTextModel:()=>il,JinaCLIPVisionModel:()=>ol,LiteWhisperForConditionalGeneration:()=>Ga,LlamaForCausalLM:()=>co,LlamaModel:()=>ti,LlamaPreTrainedModel:()=>ln,LlavaForConditionalGeneration:()=>Gn,LlavaOnevisionForConditionalGeneration:()=>qa,LlavaPreTrainedModel:()=>Ha,LongT5ForConditionalGeneration:()=>Qe,LongT5Model:()=>Ue,LongT5PreTrainedModel:()=>Ce,M2M100ForConditionalGeneration:()=>Ny,M2M100Model:()=>Ry,M2M100PreTrainedModel:()=>uc,MBartForCausalLM:()=>Tr,MBartForConditionalGeneration:()=>_r,MBartForSequenceClassification:()=>Yr,MBartModel:()=>vr,MBartPreTrainedModel:()=>Vt,MPNetForMaskedLM:()=>zr,MPNetForQuestionAnswering:()=>Ar,MPNetForSequenceClassification:()=>Pn,MPNetForTokenClassification:()=>Ns,MPNetModel:()=>En,MPNetPreTrainedModel:()=>Xr,MT5ForConditionalGeneration:()=>ht,MT5Model:()=>Ze,MT5PreTrainedModel:()=>Ke,MarianMTModel:()=>By,MarianModel:()=>zy,MarianPreTrainedModel:()=>dc,MaskFormerForInstanceSegmentation:()=>_y,MaskFormerModel:()=>my,MaskFormerPreTrainedModel:()=>rc,MaskedLMOutput:()=>wr,Metric3DForDepthEstimation:()=>py,Metric3DPreTrainedModel:()=>cy,Metric3Dv2ForDepthEstimation:()=>fy,Metric3Dv2PreTrainedModel:()=>hy,MgpstrForSceneTextRecognition:()=>eb,MgpstrModelOutput:()=>YM,MgpstrPreTrainedModel:()=>ZM,MimiDecoderModel:()=>cb,MimiDecoderOutput:()=>lb,MimiEncoderModel:()=>ub,MimiEncoderOutput:()=>ab,MimiModel:()=>db,MimiPreTrainedModel:()=>Xl,MistralForCausalLM:()=>bM,MistralModel:()=>MM,MistralPreTrainedModel:()=>pc,MobileBertForMaskedLM:()=>Bs,MobileBertForQuestionAnswering:()=>Ir,MobileBertForSequenceClassification:()=>Rs,MobileBertModel:()=>br,MobileBertPreTrainedModel:()=>Ss,MobileLLMForCausalLM:()=>mo,MobileLLMModel:()=>mt,MobileLLMPreTrainedModel:()=>Fn,MobileNetV1ForImageClassification:()=>zM,MobileNetV1ForSemanticSegmentation:()=>BM,MobileNetV1Model:()=>LM,MobileNetV1PreTrainedModel:()=>Kl,MobileNetV2ForImageClassification:()=>NM,MobileNetV2ForSemanticSegmentation:()=>jM,MobileNetV2Model:()=>RM,MobileNetV2PreTrainedModel:()=>Hl,MobileNetV3ForImageClassification:()=>UM,MobileNetV3ForSemanticSegmentation:()=>WM,MobileNetV3Model:()=>VM,MobileNetV3PreTrainedModel:()=>ql,MobileNetV4ForImageClassification:()=>KM,MobileNetV4ForSemanticSegmentation:()=>HM,MobileNetV4Model:()=>GM,MobileNetV4PreTrainedModel:()=>Ql,MobileViTForImageClassification:()=>Tl,MobileViTModel:()=>vl,MobileViTPreTrainedModel:()=>ea,MobileViTV2ForImageClassification:()=>El,MobileViTV2Model:()=>xl,MobileViTV2PreTrainedModel:()=>ta,ModelOutput:()=>fe,ModernBertForMaskedLM:()=>B,ModernBertForSequenceClassification:()=>te,ModernBertForTokenClassification:()=>de,ModernBertModel:()=>ee,ModernBertPreTrainedModel:()=>D,Moondream1ForConditionalGeneration:()=>Qa,MoonshineForConditionalGeneration:()=>Ka,MoonshineModel:()=>Ju,MoonshinePreTrainedModel:()=>Hi,MptForCausalLM:()=>Vo,MptModel:()=>jo,MptPreTrainedModel:()=>wi,MultiModalityCausalLM:()=>JM,MultiModalityPreTrainedModel:()=>XM,MusicgenForCausalLM:()=>$T,MusicgenForConditionalGeneration:()=>yc,MusicgenModel:()=>ST,MusicgenPreTrainedModel:()=>wc,NomicBertModel:()=>ve,NomicBertPreTrainedModel:()=>be,OPTForCausalLM:()=>Wo,OPTModel:()=>Uo,OPTPreTrainedModel:()=>yi,Olmo2ForCausalLM:()=>ai,Olmo2Model:()=>wo,Olmo2PreTrainedModel:()=>oi,OlmoForCausalLM:()=>go,OlmoModel:()=>_o,OlmoPreTrainedModel:()=>ii,OpenELMForCausalLM:()=>ko,OpenELMModel:()=>$o,OpenELMPreTrainedModel:()=>hi,OwlViTForObjectDetection:()=>Cl,OwlViTModel:()=>Pl,OwlViTPreTrainedModel:()=>ra,Owlv2ForObjectDetection:()=>$l,Owlv2Model:()=>Sl,Owlv2PreTrainedModel:()=>sa,PaliGemmaForConditionalGeneration:()=>Ji,PaliGemmaPreTrainedModel:()=>Xi,PatchTSMixerForPrediction:()=>nb,PatchTSMixerModel:()=>sb,PatchTSMixerPreTrainedModel:()=>bc,PatchTSTForPrediction:()=>rb,PatchTSTModel:()=>tb,PatchTSTPreTrainedModel:()=>Mc,Phi3ForCausalLM:()=>Bo,Phi3Model:()=>zo,Phi3PreTrainedModel:()=>_i,Phi3VForCausalLM:()=>Vs,Phi3VPreTrainedModel:()=>Yi,PhiForCausalLM:()=>Lo,PhiModel:()=>Do,PhiPreTrainedModel:()=>mi,PreTrainedModel:()=>j,PretrainedMixin:()=>It,PvtForImageClassification:()=>cl,PvtModel:()=>ul,PvtPreTrainedModel:()=>Jo,PyAnnoteForAudioFrameClassification:()=>Ky,PyAnnoteModel:()=>Gy,PyAnnotePreTrainedModel:()=>cc,QuestionAnsweringModelOutput:()=>Pr,Qwen2ForCausalLM:()=>Ao,Qwen2Model:()=>Io,Qwen2PreTrainedModel:()=>fi,Qwen2VLForConditionalGeneration:()=>Oo,Qwen2VLPreTrainedModel:()=>Fo,RFDetrForObjectDetection:()=>d,RFDetrModel:()=>ua,RFDetrObjectDetectionOutput:()=>f,RFDetrPreTrainedModel:()=>da,RTDetrForObjectDetection:()=>Ll,RTDetrModel:()=>Dl,RTDetrObjectDetectionOutput:()=>Ti,RTDetrPreTrainedModel:()=>aa,RTDetrV2ForObjectDetection:()=>Bl,RTDetrV2Model:()=>zl,RTDetrV2ObjectDetectionOutput:()=>Rl,RTDetrV2PreTrainedModel:()=>la,ResNetForImageClassification:()=>Fr,ResNetModel:()=>Bt,ResNetPreTrainedModel:()=>_t,RoFormerForMaskedLM:()=>je,RoFormerForQuestionAnswering:()=>ct,RoFormerForSequenceClassification:()=>qe,RoFormerForTokenClassification:()=>Xe,RoFormerModel:()=>Fe,RoFormerPreTrainedModel:()=>Re,RobertaForMaskedLM:()=>Rt,RobertaForQuestionAnswering:()=>er,RobertaForSequenceClassification:()=>Jt,RobertaForTokenClassification:()=>qt,RobertaModel:()=>cr,RobertaPreTrainedModel:()=>Ht,SamImageSegmentationOutput:()=>Ly,SamModel:()=>Dy,SamPreTrainedModel:()=>Oy,SapiensForDepthEstimation:()=>ay,SapiensForNormalEstimation:()=>ly,SapiensForSemanticSegmentation:()=>oy,SapiensPreTrainedModel:()=>Nl,SegformerForImageClassification:()=>kM,SegformerForSemanticSegmentation:()=>IM,SegformerModel:()=>CT,SegformerPreTrainedModel:()=>Gl,Seq2SeqLMOutput:()=>BT,SequenceClassifierOutput:()=>bt,SiglipModel:()=>Za,SiglipPreTrainedModel:()=>Qn,SiglipTextModel:()=>el,SiglipVisionModel:()=>tl,SmolVLMForConditionalGeneration:()=>Hn,SnacDecoderModel:()=>yb,SnacEncoderModel:()=>wb,SnacModel:()=>gb,SnacPreTrainedModel:()=>Yl,SpeechT5ForSpeechToText:()=>mM,SpeechT5ForTextToSpeech:()=>_M,SpeechT5HifiGan:()=>gM,SpeechT5Model:()=>PT,SpeechT5PreTrainedModel:()=>Ul,SqueezeBertForMaskedLM:()=>mr,SqueezeBertForQuestionAnswering:()=>Cn,SqueezeBertForSequenceClassification:()=>js,SqueezeBertModel:()=>ur,SqueezeBertPreTrainedModel:()=>Jr,StableLmForCausalLM:()=>FM,StableLmModel:()=>AM,StableLmPreTrainedModel:()=>_c,Starcoder2ForCausalLM:()=>TM,Starcoder2Model:()=>vM,Starcoder2PreTrainedModel:()=>hc,StyleTextToSpeech2Model:()=>fM,StyleTextToSpeech2PreTrainedModel:()=>hM,Swin2SRForImageSuperResolution:()=>ty,Swin2SRModel:()=>ey,Swin2SRPreTrainedModel:()=>ec,SwinForImageClassification:()=>Yw,SwinForSemanticSegmentation:()=>Zw,SwinModel:()=>Jw,SwinPreTrainedModel:()=>ks,T5ForConditionalGeneration:()=>ce,T5Model:()=>le,T5PreTrainedModel:()=>Y,TableTransformerForObjectDetection:()=>I,TableTransformerModel:()=>C,TableTransformerObjectDetectionOutput:()=>W,TableTransformerPreTrainedModel:()=>T,TokenClassifierOutput:()=>pr,TrOCRForCausalLM:()=>yM,TrOCRPreTrainedModel:()=>wM,UltravoxModel:()=>ob,UltravoxPreTrainedModel:()=>ib,UniSpeechForCTC:()=>Xy,UniSpeechForSequenceClassification:()=>Jy,UniSpeechModel:()=>Qy,UniSpeechPreTrainedModel:()=>jl,UniSpeechSatForAudioFrameClassification:()=>tM,UniSpeechSatForCTC:()=>Zy,UniSpeechSatForSequenceClassification:()=>eM,UniSpeechSatModel:()=>Yy,UniSpeechSatPreTrainedModel:()=>ca,ViTForImageClassification:()=>Ko,ViTMAEModel:()=>hl,ViTMAEPreTrainedModel:()=>pl,ViTMSNForImageClassification:()=>ml,ViTMSNModel:()=>fl,ViTMSNPreTrainedModel:()=>Yo,ViTModel:()=>Go,ViTPreTrainedModel:()=>Mi,VisionEncoderDecoderModel:()=>qi,VitMatteForImageMatting:()=>bl,VitMattePreTrainedModel:()=>Ml,VitPoseForPoseEstimation:()=>Xo,VitPosePreTrainedModel:()=>Qo,VitsModel:()=>mc,VitsModelOutput:()=>x0,VitsPreTrainedModel:()=>$M,Wav2Vec2BertForCTC:()=>sM,Wav2Vec2BertForSequenceClassification:()=>nM,Wav2Vec2BertModel:()=>rM,Wav2Vec2BertPreTrainedModel:()=>Vl,Wav2Vec2ForAudioFrameClassification:()=>Wy,Wav2Vec2ForCTC:()=>Vy,Wav2Vec2ForSequenceClassification:()=>Uy,Wav2Vec2Model:()=>jy,Wav2Vec2PreTrainedModel:()=>dn,WavLMForAudioFrameClassification:()=>pM,WavLMForCTC:()=>dM,WavLMForSequenceClassification:()=>uM,WavLMForXVector:()=>cM,WavLMModel:()=>lM,WavLMPreTrainedModel:()=>xi,WeSpeakerResNetModel:()=>qy,WeSpeakerResNetPreTrainedModel:()=>Hy,WhisperForConditionalGeneration:()=>Ki,WhisperModel:()=>Wa,WhisperPreTrainedModel:()=>Wn,XLMForQuestionAnswering:()=>Ba,XLMForSequenceClassification:()=>za,XLMForTokenClassification:()=>Ui,XLMModel:()=>sn,XLMPreTrainedModel:()=>ir,XLMRobertaForMaskedLM:()=>Na,XLMRobertaForQuestionAnswering:()=>Wi,XLMRobertaForSequenceClassification:()=>$n,XLMRobertaForTokenClassification:()=>ja,XLMRobertaModel:()=>Ra,XLMRobertaPreTrainedModel:()=>Ms,XLMWithLMHeadModel:()=>nn,XVectorOutput:()=>v0,YolosForObjectDetection:()=>Ay,YolosModel:()=>Iy,YolosObjectDetectionOutput:()=>Fy,YolosPreTrainedModel:()=>lc});var s=t("./src/configs.js"),i=t("./src/backends/onnx.js"),n=t("./src/utils/dtypes.js"),o=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"),c=t("./src/generation/configuration_utils.js"),h=t("./src/utils/tensor.js"),g=t("./src/utils/image.js"),_=t("./src/utils/maths.js"),E=t("./src/generation/stopping_criteria.js"),A=t("./src/generation/logits_sampler.js"),v=t("./src/env.js"),y=t("./src/models/whisper/generation_whisper.js"),k=t("./src/models/whisper/common_whisper.js");const P={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,MaskGeneration:5,ImageTextToText:6,Musicgen:7,MultiModality:8,Phi3V:9,AudioTextToText:10,AutoEncoder:11},M=new Map,w=new Map,x=new Map;async function $(b,S,L){var yr;const oe=((yr=L.config)==null?void 0:yr["transformers.js_config"])??{};let ge=L.device??oe.device;ge&&typeof ge!="string"&&(ge.hasOwnProperty(S)?ge=ge[S]:(console.warn(`device not specified for "${S}". Using the default device.`),ge=null));const me=ge??(v.apis.IS_NODE_ENV?"cpu":"wasm"),Se=(0,i.deviceToExecutionProviders)(me);let De=L.dtype??oe.dtype;if(typeof De!="string"&&(De&&De.hasOwnProperty(S)?De=De[S]:(De=n.DEFAULT_DEVICE_DTYPE_MAPPING[me]??n.DATA_TYPES.fp32,console.warn(`dtype not specified for "${S}". Using the default dtype (${De}) for this device (${me}).`))),De===n.DATA_TYPES.auto){let Pt=oe.dtype;typeof Pt!="string"&&(Pt=Pt[S]),Pt&&Pt!==n.DATA_TYPES.auto&&n.DATA_TYPES.hasOwnProperty(Pt)?De=Pt:De=n.DEFAULT_DEVICE_DTYPE_MAPPING[me]??n.DATA_TYPES.fp32}const Ge=De;if(n.DEFAULT_DTYPE_SUFFIX_MAPPING.hasOwnProperty(Ge)){if(Ge===n.DATA_TYPES.fp16&&me==="webgpu"&&!await(0,n.isWebGpuFp16Supported)())throw new Error(`The device (${me}) does not support fp16.`)}else throw new Error(`Invalid dtype: ${Ge}. Should be one of: ${Object.keys(n.DATA_TYPES).join(", ")}`);const Je=oe.kv_cache_dtype?typeof oe.kv_cache_dtype=="string"?oe.kv_cache_dtype:oe.kv_cache_dtype[Ge]??"float32":void 0;if(Je&&!["float32","float16"].includes(Je))throw new Error(`Invalid kv_cache_dtype: ${Je}. Should be one of: float32, float16`);const lt={dtype:Ge,kv_cache_dtype:Je},yt=n.DEFAULT_DTYPE_SUFFIX_MAPPING[Ge],st=`${S}${yt}.onnx`,Et=`${L.subfolder??""}/${st}`,at={...L.session_options};at.executionProviders??(at.executionProviders=Se);const vt=oe.free_dimension_overrides;vt?at.freeDimensionOverrides??(at.freeDimensionOverrides=vt):me.startsWith("webnn")&&!at.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 ut=(0,l.getModelFile)(b,Et,!0,L,v.apis.IS_NODE_ENV),xt=L.use_external_data_format??oe.use_external_data_format;let Lt=[];if(xt){let Pt;typeof xt=="object"?xt.hasOwnProperty(st)?Pt=xt[st]:xt.hasOwnProperty(S)?Pt=xt[S]:Pt=!1:Pt=xt;const Nt=+Pt;if(Nt>l.MAX_EXTERNAL_DATA_CHUNKS)throw new Error(`The number of external data chunks (${Nt}) exceeds the maximum allowed value (${l.MAX_EXTERNAL_DATA_CHUNKS}).`);for(let tr=0;tr{const Cr=await(0,l.getModelFile)(b,Wr,!0,L,v.apis.IS_NODE_ENV);un(Cr instanceof Uint8Array?{path:sr,data:Cr}:sr)}))}}else at.externalData!==void 0&&(Lt=at.externalData.map(async Pt=>{if(typeof Pt.data=="string"){const Nt=await(0,l.getModelFile)(b,Pt.data,!0,L);return{...Pt,data:Nt}}return Pt}));if(Lt.length>0){const Pt=await Promise.all(Lt);v.apis.IS_NODE_ENV||(at.externalData=Pt)}if(me==="webgpu"){const Pt=(0,s.getKeyValueShapes)(L.config,{prefix:"present"});if(Object.keys(Pt).length>0&&!(0,i.isONNXProxy)()){const Nt={};for(const tr in Pt)Nt[tr]="gpu-buffer";at.preferredOutputLocation=Nt}}return{buffer_or_path:await ut,session_options:at,session_config:lt}}async function z(b,S,L){return Object.fromEntries(await Promise.all(Object.keys(S).map(async oe=>{const{buffer_or_path:ge,session_options:me,session_config:Se}=await $(b,S[oe],L),De=await(0,i.createInferenceSession)(ge,me,Se);return[oe,De]})))}async function R(b,S,L){return Object.fromEntries(await Promise.all(Object.keys(S).map(async oe=>{const ge=await(0,l.getModelJSON)(b,S[oe],!1,L);return[oe,ge]})))}function Q(b,S){const L=Object.create(null),oe=[];for(const Se of b.inputNames){const De=S[Se];if(!(De instanceof h.Tensor)){oe.push(Se);continue}L[Se]=(0,i.isONNXProxy)()?De.clone():De}if(oe.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${oe.join(", ")}.`);const ge=Object.keys(S).length,me=b.inputNames.length;if(ge>me){let Se=Object.keys(S).filter(De=>!b.inputNames.includes(De));console.warn(`WARNING: Too many inputs were provided (${ge} > ${me}). The following inputs will be ignored: "${Se.join(", ")}".`)}return L}async function q(b,S){const L=Q(b,S);try{const oe=Object.fromEntries(Object.entries(L).map(([me,Se])=>[me,Se.ort_tensor]));let ge=await b.run(oe);return ge=U(ge),ge}catch(oe){const ge=Object.fromEntries(Object.entries(L).map(([me,{type:Se,dims:De,data:Ge}])=>[me,{type:Se,dims:De,data:Ge}]));throw console.error(`An error occurred during model execution: "${oe}".`),console.error("Inputs given to model:",ge),oe}}function U(b){for(let S in b)(0,i.isONNXTensor)(b[S])?b[S]=new h.Tensor(b[S]):typeof b[S]=="object"&&U(b[S]);return b}function Z(b){if(b instanceof h.Tensor)return b;if(b.length===0)throw Error("items must be non-empty");if(Array.isArray(b[0])){if(b.some(S=>S.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 h.Tensor("int64",BigInt64Array.from(b.flat().map(S=>BigInt(S))),[b.length,b[0].length])}else return new h.Tensor("int64",BigInt64Array.from(b.map(S=>BigInt(S))),[1,b.length])}function H(b){return new h.Tensor("bool",[b],[1])}async function J(b,S){let{encoder_outputs:L,input_ids:oe,decoder_input_ids:ge,...me}=S;if(!L){const De=(0,a.pick)(S,b.sessions.model.inputNames);L=(await ie(b,De)).last_hidden_state}return me.input_ids=ge,me.encoder_hidden_states=L,b.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(me.encoder_attention_mask=S.attention_mask),await ue(b,me,!0)}async function ie(b,S){const L=b.sessions.model,oe=(0,a.pick)(S,L.inputNames);if(L.inputNames.includes("inputs_embeds")&&!oe.inputs_embeds){if(!S.input_ids)throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");oe.inputs_embeds=await b.encode_text({input_ids:S.input_ids})}if(L.inputNames.includes("token_type_ids")&&!oe.token_type_ids){if(!oe.input_ids)throw new Error("Both `input_ids` and `token_type_ids` are missing in the model inputs.");oe.token_type_ids=(0,h.zeros_like)(oe.input_ids)}if(L.inputNames.includes("pixel_mask")&&!oe.pixel_mask){if(!oe.pixel_values)throw new Error("Both `pixel_values` and `pixel_mask` are missing in the model inputs.");const ge=oe.pixel_values.dims;oe.pixel_mask=(0,h.ones)([ge[0],ge[2],ge[3]])}return await q(L,oe)}async function ae(b,S){const L=await b.encode(S);return await b.decode(L)}async function ue(b,S,L=!1){const oe=b.sessions[L?"decoder_model_merged":"model"],{past_key_values:ge,...me}=S;if(oe.inputNames.includes("use_cache_branch")&&(me.use_cache_branch=H(!!ge)),oe.inputNames.includes("position_ids")&&me.attention_mask&&!me.position_ids){const De=["paligemma","gemma3_text","gemma3"].includes(b.config.model_type)?1:0;me.position_ids=_e(me,ge,De)}b.addPastKeyValues(me,ge);const Se=(0,a.pick)(me,oe.inputNames);return await q(oe,Se)}function he({modality_token_id:b,inputs_embeds:S,modality_features:L,input_ids:oe,attention_mask:ge}){const me=oe.tolist().map(Je=>Je.reduce((lt,yt,st)=>(yt==b&<.push(st),lt),[])),Se=me.reduce((Je,lt)=>Je+lt.length,0),De=L.dims[0];if(Se!==De)throw new Error(`Number of tokens and features do not match: tokens: ${Se}, features ${De}`);let Ge=0;for(let Je=0;Jeme.dims[1])){if(geDe==b.config.image_token_index)){const De=b.config.num_image_tokens;if(!De)throw new Error("`num_image_tokens` is missing in the model configuration.");const Ge=me.dims[1]-(ge-De);L.input_ids=me.slice(null,[-Ge,null]),L.attention_mask=(0,h.ones)([1,ge+Ge])}}}return L}function He(b,S,L,oe){return L.past_key_values&&(S=S.map(ge=>[ge.at(-1)])),{...L,decoder_input_ids:Z(S)}}function Me(b,...S){return b.config.is_encoder_decoder?He(b,...S):ke(b,...S)}function K(b,S,L,oe){const ge=!!L.past_key_values;return oe.guidance_scale!==null&&oe.guidance_scale>1&&(ge?L.input_ids=(0,h.cat)([L.input_ids,L.input_ids],0):(L.input_ids=(0,h.cat)([L.input_ids,(0,h.full_like)(L.input_ids,BigInt(oe.pad_token_id))],0),L.attention_mask=(0,h.cat)([L.attention_mask,(0,h.full_like)(L.attention_mask,0n)],0))),(ge||!L.pixel_values)&&(L.pixel_values=(0,h.full)([0,0,3,384,384],1)),ge&&(L.images_seq_mask=new h.Tensor("bool",new Array(1).fill(!0).fill(!1,0,1),[1,1]),L.images_emb_mask=new h.Tensor("bool",new Array(0).fill(!1),[1,1,0])),L}class j extends o.Callable{constructor(L,oe,ge){super();re(this,"main_input_name","input_ids");re(this,"forward_params",["input_ids","attention_mask"]);this.config=L,this.sessions=oe,this.configs=ge;const me=x.get(this.constructor),Se=M.get(me);switch(this.can_generate=!1,this._forward=null,this._prepare_inputs_for_generation=null,Se){case P.DecoderOnly:this.can_generate=!0,this._forward=ue,this._prepare_inputs_for_generation=ke;break;case P.Seq2Seq:case P.Vision2Seq:case P.Musicgen:this.can_generate=!0,this._forward=J,this._prepare_inputs_for_generation=He;break;case P.EncoderDecoder:this._forward=J;break;case P.ImageTextToText:this.can_generate=!0,this._forward=X,this._prepare_inputs_for_generation=Me;break;case P.AudioTextToText:this.can_generate=!0,this._forward=se,this._prepare_inputs_for_generation=Me;break;case P.Phi3V:this.can_generate=!0,this._prepare_inputs_for_generation=Me;break;case P.MultiModality:this.can_generate=!0,this._prepare_inputs_for_generation=K;break;case P.AutoEncoder:this._forward=ae;break;default:this._forward=ie;break}this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){var oe;const L=[];for(const ge of Object.values(this.sessions))(oe=ge==null?void 0:ge.handler)!=null&&oe.dispose&&L.push(ge.handler.dispose());return await Promise.all(L)}static async from_pretrained(L,{progress_callback:oe=null,config:ge=null,cache_dir:me=null,local_files_only:Se=!1,revision:De="main",model_file_name:Ge=null,subfolder:Je="onnx",device:lt=null,dtype:yt=null,use_external_data_format:st=null,session_options:Et={}}={}){let at={progress_callback:oe,config:ge,cache_dir:me,local_files_only:Se,revision:De,model_file_name:Ge,subfolder:Je,device:lt,dtype:yt,use_external_data_format:st,session_options:Et};const vt=x.get(this),ut=M.get(vt);ge=at.config=await s.AutoConfig.from_pretrained(L,at);let xt;if(ut===P.DecoderOnly)xt=await Promise.all([z(L,{model:at.model_file_name??"model"},at),R(L,{generation_config:"generation_config.json"},at)]);else if(ut===P.Seq2Seq||ut===P.Vision2Seq)xt=await Promise.all([z(L,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},at),R(L,{generation_config:"generation_config.json"},at)]);else if(ut===P.MaskGeneration)xt=await Promise.all([z(L,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},at)]);else if(ut===P.EncoderDecoder)xt=await Promise.all([z(L,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},at)]);else if(ut===P.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"),xt=await Promise.all([z(L,Lt,at),R(L,{generation_config:"generation_config.json"},at)])}else if(ut===P.AudioTextToText){const Lt={embed_tokens:"embed_tokens",audio_encoder:"audio_encoder",decoder_model_merged:"decoder_model_merged"};xt=await Promise.all([z(L,Lt,at),R(L,{generation_config:"generation_config.json"},at)])}else if(ut===P.Musicgen)xt=await Promise.all([z(L,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},at),R(L,{generation_config:"generation_config.json"},at)]);else if(ut===P.MultiModality)xt=await Promise.all([z(L,{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"},at),R(L,{generation_config:"generation_config.json"},at)]);else if(ut===P.Phi3V)xt=await Promise.all([z(L,{prepare_inputs_embeds:"prepare_inputs_embeds",model:"model",vision_encoder:"vision_encoder"},at),R(L,{generation_config:"generation_config.json"},at)]);else if(ut===P.AutoEncoder)xt=await Promise.all([z(L,{encoder_model:"encoder_model",decoder_model:"decoder_model"},at)]);else{if(ut!==P.EncoderOnly){const Lt=vt??(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}.`)}xt=await Promise.all([z(L,{model:at.model_file_name??"model"},at)])}return new this(ge,...xt)}async _call(L){return await this.forward(L)}async forward(L){return await this._forward(this,L)}get generation_config(){var L;return((L=this.configs)==null?void 0:L.generation_config)??null}_get_logits_warper(L){const oe=new p.LogitsProcessorList;return L.temperature!==null&&L.temperature!==1&&oe.push(new p.TemperatureLogitsWarper(L.temperature)),L.top_k!==null&&L.top_k!==0&&oe.push(new p.TopKLogitsWarper(L.top_k)),L.top_p!==null&&L.top_p<1&&oe.push(new p.TopPLogitsWarper(L.top_p)),oe}_get_logits_processor(L,oe,ge=null){const me=new p.LogitsProcessorList;if(L.repetition_penalty!==null&&L.repetition_penalty!==1&&me.push(new p.RepetitionPenaltyLogitsProcessor(L.repetition_penalty)),L.no_repeat_ngram_size!==null&&L.no_repeat_ngram_size>0&&me.push(new p.NoRepeatNGramLogitsProcessor(L.no_repeat_ngram_size)),L.bad_words_ids!==null&&me.push(new p.NoBadWordsLogitsProcessor(L.bad_words_ids,L.eos_token_id)),L.min_length!==null&&L.eos_token_id!==null&&L.min_length>0&&me.push(new p.MinLengthLogitsProcessor(L.min_length,L.eos_token_id)),L.min_new_tokens!==null&&L.eos_token_id!==null&&L.min_new_tokens>0&&me.push(new p.MinNewTokensLengthLogitsProcessor(oe,L.min_new_tokens,L.eos_token_id)),L.forced_bos_token_id!==null&&me.push(new p.ForcedBOSTokenLogitsProcessor(L.forced_bos_token_id)),L.forced_eos_token_id!==null&&me.push(new p.ForcedEOSTokenLogitsProcessor(L.max_length,L.forced_eos_token_id)),L.begin_suppress_tokens!==null){const Se=oe>1||L.forced_bos_token_id===null?oe:oe+1;me.push(new p.SuppressTokensAtBeginLogitsProcessor(L.begin_suppress_tokens,Se))}return L.guidance_scale!==null&&L.guidance_scale>1&&me.push(new p.ClassifierFreeGuidanceLogitsProcessor(L.guidance_scale)),ge!==null&&me.extend(ge),me}_prepare_generation_config(L,oe,ge=c.GenerationConfig){const me={...this.config};for(const De of["decoder","generator","text_config"])De in me&&Object.assign(me,me[De]);const Se=new ge(me);return Object.assign(Se,this.generation_config??{}),L&&Object.assign(Se,L),oe&&Object.assign(Se,(0,a.pick)(oe,Object.getOwnPropertyNames(Se))),Se}_get_stopping_criteria(L,oe=null){const ge=new E.StoppingCriteriaList;return L.max_length!==null&&ge.push(new E.MaxLengthCriteria(L.max_length,this.config.max_position_embeddings??null)),L.eos_token_id!==null&&ge.push(new E.EosTokenCriteria(L.eos_token_id)),oe&&ge.extend(oe),ge}_validate_model_class(){if(!this.can_generate){const L=[xc,Ec,Tc,vc],oe=x.get(this.constructor),ge=new Set,me=this.config.model_type;for(const De of L){const Ge=De.get(me);Ge&&ge.add(Ge[0])}let Se=`The current model class (${oe}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw ge.size>0&&(Se+=` Please use the following class instead: ${[...ge].join(", ")}`),Error(Se)}}prepare_inputs_for_generation(...L){return this._prepare_inputs_for_generation(this,...L)}_update_model_kwargs_for_generation({generated_input_ids:L,outputs:oe,model_inputs:ge,is_encoder_decoder:me}){return ge.past_key_values=this.getPastKeyValues(oe,ge.past_key_values),ge.input_ids=new h.Tensor("int64",L.flat(),[L.length,1]),me||(ge.attention_mask=(0,h.cat)([ge.attention_mask,(0,h.ones)([ge.attention_mask.dims[0],1])],1)),ge.position_ids=null,ge}_prepare_model_inputs({inputs:L,bos_token_id:oe,model_kwargs:ge}){const me=(0,a.pick)(ge,this.forward_params),Se=this.main_input_name;if(Se in me){if(L)throw new Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else me[Se]=L;return{inputs_tensor:me[Se],model_inputs:me,model_input_name:Se}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:L,model_inputs:oe,model_input_name:ge,generation_config:me}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!oe.inputs_embeds&&"_prepare_inputs_embeds"in this){const{input_ids:De,pixel_values:Ge,attention_mask:Je,...lt}=oe,yt=await this._prepare_inputs_embeds(oe);oe={...lt,...(0,a.pick)(yt,["inputs_embeds","attention_mask"])}}let{last_hidden_state:Se}=await ie(this,oe);if(me.guidance_scale!==null&&me.guidance_scale>1)Se=(0,h.cat)([Se,(0,h.full_like)(Se,0)],0),"attention_mask"in oe&&(oe.attention_mask=(0,h.cat)([oe.attention_mask,(0,h.zeros_like)(oe.attention_mask)],0));else if(oe.decoder_input_ids){const De=Z(oe.decoder_input_ids).dims[0];if(De!==Se.dims[0]){if(Se.dims[0]!==1)throw new Error(`The encoder outputs have a different batch size (${Se.dims[0]}) than the decoder inputs (${De}).`);Se=(0,h.cat)(Array.from({length:De},()=>Se),0)}}return oe.encoder_outputs=Se,oe}_prepare_decoder_input_ids_for_generation({batch_size:L,model_input_name:oe,model_kwargs:ge,decoder_start_token_id:me,bos_token_id:Se,generation_config:De}){let{decoder_input_ids:Ge,...Je}=ge;if(!(Ge instanceof h.Tensor)){if(Ge)Array.isArray(Ge[0])||(Ge=Array.from({length:L},()=>Ge));else if(me??(me=Se),this.config.model_type==="musicgen")Ge=Array.from({length:L*this.config.decoder.num_codebooks},()=>[me]);else if(Array.isArray(me)){if(me.length!==L)throw new Error(`\`decoder_start_token_id\` expcted to have length ${L} but got ${me.length}`);Ge=me}else Ge=Array.from({length:L},()=>[me]);Ge=Z(Ge)}return ge.decoder_attention_mask=(0,h.ones_like)(Ge),{input_ids:Ge,model_inputs:Je}}async generate({inputs:L=null,generation_config:oe=null,logits_processor:ge=null,stopping_criteria:me=null,streamer:Se=null,...De}){this._validate_model_class(),oe=this._prepare_generation_config(oe,De);let{inputs_tensor:Ge,model_inputs:Je,model_input_name:lt}=this._prepare_model_inputs({inputs:L,model_kwargs:De});const yt=this.config.is_encoder_decoder;yt&&("encoder_outputs"in Je||(Je=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:Ge,model_inputs:Je,model_input_name:lt,generation_config:oe})));let st;yt?{input_ids:st,model_inputs:Je}=this._prepare_decoder_input_ids_for_generation({batch_size:Je[lt].dims.at(0),model_input_name:lt,model_kwargs:Je,decoder_start_token_id:oe.decoder_start_token_id,bos_token_id:oe.bos_token_id,generation_config:oe}):st=Je[lt];let Et=st.dims.at(-1);oe.max_new_tokens!==null&&(oe.max_length=Et+oe.max_new_tokens);const at=this._get_logits_processor(oe,Et,ge),vt=this._get_stopping_criteria(oe,me),ut=Je[lt].dims.at(0),xt=A.LogitsSampler.getSampler(oe),Lt=new Array(ut).fill(0),Qt=st.tolist();Se&&Se.put(Qt);let yr,Pt={};for(;;){if(Je=this.prepare_inputs_for_generation(Qt,Je,oe),yr=await this.forward(Je),oe.output_attentions&&oe.return_dict_in_generate){const Cr=this.getAttentions(yr);for(const Is in Cr)Is in Pt||(Pt[Is]=[]),Pt[Is].push(Cr[Is])}const sr=yr.logits.slice(null,-1,null),Wr=at(Qt,sr),un=[];for(let Cr=0;CrCr))break;Je=this._update_model_kwargs_for_generation({generated_input_ids:un,outputs:yr,model_inputs:Je,is_encoder_decoder:yt})}Se&&Se.end();const Nt=this.getPastKeyValues(yr,Je.past_key_values,!0),tr=new h.Tensor("int64",Qt.flat(),[Qt.length,Qt[0].length]);if(oe.return_dict_in_generate)return{sequences:tr,past_key_values:Nt,...Pt};for(const sr of Object.values(yr))sr.location==="gpu-buffer"&&sr.dispose();return tr}getPastKeyValues(L,oe,ge=!1){const me=Object.create(null);for(const Se in L)if(Se.startsWith("present")){const De=Se.replace("present","past_key_values"),Ge=Se.includes("encoder");if(Ge&&oe?me[De]=oe[De]:me[De]=L[Se],oe&&(!Ge||ge)){const Je=oe[De];Je.location==="gpu-buffer"&&Je.dispose()}}return me}getAttentions(L){const oe={};for(const ge of["cross_attentions","encoder_attentions","decoder_attentions"])for(const me in L)me.startsWith(ge)&&(ge in oe||(oe[ge]=[]),oe[ge].push(L[me]));return oe}addPastKeyValues(L,oe){var ge,me,Se;if(oe)Object.assign(L,oe);else{const De=this.sessions.decoder_model_merged??this.sessions.model,Ge=((ge=De==null?void 0:De.config)==null?void 0:ge.kv_cache_dtype)??"float32",Je=Ge==="float16"?new h.DataTypeMap.float16:[],lt=((Se=(me=L[this.main_input_name]??L.attention_mask)==null?void 0:me.dims)==null?void 0:Se[0])??1,yt=(0,s.getKeyValueShapes)(this.config,{batch_size:lt});for(const st in yt)L[st]=new h.Tensor(Ge,Je,yt[st])}}async encode_image({pixel_values:L}){const oe=(await q(this.sessions.vision_encoder,{pixel_values:L})).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 (${oe.dims[1]}).`),this.config.num_image_tokens=oe.dims[1]),oe}async encode_text({input_ids:L}){return(await q(this.sessions.embed_tokens,{input_ids:L})).inputs_embeds}async encode_audio({audio_values:L}){return(await q(this.sessions.audio_encoder,{audio_values:L})).audio_features}}class fe{}class Pe extends fe{constructor({last_hidden_state:S,hidden_states:L=null,attentions:oe=null}){super(),this.last_hidden_state=S,this.hidden_states=L,this.attentions=oe}}class xe extends j{}class Ae extends xe{}class Ie extends xe{async _call(S){return new wr(await super._call(S))}}class Le extends xe{async _call(S){return new bt(await super._call(S))}}class Ne extends xe{async _call(S){return new pr(await super._call(S))}}class We extends xe{async _call(S){return new Pr(await super._call(S))}}class D extends j{}class ee extends D{}class B extends D{async _call(S){return new wr(await super._call(S))}}class te extends D{async _call(S){return new bt(await super._call(S))}}class de extends D{async _call(S){return new pr(await super._call(S))}}class be extends j{}class ve extends be{}class Re extends j{}class Fe extends Re{}class je extends Re{async _call(S){return new wr(await super._call(S))}}class qe extends Re{async _call(S){return new bt(await super._call(S))}}class Xe extends Re{async _call(S){return new pr(await super._call(S))}}class ct extends Re{async _call(S){return new Pr(await super._call(S))}}class wt extends j{}class nr extends wt{}class jt extends wt{async _call(S){return new wr(await super._call(S))}}class dr extends wt{async _call(S){return new bt(await super._call(S))}}class us extends wt{async _call(S){return new pr(await super._call(S))}}class Ds extends wt{async _call(S){return new Pr(await super._call(S))}}class Dr extends j{}class cs extends Dr{}class Ls extends Dr{async _call(S){return new wr(await super._call(S))}}class jr extends Dr{async _call(S){return new bt(await super._call(S))}}class dt extends Dr{async _call(S){return new pr(await super._call(S))}}class qr extends Dr{async _call(S){return new Pr(await super._call(S))}}class Vr extends j{}class ps extends Vr{}class xs extends Vr{async _call(S){return new wr(await super._call(S))}}class Es extends Vr{async _call(S){return new bt(await super._call(S))}}class Ps extends Vr{async _call(S){return new pr(await super._call(S))}}class zs extends Vr{async _call(S){return new Pr(await super._call(S))}}class fr extends j{}class Be extends fr{}class et extends fr{async _call(S){return new wr(await super._call(S))}}class it extends fr{async _call(S){return new bt(await super._call(S))}}class rr extends fr{async _call(S){return new pr(await super._call(S))}}class zt extends fr{async _call(S){return new Pr(await super._call(S))}}class kr extends j{}class hs extends kr{}class fs extends kr{async _call(S){return new wr(await super._call(S))}}class Er extends kr{async _call(S){return new bt(await super._call(S))}}class ms extends kr{async _call(S){return new pr(await super._call(S))}}class _s extends kr{async _call(S){return new Pr(await super._call(S))}}class Qr extends j{}class Cs extends Qr{}class Xs extends Qr{async _call(S){return new bt(await super._call(S))}}class Js extends Qr{async _call(S){return new pr(await super._call(S))}}class Ys extends Qr{async _call(S){return new Pr(await super._call(S))}}class Zs extends Qr{async _call(S){return new wr(await super._call(S))}}class gs extends j{}class en extends gs{}class tn extends gs{async _call(S){return new wr(await super._call(S))}}class rn extends gs{async _call(S){return new bt(await super._call(S))}}class Lr extends gs{async _call(S){return new pr(await super._call(S))}}class Ss extends j{}class br extends Ss{}class Bs extends Ss{async _call(S){return new wr(await super._call(S))}}class Rs extends Ss{async _call(S){return new bt(await super._call(S))}}class Ir extends Ss{async _call(S){return new Pr(await super._call(S))}}class Xr extends j{}class En extends Xr{}class zr extends Xr{async _call(S){return new wr(await super._call(S))}}class Pn extends Xr{async _call(S){return new bt(await super._call(S))}}class Ns extends Xr{async _call(S){return new pr(await super._call(S))}}class Ar extends Xr{async _call(S){return new Pr(await super._call(S))}}class Jr extends j{}class ur extends Jr{}class mr extends Jr{async _call(S){return new wr(await super._call(S))}}class js extends Jr{async _call(S){return new bt(await super._call(S))}}class Cn extends Jr{async _call(S){return new Pr(await super._call(S))}}class $s extends j{}class Sn extends $s{}class pe extends $s{async _call(S){return new bt(await super._call(S))}}class F extends $s{async _call(S){return new Pr(await super._call(S))}}class V extends $s{async _call(S){return new wr(await super._call(S))}}class Y extends j{constructor(){super(...arguments);re(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"])}}class le extends Y{}class ce extends Y{}class Ce extends j{}class Ue extends Ce{}class Qe extends Ce{}class Ke extends j{}class Ze extends Ke{}class ht extends Ke{}class Ct extends j{}class kt extends Ct{}class Wt extends Ct{}class Ot extends Ct{async _call(S){return new bt(await super._call(S))}}class Vt extends j{}class vr extends Vt{}class _r extends Vt{}class Yr extends Vt{async _call(S){return new bt(await super._call(S))}}class Tr extends Vt{}class ws extends j{}class Gt extends ws{}class Zt extends ws{}class gr extends j{}class Zr extends gr{}class ys extends gr{}class Ht extends j{}class cr extends Ht{}class Rt extends Ht{async _call(S){return new wr(await super._call(S))}}class Jt extends Ht{async _call(S){return new bt(await super._call(S))}}class qt extends Ht{async _call(S){return new pr(await super._call(S))}}class er extends Ht{async _call(S){return new Pr(await super._call(S))}}class ir extends j{}class sn extends ir{}class nn extends ir{async _call(S){return new wr(await super._call(S))}}class za extends ir{async _call(S){return new bt(await super._call(S))}}class Ui extends ir{async _call(S){return new pr(await super._call(S))}}class Ba extends ir{async _call(S){return new Pr(await super._call(S))}}class Ms extends j{}class Ra extends Ms{}class Na extends Ms{async _call(S){return new wr(await super._call(S))}}class $n extends Ms{async _call(S){return new bt(await super._call(S))}}class ja extends Ms{async _call(S){return new pr(await super._call(S))}}class Wi extends Ms{async _call(S){return new Pr(await super._call(S))}}class Gi extends j{}class Va extends Gi{}class Ua extends Gi{}class Wn extends j{constructor(){super(...arguments);re(this,"requires_attention_mask",!1);re(this,"main_input_name","input_features");re(this,"forward_params",["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"])}}class Wa extends Wn{}class Ki extends Wn{_prepare_generation_config(S,L){return super._prepare_generation_config(S,L,y.WhisperGenerationConfig)}_retrieve_init_tokens(S){const L=[S.decoder_start_token_id];let oe=S.language;const ge=S.task;if(S.is_multilingual){oe||(console.warn("No language specified - defaulting to English (en)."),oe="en");const Se=`<|${(0,k.whisper_language_to_code)(oe)}|>`;L.push(S.lang_to_id[Se]),L.push(S.task_to_id[ge??"transcribe"])}else if(oe||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!S.return_timestamps&&S.no_timestamps_token_id&&L.at(-1)!==S.no_timestamps_token_id?L.push(S.no_timestamps_token_id):S.return_timestamps&&L.at(-1)===S.no_timestamps_token_id&&(console.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),L.pop()),L.filter(me=>me!=null)}async generate({inputs:S=null,generation_config:L=null,logits_processor:oe=null,stopping_criteria:ge=null,...me}){L=this._prepare_generation_config(L,me);const Se=me.decoder_input_ids??this._retrieve_init_tokens(L);if(L.return_timestamps&&(oe??(oe=new p.LogitsProcessorList),oe.push(new p.WhisperTimeStampLogitsProcessor(L,Se))),L.begin_suppress_tokens&&(oe??(oe=new p.LogitsProcessorList),oe.push(new p.SuppressTokensAtBeginLogitsProcessor(L.begin_suppress_tokens,Se.length))),L.return_token_timestamps){if(!L.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.");L.task==="translate"&&console.warn("Token-level timestamps may not be reliable for task 'translate'."),L.output_attentions=!0,L.return_dict_in_generate=!0}const De=await super.generate({inputs:S,generation_config:L,logits_processor:oe,decoder_input_ids:Se,...me});return L.return_token_timestamps&&(De.token_timestamps=this._extract_token_timestamps(De,L.alignment_heads,L.num_frames)),De}_extract_token_timestamps(S,L,oe=null,ge=.02){if(!S.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`.");oe==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 me=this.config.median_filter_width;me===void 0&&(console.warn("Model config has no `median_filter_width`, using default value of 7."),me=7);const Se=S.cross_attentions,De=Array.from({length:this.config.decoder_layers},(vt,ut)=>(0,h.cat)(Se.map(xt=>xt[ut]),2)),Ge=(0,h.stack)(L.map(([vt,ut])=>{if(vt>=De.length)throw new Error(`Layer index ${vt} is out of bounds for cross attentions (length ${De.length}).`);return oe?De[vt].slice(null,ut,null,[0,oe]):De[vt].slice(null,ut)})).transpose(1,0,2,3),[Je,lt]=(0,h.std_mean)(Ge,-2,0,!0),yt=Ge.clone();for(let vt=0;vtxt[tr+1]-xt[tr]),yr=(0,a.mergeArrays)([1],Qt).map(Nt=>!!Nt),Pt=[];for(let Nt=0;Ntst.findIndex(Et=>Et==me)),Ge=De.every(st=>st===-1),Je=De.every(st=>st!==-1);if(!Ge&&!Je)throw new Error("Every input should contain either 0 or 1 image token.");if(Ge)return{inputs_embeds:S,attention_mask:ge};const lt=[],yt=[];for(let st=0;stArray.from({length:S.dims[0]},Qt=>Array.from({length:S.dims[1]},yr=>1))),at=L?L.tolist():[],vt=oe?oe.tolist():[];let ut=0,xt=0;for(let Lt=0;Ltst[Lt][or]==1),Pt=Qt.reduce((Kt,or,cn)=>(or==Ge&&Kt.push(cn),Kt),[]).map(Kt=>Qt[Kt+1]),Nt=Pt.filter(Kt=>Kt==Se).length,tr=Pt.filter(Kt=>Kt==De).length;let sr=[],Wr=0,un=Nt,Zl=tr;for(let Kt=0;Ktbs>Wr&&Ln==Se),cn=Qt.findIndex((Ln,bs)=>bs>Wr&&Ln==De),Dn=un>0&&or!==-1?or:Qt.length+1,Pi=Zl>0&&cn!==-1?cn:Qt.length+1;let sd,Sc,$c,kc;Dn0?(0,_.max)(sr.at(-1))[0]+1:0;sr.push(Array.from({length:3*Ac},(Ln,bs)=>E0+bs%Ac));const Fc=Ac+E0,id=NT*Ic*nd,jT=Array.from({length:id},(Ln,bs)=>Fc+Math.floor(bs/(Ic*nd))),VT=Array.from({length:id},(Ln,bs)=>Fc+Math.floor(bs/nd)%Ic),UT=Array.from({length:id},(Ln,bs)=>Fc+bs%nd);sr.push([jT,VT,UT].flat()),Wr=sd+id}if(Wr0?(0,_.max)(sr.at(-1))[0]+1:0,or=Qt.length-Wr;sr.push(Array.from({length:3*or},(cn,Dn)=>Kt+Dn%or))}const Cr=sr.reduce((Kt,or)=>Kt+or.length,0),Is=new Array(Cr);let Cc=0;for(let Kt=0;Kt<3;++Kt)for(let or=0;oryt[ut%yt.length]),at=Array.from({length:st[0]},(vt,ut)=>(0,_.max)(yt.subarray(st[1]*ut,st[1]*(ut+1)))[0]+1n+BigInt(st[1]));return[new h.Tensor("int64",Et,[3,...st]),new h.Tensor("int64",at,[at.length,1])]}else{const[yt,st]=S.dims,Et=BigInt64Array.from({length:3*yt*st},(at,vt)=>BigInt(Math.floor(vt%st/yt)));return[new h.Tensor("int64",Et,[3,...S.dims]),(0,h.zeros)([yt,1])]}}async encode_image({pixel_values:S,image_grid_thw:L}){return(await q(this.sessions.vision_encoder,{pixel_values:S,grid_thw:L})).image_features}_merge_input_ids_with_image_features(S){return N({image_token_id:this.config.image_token_id,...S})}prepare_inputs_for_generation(S,L,oe){if(L.attention_mask&&!L.position_ids)if(!L.past_key_values)[L.position_ids,L.rope_deltas]=this.get_rope_index(L.input_ids,L.image_grid_thw,L.video_grid_thw,L.attention_mask);else{L.pixel_values=null;const ge=BigInt(Object.values(L.past_key_values)[0].dims.at(-2)),me=L.rope_deltas.map(Se=>ge+Se);L.position_ids=(0,h.stack)([me,me,me],0)}return L}}class mi extends j{}class Do extends mi{}class Lo extends mi{}class _i extends j{}class zo extends _i{}class Bo extends _i{}class gi extends j{}class Ro extends gi{}class No extends gi{}class wi extends j{}class jo extends wi{}class Vo extends wi{}class yi extends j{}class Uo extends yi{}class Wo extends yi{}class Mi extends j{}class Go extends Mi{}class Ko extends Mi{async _call(S){return new bt(await super._call(S))}}class bi extends j{}class Ho extends bi{}class qo extends bi{async _call(S){return new bt(await super._call(S))}}class Qo extends j{}class Xo extends Qo{}class Jo extends j{}class ul extends Jo{}class cl extends Jo{async _call(S){return new bt(await super._call(S))}}class pl extends j{}class hl extends pl{}class Yo extends j{}class fl extends Yo{}class ml extends Yo{async _call(S){return new bt(await super._call(S))}}class _l extends j{}class gl extends _l{}class Zo extends j{}class wl extends Zo{}class yl extends Zo{async _call(S){return new bt(await super._call(S))}}class Ml extends j{}class bl extends Ml{async _call(S){return new T0(await super._call(S))}}class ea extends j{}class vl extends ea{}class Tl extends ea{async _call(S){return new bt(await super._call(S))}}class ta extends j{}class xl extends ta{}class El extends ta{async _call(S){return new bt(await super._call(S))}}class ra extends j{}class Pl extends ra{}class Cl extends ra{}class sa extends j{}class Sl extends sa{}class $l extends sa{}class na extends j{}class kl extends na{}class Il extends na{async _call(S){return new bt(await super._call(S))}}class vi extends j{}class Al extends vi{}class Fl extends vi{async _call(S){return new oa(await super._call(S))}}class ia extends vi{async _call(S){return new Ol(await super._call(S))}}class oa extends fe{constructor({logits:S,pred_boxes:L}){super(),this.logits=S,this.pred_boxes=L}}class Ol extends fe{constructor({logits:S,pred_boxes:L,pred_masks:oe}){super(),this.logits=S,this.pred_boxes=L,this.pred_masks=oe}}class aa extends j{}class Dl extends aa{}class Ll extends aa{async _call(S){return new Ti(await super._call(S))}}class Ti extends fe{constructor({logits:S,pred_boxes:L}){super(),this.logits=S,this.pred_boxes=L}}class la extends j{}class zl extends la{}class Bl extends la{async _call(S){return new Rl(await super._call(S))}}class Rl extends Ti{}class da extends j{}class ua extends da{}class d extends da{async _call(S){return new f(await super._call(S))}}class f extends Ti{}class T extends j{}class C extends T{}class I extends T{async _call(S){return new W(await super._call(S))}}class W extends oa{}class ne extends j{}class ye extends ne{}class Ee extends ne{async _call(S){return new bt(await super._call(S))}}class ze extends j{}class Ye extends ze{}class ot extends ze{async _call(S){return new bt(await super._call(S))}}class _t extends j{}class Bt extends _t{}class Fr extends _t{async _call(S){return new bt(await super._call(S))}}class ks extends j{}class Jw extends ks{}class Yw extends ks{async _call(S){return new bt(await super._call(S))}}class Zw extends ks{}class ec extends j{}class ey extends ec{}class ty extends ec{}class tc extends j{}class ry extends tc{}class sy extends tc{}class ny extends j{}class iy extends ny{}class Nl extends j{}class oy extends Nl{}class ay extends Nl{}class ly extends Nl{}class dy extends j{}class uy extends dy{}class cy extends j{}class py extends cy{}class hy extends j{}class fy extends hy{}class rc extends j{}class my extends rc{}class _y extends rc{}class sc extends j{}class gy extends sc{}class wy extends sc{}class yy extends j{}class My extends yy{}class nc extends j{}class by extends nc{}class vy extends nc{async _call(S){return new bt(await super._call(S))}}class ic extends j{}class Ty extends ic{}class xy extends ic{async _call(S){return new bt(await super._call(S))}}class oc extends j{}class Ey extends oc{}class Py extends oc{async _call(S){return new bt(await super._call(S))}}class ac extends j{}class Cy extends ac{}class Sy extends ac{async _call(S){return new bt(await super._call(S))}}class $y extends j{}class ky extends $y{}class lc extends j{}class Iy extends lc{}class Ay extends lc{async _call(S){return new Fy(await super._call(S))}}class Fy extends fe{constructor({logits:S,pred_boxes:L}){super(),this.logits=S,this.pred_boxes=L}}class Oy extends j{}class Dy extends Oy{async get_image_embeddings({pixel_values:S}){return await ie(this,{pixel_values:S})}async forward(S){if((!S.image_embeddings||!S.image_positional_embeddings)&&(S={...S,...await this.get_image_embeddings(S)}),!S.input_labels&&S.input_points){const oe=S.input_points.dims.slice(0,-1),ge=oe.reduce((me,Se)=>me*Se,1);S.input_labels=new h.Tensor("int64",new BigInt64Array(ge).fill(1n),oe)}const L={image_embeddings:S.image_embeddings,image_positional_embeddings:S.image_positional_embeddings};return S.input_points&&(L.input_points=S.input_points),S.input_labels&&(L.input_labels=S.input_labels),S.input_boxes&&(L.input_boxes=S.input_boxes),await q(this.sessions.prompt_encoder_mask_decoder,L)}async _call(S){return new Ly(await super._call(S))}}class Ly extends fe{constructor({iou_scores:S,pred_masks:L}){super(),this.iou_scores=S,this.pred_masks=L}}class dc extends j{}class zy extends dc{}class By extends dc{}class uc extends j{}class Ry extends uc{}class Ny extends uc{}class dn extends j{}class jy extends dn{}class Vy extends dn{async _call(S){return new On(await super._call(S))}}class Uy extends dn{async _call(S){return new bt(await super._call(S))}}class Wy extends dn{async _call(S){return new pr(await super._call(S))}}class cc extends j{}class Gy extends cc{}class Ky extends cc{async _call(S){return new pr(await super._call(S))}}class Hy extends j{}class qy extends Hy{}class jl extends j{}class Qy extends jl{}class Xy extends jl{async _call(S){return new On(await super._call(S))}}class Jy extends jl{async _call(S){return new bt(await super._call(S))}}class ca extends j{}class Yy extends ca{}class Zy extends ca{async _call(S){return new On(await super._call(S))}}class eM extends ca{async _call(S){return new bt(await super._call(S))}}class tM extends ca{async _call(S){return new pr(await super._call(S))}}class Vl extends j{}class rM extends Vl{}class sM extends Vl{async _call(S){return new On(await super._call(S))}}class nM extends Vl{async _call(S){return new bt(await super._call(S))}}class ET extends j{}class iM extends dn{}class oM extends dn{async _call(S){return new On(await super._call(S))}}class aM extends dn{async _call(S){return new bt(await super._call(S))}}class xi extends j{}class lM extends xi{}class dM extends xi{async _call(S){return new On(await super._call(S))}}class uM extends xi{async _call(S){return new bt(await super._call(S))}}class cM extends xi{async _call(S){return new v0(await super._call(S))}}class pM extends xi{async _call(S){return new pr(await super._call(S))}}class hM extends j{}class fM extends hM{}class Ul extends j{}class PT extends Ul{}class mM extends Ul{}class _M extends Ul{async generate_speech(S,L,{threshold:oe=.5,minlenratio:ge=0,maxlenratio:me=20,vocoder:Se=null}={}){const De={input_ids:S},{encoder_outputs:Ge,encoder_attention_mask:Je}=await ie(this,De),lt=Ge.dims[1]/this.config.reduction_factor,yt=Math.floor(lt*me),st=Math.floor(lt*ge),Et=this.config.num_mel_bins;let at=[],vt=null,ut=null,xt=0;for(;;){++xt;const yr=H(!!ut);let Pt;ut?Pt=ut.output_sequence_out:Pt=new h.Tensor("float32",new Float32Array(Et),[1,1,Et]);let Nt={use_cache_branch:yr,output_sequence:Pt,encoder_attention_mask:Je,speaker_embeddings:L,encoder_hidden_states:Ge};this.addPastKeyValues(Nt,vt),ut=await q(this.sessions.decoder_model_merged,Nt),vt=this.getPastKeyValues(ut,vt);const{prob:tr,spectrum:sr}=ut;if(at.push(sr),xt>=st&&(Array.from(tr.data).filter(Wr=>Wr>=oe).length>0||xt>=yt))break}const Lt=(0,h.cat)(at),{waveform:Qt}=await q(Se.sessions.model,{spectrogram:Lt});return{spectrogram:Lt,waveform:Qt}}}class gM extends j{constructor(){super(...arguments);re(this,"main_input_name","spectrogram")}}class wM extends j{}class yM extends wM{}class pc extends j{}class MM extends pc{}class bM extends pc{}class hc extends j{}class vM extends hc{}class TM extends hc{}class fc extends j{}class xM extends fc{}class EM extends fc{}class Wl extends j{}class PM extends Wl{}class CM extends Wl{static async from_pretrained(S,L={}){return super.from_pretrained(S,{...L,model_file_name:L.model_file_name??"text_model"})}}class SM extends Wl{static async from_pretrained(S,L={}){return super.from_pretrained(S,{...L,model_file_name:L.model_file_name??"audio_model"})}}class $M extends j{}class mc extends $M{async _call(S){return new x0(await super._call(S))}}class Gl extends j{}class CT extends Gl{}class kM extends Gl{}class IM extends Gl{}class _c extends j{}class AM extends _c{}class FM extends _c{}class gc extends j{}class OM extends gc{}class DM extends gc{async _call(S){return new bt(await super._call(S))}}class wc extends j{}class ST extends wc{}class $T extends wc{}class yc extends j{constructor(){super(...arguments);re(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(L){const[oe,ge]=L.dims,me=this.config.decoder.num_codebooks,Se=ge-me;let De=0;for(let lt=0;lt0&&Et<=Se&&(L.data[De++]=L.data[lt])}const Ge=Math.floor(oe/me),Je=De/(Ge*me);return new h.Tensor(L.type,L.data.slice(0,De),[Ge,me,Je])}prepare_inputs_for_generation(L,oe,ge){let me=structuredClone(L);for(let De=0;De=Ge&&(me[De][Ge]=BigInt(this.config.decoder.pad_token_id));return ge.guidance_scale!==null&&ge.guidance_scale>1&&(me=me.concat(me)),super.prepare_inputs_for_generation(me,oe,ge)}async generate(L){const oe=await super.generate(L),ge=this._apply_and_filter_by_delay_pattern_mask(oe).unsqueeze_(0),{audio_values:me}=await q(this.sessions.encodec_decode,{audio_codes:ge});return me}}class Kl extends j{}class LM extends Kl{}class zM extends Kl{async _call(S){return new bt(await super._call(S))}}class BM extends Kl{}class Hl extends j{}class RM extends Hl{}class NM extends Hl{async _call(S){return new bt(await super._call(S))}}class jM extends Hl{}class ql extends j{}class VM extends ql{}class UM extends ql{async _call(S){return new bt(await super._call(S))}}class WM extends ql{}class Ql extends j{}class GM extends Ql{}class KM extends Ql{async _call(S){return new bt(await super._call(S))}}class HM extends Ql{}class qM extends j{}class QM extends qM{}class XM extends j{}class JM extends XM{constructor(...L){super(...L);re(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(L){const oe=this._generation_mode??"text";let ge;if(oe==="text"||!L.past_key_values){const Je=this.sessions.prepare_inputs_embeds,lt=(0,a.pick)(L,Je.inputNames);ge=await q(Je,lt)}else{const Je=this.sessions.gen_img_embeds,lt=(0,a.pick)({image_ids:L.input_ids},Je.inputNames);ge=await q(Je,lt)}const me={...L,...ge},Se=await ue(this,me),De=this.sessions[oe==="text"?"lm_head":"gen_head"];if(!De)throw new Error(`Unable to find "${De}" generation head`);const Ge=await q(De,(0,a.pick)(Se,De.inputNames));return{...ge,...Se,...Ge}}async generate(L){return this._generation_mode="text",super.generate(L)}async generate_images(L){this._generation_mode="image";const oe=(L.inputs??L[this.main_input_name]).dims[1],me=(await super.generate(L)).slice(null,[oe,null]),Se=this.sessions.image_decode,{decoded_image:De}=await q(Se,{generated_tokens:me}),Ge=De.add_(1).mul_(255/2).clamp_(0,255).to("uint8"),Je=[];for(const lt of Ge){const yt=g.RawImage.fromTensor(lt);Je.push(yt)}return Je}}class YM extends fe{constructor({char_logits:S,bpe_logits:L,wp_logits:oe}){super(),this.char_logits=S,this.bpe_logits=L,this.wp_logits=oe}get logits(){return[this.char_logits,this.bpe_logits,this.wp_logits]}}class ZM extends j{}class eb extends ZM{async _call(S){return new YM(await super._call(S))}}class Mc extends j{}class tb extends Mc{}class rb extends Mc{}class bc extends j{}class sb extends bc{}class nb extends bc{}class ib extends j{constructor(){super(...arguments);re(this,"forward_params",["input_ids","attention_mask","position_ids","audio_values","past_key_values"])}}class ob extends ib{_merge_input_ids_with_audio_features(S){const L=S.audio_features.dims.at(-1),oe=S.audio_features.view(-1,L);return O({audio_token_id:this.config.ignore_index,...S,audio_features:oe})}}class Xl extends j{constructor(){super(...arguments);re(this,"main_input_name","input_values");re(this,"forward_params",["input_values"])}}class ab extends fe{constructor({audio_codes:S}){super(),this.audio_codes=S}}class lb extends fe{constructor({audio_values:S}){super(),this.audio_values=S}}class db extends Xl{async encode(S){return new ab(await q(this.sessions.encoder_model,S))}async decode(S){return new lb(await q(this.sessions.decoder_model,S))}}class ub extends Xl{static async from_pretrained(S,L={}){return super.from_pretrained(S,{...L,model_file_name:L.model_file_name??"encoder_model"})}}class cb extends Xl{static async from_pretrained(S,L={}){return super.from_pretrained(S,{...L,model_file_name:L.model_file_name??"decoder_model"})}}class Jl extends j{constructor(){super(...arguments);re(this,"main_input_name","input_values");re(this,"forward_params",["input_values"])}}class pb extends fe{constructor({audio_codes:S}){super(),this.audio_codes=S}}class hb extends fe{constructor({audio_values:S}){super(),this.audio_values=S}}class fb extends Jl{async encode(S){return new pb(await q(this.sessions.encoder_model,S))}async decode(S){return new hb(await q(this.sessions.decoder_model,S))}}class mb extends Jl{static async from_pretrained(S,L={}){return super.from_pretrained(S,{...L,model_file_name:L.model_file_name??"encoder_model"})}}class _b extends Jl{static async from_pretrained(S,L={}){return super.from_pretrained(S,{...L,model_file_name:L.model_file_name??"decoder_model"})}}class Yl extends j{constructor(){super(...arguments);re(this,"main_input_name","input_values");re(this,"forward_params",["input_values"])}}class gb extends Yl{async encode(S){return await q(this.sessions.encoder_model,S)}async decode(S){return await q(this.sessions.decoder_model,S)}}class wb extends Yl{static async from_pretrained(S,L={}){return super.from_pretrained(S,{...L,model_file_name:L.model_file_name??"encoder_model"})}}class yb extends Yl{static async from_pretrained(S,L={}){return super.from_pretrained(S,{...L,model_file_name:L.model_file_name??"decoder_model"})}}class It{static async from_pretrained(S,{progress_callback:L=null,config:oe=null,cache_dir:ge=null,local_files_only:me=!1,revision:Se="main",model_file_name:De=null,subfolder:Ge="onnx",device:Je=null,dtype:lt=null,use_external_data_format:yt=null,session_options:st={}}={}){const Et={progress_callback:L,config:oe,cache_dir:ge,local_files_only:me,revision:Se,model_file_name:De,subfolder:Ge,device:Je,dtype:lt,use_external_data_format:yt,session_options:st};if(Et.config=await s.AutoConfig.from_pretrained(S,Et),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);const at=Et.config.model_type;for(const vt of this.MODEL_CLASS_MAPPINGS){let ut=vt.get(at);if(!ut){for(const xt of vt.values())if(xt[0]===at){ut=xt;break}if(!ut)continue}return await ut[1].from_pretrained(S,Et)}if(this.BASE_IF_FAIL)return Gb.has(at)||console.warn(`Unknown model class "${at}", attempting to construct from base class.`),await j.from_pretrained(S,Et);throw Error(`Unsupported model type: ${at}`)}}re(It,"MODEL_CLASS_MAPPINGS",null),re(It,"BASE_IF_FAIL",!1);const kT=new Map([["bert",["BertModel",Ae]],["modernbert",["ModernBertModel",ee]],["nomic_bert",["NomicBertModel",ve]],["roformer",["RoFormerModel",Fe]],["electra",["ElectraModel",cs]],["esm",["EsmModel",en]],["convbert",["ConvBertModel",nr]],["camembert",["CamembertModel",ps]],["deberta",["DebertaModel",Be]],["deberta-v2",["DebertaV2Model",hs]],["mpnet",["MPNetModel",En]],["albert",["AlbertModel",Sn]],["distilbert",["DistilBertModel",Cs]],["roberta",["RobertaModel",cr]],["xlm",["XLMModel",sn]],["xlm-roberta",["XLMRobertaModel",Ra]],["clap",["ClapModel",PM]],["clip",["CLIPModel",Zi]],["clipseg",["CLIPSegModel",an]],["chinese_clip",["ChineseCLIPModel",sl]],["siglip",["SiglipModel",Za]],["jina_clip",["JinaCLIPModel",nl]],["mobilebert",["MobileBertModel",br]],["squeezebert",["SqueezeBertModel",ur]],["wav2vec2",["Wav2Vec2Model",jy]],["wav2vec2-bert",["Wav2Vec2BertModel",rM]],["unispeech",["UniSpeechModel",Qy]],["unispeech-sat",["UniSpeechSatModel",Yy]],["hubert",["HubertModel",iM]],["wavlm",["WavLMModel",lM]],["audio-spectrogram-transformer",["ASTModel",Va]],["vits",["VitsModel",mc]],["pyannote",["PyAnnoteModel",Gy]],["wespeaker-resnet",["WeSpeakerResNetModel",qy]],["detr",["DetrModel",Al]],["rt_detr",["RTDetrModel",Dl]],["rt_detr_v2",["RTDetrV2Model",zl]],["rf_detr",["RFDetrModel",ua]],["table-transformer",["TableTransformerModel",C]],["vit",["ViTModel",Go]],["ijepa",["IJepaModel",Ho]],["pvt",["PvtModel",ul]],["vit_msn",["ViTMSNModel",fl]],["vit_mae",["ViTMAEModel",hl]],["groupvit",["GroupViTModel",gl]],["fastvit",["FastViTModel",wl]],["mobilevit",["MobileViTModel",vl]],["mobilevitv2",["MobileViTV2Model",xl]],["owlvit",["OwlViTModel",Pl]],["owlv2",["Owlv2Model",Sl]],["beit",["BeitModel",kl]],["deit",["DeiTModel",ye]],["hiera",["HieraModel",Ye]],["convnext",["ConvNextModel",by]],["convnextv2",["ConvNextV2Model",Ty]],["dinov2",["Dinov2Model",Ey]],["dinov2_with_registers",["Dinov2WithRegistersModel",Cy]],["resnet",["ResNetModel",Bt]],["swin",["SwinModel",Jw]],["swin2sr",["Swin2SRModel",ey]],["donut-swin",["DonutSwinModel",My]],["yolos",["YolosModel",Iy]],["dpt",["DPTModel",ry]],["glpn",["GLPNModel",gy]],["hifigan",["SpeechT5HifiGan",gM]],["efficientnet",["EfficientNetModel",OM]],["decision_transformer",["DecisionTransformerModel",QM]],["patchtst",["PatchTSTForPrediction",tb]],["patchtsmixer",["PatchTSMixerForPrediction",sb]],["mobilenet_v1",["MobileNetV1Model",LM]],["mobilenet_v2",["MobileNetV2Model",RM]],["mobilenet_v3",["MobileNetV3Model",VM]],["mobilenet_v4",["MobileNetV4Model",GM]],["maskformer",["MaskFormerModel",my]],["mgp-str",["MgpstrForSceneTextRecognition",eb]],["style_text_to_speech_2",["StyleTextToSpeech2Model",fM]]]),IT=new Map([["t5",["T5Model",le]],["longt5",["LongT5Model",Ue]],["mt5",["MT5Model",Ze]],["bart",["BartModel",kt]],["mbart",["MBartModel",vr]],["marian",["MarianModel",zy]],["whisper",["WhisperModel",Wa]],["m2m_100",["M2M100Model",Ry]],["blenderbot",["BlenderbotModel",Gt]],["blenderbot-small",["BlenderbotSmallModel",Zr]]]),AT=new Map([["mimi",["MimiModel",db]],["dac",["DacModel",fb]],["snac",["SnacModel",gb]]]),FT=new Map([["bloom",["BloomModel",Ro]],["jais",["JAISModel",ro]],["gpt2",["GPT2Model",al]],["gptj",["GPTJModel",lo]],["gpt_bigcode",["GPTBigCodeModel",dl]],["gpt_neo",["GPTNeoModel",no]],["gpt_neox",["GPTNeoXModel",ll]],["codegen",["CodeGenModel",An]],["llama",["LlamaModel",ti]],["exaone",["ExaoneModel",fo]],["olmo",["OlmoModel",_o]],["olmo2",["Olmo2Model",wo]],["mobilellm",["MobileLLMModel",mt]],["granite",["GraniteModel",yo]],["cohere",["CohereModel",bo]],["gemma",["GemmaModel",To]],["gemma2",["Gemma2Model",Eo]],["gemma3_text",["Gemma3Model",Co]],["helium",["HeliumModel",po]],["glm",["GlmModel",ho]],["openelm",["OpenELMModel",$o]],["qwen2",["Qwen2Model",Io]],["phi",["PhiModel",Do]],["phi3",["Phi3Model",zo]],["mpt",["MptModel",jo]],["opt",["OPTModel",Uo]],["mistral",["MistralModel",MM]],["starcoder2",["Starcoder2Model",vM]],["falcon",["FalconModel",xM]],["stablelm",["StableLmModel",AM]]]),vc=new Map([["speecht5",["SpeechT5ForSpeechToText",mM]],["whisper",["WhisperForConditionalGeneration",Ki]],["lite-whisper",["LiteWhisperForConditionalGeneration",Ga]],["moonshine",["MoonshineForConditionalGeneration",Ka]]]),Mb=new Map([["speecht5",["SpeechT5ForTextToSpeech",_M]]]),bb=new Map([["vits",["VitsModel",mc]],["musicgen",["MusicgenForConditionalGeneration",yc]]]),vb=new Map([["bert",["BertForSequenceClassification",Le]],["modernbert",["ModernBertForSequenceClassification",te]],["roformer",["RoFormerForSequenceClassification",qe]],["electra",["ElectraForSequenceClassification",jr]],["esm",["EsmForSequenceClassification",rn]],["convbert",["ConvBertForSequenceClassification",dr]],["camembert",["CamembertForSequenceClassification",Es]],["deberta",["DebertaForSequenceClassification",it]],["deberta-v2",["DebertaV2ForSequenceClassification",Er]],["mpnet",["MPNetForSequenceClassification",Pn]],["albert",["AlbertForSequenceClassification",pe]],["distilbert",["DistilBertForSequenceClassification",Xs]],["roberta",["RobertaForSequenceClassification",Jt]],["xlm",["XLMForSequenceClassification",za]],["xlm-roberta",["XLMRobertaForSequenceClassification",$n]],["bart",["BartForSequenceClassification",Ot]],["mbart",["MBartForSequenceClassification",Yr]],["mobilebert",["MobileBertForSequenceClassification",Rs]],["squeezebert",["SqueezeBertForSequenceClassification",js]]]),Tb=new Map([["bert",["BertForTokenClassification",Ne]],["modernbert",["ModernBertForTokenClassification",de]],["roformer",["RoFormerForTokenClassification",Xe]],["electra",["ElectraForTokenClassification",dt]],["esm",["EsmForTokenClassification",Lr]],["convbert",["ConvBertForTokenClassification",us]],["camembert",["CamembertForTokenClassification",Ps]],["deberta",["DebertaForTokenClassification",rr]],["deberta-v2",["DebertaV2ForTokenClassification",ms]],["mpnet",["MPNetForTokenClassification",Ns]],["distilbert",["DistilBertForTokenClassification",Js]],["roberta",["RobertaForTokenClassification",qt]],["xlm",["XLMForTokenClassification",Ui]],["xlm-roberta",["XLMRobertaForTokenClassification",ja]]]),Tc=new Map([["t5",["T5ForConditionalGeneration",ce]],["longt5",["LongT5ForConditionalGeneration",Qe]],["mt5",["MT5ForConditionalGeneration",ht]],["bart",["BartForConditionalGeneration",Wt]],["mbart",["MBartForConditionalGeneration",_r]],["marian",["MarianMTModel",By]],["m2m_100",["M2M100ForConditionalGeneration",Ny]],["blenderbot",["BlenderbotForConditionalGeneration",Zt]],["blenderbot-small",["BlenderbotSmallForConditionalGeneration",ys]]]),xc=new Map([["bloom",["BloomForCausalLM",No]],["gpt2",["GPT2LMHeadModel",Jn]],["jais",["JAISLMHeadModel",so]],["gptj",["GPTJForCausalLM",In]],["gpt_bigcode",["GPTBigCodeForCausalLM",uo]],["gpt_neo",["GPTNeoForCausalLM",io]],["gpt_neox",["GPTNeoXForCausalLM",oo]],["codegen",["CodeGenForCausalLM",Ur]],["llama",["LlamaForCausalLM",co]],["exaone",["ExaoneForCausalLM",ft]],["olmo",["OlmoForCausalLM",go]],["olmo2",["Olmo2ForCausalLM",ai]],["mobilellm",["MobileLLMForCausalLM",mo]],["granite",["GraniteForCausalLM",Mo]],["cohere",["CohereForCausalLM",vo]],["gemma",["GemmaForCausalLM",xo]],["gemma2",["Gemma2ForCausalLM",Po]],["gemma3_text",["Gemma3ForCausalLM",So]],["helium",["HeliumForCausalLM",si]],["glm",["GlmForCausalLM",gt]],["openelm",["OpenELMForCausalLM",ko]],["qwen2",["Qwen2ForCausalLM",Ao]],["phi",["PhiForCausalLM",Lo]],["phi3",["Phi3ForCausalLM",Bo]],["mpt",["MptForCausalLM",Vo]],["opt",["OPTForCausalLM",Wo]],["mbart",["MBartForCausalLM",Tr]],["mistral",["MistralForCausalLM",bM]],["starcoder2",["Starcoder2ForCausalLM",TM]],["falcon",["FalconForCausalLM",EM]],["trocr",["TrOCRForCausalLM",yM]],["stablelm",["StableLmForCausalLM",FM]],["phi3_v",["Phi3VForCausalLM",Vs]]]),OT=new Map([["multi_modality",["MultiModalityCausalLM",JM]]]),xb=new Map([["bert",["BertForMaskedLM",Ie]],["modernbert",["ModernBertForMaskedLM",B]],["roformer",["RoFormerForMaskedLM",je]],["electra",["ElectraForMaskedLM",Ls]],["esm",["EsmForMaskedLM",tn]],["convbert",["ConvBertForMaskedLM",jt]],["camembert",["CamembertForMaskedLM",xs]],["deberta",["DebertaForMaskedLM",et]],["deberta-v2",["DebertaV2ForMaskedLM",fs]],["mpnet",["MPNetForMaskedLM",zr]],["albert",["AlbertForMaskedLM",V]],["distilbert",["DistilBertForMaskedLM",Zs]],["roberta",["RobertaForMaskedLM",Rt]],["xlm",["XLMWithLMHeadModel",nn]],["xlm-roberta",["XLMRobertaForMaskedLM",Na]],["mobilebert",["MobileBertForMaskedLM",Bs]],["squeezebert",["SqueezeBertForMaskedLM",mr]]]),Eb=new Map([["bert",["BertForQuestionAnswering",We]],["roformer",["RoFormerForQuestionAnswering",ct]],["electra",["ElectraForQuestionAnswering",qr]],["convbert",["ConvBertForQuestionAnswering",Ds]],["camembert",["CamembertForQuestionAnswering",zs]],["deberta",["DebertaForQuestionAnswering",zt]],["deberta-v2",["DebertaV2ForQuestionAnswering",_s]],["mpnet",["MPNetForQuestionAnswering",Ar]],["albert",["AlbertForQuestionAnswering",F]],["distilbert",["DistilBertForQuestionAnswering",Ys]],["roberta",["RobertaForQuestionAnswering",er]],["xlm",["XLMForQuestionAnswering",Ba]],["xlm-roberta",["XLMRobertaForQuestionAnswering",Wi]],["mobilebert",["MobileBertForQuestionAnswering",Ir]],["squeezebert",["SqueezeBertForQuestionAnswering",Cn]]]),Ec=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",qi]],["idefics3",["Idefics3ForConditionalGeneration",Kn]],["smolvlm",["SmolVLMForConditionalGeneration",Hn]]]),Pb=new Map([["llava",["LlavaForConditionalGeneration",Gn]],["llava_onevision",["LlavaOnevisionForConditionalGeneration",qa]],["moondream1",["Moondream1ForConditionalGeneration",Qa]],["florence2",["Florence2ForConditionalGeneration",Qi]],["qwen2-vl",["Qwen2VLForConditionalGeneration",Oo]],["idefics3",["Idefics3ForConditionalGeneration",Kn]],["smolvlm",["SmolVLMForConditionalGeneration",Hn]],["paligemma",["PaliGemmaForConditionalGeneration",Ji]]]),Cb=new Map([["ultravox",["UltravoxModel",ob]]]),DT=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",qi]]]),Sb=new Map([["vit",["ViTForImageClassification",Ko]],["ijepa",["IJepaForImageClassification",qo]],["pvt",["PvtForImageClassification",cl]],["vit_msn",["ViTMSNForImageClassification",ml]],["fastvit",["FastViTForImageClassification",yl]],["mobilevit",["MobileViTForImageClassification",Tl]],["mobilevitv2",["MobileViTV2ForImageClassification",El]],["beit",["BeitForImageClassification",Il]],["deit",["DeiTForImageClassification",Ee]],["hiera",["HieraForImageClassification",ot]],["convnext",["ConvNextForImageClassification",vy]],["convnextv2",["ConvNextV2ForImageClassification",xy]],["dinov2",["Dinov2ForImageClassification",Py]],["dinov2_with_registers",["Dinov2WithRegistersForImageClassification",Sy]],["resnet",["ResNetForImageClassification",Fr]],["swin",["SwinForImageClassification",Yw]],["segformer",["SegformerForImageClassification",kM]],["efficientnet",["EfficientNetForImageClassification",DM]],["mobilenet_v1",["MobileNetV1ForImageClassification",zM]],["mobilenet_v2",["MobileNetV2ForImageClassification",NM]],["mobilenet_v3",["MobileNetV3ForImageClassification",UM]],["mobilenet_v4",["MobileNetV4ForImageClassification",KM]]]),$b=new Map([["detr",["DetrForObjectDetection",Fl]],["rt_detr",["RTDetrForObjectDetection",Ll]],["rt_detr_v2",["RTDetrV2ForObjectDetection",Bl]],["rf_detr",["RFDetrForObjectDetection",d]],["table-transformer",["TableTransformerForObjectDetection",I]],["yolos",["YolosForObjectDetection",Ay]]]),kb=new Map([["owlvit",["OwlViTForObjectDetection",Cl]],["owlv2",["Owlv2ForObjectDetection",$l]],["grounding-dino",["GroundingDinoForObjectDetection",ky]]]),Ei=new Map([["detr",["DetrForSegmentation",ia]],["clipseg",["CLIPSegForImageSegmentation",eo]]]),Ib=new Map([["segformer",["SegformerForSemanticSegmentation",IM]],["sapiens",["SapiensForSemanticSegmentation",oy]],["swin",["SwinForSemanticSegmentation",Zw]],["mobilenet_v1",["MobileNetV1ForSemanticSegmentation",BM]],["mobilenet_v2",["MobileNetV2ForSemanticSegmentation",jM]],["mobilenet_v3",["MobileNetV3ForSemanticSegmentation",WM]],["mobilenet_v4",["MobileNetV4ForSemanticSegmentation",HM]]]),Ab=new Map([["detr",["DetrForSegmentation",ia]],["maskformer",["MaskFormerForInstanceSegmentation",_y]]]),Fb=new Map([["sam",["SamModel",Dy]]]),Ob=new Map([["wav2vec2",["Wav2Vec2ForCTC",Vy]],["wav2vec2-bert",["Wav2Vec2BertForCTC",sM]],["unispeech",["UniSpeechForCTC",Xy]],["unispeech-sat",["UniSpeechSatForCTC",Zy]],["wavlm",["WavLMForCTC",dM]],["hubert",["HubertForCTC",oM]]]),Db=new Map([["wav2vec2",["Wav2Vec2ForSequenceClassification",Uy]],["wav2vec2-bert",["Wav2Vec2BertForSequenceClassification",nM]],["unispeech",["UniSpeechForSequenceClassification",Jy]],["unispeech-sat",["UniSpeechSatForSequenceClassification",eM]],["wavlm",["WavLMForSequenceClassification",uM]],["hubert",["HubertForSequenceClassification",aM]],["audio-spectrogram-transformer",["ASTForAudioClassification",Ua]]]),Lb=new Map([["wavlm",["WavLMForXVector",cM]]]),zb=new Map([["unispeech-sat",["UniSpeechSatForAudioFrameClassification",tM]],["wavlm",["WavLMForAudioFrameClassification",pM]],["wav2vec2",["Wav2Vec2ForAudioFrameClassification",Wy]],["pyannote",["PyAnnoteForAudioFrameClassification",Ky]]]),Bb=new Map([["vitmatte",["VitMatteForImageMatting",bl]]]),LT=new Map([["patchtst",["PatchTSTForPrediction",rb]],["patchtsmixer",["PatchTSMixerForPrediction",nb]]]),Rb=new Map([["swin2sr",["Swin2SRForImageSuperResolution",ty]]]),Nb=new Map([["dpt",["DPTForDepthEstimation",sy]],["depth_anything",["DepthAnythingForDepthEstimation",iy]],["glpn",["GLPNForDepthEstimation",wy]],["sapiens",["SapiensForDepthEstimation",ay]],["depth_pro",["DepthProForDepthEstimation",uy]],["metric3d",["Metric3DForDepthEstimation",py]],["metric3dv2",["Metric3Dv2ForDepthEstimation",fy]]]),jb=new Map([["sapiens",["SapiensForNormalEstimation",ly]]]),Vb=new Map([["vitpose",["VitPoseForPoseEstimation",Xo]]]),Ub=new Map([["clip",["CLIPVisionModelWithProjection",qn]],["siglip",["SiglipVisionModel",tl]],["jina_clip",["JinaCLIPVisionModel",ol]]]),Wb=[[kT,P.EncoderOnly],[IT,P.EncoderDecoder],[FT,P.DecoderOnly],[AT,P.AutoEncoder],[vb,P.EncoderOnly],[Tb,P.EncoderOnly],[Tc,P.Seq2Seq],[vc,P.Seq2Seq],[xc,P.DecoderOnly],[OT,P.MultiModality],[xb,P.EncoderOnly],[Eb,P.EncoderOnly],[Ec,P.Vision2Seq],[Pb,P.ImageTextToText],[Cb,P.AudioTextToText],[Sb,P.EncoderOnly],[Ei,P.EncoderOnly],[Ab,P.EncoderOnly],[Ib,P.EncoderOnly],[Bb,P.EncoderOnly],[LT,P.EncoderOnly],[Rb,P.EncoderOnly],[Nb,P.EncoderOnly],[jb,P.EncoderOnly],[Vb,P.EncoderOnly],[$b,P.EncoderOnly],[kb,P.EncoderOnly],[Fb,P.MaskGeneration],[Ob,P.EncoderOnly],[Db,P.EncoderOnly],[Mb,P.Seq2Seq],[bb,P.EncoderOnly],[Lb,P.EncoderOnly],[zb,P.EncoderOnly],[Ub,P.EncoderOnly]];for(const[b,S]of Wb)for(const[L,oe]of b.values())M.set(L,S),x.set(oe,L),w.set(L,oe);const zT=[["MusicgenForConditionalGeneration",yc,P.Musicgen],["Phi3VForCausalLM",Vs,P.Phi3V],["CLIPTextModelWithProjection",Ya,P.EncoderOnly],["SiglipTextModel",el,P.EncoderOnly],["JinaCLIPTextModel",il,P.EncoderOnly],["ClapTextModelWithProjection",CM,P.EncoderOnly],["ClapAudioModelWithProjection",SM,P.EncoderOnly],["DacEncoderModel",mb,P.EncoderOnly],["DacDecoderModel",_b,P.EncoderOnly],["MimiEncoderModel",ub,P.EncoderOnly],["MimiDecoderModel",cb,P.EncoderOnly],["SnacEncoderModel",wb,P.EncoderOnly],["SnacDecoderModel",yb,P.EncoderOnly]];for(const[b,S,L]of zT)M.set(b,L),x.set(S,b),w.set(b,S);const Gb=new Map([["modnet",Ei],["birefnet",Ei],["isnet",Ei],["ben",Ei]]);for(const[b,S]of Gb.entries())S.set(b,["PreTrainedModel",j]),M.set(b,P.EncoderOnly),x.set(j,b),w.set(b,j);class Pc extends It{}re(Pc,"MODEL_CLASS_MAPPINGS",Wb.map(S=>S[0])),re(Pc,"BASE_IF_FAIL",!0);class Kb extends It{}re(Kb,"MODEL_CLASS_MAPPINGS",[vb]);class Hb extends It{}re(Hb,"MODEL_CLASS_MAPPINGS",[Tb]);class qb extends It{}re(qb,"MODEL_CLASS_MAPPINGS",[Tc]);class Qb extends It{}re(Qb,"MODEL_CLASS_MAPPINGS",[vc]);class Xb extends It{}re(Xb,"MODEL_CLASS_MAPPINGS",[Mb]);class Jb extends It{}re(Jb,"MODEL_CLASS_MAPPINGS",[bb]);class Yb extends It{}re(Yb,"MODEL_CLASS_MAPPINGS",[xc]);class Zb extends It{}re(Zb,"MODEL_CLASS_MAPPINGS",[xb]);class e0 extends It{}re(e0,"MODEL_CLASS_MAPPINGS",[Eb]);class t0 extends It{}re(t0,"MODEL_CLASS_MAPPINGS",[Ec]);class r0 extends It{}re(r0,"MODEL_CLASS_MAPPINGS",[Sb]);class s0 extends It{}re(s0,"MODEL_CLASS_MAPPINGS",[Ei]);class n0 extends It{}re(n0,"MODEL_CLASS_MAPPINGS",[Ib]);class i0 extends It{}re(i0,"MODEL_CLASS_MAPPINGS",[Ab]);class o0 extends It{}re(o0,"MODEL_CLASS_MAPPINGS",[$b]);class a0 extends It{}re(a0,"MODEL_CLASS_MAPPINGS",[kb]);class l0 extends It{}re(l0,"MODEL_CLASS_MAPPINGS",[Fb]);class d0 extends It{}re(d0,"MODEL_CLASS_MAPPINGS",[Ob]);class u0 extends It{}re(u0,"MODEL_CLASS_MAPPINGS",[Db]);class c0 extends It{}re(c0,"MODEL_CLASS_MAPPINGS",[Lb]);class p0 extends It{}re(p0,"MODEL_CLASS_MAPPINGS",[zb]);class h0 extends It{}re(h0,"MODEL_CLASS_MAPPINGS",[DT]);class f0 extends It{}re(f0,"MODEL_CLASS_MAPPINGS",[Bb]);class m0 extends It{}re(m0,"MODEL_CLASS_MAPPINGS",[Rb]);class _0 extends It{}re(_0,"MODEL_CLASS_MAPPINGS",[Nb]);class g0 extends It{}re(g0,"MODEL_CLASS_MAPPINGS",[jb]);class w0 extends It{}re(w0,"MODEL_CLASS_MAPPINGS",[Vb]);class y0 extends It{}re(y0,"MODEL_CLASS_MAPPINGS",[Ub]);class M0 extends It{}re(M0,"MODEL_CLASS_MAPPINGS",[Pb]);class b0 extends It{}re(b0,"MODEL_CLASS_MAPPINGS",[Cb]);class BT extends fe{constructor({logits:S,past_key_values:L,encoder_outputs:oe,decoder_attentions:ge=null,cross_attentions:me=null}){super(),this.logits=S,this.past_key_values=L,this.encoder_outputs=oe,this.decoder_attentions=ge,this.cross_attentions=me}}class bt extends fe{constructor({logits:S,...L}){super(),this.logits=S;const oe=Object.values(L);oe.length>0&&(this.attentions=oe)}}class v0 extends fe{constructor({logits:S,embeddings:L}){super(),this.logits=S,this.embeddings=L}}class pr extends fe{constructor({logits:S}){super(),this.logits=S}}class wr extends fe{constructor({logits:S}){super(),this.logits=S}}class Pr extends fe{constructor({start_logits:S,end_logits:L}){super(),this.start_logits=S,this.end_logits=L}}class On extends fe{constructor({logits:S}){super(),this.logits=S}}class RT extends fe{constructor({logits:S,past_key_values:L}){super(),this.logits=S,this.past_key_values=L}}class T0 extends fe{constructor({alphas:S}){super(),this.alphas=S}}class x0 extends fe{constructor({waveform:S,spectrogram:L}){super(),this.waveform=S,this.spectrogram=L}}},"./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 i=t("./src/utils/audio.js");class n extends s.FeatureExtractor{constructor(a){super(a);const l=this.config.sampling_rate,u=(0,i.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(l/2),l,null,"kaldi",!0);for(let p=0;p{t.r(r),t.d(r,{AutoFeatureExtractor:()=>o});var s=t("./src/utils/constants.js"),i=t("./src/utils/hub.js");t("./src/base/feature_extraction_utils.js");var n=t("./src/models/feature_extractors.js");class o{static async from_pretrained(l,u={}){const p=await(0,i.getModelJSON)(l,s.FEATURE_EXTRACTOR_NAME,!0,u),c=p.feature_extractor_type,h=n[c];if(!h)throw new Error(`Unknown feature_extractor_type: '${c}'. Please report this at ${s.GITHUB_ISSUE_URL}.`);return new h(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"),i=t("./src/utils/hub.js"),n=t("./src/base/image_processors_utils.js"),o=t("./src/models/image_processors.js");class a{static async from_pretrained(u,p={}){const c=await(0,i.getModelJSON)(u,s.IMAGE_PROCESSOR_NAME,!0,p),h=c.image_processor_type??c.feature_extractor_type;let g=o[h];return g||(h!==void 0&&console.warn(`Image processor type '${h}' not found, assuming base ImageProcessor. Please report this at ${s.GITHUB_ISSUE_URL}.`),g=n.ImageProcessor),new g(c)}}},"./src/models/auto/processing_auto.js":(e,r,t)=>{t.r(r),t.d(r,{AutoProcessor:()=>u});var s=t("./src/utils/constants.js"),i=t("./src/utils/hub.js"),n=t("./src/base/processing_utils.js"),o=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(c,h={}){const g=await(0,i.getModelJSON)(c,s.IMAGE_PROCESSOR_NAME,!0,h),{image_processor_type:_,feature_extractor_type:E,processor_class:A}=g;if(A&&o[A])return o[A].from_pretrained(c,h);if(!_&&!E)throw new Error("No `image_processor_type` or `feature_extractor_type` found in the config.");const v={};if(_){const k=a[_];if(!k)throw new Error(`Unknown image_processor_type: '${_}'.`);v.image_processor=new k(g)}if(E){const k=a[E];if(k)v.image_processor=new k(g);else{const P=l[E];if(!P)throw new Error(`Unknown feature_extractor_type: '${E}'.`);v.feature_extractor=new P(g)}}const y={};return new n.Processor(y,v)}}},"./src/models/beit/image_processing_beit.js":(e,r,t)=>{t.r(r),t.d(r,{BeitFeatureExtractor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{}},"./src/models/bit/image_processing_bit.js":(e,r,t)=>{t.r(r),t.d(r,{BitImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{}},"./src/models/chinese_clip/image_processing_chinese_clip.js":(e,r,t)=>{t.r(r),t.d(r,{ChineseCLIPFeatureExtractor:()=>i});var s=t("./src/base/image_processors_utils.js");class i 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 i=t("./src/utils/audio.js");class n extends s.FeatureExtractor{constructor(a){super(a),this.mel_filters=(0,i.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,i.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,i.window_function)(this.config.fft_window_size,"hann")}async _get_input_mel(a,l,u,p){let c;const h=a.length-l;if(h>0)if(u==="rand_trunc"){const g=Math.floor(Math.random()*(h+1));a=a.subarray(g,g+l),c=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(h<0){let g=new Float64Array(l);if(g.set(a),p==="repeat")for(let _=a.length;_{t.r(r),t.d(r,{CLIPFeatureExtractor:()=>n,CLIPImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{}class n extends i{}},"./src/models/convnext/image_processing_convnext.js":(e,r,t)=>{t.r(r),t.d(r,{ConvNextFeatureExtractor:()=>n,ConvNextImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i 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),[c,h]=this.get_resize_output_image_size(a,{shortest_edge:p});a=await a.resize(c,h,{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 i{}},"./src/models/dac/feature_extraction_dac.js":(e,r,t)=>{t.r(r),t.d(r,{DacFeatureExtractor:()=>i});var s=t("./src/models/encodec/feature_extraction_encodec.js");class i extends s.EncodecFeatureExtractor{}},"./src/models/deit/image_processing_deit.js":(e,r,t)=>{t.r(r),t.d(r,{DeiTFeatureExtractor:()=>n,DeiTImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{}class n extends i{}},"./src/models/detr/image_processing_detr.js":(e,r,t)=>{t.r(r),t.d(r,{DetrFeatureExtractor:()=>o,DetrImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js"),i=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],c=(0,i.full)(p,1n);return{...u,pixel_mask:c}}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 o extends n{}},"./src/models/donut/image_processing_donut.js":(e,r,t)=>{t.r(r),t.d(r,{DonutFeatureExtractor:()=>n,DonutImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{pad_image(a,l,u,p={}){const[c,h,g]=l;let _=this.image_mean;Array.isArray(this.image_mean)||(_=new Array(g).fill(_));let E=this.image_std;Array.isArray(E)||(E=new Array(g).fill(_));const A=_.map((v,y)=>-v/E[y]);return super.pad_image(a,l,u,{center:!0,constant_values:A,...p})}}class n extends i{}},"./src/models/dpt/image_processing_dpt.js":(e,r,t)=>{t.r(r),t.d(r,{DPTFeatureExtractor:()=>n,DPTImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{}class n extends i{}},"./src/models/efficientnet/image_processing_efficientnet.js":(e,r,t)=>{t.r(r),t.d(r,{EfficientNetImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{constructor(o){super(o),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"),i=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 i.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:()=>o.DacFeatureExtractor,EncodecFeatureExtractor:()=>i.EncodecFeatureExtractor,ImageFeatureExtractor:()=>E.ImageProcessor,MoonshineFeatureExtractor:()=>a.MoonshineFeatureExtractor,PyAnnoteFeatureExtractor:()=>l.PyAnnoteFeatureExtractor,SeamlessM4TFeatureExtractor:()=>u.SeamlessM4TFeatureExtractor,SnacFeatureExtractor:()=>p.SnacFeatureExtractor,SpeechT5FeatureExtractor:()=>c.SpeechT5FeatureExtractor,Wav2Vec2FeatureExtractor:()=>h.Wav2Vec2FeatureExtractor,WeSpeakerFeatureExtractor:()=>g.WeSpeakerFeatureExtractor,WhisperFeatureExtractor:()=>_.WhisperFeatureExtractor});var s=t("./src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js"),i=t("./src/models/encodec/feature_extraction_encodec.js"),n=t("./src/models/clap/feature_extraction_clap.js"),o=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"),c=t("./src/models/speecht5/feature_extraction_speecht5.js"),h=t("./src/models/wav2vec2/feature_extraction_wav2vec2.js"),g=t("./src/models/wespeaker/feature_extraction_wespeaker.js"),_=t("./src/models/whisper/feature_extraction_whisper.js"),E=t("./src/base/image_processors_utils.js")},"./src/models/florence2/processing_florence2.js":(e,r,t)=>{t.r(r),t.d(r,{Florence2Processor:()=>o});var s=t("./src/base/processing_utils.js"),i=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");class o extends s.Processor{constructor(l,u){super(l,u);const{tasks_answer_post_processing_type:p,task_prompts_without_inputs:c,task_prompts_with_input:h}=this.image_processor.config;this.tasks_answer_post_processing_type=new Map(Object.entries(p??{})),this.task_prompts_without_inputs=new Map(Object.entries(c??{})),this.task_prompts_with_input=new Map(Object.entries(h??{})),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[c,h]of this.task_prompts_with_input)if(p.includes(c)){u.push(h.replaceAll("{input}",p).replaceAll(c,""));break}u.length!==l.length&&u.push(p)}return u}post_process_generation(l,u,p){const c=this.tasks_answer_post_processing_type.get(u)??"pure_text";l=l.replaceAll("","").replaceAll("","");let h;switch(c){case"pure_text":h=l;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":const g=c==="ocr"?"quad_boxes":"bboxes",_=l.matchAll(this.regexes[g]),E=[],A=[];for(const[v,y,...k]of _)E.push(y?y.trim():E.at(-1)??""),A.push(k.map((P,M)=>(Number(P)+.5)/this.size_per_bin*p[M%2]));h={labels:E,[g]:A};break;default:throw new Error(`Task "${u}" (of type "${c}") not yet implemented.`)}return{[u]:h}}async _call(l,u=null,p={}){if(!l&&!u)throw new Error("Either text or images must be provided");const c=await this.image_processor(l,p),h=u?this.tokenizer(u,p):{};return{...c,...h}}}re(o,"tokenizer_class",n.AutoTokenizer),re(o,"image_processor_class",i.AutoImageProcessor)},"./src/models/glpn/image_processing_glpn.js":(e,r,t)=>{t.r(r),t.d(r,{GLPNFeatureExtractor:()=>i});var s=t("./src/base/image_processors_utils.js");class i 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"),i=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,i.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"),i=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js"),o=t("./src/base/image_processors_utils.js");function a(u,p){const h=u.dims.at(-1)-1,g=u.tolist();g.fill(!1,0,1),g.fill(!1,h);const _=p.tolist();return g.map((E,A)=>E?A:null).filter(E=>E!==null).map(E=>_[E])}class l extends s.Processor{async _call(p,c,h={}){const g=p?await this.image_processor(p,h):{};return{...c?this.tokenizer(c,h):{},...g}}post_process_grounded_object_detection(p,c,{box_threshold:h=.25,text_threshold:g=.25,target_sizes:_=null}={}){const{logits:E,pred_boxes:A}=p,v=E.dims[0];if(_!==null&&_.length!==v)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const y=E.dims.at(1),k=E.sigmoid(),P=k.max(-1).tolist(),M=A.tolist().map(x=>x.map($=>(0,o.center_to_corners_format)($))),w=[];for(let x=0;xU.map((Z,H)=>Z*$[(H+1)%2])));const z=P[x],R=[],Q=[],q=[];for(let U=0;U{t.r(r),t.d(r,{Idefics3ImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js"),i=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 c=p/u;return p>=u?(p=Math.ceil(p/l)*l,u=Math.floor(p/c),u=Math.ceil(u/l)*l):(u=Math.ceil(u/l)*l,p=Math.floor(u*c),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 c=[],h=[],g=[];const _=[],E=[];for(const x of p){let $=await Promise.all(x.map(Q=>this.preprocess(Q)));_.push(...$.map(Q=>Q.original_size)),E.push(...$.map(Q=>Q.reshaped_input_size)),$.forEach(Q=>Q.pixel_values.unsqueeze_(0));const{longest_edge:z}=this.max_image_size;let R;if(l??this.do_image_splitting){let Q=new Array($.length),q=new Array($.length);R=await Promise.all($.map(async(U,Z)=>{const H=this.get_resize_for_vision_encoder(U.pixel_values,z),J=await(0,i.interpolate_4d)(U.pixel_values,{size:[H.height,H.width]}),{frames:ie,num_splits_h:ae,num_splits_w:ue}=await this.split_image(J,this.max_image_size);return Q[Z]=ae,q[Z]=ue,(0,i.cat)(ie,0)})),h.push(Q),g.push(q)}else{const Q=[z,z];R=await Promise.all($.map(q=>(0,i.interpolate_4d)(q.pixel_values,{size:Q}))),h.push(new Array($.length).fill(0)),g.push(new Array($.length).fill(0))}c.push((0,i.cat)(R,0))}const A=c.length,[v,y,k,P]=c[0].dims;let M,w;if(A===1)M=c[0].unsqueeze_(0),w=(0,i.full)([A,v,k,P],!0);else{const x=Math.max(...c.map(R=>R.dims.at(0)));w=(0,i.full)([A,x,k,P],!0);const $=w.data,z=x*k*P;for(let R=0;Ru||g>p){_=Math.ceil(h/u),E=Math.ceil(g/p);const A=Math.ceil(h/_),v=Math.ceil(g/E);for(let P=0;P<_;++P)for(let M=0;M{t.r(r),t.d(r,{Idefics3Processor:()=>p});var s=t("./src/base/processing_utils.js"),i=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");t("./src/utils/image.js");var o=t("./src/utils/core.js");function a(c,h,g,_,E,A){let v="";for(let y=0;y`+E.repeat(c);v+=` +`}return v+=` +${_}${A}`+E.repeat(c)+`${_}`,v}function l(c,h,g,_){return`${h}${_}`+g.repeat(c)+`${h}`}function u(c,h,g,_,E,A){return c===0&&h===0?l(g,_,E,A):a(g,c,h,_,E,A)}class p extends s.Processor{constructor(){super(...arguments);re(this,"fake_image_token","");re(this,"image_token","");re(this,"global_img_token","")}async _call(g,_=null,E={}){E.return_row_col_info??(E.return_row_col_info=!0);let A;_&&(A=await this.image_processor(_,E)),Array.isArray(g)||(g=[g]);const v=A.rows??[new Array(g.length).fill(0)],y=A.cols??[new Array(g.length).fill(0)],k=this.config.image_seq_len,P=[],M=[];for(let x=0;xu(Z,R[H],k,this.fake_image_token,this.image_token,this.global_img_token)),q=$.split(this.image_token);if(q.length===0)throw new Error("The image token should be present in the text.");let U=q[0];for(let Z=0;Z{t.r(r),t.d(r,{BeitFeatureExtractor:()=>s.BeitFeatureExtractor,BitImageProcessor:()=>i.BitImageProcessor,CLIPFeatureExtractor:()=>o.CLIPFeatureExtractor,CLIPImageProcessor:()=>o.CLIPImageProcessor,ChineseCLIPFeatureExtractor:()=>n.ChineseCLIPFeatureExtractor,ConvNextFeatureExtractor:()=>a.ConvNextFeatureExtractor,ConvNextImageProcessor:()=>a.ConvNextImageProcessor,DPTFeatureExtractor:()=>c.DPTFeatureExtractor,DPTImageProcessor:()=>c.DPTImageProcessor,DeiTFeatureExtractor:()=>l.DeiTFeatureExtractor,DeiTImageProcessor:()=>l.DeiTImageProcessor,DetrFeatureExtractor:()=>u.DetrFeatureExtractor,DetrImageProcessor:()=>u.DetrImageProcessor,DonutFeatureExtractor:()=>p.DonutFeatureExtractor,DonutImageProcessor:()=>p.DonutImageProcessor,EfficientNetImageProcessor:()=>h.EfficientNetImageProcessor,GLPNFeatureExtractor:()=>g.GLPNFeatureExtractor,GroundingDinoImageProcessor:()=>_.GroundingDinoImageProcessor,Idefics3ImageProcessor:()=>E.Idefics3ImageProcessor,JinaCLIPImageProcessor:()=>v.JinaCLIPImageProcessor,LlavaOnevisionImageProcessor:()=>y.LlavaOnevisionImageProcessor,Mask2FormerImageProcessor:()=>k.Mask2FormerImageProcessor,MaskFormerFeatureExtractor:()=>P.MaskFormerFeatureExtractor,MaskFormerImageProcessor:()=>P.MaskFormerImageProcessor,MobileNetV1FeatureExtractor:()=>M.MobileNetV1FeatureExtractor,MobileNetV1ImageProcessor:()=>M.MobileNetV1ImageProcessor,MobileNetV2FeatureExtractor:()=>w.MobileNetV2FeatureExtractor,MobileNetV2ImageProcessor:()=>w.MobileNetV2ImageProcessor,MobileNetV3FeatureExtractor:()=>x.MobileNetV3FeatureExtractor,MobileNetV3ImageProcessor:()=>x.MobileNetV3ImageProcessor,MobileNetV4FeatureExtractor:()=>$.MobileNetV4FeatureExtractor,MobileNetV4ImageProcessor:()=>$.MobileNetV4ImageProcessor,MobileViTFeatureExtractor:()=>z.MobileViTFeatureExtractor,MobileViTImageProcessor:()=>z.MobileViTImageProcessor,NougatImageProcessor:()=>R.NougatImageProcessor,OwlViTFeatureExtractor:()=>q.OwlViTFeatureExtractor,OwlViTImageProcessor:()=>q.OwlViTImageProcessor,Owlv2ImageProcessor:()=>Q.Owlv2ImageProcessor,Phi3VImageProcessor:()=>U.Phi3VImageProcessor,PvtImageProcessor:()=>Z.PvtImageProcessor,Qwen2VLImageProcessor:()=>H.Qwen2VLImageProcessor,RTDetrImageProcessor:()=>J.RTDetrImageProcessor,SamImageProcessor:()=>ie.SamImageProcessor,SegformerFeatureExtractor:()=>ae.SegformerFeatureExtractor,SegformerImageProcessor:()=>ae.SegformerImageProcessor,SiglipImageProcessor:()=>ue.SiglipImageProcessor,SmolVLMImageProcessor:()=>he.SmolVLMImageProcessor,Swin2SRImageProcessor:()=>N.Swin2SRImageProcessor,VLMImageProcessor:()=>A.VLMImageProcessor,ViTFeatureExtractor:()=>O.ViTFeatureExtractor,ViTImageProcessor:()=>O.ViTImageProcessor,VitMatteImageProcessor:()=>G.VitMatteImageProcessor,VitPoseImageProcessor:()=>se.VitPoseImageProcessor,YolosFeatureExtractor:()=>X.YolosFeatureExtractor,YolosImageProcessor:()=>X.YolosImageProcessor});var s=t("./src/models/beit/image_processing_beit.js"),i=t("./src/models/bit/image_processing_bit.js"),n=t("./src/models/chinese_clip/image_processing_chinese_clip.js"),o=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"),c=t("./src/models/dpt/image_processing_dpt.js"),h=t("./src/models/efficientnet/image_processing_efficientnet.js"),g=t("./src/models/glpn/image_processing_glpn.js"),_=t("./src/models/grounding_dino/image_processing_grounding_dino.js"),E=t("./src/models/idefics3/image_processing_idefics3.js"),A=t("./src/models/janus/image_processing_janus.js"),v=t("./src/models/jina_clip/image_processing_jina_clip.js"),y=t("./src/models/llava_onevision/image_processing_llava_onevision.js"),k=t("./src/models/mask2former/image_processing_mask2former.js"),P=t("./src/models/maskformer/image_processing_maskformer.js"),M=t("./src/models/mobilenet_v1/image_processing_mobilenet_v1.js"),w=t("./src/models/mobilenet_v2/image_processing_mobilenet_v2.js"),x=t("./src/models/mobilenet_v3/image_processing_mobilenet_v3.js"),$=t("./src/models/mobilenet_v4/image_processing_mobilenet_v4.js"),z=t("./src/models/mobilevit/image_processing_mobilevit.js"),R=t("./src/models/nougat/image_processing_nougat.js"),Q=t("./src/models/owlv2/image_processing_owlv2.js"),q=t("./src/models/owlvit/image_processing_owlvit.js"),U=t("./src/models/phi3_v/image_processing_phi3_v.js"),Z=t("./src/models/pvt/image_processing_pvt.js"),H=t("./src/models/qwen2_vl/image_processing_qwen2_vl.js"),J=t("./src/models/rt_detr/image_processing_rt_detr.js"),ie=t("./src/models/sam/image_processing_sam.js"),ae=t("./src/models/segformer/image_processing_segformer.js"),ue=t("./src/models/siglip/image_processing_siglip.js"),he=t("./src/models/smolvlm/image_processing_smolvlm.js"),N=t("./src/models/swin2sr/image_processing_swin2sr.js"),O=t("./src/models/vit/image_processing_vit.js"),G=t("./src/models/vitmatte/image_processing_vitmatte.js"),se=t("./src/models/vitpose/image_processing_vitpose.js"),X=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:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{constructor(o){super({do_pad:!0,pad_size:{width:o.image_size,height:o.image_size},...o}),this.constant_values=this.config.background_color.map(a=>a*this.rescale_factor)}pad_image(o,a,l,u){return super.pad_image(o,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"),i=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js"),o=t("./src/utils/core.js"),a=t("./src/utils/tensor.js"),l=t("./src/utils/image.js");class u extends s.Processor{constructor(c,h){super(c,h),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(c,{images:h=null,chat_template:g="default"}={}){h?Array.isArray(h)||(h=[h]):h=await Promise.all(c.filter(R=>R.images).flatMap(R=>R.images).map(R=>l.RawImage.read(R)));const _=this.tokenizer,E=_.apply_chat_template(c,{tokenize:!1,add_generation_prompt:!0,chat_template:g}),A=R=>_.encode(R,{add_special_tokens:!1}),v=E.split(this.image_tag),y=v.length-1;if(h.length!==y)throw new Error(`Number of images provided (${h.length}) does not match number of "${this.image_tag}" image tags (${y})`);const[k,P,M]=_.model.convert_tokens_to_ids([this.image_tag,this.image_start_tag,this.image_end_tag]);let w=A(v[0]),x=new Array(w.length).fill(!1);for(let R=1;R0){const R=await this.image_processor(h);return R.pixel_values.unsqueeze_(0),{...z,...R}}return z}}re(u,"image_processor_class",i.AutoImageProcessor),re(u,"tokenizer_class",n.AutoTokenizer),re(u,"uses_processor_config",!0)},"./src/models/jina_clip/image_processing_jina_clip.js":(e,r,t)=>{t.r(r),t.d(r,{JinaCLIPImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{constructor(o){const{resize_mode:a,fill_color:l,interpolation:u,size:p,...c}=o,h=a==="squash"?{width:p,height:p}:a==="shortest"?{shortest_edge:p}:{longest_edge:p},g=u==="bicubic"?3:2;super({...c,size:h,resample:g,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:()=>o});var s=t("./src/base/processing_utils.js"),i=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");class o extends s.Processor{async _call(l=null,u=null,p={}){if(!l&&!u)throw new Error("Either text or images must be provided");const c=l?this.tokenizer(l,p):{},h=u?await this.image_processor(u,p):{};return{...c,...h}}}re(o,"tokenizer_class",n.AutoTokenizer),re(o,"image_processor_class",i.AutoImageProcessor)},"./src/models/llava_onevision/image_processing_llava_onevision.js":(e,r,t)=>{t.r(r),t.d(r,{LlavaOnevisionImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{}},"./src/models/mask2former/image_processing_mask2former.js":(e,r,t)=>{t.r(r),t.d(r,{Mask2FormerImageProcessor:()=>i});var s=t("./src/models/maskformer/image_processing_maskformer.js");class i extends s.MaskFormerImageProcessor{}},"./src/models/maskformer/image_processing_maskformer.js":(e,r,t)=>{t.r(r),t.d(r,{MaskFormerFeatureExtractor:()=>n,MaskFormerImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i 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 i{}},"./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"),i=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js"),o=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,c){if(!a.hasOwnProperty(c))throw new Error(`Format ${c} is not supported.`);const[h,g]=a[c],_=this[h].bind(this),[E,A]=p.dims,v=[],y=[],k=p.tolist();for(let M=0;M0?$.reduce((R,Q)=>R*Q,1):0;y.push(x),v.push(z)}return[_(y),v]}char_decode(p){return this.char_tokenizer.batch_decode(p).map(c=>c.replaceAll(" ",""))}bpe_decode(p){return this.bpe_tokenizer.batch_decode(p)}wp_decode(p){return this.wp_tokenizer.batch_decode(p).map(c=>c.replaceAll(" ",""))}batch_decode([p,c,h]){const[g,_]=this._decode_helper(p,"char"),[E,A]=this._decode_helper(c,"bpe"),[v,y]=this._decode_helper(h,"wp"),k=[],P=[];for(let M=0;M{t.r(r),t.d(r,{MobileNetV1FeatureExtractor:()=>n,MobileNetV1ImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{}class n extends i{}},"./src/models/mobilenet_v2/image_processing_mobilenet_v2.js":(e,r,t)=>{t.r(r),t.d(r,{MobileNetV2FeatureExtractor:()=>n,MobileNetV2ImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{}class n extends i{}},"./src/models/mobilenet_v3/image_processing_mobilenet_v3.js":(e,r,t)=>{t.r(r),t.d(r,{MobileNetV3FeatureExtractor:()=>n,MobileNetV3ImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{}class n extends i{}},"./src/models/mobilenet_v4/image_processing_mobilenet_v4.js":(e,r,t)=>{t.r(r),t.d(r,{MobileNetV4FeatureExtractor:()=>n,MobileNetV4ImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{}class n extends i{}},"./src/models/mobilevit/image_processing_mobilevit.js":(e,r,t)=>{t.r(r),t.d(r,{MobileViTFeatureExtractor:()=>n,MobileViTImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{}class n extends i{}},"./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"),i=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 i.Tensor("float32",a,l)}}}},"./src/models/moonshine/processing_moonshine.js":(e,r,t)=>{t.r(r),t.d(r,{MoonshineProcessor:()=>o});var s=t("./src/models/auto/feature_extraction_auto.js"),i=t("./src/tokenizers.js"),n=t("./src/base/processing_utils.js");class o extends n.Processor{async _call(l){return await this.feature_extractor(l)}}re(o,"tokenizer_class",i.AutoTokenizer),re(o,"feature_extractor_class",s.AutoFeatureExtractor)},"./src/models/nougat/image_processing_nougat.js":(e,r,t)=>{t.r(r),t.d(r,{NougatImageProcessor:()=>i});var s=t("./src/models/donut/image_processing_donut.js");class i extends s.DonutImageProcessor{}},"./src/models/owlv2/image_processing_owlv2.js":(e,r,t)=>{t.r(r),t.d(r,{Owlv2ImageProcessor:()=>i});var s=t("./src/models/owlvit/image_processing_owlvit.js");class i extends s.OwlViTImageProcessor{}},"./src/models/owlvit/image_processing_owlvit.js":(e,r,t)=>{t.r(r),t.d(r,{OwlViTFeatureExtractor:()=>n,OwlViTImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{post_process_object_detection(...a){return(0,s.post_process_object_detection)(...a)}}class n extends i{}},"./src/models/owlvit/processing_owlvit.js":(e,r,t)=>{t.r(r),t.d(r,{OwlViTProcessor:()=>o});var s=t("./src/base/processing_utils.js"),i=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");class o extends s.Processor{}re(o,"tokenizer_class",n.AutoTokenizer),re(o,"image_processor_class",i.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"),i=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");const o="";function a(u,p,c,h,g){return`${h.repeat(c*g)}${p}${u} +`}class l extends s.Processor{async _call(p,c=null,h={}){c||(console.warn("You are using PaliGemma without a text prefix. It will perform as a picture-captioning model."),c=""),Array.isArray(p)||(p=[p]),Array.isArray(c)||(c=[c]);const g=this.tokenizer.bos_token,_=this.image_processor.config.image_seq_length;let E;c.some(y=>y.includes(o))?E=c.map(y=>{const k=y.replaceAll(o,o.repeat(_)),P=k.lastIndexOf(o),M=P===-1?0:P+o.length;return k.slice(0,M)+g+k.slice(M)+` +`}):(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."),E=c.map(y=>a(y,g,_,o,p.length)));const A=this.tokenizer(E,h);return{...await this.image_processor(p,h),...A}}}re(l,"tokenizer_class",n.AutoTokenizer),re(l,"image_processor_class",i.AutoImageProcessor),re(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"),i=t("./src/utils/tensor.js");const n=336,o=[2,3],{ceil:a,floor:l,sqrt:u}=Math;class p extends s.ImageProcessor{constructor(h){super({...h,do_normalize:!0,do_pad:!0,pad_size:"custom",do_convert_rgb:!0,do_resize:!0}),this._num_crops=h.num_crops}calc_num_image_tokens_from_image_size(h,g){const{num_img_tokens:_}=this.config;return l((l(g/n)*l(h/n)+1)*_+1+(l(g/n)+1)*u(_))}get_resize_output_image_size(h,g){const _=this._num_crops,[E,A]=h.size;let v=E/A,y=1;for(;y*Math.ceil(y/v)<=_;)y+=1;y-=1;const k=Math.floor(y*336),P=Math.floor(k/v);return[k,P]}pad_image(h,g,_,E={}){const[A,v]=g,y=n*a(A/n),k=n*a(v/n),P=[1,1,1].map((M,w)=>(M-this.image_mean[w])/this.image_std[w]);return super.pad_image(h,g,{width:k,height:y},{center:!0,constant_values:P,...E})}async _call(h,{num_crops:g=null}={}){if(this._num_crops=g??(g=this.config.num_crops),g<4||u(g)%1!==0)throw new Error("num_crops must be a square number >= 4");Array.isArray(h)||(h=[h]);const _=h.length,E=await Promise.all(h.map(x=>this.preprocess(x))),A=E.map(x=>x.original_size),v=E.map(x=>x.reshaped_input_size),y=[];for(const{pixel_values:x}of E){x.unsqueeze_(0);const[$,z]=x.dims.slice(-2),R=await(0,i.interpolate_4d)(x,{size:[n,n],mode:"bicubic"});if(g>0){const Q=[],q=u(g),U=l(z/q),Z=l($/q);for(let J=0;Jx.map($=>n*a($/n))),M=new i.Tensor("int64",P.flat(),[_,2]),w=P.map(([x,$])=>this.calc_num_image_tokens_from_image_size($,x));return{pixel_values:k,original_sizes:A,reshaped_input_sizes:v,image_sizes:M,num_img_tokens:w}}}},"./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"),i=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");t("./src/utils/image.js");const o="<|image|>",a=/<\|image_\d+\|>/g;class l extends s.Processor{async _call(p,c=null,{padding:h=!0,truncation:g=!0,num_crops:_=null}={}){Array.isArray(p)||(p=[p]);let E,A;if(c){A=await this.image_processor(c,{num_crops:_});const{num_img_tokens:v}=A,y=p.map((P,M)=>P.split(a).join(o.repeat(v[M])));E=this.tokenizer(y,{padding:h,truncation:g});const k=this.tokenizer.model.convert_tokens_to_ids([o])[0];E.input_ids.map_(P=>P==k?-P:P)}else E=this.tokenizer(p);return{...E,...A}}}re(l,"image_processor_class",i.AutoImageProcessor),re(l,"tokenizer_class",n.AutoTokenizer)},"./src/models/processors.js":(e,r,t)=>{t.r(r),t.d(r,{Florence2Processor:()=>s.Florence2Processor,GroundingDinoProcessor:()=>i.GroundingDinoProcessor,Idefics3Processor:()=>n.Idefics3Processor,JinaCLIPProcessor:()=>a.JinaCLIPProcessor,MgpstrProcessor:()=>l.MgpstrProcessor,MoonshineProcessor:()=>u.MoonshineProcessor,OwlViTProcessor:()=>p.OwlViTProcessor,PaliGemmaProcessor:()=>h.PaliGemmaProcessor,Phi3VProcessor:()=>c.Phi3VProcessor,PyAnnoteProcessor:()=>g.PyAnnoteProcessor,Qwen2VLProcessor:()=>_.Qwen2VLProcessor,SamProcessor:()=>E.SamProcessor,SmolVLMProcessor:()=>A.SmolVLMProcessor,SpeechT5Processor:()=>v.SpeechT5Processor,UltravoxProcessor:()=>y.UltravoxProcessor,VLChatProcessor:()=>o.VLChatProcessor,Wav2Vec2Processor:()=>k.Wav2Vec2Processor,Wav2Vec2ProcessorWithLM:()=>P.Wav2Vec2ProcessorWithLM,WhisperProcessor:()=>M.WhisperProcessor});var s=t("./src/models/florence2/processing_florence2.js"),i=t("./src/models/grounding_dino/processing_grounding_dino.js"),n=t("./src/models/idefics3/processing_idefics3.js"),o=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"),c=t("./src/models/phi3_v/processing_phi3_v.js"),h=t("./src/models/paligemma/processing_paligemma.js"),g=t("./src/models/pyannote/processing_pyannote.js"),_=t("./src/models/qwen2_vl/processing_qwen2_vl.js"),E=t("./src/models/sam/processing_sam.js"),A=t("./src/models/smolvlm/processing_smolvlm.js"),v=t("./src/models/speecht5/processing_speecht5.js"),y=t("./src/models/ultravox/processing_ultravox.js"),k=t("./src/models/wav2vec2/processing_wav2vec2.js"),P=t("./src/models/wav2vec2_with_lm/processing_wav2vec2_with_lm.js"),M=t("./src/models/whisper/processing_whisper.js")},"./src/models/pvt/image_processing_pvt.js":(e,r,t)=>{t.r(r),t.d(r,{PvtImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{}},"./src/models/pyannote/feature_extraction_pyannote.js":(e,r,t)=>{t.r(r),t.d(r,{PyAnnoteFeatureExtractor:()=>o});var s=t("./src/base/feature_extraction_utils.js"),i=t("./src/utils/tensor.js"),n=t("./src/utils/maths.js");class o 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 i.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,c=[];for(const h of l.tolist()){const g=[];let _=-1;for(let E=0;E({id:E,start:A*p,end:v*p,confidence:y/(v-A)})))}return c}}},"./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"),i=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}}re(n,"feature_extractor_class",i.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"),i=t("./src/utils/tensor.js");class n extends s.ImageProcessor{async _call(a,...l){const{pixel_values:u,original_sizes:p,reshaped_input_sizes:c}=await super._call(a,...l);let h=u;const{temporal_patch_size:g,merge_size:_,patch_size:E}=this.config;h.dims[0]===1&&(h=(0,i.cat)(Array.from({length:g},()=>h),0));const A=h.dims[0]/g,v=h.dims[1],y=Math.floor(h.dims[2]/E),k=Math.floor(h.dims[3]/E),P=h.view(A,g,v,Math.floor(y/_),_,E,Math.floor(k/_),_,E).permute(0,3,6,4,7,2,1,5,8).view(A*y*k,v*g*E*E),M=new i.Tensor("int64",[A,y,k],[1,3]);return{pixel_values:P,image_grid_thw:M,original_sizes:p,reshaped_input_sizes:c}}}},"./src/models/qwen2_vl/processing_qwen2_vl.js":(e,r,t)=>{t.r(r),t.d(r,{Qwen2VLProcessor:()=>o});var s=t("./src/base/processing_utils.js"),i=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");t("./src/utils/image.js");class o extends s.Processor{async _call(l,u=null,...p){Array.isArray(l)||(l=[l]);let c,h;if(u&&(c=await this.image_processor(u),h=c.image_grid_thw),h){let _=this.image_processor.config.merge_size**2,E=0;const A=h.tolist();l=l.map(v=>{for(;v.includes("<|image_pad|>");){const y=Number(A[E++].reduce((k,P)=>k*P,1n));v=v.replace("<|image_pad|>","<|placeholder|>".repeat(Math.floor(y/_)))}return v.replaceAll("<|placeholder|>","<|image_pad|>")})}return{...this.tokenizer(l),...c}}}re(o,"image_processor_class",i.AutoImageProcessor),re(o,"tokenizer_class",n.AutoTokenizer)},"./src/models/rt_detr/image_processing_rt_detr.js":(e,r,t)=>{t.r(r),t.d(r,{RTDetrImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{post_process_object_detection(...o){return(0,s.post_process_object_detection)(...o)}}},"./src/models/sam/image_processing_sam.js":(e,r,t)=>{t.r(r),t.d(r,{SamImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js"),i=t("./src/utils/core.js"),n=t("./src/utils/tensor.js");class o extends s.ImageProcessor{reshape_input_points(l,u,p,c=!1){l=structuredClone(l);let h=(0,i.calculateDimensions)(l);if(h.length===3)c||(h=[1,...h]),l=[l];else if(h.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 g=0;gc!==u.dims[h]))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:c=null}={}){const h=await super._call(l);if(u&&(h.input_points=this.reshape_input_points(u,h.original_sizes,h.reshaped_input_sizes)),p){if(!h.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");h.input_labels=this.add_input_labels(p,h.input_points)}return c&&(h.input_boxes=this.reshape_input_points(c,h.original_sizes,h.reshaped_input_sizes,!0)),h}async post_process_masks(l,u,p,{mask_threshold:c=0,binarize:h=!0,pad_size:g=null}={}){const _=[];g=g??this.pad_size;const E=[g.height,g.width];for(let A=0;Ac&&(M[w]=1);k=new n.Tensor("bool",M,k.dims)}_.push(k)}return _}generate_crop_boxes(l,u,{crop_n_layers:p=0,overlap_ratio:c=512/1500,points_per_crop:h=32,crop_n_points_downscale_factor:g=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"),i=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)}}re(n,"image_processor_class",i.AutoImageProcessor)},"./src/models/seamless_m4t/feature_extraction_seamless_m4t.js":(e,r,t)=>{t.r(r),t.d(r,{SeamlessM4TFeatureExtractor:()=>o});var s=t("./src/base/feature_extraction_utils.js"),i=t("./src/utils/tensor.js"),n=t("./src/utils/audio.js");class o extends s.FeatureExtractor{constructor(l){super(l);const u=this.config.sampling_rate,p=(0,n.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(u/2),u,null,"kaldi",!0);for(let c=0;cp*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:c=!0,return_attention_mask:h=!0}={}){(0,s.validate_audio_inputs)(l,"SeamlessM4TFeatureExtractor");let g=await this._extract_fbank_features(l,this.config.max_length);if(c){const[M,w]=g.dims,x=g.data;for(let $=0;$0){const z=new Float32Array(w*(M+$));z.set(x),z.fill(this.config.padding_value,x.length);const R=M+$;g=new i.Tensor(g.type,z,[R,w]),h&&(_=new i.Tensor("int64",new BigInt64Array(R),[1,R]),_.data.fill(1n,0,M))}}const[E,A]=g.dims,v=this.config.stride;if(E%v!==0)throw new Error(`The number of frames (${E}) must be a multiple of the stride (${v}).`);const k=g.view(1,Math.floor(E/v),A*v),P={input_features:k};if(h){const M=k.dims[1],w=new BigInt64Array(M);if(_){const x=_.data;for(let $=1,z=0;${t.r(r),t.d(r,{SegformerFeatureExtractor:()=>n,SegformerImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{post_process_semantic_segmentation(...a){return(0,s.post_process_semantic_segmentation)(...a)}}class n extends i{}},"./src/models/siglip/image_processing_siglip.js":(e,r,t)=>{t.r(r),t.d(r,{SiglipImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i 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:()=>i});var s=t("./src/models/dac/feature_extraction_dac.js");class i extends s.DacFeatureExtractor{}},"./src/models/speecht5/feature_extraction_speecht5.js":(e,r,t)=>{t.r(r),t.d(r,{SpeechT5FeatureExtractor:()=>i});var s=t("./src/base/feature_extraction_utils.js");class i extends s.FeatureExtractor{}},"./src/models/speecht5/processing_speecht5.js":(e,r,t)=>{t.r(r),t.d(r,{SpeechT5Processor:()=>o});var s=t("./src/base/processing_utils.js"),i=t("./src/tokenizers.js"),n=t("./src/models/auto/feature_extraction_auto.js");class o extends s.Processor{async _call(l){return await this.feature_extractor(l)}}re(o,"tokenizer_class",i.AutoTokenizer),re(o,"feature_extractor_class",n.AutoFeatureExtractor)},"./src/models/swin2sr/image_processing_swin2sr.js":(e,r,t)=>{t.r(r),t.d(r,{Swin2SRImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{pad_image(o,a,l,u={}){const[p,c,h]=a;return super.pad_image(o,a,{width:c+(l-c%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:()=>o});var s=t("./src/models/auto/feature_extraction_auto.js"),i=t("./src/tokenizers.js"),n=t("./src/base/processing_utils.js");class o extends n.Processor{async _call(l,u=null,p={}){if(Array.isArray(l))throw new Error("Batched inputs are not supported yet.");let c={};if(u){const g=u.length,{input_features:_}=await this.feature_extractor(u,{...p,max_length:g}),E=Math.round(g/this.config.encoder_ds_factor+1e-4),A=1+Math.ceil(E/this.config.stack_factor);c.audio_token_len=[A],c.audio_values=_;const v=this.config.audio_placeholder;if(!l.includes(v))throw new Error(`The input text does not contain the image token ${v}.`);l=l.replaceAll(v,v.repeat(A))}return{...this.tokenizer(l,{add_special_tokens:!1,...p}),...c}}}re(o,"tokenizer_class",i.AutoTokenizer),re(o,"feature_extractor_class",s.AutoFeatureExtractor),re(o,"uses_processor_config",!0)},"./src/models/vit/image_processing_vit.js":(e,r,t)=>{t.r(r),t.d(r,{ViTFeatureExtractor:()=>n,ViTImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{}class n extends i{}},"./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"),i=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(h=>this.preprocess(h))),p=await Promise.all(l.map(h=>this.preprocess(h,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:(0,i.stack)(u.map((h,g)=>(0,i.cat)([h.pixel_values,p[g].pixel_values],0)),0),original_sizes:u.map(h=>h.original_size),reshaped_input_sizes:u.map(h=>h.reshaped_input_size)}}}},"./src/models/vitpose/image_processing_vitpose.js":(e,r,t)=>{t.r(r),t.d(r,{VitPoseImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{post_process_pose_estimation(o,a,{threshold:l=null}={}){const u=o.tolist(),[p,c,h,g]=o.dims,_=[];for(let E=0;E{t.r(r),t.d(r,{Wav2Vec2FeatureExtractor:()=>n});var s=t("./src/base/feature_extraction_utils.js"),i=t("./src/utils/tensor.js");class n extends s.FeatureExtractor{_zero_mean_unit_var_norm(a){const u=a.reduce((c,h)=>c+h,0)/a.length,p=a.reduce((c,h)=>c+(h-u)**2,0)/a.length;return a.map(c=>(c-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 i.Tensor("float32",l,u),attention_mask:new i.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:()=>o});var s=t("./src/tokenizers.js"),i=t("./src/models/auto/feature_extraction_auto.js"),n=t("./src/base/processing_utils.js");class o extends n.Processor{async _call(l){return await this.feature_extractor(l)}}re(o,"tokenizer_class",s.AutoTokenizer),re(o,"feature_extractor_class",i.AutoFeatureExtractor)},"./src/models/wav2vec2_with_lm/processing_wav2vec2_with_lm.js":(e,r,t)=>{t.r(r),t.d(r,{Wav2Vec2ProcessorWithLM:()=>o});var s=t("./src/tokenizers.js"),i=t("./src/models/auto/feature_extraction_auto.js"),n=t("./src/base/processing_utils.js");class o extends n.Processor{async _call(l){return await this.feature_extractor(l)}}re(o,"tokenizer_class",s.AutoTokenizer),re(o,"feature_extractor_class",i.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 i=t("./src/utils/audio.js");class n extends s.FeatureExtractor{constructor(a){super(a);const l=this.config.sampling_rate,u=(0,i.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(l/2),l,null,"kaldi",!0);for(let p=0;pl*32768),(0,i.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,[c,h,g]=l.dims;for(let _=0;_{t.r(r),t.d(r,{WHISPER_LANGUAGE_MAPPING:()=>i,WHISPER_TO_LANGUAGE_CODE_MAPPING:()=>n,whisper_language_to_code:()=>o});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"]],i=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 o(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]),i.has(a))l=a;else{const c=a.length===2?i.keys():i.values();throw new Error(`Language "${a}" is not supported. Must be one of: ${JSON.stringify(Array.from(c))}`)}}return l}},"./src/models/whisper/feature_extraction_whisper.js":(e,r,t)=>{t.r(r),t.d(r,{WhisperFeatureExtractor:()=>o});var s=t("./src/base/feature_extraction_utils.js");t("./src/utils/tensor.js");var i=t("./src/utils/audio.js"),n=t("./src/utils/maths.js");class o extends s.FeatureExtractor{constructor(l){var u;super(l),(u=this.config).mel_filters??(u.mel_filters=(0,i.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,i.window_function)(this.config.n_fft,"hann")}async _extract_fbank_features(l){const u=await(0,i.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,c=(0,n.max)(p)[0];for(let h=0;hc?(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,c)):(p=new Float32Array(c),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:()=>i});var s=t("./src/generation/configuration_utils.js");class i extends s.GenerationConfig{constructor(){super(...arguments);re(this,"return_timestamps",null);re(this,"return_token_timestamps",null);re(this,"num_frames",null);re(this,"alignment_heads",null);re(this,"task",null);re(this,"language",null);re(this,"no_timestamps_token_id",null);re(this,"prompt_ids",null);re(this,"is_multilingual",null);re(this,"lang_to_id",null);re(this,"task_to_id",null);re(this,"max_initial_timestamp_index",1)}}},"./src/models/whisper/processing_whisper.js":(e,r,t)=>{t.r(r),t.d(r,{WhisperProcessor:()=>o});var s=t("./src/models/auto/feature_extraction_auto.js"),i=t("./src/tokenizers.js"),n=t("./src/base/processing_utils.js");class o extends n.Processor{async _call(l){return await this.feature_extractor(l)}}re(o,"tokenizer_class",i.AutoTokenizer),re(o,"feature_extractor_class",s.AutoFeatureExtractor)},"./src/models/yolos/image_processing_yolos.js":(e,r,t)=>{t.r(r),t.d(r,{YolosFeatureExtractor:()=>n,YolosImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{post_process_object_detection(...a){return(0,s.post_process_object_detection)(...a)}}class n extends i{}},"./src/ops/registry.js":(e,r,t)=>{t.r(r),t.d(r,{TensorOpRegistry:()=>l});var s=t("./src/backends/onnx.js"),i=t("./src/utils/tensor.js"),n=t("./src/env.js");const o=n.apis.IS_BROWSER_ENV||n.apis.IS_WEBWORKER_ENV,a=async(u,p,c)=>{const h=await(0,s.createInferenceSession)(new Uint8Array(u),p);let g=Promise.resolve();return async _=>{const E=(0,s.isONNXProxy)(),A=Object.fromEntries(Object.entries(_).map(([y,k])=>[y,(E?k.clone():k).ort_tensor])),v=await(g=o?g.then(()=>h.run(A)):h.run(A));return Array.isArray(c)?c.map(y=>new i.Tensor(v[y])):new i.Tensor(v[c])}};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}}re(l,"session_options",{})},"./src/pipelines.js":(e,r,t)=>{t.r(r),t.d(r,{AudioClassificationPipeline:()=>q,AutomaticSpeechRecognitionPipeline:()=>Z,BackgroundRemovalPipeline:()=>ae,DepthEstimationPipeline:()=>X,DocumentQuestionAnsweringPipeline:()=>O,FeatureExtractionPipeline:()=>R,FillMaskPipeline:()=>k,ImageClassificationPipeline:()=>J,ImageFeatureExtractionPipeline:()=>Q,ImageSegmentationPipeline:()=>ie,ImageToImagePipeline:()=>se,ImageToTextPipeline:()=>H,ObjectDetectionPipeline:()=>he,Pipeline:()=>E,QuestionAnsweringPipeline:()=>y,SummarizationPipeline:()=>M,Text2TextGenerationPipeline:()=>P,TextClassificationPipeline:()=>A,TextGenerationPipeline:()=>$,TextToAudioPipeline:()=>G,TokenClassificationPipeline:()=>v,TranslationPipeline:()=>w,ZeroShotAudioClassificationPipeline:()=>U,ZeroShotClassificationPipeline:()=>z,ZeroShotImageClassificationPipeline:()=>ue,ZeroShotObjectDetectionPipeline:()=>N,pipeline:()=>ke});var s=t("./src/tokenizers.js"),i=t("./src/models.js"),n=t("./src/models/auto/processing_auto.js");t("./src/base/processing_utils.js");var o=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"),c=t("./src/utils/image.js");async function h(Me){return Array.isArray(Me)||(Me=[Me]),await Promise.all(Me.map(K=>c.RawImage.read(K)))}async function g(Me,K){return Array.isArray(Me)||(Me=[Me]),await Promise.all(Me.map(j=>typeof j=="string"||j instanceof URL?(0,u.read_audio)(j,K):j instanceof Float64Array?new Float32Array(j):j))}function _(Me,K){K&&(Me=Me.map(Ae=>Ae|0));const[j,fe,Pe,xe]=Me;return{xmin:j,ymin:fe,xmax:Pe,ymax:xe}}class E extends o.Callable{constructor({task:K,model:j,tokenizer:fe=null,processor:Pe=null}){super(),this.task=K,this.model=j,this.tokenizer=fe,this.processor=Pe}async dispose(){await this.model.dispose()}}class A extends E{constructor(K){super(K)}async _call(K,{top_k:j=1}={}){const fe=this.tokenizer(K,{padding:!0,truncation:!0}),Pe=await this.model(fe),xe=this.model.config.problem_type==="multi_label_classification"?Le=>Le.sigmoid():Le=>new p.Tensor("float32",(0,l.softmax)(Le.data),Le.dims),Ae=this.model.config.id2label,Ie=[];for(const Le of Pe.logits){const Ne=xe(Le),We=await(0,p.topk)(Ne,j),D=We[0].tolist(),B=We[1].tolist().map((te,de)=>({label:Ae?Ae[te]:`LABEL_${te}`,score:D[de]}));j===1?Ie.push(...B):Ie.push(B)}return Array.isArray(K)||j===1?Ie:Ie[0]}}class v extends E{constructor(K){super(K)}async _call(K,{ignore_labels:j=["O"]}={}){const fe=Array.isArray(K),Pe=this.tokenizer(fe?K:[K],{padding:!0,truncation:!0}),Ae=(await this.model(Pe)).logits,Ie=this.model.config.id2label,Le=[];for(let Ne=0;NeFe==this.tokenizer.sep_token_id);Le[D].map((Fe,je)=>Fe==1&&(je===0||je>B&&Ne.findIndex(qe=>qe==ee[je])===-1));const te=xe[D].tolist(),de=Ae[D].tolist();for(let Fe=1;Feje==ee[Fe])!==-1)&&(te[Fe]=-1/0,de[Fe]=-1/0);const be=(0,l.softmax)(te).map((Fe,je)=>[Fe,je]),ve=(0,l.softmax)(de).map((Fe,je)=>[Fe,je]);be[0][0]=0,ve[0][0]=0;const Re=(0,a.product)(be,ve).filter(Fe=>Fe[0][1]<=Fe[1][1]).map(Fe=>[Fe[0][1],Fe[1][1],Fe[0][0]*Fe[1][0]]).sort((Fe,je)=>je[2]-Fe[2]);for(let Fe=0;Fete==this.tokenizer.mask_token_id);if(Ne===-1)throw Error(`Mask token (${this.tokenizer.mask_token}) not found in text.`);const We=Pe[Ie][Ne],D=await(0,p.topk)(new p.Tensor("float32",(0,l.softmax)(We.data),We.dims),j),ee=D[0].tolist(),B=D[1].tolist();xe.push(B.map((te,de)=>{const be=Le.slice();return be[Ne]=te,{score:ee[de],token:Number(te),token_str:this.tokenizer.decode([te]),sequence:this.tokenizer.decode(be,{skip_special_tokens:!0})}}))}return Array.isArray(K)?xe:xe[0]}}class P extends E{constructor(j){super(j);re(this,"_key","generated_text")}async _call(j,fe={}){Array.isArray(j)||(j=[j]),this.model.config.prefix&&(j=j.map(Ne=>this.model.config.prefix+Ne));const Pe=this.model.config.task_specific_params;Pe&&Pe[this.task]&&Pe[this.task].prefix&&(j=j.map(Ne=>Pe[this.task].prefix+Ne));const xe=this.tokenizer,Ae={padding:!0,truncation:!0};let Ie;this instanceof w&&"_build_translation_inputs"in xe?Ie=xe._build_translation_inputs(j,Ae,fe):Ie=xe(j,Ae);const Le=await this.model.generate({...Ie,...fe});return xe.batch_decode(Le,{skip_special_tokens:!0}).map(Ne=>({[this._key]:Ne}))}}class M extends P{constructor(j){super(j);re(this,"_key","summary_text")}}class w extends P{constructor(j){super(j);re(this,"_key","translation_text")}}function x(Me){return Array.isArray(Me)&&Me.every(K=>"role"in K&&"content"in K)}class $ extends E{constructor(K){super(K)}async _call(K,j={}){let fe=!1,Pe=!1,xe;if(typeof K=="string")xe=K=[K];else if(Array.isArray(K)&&K.every(B=>typeof B=="string"))fe=!0,xe=K;else{if(x(K))K=[K];else if(Array.isArray(K)&&K.every(x))fe=!0;else throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats");Pe=!0,xe=K.map(B=>this.tokenizer.apply_chat_template(B,{tokenize:!1,add_generation_prompt:!0}))}const Ae=j.add_special_tokens??!1,Ie=Pe?!1:j.return_full_text??!0;this.tokenizer.padding_side="left";const Le=this.tokenizer(xe,{add_special_tokens:Ae,padding:!0,truncation:!0}),Ne=await this.model.generate({...Le,...j}),We=this.tokenizer.batch_decode(Ne,{skip_special_tokens:!0});let D;!Ie&&Le.input_ids.dims.at(-1)>0&&(D=this.tokenizer.batch_decode(Le.input_ids,{skip_special_tokens:!0}).map(B=>B.length));const ee=Array.from({length:K.length},B=>[]);for(let B=0;B[j.toLowerCase(),fe])),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(K,j,{hypothesis_template:fe="This example is {}.",multi_label:Pe=!1}={}){const xe=Array.isArray(K);xe||(K=[K]),Array.isArray(j)||(j=[j]);const Ae=j.map(Ne=>fe.replace("{}",Ne)),Ie=Pe||j.length===1,Le=[];for(const Ne of K){const We=[];for(const B of Ae){const te=this.tokenizer(Ne,{text_pair:B,padding:!0,truncation:!0}),de=await this.model(te);Ie?We.push([de.logits.data[this.contradiction_id],de.logits.data[this.entailment_id]]):We.push(de.logits.data[this.entailment_id])}const ee=(Ie?We.map(B=>(0,l.softmax)(B)[1]):(0,l.softmax)(We)).map((B,te)=>[B,te]).sort((B,te)=>te[0]-B[0]);Le.push({sequence:Ne,labels:ee.map(B=>j[B[1]]),scores:ee.map(B=>B[0])})}return xe?Le:Le[0]}}class R extends E{constructor(K){super(K)}async _call(K,{pooling:j="none",normalize:fe=!1,quantize:Pe=!1,precision:xe="binary"}={}){const Ae=this.tokenizer(K,{padding:!0,truncation:!0}),Ie=await this.model(Ae);let Le=Ie.last_hidden_state??Ie.logits??Ie.token_embeddings;if(j!=="none")if(j==="mean")Le=(0,p.mean_pooling)(Le,Ae.attention_mask);else if(j==="cls")Le=Le.slice(null,0);else throw Error(`Pooling method '${j}' not supported.`);return fe&&(Le=Le.normalize(2,-1)),Pe&&(Le=(0,p.quantize_embeddings)(Le,xe)),Le}}class Q extends E{constructor(K){super(K)}async _call(K,{pool:j=null}={}){const fe=await h(K),{pixel_values:Pe}=await this.processor(fe),xe=await this.model({pixel_values:Pe});let Ae;if(j){if(!("pooler_output"in xe))throw Error("No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.");Ae=xe.pooler_output}else Ae=xe.last_hidden_state??xe.logits??xe.image_embeds;return Ae}}class q extends E{constructor(K){super(K)}async _call(K,{top_k:j=5}={}){const fe=this.processor.feature_extractor.config.sampling_rate,Pe=await g(K,fe),xe=this.model.config.id2label,Ae=[];for(const Ie of Pe){const Le=await this.processor(Ie),We=(await this.model(Le)).logits[0],D=await(0,p.topk)(new p.Tensor("float32",(0,l.softmax)(We.data),We.dims),j),ee=D[0].tolist(),te=D[1].tolist().map((de,be)=>({label:xe?xe[de]:`LABEL_${de}`,score:ee[be]}));Ae.push(te)}return Array.isArray(K)?Ae:Ae[0]}}class U extends E{constructor(K){super(K)}async _call(K,j,{hypothesis_template:fe="This is a sound of {}."}={}){const Pe=!Array.isArray(K);Pe&&(K=[K]);const xe=j.map(We=>fe.replace("{}",We)),Ae=this.tokenizer(xe,{padding:!0,truncation:!0}),Ie=this.processor.feature_extractor.config.sampling_rate,Le=await g(K,Ie),Ne=[];for(const We of Le){const D=await this.processor(We),ee=await this.model({...Ae,...D}),B=(0,l.softmax)(ee.logits_per_audio.data);Ne.push([...B].map((te,de)=>({score:te,label:j[de]})))}return Pe?Ne[0]:Ne}}class Z extends E{constructor(K){super(K)}async _call(K,j={}){switch(this.model.config.model_type){case"whisper":case"lite-whisper":return this._call_whisper(K,j);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":return this._call_wav2vec2(K,j);case"moonshine":return this._call_moonshine(K,j);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(K,j){j.language&&console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),j.task&&console.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');const fe=!Array.isArray(K);fe&&(K=[K]);const Pe=this.processor.feature_extractor.config.sampling_rate,xe=await g(K,Pe),Ae=[];for(const Ie of xe){const Le=await this.processor(Ie),We=(await this.model(Le)).logits[0],D=[];for(const B of We)D.push((0,l.max)(B.data)[1]);const ee=this.tokenizer.decode(D);Ae.push({text:ee})}return fe?Ae[0]:Ae}async _call_whisper(K,j){const fe=j.return_timestamps??!1,Pe=j.chunk_length_s??0,xe=j.force_full_sequences??!1;let Ae=j.stride_length_s??null;const Ie={...j};fe==="word"&&(Ie.return_token_timestamps=!0,Ie.return_timestamps=!1);const Le=!Array.isArray(K);Le&&(K=[K]);const Ne=this.processor.feature_extractor.config.chunk_length/this.model.config.max_source_positions,We=this.processor.feature_extractor.config.hop_length,D=this.processor.feature_extractor.config.sampling_rate,ee=await g(K,D),B=[];for(const te of ee){let de=[];if(Pe>0){if(Ae===null)Ae=Pe/6;else if(Pe<=Ae)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");const Re=D*Pe,Fe=D*Ae,je=Re-2*Fe;let qe=0;for(;;){const Xe=qe+Re,ct=te.subarray(qe,Xe),wt=await this.processor(ct),nr=qe===0,jt=Xe>=te.length;if(de.push({stride:[ct.length,nr?0:Fe,jt?0:Fe],input_features:wt.input_features,is_last:jt}),jt)break;qe+=je}}else de=[{stride:[te.length,0,0],input_features:(await this.processor(te)).input_features,is_last:!0}];for(const Re of de){Ie.num_frames=Math.floor(Re.stride[0]/We);const Fe=await this.model.generate({inputs:Re.input_features,...Ie});fe==="word"?(Re.tokens=Fe.sequences.tolist()[0],Re.token_timestamps=Fe.token_timestamps.tolist()[0].map(je=>(0,l.round)(je,2))):Re.tokens=Fe[0].tolist(),Re.stride=Re.stride.map(je=>je/D)}const[be,ve]=this.tokenizer._decode_asr(de,{time_precision:Ne,return_timestamps:fe,force_full_sequences:xe});B.push({text:be,...ve})}return Le?B[0]:B}async _call_moonshine(K,j){const fe=!Array.isArray(K);fe&&(K=[K]);const Pe=this.processor.feature_extractor.config.sampling_rate,xe=await g(K,Pe),Ae=[];for(const Ie of xe){const Le=await this.processor(Ie),Ne=Math.floor(Ie.length/Pe)*6,We=await this.model.generate({max_new_tokens:Ne,...j,...Le}),D=this.processor.batch_decode(We,{skip_special_tokens:!0})[0];Ae.push({text:D})}return fe?Ae[0]:Ae}}class H extends E{constructor(K){super(K)}async _call(K,j={}){const fe=Array.isArray(K),Pe=await h(K),{pixel_values:xe}=await this.processor(Pe),Ae=[];for(const Ie of xe){Ie.dims=[1,...Ie.dims];const Le=await this.model.generate({inputs:Ie,...j}),Ne=this.tokenizer.batch_decode(Le,{skip_special_tokens:!0}).map(We=>({generated_text:We.trim()}));Ae.push(Ne)}return fe?Ae:Ae[0]}}class J extends E{constructor(K){super(K)}async _call(K,{top_k:j=5}={}){const fe=await h(K),{pixel_values:Pe}=await this.processor(fe),xe=await this.model({pixel_values:Pe}),Ae=this.model.config.id2label,Ie=[];for(const Le of xe.logits){const Ne=await(0,p.topk)(new p.Tensor("float32",(0,l.softmax)(Le.data),Le.dims),j),We=Ne[0].tolist(),ee=Ne[1].tolist().map((B,te)=>({label:Ae?Ae[B]:`LABEL_${B}`,score:We[te]}));Ie.push(ee)}return Array.isArray(K)?Ie:Ie[0]}}class ie extends E{constructor(K){super(K),this.subtasks_mapping={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"}}async _call(K,{threshold:j=.5,mask_threshold:fe=.5,overlap_mask_area_threshold:Pe=.8,label_ids_to_fuse:xe=null,target_sizes:Ae=null,subtask:Ie=null}={}){if(Array.isArray(K)&&K.length!==1)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");const Ne=await h(K),We=Ne.map(Re=>[Re.height,Re.width]),D=await this.processor(Ne),{inputNames:ee,outputNames:B}=this.model.sessions.model;if(!ee.includes("pixel_values")){if(ee.length!==1)throw Error(`Expected a single input name, but got ${ee.length} inputs: ${ee}.`);const Re=ee[0];if(Re in D)throw Error(`Input name ${Re} already exists in the inputs.`);D[Re]=D.pixel_values}const te=await this.model(D);let de=null;if(Ie!==null)de=this.subtasks_mapping[Ie];else if(this.processor.image_processor){for(const[Re,Fe]of Object.entries(this.subtasks_mapping))if(Fe in this.processor.image_processor){de=this.processor.image_processor[Fe].bind(this.processor.image_processor),Ie=Re;break}}const be=this.model.config.id2label,ve=[];if(Ie)if(Ie==="panoptic"||Ie==="instance"){const Re=de(te,j,fe,Pe,xe,Ae??We)[0],Fe=Re.segmentation;for(const je of Re.segments_info){const qe=new Uint8ClampedArray(Fe.data.length);for(let ct=0;ctwt<-1e-5||wt>1+1e-5)&&Xe.sigmoid_();const ct=await c.RawImage.fromTensor(Xe.mul_(255).to("uint8")).resize(qe[1],qe[0]);ve.push({label:null,score:null,mask:ct})}}return ve}}class ae extends ie{constructor(K){super(K)}async _call(K,j={}){if(Array.isArray(K)&&K.length!==1)throw Error("Background removal pipeline currently only supports a batch size of 1.");const Pe=await h(K),xe=await super._call(K,j);return Pe.map((Ie,Le)=>{const Ne=Ie.clone();return Ne.putAlpha(xe[Le].mask),Ne})}}class ue extends E{constructor(K){super(K)}async _call(K,j,{hypothesis_template:fe="This is a photo of {}"}={}){const Pe=Array.isArray(K),xe=await h(K),Ae=j.map(ee=>fe.replace("{}",ee)),Ie=this.tokenizer(Ae,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:Le}=await this.processor(xe),Ne=await this.model({...Ie,pixel_values:Le}),We=this.model.config.model_type==="siglip"?ee=>ee.sigmoid().data:ee=>(0,l.softmax)(ee.data),D=[];for(const ee of Ne.logits_per_image){const te=[...We(ee)].map((de,be)=>({score:de,label:j[be]}));te.sort((de,be)=>be.score-de.score),D.push(te)}return Pe?D:D[0]}}class he extends E{constructor(K){super(K)}async _call(K,{threshold:j=.9,percentage:fe=!1}={}){const Pe=Array.isArray(K);if(Pe&&K.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");const xe=await h(K),Ae=fe?null:xe.map(B=>[B.height,B.width]),{pixel_values:Ie,pixel_mask:Le}=await this.processor(xe),Ne=await this.model({pixel_values:Ie,pixel_mask:Le}),We=this.processor.image_processor.post_process_object_detection(Ne,j,Ae),D=this.model.config.id2label,ee=We.map(B=>B.boxes.map((te,de)=>({score:B.scores[de],label:D[B.classes[de]],box:_(te,!fe)})));return Pe?ee:ee[0]}}class N extends E{constructor(K){super(K)}async _call(K,j,{threshold:fe=.1,top_k:Pe=null,percentage:xe=!1}={}){const Ae=Array.isArray(K),Ie=await h(K),Le=this.tokenizer(j,{padding:!0,truncation:!0}),Ne=await this.processor(Ie),We=[];for(let D=0;D({score:ve.scores[Fe],label:ve.labels[Fe],box:_(Re,!xe)}))}else{const ve=this.processor.image_processor.post_process_object_detection(de,fe,B,!0)[0];be=ve.boxes.map((Re,Fe)=>({score:ve.scores[Fe],label:j[ve.classes[Fe]],box:_(Re,!xe)}))}be.sort((ve,Re)=>Re.score-ve.score),Pe!==null&&(be=be.slice(0,Pe)),We.push(be)}return Ae?We:We[0]}}class O extends E{constructor(K){super(K)}async _call(K,j,fe={}){const Pe=(await h(K))[0],{pixel_values:xe}=await this.processor(Pe),Ae=`${j}`,Ie=this.tokenizer(Ae,{add_special_tokens:!1,padding:!0,truncation:!0}).input_ids,Le=await this.model.generate({inputs:xe,max_length:this.model.config.decoder.max_position_embeddings,decoder_input_ids:Ie,...fe}),We=this.tokenizer.batch_decode(Le)[0].match(/(.*?)<\/s_answer>/);let D=null;return We&&We.length>=2&&(D=We[1].trim()),[{answer:D}]}}class G extends E{constructor(j){super(j);re(this,"DEFAULT_VOCODER_ID","Xenova/speecht5_hifigan");this.vocoder=j.vocoder??null}async _call(j,{speaker_embeddings:fe=null}={}){return this.processor?this._call_text_to_spectrogram(j,{speaker_embeddings:fe}):this._call_text_to_waveform(j)}async _call_text_to_waveform(j){const fe=this.tokenizer(j,{padding:!0,truncation:!0}),{waveform:Pe}=await this.model(fe),xe=this.model.config.sampling_rate;return new u.RawAudio(Pe.data,xe)}async _call_text_to_spectrogram(j,{speaker_embeddings:fe}){if(this.vocoder||(console.log("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await i.AutoModel.from_pretrained(this.DEFAULT_VOCODER_ID,{dtype:"fp32"})),(typeof fe=="string"||fe instanceof URL)&&(fe=new Float32Array(await(await fetch(fe)).arrayBuffer())),fe instanceof Float32Array)fe=new p.Tensor("float32",fe,[1,fe.length]);else if(!(fe instanceof p.Tensor))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");const{input_ids:Pe}=this.tokenizer(j,{padding:!0,truncation:!0}),{waveform:xe}=await this.model.generate_speech(Pe,fe,{vocoder:this.vocoder}),Ae=this.processor.feature_extractor.config.sampling_rate;return new u.RawAudio(xe.data,Ae)}}class se extends E{constructor(K){super(K)}async _call(K){const j=await h(K),fe=await this.processor(j),Pe=await this.model(fe),xe=[];for(const Ae of Pe.reconstruction){const Ie=Ae.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");xe.push(c.RawImage.fromTensor(Ie))}return xe.length>1?xe:xe[0]}}class X extends E{constructor(K){super(K)}async _call(K){const j=await h(K),fe=await this.processor(j),{predicted_depth:Pe}=await this.model(fe),xe=[];for(let Ae=0;Ae1?xe:xe[0]}}const we=Object.freeze({"text-classification":{tokenizer:s.AutoTokenizer,pipeline:A,model:i.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{tokenizer:s.AutoTokenizer,pipeline:v,model:i.AutoModelForTokenClassification,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{tokenizer:s.AutoTokenizer,pipeline:y,model:i.AutoModelForQuestionAnswering,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{tokenizer:s.AutoTokenizer,pipeline:k,model:i.AutoModelForMaskedLM,default:{model:"Xenova/bert-base-uncased"},type:"text"},summarization:{tokenizer:s.AutoTokenizer,pipeline:M,model:i.AutoModelForSeq2SeqLM,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{tokenizer:s.AutoTokenizer,pipeline:w,model:i.AutoModelForSeq2SeqLM,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{tokenizer:s.AutoTokenizer,pipeline:P,model:i.AutoModelForSeq2SeqLM,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{tokenizer:s.AutoTokenizer,pipeline:$,model:i.AutoModelForCausalLM,default:{model:"Xenova/gpt2"},type:"text"},"zero-shot-classification":{tokenizer:s.AutoTokenizer,pipeline:z,model:i.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:q,model:i.AutoModelForAudioClassification,processor:n.AutoProcessor,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{tokenizer:s.AutoTokenizer,pipeline:U,model:i.AutoModel,processor:n.AutoProcessor,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{tokenizer:s.AutoTokenizer,pipeline:Z,model:[i.AutoModelForSpeechSeq2Seq,i.AutoModelForCTC],processor:n.AutoProcessor,default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{tokenizer:s.AutoTokenizer,pipeline:G,model:[i.AutoModelForTextToWaveform,i.AutoModelForTextToSpectrogram],processor:[n.AutoProcessor,null],default:{model:"Xenova/speecht5_tts"},type:"text"},"image-to-text":{tokenizer:s.AutoTokenizer,pipeline:H,model:i.AutoModelForVision2Seq,processor:n.AutoProcessor,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:J,model:i.AutoModelForImageClassification,processor:n.AutoProcessor,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:ie,model:[i.AutoModelForImageSegmentation,i.AutoModelForSemanticSegmentation,i.AutoModelForUniversalSegmentation],processor:n.AutoProcessor,default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"background-removal":{pipeline:ae,model:[i.AutoModelForImageSegmentation,i.AutoModelForSemanticSegmentation,i.AutoModelForUniversalSegmentation],processor:n.AutoProcessor,default:{model:"Xenova/modnet"},type:"image"},"zero-shot-image-classification":{tokenizer:s.AutoTokenizer,pipeline:ue,model:i.AutoModel,processor:n.AutoProcessor,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:he,model:i.AutoModelForObjectDetection,processor:n.AutoProcessor,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{tokenizer:s.AutoTokenizer,pipeline:N,model:i.AutoModelForZeroShotObjectDetection,processor:n.AutoProcessor,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{tokenizer:s.AutoTokenizer,pipeline:O,model:i.AutoModelForDocumentQuestionAnswering,processor:n.AutoProcessor,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:se,model:i.AutoModelForImageToImage,processor:n.AutoProcessor,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:X,model:i.AutoModelForDepthEstimation,processor:n.AutoProcessor,default:{model:"Xenova/dpt-large"},type:"image"},"feature-extraction":{tokenizer:s.AutoTokenizer,pipeline:R,model:i.AutoModel,default:{model:"Xenova/all-MiniLM-L6-v2"},type:"text"},"image-feature-extraction":{processor:n.AutoProcessor,pipeline:Q,model:[i.AutoModelForImageFeatureExtraction,i.AutoModel],default:{model:"Xenova/vit-base-patch16-224-in21k"},type:"image"}}),_e=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});async function ke(Me,K=null,{progress_callback:j=null,config:fe=null,cache_dir:Pe=null,local_files_only:xe=!1,revision:Ae="main",device:Ie=null,dtype:Le=null,subfolder:Ne="onnx",use_external_data_format:We=null,model_file_name:D=null,session_options:ee={}}={}){Me=_e[Me]??Me;const B=we[Me.split("_",1)[0]];if(!B)throw Error(`Unsupported pipeline: ${Me}. Must be one of [${Object.keys(we)}]`);K||(K=B.default.model,console.log(`No model specified. Using default model: "${K}".`));const te={progress_callback:j,config:fe,cache_dir:Pe,local_files_only:xe,revision:Ae,device:Ie,dtype:Le,subfolder:Ne,use_external_data_format:We,model_file_name:D,session_options:ee},de=new Map([["tokenizer",B.tokenizer],["model",B.model],["processor",B.processor]]),be=await He(de,K,te);be.task=Me,(0,a.dispatchCallback)(j,{status:"ready",task:Me,model:K});const ve=B.pipeline;return new ve(be)}async function He(Me,K,j){const fe=Object.create(null),Pe=[];for(const[xe,Ae]of Me.entries()){if(!Ae)continue;let Ie;Array.isArray(Ae)?Ie=new Promise(async(Le,Ne)=>{var D,ee;let We;for(const B of Ae){if(B===null){Le(null);return}try{Le(await B.from_pretrained(K,j));return}catch(te){if((D=te.message)!=null&&D.includes("Unsupported model type"))We=te;else if((ee=te.message)!=null&&ee.includes("Could not locate file"))We=te;else{Ne(te);return}}}Ne(We)}):Ie=Ae.from_pretrained(K,j),fe[xe]=Ie,Pe.push(Ie)}await Promise.all(Pe);for(const[xe,Ae]of Object.entries(fe))fe[xe]=await Ae;return fe}},"./src/tokenizers.js":(e,r,t)=>{t.r(r),t.d(r,{AlbertTokenizer:()=>Vr,AutoTokenizer:()=>Sn,BartTokenizer:()=>fs,BertTokenizer:()=>qr,BlenderbotSmallTokenizer:()=>Jr,BlenderbotTokenizer:()=>Ar,BloomTokenizer:()=>Qr,CLIPTokenizer:()=>En,CamembertTokenizer:()=>it,CodeGenTokenizer:()=>Xr,CodeLlamaTokenizer:()=>Js,CohereTokenizer:()=>Cn,ConvBertTokenizer:()=>fr,DebertaTokenizer:()=>Es,DebertaV2Tokenizer:()=>Ps,DistilBertTokenizer:()=>et,ElectraTokenizer:()=>zt,EsmTokenizer:()=>tn,FalconTokenizer:()=>gs,GPT2Tokenizer:()=>hs,GPTNeoXTokenizer:()=>en,GemmaTokenizer:()=>Lr,Grok1Tokenizer:()=>Ss,HerbertTokenizer:()=>zs,LlamaTokenizer:()=>Xs,M2M100Tokenizer:()=>Rs,MBart50Tokenizer:()=>ms,MBartTokenizer:()=>Er,MPNetTokenizer:()=>Zs,MarianTokenizer:()=>Pn,MgpstrTokenizer:()=>$s,MobileBertTokenizer:()=>ps,NllbTokenizer:()=>Bs,NougatTokenizer:()=>mr,PreTrainedTokenizer:()=>dt,Qwen2Tokenizer:()=>rn,RoFormerTokenizer:()=>Be,RobertaTokenizer:()=>_s,SiglipTokenizer:()=>zr,SpeechT5Tokenizer:()=>ur,SqueezeBertTokenizer:()=>xs,T5Tokenizer:()=>kr,TokenizerModel:()=>Q,VitsTokenizer:()=>js,Wav2Vec2CTCTokenizer:()=>Ns,WhisperTokenizer:()=>Ir,XLMRobertaTokenizer:()=>Ys,XLMTokenizer:()=>rr,is_chinese_char:()=>k});var s=t("./src/utils/generic.js"),i=t("./src/utils/core.js"),n=t("./src/utils/hub.js"),o=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 c(pe,F){const V=await Promise.all([(0,n.getModelJSON)(pe,"tokenizer.json",!0,F),(0,n.getModelJSON)(pe,"tokenizer_config.json",!0,F)]);return F.legacy!==null&&(V[1].legacy=F.legacy),V}function h(pe,F){const V=[];let Y=0;for(const le of pe.matchAll(F)){const ce=le[0];Y0&&V.push(ce),Y=le.index+ce.length}return Y=19968&&pe<=40959||pe>=13312&&pe<=19903||pe>=131072&&pe<=173791||pe>=173824&&pe<=177983||pe>=177984&&pe<=178207||pe>=178208&&pe<=183983||pe>=63744&&pe<=64255||pe>=194560&&pe<=195103}function P(pe,F,V){const Y=[];let le=0;for(;lethis.tokens_to_ids.get(V)??this.unk_token_id)}convert_ids_to_tokens(F){return F.map(V=>this.vocab[V]??this.unk_token)}}class q extends Q{constructor(F){super(F),this.tokens_to_ids=_(F.vocab),this.unk_token_id=this.tokens_to_ids.get(F.unk_token),this.unk_token=F.unk_token,this.max_input_chars_per_word=F.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(const[V,Y]of this.tokens_to_ids)this.vocab[Y]=V}encode(F){const V=[];for(const Y of F){const le=[...Y];if(le.length>this.max_input_chars_per_word){V.push(this.unk_token);continue}let ce=!1,Ce=0;const Ue=[];for(;Ce0&&(Ze=this.config.continuing_subword_prefix+Ze),this.tokens_to_ids.has(Ze)){Ke=Ze;break}--Qe}if(Ke===null){ce=!0;break}Ue.push(Ke),Ce=Qe}ce?V.push(this.unk_token):V.push(...Ue)}return V}}class U extends Q{constructor(F,V){super(F);const Y=F.vocab.length;this.vocab=new Array(Y),this.scores=new Array(Y);for(let le=0;le[le,ce])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=V.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,o.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(F){const V=F.chars,Y=1;let le=0;for(;le{const pe=[...Array.from({length:94},(le,ce)=>ce+33),...Array.from({length:12},(le,ce)=>ce+161),...Array.from({length:82},(le,ce)=>ce+174)],F=pe.slice();let V=0;for(let le=0;le<256;++le)pe.includes(le)||(pe.push(le),F.push(256+V),V+=1);const Y=F.map(le=>String.fromCharCode(le));return Object.fromEntries(pe.map((le,ce)=>[le,Y[ce]]))})(),H=(0,i.reverseDictionary)(Z);class J extends Q{constructor(F){super(F),this.tokens_to_ids=_(F.vocab),this.unk_token_id=this.tokens_to_ids.get(F.unk_token),this.unk_token=F.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(const[Y,le]of this.tokens_to_ids)this.vocab[le]=Y;const V=Array.isArray(F.merges[0]);this.merges=V?F.merges:F.merges.map(Y=>Y.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((Y,le)=>[JSON.stringify(Y),le])),this.end_of_word_suffix=F.end_of_word_suffix,this.continuing_subword_suffix=F.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(F){if(F.length===0)return[];const V=this.cache.get(F);if(V!==void 0)return V;const Y=Array.from(F);this.end_of_word_suffix&&(Y[Y.length-1]+=this.end_of_word_suffix);let le=[];if(Y.length>1){const ce=new l.PriorityQueue((Qe,Ke)=>Qe.score`<0x${Ue.toString(16).toUpperCase().padStart(2,"0")}>`);Ce.every(Ue=>this.tokens_to_ids.has(Ue))?V.push(...Ce):V.push(this.unk_token)}else V.push(this.unk_token)}return V}}class ie extends Q{constructor(F,V){super(F),this.tokens_to_ids=_(V.target_lang?F.vocab[V.target_lang]:F.vocab),this.bos_token=V.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=V.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=V.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=V.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[Y,le]of this.tokens_to_ids)this.vocab[le]=Y}encode(F){return F}}class ae extends s.Callable{constructor(F){super(),this.config=F}static fromConfig(F){if(F===null)return null;switch(F.type){case"BertNormalizer":return new Me(F);case"Precompiled":return new jt(F);case"Sequence":return new He(F);case"Replace":return new ue(F);case"NFC":return new N(F);case"NFD":return new O(F);case"NFKC":return new G(F);case"NFKD":return new se(F);case"Strip":return new X(F);case"StripAccents":return new we(F);case"Lowercase":return new _e(F);case"Prepend":return new ke(F);default:throw new Error(`Unknown Normalizer type: ${F.type}`)}}normalize(F){throw Error("normalize should be implemented in subclass.")}_call(F){return this.normalize(F)}}class ue extends ae{normalize(F){const V=g(this.config.pattern);return V===null?F:F.replaceAll(V,this.config.content)}}class he extends ae{constructor(){super(...arguments);re(this,"form")}normalize(V){return V=V.normalize(this.form),V}}class N extends he{constructor(){super(...arguments);re(this,"form","NFC")}}class O extends he{constructor(){super(...arguments);re(this,"form","NFD")}}class G extends he{constructor(){super(...arguments);re(this,"form","NFKC")}}class se extends he{constructor(){super(...arguments);re(this,"form","NFKD")}}class X extends ae{normalize(F){return this.config.strip_left&&this.config.strip_right?F=F.trim():(this.config.strip_left&&(F=F.trimStart()),this.config.strip_right&&(F=F.trimEnd())),F}}class we extends ae{normalize(F){return F=v(F),F}}class _e extends ae{normalize(F){return F=F.toLowerCase(),F}}class ke extends ae{normalize(F){return F=this.config.prepend+F,F}}class He extends ae{constructor(F){super(F),this.normalizers=F.normalizers.map(V=>ae.fromConfig(V))}normalize(F){return this.normalizers.reduce((V,Y)=>Y.normalize(V),F)}}class Me extends ae{_tokenize_chinese_chars(F){const V=[];for(let Y=0;Ythis.pre_tokenize_text(Y,V)):this.pre_tokenize_text(F,V)).flat()}_call(F,V){return this.pre_tokenize(F,V)}}class j extends K{constructor(F){super(),this.pattern=new RegExp(`[^\\s${w}]+|[${w}]`,"gu")}pre_tokenize_text(F,V){return F.trim().match(this.pattern)||[]}}class fe extends K{constructor(F){super(),this.config=F,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=Z,this.text_encoder=new TextEncoder}pre_tokenize_text(F,V){return this.add_prefix_space&&!F.startsWith(" ")&&(F=" "+F),(this.use_regex?F.match(this.pattern)||[]:[F]).map(le=>Array.from(this.text_encoder.encode(le),ce=>this.byte_encoder[ce]).join(""))}}class Pe extends K{constructor(F){super(),this.config=F,this.pattern=g(this.config.pattern,this.config.invert)}pre_tokenize_text(F,V){var Y;return this.pattern===null?[]:this.config.invert?F.match(this.pattern)||[]:((Y=this.config.behavior)==null?void 0:Y.toLowerCase())==="removed"?F.split(this.pattern).filter(le=>le):h(F,this.pattern)}}class xe extends K{constructor(F){super(),this.config=F,this.pattern=new RegExp(`[^${w}]+|[${w}]+`,"gu")}pre_tokenize_text(F,V){return F.match(this.pattern)||[]}}class Ae extends K{constructor(F){super(),this.config=F;const V=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(V,"gu")}pre_tokenize_text(F,V){return F.match(this.pattern)||[]}}class Ie extends s.Callable{constructor(F){super(),this.config=F}static fromConfig(F){if(F===null)return null;switch(F.type){case"TemplateProcessing":return new We(F);case"ByteLevel":return new D(F);case"RobertaProcessing":return new Ne(F);case"BertProcessing":return new Le(F);case"Sequence":return new ee(F);default:throw new Error(`Unknown PostProcessor type: ${F.type}`)}}post_process(F,...V){throw Error("post_process should be implemented in subclass.")}_call(F,...V){return this.post_process(F,...V)}}class Le extends Ie{constructor(F){super(F),this.cls=F.cls[0],this.sep=F.sep[0]}post_process(F,V=null,{add_special_tokens:Y=!0}={}){Y&&(F=(0,i.mergeArrays)([this.cls],F,[this.sep]));let le=new Array(F.length).fill(0);if(V!==null){const ce=Y&&this instanceof Ne?[this.sep]:[],Ce=Y?[this.sep]:[];F=(0,i.mergeArrays)(F,ce,V,Ce),le=(0,i.mergeArrays)(le,new Array(V.length+ce.length+Ce.length).fill(1))}return{tokens:F,token_type_ids:le}}}class Ne extends Le{}class We extends Ie{constructor(F){super(F),this.single=F.single,this.pair=F.pair}post_process(F,V=null,{add_special_tokens:Y=!0}={}){const le=V===null?this.single:this.pair;let ce=[],Ce=[];for(const Ue of le)"SpecialToken"in Ue?Y&&(ce.push(Ue.SpecialToken.id),Ce.push(Ue.SpecialToken.type_id)):"Sequence"in Ue&&(Ue.Sequence.id==="A"?(ce=(0,i.mergeArrays)(ce,F),Ce=(0,i.mergeArrays)(Ce,new Array(F.length).fill(Ue.Sequence.type_id))):Ue.Sequence.id==="B"&&(ce=(0,i.mergeArrays)(ce,V),Ce=(0,i.mergeArrays)(Ce,new Array(V.length).fill(Ue.Sequence.type_id))));return{tokens:ce,token_type_ids:Ce}}}class D extends Ie{post_process(F,V=null){return V&&(F=(0,i.mergeArrays)(F,V)),{tokens:F}}}class ee extends Ie{constructor(F){super(F),this.processors=F.processors.map(V=>Ie.fromConfig(V))}post_process(F,V=null,Y={}){let le;for(const ce of this.processors)if(ce instanceof D)F=ce.post_process(F).tokens,V&&(V=ce.post_process(V).tokens);else{const Ce=ce.post_process(F,V,Y);F=Ce.tokens,le=Ce.token_type_ids}return{tokens:F,token_type_ids:le}}}class B extends s.Callable{constructor(F){super(),this.config=F,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets=F.trim_offsets}static fromConfig(F){if(F===null)return null;switch(F.type){case"WordPiece":return new Re(F);case"Metaspace":return new nr(F);case"ByteLevel":return new Fe(F);case"Replace":return new te(F);case"ByteFallback":return new de(F);case"Fuse":return new be(F);case"Strip":return new ve(F);case"Sequence":return new qe(F);case"CTC":return new je(F);case"BPEDecoder":return new Xe(F);default:throw new Error(`Unknown Decoder type: ${F.type}`)}}_call(F){return this.decode(F)}decode(F){return this.decode_chain(F).join("")}decode_chain(F){throw Error("`decode_chain` should be implemented in subclass.")}}class te extends B{decode_chain(F){const V=g(this.config.pattern);return V===null?F:F.map(Y=>Y.replaceAll(V,this.config.content))}}class de extends B{constructor(F){super(F),this.text_decoder=new TextDecoder}decode_chain(F){const V=[];let Y=[];for(const le of F){let ce=null;if(le.length===6&&le.startsWith("<0x")&&le.endsWith(">")){const Ce=parseInt(le.slice(3,5),16);isNaN(Ce)||(ce=Ce)}if(ce!==null)Y.push(ce);else{if(Y.length>0){const Ce=this.text_decoder.decode(Uint8Array.from(Y));V.push(Ce),Y=[]}V.push(le)}}if(Y.length>0){const le=this.text_decoder.decode(Uint8Array.from(Y));V.push(le),Y=[]}return V}}class be extends B{decode_chain(F){return[F.join("")]}}class ve extends B{constructor(F){super(F),this.content=this.config.content,this.start=this.config.start,this.stop=this.config.stop}decode_chain(F){return F.map(V=>{let Y=0;for(let ce=0;ce(Y!==0&&(V.startsWith(this.config.prefix)?V=V.replace(this.config.prefix,""):V=" "+V),this.cleanup&&(V=A(V)),V))}}class Fe extends B{constructor(F){super(F),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(F){const V=F.join(""),Y=new Uint8Array([...V].map(ce=>this.byte_decoder[ce]));return this.text_decoder.decode(Y)}decode_chain(F){const V=[];let Y=[];for(const le of F)this.added_tokens.find(ce=>ce.content===le)!==void 0?(Y.length>0&&(V.push(this.convert_tokens_to_string(Y)),Y=[]),V.push(le)):Y.push(le);return Y.length>0&&V.push(this.convert_tokens_to_string(Y)),V}}class je extends B{constructor(F){super(F),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(F){if(F.length===0)return"";const V=[F[0]];for(let ce=1;cece!==this.pad_token).join("");return this.cleanup&&(le=A(le).replaceAll(this.word_delimiter_token," ").trim()),le}decode_chain(F){return[this.convert_tokens_to_string(F)]}}class qe extends B{constructor(F){super(F),this.decoders=F.decoders.map(V=>B.fromConfig(V))}decode_chain(F){return this.decoders.reduce((V,Y)=>Y.decode_chain(V),F)}}class Xe extends B{constructor(F){super(F),this.suffix=this.config.suffix}decode_chain(F){return F.map((V,Y)=>V.replaceAll(this.suffix,Y===F.length-1?"":" "))}}class ct extends B{decode_chain(F){let V="";for(let Y=1;YY.normalize("NFKC")).join("~"):F=F.normalize("NFKC"),F}}class dr extends K{constructor(F){super(),this.tokenizers=F.pretokenizers.map(V=>K.fromConfig(V))}pre_tokenize_text(F,V){return this.tokenizers.reduce((Y,le)=>le.pre_tokenize(Y,V),[F])}}class us extends K{constructor(F){super()}pre_tokenize_text(F,V){return F.match(/\w+|[^\w\s]+/g)||[]}}class Ds extends K{constructor(F){super()}pre_tokenize_text(F,V){return M(F)}}class Dr extends K{constructor(F){super(),this.config=F,this.pattern=g(this.config.pattern),this.content=this.config.content}pre_tokenize_text(F,V){return this.pattern===null?[F]:[F.replaceAll(this.pattern,this.config.content)]}}const cs=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function Ls(pe,F,V,Y){for(const le of Object.keys(pe)){const ce=F-pe[le].length,Ce=V(le),Ue=new Array(ce).fill(Ce);pe[le]=Y==="right"?(0,i.mergeArrays)(pe[le],Ue):(0,i.mergeArrays)(Ue,pe[le])}}function jr(pe,F){for(const V of Object.keys(pe))pe[V].length=F}class dt extends s.Callable{constructor(V,Y){super();re(this,"return_token_type_ids",!1);re(this,"padding_side","right");this._tokenizer_config=Y,this.normalizer=ae.fromConfig(V.normalizer),this.pre_tokenizer=K.fromConfig(V.pre_tokenizer),this.model=Q.fromConfig(V.model,Y),this.post_processor=Ie.fromConfig(V.post_processor),this.decoder=B.fromConfig(V.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];for(const le of V.added_tokens){const ce=new R(le);this.added_tokens.push(ce),this.model.tokens_to_ids.set(ce.content,ce.id),this.model.vocab[ce.id]=ce.content,ce.special&&(this.special_tokens.push(ce.content),this.all_special_ids.push(ce.id))}if(this.additional_special_tokens=Y.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(le=>le.content)),this.added_tokens_map=new Map(this.added_tokens.map(le=>[le.content,le])),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=Y.model_max_length,this.remove_space=Y.remove_space,this.clean_up_tokenization_spaces=Y.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=Y.do_lowercase_and_remove_accent??!1,Y.padding_side&&(this.padding_side=Y.padding_side),this.legacy=!1,this.chat_template=Y.chat_template??null,Array.isArray(this.chat_template)){const le=Object.create(null);for(const{name:ce,template:Ce}of this.chat_template){if(typeof ce!="string"||typeof Ce!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');le[ce]=Ce}this.chat_template=le}this._compiled_template_cache=new Map}getToken(...V){for(const Y of V){const le=this._tokenizer_config[Y];if(le)if(typeof le=="object"){if(le.__type==="AddedToken")return le.content;throw Error(`Unknown token: ${le}`)}else return le}return null}static async from_pretrained(V,{progress_callback:Y=null,config:le=null,cache_dir:ce=null,local_files_only:Ce=!1,revision:Ue="main",legacy:Qe=null}={}){const Ke=await c(V,{progress_callback:Y,config:le,cache_dir:ce,local_files_only:Ce,revision:Ue,legacy:Qe});return new this(...Ke)}_call(V,{text_pair:Y=null,add_special_tokens:le=!0,padding:ce=!1,truncation:Ce=null,max_length:Ue=null,return_tensor:Qe=!0,return_token_type_ids:Ke=null}={}){const Ze=Array.isArray(V);let ht;if(Ze){if(V.length===0)throw Error("text array must be non-empty");if(Y!==null){if(Array.isArray(Y)){if(V.length!==Y.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");ht=V.map((kt,Wt)=>this._encode_plus(kt,{text_pair:Y[Wt],add_special_tokens:le,return_token_type_ids:Ke}))}else ht=V.map(kt=>this._encode_plus(kt,{add_special_tokens:le,return_token_type_ids:Ke}))}else{if(V==null)throw Error("text may not be null or undefined");if(Array.isArray(Y))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");ht=[this._encode_plus(V,{text_pair:Y,add_special_tokens:le,return_token_type_ids:Ke})]}if(Ue===null?ce==="max_length"?Ue=this.model_max_length:Ue=(0,o.max)(ht.map(kt=>kt.input_ids.length))[0]:Ce||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."),Ue=Math.min(Ue,this.model_max_length??1/0),ce||Ce)for(let kt=0;ktUe?Ce&&jr(ht[kt],Ue):ce&&Ls(ht[kt],Ue,Wt=>Wt==="input_ids"?this.pad_token_id:0,this.padding_side));const Ct={};if(Qe){if(!(ce&&Ce)&&ht.some(Wt=>{var Ot;for(const Vt of Object.keys(Wt))if(Wt[Vt].length!==((Ot=ht[0][Vt])==null?void 0:Ot.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 kt=[ht.length,ht[0].input_ids.length];for(const Wt of Object.keys(ht[0]))Ct[Wt]=new a.Tensor("int64",BigInt64Array.from(ht.flatMap(Ot=>Ot[Wt]).map(BigInt)),kt)}else{for(const kt of Object.keys(ht[0]))Ct[kt]=ht.map(Wt=>Wt[kt]);if(!Ze)for(const kt of Object.keys(Ct))Ct[kt]=Ct[kt][0]}return Ct}_encode_text(V){if(V===null)return null;const Y=this.added_tokens_splitter.split(V);for(let ce=0;ce0&&(Y[ce-1]=Y[ce-1].trimEnd()),Ce.rstrip&&ce{if(ce.length===0)return[];if(this.added_tokens_map.has(ce))return[ce];if(this.remove_space===!0&&(ce=ce.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(ce=y(ce)),this.normalizer!==null&&(ce=this.normalizer(ce)),ce.length===0)return[];const Ue=this.pre_tokenizer!==null?this.pre_tokenizer(ce,{section_index:Ce}):[ce];return this.model(Ue)})}_encode_plus(V,{text_pair:Y=null,add_special_tokens:le=!0,return_token_type_ids:ce=null}={}){const{tokens:Ce,token_type_ids:Ue}=this._tokenize_helper(V,{pair:Y,add_special_tokens:le}),Qe=this.model.convert_tokens_to_ids(Ce),Ke={input_ids:Qe,attention_mask:new Array(Qe.length).fill(1)};return(ce??this.return_token_type_ids)&&Ue&&(Ke.token_type_ids=Ue),Ke}_tokenize_helper(V,{pair:Y=null,add_special_tokens:le=!1}={}){const ce=this._encode_text(V),Ce=this._encode_text(Y);return this.post_processor?this.post_processor(ce,Ce,{add_special_tokens:le}):{tokens:(0,i.mergeArrays)(ce??[],Ce??[])}}tokenize(V,{pair:Y=null,add_special_tokens:le=!1}={}){return this._tokenize_helper(V,{pair:Y,add_special_tokens:le}).tokens}encode(V,{text_pair:Y=null,add_special_tokens:le=!0,return_token_type_ids:ce=null}={}){return this._encode_plus(V,{text_pair:Y,add_special_tokens:le,return_token_type_ids:ce}).input_ids}batch_decode(V,Y={}){return V instanceof a.Tensor&&(V=V.tolist()),V.map(le=>this.decode(le,Y))}decode(V,Y={}){if(V instanceof a.Tensor&&(V=E(V)),!Array.isArray(V)||V.length===0||!(0,i.isIntegralNumber)(V[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(V,Y)}decode_single(V,{skip_special_tokens:Y=!1,clean_up_tokenization_spaces:le=null}){let ce=this.model.convert_ids_to_tokens(V);Y&&(ce=ce.filter(Ue=>!this.special_tokens.includes(Ue)));let Ce=this.decoder?this.decoder(ce):ce.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(Ce=Ce.replaceAll(this.decoder.end_of_word_suffix," "),Y&&(Ce=Ce.trim())),(le??this.clean_up_tokenization_spaces)&&(Ce=A(Ce)),Ce}get_chat_template({chat_template:V=null,tools:Y=null}={}){if(this.chat_template&&typeof this.chat_template=="object"){const le=this.chat_template;if(V!==null&&Object.hasOwn(le,V))V=le[V];else if(V===null)if(Y!==null&&"tool_use"in le)V=le.tool_use;else if("default"in le)V=le.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(le).sort()}.`)}else if(V===null)if(this.chat_template)V=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 V}apply_chat_template(V,{tools:Y=null,documents:le=null,chat_template:ce=null,add_generation_prompt:Ce=!1,tokenize:Ue=!0,padding:Qe=!1,truncation:Ke=!1,max_length:Ze=null,return_tensor:ht=!0,return_dict:Ct=!1,tokenizer_kwargs:kt={},...Wt}={}){if(ce=this.get_chat_template({chat_template:ce,tools:Y}),typeof ce!="string")throw Error(`chat_template must be a string, but got ${typeof ce}`);let Ot=this._compiled_template_cache.get(ce);Ot===void 0&&(Ot=new u.Template(ce),this._compiled_template_cache.set(ce,Ot));const Vt=Object.create(null);for(const _r of cs){const Yr=this.getToken(_r);Yr&&(Vt[_r]=Yr)}const vr=Ot.render({messages:V,add_generation_prompt:Ce,tools:Y,documents:le,...Vt,...Wt});if(Ue){const _r=this._call(vr,{add_special_tokens:!1,padding:Qe,truncation:Ke,max_length:Ze,return_tensor:ht,...kt});return Ct?_r:_r.input_ids}return vr}}class qr extends dt{constructor(){super(...arguments);re(this,"return_token_type_ids",!0)}}class Vr extends dt{constructor(){super(...arguments);re(this,"return_token_type_ids",!0)}}class ps extends dt{constructor(){super(...arguments);re(this,"return_token_type_ids",!0)}}class xs extends dt{constructor(){super(...arguments);re(this,"return_token_type_ids",!0)}}class Es extends dt{constructor(){super(...arguments);re(this,"return_token_type_ids",!0)}}class Ps extends dt{constructor(){super(...arguments);re(this,"return_token_type_ids",!0)}}class zs extends dt{constructor(){super(...arguments);re(this,"return_token_type_ids",!0)}}class fr extends dt{constructor(){super(...arguments);re(this,"return_token_type_ids",!0)}}class Be extends dt{constructor(){super(...arguments);re(this,"return_token_type_ids",!0)}}class et extends dt{}class it extends dt{}class rr extends dt{constructor(V,Y){super(V,Y);re(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 zt extends dt{constructor(){super(...arguments);re(this,"return_token_type_ids",!0)}}class kr extends dt{}class hs extends dt{}class fs extends dt{}class Er extends dt{constructor(F,V){super(F,V),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.special_tokens.filter(Y=>this.languageRegex.test(Y)),this.lang_to_token=Y=>Y}_build_translation_inputs(F,V,Y){return br(this,F,V,Y)}}class ms extends Er{}class _s extends dt{}class Qr extends dt{}const Cs="▁";class Xs extends dt{constructor(V,Y){super(V,Y);re(this,"padding_side","left");this.legacy=Y.legacy??!0,this.legacy||(this.normalizer=null,this.pre_tokenizer=new wt({replacement:Cs,add_prefix_space:!0,prepend_scheme:"first"}))}_encode_text(V){if(V===null)return null;if(this.legacy||V.length===0)return super._encode_text(V);let Y=super._encode_text(Cs+V.replaceAll(Cs," "));return Y.length>1&&Y[0]===Cs&&this.special_tokens.includes(Y[1])&&(Y=Y.slice(1)),Y}}class Js extends dt{}class Ys extends dt{}class Zs extends dt{}class gs extends dt{}class en extends dt{}class tn extends dt{}class rn extends dt{}class Lr extends dt{}class Ss extends dt{}function br(pe,F,V,Y){if(!("language_codes"in pe)||!Array.isArray(pe.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in pe)||!(pe.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in pe)||typeof pe.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");const le=Y.src_lang,ce=Y.tgt_lang;if(!pe.language_codes.includes(ce))throw new Error(`Target language code "${ce}" is not valid. Must be one of: {${pe.language_codes.join(", ")}}`);if(le!==void 0){if(!pe.language_codes.includes(le))throw new Error(`Source language code "${le}" is not valid. Must be one of: {${pe.language_codes.join(", ")}}`);for(const Ce of pe.post_processor.config.single)if("SpecialToken"in Ce&&pe.languageRegex.test(Ce.SpecialToken.id)){Ce.SpecialToken.id=pe.lang_to_token(le);break}}return Y.forced_bos_token_id=pe.model.convert_tokens_to_ids([pe.lang_to_token(ce)])[0],pe._call(F,V)}class Bs extends dt{constructor(F,V){super(F,V),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.special_tokens.filter(Y=>this.languageRegex.test(Y)),this.lang_to_token=Y=>Y}_build_translation_inputs(F,V,Y){return br(this,F,V,Y)}}class Rs extends dt{constructor(F,V){super(F,V),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.special_tokens.filter(Y=>this.languageRegex.test(Y)).map(Y=>Y.slice(2,-2)),this.lang_to_token=Y=>`__${Y}__`}_build_translation_inputs(F,V,Y){return br(this,F,V,Y)}}class Ir extends dt{get timestamp_begin(){return this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0]+1}_decode_asr(F,{return_timestamps:V=!1,return_language:Y=!1,time_precision:le=null,force_full_sequences:ce=!0}={}){if(le===null)throw Error("Must specify time_precision");let Ce=null;const Ue=V==="word";function Qe(){return{language:Ce,timestamp:[null,null],text:""}}const Ke=[];let Ze=Qe(),ht=0;const Ct=this.timestamp_begin,Wt=Ct+1500;let Ot=[],Vt=[],vr=!1,_r=null;const Yr=new Set(this.all_special_ids);for(const Gt of F){const Zt=Gt.tokens,gr=Ue?Gt.token_timestamps:null;let Zr=null,ys=Ct;if("stride"in Gt){const[Rt,Jt,qt]=Gt.stride;if(ht-=Jt,_r=Rt-qt,Jt&&(ys=Jt/le+Ct),qt)for(let er=Zt.length-1;er>=0;--er){const ir=Number(Zt[er]);if(ir>=Ct){if(Zr!==null&&(ir-Ct)*le<_r)break;Zr=ir}}}let Ht=[],cr=[];for(let Rt=0;Rt=Ct&&Jt<=Wt){const qt=(Jt-Ct)*le+ht,er=(0,o.round)(qt,2);if(Zr!==null&&Jt>=Zr)vr=!0;else if(vr||Ot.length>0&&Jt0?(Ot.push(Ht),Ue&&Vt.push(cr)):Ot.every(Rt=>Rt.length===0)&&(Ze=Qe(),Ot=[],Ht=[],Vt=[],cr=[])}if(Ot.length>0){if(ce&&V)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[Gt,Zt]=this.findLongestCommonSequence(Ot,Vt),gr=this.decode(Gt);Ze.text=gr,Ue&&(Ze.words=this.collateWordTimestamps(Gt,Zt,Ce)),Ke.push(Ze)}let Tr=Object.create(null);const ws=Ke.map(Gt=>Gt.text).join("");if(V||Y){for(let Gt=0;Gt0;let Ue=Ce?[]:null,Qe=Ce?V[0]:null;for(let Ke=1;KeJt===ys[qt]&&Qe[ws+qt]<=V[Ke][gr+qt]).length:Ht=Zt.filter((Jt,qt)=>Jt===ys[qt]).length;const cr=Tr/1e4,Rt=Ht/Tr+cr;Ht>1&&Rt>ht&&(ht=Rt,Ct=[ws,Gt,gr,Zr])}const[Wt,Ot,Vt,vr]=Ct,_r=Math.floor((Ot+Wt)/2),Yr=Math.floor((vr+Vt)/2);ce.push(...Y.slice(0,_r)),Y=Ze.slice(Yr),le=Y.length,Ce&&(Ue.push(...Qe.slice(0,_r)),Qe=V[Ke].slice(Yr))}return ce.push(...Y),Ce?(Ue.push(...Qe),[ce,Ue]):[ce,[]]}collateWordTimestamps(F,V,Y){const[le,ce,Ce]=this.combineTokensIntoWords(F,Y),Ue=[];for(let Qe=0;Qe=le){const Ue=((Ce-le)*Y).toFixed(2);ce.push(`<|${Ue}|>`),ce.push([])}else ce[ce.length-1].push(Ce);return ce=ce.map(Ce=>typeof Ce=="string"?Ce:super.decode(Ce,V)),ce.join("")}splitTokensOnUnicode(F){const V=this.decode(F,{decode_with_timestamps:!0}),Y="�",le=[],ce=[],Ce=[];let Ue=[],Qe=[],Ke=0;for(let Ze=0;Ze=this.model.tokens_to_ids.get("<|endoftext|>"),Wt=Ze.startsWith(" "),Ot=Ze.trim(),Vt=Qe.test(Ot);if(kt||Wt||Vt||ce.length===0)ce.push(Ze),Ce.push(ht),Ue.push(Ct);else{const vr=ce.length-1;ce[vr]+=Ze,Ce[vr].push(...ht),Ue[vr].push(...Ct)}}return[ce,Ce,Ue]}mergePunctuations(F,V,Y,le,ce){const Ce=structuredClone(F),Ue=structuredClone(V),Qe=structuredClone(Y);let Ke=Ce.length-2,Ze=Ce.length-1;for(;Ke>=0;)Ce[Ke].startsWith(" ")&&le.includes(Ce[Ke].trim())?(Ce[Ze]=Ce[Ke]+Ce[Ze],Ue[Ze]=(0,i.mergeArrays)(Ue[Ke],Ue[Ze]),Qe[Ze]=(0,i.mergeArrays)(Qe[Ke],Qe[Ze]),Ce[Ke]="",Ue[Ke]=[],Qe[Ke]=[]):Ze=Ke,--Ke;for(Ke=0,Ze=1;Zeht),Ue.filter(ht=>ht.length>0),Qe.filter(ht=>ht.length>0)]}}class Xr extends dt{}class En extends dt{}class zr extends dt{}class Pn extends dt{constructor(F,V){super(F,V),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=this.model.vocab.filter(Y=>this.languageRegex.test(Y)),console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(F){if(F===null)return null;const[V,...Y]=F.trim().split(this.languageRegex);if(Y.length===0)return super._encode_text(V);if(Y.length===2){const[le,ce]=Y;return this.supported_language_codes.includes(le)||console.warn(`Unsupported language code "${le}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),(0,i.mergeArrays)([le],super._encode_text(ce))}}}class Ns extends dt{}class Ar extends dt{}class Jr extends dt{}class ur extends dt{}class mr extends dt{}class js extends dt{constructor(F,V){super(F,V),this.decoder=new ct({})}}class Cn extends dt{}class $s extends dt{}class Sn{static async from_pretrained(F,{progress_callback:V=null,config:Y=null,cache_dir:le=null,local_files_only:ce=!1,revision:Ce="main",legacy:Ue=null}={}){var Ct;const[Qe,Ke]=await c(F,{progress_callback:V,config:Y,cache_dir:le,local_files_only:ce,revision:Ce,legacy:Ue}),Ze=((Ct=Ke.tokenizer_class)==null?void 0:Ct.replace(/Fast$/,""))??"PreTrainedTokenizer";let ht=this.TOKENIZER_CLASS_MAPPING[Ze];return ht||(console.warn(`Unknown tokenizer class "${Ze}", attempting to construct from base class.`),ht=dt),new ht(Qe,Ke)}}re(Sn,"TOKENIZER_CLASS_MAPPING",{T5Tokenizer:kr,DistilBertTokenizer:et,CamembertTokenizer:it,DebertaTokenizer:Es,DebertaV2Tokenizer:Ps,BertTokenizer:qr,HerbertTokenizer:zs,ConvBertTokenizer:fr,RoFormerTokenizer:Be,XLMTokenizer:rr,ElectraTokenizer:zt,MobileBertTokenizer:ps,SqueezeBertTokenizer:xs,AlbertTokenizer:Vr,GPT2Tokenizer:hs,BartTokenizer:fs,MBartTokenizer:Er,MBart50Tokenizer:ms,RobertaTokenizer:_s,WhisperTokenizer:Ir,CodeGenTokenizer:Xr,CLIPTokenizer:En,SiglipTokenizer:zr,MarianTokenizer:Pn,BloomTokenizer:Qr,NllbTokenizer:Bs,M2M100Tokenizer:Rs,LlamaTokenizer:Xs,CodeLlamaTokenizer:Js,XLMRobertaTokenizer:Ys,MPNetTokenizer:Zs,FalconTokenizer:gs,GPTNeoXTokenizer:en,EsmTokenizer:tn,Wav2Vec2CTCTokenizer:Ns,BlenderbotTokenizer:Ar,BlenderbotSmallTokenizer:Jr,SpeechT5Tokenizer:ur,NougatTokenizer:mr,VitsTokenizer:js,Qwen2Tokenizer:rn,GemmaTokenizer:Lr,Grok1Tokenizer:Ss,CohereTokenizer:Cn,MgpstrTokenizer:$s,PreTrainedTokenizer:dt})},"./src/utils/audio.js":(e,r,t)=>{t.r(r),t.d(r,{RawAudio:()=>q,hamming:()=>h,hanning:()=>c,mel_filter_bank:()=>k,read_audio:()=>u,spectrogram:()=>$,window_function:()=>z});var s=t("./src/utils/hub.js"),i=t("./src/utils/maths.js"),n=t("./src/utils/core.js"),o=t("./src/env.js"),a=t("?7a2c"),l=t("./src/utils/tensor.js");async function u(U,Z){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)(U)).arrayBuffer(),J=new AudioContext({sampleRate:Z});typeof Z>"u"&&console.warn(`No sampling rate provided, using default of ${J.sampleRate}Hz.`);const ie=await J.decodeAudioData(H);let ae;if(ie.numberOfChannels===2){const ue=Math.sqrt(2),he=ie.getChannelData(0),N=ie.getChannelData(1);ae=new Float32Array(he.length);for(let O=0;O2595*Math.log10(1+U/700),kaldi:U=>1127*Math.log(1+U/700),slaney:(U,Z=1e3,H=15,J=27/Math.log(6.4))=>U>=Z?H+Math.log(U/Z)*J:3*U/200};function _(U,Z="htk"){const H=g[Z];if(!H)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof U=="number"?H(U):U.map(J=>H(J))}const E={htk:U=>700*(10**(U/2595)-1),kaldi:U=>700*(Math.exp(U/1127)-1),slaney:(U,Z=1e3,H=15,J=Math.log(6.4)/27)=>U>=H?Z*Math.exp(J*(U-H)):200*U/3};function A(U,Z="htk"){const H=E[Z];if(!H)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof U=="number"?H(U):U.map(J=>H(J))}function v(U,Z){const H=Float64Array.from({length:Z.length-1},(ue,he)=>Z[he+1]-Z[he]),J=Array.from({length:U.length},()=>new Array(Z.length));for(let ue=0;uenew Array(U.length));for(let ue=0;ueU+J*ae)}function k(U,Z,H,J,ie,ae=null,ue="htk",he=!1){if(ae!==null&&ae!=="slaney")throw new Error('norm must be one of null or "slaney"');const N=_(H,ue),O=_(J,ue),G=y(N,O,Z+2);let se=A(G,ue),X;if(he){const _e=ie/(U*2);X=_(Float64Array.from({length:U},(ke,He)=>He*_e),ue),se=G}else X=y(0,Math.floor(ie/2),U);const we=v(X,se);if(ae!==null&&ae==="slaney")for(let _e=0;_eie)throw Error(`frame_length (${H}) may not be larger than fft_length (${ie})`);if(Pe!==H)throw new Error(`Length of the window (${Pe}) must equal frame_length (${H})`);if(J<=0)throw new Error("hop_length must be greater than zero");if(ae===null&&G!==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(ue){if(he!=="reflect")throw new Error(`pad_mode="${he}" not implemented yet.`);const be=Math.floor((ie-1)/2)+1;U=P(U,be,be)}let xe=Math.floor(1+Math.floor((U.length-H)/J));Me!==null&&xexe?j&&(Le=K):Le=Ie=K);const Ne=new i.FFT(ie),We=new Float64Array(ie),D=new Float64Array(Ne.outputBufferSize),ee=new Float32Array(Ae*Le);for(let be=0;be=1;--Fe)We[Fe]-=O*We[Fe-1];We[0]*=1-O}for(let Fe=0;FeMath.pow(he,.85));break;default:throw new Error(`Unknown window type ${Z}.`)}if(H&&(ue=ue.subarray(0,U)),J===null)return ue;if(U>J)throw new Error(`Length of the window (${U}) may not be larger than frame_length (${J})`);return ue}function R(U,Z){let H=44;const J=new ArrayBuffer(H+U.length*4),ie=new DataView(J);Q(ie,0,"RIFF"),ie.setUint32(4,36+U.length*4,!0),Q(ie,8,"WAVE"),Q(ie,12,"fmt "),ie.setUint32(16,16,!0),ie.setUint16(20,3,!0),ie.setUint16(22,1,!0),ie.setUint32(24,Z,!0),ie.setUint32(28,Z*4,!0),ie.setUint16(32,4,!0),ie.setUint16(34,32,!0),Q(ie,36,"data"),ie.setUint32(40,U.length*4,!0);for(let ae=0;ae{let ae=await ie.arrayBuffer();a.writeFileSync(J,Buffer.from(ae))};else throw new Error("Unable to save because filesystem is disabled in this environment.");await H(Z,this.toBlob())}}},"./src/utils/constants.js":(e,r,t)=>{t.r(r),t.d(r,{CHAT_TEMPLATE_NAME:()=>l,CONFIG_NAME:()=>i,FEATURE_EXTRACTOR_NAME:()=>n,GENERATION_CONFIG_NAME:()=>u,GITHUB_ISSUE_URL:()=>s,IMAGE_PROCESSOR_NAME:()=>o,PROCESSOR_NAME:()=>a});const s="https://github.com/huggingface/transformers.js/issues/new/choose",i="config.json",n="preprocessor_config.json",o=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:()=>g,count:()=>v,dispatchCallback:()=>s,escapeRegExp:()=>n,isIntegralNumber:()=>a,isNullishDimension:()=>l,isTypedArray:()=>o,len:()=>A,mergeArrays:()=>c,pick:()=>E,pop:()=>p,product:()=>h,reverseDictionary:()=>i,saveBlob:()=>_});function s(y,k){y&&y(k)}function i(y){return Object.fromEntries(Object.entries(y).map(([k,P])=>[P,k]))}function n(y){return y.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function o(y){var k,P,M;return((M=(P=(k=y==null?void 0:y.prototype)==null?void 0:k.__proto__)==null?void 0:P.constructor)==null?void 0:M.name)==="TypedArray"}function a(y){return Number.isInteger(y)||typeof y=="bigint"}function l(y){return y==null||y===-1}function u(y){const k=[];let P=y;for(;Array.isArray(P);)k.push(P.length),P=P[0];return k}function p(y,k,P=void 0){const M=y[k];if(M!==void 0)return delete y[k],M;if(P===void 0)throw Error(`Key ${k} does not exist in object.`);return P}function c(...y){return Array.prototype.concat.apply([],y)}function h(...y){return y.reduce((k,P)=>k.flatMap(M=>P.map(w=>[M,w])))}function g(y,k){return Math.abs((y+k)%(2*k)-k)}function _(y,k){const P=URL.createObjectURL(k),M=document.createElement("a");M.href=P,M.download=y,M.click(),M.remove(),URL.revokeObjectURL(P)}function E(y,k){return Object.assign({},...k.map(P=>{if(y[P]!==void 0)return{[P]:y[P]}}))}function A(y){let k=0;for(const P of y)++k;return k}function v(y,k){let P=0;for(const M of y)M===k&&++P;return P}},"./src/utils/data-structures.js":(e,r,t)=>{t.r(r),t.d(r,{CharTrie:()=>i,DictionarySplitter:()=>l,PriorityQueue:()=>s,TokenLattice:()=>o});class s{constructor(p=(h,g)=>h>g,c=1/0){this._heap=[],this._comparator=p,this._maxSize=c}get size(){return this._heap.length}isEmpty(){return this.size===0}peek(){return this._heap[0]}push(...p){return this.extend(p)}extend(p){for(const c of p)if(this.size0&&this._swap(0,c),this._heap.pop(),this._siftDown(),p}replace(p){const c=this.peek();return this._heap[0]=p,this._siftDown(),c}_parent(p){return(p+1>>>1)-1}_left(p){return(p<<1)+1}_right(p){return p+1<<1}_greater(p,c){return this._comparator(this._heap[p],this._heap[c])}_swap(p,c){const h=this._heap[p];this._heap[p]=this._heap[c],this._heap[c]=h}_siftUp(){this._siftUpFrom(this.size-1)}_siftUpFrom(p){for(;p>0&&this._greater(p,this._parent(p));)this._swap(p,this._parent(p)),p=this._parent(p)}_siftDown(){let p=0;for(;this._left(p)[]),this.endNodes=Array.from({length:this.len+1},()=>[]);const g=new a(this.bosTokenId,0,0,0,0),_=new a(this.eosTokenId,1,this.len,0,0);this.nodes.push(g.clone()),this.nodes.push(_.clone()),this.beginNodes[this.len].push(_),this.endNodes[0].push(g)}insert(p,c,h,g){const _=this.nodes.length,E=new a(g,_,p,c,h);this.beginNodes[p].push(E),this.endNodes[p+c].push(E),this.nodes.push(E)}viterbi(){const p=this.len;let c=0;for(;c<=p;){if(this.beginNodes[c].length==0)return[];for(let A of this.beginNodes[c]){A.prev=null;let v=0,y=null;for(let k of this.endNodes[c]){const P=k.backtraceScore+A.score;(y===null||P>v)&&(y=k.clone(),v=P)}if(y!==null)A.prev=y,A.backtraceScore=v;else return[]}++c}const h=[],_=this.beginNodes[p][0].prev;if(_===null)return[];let E=_.clone();for(;E.prev!==null;)h.push(E.clone()),E=E.clone().prev.clone();return h.reverse(),h}piece(p){return this.chars.slice(p.pos,p.pos+p.length).join("")}tokens(){return this.viterbi().map(c=>this.piece(c))}tokenIds(){return this.viterbi().map(c=>c.tokenId)}}class a{constructor(p,c,h,g,_){this.tokenId=p,this.nodeId=c,this.pos=h,this.length=g,this.score=_,this.prev=null,this.backtraceScore=0}clone(){const p=new a(this.tokenId,this.nodeId,this.pos,this.length,this.score);return p.prev=this.prev,p.backtraceScore=this.backtraceScore,p}}class l{constructor(p){this.trie=this._buildTrie(p)}_buildTrie(p){var h;const c=Object.create(null);for(const g of p){let _=c;for(let E=0;Eg&&c.push(p.slice(g,_)),c.push(A),_+=A.length,g=_):++_}return g{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:()=>o,DEFAULT_DEVICE_DTYPE_MAPPING:()=>a,DEFAULT_DTYPE_SUFFIX_MAPPING:()=>l,isWebGpuFp16Supported:()=>n});var s=t("./src/env.js"),i=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}}(),o=Object.freeze({auto:"auto",fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16"}),a=Object.freeze({[i.DEVICE_TYPES.wasm]:o.q8}),l=Object.freeze({[o.fp32]:"",[o.fp16]:"_fp16",[o.int8]:"_int8",[o.uint8]:"_uint8",[o.q8]:"_quantized",[o.q4]:"_q4",[o.q4f16]:"_q4f16",[o.bnb4]:"_bnb4"})},"./src/utils/generic.js":(e,r,t)=>{t.r(r),t.d(r,{Callable:()=>s});const s=class{constructor(){let i=function(...n){return i._call(...n)};return Object.setPrototypeOf(i,new.target.prototype)}_call(...i){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:()=>g,getModelFile:()=>y,getModelJSON:()=>k});var s=t("?7a2c"),i=t("?a42a"),n=t("./src/env.js"),o=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(x){if(this.filePath=x,this.headers=new Headers,this.exists=s.existsSync(x),this.exists){this.status=200,this.statusText="OK";let $=s.statSync(x);this.headers.set("content-length",$.size.toString()),this.updateContentType();const z=s.createReadStream(x);this.body=new ReadableStream({start(R){z.on("data",Q=>R.enqueue(Q)),z.on("end",()=>R.close()),z.on("error",Q=>R.error(Q))},cancel(){z.destroy()}})}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",l[x]??"application/octet-stream")}clone(){let x=new u(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 s.promises.readFile(this.filePath)).buffer}async blob(){const x=await s.promises.readFile(this.filePath);return new Blob([x],{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(w,x=null,$=null){let z;try{z=new URL(w)}catch{return!1}return!(x&&!x.includes(z.protocol)||$&&!$.includes(z.hostname))}const c=/^(\b[\w\-.]+\b\/)?\b[\w\-.]{1,96}\b$/;function h(w){return!(!c.test(w)||w.includes("..")||w.includes("--")||w.endsWith(".git")||w.endsWith(".ipynb"))}async function g(w){var x;if(n.env.useFS&&!p(w,["http:","https:","blob:"]))return new u(w.toString());if(typeof process<"u"&&((x=process==null?void 0:process.release)==null?void 0:x.name)==="node"){const $=!!(Os!=null&&Os.TESTING_REMOTELY),z=n.env.version,R=new Headers;if(R.set("User-Agent",`transformers.js/${z}; is_ci/${$};`),p(w,["http:","https:"],["huggingface.co","hf.co"])){const q=(Os==null?void 0:Os.HF_TOKEN)??(Os==null?void 0:Os.HF_ACCESS_TOKEN);q&&R.set("Authorization",`Bearer ${q}`)}return fetch(w,{headers:R})}else return fetch(w)}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 E(w,x,$){if(!$)return null;const z=_[w]??`Error (${w}) occurred while trying to load file`;throw Error(`${z}: "${x}".`)}class A{constructor(x){this.path=x}async match(x){let $=i.join(this.path,x),z=new u($);if(z.exists)return z}async put(x,$,z=void 0){let R=i.join(this.path,x);try{const Q=$.headers.get("Content-Length"),q=parseInt(Q??"0");let U=0;await s.promises.mkdir(i.dirname(R),{recursive:!0});const Z=s.createWriteStream(R),H=$.body.getReader();for(;;){const{done:J,value:ie}=await H.read();if(J)break;await new Promise((ue,he)=>{Z.write(ie,N=>{if(N){he(N);return}ue()})}),U+=ie.length;const ae=q?U/q*100:0;z==null||z({progress:ae,loaded:U,total:q})}Z.close()}catch(Q){try{await s.promises.unlink(R)}catch{}throw Q}}}async function v(w,...x){for(let $ of x)try{let z=await w.match($);if(z)return z}catch{continue}}async function y(w,x,$=!0,z={},R=!1){if(!n.env.allowLocalModels){if(z.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,o.dispatchCallback)(z.progress_callback,{status:"initiate",name:w,file:x});let Q;if(!Q&&n.env.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{Q=await caches.open("transformers-cache")}catch(se){console.warn("An error occurred while opening the browser cache:",se)}}if(!Q&&n.env.useFSCache&&(Q=new A(z.cache_dir??n.env.cacheDir)),!Q&&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");Q=n.env.customCache}const q=z.revision??"main",U=M(w,x),Z=h(w),H=Z?M(n.env.localModelPath,U):U,J=M(n.env.remoteHost,n.env.remotePathTemplate.replaceAll("{model}",w).replaceAll("{revision}",encodeURIComponent(q)),x);let ie;const ae=Q instanceof A?q==="main"?U:M(w,q,x):J;let ue=!1,he;Q&&(he=await v(Q,H,ae));const N=he!==void 0;if(he===void 0){if(n.env.allowLocalModels)if(p(U,["http:","https:"])){if(z.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${U}.`);if(!n.env.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${U}.`)}else try{he=await g(H),ie=H}catch(X){console.warn(`Unable to load from local path "${H}": "${X}"`)}if(he===void 0||he.status===404){if(z.local_files_only||!n.env.allowRemoteModels){if($)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${H}".`);return null}if(!Z)throw Error(`Local file missing at "${H}" and download aborted due to invalid model ID "${w}".`);if(he=await g(J),he.status!==200)return E(he.status,J,$);ie=ae}ue=Q&&typeof Response<"u"&&he instanceof Response&&he.status===200}(0,o.dispatchCallback)(z.progress_callback,{status:"download",name:w,file:x});let O;if(!(n.apis.IS_NODE_ENV&&R)){let se;z.progress_callback?N&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent)?(se=new Uint8Array(await he.arrayBuffer()),(0,o.dispatchCallback)(z.progress_callback,{status:"progress",name:w,file:x,progress:100,loaded:se.length,total:se.length})):se=await P(he,X=>{(0,o.dispatchCallback)(z.progress_callback,{status:"progress",name:w,file:x,...X})}):se=new Uint8Array(await he.arrayBuffer()),O=se}if(ue&&ie&&await Q.match(ie)===void 0&&(O?await Q.put(ie,new Response(O,{headers:he.headers})).catch(se=>{console.warn(`Unable to add response to browser cache: ${se}.`)}):await Q.put(ie,he,z.progress_callback)),(0,o.dispatchCallback)(z.progress_callback,{status:"done",name:w,file:x}),O){if(R)throw new Error("Cannot return path in a browser environment.");return O}if(he instanceof u)return he.filePath;const G=await Q.match(ie);if(G instanceof u)return G.filePath;throw new Error("Unable to return path for response.")}async function k(w,x,$=!0,z={}){const R=await y(w,x,$,z,!1);if(R===null)return{};const q=new TextDecoder("utf-8").decode(R);return JSON.parse(q)}async function P(w,x){const $=w.headers.get("Content-Length");$===null&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let z=parseInt($??"0"),R=new Uint8Array(z),Q=0;const q=w.body.getReader();async function U(){const{done:Z,value:H}=await q.read();if(Z)return;const J=Q+H.length;if(J>z){z=J;const ae=new Uint8Array(z);ae.set(R),R=ae}R.set(H,Q),Q=J;const ie=Q/z*100;return x({progress:ie,loaded:Q,total:z}),U()}return await U(),R}function M(...w){return w=w.map((x,$)=>($&&(x=x.replace(new RegExp("^/"),"")),$!==w.length-1&&(x=x.replace(new RegExp("/$"),"")),x)),w.join("/")}},"./src/utils/image.js":(e,r,t)=>{t.r(r),t.d(r,{RawImage:()=>_,load_image:()=>E});var s=t("./src/utils/core.js"),i=t("./src/utils/hub.js"),n=t("./src/env.js"),o=t("./src/utils/tensor.js"),a=t("?2b25");let l,u,p;const c=n.apis.IS_BROWSER_ENV||n.apis.IS_WEBWORKER_ENV;if(c)l=(A,v)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(A,v)},p=self.createImageBitmap,u=self.ImageData;else if(a)p=async A=>{const y=(await A.metadata()).channels,{data:k,info:P}=await A.rotate().raw().toBuffer({resolveWithObject:!0}),M=new _(new Uint8ClampedArray(k),P.width,P.height,P.channels);return y!==void 0&&y!==P.channels&&M.convert(y),M};else throw new Error("Unable to load image processing library.");const h={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},g=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]);class _{constructor(v,y,k,P){this.data=v,this.width=y,this.height=k,this.channels=P}get size(){return[this.width,this.height]}static async read(v){if(v instanceof _)return v;if(typeof v=="string"||v instanceof URL)return await this.fromURL(v);if(v instanceof Blob)return await this.fromBlob(v);if(typeof HTMLCanvasElement<"u"&&v instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&v instanceof OffscreenCanvas)return this.fromCanvas(v);throw new Error(`Unsupported input type: ${typeof v}`)}static fromCanvas(v){if(!c)throw new Error("fromCanvas() is only supported in browser environments.");const k=v.getContext("2d").getImageData(0,0,v.width,v.height).data;return new _(k,v.width,v.height,4)}static async fromURL(v){const y=await(0,i.getFile)(v);if(y.status!==200)throw new Error(`Unable to read image from "${v}" (${y.status} ${y.statusText})`);const k=await y.blob();return this.fromBlob(k)}static async fromBlob(v){if(c){const y=await p(v),k=l(y.width,y.height).getContext("2d");return k.drawImage(y,0,0),new this(k.getImageData(0,0,y.width,y.height).data,y.width,y.height,4)}else{const y=a(await v.arrayBuffer());return await p(y)}}static fromTensor(v,y="CHW"){if(v.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${v.dims.length} dimensions.`);if(y==="CHW")v=v.transpose(1,2,0);else if(y!=="HWC")throw new Error(`Unsupported channel format: ${y}`);if(!(v.data instanceof Uint8ClampedArray||v.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${v.type}`);switch(v.dims[2]){case 1:case 2:case 3:case 4:return new _(v.data,v.dims[1],v.dims[0],v.dims[2]);default:throw new Error(`Unsupported number of channels: ${v.dims[2]}`)}}grayscale(){if(this.channels===1)return this;const v=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let y=0,k=0;y=0?$=k:R=-k,P>=0?z=P:Q=-P,x.drawImage(w,$,z,v,y,R,Q,v,y),new _(x.getImageData(0,0,v,y).data,v,y,4).convert(M)}else{let M=this.toSharp();if(k>=0&&P>=0)M=M.extract({left:Math.floor(k),top:Math.floor(P),width:v,height:y});else if(k<=0&&P<=0){const w=Math.floor(-P),x=Math.floor(-k);M=M.extend({top:w,left:x,right:v-this.width-x,bottom:y-this.height-w})}else{let w=[0,0],x=0;P<0?(w[0]=Math.floor(-P),w[1]=y-this.height-w[0]):x=Math.floor(P);let $=[0,0],z=0;k<0?($[0]=Math.floor(-k),$[1]=v-this.width-$[0]):z=Math.floor(k),M=M.extend({top:w[0],bottom:w[1],left:$[0],right:$[1]}).extract({left:z,top:x,width:v,height:y})}return await p(M)}}async toBlob(v="image/png",y=1){if(!c)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:v,quality:y})}toTensor(v="CHW"){let y=new o.Tensor("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(v!=="HWC")if(v==="CHW")y=y.permute(2,0,1);else throw new Error(`Unsupported channel format: ${v}`);return y}toCanvas(){if(!c)throw new Error("toCanvas() is only supported in browser environments.");const v=this.clone().rgba(),y=l(v.width,v.height),k=new u(v.data,v.width,v.height);return y.getContext("2d").putImageData(k,0,0),y}split(){const{data:v,width:y,height:k,channels:P}=this,M=v.constructor,w=v.length/P,x=Array.from({length:P},()=>new M(w));for(let $=0;$new _($,y,k,1))}_update(v,y,k,P=null){return this.data=v,this.width=y,this.height=k,P!==null&&(this.channels=P),this}clone(){return new _(this.data.slice(),this.width,this.height,this.channels)}convert(v){if(this.channels===v)return this;switch(v){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(v){if(c){if(n.apis.IS_WEBWORKER_ENV)throw new Error("Unable to save an image from a Web Worker.");const y=v.split(".").pop().toLowerCase(),k=g.get(y)??"image/png",P=await this.toBlob(k);(0,s.saveBlob)(v,P)}else{if(n.apis.IS_FS_AVAILABLE)return await this.toSharp().toFile(v);throw new Error("Unable to save the image because filesystem is disabled in this environment.")}}toSharp(){if(c)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 E=_.read.bind(_)},"./src/utils/maths.js":(e,r,t)=>{t.r(r),t.d(r,{FFT:()=>E,bankers_round:()=>y,cos_sim:()=>l,dot:()=>a,dynamic_time_warping:()=>k,interpolate_data:()=>s,log_softmax:()=>o,magnitude:()=>u,max:()=>c,medianFilter:()=>A,min:()=>p,permute_data:()=>i,round:()=>v,softmax:()=>n});function s(P,[M,w,x],[$,z],R="bilinear",Q=!1){const q=z/x,U=$/w,Z=new P.constructor($*z*M),H=w*x,J=$*z;for(let ie=0;ie<$;++ie)for(let ae=0;ae=0;--Q)$[Q]=q,x[Q]=M[w[Q]],q*=x[Q];const z=w.map((Q,q)=>$[w.indexOf(q)]),R=new P.constructor(P.length);for(let Q=0;Q=0;--U)q+=Z%M[U]*z[U],Z=Math.floor(Z/M[U]);R[q]=P[Q]}return[R,x]}function n(P){const M=c(P)[0],w=P.map(z=>Math.exp(z-M)),x=w.reduce((z,R)=>z+R,0);return w.map(z=>z/x)}function o(P){const M=c(P)[0];let w=0;for(let z=0;zz-M-x)}function a(P,M){let w=0;for(let x=0;xM+w*w,0))}function p(P){if(P.length===0)throw Error("Array must not be empty");let M=P[0],w=0;for(let x=1;xM&&(M=P[x],w=x);return[M,w]}function h(P){return P>0&&(P&P-1)===0}class g{constructor(M){if(this.size=M|0,this.size<=1||!h(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=M<<1,this.table=new Float64Array(this.size*2);for(let x=0;xx;x<<=1)++w;this._width=w%2===0?w-1:w,this._bitrev=new Int32Array(1<>>$&3)<>>1);for(let $=0;$>>1]=M[$];return x}toComplexArray(M,w){const x=w||this.createComplexArray();for(let $=0;$>>1],x[$+1]=0;return x}transform(M,w){if(M===w)throw new Error("Input and output buffers must be different");this._transform4(M,w,1)}realTransform(M,w){if(M===w)throw new Error("Input and output buffers must be different");this._realTransform4(M,w,1)}inverseTransform(M,w){if(M===w)throw new Error("Input and output buffers must be different");this._transform4(M,w,-1);for(let x=0;x>=2;R>=2;R>>=2){Q=$/R<<1;const J=Q>>>2;for(q=0;q<$;q+=Q){const ie=q+J-1;for(let ae=q,ue=0;ae>>1,R>>>1)}else for(q=0,U=0;q<$;q+=Q,++U){const ie=Z[U];this._singleRealTransform4(w,M,q,ie>>>1,R>>>1,x)}const H=this.table;for(R>>=2;R>=2;R>>=2){Q=$/R<<1;const ie=Q>>>1,ae=ie>>>1,ue=ae>>>1;for(q=0;q<$;q+=Q)for(let he=0,N=0;he<=ue;he+=2,N+=R){const O=q+he,G=O+ae,se=G+ae,X=se+ae,we=M[O],_e=M[O+1],ke=M[G],He=M[G+1],Me=M[se],K=M[se+1],j=M[X],fe=M[X+1],Pe=we,xe=_e,Ae=H[N],Ie=x*H[N+1],Le=ke*Ae-He*Ie,Ne=ke*Ie+He*Ae,We=H[2*N],D=x*H[2*N+1],ee=Me*We-K*D,B=Me*D+K*We,te=H[3*N],de=x*H[3*N+1],be=j*te-fe*de,ve=j*de+fe*te,Re=Pe+ee,Fe=xe+B,je=Pe-ee,qe=xe-B,Xe=Le+be,ct=Ne+ve,wt=x*(Le-be),nr=x*(Ne-ve);if(M[O]=Re+Xe,M[O+1]=Fe+ct,M[G]=je+nr,M[G+1]=qe-wt,he===0){M[se]=Re-Xe,M[se+1]=Fe-ct;continue}if(he===ue)continue;const jt=q+ae-he,dr=q+ie-he;M[jt]=je-x*nr,M[jt+1]=-qe-x*wt,M[dr]=Re-x*Xe,M[dr+1]=-Fe+x*ct}}const J=$>>>1;for(let ie=2;ie>1;++Z){const H=(Z+1-M)**2/2,J=Math.sqrt(q**2+U**2)**H,ie=H*Math.atan2(U,q),ae=2*Z;z[ae]=J*Math.cos(ie),z[ae+1]=J*Math.sin(ie),R[ae]=z[ae],R[ae+1]=-z[ae+1]}this._slicedChirpBuffer=z.subarray(w,x),this._f=new g($>>1),this._f.transform(this._chirpBuffer,R)}_transform(M,w,x){const $=this._buffer1,z=this._buffer2,R=this._outBuffer1,Q=this._outBuffer2,q=this._chirpBuffer,U=this._slicedChirpBuffer,Z=this._a;if(x)for(let H=0;H>1,ae=w[ie];$[H]=ae*U[H],$[J]=ae*U[J]}else for(let H=0;H=P.length&&(q=2*(P.length-1)-q),x[R++]=P[q]}x.sort(),w[z]=x[$]}return w}function v(P,M){const w=Math.pow(10,M);return Math.round(P*w)/w}function y(P){const M=Math.round(P);return Math.abs(P)%1===.5?M%2===0?M:M-1:M}function k(P){const M=P.length,w=P[0].length,x=[M+1,w+1],$=Array.from({length:x[0]},()=>Array(x[1]).fill(1/0));$[0][0]=0;const z=Array.from({length:x[0]},()=>Array(x[1]).fill(-1));for(let Z=1;Z0||Q>0;)switch(q.push(R-1),U.push(Q-1),z[R][Q]){case 0:--R,--Q;break;case 1:--R;break;case 2:--Q;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${R}, ${Q}]. Please file a bug report.`)}return q.reverse(),U.reverse(),[q,U]}},"./src/utils/tensor.js":(e,r,t)=>{t.r(r),t.d(r,{DataTypeMap:()=>o,Tensor:()=>a,cat:()=>w,full:()=>U,full_like:()=>Z,interpolate:()=>p,interpolate_4d:()=>c,layer_norm:()=>y,matmul:()=>h,mean:()=>R,mean_pooling:()=>v,ones:()=>H,ones_like:()=>J,permute:()=>u,quantize_embeddings:()=>he,rand:()=>ue,rfft:()=>g,slice:()=>A,stack:()=>x,std_mean:()=>z,topk:()=>_,zeros:()=>ie,zeros_like:()=>ae});var s=t("./src/utils/maths.js"),i=t("./src/backends/onnx.js"),n=t("./src/ops/registry.js");const o=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(...O){re(this,"ort_tensor");return(0,i.isONNXTensor)(O[0])?this.ort_tensor=O[0]:this.ort_tensor=new i.Tensor(O[0],O[1],O[2]),new Proxy(this,{get:(G,se)=>{if(typeof se=="string"){let X=Number(se);if(Number.isInteger(X))return G._getitem(X)}return G[se]},set:(G,se,X)=>G[se]=X})}get dims(){return this.ort_tensor.dims}set dims(O){this.ort_tensor.dims=O}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[O,...G]=this.dims;if(G.length>0){const se=G.reduce((X,we)=>X*we);for(let X=0;X0){const X=se.reduce((we,_e)=>we*_e);return this._subarray(O,X,se)}else return new a(this.type,[this.data[O]],se)}indexOf(O){const G=this.data;for(let se=0;sefe)throw new Error(`Invalid slice: ${K}`);const Pe=[Math.max(j,0),Math.min(fe,this.dims[Me])];se.push(Pe),G.push(Pe[1]-Pe[0])}else throw new Error(`Invalid slice: ${K}`)}const X=se.map(([Me,K])=>K-Me),we=X.reduce((Me,K)=>Me*K),_e=this.data,ke=new _e.constructor(we),He=this.stride();for(let Me=0;Me=0;--j){const Pe=X[j];K+=(fe%Pe+se[j][0])*He[j],fe=Math.floor(fe/Pe)}ke[Me]=_e[K]}return new a(this.type,ke,G)}permute(...O){return u(this,O)}transpose(...O){return this.permute(...O)}sum(O=null,G=!1){return this.norm(1,O,G)}norm(O="fro",G=null,se=!1){if(O==="fro")O=2;else if(typeof O=="string")throw Error(`Unsupported norm: ${O}`);const X=this.data,we=(Me,K)=>Me+K**O;if(G===null){const Me=X.reduce(we,0)**(1/O);return new a(this.type,[Me],[])}const[_e,ke,He]=$(we,this,G,se);if(O!==1)for(let Me=0;Me=0;--He){const j=this.dims[He];if(He!==G){const fe=Me%j;ke+=fe*K,K*=this.dims[He]}Me=Math.floor(Me/j)}X[_e]/=we[ke]}return this}normalize(O=2,G=1){return this.clone().normalize_(O,G)}stride(){return Q(this.dims)}squeeze(O=null){return new a(this.type,this.data,k(this.dims,O))}squeeze_(O=null){return this.dims=k(this.dims,O),this}unsqueeze(O=null){return new a(this.type,this.data,P(this.dims,O))}unsqueeze_(O=null){return this.dims=P(this.dims,O),this}flatten_(O=0,G=-1){G=(G+this.dims.length)%this.dims.length;let se=this.dims.slice(0,O),X=this.dims.slice(O,G+1),we=this.dims.slice(G+1);return this.dims=[...se,X.reduce((_e,ke)=>_e*ke,1),...we],this}flatten(O=0,G=-1){return this.clone().flatten_(O,G)}view(...O){let G=-1;for(let X=0;Xke!==G?we*_e:we,1);O[G]=se.length/X}return new a(this.type,se,O)}neg_(){const O=this.data;for(let G=0;GO?1:0;return new a("bool",G,this.dims)}lt(O){const G=new Uint8Array(this.data.length),se=this.data;for(let X=0;XMath.min(_e,ke),this,O,G,1/0);return new a(se,X,we)}max(O=null,G=!1){if(O===null){const _e=(0,s.max)(this.data)[0];return new a(this.type,[_e],[])}const[se,X,we]=$((_e,ke)=>Math.max(_e,ke),this,O,G,-1/0);return new a(se,X,we)}argmin(O=null,G=!1){if(O!==null)throw new Error("`dim !== null` not yet implemented.");const se=(0,s.min)(this.data)[1];return new a("int64",[BigInt(se)],[])}argmax(O=null,G=!1){if(O!==null)throw new Error("`dim !== null` not yet implemented.");const se=(0,s.max)(this.data)[1];return new a("int64",[BigInt(se)],[])}to(O){if(this.type===O)return this;if(!o.hasOwnProperty(O))throw new Error(`Unsupported type: ${O}`);let G;const se=["int64","uint64"].includes(this.type),X=["int64","uint64"].includes(O);return se&&!X?G=Number:!se&&X&&(G=BigInt),new a(O,o[O].from(this.data,G),this.dims)}}function l(N,O){const G=N.length,se=O.reduce((we,_e)=>we*_e);if(G!==se)throw Error(`cannot reshape array of size ${G} into shape (${O})`);let X=N;for(let we=O.length-1;we>=0;we--)X=X.reduce((_e,ke)=>{let He=_e[_e.length-1];return He.lengthnew a("int64",N,[N.length]);async function A(N,O,G,se,X){return await(await n.TensorOpRegistry.slice)({x:N,s:E(O),e:E(G),a:E(se),t:E(X??new Array(se.length).fill(1))})}function v(N,O){const G=N.data,se=O.data,X=[N.dims[0],N.dims[2]],we=new G.constructor(X[0]*X[1]),[_e,ke,He]=N.dims;let Me=0;for(let K=0;K<_e;++K){const j=K*He*ke;for(let fe=0;feG!==1):typeof O=="number"?N[O]===1&&N.splice(O,1):Array.isArray(O)&&(N=N.filter((G,se)=>G!==1||!O.includes(se))),N}function P(N,O){return O=M(O,N.length+1),N=N.slice(),N.splice(O,0,1),N}function M(N,O,G=null,se=!0){if(N<-O||N>=O){if(se)throw new Error(`IndexError: index ${N} is out of bounds for dimension${G===null?"":" "+G} with size ${O}`);return N<-O?0:O}return N<0&&(N=(N%O+O)%O),N}function w(N,O=0){O=M(O,N[0].dims.length);const G=N[0].dims.slice();G[O]=N.reduce((_e,ke)=>_e+ke.dims[O],0);const se=G.reduce((_e,ke)=>_e*ke,1),X=new N[0].data.constructor(se),we=N[0].type;if(O===0){let _e=0;for(const ke of N){const He=ke.data;X.set(He,_e),_e+=He.length}}else{let _e=0;for(let ke=0;ke=0;--fe){const Ae=Me[fe];let Ie=Pe%Ae;fe===O&&(Ie+=_e),j+=Ie*xe,xe*=G[fe],Pe=Math.floor(Pe/Ae)}X[j]=He[K]}_e+=Me[O]}}return new a(we,X,G)}function x(N,O=0){return w(N.map(G=>G.unsqueeze(O)),O)}function $(N,O,G=null,se=!1,X=null){const we=O.data,_e=O.dims;G=M(G,_e.length);const ke=_e.slice();ke[G]=1;const He=new we.constructor(we.length/_e[G]);X!==null&&He.fill(X);for(let Me=0;Me=0;--j){const xe=_e[j];if(j!==G){const Ae=fe%xe;K+=Ae*Pe,Pe*=ke[j]}fe=Math.floor(fe/xe)}He[K]=N(He[K],we[Me],Me,K)}return se||ke.splice(G,1),[O.type,He,ke]}function z(N,O=null,G=1,se=!1){const X=N.data,we=N.dims;if(O===null){const Pe=X.reduce((Le,Ne)=>Le+Ne,0)/X.length,xe=Math.sqrt(X.reduce((Le,Ne)=>Le+(Ne-Pe)**2,0)/(X.length-G)),Ae=new a(N.type,[Pe],[]);return[new a(N.type,[xe],[]),Ae]}O=M(O,we.length);const _e=R(N,O,se),ke=_e.data,[He,Me,K]=$((fe,Pe,xe,Ae)=>fe+(Pe-ke[Ae])**2,N,O,se);for(let fe=0;feMe+K,0);return new a(N.type,[He/X.length],[])}O=M(O,se.length);const[we,_e,ke]=$((He,Me)=>He+Me,N,O,G);if(se[O]!==1)for(let He=0;He<_e.length;++He)_e[He]/=se[O];return new a(we,_e,ke)}function Q(N){const O=new Array(N.length);for(let G=N.length-1,se=1;G>=0;--G)O[G]=se,se*=N[G];return O}function q(N,O,G,se){const X=N.reduce((we,_e)=>we*_e,1);return new a(G,new se(X).fill(O),N)}function U(N,O){let G,se;if(typeof O=="number")G="float32",se=Float32Array;else if(typeof O=="bigint")G="int64",se=BigInt64Array;else if(typeof O=="boolean")G="bool",se=Uint8Array;else throw new Error(`Unsupported data type: ${typeof O}`);return q(N,O,G,se)}function Z(N,O){return U(N.dims,O)}function H(N){return q(N,1n,"int64",BigInt64Array)}function J(N){return H(N.dims)}function ie(N){return q(N,0n,"int64",BigInt64Array)}function ae(N){return ie(N.dims)}function ue(N){const O=N.reduce((G,se)=>G*se,1);return new a("float32",Float32Array.from({length:O},()=>Math.random()),N)}function he(N,O){if(N.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(N.dims.at(-1)%8!==0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(O))throw new Error("The precision must be either 'binary' or 'ubinary'");const G=O==="binary",se=G?"int8":"uint8",X=G?Int8Array:Uint8Array,we=N.data,_e=new X(we.length/8);for(let ke=0;ke0?1:0,Me=Math.floor(ke/8),K=ke%8;_e[Me]|=He<<7-K,G&&K===0&&(_e[Me]-=128)}return new a(se,_e,[N.dims[0],N.dims[1]/8])}},"./src/utils/video.js":(e,r,t)=>{t.r(r),t.d(r,{RawVideo:()=>o,RawVideoFrame:()=>n,load_video:()=>a});var s=t("./src/utils/image.js"),i=t("./src/env.js");class n{constructor(u,p){this.image=u,this.timestamp=p}}class o{constructor(u,p){u.length>0&&u[0]instanceof s.RawImage&&(u=u.map((c,h)=>new n(c,(h+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(!i.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 c=[],h=document.createElement("video");if(h.crossOrigin="anonymous",h.muted=!0,typeof l=="string")h.src=l;else if(l instanceof Blob)h.src=URL.createObjectURL(l);else if(l instanceof HTMLVideoElement)h.src=l.src;else throw new Error("Invalid URL or video element provided.");if(await new Promise(k=>h.onloadedmetadata=k),h.seekable.start(0)===h.seekable.end(0)){const P=await(await fetch(h.src)).blob();h.src=URL.createObjectURL(P),await new Promise(M=>h.onloadedmetadata=M)}const g=h.duration;let _,E;u!=null?(_=u,E=u===1?0:g/(u-1)):(E=1/p,_=Math.floor(g/E));let A=[];for(let k=0;k<_;++k)A.push(u===1?g/2:k*E);const v=document.createElement("canvas");v.width=h.videoWidth,v.height=h.videoHeight;const y=v.getContext("2d",{willReadFrequently:!0});for(const k of A){h.currentTime=k,await new Promise(x=>{h.onseeked=x}),y.drawImage(h,0,0,v.width,v.height);const P=y.getImageData(0,0,v.width,v.height),M=new s.RawImage(P.data,v.width,v.height,4),w=new n(M,k);c.push(w)}return h.remove(),new o(c,g)}}},Xw={};function Ft(e){var r=Xw[e];if(r!==void 0)return r.exports;var t=Xw[e]={exports:{}};return fT[e](t,t.exports,Ft),t.exports}(()=>{var e=Object.getPrototypeOf?t=>Object.getPrototypeOf(t):t=>t.__proto__,r;Ft.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 i=Object.create(null);Ft.r(i);var n={};r=r||[null,e({}),e([]),e(e)];for(var o=s&2&&t;typeof o=="object"&&!~r.indexOf(o);o=e(o))Object.getOwnPropertyNames(o).forEach(a=>n[a]=()=>t[a]);return n.default=()=>t,Ft.d(i,n),i}})(),Ft.d=(e,r)=>{for(var t in r)Ft.o(r,t)&&!Ft.o(e,t)&&Object.defineProperty(e,t,{enumerable:!0,get:r[t]})},Ft.o=(e,r)=>Object.prototype.hasOwnProperty.call(e,r),Ft.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 ***! + \*****************************/Ft.r(m),Ft.d(m,{ASTFeatureExtractor:()=>c.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:()=>i.AutoConfig,AutoFeatureExtractor:()=>h.AutoFeatureExtractor,AutoImageProcessor:()=>E.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:()=>y.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:()=>k.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:()=>c.ClapFeatureExtractor,ClapModel:()=>t.ClapModel,ClapPreTrainedModel:()=>t.ClapPreTrainedModel,ClapTextModelWithProjection:()=>t.ClapTextModelWithProjection,ClassifierFreeGuidanceLogitsProcessor:()=>M.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:()=>c.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:()=>c.EncodecFeatureExtractor,EosTokenCriteria:()=>P.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:()=>v.Florence2Processor,ForcedBOSTokenLogitsProcessor:()=>M.ForcedBOSTokenLogitsProcessor,ForcedEOSTokenLogitsProcessor:()=>M.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:()=>v.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:()=>v.Idefics3Processor,ImageClassificationPipeline:()=>r.ImageClassificationPipeline,ImageFeatureExtractionPipeline:()=>r.ImageFeatureExtractionPipeline,ImageFeatureExtractor:()=>c.ImageFeatureExtractor,ImageMattingOutput:()=>t.ImageMattingOutput,ImageProcessor:()=>g.ImageProcessor,ImageSegmentationPipeline:()=>r.ImageSegmentationPipeline,ImageToImagePipeline:()=>r.ImageToImagePipeline,ImageToTextPipeline:()=>r.ImageToTextPipeline,InterruptableStoppingCriteria:()=>P.InterruptableStoppingCriteria,JAISLMHeadModel:()=>t.JAISLMHeadModel,JAISModel:()=>t.JAISModel,JAISPreTrainedModel:()=>t.JAISPreTrainedModel,JinaCLIPImageProcessor:()=>_.JinaCLIPImageProcessor,JinaCLIPModel:()=>t.JinaCLIPModel,JinaCLIPPreTrainedModel:()=>t.JinaCLIPPreTrainedModel,JinaCLIPProcessor:()=>v.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:()=>M.LogitsProcessor,LogitsProcessorList:()=>M.LogitsProcessorList,LogitsWarper:()=>M.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:()=>P.MaxLengthCriteria,Metric3DForDepthEstimation:()=>t.Metric3DForDepthEstimation,Metric3DPreTrainedModel:()=>t.Metric3DPreTrainedModel,Metric3Dv2ForDepthEstimation:()=>t.Metric3Dv2ForDepthEstimation,Metric3Dv2PreTrainedModel:()=>t.Metric3Dv2PreTrainedModel,MgpstrForSceneTextRecognition:()=>t.MgpstrForSceneTextRecognition,MgpstrModelOutput:()=>t.MgpstrModelOutput,MgpstrPreTrainedModel:()=>t.MgpstrPreTrainedModel,MgpstrProcessor:()=>v.MgpstrProcessor,MgpstrTokenizer:()=>s.MgpstrTokenizer,MimiDecoderModel:()=>t.MimiDecoderModel,MimiDecoderOutput:()=>t.MimiDecoderOutput,MimiEncoderModel:()=>t.MimiEncoderModel,MimiEncoderOutput:()=>t.MimiEncoderOutput,MimiModel:()=>t.MimiModel,MimiPreTrainedModel:()=>t.MimiPreTrainedModel,MinLengthLogitsProcessor:()=>M.MinLengthLogitsProcessor,MinNewTokensLengthLogitsProcessor:()=>M.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:()=>c.MoonshineFeatureExtractor,MoonshineForConditionalGeneration:()=>t.MoonshineForConditionalGeneration,MoonshineModel:()=>t.MoonshineModel,MoonshinePreTrainedModel:()=>t.MoonshinePreTrainedModel,MoonshineProcessor:()=>v.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:()=>M.NoBadWordsLogitsProcessor,NoRepeatNGramLogitsProcessor:()=>M.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:()=>v.OwlViTProcessor,Owlv2ForObjectDetection:()=>t.Owlv2ForObjectDetection,Owlv2ImageProcessor:()=>_.Owlv2ImageProcessor,Owlv2Model:()=>t.Owlv2Model,Owlv2PreTrainedModel:()=>t.Owlv2PreTrainedModel,PaliGemmaForConditionalGeneration:()=>t.PaliGemmaForConditionalGeneration,PaliGemmaPreTrainedModel:()=>t.PaliGemmaPreTrainedModel,PaliGemmaProcessor:()=>v.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:()=>v.Phi3VProcessor,PhiForCausalLM:()=>t.PhiForCausalLM,PhiModel:()=>t.PhiModel,PhiPreTrainedModel:()=>t.PhiPreTrainedModel,Pipeline:()=>r.Pipeline,PreTrainedModel:()=>t.PreTrainedModel,PreTrainedTokenizer:()=>s.PreTrainedTokenizer,PretrainedConfig:()=>i.PretrainedConfig,PretrainedMixin:()=>t.PretrainedMixin,Processor:()=>A.Processor,PvtForImageClassification:()=>t.PvtForImageClassification,PvtImageProcessor:()=>_.PvtImageProcessor,PvtModel:()=>t.PvtModel,PvtPreTrainedModel:()=>t.PvtPreTrainedModel,PyAnnoteFeatureExtractor:()=>c.PyAnnoteFeatureExtractor,PyAnnoteForAudioFrameClassification:()=>t.PyAnnoteForAudioFrameClassification,PyAnnoteModel:()=>t.PyAnnoteModel,PyAnnotePreTrainedModel:()=>t.PyAnnotePreTrainedModel,PyAnnoteProcessor:()=>v.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:()=>v.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:()=>o.RawImage,RawVideo:()=>a.RawVideo,RawVideoFrame:()=>a.RawVideoFrame,RepetitionPenaltyLogitsProcessor:()=>M.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:()=>v.SamProcessor,SapiensForDepthEstimation:()=>t.SapiensForDepthEstimation,SapiensForNormalEstimation:()=>t.SapiensForNormalEstimation,SapiensForSemanticSegmentation:()=>t.SapiensForSemanticSegmentation,SapiensPreTrainedModel:()=>t.SapiensPreTrainedModel,SeamlessM4TFeatureExtractor:()=>c.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:()=>v.SmolVLMProcessor,SnacDecoderModel:()=>t.SnacDecoderModel,SnacEncoderModel:()=>t.SnacEncoderModel,SnacFeatureExtractor:()=>c.SnacFeatureExtractor,SnacModel:()=>t.SnacModel,SnacPreTrainedModel:()=>t.SnacPreTrainedModel,SpeechT5FeatureExtractor:()=>c.SpeechT5FeatureExtractor,SpeechT5ForSpeechToText:()=>t.SpeechT5ForSpeechToText,SpeechT5ForTextToSpeech:()=>t.SpeechT5ForTextToSpeech,SpeechT5HifiGan:()=>t.SpeechT5HifiGan,SpeechT5Model:()=>t.SpeechT5Model,SpeechT5PreTrainedModel:()=>t.SpeechT5PreTrainedModel,SpeechT5Processor:()=>v.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:()=>P.StoppingCriteria,StoppingCriteriaList:()=>P.StoppingCriteriaList,StyleTextToSpeech2Model:()=>t.StyleTextToSpeech2Model,StyleTextToSpeech2PreTrainedModel:()=>t.StyleTextToSpeech2PreTrainedModel,SummarizationPipeline:()=>r.SummarizationPipeline,SuppressTokensAtBeginLogitsProcessor:()=>M.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:()=>M.TemperatureLogitsWarper,Tensor:()=>l.Tensor,Text2TextGenerationPipeline:()=>r.Text2TextGenerationPipeline,TextClassificationPipeline:()=>r.TextClassificationPipeline,TextGenerationPipeline:()=>r.TextGenerationPipeline,TextStreamer:()=>k.TextStreamer,TextToAudioPipeline:()=>r.TextToAudioPipeline,TokenClassificationPipeline:()=>r.TokenClassificationPipeline,TokenClassifierOutput:()=>t.TokenClassifierOutput,TokenizerModel:()=>s.TokenizerModel,TopKLogitsWarper:()=>M.TopKLogitsWarper,TopPLogitsWarper:()=>M.TopPLogitsWarper,TrOCRForCausalLM:()=>t.TrOCRForCausalLM,TrOCRPreTrainedModel:()=>t.TrOCRPreTrainedModel,TranslationPipeline:()=>r.TranslationPipeline,UltravoxModel:()=>t.UltravoxModel,UltravoxPreTrainedModel:()=>t.UltravoxPreTrainedModel,UltravoxProcessor:()=>v.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:()=>v.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:()=>c.Wav2Vec2FeatureExtractor,Wav2Vec2ForAudioFrameClassification:()=>t.Wav2Vec2ForAudioFrameClassification,Wav2Vec2ForCTC:()=>t.Wav2Vec2ForCTC,Wav2Vec2ForSequenceClassification:()=>t.Wav2Vec2ForSequenceClassification,Wav2Vec2Model:()=>t.Wav2Vec2Model,Wav2Vec2PreTrainedModel:()=>t.Wav2Vec2PreTrainedModel,Wav2Vec2Processor:()=>v.Wav2Vec2Processor,Wav2Vec2ProcessorWithLM:()=>v.Wav2Vec2ProcessorWithLM,WavLMForAudioFrameClassification:()=>t.WavLMForAudioFrameClassification,WavLMForCTC:()=>t.WavLMForCTC,WavLMForSequenceClassification:()=>t.WavLMForSequenceClassification,WavLMForXVector:()=>t.WavLMForXVector,WavLMModel:()=>t.WavLMModel,WavLMPreTrainedModel:()=>t.WavLMPreTrainedModel,WeSpeakerFeatureExtractor:()=>c.WeSpeakerFeatureExtractor,WeSpeakerResNetModel:()=>t.WeSpeakerResNetModel,WeSpeakerResNetPreTrainedModel:()=>t.WeSpeakerResNetPreTrainedModel,WhisperFeatureExtractor:()=>c.WhisperFeatureExtractor,WhisperForConditionalGeneration:()=>t.WhisperForConditionalGeneration,WhisperModel:()=>t.WhisperModel,WhisperPreTrainedModel:()=>t.WhisperPreTrainedModel,WhisperProcessor:()=>v.WhisperProcessor,WhisperTextStreamer:()=>k.WhisperTextStreamer,WhisperTimeStampLogitsProcessor:()=>M.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:()=>i.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:()=>o.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=Ft("./src/env.js"),r=Ft("./src/pipelines.js"),t=Ft("./src/models.js"),s=Ft("./src/tokenizers.js"),i=Ft("./src/configs.js"),n=Ft("./src/utils/audio.js"),o=Ft("./src/utils/image.js"),a=Ft("./src/utils/video.js"),l=Ft("./src/utils/tensor.js"),u=Ft("./src/utils/maths.js"),p=Ft("./src/base/feature_extraction_utils.js"),c=Ft("./src/models/feature_extractors.js"),h=Ft("./src/models/auto/feature_extraction_auto.js"),g=Ft("./src/base/image_processors_utils.js"),_=Ft("./src/models/image_processors.js"),E=Ft("./src/models/auto/image_processing_auto.js"),A=Ft("./src/base/processing_utils.js"),v=Ft("./src/models/processors.js"),y=Ft("./src/models/auto/processing_auto.js"),k=Ft("./src/generation/streamers.js"),P=Ft("./src/generation/stopping_criteria.js"),M=Ft("./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,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;var mT=m.AutoModelForVision2Seq;m.AutoModelForXVector,m.AutoModelForZeroShotObjectDetection;var _T=m.AutoProcessor;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 gT=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 wT=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;var yT=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;const MT=1024;let bT=!1;async function vT(){try{const e=await navigator.gpu.requestAdapter();if(!e)throw new Error("WebGPU is not supported (no adapter found)");bT=e.features.has("shader-f16")}catch(e){self.postMessage({status:"error",data:e.toString()})}}class Xu{static async getInstance(r=null){return this.processor??(this.processor=_T.from_pretrained(this.model_id,{progress_callback:r})),this.model??(this.model=mT.from_pretrained(this.model_id,{dtype:"fp32",device:"webgpu",progress_callback:r})),Promise.all([this.processor,this.model])}}re(Xu,"model_id","HuggingFaceTB/SmolVLM-256M-Instruct");const La=new gT;async function TT(e){e=e.slice(-1);const[r,t]=await Xu.getInstance(),s=await Promise.all(e.map(E=>E.content).flat(1/0).filter(E=>E.image!==void 0).map(E=>yT(E.image))),i=r.apply_chat_template(e,{add_generation_prompt:!0}),n=await r(i,s,{});let o,a=0,l;const u=E=>{o??(o=performance.now()),a++>0&&(l=a/(performance.now()-o)*1e3)},p=E=>{self.postMessage({status:"update",output:E,tps:l,numTokens:a})},c=new wT(r.tokenizer,{skip_prompt:!0,skip_special_tokens:!0,callback_function:p,token_callback_function:u});self.postMessage({status:"start"});const{past_key_values:h,sequences:g}=await t.generate({...n,do_sample:!1,repetition_penalty:1.1,max_new_tokens:MT,streamer:c,stopping_criteria:La,return_dict_in_generate:!0}).catch(E=>{self.postMessage({status:"error",data:E.toString()})}),_=r.batch_decode(g,{skip_special_tokens:!0});self.postMessage({status:"complete",output:_})}async function xT(){self.postMessage({status:"loading",data:"Loading model..."});const[e,r]=await Xu.getInstance(t=>{self.postMessage(t)});self.postMessage({status:"ready"})}self.addEventListener("message",async e=>{const{type:r,data:t}=e.data;switch(r){case"check":vT();break;case"load":xT();break;case"generate":La.reset(),TT(t);break;case"interrupt":La.interrupt();break;case"reset":La.reset();break}})})(); diff --git a/assets/worker-y4d95NqO.js b/assets/worker-y4d95NqO.js deleted file mode 100644 index e29c161064fbb2e40755a18e6cc517d51e5788e0..0000000000000000000000000000000000000000 --- a/assets/worker-y4d95NqO.js +++ /dev/null @@ -1,2787 +0,0 @@ -var Lf=Object.defineProperty;var zf=(dr,Xr,no)=>Xr in dr?Lf(dr,Xr,{enumerable:!0,configurable:!0,writable:!0,value:no}):dr[Xr]=no;var _e=(dr,Xr,no)=>zf(dr,typeof Xr!="symbol"?Xr+"":Xr,no);(function(){"use strict";var dr={},Xr={"./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm":(De,A,r)=>{De.exports=r.p+"ort-wasm-simd-threaded.jsep.wasm"},"./node_modules/onnxruntime-web/dist/ort.bundle.min.mjs?46eb":(De,A,r)=>{De.exports=r.p+"ort.bundle.min.mjs"},"?2ce3":()=>{},"?7a2c":()=>{},"?a42a":()=>{},"?2b25":()=>{},"?569f":()=>{},"?3f59":()=>{},"?154a":()=>{},"./node_modules/@huggingface/jinja/dist/index.js":(De,A,r)=>{r.r(A),r.d(A,{Environment:()=>st,Interpreter:()=>dt,Template:()=>ht,parse:()=>ye,tokenize:()=>y});var f=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",EndIf:"EndIf",ElseIf:"ElseIf",EndFor:"EndFor",And:"And",Or:"Or",Not:"UnaryOperator",Macro:"Macro",EndMacro:"EndMacro"}),D=Object.freeze({set:f.Set,for:f.For,in:f.In,is:f.Is,if:f.If,else:f.Else,endif:f.EndIf,elif:f.ElseIf,endfor:f.EndFor,and:f.And,or:f.Or,not:f.Not,"not in":f.NotIn,macro:f.Macro,endmacro:f.EndMacro,true:f.BooleanLiteral,false:f.BooleanLiteral,none:f.NullLiteral,True:f.BooleanLiteral,False:f.BooleanLiteral,None:f.NullLiteral}),U=class{constructor(L,ie){this.value=L,this.type=ie}};function Y(L){return/\w/.test(L)}function R(L){return/[0-9]/.test(L)}var g=[["{%",f.OpenStatement],["%}",f.CloseStatement],["{{",f.OpenExpression],["}}",f.CloseExpression],["(",f.OpenParen],[")",f.CloseParen],["{",f.OpenCurlyBracket],["}",f.CloseCurlyBracket],["[",f.OpenSquareBracket],["]",f.CloseSquareBracket],[",",f.Comma],[".",f.Dot],[":",f.Colon],["|",f.Pipe],["<=",f.ComparisonBinaryOperator],[">=",f.ComparisonBinaryOperator],["==",f.ComparisonBinaryOperator],["!=",f.ComparisonBinaryOperator],["<",f.ComparisonBinaryOperator],[">",f.ComparisonBinaryOperator],["+",f.AdditiveBinaryOperator],["-",f.AdditiveBinaryOperator],["*",f.MultiplicativeBinaryOperator],["/",f.MultiplicativeBinaryOperator],["%",f.MultiplicativeBinaryOperator],["=",f.Equals]],v=new Map([["n",` -`],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function M(L,ie={}){return L.endsWith(` -`)&&(L=L.slice(0,-1)),L=L.replace(/{#.*?#}/gs,"{##}"),ie.lstrip_blocks&&(L=L.replace(/^[ \t]*({[#%])/gm,"$1")),ie.trim_blocks&&(L=L.replace(/([#%]})\n/g,"$1")),L.replace(/{##}/g,"").replace(/-%}\s*/g,"%}").replace(/\s*{%-/g,"{%").replace(/-}}\s*/g,"}}").replace(/\s*{{-/g,"{{")}function y(L,ie={}){var Je,ut,mt;const H=[],me=M(L,ie);let $e=0;const We=vt=>{let kt="";for(;vt(me[$e]);){if(me[$e]==="\\"){if(++$e,$e>=me.length)throw new SyntaxError("Unexpected end of input");const At=me[$e++],os=v.get(At);if(os===void 0)throw new SyntaxError(`Unexpected escaped character: ${At}`);kt+=os;continue}if(kt+=me[$e++],$e>=me.length)throw new SyntaxError("Unexpected end of input")}return kt};e:for(;$e0){H.push(new U(At,f.Text));continue}}We(At=>/\s/.test(At));const kt=me[$e];if(kt==="-"||kt==="+"){const At=(ut=H.at(-1))==null?void 0:ut.type;if(At===f.Text||At===void 0)throw new SyntaxError(`Unexpected character: ${kt}`);switch(At){case f.Identifier:case f.NumericLiteral:case f.BooleanLiteral:case f.NullLiteral:case f.StringLiteral:case f.CloseParen:case f.CloseSquareBracket:break;default:{++$e;const os=We(R);H.push(new U(`${kt}${os}`,os.length>0?f.NumericLiteral:f.UnaryOperator));continue}}}for(const[At,os]of g)if(me.slice($e,$e+At.length)===At){H.push(new U(At,os)),$e+=At.length;continue e}if(kt==="'"||kt==='"'){++$e;const At=We(os=>os!==kt);H.push(new U(At,f.StringLiteral)),++$e;continue}if(R(kt)){const At=We(R);H.push(new U(At,f.NumericLiteral));continue}if(Y(kt)){const At=We(Y),os=Object.hasOwn(D,At)?D[At]:f.Identifier;os===f.In&&((mt=H.at(-1))==null?void 0:mt.type)===f.Not?(H.pop(),H.push(new U("not in",f.NotIn))):H.push(new U(At,os));continue}throw new SyntaxError(`Unexpected character: ${kt}`)}return H}var b=class{constructor(){_e(this,"type","Statement")}},I=class extends b{constructor(ie){super();_e(this,"type","Program");this.body=ie}},K=class extends b{constructor(ie,H,me){super();_e(this,"type","If");this.test=ie,this.body=H,this.alternate=me}},te=class extends b{constructor(ie,H,me,$e){super();_e(this,"type","For");this.loopvar=ie,this.iterable=H,this.body=me,this.defaultBlock=$e}},ne=class extends b{constructor(ie,H){super();_e(this,"type","Set");this.assignee=ie,this.value=H}},W=class extends b{constructor(ie,H,me){super();_e(this,"type","Macro");this.name=ie,this.args=H,this.body=me}},j=class extends b{constructor(){super(...arguments);_e(this,"type","Expression")}},q=class extends j{constructor(ie,H,me){super();_e(this,"type","MemberExpression");this.object=ie,this.property=H,this.computed=me}},$=class extends j{constructor(ie,H){super();_e(this,"type","CallExpression");this.callee=ie,this.args=H}},S=class extends j{constructor(ie){super();_e(this,"type","Identifier");this.value=ie}},w=class extends j{constructor(ie){super();_e(this,"type","Literal");this.value=ie}},x=class extends w{constructor(){super(...arguments);_e(this,"type","NumericLiteral")}},O=class extends w{constructor(){super(...arguments);_e(this,"type","StringLiteral")}},ae=class extends w{constructor(){super(...arguments);_e(this,"type","BooleanLiteral")}},oe=class extends w{constructor(){super(...arguments);_e(this,"type","NullLiteral")}},ve=class extends w{constructor(){super(...arguments);_e(this,"type","ArrayLiteral")}},we=class extends w{constructor(){super(...arguments);_e(this,"type","TupleLiteral")}},re=class extends w{constructor(){super(...arguments);_e(this,"type","ObjectLiteral")}},xe=class extends j{constructor(ie,H,me){super();_e(this,"type","BinaryExpression");this.operator=ie,this.left=H,this.right=me}},ce=class extends j{constructor(ie,H){super();_e(this,"type","FilterExpression");this.operand=ie,this.filter=H}},ke=class extends j{constructor(ie,H){super();_e(this,"type","SelectExpression");this.iterable=ie,this.test=H}},Ie=class extends j{constructor(ie,H,me){super();_e(this,"type","TestExpression");this.operand=ie,this.negate=H,this.test=me}},Ee=class extends j{constructor(ie,H){super();_e(this,"type","UnaryExpression");this.operator=ie,this.argument=H}},tt=class extends j{constructor(ie=void 0,H=void 0,me=void 0){super();_e(this,"type","SliceExpression");this.start=ie,this.stop=H,this.step=me}},Ge=class extends j{constructor(ie,H){super();_e(this,"type","KeywordArgumentExpression");this.key=ie,this.value=H}};function ye(L){const ie=new I([]);let H=0;function me(ot,Tt){const Dt=L[H++];if(!Dt||Dt.type!==ot)throw new Error(`Parser Error: ${Tt}. ${Dt.type} !== ${ot}.`);return Dt}function $e(){switch(L[H].type){case f.Text:return ut();case f.OpenStatement:return mt();case f.OpenExpression:return vt();default:throw new SyntaxError(`Unexpected token type: ${L[H].type}`)}}function We(...ot){return H+ot.length<=L.length&&ot.some((Tt,Dt)=>Tt!==L[H+Dt].type)}function Je(...ot){return H+ot.length<=L.length&&ot.every((Tt,Dt)=>Tt===L[H+Dt].type)}function ut(){return new O(me(f.Text,"Expected text token").value)}function mt(){me(f.OpenStatement,"Expected opening statement token");let ot;switch(L[H].type){case f.Set:++H,ot=kt(),me(f.CloseStatement,"Expected closing statement token");break;case f.If:++H,ot=At(),me(f.OpenStatement,"Expected {% token"),me(f.EndIf,"Expected endif token"),me(f.CloseStatement,"Expected %} token");break;case f.Macro:++H,ot=os(),me(f.OpenStatement,"Expected {% token"),me(f.EndMacro,"Expected endmacro token"),me(f.CloseStatement,"Expected %} token");break;case f.For:++H,ot=Cs(),me(f.OpenStatement,"Expected {% token"),me(f.EndFor,"Expected endfor token"),me(f.CloseStatement,"Expected %} token");break;default:throw new SyntaxError(`Unknown statement type: ${L[H].type}`)}return ot}function vt(){me(f.OpenExpression,"Expected opening expression token");const ot=Ds();return me(f.CloseExpression,"Expected closing expression token"),ot}function kt(){const ot=Ds();if(Je(f.Equals)){++H;const Tt=kt();return new ne(ot,Tt)}return ot}function At(){var Vs,jr,Or,Ms,lr,Os,Er,es;const ot=Ds();me(f.CloseStatement,"Expected closing statement token");const Tt=[],Dt=[];for(;!(((Vs=L[H])==null?void 0:Vs.type)===f.OpenStatement&&(((jr=L[H+1])==null?void 0:jr.type)===f.ElseIf||((Or=L[H+1])==null?void 0:Or.type)===f.Else||((Ms=L[H+1])==null?void 0:Ms.type)===f.EndIf));)Tt.push($e());if(((lr=L[H])==null?void 0:lr.type)===f.OpenStatement&&((Os=L[H+1])==null?void 0:Os.type)!==f.EndIf)if(++H,Je(f.ElseIf))me(f.ElseIf,"Expected elseif token"),Dt.push(At());else for(me(f.Else,"Expected else token"),me(f.CloseStatement,"Expected closing statement token");!(((Er=L[H])==null?void 0:Er.type)===f.OpenStatement&&((es=L[H+1])==null?void 0:es.type)===f.EndIf);)Dt.push($e());return new K(ot,Tt,Dt)}function os(){const ot=ar();if(ot.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");const Tt=Ar();me(f.CloseStatement,"Expected closing statement token");const Dt=[];for(;We(f.OpenStatement,f.EndMacro);)Dt.push($e());return new W(ot,Tt,Dt)}function ys(ot=!1){const Tt=ot?ar:Ds,Dt=[Tt()],Vs=Je(f.Comma);for(;Vs&&(++H,Dt.push(Tt()),!!Je(f.Comma)););return Vs?new we(Dt):Dt[0]}function Cs(){const ot=ys(!0);if(!(ot instanceof S||ot instanceof we))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${ot.type} instead`);me(f.In,"Expected `in` keyword following loop variable");const Tt=Ds();me(f.CloseStatement,"Expected closing statement token");const Dt=[];for(;We(f.OpenStatement,f.EndFor)&&We(f.OpenStatement,f.Else);)Dt.push($e());const Vs=[];if(Je(f.OpenStatement,f.Else))for(++H,++H,me(f.CloseStatement,"Expected closing statement token");We(f.OpenStatement,f.EndFor);)Vs.push($e());return new te(ot,Tt,Dt,Vs)}function Ds(){return sr()}function sr(){const ot=Sr();if(Je(f.If)){++H;const Tt=Sr();if(Je(f.Else)){++H;const Dt=Sr();return new K(Tt,[ot],[Dt])}else return new ke(ot,Tt)}return ot}function Sr(){let ot=Yr();for(;Je(f.Or);){const Tt=L[H];++H;const Dt=Yr();ot=new xe(Tt,ot,Dt)}return ot}function Yr(){let ot=Us();for(;Je(f.And);){const Tt=L[H];++H;const Dt=Us();ot=new xe(Tt,ot,Dt)}return ot}function Us(){let ot;for(;Je(f.Not);){const Tt=L[H];++H;const Dt=Us();ot=new Ee(Tt,Dt)}return ot??Pr()}function Pr(){let ot=Nt();for(;Je(f.ComparisonBinaryOperator)||Je(f.In)||Je(f.NotIn);){const Tt=L[H];++H;const Dt=Nt();ot=new xe(Tt,ot,Dt)}return ot}function Nt(){let ot=Ir();for(;Je(f.AdditiveBinaryOperator);){const Tt=L[H];++H;const Dt=Ir();ot=new xe(Tt,ot,Dt)}return ot}function Jr(){const ot=en();return Je(f.OpenParen)?$r(ot):ot}function $r(ot){let Tt=new $(ot,Ar());return Je(f.OpenParen)&&(Tt=$r(Tt)),Tt}function Ar(){me(f.OpenParen,"Expected opening parenthesis for arguments list");const ot=Zr();return me(f.CloseParen,"Expected closing parenthesis for arguments list"),ot}function Zr(){const ot=[];for(;!Je(f.CloseParen);){let Tt=Ds();if(Je(f.Equals)){if(++H,!(Tt instanceof S))throw new SyntaxError("Expected identifier for keyword argument");const Dt=Ds();Tt=new Ge(Tt,Dt)}ot.push(Tt),Je(f.Comma)&&++H}return ot}function cr(){const ot=[];let Tt=!1;for(;!Je(f.CloseSquareBracket);)Je(f.Colon)?(ot.push(void 0),++H,Tt=!0):(ot.push(Ds()),Je(f.Colon)&&(++H,Tt=!0));if(ot.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(Tt){if(ot.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new tt(...ot)}return ot[0]}function en(){let ot=ar();for(;Je(f.Dot)||Je(f.OpenSquareBracket);){const Tt=L[H];++H;let Dt;const Vs=Tt.type!==f.Dot;if(Vs)Dt=cr(),me(f.CloseSquareBracket,"Expected closing square bracket");else if(Dt=ar(),Dt.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");ot=new q(ot,Dt,Vs)}return ot}function Ir(){let ot=Rr();for(;Je(f.MultiplicativeBinaryOperator);){const Tt=L[H];++H;const Dt=Rr();ot=new xe(Tt,ot,Dt)}return ot}function Rr(){let ot=Nr();for(;Je(f.Is);){++H;const Tt=Je(f.Not);Tt&&++H;let Dt=ar();if(Dt instanceof ae?Dt=new S(Dt.value.toString()):Dt instanceof oe&&(Dt=new S("none")),!(Dt instanceof S))throw new SyntaxError("Expected identifier for the test");ot=new Ie(ot,Tt,Dt)}return ot}function Nr(){let ot=Jr();for(;Je(f.Pipe);){++H;let Tt=ar();if(!(Tt instanceof S))throw new SyntaxError("Expected identifier for the filter");Je(f.OpenParen)&&(Tt=$r(Tt)),ot=new ce(ot,Tt)}return ot}function ar(){const ot=L[H];switch(ot.type){case f.NumericLiteral:return++H,new x(Number(ot.value));case f.StringLiteral:return++H,new O(ot.value);case f.BooleanLiteral:return++H,new ae(ot.value.toLowerCase()==="true");case f.NullLiteral:return++H,new oe(null);case f.Identifier:return++H,new S(ot.value);case f.OpenParen:{++H;const Tt=ys();if(L[H].type!==f.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${L[H].type} instead`);return++H,Tt}case f.OpenSquareBracket:{++H;const Tt=[];for(;!Je(f.CloseSquareBracket);)Tt.push(Ds()),Je(f.Comma)&&++H;return++H,new ve(Tt)}case f.OpenCurlyBracket:{++H;const Tt=new Map;for(;!Je(f.CloseCurlyBracket);){const Dt=Ds();me(f.Colon,"Expected colon between key and value in object literal");const Vs=Ds();Tt.set(Dt,Vs),Je(f.Comma)&&++H}return++H,new re(Tt)}default:throw new SyntaxError(`Unexpected token: ${ot.type}`)}}for(;H=0?(ie=(ie??(ie=0))<0?Math.max(L.length+ie,0):Math.min(ie,L.length),H=(H??(H=L.length))<0?Math.max(L.length+H,0):Math.min(H,L.length)):(ie=(ie??(ie=L.length-1))<0?Math.max(L.length+ie,-1):Math.min(ie,L.length-1),H=(H??(H=-1))<-1?Math.max(L.length+H,-1):Math.min(H,L.length-1));const We=[];for(let Je=ie;$e*Je<$e*H;Je+=me)We.push(L[Je]);return We}function Ce(L){return L.replace(/\b\w/g,ie=>ie.toUpperCase())}var Be=class{constructor(L=void 0){_e(this,"type","RuntimeValue");_e(this,"value");_e(this,"builtins",new Map);this.value=L}__bool__(){return new Ke(!!this.value)}},Ze=class extends Be{constructor(){super(...arguments);_e(this,"type","NumericValue")}},se=class extends Be{constructor(){super(...arguments);_e(this,"type","StringValue");_e(this,"builtins",new Map([["upper",new Ve(()=>new se(this.value.toUpperCase()))],["lower",new Ve(()=>new se(this.value.toLowerCase()))],["strip",new Ve(()=>new se(this.value.trim()))],["title",new Ve(()=>new se(Ce(this.value)))],["length",new Ze(this.value.length)],["rstrip",new Ve(()=>new se(this.value.trimEnd()))],["lstrip",new Ve(()=>new se(this.value.trimStart()))]]))}},Ke=class extends Be{constructor(){super(...arguments);_e(this,"type","BooleanValue")}},je=class extends Be{constructor(){super(...arguments);_e(this,"type","ObjectValue");_e(this,"builtins",new Map([["get",new Ve(([ie,H])=>{if(!(ie instanceof se))throw new Error(`Object key must be a string: got ${ie.type}`);return this.value.get(ie.value)??H??new Ne})],["items",new Ve(()=>new Te(Array.from(this.value.entries()).map(([ie,H])=>new Te([new se(ie),H]))))]]))}__bool__(){return new Ke(this.value.size>0)}},le=class extends je{constructor(){super(...arguments);_e(this,"type","KeywordArgumentsValue")}},Te=class extends Be{constructor(){super(...arguments);_e(this,"type","ArrayValue");_e(this,"builtins",new Map([["length",new Ze(this.value.length)]]))}__bool__(){return new Ke(this.value.length>0)}},Ue=class extends Te{constructor(){super(...arguments);_e(this,"type","TupleValue")}},Ve=class extends Be{constructor(){super(...arguments);_e(this,"type","FunctionValue")}},Ne=class extends Be{constructor(){super(...arguments);_e(this,"type","NullValue")}},Re=class extends Be{constructor(){super(...arguments);_e(this,"type","UndefinedValue")}},st=class{constructor(L){_e(this,"variables",new Map([["namespace",new Ve(L=>{if(L.length===0)return new je(new Map);if(L.length!==1||!(L[0]instanceof je))throw new Error("`namespace` expects either zero arguments or a single object argument");return L[0]})]]));_e(this,"tests",new Map([["boolean",L=>L.type==="BooleanValue"],["callable",L=>L instanceof Ve],["odd",L=>{if(L.type!=="NumericValue")throw new Error(`Cannot apply test "odd" to type: ${L.type}`);return L.value%2!==0}],["even",L=>{if(L.type!=="NumericValue")throw new Error(`Cannot apply test "even" to type: ${L.type}`);return L.value%2===0}],["false",L=>L.type==="BooleanValue"&&!L.value],["true",L=>L.type==="BooleanValue"&&L.value],["none",L=>L.type==="NullValue"],["string",L=>L.type==="StringValue"],["number",L=>L.type==="NumericValue"],["integer",L=>L.type==="NumericValue"&&Number.isInteger(L.value)],["iterable",L=>L.type==="ArrayValue"||L.type==="StringValue"],["mapping",L=>L.type==="ObjectValue"],["lower",L=>{const ie=L.value;return L.type==="StringValue"&&ie===ie.toLowerCase()}],["upper",L=>{const ie=L.value;return L.type==="StringValue"&&ie===ie.toUpperCase()}],["none",L=>L.type==="NullValue"],["defined",L=>L.type!=="UndefinedValue"],["undefined",L=>L.type==="UndefinedValue"],["equalto",(L,ie)=>L.value===ie.value],["eq",(L,ie)=>L.value===ie.value]]));this.parent=L}set(L,ie){return this.declareVariable(L,ct(ie))}declareVariable(L,ie){if(this.variables.has(L))throw new SyntaxError(`Variable already declared: ${L}`);return this.variables.set(L,ie),ie}setVariable(L,ie){return this.variables.set(L,ie),ie}resolve(L){if(this.variables.has(L))return this;if(this.parent)return this.parent.resolve(L);throw new Error(`Unknown variable: ${L}`)}lookupVariable(L){try{return this.resolve(L).variables.get(L)??new Re}catch{return new Re}}},dt=class{constructor(L){_e(this,"global");this.global=L??new st}run(L){return this.evaluate(L,this.global)}evaluateBinaryExpression(L,ie){const H=this.evaluate(L.left,ie);switch(L.operator.value){case"and":return H.__bool__().value?this.evaluate(L.right,ie):H;case"or":return H.__bool__().value?H:this.evaluate(L.right,ie)}const me=this.evaluate(L.right,ie);switch(L.operator.value){case"==":return new Ke(H.value==me.value);case"!=":return new Ke(H.value!=me.value)}if(H instanceof Re||me instanceof Re)throw new Error("Cannot perform operation on undefined values");if(H instanceof Ne||me instanceof Ne)throw new Error("Cannot perform operation on null values");if(H instanceof Ze&&me instanceof Ze)switch(L.operator.value){case"+":return new Ze(H.value+me.value);case"-":return new Ze(H.value-me.value);case"*":return new Ze(H.value*me.value);case"/":return new Ze(H.value/me.value);case"%":return new Ze(H.value%me.value);case"<":return new Ke(H.value":return new Ke(H.value>me.value);case">=":return new Ke(H.value>=me.value);case"<=":return new Ke(H.value<=me.value)}else if(H instanceof Te&&me instanceof Te)switch(L.operator.value){case"+":return new Te(H.value.concat(me.value))}else if(me instanceof Te){const $e=me.value.find(We=>We.value===H.value)!==void 0;switch(L.operator.value){case"in":return new Ke($e);case"not in":return new Ke(!$e)}}if(H instanceof se||me instanceof se)switch(L.operator.value){case"+":return new se(H.value.toString()+me.value.toString())}if(H instanceof se&&me instanceof se)switch(L.operator.value){case"in":return new Ke(me.value.includes(H.value));case"not in":return new Ke(!me.value.includes(H.value))}if(H instanceof se&&me instanceof je)switch(L.operator.value){case"in":return new Ke(me.value.has(H.value));case"not in":return new Ke(!me.value.has(H.value))}throw new SyntaxError(`Unknown operator "${L.operator.value}" between ${H.type} and ${me.type}`)}evaluateArguments(L,ie){const H=[],me=new Map;for(const $e of L)if($e.type==="KeywordArgumentExpression"){const We=$e;me.set(We.key.value,this.evaluate(We.value,ie))}else{if(me.size>0)throw new Error("Positional arguments must come before keyword arguments");H.push(this.evaluate($e,ie))}return[H,me]}evaluateFilterExpression(L,ie){const H=this.evaluate(L.operand,ie);if(L.filter.type==="Identifier"){const me=L.filter;if(me.value==="tojson")return new se(lt(H));if(H instanceof Te)switch(me.value){case"list":return H;case"first":return H.value[0];case"last":return H.value[H.value.length-1];case"length":return new Ze(H.value.length);case"reverse":return new Te(H.value.reverse());case"sort":return new Te(H.value.sort(($e,We)=>{if($e.type!==We.type)throw new Error(`Cannot compare different types: ${$e.type} and ${We.type}`);switch($e.type){case"NumericValue":return $e.value-We.value;case"StringValue":return $e.value.localeCompare(We.value);default:throw new Error(`Cannot compare type: ${$e.type}`)}}));default:throw new Error(`Unknown ArrayValue filter: ${me.value}`)}else if(H instanceof se)switch(me.value){case"length":return new Ze(H.value.length);case"upper":return new se(H.value.toUpperCase());case"lower":return new se(H.value.toLowerCase());case"title":return new se(Ce(H.value));case"capitalize":return new se(H.value.charAt(0).toUpperCase()+H.value.slice(1));case"trim":return new se(H.value.trim());case"indent":return new se(H.value.split(` -`).map(($e,We)=>We===0||$e.length===0?$e:" "+$e).join(` -`));case"string":return H;default:throw new Error(`Unknown StringValue filter: ${me.value}`)}else if(H instanceof Ze)switch(me.value){case"abs":return new Ze(Math.abs(H.value));default:throw new Error(`Unknown NumericValue filter: ${me.value}`)}else if(H instanceof je)switch(me.value){case"items":return new Te(Array.from(H.value.entries()).map(([$e,We])=>new Te([new se($e),We])));case"length":return new Ze(H.value.size);default:throw new Error(`Unknown ObjectValue filter: ${me.value}`)}throw new Error(`Cannot apply filter "${me.value}" to type: ${H.type}`)}else if(L.filter.type==="CallExpression"){const me=L.filter;if(me.callee.type!=="Identifier")throw new Error(`Unknown filter: ${me.callee.type}`);const $e=me.callee.value;if($e==="tojson"){const[,We]=this.evaluateArguments(me.args,ie),Je=We.get("indent")??new Ne;if(!(Je instanceof Ze||Je instanceof Ne))throw new Error("If set, indent must be a number");return new se(lt(H,Je.value))}if(H instanceof Te){switch($e){case"selectattr":case"rejectattr":{const We=$e==="selectattr";if(H.value.some(At=>!(At instanceof je)))throw new Error(`\`${$e}\` can only be applied to array of objects`);if(me.args.some(At=>At.type!=="StringLiteral"))throw new Error(`arguments of \`${$e}\` must be strings`);const[Je,ut,mt]=me.args.map(At=>this.evaluate(At,ie));let vt;if(ut){const At=ie.tests.get(ut.value);if(!At)throw new Error(`Unknown test: ${ut.value}`);vt=At}else vt=(...At)=>At[0].__bool__().value;const kt=H.value.filter(At=>{const os=At.value.get(Je.value),ys=os?vt(os,mt):!1;return We?ys:!ys});return new Te(kt)}case"map":{const[,We]=this.evaluateArguments(me.args,ie);if(We.has("attribute")){const Je=We.get("attribute");if(!(Je instanceof se))throw new Error("attribute must be a string");const ut=We.get("default"),mt=H.value.map(vt=>{if(!(vt instanceof je))throw new Error("items in map must be an object");return vt.value.get(Je.value)??ut??new Re});return new Te(mt)}else throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${$e}`)}else if(H instanceof se){switch($e){case"indent":{const[We,Je]=this.evaluateArguments(me.args,ie),ut=We.at(0)??Je.get("width")??new Ze(4);if(!(ut instanceof Ze))throw new Error("width must be a number");const mt=We.at(1)??Je.get("first")??new Ke(!1),vt=We.at(2)??Je.get("blank")??new Ke(!1),kt=H.value.split(` -`),At=" ".repeat(ut.value),os=kt.map((ys,Cs)=>!mt.value&&Cs===0||!vt.value&&ys.length===0?ys:At+ys);return new se(os.join(` -`))}}throw new Error(`Unknown StringValue filter: ${$e}`)}else throw new Error(`Cannot apply filter "${$e}" to type: ${H.type}`)}throw new Error(`Unknown filter: ${L.filter.type}`)}evaluateTestExpression(L,ie){const H=this.evaluate(L.operand,ie),me=ie.tests.get(L.test.value);if(!me)throw new Error(`Unknown test: ${L.test.value}`);const $e=me(H);return new Ke(L.negate?!$e:$e)}evaluateUnaryExpression(L,ie){const H=this.evaluate(L.argument,ie);switch(L.operator.value){case"not":return new Ke(!H.value);default:throw new SyntaxError(`Unknown operator: ${L.operator.value}`)}}evalProgram(L,ie){return this.evaluateBlock(L.body,ie)}evaluateBlock(L,ie){let H="";for(const me of L){const $e=this.evaluate(me,ie);$e.type!=="NullValue"&&$e.type!=="UndefinedValue"&&(H+=$e.value)}return new se(H)}evaluateIdentifier(L,ie){return ie.lookupVariable(L.value)}evaluateCallExpression(L,ie){const[H,me]=this.evaluateArguments(L.args,ie);me.size>0&&H.push(new le(me));const $e=this.evaluate(L.callee,ie);if($e.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${$e.type}`);return $e.value(H,ie)}evaluateSliceExpression(L,ie,H){if(!(L instanceof Te||L instanceof se))throw new Error("Slice object must be an array or string");const me=this.evaluate(ie.start,H),$e=this.evaluate(ie.stop,H),We=this.evaluate(ie.step,H);if(!(me instanceof Ze||me instanceof Re))throw new Error("Slice start must be numeric or undefined");if(!($e instanceof Ze||$e instanceof Re))throw new Error("Slice stop must be numeric or undefined");if(!(We instanceof Ze||We instanceof Re))throw new Error("Slice step must be numeric or undefined");return L instanceof Te?new Te(de(L.value,me.value,$e.value,We.value)):new se(de(Array.from(L.value),me.value,$e.value,We.value).join(""))}evaluateMemberExpression(L,ie){const H=this.evaluate(L.object,ie);let me;if(L.computed){if(L.property.type==="SliceExpression")return this.evaluateSliceExpression(H,L.property,ie);me=this.evaluate(L.property,ie)}else me=new se(L.property.value);let $e;if(H instanceof je){if(!(me instanceof se))throw new Error(`Cannot access property with non-string: got ${me.type}`);$e=H.value.get(me.value)??H.builtins.get(me.value)}else if(H instanceof Te||H instanceof se)if(me instanceof Ze)$e=H.value.at(me.value),H instanceof se&&($e=new se(H.value.at(me.value)));else if(me instanceof se)$e=H.builtins.get(me.value);else throw new Error(`Cannot access property with non-string/non-number: got ${me.type}`);else{if(!(me instanceof se))throw new Error(`Cannot access property with non-string: got ${me.type}`);$e=H.builtins.get(me.value)}return $e instanceof Be?$e:new Re}evaluateSet(L,ie){const H=this.evaluate(L.value,ie);if(L.assignee.type==="Identifier"){const me=L.assignee.value;ie.setVariable(me,H)}else if(L.assignee.type==="MemberExpression"){const me=L.assignee,$e=this.evaluate(me.object,ie);if(!($e instanceof je))throw new Error("Cannot assign to member of non-object");if(me.property.type!=="Identifier")throw new Error("Cannot assign to member with non-identifier property");$e.value.set(me.property.value,H)}else throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(L.assignee)}`);return new Ne}evaluateIf(L,ie){const H=this.evaluate(L.test,ie);return this.evaluateBlock(H.__bool__().value?L.body:L.alternate,ie)}evaluateFor(L,ie){const H=new st(ie);let me,$e;if(L.iterable.type==="SelectExpression"){const vt=L.iterable;$e=this.evaluate(vt.iterable,H),me=vt.test}else $e=this.evaluate(L.iterable,H);if(!($e instanceof Te))throw new Error(`Expected iterable type in for loop: got ${$e.type}`);const We=[],Je=[];for(let vt=0;vt<$e.value.length;++vt){const kt=new st(H),At=$e.value[vt];let os;if(L.loopvar.type==="Identifier")os=ys=>ys.setVariable(L.loopvar.value,At);else if(L.loopvar.type==="TupleLiteral"){const ys=L.loopvar;if(At.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${At.type}`);const Cs=At;if(ys.value.length!==Cs.value.length)throw new Error(`Too ${ys.value.length>Cs.value.length?"few":"many"} items to unpack`);os=Ds=>{for(let sr=0;sr0?We[vt-1]:new Re],["nextitem",vt{var Je;const $e=new st(me);H=H.slice();let We;((Je=H.at(-1))==null?void 0:Je.type)==="KeywordArgumentsValue"&&(We=H.pop());for(let ut=0;utthis.evaluate(H,ie)));case"TupleLiteral":return new Ue(L.value.map(H=>this.evaluate(H,ie)));case"ObjectLiteral":{const H=new Map;for(const[me,$e]of L.value){const We=this.evaluate(me,ie);if(!(We instanceof se))throw new Error(`Object keys must be strings: got ${We.type}`);H.set(We.value,this.evaluate($e,ie))}return new je(H)}case"Identifier":return this.evaluateIdentifier(L,ie);case"CallExpression":return this.evaluateCallExpression(L,ie);case"MemberExpression":return this.evaluateMemberExpression(L,ie);case"UnaryExpression":return this.evaluateUnaryExpression(L,ie);case"BinaryExpression":return this.evaluateBinaryExpression(L,ie);case"FilterExpression":return this.evaluateFilterExpression(L,ie);case"TestExpression":return this.evaluateTestExpression(L,ie);default:throw new SyntaxError(`Unknown node type: ${L.type}`)}}};function ct(L){switch(typeof L){case"number":return new Ze(L);case"string":return new se(L);case"boolean":return new Ke(L);case"undefined":return new Re;case"object":return L===null?new Ne:Array.isArray(L)?new Te(L.map(ct)):new je(new Map(Object.entries(L).map(([ie,H])=>[ie,ct(H)])));case"function":return new Ve((ie,H)=>{const me=L(...ie.map($e=>$e.value))??null;return ct(me)});default:throw new Error(`Cannot convert to runtime value: ${L}`)}}function lt(L,ie,H){const me=H??0;switch(L.type){case"NullValue":case"UndefinedValue":return"null";case"NumericValue":case"StringValue":case"BooleanValue":return JSON.stringify(L.value);case"ArrayValue":case"ObjectValue":{const $e=ie?" ".repeat(ie):"",We=` -`+$e.repeat(me),Je=We+$e;if(L.type==="ArrayValue"){const ut=L.value.map(mt=>lt(mt,ie,me+1));return ie?`[${Je}${ut.join(`,${Je}`)}${We}]`:`[${ut.join(", ")}]`}else{const ut=Array.from(L.value.entries()).map(([mt,vt])=>{const kt=`"${mt}": ${lt(vt,ie,me+1)}`;return ie?`${Je}${kt}`:kt});return ie?`{${ut.join(",")}${We}}`:`{${ut.join(", ")}}`}}default:throw new Error(`Cannot convert to JSON: ${L.type}`)}}var ht=class{constructor(L){_e(this,"parsed");const ie=y(L,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=ye(ie)}render(L){const ie=new st;ie.set("false",!1),ie.set("true",!0),ie.set("raise_exception",$e=>{throw new Error($e)}),ie.set("range",J);for(const[$e,We]of Object.entries(L))ie.set($e,We);return new dt(ie).run(this.parsed).value}}},"./node_modules/onnxruntime-common/dist/esm/backend-impl.js":(De,A,r)=>{r.r(A),r.d(A,{registerBackend:()=>U,resolveBackendAndExecutionProviders:()=>R});const f=new Map,D=[],U=(g,v,M)=>{if(v&&typeof v.init=="function"&&typeof v.createInferenceSessionHandler=="function"){const y=f.get(g);if(y===void 0)f.set(g,{backend:v,priority:M});else{if(y.priority>M)return;if(y.priority===M&&y.backend!==v)throw new Error(`cannot register backend "${g}" using priority ${M}`)}if(M>=0){const b=D.indexOf(g);b!==-1&&D.splice(b,1);for(let I=0;I{const v=f.get(g);if(!v)return"backend not found.";if(v.initialized)return v.backend;if(v.aborted)return v.error;{const M=!!v.initPromise;try{return M||(v.initPromise=v.backend.init(g)),await v.initPromise,v.initialized=!0,v.backend}catch(y){return M||(v.error=`${y}`,v.aborted=!0),v.error}finally{delete v.initPromise}}},R=async g=>{const v=g.executionProviders||[],M=v.map(ne=>typeof ne=="string"?ne:ne.name),y=M.length===0?D:M;let b;const I=[],K=new Set;for(const ne of y){const W=await Y(ne);typeof W=="string"?I.push({name:ne,err:W}):(b||(b=W),b===W&&K.add(ne))}if(!b)throw new Error(`no available backend found. ERR: ${I.map(ne=>`[${ne.name}] ${ne.err}`).join(", ")}`);for(const{name:ne,err:W}of I)M.includes(ne)&&console.warn(`removing requested execution provider "${ne}" from session options because it is not available: ${W}`);const te=v.filter(ne=>K.has(typeof ne=="string"?ne:ne.name));return[b,new Proxy(g,{get:(ne,W)=>W==="executionProviders"?te:Reflect.get(ne,W)})]}},"./node_modules/onnxruntime-common/dist/esm/backend.js":(De,A,r)=>{r.r(A),r.d(A,{registerBackend:()=>f.registerBackend});var f=r("./node_modules/onnxruntime-common/dist/esm/backend-impl.js")},"./node_modules/onnxruntime-common/dist/esm/env-impl.js":(De,A,r)=>{r.r(A),r.d(A,{env:()=>U});var f=r("./node_modules/onnxruntime-common/dist/esm/version.js");let D="warning";const U={wasm:{},webgl:{},webgpu:{},versions:{common:f.version},set logLevel(Y){if(Y!==void 0){if(typeof Y!="string"||["verbose","info","warning","error","fatal"].indexOf(Y)===-1)throw new Error(`Unsupported logging level: ${Y}`);D=Y}},get logLevel(){return D}};Object.defineProperty(U,"logLevel",{enumerable:!0})},"./node_modules/onnxruntime-common/dist/esm/env.js":(De,A,r)=>{r.r(A),r.d(A,{env:()=>D});var f=r("./node_modules/onnxruntime-common/dist/esm/env-impl.js");const D=f.env},"./node_modules/onnxruntime-common/dist/esm/index.js":(De,A,r)=>{r.r(A),r.d(A,{InferenceSession:()=>U.InferenceSession,TRACE:()=>R.TRACE,TRACE_FUNC_BEGIN:()=>R.TRACE_FUNC_BEGIN,TRACE_FUNC_END:()=>R.TRACE_FUNC_END,Tensor:()=>Y.Tensor,TrainingSession:()=>g.TrainingSession,env:()=>D.env,registerBackend:()=>f.registerBackend});var f=r("./node_modules/onnxruntime-common/dist/esm/backend.js"),D=r("./node_modules/onnxruntime-common/dist/esm/env.js"),U=r("./node_modules/onnxruntime-common/dist/esm/inference-session.js"),Y=r("./node_modules/onnxruntime-common/dist/esm/tensor.js");r("./node_modules/onnxruntime-common/dist/esm/tensor-conversion.js"),r("./node_modules/onnxruntime-common/dist/esm/tensor-factory.js");var R=r("./node_modules/onnxruntime-common/dist/esm/trace.js");r("./node_modules/onnxruntime-common/dist/esm/onnx-model.js"),r("./node_modules/onnxruntime-common/dist/esm/onnx-value.js");var g=r("./node_modules/onnxruntime-common/dist/esm/training-session.js")},"./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js":(De,A,r)=>{r.r(A),r.d(A,{InferenceSession:()=>Y});var f=r("./node_modules/onnxruntime-common/dist/esm/backend-impl.js"),D=r("./node_modules/onnxruntime-common/dist/esm/tensor.js"),U=r("./node_modules/onnxruntime-common/dist/esm/trace.js");class Y{constructor(g){this.handler=g}async run(g,v,M){(0,U.TRACE_FUNC_BEGIN)();const y={};let b={};if(typeof g!="object"||g===null||g instanceof D.Tensor||Array.isArray(g))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let I=!0;if(typeof v=="object"){if(v===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(v instanceof D.Tensor)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(v)){if(v.length===0)throw new TypeError("'fetches' cannot be an empty array.");I=!1;for(const ne of v){if(typeof ne!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(ne)===-1)throw new RangeError(`'fetches' contains invalid output name: ${ne}.`);y[ne]=null}if(typeof M=="object"&&M!==null)b=M;else if(typeof M<"u")throw new TypeError("'options' must be an object.")}else{let ne=!1;const W=Object.getOwnPropertyNames(v);for(const j of this.outputNames)if(W.indexOf(j)!==-1){const q=v[j];(q===null||q instanceof D.Tensor)&&(ne=!0,I=!1,y[j]=q)}if(ne){if(typeof M=="object"&&M!==null)b=M;else if(typeof M<"u")throw new TypeError("'options' must be an object.")}else b=v}}else if(typeof v<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const ne of this.inputNames)if(typeof g[ne]>"u")throw new Error(`input '${ne}' is missing in 'feeds'.`);if(I)for(const ne of this.outputNames)y[ne]=null;const K=await this.handler.run(g,y,b),te={};for(const ne in K)if(Object.hasOwnProperty.call(K,ne)){const W=K[ne];W instanceof D.Tensor?te[ne]=W:te[ne]=new D.Tensor(W.type,W.data,W.dims)}return(0,U.TRACE_FUNC_END)(),te}async release(){return this.handler.dispose()}static async create(g,v,M,y){(0,U.TRACE_FUNC_BEGIN)();let b,I={};if(typeof g=="string"){if(b=g,typeof v=="object"&&v!==null)I=v;else if(typeof v<"u")throw new TypeError("'options' must be an object.")}else if(g instanceof Uint8Array){if(b=g,typeof v=="object"&&v!==null)I=v;else if(typeof v<"u")throw new TypeError("'options' must be an object.")}else if(g instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&g instanceof SharedArrayBuffer){const W=g;let j=0,q=g.byteLength;if(typeof v=="object"&&v!==null)I=v;else if(typeof v=="number"){if(j=v,!Number.isSafeInteger(j))throw new RangeError("'byteOffset' must be an integer.");if(j<0||j>=W.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${W.byteLength}).`);if(q=g.byteLength-j,typeof M=="number"){if(q=M,!Number.isSafeInteger(q))throw new RangeError("'byteLength' must be an integer.");if(q<=0||j+q>W.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${W.byteLength-j}].`);if(typeof y=="object"&&y!==null)I=y;else if(typeof y<"u")throw new TypeError("'options' must be an object.")}else if(typeof M<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof v<"u")throw new TypeError("'options' must be an object.");b=new Uint8Array(W,j,q)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");const[K,te]=await(0,f.resolveBackendAndExecutionProviders)(I),ne=await K.createInferenceSessionHandler(b,te);return(0,U.TRACE_FUNC_END)(),new Y(ne)}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":(De,A,r)=>{r.r(A),r.d(A,{InferenceSession:()=>D});var f=r("./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js");const D=f.InferenceSession},"./node_modules/onnxruntime-common/dist/esm/onnx-model.js":(De,A,r)=>{r.r(A)},"./node_modules/onnxruntime-common/dist/esm/onnx-value.js":(De,A,r)=>{r.r(A)},"./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js":(De,A,r)=>{r.r(A),r.d(A,{tensorToDataURL:()=>f,tensorToImageData:()=>D});const f=(U,Y)=>{const R=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);R.width=U.dims[3],R.height=U.dims[2];const g=R.getContext("2d");if(g!=null){let v,M;(Y==null?void 0:Y.tensorLayout)!==void 0&&Y.tensorLayout==="NHWC"?(v=U.dims[2],M=U.dims[3]):(v=U.dims[3],M=U.dims[2]);const y=(Y==null?void 0:Y.format)!==void 0?Y.format:"RGB",b=Y==null?void 0:Y.norm;let I,K;b===void 0||b.mean===void 0?I=[255,255,255,255]:typeof b.mean=="number"?I=[b.mean,b.mean,b.mean,b.mean]:(I=[b.mean[0],b.mean[1],b.mean[2],0],b.mean[3]!==void 0&&(I[3]=b.mean[3])),b===void 0||b.bias===void 0?K=[0,0,0,0]:typeof b.bias=="number"?K=[b.bias,b.bias,b.bias,b.bias]:(K=[b.bias[0],b.bias[1],b.bias[2],0],b.bias[3]!==void 0&&(K[3]=b.bias[3]));const te=M*v;let ne=0,W=te,j=te*2,q=-1;y==="RGBA"?(ne=0,W=te,j=te*2,q=te*3):y==="RGB"?(ne=0,W=te,j=te*2):y==="RBG"&&(ne=0,j=te,W=te*2);for(let $=0;${const R=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");let g;if(R!=null){let v,M,y;(Y==null?void 0:Y.tensorLayout)!==void 0&&Y.tensorLayout==="NHWC"?(v=U.dims[2],M=U.dims[1],y=U.dims[3]):(v=U.dims[3],M=U.dims[2],y=U.dims[1]);const b=Y!==void 0&&Y.format!==void 0?Y.format:"RGB",I=Y==null?void 0:Y.norm;let K,te;I===void 0||I.mean===void 0?K=[255,255,255,255]:typeof I.mean=="number"?K=[I.mean,I.mean,I.mean,I.mean]:(K=[I.mean[0],I.mean[1],I.mean[2],255],I.mean[3]!==void 0&&(K[3]=I.mean[3])),I===void 0||I.bias===void 0?te=[0,0,0,0]:typeof I.bias=="number"?te=[I.bias,I.bias,I.bias,I.bias]:(te=[I.bias[0],I.bias[1],I.bias[2],0],I.bias[3]!==void 0&&(te[3]=I.bias[3]));const ne=M*v;if(Y!==void 0&&(Y.format!==void 0&&y===4&&Y.format!=="RGBA"||y===3&&Y.format!=="RGB"&&Y.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");const W=4;let j=0,q=1,$=2,S=3,w=0,x=ne,O=ne*2,ae=-1;b==="RGBA"?(w=0,x=ne,O=ne*2,ae=ne*3):b==="RGB"?(w=0,x=ne,O=ne*2):b==="RBG"&&(w=0,O=ne,x=ne*2),g=R.createImageData(v,M);for(let oe=0;oe{r.r(A)},"./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js":(De,A,r)=>{r.r(A),r.d(A,{bufferToTensor:()=>D,tensorFromGpuBuffer:()=>R,tensorFromImage:()=>U,tensorFromMLTensor:()=>g,tensorFromPinnedBuffer:()=>v,tensorFromTexture:()=>Y});var f=r("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const D=(M,y)=>{if(M===void 0)throw new Error("Image buffer must be defined");if(y.height===void 0||y.width===void 0)throw new Error("Image height and width must be defined");if(y.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");const{height:b,width:I}=y,K=y.norm??{mean:255,bias:0};let te,ne;typeof K.mean=="number"?te=[K.mean,K.mean,K.mean,K.mean]:te=[K.mean[0],K.mean[1],K.mean[2],K.mean[3]??255],typeof K.bias=="number"?ne=[K.bias,K.bias,K.bias,K.bias]:ne=[K.bias[0],K.bias[1],K.bias[2],K.bias[3]??0];const W=y.format!==void 0?y.format:"RGBA",j=y.tensorFormat!==void 0&&y.tensorFormat!==void 0?y.tensorFormat:"RGB",q=b*I,$=j==="RGBA"?new Float32Array(q*4):new Float32Array(q*3);let S=4,w=0,x=1,O=2,ae=3,oe=0,ve=q,we=q*2,re=-1;W==="RGB"&&(S=3,w=0,x=1,O=2,ae=-1),j==="RGBA"?re=q*3:j==="RBG"?(oe=0,we=q,ve=q*2):j==="BGR"&&(we=0,ve=q,oe=q*2);for(let ce=0;ce{const b=typeof HTMLImageElement<"u"&&M instanceof HTMLImageElement,I=typeof ImageData<"u"&&M instanceof ImageData,K=typeof ImageBitmap<"u"&&M instanceof ImageBitmap,te=typeof M=="string";let ne,W=y??{};const j=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},q=$=>typeof HTMLCanvasElement<"u"&&$ instanceof HTMLCanvasElement||$ instanceof OffscreenCanvas?$.getContext("2d"):null;if(b){const $=j();$.width=M.width,$.height=M.height;const S=q($);if(S!=null){let w=M.height,x=M.width;if(y!==void 0&&y.resizedHeight!==void 0&&y.resizedWidth!==void 0&&(w=y.resizedHeight,x=y.resizedWidth),y!==void 0){if(W=y,y.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");W.tensorFormat="RGBA",W.height=w,W.width=x}else W.tensorFormat="RGBA",W.height=w,W.width=x;S.drawImage(M,0,0),ne=S.getImageData(0,0,x,w).data}else throw new Error("Can not access image data")}else if(I){let $,S;if(y!==void 0&&y.resizedWidth!==void 0&&y.resizedHeight!==void 0?($=y.resizedHeight,S=y.resizedWidth):($=M.height,S=M.width),y!==void 0&&(W=y),W.format="RGBA",W.height=$,W.width=S,y!==void 0){const w=j();w.width=S,w.height=$;const x=q(w);if(x!=null)x.putImageData(M,0,0),ne=x.getImageData(0,0,S,$).data;else throw new Error("Can not access image data")}else ne=M.data}else if(K){if(y===void 0)throw new Error("Please provide image config with format for Imagebitmap");const $=j();$.width=M.width,$.height=M.height;const S=q($);if(S!=null){const w=M.height,x=M.width;return S.drawImage(M,0,0,x,w),ne=S.getImageData(0,0,x,w).data,W.height=w,W.width=x,D(ne,W)}else throw new Error("Can not access image data")}else{if(te)return new Promise(($,S)=>{const w=j(),x=q(w);if(!M||!x)return S();const O=new Image;O.crossOrigin="Anonymous",O.src=M,O.onload=()=>{w.width=O.width,w.height=O.height,x.drawImage(O,0,0,w.width,w.height);const ae=x.getImageData(0,0,w.width,w.height);W.height=w.height,W.width=w.width,$(D(ae.data,W))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(ne!==void 0)return D(ne,W);throw new Error("Input data provided is not supported - aborted tensor creation")},Y=(M,y)=>{const{width:b,height:I,download:K,dispose:te}=y,ne=[1,I,b,4];return new f.Tensor({location:"texture",type:"float32",texture:M,dims:ne,download:K,dispose:te})},R=(M,y)=>{const{dataType:b,dims:I,download:K,dispose:te}=y;return new f.Tensor({location:"gpu-buffer",type:b??"float32",gpuBuffer:M,dims:I,download:K,dispose:te})},g=(M,y)=>{const{dataType:b,dims:I,download:K,dispose:te}=y;return new f.Tensor({location:"ml-tensor",type:b??"float32",mlTensor:M,dims:I,download:K,dispose:te})},v=(M,y,b)=>new f.Tensor({location:"cpu-pinned",type:M,data:y,dims:b??[y.length]})},"./node_modules/onnxruntime-common/dist/esm/tensor-factory.js":(De,A,r)=>{r.r(A)},"./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js":(De,A,r)=>{r.r(A),r.d(A,{NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP:()=>D,NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP:()=>f,checkTypedArray:()=>Y});const f=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),D=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);let U=!1;const Y=()=>{if(!U){U=!0;const R=typeof BigInt64Array<"u"&&BigInt64Array.from,g=typeof BigUint64Array<"u"&&BigUint64Array.from,v=typeof Float16Array<"u"&&Float16Array.from;R&&(f.set("int64",BigInt64Array),D.set(BigInt64Array,"int64")),g&&(f.set("uint64",BigUint64Array),D.set(BigUint64Array,"uint64")),v?(f.set("float16",Float16Array),D.set(Float16Array,"float16")):f.set("float16",Uint16Array)}}},"./node_modules/onnxruntime-common/dist/esm/tensor-impl.js":(De,A,r)=>{r.r(A),r.d(A,{Tensor:()=>R});var f=r("./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js"),D=r("./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js"),U=r("./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js"),Y=r("./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js");class R{constructor(v,M,y){(0,U.checkTypedArray)();let b,I;if(typeof v=="object"&&"location"in v)switch(this.dataLocation=v.location,b=v.type,I=v.dims,v.location){case"cpu-pinned":{const te=U.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(b);if(!te)throw new TypeError(`unsupported type "${b}" to create tensor from pinned buffer`);if(!(v.data instanceof te))throw new TypeError(`buffer should be of type ${te.name}`);this.cpuData=v.data;break}case"texture":{if(b!=="float32")throw new TypeError(`unsupported type "${b}" to create tensor from texture`);this.gpuTextureData=v.texture,this.downloader=v.download,this.disposer=v.dispose;break}case"gpu-buffer":{if(b!=="float32"&&b!=="float16"&&b!=="int32"&&b!=="int64"&&b!=="uint32"&&b!=="uint8"&&b!=="bool"&&b!=="uint4"&&b!=="int4")throw new TypeError(`unsupported type "${b}" to create tensor from gpu buffer`);this.gpuBufferData=v.gpuBuffer,this.downloader=v.download,this.disposer=v.dispose;break}case"ml-tensor":{if(b!=="float32"&&b!=="float16"&&b!=="int32"&&b!=="int64"&&b!=="uint32"&&b!=="uint64"&&b!=="int8"&&b!=="uint8"&&b!=="bool")throw new TypeError(`unsupported type "${b}" to create tensor from MLTensor`);this.mlTensorData=v.mlTensor,this.downloader=v.download,this.disposer=v.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let te,ne;if(typeof v=="string")if(b=v,ne=y,v==="string"){if(!Array.isArray(M))throw new TypeError("A string tensor's data must be a string array.");te=M}else{const W=U.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(v);if(W===void 0)throw new TypeError(`Unsupported tensor type: ${v}.`);if(Array.isArray(M)){if(v==="float16"&&W===Uint16Array||v==="uint4"||v==="int4")throw new TypeError(`Creating a ${v} tensor from number array is not supported. Please use ${W.name} as data.`);v==="uint64"||v==="int64"?te=W.from(M,BigInt):te=W.from(M)}else if(M instanceof W)te=M;else if(M instanceof Uint8ClampedArray)if(v==="uint8")te=Uint8Array.from(M);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else throw new TypeError(`A ${b} tensor's data must be type of ${W}`)}else if(ne=M,Array.isArray(v)){if(v.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");const W=typeof v[0];if(W==="string")b="string",te=v;else if(W==="boolean")b="bool",te=Uint8Array.from(v);else throw new TypeError(`Invalid element type of data array: ${W}.`)}else if(v instanceof Uint8ClampedArray)b="uint8",te=Uint8Array.from(v);else{const W=U.NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.get(v.constructor);if(W===void 0)throw new TypeError(`Unsupported type for tensor data: ${v.constructor}.`);b=W,te=v}if(ne===void 0)ne=[te.length];else if(!Array.isArray(ne))throw new TypeError("A tensor's dims must be a number array");I=ne,this.cpuData=te,this.dataLocation="cpu"}const K=(0,Y.calculateSize)(I);if(this.cpuData&&K!==this.cpuData.length&&!((b==="uint4"||b==="int4")&&Math.ceil(K/2)===this.cpuData.length))throw new Error(`Tensor's size(${K}) does not match data length(${this.cpuData.length}).`);this.type=b,this.dims=I,this.size=K}static async fromImage(v,M){return(0,D.tensorFromImage)(v,M)}static fromTexture(v,M){return(0,D.tensorFromTexture)(v,M)}static fromGpuBuffer(v,M){return(0,D.tensorFromGpuBuffer)(v,M)}static fromMLTensor(v,M){return(0,D.tensorFromMLTensor)(v,M)}static fromPinnedBuffer(v,M,y){return(0,D.tensorFromPinnedBuffer)(v,M,y)}toDataURL(v){return(0,f.tensorToDataURL)(this,v)}toImageData(v){return(0,f.tensorToImageData)(this,v)}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(v){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 M=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=M,v&&this.disposer&&(this.disposer(),this.disposer=void 0),M}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(v){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return(0,Y.tensorReshape)(this,v)}}},"./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js":(De,A,r)=>{r.r(A),r.d(A,{calculateSize:()=>D,tensorReshape:()=>U});var f=r("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const D=Y=>{let R=1;for(let g=0;g{switch(Y.location){case"cpu":return new f.Tensor(Y.type,Y.data,R);case"cpu-pinned":return new f.Tensor({location:"cpu-pinned",data:Y.data,type:Y.type,dims:R});case"texture":return new f.Tensor({location:"texture",texture:Y.texture,type:Y.type,dims:R});case"gpu-buffer":return new f.Tensor({location:"gpu-buffer",gpuBuffer:Y.gpuBuffer,type:Y.type,dims:R});case"ml-tensor":return new f.Tensor({location:"ml-tensor",mlTensor:Y.mlTensor,type:Y.type,dims:R});default:throw new Error(`tensorReshape: tensor location ${Y.location} is not supported`)}}},"./node_modules/onnxruntime-common/dist/esm/tensor.js":(De,A,r)=>{r.r(A),r.d(A,{Tensor:()=>D});var f=r("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const D=f.Tensor},"./node_modules/onnxruntime-common/dist/esm/trace.js":(De,A,r)=>{r.r(A),r.d(A,{TRACE:()=>D,TRACE_FUNC_BEGIN:()=>Y,TRACE_FUNC_END:()=>R});var f=r("./node_modules/onnxruntime-common/dist/esm/env-impl.js");const D=(g,v)=>{(typeof f.env.trace>"u"?!f.env.wasm.trace:!f.env.trace)||console.timeStamp(`${g}::ORT::${v}`)},U=(g,v)=>{var b;const M=((b=new Error().stack)==null?void 0:b.split(/\r\n|\r|\n/g))||[];let y=!1;for(let I=0;I{(typeof f.env.trace>"u"?!f.env.wasm.trace:!f.env.trace)||U("BEGIN",g)},R=g=>{(typeof f.env.trace>"u"?!f.env.wasm.trace:!f.env.trace)||U("END",g)}},"./node_modules/onnxruntime-common/dist/esm/training-session-impl.js":(De,A,r)=>{r.r(A),r.d(A,{TrainingSession:()=>Y});var f=r("./node_modules/onnxruntime-common/dist/esm/backend-impl.js"),D=r("./node_modules/onnxruntime-common/dist/esm/tensor.js");const U="Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.";class Y{constructor(g,v,M){this.handler=g,this.hasOptimizerModel=v,this.hasEvalModel=M}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(g,v){const M=g.evalModel||"",y=g.optimizerModel||"",b=v||{},[I,K]=await(0,f.resolveBackendAndExecutionProviders)(b);if(I.createTrainingSessionHandler){const te=await I.createTrainingSessionHandler(g.checkpointState,g.trainModel,M,y,K);return new Y(te,!!g.optimizerModel,!!g.evalModel)}else throw new Error(U)}typeNarrowingForRunStep(g,v,M,y,b){const I={};let K={};if(typeof M!="object"||M===null||M instanceof D.Tensor||Array.isArray(M))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let te=!0;if(typeof y=="object"){if(y===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(y instanceof D.Tensor)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(y)){if(y.length===0)throw new TypeError("'fetches' cannot be an empty array.");te=!1;for(const ne of y){if(typeof ne!="string")throw new TypeError("'fetches' must be a string array or an object.");if(v.indexOf(ne)===-1)throw new RangeError(`'fetches' contains invalid output name: ${ne}.`);I[ne]=null}if(typeof b=="object"&&b!==null)K=b;else if(typeof b<"u")throw new TypeError("'options' must be an object.")}else{let ne=!1;const W=Object.getOwnPropertyNames(y);for(const j of v)if(W.indexOf(j)!==-1){const q=y[j];(q===null||q instanceof D.Tensor)&&(ne=!0,te=!1,I[j]=q)}if(ne){if(typeof b=="object"&&b!==null)K=b;else if(typeof b<"u")throw new TypeError("'options' must be an object.")}else K=y}}else if(typeof y<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const ne of g)if(typeof M[ne]>"u")throw new Error(`input '${ne}' is missing in 'feeds'.`);if(te)for(const ne of v)I[ne]=null;return[I,K]}convertHandlerReturnTypeToMapOfTensors(g){const v={};for(const M in g)if(Object.hasOwnProperty.call(g,M)){const y=g[M];y instanceof D.Tensor?v[M]=y:v[M]=new D.Tensor(y.type,y.data,y.dims)}return v}async lazyResetGrad(){await this.handler.lazyResetGrad()}async runTrainStep(g,v,M){const[y,b]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,g,v,M),I=await this.handler.runTrainStep(g,y,b);return this.convertHandlerReturnTypeToMapOfTensors(I)}async runOptimizerStep(g){if(this.hasOptimizerModel)await this.handler.runOptimizerStep(g||{});else throw new Error("This TrainingSession has no OptimizerModel loaded.")}async runEvalStep(g,v,M){if(this.hasEvalModel){const[y,b]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,g,v,M),I=await this.handler.runEvalStep(g,y,b);return this.convertHandlerReturnTypeToMapOfTensors(I)}else throw new Error("This TrainingSession has no EvalModel loaded.")}async getParametersSize(g=!0){return this.handler.getParametersSize(g)}async loadParametersBuffer(g,v=!0){const M=await this.getParametersSize(v);if(g.length!==4*M)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(g,v)}async getContiguousParameters(g=!0){return this.handler.getContiguousParameters(g)}async release(){return this.handler.dispose()}}},"./node_modules/onnxruntime-common/dist/esm/training-session.js":(De,A,r)=>{r.r(A),r.d(A,{TrainingSession:()=>D});var f=r("./node_modules/onnxruntime-common/dist/esm/training-session-impl.js");const D=f.TrainingSession},"./node_modules/onnxruntime-common/dist/esm/version.js":(De,A,r)=>{r.r(A),r.d(A,{version:()=>f});const f="1.20.1"},"./node_modules/onnxruntime-web/dist/ort.bundle.min.mjs?3a96":(De,A,r)=>{r.r(A),r.d(A,{InferenceSession:()=>lt,TRACE:()=>Ue,TRACE_FUNC_BEGIN:()=>Ne,TRACE_FUNC_END:()=>Re,Tensor:()=>le,default:()=>f_,env:()=>O,registerBackend:()=>K});/*! - * ONNX Runtime Web v1.21.0-dev.20250114-228dd16893 - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */var f=Object.defineProperty,D=Object.getOwnPropertyDescriptor,U=Object.getOwnPropertyNames,Y=Object.prototype.hasOwnProperty,R=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,s)=>(typeof require<"u"?require:t)[s]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),g=(e,t)=>()=>(e&&(t=e(e=0)),t),v=(e,t)=>{for(var s in t)f(e,s,{get:t[s],enumerable:!0})},M=(e,t,s,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of U(t))!Y.call(e,o)&&o!==s&&f(e,o,{get:()=>t[o],enumerable:!(n=D(t,o))||n.enumerable});return e},y=e=>M(f({},"__esModule",{value:!0}),e),b,I,K,te,ne,W=g(()=>{b=new Map,I=[],K=(e,t,s)=>{if(t&&typeof t.init=="function"&&typeof t.createInferenceSessionHandler=="function"){let n=b.get(e);if(n===void 0)b.set(e,{backend:t,priority:s});else{if(n.priority>s)return;if(n.priority===s&&n.backend!==t)throw new Error(`cannot register backend "${e}" using priority ${s}`)}if(s>=0){let o=I.indexOf(e);o!==-1&&I.splice(o,1);for(let a=0;a{let t=b.get(e);if(!t)return"backend not found.";if(t.initialized)return t.backend;if(t.aborted)return t.error;{let s=!!t.initPromise;try{return s||(t.initPromise=t.backend.init(e)),await t.initPromise,t.initialized=!0,t.backend}catch(n){return s||(t.error=`${n}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},ne=async e=>{let t=e.executionProviders||[],s=t.map(p=>typeof p=="string"?p:p.name),n=s.length===0?I:s,o,a=[],i=new Set;for(let p of n){let h=await te(p);typeof h=="string"?a.push({name:p,err:h}):(o||(o=h),o===h&&i.add(p))}if(!o)throw new Error(`no available backend found. ERR: ${a.map(p=>`[${p.name}] ${p.err}`).join(", ")}`);for(let{name:p,err:h}of a)s.includes(p)&&console.warn(`removing requested execution provider "${p}" from session options because it is not available: ${h}`);let u=t.filter(p=>i.has(typeof p=="string"?p:p.name));return[o,new Proxy(e,{get:(p,h)=>h==="executionProviders"?u:Reflect.get(p,h)})]}}),j=g(()=>{W()}),q,$=g(()=>{q="1.21.0-dev.20241212-1f88284f96"}),S,w,x=g(()=>{$(),S="warning",w={wasm:{},webgl:{},webgpu:{},versions:{common:q},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}`);S=e}},get logLevel(){return S}},Object.defineProperty(w,"logLevel",{enumerable:!0})}),O,ae=g(()=>{x(),O=w}),oe,ve,we=g(()=>{oe=(e,t)=>{let s=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);s.width=e.dims[3],s.height=e.dims[2];let n=s.getContext("2d");if(n!=null){let o,a;(t==null?void 0:t.tensorLayout)!==void 0&&t.tensorLayout==="NHWC"?(o=e.dims[2],a=e.dims[3]):(o=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,p,h;u===void 0||u.mean===void 0?p=[255,255,255,255]:typeof u.mean=="number"?p=[u.mean,u.mean,u.mean,u.mean]:(p=[u.mean[0],u.mean[1],u.mean[2],0],u.mean[3]!==void 0&&(p[3]=u.mean[3])),u===void 0||u.bias===void 0?h=[0,0,0,0]:typeof u.bias=="number"?h=[u.bias,u.bias,u.bias,u.bias]:(h=[u.bias[0],u.bias[1],u.bias[2],0],u.bias[3]!==void 0&&(h[3]=u.bias[3]));let k=a*o,C=0,d=k,z=k*2,B=-1;i==="RGBA"?(C=0,d=k,z=k*2,B=k*3):i==="RGB"?(C=0,d=k,z=k*2):i==="RBG"&&(C=0,z=k,d=k*2);for(let V=0;V{let s=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),n;if(s!=null){let o,a,i;(t==null?void 0:t.tensorLayout)!==void 0&&t.tensorLayout==="NHWC"?(o=e.dims[2],a=e.dims[1],i=e.dims[3]):(o=e.dims[3],a=e.dims[2],i=e.dims[1]);let u=t!==void 0&&t.format!==void 0?t.format:"RGB",p=t==null?void 0:t.norm,h,k;p===void 0||p.mean===void 0?h=[255,255,255,255]:typeof p.mean=="number"?h=[p.mean,p.mean,p.mean,p.mean]:(h=[p.mean[0],p.mean[1],p.mean[2],255],p.mean[3]!==void 0&&(h[3]=p.mean[3])),p===void 0||p.bias===void 0?k=[0,0,0,0]:typeof p.bias=="number"?k=[p.bias,p.bias,p.bias,p.bias]:(k=[p.bias[0],p.bias[1],p.bias[2],0],p.bias[3]!==void 0&&(k[3]=p.bias[3]));let C=a*o;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 d=4,z=0,B=1,V=2,Z=3,ee=0,X=C,he=C*2,pe=-1;u==="RGBA"?(ee=0,X=C,he=C*2,pe=C*3):u==="RGB"?(ee=0,X=C,he=C*2):u==="RBG"&&(ee=0,he=C,X=C*2),n=s.createImageData(o,a);for(let Me=0;Me{je(),re=(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:s,width:n}=t,o=t.norm??{mean:255,bias:0},a,i;typeof o.mean=="number"?a=[o.mean,o.mean,o.mean,o.mean]:a=[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 u=t.format!==void 0?t.format:"RGBA",p=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:"RGB",h=s*n,k=p==="RGBA"?new Float32Array(h*4):new Float32Array(h*3),C=4,d=0,z=1,B=2,V=3,Z=0,ee=h,X=h*2,he=-1;u==="RGB"&&(C=3,d=0,z=1,B=2,V=-1),p==="RGBA"?he=h*3:p==="RBG"?(Z=0,X=h,ee=h*2):p==="BGR"&&(X=0,ee=h,Z=h*2);for(let pe=0;pe{let s=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,n=typeof ImageData<"u"&&e instanceof ImageData,o=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,a=typeof e=="string",i,u=t??{},p=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},h=k=>typeof HTMLCanvasElement<"u"&&k instanceof HTMLCanvasElement||k instanceof OffscreenCanvas?k.getContext("2d"):null;if(s){let k=p();k.width=e.width,k.height=e.height;let C=h(k);if(C!=null){let d=e.height,z=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(d=t.resizedHeight,z=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=d,u.width=z}else u.tensorFormat="RGBA",u.height=d,u.width=z;C.drawImage(e,0,0),i=C.getImageData(0,0,z,d).data}else throw new Error("Can not access image data")}else if(n){let k,C;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(k=t.resizedHeight,C=t.resizedWidth):(k=e.height,C=e.width),t!==void 0&&(u=t),u.format="RGBA",u.height=k,u.width=C,t!==void 0){let d=p();d.width=C,d.height=k;let z=h(d);if(z!=null)z.putImageData(e,0,0),i=z.getImageData(0,0,C,k).data;else throw new Error("Can not access image data")}else i=e.data}else if(o){if(t===void 0)throw new Error("Please provide image config with format for Imagebitmap");let k=p();k.width=e.width,k.height=e.height;let C=h(k);if(C!=null){let d=e.height,z=e.width;return C.drawImage(e,0,0,z,d),i=C.getImageData(0,0,z,d).data,u.height=d,u.width=z,re(i,u)}else throw new Error("Can not access image data")}else{if(a)return new Promise((k,C)=>{let d=p(),z=h(d);if(!e||!z)return C();let B=new Image;B.crossOrigin="Anonymous",B.src=e,B.onload=()=>{d.width=B.width,d.height=B.height,z.drawImage(B,0,0,d.width,d.height);let V=z.getImageData(0,0,d.width,d.height);u.height=d.height,u.width=d.width,k(re(V.data,u))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(i!==void 0)return re(i,u);throw new Error("Input data provided is not supported - aborted tensor creation")},ce=(e,t)=>{let{width:s,height:n,download:o,dispose:a}=t,i=[1,n,s,4];return new Ke({location:"texture",type:"float32",texture:e,dims:i,download:o,dispose:a})},ke=(e,t)=>{let{dataType:s,dims:n,download:o,dispose:a}=t;return new Ke({location:"gpu-buffer",type:s??"float32",gpuBuffer:e,dims:n,download:o,dispose:a})},Ie=(e,t)=>{let{dataType:s,dims:n,download:o,dispose:a}=t;return new Ke({location:"ml-tensor",type:s??"float32",mlTensor:e,dims:n,download:o,dispose:a})},Ee=(e,t,s)=>new Ke({location:"cpu-pinned",type:e,data:t,dims:s??[t.length]})}),Ge,ye,J,de,Ce=g(()=>{Ge=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),ye=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),J=!1,de=()=>{if(!J){J=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,s=typeof Float16Array<"u"&&Float16Array.from;e&&(Ge.set("int64",BigInt64Array),ye.set(BigInt64Array,"int64")),t&&(Ge.set("uint64",BigUint64Array),ye.set(BigUint64Array,"uint64")),s?(Ge.set("float16",Float16Array),ye.set(Float16Array,"float16")):Ge.set("float16",Uint16Array)}}}),Be,Ze,se=g(()=>{je(),Be=e=>{let t=1;for(let s=0;s{switch(e.location){case"cpu":return new Ke(e.type,e.data,t);case"cpu-pinned":return new Ke({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new Ke({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new Ke({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case"ml-tensor":return new Ke({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),Ke,je=g(()=>{we(),tt(),Ce(),se(),Ke=class{constructor(e,t,s){de();let n,o;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,n=e.type,o=e.dims,e.location){case"cpu-pinned":{let i=Ge.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"&&n!=="uint4"&&n!=="int4")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=s,e==="string"){if(!Array.isArray(t))throw new TypeError("A string tensor's data must be a string array.");i=t}else{let p=Ge.get(e);if(p===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if(e==="float16"&&p===Uint16Array||e==="uint4"||e==="int4")throw new TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${p.name} as data.`);e==="uint64"||e==="int64"?i=p.from(t,BigInt):i=p.from(t)}else if(t instanceof p)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 ${p}`)}else if(u=t,Array.isArray(e)){if(e.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let p=typeof e[0];if(p==="string")n="string",i=e;else if(p==="boolean")n="bool",i=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${p}.`)}else if(e instanceof Uint8ClampedArray)n="uint8",i=Uint8Array.from(e);else{let p=ye.get(e.constructor);if(p===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);n=p,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");o=u,this.cpuData=i,this.dataLocation="cpu"}let a=Be(o);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=o,this.size=a}static async fromImage(e,t){return xe(e,t)}static fromTexture(e,t){return ce(e,t)}static fromGpuBuffer(e,t){return ke(e,t)}static fromMLTensor(e,t){return Ie(e,t)}static fromPinnedBuffer(e,t,s){return Ee(e,t,s)}toDataURL(e){return oe(this,e)}toImageData(e){return ve(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 Ze(this,e)}}}),le,Te=g(()=>{je(),le=Ke}),Ue,Ve,Ne,Re,st=g(()=>{x(),Ue=(e,t)=>{(typeof w.trace>"u"?!w.wasm.trace:!w.trace)||console.timeStamp(`${e}::ORT::${t}`)},Ve=(e,t)=>{var o;let s=((o=new Error().stack)==null?void 0:o.split(/\r\n|\r|\n/g))||[],n=!1;for(let a=0;a{(typeof w.trace>"u"?!w.wasm.trace:!w.trace)||Ve("BEGIN",e)},Re=e=>{(typeof w.trace>"u"?!w.wasm.trace:!w.trace)||Ve("END",e)}}),dt,ct=g(()=>{W(),Te(),st(),dt=class t_{constructor(t){this.handler=t}async run(t,s,n){Ne();let o={},a={};if(typeof t!="object"||t===null||t instanceof le||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 s=="object"){if(s===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(s instanceof le)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.");i=!1;for(let h of s){if(typeof h!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(h)===-1)throw new RangeError(`'fetches' contains invalid output name: ${h}.`);o[h]=null}if(typeof n=="object"&&n!==null)a=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else{let h=!1,k=Object.getOwnPropertyNames(s);for(let C of this.outputNames)if(k.indexOf(C)!==-1){let d=s[C];(d===null||d instanceof le)&&(h=!0,i=!1,o[C]=d)}if(h){if(typeof n=="object"&&n!==null)a=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else a=s}}else if(typeof s<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let h of this.inputNames)if(typeof t[h]>"u")throw new Error(`input '${h}' is missing in 'feeds'.`);if(i)for(let h of this.outputNames)o[h]=null;let u=await this.handler.run(t,o,a),p={};for(let h in u)if(Object.hasOwnProperty.call(u,h)){let k=u[h];k instanceof le?p[h]=k:p[h]=new le(k.type,k.data,k.dims)}return Re(),p}async release(){return this.handler.dispose()}static async create(t,s,n,o){Ne();let a,i={};if(typeof t=="string"){if(a=t,typeof s=="object"&&s!==null)i=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof Uint8Array){if(a=t,typeof s=="object"&&s!==null)i=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer){let k=t,C=0,d=t.byteLength;if(typeof s=="object"&&s!==null)i=s;else if(typeof s=="number"){if(C=s,!Number.isSafeInteger(C))throw new RangeError("'byteOffset' must be an integer.");if(C<0||C>=k.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${k.byteLength}).`);if(d=t.byteLength-C,typeof n=="number"){if(d=n,!Number.isSafeInteger(d))throw new RangeError("'byteLength' must be an integer.");if(d<=0||C+d>k.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${k.byteLength-C}].`);if(typeof o=="object"&&o!==null)i=o;else if(typeof o<"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 s<"u")throw new TypeError("'options' must be an object.");a=new Uint8Array(k,C,d)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[u,p]=await ne(i),h=await u.createInferenceSessionHandler(a,p);return Re(),new t_(h)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}}),lt,ht=g(()=>{ct(),lt=dt}),L=g(()=>{}),ie=g(()=>{}),H=g(()=>{}),me=g(()=>{}),$e={};v($e,{InferenceSession:()=>lt,TRACE:()=>Ue,TRACE_FUNC_BEGIN:()=>Ne,TRACE_FUNC_END:()=>Re,Tensor:()=>le,env:()=>O,registerBackend:()=>K});var We=g(()=>{j(),ae(),ht(),Te(),L(),ie(),st(),H(),me()}),Je=g(()=>{}),ut={};v(ut,{default:()=>kt});var mt,vt,kt,At=g(()=>{var e;vh(),lr(),Nr(),mt="ort-wasm-proxy-worker",vt=((e=globalThis.self)==null?void 0:e.name)===mt,vt&&(self.onmessage=t=>{let{type:s,in:n}=t.data;try{switch(s){case"init-wasm":Or(n.wasm).then(()=>{Do(n).then(()=>{postMessage({type:s})},o=>{postMessage({type:s,err:o})})},o=>{postMessage({type:s,err:o})});break;case"init-ep":{let{epName:o,env:a}=n;qn(a,o).then(()=>{postMessage({type:s})},i=>{postMessage({type:s,err:i})});break}case"copy-from":{let{buffer:o}=n,a=Qn(o);postMessage({type:s,out:a});break}case"create":{let{model:o,options:a}=n;Xn(o,a).then(i=>{postMessage({type:s,out:i})},i=>{postMessage({type:s,err:i})});break}case"release":kc(n),postMessage({type:s});break;case"run":{let{sessionId:o,inputIndices:a,inputs:i,outputIndices:u,options:p}=n;$c(o,a,i,u,new Array(u.length).fill(null),p).then(h=>{h.some(k=>k[3]!=="cpu")?postMessage({type:s,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:s,out:h},mr([...i,...h]))},h=>{postMessage({type:s,err:h})});break}case"end-profiling":Qr(n),postMessage({type:s});break;default:}}catch(o){postMessage({type:s,err:o})}}),kt=vt?null:t=>new Worker(t??Us,{type:"module",name:mt})}),os={};v(os,{default:()=>Ds});var ys,Cs,Ds,sr=g(()=>{var e;Cs=(ys=self.location.href,async function(t={}){function s(){return Ft.buffer!=Rt.buffer&&Ps(),Rt}function n(){return Ft.buffer!=Rt.buffer&&Ps(),fs}function o(){return Ft.buffer!=Rt.buffer&&Ps(),it}function a(){return Ft.buffer!=Rt.buffer&&Ps(),Et}function i(){return Ft.buffer!=Rt.buffer&&Ps(),ps}function u(){return Ft.buffer!=Rt.buffer&&Ps(),Ns}function p(){return Ft.buffer!=Rt.buffer&&Ps(),Tr}function h(){return Ft.buffer!=Rt.buffer&&Ps(),Bo}var k,C,d=Object.assign({},t),z=new Promise((l,m)=>{k=l,C=m}),B=typeof window=="object",V=typeof importScripts=="function",Z=V&&self.name=="em-pthread";d.mountExternalData=(l,m)=>{l.startsWith("./")&&(l=l.substring(2)),(d.Fb||(d.Fb=new Map)).set(l,m)},d.unmountExternalData=()=>{delete d.Fb};var ee=globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,shared:!0}).buffer.constructor;let X=()=>{let l=(E,F,G)=>(...ge)=>{let Xe=fn,nt=F==null?void 0:F();ge=E(...ge);let wt=F==null?void 0:F();return nt!==wt&&(E=wt,G(nt),F=G=null),fn!=Xe?new Promise((Ct,Wt)=>{mh={resolve:Ct,reject:Wt}}):ge},m=E=>async(...F)=>{var G;try{if(d.Gb)throw Error("Session already started");let ge=d.Gb={hc:F[0],errors:[]},Xe=await E(...F);if(d.Gb!==ge)throw Error("Session mismatch");(G=d.Hb)==null||G.flush();let nt=ge.errors;if(0Ct),0d._OrtCreateSession,E=>d._OrtCreateSession=E),d._OrtRun=m(l(d._OrtRun,()=>d._OrtRun,E=>d._OrtRun=E)),d._OrtRunWithBinding=m(l(d._OrtRunWithBinding,()=>d._OrtRunWithBinding,E=>d._OrtRunWithBinding=E)),d._OrtBindInput=l(d._OrtBindInput,()=>d._OrtBindInput,E=>d._OrtBindInput=E),X=void 0};d.jsepInit=(l,m)=>{if(X==null||X(),l==="webgpu"){[d.Hb,d.Vb,d.Zb,d.Ob,d.Yb,d.kb,d.$b,d.cc,d.Wb,d.Xb,d.ac]=m;let E=d.Hb;d.jsepRegisterBuffer=(F,G,ge,Xe)=>E.registerBuffer(F,G,ge,Xe),d.jsepGetBuffer=F=>E.getBuffer(F),d.jsepCreateDownloader=(F,G,ge)=>E.createDownloader(F,G,ge),d.jsepOnCreateSession=F=>{E.onCreateSession(F)},d.jsepOnReleaseSession=F=>{E.onReleaseSession(F)},d.jsepOnRunStart=F=>E.onRunStart(F),d.dc=(F,G)=>{E.upload(F,G)}}else if(l==="webnn"){[d.Hb,d.bc,d.Pb,d.jsepEnsureTensor,d.ec,d.jsepDownloadTensor]=m,d.jsepReleaseTensorId=d.Pb;let E=d.Hb;d.jsepOnRunStart=F=>E.onRunStart(F),d.jsepRegisterMLContext=(F,G)=>{E.registerMLContext(F,G)},d.jsepOnReleaseSession=F=>{E.onReleaseSession(F)},d.jsepCreateMLTensorDownloader=(F,G)=>E.createMLTensorDownloader(F,G),d.jsepRegisterMLTensor=(F,G,ge)=>E.registerMLTensor(F,G,ge),d.jsepCreateMLContext=F=>E.createMLContext(F),d.jsepRegisterMLConstant=(F,G,ge,Xe,nt)=>E.registerMLConstant(F,G,ge,Xe,nt,d.Fb)}};var he,pe,Me=Object.assign({},d),Oe="./this.program",Le=(l,m)=>{throw m},Ye="";(B||V)&&(V?Ye=self.location.href:typeof document<"u"&&document.currentScript&&(Ye=document.currentScript.src),ys&&(Ye=ys),Ye=Ye.startsWith("blob:")?"":Ye.substr(0,Ye.replace(/[?#].*/,"").lastIndexOf("/")+1),V&&(pe=l=>{var m=new XMLHttpRequest;return m.open("GET",l,!1),m.responseType="arraybuffer",m.send(null),new Uint8Array(m.response)}),he=(l,m,E)=>{var F=new XMLHttpRequest;F.open("GET",l,!0),F.responseType="arraybuffer",F.onload=()=>{F.status==200||F.status==0&&F.response?m(F.response):E()},F.onerror=E,F.send(null)});var at,Pt=console.log.bind(console),Xt=console.error.bind(console),Zt=Pt,bt=Xt;if(Object.assign(d,Me),Me=null,Z){let l=function(m){try{var E=m.data,F=E.cmd;if(F==="load"){let G=[];self.onmessage=ge=>G.push(ge),self.startWorker=()=>{postMessage({cmd:"loaded"});for(let ge of G)l(ge);self.onmessage=l};for(let ge of E.handlers)d[ge]&&!d[ge].proxy||(d[ge]=(...Xe)=>{postMessage({Nb:"callHandler",pc:ge,args:Xe})},ge=="print"&&(Zt=d[ge]),ge=="printErr"&&(bt=d[ge]));Ft=E.wasmMemory,Ps(),ss(E.wasmModule)}else if(F==="run"){wh(E.pthread_ptr,0,0,1,0,0),ph(E.pthread_ptr),y_(),Kh(),St||(Vm(),St=!0);try{M_(E.start_routine,E.arg)}catch(G){if(G!="unwind")throw G}}else F==="cancel"?Da()&&Up(-1):E.target!=="setimmediate"&&(F==="checkMailbox"?St&&Ip():F&&(bt(`worker: received unknown command ${F}`),bt(E)))}catch(G){throw Wm(),G}};var ss,St=!1;bt=function(...m){m=m.join(" "),console.error(m)},self.alert=function(...m){postMessage({Nb:"alert",text:m.join(" "),rc:Da()})},d.instantiateWasm=(m,E)=>new Promise(F=>{ss=G=>{G=new WebAssembly.Instance(G,jh()),E(G),F()}}),self.onunhandledrejection=m=>{throw m.reason||m},self.onmessage=l}d.wasmBinary&&(at=d.wasmBinary);var Ft,bs,Ht,Rt,fs,it,Et,ps,Ns,Tr,er,hn,Bo,zs=!1;function Ps(){var l=Ft.buffer;d.HEAP8=Rt=new Int8Array(l),d.HEAP16=it=new Int16Array(l),d.HEAPU8=fs=new Uint8Array(l),d.HEAPU16=Et=new Uint16Array(l),d.HEAP32=ps=new Int32Array(l),d.HEAPU32=Ns=new Uint32Array(l),d.HEAPF32=Tr=new Float32Array(l),d.HEAPF64=Bo=new Float64Array(l),d.HEAP64=er=new BigInt64Array(l),d.HEAPU64=hn=new BigUint64Array(l)}if(!Z){if(!((Ft=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0})).buffer instanceof ee))throw bt("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");Ps()}var Jn=[],Oc=[],Zp=[],Fc=0,Dc=null;function Lh(){if(--Fc==0&&Dc){var l=Dc;Dc=null,l()}}function Zn(l){throw bt(l="Aborted("+l+")"),zs=!0,Ht=1,l=new WebAssembly.RuntimeError(l+". Build with -sASSERTIONS for more info."),C(l),l}var eh,zh=l=>l.startsWith("data:application/octet-stream;base64,"),Bh=l=>l.startsWith("file://");function Rh(l){if(l==eh&&at)return new Uint8Array(at);if(pe)return pe(l);throw"both async and sync fetching of the wasm failed"}function Nh(l,m,E){return function(F){if(!at&&(B||V)){if(typeof fetch=="function"&&!Bh(F))return fetch(F,{credentials:"same-origin"}).then(G=>{if(!G.ok)throw`failed to load wasm binary file at '${F}'`;return G.arrayBuffer()}).catch(()=>Rh(F));if(he)return new Promise((G,ge)=>{he(F,Xe=>G(new Uint8Array(Xe)),ge)})}return Promise.resolve().then(()=>Rh(F))}(l).then(F=>WebAssembly.instantiate(F,m)).then(E,F=>{bt(`failed to asynchronously prepare wasm: ${F}`),Zn(F)})}function jh(){return{a:{O:w_,Aa:g_,b:v_,aa:Xh,B:Zh,qa:em,Y:sm,_:rm,ra:nm,oa:om,ha:im,na:am,L:lm,Z:um,W:dm,pa:cm,X:pm,va:x_,F:T_,Q:P_,P:C_,E:S_,u:$_,q:A_,G:I_,A:R_,R:N_,ua:j_,ka:U_,U:V_,ba:W_,H:G_,ja:ph,ta:K_,t:H_,Ba:q_,x:Y_,n:J_,l:ef,c:dh,o:tf,j:nf,w:of,p:af,f:lf,s:uf,m:df,e:cf,k:pf,i:hf,h:mf,d:_f,ea:ff,fa:gf,ga:wf,ca:Em,da:Cm,T:yf,g:Mf,D:bf,I:vf,M:xf,y:Tf,sa:Pf,V:Ef,v:Sm,z:Cf,N:kf,S:Sf,za:$f,ya:Af,la:Im,ma:Om,$:oh,C:Fm,K:Dm,ia:Lm,J:zm,a:Ft,xa:nh,wa:Nm,r:Ff}}}var th={913700:(l,m,E,F,G)=>{if(d===void 0||!d.Fb)return 1;if((l=Qs(Number(l>>>0))).startsWith("./")&&(l=l.substring(2)),!(l=d.Fb.get(l)))return 2;if(m=Number(m>>>0),E=Number(E>>>0),F=Number(F>>>0),m+E>l.byteLength)return 3;try{let ge=l.subarray(m,m+E);switch(G){case 0:n().set(ge,F>>>0);break;case 1:d.dc(F,ge);break;default:return 4}return 0}catch{return 4}},914415:(l,m,E)=>{d.ec(l,n().subarray(m>>>0,m+E>>>0))},914478:()=>d.bc(),914519:l=>{d.Pb(l)},914555:()=>{d.Wb()},914586:()=>{d.Xb()},914615:()=>{d.ac()},914640:l=>d.Vb(l),914673:l=>d.Zb(l),914705:(l,m,E)=>{d.Ob(Number(l),Number(m),Number(E),!0)},914768:(l,m,E)=>{d.Ob(Number(l),Number(m),Number(E))},914825:()=>typeof wasmOffsetConverter<"u",914882:l=>{d.kb("Abs",l,void 0)},914933:l=>{d.kb("Neg",l,void 0)},914984:l=>{d.kb("Floor",l,void 0)},915037:l=>{d.kb("Ceil",l,void 0)},915089:l=>{d.kb("Reciprocal",l,void 0)},915147:l=>{d.kb("Sqrt",l,void 0)},915199:l=>{d.kb("Exp",l,void 0)},915250:l=>{d.kb("Erf",l,void 0)},915301:l=>{d.kb("Sigmoid",l,void 0)},915356:(l,m,E)=>{d.kb("HardSigmoid",l,{alpha:m,beta:E})},915435:l=>{d.kb("Log",l,void 0)},915486:l=>{d.kb("Sin",l,void 0)},915537:l=>{d.kb("Cos",l,void 0)},915588:l=>{d.kb("Tan",l,void 0)},915639:l=>{d.kb("Asin",l,void 0)},915691:l=>{d.kb("Acos",l,void 0)},915743:l=>{d.kb("Atan",l,void 0)},915795:l=>{d.kb("Sinh",l,void 0)},915847:l=>{d.kb("Cosh",l,void 0)},915899:l=>{d.kb("Asinh",l,void 0)},915952:l=>{d.kb("Acosh",l,void 0)},916005:l=>{d.kb("Atanh",l,void 0)},916058:l=>{d.kb("Tanh",l,void 0)},916110:l=>{d.kb("Not",l,void 0)},916161:(l,m,E)=>{d.kb("Clip",l,{min:m,max:E})},916230:l=>{d.kb("Clip",l,void 0)},916282:(l,m)=>{d.kb("Elu",l,{alpha:m})},916340:l=>{d.kb("Gelu",l,void 0)},916392:l=>{d.kb("Relu",l,void 0)},916444:(l,m)=>{d.kb("LeakyRelu",l,{alpha:m})},916508:(l,m)=>{d.kb("ThresholdedRelu",l,{alpha:m})},916578:(l,m)=>{d.kb("Cast",l,{to:m})},916636:l=>{d.kb("Add",l,void 0)},916687:l=>{d.kb("Sub",l,void 0)},916738:l=>{d.kb("Mul",l,void 0)},916789:l=>{d.kb("Div",l,void 0)},916840:l=>{d.kb("Pow",l,void 0)},916891:l=>{d.kb("Equal",l,void 0)},916944:l=>{d.kb("Greater",l,void 0)},916999:l=>{d.kb("GreaterOrEqual",l,void 0)},917061:l=>{d.kb("Less",l,void 0)},917113:l=>{d.kb("LessOrEqual",l,void 0)},917172:(l,m,E,F,G)=>{d.kb("ReduceMean",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:F?Array.from(i().subarray(Number(F)>>>0,Number(G)>>>0)):[]})},917347:(l,m,E,F,G)=>{d.kb("ReduceMax",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:F?Array.from(i().subarray(Number(F)>>>0,Number(G)>>>0)):[]})},917521:(l,m,E,F,G)=>{d.kb("ReduceMin",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:F?Array.from(i().subarray(Number(F)>>>0,Number(G)>>>0)):[]})},917695:(l,m,E,F,G)=>{d.kb("ReduceProd",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:F?Array.from(i().subarray(Number(F)>>>0,Number(G)>>>0)):[]})},917870:(l,m,E,F,G)=>{d.kb("ReduceSum",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:F?Array.from(i().subarray(Number(F)>>>0,Number(G)>>>0)):[]})},918044:(l,m,E,F,G)=>{d.kb("ReduceL1",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:F?Array.from(i().subarray(Number(F)>>>0,Number(G)>>>0)):[]})},918217:(l,m,E,F,G)=>{d.kb("ReduceL2",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:F?Array.from(i().subarray(Number(F)>>>0,Number(G)>>>0)):[]})},918390:(l,m,E,F,G)=>{d.kb("ReduceLogSum",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:F?Array.from(i().subarray(Number(F)>>>0,Number(G)>>>0)):[]})},918567:(l,m,E,F,G)=>{d.kb("ReduceSumSquare",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:F?Array.from(i().subarray(Number(F)>>>0,Number(G)>>>0)):[]})},918747:(l,m,E,F,G)=>{d.kb("ReduceLogSumExp",l,{keepDims:!!m,noopWithEmptyAxes:!!E,axes:F?Array.from(i().subarray(Number(F)>>>0,Number(G)>>>0)):[]})},918927:l=>{d.kb("Where",l,void 0)},918980:(l,m,E)=>{d.kb("Transpose",l,{perm:m?Array.from(i().subarray(Number(m)>>>0,Number(E)>>>0)):[]})},919104:(l,m,E,F)=>{d.kb("DepthToSpace",l,{blocksize:m,mode:Qs(E),format:F?"NHWC":"NCHW"})},919237:(l,m,E,F)=>{d.kb("DepthToSpace",l,{blocksize:m,mode:Qs(E),format:F?"NHWC":"NCHW"})},919370:(l,m,E,F,G,ge,Xe,nt,wt,Ct,Wt,hs,vs,He,ls)=>{d.kb("ConvTranspose",l,{format:wt?"NHWC":"NCHW",autoPad:m,dilations:[E],group:F,kernelShape:[G],pads:[ge,Xe],strides:[nt],wIsConst:()=>!!s()[Ct>>>0],outputPadding:Wt?Array.from(i().subarray(Number(Wt)>>>0,Number(hs)>>>0)):[],outputShape:vs?Array.from(i().subarray(Number(vs)>>>0,Number(He)>>>0)):[],activation:Qs(ls)})},919803:(l,m,E,F,G,ge,Xe,nt,wt,Ct,Wt,hs,vs,He)=>{d.kb("ConvTranspose",l,{format:nt?"NHWC":"NCHW",autoPad:m,dilations:Array.from(i().subarray(Number(E)>>>0,2+(Number(E)>>>0)>>>0)),group:F,kernelShape:Array.from(i().subarray(Number(G)>>>0,2+(Number(G)>>>0)>>>0)),pads:Array.from(i().subarray(Number(ge)>>>0,4+(Number(ge)>>>0)>>>0)),strides:Array.from(i().subarray(Number(Xe)>>>0,2+(Number(Xe)>>>0)>>>0)),wIsConst:()=>!!s()[wt>>>0],outputPadding:Ct?Array.from(i().subarray(Number(Ct)>>>0,Number(Wt)>>>0)):[],outputShape:hs?Array.from(i().subarray(Number(hs)>>>0,Number(vs)>>>0)):[],activation:Qs(He)})},920464:(l,m,E,F,G,ge,Xe,nt,wt,Ct,Wt,hs,vs,He,ls)=>{d.kb("ConvTranspose",l,{format:wt?"NHWC":"NCHW",autoPad:m,dilations:[E],group:F,kernelShape:[G],pads:[ge,Xe],strides:[nt],wIsConst:()=>!!s()[Ct>>>0],outputPadding:Wt?Array.from(i().subarray(Number(Wt)>>>0,Number(hs)>>>0)):[],outputShape:vs?Array.from(i().subarray(Number(vs)>>>0,Number(He)>>>0)):[],activation:Qs(ls)})},920897:(l,m,E,F,G,ge,Xe,nt,wt,Ct,Wt,hs,vs,He)=>{d.kb("ConvTranspose",l,{format:nt?"NHWC":"NCHW",autoPad:m,dilations:Array.from(i().subarray(Number(E)>>>0,2+(Number(E)>>>0)>>>0)),group:F,kernelShape:Array.from(i().subarray(Number(G)>>>0,2+(Number(G)>>>0)>>>0)),pads:Array.from(i().subarray(Number(ge)>>>0,4+(Number(ge)>>>0)>>>0)),strides:Array.from(i().subarray(Number(Xe)>>>0,2+(Number(Xe)>>>0)>>>0)),wIsConst:()=>!!s()[wt>>>0],outputPadding:Ct?Array.from(i().subarray(Number(Ct)>>>0,Number(Wt)>>>0)):[],outputShape:hs?Array.from(i().subarray(Number(hs)>>>0,Number(vs)>>>0)):[],activation:Qs(He)})},921558:(l,m)=>{d.kb("GlobalAveragePool",l,{format:m?"NHWC":"NCHW"})},921649:(l,m,E,F,G,ge,Xe,nt,wt,Ct,Wt,hs,vs,He)=>{d.kb("AveragePool",l,{format:He?"NHWC":"NCHW",auto_pad:m,ceil_mode:E,count_include_pad:F,storage_order:G,dilations:ge?Array.from(i().subarray(Number(ge)>>>0,Number(Xe)>>>0)):[],kernel_shape:nt?Array.from(i().subarray(Number(nt)>>>0,Number(wt)>>>0)):[],pads:Ct?Array.from(i().subarray(Number(Ct)>>>0,Number(Wt)>>>0)):[],strides:hs?Array.from(i().subarray(Number(hs)>>>0,Number(vs)>>>0)):[]})},922128:(l,m)=>{d.kb("GlobalAveragePool",l,{format:m?"NHWC":"NCHW"})},922219:(l,m,E,F,G,ge,Xe,nt,wt,Ct,Wt,hs,vs,He)=>{d.kb("AveragePool",l,{format:He?"NHWC":"NCHW",auto_pad:m,ceil_mode:E,count_include_pad:F,storage_order:G,dilations:ge?Array.from(i().subarray(Number(ge)>>>0,Number(Xe)>>>0)):[],kernel_shape:nt?Array.from(i().subarray(Number(nt)>>>0,Number(wt)>>>0)):[],pads:Ct?Array.from(i().subarray(Number(Ct)>>>0,Number(Wt)>>>0)):[],strides:hs?Array.from(i().subarray(Number(hs)>>>0,Number(vs)>>>0)):[]})},922698:(l,m)=>{d.kb("GlobalMaxPool",l,{format:m?"NHWC":"NCHW"})},922785:(l,m,E,F,G,ge,Xe,nt,wt,Ct,Wt,hs,vs,He)=>{d.kb("MaxPool",l,{format:He?"NHWC":"NCHW",auto_pad:m,ceil_mode:E,count_include_pad:F,storage_order:G,dilations:ge?Array.from(i().subarray(Number(ge)>>>0,Number(Xe)>>>0)):[],kernel_shape:nt?Array.from(i().subarray(Number(nt)>>>0,Number(wt)>>>0)):[],pads:Ct?Array.from(i().subarray(Number(Ct)>>>0,Number(Wt)>>>0)):[],strides:hs?Array.from(i().subarray(Number(hs)>>>0,Number(vs)>>>0)):[]})},923260:(l,m)=>{d.kb("GlobalMaxPool",l,{format:m?"NHWC":"NCHW"})},923347:(l,m,E,F,G,ge,Xe,nt,wt,Ct,Wt,hs,vs,He)=>{d.kb("MaxPool",l,{format:He?"NHWC":"NCHW",auto_pad:m,ceil_mode:E,count_include_pad:F,storage_order:G,dilations:ge?Array.from(i().subarray(Number(ge)>>>0,Number(Xe)>>>0)):[],kernel_shape:nt?Array.from(i().subarray(Number(nt)>>>0,Number(wt)>>>0)):[],pads:Ct?Array.from(i().subarray(Number(Ct)>>>0,Number(Wt)>>>0)):[],strides:hs?Array.from(i().subarray(Number(hs)>>>0,Number(vs)>>>0)):[]})},923822:(l,m,E,F,G)=>{d.kb("Gemm",l,{alpha:m,beta:E,transA:F,transB:G})},923926:l=>{d.kb("MatMul",l,void 0)},923980:(l,m,E,F)=>{d.kb("ArgMax",l,{keepDims:!!m,selectLastIndex:!!E,axis:F})},924088:(l,m,E,F)=>{d.kb("ArgMin",l,{keepDims:!!m,selectLastIndex:!!E,axis:F})},924196:(l,m)=>{d.kb("Softmax",l,{axis:m})},924259:(l,m)=>{d.kb("Concat",l,{axis:m})},924319:(l,m,E,F,G)=>{d.kb("Split",l,{axis:m,numOutputs:E,splitSizes:F?Array.from(i().subarray(Number(F)>>>0,Number(G)>>>0)):[]})},924475:l=>{d.kb("Expand",l,void 0)},924529:(l,m)=>{d.kb("Gather",l,{axis:Number(m)})},924600:(l,m)=>{d.kb("GatherElements",l,{axis:Number(m)})},924679:(l,m)=>{d.kb("GatherND",l,{batch_dims:Number(m)})},924758:(l,m,E,F,G,ge,Xe,nt,wt,Ct,Wt)=>{d.kb("Resize",l,{antialias:m,axes:E?Array.from(i().subarray(Number(E)>>>0,Number(F)>>>0)):[],coordinateTransformMode:Qs(G),cubicCoeffA:ge,excludeOutside:Xe,extrapolationValue:nt,keepAspectRatioPolicy:Qs(wt),mode:Qs(Ct),nearestMode:Qs(Wt)})},925120:(l,m,E,F,G,ge,Xe)=>{d.kb("Slice",l,{starts:m?Array.from(i().subarray(Number(m)>>>0,Number(E)>>>0)):[],ends:F?Array.from(i().subarray(Number(F)>>>0,Number(G)>>>0)):[],axes:ge?Array.from(i().subarray(Number(ge)>>>0,Number(Xe)>>>0)):[]})},925384:l=>{d.kb("Tile",l,void 0)},925436:(l,m,E)=>{d.kb("InstanceNormalization",l,{epsilon:m,format:E?"NHWC":"NCHW"})},925550:(l,m,E)=>{d.kb("InstanceNormalization",l,{epsilon:m,format:E?"NHWC":"NCHW"})},925664:l=>{d.kb("Range",l,void 0)},925717:(l,m)=>{d.kb("Einsum",l,{equation:Qs(m)})},925798:(l,m,E,F,G)=>{d.kb("Pad",l,{mode:m,value:E,pads:F?Array.from(i().subarray(Number(F)>>>0,Number(G)>>>0)):[]})},925941:(l,m,E,F,G,ge)=>{d.kb("BatchNormalization",l,{epsilon:m,momentum:E,spatial:!!G,trainingMode:!!F,format:ge?"NHWC":"NCHW"})},926110:(l,m,E,F,G,ge)=>{d.kb("BatchNormalization",l,{epsilon:m,momentum:E,spatial:!!G,trainingMode:!!F,format:ge?"NHWC":"NCHW"})},926279:(l,m,E)=>{d.kb("CumSum",l,{exclusive:Number(m),reverse:Number(E)})},926376:(l,m,E)=>{d.kb("DequantizeLinear",l,{axis:m,blockSize:E})},926466:(l,m,E,F,G)=>{d.kb("GridSample",l,{align_corners:m,mode:Qs(E),padding_mode:Qs(F),format:G?"NHWC":"NCHW"})},926636:(l,m,E,F,G)=>{d.kb("GridSample",l,{align_corners:m,mode:Qs(E),padding_mode:Qs(F),format:G?"NHWC":"NCHW"})},926806:(l,m,E,F,G,ge,Xe,nt,wt)=>{d.kb("Attention",l,{numHeads:m,isUnidirectional:E,maskFilterValue:F,scale:G,doRotary:ge,qkvHiddenSizes:Xe?Array.from(i().subarray(Number(nt)>>>0,Number(nt)+Xe>>>0)):[],pastPresentShareBuffer:!!wt})},927078:l=>{d.kb("BiasAdd",l,void 0)},927133:l=>{d.kb("BiasSplitGelu",l,void 0)},927194:l=>{d.kb("FastGelu",l,void 0)},927250:(l,m,E,F,G,ge,Xe,nt,wt,Ct,Wt,hs,vs,He,ls,js)=>{d.kb("Conv",l,{format:hs?"NHWC":"NCHW",auto_pad:m,dilations:E?Array.from(i().subarray(Number(E)>>>0,Number(F)>>>0)):[],group:G,kernel_shape:ge?Array.from(i().subarray(Number(ge)>>>0,Number(Xe)>>>0)):[],pads:nt?Array.from(i().subarray(Number(nt)>>>0,Number(wt)>>>0)):[],strides:Ct?Array.from(i().subarray(Number(Ct)>>>0,Number(Wt)>>>0)):[],w_is_const:()=>!!s()[Number(vs)>>>0],activation:Qs(He),activation_params:ls?Array.from(p().subarray(Number(ls)>>>0,Number(js)>>>0)):[]})},927834:l=>{d.kb("Gelu",l,void 0)},927886:(l,m,E,F,G,ge,Xe,nt,wt)=>{d.kb("GroupQueryAttention",l,{numHeads:m,kvNumHeads:E,scale:F,softcap:G,doRotary:ge,rotaryInterleaved:Xe,smoothSoftmax:nt,localWindowSize:wt})},928103:(l,m,E,F)=>{d.kb("LayerNormalization",l,{axis:m,epsilon:E,simplified:!!F})},928214:(l,m,E,F)=>{d.kb("LayerNormalization",l,{axis:m,epsilon:E,simplified:!!F})},928325:(l,m,E,F,G,ge)=>{d.kb("MatMulNBits",l,{k:m,n:E,accuracyLevel:F,bits:G,blockSize:ge})},928452:(l,m,E,F,G,ge)=>{d.kb("MultiHeadAttention",l,{numHeads:m,isUnidirectional:E,maskFilterValue:F,scale:G,doRotary:ge})},928611:(l,m)=>{d.kb("QuickGelu",l,{alpha:m})},928675:(l,m,E,F,G)=>{d.kb("RotaryEmbedding",l,{interleaved:!!m,numHeads:E,rotaryEmbeddingDim:F,scale:G})},928814:(l,m,E)=>{d.kb("SkipLayerNormalization",l,{epsilon:m,simplified:!!E})},928916:(l,m,E)=>{d.kb("SkipLayerNormalization",l,{epsilon:m,simplified:!!E})},929018:(l,m,E,F)=>{d.kb("GatherBlockQuantized",l,{gatherAxis:m,quantizeAxis:E,blockSize:F})},929139:l=>{d.$b(l)},929173:(l,m)=>d.cc(Number(l),Number(m),d.Gb.hc,d.Gb.errors)};function g_(l,m,E){return bm(async()=>{await d.Yb(Number(l),Number(m),Number(E))})}function w_(){return typeof wasmOffsetConverter<"u"}function sh(l){this.name="ExitStatus",this.message=`Program terminated with exit(${l})`,this.status=l}var rh=l=>{l.terminate(),l.onmessage=()=>{}},Uh=l=>{eo.length==0&&(qh(),Hh(eo[0]));var m=eo.pop();if(!m)return 6;No.push(m),mn[l.Bb]=m,m.Bb=l.Bb;var E={cmd:"run",start_routine:l.ic,arg:l.Rb,pthread_ptr:l.Bb};return m.postMessage(E,l.nc),0},Ro=0,Bs=(l,m,...E)=>{for(var F=2*E.length,G=bh(),ge=Mh(8*F),Xe=ge>>>3,nt=0;nt>>0]=wt)}return l=Gm(l,0,F,ge,m),Vp(G),l};function nh(l){if(Z)return Bs(0,1,l);if(Ht=l,!(0{if(Ht=l,Z)throw Vh(l),"unwind";nh(l)},eo=[],No=[],Wh=[],mn={},Gh=l=>{var m=l.Bb;delete mn[m],eo.push(l),No.splice(No.indexOf(l),1),l.Bb=0,yh(m)};function Kh(){Wh.forEach(l=>l())}var Hh=l=>new Promise(m=>{l.onmessage=G=>{var ge=(G=G.data).cmd;if(G.targetThread&&G.targetThread!=Da()){var Xe=mn[G.targetThread];Xe?Xe.postMessage(G,G.transferList):bt(`Internal error! Worker sent a message "${ge}" to target pthread ${G.targetThread}, but that thread no longer exists!`)}else ge==="checkMailbox"?Ip():ge==="spawnThread"?Uh(G):ge==="cleanupThread"?Gh(mn[G.thread]):ge==="killThread"?(G=G.thread,ge=mn[G],delete mn[G],rh(ge),yh(G),No.splice(No.indexOf(ge),1),ge.Bb=0):ge==="cancelThread"?mn[G.thread].postMessage({cmd:"cancel"}):ge==="loaded"?(l.loaded=!0,m(l)):ge==="alert"?alert(`Thread ${G.threadId}: ${G.text}`):G.target==="setimmediate"?l.postMessage(G):ge==="callHandler"?d[G.handler](...G.args):ge&&bt(`worker sent an unknown command ${ge}`)},l.onerror=G=>{throw bt(`worker sent an error! ${G.filename}:${G.lineno}: ${G.message}`),G};var E,F=[];for(E of[])d.hasOwnProperty(E)&&F.push(E);l.postMessage({cmd:"load",handlers:F,wasmMemory:Ft,wasmModule:bs})});function qh(){var l=new Worker(self.location.href.startsWith("file:")?new URL(r("./node_modules/onnxruntime-web/dist/ort.bundle.min.mjs?46eb"),r.b):new URL(self.location.href),{type:"module",workerData:"em-pthread",name:"em-pthread"});eo.push(l)}var Ap=l=>{for(;0{var l=Da(),m=u()[l+52>>>2>>>0];l=u()[l+56>>>2>>>0],Hm(m,m-l),Vp(m)},M_=(l,m)=>{Ro=0,l=qm(l,m),0>>=0);throw m>>>=0,E>>>=0,u()[F.Kb+16>>>2>>>0]=0,u()[F.Kb+4>>>2>>>0]=m,u()[F.Kb+8>>>2>>>0]=E,l}function Qh(l,m,E,F){return Z?Bs(2,1,l,m,E,F):Xh(l,m,E,F)}function Xh(l,m,E,F){if(l>>>=0,m>>>=0,E>>>=0,F>>>=0,ee===void 0)return bt("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var G=[];return Z&&G.length===0?Qh(l,m,E,F):(l={ic:E,Bb:l,Rb:F,nc:G},Z?(l.Nb="spawnThread",postMessage(l,G),0):Uh(l))}var Yh=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,Jh=(l,m,E)=>{var F=(m>>>=0)+E;for(E=m;l[E]&&!(E>=F);)++E;if(16(G=(240&G)==224?(15&G)<<12|ge<<6|Xe:(7&G)<<18|ge<<12|Xe<<6|63&l[m++])?F+=String.fromCharCode(G):(G-=65536,F+=String.fromCharCode(55296|G>>10,56320|1023&G))}}else F+=String.fromCharCode(G)}return F},Qs=(l,m)=>(l>>>=0)?Jh(n(),l,m):"";function Zh(l,m,E){return Z?Bs(3,1,l,m,E):0}function em(l,m){if(Z)return Bs(4,1,l,m)}var ih=l=>{for(var m=0,E=0;E=F?m++:2047>=F?m+=2:55296<=F&&57343>=F?(m+=4,++E):m+=3}return m},tm=(l,m,E,F)=>{if(!(0>>=0;F=E+F-1;for(var ge=0;ge=Xe&&(Xe=65536+((1023&Xe)<<10)|1023&l.charCodeAt(++ge)),127>=Xe){if(E>=F)break;m[E++>>>0]=Xe}else{if(2047>=Xe){if(E+1>=F)break;m[E++>>>0]=192|Xe>>6}else{if(65535>=Xe){if(E+2>=F)break;m[E++>>>0]=224|Xe>>12}else{if(E+3>=F)break;m[E++>>>0]=240|Xe>>18,m[E++>>>0]=128|Xe>>12&63}m[E++>>>0]=128|Xe>>6&63}m[E++>>>0]=128|63&Xe}}return m[E>>>0]=0,E-G},Oa=(l,m,E)=>tm(l,n(),m,E);function sm(l,m){if(Z)return Bs(5,1,l,m)}function rm(l,m,E){if(Z)return Bs(6,1,l,m,E)}function nm(l,m,E){return Z?Bs(7,1,l,m,E):0}function om(l,m){if(Z)return Bs(8,1,l,m)}function im(l,m,E){if(Z)return Bs(9,1,l,m,E)}function am(l,m,E,F){if(Z)return Bs(10,1,l,m,E,F)}function lm(l,m,E,F){if(Z)return Bs(11,1,l,m,E,F)}function um(l,m,E,F){if(Z)return Bs(12,1,l,m,E,F)}function dm(l){if(Z)return Bs(13,1,l)}function cm(l,m){if(Z)return Bs(14,1,l,m)}function pm(l,m,E){if(Z)return Bs(15,1,l,m,E)}var hm,to,x_=()=>{Zn("")},_n=l=>{for(var m="";n()[l>>>0];)m+=hm[n()[l++>>>0]];return m},ah={},lh={};function Sn(l,m,E={}){if(!("argPackAdvance"in m))throw new TypeError("registerType registeredInstance requires argPackAdvance");return function(F,G,ge={}){var Xe=G.name;if(!F)throw new to(`type "${Xe}" must have a positive integer typeid pointer`);if(lh.hasOwnProperty(F)){if(ge.Tb)return;throw new to(`Cannot register type '${Xe}' twice`)}lh[F]=G,ah.hasOwnProperty(F)&&(G=ah[F],delete ah[F],G.forEach(nt=>nt()))}(l,m,E)}var mm=(l,m,E)=>{switch(m){case 1:return E?F=>s()[F>>>0]:F=>n()[F>>>0];case 2:return E?F=>o()[F>>>1>>>0]:F=>a()[F>>>1>>>0];case 4:return E?F=>i()[F>>>2>>>0]:F=>u()[F>>>2>>>0];case 8:return E?F=>er[F>>>3]:F=>hn[F>>>3];default:throw new TypeError(`invalid integer width (${m}): ${l}`)}};function T_(l,m,E){E>>>=0,Sn(l>>>=0,{name:m=_n(m>>>0),fromWireType:F=>F,toWireType:function(F,G){if(typeof G!="bigint"&&typeof G!="number")throw G=G===null?"null":(F=typeof G)=="object"||F==="array"||F==="function"?G.toString():""+G,new TypeError(`Cannot convert "${G}" to ${this.name}`);return typeof G=="number"&&(G=BigInt(G)),G},argPackAdvance:so,readValueFromPointer:mm(m,E,m.indexOf("u")==-1),Eb:null})}var so=8;function P_(l,m,E,F){Sn(l>>>=0,{name:m=_n(m>>>0),fromWireType:function(G){return!!G},toWireType:function(G,ge){return ge?E:F},argPackAdvance:so,readValueFromPointer:function(G){return this.fromWireType(n()[G>>>0])},Eb:null})}var uh=[],$n=[];function dh(l){9<(l>>>=0)&&--$n[l+1]==0&&($n[l]=void 0,uh.push(l))}var kr=l=>{if(!l)throw new to("Cannot use deleted val. handle = "+l);return $n[l]},Br=l=>{switch(l){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let m=uh.pop()||$n.length;return $n[m]=l,$n[m+1]=1,m}};function ch(l){return this.fromWireType(u()[l>>>2>>>0])}var E_={name:"emscripten::val",fromWireType:l=>{var m=kr(l);return dh(l),m},toWireType:(l,m)=>Br(m),argPackAdvance:so,readValueFromPointer:ch,Eb:null};function C_(l){return Sn(l>>>0,E_)}var k_=(l,m)=>{switch(m){case 4:return function(E){return this.fromWireType(p()[E>>>2>>>0])};case 8:return function(E){return this.fromWireType(h()[E>>>3>>>0])};default:throw new TypeError(`invalid float width (${m}): ${l}`)}};function S_(l,m,E){E>>>=0,Sn(l>>>=0,{name:m=_n(m>>>0),fromWireType:F=>F,toWireType:(F,G)=>G,argPackAdvance:so,readValueFromPointer:k_(m,E),Eb:null})}function $_(l,m,E,F,G){if(l>>>=0,E>>>=0,m=_n(m>>>0),G===-1&&(G=4294967295),G=nt=>nt,F===0){var ge=32-8*E;G=nt=>nt<>>ge}var Xe=m.includes("unsigned")?function(nt,wt){return wt>>>0}:function(nt,wt){return wt};Sn(l,{name:m,fromWireType:G,toWireType:Xe,argPackAdvance:so,readValueFromPointer:mm(m,E,F!==0),Eb:null})}function A_(l,m,E){function F(ge){var Xe=u()[ge>>>2>>>0];return ge=u()[ge+4>>>2>>>0],new G(s().buffer,ge,Xe)}var G=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][m];Sn(l>>>=0,{name:E=_n(E>>>0),fromWireType:F,argPackAdvance:so,readValueFromPointer:F},{Tb:!0})}function I_(l,m){l>>>=0;var E=(m=_n(m>>>0))==="std::string";Sn(l,{name:m,fromWireType:function(F){var G=u()[F>>>2>>>0],ge=F+4;if(E)for(var Xe=ge,nt=0;nt<=G;++nt){var wt=ge+nt;if(nt==G||n()[wt>>>0]==0){if(Xe=Qs(Xe,wt-Xe),Ct===void 0)var Ct=Xe;else Ct+="\0",Ct+=Xe;Xe=wt+1}}else{for(Ct=Array(G),nt=0;nt>>0]);Ct=Ct.join("")}return gn(F),Ct},toWireType:function(F,G){G instanceof ArrayBuffer&&(G=new Uint8Array(G));var ge=typeof G=="string";if(!(ge||G instanceof Uint8Array||G instanceof Uint8ClampedArray||G instanceof Int8Array))throw new to("Cannot pass non-string to std::string");var Xe=E&&ge?ih(G):G.length,nt=jp(4+Xe+1),wt=nt+4;if(u()[nt>>>2>>>0]=Xe,E&&ge)Oa(G,wt,Xe+1);else if(ge)for(ge=0;ge>>0]=Ct}else for(ge=0;ge>>0]=G[ge];return F!==null&&F.push(gn,nt),nt},argPackAdvance:so,readValueFromPointer:ch,Eb(F){gn(F)}})}var _m=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,O_=(l,m)=>{for(var E=l>>1,F=E+m/2;!(E>=F)&&a()[E>>>0];)++E;if(32<(E<<=1)-l&&_m)return _m.decode(n().slice(l,E));for(E="",F=0;!(F>=m/2);++F){var G=o()[l+2*F>>>1>>>0];if(G==0)break;E+=String.fromCharCode(G)}return E},F_=(l,m,E)=>{if(E??(E=2147483647),2>E)return 0;var F=m;E=(E-=2)<2*l.length?E/2:l.length;for(var G=0;G>>1>>>0]=ge,m+=2}return o()[m>>>1>>>0]=0,m-F},D_=l=>2*l.length,L_=(l,m)=>{for(var E=0,F="";!(E>=m/4);){var G=i()[l+4*E>>>2>>>0];if(G==0)break;++E,65536<=G?(G-=65536,F+=String.fromCharCode(55296|G>>10,56320|1023&G)):F+=String.fromCharCode(G)}return F},z_=(l,m,E)=>{if(m>>>=0,E??(E=2147483647),4>E)return 0;var F=m;E=F+E-4;for(var G=0;G=ge&&(ge=65536+((1023&ge)<<10)|1023&l.charCodeAt(++G)),i()[m>>>2>>>0]=ge,(m+=4)+4>E)break}return i()[m>>>2>>>0]=0,m-F},B_=l=>{for(var m=0,E=0;E=F&&++E,m+=4}return m};function R_(l,m,E){if(l>>>=0,m>>>=0,E=_n(E>>>=0),m===2)var F=O_,G=F_,ge=D_,Xe=nt=>a()[nt>>>1>>>0];else m===4&&(F=L_,G=z_,ge=B_,Xe=nt=>u()[nt>>>2>>>0]);Sn(l,{name:E,fromWireType:nt=>{for(var wt,Ct=u()[nt>>>2>>>0],Wt=nt+4,hs=0;hs<=Ct;++hs){var vs=nt+4+hs*m;hs!=Ct&&Xe(vs)!=0||(Wt=F(Wt,vs-Wt),wt===void 0?wt=Wt:(wt+="\0",wt+=Wt),Wt=vs+m)}return gn(nt),wt},toWireType:(nt,wt)=>{if(typeof wt!="string")throw new to(`Cannot pass non-string to C++ string type ${E}`);var Ct=ge(wt),Wt=jp(4+Ct+m);return u()[Wt>>>2>>>0]=Ct/m,G(wt,Wt+4,Ct+m),nt!==null&&nt.push(gn,Wt),Wt},argPackAdvance:so,readValueFromPointer:ch,Eb(nt){gn(nt)}})}function N_(l,m){Sn(l>>>=0,{Ub:!0,name:m=_n(m>>>0),argPackAdvance:0,fromWireType:()=>{},toWireType:()=>{}})}var j_=()=>1;function U_(l){wh(l>>>0,!V,1,!B,131072,!1),Kh()}var fm=l=>{if(!zs)try{if(l(),!(0>>=0,typeof Atomics.oc=="function"&&(Atomics.oc(i(),l>>>2,l).value.then(Ip),l+=128,Atomics.store(i(),l>>>2,1))}var Ip=()=>{var l=Da();l&&(ph(l),fm(Km))};function V_(l,m){(l>>>=0)==m>>>0?setTimeout(Ip):Z?postMessage({targetThread:l,cmd:"checkMailbox"}):(l=mn[l])&&l.postMessage({cmd:"checkMailbox"})}var hh=[];function W_(l,m,E,F,G){for(m>>>=0,F/=2,hh.length=F,E=G>>>0>>>3,G=0;G>>0];return(m?th[m]:Df[l])(...hh)}function G_(l){l>>>=0,Z?postMessage({cmd:"cleanupThread",thread:l}):Gh(mn[l])}function K_(l){}var Op=(l,m)=>{var E=lh[l];if(E===void 0)throw l=Um(l),E=_n(l),gn(l),new to(`${m} has unknown type ${E}`);return E},gm=(l,m,E)=>{var F=[];return l=l.toWireType(F,E),F.length&&(u()[m>>>2>>>0]=Br(F)),l};function H_(l,m,E){return m>>>=0,E>>>=0,l=kr(l>>>0),m=Op(m,"emval::as"),gm(m,E,l)}function q_(l,m){return m>>>=0,l=kr(l>>>0),(m=Op(m,"emval::as")).toWireType(null,l)}var Fp=l=>{try{l()}catch(m){Zn(m)}},ro=0,fn=null,wm=0,Dp=[],ym={},Mm={},Q_=0,mh=null,X_=[];function bm(l){return function(m){if(!zs){if(ro===0){var E=!1,F=!1;m((G=0)=>{if(!zs&&(wm=G,E=!0,F)){ro=2,Fp(()=>Ym(fn)),typeof Browser<"u"&&Browser.Lb.Sb&&Browser.Lb.resume(),G=!1;try{var ge=function(){var wt=i()[fn+8>>>2>>>0];return wt=Ut[Mm[wt]],--Ro,wt()}()}catch(wt){ge=wt,G=!0}var Xe=!1;if(!fn){var nt=mh;nt&&(mh=null,(G?nt.reject:nt.resolve)(ge),Xe=!0)}if(G&&!Xe)throw ge}}),F=!0,E||(ro=1,fn=function(){var G=jp(65548),ge=G+12;u()[G>>>2>>>0]=ge,u()[G+4>>>2>>>0]=ge+65536,ge=Dp[0];var Xe=ym[ge];return Xe===void 0&&(Xe=Q_++,ym[ge]=Xe,Mm[Xe]=ge),ge=Xe,i()[G+8>>>2>>>0]=ge,G}(),typeof Browser<"u"&&Browser.Lb.Sb&&Browser.Lb.pause(),Fp(()=>Qm(fn)))}else ro===2?(ro=0,Fp(Jm),gn(fn),fn=null,X_.forEach(fm)):Zn(`invalid state: ${ro}`);return wm}}(m=>{l().then(m)})}function Y_(l){return l>>>=0,bm(()=>(l=kr(l)).then(Br))}var Lp=[];function J_(l,m,E,F){return E>>>=0,F>>>=0,(l=Lp[l>>>0])(null,m=kr(m>>>0),E,F)}var Z_={},zp=l=>{var m=Z_[l];return m===void 0?_n(l):m};function ef(l,m,E,F,G){return E>>>=0,F>>>=0,G>>>=0,(l=Lp[l>>>0])(m=kr(m>>>0),m[E=zp(E)],F,G)}var vm=()=>typeof globalThis=="object"?globalThis:Function("return this")();function tf(l){return(l>>>=0)==0?Br(vm()):(l=zp(l),Br(vm()[l]))}var sf=l=>{var m=Lp.length;return Lp.push(l),m},rf=(l,m)=>{for(var E=Array(l),F=0;F>>2>>>0],"parameter "+F);return E},xm=(l,m)=>Object.defineProperty(m,"name",{value:l});function nf(l,m,E){var F=(m=rf(l,m>>>0)).shift();l--;var G=`return function (obj, func, destructorsRef, args) { -`,ge=0,Xe=[];E===0&&Xe.push("obj");for(var nt=["retType"],wt=[F],Ct=0;CtWt.name).join(", ")}) => ${F.name}>`,sf(xm(E,l))}function of(l){return l=zp(l>>>0),Br(d[l])}function af(l,m){return m>>>=0,l=kr(l>>>0),m=kr(m),Br(l[m])}function lf(l){9<(l>>>=0)&&($n[l+1]+=1)}function uf(){return Br([])}function df(l){l=kr(l>>>0);for(var m=Array(l.length),E=0;E>>0))}function pf(){return Br({})}function hf(l){for(var m=kr(l>>>=0);m.length;){var E=m.pop();m.pop()(E)}dh(l)}function mf(l,m,E){m>>>=0,E>>>=0,l=kr(l>>>0),m=kr(m),E=kr(E),l[m]=E}function _f(l,m){return m>>>=0,l=(l=Op(l>>>0,"_emval_take_value")).readValueFromPointer(m),Br(l)}function ff(l,m){l=-9007199254740992>l||9007199254740992>>=0,l=new Date(1e3*l),i()[m>>>2>>>0]=l.getUTCSeconds(),i()[m+4>>>2>>>0]=l.getUTCMinutes(),i()[m+8>>>2>>>0]=l.getUTCHours(),i()[m+12>>>2>>>0]=l.getUTCDate(),i()[m+16>>>2>>>0]=l.getUTCMonth(),i()[m+20>>>2>>>0]=l.getUTCFullYear()-1900,i()[m+24>>>2>>>0]=l.getUTCDay(),l=(l.getTime()-Date.UTC(l.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,i()[m+28>>>2>>>0]=l}var Fa=l=>l%4==0&&(l%100!=0||l%400==0),Tm=[0,31,60,91,121,152,182,213,244,274,305,335],Pm=[0,31,59,90,120,151,181,212,243,273,304,334];function gf(l,m){l=-9007199254740992>l||9007199254740992>>=0,l=new Date(1e3*l),i()[m>>>2>>>0]=l.getSeconds(),i()[m+4>>>2>>>0]=l.getMinutes(),i()[m+8>>>2>>>0]=l.getHours(),i()[m+12>>>2>>>0]=l.getDate(),i()[m+16>>>2>>>0]=l.getMonth(),i()[m+20>>>2>>>0]=l.getFullYear()-1900,i()[m+24>>>2>>>0]=l.getDay();var E=(Fa(l.getFullYear())?Tm:Pm)[l.getMonth()]+l.getDate()-1|0;i()[m+28>>>2>>>0]=E,i()[m+36>>>2>>>0]=-60*l.getTimezoneOffset(),E=new Date(l.getFullYear(),6,1).getTimezoneOffset();var F=new Date(l.getFullYear(),0,1).getTimezoneOffset();l=0|(E!=F&&l.getTimezoneOffset()==Math.min(F,E)),i()[m+32>>>2>>>0]=l}function wf(l){l>>>=0;var m=new Date(i()[l+20>>>2>>>0]+1900,i()[l+16>>>2>>>0],i()[l+12>>>2>>>0],i()[l+8>>>2>>>0],i()[l+4>>>2>>>0],i()[l>>>2>>>0],0),E=i()[l+32>>>2>>>0],F=m.getTimezoneOffset(),G=new Date(m.getFullYear(),6,1).getTimezoneOffset(),ge=new Date(m.getFullYear(),0,1).getTimezoneOffset(),Xe=Math.min(ge,G);return 0>E?i()[l+32>>>2>>>0]=+(G!=ge&&Xe==F):0>>2>>>0]=m.getDay(),E=(Fa(m.getFullYear())?Tm:Pm)[m.getMonth()]+m.getDate()-1|0,i()[l+28>>>2>>>0]=E,i()[l>>>2>>>0]=m.getSeconds(),i()[l+4>>>2>>>0]=m.getMinutes(),i()[l+8>>>2>>>0]=m.getHours(),i()[l+12>>>2>>>0]=m.getDate(),i()[l+16>>>2>>>0]=m.getMonth(),i()[l+20>>>2>>>0]=m.getYear(),l=m.getTime(),BigInt(isNaN(l)?-1:l/1e3)}function Em(l,m,E,F,G,ge,Xe){return Z?Bs(16,1,l,m,E,F,G,ge,Xe):-52}function Cm(l,m,E,F,G,ge){if(Z)return Bs(17,1,l,m,E,F,G,ge)}function yf(l,m,E,F){l>>>=0,m>>>=0,E>>>=0,F>>>=0;var G=new Date().getFullYear(),ge=new Date(G,0,1),Xe=new Date(G,6,1);G=ge.getTimezoneOffset();var nt=Xe.getTimezoneOffset(),wt=Math.max(G,nt);u()[l>>>2>>>0]=60*wt,i()[m>>>2>>>0]=+(G!=nt),ge=(l=Ct=>Ct.toLocaleTimeString(void 0,{hour12:!1,timeZoneName:"short"}).split(" ")[1])(ge),Xe=l(Xe),nt{_h.length=0;for(var E;E=n()[l++>>>0];){var F=E!=105;m+=(F&=E!=112)&&m%8?4:0,_h.push(E==112?u()[m>>>2>>>0]:E==106?er[m>>>3]:E==105?i()[m>>>2>>>0]:h()[m>>>3>>>0]),m+=F?8:4}return _h};function Mf(l,m,E){return l>>>=0,m=km(m>>>0,E>>>0),th[l](...m)}function bf(l,m,E){return l>>>=0,m=km(m>>>0,E>>>0),th[l](...m)}var vf=()=>{},xf=()=>Date.now();function Tf(l,m){return bt(Qs(l>>>0,m>>>0))}var Sm,Pf=()=>{throw Ro+=1,"unwind"};function Ef(){return 4294901760}Sm=()=>performance.timeOrigin+performance.now();var Cf=()=>navigator.hardwareConcurrency;function kf(){return Zn("Cannot use emscripten_pc_get_function without -sUSE_OFFSET_CONVERTER"),0}function Sf(l){l>>>=0;var m=n().length;if(l<=m||4294901760=E;E*=2){var F=m*(1+.2/E);F=Math.min(F,l+100663296);var G=Math;F=Math.max(l,F);e:{G=(G.min.call(G,4294901760,F+(65536-F%65536)%65536)-Ft.buffer.byteLength+65535)/65536;try{Ft.grow(G),Ps();var ge=1;break e}catch{}ge=void 0}if(ge)return!0}return!1}var Bp=()=>(Zn("Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER"),0),Lc={},$m=l=>{l.forEach(m=>{Bp()})};function $f(){var l=Error().stack.toString().split(` -`);return l[0]=="Error"&&l.shift(),$m(l),Lc.Qb=Bp(),Lc.fc=l,Lc.Qb}function Af(l,m,E){if(l>>>=0,m>>>=0,Lc.Qb==l)var F=Lc.fc;else(F=Error().stack.toString().split(` -`))[0]=="Error"&&F.shift(),$m(F);for(var G=3;F[G]&&Bp()!=l;)++G;for(l=0;l>>2>>>0]=Bp();return l}var fh,gh={},Am=()=>{if(!fh){var l,m={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:Oe};for(l in gh)gh[l]===void 0?delete m[l]:m[l]=gh[l];var E=[];for(l in m)E.push(`${l}=${m[l]}`);fh=E}return fh};function Im(l,m){if(Z)return Bs(18,1,l,m);l>>>=0,m>>>=0;var E=0;return Am().forEach((F,G)=>{var ge=m+E;for(G=u()[l+4*G>>>2>>>0]=ge,ge=0;ge>>0]=F.charCodeAt(ge);s()[G>>>0]=0,E+=F.length+1}),0}function Om(l,m){if(Z)return Bs(19,1,l,m);l>>>=0,m>>>=0;var E=Am();u()[l>>>2>>>0]=E.length;var F=0;return E.forEach(G=>F+=G.length+1),u()[m>>>2>>>0]=F,0}function Fm(l){return Z?Bs(20,1,l):52}function Dm(l,m,E,F){return Z?Bs(21,1,l,m,E,F):52}function Lm(l,m,E,F){return Z?Bs(22,1,l,m,E,F):70}var If=[null,[],[]];function zm(l,m,E,F){if(Z)return Bs(23,1,l,m,E,F);m>>>=0,E>>>=0,F>>>=0;for(var G=0,ge=0;ge>>2>>>0],nt=u()[m+4>>>2>>>0];m+=8;for(var wt=0;wt>>0],Wt=If[l];Ct===0||Ct===10?((l===1?Zt:bt)(Jh(Wt,0)),Wt.length=0):Wt.push(Ct)}G+=nt}return u()[F>>>2>>>0]=G,0}var Bm=[31,29,31,30,31,30,31,31,30,31,30,31],Rm=[31,28,31,30,31,30,31,31,30,31,30,31],Of=(l,m)=>{s().set(l,m>>>0)};function Nm(l,m,E,F){function G(He,ls,js){for(He=typeof He=="number"?He.toString():He||"";He.lengthe_?-1:0jo-He.getDate())){He.setDate(He.getDate()+ls);break}ls-=jo-He.getDate()+1,He.setDate(1),11>js?He.setMonth(js+1):(He.setMonth(0),He.setFullYear(He.getFullYear()+1))}return js=new Date(He.getFullYear()+1,0,4),ls=nt(new Date(He.getFullYear(),0,4)),js=nt(js),0>=Xe(ls,He)?0>=Xe(js,He)?He.getFullYear()+1:He.getFullYear():He.getFullYear()-1}l>>>=0,m>>>=0,E>>>=0,F>>>=0;var Ct=u()[F+40>>>2>>>0];for(var Wt in F={lc:i()[F>>>2>>>0],kc:i()[F+4>>>2>>>0],Ib:i()[F+8>>>2>>>0],Mb:i()[F+12>>>2>>>0],Jb:i()[F+16>>>2>>>0],Db:i()[F+20>>>2>>>0],vb:i()[F+24>>>2>>>0],Cb:i()[F+28>>>2>>>0],sc:i()[F+32>>>2>>>0],jc:i()[F+36>>>2>>>0],mc:Ct?Qs(Ct):""},E=Qs(E),Ct={"%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"})E=E.replace(new RegExp(Wt,"g"),Ct[Wt]);var hs="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),vs="January February March April May June July August September October November December".split(" ");for(Wt in Ct={"%a":He=>hs[He.vb].substring(0,3),"%A":He=>hs[He.vb],"%b":He=>vs[He.Jb].substring(0,3),"%B":He=>vs[He.Jb],"%C":He=>ge((He.Db+1900)/100|0,2),"%d":He=>ge(He.Mb,2),"%e":He=>G(He.Mb,2," "),"%g":He=>wt(He).toString().substring(2),"%G":wt,"%H":He=>ge(He.Ib,2),"%I":He=>((He=He.Ib)==0?He=12:12{for(var ls=0,js=0;js<=He.Jb-1;ls+=(Fa(He.Db+1900)?Bm:Rm)[js++]);return ge(He.Mb+ls,3)},"%m":He=>ge(He.Jb+1,2),"%M":He=>ge(He.kc,2),"%n":()=>` -`,"%p":He=>0<=He.Ib&&12>He.Ib?"AM":"PM","%S":He=>ge(He.lc,2),"%t":()=>" ","%u":He=>He.vb||7,"%U":He=>ge(Math.floor((He.Cb+7-He.vb)/7),2),"%V":He=>{var ls=Math.floor((He.Cb+7-(He.vb+6)%7)/7);if(2>=(He.vb+371-He.Cb-2)%7&&ls++,ls)ls==53&&((js=(He.vb+371-He.Cb)%7)==4||js==3&&Fa(He.Db)||(ls=1));else{ls=52;var js=(He.vb+7-He.Cb-1)%7;(js==4||js==5&&Fa(He.Db%400-1))&&ls++}return ge(ls,2)},"%w":He=>He.vb,"%W":He=>ge(Math.floor((He.Cb+7-(He.vb+6)%7)/7),2),"%y":He=>(He.Db+1900).toString().substring(2),"%Y":He=>He.Db+1900,"%z":He=>{var ls=0<=(He=He.jc);return He=Math.abs(He)/60,(ls?"+":"-")+("0000"+(He/60*100+He%60)).slice(-4)},"%Z":He=>He.mc,"%%":()=>"%"},E=E.replace(/%%/g,"\0\0"),Ct)E.includes(Wt)&&(E=E.replace(new RegExp(Wt,"g"),Ct[Wt](F)));return Wt=function(He){var ls=Array(ih(He)+1);return tm(He,ls,0,ls.length),ls}(E=E.replace(/\0\0/g,"%")),Wt.length>m?0:(Of(Wt,l),Wt.length-1)}function Ff(l,m,E,F){return Nm(l>>>0,m>>>0,E>>>0,F>>>0)}Z||function(){for(var l=d.numThreads-1;l--;)qh();Jn.unshift(()=>{Fc++,function(m){Z?m():Promise.all(eo.map(Hh)).then(m)}(()=>Lh())})}();for(var jm=Array(256),Rp=0;256>Rp;++Rp)jm[Rp]=String.fromCharCode(Rp);hm=jm,to=d.BindingError=class extends Error{constructor(l){super(l),this.name="BindingError"}},d.InternalError=class extends Error{constructor(l){super(l),this.name="InternalError"}},$n.push(0,1,void 0,1,null,1,!0,1,!1,1),d.count_emval_handles=()=>$n.length/2-5-uh.length;var Df=[nh,Vh,Qh,Zh,em,sm,rm,nm,om,im,am,lm,um,dm,cm,pm,Em,Cm,Im,Om,Fm,Dm,Lm,zm],Ut=function(){function l(E,F){return Ut=E.exports,Ut=function(){var G=Ut,ge={};for(let[Xe,nt]of Object.entries(G))ge[Xe]=typeof nt=="function"?(...wt)=>{Dp.push(Xe);try{return nt(...wt)}finally{zs||(Dp.pop(),fn&&ro===1&&Dp.length===0&&(ro=0,Ro+=1,Fp(Xm),typeof Fibers<"u"&&Fibers.tc()))}}:nt;return ge}(),Ut=function(){var G=Ut,ge=nt=>wt=>nt(wt)>>>0,Xe=nt=>()=>nt()>>>0;return(G=Object.assign({},G)).Da=ge(G.Da),G.gb=Xe(G.gb),G.ib=ge(G.ib),G.emscripten_main_runtime_thread_id=Xe(G.emscripten_main_runtime_thread_id),G.tb=ge(G.tb),G.ub=Xe(G.ub),G}(),Wh.push(Ut.jb),Oc.unshift(Ut.Ca),bs=F,Lh(),Ut}var m=jh();if(Fc++,d.instantiateWasm)try{return d.instantiateWasm(m,l)}catch(E){bt(`Module.instantiateWasm callback failed with error: ${E}`),C(E)}return eh||(eh=d.locateFile?zh("ort-wasm-simd-threaded.jsep.wasm")?"ort-wasm-simd-threaded.jsep.wasm":d.locateFile?d.locateFile("ort-wasm-simd-threaded.jsep.wasm",Ye):Ye+"ort-wasm-simd-threaded.jsep.wasm":new URL(r("./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm"),r.b).href),function(E,F){var G=eh;return at||typeof WebAssembly.instantiateStreaming!="function"||zh(G)||Bh(G)||typeof fetch!="function"?Nh(G,E,F):fetch(G,{credentials:"same-origin"}).then(ge=>WebAssembly.instantiateStreaming(ge,E).then(F,function(Xe){return bt(`wasm streaming compile failed: ${Xe}`),bt("falling back to ArrayBuffer instantiation"),Nh(G,E,F)}))}(m,function(E){l(E.instance,E.module)}).catch(C),{}}(),Um=l=>(Um=Ut.Da)(l),Vm=()=>(Vm=Ut.Ea)();d._OrtInit=(l,m)=>(d._OrtInit=Ut.Fa)(l,m),d._OrtGetLastError=(l,m)=>(d._OrtGetLastError=Ut.Ga)(l,m),d._OrtCreateSessionOptions=(l,m,E,F,G,ge,Xe,nt,wt,Ct)=>(d._OrtCreateSessionOptions=Ut.Ha)(l,m,E,F,G,ge,Xe,nt,wt,Ct),d._OrtAppendExecutionProvider=(l,m)=>(d._OrtAppendExecutionProvider=Ut.Ia)(l,m),d._OrtAddFreeDimensionOverride=(l,m,E)=>(d._OrtAddFreeDimensionOverride=Ut.Ja)(l,m,E),d._OrtAddSessionConfigEntry=(l,m,E)=>(d._OrtAddSessionConfigEntry=Ut.Ka)(l,m,E),d._OrtReleaseSessionOptions=l=>(d._OrtReleaseSessionOptions=Ut.La)(l),d._OrtCreateSession=(l,m,E)=>(d._OrtCreateSession=Ut.Ma)(l,m,E),d._OrtReleaseSession=l=>(d._OrtReleaseSession=Ut.Na)(l),d._OrtGetInputOutputCount=(l,m,E)=>(d._OrtGetInputOutputCount=Ut.Oa)(l,m,E),d._OrtGetInputName=(l,m)=>(d._OrtGetInputName=Ut.Pa)(l,m),d._OrtGetOutputName=(l,m)=>(d._OrtGetOutputName=Ut.Qa)(l,m),d._OrtFree=l=>(d._OrtFree=Ut.Ra)(l),d._OrtCreateTensor=(l,m,E,F,G,ge)=>(d._OrtCreateTensor=Ut.Sa)(l,m,E,F,G,ge),d._OrtGetTensorData=(l,m,E,F,G)=>(d._OrtGetTensorData=Ut.Ta)(l,m,E,F,G),d._OrtReleaseTensor=l=>(d._OrtReleaseTensor=Ut.Ua)(l),d._OrtCreateRunOptions=(l,m,E,F)=>(d._OrtCreateRunOptions=Ut.Va)(l,m,E,F),d._OrtAddRunConfigEntry=(l,m,E)=>(d._OrtAddRunConfigEntry=Ut.Wa)(l,m,E),d._OrtReleaseRunOptions=l=>(d._OrtReleaseRunOptions=Ut.Xa)(l),d._OrtCreateBinding=l=>(d._OrtCreateBinding=Ut.Ya)(l),d._OrtBindInput=(l,m,E)=>(d._OrtBindInput=Ut.Za)(l,m,E),d._OrtBindOutput=(l,m,E,F)=>(d._OrtBindOutput=Ut._a)(l,m,E,F),d._OrtClearBoundOutputs=l=>(d._OrtClearBoundOutputs=Ut.$a)(l),d._OrtReleaseBinding=l=>(d._OrtReleaseBinding=Ut.ab)(l),d._OrtRunWithBinding=(l,m,E,F,G)=>(d._OrtRunWithBinding=Ut.bb)(l,m,E,F,G),d._OrtRun=(l,m,E,F,G,ge,Xe,nt)=>(d._OrtRun=Ut.cb)(l,m,E,F,G,ge,Xe,nt),d._OrtEndProfiling=l=>(d._OrtEndProfiling=Ut.db)(l),d._JsepOutput=(l,m,E)=>(d._JsepOutput=Ut.eb)(l,m,E),d._JsepGetNodeName=l=>(d._JsepGetNodeName=Ut.fb)(l);var Np,Da=()=>(Da=Ut.gb)(),gn=d._free=l=>(gn=d._free=Ut.hb)(l),jp=d._malloc=l=>(jp=d._malloc=Ut.ib)(l),wh=(l,m,E,F,G,ge)=>(wh=Ut.lb)(l,m,E,F,G,ge),Wm=()=>(Wm=Ut.mb)(),Gm=(l,m,E,F,G)=>(Gm=Ut.nb)(l,m,E,F,G),yh=l=>(yh=Ut.ob)(l),Up=l=>(Up=Ut.pb)(l),Km=()=>(Km=Ut.qb)(),Hm=(l,m)=>(Hm=Ut.rb)(l,m),Vp=l=>(Vp=Ut.sb)(l),Mh=l=>(Mh=Ut.tb)(l),bh=()=>(bh=Ut.ub)(),qm=d.dynCall_ii=(l,m)=>(qm=d.dynCall_ii=Ut.wb)(l,m),Qm=l=>(Qm=Ut.xb)(l),Xm=()=>(Xm=Ut.yb)(),Ym=l=>(Ym=Ut.zb)(l),Jm=()=>(Jm=Ut.Ab)();function Zm(){0bh(),d.stackRestore=l=>Vp(l),d.stackAlloc=l=>Mh(l),d.setValue=function(l,m,E="i8"){switch(E.endsWith("*")&&(E="*"),E){case"i1":case"i8":s()[l>>>0]=m;break;case"i16":o()[l>>>1>>>0]=m;break;case"i32":i()[l>>>2>>>0]=m;break;case"i64":er[l>>>3]=BigInt(m);break;case"float":p()[l>>>2>>>0]=m;break;case"double":h()[l>>>3>>>0]=m;break;case"*":u()[l>>>2>>>0]=m;break;default:Zn(`invalid type for setValue: ${E}`)}},d.getValue=function(l,m="i8"){switch(m.endsWith("*")&&(m="*"),m){case"i1":case"i8":return s()[l>>>0];case"i16":return o()[l>>>1>>>0];case"i32":return i()[l>>>2>>>0];case"i64":return er[l>>>3];case"float":return p()[l>>>2>>>0];case"double":return h()[l>>>3>>>0];case"*":return u()[l>>>2>>>0];default:Zn(`invalid type for getValue: ${m}`)}},d.UTF8ToString=Qs,d.stringToUTF8=Oa,d.lengthBytesUTF8=ih,Dc=function l(){Np||Zm(),Np||(Dc=l)},Zm(),d.PTR_SIZE=4,z}),Ds=Cs,((e=globalThis.self)==null?void 0:e.name)==="em-pthread"&&Cs()}),Sr,Yr,Us,Pr,Nt,Jr,$r,Ar,Zr,cr,en,Ir,Rr,Nr=g(()=>{Je(),Sr=typeof location>"u"?void 0:location.origin,Yr=()=>{var e;return(e=self.location.href)!=null&&e.startsWith("file:")?new URL(new URL(r("./node_modules/onnxruntime-web/dist/ort.bundle.min.mjs?46eb"),r.b).href,Sr).href:self.location.href},Us=Yr(),Pr=()=>{if(Us&&!Us.startsWith("blob:"))return Us.substring(0,Us.lastIndexOf("/")+1)},Nt=(e,t)=>{try{let s=t??Us;return(s?new URL(e,s):new URL(e)).origin===Sr}catch{return!1}},Jr=(e,t)=>{let s=t??Us;try{return(s?new URL(e,s):new URL(e)).href}catch{return}},$r=(e,t)=>`${t??"./"}${e}`,Ar=async e=>{let t=await(await fetch(e,{credentials:"same-origin"})).blob();return URL.createObjectURL(t)},Zr=async e=>(await import(e)).default,cr=(At(),y(ut)).default,en=async()=>{if(!Us)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(Nt(Us))return[void 0,cr()];let e=await Ar(Us);return[e,cr(e)]},Ir=(sr(),y(os)).default,Rr=async(e,t,s)=>{if(!e&&!t&&Ir&&Us&&Nt(Us))return[void 0,Ir];{let n="ort-wasm-simd-threaded.jsep.mjs",o=e??Jr(n,t),a=s&&o&&!Nt(o,t),i=a?await Ar(o):o??$r(n,t);return[a?i:void 0,await Zr(i)]}}}),ar,ot,Tt,Dt,Vs,jr,Or,Ms,lr=g(()=>{Nr(),ot=!1,Tt=!1,Dt=!1,Vs=()=>{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}},jr=()=>{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}},Or=async e=>{if(ot)return Promise.resolve();if(Tt)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Dt)throw new Error("previous call to 'initializeWebAssembly()' failed.");Tt=!0;let t=e.initTimeout,s=e.numThreads;if(!jr())throw new Error("WebAssembly SIMD is not supported in the current environment.");let n=Vs();s>1&&!n&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+s+", 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=s=1);let o=e.wasmPaths,a=typeof o=="string"?o:void 0,i=o==null?void 0:o.mjs,u=(i==null?void 0:i.href)??i,p=o==null?void 0:o.wasm,h=(p==null?void 0:p.href)??p,k=e.wasmBinary,[C,d]=await Rr(u,a,s>1),z=!1,B=[];if(t>0&&B.push(new Promise(V=>{setTimeout(()=>{z=!0,V()},t)})),B.push(new Promise((V,Z)=>{let ee={numThreads:s};if(k)ee.wasmBinary=k;else if(h||a)ee.locateFile=X=>h??a+X;else if(u&&u.indexOf("blob:")!==0)ee.locateFile=X=>new URL(X,u).href;else if(C){let X=Pr();X&&(ee.locateFile=he=>X+he)}d(ee).then(X=>{Tt=!1,ot=!0,ar=X,V(),C&&URL.revokeObjectURL(C)},X=>{Tt=!1,Dt=!0,Z(X)})})),await Promise.race(B),z)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},Ms=()=>{if(ot&&ar)return ar;throw new Error("WebAssembly is not initialized yet.")}}),Os,Er,es,wn=g(()=>{lr(),Os=(e,t)=>{let s=Ms(),n=s.lengthBytesUTF8(e)+1,o=s._malloc(n);return s.stringToUTF8(e,o,n),t.push(o),o},Er=(e,t,s,n)=>{if(typeof e=="object"&&e!==null){if(s.has(e))throw new Error("Circular reference in options");s.add(e)}Object.entries(e).forEach(([o,a])=>{let i=t?t+o:o;if(typeof a=="object")Er(a,i+".",s,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}`)})},es=e=>{let t=Ms(),s=t.stackSave();try{let n=t.PTR_SIZE,o=t.stackAlloc(2*n);t._OrtGetLastError(o,o+n);let a=Number(t.getValue(o,n===4?"i32":"i64")),i=t.getValue(o+n,"*"),u=i?t.UTF8ToString(i):"";throw new Error(`${e} ERROR_CODE: ${a}, ERROR_MESSAGE: ${u}`)}finally{t.stackRestore(s)}}}),Ur,oo=g(()=>{lr(),wn(),Ur=e=>{let t=Ms(),s=0,n=[],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 a=0;return(e==null?void 0:e.tag)!==void 0&&(a=Os(e.tag,n)),s=t._OrtCreateRunOptions(o.logSeverityLevel,o.logVerbosityLevel,!!o.terminate,a),s===0&&es("Can't create run options."),(e==null?void 0:e.extra)!==void 0&&Er(e.extra,"",new WeakSet,(i,u)=>{let p=Os(i,n),h=Os(u,n);t._OrtAddRunConfigEntry(s,p,h)!==0&&es(`Can't set a run config entry: ${i} - ${u}.`)}),[s,n]}catch(a){throw s!==0&&t._OrtReleaseRunOptions(s),n.forEach(i=>t._free(i)),a}}}),An,In,On,Vr,Fn,io=g(()=>{lr(),wn(),An=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}`)}},In=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},On=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(s=>(typeof s=="string"?s:s.name)==="webgpu")&&(e.enableMemPattern=!1)},Vr=(e,t,s)=>{for(let n of t){let o=typeof n=="string"?n:n.name;switch(o){case"webnn":if(o="WEBNN",typeof n!="string"){let i=n==null?void 0:n.deviceType;if(i){let u=Os("deviceType",s),p=Os(i,s);Ms()._OrtAddSessionConfigEntry(e,u,p)!==0&&es(`Can't set a session config entry: 'deviceType' - ${i}.`)}}break;case"webgpu":if(o="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=Os("preferredLayout",s),p=Os(i.preferredLayout,s);Ms()._OrtAddSessionConfigEntry(e,u,p)!==0&&es(`Can't set a session config entry: 'preferredLayout' - ${i.preferredLayout}.`)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${o}`)}let a=Os(o,s);Ms()._OrtAppendExecutionProvider(e,a)!==0&&es(`Can't append execution provider: ${o}.`)}},Fn=e=>{let t=Ms(),s=0,n=[],o=e||{};On(o);try{let a=An(o.graphOptimizationLevel??"all"),i=In(o.executionMode??"sequential"),u=typeof o.logId=="string"?Os(o.logId,n):0,p=o.logSeverityLevel??2;if(!Number.isInteger(p)||p<0||p>4)throw new Error(`log serverity level is not valid: ${p}`);let h=o.logVerbosityLevel??0;if(!Number.isInteger(h)||h<0||h>4)throw new Error(`log verbosity level is not valid: ${h}`);let k=typeof o.optimizedModelFilePath=="string"?Os(o.optimizedModelFilePath,n):0;if(s=t._OrtCreateSessionOptions(a,!!o.enableCpuMemArena,!!o.enableMemPattern,i,!!o.enableProfiling,0,u,p,h,k),s===0&&es("Can't create session options."),o.executionProviders&&Vr(s,o.executionProviders,n),o.enableGraphCapture!==void 0){if(typeof o.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${o.enableGraphCapture}`);let C=Os("enableGraphCapture",n),d=Os(o.enableGraphCapture.toString(),n);t._OrtAddSessionConfigEntry(s,C,d)!==0&&es(`Can't set a session config entry: 'enableGraphCapture' - ${o.enableGraphCapture}.`)}if(o.freeDimensionOverrides)for(let[C,d]of Object.entries(o.freeDimensionOverrides)){if(typeof C!="string")throw new Error(`free dimension override name must be a string: ${C}`);if(typeof d!="number"||!Number.isInteger(d)||d<0)throw new Error(`free dimension override value must be a non-negative integer: ${d}`);let z=Os(C,n);t._OrtAddFreeDimensionOverride(s,z,d)!==0&&es(`Can't set a free dimension override: ${C} - ${d}.`)}return o.extra!==void 0&&Er(o.extra,"",new WeakSet,(C,d)=>{let z=Os(C,n),B=Os(d,n);t._OrtAddSessionConfigEntry(s,z,B)!==0&&es(`Can't set a session config entry: ${C} - ${d}.`)}),[s,n]}catch(a){throw s!==0&&t._OrtReleaseSessionOptions(s)!==0&&es("Can't release session options."),n.forEach(i=>t._free(i)),a}}}),Wr,_r,ur,yn,tn,Mn,bn,vn,zt=g(()=>{Wr=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}`)}},_r=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}`)}},ur=(e,t)=>{let s=[-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((o,a)=>o*a,1);return s>0?Math.ceil(n*s):void 0},yn=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}`)}},tn=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}`)}},Mn=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",bn=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint64"||e==="int8"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",vn=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}`)}}}),xn,Dn=g(()=>{Je(),xn=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 s=t.headers.get("Content-Length"),n=s?parseInt(s,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 o=t.body.getReader(),a;try{a=new ArrayBuffer(n)}catch(u){if(u instanceof RangeError){let p=Math.ceil(n/65536);a=new WebAssembly.Memory({initial:p,maximum:p}).buffer}else throw u}let i=0;for(;;){let{done:u,value:p}=await o.read();if(u)break;let h=p.byteLength;new Uint8Array(a,i,h).set(p),i+=h}return new Uint8Array(a,0,n)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),Ln,zn,Gr,Bn,Tn,Rn,as,Pe=g(()=>{zt(),Ln=["V","I","W","E","F"],zn=(e,t)=>{console.log(`[${Ln[e]},${new Date().toISOString()}]${t}`)},Tn=(e,t)=>{Gr=e,Bn=t},Rn=(e,t)=>{let s=tn(e),n=tn(Gr);s>=n&&zn(s,typeof t=="function"?t():t)},as=(...e)=>{Bn&&Rn(...e)}}),P,Q=g(()=>{zt(),P=(e,t)=>new(yn(t))(e)}),ue=g(()=>{}),be,Se,Qe,pt,gt,_t,xt,Kt,ms,us=g(()=>{Pe(),ue(),be=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]]),Se=[],Qe=e=>Math.ceil(Number(e)/16)*16,pt=e=>{for(let t=0;tgt++,xt=async(e,t,s,n)=>{let o=Qe(s),a=e.device.createBuffer({size:o,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let i=e.getCommandEncoder();e.endComputePass(),i.copyBufferToBuffer(t,0,a,0,o),e.flush(),await a.mapAsync(GPUMapMode.READ);let u=a.getMappedRange();if(n){let p=n();return p.set(new Uint8Array(u,0,s)),p}else return new Uint8Array(u.slice(0,s))}finally{a.destroy()}},Kt=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[t]of be)Se.push(t),this.freeBuffers.set(t,[]),this.freeUniformBuffers.set(t,[]);this.sessionCount=0}upload(e,t){let s=t.buffer,n=t.byteOffset,o=t.byteLength,a=Qe(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 u=this.backend.device.createBuffer({mappedAtCreation:!0,size:a,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),p=u.getMappedRange();new Uint8Array(p).set(new Uint8Array(s,n,o)),u.unmap();let h=this.backend.device.createCommandEncoder();h.copyBufferToBuffer(u,0,i.gpuData.buffer,0,a),this.backend.device.queue.submit([h.finish()]),u.destroy(),as("verbose",()=>`[WebGPU] GpuDataManager.upload(id=${e})`)}memcpy(e,t){let s=this.storageCache.get(e);if(!s)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(s.originalSize!==n.originalSize)throw new Error("inconsistent source and destination gpu data size");let o=Qe(s.originalSize),a=this.backend.getCommandEncoder();this.backend.endComputePass(),a.copyBufferToBuffer(s.gpuData.buffer,0,n.gpuData.buffer,0,o)}registerExternalBuffer(e,t,s){let n;if(s){if(n=s[0],e===s[1])return as("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=_t();return this.storageCache.set(n,{gpuData:{id:n,type:0,buffer:e},originalSize:t}),as("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${n}, registered.`),n}unregisterExternalBuffer(e){e!==void 0&&(this.storageCache.delete(e),as("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${e}`))}create(e,t=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let s=pt(e),n,o=(t&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,a=(t&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(o||a){let u=(o?this.freeBuffers:this.freeUniformBuffers).get(s);u?u.length>0?n=u.pop():n=this.backend.device.createBuffer({size:s,usage:t}):n=this.backend.device.createBuffer({size:s,usage:t})}else n=this.backend.device.createBuffer({size:s,usage:t});let i={id:_t(),type:0,buffer:n};return this.storageCache.set(i.id,{gpuData:i,originalSize:Number(e)}),as("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=typeof e=="bigint"?Number(e):e,s=this.storageCache.get(t);if(!s){if(this.storageCache.size===0)return 0;throw new Error("releasing data does not exist")}return as("verbose",()=>`[WebGPU] GpuDataManager.release(id=${t}), gpuDataId=${s.gpuData.id}`),this.storageCache.delete(t),this.buffersPending.push(s.gpuData.buffer),s.originalSize}async download(e,t){let s=this.storageCache.get(Number(e));if(!s)throw new Error("data does not exist");await xt(this.backend,s.gpuData.buffer,s.originalSize,t)}refreshPendingBuffers(){if(this.buffersPending.length!==0)if(this.backend.sessionStatus==="default"){for(let e of this.buffersPending){let t=be.get(e.size);if((e.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE){let s=this.freeBuffers.get(e.size)||[];t===void 0||s.length>=t?e.destroy():s.push(e)}else if((e.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM){let s=this.freeUniformBuffers.get(e.size)||[];t===void 0||s.length>=t?e.destroy():s.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}onCreateSession(){this.sessionCount+=1}onReleaseSession(e){let t=this.capturedPendingBuffers.get(e);t&&(t.forEach(s=>{s.destroy()}),this.capturedPendingBuffers.delete(e)),this.sessionCount-=1,this.sessionCount===0&&(as("warning",()=>"[WebGPU] Clearing webgpu buffer cache"),this.storageCache.forEach(s=>{s.gpuData.buffer.destroy()}),this.storageCache=new Map)}},ms=(...e)=>new Kt(...e)}),Fs,Bt,rs=g(()=>{Fs=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}},Bt=e=>new Fs(e)}),rr,Ws,ze,Js,Fr,ks,Xs,Ot=g(()=>{rr=class{static calcMatMulShape(e,t){return e[1]!==t[0]?void 0:[e[0],t[1]]}},Ws=class{static calcShape(e,t,s=!1){let n=e.length,o=t.length;if(n===0)return t;if(o===0)return e;let a=Math.max(e.length,t.length),i=new Array(a);if(s){if(n<2||o<2)return;let u=rr.calcMatMulShape([e[n-2],e[n-1]],[t[o-2],t[o-1]]);if(u===void 0)return;[i[a-2],i[a-1]]=u}for(let u=s?3:1;u<=a;u++){let p=n-u<0?1:e[n-u],h=o-u<0?1:t[o-u];if(p!==h&&p>1&&h>1)return;let k=Math.max(p,h);if(p&&h)i[a-u]=Math.max(p,h);else{if(k>1)return;i[a-u]=0}}return i}static isValidBroadcast(e,t){let s=e.length,n=t.length;if(s>n)return!1;for(let o=1;o<=s;o++)if(e[s-o]!==1&&e[s-o]!==t[n-o])return!1;return!0}},ze=class Wp{static size(t){return Wp.getSizeFromDimensionRange(t,0,t.length)}static convertShape(t,s=4){let n=t.length;if(n===0)return[];let o=new Array(n),a=n-1;for(;a>=0;){if(t[a]%s===0){o[a]=t[a]/s;break}if(s%t[a]!==0)throw new Error("cannot convert shape");o[a]=1,s/=t[a],a--}for(a--;a>=0;a--)o[a]=t[a];return o}static sizeFromDimension(t,s){if(s<0||s>t.length)throw new Error(`invalid dimension of ${s} for sizeFromDimension as Tensor has ${t.length} dimensions.`);return Wp.getSizeFromDimensionRange(t,s,t.length)}static sizeToDimension(t,s){if(s<0||s>t.length)throw new Error(`invalid dimension of ${s} for sizeToDimension as Tensor has ${t.length} dimensions.`);return Wp.getSizeFromDimensionRange(t,0,s)}static getSizeFromDimensionRange(t,s,n){let o=1;for(let a=s;a=0;--o)n[o]=n[o+1]*t[o+1];return n}static normalizeAxis(t,s){if(t<-s&&t>=s)throw new Error("unsupported axis for this operation.");return t<0?t+s:t}static normalizeAxes(t,s){return t.map(n=>this.normalizeAxis(n,s??t.length))}static sortBasedOnPerm(t,s){return s?s.map(n=>t[n]):t.slice().reverse()}static padShape(t,s){let n=t.length;return t.map((o,a)=>o+s[a]+s[a+n])}static areEqual(t,s){return t.length!==s.length?!1:t.every((n,o)=>n===s[o])}},Js=class zc{static adjustPoolAttributes(t,s,n,o,a,i){if(!t&&n.length!==s.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(s[u+2]):n[u]=s[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,s,n,o,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(s.length!==t.length-2)throw new Error("length of strides should be the length of data dimensions");if(o.length!==t.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let p=0;p{zt(),Ot(),or=64,fr=(e,t)=>{if(t===3)throw new Error("vec3 has same alignment as vec4, use vec4 instead");switch(Number(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}`)}},_s=(e,t=1)=>{let s=fr(e,t);return typeof s=="string"?s:s[0]},Ss=(e,t=1)=>{let s=fr(e,t);return typeof s=="string"?s:s[1]},yt=(...e)=>{let t=[];return e.forEach(s=>{s.length!==0&&t.push({type:12,data:s},{type:12,data:ze.computeStrides(s)})}),t},qt=e=>e%4===0?4:e%2===0?2:1,Ls=(e="f32",t,s="0")=>!t||t===1?`${e}(${s})`:`vec${t}<${e}>(${s})`,$s=(e,t,s)=>e==="f32"?s:t===1?`f32(${s})`:`vec${t}(${s})`,Gs=(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,$t=(e,t,s,n)=>e.startsWith("uniforms.")&&s>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}]`:s>1?`${e}[${t}]`:e,sn=(e,t,s,n,o)=>{let a=typeof s=="number",i=a?s:s.length,u=[...new Array(i).keys()],p=i<2?"u32":i<=4?`vec${i}`:`array`,h=fr(t,o),k=typeof h=="string"?h:h[1],C=typeof h=="string"?h:h[0],d={indices:p,value:k,storage:C,tensor:t},z=it=>typeof it=="string"?it:`${it}u`,B={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},V=a?"uniforms.":"",Z=`${V}${e}_shape`,ee=`${V}${e}_strides`,X="";for(let it=0;it ${d.indices} { - var indices: ${d.indices}; - var current = offset; - ${X} - return indices; - }`,pe=it=>(B.offsetToIndices=!0,i<2?it:`o2i_${e}(${it})`),Me=[];if(i>=2)for(let it=i-1;it>=0;it--)Me.push(`${$t(ee,it,i)} * (indices[${it}])`);let Oe=i<2?"":` - fn i2o_${e}(indices: ${d.indices}) -> u32 { - return ${Me.join("+")}; - }`,Le=it=>(B.indicesToOffset=!0,i<2?it:`i2o_${e}(${it})`),Ye=(...it)=>i===0?"0u":`${d.indices}(${it.map(z).join(",")})`,at=(it,Et)=>i<2?`${it}`:`${$t(it,Et,i)}`,Pt=(it,Et,ps)=>i<2?`${it}=${ps};`:`${$t(it,Et,i)}=${ps};`,Xt={},Zt=(it,Et)=>{B.broadcastedIndicesToOffset=!0;let ps=`${Et.name}broadcastedIndicesTo${e}Offset`;if(ps in Xt)return`${ps}(${it})`;let Ns=[];for(let Tr=i-1;Tr>=0;Tr--){let er=Et.indicesGet("outputIndices",Tr+Et.rank-i);Ns.push(`${at(ee,Tr)} * (${er} % ${at(Z,Tr)})`)}return Xt[ps]=`fn ${ps}(outputIndices: ${Et.type.indices}) -> u32 { - return ${Ns.length>0?Ns.join("+"):"0u"}; - }`,`${ps}(${it})`},bt=(it,Et)=>(()=>{if(d.storage===d.value)return`${e}[${it}]=${Et};`;if(d.storage==="vec2"&&d.value==="i32")return`${e}[${it}]=vec2(u32(${Et}), select(0u, 0xFFFFFFFFu, ${Et} < 0));`;if(d.storage==="vec2"&&d.value==="u32")return`${e}[${it}]=vec2(u32(${Et}), 0u);`;if(d.storage==="u32"&&d.value==="vec4")return`${e}[${it}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${Et}));`;throw new Error(`not supported combination of storage type ${d.storage} and value type ${d.value} yet`)})(),ss=it=>(()=>{if(d.storage===d.value)return`${e}[${it}]`;if(d.storage==="vec2"&&d.value==="i32")return`i32(${e}[${it}].x)`;if(d.storage==="vec2"&&d.value==="u32")return`u32(${e}[${it}].x)`;if(d.storage==="u32"&&d.value==="vec4")return`vec4(bool(${e}[${it}] & 0xFFu), bool(${e}[${it}] & 0xFF00u), bool(${e}[${it}] & 0xFF0000u), bool(${e}[${it}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${d.storage} and value type ${d.value} yet`)})(),St=i<2?"":` - fn get_${e}ByIndices(indices: ${d.indices}) -> ${k} { - return ${ss(`i2o_${e}(indices)`)}; - }`,Ft=i<2?"":(()=>{let it=u.map(ps=>`d${ps}: u32`).join(", "),Et=u.map(ps=>`d${ps}`).join(", ");return` - fn get_${e}(${it}) -> ${k} { - return get_${e}ByIndices(${Ye(Et)}); - }`})(),bs=(...it)=>{if(it.length!==i)throw new Error(`indices length must be ${i}`);let Et=it.map(z).join(",");return i===0?ss("0u"):i===1?ss(Et[0]):(B.get=!0,B.getByIndices=!0,B.indicesToOffset=!0,`get_${e}(${Et})`)},Ht=it=>i<2?ss(it):(B.getByIndices=!0,B.indicesToOffset=!0,`get_${e}ByIndices(${it})`),Rt=i<2?"":` - fn set_${e}ByIndices(indices: ${d.indices}, value: ${k}) { - ${bt(`i2o_${e}(indices)`,"value")} - }`,fs=i<2?"":(()=>{let it=u.map(ps=>`d${ps}: u32`).join(", "),Et=u.map(ps=>`d${ps}`).join(", ");return` - fn set_${e}(${it}, value: ${k}) { - set_${e}ByIndices(${Ye(Et)}, value); - }`})();return{impl:()=>{let it=[],Et=!1;return B.offsetToIndices&&(it.push(he),Et=!0),B.indicesToOffset&&(it.push(Oe),Et=!0),B.broadcastedIndicesToOffset&&(Object.values(Xt).forEach(ps=>it.push(ps)),Et=!0),B.set&&(it.push(fs),Et=!0),B.setByIndices&&(it.push(Rt),Et=!0),B.get&&(it.push(Ft),Et=!0),B.getByIndices&&(it.push(St),Et=!0),!a&&Et&&it.unshift(`const ${Z} = ${d.indices}(${s.join(",")});`,`const ${ee} = ${d.indices}(${ze.computeStrides(s).join(",")});`),it.join(` -`)},type:d,offsetToIndices:pe,indicesToOffset:Le,broadcastedIndicesToOffset:Zt,indices:Ye,indicesGet:at,indicesSet:Pt,set:(...it)=>{if(it.length!==i+1)throw new Error(`indices length must be ${i}`);let Et=it[i];if(typeof Et!="string")throw new Error("value must be string");let ps=it.slice(0,i).map(z).join(",");return i===0?bt("0u",Et):i===1?bt(ps[0],Et):(B.set=!0,B.setByIndices=!0,B.indicesToOffset=!0,`set_${e}(${ps}, ${Et})`)},setByOffset:bt,setByIndices:(it,Et)=>i<2?bt(it,Et):(B.setByIndices=!0,B.indicesToOffset=!0,`set_${e}ByIndices(${it}, ${Et});`),get:bs,getByOffset:ss,getByIndices:Ht,usage:n,name:e,strides:ee,shape:Z,rank:i}},qe=(e,t,s,n=1)=>sn(e,t,s,"input",n),It=(e,t,s,n=1)=>sn(e,t,s,"output",n),La=(e,t,s)=>sn(e,t,s,"atomicOutput",1),Uo=(e,t,s,n=1)=>sn(e,t,s,"internal",n),za=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=or){let t=typeof e=="number"?e:e[0],s=typeof e=="number"?1:e[1],n=typeof e=="number"?1:e[2];if(t>this.limits.maxComputeWorkgroupSizeX||s>this.limits.maxComputeWorkgroupSizeY||n>this.limits.maxComputeWorkgroupSizeZ)throw new Error(`workgroup size [${t}, ${s}, ${n}] exceeds the maximum workgroup size [${this.limits.maxComputeWorkgroupSizeX}, ${this.limits.maxComputeWorkgroupSizeY}, ${this.limits.maxComputeWorkgroupSizeZ}].`);if(t*s*n>this.limits.maxComputeInvocationsPerWorkgroup)throw new Error(`workgroup size [${t}, ${s}, ${n}] exceeds the maximum workgroup invocations ${this.limits.maxComputeInvocationsPerWorkgroup}.`);let o=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1,a=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 * ${t*s*n}u + local_idx;`;return`@compute @workgroup_size(${t}, ${s}, ${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 s=e.usage==="input"?"read":"read_write",n=e.usage==="atomicOutput"?"atomic":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,s=1){return this.uniforms.push({name:e,type:t,length:s}),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:s,length:n}of this.uniforms)if(n&&n>4)s==="f16"?e.push(`@align(16) ${t}:array, ${Math.ceil(n/8)}>`):e.push(`${t}:array, ${Math.ceil(n/4)}>`);else{let o=n==null||n===1?s:`vec${n}<${s}>`;e.push(`${t}:${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=t=>[12,10,1,6][["u32","f16","f32","i32"].indexOf(t)];return this.uniforms.map(t=>[e(t.type),t.length??1])}},Ba=(e,t)=>new za(e,t)}),Ra,Vo,Wo,Na,ja,Go,pr,Ua,Ko,Kr=g(()=>{zt(),Ot(),rs(),Yt(),Ra=(e,t)=>{if(!e||e.length!==1)throw new Error("Transpose requires 1 input.");if(t.length!==0&&t.length!==e[0].dims.length)throw new Error(`perm size ${t.length} does not match input rank ${e[0].dims.length}`)},Vo=(e,t)=>t.length!==0?t:[...new Array(e).keys()].reverse(),Wo=(e,t)=>ze.sortBasedOnPerm(e,Vo(e.length,t)),Na=(e,t,s,n)=>{let o=`fn perm(i: ${n.type.indices}) -> ${s.type.indices} { - var a: ${s.type.indices};`;for(let a=0;a{let s=[],n=[];for(let o=0;o{let s=0;for(let n=0;n{let s=e.dataType,n=e.dims.length,o=Vo(n,t),a=Wo(e.dims,o),i=e.dims,u=a,p=n<2||Go(o,e.dims),h;if(p)return h=B=>{let V=qe("input",s,i,4),Z=It("output",s,u,4);return` - ${B.registerUniform("output_size","u32").declareVariables(V,Z)} - ${B.mainStart()} - ${B.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - output[global_idx] = input[global_idx]; - }`},{name:"TransposeCopy",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let B=ze.size(a);return{outputs:[{dims:a,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(B/64/4)},programUniforms:[{type:12,data:Math.ceil(B/4)}]}},getShaderSource:h};let{newShape:k,newPerm:C}=ja(e.dims,o),d=ze.areEqual(C,[2,3,1]),z=ze.areEqual(C,[3,1,2]);if(k.length===2||d||z){i=d?[k[0],k[1]*k[2]]:z?[k[0]*k[1],k[2]]:k,u=[i[1],i[0]];let B=16;return h=V=>{let Z=qe("a",s,i.length),ee=It("output",s,u.length);return` - ${V.registerUniform("output_size","u32").declareVariables(Z,ee)} - var tile : array, ${B}>; - ${V.mainStart([B,B,1])} - let stride = (uniforms.output_shape[1] - 1) / ${B} + 1; - let workgroup_id_x = workgroup_index % stride; - let workgroup_id_y = workgroup_index / stride; - let input_col = workgroup_id_y * ${B}u + local_id.x; - let input_row = workgroup_id_x * ${B}u + local_id.y; - if (input_row < uniforms.a_shape[0] && input_col < uniforms.a_shape[1]) { - tile[local_id.y][local_id.x] = ${Z.getByIndices(`${Z.type.indices}(input_row, input_col)`)}; - } - workgroupBarrier(); - - let output_col = workgroup_id_x * ${B}u + local_id.x; - let output_row = workgroup_id_y * ${B}u + local_id.y; - if (output_row < uniforms.output_shape[0] && output_col < uniforms.output_shape[1]) { - ${ee.setByIndices(`${ee.type.indices}(output_row, output_col)`,"tile[local_id.x][local_id.y]")} - } - }`},{name:"TransposeShared",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let V=ze.size(a);return{outputs:[{dims:a,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(u[1]/B),y:Math.ceil(u[0]/B)},programUniforms:[{type:12,data:V},...yt(i,u)]}},getShaderSource:h}}return h=B=>{let V=qe("a",s,i.length),Z=It("output",s,u.length);return` - ${B.registerUniform("output_size","u32").declareVariables(V,Z)} - - ${Na(o,n,V,Z)} - - ${B.mainStart()} - ${B.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - - let indices = ${Z.offsetToIndices("global_idx")}; - let aIndices = perm(indices); - - ${Z.setByOffset("global_idx",V.getByIndices("aIndices"))} - }`},{name:"Transpose",shaderCache:{hint:`${t}`,inputDependencies:["rank"]},getRunData:()=>{let B=ze.size(a);return{outputs:[{dims:a,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(B/64)},programUniforms:[{type:12,data:B},...yt(i,u)]}},getShaderSource:h}},Ua=(e,t)=>{Ra(e.inputs,t.perm),e.compute(pr(e.inputs[0],t.perm))},Ko=e=>Bt({perm:e.perm})}),ao,Va,Wa,Ga,Ka,Ha,qa,Qa,Ho,Xa,hr,rn,Ya,Rc,Ja,Nc,Za,qo,el,tl,sl,jc=g(()=>{zt(),Ot(),Yt(),co(),Kr(),ao={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"},Va={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"},Wa={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},Ga={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},Ka=(e,t)=>{let s=[];for(let n=t-e;n{let s=[],n=e.length;for(let a=0;ae[a]);return[s,o]},qa=(e,t)=>{let s=e.length+t.length,n=[],o=0;for(let a=0;a{for(let s=0;s{let s=[];if(!Qa(e,t)){for(let n=0;ns.push(n))}return s},Xa=(e,t,s,n,o,a,i)=>{let u=s[0].dims,p=ze.size(a),h=ze.size(i),k=qe("_A",s[0].dataType,u),C=It("output",o,a),d=64;p===1&&(d=256);let z=` - var aBestValues : array; - `,B=V=>` - ${V.registerUniform("reduceSize","u32").declareVariables(k,C)} - ${z} - fn DIV_CEIL(a : u32, b : u32) -> u32 { - return ((a - 1u) / b + 1u); - } - ${V.mainStart(d)} - - let outputIndex = global_idx / ${d}; - let offset = outputIndex * uniforms.reduceSize; - - var bestValue = f32(${Wa[n]}); - let Length = uniforms.reduceSize; - for (var k = local_idx; k < Length; k = k + ${d}) { - let candidate = f32(${k.getByOffset("offset + k")}); - bestValue = ${ao[n]}; - } - aBestValues[local_idx] = bestValue; - workgroupBarrier(); - - var reduceSize = min(Length, ${d}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 = ${Va[n]}; - aBestValues[local_idx] = bestValue; - } - reduceSize = interval; - workgroupBarrier(); - } - - if (local_idx == 0u) { - ${C.setByOffset("outputIndex",`${n==="mean"?`${C.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${C.type.storage}(${Ga[n]})`}`)}; - } - }`;return{name:e,shaderCache:{hint:`${t};${d}`,inputDependencies:["type"]},getShaderSource:B,getRunData:()=>({outputs:[{dims:a,dataType:o}],dispatchGroup:{x:p},programUniforms:[{type:12,data:h}]})}},hr=(e,t,s,n)=>{let o=e.inputs.length===1?s:Qo(e.inputs,s),a=o.axes;a.length===0&&!o.noopWithEmptyAxes&&(a=e.inputs[0].dims.map((z,B)=>B));let i=ze.normalizeAxes(a,e.inputs[0].dims.length),u=i,p=e.inputs[0],h=Ho(u,e.inputs[0].dims.length);h.length>0&&(p=e.compute(pr(e.inputs[0],h),{inputs:[0],outputs:[-1]})[0],u=Ka(u.length,p.dims.length));let[k,C]=Ha(p.dims,u),d=k;o.keepDims&&(d=qa(k,i)),e.compute(Xa(t,o.cacheKey,[p],n,e.inputs[0].dataType,d,C),{inputs:[p]})},rn=(e,t)=>{hr(e,"ReduceMeanShared",t,"mean")},Ya=(e,t)=>{hr(e,"ReduceL1Shared",t,"l1")},Rc=(e,t)=>{hr(e,"ReduceL2Shared",t,"l2")},Ja=(e,t)=>{hr(e,"ReduceLogSumExpShared",t,"logSumExp")},Nc=(e,t)=>{hr(e,"ReduceMaxShared",t,"max")},Za=(e,t)=>{hr(e,"ReduceMinShared",t,"min")},qo=(e,t)=>{hr(e,"ReduceProdShared",t,"prod")},el=(e,t)=>{hr(e,"ReduceSumShared",t,"sum")},tl=(e,t)=>{hr(e,"ReduceSumSquareShared",t,"sumSquare")},sl=(e,t)=>{hr(e,"ReduceLogSumShared",t,"logSum")}}),gr,lo,uo,Qo,wr,Xo,rl,nl,Yo,ol,il,Jo,al,ll,Zo,yr,ul,ei,dl,cl,ti,pl,hl,si,ml,_l,co=g(()=>{zt(),Ot(),rs(),Yt(),jc(),gr=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.")},lo=e=>["","",`var value = ${e.getByIndices("input_indices")};`,""],uo=(e,t,s,n,o,a,i=!1,u=!1)=>{let p=[],h=s[0].dims,k=h.length,C=ze.normalizeAxes(o,k),d=!u&&C.length===0;h.forEach((V,Z)=>{d||C.indexOf(Z)>=0?i&&p.push(1):p.push(V)});let z=p.length,B=ze.size(p);return{name:e,shaderCache:t,getShaderSource:V=>{let Z=[],ee=qe("_A",s[0].dataType,k),X=It("output",a,z),he=n(ee,X,C),pe=he[2];for(let Me=0,Oe=0;Me=0?(i&&Oe++,pe=`for(var j${Me}: u32 = 0; j${Me} < ${h[Me]}; j${Me}++) { - ${he[2].includes("last_index")?`let last_index = j${Me};`:""} - ${ee.indicesSet("input_indices",Me,`j${Me}`)} - ${pe} - }`):(Z.push(`${ee.indicesSet("input_indices",Me,X.indicesGet("output_indices",Oe))};`),Oe++);return` - - ${V.registerUniform("output_size","u32").declareVariables(ee,X)} - - ${V.mainStart()} - ${V.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - var input_indices: ${ee.type.indices}; - let output_indices = ${X.offsetToIndices("global_idx")}; - - ${Z.join(` -`)} - ${he[0]} // init ops for reduce max/min - ${he[1]} - ${pe} - ${he[3]} - ${he.length===4?X.setByOffset("global_idx","value"):he.slice(4).join(` -`)} - }`},getRunData:()=>({outputs:[{dims:p,dataType:a}],dispatchGroup:{x:Math.ceil(B/64)},programUniforms:[{type:12,data:B},...yt(h,p)]})}},Qo=(e,t)=>{let s=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach(n=>s.push(Number(n))),Bt({axes:s,keepDims:t.keepDims,noopWithEmptyAxes:t.noopWithEmptyAxes})},wr=(e,t,s,n)=>{let o=e.inputs,a=o.length===1?s:Qo(o,s);e.compute(uo(t,{hint:a.cacheKey,inputDependencies:["rank"]},[o[0]],a.noopWithEmptyAxes&&a.axes.length===0?lo:n,a.axes,o[0].dataType,a.keepDims,a.noopWithEmptyAxes),{inputs:[0]})},Xo=(e,t)=>{gr(e.inputs),wr(e,"ReduceLogSum",t,(s,n)=>[`var value = ${n.type.storage}(0);`,"",`value += ${s.getByIndices("input_indices")};`,"value = log(value);"])},rl=(e,t)=>{gr(e.inputs),wr(e,"ReduceL1",t,(s,n)=>[`var value = ${n.type.storage}(0);`,"",`value += abs(${s.getByIndices("input_indices")});`,""])},nl=(e,t)=>{gr(e.inputs),wr(e,"ReduceL2",t,(s,n)=>[`var t = ${n.type.value}(0); var value = ${n.type.value}(0);`,"",`t = ${s.getByIndices("input_indices")}; value += (t * t);`,"value = sqrt(value);"])},Yo=(e,t)=>{gr(e.inputs),wr(e,"ReduceLogSumExp",t,(s,n)=>[`var value = ${n.type.storage}(0);`,"",`value += exp(${s.getByIndices("input_indices")});`,"value = log(value);"])},ol=(e,t)=>{gr(e.inputs),wr(e,"ReduceMax",t,(s,n,o)=>{let a=[];for(let i=0;i=0||o.length===0)&&a.push(s.indicesSet("input_indices",i,0));return[`${a.join(` -`)}`,`var value = ${s.getByIndices("input_indices")};`,`value = max(value, ${s.getByIndices("input_indices")});`,""]})},il=(e,t)=>{gr(e.inputs),wr(e,"ReduceMean",t,(s,n,o)=>{let a=1;for(let i=0;i=0||o.length===0)&&(a*=e.inputs[0].dims[i]);return["var sum = f32(0);","",`sum += f32(${s.getByIndices("input_indices")});`,`let value = ${n.type.value}(sum / ${a});`]})},Jo=(e,t)=>{gr(e.inputs),wr(e,"ReduceMin",t,(s,n,o)=>{let a=[];for(let i=0;i=0||o.length===0)&&a.push(`input_indices[${i}] = 0;`);return[`${a.join(` -`)}`,`var value = ${s.getByIndices("input_indices")};`,`value = min(value, ${s.getByIndices("input_indices")});`,""]})},al=(e,t)=>{gr(e.inputs),wr(e,"ReduceProd",t,(s,n)=>[`var value = ${n.type.storage}(1);`,"",`value *= ${s.getByIndices("input_indices")};`,""])},ll=(e,t)=>{gr(e.inputs),wr(e,"ReduceSum",t,(s,n)=>[`var value = ${n.type.storage}(0);`,"",`value += ${s.getByIndices("input_indices")};`,""])},Zo=(e,t)=>{gr(e.inputs),wr(e,"ReduceSumSquare",t,(s,n)=>[`var t = ${n.type.value}(0); var value = ${n.type.value}(0);`,"",`t = ${s.getByIndices("input_indices")}; value += t * t;`,""])},yr=(e,t,s)=>{if(t.length===0)return s;let n=1,o=1;for(let a=0;a1024},ul=(e,t)=>{yr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?il(e,t):rn(e,t)},ei=(e,t)=>{yr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?rl(e,t):Ya(e,t)},dl=(e,t)=>{yr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?nl(e,t):Rc(e,t)},cl=(e,t)=>{yr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Yo(e,t):Ja(e,t)},ti=(e,t)=>{yr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?ol(e,t):Nc(e,t)},pl=(e,t)=>{yr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Jo(e,t):Za(e,t)},hl=(e,t)=>{yr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?al(e,t):qo(e,t)},si=(e,t)=>{yr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?ll(e,t):el(e,t)},ml=(e,t)=>{yr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Zo(e,t):tl(e,t)},_l=(e,t)=>{yr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Xo(e,t):sl(e,t)}}),ri,fl,ni,oi,Uc=g(()=>{zt(),rs(),co(),ri=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.")},fl=(e,t)=>{ri(e.inputs);let s=(n,o,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); - }`,"",o.setByOffset("global_idx","best_index")]};e.compute(uo("ArgMin",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],s,[t.axis],7,t.keepDims),{inputs:[0]})},ni=(e,t)=>{ri(e.inputs);let s=(n,o,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); - }`,"",o.setByOffset("global_idx","best_index")]};e.compute(uo("argMax",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],s,[t.axis],7,t.keepDims),{inputs:[0]})},oi=e=>Bt(e)}),ii,po,gl,ai,wl,Nn,li,yl,ui=g(()=>{zt(),Ot(),ue(),Yt(),ii=(e,t)=>{let s=e[0],n=e[1],o=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(s.dims.length!==3)throw new Error('Input "input" must have 3 dimensions');let p=s.dims[0],h=s.dims[1],k=s.dims[2];if(o.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]!==k)throw new Error("Input 1 dimension 0 should have same length as dimension 2 of input 0");if(o.dims[0]!==n.dims[1])throw new Error('Input "bias" dimension 0 should have same length as dimension 1 of input "weights"');let C=o.dims[0]/3,d=C,z=d;if(t.qkvHiddenSizes.length>0){if(t.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let he of t.qkvHiddenSizes)if(he%t.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");C=t.qkvHiddenSizes[0],d=t.qkvHiddenSizes[1],z=t.qkvHiddenSizes[2]}let B=h;if(C!==d)throw new Error("qkv_hidden_sizes first element should be same as the second");if(o.dims[0]!==C+d+z)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let V=0;if(i){if(d!==z)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]!==p)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]!==d/t.numHeads)throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads');t.pastPresentShareBuffer||(V=i.dims[3])}let Z=B+V,ee=-1,X=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]!==p||u.dims[1]!==t.numHeads||u.dims[2]!==h||u.dims[3]!==Z)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:p,sequenceLength:h,pastSequenceLength:V,kvSequenceLength:B,totalSequenceLength:Z,maxSequenceLength:ee,inputHiddenSize:k,hiddenSize:C,vHiddenSize:z,headSize:Math.floor(C/t.numHeads),vHeadSize:Math.floor(z/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:X,scale:t.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},po=(e,t,s)=>t&&e?` - let total_sequence_length_input = u32(${t.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; - } - `:` - ${s?"let past_sequence_length = uniforms.past_sequence_length":""}; - let present_sequence_length = total_sequence_length; - `,gl=(e,t,s,n,o,a,i,u)=>{let p=qt(i?1:a),h=64,k=a/p;k{let X=It("x",e.dataType,e.dims,p),he=[X],pe=i?qe("seq_lens",i.dataType,i.dims):void 0;pe&&he.push(pe);let Me=u?qe("total_sequence_length_input",u.dataType,u.dims):void 0;Me&&he.push(Me);let Oe=Ss(e.dataType),Le=[{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; - ${ee.registerUniforms(Le).declareVariables(...he)} - ${ee.mainStart([h,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; - ${po(pe,Me,!1)} - let local_offset = local_idx * uniforms.elements_per_thread; - let offset = (global_idx / ${h}) * 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 = ${B}(-3.402823e+38f); - for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { - thread_max_vector = max(${B}(x[offset + i]), thread_max_vector); - } - thread_max[local_idx] = ${(()=>{switch(p){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: ${p}`)}})()}; - workgroupBarrier(); - - var max_value = f32(-3.402823e+38f); - for (var i = 0u; i < ${h}; i++) { - max_value = max(thread_max[i], max_value); - } - - var sum_vector = ${B}(0); - for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { - sum_vector += exp(${B}(x[offset + i]) - max_value); - } - thread_sum[local_idx] = ${(()=>{switch(p){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: ${p}`)}})()}; - workgroupBarrier(); - - var sum: f32 = 0; - for (var i = 0u; i < ${h}; 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] = ${X.type.value}(${Oe}(1.0) / ${Oe}(seq_causal_length)); - } - } else { - for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { - var f32input = ${B}(x[offset + i]); - x[offset + i] = ${X.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] = ${X.type.value}(${Oe}(0)); - }`:""}; - }`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${h};${z};${p}`,inputDependencies:V},getShaderSource:Z,getRunData:()=>({outputs:[],dispatchGroup:{x:Math.ceil(a/h),y:o,z:t*s},programUniforms:d})}},ai=(e,t,s,n,o,a,i,u,p)=>{let h=i+a.kvSequenceLength,k=[a.batchSize,a.numHeads,a.sequenceLength,h],C=e>1&&n,d=a.kvNumHeads?a.kvNumHeads:a.numHeads,z=C?[a.batchSize,d,h,a.headSize]:void 0,B=a.nReps?a.nReps:1,V=a.scale===0?1/Math.sqrt(a.headSize):a.scale,Z=qt(a.headSize),ee=a.headSize/Z,X=12,he={x:Math.ceil(h/X),y:Math.ceil(a.sequenceLength/X),z:a.batchSize*a.numHeads},pe=[{type:12,data:a.sequenceLength},{type:12,data:ee},{type:12,data:h},{type:12,data:a.numHeads},{type:12,data:a.headSize},{type:1,data:V},{type:12,data:i},{type:12,data:a.kvSequenceLength},{type:12,data:B}],Me=C&&n&&ze.size(n.dims)>0,Oe=["type","type"];Me&&Oe.push("type"),o&&Oe.push("type"),u&&Oe.push("type"),p&&Oe.push("type");let Le=[{dims:k,dataType:t.dataType,gpuDataType:0}];C&&Le.push({dims:z,dataType:t.dataType,gpuDataType:0});let Ye=at=>{let Pt=qe("q",t.dataType,t.dims,Z),Xt=qe("key",s.dataType,s.dims,Z),Zt=[Pt,Xt];if(Me){let Rt=qe("past_key",n.dataType,n.dims,Z);Zt.push(Rt)}o&&Zt.push(qe("attention_bias",o.dataType,o.dims));let bt=u?qe("seq_lens",u.dataType,u.dims):void 0;bt&&Zt.push(bt);let ss=p?qe("total_sequence_length_input",p.dataType,p.dims):void 0;ss&&Zt.push(ss);let St=It("output",t.dataType,k),Ft=[St];C&&Ft.push(It("present_key",t.dataType,z,Z));let bs=Ss(1,Z),Ht=[{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 = ${X}u; - - var tileQ: array<${Pt.type.storage}, ${X*X}>; - var tileK: array<${Pt.type.storage}, ${X*X}>; - ${at.registerUniforms(Ht).declareVariables(...Zt,...Ft)} - ${at.mainStart([X,X,1])} - // x holds the N and y holds the M - let headIdx = workgroup_id.z % uniforms.num_heads; - let kvHeadIdx = ${B===1?"headIdx":"headIdx / uniforms.n_reps"}; - let kv_num_heads = ${B===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; - ${po(bt,ss,!0)} - let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx; - let qOffset = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K; - ${Me&&C?"let pastKeyOffset = absKvHeadIdx * uniforms.past_sequence_length * uniforms.K;":""}; - let kOffset = absKvHeadIdx * uniforms.kv_sequence_length * uniforms.K; - ${C?"let presentKeyOffset = absKvHeadIdx * uniforms.N * uniforms.K;":""} - var value = ${bs}(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; - ${Me&&C?` - 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]; - }`} - ${C?`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 += ${bs}(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(Z){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: ${Z}`)}})()}; - output[outputIdx] = ${St.type.value} (sum * uniforms.alpha) + ${o?"attention_bias[outputIdx]":"0.0"}; - } - }`};return{name:"AttentionProbs",shaderCache:{hint:`${Z};${o!==void 0};${n!==void 0};${e}`,inputDependencies:Oe},getRunData:()=>({outputs:Le,dispatchGroup:he,programUniforms:pe}),getShaderSource:Ye}},wl=(e,t,s,n,o,a,i=void 0,u=void 0)=>{let p=a+o.kvSequenceLength,h=o.nReps?o.nReps:1,k=o.vHiddenSize*h,C=e>1&&n,d=o.kvNumHeads?o.kvNumHeads:o.numHeads,z=C?[o.batchSize,d,p,o.headSize]:void 0,B=[o.batchSize,o.sequenceLength,k],V=12,Z={x:Math.ceil(o.vHeadSize/V),y:Math.ceil(o.sequenceLength/V),z:o.batchSize*o.numHeads},ee=[{type:12,data:o.sequenceLength},{type:12,data:p},{type:12,data:o.vHeadSize},{type:12,data:o.numHeads},{type:12,data:o.headSize},{type:12,data:k},{type:12,data:a},{type:12,data:o.kvSequenceLength},{type:12,data:h}],X=C&&n&&ze.size(n.dims)>0,he=["type","type"];X&&he.push("type"),i&&he.push("type"),u&&he.push("type");let pe=[{dims:B,dataType:t.dataType,gpuDataType:0}];C&&pe.push({dims:z,dataType:t.dataType,gpuDataType:0});let Me=Oe=>{let Le=qe("probs",t.dataType,t.dims),Ye=qe("v",s.dataType,s.dims),at=[Le,Ye];X&&at.push(qe("past_value",n.dataType,n.dims));let Pt=i?qe("seq_lens",i.dataType,i.dims):void 0;i&&at.push(Pt);let Xt=u?qe("total_sequence_length_input",u.dataType,u.dims):void 0;u&&at.push(Xt);let Zt=[It("output",t.dataType,B)];C&&Zt.push(It("present_value",t.dataType,z));let bt=[{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 = ${V}u; - var tileQ: array<${Le.type.value}, ${V*V}>; - var tileV: array<${Le.type.value}, ${V*V}>; - ${Oe.registerUniforms(bt).declareVariables(...at,...Zt)} - ${Oe.mainStart([V,V,1])} - let headIdx = workgroup_id.z % uniforms.num_heads; - let batchIdx = workgroup_id.z / uniforms.num_heads; - let kvHeadIdx = ${h===1?"headIdx":"headIdx / uniforms.n_reps"}; - let kv_num_heads = ${h===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; - ${po(Pt,Xt,!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 - ${X&&C?"let pastValueOffset = absKvHeadIdx * uniforms.N * uniforms.past_sequence_length + n;":""}; - let vOffset = absKvHeadIdx * uniforms.N * uniforms.kv_sequence_length + n; - ${C?"let presentValueOffset = absKvHeadIdx * uniforms.N * uniforms.K + n;":""} - var value = ${Le.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; - ${X&&C?` - 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]; - }`} - ${C?` - 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:`${n!==void 0};${e}`,inputDependencies:he},getRunData:()=>({outputs:pe,dispatchGroup:Z,programUniforms:ee}),getShaderSource:Me}},Nn=(e,t,s,n,o,a,i,u,p,h,k=void 0,C=void 0)=>{let d=Math.min(e.outputCount,1+(i?1:0)+(u?1:0)),z=d>1?h.pastSequenceLength:0,B=z+h.kvSequenceLength,V=p&&ze.size(p.dims)>0?p:void 0,Z=[t,s];d>1&&i&&ze.size(i.dims)>0&&Z.push(i),V&&Z.push(V),k&&Z.push(k),C&&Z.push(C);let ee=e.compute(ai(d,t,s,i,V,h,z,k,C),{inputs:Z,outputs:d>1?[-1,1]:[-1]})[0];e.compute(gl(ee,h.batchSize,h.numHeads,z,h.sequenceLength,B,k,C),{inputs:k&&C?[ee,k,C]:[ee],outputs:[]});let X=[ee,n];d>1&&u&&ze.size(u.dims)>0&&X.push(u),k&&X.push(k),C&&X.push(C),e.compute(wl(d,ee,n,u,h,z,k,C),{inputs:X,outputs:d>1?[0,2]:[0]})},li=(e,t)=>{let s=[t.batchSize,t.numHeads,t.sequenceLength,t.headSize],n=t.sequenceLength,o=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},p=[e.inputs[0],e.inputs[1],e.inputs[2]],h=[{type:12,data:n},{type:12,data:o},{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}],k=C=>{let d=It("output_q",p[0].dataType,s),z=It("output_k",p[0].dataType,s),B=It("output_v",p[0].dataType,s),V=qe("input",p[0].dataType,p[0].dims),Z=qe("weight",p[1].dataType,p[1].dims),ee=qe("bias",p[2].dataType,p[2].dims),X=V.type.storage,he=[{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<${X}, ${i*i}>; - var tileWeightQ: array<${X}, ${i*i}>; - var tileWeightK: array<${X}, ${i*i}>; - var tileWeightV: array<${X}, ${i*i}>; - ${C.registerUniforms(he).declareVariables(V,Z,ee,d,z,B)} - ${C.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 = ${X}(0); - var valueK = ${X}(0); - var valueV = ${X}(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:s,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:s,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:s,dataType:e.inputs[0].dataType,gpuDataType:0}],dispatchGroup:u,programUniforms:h}),getShaderSource:k},{inputs:p,outputs:[-1,-1,-1]})},yl=(e,t)=>{let s=ii(e.inputs,t),[n,o,a]=li(e,s);return Nn(e,n,o,a,e.inputs[4],void 0,void 0,void 0,e.inputs[5],s)}}),di,Ml,bl,ci,Vc=g(()=>{We(),zt(),Ot(),rs(),Yt(),di=(e,t)=>{if(!e||e.length!==5)throw new Error("BatchNormalization requires 5 inputs");let s=(n,o,a)=>{let i=o.length;if(i!==n.length)throw new Error(`${a}: num dimensions != ${i}`);o.forEach((u,p)=>{if(u!==n[p])throw new Error(`${a}: dim[${p}] 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);s(e[1].dims,n,"Invalid input scale"),s(e[2].dims,n,"Invalid input B"),s(e[3].dims,n,"Invalid input mean"),s(e[4].dims,n,"Invalid input var")}else s(e[1].dims,[1],"Invalid input scale"),s(e[2].dims,[1],"Invalid input B"),s(e[3].dims,[1],"Invalid input mean"),s(e[4].dims,[1],"Invalid input var")},Ml=(e,t)=>{let{epsilon:s,spatial:n,format:o}=t,a=e[0].dims,i=n?qt(a[a.length-1]):1,u=o==="NHWC"&&a.length>1?i:1,p=ze.size(a)/i,h=n,k=h?a.length:a,C=qe("x",e[0].dataType,e[0].dims,i),d=qe("scale",e[1].dataType,e[1].dims,u),z=qe("bias",e[2].dataType,e[2].dims,u),B=qe("inputMean",e[3].dataType,e[3].dims,u),V=qe("inputVar",e[4].dataType,e[4].dims,u),Z=It("y",e[0].dataType,k,i),ee=()=>{let he="";if(n)he=`let cOffset = ${a.length===1?"0u":o==="NHWC"?`outputIndices[${a.length-1}] / ${i}`:"outputIndices[1]"};`;else if(o==="NCHW")he=` - ${Z.indicesSet("outputIndices","0","0")} - let cOffset = ${Z.indicesToOffset("outputIndices")};`;else{he=`var cIndices = ${d.type.indices}(0); - cIndices[0] = outputIndices[${a.length-1}];`;for(let pe=1;pe` - const epsilon = ${s}; - ${he.registerUniform("outputSize","u32").declareVariables(C,d,z,B,V,Z)} - ${he.mainStart()} - ${he.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} - var outputIndices = ${Z.offsetToIndices(`global_idx * ${i}`)}; - ${ee()} - let scale = ${d.getByOffset("cOffset")}; - let bias = ${z.getByOffset("cOffset")}; - let inputMean = ${B.getByOffset("cOffset")}; - let inputVar = ${V.getByOffset("cOffset")}; - let x = ${C.getByOffset("global_idx")}; - let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias; - ${Z.setByOffset("global_idx","value")} - }`;return{name:"BatchNormalization",shaderCache:{hint:`${t.epsilon}_${t.format}_${n}_${i}`,inputDependencies:h?["rank","type","type","type","type"]:void 0},getShaderSource:X,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:h?[{type:12,data:p},...yt(a)]:[{type:12,data:p}]})}},bl=e=>Bt(e),ci=(e,t)=>{let{inputs:s,outputCount:n}=e,o=bl({...t,outputCount:n});if(O.webgpu.validateInputContent&&di(s,o),t.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");e.compute(Ml(s,o))}}),vl,pi,xl,Wc=g(()=>{Ot(),Yt(),vl=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")},pi=e=>{let t=e[0].dims,s=e[0].dims[2],n=ze.size(t)/4,o=e[0].dataType,a=qe("input",o,t,4),i=qe("bias",o,[s],4),u=qe("residual",o,t,4),p=It("output",o,t,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(n/64)}}),getShaderSource:h=>` - const channels = ${s}u / 4; - ${h.declareVariables(a,i,u,p)} - - ${h.mainStart()} - ${h.guardAgainstOutOfBoundsWorkgroupSizes(n)} - let value = ${a.getByOffset("global_idx")} - + ${i.getByOffset("global_idx % channels")} + ${u.getByOffset("global_idx")}; - ${p.setByOffset("global_idx","value")} - }`}},xl=e=>{vl(e.inputs),e.compute(pi(e.inputs))}}),hi,ds,Tl,mi,Pl,El,_i,Cl,kl,fi,Sl,$l,gi,Al,Il,wi,jn,Ol,ho,Fl,yi,Dl,Ll,Mi,zl,Bl,bi,Rl,Nl,vi,jl,Ul,xi,Vl,Wl,mo,Gl,Ti,_o,Kl,Hl,ql,Ql,Pi,Xl,Ei=g(()=>{zt(),Ot(),rs(),Yt(),hi=(e,t,s,n,o,a,i)=>{let u=Math.ceil(t/4),p="";typeof o=="string"?p=`${o}(a)`:p=o("a");let h=qe("inputData",s,[u],4),k=It("outputData",n,[u],4),C=[{name:"vec_size",type:"u32"}];return i&&C.push(...i),` - ${e.registerUniforms(C).declareVariables(h,k)} - - ${a??""} - - ${e.mainStart()} - ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} - - let a = ${h.getByOffset("global_idx")}; - ${k.setByOffset("global_idx",p)} - }`},ds=(e,t,s,n,o,a=e.dataType,i,u)=>{let p=[{type:12,data:Math.ceil(ze.size(e.dims)/4)}];return i&&p.push(...i),{name:t,shaderCache:{hint:o,inputDependencies:["type"]},getShaderSource:h=>hi(h,ze.size(e.dims),e.dataType,a,s,n,u),getRunData:h=>({outputs:[{dims:e.dims,dataType:a}],dispatchGroup:{x:Math.ceil(ze.size(h[0].dims)/64/4)},programUniforms:p})}},Tl=e=>{e.compute(ds(e.inputs[0],"Abs","abs"))},mi=e=>{e.compute(ds(e.inputs[0],"Acos","acos"))},Pl=e=>{e.compute(ds(e.inputs[0],"Acosh","acosh"))},El=e=>{e.compute(ds(e.inputs[0],"Asin","asin"))},_i=e=>{e.compute(ds(e.inputs[0],"Asinh","asinh"))},Cl=e=>{e.compute(ds(e.inputs[0],"Atan","atan"))},kl=e=>{e.compute(ds(e.inputs[0],"Atanh","atanh"))},fi=e=>Bt(e),Sl=(e,t)=>{let s;switch(t.to){case 10:s="vec4";break;case 1:s="vec4";break;case 12:s="vec4";break;case 6:s="vec4";break;case 9:s="vec4";break;default:throw new RangeError(`not supported type (specified in attribute 'to' from 'Cast' operator): ${t.to}`)}e.compute(ds(e.inputs[0],"Cast",s,void 0,t.cacheKey,t.to))},$l=e=>{let t,s,n=e.length>=2&&e[1].data!==0,o=e.length>=3&&e[2].data!==0;switch(e[0].dataType){case 1:t=n?e[1].getFloat32Array()[0]:-34028234663852886e22,s=o?e[2].getFloat32Array()[0]:34028234663852886e22;break;case 10:t=n?e[1].getUint16Array()[0]:64511,s=o?e[2].getUint16Array()[0]:31743;break;default:throw new Error("Unsupport data type")}return Bt({min:t,max:s})},gi=(e,t)=>{let s=t||$l(e.inputs),n=Ss(e.inputs[0].dataType);e.compute(ds(e.inputs[0],"Clip",o=>`clamp(${o}, vec4<${n}>(uniforms.min), vec4<${n}>(uniforms.max))`,void 0,s.cacheKey,void 0,[{type:e.inputs[0].dataType,data:s.min},{type:e.inputs[0].dataType,data:s.max}],[{name:"min",type:n},{name:"max",type:n}]),{inputs:[0]})},Al=e=>{e.compute(ds(e.inputs[0],"Ceil","ceil"))},Il=e=>{e.compute(ds(e.inputs[0],"Cos","cos"))},wi=e=>{e.compute(ds(e.inputs[0],"Cosh","cosh"))},jn=e=>Bt(e),Ol=(e,t)=>{let s=Ss(e.inputs[0].dataType);e.compute(ds(e.inputs[0],"Elu",n=>`elu_vf32(${n})`,` - const elu_alpha_ = ${s}(${t.alpha}); - - fn elu_f32(a: ${s}) -> ${s} { - return select((exp(a) - 1.0) * elu_alpha_, a, a >= 0.0); - } - - fn elu_vf32(v: vec4<${s}>) -> vec4<${s}> { - return vec4(elu_f32(v.x), elu_f32(v.y), elu_f32(v.z), elu_f32(v.w)); - }`,t.cacheKey))},ho=(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)); -}`,Fl=e=>{let t=Ss(e.inputs[0].dataType);e.compute(ds(e.inputs[0],"Erf",s=>`erf_vf32(${s})`,ho(t)))},yi=e=>{e.compute(ds(e.inputs[0],"Exp","exp"))},Dl=e=>{e.compute(ds(e.inputs[0],"Floor","floor"))},Ll=e=>{let t=Ss(e.inputs[0].dataType);e.compute(ds(e.inputs[0],"Gelu",s=>`0.5 * ${s} * (1.0 + erf_vf32(${s} * 0.7071067811865475))`,ho(t)))},Mi=(e,t)=>{let s=Ss(e.inputs[0].dataType);e.compute(ds(e.inputs[0],"LeakyRelu",n=>`select(leaky_relu_alpha_ * ${n}, ${n}, ${n} >= vec4<${s}>(0.0))`,`const leaky_relu_alpha_ = ${s}(${t.alpha});`,t.cacheKey))},zl=e=>{e.compute(ds(e.inputs[0],"Not",t=>`!${t}`))},Bl=e=>{e.compute(ds(e.inputs[0],"Neg",t=>`-${t}`))},bi=e=>{e.compute(ds(e.inputs[0],"Reciprocal",t=>`1.0/${t}`))},Rl=e=>{let t=Ss(e.inputs[0].dataType);e.compute(ds(e.inputs[0],"Relu",s=>`select(vec4<${t}>(0.0), ${s}, ${s} > vec4<${t}>(0.0))`))},Nl=e=>{e.compute(ds(e.inputs[0],"Sigmoid",t=>`(1.0 / (1.0 + exp(-${t})))`))},vi=e=>Bt(e),jl=(e,t)=>{let s=Ss(e.inputs[0].dataType);e.compute(ds(e.inputs[0],"HardSigmoid",n=>`max(vec4<${s}>(0.0), min(vec4<${s}>(1.0), ${t.alpha} * ${n} + vec4<${s}>(${t.beta})))`,void 0,t.cacheKey))},Ul=e=>{e.compute(ds(e.inputs[0],"Sin","sin"))},xi=e=>{e.compute(ds(e.inputs[0],"Sinh","sinh"))},Vl=e=>{e.compute(ds(e.inputs[0],"Sqrt","sqrt"))},Wl=e=>{e.compute(ds(e.inputs[0],"Tan","tan"))},mo=e=>`sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`,Gl=e=>{e.compute(ds(e.inputs[0],"Tanh",mo))},Ti=(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 ${mo("v")}; -} -`,_o=e=>`(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`,Kl=e=>{let t=Ss(e.inputs[0].dataType);e.compute(ds(e.inputs[0],"FastGelu",_o,Ti(t),void 0,e.inputs[0].dataType))},Hl=(e,t)=>{let s=Ss(e.inputs[0].dataType);return e.compute(ds(e.inputs[0],"ThresholdedRelu",n=>`select(vec4<${s}>(0.0), ${n}, ${n} > thresholded_relu_alpha_)`,`const thresholded_relu_alpha_ = vec4<${s}>(${t.alpha});`,t.cacheKey)),0},ql=e=>{e.compute(ds(e.inputs[0],"Log","log"))},Ql=(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; -} -`,Pi=e=>`quick_gelu_impl(${e})`,Xl=(e,t)=>{let s=Ss(e.inputs[0].dataType);e.compute(ds(e.inputs[0],"QuickGelu",Pi,Ql(s,t.alpha),t.cacheKey,e.inputs[0].dataType))}}),Yl,Jl,Ci,Gc=g(()=>{Ot(),Yt(),Ei(),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")},Jl=e=>{let t=e[0].dims.slice();t[2]=t[2]/2;let s=qe("input",e[0].dataType,e[0].dims,4),n=qe("bias",e[0].dataType,[e[0].dims[2]],4),o=It("output",e[0].dataType,t,4),a=ze.size(t)/4,i=_s(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(s,n,o)} - - ${ho(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); - - ${o.setByOffset("global_idx","valueLeft * geluRight")} - }`}},Ci=e=>{Yl(e.inputs),e.compute(Jl(e.inputs))}}),Zl,eu,Mr,ki,tu,su,ru,nu,Si,ou,iu,$i,au,Kc=g(()=>{zt(),Ot(),Yt(),Zl=(e,t,s,n,o,a,i,u,p,h,k,C)=>{let d,z;typeof u=="string"?d=z=(X,he)=>`${u}((${X}),(${he}))`:typeof u=="function"?d=z=u:(d=u.scalar,z=u.vector);let B=It("outputData",k,n.length,4),V=qe("aData",p,t.length,4),Z=qe("bData",h,s.length,4),ee;if(o)if(a){let X=ze.size(t)===1,he=ze.size(s)===1,pe=t.length>0&&t[t.length-1]%4===0,Me=s.length>0&&s[s.length-1]%4===0;X||he?ee=B.setByOffset("global_idx",z(X?`${V.type.value}(${V.getByOffset("0")}.x)`:V.getByOffset("global_idx"),he?`${Z.type.value}(${Z.getByOffset("0")}.x)`:Z.getByOffset("global_idx"))):ee=` - let outputIndices = ${B.offsetToIndices("global_idx * 4u")}; - let offsetA = ${V.broadcastedIndicesToOffset("outputIndices",B)}; - let offsetB = ${Z.broadcastedIndicesToOffset("outputIndices",B)}; - ${B.setByOffset("global_idx",z(i||pe?V.getByOffset("offsetA / 4u"):`${V.type.value}(${V.getByOffset("offsetA / 4u")}[offsetA % 4u])`,i||Me?Z.getByOffset("offsetB / 4u"):`${Z.type.value}(${Z.getByOffset("offsetB / 4u")}[offsetB % 4u])`))} - `}else ee=B.setByOffset("global_idx",z(V.getByOffset("global_idx"),Z.getByOffset("global_idx")));else{if(!a)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let X=(he,pe,Me="")=>{let Oe=`aData[indexA${pe}][componentA${pe}]`,Le=`bData[indexB${pe}][componentB${pe}]`;return` - let outputIndices${pe} = ${B.offsetToIndices(`global_idx * 4u + ${pe}u`)}; - let offsetA${pe} = ${V.broadcastedIndicesToOffset(`outputIndices${pe}`,B)}; - let offsetB${pe} = ${Z.broadcastedIndicesToOffset(`outputIndices${pe}`,B)}; - let indexA${pe} = offsetA${pe} / 4u; - let indexB${pe} = offsetB${pe} / 4u; - let componentA${pe} = offsetA${pe} % 4u; - let componentB${pe} = offsetB${pe} % 4u; - ${he}[${pe}] = ${Me}(${d(Oe,Le)}); - `};k===9?ee=` - var data = vec4(0); - ${X("data",0,"u32")} - ${X("data",1,"u32")} - ${X("data",2,"u32")} - ${X("data",3,"u32")} - outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:ee=` - ${X("outputData[global_idx]",0)} - ${X("outputData[global_idx]",1)} - ${X("outputData[global_idx]",2)} - ${X("outputData[global_idx]",3)} - `}return` - ${e.registerUniform("vec_size","u32").declareVariables(V,Z,B)} - - ${C??""} - - ${e.mainStart()} - ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} - ${ee} - }`},eu=(e,t,s,n,o,a,i=s.dataType)=>{let u=s.dims.map(V=>Number(V)??1),p=n.dims.map(V=>Number(V)??1),h=!ze.areEqual(u,p),k=u,C=ze.size(u),d=!1,z=!1,B=[h];if(h){let V=Ws.calcShape(u,p,!1);if(!V)throw new Error("Can't perform binary op on the given tensors");k=V.slice(),C=ze.size(k);let Z=ze.size(u)===1,ee=ze.size(p)===1,X=u.length>0&&u[u.length-1]%4===0,he=p.length>0&&p[p.length-1]%4===0;B.push(Z),B.push(ee),B.push(X),B.push(he);let pe=1;for(let Me=1;MeV.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:V=>Zl(V,u,p,k,d,h,z,o,s.dataType,n.dataType,i,a),getRunData:()=>({outputs:[{dims:k,dataType:i}],dispatchGroup:{x:Math.ceil(C/64/4)},programUniforms:[{type:12,data:Math.ceil(ze.size(k)/4)},...yt(u,p,k)]})}},Mr=(e,t,s,n,o,a)=>{e.compute(eu(t,o??"",e.inputs[0],e.inputs[1],s,n,a))},ki=e=>{Mr(e,"Add",(t,s)=>`${t}+${s}`)},tu=e=>{Mr(e,"Div",(t,s)=>`${t}/${s}`)},su=e=>{Mr(e,"Equal",{scalar:(t,s)=>`u32(${t}==${s})`,vector:(t,s)=>`vec4(${t}==${s})`},void 0,void 0,9)},ru=e=>{Mr(e,"Mul",(t,s)=>`${t}*${s}`)},nu=e=>{let t=qe("input",e.inputs[0].dataType,e.inputs[0].dims).type.value;Mr(e,"Pow",{scalar:(s,n)=>`pow_custom(${s},${n})`,vector:(s,n)=>`pow_vector_custom(${s},${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)); - } - `)},Si=e=>{Mr(e,"Sub",(t,s)=>`${t}-${s}`)},ou=e=>{Mr(e,"Greater",{scalar:(t,s)=>`u32(${t}>${s})`,vector:(t,s)=>`vec4(${t}>${s})`},void 0,void 0,9)},iu=e=>{Mr(e,"Less",{scalar:(t,s)=>`u32(${t}<${s})`,vector:(t,s)=>`vec4(${t}<${s})`},void 0,void 0,9)},$i=e=>{Mr(e,"GreaterOrEqual",{scalar:(t,s)=>`u32(${t}>=${s})`,vector:(t,s)=>`vec4(${t}>=${s})`},void 0,void 0,9)},au=e=>{Mr(e,"LessOrEqual",{scalar:(t,s)=>`u32(${t}<=${s})`,vector:(t,s)=>`vec4(${t}<=${s})`},void 0,void 0,9)}}),Ai,lu,uu,Ii,du,cu,pu=g(()=>{zt(),Ot(),rs(),Yt(),Ai=(e,t)=>{if(!e||e.length<1)throw new Error("too few inputs");let s=0,n=e[s],o=n.dataType,a=n.dims.length;e.forEach((i,u)=>{if(u!==s){if(i.dataType!==o)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((p,h)=>{if(h!==t&&p!==n.dims[h])throw new Error("non concat dimensions must match")})}})},lu=(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; - }`,uu=(e,t)=>{let s=e.length,n=[];for(let o=0;o{let o=ze.size(s),a=new Array(e.length),i=new Array(e.length),u=0,p=[],h=[],k=[{type:12,data:o}];for(let V=0;V`uniforms.sizeInConcatAxis${V}`).join(","),B=V=>` - - ${(()=>{V.registerUniform("outputSize","u32");for(let Z=0;Z(${z}); - ${d} -= sizeInConcatAxis[inputIndex - 1u]; - } - - ${uu(i,C)} - }`;return{name:"Concat",shaderCache:{hint:`${t}`,inputDependencies:p},getRunData:()=>({outputs:[{dims:s,dataType:n}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:k}),getShaderSource:B}},du=(e,t)=>{let s=e.inputs,n=s[0].dims,o=ze.normalizeAxis(t.axis,n.length);Ai(s,o);let a=n.slice();a[o]=s.reduce((u,p)=>u+(p.dims.length>o?p.dims[o]:0),0);let i=s.filter(u=>ze.size(u.dims)>0);e.compute(Ii(i,o,a,s[0].dataType),{inputs:i})},cu=e=>Bt({axis:e.axis})}),nn,on,Dr,Oi,an=g(()=>{zt(),Ot(),nn=(e,t,s="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}(${s}(uniforms.clip_min)), ${t}(${s}(uniforms.clip_max)));`;case"HardSigmoid":return`value = max(${t}(0.0), min(${t}(1.0), ${s}(uniforms.alpha) * value + ${s}(uniforms.beta)));`;case"LeakyRelu":return`value = select(${s}(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}`)}},on=(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})},Dr=(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"})},Oi=e=>{let t=(e==null?void 0:e.activation)||"";if(t==="HardSigmoid"){let[s,n]=(e==null?void 0:e.activation_params)||[.2,.5];return{activation:t,alpha:s,beta:n}}else if(t==="Clip"){let[s,n]=(e==null?void 0:e.activation_params)||[ks,Xs];return{activation:t,clipMax:n,clipMin:s}}else if(t==="LeakyRelu"){let[s]=(e==null?void 0:e.activation_params)||[.01];return{activation:t,alpha:s}}return{activation:t}}}),Ks,Fi,Di=g(()=>{Ks=(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.`)}},Fi=e=>` - ${e?"value = value + getBiasByOutputCoords(coords);":""} - `}),Li,Hc=g(()=>{Li=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)); -} -`}),Un,zi,fo=g(()=>{zt(),Ot(),Yt(),an(),Un=(e,t,s,n,o)=>{let a=n-s;return` - ${Array.from({length:s}).map((i,u)=>` - if (${$t(t.shape,u,t.rank)} != 1) { - ${t.indicesSet(e,u,$t(o,u+a,n))} - } else { - ${t.indicesSet(e,u,0)} - }`).join("")} -`},zi=(e,t,s,n,o=!1,a)=>{let i=e[0].dims,u=e[1].dims,p=i[i.length-2],h=u[u.length-1],k=i[i.length-1],C=qt(h),d=qt(k),z=qt(p),B=ze.size(s)/C/z,V=e.length>2,Z=n?n.slice(0,-2):s.slice(0,-2),ee=[ze.size(Z),p,h],X=[{type:12,data:B},{type:12,data:p},{type:12,data:h},{type:12,data:k}];on(t,X),X.push(...yt(Z,i,u)),V&&X.push(...yt(e[2].dims)),X.push(...yt(ee));let he=pe=>{let Me=Uo("batch_dims",e[0].dataType,Z.length),Oe=qe("a",e[0].dataType,i.length,d),Le=qe("b",e[1].dataType,u.length,C),Ye=It("output",e[0].dataType,ee.length,C),at=_s(Ye.type.tensor),Pt=nn(t,Ye.type.value,at),Xt=[Oe,Le],Zt="";if(V){let St=o?C:1;Xt.push(qe("bias",e[2].dataType,e[2].dims.length,St)),Zt=`${o?`value += bias[col / ${St}];`:`value += ${Ye.type.value}(bias[row + i]);`}`}let bt=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];Dr(t,bt);let ss=()=>{let St=`var a_data: ${Oe.type.value};`;for(let Ft=0;Ft; - for (var k: u32 = 0u; k < uniforms.K; k = k + ${d}) { - ${ss()} - } - for (var i = 0u; i < ${z}u; i++) { - var value = values[i]; - ${Zt} - ${Pt} - let cur_indices = ${Ye.type.indices}(batch, row + i, col); - let offset = ${Ye.indicesToOffset("cur_indices")}; - ${Ye.setByOffset(`offset / ${C}`,"value")}; - } - } - `};return{name:"MatMulNaive",shaderCache:{hint:`${t.activation};${C};${d};${z};${o}`,inputDependencies:V?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:a?a(s):s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(B/64)},programUniforms:X}),getShaderSource:he}}}),hu,mu,Bi,go,_u,Ri,Ni,wo,ji=g(()=>{zt(),Ot(),Yt(),an(),fo(),Di(),hu=(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":""}); - `,mu=(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];"} - }`,Bi=(e,t,s="f32",n,o=!1,a=32,i=!1,u=32)=>{let p=t[1]*e[1],h=t[0]*e[0],k=o?p:a,C=o?a:p,d=k/t[0],z=a/t[1];if(!((o&&d===4&&e[1]===4||!o&&(d===3||d===4))&&k%t[0]===0&&a%t[1]===0&&e[0]===4))throw new Error(`If transposeA ${o} is true, innerElementSize ${d} and workPerThread[1] ${e[1]} must be 4. - Otherwise, innerElementSize ${d} must be 3 or 4. - tileAWidth ${k} 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, ${k/d}>, ${C}>; -var mm_Bsub: array, ${h/e[0]}>, ${a}>; - -const rowPerThread = ${e[1]}; -const colPerThread = ${e[0]}; -const innerElementSize = ${d}; -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) * ${p}; - - 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 * ${z}; - 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; - ${hu(o,n)} - } - - // Load one tile of B into local memory. - for (var innerRow = 0; innerRow < ${z}; 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]; - ${d===3?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"} - - ${mu(o,d)} - } - - workgroupBarrier(); - } - - for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { - mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]); - } -}`},go=(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":""}); - `,_u=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",Ri=(e,t,s="f32",n,o=!1,a=32,i=!1,u=32,p=!1)=>{let h=e[1]*t[1],k=e[0]*t[0],C=o?h:a,d=o?a:h;if(!(d%t[1]===0&&C%t[0]===0&&a%t[1]===0))throw new Error(`tileAHight ${d} must be divisible by workgroupSize[1]${t[1]}, tileAWidth ${C} must be divisible by workgroupSize[0]${t[0]}, tileInner ${a} must be divisible by workgroupSize[1]${t[1]}`);let z=d/t[1],B=C/t[0],V=a/t[1],Z=p?` - let localRow = i32(localId.y); - let localCol = i32(localId.x); - let globalRowStart = i32(workgroupId.y) * ${h}; - let globalColStart = i32(workgroupId.x) * ${k}; - - // 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 < ${d}; inputRow = inputRow + ${t[1]}) { - for (var inputCol = localCol; inputCol < ${C}; inputCol = inputCol + ${t[0]}) { - ${go(o,n)} - } - } - // Load one tile of B into local memory. - for (var inputRow = localRow; inputRow < ${a}; inputRow = inputRow + ${t[1]}) { - for (var inputCol = localCol; inputCol < ${k}; 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<${s}, 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 = ${o?`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) * ${h}; - -let tileRowA = i32(localId.y) * ${z}; -let tileColA = i32(localId.x) * ${B}; -let tileRowB = i32(localId.y) * ${V}; -// 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 < ${z}; innerRow = innerRow + 1) { - for (var innerCol = 0; innerCol < ${B}; innerCol = innerCol + 1) { - let inputRow = tileRowA + innerRow; - let inputCol = tileColA + innerCol; - ${go(o,n)} - } - } - - // Load one tile of B into local memory. - for (var innerRow = 0; innerRow < ${V}; 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<${s}, 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) { - ${_u(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, ${d}>; - 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>; - ${Z} - } -`},Ni=(e,t,s,n,o=!1)=>{let[a,i,u,p]=n,h=_s(n[0].type.tensor);return` - fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${a.type.indices}) -> ${Ks(e,h)} { - var value = ${Ks(e,h)}(0.0); - let col = colIn * ${e}; - if(row < uniforms.dim_a_outer && col < uniforms.dim_inner) - { - var aIndices: ${i.type.indices}; - ${Un("aIndices",i,i.rank-2,a.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: ${a.type.indices}) -> ${Ks(e,h)} { - var value = ${Ks(e,h)}(0.0); - let col = colIn * ${e}; - if(row < uniforms.dim_inner && col < uniforms.dim_b_outer) - { - var bIndices: ${u.type.indices}; - ${Un("bIndices",u,u.rank-2,a.rank,"batchIndices")} - ${u.indicesSet("bIndices",u.rank-2,"u32(row)")} - ${u.indicesSet("bIndices",u.rank-1,"u32(colIn)")} - value = ${u.getByIndices("bIndices")}; - } - return value; - } - - fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${Ks(e,h)}) { - let col = colIn * ${e}; - if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) { - var value = valueIn; - let coords = vec3(batch, row, colIn); - ${t?`value = value + ${o?"bias[colIn]":`${Ks(e,h)}(bias[row])`};`:""} - ${s} - ${p.setByIndices("vec3(coords)","value")} - } - } - `},wo=(e,t,s,n,o=!1,a)=>{let i=e[0].dims,u=e[1].dims,p=i.slice(0,-2),h=u.slice(0,-2),k=n?n.slice(0,-2):s.slice(0,-2),C=ze.size(k),d=i[i.length-2],z=i[i.length-1],B=u[u.length-1],V=z%4===0&&B%4===0,Z=d<=8?[4,1,1]:[4,4,1],ee=[8,8,1],X=[Math.ceil(B/ee[0]/Z[0]),Math.ceil(d/ee[1]/Z[1]),Math.ceil(C/ee[2]/Z[2])],he=V?4:1,pe=[...p,d,z/he],Me=pe.length,Oe=[...h,z,B/he],Le=Oe.length,Ye=[C,d,B/he],at=[{type:6,data:d},{type:6,data:B},{type:6,data:z}];on(t,at),at.push(...yt(k,pe,Oe));let Pt=["rank","rank"],Xt=e.length>2;Xt&&(at.push(...yt(e[2].dims)),Pt.push("rank")),at.push(...yt(Ye));let Zt=bt=>{let ss=k.length,St=Uo("batchDims",e[0].dataType,ss,1),Ft=_s(e[0].dataType),bs=qe("a",e[0].dataType,Me,he),Ht=qe("b",e[1].dataType,Le,he),Rt=It("result",e[0].dataType,Ye.length,he),fs=[bs,Ht];if(Xt){let Tr=o?he:1;fs.push(qe("bias",e[2].dataType,e[2].dims.length,Tr))}let it=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];Dr(t,it);let Et=_s(Rt.type.tensor),ps=nn(t,Rt.type.value,Et),Ns=Ni(he,Xt,ps,[St,bs,Ht,Rt],o);return` - ${bt.registerUniforms(it).registerInternalVariables(St).declareVariables(...fs,Rt)} - ${Ns} - ${V?Bi(Z,ee,Ft,St):Ri(Z,ee,Ft,St)} - `};return{name:"MatMul",shaderCache:{hint:`${Z};${t.activation};${V};${o}`,inputDependencies:Pt},getRunData:()=>({outputs:[{dims:a?a(s):s,dataType:e[0].dataType}],dispatchGroup:{x:X[0],y:X[1],z:X[2]},programUniforms:at}),getShaderSource:Zt}}}),Ui,fu,qc=g(()=>{zt(),Pe(),Yt(),an(),Di(),Hc(),ji(),Ui=(e,t,s,n,o=!1,a,i=4,u=4,p=4,h="f32")=>{let k=at=>{switch(at){case 1:return"resData = x[xIndex];";case 3:return`resData = vec3<${h}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return"resData = x[xIndex / 4];";default:throw new Error(`innerElementSize ${at} is not supported.`)}},C=at=>{switch(at){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 ${at} is not supported.`)}},d=e?` - let coord = vec4(batch, xRow, xCol, xCh); - `:` - let coord = vec4(batch, xCh, xRow, xCol); - `,z=e?` - let coords = vec4( - batch, - row / outWidth, - row % outWidth, - col); - `:` - let coords = vec4( - batch, - row, - col / outWidth, - col % outWidth); - `,B=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",V=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",Z=e?"row":"col",ee=e?"col":"row",X=` - let inChannels = i32(uniforms.w_shape[2]); - let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; - let outRow = ${Z} / outWidth; - let outCol = ${Z} % outWidth; - - let WRow = ${ee} / (i32(uniforms.w_shape[1]) * inChannels); - let WCol = ${ee} / 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 = ${ee} % inChannels; - var resData = ${Ks(i,h)}(0.0); - // The bounds checking is always needed since we use it to pad zero for - // the 'same' padding type. - if (xRow >= 0 && xRow < ${B} && xCol >= 0 && xCol < ${V}) { - ${d} - let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape)); - ${k(i)} - } - return resData;`,he=e?t&&n?` - let col = colIn * ${i}; - ${X}`:` - let col = colIn * ${i}; - if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { - ${X} - } - return ${Ks(i,h)}(0.0);`:n&&s?` - let col = colIn * ${i}; - ${X}`:` - let col = colIn * ${i}; - if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { - ${X} - } - return ${Ks(i,h)}(0.0);`,pe=e?n&&s?C(u):` - let col = colIn * ${u}; - if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { - ${C(u)} - } - return ${Ks(u,h)}(0.0);`:` - let col = colIn * ${u}; - if (row < uniforms.dim_inner && col < uniforms.dim_a_outer) { - ${C(u)} - } - return ${Ks(u,h)}(0.0);`,Me=Ks(p,h),Oe=Ks(e?i:u,h),Le=Ks(e?u:i,h),Ye=nn(a,Me,h);return` - fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${Oe} { - ${e?he:pe} - } - - fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${Le} { - ${e?pe:he} - } - - fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${Me}) { - let col = colIn * ${p}; - 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])"}; - ${z} - ${Fi(o)} - ${Ye} - setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); - } - }`},fu=(e,t,s,n,o,a,i,u,p)=>{let h=t.format==="NHWC",k=h?e[0].dims[3]:e[0].dims[1],C=s[0],d=h?s[2]:s[3],z=h?s[1]:s[2],B=h?s[3]:s[1],V=h&&(k%4===0||k%3===0)&&B%4===0,Z=h?B:d*z,ee=h?d*z:B,X=[8,8,1],he=n<=8?[4,1,1]:[4,4,1],pe=[Math.ceil(Z/X[0]/he[0]),Math.ceil(ee/X[1]/he[1]),Math.ceil(C/X[2]/he[2])];as("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${pe}`);let Me=V?h&&k%4!==0?3:4:1,Oe=X[1]*he[1],Le=X[0]*he[0],Ye=Math.max(X[0]*Me,X[1]),at=n%Oe===0,Pt=o%Le===0,Xt=a%Ye===0,Zt=V?[Me,4,4]:[1,1,1],bt=[{type:6,data:n},{type:6,data:o},{type:6,data:a},{type:6,data:[t.pads[0],t.pads[1]]},{type:6,data:t.strides},{type:6,data:t.dilations}];on(t,bt),bt.push(...yt(e[0].dims,e[1].dims));let ss=["rank","rank"];i&&(bt.push(...yt(e[2].dims)),ss.push("rank")),bt.push(...yt(s));let St=Ft=>{let bs=[{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}];Dr(t,bs);let Ht=V?4:1,Rt=_s(e[0].dataType),fs=` - fn setOutputAtIndex(flatIndex : i32, value : ${V?`vec4<${Rt}>`:Rt}) { - result[flatIndex] = ${V?`vec4<${Rt}>`:Rt}(value); - } - fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${V?`vec4<${Rt}>`:Rt}) { - let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3)); - setOutputAtIndex(flatIndex ${V?"/ 4":""}, value); - }`,it=qe("x",e[0].dataType,e[0].dims.length,Me===3?1:Me),Et=qe("w",e[1].dataType,e[1].dims.length,Ht),ps=[it,Et],Ns=It("result",e[0].dataType,s.length,Ht);if(i){let Tr=qe("bias",e[2].dataType,e[2].dims.length,Ht);ps.push(Tr),fs+=` - fn getBiasByOutputCoords(coords : vec4) -> ${V?`vec4<${Rt}>`:Rt} { - return bias[coords.${h?"w":"y"}${V?"/ 4":""}]; - }`}return` - ${Li("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 }; - ${Ft.registerUniforms(bs).declareVariables(...ps,Ns)} - ${fs} - ${Ui(h,at,Pt,Xt,i,t,Zt[0],Zt[1],Zt[2],Rt)} - ${V?Bi(he,X,Rt,void 0,!h,Ye):Ri(he,X,Rt,void 0,!h,Ye,!1,void 0,u)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${t.cacheKey};${Me};${V};${at};${Pt};${Xt};${Oe};${Le};${Ye}`,inputDependencies:ss},getRunData:()=>({outputs:[{dims:p?p(s):s,dataType:e[0].dataType}],dispatchGroup:{x:pe[0],y:pe[1],z:pe[2]},programUniforms:bt}),getShaderSource:St}}}),Vi,Wi,Vn,Gi,Ki,gu,Hi,wu,Qc=g(()=>{zt(),Pe(),Ot(),Yt(),an(),Di(),Vi=e=>{let t=1;for(let s=0;stypeof e=="number"?[e,e,e]:e,Vn=(e,t)=>t<=1?e:e+(e-1)*(t-1),Gi=(e,t,s,n=1)=>{let o=Vn(t,n);return Math.floor((e[0]*(s-1)-s+o)/2)},Ki=(e,t,s,n,o)=>{o==null&&(o=Gi(e,t[0],n[0]));let a=[0,0,0,s];for(let i=0;i<3;i++)e[i]+2*o>=t[i]&&(a[i]=Math.trunc((e[i]-t[i]+2*o)/n[i]+1));return a},gu=(e,t,s,n,o,a,i,u,p,h)=>{let k,C,d,z;if(e==="VALID"&&(e=0),typeof e=="number"){k={top:e,bottom:e,left:e,right:e,front:e,back:e};let B=Ki([t,s,n,1],[u,p,h],1,[o,a,i],e);C=B[0],d=B[1],z=B[2]}else if(Array.isArray(e)){if(!e.every((V,Z,ee)=>V===ee[0]))throw Error(`Unsupported padding parameter: ${e}`);k={top:e[0],bottom:e[1],left:e[2],right:e[3],front:e[4],back:e[5]};let B=Ki([t,s,n,1],[u,p,h],1,[o,a,i],e[0]);C=B[0],d=B[1],z=B[2]}else if(e==="SAME_UPPER"){C=Math.ceil(t/o),d=Math.ceil(s/a),z=Math.ceil(n/i);let B=(C-1)*o+u-t,V=(d-1)*a+p-s,Z=(z-1)*i+h-n,ee=Math.floor(B/2),X=B-ee,he=Math.floor(V/2),pe=V-he,Me=Math.floor(Z/2),Oe=Z-Me;k={top:he,bottom:pe,left:Me,right:Oe,front:ee,back:X}}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:k,outDepth:C,outHeight:d,outWidth:z}},Hi=(e,t,s,n,o,a=!1,i="channelsLast")=>{let u,p,h,k,C;if(i==="channelsLast")[u,p,h,k,C]=e;else if(i==="channelsFirst")[u,C,p,h,k]=e;else throw new Error(`Unknown dataFormat ${i}`);let[d,,z,B,V]=t,[Z,ee,X]=Wi(s),[he,pe,Me]=Wi(n),Oe=Vn(z,he),Le=Vn(B,pe),Ye=Vn(V,Me),{padInfo:at,outDepth:Pt,outHeight:Xt,outWidth:Zt}=gu(o,p,h,k,Z,ee,X,Oe,Le,Ye),bt=a?d*C:d,ss=[0,0,0,0,0];return i==="channelsFirst"?ss=[u,bt,Pt,Xt,Zt]:i==="channelsLast"&&(ss=[u,Pt,Xt,Zt,bt]),{batchSize:u,dataFormat:i,inDepth:p,inHeight:h,inWidth:k,inChannels:C,outDepth:Pt,outHeight:Xt,outWidth:Zt,outChannels:bt,padInfo:at,strideDepth:Z,strideHeight:ee,strideWidth:X,filterDepth:z,filterHeight:B,filterWidth:V,effectiveFilterDepth:Oe,effectiveFilterHeight:Le,effectiveFilterWidth:Ye,dilationDepth:he,dilationHeight:pe,dilationWidth:Me,inShape:e,outShape:ss,filterShape:t}},wu=(e,t,s,n,o,a)=>{let i=a==="channelsLast";i?e[0].dims[3]:e[0].dims[1];let u=[64,1,1],p={x:s.map((Z,ee)=>ee)},h=[Math.ceil(Vi(p.x.map(Z=>s[Z]))/u[0]),1,1];as("verbose",()=>`[conv3d_naive_webgpu] dispatch = ${h}`);let k=1,C=ze.size(s),d=[{type:12,data:C},{type:12,data:n},{type:12,data:o},{type:12,data:t.strides},{type:12,data:t.dilations}];on(t,d),d.push(...yt(e[0].dims,e[1].dims));let z=["rank","rank"],B=e.length===3;B&&(d.push(...yt(e[2].dims)),z.push("rank")),d.push(...yt(s));let V=Z=>{let ee=[{name:"output_size",type:"u32"},{name:"filter_dims",type:"u32",length:n.length},{name:"pads",type:"u32",length:o.length},{name:"strides",type:"u32",length:t.strides.length},{name:"dilations",type:"u32",length:t.dilations.length}];Dr(t,ee);let X=1,he=_s(e[0].dataType),pe=qe("x",e[0].dataType,e[0].dims.length,k),Me=qe("W",e[1].dataType,e[1].dims.length,X),Oe=[pe,Me],Le=It("result",e[0].dataType,s.length,X),Ye="";if(B){let Xt=qe("bias",e[2].dataType,e[2].dims.length,X);Oe.push(Xt),Ye+=` - fn getBiasByOutputCoords(coords : array) -> ${he} { - return bias[${i?$t("coords",4,5):$t("coords",1,5)}]; - }`}let at=Ks(k,he),Pt=nn(t,at,he);return` - ${Ye} - fn getX(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { - let aIndices = array(d0, d1, d2, d3, d4); - return ${pe.getByIndices("aIndices")}; - } - fn getW(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { - let aIndices = array(d0, d1, d2, d3, d4); - return ${Me.getByIndices("aIndices")}; - } - ${Z.registerUniforms(ee).declareVariables(...Oe,Le)} - ${Z.mainStart()} - ${Z.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - let coords = ${Le.offsetToIndices("global_idx")}; - let batch = ${$t("coords",0,pe.rank)}; - let d2 = ${i?$t("coords",pe.rank-1,pe.rank):$t("coords",1,pe.rank)}; - let xFRCCorner = vec3(${i?$t("coords",1,pe.rank):$t("coords",2,pe.rank)}, - ${i?$t("coords",2,pe.rank):$t("coords",3,pe.rank)}, - ${i?$t("coords",3,pe.rank):$t("coords",4,pe.rank)}) * uniforms.strides - uniforms.pads; - let xFCorner = xFRCCorner.x; - let xRCorner = xFRCCorner.y; - let xCCorner = xFRCCorner.z; - let xShapeY = ${i?$t("uniforms.x_shape",1,pe.rank):$t("uniforms.x_shape",2,pe.rank)}; - let xShapeZ = ${i?$t("uniforms.x_shape",2,pe.rank):$t("uniforms.x_shape",3,pe.rank)}; - let xShapeW = ${i?$t("uniforms.x_shape",3,pe.rank):$t("uniforms.x_shape",4,pe.rank)}; - let xShapeU = ${i?$t("uniforms.x_shape",4,pe.rank):$t("uniforms.x_shape",1,pe.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); - } - } - } - } - ${B?"value = value + getBiasByOutputCoords(coords)":""}; - ${Pt} - result[global_idx] = f32(value); - }`};return{name:"Conv3DNaive",shaderCache:{hint:`${t.cacheKey};${i};${k};${B}`,inputDependencies:z},getRunData:()=>({outputs:[{dims:s,dataType:e[0].dataType}],dispatchGroup:{x:h[0],y:h[1],z:h[2]},programUniforms:d}),getShaderSource:V}}}),yu,Mu,qi=g(()=>{zt(),Ot(),Yt(),an(),yu=(e,t,s,n)=>{let o=e.length>2,a=o?"value += b[output_channel];":"",i=e[0].dims,u=e[1].dims,p=t.format==="NHWC",h=p?s[3]:s[1],k=h/t.group,C=p&&k>=4?qt(h):1,d=ze.size(s)/C,z=[{type:12,data:d},{type:12,data:t.dilations},{type:12,data:[t.strides[0],t.strides[1]]},{type:12,data:[t.pads[0],t.pads[1]]},{type:12,data:k}];on(t,z),z.push(...yt(i,[u[0],u[1],u[2],u[3]/C]));let B=o?["rank","rank","rank"]:["rank","rank"];z.push(...yt([s[0],s[1],s[2],s[3]/C]));let V=Z=>{let ee=It("output",e[0].dataType,s.length,C),X=_s(ee.type.tensor),he=nn(t,ee.type.value,X),pe=qe("x",e[0].dataType,i.length),Me=qe("w",e[1].dataType,u.length,C),Oe=[pe,Me];o&&Oe.push(qe("b",e[2].dataType,e[2].dims,C));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"}];Dr(t,Le);let Ye=p?` - 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 = ${pe.get("batch","xHeight","xWidth","input_channel")}; - let wVal = ${Me.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 = ${pe.get("batch","input_channel","xHeight","xWidth")}; - let wVal = ${Me.get("output_channel","wInChannel","wHeight","wWidth")}; - value += xVal * wVal; - } - } - } - `;return` - ${Z.registerUniforms(Le).declareVariables(...Oe,ee)} - - ${Z.mainStart()} - ${Z.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - - let outputIndices = ${ee.offsetToIndices("global_idx")}; - let batch: u32 = outputIndices[0]; - let output_channel: u32 = outputIndices[${p?3:1}]; - let xRCCorner: vec2 = vec2(outputIndices[${p?1:2}], outputIndices[${p?2:3}]) * uniforms.strides - uniforms.pads; - let group_id: u32 = output_channel * ${C} / uniforms.output_channels_per_group; - var in_channel_offset = group_id * uniforms.w_shape[${p?2:1}]; - - var value: ${ee.type.value} = ${ee.type.value}(0); - ${Ye} - ${a} - ${he} - ${ee.setByOffset("global_idx","value")} - }`};return{name:"GroupedConv",shaderCache:{hint:`${t.cacheKey}_${C}`,inputDependencies:B},getRunData:()=>({outputs:[{dims:n?n(s):s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:z}),getShaderSource:V}},Mu=(e,t,s,n)=>{let o=e.length>2,a=qt(s[3]),i=qt(s[2]),u=ze.size(s)/a/i,p=[e[0].dims[0],e[0].dims[1],e[0].dims[2],e[0].dims[3]/a],h=[e[1].dims[0],e[1].dims[1],e[1].dims[2],e[1].dims[3]/a],k=[s[0],s[1],s[2],s[3]/a],C=[{type:12,data:u},{type:6,data:[t.strides[0],t.strides[1]]},{type:6,data:[t.pads[0],t.pads[1]]}];on(t,C),C.push(...yt(p,h,k));let d=(i-1)*t.strides[1]+h[1],z=B=>{let V=It("output",e[0].dataType,k.length,a),Z=_s(V.type.tensor),ee=nn(t,V.type.value,Z),X=qe("x",e[0].dataType,p.length,a),he=qe("w",e[1].dataType,h.length,a),pe=[X,he];o&&pe.push(qe("b",e[2].dataType,e[2].dims,a));let Me=o?"value += b[output_channel];":"",Oe=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return Dr(t,Oe),` - ${B.registerUniforms(Oe).declareVariables(...pe,V)} - ${B.mainStart()} - ${B.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<${X.type.value}, ${d}>; - var values: array<${V.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 < ${h[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 < ${d}; i++) { - let x_width = x_corner.y + i; - if (x_width >= 0 && u32(x_width) < uniforms.x_shape[2]) { - x_vals[i] = ${X.get("batch","u32(x_height)","u32(x_width)","input_channel")}; - } else { - x_vals[i] = ${X.type.value}(0); - } - } - for (var w_width: u32 = 0u; w_width < ${h[1]}; w_width++) { - let w_val = ${he.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]; - ${Me} - ${ee} - ${V.set("batch","row","col + i","output_channel","value")}; - } - }`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${t.cacheKey};${a};${i};${d};${h[0]};${h[1]}`,inputDependencies:o?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:n?n(s):s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:C}),getShaderSource:z}}}),bu,yo,vu,Mo,Qi,bo,xu,Tu,vo,Xc=g(()=>{Ot(),qc(),Qc(),ji(),qi(),an(),fo(),Kr(),bu=(e,t,s,n,o,a)=>{let i=e[0],u=e.slice(a?1:2,a?3:4),p=u.length,h=t[0],k=t.slice(2).map((d,z)=>d+(d-1)*(s[z]-1)),C=u.map((d,z)=>d+n[z]+n[z+p]).map((d,z)=>Math.floor((d-k[z]+o[z])/o[z]));return C.splice(0,0,i),C.splice(a?3:1,0,h),C},yo=[2,3,1,0],vu=(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 s=e[0].dims[t.format==="NHWC"?e[0].dims.length-1:1],n=e[1].dims[1]*t.group;if(s!==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 o=e[0].dims.length-2;if(t.dilations.length!==o)throw new Error(`dilations should be ${o}D`);if(t.strides.length!==o)throw new Error(`strides should be ${o}D`);if(t.pads.length!==o*2)throw new Error(`pads should be ${o*2}D`);if(t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape")},Mo=(e,t)=>{let s=e.kernelShape.slice();s.length{let t=Oi(e),s=e.format,n=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],o=e.dilations,a=e.group,i=e.kernel_shape,u=e.pads,p=e.strides,h=e.w_is_const();return{autoPad:n,format:s,dilations:o,group:a,kernelShape:i,pads:u,strides:p,wIsConst:h,...t,cacheKey:`${e.format};${t.activation};`}},bo=(e,t,s,n)=>{let o=s.format==="NHWC",a=bu(t[0].dims,t[1].dims,s.dilations,s.pads,s.strides,o);if(s.group!==1){let Oe=[t[0]];if(o){let Le=e.kernelCustomData.wT??e.compute(pr(t[1],yo),{inputs:[1],outputs:[s.wIsConst?-2:-1]})[0];s.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=Le),Oe.push(Le)}else Oe.push(t[1]);t.length===3&&Oe.push(t[2]),!e.adapterInfo.isArchitecture("ampere")&&o&&t[1].dims[0]===s.group&&t[1].dims[1]===1&&s.dilations[0]===1&&s.dilations[1]===1?e.compute(Mu(Oe,s,a,n),{inputs:Oe}):e.compute(yu(Oe,s,a,n),{inputs:Oe});return}let i=t.length===3,u=t[0].dims[o?1:2],p=t[0].dims[o?2:3],h=t[0].dims[o?3:1],k=t[1].dims[2],C=t[1].dims[3],d=a[o?1:2],z=a[o?2:3],B=a[o?3:1],V=o&&k===u&&C===p&&s.pads[0]===0&&s.pads[1]===0;if(V||k===1&&C===1&&s.dilations[0]===1&&s.dilations[1]===1&&s.strides[0]===1&&s.strides[1]===1&&s.pads[0]===0&&s.pads[1]===0){let Oe=a[0],Le,Ye,at,Pt=[];if(o){let bt=e.kernelCustomData.wT??e.compute(pr(t[1],yo),{inputs:[1],outputs:[s.wIsConst?-2:-1]})[0];if(s.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=bt),V){let ss=u*p*h;Le=t[0].reshape([1,Oe,ss]),Ye=bt.reshape([1,ss,B]),at=[1,Oe,B]}else Le=t[0].reshape([Oe,u*p,h]),Ye=bt.reshape([1,h,B]),at=[Oe,d*z,B];Pt.push(Le),Pt.push(Ye)}else Le=t[0].reshape([Oe,h,u*p]),Ye=t[1].reshape([1,B,h]),at=[Oe,B,d*z],Pt.push(Ye),Pt.push(Le);i&&Pt.push(t[2]);let Xt=at[2],Zt=Pt[0].dims[Pt[0].dims.length-1];Xt<8&&Zt<8?e.compute(zi(Pt,s,a,at,o,n),{inputs:Pt}):e.compute(wo(Pt,s,a,at,o,n),{inputs:Pt});return}let Z=!0,ee=e.kernelCustomData.wT??e.compute(pr(t[1],yo),{inputs:[1],outputs:[s.wIsConst?-2:-1]})[0];s.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=ee);let X=[t[0],ee];i&&X.push(t[2]);let he=o?d*z:B,pe=o?B:d*z,Me=k*C*h;e.compute(fu(X,s,a,he,pe,Me,i,Z,n),{inputs:X})},xu=(e,t)=>{let s=t.format==="NHWC",n=[e.inputs[0].reshape(s?[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 o=[0,t.pads[0],0,t.pads[1]],a=[1].concat(t.strides),i=[1].concat(t.dilations),u=[1].concat(t.kernelShape),p=Mo({...t,pads:o,strides:a,dilations:i,kernelShape:u},n);bo(e,n,p,h=>s?[h[0],h[2],h[3]]:[h[0],h[1],h[3]])},Tu=(e,t,s)=>{let n=s.format==="NHWC"?"channelsLast":"channelsFirst",o=Mo(s,t),a=s.autoPad==="NOTSET"?s.pads:s.autoPad,i=Hi(t[0].dims,t[1].dims,s.strides,s.dilations,a,!1,n);e.compute(wu(t,o,i.outShape,[i.filterDepth,i.filterHeight,i.filterWidth],[i.padInfo.front,i.padInfo.top,i.padInfo.left],n))},vo=(e,t)=>{if(vu(e.inputs,t),e.inputs[0].dims.length===3)xu(e,t);else if(e.inputs[0].dims.length===5)Tu(e,e.inputs,t);else{let s=Mo(t,e.inputs);bo(e,e.inputs,s)}}}),Pu,Yc=g(()=>{zt(),Pe(),Ot(),Yt(),Pu=(e,t,s)=>{let n=e.length>2,o=t.outputShape,a=t.format==="NHWC",i=t.group,u=e[1].dims,p=u[2]/i,h=u[3],k=a?qt(p):1,C=a?qt(h):1,d=a?h===1?k:C:1,z=ze.size(o)/C,B=[Math.ceil(z/64),1,1];as("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${B}`);let V=["rank","rank"],Z=[t.strides[0],t.strides[1]],ee=[t.kernelShape[a?1:2],t.kernelShape[a?2:3]],X=[t.dilations[0],t.dilations[1]],he=[ee[0]+(t.dilations[0]<=1?0:(t.kernelShape[a?1:2]-1)*(t.dilations[0]-1)),ee[1]+(t.dilations[1]<=1?0:(t.kernelShape[a?2:3]-1)*(t.dilations[1]-1))],pe=[he[0]-1-Math.floor((t.pads[0]+t.pads[2])/2),he[1]-1-Math.floor((t.pads[1]+t.pads[3])/2)],Me=[{type:12,data:z},{type:12,data:Z},{type:12,data:ee},{type:12,data:X},{type:12,data:he},{type:6,data:pe},{type:12,data:p},{type:12,data:h},...yt(e[0].dims,e[1].dims)];n&&(Me.push(...yt(e[2].dims)),V.push("rank")),Me.push(...yt(o));let Oe=Le=>{let Ye=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:Z.length},{name:"filter_dims",type:"u32",length:ee.length},{name:"dilations",type:"u32",length:ee.length},{name:"effective_filter_dims",type:"u32",length:he.length},{name:"pads",type:"i32",length:pe.length},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],at=_s(e[0].dataType),Pt=a?1:2,Xt=a?2:3,Zt=a?3:1,bt=qe("W",e[1].dataType,e[1].dims.length,d),ss=qe("Dy",e[0].dataType,e[0].dims.length,k),St=[ss,bt];n&&St.push(qe("bias",e[2].dataType,[o[Zt]].length,C));let Ft=It("result",e[0].dataType,o.length,C),bs=()=>{let Rt="";if(k===1)Rt+=` - let w_offset = ${bt.indicesToOffset(`${bt.type.indices}(u32(wRPerm), u32(wCPerm), inputChannel, wOutChannel)`)}; - let wValue = ${bt.getByOffset(`w_offset / ${d}`)}; - dotProd = dotProd + xValue * wValue;`;else if(h===1)Rt+=` - let wValue = ${bt.getByOffset(`${bt.indicesToOffset(`${bt.type.indices}(u32(wRPerm), u32(wCPerm), inputChannel, wOutChannel)`)} / ${d}`)}; - dotProd = dotProd + dot(xValue, wValue);`;else for(let fs=0;fs(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 = ${Ft.type.value}(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 = (${at}(dyRCorner) + ${at}(wR)) / ${at}(uniforms.strides[0]); - let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x; - if (dyR < 0.0 || dyR >= ${at}(uniforms.Dy_shape[${Pt}]) || fract(dyR) > 0.0 || - wRPerm < 0) { - continue; - } - wR = wR + uniforms.strides[0] - 1; - 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 = (${at}(dyCCorner) + ${at}(wC)) / ${at}(uniforms.strides.y); - let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y; - if (dyC < 0.0 || dyC >= ${at}(uniforms.Dy_shape[${Xt}]) || - fract(dyC) > 0.0 || wCPerm < 0) { - continue; - } - wC = wC + uniforms.strides.y - 1; - 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 + ${k}) { - let xValue = ${a?ss.getByOffset(`${ss.indicesToOffset(`${ss.type.indices}(batch, idyR, idyC, inputChannel)`)} / ${k}`):ss.get("batch","inputChannel","idyR","idyC")}; - ${bs()} - inputChannel = inputChannel + ${k}; - } - } - } - let value = dotProd${n?` + bias[d1 / ${C}]`:""}; - ${Ft.setByOffset("global_idx","value")}; - `;return` - ${Le.registerUniforms(Ye).declareVariables(...St,Ft)} - ${Le.mainStart()} - ${Le.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}; - ${Ht}}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${t.cacheKey};${k}${d}${C}${h===1}`,inputDependencies:V},getRunData:()=>({dispatchGroup:{x:B[0],y:B[1],z:B[2]},outputs:[{dims:s?s(o):o,dataType:e[0].dataType}],programUniforms:Me}),getShaderSource:Oe}}}),Eu,Xi,Cu,Yi,Ji,ku,Zi,ea,Su,Jc=g(()=>{Yc(),an(),Kr(),Eu=(e,t,s,n,o,a)=>(e-1)*t+s+(n-1)*o+1-a,Xi=(e,t,s,n,o)=>{let a=Math.floor(e/2);t==="SAME_UPPER"?(s[n]=a,s[o]=e-a):t==="SAME_LOWER"&&(s[n]=e-a,s[o]=a)},Cu=(e,t,s,n,o,a,i,u,p,h)=>{let k=e.length-2,C=h.length===0;p.length{let s=e.kernelShape.slice();if(e.kernelShape.length===0||e.kernelShape.reduce((C,d)=>C*d,1)===0){s.length=0;for(let C=2;CC+d,0)===0){let C=t[0].dims.length-2;p=new Array(C).fill(1)}let h=e.strides.slice();if(h.reduce((C,d)=>C+d,0)===0){let C=t[0].dims.length-2;h=new Array(C).fill(1)}Cu(u,s,p,e.autoPad,e.group,o,h,n,i,a);let k=Object.assign({},e);return Object.assign(k,{kernelShape:s,pads:o,outputPadding:i,outputShape:a,dilations:p,strides:h}),k},Ji=e=>{let t=Oi(e),s=e.format,n=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof e.autoPad>"u"?0:e.autoPad],o=e.dilations,a=e.group,i=e.kernelShape,u=e.pads,p=e.strides,h=e.wIsConst(),k=e.outputPadding,C=e.outputShape;return{autoPad:n,format:s,dilations:o,group:a,kernelShape:i,outputPadding:k,outputShape:C,pads:u,strides:p,wIsConst:h,...t,cacheKey:`${e.format};${t.activation};`}},ku=(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 s=e[0].dims[t.format==="NHWC"?e[0].dims.length-1:1],n=e[1].dims[0];if(s!==n)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");let o=e[1].dims[1]*t.group;if(e.length===3&&(e[2].dims.length!==1||e[2].dims[0]!==o))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")},Zi=(e,t,s,n)=>{let o=e.kernelCustomData.wT??e.compute(pr(t[1],[2,3,0,1]),{inputs:[1],outputs:[s.wIsConst?-2:-1]})[0];s.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=o);let a=[t[0],o];t.length===3&&a.push(t[2]),e.compute(Pu(a,s,n),{inputs:a})},ea=(e,t)=>{let s=t.format==="NHWC",n=[e.inputs[0].reshape(s?[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 o=t.kernelShape;(o.length===0||o[0]===0)&&(o=[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),o=[1].concat(o);let p=Yi({...t,pads:u,strides:i,dilations:a,kernelShape:o},n);Zi(e,n,p,h=>s?[h[0],h[2],h[3]]:[h[0],h[1],h[3]])},Su=(e,t)=>{if(ku(e.inputs,t),e.inputs[0].dims.length===3)ea(e,t);else{let s=Yi(t,e.inputs);Zi(e,e.inputs,s)}}}),ta,$u,Au,Zc=g(()=>{zt(),Ot(),rs(),Yt(),ta=(e,t,s,n)=>{let o=ze.size(t),a=t.length,i=qe("input",e,a),u=It("output",e,a),p=s.dataType===6?s.getInt32Array()[0]:Number(s.getBigInt64Array()[0]),h=ze.normalizeAxis(p,a),k=C=>{let d=` i32(${i.indicesGet("inputIndices","uniforms.axis")}) `,z=$t("uniforms.input_shape","uniforms.axis",a),B=n.reverse?d+(n.exclusive?" + 1":""):"0",V=n.reverse?z:d+(n.exclusive?"":" + 1");return` - ${C.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(i,u)} - ${C.mainStart()} - ${C.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} - var inputIndices = ${u.offsetToIndices("global_idx")}; - var sum = ${u.type.value}(0); - let first : i32 = ${B}; - let last : i32 = ${V}; - 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(o/64)},programUniforms:[{type:12,data:o},{type:12,data:h},...yt(t,t)]}),getShaderSource:k}},$u=(e,t)=>{let s=e.inputs[0].dims,n=e.inputs[0].dataType,o=e.inputs[1];e.compute(ta(n,s,o,t),{inputs:[0]})},Au=e=>{let t=e.exclusive===1,s=e.reverse===1;return Bt({exclusive:t,reverse:s})}}),Iu,sa,Ou,Fu,Du,ep=g(()=>{zt(),Ot(),rs(),Yt(),Iu=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.")},sa=(e,t,s,n)=>{let o=[];o.push(`fn perm(i: ${n.type.indices}) -> ${s.type.indices} { - var a: ${s.type.indices};`);for(let a=0;a{let s,n,o,a,i,u,p=t.format==="NHWC",h=t.blocksize,k=t.mode==="DCR";p?([s,n,o,a]=e.dims,i=k?[s,n,o,h,h,a/h**2]:[s,n,o,a/h**2,h,h],u=k?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([s,n,o,a]=[e.dims[0],e.dims[2],e.dims[3],e.dims[1]],i=k?[s,h,h,a/h**2,n,o]:[s,a/h**2,h,h,n,o],u=k?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let C=e.reshape(i),d=C.dims.length,z=e.dataType,B=qe("a",z,d),V=It("output",z,d),Z=ee=>` - ${ee.registerUniform("output_size","u32").declareVariables(B,V)} - - ${sa(u,d,B,V)} - - ${ee.mainStart()} - ${ee.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - - let indices = ${V.offsetToIndices("global_idx")}; - let aIndices = perm(indices); - - ${V.setByOffset("global_idx",B.getByIndices("aIndices"))} - }`;return{name:"DepthToSpace",shaderCache:{hint:`${e.dims};${t.blocksize};${t.mode}`,inputDependencies:["rank"]},getRunData:ee=>{let X=p?[s,n*h,o*h,a/h**2]:[s,a/h**2,n*h,o*h],he=ze.size(X),pe=C.dims,Me=ze.sortBasedOnPerm(pe,u);return{outputs:[{dims:X,dataType:ee[0].dataType}],dispatchGroup:{x:Math.ceil(he/64)},programUniforms:[{type:12,data:he},...yt(pe,Me)]}},getShaderSource:Z}},Fu=(e,t)=>{Iu(e.inputs),e.compute(Ou(e.inputs[0],t))},Du=e=>Bt({blocksize:e.blocksize,mode:e.mode,format:e.format})}),xo,Wn,To,Lu,zu,ra,Bu,na,Hr,Ru,Nu,tp=g(()=>{zt(),Ot(),rs(),Yt(),xo="[a-zA-Z]|\\.\\.\\.",Wn="("+xo+")+",To="^"+Wn+"$",Lu="("+Wn+",)*"+Wn,zu="^"+Lu+"$",ra=class{constructor(e=-1){this.symbolToIndices=new Map,this.inputIndex=e}addSymbol(e,t){let s=this.symbolToIndices.get(e);s===void 0?s=[t]:s.push(t),this.symbolToIndices.set(e,s)}},Bu=class{constructor(e,t){var o;this.equation=t,this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=new Array,this.outputDims=[];let[s,n]=t.includes("->")?t.split("->",2):[t,""];if(!s.match(RegExp(zu)))throw new Error("Invalid LHS term");if(s.split(",").forEach((a,i)=>{let u=e[i].dims.slice();if(!a.match(RegExp(To)))throw new Error("Invalid LHS term");let p=this.processTerm(a,!0,u,i);this.lhs.push(p)}),n==="")n+=[...this.symbolToInfo.entries()].filter(([a,i])=>i.count===1||a==="...").map(([a])=>a).join("");else if(!n.match(RegExp(Wn)))throw new Error("Invalid RHS");(o=n.match(RegExp(xo,"g")))==null||o.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,s){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(s)}else n={count:1,dimValue:t,inputIndices:[s]};this.symbolToInfo.set(e,n)}processTerm(e,t,s,n=-1){let o=s.length,a=!1,i=[],u=0;if(!e.match(RegExp(To))&&!t&&e!=="")throw new Error("Invalid LHS term");let p=e.match(RegExp(xo,"g")),h=new ra(n);return p==null||p.forEach((k,C)=>{if(k==="..."){if(a)throw new Error("Only one ellipsis is allowed per input term");a=!0;let d=o-p.length+1;if(d<0)throw new Error("Ellipsis out of bounds");if(i=s.slice(u,u+d),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 z=0;ze+"_max",Hr=(e,t,s,n)=>{let o=e.map(h=>h.length).map((h,k)=>qe(`input${k}`,t,h)),a=ze.size(n),i=It("output",t,n.length),u=[...s.symbolToInfo.keys()].filter(h=>!s.rhs.symbolToIndices.has(h)),p=h=>{let k=[],C="var prod = 1.0;",d="var sum = 0.0;",z="sum += prod;",B=[],V=[],Z=[],ee=[],X=s.symbolToInfo.size===s.rhs.symbolToIndices.size;s.symbolToInfo.forEach((pe,Me)=>{var Oe;if(s.rhs.symbolToIndices.has(Me)){let Le=(Oe=s.rhs.symbolToIndices.get(Me))==null?void 0:Oe[0];Le!==void 0&&s.lhs.forEach((Ye,at)=>{if(pe.inputIndices.includes(at)){let Pt=Ye.symbolToIndices.get(Me);if(Pt===void 0)throw new Error("Invalid symbol error");Pt.forEach(Xt=>{k.push(`${o[at].indicesSet(`input${at}Indices`,Xt,i.indicesGet("outputIndices",Le))}`)})}})}else s.lhs.forEach((Le,Ye)=>{if(pe.inputIndices.includes(Ye)){let at=Le.symbolToIndices.get(Me);if(at===void 0)throw new Error("Invalid symbol error");at.forEach(Pt=>{B.push(`${o[Ye].indicesSet(`input${Ye}Indices`,Pt,`${Me}`)}`)}),ee.push(`prod *= ${o[Ye].getByIndices(`input${Ye}Indices`)};`)}}),V.push(`for(var ${Me}: u32 = 0; ${Me} < uniforms.${na(Me)}; ${Me}++) {`),Z.push("}")});let he=X?[...k,`let sum = ${o.map((pe,Me)=>pe.getByIndices(`input${Me}Indices`)).join(" * ")};`]:[...k,d,...V,...B,C,...ee,z,...Z];return` - ${h.registerUniforms(u.map(pe=>({name:`${na(pe)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...o,i)} - - ${h.mainStart()} - ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} - var outputIndices = ${i.offsetToIndices("global_idx")}; - ${o.map((pe,Me)=>`var input${Me}Indices: ${o[Me].type.indices};`).join(` -`)} - ${he.join(` -`)}; - ${i.setByOffset("global_idx","sum")}; - }`};return{name:"Einsum",shaderCache:{hint:s.equation,inputDependencies:e.map(()=>"rank")},getRunData:()=>{let h=u.filter(C=>s.symbolToInfo.has(C)).map(C=>{var d;return{type:12,data:((d=s.symbolToInfo.get(C))==null?void 0:d.dimValue)||0}});h.push({type:12,data:a});let k=e.map((C,d)=>[...yt(C)]).reduce((C,d)=>C.concat(d),h);return k.push(...yt(n)),{outputs:[{dims:n,dataType:t}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:k}},getShaderSource:p}},Ru=(e,t)=>{let s=new Bu(e.inputs,t.equation),n=s.outputDims,o=e.inputs.map((a,i)=>a.dims);e.compute(Hr(o,e.inputs[0].dataType,s,n))},Nu=e=>{let t=e.equation.replace(/\s+/g,"");return Bt({equation:t})}}),ju,Po,Uu,Vu,Wu,sp=g(()=>{zt(),Ot(),Yt(),ju=e=>{if(!e||e.length!==2)throw new Error("Expand requires 2 input.");let t=e[0].dims,s=Array.from(e[1].getBigInt64Array(),Number),n=s.length{let s=e.length-t.length,n=[];for(let o=0;oe.length>t.length?Po(e,t):Po(t,e),Vu=e=>{let t=e[0].dims,s=Array.from(e[1].getBigInt64Array(),Number),n=Uu(t,s),o=e[0].dataType,a=o===9||ze.size(t)===1,i=o===9||t.length>0&&t[t.length-1]%4===0?4:1,u=a||n.length>0&&n[n.length-1]%4===0?4:1,p=Math.ceil(ze.size(n)/u),h=C=>{let d=qe("input",o,t.length,i),z=It("output",o,n.length,u),B;if(o===9){let V=(Z,ee,X="")=>` - let outputIndices${ee} = ${z.offsetToIndices(`outputOffset + ${ee}u`)}; - let offset${ee} = ${d.broadcastedIndicesToOffset(`outputIndices${ee}`,z)}; - let index${ee} = offset${ee} / 4u; - let component${ee} = offset${ee} % 4u; - ${Z}[${ee}] = ${X}(${d.getByOffset(`index${ee}`)}[component${ee}]); - `;B=` - let outputOffset = global_idx * ${u}; - var data = vec4(0); - ${V("data",0,"u32")} - ${V("data",1,"u32")} - ${V("data",2,"u32")} - ${V("data",3,"u32")} - ${z.setByOffset("global_idx","data")} - }`}else B=` - let outputIndices = ${z.offsetToIndices(`global_idx * ${u}`)}; - let inputOffset = ${d.broadcastedIndicesToOffset("outputIndices",z)}; - let data = ${z.type.value}(${d.getByOffset(`inputOffset / ${i}`)}); - ${z.setByOffset("global_idx","data")} - }`;return` - ${C.registerUniform("vec_size","u32").declareVariables(d,z)} - ${C.mainStart()} - ${C.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} - ${B}`},k=[{type:12,data:p},...yt(t,n)];return{name:"Expand",shaderCache:{hint:`${n.length};${i}${u}`,inputDependencies:["rank"]},getShaderSource:h,getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:k})}},Wu=e=>{ju(e.inputs),e.compute(Vu(e.inputs),{inputs:[0]})}}),Eo,Gu,rp=g(()=>{zt(),Ot(),Yt(),Ei(),Eo=e=>{let t=e[0].dataType,s=ze.size(e[0].dims),n=ze.size(e[1].dims),o=n%4===0,a=i=>{let u=qe("x",t,[1],4),p=qe("bias",t,[1],4),h=It("y",t,[1],4),k=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],C=z=>` - let bias${z}_offset: u32 = (global_idx * 4 + ${z}) % uniforms.bias_size; - let bias${z} = ${p.getByOffset(`bias${z}_offset / 4`)}[bias${z}_offset % 4];`,d=o?` - let bias = ${p.getByOffset("global_idx % (uniforms.bias_size / 4)")};`:`${C(0)}${C(1)}${C(2)}${C(3)} - let bias = ${u.type.value}(bias0, bias1, bias2, bias3);`;return`${i.registerUniforms(k).declareVariables(u,p,h)} - - ${Ti(Ss(t))} - - ${i.mainStart(or)} - ${i.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")} - - let x = ${u.getByOffset("global_idx")}; - ${d} - let x_in = x + bias; - ${h.setByOffset("global_idx",_o("x_in"))} - }`};return{name:"FastGeluWithBias",shaderCache:{hint:`${o}`,inputDependencies:["type","type"]},getShaderSource:a,getRunData:i=>({outputs:[{dims:i[0].dims,dataType:i[0].dataType}],programUniforms:[{type:12,data:Math.ceil(s/4)},{type:12,data:n}],dispatchGroup:{x:Math.ceil(s/or/4)}})}},Gu=e=>{e.inputs.length<2||ze.size(e.inputs[1].dims)===0?Kl(e):e.compute(Eo(e.inputs))}}),Ku,Gn,Hu,qu,np=g(()=>{zt(),Ot(),rs(),Yt(),Ku=e=>{if(!e||e.length!==2)throw new Error("Gather requires 2 inputs.")},Gn=(e,t)=>{let s=e[0].dims,n=e[1].dims,o=s.length,a=ze.normalizeAxis(t.axis,o),i=s.slice(0);i.splice(a,1,...n);let u=s[a],p=e[0].dataType===9?4:1,h=Math.ceil(ze.size(i)/p),k=[{type:12,data:h},{type:6,data:u},{type:12,data:a},...yt(e[0].dims,e[1].dims,i)],C=d=>{let z=qe("data",e[0].dataType,e[0].dims.length,p),B=qe("inputIndices",e[1].dataType,e[1].dims.length),V=It("output",e[0].dataType,i.length,p),Z=X=>{let he=n.length,pe=`var indicesIndices${X} = ${B.type.indices}(0);`;for(let Me=0;Me1?`indicesIndices${X}[${Me}]`:`indicesIndices${X}`} = ${i.length>1?`outputIndices${X}[uniforms.axis + ${Me}]`:`outputIndices${X}`};`;pe+=` - var idx${X} = ${B.getByIndices(`indicesIndices${X}`)}; - if (idx${X} < 0) { - idx${X} = idx${X} + uniforms.axisDimLimit; - } - var dataIndices${X} : ${z.type.indices}; - `;for(let Me=0,Oe=0;Me1?`dataIndices${X}[${Me}]`:`dataIndices${X}`} = u32(idx${X});`,Oe+=he):(pe+=`${o>1?`dataIndices${X}[${Me}]`:`dataIndices${X}`} = ${i.length>1?`outputIndices${X}[${Oe}]`:`outputIndices${X}`};`,Oe++);return pe},ee;if(e[0].dataType===9){let X=(he,pe,Me="")=>` - let outputIndices${pe} = ${V.offsetToIndices(`outputOffset + ${pe}u`)}; - ${Z(pe)}; - let offset${pe} = ${z.indicesToOffset(`dataIndices${pe}`)}; - let index${pe} = offset${pe} / 4u; - let component${pe} = offset${pe} % 4u; - ${he}[${pe}] = ${Me}(${z.getByOffset(`index${pe}`)}[component${pe}]); - `;ee=` - let outputOffset = global_idx * ${p}; - var value = vec4(0); - ${X("value",0,"u32")} - ${X("value",1,"u32")} - ${X("value",2,"u32")} - ${X("value",3,"u32")} - ${V.setByOffset("global_idx","value")} - `}else ee=` - let outputIndices = ${V.offsetToIndices("global_idx")}; - ${Z("")}; - let value = ${z.getByIndices("dataIndices")}; - ${V.setByOffset("global_idx","value")}; - `;return` - ${d.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(z,B,V)} - ${d.mainStart()} - ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} - ${ee} - }`};return{name:"Gather",shaderCache:{hint:t.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:i,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:k}),getShaderSource:C}},Hu=e=>Bt({axis:e.axis}),qu=(e,t)=>{let s=e.inputs;Ku(s),e.compute(Gn(e.inputs,t))}}),Qu,Co,Xu,op=g(()=>{zt(),Ot(),Yt(),Qu=(e,t,s,n,o,a,i,u,p)=>{let h=[{type:12,data:a},{type:12,data:n},{type:12,data:o},{type:12,data:s},{type:12,data:i},{type:12,data:u},{type:12,data:p}],k=[a];h.push(...yt(t.dims,k));let C=d=>{let z=qe("indices_data",t.dataType,t.dims.length),B=It("input_slice_offsets_data",12,1,1),V=[z,B],Z=[{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:s.length},{name:"num_slices_per_batch",type:"u32"},{name:"input_batch_stride",type:"u32"},{name:"num_slice_dims",type:"u32"}];return` - ${d.registerUniforms(Z).declareVariables(...V)} - ${d.mainStart()} - ${d.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]);"} - } - ${s.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}_${s.length}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:k,dataType:e.inputs[1].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:h}),getShaderSource:C},{inputs:[t],outputs:[-1]})[0]},Co=(e,t)=>{let s=e.inputs,n=s[0].dims,o=s[0].dataType,a=s[1].dims,i=a[a.length-1],u=ze.sizeToDimension(a,a.length-1),p=ze.sizeFromDimension(n,t.batchDims+i),h=ze.sizeToDimension(n,t.batchDims),k=ze.sizeFromDimension(n,t.batchDims),C=u/h,d=new Array(i),z=p;for(let pe=0;pen.length)throw new Error("last dimension of indices must not be larger than rank of input tensor");let Z=a.slice(0,-1).concat(n.slice(V)),ee=ze.size(Z),X=[{type:12,data:ee},{type:12,data:p},...yt(s[0].dims,B.dims,Z)],he=pe=>{let Me=qe("data",s[0].dataType,s[0].dims.length),Oe=qe("slice_offsets",12,B.dims.length),Le=It("output",s[0].dataType,Z.length);return` - ${pe.registerUniform("output_size","u32").registerUniform("slice_size","u32").declareVariables(Me,Oe,Le)} - ${pe.mainStart()} - ${pe.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:t.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:Z,dataType:o}],dispatchGroup:{x:Math.ceil(ee/64)},programUniforms:X}),getShaderSource:he},{inputs:[s[0],B]})},Xu=e=>({batchDims:e.batch_dims,cacheKey:""})}),Yu,ip,Ju,Zu,ap=g(()=>{zt(),Ot(),rs(),Yt(),Yu=(e,t)=>{if(e.length<3||e.length>4)throw new Error("GatherBlockQuantized requires 3 or 4 inputs.");let s=ze.normalizeAxis(t.quantizeAxis,e[0].dims.length),n=t.blockSize,o=e[0],a=e[2],i=e.length===4?e[3]:void 0;if(a.dims.length!==o.dims.length||!o.dims.map((u,p)=>p===s?Math.ceil(u/n)===a.dims[p]:u===a.dims[p]).reduce((u,p)=>u&&p,!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!==a.dims.length||!i.dims.map((u,p)=>u===a.dims[p]).reduce((u,p)=>u&&p,!0))throw new Error("Zero point must have the same rank as the input tensor and the dims should match except on quantizeAxis.")}},ip=(e,t)=>{let s=e[0].dims,n=e[1].dims,o=s.length,a=ze.normalizeAxis(t.gatherAxis,o),i=ze.normalizeAxis(t.quantizeAxis,o),u=s.slice(0);u.splice(a,1,...n);let p=ze.size(u),h=e[2].dataType,k=e[0].dataType===22,C=[{type:12,data:p},{type:12,data:i},{type:12,data:a},{type:12,data:t.blockSize},...yt(...e.map((z,B)=>z.dims),u)],d=z=>{let B=qe("data",e[0].dataType,e[0].dims.length),V=qe("inputIndices",e[1].dataType,e[1].dims.length),Z=qe("scales",e[2].dataType,e[2].dims.length),ee=e.length>3?qe("zeroPoint",e[3].dataType,e[3].dims.length):void 0,X=It("output",h,u.length),he=[B,V,Z];ee&&he.push(ee);let pe=[{name:"output_size",type:"u32"},{name:"quantize_axis",type:"u32"},{name:"gather_axis",type:"u32"},{name:"block_size",type:"u32"}];return` - ${z.registerUniforms(pe).declareVariables(...he,X)} - ${z.mainStart()} - let output_indices = ${X.offsetToIndices("global_idx")}; - var indices_indices = ${V.type.indices}(0); - ${n.length>1?` - for (var i: u32 = 0; i < ${n.length}; i++) { - let index = ${X.indicesGet("output_indices","uniforms.gather_axis + i")}; - ${V.indicesSet("indices_indices","i","index")}; - }`:`indices_indices = ${X.indicesGet("output_indices","uniforms.gather_axis")};`}; - var data_indices = ${B.type.indices}(0); - for (var i: u32 = 0; i < uniforms.gather_axis; i++) { - let index = ${X.indicesGet("output_indices","i")}; - ${B.indicesSet("data_indices","i","index")}; - } - var index_from_indices = ${V.getByIndices("indices_indices")}; - if (index_from_indices < 0) { - index_from_indices += ${s[a]}; - } - ${B.indicesSet("data_indices","uniforms.gather_axis","u32(index_from_indices)")}; - for (var i = uniforms.gather_axis + 1; i < ${u.length}; i++) { - let index = ${X.indicesGet("output_indices",`i + ${n.length} - 1`)}; - ${B.indicesSet("data_indices","i","index")}; - } - let data_offset = ${B.indicesToOffset("data_indices")}; - let data_index = data_offset % 8; - // Convert 4-bit packed data to 8-bit packed data. - let packed_4bit_quantized_data = ${B.getByOffset("data_offset / 8")}; - let packed_8bit_quantized_data = (packed_4bit_quantized_data >> (4 * (data_index % 2))) & 0x0f0f0f0f; - let quantized_data_vec = ${k?"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 = ${Z.indicesGet("data_indices","uniforms.quantize_axis")} / uniforms.block_size; - ${Z.indicesSet("scale_indices","uniforms.quantize_axis","quantize_axis_index")}; - var scale = ${Z.getByIndices("scale_indices")}; - ${ee?` - let zero_point_indices = scale_indices; - let zero_point_offset = ${ee.indicesToOffset("zero_point_indices")}; - let zero_point_index = zero_point_offset % 8; - let packed_4bit_zero_points = ${ee.getByOffset("zero_point_offset / 8")}; - let packed_8bit_zero_points = (packed_4bit_zero_points >> (4 * (zero_point_index % 2))) & 0x0f0f0f0f; - let zero_point_vec = ${k?"unpack4xI8":"unpack4xU8"}(u32(packed_8bit_zero_points)); - let zero_point = zero_point_vec[zero_point_index / 2];`:"var zero_point = 0"}; - let dequantized_data = ${Ss(h)}(quantized_data - zero_point) * scale; - ${X.setByOffset("global_idx","dequantized_data")}; - }`};return{name:"GatherBlockQuantized",shaderCache:{hint:`${t.cacheKey};${e.filter((z,B)=>B!==1).map(z=>z.dims.join("_")).join(";")}`,inputDependencies:Array.from({length:e.length},(z,B)=>"rank")},getRunData:()=>({outputs:[{dims:u,dataType:h}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:C}),getShaderSource:d}},Ju=(e,t)=>{let s=e.inputs;Yu(s,t),e.compute(ip(e.inputs,t))},Zu=e=>Bt({blockSize:e.blockSize,gatherAxis:e.gatherAxis,quantizeAxis:e.quantizeAxis})}),Pn,ed,td,sd,lp=g(()=>{zt(),Ot(),rs(),Yt(),Pn=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.`)},ed=(e,t)=>{let s=e[0].dims,n=e[0].dataType,o=s.length,a=e[1].dims,i=e[1].dataType,u=ze.normalizeAxis(t.axis,o),p=s[u],h=a.slice(0),k=ze.size(h),C=qe("input",n,o),d=qe("indicesInput",i,a.length),z=It("output",n,h.length),B=[{type:12,data:k},{type:6,data:p},{type:12,data:u}];return B.push(...yt(s,a,h)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:h,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(k/64)},programUniforms:B}),getShaderSource:V=>` - ${V.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(C,d,z)} - ${V.mainStart()} - ${V.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} - - let outputIndices = ${z.offsetToIndices("global_idx")}; - - var idx = ${d.getByOffset("global_idx")}; - if (idx < 0) { - idx = idx + uniforms.axisDimLimit; - } - var inputIndices = ${C.type.indices}(outputIndices); - ${C.indicesSet("inputIndices","uniforms.axis","u32(idx)")}; - let value = ${C.getByIndices("inputIndices")}; - - ${z.setByOffset("global_idx","value")}; - }`}},td=e=>Bt({axis:e.axis}),sd=(e,t)=>{let s=e.inputs;Pn(s),e.compute(ed(e.inputs,t))}}),rd,nd,od,ko,Kp=g(()=>{zt(),Ot(),Yt(),rd=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")},nd=(e,t)=>{let s=e[0].dims.slice(),n=e[1].dims.slice(),[o,a,i]=Fr.getShapeOfGemmResult(s,t.transA,n,t.transB,e.length===3?e[2].dims:void 0),u=[o,a];if(!u)throw new Error("Can't use gemm on the given tensors");let p=16,h=Math.ceil(a/p),k=Math.ceil(o/p),C=!0,d=ze.size(u),z=[{type:12,data:C?h:d},{type:12,data:o},{type:12,data:a},{type:12,data:i},{type:1,data:t.alpha},{type:1,data:t.beta}],B=["type","type"];e.length===3&&(z.push(...yt(e[2].dims)),B.push("rank")),z.push(...yt(u));let V=ee=>{let X="";t.transA&&t.transB?X="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":t.transA&&!t.transB?X="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!t.transA&&t.transB?X="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!t.transA&&!t.transB&&(X="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let he=t.alpha===1?"":"value *= uniforms.alpha;",pe=qe("a",e[0].dataType,e[0].dims),Me=qe("b",e[1].dataType,e[1].dims),Oe=pe.type.value,Le=null,Ye=[pe,Me];e.length===3&&(Le=qe("c",e[2].dataType,e[2].dims.length),Ye.push(Le));let at=It("output",e[0].dataType,u.length);Ye.push(at);let Pt=[{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` - ${ee.registerUniforms(Pt).declareVariables(...Ye)} - - ${ee.mainStart()} - ${ee.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - - let m = global_idx / uniforms.N; - let n = global_idx % uniforms.N; - - var value = ${Oe}(0); - for (var k: u32 = 0u; k < uniforms.K; k++) { - ${X} - } - - ${he} - ${Le!=null?`let cOffset = ${Le.broadcastedIndicesToOffset("vec2(m, n)",at)}; value += ${Oe}(uniforms.beta) * ${Le.getByOffset("cOffset")};`:""} - output[global_idx] = value; - }`},Z=ee=>{let X=qe("a",e[0].dataType,e[0].dims),he=qe("b",e[1].dataType,e[1].dims),pe=null,Me=[X,he];e.length===3&&(pe=qe("c",e[2].dataType,e[2].dims.length),Me.push(pe));let Oe=It("output",e[0].dataType,u.length);Me.push(Oe);let Le=[{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"}],Ye="",at="";t.transA&&t.transB?(at=` - 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] = ${X.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] = ${he.type.value}(0); - } - `,Ye="value += tile_a[k][local_id.y] * tile_b[local_id.x][k];"):t.transA&&!t.transB?(at=` - 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] = ${X.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] = ${he.type.value}(0); - } - `,Ye="value += tile_a[k][local_id.y] * tile_b[k][local_id.x];"):!t.transA&&t.transB?(at=` - 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] = ${X.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] = ${he.type.value}(0); - } - `,Ye="value += tile_a[local_id.y][k] * tile_b[local_id.x][k];"):!t.transA&&!t.transB&&(at=` - 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] = ${X.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] = ${he.type.value}(0); - } - `,Ye="value += tile_a[local_id.y][k] * tile_b[k][local_id.x];");let Pt=t.alpha===1?"":"value *= uniforms.alpha;";return` - ${ee.registerUniforms(Le).declareVariables(...Me)} - var tile_a: array, ${p}>; - var tile_b: array, ${p}>; - ${ee.mainStart([p,p,1])} - let tile_col_start = (workgroup_index % uniforms.num_tile_n) * ${p}; - let tile_row_start = (workgroup_index / uniforms.num_tile_n) * ${p}; - let num_tiles = (uniforms.K - 1) / ${p} + 1; - var k_start = 0u; - var value = ${Oe.type.value}(0); - for (var t: u32 = 0u; t < num_tiles; t++) { - ${at} - k_start = k_start + ${p}; - workgroupBarrier(); - - for (var k: u32 = 0u; k < ${p}; k++) { - ${Ye} - } - workgroupBarrier(); - } - - ${Pt} - let m = tile_row_start + local_id.y; - let n = tile_col_start + local_id.x; - ${pe!=null?`let cOffset = ${pe.broadcastedIndicesToOffset("vec2(m, n)",Oe)}; value += ${Oe.type.value}(uniforms.beta) * ${pe.getByOffset("cOffset")};`:""} - if (m < uniforms.M && n < uniforms.N) { - output[m * uniforms.N + n] = value; - } - }`};return C?{name:"GemmShared",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:B},getRunData:()=>({outputs:[{dims:u,dataType:e[0].dataType}],dispatchGroup:{x:h*k},programUniforms:z}),getShaderSource:Z}:{name:"Gemm",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:B},getRunData:()=>({outputs:[{dims:u,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:z}),getShaderSource:V}},od=e=>{let t=e.transA,s=e.transB,n=e.alpha,o=e.beta;return{transA:t,transB:s,alpha:n,beta:o,cacheKey:`${e.transA};${e.transB};${e.alpha===1}`}},ko=(e,t)=>{rd(e.inputs),e.compute(nd(e.inputs,t))}}),Cr,Lr,ln,un,id,oa,ad,ld,ia,ud,dd,aa,cd,pd,la=g(()=>{zt(),Ot(),rs(),Yt(),[Cr,Lr,ln,un]=[0,1,2,3],id=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")},oa=` - 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; - } -`,ad=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; - } -`,ld=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)); - `} - } -`,ia=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); - }`:""} -`,ud=(e,t,s)=>` - fn pixel_at_grid(r: i32, c: i32, H: i32, W: i32, batch: u32, channel: u32, border: vec4) -> ${t} { - var pixel = ${t}(0); - var indices = vec4(0); - indices[${Cr}] = batch; - indices[${Lr}] = channel;`+(()=>{switch(s.paddingMode){case"zeros":return` - if (r >= 0 && r < H && c >=0 && c < W) { - indices[${ln}] = u32(r); - indices[${un}] = u32(c); - } - `;case"border":return` - indices[${ln}] = u32(clamp(r, 0, H - 1)); - indices[${un}] = u32(clamp(c, 0, W - 1)); - `;case"reflection":return` - indices[${ln}] = gs_reflect(r, border[1], border[3]); - indices[${un}] = gs_reflect(c, border[0], border[2]); - `;default:throw new Error(`padding mode ${s.paddingMode} is not supported`)}})()+` - return ${e.getByIndices("indices")}; - } -`,dd=(e,t,s)=>(()=>{switch(s.mode){case"nearest":return` - let result = pixel_at_grid(i32(round(y)), i32(round(x)), H_in, W_in, indices[${Cr}], indices[${Lr}], 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[${Cr}], indices[${Lr}], border); - let p12 = pixel_at_grid(y1, x2, H_in, W_in, indices[${Cr}], indices[${Lr}], border); - let p21 = pixel_at_grid(y2, x1, H_in, W_in, indices[${Cr}], indices[${Lr}], border); - let p22 = pixel_at_grid(y2, x2, H_in, W_in, indices[${Cr}], indices[${Lr}], border); - - let dx2 = ${t}(f32(x2) - x); - let dx1 = ${t}(x - f32(x1)); - let dy2 = ${t}(f32(y2) - y); - let dy1 = ${t}(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<${t}>; - 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[${Cr}], indices[${Lr}], 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 ${s.mode} is not supported`)}})()+`${e.setByOffset("global_idx","result")}`,aa=(e,t)=>{let s=qe("x",e[0].dataType,e[0].dims.length),n=[e[1].dims[0],e[1].dims[1],e[1].dims[2]],o=qe("grid",e[1].dataType,n.length,2),a=[e[0].dims[0],e[0].dims[1],e[1].dims[1],e[1].dims[2]];t.format==="NHWC"&&(a=[e[0].dims[0],e[1].dims[1],e[1].dims[2],e[0].dims[3]],[Cr,Lr,ln,un]=[0,3,1,2]);let i=It("output",e[0].dataType,a.length),u=s.type.value,p=ze.size(a),h=[{type:12,data:p},...yt(e[0].dims,n,a)],k=C=>` - ${C.registerUniform("output_size","u32").declareVariables(s,o,i)} - ${oa} - ${ad(u)} - ${ld(t)} - ${ia(t)} - ${ud(s,u,t)} - - ${C.mainStart()} - ${C.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - let H_in = i32(uniforms.x_shape[${ln}]); - let W_in = i32(uniforms.x_shape[${un}]); - - ${t.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[${Cr}], indices[${ln}], indices[${un}]); - let nxy = ${o.getByIndices("grid_indices")}; - var x = gs_denormalize(f32(nxy[0]), W_in); - var y = gs_denormalize(f32(nxy[1]), H_in); - - ${dd(i,u,t)} - }`;return{name:"GridSample",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:["type","type"]},getRunData:C=>{let d=ze.size(a);return{outputs:[{dims:a,dataType:C[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:h}},getShaderSource:k}},cd=(e,t)=>{id(e.inputs),e.compute(aa(e.inputs,t))},pd=e=>Bt({alignCorners:e.align_corners,mode:e.mode,paddingMode:e.padding_mode,format:e.format})}),nr,hd,md,ua,da,dn,up,_d=g(()=>{zt(),Ot(),rs(),ue(),ui(),Yt(),Kr(),nr=(e,t)=>e.length>t&&e[t].dims.length>0?e[t]:void 0,hd=(e,t)=>{let s=e[0],n=nr(e,1),o=nr(e,2),a=nr(e,3),i=nr(e,4),u=nr(e,5),p=nr(e,6),h=nr(e,7);if(s.dims.length!==3&&s.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let k=s.dims[0],C=s.dims[1],d=s.dims.length===3?s.dims[2]:t.numHeads*s.dims[4],z=C,B=0,V=0,Z=Math.floor(d/t.numHeads);if(p&&h&&ze.size(p.dims)&&ze.size(h.dims)){if(p.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(p.dims[0]!==k||p.dims[1]!==t.numHeads||p.dims[3]!==Z)throw new Error('Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)');if(h.dims[0]!==k||h.dims[1]!==t.numHeads||h.dims[3]!==Z)throw new Error('Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)');if(p.dims[2]!==h.dims[2])throw new Error('Input "past_key" and "past_value" shall have same dim 2 (past_sequence_length)');if(h.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');B=p.dims[2],V=p.dims[2]}else if(p&&ze.size(p.dims)||h&&ze.size(h.dims))throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let ee;if(n&&ze.size(n.dims)>0){if(s.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(s.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]!==s.dims[2])throw new Error('Input "query" and "key" shall have same dim 2 (hidden_size)');ee=2,z=n.dims[1]}else if(n.dims.length===5){if(n.dims[2]!==t.numHeads||n.dims[3]!==2||n.dims[4]!==Z)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.');ee=5,z=n.dims[1]}else{if(n.dims[1]!==t.numHeads||n.dims[3]!==Z)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');ee=0,z=n.dims[2]}}else{if(s.dims.length!==5)throw new Error('Input "query" is expected to have 5 dimensions when key is empty');if(s.dims[2]!==t.numHeads||s.dims[3]!==3)throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');ee=3}if(a&&ze.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 X=B+z,he=0;if(i&&ze.size(i.dims)>0){he=8;let Le=i.dims;throw Le.length===1?Le[0]===k?he=1:Le[0]===3*k+2&&(he=3):Le.length===2&&Le[0]===k&&Le[1]===X&&(he=5),he===8?new Error('Input "key_padding_mask" shape shall be (batch_size) or (batch_size, total_sequence_length)'):new Error("Mask not supported")}let pe=!1,Me=d;if(o&&ze.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(s.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(z!==o.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');Me=o.dims[2]}else{if(z!==o.dims[2])throw new Error('Input "key" and "value" shall have the same dim 2 (kv_sequence_length)');Me=o.dims[1]*o.dims[3],pe=!0}}let Oe=!1;if(i&&ze.size(i.dims)>0)throw new Error("Key padding mask is not supported");if(u&&ze.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]!==k||u.dims[1]!==t.numHeads||u.dims[2]!==C||u.dims[3]!==X)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:k,sequenceLength:C,pastSequenceLength:B,kvSequenceLength:z,totalSequenceLength:X,maxSequenceLength:V,inputHiddenSize:0,hiddenSize:d,vHiddenSize:Me,headSize:Z,vHeadSize:Math.floor(Me/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:he,scale:t.scale,broadcastResPosBias:Oe,passPastInKv:pe,qkvFormat:ee}},md=e=>Bt({...e}),ua=Bt({perm:[0,2,1,3]}),da=(e,t,s,n,o,a,i)=>{let u=[n,o,a],p=ze.size(u),h=[{type:12,data:p},{type:12,data:i},{type:12,data:a}],k=C=>{let d=It("qkv_with_bias",t.dataType,u),z=qe("qkv",t.dataType,u),B=qe("bias",s.dataType,u),V=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return` - ${C.registerUniforms(V).declareVariables(z,B,d)} - ${C.mainStart()} - ${C.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(p/64)},programUniforms:h}),getShaderSource:k},{inputs:[t,s],outputs:[-1]})[0]},dn=(e,t,s,n,o,a,i,u)=>{let p=a;if(i&&ze.size(i.dims)>0){if(n===1)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return p=da(e,a,i,t,n,s*o,u),p=p.reshape([t,n,s,o]),s===1||n===1?p:e.compute(pr(p,ua.perm),{inputs:[p],outputs:[-1]})[0]}else return a.dims.length===3&&(p=a.reshape([t,n,s,o])),s===1||n===1?p:e.compute(pr(p,ua.perm),{inputs:[p],outputs:[-1]})[0]},up=(e,t)=>{let s=hd(e.inputs,t),n=e.inputs[0],o=nr(e.inputs,1),a=nr(e.inputs,2),i=nr(e.inputs,3),u=nr(e.inputs,4),p=nr(e.inputs,5),h=nr(e.inputs,6),k=nr(e.inputs,7);if(n.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 C=o&&a&&o.dims.length===4&&a.dims.length===4,d=dn(e,s.batchSize,s.numHeads,s.sequenceLength,s.headSize,n,i,0);if(C)return Nn(e,d,o,a,u,void 0,h,k,p,s);if(!o||!a)throw new Error("key and value must be provided");let z=dn(e,s.batchSize,s.numHeads,s.kvSequenceLength,s.headSize,o,i,s.hiddenSize),B=dn(e,s.batchSize,s.numHeads,s.kvSequenceLength,s.vHeadSize,a,i,2*s.hiddenSize);Nn(e,d,z,B,u,void 0,h,k,p,s)}}),fd,ca,gd,wd,So,yd,Md,pa=g(()=>{zt(),Ot(),rs(),Yt(),fd=e=>{if(!e||e.length<1)throw new Error("too few inputs")},ca=(e,t)=>{let s=[],n=t.numOutputs;return e[1].dims[0]>0&&(e[1].getBigInt64Array().forEach(o=>s.push(Number(o))),n=s.length),Bt({numOutputs:n,axis:t.axis,splitSizes:s})},gd=e=>` -fn calculateOutputIndex(index: u32) -> u32 { - for (var i: u32 = 0u; i < ${e}u; i += 1u ) { - if (index < ${$t("uniforms.size_in_split_axis","i",e)}) { - return i; - } - } - return ${e}u; -}`,wd=e=>{let t=e.length,s=[];for(let n=0;n{let s=e[0].dims,n=ze.size(s),o=e[0].dataType,a=ze.normalizeAxis(t.axis,s.length),i=new Array(t.numOutputs),u=qe("input",o,s.length),p=new Array(t.numOutputs),h=[],k=[],C=0,d=[{type:12,data:n}];for(let B=0;B` - ${B.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",p.length).declareVariables(u,...i)} - ${gd(p.length)} - ${wd(i)} - - ${B.mainStart()} - ${B.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 -= ${$t("uniforms.size_in_split_axis","output_number - 1u",p.length)}; - ${u.indicesSet("indices",a,"index")}; - } - writeBufferData(output_number, indices, global_idx); - }`;return{name:"Split",shaderCache:{hint:t.cacheKey,inputDependencies:["rank"]},getShaderSource:z,getRunData:()=>({outputs:h,dispatchGroup:{x:Math.ceil(n/64)},programUniforms:d})}},yd=(e,t)=>{fd(e.inputs);let s=e.inputs.length===1?t:ca(e.inputs,t);e.compute(So(e.inputs,s),{inputs:[0]})},Md=e=>{let t=e.axis,s=e.splitSizes,n=e.numOutputs<0?s.length:e.numOutputs;if(n!==s.length)throw new Error("numOutputs and splitSizes lengh must be equal");return Bt({axis:t,numOutputs:n,splitSizes:s})}}),dp,cp,$o,ha,pp=g(()=>{rs(),ui(),_d(),pa(),Kr(),dp=(e,t)=>{if(t.doRotary)throw new Error("GroupQuerryAttention do_rotary attribute is not supported");if(t.doRotary&&e.length<=7)throw new Error("cos_cache and sin_cache inputs are required if do_rotary is specified");let s=e[0],n=e[1],o=e[2],a=e[3],i=e[4];if(t.localWindowSize!==-1)throw new Error("Local attention is not supported");if(t.softcap!==0)throw new Error("Softcap is not supported");if(t.rotaryInterleaved!==0)throw new Error("Rotary interleaved is not supported");if(t.smoothSoftmax)throw new Error("Smooth softmax is not supported");if(s.dims.length!==3&&s.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let u=!1,p=s.dims[0],h=s.dims[1],k=s.dims.length===3?u?s.dims[2]/3:s.dims[2]:t.numHeads*s.dims[4],C=h,d=0,z=!n||n.dims.length===0,B=Math.floor(z?k/(t.numHeads+2*t.kvNumHeads):k/t.numHeads);z&&(k=B*t.numHeads);let V=a&&a.dims.length!==0,Z=i&&i.dims.length!==0;if(V&&a.dims.length===4&&a.dims[0]===p&&a.dims[1]!==t.kvNumHeads&&a.dims[2]===t.kvNumHeads&&a.dims[3]===B)throw new Error("BSNH pastKey/pastValue is not supported");if(V&&Z){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');d=a.dims[2]}else if(V||Z)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let ee=1;if(n&&n.dims.length>0){if(s.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(s.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(s.dims[2]%n.dims[2]!==0)throw new Error('Dimension 2 of "query" should be a multiple of "key"');C=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(o)throw new Error('Expect "value" be none when "key" has packed kv format.');C=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');C=n.dims[2]}}else{if(s.dims.length!==3&&s.dims.length!==5)throw new Error('Input "query" is expected to have 3 or 5 dimensions when key is empty');if(s.dims.length===5&&(s.dims[2]!==t.numHeads||s.dims[3]!==3))throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');ee=3}let X=0,he=!1,pe=t.kvNumHeads?B*t.kvNumHeads:k;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(s.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(C!==o.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');pe=o.dims[2]}else{if(C!==o.dims[2])throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');pe=o.dims[1]*o.dims[3],he=!0}}let Me=e.length>4?e[5]:void 0;if(Me&&Me.dims.length!==1&&Me.dims[0]!==p)throw new Error('Input "seqlens" is expected to have 1 dimension and the same dim 0 as batch_size');return{batchSize:p,sequenceLength:h,pastSequenceLength:d,kvSequenceLength:C,totalSequenceLength:-1,maxSequenceLength:-1,inputHiddenSize:0,hiddenSize:k,vHiddenSize:pe,headSize:B,vHeadSize:Math.floor(pe/t.kvNumHeads),numHeads:t.numHeads,kvNumHeads:t.kvNumHeads,nReps:t.numHeads/t.kvNumHeads,pastPresentShareBuffer:!1,maskType:X,scale:t.scale,broadcastResPosBias:!1,passPastInKv:he,qkvFormat:ee}},cp=Bt({perm:[0,2,1,3]}),$o=(e,t,s)=>{let n=t,o=s.kvNumHeads;return t.dims.length===3&&s.kvSequenceLength!==0&&(n=t.reshape([s.batchSize,s.kvSequenceLength,o,s.headSize]),n=e.compute(pr(n,cp.perm),{inputs:[n],outputs:[-1]})[0]),n},ha=(e,t)=>{var Z;let s=dp(e.inputs,t);if(e.inputs[0].dims.length===5)throw new Error("Packed QKV is not implemented");if(((Z=e.inputs[1])==null?void 0:Z.dims.length)===5)throw new Error("Packed KV is not implemented");let n=e.inputs[0],o=e.inputs[1]&&e.inputs[1].dims.length>0?e.inputs[1]:void 0,a=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,u=e.inputs[4]&&e.inputs[4].dims.length!==0?e.inputs[4]:void 0,p=e.inputs.length>4?e.inputs[5]:void 0,h=e.inputs.length>5?e.inputs[6]:void 0,k=s.kvNumHeads?s.kvNumHeads:s.numHeads,C=Bt({axis:2,numOutputs:3,splitSizes:[s.numHeads*s.headSize,k*s.headSize,k*s.headSize]}),[d,z,B]=!o&&!a?e.compute(So([n],C),{inputs:[n],outputs:[-1,-1,-1]}):[n,o,a],V=dn(e,s.batchSize,s.numHeads,s.sequenceLength,s.headSize,d,void 0,0);Nn(e,V,$o(e,z,s),$o(e,B,s),void 0,void 0,i,u,void 0,s,p,h)}}),ma,_a,bd,vd,xd=g(()=>{zt(),Ot(),Kr(),Yt(),ma=(e,t,s,n,o,a,i,u)=>{let p=qt(a),h=p===1?"f32":`vec${p}f`,k=p===1?"vec2f":`mat2x${p}f`,C=o*i,d=64;C===1&&(d=256);let z=[o,i,a/p],B=[o,i,2],V=["rank","type","type"],Z=[];Z.push(...yt(z,B));let ee=X=>{let he=qe("x",t.dataType,3,p),pe=qe("scale",s.dataType,s.dims),Me=qe("bias",n.dataType,n.dims),Oe=It("output",1,3,2),Le=[he,pe,Me,Oe];return` - var workgroup_shared : array<${k}, ${d}>; - const workgroup_size = ${d}u; - ${X.declareVariables(...Le)} - ${X.mainStart(d)} - 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 = ${h}(0); - var squared_sum = ${h}(0); - for (var h = local_idx; h < hight; h += workgroup_size) { - let value = ${h}(${he.get("batch","channel","h")}); - sum += value; - squared_sum += value * value; - } - workgroup_shared[local_idx] = ${k}(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 = ${Gs("workgroup_shared[0][0]",p)} / f32(hight * ${p}); - let squared_sum_final = ${Gs("workgroup_shared[0][1]",p)} / f32(hight * ${p}); - - 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:`${p};${u};${d}`,inputDependencies:V},getRunData:()=>({outputs:[{dims:B,dataType:1}],dispatchGroup:{x:C},programUniforms:Z}),getShaderSource:ee},{inputs:[t,s,n],outputs:[-1]})[0]},_a=(e,t,s)=>{let n=t[0].dims,o=n,a=2,i=n[0],u=n[1],p=ze.sizeFromDimension(n,a),h=qt(p),k=ze.size(o)/h,C=ma(e,t[0],t[1],t[2],i,p,u,s.epsilon),d=[i,u,p/h],z=[i,u],B=["type","none"],V=Z=>{let ee=qe("x",t[0].dataType,d.length,h),X=qe("scale_shift",1,z.length,2),he=It("output",t[0].dataType,d.length,h),pe=[ee,X,he];return` - ${Z.registerUniform("output_size","u32").declareVariables(...pe)} - ${Z.mainStart()} - ${Z.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - let outputIndices = ${he.offsetToIndices("global_idx")}; - let batch = outputIndices[0]; - let channel = outputIndices[1]; - let scale_shift = ${X.getByIndices("vec2(batch, channel)")}; - let value = ${ee.getByOffset("global_idx")} * ${he.type.value}(scale_shift.x) + ${he.type.value}(scale_shift.y); - ${he.setByOffset("global_idx","value")}; - }`};e.compute({name:"InstanceNormalization",shaderCache:{hint:`${h}`,inputDependencies:B},getRunData:()=>({outputs:[{dims:o,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(k/64)},programUniforms:[{type:12,data:k},...yt(d,z,d)]}),getShaderSource:V},{inputs:[t[0],C]})},bd=(e,t,s)=>{let n=t[0].dims,o=n,a=n[0],i=n[n.length-1],u=ze.sizeFromDimension(n,1)/i,p=qt(i),h=ze.size(o)/p,k=[{type:12,data:u},{type:12,data:Math.floor(i/p)}],C=["type","type"],d=!1,z=[0,n.length-1];for(let ee=0;een[z[X]])),V=ma(e,B,t[1],t[2],a,u,i,s.epsilon),Z=ee=>{let X=_s(t[0].dataType),he=p===1?"vec2f":`mat${p}x2f`,pe=Le=>{let Ye=Le===0?"x":"y",at=p===1?"f32":`vec${p}f`;switch(p){case 1:return`${X}(${at}(scale.${Ye}))`;case 2:return`vec2<${X}>(${at}(scale[0].${Ye}, scale[1].${Ye}))`;case 4:return`vec4<${X}>(${at}(scale[0].${Ye}, scale[1].${Ye}, scale[2].${Ye}, scale[3].${Ye}))`;default:throw new Error(`Not supported compoents ${p}`)}},Me=qe("input",t[0].dataType,t[0].dims,p),Oe=It("output",t[0].dataType,o,p);return` - @group(0) @binding(0) var input : array<${Me.type.storage}>; - @group(0) @binding(1) var scale_input : array<${he}>; - @group(0) @binding(2) var output : array<${Oe.type.storage}>; - struct Uniforms {H: u32, C : u32}; - @group(0) @binding(3) var uniforms: Uniforms; - - ${ee.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], ${pe(0)}, ${pe(1)}); - }`};e.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${p}`,inputDependencies:C},getRunData:()=>({outputs:[{dims:o,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:k}),getShaderSource:Z},{inputs:[t[0],V]})},vd=(e,t)=>{t.format==="NHWC"?bd(e,e.inputs,t):_a(e,e.inputs,t)}}),Td,Pd,fa,hp=g(()=>{zt(),Ot(),Yt(),Td=e=>{if(!e||e.length<2)throw new Error("layerNorm requires at least 2 inputs.")},Pd=(e,t,s)=>{let n=t.simplified,o=e[0].dims,a=e[1],i=!n&&e[2],u=o,p=ze.normalizeAxis(t.axis,o.length),h=ze.sizeToDimension(o,p),k=ze.sizeFromDimension(o,p),C=ze.size(a.dims),d=i?ze.size(i.dims):0;if(C!==k||i&&d!==k)throw new Error(`Size of X.shape()[axis:] == ${k}. - Size of scale and bias (if provided) must match this. - Got scale size of ${C} and bias size of ${d}`);let z=[];for(let Me=0;Me1,X=s>2,he=Me=>{let Oe=_s(e[0].dataType),Le=[qe("x",e[0].dataType,e[0].dims,B),qe("scale",a.dataType,a.dims,B)];i&&Le.push(qe("bias",i.dataType,i.dims,B)),Le.push(It("output",e[0].dataType,u,B)),ee&&Le.push(It("mean_data_output",1,z)),X&&Le.push(It("inv_std_output",1,z));let Ye=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return` - ${Me.registerUniforms(Ye).declareVariables(...Le)} - ${Me.mainStart()} - ${Me.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")} - let offset = global_idx * uniforms.norm_size_vectorized; - var mean_vector = ${Ls("f32",B)}; - var mean_square_vector = ${Ls("f32",B)}; - - for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) { - let value = ${$s(Oe,B,"x[h + offset]")}; - mean_vector += value; - mean_square_vector += value * value; - } - let mean = ${Gs("mean_vector",B)} / uniforms.norm_size; - let inv_std_dev = inverseSqrt(${Gs("mean_square_vector",B)} / uniforms.norm_size ${n?"":"- mean * mean"} + uniforms.epsilon); - - for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) { - let f32input = ${$s(Oe,B,"x[j + offset]")}; - let f32scale = ${$s(Oe,B,"scale[j]")}; - output[j + offset] = ${Le[0].type.value}((f32input ${n?"":"- mean"}) * inv_std_dev * f32scale - ${i?`+ ${$s(Oe,B,"bias[j]")}`:""} - ); - } - - ${ee?"mean_data_output[global_idx] = mean":""}; - ${X?"inv_std_output[global_idx] = inv_std_dev":""}; - }`},pe=[{dims:u,dataType:e[0].dataType}];return ee&&pe.push({dims:z,dataType:1}),X&&pe.push({dims:z,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${B};${s};${n}`,inputDependencies:V},getRunData:()=>({outputs:pe,dispatchGroup:{x:Math.ceil(h/64)},programUniforms:Z}),getShaderSource:he}},fa=(e,t)=>{Td(e.inputs),e.compute(Pd(e.inputs,t,e.outputCount))}}),Ed,Cd,mp=g(()=>{Ot(),fo(),ji(),Ed=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.")},Cd=e=>{Ed(e.inputs);let t=Ws.calcShape(e.inputs[0].dims,e.inputs[1].dims,!0);if(!t)throw new Error("Can't use matmul on the given tensors");let s=t[t.length-1],n=e.inputs[0].dims[e.inputs[0].dims.length-1];if(s<8&&n<8)e.compute(zi(e.inputs,{activation:""},t));else{let o=t[t.length-2],a=ze.size(e.inputs[0].dims.slice(0,-2)),i=ze.size(e.inputs[1].dims.slice(0,-2));if(a!==1&&o===1&&i===1){let u=e.inputs[0].reshape([1,a,n]),p=e.inputs[1].reshape([1,n,s]),h=[1,a,s],k=[u,p];e.compute(wo(k,{activation:""},t,h),{inputs:k})}else e.compute(wo(e.inputs,{activation:""},t))}}}),kd,Sd,$d,Ad,Id,Od=g(()=>{zt(),Ot(),rs(),Yt(),kd=(e,t)=>{if(e.length<3||e.length>4)throw new Error("MatMulNBits requires 3 or 4 inputs");let s=e[0],n=s.dims.length;if(s.dims[n-1]!==t.k)throw new Error("The last dim of input shape does not match the k value");let o=Math.floor((t.k+t.blockSize-1)/t.blockSize),a=t.blockSize/8*t.bits,i=e[1];if(!ze.areEqual(i.dims,[t.n,o,a]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let u=e[2].dims;if(ze.size(u)!==t.n*o)throw new Error("scales input size error.");if(e.length===4){let p=e[3].dims,h=t.bits>4?t.n*o:t.n*Math.floor((o+1)/2);if(ze.size(p)!==h)throw new Error("zeroPoints input size error.")}},Sd=(e,t)=>{let s=e[0].dims,n=s.length,o=s[n-2],a=t.k,i=t.n,u=s.slice(0,n-2),p=ze.size(u),h=e[1].dims[2]/4,k=e[0].dataType,C=qt(t.k),d=qt(h),z=qt(i),B=u.concat([o,i]),V=o>1&&i/z%2===0?2:1,Z=ze.size(B)/z/V,ee=64,X=[],he=[p,o,a/C],pe=ze.convertShape(e[1].dims).slice();pe.splice(-1,1,h/d),X.push(...yt(he)),X.push(...yt(pe)),X.push(...yt(e[2].dims)),e.length===4&&X.push(...yt(ze.convertShape(e[3].dims)));let Me=[p,o,i/z];X.push(...yt(Me));let Oe=Le=>{let Ye=he.length,at=qe("a",e[0].dataType,Ye,C),Pt=qe("b",12,pe.length,d),Xt=qe("scales",e[2].dataType,e[2].dims.length),Zt=[at,Pt,Xt],bt=e.length===4?qe("zero_points",12,e[3].dims.length):void 0;bt&&Zt.push(bt);let ss=Me.length,St=It("output",e[0].dataType,ss,z),Ft=_s(e[0].dataType),bs=(()=>{switch(C){case 1:return`array<${Ft}, 8>`;case 2:return`mat4x2<${Ft}>`;case 4:return`mat2x4<${Ft}>`;default:throw new Error(`${C}-component is not supported.`)}})(),Ht=()=>{let it=` - // reuse a data - var input_offset = ${at.indicesToOffset(`${at.type.indices}(batch, row, word_offset)`)}; - var a_data: ${bs}; - for (var j: u32 = 0; j < ${8/C}; j++) { - a_data[j] = ${at.getByOffset("input_offset")}; - input_offset++; - } - `;for(let Et=0;Et> 4) & b_mask); - b_quantized_values = ${bs}(${Array.from({length:4},(ps,Ns)=>`${Ft}(b_value_lower[${Ns}]), ${Ft}(b_value_upper[${Ns}])`).join(", ")}); - b_dequantized_values = ${C===1?`${bs}(${Array.from({length:8},(ps,Ns)=>`(b_quantized_values[${Ns}] - ${bt?`zero_point${Et}`:"zero_point"}) * scale${Et}`).join(", ")});`:`(b_quantized_values - ${bs}(${Array(8).fill(`${bt?`zero_point${Et}`:"zero_point"}`).join(",")})) * scale${Et};`}; - workgroup_shared[local_id.x * ${V} + ${Math.floor(Et/z)}]${z>1?`[${Et%z}]`:""} += ${Array.from({length:8/C},(ps,Ns)=>`${C===1?`a_data[${Ns}] * b_dequantized_values[${Ns}]`:`dot(a_data[${Ns}], b_dequantized_values[${Ns}])`}`).join(" + ")}; - `;return it},Rt=()=>{let it=` - var col_index = col * ${z}; - ${bt?` - 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 = ${Ft}(8);`} - `;for(let Et=0;Et> 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 = ${bt.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; - let zero_point${Et} = ${Ft}((zero_point_word) & 0xFu);`:""} - col_index += 1;`;return it},fs=()=>{let it=`col_index = col * ${z};`;for(let Et=0;Et; - var b_value_upper: vec4; - var b_quantized_values: ${bs}; - var b_dequantized_values: ${bs};`,it};return` - var workgroup_shared: array<${St.type.value}, ${V*ee}>; - ${Le.declareVariables(...Zt,St)} - ${Le.mainStart([ee,1,1])} - let output_indices = ${St.offsetToIndices(`(global_idx / ${ee}) * ${V}`)}; - 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 += ${ee}) { - //process one block - var word_offset: u32 = block * ${t.blockSize/C}; - ${Rt()} - for (var word: u32 = 0; word < ${h}; word += ${d}) { - ${fs()} - for (var i: u32 = 0; i < ${d}; i++) { - ${Ht()} - word_offset += ${8/C}; - } - } - } - workgroupBarrier(); - - if (local_id.x < ${V}) { - var output_value: ${St.type.value} = ${St.type.value}(0); - var workgroup_shared_offset: u32 = local_id.x; - for (var b: u32 = 0u; b < ${ee}u; b++) { - output_value += workgroup_shared[workgroup_shared_offset]; - workgroup_shared_offset += ${V}; - } - ${St.setByIndices(`${St.type.indices}(batch, row, col + local_id.x)`,"output_value")}; - } - }`};return{name:"MatMulNBits",shaderCache:{hint:`${t.blockSize};${t.bits};${C};${d};${z};${V};${ee}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:B,dataType:k}],dispatchGroup:{x:Z},programUniforms:X}),getShaderSource:Oe}},$d=(e,t)=>{let s=e[0].dims,n=s.length,o=s[n-2],a=t.k,i=t.n,u=s.slice(0,n-2),p=ze.size(u),h=e[1].dims[2]/4,k=e[0].dataType,C=qt(t.k),d=qt(h),z=u.concat([o,i]),B=128,V=i%8===0?8:i%4===0?4:1,Z=B/V,ee=Z*d*8,X=ee/C,he=ee/t.blockSize,pe=ze.size(z)/V,Me=[],Oe=[p,o,a/C],Le=ze.convertShape(e[1].dims).slice();Le.splice(-1,1,h/d),Me.push(...yt(Oe)),Me.push(...yt(Le)),Me.push(...yt(e[2].dims)),e.length===4&&Me.push(...yt(ze.convertShape(e[3].dims)));let Ye=[p,o,i];Me.push(...yt(Ye));let at=Pt=>{let Xt=Oe.length,Zt=qe("a",e[0].dataType,Xt,C),bt=qe("b",12,Le.length,d),ss=qe("scales",e[2].dataType,e[2].dims.length),St=[Zt,bt,ss],Ft=e.length===4?qe("zero_points",12,e[3].dims.length):void 0;Ft&&St.push(Ft);let bs=Ye.length,Ht=It("output",e[0].dataType,bs),Rt=_s(e[0].dataType),fs=()=>{switch(C){case 1:return` - let a_data0 = vec4<${Rt}>(sub_a[word_offset], sub_a[word_offset + 1], sub_a[word_offset + 2], sub_a[word_offset + 3]); - let a_data1 = vec4<${Rt}>(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<${Rt}>(sub_a[word_offset], sub_a[word_offset + 1]); - let a_data1 = vec4<${Rt}>(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(`${C}-component is not supported.`)}};return` - var sub_a: array<${Zt.type.value}, ${X}>; - var inter_results: array, ${V}>; - ${Pt.declareVariables(...St,Ht)} - ${Pt.mainStart([Z,V,1])} - let output_indices = ${Ht.offsetToIndices(`workgroup_index * ${V}`)}; - 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) / ${he} + 1; - - // Loop over shared dimension. - for (var tile: u32 = 0; tile < num_tiles; tile += 1) { - let a_col_start = tile * ${X}; - // load one tile A data into shared memory. - for (var a_offset = local_idx; a_offset < ${X}; a_offset += ${B}) - { - let a_col = a_col_start + a_offset; - if (a_col < uniforms.a_shape[2]) - { - sub_a[a_offset] = ${Zt.getByIndices(`${Zt.type.indices}(batch, row, a_col)`)}; - } else { - sub_a[a_offset] = ${Zt.type.value}(0); - } - } - workgroupBarrier(); - - // each thread process one block - let b_row = col + local_id.y; - let block = tile * ${he} + local_id.x; - ${Ft?` - 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 = ${Ft.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; - let zero_point = ${Rt}((zero_point_word) & 0xFu);`:` - // The default zero point is 8 for unsigned 4-bit quantization. - let zero_point = ${Rt}(8);`} - let scale = ${ss.getByOffset("b_row * n_blocks_per_col + block")}; - let b_data = ${bt.getByIndices(`${bt.type.indices}(b_row, block, 0)`)}; - var word_offset = local_id.x * ${t.blockSize/C}; - for (var i: u32 = 0; i < ${d}; i++) { - ${fs()} - let b_value = ${d===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<${Rt}>(${Array.from({length:4},(it,Et)=>`${Rt}(b_value_lower[${Et}]), ${Rt}(b_value_upper[${Et}])`).join(", ")}); - let b_dequantized_values = (b_quantized_values - mat2x4<${Rt}>(${Array(8).fill("zero_point").join(",")})) * scale; - inter_results[local_id.y][local_id.x] += ${Array.from({length:2},(it,Et)=>`${`dot(a_data${Et}, b_dequantized_values[${Et}])`}`).join(" + ")}; - word_offset += ${8/C}; - } - workgroupBarrier(); - } - - if (local_idx < ${V}) { - var output_value: ${Ht.type.value} = ${Ht.type.value}(0); - for (var b = 0u; b < ${Z}; b++) { - output_value += inter_results[local_idx][b]; - } - if (col + local_idx < uniforms.output_shape[2]) - { - ${Ht.setByIndices(`${Ht.type.indices}(batch, row, col + local_idx)`,"output_value")} - } - } - }`};return{name:"BlockwiseMatMulNBits32",shaderCache:{hint:`${t.blockSize};${C};${d};${Z};${V}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:z,dataType:k}],dispatchGroup:{x:pe},programUniforms:Me}),getShaderSource:at}},Ad=(e,t)=>{kd(e.inputs,t),t.blockSize===32&&e.adapterInfo.isVendor("intel")&&e.adapterInfo.isArchitecture("gen-12lp")?e.compute($d(e.inputs,t)):e.compute(Sd(e.inputs,t))},Id=e=>Bt(e)}),Fd,Dd,ga,Ld,zd,ws,_p,fp,gp,Bd=g(()=>{zt(),Ot(),Yt(),Fd=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].")}},Dd=(e,t,s)=>{let n="";for(let o=t-1;o>=0;--o)n+=` - k = i32(${e.indicesGet("indices",o)}) - ${$t("uniforms.pads",o,s)}; - if (k < 0) { - break; - } - if (k >= i32(${$t("uniforms.x_shape",o,t)})) { - break; - } - offset += k * i32(${$t("uniforms.x_strides",o,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]; - } - `},ga=(e,t,s)=>{let n="";for(let o=t-1;o>=0;--o)n+=` - k = i32(${e.indicesGet("indices",o)}) - ${$t("uniforms.pads",o,s)}; - if (k < 0) { - k = -k; - } - { - let _2n_1 = 2 * (i32(${$t("uniforms.x_shape",o,t)}) - 1); - k = k % _2n_1; - if(k >= i32(${$t("uniforms.x_shape",o,t)})) { - k = _2n_1 - k; - } - } - offset += k * i32(${$t("uniforms.x_strides",o,t)}); - `;return` - var offset = 0; - var k = 0; - ${n} - value = x[offset]; - `},Ld=(e,t,s)=>{let n="";for(let o=t-1;o>=0;--o)n+=` - k = i32(${e.indicesGet("indices",o)}) - ${$t("uniforms.pads",o,s)}; - if (k < 0) { - k = 0; - } - if (k >= i32(${$t("uniforms.x_shape",o,t)})) { - k = i32(${$t("uniforms.x_shape",o,t)}) - 1; - } - offset += k * i32(${$t("uniforms.x_strides",o,t)}); - `;return` - var offset = 0; - var k = 0; - ${n} - value = x[offset]; - `},zd=(e,t,s)=>{let n="";for(let o=t-1;o>=0;--o)n+=` - k = i32(${e.indicesGet("indices",o)}) - ${$t("uniforms.pads",o,s)}; - if (k < 0) { - k += i32(${$t("uniforms.x_shape",o,t)}]); - } - if (k >= i32(${$t("uniforms.x_shape",o,t)})) { - k -= i32(${$t("uniforms.x_shape",o,t)}); - } - offset += k * i32(${$t("uniforms.x_strides",o,t)}); - `;return` - var offset = 0; - var k = 0; - ${n} - value = x[offset]; - `},ws=(e,t,s)=>{switch(s.mode){case 0:return Dd(e,t,s.pads.length);case 1:return ga(e,t,s.pads.length);case 2:return Ld(e,t,s.pads.length);case 3:return zd(e,t,s.pads.length);default:throw new Error("Invalid mode")}},_p=(e,t)=>{let s=ze.padShape(e[0].dims.slice(),t.pads),n=e[0].dims,o=ze.size(s),a=[{type:12,data:o},{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(...yt(e[0].dims,s));let u=["rank"],p=h=>{let k=It("output",e[0].dataType,s.length),C=qe("x",e[0].dataType,n.length),d=C.type.value,z=ws(k,n.length,t),B=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:t.pads.length}];return t.mode===0&&B.push({name:"constant_value",type:i?d:"f32"}),` - ${h.registerUniforms(B).declareVariables(C,k)} - ${h.mainStart()} - ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - - let indices = ${k.offsetToIndices("global_idx")}; - - var value = ${d}(0); - ${z} - output[global_idx] = value; - }`};return{name:"Pad",shaderCache:{hint:`${t.mode}${i}`,inputDependencies:u},getRunData:()=>({outputs:[{dims:s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(ze.size(s)/64)},programUniforms:a}),getShaderSource:p}},fp=(e,t)=>{if(e.length>1){let s=e[1].getBigInt64Array(),n=e.length>=3&&e[2].data?e[2].dataType===10?e[2].getUint16Array()[0]:e[2].getFloat32Array()[0]:0,o=e[0].dims.length,a=new Int32Array(2*o).fill(0);if(e.length>=4){let u=e[3].getBigInt64Array();for(let p=0;pa[Number(p)]=Number(u));let i=[];return a.forEach(u=>i.push(u)),{mode:t.mode,value:n,pads:i}}else return t},gp=(e,t)=>{Fd(e.inputs);let s=fp(e.inputs,t);e.compute(_p(e.inputs,s),{inputs:[0]})}}),Kn,wa,ya,Ma,Ao,ba,wp,va,xa,Ta,yp,Rd,Nd,jd,Pa,Ud,Vd,Wd,Gd,Mp=g(()=>{We(),zt(),Ot(),Yt(),Kn=e=>{if(O.webgpu.validateInputContent&&(!e||e.length!==1))throw new Error("Pool ops requires 1 input.")},wa=(e,t,s)=>{let n=t.format==="NHWC",o=e.dims.slice();n&&o.splice(1,0,o.pop());let a=Object.hasOwnProperty.call(t,"dilations"),i=t.kernelShape.slice(),u=t.strides.slice(),p=a?t.dilations.slice():[],h=t.pads.slice();Js.adjustPoolAttributes(s,o,i,u,p,h);let k=Js.computePoolOutputShape(s,o,u,p,i,h,t.autoPad),C=Object.assign({},t);a?Object.assign(C,{kernelShape:i,strides:u,pads:h,dilations:p,cacheKey:t.cacheKey}):Object.assign(C,{kernelShape:i,strides:u,pads:h,cacheKey:t.cacheKey});let d=k.slice();return d.push(d.splice(1,1)[0]),[C,n?d:k]},ya=(e,t)=>{let s=t.format==="NHWC",n=ze.size(e),o=ze.size(t.kernelShape),a=[{type:12,data:n},{type:12,data:o}],i=[{name:"outputSize",type:"u32"},{name:"kernelSize",type:"u32"}];if(t.kernelShape.length<=2){let u=t.kernelShape[t.kernelShape.length-1],p=t.strides[t.strides.length-1],h=t.pads[t.pads.length/2-1],k=t.pads[t.pads.length-1],C=!!(h+k);a.push({type:12,data:u},{type:12,data:p},{type:12,data:h},{type:12,data:k}),i.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let d=!1;if(t.kernelShape.length===2){let z=t.kernelShape[t.kernelShape.length-2],B=t.strides[t.strides.length-2],V=t.pads[t.pads.length/2-2],Z=t.pads[t.pads.length-2];d=!!(V+Z),a.push({type:12,data:z},{type:12,data:B},{type:12,data:V},{type:12,data:Z}),i.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[a,i,!0,C,d]}else{if(s)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let u=ze.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 p=t.pads.reduce((h,k)=>h+k);return[a,i,!!p,!1,!1]}},Ma=(e,t,s,n,o,a,i,u,p,h,k,C)=>{let d=o.format==="NHWC",z=t.type.value,B=It("output",t.type.tensor,n);if(o.kernelShape.length<=2){let V="",Z="",ee="",X=s-(d?2:1);if(k?V=` - for (var i: u32 = 0u; i < uniforms.kw; i++) { - xIndices[${X}] = indices[${X}] * uniforms.sw - uniforms.pwStart + i; - if (xIndices[${X}] < 0 || xIndices[${X}] - >= uniforms.x_shape[${X}]) { - pad++; - continue; - } - let x_val = x[${t.indicesToOffset("xIndices")}]; - ${a} - }`:V=` - for (var i: u32 = 0u; i < uniforms.kw; i++) { - xIndices[${X}] = indices[${X}] * uniforms.sw - uniforms.pwStart + i; - let x_val = x[${t.indicesToOffset("xIndices")}]; - ${a} - }`,o.kernelShape.length===2){let he=s-(d?3:2);C?Z=` - for (var j: u32 = 0u; j < uniforms.kh; j++) { - xIndices[${he}] = indices[${he}] * uniforms.sh - uniforms.phStart + j; - if (xIndices[${he}] < 0 || xIndices[${he}] >= uniforms.x_shape[${he}]) { - pad += i32(uniforms.kw); - continue; - } - `:Z=` - for (var j: u32 = 0u; j < uniforms.kh; j++) { - xIndices[${he}] = indices[${he}] * uniforms.sh - uniforms.phStart + j; - `,ee=` - } - `}return` - ${e.registerUniforms(p).declareVariables(t,B)} - - ${e.mainStart()} - ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} - - let indices = ${B.offsetToIndices("global_idx")}; - var xIndices = ${B.offsetToIndices("global_idx")}; - - var value = ${z}(${u}); - var pad = 0; - ${Z} - ${V} - ${ee} - ${i} - - output[global_idx] = value; - }`}else{if(d)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let V=o.kernelShape.length,Z=o.pads.length,ee="";return h?ee=` - if (xIndices[j] >= uniforms.x_shape[j]) { - pad++; - isPad = true; - break; - } - } - if (!isPad) { - let x_val = x[${t.indicesToOffset("xIndices")}]; - ${a} - }`:ee=` - } - let x_val = x[${t.indicesToOffset("xIndices")}]; - ${a} - `,` - ${e.registerUniforms(p).declareVariables(t,B)} - - ${e.mainStart()} - ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} - let indices = ${B.offsetToIndices("global_idx")}; - var xIndices = ${B.offsetToIndices("global_idx")}; - - var offsets: array; - - var value = ${z}(${u}); - var pad = 0; - var isPad = false; - - for (var i: u32 = 0u; i < uniforms.kernelSize; i++) { - var offset = i; - for (var j = 0u; j < ${V-1}u; j++) { - offsets[j] = offset / ${$t("uniforms.kernelStrides","j",V)}; - offset -= offsets[j] * ${$t("uniforms.kernelStrides","j",V)}; - } - offsets[${V-1}] = offset; - - isPad = false; - for (var j = ${s-V}u; j < ${s}u; j++) { - xIndices[j] = indices[j] * ${$t("uniforms.strides",`j - ${s-V}u`,V)} - + offsets[j - ${s-V}u] - ${$t("uniforms.pads","j - 2u",Z)}; - ${ee} - } - ${i} - - output[global_idx] = value; - }`}},Ao=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,ba=e=>`${Ao(e)};${e.countIncludePad}`,wp=e=>`${Ao(e)};${e.storageOrder};${e.dilations}`,va=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}),xa=(e,t,s,n)=>{let[o,a]=wa(t,n,s),i=qe("x",t.dataType,t.dims.length),u=i.type.value,p="value += x_val;",h="";o.countIncludePad?h+=`value /= ${u}(uniforms.kernelSize);`:h+=`value /= ${u}(i32(uniforms.kernelSize) - pad);`;let[k,C,d,z,B]=ya(a,o);k.push(...yt(t.dims,a));let V=["rank"];return{name:e,shaderCache:{hint:`${n.cacheKey};${d};${z};${B}`,inputDependencies:V},getRunData:()=>({outputs:[{dims:a,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(ze.size(a)/64)},programUniforms:k}),getShaderSource:Z=>Ma(Z,i,t.dims.length,a.length,o,p,h,0,C,d,z,B)}},Ta=e=>{let t=e.count_include_pad!==0,s=va(e);if(s.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");let n={countIncludePad:t,...s,cacheKey:""};return{...n,cacheKey:ba(n)}},yp=(e,t)=>{Kn(e.inputs),e.compute(xa("AveragePool",e.inputs[0],!1,t))},Rd={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},Nd=e=>{let t=e.format;return{format:t,...Rd,cacheKey:t}},jd=(e,t)=>{Kn(e.inputs),e.compute(xa("GlobalAveragePool",e.inputs[0],!0,t))},Pa=(e,t,s,n)=>{let[o,a]=wa(t,n,s),i=` - value = max(x_val, value); - `,u="",p=qe("x",t.dataType,t.dims.length),h=["rank"],[k,C,d,z,B]=ya(a,o);return k.push(...yt(t.dims,a)),{name:e,shaderCache:{hint:`${n.cacheKey};${d};${z};${B}`,inputDependencies:h},getRunData:()=>({outputs:[{dims:a,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(ze.size(a)/64)},programUniforms:k}),getShaderSource:V=>Ma(V,p,t.dims.length,a.length,o,i,u,t.dataType===10?-65504:-1e5,C,d,z,B)}},Ud=(e,t)=>{Kn(e.inputs),e.compute(Pa("MaxPool",e.inputs[0],!1,t))},Vd=e=>{let t=e.storage_order,s=e.dilations,n=va(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 o={storageOrder:t,dilations:s,...n,cacheKey:""};return{...o,cacheKey:wp(o)}},Wd=e=>{let t=e.format;return{format:t,...Rd,cacheKey:t}},Gd=(e,t)=>{Kn(e.inputs),e.compute(Pa("GlobalMaxPool",e.inputs[0],!0,t))}}),Kd,Hd,qd,Qd,Hp=g(()=>{zt(),Ot(),rs(),Yt(),Kd=(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((s,n)=>s===e[2].dims[n]).reduce((s,n)=>s&&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((o,a)=>a===t.axis||o===e[0].dims[a]).reduce((o,a)=>o&&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 s=e[0].dims[t.axis],n=e[1].dims[t.axis];if(t.blockSizeMath.ceil(s/(n-1)-1))throw new Error("blockSize must be with in the range [ceil(dI / Si), ceil(dI / (Si - 1) - 1)].")}},Hd=(e,t)=>{let s=ze.normalizeAxis(t.axis,e[0].dims.length),n=e[0].dataType,o=n===3,a=e[0].dims,i=e[1].dataType,u=ze.size(a),p=n===3||n===2,h=p?[Math.ceil(ze.size(e[0].dims)/4)]:e[0].dims,k=e[1].dims,C=e.length>2?e[2]:void 0,d=C?p?[Math.ceil(ze.size(C.dims)/4)]:C.dims:void 0,z=k.length===0||k.length===1&&k[0]===1,B=z===!1&&k.length===1,V=qt(u),Z=z&&(!p||V===4),ee=Z?V:1,X=Z&&!p?V:1,he=qe("input",p?12:n,h.length,X),pe=qe("scale",i,k.length),Me=C?qe("zero_point",p?12:n,d.length):void 0,Oe=It("output",i,a.length,ee),Le=[he,pe];Me&&Le.push(Me);let Ye=[h,k];C&&Ye.push(d);let at=[{type:12,data:u/ee},{type:12,data:s},{type:12,data:t.blockSize},...yt(...Ye,a)],Pt=Xt=>{let Zt=[{name:"output_size",type:"u32"},{name:"axis",type:"u32"},{name:"block_size",type:"u32"}];return` - ${Xt.registerUniforms(Zt).declareVariables(...Le,Oe)} - ${Xt.mainStart()} - ${Xt.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - let output_indices = ${Oe.offsetToIndices("global_idx")}; - - // Set input x - ${p?` - let input = ${he.getByOffset("global_idx / 4")}; - let x_vec = ${o?"unpack4xI8(input)":"unpack4xU8(input)"}; - let x_value = ${ee===1?"x_vec[global_idx % 4]":"x_vec"};`:`let x_value = ${he.getByOffset("global_idx")};`}; - - // Set scale input - ${z?`let scale_value= ${pe.getByOffset("0")}`:B?` - let scale_index = ${Oe.indicesGet("output_indices","uniforms.axis")}; - let scale_value= ${pe.getByOffset("scale_index")};`:` - var scale_indices: ${pe.type.indices} = output_indices; - let index = ${pe.indicesGet("scale_indices","uniforms.axis")} / uniforms.block_size; - ${pe.indicesSet("scale_indices","uniforms.axis","index")}; - let scale_value= ${pe.getByIndices("scale_indices")};`}; - - // Set zero-point input - ${Me?z?p?` - let zero_point_input = ${Me.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 = ${Me.getByOffset("0")}`:B?p?` - let zero_point_index = ${Oe.indicesGet("output_indices","uniforms.axis")}; - let zero_point_input = ${Me.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 = ${Oe.indicesGet("output_indices","uniforms.axis")}; - let zero_point_value = ${Me.getByOffset("zero_point_index")};`:p?` - let zero_point_offset = ${pe.indicesToOffset("scale_indices")}; - let zero_point_input = ${Me.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 = ${Me.getByIndices("scale_indices")};`:`let zero_point_value = ${p?o?"i32":"u32":he.type.value}(0);`}; - // Compute and write output - ${Oe.setByOffset("global_idx",`${Oe.type.value}(x_value - zero_point_value) * scale_value`)}; - }`};return{name:"DequantizeLinear",shaderCache:{hint:t.cacheKey,inputDependencies:Me?["rank","rank","rank"]:["rank","rank"]},getShaderSource:Pt,getRunData:()=>({outputs:[{dims:a,dataType:i}],dispatchGroup:{x:Math.ceil(u/ee/64),y:1,z:1},programUniforms:at})}},qd=(e,t)=>{Kd(e.inputs,t),e.compute(Hd(e.inputs,t))},Qd=e=>Bt({axis:e.axis,blockSize:e.blockSize})}),Xd,Yd,Jd,bp=g(()=>{We(),zt(),Yt(),Xd=(e,t,s)=>{let n=e===t,o=et&&s>0;if(n||o||a)throw new Error("Range these inputs' contents are invalid.")},Yd=(e,t,s,n)=>{let o=Math.abs(Math.ceil((t-e)/s)),a=[o],i=o,u=[{type:12,data:i},{type:n,data:e},{type:n,data:s},...yt(a)],p=h=>{let k=It("output",n,a.length),C=k.type.value,d=[{name:"outputSize",type:"u32"},{name:"start",type:C},{name:"delta",type:C}];return` - ${h.registerUniforms(d).declareVariables(k)} - ${h.mainStart()} - ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} - output[global_idx] = uniforms.start + ${C}(global_idx) * uniforms.delta; - }`};return{name:"Range",shaderCache:{hint:`${n}`},getShaderSource:p,getRunData:()=>({outputs:[{dims:a,dataType:n}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:u})}},Jd=e=>{let t=0,s=0,n=0;e.inputs[0].dataType===6?(t=e.inputs[0].getInt32Array()[0],s=e.inputs[1].getInt32Array()[0],n=e.inputs[2].getInt32Array()[0]):e.inputs[0].dataType===1&&(t=e.inputs[0].getFloat32Array()[0],s=e.inputs[1].getFloat32Array()[0],n=e.inputs[2].getFloat32Array()[0]),O.webgpu.validateInputContent&&Xd(t,s,n),e.compute(Yd(t,s,n,e.inputs[0].dataType),{inputs:[]})}}),Zd,ec,vp,Ea,xp=g(()=>{zt(),Ot(),rs(),Yt(),Zd=(e,t,s,n)=>{if(e!=="none"&&n!=="i32"&&n!=="u32"&&n!=="f32")throw new Error(`Input ${n} is not supported with reduction ${e}.`);let o=`{ - var oldValue = 0; - loop { - let newValueF32 =`,a=`; - let newValue = bitcast(newValueF32); - let res = atomicCompareExchangeWeak(&${t}, oldValue, newValue); - if res.exchanged { - break; - } - oldValue = res.old_value; - } - }`;switch(e){case"none":return`${t}=${s};`;case"add":return n==="i32"||n==="u32"?`atomicAdd(&${t}, bitcast<${n}>(${s}));`:` - ${o}bitcast<${n}>(oldValue) + (${s})${a}`;case"max":return n==="i32"||n==="u32"?`atomicMax(&${t}, bitcast<${n}>(${s}));`:` - ${o}max(bitcast(oldValue), (${s}))${a}`;case"min":return n==="i32"||n==="u32"?`atomicMin(&${t}, bitcast<${n}>(${s}));`:`${o}min(bitcast<${n}>(oldValue), (${s}))${a}`;case"mul":return`${o}(bitcast<${n}>(oldValue) * (${s}))${a}`;default:throw new Error(`Reduction ${e} is not supported.`)}},ec=(e,t)=>{let s=e[0].dims,n=e[1].dims,o=s,a=1,i=Math.ceil(ze.size(n)/a),u=n[n.length-1],p=ze.sizeFromDimension(s,u),h=[{type:12,data:i},{type:12,data:u},{type:12,data:p},...yt(e[1].dims,e[2].dims,o)],k=C=>{let d=qe("indices",e[1].dataType,e[1].dims.length),z=qe("updates",e[2].dataType,e[2].dims.length,a),B=t.reduction!=="none"&&t.reduction!==""?La("output",e[0].dataType,o.length):It("output",e[0].dataType,o.length,a);return` - ${C.registerUniform("output_size","u32").registerUniform("last_index_dimension","u32").registerUniform("num_updates_elements","u32").declareVariables(d,z,B)} - ${C.mainStart()} - ${C.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - var data_offset = 0u; - let indices_start = uniforms.last_index_dimension * global_idx; - let indices_end = indices_start + uniforms.last_index_dimension; - for (var i = indices_start; i < indices_end; i++) { - var index = i32(indices[i].x); - ${e[0].dims.length===1?` - let element_count_dim = uniforms.output_strides; - let dim_value = uniforms.output_shape;`:` - let element_count_dim = uniforms.output_strides[i - indices_start]; - let dim_value = uniforms.output_shape[i - indices_start + 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)); - } - - for (var i = 0u; i < uniforms.num_updates_elements; i++) { - let value = updates[uniforms.num_updates_elements * global_idx + i]; - ${Zd(t.reduction,"output[data_offset + i]","value",B.type.value)} - } - - }`};return{name:"ScatterND",shaderCache:{hint:`${t.cacheKey}_${t.reduction}`,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:h}),getShaderSource:k}},vp=e=>Bt({reduction:e.reduction}),Ea=(e,t)=>{e.compute(ec(e.inputs,t),{inputs:[e.inputs[1],e.inputs[2]],outputs:[]})}}),tc,sc,rc,nc,oc,ic,ac,lc,uc,dc,cc,Ca,pc,hc,mc,_c,fc,gc,wc,Tp=g(()=>{zt(),Ot(),rs(),Yt(),tc=(e,t)=>{if(e.every(s=>s>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")}},sc=(e,t,s)=>{t.every(o=>o>=0&&o{throw new Error("Resize requires axes input values to be positive and less than rank")}));let n=new Array(s).fill(1);return t.forEach((o,a)=>n[o]=e[a]),n},rc=(e,t,s,n,o,a)=>{let[i,u,p]=s>10?[1,2,3]:[-1,e.length>1?1:-1,-1],h=e[0].dims.length;if(i>0&&e.length>i&&e[i].dims.length>0)e[i].getFloat32Array().forEach(k=>a.push(k));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===1&&e[u].dims[0]>0){if(e[u].getFloat32Array().forEach(k=>n.push(k)),n.length!==0&&n.length!==h&&s>=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");tc(n,t),t.axes.length>0&&sc(n,t.axes,h).forEach((k,C)=>n[C]=k)}if(p>0&&e.length>p&&e[p].dims.length===1&&e[p].dims[0]>0&&(e[p].getBigInt64Array().forEach(k=>o.push(Number(k))),o.length!==0&&o.length!==h&&s>=18&&o.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!==0&&n.length!==t.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!==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 o<"u"&&n.length>0&&o.length>h)throw new Error("Resize requires only of scales or sizes to be specified")},nc=(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`)}})()+"}",oc=(e,t,s)=>`fn getNearestPixelFromOriginal(xOriginal: ${s}, isDownSample: bool) -> ${s} {`+(()=>{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`)}})()+"}",ic=(e,t,s)=>{let n=new Array(s).fill(0).concat(new Array(s).fill(1)),o=e.length===0?n:e.slice();return t.length>0?(t.forEach((a,i)=>{n[a]=o[i],n[i+s]=o[t.length+i]}),n):o},ac=(e,t,s,n)=>{let o=[];if(s.length>0)if(n.length>0){if(e.forEach(a=>o.push(a)),Math.max(...n)>e.length)throw new Error("axes is out of bound");n.forEach((a,i)=>o[a]=s[i])}else s.forEach(a=>o.push(a));else{if(t.length===0)throw new Error("Resize requires either scales or sizes.");o=e.map((a,i)=>Math.round(a*t[i]))}return o},lc=(e,t,s)=>{let n=(()=>{switch(s.keepAspectRatioPolicy){case"not_larger":return s.axes.length>0?Math.min(...s.axes.map(a=>t[a]),Number.MAX_VALUE):Math.min(...t,Number.MAX_VALUE);case"not_smaller":return s.axes.length>0?Math.max(...s.axes.map(a=>t[a]),Number.MIN_VALUE):Math.max(...t,Number.MIN_VALUE);default:throw new Error(`Keep aspect ratio policy ${s.keepAspectRatioPolicy} is not supported`)}})();t.fill(1,0,t.length);let o=e.slice();return s.axes.length>0?(s.axes.forEach(a=>t[a]=n),s.axes.forEach(a=>o[a]=Math.round(e[a]*t[a]))):(t.fill(n,0,t.length),o.forEach((a,i)=>o[i]=Math.round(a*t[i]))),o},uc=(e,t,s,n,o)=>` - fn calculateOriginalIndicesFromOutputIndices(output_indices: ${e.type.indices}) -> array<${e.type.value}, ${s.length}> { - var original_indices: array<${e.type.value}, ${s.length}>; - for (var i:u32 = 0; i < ${s.length}; i++) { - var output_index = ${e.indicesGet("output_indices","i")}; - var scale = ${$t("uniforms.scales","i",n)}; - var roi_low = ${$t("uniforms.roi","i",o)}; - var roi_hi = ${$t("uniforms.roi",`i + ${t.length}`,o)}; - if (scale == 1.0) { - original_indices[i] = ${e.type.value}(output_index); - } else { - var input_shape_i = ${$t("uniforms.input_shape","i",t.length)}; - var output_shape_i = ${$t("uniforms.output_shape","i",s.length)}; - original_indices[i] = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, - input_shape_i, roi_low, roi_hi); - } - } - return original_indices; - }`,dc=(e,t,s,n,o,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 = ${$t("uniforms.scales","i",o)}; - if (scale == 1.0) { - input_index = output_index; - } else { - var roi_low = ${$t("uniforms.roi","i",a)}; - var roi_hi = ${$t("uniforms.roi",`i + ${s.length}`,a)}; - var input_shape_i = ${$t("uniforms.input_shape","i",s.length)}; - var output_shape_i = ${$t("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; - }`,cc=(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 >= ${$t("uniforms.input_shape","i",t.length)}) { - return false; - } - } - return true; - }`,Ca=(e,t,s,n)=>e.rank>n?` - ${e.indicesSet("input_indices",t,"channel")}; - ${e.indicesSet("input_indices",s,"batch")}; -`:"",pc=(e,t,s,n,o)=>{let[a,i,u,p]=s.length===2?[-1,0,1,-1]:[0,2,3,1],h=e.type.value;return` - fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${h} { - var input_indices: ${e.type.indices}; - ${e.indicesSet("input_indices",i,`max(0, min(row, ${s[i]} - 1))`)}; - ${e.indicesSet("input_indices",u,`max(0, min(col, ${s[u]} - 1))`)}; - ${Ca(e,p,a,2)} - return ${e.getByIndices("input_indices")}; - } - - fn bilinearInterpolation(output_indices: ${t.type.indices}) -> ${h} { - var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); - var row:${h} = originalIndices[${i}]; - var col:${h} = originalIndices[${u}]; - ${n?`if (row < 0 || row > (${s[i]} - 1) || col < 0 || col > (${s[u]} - 1)) { - return ${o}; - }`:""}; - row = max(0, min(row, ${s[i]} - 1)); - col = max(0, min(col, ${s[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 = ${s.length>2?`u32(originalIndices[${p}])`:"0"}; - var batch: u32 = ${s.length>2?`u32(originalIndices[${a}])`:"0"}; - var x11: ${h} = getInputValue(batch, channel, row1, col1); - var x12: ${h} = getInputValue(batch, channel, row1, col2); - var x21: ${h} = getInputValue(batch, channel, row2, col1); - var x22: ${h} = getInputValue(batch, channel, row2, col2); - var dx1: ${h} = abs(row - ${h}(row1)); - var dx2: ${h} = abs(${h}(row2) - row); - var dy1: ${h} = abs(col - ${h}(col1)); - var dy2: ${h} = abs(${h}(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); - }`},hc=(e,t,s,n,o,a,i,u,p,h)=>{let k=s.length===2,[C,d]=k?[0,1]:[2,3],z=e.type.value,B=V=>{let Z=V===C?"row":"col";return` - fn ${Z}CubicInterpolation(input_indices: ${e.type.indices}, output_indices: ${t.type.indices}) -> ${z} { - var output_index = ${t.indicesGet("output_indices",V)}; - var originalIdx: ${z} = getOriginalCoordinateFromResizedCoordinate(output_index, ${o[V]}, - ${n[V]}, ${s[V]}, ${a[V]}, ${a[V]} + ${s.length}); - var fractOriginalIdx: ${z} = originalIdx - floor(originalIdx); - var coefs = getCubicInterpolationCoefs(fractOriginalIdx); - - if (${u} && (originalIdx < 0 || originalIdx > (${s[V]} - 1))) { - return ${p}; - } - var data: array<${z}, 4> = array<${z}, 4>(0.0, 0.0, 0.0, 0.0); - for (var i: i32 = -1; i < 3; i++) { - var ${Z}: ${z} = originalIdx + ${z}(i); - if (${Z} < 0 || ${Z} >= ${s[V]}) { - ${h?`coefs[i + 1] = 0.0; - continue;`:u?`return ${p};`:`${Z} = max(0, min(${Z}, ${s[V]} - 1));`}; - } - var input_indices_copy: ${e.type.indices} = input_indices; - ${e.indicesSet("input_indices_copy",V,`u32(${Z})`)}; - data[i + 1] = ${V===C?e.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"}; - } - return cubicInterpolation1D(data, coefs); - }`};return` - ${B(C)}; - ${B(d)}; - fn getCubicInterpolationCoefs(s: ${z}) -> array<${z}, 4> { - var absS = abs(s); - var coeffs: array<${z}, 4> = array<${z}, 4>(0.0, 0.0, 0.0, 0.0); - var oneMinusAbsS: ${z} = 1.0 - absS; - var twoMinusAbsS: ${z} = 2.0 - absS; - var onePlusAbsS: ${z} = 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<${z}, 4>, coefs: array<${z}, 4>) -> ${z} { - var coefsSum: ${z} = 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}) -> ${z} { - var input_indices: ${e.type.indices} = output_indices; - return colCubicInterpolation(input_indices, output_indices); - } - `},mc=(e,t,s,n,o)=>{let[a,i,u,p,h]=s.length===3?[-1,0,1,2,-1]:[0,2,3,4,1],k=e.type.value;return` - fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${k} { - var input_indices: ${e.type.indices}; - ${e.indicesSet("input_indices",i,`max(0, min(depth, ${s[i]} - 1))`)}; - ${e.indicesSet("input_indices",u,`max(0, min(height, ${s[u]} - 1))`)}; - ${e.indicesSet("input_indices",p,`max(0, min(width, ${s[p]} - 1))`)}; - ${Ca(e,h,a,3)} - return ${e.getByIndices("input_indices")}; - } - - fn trilinearInterpolation(output_indices: ${t.type.indices}) -> ${k} { - var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); - var depth:${k} = originalIndices[${i}]; - var height:${k} = originalIndices[${u}]; - var width:${k} = originalIndices[${p}]; - ${n?`if (depth < 0 || depth > (${s[i]} - 1) || height < 0 || height > (${s[u]} - 1) || width < 0 || (width > ${s[p]} - 1)) { - return ${o}; - }`:""}; - - depth = max(0, min(depth, ${s[i]} - 1)); - height = max(0, min(height, ${s[u]} - 1)); - width = max(0, min(width, ${s[p]} - 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 = ${s.length>3?`u32(originalIndices[${h}])`:"0"}; - var batch: u32 = ${s.length>3?`u32(originalIndices[${a}])`:"0"}; - - var x111: ${k} = getInputValue(batch, channel, depth1, height1, width1); - var x112: ${k} = getInputValue(batch, channel, depth1, height1, width2); - var x121: ${k} = getInputValue(batch, channel, depth1, height2, width1); - var x122: ${k} = getInputValue(batch, channel, depth1, height2, width2); - var x211: ${k} = getInputValue(batch, channel, depth2, height1, width1); - var x212: ${k} = getInputValue(batch, channel, depth2, height1, width2); - var x221: ${k} = getInputValue(batch, channel, depth2, height2, width1); - var x222: ${k} = getInputValue(batch, channel, depth2, height2, width2); - var dx1: ${k} = abs(depth - ${k}(depth1)); - var dx2: ${k} = abs(${k}(depth2) - depth); - var dy1: ${k} = abs(height - ${k}(height1)); - var dy2: ${k} = abs(${k}(height2) - height); - var dz1: ${k} = abs(width - ${k}(width1)); - var dz2: ${k} = abs(${k}(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); - }`},_c=(e,t,s,n,o,a)=>{let i=e.dims,u=ic(a,t.axes,i.length),p=ac(i,n,o,t.axes),h=n.slice();n.length===0&&(h=i.map((X,he)=>X===0?1:p[he]/X),t.keepAspectRatioPolicy!=="stretch"&&(p=lc(i,h,t)));let k=It("output",e.dataType,p.length),C=qe("input",e.dataType,i.length),d=ze.size(p),z=i.length===p.length&&i.every((X,he)=>X===p[he]),B=t.coordinateTransformMode==="tf_crop_and_resize",V=t.extrapolationValue,Z=C.type.value,ee=X=>` - ${z?"":` - ${nc(t.coordinateTransformMode,Z)}; - ${(()=>{switch(t.mode){case"nearest":return` - ${cc(C,i)}; - ${oc(t.nearestMode,s,Z)}; - ${dc(C,k,i,p,h.length,u.length,B)}; - `;case"linear":return` - ${uc(k,i,p,h.length,u.length)}; - ${(()=>{if(i.length===2||i.length===4)return`${pc(C,k,i,B,V)}`;if(i.length===3||i.length===5)return`${mc(C,k,i,B,V)}`;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`${hc(C,k,i,p,h,u,t.cubicCoeffA,B,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")}})()}; - `} - ${X.registerUniform("output_size","u32").registerUniform("scales","f32",h.length).registerUniform("roi","f32",u.length).declareVariables(C,k)} - ${X.mainStart()} - ${X.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - ${z?"output[global_idx] = input[global_idx];":` - let output_indices = ${k.offsetToIndices("global_idx")}; - var input_indices: ${C.type.indices}; - ${(()=>{switch(t.mode){case"nearest":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices); - if (checkInputIndices(input_indices)) { - output[global_idx] = ${C.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}|${s}|${h.length>0?h:""}|${o.length>0?o:""}|${u.length>0?u:""}|${z}|${i}`,inputDependencies:["rank"]},getShaderSource:ee,getRunData:()=>({outputs:[{dims:p,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:[{type:12,data:d},{type:1,data:h},{type:1,data:u},...yt(i,p)]})}},fc=e=>{let t=e.customDataBuffer;return new Uint32Array(t,t.byteOffset,1)[0]},gc=(e,t)=>{let s=[],n=[],o=[],a=fc(e);if(t.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");rc(e.inputs,t,a,s,n,o),e.compute(_c(e.inputs[0],t,a,s,n,o),{inputs:[0]})},wc=e=>{let t=e.antialias,s=e.axes,n=e.coordinateTransformMode,o=e.cubicCoeffA,a=e.excludeOutside!==0,i=e.extrapolationValue,u=e.keepAspectRatioPolicy,p=e.mode,h=e.nearestMode===""?"simple":e.nearestMode;return Bt({antialias:t,axes:s,coordinateTransformMode:n,cubicCoeffA:o,excludeOutside:a,extrapolationValue:i,keepAspectRatioPolicy:u,mode:p,nearestMode:h})}}),yc,Mc,bc,Pp=g(()=>{zt(),Ot(),rs(),Yt(),yc=(e,t)=>{let[s,n,o,a]=e,{numHeads:i,rotaryEmbeddingDim:u}=t;if(s.dims.length!==3&&s.dims.length!==4)throw new Error(`Input 'x' is expected to have 3 or 4 dimensions, got ${s.dims.length}`);if(!ze.areEqual(n.dims,[])&&!ze.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(o.dims.length!==2)throw new Error(`Input 'cos_cache' is expected to have 2 dimensions, got ${o.dims.length}`);if(a.dims.length!==2)throw new Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${a.dims.length}`);if(!ze.areEqual(o.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 p=s.dims[0],h=s.dims[s.dims.length-2],k=o.dims[0],C=ze.sizeFromDimension(s.dims,1)/h,d=u===0?o.dims[1]*2:C/i;if(u>d)throw new Error("rotary_embedding_dim must be less than or equal to head_size");if(n.dims.length===2){if(p!==n.dims[0])throw new Error(`Input 'position_ids' dimension 0 should be of size batch_size, got ${n.dims[0]}`);if(h!==n.dims[1])throw new Error(`Input 'position_ids' dimension 1 should be of size sequence_length, got ${n.dims[1]}`)}if(d/2!==o.dims[1]&&u/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(h>k)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported")},Mc=(e,t)=>{let{interleaved:s,numHeads:n,rotaryEmbeddingDim:o,scale:a}=t,i=e[0].dims[0],u=ze.sizeFromDimension(e[0].dims,1),p=e[0].dims[e[0].dims.length-2],h=u/p,k=e[2].dims[1],C=o===0?k*2:h/n,d=new Array(i,p,h/C,C-k),z=ze.computeStrides(d),B=[{type:1,data:a},{type:12,data:d},{type:12,data:z},...e[0].dims.length===3?new Array({type:12,data:[u,h,C,1]}):[],...e[0].dims.length===4?new Array({type:12,data:[u,C,p*C,1]}):[],...yt(e[0].dims,e[1].dims,e[2].dims,e[3].dims,e[0].dims)],V=Z=>{let ee=qe("input",e[0].dataType,e[0].dims.length),X=qe("position_ids",e[1].dataType,e[1].dims.length),he=qe("cos_cache",e[2].dataType,e[2].dims.length),pe=qe("sin_cache",e[3].dataType,e[3].dims.length),Me=It("output",e[0].dataType,e[0].dims.length);return Z.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:d.length},{name:"global_strides",type:"u32",length:z.length},{name:"input_output_strides",type:"u32",length:z.length}]),` - ${Z.declareVariables(ee,X,he,pe,Me)} - - ${Z.mainStart(or)} - let half_rotary_emb_dim = uniforms.${he.name}_shape[1]; - let bsnh = global_idx / uniforms.global_strides % uniforms.global_shape; - let size = uniforms.global_shape[0] * uniforms.global_strides[0]; - ${Z.guardAgainstOutOfBoundsWorkgroupSizes("size")} - - if (bsnh[3] < half_rotary_emb_dim) { - let position_ids_idx = - ${X.broadcastedIndicesToOffset("bsnh.xy",It("",X.type.tensor,2))}; - let position_id = - u32(${X.getByOffset("position_ids_idx")}) + select(0, bsnh[1], position_ids_idx == 0); - let i = dot(bsnh, uniforms.input_output_strides) + select(0, bsnh[3], ${s}); - let j = i + select(half_rotary_emb_dim, 1, ${s}); - let re = ${ee.getByOffset("i")} * ${he.get("position_id","bsnh[3]")} - - ${ee.getByOffset("j")} * ${pe.get("position_id","bsnh[3]")}; - ${Me.setByOffset("i","re")} - let im = ${ee.getByOffset("i")} * ${pe.get("position_id","bsnh[3]")} + - ${ee.getByOffset("j")} * ${he.get("position_id","bsnh[3]")}; - ${Me.setByOffset("j","im")} - } else { - let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim; - ${Me.setByOffset("k",ee.getByOffset("k"))} - } - }`};return{name:"RotaryEmbedding",shaderCache:{hint:Bt({interleaved:s}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:V,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(ze.size(d)/or)},programUniforms:B})}},bc=(e,t)=>{yc(e.inputs,t),e.compute(Mc(e.inputs,t))}}),vc,xc,Tc,qp=g(()=>{zt(),Ot(),Yt(),vc=e=>{if(!e||e.length<3)throw new Error("layerNorm requires at least 3 inputs.");let t=e[0],s=e[1],n=e[2];if(t.dataType!==s.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(s.dims.length!==3&&s.dims.length!==2)throw new Error("Skip must be 2D or 3D");let o=t.dims[t.dims.length-1],a=t.dims[t.dims.length-2];if(s.dims[s.dims.length-1]!==o)throw new Error("Skip must have the same hidden size as input");if(s.dims[s.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]!==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")}},xc=(e,t,s,n)=>{let o=t.simplified,a=e[0].dims,i=ze.size(a),u=a,p=i,h=a.slice(-1)[0],k=n?a.slice(0,-1).concat(1):[],C=!o&&e.length>3,d=e.length>4,z=n&&s>1,B=n&&s>2,V=s>3,Z=64,ee=qt(h),X=[{type:12,data:p},{type:12,data:ee},{type:12,data:h},{type:1,data:t.epsilon}],he=Me=>{let Oe=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],Le=[qe("x",e[0].dataType,e[0].dims,ee),qe("skip",e[1].dataType,e[1].dims,ee),qe("gamma",e[2].dataType,e[2].dims,ee)];C&&Le.push(qe("beta",e[3].dataType,e[3].dims,ee)),d&&Le.push(qe("bias",e[4].dataType,e[4].dims,ee)),Le.push(It("output",e[0].dataType,u,ee)),z&&Le.push(It("mean_output",1,k)),B&&Le.push(It("inv_std_output",1,k)),V&&Le.push(It("input_skip_bias_sum",e[0].dataType,u,ee));let Ye=_s(e[0].dataType),at=_s(1,ee);return` - - ${Me.registerUniforms(Oe).declareVariables(...Le)} - var sum_shared : array<${at}, ${Z}>; - var sum_squared_shared : array<${at}, ${Z}>; - - ${Me.mainStart([Z,1,1])} - let ix = local_id.x; - let iy = global_id.x / ${Z}; - - let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components; - var stride = hidden_size_vectorized / ${Z}; - let offset = ix * stride + iy * hidden_size_vectorized; - let offset1d = stride * ix; - if (ix == ${Z-1}) { - stride = hidden_size_vectorized - stride * ix; - } - for (var i: u32 = 0; i < stride; i++) { - let skip_value = skip[offset + i]; - let bias_value = ${d?"bias[offset1d + i]":Ye+"(0.0)"}; - let input_value = x[offset + i]; - let value = input_value + skip_value + bias_value; - ${V?"input_skip_bias_sum[offset + i] = value;":""} - output[offset + i] = value; - let f32_value = ${$s(Ye,ee,"value")}; - sum_shared[ix] += f32_value; - sum_squared_shared[ix] += f32_value * f32_value; - } - workgroupBarrier(); - - var reduce_size : u32 = ${Z}; - 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 = ${Gs("sum",ee)} / f32(uniforms.hidden_size); - let inv_std_dev = inverseSqrt(${Gs("square_sum",ee)} / f32(uniforms.hidden_size) ${o?"":"- mean * mean"} + uniforms.epsilon); - ${z?"mean_output[global_idx] = mean;":""} - ${B?"inv_std_output[global_idx] = inv_std_dev;":""} - - for (var i: u32 = 0; i < stride; i++) { - output[offset + i] = (output[offset + i] ${o?"":`- ${Ye}(mean)`}) * - ${Ye}(inv_std_dev) * gamma[offset1d + i] - ${C?"+ beta[offset1d + i]":""}; - } - }`},pe=[{dims:u,dataType:e[0].dataType}];return s>1&&pe.push({dims:k,dataType:1}),s>2&&pe.push({dims:k,dataType:1}),s>3&&pe.push({dims:a,dataType:e[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${ee};${z};${B};${V}`,inputDependencies:e.map((Me,Oe)=>"type")},getShaderSource:he,getRunData:()=>({outputs:pe,dispatchGroup:{x:Math.ceil(p/h)},programUniforms:X})}},Tc=(e,t)=>{vc(e.inputs);let s=[0];e.outputCount>1&&s.push(-3),e.outputCount>2&&s.push(-3),e.outputCount>3&&s.push(3),e.compute(xc(e.inputs,t,e.outputCount,!1),{outputs:s})}}),Qt,Hn,Hs,qs,tr,cn,Ep,Pc,Cp=g(()=>{zt(),Ot(),rs(),Yt(),Qt=(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((s,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`)})},Hn=(e,t)=>{let s=[];if(e.length>t)if(e[t].dataType===7)e[t].getBigInt64Array().forEach(n=>s.push(Number(n)));else if(e[t].dataType===6)e[t].getInt32Array().forEach(n=>s.push(Number(n)));else throw new Error(`Input ${t} must be an array of int32 or int64`);return s},Hs=(e,t)=>{if(e.length>1){let s=Hn(e,1),n=Hn(e,2),o=Hn(e,3);return o.length===0&&(o=[...Array(e[0].dims.length).keys()]),Bt({starts:s,ends:n,axes:o})}else return t},qs=(e,t,s,n,o)=>{let a=e;return e<0&&(a+=s[n[t]]),o[t]<0?Math.max(0,Math.min(a,s[n[t]]-1)):Math.max(0,Math.min(a,s[n[t]]))},tr=(e,t,s)=>`fn calculateInputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} { - var input_indices: ${e.type.indices}; - var carry = 0u; - for (var i = ${s.length}; i >= 0; i--) { - let input_shape_i = ${$t("uniforms.input_shape","i",s.length)}; - let steps_i = ${$t("uniforms.steps","i",s.length)}; - let signs_i = ${$t("uniforms.signs","i",s.length)}; - let starts_i = ${$t("uniforms.starts","i",s.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; - }`,cn=(e,t)=>{let s=e[0].dims,n=ze.size(s),o=t.axes.length>0?ze.normalizeAxes(t.axes,s.length):[...Array(s.length).keys()],a=Hn(e,4);a.forEach(ee=>ee!==0||(()=>{throw new Error("step cannot be 0")})),a.length===0&&(a=Array(o.length).fill(1));let i=t.starts.map((ee,X)=>qs(ee,X,s,o,a)),u=t.ends.map((ee,X)=>qs(ee,X,s,o,a));if(o.length!==i.length||o.length!==u.length)throw new Error("start, ends and axes should have the same number of elements");if(o.length!==s.length)for(let ee=0;eeMath.sign(ee));a.forEach((ee,X,he)=>{if(ee<0){let pe=(u[X]-i[X])/ee,Me=i[X],Oe=Me+pe*a[X];i[X]=Oe,u[X]=Me,he[X]=-ee}});let h=s.slice(0);o.forEach((ee,X)=>{h[ee]=Math.ceil((u[ee]-i[ee])/a[ee])});let k={dims:h,dataType:e[0].dataType},C=It("output",e[0].dataType,h.length),d=qe("input",e[0].dataType,e[0].dims.length),z=ze.size(h),B=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:i.length},{name:"signs",type:"i32",length:p.length},{name:"steps",type:"u32",length:a.length}],V=[{type:12,data:z},{type:12,data:i},{type:6,data:p},{type:12,data:a},...yt(e[0].dims,h)],Z=ee=>` - ${ee.registerUniforms(B).declareVariables(d,C)} - ${tr(d,C,s)} - ${ee.mainStart()} - ${ee.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} - let output_indices = ${C.offsetToIndices("global_idx")}; - let input_indices = calculateInputIndices(output_indices); - ${C.setByOffset("global_idx",d.getByIndices("input_indices"))} - }`;return{name:"Slice",shaderCache:{hint:`${p.length}_${i.length}_${a.length}`,inputDependencies:["rank"]},getShaderSource:Z,getRunData:()=>({outputs:[k],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:V})}},Ep=(e,t)=>{Qt(e.inputs,t);let s=Hs(e.inputs,t);e.compute(cn(e.inputs,s),{inputs:[0]})},Pc=e=>{let t=e.starts,s=e.ends,n=e.axes;return Bt({starts:t,ends:s,axes:n})}}),_,T,N,fe,Fe=g(()=>{zt(),Ot(),rs(),Kr(),Yt(),_=e=>{if(!e||e.length!==1)throw new Error("Softmax op requires 1 input.")},T=(e,t)=>{let s=e.inputs[0],n=s.dims,o=ze.size(n),a=n.length,i=ze.normalizeAxis(t.axis,a),u=iYe),h[i]=a-1,h[a-1]=i,p=e.compute(pr(s,h),{inputs:[s],outputs:[-1]})[0]):p=s;let k=p.dims,C=k[a-1],d=o/C,z=qt(C),B=C/z,V=64;d===1&&(V=256);let Z=(Le,Ye)=>Ye===4?`max(max(${Le}.x, ${Le}.y), max(${Le}.z, ${Le}.w))`:Ye===2?`max(${Le}.x, ${Le}.y)`:Ye===3?`max(max(${Le}.x, ${Le}.y), ${Le}.z)`:Le,ee=qe("x",p.dataType,p.dims,z),X=It("result",p.dataType,p.dims,z),he=ee.type.value,pe=_s(p.dataType)==="f32"?`var threadMax = ${he}(-3.402823e+38f);`:`var threadMax = ${he}(-65504.0h);`,Me=Le=>` - var rowMaxShared : ${he}; - var rowSumShared : ${he}; - var threadShared : array<${he}, ${V}>; - - fn getValue(row: i32, col: i32, row_stride: i32) -> ${he} { - let index = row * row_stride + col; - return x[index]; - } - - fn setValue(row: i32, col: i32, row_stride: i32, value: ${he}) { - let index = row * row_stride + col; - result[index] = value; - } - ${Le.registerUniform("packedCols","i32").declareVariables(ee,X)} - ${Le.mainStart(V)} - let gindex = i32(global_idx); - let lindex = i32(local_idx); - const wg = ${V}; - let row = gindex / wg; - let cols = uniforms.packedCols; - let row_stride : i32 = uniforms.packedCols; - - // find the rows max - ${pe} - 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 = ${he}(${Z("threadShared[0]",z)}); - } - workgroupBarrier(); - - // find the rows sum - var threadSum = ${he}(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 = ${he}(${Gs("threadShared[0]",z)}); - } - 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); - } - }`,Oe=e.compute({name:"Softmax",shaderCache:{hint:`${z};${V}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:k,dataType:p.dataType}],dispatchGroup:{x:d},programUniforms:[{type:6,data:B}]}),getShaderSource:Me},{inputs:[p],outputs:[u?-1:0]})[0];u&&e.compute(pr(Oe,h),{inputs:[Oe]})},N=(e,t)=>{_(e.inputs),T(e,t)},fe=e=>Bt({axis:e.axis})}),Ae,et,rt,ft,Mt,jt=g(()=>{zt(),Ot(),Yt(),Ae=e=>Array.from(e.getBigInt64Array(),Number),et=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(Ae(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")},rt=(e,t)=>{let s=[];for(let n=0;n{let s=e[0].dims,n=t??Ae(e[1]),o=rt(s,n),a=ze.size(o),i=e[0].dataType,u=qe("input",i,s.length),p=It("output",i,o.length),h=k=>` - const inputShape = ${u.indices(...s)}; - ${k.registerUniform("output_size","u32").declareVariables(u,p)} - ${k.mainStart()} - ${k.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - let output_indices = ${p.offsetToIndices("global_idx")}; - var input_indices: ${u.type.indices}; - for (var i = 0; i < ${s.length}; i++) { - let input_dim_i = ${u.indicesGet("uniforms.input_shape","i")}; - let input_dim_value = ${p.indicesGet("output_indices","i")} % input_dim_i; - - ${u.indicesSet("input_indices","i","input_dim_value")} - } - ${p.setByOffset("global_idx",u.getByIndices("input_indices"))} - }`;return{name:"Tile",shaderCache:{hint:`${n}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:[{type:12,data:a},...yt(e[0].dims,o)]}),getShaderSource:h}},Mt=e=>{et(e.inputs),e.compute(ft(e.inputs),{inputs:[0]})}}),Vt,Lt,Gt,ts=g(()=>{zt(),Ot(),Yt(),Vt=(e,t,s,n,o)=>{let a=It("output_data",o,s.length,4),i=qe("a_data",t[1].dataType,t[1].dims.length,4),u=qe("b_data",t[2].dataType,t[2].dims.length,4),p=qe("c_data",t[0].dataType,t[0].dims.length,4),h,k=(C,d,z)=>`select(${d}, ${C}, ${z})`;if(!n)h=a.setByOffset("global_idx",k(i.getByOffset("global_idx"),u.getByOffset("global_idx"),p.getByOffset("global_idx")));else{let C=(d,z,B="")=>{let V=`a_data[index_a${z}][component_a${z}]`,Z=`b_data[index_b${z}][component_b${z}]`,ee=`bool(c_data[index_c${z}] & (0xffu << (component_c${z} * 8)))`;return` - let output_indices${z} = ${a.offsetToIndices(`global_idx * 4u + ${z}u`)}; - let offset_a${z} = ${i.broadcastedIndicesToOffset(`output_indices${z}`,a)}; - let offset_b${z} = ${u.broadcastedIndicesToOffset(`output_indices${z}`,a)}; - let offset_c${z} = ${p.broadcastedIndicesToOffset(`output_indices${z}`,a)}; - let index_a${z} = offset_a${z} / 4u; - let index_b${z} = offset_b${z} / 4u; - let index_c${z} = offset_c${z} / 4u; - let component_a${z} = offset_a${z} % 4u; - let component_b${z} = offset_b${z} % 4u; - let component_c${z} = offset_c${z} % 4u; - ${d}[${z}] = ${B}(${k(V,Z,ee)}); - `};o===9?h=` - var data = vec4(0); - ${C("data",0,"u32")} - ${C("data",1,"u32")} - ${C("data",2,"u32")} - ${C("data",3,"u32")} - output_data[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:h=` - ${C("output_data[global_idx]",0)} - ${C("output_data[global_idx]",1)} - ${C("output_data[global_idx]",2)} - ${C("output_data[global_idx]",3)} - `}return` - ${e.registerUniform("vec_size","u32").declareVariables(p,i,u,a)} - ${e.mainStart()} - ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} - ${h} - }`},Lt=e=>{let t=e[1].dims,s=e[2].dims,n=e[0].dims,o=e[1].dataType,a=!(ze.areEqual(t,s)&&ze.areEqual(s,n)),i=t,u=ze.size(t);if(a){let h=Ws.calcShape(Ws.calcShape(t,s,!1),n,!1);if(!h)throw new Error("Can't perform where op on the given tensors");i=h,u=ze.size(i)}let p=Math.ceil(u/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:h=>Vt(h,e,i,a,o),getRunData:()=>({outputs:[{dims:i,dataType:o}],dispatchGroup:{x:Math.ceil(u/64/4)},programUniforms:[{type:12,data:p},...yt(n,t,s,i)]})}},Gt=e=>{e.compute(Lt(e.inputs))}}),ns,Jt=g(()=>{Uc(),ui(),Vc(),Wc(),Gc(),Kc(),pu(),Xc(),Jc(),Zc(),ep(),tp(),sp(),rp(),np(),op(),ap(),lp(),Kp(),la(),pp(),xd(),hp(),mp(),Od(),_d(),Bd(),Mp(),Hp(),bp(),xp(),co(),Tp(),Pp(),qp(),Cp(),Fe(),pa(),jt(),Kr(),Ei(),ts(),ns=new Map([["Abs",[Tl]],["Acos",[mi]],["Acosh",[Pl]],["Add",[ki]],["ArgMax",[ni,oi]],["ArgMin",[fl,oi]],["Asin",[El]],["Asinh",[_i]],["Atan",[Cl]],["Atanh",[kl]],["Attention",[yl]],["AveragePool",[yp,Ta]],["BatchNormalization",[ci]],["BiasAdd",[xl]],["BiasSplitGelu",[Ci]],["Cast",[Sl,fi]],["Ceil",[Al]],["Clip",[gi]],["Concat",[du,cu]],["Conv",[vo,Qi]],["ConvTranspose",[Su,Ji]],["Cos",[Il]],["Cosh",[wi]],["CumSum",[$u,Au]],["DepthToSpace",[Fu,Du]],["DequantizeLinear",[qd,Qd]],["Div",[tu]],["Einsum",[Ru,Nu]],["Elu",[Ol,jn]],["Equal",[su]],["Erf",[Fl]],["Exp",[yi]],["Expand",[Wu]],["FastGelu",[Gu]],["Floor",[Dl]],["FusedConv",[vo,Qi]],["Gather",[qu,Hu]],["GatherElements",[sd,td]],["GatherBlockQuantized",[Ju,Zu]],["GatherND",[Co,Xu]],["Gelu",[Ll]],["Gemm",[ko,od]],["GlobalAveragePool",[jd,Nd]],["GlobalMaxPool",[Gd,Wd]],["Greater",[ou]],["GreaterOrEqual",[$i]],["GridSample",[cd,pd]],["GroupQueryAttention",[ha]],["HardSigmoid",[jl,vi]],["InstanceNormalization",[vd]],["LayerNormalization",[fa]],["LeakyRelu",[Mi,jn]],["Less",[iu]],["LessOrEqual",[au]],["Log",[ql]],["MatMul",[Cd]],["MatMulNBits",[Ad,Id]],["MaxPool",[Ud,Vd]],["Mul",[ru]],["MultiHeadAttention",[up,md]],["Neg",[Bl]],["Not",[zl]],["Pad",[gp]],["Pow",[nu]],["QuickGelu",[Xl,jn]],["Range",[Jd]],["Reciprocal",[bi]],["ReduceMin",[pl]],["ReduceMean",[ul]],["ReduceMax",[ti]],["ReduceSum",[si]],["ReduceProd",[hl]],["ReduceL1",[ei]],["ReduceL2",[dl]],["ReduceLogSum",[_l]],["ReduceLogSumExp",[cl]],["ReduceSumSquare",[ml]],["Relu",[Rl]],["Resize",[gc,wc]],["RotaryEmbedding",[bc]],["ScatterND",[Ea,vp]],["Sigmoid",[Nl]],["Sin",[Ul]],["Sinh",[xi]],["Slice",[Ep,Pc]],["SkipLayerNormalization",[Tc]],["Split",[yd,Md]],["Sqrt",[Vl]],["Softmax",[N,fe]],["Sub",[Si]],["Tan",[Wl]],["Tanh",[Gl]],["ThresholdedRelu",[Hl,jn]],["Tile",[Mt]],["Transpose",[Ua,Ko]],["Where",[Gt]]])}),is,As=g(()=>{We(),Pe(),Yt(),is=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,s,n,o){Ne(e.programInfo.name);let a=this.backend.device,i=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let u=[];for(let h of t)u.push({binding:u.length,resource:{buffer:h.buffer}});for(let h of s)u.push({binding:u.length,resource:{buffer:h.buffer}});o&&u.push({binding:u.length,resource:o});let p=a.createBindGroup({layout:e.computePipeline.getBindGroupLayout(0),entries:u,label:e.programInfo.name});if(this.backend.sessionStatus==="capturing"){let h={kernelId:this.backend.currentKernelId,computePipeline:e.computePipeline,bindGroup:p,dispatchGroup:n};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(h)}i.setPipeline(e.computePipeline),i.setBindGroup(0,p),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(),Re(e.programInfo.name)}dispose(){}build(e,t){Ne(e.name);let s=this.backend.device,n=[];[{feature:"shader-f16",extension:"f16"},{feature:"subgroups",extension:"subgroups"},{feature:"subgroups-f16",extension:"subgroups_f16"}].forEach(h=>{s.features.has(h.feature)&&n.push(`enable ${h.extension};`)});let o=Ba(t,this.backend.device.limits),a=e.getShaderSource(o),i=`${n.join(` -`)} -${o.additionalImplementations} -${a}`,u=s.createShaderModule({code:i,label:e.name});as("verbose",()=>`[WebGPU] ${e.name} shader code: ${i}`);let p=s.createComputePipeline({compute:{module:u,entryPoint:"main"},layout:"auto",label:e.name});return Re(e.name),{programInfo:e,computePipeline:p,uniformVariablesInfo:o.variablesInfo}}normalizeDispatchGroupSize(e){let t=typeof e=="number"?e:e.x,s=typeof e=="number"?1:e.y||1,n=typeof e=="number"?1:e.z||1,o=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(t<=o&&s<=o&&n<=o)return[t,s,n];let a=t*s*n,i=Math.ceil(Math.sqrt(a));if(i>o){if(i=Math.ceil(Math.cbrt(a)),i>o)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[i,i,i]}else return[i,i,1]}}}),xs,cs,Es,Is,Zs,Ys=g(()=>{We(),zt(),Pe(),Q(),us(),Jt(),As(),xs=(e,t)=>{if(t.length!==e.length)throw new Error(`inputDependencies length ${t.length} is not equal to inputTensors length ${e.length}.`);let s=[];for(let n=0;n{var o,a;let n=e.name;return(o=e.shaderCache)!=null&&o.hint&&(n+="["+e.shaderCache.hint+"]"),n+=":"+s+`:${xs(t,((a=e.shaderCache)==null?void 0:a.inputDependencies)??new Array(t.length).fill("dims"))}`,n},Es=class{constructor(e){e&&(this.architecture=e.architecture,this.vendor=e.vendor)}isArchitecture(e){return this.architecture===e}isVendor(e){return this.vendor===e}},Is=class{constructor(e){this.subgroupsSupported=e.features.has("subgroups"),this.subgroupsF16Supported=e.features.has("subgroups");let t=e.limits;!this.subgroupsSupported||!t.minSubgroupSize||!t.maxSubgroupSize?this.subgroupSizeRange=void 0:this.subgroupSizeRange=[t.minSubgroupSize,t.maxSubgroupSize]}},Zs=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 s=[],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:s},o=a=>t.features.has(a)&&s.push(a)&&!0;o("chromium-experimental-timestamp-query-inside-passes")||o("timestamp-query"),o("shader-f16"),o("subgroups")&&o("subgroups-f16"),this.device=await t.requestDevice(n),this.deviceInfo=new Is(this.device),this.adapterInfo=new Es(t.info||await t.requestAdapterInfo()),this.gpuDataManager=ms(this),this.programManager=new is(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,Tn(e.logLevel,!!e.debug),this.device.onuncapturederror=a=>{a.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${a.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;Ne(),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()),s=this.pendingQueries.get(e);for(let o=0;o"u"&&(this.queryTimeBase=z);let V=Number(z-this.queryTimeBase),Z=Number(B-this.queryTimeBase);if(!Number.isSafeInteger(V)||!Number.isSafeInteger(Z))throw new RangeError("incorrect timestamp range");if((n=this.env.webgpu.profiling)!=null&&n.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:C.map(ee=>({dims:ee.dims,dataType:_r(ee.dataType)})),outputsMetadata:d.map(ee=>({dims:ee.dims,dataType:_r(ee.dataType)})),kernelId:i,kernelType:p,kernelName:h,programName:k,startTime:V,endTime:Z});else{let ee="";C.forEach((he,pe)=>{ee+=`input[${pe}]: [${he.dims}] | ${_r(he.dataType)}, `});let X="";d.forEach((he,pe)=>{X+=`output[${pe}]: [${he.dims}] | ${_r(he.dataType)}, `}),console.log(`[profiling] kernel "${i}|${p}|${h}|${k}" ${ee}${X}execution time: ${Z-V} ns`)}Ue("GPU",`${k}::${z}::${B}`)}e.unmap(),this.pendingQueries.delete(e)}),Re()}run(e,t,s,n,o,a){Ne(e.name);let i=[];for(let X=0;Xhe):s;if(k.length!==u.length)throw new Error(`Output size ${k.length} must be equal to ${u.length}.`);let C=[],d=[];for(let X=0;X=a)throw new Error(`Invalid output index: ${k[X]}`);if(k[X]===-3)continue;let he=k[X]===-1,pe=k[X]===-2,Me=he||pe?o(u[X].dataType,u[X].dims):n(k[X],u[X].dataType,u[X].dims);if(C.push(Me),Me.data===0)continue;let Oe=this.gpuDataManager.get(Me.data);if(!Oe)throw new Error(`no GPU data for output: ${Me.data}`);if(he&&this.temporaryData.push(Oe),pe){let Le=this.kernelPersistentData.get(this.currentKernelId);Le||(Le=[],this.kernelPersistentData.set(this.currentKernelId,Le)),Le.push(Oe)}d.push(Oe)}if(i.length!==t.length||d.length!==C.length){if(d.length===0)return Re(e.name),C;throw new Error(`Program ${e.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let z;if(h){let X=0,he=[];h.forEach(Le=>{let Ye=typeof Le.data=="number"?[Le.data]:Le.data;if(Ye.length===0)return;let at=Le.type===10?2:4,Pt,Xt;Le.type===10?(Xt=Ye.length>4?16:Ye.length>2?8:Ye.length*at,Pt=Ye.length>4?16:at*Ye.length):(Xt=Ye.length<=2?Ye.length*at:16,Pt=16),X=Math.ceil(X/Xt)*Xt,he.push(X);let Zt=Le.type===10?8:4;X+=Ye.length>4?Math.ceil(Ye.length/Zt)*Pt:Ye.length*at});let pe=16;X=Math.ceil(X/pe)*pe;let Me=new ArrayBuffer(X);h.forEach((Le,Ye)=>{let at=he[Ye],Pt=typeof Le.data=="number"?[Le.data]:Le.data;if(Le.type===6)new Int32Array(Me,at,Pt.length).set(Pt);else if(Le.type===12)new Uint32Array(Me,at,Pt.length).set(Pt);else if(Le.type===10)new Uint16Array(Me,at,Pt.length).set(Pt);else if(Le.type===1)new Float32Array(Me,at,Pt.length).set(Pt);else throw new Error(`Unsupported uniform type: ${_r(Le.type)}`)});let Oe=this.gpuDataManager.create(X,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(Oe.buffer,0,Me,0,X),this.gpuDataManager.release(Oe.id),z={offset:0,size:X,buffer:Oe.buffer}}let B=this.programManager.normalizeDispatchGroupSize(p),V=B[1]===1&&B[2]===1,Z=cs(e,t,V),ee=this.programManager.getArtifact(Z);if(ee||(ee=this.programManager.build(e,B),this.programManager.setArtifact(Z,ee),as("info",()=>`[artifact] key: ${Z}, programName: ${e.name}`)),h&&ee.uniformVariablesInfo){if(h.length!==ee.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${ee.uniformVariablesInfo.length}, got ${h.length} in program "${ee.programInfo.name}".`);for(let X=0;X`[ProgramManager] run "${e.name}" (key=${Z}) with ${B[0]}x${B[1]}x${B[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let X={kernelId:this.currentKernelId,programName:ee.programInfo.name,inputTensorViews:t,outputTensorViews:C};this.pendingKernels.push(X),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(X)}return this.programManager.run(ee,i,d,B,z),Re(e.name),C}upload(e,t){this.gpuDataManager.upload(e,t)}memcpy(e,t){this.gpuDataManager.memcpy(e,t)}async download(e,t){await this.gpuDataManager.download(e,t)}alloc(e){return this.gpuDataManager.create(e).id}free(e){return this.gpuDataManager.release(e)}createKernel(e,t,s,n){let o=ns.get(e);if(!o)throw new Error(`kernel not implemented: ${e}`);let a={kernelType:e,kernelName:n,kernelEntry:o[0],attributes:[o[1],s]};this.kernels.set(t,a)}releaseKernel(e){let t=this.kernelPersistentData.get(e);if(t){for(let s of t)this.gpuDataManager.release(s.id);this.kernelPersistentData.delete(e)}this.kernelCustomData.delete(e),this.kernels.delete(e)}computeKernel(e,t,s){let n=this.kernels.get(e);if(!n)throw new Error(`kernel not created: ${e}`);let o=n.kernelType,a=n.kernelName,i=n.kernelEntry,u=n.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${o}] ${a}" is not allowed to be called recursively`);this.currentKernelId=e,u[0]&&(u[1]=u[0](u[1]),u[0]=void 0),as("info",()=>`[WebGPU] Start to run kernel "[${o}] ${a}"...`);let p=this.env.debug;this.temporaryData=[];try{return p&&this.device.pushErrorScope("validation"),i(t,u[1]),0}catch(h){return s.push(Promise.resolve(`[WebGPU] Kernel "[${o}] ${a}" failed. ${h}`)),1}finally{p&&s.push(this.device.popErrorScope().then(h=>h?`GPU validation error for kernel "[${o}] ${a}": ${h.message}`:null));for(let h of this.temporaryData)this.gpuDataManager.release(h.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(e,t,s,n){let o=this.sessionExternalDataMapping.get(e);o||(o=new Map,this.sessionExternalDataMapping.set(e,o));let a=o.get(t),i=this.gpuDataManager.registerExternalBuffer(s,n,a);return o.set(t,[i,s]),i}unregisterBuffers(e){let t=this.sessionExternalDataMapping.get(e);t&&(t.forEach(s=>this.gpuDataManager.unregisterExternalBuffer(s[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,s){return async()=>{let n=await xt(this,e,t);return P(n.buffer,s)}}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(){as("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(){as("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){as("info","replay"),this.sessionStatus="replaying";let e=this.capturedCommandList.get(this.currentSessionId),t=this.capturedPendingKernels.get(this.currentSessionId),s=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"}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()}}}),br,pn,ka,ir,vr,Io,Oo,Fo,Sa=g(()=>{Pe(),br=1,pn=()=>br++,ka=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),ir=(e,t)=>{let s=ka.get(e);if(!s)throw new Error("Unsupported data type.");return t.length>0?Math.ceil(t.reduce((n,o)=>n*o)*s/8):0},vr=class{constructor(e){this.sessionId=e.sessionId,this.mlContext=e.context,this.mlTensor=e.tensor,this.dataType=e.dataType,this.tensorShape=e.shape}get tensor(){return this.mlTensor}get type(){return this.dataType}get shape(){return this.tensorShape}get byteLength(){return ir(this.dataType,this.tensorShape)}destroy(){as("verbose",()=>"[WebNN] TensorWrapper.destroy"),this.mlTensor.destroy()}write(e){this.mlContext.writeTensor(this.mlTensor,e)}async read(e){return e?this.mlContext.readTensor(this.mlTensor,e):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(e,t,s){return this.mlContext===e&&this.dataType===t&&this.tensorShape.length===s.length&&this.tensorShape.every((n,o)=>n===s[o])}},Io=class{constructor(e,t){this.tensorManager=e,this.wrapper=t}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(e,t,s,n){if(this.wrapper){if(this.wrapper.canReuseTensor(e,t,s))return this.wrapper.tensor;if(n){if(this.wrapper.byteLength!==ir(t,s))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 o=typeof MLTensorUsage>"u"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(t,s,o,!0,!0),n&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(e){if(this.wrapper)if(e.byteLength===this.wrapper.byteLength){this.wrapper.write(e);return}else as("verbose",()=>"Data size does not match tensor size. Releasing tensor."),this.releaseTensor();this.activeUpload?this.activeUpload.set(e):this.activeUpload=new Uint8Array(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.wrapper)throw new Error("Tensor has not been created.");return e?this.wrapper.read(e):this.wrapper.read()}},Oo=class{constructor(e){this.backend=e,this.tensorTrackersById=new Map,this.freeTensors=[],this.externalTensors=new Set}reserveTensorId(){let e=pn();return this.tensorTrackersById.set(e,new Io(this)),e}releaseTensorId(e){let t=this.tensorTrackersById.get(e);t&&(this.tensorTrackersById.delete(e),t.tensorWrapper&&this.releaseTensor(t.tensorWrapper))}async ensureTensor(e,t,s,n){as("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${e}, dataType: ${t}, shape: ${s}, copyOld: ${n}}`);let o=this.tensorTrackersById.get(e);if(!o)throw new Error("Tensor not found.");return o.ensureTensor(this.backend.currentContext,t,s,n)}upload(e,t){let s=this.tensorTrackersById.get(e);if(!s)throw new Error("Tensor not found.");s.upload(t)}async download(e,t){as("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${e}, dstBuffer: ${t==null?void 0:t.byteLength}}`);let s=this.tensorTrackersById.get(e);if(!s)throw new Error("Tensor not found.");return s.download(t)}releaseTensorsForSession(e){for(let t of this.freeTensors)t.sessionId===e&&t.destroy();this.freeTensors=this.freeTensors.filter(t=>t.sessionId!==e)}registerTensor(e,t,s,n){let o=pn(),a=new vr({sessionId:this.backend.currentSessionId,context:e,tensor:t,dataType:s,shape:n});return this.tensorTrackersById.set(o,new Io(this,a)),this.externalTensors.add(a),o}async getCachedTensor(e,t,s,n,o){let a=this.backend.currentSessionId,i=this.backend.currentContext;for(let[p,h]of this.freeTensors.entries())if(h.canReuseTensor(i,e,t)){as("verbose",()=>`[WebNN] Reusing tensor {dataType: ${e}, shape: ${t}}`);let k=this.freeTensors.splice(p,1)[0];return k.sessionId=a,k}as("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${e}, shape: ${t}}`);let u=await i.createTensor({dataType:e,shape:t,dimensions:t,usage:s,writable:n,readable:o});return new vr({sessionId:a,context:i,tensor:u,dataType:e,shape:t})}releaseTensor(e){this.externalTensors.has(e)&&this.externalTensors.delete(e),this.freeTensors.push(e)}},Fo=(...e)=>new Oo(...e)}),Ts,Rs,qr,En=g(()=>{zt(),lr(),Q(),Sa(),Pe(),Ts=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),Rs=(e,t)=>{if(e===t)return!0;if(e===void 0||t===void 0)return!1;let s=Object.keys(e).sort(),n=Object.keys(t).sort();return s.length===n.length&&s.every((o,a)=>o===n[a]&&e[o]===t[o])},qr=class{constructor(e){this.tensorManager=Fo(this),this.mlContextBySessionId=new Map,this.sessionIdsByMLContext=new Map,this.mlContextCache=[],Tn(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}async createMLContext(e){if(e instanceof GPUDevice){let s=this.mlContextCache.findIndex(n=>n.gpuDevice===e);if(s!==-1)return this.mlContextCache[s].mlContext;{let n=await navigator.ml.createContext(e);return this.mlContextCache.push({gpuDevice:e,mlContext:n}),n}}else if(e===void 0){let s=this.mlContextCache.findIndex(n=>n.options===void 0&&n.gpuDevice===void 0);if(s!==-1)return this.mlContextCache[s].mlContext;{let n=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:n}),n}}let t=this.mlContextCache.findIndex(s=>Rs(s.options,e));if(t!==-1)return this.mlContextCache[t].mlContext;{let s=await navigator.ml.createContext(e);return this.mlContextCache.push({options:e,mlContext:s}),s}}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 s=this.sessionIdsByMLContext.get(t);s||(s=new Set,this.sessionIdsByMLContext.set(t,s)),s.add(e)}onReleaseSession(e){let t=this.mlContextBySessionId.get(e);if(!t)return;this.tensorManager.releaseTensorsForSession(e),this.mlContextBySessionId.delete(e);let s=this.sessionIdsByMLContext.get(t);if(s.delete(e),s.size===0){this.sessionIdsByMLContext.delete(t);let n=this.mlContextCache.findIndex(o=>o.mlContext===t);n!==-1&&this.mlContextCache.splice(n,1)}}getMLContext(e){return this.mlContextBySessionId.get(e)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(e){as("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,t,s,n){let o=Ts.get(t);if(!o)throw new Error(`Unsupported ONNX data type: ${t}`);return this.tensorManager.ensureTensor(e,o,s,n)}uploadTensor(e,t){if(!Ms().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");as("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 s=await this.tensorManager.download(e);return P(s,t)}}registerMLTensor(e,t,s){let n=Ts.get(t);if(!n)throw new Error(`Unsupported ONNX data type: ${t}`);let o=this.tensorManager.registerTensor(this.currentContext,e,n,s);return as("verbose",()=>`[WebNN] registerMLTensor {tensor: ${e}, dataType: ${n}, dimensions: ${s}} -> {tensorId: ${o}}`),o}registerMLConstant(e,t,s,n,o,a){if(!a)throw new Error("External mounted files are not available.");let i=e;e.startsWith("./")&&(i=e.substring(2));let u=a.get(i);if(!u)throw new Error(`File with name ${i} not found in preloaded files.`);if(t+s>u.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let p=u.slice(t,t+s).buffer,h;switch(o.dataType){case"float32":h=new Float32Array(p);break;case"float16":h=new Uint16Array(p);break;case"int32":h=new Int32Array(p);break;case"uint32":h=new Uint32Array(p);break;case"int64":h=new BigInt64Array(p);break;case"uint64":h=new BigUint64Array(p);break;case"int8":h=new Int8Array(p);break;case"int4":case"uint4":case"uint8":h=new Uint8Array(p);break;default:throw new Error(`Unsupported data type: ${o.dataType} in creating WebNN Constant from external data.`)}return as("verbose",()=>`[WebNN] registerMLConstant {dataType: ${o.dataType}, shape: ${o.shape}}}`),n.constant(o,h)}flush(){}}}),Cn={};v(Cn,{init:()=>Aa});var kn,$a,Aa,Ec=g(()=>{zt(),Ys(),Pe(),Ot(),En(),kn=class s_{constructor(t,s,n,o){this.module=t,this.dataType=s,this.data=n,this.dims=o}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let t=ze.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=ze.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=ze.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=ze.size(this.dims);return t===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,t)}reshape(t){if(ze.size(t)!==ze.size(this.dims))throw new Error("Invalid new shape");return new s_(this.module,this.dataType,this.data,t)}},$a=class{constructor(e,t,s){this.module=e,this.backend=t,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=t.adapterInfo,this.deviceInfo=t.deviceInfo;let n=e.PTR_SIZE,o=s/e.PTR_SIZE,a=n===4?"i32":"i64";this.opKernelContext=Number(e.getValue(n*o++,a));let i=Number(e.getValue(n*o++,a));this.outputCount=Number(e.getValue(n*o++,a)),this.customDataOffset=Number(e.getValue(n*o++,"*")),this.customDataSize=Number(e.getValue(n*o++,a));let u=[];for(let p=0;ptypeof u=="number"?this.inputs[u]:u))??this.inputs,n=(t==null?void 0:t.outputs)??[],o=(u,p,h)=>new kn(this.module,p,this.output(u,h),h),a=(u,p)=>{let h=ur(u,p);if(!h)throw new Error(`Unsupported data type: ${u}`);let k=h>0?this.backend.gpuDataManager.create(h).id:0;return new kn(this.module,u,k,p)};return this.backend.run(e,s,n,o,a,this.outputCount)}output(e,t){let s=this.module.stackSave();try{let n=this.module.PTR_SIZE,o=n===4?"i32":"i64",a=this.module.stackAlloc((1+t.length)*n);this.module.setValue(a,t.length,o);for(let i=0;i{let o=t.jsepInit;if(!o)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(e==="webgpu"){let a=new Zs;await a.initialize(s,n),o("webgpu",[a,i=>a.alloc(Number(i)),i=>a.free(i),(i,u,p,h=!1)=>{if(h)as("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${Number(i)}, dst=${Number(u)}, size=${Number(p)}`),a.memcpy(Number(i),Number(u));else{as("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(i)}, gpuDataId=${Number(u)}, size=${Number(p)}`);let k=t.HEAPU8.subarray(Number(i>>>0),Number(i>>>0)+Number(p));a.upload(Number(u),k)}},async(i,u,p)=>{as("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${i}, dataOffset=${u}, size=${p}`),await a.download(Number(i),()=>t.HEAPU8.subarray(Number(u)>>>0,Number(u+p)>>>0))},(i,u,p)=>a.createKernel(i,Number(u),p,t.UTF8ToString(t._JsepGetNodeName(Number(u)))),i=>a.releaseKernel(i),(i,u,p,h)=>{as("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${p}, kernel=${i}, contextDataOffset=${u}`);let k=new $a(t,a,Number(u));return a.computeKernel(Number(i),k,h)},()=>a.captureBegin(),()=>a.captureEnd(),()=>a.replay()])}else{let a=new qr(s);o("webnn",[a,()=>a.reserveTensorId(),i=>a.releaseTensorId(i),async(i,u,p,h)=>a.ensureTensor(i,u,p,h),(i,u)=>{a.uploadTensor(i,u)},async(i,u)=>a.downloadTensor(i,u)])}}}),kp,Do,qn,zr,Cc,Qn,Xn,kc,Sc,$c,Qr,mr,vh=g(()=>{oo(),io(),zt(),lr(),wn(),Dn(),kp=(e,t)=>{Ms()._OrtInit(e,t)!==0&&es("Can't initialize onnxruntime.")},Do=async e=>{kp(e.wasm.numThreads,tn(e.logLevel))},qn=async(e,t)=>{{let s=(Ec(),y(Cn)).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 o=e.webgpu.powerPreference;if(o!==void 0&&o!=="low-power"&&o!=="high-performance")throw new Error(`Invalid powerPreference setting: "${o}"`);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:o,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 s("webgpu",Ms(),e,n)}if(t==="webnn"){if(typeof navigator>"u"||!navigator.ml)throw new Error("WebNN is not supported in current environment");await s("webnn",Ms(),e)}}},zr=new Map,Cc=e=>{let t=Ms(),s=t.stackSave();try{let n=t.PTR_SIZE,o=t.stackAlloc(2*n);t._OrtGetInputOutputCount(e,o,o+n)!==0&&es("Can't get session input/output count.");let a=n===4?"i32":"i64";return[Number(t.getValue(o,a)),Number(t.getValue(o+n,a))]}finally{t.stackRestore(s)}},Qn=e=>{let t=Ms(),s=t._malloc(e.byteLength);if(s===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,s),[s,e.byteLength]},Xn=async(e,t)=>{var C,d,z;let s,n,o=Ms();Array.isArray(e)?[s,n]=e:e.buffer===o.HEAPU8.buffer?[s,n]=[e.byteOffset,e.byteLength]:[s,n]=Qn(e);let a=0,i=0,u=0,p=[],h=[],k=[];try{if([i,p]=Fn(t),(t==null?void 0:t.externalData)&&o.mountExternalData){let Me=[];for(let Oe of t.externalData){let Le=typeof Oe=="string"?Oe:Oe.path;Me.push(xn(typeof Oe=="string"?Oe:Oe.data).then(Ye=>{o.mountExternalData(Le,Ye)}))}await Promise.all(Me)}for(let Me of(t==null?void 0:t.executionProviders)??[])if((typeof Me=="string"?Me:Me.name)==="webnn"){if(o.shouldTransferToMLTensor=!1,typeof Me!="string"){let Oe=Me,Le=Oe==null?void 0:Oe.context,Ye=Oe==null?void 0:Oe.gpuDevice,at=Oe==null?void 0:Oe.deviceType,Pt=Oe==null?void 0:Oe.powerPreference;Le?o.currentContext=Le:Ye?o.currentContext=await o.jsepCreateMLContext(Ye):o.currentContext=await o.jsepCreateMLContext({deviceType:at,powerPreference:Pt})}else o.currentContext=await o.jsepCreateMLContext();break}a=await o._OrtCreateSession(s,n,i),a===0&&es("Can't create a session."),(C=o.jsepOnCreateSession)==null||C.call(o),o.currentContext&&(o.jsepRegisterMLContext(a,o.currentContext),o.currentContext=void 0,o.shouldTransferToMLTensor=!0);let[B,V]=Cc(a),Z=!!(t!=null&&t.enableGraphCapture),ee=[],X=[],he=[];for(let Me=0;MeMe==="gpu-buffer"||Me==="ml-tensor")&&(u=o._OrtCreateBinding(a),u===0&&es("Can't create IO binding."),pe={handle:u,outputPreferredLocations:he,outputPreferredLocationsEncoded:he.map(Me=>vn(Me))}),zr.set(a,[a,h,k,pe,Z,!1]),[a,ee,X]}catch(B){throw h.forEach(V=>o._OrtFree(V)),k.forEach(V=>o._OrtFree(V)),u!==0&&o._OrtReleaseBinding(u)!==0&&es("Can't release IO binding."),a!==0&&o._OrtReleaseSession(a)!==0&&es("Can't release session."),B}finally{o._free(s),i!==0&&o._OrtReleaseSessionOptions(i)!==0&&es("Can't release session options."),p.forEach(B=>o._free(B)),(z=o.unmountExternalData)==null||z.call(o)}},kc=e=>{var p;let t=Ms(),s=zr.get(e);if(!s)throw new Error(`cannot release session. invalid session id: ${e}`);let[n,o,a,i,u]=s;i&&(u&&t._OrtClearBoundOutputs(i.handle)!==0&&es("Can't clear bound outputs."),t._OrtReleaseBinding(i.handle)!==0&&es("Can't release IO binding.")),(p=t.jsepOnReleaseSession)==null||p.call(t,e),o.forEach(h=>t._OrtFree(h)),a.forEach(h=>t._OrtFree(h)),t._OrtReleaseSession(n)!==0&&es("Can't release session."),zr.delete(e)},Sc=(e,t,s,n,o,a=!1)=>{if(!e){t.push(0);return}let i=Ms(),u=i.PTR_SIZE,p=e[0],h=e[1],k=e[3],C,d;if(p==="string"&&(k==="gpu-buffer"||k==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(a&&k!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${o} when enableGraphCapture is true.`);if(k==="gpu-buffer"){let V=e[2].gpuBuffer;d=ur(Wr(p),h);let Z=i.jsepRegisterBuffer;if(!Z)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');C=Z(n,o,V,d)}else if(k==="ml-tensor"){let V=e[2].mlTensor;d=ur(Wr(p),h);let Z=i.jsepRegisterMLTensor;if(!Z)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');C=Z(V,Wr(p),h)}else{let V=e[2];if(Array.isArray(V)){d=u*V.length,C=i._malloc(d),s.push(C);for(let Z=0;Zi.setValue(B+ee*u,Z,u===4?"i32":"i64"));let V=i._OrtCreateTensor(Wr(p),C,d,B,h.length,vn(k));V===0&&es(`Can't create tensor for input/output. session=${n}, index=${o}.`),t.push(V)}finally{i.stackRestore(z)}},$c=async(e,t,s,n,o,a)=>{var Xt,Zt;let i=Ms(),u=i.PTR_SIZE,p=zr.get(e);if(!p)throw new Error(`cannot run inference. invalid session id: ${e}`);let h=p[0],k=p[1],C=p[2],d=p[3],z=p[4],B=p[5],V=t.length,Z=n.length,ee=0,X=[],he=[],pe=[],Me=[],Oe=i.stackSave(),Le=i.stackAlloc(V*u),Ye=i.stackAlloc(V*u),at=i.stackAlloc(Z*u),Pt=i.stackAlloc(Z*u);try{(Xt=i.jsepOnRunStart)==null||Xt.call(i,h),[ee,X]=Ur(a);for(let St=0;Stzs*Ps,1);fs=_r(ps);let Bo=d==null?void 0:d.outputPreferredLocations[n[St]];if(fs==="string"){if(Bo==="gpu-buffer"||Bo==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let zs=[];for(let Ps=0;Ps0){let zs=i.jsepGetBuffer;if(!zs)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let Ps=zs(it),Jn=ur(ps,hn);if(Jn===void 0||!Mn(fs))throw new Error(`Unsupported data type: ${fs}`);Rt=!0,ss.push([fs,er,{gpuBuffer:Ps,download:i.jsepCreateDownloader(Ps,Jn,fs),dispose:()=>{i._OrtReleaseTensor(Ft)!==0&&es("Can't release tensor.")}},"gpu-buffer"])}else if(Bo==="ml-tensor"&&hn>0){let zs=i.jsepEnsureTensor;if(!zs)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(ur(ps,hn)===void 0||!bn(fs))throw new Error(`Unsupported data type: ${fs}`);let Ps=await zs(it,ps,er,!1);Rt=!0,ss.push([fs,er,{mlTensor:Ps,download:i.jsepCreateMLTensorDownloader(it,fs),dispose:()=>{i.jsepReleaseTensorId(it),i._OrtReleaseTensor(Ft)}},"ml-tensor"])}else{let zs=yn(fs),Ps=new zs(hn);new Uint8Array(Ps.buffer,Ps.byteOffset,Ps.byteLength).set(i.HEAPU8.subarray(it,it+Ps.byteLength)),ss.push([fs,er,Ps,"cpu"])}}finally{i.stackRestore(bs),fs==="string"&&it&&i._free(it),Rt||i._OrtReleaseTensor(Ft)}}return d&&!z&&(i._OrtClearBoundOutputs(d.handle)!==0&&es("Can't clear bound outputs."),zr.set(e,[h,k,C,d,z,!1])),ss}finally{i.stackRestore(Oe),he.forEach(bt=>i._OrtReleaseTensor(bt)),pe.forEach(bt=>i._OrtReleaseTensor(bt)),Me.forEach(bt=>i._free(bt)),ee!==0&&i._OrtReleaseRunOptions(ee),X.forEach(bt=>i._free(bt))}},Qr=e=>{let t=Ms(),s=zr.get(e);if(!s)throw new Error("invalid session id");let n=s[0],o=t._OrtEndProfiling(n);o===0&&es("Can't get an profile file name."),t._OrtFree(o)},mr=e=>{let t=[];for(let s of e){let n=s[2];!Array.isArray(n)&&"buffer"in n&&t.push(n.buffer)}return t}}),Yn,xr,Ia,Ac,Ic,Sp,Qp,$p,Lo,zo,xh,Th,Ph,Eh,Ch,kh,Sh,$h,Ah=g(()=>{We(),vh(),lr(),Nr(),Yn=()=>!!O.wasm.proxy&&typeof document<"u",Ia=!1,Ac=!1,Ic=!1,$p=new Map,Lo=(e,t)=>{let s=$p.get(e);s?s.push(t):$p.set(e,[t])},zo=()=>{if(Ia||!Ac||Ic||!xr)throw new Error("worker not ready")},xh=e=>{switch(e.data.type){case"init-wasm":Ia=!1,e.data.err?(Ic=!0,Qp[1](e.data.err)):(Ac=!0,Qp[0]()),Sp&&(URL.revokeObjectURL(Sp),Sp=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let t=$p.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}}},Th=async()=>{if(!Ac){if(Ia)throw new Error("multiple calls to 'initWasm()' detected.");if(Ic)throw new Error("previous call to 'initWasm()' failed.");if(Ia=!0,Yn())return new Promise((e,t)=>{xr==null||xr.terminate(),en().then(([s,n])=>{var o;try{xr=n,xr.onerror=i=>t(i),xr.onmessage=xh,Qp=[e,t];let a={type:"init-wasm",in:O};!a.in.wasm.wasmPaths&&(s||(o=self.location.href)!=null&&o.startsWith("file:"))&&(a.in.wasm.wasmPaths={wasm:new URL(r("./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm"),r.b).href}),xr.postMessage(a),Sp=s}catch(a){t(a)}},t)});try{await Or(O.wasm),await Do(O),Ac=!0}catch(e){throw Ic=!0,e}finally{Ia=!1}}},Ph=async e=>{if(Yn())return zo(),new Promise((t,s)=>{Lo("init-ep",[t,s]);let n={type:"init-ep",in:{epName:e,env:O}};xr.postMessage(n)});await qn(O,e)},Eh=async e=>Yn()?(zo(),new Promise((t,s)=>{Lo("copy-from",[t,s]);let n={type:"copy-from",in:{buffer:e}};xr.postMessage(n,[e.buffer])})):Qn(e),Ch=async(e,t)=>{if(Yn()){if(t!=null&&t.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return zo(),new Promise((s,n)=>{Lo("create",[s,n]);let o={type:"create",in:{model:e,options:{...t}}},a=[];e instanceof Uint8Array&&a.push(e.buffer),xr.postMessage(o,a)})}else return Xn(e,t)},kh=async e=>{if(Yn())return zo(),new Promise((t,s)=>{Lo("release",[t,s]);let n={type:"release",in:e};xr.postMessage(n)});kc(e)},Sh=async(e,t,s,n,o,a)=>{if(Yn()){if(s.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 zo(),new Promise((i,u)=>{Lo("run",[i,u]);let p=s,h={type:"run",in:{sessionId:e,inputIndices:t,inputs:p,outputIndices:n,options:a}};xr.postMessage(h,mr(p))})}else return $c(e,t,s,n,o,a)},$h=async e=>{if(Yn())return zo(),new Promise((t,s)=>{Lo("end-profiling",[t,s]);let n={type:"end-profiling",in:e};xr.postMessage(n)});Qr(e)}}),Xp,Ih,Oh,h_=g(()=>{We(),Ah(),zt(),Je(),Dn(),Xp=(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()}`)}},Ih=e=>{switch(e[3]){case"cpu":return new le(e[0],e[2],e[1]);case"gpu-buffer":{let t=e[0];if(!Mn(t))throw new Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:s,download:n,dispose:o}=e[2];return le.fromGpuBuffer(s,{dataType:t,dims:e[1],download:n,dispose:o})}case"ml-tensor":{let t=e[0];if(!bn(t))throw new Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:s,download:n,dispose:o}=e[2];return le.fromMLTensor(s,{dataType:t,dims:e[1],download:n,dispose:o})}default:throw new Error(`invalid data location: ${e[3]}`)}},Oh=class{async fetchModelAndCopyToWasmMemory(e){return Eh(await xn(e))}async loadModel(e,t){Ne();let s;typeof e=="string"?s=await this.fetchModelAndCopyToWasmMemory(e):s=e,[this.sessionId,this.inputNames,this.outputNames]=await Ch(s,t),Re()}async dispose(){return kh(this.sessionId)}async run(e,t,s){Ne();let n=[],o=[];Object.entries(e).forEach(C=>{let d=C[0],z=C[1],B=this.inputNames.indexOf(d);if(B===-1)throw new Error(`invalid input '${d}'`);n.push(z),o.push(B)});let a=[],i=[];Object.entries(t).forEach(C=>{let d=C[0],z=C[1],B=this.outputNames.indexOf(d);if(B===-1)throw new Error(`invalid output '${d}'`);a.push(z),i.push(B)});let u=n.map((C,d)=>Xp(C,()=>`input "${this.inputNames[o[d]]}"`)),p=a.map((C,d)=>C?Xp(C,()=>`output "${this.outputNames[i[d]]}"`):null),h=await Sh(this.sessionId,o,u,i,p,s),k={};for(let C=0;CJp,initializeFlags:()=>Yp,wasmBackend:()=>Dh});var Yp,Jp,Dh,m_=g(()=>{We(),Ah(),h_(),Yp=()=>{if((typeof O.wasm.initTimeout!="number"||O.wasm.initTimeout<0)&&(O.wasm.initTimeout=0),O.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 O.wasm.proxy!="boolean"&&(O.wasm.proxy=!1),typeof O.wasm.trace!="boolean"&&(O.wasm.trace=!1),typeof O.wasm.numThreads!="number"||!Number.isInteger(O.wasm.numThreads)||O.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)O.wasm.numThreads=1;else{let e=typeof navigator>"u"?R("node:os").cpus().length:navigator.hardwareConcurrency;O.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},Jp=class{async init(e){Yp(),await Th(),await Ph(e)}async createInferenceSessionHandler(e,t){let s=new Oh;return await s.loadModel(e,t),Promise.resolve(s)}},Dh=new Jp});We(),We(),We();var __="1.21.0-dev.20250114-228dd16893",f_=$e;{let e=(m_(),y(Fh)).wasmBackend;K("webgpu",e,5),K("webnn",e,5),K("cpu",e,10),K("wasm",e,10)}Object.defineProperty(O.versions,"web",{value:__,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":(De,A,r)=>{var f;r.r(A),r.d(A,{Tensor:()=>R.Tensor,createInferenceSession:()=>ne,deviceToExecutionProviders:()=>K,isONNXProxy:()=>q,isONNXTensor:()=>W});var D=r("./src/env.js"),U=r("?2ce3"),Y=r("./node_modules/onnxruntime-web/dist/ort.bundle.min.mjs?3a96"),R=r("./node_modules/onnxruntime-common/dist/esm/index.js");const g=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"}}),v=[];let M,y;const b=Symbol.for("onnxruntime");if(b in globalThis)y=globalThis[b];else if(D.apis.IS_NODE_ENV){switch(y=U??(f||(f=r.t(U,2))),process.platform){case"win32":v.push("dml");break;case"linux":process.arch==="x64"&&v.push("cuda");break}v.push("cpu"),M=["cpu"]}else y=Y,D.apis.IS_WEBNN_AVAILABLE&&v.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),D.apis.IS_WEBGPU_AVAILABLE&&v.push("webgpu"),v.push("wasm"),M=["wasm"];const I=y.InferenceSession;function K($=null){if(!$)return M;switch($){case"auto":return v;case"gpu":return v.filter(S=>["webgpu","cuda","dml","webnn-gpu"].includes(S))}if(v.includes($))return[g[$]??$];throw new Error(`Unsupported device: "${$}". Should be one of: ${v.join(", ")}.`)}let te=null;async function ne($,S,w){te&&await te;const x=I.create($,S);te??(te=x);const O=await x;return O.config=w,O}function W($){return $ instanceof y.Tensor}const j=y==null?void 0:y.env;j!=null&&j.wasm&&(j.wasm.wasmPaths=`https://cdn.jsdelivr.net/npm/@huggingface/transformers@${D.env.version}/dist/`,j.wasm.proxy=!1,(typeof crossOriginIsolated>"u"||!crossOriginIsolated)&&(j.wasm.numThreads=1)),j!=null&&j.webgpu&&(j.webgpu.powerPreference="high-performance");function q(){var $;return($=j==null?void 0:j.wasm)==null?void 0:$.proxy}D.env.backends.onnx=j},"./src/base/feature_extraction_utils.js":(De,A,r)=>{r.r(A),r.d(A,{FeatureExtractor:()=>Y,validate_audio_inputs:()=>R});var f=r("./src/utils/constants.js"),D=r("./src/utils/generic.js"),U=r("./src/utils/hub.js");class Y extends D.Callable{constructor(v){super(),this.config=v}static async from_pretrained(v,M){const y=await(0,U.getModelJSON)(v,f.FEATURE_EXTRACTOR_NAME,!0,M);return new this(y)}}function R(g,v){var M;if(!(g instanceof Float32Array||g instanceof Float64Array))throw new Error(`${v} expects input to be a Float32Array or a Float64Array, but got ${((M=g==null?void 0:g.constructor)==null?void 0:M.name)??typeof g} 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":(De,A,r)=>{r.r(A),r.d(A,{ImageProcessor:()=>$,center_to_corners_format:()=>y,post_process_instance_segmentation:()=>q,post_process_object_detection:()=>b,post_process_panoptic_segmentation:()=>j,post_process_semantic_segmentation:()=>I});var f=r("./src/utils/generic.js"),D=r("./src/utils/tensor.js"),U=r("./src/utils/maths.js");r("./src/utils/image.js");var Y=r("./src/utils/core.js"),R=r("./src/utils/hub.js"),g=r("./src/utils/constants.js");function v(S,w,x=0,O=null){const ae=S/w;let oe=(0,U.bankers_round)(ae)*w;return O!==null&&oe>O&&(oe=Math.floor(ae)*w),oew&&J.push(Ce)}else{let Ce=(0,U.max)(ye.data)[1];if(Ce===re-1||(de=(0,U.softmax)(ye.data),de[Ce]Ze*ke[(se+1)%2])),Ie.boxes.push(Be),Ie.classes.push(Ce),Ie.scores.push(de[Ce])}}xe.push(Ie)}return xe}function I(S,w=null){const x=S.logits,O=x.dims[0];if(w!==null&&w.length!==O)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const ae=[];for(let oe=0;oeke[J]&&(ke[J]=ye[J],Ie[J]=Ge)}const Ee=new Array(we.dims[0]);for(let Ge=0;GeGe!==void 0);ae.push({segmentation:ce,labels:tt})}return ae}function K(S,w,x,O){const ae=[],oe=[],ve=[];for(let we=0;wex&&(ae.push(xe),oe.push(Ie),ve.push(ce))}return[ae,oe,ve]}function te(S,w,x,O=.5,ae=.8){const oe=[];let ve=0,we=0;const re=w[x].data;for(let ce=0;ce=O&&++we;let xe=ve>0&&we>0;return xe&&(xe=ve/we>ae),[xe,oe]}function ne(S,w,x,O,ae,oe=null,ve=null){const[we,re]=ve??S[0].dims,xe=new D.Tensor("int32",new Int32Array(we*re),[we,re]),ce=[];if(ve!==null)for(let Ge=0;GeIe[de]&&(ke[de]=Ge,Ie[de]=J[de])}let Ee=0;const tt=xe.data;for(let Ge=0;Ge200)throw new Error(`absolute aspect ratio must be smaller than 200, got ${Math.max(S,w)/Math.min(S,w)}`);let oe=Math.round(S/x)*x,ve=Math.round(w/x)*x;if(oe*ve>ae){const we=Math.sqrt(S*w/ae);oe=Math.floor(S/we/x)*x,ve=Math.floor(w/we/x)*x}else if(oe*veoe?xe=Math.floor(oe*re/ae):oe>ae&&(re=Math.floor(ae*xe/oe)),await w.resize(xe,re,{resample:O}))}async crop_margin(w,x=200){const O=w.clone().grayscale(),ae=(0,U.min)(O.data)[0],ve=(0,U.max)(O.data)[0]-ae;if(ve===0)return w;const we=x/255;let re=O.width,xe=O.height,ce=0,ke=0;const Ie=O.data;for(let Ee=0;Eethis.preprocess(oe)));return{pixel_values:(0,D.stack)(O.map(oe=>oe.pixel_values),0),original_sizes:O.map(oe=>oe.original_size),reshaped_input_sizes:O.map(oe=>oe.reshaped_input_size)}}static async from_pretrained(w,x){const O=await(0,R.getModelJSON)(w,g.IMAGE_PROCESSOR_NAME,!0,x);return new this(O)}}},"./src/base/processing_utils.js":(De,A,r)=>{r.r(A),r.d(A,{Processor:()=>Y});var f=r("./src/utils/constants.js"),D=r("./src/utils/generic.js"),U=r("./src/utils/hub.js");class Y extends D.Callable{constructor(g,v){super(),this.config=g,this.components=v}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(g,v={}){if(!this.tokenizer)throw new Error("Unable to apply chat template without a tokenizer.");return this.tokenizer.apply_chat_template(g,{tokenize:!1,...v})}batch_decode(...g){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.batch_decode(...g)}decode(...g){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.decode(...g)}async _call(g,...v){for(const M of[this.image_processor,this.feature_extractor,this.tokenizer])if(M)return M(g,...v);throw new Error("No image processor, feature extractor, or tokenizer found.")}static async from_pretrained(g,v){const[M,y]=await Promise.all([this.uses_processor_config?(0,U.getModelJSON)(g,f.PROCESSOR_NAME,!0,v):{},Promise.all(this.classes.filter(b=>b in this).map(async b=>{const I=await this[b].from_pretrained(g,v);return[b.replace(/_class$/,""),I]})).then(Object.fromEntries)]);return new this(M,y)}}_e(Y,"classes",["image_processor_class","tokenizer_class","feature_extractor_class"]),_e(Y,"uses_processor_config",!1)},"./src/configs.js":(De,A,r)=>{r.r(A),r.d(A,{AutoConfig:()=>v,PretrainedConfig:()=>g,getKeyValueShapes:()=>R});var f=r("./src/utils/core.js"),D=r("./src/utils/hub.js");async function U(M,y){return await(0,D.getModelJSON)(M,"config.json",!0,y)}function Y(M){const y={};let b={};switch(M.model_type){case"llava":case"paligemma":case"florence2":case"llava_onevision":case"idefics3":b=Y(M.text_config);break;case"moondream1":b=Y(M.phi_config);break;case"musicgen":b=Y(M.decoder);break;case"multi_modality":b=Y(M.language_config);break;case"gpt2":case"gptj":case"jais":case"codegen":case"gpt_bigcode":y.num_heads="n_head",y.num_layers="n_layer",y.hidden_size="n_embd";break;case"gpt_neox":case"stablelm":case"opt":case"falcon":y.num_heads="num_attention_heads",y.num_layers="num_hidden_layers",y.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":y.num_heads="num_key_value_heads",y.num_layers="num_hidden_layers",y.hidden_size="hidden_size",y.num_attention_heads="num_attention_heads";break;case"gemma":case"gemma2":case"glm":case"helium":y.num_heads="num_key_value_heads",y.num_layers="num_hidden_layers",y.dim_kv="head_dim";break;case"openelm":y.num_heads="num_kv_heads",y.num_layers="num_transformer_layers",y.dim_kv="head_dim";break;case"gpt_neo":case"donut-swin":y.num_heads="num_heads",y.num_layers="num_layers",y.hidden_size="hidden_size";break;case"bloom":y.num_heads="n_head",y.num_layers="n_layer",y.hidden_size="hidden_size";break;case"mpt":y.num_heads="n_heads",y.num_layers="n_layers",y.hidden_size="d_model";break;case"exaone":y.num_heads="num_key_value_heads",y.num_layers="num_layers",y.dim_kv="head_dim",y.num_attention_heads="num_attention_heads";break;case"t5":case"mt5":case"longt5":y.num_decoder_layers="num_decoder_layers",y.num_decoder_heads="num_heads",y.decoder_dim_kv="d_kv",y.num_encoder_layers="num_layers",y.num_encoder_heads="num_heads",y.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":y.num_decoder_layers="decoder_layers",y.num_decoder_heads="decoder_attention_heads",y.decoder_hidden_size="d_model",y.num_encoder_layers="encoder_layers",y.num_encoder_heads="encoder_attention_heads",y.encoder_hidden_size="d_model";break;case"speecht5":y.num_decoder_layers="decoder_layers",y.num_decoder_heads="decoder_attention_heads",y.decoder_hidden_size="hidden_size",y.num_encoder_layers="encoder_layers",y.num_encoder_heads="encoder_attention_heads",y.encoder_hidden_size="hidden_size";break;case"trocr":y.num_encoder_layers=y.num_decoder_layers="decoder_layers",y.num_encoder_heads=y.num_decoder_heads="decoder_attention_heads",y.encoder_hidden_size=y.decoder_hidden_size="d_model";break;case"musicgen_decoder":y.num_encoder_layers=y.num_decoder_layers="num_hidden_layers",y.num_encoder_heads=y.num_decoder_heads="num_attention_heads",y.encoder_hidden_size=y.decoder_hidden_size="hidden_size";break;case"moonshine":y.num_decoder_layers="decoder_num_hidden_layers",y.num_decoder_heads="decoder_num_key_value_heads",y.num_encoder_layers="encoder_num_hidden_layers",y.num_encoder_heads="encoder_num_key_value_heads",y.encoder_hidden_size=y.decoder_hidden_size="hidden_size";break;case"vision-encoder-decoder":const K=Y(M.decoder),te="num_decoder_layers"in K,ne=(0,f.pick)(M,["model_type","is_encoder_decoder"]);return te?(ne.num_decoder_layers=K.num_decoder_layers,ne.num_decoder_heads=K.num_decoder_heads,ne.decoder_hidden_size=K.decoder_hidden_size,ne.num_encoder_layers=K.num_encoder_layers,ne.num_encoder_heads=K.num_encoder_heads,ne.encoder_hidden_size=K.encoder_hidden_size):(ne.num_layers=K.num_layers,ne.num_heads=K.num_heads,ne.hidden_size=K.hidden_size),ne}const I={...b,...(0,f.pick)(M,["model_type","multi_query","is_encoder_decoder"])};for(const K in y)I[K]=M[y[K]];return I}function R(M,{prefix:y="past_key_values",batch_size:b=1}={}){const I={},K=M.normalized_config;if(K.is_encoder_decoder&&"num_encoder_heads"in K&&"num_decoder_heads"in K){const te=K.encoder_dim_kv??K.encoder_hidden_size/K.num_encoder_heads,ne=K.decoder_dim_kv??K.decoder_hidden_size/K.num_decoder_heads,W=[b,K.num_encoder_heads,0,te],j=[b,K.num_decoder_heads,0,ne];for(let q=0;q{var O,ae;r.r(A),r.d(A,{apis:()=>ne,env:()=>w});var f=r("?569f"),D=r("?3f59"),U=r("?154a");const Y="3.3.2",R=typeof window<"u"&&typeof window.document<"u",g=typeof self<"u"&&((O=self.constructor)==null?void 0:O.name)==="DedicatedWorkerGlobalScope",v=typeof self<"u"&&"caches"in self,M=typeof navigator<"u"&&"gpu"in navigator,y=typeof navigator<"u"&&"ml"in navigator,b=typeof process<"u",I=b&&((ae=process==null?void 0:process.release)==null?void 0:ae.name)==="node",K=!x(f),te=!x(D),ne=Object.freeze({IS_BROWSER_ENV:R,IS_WEBWORKER_ENV:g,IS_WEB_CACHE_AVAILABLE:v,IS_WEBGPU_AVAILABLE:M,IS_WEBNN_AVAILABLE:y,IS_PROCESS_AVAILABLE:b,IS_NODE_ENV:I,IS_FS_AVAILABLE:K,IS_PATH_AVAILABLE:te}),W=K&&te;let j="./";if(W){const oe=Object({url:self.location.href}).url;oe?j=D.dirname(D.dirname(U.fileURLToPath(oe))):typeof __dirname<"u"&&(j=D.dirname(__dirname))}const q=W?D.join(j,"/.cache/"):null,$="/models/",S=W?D.join(j,$):$,w={version:Y,backends:{onnx:{}},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!(R||g),localModelPath:S,useFS:K,useBrowserCache:v,useFSCache:K,cacheDir:q,useCustomCache:!1,customCache:null};function x(oe){return Object.keys(oe).length===0}},"./src/generation/configuration_utils.js":(De,A,r)=>{r.r(A),r.d(A,{GenerationConfig:()=>D});var f=r("./src/utils/core.js");class D{constructor(Y){_e(this,"max_length",20);_e(this,"max_new_tokens",null);_e(this,"min_length",0);_e(this,"min_new_tokens",null);_e(this,"early_stopping",!1);_e(this,"max_time",null);_e(this,"do_sample",!1);_e(this,"num_beams",1);_e(this,"num_beam_groups",1);_e(this,"penalty_alpha",null);_e(this,"use_cache",!0);_e(this,"temperature",1);_e(this,"top_k",50);_e(this,"top_p",1);_e(this,"typical_p",1);_e(this,"epsilon_cutoff",0);_e(this,"eta_cutoff",0);_e(this,"diversity_penalty",0);_e(this,"repetition_penalty",1);_e(this,"encoder_repetition_penalty",1);_e(this,"length_penalty",1);_e(this,"no_repeat_ngram_size",0);_e(this,"bad_words_ids",null);_e(this,"force_words_ids",null);_e(this,"renormalize_logits",!1);_e(this,"constraints",null);_e(this,"forced_bos_token_id",null);_e(this,"forced_eos_token_id",null);_e(this,"remove_invalid_values",!1);_e(this,"exponential_decay_length_penalty",null);_e(this,"suppress_tokens",null);_e(this,"streamer",null);_e(this,"begin_suppress_tokens",null);_e(this,"forced_decoder_ids",null);_e(this,"guidance_scale",null);_e(this,"num_return_sequences",1);_e(this,"output_attentions",!1);_e(this,"output_hidden_states",!1);_e(this,"output_scores",!1);_e(this,"return_dict_in_generate",!1);_e(this,"pad_token_id",null);_e(this,"bos_token_id",null);_e(this,"eos_token_id",null);_e(this,"encoder_no_repeat_ngram_size",0);_e(this,"decoder_start_token_id",null);_e(this,"generation_kwargs",{});Object.assign(this,(0,f.pick)(Y,Object.getOwnPropertyNames(this)))}}},"./src/generation/logits_process.js":(De,A,r)=>{r.r(A),r.d(A,{ClassifierFreeGuidanceLogitsProcessor:()=>W,ForcedBOSTokenLogitsProcessor:()=>g,ForcedEOSTokenLogitsProcessor:()=>v,LogitsProcessor:()=>U,LogitsProcessorList:()=>R,LogitsWarper:()=>Y,MinLengthLogitsProcessor:()=>K,MinNewTokensLengthLogitsProcessor:()=>te,NoBadWordsLogitsProcessor:()=>ne,NoRepeatNGramLogitsProcessor:()=>b,RepetitionPenaltyLogitsProcessor:()=>I,SuppressTokensAtBeginLogitsProcessor:()=>M,TemperatureLogitsWarper:()=>j,TopKLogitsWarper:()=>$,TopPLogitsWarper:()=>q,WhisperTimeStampLogitsProcessor:()=>y});var f=r("./src/utils/generic.js");r("./src/utils/tensor.js");var D=r("./src/utils/maths.js");class U extends f.Callable{_call(w,x){throw Error("`_call` should be implemented in a subclass")}}class Y extends f.Callable{_call(w,x){throw Error("`_call` should be implemented in a subclass")}}class R extends f.Callable{constructor(){super(),this.processors=[]}push(w){this.processors.push(w)}extend(w){this.processors.push(...w)}_call(w,x){let O=x;for(const ae of this.processors)O=ae(w,O);return O}[Symbol.iterator](){return this.processors.values()}}class g extends U{constructor(w){super(),this.bos_token_id=w}_call(w,x){for(let O=0;O=1&&oe[oe.length-1]>=this.timestamp_begin,we=oe.length<2||oe[oe.length-2]>=this.timestamp_begin;if(ve&&(we?ae.subarray(this.timestamp_begin).fill(-1/0):ae.subarray(0,this.eos_token_id).fill(-1/0)),w[O].length===this.begin_index&&this.max_initial_timestamp_index!==null){const ke=this.timestamp_begin+this.max_initial_timestamp_index;ae.subarray(ke+1).fill(-1/0)}const re=(0,D.log_softmax)(ae),xe=Math.log(re.subarray(this.timestamp_begin).map(Math.exp).reduce((ke,Ie)=>ke+Ie)),ce=(0,D.max)(re.subarray(0,this.timestamp_begin))[0];xe>ce&&ae.subarray(0,this.timestamp_begin).fill(-1/0)}return x}}class b extends U{constructor(w){super(),this.no_repeat_ngram_size=w}getNgrams(w){const x=w.length,O=[];for(let oe=0;oe1 to use the classifier free guidance processor, got guidance scale ${w}.`);this.guidance_scale=w}_call(w,x){if(x.dims[0]!==2*w.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 ${x.dims[0]} for the logits and ${w.length} for the input ids.`);const O=w.length,ae=x.slice([0,O],null),oe=x.slice([O,x.dims[0]],null);for(let ve=0;ve1)throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${w}`);if(!Number.isInteger(O)||O<1)throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${O}`);this.top_p=w,this.filter_value=x,this.min_tokens_to_keep=O}}class $ extends Y{constructor(w,{filter_value:x=-1/0,min_tokens_to_keep:O=1}={}){if(super(),!Number.isInteger(w)||w<0)throw new Error(`\`top_k\` must be a positive integer, but is ${w}`);this.top_k=Math.max(w,O),this.filter_value=x}}},"./src/generation/logits_sampler.js":(De,A,r)=>{r.r(A),r.d(A,{LogitsSampler:()=>Y});var f=r("./src/utils/generic.js"),D=r("./src/utils/tensor.js"),U=r("./src/utils/maths.js");r("./src/generation/configuration_utils.js");class Y extends f.Callable{constructor(y){super(),this.generation_config=y}async _call(y){return this.sample(y)}async sample(y){throw Error("sample should be implemented in subclasses.")}getLogits(y,b){let I=y.dims.at(-1),K=y.data;if(b===-1)K=K.slice(-I);else{let te=b*I;K=K.slice(te,te+I)}return K}randomSelect(y){let b=0;for(let K=0;K1)return new v(y);if(y.num_return_sequences>1)throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${y.num_return_sequences}.`);return new R(y)}}class R extends Y{async sample(y){const b=(0,U.max)(y.data)[1];return[[BigInt(b),0]]}}class g extends Y{async sample(y){let b=y.dims.at(-1);this.generation_config.top_k>0&&(b=Math.min(this.generation_config.top_k,b));const[I,K]=await(0,D.topk)(y,b),te=(0,U.softmax)(I.data);return Array.from({length:this.generation_config.num_beams},()=>{const ne=this.randomSelect(te);return[K.data[ne],Math.log(te[ne])]})}}class v extends Y{async sample(y){let b=y.dims.at(-1);this.generation_config.top_k>0&&(b=Math.min(this.generation_config.top_k,b));const[I,K]=await(0,D.topk)(y,b),te=(0,U.softmax)(I.data);return Array.from({length:this.generation_config.num_beams},(ne,W)=>[K.data[W],Math.log(te[W])])}}},"./src/generation/stopping_criteria.js":(De,A,r)=>{r.r(A),r.d(A,{EosTokenCriteria:()=>R,InterruptableStoppingCriteria:()=>g,MaxLengthCriteria:()=>Y,StoppingCriteria:()=>D,StoppingCriteriaList:()=>U});var f=r("./src/utils/generic.js");class D extends f.Callable{_call(M,y){throw Error("StoppingCriteria needs to be subclassed")}}class U extends f.Callable{constructor(){super(),this.criteria=[]}push(M){this.criteria.push(M)}extend(M){M instanceof U?M=M.criteria:M instanceof D&&(M=[M]),this.criteria.push(...M)}_call(M,y){const b=new Array(M.length).fill(!1);for(const I of this.criteria){const K=I(M,y);for(let te=0;tey.length>=this.max_length)}}class R extends D{constructor(M){super(),Array.isArray(M)||(M=[M]),this.eos_token_id=M}_call(M,y){return M.map(b=>{const I=b.at(-1);return this.eos_token_id.some(K=>I==K)})}}class g extends D{constructor(){super(),this.interrupted=!1}interrupt(){this.interrupted=!0}reset(){this.interrupted=!1}_call(M,y){return new Array(M.length).fill(this.interrupted)}}},"./src/generation/streamers.js":(De,A,r)=>{r.r(A),r.d(A,{BaseStreamer:()=>Y,TextStreamer:()=>g,WhisperTextStreamer:()=>v});var f=r("./src/utils/core.js"),D=r("./src/tokenizers.js"),U=r("./src/env.js");class Y{put(y){throw Error("Not implemented")}end(){throw Error("Not implemented")}}const R=U.apis.IS_PROCESS_AVAILABLE?M=>process.stdout.write(M):M=>console.log(M);class g extends Y{constructor(y,{skip_prompt:b=!1,callback_function:I=null,token_callback_function:K=null,skip_special_tokens:te=!0,decode_kwargs:ne={},...W}={}){super(),this.tokenizer=y,this.skip_prompt=b,this.callback_function=I??R,this.token_callback_function=K,this.decode_kwargs={skip_special_tokens:te,...ne,...W},this.token_cache=[],this.print_len=0,this.next_tokens_are_prompt=!0}put(y){var te;if(y.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 b=y[0];(te=this.token_callback_function)==null||te.call(this,b),this.token_cache=(0,f.mergeArrays)(this.token_cache,b);const I=this.tokenizer.decode(this.token_cache,this.decode_kwargs);let K;I.endsWith(` -`)?(K=I.slice(this.print_len),this.token_cache=[],this.print_len=0):I.length>0&&(0,D.is_chinese_char)(I.charCodeAt(I.length-1))?(K=I.slice(this.print_len),this.print_len+=K.length):(K=I.slice(this.print_len,I.lastIndexOf(" ")+1),this.print_len+=K.length),this.on_finalized_text(K,!1)}end(){let y;this.token_cache.length>0?(y=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len),this.token_cache=[],this.print_len=0):y="",this.next_tokens_are_prompt=!0,this.on_finalized_text(y,!0)}on_finalized_text(y,b){var I,K;y.length>0&&((I=this.callback_function)==null||I.call(this,y)),b&&this.callback_function===R&&U.apis.IS_PROCESS_AVAILABLE&&((K=this.callback_function)==null||K.call(this,` -`))}}class v extends g{constructor(y,{skip_prompt:b=!1,callback_function:I=null,token_callback_function:K=null,on_chunk_start:te=null,on_chunk_end:ne=null,on_finalize:W=null,time_precision:j=.02,skip_special_tokens:q=!0,decode_kwargs:$={}}={}){super(y,{skip_prompt:b,skip_special_tokens:q,callback_function:I,token_callback_function:K,decode_kwargs:$}),this.timestamp_begin=y.timestamp_begin,this.on_chunk_start=te,this.on_chunk_end=ne,this.on_finalize=W,this.time_precision=j,this.waiting_for_timestamp=!1}put(y){var I,K;if(y.length>1)throw Error("WhisperTextStreamer only supports batch size of 1");const b=y[0];if(b.length===1){const te=Number(b[0])-this.timestamp_begin;if(te>=0){const ne=te*this.time_precision;this.waiting_for_timestamp?(I=this.on_chunk_end)==null||I.call(this,ne):(K=this.on_chunk_start)==null||K.call(this,ne),this.waiting_for_timestamp=!this.waiting_for_timestamp,y=[[]]}}return super.put(y)}end(){var y;super.end(),(y=this.on_finalize)==null||y.call(this)}}},"./src/models.js":(De,A,r)=>{r.r(A),r.d(A,{ASTForAudioClassification:()=>Vo,ASTModel:()=>Ra,ASTPreTrainedModel:()=>Yt,AlbertForMaskedLM:()=>as,AlbertForQuestionAnswering:()=>Rn,AlbertForSequenceClassification:()=>Tn,AlbertModel:()=>Bn,AlbertPreTrainedModel:()=>Gr,AutoModel:()=>Ea,AutoModelForAudioClassification:()=>gc,AutoModelForAudioFrameClassification:()=>Tp,AutoModelForCTC:()=>fc,AutoModelForCausalLM:()=>ic,AutoModelForDepthEstimation:()=>Pp,AutoModelForDocumentQuestionAnswering:()=>yc,AutoModelForImageClassification:()=>dc,AutoModelForImageFeatureExtraction:()=>Tc,AutoModelForImageMatting:()=>Mc,AutoModelForImageSegmentation:()=>cc,AutoModelForImageToImage:()=>bc,AutoModelForMaskGeneration:()=>_c,AutoModelForMaskedLM:()=>ac,AutoModelForNormalEstimation:()=>vc,AutoModelForObjectDetection:()=>hc,AutoModelForPoseEstimation:()=>xc,AutoModelForQuestionAnswering:()=>lc,AutoModelForSemanticSegmentation:()=>Ca,AutoModelForSeq2SeqLM:()=>sc,AutoModelForSequenceClassification:()=>xp,AutoModelForSpeechSeq2Seq:()=>rc,AutoModelForTextToSpectrogram:()=>nc,AutoModelForTextToWaveform:()=>oc,AutoModelForTokenClassification:()=>tc,AutoModelForUniversalSegmentation:()=>pc,AutoModelForVision2Seq:()=>uc,AutoModelForXVector:()=>wc,AutoModelForZeroShotObjectDetection:()=>mc,BartForConditionalGeneration:()=>Kt,BartForSequenceClassification:()=>ms,BartModel:()=>xt,BartPretrainedModel:()=>_t,BaseModelOutput:()=>je,BeitForImageClassification:()=>on,BeitModel:()=>nn,BeitPreTrainedModel:()=>pu,BertForMaskedLM:()=>Ue,BertForQuestionAnswering:()=>Re,BertForSequenceClassification:()=>Ve,BertForTokenClassification:()=>Ne,BertModel:()=>Te,BertPreTrainedModel:()=>le,BlenderbotForConditionalGeneration:()=>Js,BlenderbotModel:()=>ze,BlenderbotPreTrainedModel:()=>Ws,BlenderbotSmallForConditionalGeneration:()=>Xs,BlenderbotSmallModel:()=>ks,BlenderbotSmallPreTrainedModel:()=>Fr,BloomForCausalLM:()=>Nl,BloomModel:()=>Rl,BloomPreTrainedModel:()=>bi,CLIPModel:()=>Ya,CLIPPreTrainedModel:()=>rn,CLIPSegForImageSegmentation:()=>nl,CLIPSegModel:()=>rl,CLIPSegPreTrainedModel:()=>Xo,CLIPTextModel:()=>Rc,CLIPTextModelWithProjection:()=>Ja,CLIPVisionModel:()=>Nc,CLIPVisionModelWithProjection:()=>Za,CamembertForMaskedLM:()=>Jr,CamembertForQuestionAnswering:()=>Zr,CamembertForSequenceClassification:()=>$r,CamembertForTokenClassification:()=>Ar,CamembertModel:()=>Nt,CamembertPreTrainedModel:()=>Pr,CausalLMOutput:()=>cn,CausalLMOutputWithPast:()=>Ep,ChineseCLIPModel:()=>gr,ChineseCLIPPreTrainedModel:()=>jc,ClapAudioModelWithProjection:()=>md,ClapModel:()=>nr,ClapPreTrainedModel:()=>la,ClapTextModelWithProjection:()=>hd,CodeGenForCausalLM:()=>fl,CodeGenModel:()=>ri,CodeGenPreTrainedModel:()=>co,CohereForCausalLM:()=>El,CohereModel:()=>Pl,CoherePreTrainedModel:()=>mi,ConvBertForMaskedLM:()=>kt,ConvBertForQuestionAnswering:()=>ys,ConvBertForSequenceClassification:()=>At,ConvBertForTokenClassification:()=>os,ConvBertModel:()=>vt,ConvBertPreTrainedModel:()=>mt,ConvNextForImageClassification:()=>Yi,ConvNextModel:()=>Cu,ConvNextPreTrainedModel:()=>Xi,ConvNextV2ForImageClassification:()=>Zi,ConvNextV2Model:()=>ku,ConvNextV2PreTrainedModel:()=>Ji,DPTForDepthEstimation:()=>Qc,DPTModel:()=>wu,DPTPreTrainedModel:()=>Hi,DebertaForMaskedLM:()=>Ir,DebertaForQuestionAnswering:()=>ar,DebertaForSequenceClassification:()=>Rr,DebertaForTokenClassification:()=>Nr,DebertaModel:()=>en,DebertaPreTrainedModel:()=>cr,DebertaV2ForMaskedLM:()=>Dt,DebertaV2ForQuestionAnswering:()=>Or,DebertaV2ForSequenceClassification:()=>Vs,DebertaV2ForTokenClassification:()=>jr,DebertaV2Model:()=>Tt,DebertaV2PreTrainedModel:()=>ot,DecisionTransformerModel:()=>mp,DecisionTransformerPreTrainedModel:()=>Cd,DeiTForImageClassification:()=>Ri,DeiTModel:()=>_u,DeiTPreTrainedModel:()=>go,DepthAnythingForDepthEstimation:()=>Mu,DepthAnythingPreTrainedModel:()=>yu,DepthProForDepthEstimation:()=>Qi,DepthProPreTrainedModel:()=>Mo,DetrForObjectDetection:()=>an,DetrForSegmentation:()=>Ks,DetrModel:()=>Oi,DetrObjectDetectionOutput:()=>Fi,DetrPreTrainedModel:()=>Dr,DetrSegmentationOutput:()=>Di,Dinov2ForImageClassification:()=>Jc,Dinov2Model:()=>Su,Dinov2PreTrainedModel:()=>ea,Dinov2WithRegistersForImageClassification:()=>Au,Dinov2WithRegistersModel:()=>$u,Dinov2WithRegistersPreTrainedModel:()=>ta,DistilBertForMaskedLM:()=>wn,DistilBertForQuestionAnswering:()=>es,DistilBertForSequenceClassification:()=>Os,DistilBertForTokenClassification:()=>Er,DistilBertModel:()=>lr,DistilBertPreTrainedModel:()=>Ms,DonutSwinModel:()=>Eu,DonutSwinPreTrainedModel:()=>Yc,EfficientNetForImageClassification:()=>Md,EfficientNetModel:()=>yd,EfficientNetPreTrainedModel:()=>So,ElectraForMaskedLM:()=>sr,ElectraForQuestionAnswering:()=>Us,ElectraForSequenceClassification:()=>Sr,ElectraForTokenClassification:()=>Yr,ElectraModel:()=>Ds,ElectraPreTrainedModel:()=>Cs,EsmForMaskedLM:()=>An,EsmForSequenceClassification:()=>In,EsmForTokenClassification:()=>On,EsmModel:()=>oo,EsmPreTrainedModel:()=>Ur,ExaoneForCausalLM:()=>ui,ExaoneModel:()=>yl,ExaonePreTrainedModel:()=>li,FalconForCausalLM:()=>pd,FalconModel:()=>cd,FalconPreTrainedModel:()=>aa,FastViTForImageClassification:()=>su,FastViTModel:()=>tu,FastViTPreTrainedModel:()=>ki,Florence2ForConditionalGeneration:()=>Ka,Florence2PreTrainedModel:()=>Ga,GLPNForDepthEstimation:()=>Pu,GLPNModel:()=>Xc,GLPNPreTrainedModel:()=>vo,GPT2LMHeadModel:()=>il,GPT2Model:()=>ol,GPT2PreTrainedModel:()=>Yo,GPTBigCodeForCausalLM:()=>_l,GPTBigCodeModel:()=>ml,GPTBigCodePreTrainedModel:()=>si,GPTJForCausalLM:()=>hl,GPTJModel:()=>pl,GPTJPreTrainedModel:()=>ti,GPTNeoForCausalLM:()=>ul,GPTNeoModel:()=>yr,GPTNeoPreTrainedModel:()=>Zo,GPTNeoXForCausalLM:()=>cl,GPTNeoXModel:()=>dl,GPTNeoXPreTrainedModel:()=>ei,Gemma2ForCausalLM:()=>$l,Gemma2Model:()=>Sl,Gemma2PreTrainedModel:()=>fi,GemmaForCausalLM:()=>kl,GemmaModel:()=>Cl,GemmaPreTrainedModel:()=>_i,GlmForCausalLM:()=>Nn,GlmModel:()=>wl,GlmPreTrainedModel:()=>ai,GraniteForCausalLM:()=>Tl,GraniteModel:()=>ds,GranitePreTrainedModel:()=>hi,GroundingDinoForObjectDetection:()=>Iu,GroundingDinoPreTrainedModel:()=>Zc,GroupViTModel:()=>Mr,GroupViTPreTrainedModel:()=>eu,HeliumForCausalLM:()=>gl,HeliumModel:()=>po,HeliumPreTrainedModel:()=>ii,HieraForImageClassification:()=>ji,HieraModel:()=>wo,HieraPreTrainedModel:()=>Ni,HubertForCTC:()=>Zu,HubertForSequenceClassification:()=>ap,HubertModel:()=>Ju,HubertPreTrainedModel:()=>ip,IJepaForImageClassification:()=>Hl,IJepaModel:()=>Kl,IJepaPreTrainedModel:()=>_o,Idefics3ForConditionalGeneration:()=>Ho,Idefics3PreTrainedModel:()=>Qa,ImageMattingOutput:()=>Pc,JAISLMHeadModel:()=>ll,JAISModel:()=>al,JAISPreTrainedModel:()=>Jo,JinaCLIPModel:()=>uo,JinaCLIPPreTrainedModel:()=>lo,JinaCLIPTextModel:()=>Qo,JinaCLIPVisionModel:()=>wr,LlamaForCausalLM:()=>Uc,LlamaModel:()=>oi,LlamaPreTrainedModel:()=>ni,LlavaForConditionalGeneration:()=>ao,LlavaOnevisionForConditionalGeneration:()=>Va,LlavaPreTrainedModel:()=>Kr,LongT5ForConditionalGeneration:()=>Se,LongT5Model:()=>be,LongT5PreTrainedModel:()=>ue,M2M100ForConditionalGeneration:()=>na,M2M100Model:()=>Bu,M2M100PreTrainedModel:()=>ra,MBartForCausalLM:()=>rr,MBartForConditionalGeneration:()=>Bt,MBartForSequenceClassification:()=>rs,MBartModel:()=>Fs,MBartPreTrainedModel:()=>us,MPNetForMaskedLM:()=>tn,MPNetForQuestionAnswering:()=>vn,MPNetForSequenceClassification:()=>Mn,MPNetForTokenClassification:()=>bn,MPNetModel:()=>yn,MPNetPreTrainedModel:()=>ur,MT5ForConditionalGeneration:()=>gt,MT5Model:()=>pt,MT5PreTrainedModel:()=>Qe,MarianMTModel:()=>zu,MarianModel:()=>Lu,MarianPreTrainedModel:()=>To,MaskFormerForInstanceSegmentation:()=>Tu,MaskFormerModel:()=>xu,MaskFormerPreTrainedModel:()=>bo,MaskedLMOutput:()=>qs,MgpstrForSceneTextRecognition:()=>Id,MgpstrModelOutput:()=>$d,MgpstrPreTrainedModel:()=>Ad,MistralForCausalLM:()=>ld,MistralModel:()=>ad,MistralPreTrainedModel:()=>oa,MobileBertForMaskedLM:()=>io,MobileBertForQuestionAnswering:()=>_r,MobileBertForSequenceClassification:()=>Wr,MobileBertModel:()=>Fn,MobileBertPreTrainedModel:()=>Vr,MobileLLMForCausalLM:()=>bl,MobileLLMModel:()=>Ml,MobileLLMPreTrainedModel:()=>di,MobileNetV1ForImageClassification:()=>ma,MobileNetV1Model:()=>pp,MobileNetV1PreTrainedModel:()=>ha,MobileNetV2ForImageClassification:()=>vd,MobileNetV2Model:()=>bd,MobileNetV2PreTrainedModel:()=>_a,MobileNetV3ForImageClassification:()=>Pd,MobileNetV3Model:()=>Td,MobileNetV3PreTrainedModel:()=>xd,MobileNetV4ForImageClassification:()=>Ed,MobileNetV4Model:()=>hp,MobileNetV4PreTrainedModel:()=>fa,MobileViTForImageClassification:()=>iu,MobileViTModel:()=>ou,MobileViTPreTrainedModel:()=>Si,MobileViTV2ForImageClassification:()=>Kc,MobileViTV2Model:()=>au,MobileViTV2PreTrainedModel:()=>$i,ModelOutput:()=>Ke,ModernBertForMaskedLM:()=>ct,ModernBertForSequenceClassification:()=>lt,ModernBertForTokenClassification:()=>ht,ModernBertModel:()=>dt,ModernBertPreTrainedModel:()=>st,Moondream1ForConditionalGeneration:()=>Wa,MoonshineForConditionalGeneration:()=>Ua,MoonshineModel:()=>pr,MoonshinePreTrainedModel:()=>Go,MptForCausalLM:()=>Ul,MptModel:()=>jl,MptPreTrainedModel:()=>vi,MultiModalityCausalLM:()=>Sd,MultiModalityPreTrainedModel:()=>kd,MusicgenForCausalLM:()=>cp,MusicgenForConditionalGeneration:()=>$o,MusicgenModel:()=>dp,MusicgenPreTrainedModel:()=>pa,NomicBertModel:()=>ie,NomicBertPreTrainedModel:()=>L,OPTForCausalLM:()=>Wl,OPTModel:()=>Vl,OPTPreTrainedModel:()=>xi,Olmo2ForCausalLM:()=>Wc,Olmo2Model:()=>xl,Olmo2PreTrainedModel:()=>pi,OlmoForCausalLM:()=>vl,OlmoModel:()=>Vc,OlmoPreTrainedModel:()=>ci,OpenELMForCausalLM:()=>Il,OpenELMModel:()=>Al,OpenELMPreTrainedModel:()=>gi,OwlViTForObjectDetection:()=>uu,OwlViTModel:()=>lu,OwlViTPreTrainedModel:()=>Ai,Owlv2ForObjectDetection:()=>cu,Owlv2Model:()=>du,Owlv2PreTrainedModel:()=>Ii,PaliGemmaForConditionalGeneration:()=>qa,PaliGemmaPreTrainedModel:()=>Ha,PatchTSMixerForPrediction:()=>zd,PatchTSMixerModel:()=>Ld,PatchTSMixerPreTrainedModel:()=>ga,PatchTSTForPrediction:()=>Dd,PatchTSTModel:()=>Fd,PatchTSTPreTrainedModel:()=>Od,Phi3ForCausalLM:()=>Bl,Phi3Model:()=>zl,Phi3PreTrainedModel:()=>Mi,Phi3VForCausalLM:()=>hr,Phi3VPreTrainedModel:()=>Xa,PhiForCausalLM:()=>Ll,PhiModel:()=>Dl,PhiPreTrainedModel:()=>yi,PreTrainedModel:()=>se,PretrainedMixin:()=>ws,PvtForImageClassification:()=>Ei,PvtModel:()=>Xl,PvtPreTrainedModel:()=>Pi,PyAnnoteForAudioFrameClassification:()=>Vu,PyAnnoteModel:()=>Uu,PyAnnotePreTrainedModel:()=>Po,QuestionAnsweringModelOutput:()=>tr,Qwen2ForCausalLM:()=>Ol,Qwen2Model:()=>jn,Qwen2PreTrainedModel:()=>wi,Qwen2VLForConditionalGeneration:()=>Fl,Qwen2VLPreTrainedModel:()=>ho,RTDetrForObjectDetection:()=>Un,RTDetrModel:()=>Hc,RTDetrObjectDetectionOutput:()=>zi,RTDetrPreTrainedModel:()=>Li,ResNetForImageClassification:()=>qc,ResNetModel:()=>fu,ResNetPreTrainedModel:()=>Ui,RoFormerForMaskedLM:()=>$e,RoFormerForQuestionAnswering:()=>ut,RoFormerForSequenceClassification:()=>We,RoFormerForTokenClassification:()=>Je,RoFormerModel:()=>me,RoFormerPreTrainedModel:()=>H,RobertaForMaskedLM:()=>fr,RobertaForQuestionAnswering:()=>yt,RobertaForSequenceClassification:()=>_s,RobertaForTokenClassification:()=>Ss,RobertaModel:()=>or,RobertaPreTrainedModel:()=>Ot,SamImageSegmentationOutput:()=>Wn,SamModel:()=>xo,SamPreTrainedModel:()=>ep,SapiensForDepthEstimation:()=>yo,SapiensForNormalEstimation:()=>vu,SapiensForSemanticSegmentation:()=>bu,SapiensPreTrainedModel:()=>qi,SegformerForImageClassification:()=>_d,SegformerForSemanticSegmentation:()=>fd,SegformerModel:()=>up,SegformerPreTrainedModel:()=>dn,Seq2SeqLMOutput:()=>qp,SequenceClassifierOutput:()=>Qt,SiglipModel:()=>el,SiglipPreTrainedModel:()=>qo,SiglipTextModel:()=>tl,SiglipVisionModel:()=>sl,SpeechT5ForSpeechToText:()=>Cr,SpeechT5ForTextToSpeech:()=>Lr,SpeechT5HifiGan:()=>ln,SpeechT5Model:()=>Kp,SpeechT5PreTrainedModel:()=>ko,SqueezeBertForMaskedLM:()=>Dn,SqueezeBertForQuestionAnswering:()=>zn,SqueezeBertForSequenceClassification:()=>Ln,SqueezeBertModel:()=>xn,SqueezeBertPreTrainedModel:()=>zt,StableLmForCausalLM:()=>wd,StableLmModel:()=>gd,StableLmPreTrainedModel:()=>ca,Starcoder2ForCausalLM:()=>dd,Starcoder2Model:()=>ud,Starcoder2PreTrainedModel:()=>ia,StyleTextToSpeech2Model:()=>od,StyleTextToSpeech2PreTrainedModel:()=>nd,Swin2SRForImageSuperResolution:()=>gu,Swin2SRModel:()=>Ki,Swin2SRPreTrainedModel:()=>Gi,SwinForImageClassification:()=>Vn,SwinModel:()=>Wi,SwinPreTrainedModel:()=>Vi,T5ForConditionalGeneration:()=>Q,T5Model:()=>P,T5PreTrainedModel:()=>Pe,TableTransformerForObjectDetection:()=>mu,TableTransformerModel:()=>hu,TableTransformerObjectDetectionOutput:()=>Bi,TableTransformerPreTrainedModel:()=>fo,TokenClassifierOutput:()=>Hs,TrOCRForCausalLM:()=>id,TrOCRPreTrainedModel:()=>un,UniSpeechForCTC:()=>rp,UniSpeechForSequenceClassification:()=>Ku,UniSpeechModel:()=>Gu,UniSpeechPreTrainedModel:()=>Eo,UniSpeechSatForAudioFrameClassification:()=>Qu,UniSpeechSatForCTC:()=>qu,UniSpeechSatForSequenceClassification:()=>np,UniSpeechSatModel:()=>Hu,UniSpeechSatPreTrainedModel:()=>Gn,ViTForImageClassification:()=>Ti,ViTMAEModel:()=>Jl,ViTMAEPreTrainedModel:()=>Yl,ViTMSNForImageClassification:()=>Zl,ViTMSNModel:()=>Gc,ViTMSNPreTrainedModel:()=>Ci,ViTModel:()=>Gl,ViTPreTrainedModel:()=>mo,VisionEncoderDecoderModel:()=>Ko,VitMatteForImageMatting:()=>nu,VitMattePreTrainedModel:()=>ru,VitPoseForPoseEstimation:()=>Ql,VitPosePreTrainedModel:()=>ql,VitsModel:()=>da,VitsModelOutput:()=>Cp,VitsPreTrainedModel:()=>ua,Wav2Vec2BertForCTC:()=>op,Wav2Vec2BertForSequenceClassification:()=>Yu,Wav2Vec2BertModel:()=>Xu,Wav2Vec2BertPreTrainedModel:()=>Co,Wav2Vec2ForAudioFrameClassification:()=>ju,Wav2Vec2ForCTC:()=>Nu,Wav2Vec2ForSequenceClassification:()=>tp,Wav2Vec2Model:()=>Ru,Wav2Vec2PreTrainedModel:()=>Hr,WavLMForAudioFrameClassification:()=>rd,WavLMForCTC:()=>td,WavLMForSequenceClassification:()=>sd,WavLMForXVector:()=>lp,WavLMModel:()=>ed,WavLMPreTrainedModel:()=>Pn,WeSpeakerResNetModel:()=>sp,WeSpeakerResNetPreTrainedModel:()=>Wu,WhisperForConditionalGeneration:()=>ja,WhisperModel:()=>Na,WhisperPreTrainedModel:()=>Wo,XLMForQuestionAnswering:()=>sn,XLMForSequenceClassification:()=>Gs,XLMForTokenClassification:()=>$t,XLMModel:()=>Ls,XLMPreTrainedModel:()=>qt,XLMRobertaForMaskedLM:()=>La,XLMRobertaForQuestionAnswering:()=>Ba,XLMRobertaForSequenceClassification:()=>Uo,XLMRobertaForTokenClassification:()=>za,XLMRobertaModel:()=>It,XLMRobertaPreTrainedModel:()=>qe,XLMWithLMHeadModel:()=>$s,XVectorOutput:()=>Hn,YolosForObjectDetection:()=>Fu,YolosModel:()=>Ou,YolosObjectDetectionOutput:()=>Du,YolosPreTrainedModel:()=>sa});var f=r("./src/configs.js"),D=r("./src/backends/onnx.js"),U=r("./src/utils/dtypes.js"),Y=r("./src/utils/generic.js"),R=r("./src/utils/core.js"),g=r("./src/utils/hub.js"),v=r("./src/utils/constants.js"),M=r("./src/generation/logits_process.js"),y=r("./src/generation/configuration_utils.js"),b=r("./src/utils/tensor.js"),I=r("./src/utils/image.js"),K=r("./src/utils/maths.js"),te=r("./src/generation/stopping_criteria.js"),ne=r("./src/generation/logits_sampler.js"),W=r("./src/env.js"),j=r("./src/models/whisper/generation_whisper.js"),q=r("./src/models/whisper/common_whisper.js");const $={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,MaskGeneration:5,ImageTextToText:6,Musicgen:7,MultiModality:8,Phi3V:9},S=new Map,w=new Map,x=new Map;async function O(_,T,N){var xs;const fe=((xs=N.config)==null?void 0:xs["transformers.js_config"])??{};let Fe=N.device??fe.device;Fe&&typeof Fe!="string"&&(Fe.hasOwnProperty(T)?Fe=Fe[T]:(console.warn(`device not specified for "${T}". Using the default device.`),Fe=null));const Ae=Fe??(W.apis.IS_NODE_ENV?"cpu":"wasm"),et=(0,D.deviceToExecutionProviders)(Ae);let rt=N.dtype??fe.dtype;if(typeof rt!="string"&&(rt&&rt.hasOwnProperty(T)?rt=rt[T]:(rt=U.DEFAULT_DEVICE_DTYPE_MAPPING[Ae]??U.DATA_TYPES.fp32,console.warn(`dtype not specified for "${T}". Using the default dtype (${rt}) for this device (${Ae}).`))),rt===U.DATA_TYPES.auto){let cs=fe.dtype;typeof cs!="string"&&(cs=cs[T]),cs&&cs!==U.DATA_TYPES.auto&&U.DATA_TYPES.hasOwnProperty(cs)?rt=cs:rt=U.DEFAULT_DEVICE_DTYPE_MAPPING[Ae]??U.DATA_TYPES.fp32}const ft=rt;if(U.DEFAULT_DTYPE_SUFFIX_MAPPING.hasOwnProperty(ft)){if(ft===U.DATA_TYPES.fp16&&Ae==="webgpu"&&!await(0,U.isWebGpuFp16Supported)())throw new Error(`The device (${Ae}) does not support fp16.`)}else throw new Error(`Invalid dtype: ${ft}. Should be one of: ${Object.keys(U.DATA_TYPES).join(", ")}`);const Mt=fe.kv_cache_dtype?typeof fe.kv_cache_dtype=="string"?fe.kv_cache_dtype:fe.kv_cache_dtype[ft]??"float32":void 0;if(Mt&&!["float32","float16"].includes(Mt))throw new Error(`Invalid kv_cache_dtype: ${Mt}. Should be one of: float32, float16`);const jt={dtype:ft,kv_cache_dtype:Mt},Vt=U.DEFAULT_DTYPE_SUFFIX_MAPPING[ft],Lt=`${N.subfolder??""}/${T}${Vt}.onnx`,Gt={...N.session_options};Gt.executionProviders??(Gt.executionProviders=et);const ts=fe.free_dimension_overrides;ts?Gt.freeDimensionOverrides??(Gt.freeDimensionOverrides=ts):Ae.startsWith("webnn")&&!Gt.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 ns=(0,g.getModelFile)(_,Lt,!0,N),Jt=N.use_external_data_format??fe.use_external_data_format;let is=[];if(Jt&&(Jt===!0||typeof Jt=="object"&&Jt.hasOwnProperty(T)&&Jt[T]===!0)){if(W.apis.IS_NODE_ENV)throw new Error("External data format is not yet supported in Node.js");const cs=`${T}${Vt}.onnx_data`,Es=`${N.subfolder??""}/${cs}`;is.push(new Promise(async(Is,Zs)=>{const Ys=await(0,g.getModelFile)(_,Es,!0,N);Is({path:cs,data:Ys})}))}else Gt.externalData!==void 0&&(is=Gt.externalData.map(async cs=>{if(typeof cs.data=="string"){const Es=await(0,g.getModelFile)(_,cs.data,!0,N);return{...cs,data:Es}}return cs}));if(is.length>0&&(Gt.externalData=await Promise.all(is)),Ae==="webgpu"){const cs=(0,f.getKeyValueShapes)(N.config,{prefix:"present"});if(Object.keys(cs).length>0&&!(0,D.isONNXProxy)()){const Es={};for(const Is in cs)Es[Is]="gpu-buffer";Gt.preferredOutputLocation=Es}}return{buffer:await ns,session_options:Gt,session_config:jt}}async function ae(_,T,N){return Object.fromEntries(await Promise.all(Object.keys(T).map(async fe=>{const{buffer:Fe,session_options:Ae,session_config:et}=await O(_,T[fe],N),rt=await(0,D.createInferenceSession)(Fe,Ae,et);return[fe,rt]})))}async function oe(_,T,N){return Object.fromEntries(await Promise.all(Object.keys(T).map(async fe=>{const Fe=await(0,g.getModelJSON)(_,T[fe],!1,N);return[fe,Fe]})))}function ve(_,T){const N=Object.create(null),fe=[];for(const et of _.inputNames){const rt=T[et];if(!(rt instanceof b.Tensor)){fe.push(et);continue}N[et]=(0,D.isONNXProxy)()?rt.clone():rt}if(fe.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${fe.join(", ")}.`);const Fe=Object.keys(T).length,Ae=_.inputNames.length;if(Fe>Ae){let et=Object.keys(T).filter(rt=>!_.inputNames.includes(rt));console.warn(`WARNING: Too many inputs were provided (${Fe} > ${Ae}). The following inputs will be ignored: "${et.join(", ")}".`)}return N}async function we(_,T){const N=ve(_,T);try{const fe=Object.fromEntries(Object.entries(N).map(([Ae,et])=>[Ae,et.ort_tensor]));let Fe=await _.run(fe);return Fe=re(Fe),Fe}catch(fe){const Fe=Object.fromEntries(Object.entries(N).map(([Ae,{type:et,dims:rt,data:ft}])=>[Ae,{type:et,dims:rt,data:ft}]));throw console.error(`An error occurred during model execution: "${fe}".`),console.error("Inputs given to model:",Fe),fe}}function re(_){for(let T in _)(0,D.isONNXTensor)(_[T])?_[T]=new b.Tensor(_[T]):typeof _[T]=="object"&&re(_[T]);return _}function xe(_){if(_ instanceof b.Tensor)return _;if(_.length===0)throw Error("items must be non-empty");if(Array.isArray(_[0])){if(_.some(T=>T.length!==_[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 b.Tensor("int64",BigInt64Array.from(_.flat().map(T=>BigInt(T))),[_.length,_[0].length])}else return new b.Tensor("int64",BigInt64Array.from(_.map(T=>BigInt(T))),[1,_.length])}function ce(_){return new b.Tensor("bool",[_],[1])}async function ke(_,T){let{encoder_outputs:N,input_ids:fe,decoder_input_ids:Fe,...Ae}=T;if(!N){const rt=(0,R.pick)(T,_.sessions.model.inputNames);N=(await Ie(_,rt)).last_hidden_state}return Ae.input_ids=Fe,Ae.encoder_hidden_states=N,_.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(Ae.encoder_attention_mask=T.attention_mask),await Ee(_,Ae,!0)}async function Ie(_,T){const N=_.sessions.model,fe=(0,R.pick)(T,N.inputNames);if(N.inputNames.includes("inputs_embeds")&&!fe.inputs_embeds){if(!T.input_ids)throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");fe.inputs_embeds=await _.encode_text({input_ids:T.input_ids})}if(N.inputNames.includes("token_type_ids")&&!fe.token_type_ids){if(!fe.input_ids)throw new Error("Both `input_ids` and `token_type_ids` are missing in the model inputs.");fe.token_type_ids=(0,b.zeros_like)(fe.input_ids)}if(N.inputNames.includes("pixel_mask")&&!fe.pixel_mask){if(!fe.pixel_values)throw new Error("Both `pixel_values` and `pixel_mask` are missing in the model inputs.");const Fe=fe.pixel_values.dims;fe.pixel_mask=(0,b.ones)([Fe[0],Fe[2],Fe[3]])}return await we(N,fe)}async function Ee(_,T,N=!1){const fe=_.sessions[N?"decoder_model_merged":"model"],{past_key_values:Fe,...Ae}=T;if(fe.inputNames.includes("use_cache_branch")&&(Ae.use_cache_branch=ce(!!Fe)),fe.inputNames.includes("position_ids")&&Ae.attention_mask&&!Ae.position_ids){const rt=_.config.model_type==="paligemma"?1:0;Ae.position_ids=J(Ae,Fe,rt)}_.addPastKeyValues(Ae,Fe);const et=(0,R.pick)(Ae,fe.inputNames);return await we(fe,et)}function tt({image_token_id:_,inputs_embeds:T,image_features:N,input_ids:fe,attention_mask:Fe}){const Ae=fe.tolist().map(Mt=>Mt.reduce((jt,Vt,Lt)=>(Vt==_&&jt.push(Lt),jt),[])),et=Ae.reduce((Mt,jt)=>Mt+jt.length,0),rt=N.dims[0];if(et!==rt)throw new Error(`Image features and image tokens do not match: tokens: ${et}, features ${rt}`);let ft=0;for(let Mt=0;MtAe.dims[1])){if(Fert==_.config.image_token_index)){const rt=_.config.num_image_tokens;if(!rt)throw new Error("`num_image_tokens` is missing in the model configuration.");const ft=Ae.dims[1]-(Fe-rt);N.input_ids=Ae.slice(null,[-ft,null]),N.attention_mask=(0,b.ones)([1,Fe+ft])}}}return N}function Ce(_,T,N,fe){return N.past_key_values&&(T=T.map(Fe=>[Fe.at(-1)])),{...N,decoder_input_ids:xe(T)}}function Be(_,...T){return _.config.is_encoder_decoder?Ce(_,...T):de(_,...T)}function Ze(_,T,N,fe){const Fe=!!N.past_key_values;return fe.guidance_scale!==null&&fe.guidance_scale>1&&(Fe?N.input_ids=(0,b.cat)([N.input_ids,N.input_ids],0):(N.input_ids=(0,b.cat)([N.input_ids,(0,b.full_like)(N.input_ids,BigInt(fe.pad_token_id))],0),N.attention_mask=(0,b.cat)([N.attention_mask,(0,b.full_like)(N.attention_mask,0n)],0))),(Fe||!N.pixel_values)&&(N.pixel_values=(0,b.full)([0,0,3,384,384],1)),Fe&&(N.images_seq_mask=new b.Tensor("bool",new Array(1).fill(!0).fill(!1,0,1),[1,1]),N.images_emb_mask=new b.Tensor("bool",new Array(0).fill(!1),[1,1,0])),N}class se extends Y.Callable{constructor(N,fe,Fe){super();_e(this,"main_input_name","input_ids");_e(this,"forward_params",["input_ids","attention_mask"]);this.config=N,this.sessions=fe,this.configs=Fe;const Ae=x.get(this.constructor),et=S.get(Ae);switch(this.can_generate=!1,this._forward=null,this._prepare_inputs_for_generation=null,et){case $.DecoderOnly:this.can_generate=!0,this._forward=Ee,this._prepare_inputs_for_generation=de;break;case $.Seq2Seq:case $.Vision2Seq:case $.Musicgen:this.can_generate=!0,this._forward=ke,this._prepare_inputs_for_generation=Ce;break;case $.EncoderDecoder:this._forward=ke;break;case $.ImageTextToText:this.can_generate=!0,this._forward=Ge,this._prepare_inputs_for_generation=Be;break;case $.Phi3V:this.can_generate=!0,this._prepare_inputs_for_generation=Be;break;case $.MultiModality:this.can_generate=!0,this._prepare_inputs_for_generation=Ze;break;default:this._forward=Ie;break}this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){var fe;const N=[];for(const Fe of Object.values(this.sessions))(fe=Fe==null?void 0:Fe.handler)!=null&&fe.dispose&&N.push(Fe.handler.dispose());return await Promise.all(N)}static async from_pretrained(N,{progress_callback:fe=null,config:Fe=null,cache_dir:Ae=null,local_files_only:et=!1,revision:rt="main",model_file_name:ft=null,subfolder:Mt="onnx",device:jt=null,dtype:Vt=null,use_external_data_format:Lt=null,session_options:Gt={}}={}){let ts={progress_callback:fe,config:Fe,cache_dir:Ae,local_files_only:et,revision:rt,model_file_name:ft,subfolder:Mt,device:jt,dtype:Vt,use_external_data_format:Lt,session_options:Gt};const ns=x.get(this),Jt=S.get(ns);Fe=ts.config=await f.AutoConfig.from_pretrained(N,ts);let is;if(Jt===$.DecoderOnly)is=await Promise.all([ae(N,{model:ts.model_file_name??"model"},ts),oe(N,{generation_config:"generation_config.json"},ts)]);else if(Jt===$.Seq2Seq||Jt===$.Vision2Seq)is=await Promise.all([ae(N,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},ts),oe(N,{generation_config:"generation_config.json"},ts)]);else if(Jt===$.MaskGeneration)is=await Promise.all([ae(N,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},ts)]);else if(Jt===$.EncoderDecoder)is=await Promise.all([ae(N,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},ts)]);else if(Jt===$.ImageTextToText){const As={embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};Fe.is_encoder_decoder&&(As.model="encoder_model"),is=await Promise.all([ae(N,As,ts),oe(N,{generation_config:"generation_config.json"},ts)])}else if(Jt===$.Musicgen)is=await Promise.all([ae(N,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},ts),oe(N,{generation_config:"generation_config.json"},ts)]);else if(Jt===$.MultiModality)is=await Promise.all([ae(N,{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"},ts),oe(N,{generation_config:"generation_config.json"},ts)]);else if(Jt===$.Phi3V)is=await Promise.all([ae(N,{prepare_inputs_embeds:"prepare_inputs_embeds",model:"model",vision_encoder:"vision_encoder"},ts),oe(N,{generation_config:"generation_config.json"},ts)]);else{if(Jt!==$.EncoderOnly){const As=ns??(Fe==null?void 0:Fe.model_type);As!=="custom"&&console.warn(`Model type for '${As}' not found, assuming encoder-only architecture. Please report this at ${v.GITHUB_ISSUE_URL}.`)}is=await Promise.all([ae(N,{model:ts.model_file_name??"model"},ts)])}return new this(Fe,...is)}async _call(N){return await this.forward(N)}async forward(N){return await this._forward(this,N)}get generation_config(){var N;return((N=this.configs)==null?void 0:N.generation_config)??null}_get_logits_warper(N){const fe=new M.LogitsProcessorList;return N.temperature!==null&&N.temperature!==1&&fe.push(new M.TemperatureLogitsWarper(N.temperature)),N.top_k!==null&&N.top_k!==0&&fe.push(new M.TopKLogitsWarper(N.top_k)),N.top_p!==null&&N.top_p<1&&fe.push(new M.TopPLogitsWarper(N.top_p)),fe}_get_logits_processor(N,fe,Fe=null){const Ae=new M.LogitsProcessorList;if(N.repetition_penalty!==null&&N.repetition_penalty!==1&&Ae.push(new M.RepetitionPenaltyLogitsProcessor(N.repetition_penalty)),N.no_repeat_ngram_size!==null&&N.no_repeat_ngram_size>0&&Ae.push(new M.NoRepeatNGramLogitsProcessor(N.no_repeat_ngram_size)),N.bad_words_ids!==null&&Ae.push(new M.NoBadWordsLogitsProcessor(N.bad_words_ids,N.eos_token_id)),N.min_length!==null&&N.eos_token_id!==null&&N.min_length>0&&Ae.push(new M.MinLengthLogitsProcessor(N.min_length,N.eos_token_id)),N.min_new_tokens!==null&&N.eos_token_id!==null&&N.min_new_tokens>0&&Ae.push(new M.MinNewTokensLengthLogitsProcessor(fe,N.min_new_tokens,N.eos_token_id)),N.forced_bos_token_id!==null&&Ae.push(new M.ForcedBOSTokenLogitsProcessor(N.forced_bos_token_id)),N.forced_eos_token_id!==null&&Ae.push(new M.ForcedEOSTokenLogitsProcessor(N.max_length,N.forced_eos_token_id)),N.begin_suppress_tokens!==null){const et=fe>1||N.forced_bos_token_id===null?fe:fe+1;Ae.push(new M.SuppressTokensAtBeginLogitsProcessor(N.begin_suppress_tokens,et))}return N.guidance_scale!==null&&N.guidance_scale>1&&Ae.push(new M.ClassifierFreeGuidanceLogitsProcessor(N.guidance_scale)),Fe!==null&&Ae.extend(Fe),Ae}_prepare_generation_config(N,fe,Fe=y.GenerationConfig){const Ae={...this.config};for(const rt of["decoder","generator","text_config"])rt in Ae&&Object.assign(Ae,Ae[rt]);const et=new Fe(Ae);return Object.assign(et,this.generation_config??{}),N&&Object.assign(et,N),fe&&Object.assign(et,(0,R.pick)(fe,Object.getOwnPropertyNames(et))),et}_get_stopping_criteria(N,fe=null){const Fe=new te.StoppingCriteriaList;return N.max_length!==null&&Fe.push(new te.MaxLengthCriteria(N.max_length,this.config.max_position_embeddings??null)),N.eos_token_id!==null&&Fe.push(new te.EosTokenCriteria(N.eos_token_id)),fe&&Fe.extend(fe),Fe}_validate_model_class(){if(!this.can_generate){const N=[ba,Ta,Ao,Bd],fe=x.get(this.constructor),Fe=new Set,Ae=this.config.model_type;for(const rt of N){const ft=rt.get(Ae);ft&&Fe.add(ft[0])}let et=`The current model class (${fe}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw Fe.size>0&&(et+=` Please use the following class instead: ${[...Fe].join(", ")}`),Error(et)}}prepare_inputs_for_generation(...N){return this._prepare_inputs_for_generation(this,...N)}_update_model_kwargs_for_generation({generated_input_ids:N,outputs:fe,model_inputs:Fe,is_encoder_decoder:Ae}){return Fe.past_key_values=this.getPastKeyValues(fe,Fe.past_key_values),Fe.input_ids=new b.Tensor("int64",N.flat(),[N.length,1]),Ae||(Fe.attention_mask=(0,b.cat)([Fe.attention_mask,(0,b.ones)([Fe.attention_mask.dims[0],1])],1)),Fe.position_ids=null,Fe}_prepare_model_inputs({inputs:N,bos_token_id:fe,model_kwargs:Fe}){const Ae=(0,R.pick)(Fe,this.forward_params),et=this.main_input_name;if(et in Ae){if(N)throw new Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else Ae[et]=N;return{inputs_tensor:Ae[et],model_inputs:Ae,model_input_name:et}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:N,model_inputs:fe,model_input_name:Fe,generation_config:Ae}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!fe.inputs_embeds&&"_prepare_inputs_embeds"in this){const{input_ids:rt,pixel_values:ft,attention_mask:Mt,...jt}=fe,Vt=await this._prepare_inputs_embeds(fe);fe={...jt,...(0,R.pick)(Vt,["inputs_embeds","attention_mask"])}}let{last_hidden_state:et}=await Ie(this,fe);if(Ae.guidance_scale!==null&&Ae.guidance_scale>1)et=(0,b.cat)([et,(0,b.full_like)(et,0)],0),"attention_mask"in fe&&(fe.attention_mask=(0,b.cat)([fe.attention_mask,(0,b.zeros_like)(fe.attention_mask)],0));else if(fe.decoder_input_ids){const rt=xe(fe.decoder_input_ids).dims[0];if(rt!==et.dims[0]){if(et.dims[0]!==1)throw new Error(`The encoder outputs have a different batch size (${et.dims[0]}) than the decoder inputs (${rt}).`);et=(0,b.cat)(Array.from({length:rt},()=>et),0)}}return fe.encoder_outputs=et,fe}_prepare_decoder_input_ids_for_generation({batch_size:N,model_input_name:fe,model_kwargs:Fe,decoder_start_token_id:Ae,bos_token_id:et,generation_config:rt}){let{decoder_input_ids:ft,...Mt}=Fe;if(!(ft instanceof b.Tensor)){if(ft)Array.isArray(ft[0])||(ft=Array.from({length:N},()=>ft));else if(Ae??(Ae=et),this.config.model_type==="musicgen")ft=Array.from({length:N*this.config.decoder.num_codebooks},()=>[Ae]);else if(Array.isArray(Ae)){if(Ae.length!==N)throw new Error(`\`decoder_start_token_id\` expcted to have length ${N} but got ${Ae.length}`);ft=Ae}else ft=Array.from({length:N},()=>[Ae]);ft=xe(ft)}return Fe.decoder_attention_mask=(0,b.ones_like)(ft),{input_ids:ft,model_inputs:Mt}}async generate({inputs:N=null,generation_config:fe=null,logits_processor:Fe=null,stopping_criteria:Ae=null,streamer:et=null,...rt}){this._validate_model_class(),fe=this._prepare_generation_config(fe,rt);let{inputs_tensor:ft,model_inputs:Mt,model_input_name:jt}=this._prepare_model_inputs({inputs:N,model_kwargs:rt});const Vt=this.config.is_encoder_decoder;Vt&&("encoder_outputs"in Mt||(Mt=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:ft,model_inputs:Mt,model_input_name:jt,generation_config:fe})));let Lt;Vt?{input_ids:Lt,model_inputs:Mt}=this._prepare_decoder_input_ids_for_generation({batch_size:Mt[jt].dims.at(0),model_input_name:jt,model_kwargs:Mt,decoder_start_token_id:fe.decoder_start_token_id,bos_token_id:fe.bos_token_id,generation_config:fe}):Lt=Mt[jt];let Gt=Lt.dims.at(-1);fe.max_new_tokens!==null&&(fe.max_length=Gt+fe.max_new_tokens);const ts=this._get_logits_processor(fe,Gt,Fe),ns=this._get_stopping_criteria(fe,Ae),Jt=Mt[jt].dims.at(0),is=ne.LogitsSampler.getSampler(fe),As=new Array(Jt).fill(0),xs=Lt.tolist();et&&et.put(xs);let cs,Es={};for(;;){if(Mt=this.prepare_inputs_for_generation(xs,Mt,fe),cs=await this.forward(Mt),fe.output_attentions&&fe.return_dict_in_generate){const ir=this.getAttentions(cs);for(const vr in ir)vr in Es||(Es[vr]=[]),Es[vr].push(ir[vr])}const Ys=cs.logits.slice(null,-1,null),br=ts(xs,Ys),pn=[];for(let ir=0;irir))break;Mt=this._update_model_kwargs_for_generation({generated_input_ids:pn,outputs:cs,model_inputs:Mt,is_encoder_decoder:Vt})}et&&et.end();const Is=this.getPastKeyValues(cs,Mt.past_key_values,!0),Zs=new b.Tensor("int64",xs.flat(),[xs.length,xs[0].length]);if(fe.return_dict_in_generate)return{sequences:Zs,past_key_values:Is,...Es};for(const Ys of Object.values(cs))Ys.location==="gpu-buffer"&&Ys.dispose();return Zs}getPastKeyValues(N,fe,Fe=!1){const Ae=Object.create(null);for(const et in N)if(et.startsWith("present")){const rt=et.replace("present","past_key_values"),ft=et.includes("encoder");if(ft&&fe?Ae[rt]=fe[rt]:Ae[rt]=N[et],fe&&(!ft||Fe)){const Mt=fe[rt];Mt.location==="gpu-buffer"&&Mt.dispose()}}return Ae}getAttentions(N){const fe={};for(const Fe of["cross_attentions","encoder_attentions","decoder_attentions"])for(const Ae in N)Ae.startsWith(Fe)&&(Fe in fe||(fe[Fe]=[]),fe[Fe].push(N[Ae]));return fe}addPastKeyValues(N,fe){var Fe,Ae,et;if(fe)Object.assign(N,fe);else{const rt=this.sessions.decoder_model_merged??this.sessions.model,ft=((Fe=rt==null?void 0:rt.config)==null?void 0:Fe.kv_cache_dtype)??"float32",Mt=ft==="float16"?new Uint16Array:[],jt=((et=(Ae=N[this.main_input_name]??N.attention_mask)==null?void 0:Ae.dims)==null?void 0:et[0])??1,Vt=(0,f.getKeyValueShapes)(this.config,{batch_size:jt});for(const Lt in Vt)N[Lt]=new b.Tensor(ft,Mt,Vt[Lt])}}async encode_image({pixel_values:N}){const fe=(await we(this.sessions.vision_encoder,{pixel_values:N})).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 (${fe.dims[1]}).`),this.config.num_image_tokens=fe.dims[1]),fe}async encode_text({input_ids:N}){return(await we(this.sessions.embed_tokens,{input_ids:N})).inputs_embeds}}class Ke{}class je extends Ke{constructor({last_hidden_state:T,hidden_states:N=null,attentions:fe=null}){super(),this.last_hidden_state=T,this.hidden_states=N,this.attentions=fe}}class le extends se{}class Te extends le{}class Ue extends le{async _call(T){return new qs(await super._call(T))}}class Ve extends le{async _call(T){return new Qt(await super._call(T))}}class Ne extends le{async _call(T){return new Hs(await super._call(T))}}class Re extends le{async _call(T){return new tr(await super._call(T))}}class st extends se{}class dt extends st{}class ct extends st{async _call(T){return new qs(await super._call(T))}}class lt extends st{async _call(T){return new Qt(await super._call(T))}}class ht extends st{async _call(T){return new Hs(await super._call(T))}}class L extends se{}class ie extends L{}class H extends se{}class me extends H{}class $e extends H{async _call(T){return new qs(await super._call(T))}}class We extends H{async _call(T){return new Qt(await super._call(T))}}class Je extends H{async _call(T){return new Hs(await super._call(T))}}class ut extends H{async _call(T){return new tr(await super._call(T))}}class mt extends se{}class vt extends mt{}class kt extends mt{async _call(T){return new qs(await super._call(T))}}class At extends mt{async _call(T){return new Qt(await super._call(T))}}class os extends mt{async _call(T){return new Hs(await super._call(T))}}class ys extends mt{async _call(T){return new tr(await super._call(T))}}class Cs extends se{}class Ds extends Cs{}class sr extends Cs{async _call(T){return new qs(await super._call(T))}}class Sr extends Cs{async _call(T){return new Qt(await super._call(T))}}class Yr extends Cs{async _call(T){return new Hs(await super._call(T))}}class Us extends Cs{async _call(T){return new tr(await super._call(T))}}class Pr extends se{}class Nt extends Pr{}class Jr extends Pr{async _call(T){return new qs(await super._call(T))}}class $r extends Pr{async _call(T){return new Qt(await super._call(T))}}class Ar extends Pr{async _call(T){return new Hs(await super._call(T))}}class Zr extends Pr{async _call(T){return new tr(await super._call(T))}}class cr extends se{}class en extends cr{}class Ir extends cr{async _call(T){return new qs(await super._call(T))}}class Rr extends cr{async _call(T){return new Qt(await super._call(T))}}class Nr extends cr{async _call(T){return new Hs(await super._call(T))}}class ar extends cr{async _call(T){return new tr(await super._call(T))}}class ot extends se{}class Tt extends ot{}class Dt extends ot{async _call(T){return new qs(await super._call(T))}}class Vs extends ot{async _call(T){return new Qt(await super._call(T))}}class jr extends ot{async _call(T){return new Hs(await super._call(T))}}class Or extends ot{async _call(T){return new tr(await super._call(T))}}class Ms extends se{}class lr extends Ms{}class Os extends Ms{async _call(T){return new Qt(await super._call(T))}}class Er extends Ms{async _call(T){return new Hs(await super._call(T))}}class es extends Ms{async _call(T){return new tr(await super._call(T))}}class wn extends Ms{async _call(T){return new qs(await super._call(T))}}class Ur extends se{}class oo extends Ur{}class An extends Ur{async _call(T){return new qs(await super._call(T))}}class In extends Ur{async _call(T){return new Qt(await super._call(T))}}class On extends Ur{async _call(T){return new Hs(await super._call(T))}}class Vr extends se{}class Fn extends Vr{}class io extends Vr{async _call(T){return new qs(await super._call(T))}}class Wr extends Vr{async _call(T){return new Qt(await super._call(T))}}class _r extends Vr{async _call(T){return new tr(await super._call(T))}}class ur extends se{}class yn extends ur{}class tn extends ur{async _call(T){return new qs(await super._call(T))}}class Mn extends ur{async _call(T){return new Qt(await super._call(T))}}class bn extends ur{async _call(T){return new Hs(await super._call(T))}}class vn extends ur{async _call(T){return new tr(await super._call(T))}}class zt extends se{}class xn extends zt{}class Dn extends zt{async _call(T){return new qs(await super._call(T))}}class Ln extends zt{async _call(T){return new Qt(await super._call(T))}}class zn extends zt{async _call(T){return new tr(await super._call(T))}}class Gr extends se{}class Bn extends Gr{}class Tn extends Gr{async _call(T){return new Qt(await super._call(T))}}class Rn extends Gr{async _call(T){return new tr(await super._call(T))}}class as extends Gr{async _call(T){return new qs(await super._call(T))}}class Pe extends se{constructor(){super(...arguments);_e(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"])}}class P extends Pe{}class Q extends Pe{}class ue extends se{}class be extends ue{}class Se extends ue{}class Qe extends se{}class pt extends Qe{}class gt extends Qe{}class _t extends se{}class xt extends _t{}class Kt extends _t{}class ms extends _t{async _call(T){return new Qt(await super._call(T))}}class us extends se{}class Fs extends us{}class Bt extends us{}class rs extends us{async _call(T){return new Qt(await super._call(T))}}class rr extends us{}class Ws extends se{}class ze extends Ws{}class Js extends Ws{}class Fr extends se{}class ks extends Fr{}class Xs extends Fr{}class Ot extends se{}class or extends Ot{}class fr extends Ot{async _call(T){return new qs(await super._call(T))}}class _s extends Ot{async _call(T){return new Qt(await super._call(T))}}class Ss extends Ot{async _call(T){return new Hs(await super._call(T))}}class yt extends Ot{async _call(T){return new tr(await super._call(T))}}class qt extends se{}class Ls extends qt{}class $s extends qt{async _call(T){return new qs(await super._call(T))}}class Gs extends qt{async _call(T){return new Qt(await super._call(T))}}class $t extends qt{async _call(T){return new Hs(await super._call(T))}}class sn extends qt{async _call(T){return new tr(await super._call(T))}}class qe extends se{}class It extends qe{}class La extends qe{async _call(T){return new qs(await super._call(T))}}class Uo extends qe{async _call(T){return new Qt(await super._call(T))}}class za extends qe{async _call(T){return new Hs(await super._call(T))}}class Ba extends qe{async _call(T){return new tr(await super._call(T))}}class Yt extends se{}class Ra extends Yt{}class Vo extends Yt{}class Wo extends se{constructor(){super(...arguments);_e(this,"requires_attention_mask",!1);_e(this,"main_input_name","input_features");_e(this,"forward_params",["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"])}}class Na extends Wo{}class ja extends Wo{_prepare_generation_config(T,N){return super._prepare_generation_config(T,N,j.WhisperGenerationConfig)}_retrieve_init_tokens(T){const N=[T.decoder_start_token_id];let fe=T.language;const Fe=T.task;if(T.is_multilingual){fe||(console.warn("No language specified - defaulting to English (en)."),fe="en");const et=`<|${(0,q.whisper_language_to_code)(fe)}|>`;N.push(T.lang_to_id[et]),N.push(T.task_to_id[Fe??"transcribe"])}else if(fe||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!T.return_timestamps&&T.no_timestamps_token_id&&N.at(-1)!==T.no_timestamps_token_id?N.push(T.no_timestamps_token_id):T.return_timestamps&&N.at(-1)===T.no_timestamps_token_id&&(console.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),N.pop()),N.filter(Ae=>Ae!=null)}async generate({inputs:T=null,generation_config:N=null,logits_processor:fe=null,stopping_criteria:Fe=null,...Ae}){N=this._prepare_generation_config(N,Ae);const et=Ae.decoder_input_ids??this._retrieve_init_tokens(N);if(N.return_timestamps&&(fe??(fe=new M.LogitsProcessorList),fe.push(new M.WhisperTimeStampLogitsProcessor(N,et))),N.begin_suppress_tokens&&(fe??(fe=new M.LogitsProcessorList),fe.push(new M.SuppressTokensAtBeginLogitsProcessor(N.begin_suppress_tokens,et.length))),N.return_token_timestamps){if(!N.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.");N.task==="translate"&&console.warn("Token-level timestamps may not be reliable for task 'translate'."),N.output_attentions=!0,N.return_dict_in_generate=!0}const rt=await super.generate({inputs:T,generation_config:N,logits_processor:fe,decoder_input_ids:et,...Ae});return N.return_token_timestamps&&(rt.token_timestamps=this._extract_token_timestamps(rt,N.alignment_heads,N.num_frames)),rt}_extract_token_timestamps(T,N,fe=null,Fe=.02){if(!T.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`.");fe==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 Ae=this.config.median_filter_width;Ae===void 0&&(console.warn("Model config has no `median_filter_width`, using default value of 7."),Ae=7);const et=T.cross_attentions,rt=Array.from({length:this.config.decoder_layers},(ns,Jt)=>(0,b.cat)(et.map(is=>is[Jt]),2)),ft=(0,b.stack)(N.map(([ns,Jt])=>{if(ns>=rt.length)throw new Error(`Layer index ${ns} is out of bounds for cross attentions (length ${rt.length}).`);return fe?rt[ns].slice(null,Jt,null,[0,fe]):rt[ns].slice(null,Jt)})).transpose(1,0,2,3),[Mt,jt]=(0,b.std_mean)(ft,-2,0,!0),Vt=ft.clone();for(let ns=0;nsis[Zs+1]-is[Zs]),cs=(0,R.mergeArrays)([1],xs).map(Is=>!!Is),Es=[];for(let Is=0;IsLt.findIndex(Gt=>Gt==Ae)),ft=rt.every(Lt=>Lt===-1),Mt=rt.every(Lt=>Lt!==-1);if(!ft&&!Mt)throw new Error("Every input should contain either 0 or 1 image token.");if(ft)return{inputs_embeds:T,attention_mask:Fe};const jt=[],Vt=[];for(let Lt=0;LtArray.from({length:T.dims[0]},xs=>Array.from({length:T.dims[1]},cs=>1))),ts=N?N.tolist():[],ns=fe?fe.tolist():[];let Jt=0,is=0;for(let As=0;AsLt[As][Rs]==1),Es=xs.reduce((Ts,Rs,qr)=>(Rs==ft&&Ts.push(qr),Ts),[]).map(Ts=>xs[Ts+1]),Is=Es.filter(Ts=>Ts==et).length,Zs=Es.filter(Ts=>Ts==rt).length;let Ys=[],br=0,pn=Is,ka=Zs;for(let Ts=0;Tsmr>br&&Qr==et),qr=xs.findIndex((Qr,mr)=>mr>br&&Qr==rt),En=pn>0&&Rs!==-1?Rs:xs.length+1,Cn=ka>0&&qr!==-1?qr:xs.length+1;let kn,$a,Aa,Ec;En0?(0,K.max)(Ys.at(-1))[0]+1:0;Ys.push(Array.from({length:3*zr},(Qr,mr)=>Cc+mr%zr));const Qn=zr+Cc,Xn=kp*Do*qn,kc=Array.from({length:Xn},(Qr,mr)=>Qn+Math.floor(mr/(Do*qn))),Sc=Array.from({length:Xn},(Qr,mr)=>Qn+Math.floor(mr/qn)%Do),$c=Array.from({length:Xn},(Qr,mr)=>Qn+mr%qn);Ys.push([kc,Sc,$c].flat()),br=kn+Xn}if(br0?(0,K.max)(Ys.at(-1))[0]+1:0,Rs=xs.length-br;Ys.push(Array.from({length:3*Rs},(qr,En)=>Ts+En%Rs))}const ir=Ys.reduce((Ts,Rs)=>Ts+Rs.length,0),vr=new Array(ir);let Io=0;for(let Ts=0;Ts<3;++Ts)for(let Rs=0;RsVt[Jt%Vt.length]),ts=Array.from({length:Lt[0]},(ns,Jt)=>(0,K.max)(Vt.subarray(Lt[1]*Jt,Lt[1]*(Jt+1)))[0]+1n+BigInt(Lt[1]));return[new b.Tensor("int64",Gt,[3,...Lt]),new b.Tensor("int64",ts,[ts.length,1])]}else{const[Vt,Lt]=T.dims,Gt=BigInt64Array.from({length:3*Vt*Lt},(ts,ns)=>BigInt(Math.floor(ns%Lt/Vt)));return[new b.Tensor("int64",Gt,[3,...T.dims]),(0,b.zeros)([Vt,1])]}}async encode_image({pixel_values:T,image_grid_thw:N}){return(await we(this.sessions.vision_encoder,{pixel_values:T,grid_thw:N})).image_features}_merge_input_ids_with_image_features(T){return tt({image_token_id:this.config.image_token_id,...T})}prepare_inputs_for_generation(T,N,fe){if(N.attention_mask&&!N.position_ids)if(!N.past_key_values)[N.position_ids,N.rope_deltas]=this.get_rope_index(N.input_ids,N.image_grid_thw,N.video_grid_thw,N.attention_mask);else{N.pixel_values=null;const Fe=BigInt(Object.values(N.past_key_values)[0].dims.at(-2)),Ae=N.rope_deltas.map(et=>Fe+et);N.position_ids=(0,b.stack)([Ae,Ae,Ae],0)}return N}}class yi extends se{}class Dl extends yi{}class Ll extends yi{}class Mi extends se{}class zl extends Mi{}class Bl extends Mi{}class bi extends se{}class Rl extends bi{}class Nl extends bi{}class vi extends se{}class jl extends vi{}class Ul extends vi{}class xi extends se{}class Vl extends xi{}class Wl extends xi{}class mo extends se{}class Gl extends mo{}class Ti extends mo{async _call(T){return new Qt(await super._call(T))}}class _o extends se{}class Kl extends _o{}class Hl extends _o{async _call(T){return new Qt(await super._call(T))}}class ql extends se{}class Ql extends ql{}class Pi extends se{}class Xl extends Pi{}class Ei extends Pi{async _call(T){return new Qt(await super._call(T))}}class Yl extends se{}class Jl extends Yl{}class Ci extends se{}class Gc extends Ci{}class Zl extends Ci{async _call(T){return new Qt(await super._call(T))}}class eu extends se{}class Mr extends eu{}class ki extends se{}class tu extends ki{}class su extends ki{async _call(T){return new Qt(await super._call(T))}}class ru extends se{}class nu extends ru{async _call(T){return new Pc(await super._call(T))}}class Si extends se{}class ou extends Si{}class iu extends Si{async _call(T){return new Qt(await super._call(T))}}class $i extends se{}class au extends $i{}class Kc extends $i{async _call(T){return new Qt(await super._call(T))}}class Ai extends se{}class lu extends Ai{}class uu extends Ai{}class Ii extends se{}class du extends Ii{}class cu extends Ii{}class pu extends se{}class nn extends pu{}class on extends pu{async _call(T){return new Qt(await super._call(T))}}class Dr extends se{}class Oi extends Dr{}class an extends Dr{async _call(T){return new Fi(await super._call(T))}}class Ks extends Dr{async _call(T){return new Di(await super._call(T))}}class Fi extends Ke{constructor({logits:T,pred_boxes:N}){super(),this.logits=T,this.pred_boxes=N}}class Di extends Ke{constructor({logits:T,pred_boxes:N,pred_masks:fe}){super(),this.logits=T,this.pred_boxes=N,this.pred_masks=fe}}class Li extends se{}class Hc extends Li{}class Un extends Li{async _call(T){return new zi(await super._call(T))}}class zi extends Ke{constructor({logits:T,pred_boxes:N}){super(),this.logits=T,this.pred_boxes=N}}class fo extends se{}class hu extends fo{}class mu extends fo{async _call(T){return new Bi(await super._call(T))}}class Bi extends Fi{}class go extends se{}class _u extends go{}class Ri extends go{async _call(T){return new Qt(await super._call(T))}}class Ni extends se{}class wo extends Ni{}class ji extends Ni{async _call(T){return new Qt(await super._call(T))}}class Ui extends se{}class fu extends Ui{}class qc extends Ui{async _call(T){return new Qt(await super._call(T))}}class Vi extends se{}class Wi extends Vi{}class Vn extends Vi{async _call(T){return new Qt(await super._call(T))}}class Gi extends se{}class Ki extends Gi{}class gu extends Gi{}class Hi extends se{}class wu extends Hi{}class Qc extends Hi{}class yu extends se{}class Mu extends yu{}class qi extends se{}class bu extends qi{}class yo extends qi{}class vu extends qi{}class Mo extends se{}class Qi extends Mo{}class bo extends se{}class xu extends bo{}class Tu extends bo{}class vo extends se{}class Xc extends vo{}class Pu extends vo{}class Yc extends se{}class Eu extends Yc{}class Xi extends se{}class Cu extends Xi{}class Yi extends Xi{async _call(T){return new Qt(await super._call(T))}}class Ji extends se{}class ku extends Ji{}class Zi extends Ji{async _call(T){return new Qt(await super._call(T))}}class ea extends se{}class Su extends ea{}class Jc extends ea{async _call(T){return new Qt(await super._call(T))}}class ta extends se{}class $u extends ta{}class Au extends ta{async _call(T){return new Qt(await super._call(T))}}class Zc extends se{}class Iu extends Zc{}class sa extends se{}class Ou extends sa{}class Fu extends sa{async _call(T){return new Du(await super._call(T))}}class Du extends Ke{constructor({logits:T,pred_boxes:N}){super(),this.logits=T,this.pred_boxes=N}}class ep extends se{}class xo extends ep{async get_image_embeddings({pixel_values:T}){return await Ie(this,{pixel_values:T})}async forward(T){if((!T.image_embeddings||!T.image_positional_embeddings)&&(T={...T,...await this.get_image_embeddings(T)}),!T.input_labels&&T.input_points){const fe=T.input_points.dims.slice(0,-1),Fe=fe.reduce((Ae,et)=>Ae*et,1);T.input_labels=new b.Tensor("int64",new BigInt64Array(Fe).fill(1n),fe)}const N={image_embeddings:T.image_embeddings,image_positional_embeddings:T.image_positional_embeddings};return T.input_points&&(N.input_points=T.input_points),T.input_labels&&(N.input_labels=T.input_labels),T.input_boxes&&(N.input_boxes=T.input_boxes),await we(this.sessions.prompt_encoder_mask_decoder,N)}async _call(T){return new Wn(await super._call(T))}}class Wn extends Ke{constructor({iou_scores:T,pred_masks:N}){super(),this.iou_scores=T,this.pred_masks=N}}class To extends se{}class Lu extends To{}class zu extends To{}class ra extends se{}class Bu extends ra{}class na extends ra{}class Hr extends se{}class Ru extends Hr{}class Nu extends Hr{async _call(T){return new cn(await super._call(T))}}class tp extends Hr{async _call(T){return new Qt(await super._call(T))}}class ju extends Hr{async _call(T){return new Hs(await super._call(T))}}class Po extends se{}class Uu extends Po{}class Vu extends Po{async _call(T){return new Hs(await super._call(T))}}class Wu extends se{}class sp extends Wu{}class Eo extends se{}class Gu extends Eo{}class rp extends Eo{async _call(T){return new cn(await super._call(T))}}class Ku extends Eo{async _call(T){return new Qt(await super._call(T))}}class Gn extends se{}class Hu extends Gn{}class qu extends Gn{async _call(T){return new cn(await super._call(T))}}class np extends Gn{async _call(T){return new Qt(await super._call(T))}}class Qu extends Gn{async _call(T){return new Hs(await super._call(T))}}class Co extends se{}class Xu extends Co{}class op extends Co{async _call(T){return new cn(await super._call(T))}}class Yu extends Co{async _call(T){return new Qt(await super._call(T))}}class ip extends se{}class Ju extends Hr{}class Zu extends Hr{async _call(T){return new cn(await super._call(T))}}class ap extends Hr{async _call(T){return new Qt(await super._call(T))}}class Pn extends se{}class ed extends Pn{}class td extends Pn{async _call(T){return new cn(await super._call(T))}}class sd extends Pn{async _call(T){return new Qt(await super._call(T))}}class lp extends Pn{async _call(T){return new Hn(await super._call(T))}}class rd extends Pn{async _call(T){return new Hs(await super._call(T))}}class nd extends se{}class od extends nd{}class ko extends se{}class Kp extends ko{}class Cr extends ko{}class Lr extends ko{async generate_speech(T,N,{threshold:fe=.5,minlenratio:Fe=0,maxlenratio:Ae=20,vocoder:et=null}={}){const rt={input_ids:T},{encoder_outputs:ft,encoder_attention_mask:Mt}=await Ie(this,rt),jt=ft.dims[1]/this.config.reduction_factor,Vt=Math.floor(jt*Ae),Lt=Math.floor(jt*Fe),Gt=this.config.num_mel_bins;let ts=[],ns=null,Jt=null,is=0;for(;;){++is;const cs=ce(!!Jt);let Es;Jt?Es=Jt.output_sequence_out:Es=new b.Tensor("float32",new Float32Array(Gt),[1,1,Gt]);let Is={use_cache_branch:cs,output_sequence:Es,encoder_attention_mask:Mt,speaker_embeddings:N,encoder_hidden_states:ft};this.addPastKeyValues(Is,ns),Jt=await we(this.sessions.decoder_model_merged,Is),ns=this.getPastKeyValues(Jt,ns);const{prob:Zs,spectrum:Ys}=Jt;if(ts.push(Ys),is>=Lt&&(Array.from(Zs.data).filter(br=>br>=fe).length>0||is>=Vt))break}const As=(0,b.cat)(ts),{waveform:xs}=await we(et.sessions.model,{spectrogram:As});return{spectrogram:As,waveform:xs}}}class ln extends se{constructor(){super(...arguments);_e(this,"main_input_name","spectrogram")}}class un extends se{}class id extends un{}class oa extends se{}class ad extends oa{}class ld extends oa{}class ia extends se{}class ud extends ia{}class dd extends ia{}class aa extends se{}class cd extends aa{}class pd extends aa{}class la extends se{}class nr extends la{}class hd extends la{static async from_pretrained(T,N={}){return super.from_pretrained(T,{...N,model_file_name:N.model_file_name??"text_model"})}}class md extends la{static async from_pretrained(T,N={}){return super.from_pretrained(T,{...N,model_file_name:N.model_file_name??"audio_model"})}}class ua extends se{}class da extends ua{async _call(T){return new Cp(await super._call(T))}}class dn extends se{}class up extends dn{}class _d extends dn{}class fd extends dn{}class ca extends se{}class gd extends ca{}class wd extends ca{}class So extends se{}class yd extends So{}class Md extends So{async _call(T){return new Qt(await super._call(T))}}class pa extends se{}class dp extends pa{}class cp extends pa{}class $o extends se{constructor(){super(...arguments);_e(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(N){const[fe,Fe]=N.dims,Ae=this.config.decoder.num_codebooks,et=Fe-Ae;let rt=0;for(let jt=0;jt0&&Gt<=et&&(N.data[rt++]=N.data[jt])}const ft=Math.floor(fe/Ae),Mt=rt/(ft*Ae);return new b.Tensor(N.type,N.data.slice(0,rt),[ft,Ae,Mt])}prepare_inputs_for_generation(N,fe,Fe){let Ae=structuredClone(N);for(let rt=0;rt=ft&&(Ae[rt][ft]=BigInt(this.config.decoder.pad_token_id));return Fe.guidance_scale!==null&&Fe.guidance_scale>1&&(Ae=Ae.concat(Ae)),super.prepare_inputs_for_generation(Ae,fe,Fe)}async generate(N){const fe=await super.generate(N),Fe=this._apply_and_filter_by_delay_pattern_mask(fe).unsqueeze_(0),{audio_values:Ae}=await we(this.sessions.encodec_decode,{audio_codes:Fe});return Ae}}class ha extends se{}class pp extends ha{}class ma extends ha{async _call(T){return new Qt(await super._call(T))}}class _a extends se{}class bd extends _a{}class vd extends _a{async _call(T){return new Qt(await super._call(T))}}class xd extends se{}class Td extends xd{}class Pd extends xd{async _call(T){return new Qt(await super._call(T))}}class fa extends se{}class hp extends fa{}class Ed extends fa{async _call(T){return new Qt(await super._call(T))}}class Cd extends se{}class mp extends Cd{}class kd extends se{}class Sd extends kd{constructor(...N){super(...N);_e(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(N){const fe=this._generation_mode??"text";let Fe;if(fe==="text"||!N.past_key_values){const Mt=this.sessions.prepare_inputs_embeds,jt=(0,R.pick)(N,Mt.inputNames);Fe=await we(Mt,jt)}else{const Mt=this.sessions.gen_img_embeds,jt=(0,R.pick)({image_ids:N.input_ids},Mt.inputNames);Fe=await we(Mt,jt)}const Ae={...N,...Fe},et=await Ee(this,Ae),rt=this.sessions[fe==="text"?"lm_head":"gen_head"];if(!rt)throw new Error(`Unable to find "${rt}" generation head`);const ft=await we(rt,(0,R.pick)(et,rt.inputNames));return{...Fe,...et,...ft}}async generate(N){return this._generation_mode="text",super.generate(N)}async generate_images(N){this._generation_mode="image";const fe=(N.inputs??N[this.main_input_name]).dims[1],Ae=(await super.generate(N)).slice(null,[fe,null]),et=this.sessions.image_decode,{decoded_image:rt}=await we(et,{generated_tokens:Ae}),ft=rt.add_(1).mul_(255/2).clamp_(0,255).to("uint8"),Mt=[];for(const jt of ft){const Vt=I.RawImage.fromTensor(jt);Mt.push(Vt)}return Mt}}class $d extends Ke{constructor({char_logits:T,bpe_logits:N,wp_logits:fe}){super(),this.char_logits=T,this.bpe_logits=N,this.wp_logits=fe}get logits(){return[this.char_logits,this.bpe_logits,this.wp_logits]}}class Ad extends se{}class Id extends Ad{async _call(T){return new $d(await super._call(T))}}class Od extends se{}class Fd extends Od{}class Dd extends Od{}class ga extends se{}class Ld extends ga{}class zd extends ga{}class ws{static async from_pretrained(T,{progress_callback:N=null,config:fe=null,cache_dir:Fe=null,local_files_only:Ae=!1,revision:et="main",model_file_name:rt=null,subfolder:ft="onnx",device:Mt=null,dtype:jt=null,use_external_data_format:Vt=null,session_options:Lt={}}={}){const Gt={progress_callback:N,config:fe,cache_dir:Fe,local_files_only:Ae,revision:et,model_file_name:rt,subfolder:ft,device:Mt,dtype:jt,use_external_data_format:Vt,session_options:Lt};if(Gt.config=await f.AutoConfig.from_pretrained(T,Gt),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);for(const ts of this.MODEL_CLASS_MAPPINGS){const ns=ts.get(Gt.config.model_type);if(ns)return await ns[1].from_pretrained(T,Gt)}if(this.BASE_IF_FAIL)return console.warn(`Unknown model class "${Gt.config.model_type}", attempting to construct from base class.`),await se.from_pretrained(T,Gt);throw Error(`Unsupported model type: ${Gt.config.model_type}`)}}_e(ws,"MODEL_CLASS_MAPPINGS",null),_e(ws,"BASE_IF_FAIL",!1);const _p=new Map([["bert",["BertModel",Te]],["modernbert",["ModernBertModel",dt]],["nomic_bert",["NomicBertModel",ie]],["roformer",["RoFormerModel",me]],["electra",["ElectraModel",Ds]],["esm",["EsmModel",oo]],["convbert",["ConvBertModel",vt]],["camembert",["CamembertModel",Nt]],["deberta",["DebertaModel",en]],["deberta-v2",["DebertaV2Model",Tt]],["mpnet",["MPNetModel",yn]],["albert",["AlbertModel",Bn]],["distilbert",["DistilBertModel",lr]],["roberta",["RobertaModel",or]],["xlm",["XLMModel",Ls]],["xlm-roberta",["XLMRobertaModel",It]],["clap",["ClapModel",nr]],["clip",["CLIPModel",Ya]],["clipseg",["CLIPSegModel",rl]],["chinese_clip",["ChineseCLIPModel",gr]],["siglip",["SiglipModel",el]],["jina_clip",["JinaCLIPModel",uo]],["mobilebert",["MobileBertModel",Fn]],["squeezebert",["SqueezeBertModel",xn]],["wav2vec2",["Wav2Vec2Model",Ru]],["wav2vec2-bert",["Wav2Vec2BertModel",Xu]],["unispeech",["UniSpeechModel",Gu]],["unispeech-sat",["UniSpeechSatModel",Hu]],["hubert",["HubertModel",Ju]],["wavlm",["WavLMModel",ed]],["audio-spectrogram-transformer",["ASTModel",Ra]],["vits",["VitsModel",da]],["pyannote",["PyAnnoteModel",Uu]],["wespeaker-resnet",["WeSpeakerResNetModel",sp]],["detr",["DetrModel",Oi]],["rt_detr",["RTDetrModel",Hc]],["table-transformer",["TableTransformerModel",hu]],["vit",["ViTModel",Gl]],["ijepa",["IJepaModel",Kl]],["pvt",["PvtModel",Xl]],["vit_msn",["ViTMSNModel",Gc]],["vit_mae",["ViTMAEModel",Jl]],["groupvit",["GroupViTModel",Mr]],["fastvit",["FastViTModel",tu]],["mobilevit",["MobileViTModel",ou]],["mobilevitv2",["MobileViTV2Model",au]],["owlvit",["OwlViTModel",lu]],["owlv2",["Owlv2Model",du]],["beit",["BeitModel",nn]],["deit",["DeiTModel",_u]],["hiera",["HieraModel",wo]],["convnext",["ConvNextModel",Cu]],["convnextv2",["ConvNextV2Model",ku]],["dinov2",["Dinov2Model",Su]],["dinov2_with_registers",["Dinov2WithRegistersModel",$u]],["resnet",["ResNetModel",fu]],["swin",["SwinModel",Wi]],["swin2sr",["Swin2SRModel",Ki]],["donut-swin",["DonutSwinModel",Eu]],["yolos",["YolosModel",Ou]],["dpt",["DPTModel",wu]],["glpn",["GLPNModel",Xc]],["hifigan",["SpeechT5HifiGan",ln]],["efficientnet",["EfficientNetModel",yd]],["decision_transformer",["DecisionTransformerModel",mp]],["patchtst",["PatchTSTForPrediction",Fd]],["patchtsmixer",["PatchTSMixerForPrediction",Ld]],["mobilenet_v1",["MobileNetV1Model",pp]],["mobilenet_v2",["MobileNetV2Model",bd]],["mobilenet_v3",["MobileNetV3Model",Td]],["mobilenet_v4",["MobileNetV4Model",hp]],["maskformer",["MaskFormerModel",xu]],["mgp-str",["MgpstrForSceneTextRecognition",Id]],["style_text_to_speech_2",["StyleTextToSpeech2Model",od]]]),fp=new Map([["t5",["T5Model",P]],["longt5",["LongT5Model",be]],["mt5",["MT5Model",pt]],["bart",["BartModel",xt]],["mbart",["MBartModel",Fs]],["marian",["MarianModel",Lu]],["whisper",["WhisperModel",Na]],["m2m_100",["M2M100Model",Bu]],["blenderbot",["BlenderbotModel",ze]],["blenderbot-small",["BlenderbotSmallModel",ks]]]),gp=new Map([["bloom",["BloomModel",Rl]],["jais",["JAISModel",al]],["gpt2",["GPT2Model",ol]],["gptj",["GPTJModel",pl]],["gpt_bigcode",["GPTBigCodeModel",ml]],["gpt_neo",["GPTNeoModel",yr]],["gpt_neox",["GPTNeoXModel",dl]],["codegen",["CodeGenModel",ri]],["llama",["LlamaModel",oi]],["exaone",["ExaoneModel",yl]],["olmo",["OlmoModel",Vc]],["olmo2",["Olmo2Model",xl]],["mobilellm",["MobileLLMModel",Ml]],["granite",["GraniteModel",ds]],["cohere",["CohereModel",Pl]],["gemma",["GemmaModel",Cl]],["gemma2",["Gemma2Model",Sl]],["helium",["HeliumModel",po]],["glm",["GlmModel",wl]],["openelm",["OpenELMModel",Al]],["qwen2",["Qwen2Model",jn]],["phi",["PhiModel",Dl]],["phi3",["Phi3Model",zl]],["mpt",["MptModel",jl]],["opt",["OPTModel",Vl]],["mistral",["MistralModel",ad]],["starcoder2",["Starcoder2Model",ud]],["falcon",["FalconModel",cd]],["stablelm",["StableLmModel",gd]]]),Bd=new Map([["speecht5",["SpeechT5ForSpeechToText",Cr]],["whisper",["WhisperForConditionalGeneration",ja]],["moonshine",["MoonshineForConditionalGeneration",Ua]]]),Kn=new Map([["speecht5",["SpeechT5ForTextToSpeech",Lr]]]),wa=new Map([["vits",["VitsModel",da]],["musicgen",["MusicgenForConditionalGeneration",$o]]]),ya=new Map([["bert",["BertForSequenceClassification",Ve]],["modernbert",["ModernBertForSequenceClassification",lt]],["roformer",["RoFormerForSequenceClassification",We]],["electra",["ElectraForSequenceClassification",Sr]],["esm",["EsmForSequenceClassification",In]],["convbert",["ConvBertForSequenceClassification",At]],["camembert",["CamembertForSequenceClassification",$r]],["deberta",["DebertaForSequenceClassification",Rr]],["deberta-v2",["DebertaV2ForSequenceClassification",Vs]],["mpnet",["MPNetForSequenceClassification",Mn]],["albert",["AlbertForSequenceClassification",Tn]],["distilbert",["DistilBertForSequenceClassification",Os]],["roberta",["RobertaForSequenceClassification",_s]],["xlm",["XLMForSequenceClassification",Gs]],["xlm-roberta",["XLMRobertaForSequenceClassification",Uo]],["bart",["BartForSequenceClassification",ms]],["mbart",["MBartForSequenceClassification",rs]],["mobilebert",["MobileBertForSequenceClassification",Wr]],["squeezebert",["SqueezeBertForSequenceClassification",Ln]]]),Ma=new Map([["bert",["BertForTokenClassification",Ne]],["modernbert",["ModernBertForTokenClassification",ht]],["roformer",["RoFormerForTokenClassification",Je]],["electra",["ElectraForTokenClassification",Yr]],["esm",["EsmForTokenClassification",On]],["convbert",["ConvBertForTokenClassification",os]],["camembert",["CamembertForTokenClassification",Ar]],["deberta",["DebertaForTokenClassification",Nr]],["deberta-v2",["DebertaV2ForTokenClassification",jr]],["mpnet",["MPNetForTokenClassification",bn]],["distilbert",["DistilBertForTokenClassification",Er]],["roberta",["RobertaForTokenClassification",Ss]],["xlm",["XLMForTokenClassification",$t]],["xlm-roberta",["XLMRobertaForTokenClassification",za]]]),Ao=new Map([["t5",["T5ForConditionalGeneration",Q]],["longt5",["LongT5ForConditionalGeneration",Se]],["mt5",["MT5ForConditionalGeneration",gt]],["bart",["BartForConditionalGeneration",Kt]],["mbart",["MBartForConditionalGeneration",Bt]],["marian",["MarianMTModel",zu]],["m2m_100",["M2M100ForConditionalGeneration",na]],["blenderbot",["BlenderbotForConditionalGeneration",Js]],["blenderbot-small",["BlenderbotSmallForConditionalGeneration",Xs]]]),ba=new Map([["bloom",["BloomForCausalLM",Nl]],["gpt2",["GPT2LMHeadModel",il]],["jais",["JAISLMHeadModel",ll]],["gptj",["GPTJForCausalLM",hl]],["gpt_bigcode",["GPTBigCodeForCausalLM",_l]],["gpt_neo",["GPTNeoForCausalLM",ul]],["gpt_neox",["GPTNeoXForCausalLM",cl]],["codegen",["CodeGenForCausalLM",fl]],["llama",["LlamaForCausalLM",Uc]],["exaone",["ExaoneForCausalLM",ui]],["olmo",["OlmoForCausalLM",vl]],["olmo2",["Olmo2ForCausalLM",Wc]],["mobilellm",["MobileLLMForCausalLM",bl]],["granite",["GraniteForCausalLM",Tl]],["cohere",["CohereForCausalLM",El]],["gemma",["GemmaForCausalLM",kl]],["gemma2",["Gemma2ForCausalLM",$l]],["helium",["HeliumForCausalLM",gl]],["glm",["GlmForCausalLM",Nn]],["openelm",["OpenELMForCausalLM",Il]],["qwen2",["Qwen2ForCausalLM",Ol]],["phi",["PhiForCausalLM",Ll]],["phi3",["Phi3ForCausalLM",Bl]],["mpt",["MptForCausalLM",Ul]],["opt",["OPTForCausalLM",Wl]],["mbart",["MBartForCausalLM",rr]],["mistral",["MistralForCausalLM",ld]],["starcoder2",["Starcoder2ForCausalLM",dd]],["falcon",["FalconForCausalLM",pd]],["trocr",["TrOCRForCausalLM",id]],["stablelm",["StableLmForCausalLM",wd]],["phi3_v",["Phi3VForCausalLM",hr]]]),wp=new Map([["multi_modality",["MultiModalityCausalLM",Sd]]]),va=new Map([["bert",["BertForMaskedLM",Ue]],["modernbert",["ModernBertForMaskedLM",ct]],["roformer",["RoFormerForMaskedLM",$e]],["electra",["ElectraForMaskedLM",sr]],["esm",["EsmForMaskedLM",An]],["convbert",["ConvBertForMaskedLM",kt]],["camembert",["CamembertForMaskedLM",Jr]],["deberta",["DebertaForMaskedLM",Ir]],["deberta-v2",["DebertaV2ForMaskedLM",Dt]],["mpnet",["MPNetForMaskedLM",tn]],["albert",["AlbertForMaskedLM",as]],["distilbert",["DistilBertForMaskedLM",wn]],["roberta",["RobertaForMaskedLM",fr]],["xlm",["XLMWithLMHeadModel",$s]],["xlm-roberta",["XLMRobertaForMaskedLM",La]],["mobilebert",["MobileBertForMaskedLM",io]],["squeezebert",["SqueezeBertForMaskedLM",Dn]]]),xa=new Map([["bert",["BertForQuestionAnswering",Re]],["roformer",["RoFormerForQuestionAnswering",ut]],["electra",["ElectraForQuestionAnswering",Us]],["convbert",["ConvBertForQuestionAnswering",ys]],["camembert",["CamembertForQuestionAnswering",Zr]],["deberta",["DebertaForQuestionAnswering",ar]],["deberta-v2",["DebertaV2ForQuestionAnswering",Or]],["mpnet",["MPNetForQuestionAnswering",vn]],["albert",["AlbertForQuestionAnswering",Rn]],["distilbert",["DistilBertForQuestionAnswering",es]],["roberta",["RobertaForQuestionAnswering",yt]],["xlm",["XLMForQuestionAnswering",sn]],["xlm-roberta",["XLMRobertaForQuestionAnswering",Ba]],["mobilebert",["MobileBertForQuestionAnswering",_r]],["squeezebert",["SqueezeBertForQuestionAnswering",zn]]]),Ta=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",Ko]],["idefics3",["Idefics3ForConditionalGeneration",Ho]]]),yp=new Map([["llava",["LlavaForConditionalGeneration",ao]],["llava_onevision",["LlavaOnevisionForConditionalGeneration",Va]],["moondream1",["Moondream1ForConditionalGeneration",Wa]],["florence2",["Florence2ForConditionalGeneration",Ka]],["qwen2-vl",["Qwen2VLForConditionalGeneration",Fl]],["idefics3",["Idefics3ForConditionalGeneration",Ho]],["paligemma",["PaliGemmaForConditionalGeneration",qa]]]),Rd=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",Ko]]]),Nd=new Map([["vit",["ViTForImageClassification",Ti]],["ijepa",["IJepaForImageClassification",Hl]],["pvt",["PvtForImageClassification",Ei]],["vit_msn",["ViTMSNForImageClassification",Zl]],["fastvit",["FastViTForImageClassification",su]],["mobilevit",["MobileViTForImageClassification",iu]],["mobilevitv2",["MobileViTV2ForImageClassification",Kc]],["beit",["BeitForImageClassification",on]],["deit",["DeiTForImageClassification",Ri]],["hiera",["HieraForImageClassification",ji]],["convnext",["ConvNextForImageClassification",Yi]],["convnextv2",["ConvNextV2ForImageClassification",Zi]],["dinov2",["Dinov2ForImageClassification",Jc]],["dinov2_with_registers",["Dinov2WithRegistersForImageClassification",Au]],["resnet",["ResNetForImageClassification",qc]],["swin",["SwinForImageClassification",Vn]],["segformer",["SegformerForImageClassification",_d]],["efficientnet",["EfficientNetForImageClassification",Md]],["mobilenet_v1",["MobileNetV1ForImageClassification",ma]],["mobilenet_v2",["MobileNetV2ForImageClassification",vd]],["mobilenet_v3",["MobileNetV3ForImageClassification",Pd]],["mobilenet_v4",["MobileNetV4ForImageClassification",Ed]]]),jd=new Map([["detr",["DetrForObjectDetection",an]],["rt_detr",["RTDetrForObjectDetection",Un]],["table-transformer",["TableTransformerForObjectDetection",mu]],["yolos",["YolosForObjectDetection",Fu]]]),Pa=new Map([["owlvit",["OwlViTForObjectDetection",uu]],["owlv2",["Owlv2ForObjectDetection",cu]],["grounding-dino",["GroundingDinoForObjectDetection",Iu]]]),Ud=new Map([["detr",["DetrForSegmentation",Ks]],["clipseg",["CLIPSegForImageSegmentation",nl]]]),Vd=new Map([["segformer",["SegformerForSemanticSegmentation",fd]],["sapiens",["SapiensForSemanticSegmentation",bu]]]),Wd=new Map([["detr",["DetrForSegmentation",Ks]],["maskformer",["MaskFormerForInstanceSegmentation",Tu]]]),Gd=new Map([["sam",["SamModel",xo]]]),Mp=new Map([["wav2vec2",["Wav2Vec2ForCTC",Nu]],["wav2vec2-bert",["Wav2Vec2BertForCTC",op]],["unispeech",["UniSpeechForCTC",rp]],["unispeech-sat",["UniSpeechSatForCTC",qu]],["wavlm",["WavLMForCTC",td]],["hubert",["HubertForCTC",Zu]]]),Kd=new Map([["wav2vec2",["Wav2Vec2ForSequenceClassification",tp]],["wav2vec2-bert",["Wav2Vec2BertForSequenceClassification",Yu]],["unispeech",["UniSpeechForSequenceClassification",Ku]],["unispeech-sat",["UniSpeechSatForSequenceClassification",np]],["wavlm",["WavLMForSequenceClassification",sd]],["hubert",["HubertForSequenceClassification",ap]],["audio-spectrogram-transformer",["ASTForAudioClassification",Vo]]]),Hd=new Map([["wavlm",["WavLMForXVector",lp]]]),qd=new Map([["unispeech-sat",["UniSpeechSatForAudioFrameClassification",Qu]],["wavlm",["WavLMForAudioFrameClassification",rd]],["wav2vec2",["Wav2Vec2ForAudioFrameClassification",ju]],["pyannote",["PyAnnoteForAudioFrameClassification",Vu]]]),Qd=new Map([["vitmatte",["VitMatteForImageMatting",nu]]]),Hp=new Map([["patchtst",["PatchTSTForPrediction",Dd]],["patchtsmixer",["PatchTSMixerForPrediction",zd]]]),Xd=new Map([["swin2sr",["Swin2SRForImageSuperResolution",gu]]]),Yd=new Map([["dpt",["DPTForDepthEstimation",Qc]],["depth_anything",["DepthAnythingForDepthEstimation",Mu]],["glpn",["GLPNForDepthEstimation",Pu]],["sapiens",["SapiensForDepthEstimation",yo]],["depth_pro",["DepthProForDepthEstimation",Qi]]]),Jd=new Map([["sapiens",["SapiensForNormalEstimation",vu]]]),bp=new Map([["vitpose",["VitPoseForPoseEstimation",Ql]]]),Zd=new Map([["clip",["CLIPVisionModelWithProjection",Za]],["siglip",["SiglipVisionModel",sl]],["jina_clip",["JinaCLIPVisionModel",wr]]]),ec=[[_p,$.EncoderOnly],[fp,$.EncoderDecoder],[gp,$.DecoderOnly],[ya,$.EncoderOnly],[Ma,$.EncoderOnly],[Ao,$.Seq2Seq],[Bd,$.Seq2Seq],[ba,$.DecoderOnly],[wp,$.MultiModality],[va,$.EncoderOnly],[xa,$.EncoderOnly],[Ta,$.Vision2Seq],[yp,$.ImageTextToText],[Nd,$.EncoderOnly],[Ud,$.EncoderOnly],[Wd,$.EncoderOnly],[Vd,$.EncoderOnly],[Qd,$.EncoderOnly],[Hp,$.EncoderOnly],[Xd,$.EncoderOnly],[Yd,$.EncoderOnly],[Jd,$.EncoderOnly],[bp,$.EncoderOnly],[jd,$.EncoderOnly],[Pa,$.EncoderOnly],[Gd,$.MaskGeneration],[Mp,$.EncoderOnly],[Kd,$.EncoderOnly],[Kn,$.Seq2Seq],[wa,$.EncoderOnly],[Hd,$.EncoderOnly],[qd,$.EncoderOnly],[Zd,$.EncoderOnly]];for(const[_,T]of ec)for(const[N,fe]of _.values())S.set(N,T),x.set(fe,N),w.set(N,fe);const vp=[["MusicgenForConditionalGeneration",$o,$.Musicgen],["Phi3VForCausalLM",hr,$.Phi3V],["CLIPTextModelWithProjection",Ja,$.EncoderOnly],["SiglipTextModel",tl,$.EncoderOnly],["JinaCLIPTextModel",Qo,$.EncoderOnly],["ClapTextModelWithProjection",hd,$.EncoderOnly],["ClapAudioModelWithProjection",md,$.EncoderOnly]];for(const[_,T,N]of vp)S.set(_,N),x.set(T,_),w.set(_,T);class Ea extends ws{}_e(Ea,"MODEL_CLASS_MAPPINGS",ec.map(T=>T[0])),_e(Ea,"BASE_IF_FAIL",!0);class xp extends ws{}_e(xp,"MODEL_CLASS_MAPPINGS",[ya]);class tc extends ws{}_e(tc,"MODEL_CLASS_MAPPINGS",[Ma]);class sc extends ws{}_e(sc,"MODEL_CLASS_MAPPINGS",[Ao]);class rc extends ws{}_e(rc,"MODEL_CLASS_MAPPINGS",[Bd]);class nc extends ws{}_e(nc,"MODEL_CLASS_MAPPINGS",[Kn]);class oc extends ws{}_e(oc,"MODEL_CLASS_MAPPINGS",[wa]);class ic extends ws{}_e(ic,"MODEL_CLASS_MAPPINGS",[ba]);class ac extends ws{}_e(ac,"MODEL_CLASS_MAPPINGS",[va]);class lc extends ws{}_e(lc,"MODEL_CLASS_MAPPINGS",[xa]);class uc extends ws{}_e(uc,"MODEL_CLASS_MAPPINGS",[Ta]);class dc extends ws{}_e(dc,"MODEL_CLASS_MAPPINGS",[Nd]);class cc extends ws{}_e(cc,"MODEL_CLASS_MAPPINGS",[Ud]);class Ca extends ws{}_e(Ca,"MODEL_CLASS_MAPPINGS",[Vd]);class pc extends ws{}_e(pc,"MODEL_CLASS_MAPPINGS",[Wd]);class hc extends ws{}_e(hc,"MODEL_CLASS_MAPPINGS",[jd]);class mc extends ws{}_e(mc,"MODEL_CLASS_MAPPINGS",[Pa]);class _c extends ws{}_e(_c,"MODEL_CLASS_MAPPINGS",[Gd]);class fc extends ws{}_e(fc,"MODEL_CLASS_MAPPINGS",[Mp]);class gc extends ws{}_e(gc,"MODEL_CLASS_MAPPINGS",[Kd]);class wc extends ws{}_e(wc,"MODEL_CLASS_MAPPINGS",[Hd]);class Tp extends ws{}_e(Tp,"MODEL_CLASS_MAPPINGS",[qd]);class yc extends ws{}_e(yc,"MODEL_CLASS_MAPPINGS",[Rd]);class Mc extends ws{}_e(Mc,"MODEL_CLASS_MAPPINGS",[Qd]);class bc extends ws{}_e(bc,"MODEL_CLASS_MAPPINGS",[Xd]);class Pp extends ws{}_e(Pp,"MODEL_CLASS_MAPPINGS",[Yd]);class vc extends ws{}_e(vc,"MODEL_CLASS_MAPPINGS",[Jd]);class xc extends ws{}_e(xc,"MODEL_CLASS_MAPPINGS",[bp]);class Tc extends ws{}_e(Tc,"MODEL_CLASS_MAPPINGS",[Zd]);class qp extends Ke{constructor({logits:T,past_key_values:N,encoder_outputs:fe,decoder_attentions:Fe=null,cross_attentions:Ae=null}){super(),this.logits=T,this.past_key_values=N,this.encoder_outputs=fe,this.decoder_attentions=Fe,this.cross_attentions=Ae}}class Qt extends Ke{constructor({logits:T,...N}){super(),this.logits=T;const fe=Object.values(N);fe.length>0&&(this.attentions=fe)}}class Hn extends Ke{constructor({logits:T,embeddings:N}){super(),this.logits=T,this.embeddings=N}}class Hs extends Ke{constructor({logits:T}){super(),this.logits=T}}class qs extends Ke{constructor({logits:T}){super(),this.logits=T}}class tr extends Ke{constructor({start_logits:T,end_logits:N}){super(),this.start_logits=T,this.end_logits=N}}class cn extends Ke{constructor({logits:T}){super(),this.logits=T}}class Ep extends Ke{constructor({logits:T,past_key_values:N}){super(),this.logits=T,this.past_key_values=N}}class Pc extends Ke{constructor({alphas:T}){super(),this.alphas=T}}class Cp extends Ke{constructor({waveform:T,spectrogram:N}){super(),this.waveform=T,this.spectrogram=N}}},"./src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js":(De,A,r)=>{r.r(A),r.d(A,{ASTFeatureExtractor:()=>U});var f=r("./src/base/feature_extraction_utils.js");r("./src/utils/tensor.js");var D=r("./src/utils/audio.js");class U extends f.FeatureExtractor{constructor(R){super(R);const g=this.config.sampling_rate,v=(0,D.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(g/2),g,null,"kaldi",!0);for(let M=0;M{r.r(A),r.d(A,{AutoFeatureExtractor:()=>Y});var f=r("./src/utils/constants.js"),D=r("./src/utils/hub.js");r("./src/base/feature_extraction_utils.js");var U=r("./src/models/feature_extractors.js");class Y{static async from_pretrained(g,v={}){const M=await(0,D.getModelJSON)(g,f.FEATURE_EXTRACTOR_NAME,!0,v),y=M.feature_extractor_type,b=U[y];if(!b)throw new Error(`Unknown feature_extractor_type: '${y}'. Please report this at ${f.GITHUB_ISSUE_URL}.`);return new b(M)}}},"./src/models/auto/image_processing_auto.js":(De,A,r)=>{r.r(A),r.d(A,{AutoImageProcessor:()=>R});var f=r("./src/utils/constants.js"),D=r("./src/utils/hub.js"),U=r("./src/base/image_processors_utils.js"),Y=r("./src/models/image_processors.js");class R{static async from_pretrained(v,M={}){const y=await(0,D.getModelJSON)(v,f.IMAGE_PROCESSOR_NAME,!0,M),b=y.image_processor_type??y.feature_extractor_type;let I=Y[b];return I||(b!==void 0&&console.warn(`Image processor type '${b}' not found, assuming base ImageProcessor. Please report this at ${f.GITHUB_ISSUE_URL}.`),I=U.ImageProcessor),new I(y)}}},"./src/models/auto/processing_auto.js":(De,A,r)=>{r.r(A),r.d(A,{AutoProcessor:()=>v});var f=r("./src/utils/constants.js"),D=r("./src/utils/hub.js"),U=r("./src/base/processing_utils.js"),Y=r("./src/models/processors.js"),R=r("./src/models/image_processors.js"),g=r("./src/models/feature_extractors.js");class v{static async from_pretrained(y,b={}){const I=await(0,D.getModelJSON)(y,f.IMAGE_PROCESSOR_NAME,!0,b),{image_processor_type:K,feature_extractor_type:te,processor_class:ne}=I;if(ne&&Y[ne])return Y[ne].from_pretrained(y,b);if(!K&&!te)throw new Error("No `image_processor_type` or `feature_extractor_type` found in the config.");const W={};if(K){const q=R[K];if(!q)throw new Error(`Unknown image_processor_type: '${K}'.`);W.image_processor=new q(I)}if(te){const q=R[te];if(q)W.image_processor=new q(I);else{const $=g[te];if(!$)throw new Error(`Unknown feature_extractor_type: '${te}'.`);W.feature_extractor=new $(I)}}const j={};return new U.Processor(j,W)}}},"./src/models/beit/image_processing_beit.js":(De,A,r)=>{r.r(A),r.d(A,{BeitFeatureExtractor:()=>D});var f=r("./src/base/image_processors_utils.js");class D extends f.ImageProcessor{}},"./src/models/bit/image_processing_bit.js":(De,A,r)=>{r.r(A),r.d(A,{BitImageProcessor:()=>D});var f=r("./src/base/image_processors_utils.js");class D extends f.ImageProcessor{}},"./src/models/chinese_clip/image_processing_chinese_clip.js":(De,A,r)=>{r.r(A),r.d(A,{ChineseCLIPFeatureExtractor:()=>D});var f=r("./src/base/image_processors_utils.js");class D extends f.ImageProcessor{}},"./src/models/clap/feature_extraction_clap.js":(De,A,r)=>{r.r(A),r.d(A,{ClapFeatureExtractor:()=>U});var f=r("./src/base/feature_extraction_utils.js");r("./src/utils/tensor.js");var D=r("./src/utils/audio.js");class U extends f.FeatureExtractor{constructor(R){super(R),this.mel_filters=(0,D.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,D.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,D.window_function)(this.config.fft_window_size,"hann")}async _get_input_mel(R,g,v,M){let y;const b=R.length-g;if(b>0)if(v==="rand_trunc"){const I=Math.floor(Math.random()*(b+1));R=R.subarray(I,I+g),y=await this._extract_fbank_features(R,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${v}" not implemented`);else{if(b<0){let I=new Float64Array(g);if(I.set(R),M==="repeat")for(let K=R.length;K{r.r(A),r.d(A,{CLIPFeatureExtractor:()=>U,CLIPImageProcessor:()=>D});var f=r("./src/base/image_processors_utils.js");class D extends f.ImageProcessor{}class U extends D{}},"./src/models/convnext/image_processing_convnext.js":(De,A,r)=>{r.r(A),r.d(A,{ConvNextFeatureExtractor:()=>U,ConvNextImageProcessor:()=>D});var f=r("./src/base/image_processors_utils.js");class D extends f.ImageProcessor{constructor(R){super(R),this.crop_pct=this.config.crop_pct??.875}async resize(R){var v;const g=(v=this.size)==null?void 0:v.shortest_edge;if(g===void 0)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(g<384){const M=Math.floor(g/this.crop_pct),[y,b]=this.get_resize_output_image_size(R,{shortest_edge:M});R=await R.resize(y,b,{resample:this.resample}),R=await R.center_crop(g,g)}else R=await R.resize(g,g,{resample:this.resample});return R}}class U extends D{}},"./src/models/deit/image_processing_deit.js":(De,A,r)=>{r.r(A),r.d(A,{DeiTFeatureExtractor:()=>U,DeiTImageProcessor:()=>D});var f=r("./src/base/image_processors_utils.js");class D extends f.ImageProcessor{}class U extends D{}},"./src/models/detr/image_processing_detr.js":(De,A,r)=>{r.r(A),r.d(A,{DetrFeatureExtractor:()=>Y,DetrImageProcessor:()=>U});var f=r("./src/base/image_processors_utils.js"),D=r("./src/utils/tensor.js");class U extends f.ImageProcessor{async _call(g){const v=await super._call(g),M=[v.pixel_values.dims[0],64,64],y=(0,D.full)(M,1n);return{...v,pixel_mask:y}}post_process_object_detection(...g){return(0,f.post_process_object_detection)(...g)}post_process_panoptic_segmentation(...g){return(0,f.post_process_panoptic_segmentation)(...g)}post_process_instance_segmentation(...g){return(0,f.post_process_instance_segmentation)(...g)}}class Y extends U{}},"./src/models/donut/image_processing_donut.js":(De,A,r)=>{r.r(A),r.d(A,{DonutFeatureExtractor:()=>U,DonutImageProcessor:()=>D});var f=r("./src/base/image_processors_utils.js");class D extends f.ImageProcessor{pad_image(R,g,v,M={}){const[y,b,I]=g;let K=this.image_mean;Array.isArray(this.image_mean)||(K=new Array(I).fill(K));let te=this.image_std;Array.isArray(te)||(te=new Array(I).fill(K));const ne=K.map((W,j)=>-W/te[j]);return super.pad_image(R,g,v,{center:!0,constant_values:ne,...M})}}class U extends D{}},"./src/models/dpt/image_processing_dpt.js":(De,A,r)=>{r.r(A),r.d(A,{DPTFeatureExtractor:()=>U,DPTImageProcessor:()=>D});var f=r("./src/base/image_processors_utils.js");class D extends f.ImageProcessor{}class U extends D{}},"./src/models/efficientnet/image_processing_efficientnet.js":(De,A,r)=>{r.r(A),r.d(A,{EfficientNetImageProcessor:()=>D});var f=r("./src/base/image_processors_utils.js");class D extends f.ImageProcessor{constructor(Y){super(Y),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map(R=>R*R))}}},"./src/models/feature_extractors.js":(De,A,r)=>{r.r(A),r.d(A,{ASTFeatureExtractor:()=>f.ASTFeatureExtractor,ClapFeatureExtractor:()=>D.ClapFeatureExtractor,ImageFeatureExtractor:()=>b.ImageProcessor,MoonshineFeatureExtractor:()=>U.MoonshineFeatureExtractor,PyAnnoteFeatureExtractor:()=>Y.PyAnnoteFeatureExtractor,SeamlessM4TFeatureExtractor:()=>R.SeamlessM4TFeatureExtractor,SpeechT5FeatureExtractor:()=>g.SpeechT5FeatureExtractor,Wav2Vec2FeatureExtractor:()=>v.Wav2Vec2FeatureExtractor,WeSpeakerFeatureExtractor:()=>M.WeSpeakerFeatureExtractor,WhisperFeatureExtractor:()=>y.WhisperFeatureExtractor});var f=r("./src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js"),D=r("./src/models/clap/feature_extraction_clap.js"),U=r("./src/models/moonshine/feature_extraction_moonshine.js"),Y=r("./src/models/pyannote/feature_extraction_pyannote.js"),R=r("./src/models/seamless_m4t/feature_extraction_seamless_m4t.js"),g=r("./src/models/speecht5/feature_extraction_speecht5.js"),v=r("./src/models/wav2vec2/feature_extraction_wav2vec2.js"),M=r("./src/models/wespeaker/feature_extraction_wespeaker.js"),y=r("./src/models/whisper/feature_extraction_whisper.js"),b=r("./src/base/image_processors_utils.js")},"./src/models/florence2/processing_florence2.js":(De,A,r)=>{r.r(A),r.d(A,{Florence2Processor:()=>Y});var f=r("./src/base/processing_utils.js"),D=r("./src/models/auto/image_processing_auto.js"),U=r("./src/tokenizers.js");class Y extends f.Processor{constructor(g,v){super(g,v);const{tasks_answer_post_processing_type:M,task_prompts_without_inputs:y,task_prompts_with_input:b}=this.image_processor.config;this.tasks_answer_post_processing_type=new Map(Object.entries(M??{})),this.task_prompts_without_inputs=new Map(Object.entries(y??{})),this.task_prompts_with_input=new Map(Object.entries(b??{})),this.regexes={quad_boxes:/(.+?)/gm,bboxes:/([^<]+)?/gm},this.size_per_bin=1e3}construct_prompts(g){typeof g=="string"&&(g=[g]);const v=[];for(const M of g)if(this.task_prompts_without_inputs.has(M))v.push(this.task_prompts_without_inputs.get(M));else{for(const[y,b]of this.task_prompts_with_input)if(M.includes(y)){v.push(b.replaceAll("{input}",M).replaceAll(y,""));break}v.length!==g.length&&v.push(M)}return v}post_process_generation(g,v,M){const y=this.tasks_answer_post_processing_type.get(v)??"pure_text";g=g.replaceAll("","").replaceAll("","");let b;switch(y){case"pure_text":b=g;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":const I=y==="ocr"?"quad_boxes":"bboxes",K=g.matchAll(this.regexes[I]),te=[],ne=[];for(const[W,j,...q]of K)te.push(j?j.trim():te.at(-1)??""),ne.push(q.map(($,S)=>(Number($)+.5)/this.size_per_bin*M[S%2]));b={labels:te,[I]:ne};break;default:throw new Error(`Task "${v}" (of type "${y}") not yet implemented.`)}return{[v]:b}}async _call(g,v=null,M={}){if(!g&&!v)throw new Error("Either text or images must be provided");const y=await this.image_processor(g,M),b=v?this.tokenizer(v,M):{};return{...y,...b}}}_e(Y,"tokenizer_class",U.AutoTokenizer),_e(Y,"image_processor_class",D.AutoImageProcessor)},"./src/models/glpn/image_processing_glpn.js":(De,A,r)=>{r.r(A),r.d(A,{GLPNFeatureExtractor:()=>D});var f=r("./src/base/image_processors_utils.js");class D extends f.ImageProcessor{}},"./src/models/grounding_dino/image_processing_grounding_dino.js":(De,A,r)=>{r.r(A),r.d(A,{GroundingDinoImageProcessor:()=>U});var f=r("./src/base/image_processors_utils.js"),D=r("./src/utils/tensor.js");class U extends f.ImageProcessor{async _call(R){const g=await super._call(R),v=g.pixel_values.dims,M=(0,D.ones)([v[0],v[2],v[3]]);return{...g,pixel_mask:M}}}},"./src/models/grounding_dino/processing_grounding_dino.js":(De,A,r)=>{r.r(A),r.d(A,{GroundingDinoProcessor:()=>g});var f=r("./src/base/processing_utils.js"),D=r("./src/models/auto/image_processing_auto.js"),U=r("./src/tokenizers.js"),Y=r("./src/base/image_processors_utils.js");function R(v,M){const b=v.dims.at(-1)-1,I=v.tolist();I.fill(!1,0,1),I.fill(!1,b);const K=M.tolist();return I.map((te,ne)=>te?ne:null).filter(te=>te!==null).map(te=>K[te])}class g extends f.Processor{async _call(M,y,b={}){const I=M?await this.image_processor(M,b):{};return{...y?this.tokenizer(y,b):{},...I}}post_process_grounded_object_detection(M,y,{box_threshold:b=.25,text_threshold:I=.25,target_sizes:K=null}={}){const{logits:te,pred_boxes:ne}=M,W=te.dims[0];if(K!==null&&K.length!==W)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const j=te.dims.at(1),q=te.sigmoid(),$=q.max(-1).tolist(),S=ne.tolist().map(x=>x.map(O=>(0,Y.center_to_corners_format)(O))),w=[];for(let x=0;xre.map((xe,ce)=>xe*O[(ce+1)%2])));const ae=$[x],oe=[],ve=[],we=[];for(let re=0;re{r.r(A),r.d(A,{Idefics3ImageProcessor:()=>U});var f=r("./src/base/image_processors_utils.js"),D=r("./src/utils/tensor.js");class U extends f.ImageProcessor{constructor(R){super(R),this.do_image_splitting=R.do_image_splitting??!0,this.max_image_size=R.max_image_size}get_resize_for_vision_encoder(R,g){let[v,M]=R.dims.slice(-2);const y=M/v;return M>=v?(M=Math.ceil(M/g)*g,v=Math.floor(M/y),v=Math.ceil(v/g)*g):(v=Math.ceil(v/g)*g,M=Math.floor(v*y),M=Math.ceil(M/g)*g),{height:v,width:M}}async _call(R,{do_image_splitting:g=null,return_row_col_info:v=!1}={}){let M;if(!Array.isArray(R))M=[[R]];else{if(R.length===0||!R[0])throw new Error("No images provided.");Array.isArray(R[0])?M=R:M=[R]}let y=[],b=[],I=[];const K=[],te=[];for(const x of M){let O=await Promise.all(x.map(ve=>this.preprocess(ve)));K.push(...O.map(ve=>ve.original_size)),te.push(...O.map(ve=>ve.reshaped_input_size)),O.forEach(ve=>ve.pixel_values.unsqueeze_(0));const{longest_edge:ae}=this.max_image_size;let oe;if(g??this.do_image_splitting){let ve=new Array(O.length),we=new Array(O.length);oe=await Promise.all(O.map(async(re,xe)=>{const ce=this.get_resize_for_vision_encoder(re.pixel_values,ae),ke=await(0,D.interpolate_4d)(re.pixel_values,{size:[ce.height,ce.width]}),{frames:Ie,num_splits_h:Ee,num_splits_w:tt}=await this.split_image(ke,this.max_image_size);return ve[xe]=Ee,we[xe]=tt,(0,D.cat)(Ie,0)})),b.push(ve),I.push(we)}else{const ve=[ae,ae];oe=await Promise.all(O.map(we=>(0,D.interpolate_4d)(we.pixel_values,{size:ve}))),b.push(new Array(O.length).fill(0)),I.push(new Array(O.length).fill(0))}y.push((0,D.cat)(oe,0))}const ne=y.length,[W,j,q,$]=y[0].dims;let S,w;if(ne===1)S=y[0].unsqueeze_(0),w=(0,D.full)([ne,W,q,$],!0);else{const x=Math.max(...y.map(oe=>oe.dims.at(0)));w=(0,D.full)([ne,x,q,$],!0);const O=w.data,ae=x*q*$;for(let oe=0;oev||I>M){K=Math.ceil(b/v),te=Math.ceil(I/M);const ne=Math.ceil(b/K),W=Math.ceil(I/te);for(let $=0;${r.r(A),r.d(A,{Idefics3Processor:()=>M});var f=r("./src/base/processing_utils.js"),D=r("./src/models/auto/image_processing_auto.js"),U=r("./src/tokenizers.js");r("./src/utils/image.js");var Y=r("./src/utils/core.js");function R(y,b,I,K,te,ne){let W="";for(let j=0;j`+te.repeat(y);W+=` -`}return W+=` -${K}${ne}`+te.repeat(y)+`${K}`,W}function g(y,b,I,K){return`${b}${K}`+I.repeat(y)+`${b}`}function v(y,b,I,K,te,ne){return y===0&&b===0?g(I,K,te,ne):R(I,y,b,K,te,ne)}class M extends f.Processor{constructor(){super(...arguments);_e(this,"fake_image_token","");_e(this,"image_token","");_e(this,"global_img_token","")}async _call(I,K=null,te={}){te.return_row_col_info??(te.return_row_col_info=!0);let ne;K&&(ne=await this.image_processor(K,te)),Array.isArray(I)||(I=[I]);const W=ne.rows??[new Array(I.length).fill(0)],j=ne.cols??[new Array(I.length).fill(0)],q=this.config.image_seq_len,$=[],S=[];for(let x=0;xv(xe,oe[ce],q,this.fake_image_token,this.image_token,this.global_img_token)),we=O.split(this.image_token);if(we.length===0)throw new Error("The image token should be present in the text.");let re=we[0];for(let xe=0;xe{r.r(A),r.d(A,{BeitFeatureExtractor:()=>f.BeitFeatureExtractor,BitImageProcessor:()=>D.BitImageProcessor,CLIPFeatureExtractor:()=>Y.CLIPFeatureExtractor,CLIPImageProcessor:()=>Y.CLIPImageProcessor,ChineseCLIPFeatureExtractor:()=>U.ChineseCLIPFeatureExtractor,ConvNextFeatureExtractor:()=>R.ConvNextFeatureExtractor,ConvNextImageProcessor:()=>R.ConvNextImageProcessor,DPTFeatureExtractor:()=>y.DPTFeatureExtractor,DPTImageProcessor:()=>y.DPTImageProcessor,DeiTFeatureExtractor:()=>g.DeiTFeatureExtractor,DeiTImageProcessor:()=>g.DeiTImageProcessor,DetrFeatureExtractor:()=>v.DetrFeatureExtractor,DetrImageProcessor:()=>v.DetrImageProcessor,DonutFeatureExtractor:()=>M.DonutFeatureExtractor,DonutImageProcessor:()=>M.DonutImageProcessor,EfficientNetImageProcessor:()=>b.EfficientNetImageProcessor,GLPNFeatureExtractor:()=>I.GLPNFeatureExtractor,GroundingDinoImageProcessor:()=>K.GroundingDinoImageProcessor,Idefics3ImageProcessor:()=>te.Idefics3ImageProcessor,JinaCLIPImageProcessor:()=>W.JinaCLIPImageProcessor,LlavaOnevisionImageProcessor:()=>j.LlavaOnevisionImageProcessor,Mask2FormerImageProcessor:()=>q.Mask2FormerImageProcessor,MaskFormerFeatureExtractor:()=>$.MaskFormerFeatureExtractor,MaskFormerImageProcessor:()=>$.MaskFormerImageProcessor,MobileNetV1FeatureExtractor:()=>S.MobileNetV1FeatureExtractor,MobileNetV1ImageProcessor:()=>S.MobileNetV1ImageProcessor,MobileNetV2FeatureExtractor:()=>w.MobileNetV2FeatureExtractor,MobileNetV2ImageProcessor:()=>w.MobileNetV2ImageProcessor,MobileNetV3FeatureExtractor:()=>x.MobileNetV3FeatureExtractor,MobileNetV3ImageProcessor:()=>x.MobileNetV3ImageProcessor,MobileNetV4FeatureExtractor:()=>O.MobileNetV4FeatureExtractor,MobileNetV4ImageProcessor:()=>O.MobileNetV4ImageProcessor,MobileViTFeatureExtractor:()=>ae.MobileViTFeatureExtractor,MobileViTImageProcessor:()=>ae.MobileViTImageProcessor,NougatImageProcessor:()=>oe.NougatImageProcessor,OwlViTFeatureExtractor:()=>we.OwlViTFeatureExtractor,OwlViTImageProcessor:()=>we.OwlViTImageProcessor,Owlv2ImageProcessor:()=>ve.Owlv2ImageProcessor,Phi3VImageProcessor:()=>re.Phi3VImageProcessor,PvtImageProcessor:()=>xe.PvtImageProcessor,Qwen2VLImageProcessor:()=>ce.Qwen2VLImageProcessor,RTDetrImageProcessor:()=>ke.RTDetrImageProcessor,SamImageProcessor:()=>Ie.SamImageProcessor,SegformerFeatureExtractor:()=>Ee.SegformerFeatureExtractor,SegformerImageProcessor:()=>Ee.SegformerImageProcessor,SiglipImageProcessor:()=>tt.SiglipImageProcessor,Swin2SRImageProcessor:()=>Ge.Swin2SRImageProcessor,VLMImageProcessor:()=>ne.VLMImageProcessor,ViTFeatureExtractor:()=>ye.ViTFeatureExtractor,ViTImageProcessor:()=>ye.ViTImageProcessor,VitMatteImageProcessor:()=>J.VitMatteImageProcessor,VitPoseImageProcessor:()=>de.VitPoseImageProcessor,YolosFeatureExtractor:()=>Ce.YolosFeatureExtractor,YolosImageProcessor:()=>Ce.YolosImageProcessor});var f=r("./src/models/beit/image_processing_beit.js"),D=r("./src/models/bit/image_processing_bit.js"),U=r("./src/models/chinese_clip/image_processing_chinese_clip.js"),Y=r("./src/models/clip/image_processing_clip.js"),R=r("./src/models/convnext/image_processing_convnext.js"),g=r("./src/models/deit/image_processing_deit.js"),v=r("./src/models/detr/image_processing_detr.js"),M=r("./src/models/donut/image_processing_donut.js"),y=r("./src/models/dpt/image_processing_dpt.js"),b=r("./src/models/efficientnet/image_processing_efficientnet.js"),I=r("./src/models/glpn/image_processing_glpn.js"),K=r("./src/models/grounding_dino/image_processing_grounding_dino.js"),te=r("./src/models/idefics3/image_processing_idefics3.js"),ne=r("./src/models/janus/image_processing_janus.js"),W=r("./src/models/jina_clip/image_processing_jina_clip.js"),j=r("./src/models/llava_onevision/image_processing_llava_onevision.js"),q=r("./src/models/mask2former/image_processing_mask2former.js"),$=r("./src/models/maskformer/image_processing_maskformer.js"),S=r("./src/models/mobilenet_v1/image_processing_mobilenet_v1.js"),w=r("./src/models/mobilenet_v2/image_processing_mobilenet_v2.js"),x=r("./src/models/mobilenet_v3/image_processing_mobilenet_v3.js"),O=r("./src/models/mobilenet_v4/image_processing_mobilenet_v4.js"),ae=r("./src/models/mobilevit/image_processing_mobilevit.js"),oe=r("./src/models/nougat/image_processing_nougat.js"),ve=r("./src/models/owlv2/image_processing_owlv2.js"),we=r("./src/models/owlvit/image_processing_owlvit.js"),re=r("./src/models/phi3_v/image_processing_phi3_v.js"),xe=r("./src/models/pvt/image_processing_pvt.js"),ce=r("./src/models/qwen2_vl/image_processing_qwen2_vl.js"),ke=r("./src/models/rt_detr/image_processing_rt_detr.js"),Ie=r("./src/models/sam/image_processing_sam.js"),Ee=r("./src/models/segformer/image_processing_segformer.js"),tt=r("./src/models/siglip/image_processing_siglip.js"),Ge=r("./src/models/swin2sr/image_processing_swin2sr.js"),ye=r("./src/models/vit/image_processing_vit.js"),J=r("./src/models/vitmatte/image_processing_vitmatte.js"),de=r("./src/models/vitpose/image_processing_vitpose.js"),Ce=r("./src/models/yolos/image_processing_yolos.js")},"./src/models/janus/image_processing_janus.js":(De,A,r)=>{r.r(A),r.d(A,{VLMImageProcessor:()=>D});var f=r("./src/base/image_processors_utils.js");class D extends f.ImageProcessor{constructor(Y){super({do_pad:!0,pad_size:{width:Y.image_size,height:Y.image_size},...Y}),this.constant_values=this.config.background_color.map(R=>R*this.rescale_factor)}pad_image(Y,R,g,v){return super.pad_image(Y,R,g,{constant_values:this.constant_values,center:!0,...v})}}},"./src/models/janus/processing_janus.js":(De,A,r)=>{r.r(A),r.d(A,{VLChatProcessor:()=>v});var f=r("./src/base/processing_utils.js"),D=r("./src/models/auto/image_processing_auto.js"),U=r("./src/tokenizers.js"),Y=r("./src/utils/core.js"),R=r("./src/utils/tensor.js"),g=r("./src/utils/image.js");class v extends f.Processor{constructor(y,b){super(y,b),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(y,{images:b=null,chat_template:I="default"}={}){b?Array.isArray(b)||(b=[b]):b=await Promise.all(y.filter(oe=>oe.images).flatMap(oe=>oe.images).map(oe=>g.RawImage.read(oe)));const K=this.tokenizer,te=K.apply_chat_template(y,{tokenize:!1,add_generation_prompt:!0,chat_template:I}),ne=oe=>K.encode(oe,{add_special_tokens:!1}),W=te.split(this.image_tag),j=W.length-1;if(b.length!==j)throw new Error(`Number of images provided (${b.length}) does not match number of "${this.image_tag}" image tags (${j})`);const[q,$,S]=K.model.convert_tokens_to_ids([this.image_tag,this.image_start_tag,this.image_end_tag]);let w=ne(W[0]),x=new Array(w.length).fill(!1);for(let oe=1;oe0){const oe=await this.image_processor(b);return oe.pixel_values.unsqueeze_(0),{...ae,...oe}}return ae}}_e(v,"image_processor_class",D.AutoImageProcessor),_e(v,"tokenizer_class",U.AutoTokenizer),_e(v,"uses_processor_config",!0)},"./src/models/jina_clip/image_processing_jina_clip.js":(De,A,r)=>{r.r(A),r.d(A,{JinaCLIPImageProcessor:()=>D});var f=r("./src/base/image_processors_utils.js");class D extends f.ImageProcessor{constructor(Y){const{resize_mode:R,fill_color:g,interpolation:v,size:M,...y}=Y,b=R==="squash"?{width:M,height:M}:R==="shortest"?{shortest_edge:M}:{longest_edge:M},I=v==="bicubic"?3:2;super({...y,size:b,resample:I,do_center_crop:!0,crop_size:M,do_normalize:!0})}}},"./src/models/jina_clip/processing_jina_clip.js":(De,A,r)=>{r.r(A),r.d(A,{JinaCLIPProcessor:()=>Y});var f=r("./src/base/processing_utils.js"),D=r("./src/models/auto/image_processing_auto.js"),U=r("./src/tokenizers.js");class Y extends f.Processor{async _call(g=null,v=null,M={}){if(!g&&!v)throw new Error("Either text or images must be provided");const y=g?this.tokenizer(g,M):{},b=v?await this.image_processor(v,M):{};return{...y,...b}}}_e(Y,"tokenizer_class",U.AutoTokenizer),_e(Y,"image_processor_class",D.AutoImageProcessor)},"./src/models/llava_onevision/image_processing_llava_onevision.js":(De,A,r)=>{r.r(A),r.d(A,{LlavaOnevisionImageProcessor:()=>D});var f=r("./src/base/image_processors_utils.js");class D extends f.ImageProcessor{}},"./src/models/mask2former/image_processing_mask2former.js":(De,A,r)=>{r.r(A),r.d(A,{Mask2FormerImageProcessor:()=>D});var f=r("./src/models/maskformer/image_processing_maskformer.js");class D extends f.MaskFormerImageProcessor{}},"./src/models/maskformer/image_processing_maskformer.js":(De,A,r)=>{r.r(A),r.d(A,{MaskFormerFeatureExtractor:()=>U,MaskFormerImageProcessor:()=>D});var f=r("./src/base/image_processors_utils.js");class D extends f.ImageProcessor{post_process_panoptic_segmentation(...R){return(0,f.post_process_panoptic_segmentation)(...R)}post_process_instance_segmentation(...R){return(0,f.post_process_instance_segmentation)(...R)}}class U extends D{}},"./src/models/mgp_str/processing_mgp_str.js":(De,A,r)=>{r.r(A),r.d(A,{MgpstrProcessor:()=>g});var f=r("./src/base/processing_utils.js"),D=r("./src/models/auto/image_processing_auto.js"),U=r("./src/tokenizers.js"),Y=r("./src/utils/maths.js");const R={char:["char_decode",1],bpe:["bpe_decode",2],wp:["wp_decode",102]};class g extends f.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(M,y){if(!R.hasOwnProperty(y))throw new Error(`Format ${y} is not supported.`);const[b,I]=R[y],K=this[b].bind(this),[te,ne]=M.dims,W=[],j=[],q=M.tolist();for(let S=0;S0?O.reduce((oe,ve)=>oe*ve,1):0;j.push(x),W.push(ae)}return[K(j),W]}char_decode(M){return this.char_tokenizer.batch_decode(M).map(y=>y.replaceAll(" ",""))}bpe_decode(M){return this.bpe_tokenizer.batch_decode(M)}wp_decode(M){return this.wp_tokenizer.batch_decode(M).map(y=>y.replaceAll(" ",""))}batch_decode([M,y,b]){const[I,K]=this._decode_helper(M,"char"),[te,ne]=this._decode_helper(y,"bpe"),[W,j]=this._decode_helper(b,"wp"),q=[],$=[];for(let S=0;S{r.r(A),r.d(A,{MobileNetV1FeatureExtractor:()=>U,MobileNetV1ImageProcessor:()=>D});var f=r("./src/base/image_processors_utils.js");class D extends f.ImageProcessor{}class U extends D{}},"./src/models/mobilenet_v2/image_processing_mobilenet_v2.js":(De,A,r)=>{r.r(A),r.d(A,{MobileNetV2FeatureExtractor:()=>U,MobileNetV2ImageProcessor:()=>D});var f=r("./src/base/image_processors_utils.js");class D extends f.ImageProcessor{}class U extends D{}},"./src/models/mobilenet_v3/image_processing_mobilenet_v3.js":(De,A,r)=>{r.r(A),r.d(A,{MobileNetV3FeatureExtractor:()=>U,MobileNetV3ImageProcessor:()=>D});var f=r("./src/base/image_processors_utils.js");class D extends f.ImageProcessor{}class U extends D{}},"./src/models/mobilenet_v4/image_processing_mobilenet_v4.js":(De,A,r)=>{r.r(A),r.d(A,{MobileNetV4FeatureExtractor:()=>U,MobileNetV4ImageProcessor:()=>D});var f=r("./src/base/image_processors_utils.js");class D extends f.ImageProcessor{}class U extends D{}},"./src/models/mobilevit/image_processing_mobilevit.js":(De,A,r)=>{r.r(A),r.d(A,{MobileViTFeatureExtractor:()=>U,MobileViTImageProcessor:()=>D});var f=r("./src/base/image_processors_utils.js");class D extends f.ImageProcessor{}class U extends D{}},"./src/models/moonshine/feature_extraction_moonshine.js":(De,A,r)=>{r.r(A),r.d(A,{MoonshineFeatureExtractor:()=>U});var f=r("./src/base/feature_extraction_utils.js"),D=r("./src/utils/tensor.js");class U extends f.FeatureExtractor{async _call(R){(0,f.validate_audio_inputs)(R,"MoonshineFeatureExtractor"),R instanceof Float64Array&&(R=new Float32Array(R));const g=[1,R.length];return{input_values:new D.Tensor("float32",R,g)}}}},"./src/models/moonshine/processing_moonshine.js":(De,A,r)=>{r.r(A),r.d(A,{MoonshineProcessor:()=>Y});var f=r("./src/models/auto/feature_extraction_auto.js"),D=r("./src/tokenizers.js"),U=r("./src/base/processing_utils.js");class Y extends U.Processor{async _call(g){return await this.feature_extractor(g)}}_e(Y,"tokenizer_class",D.AutoTokenizer),_e(Y,"feature_extractor_class",f.AutoFeatureExtractor)},"./src/models/nougat/image_processing_nougat.js":(De,A,r)=>{r.r(A),r.d(A,{NougatImageProcessor:()=>D});var f=r("./src/models/donut/image_processing_donut.js");class D extends f.DonutImageProcessor{}},"./src/models/owlv2/image_processing_owlv2.js":(De,A,r)=>{r.r(A),r.d(A,{Owlv2ImageProcessor:()=>D});var f=r("./src/models/owlvit/image_processing_owlvit.js");class D extends f.OwlViTImageProcessor{}},"./src/models/owlvit/image_processing_owlvit.js":(De,A,r)=>{r.r(A),r.d(A,{OwlViTFeatureExtractor:()=>U,OwlViTImageProcessor:()=>D});var f=r("./src/base/image_processors_utils.js");class D extends f.ImageProcessor{post_process_object_detection(...R){return(0,f.post_process_object_detection)(...R)}}class U extends D{}},"./src/models/owlvit/processing_owlvit.js":(De,A,r)=>{r.r(A),r.d(A,{OwlViTProcessor:()=>Y});var f=r("./src/base/processing_utils.js"),D=r("./src/models/auto/image_processing_auto.js"),U=r("./src/tokenizers.js");class Y extends f.Processor{}_e(Y,"tokenizer_class",U.AutoTokenizer),_e(Y,"image_processor_class",D.AutoImageProcessor)},"./src/models/paligemma/processing_paligemma.js":(De,A,r)=>{r.r(A),r.d(A,{PaliGemmaProcessor:()=>g});var f=r("./src/base/processing_utils.js"),D=r("./src/models/auto/image_processing_auto.js"),U=r("./src/tokenizers.js");const Y="";function R(v,M,y,b,I){return`${b.repeat(y*I)}${M}${v} -`}class g extends f.Processor{async _call(M,y=null,b={}){y||(console.warn("You are using PaliGemma without a text prefix. It will perform as a picture-captioning model."),y=""),Array.isArray(M)||(M=[M]),Array.isArray(y)||(y=[y]);const I=this.tokenizer.bos_token,K=this.image_processor.config.image_seq_length;let te;y.some(j=>j.includes(Y))?te=y.map(j=>{const q=j.replaceAll(Y,Y.repeat(K)),$=q.lastIndexOf(Y),S=$===-1?0:$+Y.length;return q.slice(0,S)+I+q.slice(S)+` -`}):(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."),te=y.map(j=>R(j,I,K,Y,M.length)));const ne=this.tokenizer(te,b);return{...await this.image_processor(M,b),...ne}}}_e(g,"tokenizer_class",U.AutoTokenizer),_e(g,"image_processor_class",D.AutoImageProcessor),_e(g,"uses_processor_config",!1)},"./src/models/phi3_v/image_processing_phi3_v.js":(De,A,r)=>{r.r(A),r.d(A,{Phi3VImageProcessor:()=>M});var f=r("./src/base/image_processors_utils.js"),D=r("./src/utils/tensor.js");const U=336,Y=[2,3],{ceil:R,floor:g,sqrt:v}=Math;class M extends f.ImageProcessor{constructor(b){super({...b,do_normalize:!0,do_pad:!0,pad_size:"custom",do_convert_rgb:!0,do_resize:!0}),this._num_crops=b.num_crops}calc_num_image_tokens_from_image_size(b,I){const{num_img_tokens:K}=this.config;return g((g(I/U)*g(b/U)+1)*K+1+(g(I/U)+1)*v(K))}get_resize_output_image_size(b,I){const K=this._num_crops,[te,ne]=b.size;let W=te/ne,j=1;for(;j*Math.ceil(j/W)<=K;)j+=1;j-=1;const q=Math.floor(j*336),$=Math.floor(q/W);return[q,$]}pad_image(b,I,K,te={}){const[ne,W]=I,j=U*R(ne/U),q=U*R(W/U),$=[1,1,1].map((S,w)=>(S-this.image_mean[w])/this.image_std[w]);return super.pad_image(b,I,{width:q,height:j},{center:!0,constant_values:$,...te})}async _call(b,{num_crops:I=null}={}){if(this._num_crops=I??(I=this.config.num_crops),I<4||v(I)%1!==0)throw new Error("num_crops must be a square number >= 4");Array.isArray(b)||(b=[b]);const K=b.length,te=await Promise.all(b.map(x=>this.preprocess(x))),ne=te.map(x=>x.original_size),W=te.map(x=>x.reshaped_input_size),j=[];for(const{pixel_values:x}of te){x.unsqueeze_(0);const[O,ae]=x.dims.slice(-2),oe=await(0,D.interpolate_4d)(x,{size:[U,U],mode:"bicubic"});if(I>0){const ve=[],we=v(I),re=g(ae/we),xe=g(O/we);for(let ke=0;kex.map(O=>U*R(O/U))),S=new D.Tensor("int64",$.flat(),[K,2]),w=$.map(([x,O])=>this.calc_num_image_tokens_from_image_size(O,x));return{pixel_values:q,original_sizes:ne,reshaped_input_sizes:W,image_sizes:S,num_img_tokens:w}}}},"./src/models/phi3_v/processing_phi3_v.js":(De,A,r)=>{r.r(A),r.d(A,{Phi3VProcessor:()=>g});var f=r("./src/base/processing_utils.js"),D=r("./src/models/auto/image_processing_auto.js"),U=r("./src/tokenizers.js");r("./src/utils/image.js");const Y="<|image|>",R=/<\|image_\d+\|>/g;class g extends f.Processor{async _call(M,y=null,{padding:b=!0,truncation:I=!0,num_crops:K=null}={}){Array.isArray(M)||(M=[M]);let te,ne;if(y){ne=await this.image_processor(y,{num_crops:K});const{num_img_tokens:W}=ne,j=M.map(($,S)=>$.split(R).join(Y.repeat(W[S])));te=this.tokenizer(j,{padding:b,truncation:I});const q=this.tokenizer.model.convert_tokens_to_ids([Y])[0];te.input_ids.map_($=>$==q?-$:$)}else te=this.tokenizer(M);return{...te,...ne}}}_e(g,"image_processor_class",D.AutoImageProcessor),_e(g,"tokenizer_class",U.AutoTokenizer)},"./src/models/processors.js":(De,A,r)=>{r.r(A),r.d(A,{Florence2Processor:()=>f.Florence2Processor,GroundingDinoProcessor:()=>D.GroundingDinoProcessor,Idefics3Processor:()=>U.Idefics3Processor,JinaCLIPProcessor:()=>R.JinaCLIPProcessor,MgpstrProcessor:()=>g.MgpstrProcessor,MoonshineProcessor:()=>v.MoonshineProcessor,OwlViTProcessor:()=>M.OwlViTProcessor,PaliGemmaProcessor:()=>b.PaliGemmaProcessor,Phi3VProcessor:()=>y.Phi3VProcessor,PyAnnoteProcessor:()=>I.PyAnnoteProcessor,Qwen2VLProcessor:()=>K.Qwen2VLProcessor,SamProcessor:()=>te.SamProcessor,SpeechT5Processor:()=>ne.SpeechT5Processor,VLChatProcessor:()=>Y.VLChatProcessor,Wav2Vec2Processor:()=>W.Wav2Vec2Processor,Wav2Vec2ProcessorWithLM:()=>j.Wav2Vec2ProcessorWithLM,WhisperProcessor:()=>q.WhisperProcessor});var f=r("./src/models/florence2/processing_florence2.js"),D=r("./src/models/grounding_dino/processing_grounding_dino.js"),U=r("./src/models/idefics3/processing_idefics3.js"),Y=r("./src/models/janus/processing_janus.js"),R=r("./src/models/jina_clip/processing_jina_clip.js"),g=r("./src/models/mgp_str/processing_mgp_str.js"),v=r("./src/models/moonshine/processing_moonshine.js"),M=r("./src/models/owlvit/processing_owlvit.js"),y=r("./src/models/phi3_v/processing_phi3_v.js"),b=r("./src/models/paligemma/processing_paligemma.js"),I=r("./src/models/pyannote/processing_pyannote.js"),K=r("./src/models/qwen2_vl/processing_qwen2_vl.js"),te=r("./src/models/sam/processing_sam.js"),ne=r("./src/models/speecht5/processing_speecht5.js"),W=r("./src/models/wav2vec2/processing_wav2vec2.js"),j=r("./src/models/wav2vec2_with_lm/processing_wav2vec2_with_lm.js"),q=r("./src/models/whisper/processing_whisper.js")},"./src/models/pvt/image_processing_pvt.js":(De,A,r)=>{r.r(A),r.d(A,{PvtImageProcessor:()=>D});var f=r("./src/base/image_processors_utils.js");class D extends f.ImageProcessor{}},"./src/models/pyannote/feature_extraction_pyannote.js":(De,A,r)=>{r.r(A),r.d(A,{PyAnnoteFeatureExtractor:()=>Y});var f=r("./src/base/feature_extraction_utils.js"),D=r("./src/utils/tensor.js"),U=r("./src/utils/maths.js");class Y extends f.FeatureExtractor{async _call(g){(0,f.validate_audio_inputs)(g,"PyAnnoteFeatureExtractor"),g instanceof Float64Array&&(g=new Float32Array(g));const v=[1,1,g.length];return{input_values:new D.Tensor("float32",g,v)}}samples_to_frames(g){return(g-this.config.offset)/this.config.step}post_process_speaker_diarization(g,v){const M=v/this.samples_to_frames(v)/this.config.sampling_rate,y=[];for(const b of g.tolist()){const I=[];let K=-1;for(let te=0;te({id:te,start:ne*M,end:W*M,confidence:j/(W-ne)})))}return y}}},"./src/models/pyannote/processing_pyannote.js":(De,A,r)=>{r.r(A),r.d(A,{PyAnnoteProcessor:()=>U});var f=r("./src/base/processing_utils.js"),D=r("./src/models/pyannote/feature_extraction_pyannote.js");class U extends f.Processor{async _call(R){return await this.feature_extractor(R)}post_process_speaker_diarization(...R){return this.feature_extractor.post_process_speaker_diarization(...R)}get sampling_rate(){return this.feature_extractor.config.sampling_rate}}_e(U,"feature_extractor_class",D.PyAnnoteFeatureExtractor)},"./src/models/qwen2_vl/image_processing_qwen2_vl.js":(De,A,r)=>{r.r(A),r.d(A,{Qwen2VLImageProcessor:()=>U});var f=r("./src/base/image_processors_utils.js"),D=r("./src/utils/tensor.js");class U extends f.ImageProcessor{async _call(R,...g){const{pixel_values:v,original_sizes:M,reshaped_input_sizes:y}=await super._call(R,...g);let b=v;const{temporal_patch_size:I,merge_size:K,patch_size:te}=this.config;b.dims[0]===1&&(b=(0,D.cat)(Array.from({length:I},()=>b),0));const ne=b.dims[0]/I,W=b.dims[1],j=Math.floor(b.dims[2]/te),q=Math.floor(b.dims[3]/te),$=b.view(ne,I,W,Math.floor(j/K),K,te,Math.floor(q/K),K,te).permute(0,3,6,4,7,2,1,5,8).view(ne*j*q,W*I*te*te),S=new D.Tensor("int64",[ne,j,q],[1,3]);return{pixel_values:$,image_grid_thw:S,original_sizes:M,reshaped_input_sizes:y}}}},"./src/models/qwen2_vl/processing_qwen2_vl.js":(De,A,r)=>{r.r(A),r.d(A,{Qwen2VLProcessor:()=>Y});var f=r("./src/base/processing_utils.js"),D=r("./src/models/auto/image_processing_auto.js"),U=r("./src/tokenizers.js");r("./src/utils/image.js");class Y extends f.Processor{async _call(g,v=null,...M){Array.isArray(g)||(g=[g]);let y,b;if(v&&(y=await this.image_processor(v),b=y.image_grid_thw),b){let K=this.image_processor.config.merge_size**2,te=0;const ne=b.tolist();g=g.map(W=>{for(;W.includes("<|image_pad|>");){const j=Number(ne[te++].reduce((q,$)=>q*$,1n));W=W.replace("<|image_pad|>","<|placeholder|>".repeat(Math.floor(j/K)))}return W.replaceAll("<|placeholder|>","<|image_pad|>")})}return{...this.tokenizer(g),...y}}}_e(Y,"image_processor_class",D.AutoImageProcessor),_e(Y,"tokenizer_class",U.AutoTokenizer)},"./src/models/rt_detr/image_processing_rt_detr.js":(De,A,r)=>{r.r(A),r.d(A,{RTDetrImageProcessor:()=>D});var f=r("./src/base/image_processors_utils.js");class D extends f.ImageProcessor{post_process_object_detection(...Y){return(0,f.post_process_object_detection)(...Y)}}},"./src/models/sam/image_processing_sam.js":(De,A,r)=>{r.r(A),r.d(A,{SamImageProcessor:()=>Y});var f=r("./src/base/image_processors_utils.js"),D=r("./src/utils/core.js"),U=r("./src/utils/tensor.js");class Y extends f.ImageProcessor{reshape_input_points(g,v,M,y=!1){g=structuredClone(g);let b=(0,D.calculateDimensions)(g);if(b.length===3)y||(b=[1,...b]),g=[g];else if(b.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 I=0;Iy!==v.dims[b]))throw Error(`The first ${M.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new U.Tensor("int64",g.flat(1/0).map(BigInt),M)}async _call(g,{input_points:v=null,input_labels:M=null,input_boxes:y=null}={}){const b=await super._call(g);if(v&&(b.input_points=this.reshape_input_points(v,b.original_sizes,b.reshaped_input_sizes)),M){if(!b.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");b.input_labels=this.add_input_labels(M,b.input_points)}return y&&(b.input_boxes=this.reshape_input_points(y,b.original_sizes,b.reshaped_input_sizes,!0)),b}async post_process_masks(g,v,M,{mask_threshold:y=0,binarize:b=!0,pad_size:I=null}={}){const K=[];I=I??this.pad_size;const te=[I.height,I.width];for(let ne=0;ney&&(S[w]=1);q=new U.Tensor("bool",S,q.dims)}K.push(q)}return K}generate_crop_boxes(g,v,{crop_n_layers:M=0,overlap_ratio:y=.3413333333333333,points_per_crop:b=32,crop_n_points_downscale_factor:I=1}={}){}}},"./src/models/sam/processing_sam.js":(De,A,r)=>{r.r(A),r.d(A,{SamProcessor:()=>U});var f=r("./src/base/processing_utils.js"),D=r("./src/models/auto/image_processing_auto.js");class U extends f.Processor{async _call(...R){return await this.image_processor(...R)}post_process_masks(...R){return this.image_processor.post_process_masks(...R)}reshape_input_points(...R){return this.image_processor.reshape_input_points(...R)}}_e(U,"image_processor_class",D.AutoImageProcessor)},"./src/models/seamless_m4t/feature_extraction_seamless_m4t.js":(De,A,r)=>{r.r(A),r.d(A,{SeamlessM4TFeatureExtractor:()=>Y});var f=r("./src/base/feature_extraction_utils.js"),D=r("./src/utils/tensor.js"),U=r("./src/utils/audio.js");class Y extends f.FeatureExtractor{constructor(g){super(g);const v=this.config.sampling_rate,M=(0,U.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(v/2),v,null,"kaldi",!0);for(let y=0;yM*32768),(0,U.spectrogram)(g,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:v,transpose:!0})}async _call(g,{padding:v=!0,pad_to_multiple_of:M=2,do_normalize_per_mel_bins:y=!0,return_attention_mask:b=!0}={}){(0,f.validate_audio_inputs)(g,"SeamlessM4TFeatureExtractor");let I=await this._extract_fbank_features(g,this.config.max_length);if(y){const[S,w]=I.dims,x=I.data;for(let O=0;O0){const ae=new Float32Array(w*(S+O));ae.set(x),ae.fill(this.config.padding_value,x.length);const oe=S+O;I=new D.Tensor(I.type,ae,[oe,w]),b&&(K=new D.Tensor("int64",new BigInt64Array(oe),[1,oe]),K.data.fill(1n,0,S))}}const[te,ne]=I.dims,W=this.config.stride;if(te%W!==0)throw new Error(`The number of frames (${te}) must be a multiple of the stride (${W}).`);const q=I.view(1,Math.floor(te/W),ne*W),$={input_features:q};if(b){const S=q.dims[1],w=new BigInt64Array(S);if(K){const x=K.data;for(let O=1,ae=0;O{r.r(A),r.d(A,{SegformerFeatureExtractor:()=>U,SegformerImageProcessor:()=>D});var f=r("./src/base/image_processors_utils.js");class D extends f.ImageProcessor{post_process_semantic_segmentation(...R){return(0,f.post_process_semantic_segmentation)(...R)}}class U extends D{}},"./src/models/siglip/image_processing_siglip.js":(De,A,r)=>{r.r(A),r.d(A,{SiglipImageProcessor:()=>D});var f=r("./src/base/image_processors_utils.js");class D extends f.ImageProcessor{}},"./src/models/speecht5/feature_extraction_speecht5.js":(De,A,r)=>{r.r(A),r.d(A,{SpeechT5FeatureExtractor:()=>D});var f=r("./src/base/feature_extraction_utils.js");class D extends f.FeatureExtractor{}},"./src/models/speecht5/processing_speecht5.js":(De,A,r)=>{r.r(A),r.d(A,{SpeechT5Processor:()=>Y});var f=r("./src/base/processing_utils.js"),D=r("./src/tokenizers.js"),U=r("./src/models/auto/feature_extraction_auto.js");class Y extends f.Processor{async _call(g){return await this.feature_extractor(g)}}_e(Y,"tokenizer_class",D.AutoTokenizer),_e(Y,"feature_extractor_class",U.AutoFeatureExtractor)},"./src/models/swin2sr/image_processing_swin2sr.js":(De,A,r)=>{r.r(A),r.d(A,{Swin2SRImageProcessor:()=>D});var f=r("./src/base/image_processors_utils.js");class D extends f.ImageProcessor{pad_image(Y,R,g,v={}){const[M,y,b]=R;return super.pad_image(Y,R,{width:y+(g-y%g)%g,height:M+(g-M%g)%g},{mode:"symmetric",center:!1,constant_values:-1,...v})}}},"./src/models/vit/image_processing_vit.js":(De,A,r)=>{r.r(A),r.d(A,{ViTFeatureExtractor:()=>U,ViTImageProcessor:()=>D});var f=r("./src/base/image_processors_utils.js");class D extends f.ImageProcessor{}class U extends D{}},"./src/models/vitmatte/image_processing_vitmatte.js":(De,A,r)=>{r.r(A),r.d(A,{VitMatteImageProcessor:()=>U});var f=r("./src/base/image_processors_utils.js"),D=r("./src/utils/tensor.js");class U extends f.ImageProcessor{async _call(R,g){Array.isArray(R)||(R=[R]),Array.isArray(g)||(g=[g]);const v=await Promise.all(R.map(b=>this.preprocess(b))),M=await Promise.all(g.map(b=>this.preprocess(b,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:(0,D.stack)(v.map((b,I)=>(0,D.cat)([b.pixel_values,M[I].pixel_values],0)),0),original_sizes:v.map(b=>b.original_size),reshaped_input_sizes:v.map(b=>b.reshaped_input_size)}}}},"./src/models/vitpose/image_processing_vitpose.js":(De,A,r)=>{r.r(A),r.d(A,{VitPoseImageProcessor:()=>D});var f=r("./src/base/image_processors_utils.js");class D extends f.ImageProcessor{post_process_pose_estimation(Y,R,{threshold:g=null}={}){const v=Y.tolist(),[M,y,b,I]=Y.dims,K=[];for(let te=0;te{r.r(A),r.d(A,{Wav2Vec2FeatureExtractor:()=>U});var f=r("./src/base/feature_extraction_utils.js"),D=r("./src/utils/tensor.js");class U extends f.FeatureExtractor{_zero_mean_unit_var_norm(R){const v=R.reduce((y,b)=>y+b,0)/R.length,M=R.reduce((y,b)=>y+(b-v)**2,0)/R.length;return R.map(y=>(y-v)/Math.sqrt(M+1e-7))}async _call(R){(0,f.validate_audio_inputs)(R,"Wav2Vec2FeatureExtractor"),R instanceof Float64Array&&(R=new Float32Array(R));let g=R;this.config.do_normalize&&(g=this._zero_mean_unit_var_norm(g));const v=[1,g.length];return{input_values:new D.Tensor("float32",g,v),attention_mask:new D.Tensor("int64",new BigInt64Array(g.length).fill(1n),v)}}}},"./src/models/wav2vec2/processing_wav2vec2.js":(De,A,r)=>{r.r(A),r.d(A,{Wav2Vec2Processor:()=>Y});var f=r("./src/tokenizers.js"),D=r("./src/models/auto/feature_extraction_auto.js"),U=r("./src/base/processing_utils.js");class Y extends U.Processor{async _call(g){return await this.feature_extractor(g)}}_e(Y,"tokenizer_class",f.AutoTokenizer),_e(Y,"feature_extractor_class",D.AutoFeatureExtractor)},"./src/models/wav2vec2_with_lm/processing_wav2vec2_with_lm.js":(De,A,r)=>{r.r(A),r.d(A,{Wav2Vec2ProcessorWithLM:()=>Y});var f=r("./src/tokenizers.js"),D=r("./src/models/auto/feature_extraction_auto.js"),U=r("./src/base/processing_utils.js");class Y extends U.Processor{async _call(g){return await this.feature_extractor(g)}}_e(Y,"tokenizer_class",f.AutoTokenizer),_e(Y,"feature_extractor_class",D.AutoFeatureExtractor)},"./src/models/wespeaker/feature_extraction_wespeaker.js":(De,A,r)=>{r.r(A),r.d(A,{WeSpeakerFeatureExtractor:()=>U});var f=r("./src/base/feature_extraction_utils.js");r("./src/utils/tensor.js");var D=r("./src/utils/audio.js");class U extends f.FeatureExtractor{constructor(R){super(R);const g=this.config.sampling_rate,v=(0,D.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(g/2),g,null,"kaldi",!0);for(let M=0;Mg*32768),(0,D.spectrogram)(R,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(R){(0,f.validate_audio_inputs)(R,"WeSpeakerFeatureExtractor");const g=(await this._extract_fbank_features(R)).unsqueeze_(0);if(this.config.fbank_centering_span===null){const v=g.mean(1).data,M=g.data,[y,b,I]=g.dims;for(let K=0;K{r.r(A),r.d(A,{WHISPER_LANGUAGE_MAPPING:()=>D,WHISPER_TO_LANGUAGE_CODE_MAPPING:()=>U,whisper_language_to_code:()=>Y});const f=[["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"]],D=new Map(f),U=new Map([...f.map(([R,g])=>[g,R]),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);function Y(R){R=R.toLowerCase();let g=U.get(R);if(g===void 0)if(D.has(R))g=R;else{const M=R.length===2?D.keys():D.values();throw new Error(`Language "${R}" is not supported. Must be one of: ${JSON.stringify(M)}`)}return g}},"./src/models/whisper/feature_extraction_whisper.js":(De,A,r)=>{r.r(A),r.d(A,{WhisperFeatureExtractor:()=>Y});var f=r("./src/base/feature_extraction_utils.js");r("./src/utils/tensor.js");var D=r("./src/utils/audio.js"),U=r("./src/utils/maths.js");class Y extends f.FeatureExtractor{constructor(g){var v;super(g),(v=this.config).mel_filters??(v.mel_filters=(0,D.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,D.window_function)(this.config.n_fft,"hann")}async _extract_fbank_features(g){const v=await(0,D.spectrogram)(g,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}),M=v.data,y=(0,U.max)(M)[0];for(let b=0;bthis.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`."),v=g.slice(0,this.config.n_samples)):(v=new Float32Array(this.config.n_samples),v.set(g)),{input_features:(await this._extract_fbank_features(v)).unsqueeze_(0)}}}},"./src/models/whisper/generation_whisper.js":(De,A,r)=>{r.r(A),r.d(A,{WhisperGenerationConfig:()=>D});var f=r("./src/generation/configuration_utils.js");class D extends f.GenerationConfig{constructor(){super(...arguments);_e(this,"return_timestamps",null);_e(this,"return_token_timestamps",null);_e(this,"num_frames",null);_e(this,"alignment_heads",null);_e(this,"task",null);_e(this,"language",null);_e(this,"no_timestamps_token_id",null);_e(this,"prompt_ids",null);_e(this,"is_multilingual",null);_e(this,"lang_to_id",null);_e(this,"task_to_id",null);_e(this,"max_initial_timestamp_index",1)}}},"./src/models/whisper/processing_whisper.js":(De,A,r)=>{r.r(A),r.d(A,{WhisperProcessor:()=>Y});var f=r("./src/models/auto/feature_extraction_auto.js"),D=r("./src/tokenizers.js"),U=r("./src/base/processing_utils.js");class Y extends U.Processor{async _call(g){return await this.feature_extractor(g)}}_e(Y,"tokenizer_class",D.AutoTokenizer),_e(Y,"feature_extractor_class",f.AutoFeatureExtractor)},"./src/models/yolos/image_processing_yolos.js":(De,A,r)=>{r.r(A),r.d(A,{YolosFeatureExtractor:()=>U,YolosImageProcessor:()=>D});var f=r("./src/base/image_processors_utils.js");class D extends f.ImageProcessor{post_process_object_detection(...R){return(0,f.post_process_object_detection)(...R)}}class U extends D{}},"./src/ops/registry.js":(De,A,r)=>{r.r(A),r.d(A,{TensorOpRegistry:()=>g});var f=r("./src/backends/onnx.js"),D=r("./src/utils/tensor.js"),U=r("./src/env.js");const Y=U.apis.IS_BROWSER_ENV||U.apis.IS_WEBWORKER_ENV,R=async(v,M,y)=>{const b=await(0,f.createInferenceSession)(new Uint8Array(v),M);let I=Promise.resolve();return async K=>{const te=(0,f.isONNXProxy)(),ne=Object.fromEntries(Object.entries(K).map(([j,q])=>[j,(te?q.clone():q).ort_tensor])),W=await(I=Y?I.then(()=>b.run(ne)):b.run(ne));return Array.isArray(y)?y.map(j=>new D.Tensor(W[j])):new D.Tensor(W[y])}};class g{static get nearest_interpolate_4d(){return this._nearest_interpolate_4d||(this._nearest_interpolate_4d=R([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=R([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=R([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=R([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=R([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=R([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=R([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=R([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}}_e(g,"session_options",{})},"./src/pipelines.js":(De,A,r)=>{r.r(A),r.d(A,{AudioClassificationPipeline:()=>we,AutomaticSpeechRecognitionPipeline:()=>xe,DepthEstimationPipeline:()=>Ce,DocumentQuestionAnsweringPipeline:()=>ye,FeatureExtractionPipeline:()=>oe,FillMaskPipeline:()=>q,ImageClassificationPipeline:()=>ke,ImageFeatureExtractionPipeline:()=>ve,ImageSegmentationPipeline:()=>Ie,ImageToImagePipeline:()=>de,ImageToTextPipeline:()=>ce,ObjectDetectionPipeline:()=>tt,Pipeline:()=>te,QuestionAnsweringPipeline:()=>j,SummarizationPipeline:()=>S,Text2TextGenerationPipeline:()=>$,TextClassificationPipeline:()=>ne,TextGenerationPipeline:()=>O,TextToAudioPipeline:()=>J,TokenClassificationPipeline:()=>W,TranslationPipeline:()=>w,ZeroShotAudioClassificationPipeline:()=>re,ZeroShotClassificationPipeline:()=>ae,ZeroShotImageClassificationPipeline:()=>Ee,ZeroShotObjectDetectionPipeline:()=>Ge,pipeline:()=>se});var f=r("./src/tokenizers.js"),D=r("./src/models.js"),U=r("./src/models/auto/processing_auto.js");r("./src/base/processing_utils.js");var Y=r("./src/utils/generic.js"),R=r("./src/utils/core.js"),g=r("./src/utils/maths.js"),v=r("./src/utils/audio.js"),M=r("./src/utils/tensor.js"),y=r("./src/utils/image.js");async function b(je){return Array.isArray(je)||(je=[je]),await Promise.all(je.map(le=>y.RawImage.read(le)))}async function I(je,le){return Array.isArray(je)||(je=[je]),await Promise.all(je.map(Te=>typeof Te=="string"||Te instanceof URL?(0,v.read_audio)(Te,le):Te instanceof Float64Array?new Float32Array(Te):Te))}function K(je,le){le&&(je=je.map(Re=>Re|0));const[Te,Ue,Ve,Ne]=je;return{xmin:Te,ymin:Ue,xmax:Ve,ymax:Ne}}class te extends Y.Callable{constructor({task:le,model:Te,tokenizer:Ue=null,processor:Ve=null}){super(),this.task=le,this.model=Te,this.tokenizer=Ue,this.processor=Ve}async dispose(){await this.model.dispose()}}class ne extends te{constructor(le){super(le)}async _call(le,{top_k:Te=1}={}){const Ue=this.tokenizer(le,{padding:!0,truncation:!0}),Ve=await this.model(Ue),Ne=this.model.config.problem_type==="multi_label_classification"?dt=>dt.sigmoid():dt=>new M.Tensor("float32",(0,g.softmax)(dt.data),dt.dims),Re=this.model.config.id2label,st=[];for(const dt of Ve.logits){const ct=Ne(dt),lt=await(0,M.topk)(ct,Te),ht=lt[0].tolist(),ie=lt[1].tolist().map((H,me)=>({label:Re?Re[H]:`LABEL_${H}`,score:ht[me]}));Te===1?st.push(...ie):st.push(ie)}return Array.isArray(le)||Te===1?st:st[0]}}class W extends te{constructor(le){super(le)}async _call(le,{ignore_labels:Te=["O"]}={}){const Ue=Array.isArray(le),Ve=this.tokenizer(Ue?le:[le],{padding:!0,truncation:!0}),Re=(await this.model(Ve)).logits,st=this.model.config.id2label,dt=[];for(let ct=0;ctut==this.tokenizer.sep_token_id);dt[ht].map((ut,mt)=>ut==1&&(mt===0||mt>ie&&ct.findIndex(vt=>vt==L[mt])===-1));const H=Ne[ht].tolist(),me=Re[ht].tolist();for(let ut=1;utmt==L[ut])!==-1)&&(H[ut]=-1/0,me[ut]=-1/0);const $e=(0,g.softmax)(H).map((ut,mt)=>[ut,mt]),We=(0,g.softmax)(me).map((ut,mt)=>[ut,mt]);$e[0][0]=0,We[0][0]=0;const Je=(0,R.product)($e,We).filter(ut=>ut[0][1]<=ut[1][1]).map(ut=>[ut[0][1],ut[1][1],ut[0][0]*ut[1][0]]).sort((ut,mt)=>mt[2]-ut[2]);for(let ut=0;utH==this.tokenizer.mask_token_id);if(ct===-1)throw Error(`Mask token (${this.tokenizer.mask_token}) not found in text.`);const lt=Ve[st][ct],ht=await(0,M.topk)(new M.Tensor("float32",(0,g.softmax)(lt.data),lt.dims),Te),L=ht[0].tolist(),ie=ht[1].tolist();Ne.push(ie.map((H,me)=>{const $e=dt.slice();return $e[ct]=H,{score:L[me],token:Number(H),token_str:this.tokenizer.decode([H]),sequence:this.tokenizer.decode($e,{skip_special_tokens:!0})}}))}return Array.isArray(le)?Ne:Ne[0]}}class $ extends te{constructor(Te){super(Te);_e(this,"_key","generated_text")}async _call(Te,Ue={}){Array.isArray(Te)||(Te=[Te]),this.model.config.prefix&&(Te=Te.map(ct=>this.model.config.prefix+ct));const Ve=this.model.config.task_specific_params;Ve&&Ve[this.task]&&Ve[this.task].prefix&&(Te=Te.map(ct=>Ve[this.task].prefix+ct));const Ne=this.tokenizer,Re={padding:!0,truncation:!0};let st;this instanceof w&&"_build_translation_inputs"in Ne?st=Ne._build_translation_inputs(Te,Re,Ue):st=Ne(Te,Re);const dt=await this.model.generate({...st,...Ue});return Ne.batch_decode(dt,{skip_special_tokens:!0}).map(ct=>({[this._key]:ct}))}}class S extends ${constructor(Te){super(Te);_e(this,"_key","summary_text")}}class w extends ${constructor(Te){super(Te);_e(this,"_key","translation_text")}}function x(je){return Array.isArray(je)&&je.every(le=>"role"in le&&"content"in le)}class O extends te{constructor(le){super(le)}async _call(le,Te={}){let Ue=!1,Ve=!1,Ne;if(typeof le=="string")Ne=le=[le];else if(Array.isArray(le)&&le.every(ie=>typeof ie=="string"))Ue=!0,Ne=le;else{if(x(le))le=[le];else if(Array.isArray(le)&&le.every(x))Ue=!0;else throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats");Ve=!0,Ne=le.map(ie=>this.tokenizer.apply_chat_template(ie,{tokenize:!1,add_generation_prompt:!0}))}const Re=Te.add_special_tokens??!1,st=Ve?!1:Te.return_full_text??!0;this.tokenizer.padding_side="left";const dt=this.tokenizer(Ne,{add_special_tokens:Re,padding:!0,truncation:!0}),ct=await this.model.generate({...dt,...Te}),lt=this.tokenizer.batch_decode(ct,{skip_special_tokens:!0});let ht;!st&&dt.input_ids.dims.at(-1)>0&&(ht=this.tokenizer.batch_decode(dt.input_ids,{skip_special_tokens:!0}).map(ie=>ie.length));const L=Array.from({length:le.length},ie=>[]);for(let ie=0;ie[Te.toLowerCase(),Ue])),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(le,Te,{hypothesis_template:Ue="This example is {}.",multi_label:Ve=!1}={}){const Ne=Array.isArray(le);Ne||(le=[le]),Array.isArray(Te)||(Te=[Te]);const Re=Te.map(ct=>Ue.replace("{}",ct)),st=Ve||Te.length===1,dt=[];for(const ct of le){const lt=[];for(const ie of Re){const H=this.tokenizer(ct,{text_pair:ie,padding:!0,truncation:!0}),me=await this.model(H);st?lt.push([me.logits.data[this.contradiction_id],me.logits.data[this.entailment_id]]):lt.push(me.logits.data[this.entailment_id])}const L=(st?lt.map(ie=>(0,g.softmax)(ie)[1]):(0,g.softmax)(lt)).map((ie,H)=>[ie,H]).sort((ie,H)=>H[0]-ie[0]);dt.push({sequence:ct,labels:L.map(ie=>Te[ie[1]]),scores:L.map(ie=>ie[0])})}return Ne?dt:dt[0]}}class oe extends te{constructor(le){super(le)}async _call(le,{pooling:Te="none",normalize:Ue=!1,quantize:Ve=!1,precision:Ne="binary"}={}){const Re=this.tokenizer(le,{padding:!0,truncation:!0}),st=await this.model(Re);let dt=st.last_hidden_state??st.logits??st.token_embeddings;if(Te!=="none")if(Te==="mean")dt=(0,M.mean_pooling)(dt,Re.attention_mask);else if(Te==="cls")dt=dt.slice(null,0);else throw Error(`Pooling method '${Te}' not supported.`);return Ue&&(dt=dt.normalize(2,-1)),Ve&&(dt=(0,M.quantize_embeddings)(dt,Ne)),dt}}class ve extends te{constructor(le){super(le)}async _call(le,{pool:Te=null}={}){const Ue=await b(le),{pixel_values:Ve}=await this.processor(Ue),Ne=await this.model({pixel_values:Ve});let Re;if(Te){if(!("pooler_output"in Ne))throw Error("No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.");Re=Ne.pooler_output}else Re=Ne.last_hidden_state??Ne.logits??Ne.image_embeds;return Re}}class we extends te{constructor(le){super(le)}async _call(le,{top_k:Te=5}={}){const Ue=this.processor.feature_extractor.config.sampling_rate,Ve=await I(le,Ue),Ne=this.model.config.id2label,Re=[];for(const st of Ve){const dt=await this.processor(st),lt=(await this.model(dt)).logits[0],ht=await(0,M.topk)(new M.Tensor("float32",(0,g.softmax)(lt.data),lt.dims),Te),L=ht[0].tolist(),H=ht[1].tolist().map((me,$e)=>({label:Ne?Ne[me]:`LABEL_${me}`,score:L[$e]}));Re.push(H)}return Array.isArray(le)?Re:Re[0]}}class re extends te{constructor(le){super(le)}async _call(le,Te,{hypothesis_template:Ue="This is a sound of {}."}={}){const Ve=!Array.isArray(le);Ve&&(le=[le]);const Ne=Te.map(lt=>Ue.replace("{}",lt)),Re=this.tokenizer(Ne,{padding:!0,truncation:!0}),st=this.processor.feature_extractor.config.sampling_rate,dt=await I(le,st),ct=[];for(const lt of dt){const ht=await this.processor(lt),L=await this.model({...Re,...ht}),ie=(0,g.softmax)(L.logits_per_audio.data);ct.push([...ie].map((H,me)=>({score:H,label:Te[me]})))}return Ve?ct[0]:ct}}class xe extends te{constructor(le){super(le)}async _call(le,Te={}){switch(this.model.config.model_type){case"whisper":return this._call_whisper(le,Te);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":return this._call_wav2vec2(le,Te);case"moonshine":return this._call_moonshine(le,Te);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(le,Te){Te.language&&console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),Te.task&&console.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');const Ue=!Array.isArray(le);Ue&&(le=[le]);const Ve=this.processor.feature_extractor.config.sampling_rate,Ne=await I(le,Ve),Re=[];for(const st of Ne){const dt=await this.processor(st),lt=(await this.model(dt)).logits[0],ht=[];for(const ie of lt)ht.push((0,g.max)(ie.data)[1]);const L=this.tokenizer.decode(ht);Re.push({text:L})}return Ue?Re[0]:Re}async _call_whisper(le,Te){const Ue=Te.return_timestamps??!1,Ve=Te.chunk_length_s??0,Ne=Te.force_full_sequences??!1;let Re=Te.stride_length_s??null;const st={...Te};Ue==="word"&&(st.return_token_timestamps=!0,st.return_timestamps=!1);const dt=!Array.isArray(le);dt&&(le=[le]);const ct=this.processor.feature_extractor.config.chunk_length/this.model.config.max_source_positions,lt=this.processor.feature_extractor.config.hop_length,ht=this.processor.feature_extractor.config.sampling_rate,L=await I(le,ht),ie=[];for(const H of L){let me=[];if(Ve>0){if(Re===null)Re=Ve/6;else if(Ve<=Re)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");const Je=ht*Ve,ut=ht*Re,mt=Je-2*ut;let vt=0;for(;;){const kt=vt+Je,At=H.subarray(vt,kt),os=await this.processor(At),ys=vt===0,Cs=kt>=H.length;if(me.push({stride:[At.length,ys?0:ut,Cs?0:ut],input_features:os.input_features,is_last:Cs}),Cs)break;vt+=mt}}else me=[{stride:[H.length,0,0],input_features:(await this.processor(H)).input_features,is_last:!0}];for(const Je of me){st.num_frames=Math.floor(Je.stride[0]/lt);const ut=await this.model.generate({inputs:Je.input_features,...st});Ue==="word"?(Je.tokens=ut.sequences.tolist()[0],Je.token_timestamps=ut.token_timestamps.tolist()[0].map(mt=>(0,g.round)(mt,2))):Je.tokens=ut[0].tolist(),Je.stride=Je.stride.map(mt=>mt/ht)}const[$e,We]=this.tokenizer._decode_asr(me,{time_precision:ct,return_timestamps:Ue,force_full_sequences:Ne});ie.push({text:$e,...We})}return dt?ie[0]:ie}async _call_moonshine(le,Te){const Ue=!Array.isArray(le);Ue&&(le=[le]);const Ve=this.processor.feature_extractor.config.sampling_rate,Ne=await I(le,Ve),Re=[];for(const st of Ne){const dt=await this.processor(st),ct=Math.floor(st.length/Ve)*6,lt=await this.model.generate({max_new_tokens:ct,...Te,...dt}),ht=this.processor.batch_decode(lt,{skip_special_tokens:!0})[0];Re.push({text:ht})}return Ue?Re[0]:Re}}class ce extends te{constructor(le){super(le)}async _call(le,Te={}){const Ue=Array.isArray(le),Ve=await b(le),{pixel_values:Ne}=await this.processor(Ve),Re=[];for(const st of Ne){st.dims=[1,...st.dims];const dt=await this.model.generate({inputs:st,...Te}),ct=this.tokenizer.batch_decode(dt,{skip_special_tokens:!0}).map(lt=>({generated_text:lt.trim()}));Re.push(ct)}return Ue?Re:Re[0]}}class ke extends te{constructor(le){super(le)}async _call(le,{top_k:Te=5}={}){const Ue=await b(le),{pixel_values:Ve}=await this.processor(Ue),Ne=await this.model({pixel_values:Ve}),Re=this.model.config.id2label,st=[];for(const dt of Ne.logits){const ct=await(0,M.topk)(new M.Tensor("float32",(0,g.softmax)(dt.data),dt.dims),Te),lt=ct[0].tolist(),L=ct[1].tolist().map((ie,H)=>({label:Re?Re[ie]:`LABEL_${ie}`,score:lt[H]}));st.push(L)}return Array.isArray(le)?st:st[0]}}class Ie extends te{constructor(le){super(le),this.subtasks_mapping={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"}}async _call(le,{threshold:Te=.5,mask_threshold:Ue=.5,overlap_mask_area_threshold:Ve=.8,label_ids_to_fuse:Ne=null,target_sizes:Re=null,subtask:st=null}={}){if(Array.isArray(le)&&le.length!==1)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");const ct=await b(le),lt=ct.map(We=>[We.height,We.width]),{pixel_values:ht,pixel_mask:L}=await this.processor(ct),ie=await this.model({pixel_values:ht,pixel_mask:L});let H=null;if(st!==null)H=this.subtasks_mapping[st];else for(let[We,Je]of Object.entries(this.subtasks_mapping))if(Je in this.processor.image_processor){H=this.processor.image_processor[Je].bind(this.processor.image_processor),st=We;break}const me=this.model.config.id2label,$e=[];if(st==="panoptic"||st==="instance"){const We=H(ie,Te,Ue,Ve,Ne,Re??lt)[0],Je=We.segmentation;for(const ut of We.segments_info){const mt=new Uint8ClampedArray(Je.data.length);for(let kt=0;ktUe.replace("{}",L)),st=this.tokenizer(Re,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:dt}=await this.processor(Ne),ct=await this.model({...st,pixel_values:dt}),lt=this.model.config.model_type==="siglip"?L=>L.sigmoid().data:L=>(0,g.softmax)(L.data),ht=[];for(const L of ct.logits_per_image){const H=[...lt(L)].map((me,$e)=>({score:me,label:Te[$e]}));H.sort((me,$e)=>$e.score-me.score),ht.push(H)}return Ve?ht:ht[0]}}class tt extends te{constructor(le){super(le)}async _call(le,{threshold:Te=.9,percentage:Ue=!1}={}){const Ve=Array.isArray(le);if(Ve&&le.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");const Ne=await b(le),Re=Ue?null:Ne.map(ie=>[ie.height,ie.width]),{pixel_values:st,pixel_mask:dt}=await this.processor(Ne),ct=await this.model({pixel_values:st,pixel_mask:dt}),lt=this.processor.image_processor.post_process_object_detection(ct,Te,Re),ht=this.model.config.id2label,L=lt.map(ie=>ie.boxes.map((H,me)=>({score:ie.scores[me],label:ht[ie.classes[me]],box:K(H,!Ue)})));return Ve?L:L[0]}}class Ge extends te{constructor(le){super(le)}async _call(le,Te,{threshold:Ue=.1,top_k:Ve=null,percentage:Ne=!1}={}){const Re=Array.isArray(le),st=await b(le),dt=this.tokenizer(Te,{padding:!0,truncation:!0}),ct=await this.processor(st),lt=[];for(let ht=0;ht({score:We.scores[ut],label:We.labels[ut],box:K(Je,!Ne)}))}else{const We=this.processor.image_processor.post_process_object_detection(me,Ue,ie,!0)[0];$e=We.boxes.map((Je,ut)=>({score:We.scores[ut],label:Te[We.classes[ut]],box:K(Je,!Ne)}))}$e.sort((We,Je)=>Je.score-We.score),Ve!==null&&($e=$e.slice(0,Ve)),lt.push($e)}return Re?lt:lt[0]}}class ye extends te{constructor(le){super(le)}async _call(le,Te,Ue={}){const Ve=(await b(le))[0],{pixel_values:Ne}=await this.processor(Ve),Re=`${Te}`,st=this.tokenizer(Re,{add_special_tokens:!1,padding:!0,truncation:!0}).input_ids,dt=await this.model.generate({inputs:Ne,max_length:this.model.config.decoder.max_position_embeddings,decoder_input_ids:st,...Ue}),lt=this.tokenizer.batch_decode(dt)[0].match(/(.*?)<\/s_answer>/);let ht=null;return lt&<.length>=2&&(ht=lt[1].trim()),[{answer:ht}]}}class J extends te{constructor(Te){super(Te);_e(this,"DEFAULT_VOCODER_ID","Xenova/speecht5_hifigan");this.vocoder=Te.vocoder??null}async _call(Te,{speaker_embeddings:Ue=null}={}){return this.processor?this._call_text_to_spectrogram(Te,{speaker_embeddings:Ue}):this._call_text_to_waveform(Te)}async _call_text_to_waveform(Te){const Ue=this.tokenizer(Te,{padding:!0,truncation:!0}),{waveform:Ve}=await this.model(Ue),Ne=this.model.config.sampling_rate;return new v.RawAudio(Ve.data,Ne)}async _call_text_to_spectrogram(Te,{speaker_embeddings:Ue}){if(this.vocoder||(console.log("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await D.AutoModel.from_pretrained(this.DEFAULT_VOCODER_ID,{dtype:"fp32"})),(typeof Ue=="string"||Ue instanceof URL)&&(Ue=new Float32Array(await(await fetch(Ue)).arrayBuffer())),Ue instanceof Float32Array)Ue=new M.Tensor("float32",Ue,[1,Ue.length]);else if(!(Ue instanceof M.Tensor))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");const{input_ids:Ve}=this.tokenizer(Te,{padding:!0,truncation:!0}),{waveform:Ne}=await this.model.generate_speech(Ve,Ue,{vocoder:this.vocoder}),Re=this.processor.feature_extractor.config.sampling_rate;return new v.RawAudio(Ne.data,Re)}}class de extends te{constructor(le){super(le)}async _call(le){const Te=await b(le),Ue=await this.processor(Te),Ve=await this.model(Ue),Ne=[];for(const Re of Ve.reconstruction){const st=Re.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");Ne.push(y.RawImage.fromTensor(st))}return Ne.length>1?Ne:Ne[0]}}class Ce extends te{constructor(le){super(le)}async _call(le){const Te=await b(le),Ue=await this.processor(Te),{predicted_depth:Ve}=await this.model(Ue),Ne=[];for(let Re=0;Re1?Ne:Ne[0]}}const Be=Object.freeze({"text-classification":{tokenizer:f.AutoTokenizer,pipeline:ne,model:D.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{tokenizer:f.AutoTokenizer,pipeline:W,model:D.AutoModelForTokenClassification,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{tokenizer:f.AutoTokenizer,pipeline:j,model:D.AutoModelForQuestionAnswering,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{tokenizer:f.AutoTokenizer,pipeline:q,model:D.AutoModelForMaskedLM,default:{model:"Xenova/bert-base-uncased"},type:"text"},summarization:{tokenizer:f.AutoTokenizer,pipeline:S,model:D.AutoModelForSeq2SeqLM,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{tokenizer:f.AutoTokenizer,pipeline:w,model:D.AutoModelForSeq2SeqLM,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{tokenizer:f.AutoTokenizer,pipeline:$,model:D.AutoModelForSeq2SeqLM,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{tokenizer:f.AutoTokenizer,pipeline:O,model:D.AutoModelForCausalLM,default:{model:"Xenova/gpt2"},type:"text"},"zero-shot-classification":{tokenizer:f.AutoTokenizer,pipeline:ae,model:D.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:we,model:D.AutoModelForAudioClassification,processor:U.AutoProcessor,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{tokenizer:f.AutoTokenizer,pipeline:re,model:D.AutoModel,processor:U.AutoProcessor,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{tokenizer:f.AutoTokenizer,pipeline:xe,model:[D.AutoModelForSpeechSeq2Seq,D.AutoModelForCTC],processor:U.AutoProcessor,default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{tokenizer:f.AutoTokenizer,pipeline:J,model:[D.AutoModelForTextToWaveform,D.AutoModelForTextToSpectrogram],processor:[U.AutoProcessor,null],default:{model:"Xenova/speecht5_tts"},type:"text"},"image-to-text":{tokenizer:f.AutoTokenizer,pipeline:ce,model:D.AutoModelForVision2Seq,processor:U.AutoProcessor,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:ke,model:D.AutoModelForImageClassification,processor:U.AutoProcessor,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:Ie,model:[D.AutoModelForImageSegmentation,D.AutoModelForSemanticSegmentation,D.AutoModelForUniversalSegmentation],processor:U.AutoProcessor,default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"zero-shot-image-classification":{tokenizer:f.AutoTokenizer,pipeline:Ee,model:D.AutoModel,processor:U.AutoProcessor,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:tt,model:D.AutoModelForObjectDetection,processor:U.AutoProcessor,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{tokenizer:f.AutoTokenizer,pipeline:Ge,model:D.AutoModelForZeroShotObjectDetection,processor:U.AutoProcessor,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{tokenizer:f.AutoTokenizer,pipeline:ye,model:D.AutoModelForDocumentQuestionAnswering,processor:U.AutoProcessor,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:de,model:D.AutoModelForImageToImage,processor:U.AutoProcessor,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:Ce,model:D.AutoModelForDepthEstimation,processor:U.AutoProcessor,default:{model:"Xenova/dpt-large"},type:"image"},"feature-extraction":{tokenizer:f.AutoTokenizer,pipeline:oe,model:D.AutoModel,default:{model:"Xenova/all-MiniLM-L6-v2"},type:"text"},"image-feature-extraction":{processor:U.AutoProcessor,pipeline:ve,model:[D.AutoModelForImageFeatureExtraction,D.AutoModel],default:{model:"Xenova/vit-base-patch16-224-in21k"},type:"image"}}),Ze=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});async function se(je,le=null,{progress_callback:Te=null,config:Ue=null,cache_dir:Ve=null,local_files_only:Ne=!1,revision:Re="main",device:st=null,dtype:dt=null,model_file_name:ct=null,session_options:lt={}}={}){je=Ze[je]??je;const ht=Be[je.split("_",1)[0]];if(!ht)throw Error(`Unsupported pipeline: ${je}. Must be one of [${Object.keys(Be)}]`);le||(le=ht.default.model,console.log(`No model specified. Using default model: "${le}".`));const L={progress_callback:Te,config:Ue,cache_dir:Ve,local_files_only:Ne,revision:Re,device:st,dtype:dt,model_file_name:ct,session_options:lt},ie=new Map([["tokenizer",ht.tokenizer],["model",ht.model],["processor",ht.processor]]),H=await Ke(ie,le,L);H.task=je,(0,R.dispatchCallback)(Te,{status:"ready",task:je,model:le});const me=ht.pipeline;return new me(H)}async function Ke(je,le,Te){const Ue=Object.create(null),Ve=[];for(const[Ne,Re]of je.entries()){if(!Re)continue;let st;Array.isArray(Re)?st=new Promise(async(dt,ct)=>{var ht,L;let lt;for(const ie of Re){if(ie===null){dt(null);return}try{dt(await ie.from_pretrained(le,Te));return}catch(H){if((ht=H.message)!=null&&ht.includes("Unsupported model type"))lt=H;else if((L=H.message)!=null&&L.includes("Could not locate file"))lt=H;else{ct(H);return}}}ct(lt)}):st=Re.from_pretrained(le,Te),Ue[Ne]=st,Ve.push(st)}await Promise.all(Ve);for(const[Ne,Re]of Object.entries(Ue))Ue[Ne]=await Re;return Ue}},"./src/tokenizers.js":(De,A,r)=>{r.r(A),r.d(A,{AlbertTokenizer:()=>$r,AutoTokenizer:()=>as,BartTokenizer:()=>Or,BertTokenizer:()=>Jr,BlenderbotSmallTokenizer:()=>Ln,BlenderbotTokenizer:()=>Dn,BloomTokenizer:()=>Er,CLIPTokenizer:()=>bn,CamembertTokenizer:()=>ot,CodeGenTokenizer:()=>Mn,CodeLlamaTokenizer:()=>Ur,CohereTokenizer:()=>Tn,ConvBertTokenizer:()=>Rr,DebertaTokenizer:()=>cr,DebertaV2Tokenizer:()=>en,DistilBertTokenizer:()=>ar,ElectraTokenizer:()=>Dt,EsmTokenizer:()=>Vr,FalconTokenizer:()=>In,GPT2Tokenizer:()=>jr,GPTNeoXTokenizer:()=>On,GemmaTokenizer:()=>io,Grok1Tokenizer:()=>Wr,HerbertTokenizer:()=>Ir,LlamaTokenizer:()=>wn,M2M100Tokenizer:()=>yn,MBart50Tokenizer:()=>lr,MBartTokenizer:()=>Ms,MPNetTokenizer:()=>An,MarianTokenizer:()=>zt,MgpstrTokenizer:()=>Rn,MobileBertTokenizer:()=>Ar,NllbTokenizer:()=>ur,NougatTokenizer:()=>Gr,PreTrainedTokenizer:()=>Nt,Qwen2Tokenizer:()=>Fn,RoFormerTokenizer:()=>Nr,RobertaTokenizer:()=>Os,SiglipTokenizer:()=>vn,SpeechT5Tokenizer:()=>zn,SqueezeBertTokenizer:()=>Zr,T5Tokenizer:()=>Vs,TokenizerModel:()=>ve,VitsTokenizer:()=>Bn,Wav2Vec2CTCTokenizer:()=>xn,WhisperTokenizer:()=>tn,XLMRobertaTokenizer:()=>oo,XLMTokenizer:()=>Tt,is_chinese_char:()=>q});var f=r("./src/utils/generic.js"),D=r("./src/utils/core.js"),U=r("./src/utils/hub.js"),Y=r("./src/utils/maths.js"),R=r("./src/utils/tensor.js"),g=r("./src/utils/data-structures.js"),v=r("./node_modules/@huggingface/jinja/dist/index.js"),M=r("./src/models/whisper/common_whisper.js");async function y(Pe,P){const Q=await Promise.all([(0,U.getModelJSON)(Pe,"tokenizer.json",!0,P),(0,U.getModelJSON)(Pe,"tokenizer_config.json",!0,P)]);return P.legacy!==null&&(Q[1].legacy=P.legacy),Q}function b(Pe,P){const Q=[];let ue=0;for(const be of Pe.matchAll(P)){const Se=be[0];ue0&&Q.push(Se),ue=be.index+Se.length}return ue=19968&&Pe<=40959||Pe>=13312&&Pe<=19903||Pe>=131072&&Pe<=173791||Pe>=173824&&Pe<=177983||Pe>=177984&&Pe<=178207||Pe>=178208&&Pe<=183983||Pe>=63744&&Pe<=64255||Pe>=194560&&Pe<=195103}function $(Pe,P,Q){const ue=[];let be=0;for(;bethis.tokens_to_ids.get(Q)??this.unk_token_id)}convert_ids_to_tokens(P){return P.map(Q=>this.vocab[Q]??this.unk_token)}}class we extends ve{constructor(P){super(P),this.tokens_to_ids=K(P.vocab),this.unk_token_id=this.tokens_to_ids.get(P.unk_token),this.unk_token=P.unk_token,this.max_input_chars_per_word=P.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(const[Q,ue]of this.tokens_to_ids)this.vocab[ue]=Q}encode(P){const Q=[];for(const ue of P){const be=[...ue];if(be.length>this.max_input_chars_per_word){Q.push(this.unk_token);continue}let Se=!1,Qe=0;const pt=[];for(;Qe0&&(xt=this.config.continuing_subword_prefix+xt),this.tokens_to_ids.has(xt)){_t=xt;break}--gt}if(_t===null){Se=!0;break}pt.push(_t),Qe=gt}Se?Q.push(this.unk_token):Q.push(...pt)}return Q}}class re extends ve{constructor(P,Q){super(P);const ue=P.vocab.length;this.vocab=new Array(ue),this.scores=new Array(ue);for(let be=0;be[be,Se])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=Q.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,Y.min)(this.scores)[0],this.unk_score=this.minScore-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new g.CharTrie,this.trie.extend(this.vocab),this.fuse_unk=!0}populateNodes(P){const Q=P.chars,ue=1;let be=0;for(;be{const Pe=[...Array.from({length:94},(be,Se)=>Se+33),...Array.from({length:12},(be,Se)=>Se+161),...Array.from({length:82},(be,Se)=>Se+174)],P=Pe.slice();let Q=0;for(let be=0;be<256;++be)Pe.includes(be)||(Pe.push(be),P.push(256+Q),Q+=1);const ue=P.map(be=>String.fromCharCode(be));return Object.fromEntries(Pe.map((be,Se)=>[be,ue[Se]]))})(),ce=(0,D.reverseDictionary)(xe);class ke extends ve{constructor(P){super(P),this.tokens_to_ids=K(P.vocab),this.unk_token_id=this.tokens_to_ids.get(P.unk_token),this.unk_token=P.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(const[ue,be]of this.tokens_to_ids)this.vocab[be]=ue;const Q=Array.isArray(P.merges[0]);this.merges=Q?P.merges:P.merges.map(ue=>ue.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((ue,be)=>[JSON.stringify(ue),be])),this.end_of_word_suffix=P.end_of_word_suffix,this.continuing_subword_suffix=P.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(P){if(P.length===0)return[];const Q=this.cache.get(P);if(Q!==void 0)return Q;const ue=Array.from(P);this.end_of_word_suffix&&(ue[ue.length-1]+=this.end_of_word_suffix);let be=[];if(ue.length>1){const Se=new g.PriorityQueue((gt,_t)=>gt.score<_t.score);let Qe={token:ue[0],bias:0,prev:null,next:null},pt=Qe;for(let gt=1;gt`<0x${pt.toString(16).toUpperCase().padStart(2,"0")}>`);Qe.every(pt=>this.tokens_to_ids.has(pt))?Q.push(...Qe):Q.push(this.unk_token)}else Q.push(this.unk_token)}return Q}}class Ie extends ve{constructor(P,Q){super(P),this.tokens_to_ids=K(Q.target_lang?P.vocab[Q.target_lang]:P.vocab),this.bos_token=Q.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=Q.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=Q.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=Q.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[ue,be]of this.tokens_to_ids)this.vocab[be]=ue}encode(P){return P}}class Ee extends f.Callable{constructor(P){super(),this.config=P}static fromConfig(P){if(P===null)return null;switch(P.type){case"BertNormalizer":return new Ke(P);case"Precompiled":return new ys(P);case"Sequence":return new se(P);case"Replace":return new tt(P);case"NFC":return new Ge(P);case"NFKC":return new ye(P);case"NFKD":return new J(P);case"Strip":return new de(P);case"StripAccents":return new Ce(P);case"Lowercase":return new Be(P);case"Prepend":return new Ze(P);default:throw new Error(`Unknown Normalizer type: ${P.type}`)}}normalize(P){throw Error("normalize should be implemented in subclass.")}_call(P){return this.normalize(P)}}class tt extends Ee{normalize(P){const Q=I(this.config.pattern);return Q===null?P:P.replaceAll(Q,this.config.content)}}class Ge extends Ee{normalize(P){return P=P.normalize("NFC"),P}}class ye extends Ee{normalize(P){return P=P.normalize("NFKC"),P}}class J extends Ee{normalize(P){return P=P.normalize("NFKD"),P}}class de extends Ee{normalize(P){return this.config.strip_left&&this.config.strip_right?P=P.trim():(this.config.strip_left&&(P=P.trimStart()),this.config.strip_right&&(P=P.trimEnd())),P}}class Ce extends Ee{normalize(P){return P=W(P),P}}class Be extends Ee{normalize(P){return P=P.toLowerCase(),P}}class Ze extends Ee{normalize(P){return P=this.config.prepend+P,P}}class se extends Ee{constructor(P){super(P),this.normalizers=P.normalizers.map(Q=>Ee.fromConfig(Q))}normalize(P){return this.normalizers.reduce((Q,ue)=>ue.normalize(Q),P)}}class Ke extends Ee{_tokenize_chinese_chars(P){const Q=[];for(let ue=0;uethis.pre_tokenize_text(ue,Q)):this.pre_tokenize_text(P,Q)).flat()}_call(P,Q){return this.pre_tokenize(P,Q)}}class le extends je{constructor(P){super(),this.pattern=new RegExp(`[^\\s${w}]+|[${w}]`,"gu")}pre_tokenize_text(P,Q){return P.trim().match(this.pattern)||[]}}class Te extends je{constructor(P){super(),this.config=P,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=xe,this.text_encoder=new TextEncoder}pre_tokenize_text(P,Q){return this.add_prefix_space&&!P.startsWith(" ")&&(P=" "+P),(this.use_regex?P.match(this.pattern)||[]:[P]).map(be=>Array.from(this.text_encoder.encode(be),Se=>this.byte_encoder[Se]).join(""))}}class Ue extends je{constructor(P){super(),this.config=P,this.pattern=I(this.config.pattern,this.config.invert)}pre_tokenize_text(P,Q){var ue;return this.pattern===null?[]:this.config.invert?P.match(this.pattern)||[]:((ue=this.config.behavior)==null?void 0:ue.toLowerCase())==="removed"?P.split(this.pattern).filter(be=>be):b(P,this.pattern)}}class Ve extends je{constructor(P){super(),this.config=P,this.pattern=new RegExp(`[^${w}]+|[${w}]+`,"gu")}pre_tokenize_text(P,Q){return P.match(this.pattern)||[]}}class Ne extends je{constructor(P){super(),this.config=P;const Q=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(Q,"gu")}pre_tokenize_text(P,Q){return P.match(this.pattern)||[]}}class Re extends f.Callable{constructor(P){super(),this.config=P}static fromConfig(P){if(P===null)return null;switch(P.type){case"TemplateProcessing":return new ct(P);case"ByteLevel":return new lt(P);case"RobertaProcessing":return new dt(P);case"BertProcessing":return new st(P);case"Sequence":return new ht(P);default:throw new Error(`Unknown PostProcessor type: ${P.type}`)}}post_process(P,...Q){throw Error("post_process should be implemented in subclass.")}_call(P,...Q){return this.post_process(P,...Q)}}class st extends Re{constructor(P){super(P),this.cls=P.cls[0],this.sep=P.sep[0]}post_process(P,Q=null,{add_special_tokens:ue=!0}={}){ue&&(P=(0,D.mergeArrays)([this.cls],P,[this.sep]));let be=new Array(P.length).fill(0);if(Q!==null){const Se=ue&&this instanceof dt?[this.sep]:[],Qe=ue?[this.sep]:[];P=(0,D.mergeArrays)(P,Se,Q,Qe),be=(0,D.mergeArrays)(be,new Array(Q.length+Se.length+Qe.length).fill(1))}return{tokens:P,token_type_ids:be}}}class dt extends st{}class ct extends Re{constructor(P){super(P),this.single=P.single,this.pair=P.pair}post_process(P,Q=null,{add_special_tokens:ue=!0}={}){const be=Q===null?this.single:this.pair;let Se=[],Qe=[];for(const pt of be)"SpecialToken"in pt?ue&&(Se.push(pt.SpecialToken.id),Qe.push(pt.SpecialToken.type_id)):"Sequence"in pt&&(pt.Sequence.id==="A"?(Se=(0,D.mergeArrays)(Se,P),Qe=(0,D.mergeArrays)(Qe,new Array(P.length).fill(pt.Sequence.type_id))):pt.Sequence.id==="B"&&(Se=(0,D.mergeArrays)(Se,Q),Qe=(0,D.mergeArrays)(Qe,new Array(Q.length).fill(pt.Sequence.type_id))));return{tokens:Se,token_type_ids:Qe}}}class lt extends Re{post_process(P,Q=null){return Q&&(P=(0,D.mergeArrays)(P,Q)),{tokens:P}}}class ht extends Re{constructor(P){super(P),this.processors=P.processors.map(Q=>Re.fromConfig(Q))}post_process(P,Q=null,ue={}){let be;for(const Se of this.processors)if(Se instanceof lt)P=Se.post_process(P).tokens,Q&&(Q=Se.post_process(Q).tokens);else{const Qe=Se.post_process(P,Q,ue);P=Qe.tokens,be=Qe.token_type_ids}return{tokens:P,token_type_ids:be}}}class L extends f.Callable{constructor(P){super(),this.config=P,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets=P.trim_offsets}static fromConfig(P){if(P===null)return null;switch(P.type){case"WordPiece":return new We(P);case"Metaspace":return new os(P);case"ByteLevel":return new Je(P);case"Replace":return new ie(P);case"ByteFallback":return new H(P);case"Fuse":return new me(P);case"Strip":return new $e(P);case"Sequence":return new mt(P);case"CTC":return new ut(P);case"BPEDecoder":return new vt(P);default:throw new Error(`Unknown Decoder type: ${P.type}`)}}_call(P){return this.decode(P)}decode(P){return this.decode_chain(P).join("")}decode_chain(P){throw Error("`decode_chain` should be implemented in subclass.")}}class ie extends L{decode_chain(P){const Q=I(this.config.pattern);return Q===null?P:P.map(ue=>ue.replaceAll(Q,this.config.content))}}class H extends L{constructor(P){super(P),this.text_decoder=new TextDecoder}decode_chain(P){const Q=[];let ue=[];for(const be of P){let Se=null;if(be.length===6&&be.startsWith("<0x")&&be.endsWith(">")){const Qe=parseInt(be.slice(3,5),16);isNaN(Qe)||(Se=Qe)}if(Se!==null)ue.push(Se);else{if(ue.length>0){const Qe=this.text_decoder.decode(Uint8Array.from(ue));Q.push(Qe),ue=[]}Q.push(be)}}if(ue.length>0){const be=this.text_decoder.decode(Uint8Array.from(ue));Q.push(be),ue=[]}return Q}}class me extends L{decode_chain(P){return[P.join("")]}}class $e extends L{constructor(P){super(P),this.content=this.config.content,this.start=this.config.start,this.stop=this.config.stop}decode_chain(P){return P.map(Q=>{let ue=0;for(let Se=0;Se(ue!==0&&(Q.startsWith(this.config.prefix)?Q=Q.replace(this.config.prefix,""):Q=" "+Q),this.cleanup&&(Q=ne(Q)),Q))}}class Je extends L{constructor(P){super(P),this.byte_decoder=ce,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(P){const Q=P.join(""),ue=new Uint8Array([...Q].map(Se=>this.byte_decoder[Se]));return this.text_decoder.decode(ue)}decode_chain(P){const Q=[];let ue=[];for(const be of P)this.added_tokens.find(Se=>Se.content===be)!==void 0?(ue.length>0&&(Q.push(this.convert_tokens_to_string(ue)),ue=[]),Q.push(be)):ue.push(be);return ue.length>0&&Q.push(this.convert_tokens_to_string(ue)),Q}}class ut extends L{constructor(P){super(P),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(P){if(P.length===0)return"";const Q=[P[0]];for(let Se=1;SeSe!==this.pad_token).join("");return this.cleanup&&(be=ne(be).replaceAll(this.word_delimiter_token," ").trim()),be}decode_chain(P){return[this.convert_tokens_to_string(P)]}}class mt extends L{constructor(P){super(P),this.decoders=P.decoders.map(Q=>L.fromConfig(Q))}decode_chain(P){return this.decoders.reduce((Q,ue)=>ue.decode_chain(Q),P)}}class vt extends L{constructor(P){super(P),this.suffix=this.config.suffix}decode_chain(P){return P.map((Q,ue)=>Q.replaceAll(this.suffix,ue===P.length-1?"":" "))}}class kt extends L{decode_chain(P){let Q="";for(let ue=1;ueue.normalize("NFKC")).join("~"):P=P.normalize("NFKC"),P}}class Cs extends je{constructor(P){super(),this.tokenizers=P.pretokenizers.map(Q=>je.fromConfig(Q))}pre_tokenize_text(P,Q){return this.tokenizers.reduce((ue,be)=>be.pre_tokenize(ue,Q),[P])}}class Ds extends je{constructor(P){super()}pre_tokenize_text(P,Q){return P.match(/\w+|[^\w\s]+/g)||[]}}class sr extends je{constructor(P){super()}pre_tokenize_text(P,Q){return S(P)}}class Sr extends je{constructor(P){super(),this.config=P,this.pattern=I(this.config.pattern),this.content=this.config.content}pre_tokenize_text(P,Q){return this.pattern===null?[P]:[P.replaceAll(this.pattern,this.config.content)]}}const Yr=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function Us(Pe,P,Q,ue){for(const be of Object.keys(Pe)){const Se=P-Pe[be].length,Qe=Q(be),pt=new Array(Se).fill(Qe);Pe[be]=ue==="right"?(0,D.mergeArrays)(Pe[be],pt):(0,D.mergeArrays)(pt,Pe[be])}}function Pr(Pe,P){for(const Q of Object.keys(Pe))Pe[Q].length=P}class Nt extends f.Callable{constructor(Q,ue){super();_e(this,"return_token_type_ids",!1);_e(this,"padding_side","right");this._tokenizer_config=ue,this.normalizer=Ee.fromConfig(Q.normalizer),this.pre_tokenizer=je.fromConfig(Q.pre_tokenizer),this.model=ve.fromConfig(Q.model,ue),this.post_processor=Re.fromConfig(Q.post_processor),this.decoder=L.fromConfig(Q.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];for(const be of Q.added_tokens){const Se=new oe(be);this.added_tokens.push(Se),this.model.tokens_to_ids.set(Se.content,Se.id),this.model.vocab[Se.id]=Se.content,Se.special&&(this.special_tokens.push(Se.content),this.all_special_ids.push(Se.id))}if(this.additional_special_tokens=ue.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((be,Se)=>Se.content.length-be.content.length).map(be=>`${be.lstrip?"\\s*":""}(${(0,D.escapeRegExp)(be.content)})${be.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.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=ue.model_max_length,this.remove_space=ue.remove_space,this.clean_up_tokenization_spaces=ue.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=ue.do_lowercase_and_remove_accent??!1,ue.padding_side&&(this.padding_side=ue.padding_side),this.legacy=!1,this.chat_template=ue.chat_template??null,Array.isArray(this.chat_template)){const be=Object.create(null);for(const{name:Se,template:Qe}of this.chat_template){if(typeof Se!="string"||typeof Qe!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');be[Se]=Qe}this.chat_template=be}this._compiled_template_cache=new Map}getToken(...Q){for(const ue of Q){const be=this._tokenizer_config[ue];if(be)if(typeof be=="object"){if(be.__type==="AddedToken")return be.content;throw Error(`Unknown token: ${be}`)}else return be}return null}static async from_pretrained(Q,{progress_callback:ue=null,config:be=null,cache_dir:Se=null,local_files_only:Qe=!1,revision:pt="main",legacy:gt=null}={}){const _t=await y(Q,{progress_callback:ue,config:be,cache_dir:Se,local_files_only:Qe,revision:pt,legacy:gt});return new this(..._t)}_call(Q,{text_pair:ue=null,add_special_tokens:be=!0,padding:Se=!1,truncation:Qe=null,max_length:pt=null,return_tensor:gt=!0,return_token_type_ids:_t=null}={}){const xt=Array.isArray(Q);let Kt;if(xt){if(Q.length===0)throw Error("text array must be non-empty");if(ue!==null){if(Array.isArray(ue)){if(Q.length!==ue.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");Kt=Q.map((us,Fs)=>this._encode_plus(us,{text_pair:ue[Fs],add_special_tokens:be,return_token_type_ids:_t}))}else Kt=Q.map(us=>this._encode_plus(us,{add_special_tokens:be,return_token_type_ids:_t}))}else{if(Q==null)throw Error("text may not be null or undefined");if(Array.isArray(ue))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");Kt=[this._encode_plus(Q,{text_pair:ue,add_special_tokens:be,return_token_type_ids:_t})]}if(pt===null?Se==="max_length"?pt=this.model_max_length:pt=(0,Y.max)(Kt.map(us=>us.input_ids.length))[0]:Qe||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."),pt=Math.min(pt,this.model_max_length??1/0),Se||Qe)for(let us=0;uspt?Qe&&Pr(Kt[us],pt):Se&&Us(Kt[us],pt,Fs=>Fs==="input_ids"?this.pad_token_id:0,this.padding_side));const ms={};if(gt){if(!(Se&&Qe)&&Kt.some(Fs=>{var Bt;for(const rs of Object.keys(Fs))if(Fs[rs].length!==((Bt=Kt[0][rs])==null?void 0:Bt.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 us=[Kt.length,Kt[0].input_ids.length];for(const Fs of Object.keys(Kt[0]))ms[Fs]=new R.Tensor("int64",BigInt64Array.from(Kt.flatMap(Bt=>Bt[Fs]).map(BigInt)),us)}else{for(const us of Object.keys(Kt[0]))ms[us]=Kt.map(Fs=>Fs[us]);if(!xt)for(const us of Object.keys(ms))ms[us]=ms[us][0]}return ms}_encode_text(Q){return Q===null?null:(this.added_tokens_regex?Q.split(this.added_tokens_regex).filter(Se=>Se):[Q]).map((Se,Qe)=>{if(this.added_tokens.find(gt=>gt.content===Se)!==void 0)return Se;{if(this.remove_space===!0&&(Se=Se.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(Se=j(Se)),this.normalizer!==null&&(Se=this.normalizer(Se)),Se.length===0)return[];const gt=this.pre_tokenizer!==null?this.pre_tokenizer(Se,{section_index:Qe}):[Se];return this.model(gt)}}).flat()}_encode_plus(Q,{text_pair:ue=null,add_special_tokens:be=!0,return_token_type_ids:Se=null}={}){const{tokens:Qe,token_type_ids:pt}=this._tokenize_helper(Q,{pair:ue,add_special_tokens:be}),gt=this.model.convert_tokens_to_ids(Qe),_t={input_ids:gt,attention_mask:new Array(gt.length).fill(1)};return(Se??this.return_token_type_ids)&&pt&&(_t.token_type_ids=pt),_t}_tokenize_helper(Q,{pair:ue=null,add_special_tokens:be=!1}={}){const Se=this._encode_text(Q),Qe=this._encode_text(ue);return this.post_processor?this.post_processor(Se,Qe,{add_special_tokens:be}):{tokens:(0,D.mergeArrays)(Se??[],Qe??[])}}tokenize(Q,{pair:ue=null,add_special_tokens:be=!1}={}){return this._tokenize_helper(Q,{pair:ue,add_special_tokens:be}).tokens}encode(Q,{text_pair:ue=null,add_special_tokens:be=!0,return_token_type_ids:Se=null}={}){return this._encode_plus(Q,{text_pair:ue,add_special_tokens:be,return_token_type_ids:Se}).input_ids}batch_decode(Q,ue={}){return Q instanceof R.Tensor&&(Q=Q.tolist()),Q.map(be=>this.decode(be,ue))}decode(Q,ue={}){if(Q instanceof R.Tensor&&(Q=te(Q)),!Array.isArray(Q)||Q.length===0||!(0,D.isIntegralNumber)(Q[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(Q,ue)}decode_single(Q,{skip_special_tokens:ue=!1,clean_up_tokenization_spaces:be=null}){let Se=this.model.convert_ids_to_tokens(Q);ue&&(Se=Se.filter(pt=>!this.special_tokens.includes(pt)));let Qe=this.decoder?this.decoder(Se):Se.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(Qe=Qe.replaceAll(this.decoder.end_of_word_suffix," "),ue&&(Qe=Qe.trim())),(be??this.clean_up_tokenization_spaces)&&(Qe=ne(Qe)),Qe}get_chat_template({chat_template:Q=null,tools:ue=null}={}){if(this.chat_template&&typeof this.chat_template=="object"){const be=this.chat_template;if(Q!==null&&Object.hasOwn(be,Q))Q=be[Q];else if(Q===null)if(ue!==null&&"tool_use"in be)Q=be.tool_use;else if("default"in be)Q=be.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(be).sort()}.`)}else if(Q===null)if(this.chat_template)Q=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 Q}apply_chat_template(Q,{tools:ue=null,documents:be=null,chat_template:Se=null,add_generation_prompt:Qe=!1,tokenize:pt=!0,padding:gt=!1,truncation:_t=!1,max_length:xt=null,return_tensor:Kt=!0,return_dict:ms=!1,tokenizer_kwargs:us={},...Fs}={}){if(Se=this.get_chat_template({chat_template:Se,tools:ue}),typeof Se!="string")throw Error(`chat_template must be a string, but got ${typeof Se}`);let Bt=this._compiled_template_cache.get(Se);Bt===void 0&&(Bt=new v.Template(Se),this._compiled_template_cache.set(Se,Bt));const rs=Object.create(null);for(const Ws of Yr){const ze=this.getToken(Ws);ze&&(rs[Ws]=ze)}const rr=Bt.render({messages:Q,add_generation_prompt:Qe,tools:ue,documents:be,...rs,...Fs});if(pt){const Ws=this._call(rr,{add_special_tokens:!1,padding:gt,truncation:_t,max_length:xt,return_tensor:Kt,...us});return ms?Ws:Ws.input_ids}return rr}}class Jr extends Nt{constructor(){super(...arguments);_e(this,"return_token_type_ids",!0)}}class $r extends Nt{constructor(){super(...arguments);_e(this,"return_token_type_ids",!0)}}class Ar extends Nt{constructor(){super(...arguments);_e(this,"return_token_type_ids",!0)}}class Zr extends Nt{constructor(){super(...arguments);_e(this,"return_token_type_ids",!0)}}class cr extends Nt{constructor(){super(...arguments);_e(this,"return_token_type_ids",!0)}}class en extends Nt{constructor(){super(...arguments);_e(this,"return_token_type_ids",!0)}}class Ir extends Nt{constructor(){super(...arguments);_e(this,"return_token_type_ids",!0)}}class Rr extends Nt{constructor(){super(...arguments);_e(this,"return_token_type_ids",!0)}}class Nr extends Nt{constructor(){super(...arguments);_e(this,"return_token_type_ids",!0)}}class ar extends Nt{}class ot extends Nt{}class Tt extends Nt{constructor(Q,ue){super(Q,ue);_e(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 Dt extends Nt{constructor(){super(...arguments);_e(this,"return_token_type_ids",!0)}}class Vs extends Nt{}class jr extends Nt{}class Or extends Nt{}class Ms extends Nt{constructor(P,Q){super(P,Q),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.special_tokens.filter(ue=>this.languageRegex.test(ue)),this.lang_to_token=ue=>ue}_build_translation_inputs(P,Q,ue){return _r(this,P,Q,ue)}}class lr extends Ms{}class Os extends Nt{}class Er extends Nt{}const es="▁";class wn extends Nt{constructor(Q,ue){super(Q,ue);_e(this,"padding_side","left");this.legacy=ue.legacy??!0,this.legacy||(this.normalizer=null,this.pre_tokenizer=new At({replacement:es,add_prefix_space:!0,prepend_scheme:"first"}))}_encode_text(Q){if(Q===null)return null;if(this.legacy||Q.length===0)return super._encode_text(Q);let ue=super._encode_text(es+Q.replaceAll(es," "));return ue.length>1&&ue[0]===es&&this.special_tokens.includes(ue[1])&&(ue=ue.slice(1)),ue}}class Ur extends Nt{}class oo extends Nt{}class An extends Nt{}class In extends Nt{}class On extends Nt{}class Vr extends Nt{}class Fn extends Nt{}class io extends Nt{}class Wr extends Nt{}function _r(Pe,P,Q,ue){if(!("language_codes"in Pe)||!Array.isArray(Pe.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in Pe)||!(Pe.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in Pe)||typeof Pe.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");const be=ue.src_lang,Se=ue.tgt_lang;if(!Pe.language_codes.includes(Se))throw new Error(`Target language code "${Se}" is not valid. Must be one of: {${Pe.language_codes.join(", ")}}`);if(be!==void 0){if(!Pe.language_codes.includes(be))throw new Error(`Source language code "${be}" is not valid. Must be one of: {${Pe.language_codes.join(", ")}}`);for(const Qe of Pe.post_processor.config.single)if("SpecialToken"in Qe&&Pe.languageRegex.test(Qe.SpecialToken.id)){Qe.SpecialToken.id=Pe.lang_to_token(be);break}}return ue.forced_bos_token_id=Pe.model.convert_tokens_to_ids([Pe.lang_to_token(Se)])[0],Pe._call(P,Q)}class ur extends Nt{constructor(P,Q){super(P,Q),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.special_tokens.filter(ue=>this.languageRegex.test(ue)),this.lang_to_token=ue=>ue}_build_translation_inputs(P,Q,ue){return _r(this,P,Q,ue)}}class yn extends Nt{constructor(P,Q){super(P,Q),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.special_tokens.filter(ue=>this.languageRegex.test(ue)).map(ue=>ue.slice(2,-2)),this.lang_to_token=ue=>`__${ue}__`}_build_translation_inputs(P,Q,ue){return _r(this,P,Q,ue)}}class tn extends Nt{get timestamp_begin(){return this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0]+1}_decode_asr(P,{return_timestamps:Q=!1,return_language:ue=!1,time_precision:be=null,force_full_sequences:Se=!0}={}){if(be===null)throw Error("Must specify time_precision");let Qe=null;const pt=Q==="word";function gt(){return{language:Qe,timestamp:[null,null],text:""}}const _t=[];let xt=gt(),Kt=0;const ms=this.timestamp_begin,Fs=ms+1500;let Bt=[],rs=[],rr=!1,Ws=null;const ze=new Set(this.all_special_ids);for(const ks of P){const Xs=ks.tokens,Ot=pt?ks.token_timestamps:null;let or=null,fr=ms;if("stride"in ks){const[yt,qt,Ls]=ks.stride;if(Kt-=qt,Ws=yt-Ls,qt&&(fr=qt/be+ms),Ls)for(let $s=Xs.length-1;$s>=0;--$s){const Gs=Number(Xs[$s]);if(Gs>=ms){if(or!==null&&(Gs-ms)*be=ms&&qt<=Fs){const Ls=(qt-ms)*be+Kt,$s=(0,Y.round)(Ls,2);if(or!==null&&qt>=or)rr=!0;else if(rr||Bt.length>0&&qt0?(Bt.push(_s),pt&&rs.push(Ss)):Bt.every(yt=>yt.length===0)&&(xt=gt(),Bt=[],_s=[],rs=[],Ss=[])}if(Bt.length>0){if(Se&&Q)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[ks,Xs]=this.findLongestCommonSequence(Bt,rs),Ot=this.decode(ks);xt.text=Ot,pt&&(xt.words=this.collateWordTimestamps(ks,Xs,Qe)),_t.push(xt)}let Js=Object.create(null);const Fr=_t.map(ks=>ks.text).join("");if(Q||ue){for(let ks=0;ks<_t.length;++ks){const Xs=_t[ks];Q||delete Xs.timestamp,ue||delete Xs.language}if(pt){const ks=[];for(const Xs of _t)for(const Ot of Xs.words)ks.push(Ot);Js={chunks:ks}}else Js={chunks:_t}}return[Fr,Js]}findLongestCommonSequence(P,Q=null){let ue=P[0],be=ue.length,Se=[];const Qe=Array.isArray(Q)&&Q.length>0;let pt=Qe?[]:null,gt=Qe?Q[0]:null;for(let _t=1;_tqt===fr[Ls]&>[Fr+Ls]<=Q[_t][Ot+Ls]).length:_s=Xs.filter((qt,Ls)=>qt===fr[Ls]).length;const Ss=Js/1e4,yt=_s/Js+Ss;_s>1&&yt>Kt&&(Kt=yt,ms=[Fr,ks,Ot,or])}const[Fs,Bt,rs,rr]=ms,Ws=Math.floor((Bt+Fs)/2),ze=Math.floor((rr+rs)/2);Se.push(...ue.slice(0,Ws)),ue=xt.slice(ze),be=ue.length,Qe&&(pt.push(...gt.slice(0,Ws)),gt=Q[_t].slice(ze))}return Se.push(...ue),Qe?(pt.push(...gt),[Se,pt]):[Se,[]]}collateWordTimestamps(P,Q,ue){const[be,Se,Qe]=this.combineTokensIntoWords(P,ue),pt=[];for(let gt=0;gt=be){const pt=((Qe-be)*ue).toFixed(2);Se.push(`<|${pt}|>`),Se.push([])}else Se[Se.length-1].push(Qe);return Se=Se.map(Qe=>typeof Qe=="string"?Qe:super.decode(Qe,Q)),Se.join("")}splitTokensOnUnicode(P){const Q=this.decode(P,{decode_with_timestamps:!0}),ue="�",be=[],Se=[],Qe=[];let pt=[],gt=[],_t=0;for(let xt=0;xt=this.model.tokens_to_ids.get("<|endoftext|>"),Fs=xt.startsWith(" "),Bt=xt.trim(),rs=gt.test(Bt);if(us||Fs||rs||Se.length===0)Se.push(xt),Qe.push(Kt),pt.push(ms);else{const rr=Se.length-1;Se[rr]+=xt,Qe[rr].push(...Kt),pt[rr].push(...ms)}}return[Se,Qe,pt]}mergePunctuations(P,Q,ue,be,Se){const Qe=structuredClone(P),pt=structuredClone(Q),gt=structuredClone(ue);let _t=Qe.length-2,xt=Qe.length-1;for(;_t>=0;)Qe[_t].startsWith(" ")&&be.includes(Qe[_t].trim())?(Qe[xt]=Qe[_t]+Qe[xt],pt[xt]=(0,D.mergeArrays)(pt[_t],pt[xt]),gt[xt]=(0,D.mergeArrays)(gt[_t],gt[xt]),Qe[_t]="",pt[_t]=[],gt[_t]=[]):xt=_t,--_t;for(_t=0,xt=1;xtKt),pt.filter(Kt=>Kt.length>0),gt.filter(Kt=>Kt.length>0)]}}class Mn extends Nt{}class bn extends Nt{}class vn extends Nt{}class zt extends Nt{constructor(P,Q){super(P,Q),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=this.model.vocab.filter(ue=>this.languageRegex.test(ue)),console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(P){if(P===null)return null;const[Q,...ue]=P.trim().split(this.languageRegex);if(ue.length===0)return super._encode_text(Q);if(ue.length===2){const[be,Se]=ue;return this.supported_language_codes.includes(be)||console.warn(`Unsupported language code "${be}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),(0,D.mergeArrays)([be],super._encode_text(Se))}}}class xn extends Nt{}class Dn extends Nt{}class Ln extends Nt{}class zn extends Nt{}class Gr extends Nt{}class Bn extends Nt{constructor(P,Q){super(P,Q),this.decoder=new kt({})}}class Tn extends Nt{}class Rn extends Nt{}class as{static async from_pretrained(P,{progress_callback:Q=null,config:ue=null,cache_dir:be=null,local_files_only:Se=!1,revision:Qe="main",legacy:pt=null}={}){var ms;const[gt,_t]=await y(P,{progress_callback:Q,config:ue,cache_dir:be,local_files_only:Se,revision:Qe,legacy:pt}),xt=((ms=_t.tokenizer_class)==null?void 0:ms.replace(/Fast$/,""))??"PreTrainedTokenizer";let Kt=this.TOKENIZER_CLASS_MAPPING[xt];return Kt||(console.warn(`Unknown tokenizer class "${xt}", attempting to construct from base class.`),Kt=Nt),new Kt(gt,_t)}}_e(as,"TOKENIZER_CLASS_MAPPING",{T5Tokenizer:Vs,DistilBertTokenizer:ar,CamembertTokenizer:ot,DebertaTokenizer:cr,DebertaV2Tokenizer:en,BertTokenizer:Jr,HerbertTokenizer:Ir,ConvBertTokenizer:Rr,RoFormerTokenizer:Nr,XLMTokenizer:Tt,ElectraTokenizer:Dt,MobileBertTokenizer:Ar,SqueezeBertTokenizer:Zr,AlbertTokenizer:$r,GPT2Tokenizer:jr,BartTokenizer:Or,MBartTokenizer:Ms,MBart50Tokenizer:lr,RobertaTokenizer:Os,WhisperTokenizer:tn,CodeGenTokenizer:Mn,CLIPTokenizer:bn,SiglipTokenizer:vn,MarianTokenizer:zt,BloomTokenizer:Er,NllbTokenizer:ur,M2M100Tokenizer:yn,LlamaTokenizer:wn,CodeLlamaTokenizer:Ur,XLMRobertaTokenizer:oo,MPNetTokenizer:An,FalconTokenizer:In,GPTNeoXTokenizer:On,EsmTokenizer:Vr,Wav2Vec2CTCTokenizer:xn,BlenderbotTokenizer:Dn,BlenderbotSmallTokenizer:Ln,SpeechT5Tokenizer:zn,NougatTokenizer:Gr,VitsTokenizer:Bn,Qwen2Tokenizer:Fn,GemmaTokenizer:io,Grok1Tokenizer:Wr,CohereTokenizer:Tn,MgpstrTokenizer:Rn,PreTrainedTokenizer:Nt})},"./src/utils/audio.js":(De,A,r)=>{r.r(A),r.d(A,{RawAudio:()=>we,hamming:()=>b,hanning:()=>y,mel_filter_bank:()=>q,read_audio:()=>v,spectrogram:()=>O,window_function:()=>ae});var f=r("./src/utils/hub.js"),D=r("./src/utils/maths.js"),U=r("./src/utils/core.js"),Y=r("./src/env.js"),R=r("?7a2c"),g=r("./src/utils/tensor.js");async function v(re,xe){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 ce=await(await(0,f.getFile)(re)).arrayBuffer(),ke=new AudioContext({sampleRate:xe});typeof xe>"u"&&console.warn(`No sampling rate provided, using default of ${ke.sampleRate}Hz.`);const Ie=await ke.decodeAudioData(ce);let Ee;if(Ie.numberOfChannels===2){const tt=Math.sqrt(2),Ge=Ie.getChannelData(0),ye=Ie.getChannelData(1);Ee=new Float32Array(Ge.length);for(let J=0;J2595*Math.log10(1+re/700),kaldi:re=>1127*Math.log(1+re/700),slaney:(re,xe=1e3,ce=15,ke=27/Math.log(6.4))=>re>=xe?ce+Math.log(re/xe)*ke:3*re/200};function K(re,xe="htk"){const ce=I[xe];if(!ce)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof re=="number"?ce(re):re.map(ke=>ce(ke))}const te={htk:re=>700*(10**(re/2595)-1),kaldi:re=>700*(Math.exp(re/1127)-1),slaney:(re,xe=1e3,ce=15,ke=Math.log(6.4)/27)=>re>=ce?xe*Math.exp(ke*(re-ce)):200*re/3};function ne(re,xe="htk"){const ce=te[xe];if(!ce)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof re=="number"?ce(re):re.map(ke=>ce(ke))}function W(re,xe){const ce=Float64Array.from({length:xe.length-1},(tt,Ge)=>xe[Ge+1]-xe[Ge]),ke=Array.from({length:re.length},()=>new Array(xe.length));for(let tt=0;ttnew Array(re.length));for(let tt=0;ttre+ke*Ee)}function q(re,xe,ce,ke,Ie,Ee=null,tt="htk",Ge=!1){if(Ee!==null&&Ee!=="slaney")throw new Error('norm must be one of null or "slaney"');const ye=K(ce,tt),J=K(ke,tt),de=j(ye,J,xe+2);let Ce=ne(de,tt),Be;if(Ge){const se=Ie/(re*2);Be=K(Float64Array.from({length:re},(Ke,je)=>je*se),tt),Ce=de}else Be=j(0,Math.floor(Ie/2),re);const Ze=W(Be,Ce);if(Ee!==null&&Ee==="slaney")for(let se=0;seIe)throw Error(`frame_length (${ce}) may not be larger than fft_length (${Ie})`);if(Ne!==ce)throw new Error(`Length of the window (${Ne}) must equal frame_length (${ce})`);if(ke<=0)throw new Error("hop_length must be greater than zero");if(Ee===null&&de!==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(tt){if(Ge!=="reflect")throw new Error(`pad_mode="${Ge}" not implemented yet.`);const We=Math.floor((Ie-1)/2)+1;re=$(re,We,We)}let Re=Math.floor(1+Math.floor((re.length-ce)/ke));le!==null&&ReRe?Ue&&(ct=Te):ct=dt=Te);const lt=new D.FFT(Ie),ht=new Float64Array(Ie),L=new Float64Array(lt.outputBufferSize),ie=new Float32Array(st*ct);for(let We=0;We=1;--mt)ht[mt]-=J*ht[mt-1];ht[0]*=1-J}for(let mt=0;mtMath.pow(Ge,.85));break;default:throw new Error(`Unknown window type ${xe}.`)}if(ce&&(tt=tt.subarray(0,re)),ke===null)return tt;if(re>ke)throw new Error(`Length of the window (${re}) may not be larger than frame_length (${ke})`);return tt}function oe(re,xe){let ce=44;const ke=new ArrayBuffer(ce+re.length*4),Ie=new DataView(ke);ve(Ie,0,"RIFF"),Ie.setUint32(4,36+re.length*4,!0),ve(Ie,8,"WAVE"),ve(Ie,12,"fmt "),Ie.setUint32(16,16,!0),Ie.setUint16(20,3,!0),Ie.setUint16(22,1,!0),Ie.setUint32(24,xe,!0),Ie.setUint32(28,xe*4,!0),Ie.setUint16(32,4,!0),Ie.setUint16(34,32,!0),ve(Ie,36,"data"),Ie.setUint32(40,re.length*4,!0);for(let Ee=0;Ee{let Ee=await Ie.arrayBuffer();R.writeFileSync(ke,Buffer.from(Ee))};else throw new Error("Unable to save because filesystem is disabled in this environment.");await ce(xe,this.toBlob())}}},"./src/utils/constants.js":(De,A,r)=>{r.r(A),r.d(A,{CHAT_TEMPLATE_NAME:()=>g,CONFIG_NAME:()=>D,FEATURE_EXTRACTOR_NAME:()=>U,GENERATION_CONFIG_NAME:()=>v,GITHUB_ISSUE_URL:()=>f,IMAGE_PROCESSOR_NAME:()=>Y,PROCESSOR_NAME:()=>R});const f="https://github.com/huggingface/transformers.js/issues/new/choose",D="config.json",U="preprocessor_config.json",Y=U,R="processor_config.json",g="chat_template.json",v="generation_config.json"},"./src/utils/core.js":(De,A,r)=>{r.r(A),r.d(A,{calculateDimensions:()=>v,calculateReflectOffset:()=>I,count:()=>W,dispatchCallback:()=>f,escapeRegExp:()=>U,isIntegralNumber:()=>R,isNullishDimension:()=>g,isTypedArray:()=>Y,len:()=>ne,mergeArrays:()=>y,pick:()=>te,pop:()=>M,product:()=>b,reverseDictionary:()=>D,saveBlob:()=>K});function f(j,q){j&&j(q)}function D(j){return Object.fromEntries(Object.entries(j).map(([q,$])=>[$,q]))}function U(j){return j.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Y(j){var q,$,S;return((S=($=(q=j==null?void 0:j.prototype)==null?void 0:q.__proto__)==null?void 0:$.constructor)==null?void 0:S.name)==="TypedArray"}function R(j){return Number.isInteger(j)||typeof j=="bigint"}function g(j){return j==null||j===-1}function v(j){const q=[];let $=j;for(;Array.isArray($);)q.push($.length),$=$[0];return q}function M(j,q,$=void 0){const S=j[q];if(S!==void 0)return delete j[q],S;if($===void 0)throw Error(`Key ${q} does not exist in object.`);return $}function y(...j){return Array.prototype.concat.apply([],j)}function b(...j){return j.reduce((q,$)=>q.flatMap(S=>$.map(w=>[S,w])))}function I(j,q){return Math.abs((j+q)%(2*q)-q)}function K(j,q){const $=URL.createObjectURL(q),S=document.createElement("a");S.href=$,S.download=j,S.click(),S.remove(),URL.revokeObjectURL($)}function te(j,q){return Object.assign({},...q.map($=>{if(j[$]!==void 0)return{[$]:j[$]}}))}function ne(j){let q=0;for(const $ of j)++q;return q}function W(j,q){let $=0;for(const S of j)S===q&&++$;return $}},"./src/utils/data-structures.js":(De,A,r)=>{r.r(A),r.d(A,{CharTrie:()=>D,PriorityQueue:()=>f,TokenLattice:()=>Y});class f{constructor(v=(y,b)=>y>b,M=1/0){this._heap=[],this._comparator=v,this._maxSize=M}get size(){return this._heap.length}isEmpty(){return this.size===0}peek(){return this._heap[0]}push(...v){return this.extend(v)}extend(v){for(const M of v)if(this.size0&&this._swap(0,M),this._heap.pop(),this._siftDown(),v}replace(v){const M=this.peek();return this._heap[0]=v,this._siftDown(),M}_parent(v){return(v+1>>>1)-1}_left(v){return(v<<1)+1}_right(v){return v+1<<1}_greater(v,M){return this._comparator(this._heap[v],this._heap[M])}_swap(v,M){const y=this._heap[v];this._heap[v]=this._heap[M],this._heap[M]=y}_siftUp(){this._siftUpFrom(this.size-1)}_siftUpFrom(v){for(;v>0&&this._greater(v,this._parent(v));)this._swap(v,this._parent(v)),v=this._parent(v)}_siftDown(){let v=0;for(;this._left(v)[]),this.endNodes=Array.from({length:this.len+1},()=>[]);const b=new R(this.bosTokenId,0,0,0,0),I=new R(this.eosTokenId,1,this.len,0,0);this.nodes.push(b.clone()),this.nodes.push(I.clone()),this.beginNodes[this.len].push(I),this.endNodes[0].push(b)}insert(v,M,y,b){const I=this.nodes.length,K=new R(b,I,v,M,y);this.beginNodes[v].push(K),this.endNodes[v+M].push(K),this.nodes.push(K)}viterbi(){const v=this.len;let M=0;for(;M<=v;){if(this.beginNodes[M].length==0)return[];for(let te of this.beginNodes[M]){te.prev=null;let ne=0,W=null;for(let j of this.endNodes[M]){const q=j.backtraceScore+te.score;(W===null||q>ne)&&(W=j.clone(),ne=q)}if(W!==null)te.prev=W,te.backtraceScore=ne;else return[]}++M}const y=[],I=this.beginNodes[v][0].prev;if(I===null)return[];let K=I.clone();for(;K.prev!==null;)y.push(K.clone()),K=K.clone().prev.clone();return y.reverse(),y}piece(v){return this.chars.slice(v.pos,v.pos+v.length).join("")}tokens(){return this.viterbi().map(M=>this.piece(M))}tokenIds(){return this.viterbi().map(M=>M.tokenId)}}class R{constructor(v,M,y,b,I){this.tokenId=v,this.nodeId=M,this.pos=y,this.length=b,this.score=I,this.prev=null,this.backtraceScore=0}clone(){const v=new R(this.tokenId,this.nodeId,this.pos,this.length,this.score);return v.prev=this.prev,v.backtraceScore=this.backtraceScore,v}}},"./src/utils/devices.js":(De,A,r)=>{r.r(A),r.d(A,{DEVICE_TYPES:()=>f});const f=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":(De,A,r)=>{r.r(A),r.d(A,{DATA_TYPES:()=>Y,DEFAULT_DEVICE_DTYPE_MAPPING:()=>R,DEFAULT_DTYPE_SUFFIX_MAPPING:()=>g,isWebGpuFp16Supported:()=>U});var f=r("./src/env.js"),D=r("./src/utils/devices.js");const U=function(){let v;return async function(){if(v===void 0)if(!f.apis.IS_WEBGPU_AVAILABLE)v=!1;else try{v=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{v=!1}return v}}(),Y=Object.freeze({auto:"auto",fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16"}),R=Object.freeze({[D.DEVICE_TYPES.wasm]:Y.q8}),g=Object.freeze({[Y.fp32]:"",[Y.fp16]:"_fp16",[Y.int8]:"_int8",[Y.uint8]:"_uint8",[Y.q8]:"_quantized",[Y.q4]:"_q4",[Y.q4f16]:"_q4f16",[Y.bnb4]:"_bnb4"})},"./src/utils/generic.js":(De,A,r)=>{r.r(A),r.d(A,{Callable:()=>f});const f=class{constructor(){let D=function(...U){return D._call(...U)};return Object.setPrototypeOf(D,new.target.prototype)}_call(...D){throw Error("Must implement _call method in subclass")}}},"./src/utils/hub.js":(De,A,r)=>{r.r(A),r.d(A,{getFile:()=>M,getModelFile:()=>te,getModelJSON:()=>ne});var f=r("?7a2c"),D=r("?a42a"),U=r("./src/env.js"),Y=r("./src/utils/core.js");const R={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 g{constructor($){if(this.filePath=$,this.headers=new Headers,this.exists=f.existsSync($),this.exists){this.status=200,this.statusText="OK";let S=f.statSync($);this.headers.set("content-length",S.size.toString()),this.updateContentType();let w=this;this.body=new ReadableStream({start(x){w.arrayBuffer().then(O=>{x.enqueue(new Uint8Array(O)),x.close()})}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){const $=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",R[$]??"application/octet-stream")}clone(){let $=new g(this.filePath);return $.exists=this.exists,$.status=this.status,$.statusText=this.statusText,$.headers=new Headers(this.headers),$}async arrayBuffer(){return(await f.promises.readFile(this.filePath)).buffer}async blob(){const $=await f.promises.readFile(this.filePath);return new Blob([$],{type:this.headers.get("content-type")})}async text(){return await f.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}}function v(q,$=null,S=null){let w;try{w=new URL(q)}catch{return!1}return!($&&!$.includes(w.protocol)||S&&!S.includes(w.hostname))}async function M(q){var $;if(U.env.useFS&&!v(q,["http:","https:","blob:"]))return new g(q);if(typeof process<"u"&&(($=process==null?void 0:process.release)==null?void 0:$.name)==="node"){const S=!!(dr!=null&&dr.TESTING_REMOTELY),w=U.env.version,x=new Headers;if(x.set("User-Agent",`transformers.js/${w}; is_ci/${S};`),v(q,["http:","https:"],["huggingface.co","hf.co"])){const ae=(dr==null?void 0:dr.HF_TOKEN)??(dr==null?void 0:dr.HF_ACCESS_TOKEN);ae&&x.set("Authorization",`Bearer ${ae}`)}return fetch(q,{headers:x})}else return fetch(q)}const y={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 b(q,$,S){if(!S)return null;const w=y[q]??`Error (${q}) occurred while trying to load file`;throw Error(`${w}: "${$}".`)}class I{constructor($){this.path=$}async match($){let S=D.join(this.path,$),w=new g(S);if(w.exists)return w}async put($,S){const w=Buffer.from(await S.arrayBuffer());let x=D.join(this.path,$);try{await f.promises.mkdir(D.dirname(x),{recursive:!0}),await f.promises.writeFile(x,w)}catch(O){console.warn("An error occurred while writing the file to cache:",O)}}}async function K(q,...$){for(let S of $)try{let w=await q.match(S);if(w)return w}catch{continue}}async function te(q,$,S=!0,w={}){if(!U.env.allowLocalModels){if(w.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(!U.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,Y.dispatchCallback)(w.progress_callback,{status:"initiate",name:q,file:$});let x;if(!x&&U.env.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{x=await caches.open("transformers-cache")}catch(tt){console.warn("An error occurred while opening the browser cache:",tt)}}if(!x&&U.env.useFSCache&&(x=new I(w.cache_dir??U.env.cacheDir)),!x&&U.env.useCustomCache){if(!U.env.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!U.env.customCache.match||!U.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");x=U.env.customCache}const O=w.revision??"main";let ae=j(q,$),oe=j(U.env.localModelPath,ae),ve=j(U.env.remoteHost,U.env.remotePathTemplate.replaceAll("{model}",q).replaceAll("{revision}",encodeURIComponent(O)),$),we=O==="main"?ae:j(q,O,$),re,xe=x instanceof I?we:ve,ce=!1,ke;x&&(ke=await K(x,oe,xe));const Ie=ke!==void 0;if(ke===void 0){if(U.env.allowLocalModels)if(v(ae,["http:","https:"])){if(w.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${ae}.`);if(!U.env.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${ae}.`)}else try{ke=await M(oe),re=oe}catch(Ge){console.warn(`Unable to load from local path "${oe}": "${Ge}"`)}if(ke===void 0||ke.status===404){if(w.local_files_only||!U.env.allowRemoteModels){if(S)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${oe}".`);return null}if(ke=await M(ve),ke.status!==200)return b(ke.status,ve,S);re=xe}ce=x&&typeof Response<"u"&&ke instanceof Response&&ke.status===200}(0,Y.dispatchCallback)(w.progress_callback,{status:"download",name:q,file:$});let Ee;return w.progress_callback?Ie&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent)?(Ee=new Uint8Array(await ke.arrayBuffer()),(0,Y.dispatchCallback)(w.progress_callback,{status:"progress",name:q,file:$,progress:100,loaded:Ee.length,total:Ee.length})):Ee=await W(ke,tt=>{(0,Y.dispatchCallback)(w.progress_callback,{status:"progress",name:q,file:$,...tt})}):Ee=new Uint8Array(await ke.arrayBuffer()),ce&&re&&await x.match(re)===void 0&&await x.put(re,new Response(Ee,{headers:ke.headers})).catch(tt=>{console.warn(`Unable to add response to browser cache: ${tt}.`)}),(0,Y.dispatchCallback)(w.progress_callback,{status:"done",name:q,file:$}),Ee}async function ne(q,$,S=!0,w={}){let x=await te(q,$,S,w);if(x===null)return{};let ae=new TextDecoder("utf-8").decode(x);return JSON.parse(ae)}async function W(q,$){const S=q.headers.get("Content-Length");S===null&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let w=parseInt(S??"0"),x=new Uint8Array(w),O=0;const ae=q.body.getReader();async function oe(){const{done:ve,value:we}=await ae.read();if(ve)return;let re=O+we.length;if(re>w){w=re;let ce=new Uint8Array(w);ce.set(x),x=ce}x.set(we,O),O=re;const xe=O/w*100;return $({progress:xe,loaded:O,total:w}),oe()}return await oe(),x}function j(...q){return q=q.map(($,S)=>(S&&($=$.replace(new RegExp("^/"),"")),S!==q.length-1&&($=$.replace(new RegExp("/$"),"")),$)),q.join("/")}},"./src/utils/image.js":(De,A,r)=>{r.r(A),r.d(A,{RawImage:()=>K,load_image:()=>te});var f=r("./src/utils/core.js"),D=r("./src/utils/hub.js"),U=r("./src/env.js"),Y=r("./src/utils/tensor.js"),R=r("?2b25");let g,v,M;const y=U.apis.IS_BROWSER_ENV||U.apis.IS_WEBWORKER_ENV;if(y)g=(ne,W)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(ne,W)},M=self.createImageBitmap,v=self.ImageData;else if(R)M=async ne=>{const j=(await ne.metadata()).channels,{data:q,info:$}=await ne.rotate().raw().toBuffer({resolveWithObject:!0}),S=new K(new Uint8ClampedArray(q),$.width,$.height,$.channels);return j!==void 0&&j!==$.channels&&S.convert(j),S};else throw new Error("Unable to load image processing library.");const b={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},I=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]);class K{constructor(W,j,q,$){this.data=W,this.width=j,this.height=q,this.channels=$}get size(){return[this.width,this.height]}static async read(W){if(W instanceof K)return W;if(typeof W=="string"||W instanceof URL)return await this.fromURL(W);throw new Error(`Unsupported input type: ${typeof W}`)}static fromCanvas(W){if(!y)throw new Error("fromCanvas() is only supported in browser environments.");const q=W.getContext("2d").getImageData(0,0,W.width,W.height).data;return new K(q,W.width,W.height,4)}static async fromURL(W){const j=await(0,D.getFile)(W);if(j.status!==200)throw new Error(`Unable to read image from "${W}" (${j.status} ${j.statusText})`);const q=await j.blob();return this.fromBlob(q)}static async fromBlob(W){if(y){const j=await M(W),q=g(j.width,j.height).getContext("2d");return q.drawImage(j,0,0),new this(q.getImageData(0,0,j.width,j.height).data,j.width,j.height,4)}else{const j=R(await W.arrayBuffer());return await M(j)}}static fromTensor(W,j="CHW"){if(W.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${W.dims.length} dimensions.`);if(j==="CHW")W=W.transpose(1,2,0);else if(j!=="HWC")throw new Error(`Unsupported channel format: ${j}`);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 K(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 j=0,q=0;j=0?O=q:oe=-q,$>=0?ae=$:ve=-$,x.drawImage(w,O,ae,W,j,oe,ve,W,j),new K(x.getImageData(0,0,W,j).data,W,j,4).convert(S)}else{let S=this.toSharp();if(q>=0&&$>=0)S=S.extract({left:Math.floor(q),top:Math.floor($),width:W,height:j});else if(q<=0&&$<=0){const w=Math.floor(-$),x=Math.floor(-q);S=S.extend({top:w,left:x,right:W-this.width-x,bottom:j-this.height-w})}else{let w=[0,0],x=0;$<0?(w[0]=Math.floor(-$),w[1]=j-this.height-w[0]):x=Math.floor($);let O=[0,0],ae=0;q<0?(O[0]=Math.floor(-q),O[1]=W-this.width-O[0]):ae=Math.floor(q),S=S.extend({top:w[0],bottom:w[1],left:O[0],right:O[1]}).extract({left:ae,top:x,width:W,height:j})}return await M(S)}}async toBlob(W="image/png",j=1){if(!y)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:W,quality:j})}toTensor(W="CHW"){let j=new Y.Tensor("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(W!=="HWC")if(W==="CHW")j=j.permute(2,0,1);else throw new Error(`Unsupported channel format: ${W}`);return j}toCanvas(){if(!y)throw new Error("toCanvas() is only supported in browser environments.");const W=this.clone().rgba(),j=g(W.width,W.height),q=new v(W.data,W.width,W.height);return j.getContext("2d").putImageData(q,0,0),j}split(){const{data:W,width:j,height:q,channels:$}=this,S=W.constructor,w=W.length/$,x=Array.from({length:$},()=>new S(w));for(let O=0;Onew K(O,j,q,1))}_update(W,j,q,$=null){return this.data=W,this.width=j,this.height=q,$!==null&&(this.channels=$),this}clone(){return new K(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(y){if(U.apis.IS_WEBWORKER_ENV)throw new Error("Unable to save an image from a Web Worker.");const j=W.split(".").pop().toLowerCase(),q=I.get(j)??"image/png",$=await this.toBlob(q);(0,f.saveBlob)(W,$)}else{if(U.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(y)throw new Error("toSharp() is only supported in server-side environments.");return R(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}}const te=K.read.bind(K)},"./src/utils/maths.js":(De,A,r)=>{r.r(A),r.d(A,{FFT:()=>te,bankers_round:()=>j,cos_sim:()=>g,dot:()=>R,dynamic_time_warping:()=>q,interpolate_data:()=>f,log_softmax:()=>Y,magnitude:()=>v,max:()=>y,medianFilter:()=>ne,min:()=>M,permute_data:()=>D,round:()=>W,softmax:()=>U});function f($,[S,w,x],[O,ae],oe="bilinear",ve=!1){const we=ae/x,re=O/w,xe=new $.constructor(O*ae*S),ce=w*x,ke=O*ae;for(let Ie=0;Ie=0;--ve)O[ve]=we,x[ve]=S[w[ve]],we*=x[ve];const ae=w.map((ve,we)=>O[w.indexOf(we)]),oe=new $.constructor($.length);for(let ve=0;ve<$.length;++ve){let we=0;for(let re=S.length-1,xe=ve;re>=0;--re)we+=xe%S[re]*ae[re],xe=Math.floor(xe/S[re]);oe[we]=$[ve]}return[oe,x]}function U($){const S=y($)[0],w=$.map(ae=>Math.exp(ae-S)),x=w.reduce((ae,oe)=>ae+oe,0);return w.map(ae=>ae/x)}function Y($){const S=y($)[0];let w=0;for(let ae=0;ae<$.length;++ae)w+=Math.exp($[ae]-S);const x=Math.log(w);return $.map(ae=>ae-S-x)}function R($,S){let w=0;for(let x=0;x<$.length;++x)w+=$[x]*S[x];return w}function g($,S){const w=R($,S),x=v($),O=v(S);return w/(x*O)}function v($){return Math.sqrt($.reduce((S,w)=>S+w*w,0))}function M($){if($.length===0)throw Error("Array must not be empty");let S=$[0],w=0;for(let x=1;x<$.length;++x)$[x]S&&(S=$[x],w=x);return[S,w]}function b($){return $>0&&($&$-1)===0}class I{constructor(S){if(this.size=S|0,this.size<=1||!b(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=S<<1,this.table=new Float64Array(this.size*2);for(let x=0;xx;x<<=1)++w;this._width=w%2===0?w-1:w,this._bitrev=new Int32Array(1<>>O&3)<>>1);for(let O=0;O>>1]=S[O];return x}toComplexArray(S,w){const x=w||this.createComplexArray();for(let O=0;O>>1],x[O+1]=0;return x}transform(S,w){if(S===w)throw new Error("Input and output buffers must be different");this._transform4(S,w,1)}realTransform(S,w){if(S===w)throw new Error("Input and output buffers must be different");this._realTransform4(S,w,1)}inverseTransform(S,w){if(S===w)throw new Error("Input and output buffers must be different");this._transform4(S,w,-1);for(let x=0;x>=2;oe>=2;oe>>=2){ve=O/oe<<1;const ke=ve>>>2;for(we=0;we>>1,oe>>>1)}else for(we=0,re=0;we>>1,oe>>>1,x)}const ce=this.table;for(oe>>=2;oe>=2;oe>>=2){ve=O/oe<<1;const Ie=ve>>>1,Ee=Ie>>>1,tt=Ee>>>1;for(we=0;we>>1;for(let Ie=2;Ie>1;++xe){const ce=(xe+1-S)**2/2,ke=Math.sqrt(we**2+re**2)**ce,Ie=ce*Math.atan2(re,we),Ee=2*xe;ae[Ee]=ke*Math.cos(Ie),ae[Ee+1]=ke*Math.sin(Ie),oe[Ee]=ae[Ee],oe[Ee+1]=-ae[Ee+1]}this._slicedChirpBuffer=ae.subarray(w,x),this._f=new I(O>>1),this._f.transform(this._chirpBuffer,oe)}_transform(S,w,x){const O=this._buffer1,ae=this._buffer2,oe=this._outBuffer1,ve=this._outBuffer2,we=this._chirpBuffer,re=this._slicedChirpBuffer,xe=this._a;if(x)for(let ce=0;ce>1,Ee=w[Ie];O[ce]=Ee*re[ce],O[ke]=Ee*re[ke]}else for(let ce=0;ce=$.length&&(we=2*($.length-1)-we),x[oe++]=$[we]}x.sort(),w[ae]=x[O]}return w}function W($,S){const w=Math.pow(10,S);return Math.round($*w)/w}function j($){const S=Math.round($);return Math.abs($)%1===.5?S%2===0?S:S-1:S}function q($){const S=$.length,w=$[0].length,x=[S+1,w+1],O=Array.from({length:x[0]},()=>Array(x[1]).fill(1/0));O[0][0]=0;const ae=Array.from({length:x[0]},()=>Array(x[1]).fill(-1));for(let xe=1;xe0||ve>0;)switch(we.push(oe-1),re.push(ve-1),ae[oe][ve]){case 0:--oe,--ve;break;case 1:--oe;break;case 2:--ve;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${oe}, ${ve}]. Please file a bug report.`)}return we.reverse(),re.reverse(),[we,re]}},"./src/utils/tensor.js":(De,A,r)=>{r.r(A),r.d(A,{Tensor:()=>R,cat:()=>w,full:()=>re,full_like:()=>xe,interpolate:()=>M,interpolate_4d:()=>y,layer_norm:()=>j,matmul:()=>b,mean:()=>oe,mean_pooling:()=>W,ones:()=>ce,ones_like:()=>ke,permute:()=>v,quantize_embeddings:()=>Ge,rand:()=>tt,rfft:()=>I,slice:()=>ne,stack:()=>x,std_mean:()=>ae,topk:()=>K,zeros:()=>Ie,zeros_like:()=>Ee});var f=r("./src/utils/maths.js"),D=r("./src/backends/onnx.js"),U=r("./src/ops/registry.js");const Y=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,uint4:Uint8Array,int4:Int8Array});class R{constructor(...J){_e(this,"ort_tensor");return(0,D.isONNXTensor)(J[0])?this.ort_tensor=J[0]:this.ort_tensor=new D.Tensor(J[0],J[1],J[2]),new Proxy(this,{get:(de,Ce)=>{if(typeof Ce=="string"){let Be=Number(Ce);if(Number.isInteger(Be))return de._getitem(Be)}return de[Ce]},set:(de,Ce,Be)=>de[Ce]=Be})}get dims(){return this.ort_tensor.dims}set dims(J){this.ort_tensor.dims=J}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[J,...de]=this.dims;if(de.length>0){const Ce=de.reduce((Be,Ze)=>Be*Ze);for(let Be=0;Be0){const Be=Ce.reduce((Ze,se)=>Ze*se);return this._subarray(J,Be,Ce)}else return new R(this.type,[this.data[J]],Ce)}indexOf(J){const de=this.data;for(let Ce=0;CeVe)throw new Error(`Invalid slice: ${Te}`);const Ne=[Math.max(Ue,0),Math.min(Ve,this.dims[le])];Ce.push(Ne),de.push(Ne[1]-Ne[0])}else throw new Error(`Invalid slice: ${Te}`)}const Be=Ce.map(([le,Te])=>Te-le),Ze=Be.reduce((le,Te)=>le*Te),se=this.data,Ke=new se.constructor(Ze),je=this.stride();for(let le=0;le=0;--Ue){const Ne=Be[Ue];Te+=(Ve%Ne+Ce[Ue][0])*je[Ue],Ve=Math.floor(Ve/Ne)}Ke[le]=se[Te]}return new R(this.type,Ke,de)}permute(...J){return v(this,J)}transpose(...J){return this.permute(...J)}sum(J=null,de=!1){return this.norm(1,J,de)}norm(J="fro",de=null,Ce=!1){if(J==="fro")J=2;else if(typeof J=="string")throw Error(`Unsupported norm: ${J}`);const Be=this.data,Ze=(le,Te)=>le+Te**J;if(de===null){const le=Be.reduce(Ze,0)**(1/J);return new R(this.type,[le],[])}const[se,Ke,je]=O(Ze,this,de,Ce);if(J!==1)for(let le=0;le=0;--je){const Ue=this.dims[je];if(je!==de){const Ve=le%Ue;Ke+=Ve*Te,Te*=this.dims[je]}le=Math.floor(le/Ue)}Be[se]/=Ze[Ke]}return this}normalize(J=2,de=1){return this.clone().normalize_(J,de)}stride(){return ve(this.dims)}squeeze(J=null){return new R(this.type,this.data,q(this.dims,J))}squeeze_(J=null){return this.dims=q(this.dims,J),this}unsqueeze(J=null){return new R(this.type,this.data,$(this.dims,J))}unsqueeze_(J=null){return this.dims=$(this.dims,J),this}flatten_(J=0,de=-1){de=(de+this.dims.length)%this.dims.length;let Ce=this.dims.slice(0,J),Be=this.dims.slice(J,de+1),Ze=this.dims.slice(de+1);return this.dims=[...Ce,Be.reduce((se,Ke)=>se*Ke,1),...Ze],this}flatten(J=0,de=-1){return this.clone().flatten_(J,de)}view(...J){let de=-1;for(let Be=0;BeKe!==de?Ze*se:Ze,1);J[de]=Ce.length/Be}return new R(this.type,Ce,J)}neg_(){const J=this.data;for(let de=0;deJ?1:0;return new R("bool",de,this.dims)}lt(J){const de=new Uint8Array(this.data.length),Ce=this.data;for(let Be=0;BeMath.min(se,Ke),this,J,de,1/0);return new R(Ce,Be,Ze)}max(J=null,de=!1){if(J===null){const se=(0,f.max)(this.data)[0];return new R(this.type,[se],[])}const[Ce,Be,Ze]=O((se,Ke)=>Math.max(se,Ke),this,J,de,-1/0);return new R(Ce,Be,Ze)}argmin(J=null,de=!1){if(J!==null)throw new Error("`dim !== null` not yet implemented.");const Ce=(0,f.min)(this.data)[1];return new R("int64",[BigInt(Ce)],[])}argmax(J=null,de=!1){if(J!==null)throw new Error("`dim !== null` not yet implemented.");const Ce=(0,f.max)(this.data)[1];return new R("int64",[BigInt(Ce)],[])}to(J){if(this.type===J)return this;if(!Y.hasOwnProperty(J))throw new Error(`Unsupported type: ${J}`);let de;const Ce=["int64","uint64"].includes(this.type),Be=["int64","uint64"].includes(J);return Ce&&!Be?de=Number:!Ce&&Be&&(de=BigInt),new R(J,Y[J].from(this.data,de),this.dims)}}function g(ye,J){const de=ye.length,Ce=J.reduce((Ze,se)=>Ze*se);if(de!==Ce)throw Error(`cannot reshape array of size ${de} into shape (${J})`);let Be=ye;for(let Ze=J.length-1;Ze>=0;Ze--)Be=Be.reduce((se,Ke)=>{let je=se[se.length-1];return je.lengthnew R("int64",ye,[ye.length]);async function ne(ye,J,de,Ce,Be){return await(await U.TensorOpRegistry.slice)({x:ye,s:te(J),e:te(de),a:te(Ce),t:te(Be??new Array(Ce.length).fill(1))})}function W(ye,J){const de=ye.data,Ce=J.data,Be=[ye.dims[0],ye.dims[2]],Ze=new de.constructor(Be[0]*Be[1]),[se,Ke,je]=ye.dims;let le=0;for(let Te=0;Tede!==1):typeof J=="number"?ye[J]===1&&ye.splice(J,1):Array.isArray(J)&&(ye=ye.filter((de,Ce)=>de!==1||!J.includes(Ce))),ye}function $(ye,J){return J=S(J,ye.length+1),ye=ye.slice(),ye.splice(J,0,1),ye}function S(ye,J,de=null,Ce=!0){if(Ce&&(ye<-J||ye>=J))throw new Error(`IndexError: index ${ye} is out of bounds for dimension${de===null?"":" "+de} with size ${J}`);return ye<0&&(ye=(ye%J+J)%J),ye}function w(ye,J=0){J=S(J,ye[0].dims.length);const de=ye[0].dims.slice();de[J]=ye.reduce((se,Ke)=>se+Ke.dims[J],0);const Ce=de.reduce((se,Ke)=>se*Ke,1),Be=new ye[0].data.constructor(Ce),Ze=ye[0].type;if(J===0){let se=0;for(const Ke of ye){const je=Ke.data;Be.set(je,se),se+=je.length}}else{let se=0;for(let Ke=0;Ke=0;--Ve){const st=le[Ve];let dt=Ne%st;Ve===J&&(dt+=se),Ue+=dt*Re,Re*=de[Ve],Ne=Math.floor(Ne/st)}Be[Ue]=je[Te]}se+=le[J]}}return new R(Ze,Be,de)}function x(ye,J=0){return w(ye.map(de=>de.unsqueeze(J)),J)}function O(ye,J,de=null,Ce=!1,Be=null){const Ze=J.data,se=J.dims;de=S(de,se.length);const Ke=se.slice();Ke[de]=1;const je=new Ze.constructor(Ze.length/se[de]);Be!==null&&je.fill(Be);for(let le=0;le=0;--Ue){const Re=se[Ue];if(Ue!==de){const st=Ve%Re;Te+=st*Ne,Ne*=Ke[Ue]}Ve=Math.floor(Ve/Re)}je[Te]=ye(je[Te],Ze[le],le,Te)}return Ce||Ke.splice(de,1),[J.type,je,Ke]}function ae(ye,J=null,de=1,Ce=!1){const Be=ye.data,Ze=ye.dims;if(J===null){const Ne=Be.reduce((ct,lt)=>ct+lt,0)/Be.length,Re=Math.sqrt(Be.reduce((ct,lt)=>ct+(lt-Ne)**2,0)/(Be.length-de)),st=new R(ye.type,[Ne],[]);return[new R(ye.type,[Re],[]),st]}J=S(J,Ze.length);const se=oe(ye,J,Ce),Ke=se.data,[je,le,Te]=O((Ve,Ne,Re,st)=>Ve+(Ne-Ke[st])**2,ye,J,Ce);for(let Ve=0;Vele+Te,0);return new R(ye.type,[je/Be.length],[])}J=S(J,Ce.length);const[Ze,se,Ke]=O((je,le)=>je+le,ye,J,de);if(Ce[J]!==1)for(let je=0;je=0;--de)J[de]=Ce,Ce*=ye[de];return J}function we(ye,J,de,Ce){const Be=ye.reduce((Ze,se)=>Ze*se,1);return new R(de,new Ce(Be).fill(J),ye)}function re(ye,J){let de,Ce;if(typeof J=="number")de="float32",Ce=Float32Array;else if(typeof J=="bigint")de="int64",Ce=BigInt64Array;else if(typeof J=="boolean")de="bool",Ce=Uint8Array;else throw new Error(`Unsupported data type: ${typeof J}`);return we(ye,J,de,Ce)}function xe(ye,J){return re(ye.dims,J)}function ce(ye){return we(ye,1n,"int64",BigInt64Array)}function ke(ye){return ce(ye.dims)}function Ie(ye){return we(ye,0n,"int64",BigInt64Array)}function Ee(ye){return Ie(ye.dims)}function tt(ye){const J=ye.reduce((de,Ce)=>de*Ce,1);return new R("float32",Float32Array.from({length:J},()=>Math.random()),ye)}function Ge(ye,J){if(ye.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(ye.dims.at(-1)%8!==0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(J))throw new Error("The precision must be either 'binary' or 'ubinary'");const de=J==="binary",Ce=de?"int8":"uint8",Be=de?Int8Array:Uint8Array,Ze=ye.data,se=new Be(Ze.length/8);for(let Ke=0;Ke0?1:0,le=Math.floor(Ke/8),Te=Ke%8;se[le]|=je<<7-Te,de&&Te===0&&(se[le]-=128)}return new R(Ce,se,[ye.dims[0],ye.dims[1]/8])}}},no={};function gs(De){var A=no[De];if(A!==void 0)return A.exports;var r=no[De]={exports:{}};return Xr[De](r,r.exports,gs),r.exports}gs.m=Xr,(()=>{var De=Object.getPrototypeOf?r=>Object.getPrototypeOf(r):r=>r.__proto__,A;gs.t=function(r,f){if(f&1&&(r=this(r)),f&8||typeof r=="object"&&r&&(f&4&&r.__esModule||f&16&&typeof r.then=="function"))return r;var D=Object.create(null);gs.r(D);var U={};A=A||[null,De({}),De([]),De(De)];for(var Y=f&2&&r;typeof Y=="object"&&!~A.indexOf(Y);Y=De(Y))Object.getOwnPropertyNames(Y).forEach(R=>U[R]=()=>r[R]);return U.default=()=>r,gs.d(D,U),D}})(),gs.d=(De,A)=>{for(var r in A)gs.o(A,r)&&!gs.o(De,r)&&Object.defineProperty(De,r,{enumerable:!0,get:A[r]})},gs.o=(De,A)=>Object.prototype.hasOwnProperty.call(De,A),gs.r=De=>{typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(De,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(De,"__esModule",{value:!0})},(()=>{var De;if(typeof self.location.href=="string"&&(De=self.location.href),!De)throw new Error("Automatic publicPath is not supported in this browser");De=De.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),gs.p=De})(),gs.b=new URL(self.location.href);var c={};(()=>{/*!*****************************!*\ - !*** ./src/transformers.js ***! - \*****************************/gs.r(c),gs.d(c,{ASTFeatureExtractor:()=>M.ASTFeatureExtractor,ASTForAudioClassification:()=>r.ASTForAudioClassification,ASTModel:()=>r.ASTModel,ASTPreTrainedModel:()=>r.ASTPreTrainedModel,AlbertForMaskedLM:()=>r.AlbertForMaskedLM,AlbertForQuestionAnswering:()=>r.AlbertForQuestionAnswering,AlbertForSequenceClassification:()=>r.AlbertForSequenceClassification,AlbertModel:()=>r.AlbertModel,AlbertPreTrainedModel:()=>r.AlbertPreTrainedModel,AlbertTokenizer:()=>f.AlbertTokenizer,AudioClassificationPipeline:()=>A.AudioClassificationPipeline,AutoConfig:()=>D.AutoConfig,AutoFeatureExtractor:()=>y.AutoFeatureExtractor,AutoImageProcessor:()=>K.AutoImageProcessor,AutoModel:()=>r.AutoModel,AutoModelForAudioClassification:()=>r.AutoModelForAudioClassification,AutoModelForAudioFrameClassification:()=>r.AutoModelForAudioFrameClassification,AutoModelForCTC:()=>r.AutoModelForCTC,AutoModelForCausalLM:()=>r.AutoModelForCausalLM,AutoModelForDepthEstimation:()=>r.AutoModelForDepthEstimation,AutoModelForDocumentQuestionAnswering:()=>r.AutoModelForDocumentQuestionAnswering,AutoModelForImageClassification:()=>r.AutoModelForImageClassification,AutoModelForImageFeatureExtraction:()=>r.AutoModelForImageFeatureExtraction,AutoModelForImageMatting:()=>r.AutoModelForImageMatting,AutoModelForImageSegmentation:()=>r.AutoModelForImageSegmentation,AutoModelForImageToImage:()=>r.AutoModelForImageToImage,AutoModelForMaskGeneration:()=>r.AutoModelForMaskGeneration,AutoModelForMaskedLM:()=>r.AutoModelForMaskedLM,AutoModelForNormalEstimation:()=>r.AutoModelForNormalEstimation,AutoModelForObjectDetection:()=>r.AutoModelForObjectDetection,AutoModelForPoseEstimation:()=>r.AutoModelForPoseEstimation,AutoModelForQuestionAnswering:()=>r.AutoModelForQuestionAnswering,AutoModelForSemanticSegmentation:()=>r.AutoModelForSemanticSegmentation,AutoModelForSeq2SeqLM:()=>r.AutoModelForSeq2SeqLM,AutoModelForSequenceClassification:()=>r.AutoModelForSequenceClassification,AutoModelForSpeechSeq2Seq:()=>r.AutoModelForSpeechSeq2Seq,AutoModelForTextToSpectrogram:()=>r.AutoModelForTextToSpectrogram,AutoModelForTextToWaveform:()=>r.AutoModelForTextToWaveform,AutoModelForTokenClassification:()=>r.AutoModelForTokenClassification,AutoModelForUniversalSegmentation:()=>r.AutoModelForUniversalSegmentation,AutoModelForVision2Seq:()=>r.AutoModelForVision2Seq,AutoModelForXVector:()=>r.AutoModelForXVector,AutoModelForZeroShotObjectDetection:()=>r.AutoModelForZeroShotObjectDetection,AutoProcessor:()=>W.AutoProcessor,AutoTokenizer:()=>f.AutoTokenizer,AutomaticSpeechRecognitionPipeline:()=>A.AutomaticSpeechRecognitionPipeline,BartForConditionalGeneration:()=>r.BartForConditionalGeneration,BartForSequenceClassification:()=>r.BartForSequenceClassification,BartModel:()=>r.BartModel,BartPretrainedModel:()=>r.BartPretrainedModel,BartTokenizer:()=>f.BartTokenizer,BaseModelOutput:()=>r.BaseModelOutput,BaseStreamer:()=>j.BaseStreamer,BeitFeatureExtractor:()=>I.BeitFeatureExtractor,BeitForImageClassification:()=>r.BeitForImageClassification,BeitModel:()=>r.BeitModel,BeitPreTrainedModel:()=>r.BeitPreTrainedModel,BertForMaskedLM:()=>r.BertForMaskedLM,BertForQuestionAnswering:()=>r.BertForQuestionAnswering,BertForSequenceClassification:()=>r.BertForSequenceClassification,BertForTokenClassification:()=>r.BertForTokenClassification,BertModel:()=>r.BertModel,BertPreTrainedModel:()=>r.BertPreTrainedModel,BertTokenizer:()=>f.BertTokenizer,BitImageProcessor:()=>I.BitImageProcessor,BlenderbotForConditionalGeneration:()=>r.BlenderbotForConditionalGeneration,BlenderbotModel:()=>r.BlenderbotModel,BlenderbotPreTrainedModel:()=>r.BlenderbotPreTrainedModel,BlenderbotSmallForConditionalGeneration:()=>r.BlenderbotSmallForConditionalGeneration,BlenderbotSmallModel:()=>r.BlenderbotSmallModel,BlenderbotSmallPreTrainedModel:()=>r.BlenderbotSmallPreTrainedModel,BlenderbotSmallTokenizer:()=>f.BlenderbotSmallTokenizer,BlenderbotTokenizer:()=>f.BlenderbotTokenizer,BloomForCausalLM:()=>r.BloomForCausalLM,BloomModel:()=>r.BloomModel,BloomPreTrainedModel:()=>r.BloomPreTrainedModel,BloomTokenizer:()=>f.BloomTokenizer,CLIPFeatureExtractor:()=>I.CLIPFeatureExtractor,CLIPImageProcessor:()=>I.CLIPImageProcessor,CLIPModel:()=>r.CLIPModel,CLIPPreTrainedModel:()=>r.CLIPPreTrainedModel,CLIPSegForImageSegmentation:()=>r.CLIPSegForImageSegmentation,CLIPSegModel:()=>r.CLIPSegModel,CLIPSegPreTrainedModel:()=>r.CLIPSegPreTrainedModel,CLIPTextModel:()=>r.CLIPTextModel,CLIPTextModelWithProjection:()=>r.CLIPTextModelWithProjection,CLIPTokenizer:()=>f.CLIPTokenizer,CLIPVisionModel:()=>r.CLIPVisionModel,CLIPVisionModelWithProjection:()=>r.CLIPVisionModelWithProjection,CamembertForMaskedLM:()=>r.CamembertForMaskedLM,CamembertForQuestionAnswering:()=>r.CamembertForQuestionAnswering,CamembertForSequenceClassification:()=>r.CamembertForSequenceClassification,CamembertForTokenClassification:()=>r.CamembertForTokenClassification,CamembertModel:()=>r.CamembertModel,CamembertPreTrainedModel:()=>r.CamembertPreTrainedModel,CamembertTokenizer:()=>f.CamembertTokenizer,CausalLMOutput:()=>r.CausalLMOutput,CausalLMOutputWithPast:()=>r.CausalLMOutputWithPast,ChineseCLIPFeatureExtractor:()=>I.ChineseCLIPFeatureExtractor,ChineseCLIPModel:()=>r.ChineseCLIPModel,ChineseCLIPPreTrainedModel:()=>r.ChineseCLIPPreTrainedModel,ClapAudioModelWithProjection:()=>r.ClapAudioModelWithProjection,ClapFeatureExtractor:()=>M.ClapFeatureExtractor,ClapModel:()=>r.ClapModel,ClapPreTrainedModel:()=>r.ClapPreTrainedModel,ClapTextModelWithProjection:()=>r.ClapTextModelWithProjection,ClassifierFreeGuidanceLogitsProcessor:()=>$.ClassifierFreeGuidanceLogitsProcessor,CodeGenForCausalLM:()=>r.CodeGenForCausalLM,CodeGenModel:()=>r.CodeGenModel,CodeGenPreTrainedModel:()=>r.CodeGenPreTrainedModel,CodeGenTokenizer:()=>f.CodeGenTokenizer,CodeLlamaTokenizer:()=>f.CodeLlamaTokenizer,CohereForCausalLM:()=>r.CohereForCausalLM,CohereModel:()=>r.CohereModel,CoherePreTrainedModel:()=>r.CoherePreTrainedModel,CohereTokenizer:()=>f.CohereTokenizer,ConvBertForMaskedLM:()=>r.ConvBertForMaskedLM,ConvBertForQuestionAnswering:()=>r.ConvBertForQuestionAnswering,ConvBertForSequenceClassification:()=>r.ConvBertForSequenceClassification,ConvBertForTokenClassification:()=>r.ConvBertForTokenClassification,ConvBertModel:()=>r.ConvBertModel,ConvBertPreTrainedModel:()=>r.ConvBertPreTrainedModel,ConvBertTokenizer:()=>f.ConvBertTokenizer,ConvNextFeatureExtractor:()=>I.ConvNextFeatureExtractor,ConvNextForImageClassification:()=>r.ConvNextForImageClassification,ConvNextImageProcessor:()=>I.ConvNextImageProcessor,ConvNextModel:()=>r.ConvNextModel,ConvNextPreTrainedModel:()=>r.ConvNextPreTrainedModel,ConvNextV2ForImageClassification:()=>r.ConvNextV2ForImageClassification,ConvNextV2Model:()=>r.ConvNextV2Model,ConvNextV2PreTrainedModel:()=>r.ConvNextV2PreTrainedModel,DPTFeatureExtractor:()=>I.DPTFeatureExtractor,DPTForDepthEstimation:()=>r.DPTForDepthEstimation,DPTImageProcessor:()=>I.DPTImageProcessor,DPTModel:()=>r.DPTModel,DPTPreTrainedModel:()=>r.DPTPreTrainedModel,DebertaForMaskedLM:()=>r.DebertaForMaskedLM,DebertaForQuestionAnswering:()=>r.DebertaForQuestionAnswering,DebertaForSequenceClassification:()=>r.DebertaForSequenceClassification,DebertaForTokenClassification:()=>r.DebertaForTokenClassification,DebertaModel:()=>r.DebertaModel,DebertaPreTrainedModel:()=>r.DebertaPreTrainedModel,DebertaTokenizer:()=>f.DebertaTokenizer,DebertaV2ForMaskedLM:()=>r.DebertaV2ForMaskedLM,DebertaV2ForQuestionAnswering:()=>r.DebertaV2ForQuestionAnswering,DebertaV2ForSequenceClassification:()=>r.DebertaV2ForSequenceClassification,DebertaV2ForTokenClassification:()=>r.DebertaV2ForTokenClassification,DebertaV2Model:()=>r.DebertaV2Model,DebertaV2PreTrainedModel:()=>r.DebertaV2PreTrainedModel,DebertaV2Tokenizer:()=>f.DebertaV2Tokenizer,DecisionTransformerModel:()=>r.DecisionTransformerModel,DecisionTransformerPreTrainedModel:()=>r.DecisionTransformerPreTrainedModel,DeiTFeatureExtractor:()=>I.DeiTFeatureExtractor,DeiTForImageClassification:()=>r.DeiTForImageClassification,DeiTImageProcessor:()=>I.DeiTImageProcessor,DeiTModel:()=>r.DeiTModel,DeiTPreTrainedModel:()=>r.DeiTPreTrainedModel,DepthAnythingForDepthEstimation:()=>r.DepthAnythingForDepthEstimation,DepthAnythingPreTrainedModel:()=>r.DepthAnythingPreTrainedModel,DepthEstimationPipeline:()=>A.DepthEstimationPipeline,DepthProForDepthEstimation:()=>r.DepthProForDepthEstimation,DepthProPreTrainedModel:()=>r.DepthProPreTrainedModel,DetrFeatureExtractor:()=>I.DetrFeatureExtractor,DetrForObjectDetection:()=>r.DetrForObjectDetection,DetrForSegmentation:()=>r.DetrForSegmentation,DetrImageProcessor:()=>I.DetrImageProcessor,DetrModel:()=>r.DetrModel,DetrObjectDetectionOutput:()=>r.DetrObjectDetectionOutput,DetrPreTrainedModel:()=>r.DetrPreTrainedModel,DetrSegmentationOutput:()=>r.DetrSegmentationOutput,Dinov2ForImageClassification:()=>r.Dinov2ForImageClassification,Dinov2Model:()=>r.Dinov2Model,Dinov2PreTrainedModel:()=>r.Dinov2PreTrainedModel,Dinov2WithRegistersForImageClassification:()=>r.Dinov2WithRegistersForImageClassification,Dinov2WithRegistersModel:()=>r.Dinov2WithRegistersModel,Dinov2WithRegistersPreTrainedModel:()=>r.Dinov2WithRegistersPreTrainedModel,DistilBertForMaskedLM:()=>r.DistilBertForMaskedLM,DistilBertForQuestionAnswering:()=>r.DistilBertForQuestionAnswering,DistilBertForSequenceClassification:()=>r.DistilBertForSequenceClassification,DistilBertForTokenClassification:()=>r.DistilBertForTokenClassification,DistilBertModel:()=>r.DistilBertModel,DistilBertPreTrainedModel:()=>r.DistilBertPreTrainedModel,DistilBertTokenizer:()=>f.DistilBertTokenizer,DocumentQuestionAnsweringPipeline:()=>A.DocumentQuestionAnsweringPipeline,DonutFeatureExtractor:()=>I.DonutFeatureExtractor,DonutImageProcessor:()=>I.DonutImageProcessor,DonutSwinModel:()=>r.DonutSwinModel,DonutSwinPreTrainedModel:()=>r.DonutSwinPreTrainedModel,EfficientNetForImageClassification:()=>r.EfficientNetForImageClassification,EfficientNetImageProcessor:()=>I.EfficientNetImageProcessor,EfficientNetModel:()=>r.EfficientNetModel,EfficientNetPreTrainedModel:()=>r.EfficientNetPreTrainedModel,ElectraForMaskedLM:()=>r.ElectraForMaskedLM,ElectraForQuestionAnswering:()=>r.ElectraForQuestionAnswering,ElectraForSequenceClassification:()=>r.ElectraForSequenceClassification,ElectraForTokenClassification:()=>r.ElectraForTokenClassification,ElectraModel:()=>r.ElectraModel,ElectraPreTrainedModel:()=>r.ElectraPreTrainedModel,ElectraTokenizer:()=>f.ElectraTokenizer,EosTokenCriteria:()=>q.EosTokenCriteria,EsmForMaskedLM:()=>r.EsmForMaskedLM,EsmForSequenceClassification:()=>r.EsmForSequenceClassification,EsmForTokenClassification:()=>r.EsmForTokenClassification,EsmModel:()=>r.EsmModel,EsmPreTrainedModel:()=>r.EsmPreTrainedModel,EsmTokenizer:()=>f.EsmTokenizer,ExaoneForCausalLM:()=>r.ExaoneForCausalLM,ExaoneModel:()=>r.ExaoneModel,ExaonePreTrainedModel:()=>r.ExaonePreTrainedModel,FFT:()=>g.FFT,FalconForCausalLM:()=>r.FalconForCausalLM,FalconModel:()=>r.FalconModel,FalconPreTrainedModel:()=>r.FalconPreTrainedModel,FalconTokenizer:()=>f.FalconTokenizer,FastViTForImageClassification:()=>r.FastViTForImageClassification,FastViTModel:()=>r.FastViTModel,FastViTPreTrainedModel:()=>r.FastViTPreTrainedModel,FeatureExtractionPipeline:()=>A.FeatureExtractionPipeline,FeatureExtractor:()=>v.FeatureExtractor,FillMaskPipeline:()=>A.FillMaskPipeline,Florence2ForConditionalGeneration:()=>r.Florence2ForConditionalGeneration,Florence2PreTrainedModel:()=>r.Florence2PreTrainedModel,Florence2Processor:()=>ne.Florence2Processor,ForcedBOSTokenLogitsProcessor:()=>$.ForcedBOSTokenLogitsProcessor,ForcedEOSTokenLogitsProcessor:()=>$.ForcedEOSTokenLogitsProcessor,GLPNFeatureExtractor:()=>I.GLPNFeatureExtractor,GLPNForDepthEstimation:()=>r.GLPNForDepthEstimation,GLPNModel:()=>r.GLPNModel,GLPNPreTrainedModel:()=>r.GLPNPreTrainedModel,GPT2LMHeadModel:()=>r.GPT2LMHeadModel,GPT2Model:()=>r.GPT2Model,GPT2PreTrainedModel:()=>r.GPT2PreTrainedModel,GPT2Tokenizer:()=>f.GPT2Tokenizer,GPTBigCodeForCausalLM:()=>r.GPTBigCodeForCausalLM,GPTBigCodeModel:()=>r.GPTBigCodeModel,GPTBigCodePreTrainedModel:()=>r.GPTBigCodePreTrainedModel,GPTJForCausalLM:()=>r.GPTJForCausalLM,GPTJModel:()=>r.GPTJModel,GPTJPreTrainedModel:()=>r.GPTJPreTrainedModel,GPTNeoForCausalLM:()=>r.GPTNeoForCausalLM,GPTNeoModel:()=>r.GPTNeoModel,GPTNeoPreTrainedModel:()=>r.GPTNeoPreTrainedModel,GPTNeoXForCausalLM:()=>r.GPTNeoXForCausalLM,GPTNeoXModel:()=>r.GPTNeoXModel,GPTNeoXPreTrainedModel:()=>r.GPTNeoXPreTrainedModel,GPTNeoXTokenizer:()=>f.GPTNeoXTokenizer,Gemma2ForCausalLM:()=>r.Gemma2ForCausalLM,Gemma2Model:()=>r.Gemma2Model,Gemma2PreTrainedModel:()=>r.Gemma2PreTrainedModel,GemmaForCausalLM:()=>r.GemmaForCausalLM,GemmaModel:()=>r.GemmaModel,GemmaPreTrainedModel:()=>r.GemmaPreTrainedModel,GemmaTokenizer:()=>f.GemmaTokenizer,GlmForCausalLM:()=>r.GlmForCausalLM,GlmModel:()=>r.GlmModel,GlmPreTrainedModel:()=>r.GlmPreTrainedModel,GraniteForCausalLM:()=>r.GraniteForCausalLM,GraniteModel:()=>r.GraniteModel,GranitePreTrainedModel:()=>r.GranitePreTrainedModel,Grok1Tokenizer:()=>f.Grok1Tokenizer,GroundingDinoForObjectDetection:()=>r.GroundingDinoForObjectDetection,GroundingDinoImageProcessor:()=>I.GroundingDinoImageProcessor,GroundingDinoPreTrainedModel:()=>r.GroundingDinoPreTrainedModel,GroundingDinoProcessor:()=>ne.GroundingDinoProcessor,GroupViTModel:()=>r.GroupViTModel,GroupViTPreTrainedModel:()=>r.GroupViTPreTrainedModel,HeliumForCausalLM:()=>r.HeliumForCausalLM,HeliumModel:()=>r.HeliumModel,HeliumPreTrainedModel:()=>r.HeliumPreTrainedModel,HerbertTokenizer:()=>f.HerbertTokenizer,HieraForImageClassification:()=>r.HieraForImageClassification,HieraModel:()=>r.HieraModel,HieraPreTrainedModel:()=>r.HieraPreTrainedModel,HubertForCTC:()=>r.HubertForCTC,HubertForSequenceClassification:()=>r.HubertForSequenceClassification,HubertModel:()=>r.HubertModel,HubertPreTrainedModel:()=>r.HubertPreTrainedModel,IJepaForImageClassification:()=>r.IJepaForImageClassification,IJepaModel:()=>r.IJepaModel,IJepaPreTrainedModel:()=>r.IJepaPreTrainedModel,Idefics3ForConditionalGeneration:()=>r.Idefics3ForConditionalGeneration,Idefics3ImageProcessor:()=>I.Idefics3ImageProcessor,Idefics3PreTrainedModel:()=>r.Idefics3PreTrainedModel,Idefics3Processor:()=>ne.Idefics3Processor,ImageClassificationPipeline:()=>A.ImageClassificationPipeline,ImageFeatureExtractionPipeline:()=>A.ImageFeatureExtractionPipeline,ImageFeatureExtractor:()=>M.ImageFeatureExtractor,ImageMattingOutput:()=>r.ImageMattingOutput,ImageProcessor:()=>b.ImageProcessor,ImageSegmentationPipeline:()=>A.ImageSegmentationPipeline,ImageToImagePipeline:()=>A.ImageToImagePipeline,ImageToTextPipeline:()=>A.ImageToTextPipeline,InterruptableStoppingCriteria:()=>q.InterruptableStoppingCriteria,JAISLMHeadModel:()=>r.JAISLMHeadModel,JAISModel:()=>r.JAISModel,JAISPreTrainedModel:()=>r.JAISPreTrainedModel,JinaCLIPImageProcessor:()=>I.JinaCLIPImageProcessor,JinaCLIPModel:()=>r.JinaCLIPModel,JinaCLIPPreTrainedModel:()=>r.JinaCLIPPreTrainedModel,JinaCLIPProcessor:()=>ne.JinaCLIPProcessor,JinaCLIPTextModel:()=>r.JinaCLIPTextModel,JinaCLIPVisionModel:()=>r.JinaCLIPVisionModel,LlamaForCausalLM:()=>r.LlamaForCausalLM,LlamaModel:()=>r.LlamaModel,LlamaPreTrainedModel:()=>r.LlamaPreTrainedModel,LlamaTokenizer:()=>f.LlamaTokenizer,LlavaForConditionalGeneration:()=>r.LlavaForConditionalGeneration,LlavaOnevisionForConditionalGeneration:()=>r.LlavaOnevisionForConditionalGeneration,LlavaOnevisionImageProcessor:()=>I.LlavaOnevisionImageProcessor,LlavaPreTrainedModel:()=>r.LlavaPreTrainedModel,LogitsProcessor:()=>$.LogitsProcessor,LogitsProcessorList:()=>$.LogitsProcessorList,LogitsWarper:()=>$.LogitsWarper,LongT5ForConditionalGeneration:()=>r.LongT5ForConditionalGeneration,LongT5Model:()=>r.LongT5Model,LongT5PreTrainedModel:()=>r.LongT5PreTrainedModel,M2M100ForConditionalGeneration:()=>r.M2M100ForConditionalGeneration,M2M100Model:()=>r.M2M100Model,M2M100PreTrainedModel:()=>r.M2M100PreTrainedModel,M2M100Tokenizer:()=>f.M2M100Tokenizer,MBart50Tokenizer:()=>f.MBart50Tokenizer,MBartForCausalLM:()=>r.MBartForCausalLM,MBartForConditionalGeneration:()=>r.MBartForConditionalGeneration,MBartForSequenceClassification:()=>r.MBartForSequenceClassification,MBartModel:()=>r.MBartModel,MBartPreTrainedModel:()=>r.MBartPreTrainedModel,MBartTokenizer:()=>f.MBartTokenizer,MPNetForMaskedLM:()=>r.MPNetForMaskedLM,MPNetForQuestionAnswering:()=>r.MPNetForQuestionAnswering,MPNetForSequenceClassification:()=>r.MPNetForSequenceClassification,MPNetForTokenClassification:()=>r.MPNetForTokenClassification,MPNetModel:()=>r.MPNetModel,MPNetPreTrainedModel:()=>r.MPNetPreTrainedModel,MPNetTokenizer:()=>f.MPNetTokenizer,MT5ForConditionalGeneration:()=>r.MT5ForConditionalGeneration,MT5Model:()=>r.MT5Model,MT5PreTrainedModel:()=>r.MT5PreTrainedModel,MarianMTModel:()=>r.MarianMTModel,MarianModel:()=>r.MarianModel,MarianPreTrainedModel:()=>r.MarianPreTrainedModel,MarianTokenizer:()=>f.MarianTokenizer,Mask2FormerImageProcessor:()=>I.Mask2FormerImageProcessor,MaskFormerFeatureExtractor:()=>I.MaskFormerFeatureExtractor,MaskFormerForInstanceSegmentation:()=>r.MaskFormerForInstanceSegmentation,MaskFormerImageProcessor:()=>I.MaskFormerImageProcessor,MaskFormerModel:()=>r.MaskFormerModel,MaskFormerPreTrainedModel:()=>r.MaskFormerPreTrainedModel,MaskedLMOutput:()=>r.MaskedLMOutput,MaxLengthCriteria:()=>q.MaxLengthCriteria,MgpstrForSceneTextRecognition:()=>r.MgpstrForSceneTextRecognition,MgpstrModelOutput:()=>r.MgpstrModelOutput,MgpstrPreTrainedModel:()=>r.MgpstrPreTrainedModel,MgpstrProcessor:()=>ne.MgpstrProcessor,MgpstrTokenizer:()=>f.MgpstrTokenizer,MinLengthLogitsProcessor:()=>$.MinLengthLogitsProcessor,MinNewTokensLengthLogitsProcessor:()=>$.MinNewTokensLengthLogitsProcessor,MistralForCausalLM:()=>r.MistralForCausalLM,MistralModel:()=>r.MistralModel,MistralPreTrainedModel:()=>r.MistralPreTrainedModel,MobileBertForMaskedLM:()=>r.MobileBertForMaskedLM,MobileBertForQuestionAnswering:()=>r.MobileBertForQuestionAnswering,MobileBertForSequenceClassification:()=>r.MobileBertForSequenceClassification,MobileBertModel:()=>r.MobileBertModel,MobileBertPreTrainedModel:()=>r.MobileBertPreTrainedModel,MobileBertTokenizer:()=>f.MobileBertTokenizer,MobileLLMForCausalLM:()=>r.MobileLLMForCausalLM,MobileLLMModel:()=>r.MobileLLMModel,MobileLLMPreTrainedModel:()=>r.MobileLLMPreTrainedModel,MobileNetV1FeatureExtractor:()=>I.MobileNetV1FeatureExtractor,MobileNetV1ForImageClassification:()=>r.MobileNetV1ForImageClassification,MobileNetV1ImageProcessor:()=>I.MobileNetV1ImageProcessor,MobileNetV1Model:()=>r.MobileNetV1Model,MobileNetV1PreTrainedModel:()=>r.MobileNetV1PreTrainedModel,MobileNetV2FeatureExtractor:()=>I.MobileNetV2FeatureExtractor,MobileNetV2ForImageClassification:()=>r.MobileNetV2ForImageClassification,MobileNetV2ImageProcessor:()=>I.MobileNetV2ImageProcessor,MobileNetV2Model:()=>r.MobileNetV2Model,MobileNetV2PreTrainedModel:()=>r.MobileNetV2PreTrainedModel,MobileNetV3FeatureExtractor:()=>I.MobileNetV3FeatureExtractor,MobileNetV3ForImageClassification:()=>r.MobileNetV3ForImageClassification,MobileNetV3ImageProcessor:()=>I.MobileNetV3ImageProcessor,MobileNetV3Model:()=>r.MobileNetV3Model,MobileNetV3PreTrainedModel:()=>r.MobileNetV3PreTrainedModel,MobileNetV4FeatureExtractor:()=>I.MobileNetV4FeatureExtractor,MobileNetV4ForImageClassification:()=>r.MobileNetV4ForImageClassification,MobileNetV4ImageProcessor:()=>I.MobileNetV4ImageProcessor,MobileNetV4Model:()=>r.MobileNetV4Model,MobileNetV4PreTrainedModel:()=>r.MobileNetV4PreTrainedModel,MobileViTFeatureExtractor:()=>I.MobileViTFeatureExtractor,MobileViTForImageClassification:()=>r.MobileViTForImageClassification,MobileViTImageProcessor:()=>I.MobileViTImageProcessor,MobileViTModel:()=>r.MobileViTModel,MobileViTPreTrainedModel:()=>r.MobileViTPreTrainedModel,MobileViTV2ForImageClassification:()=>r.MobileViTV2ForImageClassification,MobileViTV2Model:()=>r.MobileViTV2Model,MobileViTV2PreTrainedModel:()=>r.MobileViTV2PreTrainedModel,ModelOutput:()=>r.ModelOutput,ModernBertForMaskedLM:()=>r.ModernBertForMaskedLM,ModernBertForSequenceClassification:()=>r.ModernBertForSequenceClassification,ModernBertForTokenClassification:()=>r.ModernBertForTokenClassification,ModernBertModel:()=>r.ModernBertModel,ModernBertPreTrainedModel:()=>r.ModernBertPreTrainedModel,Moondream1ForConditionalGeneration:()=>r.Moondream1ForConditionalGeneration,MoonshineFeatureExtractor:()=>M.MoonshineFeatureExtractor,MoonshineForConditionalGeneration:()=>r.MoonshineForConditionalGeneration,MoonshineModel:()=>r.MoonshineModel,MoonshinePreTrainedModel:()=>r.MoonshinePreTrainedModel,MoonshineProcessor:()=>ne.MoonshineProcessor,MptForCausalLM:()=>r.MptForCausalLM,MptModel:()=>r.MptModel,MptPreTrainedModel:()=>r.MptPreTrainedModel,MultiModalityCausalLM:()=>r.MultiModalityCausalLM,MultiModalityPreTrainedModel:()=>r.MultiModalityPreTrainedModel,MusicgenForCausalLM:()=>r.MusicgenForCausalLM,MusicgenForConditionalGeneration:()=>r.MusicgenForConditionalGeneration,MusicgenModel:()=>r.MusicgenModel,MusicgenPreTrainedModel:()=>r.MusicgenPreTrainedModel,NllbTokenizer:()=>f.NllbTokenizer,NoBadWordsLogitsProcessor:()=>$.NoBadWordsLogitsProcessor,NoRepeatNGramLogitsProcessor:()=>$.NoRepeatNGramLogitsProcessor,NomicBertModel:()=>r.NomicBertModel,NomicBertPreTrainedModel:()=>r.NomicBertPreTrainedModel,NougatImageProcessor:()=>I.NougatImageProcessor,NougatTokenizer:()=>f.NougatTokenizer,OPTForCausalLM:()=>r.OPTForCausalLM,OPTModel:()=>r.OPTModel,OPTPreTrainedModel:()=>r.OPTPreTrainedModel,ObjectDetectionPipeline:()=>A.ObjectDetectionPipeline,Olmo2ForCausalLM:()=>r.Olmo2ForCausalLM,Olmo2Model:()=>r.Olmo2Model,Olmo2PreTrainedModel:()=>r.Olmo2PreTrainedModel,OlmoForCausalLM:()=>r.OlmoForCausalLM,OlmoModel:()=>r.OlmoModel,OlmoPreTrainedModel:()=>r.OlmoPreTrainedModel,OpenELMForCausalLM:()=>r.OpenELMForCausalLM,OpenELMModel:()=>r.OpenELMModel,OpenELMPreTrainedModel:()=>r.OpenELMPreTrainedModel,OwlViTFeatureExtractor:()=>I.OwlViTFeatureExtractor,OwlViTForObjectDetection:()=>r.OwlViTForObjectDetection,OwlViTImageProcessor:()=>I.OwlViTImageProcessor,OwlViTModel:()=>r.OwlViTModel,OwlViTPreTrainedModel:()=>r.OwlViTPreTrainedModel,OwlViTProcessor:()=>ne.OwlViTProcessor,Owlv2ForObjectDetection:()=>r.Owlv2ForObjectDetection,Owlv2ImageProcessor:()=>I.Owlv2ImageProcessor,Owlv2Model:()=>r.Owlv2Model,Owlv2PreTrainedModel:()=>r.Owlv2PreTrainedModel,PaliGemmaForConditionalGeneration:()=>r.PaliGemmaForConditionalGeneration,PaliGemmaPreTrainedModel:()=>r.PaliGemmaPreTrainedModel,PaliGemmaProcessor:()=>ne.PaliGemmaProcessor,PatchTSMixerForPrediction:()=>r.PatchTSMixerForPrediction,PatchTSMixerModel:()=>r.PatchTSMixerModel,PatchTSMixerPreTrainedModel:()=>r.PatchTSMixerPreTrainedModel,PatchTSTForPrediction:()=>r.PatchTSTForPrediction,PatchTSTModel:()=>r.PatchTSTModel,PatchTSTPreTrainedModel:()=>r.PatchTSTPreTrainedModel,Phi3ForCausalLM:()=>r.Phi3ForCausalLM,Phi3Model:()=>r.Phi3Model,Phi3PreTrainedModel:()=>r.Phi3PreTrainedModel,Phi3VForCausalLM:()=>r.Phi3VForCausalLM,Phi3VImageProcessor:()=>I.Phi3VImageProcessor,Phi3VPreTrainedModel:()=>r.Phi3VPreTrainedModel,Phi3VProcessor:()=>ne.Phi3VProcessor,PhiForCausalLM:()=>r.PhiForCausalLM,PhiModel:()=>r.PhiModel,PhiPreTrainedModel:()=>r.PhiPreTrainedModel,Pipeline:()=>A.Pipeline,PreTrainedModel:()=>r.PreTrainedModel,PreTrainedTokenizer:()=>f.PreTrainedTokenizer,PretrainedConfig:()=>D.PretrainedConfig,PretrainedMixin:()=>r.PretrainedMixin,Processor:()=>te.Processor,PvtForImageClassification:()=>r.PvtForImageClassification,PvtImageProcessor:()=>I.PvtImageProcessor,PvtModel:()=>r.PvtModel,PvtPreTrainedModel:()=>r.PvtPreTrainedModel,PyAnnoteFeatureExtractor:()=>M.PyAnnoteFeatureExtractor,PyAnnoteForAudioFrameClassification:()=>r.PyAnnoteForAudioFrameClassification,PyAnnoteModel:()=>r.PyAnnoteModel,PyAnnotePreTrainedModel:()=>r.PyAnnotePreTrainedModel,PyAnnoteProcessor:()=>ne.PyAnnoteProcessor,QuestionAnsweringModelOutput:()=>r.QuestionAnsweringModelOutput,QuestionAnsweringPipeline:()=>A.QuestionAnsweringPipeline,Qwen2ForCausalLM:()=>r.Qwen2ForCausalLM,Qwen2Model:()=>r.Qwen2Model,Qwen2PreTrainedModel:()=>r.Qwen2PreTrainedModel,Qwen2Tokenizer:()=>f.Qwen2Tokenizer,Qwen2VLForConditionalGeneration:()=>r.Qwen2VLForConditionalGeneration,Qwen2VLImageProcessor:()=>I.Qwen2VLImageProcessor,Qwen2VLPreTrainedModel:()=>r.Qwen2VLPreTrainedModel,Qwen2VLProcessor:()=>ne.Qwen2VLProcessor,RTDetrForObjectDetection:()=>r.RTDetrForObjectDetection,RTDetrImageProcessor:()=>I.RTDetrImageProcessor,RTDetrModel:()=>r.RTDetrModel,RTDetrObjectDetectionOutput:()=>r.RTDetrObjectDetectionOutput,RTDetrPreTrainedModel:()=>r.RTDetrPreTrainedModel,RawAudio:()=>U.RawAudio,RawImage:()=>Y.RawImage,RepetitionPenaltyLogitsProcessor:()=>$.RepetitionPenaltyLogitsProcessor,ResNetForImageClassification:()=>r.ResNetForImageClassification,ResNetModel:()=>r.ResNetModel,ResNetPreTrainedModel:()=>r.ResNetPreTrainedModel,RoFormerForMaskedLM:()=>r.RoFormerForMaskedLM,RoFormerForQuestionAnswering:()=>r.RoFormerForQuestionAnswering,RoFormerForSequenceClassification:()=>r.RoFormerForSequenceClassification,RoFormerForTokenClassification:()=>r.RoFormerForTokenClassification,RoFormerModel:()=>r.RoFormerModel,RoFormerPreTrainedModel:()=>r.RoFormerPreTrainedModel,RoFormerTokenizer:()=>f.RoFormerTokenizer,RobertaForMaskedLM:()=>r.RobertaForMaskedLM,RobertaForQuestionAnswering:()=>r.RobertaForQuestionAnswering,RobertaForSequenceClassification:()=>r.RobertaForSequenceClassification,RobertaForTokenClassification:()=>r.RobertaForTokenClassification,RobertaModel:()=>r.RobertaModel,RobertaPreTrainedModel:()=>r.RobertaPreTrainedModel,RobertaTokenizer:()=>f.RobertaTokenizer,SamImageProcessor:()=>I.SamImageProcessor,SamImageSegmentationOutput:()=>r.SamImageSegmentationOutput,SamModel:()=>r.SamModel,SamPreTrainedModel:()=>r.SamPreTrainedModel,SamProcessor:()=>ne.SamProcessor,SapiensForDepthEstimation:()=>r.SapiensForDepthEstimation,SapiensForNormalEstimation:()=>r.SapiensForNormalEstimation,SapiensForSemanticSegmentation:()=>r.SapiensForSemanticSegmentation,SapiensPreTrainedModel:()=>r.SapiensPreTrainedModel,SeamlessM4TFeatureExtractor:()=>M.SeamlessM4TFeatureExtractor,SegformerFeatureExtractor:()=>I.SegformerFeatureExtractor,SegformerForImageClassification:()=>r.SegformerForImageClassification,SegformerForSemanticSegmentation:()=>r.SegformerForSemanticSegmentation,SegformerImageProcessor:()=>I.SegformerImageProcessor,SegformerModel:()=>r.SegformerModel,SegformerPreTrainedModel:()=>r.SegformerPreTrainedModel,Seq2SeqLMOutput:()=>r.Seq2SeqLMOutput,SequenceClassifierOutput:()=>r.SequenceClassifierOutput,SiglipImageProcessor:()=>I.SiglipImageProcessor,SiglipModel:()=>r.SiglipModel,SiglipPreTrainedModel:()=>r.SiglipPreTrainedModel,SiglipTextModel:()=>r.SiglipTextModel,SiglipTokenizer:()=>f.SiglipTokenizer,SiglipVisionModel:()=>r.SiglipVisionModel,SpeechT5FeatureExtractor:()=>M.SpeechT5FeatureExtractor,SpeechT5ForSpeechToText:()=>r.SpeechT5ForSpeechToText,SpeechT5ForTextToSpeech:()=>r.SpeechT5ForTextToSpeech,SpeechT5HifiGan:()=>r.SpeechT5HifiGan,SpeechT5Model:()=>r.SpeechT5Model,SpeechT5PreTrainedModel:()=>r.SpeechT5PreTrainedModel,SpeechT5Processor:()=>ne.SpeechT5Processor,SpeechT5Tokenizer:()=>f.SpeechT5Tokenizer,SqueezeBertForMaskedLM:()=>r.SqueezeBertForMaskedLM,SqueezeBertForQuestionAnswering:()=>r.SqueezeBertForQuestionAnswering,SqueezeBertForSequenceClassification:()=>r.SqueezeBertForSequenceClassification,SqueezeBertModel:()=>r.SqueezeBertModel,SqueezeBertPreTrainedModel:()=>r.SqueezeBertPreTrainedModel,SqueezeBertTokenizer:()=>f.SqueezeBertTokenizer,StableLmForCausalLM:()=>r.StableLmForCausalLM,StableLmModel:()=>r.StableLmModel,StableLmPreTrainedModel:()=>r.StableLmPreTrainedModel,Starcoder2ForCausalLM:()=>r.Starcoder2ForCausalLM,Starcoder2Model:()=>r.Starcoder2Model,Starcoder2PreTrainedModel:()=>r.Starcoder2PreTrainedModel,StoppingCriteria:()=>q.StoppingCriteria,StoppingCriteriaList:()=>q.StoppingCriteriaList,StyleTextToSpeech2Model:()=>r.StyleTextToSpeech2Model,StyleTextToSpeech2PreTrainedModel:()=>r.StyleTextToSpeech2PreTrainedModel,SummarizationPipeline:()=>A.SummarizationPipeline,SuppressTokensAtBeginLogitsProcessor:()=>$.SuppressTokensAtBeginLogitsProcessor,Swin2SRForImageSuperResolution:()=>r.Swin2SRForImageSuperResolution,Swin2SRImageProcessor:()=>I.Swin2SRImageProcessor,Swin2SRModel:()=>r.Swin2SRModel,Swin2SRPreTrainedModel:()=>r.Swin2SRPreTrainedModel,SwinForImageClassification:()=>r.SwinForImageClassification,SwinModel:()=>r.SwinModel,SwinPreTrainedModel:()=>r.SwinPreTrainedModel,T5ForConditionalGeneration:()=>r.T5ForConditionalGeneration,T5Model:()=>r.T5Model,T5PreTrainedModel:()=>r.T5PreTrainedModel,T5Tokenizer:()=>f.T5Tokenizer,TableTransformerForObjectDetection:()=>r.TableTransformerForObjectDetection,TableTransformerModel:()=>r.TableTransformerModel,TableTransformerObjectDetectionOutput:()=>r.TableTransformerObjectDetectionOutput,TableTransformerPreTrainedModel:()=>r.TableTransformerPreTrainedModel,TemperatureLogitsWarper:()=>$.TemperatureLogitsWarper,Tensor:()=>R.Tensor,Text2TextGenerationPipeline:()=>A.Text2TextGenerationPipeline,TextClassificationPipeline:()=>A.TextClassificationPipeline,TextGenerationPipeline:()=>A.TextGenerationPipeline,TextStreamer:()=>j.TextStreamer,TextToAudioPipeline:()=>A.TextToAudioPipeline,TokenClassificationPipeline:()=>A.TokenClassificationPipeline,TokenClassifierOutput:()=>r.TokenClassifierOutput,TokenizerModel:()=>f.TokenizerModel,TopKLogitsWarper:()=>$.TopKLogitsWarper,TopPLogitsWarper:()=>$.TopPLogitsWarper,TrOCRForCausalLM:()=>r.TrOCRForCausalLM,TrOCRPreTrainedModel:()=>r.TrOCRPreTrainedModel,TranslationPipeline:()=>A.TranslationPipeline,UniSpeechForCTC:()=>r.UniSpeechForCTC,UniSpeechForSequenceClassification:()=>r.UniSpeechForSequenceClassification,UniSpeechModel:()=>r.UniSpeechModel,UniSpeechPreTrainedModel:()=>r.UniSpeechPreTrainedModel,UniSpeechSatForAudioFrameClassification:()=>r.UniSpeechSatForAudioFrameClassification,UniSpeechSatForCTC:()=>r.UniSpeechSatForCTC,UniSpeechSatForSequenceClassification:()=>r.UniSpeechSatForSequenceClassification,UniSpeechSatModel:()=>r.UniSpeechSatModel,UniSpeechSatPreTrainedModel:()=>r.UniSpeechSatPreTrainedModel,VLChatProcessor:()=>ne.VLChatProcessor,VLMImageProcessor:()=>I.VLMImageProcessor,ViTFeatureExtractor:()=>I.ViTFeatureExtractor,ViTForImageClassification:()=>r.ViTForImageClassification,ViTImageProcessor:()=>I.ViTImageProcessor,ViTMAEModel:()=>r.ViTMAEModel,ViTMAEPreTrainedModel:()=>r.ViTMAEPreTrainedModel,ViTMSNForImageClassification:()=>r.ViTMSNForImageClassification,ViTMSNModel:()=>r.ViTMSNModel,ViTMSNPreTrainedModel:()=>r.ViTMSNPreTrainedModel,ViTModel:()=>r.ViTModel,ViTPreTrainedModel:()=>r.ViTPreTrainedModel,VisionEncoderDecoderModel:()=>r.VisionEncoderDecoderModel,VitMatteForImageMatting:()=>r.VitMatteForImageMatting,VitMatteImageProcessor:()=>I.VitMatteImageProcessor,VitMattePreTrainedModel:()=>r.VitMattePreTrainedModel,VitPoseForPoseEstimation:()=>r.VitPoseForPoseEstimation,VitPoseImageProcessor:()=>I.VitPoseImageProcessor,VitPosePreTrainedModel:()=>r.VitPosePreTrainedModel,VitsModel:()=>r.VitsModel,VitsModelOutput:()=>r.VitsModelOutput,VitsPreTrainedModel:()=>r.VitsPreTrainedModel,VitsTokenizer:()=>f.VitsTokenizer,Wav2Vec2BertForCTC:()=>r.Wav2Vec2BertForCTC,Wav2Vec2BertForSequenceClassification:()=>r.Wav2Vec2BertForSequenceClassification,Wav2Vec2BertModel:()=>r.Wav2Vec2BertModel,Wav2Vec2BertPreTrainedModel:()=>r.Wav2Vec2BertPreTrainedModel,Wav2Vec2CTCTokenizer:()=>f.Wav2Vec2CTCTokenizer,Wav2Vec2FeatureExtractor:()=>M.Wav2Vec2FeatureExtractor,Wav2Vec2ForAudioFrameClassification:()=>r.Wav2Vec2ForAudioFrameClassification,Wav2Vec2ForCTC:()=>r.Wav2Vec2ForCTC,Wav2Vec2ForSequenceClassification:()=>r.Wav2Vec2ForSequenceClassification,Wav2Vec2Model:()=>r.Wav2Vec2Model,Wav2Vec2PreTrainedModel:()=>r.Wav2Vec2PreTrainedModel,Wav2Vec2Processor:()=>ne.Wav2Vec2Processor,Wav2Vec2ProcessorWithLM:()=>ne.Wav2Vec2ProcessorWithLM,WavLMForAudioFrameClassification:()=>r.WavLMForAudioFrameClassification,WavLMForCTC:()=>r.WavLMForCTC,WavLMForSequenceClassification:()=>r.WavLMForSequenceClassification,WavLMForXVector:()=>r.WavLMForXVector,WavLMModel:()=>r.WavLMModel,WavLMPreTrainedModel:()=>r.WavLMPreTrainedModel,WeSpeakerFeatureExtractor:()=>M.WeSpeakerFeatureExtractor,WeSpeakerResNetModel:()=>r.WeSpeakerResNetModel,WeSpeakerResNetPreTrainedModel:()=>r.WeSpeakerResNetPreTrainedModel,WhisperFeatureExtractor:()=>M.WhisperFeatureExtractor,WhisperForConditionalGeneration:()=>r.WhisperForConditionalGeneration,WhisperModel:()=>r.WhisperModel,WhisperPreTrainedModel:()=>r.WhisperPreTrainedModel,WhisperProcessor:()=>ne.WhisperProcessor,WhisperTextStreamer:()=>j.WhisperTextStreamer,WhisperTimeStampLogitsProcessor:()=>$.WhisperTimeStampLogitsProcessor,WhisperTokenizer:()=>f.WhisperTokenizer,XLMForQuestionAnswering:()=>r.XLMForQuestionAnswering,XLMForSequenceClassification:()=>r.XLMForSequenceClassification,XLMForTokenClassification:()=>r.XLMForTokenClassification,XLMModel:()=>r.XLMModel,XLMPreTrainedModel:()=>r.XLMPreTrainedModel,XLMRobertaForMaskedLM:()=>r.XLMRobertaForMaskedLM,XLMRobertaForQuestionAnswering:()=>r.XLMRobertaForQuestionAnswering,XLMRobertaForSequenceClassification:()=>r.XLMRobertaForSequenceClassification,XLMRobertaForTokenClassification:()=>r.XLMRobertaForTokenClassification,XLMRobertaModel:()=>r.XLMRobertaModel,XLMRobertaPreTrainedModel:()=>r.XLMRobertaPreTrainedModel,XLMRobertaTokenizer:()=>f.XLMRobertaTokenizer,XLMTokenizer:()=>f.XLMTokenizer,XLMWithLMHeadModel:()=>r.XLMWithLMHeadModel,XVectorOutput:()=>r.XVectorOutput,YolosFeatureExtractor:()=>I.YolosFeatureExtractor,YolosForObjectDetection:()=>r.YolosForObjectDetection,YolosImageProcessor:()=>I.YolosImageProcessor,YolosModel:()=>r.YolosModel,YolosObjectDetectionOutput:()=>r.YolosObjectDetectionOutput,YolosPreTrainedModel:()=>r.YolosPreTrainedModel,ZeroShotAudioClassificationPipeline:()=>A.ZeroShotAudioClassificationPipeline,ZeroShotClassificationPipeline:()=>A.ZeroShotClassificationPipeline,ZeroShotImageClassificationPipeline:()=>A.ZeroShotImageClassificationPipeline,ZeroShotObjectDetectionPipeline:()=>A.ZeroShotObjectDetectionPipeline,bankers_round:()=>g.bankers_round,cat:()=>R.cat,cos_sim:()=>g.cos_sim,dot:()=>g.dot,dynamic_time_warping:()=>g.dynamic_time_warping,env:()=>De.env,full:()=>R.full,full_like:()=>R.full_like,getKeyValueShapes:()=>D.getKeyValueShapes,hamming:()=>U.hamming,hanning:()=>U.hanning,interpolate:()=>R.interpolate,interpolate_4d:()=>R.interpolate_4d,interpolate_data:()=>g.interpolate_data,is_chinese_char:()=>f.is_chinese_char,layer_norm:()=>R.layer_norm,load_image:()=>Y.load_image,log_softmax:()=>g.log_softmax,magnitude:()=>g.magnitude,matmul:()=>R.matmul,max:()=>g.max,mean:()=>R.mean,mean_pooling:()=>R.mean_pooling,medianFilter:()=>g.medianFilter,mel_filter_bank:()=>U.mel_filter_bank,min:()=>g.min,ones:()=>R.ones,ones_like:()=>R.ones_like,permute:()=>R.permute,permute_data:()=>g.permute_data,pipeline:()=>A.pipeline,quantize_embeddings:()=>R.quantize_embeddings,rand:()=>R.rand,read_audio:()=>U.read_audio,rfft:()=>R.rfft,round:()=>g.round,slice:()=>R.slice,softmax:()=>g.softmax,spectrogram:()=>U.spectrogram,stack:()=>R.stack,std_mean:()=>R.std_mean,topk:()=>R.topk,window_function:()=>U.window_function,zeros:()=>R.zeros,zeros_like:()=>R.zeros_like});var De=gs("./src/env.js"),A=gs("./src/pipelines.js"),r=gs("./src/models.js"),f=gs("./src/tokenizers.js"),D=gs("./src/configs.js"),U=gs("./src/utils/audio.js"),Y=gs("./src/utils/image.js"),R=gs("./src/utils/tensor.js"),g=gs("./src/utils/maths.js"),v=gs("./src/base/feature_extraction_utils.js"),M=gs("./src/models/feature_extractors.js"),y=gs("./src/models/auto/feature_extraction_auto.js"),b=gs("./src/base/image_processors_utils.js"),I=gs("./src/models/image_processors.js"),K=gs("./src/models/auto/image_processing_auto.js"),te=gs("./src/base/processing_utils.js"),ne=gs("./src/models/processors.js"),W=gs("./src/models/auto/processing_auto.js"),j=gs("./src/generation/streamers.js"),q=gs("./src/generation/stopping_criteria.js"),$=gs("./src/generation/logits_process.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.AutoFeatureExtractor,c.AutoImageProcessor,c.AutoModel,c.AutoModelForAudioClassification,c.AutoModelForAudioFrameClassification,c.AutoModelForCTC,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.AutoModelForPoseEstimation,c.AutoModelForQuestionAnswering,c.AutoModelForSemanticSegmentation,c.AutoModelForSeq2SeqLM,c.AutoModelForSequenceClassification,c.AutoModelForSpeechSeq2Seq,c.AutoModelForTextToSpectrogram,c.AutoModelForTextToWaveform,c.AutoModelForTokenClassification,c.AutoModelForUniversalSegmentation;var r_=c.AutoModelForVision2Seq;c.AutoModelForXVector,c.AutoModelForZeroShotObjectDetection;var n_=c.AutoProcessor;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.ClassifierFreeGuidanceLogitsProcessor,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.DeiTImageProcessor,c.DeiTModel,c.DeiTPreTrainedModel,c.DepthAnythingForDepthEstimation,c.DepthAnythingPreTrainedModel,c.DepthEstimationPipeline,c.DepthProForDepthEstimation,c.DepthProPreTrainedModel,c.DetrFeatureExtractor,c.DetrForObjectDetection,c.DetrForSegmentation,c.DetrImageProcessor,c.DetrModel,c.DetrObjectDetectionOutput,c.DetrPreTrainedModel,c.DetrSegmentationOutput,c.Dinov2ForImageClassification,c.Dinov2Model,c.Dinov2PreTrainedModel,c.Dinov2WithRegistersForImageClassification,c.Dinov2WithRegistersModel,c.Dinov2WithRegistersPreTrainedModel,c.DistilBertForMaskedLM,c.DistilBertForQuestionAnswering,c.DistilBertForSequenceClassification,c.DistilBertForTokenClassification,c.DistilBertModel,c.DistilBertPreTrainedModel,c.DistilBertTokenizer,c.DocumentQuestionAnsweringPipeline,c.DonutFeatureExtractor,c.DonutImageProcessor,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.ExaoneForCausalLM,c.ExaoneModel,c.ExaonePreTrainedModel,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.ForcedBOSTokenLogitsProcessor,c.ForcedEOSTokenLogitsProcessor,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.GlmForCausalLM,c.GlmModel,c.GlmPreTrainedModel,c.GraniteForCausalLM,c.GraniteModel,c.GranitePreTrainedModel,c.Grok1Tokenizer,c.GroundingDinoForObjectDetection,c.GroundingDinoImageProcessor,c.GroundingDinoPreTrainedModel,c.GroundingDinoProcessor,c.GroupViTModel,c.GroupViTPreTrainedModel,c.HeliumForCausalLM,c.HeliumModel,c.HeliumPreTrainedModel,c.HerbertTokenizer,c.HieraForImageClassification,c.HieraModel,c.HieraPreTrainedModel,c.HubertForCTC,c.HubertForSequenceClassification,c.HubertModel,c.HubertPreTrainedModel,c.IJepaForImageClassification,c.IJepaModel,c.IJepaPreTrainedModel,c.Idefics3ForConditionalGeneration,c.Idefics3ImageProcessor,c.Idefics3PreTrainedModel,c.Idefics3Processor,c.ImageClassificationPipeline,c.ImageFeatureExtractionPipeline,c.ImageFeatureExtractor,c.ImageMattingOutput,c.ImageProcessor,c.ImageSegmentationPipeline,c.ImageToImagePipeline,c.ImageToTextPipeline;var o_=c.InterruptableStoppingCriteria;c.JAISLMHeadModel,c.JAISModel,c.JAISPreTrainedModel,c.JinaCLIPImageProcessor,c.JinaCLIPModel,c.JinaCLIPPreTrainedModel,c.JinaCLIPProcessor,c.JinaCLIPTextModel,c.JinaCLIPVisionModel,c.LlamaForCausalLM,c.LlamaModel,c.LlamaPreTrainedModel,c.LlamaTokenizer,c.LlavaForConditionalGeneration,c.LlavaOnevisionForConditionalGeneration,c.LlavaOnevisionImageProcessor,c.LlavaPreTrainedModel,c.LogitsProcessor,c.LogitsProcessorList,c.LogitsWarper,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.Mask2FormerImageProcessor,c.MaskFormerFeatureExtractor,c.MaskFormerForInstanceSegmentation,c.MaskFormerImageProcessor,c.MaskFormerModel,c.MaskFormerPreTrainedModel,c.MaskedLMOutput,c.MaxLengthCriteria,c.MgpstrForSceneTextRecognition,c.MgpstrModelOutput,c.MgpstrPreTrainedModel,c.MgpstrProcessor,c.MgpstrTokenizer,c.MinLengthLogitsProcessor,c.MinNewTokensLengthLogitsProcessor,c.MistralForCausalLM,c.MistralModel,c.MistralPreTrainedModel,c.MobileBertForMaskedLM,c.MobileBertForQuestionAnswering,c.MobileBertForSequenceClassification,c.MobileBertModel,c.MobileBertPreTrainedModel,c.MobileBertTokenizer,c.MobileLLMForCausalLM,c.MobileLLMModel,c.MobileLLMPreTrainedModel,c.MobileNetV1FeatureExtractor,c.MobileNetV1ForImageClassification,c.MobileNetV1ImageProcessor,c.MobileNetV1Model,c.MobileNetV1PreTrainedModel,c.MobileNetV2FeatureExtractor,c.MobileNetV2ForImageClassification,c.MobileNetV2ImageProcessor,c.MobileNetV2Model,c.MobileNetV2PreTrainedModel,c.MobileNetV3FeatureExtractor,c.MobileNetV3ForImageClassification,c.MobileNetV3ImageProcessor,c.MobileNetV3Model,c.MobileNetV3PreTrainedModel,c.MobileNetV4FeatureExtractor,c.MobileNetV4ForImageClassification,c.MobileNetV4ImageProcessor,c.MobileNetV4Model,c.MobileNetV4PreTrainedModel,c.MobileViTFeatureExtractor,c.MobileViTForImageClassification,c.MobileViTImageProcessor,c.MobileViTModel,c.MobileViTPreTrainedModel,c.MobileViTV2ForImageClassification,c.MobileViTV2Model,c.MobileViTV2PreTrainedModel,c.ModelOutput,c.ModernBertForMaskedLM,c.ModernBertForSequenceClassification,c.ModernBertForTokenClassification,c.ModernBertModel,c.ModernBertPreTrainedModel,c.Moondream1ForConditionalGeneration,c.MoonshineFeatureExtractor,c.MoonshineForConditionalGeneration,c.MoonshineModel,c.MoonshinePreTrainedModel,c.MoonshineProcessor,c.MptForCausalLM,c.MptModel,c.MptPreTrainedModel,c.MultiModalityCausalLM,c.MultiModalityPreTrainedModel,c.MusicgenForCausalLM,c.MusicgenForConditionalGeneration,c.MusicgenModel,c.MusicgenPreTrainedModel,c.NllbTokenizer,c.NoBadWordsLogitsProcessor,c.NoRepeatNGramLogitsProcessor,c.NomicBertModel,c.NomicBertPreTrainedModel,c.NougatImageProcessor,c.NougatTokenizer,c.OPTForCausalLM,c.OPTModel,c.OPTPreTrainedModel,c.ObjectDetectionPipeline,c.Olmo2ForCausalLM,c.Olmo2Model,c.Olmo2PreTrainedModel,c.OlmoForCausalLM,c.OlmoModel,c.OlmoPreTrainedModel,c.OpenELMForCausalLM,c.OpenELMModel,c.OpenELMPreTrainedModel,c.OwlViTFeatureExtractor,c.OwlViTForObjectDetection,c.OwlViTImageProcessor,c.OwlViTModel,c.OwlViTPreTrainedModel,c.OwlViTProcessor,c.Owlv2ForObjectDetection,c.Owlv2ImageProcessor,c.Owlv2Model,c.Owlv2PreTrainedModel,c.PaliGemmaForConditionalGeneration,c.PaliGemmaPreTrainedModel,c.PaliGemmaProcessor,c.PatchTSMixerForPrediction,c.PatchTSMixerModel,c.PatchTSMixerPreTrainedModel,c.PatchTSTForPrediction,c.PatchTSTModel,c.PatchTSTPreTrainedModel,c.Phi3ForCausalLM,c.Phi3Model,c.Phi3PreTrainedModel,c.Phi3VForCausalLM,c.Phi3VImageProcessor,c.Phi3VPreTrainedModel,c.Phi3VProcessor,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.Qwen2VLForConditionalGeneration,c.Qwen2VLImageProcessor,c.Qwen2VLPreTrainedModel,c.Qwen2VLProcessor,c.RTDetrForObjectDetection,c.RTDetrImageProcessor,c.RTDetrModel,c.RTDetrObjectDetectionOutput,c.RTDetrPreTrainedModel,c.RawAudio,c.RawImage,c.RepetitionPenaltyLogitsProcessor,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.SapiensForDepthEstimation,c.SapiensForNormalEstimation,c.SapiensForSemanticSegmentation,c.SapiensPreTrainedModel,c.SeamlessM4TFeatureExtractor,c.SegformerFeatureExtractor,c.SegformerForImageClassification,c.SegformerForSemanticSegmentation,c.SegformerImageProcessor,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.StyleTextToSpeech2Model,c.StyleTextToSpeech2PreTrainedModel,c.SummarizationPipeline,c.SuppressTokensAtBeginLogitsProcessor,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.TemperatureLogitsWarper,c.Tensor,c.Text2TextGenerationPipeline,c.TextClassificationPipeline,c.TextGenerationPipeline;var i_=c.TextStreamer;c.TextToAudioPipeline,c.TokenClassificationPipeline,c.TokenClassifierOutput,c.TokenizerModel,c.TopKLogitsWarper,c.TopPLogitsWarper,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.VLChatProcessor,c.VLMImageProcessor,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.VitPoseForPoseEstimation,c.VitPoseImageProcessor,c.VitPosePreTrainedModel,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.Wav2Vec2Processor,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.WhisperTimeStampLogitsProcessor,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.YolosImageProcessor,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;var a_=c.load_image;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.rand,c.read_audio,c.rfft,c.round,c.slice,c.softmax,c.spectrogram,c.stack,c.std_mean,c.topk,c.window_function,c.zeros,c.zeros_like;const l_=1024;let u_=!1;async function d_(){try{const De=await navigator.gpu.requestAdapter();if(!De)throw new Error("WebGPU is not supported (no adapter found)");u_=De.features.has("shader-f16")}catch(De){self.postMessage({status:"error",data:De.toString()})}}class Gp{static async getInstance(A=null){return this.processor??(this.processor=n_.from_pretrained(this.model_id,{progress_callback:A})),this.model??(this.model=r_.from_pretrained(this.model_id,{dtype:"fp32",device:"webgpu",progress_callback:A})),Promise.all([this.processor,this.model])}}_e(Gp,"model_id","HuggingFaceTB/SmolVLM-256M-Instruct");const Bc=new o_;async function c_(De){De=De.slice(-1);const[A,r]=await Gp.getInstance(),f=await Promise.all(De.map(te=>te.content).flat(1/0).filter(te=>te.image!==void 0).map(te=>a_(te.image))),D=A.apply_chat_template(De,{add_generation_prompt:!0}),U=await A(D,f,{});let Y,R=0,g;const v=te=>{Y??(Y=performance.now()),R++>0&&(g=R/(performance.now()-Y)*1e3)},M=te=>{self.postMessage({status:"update",output:te,tps:g,numTokens:R})},y=new i_(A.tokenizer,{skip_prompt:!0,skip_special_tokens:!0,callback_function:M,token_callback_function:v});self.postMessage({status:"start"});const{past_key_values:b,sequences:I}=await r.generate({...U,do_sample:!1,repetition_penalty:1.1,max_new_tokens:l_,streamer:y,stopping_criteria:Bc,return_dict_in_generate:!0}).catch(te=>{self.postMessage({status:"error",data:te.toString()})}),K=A.batch_decode(I,{skip_special_tokens:!0});self.postMessage({status:"complete",output:K})}async function p_(){self.postMessage({status:"loading",data:"Loading model..."}),await Gp.getInstance(De=>{self.postMessage(De)}),self.postMessage({status:"ready"})}self.addEventListener("message",async De=>{const{type:A,data:r}=De.data;switch(A){case"check":d_();break;case"load":p_();break;case"generate":Bc.reset(),c_(r);break;case"interrupt":Bc.interrupt();break;case"reset":Bc.reset();break}})})(); diff --git a/index.html b/index.html index 04d92d96ec4e0cb3eed3da724a4f9f791a75c5b7..37ea091834475fb20169652e58879cd720779ba3 100644 --- a/index.html +++ b/index.html @@ -5,7 +5,7 @@ SmolVLM WebGPU - +