diff --git "a/assets/index-Dt4CdiUt.js" "b/assets/index-Dt4CdiUt.js" new file mode 100644--- /dev/null +++ "b/assets/index-Dt4CdiUt.js" @@ -0,0 +1,2669 @@ +var Dx=Object.defineProperty;var Lx=(e,n,r)=>n in e?Dx(e,n,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[n]=r;var Ee=(e,n,r)=>Lx(e,typeof n!="symbol"?n+"":n,r);(function(){const n=document.createElement("link").relList;if(n&&n.supports&&n.supports("modulepreload"))return;for(const l of document.querySelectorAll('link[rel="modulepreload"]'))o(l);new MutationObserver(l=>{for(const p of l)if(p.type==="childList")for(const _ of p.addedNodes)_.tagName==="LINK"&&_.rel==="modulepreload"&&o(_)}).observe(document,{childList:!0,subtree:!0});function r(l){const p={};return l.integrity&&(p.integrity=l.integrity),l.referrerPolicy&&(p.referrerPolicy=l.referrerPolicy),l.crossOrigin==="use-credentials"?p.credentials="include":l.crossOrigin==="anonymous"?p.credentials="omit":p.credentials="same-origin",p}function o(l){if(l.ep)return;l.ep=!0;const p=r(l);fetch(l.href,p)}})();var Nv={exports:{}},Oh={},jv={exports:{}},xn={};/** + * @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 Bp=Symbol.for("react.element"),Bx=Symbol.for("react.portal"),Rx=Symbol.for("react.fragment"),Nx=Symbol.for("react.strict_mode"),jx=Symbol.for("react.profiler"),Vx=Symbol.for("react.provider"),Ux=Symbol.for("react.context"),Wx=Symbol.for("react.forward_ref"),Gx=Symbol.for("react.suspense"),qx=Symbol.for("react.memo"),Hx=Symbol.for("react.lazy"),$0=Symbol.iterator;function Kx(e){return e===null||typeof e!="object"?null:(e=$0&&e[$0]||e["@@iterator"],typeof e=="function"?e:null)}var Vv={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},Uv=Object.assign,Wv={};function Ql(e,n,r){this.props=e,this.context=n,this.refs=Wv,this.updater=r||Vv}Ql.prototype.isReactComponent={};Ql.prototype.setState=function(e,n){if(typeof e!="object"&&typeof e!="function"&&e!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,n,"setState")};Ql.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function Gv(){}Gv.prototype=Ql.prototype;function e_(e,n,r){this.props=e,this.context=n,this.refs=Wv,this.updater=r||Vv}var t_=e_.prototype=new Gv;t_.constructor=e_;Uv(t_,Ql.prototype);t_.isPureReactComponent=!0;var P0=Array.isArray,qv=Object.prototype.hasOwnProperty,n_={current:null},Hv={key:!0,ref:!0,__self:!0,__source:!0};function Kv(e,n,r){var o,l={},p=null,_=null;if(n!=null)for(o in n.ref!==void 0&&(_=n.ref),n.key!==void 0&&(p=""+n.key),n)qv.call(n,o)&&!Hv.hasOwnProperty(o)&&(l[o]=n[o]);var C=arguments.length-2;if(C===1)l.children=r;else if(1>>1,Fe=H[se];if(0>>1;sel(st,Me))Oel(rt,st)?(H[se]=rt,H[Oe]=Me,se=Oe):(H[se]=st,H[Ye]=Me,se=Ye);else if(Oel(rt,Me))H[se]=rt,H[Oe]=Me,se=Oe;else break e}}return pe}function l(H,pe){var Me=H.sortIndex-pe.sortIndex;return Me!==0?Me:H.id-pe.id}if(typeof performance=="object"&&typeof performance.now=="function"){var p=performance;e.unstable_now=function(){return p.now()}}else{var _=Date,C=_.now();e.unstable_now=function(){return _.now()-C}}var M=[],b=[],F=1,S=null,G=3,J=!1,te=!1,ne=!1,X=typeof setTimeout=="function"?setTimeout:null,A=typeof clearTimeout=="function"?clearTimeout:null,P=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function L(H){for(var pe=r(b);pe!==null;){if(pe.callback===null)o(b);else if(pe.startTime<=H)o(b),pe.sortIndex=pe.expirationTime,n(M,pe);else break;pe=r(b)}}function Z(H){if(ne=!1,L(H),!te)if(r(M)!==null)te=!0,pt(V);else{var pe=r(b);pe!==null&&xe(Z,pe.startTime-H)}}function V(H,pe){te=!1,ne&&(ne=!1,A(z),z=-1),J=!0;var Me=G;try{for(L(pe),S=r(M);S!==null&&(!(S.expirationTime>pe)||H&&!ke());){var se=S.callback;if(typeof se=="function"){S.callback=null,G=S.priorityLevel;var Fe=se(S.expirationTime<=pe);pe=e.unstable_now(),typeof Fe=="function"?S.callback=Fe:S===r(M)&&o(M),L(pe)}else o(M);S=r(M)}if(S!==null)var ut=!0;else{var Ye=r(b);Ye!==null&&xe(Z,Ye.startTime-pe),ut=!1}return ut}finally{S=null,G=Me,J=!1}}var D=!1,N=null,z=-1,me=5,he=-1;function ke(){return!(e.unstable_now()-heH||125se?(H.sortIndex=Me,n(b,H),r(M)===null&&H===r(b)&&(ne?(A(z),z=-1):ne=!0,xe(Z,Me-se))):(H.sortIndex=Fe,n(M,H),te||J||(te=!0,pt(V))),H},e.unstable_shouldYield=ke,e.unstable_wrapCallback=function(H){var pe=G;return function(){var Me=G;G=pe;try{return H.apply(this,arguments)}finally{G=Me}}}})(Jv);Zv.exports=Jv;var oT=Zv.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 sT=ji,hi=oT;function gt(e){for(var n="https://reactjs.org/docs/error-decoder.html?invariant="+e,r=1;r"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),lg=Object.prototype.hasOwnProperty,aT=/^[: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]*$/,F0={},z0={};function lT(e){return lg.call(z0,e)?!0:lg.call(F0,e)?!1:aT.test(e)?z0[e]=!0:(F0[e]=!0,!1)}function uT(e,n,r,o){if(r!==null&&r.type===0)return!1;switch(typeof n){case"function":case"symbol":return!0;case"boolean":return o?!1:r!==null?!r.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function dT(e,n,r,o){if(n===null||typeof n>"u"||uT(e,n,r,o))return!0;if(o)return!1;if(r!==null)switch(r.type){case 3:return!n;case 4:return n===!1;case 5:return isNaN(n);case 6:return isNaN(n)||1>n}return!1}function Zr(e,n,r,o,l,p,_){this.acceptsBooleans=n===2||n===3||n===4,this.attributeName=o,this.attributeNamespace=l,this.mustUseProperty=r,this.propertyName=e,this.type=n,this.sanitizeURL=p,this.removeEmptyString=_}var Fr={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){Fr[e]=new Zr(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var n=e[0];Fr[n]=new Zr(n,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){Fr[e]=new Zr(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){Fr[e]=new Zr(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){Fr[e]=new Zr(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){Fr[e]=new Zr(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){Fr[e]=new Zr(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){Fr[e]=new Zr(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){Fr[e]=new Zr(e,5,!1,e.toLowerCase(),null,!1,!1)});var i_=/[\-:]([a-z])/g;function o_(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 n=e.replace(i_,o_);Fr[n]=new Zr(n,1,!1,e,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var n=e.replace(i_,o_);Fr[n]=new Zr(n,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(e){var n=e.replace(i_,o_);Fr[n]=new Zr(n,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){Fr[e]=new Zr(e,1,!1,e.toLowerCase(),null,!1,!1)});Fr.xlinkHref=new Zr("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){Fr[e]=new Zr(e,1,!1,e.toLowerCase(),null,!0,!0)});function s_(e,n,r,o){var l=Fr.hasOwnProperty(n)?Fr[n]:null;(l!==null?l.type!==0:o||!(2C||l[_]!==p[C]){var M=` +`+l[_].replace(" at new "," at ");return e.displayName&&M.includes("")&&(M=M.replace("",e.displayName)),M}while(1<=_&&0<=C);break}}}finally{Bm=!1,Error.prepareStackTrace=r}return(e=e?e.displayName||e.name:"")?ap(e):""}function cT(e){switch(e.tag){case 5:return ap(e.type);case 16:return ap("Lazy");case 13:return ap("Suspense");case 19:return ap("SuspenseList");case 0:case 2:case 15:return e=Rm(e.type,!1),e;case 11:return e=Rm(e.type.render,!1),e;case 1:return e=Rm(e.type,!0),e;default:return""}}function pg(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 Sl:return"Fragment";case Tl:return"Portal";case ug:return"Profiler";case a_:return"StrictMode";case dg:return"Suspense";case cg:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case n1:return(e.displayName||"Context")+".Consumer";case t1:return(e._context.displayName||"Context")+".Provider";case l_:var n=e.render;return e=e.displayName,e||(e=n.displayName||n.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case u_:return n=e.displayName||null,n!==null?n:pg(e.type)||"Memo";case ts:n=e._payload,e=e._init;try{return pg(e(n))}catch{}}return null}function pT(e){var n=e.type;switch(e.tag){case 24:return"Cache";case 9:return(n.displayName||"Context")+".Consumer";case 10:return(n._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=n.render,e=e.displayName||e.name||"",n.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return n;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return pg(n);case 8:return n===a_?"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 n=="function")return n.displayName||n.name||null;if(typeof n=="string")return n}return null}function ms(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function i1(e){var n=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(n==="checkbox"||n==="radio")}function fT(e){var n=i1(e)?"checked":"value",r=Object.getOwnPropertyDescriptor(e.constructor.prototype,n),o=""+e[n];if(!e.hasOwnProperty(n)&&typeof r<"u"&&typeof r.get=="function"&&typeof r.set=="function"){var l=r.get,p=r.set;return Object.defineProperty(e,n,{configurable:!0,get:function(){return l.call(this)},set:function(_){o=""+_,p.call(this,_)}}),Object.defineProperty(e,n,{enumerable:r.enumerable}),{getValue:function(){return o},setValue:function(_){o=""+_},stopTracking:function(){e._valueTracker=null,delete e[n]}}}}function Lf(e){e._valueTracker||(e._valueTracker=fT(e))}function o1(e){if(!e)return!1;var n=e._valueTracker;if(!n)return!0;var r=n.getValue(),o="";return e&&(o=i1(e)?e.checked?"true":"false":e.value),e=o,e!==r?(n.setValue(e),!0):!1}function ch(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 fg(e,n){var r=n.checked;return tr({},n,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:r??e._wrapperState.initialChecked})}function D0(e,n){var r=n.defaultValue==null?"":n.defaultValue,o=n.checked!=null?n.checked:n.defaultChecked;r=ms(n.value!=null?n.value:r),e._wrapperState={initialChecked:o,initialValue:r,controlled:n.type==="checkbox"||n.type==="radio"?n.checked!=null:n.value!=null}}function s1(e,n){n=n.checked,n!=null&&s_(e,"checked",n,!1)}function hg(e,n){s1(e,n);var r=ms(n.value),o=n.type;if(r!=null)o==="number"?(r===0&&e.value===""||e.value!=r)&&(e.value=""+r):e.value!==""+r&&(e.value=""+r);else if(o==="submit"||o==="reset"){e.removeAttribute("value");return}n.hasOwnProperty("value")?mg(e,n.type,r):n.hasOwnProperty("defaultValue")&&mg(e,n.type,ms(n.defaultValue)),n.checked==null&&n.defaultChecked!=null&&(e.defaultChecked=!!n.defaultChecked)}function L0(e,n,r){if(n.hasOwnProperty("value")||n.hasOwnProperty("defaultValue")){var o=n.type;if(!(o!=="submit"&&o!=="reset"||n.value!==void 0&&n.value!==null))return;n=""+e._wrapperState.initialValue,r||n===e.value||(e.value=n),e.defaultValue=n}r=e.name,r!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,r!==""&&(e.name=r)}function mg(e,n,r){(n!=="number"||ch(e.ownerDocument)!==e)&&(r==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+r&&(e.defaultValue=""+r))}var lp=Array.isArray;function Dl(e,n,r,o){if(e=e.options,n){n={};for(var l=0;l"+n.valueOf().toString()+"",n=Bf.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;n.firstChild;)e.appendChild(n.firstChild)}});function bp(e,n){if(n){var r=e.firstChild;if(r&&r===e.lastChild&&r.nodeType===3){r.nodeValue=n;return}}e.textContent=n}var pp={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},hT=["Webkit","ms","Moz","O"];Object.keys(pp).forEach(function(e){hT.forEach(function(n){n=n+e.charAt(0).toUpperCase()+e.substring(1),pp[n]=pp[e]})});function d1(e,n,r){return n==null||typeof n=="boolean"||n===""?"":r||typeof n!="number"||n===0||pp.hasOwnProperty(e)&&pp[e]?(""+n).trim():n+"px"}function c1(e,n){e=e.style;for(var r in n)if(n.hasOwnProperty(r)){var o=r.indexOf("--")===0,l=d1(r,n[r],o);r==="float"&&(r="cssFloat"),o?e.setProperty(r,l):e[r]=l}}var mT=tr({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 yg(e,n){if(n){if(mT[e]&&(n.children!=null||n.dangerouslySetInnerHTML!=null))throw Error(gt(137,e));if(n.dangerouslySetInnerHTML!=null){if(n.children!=null)throw Error(gt(60));if(typeof n.dangerouslySetInnerHTML!="object"||!("__html"in n.dangerouslySetInnerHTML))throw Error(gt(61))}if(n.style!=null&&typeof n.style!="object")throw Error(gt(62))}}function wg(e,n){if(e.indexOf("-")===-1)return typeof n.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 vg=null;function d_(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var Mg=null,Ll=null,Bl=null;function N0(e){if(e=jp(e)){if(typeof Mg!="function")throw Error(gt(280));var n=e.stateNode;n&&(n=Nh(n),Mg(e.stateNode,e.type,n))}}function p1(e){Ll?Bl?Bl.push(e):Bl=[e]:Ll=e}function f1(){if(Ll){var e=Ll,n=Bl;if(Bl=Ll=null,N0(e),n)for(e=0;e>>=0,e===0?32:31-(kT(e)/ET|0)|0}var Rf=64,Nf=4194304;function up(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 mh(e,n){var r=e.pendingLanes;if(r===0)return 0;var o=0,l=e.suspendedLanes,p=e.pingedLanes,_=r&268435455;if(_!==0){var C=_&~l;C!==0?o=up(C):(p&=_,p!==0&&(o=up(p)))}else _=r&~l,_!==0?o=up(_):p!==0&&(o=up(p));if(o===0)return 0;if(n!==0&&n!==o&&!(n&l)&&(l=o&-o,p=n&-n,l>=p||l===16&&(p&4194240)!==0))return n;if(o&4&&(o|=r&16),n=e.entangledLanes,n!==0)for(e=e.entanglements,n&=o;0r;r++)n.push(e);return n}function Rp(e,n,r){e.pendingLanes|=n,n!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,n=31-Gi(n),e[n]=r}function AT(e,n){var r=e.pendingLanes&~n;e.pendingLanes=n,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=n,e.mutableReadLanes&=n,e.entangledLanes&=n,n=e.entanglements;var o=e.eventTimes;for(e=e.expirationTimes;0=hp),Q0=" ",X0=!1;function F1(e,n){switch(e){case"keyup":return o2.indexOf(n.keyCode)!==-1;case"keydown":return n.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function z1(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var kl=!1;function a2(e,n){switch(e){case"compositionend":return z1(n);case"keypress":return n.which!==32?null:(X0=!0,Q0);case"textInput":return e=n.data,e===Q0&&X0?null:e;default:return null}}function l2(e,n){if(kl)return e==="compositionend"||!y_&&F1(e,n)?(e=A1(),th=m_=os=null,kl=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(n.ctrlKey||n.altKey||n.metaKey)||n.ctrlKey&&n.altKey){if(n.char&&1=n)return{node:r,offset:n-e};e=o}e:{for(;r;){if(r.nextSibling){r=r.nextSibling;break e}r=r.parentNode}r=void 0}r=ev(r)}}function B1(e,n){return e&&n?e===n?!0:e&&e.nodeType===3?!1:n&&n.nodeType===3?B1(e,n.parentNode):"contains"in e?e.contains(n):e.compareDocumentPosition?!!(e.compareDocumentPosition(n)&16):!1:!1}function R1(){for(var e=window,n=ch();n instanceof e.HTMLIFrameElement;){try{var r=typeof n.contentWindow.location.href=="string"}catch{r=!1}if(r)e=n.contentWindow;else break;n=ch(e.document)}return n}function w_(e){var n=e&&e.nodeName&&e.nodeName.toLowerCase();return n&&(n==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||n==="textarea"||e.contentEditable==="true")}function _2(e){var n=R1(),r=e.focusedElem,o=e.selectionRange;if(n!==r&&r&&r.ownerDocument&&B1(r.ownerDocument.documentElement,r)){if(o!==null&&w_(r)){if(n=o.start,e=o.end,e===void 0&&(e=n),"selectionStart"in r)r.selectionStart=n,r.selectionEnd=Math.min(e,r.value.length);else if(e=(n=r.ownerDocument||document)&&n.defaultView||window,e.getSelection){e=e.getSelection();var l=r.textContent.length,p=Math.min(o.start,l);o=o.end===void 0?p:Math.min(o.end,l),!e.extend&&p>o&&(l=o,o=p,p=l),l=tv(r,p);var _=tv(r,o);l&&_&&(e.rangeCount!==1||e.anchorNode!==l.node||e.anchorOffset!==l.offset||e.focusNode!==_.node||e.focusOffset!==_.offset)&&(n=n.createRange(),n.setStart(l.node,l.offset),e.removeAllRanges(),p>o?(e.addRange(n),e.extend(_.node,_.offset)):(n.setEnd(_.node,_.offset),e.addRange(n)))}}for(n=[],e=r;e=e.parentNode;)e.nodeType===1&&n.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof r.focus=="function"&&r.focus(),r=0;r=document.documentMode,El=null,Eg=null,gp=null,Cg=!1;function nv(e,n,r){var o=r.window===r?r.document:r.nodeType===9?r:r.ownerDocument;Cg||El==null||El!==ch(o)||(o=El,"selectionStart"in o&&w_(o)?o={start:o.selectionStart,end:o.selectionEnd}:(o=(o.ownerDocument&&o.ownerDocument.defaultView||window).getSelection(),o={anchorNode:o.anchorNode,anchorOffset:o.anchorOffset,focusNode:o.focusNode,focusOffset:o.focusOffset}),gp&&Cp(gp,o)||(gp=o,o=yh(Eg,"onSelect"),0Pl||(e.current=zg[Pl],zg[Pl]=null,Pl--)}function qn(e,n){Pl++,zg[Pl]=e.current,e.current=n}var gs={},jr=ys(gs),ri=ys(!1),Zs=gs;function Ul(e,n){var r=e.type.contextTypes;if(!r)return gs;var o=e.stateNode;if(o&&o.__reactInternalMemoizedUnmaskedChildContext===n)return o.__reactInternalMemoizedMaskedChildContext;var l={},p;for(p in r)l[p]=n[p];return o&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=n,e.__reactInternalMemoizedMaskedChildContext=l),l}function ii(e){return e=e.childContextTypes,e!=null}function vh(){Xn(ri),Xn(jr)}function uv(e,n,r){if(jr.current!==gs)throw Error(gt(168));qn(jr,n),qn(ri,r)}function K1(e,n,r){var o=e.stateNode;if(n=n.childContextTypes,typeof o.getChildContext!="function")return r;o=o.getChildContext();for(var l in o)if(!(l in n))throw Error(gt(108,pT(e)||"Unknown",l));return tr({},r,o)}function Mh(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||gs,Zs=jr.current,qn(jr,e),qn(ri,ri.current),!0}function dv(e,n,r){var o=e.stateNode;if(!o)throw Error(gt(169));r?(e=K1(e,n,Zs),o.__reactInternalMemoizedMergedChildContext=e,Xn(ri),Xn(jr),qn(jr,e)):Xn(ri),qn(ri,r)}var Mo=null,jh=!1,Jm=!1;function Q1(e){Mo===null?Mo=[e]:Mo.push(e)}function $2(e){jh=!0,Q1(e)}function ws(){if(!Jm&&Mo!==null){Jm=!0;var e=0,n=Bn;try{var r=Mo;for(Bn=1;e>=_,l-=_,bo=1<<32-Gi(n)+l|r<z?(me=N,N=null):me=N.sibling;var he=G(A,N,L[z],Z);if(he===null){N===null&&(N=me);break}e&&N&&he.alternate===null&&n(A,N),P=p(he,P,z),D===null?V=he:D.sibling=he,D=he,N=me}if(z===L.length)return r(A,N),Zn&&Gs(A,z),V;if(N===null){for(;zz?(me=N,N=null):me=N.sibling;var ke=G(A,N,he.value,Z);if(ke===null){N===null&&(N=me);break}e&&N&&ke.alternate===null&&n(A,N),P=p(ke,P,z),D===null?V=ke:D.sibling=ke,D=ke,N=me}if(he.done)return r(A,N),Zn&&Gs(A,z),V;if(N===null){for(;!he.done;z++,he=L.next())he=S(A,he.value,Z),he!==null&&(P=p(he,P,z),D===null?V=he:D.sibling=he,D=he);return Zn&&Gs(A,z),V}for(N=o(A,N);!he.done;z++,he=L.next())he=J(N,A,z,he.value,Z),he!==null&&(e&&he.alternate!==null&&N.delete(he.key===null?z:he.key),P=p(he,P,z),D===null?V=he:D.sibling=he,D=he);return e&&N.forEach(function($e){return n(A,$e)}),Zn&&Gs(A,z),V}function X(A,P,L,Z){if(typeof L=="object"&&L!==null&&L.type===Sl&&L.key===null&&(L=L.props.children),typeof L=="object"&&L!==null){switch(L.$$typeof){case Df:e:{for(var V=L.key,D=P;D!==null;){if(D.key===V){if(V=L.type,V===Sl){if(D.tag===7){r(A,D.sibling),P=l(D,L.props.children),P.return=A,A=P;break e}}else if(D.elementType===V||typeof V=="object"&&V!==null&&V.$$typeof===ts&&fv(V)===D.type){r(A,D.sibling),P=l(D,L.props),P.ref=ip(A,D,L),P.return=A,A=P;break e}r(A,D);break}else n(A,D);D=D.sibling}L.type===Sl?(P=Ys(L.props.children,A.mode,Z,L.key),P.return=A,A=P):(Z=uh(L.type,L.key,L.props,null,A.mode,Z),Z.ref=ip(A,P,L),Z.return=A,A=Z)}return _(A);case Tl:e:{for(D=L.key;P!==null;){if(P.key===D)if(P.tag===4&&P.stateNode.containerInfo===L.containerInfo&&P.stateNode.implementation===L.implementation){r(A,P.sibling),P=l(P,L.children||[]),P.return=A,A=P;break e}else{r(A,P);break}else n(A,P);P=P.sibling}P=ag(L,A.mode,Z),P.return=A,A=P}return _(A);case ts:return D=L._init,X(A,P,D(L._payload),Z)}if(lp(L))return te(A,P,L,Z);if(Jc(L))return ne(A,P,L,Z);Hf(A,L)}return typeof L=="string"&&L!==""||typeof L=="number"?(L=""+L,P!==null&&P.tag===6?(r(A,P.sibling),P=l(P,L),P.return=A,A=P):(r(A,P),P=sg(L,A.mode,Z),P.return=A,A=P),_(A)):r(A,P)}return X}var Gl=J1(!0),eM=J1(!1),Th=ys(null),Sh=null,Fl=null,x_=null;function T_(){x_=Fl=Sh=null}function S_(e){var n=Th.current;Xn(Th),e._currentValue=n}function Lg(e,n,r){for(;e!==null;){var o=e.alternate;if((e.childLanes&n)!==n?(e.childLanes|=n,o!==null&&(o.childLanes|=n)):o!==null&&(o.childLanes&n)!==n&&(o.childLanes|=n),e===r)break;e=e.return}}function Nl(e,n){Sh=e,x_=Fl=null,e=e.dependencies,e!==null&&e.firstContext!==null&&(e.lanes&n&&(ni=!0),e.firstContext=null)}function Ai(e){var n=e._currentValue;if(x_!==e)if(e={context:e,memoizedValue:n,next:null},Fl===null){if(Sh===null)throw Error(gt(308));Fl=e,Sh.dependencies={lanes:0,firstContext:e}}else Fl=Fl.next=e;return n}var Ks=null;function k_(e){Ks===null?Ks=[e]:Ks.push(e)}function tM(e,n,r,o){var l=n.interleaved;return l===null?(r.next=r,k_(n)):(r.next=l.next,l.next=r),n.interleaved=r,Eo(e,o)}function Eo(e,n){e.lanes|=n;var r=e.alternate;for(r!==null&&(r.lanes|=n),r=e,e=e.return;e!==null;)e.childLanes|=n,r=e.alternate,r!==null&&(r.childLanes|=n),r=e,e=e.return;return r.tag===3?r.stateNode:null}var ns=!1;function E_(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function nM(e,n){e=e.updateQueue,n.updateQueue===e&&(n.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function To(e,n){return{eventTime:e,lane:n,tag:0,payload:null,callback:null,next:null}}function cs(e,n,r){var o=e.updateQueue;if(o===null)return null;if(o=o.shared,In&2){var l=o.pending;return l===null?n.next=n:(n.next=l.next,l.next=n),o.pending=n,Eo(e,r)}return l=o.interleaved,l===null?(n.next=n,k_(o)):(n.next=l.next,l.next=n),o.interleaved=n,Eo(e,r)}function rh(e,n,r){if(n=n.updateQueue,n!==null&&(n=n.shared,(r&4194240)!==0)){var o=n.lanes;o&=e.pendingLanes,r|=o,n.lanes=r,p_(e,r)}}function hv(e,n){var r=e.updateQueue,o=e.alternate;if(o!==null&&(o=o.updateQueue,r===o)){var l=null,p=null;if(r=r.firstBaseUpdate,r!==null){do{var _={eventTime:r.eventTime,lane:r.lane,tag:r.tag,payload:r.payload,callback:r.callback,next:null};p===null?l=p=_:p=p.next=_,r=r.next}while(r!==null);p===null?l=p=n:p=p.next=n}else l=p=n;r={baseState:o.baseState,firstBaseUpdate:l,lastBaseUpdate:p,shared:o.shared,effects:o.effects},e.updateQueue=r;return}e=r.lastBaseUpdate,e===null?r.firstBaseUpdate=n:e.next=n,r.lastBaseUpdate=n}function kh(e,n,r,o){var l=e.updateQueue;ns=!1;var p=l.firstBaseUpdate,_=l.lastBaseUpdate,C=l.shared.pending;if(C!==null){l.shared.pending=null;var M=C,b=M.next;M.next=null,_===null?p=b:_.next=b,_=M;var F=e.alternate;F!==null&&(F=F.updateQueue,C=F.lastBaseUpdate,C!==_&&(C===null?F.firstBaseUpdate=b:C.next=b,F.lastBaseUpdate=M))}if(p!==null){var S=l.baseState;_=0,F=b=M=null,C=p;do{var G=C.lane,J=C.eventTime;if((o&G)===G){F!==null&&(F=F.next={eventTime:J,lane:0,tag:C.tag,payload:C.payload,callback:C.callback,next:null});e:{var te=e,ne=C;switch(G=n,J=r,ne.tag){case 1:if(te=ne.payload,typeof te=="function"){S=te.call(J,S,G);break e}S=te;break e;case 3:te.flags=te.flags&-65537|128;case 0:if(te=ne.payload,G=typeof te=="function"?te.call(J,S,G):te,G==null)break e;S=tr({},S,G);break e;case 2:ns=!0}}C.callback!==null&&C.lane!==0&&(e.flags|=64,G=l.effects,G===null?l.effects=[C]:G.push(C))}else J={eventTime:J,lane:G,tag:C.tag,payload:C.payload,callback:C.callback,next:null},F===null?(b=F=J,M=S):F=F.next=J,_|=G;if(C=C.next,C===null){if(C=l.shared.pending,C===null)break;G=C,C=G.next,G.next=null,l.lastBaseUpdate=G,l.shared.pending=null}}while(!0);if(F===null&&(M=S),l.baseState=M,l.firstBaseUpdate=b,l.lastBaseUpdate=F,n=l.shared.interleaved,n!==null){l=n;do _|=l.lane,l=l.next;while(l!==n)}else p===null&&(l.shared.lanes=0);ta|=_,e.lanes=_,e.memoizedState=S}}function mv(e,n,r){if(e=n.effects,n.effects=null,e!==null)for(n=0;nr?r:4,e(!0);var o=tg.transition;tg.transition={};try{e(!1),n()}finally{Bn=r,tg.transition=o}}function wM(){return Ii().memoizedState}function F2(e,n,r){var o=fs(e);if(r={lane:o,action:r,hasEagerState:!1,eagerState:null,next:null},vM(e))MM(n,r);else if(r=tM(e,n,r,o),r!==null){var l=Xr();qi(r,e,o,l),bM(r,n,o)}}function z2(e,n,r){var o=fs(e),l={lane:o,action:r,hasEagerState:!1,eagerState:null,next:null};if(vM(e))MM(n,l);else{var p=e.alternate;if(e.lanes===0&&(p===null||p.lanes===0)&&(p=n.lastRenderedReducer,p!==null))try{var _=n.lastRenderedState,C=p(_,r);if(l.hasEagerState=!0,l.eagerState=C,Hi(C,_)){var M=n.interleaved;M===null?(l.next=l,k_(n)):(l.next=M.next,M.next=l),n.interleaved=l;return}}catch{}finally{}r=tM(e,n,l,o),r!==null&&(l=Xr(),qi(r,e,o,l),bM(r,n,o))}}function vM(e){var n=e.alternate;return e===er||n!==null&&n===er}function MM(e,n){_p=Ch=!0;var r=e.pending;r===null?n.next=n:(n.next=r.next,r.next=n),e.pending=n}function bM(e,n,r){if(r&4194240){var o=n.lanes;o&=e.pendingLanes,r|=o,n.lanes=r,p_(e,r)}}var $h={readContext:Ai,useCallback:Br,useContext:Br,useEffect:Br,useImperativeHandle:Br,useInsertionEffect:Br,useLayoutEffect:Br,useMemo:Br,useReducer:Br,useRef:Br,useState:Br,useDebugValue:Br,useDeferredValue:Br,useTransition:Br,useMutableSource:Br,useSyncExternalStore:Br,useId:Br,unstable_isNewReconciler:!1},O2={readContext:Ai,useCallback:function(e,n){return no().memoizedState=[e,n===void 0?null:n],e},useContext:Ai,useEffect:_v,useImperativeHandle:function(e,n,r){return r=r!=null?r.concat([e]):null,oh(4194308,4,hM.bind(null,n,e),r)},useLayoutEffect:function(e,n){return oh(4194308,4,e,n)},useInsertionEffect:function(e,n){return oh(4,2,e,n)},useMemo:function(e,n){var r=no();return n=n===void 0?null:n,e=e(),r.memoizedState=[e,n],e},useReducer:function(e,n,r){var o=no();return n=r!==void 0?r(n):n,o.memoizedState=o.baseState=n,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:n},o.queue=e,e=e.dispatch=F2.bind(null,er,e),[o.memoizedState,e]},useRef:function(e){var n=no();return e={current:e},n.memoizedState=e},useState:gv,useDebugValue:O_,useDeferredValue:function(e){return no().memoizedState=e},useTransition:function(){var e=gv(!1),n=e[0];return e=I2.bind(null,e[1]),no().memoizedState=e,[n,e]},useMutableSource:function(){},useSyncExternalStore:function(e,n,r){var o=er,l=no();if(Zn){if(r===void 0)throw Error(gt(407));r=r()}else{if(r=n(),Sr===null)throw Error(gt(349));ea&30||sM(o,n,r)}l.memoizedState=r;var p={value:r,getSnapshot:n};return l.queue=p,_v(lM.bind(null,o,p,e),[e]),o.flags|=2048,Dp(9,aM.bind(null,o,p,r,n),void 0,null),r},useId:function(){var e=no(),n=Sr.identifierPrefix;if(Zn){var r=xo,o=bo;r=(o&~(1<<32-Gi(o)-1)).toString(32)+r,n=":"+n+"R"+r,r=zp++,0<\/script>",e=e.removeChild(e.firstChild)):typeof o.is=="string"?e=_.createElement(r,{is:o.is}):(e=_.createElement(r),r==="select"&&(_=e,o.multiple?_.multiple=!0:o.size&&(_.size=o.size))):e=_.createElementNS(e,r),e[ro]=n,e[Ap]=o,IM(e,n,!1,!1),n.stateNode=e;e:{switch(_=wg(r,o),r){case"dialog":Kn("cancel",e),Kn("close",e),l=o;break;case"iframe":case"object":case"embed":Kn("load",e),l=o;break;case"video":case"audio":for(l=0;lKl&&(n.flags|=128,o=!0,op(p,!1),n.lanes=4194304)}else{if(!o)if(e=Eh(_),e!==null){if(n.flags|=128,o=!0,r=e.updateQueue,r!==null&&(n.updateQueue=r,n.flags|=4),op(p,!0),p.tail===null&&p.tailMode==="hidden"&&!_.alternate&&!Zn)return Rr(n),null}else 2*lr()-p.renderingStartTime>Kl&&r!==1073741824&&(n.flags|=128,o=!0,op(p,!1),n.lanes=4194304);p.isBackwards?(_.sibling=n.child,n.child=_):(r=p.last,r!==null?r.sibling=_:n.child=_,p.last=_)}return p.tail!==null?(n=p.tail,p.rendering=n,p.tail=n.sibling,p.renderingStartTime=lr(),n.sibling=null,r=Jn.current,qn(Jn,o?r&1|2:r&1),n):(Rr(n),null);case 22:case 23:return j_(),o=n.memoizedState!==null,e!==null&&e.memoizedState!==null!==o&&(n.flags|=8192),o&&n.mode&1?ci&1073741824&&(Rr(n),n.subtreeFlags&6&&(n.flags|=8192)):Rr(n),null;case 24:return null;case 25:return null}throw Error(gt(156,n.tag))}function U2(e,n){switch(M_(n),n.tag){case 1:return ii(n.type)&&vh(),e=n.flags,e&65536?(n.flags=e&-65537|128,n):null;case 3:return ql(),Xn(ri),Xn(jr),P_(),e=n.flags,e&65536&&!(e&128)?(n.flags=e&-65537|128,n):null;case 5:return $_(n),null;case 13:if(Xn(Jn),e=n.memoizedState,e!==null&&e.dehydrated!==null){if(n.alternate===null)throw Error(gt(340));Wl()}return e=n.flags,e&65536?(n.flags=e&-65537|128,n):null;case 19:return Xn(Jn),null;case 4:return ql(),null;case 10:return S_(n.type._context),null;case 22:case 23:return j_(),null;case 24:return null;default:return null}}var Qf=!1,Nr=!1,W2=typeof WeakSet=="function"?WeakSet:Set,Rt=null;function zl(e,n){var r=e.ref;if(r!==null)if(typeof r=="function")try{r(null)}catch(o){sr(e,n,o)}else r.current=null}function qg(e,n,r){try{r()}catch(o){sr(e,n,o)}}var Cv=!1;function G2(e,n){if($g=gh,e=R1(),w_(e)){if("selectionStart"in e)var r={start:e.selectionStart,end:e.selectionEnd};else e:{r=(r=e.ownerDocument)&&r.defaultView||window;var o=r.getSelection&&r.getSelection();if(o&&o.rangeCount!==0){r=o.anchorNode;var l=o.anchorOffset,p=o.focusNode;o=o.focusOffset;try{r.nodeType,p.nodeType}catch{r=null;break e}var _=0,C=-1,M=-1,b=0,F=0,S=e,G=null;t:for(;;){for(var J;S!==r||l!==0&&S.nodeType!==3||(C=_+l),S!==p||o!==0&&S.nodeType!==3||(M=_+o),S.nodeType===3&&(_+=S.nodeValue.length),(J=S.firstChild)!==null;)G=S,S=J;for(;;){if(S===e)break t;if(G===r&&++b===l&&(C=_),G===p&&++F===o&&(M=_),(J=S.nextSibling)!==null)break;S=G,G=S.parentNode}S=J}r=C===-1||M===-1?null:{start:C,end:M}}else r=null}r=r||{start:0,end:0}}else r=null;for(Pg={focusedElem:e,selectionRange:r},gh=!1,Rt=n;Rt!==null;)if(n=Rt,e=n.child,(n.subtreeFlags&1028)!==0&&e!==null)e.return=n,Rt=e;else for(;Rt!==null;){n=Rt;try{var te=n.alternate;if(n.flags&1024)switch(n.tag){case 0:case 11:case 15:break;case 1:if(te!==null){var ne=te.memoizedProps,X=te.memoizedState,A=n.stateNode,P=A.getSnapshotBeforeUpdate(n.elementType===n.type?ne:Vi(n.type,ne),X);A.__reactInternalSnapshotBeforeUpdate=P}break;case 3:var L=n.stateNode.containerInfo;L.nodeType===1?L.textContent="":L.nodeType===9&&L.documentElement&&L.removeChild(L.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(gt(163))}}catch(Z){sr(n,n.return,Z)}if(e=n.sibling,e!==null){e.return=n.return,Rt=e;break}Rt=n.return}return te=Cv,Cv=!1,te}function yp(e,n,r){var o=n.updateQueue;if(o=o!==null?o.lastEffect:null,o!==null){var l=o=o.next;do{if((l.tag&e)===e){var p=l.destroy;l.destroy=void 0,p!==void 0&&qg(n,r,p)}l=l.next}while(l!==o)}}function Wh(e,n){if(n=n.updateQueue,n=n!==null?n.lastEffect:null,n!==null){var r=n=n.next;do{if((r.tag&e)===e){var o=r.create;r.destroy=o()}r=r.next}while(r!==n)}}function Hg(e){var n=e.ref;if(n!==null){var r=e.stateNode;switch(e.tag){case 5:e=r;break;default:e=r}typeof n=="function"?n(e):n.current=e}}function OM(e){var n=e.alternate;n!==null&&(e.alternate=null,OM(n)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(n=e.stateNode,n!==null&&(delete n[ro],delete n[Ap],delete n[Fg],delete n[E2],delete n[C2])),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 DM(e){return e.tag===5||e.tag===3||e.tag===4}function $v(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||DM(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 Kg(e,n,r){var o=e.tag;if(o===5||o===6)e=e.stateNode,n?r.nodeType===8?r.parentNode.insertBefore(e,n):r.insertBefore(e,n):(r.nodeType===8?(n=r.parentNode,n.insertBefore(e,r)):(n=r,n.appendChild(e)),r=r._reactRootContainer,r!=null||n.onclick!==null||(n.onclick=wh));else if(o!==4&&(e=e.child,e!==null))for(Kg(e,n,r),e=e.sibling;e!==null;)Kg(e,n,r),e=e.sibling}function Qg(e,n,r){var o=e.tag;if(o===5||o===6)e=e.stateNode,n?r.insertBefore(e,n):r.appendChild(e);else if(o!==4&&(e=e.child,e!==null))for(Qg(e,n,r),e=e.sibling;e!==null;)Qg(e,n,r),e=e.sibling}var Ar=null,Ui=!1;function es(e,n,r){for(r=r.child;r!==null;)LM(e,n,r),r=r.sibling}function LM(e,n,r){if(io&&typeof io.onCommitFiberUnmount=="function")try{io.onCommitFiberUnmount(Dh,r)}catch{}switch(r.tag){case 5:Nr||zl(r,n);case 6:var o=Ar,l=Ui;Ar=null,es(e,n,r),Ar=o,Ui=l,Ar!==null&&(Ui?(e=Ar,r=r.stateNode,e.nodeType===8?e.parentNode.removeChild(r):e.removeChild(r)):Ar.removeChild(r.stateNode));break;case 18:Ar!==null&&(Ui?(e=Ar,r=r.stateNode,e.nodeType===8?Zm(e.parentNode,r):e.nodeType===1&&Zm(e,r),kp(e)):Zm(Ar,r.stateNode));break;case 4:o=Ar,l=Ui,Ar=r.stateNode.containerInfo,Ui=!0,es(e,n,r),Ar=o,Ui=l;break;case 0:case 11:case 14:case 15:if(!Nr&&(o=r.updateQueue,o!==null&&(o=o.lastEffect,o!==null))){l=o=o.next;do{var p=l,_=p.destroy;p=p.tag,_!==void 0&&(p&2||p&4)&&qg(r,n,_),l=l.next}while(l!==o)}es(e,n,r);break;case 1:if(!Nr&&(zl(r,n),o=r.stateNode,typeof o.componentWillUnmount=="function"))try{o.props=r.memoizedProps,o.state=r.memoizedState,o.componentWillUnmount()}catch(C){sr(r,n,C)}es(e,n,r);break;case 21:es(e,n,r);break;case 22:r.mode&1?(Nr=(o=Nr)||r.memoizedState!==null,es(e,n,r),Nr=o):es(e,n,r);break;default:es(e,n,r)}}function Pv(e){var n=e.updateQueue;if(n!==null){e.updateQueue=null;var r=e.stateNode;r===null&&(r=e.stateNode=new W2),n.forEach(function(o){var l=eS.bind(null,e,o);r.has(o)||(r.add(o),o.then(l,l))})}}function Ni(e,n){var r=n.deletions;if(r!==null)for(var o=0;ol&&(l=_),o&=~p}if(o=l,o=lr()-o,o=(120>o?120:480>o?480:1080>o?1080:1920>o?1920:3e3>o?3e3:4320>o?4320:1960*H2(o/1960))-o,10e?16:e,ss===null)var o=!1;else{if(e=ss,ss=null,Ih=0,In&6)throw Error(gt(331));var l=In;for(In|=4,Rt=e.current;Rt!==null;){var p=Rt,_=p.child;if(Rt.flags&16){var C=p.deletions;if(C!==null){for(var M=0;Mlr()-R_?Xs(e,0):B_|=r),oi(e,n)}function GM(e,n){n===0&&(e.mode&1?(n=Nf,Nf<<=1,!(Nf&130023424)&&(Nf=4194304)):n=1);var r=Xr();e=Eo(e,n),e!==null&&(Rp(e,n,r),oi(e,r))}function J2(e){var n=e.memoizedState,r=0;n!==null&&(r=n.retryLane),GM(e,r)}function eS(e,n){var r=0;switch(e.tag){case 13:var o=e.stateNode,l=e.memoizedState;l!==null&&(r=l.retryLane);break;case 19:o=e.stateNode;break;default:throw Error(gt(314))}o!==null&&o.delete(n),GM(e,r)}var qM;qM=function(e,n,r){if(e!==null)if(e.memoizedProps!==n.pendingProps||ri.current)ni=!0;else{if(!(e.lanes&r)&&!(n.flags&128))return ni=!1,j2(e,n,r);ni=!!(e.flags&131072)}else ni=!1,Zn&&n.flags&1048576&&X1(n,xh,n.index);switch(n.lanes=0,n.tag){case 2:var o=n.type;sh(e,n),e=n.pendingProps;var l=Ul(n,jr.current);Nl(n,r),l=I_(null,n,o,e,l,r);var p=F_();return n.flags|=1,typeof l=="object"&&l!==null&&typeof l.render=="function"&&l.$$typeof===void 0?(n.tag=1,n.memoizedState=null,n.updateQueue=null,ii(o)?(p=!0,Mh(n)):p=!1,n.memoizedState=l.state!==null&&l.state!==void 0?l.state:null,E_(n),l.updater=Uh,n.stateNode=l,l._reactInternals=n,Rg(n,o,e,r),n=Vg(null,n,o,!0,p,r)):(n.tag=0,Zn&&p&&v_(n),Qr(null,n,l,r),n=n.child),n;case 16:o=n.elementType;e:{switch(sh(e,n),e=n.pendingProps,l=o._init,o=l(o._payload),n.type=o,l=n.tag=nS(o),e=Vi(o,e),l){case 0:n=jg(null,n,o,e,r);break e;case 1:n=Sv(null,n,o,e,r);break e;case 11:n=xv(null,n,o,e,r);break e;case 14:n=Tv(null,n,o,Vi(o.type,e),r);break e}throw Error(gt(306,o,""))}return n;case 0:return o=n.type,l=n.pendingProps,l=n.elementType===o?l:Vi(o,l),jg(e,n,o,l,r);case 1:return o=n.type,l=n.pendingProps,l=n.elementType===o?l:Vi(o,l),Sv(e,n,o,l,r);case 3:e:{if($M(n),e===null)throw Error(gt(387));o=n.pendingProps,p=n.memoizedState,l=p.element,nM(e,n),kh(n,o,null,r);var _=n.memoizedState;if(o=_.element,p.isDehydrated)if(p={element:o,isDehydrated:!1,cache:_.cache,pendingSuspenseBoundaries:_.pendingSuspenseBoundaries,transitions:_.transitions},n.updateQueue.baseState=p,n.memoizedState=p,n.flags&256){l=Hl(Error(gt(423)),n),n=kv(e,n,o,r,l);break e}else if(o!==l){l=Hl(Error(gt(424)),n),n=kv(e,n,o,r,l);break e}else for(pi=ds(n.stateNode.containerInfo.firstChild),fi=n,Zn=!0,Wi=null,r=eM(n,null,o,r),n.child=r;r;)r.flags=r.flags&-3|4096,r=r.sibling;else{if(Wl(),o===l){n=Co(e,n,r);break e}Qr(e,n,o,r)}n=n.child}return n;case 5:return rM(n),e===null&&Dg(n),o=n.type,l=n.pendingProps,p=e!==null?e.memoizedProps:null,_=l.children,Ag(o,l)?_=null:p!==null&&Ag(o,p)&&(n.flags|=32),CM(e,n),Qr(e,n,_,r),n.child;case 6:return e===null&&Dg(n),null;case 13:return PM(e,n,r);case 4:return C_(n,n.stateNode.containerInfo),o=n.pendingProps,e===null?n.child=Gl(n,null,o,r):Qr(e,n,o,r),n.child;case 11:return o=n.type,l=n.pendingProps,l=n.elementType===o?l:Vi(o,l),xv(e,n,o,l,r);case 7:return Qr(e,n,n.pendingProps,r),n.child;case 8:return Qr(e,n,n.pendingProps.children,r),n.child;case 12:return Qr(e,n,n.pendingProps.children,r),n.child;case 10:e:{if(o=n.type._context,l=n.pendingProps,p=n.memoizedProps,_=l.value,qn(Th,o._currentValue),o._currentValue=_,p!==null)if(Hi(p.value,_)){if(p.children===l.children&&!ri.current){n=Co(e,n,r);break e}}else for(p=n.child,p!==null&&(p.return=n);p!==null;){var C=p.dependencies;if(C!==null){_=p.child;for(var M=C.firstContext;M!==null;){if(M.context===o){if(p.tag===1){M=To(-1,r&-r),M.tag=2;var b=p.updateQueue;if(b!==null){b=b.shared;var F=b.pending;F===null?M.next=M:(M.next=F.next,F.next=M),b.pending=M}}p.lanes|=r,M=p.alternate,M!==null&&(M.lanes|=r),Lg(p.return,r,n),C.lanes|=r;break}M=M.next}}else if(p.tag===10)_=p.type===n.type?null:p.child;else if(p.tag===18){if(_=p.return,_===null)throw Error(gt(341));_.lanes|=r,C=_.alternate,C!==null&&(C.lanes|=r),Lg(_,r,n),_=p.sibling}else _=p.child;if(_!==null)_.return=p;else for(_=p;_!==null;){if(_===n){_=null;break}if(p=_.sibling,p!==null){p.return=_.return,_=p;break}_=_.return}p=_}Qr(e,n,l.children,r),n=n.child}return n;case 9:return l=n.type,o=n.pendingProps.children,Nl(n,r),l=Ai(l),o=o(l),n.flags|=1,Qr(e,n,o,r),n.child;case 14:return o=n.type,l=Vi(o,n.pendingProps),l=Vi(o.type,l),Tv(e,n,o,l,r);case 15:return kM(e,n,n.type,n.pendingProps,r);case 17:return o=n.type,l=n.pendingProps,l=n.elementType===o?l:Vi(o,l),sh(e,n),n.tag=1,ii(o)?(e=!0,Mh(n)):e=!1,Nl(n,r),xM(n,o,l),Rg(n,o,l,r),Vg(null,n,o,!0,e,r);case 19:return AM(e,n,r);case 22:return EM(e,n,r)}throw Error(gt(156,n.tag))};function HM(e,n){return v1(e,n)}function tS(e,n,r,o){this.tag=e,this.key=r,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=n,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=o,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function $i(e,n,r,o){return new tS(e,n,r,o)}function U_(e){return e=e.prototype,!(!e||!e.isReactComponent)}function nS(e){if(typeof e=="function")return U_(e)?1:0;if(e!=null){if(e=e.$$typeof,e===l_)return 11;if(e===u_)return 14}return 2}function hs(e,n){var r=e.alternate;return r===null?(r=$i(e.tag,n,e.key,e.mode),r.elementType=e.elementType,r.type=e.type,r.stateNode=e.stateNode,r.alternate=e,e.alternate=r):(r.pendingProps=n,r.type=e.type,r.flags=0,r.subtreeFlags=0,r.deletions=null),r.flags=e.flags&14680064,r.childLanes=e.childLanes,r.lanes=e.lanes,r.child=e.child,r.memoizedProps=e.memoizedProps,r.memoizedState=e.memoizedState,r.updateQueue=e.updateQueue,n=e.dependencies,r.dependencies=n===null?null:{lanes:n.lanes,firstContext:n.firstContext},r.sibling=e.sibling,r.index=e.index,r.ref=e.ref,r}function uh(e,n,r,o,l,p){var _=2;if(o=e,typeof e=="function")U_(e)&&(_=1);else if(typeof e=="string")_=5;else e:switch(e){case Sl:return Ys(r.children,l,p,n);case a_:_=8,l|=8;break;case ug:return e=$i(12,r,n,l|2),e.elementType=ug,e.lanes=p,e;case dg:return e=$i(13,r,n,l),e.elementType=dg,e.lanes=p,e;case cg:return e=$i(19,r,n,l),e.elementType=cg,e.lanes=p,e;case r1:return qh(r,l,p,n);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case t1:_=10;break e;case n1:_=9;break e;case l_:_=11;break e;case u_:_=14;break e;case ts:_=16,o=null;break e}throw Error(gt(130,e==null?e:typeof e,""))}return n=$i(_,r,n,l),n.elementType=e,n.type=o,n.lanes=p,n}function Ys(e,n,r,o){return e=$i(7,e,o,n),e.lanes=r,e}function qh(e,n,r,o){return e=$i(22,e,o,n),e.elementType=r1,e.lanes=r,e.stateNode={isHidden:!1},e}function sg(e,n,r){return e=$i(6,e,null,n),e.lanes=r,e}function ag(e,n,r){return n=$i(4,e.children!==null?e.children:[],e.key,n),n.lanes=r,n.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},n}function rS(e,n,r,o,l){this.tag=n,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=jm(0),this.expirationTimes=jm(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=jm(0),this.identifierPrefix=o,this.onRecoverableError=l,this.mutableSourceEagerHydrationData=null}function W_(e,n,r,o,l,p,_,C,M){return e=new rS(e,n,r,C,M),n===1?(n=1,p===!0&&(n|=8)):n=0,p=$i(3,null,null,n),e.current=p,p.stateNode=e,p.memoizedState={element:o,isDehydrated:r,cache:null,transitions:null,pendingSuspenseBoundaries:null},E_(p),e}function iS(e,n,r){var o=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(YM)}catch(e){console.error(e)}}YM(),Yv.exports=mi;var uS=Yv.exports,ZM,Bv=uS;ZM=Bv.createRoot,Bv.hydrateRoot;var wo={},dS={"./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm":(e,n,r)=>{e.exports=r.p+"ort-wasm-simd-threaded.jsep.wasm"},"?2ce3":()=>{},"?7a2c":()=>{},"?a42a":()=>{},"?2b25":()=>{},"?569f":()=>{},"?3f59":()=>{},"?154a":()=>{},"./node_modules/@huggingface/jinja/dist/index.js":(e,n,r)=>{r.r(n),r.d(n,{Environment:()=>He,Interpreter:()=>dt,Template:()=>xt,parse:()=>Me,tokenize:()=>S});var o=Object.freeze({Text:"Text",NumericLiteral:"NumericLiteral",BooleanLiteral:"BooleanLiteral",StringLiteral:"StringLiteral",Identifier:"Identifier",Equals:"Equals",OpenParen:"OpenParen",CloseParen:"CloseParen",OpenStatement:"OpenStatement",CloseStatement:"CloseStatement",OpenExpression:"OpenExpression",CloseExpression:"CloseExpression",OpenSquareBracket:"OpenSquareBracket",CloseSquareBracket:"CloseSquareBracket",OpenCurlyBracket:"OpenCurlyBracket",CloseCurlyBracket:"CloseCurlyBracket",Comma:"Comma",Dot:"Dot",Colon:"Colon",Pipe:"Pipe",CallOperator:"CallOperator",AdditiveBinaryOperator:"AdditiveBinaryOperator",MultiplicativeBinaryOperator:"MultiplicativeBinaryOperator",ComparisonBinaryOperator:"ComparisonBinaryOperator",UnaryOperator:"UnaryOperator",Set:"Set",If:"If",For:"For",In:"In",Is:"Is",NotIn:"NotIn",Else:"Else",EndIf:"EndIf",ElseIf:"ElseIf",EndFor:"EndFor",And:"And",Or:"Or",Not:"UnaryOperator",Macro:"Macro",EndMacro:"EndMacro"}),l=Object.freeze({set:o.Set,for:o.For,in:o.In,is:o.Is,if:o.If,else:o.Else,endif:o.EndIf,elif:o.ElseIf,endfor:o.EndFor,and:o.And,or:o.Or,not:o.Not,"not in":o.NotIn,macro:o.Macro,endmacro:o.EndMacro,true:o.BooleanLiteral,false:o.BooleanLiteral,True:o.BooleanLiteral,False:o.BooleanLiteral}),p=class{constructor(O,ie){this.value=O,this.type=ie}};function _(O){return/\w/.test(O)}function C(O){return/[0-9]/.test(O)}var M=[["{%",o.OpenStatement],["%}",o.CloseStatement],["{{",o.OpenExpression],["}}",o.CloseExpression],["(",o.OpenParen],[")",o.CloseParen],["{",o.OpenCurlyBracket],["}",o.CloseCurlyBracket],["[",o.OpenSquareBracket],["]",o.CloseSquareBracket],[",",o.Comma],[".",o.Dot],[":",o.Colon],["|",o.Pipe],["<=",o.ComparisonBinaryOperator],[">=",o.ComparisonBinaryOperator],["==",o.ComparisonBinaryOperator],["!=",o.ComparisonBinaryOperator],["<",o.ComparisonBinaryOperator],[">",o.ComparisonBinaryOperator],["+",o.AdditiveBinaryOperator],["-",o.AdditiveBinaryOperator],["*",o.MultiplicativeBinaryOperator],["/",o.MultiplicativeBinaryOperator],["%",o.MultiplicativeBinaryOperator],["=",o.Equals]],b=new Map([["n",` +`],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function F(O,ie={}){return O.endsWith(` +`)&&(O=O.slice(0,-1)),O=O.replace(/{#.*?#}/gs,"{##}"),ie.lstrip_blocks&&(O=O.replace(/^[ \t]*({[#%])/gm,"$1")),ie.trim_blocks&&(O=O.replace(/([#%]})\n/g,"$1")),O.replace(/{##}/g,"").replace(/-%}\s*/g,"%}").replace(/\s*{%-/g,"{%").replace(/-}}\s*/g,"}}").replace(/\s*{{-/g,"{{")}function S(O,ie={}){var nt,At,_t;const q=[],de=F(O,ie);let ve=0;const et=Pe=>{let j="";for(;Pe(de[ve]);){if(de[ve]==="\\"){if(++ve,ve>=de.length)throw new SyntaxError("Unexpected end of input");const le=de[ve++],Te=b.get(le);if(Te===void 0)throw new SyntaxError(`Unexpected escaped character: ${le}`);j+=Te;continue}if(j+=de[ve++],ve>=de.length)throw new SyntaxError("Unexpected end of input")}return j};e:for(;ve0){q.push(new p(le,o.Text));continue}}et(le=>/\s/.test(le));const j=de[ve];if(j==="-"||j==="+"){const le=(At=q.at(-1))==null?void 0:At.type;if(le===o.Text||le===void 0)throw new SyntaxError(`Unexpected character: ${j}`);switch(le){case o.Identifier:case o.NumericLiteral:case o.BooleanLiteral:case o.StringLiteral:case o.CloseParen:case o.CloseSquareBracket:break;default:{++ve;const Te=et(C);q.push(new p(`${j}${Te}`,Te.length>0?o.NumericLiteral:o.UnaryOperator));continue}}}for(const[le,Te]of M)if(de.slice(ve,ve+le.length)===le){q.push(new p(le,Te)),ve+=le.length;continue e}if(j==="'"||j==='"'){++ve;const le=et(Te=>Te!==j);q.push(new p(le,o.StringLiteral)),++ve;continue}if(C(j)){const le=et(C);q.push(new p(le,o.NumericLiteral));continue}if(_(j)){const le=et(_),Te=Object.hasOwn(l,le)?l[le]:o.Identifier;Te===o.In&&((_t=q.at(-1))==null?void 0:_t.type)===o.Not?(q.pop(),q.push(new p("not in",o.NotIn))):q.push(new p(le,Te));continue}throw new SyntaxError(`Unexpected character: ${j}`)}return q}var G=class{constructor(){Ee(this,"type","Statement")}},J=class extends G{constructor(ie){super();Ee(this,"type","Program");this.body=ie}},te=class extends G{constructor(ie,q,de){super();Ee(this,"type","If");this.test=ie,this.body=q,this.alternate=de}},ne=class extends G{constructor(ie,q,de,ve){super();Ee(this,"type","For");this.loopvar=ie,this.iterable=q,this.body=de,this.defaultBlock=ve}},X=class extends G{constructor(ie,q){super();Ee(this,"type","Set");this.assignee=ie,this.value=q}},A=class extends G{constructor(ie,q,de){super();Ee(this,"type","Macro");this.name=ie,this.args=q,this.body=de}},P=class extends G{constructor(){super(...arguments);Ee(this,"type","Expression")}},L=class extends P{constructor(ie,q,de){super();Ee(this,"type","MemberExpression");this.object=ie,this.property=q,this.computed=de}},Z=class extends P{constructor(ie,q){super();Ee(this,"type","CallExpression");this.callee=ie,this.args=q}},V=class extends P{constructor(ie){super();Ee(this,"type","Identifier");this.value=ie}},D=class extends P{constructor(ie){super();Ee(this,"type","Literal");this.value=ie}},N=class extends D{constructor(){super(...arguments);Ee(this,"type","NumericLiteral")}},z=class extends D{constructor(){super(...arguments);Ee(this,"type","StringLiteral")}},me=class extends D{constructor(){super(...arguments);Ee(this,"type","BooleanLiteral")}},he=class extends D{constructor(){super(...arguments);Ee(this,"type","ArrayLiteral")}},ke=class extends D{constructor(){super(...arguments);Ee(this,"type","TupleLiteral")}},$e=class extends D{constructor(){super(...arguments);Ee(this,"type","ObjectLiteral")}},Ae=class extends P{constructor(ie,q,de){super();Ee(this,"type","BinaryExpression");this.operator=ie,this.left=q,this.right=de}},Je=class extends P{constructor(ie,q){super();Ee(this,"type","FilterExpression");this.operand=ie,this.filter=q}},Xe=class extends P{constructor(ie,q){super();Ee(this,"type","SelectExpression");this.iterable=ie,this.test=q}},pt=class extends P{constructor(ie,q,de){super();Ee(this,"type","TestExpression");this.operand=ie,this.negate=q,this.test=de}},xe=class extends P{constructor(ie,q){super();Ee(this,"type","UnaryExpression");this.operator=ie,this.argument=q}},H=class extends P{constructor(ie=void 0,q=void 0,de=void 0){super();Ee(this,"type","SliceExpression");this.start=ie,this.stop=q,this.step=de}},pe=class extends P{constructor(ie,q){super();Ee(this,"type","KeywordArgumentExpression");this.key=ie,this.value=q}};function Me(O){const ie=new J([]);let q=0;function de(tt,Ct){const Lt=O[q++];if(!Lt||Lt.type!==tt)throw new Error(`Parser Error: ${Ct}. ${Lt.type} !== ${tt}.`);return Lt}function ve(){switch(O[q].type){case o.Text:return At();case o.OpenStatement:return _t();case o.OpenExpression:return Pe();default:throw new SyntaxError(`Unexpected token type: ${O[q].type}`)}}function et(...tt){return q+tt.length<=O.length&&tt.some((Ct,Lt)=>Ct!==O[q+Lt].type)}function nt(...tt){return q+tt.length<=O.length&&tt.every((Ct,Lt)=>Ct===O[q+Lt].type)}function At(){return new z(de(o.Text,"Expected text token").value)}function _t(){de(o.OpenStatement,"Expected opening statement token");let tt;switch(O[q].type){case o.Set:++q,tt=j(),de(o.CloseStatement,"Expected closing statement token");break;case o.If:++q,tt=le(),de(o.OpenStatement,"Expected {% token"),de(o.EndIf,"Expected endif token"),de(o.CloseStatement,"Expected %} token");break;case o.Macro:++q,tt=Te(),de(o.OpenStatement,"Expected {% token"),de(o.EndMacro,"Expected endmacro token"),de(o.CloseStatement,"Expected %} token");break;case o.For:++q,tt=De(),de(o.OpenStatement,"Expected {% token"),de(o.EndFor,"Expected endfor token"),de(o.CloseStatement,"Expected %} token");break;default:throw new SyntaxError(`Unknown statement type: ${O[q].type}`)}return tt}function Pe(){de(o.OpenExpression,"Expected opening expression token");const tt=je();return de(o.CloseExpression,"Expected closing expression token"),tt}function j(){const tt=je();if(nt(o.Equals)){++q;const Ct=j();return new X(tt,Ct)}return tt}function le(){var nr,Fi,_i,Nn,cr,Vn,si,Fn;const tt=je();de(o.CloseStatement,"Expected closing statement token");const Ct=[],Lt=[];for(;!(((nr=O[q])==null?void 0:nr.type)===o.OpenStatement&&(((Fi=O[q+1])==null?void 0:Fi.type)===o.ElseIf||((_i=O[q+1])==null?void 0:_i.type)===o.Else||((Nn=O[q+1])==null?void 0:Nn.type)===o.EndIf));)Ct.push(ve());if(((cr=O[q])==null?void 0:cr.type)===o.OpenStatement&&((Vn=O[q+1])==null?void 0:Vn.type)!==o.EndIf)if(++q,nt(o.ElseIf))de(o.ElseIf,"Expected elseif token"),Lt.push(le());else for(de(o.Else,"Expected else token"),de(o.CloseStatement,"Expected closing statement token");!(((si=O[q])==null?void 0:si.type)===o.OpenStatement&&((Fn=O[q+1])==null?void 0:Fn.type)===o.EndIf);)Lt.push(ve());return new te(tt,Ct,Lt)}function Te(){const tt=Cn();if(tt.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");const Ct=jt();de(o.CloseStatement,"Expected closing statement token");const Lt=[];for(;et(o.OpenStatement,o.EndMacro);)Lt.push(ve());return new A(tt,Ct,Lt)}function Ne(tt=!1){const Ct=tt?Cn:je,Lt=[Ct()],nr=nt(o.Comma);for(;nr&&(++q,Lt.push(Ct()),!!nt(o.Comma)););return nr?new ke(Lt):Lt[0]}function De(){const tt=Ne(!0);if(!(tt instanceof V||tt instanceof ke))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${tt.type} instead`);de(o.In,"Expected `in` keyword following loop variable");const Ct=je();de(o.CloseStatement,"Expected closing statement token");const Lt=[];for(;et(o.OpenStatement,o.EndFor)&&et(o.OpenStatement,o.Else);)Lt.push(ve());const nr=[];if(nt(o.OpenStatement,o.Else))for(++q,++q,de(o.CloseStatement,"Expected closing statement token");et(o.OpenStatement,o.EndFor);)nr.push(ve());return new ne(tt,Ct,Lt,nr)}function je(){return ct()}function ct(){const tt=ot();if(nt(o.If)){++q;const Ct=ot();if(nt(o.Else)){++q;const Lt=ot();return new te(Ct,[tt],[Lt])}else return new Xe(tt,Ct)}return tt}function ot(){let tt=bt();for(;nt(o.Or);){const Ct=O[q];++q;const Lt=bt();tt=new Ae(Ct,tt,Lt)}return tt}function bt(){let tt=ft();for(;nt(o.And);){const Ct=O[q];++q;const Lt=ft();tt=new Ae(Ct,tt,Lt)}return tt}function ft(){let tt;for(;nt(o.Not);){const Ct=O[q];++q;const Lt=ft();tt=new xe(Ct,Lt)}return tt??St()}function St(){let tt=Nt();for(;nt(o.ComparisonBinaryOperator)||nt(o.In)||nt(o.NotIn);){const Ct=O[q];++q;const Lt=Nt();tt=new Ae(Ct,tt,Lt)}return tt}function Nt(){let tt=qt();for(;nt(o.AdditiveBinaryOperator);){const Ct=O[q];++q;const Lt=qt();tt=new Ae(Ct,tt,Lt)}return tt}function Ke(){const tt=Jt();return nt(o.OpenParen)?Vt(tt):tt}function Vt(tt){let Ct=new Z(tt,jt());return nt(o.OpenParen)&&(Ct=Vt(Ct)),Ct}function jt(){de(o.OpenParen,"Expected opening parenthesis for arguments list");const tt=Kt();return de(o.CloseParen,"Expected closing parenthesis for arguments list"),tt}function Kt(){const tt=[];for(;!nt(o.CloseParen);){let Ct=je();if(nt(o.Equals)){if(++q,!(Ct instanceof V))throw new SyntaxError("Expected identifier for keyword argument");const Lt=je();Ct=new pe(Ct,Lt)}tt.push(Ct),nt(o.Comma)&&++q}return tt}function Qt(){const tt=[];let Ct=!1;for(;!nt(o.CloseSquareBracket);)nt(o.Colon)?(tt.push(void 0),++q,Ct=!0):(tt.push(je()),nt(o.Colon)&&(++q,Ct=!0));if(tt.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(Ct){if(tt.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new H(...tt)}return tt[0]}function Jt(){let tt=Cn();for(;nt(o.Dot)||nt(o.OpenSquareBracket);){const Ct=O[q];++q;let Lt;const nr=Ct.type!==o.Dot;if(nr)Lt=Qt(),de(o.CloseSquareBracket,"Expected closing square bracket");else if(Lt=Cn(),Lt.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");tt=new L(tt,Lt,nr)}return tt}function qt(){let tt=En();for(;nt(o.MultiplicativeBinaryOperator);){const Ct=O[q];++q;const Lt=En();tt=new Ae(Ct,tt,Lt)}return tt}function En(){let tt=Hn();for(;nt(o.Is);){++q;const Ct=nt(o.Not);Ct&&++q;let Lt=Cn();if(Lt instanceof me&&(Lt=new V(Lt.value.toString())),!(Lt instanceof V))throw new SyntaxError("Expected identifier for the test");tt=new pt(tt,Ct,Lt)}return tt}function Hn(){let tt=Ke();for(;nt(o.Pipe);){++q;let Ct=Cn();if(!(Ct instanceof V))throw new SyntaxError("Expected identifier for the filter");nt(o.OpenParen)&&(Ct=Vt(Ct)),tt=new Je(tt,Ct)}return tt}function Cn(){const tt=O[q];switch(tt.type){case o.NumericLiteral:return++q,new N(Number(tt.value));case o.StringLiteral:return++q,new z(tt.value);case o.BooleanLiteral:return++q,new me(tt.value.toLowerCase()==="true");case o.Identifier:return++q,new V(tt.value);case o.OpenParen:{++q;const Ct=Ne();if(O[q].type!==o.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${O[q].type} instead`);return++q,Ct}case o.OpenSquareBracket:{++q;const Ct=[];for(;!nt(o.CloseSquareBracket);)Ct.push(je()),nt(o.Comma)&&++q;return++q,new he(Ct)}case o.OpenCurlyBracket:{++q;const Ct=new Map;for(;!nt(o.CloseCurlyBracket);){const Lt=je();de(o.Colon,"Expected colon between key and value in object literal");const nr=je();Ct.set(Lt,nr),nt(o.Comma)&&++q}return++q,new $e(Ct)}default:throw new SyntaxError(`Unexpected token: ${tt.type}`)}}for(;q=0?(ie=(ie??(ie=0))<0?Math.max(O.length+ie,0):Math.min(ie,O.length),q=(q??(q=O.length))<0?Math.max(O.length+q,0):Math.min(q,O.length)):(ie=(ie??(ie=O.length-1))<0?Math.max(O.length+ie,-1):Math.min(ie,O.length-1),q=(q??(q=-1))<-1?Math.max(O.length+q,-1):Math.min(q,O.length-1));const et=[];for(let nt=ie;ve*ntie.toUpperCase())}var Ye=class{constructor(O=void 0){Ee(this,"type","RuntimeValue");Ee(this,"value");Ee(this,"builtins",new Map);this.value=O}__bool__(){return new rt(!!this.value)}},st=class extends Ye{constructor(){super(...arguments);Ee(this,"type","NumericValue")}},Oe=class extends Ye{constructor(){super(...arguments);Ee(this,"type","StringValue");Ee(this,"builtins",new Map([["upper",new Ue(()=>new Oe(this.value.toUpperCase()))],["lower",new Ue(()=>new Oe(this.value.toLowerCase()))],["strip",new Ue(()=>new Oe(this.value.trim()))],["title",new Ue(()=>new Oe(ut(this.value)))],["length",new st(this.value.length)]]))}},rt=class extends Ye{constructor(){super(...arguments);Ee(this,"type","BooleanValue")}},Tt=class extends Ye{constructor(){super(...arguments);Ee(this,"type","ObjectValue");Ee(this,"builtins",new Map([["get",new Ue(([ie,q])=>{if(!(ie instanceof Oe))throw new Error(`Object key must be a string: got ${ie.type}`);return this.value.get(ie.value)??q??new Ge})],["items",new Ue(()=>new fe(Array.from(this.value.entries()).map(([ie,q])=>new fe([new Oe(ie),q]))))]]))}__bool__(){return new rt(this.value.size>0)}},Be=class extends Tt{constructor(){super(...arguments);Ee(this,"type","KeywordArgumentsValue")}},fe=class extends Ye{constructor(){super(...arguments);Ee(this,"type","ArrayValue");Ee(this,"builtins",new Map([["length",new st(this.value.length)]]))}__bool__(){return new rt(this.value.length>0)}},Ce=class extends fe{constructor(){super(...arguments);Ee(this,"type","TupleValue")}},Ue=class extends Ye{constructor(){super(...arguments);Ee(this,"type","FunctionValue")}},Ge=class extends Ye{constructor(){super(...arguments);Ee(this,"type","NullValue")}},We=class extends Ye{constructor(){super(...arguments);Ee(this,"type","UndefinedValue")}},He=class{constructor(O){Ee(this,"variables",new Map([["namespace",new Ue(O=>{if(O.length===0)return new Tt(new Map);if(O.length!==1||!(O[0]instanceof Tt))throw new Error("`namespace` expects either zero arguments or a single object argument");return O[0]})]]));Ee(this,"tests",new Map([["boolean",O=>O.type==="BooleanValue"],["callable",O=>O instanceof Ue],["odd",O=>{if(O.type!=="NumericValue")throw new Error(`Cannot apply test "odd" to type: ${O.type}`);return O.value%2!==0}],["even",O=>{if(O.type!=="NumericValue")throw new Error(`Cannot apply test "even" to type: ${O.type}`);return O.value%2===0}],["false",O=>O.type==="BooleanValue"&&!O.value],["true",O=>O.type==="BooleanValue"&&O.value],["string",O=>O.type==="StringValue"],["number",O=>O.type==="NumericValue"],["integer",O=>O.type==="NumericValue"&&Number.isInteger(O.value)],["iterable",O=>O instanceof fe||O instanceof Oe],["lower",O=>{const ie=O.value;return O.type==="StringValue"&&ie===ie.toLowerCase()}],["upper",O=>{const ie=O.value;return O.type==="StringValue"&&ie===ie.toUpperCase()}],["none",O=>O.type==="NullValue"],["defined",O=>O.type!=="UndefinedValue"],["undefined",O=>O.type==="UndefinedValue"],["equalto",(O,ie)=>O.value===ie.value],["eq",(O,ie)=>O.value===ie.value]]));this.parent=O}set(O,ie){return this.declareVariable(O,mt(ie))}declareVariable(O,ie){if(this.variables.has(O))throw new SyntaxError(`Variable already declared: ${O}`);return this.variables.set(O,ie),ie}setVariable(O,ie){return this.variables.set(O,ie),ie}resolve(O){if(this.variables.has(O))return this;if(this.parent)return this.parent.resolve(O);throw new Error(`Unknown variable: ${O}`)}lookupVariable(O){try{return this.resolve(O).variables.get(O)??new We}catch{return new We}}},dt=class{constructor(O){Ee(this,"global");this.global=O??new He}run(O){return this.evaluate(O,this.global)}evaluateBinaryExpression(O,ie){const q=this.evaluate(O.left,ie);switch(O.operator.value){case"and":return q.__bool__().value?this.evaluate(O.right,ie):q;case"or":return q.__bool__().value?q:this.evaluate(O.right,ie)}const de=this.evaluate(O.right,ie);switch(O.operator.value){case"==":return new rt(q.value==de.value);case"!=":return new rt(q.value!=de.value)}if(q instanceof We||de instanceof We)throw new Error("Cannot perform operation on undefined values");if(q instanceof Ge||de instanceof Ge)throw new Error("Cannot perform operation on null values");if(q instanceof st&&de instanceof st)switch(O.operator.value){case"+":return new st(q.value+de.value);case"-":return new st(q.value-de.value);case"*":return new st(q.value*de.value);case"/":return new st(q.value/de.value);case"%":return new st(q.value%de.value);case"<":return new rt(q.value":return new rt(q.value>de.value);case">=":return new rt(q.value>=de.value);case"<=":return new rt(q.value<=de.value)}else if(q instanceof fe&&de instanceof fe)switch(O.operator.value){case"+":return new fe(q.value.concat(de.value))}else if(de instanceof fe){const ve=de.value.find(et=>et.value===q.value)!==void 0;switch(O.operator.value){case"in":return new rt(ve);case"not in":return new rt(!ve)}}if(q instanceof Oe||de instanceof Oe)switch(O.operator.value){case"+":return new Oe(q.value.toString()+de.value.toString())}if(q instanceof Oe&&de instanceof Oe)switch(O.operator.value){case"in":return new rt(de.value.includes(q.value));case"not in":return new rt(!de.value.includes(q.value))}if(q instanceof Oe&&de instanceof Tt)switch(O.operator.value){case"in":return new rt(de.value.has(q.value));case"not in":return new rt(!de.value.has(q.value))}throw new SyntaxError(`Unknown operator "${O.operator.value}" between ${q.type} and ${de.type}`)}evaluateArguments(O,ie){const q=[],de=new Map;for(const ve of O)if(ve.type==="KeywordArgumentExpression"){const et=ve;de.set(et.key.value,this.evaluate(et.value,ie))}else{if(de.size>0)throw new Error("Positional arguments must come before keyword arguments");q.push(this.evaluate(ve,ie))}return[q,de]}evaluateFilterExpression(O,ie){const q=this.evaluate(O.operand,ie);if(O.filter.type==="Identifier"){const de=O.filter;if(de.value==="tojson")return new Oe(wt(q));if(q instanceof fe)switch(de.value){case"list":return q;case"first":return q.value[0];case"last":return q.value[q.value.length-1];case"length":return new st(q.value.length);case"reverse":return new fe(q.value.reverse());case"sort":return new fe(q.value.sort((ve,et)=>{if(ve.type!==et.type)throw new Error(`Cannot compare different types: ${ve.type} and ${et.type}`);switch(ve.type){case"NumericValue":return ve.value-et.value;case"StringValue":return ve.value.localeCompare(et.value);default:throw new Error(`Cannot compare type: ${ve.type}`)}}));default:throw new Error(`Unknown ArrayValue filter: ${de.value}`)}else if(q instanceof Oe)switch(de.value){case"length":return new st(q.value.length);case"upper":return new Oe(q.value.toUpperCase());case"lower":return new Oe(q.value.toLowerCase());case"title":return new Oe(ut(q.value));case"capitalize":return new Oe(q.value.charAt(0).toUpperCase()+q.value.slice(1));case"trim":return new Oe(q.value.trim());case"indent":return new Oe(q.value.split(` +`).map((ve,et)=>et===0||ve.length===0?ve:" "+ve).join(` +`));case"string":return q;default:throw new Error(`Unknown StringValue filter: ${de.value}`)}else if(q instanceof st)switch(de.value){case"abs":return new st(Math.abs(q.value));default:throw new Error(`Unknown NumericValue filter: ${de.value}`)}else if(q instanceof Tt)switch(de.value){case"items":return new fe(Array.from(q.value.entries()).map(([ve,et])=>new fe([new Oe(ve),et])));case"length":return new st(q.value.size);default:throw new Error(`Unknown ObjectValue filter: ${de.value}`)}throw new Error(`Cannot apply filter "${de.value}" to type: ${q.type}`)}else if(O.filter.type==="CallExpression"){const de=O.filter;if(de.callee.type!=="Identifier")throw new Error(`Unknown filter: ${de.callee.type}`);const ve=de.callee.value;if(ve==="tojson"){const[,et]=this.evaluateArguments(de.args,ie),nt=et.get("indent")??new Ge;if(!(nt instanceof st||nt instanceof Ge))throw new Error("If set, indent must be a number");return new Oe(wt(q,nt.value))}if(q instanceof fe){switch(ve){case"selectattr":{if(q.value.some(j=>!(j instanceof Tt)))throw new Error("`selectattr` can only be applied to array of objects");if(de.args.some(j=>j.type!=="StringLiteral"))throw new Error("arguments of `selectattr` must be strings");const[et,nt,At]=de.args.map(j=>this.evaluate(j,ie));let _t;if(nt){const j=ie.tests.get(nt.value);if(!j)throw new Error(`Unknown test: ${nt.value}`);_t=j}else _t=(...j)=>j[0].__bool__().value;const Pe=q.value.filter(j=>{const le=j.value.get(et.value);return le?_t(le,At):!1});return new fe(Pe)}case"map":{const[,et]=this.evaluateArguments(de.args,ie);if(et.has("attribute")){const nt=et.get("attribute");if(!(nt instanceof Oe))throw new Error("attribute must be a string");const At=et.get("default"),_t=q.value.map(Pe=>{if(!(Pe instanceof Tt))throw new Error("items in map must be an object");return Pe.value.get(nt.value)??At??new We});return new fe(_t)}else throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${ve}`)}else if(q instanceof Oe){switch(ve){case"indent":{const[et,nt]=this.evaluateArguments(de.args,ie),At=et.at(0)??nt.get("width")??new st(4);if(!(At instanceof st))throw new Error("width must be a number");const _t=et.at(1)??nt.get("first")??new rt(!1),Pe=et.at(2)??nt.get("blank")??new rt(!1),j=q.value.split(` +`),le=" ".repeat(At.value),Te=j.map((Ne,De)=>!_t.value&&De===0||!Pe.value&&Ne.length===0?Ne:le+Ne);return new Oe(Te.join(` +`))}}throw new Error(`Unknown StringValue filter: ${ve}`)}else throw new Error(`Cannot apply filter "${ve}" to type: ${q.type}`)}throw new Error(`Unknown filter: ${O.filter.type}`)}evaluateTestExpression(O,ie){const q=this.evaluate(O.operand,ie),de=ie.tests.get(O.test.value);if(!de)throw new Error(`Unknown test: ${O.test.value}`);const ve=de(q);return new rt(O.negate?!ve:ve)}evaluateUnaryExpression(O,ie){const q=this.evaluate(O.argument,ie);switch(O.operator.value){case"not":return new rt(!q.value);default:throw new SyntaxError(`Unknown operator: ${O.operator.value}`)}}evalProgram(O,ie){return this.evaluateBlock(O.body,ie)}evaluateBlock(O,ie){let q="";for(const de of O){const ve=this.evaluate(de,ie);ve.type!=="NullValue"&&ve.type!=="UndefinedValue"&&(q+=ve.value)}return new Oe(q)}evaluateIdentifier(O,ie){return ie.lookupVariable(O.value)}evaluateCallExpression(O,ie){const[q,de]=this.evaluateArguments(O.args,ie);de.size>0&&q.push(new Be(de));const ve=this.evaluate(O.callee,ie);if(ve.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${ve.type}`);return ve.value(q,ie)}evaluateSliceExpression(O,ie,q){if(!(O instanceof fe||O instanceof Oe))throw new Error("Slice object must be an array or string");const de=this.evaluate(ie.start,q),ve=this.evaluate(ie.stop,q),et=this.evaluate(ie.step,q);if(!(de instanceof st||de instanceof We))throw new Error("Slice start must be numeric or undefined");if(!(ve instanceof st||ve instanceof We))throw new Error("Slice stop must be numeric or undefined");if(!(et instanceof st||et instanceof We))throw new Error("Slice step must be numeric or undefined");return O instanceof fe?new fe(Fe(O.value,de.value,ve.value,et.value)):new Oe(Fe(Array.from(O.value),de.value,ve.value,et.value).join(""))}evaluateMemberExpression(O,ie){const q=this.evaluate(O.object,ie);let de;if(O.computed){if(O.property.type==="SliceExpression")return this.evaluateSliceExpression(q,O.property,ie);de=this.evaluate(O.property,ie)}else de=new Oe(O.property.value);let ve;if(q instanceof Tt){if(!(de instanceof Oe))throw new Error(`Cannot access property with non-string: got ${de.type}`);ve=q.value.get(de.value)??q.builtins.get(de.value)}else if(q instanceof fe||q instanceof Oe)if(de instanceof st)ve=q.value.at(de.value),q instanceof Oe&&(ve=new Oe(q.value.at(de.value)));else if(de instanceof Oe)ve=q.builtins.get(de.value);else throw new Error(`Cannot access property with non-string/non-number: got ${de.type}`);else{if(!(de instanceof Oe))throw new Error(`Cannot access property with non-string: got ${de.type}`);ve=q.builtins.get(de.value)}return ve instanceof Ye?ve:new We}evaluateSet(O,ie){const q=this.evaluate(O.value,ie);if(O.assignee.type==="Identifier"){const de=O.assignee.value;ie.setVariable(de,q)}else if(O.assignee.type==="MemberExpression"){const de=O.assignee,ve=this.evaluate(de.object,ie);if(!(ve instanceof Tt))throw new Error("Cannot assign to member of non-object");if(de.property.type!=="Identifier")throw new Error("Cannot assign to member with non-identifier property");ve.value.set(de.property.value,q)}else throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(O.assignee)}`);return new Ge}evaluateIf(O,ie){const q=this.evaluate(O.test,ie);return this.evaluateBlock(q.__bool__().value?O.body:O.alternate,ie)}evaluateFor(O,ie){const q=new He(ie);let de,ve;if(O.iterable.type==="SelectExpression"){const Pe=O.iterable;ve=this.evaluate(Pe.iterable,q),de=Pe.test}else ve=this.evaluate(O.iterable,q);if(!(ve instanceof fe))throw new Error(`Expected iterable type in for loop: got ${ve.type}`);const et=[],nt=[];for(let Pe=0;PeNe.setVariable(O.loopvar.value,le);else if(O.loopvar.type==="TupleLiteral"){const Ne=O.loopvar;if(le.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${le.type}`);const De=le;if(Ne.value.length!==De.value.length)throw new Error(`Too ${Ne.value.length>De.value.length?"few":"many"} items to unpack`);Te=je=>{for(let ct=0;ct0?et[Pe-1]:new We],["nextitem",Pe{var nt;const ve=new He(de);q=q.slice();let et;((nt=q.at(-1))==null?void 0:nt.type)==="KeywordArgumentsValue"&&(et=q.pop());for(let At=0;Atthis.evaluate(q,ie)));case"TupleLiteral":return new Ce(O.value.map(q=>this.evaluate(q,ie)));case"ObjectLiteral":{const q=new Map;for(const[de,ve]of O.value){const et=this.evaluate(de,ie);if(!(et instanceof Oe))throw new Error(`Object keys must be strings: got ${et.type}`);q.set(et.value,this.evaluate(ve,ie))}return new Tt(q)}case"Identifier":return this.evaluateIdentifier(O,ie);case"CallExpression":return this.evaluateCallExpression(O,ie);case"MemberExpression":return this.evaluateMemberExpression(O,ie);case"UnaryExpression":return this.evaluateUnaryExpression(O,ie);case"BinaryExpression":return this.evaluateBinaryExpression(O,ie);case"FilterExpression":return this.evaluateFilterExpression(O,ie);case"TestExpression":return this.evaluateTestExpression(O,ie);default:throw new SyntaxError(`Unknown node type: ${O.type}`)}}};function mt(O){switch(typeof O){case"number":return new st(O);case"string":return new Oe(O);case"boolean":return new rt(O);case"undefined":return new We;case"object":return O===null?new Ge:Array.isArray(O)?new fe(O.map(mt)):new Tt(new Map(Object.entries(O).map(([ie,q])=>[ie,mt(q)])));case"function":return new Ue((ie,q)=>{const de=O(...ie.map(ve=>ve.value))??null;return mt(de)});default:throw new Error(`Cannot convert to runtime value: ${O}`)}}function wt(O,ie,q){const de=q??0;switch(O.type){case"NullValue":case"UndefinedValue":return"null";case"NumericValue":case"StringValue":case"BooleanValue":return JSON.stringify(O.value);case"ArrayValue":case"ObjectValue":{const ve=ie?" ".repeat(ie):"",et=` +`+ve.repeat(de),nt=et+ve;if(O.type==="ArrayValue"){const At=O.value.map(_t=>wt(_t,ie,de+1));return ie?`[${nt}${At.join(`,${nt}`)}${et}]`:`[${At.join(", ")}]`}else{const At=Array.from(O.value.entries()).map(([_t,Pe])=>{const j=`"${_t}": ${wt(Pe,ie,de+1)}`;return ie?`${nt}${j}`:j});return ie?`{${At.join(",")}${et}}`:`{${At.join(", ")}}`}}default:throw new Error(`Cannot convert to JSON: ${O.type}`)}}var xt=class{constructor(O){Ee(this,"parsed");const ie=S(O,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=Me(ie)}render(O){const ie=new He;ie.set("false",!1),ie.set("true",!0),ie.set("raise_exception",ve=>{throw new Error(ve)}),ie.set("range",se);for(const[ve,et]of Object.entries(O))ie.set(ve,et);return new dt(ie).run(this.parsed).value}}},"./node_modules/onnxruntime-common/dist/esm/backend-impl.js":(e,n,r)=>{r.r(n),r.d(n,{registerBackend:()=>p,resolveBackendAndExecutionProviders:()=>C});const o=new Map,l=[],p=(M,b,F)=>{if(b&&typeof b.init=="function"&&typeof b.createInferenceSessionHandler=="function"){const S=o.get(M);if(S===void 0)o.set(M,{backend:b,priority:F});else{if(S.priority>F)return;if(S.priority===F&&S.backend!==b)throw new Error(`cannot register backend "${M}" using priority ${F}`)}if(F>=0){const G=l.indexOf(M);G!==-1&&l.splice(G,1);for(let J=0;J{const b=o.get(M);if(!b)return"backend not found.";if(b.initialized)return b.backend;if(b.aborted)return b.error;{const F=!!b.initPromise;try{return F||(b.initPromise=b.backend.init(M)),await b.initPromise,b.initialized=!0,b.backend}catch(S){return F||(b.error=`${S}`,b.aborted=!0),b.error}finally{delete b.initPromise}}},C=async M=>{const b=M.executionProviders||[],F=b.map(X=>typeof X=="string"?X:X.name),S=F.length===0?l:F;let G;const J=[],te=new Set;for(const X of S){const A=await _(X);typeof A=="string"?J.push({name:X,err:A}):(G||(G=A),G===A&&te.add(X))}if(!G)throw new Error(`no available backend found. ERR: ${J.map(X=>`[${X.name}] ${X.err}`).join(", ")}`);for(const{name:X,err:A}of J)F.includes(X)&&console.warn(`removing requested execution provider "${X}" from session options because it is not available: ${A}`);const ne=b.filter(X=>te.has(typeof X=="string"?X:X.name));return[G,new Proxy(M,{get:(X,A)=>A==="executionProviders"?ne:Reflect.get(X,A)})]}},"./node_modules/onnxruntime-common/dist/esm/backend.js":(e,n,r)=>{r.r(n),r.d(n,{registerBackend:()=>o.registerBackend});var o=r("./node_modules/onnxruntime-common/dist/esm/backend-impl.js")},"./node_modules/onnxruntime-common/dist/esm/env-impl.js":(e,n,r)=>{r.r(n),r.d(n,{env:()=>p});var o=r("./node_modules/onnxruntime-common/dist/esm/version.js");let l="warning";const p={wasm:{},webgl:{},webgpu:{},versions:{common:o.version},set logLevel(_){if(_!==void 0){if(typeof _!="string"||["verbose","info","warning","error","fatal"].indexOf(_)===-1)throw new Error(`Unsupported logging level: ${_}`);l=_}},get logLevel(){return l}};Object.defineProperty(p,"logLevel",{enumerable:!0})},"./node_modules/onnxruntime-common/dist/esm/env.js":(e,n,r)=>{r.r(n),r.d(n,{env:()=>l});var o=r("./node_modules/onnxruntime-common/dist/esm/env-impl.js");const l=o.env},"./node_modules/onnxruntime-common/dist/esm/index.js":(e,n,r)=>{r.r(n),r.d(n,{InferenceSession:()=>p.InferenceSession,TRACE:()=>C.TRACE,TRACE_FUNC_BEGIN:()=>C.TRACE_FUNC_BEGIN,TRACE_FUNC_END:()=>C.TRACE_FUNC_END,Tensor:()=>_.Tensor,TrainingSession:()=>M.TrainingSession,env:()=>l.env,registerBackend:()=>o.registerBackend});var o=r("./node_modules/onnxruntime-common/dist/esm/backend.js"),l=r("./node_modules/onnxruntime-common/dist/esm/env.js"),p=r("./node_modules/onnxruntime-common/dist/esm/inference-session.js"),_=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 C=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 M=r("./node_modules/onnxruntime-common/dist/esm/training-session.js")},"./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js":(e,n,r)=>{r.r(n),r.d(n,{InferenceSession:()=>_});var o=r("./node_modules/onnxruntime-common/dist/esm/backend-impl.js"),l=r("./node_modules/onnxruntime-common/dist/esm/tensor.js"),p=r("./node_modules/onnxruntime-common/dist/esm/trace.js");class _{constructor(M){this.handler=M}async run(M,b,F){(0,p.TRACE_FUNC_BEGIN)();const S={};let G={};if(typeof M!="object"||M===null||M instanceof l.Tensor||Array.isArray(M))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let J=!0;if(typeof b=="object"){if(b===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(b instanceof l.Tensor)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(b)){if(b.length===0)throw new TypeError("'fetches' cannot be an empty array.");J=!1;for(const X of b){if(typeof X!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(X)===-1)throw new RangeError(`'fetches' contains invalid output name: ${X}.`);S[X]=null}if(typeof F=="object"&&F!==null)G=F;else if(typeof F<"u")throw new TypeError("'options' must be an object.")}else{let X=!1;const A=Object.getOwnPropertyNames(b);for(const P of this.outputNames)if(A.indexOf(P)!==-1){const L=b[P];(L===null||L instanceof l.Tensor)&&(X=!0,J=!1,S[P]=L)}if(X){if(typeof F=="object"&&F!==null)G=F;else if(typeof F<"u")throw new TypeError("'options' must be an object.")}else G=b}}else if(typeof b<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const X of this.inputNames)if(typeof M[X]>"u")throw new Error(`input '${X}' is missing in 'feeds'.`);if(J)for(const X of this.outputNames)S[X]=null;const te=await this.handler.run(M,S,G),ne={};for(const X in te)if(Object.hasOwnProperty.call(te,X)){const A=te[X];A instanceof l.Tensor?ne[X]=A:ne[X]=new l.Tensor(A.type,A.data,A.dims)}return(0,p.TRACE_FUNC_END)(),ne}async release(){return this.handler.dispose()}static async create(M,b,F,S){(0,p.TRACE_FUNC_BEGIN)();let G,J={};if(typeof M=="string"){if(G=M,typeof b=="object"&&b!==null)J=b;else if(typeof b<"u")throw new TypeError("'options' must be an object.")}else if(M instanceof Uint8Array){if(G=M,typeof b=="object"&&b!==null)J=b;else if(typeof b<"u")throw new TypeError("'options' must be an object.")}else if(M instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&M instanceof SharedArrayBuffer){const A=M;let P=0,L=M.byteLength;if(typeof b=="object"&&b!==null)J=b;else if(typeof b=="number"){if(P=b,!Number.isSafeInteger(P))throw new RangeError("'byteOffset' must be an integer.");if(P<0||P>=A.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${A.byteLength}).`);if(L=M.byteLength-P,typeof F=="number"){if(L=F,!Number.isSafeInteger(L))throw new RangeError("'byteLength' must be an integer.");if(L<=0||P+L>A.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${A.byteLength-P}].`);if(typeof S=="object"&&S!==null)J=S;else if(typeof S<"u")throw new TypeError("'options' must be an object.")}else if(typeof F<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof b<"u")throw new TypeError("'options' must be an object.");G=new Uint8Array(A,P,L)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");const[te,ne]=await(0,o.resolveBackendAndExecutionProviders)(J),X=await te.createInferenceSessionHandler(G,ne);return(0,p.TRACE_FUNC_END)(),new _(X)}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":(e,n,r)=>{r.r(n),r.d(n,{InferenceSession:()=>l});var o=r("./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js");const l=o.InferenceSession},"./node_modules/onnxruntime-common/dist/esm/onnx-model.js":(e,n,r)=>{r.r(n)},"./node_modules/onnxruntime-common/dist/esm/onnx-value.js":(e,n,r)=>{r.r(n)},"./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js":(e,n,r)=>{r.r(n),r.d(n,{tensorToDataURL:()=>o,tensorToImageData:()=>l});const o=(p,_)=>{const C=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);C.width=p.dims[3],C.height=p.dims[2];const M=C.getContext("2d");if(M!=null){let b,F;(_==null?void 0:_.tensorLayout)!==void 0&&_.tensorLayout==="NHWC"?(b=p.dims[2],F=p.dims[3]):(b=p.dims[3],F=p.dims[2]);const S=(_==null?void 0:_.format)!==void 0?_.format:"RGB",G=_==null?void 0:_.norm;let J,te;G===void 0||G.mean===void 0?J=[255,255,255,255]:typeof G.mean=="number"?J=[G.mean,G.mean,G.mean,G.mean]:(J=[G.mean[0],G.mean[1],G.mean[2],0],G.mean[3]!==void 0&&(J[3]=G.mean[3])),G===void 0||G.bias===void 0?te=[0,0,0,0]:typeof G.bias=="number"?te=[G.bias,G.bias,G.bias,G.bias]:(te=[G.bias[0],G.bias[1],G.bias[2],0],G.bias[3]!==void 0&&(te[3]=G.bias[3]));const ne=F*b;let X=0,A=ne,P=ne*2,L=-1;S==="RGBA"?(X=0,A=ne,P=ne*2,L=ne*3):S==="RGB"?(X=0,A=ne,P=ne*2):S==="RBG"&&(X=0,P=ne,A=ne*2);for(let Z=0;Z{const C=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");let M;if(C!=null){let b,F,S;(_==null?void 0:_.tensorLayout)!==void 0&&_.tensorLayout==="NHWC"?(b=p.dims[2],F=p.dims[1],S=p.dims[3]):(b=p.dims[3],F=p.dims[2],S=p.dims[1]);const G=_!==void 0&&_.format!==void 0?_.format:"RGB",J=_==null?void 0:_.norm;let te,ne;J===void 0||J.mean===void 0?te=[255,255,255,255]:typeof J.mean=="number"?te=[J.mean,J.mean,J.mean,J.mean]:(te=[J.mean[0],J.mean[1],J.mean[2],255],J.mean[3]!==void 0&&(te[3]=J.mean[3])),J===void 0||J.bias===void 0?ne=[0,0,0,0]:typeof J.bias=="number"?ne=[J.bias,J.bias,J.bias,J.bias]:(ne=[J.bias[0],J.bias[1],J.bias[2],0],J.bias[3]!==void 0&&(ne[3]=J.bias[3]));const X=F*b;if(_!==void 0&&(_.format!==void 0&&S===4&&_.format!=="RGBA"||S===3&&_.format!=="RGB"&&_.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");const A=4;let P=0,L=1,Z=2,V=3,D=0,N=X,z=X*2,me=-1;G==="RGBA"?(D=0,N=X,z=X*2,me=X*3):G==="RGB"?(D=0,N=X,z=X*2):G==="RBG"&&(D=0,z=X,N=X*2),M=C.createImageData(b,F);for(let he=0;he{r.r(n)},"./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js":(e,n,r)=>{r.r(n),r.d(n,{bufferToTensor:()=>l,tensorFromGpuBuffer:()=>C,tensorFromImage:()=>p,tensorFromPinnedBuffer:()=>M,tensorFromTexture:()=>_});var o=r("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const l=(b,F)=>{if(b===void 0)throw new Error("Image buffer must be defined");if(F.height===void 0||F.width===void 0)throw new Error("Image height and width must be defined");if(F.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");const{height:S,width:G}=F,J=F.norm??{mean:255,bias:0};let te,ne;typeof J.mean=="number"?te=[J.mean,J.mean,J.mean,J.mean]:te=[J.mean[0],J.mean[1],J.mean[2],J.mean[3]??255],typeof J.bias=="number"?ne=[J.bias,J.bias,J.bias,J.bias]:ne=[J.bias[0],J.bias[1],J.bias[2],J.bias[3]??0];const X=F.format!==void 0?F.format:"RGBA",A=F.tensorFormat!==void 0&&F.tensorFormat!==void 0?F.tensorFormat:"RGB",P=S*G,L=A==="RGBA"?new Float32Array(P*4):new Float32Array(P*3);let Z=4,V=0,D=1,N=2,z=3,me=0,he=P,ke=P*2,$e=-1;X==="RGB"&&(Z=3,V=0,D=1,N=2,z=-1),A==="RGBA"?$e=P*3:A==="RBG"?(me=0,ke=P,he=P*2):A==="BGR"&&(ke=0,he=P,me=P*2);for(let Je=0;Je{const S=typeof HTMLImageElement<"u"&&b instanceof HTMLImageElement,G=typeof ImageData<"u"&&b instanceof ImageData,J=typeof ImageBitmap<"u"&&b instanceof ImageBitmap,te=typeof b=="string";let ne,X=F??{};const A=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},P=L=>L instanceof HTMLCanvasElement||L instanceof OffscreenCanvas?L.getContext("2d"):null;if(S){const L=A();L.width=b.width,L.height=b.height;const Z=P(L);if(Z!=null){let V=b.height,D=b.width;if(F!==void 0&&F.resizedHeight!==void 0&&F.resizedWidth!==void 0&&(V=F.resizedHeight,D=F.resizedWidth),F!==void 0){if(X=F,F.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");X.tensorFormat="RGBA",X.height=V,X.width=D}else X.tensorFormat="RGBA",X.height=V,X.width=D;Z.drawImage(b,0,0),ne=Z.getImageData(0,0,D,V).data}else throw new Error("Can not access image data")}else if(G){let L,Z;if(F!==void 0&&F.resizedWidth!==void 0&&F.resizedHeight!==void 0?(L=F.resizedHeight,Z=F.resizedWidth):(L=b.height,Z=b.width),F!==void 0&&(X=F),X.format="RGBA",X.height=L,X.width=Z,F!==void 0){const V=A();V.width=Z,V.height=L;const D=P(V);if(D!=null)D.putImageData(b,0,0),ne=D.getImageData(0,0,Z,L).data;else throw new Error("Can not access image data")}else ne=b.data}else if(J){if(F===void 0)throw new Error("Please provide image config with format for Imagebitmap");const L=A();L.width=b.width,L.height=b.height;const Z=P(L);if(Z!=null){const V=b.height,D=b.width;return Z.drawImage(b,0,0,D,V),ne=Z.getImageData(0,0,D,V).data,X.height=V,X.width=D,l(ne,X)}else throw new Error("Can not access image data")}else{if(te)return new Promise((L,Z)=>{const V=A(),D=P(V);if(!b||!D)return Z();const N=new Image;N.crossOrigin="Anonymous",N.src=b,N.onload=()=>{V.width=N.width,V.height=N.height,D.drawImage(N,0,0,V.width,V.height);const z=D.getImageData(0,0,V.width,V.height);X.height=V.height,X.width=V.width,L(l(z.data,X))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(ne!==void 0)return l(ne,X);throw new Error("Input data provided is not supported - aborted tensor creation")},_=(b,F)=>{const{width:S,height:G,download:J,dispose:te}=F,ne=[1,G,S,4];return new o.Tensor({location:"texture",type:"float32",texture:b,dims:ne,download:J,dispose:te})},C=(b,F)=>{const{dataType:S,dims:G,download:J,dispose:te}=F;return new o.Tensor({location:"gpu-buffer",type:S??"float32",gpuBuffer:b,dims:G,download:J,dispose:te})},M=(b,F,S)=>new o.Tensor({location:"cpu-pinned",type:b,data:F,dims:S??[F.length]})},"./node_modules/onnxruntime-common/dist/esm/tensor-factory.js":(e,n,r)=>{r.r(n)},"./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js":(e,n,r)=>{r.r(n),r.d(n,{NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP:()=>l,NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP:()=>o,checkTypedArray:()=>_});const o=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array]]),l=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);let p=!1;const _=()=>{if(!p){p=!0;const C=typeof BigInt64Array<"u"&&BigInt64Array.from,M=typeof BigUint64Array<"u"&&BigUint64Array.from,b=typeof Float16Array<"u"&&Float16Array.from;C&&(o.set("int64",BigInt64Array),l.set(BigInt64Array,"int64")),M&&(o.set("uint64",BigUint64Array),l.set(BigUint64Array,"uint64")),b?(o.set("float16",Float16Array),l.set(Float16Array,"float16")):o.set("float16",Uint16Array)}}},"./node_modules/onnxruntime-common/dist/esm/tensor-impl.js":(e,n,r)=>{r.r(n),r.d(n,{Tensor:()=>C});var o=r("./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js"),l=r("./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js"),p=r("./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js"),_=r("./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js");class C{constructor(b,F,S){(0,p.checkTypedArray)();let G,J;if(typeof b=="object"&&"location"in b)switch(this.dataLocation=b.location,G=b.type,J=b.dims,b.location){case"cpu-pinned":{const ne=p.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(G);if(!ne)throw new TypeError(`unsupported type "${G}" to create tensor from pinned buffer`);if(!(b.data instanceof ne))throw new TypeError(`buffer should be of type ${ne.name}`);this.cpuData=b.data;break}case"texture":{if(G!=="float32")throw new TypeError(`unsupported type "${G}" to create tensor from texture`);this.gpuTextureData=b.texture,this.downloader=b.download,this.disposer=b.dispose;break}case"gpu-buffer":{if(G!=="float32"&&G!=="float16"&&G!=="int32"&&G!=="int64"&&G!=="uint32"&&G!=="uint8"&&G!=="bool")throw new TypeError(`unsupported type "${G}" to create tensor from gpu buffer`);this.gpuBufferData=b.gpuBuffer,this.downloader=b.download,this.disposer=b.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let ne,X;if(typeof b=="string")if(G=b,X=S,b==="string"){if(!Array.isArray(F))throw new TypeError("A string tensor's data must be a string array.");ne=F}else{const A=p.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(b);if(A===void 0)throw new TypeError(`Unsupported tensor type: ${b}.`);if(Array.isArray(F)){if(b==="float16"&&A===Uint16Array)throw new TypeError("Creating a float16 tensor from number array is not supported. Please use Uint16Array as data.");b==="uint64"||b==="int64"?ne=A.from(F,BigInt):ne=A.from(F)}else if(F instanceof A)ne=F;else throw new TypeError(`A ${G} tensor's data must be type of ${A}`)}else if(X=F,Array.isArray(b)){if(b.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");const A=typeof b[0];if(A==="string")G="string",ne=b;else if(A==="boolean")G="bool",ne=Uint8Array.from(b);else throw new TypeError(`Invalid element type of data array: ${A}.`)}else{const A=p.NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.get(b.constructor);if(A===void 0)throw new TypeError(`Unsupported type for tensor data: ${b.constructor}.`);G=A,ne=b}if(X===void 0)X=[ne.length];else if(!Array.isArray(X))throw new TypeError("A tensor's dims must be a number array");J=X,this.cpuData=ne,this.dataLocation="cpu"}const te=(0,_.calculateSize)(J);if(this.cpuData&&te!==this.cpuData.length)throw new Error(`Tensor's size(${te}) does not match data length(${this.cpuData.length}).`);this.type=G,this.dims=J,this.size=te}static async fromImage(b,F){return(0,l.tensorFromImage)(b,F)}static fromTexture(b,F){return(0,l.tensorFromTexture)(b,F)}static fromGpuBuffer(b,F){return(0,l.tensorFromGpuBuffer)(b,F)}static fromPinnedBuffer(b,F,S){return(0,l.tensorFromPinnedBuffer)(b,F,S)}toDataURL(b){return(0,o.tensorToDataURL)(this,b)}toImageData(b){return(0,o.tensorToImageData)(this,b)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}async getData(b){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;const F=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=F,b&&this.disposer&&(this.disposer(),this.disposer=void 0),F}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(b){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return(0,_.tensorReshape)(this,b)}}},"./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js":(e,n,r)=>{r.r(n),r.d(n,{calculateSize:()=>l,tensorReshape:()=>p});var o=r("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const l=_=>{let C=1;for(let M=0;M<_.length;M++){const b=_[M];if(typeof b!="number"||!Number.isSafeInteger(b))throw new TypeError(`dims[${M}] must be an integer, got: ${b}`);if(b<0)throw new RangeError(`dims[${M}] must be a non-negative integer, got: ${b}`);C*=b}return C},p=(_,C)=>{switch(_.location){case"cpu":return new o.Tensor(_.type,_.data,C);case"cpu-pinned":return new o.Tensor({location:"cpu-pinned",data:_.data,type:_.type,dims:C});case"texture":return new o.Tensor({location:"texture",texture:_.texture,type:_.type,dims:C});case"gpu-buffer":return new o.Tensor({location:"gpu-buffer",gpuBuffer:_.gpuBuffer,type:_.type,dims:C});default:throw new Error(`tensorReshape: tensor location ${_.location} is not supported`)}}},"./node_modules/onnxruntime-common/dist/esm/tensor.js":(e,n,r)=>{r.r(n),r.d(n,{Tensor:()=>l});var o=r("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const l=o.Tensor},"./node_modules/onnxruntime-common/dist/esm/trace.js":(e,n,r)=>{r.r(n),r.d(n,{TRACE:()=>l,TRACE_FUNC_BEGIN:()=>_,TRACE_FUNC_END:()=>C});var o=r("./node_modules/onnxruntime-common/dist/esm/env-impl.js");const l=(M,b)=>{(typeof o.env.trace>"u"?!o.env.wasm.trace:!o.env.trace)||console.timeStamp(`${M}::ORT::${b}`)},p=(M,b)=>{var G;const F=((G=new Error().stack)==null?void 0:G.split(/\r\n|\r|\n/g))||[];let S=!1;for(let J=0;J{(typeof o.env.trace>"u"?!o.env.wasm.trace:!o.env.trace)||p("BEGIN",M)},C=M=>{(typeof o.env.trace>"u"?!o.env.wasm.trace:!o.env.trace)||p("END",M)}},"./node_modules/onnxruntime-common/dist/esm/training-session-impl.js":(e,n,r)=>{r.r(n),r.d(n,{TrainingSession:()=>_});var o=r("./node_modules/onnxruntime-common/dist/esm/backend-impl.js"),l=r("./node_modules/onnxruntime-common/dist/esm/tensor.js");const p="Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.";class _{constructor(M,b,F){this.handler=M,this.hasOptimizerModel=b,this.hasEvalModel=F}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(M,b){const F=M.evalModel||"",S=M.optimizerModel||"",G=b||{},[J,te]=await(0,o.resolveBackendAndExecutionProviders)(G);if(J.createTrainingSessionHandler){const ne=await J.createTrainingSessionHandler(M.checkpointState,M.trainModel,F,S,te);return new _(ne,!!M.optimizerModel,!!M.evalModel)}else throw new Error(p)}typeNarrowingForRunStep(M,b,F,S,G){const J={};let te={};if(typeof F!="object"||F===null||F instanceof l.Tensor||Array.isArray(F))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let ne=!0;if(typeof S=="object"){if(S===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(S instanceof l.Tensor)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(S)){if(S.length===0)throw new TypeError("'fetches' cannot be an empty array.");ne=!1;for(const X of S){if(typeof X!="string")throw new TypeError("'fetches' must be a string array or an object.");if(b.indexOf(X)===-1)throw new RangeError(`'fetches' contains invalid output name: ${X}.`);J[X]=null}if(typeof G=="object"&&G!==null)te=G;else if(typeof G<"u")throw new TypeError("'options' must be an object.")}else{let X=!1;const A=Object.getOwnPropertyNames(S);for(const P of b)if(A.indexOf(P)!==-1){const L=S[P];(L===null||L instanceof l.Tensor)&&(X=!0,ne=!1,J[P]=L)}if(X){if(typeof G=="object"&&G!==null)te=G;else if(typeof G<"u")throw new TypeError("'options' must be an object.")}else te=S}}else if(typeof S<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const X of M)if(typeof F[X]>"u")throw new Error(`input '${X}' is missing in 'feeds'.`);if(ne)for(const X of b)J[X]=null;return[J,te]}convertHandlerReturnTypeToMapOfTensors(M){const b={};for(const F in M)if(Object.hasOwnProperty.call(M,F)){const S=M[F];S instanceof l.Tensor?b[F]=S:b[F]=new l.Tensor(S.type,S.data,S.dims)}return b}async lazyResetGrad(){await this.handler.lazyResetGrad()}async runTrainStep(M,b,F){const[S,G]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,M,b,F),J=await this.handler.runTrainStep(M,S,G);return this.convertHandlerReturnTypeToMapOfTensors(J)}async runOptimizerStep(M){if(this.hasOptimizerModel)await this.handler.runOptimizerStep(M||{});else throw new Error("This TrainingSession has no OptimizerModel loaded.")}async runEvalStep(M,b,F){if(this.hasEvalModel){const[S,G]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,M,b,F),J=await this.handler.runEvalStep(M,S,G);return this.convertHandlerReturnTypeToMapOfTensors(J)}else throw new Error("This TrainingSession has no EvalModel loaded.")}async getParametersSize(M=!0){return this.handler.getParametersSize(M)}async loadParametersBuffer(M,b=!0){const F=await this.getParametersSize(b);if(M.length!==4*F)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(M,b)}async getContiguousParameters(M=!0){return this.handler.getContiguousParameters(M)}async release(){return this.handler.dispose()}}},"./node_modules/onnxruntime-common/dist/esm/training-session.js":(e,n,r)=>{r.r(n),r.d(n,{TrainingSession:()=>l});var o=r("./node_modules/onnxruntime-common/dist/esm/training-session-impl.js");const l=o.TrainingSession},"./node_modules/onnxruntime-common/dist/esm/version.js":(e,n,r)=>{r.r(n),r.d(n,{version:()=>o});const o="1.19.0"},"./node_modules/onnxruntime-web/dist/ort.webgpu.bundle.min.mjs":(e,n,r)=>{r.r(n),r.d(n,{InferenceSession:()=>wt,TRACE:()=>Ce,TRACE_FUNC_BEGIN:()=>Ge,TRACE_FUNC_END:()=>We,Tensor:()=>Be,TrainingSession:()=>At,default:()=>wb,env:()=>z,registerBackend:()=>te});/*! + * ONNX Runtime Web v1.20.0-dev.20240821-009209e016 + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */var o=Object.defineProperty,l=Object.getOwnPropertyDescriptor,p=Object.getOwnPropertyNames,_=Object.prototype.hasOwnProperty,C=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(i,s)=>(typeof require<"u"?require:i)[s]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')}),M=(t,i)=>()=>(t&&(i=t(t=0)),i),b=(t,i)=>{for(var s in i)o(t,s,{get:i[s],enumerable:!0})},F=(t,i,s,a)=>{if(i&&typeof i=="object"||typeof i=="function")for(let u of p(i))!_.call(t,u)&&u!==s&&o(t,u,{get:()=>i[u],enumerable:!(a=l(i,u))||a.enumerable});return t},S=t=>F(o({},"__esModule",{value:!0}),t),G,J,te,ne,X,A=M(()=>{G=new Map,J=[],te=(t,i,s)=>{if(i&&typeof i.init=="function"&&typeof i.createInferenceSessionHandler=="function"){let a=G.get(t);if(a===void 0)G.set(t,{backend:i,priority:s});else{if(a.priority>s)return;if(a.priority===s&&a.backend!==i)throw new Error(`cannot register backend "${t}" using priority ${s}`)}if(s>=0){let u=J.indexOf(t);u!==-1&&J.splice(u,1);for(let c=0;c{let i=G.get(t);if(!i)return"backend not found.";if(i.initialized)return i.backend;if(i.aborted)return i.error;{let s=!!i.initPromise;try{return s||(i.initPromise=i.backend.init(t)),await i.initPromise,i.initialized=!0,i.backend}catch(a){return s||(i.error=`${a}`,i.aborted=!0),i.error}finally{delete i.initPromise}}},X=async t=>{let i=t.executionProviders||[],s=i.map(g=>typeof g=="string"?g:g.name),a=s.length===0?J:s,u,c=[],d=new Set;for(let g of a){let y=await ne(g);typeof y=="string"?c.push({name:g,err:y}):(u||(u=y),u===y&&d.add(g))}if(!u)throw new Error(`no available backend found. ERR: ${c.map(g=>`[${g.name}] ${g.err}`).join(", ")}`);for(let{name:g,err:y}of c)s.includes(g)&&console.warn(`removing requested execution provider "${g}" from session options because it is not available: ${y}`);let m=i.filter(g=>d.has(typeof g=="string"?g:g.name));return[u,new Proxy(t,{get:(g,y)=>y==="executionProviders"?m:Reflect.get(g,y)})]}}),P=M(()=>{A()}),L,Z=M(()=>{L="1.20.0-dev.20240816-b2d603abda"}),V,D,N=M(()=>{Z(),V="warning",D={wasm:{},webgl:{},webgpu:{},versions:{common:L},set logLevel(t){if(t!==void 0){if(typeof t!="string"||["verbose","info","warning","error","fatal"].indexOf(t)===-1)throw new Error(`Unsupported logging level: ${t}`);V=t}},get logLevel(){return V}},Object.defineProperty(D,"logLevel",{enumerable:!0})}),z,me=M(()=>{N(),z=D}),he,ke,$e=M(()=>{he=(t,i)=>{let s=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);s.width=t.dims[3],s.height=t.dims[2];let a=s.getContext("2d");if(a!=null){let u,c;(i==null?void 0:i.tensorLayout)!==void 0&&i.tensorLayout==="NHWC"?(u=t.dims[2],c=t.dims[3]):(u=t.dims[3],c=t.dims[2]);let d=(i==null?void 0:i.format)!==void 0?i.format:"RGB",m=i==null?void 0:i.norm,g,y;m===void 0||m.mean===void 0?g=[255,255,255,255]:typeof m.mean=="number"?g=[m.mean,m.mean,m.mean,m.mean]:(g=[m.mean[0],m.mean[1],m.mean[2],0],m.mean[3]!==void 0&&(g[3]=m.mean[3])),m===void 0||m.bias===void 0?y=[0,0,0,0]:typeof m.bias=="number"?y=[m.bias,m.bias,m.bias,m.bias]:(y=[m.bias[0],m.bias[1],m.bias[2],0],m.bias[3]!==void 0&&(y[3]=m.bias[3]));let E=c*u,$=0,h=E,R=E*2,B=-1;d==="RGBA"?($=0,h=E,R=E*2,B=E*3):d==="RGB"?($=0,h=E,R=E*2):d==="RBG"&&($=0,R=E,h=E*2);for(let K=0;K{let s=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),a;if(s!=null){let u,c,d;(i==null?void 0:i.tensorLayout)!==void 0&&i.tensorLayout==="NHWC"?(u=t.dims[2],c=t.dims[1],d=t.dims[3]):(u=t.dims[3],c=t.dims[2],d=t.dims[1]);let m=i!==void 0&&i.format!==void 0?i.format:"RGB",g=i==null?void 0:i.norm,y,E;g===void 0||g.mean===void 0?y=[255,255,255,255]:typeof g.mean=="number"?y=[g.mean,g.mean,g.mean,g.mean]:(y=[g.mean[0],g.mean[1],g.mean[2],255],g.mean[3]!==void 0&&(y[3]=g.mean[3])),g===void 0||g.bias===void 0?E=[0,0,0,0]:typeof g.bias=="number"?E=[g.bias,g.bias,g.bias,g.bias]:(E=[g.bias[0],g.bias[1],g.bias[2],0],g.bias[3]!==void 0&&(E[3]=g.bias[3]));let $=c*u;if(i!==void 0&&(i.format!==void 0&&d===4&&i.format!=="RGBA"||d===3&&i.format!=="RGB"&&i.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let h=4,R=0,B=1,K=2,re=3,oe=0,ee=$,_e=$*2,ae=-1;m==="RGBA"?(oe=0,ee=$,_e=$*2,ae=$*3):m==="RGB"?(oe=0,ee=$,_e=$*2):m==="RBG"&&(oe=0,_e=$,ee=$*2),a=s.createImageData(u,c);for(let ge=0;ge{Tt(),Ae=(t,i)=>{if(t===void 0)throw new Error("Image buffer must be defined");if(i.height===void 0||i.width===void 0)throw new Error("Image height and width must be defined");if(i.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:s,width:a}=i,u=i.norm??{mean:255,bias:0},c,d;typeof u.mean=="number"?c=[u.mean,u.mean,u.mean,u.mean]:c=[u.mean[0],u.mean[1],u.mean[2],u.mean[3]??255],typeof u.bias=="number"?d=[u.bias,u.bias,u.bias,u.bias]:d=[u.bias[0],u.bias[1],u.bias[2],u.bias[3]??0];let m=i.format!==void 0?i.format:"RGBA",g=i.tensorFormat!==void 0&&i.tensorFormat!==void 0?i.tensorFormat:"RGB",y=s*a,E=g==="RGBA"?new Float32Array(y*4):new Float32Array(y*3),$=4,h=0,R=1,B=2,K=3,re=0,oe=y,ee=y*2,_e=-1;m==="RGB"&&($=3,h=0,R=1,B=2,K=-1),g==="RGBA"?_e=y*3:g==="RBG"?(re=0,ee=y,oe=y*2):g==="BGR"&&(ee=0,oe=y,re=y*2);for(let ae=0;ae{let s=typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement,a=typeof ImageData<"u"&&t instanceof ImageData,u=typeof ImageBitmap<"u"&&t instanceof ImageBitmap,c=typeof t=="string",d,m=i??{},g=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},y=E=>E instanceof HTMLCanvasElement||E instanceof OffscreenCanvas?E.getContext("2d"):null;if(s){let E=g();E.width=t.width,E.height=t.height;let $=y(E);if($!=null){let h=t.height,R=t.width;if(i!==void 0&&i.resizedHeight!==void 0&&i.resizedWidth!==void 0&&(h=i.resizedHeight,R=i.resizedWidth),i!==void 0){if(m=i,i.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");m.tensorFormat="RGBA",m.height=h,m.width=R}else m.tensorFormat="RGBA",m.height=h,m.width=R;$.drawImage(t,0,0),d=$.getImageData(0,0,R,h).data}else throw new Error("Can not access image data")}else if(a){let E,$;if(i!==void 0&&i.resizedWidth!==void 0&&i.resizedHeight!==void 0?(E=i.resizedHeight,$=i.resizedWidth):(E=t.height,$=t.width),i!==void 0&&(m=i),m.format="RGBA",m.height=E,m.width=$,i!==void 0){let h=g();h.width=$,h.height=E;let R=y(h);if(R!=null)R.putImageData(t,0,0),d=R.getImageData(0,0,$,E).data;else throw new Error("Can not access image data")}else d=t.data}else if(u){if(i===void 0)throw new Error("Please provide image config with format for Imagebitmap");let E=g();E.width=t.width,E.height=t.height;let $=y(E);if($!=null){let h=t.height,R=t.width;return $.drawImage(t,0,0,R,h),d=$.getImageData(0,0,R,h).data,m.height=h,m.width=R,Ae(d,m)}else throw new Error("Can not access image data")}else{if(c)return new Promise((E,$)=>{let h=g(),R=y(h);if(!t||!R)return $();let B=new Image;B.crossOrigin="Anonymous",B.src=t,B.onload=()=>{h.width=B.width,h.height=B.height,R.drawImage(B,0,0,h.width,h.height);let K=R.getImageData(0,0,h.width,h.height);m.height=h.height,m.width=h.width,E(Ae(K.data,m))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(d!==void 0)return Ae(d,m);throw new Error("Input data provided is not supported - aborted tensor creation")},Xe=(t,i)=>{let{width:s,height:a,download:u,dispose:c}=i,d=[1,a,s,4];return new rt({location:"texture",type:"float32",texture:t,dims:d,download:u,dispose:c})},pt=(t,i)=>{let{dataType:s,dims:a,download:u,dispose:c}=i;return new rt({location:"gpu-buffer",type:s??"float32",gpuBuffer:t,dims:a,download:u,dispose:c})},xe=(t,i,s)=>new rt({location:"cpu-pinned",type:t,data:i,dims:s??[i.length]})}),pe,Me,se,Fe,ut=M(()=>{pe=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),Me=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),se=!1,Fe=()=>{if(!se){se=!0;let t=typeof BigInt64Array<"u"&&BigInt64Array.from,i=typeof BigUint64Array<"u"&&BigUint64Array.from,s=typeof Float16Array<"u"&&Float16Array.from;t&&(pe.set("int64",BigInt64Array),Me.set(BigInt64Array,"int64")),i&&(pe.set("uint64",BigUint64Array),Me.set(BigUint64Array,"uint64")),s?(pe.set("float16",Float16Array),Me.set(Float16Array,"float16")):pe.set("float16",Uint16Array)}}}),Ye,st,Oe=M(()=>{Tt(),Ye=t=>{let i=1;for(let s=0;s{switch(t.location){case"cpu":return new rt(t.type,t.data,i);case"cpu-pinned":return new rt({location:"cpu-pinned",data:t.data,type:t.type,dims:i});case"texture":return new rt({location:"texture",texture:t.texture,type:t.type,dims:i});case"gpu-buffer":return new rt({location:"gpu-buffer",gpuBuffer:t.gpuBuffer,type:t.type,dims:i});default:throw new Error(`tensorReshape: tensor location ${t.location} is not supported`)}}}),rt,Tt=M(()=>{$e(),H(),ut(),Oe(),rt=class{constructor(t,i,s){Fe();let a,u;if(typeof t=="object"&&"location"in t)switch(this.dataLocation=t.location,a=t.type,u=t.dims,t.location){case"cpu-pinned":{let d=pe.get(a);if(!d)throw new TypeError(`unsupported type "${a}" to create tensor from pinned buffer`);if(!(t.data instanceof d))throw new TypeError(`buffer should be of type ${d.name}`);this.cpuData=t.data;break}case"texture":{if(a!=="float32")throw new TypeError(`unsupported type "${a}" to create tensor from texture`);this.gpuTextureData=t.texture,this.downloader=t.download,this.disposer=t.dispose;break}case"gpu-buffer":{if(a!=="float32"&&a!=="float16"&&a!=="int32"&&a!=="int64"&&a!=="uint32"&&a!=="uint8"&&a!=="bool")throw new TypeError(`unsupported type "${a}" to create tensor from gpu buffer`);this.gpuBufferData=t.gpuBuffer,this.downloader=t.download,this.disposer=t.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let d,m;if(typeof t=="string")if(a=t,m=s,t==="string"){if(!Array.isArray(i))throw new TypeError("A string tensor's data must be a string array.");d=i}else{let g=pe.get(t);if(g===void 0)throw new TypeError(`Unsupported tensor type: ${t}.`);if(Array.isArray(i)){if(t==="float16"&&g===Uint16Array||t==="uint4"||t==="int4")throw new TypeError(`Creating a ${t} tensor from number array is not supported. Please use ${g.name} as data.`);t==="uint64"||t==="int64"?d=g.from(i,BigInt):d=g.from(i)}else if(i instanceof g)d=i;else throw new TypeError(`A ${a} tensor's data must be type of ${g}`)}else if(m=i,Array.isArray(t)){if(t.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let g=typeof t[0];if(g==="string")a="string",d=t;else if(g==="boolean")a="bool",d=Uint8Array.from(t);else throw new TypeError(`Invalid element type of data array: ${g}.`)}else{let g=Me.get(t.constructor);if(g===void 0)throw new TypeError(`Unsupported type for tensor data: ${t.constructor}.`);a=g,d=t}if(m===void 0)m=[d.length];else if(!Array.isArray(m))throw new TypeError("A tensor's dims must be a number array");u=m,this.cpuData=d,this.dataLocation="cpu"}let c=Ye(u);if(this.cpuData&&c!==this.cpuData.length&&!((a==="uint4"||a==="int4")&&Math.ceil(c/2)===this.cpuData.length))throw new Error(`Tensor's size(${c}) does not match data length(${this.cpuData.length}).`);this.type=a,this.dims=u,this.size=c}static async fromImage(t,i){return Je(t,i)}static fromTexture(t,i){return Xe(t,i)}static fromGpuBuffer(t,i){return pt(t,i)}static fromPinnedBuffer(t,i,s){return xe(t,i,s)}toDataURL(t){return he(this,t)}toImageData(t){return ke(this,t)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}async getData(t){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let i=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=i,t&&this.disposer&&(this.disposer(),this.disposer=void 0),i}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(t){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return st(this,t)}}}),Be,fe=M(()=>{Tt(),Be=rt}),Ce,Ue,Ge,We,He=M(()=>{N(),Ce=(t,i)=>{(typeof D.trace>"u"?!D.wasm.trace:!D.trace)||console.timeStamp(`${t}::ORT::${i}`)},Ue=(t,i)=>{var u;let s=((u=new Error().stack)==null?void 0:u.split(/\r\n|\r|\n/g))||[],a=!1;for(let c=0;c{(typeof D.trace>"u"?!D.wasm.trace:!D.trace)||Ue("BEGIN",t)},We=t=>{(typeof D.trace>"u"?!D.wasm.trace:!D.trace)||Ue("END",t)}}),dt,mt=M(()=>{A(),fe(),He(),dt=class JM{constructor(i){this.handler=i}async run(i,s,a){Ge();let u={},c={};if(typeof i!="object"||i===null||i instanceof Be||Array.isArray(i))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let d=!0;if(typeof s=="object"){if(s===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(s instanceof Be)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(s)){if(s.length===0)throw new TypeError("'fetches' cannot be an empty array.");d=!1;for(let y of s){if(typeof y!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(y)===-1)throw new RangeError(`'fetches' contains invalid output name: ${y}.`);u[y]=null}if(typeof a=="object"&&a!==null)c=a;else if(typeof a<"u")throw new TypeError("'options' must be an object.")}else{let y=!1,E=Object.getOwnPropertyNames(s);for(let $ of this.outputNames)if(E.indexOf($)!==-1){let h=s[$];(h===null||h instanceof Be)&&(y=!0,d=!1,u[$]=h)}if(y){if(typeof a=="object"&&a!==null)c=a;else if(typeof a<"u")throw new TypeError("'options' must be an object.")}else c=s}}else if(typeof s<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let y of this.inputNames)if(typeof i[y]>"u")throw new Error(`input '${y}' is missing in 'feeds'.`);if(d)for(let y of this.outputNames)u[y]=null;let m=await this.handler.run(i,u,c),g={};for(let y in m)if(Object.hasOwnProperty.call(m,y)){let E=m[y];E instanceof Be?g[y]=E:g[y]=new Be(E.type,E.data,E.dims)}return We(),g}async release(){return this.handler.dispose()}static async create(i,s,a,u){Ge();let c,d={};if(typeof i=="string"){if(c=i,typeof s=="object"&&s!==null)d=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else if(i instanceof Uint8Array){if(c=i,typeof s=="object"&&s!==null)d=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else if(i instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&i instanceof SharedArrayBuffer){let E=i,$=0,h=i.byteLength;if(typeof s=="object"&&s!==null)d=s;else if(typeof s=="number"){if($=s,!Number.isSafeInteger($))throw new RangeError("'byteOffset' must be an integer.");if($<0||$>=E.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${E.byteLength}).`);if(h=i.byteLength-$,typeof a=="number"){if(h=a,!Number.isSafeInteger(h))throw new RangeError("'byteLength' must be an integer.");if(h<=0||$+h>E.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${E.byteLength-$}].`);if(typeof u=="object"&&u!==null)d=u;else if(typeof u<"u")throw new TypeError("'options' must be an object.")}else if(typeof a<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof s<"u")throw new TypeError("'options' must be an object.");c=new Uint8Array(E,$,h)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[m,g]=await X(d),y=await m.createInferenceSessionHandler(c,g);return We(),new JM(y)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}}),wt,xt=M(()=>{mt(),wt=dt}),O=M(()=>{}),ie=M(()=>{}),q=M(()=>{}),de=M(()=>{}),ve,et,nt=M(()=>{A(),fe(),ve="Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.",et=class eb{constructor(i,s,a){this.handler=i,this.hasOptimizerModel=s,this.hasEvalModel=a}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(i,s){let a=i.evalModel||"",u=i.optimizerModel||"",c=s||{},[d,m]=await X(c);if(d.createTrainingSessionHandler){let g=await d.createTrainingSessionHandler(i.checkpointState,i.trainModel,a,u,m);return new eb(g,!!i.optimizerModel,!!i.evalModel)}else throw new Error(ve)}typeNarrowingForRunStep(i,s,a,u,c){let d={},m={};if(typeof a!="object"||a===null||a instanceof Be||Array.isArray(a))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let g=!0;if(typeof u=="object"){if(u===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(u instanceof Be)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(u)){if(u.length===0)throw new TypeError("'fetches' cannot be an empty array.");g=!1;for(let y of u){if(typeof y!="string")throw new TypeError("'fetches' must be a string array or an object.");if(s.indexOf(y)===-1)throw new RangeError(`'fetches' contains invalid output name: ${y}.`);d[y]=null}if(typeof c=="object"&&c!==null)m=c;else if(typeof c<"u")throw new TypeError("'options' must be an object.")}else{let y=!1,E=Object.getOwnPropertyNames(u);for(let $ of s)if(E.indexOf($)!==-1){let h=u[$];(h===null||h instanceof Be)&&(y=!0,g=!1,d[$]=h)}if(y){if(typeof c=="object"&&c!==null)m=c;else if(typeof c<"u")throw new TypeError("'options' must be an object.")}else m=u}}else if(typeof u<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let y of i)if(typeof a[y]>"u")throw new Error(`input '${y}' is missing in 'feeds'.`);if(g)for(let y of s)d[y]=null;return[d,m]}convertHandlerReturnTypeToMapOfTensors(i){let s={};for(let a in i)if(Object.hasOwnProperty.call(i,a)){let u=i[a];u instanceof Be?s[a]=u:s[a]=new Be(u.type,u.data,u.dims)}return s}async lazyResetGrad(){await this.handler.lazyResetGrad()}async runTrainStep(i,s,a){let[u,c]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,i,s,a),d=await this.handler.runTrainStep(i,u,c);return this.convertHandlerReturnTypeToMapOfTensors(d)}async runOptimizerStep(i){if(this.hasOptimizerModel)await this.handler.runOptimizerStep(i||{});else throw new Error("This TrainingSession has no OptimizerModel loaded.")}async runEvalStep(i,s,a){if(this.hasEvalModel){let[u,c]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,i,s,a),d=await this.handler.runEvalStep(i,u,c);return this.convertHandlerReturnTypeToMapOfTensors(d)}else throw new Error("This TrainingSession has no EvalModel loaded.")}async getParametersSize(i=!0){return this.handler.getParametersSize(i)}async loadParametersBuffer(i,s=!0){let a=await this.getParametersSize(s);if(i.length!==4*a)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(i,s)}async getContiguousParameters(i=!0){return this.handler.getContiguousParameters(i)}async release(){return this.handler.dispose()}}}),At,_t=M(()=>{nt(),At=et}),Pe={};b(Pe,{InferenceSession:()=>wt,TRACE:()=>Ce,TRACE_FUNC_BEGIN:()=>Ge,TRACE_FUNC_END:()=>We,Tensor:()=>Be,TrainingSession:()=>At,env:()=>z,registerBackend:()=>te});var j=M(()=>{P(),me(),xt(),fe(),O(),ie(),He(),q(),de(),_t()}),le=M(()=>{}),Te={};b(Te,{default:()=>je});var Ne,De,je,ct=M(()=>{var t;Zy(),cr(),Hn(),Ne="ort-wasm-proxy-worker",De=((t=globalThis.self)==null?void 0:t.name)===Ne,De&&(self.onmessage=i=>{let{type:s,in:a}=i.data;try{switch(s){case"init-wasm":_i(a.wasm).then(()=>{im(a).then(()=>{postMessage({type:s})},u=>{postMessage({type:s,err:u})})},u=>{postMessage({type:s,err:u})});break;case"init-ep":{let{epName:u,env:c}=a;om(c,u).then(()=>{postMessage({type:s})},d=>{postMessage({type:s,err:d})});break}case"copy-from":{let{buffer:u}=a,c=yf(u);postMessage({type:s,out:c});break}case"create":{let{model:u,options:c}=a;sm(u,c).then(d=>{postMessage({type:s,out:d})},d=>{postMessage({type:s,err:d})});break}case"release":am(a),postMessage({type:s});break;case"run":{let{sessionId:u,inputIndices:c,inputs:d,outputIndices:m,options:g}=a;um(u,c,d,m,new Array(m.length).fill(null),g).then(y=>{y.some(E=>E[3]!=="cpu")?postMessage({type:s,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:s,out:y},cm([...d,...y]))},y=>{postMessage({type:s,err:y})});break}case"end-profiling":dm(a),postMessage({type:s});break;default:}}catch(u){postMessage({type:s,err:u})}}),je=De?null:i=>new Worker(i??Ke,{type:"module",name:Ne})}),ot={};b(ot,{default:()=>St});var bt,ft,St,Nt=M(()=>{var t;ft=(bt=import.meta.url,async function(i={}){function s(){return kn.buffer!=tn.buffer&&Cr(),tn}function a(){return kn.buffer!=tn.buffer&&Cr(),en}function u(){return kn.buffer!=tn.buffer&&Cr(),Ze}function c(){return kn.buffer!=tn.buffer&&Cr(),zt}function d(){return kn.buffer!=tn.buffer&&Cr(),on}function m(){return kn.buffer!=tn.buffer&&Cr(),Gn}function g(){return kn.buffer!=tn.buffer&&Cr(),or}function y(){return kn.buffer!=tn.buffer&&Cr(),Mf}var E,$,h=i,R=new Promise((f,v)=>{E=f,$=v}),B=typeof window=="object",K=typeof importScripts=="function",re=K&&self.name=="em-pthread";h.mountExternalData=(f,v)=>{f.startsWith("./")&&(f=f.substring(2)),(h.Ab||(h.Ab=new Map)).set(f,v)},h.unmountExternalData=()=>{delete h.Ab};var oe=globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,shared:!0}).buffer.constructor;let ee=()=>{let f=(I,W,Y)=>(...be)=>{let qe=Ji,lt=W==null?void 0:W();be=I(...be);let $t=W==null?void 0:W();return lt!==$t&&(I=$t,Y(lt),W=Y=null),Ji!=qe?new Promise((Bt,un)=>{Cm={resolve:Bt,reject:un}}):be},v=I=>async(...W)=>{var Y;try{if(h.zb)throw Error("Session already started");let be=h.zb={Ub:W[0],errors:[]},qe=await I(...W);if(h.zb!==be)throw Error("Session mismatch");(Y=h.Eb)==null||Y.flush();let lt=be.errors;if(0Bt),0<$t.length)throw Error($t.join(` +`))}return qe}finally{h.zb=null}};h._OrtCreateSession=f(h._OrtCreateSession,()=>h._OrtCreateSession,I=>h._OrtCreateSession=I),h._OrtRun=v(f(h._OrtRun,()=>h._OrtRun,I=>h._OrtRun=I)),h._OrtRunWithBinding=v(f(h._OrtRunWithBinding,()=>h._OrtRunWithBinding,I=>h._OrtRunWithBinding=I)),h._OrtBindInput=f(h._OrtBindInput,()=>h._OrtBindInput,I=>h._OrtBindInput=I),ee=void 0};h.jsepInit=(f,v)=>{if(ee==null||ee(),f==="webgpu"){[h.Eb,h.Lb,h.Pb,h.Fb,h.Ob,h.hb,h.Qb,h.Sb,h.Mb,h.Nb,h.Rb]=v;let I=h.Eb;h.jsepRegisterBuffer=(W,Y,be,qe)=>I.registerBuffer(W,Y,be,qe),h.jsepGetBuffer=W=>I.getBuffer(W),h.jsepCreateDownloader=(W,Y,be)=>I.createDownloader(W,Y,be),h.jsepOnReleaseSession=W=>{I.onReleaseSession(W)},h.jsepOnRunStart=W=>I.onRunStart(W)}};var _e,ae,ge=Object.assign({},h),Qe="./this.program",ze=(f,v)=>{throw v},ht="";(B||K)&&(K?ht=self.location.href:typeof document<"u"&&document.currentScript&&(ht=document.currentScript.src),bt&&(ht=bt),ht=ht.startsWith("blob:")?"":ht.substr(0,ht.replace(/[?#].*/,"").lastIndexOf("/")+1),K&&(ae=f=>{var v=new XMLHttpRequest;return v.open("GET",f,!1),v.responseType="arraybuffer",v.send(null),new Uint8Array(v.response)}),_e=f=>mw(f)?new Promise((v,I)=>{var W=new XMLHttpRequest;W.open("GET",f,!0),W.responseType="arraybuffer",W.onload=()=>{(W.status==200||W.status==0&&W.response)&&I(W.response),v(W.status)},W.onerror=v,W.send(null)}):fetch(f,{credentials:"same-origin"}).then(v=>v.ok?v.arrayBuffer():Promise.reject(Error(v.status+" : "+v.url))));var Ft,Dt=console.log.bind(console),hn=console.error.bind(console),ln=Dt,rn=hn;if(Object.assign(h,ge),ge=null,re){let f=function(v){try{var I=v.data,W=I.cmd;if(W==="load"){let Y=[];self.onmessage=be=>Y.push(be),self.startWorker=()=>{postMessage({cmd:"loaded"});for(let be of Y)f(be);self.onmessage=f};for(let be of I.handlers)h[be]&&!h[be].proxy||(h[be]=(...qe)=>{postMessage({Db:"callHandler",Yb:be,args:qe})},be=="print"&&(ln=h[be]),be=="printErr"&&(rn=h[be]));kn=I.wasmMemory,Cr(),yn(I.wasmModule)}else if(W==="run"){Im(I.pthread_ptr,0,0,1,0,0),Sm(I.pthread_ptr),bb(),xw(),Wn||(y0(),Wn=!0);try{xb(I.start_routine,I.arg)}catch(Y){if(Y!="unwind")throw Y}}else W==="cancel"?Ml()&&Ff(-1):I.target!=="setimmediate"&&(W==="checkMailbox"?Wn&&Tf():W&&(rn(`worker: received unknown command ${W}`),rn(I)))}catch(Y){throw w0(),Y}};var yn,Wn=!1;rn=function(...v){v=v.join(" "),console.error(v)},self.alert=function(...v){postMessage({Db:"alert",text:v.join(" "),$b:Ml()})},h.instantiateWasm=(v,I)=>new Promise(W=>{yn=Y=>{Y=new WebAssembly.Instance(Y,yw()),I(Y),W()}}),self.onunhandledrejection=v=>{throw v.reason||v},self.onmessage=f}h.wasmBinary&&(Ft=h.wasmBinary);var kn,jn,It,tn,en,Ze,zt,on,Gn,or,yr,Hr,Mf,di=!1;function Cr(){var f=kn.buffer;h.HEAP8=tn=new Int8Array(f),h.HEAP16=Ze=new Int16Array(f),h.HEAPU8=en=new Uint8Array(f),h.HEAPU16=zt=new Uint16Array(f),h.HEAP32=on=new Int32Array(f),h.HEAPU32=Gn=new Uint32Array(f),h.HEAPF32=or=new Float32Array(f),h.HEAPF64=Mf=new Float64Array(f),h.HEAP64=yr=new BigInt64Array(f),h.HEAPU64=Hr=new BigUint64Array(f)}if(!re){if(!((kn=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0})).buffer instanceof oe))throw rn("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");Cr()}var Yc=[],$r=[],Kr=[],Ti=0,Qo=null;function bf(){if(--Ti==0&&Qo){var f=Qo;Qo=null,f()}}function wl(f){throw rn(f="Aborted("+f+")"),di=!0,It=1,f=new WebAssembly.RuntimeError(f+". Build with -sASSERTIONS for more info."),$(f),f}var hm,hw=f=>f.startsWith("data:application/octet-stream;base64,"),mw=f=>f.startsWith("file://");function gw(f){if(f==hm&&Ft)return new Uint8Array(Ft);if(ae)return ae(f);throw"both async and sync fetching of the wasm failed"}function _w(f,v,I){return function(W){return Ft?Promise.resolve().then(()=>gw(W)):_e(W).then(Y=>new Uint8Array(Y),()=>gw(W))}(f).then(W=>WebAssembly.instantiate(W,v)).then(I,W=>{rn(`failed to asynchronously prepare wasm: ${W}`),wl(W)})}function yw(){return{a:{L:Mb,xa:vb,b:Sb,Z:Ew,y:Pw,na:Aw,V:Fw,X:zw,oa:Ow,la:Dw,ea:Lw,ka:Bw,I:Rw,W:Nw,T:jw,ma:Vw,U:Uw,sa:kb,B:Eb,O:Cb,N:Pb,A:Ib,r:Fb,p:zb,C:Ob,x:Vb,P:Ub,ra:Wb,ha:Gb,R:qb,_:Hb,E:Kb,ga:Sm,qa:Qb,t:Xb,D:Jb,o:ex,m:nx,c:xm,n:rx,k:sx,ya:ax,q:lx,g:ux,u:dx,l:cx,f:px,i:fx,j:hx,h:mx,e:gx,ba:_x,ca:yx,da:wx,$:i0,aa:o0,ua:vx,d:Mx,M:bx,F:xx,J:Tx,v:Sx,pa:kx,S:Ex,s:a0,w:Cx,K:$x,Q:Px,wa:Ax,va:Ix,ia:d0,ja:c0,Y:wm,z:p0,H:f0,fa:h0,G:m0,a:kn,ta:ym}}}var mm={858772:(f,v,I,W)=>{if(h===void 0||!h.Ab)return 1;if((f=Lr(f>>>0)).startsWith("./")&&(f=f.substring(2)),!(f=h.Ab.get(f)))return 2;if(W>>>=0,(v>>>=0)+(I>>>=0)>f.byteLength)return 3;try{return a().set(f.subarray(v,v+I),W>>>0),0}catch{return 4}},859273:()=>{h.Mb()},859304:()=>{h.Nb()},859333:()=>{h.Rb()},859358:f=>h.Lb(f),859391:f=>h.Pb(f),859423:(f,v,I)=>{h.Fb(f,v,I,!0)},859462:(f,v,I)=>{h.Fb(f,v,I)},859495:()=>typeof wasmOffsetConverter<"u",859552:f=>{h.hb("Abs",f,void 0)},859603:f=>{h.hb("Neg",f,void 0)},859654:f=>{h.hb("Floor",f,void 0)},859707:f=>{h.hb("Ceil",f,void 0)},859759:f=>{h.hb("Reciprocal",f,void 0)},859817:f=>{h.hb("Sqrt",f,void 0)},859869:f=>{h.hb("Exp",f,void 0)},859920:f=>{h.hb("Erf",f,void 0)},859971:f=>{h.hb("Sigmoid",f,void 0)},860026:(f,v,I)=>{h.hb("HardSigmoid",f,{alpha:v,beta:I})},860105:f=>{h.hb("Log",f,void 0)},860156:f=>{h.hb("Sin",f,void 0)},860207:f=>{h.hb("Cos",f,void 0)},860258:f=>{h.hb("Tan",f,void 0)},860309:f=>{h.hb("Asin",f,void 0)},860361:f=>{h.hb("Acos",f,void 0)},860413:f=>{h.hb("Atan",f,void 0)},860465:f=>{h.hb("Sinh",f,void 0)},860517:f=>{h.hb("Cosh",f,void 0)},860569:f=>{h.hb("Asinh",f,void 0)},860622:f=>{h.hb("Acosh",f,void 0)},860675:f=>{h.hb("Atanh",f,void 0)},860728:f=>{h.hb("Tanh",f,void 0)},860780:f=>{h.hb("Not",f,void 0)},860831:(f,v,I)=>{h.hb("Clip",f,{min:v,max:I})},860900:f=>{h.hb("Clip",f,void 0)},860952:(f,v)=>{h.hb("Elu",f,{alpha:v})},861010:f=>{h.hb("Gelu",f,void 0)},861062:f=>{h.hb("Relu",f,void 0)},861114:(f,v)=>{h.hb("LeakyRelu",f,{alpha:v})},861178:(f,v)=>{h.hb("ThresholdedRelu",f,{alpha:v})},861248:(f,v)=>{h.hb("Cast",f,{to:v})},861306:f=>{h.hb("Add",f,void 0)},861357:f=>{h.hb("Sub",f,void 0)},861408:f=>{h.hb("Mul",f,void 0)},861459:f=>{h.hb("Div",f,void 0)},861510:f=>{h.hb("Pow",f,void 0)},861561:f=>{h.hb("Equal",f,void 0)},861614:f=>{h.hb("Greater",f,void 0)},861669:f=>{h.hb("GreaterOrEqual",f,void 0)},861731:f=>{h.hb("Less",f,void 0)},861783:f=>{h.hb("LessOrEqual",f,void 0)},861842:(f,v,I,W,Y)=>{h.hb("ReduceMean",f,{keepDims:!!v,noopWithEmptyAxes:!!I,axes:W?Array.from(d().subarray(W>>>0,Y>>>0)):[]})},862001:(f,v,I,W,Y)=>{h.hb("ReduceMax",f,{keepDims:!!v,noopWithEmptyAxes:!!I,axes:W?Array.from(d().subarray(W>>>0,Y>>>0)):[]})},862159:(f,v,I,W,Y)=>{h.hb("ReduceMin",f,{keepDims:!!v,noopWithEmptyAxes:!!I,axes:W?Array.from(d().subarray(W>>>0,Y>>>0)):[]})},862317:(f,v,I,W,Y)=>{h.hb("ReduceProd",f,{keepDims:!!v,noopWithEmptyAxes:!!I,axes:W?Array.from(d().subarray(W>>>0,Y>>>0)):[]})},862476:(f,v,I,W,Y)=>{h.hb("ReduceSum",f,{keepDims:!!v,noopWithEmptyAxes:!!I,axes:W?Array.from(d().subarray(W>>>0,Y>>>0)):[]})},862634:(f,v,I,W,Y)=>{h.hb("ReduceL1",f,{keepDims:!!v,noopWithEmptyAxes:!!I,axes:W?Array.from(d().subarray(W>>>0,Y>>>0)):[]})},862791:(f,v,I,W,Y)=>{h.hb("ReduceL2",f,{keepDims:!!v,noopWithEmptyAxes:!!I,axes:W?Array.from(d().subarray(W>>>0,Y>>>0)):[]})},862948:(f,v,I,W,Y)=>{h.hb("ReduceLogSum",f,{keepDims:!!v,noopWithEmptyAxes:!!I,axes:W?Array.from(d().subarray(W>>>0,Y>>>0)):[]})},863109:(f,v,I,W,Y)=>{h.hb("ReduceSumSquare",f,{keepDims:!!v,noopWithEmptyAxes:!!I,axes:W?Array.from(d().subarray(W>>>0,Y>>>0)):[]})},863273:(f,v,I,W,Y)=>{h.hb("ReduceLogSumExp",f,{keepDims:!!v,noopWithEmptyAxes:!!I,axes:W?Array.from(d().subarray(W>>>0,Y>>>0)):[]})},863437:f=>{h.hb("Where",f,void 0)},863490:(f,v,I)=>{h.hb("Transpose",f,{perm:v?Array.from(d().subarray(v>>>0,I>>>0)):[]})},863598:(f,v,I,W)=>{h.hb("DepthToSpace",f,{blocksize:v,mode:Lr(I),format:W?"NHWC":"NCHW"})},863731:(f,v,I,W)=>{h.hb("DepthToSpace",f,{blocksize:v,mode:Lr(I),format:W?"NHWC":"NCHW"})},863864:(f,v,I,W,Y,be,qe,lt,$t,Bt,un,An,Ln,Pr,bl)=>{h.hb("ConvTranspose",f,{format:$t?"NHWC":"NCHW",autoPad:v,dilations:[I],group:W,kernelShape:[Y],pads:[be,qe],strides:[lt],wIsConst:()=>!!s()[Bt>>>0],outputPadding:un?Array.from(d().subarray(un>>>0,An>>>0)):[],outputShape:Ln?Array.from(d().subarray(Ln>>>0,Pr>>>0)):[],activation:Lr(bl)})},864265:(f,v,I,W,Y,be,qe,lt,$t,Bt,un,An,Ln,Pr)=>{h.hb("ConvTranspose",f,{format:lt?"NHWC":"NCHW",autoPad:v,dilations:Array.from(d().subarray(I>>>0,2+(I>>>0)>>>0)),group:W,kernelShape:Array.from(d().subarray(Y>>>0,2+(Y>>>0)>>>0)),pads:Array.from(d().subarray(be>>>0,4+(be>>>0)>>>0)),strides:Array.from(d().subarray(qe>>>0,2+(qe>>>0)>>>0)),wIsConst:()=>!!s()[$t>>>0],outputPadding:Bt?Array.from(d().subarray(Bt>>>0,un>>>0)):[],outputShape:An?Array.from(d().subarray(An>>>0,Ln>>>0)):[],activation:Lr(Pr)})},864830:(f,v,I,W,Y,be,qe,lt,$t,Bt,un,An,Ln,Pr,bl)=>{h.hb("ConvTranspose",f,{format:$t?"NHWC":"NCHW",autoPad:v,dilations:[I],group:W,kernelShape:[Y],pads:[be,qe],strides:[lt],wIsConst:()=>!!s()[Bt>>>0],outputPadding:un?Array.from(d().subarray(un>>>0,An>>>0)):[],outputShape:Ln?Array.from(d().subarray(Ln>>>0,Pr>>>0)):[],activation:Lr(bl)})},865231:(f,v,I,W,Y,be,qe,lt,$t,Bt,un,An,Ln,Pr)=>{h.hb("ConvTranspose",f,{format:lt?"NHWC":"NCHW",autoPad:v,dilations:Array.from(d().subarray(I>>>0,2+(I>>>0)>>>0)),group:W,kernelShape:Array.from(d().subarray(Y>>>0,2+(Y>>>0)>>>0)),pads:Array.from(d().subarray(be>>>0,4+(be>>>0)>>>0)),strides:Array.from(d().subarray(qe>>>0,2+(qe>>>0)>>>0)),wIsConst:()=>!!s()[$t>>>0],outputPadding:Bt?Array.from(d().subarray(Bt>>>0,un>>>0)):[],outputShape:An?Array.from(d().subarray(An>>>0,Ln>>>0)):[],activation:Lr(Pr)})},865796:(f,v)=>{h.hb("GlobalAveragePool",f,{format:v?"NHWC":"NCHW"})},865887:(f,v,I,W,Y,be,qe,lt,$t,Bt,un,An,Ln,Pr)=>{h.hb("AveragePool",f,{format:Pr?"NHWC":"NCHW",auto_pad:v,ceil_mode:I,count_include_pad:W,storage_order:Y,dilations:be?Array.from(d().subarray(be>>>0,qe>>>0)):[],kernel_shape:lt?Array.from(d().subarray(lt>>>0,$t>>>0)):[],pads:Bt?Array.from(d().subarray(Bt>>>0,un>>>0)):[],strides:An?Array.from(d().subarray(An>>>0,Ln>>>0)):[]})},866302:(f,v)=>{h.hb("GlobalAveragePool",f,{format:v?"NHWC":"NCHW"})},866393:(f,v,I,W,Y,be,qe,lt,$t,Bt,un,An,Ln,Pr)=>{h.hb("AveragePool",f,{format:Pr?"NHWC":"NCHW",auto_pad:v,ceil_mode:I,count_include_pad:W,storage_order:Y,dilations:be?Array.from(d().subarray(be>>>0,qe>>>0)):[],kernel_shape:lt?Array.from(d().subarray(lt>>>0,$t>>>0)):[],pads:Bt?Array.from(d().subarray(Bt>>>0,un>>>0)):[],strides:An?Array.from(d().subarray(An>>>0,Ln>>>0)):[]})},866808:(f,v)=>{h.hb("GlobalMaxPool",f,{format:v?"NHWC":"NCHW"})},866895:(f,v,I,W,Y,be,qe,lt,$t,Bt,un,An,Ln,Pr)=>{h.hb("MaxPool",f,{format:Pr?"NHWC":"NCHW",auto_pad:v,ceil_mode:I,count_include_pad:W,storage_order:Y,dilations:be?Array.from(d().subarray(be>>>0,qe>>>0)):[],kernel_shape:lt?Array.from(d().subarray(lt>>>0,$t>>>0)):[],pads:Bt?Array.from(d().subarray(Bt>>>0,un>>>0)):[],strides:An?Array.from(d().subarray(An>>>0,Ln>>>0)):[]})},867306:(f,v)=>{h.hb("GlobalMaxPool",f,{format:v?"NHWC":"NCHW"})},867393:(f,v,I,W,Y,be,qe,lt,$t,Bt,un,An,Ln,Pr)=>{h.hb("MaxPool",f,{format:Pr?"NHWC":"NCHW",auto_pad:v,ceil_mode:I,count_include_pad:W,storage_order:Y,dilations:be?Array.from(d().subarray(be>>>0,qe>>>0)):[],kernel_shape:lt?Array.from(d().subarray(lt>>>0,$t>>>0)):[],pads:Bt?Array.from(d().subarray(Bt>>>0,un>>>0)):[],strides:An?Array.from(d().subarray(An>>>0,Ln>>>0)):[]})},867804:(f,v,I,W,Y)=>{h.hb("Gemm",f,{alpha:v,beta:I,transA:W,transB:Y})},867908:f=>{h.hb("MatMul",f,void 0)},867962:(f,v,I,W)=>{h.hb("ArgMax",f,{keepDims:!!v,selectLastIndex:!!I,axis:W})},868070:(f,v,I,W)=>{h.hb("ArgMin",f,{keepDims:!!v,selectLastIndex:!!I,axis:W})},868178:(f,v)=>{h.hb("Softmax",f,{axis:v})},868241:(f,v)=>{h.hb("Concat",f,{axis:v})},868301:(f,v,I,W,Y)=>{h.hb("Split",f,{axis:v,numOutputs:I,splitSizes:W?Array.from(d().subarray(W>>>0,Y>>>0)):[]})},868441:f=>{h.hb("Expand",f,void 0)},868495:(f,v)=>{h.hb("Gather",f,{axis:Number(v)})},868566:(f,v)=>{h.hb("GatherElements",f,{axis:Number(v)})},868645:(f,v,I,W,Y,be,qe,lt,$t,Bt,un)=>{h.hb("Resize",f,{antialias:v,axes:I?Array.from(d().subarray(I>>>0,W>>>0)):[],coordinateTransformMode:Lr(Y),cubicCoeffA:be,excludeOutside:qe,extrapolationValue:lt,keepAspectRatioPolicy:Lr($t),mode:Lr(Bt),nearestMode:Lr(un)})},868991:(f,v,I,W,Y,be,qe)=>{h.hb("Slice",f,{starts:v?Array.from(d().subarray(v>>>0,I>>>0)):[],ends:W?Array.from(d().subarray(W>>>0,Y>>>0)):[],axes:be?Array.from(d().subarray(be>>>0,qe>>>0)):[]})},869207:f=>{h.hb("Tile",f,void 0)},869259:(f,v,I)=>{h.hb("InstanceNormalization",f,{epsilon:v,format:I?"NHWC":"NCHW"})},869373:(f,v,I)=>{h.hb("InstanceNormalization",f,{epsilon:v,format:I?"NHWC":"NCHW"})},869487:f=>{h.hb("Range",f,void 0)},869540:(f,v)=>{h.hb("Einsum",f,{equation:Lr(v)})},869621:(f,v,I,W,Y)=>{h.hb("Pad",f,{mode:v,value:I,pads:W?Array.from(d().subarray(W>>>0,Y>>>0)):[]})},869748:(f,v,I,W,Y,be)=>{h.hb("BatchNormalization",f,{epsilon:v,momentum:I,spatial:!!Y,trainingMode:!!W,format:be?"NHWC":"NCHW"})},869917:(f,v,I,W,Y,be)=>{h.hb("BatchNormalization",f,{epsilon:v,momentum:I,spatial:!!Y,trainingMode:!!W,format:be?"NHWC":"NCHW"})},870086:(f,v,I)=>{h.hb("CumSum",f,{exclusive:Number(v),reverse:Number(I)})},870183:(f,v,I)=>{h.hb("DequantizeLinear",f,{axis:v,blockSize:I})},870273:(f,v,I,W,Y,be,qe,lt,$t)=>{h.hb("Attention",f,{numHeads:v,isUnidirectional:I,maskFilterValue:W,scale:Y,doRotary:be,qkvHiddenSizes:qe?Array.from(d().subarray(Number(lt)>>>0,Number(lt)+qe>>>0)):[],pastPresentShareBuffer:!!$t})},870545:f=>{h.hb("BiasAdd",f,void 0)},870600:f=>{h.hb("BiasSplitGelu",f,void 0)},870661:f=>{h.hb("FastGelu",f,void 0)},870717:(f,v,I,W,Y,be,qe,lt,$t,Bt,un,An,Ln,Pr,bl,Ox)=>{h.hb("Conv",f,{format:An?"NHWC":"NCHW",auto_pad:v,dilations:I?Array.from(d().subarray(I>>>0,W>>>0)):[],group:Y,kernel_shape:be?Array.from(d().subarray(be>>>0,qe>>>0)):[],pads:lt?Array.from(d().subarray(lt>>>0,$t>>>0)):[],strides:Bt?Array.from(d().subarray(Bt>>>0,un>>>0)):[],w_is_const:()=>!!s()[Ln>>>0],activation:Lr(Pr),activation_params:bl?Array.from(g().subarray(bl>>>0,Ox>>>0)):[]})},871213:f=>{h.hb("Gelu",f,void 0)},871265:(f,v,I,W)=>{h.hb("GroupQueryAttention",f,{numHeads:v,kvNumHeads:I,scale:W})},871378:(f,v,I,W)=>{h.hb("LayerNormalization",f,{axis:v,epsilon:I,simplified:!!W})},871489:(f,v,I,W)=>{h.hb("LayerNormalization",f,{axis:v,epsilon:I,simplified:!!W})},871600:(f,v,I,W,Y,be)=>{h.hb("MatMulNBits",f,{k:v,n:I,accuracyLevel:W,bits:Y,blockSize:be})},871727:(f,v,I,W,Y,be)=>{h.hb("MultiHeadAttention",f,{numHeads:v,isUnidirectional:I,maskFilterValue:W,scale:Y,doRotary:be})},871886:(f,v)=>{h.hb("QuickGelu",f,{alpha:v})},871950:(f,v,I,W,Y)=>{h.hb("RotaryEmbedding",f,{interleaved:!!v,numHeads:I,rotaryEmbeddingDim:W,scale:Y})},872089:(f,v,I)=>{h.hb("SkipLayerNormalization",f,{epsilon:v,simplified:!!I})},872191:f=>{h.Qb(f)},872225:(f,v)=>h.Sb(f,v,h.zb.Ub,h.zb.errors),872337:(f,v,I)=>{h.hb("SkipLayerNormalization",f,{epsilon:v,simplified:!!I})}};function vb(f,v,I){return Zw(async()=>{await h.Ob(f,v,I)})}function Mb(){return typeof wasmOffsetConverter<"u"}function gm(f){this.name="ExitStatus",this.message=`Program terminated with exit(${f})`,this.status=f}var _m=f=>{f.terminate(),f.onmessage=()=>{}},ww=f=>{Xo.length==0&&(Sw(),Tw(Xo[0]));var v=Xo.pop();if(!v)return 6;Ws.push(v),Yi[f.sb]=v,v.sb=f.sb;var I={cmd:"run",start_routine:f.Vb,arg:f.Hb,pthread_ptr:f.sb};return v.postMessage(I,f.Wb),0},Us=0,Yn=(f,v,...I)=>{for(var W=2*I.length,Y=Om(),be=zm(8*W),qe=be>>>3,lt=0;lt>>0]=$t)}return f=v0(f,0,W,be,v),zf(Y),f};function ym(f){if(re)return Yn(0,1,f);if(It=f,!(0{if(It=f,re)throw vw(f),"unwind";ym(f)},Xo=[],Ws=[],Mw=[],Yi={},bw=f=>{var v=f.sb;delete Yi[v],Xo.push(f),Ws.splice(Ws.indexOf(f),1),f.sb=0,Fm(v)};function xw(){Mw.forEach(f=>f())}var Tw=f=>new Promise(v=>{f.onmessage=Y=>{var be=(Y=Y.data).cmd;if(Y.targetThread&&Y.targetThread!=Ml()){var qe=Yi[Y.targetThread];qe?qe.postMessage(Y,Y.transferList):rn(`Internal error! Worker sent a message "${be}" to target pthread ${Y.targetThread}, but that thread no longer exists!`)}else be==="checkMailbox"?Tf():be==="spawnThread"?ww(Y):be==="cleanupThread"?bw(Yi[Y.thread]):be==="killThread"?(Y=Y.thread,be=Yi[Y],delete Yi[Y],_m(be),Fm(Y),Ws.splice(Ws.indexOf(be),1),be.sb=0):be==="cancelThread"?Yi[Y.thread].postMessage({cmd:"cancel"}):be==="loaded"?(f.loaded=!0,v(f)):be==="alert"?alert(`Thread ${Y.threadId}: ${Y.text}`):Y.target==="setimmediate"?f.postMessage(Y):be==="callHandler"?h[Y.handler](...Y.args):be&&rn(`worker sent an unknown command ${be}`)},f.onerror=Y=>{throw rn(`worker sent an error! ${Y.filename}:${Y.lineno}: ${Y.message}`),Y};var I,W=[];for(I of[])h.propertyIsEnumerable(I)&&W.push(I);f.postMessage({cmd:"load",handlers:W,wasmMemory:kn,wasmModule:jn})});function Sw(){var f=new Worker(new URL(import.meta.url),{type:"module",workerData:"em-pthread",name:"em-pthread"});Xo.push(f)}var xf=f=>{for(;0{var f=Ml(),v=m()[f+52>>>2>>>0];f=m()[f+56>>>2>>>0],b0(v,v-f),zf(v)},xb=(f,v)=>{Us=0,f=x0(f,v),0>>=0);throw v>>>=0,I>>>=0,m()[W.Bb+16>>>2>>>0]=0,m()[W.Bb+4>>>2>>>0]=v,m()[W.Bb+8>>>2>>>0]=I,f}function kw(f,v,I,W){return re?Yn(2,1,f,v,I,W):Ew(f,v,I,W)}function Ew(f,v,I,W){if(f>>>=0,v>>>=0,I>>>=0,W>>>=0,oe===void 0)return rn("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var Y=[];return re&&Y.length===0?kw(f,v,I,W):(f={Vb:I,sb:f,Hb:W,Wb:Y},re?(f.Db="spawnThread",postMessage(f,Y),0):ww(f))}var Cw=typeof TextDecoder<"u"?new TextDecoder:void 0,$w=(f,v,I)=>{var W=(v>>>=0)+I;for(I=v;f[I]&&!(I>=W);)++I;if(16(Y=(240&Y)==224?(15&Y)<<12|be<<6|qe:(7&Y)<<18|be<<12|qe<<6|63&f[v++])?W+=String.fromCharCode(Y):(Y-=65536,W+=String.fromCharCode(55296|Y>>10,56320|1023&Y))}}else W+=String.fromCharCode(Y)}return W},Lr=(f,v)=>(f>>>=0)?$w(a(),f,v):"";function Pw(f,v,I){return re?Yn(3,1,f,v,I):0}function Aw(f,v){if(re)return Yn(4,1,f,v)}var Iw=f=>{for(var v=0,I=0;I=W?v++:2047>=W?v+=2:55296<=W&&57343>=W?(v+=4,++I):v+=3}return v},vl=(f,v,I)=>{var W=a();if(v>>>=0,0=qe&&(qe=65536+((1023&qe)<<10)|1023&f.charCodeAt(++be)),127>=qe){if(v>=I)break;W[v++>>>0]=qe}else{if(2047>=qe){if(v+1>=I)break;W[v++>>>0]=192|qe>>6}else{if(65535>=qe){if(v+2>=I)break;W[v++>>>0]=224|qe>>12}else{if(v+3>=I)break;W[v++>>>0]=240|qe>>18,W[v++>>>0]=128|qe>>12&63}W[v++>>>0]=128|qe>>6&63}W[v++>>>0]=128|63&qe}}W[v>>>0]=0,f=v-Y}else f=0;return f};function Fw(f,v){if(re)return Yn(5,1,f,v)}function zw(f,v,I){if(re)return Yn(6,1,f,v,I)}function Ow(f,v,I){return re?Yn(7,1,f,v,I):0}function Dw(f,v){if(re)return Yn(8,1,f,v)}function Lw(f,v,I){if(re)return Yn(9,1,f,v,I)}function Bw(f,v,I,W){if(re)return Yn(10,1,f,v,I,W)}function Rw(f,v,I,W){if(re)return Yn(11,1,f,v,I,W)}function Nw(f,v,I,W){if(re)return Yn(12,1,f,v,I,W)}function jw(f){if(re)return Yn(13,1,f)}function Vw(f,v){if(re)return Yn(14,1,f,v)}function Uw(f,v,I){if(re)return Yn(15,1,f,v,I)}var Ww,Yo,kb=()=>{wl("")},Zi=f=>{for(var v="";a()[f>>>0];)v+=Ww[a()[f++>>>0]];return v},vm={},Mm={};function _o(f,v,I={}){if(!("argPackAdvance"in v))throw new TypeError("registerType registeredInstance requires argPackAdvance");return function(W,Y,be={}){var qe=Y.name;if(!W)throw new Yo(`type "${qe}" must have a positive integer typeid pointer`);if(Mm.hasOwnProperty(W)){if(be.Jb)return;throw new Yo(`Cannot register type '${qe}' twice`)}Mm[W]=Y,vm.hasOwnProperty(W)&&(Y=vm[W],delete vm[W],Y.forEach(lt=>lt()))}(f,v,I)}var Gw=(f,v,I)=>{switch(v){case 1:return I?W=>s()[W>>>0]:W=>a()[W>>>0];case 2:return I?W=>u()[W>>>1>>>0]:W=>c()[W>>>1>>>0];case 4:return I?W=>d()[W>>>2>>>0]:W=>m()[W>>>2>>>0];case 8:return I?W=>yr[W>>>3]:W=>Hr[W>>>3];default:throw new TypeError(`invalid integer width (${v}): ${f}`)}};function Eb(f,v,I){I>>>=0,_o(f>>>=0,{name:v=Zi(v>>>0),fromWireType:W=>W,toWireType:function(W,Y){if(typeof Y!="bigint"&&typeof Y!="number")throw Y=Y===null?"null":(W=typeof Y)=="object"||W==="array"||W==="function"?Y.toString():""+Y,new TypeError(`Cannot convert "${Y}" to ${this.name}`);return typeof Y=="number"&&(Y=BigInt(Y)),Y},argPackAdvance:Zo,readValueFromPointer:Gw(v,I,v.indexOf("u")==-1),yb:null})}var Zo=8;function Cb(f,v,I,W){_o(f>>>=0,{name:v=Zi(v>>>0),fromWireType:function(Y){return!!Y},toWireType:function(Y,be){return be?I:W},argPackAdvance:Zo,readValueFromPointer:function(Y){return this.fromWireType(a()[Y>>>0])},yb:null})}var bm=[],yo=[];function xm(f){9<(f>>>=0)&&--yo[f+1]==0&&(yo[f]=void 0,bm.push(f))}var Si=f=>{if(!f)throw new Yo("Cannot use deleted val. handle = "+f);return yo[f]},ki=f=>{switch(f){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let v=bm.pop()||yo.length;return yo[v]=f,yo[v+1]=1,v}};function Tm(f){return this.fromWireType(m()[f>>>2>>>0])}var $b={name:"emscripten::val",fromWireType:f=>{var v=Si(f);return xm(f),v},toWireType:(f,v)=>ki(v),argPackAdvance:Zo,readValueFromPointer:Tm,yb:null};function Pb(f){return _o(f>>>0,$b)}var Ab=(f,v)=>{switch(v){case 4:return function(I){return this.fromWireType(g()[I>>>2>>>0])};case 8:return function(I){return this.fromWireType(y()[I>>>3>>>0])};default:throw new TypeError(`invalid float width (${v}): ${f}`)}};function Ib(f,v,I){I>>>=0,_o(f>>>=0,{name:v=Zi(v>>>0),fromWireType:W=>W,toWireType:(W,Y)=>Y,argPackAdvance:Zo,readValueFromPointer:Ab(v,I),yb:null})}function Fb(f,v,I,W,Y){if(f>>>=0,I>>>=0,v=Zi(v>>>0),Y===-1&&(Y=4294967295),Y=lt=>lt,W===0){var be=32-8*I;Y=lt=>lt<>>be}var qe=v.includes("unsigned")?function(lt,$t){return $t>>>0}:function(lt,$t){return $t};_o(f,{name:v,fromWireType:Y,toWireType:qe,argPackAdvance:Zo,readValueFromPointer:Gw(v,I,W!==0),yb:null})}function zb(f,v,I){function W(be){var qe=m()[be>>>2>>>0];return be=m()[be+4>>>2>>>0],new Y(s().buffer,be,qe)}var Y=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][v];_o(f>>>=0,{name:I=Zi(I>>>0),fromWireType:W,argPackAdvance:Zo,readValueFromPointer:W},{Jb:!0})}function Ob(f,v){f>>>=0;var I=(v=Zi(v>>>0))==="std::string";_o(f,{name:v,fromWireType:function(W){var Y=m()[W>>>2>>>0],be=W+4;if(I)for(var qe=be,lt=0;lt<=Y;++lt){var $t=be+lt;if(lt==Y||a()[$t>>>0]==0){if(qe=Lr(qe,$t-qe),Bt===void 0)var Bt=qe;else Bt+="\0",Bt+=qe;qe=$t+1}}else{for(Bt=Array(Y),lt=0;lt>>0]);Bt=Bt.join("")}return eo(W),Bt},toWireType:function(W,Y){Y instanceof ArrayBuffer&&(Y=new Uint8Array(Y));var be=typeof Y=="string";if(!(be||Y instanceof Uint8Array||Y instanceof Uint8ClampedArray||Y instanceof Int8Array))throw new Yo("Cannot pass non-string to std::string");var qe=I&&be?Iw(Y):Y.length,lt=If(4+qe+1),$t=lt+4;if(m()[lt>>>2>>>0]=qe,I&&be)vl(Y,$t,qe+1);else if(be)for(be=0;be>>0]=Bt}else for(be=0;be>>0]=Y[be];return W!==null&&W.push(eo,lt),lt},argPackAdvance:Zo,readValueFromPointer:Tm,yb(W){eo(W)}})}var qw=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,Db=(f,v)=>{for(var I=f>>1,W=I+v/2;!(I>=W)&&c()[I>>>0];)++I;if(32<(I<<=1)-f&&qw)return qw.decode(a().slice(f,I));for(I="",W=0;!(W>=v/2);++W){var Y=u()[f+2*W>>>1>>>0];if(Y==0)break;I+=String.fromCharCode(Y)}return I},Lb=(f,v,I)=>{if(I??(I=2147483647),2>I)return 0;var W=v;I=(I-=2)<2*f.length?I/2:f.length;for(var Y=0;Y>>1>>>0]=be,v+=2}return u()[v>>>1>>>0]=0,v-W},Bb=f=>2*f.length,Rb=(f,v)=>{for(var I=0,W="";!(I>=v/4);){var Y=d()[f+4*I>>>2>>>0];if(Y==0)break;++I,65536<=Y?(Y-=65536,W+=String.fromCharCode(55296|Y>>10,56320|1023&Y)):W+=String.fromCharCode(Y)}return W},Nb=(f,v,I)=>{if(v>>>=0,I??(I=2147483647),4>I)return 0;var W=v;I=W+I-4;for(var Y=0;Y=be&&(be=65536+((1023&be)<<10)|1023&f.charCodeAt(++Y)),d()[v>>>2>>>0]=be,(v+=4)+4>I)break}return d()[v>>>2>>>0]=0,v-W},jb=f=>{for(var v=0,I=0;I=W&&++I,v+=4}return v};function Vb(f,v,I){if(f>>>=0,v>>>=0,I=Zi(I>>>=0),v===2)var W=Db,Y=Lb,be=Bb,qe=lt=>c()[lt>>>1>>>0];else v===4&&(W=Rb,Y=Nb,be=jb,qe=lt=>m()[lt>>>2>>>0]);_o(f,{name:I,fromWireType:lt=>{for(var $t,Bt=m()[lt>>>2>>>0],un=lt+4,An=0;An<=Bt;++An){var Ln=lt+4+An*v;An!=Bt&&qe(Ln)!=0||(un=W(un,Ln-un),$t===void 0?$t=un:($t+="\0",$t+=un),un=Ln+v)}return eo(lt),$t},toWireType:(lt,$t)=>{if(typeof $t!="string")throw new Yo(`Cannot pass non-string to C++ string type ${I}`);var Bt=be($t),un=If(4+Bt+v);return m()[un>>>2>>>0]=Bt/v,Y($t,un+4,Bt+v),lt!==null&<.push(eo,un),un},argPackAdvance:Zo,readValueFromPointer:Tm,yb(lt){eo(lt)}})}function Ub(f,v){_o(f>>>=0,{Kb:!0,name:v=Zi(v>>>0),argPackAdvance:0,fromWireType:()=>{},toWireType:()=>{}})}var Wb=()=>1;function Gb(f){Im(f>>>0,!K,1,!B,131072,!1),xw()}var Hw=f=>{if(!di)try{if(f(),!(0>>=0,typeof Atomics.Xb=="function"&&(Atomics.Xb(d(),f>>>2,f).value.then(Tf),f+=128,Atomics.store(d(),f>>>2,1))}var Tf=()=>{var f=Ml();f&&(Sm(f),Hw(M0))};function qb(f,v){(f>>>=0)==v>>>0?setTimeout(Tf):re?postMessage({targetThread:f,cmd:"checkMailbox"}):(f=Yi[f])&&f.postMessage({cmd:"checkMailbox"})}var km=[];function Hb(f,v,I,W,Y){for(v>>>=0,W/=2,km.length=W,I=Y>>>0>>>3,Y=0;Y>>0];return(v?mm[v]:zx[f])(...km)}function Kb(f){f>>>=0,re?postMessage({cmd:"cleanupThread",thread:f}):bw(Yi[f])}function Qb(f){}var Em=(f,v)=>{var I=Mm[f];if(I===void 0)throw f=_0(f),I=Zi(f),eo(f),new Yo(`${v} has unknown type ${I}`);return I},Kw=(f,v,I)=>{var W=[];return f=f.toWireType(W,I),W.length&&(m()[v>>>2>>>0]=ki(W)),f};function Xb(f,v,I){return v>>>=0,I>>>=0,f=Si(f>>>0),v=Em(v,"emval::as"),Kw(v,I,f)}var Sf=f=>{try{f()}catch(v){wl(v)}},Jo=0,Ji=null,Qw=0,kf=[],Xw={},Yw={},Yb=0,Cm=null,Zb=[];function Zw(f){return function(v){if(!di){if(Jo===0){var I=!1,W=!1;v((Y=0)=>{if(!di&&(Qw=Y,I=!0,W)){Jo=2,Sf(()=>k0(Ji)),typeof Browser<"u"&&Browser.Cb.Ib&&Browser.Cb.resume(),Y=!1;try{var be=function(){var $t=d()[Ji+8>>>2>>>0];return $t=Ht[Yw[$t]],--Us,$t()}()}catch($t){be=$t,Y=!0}var qe=!1;if(!Ji){var lt=Cm;lt&&(Cm=null,(Y?lt.reject:lt.resolve)(be),qe=!0)}if(Y&&!qe)throw be}}),W=!0,I||(Jo=1,Ji=function(){var Y=If(65548),be=Y+12;m()[Y>>>2>>>0]=be,m()[Y+4>>>2>>>0]=be+65536,be=kf[0];var qe=Xw[be];return qe===void 0&&(qe=Yb++,Xw[be]=qe,Yw[qe]=be),be=qe,d()[Y+8>>>2>>>0]=be,Y}(),typeof Browser<"u"&&Browser.Cb.Ib&&Browser.Cb.pause(),Sf(()=>T0(Ji)))}else Jo===2?(Jo=0,Sf(E0),eo(Ji),Ji=null,Zb.forEach(Hw)):wl(`invalid state: ${Jo}`);return Qw}}(v=>{f().then(v)})}function Jb(f){return f>>>=0,Zw(()=>(f=Si(f)).then(ki))}var Ef=[];function ex(f,v,I,W){return I>>>=0,W>>>=0,(f=Ef[f>>>0])(null,v=Si(v>>>0),I,W)}var tx={},Cf=f=>{var v=tx[f];return v===void 0?Zi(f):v};function nx(f,v,I,W,Y){return I>>>=0,W>>>=0,Y>>>=0,(f=Ef[f>>>0])(v=Si(v>>>0),v[I=Cf(I)],W,Y)}var Jw=()=>typeof globalThis=="object"?globalThis:Function("return this")();function rx(f){return(f>>>=0)==0?ki(Jw()):(f=Cf(f),ki(Jw()[f]))}var ix=f=>{var v=Ef.length;return Ef.push(f),v},ox=(f,v)=>{for(var I=Array(f),W=0;W>>2>>>0],"parameter "+W);return I},e0=(f,v)=>Object.defineProperty(v,"name",{value:f});function sx(f,v,I){var W=(v=ox(f,v>>>0)).shift();f--;var Y=`return function (obj, func, destructorsRef, args) { +`,be=0,qe=[];I===0&&qe.push("obj");for(var lt=["retType"],$t=[W],Bt=0;Btun.name).join(", ")}) => ${W.name}>`,ix(e0(I,f))}function ax(f){return f=Cf(f>>>0),ki(h[f])}function lx(f,v){return v>>>=0,f=Si(f>>>0),v=Si(v),ki(f[v])}function ux(f){9<(f>>>=0)&&(yo[f+1]+=1)}function dx(){return ki([])}function cx(f){f=Si(f>>>0);for(var v=Array(f.length),I=0;I>>0))}function fx(){return ki({})}function hx(f){for(var v=Si(f>>>=0);v.length;){var I=v.pop();v.pop()(I)}xm(f)}function mx(f,v,I){v>>>=0,I>>>=0,f=Si(f>>>0),v=Si(v),I=Si(I),f[v]=I}function gx(f,v){return v>>>=0,f=(f=Em(f>>>0,"_emval_take_value")).readValueFromPointer(v),ki(f)}function _x(f,v){f=-9007199254740992>f||9007199254740992>>=0,f=new Date(1e3*f),d()[v>>>2>>>0]=f.getUTCSeconds(),d()[v+4>>>2>>>0]=f.getUTCMinutes(),d()[v+8>>>2>>>0]=f.getUTCHours(),d()[v+12>>>2>>>0]=f.getUTCDate(),d()[v+16>>>2>>>0]=f.getUTCMonth(),d()[v+20>>>2>>>0]=f.getUTCFullYear()-1900,d()[v+24>>>2>>>0]=f.getUTCDay(),f=(f.getTime()-Date.UTC(f.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,d()[v+28>>>2>>>0]=f}var t0=f=>f%4==0&&(f%100!=0||f%400==0),n0=[0,31,60,91,121,152,182,213,244,274,305,335],r0=[0,31,59,90,120,151,181,212,243,273,304,334];function yx(f,v){f=-9007199254740992>f||9007199254740992>>=0,f=new Date(1e3*f),d()[v>>>2>>>0]=f.getSeconds(),d()[v+4>>>2>>>0]=f.getMinutes(),d()[v+8>>>2>>>0]=f.getHours(),d()[v+12>>>2>>>0]=f.getDate(),d()[v+16>>>2>>>0]=f.getMonth(),d()[v+20>>>2>>>0]=f.getFullYear()-1900,d()[v+24>>>2>>>0]=f.getDay();var I=(t0(f.getFullYear())?n0:r0)[f.getMonth()]+f.getDate()-1|0;d()[v+28>>>2>>>0]=I,d()[v+36>>>2>>>0]=-60*f.getTimezoneOffset(),I=new Date(f.getFullYear(),6,1).getTimezoneOffset();var W=new Date(f.getFullYear(),0,1).getTimezoneOffset();f=0|(I!=W&&f.getTimezoneOffset()==Math.min(W,I)),d()[v+32>>>2>>>0]=f}function wx(f){f>>>=0;var v=new Date(d()[f+20>>>2>>>0]+1900,d()[f+16>>>2>>>0],d()[f+12>>>2>>>0],d()[f+8>>>2>>>0],d()[f+4>>>2>>>0],d()[f>>>2>>>0],0),I=d()[f+32>>>2>>>0],W=v.getTimezoneOffset(),Y=new Date(v.getFullYear(),6,1).getTimezoneOffset(),be=new Date(v.getFullYear(),0,1).getTimezoneOffset(),qe=Math.min(be,Y);return 0>I?d()[f+32>>>2>>>0]=+(Y!=be&&qe==W):0>>2>>>0]=v.getDay(),I=(t0(v.getFullYear())?n0:r0)[v.getMonth()]+v.getDate()-1|0,d()[f+28>>>2>>>0]=I,d()[f>>>2>>>0]=v.getSeconds(),d()[f+4>>>2>>>0]=v.getMinutes(),d()[f+8>>>2>>>0]=v.getHours(),d()[f+12>>>2>>>0]=v.getDate(),d()[f+16>>>2>>>0]=v.getMonth(),d()[f+20>>>2>>>0]=v.getYear(),f=v.getTime(),BigInt(isNaN(f)?-1:f/1e3)}function i0(f,v,I,W,Y,be,qe){return re?Yn(16,1,f,v,I,W,Y,be,qe):-52}function o0(f,v,I,W,Y,be){if(re)return Yn(17,1,f,v,I,W,Y,be)}function vx(f,v,I,W){f>>>=0,v>>>=0,I>>>=0,W>>>=0;var Y=new Date().getFullYear(),be=new Date(Y,0,1),qe=new Date(Y,6,1);Y=be.getTimezoneOffset();var lt=qe.getTimezoneOffset(),$t=Math.max(Y,lt);m()[f>>>2>>>0]=60*$t,d()[v>>>2>>>0]=+(Y!=lt),be=(f=Bt=>Bt.toLocaleTimeString(void 0,{hour12:!1,timeZoneName:"short"}).split(" ")[1])(be),qe=f(qe),lt{$m.length=0;for(var I;I=a()[f++>>>0];){var W=I!=105;v+=(W&=I!=112)&&v%8?4:0,$m.push(I==112?m()[v>>>2>>>0]:I==106?yr[v>>>3]:I==105?d()[v>>>2>>>0]:y()[v>>>3>>>0]),v+=W?8:4}return $m};function Mx(f,v,I){return f>>>=0,v=s0(v>>>0,I>>>0),mm[f](...v)}function bx(f,v,I){return f>>>=0,v=s0(v>>>0,I>>>0),mm[f](...v)}var xx=()=>{},Tx=()=>Date.now();function Sx(f,v){return rn(Lr(f>>>0,v>>>0))}var a0,kx=()=>{throw Us+=1,"unwind"};function Ex(){return 4294901760}a0=()=>performance.timeOrigin+performance.now();var Cx=()=>navigator.hardwareConcurrency;function $x(){return wl("Cannot use emscripten_pc_get_function without -sUSE_OFFSET_CONVERTER"),0}function Px(f){f>>>=0;var v=a().length;if(f<=v||4294901760=I;I*=2){var W=v*(1+.2/I);W=Math.min(W,f+100663296);var Y=Math;W=Math.max(f,W);e:{Y=(Y.min.call(Y,4294901760,W+(65536-W%65536)%65536)-kn.buffer.byteLength+65535)/65536;try{kn.grow(Y),Cr();var be=1;break e}catch{}be=void 0}if(be)return!0}return!1}var $f=()=>(wl("Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER"),0),Zc={},l0=f=>{f.forEach(v=>{$f()})};function Ax(){var f=Error().stack.toString().split(` +`);return f[0]=="Error"&&f.shift(),l0(f),Zc.Gb=$f(),Zc.Tb=f,Zc.Gb}function Ix(f,v,I){if(f>>>=0,v>>>=0,Zc.Gb==f)var W=Zc.Tb;else(W=Error().stack.toString().split(` +`))[0]=="Error"&&W.shift(),l0(W);for(var Y=3;W[Y]&&$f()!=f;)++Y;for(f=0;f>>2>>>0]=$f();return f}var Pm,Am={},u0=()=>{if(!Pm){var f,v={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",_:Qe};for(f in Am)Am[f]===void 0?delete v[f]:v[f]=Am[f];var I=[];for(f in v)I.push(`${f}=${v[f]}`);Pm=I}return Pm};function d0(f,v){if(re)return Yn(18,1,f,v);f>>>=0,v>>>=0;var I=0;return u0().forEach((W,Y)=>{var be=v+I;for(Y=m()[f+4*Y>>>2>>>0]=be,be=0;be>>0]=W.charCodeAt(be);s()[Y>>>0]=0,I+=W.length+1}),0}function c0(f,v){if(re)return Yn(19,1,f,v);f>>>=0,v>>>=0;var I=u0();m()[f>>>2>>>0]=I.length;var W=0;return I.forEach(Y=>W+=Y.length+1),m()[v>>>2>>>0]=W,0}function p0(f){return re?Yn(20,1,f):52}function f0(f,v,I,W){return re?Yn(21,1,f,v,I,W):52}function h0(f,v,I,W){return re?Yn(22,1,f,v,I,W):70}var Fx=[null,[],[]];function m0(f,v,I,W){if(re)return Yn(23,1,f,v,I,W);v>>>=0,I>>>=0,W>>>=0;for(var Y=0,be=0;be>>2>>>0],lt=m()[v+4>>>2>>>0];v+=8;for(var $t=0;$t>>0],un=Fx[f];Bt===0||Bt===10?((f===1?ln:rn)($w(un,0)),un.length=0):un.push(Bt)}Y+=lt}return m()[W>>>2>>>0]=Y,0}re||function(){for(var f=h.numThreads-1;f--;)Sw();Yc.unshift(()=>{Ti++,function(v){re?v():Promise.all(Xo.map(Tw)).then(v)}(()=>bf())})}();for(var g0=Array(256),Pf=0;256>Pf;++Pf)g0[Pf]=String.fromCharCode(Pf);Ww=g0,Yo=h.BindingError=class extends Error{constructor(f){super(f),this.name="BindingError"}},h.InternalError=class extends Error{constructor(f){super(f),this.name="InternalError"}},yo.push(0,1,void 0,1,null,1,!0,1,!1,1),h.count_emval_handles=()=>yo.length/2-5-bm.length;var zx=[ym,vw,kw,Pw,Aw,Fw,zw,Ow,Dw,Lw,Bw,Rw,Nw,jw,Vw,Uw,i0,o0,d0,c0,p0,f0,h0,m0],Ht=function(){function f(I,W){return Ht=I.exports,Ht=function(){var Y=Ht,be={};for(let[qe,lt]of Object.entries(Y))be[qe]=typeof lt=="function"?(...$t)=>{kf.push(qe);try{return lt(...$t)}finally{di||(kf.pop(),Ji&&Jo===1&&kf.length===0&&(Jo=0,Us+=1,Sf(S0),typeof Fibers<"u"&&Fibers.ac()))}}:lt;return be}(),Ht=function(){var Y=Ht,be=lt=>$t=>lt($t)>>>0,qe=lt=>()=>lt()>>>0;return(Y=Object.assign({},Y)).Aa=be(Y.Aa),Y.db=qe(Y.db),Y.eb=be(Y.eb),Y.emscripten_main_runtime_thread_id=qe(Y.emscripten_main_runtime_thread_id),Y.qb=be(Y.qb),Y.rb=qe(Y.rb),Y}(),Mw.push(Ht.gb),$r.unshift(Ht.za),jn=W,bf(),Ht}var v=yw();if(Ti++,h.instantiateWasm)try{return h.instantiateWasm(v,f)}catch(I){rn(`Module.instantiateWasm callback failed with error: ${I}`),$(I)}return hm||(hm=h.locateFile?hw("ort-wasm-simd-threaded.jsep.wasm")?"ort-wasm-simd-threaded.jsep.wasm":h.locateFile?h.locateFile("ort-wasm-simd-threaded.jsep.wasm",ht):ht+"ort-wasm-simd-threaded.jsep.wasm":new URL(r("./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm"),r.b).href),function(I,W){var Y=hm;return Ft||typeof WebAssembly.instantiateStreaming!="function"||hw(Y)||mw(Y)||typeof fetch!="function"?_w(Y,I,W):fetch(Y,{credentials:"same-origin"}).then(be=>WebAssembly.instantiateStreaming(be,I).then(W,function(qe){return rn(`wasm streaming compile failed: ${qe}`),rn("falling back to ArrayBuffer instantiation"),_w(Y,I,W)}))}(v,function(I){f(I.instance,I.module)}).catch($),{}}(),_0=f=>(_0=Ht.Aa)(f),y0=()=>(y0=Ht.Ba)();h._OrtInit=(f,v)=>(h._OrtInit=Ht.Ca)(f,v),h._OrtGetLastError=(f,v)=>(h._OrtGetLastError=Ht.Da)(f,v),h._OrtCreateSessionOptions=(f,v,I,W,Y,be,qe,lt,$t,Bt)=>(h._OrtCreateSessionOptions=Ht.Ea)(f,v,I,W,Y,be,qe,lt,$t,Bt),h._OrtAppendExecutionProvider=(f,v)=>(h._OrtAppendExecutionProvider=Ht.Fa)(f,v),h._OrtAddFreeDimensionOverride=(f,v,I)=>(h._OrtAddFreeDimensionOverride=Ht.Ga)(f,v,I),h._OrtAddSessionConfigEntry=(f,v,I)=>(h._OrtAddSessionConfigEntry=Ht.Ha)(f,v,I),h._OrtReleaseSessionOptions=f=>(h._OrtReleaseSessionOptions=Ht.Ia)(f),h._OrtCreateSession=(f,v,I)=>(h._OrtCreateSession=Ht.Ja)(f,v,I),h._OrtReleaseSession=f=>(h._OrtReleaseSession=Ht.Ka)(f),h._OrtGetInputOutputCount=(f,v,I)=>(h._OrtGetInputOutputCount=Ht.La)(f,v,I),h._OrtGetInputName=(f,v)=>(h._OrtGetInputName=Ht.Ma)(f,v),h._OrtGetOutputName=(f,v)=>(h._OrtGetOutputName=Ht.Na)(f,v),h._OrtFree=f=>(h._OrtFree=Ht.Oa)(f),h._OrtCreateTensor=(f,v,I,W,Y,be)=>(h._OrtCreateTensor=Ht.Pa)(f,v,I,W,Y,be),h._OrtGetTensorData=(f,v,I,W,Y)=>(h._OrtGetTensorData=Ht.Qa)(f,v,I,W,Y),h._OrtReleaseTensor=f=>(h._OrtReleaseTensor=Ht.Ra)(f),h._OrtCreateRunOptions=(f,v,I,W)=>(h._OrtCreateRunOptions=Ht.Sa)(f,v,I,W),h._OrtAddRunConfigEntry=(f,v,I)=>(h._OrtAddRunConfigEntry=Ht.Ta)(f,v,I),h._OrtReleaseRunOptions=f=>(h._OrtReleaseRunOptions=Ht.Ua)(f),h._OrtCreateBinding=f=>(h._OrtCreateBinding=Ht.Va)(f),h._OrtBindInput=(f,v,I)=>(h._OrtBindInput=Ht.Wa)(f,v,I),h._OrtBindOutput=(f,v,I,W)=>(h._OrtBindOutput=Ht.Xa)(f,v,I,W),h._OrtClearBoundOutputs=f=>(h._OrtClearBoundOutputs=Ht.Ya)(f),h._OrtReleaseBinding=f=>(h._OrtReleaseBinding=Ht.Za)(f),h._OrtRunWithBinding=(f,v,I,W,Y)=>(h._OrtRunWithBinding=Ht._a)(f,v,I,W,Y),h._OrtRun=(f,v,I,W,Y,be,qe,lt)=>(h._OrtRun=Ht.$a)(f,v,I,W,Y,be,qe,lt),h._OrtEndProfiling=f=>(h._OrtEndProfiling=Ht.ab)(f),h._JsepOutput=(f,v,I)=>(h._JsepOutput=Ht.bb)(f,v,I),h._JsepGetNodeName=f=>(h._JsepGetNodeName=Ht.cb)(f);var Af,Ml=()=>(Ml=Ht.db)(),If=h._malloc=f=>(If=h._malloc=Ht.eb)(f),eo=h._free=f=>(eo=h._free=Ht.fb)(f),Im=(f,v,I,W,Y,be)=>(Im=Ht.ib)(f,v,I,W,Y,be),w0=()=>(w0=Ht.jb)(),v0=(f,v,I,W,Y)=>(v0=Ht.kb)(f,v,I,W,Y),Fm=f=>(Fm=Ht.lb)(f),Ff=f=>(Ff=Ht.mb)(f),M0=()=>(M0=Ht.nb)(),b0=(f,v)=>(b0=Ht.ob)(f,v),zf=f=>(zf=Ht.pb)(f),zm=f=>(zm=Ht.qb)(f),Om=()=>(Om=Ht.rb)(),x0=h.dynCall_ii=(f,v)=>(x0=h.dynCall_ii=Ht.tb)(f,v),T0=f=>(T0=Ht.ub)(f),S0=()=>(S0=Ht.vb)(),k0=f=>(k0=Ht.wb)(f),E0=()=>(E0=Ht.xb)();function C0(){0Om(),h.stackRestore=f=>zf(f),h.stackAlloc=f=>zm(f),h.UTF8ToString=Lr,h.stringToUTF8=vl,h.lengthBytesUTF8=Iw,Qo=function f(){Af||C0(),Af||(Qo=f)},C0(),R}),St=ft,((t=globalThis.self)==null?void 0:t.name)==="em-pthread"&&ft()}),Ke,Vt,jt,Kt,Qt,Jt,qt,En,Hn=M(()=>{var t,i;le(),Ke=import.meta.url??(typeof document<"u"?(t=document.currentScript)==null?void 0:t.src:typeof self<"u"?(i=self.location)==null?void 0:i.href:void 0),Vt=typeof location>"u"?void 0:location.origin,jt=(s,a)=>{try{let u=a??Ke;return(u?new URL(s,u):new URL(s)).origin===Vt}catch{return!1}},Kt=async s=>{let a=await(await fetch(s,{credentials:"same-origin"})).blob();return URL.createObjectURL(a)},Qt=(ct(),S(Te)).default,Jt=async()=>{if(!Ke)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(jt(Ke))return[void 0,Qt()];let s=await Kt(Ke);return[s,Qt(s)]},qt=(Nt(),S(ot)).default,En=async(s,a,u)=>[void 0,qt]}),Cn,tt,Ct,Lt,nr,Fi,_i,Nn,cr=M(()=>{Hn(),tt=!1,Ct=!1,Lt=!1,nr=()=>{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}},Fi=()=>{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}},_i=async t=>{if(tt)return Promise.resolve();if(Ct)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Lt)throw new Error("previous call to 'initializeWebAssembly()' failed.");Ct=!0;let i=t.initTimeout,s=t.numThreads;if(!Fi())throw new Error("WebAssembly SIMD is not supported in the current environment.");let a=nr();s>1&&!a&&(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."),t.numThreads=s=1);let u=t.wasmPaths,c=typeof u=="string"?u:void 0,d=u==null?void 0:u.mjs,m=(d==null?void 0:d.href)??d,g=u==null?void 0:u.wasm,y=(g==null?void 0:g.href)??g,E=t.wasmBinary,[$,h]=await En(m,c,s>1),R=!1,B=[];if(i>0&&B.push(new Promise(K=>{setTimeout(()=>{R=!0,K()},i)})),B.push(new Promise((K,re)=>{let oe={numThreads:s};E?oe.wasmBinary=E:(y||c)&&(oe.locateFile=(ee,_e)=>y??(c??_e)+ee),h(oe).then(ee=>{Ct=!1,tt=!0,Cn=ee,K(),$&&URL.revokeObjectURL($)},ee=>{Ct=!1,Lt=!0,re(ee)})})),await Promise.race(B),R)throw new Error(`WebAssembly backend initializing failed due to timeout: ${i}ms`)},Nn=()=>{if(tt&&Cn)return Cn;throw new Error("WebAssembly is not initialized yet.")}}),Vn,si,Fn,zi=M(()=>{cr(),Vn=(t,i)=>{let s=Nn(),a=s.lengthBytesUTF8(t)+1,u=s._malloc(a);return s.stringToUTF8(t,u,a),i.push(u),u},si=(t,i,s,a)=>{if(typeof t=="object"&&t!==null){if(s.has(t))throw new Error("Circular reference in options");s.add(t)}Object.entries(t).forEach(([u,c])=>{let d=i?i+u:u;if(typeof c=="object")si(c,d+".",s,a);else if(typeof c=="string"||typeof c=="number")a(d,c.toString());else if(typeof c=="boolean")a(d,c?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof c}`)})},Fn=t=>{let i=Nn(),s=i.stackSave();try{let a=i.stackAlloc(8);i._OrtGetLastError(a,a+4);let u=i.HEAP32[a/4],c=i.HEAPU32[a/4+1],d=c?i.UTF8ToString(c):"";throw new Error(`${t} ERROR_CODE: ${u}, ERROR_MESSAGE: ${d}`)}finally{i.stackRestore(s)}}}),yi,vs=M(()=>{cr(),zi(),yi=t=>{let i=Nn(),s=0,a=[],u=t||{};try{if((t==null?void 0:t.logSeverityLevel)===void 0)u.logSeverityLevel=2;else if(typeof t.logSeverityLevel!="number"||!Number.isInteger(t.logSeverityLevel)||t.logSeverityLevel<0||t.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${t.logSeverityLevel}`);if((t==null?void 0:t.logVerbosityLevel)===void 0)u.logVerbosityLevel=0;else if(typeof t.logVerbosityLevel!="number"||!Number.isInteger(t.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${t.logVerbosityLevel}`);(t==null?void 0:t.terminate)===void 0&&(u.terminate=!1);let c=0;return(t==null?void 0:t.tag)!==void 0&&(c=Vn(t.tag,a)),s=i._OrtCreateRunOptions(u.logSeverityLevel,u.logVerbosityLevel,!!u.terminate,c),s===0&&Fn("Can't create run options."),(t==null?void 0:t.extra)!==void 0&&si(t.extra,"",new WeakSet,(d,m)=>{let g=Vn(d,a),y=Vn(m,a);i._OrtAddRunConfigEntry(s,g,y)!==0&&Fn(`Can't set a run config entry: ${d} - ${m}.`)}),[s,a]}catch(c){throw s!==0&&i._OrtReleaseRunOptions(s),a.forEach(d=>i._free(d)),c}}}),Po,Ao,Io,Fo,Oi,Ms=M(()=>{cr(),zi(),Po=t=>{switch(t){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${t}`)}},Ao=t=>{switch(t){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${t}`)}},Io=t=>{t.extra||(t.extra={}),t.extra.session||(t.extra.session={});let i=t.extra.session;i.use_ort_model_bytes_directly||(i.use_ort_model_bytes_directly="1"),t.executionProviders&&t.executionProviders.some(s=>(typeof s=="string"?s:s.name)==="webgpu")&&(t.enableMemPattern=!1)},Fo=(t,i,s)=>{for(let a of i){let u=typeof a=="string"?a:a.name;switch(u){case"webnn":if(u="WEBNN",typeof a!="string"){let d=a==null?void 0:a.deviceType;if(d){let m=Vn("deviceType",s),g=Vn(d,s);Nn()._OrtAddSessionConfigEntry(t,m,g)!==0&&Fn(`Can't set a session config entry: 'deviceType' - ${d}.`)}}break;case"webgpu":if(u="JS",typeof a!="string"){let d=a;if(d!=null&&d.preferredLayout){if(d.preferredLayout!=="NCHW"&&d.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${d.preferredLayout}`);let m=Vn("preferredLayout",s),g=Vn(d.preferredLayout,s);Nn()._OrtAddSessionConfigEntry(t,m,g)!==0&&Fn(`Can't set a session config entry: 'preferredLayout' - ${d.preferredLayout}.`)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${u}`)}let c=Vn(u,s);Nn()._OrtAppendExecutionProvider(t,c)!==0&&Fn(`Can't append execution provider: ${u}.`)}},Oi=t=>{let i=Nn(),s=0,a=[],u=t||{};Io(u);try{let c=Po(u.graphOptimizationLevel??"all"),d=Ao(u.executionMode??"sequential"),m=typeof u.logId=="string"?Vn(u.logId,a):0,g=u.logSeverityLevel??2;if(!Number.isInteger(g)||g<0||g>4)throw new Error(`log serverity level is not valid: ${g}`);let y=u.logVerbosityLevel??0;if(!Number.isInteger(y)||y<0||y>4)throw new Error(`log verbosity level is not valid: ${y}`);let E=typeof u.optimizedModelFilePath=="string"?Vn(u.optimizedModelFilePath,a):0;if(s=i._OrtCreateSessionOptions(c,!!u.enableCpuMemArena,!!u.enableMemPattern,d,!!u.enableProfiling,0,m,g,y,E),s===0&&Fn("Can't create session options."),u.executionProviders&&Fo(s,u.executionProviders,a),u.enableGraphCapture!==void 0){if(typeof u.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${u.enableGraphCapture}`);let $=Vn("enableGraphCapture",a),h=Vn(u.enableGraphCapture.toString(),a);i._OrtAddSessionConfigEntry(s,$,h)!==0&&Fn(`Can't set a session config entry: 'enableGraphCapture' - ${u.enableGraphCapture}.`)}if(u.freeDimensionOverrides)for(let[$,h]of Object.entries(u.freeDimensionOverrides)){if(typeof $!="string")throw new Error(`free dimension override name must be a string: ${$}`);if(typeof h!="number"||!Number.isInteger(h)||h<0)throw new Error(`free dimension override value must be a non-negative integer: ${h}`);let R=Vn($,a);i._OrtAddFreeDimensionOverride(s,R,h)!==0&&Fn(`Can't set a free dimension override: ${$} - ${h}.`)}return u.extra!==void 0&&si(u.extra,"",new WeakSet,($,h)=>{let R=Vn($,a),B=Vn(h,a);i._OrtAddSessionConfigEntry(s,R,B)!==0&&Fn(`Can't set a session config entry: ${$} - ${h}.`)}),[s,a]}catch(c){throw s!==0&&i._OrtReleaseSessionOptions(s),a.forEach(d=>i._free(d)),c}}}),so,ai,wi,vi,Ki,ao,lo,Xt=M(()=>{so=t=>{switch(t){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: ${t}`)}},ai=t=>{switch(t){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: ${t}`)}},wi=(t,i)=>{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][t],a=typeof i=="number"?i:i.reduce((u,c)=>u*c,1);return s>0?Math.ceil(a*s):void 0},vi=t=>{switch(t){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: ${t}`)}},Ki=t=>{switch(t){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: ${t}`)}},ao=t=>t==="float32"||t==="float16"||t==="int32"||t==="int64"||t==="uint32"||t==="uint8"||t==="bool",lo=t=>{switch(t){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;default:throw new Error(`unsupported data location: ${t}`)}}}),Qi,zo=M(()=>{le(),Qi=async t=>{if(typeof t=="string"){let i=await fetch(t);if(!i.ok)throw new Error(`failed to load external data file: ${t}`);let s=i.headers.get("Content-Length"),a=s?parseInt(s,10):0;if(a<1073741824)return new Uint8Array(await i.arrayBuffer());{if(!i.body)throw new Error(`failed to load external data file: ${t}, no response body.`);let u=i.body.getReader(),c;try{c=new ArrayBuffer(a)}catch(m){if(m instanceof RangeError){let g=Math.ceil(a/65536);c=new WebAssembly.Memory({initial:g,maximum:g}).buffer}else throw m}let d=0;for(;;){let{done:m,value:g}=await u.read();if(m)break;let y=g.byteLength;new Uint8Array(c,d,y).set(g),d+=y}return new Uint8Array(c,0,a)}}else return t instanceof Blob?new Uint8Array(await t.arrayBuffer()):t instanceof Uint8Array?t:new Uint8Array(t)}}),Oo,uo,Do,Lo,co,Bo,Rn,zr=M(()=>{Xt(),Oo=["V","I","W","E","F"],uo=(t,i)=>{console.log(`[${Oo[t]},${new Date().toISOString()}]${i}`)},co=(t,i)=>{Do=t,Lo=i},Bo=(t,i)=>{let s=Ki(t),a=Ki(Do);s>=a&&uo(s,typeof i=="function"?i():i)},Rn=(...t)=>{Lo&&Bo(...t)}}),Se,T=M(()=>{Xt(),Se=(t,i)=>new(vi(i))(t)}),Q=M(()=>{}),ce,ye,we,Le,yt,Mt,vt,Pt,Zt,$n=M(()=>{zr(),Q(),ce=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]]),ye=[],we=t=>Math.ceil(t/16)*16,Le=t=>{for(let i=0;iyt++,vt=async(t,i,s,a)=>{let u=we(s),c=t.device.createBuffer({size:u,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let d=t.getCommandEncoder();t.endComputePass(),d.copyBufferToBuffer(i,0,c,0,u),t.flush(),await c.mapAsync(GPUMapMode.READ);let m=c.getMappedRange();if(a){let g=a();return g.set(new Uint8Array(m,0,s)),g}else return new Uint8Array(m.slice(0,s))}finally{c.destroy()}},Pt=class{constructor(t){this.backend=t,this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.buffersForUploadingPending=[],this.buffersPending=[],this.externalBuffers=new Map,this.capturedPendingBuffers=new Map;for(let[i]of ce)ye.push(i),this.freeBuffers.set(i,[]),this.freeUniformBuffers.set(i,[])}upload(t,i){let s=i.buffer,a=i.byteOffset,u=i.byteLength,c=we(u),d=this.storageCache.get(t);if(!d)throw new Error("gpu data for uploading does not exist");if(d.originalSize!==u)throw new Error(`inconsistent data size. gpu data size=${d.originalSize}, data size=${u}`);let m=this.backend.device.createBuffer({mappedAtCreation:!0,size:c,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),g=m.getMappedRange();new Uint8Array(g).set(new Uint8Array(s,a,u)),m.unmap();let y=this.backend.getCommandEncoder();this.backend.endComputePass(),y.copyBufferToBuffer(m,0,d.gpuData.buffer,0,c),Rn("verbose",()=>`[WebGPU] GpuDataManager.upload(id=${t})`),this.buffersForUploadingPending.push(m)}memcpy(t,i){let s=this.storageCache.get(t);if(!s)throw new Error("source gpu data for memcpy does not exist");let a=this.storageCache.get(i);if(!a)throw new Error("destination gpu data for memcpy does not exist");if(s.originalSize!==a.originalSize)throw new Error("inconsistent source and destination gpu data size");let u=we(s.originalSize),c=this.backend.getCommandEncoder();this.backend.endComputePass(),c.copyBufferToBuffer(s.gpuData.buffer,0,a.gpuData.buffer,0,u)}registerExternalBuffer(t,i,s){let a;if(s){if(a=this.externalBuffers.get(s),a===void 0)throw new Error("previous buffer is not registered");if(t===s)return Rn("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${i}) => id=${a}, buffer is the same, skip.`),a;if(this.backend.capturedCommandList.has(this.backend.currentSessionId))throw new Error(`Registering a different external buffer under graph capture mode is not supported yet. + Please use the previous external buffer!`);this.externalBuffers.delete(s)}else a=Mt();return this.storageCache.set(a,{gpuData:{id:a,type:0,buffer:t},originalSize:i}),this.externalBuffers.set(t,a),Rn("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${i}) => id=${a}, registered.`),a}unregisterExternalBuffer(t){let i=this.externalBuffers.get(t);i!==void 0&&(this.storageCache.delete(i),this.externalBuffers.delete(t),Rn("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${i}`))}create(t,i=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let s=Le(t),a,u=(i&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,c=(i&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(u||c){let m=(u?this.freeBuffers:this.freeUniformBuffers).get(s);m?m.length>0?a=m.pop():a=this.backend.device.createBuffer({size:s,usage:i}):a=this.backend.device.createBuffer({size:s,usage:i})}else a=this.backend.device.createBuffer({size:s,usage:i});let d={id:Mt(),type:0,buffer:a};return this.storageCache.set(d.id,{gpuData:d,originalSize:t}),Rn("verbose",()=>`[WebGPU] GpuDataManager.create(size=${t}) => id=${d.id}`),d}get(t){var i;return(i=this.storageCache.get(t))==null?void 0:i.gpuData}release(t){let i=this.storageCache.get(t);if(!i)throw new Error("releasing data does not exist");return Rn("verbose",()=>`[WebGPU] GpuDataManager.release(id=${t}), gpuDataId=${i.gpuData.id}`),this.storageCache.delete(t),this.buffersPending.push(i.gpuData.buffer),i.originalSize}async download(t,i){let s=this.storageCache.get(t);if(!s)throw new Error("data does not exist");await vt(this.backend,s.gpuData.buffer,s.originalSize,i)}refreshPendingBuffers(){for(let t of this.buffersForUploadingPending)t.destroy();if(this.buffersForUploadingPending=[],this.buffersPending.length!==0)if(this.backend.sessionStatus==="default"){for(let t of this.buffersPending){let i=ce.get(t.size);if((t.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE){let s=this.freeBuffers.get(t.size)||[];i===void 0||s.length>=i?t.destroy():s.push(t)}else if((t.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM){let s=this.freeUniformBuffers.get(t.size)||[];i===void 0||s.length>=i?t.destroy():s.push(t)}else t.destroy()}this.buffersPending=[]}else{let t=this.capturedPendingBuffers.get(this.backend.currentSessionId);t||(t=[],this.capturedPendingBuffers.set(this.backend.currentSessionId,t));for(let i of this.buffersPending)t.push(i);this.buffersPending=[]}}dispose(){this.freeBuffers.forEach(t=>{t.forEach(i=>{i.destroy()})}),this.freeUniformBuffers.forEach(t=>{t.forEach(i=>{i.destroy()})}),this.storageCache.forEach(t=>{t.gpuData.buffer.destroy()}),this.capturedPendingBuffers.forEach(t=>{t.forEach(i=>{i.destroy()})}),this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.capturedPendingBuffers=new Map}onReleaseSession(t){let i=this.capturedPendingBuffers.get(t);i&&(i.forEach(s=>{s.destroy()}),this.capturedPendingBuffers.delete(t))}},Zt=(...t)=>new Pt(...t)}),nn,Gt,mn=M(()=>{nn=class{constructor(t){Object.assign(this,t)}get cacheKey(){return this.key||(this.key=Object.getOwnPropertyNames(this).sort().map(t=>`${this[t]}`).join(";")),this.key}},Gt=t=>new nn(t)}),Mr,ur,Ve,Vr,bn,rr,kr,Yt=M(()=>{Mr=class{static calcMatMulShape(t,i){return t[1]!==i[0]?void 0:[t[0],i[1]]}},ur=class{static calcShape(t,i,s=!1){let a=t.length,u=i.length;if(a===0)return i;if(u===0)return t;let c=Math.max(t.length,i.length),d=new Array(c);if(s){if(a<2||u<2)return;let m=Mr.calcMatMulShape([t[a-2],t[a-1]],[i[u-2],i[u-1]]);if(m===void 0)return;[d[c-2],d[c-1]]=m}for(let m=s?3:1;m<=c;m++){let g=a-m<0?1:t[a-m],y=u-m<0?1:i[u-m];if(g!==y&&g>1&&y>1)return;let E=Math.max(g,y);if(g&&y)d[c-m]=Math.max(g,y);else{if(E>1)return;d[c-m]=0}}return d}static isValidBroadcast(t,i){let s=t.length,a=i.length;if(s>a)return!1;for(let u=1;u<=s;u++)if(t[s-u]!==1&&t[s-u]!==i[a-u])return!1;return!0}},Ve=class dh{static size(i){return dh.getSizeFromDimensionRange(i,0,i.length)}static convertShape(i,s=4){let a=i.length;if(a===0)return[];let u=new Array(a),c=a-1;for(;c>=0;){if(i[c]%s===0){u[c]=i[c]/s;break}if(s%i[c]!==0)throw new Error("cannot convert shape");u[c]=1,s/=i[c],c--}for(c--;c>=0;c--)u[c]=i[c];return u}static sizeFromDimension(i,s){if(s<0||s>i.length)throw new Error(`invalid dimension of ${s} for sizeFromDimension as Tensor has ${i.length} dimensions.`);return dh.getSizeFromDimensionRange(i,s,i.length)}static sizeToDimension(i,s){if(s<0||s>i.length)throw new Error(`invalid dimension of ${s} for sizeToDimension as Tensor has ${i.length} dimensions.`);return dh.getSizeFromDimensionRange(i,0,s)}static getSizeFromDimensionRange(i,s,a){let u=1;for(let c=s;c=0;--u)a[u]=a[u+1]*i[u+1];return a}static normalizeAxis(i,s){if(i<-s&&i>=s)throw new Error("unsupported axis for this operation.");return i<0?i+s:i}static normalizeAxes(i,s){return i.map(a=>this.normalizeAxis(a,s??i.length))}static sortBasedOnPerm(i,s){return s?s.map(a=>i[a]):i.slice().reverse()}static padShape(i,s){let a=i.length;return i.map((u,c)=>u+s[c]+s[c+a])}static areEqual(i,s){return i.length!==s.length?!1:i.every((a,u)=>a===s[u])}},Vr=class cp{static adjustPoolAttributes(i,s,a,u,c,d){if(!i&&a.length!==s.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(i)for(let m=0;m=a.length?a.push(s[m+2]):a[m]=s[m+2];for(let m=0;m=a[m]||d[m+a.length]>=a[m])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(i,s,a,u,c,d,m){if(m){if(c.length!==2*(i.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(s.length!==i.length-2)throw new Error("length of strides should be the length of data dimensions");if(u.length!==i.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let g=0;g{Xt(),Yt(),Or=64,pr=(t,i)=>{if(i===3)throw new Error("vec3 has same alignment as vec4, use vec4 instead");switch(t){case 10:return i>1?`vec${i}`:"f16";case 1:return i>1?`vec${i}`:"f32";case 6:return i>1?`vec${i}`:"i32";case 12:return i>1?`vec${i}`:"u32";case 7:if(i>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","i32"];case 13:if(i>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","u32"];case 9:if(i!==4)throw new Error("bool must be vec4");return["u32","vec4"];default:throw new Error(`Unknown data type: ${t}`)}},Tn=(t,i=1)=>{let s=pr(t,i);return typeof s=="string"?s:s[0]},Sn=(t,i=1)=>{let s=pr(t,i);return typeof s=="string"?s:s[1]},Et=(...t)=>{let i=[];return t.forEach(s=>{s.length!==0&&i.push({type:12,data:s},{type:12,data:Ve.computeStrides(s)})}),i},wn=t=>t%4===0?4:t%2===0?2:1,zn=(t="f32",i,s="0")=>!i||i===1?`${t}(${s})`:`vec${i}<${t}>(${s})`,Un=(t,i,s)=>t==="f32"?s:i===1?`f32(${s})`:`vec${i}(${s})`,Dr=(t,i)=>i===4?`(${t}.x + ${t}.y + ${t}.z + ${t}.w)`:i===2?`(${t}.x + ${t}.y)`:i===3?`(${t}.x + ${t}.y + ${t}.z)`:t,Ot=(t,i,s,a)=>t.startsWith("uniforms.")&&s>4?typeof i=="string"?a==="f16"?`${t}[(${i}) / 8][(${i}) % 8 / 4][(${i}) % 8 % 4]`:`${t}[(${i}) / 4][(${i}) % 4]`:a==="f16"?`${t}[${Math.floor(i/8)}][${Math.floor(i%8/4)}][${i%8%4}]`:`${t}[${Math.floor(i/4)}][${i%4}]`:s>1?`${t}[${i}]`:t,bs=(t,i,s,a,u)=>{let c=typeof s=="number",d=c?s:s.length,m=[...new Array(d).keys()],g=d<2?"u32":d<=4?`vec${d}`:`array`,y=pr(i,u),E=typeof y=="string"?y:y[1],$=typeof y=="string"?y:y[0],h={indices:g,value:E,storage:$,tensor:i},R=Ze=>typeof Ze=="string"?Ze:`${Ze}u`,B={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},K=c?"uniforms.":"",re=`${K}${t}_shape`,oe=`${K}${t}_strides`,ee="";for(let Ze=0;Ze ${h.indices} { + var indices: ${h.indices}; + var current = offset; + ${ee} + return indices; + }`,ae=Ze=>(B.offsetToIndices=!0,d<2?Ze:`o2i_${t}(${Ze})`),ge=[];if(d>=2)for(let Ze=d-1;Ze>=0;Ze--)ge.push(`${Ot(oe,Ze,d)} * (indices[${Ze}])`);let Qe=d<2?"":` + fn i2o_${t}(indices: ${h.indices}) -> u32 { + return ${ge.join("+")}; + }`,ze=Ze=>(B.indicesToOffset=!0,d<2?Ze:`i2o_${t}(${Ze})`),ht=(...Ze)=>d===0?"0u":`${h.indices}(${Ze.map(R).join(",")})`,Ft=(Ze,zt)=>d<2?`${Ze}`:`${Ot(Ze,zt,d)}`,Dt=(Ze,zt,on)=>d<2?`${Ze}=${on};`:`${Ot(Ze,zt,d)}=${on};`,hn={},ln=(Ze,zt)=>{B.broadcastedIndicesToOffset=!0;let on=`${zt.name}broadcastedIndicesTo${t}Offset`;if(on in hn)return`${on}(${Ze})`;let Gn=[];for(let or=d-1;or>=0;or--){let yr=zt.indicesGet("outputIndices",or+zt.rank-d);Gn.push(`${Ft(oe,or)} * (${yr} % ${Ft(re,or)})`)}return hn[on]=`fn ${on}(outputIndices: ${zt.type.indices}) -> u32 { + return ${Gn.length>0?Gn.join("+"):"0u"}; + }`,`${on}(${Ze})`},rn=(Ze,zt)=>(()=>{if(h.storage===h.value)return`${t}[${Ze}]=${zt};`;if(h.storage==="vec2"&&h.value==="i32")return`${t}[${Ze}]=vec2(u32(${zt}), select(0u, 0xFFFFFFFFu, ${zt} < 0));`;if(h.storage==="vec2"&&h.value==="u32")return`${t}[${Ze}]=vec2(u32(${zt}), 0u);`;if(h.storage==="u32"&&h.value==="vec4")return`${t}[${Ze}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${zt}));`;throw new Error(`not supported combination of storage type ${h.storage} and value type ${h.value} yet`)})(),yn=Ze=>(()=>{if(h.storage===h.value)return`${t}[${Ze}]`;if(h.storage==="vec2"&&h.value==="i32")return`i32(${t}[${Ze}].x)`;if(h.storage==="vec2"&&h.value==="u32")return`u32(${t}[${Ze}].x)`;if(h.storage==="u32"&&h.value==="vec4")return`vec4(bool(${t}[${Ze}] & 0xFFu), bool(${t}[${Ze}] & 0xFF00u), bool(${t}[${Ze}] & 0xFF0000u), bool(${t}[${Ze}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${h.storage} and value type ${h.value} yet`)})(),Wn=d<2?"":` + fn get_${t}ByIndices(indices: ${h.indices}) -> ${E} { + return ${yn(`i2o_${t}(indices)`)}; + }`,kn=d<2?"":(()=>{let Ze=m.map(on=>`d${on}: u32`).join(", "),zt=m.map(on=>`d${on}`).join(", ");return` + fn get_${t}(${Ze}) -> ${E} { + return get_${t}ByIndices(${ht(zt)}); + }`})(),jn=(...Ze)=>{if(Ze.length!==d)throw new Error(`indices length must be ${d}`);let zt=Ze.map(R).join(",");return d===0?yn("0u"):d===1?yn(zt[0]):(B.get=!0,B.getByIndices=!0,B.indicesToOffset=!0,`get_${t}(${zt})`)},It=Ze=>d<2?yn(Ze):(B.getByIndices=!0,B.indicesToOffset=!0,`get_${t}ByIndices(${Ze})`),tn=d<2?"":` + fn set_${t}ByIndices(indices: ${h.indices}, value: ${E}) { + ${rn(`i2o_${t}(indices)`,"value")} + }`,en=d<2?"":(()=>{let Ze=m.map(on=>`d${on}: u32`).join(", "),zt=m.map(on=>`d${on}`).join(", ");return` + fn set_${t}(${Ze}, value: ${E}) { + set_${t}ByIndices(${ht(zt)}, value); + }`})();return{impl:()=>{let Ze=[],zt=!1;return B.offsetToIndices&&(Ze.push(_e),zt=!0),B.indicesToOffset&&(Ze.push(Qe),zt=!0),B.broadcastedIndicesToOffset&&(Object.values(hn).forEach(on=>Ze.push(on)),zt=!0),B.set&&(Ze.push(en),zt=!0),B.setByIndices&&(Ze.push(tn),zt=!0),B.get&&(Ze.push(kn),zt=!0),B.getByIndices&&(Ze.push(Wn),zt=!0),!c&&zt&&Ze.unshift(`const ${re} = ${h.indices}(${s.join(",")});`,`const ${oe} = ${h.indices}(${Ve.computeStrides(s).join(",")});`),Ze.join(` +`)},type:h,offsetToIndices:ae,indicesToOffset:ze,broadcastedIndicesToOffset:ln,indices:ht,indicesGet:Ft,indicesSet:Dt,set:(...Ze)=>{if(Ze.length!==d+1)throw new Error(`indices length must be ${d}`);let zt=Ze[d];if(typeof zt!="string")throw new Error("value must be string");let on=Ze.slice(0,d).map(R).join(",");return d===0?rn("0u",zt):d===1?rn(on[0],zt):(B.set=!0,B.setByIndices=!0,B.indicesToOffset=!0,`set_${t}(${on}, ${zt})`)},setByOffset:rn,setByIndices:(Ze,zt)=>d<2?rn(Ze,zt):(B.setByIndices=!0,B.indicesToOffset=!0,`set_${t}ByIndices(${Ze}, ${zt});`),get:jn,getByOffset:yn,getByIndices:It,usage:a,name:t,strides:oe,shape:re,rank:d}},it=(t,i,s,a=1)=>bs(t,i,s,"input",a),Ut=(t,i,s,a=1)=>bs(t,i,s,"output",a),oa=(t,i,s,a=1)=>bs(t,i,s,"internal",a),sa=class{constructor(t,i){this.normalizedDispatchGroup=t,this.limits=i,this.internalVariables=[],this.variables=[],this.uniforms=[],this.variableIndex=0}guardAgainstOutOfBoundsWorkgroupSizes(t){return`if (global_idx >= ${typeof t=="number"?`${t}u`:t}) { return; }`}mainStart(t=Or){let i=typeof t=="number"?t:t[0],s=typeof t=="number"?1:t[1],a=typeof t=="number"?1:t[2];if(i>this.limits.maxComputeWorkgroupSizeX||s>this.limits.maxComputeWorkgroupSizeY||a>this.limits.maxComputeWorkgroupSizeZ)throw new Error(`workgroup size [${i}, ${s}, ${a}] exceeds the maximum workgroup size [${this.limits.maxComputeWorkgroupSizeX}, ${this.limits.maxComputeWorkgroupSizeY}, ${this.limits.maxComputeWorkgroupSizeZ}].`);if(i*s*a>this.limits.maxComputeInvocationsPerWorkgroup)throw new Error(`workgroup size [${i}, ${s}, ${a}] exceeds the maximum workgroup invocations ${this.limits.maxComputeInvocationsPerWorkgroup}.`);let u=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1,c=u?`@builtin(global_invocation_id) global_id : vec3, + @builtin(workgroup_id) workgroup_id : vec3, + @builtin(local_invocation_id) local_id : vec3`:`@builtin(global_invocation_id) global_id : vec3, + @builtin(local_invocation_id) local_id : vec3, + @builtin(local_invocation_index) local_idx : u32, + @builtin(workgroup_id) workgroup_id : vec3, + @builtin(num_workgroups) num_workgroups : vec3`,d=u?"let global_idx = global_id.x; let local_idx = local_id.x;":`let global_idx = (workgroup_id.z * num_workgroups[0] * num_workgroups[1] + + workgroup_id.y * num_workgroups[0] + workgroup_id.x) * ${i*s*a}u + local_idx;`;return`@compute @workgroup_size(${i}, ${s}, ${a}) + fn main(${c}) { + ${d} + `}appendVariableUniforms(t){t.rank!==0&&(t.shape.startsWith("uniforms.")&&this.uniforms.push({name:t.shape.replace("uniforms.",""),type:"u32",length:t.rank}),t.strides.startsWith("uniforms.")&&this.uniforms.push({name:t.strides.replace("uniforms.",""),type:"u32",length:t.rank}))}declareVariable(t,i){if(t.usage==="internal")throw new Error("cannot use internal variable with declareVariable(). use registerInternalVariables() instead.");this.variables.push(t),this.appendVariableUniforms(t);let s=t.usage==="input"?"read":"read_write",a=t.type.storage;return`@group(0) @binding(${i}) var ${t.name}: array<${a}>;`}declareVariables(...t){return t.map(i=>this.declareVariable(i,this.variableIndex++)).join(` +`)}registerInternalVariable(t){if(t.usage!=="internal")throw new Error("cannot use input or output variable with registerInternalVariable(). use declareVariables() instead.");this.internalVariables.push(t),this.appendVariableUniforms(t)}registerInternalVariables(...t){return t.forEach(i=>this.registerInternalVariable(i)),this}registerUniform(t,i,s=1){return this.uniforms.push({name:t,type:i,length:s}),this}registerUniforms(t){return this.uniforms=this.uniforms.concat(t),this}uniformDeclaration(){if(this.uniforms.length===0)return"";let t=[];for(let{name:i,type:s,length:a}of this.uniforms)if(a&&a>4)s==="f16"?t.push(`@align(16) ${i}:array, ${Math.ceil(a/8)}>`):t.push(`${i}:array, ${Math.ceil(a/4)}>`);else{let u=a==null||a===1?s:`vec${a}<${s}>`;t.push(`${i}:${u}`)}return` + struct Uniforms { ${t.join(", ")} }; + @group(0) @binding(${this.variableIndex}) var uniforms: Uniforms;`}get additionalImplementations(){return this.uniformDeclaration()+this.variables.map(t=>t.impl()).join(` +`)+this.internalVariables.map(t=>t.impl()).join(` +`)}get variablesInfo(){if(this.uniforms.length===0)return;let t=i=>[12,10,1,6][["u32","f16","f32","i32"].indexOf(i)];return this.uniforms.map(i=>[t(i.type),i.length??1])}},Zl=(t,i)=>new sa(t,i),po=(t,i)=>{let s=t.length,a=[];for(let u=0;u1&&d===1&&a.unshift(c)}return a}}),Jl,aa,Ro,eu,li,tu,la,fo=M(()=>{Xt(),Yt(),mn(),sn(),Jl=t=>{if(!t||t.length!==1)throw new Error("Transpose requires 1 input.")},aa=(t,i)=>i&&i.length!==t?[...new Array(t).keys()].reverse():i,Ro=(t,i)=>Ve.sortBasedOnPerm(t,aa(t.length,i)),eu=(t,i,s,a)=>{let u=[];u.push(`fn perm(i: ${a.type.indices}) -> ${s.type.indices} { + var a: ${s.type.indices};`);for(let c=0;c{let s=t.dataType,a=t.dims.length,u=aa(a,i),c=Ro(t.dims,u),d=Ut("output",s,c.length),m=it("a",s,a),g;if(u.length===2&&u[0]===1&&u[1]===0){let y=d.type.value,E=[16,16,1];g=$=>` + ${$.registerUniform("output_size","u32").declareVariables(m,d)} + var tile : array, ${E[0]}>; + ${$.mainStart(E)} + var x = workgroup_id.x * ${E[0]}u + local_id.x; + var y = workgroup_id.y * ${E[0]}u + local_id.y; + let width = uniforms.output_shape[0]; + let height = uniforms.output_shape[1]; + if (x < width && y < height) { + tile[local_id.y][local_id.x] = ${m.getByOffset("y * width + x")}; + } + workgroupBarrier(); + x = workgroup_id.y * ${E[0]}u + local_id.x; + y = workgroup_id.x * ${E[0]}u + local_id.y; + if (x < height && y < width) { + ${d.setByOffset("y * height + x","tile[local_id.x][local_id.y]")} + } + }`}else g=y=>` + ${y.registerUniform("output_size","u32").declareVariables(m,d)} + + ${eu(u,a,m,d)} + + ${y.mainStart()} + ${y.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${d.offsetToIndices("global_idx")}; + let aIndices = perm(indices); + + ${d.setByOffset("global_idx",m.getByIndices("aIndices"))} + }`;return{name:"Transpose",shaderCache:{hint:`${i}`,inputDependencies:["rank"]},getRunData:y=>{let E=Ve.size(c);return{outputs:[{dims:c,dataType:y[0].dataType}],dispatchGroup:{x:Math.ceil(E/64)},programUniforms:[{type:12,data:E},...Et(y[0].dims,c)]}},getShaderSource:g}},tu=(t,i)=>{Jl(t.inputs),t.compute(li(t.inputs[0],i.perm))},la=t=>Gt({perm:t.perm})}),nu,ru,iu,ou,ua,su,au,da,lu,uu,Ur,du,cu,ca,pu,fu,pa,hu,mu,fa,gu,Up=M(()=>{Xt(),Yt(),sn(),va(),fo(),nu={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"},ru={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"},iu={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},ou={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},ua=(t,i)=>{let s=[];for(let a=i-t;a{let s=[],a=t.length;for(let c=0;ct[c]);return[s,u]},au=(t,i)=>{let s=t.length+i.length,a=[],u=0;for(let c=0;c{for(let s=0;s{let s=[];if(!da(t,i)){for(let a=0;as.push(a))}return s},uu=(t,i,s,a,u,c,d)=>{let m=s[0].dims,g=Ve.size(c),y=Ve.size(d),E=it("_A",s[0].dataType,m),$=Ut("output",u,c),h=32,R=` + var aBestValues : array; + `;return{name:t,shaderCache:i,getShaderSource:B=>` + ${B.registerUniform("reduceSize","u32").declareVariables(E,$)} + ${R} + fn DIV_CEIL(a : u32, b : u32) -> u32 { + return ((a - 1u) / b + 1u); + } + ${B.mainStart(h)} + + let outputIndex = global_idx / ${h}; + let offset = outputIndex * uniforms.reduceSize; + + var bestValue = f32(${iu[a]}); + let Length = uniforms.reduceSize; + for (var k = local_idx; k < Length; k = k + ${h}) { + let candidate = f32(${E.getByOffset("offset + k")}); + bestValue = ${nu[a]}; + } + 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 = ${ru[a]}; + aBestValues[local_idx] = bestValue; + } + reduceSize = interval; + workgroupBarrier(); + } + + if (local_idx == 0u) { + ${$.setByOffset("outputIndex",`${a==="mean"?`${$.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${$.type.storage}(${ou[a]})`}`)}; + } + }`,getRunData:()=>({outputs:[{dims:c,dataType:u}],dispatchGroup:{x:g},programUniforms:[{type:12,data:y}]})}},Ur=(t,i,s,a)=>{let u=t.inputs.length===1?s:Ts(t.inputs,s),c=u.axes;c.length===0&&!u.noopWithEmptyAxes&&(c=t.inputs[0].dims.map((R,B)=>B));let d=Ve.normalizeAxes(c,t.inputs[0].dims.length),m=d,g=t.inputs[0],y=lu(m,t.inputs[0].dims.length);y.length>0&&(g=t.compute(li(t.inputs[0],y),{inputs:[0],outputs:[-1]})[0],m=ua(m.length,g.dims.length));let[E,$]=su(g.dims,m),h=E;u.keepDims&&(h=au(E,d)),t.compute(uu(i,{hint:u.cacheKey,inputDependencies:["type"]},[g],a,t.inputs[0].dataType,h,$),{inputs:[g]})},du=(t,i)=>{Ur(t,"ReduceMeanShared",i,"mean")},cu=(t,i)=>{Ur(t,"ReduceL1Shared",i,"l1")},ca=(t,i)=>{Ur(t,"ReduceL2Shared",i,"l2")},pu=(t,i)=>{Ur(t,"ReduceLogSumExpShared",i,"logSumExp")},fu=(t,i)=>{Ur(t,"ReduceMaxShared",i,"max")},pa=(t,i)=>{Ur(t,"ReduceMinShared",i,"min")},hu=(t,i)=>{Ur(t,"ReduceProdShared",i,"prod")},mu=(t,i)=>{Ur(t,"ReduceSumShared",i,"sum")},fa=(t,i)=>{Ur(t,"ReduceSumSquareShared",i,"sumSquare")},gu=(t,i)=>{Ur(t,"ReduceLogSumShared",i,"logSum")}}),Wr,_u,xs,Ts,Jr,yu,ha,wu,vu,ma,Mu,bu,ga,xu,Tu,Gr,Su,ku,_a,Eu,Cu,ya,$u,Pu,wa,Au,va=M(()=>{Xt(),Yt(),mn(),sn(),Up(),Wr=t=>{if(!t||t.length===0||t.length>2)throw new Error("Reduce op requires 1 or 2 inputs.");if(t.length===2&&t[1].dims.length!==1)throw new Error("Invalid axes input dims.")},_u=t=>["","",`var value = ${t.getByIndices("input_indices")};`,""],xs=(t,i,s,a,u,c,d=!1,m=!1)=>{let g=[],y=s[0].dims,E=y.length,$=Ve.normalizeAxes(u,E),h=!m&&$.length===0;y.forEach((K,re)=>{h||$.indexOf(re)>=0?d&&g.push(1):g.push(K)});let R=g.length,B=Ve.size(g);return{name:t,shaderCache:i,getShaderSource:K=>{let re=[],oe=it("_A",s[0].dataType,E),ee=Ut("output",c,R),_e=a(oe,ee,$),ae=_e[2];for(let ge=0,Qe=0;ge=0?(d&&Qe++,ae=`for(var j${ge}: u32 = 0; j${ge} < ${y[ge]}; j${ge}++) { + ${_e[2].includes("last_index")?`let last_index = j${ge};`:""} + ${oe.indicesSet("input_indices",ge,`j${ge}`)} + ${ae} + }`):(re.push(`${oe.indicesSet("input_indices",ge,ee.indicesGet("output_indices",Qe))};`),Qe++);return` + + ${K.registerUniform("output_size","u32").declareVariables(oe,ee)} + + ${K.mainStart()} + ${K.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + var input_indices: ${oe.type.indices}; + let output_indices = ${ee.offsetToIndices("global_idx")}; + + ${re.join(` +`)} + ${_e[0]} // init ops for reduce max/min + ${_e[1]} + ${ae} + ${_e[3]} + ${_e.length===4?ee.setByOffset("global_idx","value"):_e.slice(4).join(` +`)} + }`},getRunData:()=>({outputs:[{dims:g,dataType:c}],dispatchGroup:{x:Math.ceil(B/64)},programUniforms:[{type:12,data:B},...Et(y,g)]})}},Ts=(t,i)=>{let s=[];return t[1].dims[0]>0&&t[1].getBigInt64Array().forEach(a=>s.push(Number(a))),Gt({axes:s,keepDims:i.keepDims,noopWithEmptyAxes:i.noopWithEmptyAxes})},Jr=(t,i,s,a)=>{let u=t.inputs,c=u.length===1?s:Ts(u,s);t.compute(xs(i,{hint:c.cacheKey,inputDependencies:["rank"]},[u[0]],c.noopWithEmptyAxes&&c.axes.length===0?_u:a,c.axes,u[0].dataType,c.keepDims,c.noopWithEmptyAxes),{inputs:[0]})},yu=(t,i)=>{Wr(t.inputs),Jr(t,"ReduceLogSum",i,(s,a)=>[`var value = ${a.type.storage}(0);`,"",`value += ${s.getByIndices("input_indices")};`,"value = log(value);"])},ha=(t,i)=>{Wr(t.inputs),Jr(t,"ReduceL1",i,(s,a)=>[`var value = ${a.type.storage}(0);`,"",`value += abs(${s.getByIndices("input_indices")});`,""])},wu=(t,i)=>{Wr(t.inputs),Jr(t,"ReduceL2",i,(s,a)=>[`var t = ${a.type.value}(0); var value = ${a.type.value}(0);`,"",`t = ${s.getByIndices("input_indices")}; value += (t * t);`,"value = sqrt(value);"])},vu=(t,i)=>{Wr(t.inputs),Jr(t,"ReduceLogSumExp",i,(s,a)=>[`var value = ${a.type.storage}(0);`,"",`value += exp(${s.getByIndices("input_indices")});`,"value = log(value);"])},ma=(t,i)=>{Wr(t.inputs),Jr(t,"ReduceMax",i,(s,a,u)=>{let c=[];for(let d=0;d=0||u.length===0)&&c.push(s.indicesSet("input_indices",d,0));return[`${c.join(` +`)}`,`var value = ${s.getByIndices("input_indices")};`,`value = max(value, ${s.getByIndices("input_indices")});`,""]})},Mu=(t,i)=>{Wr(t.inputs),Jr(t,"ReduceMean",i,(s,a,u)=>{let c=1;for(let d=0;d=0||u.length===0)&&(c*=t.inputs[0].dims[d]);return["var sum = f32(0);","",`sum += f32(${s.getByIndices("input_indices")});`,`let value = ${a.type.value}(sum / ${c});`]})},bu=(t,i)=>{Wr(t.inputs),Jr(t,"ReduceMin",i,(s,a,u)=>{let c=[];for(let d=0;d=0||u.length===0)&&c.push(`input_indices[${d}] = 0;`);return[`${c.join(` +`)}`,`var value = ${s.getByIndices("input_indices")};`,`value = min(value, ${s.getByIndices("input_indices")});`,""]})},ga=(t,i)=>{Wr(t.inputs),Jr(t,"ReduceProd",i,(s,a)=>[`var value = ${a.type.storage}(1);`,"",`value *= ${s.getByIndices("input_indices")};`,""])},xu=(t,i)=>{Wr(t.inputs),Jr(t,"ReduceSum",i,(s,a)=>[`var value = ${a.type.storage}(0);`,"",`value += ${s.getByIndices("input_indices")};`,""])},Tu=(t,i)=>{Wr(t.inputs),Jr(t,"ReduceSumSquare",i,(s,a)=>[`var t = ${a.type.value}(0); var value = ${a.type.value}(0);`,"",`t = ${s.getByIndices("input_indices")}; value += t * t;`,""])},Gr=(t,i,s)=>{if(i.length===0)return s;let a=1,u=1;for(let c=0;c1024},Su=(t,i)=>{Gr(t.inputs[0].dims,i.axes,i.noopWithEmptyAxes)?Mu(t,i):du(t,i)},ku=(t,i)=>{Gr(t.inputs[0].dims,i.axes,i.noopWithEmptyAxes)?ha(t,i):cu(t,i)},_a=(t,i)=>{Gr(t.inputs[0].dims,i.axes,i.noopWithEmptyAxes)?wu(t,i):ca(t,i)},Eu=(t,i)=>{Gr(t.inputs[0].dims,i.axes,i.noopWithEmptyAxes)?vu(t,i):pu(t,i)},Cu=(t,i)=>{Gr(t.inputs[0].dims,i.axes,i.noopWithEmptyAxes)?ma(t,i):fu(t,i)},ya=(t,i)=>{Gr(t.inputs[0].dims,i.axes,i.noopWithEmptyAxes)?bu(t,i):pa(t,i)},$u=(t,i)=>{Gr(t.inputs[0].dims,i.axes,i.noopWithEmptyAxes)?ga(t,i):hu(t,i)},Pu=(t,i)=>{Gr(t.inputs[0].dims,i.axes,i.noopWithEmptyAxes)?xu(t,i):mu(t,i)},wa=(t,i)=>{Gr(t.inputs[0].dims,i.axes,i.noopWithEmptyAxes)?Tu(t,i):fa(t,i)},Au=(t,i)=>{Gr(t.inputs[0].dims,i.axes,i.noopWithEmptyAxes)?yu(t,i):gu(t,i)}}),Ss,Iu,Fu,ks,Wp=M(()=>{Xt(),mn(),va(),Ss=t=>{if(!t||t.length===0||t.length>2)throw new Error("ArgMinMaxOp op requires 1 or 2 inputs.");if(t[0].dataType!==1)throw new Error("Invalid input type.")},Iu=(t,i)=>{Ss(t.inputs);let s=(a,u,c)=>{let d=[];for(let m=0;m=0||c.length===0)&&d.push(`input_indices[${m}] = 0;`);return[`${d.join(` +`)}`,`var value = ${a.getByIndices("input_indices")}; +var best_index : i32 = 0;`,`if (${a.getByIndices("input_indices")} ${i.selectLastIndex>0?"<=":"<"} value) { + value = ${a.getByIndices("input_indices")}; + best_index = i32(last_index); + }`,"",u.setByOffset("global_idx","best_index")]};t.compute(xs("ArgMin",{hint:i.cacheKey,inputDependencies:["rank"]},[t.inputs[0]],s,[i.axis],7,i.keepDims),{inputs:[0]})},Fu=(t,i)=>{Ss(t.inputs);let s=(a,u,c)=>{let d=[];for(let m=0;m=0||c.length===0)&&d.push(`input_indices[${m}] = 0;`);return[`${d.join(` +`)}`,`var value = ${a.getByIndices("input_indices")}; +var best_index : i32 = 0;`,`if (${a.getByIndices("input_indices")} ${i.selectLastIndex>0?">=":">"} value) { + value = ${a.getByIndices("input_indices")}; + best_index = i32(last_index); + }`,"",u.setByOffset("global_idx","best_index")]};t.compute(xs("argMax",{hint:i.cacheKey,inputDependencies:["rank"]},[t.inputs[0]],s,[i.axis],7,i.keepDims),{inputs:[0]})},ks=t=>Gt(t)}),zu,Ma,Ou,Du,ho,Lu,Bu,Es=M(()=>{Xt(),Yt(),Q(),sn(),zu=(t,i)=>{let s=t[0],a=t[1],u=t[2],c=t[3],d=t[4],m=t[5];if(d&&m)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 g=s.dims[0],y=s.dims[1],E=s.dims[2];if(u.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimensions');if(a.dims.length!==2)throw new Error('Input "weights" is expected to have 2 dimensions');if(a.dims[0]!==E)throw new Error("Input 1 dimension 0 should have same length as dimension 2 of input 0");if(u.dims[0]!==a.dims[1])throw new Error('Input "bias" dimension 0 should have same length as dimension 1 of input "weights"');let $=u.dims[0]/3,h=$,R=h;if(i.qkvHiddenSizes.length>0){if(i.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let _e of i.qkvHiddenSizes)if(_e%i.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");$=i.qkvHiddenSizes[0],h=i.qkvHiddenSizes[1],R=i.qkvHiddenSizes[2]}let B=y;if($!==h)throw new Error("qkv_hidden_sizes first element should be same as the second");if(u.dims[0]!==$+h+R)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let K=0;if(d){if(h!==R)throw new Error('Input "past" expect k_hidden_size == v_hidden_size');if(d.dims.length!==5)throw new Error('Input "past" must have 5 dimensions');if(d.dims[0]!==2)throw new Error('Input "past" first dimension must be 2');if(d.dims[1]!==g)throw new Error('Input "past" second dimension must be batch_size');if(d.dims[2]!==i.numHeads)throw new Error('Input "past" third dimension must be num_heads');if(d.dims[4]!==h/i.numHeads)throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads');i.pastPresentShareBuffer||(K=d.dims[3])}let re=B+K,oe=-1,ee=0;if(c)throw new Error("Mask not supported");if(d)throw new Error("past is not supported");if(m){if(m.dims.length!==4)throw new Error('Input "attention_bias" must have 4 dimensions');if(m.dims[0]!==g||m.dims[1]!==i.numHeads||m.dims[2]!==y||m.dims[3]!==re)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:g,sequenceLength:y,pastSequenceLength:K,kvSequenceLength:B,totalSequenceLength:re,maxSequenceLength:oe,inputHiddenSize:E,hiddenSize:$,vHiddenSize:R,headSize:Math.floor($/i.numHeads),vHeadSize:Math.floor(R/i.numHeads),numHeads:i.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:i.maskFilterValue,maskType:ee,scale:i.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},Ma=(t,i,s)=>{let a=wn(s),u=64,c=s/a;c{let R=Ut("x",t.dataType,t.dims,a),B=Sn(t.dataType),K=[{name:"d_inv",type:"f32"},{name:"d_comp",type:"u32"},{name:"elements_per_thread",type:"u32"}];return` + var thread_max: array; + var thread_sum: array; + ${h.registerUniforms(K).declareVariables(R)} + ${h.mainStart([u,1,1])} + let local_offset = local_idx * uniforms.elements_per_thread; + let offset = (global_idx / ${u}) * uniforms.d_comp + local_offset; + + var thread_max_vector = ${y}(-3.402823e+38f); + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { + thread_max_vector = max(${y}(x[offset + i]), thread_max_vector); + } + thread_max[local_idx] = ${(()=>{switch(a){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: ${a}`)}})()}; + 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 = ${y}(0); + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { + sum_vector += exp(${y}(x[offset + i]) - max_value); + } + thread_sum[local_idx] = ${(()=>{switch(a){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: ${a}`)}})()}; + 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 < uniforms.d_comp; i++) { + x[offset + i] = ${R.type.value}(${B}(uniforms.d_inv)); + } + } else { + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { + var f32input = ${y}(x[offset + i]); + x[offset + i] = ${R.type.value}(exp(f32input - max_value) / sum); + } + } + }`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${u};${g};${a}`,inputDependencies:E},getShaderSource:$,getRunData:()=>({outputs:[],dispatchGroup:{x:i},programUniforms:m})}},Ou=(t,i,s,a,u,c,d,m)=>{let g=m+c.kvSequenceLength,y=[c.batchSize,c.numHeads,c.sequenceLength,g],E=c.kvNumHeads===void 0&&t>1&&a,$=E?[c.batchSize,c.numHeads,g,c.headSize]:void 0,h=d.scale===0?1/Math.sqrt(c.headSize):d.scale,R=wn(c.headSize),B=c.headSize/R,K=12,re={x:Math.ceil(g/K),y:Math.ceil(c.sequenceLength/K),z:c.batchSize*c.numHeads},oe=[{type:12,data:c.sequenceLength},{type:12,data:B},{type:12,data:g},{type:12,data:c.numHeads},{type:1,data:h},{type:12,data:m},{type:12,data:c.kvSequenceLength}],ee=E&&a&&Ve.size(a.dims)>0,_e=["type","type"];ee&&_e.push("type"),u&&_e.push("type");let ae=[{dims:y,dataType:i.dataType,gpuDataType:0}];E&&ae.push({dims:$,dataType:i.dataType,gpuDataType:0});let ge=Qe=>{let ze=it("q",i.dataType,i.dims,R),ht=it("key",s.dataType,s.dims,R),Ft=[ze,ht];if(ee){let yn=it("past_key",a.dataType,a.dims,R);Ft.push(yn)}u&&Ft.push(it("attention_bias",u.dataType,u.dims));let Dt=Ut("output",i.dataType,y),hn=[Dt];E&&hn.push(Ut("present_key",i.dataType,$,R));let ln=Sn(1,R),rn=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"alpha",type:"f32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"}];return` + const TILE_SIZE = ${K}u; + + var tileQ: array<${ze.type.storage}, ${K*K}>; + var tileK: array<${ze.type.storage}, ${K*K}>; + ${Qe.registerUniforms(rn).declareVariables(...Ft,...hn)} + ${Qe.mainStart([K,K,1])} + // x holds the N and y holds the M + let headIdx = workgroup_id.z; + let m = workgroup_id.y * TILE_SIZE; + let n = workgroup_id.x * TILE_SIZE; + let qOffset = uniforms.M * uniforms.K * headIdx + m * uniforms.K; + ${ee&&E?` + let kOffset = uniforms.kv_sequence_length * uniforms.K * headIdx; + let pastKeyOffset = uniforms.past_sequence_length * uniforms.K * headIdx;`:` + let kOffset = uniforms.N * uniforms.K * headIdx + n * uniforms.K;`} + ${E?"let presentKeyOffset = headIdx * uniforms.N * uniforms.K;":""} + var value = ${ln}(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; + ${ee&&E?` + if (n + local_id.y < uniforms.past_sequence_length) { + tileK[idx] = past_key[pastKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x]; + } else { + tileK[idx] = + key[kOffset + (n + local_id.y - uniforms.past_sequence_length) * uniforms.K + w + local_id.x]; + }`:"tileK[idx] = key[kOffset + local_id.y * uniforms.K + w + local_id.x];"} + ${E?"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 += ${ln}(tileQ[TILE_SIZE * local_id.y + k] * tileK[TILE_SIZE * local_id.x + k]); + } + + workgroupBarrier(); + } + + let headOffset = headIdx * uniforms.M * uniforms.N; + if (global_id.y < uniforms.M && global_id.x < uniforms.N) { + let outputIdx = headOffset + global_id.y * uniforms.N + global_id.x; + var sum: f32 = ${(()=>{switch(R){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: ${R}`)}})()}; + output[outputIdx] = ${Dt.type.value} (sum * uniforms.alpha) + ${u?"attention_bias[outputIdx]":"0.0"}; + } + }`};return{name:"AttentionProbs",shaderCache:{hint:`${R};${u!==void 0};${a!==void 0};${t}`,inputDependencies:_e},getRunData:()=>({outputs:ae,dispatchGroup:re,programUniforms:oe}),getShaderSource:ge}},Du=(t,i,s,a,u,c)=>{let d=c+u.kvSequenceLength,m=u.nReps?u.nReps:1,g=u.vHiddenSize*m,y=u.kvNumHeads==null&&t>1&&a,E=y?[u.batchSize,u.numHeads,d,u.headSize]:void 0,$=[u.batchSize,u.sequenceLength,g],h=12,R={x:Math.ceil(u.vHeadSize/h),y:Math.ceil(u.sequenceLength/h),z:u.batchSize*u.numHeads},B=[{type:12,data:u.sequenceLength},{type:12,data:d},{type:12,data:u.vHeadSize},{type:12,data:u.numHeads},{type:12,data:g},{type:12,data:c},{type:12,data:u.kvSequenceLength}],K=y&&a&&Ve.size(a.dims)>0,re=["type","type"];K&&re.push("type");let oe=[{dims:$,dataType:i.dataType,gpuDataType:0}];y&&oe.push({dims:E,dataType:i.dataType,gpuDataType:0});let ee=_e=>{let ae=it("probs",i.dataType,i.dims),ge=it("v",s.dataType,s.dims),Qe=[ae,ge];K&&Qe.push(it("past_value",a.dataType,a.dims));let ze=[Ut("output",i.dataType,$)];y&&ze.push(Ut("present_value",i.dataType,E));let ht=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"v_hidden_size",type:"u32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"}];return` + const TILE_SIZE = ${h}u; + var tileQ: array<${ae.type.value}, ${h*h}>; + var tileK: array<${ae.type.value}, ${h*h}>; + ${_e.registerUniforms(ht).declareVariables(...Qe,...ze)} + ${_e.mainStart([h,h,1])} + let headIdx = workgroup_id.z; + let m = global_id.y; + let n = global_id.x; + + let offsetA = headIdx * (uniforms.M * uniforms.K) + m * uniforms.K; + ${K&&y?` + let pastValueOffset = headIdx * uniforms.N * uniforms.past_sequence_length + n; + let vOffset = headIdx * uniforms.N * uniforms.kv_sequence_length + n; + `:` + let offsetB = headIdx * uniforms.N * uniforms.K + n; + `} + ${y?"let presentValueOffset = headIdx * uniforms.N * uniforms.K + n;":""} + var value = ${ae.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; + ${K&&y?` + if (w + local_id.y < uniforms.past_sequence_length) { + tileK[idx] = past_value[pastValueOffset + (w + local_id.y) * uniforms.N]; + } else { + tileK[idx] = v[vOffset + (w + local_id.y - uniforms.past_sequence_length) * uniforms.N]; + } + `:` + tileK[idx] = v[offsetB + (w + local_id.y) * uniforms.N]; + `} + ${y?"present_value[presentValueOffset + (w + local_id.y) * uniforms.N] = tileK[idx];":""} + } + workgroupBarrier(); + for (var k: u32 = 0u; k < TILE_SIZE && w+k < uniforms.K; k++) { + value += tileQ[TILE_SIZE * local_id.y + k] * tileK[TILE_SIZE * k + local_id.x]; + } + workgroupBarrier(); + } + + // we need to transpose output from BNSH_v to BSND_v + let batchIdx = workgroup_id.z / uniforms.num_heads; + let currentBatchHeadNumber = workgroup_id.z % uniforms.num_heads; + if (m < uniforms.M && n < uniforms.N) { + let outputIdx = batchIdx * uniforms.M * uniforms.v_hidden_size + m * uniforms.v_hidden_size + + currentBatchHeadNumber * uniforms.N + n; + output[outputIdx] = value; + } + }`};return{name:"AttentionScore",shaderCache:{hint:`${a!==void 0};${t}`,inputDependencies:re},getRunData:()=>({outputs:oe,dispatchGroup:R,programUniforms:B}),getShaderSource:ee}},ho=(t,i,s,a,u,c,d,m,g,y,E)=>{let $=Math.min(t.outputCount,1+(d?1:0)+(m?1:0)),h=y.kvNumHeads!==void 0||$>1?y.pastSequenceLength:0,R=h+y.kvSequenceLength,B=g&&Ve.size(g.dims)>0?g:void 0,K=[i,s];y.kvNumHeads===void 0&&$>1&&d&&Ve.size(d.dims)>0&&K.push(d),B&&K.push(B);let re=t.compute(Ou($,i,s,d,B,y,E,h),{inputs:K,outputs:y.kvNumHeads===void 0&&$>1?[-1,1]:[-1]})[0];t.compute(Ma(re,y.batchSize*y.numHeads*y.sequenceLength,R),{inputs:[re],outputs:[]});let oe=[re,a];y.kvNumHeads===void 0&&$>1&&m&&Ve.size(m.dims)>0&&oe.push(m),t.compute(Du($,re,a,m,y,h),{inputs:oe,outputs:y.kvNumHeads===void 0&&$>1?[0,2]:[0]})},Lu=(t,i)=>{let s=[i.batchSize,i.numHeads,i.sequenceLength,i.headSize],a=i.sequenceLength,u=i.inputHiddenSize,c=i.headSize,d=12,m={x:Math.ceil(i.headSize/d),y:Math.ceil(i.sequenceLength/d),z:i.batchSize*i.numHeads},g=[t.inputs[0],t.inputs[1],t.inputs[2]],y=[{type:12,data:a},{type:12,data:u},{type:12,data:c},{type:12,data:i.numHeads},{type:12,data:i.headSize},{type:12,data:i.hiddenSize},{type:12,data:i.hiddenSize+i.hiddenSize+i.vHiddenSize}],E=$=>{let h=Ut("output_q",g[0].dataType,s),R=Ut("output_k",g[0].dataType,s),B=Ut("output_v",g[0].dataType,s),K=it("input",g[0].dataType,g[0].dims),re=it("weight",g[1].dataType,g[1].dims),oe=it("bias",g[2].dataType,g[2].dims),ee=K.type.storage,_e=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"hidden_size",type:"u32"},{name:"ldb",type:"u32"}];return` + const TILE_SIZE = ${d}u; + var tileInput: array<${ee}, ${d*d}>; + var tileWeightQ: array<${ee}, ${d*d}>; + var tileWeightK: array<${ee}, ${d*d}>; + var tileWeightV: array<${ee}, ${d*d}>; + ${$.registerUniforms(_e).declareVariables(K,re,oe,h,R,B)} + ${$.mainStart([d,d,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 = ${ee}(0); + var valueK = ${ee}(0); + var valueV = ${ee}(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:t.inputs[0].dataType,gpuDataType:0},{dims:s,dataType:t.inputs[0].dataType,gpuDataType:0},{dims:s,dataType:t.inputs[0].dataType,gpuDataType:0}],dispatchGroup:m,programUniforms:y}),getShaderSource:E},{inputs:g,outputs:[-1,-1,-1]})},Bu=(t,i)=>{let s=zu(t.inputs,i),[a,u,c]=Lu(t,s);return ho(t,a,u,c,t.inputs[4],void 0,void 0,void 0,t.inputs[5],s,i)}}),Ru,Nu,ju,Vu,Uu=M(()=>{j(),Xt(),Yt(),mn(),sn(),Ru=(t,i)=>{if(!t||t.length!==5)throw new Error("BatchNormalization requires 5 inputs");let s=(a,u,c)=>{let d=u.length;if(d!==a.length)throw new Error(`${c}: num dimensions != ${d}`);u.forEach((m,g)=>{if(m!==a[g])throw new Error(`${c}: dim[${g}] do not match`)})};if(t[0].dims.length>1){let a=i.format==="NHWC"?i.spatial?t[0].dims.slice(-1):t[0].dims.slice(-1).concat(t[0].dims.slice(1,t[0].dims.length-1)):t[0].dims.slice(1,i.spatial?2:void 0);s(t[1].dims,a,"Invalid input scale"),s(t[2].dims,a,"Invalid input B"),s(t[3].dims,a,"Invalid input mean"),s(t[4].dims,a,"Invalid input var")}else s(t[1].dims,[1],"Invalid input scale"),s(t[2].dims,[1],"Invalid input B"),s(t[3].dims,[1],"Invalid input mean"),s(t[4].dims,[1],"Invalid input var")},Nu=(t,i)=>{let{epsilon:s,spatial:a,format:u}=i,c=t[0].dims,d=a?wn(c[c.length-1]):1,m=u==="NHWC"&&c.length>1?d:1,g=Ve.size(c)/d,y=a,E=y?c.length:c,$=it("x",t[0].dataType,t[0].dims,d),h=it("scale",t[1].dataType,t[1].dims,m),R=it("bias",t[2].dataType,t[2].dims,m),B=it("inputMean",t[3].dataType,t[3].dims,m),K=it("inputVar",t[4].dataType,t[4].dims,m),re=Ut("y",t[0].dataType,E,d),oe=()=>{let _e="";if(a)_e=`let cOffset = ${c.length===1?"0u":u==="NHWC"?`outputIndices[${c.length-1}] / ${d}`:"outputIndices[1]"};`;else if(u==="NCHW")_e=` + ${re.indicesSet("outputIndices","0","0")} + let cOffset = ${re.indicesToOffset("outputIndices")};`;else{_e=`var cIndices = ${h.type.indices}(0); + cIndices[0] = outputIndices[${c.length-1}];`;for(let ae=1;ae` + const epsilon = ${s}; + ${_e.registerUniform("outputSize","u32").declareVariables($,h,R,B,K,re)} + ${_e.mainStart()} + ${_e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var outputIndices = ${re.offsetToIndices(`global_idx * ${d}`)}; + ${oe()} + let scale = ${h.getByOffset("cOffset")}; + let bias = ${R.getByOffset("cOffset")}; + let inputMean = ${B.getByOffset("cOffset")}; + let inputVar = ${K.getByOffset("cOffset")}; + let x = ${$.getByOffset("global_idx")}; + let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias; + ${re.setByOffset("global_idx","value")} + }`;return{name:"BatchNormalization",shaderCache:{hint:`${i.epsilon}_${i.format}_${a}_${d}`,inputDependencies:y?["rank","type","type","type","type"]:void 0},getShaderSource:ee,getRunData:()=>({outputs:[{dims:t[0].dims,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(g/64)},programUniforms:y?[{type:12,data:g},...Et(c)]:[{type:12,data:g}]})}},ju=t=>Gt(t),Vu=(t,i)=>{let{inputs:s,outputCount:a}=t,u=ju({...i,outputCount:a});if(z.webgpu.validateInputContent&&Ru(s,u),i.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");t.compute(Nu(s,u))}}),Wu,Gu,ba,Gp=M(()=>{Yt(),sn(),Wu=t=>{if(t[0].dims.length!==3)throw new Error("input should have 3 dimensions");if(![320,640,1280].includes(t[0].dims[2]))throw new Error("number of channels should be 320, 640 or 1280");if(t[1].dims.length!==1)throw new Error("bias is expected to have 1 dimensions");if(t[0].dims[2]!==t[1].dims[0])throw new Error("last dimension of input and bias are not the same")},Gu=t=>{let i=t[0].dims,s=t[0].dims[2],a=Ve.size(i)/4,u=t[0].dataType,c=it("input",u,i,4),d=it("bias",u,[s],4),m=it("residual",u,i,4),g=Ut("output",u,i,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:i,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)}}),getShaderSource:y=>` + const channels = ${s}u / 4; + ${y.declareVariables(c,d,m,g)} + + ${y.mainStart()} + ${y.guardAgainstOutOfBoundsWorkgroupSizes(a)} + let value = ${c.getByOffset("global_idx")} + + ${d.getByOffset("global_idx % channels")} + ${m.getByOffset("global_idx")}; + ${g.setByOffset("global_idx","value")} + }`}},ba=t=>{Wu(t.inputs),t.compute(Gu(t.inputs))}}),qu,vn,Hu,Ku,xa,Qu,Xu,Ta,Yu,Zu,Cs,Ju,ed,td,Sa,nd,mo,rd,$s,id,ka,od,sd,ad,Ea,ld,ud,Ca,dd,cd,$a,pd,fd,Pa,hd,Aa,Ia,Fa,za,md,gd,Oa,_d,yd,wd,Da=M(()=>{Xt(),Yt(),mn(),sn(),qu=(t,i,s,a,u,c)=>{let d=Math.ceil(i/4),m="";typeof u=="string"?m=`${u}(a)`:m=u("a");let g=it("inputData",s,[d],4),y=Ut("outputData",a,[d],4);return` + ${t.registerUniform("vec_size","u32").declareVariables(g,y)} + + ${c??""} + + ${t.mainStart()} + ${t.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + + let a = ${g.getByOffset("global_idx")}; + ${y.setByOffset("global_idx",m)} + }`},vn=(t,i,s,a,u,c=t.dataType)=>({name:i,shaderCache:{hint:u,inputDependencies:["type"]},getShaderSource:d=>qu(d,Ve.size(t.dims),t.dataType,c,s,a),getRunData:d=>({outputs:[{dims:t.dims,dataType:c}],dispatchGroup:{x:Math.ceil(Ve.size(d[0].dims)/64/4)},programUniforms:[{type:12,data:Math.ceil(Ve.size(t.dims)/4)}]})}),Hu=t=>{t.compute(vn(t.inputs[0],"Abs","abs"))},Ku=t=>{t.compute(vn(t.inputs[0],"Acos","acos"))},xa=t=>{t.compute(vn(t.inputs[0],"Acosh","acosh"))},Qu=t=>{t.compute(vn(t.inputs[0],"Asin","asin"))},Xu=t=>{t.compute(vn(t.inputs[0],"Asinh","asinh"))},Ta=t=>{t.compute(vn(t.inputs[0],"Atan","atan"))},Yu=t=>{t.compute(vn(t.inputs[0],"Atanh","atanh"))},Zu=t=>Gt(t),Cs=(t,i)=>{let s;switch(i.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): ${i.to}`)}t.compute(vn(t.inputs[0],"Cast",s,void 0,i.cacheKey,i.to))},Ju=t=>{let i=t.length>=2&&t[1].data!==0?t[1].getFloat32Array()[0]:rr,s=t.length>=3&&t[2].data!==0?t[2].getFloat32Array()[0]:kr;return Gt({min:i,max:s})},ed=(t,i)=>{let s=t.inputs.length===1?i:Ju(t.inputs),a=Sn(t.inputs[0].dataType);t.compute(vn(t.inputs[0],"Clip",u=>`clamp(${u}, clip_min_, clip_max_)`,` + const clip_min_: vec4<${a}> = vec4(${a}(${s.min})); + const clip_max_: vec4<${a}> = vec4(${a}(${s.max})); +`,s.cacheKey),{inputs:[0]})},td=t=>{t.compute(vn(t.inputs[0],"Ceil","ceil"))},Sa=t=>{t.compute(vn(t.inputs[0],"Cos","cos"))},nd=t=>{t.compute(vn(t.inputs[0],"Cosh","cosh"))},mo=t=>Gt(t),rd=(t,i)=>{let s=Sn(t.inputs[0].dataType);t.compute(vn(t.inputs[0],"Elu",a=>`elu_vf32(${a})`,` + const elu_alpha_ = ${s}(${i.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)); + }`,i.cacheKey))},$s=(t="f32")=>` +const r0: ${t} = 0.3275911; +const r1: ${t} = 0.254829592; +const r2: ${t} = -0.284496736; +const r3: ${t} = 1.421413741; +const r4: ${t} = -1.453152027; +const r5: ${t} = 1.061405429; + +fn erf_vf32(v: vec4<${t}>) -> vec4<${t}> { + 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)); +}`,id=t=>{let i=Sn(t.inputs[0].dataType);t.compute(vn(t.inputs[0],"Erf",s=>`erf_vf32(${s})`,$s(i)))},ka=t=>{t.compute(vn(t.inputs[0],"Exp","exp"))},od=t=>{t.compute(vn(t.inputs[0],"Floor","floor"))},sd=t=>{let i=Sn(t.inputs[0].dataType);t.compute(vn(t.inputs[0],"Gelu",s=>`0.5 * ${s} * (1.0 + erf_vf32(${s} * 0.7071067811865475))`,$s(i)))},ad=(t,i)=>{let s=Sn(t.inputs[0].dataType);t.compute(vn(t.inputs[0],"LeakyRelu",a=>`select(leaky_relu_alpha_ * ${a}, ${a}, ${a} >= vec4<${s}>(0.0))`,`const leaky_relu_alpha_ = ${s}(${i.alpha});`,i.cacheKey))},Ea=t=>{t.compute(vn(t.inputs[0],"Not",i=>`!${i}`))},ld=t=>{t.compute(vn(t.inputs[0],"Neg",i=>`-${i}`))},ud=t=>{t.compute(vn(t.inputs[0],"Reciprocal",i=>`1.0/${i}`))},Ca=t=>{let i=Sn(t.inputs[0].dataType);t.compute(vn(t.inputs[0],"Relu",s=>`select(vec4<${i}>(0.0), ${s}, ${s} > vec4<${i}>(0.0))`))},dd=t=>{t.compute(vn(t.inputs[0],"Sigmoid",i=>`(1.0 / (1.0 + exp(-${i})))`))},cd=t=>Gt(t),$a=(t,i)=>{let s=Sn(t.inputs[0].dataType);t.compute(vn(t.inputs[0],"HardSigmoid",a=>`max(vec4<${s}>(0.0), min(vec4<${s}>(1.0), ${i.alpha} * ${a} + vec4<${s}>(${i.beta})))`,void 0,i.cacheKey))},pd=t=>{t.compute(vn(t.inputs[0],"Sin","sin"))},fd=t=>{t.compute(vn(t.inputs[0],"Sinh","sinh"))},Pa=t=>{t.compute(vn(t.inputs[0],"Sqrt","sqrt"))},hd=t=>{t.compute(vn(t.inputs[0],"Tan","tan"))},Aa=t=>`sign(${t}) * (1 - exp(-2 * abs(${t}))) / (1 + exp(-2 * abs(${t})))`,Ia=t=>{t.compute(vn(t.inputs[0],"Tanh",Aa))},Fa=(t="f32")=>` +const fast_gelu_a: ${t} = 0.5; +const fast_gelu_b: ${t} = 0.7978845608028654; +const fast_gelu_c: ${t} = 0.035677408136300125; + +fn tanh_v(v: vec4<${t}>) -> vec4<${t}> { + return ${Aa("v")}; +} +`,za=t=>`(fast_gelu_a + fast_gelu_a * tanh_v(${t} * (fast_gelu_c * ${t} * ${t} + fast_gelu_b))) * ${t}`,md=t=>{let i=Sn(t.inputs[0].dataType);t.compute(vn(t.inputs[0],"FastGelu",za,Fa(i),void 0,t.inputs[0].dataType))},gd=(t,i)=>{let s=Sn(t.inputs[0].dataType);return t.compute(vn(t.inputs[0],"ThresholdedRelu",a=>`select(vec4<${s}>(0.0), ${a}, ${a} > thresholded_relu_alpha_)`,`const thresholded_relu_alpha_ = vec4<${s}>(${i.alpha});`,i.cacheKey)),0},Oa=t=>{t.compute(vn(t.inputs[0],"Log","log"))},_d=(t,i)=>` +const alpha = vec4<${t}>(${i}); +const one = ${t}(1.0); +const zero = ${t}(0.0); + +fn quick_gelu_impl(x: vec4<${t}>) -> vec4<${t}> { + let v = x *alpha; + var x1 : vec4<${t}>; + 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; +} +`,yd=t=>`quick_gelu_impl(${t})`,wd=(t,i)=>{let s=Sn(t.inputs[0].dataType);t.compute(vn(t.inputs[0],"QuickGelu",yd,_d(s,i.alpha),i.cacheKey,t.inputs[0].dataType))}}),La,vd,Md,bd=M(()=>{Yt(),sn(),Da(),La=t=>{if(t[0].dims.length!==3)throw new Error("input should have 3 dimensions");if(![2560,5120,10240].includes(t[0].dims[2]))throw new Error("hidden state should be 2560, 5120 or 10240");if(t[1].dims.length!==1)throw new Error("bias is expected to have 1 dimensions");if(t[0].dims[2]!==t[1].dims[0])throw new Error("last dimension of input and bias are not the same")},vd=t=>{let i=t[0].dims.slice();i[2]=i[2]/2;let s=it("input",t[0].dataType,t[0].dims,4),a=it("bias",t[0].dataType,[t[0].dims[2]],4),u=Ut("output",t[0].dataType,i,4),c=Ve.size(i)/4,d=Tn(t[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:i,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)}}),getShaderSource:m=>` + const M_SQRT2 = sqrt(2.0); + const halfChannels = ${t[0].dims[2]/4/2}u; + + ${m.declareVariables(s,a,u)} + + ${$s(d)} + + ${m.mainStart()} + ${m.guardAgainstOutOfBoundsWorkgroupSizes(c)} + 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); + + ${u.setByOffset("global_idx","valueLeft * geluRight")} + }`}},Md=t=>{La(t.inputs),t.compute(vd(t.inputs))}}),xd,Td,qr,Sd,kd,Ba,Ed,Cd,$d,Pd,Ad,Id,Ra,qp=M(()=>{Xt(),Yt(),sn(),xd=(t,i,s,a,u,c,d,m,g,y,E,$)=>{let h,R;typeof m=="string"?h=R=(ee,_e)=>`${m}((${ee}),(${_e}))`:typeof m=="function"?h=R=m:(h=m.scalar,R=m.vector);let B=Ut("outputData",E,a.length,4),K=it("aData",g,i.length,4),re=it("bData",y,s.length,4),oe;if(u)if(c){let ee=Ve.size(i)===1,_e=Ve.size(s)===1,ae=i.length>0&&i[i.length-1]%4===0,ge=s.length>0&&s[s.length-1]%4===0;ee||_e?oe=B.setByOffset("global_idx",R(ee?`${K.type.value}(${K.getByOffset("0")}.x)`:K.getByOffset("global_idx"),_e?`${re.type.value}(${re.getByOffset("0")}.x)`:re.getByOffset("global_idx"))):oe=` + let outputIndices = ${B.offsetToIndices("global_idx * 4u")}; + let offsetA = ${K.broadcastedIndicesToOffset("outputIndices",B)}; + let offsetB = ${re.broadcastedIndicesToOffset("outputIndices",B)}; + ${B.setByOffset("global_idx",R(d||ae?K.getByOffset("offsetA / 4u"):`${K.type.value}(${K.getByOffset("offsetA / 4u")}[offsetA % 4u])`,d||ge?re.getByOffset("offsetB / 4u"):`${re.type.value}(${re.getByOffset("offsetB / 4u")}[offsetB % 4u])`))} + `}else oe=B.setByOffset("global_idx",R(K.getByOffset("global_idx"),re.getByOffset("global_idx")));else{if(!c)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let ee=(_e,ae,ge="")=>{let Qe=`aData[indexA${ae}][componentA${ae}]`,ze=`bData[indexB${ae}][componentB${ae}]`;return` + let outputIndices${ae} = ${B.offsetToIndices(`global_idx * 4u + ${ae}u`)}; + let offsetA${ae} = ${K.broadcastedIndicesToOffset(`outputIndices${ae}`,B)}; + let offsetB${ae} = ${re.broadcastedIndicesToOffset(`outputIndices${ae}`,B)}; + let indexA${ae} = offsetA${ae} / 4u; + let indexB${ae} = offsetB${ae} / 4u; + let componentA${ae} = offsetA${ae} % 4u; + let componentB${ae} = offsetB${ae} % 4u; + ${_e}[${ae}] = ${ge}(${h(Qe,ze)}); + `};E===9?oe=` + var data = vec4(0); + ${ee("data",0,"u32")} + ${ee("data",1,"u32")} + ${ee("data",2,"u32")} + ${ee("data",3,"u32")} + outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:oe=` + ${ee("outputData[global_idx]",0)} + ${ee("outputData[global_idx]",1)} + ${ee("outputData[global_idx]",2)} + ${ee("outputData[global_idx]",3)} + `}return` + ${t.registerUniform("vec_size","u32").declareVariables(K,re,B)} + + ${$??""} + + ${t.mainStart()} + ${t.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${oe} + }`},Td=(t,i,s,a,u,c,d=s.dataType)=>{let m=!Ve.areEqual(s.dims,a.dims),g=s.dims,y=Ve.size(s.dims),E=!1,$=!1,h=[m];if(m){let R=ur.calcShape(s.dims,a.dims,!1);if(!R)throw new Error("Can't perform binary op on the given tensors");g=R,y=Ve.size(g);let B=Ve.size(s.dims)===1,K=Ve.size(a.dims)===1,re=s.dims.length>0&&s.dims[s.dims.length-1]%4===0,oe=a.dims.length>0&&a.dims[a.dims.length-1]%4===0;h.push(B),h.push(K),h.push(re),h.push(oe);let ee=1;for(let _e=1;_eR.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:R=>xd(R,s.dims,a.dims,g,E,m,$,u,s.dataType,a.dataType,d,c),getRunData:()=>({outputs:[{dims:g,dataType:d}],dispatchGroup:{x:Math.ceil(y/64/4)},programUniforms:[{type:12,data:Math.ceil(Ve.size(g)/4)},...Et(s.dims,a.dims,g)]})}},qr=(t,i,s,a,u,c)=>{t.compute(Td(i,u??"",t.inputs[0],t.inputs[1],s,a,c))},Sd=t=>{qr(t,"Add",(i,s)=>`${i}+${s}`)},kd=t=>{qr(t,"Div",(i,s)=>`${i}/${s}`)},Ba=t=>{qr(t,"Equal",{scalar:(i,s)=>`u32(${i}==${s})`,vector:(i,s)=>`vec4(${i}==${s})`},void 0,void 0,9)},Ed=t=>{qr(t,"Mul",(i,s)=>`${i}*${s}`)},Cd=t=>{let i=it("input",t.inputs[0].dataType,t.inputs[0].dims).type.value;qr(t,"Pow",{scalar:(s,a)=>`pow_custom(${s},${a})`,vector:(s,a)=>`pow_vector_custom(${s},${a})`},` + fn pow_custom(a : ${i}, b : ${i}) -> ${i} { + if (b == ${i}(0.0)) { + return ${i}(1.0); + } else if (a < ${i}(0.0) && f32(b) != floor(f32(b))) { + return ${i}(pow(f32(a), f32(b))); // NaN + } + return select(sign(a), ${i}(1.0), round(f32(abs(b) % ${i}(2.0))) != 1.0) * ${i}(${i==="i32"?"round":""}(pow(f32(abs(a)), f32(b)))); + } + fn pow_vector_custom(a : vec4<${i}>, b : vec4<${i}>) -> vec4<${i}> { + // TODO: implement vectorized pow + return vec4<${i}>(pow_custom(a.x, b.x), pow_custom(a.y, b.y), pow_custom(a.z, b.z), pow_custom(a.w, b.w)); + } + `)},$d=t=>{qr(t,"Sub",(i,s)=>`${i}-${s}`)},Pd=t=>{qr(t,"Greater",{scalar:(i,s)=>`u32(${i}>${s})`,vector:(i,s)=>`vec4(${i}>${s})`},void 0,void 0,9)},Ad=t=>{qr(t,"Less",{scalar:(i,s)=>`u32(${i}<${s})`,vector:(i,s)=>`vec4(${i}<${s})`},void 0,void 0,9)},Id=t=>{qr(t,"GreaterOrEqual",{scalar:(i,s)=>`u32(${i}>=${s})`,vector:(i,s)=>`vec4(${i}>=${s})`},void 0,void 0,9)},Ra=t=>{qr(t,"LessOrEqual",{scalar:(i,s)=>`u32(${i}<=${s})`,vector:(i,s)=>`vec4(${i}<=${s})`},void 0,void 0,9)}}),Fd,Na,zd,Od,Di,Dd,Hp=M(()=>{Xt(),Yt(),mn(),sn(),Fd=(t,i)=>{if(!t||t.length<1)throw new Error("too few inputs");let s=0,a=t[s],u=a.dataType,c=a.dims.length;t.forEach((d,m)=>{if(m!==s){if(d.dataType!==u)throw new Error("input tensors should be one type");if(d.dims.length!==c)throw new Error("input tensors should have the same shape");d.dims.forEach((g,y)=>{if(y!==i&&g!==a.dims[y])throw new Error("non concat dimensions must match")})}})},Na=(t,i)=>` + fn calculateInputIndex(index: u32) -> u32 { + let sizeInConcatAxis = array(${i}); + for (var i: u32 = 0u; i < ${t}; i += 1u ) { + if (index < sizeInConcatAxis[i]) { + return i; + } + } + return ${t}u; + }`,zd=(t,i)=>{let s=t.length,a=[];for(let u=0;u{let u=Ve.size(s),c=new Array(t.length),d=new Array(t.length),m=0,g=[],y=[],E=[{type:12,data:u}];for(let K=0;K`uniforms.sizeInConcatAxis${K}`).join(","),B=K=>` + + ${(()=>{K.registerUniform("outputSize","u32");for(let re=0;re(${R}); + ${h} -= sizeInConcatAxis[inputIndex - 1u]; + } + + ${zd(d,$)} + }`;return{name:"Concat",shaderCache:{hint:`${i}`,inputDependencies:g},getRunData:()=>({outputs:[{dims:s,dataType:a}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:E}),getShaderSource:B}},Di=(t,i)=>{let s=t.inputs,a=s[0].dims,u=Ve.normalizeAxis(i.axis,a.length);Fd(s,u);let c=a.slice();c[u]=s.reduce((m,g)=>m+(g.dims.length>u?g.dims[u]:0),0);let d=s.filter(m=>Ve.size(m.dims)>0);t.compute(Od(d,u,c,s[0].dataType),{inputs:d})},Dd=t=>Gt({axis:t.axis})}),Li,Bi,Mi,ja,Ri=M(()=>{Xt(),Yt(),Li=(t,i,s="f32")=>{switch(t.activation){case"Relu":return`value = max(value, ${i}(0.0));`;case"Sigmoid":return`value = (${i}(1.0) / (${i}(1.0) + exp(-value)));`;case"Clip":return`value = clamp(value, ${i}(${s}(uniforms.clip_min)), ${i}(${s}(uniforms.clip_max)));`;case"HardSigmoid":return`value = max(${i}(0.0), min(${i}(1.0), ${s}(uniforms.alpha) * value + ${s}(uniforms.beta)));`;case"LeakyRelu":return`value = select(${s}(uniforms.alpha) * value, value, value >= ${i}(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 ${t.activation}`)}},Bi=(t,i)=>{t.activation==="Clip"?i.push({type:1,data:t.clipMax},{type:1,data:t.clipMin}):t.activation==="HardSigmoid"?i.push({type:1,data:t.alpha},{type:1,data:t.beta}):t.activation==="LeakyRelu"&&i.push({type:1,data:t.alpha})},Mi=(t,i)=>{t.activation==="Clip"?i.push({name:"clip_max",type:"f32"},{name:"clip_min",type:"f32"}):t.activation==="HardSigmoid"?i.push({name:"alpha",type:"f32"},{name:"beta",type:"f32"}):t.activation==="LeakyRelu"&&i.push({name:"alpha",type:"f32"})},ja=t=>{let i=(t==null?void 0:t.activation)||"";if(i==="HardSigmoid"){let[s,a]=(t==null?void 0:t.activation_params)||[.2,.5];return{activation:i,alpha:s,beta:a}}else if(i==="Clip"){let[s,a]=(t==null?void 0:t.activation_params)||[rr,kr];return{activation:i,clipMax:a,clipMin:s}}else if(i==="LeakyRelu"){let[s]=(t==null?void 0:t.activation_params)||[.01];return{activation:i,alpha:s}}return{activation:i}}}),fr,Va,go=M(()=>{fr=(t,i)=>{switch(t){case 1:return i;case 2:return`vec2<${i}>`;case 3:return`vec3<${i}>`;case 4:return`vec4<${i}>`;default:throw new Error(`${t}-component is not supported.`)}},Va=t=>` + ${t?"value = value + getBiasByOutputCoords(coords);":""} + `}),Ua,Ld=M(()=>{Ua=t=>` +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(${t}.x), i32(${t}.y), i32(${t}.z), 1)); +} +`}),Bd,No,Ps,Wa,Rd,As,Is,Ga,Fs=M(()=>{Xt(),Yt(),sn(),Ri(),go(),Bd=(t,i)=>t?` + mm_Asub[inputRow][inputCol] = mm_readA(batch, + kStart + inputRow, + globalRowStart / innerElementSize + inputCol${i?", batchIndices":""}); + `:` + mm_Asub[inputRow][inputCol] = mm_readA(batch, + globalRow + innerRow, + kStart / innerElementSize + inputCol${i?", batchIndices":""}); + `,No=(t,i)=>t?` + let ACached0 = mm_Asub[k * innerElementSize][localRow]; + let ACached1 = mm_Asub[k * innerElementSize + 1][localRow]; + let ACached2 = mm_Asub[k * innerElementSize + 2][localRow]; + ${i===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]; + ${i===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]; + ${i===3?"":"acc[i] = BCached3 * ACached.w + acc[i];"} + }`,Ps=(t,i,s="f32",a,u=!1,c=32,d=!1,m=32)=>{let g=i[1]*t[1],y=i[0]*t[0],E=u?g:c,$=u?c:g,h=E/i[0],R=c/i[1];if(!((u&&h===4&&t[1]===4||!u&&(h===3||h===4))&&E%i[0]===0&&c%i[1]===0&&t[0]===4))throw new Error(`If transposeA ${u} is true, innerElementSize ${h} and workPerThread[1] ${t[1]} must be 4. + Otherwise, innerElementSize ${h} must be 3 or 4. + tileAWidth ${E} must be divisible by workgroupSize[0]${i[0]}. tileInner ${c} must be divisible by workgroupSize[1] ${i[1]}. colPerThread ${t[0]} must be 4.`);return` +var mm_Asub: array, ${E/h}>, ${$}>; +var mm_Bsub: array, ${y/t[0]}>, ${c}>; + +const rowPerThread = ${t[1]}; +const colPerThread = ${t[0]}; +const innerElementSize = ${h}; +const tileInner = ${c}; + +@compute @workgroup_size(${i[0]}, ${i[1]}, ${i[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 = ${d?"0":"i32(globalId.z)"}; + ${a?`let batchIndices = ${a.offsetToIndices("u32(batch)")};`:""} + let globalRowStart = i32(workgroupId.y) * ${g}; + + let num_tiles = ${d?`${Math.ceil(m/c)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; + var kStart = ${d?`i32(globalId.z) * ${m}`:"0"}; + + var acc: array, rowPerThread>; + + // Loop over shared dimension. + let tileRowB = localRow * ${R}; + 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; + ${Bd(u,a)} + } + + // Load one tile of B into local memory. + for (var innerRow = 0; innerRow < ${R}; innerRow = innerRow + 1) { + let inputRow = tileRowB + innerRow; + let inputCol = tileCol; + mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol${a?", 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];"} + + ${No(u,h)} + } + + workgroupBarrier(); + } + + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]); + } +}`},Wa=(t,i)=>t?` + mm_Asub[inputRow][inputCol] = mm_readA(batch, + kStart + inputRow, + globalRowStart + inputCol${i?", batchIndices":""}); + `:` + mm_Asub[inputRow][inputCol] = mm_readA(batch, + globalRowStart + inputRow, + kStart + inputCol${i?", batchIndices":""}); + `,Rd=t=>t?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",As=(t,i,s="f32",a,u=!1,c=32,d=!1,m=32,g=!1)=>{let y=t[1]*i[1],E=t[0]*i[0],$=u?y:c,h=u?c:y;if(!(h%i[1]===0&&$%i[0]===0&&c%i[1]===0))throw new Error(`tileAHight ${h} must be divisible by workgroupSize[1]${i[1]}, tileAWidth ${$} must be divisible by workgroupSize[0]${i[0]}, tileInner ${c} must be divisible by workgroupSize[1]${i[1]}`);let R=h/i[1],B=$/i[0],K=c/i[1],re=g?` + let localRow = i32(localId.y); + let localCol = i32(localId.x); + let globalRowStart = i32(workgroupId.y) * ${y}; + let globalColStart = i32(workgroupId.x) * ${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 inputRow = localRow; inputRow < ${h}; inputRow = inputRow + ${i[1]}) { + for (var inputCol = localCol; inputCol < ${$}; inputCol = inputCol + ${i[0]}) { + ${Wa(u,a)} + } + } + // Load one tile of B into local memory. + for (var inputRow = localRow; inputRow < ${c}; inputRow = inputRow + ${i[1]}) { + for (var inputCol = localCol; inputCol < ${E}; inputCol = inputCol + ${i[0]}) { + mm_Bsub[inputRow][inputCol] = mm_readB(batch, + kStart + inputRow, + globalColStart + inputCol${a?", 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 * ${i[0]}]; + } + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + let ACached = ${u?`mm_Asub[k][localRow + innerRow * ${i[1]}];`:`mm_Asub[localRow + innerRow * ${i[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 * ${i[1]}; + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + let gCol = globalColStart + localCol + innerCol * ${i[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) * ${y}; + +let tileRowA = i32(localId.y) * ${R}; +let tileColA = i32(localId.x) * ${B}; +let tileRowB = i32(localId.y) * ${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 innerRow = 0; innerRow < ${R}; innerRow = innerRow + 1) { + for (var innerCol = 0; innerCol < ${B}; innerCol = innerCol + 1) { + let inputRow = tileRowA + innerRow; + let inputCol = tileColA + innerCol; + ${Wa(u,a)} + } + } + + // Load one tile of B into local memory. + for (var innerRow = 0; innerRow < ${K}; 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${a?", 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) { + ${Rd(u)} + 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, ${c}>; + const rowPerThread = ${t[1]}; + const colPerThread = ${t[0]}; + const tileInner = ${c}; + +@compute @workgroup_size(${i[0]}, ${i[1]}, ${i[2]}) +fn main(@builtin(local_invocation_id) localId : vec3, + @builtin(global_invocation_id) globalId : vec3, + @builtin(workgroup_id) workgroupId : vec3) { + let batch = ${d?"0":"i32(globalId.z)"}; + ${a?`let batchIndices = ${a.offsetToIndices("u32(batch)")};`:""} + let num_tiles = ${d?`${Math.ceil(m/c)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; + var kStart = ${d?`i32(globalId.z) * ${m}`:"0"}; + + var acc : array, rowPerThread>; + ${re} + } +`},Is=(t,i,s,a,u,c=!1)=>{let[d,m,g]=u,[y,E,$,h]=a,R=po(d,g),B=po(m,g),K=Tn(a[0].type.tensor),re=()=>{let ee=E.rank,_e=y.rank,ae=`var aIndices: ${E.type.indices};`;for(let ge=ee-2-1,Qe=_e-1;ge>=0;ge--,Qe--)ae+=` +aIndices[${ge}] = ${_e>1?`batchIndices[${Qe}]`:"batchIndices"};`;return R.forEach(ge=>{ae+=` +aIndices[${ge}] = 0;`}),ae+=` +aIndices[${ee-2}] = u32(row); + aIndices[${ee-1}] = u32(colIn);`,ae},oe=()=>{let ee=$.rank,_e=y.rank,ae=`var bIndices: ${$.type.indices};`;for(let ge=ee-2-1,Qe=_e-1;ge>=0;ge--,Qe--)ae+=` +bIndices[${ge}] = ${_e>1?`batchIndices[${Qe}]`:"batchIndices"};`;return B.forEach(ge=>{ae+=` +bIndices[${ge}] = 0;`}),ae+=` +bIndices[${ee-2}] = u32(row); + bIndices[${ee-1}] = u32(colIn);`,ae};return` + fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${y.type.indices}) -> ${fr(t,K)} { + var value = ${fr(t,K)}(0.0); + let col = colIn * ${t}; + if(row < uniforms.dim_a_outer && col < uniforms.dim_inner) + { + ${re()} + value = ${E.getByIndices("aIndices")}; + } + return value; + } + + fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${y.type.indices}) -> ${fr(t,K)} { + var value = ${fr(t,K)}(0.0); + let col = colIn * ${t}; + if(row < uniforms.dim_inner && col < uniforms.dim_b_outer) + { + ${oe()} + value = ${$.getByIndices("bIndices")}; + } + return value; + } + + fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${fr(t,K)}) { + let col = colIn * ${t}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) { + var value = valueIn; + let coords = vec3(batch, row, colIn); + ${i?`value = value + ${c?"bias[colIn]":`${fr(t,K)}(bias[row])`};`:""} + ${s} + ${h.setByIndices("vec3(coords)","value")} + } + } + `},Ga=(t,i,s,a,u=!1)=>{let c=t[0].dims,d=t[1].dims,m=c.slice(0,-2),g=d.slice(0,-2),y=a?a.slice(0,-2):s.slice(0,-2),E=Ve.size(y),$=c[c.length-2],h=c[c.length-1],R=d[d.length-1],B=h%4===0&&R%4===0,K=$<=8?[4,1,1]:[4,4,1],re=[8,8,1],oe=[Math.ceil(R/re[0]/K[0]),Math.ceil($/re[1]/K[1]),Math.ceil(E/re[2]/K[2])],ee=B?4:1,_e=[...m,$,h/ee],ae=_e.length,ge=[...g,h,R/ee],Qe=ge.length,ze=[E,$,R/ee],ht=[{type:6,data:$},{type:6,data:R},{type:6,data:h}];Bi(i,ht),ht.push(...Et(y,_e,ge));let Ft=["rank","rank"],Dt=t.length>2;Dt&&(ht.push(...Et(t[2].dims)),Ft.push("rank")),ht.push(...Et(ze));let hn=ln=>{let rn=y.length,yn=oa("batchDims",t[0].dataType,rn,1),Wn=Tn(t[0].dataType),kn=it("a",t[0].dataType,ae,ee),jn=it("b",t[1].dataType,Qe,ee),It=Ut("result",t[0].dataType,ze.length,ee),tn=[kn,jn];if(Dt){let Gn=u?ee:1;tn.push(it("bias",t[2].dataType,t[2].dims.length,Gn))}let en=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];Mi(i,en);let Ze=Tn(It.type.tensor),zt=Li(i,It.type.value,Ze),on=Is(ee,Dt,zt,[yn,kn,jn,It],[m,g,y],u);return` + ${ln.registerUniforms(en).registerInternalVariables(yn).declareVariables(...tn,It)} + ${on} + ${B?Ps(K,re,Wn,yn):As(K,re,Wn,yn)} + `};return{name:"MatMul",shaderCache:{hint:`${K};${i.activation};${B};${u}`,inputDependencies:Ft},getRunData:()=>({outputs:[{dims:s,dataType:t[0].dataType}],dispatchGroup:{x:oe[0],y:oe[1],z:oe[2]},programUniforms:ht}),getShaderSource:hn}}}),Nd,Kp,Qp=M(()=>{Xt(),zr(),sn(),Ri(),go(),Ld(),Fs(),Nd=(t,i,s,a,u=!1,c,d=4,m=4,g=4,y="f32")=>{let E=Ft=>{switch(Ft){case 1:return"resData = x[xIndex];";case 3:return`resData = vec3<${y}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return"resData = x[xIndex / 4];";default:throw new Error(`innerElementSize ${Ft} is not supported.`)}},$=Ft=>{switch(Ft){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 ${Ft} is not supported.`)}},h=t?` + let coord = vec4(batch, xRow, xCol, xCh); + `:` + let coord = vec4(batch, xCh, xRow, xCol); + `,R=t?` + let coords = vec4( + batch, + row / outWidth, + row % outWidth, + col); + `:` + let coords = vec4( + batch, + row, + col / outWidth, + col % outWidth); + `,B=t?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",K=t?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",re=t?"row":"col",oe=t?"col":"row",ee=` + let inChannels = i32(uniforms.w_shape[2]); + let outWidth = ${t?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; + let outRow = ${re} / outWidth; + let outCol = ${re} % outWidth; + + let WRow = ${oe} / (i32(uniforms.w_shape[1]) * inChannels); + let WCol = ${oe} / 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 = ${oe} % inChannels; + var resData = ${fr(d,y)}(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 < ${K}) { + ${h} + let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape)); + ${E(d)} + } + return resData;`,_e=t?i&&a?` + let col = colIn * ${d}; + ${ee}`:` + let col = colIn * ${d}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { + ${ee} + } + return ${fr(d,y)}(0.0);`:a&&s?` + let col = colIn * ${d}; + ${ee}`:` + let col = colIn * ${d}; + if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { + ${ee} + } + return ${fr(d,y)}(0.0);`,ae=`${$(m)}`,ge=fr(g,y),Qe=fr(t?d:m,y),ze=fr(t?m:d,y),ht=Li(c,ge,y);return` + fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${Qe} { + ${t?_e:ae} + } + + fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${ze} { + ${t?ae:_e} + } + + fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${ge}) { + let col = colIn * ${g}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) + { + var value = valueIn; + let outWidth = ${t?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; + ${R} + ${Va(u)} + ${ht} + setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); + } + }`},Kp=(t,i,s,a,u,c,d,m)=>{let g=i.format==="NHWC",y=g?t[0].dims[3]:t[0].dims[1],E=s[0],$=g?s[2]:s[3],h=g?s[1]:s[2],R=g?s[3]:s[1],B=g&&(y%4===0||y%3===0)&&R%4===0,K=g?R:$*h,re=g?$*h:R,oe=[8,8,1],ee=a<=8?[4,1,1]:[4,4,1],_e=[Math.ceil(K/oe[0]/ee[0]),Math.ceil(re/oe[1]/ee[1]),Math.ceil(E/oe[2]/ee[2])];Rn("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${_e}`);let ae=B?g&&y%4!==0?3:4:1,ge=oe[1]*ee[1],Qe=oe[0]*ee[0],ze=Math.max(oe[0]*ae,oe[1]),ht=a%ge===0,Ft=u%Qe===0,Dt=c%ze===0,hn=B?[ae,4,4]:[1,1,1],ln=[{type:6,data:a},{type:6,data:u},{type:6,data:c},{type:6,data:[i.pads[0],i.pads[1]]},{type:6,data:i.strides},{type:6,data:i.dilations}];Bi(i,ln),ln.push(...Et(t[0].dims,t[1].dims));let rn=["rank","rank"];d&&(ln.push(...Et(t[2].dims)),rn.push("rank")),ln.push(...Et(s));let yn=Wn=>{let kn=[{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}];Mi(i,kn);let jn=B?4:1,It=Tn(t[0].dataType),tn=` + fn setOutputAtIndex(flatIndex : i32, value : ${B?`vec4<${It}>`:It}) { + result[flatIndex] = ${B?`vec4<${It}>`:It}(value); + } + fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${B?`vec4<${It}>`:It}) { + let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3)); + setOutputAtIndex(flatIndex ${B?"/ 4":""}, value); + }`,en=it("x",t[0].dataType,t[0].dims.length,ae===3?1:ae),Ze=it("w",t[1].dataType,t[1].dims.length,jn),zt=[en,Ze],on=Ut("result",t[0].dataType,s.length,jn);if(d){let Gn=it("bias",t[2].dataType,t[2].dims.length,jn);zt.push(Gn),tn+=` + fn getBiasByOutputCoords(coords : vec4) -> ${B?`vec4<${It}>`:It} { + return bias[coords.${g?"w":"y"}${B?"/ 4":""}]; + }`}return` + ${Ua("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 }; + ${Wn.registerUniforms(kn).declareVariables(...zt,on)} + ${tn} + ${Nd(g,ht,Ft,Dt,d,i,hn[0],hn[1],hn[2],It)} + ${B?Ps(ee,oe,It,void 0,!g,ze):As(ee,oe,It,void 0,!g,ze,!1,void 0,m)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${i.cacheKey};${ae};${B};${ht};${Ft};${Dt};${ge};${Qe};${ze}`,inputDependencies:rn},getRunData:()=>({outputs:[{dims:s,dataType:t[0].dataType}],dispatchGroup:{x:_e[0],y:_e[1],z:_e[2]},programUniforms:ln}),getShaderSource:yn}}}),jd,qa,bi,Vd,Ha,Ud,Wd,Gd,Ka=M(()=>{Xt(),zr(),Yt(),sn(),Ri(),go(),jd=t=>{let i=1;for(let s=0;stypeof t=="number"?[t,t,t]:t,bi=(t,i)=>i<=1?t:t+(t-1)*(i-1),Vd=(t,i,s,a=1)=>{let u=bi(i,a);return Math.floor((t[0]*(s-1)-s+u)/2)},Ha=(t,i,s,a,u)=>{u==null&&(u=Vd(t,i[0],a[0]));let c=[0,0,0,s];for(let d=0;d<3;d++)t[d]+2*u>=i[d]&&(c[d]=Math.trunc((t[d]-i[d]+2*u)/a[d]+1));return c},Ud=(t,i,s,a,u,c,d,m,g,y)=>{let E,$,h,R;if(t==="VALID"&&(t=0),typeof t=="number"){E={top:t,bottom:t,left:t,right:t,front:t,back:t};let B=Ha([i,s,a,1],[m,g,y],1,[u,c,d],t);$=B[0],h=B[1],R=B[2]}else if(Array.isArray(t)){if(!t.every((K,re,oe)=>K===oe[0]))throw Error(`Unsupported padding parameter: ${t}`);E={top:t[0],bottom:t[1],left:t[2],right:t[3],front:t[4],back:t[5]};let B=Ha([i,s,a,1],[m,g,y],1,[u,c,d],t[0]);$=B[0],h=B[1],R=B[2]}else if(t==="SAME_UPPER"){$=Math.ceil(i/u),h=Math.ceil(s/c),R=Math.ceil(a/d);let B=($-1)*u+m-i,K=(h-1)*c+g-s,re=(R-1)*d+y-a,oe=Math.floor(B/2),ee=B-oe,_e=Math.floor(K/2),ae=K-_e,ge=Math.floor(re/2),Qe=re-ge;E={top:_e,bottom:ae,left:ge,right:Qe,front:oe,back:ee}}else throw Error(`Unknown padding parameter: ${t}`);return{padInfo:E,outDepth:$,outHeight:h,outWidth:R}},Wd=(t,i,s,a,u,c=!1,d="channelsLast")=>{let m,g,y,E,$;if(d==="channelsLast")[m,g,y,E,$]=t;else if(d==="channelsFirst")[m,$,g,y,E]=t;else throw new Error(`Unknown dataFormat ${d}`);let[h,,R,B,K]=i,[re,oe,ee]=qa(s),[_e,ae,ge]=qa(a),Qe=bi(R,_e),ze=bi(B,ae),ht=bi(K,ge),{padInfo:Ft,outDepth:Dt,outHeight:hn,outWidth:ln}=Ud(u,g,y,E,re,oe,ee,Qe,ze,ht),rn=c?h*$:h,yn=[0,0,0,0,0];return d==="channelsFirst"?yn=[m,rn,Dt,hn,ln]:d==="channelsLast"&&(yn=[m,Dt,hn,ln,rn]),{batchSize:m,dataFormat:d,inDepth:g,inHeight:y,inWidth:E,inChannels:$,outDepth:Dt,outHeight:hn,outWidth:ln,outChannels:rn,padInfo:Ft,strideDepth:re,strideHeight:oe,strideWidth:ee,filterDepth:R,filterHeight:B,filterWidth:K,effectiveFilterDepth:Qe,effectiveFilterHeight:ze,effectiveFilterWidth:ht,dilationDepth:_e,dilationHeight:ae,dilationWidth:ge,inShape:t,outShape:yn,filterShape:i}},Gd=(t,i,s,a,u,c)=>{let d=c==="channelsLast";d?t[0].dims[3]:t[0].dims[1];let m=[64,1,1],g={x:s.map((re,oe)=>oe)},y=[Math.ceil(jd(g.x.map(re=>s[re]))/m[0]),1,1];Rn("verbose",()=>`[conv3d_naive_webgpu] dispatch = ${y}`);let E=1,$=Ve.size(s),h=[{type:12,data:$},{type:12,data:a},{type:12,data:u},{type:12,data:i.strides},{type:12,data:i.dilations}];Bi(i,h),h.push(...Et(t[0].dims,t[1].dims));let R=["rank","rank"],B=t.length===3;B&&(h.push(...Et(t[2].dims)),R.push("rank")),h.push(...Et(s));let K=re=>{let oe=[{name:"output_size",type:"u32"},{name:"filter_dims",type:"u32",length:a.length},{name:"pads",type:"u32",length:u.length},{name:"strides",type:"u32",length:i.strides.length},{name:"dilations",type:"u32",length:i.dilations.length}];Mi(i,oe);let ee=1,_e=Tn(t[0].dataType),ae=it("x",t[0].dataType,t[0].dims.length,E),ge=it("W",t[1].dataType,t[1].dims.length,ee),Qe=[ae,ge],ze=Ut("result",t[0].dataType,s.length,ee),ht="";if(B){let hn=it("bias",t[2].dataType,t[2].dims.length,ee);Qe.push(hn),ht+=` + fn getBiasByOutputCoords(coords : array) -> ${_e} { + return bias[${d?Ot("coords",4,5):Ot("coords",1,5)}]; + }`}let Ft=fr(E,_e),Dt=Li(i,Ft,_e);return` + ${ht} + fn getX(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { + let aIndices = array(d0, d1, d2, d3, d4); + return ${ae.getByIndices("aIndices")}; + } + fn getW(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { + let aIndices = array(d0, d1, d2, d3, d4); + return ${ge.getByIndices("aIndices")}; + } + ${re.registerUniforms(oe).declareVariables(...Qe,ze)} + ${re.mainStart()} + ${re.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let coords = ${ze.offsetToIndices("global_idx")}; + let batch = ${Ot("coords",0,ae.rank)}; + let d2 = ${d?Ot("coords",ae.rank-1,ae.rank):Ot("coords",1,ae.rank)}; + let xFRCCorner = vec3(${d?Ot("coords",1,ae.rank):Ot("coords",2,ae.rank)}, + ${d?Ot("coords",2,ae.rank):Ot("coords",3,ae.rank)}, + ${d?Ot("coords",3,ae.rank):Ot("coords",4,ae.rank)}) * uniforms.strides - uniforms.pads; + let xFCorner = xFRCCorner.x; + let xRCorner = xFRCCorner.y; + let xCCorner = xFRCCorner.z; + let xShapeY = ${d?Ot("uniforms.x_shape",1,ae.rank):Ot("uniforms.x_shape",2,ae.rank)}; + let xShapeZ = ${d?Ot("uniforms.x_shape",2,ae.rank):Ot("uniforms.x_shape",3,ae.rank)}; + let xShapeW = ${d?Ot("uniforms.x_shape",3,ae.rank):Ot("uniforms.x_shape",4,ae.rank)}; + let xShapeU = ${d?Ot("uniforms.x_shape",4,ae.rank):Ot("uniforms.x_shape",1,ae.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) { + ${d?`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) { + ${d?`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) { + ${d?`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) { + ${d?`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)":""}; + ${Dt} + result[global_idx] = f32(value); + }`};return{name:"Conv3DNaive",shaderCache:{hint:`${i.cacheKey};${d};${E};${B}`,inputDependencies:R},getRunData:()=>({outputs:[{dims:s,dataType:t[0].dataType}],dispatchGroup:{x:y[0],y:y[1],z:y[2]},programUniforms:h}),getShaderSource:K}}}),qd,Hd,Xp=M(()=>{Xt(),Yt(),sn(),Zd(),Ri(),qd=(t,i,s)=>{let a=t.length>2,u=a?"value += b[output_channel];":"",c=t[0].dims,d=t[1].dims,m=d[0]/i.group,g=i.format==="NHWC",y=zs(c,d,i.dilations,i.pads,i.strides,g),E=Ve.size(y),$=[{type:12,data:E},{type:12,data:i.dilations},{type:12,data:[i.strides[0],i.strides[1]]},{type:12,data:[i.pads[0],i.pads[1]]},{type:12,data:m}];Bi(i,$),$.push(...Et(c,d));let h=["rank","rank"];a&&($.push(...Et(t[2].dims)),h.push("rank")),$.push(...Et(y));let R=B=>{let K=Ut("output",t[0].dataType,y.length),re=Tn(K.type.tensor),oe=Li(i,K.type.value,re),ee=it("x",t[0].dataType,c.length),_e=it("w",t[1].dataType,d.length),ae=[ee,_e];a&&ae.push(it("b",t[2].dataType,t[2].dims.length));let ge=[{name:"output_size",type:"u32"},{name:"dilations",type:"u32",length:i.dilations.length},{name:"strides",type:"u32",length:2},{name:"pads",type:"u32",length:2},{name:"output_channels_per_group",type:"u32"}];return Mi(i,ge),` + ${B.registerUniforms(ge).declareVariables(...ae,K)} + + ${B.mainStart()} + ${B.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let outputIndices = ${K.offsetToIndices("global_idx")}; + let batch: u32 = outputIndices[0]; + let output_channel: u32 = outputIndices[${g?3:1}]; + let xRCCorner: vec2 = vec2(outputIndices[${g?1:2}], outputIndices[${g?2:3}]) * uniforms.strides - uniforms.pads; + let group_id: u32 = output_channel / uniforms.output_channels_per_group; + + var value: ${K.type.value} = ${K.type.value}(0); + for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[1]; wInChannel++) { + let input_channel = group_id * uniforms.w_shape[1] + wInChannel; + for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[2]; wHeight++) { + let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0]; + + if (xHeight < 0u || xHeight >= uniforms.x_shape[${g?1:2}]) { + continue; + } + + for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[3]; wWidth++) { + let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1]; + if (xWidth < 0u || xWidth >= uniforms.x_shape[${g?2:3}]) { + continue; + } + + let xVal = ${g?ee.get("batch","xHeight","xWidth","input_channel"):ee.get("batch","input_channel","xHeight","xWidth")}; + let wVal = ${_e.get("output_channel","wInChannel","wHeight","wWidth")}; + value += xVal*wVal; + } + } + } + ${u} + ${oe} + ${K.setByOffset("global_idx","value")} + }`};return{name:"GroupedConv",shaderCache:{hint:i.cacheKey,inputDependencies:h},getRunData:()=>({outputs:[{dims:s?s(y):y,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(E/64)},programUniforms:$}),getShaderSource:R}},Hd=(t,i,s)=>{let a=t.length>2,u=wn(s[3]),c=wn(s[2]),d=Ve.size(s)/u/c,m=[t[0].dims[0],t[0].dims[1],t[0].dims[2],t[0].dims[3]/u],g=[t[1].dims[0],t[1].dims[1],t[1].dims[2],t[1].dims[3]/u],y=[s[0],s[1],s[2],s[3]/u],E=[{type:12,data:d},{type:6,data:[i.strides[0],i.strides[1]]},{type:6,data:[i.pads[0],i.pads[1]]}];Bi(i,E),E.push(...Et(m,g,y));let $=(c-1)*i.strides[1]+g[1],h=R=>{let B=Ut("output",t[0].dataType,y.length,u),K=Tn(B.type.tensor),re=Li(i,B.type.value,K),oe=it("x",t[0].dataType,m.length,u),ee=it("w",t[1].dataType,g.length,u),_e=[oe,ee];a&&_e.push(it("b",t[2].dataType,t[2].dims,u));let ae=a?"value += b[output_channel];":"",ge=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return Mi(i,ge),` + ${R.registerUniforms(ge).declareVariables(..._e,B)} + ${R.mainStart()} + ${R.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] / ${c}u; + let col = (index1 % width1) * ${c}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<${oe.type.value}, ${$}>; + var values: array<${B.type.value}, ${c}>; + 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 < ${g[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 < ${$}; i++) { + let x_width = x_corner.y + i; + if (x_width >= 0 && u32(x_width) < uniforms.x_shape[2]) { + x_vals[i] = ${oe.get("batch","u32(x_height)","u32(x_width)","input_channel")}; + } else { + x_vals[i] = ${oe.type.value}(0); + } + } + for (var w_width: u32 = 0u; w_width < ${g[1]}; w_width++) { + let w_val = ${ee.get("w_height","w_width","0","output_channel")}; + for (var i = 0u; i < ${c}u; i++) { + values[i] = fma(x_vals[i * u32(uniforms.strides[1]) + w_width], w_val, values[i]); + } + } + } + } + + for (var i = 0u; i < ${c}u; i++) { + var value = values[i]; + ${ae} + ${re} + ${B.set("batch","row","col + i","output_channel","value")}; + } + }`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${i.cacheKey};${u};${c};${$};${g[0]};${g[1]}`,inputDependencies:a?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:s,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:E}),getShaderSource:h}}}),Qa,Kd,Qd,Xa=M(()=>{Xt(),Yt(),Fs(),sn(),Ri(),Qa=(t,i,s,a,u=!1)=>{let c=t[0].dims,d=t[1].dims,m=c[c.length-2],g=d[d.length-1],y=c[c.length-1],E=wn(g),$=wn(y),h=wn(m),R=Ve.size(s)/E/h,B=t.length>2,K=a?a.slice(0,-2):s.slice(0,-2),re=[Ve.size(K),m,g],oe=[{type:12,data:R},{type:12,data:m},{type:12,data:g},{type:12,data:y}];Bi(i,oe),oe.push(...Et(K,c,d)),B&&oe.push(...Et(t[2].dims)),oe.push(...Et(re));let ee=_e=>{let ae=oa("batch_dims",t[0].dataType,K.length),ge=it("a",t[0].dataType,c.length,$),Qe=it("b",t[1].dataType,d.length,E),ze=Ut("output",t[0].dataType,re.length,E),ht=Tn(ze.type.tensor),Ft=Li(i,ze.type.value,ht),Dt=[ge,Qe],hn="";if(B){let tn=u?E:1;Dt.push(it("bias",t[2].dataType,t[2].dims.length,tn)),hn=`${u?`value += bias[col / ${tn}];`:`value += ${ze.type.value}(bias[row + i]);`}`}let ln=c.slice(0,-2),rn=d.slice(0,-2),yn=po(ln,K),Wn=po(rn,K),kn=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];Mi(i,kn);let jn=(tn,en)=>{let Ze=tn.rank,zt=tn.name;if(Ze===2)return`var ${zt}_indices = ${tn.type.indices}(0u, 0u);`;let on=ae.rank,Gn=`var ${zt}_indices: ${tn.type.indices};`;for(let or=Ze-2-1,yr=on-1;or>=0;or--,yr--)Gn+=` +${zt}_indices[${or}] = ${on>1?`batch_indices[${yr}]`:"batch_indices"};`;return en.forEach(or=>{Gn+=` +${zt}_indices[${or}] = 0;`}),Gn+=`${zt}_indices[${Ze-2}] = 0u; + ${zt}_indices[${Ze-1}] = 0u;`,Gn},It=()=>{let tn=`var a_data: ${ge.type.value};`;for(let en=0;en<$;en++)tn+=` + let b_data${en} = b[(b_offset + (k + ${en}) * uniforms.N + col) / ${E}];`;for(let en=0;en; + for (var k: u32 = 0u; k < uniforms.K; k = k + ${$}) { + ${It()} + } + for (var i = 0u; i < ${h}u; i++) { + var value = values[i]; + ${hn} + ${Ft} + let cur_indices = ${ze.type.indices}(batch, row + i, col); + let offset = ${ze.indicesToOffset("cur_indices")}; + ${ze.setByOffset(`offset / ${E}`,"value")}; + } + } + `};return{name:"MatMulNaive",shaderCache:{hint:`${i.activation};${E};${$};${h};${u}`,inputDependencies:B?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:s,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(R/64)},programUniforms:oe}),getShaderSource:ee}},Kd=t=>{if(!t||t.length!==2)throw new Error("MatMul requires 2 inputs.");if(t[0].dims[t[0].dims.length-1]!==t[1].dims[t[1].dims.length-2])throw new Error("shared dimension does not match.")},Qd=t=>{Kd(t.inputs);let i=ur.calcShape(t.inputs[0].dims,t.inputs[1].dims,!0);if(!i)throw new Error("Can't use matmul on the given tensors");let s=i[i.length-1],a=t.inputs[0].dims[t.inputs[0].dims.length-1];s<8&&a<8?t.compute(Qa(t.inputs,{activation:""},i)):t.compute(Ga(t.inputs,{activation:""},i))}}),zs,Os,Ya,Ds,Za,Ja,Xd,Yd,jo,Zd=M(()=>{Yt(),Qp(),Ka(),Fs(),Xp(),Ri(),Xa(),fo(),zs=(t,i,s,a,u,c)=>{let d=t[0],m=t.slice(c?1:2,c?3:4),g=m.length,y=i[0],E=i.slice(2).map((h,R)=>h+(h-1)*(s[R]-1)),$=m.map((h,R)=>h+a[R]+a[R+g]).map((h,R)=>Math.floor((h-E[R]+u[R])/u[R]));return $.splice(0,0,d),$.splice(c?3:1,0,y),$},Os=[2,3,1,0],Ya=(t,i)=>{if(!t||t.length!==2&&t.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(t[0].dims.length>5)throw new Error("greater than 5D is not supported");if(t[0].dims.length!==t[1].dims.length)throw new Error("filter does not have same dimension as input");let s=t[0].dims[i.format==="NHWC"?t[0].dims.length-1:1],a=t[1].dims[1]*i.group;if(s!==a)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");if(t.length===3&&(t[2].dims.length!==1||t[1].dims[0]!==t[2].dims[0]))throw new Error("invalid bias");let u=t[0].dims.length-2;if(i.dilations.length!==u)throw new Error(`dilations should be ${u}D`);if(i.strides.length!==u)throw new Error(`strides should be ${u}D`);if(i.pads.length!==u*2)throw new Error(`pads should be ${u*2}D`);if(i.kernelShape.length!==0&&i.kernelShape.length!==t[1].dims.length-2)throw new Error("invalid kernel shape")},Ds=(t,i)=>{let s=t.kernelShape.slice();for(let c=2;c{let i=ja(t),s=t.format,a=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][t.auto_pad],u=t.dilations,c=t.group,d=t.kernel_shape,m=t.pads,g=t.strides,y=t.w_is_const();return{autoPad:a,format:s,dilations:u,group:c,kernelShape:d,pads:m,strides:g,wIsConst:y,...i,cacheKey:`${t.format};${i.activation};`}},Ja=(t,i,s)=>{let a=Ds(s,i),u=s.format==="NHWC";if(s.group!==1){if(!t.adapterInfo.isArchitecture("ampere")&&u&&i[1].dims[0]===s.group&&i[1].dims[1]===1&&s.dilations[0]===1&&s.dilations[1]===1){let Qe=zs(i[0].dims,i[1].dims,s.dilations,a.pads,s.strides,u),ze=t.kernelCustomData.wT??t.compute(li(i[1],Os),{inputs:[1],outputs:[s.wIsConst?-2:-1]})[0];s.wIsConst&&!t.kernelCustomData.wT&&(t.kernelCustomData.wT=ze);let ht=[i[0],ze];i.length===3&&ht.push(i[2]),t.compute(Hd(ht,a,Qe),{inputs:ht})}else t.compute(qd(i,a));return}let c=i.length===3,d=i[0].dims[u?1:2],m=i[0].dims[u?2:3],g=i[0].dims[u?3:1],y=i[1].dims[2],E=i[1].dims[3],$=zs(i[0].dims,i[1].dims,s.dilations,a.pads,s.strides,u),h=$[u?1:2],R=$[u?2:3],B=$[u?3:1],K=u&&y===d&&E===m&&s.pads[0]===0&&s.pads[1]===0;if(K||y===1&&E===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 Qe=$[0],ze,ht,Ft,Dt=[];if(u){let rn=t.kernelCustomData.wT??t.compute(li(i[1],Os),{inputs:[1],outputs:[s.wIsConst?-2:-1]})[0];if(s.wIsConst&&!t.kernelCustomData.wT&&(t.kernelCustomData.wT=rn),K){let yn=d*m*g;ze=i[0].reshape([1,Qe,yn]),ht=rn.reshape([1,yn,B]),Ft=[1,Qe,B]}else ze=i[0].reshape([Qe,d*m,g]),ht=rn.reshape([1,g,B]),Ft=[Qe,h*R,B];Dt.push(ze),Dt.push(ht)}else ze=i[0].reshape([Qe,g,d*m]),ht=i[1].reshape([1,B,g]),Ft=[Qe,B,h*R],Dt.push(ht),Dt.push(ze);c&&Dt.push(i[2]);let hn=Ft[2],ln=Dt[0].dims[Dt[0].dims.length-1];hn<8&&ln<8?t.compute(Qa(Dt,a,$,Ft,u),{inputs:Dt}):t.compute(Ga(Dt,a,$,Ft,u),{inputs:Dt});return}let re=!0,oe=t.kernelCustomData.wT??t.compute(li(i[1],Os),{inputs:[1],outputs:[s.wIsConst?-2:-1]})[0];s.wIsConst&&!t.kernelCustomData.wT&&(t.kernelCustomData.wT=oe);let ee=[i[0],oe];c&&ee.push(i[2]);let _e=u?h*R:B,ae=u?B:h*R,ge=y*E*g;t.compute(Kp(ee,a,$,_e,ae,ge,c,re),{inputs:ee})},Xd=(t,i)=>{let s=i.format==="NHWC",a=[t.inputs[0].reshape(s?[t.inputs[0].dims[0],1,t.inputs[0].dims[1],t.inputs[0].dims[2]]:[t.inputs[0].dims[0],t.inputs[0].dims[1],1,t.inputs[0].dims[2]]),t.inputs[1].reshape([t.inputs[1].dims[0],t.inputs[1].dims[1],1,t.inputs[1].dims[2]])];t.inputs.length===3&&a.push(t.inputs[2]);let u=[0,i.pads[0],0,i.pads[1]],c=[1].concat(i.strides),d=[1].concat(i.dilations),m=[1].concat(i.kernelShape),g=Ds({...i,pads:u,strides:c,dilations:d,kernelShape:m},a);t.compute(qd(a,g,y=>s?[y[0],y[2],y[3]]:[y[0],y[1],y[3]]))},Yd=(t,i,s)=>{let a=s.format==="NHWC"?"channelsLast":"channelsFirst",u=Ds(s,i),c=s.autoPad==="NOTSET"?s.pads:s.autoPad,d=Wd(i[0].dims,i[1].dims,s.strides,s.dilations,c,!1,a);t.compute(Gd(i,u,d.outShape,[d.filterDepth,d.filterHeight,d.filterWidth],[d.padInfo.front,d.padInfo.top,d.padInfo.left],a))},jo=(t,i)=>{Ya(t.inputs,i),t.inputs[0].dims.length===3?Xd(t,i):t.inputs[0].dims.length===5?Yd(t,t.inputs,i):Ja(t,t.inputs,i)}}),Jd,ec,Yp=M(()=>{Xt(),zr(),sn(),Ri(),go(),Ld(),Fs(),Jd=(t,i=!1,s,a,u=4)=>{let c=re=>{switch(re){case 1:return"return w[getIndexFromCoords4D(coord, vec4(uniforms.w_shape))];";case 4:return` + let coord1 = vec4(coordX, coordY, col + 1, rowInner); + let coord2 = vec4(coordX, coordY, col + 2, rowInner); + let coord3 = vec4(coordX, coordY, col + 3, rowInner); + let v0 = w[getIndexFromCoords4D(coord, vec4(uniforms.w_shape))]; + let v1 = w[getIndexFromCoords4D(coord1, vec4(uniforms.w_shape))]; + let v2 = w[getIndexFromCoords4D(coord2, vec4(uniforms.w_shape))]; + let v3 = w[getIndexFromCoords4D(coord3, vec4(uniforms.w_shape))]; + return ${a}(v0, v1, v2, v3); + `;default:throw new Error(`innerElementSize ${re} is not supported.`)}},d=t?` + let coord = vec4(batch, iXR, iXC, xCh); + `:` + let coord = vec4(batch, xCh, iXR, iXC); + `,m=t?` + let coords = vec4( + batch, + row / outWidth, + row % outWidth, + col); + `:` + let coords = vec4( + batch, + row, + col / outWidth, + col % outWidth); + `,g=t?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",y=t?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",E=t?"row":"col",$=t?"col":"row",h=` + let inChannels = ${t?"i32(uniforms.x_shape[3])":"i32(uniforms.x_shape[1])"}; + let outWidth = ${t?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; + let outRow = ${E} / outWidth; + let outCol = ${E} % outWidth; + + let WRow = ${$} / (uniforms.filter_dims[1] * inChannels); + let WCol = ${$} / inChannels % uniforms.filter_dims[1]; + let xR = f32(outRow - uniforms.pads[0] + uniforms.dilations[0] * WRow) / f32(uniforms.strides[0]); + let xC = f32(outCol - uniforms.pads[1] + uniforms.dilations[1] * WCol) / f32(uniforms.strides[1]); + if (xR < 0.0 || xR >= f32(${g}) || fract(xR) > 0.0) { + return ${a}(0.0); + } + if (xC < 0.0 || xC >= f32(${y}) || fract(xC) > 0.0) { + return ${a}(0.0); + } + let iXR = i32(xR); + let iXC = i32(xC); + let xCh = ${$} % inChannels; + ${d} + return x[getIndexFromCoords4D(coord, vec4(uniforms.x_shape))/${u}];`,R=t?` + let col = colIn * ${u}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { + ${h} + } + return ${a}(0.0);`:` + let col = colIn * ${u}; + if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { + ${h} + } + return ${a}(0.0);`,B=` + let col = colIn * ${u}; + let inChannels = ${t?"i32(uniforms.x_shape[3])":"i32(uniforms.x_shape[1])"}; + let coordX = uniforms.filter_dims[0] - 1 - row / (uniforms.filter_dims[1] * inChannels); + let coordY = uniforms.filter_dims[1] - 1 - (row / inChannels) % uniforms.filter_dims[1]; + if (${t?"row < uniforms.dim_inner && col < uniforms.dim_b_outer":"row < uniforms.dim_inner && col < uniforms.dim_a_outer"} && coordX >= 0 && coordY >= 0) { + let rowInner = row % inChannels; + let coord = vec4(coordX, coordY, col, rowInner); + ${c(u)} + } + return ${a}(0.0); + `,K=Li(s,a);return` + fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${a} { + ${t?R:B} + } + + fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${a} { + ${t?B:R} + } + + fn mm_write(batch: i32, row : i32, colIn : i32, valueInput : ${a}) { + let col = colIn * ${u}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) { + var value = valueInput; + let outWidth = ${t?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; + ${m} + ${Va(i)} + ${K} + result[getIndexFromCoords4D(coords, vec4(uniforms.result_shape))/${u}] = value; + } + }`},ec=(t,i,s,a,u,c,d,m)=>{let g=i.format==="NHWC",y=g?t[0].dims[3]:t[0].dims[1],E=s[0],$=g?s[2]:s[3],h=g?s[1]:s[2],R=g?s[3]:s[1],B=g&&y%4===0&&y%3&&R%4===0,K=g?R:$*h,re=g?$*h:R,oe=[8,8,1],ee=a<=8?[4,1,1]:[4,4,1],_e=[Math.ceil(K/oe[0]/ee[0]),Math.ceil(re/oe[1]/ee[1]),Math.ceil(E/oe[2]/ee[2])];Rn("verbose",()=>`[conv_backprop_mm_webgpu] dispatch = ${_e}`);let ae=B?4:1,ge=Math.max(oe[0]*ae,oe[1]),Qe=B?4:1,ze=[i.kernelShape[g?1:2],i.kernelShape[g?2:3]],ht=[ze[0]+(i.dilations[0]<=1?0:(ze[0]-1)*(i.dilations[0]-1)),ze[1]+(i.dilations[1]<=1?0:(ze[1]-1)*(i.dilations[1]-1))],Ft=[ht[0]-1-Math.floor((i.pads[0]+i.pads[2])/2),ht[1]-1-Math.floor((i.pads[1]+i.pads[3])/2)],Dt=[{type:6,data:a},{type:6,data:u},{type:6,data:c},{type:6,data:i.strides},{type:6,data:i.dilations},{type:6,data:ze},{type:6,data:Ft}];Bi(i,Dt),Dt.push(...Et(t[0].dims,t[1].dims));let hn=["rank","rank"];d&&(Dt.push(...Et(t[2].dims)),hn.push("rank")),Dt.push(...Et(s));let ln=rn=>{let yn=it("x",t[0].dataType,t[0].dims.length,Qe),Wn=it("w",t[1].dataType,t[1].dims.length,1),kn=Ut("result",t[0].dataType,s.length,Qe),jn=[yn,Wn],It="";if(d){let Ze=it("bias",t[2].dataType,t[2].dims.length,Qe);jn.push(Ze),It+=` + fn getBiasByOutputCoords(coords : vec4) -> ${Ze.type.value} { + return bias[coords.${g?"w":"y"}${B?"/ 4":""}]; + }`}let tn=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"},{name:"strides",type:"i32",length:2},{name:"dilations",type:"i32",length:2},{name:"filter_dims",type:"i32",length:ze.length},{name:"pads",type:"i32",length:Ft.length}];Mi(i,tn);let en=Tn(t[0].dataType,1);if(en!=="f16"&&en!=="f32")throw new Error(`elemType ${en} is not supported.`);return` + ${Ua("uniforms.result_strides")} + ${rn.registerUniforms(tn).declareVariables(...jn,kn)}; + ${It} + ${Jd(g,d,i,yn.type.value,ae)} + ${B?Ps(ee,oe,en,void 0,!g,ge):As(ee,oe,en,void 0,!g,ge,!1,void 0,m)}`};return{name:"Conv2DTransposeMatMul",shaderCache:{hint:`${i.cacheKey};${ee};${oe};${B}`,inputDependencies:hn},getRunData:()=>({outputs:[{dims:s,dataType:t[0].dataType}],dispatchGroup:{x:_e[0],y:_e[1],z:_e[2]},programUniforms:Dt}),getShaderSource:ln}}}),el,Vo,Yh=M(()=>{Xt(),zr(),Yt(),sn(),el=(t,i,s,a,u,c=!1,d,m,g=!1)=>{let y=g?1:2,E=g?2:3,$=g?3:1,h=c?2:1,R=` + fn setOutputAtIndex(flatIndex : u32, value : ${c?`vec4<${d}>`:d}) { + result[flatIndex] = ${c?`vec4<${d}>`:d}(value); + }`;a&&(R+=` + fn getBiasByOutputCoords(coords : vec4) -> ${c?`vec4<${d}>`:d} { + return bias[coords.${g?"w":"y"}${c?"/ 4":""}]; + }`);let B=c?4:1,K=it("W",i[1].dataType,i[1].dims.length,B),re=it("Dy",i[0].dataType,i[0].dims.length,B),oe=[re,K];a&&oe.push(it("bias",i[2].dataType,[s[$]].length,B));let ee=Ut("result",i[0].dataType,s.length,B),_e=`{ + let batch: u32 = ${u?"global_id.z":"workgroup_id.z"} / uniforms.result_shape[1]; + let r = ${u?"global_id.z":"workgroup_id.z"} % uniforms.result_shape[1]; + let c = ${u?"global_id.y":"workgroup_id.y"} * ${h}; + let d1: u32 = ${u?"global_id.x":"workgroup_id.x"} * 4; + + let dyCorner = vec2(i32(r), i32(c)) - vec2(uniforms.pads); + + // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1). + // ? = to be determined. : = across all values in that axis. + var dotProd: array, ${h}>; + for (var i = 0; i < ${h}; i++) { + dotProd[i] = vec4<${d}>(0.0); + } + for (var wR: u32 = 0; wR < uniforms.filter_dims[0]; wR = wR + 1) { + var dyR = (${d}(dyCorner.x) + ${d}(wR)) / ${d}(uniforms.strides.x); + let wRPerm = uniforms.filter_dims[0] - 1 - wR; + if (dyR < 0.0 || dyR >= ${d}(uniforms.Dy_shape[1]) || + fract(dyR) > 0.0 || wRPerm < 0) { + continue; + } + let idyR: u32 = u32(dyR); + + for (var wC: u32 = 0; wC < uniforms.filter_dims[1]; wC = wC + 1) { + let dyC = (${d}(dyCorner.y) + ${d}(wC)) / ${d}(uniforms.strides.y); + let dyC2 = (${d}(dyCorner.y) + 1.0 + ${d}(wC)) / ${d}(uniforms.strides.y); + let wCPerm = uniforms.filter_dims[1] - 1 - wC; + if (wCPerm < 0) { + continue; + } + var bDyCVal = true; + var bDyCVal2 = true; + if (dyC < 0.0 || dyC >= ${d}(uniforms.Dy_shape[2]) || + fract(dyC) > 0.0) { + bDyCVal = false; + } + if (dyC2 < 0.0 || dyC2 >= ${d}(uniforms.Dy_shape[2]) || + fract(dyC2) > 0.0) { + bDyCVal2 = false; + } + + let idyC: u32 = u32(dyC); + let idyC2: u32 = u32(dyC2); + if (bDyCVal && bDyCVal2) { + let d2Length = uniforms.Dy_shape[3]; + for (var d2 :u32 = 0; d2 < d2Length; d2 = d2 + 4) { + let wValue0 = ${K.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; + let wValue1 = ${K.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; + let wValue2 = ${K.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; + let wValue3 = ${K.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; + + var xValue = ${re.get("batch","idyR","idyC","d2")}; + let tmpval = vec4<${d}>(dot(xValue, wValue0), + dot(xValue, wValue1), + dot(xValue, wValue2), + dot(xValue, wValue3)); + dotProd[0] = dotProd[0] + tmpval; + + xValue = ${re.get("batch","idyR","idyC2","d2")}; + + dotProd[1] = dotProd[1] + vec4<${d}>(dot(xValue, wValue0), + dot(xValue, wValue1), + dot(xValue, wValue2), + dot(xValue, wValue3)); + } + } else if (bDyCVal) { + let d2Length = uniforms.Dy_shape[${$}]; + for (var d2: u32 = 0; d2 < d2Length; d2 = d2 + 4) { + let wValue0 = ${K.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; + let wValue1 = ${K.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; + let wValue2 = ${K.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; + let wValue3 = ${K.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; + + var xValue = ${re.get("batch","idyR","idyC","d2")}; + let tmpval = vec4<${d}>(dot(xValue, wValue0), + dot(xValue, wValue1), + dot(xValue, wValue2), + dot(xValue, wValue3)); + dotProd[0] = dotProd[0] + tmpval; + } + } else if (bDyCVal2) { + let d2Length = uniforms.Dy_shape[3]; + for (var d2: u32 = 0; d2 < d2Length; d2 = d2 + 4) { + let wValue0 = ${K.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; + let wValue1 = ${K.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; + let wValue2 = ${K.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; + let wValue3 = ${K.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; + + var xValue = ${re.get("batch","idyR","idyC2","d2")}; + let tmpval = vec4<${d}>(dot(xValue, wValue0), + dot(xValue, wValue1), + dot(xValue, wValue2), + dot(xValue, wValue3)); + dotProd[1] = dotProd[1] + tmpval; + } + } + } + } + + for (var i: u32 = 0; i < ${h}; i = i + 1) { + let value = dotProd[i] + ${a?"bias[c+i]":`vec4<${d}>(0.0)`}; + ${ee.set("batch","r","c + i","d1","value")}; + } + }`,ae=` + let outputIndices = ${ee.offsetToIndices("global_idx")}; + let batch = ${ee.indicesGet("outputIndices",0)}; + let d1 = ${ee.indicesGet("outputIndices",$)}; + let r = ${ee.indicesGet("outputIndices",y)}; + let c = ${ee.indicesGet("outputIndices",E)}; + let dyCorner = vec2(i32(r), i32(c)) - uniforms.pads; + let dyRCorner = dyCorner.x; + let dyCCorner = dyCorner.y; + let groupId = d1 / uniforms.output_channels_per_group; + let wOutChannel = d1 - groupId * uniforms.output_channels_per_group; + // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1). + // ? = to be determined. : = across all values in that axis. + var dotProd = ${d}(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 = (${d}(dyRCorner) + ${d}(wR)) / ${d}(uniforms.strides[0]); + let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x; + if (dyR < 0.0 || dyR >= ${d}(uniforms.Dy_shape[${y}]) || fract(dyR) > 0.0 || + wRPerm < 0) { + continue; + } + let idyR: u32 = u32(dyR); + + for (var wC: u32 = 0; wC < uniforms.effective_filter_dims.y; wC = wC + 1) { + if (wC % uniforms.dilations.y != 0) { + continue; + } + let dyC = (${d}(dyCCorner) + ${d}(wC)) / ${d}(uniforms.strides.y); + let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y; + if (dyC < 0.0 || dyC >= ${d}(uniforms.Dy_shape[${E}]) || + fract(dyC) > 0.0 || wCPerm < 0) { + continue; + } + let idyC: u32 = u32(dyC); + var inputChannel = groupId * uniforms.input_channels_per_group; + for (var d2: u32 = 0; d2 < uniforms.input_channels_per_group; d2 = d2 + 1) { + let xValue = ${g?re.get("batch","idyR","idyC","inputChannel"):re.get("batch","inputChannel","idyR","idyC")}; + let wValue = ${K.get("inputChannel","wOutChannel","u32(wRPerm)","u32(wCPerm)")}; + dotProd = dotProd + xValue * wValue; + inputChannel = inputChannel + 1; + } + } + } + let value = dotProd + ${a?"bias[d1]":`${d}(0.0)`}; + ${ee.setByOffset("global_idx","value")}; + `;return` + ${t.registerUniforms(m).declareVariables(...oe,ee)} + ${R} + + ${t.mainStart()} + ${t.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}; + ${c?_e:ae}}`},Vo=(t,i,s)=>{let a=t.length>2,u=i.outputShape,c=Ve.size(u),d=[Math.ceil(c/64),1,1];Rn("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${d}`);let m=i.format==="NHWC",g=["rank","rank"],y=[i.strides[0],i.strides[1]],E=[i.kernelShape[m?1:2],i.kernelShape[m?2:3]],$=[i.dilations[0],i.dilations[1]],h=[E[0]+(i.dilations[0]<=1?0:(i.kernelShape[m?1:2]-1)*(i.dilations[0]-1)),E[1]+(i.dilations[1]<=1?0:(i.kernelShape[m?2:3]-1)*(i.dilations[1]-1))],R=[h[0]-1-Math.floor((i.pads[0]+i.pads[2])/2),h[1]-1-Math.floor(i.pads[1]+i.pads[3])/2],B=!1,K=i.group,re=t[1].dims,oe=re[0]/K,ee=re[1],_e=[{type:12,data:c},{type:12,data:y},{type:12,data:E},{type:12,data:$},{type:12,data:h},{type:6,data:R},{type:12,data:oe},{type:12,data:ee},...Et(t[0].dims,t[1].dims)];a&&(_e.push(...Et(t[2].dims)),g.push("rank")),_e.push(...Et(u));let ae=d[1]===1&&d[2]===1,ge=Qe=>{let ze=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:y.length},{name:"filter_dims",type:"u32",length:E.length},{name:"dilations",type:"u32",length:E.length},{name:"effective_filter_dims",type:"u32",length:h.length},{name:"pads",type:"i32",length:R.length},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],ht=Tn(t[0].dataType);return`${el(Qe,t,u,a,ae,B,ht,ze,m)}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${i.cacheKey};`,inputDependencies:g},getRunData:()=>({dispatchGroup:{x:d[0],y:d[1],z:d[2]},outputs:[{dims:s?s(u):u,dataType:t[0].dataType}],programUniforms:_e}),getShaderSource:ge}}}),tc,nc,tl,nl,rc,rl,ic,oc,il,Zp,Zh=M(()=>{Yp(),Yh(),Ri(),fo(),tc=(t,i,s,a,u,c)=>(t-1)*i+s+(a-1)*u+1-c,nc=(t,i,s,a,u)=>{let c=Math.floor(t/2);i==="SAME_UPPER"?(s[a]=c,s[u]=t-c):i==="SAME_LOWER"&&(s[a]=t-c,s[u]=c)},tl=(t,i,s,a,u,c,d,m,g,y)=>{let E=t.length-2,$=y.length===0;if(g.length===0)for(let B=0;B{let s=t.kernelShape.slice();if(t.kernelShape.length===0||t.kernelShape.reduce(($,h)=>$*h,1)===0){s.length=0;for(let $=2;$$+h,0)===0){let $=i[0].dims.length-2;g=new Array($).fill(1)}let y=t.strides.slice();if(y.reduce(($,h)=>$+h,0)===0){let $=i[0].dims.length-2;y=new Array($).fill(1)}tl(m,s,g,t.autoPad,t.group,u,y,a,d,c);let E=Object.assign({},t);return Object.assign(E,{kernelShape:s,pads:u,outputPadding:d,outputShape:c,dilations:g,strides:y}),E},rc=t=>{let i=ja(t),s=t.format,a=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof t.autoPad>"u"?0:t.autoPad],u=t.dilations,c=t.group,d=t.kernelShape,m=t.pads,g=t.strides,y=t.wIsConst(),E=t.outputPadding,$=t.outputShape;return{autoPad:a,format:s,dilations:u,group:c,kernelShape:d,outputPadding:E,outputShape:$,pads:m,strides:g,wIsConst:y,...i,cacheKey:`${t.format};${i.activation};`}},rl=(t,i)=>{if(!t||t.length!==2&&t.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(t[0].dims.length!==4&&t[0].dims.length!==3)throw new Error("currently only support 2-dimensional conv");if(t[0].dims.length!==t[1].dims.length)throw new Error("filter does not have same dimension as input");let s=t[0].dims[i.format==="NHWC"?t[0].dims.length-1:1],a=t[1].dims[0];if(s!==a)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");let u=t[1].dims[1]*i.group;if(t.length===3&&(t[2].dims.length!==1||t[2].dims[0]!==u))throw new Error("invalid bias");let c=t[0].dims.length-2;if(i.dilations.reduce((d,m)=>d+m,0)>0&&i.dilations.length!==c)throw new Error(`dilations should be ${c}D`);if(i.strides.reduce((d,m)=>d+m,0)>0&&i.strides.length!==c)throw new Error(`strides should be ${c}D`);if(i.pads.reduce((d,m)=>d+m,0)>0&&i.pads.length!==c*2)throw new Error(`pads should be ${c*2}D`);if(i.outputPadding.length!==c&&i.outputPadding.length!==0)throw new Error(`output_padding should be ${c}D`);if(i.kernelShape.reduce((d,m)=>d+m,0)>0&&i.kernelShape.length!==0&&i.kernelShape.length!==t[1].dims.length-2)throw new Error("invalid kernel shape");if(i.outputShape.length!==0&&i.outputShape.length!==t[0].dims.length-2)throw new Error("invalid output shape")},ic=[2,3,1,0],oc=(t,i,s)=>{let a=nl(s,i),u=s.format==="NHWC",c=a.outputShape,d=c[u?3:1],m=i[0].dims[u?3:1];if(a.group!==1||d===1&&m===1){t.compute(Vo(i,a));return}let g=c[u?1:2],y=c[u?2:3],E=i[1].dims[2],$=i[1].dims[3],h=u?g*y:d,R=u?d:g*y,B=E*$*m,K=!0,re=t.kernelCustomData.wT??t.compute(li(i[1],ic),{inputs:[1],outputs:[s.wIsConst?-2:-1]})[0];s.wIsConst&&!t.kernelCustomData.wT&&(t.kernelCustomData.wT=re);let oe=[i[0],re],ee=i.length===3;ee&&(!u&&i[2].dims.length===1?oe.push(i[2].reshape([i[2].dims[0],1,1])):oe.push(i[2])),t.compute(ec(oe,a,c,h,R,B,ee,K),{inputs:oe})},il=(t,i)=>{let s=i.format==="NHWC",a=[t.inputs[0].reshape(s?[t.inputs[0].dims[0],1,t.inputs[0].dims[1],t.inputs[0].dims[2]]:[t.inputs[0].dims[0],t.inputs[0].dims[1],1,t.inputs[0].dims[2]]),t.inputs[1].reshape([t.inputs[1].dims[0],t.inputs[1].dims[1],1,t.inputs[1].dims[2]])];t.inputs.length===3&&a.push(t.inputs[2]);let u=i.kernelShape;(u.length===0||u[0]===0)&&(u=[t.inputs[1].dims[2]]);let c=i.dilations;(c.length===0||c[0]===0)&&(c=[1]);let d=i.strides;(d.length===0||d[0]===0)&&(d=[1]);let m=i.pads;m.length===0&&(m=[0,0]),m=[0,m[0],0,m[1]],d=[1].concat(d),c=[1].concat(c),u=[1].concat(u);let g=nl({...i,pads:m,strides:d,dilations:c,kernelShape:u},a);t.compute(Vo(a,g,y=>s?[y[0],y[2],y[3]]:[y[0],y[1],y[3]]))},Zp=(t,i)=>{rl(t.inputs,i),t.inputs[0].dims.length===3?il(t,i):oc(t,t.inputs,i)}}),ol,sl,sc,Jp=M(()=>{Xt(),Yt(),mn(),sn(),ol=(t,i,s,a)=>{let u=Ve.size(i),c=i.length,d=it("input",t,c),m=Ut("output",t,c),g=s.dataType===6?s.getInt32Array()[0]:Number(s.getBigInt64Array()[0]),y=Ve.normalizeAxis(g,c),E=$=>{let h=` i32(${d.indicesGet("inputIndices","uniforms.axis")}) `,R=Ot("uniforms.input_shape","uniforms.axis",c),B=a.reverse?h+(a.exclusive?" + 1":""):"0",K=a.reverse?R:h+(a.exclusive?"":" + 1");return` + ${$.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(d,m)} + ${$.mainStart()} + ${$.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var inputIndices = ${m.offsetToIndices("global_idx")}; + var sum = ${m.type.value}(0); + let first : i32 = ${B}; + let last : i32 = ${K}; + for (var i : i32 = first; i < last; i++) { + ${d.indicesSet("inputIndices","uniforms.axis","u32(i)")}; + sum = sum + ${d.getByIndices("inputIndices")}; + } + ${m.setByOffset("global_idx","sum")}; + }`};return{name:"CumSum",shaderCache:{hint:a.cacheKey,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:i,dataType:t}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:[{type:12,data:u},{type:12,data:y},...Et(i,i)]}),getShaderSource:E}},sl=(t,i)=>{let s=t.inputs[0].dims,a=t.inputs[0].dataType,u=t.inputs[1];t.compute(ol(a,s,u,i),{inputs:[0]})},sc=t=>{let i=t.exclusive===1,s=t.reverse===1;return Gt({exclusive:i,reverse:s})}}),al,ac,lc,ll,uc,ef=M(()=>{Xt(),Yt(),mn(),sn(),al=t=>{if(!t||t.length!==1)throw new Error("DepthToSpace requires 1 input.");if(t[0].dims.length!==4)throw new Error("DepthToSpace requires 4D input.")},ac=(t,i,s,a)=>{let u=[];u.push(`fn perm(i: ${a.type.indices}) -> ${s.type.indices} { + var a: ${s.type.indices};`);for(let c=0;c{let s,a,u,c,d,m,g=i.format==="NHWC",y=i.blocksize,E=i.mode==="DCR";g?([s,a,u,c]=t.dims,d=E?[s,a,u,y,y,c/y**2]:[s,a,u,c/y**2,y,y],m=E?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([s,a,u,c]=[t.dims[0],t.dims[2],t.dims[3],t.dims[1]],d=E?[s,y,y,c/y**2,a,u]:[s,c/y**2,y,y,a,u],m=E?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let $=t.reshape(d),h=$.dims.length,R=t.dataType,B=it("a",R,h),K=Ut("output",R,h),re=oe=>` + ${oe.registerUniform("output_size","u32").declareVariables(B,K)} + + ${ac(m,h,B,K)} + + ${oe.mainStart()} + ${oe.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${K.offsetToIndices("global_idx")}; + let aIndices = perm(indices); + + ${K.setByOffset("global_idx",B.getByIndices("aIndices"))} + }`;return{name:"DepthToSpace",shaderCache:{hint:`${t.dims};${i.blocksize};${i.mode}`,inputDependencies:["rank"]},getRunData:oe=>{let ee=g?[s,a*y,u*y,c/y**2]:[s,c/y**2,a*y,u*y],_e=Ve.size(ee),ae=$.dims,ge=Ve.sortBasedOnPerm(ae,m);return{outputs:[{dims:ee,dataType:oe[0].dataType}],dispatchGroup:{x:Math.ceil(_e/64)},programUniforms:[{type:12,data:_e},...Et(ae,ge)]}},getShaderSource:re}},ll=(t,i)=>{al(t.inputs),t.compute(lc(t.inputs[0],i))},uc=t=>Gt({blocksize:t.blocksize,mode:t.mode,format:t.format})}),Uo,Wo,ul,On,tf,nf,rf,Ls,dc,cc,pc,of=M(()=>{Xt(),Yt(),mn(),sn(),Uo="[a-zA-Z]|\\.\\.\\.",Wo="("+Uo+")+",ul="^"+Wo+"$",On="("+Wo+",)*"+Wo,tf="^"+On+"$",nf=class{constructor(t=-1){this.symbolToIndices=new Map,this.inputIndex=t}addSymbol(t,i){let s=this.symbolToIndices.get(t);s===void 0?s=[i]:s.push(i),this.symbolToIndices.set(t,s)}},rf=class{constructor(t,i){var u;this.equation=i,this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=new Array,this.outputDims=[];let[s,a]=i.includes("->")?i.split("->",2):[i,""];if(!s.match(RegExp(tf)))throw new Error("Invalid LHS term");if(s.split(",").forEach((c,d)=>{let m=t[d].dims.slice();if(!c.match(RegExp(ul)))throw new Error("Invalid LHS term");let g=this.processTerm(c,!0,m,d);this.lhs.push(g)}),a==="")a+=[...this.symbolToInfo.entries()].filter(([c,d])=>d.count===1||c==="...").map(([c])=>c).join("");else if(!a.match(RegExp(Wo)))throw new Error("Invalid RHS");(u=a.match(RegExp(Uo,"g")))==null||u.forEach(c=>{if(c==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let d=this.symbolToInfo.get(c);if(d===void 0)throw new Error("Invalid RHS symbol");this.outputDims.push(d.dimValue)}}),this.rhs=this.processTerm(a,!1,this.outputDims)}addSymbol(t,i,s){let a=this.symbolToInfo.get(t);if(a!==void 0){if(a.dimValue!==i&&a.count!==1)throw new Error("Dimension mismatch");a.count++,a.inputIndices.push(s)}else a={count:1,dimValue:i,inputIndices:[s]};this.symbolToInfo.set(t,a)}processTerm(t,i,s,a=-1){let u=s.length,c=!1,d=[],m=0;if(!t.match(RegExp(ul))&&!i&&t!=="")throw new Error("Invalid LHS term");let g=t.match(RegExp(Uo,"g")),y=new nf(a);return g==null||g.forEach((E,$)=>{if(E==="..."){if(c)throw new Error("Only one ellipsis is allowed per input term");c=!0;let h=u-g.length+1;if(h<0)throw new Error("Ellipsis out of bounds");if(d=s.slice(m,m+h),this.hasEllipsis){if(this.ellipsisDims.length!==d.length||this.ellipsisDims.toString()!==d.toString())throw new Error("Ellipsis dimensions mismatch")}else if(i)this.hasEllipsis=!0,this.ellipsisDims=d;else throw new Error("Ellipsis must be specified in the LHS");for(let R=0;Rt+"_max",dc=(t,i,s,a)=>{let u=t.map(y=>y.length).map((y,E)=>it(`input${E}`,i,y)),c=Ve.size(a),d=Ut("output",i,a.length),m=[...s.symbolToInfo.keys()].filter(y=>!s.rhs.symbolToIndices.has(y)),g=y=>{let E=[],$="var prod = 1.0;",h="var sum = 0.0;",R="sum += prod;",B=[],K=[],re=[],oe=[],ee=s.symbolToInfo.size===s.rhs.symbolToIndices.size;s.symbolToInfo.forEach((ae,ge)=>{var Qe;if(s.rhs.symbolToIndices.has(ge)){let ze=(Qe=s.rhs.symbolToIndices.get(ge))==null?void 0:Qe[0];ze!==void 0&&s.lhs.forEach((ht,Ft)=>{if(ae.inputIndices.includes(Ft)){let Dt=ht.symbolToIndices.get(ge);if(Dt===void 0)throw new Error("Invalid symbol error");Dt.forEach(hn=>{E.push(`${u[Ft].indicesSet(`input${Ft}Indices`,hn,d.indicesGet("outputIndices",ze))}`)})}})}else s.lhs.forEach((ze,ht)=>{if(ae.inputIndices.includes(ht)){let Ft=ze.symbolToIndices.get(ge);if(Ft===void 0)throw new Error("Invalid symbol error");Ft.forEach(Dt=>{B.push(`${u[ht].indicesSet(`input${ht}Indices`,Dt,`${ge}`)}`)}),oe.push(`prod *= ${u[ht].getByIndices(`input${ht}Indices`)};`)}}),K.push(`for(var ${ge}: u32 = 0; ${ge} < uniforms.${Ls(ge)}; ${ge}++) {`),re.push("}")});let _e=ee?[...E,`let sum = ${u.map((ae,ge)=>ae.getByIndices(`input${ge}Indices`)).join(" * ")};`]:[...E,h,...K,...B,$,...oe,R,...re];return` + ${y.registerUniforms(m.map(ae=>({name:`${Ls(ae)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...u,d)} + + ${y.mainStart()} + ${y.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var outputIndices = ${d.offsetToIndices("global_idx")}; + ${u.map((ae,ge)=>`var input${ge}Indices: ${u[ge].type.indices};`).join(` +`)} + ${_e.join(` +`)}; + ${d.setByOffset("global_idx","sum")}; + }`};return{name:"Einsum",shaderCache:{hint:s.equation,inputDependencies:t.map(()=>"rank")},getRunData:()=>{let y=m.filter($=>s.symbolToInfo.has($)).map($=>{var h;return{type:12,data:((h=s.symbolToInfo.get($))==null?void 0:h.dimValue)||0}});y.push({type:12,data:c});let E=t.map(($,h)=>[...Et($)]).reduce(($,h)=>$.concat(h),y);return E.push(...Et(a)),{outputs:[{dims:a,dataType:i}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:E}},getShaderSource:g}},cc=(t,i)=>{let s=new rf(t.inputs,i.equation),a=s.outputDims,u=t.inputs.map((c,d)=>c.dims);t.compute(dc(u,t.inputs[0].dataType,s,a))},pc=t=>{let i=t.equation.replace(/\s+/g,"");return Gt({equation:i})}}),dl,Bs,fc,hc,cl,Jh=M(()=>{Xt(),Yt(),sn(),dl=t=>{if(!t||t.length!==2)throw new Error("Expand requires 2 input.");let i=t[0].dims,s=Array.from(t[1].getBigInt64Array(),Number),a=s.length{let s=t.length-i.length,a=[];for(let u=0;ut.length>i.length?Bs(t,i):Bs(i,t),hc=t=>{let i=t[0].dims,s=Array.from(t[1].getBigInt64Array(),Number),a=fc(i,s),u=t[0].dataType,c=u===9?4:1,d=Math.ceil(Ve.size(a)/c),m=y=>{let E=it("input",u,i.length,c),$=Ut("output",u,a.length,c),h;if(u===9){let R=(B,K,re="")=>` + let outputIndices${K} = ${$.offsetToIndices(`outputOffset + ${K}u`)}; + let offset${K} = ${E.broadcastedIndicesToOffset(`outputIndices${K}`,$)}; + let index${K} = offset${K} / 4u; + let component${K} = offset${K} % 4u; + ${B}[${K}] = ${re}(${E.getByOffset(`index${K}`)}[component${K}]); + `;h=` + let outputOffset = global_idx * ${c}; + var data = vec4(0); + ${R("data",0,"u32")} + ${R("data",1,"u32")} + ${R("data",2,"u32")} + ${R("data",3,"u32")} + ${$.setByOffset("global_idx","data")} + }`}else h=` + let outputIndices = ${$.offsetToIndices("global_idx")}; + let inputOffset = ${E.broadcastedIndicesToOffset("outputIndices",$)}; + ${$.setByOffset("global_idx",E.getByOffset("inputOffset"))} + }`;return` + ${y.registerUniform("vec_size","u32").declareVariables(E,$)} + ${y.mainStart()} + ${y.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${h}`},g=[{type:12,data:d},...Et(i,a)];return{name:"Expand",shaderCache:{hint:`${a.length}`,inputDependencies:["rank"]},getShaderSource:m,getRunData:()=>({outputs:[{dims:a,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:g})}},cl=t=>{dl(t.inputs),t.compute(hc(t.inputs),{inputs:[0]})}}),sf,mc,af=M(()=>{Xt(),Yt(),sn(),Da(),sf=t=>{let i=t[0].dataType,s=Ve.size(t[0].dims),a=Ve.size(t[1].dims),u=a%4===0,c=d=>{let m=it("x",i,[1],4),g=it("bias",i,[1],4),y=Ut("y",i,[1],4),E=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],$=R=>` + let bias${R}_offset: u32 = (global_idx * 4 + ${R}) % uniforms.bias_size; + let bias${R} = ${g.getByOffset(`bias${R}_offset / 4`)}[bias${R}_offset % 4];`,h=u?` + let bias = ${g.getByOffset("global_idx % (uniforms.bias_size / 4)")};`:`${$(0)}${$(1)}${$(2)}${$(3)} + let bias = ${m.type.value}(bias0, bias1, bias2, bias3);`;return`${d.registerUniforms(E).declareVariables(m,g,y)} + + ${Fa(Sn(i))} + + ${d.mainStart(Or)} + ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")} + + let x = ${m.getByOffset("global_idx")}; + ${h} + let x_in = x + bias; + ${y.setByOffset("global_idx",za("x_in"))} + }`};return{name:"FastGeluWithBias",shaderCache:{hint:`${u}`,inputDependencies:["type","type"]},getShaderSource:c,getRunData:d=>({outputs:[{dims:d[0].dims,dataType:d[0].dataType}],programUniforms:[{type:12,data:Math.ceil(s/4)},{type:12,data:a}],dispatchGroup:{x:Math.ceil(s/Or/4)}})}},mc=t=>{t.inputs.length<2||Ve.size(t.inputs[1].dims)===0?md(t):t.compute(sf(t.inputs))}}),gc,_c,yc,wc,lf=M(()=>{Xt(),Yt(),mn(),sn(),gc=t=>{if(!t||t.length!==2)throw new Error("Gather requires 2 inputs.")},_c=(t,i)=>{let s=t[0].dims,a=t[1].dims,u=s.length,c=Ve.normalizeAxis(i.axis,u),d=s.slice(0);d.splice(c,1,...a);let m=s[c],g=t[0].dataType===9?4:1,y=Math.ceil(Ve.size(d)/g),E=[{type:12,data:y},{type:6,data:m},{type:12,data:c},...Et(t[0].dims,t[1].dims,d)],$=h=>{let R=it("data",t[0].dataType,t[0].dims.length,g),B=it("inputIndices",t[1].dataType,t[1].dims.length),K=Ut("output",t[0].dataType,d.length,g),re=ee=>{let _e=a.length,ae=`var indicesIndices${ee} = ${B.type.indices}(0);`;for(let ge=0;ge<_e;ge++)ae+=`${_e>1?`indicesIndices${ee}[${ge}]`:`indicesIndices${ee}`} = ${d.length>1?`outputIndices${ee}[uniforms.axis + ${ge}]`:`outputIndices${ee}`};`;ae+=` + var idx${ee} = ${B.getByIndices(`indicesIndices${ee}`)}; + if (idx${ee} < 0) { + idx${ee} = idx${ee} + uniforms.axisDimLimit; + } + var dataIndices${ee} : ${R.type.indices}; + `;for(let ge=0,Qe=0;ge1?`dataIndices${ee}[${ge}]`:`dataIndices${ee}`} = u32(idx${ee});`,Qe+=_e):(ae+=`${u>1?`dataIndices${ee}[${ge}]`:`dataIndices${ee}`} = ${d.length>1?`outputIndices${ee}[${Qe}]`:`outputIndices${ee}`};`,Qe++);return ae},oe;if(t[0].dataType===9){let ee=(_e,ae,ge="")=>` + let outputIndices${ae} = ${K.offsetToIndices(`outputOffset + ${ae}u`)}; + ${re(ae)}; + let offset${ae} = ${R.indicesToOffset(`dataIndices${ae}`)}; + let index${ae} = offset${ae} / 4u; + let component${ae} = offset${ae} % 4u; + ${_e}[${ae}] = ${ge}(${R.getByOffset(`index${ae}`)}[component${ae}]); + `;oe=` + let outputOffset = global_idx * ${g}; + var value = vec4(0); + ${ee("value",0,"u32")} + ${ee("value",1,"u32")} + ${ee("value",2,"u32")} + ${ee("value",3,"u32")} + ${K.setByOffset("global_idx","value")} + `}else oe=` + let outputIndices = ${K.offsetToIndices("global_idx")}; + ${re("")}; + let value = ${R.getByIndices("dataIndices")}; + ${K.setByOffset("global_idx","value")}; + `;return` + ${h.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(R,B,K)} + ${h.mainStart()} + ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + ${oe} + }`};return{name:"Gather",shaderCache:{hint:i.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:d,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(y/64)},programUniforms:E}),getShaderSource:$}},yc=t=>Gt({axis:t.axis}),wc=(t,i)=>{let s=t.inputs;gc(s),t.compute(_c(t.inputs,i))}}),vc,Mc,bc,xc,uf=M(()=>{Xt(),Yt(),mn(),sn(),vc=t=>{if(!t||t.length!==2)throw new Error("GatherElements requires 2 inputs.");if(t[0].dims.length<1)throw new Error("GatherElements requires that the data input be rank >= 1.");if(t[0].dims.length!==t[1].dims.length)throw new Error(`GatherElements requires that the data input and + indices input tensors be of same rank.`)},Mc=(t,i)=>{let s=t[0].dims,a=t[0].dataType,u=s.length,c=t[1].dims,d=t[1].dataType,m=Ve.normalizeAxis(i.axis,u),g=s[m],y=c.slice(0),E=Ve.size(y),$=it("input",a,u),h=it("indicesInput",d,c.length),R=Ut("output",a,y.length),B=[{type:12,data:E},{type:6,data:g},{type:12,data:m}];return B.push(...Et(s,c,y)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:y,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(E/64)},programUniforms:B}),getShaderSource:K=>` + ${K.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables($,h,R)} + ${K.mainStart()} + ${K.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + + let outputIndices = ${R.offsetToIndices("global_idx")}; + + var idx = ${h.getByOffset("global_idx")}; + if (idx < 0) { + idx = idx + uniforms.axisDimLimit; + } + var inputIndices = ${$.type.indices}(outputIndices); + ${$.indicesSet("inputIndices","uniforms.axis","u32(idx)")}; + let value = ${$.getByIndices("inputIndices")}; + + ${R.setByOffset("global_idx","value")}; + }`}},bc=t=>Gt({axis:t.axis}),xc=(t,i)=>{let s=t.inputs;vc(s),t.compute(Mc(t.inputs,i))}}),Tc,Sc,kc,df,Ec=M(()=>{Xt(),Yt(),sn(),Tc=t=>{if(!t)throw new Error("Input is missing");if(t.length<2||t.length>3)throw new Error("Invaid input number.");if(t.length===3&&t[2].dims.length>2)throw new Error("Invalid input shape of C");if(t[0].dataType!==t[1].dataType||t.length===3&&t[0].dataType!==t[2].dataType)throw new Error("Input types are mismatched")},Sc=(t,i)=>{let s=t[0].dims.slice(),a=t[1].dims.slice(),[u,c,d]=bn.getShapeOfGemmResult(s,i.transA,a,i.transB,t.length===3?t[2].dims:void 0),m=[u,c];if(!m)throw new Error("Can't use gemm on the given tensors");let g=Ve.size(m),y=[{type:12,data:g},{type:12,data:u},{type:12,data:c},{type:12,data:d},{type:1,data:i.alpha},{type:1,data:i.beta}],E=["type","type"];t.length===3&&(y.push(...Et(t[2].dims)),E.push("rank")),y.push(...Et(m));let $=h=>{let R="";i.transA&&i.transB?R="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":i.transA&&!i.transB?R="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!i.transA&&i.transB?R="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!i.transA&&!i.transB&&(R="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let B=i.alpha===1?"":"value *= uniforms.alpha;",K=it("a",t[0].dataType,t[0].dims),re=it("b",t[1].dataType,t[1].dims),oe=K.type.value,ee=null,_e=[K,re];t.length===3&&(ee=it("c",t[2].dataType,t[2].dims.length),_e.push(ee));let ae=Ut("output",t[0].dataType,m.length);_e.push(ae);let ge=[{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` + ${h.registerUniforms(ge).declareVariables(..._e)} + + ${h.mainStart()} + ${h.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++) { + ${R} + } + + ${B} + ${ee!=null?`let cOffset = ${ee.broadcastedIndicesToOffset("vec2(m, n)",ae)}; value += ${oe}(uniforms.beta) * ${ee.getByOffset("cOffset")};`:""} + output[global_idx] = value; + }`};return{name:"Gemm",shaderCache:{hint:`${i.cacheKey}`,inputDependencies:E},getRunData:()=>({outputs:[{dims:m,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(g/64)},programUniforms:y}),getShaderSource:$}},kc=t=>{let i=t.transA,s=t.transB,a=t.alpha,u=t.beta;return{transA:i,transB:s,alpha:a,beta:u,cacheKey:`${t.transA};${t.transB};${t.alpha===1}`}},df=(t,i)=>{Tc(t.inputs),t.compute(Sc(t.inputs,i))}}),br,Cc,$c,pl,Pc,Go,Ac,Ic=M(()=>{Xt(),Yt(),mn(),Q(),Es(),sn(),fo(),br=(t,i)=>t.length>i&&t[i].dims.length>0?t[i]:void 0,Cc=(t,i)=>{let s=t[0],a=br(t,1),u=br(t,2),c=br(t,3),d=br(t,4),m=br(t,5),g=br(t,6),y=br(t,7);if(s.dims.length!==3&&s.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let E=s.dims[0],$=s.dims[1],h=s.dims.length===3?s.dims[2]:i.numHeads*s.dims[4],R=$,B=0,K=0,re=Math.floor(h/i.numHeads);if(g&&y){if(g.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(g.dims[0]!==E||g.dims[1]!==i.numHeads||g.dims[3]!==re)throw new Error('Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)');if(y.dims[0]!==E||y.dims[1]!==i.numHeads||y.dims[3]!==re)throw new Error('Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)');if(g.dims[2]!==y.dims[2])throw new Error('Input "past_key" and "past_value" shall have same dim 2 (past_sequence_length)');if(y.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');B=g.dims[2],K=g.dims[2]}else if(g||y)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let oe;if(a){if(s.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(a.dims.length<3||a.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(s.dims[0]!==a.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(a.dims.length===3){if(a.dims[2]!==s.dims[2])throw new Error('Input "query" and "key" shall have same dim 2 (hidden_size)');oe=2,R=a.dims[1]}else if(a.dims.length===5){if(a.dims[2]!==i.numHeads||a.dims[3]!==2||a.dims[4]!==re)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(u)throw new Error('Expect "value" be none when "key" has packed kv format.');oe=5,R=a.dims[1]}else{if(a.dims[1]!==i.numHeads||a.dims[3]!==re)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');oe=0,R=a.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]!==i.numHeads||s.dims[3]!==3)throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');oe=3}if(c){if(c.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimension');if(a&&a.dims.length===5&&a.dims[3]===2)throw new Error("bias is not allowed for packed kv.")}let ee=B+R,_e=0;if(d){_e=8;let ze=d.dims;throw ze.length===1?ze[0]===E?_e=1:ze[0]===3*E+2&&(_e=3):ze.length===2&&ze[0]===E&&ze[1]===ee&&(_e=5),_e===8?new Error('Input "key_padding_mask" shape shall be (batch_size) or (batch_size, total_sequence_length)'):new Error("Mask not supported")}let ae=!1,ge=h;if(u){if(u.dims.length!==3&&u.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(s.dims[0]!==u.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(u.dims.length===3){if(R!==u.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');ge=u.dims[2]}else{if(R!==u.dims[2])throw new Error('Input "key" and "value" shall have the same dim 2 (kv_sequence_length)');ge=u.dims[1]*u.dims[3],ae=!0}}let Qe=!1;if(d)throw new Error("Key padding mask is not supported");if(m){if(m.dims.length!==4)throw new Error('Input "attention_bias" is expected to have 4 dimensions');if(m.dims[0]!==E||m.dims[1]!==i.numHeads||m.dims[2]!==$||m.dims[3]!==ee)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:E,sequenceLength:$,pastSequenceLength:B,kvSequenceLength:R,totalSequenceLength:ee,maxSequenceLength:K,inputHiddenSize:0,hiddenSize:h,vHiddenSize:ge,headSize:re,vHeadSize:Math.floor(ge/i.numHeads),numHeads:i.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:i.maskFilterValue,maskType:_e,scale:i.scale,broadcastResPosBias:Qe,passPastInKv:ae,qkvFormat:oe}},$c=t=>Gt({...t}),pl=Gt({perm:[0,2,1,3]}),Pc=(t,i,s,a,u,c,d)=>{let m=[a,u,c],g=Ve.size(m),y=[{type:12,data:g},{type:12,data:d},{type:12,data:c}],E=$=>{let h=Ut("qkv_with_bias",i.dataType,m),R=it("qkv",i.dataType,m),B=it("bias",s.dataType,m),K=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return` + ${$.registerUniforms(K).declareVariables(R,B,h)} + ${$.mainStart()} + ${$.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 t.compute({name:"MultiHeadAttentionAddBias",shaderCache:{inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:m,dataType:i.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(g/64)},programUniforms:y}),getShaderSource:E},{inputs:[i,s],outputs:[-1]})[0]},Go=(t,i,s,a,u,c,d,m)=>{let g=c;if(d){if(a===1)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return g=Pc(t,c,d,i,a,s*u,m),g=g.reshape([i,a,s,u]),t.compute(li(g,pl.perm),{inputs:[g],outputs:[-1]})[0]}else return c.dims.length===3&&(g=c.reshape([i,a,s,u])),t.compute(li(g,pl.perm),{inputs:[g],outputs:[-1]})[0]},Ac=(t,i)=>{let s=Cc(t.inputs,i),a=t.inputs[0],u=br(t.inputs,1),c=br(t.inputs,2),d=br(t.inputs,3),m=br(t.inputs,4),g=br(t.inputs,5),y=br(t.inputs,6),E=br(t.inputs,7);if(a.dims.length===5)throw new Error("Packed QKV is not implemented");if((u==null?void 0:u.dims.length)===5)throw new Error("Packed KV is not implemented");let $=u&&c&&u.dims.length===4&&c.dims.length===4,h=Go(t,s.batchSize,s.numHeads,s.sequenceLength,s.headSize,a,d,0);if($)return ho(t,h,u,c,m,void 0,y,E,g,s,i);if(!u||!c)throw new Error("key and value must be provided");let R=Go(t,s.batchSize,s.numHeads,s.kvSequenceLength,s.headSize,u,d,s.hiddenSize),B=Go(t,s.batchSize,s.numHeads,s.kvSequenceLength,s.vHeadSize,c,d,2*s.hiddenSize);ho(t,h,R,B,m,void 0,y,E,g,s,i)}}),fl,Fc,zc,hl,Oc,Dc=M(()=>{Xt(),Yt(),sn(),fl=t=>Array.from(t.getBigInt64Array(),Number),Fc=t=>{if(!t||t.length!==2)throw new Error("Tile requires 2 inputs.");if(t[0].dataType!==1&&t[0].dataType!==10&&t[0].dataType!==6&&t[0].dataType!==12)throw new Error("Tile only support float, float16, int32, and uint32 data types");if(t[1].dataType!==7)throw new Error("Tile `repeats` input should be of int64 data type");if(t[1].dims.length!==1)throw new Error("Tile `repeats` input should be 1-D");if(fl(t[1]).length!==t[0].dims.length)throw new Error("Tile `repeats` input should have same number of elements as rank of input data tensor")},zc=(t,i)=>{let s=[];for(let a=0;a{let s=t[0].dims,a=i??fl(t[1]),u=zc(s,a),c=Ve.size(u),d=t[0].dataType,m=it("input",d,s.length),g=Ut("output",d,u.length),y=E=>` + const inputShape = ${m.indices(...s)}; + ${E.registerUniform("output_size","u32").declareVariables(m,g)} + ${E.mainStart()} + ${E.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let output_indices = ${g.offsetToIndices("global_idx")}; + var input_indices: ${m.type.indices}; + for (var i = 0; i < ${s.length}; i++) { + let input_dim_i = ${m.indicesGet("uniforms.input_shape","i")}; + let input_dim_value = ${g.indicesGet("output_indices","i")} % input_dim_i; + + ${m.indicesSet("input_indices","i","input_dim_value")} + } + ${g.setByOffset("global_idx",m.getByIndices("input_indices"))} + }`;return{name:"Tile",shaderCache:{hint:`${a}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:u,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:[{type:12,data:c},...Et(t[0].dims,u)]}),getShaderSource:y}},Oc=t=>{Fc(t.inputs),t.compute(hl(t.inputs),{inputs:[0]})}}),Lc,ml,Bc,Rc,gl,Nc,cf=M(()=>{Xt(),Yt(),mn(),Es(),sn(),Ic(),Dc(),fo(),Lc=(t,i)=>{let s=t[0],a=t[1],u=t[2],c=t[3],d=t[4];if(s.dims.length!==3&&s.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let m=!1,g=s.dims[0],y=s.dims[1],E=s.dims.length===3?m?s.dims[2]/3:s.dims[2]:i.numHeads*s.dims[4],$=y,h=0,R=0,B=Math.floor(E/i.numHeads),K=c&&c.dims.length!==0,re=d&&d.dims.length!==0,oe=!0;if(K&&re){if(c.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(d.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');h=c.dims[1],R=c.dims[1]}else if(K||re)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let ee;if(a){if(s.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(a.dims.length<3||a.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(s.dims[0]!==a.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(a.dims.length===3){if(s.dims[2]%a.dims[2]!==0)throw new Error('Dimension 2 of "query" should be a multiple of "key"');ee=2,$=a.dims[1]}else if(a.dims.length===5){if(a.dims[2]!==i.numHeads||a.dims[3]!==2||a.dims[4]!==B)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(u)throw new Error('Expect "value" be none when "key" has packed kv format.');ee=5,$=a.dims[1]}else{if(a.dims[1]!==i.numHeads||a.dims[3]!==B)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');ee=0,$=a.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]!==i.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 _e=0,ae=!1,ge=E;if(u){if(u.dims.length!==3&&u.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(s.dims[0]!==u.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(u.dims.length===3){if($!==u.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');ge=u.dims[2]}else{if($!==u.dims[2])throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');ge=u.dims[1]*u.dims[3],ae=!0}}let Qe=h+$;return{batchSize:g,sequenceLength:y,pastSequenceLength:h,kvSequenceLength:$,totalSequenceLength:Qe,maxSequenceLength:R,inputHiddenSize:0,hiddenSize:E,vHiddenSize:ge,headSize:B,vHeadSize:Math.floor(ge/i.kvNumHeads),numHeads:i.numHeads,kvNumHeads:i.kvNumHeads,nReps:i.numHeads/i.kvNumHeads,pastPresentShareBuffer:!1,maskType:_e,scale:i.scale,broadcastResPosBias:!1,passPastInKv:ae,qkvFormat:ee,isPastkvBSNH:oe}},ml=(t,i,s,a)=>{let u=[a.batchSize,a.totalSequenceLength,a.kvNumHeads,a.headSize],c=4,d=Ve.size(u)/c,m=a.totalSequenceLength,g=Ut("present_kv",s,u.length,c),y=it("new_kv",t.dataType,t.dims.length,c),E=i?it("past_kv",i.dataType,i.dims.length,c):void 0,$=Math.ceil(a.headSize/c),h={x:m,y:t.dims[0],z:1},R=i?["rank","rank"]:["rank"],B=[{type:12,data:d},{type:12,data:a.pastSequenceLength},{type:12,data:a.kvSequenceLength},{type:12,data:a.totalSequenceLength}],K=[y];E?(B.push(...Et(t.dims),...Et(i.dims),...Et(u)),K.push(E)):B.push(...Et(t.dims),...Et(u));let re=[{name:"output_size",type:"u32"},{name:"past_seqlen",type:"u32"},{name:"new_seqlen",type:"u32"},{name:"present_seqlen",type:"u32"}],oe=` let past_batch_stride = uniforms.past_seqlen * num_heads * H; + var past_head_stride = uniforms.past_seqlen * H; + if (is_bsnh) { + past_head_stride = H; + } + let in_offset = b * past_batch_stride + s * row_stride + n * past_head_stride + h; + present_kv[out_offset] = past_kv[in_offset];`,ee=` let new_batch_stride = uniforms.new_seqlen * num_heads * H; + let new_row_stride = num_heads * H; + let new_head_stride = H; + let in_offset = b * new_batch_stride + (s - past_seqlen) * new_row_stride + n * new_head_stride + h; + present_kv[out_offset] = new_kv[in_offset];`,_e=i?`if (s < past_seqlen) { + ${oe} + } else if (s < past_seqlen + uniforms.new_seqlen) { + ${ee} + }`:`if (s < past_seqlen + uniforms.new_seqlen) { + ${ee} + }`,ae=ge=>` + + ${ge.registerUniforms(re).declareVariables(...K,g)} + ${ge.mainStart([$,a.kvNumHeads,1])} + ${ge.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + var indices = ${g.offsetToIndices("global_idx")}; + let h = local_id.x; + let n = local_id.y; + let s = workgroup_id.x; + let b = workgroup_id.y; + let num_heads = ${a.kvNumHeads}u; + let H = ${$}u; + + let present_seqlen = uniforms.present_seqlen; + let present_batch_stride = present_seqlen * num_heads * H; + var row_stride = H; + let is_bsnh = ${a.isPastkvBSNH}; + + if (is_bsnh) { + row_stride = num_heads * H; + } + var present_head_stride = present_seqlen * H; + if (is_bsnh) { + present_head_stride = H; + } + + let past_seqlen = uniforms.past_seqlen; + + let out_offset = b * present_batch_stride + s * row_stride + n * present_head_stride + h; + ${_e} + }`;return{name:"ConcatPastNew",shaderCache:{hint:`${a.kvNumHeads}${$}${!!i}`,inputDependencies:R},getRunData:()=>({outputs:[{dims:u,dataType:s}],dispatchGroup:h,programUniforms:B}),getShaderSource:ae}},Bc=t=>Gt({...t}),Rc=Gt({perm:[0,2,1,3]}),gl=(t,i,s,a,u)=>{let c=i,d=a.kvNumHeads,m=a.nReps;return i.dims.length===3&&a.kvSequenceLength!==0&&(c=i.reshape([a.batchSize,a.kvSequenceLength,d,a.headSize])),s?c=t.compute(ml(c,s,c.dataType,a),{inputs:[c,s],outputs:[a.isPastkvBSNH?u:-1]})[0]:c=t.compute(ml(c,void 0,c.dataType,a),{inputs:[c],outputs:[a.isPastkvBSNH?u:-1]})[0],m!==1&&(c=t.compute(hl([c],[1,1,1,m]),{inputs:[c],outputs:[-1]})[0],c=c.reshape([a.batchSize,a.totalSequenceLength,d*m,a.headSize])),t.compute(li(c,Rc.perm),{inputs:[c],outputs:[-1]})[0]},Nc=(t,i)=>{var g;let s=Lc(t.inputs,i);if(t.inputs[0].dims.length===5)throw new Error("Packed QKV is not implemented");if(((g=t.inputs[1])==null?void 0:g.dims.length)===5)throw new Error("Packed KV is not implemented");let a=Go(t,s.batchSize,s.numHeads,s.sequenceLength,s.headSize,t.inputs[0],void 0,0),u=t.inputs[3]&&t.inputs[3].dims.length!==0?t.inputs[3]:void 0,c=t.inputs[4]&&t.inputs[4].dims.length!==0?t.inputs[4]:void 0,d=gl(t,t.inputs[1],u,s,1),m=gl(t,t.inputs[2],c,s,2);ho(t,a,d,m,void 0,void 0,void 0,void 0,void 0,s,i)}}),jc,Vc,Uc,Wc,em=M(()=>{Xt(),Yt(),sn(),jc=(t,i)=>{let s=t[0].dims,a=s,u=2,c=Ve.sizeToDimension(s,u),d=Ve.sizeFromDimension(s,u),m=wn(d),g=d/m,y=[s[0],s[1],g],E=["rank","type","type"],$=[{type:12,data:d},{type:12,data:g}];$.push(...Et(y,y));let h=R=>{let B=it("x",t[0].dataType,y.length,m),K=it("scale",t[1].dataType,t[1].dims),re=it("bias",t[2].dataType,t[2].dims),oe=Ut("output",t[0].dataType,y.length,m),ee=[B,K,re,oe],_e=B.type.value,ae=m===1?"f32":`vec${m}`,ge=64,Qe=[{name:"normSize",type:"u32"},{name:"normPackedSize",type:"u32"}];return` + var meanShared : f32; + var squaredNormShared : f32; + var workgroupShared : array<${ae}, ${ge}>; + const workgroupSize = ${ge}u; + ${R.registerUniforms(Qe).declareVariables(...ee)} + ${R.mainStart(ge)} + let norm = global_idx / workgroupSize; + let batch = norm / uniforms.x_shape[1]; + let channel = norm % uniforms.x_shape[1]; + let localIndex = local_id.x; + + // initialize workgroup memory + var initial = ${ae}(0); + for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) { + initial = initial + ${ae}(${B.get("batch","channel","h")}); + } + workgroupShared[localIndex] = initial; + workgroupBarrier(); + + // Calculate the mean of current channel data. + for (var currSize = workgroupSize >> 1; currSize > 0; currSize = currSize >> 1) { + if (localIndex < currSize) { + workgroupShared[localIndex] = workgroupShared[localIndex] + workgroupShared[localIndex + currSize]; + } + workgroupBarrier(); + } + if (localIndex == 0) { + meanShared = ${Dr("workgroupShared[0]",m)} / f32(uniforms.normSize); + } + workgroupBarrier(); + + // reinitialize workgroup memory. + initial = ${ae}(0); + for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) { + let deviation = ${ae}(${B.get("batch","channel","h")}) - ${ae}(meanShared); + initial = initial + deviation * deviation; + } + workgroupShared[localIndex] = initial; + workgroupBarrier(); + + // Calculate the sum of square of deviation of current channel data. + for (var currSize = workgroupSize >> 1; currSize > 0; currSize = currSize >> 1) { + if (localIndex < currSize) { + workgroupShared[localIndex] = workgroupShared[localIndex] + workgroupShared[localIndex + currSize]; + } + workgroupBarrier(); + } + if (localIndex == 0) { + squaredNormShared = ${Dr("workgroupShared[0]",m)}; + } + workgroupBarrier(); + + let invStdDev = inverseSqrt(squaredNormShared / f32(uniforms.normSize) + f32(${i.epsilon})); + let channelScale = invStdDev * f32(${K.getByOffset("channel")}); + let channelShift = f32(${re.getByOffset("channel")}) - meanShared * channelScale; + for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) { + let value = ${B.get("batch","channel","h")} * ${_e}(${ae}(channelScale)) + ${_e}(${ae}(channelShift)); + ${oe.set("batch","channel","h","value")}; + } + }`};return{name:"InstanceNormalization",shaderCache:{hint:`${i.epsilon};${m}`,inputDependencies:E},getRunData:()=>({outputs:[{dims:a,dataType:t[0].dataType}],dispatchGroup:{x:c},programUniforms:$}),getShaderSource:h}},Vc=(t,i,s,a,u,c,d,m)=>{let g=wn(d),y=64,E=g===1?"vec2f":`mat2x${g}f`,$=g===1?"f32":`vec${g}f`,h=(Qe,ze)=>`${E}(${Qe}, ${ze})`,R=u*d/g,B=Math.ceil(c/y),K=["type"],re=[{type:12,data:B},{type:12,data:c},{type:12,data:Math.floor(d/g)},{type:12,data:Math.floor(c*d/g)}],oe=Qe=>{let ze=it("input",i.dataType,i.dims,g);return` + ${Qe.declareVariables(ze)} + @group(0) @binding(1) var output : array<${E}>; + struct Uniforms {wg_size:u32, H:u32, C:u32, image_size:u32}; + @group(0) @binding(2) var uniforms: Uniforms; + + ${Qe.mainStart(y)} + let currentImageNumber = global_idx / ${y} / uniforms.C; + let currentChannelNumber = (global_idx / ${y}) % uniforms.C; + let wgOffset = local_id.x * uniforms.wg_size; + if (wgOffset >= uniforms.H) { + return; + } + let wgMax = min(wgOffset + uniforms.wg_size, uniforms.H); + + let offset = currentImageNumber * uniforms.image_size + currentChannelNumber; + var sum = ${zn("f32",g)}; + var squaredSum = ${zn("f32",g)}; + for (var i: u32 = wgOffset; i < wgMax; i++) { + let value = ${$}(input[offset + i * uniforms.C]); + sum += value; + squaredSum += value * value; + } + output[global_idx] = ${h("sum","squaredSum")}; + }`},ee=t.compute({name:"InstanceNormComputeMean",shaderCache:{hint:`${g}`,inputDependencies:K},getRunData:()=>({outputs:[{dims:[u,d,y,2],dataType:1}],dispatchGroup:{x:u*d/g},programUniforms:re}),getShaderSource:oe},{inputs:[i],outputs:[-1]})[0],_e=[{type:12,data:R},{type:12,data:c},{type:12,data:Math.floor(d/g)},{type:12,data:Math.floor(y*d/g)}],ae=["type","type","type"],ge=Qe=>{let ze=it("scale",s.dataType,s.dims,g),ht=it("bias",a.dataType,a.dims,g);return` + @group(0) @binding(0) var input : array<${E}>; + @group(0) @binding(1) var scale : array<${ze.type.storage}>; + @group(0) @binding(2) var bias : array<${ht.type.storage}>; + @group(0) @binding(3) var output : array<${E}>; + struct Uniforms {units_of_work : u32, H: u32, C : u32, image_size : u32}; + @group(0) @binding(4) var uniforms: Uniforms; + + ${Qe.mainStart()} + ${Qe.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.units_of_work")} + let currentImageNumber = global_idx / uniforms.C; + let currentChannelNumber = global_idx % uniforms.C; + + let offset = currentImageNumber * uniforms.image_size; + var sum = ${zn("f32",g)}; + var squaredSum = ${zn("f32",g)}; + for (var i: u32 = 0; i < min(${y}, uniforms.H); i++) { + let value = input[offset + i + currentChannelNumber * ${y}]; + sum += value[0]; + squaredSum += value[1]; + } + sum = sum / f32(uniforms.H); + squaredSum = squaredSum / f32(uniforms.H); + let invStdDev = inverseSqrt(squaredSum - sum * sum + f32(${m})); + let channelScale = invStdDev * ${$}(scale[currentChannelNumber]); + let channelShift = ${$}(bias[currentChannelNumber]) - sum * channelScale; + + output[global_idx] = ${h("channelScale","channelShift")}; + }`};return t.compute({name:"InstanceNormComputeChannelScaleShift",shaderCache:{hint:`${g};${m}`,inputDependencies:ae},getRunData:()=>({outputs:[{dims:[u,d,2],dataType:1}],dispatchGroup:{x:Math.ceil(R/64)},programUniforms:_e}),getShaderSource:ge},{inputs:[ee,s,a],outputs:[-1]})[0]},Uc=(t,i,s)=>{let a=i[0].dims,u=a,c=a[0],d=a[a.length-1],m=Ve.sizeFromDimension(a,1)/d,g=wn(d),y=Ve.size(u)/g,E=[{type:12,data:m},{type:12,data:Math.floor(d/g)}],$=["type","type"],h=Vc(t,i[0],i[1],i[2],c,m,d,s.epsilon),R=B=>{let K=Tn(i[0].dataType),re=g===1?"vec2f":`mat2x${g}f`,oe=g===1?K:`vec${g}<${K}>`,ee=it("input",i[0].dataType,i[0].dims,g),_e=Ut("output",i[0].dataType,u,g);return` + @group(0) @binding(0) var input : array<${ee.type.storage}>; + @group(0) @binding(1) var scaleInput : array<${re}>; + @group(0) @binding(2) var output : array<${_e.type.storage}>; + struct Uniforms {H: u32, C : u32}; + @group(0) @binding(3) var uniforms: Uniforms; + + ${B.mainStart()} + let currentImageNumber = global_idx / (uniforms.C * uniforms.H); + let currentChannelNumber = global_idx % uniforms.C; + + let scaleOffset = currentImageNumber * uniforms.C + currentChannelNumber; + let scale = scaleInput[scaleOffset]; + output[global_idx] = fma(input[global_idx], ${oe}(scale[0]), ${oe}(scale[1])); + }`};t.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${g}`,inputDependencies:$},getRunData:()=>({outputs:[{dims:u,dataType:i[0].dataType}],dispatchGroup:{x:Math.ceil(y/64)},programUniforms:E}),getShaderSource:R},{inputs:[i[0],h]})},Wc=(t,i)=>{i.format==="NHWC"?Uc(t,t.inputs,i):t.compute(jc(t.inputs,i))}}),dn,Gc,ar,hr=M(()=>{Xt(),Yt(),sn(),dn=t=>{if(!t||t.length<2)throw new Error("layerNorm requires at least 2 inputs.")},Gc=(t,i,s)=>{let a=i.simplified,u=t[0].dims,c=t[1],d=!a&&t[2],m=u,g=Ve.normalizeAxis(i.axis,u.length),y=Ve.sizeToDimension(u,g),E=Ve.sizeFromDimension(u,g),$=Ve.size(c.dims),h=d?Ve.size(d.dims):0;if($!==E||d&&h!==E)throw new Error(`Size of X.shape()[axis:] == ${E}. + Size of scale and bias (if provided) must match this. + Got scale size of ${$} and bias size of ${h}`);let R=[];for(let ge=0;ge1,ee=s>2,_e=ge=>{let Qe=Tn(t[0].dataType),ze=[it("x",t[0].dataType,t[0].dims,B),it("scale",c.dataType,c.dims,B)];d&&ze.push(it("bias",d.dataType,d.dims,B)),ze.push(Ut("output",t[0].dataType,m,B)),oe&&ze.push(Ut("mean_data_output",1,R)),ee&&ze.push(Ut("inv_std_output",1,R));let ht=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return` + ${ge.registerUniforms(ht).declareVariables(...ze)} + ${ge.mainStart()} + ${ge.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")} + let offset = global_idx * uniforms.norm_size_vectorized; + var mean_vector = ${zn("f32",B)}; + var mean_square_vector = ${zn("f32",B)}; + + for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) { + let value = ${Un(Qe,B,"x[h + offset]")}; + mean_vector += value; + mean_square_vector += value * value; + } + let mean = ${Dr("mean_vector",B)} / uniforms.norm_size; + let inv_std_dev = inverseSqrt(${Dr("mean_square_vector",B)} / uniforms.norm_size ${a?"":"- mean * mean"} + uniforms.epsilon); + + for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) { + let f32input = ${Un(Qe,B,"x[j + offset]")}; + let f32scale = ${Un(Qe,B,"scale[j]")}; + output[j + offset] = ${ze[0].type.value}((f32input ${a?"":"- mean"}) * inv_std_dev * f32scale + ${d?`+ ${Un(Qe,B,"bias[j]")}`:""} + ); + } + + ${oe?"mean_data_output[global_idx] = mean":""}; + ${ee?"inv_std_output[global_idx] = inv_std_dev":""}; + }`},ae=[{dims:m,dataType:t[0].dataType}];return oe&&ae.push({dims:R,dataType:1}),ee&&ae.push({dims:R,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${B};${s};${a}`,inputDependencies:K},getRunData:()=>({outputs:ae,dispatchGroup:{x:Math.ceil(y/64)},programUniforms:re}),getShaderSource:_e}},ar=(t,i)=>{dn(t.inputs),t.compute(Gc(t.inputs,i,t.outputCount))}}),mr,Xi,pf,qc,ff=M(()=>{Xt(),Yt(),mn(),sn(),mr=(t,i)=>{if(t.length<3||t.length>4)throw new Error("MatMulNBits requires 3 or 4 inputs");let s=t[0],a=s.dims.length;if(s.dims[a-1]!==i.k)throw new Error("The last dim of input shape does not match the k value");let u=Math.floor((i.k+i.blockSize-1)/i.blockSize),c=i.blockSize/8*i.bits,d=t[1];if(!Ve.areEqual(d.dims,[i.n,u,c]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let m=t[2].dims;if(Ve.size(m)!==i.n*u)throw new Error("scales input size error.");if(t.length===4){let g=t[3].dims,y=i.bits>4?i.n*u:i.n*Math.floor((u+1)/2);if(Ve.size(g)!==y)throw new Error("zeroPoints input size error.")}},Xi=(t,i,s,a)=>{let u=t[0].dims,c=u.length,d=Math.floor((i.k+i.blockSize-1)/i.blockSize),m=u[c-2],g=i.k,y=i.n,E=u.slice(0,c-2),$=Ve.size(E),h=i.blockSize/8*i.bits/4,R=t[0].dataType,B=wn(m),K=wn(i.k),re=wn(h),oe=wi(R,m*d),ee=Math.floor(a/oe),_e=d<=s[0]&&ee>0,ae=!_e||ee>=4?wn(y):ee>=2&&wn(y)>=2?2:1,ge=E.concat([m,y]),Qe=Ve.size(ge)/ae/B,ze=_e?[]:[{type:12,data:Qe},{type:12,data:i.blockSize}],ht=[$,m,g/K],Ft=Ve.convertShape(t[1].dims).slice();Ft.splice(-1,1,h/re),ze.push(...Et(ht)),ze.push(...Et(Ft)),ze.push(...Et(t[2].dims)),t.length===4&&ze.push(...Et(Ve.convertShape(t[3].dims)));let Dt=[$,m,y/ae];ze.push(...Et(Dt));let hn=ln=>{let rn=ht.length,yn=it("a",t[0].dataType,rn,K),Wn=it("b",12,Ft.length,re),kn=it("scales",t[2].dataType,t[2].dims.length),jn=[yn,Wn,kn],It=t.length===4?it("zero_points",12,t[3].dims.length):void 0;It&&jn.push(It);let tn=Dt.length,en=Ut("output",t[0].dataType,tn,ae),Ze=[{name:"output_size",type:"u32"},{name:"block_size",type:"u32"}],zt=Tn(t[0].dataType),on=(()=>{switch(K){case 1:return`array<${zt}, 8>`;case 2:return`mat4x2<${zt}>`;case 4:return`mat2x4<${zt}>`;default:throw new Error(`${K}-component is not supported.`)}})(),Gn=` + for (var word: u32 = 0; word < ${h}; word += ${re}) { + ${Wn.indicesSet("b_indices","2","word")}; + let b_data = ${Wn.getByIndices("b_indices")}; + for (var i: u32 = 0; i < ${re}; i++) { + let b_value: u32 = ${re===1?"b_data":"b_data[word + i]"}; + let b_mask: u32 = 0x0F0F0F0Fu; + let b_value_lower: vec4 = unpack4xU8(b_value & b_mask); + let b_value_upper: vec4 = unpack4xU8((b_value >> 4) & b_mask); + let b_quantized_values = ${on}(${Array.from({length:4},(yr,Hr)=>`${zt}(b_value_lower[${Hr}]), ${zt}(b_value_upper[${Hr}])`).join(", ")}); + let b_dequantized_values = ${K===1?`${on}(${Array.from({length:8},(yr,Hr)=>`(b_quantized_values[${Hr}] - zero_point) * scale`).join(", ")});`:`(b_quantized_values - ${on}(${Array(8).fill("zero_point").join(",")})) * scale;`}; + // Number of B elements per 32-bit word is 32/bits = 32/4 = 8 + for (var m: u32 = 0; m < ${_e?m:B}u; m++) { + ${yn.indicesSet("a_indices",rn-2,_e?"m":`row * ${B} + m`)}; + ${yn.indicesSet("a_indices",rn-1,"word_offset")}; + var input_offset = ${yn.indicesToOffset("a_indices")}; + var a_data: ${on}; + for (var j: u32 = 0; j < ${8/K}; j++) { + a_data[j] = ${yn.getByOffset("input_offset")}; + input_offset++; + } + ${_e?"workgroup_shared[workgroup_shared_offset + m]":"output_values[m]"}${ae>1?"[c]":""} += ${Array.from({length:8/K},(yr,Hr)=>`${K===1?`a_data[${Hr}] * b_dequantized_values[${Hr}]`:`dot(a_data[${Hr}], b_dequantized_values[${Hr}])`}`).join(" + ")}; + } + word_offset += ${8/K}; + } + }`,or=It?` + zero_point_offset += 4; + if (zero_point_offset == 32) { + zero_point_offset = 0; + zero_point_index++; + zero_point_word = ${It.getByOffset("zero_point_index")}; + }`:"";return _e?` + var workgroup_shared: array<${en.type.value}, ${m*d}>; + ${ln.declareVariables(...jn,en)} + ${ln.mainStart([d,1,1])} + var a_indices: ${yn.type.indices}; + var block = local_id.x; + var col = workgroup_id.y; + var batch = workgroup_id.z; + ${yn.indicesSet("a_indices","0","batch")}; + // Two zero points are packed into one byte when uniforms.bits is 4. + for (var c: u32 = 0; c < ${ae}; c++) { + let col_times_components_plus_c = col * ${ae} + c; + ${It?` + var zero_point_bytes_per_col: u32 = (${d} + 1) / 2; + var zero_point_byte_count: u32 = col_times_components_plus_c * zero_point_bytes_per_col + (block >> 0x1u); + var zero_point_word_index: u32 = zero_point_byte_count >> 0x2u; + var zero_point_byte_offset: u32 = zero_point_byte_count & 0x3u; + var zero_point_nibble_offset: u32 = block & 0x1u; + var zero_point_bits_offset: u32 = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2); + var zero_point_word: u32 = ${It.getByOffset("zero_point_word_index")} >> zero_point_bits_offset;`:""} + var b_indices: ${Wn.type.indices}; + ${Wn.indicesSet("b_indices","0","col_times_components_plus_c")}; + // The scale and zero points are computed per block. + var scales_index = col_times_components_plus_c * ${d} + block; + let scale = ${kn.getByOffset("scales_index")}; + // The default zero point is 8 for unsigned 4-bit quantization. + let zero_point = ${zt}(${It?"(zero_point_word) & 0xFu":8}); + ${Wn.indicesSet("b_indices","1","block")}; + var word_offset: u32 = block * ${i.blockSize/K}; + var workgroup_shared_offset: u32 = block * ${m}; + ${Gn} + } + workgroupBarrier(); + var output_indices: ${en.type.indices}; + var elements_per_thread: u32 = ${Math.ceil(m/d)}; + ${en.indicesSet("output_indices","0","batch")}; + ${en.indicesSet("output_indices",tn-1,"col")}; + ${en.indicesSet("output_indices",tn-2,"local_id.x * elements_per_thread")}; + var output_offset = ${en.indicesToOffset("output_indices")}; + for (var m: u32 = 0u; m < elements_per_thread; m++) { + var row = m + local_id.x * elements_per_thread; + if (row < ${m}) { + var output_value: ${en.type.value} = ${en.type.value}(0); + var workgroup_shared_offset: u32 = row; + for (var b: u32 = 0u; b < ${d}u; b++) { + output_value += workgroup_shared[workgroup_shared_offset]; + workgroup_shared_offset += ${m}; + } + ${en.setByOffset("output_offset","output_value")}; + output_offset += ${y/ae}; + } + } + }`:` + ${ln.registerUniforms(Ze).declareVariables(...jn,en)} + ${ln.mainStart()} + ${ln.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + var output_values: array<${en.type.value}, ${B}>; + var output_indices = ${en.offsetToIndices("global_idx")}; + var col = ${en.indicesGet("output_indices",tn-1)}; + var row = ${en.indicesGet("output_indices",tn-2)}; + var a_indices: ${yn.type.indices} = output_indices; + // Two zero points are packed into one byte because uniforms.bits <= 4. + // zero_point_offset is either 0 or 4. It is bit offset within one byte. + // TODO support zero_point_offset for bits > 4 + ${It?` + var zero_point_abs_offset = col * ${ae} * ((${d} + 1) / 2); + var zero_point_index: u32 = zero_point_abs_offset / 4; + var zero_point_word: u32 = ${It.getByOffset("zero_point_index")}; + var zero_point_offset: u32 = (zero_point_abs_offset % 4) * 8;`:""} + var scale_index = col * ${d*ae}; + var b_indices: ${Wn.type.indices}; + for (var c: u32 = 0; c < ${ae}; c++) { + ${Wn.indicesSet("b_indices","0",`col * ${ae} + c`)}; + var block_offset: u32 = 0; + for (var block: u32 = 0; block < ${d}; block++) { + // The scale and zero points are computed per block. + let scale = ${kn.getByOffset("scale_index")}; + // The default zero point is 8 for unsigned 4-bit quantization. + let zero_point = ${zt}(${It?"extractBits(zero_point_word, zero_point_offset, 4)":8}); + ${Wn.indicesSet("b_indices","1","block")}; + var word_offset: u32 = block_offset; + ${Gn} + scale_index++; + ${or} + block_offset += uniforms.block_size / ${K}; + } + // Drop the trailing 4 bits if the zero_poit_offset is not a byte boundary to align with the next byte. + ${It?`if (zero_point_offset % 8 > 0) { + ${or} + }`:""} + } + for (var k: u32 = 0u; k < ${B}u; k++) { + ${en.indicesSet("output_indices",tn-2,`${B} * row + k`)}; + ${en.setByIndices("output_indices","output_values[k]")} + } + }`};return{name:_e?"BlockwiseMatMulNBits":"MatMulNBits",shaderCache:{hint:`${i.cacheKey};${m};${R};${t.length}`,inputDependencies:Array(t.length).fill("rank")},getRunData:()=>({outputs:[{dims:ge,dataType:R}],name:_e?"BlockwiseMatMulNBits":"MatMulNBits",dispatchGroup:_e?{x:1,y:Math.ceil(y/ae),z:$}:{x:Math.ceil(Qe/64)},programUniforms:ze}),getShaderSource:hn}},pf=(t,i)=>{mr(t.inputs,i);let s=t.getMaxComputeWorkgroupSizes(),a=t.getMaxComputeWorkgroupStoragesize();t.compute(Xi(t.inputs,i,s,a))},qc=t=>Gt(t)}),x,k,U,ue,Ie,Re,at,kt,Wt,cn=M(()=>{Xt(),Yt(),sn(),x=t=>{if(!t||t.length<1)throw new Error("Too few inputs");if(t[0].dataType!==1&&t[0].dataType!==10)throw new Error("Input type must be float or float16.");if(t.length>=2){let i=t[0].dims.length*2===t[1].dims[0];if(t.length===4&&(i=t[3].dims[0]*2===t[1].dims[0]),!i)throw new Error("The pads should be a 1D tensor of shape [2 * input_rank] or [2 * num_axes].")}},k=(t,i,s)=>{let a="";for(let u=i-1;u>=0;--u)a+=` + k = i32(${t.indicesGet("indices",u)}) - ${Ot("uniforms.pads",u,s)}; + if (k < 0) { + break; + } + if (k >= i32(${Ot("uniforms.x_shape",u,i)})) { + break; + } + offset += k * i32(${Ot("uniforms.x_strides",u,i)}); + `;return` + value = ${t.type.value}(uniforms.constant_value); + for (var i = 0; i < 1; i++) { + var offset = 0; + var k = 0; + ${a} + value = x[offset]; + } + `},U=(t,i,s)=>{let a="";for(let u=i-1;u>=0;--u)a+=` + k = i32(${t.indicesGet("indices",u)}) - ${Ot("uniforms.pads",u,s)}; + if (k < 0) { + k = -k; + } + { + let _2n_1 = 2 * (i32(${Ot("uniforms.x_shape",u,i)}) - 1); + k = k % _2n_1; + if(k >= i32(${Ot("uniforms.x_shape",u,i)})) { + k = _2n_1 - k; + } + } + offset += k * i32(${Ot("uniforms.x_strides",u,i)}); + `;return` + var offset = 0; + var k = 0; + ${a} + value = x[offset]; + `},ue=(t,i,s)=>{let a="";for(let u=i-1;u>=0;--u)a+=` + k = i32(${t.indicesGet("indices",u)}) - ${Ot("uniforms.pads",u,s)}; + if (k < 0) { + k = 0; + } + if (k >= i32(${Ot("uniforms.x_shape",u,i)})) { + k = i32(${Ot("uniforms.x_shape",u,i)}) - 1; + } + offset += k * i32(${Ot("uniforms.x_strides",u,i)}); + `;return` + var offset = 0; + var k = 0; + ${a} + value = x[offset]; + `},Ie=(t,i,s)=>{let a="";for(let u=i-1;u>=0;--u)a+=` + k = i32(${t.indicesGet("indices",u)}) - ${Ot("uniforms.pads",u,s)}; + if (k < 0) { + k += i32(${Ot("uniforms.x_shape",u,i)}]); + } + if (k >= i32(${Ot("uniforms.x_shape",u,i)})) { + k -= i32(${Ot("uniforms.x_shape",u,i)}); + } + offset += k * i32(${Ot("uniforms.x_strides",u,i)}); + `;return` + var offset = 0; + var k = 0; + ${a} + value = x[offset]; + `},Re=(t,i,s)=>{switch(s.mode){case 0:return k(t,i,s.pads.length);case 1:return U(t,i,s.pads.length);case 2:return ue(t,i,s.pads.length);case 3:return Ie(t,i,s.pads.length);default:throw new Error("Invalid mode")}},at=(t,i)=>{let s=Ve.padShape(t[0].dims.slice(),i.pads),a=t[0].dims,u=Ve.size(s),c=[{type:12,data:u},{type:6,data:i.pads}];i.mode===0&&c.push({type:t[0].dataType,data:i.value}),c.push(...Et(t[0].dims,s));let d=["rank"],m=g=>{let y=Ut("output",t[0].dataType,s.length),E=it("x",t[0].dataType,a.length),$=E.type.value,h=Re(y,a.length,i),R=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:i.pads.length}];return i.mode===0&&R.push({name:"constant_value",type:$}),` + ${g.registerUniforms(R).declareVariables(E,y)} + ${g.mainStart()} + ${g.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${y.offsetToIndices("global_idx")}; + + var value = ${$}(0); + ${h} + output[global_idx] = value; + }`};return{name:"Pad",shaderCache:{hint:`${i.mode}`,inputDependencies:d},getRunData:()=>({outputs:[{dims:s,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(Ve.size(s)/64)},programUniforms:c}),getShaderSource:m}},kt=(t,i)=>{if(t.length>1){let s=t[1].getBigInt64Array(),a=t.length>=3&&t[2].data?t[2].getFloat32Array()[0]:0,u=t[0].dims.length,c=new Int32Array(2*u).fill(0);if(t.length>=4){let m=t[3].getBigInt64Array();for(let g=0;gc[Number(g)]=Number(m));let d=[];return c.forEach(m=>d.push(m)),{mode:i.mode,value:a,pads:d}}else return i},Wt=(t,i)=>{x(t.inputs);let s=kt(t.inputs,i);t.compute(at(t.inputs,s),{inputs:[0]})}}),an,Pn,pn,_n,fn,gn,Mn,Dn,xr,Er,xi,gr,ir,_r,Rs,Ns,_l,tm,ui,qo=M(()=>{j(),Xt(),Yt(),sn(),an=t=>{if(z.webgpu.validateInputContent&&(!t||t.length!==1))throw new Error("Pool ops requires 1 input.")},Pn=(t,i,s)=>{let a=i.format==="NHWC",u=t.dims.slice();a&&u.splice(1,0,u.pop());let c=Object.hasOwnProperty.call(i,"dilations"),d=i.kernelShape.slice(),m=i.strides.slice(),g=c?i.dilations.slice():[],y=i.pads.slice();Vr.adjustPoolAttributes(s,u,d,m,g,y);let E=Vr.computePoolOutputShape(s,u,m,g,d,y,i.autoPad),$=Object.assign({},i);c?Object.assign($,{kernelShape:d,strides:m,pads:y,dilations:g,cacheKey:i.cacheKey}):Object.assign($,{kernelShape:d,strides:m,pads:y,cacheKey:i.cacheKey});let h=E.slice();return h.push(h.splice(1,1)[0]),[$,a?h:E]},pn=(t,i)=>{let s=i.format==="NHWC",a=Ve.size(t),u=Ve.size(i.kernelShape),c=[{type:12,data:a},{type:12,data:u}],d=[{name:"outputSize",type:"u32"},{name:"kernelSize",type:"u32"}];if(i.kernelShape.length<=2){let m=i.kernelShape[i.kernelShape.length-1],g=i.strides[i.strides.length-1],y=i.pads[i.pads.length/2-1],E=i.pads[i.pads.length-1],$=!!(y+E);c.push({type:12,data:m},{type:12,data:g},{type:12,data:y},{type:12,data:E}),d.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let h=!1;if(i.kernelShape.length===2){let R=i.kernelShape[i.kernelShape.length-2],B=i.strides[i.strides.length-2],K=i.pads[i.pads.length/2-2],re=i.pads[i.pads.length-2];h=!!(K+re),c.push({type:12,data:R},{type:12,data:B},{type:12,data:K},{type:12,data:re}),d.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[c,d,!0,$,h]}else{if(s)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let m=Ve.computeStrides(i.kernelShape);c.push({type:12,data:m},{type:12,data:i.pads},{type:12,data:i.strides}),d.push({name:"kernelStrides",type:"u32",length:m.length},{name:"pads",type:"u32",length:i.pads.length},{name:"strides",type:"u32",length:i.strides.length});let g=i.pads.reduce((y,E)=>y+E);return[c,d,!!g,!1,!1]}},_n=(t,i,s,a,u,c,d,m,g,y,E,$)=>{let h=u.format==="NHWC",R=i.type.value,B=Ut("output",i.type.tensor,a);if(u.kernelShape.length<=2){let K="",re="",oe="",ee=s-(h?2:1);if(E?K=` + for (var i: u32 = 0u; i < uniforms.kw; i++) { + xIndices[${ee}] = indices[${ee}] * uniforms.sw - uniforms.pwStart + i; + if (xIndices[${ee}] < 0 || xIndices[${ee}] + >= uniforms.x_shape[${ee}]) { + pad++; + continue; + } + let x_val = x[${i.indicesToOffset("xIndices")}]; + ${c} + }`:K=` + for (var i: u32 = 0u; i < uniforms.kw; i++) { + xIndices[${ee}] = indices[${ee}] * uniforms.sw - uniforms.pwStart + i; + let x_val = x[${i.indicesToOffset("xIndices")}]; + ${c} + }`,u.kernelShape.length===2){let _e=s-(h?3:2);$?re=` + for (var j: u32 = 0u; j < uniforms.kh; j++) { + xIndices[${_e}] = indices[${_e}] * uniforms.sh - uniforms.phStart + j; + if (xIndices[${_e}] < 0 || xIndices[${_e}] >= uniforms.x_shape[${_e}]) { + pad += i32(uniforms.kw); + continue; + } + `:re=` + for (var j: u32 = 0u; j < uniforms.kh; j++) { + xIndices[${_e}] = indices[${_e}] * uniforms.sh - uniforms.phStart + j; + `,oe=` + } + `}return` + ${t.registerUniforms(g).declareVariables(i,B)} + + ${t.mainStart()} + ${t.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + + let indices = ${B.offsetToIndices("global_idx")}; + var xIndices = ${B.offsetToIndices("global_idx")}; + + var value = ${R}(${m}); + var pad = 0; + ${re} + ${K} + ${oe} + ${d} + + output[global_idx] = value; + }`}else{if(h)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let K=u.kernelShape.length,re=u.pads.length,oe="";return y?oe=` + if (xIndices[j] >= uniforms.x_shape[j]) { + pad++; + isPad = true; + break; + } + } + if (!isPad) { + let x_val = x[${i.indicesToOffset("xIndices")}]; + ${c} + }`:oe=` + } + let x_val = x[${i.indicesToOffset("xIndices")}]; + ${c} + `,` + ${t.registerUniforms(g).declareVariables(i,B)} + + ${t.mainStart()} + ${t.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + let indices = ${B.offsetToIndices("global_idx")}; + var xIndices = ${B.offsetToIndices("global_idx")}; + + var offsets: array; + + var value = ${R}(${m}); + var pad = 0; + var isPad = false; + + for (var i: u32 = 0u; i < uniforms.kernelSize; i++) { + var offset = i; + for (var j = 0u; j < ${K-1}u; j++) { + offsets[j] = offset / ${Ot("uniforms.kernelStrides","j",K)}; + offset -= offsets[j] * ${Ot("uniforms.kernelStrides","j",K)}; + } + offsets[${K-1}] = offset; + + isPad = false; + for (var j = ${s-K}u; j < ${s}u; j++) { + xIndices[j] = indices[j] * ${Ot("uniforms.strides",`j - ${s-K}u`,K)} + + offsets[j - ${s-K}u] - ${Ot("uniforms.pads","j - 2u",re)}; + ${oe} + } + ${d} + + output[global_idx] = value; + }`}},fn=t=>`${t.format};${t.ceilMode};${t.autoPad};${t.kernelShape.length}`,gn=t=>`${fn(t)};${t.countIncludePad}`,Mn=t=>`${fn(t)};${t.storageOrder};${t.dilations}`,Dn=t=>({format:t.format,autoPad:["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][t.auto_pad],ceilMode:t.ceil_mode,kernelShape:t.kernel_shape,strides:t.strides,pads:t.pads}),xr=(t,i,s,a)=>{let[u,c]=Pn(i,a,s),d=it("x",i.dataType,i.dims.length),m=d.type.value,g="value += x_val;",y="";u.countIncludePad?y+=`value /= ${m}(uniforms.kernelSize);`:y+=`value /= ${m}(i32(uniforms.kernelSize) - pad);`;let[E,$,h,R,B]=pn(c,u);E.push(...Et(i.dims,c));let K=["rank"];return{name:t,shaderCache:{hint:`${a.cacheKey};${h};${R};${B}`,inputDependencies:K},getRunData:()=>({outputs:[{dims:c,dataType:i.dataType}],dispatchGroup:{x:Math.ceil(Ve.size(c)/64)},programUniforms:E}),getShaderSource:re=>_n(re,d,i.dims.length,c.length,u,g,y,0,$,h,R,B)}},Er=t=>{let i=t.count_include_pad!==0,s=Dn(t);if(s.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");let a={countIncludePad:i,...s,cacheKey:""};return{...a,cacheKey:gn(a)}},xi=(t,i)=>{an(t.inputs),t.compute(xr("AveragePool",t.inputs[0],!1,i))},gr={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},ir=t=>{let i=t.format;return{format:i,...gr,cacheKey:i}},_r=(t,i)=>{an(t.inputs),t.compute(xr("GlobalAveragePool",t.inputs[0],!0,i))},Rs=(t,i,s,a)=>{let[u,c]=Pn(i,a,s),d=` + value = max(x_val, value); + `,m="",g=it("x",i.dataType,i.dims.length),y=["rank"],[E,$,h,R,B]=pn(c,u);return E.push(...Et(i.dims,c)),{name:t,shaderCache:{hint:`${a.cacheKey};${h};${R};${B}`,inputDependencies:y},getRunData:()=>({outputs:[{dims:c,dataType:i.dataType}],dispatchGroup:{x:Math.ceil(Ve.size(c)/64)},programUniforms:E}),getShaderSource:K=>_n(K,g,i.dims.length,c.length,u,d,m,i.dataType===10?-65504:-1e5,$,h,R,B)}},Ns=(t,i)=>{an(t.inputs),t.compute(Rs("MaxPool",t.inputs[0],!1,i))},_l=t=>{let i=t.storage_order,s=t.dilations,a=Dn(t);if(i!==0)throw new Error("column major storage order is not yet supported for MaxPool");if(a.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");let u={storageOrder:i,dilations:s,...a,cacheKey:""};return{...u,cacheKey:Mn(u)}},tm=t=>{let i=t.format;return{format:i,...gr,cacheKey:i}},ui=(t,i)=>{an(t.inputs),t.compute(Rs("GlobalMaxPool",t.inputs[0],!0,i))}}),hf,mf,gf,Hc,nb=M(()=>{Xt(),Yt(),mn(),sn(),hf=(t,i)=>{if(t.length<2||t.length>3)throw new Error("DequantizeLinear requires 2 or 3 inputs.");if(t.length===3&&t[1].dims===t[2].dims)throw new Error("x-scale and x-zero-point must have the same shape.");if(t.length===3&&t[0].dataType!==t[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(t[0].dataType===6&&t.length>2)throw new Error("In the case of dequantizing int32 there is no zero point.");if(t[1].dims.length!==0&&t[1].dims.length!==1&&t[1].dims.length!==t[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(t.length>2){if(t[0].dataType!==t[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(t[1].dims.length!==t[2].dims.length)throw new Error("scale and zero-point inputs must have the same rank.");if(!t[1].dims.map((s,a)=>s===t[2].dims[a]).reduce((s,a)=>s&&a,!0))throw new Error("scale and zero-point inputs must have the same shape.")}if(i.blockSize>0){if(t[1].dims.length===0||t[1].dims.length===1&&t[1].dims[0]===1)throw new Error("blockSize must be set only for block quantization.");if(!t[1].dims.map((u,c)=>c===i.axis||u===t[0].dims[c]).reduce((u,c)=>u&&c,!0))throw new Error("For block qunatization, scale input shape to match the input shape except for the axis");if(t[1].dims.length!==t[0].dims.length)throw new Error("For block qunatization the scale input rank must be the same as the x rank.");let s=t[0].dims[i.axis],a=t[1].dims[i.axis];if(i.blockSizeMath.ceil(s/(a-1)-1))throw new Error("blockSize must be with in the range [ceil(dI / Si), ceil(dI / (Si - 1) - 1)].")}},mf=(t,i)=>{let s=Ve.normalizeAxis(i.axis,t[0].dims.length),a=t[0].dataType,u=a===3,c=t[0].dims,d=t[1].dataType,m=Ve.size(c),g=a===3||a===2,y=g?[Math.ceil(Ve.size(t[0].dims)/4)]:t[0].dims,E=t[1].dims,$=t.length>2?t[2]:void 0,h=$?g?[Math.ceil(Ve.size($.dims)/4)]:$.dims:void 0,R=E.length===0||E.length===1&&E[0]===1,B=R===!1&&E.length===1,K=wn(m),re=R&&(!g||K===4),oe=re?K:1,ee=re&&!g?K:1,_e=it("input",g?12:a,y.length,ee),ae=it("scale",d,E.length),ge=$?it("zero_point",g?12:a,h.length):void 0,Qe=Ut("output",d,c.length,oe),ze=[_e,ae];ge&&ze.push(ge);let ht=[y,E];$&&ht.push(h);let Ft=[{type:12,data:m/oe},{type:12,data:s},{type:12,data:i.blockSize},...Et(...ht,c)],Dt=hn=>{let ln=[{name:"output_size",type:"u32"},{name:"axis",type:"u32"},{name:"block_size",type:"u32"}];return` + ${hn.registerUniforms(ln).declareVariables(...ze,Qe)} + ${hn.mainStart()} + ${hn.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let output_indices = ${Qe.offsetToIndices("global_idx")}; + + // Set input x + ${g?` + let input = ${_e.getByOffset("global_idx / 4")}; + let x_vec = ${u?"unpack4xI8(input)":"unpack4xU8(input)"}; + let x_value = ${oe===1?"x_vec[global_idx % 4]":"x_vec"};`:`let x_value = ${_e.getByOffset("global_idx")};`}; + + // Set scale input + ${R?`let scale_value= ${ae.getByOffset("0")}`:B?` + let scale_index = ${Qe.indicesGet("output_indices","uniforms.axis")}; + let scale_value= ${ae.getByOffset("scale_index")};`:` + var scale_indices: ${ae.type.indices} = output_indices; + let index = ${ae.indicesGet("scale_indices","uniforms.axis")} / uniforms.block_size; + ${ae.indicesSet("scale_indices","uniforms.axis","index")}; + let scale_value= ${ae.getByIndices("scale_indices")};`}; + + // Set zero-point input + ${ge?R?g?` + let zero_point_input = ${ge.getByOffset("0")}; + let zero_point_vec = ${u?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; + let zero_point_value= zero_point_vec[0]`:`let zero_point_value = ${ge.getByOffset("0")}`:B?g?` + let zero_point_index = ${Qe.indicesGet("output_indices","uniforms.axis")}; + let zero_point_input = ${ge.getByOffset("zero_point_index / 4")}; + let zero_point_vec = ${u?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; + let zero_point_value = zero_point_vec[zero_point_index % 4]`:` + let zero_point_index = ${Qe.indicesGet("output_indices","uniforms.axis")}; + let zero_point_value = ${ge.getByOffset("zero_point_index")};`:g?` + let zero_point_offset = ${ae.indicesToOffset("scale_indices")}; + let zero_point_input = ${ge.getByOffset("zero_point_offset / 4")}; + let zero_point_vec = ${u?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; + let zero_point_value = zero_point_vec[zero_point_offset % 4];`:`let zero_point_value = ${ge.getByIndices("scale_indices")};`:`let zero_point_value = ${g?u?"i32":"u32":_e.type.value}(0);`}; + // Compute and write output + ${Qe.setByOffset("global_idx",`${Qe.type.value}(x_value - zero_point_value) * scale_value`)}; + }`};return{name:"DequantizeLinear",shaderCache:{hint:i.cacheKey,inputDependencies:ge?["rank","rank","rank"]:["rank","rank"]},getShaderSource:Dt,getRunData:()=>({outputs:[{dims:c,dataType:d}],dispatchGroup:{x:Math.ceil(m/oe/64),y:1,z:1},programUniforms:Ft})}},gf=(t,i)=>{hf(t.inputs,i),t.compute(mf(t.inputs,i))},Hc=t=>Gt({axis:t.axis,blockSize:t.blockSize})}),K_,Q_,X_,rb=M(()=>{j(),Xt(),sn(),K_=(t,i,s)=>{let a=t===i,u=ti&&s>0;if(a||u||c)throw new Error("Range these inputs' contents are invalid.")},Q_=(t,i,s,a)=>{let u=Math.abs(Math.ceil((i-t)/s)),c=[u],d=u,m=[{type:12,data:d},{type:a,data:t},{type:a,data:s},...Et(c)],g=y=>{let E=Ut("output",a,c.length),$=E.type.value,h=[{name:"outputSize",type:"u32"},{name:"start",type:$},{name:"delta",type:$}];return` + ${y.registerUniforms(h).declareVariables(E)} + ${y.mainStart()} + ${y.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + output[global_idx] = uniforms.start + ${$}(global_idx) * uniforms.delta; + }`};return{name:"Range",shaderCache:{hint:`${a}`},getShaderSource:g,getRunData:()=>({outputs:[{dims:c,dataType:a}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:m})}},X_=t=>{let i=0,s=0,a=0;t.inputs[0].dataType===6?(i=t.inputs[0].getInt32Array()[0],s=t.inputs[1].getInt32Array()[0],a=t.inputs[2].getInt32Array()[0]):t.inputs[0].dataType===1&&(i=t.inputs[0].getFloat32Array()[0],s=t.inputs[1].getFloat32Array()[0],a=t.inputs[2].getFloat32Array()[0]),z.webgpu.validateInputContent&&K_(i,s,a),t.compute(Q_(i,s,a,t.inputs[0].dataType),{inputs:[]})}}),Y_,Z_,J_,ey,ty,ny,ry,iy,oy,sy,ay,nm,ly,uy,dy,cy,py,fy,hy,ib=M(()=>{Xt(),Yt(),mn(),sn(),Y_=(t,i)=>{if(t.every(s=>s>0||(()=>{throw new Error("Resize requires scales input values to be positive")})),t.length>0){if(i.mode==="linear"){if(!(t.length===2||t.length===3||t.length===4&&t[0]===1&&t[1]===1||t.length===4&&t[0]===1&&t[3]===1||t.length===5&&t[0]===1&&t[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(i.mode==="cubic"&&!(t.length===2||t.length===4&&t[0]===1&&t[1]===1||t.length===4&&t[0]===1&&t[3]===1))throw new Error("Resize requires scales input size to be 2 or 4 for cubic mode")}},Z_=(t,i,s)=>{i.every(u=>u>=0&&u{throw new Error("Resize requires axes input values to be positive and less than rank")}));let a=new Array(s).fill(1);return i.forEach((u,c)=>a[u]=t[c]),a},J_=(t,i,s,a,u,c)=>{let[d,m,g]=s>10?[1,2,3]:[-1,t.length>1?1:-1,-1],y=t[0].dims.length;if(d>0&&t.length>d&&t[d].dims.length>0)t[d].getFloat32Array().forEach(E=>c.push(E));else if(i.coordinateTransformMode==="tf_crop_and_resize")throw new Error("Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize");if(m>0&&t.length>m&&t[m].dims.length>0){if(t[m].getFloat32Array().forEach(E=>a.push(E)),a.length!==0&&a.length!==y&&s>=18&&a.length!==i.axes.length)throw new Error("Resize requires scales input size to be same as input rank or axes size for opset 18 and up");Y_(a,i),i.axes.length>0&&Z_(a,i.axes,y).forEach((E,$)=>a[$]=E)}if(g>0&&t.length>g&&(t[g].getBigInt64Array().forEach(E=>u.push(Number(E))),u.length!==y||s>=18&&u.length===i.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(i.axes.length>0){if(a.length!==i.axes.length)throw new Error('Resize requires "scales" input size to be of axes rank when axes attributes is specified');if(u.length!==i.axes.length)throw new Error('Resize requires "sizes" input size to be of rank axes rank when axes attributes is specified')}if(typeof a<"u"&&typeof u<"u"&&a.length>0&&u.length>y)throw new Error("Resize requires only of scales or sizes to be specified")},ey=(t,i)=>`fn getOriginalCoordinateFromResizedCoordinate(xResized: u32, xScale: f32, lengthResized: u32, + lengthOriginal: u32, roiStart: f32, roiEnd: f32) -> ${i} { `+(()=>{switch(t){case"asymmetric":return`return ${i}(xResized) / ${i}(xScale);`;case"pytorch_half_pixel":return`if (lengthResized > 1) { + return (${i}(xResized) + 0.5) / ${i}(xScale) - 0.5; + } else { + return 0.0; + }`;case"tf_half_pixel_for_nn":return`return (${i}(xResized) + 0.5) / ${i}(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 = ${i}(xResized * (lengthOriginal - 1) / (lengthResized - 1)); + let fract = + ${i}(xResized * (lengthOriginal - 1) % (lengthResized - 1)) / ${i}(lengthResized - 1); + return whole + fract; + }`;case"tf_crop_and_resize":return`if (lengthResized > 1) { + return ${i}(roiStart) * ${i}(lengthOriginal - 1) + + (${i}(xResized) * ${i}(roiEnd - roiStart) * ${i}(lengthOriginal - 1)) / + ${i}(lengthResized - 1); + } else { + return 0.5 * ${i}(roiStart + roiEnd) * ${i}(lengthOriginal - 1); + }`;case"half_pixel_symmetric":return`const outputWidth = ${i}xScale * ${i}(lengthResized); + const adjustment = ${i}(lengthResized) / outputWidth; + const center = ${i}(lengthOriginal) / 2; + const offset = center * (1 - adjustment); + return offset + ((${i}(xResized) + 0.5) / ${i}(xScale)) - 0.5;`;case"half_pixel":return`return ((${i}(xResized) + 0.5) / ${i}(xScale)) - 0.5;`;default:throw new Error(`Coordinate transform mode ${t} is not supported`)}})()+"}",ty=(t,i,s)=>`fn getNearestPixelFromOriginal(xOriginal: ${s}, isDownSample: bool) -> ${s} {`+(()=>{switch(t){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(i<11)return"if (isDownSample) { return ceil(xOriginal); } else { return xOriginal; }";throw new Error(`Nearest mode ${t} is not supported`)}})()+"}",ny=(t,i,s)=>{let a=new Array(s).fill(0).concat(new Array(s).fill(1)),u=t.length===0?a:t.slice();return i.length>0?(i.forEach((c,d)=>{a[c]=u[d],a[d+s]=u[i.length+d]}),a):u},ry=(t,i,s,a)=>{let u=[];if(s.length>0)if(a.length>0){if(t.forEach(c=>u.push(c)),Math.max(...a)>t.length)throw new Error("axes is out of bound");a.forEach((c,d)=>u[c]=s[d])}else s.forEach(c=>u.push(c));else{if(i.length===0)throw new Error("Resize requires either scales or sizes.");u=t.map((c,d)=>Math.round(c*i[d]))}return u},iy=(t,i,s)=>{let a=(()=>{switch(s.keepAspectRatioPolicy){case"not_larger":return s.axes.length>0?Math.min(...s.axes.map(c=>i[c]),Number.MAX_VALUE):Math.min(...i,Number.MAX_VALUE);case"not_smaller":return s.axes.length>0?Math.max(...s.axes.map(c=>i[c]),Number.MIN_VALUE):Math.max(...i,Number.MIN_VALUE);default:throw new Error(`Keep aspect ratio policy ${s.keepAspectRatioPolicy} is not supported`)}})();i.fill(1,0,i.length);let u=t.slice();return s.axes.length>0?(s.axes.forEach(c=>i[c]=a),s.axes.forEach(c=>u[c]=Math.round(t[c]*i[c]))):(i.fill(a,0,i.length),u.forEach((c,d)=>u[d]=Math.round(c*i[d]))),u},oy=(t,i,s,a,u)=>` + fn calculateOriginalIndicesFromOutputIndices(output_indices: ${t.type.indices}) -> array<${t.type.value}, ${s.length}> { + var original_indices: array<${t.type.value}, ${s.length}>; + for (var i:u32 = 0; i < ${s.length}; i++) { + var output_index = ${t.indicesGet("output_indices","i")}; + var scale = ${Ot("uniforms.scales","i",a)}; + var roi_low = ${Ot("uniforms.roi","i",u)}; + var roi_hi = ${Ot("uniforms.roi",`i + ${i.length}`,u)}; + if (scale == 1.0) { + original_indices[i] = ${t.type.value}(output_index); + } else { + var input_shape_i = ${Ot("uniforms.input_shape","i",i.length)}; + var output_shape_i = ${Ot("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; + }`,sy=(t,i,s,a,u,c,d)=>` + fn calculateInputIndicesFromOutputIndices(output_indices: ${i.type.indices}) -> ${t.type.indices} { + var input_indices: ${t.type.indices}; + for (var i:u32 = 0; i < ${a.length}; i++) { + var output_index = ${i.indicesGet("output_indices","i")}; + var input_index: u32; + var scale = ${Ot("uniforms.scales","i",u)}; + if (scale == 1.0) { + input_index = output_index; + } else { + var roi_low = ${Ot("uniforms.roi","i",c)}; + var roi_hi = ${Ot("uniforms.roi",`i + ${s.length}`,c)}; + var input_shape_i = ${Ot("uniforms.input_shape","i",s.length)}; + var output_shape_i = ${Ot("uniforms.output_shape","i",a.length)}; + var original_idx = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, + input_shape_i, roi_low, roi_hi); + if (!${d} || (original_idx >= 0 && original_idx < ${i.type.value}(input_shape_i))) { + if (original_idx < 0) { + input_index = 0; + } else if (original_idx > ${i.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); + } + } + ${t.indicesSet("input_indices","i"," input_index")} + } + return input_indices; + }`,ay=(t,i)=>` + fn checkInputIndices(input_indices: ${t.type.indices}) -> bool { + for (var i:u32 = 0; i < ${i.length}; i++) { + var input_index = ${t.indicesGet("input_indices","i")}; + if (input_index < 0 || input_index >= ${Ot("uniforms.input_shape","i",i.length)}) { + return false; + } + } + return true; + }`,nm=(t,i,s,a)=>t.rank>a?` + ${t.indicesSet("input_indices",i,"channel")}; + ${t.indicesSet("input_indices",s,"batch")}; +`:"",ly=(t,i,s,a,u)=>{let[c,d,m,g]=s.length===2?[-1,0,1,-1]:[0,2,3,1],y=t.type.value;return` + fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${y} { + var input_indices: ${t.type.indices}; + ${t.indicesSet("input_indices",d,`max(0, min(row, ${s[d]} - 1))`)}; + ${t.indicesSet("input_indices",m,`max(0, min(col, ${s[m]} - 1))`)}; + ${nm(t,g,c,2)} + return ${t.getByIndices("input_indices")}; + } + + fn bilinearInterpolation(output_indices: ${i.type.indices}) -> ${y} { + var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); + var row:${y} = originalIndices[${d}]; + var col:${y} = originalIndices[${m}]; + ${a?`if (row < 0 || row > (${s[d]} - 1) || col < 0 || col > (${s[m]} - 1)) { + return ${u}; + }`:""}; + row = max(0, min(row, ${s[d]} - 1)); + col = max(0, min(col, ${s[m]} - 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[${g}])`:"0"}; + var batch: u32 = ${s.length>2?`u32(originalIndices[${c}])`:"0"}; + var x11: ${y} = getInputValue(batch, channel, row1, col1); + var x12: ${y} = getInputValue(batch, channel, row1, col2); + var x21: ${y} = getInputValue(batch, channel, row2, col1); + var x22: ${y} = getInputValue(batch, channel, row2, col2); + var dx1: ${y} = abs(row - ${y}(row1)); + var dx2: ${y} = abs(${y}(row2) - row); + var dy1: ${y} = abs(col - ${y}(col1)); + var dy2: ${y} = abs(${y}(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); + }`},uy=(t,i,s,a,u,c,d,m,g,y)=>{let E=s.length===2,[$,h]=E?[0,1]:[2,3],R=t.type.value,B=K=>{let re=K===$?"row":"col";return` + fn ${re}CubicInterpolation(input_indices: ${t.type.indices}, output_indices: ${i.type.indices}) -> ${R} { + var output_index = ${i.indicesGet("output_indices",K)}; + var originalIdx: ${R} = getOriginalCoordinateFromResizedCoordinate(output_index, ${u[K]}, + ${a[K]}, ${s[K]}, ${c[K]}, ${c[K]} + ${s.length}); + var fractOriginalIdx: ${R} = originalIdx - floor(originalIdx); + var coefs = getCubicInterpolationCoefs(fractOriginalIdx); + + if (${m} && (originalIdx < 0 || originalIdx > (${s[K]} - 1))) { + return ${g}; + } + var data: array<${R}, 4> = array<${R}, 4>(0.0, 0.0, 0.0, 0.0); + for (var i: i32 = -1; i < 3; i++) { + var ${re}: ${R} = originalIdx + ${R}(i); + if (${re} < 0 || ${re} >= ${s[K]}) { + ${y?`coefs[i + 1] = 0.0; + continue;`:m?`return ${g};`:`${re} = max(0, min(${re}, ${s[K]} - 1));`}; + } + var input_indices_copy: ${t.type.indices} = input_indices; + ${t.indicesSet("input_indices_copy",K,`u32(${re})`)}; + data[i + 1] = ${K===$?t.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"}; + } + return cubicInterpolation1D(data, coefs); + }`};return` + ${B($)}; + ${B(h)}; + fn getCubicInterpolationCoefs(s: ${R}) -> array<${R}, 4> { + var absS = abs(s); + var coeffs: array<${R}, 4> = array<${R}, 4>(0.0, 0.0, 0.0, 0.0); + var oneMinusAbsS: ${R} = 1.0 - absS; + var twoMinusAbsS: ${R} = 2.0 - absS; + var onePlusAbsS: ${R} = 1.0 + absS; + coeffs[0] = ((${d} * onePlusAbsS - 5 * ${d}) * onePlusAbsS + 8 * ${d}) * onePlusAbsS - 4 * ${d}; + coeffs[1] = ((${d} + 2) * absS - (${d} + 3)) * absS * absS + 1; + coeffs[2] = ((${d} + 2) * oneMinusAbsS - (${d} + 3)) * oneMinusAbsS * oneMinusAbsS + 1; + coeffs[3] = ((${d} * twoMinusAbsS - 5 * ${d}) * twoMinusAbsS + 8 * ${d}) * twoMinusAbsS - 4 * ${d}; + return coeffs; + } + + fn cubicInterpolation1D(x: array<${R}, 4>, coefs: array<${R}, 4>) -> ${R} { + var coefsSum: ${R} = 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: ${i.type.indices}) -> ${R} { + var input_indices: ${t.type.indices} = output_indices; + return colCubicInterpolation(input_indices, output_indices); + } + `},dy=(t,i,s,a,u)=>{let[c,d,m,g,y]=s.length===3?[-1,0,1,2,-1]:[0,2,3,4,1],E=t.type.value;return` + fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${E} { + var input_indices: ${t.type.indices}; + ${t.indicesSet("input_indices",d,`max(0, min(depth, ${s[d]} - 1))`)}; + ${t.indicesSet("input_indices",m,`max(0, min(height, ${s[m]} - 1))`)}; + ${t.indicesSet("input_indices",g,`max(0, min(width, ${s[g]} - 1))`)}; + ${nm(t,y,c,3)} + return ${t.getByIndices("input_indices")}; + } + + fn trilinearInterpolation(output_indices: ${i.type.indices}) -> ${E} { + var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); + var depth:${E} = originalIndices[${d}]; + var height:${E} = originalIndices[${m}]; + var width:${E} = originalIndices[${g}]; + ${a?`if (depth < 0 || depth > (${s[d]} - 1) || height < 0 || height > (${s[m]} - 1) || width < 0 || (width > ${s[g]} - 1)) { + return ${u}; + }`:""}; + + depth = max(0, min(depth, ${s[d]} - 1)); + height = max(0, min(height, ${s[m]} - 1)); + width = max(0, min(width, ${s[g]} - 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[${y}])`:"0"}; + var batch: u32 = ${s.length>3?`u32(originalIndices[${c}])`:"0"}; + + var x111: ${E} = getInputValue(batch, channel, depth1, height1, width1); + var x112: ${E} = getInputValue(batch, channel, depth1, height1, width2); + var x121: ${E} = getInputValue(batch, channel, depth1, height2, width1); + var x122: ${E} = getInputValue(batch, channel, depth1, height2, width2); + var x211: ${E} = getInputValue(batch, channel, depth2, height1, width1); + var x212: ${E} = getInputValue(batch, channel, depth2, height1, width2); + var x221: ${E} = getInputValue(batch, channel, depth2, height2, width1); + var x222: ${E} = getInputValue(batch, channel, depth2, height2, width2); + var dx1: ${E} = abs(depth - ${E}(depth1)); + var dx2: ${E} = abs(${E}(depth2) - depth); + var dy1: ${E} = abs(height - ${E}(height1)); + var dy2: ${E} = abs(${E}(height2) - height); + var dz1: ${E} = abs(width - ${E}(width1)); + var dz2: ${E} = abs(${E}(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); + }`},cy=(t,i,s,a,u,c)=>{let d=t.dims,m=ny(c,i.axes,d.length),g=ry(d,a,u,i.axes),y=a.slice();a.length===0&&(y=d.map((ee,_e)=>ee===0?1:g[_e]/ee),i.keepAspectRatioPolicy!=="stretch"&&(g=iy(d,y,i)));let E=Ut("output",t.dataType,g.length),$=it("input",t.dataType,d.length),h=Ve.size(g),R=d.length===g.length&&d.every((ee,_e)=>ee===g[_e]),B=i.coordinateTransformMode==="tf_crop_and_resize",K=i.extrapolationValue,re=$.type.value,oe=ee=>` + ${R?"":` + ${ey(i.coordinateTransformMode,re)}; + ${(()=>{switch(i.mode){case"nearest":return` + ${ay($,d)}; + ${ty(i.nearestMode,s,re)}; + ${sy($,E,d,g,y.length,m.length,B)}; + `;case"linear":return` + ${oy(E,d,g,y.length,m.length)}; + ${(()=>{if(d.length===2||d.length===4)return`${ly($,E,d,B,K)}`;if(d.length===3||d.length===5)return`${dy($,E,d,B,K)}`;throw Error("Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.")})()}; + `;case"cubic":return` + ${(()=>{if(d.length===2||d.length===4)return`${uy($,E,d,g,y,m,i.cubicCoeffA,B,i.extrapolationValue,i.excludeOutside)}`;throw Error("Cubic mode only supports input dims 2 and 4 are supported in linear mode.")})()}; + `;default:throw Error("Invalid resize mode")}})()}; + `} + ${ee.registerUniform("output_size","u32").registerUniform("scales","f32",y.length).registerUniform("roi","f32",m.length).declareVariables($,E)} + ${ee.mainStart()} + ${ee.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + ${R?"output[global_idx] = input[global_idx];":` + let output_indices = ${E.offsetToIndices("global_idx")}; + var input_indices: ${$.type.indices}; + ${(()=>{switch(i.mode){case"nearest":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices); + if (checkInputIndices(input_indices)) { + output[global_idx] = ${$.getByIndices("input_indices")}; + } else { + output[global_idx] = ${i.extrapolationValue}; + }`;case"linear":return`output[global_idx] = ${d.length===2||d.length===4?"bilinearInterpolation":"trilinearInterpolation"}(output_indices);`;case"cubic":return"output[global_idx] = bicubicInterpolation(output_indices);";default:throw Error(`Unsupported resize mode: ${i.mode}`)}})()}; +`} + }`;return{name:"Resize",shaderCache:{hint:`${i.cacheKey}|${s}|${y.length>0?y:""}|${u.length>0?u:""}|${m.length>0?m:""}|${R}|${d}`,inputDependencies:["rank"]},getShaderSource:oe,getRunData:()=>({outputs:[{dims:g,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:[{type:12,data:h},{type:1,data:y},{type:1,data:m},...Et(d,g)]})}},py=t=>{let i=t.customDataBuffer;return new Uint32Array(i,i.byteOffset,1)[0]},fy=(t,i)=>{let s=[],a=[],u=[],c=py(t);if(i.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");J_(t.inputs,i,c,s,a,u),t.compute(cy(t.inputs[0],i,c,s,a,u),{inputs:[0]})},hy=t=>{let i=t.antialias,s=t.axes,a=t.coordinateTransformMode,u=t.cubicCoeffA,c=t.excludeOutside!==0,d=t.extrapolationValue,m=t.keepAspectRatioPolicy,g=t.mode,y=t.nearestMode===""?"simple":t.nearestMode;return Gt({antialias:i,axes:s,coordinateTransformMode:a,cubicCoeffA:u,excludeOutside:c,extrapolationValue:d,keepAspectRatioPolicy:m,mode:g,nearestMode:y})}}),my,gy,_y,ob=M(()=>{Xt(),Yt(),mn(),sn(),my=(t,i)=>{let[s,a,u,c]=t,{numHeads:d,rotaryEmbeddingDim:m}=i;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(!Ve.areEqual(a.dims,[])&&!Ve.areEqual(a.dims,[1])&&a.dims.length!==2)throw new Error(`Input 'position_ids' is expected to have 0, 1, or 2 dimensions, got ${a.dims.length}`);if(u.dims.length!==2)throw new Error(`Input 'cos_cache' is expected to have 2 dimensions, got ${u.dims.length}`);if(c.dims.length!==2)throw new Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${c.dims.length}`);if(!Ve.areEqual(u.dims,c.dims))throw new Error("Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape");if(m>0&&d===0)throw new Error("num_heads must be provided if rotary_embedding_dim is specified");let g=s.dims[0],y=s.dims[s.dims.length-2],E=u.dims[0],$=Ve.sizeFromDimension(s.dims,1)/y,h=m===0?u.dims[1]*2:$/d;if(m>h)throw new Error("rotary_embedding_dim must be less than or equal to head_size");if(a.dims.length===2){if(g!==a.dims[0])throw new Error(`Input 'position_ids' dimension 0 should be of size batch_size, got ${a.dims[0]}`);if(y!==a.dims[1])throw new Error(`Input 'position_ids' dimension 1 should be of size sequence_length, got ${a.dims[1]}`)}if(h/2!==u.dims[1]&&m/2!==u.dims[1])throw new Error(`Input 'cos_cache' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${u.dims[1]}`);if(y>E)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported")},gy=(t,i)=>{let{interleaved:s,numHeads:a,rotaryEmbeddingDim:u,scale:c}=i,d=t[0].dims[0],m=Ve.sizeFromDimension(t[0].dims,1),g=t[0].dims[t[0].dims.length-2],y=m/g,E=t[2].dims[1],$=u===0?E*2:y/a,h=new Array(d,g,y/$,$-E),R=Ve.computeStrides(h),B=[{type:1,data:c},{type:12,data:h},{type:12,data:R},...t[0].dims.length===3?new Array({type:12,data:[m,y,$,1]}):[],...t[0].dims.length===4?new Array({type:12,data:[m,$,g*$,1]}):[],...Et(t[0].dims,t[1].dims,t[2].dims,t[3].dims,t[0].dims)],K=re=>{let oe=it("input",t[0].dataType,t[0].dims.length),ee=it("position_ids",t[1].dataType,t[1].dims.length),_e=it("cos_cache",t[2].dataType,t[2].dims.length),ae=it("sin_cache",t[3].dataType,t[3].dims.length),ge=Ut("output",t[0].dataType,t[0].dims.length);return re.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:h.length},{name:"global_strides",type:"u32",length:R.length},{name:"input_output_strides",type:"u32",length:R.length}]),` + ${re.declareVariables(oe,ee,_e,ae,ge)} + + ${re.mainStart(Or)} + let half_rotary_emb_dim = uniforms.${_e.name}_shape[1]; + let bsnh = global_idx / uniforms.global_strides % uniforms.global_shape; + let size = uniforms.global_shape[0] * uniforms.global_strides[0]; + ${re.guardAgainstOutOfBoundsWorkgroupSizes("size")} + + if (bsnh[3] < half_rotary_emb_dim) { + let position_ids_idx = + ${ee.broadcastedIndicesToOffset("bsnh.xy",Ut("",ee.type.tensor,2))}; + let position_id = + u32(${ee.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 = ${oe.getByOffset("i")} * ${_e.get("position_id","bsnh[3]")} - + ${oe.getByOffset("j")} * ${ae.get("position_id","bsnh[3]")}; + ${ge.setByOffset("i","re")} + let im = ${oe.getByOffset("i")} * ${ae.get("position_id","bsnh[3]")} + + ${oe.getByOffset("j")} * ${_e.get("position_id","bsnh[3]")}; + ${ge.setByOffset("j","im")} + } else { + let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim; + ${ge.setByOffset("k",oe.getByOffset("k"))} + } + }`};return{name:"RotaryEmbedding",shaderCache:{hint:Gt({interleaved:s}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:K,getRunData:()=>({outputs:[{dims:t[0].dims,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(Ve.size(h)/Or)},programUniforms:B})}},_y=(t,i)=>{my(t.inputs,i),t.compute(gy(t.inputs,i))}}),yy,wy,vy,sb=M(()=>{Xt(),Yt(),sn(),yy=t=>{if(!t||t.length<3)throw new Error("layerNorm requires at least 3 inputs.");let i=t[0],s=t[1],a=t[2];if(i.dataType!==s.dataType||i.dataType!==a.dataType)throw new Error("All inputs must have the same data type");if(i.dims.length!==3&&i.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 u=i.dims[i.dims.length-1],c=i.dims[i.dims.length-2];if(s.dims[s.dims.length-1]!==u)throw new Error("Skip must have the same hidden size as input");if(s.dims[s.dims.length-2]!==c)throw new Error("Skip must have the same sequence length as input");if(a.dims.length!==1)throw new Error("Gamma must be 1D");if(a.dims[a.dims.length-1]!==u)throw new Error("Gamma must have the same hidden size as input");if(t.length>3){let d=t[3];if(d.dims.length!==1)throw new Error("Beta must be 1D");if(d.dims[d.dims.length-1]!==u)throw new Error("Beta must have the same hidden size as input")}if(t.length>4){let d=t[4];if(d.dims.length!==1)throw new Error("Bias must be 1D");if(d.dims[d.dims.length-1]!==u)throw new Error("Bias must have the same hidden size as input")}},wy=(t,i,s,a)=>{let u=i.simplified,c=t[0].dims,d=Ve.size(c),m=c,g=d,y=c.slice(-1)[0],E=a?c.slice(0,-1).concat(1):[],$=!u&&t.length>3,h=t.length>4,R=a&&s>1,B=a&&s>2,K=s>3,re=64,oe=wn(y),ee=[{type:12,data:g},{type:12,data:oe},{type:12,data:y},{type:1,data:i.epsilon}],_e=ge=>{let Qe=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],ze=[it("x",t[0].dataType,t[0].dims,oe),it("skip",t[1].dataType,t[1].dims,oe),it("gamma",t[2].dataType,t[2].dims,oe)];$&&ze.push(it("beta",t[3].dataType,t[3].dims,oe)),h&&ze.push(it("bias",t[4].dataType,t[4].dims,oe)),ze.push(Ut("output",t[0].dataType,m,oe)),R&&ze.push(Ut("mean_output",1,E)),B&&ze.push(Ut("inv_std_output",1,E)),K&&ze.push(Ut("input_skip_bias_sum",t[0].dataType,m,oe));let ht=Tn(t[0].dataType),Ft=Tn(1,oe);return` + + ${ge.registerUniforms(Qe).declareVariables(...ze)} + var sum_shared : array<${Ft}, ${re}>; + var sum_squared_shared : array<${Ft}, ${re}>; + + ${ge.mainStart([re,1,1])} + let ix = local_id.x; + let iy = global_id.x / ${re}; + + let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components; + var stride = hidden_size_vectorized / ${re}; + let offset = ix * stride + iy * hidden_size_vectorized; + let offset1d = stride * ix; + if (ix == ${re-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]":ht+"(0.0)"}; + let input_value = x[offset + i]; + let value = input_value + skip_value + bias_value; + ${K?"input_skip_bias_sum[offset + i] = value;":""} + output[offset + i] = value; + let f32_value = ${Un(ht,oe,"value")}; + sum_shared[ix] += f32_value; + sum_squared_shared[ix] += f32_value * f32_value; + } + workgroupBarrier(); + + var reduce_size : u32 = ${re}; + 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 = ${Dr("sum",oe)} / f32(uniforms.hidden_size); + let inv_std_dev = inverseSqrt(${Dr("square_sum",oe)} / f32(uniforms.hidden_size) ${u?"":"- mean * mean"} + uniforms.epsilon); + ${R?"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] ${u?"":`- ${ht}(mean)`}) * + ${ht}(inv_std_dev) * gamma[offset1d + i] + ${$?"+ beta[offset1d + i]":""}; + } + }`},ae=[{dims:m,dataType:t[0].dataType}];return s>1&&ae.push({dims:E,dataType:1}),s>2&&ae.push({dims:E,dataType:1}),s>3&&ae.push({dims:c,dataType:t[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${oe};${R};${B};${K}`,inputDependencies:t.map((ge,Qe)=>"type")},getShaderSource:_e,getRunData:()=>({outputs:ae,dispatchGroup:{x:Math.ceil(g/y)},programUniforms:ee})}},vy=(t,i)=>{yy(t.inputs);let s=[0];t.outputCount>1&&s.push(-3),t.outputCount>2&&s.push(-3),t.outputCount>3&&s.push(3),t.compute(wy(t.inputs,i,t.outputCount,!1),{outputs:s})}}),My,Kc,by,rm,xy,Ty,Sy,ky,ab=M(()=>{Xt(),Yt(),mn(),sn(),My=(t,i)=>{if(!t||t.length<1)throw new Error("too few inputs");if(i.axes.length!==0){if(i.axes.length!==i.starts.length||i.axes.length!==i.ends.length)throw new Error("axes, starts and ends must have the same length")}else if(i.starts.length!==i.ends.length)throw new Error("starts and ends must have the same length");t.slice(1).forEach((s,a)=>{if(t[a+1].dataType!==6&&t[a+1].dataType!==7)throw new Error(`Input ${a} must be an array of int32 or int64`)})},Kc=(t,i)=>{let s=[];if(t.length>i)if(t[i].dataType===7)t[i].getBigInt64Array().forEach(a=>s.push(Number(a)));else if(t[i].dataType===6)t[i].getInt32Array().forEach(a=>s.push(Number(a)));else throw new Error(`Input ${i} must be an array of int32 or int64`);return s},by=(t,i)=>{if(t.length>1){let s=Kc(t,1),a=Kc(t,2),u=Kc(t,3);return u.length===0&&(u=[...Array(t[0].dims.length).keys()]),Gt({starts:s,ends:a,axes:u})}else return i},rm=(t,i,s,a,u)=>{let c=t;return t<0&&(c+=s[a[i]]),u[i]<0?Math.max(0,Math.min(c,s[a[i]]-1)):Math.max(0,Math.min(c,s[a[i]]))},xy=(t,i,s)=>`fn calculateInputIndices(output_indices: ${i.type.indices}) -> ${t.type.indices} { + var input_indices: ${t.type.indices}; + var carry = 0u; + for (var i = ${s.length}; i >= 0; i--) { + let input_shape_i = ${Ot("uniforms.input_shape","i",s.length)}; + let steps_i = ${Ot("uniforms.steps","i",s.length)}; + let signs_i = ${Ot("uniforms.signs","i",s.length)}; + let starts_i = ${Ot("uniforms.starts","i",s.length)}; + var output_index = ${i.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; + } + ${t.indicesSet("input_indices","i","input_index")}; + } + return input_indices; + }`,Ty=(t,i)=>{let s=t[0].dims,a=Ve.size(s),u=i.axes.length>0?Ve.normalizeAxes(i.axes,s.length):[...Array(s.length).keys()],c=Kc(t,4);c.forEach(oe=>oe!==0||(()=>{throw new Error("step cannot be 0")})),c.length===0&&(c=Array(u.length).fill(1));let d=i.starts.map((oe,ee)=>rm(oe,ee,s,u,c)),m=i.ends.map((oe,ee)=>rm(oe,ee,s,u,c));if(u.length!==d.length||u.length!==m.length)throw new Error("start, ends and axes should have the same number of elements");if(u.length!==s.length)for(let oe=0;oeMath.sign(oe));c.forEach((oe,ee,_e)=>{if(oe<0){let ae=(m[ee]-d[ee])/oe,ge=d[ee],Qe=ge+ae*c[ee];d[ee]=Qe,m[ee]=ge,_e[ee]=-oe}});let y=s.slice(0);u.forEach((oe,ee)=>{y[oe]=Math.ceil((m[oe]-d[oe])/c[oe])});let E={dims:y,dataType:t[0].dataType},$=Ut("output",t[0].dataType,y.length),h=it("input",t[0].dataType,t[0].dims.length),R=Ve.size(y),B=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:d.length},{name:"signs",type:"i32",length:g.length},{name:"steps",type:"u32",length:c.length}],K=[{type:12,data:R},{type:12,data:d},{type:6,data:g},{type:12,data:c},...Et(t[0].dims,y)],re=oe=>` + ${oe.registerUniforms(B).declareVariables(h,$)} + ${xy(h,$,s)} + ${oe.mainStart()} + ${oe.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + let output_indices = ${$.offsetToIndices("global_idx")}; + let input_indices = calculateInputIndices(output_indices); + ${$.setByOffset("global_idx",h.getByIndices("input_indices"))} + }`;return{name:"Slice",shaderCache:{hint:`${g.length}_${d.length}_${c.length}`,inputDependencies:["rank"]},getShaderSource:re,getRunData:()=>({outputs:[E],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:K})}},Sy=(t,i)=>{My(t.inputs,i);let s=by(t.inputs,i);t.compute(Ty(t.inputs,s),{inputs:[0]})},ky=t=>{let i=t.starts,s=t.ends,a=t.axes;return Gt({starts:i,ends:s,axes:a})}}),Ey,Cy,$y,Py,lb=M(()=>{Xt(),Yt(),mn(),sn(),Ey=t=>{if(!t||t.length!==1)throw new Error("Softmax op requires 1 input.")},Cy=(t,i)=>{let s=t.dims,a=Ve.size(s),u=64,c=i.axis;if(c<0&&(c=s.length+c),coe===4?`max(max(${re}.x, ${re}.y), max(${re}.z, ${re}.w))`:oe===2?`max(${re}.x, ${re}.y)`:oe===3?`max(max(${re}.x, ${re}.y), ${re}.z)`:re,$=it("x",t.dataType,t.dims,g),h=Ut("result",t.dataType,t.dims,g),R=$.type.value,B=Tn(t.dataType)==="f32"?`var threadMax = ${R}(-3.402823e+38f);`:`var threadMax = ${R}(-65504.0h);`,K=re=>` + var rowMaxShared : ${R}; + var rowSumShared : ${R}; + var threadShared : array<${R}, ${u}>; + + fn getValue(row: i32, col: i32, row_stride: i32) -> ${R} { + let index = row * row_stride + col; + return x[index]; + } + + fn setValue(row: i32, col: i32, row_stride: i32, value: ${R}) { + let index = row * row_stride + col; + result[index] = value; + } + ${re.registerUniform("packedCols","i32").declareVariables($,h)} + ${re.mainStart()} + let gindex = i32(global_idx); + let lindex = i32(local_idx); + const wg = ${u}; + let row = gindex / wg; + let cols = uniforms.packedCols; + let row_stride : i32 = uniforms.packedCols; + + // find the rows max + ${B} + 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 = ${R}(${E("threadShared[0]",g)}); + } + workgroupBarrier(); + + // find the rows sum + var threadSum = ${R}(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 = ${R}(${Dr("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); + } + }`;return{name:"Softmax",shaderCache:{hint:`${g}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:s,dataType:t.dataType}],dispatchGroup:{x:m},programUniforms:[{type:6,data:y}]}),getShaderSource:K}},$y=(t,i)=>{Ey(t.inputs),t.compute(Cy(t.inputs[0],i))},Py=t=>Gt({axis:t.axis})}),Ay,Iy,Fy,zy,Oy,Dy,Ly,ub=M(()=>{Xt(),Yt(),mn(),sn(),Ay=t=>{if(!t||t.length<1)throw new Error("too few inputs")},Iy=(t,i)=>{let s=[],a=i.numOutputs;return t[1].dims[0]>0&&(t[1].getBigInt64Array().forEach(u=>s.push(Number(u))),a=s.length),Gt({numOutputs:a,axis:i.axis,splitSizes:s})},Fy=t=>` +fn calculateOutputIndex(index: u32) -> u32 { + for (var i: u32 = 0u; i < ${t}u; i += 1u ) { + if (index < ${Ot("uniforms.size_in_split_axis","i",t)}) { + return i; + } + } + return ${t}u; +}`,zy=t=>{let i=t.length,s=[];for(let a=0;a{let s=t[0].dims,a=Ve.size(s),u=t[0].dataType,c=Ve.normalizeAxis(i.axis,s.length),d=new Array(i.numOutputs),m=it("input",u,s.length),g=new Array(i.numOutputs),y=[],E=[],$=0,h=[{type:12,data:a}];for(let B=0;B` + ${B.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",g.length).declareVariables(m,...d)} + ${Fy(g.length)} + ${zy(d)} + + ${B.mainStart()} + ${B.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")} + + var indices = ${m.offsetToIndices("global_idx")}; + var index = ${m.indicesGet("indices",c)}; + let output_number = calculateOutputIndex(index); + if (output_number != 0) { + index -= ${Ot("uniforms.size_in_split_axis","output_number - 1u",g.length)}; + ${m.indicesSet("indices",c,"index")}; + } + writeBufferData(output_number, indices, global_idx); + }`;return{name:"Split",shaderCache:{hint:i.cacheKey,inputDependencies:["rank"]},getShaderSource:R,getRunData:()=>({outputs:y,dispatchGroup:{x:Math.ceil(a/64)},programUniforms:h})}},Dy=(t,i)=>{Ay(t.inputs);let s=t.inputs.length===1?i:Iy(t.inputs,i);t.compute(Oy(t.inputs,s),{inputs:[0]})},Ly=t=>{let i=t.axis,s=t.splitSizes,a=t.numOutputs<0?s.length:t.numOutputs;if(a!==s.length)throw new Error("numOutputs and splitSizes lengh must be equal");return Gt({axis:i,numOutputs:a,splitSizes:s})}}),By,Ry,Ny,db=M(()=>{Xt(),Yt(),sn(),By=(t,i,s,a,u)=>{let c=Ut("output_data",u,s.length,4),d=it("a_data",i[1].dataType,i[1].dims.length,4),m=it("b_data",i[2].dataType,i[2].dims.length,4),g=it("c_data",i[0].dataType,i[0].dims.length,4),y,E=($,h,R)=>`select(${h}, ${$}, ${R})`;if(!a)y=c.setByOffset("global_idx",E(d.getByOffset("global_idx"),m.getByOffset("global_idx"),g.getByOffset("global_idx")));else{let $=(h,R,B="")=>{let K=`a_data[index_a${R}][component_a${R}]`,re=`b_data[index_b${R}][component_b${R}]`,oe=`bool(c_data[index_c${R}] & (0xffu << (component_c${R} * 8)))`;return` + let output_indices${R} = ${c.offsetToIndices(`global_idx * 4u + ${R}u`)}; + let offset_a${R} = ${d.broadcastedIndicesToOffset(`output_indices${R}`,c)}; + let offset_b${R} = ${m.broadcastedIndicesToOffset(`output_indices${R}`,c)}; + let offset_c${R} = ${g.broadcastedIndicesToOffset(`output_indices${R}`,c)}; + let index_a${R} = offset_a${R} / 4u; + let index_b${R} = offset_b${R} / 4u; + let index_c${R} = offset_c${R} / 4u; + let component_a${R} = offset_a${R} % 4u; + let component_b${R} = offset_b${R} % 4u; + let component_c${R} = offset_c${R} % 4u; + ${h}[${R}] = ${B}(${E(K,re,oe)}); + `};u===9?y=` + var data = vec4(0); + ${$("data",0,"u32")} + ${$("data",1,"u32")} + ${$("data",2,"u32")} + ${$("data",3,"u32")} + output_data[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:y=` + ${$("output_data[global_idx]",0)} + ${$("output_data[global_idx]",1)} + ${$("output_data[global_idx]",2)} + ${$("output_data[global_idx]",3)} + `}return` + ${t.registerUniform("vec_size","u32").declareVariables(g,d,m,c)} + ${t.mainStart()} + ${t.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${y} + }`},Ry=t=>{let i=t[1].dims,s=t[2].dims,a=t[0].dims,u=t[1].dataType,c=!(Ve.areEqual(i,s)&&Ve.areEqual(s,a)),d=i,m=Ve.size(i);if(c){let y=ur.calcShape(ur.calcShape(i,s,!1),a,!1);if(!y)throw new Error("Can't perform where op on the given tensors");d=y,m=Ve.size(d)}let g=Math.ceil(m/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:y=>By(y,t,d,c,u),getRunData:()=>({outputs:[{dims:d,dataType:u}],dispatchGroup:{x:Math.ceil(m/64/4)},programUniforms:[{type:12,data:g},...Et(a,i,s,d)]})}},Ny=t=>{t.compute(Ry(t.inputs))}}),jy,cb=M(()=>{Wp(),Es(),Uu(),Gp(),bd(),qp(),Hp(),Zd(),Zh(),Jp(),ef(),of(),Jh(),af(),lf(),uf(),Ec(),cf(),em(),hr(),Xa(),ff(),Ic(),cn(),qo(),nb(),rb(),va(),ib(),ob(),sb(),ab(),lb(),ub(),Dc(),fo(),Da(),db(),jy=new Map([["Abs",[Hu]],["Acos",[Ku]],["Acosh",[xa]],["Add",[Sd]],["ArgMax",[Fu,ks]],["ArgMin",[Iu,ks]],["Asin",[Qu]],["Asinh",[Xu]],["Atan",[Ta]],["Atanh",[Yu]],["Attention",[Bu]],["AveragePool",[xi,Er]],["BatchNormalization",[Vu]],["BiasAdd",[ba]],["BiasSplitGelu",[Md]],["Cast",[Cs,Zu]],["Ceil",[td]],["Clip",[ed]],["Concat",[Di,Dd]],["Conv",[jo,Za]],["ConvTranspose",[Zp,rc]],["Cos",[Sa]],["Cosh",[nd]],["CumSum",[sl,sc]],["DepthToSpace",[ll,uc]],["DequantizeLinear",[gf,Hc]],["Div",[kd]],["Einsum",[cc,pc]],["Elu",[rd,mo]],["Equal",[Ba]],["Erf",[id]],["Exp",[ka]],["Expand",[cl]],["FastGelu",[mc]],["Floor",[od]],["FusedConv",[jo,Za]],["Gather",[wc,yc]],["GatherElements",[xc,bc]],["Gelu",[sd]],["Gemm",[df,kc]],["GlobalAveragePool",[_r,ir]],["GlobalMaxPool",[ui,tm]],["Greater",[Pd]],["GreaterOrEqual",[Id]],["GroupQueryAttention",[Nc,Bc]],["HardSigmoid",[$a,cd]],["InstanceNormalization",[Wc]],["LayerNormalization",[ar]],["LeakyRelu",[ad,mo]],["Less",[Ad]],["LessOrEqual",[Ra]],["Log",[Oa]],["MatMul",[Qd]],["MatMulNBits",[pf,qc]],["MaxPool",[Ns,_l]],["Mul",[Ed]],["MultiHeadAttention",[Ac,$c]],["Neg",[ld]],["Not",[Ea]],["Pad",[Wt]],["Pow",[Cd]],["QuickGelu",[wd,mo]],["Range",[X_]],["Reciprocal",[ud]],["ReduceMin",[ya]],["ReduceMean",[Su]],["ReduceMax",[Cu]],["ReduceSum",[Pu]],["ReduceProd",[$u]],["ReduceL1",[ku]],["ReduceL2",[_a]],["ReduceLogSum",[Au]],["ReduceLogSumExp",[Eu]],["ReduceSumSquare",[wa]],["Relu",[Ca]],["Resize",[fy,hy]],["RotaryEmbedding",[_y]],["Sigmoid",[dd]],["Sin",[pd]],["Sinh",[fd]],["Slice",[Sy,ky]],["SkipLayerNormalization",[vy]],["Split",[Dy,Ly]],["Sqrt",[Pa]],["Softmax",[$y,Py]],["Sub",[$d]],["Tan",[hd]],["Tanh",[Ia]],["ThresholdedRelu",[gd,mo]],["Tile",[Oc]],["Transpose",[tu,la]],["Where",[Ny]]])}),Vy,pb=M(()=>{j(),zr(),sn(),Vy=class{constructor(t){this.backend=t,this.repo=new Map,this.attributesBound=!1}getArtifact(t){return this.repo.get(t)}setArtifact(t,i){this.repo.set(t,i)}run(t,i,s,a,u){Ge(t.programInfo.name);let c=this.backend.device,d=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let m=[];for(let y of i)m.push({binding:m.length,resource:{buffer:y.buffer}});for(let y of s)m.push({binding:m.length,resource:{buffer:y.buffer}});u&&m.push({binding:m.length,resource:u});let g=c.createBindGroup({layout:t.computePipeline.getBindGroupLayout(0),entries:m,label:t.programInfo.name});if(this.backend.sessionStatus==="capturing"){let y={kernelId:this.backend.currentKernelId,computePipeline:t.computePipeline,bindGroup:g,dispatchGroup:a};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(y)}d.setPipeline(t.computePipeline),d.setBindGroup(0,g),d.dispatchWorkgroups(...a),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(),We(t.programInfo.name)}dispose(){}build(t,i){Ge(t.name);let s=this.backend.device,a=[];s.features.has("shader-f16")&&a.push("enable f16;");let u=Zl(i,this.backend.device.limits),c=t.getShaderSource(u),d=`${a.join(` +`)} +${u.additionalImplementations} +${c}`,m=s.createShaderModule({code:d,label:t.name});Rn("verbose",()=>`[WebGPU] ${t.name} shader code: ${d}`);let g=s.createComputePipeline({compute:{module:m,entryPoint:"main"},layout:"auto",label:t.name});return We(t.name),{programInfo:t,computePipeline:g,uniformVariablesInfo:u.variablesInfo}}normalizeDispatchGroupSize(t){let i=typeof t=="number"?t:t.x,s=typeof t=="number"?1:t.y||1,a=typeof t=="number"?1:t.z||1,u=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(i<=u&&s<=u&&a<=u)return[i,s,a];let c=i*s*a,d=Math.ceil(Math.sqrt(c));if(d>u){if(d=Math.ceil(Math.cbrt(c)),d>u)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[d,d,d]}else return[d,d,1]}}}),Uy,Wy,Gy,qy,fb=M(()=>{j(),Xt(),zr(),T(),$n(),cb(),pb(),Uy=(t,i)=>{if(i.length!==t.length)throw new Error(`inputDependencies length ${i.length} is not equal to inputTensors length ${t.length}.`);let s=[];for(let a=0;a{var u,c;let a=t.name;return(u=t.shaderCache)!=null&&u.hint&&(a+="["+t.shaderCache.hint+"]"),a+=":"+s+`:${Uy(i,((c=t.shaderCache)==null?void 0:c.inputDependencies)??new Array(i.length).fill("dims"))}`,a},Gy=class{constructor(t){t&&(this.architecture=t.architecture,this.vendor=t.vendor)}isArchitecture(t){return this.architecture===t}isVendor(t){return this.vendor===t}},qy=class{constructor(){this.currentSessionId=null,this.currentKernelId=null,this.commandEncoder=null,this.computePassEncoder=null,this.maxDispatchNumber=16,this.pendingDispatchNumber=0,this.pendingKernels=[],this.pendingQueries=new Map,this.sessionStatus="default",this.capturedCommandList=new Map,this.capturedPendingKernels=new Map,this.sessionExternalDataMapping=new Map}get currentKernelCustomData(){if(this.currentKernelId===null)throw new Error("currentKernelCustomData(): currentKernelId is null. (should not happen)");let t=this.kernelCustomData.get(this.currentKernelId);return t||(t={},this.kernelCustomData.set(this.currentKernelId,t)),t}async initialize(t,i){this.env=t;let s=[],a={requiredLimits:{maxComputeWorkgroupStorageSize:i.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:i.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:i.limits.maxStorageBufferBindingSize,maxBufferSize:i.limits.maxBufferSize,maxComputeInvocationsPerWorkgroup:i.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupSizeX:i.limits.maxComputeWorkgroupSizeX,maxComputeWorkgroupSizeY:i.limits.maxComputeWorkgroupSizeY,maxComputeWorkgroupSizeZ:i.limits.maxComputeWorkgroupSizeZ},requiredFeatures:s};i.features.has("chromium-experimental-timestamp-query-inside-passes")?s.push("chromium-experimental-timestamp-query-inside-passes"):i.features.has("timestamp-query")&&s.push("timestamp-query"),i.features.has("shader-f16")&&s.push("shader-f16"),this.device=await i.requestDevice(a),this.adapterInfo=new Gy(i.info||await i.requestAdapterInfo()),this.gpuDataManager=Zt(this),this.programManager=new Vy(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,co(t.logLevel,!!t.debug),this.device.onuncapturederror=u=>{u.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${u.error.message}`)},Object.defineProperty(this.env.webgpu,"device",{value:this.device,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(this.env.webgpu,"adapter",{value:i,writable:!1,enumerable:!0,configurable:!1}),this.setQueryType()}dispose(){typeof this.querySet<"u"&&this.querySet.destroy(),this.gpuDataManager.dispose()}getCommandEncoder(){return this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder()),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let t=this.getCommandEncoder(),i={};this.queryType==="at-passes"&&(i.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=t.beginComputePass(i)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;Ge(),this.endComputePass();let t;this.queryType!=="none"&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),t=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(t,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,t,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!=="none"&&t.mapAsync(GPUMapMode.READ).then(()=>{var a;let i=new BigUint64Array(t.getMappedRange()),s=this.pendingQueries.get(t);for(let u=0;u"u"&&(this.queryTimeBase=R);let K=Number(R-this.queryTimeBase),re=Number(B-this.queryTimeBase);if(!Number.isSafeInteger(K)||!Number.isSafeInteger(re))throw new RangeError("incorrect timestamp range");if((a=this.env.webgpu.profiling)!=null&&a.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:$.map(oe=>({dims:oe.dims,dataType:ai(oe.dataType)})),outputsMetadata:h.map(oe=>({dims:oe.dims,dataType:ai(oe.dataType)})),kernelId:d,kernelType:g,kernelName:y,programName:E,startTime:K,endTime:re});else{let oe="";$.forEach((_e,ae)=>{oe+=`input[${ae}]: [${_e.dims}] | ${ai(_e.dataType)}, `});let ee="";h.forEach((_e,ae)=>{ee+=`output[${ae}]: [${_e.dims}] | ${ai(_e.dataType)}, `}),console.log(`[profiling] kernel "${d}|${g}|${y}|${E}" ${oe}${ee}execution time: ${re-K} ns`)}Ce("GPU",`${E}::${R}::${B}`)}t.unmap(),this.pendingQueries.delete(t)}),We()}run(t,i,s,a,u,c){Ge(t.name);let d=[];for(let ee=0;ee_e):s;if(E.length!==m.length)throw new Error(`Output size ${E.length} must be equal to ${m.length}.`);let $=[],h=[];for(let ee=0;ee=c)throw new Error(`Invalid output index: ${E[ee]}`);if(E[ee]===-3)continue;let _e=E[ee]===-1,ae=E[ee]===-2,ge=_e||ae?u(m[ee].dataType,m[ee].dims):a(E[ee],m[ee].dataType,m[ee].dims);if($.push(ge),ge.data===0)continue;let Qe=this.gpuDataManager.get(ge.data);if(!Qe)throw new Error(`no GPU data for output: ${ge.data}`);if(_e&&this.temporaryData.push(Qe),ae){let ze=this.kernelPersistentData.get(this.currentKernelId);ze||(ze=[],this.kernelPersistentData.set(this.currentKernelId,ze)),ze.push(Qe)}h.push(Qe)}if(d.length!==i.length||h.length!==$.length){if(h.length===0)return We(t.name),$;throw new Error(`Program ${t.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let R;if(y){let ee=0,_e=[];y.forEach(ze=>{let ht=typeof ze.data=="number"?[ze.data]:ze.data;if(ht.length===0)return;let Ft=ze.type===10?2:4,Dt,hn;ze.type===10?(hn=ht.length>4?16:ht.length>2?8:ht.length*Ft,Dt=ht.length>4?16:Ft*ht.length):(hn=ht.length<=2?ht.length*Ft:16,Dt=16),ee=Math.ceil(ee/hn)*hn,_e.push(ee);let ln=ze.type===10?8:4;ee+=ht.length>4?Math.ceil(ht.length/ln)*Dt:ht.length*Ft});let ae=16;ee=Math.ceil(ee/ae)*ae;let ge=new ArrayBuffer(ee);y.forEach((ze,ht)=>{let Ft=_e[ht],Dt=typeof ze.data=="number"?[ze.data]:ze.data;if(ze.type===6)new Int32Array(ge,Ft,Dt.length).set(Dt);else if(ze.type===12)new Uint32Array(ge,Ft,Dt.length).set(Dt);else if(ze.type===10)new Uint16Array(ge,Ft,Dt.length).set(Dt);else if(ze.type===1)new Float32Array(ge,Ft,Dt.length).set(Dt);else throw new Error(`Unsupported uniform type: ${ai(ze.type)}`)});let Qe=this.gpuDataManager.create(ee,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(Qe.buffer,0,ge,0,ee),this.gpuDataManager.release(Qe.id),R={offset:0,size:ee,buffer:Qe.buffer}}let B=this.programManager.normalizeDispatchGroupSize(g),K=B[1]===1&&B[2]===1,re=Wy(t,i,K),oe=this.programManager.getArtifact(re);if(oe||(oe=this.programManager.build(t,B),this.programManager.setArtifact(re,oe),Rn("info",()=>`[artifact] key: ${re}, programName: ${t.name}`)),y&&oe.uniformVariablesInfo){if(y.length!==oe.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${oe.uniformVariablesInfo.length}, got ${y.length} in program "${oe.programInfo.name}".`);for(let ee=0;ee`[ProgramManager] run "${t.name}" (key=${re}) with ${B[0]}x${B[1]}x${B[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let ee={kernelId:this.currentKernelId,programName:oe.programInfo.name,inputTensorViews:i,outputTensorViews:$};this.pendingKernels.push(ee),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(ee)}return this.programManager.run(oe,d,h,B,R),We(t.name),$}upload(t,i){this.gpuDataManager.upload(t,i)}memcpy(t,i){this.gpuDataManager.memcpy(t,i)}async download(t,i){await this.gpuDataManager.download(t,i)}alloc(t){return this.gpuDataManager.create(t).id}free(t){return this.gpuDataManager.release(t)}createKernel(t,i,s,a){let u=jy.get(t);if(!u)throw new Error(`kernel not implemented: ${t}`);let c={kernelType:t,kernelName:a,kernelEntry:u[0],attributes:[u[1],s]};this.kernels.set(i,c)}releaseKernel(t){let i=this.kernelPersistentData.get(t);if(i){for(let s of i)this.gpuDataManager.release(s.id);this.kernelPersistentData.delete(t)}this.kernelCustomData.delete(t),this.kernels.delete(t)}computeKernel(t,i,s){let a=this.kernels.get(t);if(!a)throw new Error(`kernel not created: ${t}`);let u=a.kernelType,c=a.kernelName,d=a.kernelEntry,m=a.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${u}] ${c}" is not allowed to be called recursively`);this.currentKernelId=t,m[0]&&(m[1]=m[0](m[1]),m[0]=void 0),Rn("info",()=>`[WebGPU] Start to run kernel "[${u}] ${c}"...`);let g=this.env.debug;this.temporaryData=[];try{return g&&this.device.pushErrorScope("validation"),d(i,m[1]),0}catch(y){return s.push(Promise.resolve(`[WebGPU] Kernel "[${u}] ${c}" failed. ${y}`)),1}finally{g&&s.push(this.device.popErrorScope().then(y=>y?`GPU validation error for kernel "[${u}] ${c}": ${y.message}`:null));for(let y of this.temporaryData)this.gpuDataManager.release(y.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(t,i,s,a){let u=this.sessionExternalDataMapping.get(t);u||(u=new Map,this.sessionExternalDataMapping.set(t,u));let c=u.get(i),d=this.gpuDataManager.registerExternalBuffer(s,a,c==null?void 0:c[1]);return u.set(i,[d,s]),d}unregisterBuffers(t){let i=this.sessionExternalDataMapping.get(t);i&&(i.forEach(s=>this.gpuDataManager.unregisterExternalBuffer(s[1])),this.sessionExternalDataMapping.delete(t))}getBuffer(t){let i=this.gpuDataManager.get(t);if(!i)throw new Error(`no GPU data for buffer: ${t}`);return i.buffer}createDownloader(t,i,s){return async()=>{let a=await vt(this,t,i);return Se(a.buffer,s)}}writeTimestamp(t){this.queryType==="inside-passes"&&this.computePassEncoder.writeTimestamp(this.querySet,t)}setQueryType(){var t;this.queryType="none",(((t=this.env.webgpu.profiling)==null?void 0:t.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(){Rn("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(){Rn("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){Rn("info","replay"),this.sessionStatus="replaying";let t=this.capturedCommandList.get(this.currentSessionId),i=this.capturedPendingKernels.get(this.currentSessionId),s=t.length;this.pendingKernels=[];for(let a=0;a=this.maxDispatchNumber||this.queryType==="at-passes")&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus="default"}onReleaseSession(t){this.unregisterBuffers(t),this.capturedCommandList.has(t)&&this.capturedCommandList.delete(t),this.capturedPendingKernels.has(t)&&this.capturedPendingKernels.delete(t),this.gpuDataManager.onReleaseSession(t)}onRunStart(t){this.currentSessionId=t,this.setQueryType()}}}),Hy={};b(Hy,{init:()=>Qy});var _f,Ky,Qy,hb=M(()=>{Xt(),fb(),zr(),Yt(),_f=class tb{constructor(i,s,a,u){this.module=i,this.dataType=s,this.data=a,this.dims=u}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let i=Ve.size(this.dims);return i===0?new Float32Array:new Float32Array(this.module.HEAP8.buffer,this.data,i)}getBigInt64Array(){if(this.dataType!==7)throw new Error("Invalid data type");let i=Ve.size(this.dims);return i===0?new BigInt64Array:new BigInt64Array(this.module.HEAP8.buffer,this.data,i)}getInt32Array(){if(this.dataType!==6)throw new Error("Invalid data type");let i=Ve.size(this.dims);return i===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,i)}reshape(i){if(Ve.size(i)!==Ve.size(this.dims))throw new Error("Invalid new shape");return new tb(this.module,this.dataType,this.data,i)}},Ky=class{constructor(t,i,s){this.module=t,this.backend=i,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=i.adapterInfo;let a=t.HEAPU32,u=s>>>2;this.opKernelContext=a[u++];let c=a[u++];this.outputCount=a[u++],this.customDataOffset=a[u++],this.customDataSize=a[u++];let d=[];for(let m=0;mtypeof m=="number"?this.inputs[m]:m))??this.inputs,a=(i==null?void 0:i.outputs)??[],u=(m,g,y)=>new _f(this.module,g,this.output(m,y),y),c=(m,g)=>{let y=wi(m,g);if(!y)throw new Error(`Unsupported data type: ${m}`);let E=y>0?this.backend.gpuDataManager.create(y).id:0;return new _f(this.module,m,E,g)};return this.backend.run(t,s,a,u,c,this.outputCount)}output(t,i){let s=this.module.stackSave();try{let a=this.module.stackAlloc((1+i.length)*4),u=a>>2;this.module.HEAPU32[u++]=i.length;for(let c=0;c{let u=i.jsepInit;if(!u)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(t==="webgpu"){let c=new qy;await c.initialize(s,a),u("webgpu",[c,d=>c.alloc(d),d=>c.free(d),(d,m,g,y=!1)=>{if(y)Rn("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${d}, dst=${m}, size=${g}`),c.memcpy(d,m);else{Rn("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${d}, gpuDataId=${m}, size=${g}`);let E=i.HEAPU8.subarray(d>>>0,(d>>>0)+g);c.upload(m,E)}},async(d,m,g)=>{Rn("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${d}, dataOffset=${m}, size=${g}`),await c.download(d,()=>i.HEAPU8.subarray(m>>>0,(m>>>0)+g))},(d,m,g)=>c.createKernel(d,m,g,i.UTF8ToString(i._JsepGetNodeName(m))),d=>c.releaseKernel(d),(d,m,g,y)=>{Rn("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${g}, kernel=${d}, contextDataOffset=${m}`);let E=new Ky(i,c,m);return c.computeKernel(d,E,y)},()=>c.captureBegin(),()=>c.captureEnd(),()=>c.replay()])}else u("webnn")}}),Xy,im,om,Ho,Yy,yf,sm,am,lm,um,dm,cm,Zy=M(()=>{vs(),Ms(),Xt(),cr(),zi(),zo(),Xy=(t,i)=>{Nn()._OrtInit(t,i)!==0&&Fn("Can't initialize onnxruntime.")},im=async t=>{Xy(t.wasm.numThreads,Ki(t.logLevel))},om=async(t,i)=>{{let s=(hb(),S(Hy)).init;if(i==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");let a=t.webgpu.adapter;if(a){if(typeof a.limits!="object"||typeof a.features!="object"||typeof a.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let u=t.webgpu.powerPreference;if(u!==void 0&&u!=="low-power"&&u!=="high-performance")throw new Error(`Invalid powerPreference setting: "${u}"`);let c=t.webgpu.forceFallbackAdapter;if(c!==void 0&&typeof c!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${c}"`);if(a=await navigator.gpu.requestAdapter({powerPreference:u,forceFallbackAdapter:c}),!a)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",Nn(),t,a)}if(i==="webnn"){if(typeof navigator>"u"||!navigator.ml)throw new Error("WebNN is not supported in current environment");await s("webnn",Nn(),t)}}},Ho=new Map,Yy=t=>{let i=Nn(),s=i.stackSave();try{let a=i.stackAlloc(8);return i._OrtGetInputOutputCount(t,a,a+4)!==0&&Fn("Can't get session input/output count."),[i.HEAP32[a/4],i.HEAP32[a/4+1]]}finally{i.stackRestore(s)}},yf=t=>{let i=Nn(),s=i._malloc(t.byteLength);if(s===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${t.byteLength}.`);return i.HEAPU8.set(t,s),[s,t.byteLength]},sm=async(t,i)=>{var $,h;let s,a,u=Nn();Array.isArray(t)?[s,a]=t:t.buffer===u.HEAPU8.buffer?[s,a]=[t.byteOffset,t.byteLength]:[s,a]=yf(t);let c=0,d=0,m=0,g=[],y=[],E=[];try{if([d,g]=Oi(i),(i==null?void 0:i.externalData)&&u.mountExternalData){let ae=[];for(let ge of i.externalData){let Qe=typeof ge=="string"?ge:ge.path;ae.push(Qi(typeof ge=="string"?ge:ge.data).then(ze=>{u.mountExternalData(Qe,ze)}))}await Promise.all(ae)}for(let ae of(i==null?void 0:i.executionProviders)??[])if((typeof ae=="string"?ae:ae.name)==="webnn"){if(u.currentContext)throw new Error("WebNN execution provider is already set.");if(typeof ae!="string"){let ge=ae,Qe=ge==null?void 0:ge.context,ze=ge==null?void 0:ge.gpuDevice,ht=ge==null?void 0:ge.deviceType,Ft=ge==null?void 0:ge.numThreads,Dt=ge==null?void 0:ge.powerPreference;Qe?u.currentContext=Qe:ze?u.currentContext=await navigator.ml.createContext(ze):u.currentContext=await navigator.ml.createContext({deviceType:ht,numThreads:Ft,powerPreference:Dt})}else u.currentContext=await navigator.ml.createContext();break}c=await u._OrtCreateSession(s,a,d),c===0&&Fn("Can't create a session."),u.currentContext&&(u.currentContext=void 0);let[R,B]=Yy(c),K=!!(i!=null&&i.enableGraphCapture),re=[],oe=[],ee=[];for(let ae=0;aeae==="gpu-buffer")&&(m=u._OrtCreateBinding(c),m===0&&Fn("Can't create IO binding."),_e={handle:m,outputPreferredLocations:ee,outputPreferredLocationsEncoded:ee.map(ae=>lo(ae))}),Ho.set(c,[c,y,E,_e,K,!1]),[c,re,oe]}catch(R){throw y.forEach(B=>u._OrtFree(B)),E.forEach(B=>u._OrtFree(B)),m!==0&&u._OrtReleaseBinding(m),c!==0&&u._OrtReleaseSession(c),R}finally{u._free(s),d!==0&&u._OrtReleaseSessionOptions(d),g.forEach(R=>u._free(R)),(h=u.unmountExternalData)==null||h.call(u)}},am=t=>{var g;let i=Nn(),s=Ho.get(t);if(!s)throw new Error(`cannot release session. invalid session id: ${t}`);let[a,u,c,d,m]=s;d&&(m&&i._OrtClearBoundOutputs(d.handle),i._OrtReleaseBinding(d.handle)),(g=i.jsepOnReleaseSession)==null||g.call(i,t),u.forEach(y=>i._OrtFree(y)),c.forEach(y=>i._OrtFree(y)),i._OrtReleaseSession(a),Ho.delete(t)},lm=(t,i,s,a,u,c=!1)=>{if(!t){i.push(0);return}let d=Nn(),m=t[0],g=t[1],y=t[3],E,$;if(m==="string"&&y==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");if(c&&y!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${u} when enableGraphCapture is true.`);if(y==="gpu-buffer"){let B=t[2].gpuBuffer;$=wi(so(m),g);let K=d.jsepRegisterBuffer;if(!K)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');E=K(a,u,B,$)}else{let B=t[2];if(Array.isArray(B)){$=4*B.length,E=d._malloc($),s.push(E);let K=E/4;for(let re=0;red.HEAP32[B++]=re);let K=d._OrtCreateTensor(so(m),E,$,R,g.length,lo(y));K===0&&Fn(`Can't create tensor for input/output. session=${a}, index=${u}.`),i.push(K)}finally{d.stackRestore(h)}},um=async(t,i,s,a,u,c)=>{var Dt,hn;let d=Nn(),m=Ho.get(t);if(!m)throw new Error(`cannot run inference. invalid session id: ${t}`);let g=m[0],y=m[1],E=m[2],$=m[3],h=m[4],R=m[5],B=i.length,K=a.length,re=0,oe=[],ee=[],_e=[],ae=[],ge=d.stackSave(),Qe=d.stackAlloc(B*4),ze=d.stackAlloc(B*4),ht=d.stackAlloc(K*4),Ft=d.stackAlloc(K*4);try{[re,oe]=yi(c);for(let It=0;It$r*Kr,1);on=ai(yr);let Yc=$==null?void 0:$.outputPreferredLocations[a[It]];if(on==="string"){if(Yc==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");let $r=[],Kr=Gn/4;for(let Ti=0;Ti0){let $r=d.jsepGetBuffer;if(!$r)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let Kr=$r(Gn),Ti=wi(yr,Cr);if(Ti===void 0||!ao(on))throw new Error(`Unsupported data type: ${on}`);zt=!0,jn.push([on,di,{gpuBuffer:Kr,download:d.jsepCreateDownloader(Kr,Ti,on),dispose:()=>{d._OrtReleaseTensor(tn)}},"gpu-buffer"])}else{let $r=vi(on),Kr=new $r(Cr);new Uint8Array(Kr.buffer,Kr.byteOffset,Kr.byteLength).set(d.HEAPU8.subarray(Gn,Gn+Kr.byteLength)),jn.push([on,di,Kr,"cpu"])}}finally{d.stackRestore(en),on==="string"&&Gn&&d._free(Gn),zt||d._OrtReleaseTensor(tn)}}return $&&!h&&(d._OrtClearBoundOutputs($.handle),Ho.set(t,[g,y,E,$,h,!1])),jn}finally{d.stackRestore(ge),ee.forEach(ln=>d._OrtReleaseTensor(ln)),_e.forEach(ln=>d._OrtReleaseTensor(ln)),ae.forEach(ln=>d._free(ln)),re!==0&&d._OrtReleaseRunOptions(re),oe.forEach(ln=>d._free(ln))}},dm=t=>{let i=Nn(),s=Ho.get(t);if(!s)throw new Error("invalid session id");let a=s[0],u=i._OrtEndProfiling(a);u===0&&Fn("Can't get an profile file name."),i._OrtFree(u)},cm=t=>{let i=[];for(let s of t){let a=s[2];!Array.isArray(a)&&"buffer"in a&&i.push(a.buffer)}return i}}),Ko,ei,yl,Qc,Xc,wf,pm,vf,js,Vs,Jy,ew,tw,nw,rw,iw,ow,sw,aw=M(()=>{j(),Zy(),cr(),Hn(),Ko=()=>!!z.wasm.proxy&&typeof document<"u",yl=!1,Qc=!1,Xc=!1,vf=new Map,js=(t,i)=>{let s=vf.get(t);s?s.push(i):vf.set(t,[i])},Vs=()=>{if(yl||!Qc||Xc||!ei)throw new Error("worker not ready")},Jy=t=>{switch(t.data.type){case"init-wasm":yl=!1,t.data.err?(Xc=!0,pm[1](t.data.err)):(Qc=!0,pm[0]()),wf&&(URL.revokeObjectURL(wf),wf=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let i=vf.get(t.data.type);t.data.err?i.shift()[1](t.data.err):i.shift()[0](t.data.out);break}}},ew=async()=>{if(!Qc){if(yl)throw new Error("multiple calls to 'initWasm()' detected.");if(Xc)throw new Error("previous call to 'initWasm()' failed.");if(yl=!0,Ko())return new Promise((t,i)=>{ei==null||ei.terminate(),Jt().then(([s,a])=>{try{ei=a,ei.onerror=c=>i(c),ei.onmessage=Jy,pm=[t,i];let u={type:"init-wasm",in:z};ei.postMessage(u),wf=s}catch(u){i(u)}},i)});try{await _i(z.wasm),await im(z),Qc=!0}catch(t){throw Xc=!0,t}finally{yl=!1}}},tw=async t=>{if(Ko())return Vs(),new Promise((i,s)=>{js("init-ep",[i,s]);let a={type:"init-ep",in:{epName:t,env:z}};ei.postMessage(a)});await om(z,t)},nw=async t=>Ko()?(Vs(),new Promise((i,s)=>{js("copy-from",[i,s]);let a={type:"copy-from",in:{buffer:t}};ei.postMessage(a,[t.buffer])})):yf(t),rw=async(t,i)=>{if(Ko()){if(i!=null&&i.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return Vs(),new Promise((s,a)=>{js("create",[s,a]);let u={type:"create",in:{model:t,options:{...i}}},c=[];t instanceof Uint8Array&&c.push(t.buffer),ei.postMessage(u,c)})}else return sm(t,i)},iw=async t=>{if(Ko())return Vs(),new Promise((i,s)=>{js("release",[i,s]);let a={type:"release",in:t};ei.postMessage(a)});am(t)},ow=async(t,i,s,a,u,c)=>{if(Ko()){if(s.some(d=>d[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(u.some(d=>d))throw new Error("pre-allocated output tensor is not supported for proxy.");return Vs(),new Promise((d,m)=>{js("run",[d,m]);let g=s,y={type:"run",in:{sessionId:t,inputIndices:i,inputs:g,outputIndices:a,options:c}};ei.postMessage(y,cm(g))})}else return um(t,i,s,a,u,c)},sw=async t=>{if(Ko())return Vs(),new Promise((i,s)=>{js("end-profiling",[i,s]);let a={type:"end-profiling",in:t};ei.postMessage(a)});dm(t)}}),fm,lw,uw,mb=M(()=>{j(),aw(),Xt(),le(),zo(),fm=(t,i)=>{switch(t.location){case"cpu":return[t.type,t.dims,t.data,"cpu"];case"gpu-buffer":return[t.type,t.dims,{gpuBuffer:t.gpuBuffer},"gpu-buffer"];default:throw new Error(`invalid data location: ${t.location} for ${i()}`)}},lw=t=>{switch(t[3]){case"cpu":return new Be(t[0],t[2],t[1]);case"gpu-buffer":{let i=t[0];if(!ao(i))throw new Error(`not supported data type: ${i} for deserializing GPU tensor`);let{gpuBuffer:s,download:a,dispose:u}=t[2];return Be.fromGpuBuffer(s,{dataType:i,dims:t[1],download:a,dispose:u})}default:throw new Error(`invalid data location: ${t[3]}`)}},uw=class{async fetchModelAndCopyToWasmMemory(t){return nw(await Qi(t))}async loadModel(t,i){Ge();let s;typeof t=="string"?s=await this.fetchModelAndCopyToWasmMemory(t):s=t,[this.sessionId,this.inputNames,this.outputNames]=await rw(s,i),We()}async dispose(){return iw(this.sessionId)}async run(t,i,s){Ge();let a=[],u=[];Object.entries(t).forEach($=>{let h=$[0],R=$[1],B=this.inputNames.indexOf(h);if(B===-1)throw new Error(`invalid input '${h}'`);a.push(R),u.push(B)});let c=[],d=[];Object.entries(i).forEach($=>{let h=$[0],R=$[1],B=this.outputNames.indexOf(h);if(B===-1)throw new Error(`invalid output '${h}'`);c.push(R),d.push(B)});let m=a.map(($,h)=>fm($,()=>`input "${this.inputNames[u[h]]}"`)),g=c.map(($,h)=>$?fm($,()=>`output "${this.outputNames[d[h]]}"`):null),y=await ow(this.sessionId,u,m,d,g,s),E={};for(let $=0;${j(),aw(),mb(),Hn(),dw=()=>{if((typeof z.wasm.initTimeout!="number"||z.wasm.initTimeout<0)&&(z.wasm.initTimeout=0),z.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 z.wasm.proxy!="boolean"&&(z.wasm.proxy=!1),typeof z.wasm.trace!="boolean"&&(z.wasm.trace=!1),typeof z.wasm.numThreads!="number"||!Number.isInteger(z.wasm.numThreads)||z.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)z.wasm.numThreads=1;else{let t=typeof navigator>"u"?C("node:os").cpus().length:navigator.hardwareConcurrency;z.wasm.numThreads=Math.min(4,Math.ceil((t||1)/2))}},cw=class{async init(t){dw(),await ew(),await tw(t)}async createInferenceSessionHandler(t,i){let s=new uw;return await s.loadModel(t,i),Promise.resolve(s)}}}),pw={};b(pw,{wasmBackend:()=>fw});var fw,_b=M(()=>{gb(),fw=new cw});j(),j(),j();var yb="1.20.0-dev.20240821-009209e016",wb=Pe;{let t=(_b(),S(pw)).wasmBackend;te("webgpu",t,5),te("webnn",t,5),te("cpu",t,10),te("wasm",t,10)}Object.defineProperty(z.versions,"web",{value:yb,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":(e,n,r)=>{var o;r.r(n),r.d(n,{Tensor:()=>C.Tensor,createInferenceSession:()=>ne,deviceToExecutionProviders:()=>J,isONNXProxy:()=>P,isONNXTensor:()=>X});var l=r("./src/env.js"),p=r("?2ce3"),_=r("./node_modules/onnxruntime-web/dist/ort.webgpu.bundle.min.mjs"),C=r("./node_modules/onnxruntime-common/dist/esm/index.js");const M=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"}}),b=[];let F,S;if(l.apis.IS_NODE_ENV){switch(S=p??(o||(o=r.t(p,2))),process.platform){case"win32":b.push("dml");break;case"linux":process.arch==="x64"&&b.push("cuda");break}b.push("cpu"),F=["cpu"]}else S=_,l.apis.IS_WEBNN_AVAILABLE&&b.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),l.apis.IS_WEBGPU_AVAILABLE&&b.push("webgpu"),b.push("wasm"),F=["wasm"];const G=S.InferenceSession;function J(L=null){if(!L)return F;switch(L){case"auto":return b;case"gpu":return b.filter(Z=>["webgpu","cuda","dml","webnn-gpu"].includes(Z))}if(b.includes(L))return[M[L]??L];throw new Error(`Unsupported device: "${L}". Should be one of: ${b.join(", ")}.`)}let te=null;async function ne(L,Z){te&&await te;const V=G.create(L,Z);return te??(te=V),await V}function X(L){return L instanceof S.Tensor}const A=S==null?void 0:S.env;A!=null&&A.wasm&&(A.wasm.wasmPaths=`https://cdn.jsdelivr.net/npm/@huggingface/transformers@${l.env.version}/dist/`,A.wasm.proxy=!l.apis.IS_WEBWORKER_ENV,(typeof crossOriginIsolated>"u"||!crossOriginIsolated)&&(A.wasm.numThreads=1),typeof navigator<"u"&&/iP(hone|od|ad).+16_4.+AppleWebKit/.test(navigator.userAgent)&&(A.wasm.simd=!1)),A!=null&&A.webgpu&&(A.webgpu.powerPreference="high-performance");function P(){var L;return(L=A==null?void 0:A.wasm)==null?void 0:L.proxy}l.env.backends.onnx=A},"./src/configs.js":(e,n,r)=>{r.r(n),r.d(n,{AutoConfig:()=>b,PretrainedConfig:()=>M,getKeyValueShapes:()=>C});var o=r("./src/utils/core.js"),l=r("./src/utils/hub.js");async function p(F,S){return await(0,l.getModelJSON)(F,"config.json",!0,S)}function _(F){const S={};let G={};switch(F.model_type){case"llava":case"paligemma":case"florence2":G=_(F.text_config);break;case"moondream1":G=_(F.phi_config);break;case"musicgen":G=_(F.decoder);break;case"gpt2":case"gptj":case"codegen":case"gpt_bigcode":S.num_heads="n_head",S.num_layers="n_layer",S.hidden_size="n_embd";break;case"gpt_neox":case"stablelm":case"opt":case"phi":case"phi3":case"falcon":S.num_heads="num_attention_heads",S.num_layers="num_hidden_layers",S.hidden_size="hidden_size";break;case"llama":case"cohere":case"mistral":case"starcoder2":case"qwen2":S.num_heads="num_key_value_heads",S.num_layers="num_hidden_layers",S.hidden_size="hidden_size",S.num_attention_heads="num_attention_heads";break;case"gemma":case"gemma2":S.num_heads="num_key_value_heads",S.num_layers="num_hidden_layers",S.dim_kv="head_dim";break;case"openelm":S.num_heads="num_kv_heads",S.num_layers="num_transformer_layers",S.dim_kv="head_dim";break;case"gpt_neo":case"donut-swin":S.num_heads="num_heads",S.num_layers="num_layers",S.hidden_size="hidden_size";break;case"bloom":S.num_heads="n_head",S.num_layers="n_layer",S.hidden_size="hidden_size";break;case"mpt":S.num_heads="n_heads",S.num_layers="n_layers",S.hidden_size="d_model";break;case"t5":case"mt5":case"longt5":S.num_decoder_layers="num_decoder_layers",S.num_decoder_heads="num_heads",S.decoder_dim_kv="d_kv",S.num_encoder_layers="num_layers",S.num_encoder_heads="num_heads",S.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":S.num_decoder_layers="decoder_layers",S.num_decoder_heads="decoder_attention_heads",S.decoder_hidden_size="d_model",S.num_encoder_layers="encoder_layers",S.num_encoder_heads="encoder_attention_heads",S.encoder_hidden_size="d_model";break;case"speecht5":S.num_decoder_layers="decoder_layers",S.num_decoder_heads="decoder_attention_heads",S.decoder_hidden_size="hidden_size",S.num_encoder_layers="encoder_layers",S.num_encoder_heads="encoder_attention_heads",S.encoder_hidden_size="hidden_size";break;case"trocr":S.num_encoder_layers=S.num_decoder_layers="decoder_layers",S.num_encoder_heads=S.num_decoder_heads="decoder_attention_heads",S.encoder_hidden_size=S.decoder_hidden_size="d_model";break;case"musicgen_decoder":S.num_encoder_layers=S.num_decoder_layers="num_hidden_layers",S.num_encoder_heads=S.num_decoder_heads="num_attention_heads",S.encoder_hidden_size=S.decoder_hidden_size="hidden_size";break;case"vision-encoder-decoder":const te=_(F.decoder),ne="num_decoder_layers"in te,X=(0,o.pick)(F,["model_type","is_encoder_decoder"]);return ne?(X.num_decoder_layers=te.num_decoder_layers,X.num_decoder_heads=te.num_decoder_heads,X.decoder_hidden_size=te.decoder_hidden_size,X.num_encoder_layers=te.num_encoder_layers,X.num_encoder_heads=te.num_encoder_heads,X.encoder_hidden_size=te.encoder_hidden_size):(X.num_layers=te.num_layers,X.num_heads=te.num_heads,X.hidden_size=te.hidden_size),X}const J={...G,...(0,o.pick)(F,["model_type","multi_query","is_encoder_decoder"])};for(const te in S)J[te]=F[S[te]];return J}function C(F,{prefix:S="past_key_values"}={}){const G={},J=F.normalized_config,te=1;if(J.is_encoder_decoder&&"num_encoder_heads"in J&&"num_decoder_heads"in J){const ne=J.encoder_dim_kv??J.encoder_hidden_size/J.num_encoder_heads,X=J.decoder_dim_kv??J.decoder_hidden_size/J.num_decoder_heads,A=[te,J.num_encoder_heads,0,ne],P=[te,J.num_decoder_heads,0,X];for(let L=0;L{var z;r.r(n),r.d(n,{apis:()=>X,env:()=>D});var o=r("?569f"),l=r("?3f59"),p=r("?154a");const _="3.0.0-alpha.9",C=typeof self<"u",M=C&&self.constructor.name==="DedicatedWorkerGlobalScope",b=C&&"caches"in self,F=typeof navigator<"u"&&"gpu"in navigator,S=typeof navigator<"u"&&"ml"in navigator,G=typeof process<"u",J=G&&((z=process==null?void 0:process.release)==null?void 0:z.name)==="node",te=!N(o),ne=!N(l),X=Object.freeze({IS_BROWSER_ENV:C,IS_WEBWORKER_ENV:M,IS_WEB_CACHE_AVAILABLE:b,IS_WEBGPU_AVAILABLE:F,IS_WEBNN_AVAILABLE:S,IS_PROCESS_AVAILABLE:G,IS_NODE_ENV:J,IS_FS_AVAILABLE:te,IS_PATH_AVAILABLE:ne}),A=te&&ne,P=A?l.dirname(l.dirname(p.fileURLToPath(import.meta.url))):"./",L=A?l.join(P,"/.cache/"):null,Z="/models/",V=A?l.join(P,Z):Z,D={version:_,backends:{onnx:{},tfjs:{}},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!C,localModelPath:V,useFS:te,useBrowserCache:b,useFSCache:te,cacheDir:L,useCustomCache:!1,customCache:null};function N(me){return Object.keys(me).length===0}},"./src/generation/configuration_utils.js":(e,n,r)=>{r.r(n),r.d(n,{GenerationConfig:()=>l});var o=r("./src/utils/core.js");class l{constructor(_){Ee(this,"max_length",20);Ee(this,"max_new_tokens",null);Ee(this,"min_length",0);Ee(this,"min_new_tokens",null);Ee(this,"early_stopping",!1);Ee(this,"max_time",null);Ee(this,"do_sample",!1);Ee(this,"num_beams",1);Ee(this,"num_beam_groups",1);Ee(this,"penalty_alpha",null);Ee(this,"use_cache",!0);Ee(this,"temperature",1);Ee(this,"top_k",50);Ee(this,"top_p",1);Ee(this,"typical_p",1);Ee(this,"epsilon_cutoff",0);Ee(this,"eta_cutoff",0);Ee(this,"diversity_penalty",0);Ee(this,"repetition_penalty",1);Ee(this,"encoder_repetition_penalty",1);Ee(this,"length_penalty",1);Ee(this,"no_repeat_ngram_size",0);Ee(this,"bad_words_ids",null);Ee(this,"force_words_ids",null);Ee(this,"renormalize_logits",!1);Ee(this,"constraints",null);Ee(this,"forced_bos_token_id",null);Ee(this,"forced_eos_token_id",null);Ee(this,"remove_invalid_values",!1);Ee(this,"exponential_decay_length_penalty",null);Ee(this,"suppress_tokens",null);Ee(this,"begin_suppress_tokens",null);Ee(this,"forced_decoder_ids",null);Ee(this,"guidance_scale",null);Ee(this,"num_return_sequences",1);Ee(this,"output_attentions",!1);Ee(this,"output_hidden_states",!1);Ee(this,"output_scores",!1);Ee(this,"return_dict_in_generate",!1);Ee(this,"pad_token_id",null);Ee(this,"bos_token_id",null);Ee(this,"eos_token_id",null);Ee(this,"encoder_no_repeat_ngram_size",0);Ee(this,"decoder_start_token_id",null);Ee(this,"generation_kwargs",{});Object.assign(this,(0,o.pick)(_,Object.getOwnPropertyNames(this)))}}},"./src/generation/logits_process.js":(e,n,r)=>{r.r(n),r.d(n,{ClassifierFreeGuidanceLogitsProcessor:()=>A,ForcedBOSTokenLogitsProcessor:()=>M,ForcedEOSTokenLogitsProcessor:()=>b,LogitsProcessor:()=>p,LogitsProcessorList:()=>C,LogitsWarper:()=>_,MinLengthLogitsProcessor:()=>te,MinNewTokensLengthLogitsProcessor:()=>ne,NoBadWordsLogitsProcessor:()=>X,NoRepeatNGramLogitsProcessor:()=>G,RepetitionPenaltyLogitsProcessor:()=>J,SuppressTokensAtBeginLogitsProcessor:()=>F,TemperatureLogitsWarper:()=>P,TopKLogitsWarper:()=>Z,TopPLogitsWarper:()=>L,WhisperTimeStampLogitsProcessor:()=>S});var o=r("./src/utils/generic.js");r("./src/utils/tensor.js");var l=r("./src/utils/maths.js");class p extends o.Callable{_call(D,N){throw Error("`_call` should be implemented in a subclass")}}class _ extends o.Callable{_call(D,N){throw Error("`_call` should be implemented in a subclass")}}class C extends o.Callable{constructor(){super(),this.processors=[]}push(D){this.processors.push(D)}extend(D){this.processors.push(...D)}_call(D,N){let z=N;for(const me of this.processors)z=me(D,z);return z}[Symbol.iterator](){return this.processors.values()}}class M extends p{constructor(D){super(),this.bos_token_id=D}_call(D,N){for(let z=0;z=1&&ke[ke.length-1]>=this.timestamp_begin,Ae=ke.length<2||ke[ke.length-2]>=this.timestamp_begin;if($e&&(Ae?he.subarray(this.timestamp_begin).fill(-1/0):he.subarray(0,this.eos_token_id).fill(-1/0)),D[z].length===this.begin_index&&this.max_initial_timestamp_index!==null){const xe=this.timestamp_begin+this.max_initial_timestamp_index;he.subarray(xe+1).fill(-1/0)}const Je=(0,l.log_softmax)(he),Xe=Math.log(Je.subarray(this.timestamp_begin).map(Math.exp).reduce((xe,H)=>xe+H)),pt=(0,l.max)(Je.subarray(0,this.timestamp_begin))[0];Xe>pt&&he.subarray(0,this.timestamp_begin).fill(-1/0)}return N}}class G extends p{constructor(D){super(),this.no_repeat_ngram_size=D}getNgrams(D){const N=D.length,z=[];for(let he=0;he1 to use the classifier free guidance processor, got guidance scale ${D}.`);this.guidance_scale=D}_call(D,N){if(N.dims[0]!==2*D.length)throw new Error(`Logits should have twice the batch size of the input ids, the first half of batches corresponding to the conditional inputs, and the second half of batches corresponding to the unconditional inputs. Got batch size ${N.dims[0]} for the logits and ${D.length} for the input ids.`);const z=D.length,me=N.slice([0,z],null),he=N.slice([z,N.dims[0]],null);for(let ke=0;ke1)throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${D}`);if(!Number.isInteger(z)||z<1)throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${z}`);this.top_p=D,this.filter_value=N,this.min_tokens_to_keep=z}}class Z extends _{constructor(D,{filter_value:N=-1/0,min_tokens_to_keep:z=1}={}){if(super(),!Number.isInteger(D)||D<0)throw new Error(`\`top_k\` must be a positive integer, but is ${D}`);this.top_k=Math.max(D,z),this.filter_value=N}}},"./src/generation/logits_sampler.js":(e,n,r)=>{r.r(n),r.d(n,{LogitsSampler:()=>_});var o=r("./src/utils/generic.js"),l=r("./src/utils/tensor.js"),p=r("./src/utils/maths.js");r("./src/generation/configuration_utils.js");class _ extends o.Callable{constructor(S){super(),this.generation_config=S}async _call(S){return this.sample(S)}async sample(S){throw Error("sample should be implemented in subclasses.")}getLogits(S,G){let J=S.dims.at(-1),te=S.data;if(G===-1)te=te.slice(-J);else{let ne=G*J;te=te.slice(ne,ne+J)}return te}randomSelect(S){let G=0;for(let te=0;te1)return new b(S);if(S.num_return_sequences>1)throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${S.num_return_sequences}.`);return new C(S)}}class C extends _{async sample(S){const G=(0,p.max)(S.data)[1];return[[BigInt(G),0]]}}class M extends _{async sample(S){let G=S.dims.at(-1);this.generation_config.top_k>0&&(G=Math.min(this.generation_config.top_k,G));const[J,te]=await(0,l.topk)(S,G),ne=(0,p.softmax)(J.data);return Array.from({length:this.generation_config.num_beams},()=>{const X=this.randomSelect(ne);return[te.data[X],Math.log(ne[X])]})}}class b extends _{async sample(S){let G=S.dims.at(-1);this.generation_config.top_k>0&&(G=Math.min(this.generation_config.top_k,G));const[J,te]=await(0,l.topk)(S,G),ne=(0,p.softmax)(J.data);return Array.from({length:this.generation_config.num_beams},(X,A)=>[te.data[A],Math.log(ne[A])])}}},"./src/generation/stopping_criteria.js":(e,n,r)=>{r.r(n),r.d(n,{EosTokenCriteria:()=>C,InterruptableStoppingCriteria:()=>M,MaxLengthCriteria:()=>_,StoppingCriteria:()=>l,StoppingCriteriaList:()=>p});var o=r("./src/utils/generic.js");class l extends o.Callable{_call(F,S){throw Error("StoppingCriteria needs to be subclassed")}}class p extends o.Callable{constructor(){super(),this.criteria=[]}push(F){this.criteria.push(F)}extend(F){F instanceof p?F=F.criteria:F instanceof l&&(F=[F]),this.criteria.push(...F)}_call(F,S){const G=new Array(F.length).fill(!1);for(const J of this.criteria){const te=J(F,S);for(let ne=0;neS.length>=this.max_length)}}class C extends l{constructor(F){super(),Array.isArray(F)||(F=[F]),this.eos_token_id=F}_call(F,S){return F.map(G=>{const J=G.at(-1);return this.eos_token_id.some(te=>J==te)})}}class M extends l{constructor(){super(),this.interrupted=!1}interrupt(){this.interrupted=!0}reset(){this.interrupted=!1}_call(F,S){return new Array(F.length).fill(this.interrupted)}}},"./src/generation/streamers.js":(e,n,r)=>{r.r(n),r.d(n,{BaseStreamer:()=>_,TextStreamer:()=>M,WhisperTextStreamer:()=>b});var o=r("./src/utils/core.js"),l=r("./src/tokenizers.js"),p=r("./src/env.js");class _{put(S){throw Error("Not implemented")}end(){throw Error("Not implemented")}}const C=p.apis.IS_PROCESS_AVAILABLE?F=>process.stdout.write(F):F=>console.log(F);class M extends _{constructor(S,{skip_prompt:G=!1,callback_function:J=null,token_callback_function:te=null,decode_kwargs:ne={},...X}={}){super(),this.tokenizer=S,this.skip_prompt=G,this.callback_function=J??C,this.token_callback_function=te,this.decode_kwargs={...ne,...X},this.token_cache=[],this.print_len=0,this.next_tokens_are_prompt=!0}put(S){var ne;if(S.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 G=S[0];(ne=this.token_callback_function)==null||ne.call(this,G),this.token_cache=(0,o.mergeArrays)(this.token_cache,G);const J=this.tokenizer.decode(this.token_cache,this.decode_kwargs);let te;J.endsWith(` +`)?(te=J.slice(this.print_len),this.token_cache=[],this.print_len=0):J.length>0&&(0,l.is_chinese_char)(J.charCodeAt(J.length-1))?(te=J.slice(this.print_len),this.print_len+=te.length):(te=J.slice(this.print_len,J.lastIndexOf(" ")+1),this.print_len+=te.length),this.on_finalized_text(te,!1)}end(){let S;this.token_cache.length>0?(S=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len),this.token_cache=[],this.print_len=0):S="",this.next_tokens_are_prompt=!0,this.on_finalized_text(S,!0)}on_finalized_text(S,G){var J,te;S.length>0&&((J=this.callback_function)==null||J.call(this,S)),G&&this.callback_function===C&&p.apis.IS_PROCESS_AVAILABLE&&((te=this.callback_function)==null||te.call(this,` +`))}}class b extends M{constructor(S,{skip_prompt:G=!1,callback_function:J=null,token_callback_function:te=null,on_chunk_start:ne=null,on_chunk_end:X=null,on_finalize:A=null,time_precision:P=.02,skip_special_tokens:L=!0,decode_kwargs:Z={}}={}){super(S,{skip_prompt:G,callback_function:J,token_callback_function:te,decode_kwargs:{skip_special_tokens:L,...Z}}),this.timestamp_begin=S.timestamp_begin,this.on_chunk_start=ne,this.on_chunk_end=X,this.on_finalize=A,this.time_precision=P,this.waiting_for_timestamp=!1}put(S){var J,te;if(S.length>1)throw Error("WhisperTextStreamer only supports batch size of 1");const G=S[0];if(G.length===1){const ne=Number(G[0])-this.timestamp_begin;if(ne>=0){const X=ne*this.time_precision;this.waiting_for_timestamp?(J=this.on_chunk_end)==null||J.call(this,X):(te=this.on_chunk_start)==null||te.call(this,X),this.waiting_for_timestamp=!this.waiting_for_timestamp,S=[[]]}}return super.put(S)}end(){var S;super.end(),(S=this.on_finalize)==null||S.call(this)}}},"./src/models.js":(e,n,r)=>{r.r(n),r.d(n,{ASTForAudioClassification:()=>bs,ASTModel:()=>Ot,ASTPreTrainedModel:()=>Dr,AlbertForMaskedLM:()=>Xt,AlbertForQuestionAnswering:()=>lo,AlbertForSequenceClassification:()=>ao,AlbertModel:()=>Ki,AlbertPreTrainedModel:()=>vi,AutoModel:()=>Ec,AutoModelForAudioClassification:()=>Rc,AutoModelForAudioFrameClassification:()=>Nc,AutoModelForCTC:()=>Bc,AutoModelForCausalLM:()=>Ac,AutoModelForDepthEstimation:()=>Uc,AutoModelForDocumentQuestionAnswering:()=>cf,AutoModelForImageClassification:()=>zc,AutoModelForImageFeatureExtraction:()=>Wc,AutoModelForImageMatting:()=>jc,AutoModelForImageSegmentation:()=>hl,AutoModelForImageToImage:()=>Vc,AutoModelForMaskGeneration:()=>ml,AutoModelForMaskedLM:()=>Ic,AutoModelForObjectDetection:()=>Dc,AutoModelForQuestionAnswering:()=>fl,AutoModelForSemanticSegmentation:()=>Oc,AutoModelForSeq2SeqLM:()=>$c,AutoModelForSequenceClassification:()=>br,AutoModelForSpeechSeq2Seq:()=>pl,AutoModelForTextToSpectrogram:()=>Pc,AutoModelForTextToWaveform:()=>Go,AutoModelForTokenClassification:()=>Cc,AutoModelForVision2Seq:()=>Fc,AutoModelForXVector:()=>gl,AutoModelForZeroShotObjectDetection:()=>Lc,BartForConditionalGeneration:()=>T,BartForSequenceClassification:()=>Q,BartModel:()=>Se,BartPretrainedModel:()=>zr,BaseModelOutput:()=>ut,BeitForImageClassification:()=>Zu,BeitModel:()=>Yu,BeitPreTrainedModel:()=>Ta,BertForMaskedLM:()=>Oe,BertForQuestionAnswering:()=>Be,BertForSequenceClassification:()=>rt,BertForTokenClassification:()=>Tt,BertModel:()=>st,BertPreTrainedModel:()=>Ye,BlenderbotForConditionalGeneration:()=>Pt,BlenderbotModel:()=>vt,BlenderbotPreTrainedModel:()=>Mt,BlenderbotSmallForConditionalGeneration:()=>nn,BlenderbotSmallModel:()=>$n,BlenderbotSmallPreTrainedModel:()=>Zt,BloomForCausalLM:()=>Fu,BloomModel:()=>Iu,BloomPreTrainedModel:()=>Ss,CLIPModel:()=>eu,CLIPPreTrainedModel:()=>Ro,CLIPSegForImageSegmentation:()=>au,CLIPSegModel:()=>su,CLIPSegPreTrainedModel:()=>ua,CLIPTextModelWithProjection:()=>li,CLIPVisionModelWithProjection:()=>tu,CamembertForMaskedLM:()=>Te,CamembertForQuestionAnswering:()=>je,CamembertForSequenceClassification:()=>Ne,CamembertForTokenClassification:()=>De,CamembertModel:()=>le,CamembertPreTrainedModel:()=>j,CausalLMOutput:()=>Xi,CausalLMOutputWithPast:()=>pf,ChineseCLIPModel:()=>ou,ChineseCLIPPreTrainedModel:()=>iu,ClapAudioModelWithProjection:()=>ec,ClapModel:()=>Zd,ClapPreTrainedModel:()=>jo,ClapTextModelWithProjection:()=>Jd,CodeGenForCausalLM:()=>xs,CodeGenModel:()=>_u,CodeGenPreTrainedModel:()=>Wr,CohereForCausalLM:()=>vu,CohereModel:()=>wu,CoherePreTrainedModel:()=>ha,ConvBertForMaskedLM:()=>O,ConvBertForQuestionAnswering:()=>de,ConvBertForSequenceClassification:()=>ie,ConvBertForTokenClassification:()=>q,ConvBertModel:()=>xt,ConvBertPreTrainedModel:()=>wt,ConvNextForImageClassification:()=>Md,ConvNextModel:()=>vd,ConvNextPreTrainedModel:()=>La,ConvNextV2ForImageClassification:()=>Td,ConvNextV2Model:()=>xd,ConvNextV2PreTrainedModel:()=>bd,DPTForDepthEstimation:()=>za,DPTModel:()=>Fa,DPTPreTrainedModel:()=>Ia,DebertaForMaskedLM:()=>bt,DebertaForQuestionAnswering:()=>Nt,DebertaForSequenceClassification:()=>ft,DebertaForTokenClassification:()=>St,DebertaModel:()=>ot,DebertaPreTrainedModel:()=>ct,DebertaV2ForMaskedLM:()=>jt,DebertaV2ForQuestionAnswering:()=>Jt,DebertaV2ForSequenceClassification:()=>Kt,DebertaV2ForTokenClassification:()=>Qt,DebertaV2Model:()=>Vt,DebertaV2PreTrainedModel:()=>Ke,DeiTForImageClassification:()=>ud,DeiTModel:()=>ld,DeiTPreTrainedModel:()=>Ea,DepthAnythingForDepthEstimation:()=>gd,DepthAnythingPreTrainedModel:()=>md,DetrForObjectDetection:()=>ed,DetrForSegmentation:()=>td,DetrModel:()=>Ju,DetrObjectDetectionOutput:()=>Sa,DetrPreTrainedModel:()=>Cs,DetrSegmentationOutput:()=>nd,Dinov2ForImageClassification:()=>kd,Dinov2Model:()=>Sd,Dinov2PreTrainedModel:()=>qr,DistilBertForMaskedLM:()=>Ct,DistilBertForQuestionAnswering:()=>tt,DistilBertForSequenceClassification:()=>Hn,DistilBertForTokenClassification:()=>Cn,DistilBertModel:()=>En,DistilBertPreTrainedModel:()=>qt,DonutSwinModel:()=>Da,DonutSwinPreTrainedModel:()=>wd,EfficientNetForImageClassification:()=>oc,EfficientNetModel:()=>ic,EfficientNetPreTrainedModel:()=>rl,ElectraForMaskedLM:()=>nt,ElectraForQuestionAnswering:()=>Pe,ElectraForSequenceClassification:()=>At,ElectraForTokenClassification:()=>_t,ElectraModel:()=>et,ElectraPreTrainedModel:()=>ve,EsmForMaskedLM:()=>Fi,EsmForSequenceClassification:()=>_i,EsmForTokenClassification:()=>Nn,EsmModel:()=>nr,EsmPreTrainedModel:()=>Lt,FalconForCausalLM:()=>Yd,FalconModel:()=>Xd,FalconPreTrainedModel:()=>Ja,FastViTForImageClassification:()=>Nu,FastViTModel:()=>Ru,FastViTPreTrainedModel:()=>Es,Florence2ForConditionalGeneration:()=>aa,Florence2PreTrainedModel:()=>Jl,GLPNForDepthEstimation:()=>yd,GLPNModel:()=>_d,GLPNPreTrainedModel:()=>Oa,GPT2LMHeadModel:()=>uu,GPT2Model:()=>lu,GPT2PreTrainedModel:()=>da,GPTBigCodeForCausalLM:()=>Up,GPTBigCodeModel:()=>gu,GPTBigCodePreTrainedModel:()=>fa,GPTJForCausalLM:()=>mu,GPTJModel:()=>hu,GPTJPreTrainedModel:()=>pa,GPTNeoForCausalLM:()=>cu,GPTNeoModel:()=>du,GPTNeoPreTrainedModel:()=>Ur,GPTNeoXForCausalLM:()=>fu,GPTNeoXModel:()=>pu,GPTNeoXPreTrainedModel:()=>ca,Gemma2ForCausalLM:()=>Tu,Gemma2Model:()=>xu,Gemma2PreTrainedModel:()=>ga,GemmaForCausalLM:()=>bu,GemmaModel:()=>Mu,GemmaPreTrainedModel:()=>ma,HubertForCTC:()=>jd,HubertForSequenceClassification:()=>qa,HubertModel:()=>Qp,HubertPreTrainedModel:()=>Kp,ImageMattingOutput:()=>qc,LlamaForCausalLM:()=>yu,LlamaModel:()=>Jr,LlamaPreTrainedModel:()=>Ts,LlavaForConditionalGeneration:()=>po,LlavaPreTrainedModel:()=>Zl,LongT5ForConditionalGeneration:()=>Lo,LongT5Model:()=>Do,LongT5PreTrainedModel:()=>uo,M2M100ForConditionalGeneration:()=>Od,M2M100Model:()=>zd,M2M100PreTrainedModel:()=>Na,MBartForCausalLM:()=>yt,MBartForConditionalGeneration:()=>we,MBartForSequenceClassification:()=>Le,MBartModel:()=>ye,MBartPreTrainedModel:()=>ce,MPNetForMaskedLM:()=>Po,MPNetForQuestionAnswering:()=>Fo,MPNetForSequenceClassification:()=>Ao,MPNetForTokenClassification:()=>Io,MPNetModel:()=>vs,MPNetPreTrainedModel:()=>yi,MT5ForConditionalGeneration:()=>Rn,MT5Model:()=>Bo,MT5PreTrainedModel:()=>co,MarianMTModel:()=>Fd,MarianModel:()=>qp,MarianPreTrainedModel:()=>Ra,MaskedLMOutput:()=>hr,MistralForCausalLM:()=>Os,MistralModel:()=>zs,MistralPreTrainedModel:()=>Xa,MobileBertForMaskedLM:()=>si,MobileBertForQuestionAnswering:()=>zi,MobileBertForSequenceClassification:()=>Fn,MobileBertModel:()=>Vn,MobileBertPreTrainedModel:()=>cr,MobileNetV1ForImageClassification:()=>Jp,MobileNetV1Model:()=>sc,MobileNetV1PreTrainedModel:()=>sl,MobileNetV2ForImageClassification:()=>lc,MobileNetV2Model:()=>ac,MobileNetV2PreTrainedModel:()=>al,MobileNetV3ForImageClassification:()=>ef,MobileNetV3Model:()=>uc,MobileNetV3PreTrainedModel:()=>ll,MobileNetV4ForImageClassification:()=>ul,MobileNetV4Model:()=>Wo,MobileNetV4PreTrainedModel:()=>Uo,MobileViTForImageClassification:()=>Gu,MobileViTModel:()=>Wu,MobileViTPreTrainedModel:()=>Uu,MobileViTV2ForImageClassification:()=>qu,MobileViTV2Model:()=>Gp,MobileViTV2PreTrainedModel:()=>ba,ModelOutput:()=>Fe,Moondream1ForConditionalGeneration:()=>sn,MptForCausalLM:()=>zu,MptModel:()=>Wp,MptPreTrainedModel:()=>ks,MusicgenForCausalLM:()=>Zh,MusicgenForConditionalGeneration:()=>ol,MusicgenModel:()=>Zp,MusicgenPreTrainedModel:()=>il,NomicBertModel:()=>Ce,NomicBertPreTrainedModel:()=>fe,OPTForCausalLM:()=>Du,OPTModel:()=>Ou,OPTPreTrainedModel:()=>Ma,OpenELMForCausalLM:()=>ku,OpenELMModel:()=>Su,OpenELMPreTrainedModel:()=>Gr,OwlViTForObjectDetection:()=>Ku,OwlViTModel:()=>Hu,OwlViTPreTrainedModel:()=>vn,Owlv2ForObjectDetection:()=>Xu,Owlv2Model:()=>Qu,Owlv2PreTrainedModel:()=>xa,Phi3ForCausalLM:()=>va,Phi3Model:()=>Au,Phi3PreTrainedModel:()=>wa,PhiForCausalLM:()=>Pu,PhiModel:()=>$u,PhiPreTrainedModel:()=>ya,PreTrainedModel:()=>se,PretrainedMixin:()=>On,PyAnnoteForAudioFrameClassification:()=>Ri,PyAnnoteModel:()=>ja,PyAnnotePreTrainedModel:()=>Mi,QuestionAnsweringModelOutput:()=>mr,Qwen2ForCausalLM:()=>Cu,Qwen2Model:()=>Eu,Qwen2PreTrainedModel:()=>_a,RTDetrForObjectDetection:()=>$s,RTDetrModel:()=>rd,RTDetrObjectDetectionOutput:()=>id,RTDetrPreTrainedModel:()=>mo,ResNetForImageClassification:()=>cd,ResNetModel:()=>dd,ResNetPreTrainedModel:()=>Ca,RoFormerForMaskedLM:()=>We,RoFormerForQuestionAnswering:()=>mt,RoFormerForSequenceClassification:()=>He,RoFormerForTokenClassification:()=>dt,RoFormerModel:()=>Ge,RoFormerPreTrainedModel:()=>Ue,RobertaForMaskedLM:()=>Mr,RobertaForQuestionAnswering:()=>Vr,RobertaForSequenceClassification:()=>ur,RobertaForTokenClassification:()=>Ve,RobertaModel:()=>mn,RobertaPreTrainedModel:()=>Gt,SamImageSegmentationOutput:()=>Id,SamModel:()=>Ad,SamPreTrainedModel:()=>Pd,SegformerForImageClassification:()=>tc,SegformerForSemanticSegmentation:()=>nc,SegformerModel:()=>Yh,SegformerPreTrainedModel:()=>Vo,Seq2SeqLMOutput:()=>em,SequenceClassifierOutput:()=>dn,SiglipModel:()=>fo,SiglipPreTrainedModel:()=>la,SiglipTextModel:()=>nu,SiglipVisionModel:()=>ru,SpeechT5ForSpeechToText:()=>Hd,SpeechT5ForTextToSpeech:()=>Xp,SpeechT5HifiGan:()=>Qa,SpeechT5Model:()=>qd,SpeechT5PreTrainedModel:()=>Ka,SqueezeBertForMaskedLM:()=>so,SqueezeBertForQuestionAnswering:()=>wi,SqueezeBertForSequenceClassification:()=>ai,SqueezeBertModel:()=>Ms,SqueezeBertPreTrainedModel:()=>Oi,StableLmForCausalLM:()=>rc,StableLmModel:()=>nl,StableLmPreTrainedModel:()=>tl,Starcoder2ForCausalLM:()=>Za,Starcoder2Model:()=>Ds,Starcoder2PreTrainedModel:()=>Ya,Swin2SRForImageSuperResolution:()=>Aa,Swin2SRModel:()=>hd,Swin2SRPreTrainedModel:()=>Pa,SwinForImageClassification:()=>fd,SwinModel:()=>pd,SwinPreTrainedModel:()=>$a,T5ForConditionalGeneration:()=>Oo,T5Model:()=>zo,T5PreTrainedModel:()=>Qi,TableTransformerForObjectDetection:()=>sd,TableTransformerModel:()=>od,TableTransformerObjectDetectionOutput:()=>ad,TableTransformerPreTrainedModel:()=>ka,TokenClassifierOutput:()=>ar,TrOCRForCausalLM:()=>Qd,TrOCRPreTrainedModel:()=>Kd,UniSpeechForCTC:()=>Ld,UniSpeechForSequenceClassification:()=>Bd,UniSpeechModel:()=>Ua,UniSpeechPreTrainedModel:()=>go,UniSpeechSatForAudioFrameClassification:()=>As,UniSpeechSatForCTC:()=>Wa,UniSpeechSatForSequenceClassification:()=>Rd,UniSpeechSatModel:()=>Ps,UniSpeechSatPreTrainedModel:()=>No,ViTForImageClassification:()=>Bu,ViTModel:()=>Lu,ViTPreTrainedModel:()=>ho,VisionEncoderDecoderModel:()=>sa,VitMatteForImageMatting:()=>Vu,VitMattePreTrainedModel:()=>ju,VitsModel:()=>el,VitsModelOutput:()=>ff,VitsPreTrainedModel:()=>Yp,Wav2Vec2BertForCTC:()=>Fs,Wav2Vec2BertForSequenceClassification:()=>Nd,Wav2Vec2BertModel:()=>Ga,Wav2Vec2BertPreTrainedModel:()=>Is,Wav2Vec2ForAudioFrameClassification:()=>Bi,Wav2Vec2ForCTC:()=>Hp,Wav2Vec2ForSequenceClassification:()=>Li,Wav2Vec2Model:()=>Dd,Wav2Vec2PreTrainedModel:()=>Di,WavLMForAudioFrameClassification:()=>Gd,WavLMForCTC:()=>Ha,WavLMForSequenceClassification:()=>Ud,WavLMForXVector:()=>Wd,WavLMModel:()=>Vd,WavLMPreTrainedModel:()=>bi,WeSpeakerResNetModel:()=>Va,WeSpeakerResNetPreTrainedModel:()=>fr,WhisperForConditionalGeneration:()=>oa,WhisperModel:()=>Ut,WhisperPreTrainedModel:()=>it,XLMForQuestionAnswering:()=>pr,XLMForSequenceClassification:()=>Yt,XLMForTokenClassification:()=>Or,XLMModel:()=>rr,XLMPreTrainedModel:()=>bn,XLMRobertaForMaskedLM:()=>Et,XLMRobertaForQuestionAnswering:()=>Un,XLMRobertaForSequenceClassification:()=>wn,XLMRobertaForTokenClassification:()=>zn,XLMRobertaModel:()=>Sn,XLMRobertaPreTrainedModel:()=>Tn,XLMWithLMHeadModel:()=>kr,XVectorOutput:()=>Gc,YolosForObjectDetection:()=>Cd,YolosModel:()=>Ed,YolosObjectDetectionOutput:()=>$d,YolosPreTrainedModel:()=>Ba});var o=r("./src/configs.js"),l=r("./src/backends/onnx.js"),p=r("./src/utils/dtypes.js"),_=r("./src/utils/generic.js"),C=r("./src/utils/core.js"),M=r("./src/utils/hub.js"),b=r("./src/generation/logits_process.js"),F=r("./src/generation/configuration_utils.js"),S=r("./src/utils/tensor.js"),G=r("./src/utils/maths.js"),J=r("./src/generation/stopping_criteria.js"),te=r("./src/generation/logits_sampler.js"),ne=r("./src/env.js"),X=r("./src/models/whisper/generation_whisper.js"),A=r("./src/models/whisper/common_whisper.js");const P={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,MaskGeneration:5,ImageTextToText:6,Musicgen:7},L=new Map,Z=new Map,V=new Map;async function D(x,k,U){let ue=U.device;ue&&typeof ue!="string"&&(ue.hasOwnProperty(k)?ue=ue[k]:(console.warn(`device not specified for "${k}". Using the default device.`),ue=null));const Ie=ue??(ne.apis.IS_NODE_ENV?"cpu":"wasm"),Re=(0,l.deviceToExecutionProviders)(Ie);let at=U.dtype;typeof at!="string"&&(at&&at.hasOwnProperty(k)?at=at[k]:(at=p.DEFAULT_DEVICE_DTYPE_MAPPING[Ie]??p.DATA_TYPES.fp32,console.warn(`dtype not specified for "${k}". Using the default dtype (${at}) for this device (${Ie}).`)));const kt=at;if(p.DEFAULT_DTYPE_SUFFIX_MAPPING.hasOwnProperty(kt)){if(kt===p.DATA_TYPES.fp16&&Ie==="webgpu"&&!await(0,p.isWebGpuFp16Supported)())throw new Error(`The device (${Ie}) does not support fp16.`)}else throw new Error(`Invalid dtype: ${kt}. Should be one of: ${Object.keys(p.DATA_TYPES).join(", ")}`);const Wt=p.DEFAULT_DTYPE_SUFFIX_MAPPING[kt],cn=`${U.subfolder??""}/${k}${Wt}.onnx`,an={...U.session_options};an.executionProviders??(an.executionProviders=Re);const Pn=(0,M.getModelFile)(x,cn,!0,U);let pn=[];if(U.use_external_data_format&&(U.use_external_data_format===!0||typeof U.use_external_data_format=="object"&&U.use_external_data_format.hasOwnProperty(k)&&U.use_external_data_format[k]===!0)){if(ne.apis.IS_NODE_ENV)throw new Error("External data format is not yet supported in Node.js");const fn=`${k}${Wt}.onnx_data`,gn=`${U.subfolder??""}/${fn}`;pn.push(new Promise(async(Mn,Dn)=>{const xr=await(0,M.getModelFile)(x,gn,!0,U);Mn({path:fn,data:xr})}))}else an.externalData!==void 0&&(pn=an.externalData.map(async fn=>{if(typeof fn.data=="string"){const gn=await(0,M.getModelFile)(x,fn.data,!0,U);return{...fn,data:gn}}return fn}));if(pn.length>0&&(an.externalData=await Promise.all(pn)),Ie==="webgpu"){const fn=(0,o.getKeyValueShapes)(U.config,{prefix:"present"});if(Object.keys(fn).length>0&&!(0,l.isONNXProxy)()){const gn={};for(const Mn in fn)gn[Mn]="gpu-buffer";an.preferredOutputLocation=gn}}return{buffer:await Pn,session_options:an}}async function N(x,k,U){return Object.fromEntries(await Promise.all(Object.keys(k).map(async ue=>{const{buffer:Ie,session_options:Re}=await D(x,k[ue],U),at=await(0,l.createInferenceSession)(Ie,Re);return[ue,at]})))}function z(x,k){const U=Object.create(null),ue=[];for(const at of x.inputNames){const kt=k[at];if(!(kt instanceof S.Tensor)){ue.push(at);continue}U[at]=(0,l.isONNXProxy)()?kt.clone():kt}if(ue.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${ue.join(", ")}.`);const Ie=Object.keys(k).length,Re=x.inputNames.length;if(Ie>Re){let at=Object.keys(k).filter(kt=>!x.inputNames.includes(kt));console.warn(`WARNING: Too many inputs were provided (${Ie} > ${Re}). The following inputs will be ignored: "${at.join(", ")}".`)}return U}async function me(x,k){const U=z(x,k);try{const ue=Object.fromEntries(Object.entries(U).map(([Re,at])=>[Re,at.ort_tensor]));let Ie=await x.run(ue);return Ie=he(Ie),Ie}catch(ue){throw console.error(`An error occurred during model execution: "${ue}".`),console.error("Inputs given to model:",U),ue}}function he(x){for(let k in x)(0,l.isONNXTensor)(x[k])?x[k]=new S.Tensor(x[k]):typeof x[k]=="object"&&he(x[k]);return x}function ke(x){if(x instanceof S.Tensor)return x;if(x.length===0)throw Error("items must be non-empty");if(Array.isArray(x[0])){if(x.some(k=>k.length!==x[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 S.Tensor("int64",BigInt64Array.from(x.flat().map(k=>BigInt(k))),[x.length,x[0].length])}else return new S.Tensor("int64",BigInt64Array.from(x.map(k=>BigInt(k))),[1,x.length])}function $e(x){return new S.Tensor("bool",[x],[1])}async function Ae(x,k){let{encoder_outputs:U,input_ids:ue,decoder_input_ids:Ie,...Re}=k;if(!U){const kt=(0,C.pick)(k,x.sessions.model.inputNames);U=(await Je(x,kt)).last_hidden_state}return Re.input_ids=Ie,Re.encoder_hidden_states=U,x.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(Re.encoder_attention_mask=k.attention_mask),await Xe(x,Re,!0)}async function Je(x,k){const U=x.sessions.model,ue=(0,C.pick)(k,U.inputNames);if(U.inputNames.includes("inputs_embeds")&&!ue.inputs_embeds){if(!k.input_ids)throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");ue.inputs_embeds=await x.encode_text({input_ids:k.input_ids})}return U.inputNames.includes("token_type_ids")&&!ue.token_type_ids&&(ue.token_type_ids=new S.Tensor("int64",new BigInt64Array(ue.input_ids.data.length),ue.input_ids.dims)),await me(U,ue)}async function Xe(x,k,U=!1){const ue=x.sessions[U?"decoder_model_merged":"model"],{past_key_values:Ie,...Re}=k;ue.inputNames.includes("use_cache_branch")&&(Re.use_cache_branch=$e(!!Ie)),ue.inputNames.includes("position_ids")&&Re.attention_mask&&!Re.position_ids&&(Re.position_ids=xe(Re,Ie)),x.addPastKeyValues(Re,Ie);const at=(0,C.pick)(Re,ue.inputNames);return await me(ue,at)}async function pt(x,{input_ids:k=null,attention_mask:U=null,pixel_values:ue=null,position_ids:Ie=null,inputs_embeds:Re=null,past_key_values:at=null,generation_config:kt=null,logits_processor:Wt=null,...cn}){if(!Re){if(Re=await x.encode_text({input_ids:k}),ue&&k.dims[1]!==1){const Pn=await x.encode_image({pixel_values:ue});({inputs_embeds:Re,attention_mask:U}=x._merge_input_ids_with_image_features({image_features:Pn,inputs_embeds:Re,input_ids:k,attention_mask:U}))}else if(at&&ue&&k.dims[1]===1){const Pn=k.dims[1],pn=Object.values(at)[0].dims.at(-2);U=(0,S.cat)([(0,S.ones)([k.dims[0],pn]),U.slice(null,[U.dims[1]-Pn,U.dims[1]])],1)}}return await Xe(x,{inputs_embeds:Re,past_key_values:at,attention_mask:U,position_ids:Ie,generation_config:kt,logits_processor:Wt},!0)}function xe(x,k=null){const{input_ids:U,inputs_embeds:ue,attention_mask:Ie}=x,[Re,at]=Ie.dims,kt=new BigInt64Array(Ie.data.length);for(let cn=0;cnRe.dims[1])){if(Iekt==x.config.image_token_index)){const kt=x.config.num_image_tokens;if(!kt)throw new Error("`num_image_tokens` is missing in the model configuration.");const Wt=Re.dims[1]-(Ie-kt);U.input_ids=Re.slice(null,[-Wt,null]),U.attention_mask=(0,S.ones)([1,Ie+Wt])}}}return U}function pe(x,k,U,ue){return U.past_key_values&&(k=k.map(Ie=>[Ie.at(-1)])),{...U,decoder_input_ids:ke(k)}}function Me(x,...k){return x.config.is_encoder_decoder?pe(x,...k):H(x,...k)}class se extends _.Callable{constructor(U,ue){super();Ee(this,"main_input_name","input_ids");Ee(this,"forward_params",["input_ids","attention_mask"]);this.config=U,this.sessions=ue;const Ie=V.get(this.constructor),Re=L.get(Ie);switch(this.can_generate=!1,this._forward=null,this._prepare_inputs_for_generation=null,Re){case P.DecoderOnly:this.can_generate=!0,this._forward=Xe,this._prepare_inputs_for_generation=H;break;case P.Seq2Seq:case P.Vision2Seq:case P.Musicgen:this.can_generate=!0,this._forward=Ae,this._prepare_inputs_for_generation=pe;break;case P.EncoderDecoder:this._forward=Ae;break;case P.ImageTextToText:this.can_generate=!0,this._forward=pt,this._prepare_inputs_for_generation=Me;break;default:this._forward=Je;break}this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){var ue;const U=[];for(const Ie of Object.values(this.sessions))(ue=Ie==null?void 0:Ie.handler)!=null&&ue.dispose&&U.push(Ie.handler.dispose());return await Promise.all(U)}static async from_pretrained(U,{progress_callback:ue=null,config:Ie=null,cache_dir:Re=null,local_files_only:at=!1,revision:kt="main",model_file_name:Wt=null,subfolder:cn="onnx",device:an=null,dtype:Pn=null,use_external_data_format:pn=null,session_options:_n={}}={}){let fn={progress_callback:ue,config:Ie,cache_dir:Re,local_files_only:at,revision:kt,model_file_name:Wt,subfolder:cn,device:an,dtype:Pn,use_external_data_format:pn,session_options:_n};const gn=V.get(this),Mn=L.get(gn);Ie=fn.config=await o.AutoConfig.from_pretrained(U,fn);let Dn;if(Mn===P.DecoderOnly)Dn=await Promise.all([N(U,{model:fn.model_file_name??"model"},fn),(0,M.getModelJSON)(U,"generation_config.json",!1,fn)]);else if(Mn===P.Seq2Seq||Mn===P.Vision2Seq)Dn=await Promise.all([N(U,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},fn),(0,M.getModelJSON)(U,"generation_config.json",!1,fn)]);else if(Mn===P.MaskGeneration)Dn=await Promise.all([N(U,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},fn)]);else if(Mn===P.EncoderDecoder)Dn=await Promise.all([N(U,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},fn)]);else if(Mn===P.ImageTextToText){const xr={embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};Ie.is_encoder_decoder&&(xr.model="encoder_model"),Dn=await Promise.all([N(U,xr,fn),(0,M.getModelJSON)(U,"generation_config.json",!1,fn)])}else Mn===P.Musicgen?Dn=await Promise.all([N(U,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},fn),(0,M.getModelJSON)(U,"generation_config.json",!1,fn)]):(Mn!==P.EncoderOnly&&console.warn(`Model type for '${gn??(Ie==null?void 0:Ie.model_type)}' not found, assuming encoder-only architecture. Please report this at https://github.com/xenova/transformers.js/issues/new/choose.`),Dn=await Promise.all([N(U,{model:fn.model_file_name??"model"},fn)]));return new this(Ie,...Dn)}async _call(U){return await this.forward(U)}async forward(U){return await this._forward(this,U)}_get_logits_warper(U){const ue=new b.LogitsProcessorList;return U.temperature!==null&&U.temperature!==1&&ue.push(new b.TemperatureLogitsWarper(U.temperature)),U.top_k!==null&&U.top_k!==0&&ue.push(new b.TopKLogitsWarper(U.top_k)),U.top_p!==null&&U.top_p<1&&ue.push(new b.TopPLogitsWarper(U.top_p)),ue}_get_logits_processor(U,ue,Ie=null){const Re=new b.LogitsProcessorList;if(U.repetition_penalty!==null&&U.repetition_penalty!==1&&Re.push(new b.RepetitionPenaltyLogitsProcessor(U.repetition_penalty)),U.no_repeat_ngram_size!==null&&U.no_repeat_ngram_size>0&&Re.push(new b.NoRepeatNGramLogitsProcessor(U.no_repeat_ngram_size)),U.bad_words_ids!==null&&Re.push(new b.NoBadWordsLogitsProcessor(U.bad_words_ids,U.eos_token_id)),U.min_length!==null&&U.eos_token_id!==null&&U.min_length>0&&Re.push(new b.MinLengthLogitsProcessor(U.min_length,U.eos_token_id)),U.min_new_tokens!==null&&U.eos_token_id!==null&&U.min_new_tokens>0&&Re.push(new b.MinNewTokensLengthLogitsProcessor(ue,U.min_new_tokens,U.eos_token_id)),U.forced_bos_token_id!==null&&Re.push(new b.ForcedBOSTokenLogitsProcessor(U.forced_bos_token_id)),U.forced_eos_token_id!==null&&Re.push(new b.ForcedEOSTokenLogitsProcessor(U.max_length,U.forced_eos_token_id)),U.begin_suppress_tokens!==null){const at=ue>1||U.forced_bos_token_id===null?ue:ue+1;Re.push(new b.SuppressTokensAtBeginLogitsProcessor(U.begin_suppress_tokens,at))}return U.guidance_scale!==null&&U.guidance_scale>1&&Re.push(new b.ClassifierFreeGuidanceLogitsProcessor(U.guidance_scale)),Ie!==null&&Re.extend(Ie),Re}_prepare_generation_config(U,ue,Ie=F.GenerationConfig){const Re={...this.config};for(const kt of["decoder","generator","text_config"])kt in Re&&Object.assign(Re,Re[kt]);const at=new Ie(Re);return"generation_config"in this&&Object.assign(at,this.generation_config),U&&Object.assign(at,U),ue&&Object.assign(at,(0,C.pick)(ue,Object.getOwnPropertyNames(at))),at}_get_stopping_criteria(U,ue=null){const Ie=new J.StoppingCriteriaList;return U.max_length!==null&&Ie.push(new J.MaxLengthCriteria(U.max_length,this.config.max_position_embeddings??null)),U.eos_token_id!==null&&Ie.push(new J.EosTokenCriteria(U.eos_token_id)),ue&&Ie.extend(ue),Ie}_validate_model_class(){if(!this.can_generate){const U=[Bs,cl,dl,Ls],ue=V.get(this.constructor),Ie=new Set,Re=this.config.model_type;for(const kt of U){const Wt=kt.get(Re);Wt&&Ie.add(Wt[0])}let at=`The current model class (${ue}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw Ie.size>0&&(at+=` Please use the following class instead: ${[...Ie].join(", ")}`),Error(at)}}prepare_inputs_for_generation(...U){return this._prepare_inputs_for_generation(this,...U)}_update_model_kwargs_for_generation({generated_input_ids:U,outputs:ue,model_inputs:Ie,is_encoder_decoder:Re}){return Ie.past_key_values=this.getPastKeyValues(ue,Ie.past_key_values),Ie.input_ids=new S.Tensor("int64",U.flat(),[U.length,1]),Re||(Ie.attention_mask=(0,S.cat)([Ie.attention_mask,(0,S.ones)([Ie.attention_mask.dims[0],1])],1)),Ie.position_ids=null,Ie}_prepare_model_inputs({inputs:U,bos_token_id:ue,model_kwargs:Ie}){const Re=(0,C.pick)(Ie,this.forward_params),at=this.main_input_name;if(at in Re){if(U)throw new Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else Re[at]=U;return{inputs_tensor:Re[at],model_inputs:Re,model_input_name:at}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:U,model_inputs:ue,model_input_name:Ie,generation_config:Re}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!ue.inputs_embeds&&"_prepare_inputs_embeds"in this){const{input_ids:kt,pixel_values:Wt,attention_mask:cn,...an}=ue,Pn=await this._prepare_inputs_embeds(ue);ue={...an,...(0,C.pick)(Pn,["inputs_embeds","attention_mask"])}}let{last_hidden_state:at}=await Je(this,ue);if(Re.guidance_scale!==null&&Re.guidance_scale>1)at=(0,S.cat)([at,(0,S.full_like)(at,0)],0),"attention_mask"in ue&&(ue.attention_mask=(0,S.cat)([ue.attention_mask,(0,S.zeros_like)(ue.attention_mask)],0));else if(ue.decoder_input_ids){const kt=ke(ue.decoder_input_ids).dims[0];if(kt!==at.dims[0]){if(at.dims[0]!==1)throw new Error(`The encoder outputs have a different batch size (${at.dims[0]}) than the decoder inputs (${kt}).`);at=(0,S.cat)(Array.from({length:kt},()=>at),0)}}return ue.encoder_outputs=at,ue}_prepare_decoder_input_ids_for_generation({batch_size:U,model_input_name:ue,model_kwargs:Ie,decoder_start_token_id:Re,bos_token_id:at,generation_config:kt}){let{decoder_input_ids:Wt,...cn}=Ie;if(Wt)Array.isArray(Wt[0])||(Wt=Array.from({length:U},()=>Wt));else if(Re??(Re=at),this.config.model_type==="musicgen")Wt=Array.from({length:U*this.config.decoder.num_codebooks},()=>[Re]);else if(Array.isArray(Re)){if(Re.length!==U)throw new Error(`\`decoder_start_token_id\` expcted to have length ${U} but got ${Re.length}`);Wt=Re}else Wt=Array.from({length:U},()=>[Re]);return Wt=ke(Wt),Ie.decoder_attention_mask=(0,S.ones_like)(Wt),{input_ids:Wt,model_inputs:cn}}async generate({inputs:U=null,generation_config:ue=null,logits_processor:Ie=null,stopping_criteria:Re=null,streamer:at=null,...kt}){this._validate_model_class(),ue=this._prepare_generation_config(ue,kt);let{inputs_tensor:Wt,model_inputs:cn,model_input_name:an}=this._prepare_model_inputs({inputs:U,model_kwargs:kt});const Pn=this.config.is_encoder_decoder;Pn&&("encoder_outputs"in cn||(cn=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:Wt,model_inputs:cn,model_input_name:an,generation_config:ue})));let pn;Pn?{input_ids:pn,model_inputs:cn}=this._prepare_decoder_input_ids_for_generation({batch_size:cn[an].dims.at(0),model_input_name:an,model_kwargs:cn,decoder_start_token_id:ue.decoder_start_token_id,bos_token_id:ue.bos_token_id,generation_config:ue}):pn=cn[an];let _n=pn.dims.at(-1);ue.max_new_tokens!==null&&(ue.max_length=_n+ue.max_new_tokens);const fn=this._get_logits_processor(ue,_n,Ie),gn=this._get_stopping_criteria(ue,Re),Mn=cn[an].dims.at(0),Dn=te.LogitsSampler.getSampler(ue),xr=new Array(Mn).fill(0),Er=pn.tolist();at&&at.put(Er);let xi=null,gr={};for(;;){cn=this.prepare_inputs_for_generation(Er,cn,ue);const _r=await this.forward(cn);if(ue.output_attentions&&ue.return_dict_in_generate){const ui=this.getAttentions(_r);for(const qo in ui)qo in gr||(gr[qo]=[]),gr[qo].push(ui[qo])}const Rs=_r.logits.slice(null,-1,null),Ns=fn(Er,Rs),_l=[];for(let ui=0;uiui)){ue.return_dict_in_generate&&(xi=this.getPastKeyValues(_r,cn.past_key_values,!1));break}cn=this._update_model_kwargs_for_generation({generated_input_ids:_l,outputs:_r,model_inputs:cn,is_encoder_decoder:Pn})}at&&at.end();const ir=new S.Tensor("int64",Er.flat(),[Er.length,Er[0].length]);return ue.return_dict_in_generate?{sequences:ir,past_key_values:xi,...gr}:ir}getPastKeyValues(U,ue,Ie=!0){const Re=Object.create(null);for(const at in U)if(at.startsWith("present")){const kt=at.replace("present","past_key_values");if(ue&&at.includes("encoder"))Re[kt]=ue[kt];else{if(Ie&&ue){const Wt=ue[kt];Wt.location==="gpu-buffer"&&Wt.dispose()}Re[kt]=U[at]}}return Re}getAttentions(U){const ue={};for(const Ie of["cross_attentions","encoder_attentions","decoder_attentions"])for(const Re in U)Re.startsWith(Ie)&&(Ie in ue||(ue[Ie]=[]),ue[Ie].push(U[Re]));return ue}addPastKeyValues(U,ue){if(ue)Object.assign(U,ue);else{const Ie=this.custom_config.kv_cache_dtype??"float32",Re=Ie==="float16"?new Uint16Array:[],at=(0,o.getKeyValueShapes)(this.config);for(const kt in at)U[kt]=new S.Tensor(Ie,Re,at[kt])}}async encode_image({pixel_values:U}){const ue=(await me(this.sessions.vision_encoder,{pixel_values:U})).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 (${ue.dims[1]}).`),this.config.num_image_tokens=ue.dims[1]),ue}async encode_text({input_ids:U}){return(await me(this.sessions.embed_tokens,{input_ids:U})).inputs_embeds}}class Fe{}class ut extends Fe{constructor({last_hidden_state:k,hidden_states:U=null,attentions:ue=null}){super(),this.last_hidden_state=k,this.hidden_states=U,this.attentions=ue}}class Ye extends se{}class st extends Ye{}class Oe extends Ye{async _call(k){return new hr(await super._call(k))}}class rt extends Ye{async _call(k){return new dn(await super._call(k))}}class Tt extends Ye{async _call(k){return new ar(await super._call(k))}}class Be extends Ye{async _call(k){return new mr(await super._call(k))}}class fe extends se{}class Ce extends fe{}class Ue extends se{}class Ge extends Ue{}class We extends Ue{async _call(k){return new hr(await super._call(k))}}class He extends Ue{async _call(k){return new dn(await super._call(k))}}class dt extends Ue{async _call(k){return new ar(await super._call(k))}}class mt extends Ue{async _call(k){return new mr(await super._call(k))}}class wt extends se{}class xt extends wt{}class O extends wt{async _call(k){return new hr(await super._call(k))}}class ie extends wt{async _call(k){return new dn(await super._call(k))}}class q extends wt{async _call(k){return new ar(await super._call(k))}}class de extends wt{async _call(k){return new mr(await super._call(k))}}class ve extends se{}class et extends ve{}class nt extends ve{async _call(k){return new hr(await super._call(k))}}class At extends ve{async _call(k){return new dn(await super._call(k))}}class _t extends ve{async _call(k){return new ar(await super._call(k))}}class Pe extends ve{async _call(k){return new mr(await super._call(k))}}class j extends se{}class le extends j{}class Te extends j{async _call(k){return new hr(await super._call(k))}}class Ne extends j{async _call(k){return new dn(await super._call(k))}}class De extends j{async _call(k){return new ar(await super._call(k))}}class je extends j{async _call(k){return new mr(await super._call(k))}}class ct extends se{}class ot extends ct{}class bt extends ct{async _call(k){return new hr(await super._call(k))}}class ft extends ct{async _call(k){return new dn(await super._call(k))}}class St extends ct{async _call(k){return new ar(await super._call(k))}}class Nt extends ct{async _call(k){return new mr(await super._call(k))}}class Ke extends se{}class Vt extends Ke{}class jt extends Ke{async _call(k){return new hr(await super._call(k))}}class Kt extends Ke{async _call(k){return new dn(await super._call(k))}}class Qt extends Ke{async _call(k){return new ar(await super._call(k))}}class Jt extends Ke{async _call(k){return new mr(await super._call(k))}}class qt extends se{}class En extends qt{}class Hn extends qt{async _call(k){return new dn(await super._call(k))}}class Cn extends qt{async _call(k){return new ar(await super._call(k))}}class tt extends qt{async _call(k){return new mr(await super._call(k))}}class Ct extends qt{async _call(k){return new hr(await super._call(k))}}class Lt extends se{}class nr extends Lt{}class Fi extends Lt{async _call(k){return new hr(await super._call(k))}}class _i extends Lt{async _call(k){return new dn(await super._call(k))}}class Nn extends Lt{async _call(k){return new ar(await super._call(k))}}class cr extends se{}class Vn extends cr{}class si extends cr{async _call(k){return new hr(await super._call(k))}}class Fn extends cr{async _call(k){return new dn(await super._call(k))}}class zi extends cr{async _call(k){return new mr(await super._call(k))}}class yi extends se{}class vs extends yi{}class Po extends yi{async _call(k){return new hr(await super._call(k))}}class Ao extends yi{async _call(k){return new dn(await super._call(k))}}class Io extends yi{async _call(k){return new ar(await super._call(k))}}class Fo extends yi{async _call(k){return new mr(await super._call(k))}}class Oi extends se{}class Ms extends Oi{}class so extends Oi{async _call(k){return new hr(await super._call(k))}}class ai extends Oi{async _call(k){return new dn(await super._call(k))}}class wi extends Oi{async _call(k){return new mr(await super._call(k))}}class vi extends se{}class Ki extends vi{}class ao extends vi{async _call(k){return new dn(await super._call(k))}}class lo extends vi{async _call(k){return new mr(await super._call(k))}}class Xt extends vi{async _call(k){return new hr(await super._call(k))}}class Qi extends se{constructor(U,ue,Ie){super(U,ue);Ee(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"]);this.generation_config=Ie}}class zo extends Qi{}class Oo extends Qi{}class uo extends se{constructor(k,U,ue){super(k,U),this.generation_config=ue}}class Do extends uo{}class Lo extends uo{}class co extends se{constructor(k,U,ue){super(k,U),this.generation_config=ue}}class Bo extends co{}class Rn extends co{}class zr extends se{constructor(k,U,ue){super(k,U),this.generation_config=ue}}class Se extends zr{}class T extends zr{}class Q extends zr{async _call(k){return new dn(await super._call(k))}}class ce extends se{constructor(k,U,ue){super(k,U),this.generation_config=ue}}class ye extends ce{}class we extends ce{}class Le extends ce{async _call(k){return new dn(await super._call(k))}}class yt extends ce{}class Mt extends se{constructor(k,U,ue){super(k,U),this.generation_config=ue}}class vt extends Mt{}class Pt extends Mt{}class Zt extends se{constructor(k,U,ue){super(k,U),this.generation_config=ue}}class $n extends Zt{}class nn extends Zt{}class Gt extends se{}class mn extends Gt{}class Mr extends Gt{async _call(k){return new hr(await super._call(k))}}class ur extends Gt{async _call(k){return new dn(await super._call(k))}}class Ve extends Gt{async _call(k){return new ar(await super._call(k))}}class Vr extends Gt{async _call(k){return new mr(await super._call(k))}}class bn extends se{}class rr extends bn{}class kr extends bn{async _call(k){return new hr(await super._call(k))}}class Yt extends bn{async _call(k){return new dn(await super._call(k))}}class Or extends bn{async _call(k){return new ar(await super._call(k))}}class pr extends bn{async _call(k){return new mr(await super._call(k))}}class Tn extends se{}class Sn extends Tn{}class Et extends Tn{async _call(k){return new hr(await super._call(k))}}class wn extends Tn{async _call(k){return new dn(await super._call(k))}}class zn extends Tn{async _call(k){return new ar(await super._call(k))}}class Un extends Tn{async _call(k){return new mr(await super._call(k))}}class Dr extends se{}class Ot extends Dr{}class bs extends Dr{}class it extends se{constructor(U,ue,Ie){super(U,ue);Ee(this,"requires_attention_mask",!1);Ee(this,"main_input_name","input_features");Ee(this,"forward_params",["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"]);this.generation_config=Ie}}class Ut extends it{}class oa extends it{_prepare_generation_config(k,U){return super._prepare_generation_config(k,U,X.WhisperGenerationConfig)}_retrieve_init_tokens(k){const U=[k.decoder_start_token_id];let ue=k.language;const Ie=k.task;if(k.is_multilingual){ue||(console.warn("No language specified - defaulting to English (en)."),ue="en");const at=`<|${(0,A.whisper_language_to_code)(ue)}|>`;U.push(k.lang_to_id[at]),U.push(k.task_to_id[Ie??"transcribe"])}else if(ue||Ie)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!k.return_timestamps&&k.no_timestamps_token_id&&U.at(-1)!==k.no_timestamps_token_id?U.push(k.no_timestamps_token_id):k.return_timestamps&&U.at(-1)===k.no_timestamps_token_id&&(console.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),U.pop()),U.filter(Re=>Re!=null)}async generate({inputs:k=null,generation_config:U=null,logits_processor:ue=null,stopping_criteria:Ie=null,...Re}){U=this._prepare_generation_config(U,Re);const at=Re.decoder_input_ids??this._retrieve_init_tokens(U);if(U.return_timestamps&&(ue??(ue=new b.LogitsProcessorList),ue.push(new b.WhisperTimeStampLogitsProcessor(U,at))),U.begin_suppress_tokens&&(ue??(ue=new b.LogitsProcessorList),ue.push(new b.SuppressTokensAtBeginLogitsProcessor(U.begin_suppress_tokens,at.length))),U.return_token_timestamps){if(!U.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.");U.task==="translate"&&console.warn("Token-level timestamps may not be reliable for task 'translate'."),U.output_attentions=!0,U.return_dict_in_generate=!0}const kt=await super.generate({inputs:k,generation_config:U,logits_processor:ue,decoder_input_ids:at,...Re});return U.return_token_timestamps&&(kt.token_timestamps=this._extract_token_timestamps(kt,U.alignment_heads,U.num_frames)),kt}_extract_token_timestamps(k,U,ue=null,Ie=.02){if(!k.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`.");ue==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 Re=this.config.median_filter_width;Re===void 0&&(console.warn("Model config has no `median_filter_width`, using default value of 7."),Re=7);const at=k.cross_attentions,kt=Array.from({length:this.config.decoder_layers},(gn,Mn)=>(0,S.cat)(at.map(Dn=>Dn[Mn]),2)),Wt=(0,S.stack)(U.map(([gn,Mn])=>{if(gn>=kt.length)throw new Error(`Layer index ${gn} is out of bounds for cross attentions (length ${kt.length}).`);return ue?kt[gn].slice(null,Mn,null,[0,ue]):kt[gn].slice(null,Mn)})).transpose(1,0,2,3),[cn,an]=(0,S.std_mean)(Wt,-2,0,!0),Pn=Wt.clone();for(let gn=0;gnDn[_r+1]-Dn[_r]),xi=(0,C.mergeArrays)([1],Er).map(ir=>!!ir),gr=[];for(let ir=0;irpn.findIndex(_n=>_n==Re)),Wt=kt.every(pn=>pn===-1),cn=kt.every(pn=>pn!==-1);if(!Wt&&!cn)throw new Error("Every input should contain either 0 or 1 image token.");if(Wt)return{inputs_embeds:k,attention_mask:Ie};const an=[],Pn=[];for(let pn=0;pnRe*at,1);k.input_labels=new S.Tensor("int64",new BigInt64Array(Ie).fill(1n),ue)}const U={image_embeddings:k.image_embeddings,image_positional_embeddings:k.image_positional_embeddings};return k.input_points&&(U.input_points=k.input_points),k.input_labels&&(U.input_labels=k.input_labels),k.input_boxes&&(U.input_boxes=k.input_boxes),await me(this.sessions.prompt_encoder_mask_decoder,U)}async _call(k){return new Id(await super._call(k))}}class Id extends Fe{constructor({iou_scores:k,pred_masks:U}){super(),this.iou_scores=k,this.pred_masks=U}}class Ra extends se{constructor(k,U,ue){super(k,U),this.generation_config=ue}}class qp extends Ra{}class Fd extends Ra{}class Na extends se{constructor(k,U,ue){super(k,U),this.generation_config=ue}}class zd extends Na{}class Od extends Na{}class Di extends se{}class Dd extends Di{}class Hp extends Di{async _call(k){return new Xi(await super._call(k))}}class Li extends Di{async _call(k){return new dn(await super._call(k))}}class Bi extends Di{async _call(k){return new ar(await super._call(k))}}class Mi extends se{}class ja extends Mi{}class Ri extends Mi{async _call(k){return new ar(await super._call(k))}}class fr extends se{}class Va extends fr{}class go extends se{}class Ua extends go{}class Ld extends go{async _call(k){return new Xi(await super._call(k))}}class Bd extends go{async _call(k){return new dn(await super._call(k))}}class No extends se{}class Ps extends No{}class Wa extends No{async _call(k){return new Xi(await super._call(k))}}class Rd extends No{async _call(k){return new dn(await super._call(k))}}class As extends No{async _call(k){return new ar(await super._call(k))}}class Is extends se{}class Ga extends Is{}class Fs extends Is{async _call(k){return new Xi(await super._call(k))}}class Nd extends Is{async _call(k){return new dn(await super._call(k))}}class Kp extends se{}class Qp extends Di{}class jd extends Di{async _call(k){return new Xi(await super._call(k))}}class qa extends Di{async _call(k){return new dn(await super._call(k))}}class bi extends se{}class Vd extends bi{}class Ha extends bi{async _call(k){return new Xi(await super._call(k))}}class Ud extends bi{async _call(k){return new dn(await super._call(k))}}class Wd extends bi{async _call(k){return new Gc(await super._call(k))}}class Gd extends bi{async _call(k){return new ar(await super._call(k))}}class Ka extends se{constructor(k,U,ue){super(k,U),this.generation_config=ue}}class qd extends Ka{}class Hd extends Ka{}class Xp extends Ka{async generate_speech(k,U,{threshold:ue=.5,minlenratio:Ie=0,maxlenratio:Re=20,vocoder:at=null}={}){const kt={input_ids:k},{encoder_outputs:Wt,encoder_attention_mask:cn}=await Je(this,kt),an=Wt.dims[1]/this.config.reduction_factor,Pn=Math.floor(an*Re),pn=Math.floor(an*Ie),_n=this.config.num_mel_bins;let fn=[],gn=null,Mn=null,Dn=0;for(;;){++Dn;const xi=$e(!!Mn);let gr;Mn?gr=Mn.output_sequence_out:gr=new S.Tensor("float32",new Float32Array(_n),[1,1,_n]);let ir={use_cache_branch:xi,output_sequence:gr,encoder_attention_mask:cn,speaker_embeddings:U,encoder_hidden_states:Wt};this.addPastKeyValues(ir,gn),Mn=await me(this.sessions.decoder_model_merged,ir),gn=this.getPastKeyValues(Mn,gn);const{prob:_r,spectrum:Rs}=Mn;if(fn.push(Rs),Dn>=pn&&(Array.from(_r.data).filter(Ns=>Ns>=ue).length>0||Dn>=Pn))break}const xr=(0,S.cat)(fn),{waveform:Er}=await me(at.sessions.model,{spectrogram:xr});return{spectrogram:xr,waveform:Er}}}class Qa extends se{constructor(){super(...arguments);Ee(this,"main_input_name","spectrogram")}}class Kd extends se{constructor(k,U,ue){super(k,U),this.generation_config=ue}}class Qd extends Kd{}class Xa extends se{constructor(k,U,ue){super(k,U),this.generation_config=ue}}class zs extends Xa{}class Os extends Xa{}class Ya extends se{constructor(k,U,ue){super(k,U),this.generation_config=ue}}class Ds extends Ya{}class Za extends Ya{}class Ja extends se{constructor(k,U,ue){super(k,U),this.generation_config=ue}}class Xd extends Ja{}class Yd extends Ja{}class jo extends se{}class Zd extends jo{}class Jd extends jo{static async from_pretrained(k,U={}){return U.model_file_name??(U.model_file_name="text_model"),super.from_pretrained(k,U)}}class ec extends jo{static async from_pretrained(k,U={}){return U.model_file_name??(U.model_file_name="audio_model"),super.from_pretrained(k,U)}}class Yp extends se{}class el extends Yp{async _call(k){return new ff(await super._call(k))}}class Vo extends se{}class Yh extends Vo{}class tc extends Vo{}class nc extends Vo{}class tl extends se{constructor(k,U,ue){super(k,U),this.generation_config=ue}}class nl extends tl{}class rc extends tl{}class rl extends se{}class ic extends rl{}class oc extends rl{async _call(k){return new dn(await super._call(k))}}class il extends se{}class Zp extends il{}class Zh extends il{}class ol extends se{constructor(U,ue,Ie){super(U,ue);Ee(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"]);this.generation_config=Ie}_apply_and_filter_by_delay_pattern_mask(U){const[ue,Ie]=U.dims,Re=this.config.decoder.num_codebooks,at=Ie-Re;let kt=0;for(let an=0;an0&&_n<=at&&(U.data[kt++]=U.data[an])}const Wt=Math.floor(ue/Re),cn=kt/(Wt*Re);return new S.Tensor(U.type,U.data.slice(0,kt),[Wt,Re,cn])}prepare_inputs_for_generation(U,ue,Ie){let Re=structuredClone(U);for(let kt=0;kt=Wt&&(Re[kt][Wt]=BigInt(this.config.decoder.pad_token_id));return Ie.guidance_scale!==null&&Ie.guidance_scale>1&&(Re=Re.concat(Re)),super.prepare_inputs_for_generation(Re,ue,Ie)}async generate(U){const ue=await super.generate(U),Ie=this._apply_and_filter_by_delay_pattern_mask(ue).unsqueeze_(0),{audio_values:Re}=await me(this.sessions.encodec_decode,{audio_codes:Ie});return Re}}class sl extends se{}class sc extends sl{}class Jp extends sl{async _call(k){return new dn(await super._call(k))}}class al extends se{}class ac extends al{}class lc extends al{async _call(k){return new dn(await super._call(k))}}class ll extends se{}class uc extends ll{}class ef extends ll{async _call(k){return new dn(await super._call(k))}}class Uo extends se{}class Wo extends Uo{}class ul extends Uo{async _call(k){return new dn(await super._call(k))}}class On{static async from_pretrained(k,{progress_callback:U=null,config:ue=null,cache_dir:Ie=null,local_files_only:Re=!1,revision:at="main",model_file_name:kt=null,subfolder:Wt="onnx",device:cn=null,dtype:an=null,use_external_data_format:Pn=null,session_options:pn={}}={}){let _n={progress_callback:U,config:ue,cache_dir:Ie,local_files_only:Re,revision:at,model_file_name:kt,subfolder:Wt,device:cn,dtype:an,use_external_data_format:Pn,session_options:pn};if(_n.config=await o.AutoConfig.from_pretrained(k,_n),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);for(let fn of this.MODEL_CLASS_MAPPINGS){const gn=fn.get(_n.config.model_type);if(gn)return await gn[1].from_pretrained(k,_n)}if(this.BASE_IF_FAIL)return console.warn(`Unknown model class "${_n.config.model_type}", attempting to construct from base class.`),await se.from_pretrained(k,_n);throw Error(`Unsupported model type: ${_n.config.model_type}`)}}Ee(On,"MODEL_CLASS_MAPPINGS",null),Ee(On,"BASE_IF_FAIL",!1);const tf=new Map([["bert",["BertModel",st]],["nomic_bert",["NomicBertModel",Ce]],["roformer",["RoFormerModel",Ge]],["electra",["ElectraModel",et]],["esm",["EsmModel",nr]],["convbert",["ConvBertModel",xt]],["camembert",["CamembertModel",le]],["deberta",["DebertaModel",ot]],["deberta-v2",["DebertaV2Model",Vt]],["mpnet",["MPNetModel",vs]],["albert",["AlbertModel",Ki]],["distilbert",["DistilBertModel",En]],["roberta",["RobertaModel",mn]],["xlm",["XLMModel",rr]],["xlm-roberta",["XLMRobertaModel",Sn]],["clap",["ClapModel",Zd]],["clip",["CLIPModel",eu]],["clipseg",["CLIPSegModel",su]],["chinese_clip",["ChineseCLIPModel",ou]],["siglip",["SiglipModel",fo]],["mobilebert",["MobileBertModel",Vn]],["squeezebert",["SqueezeBertModel",Ms]],["wav2vec2",["Wav2Vec2Model",Dd]],["wav2vec2-bert",["Wav2Vec2BertModel",Ga]],["unispeech",["UniSpeechModel",Ua]],["unispeech-sat",["UniSpeechSatModel",Ps]],["hubert",["HubertModel",Qp]],["wavlm",["WavLMModel",Vd]],["audio-spectrogram-transformer",["ASTModel",Ot]],["vits",["VitsModel",el]],["pyannote",["PyAnnoteModel",ja]],["wespeaker-resnet",["WeSpeakerResNetModel",Va]],["detr",["DetrModel",Ju]],["rt_detr",["RTDetrModel",rd]],["table-transformer",["TableTransformerModel",od]],["vit",["ViTModel",Lu]],["fastvit",["FastViTModel",Ru]],["mobilevit",["MobileViTModel",Wu]],["mobilevitv2",["MobileViTV2Model",Gp]],["owlvit",["OwlViTModel",Hu]],["owlv2",["Owlv2Model",Qu]],["beit",["BeitModel",Yu]],["deit",["DeiTModel",ld]],["convnext",["ConvNextModel",vd]],["convnextv2",["ConvNextV2Model",xd]],["dinov2",["Dinov2Model",Sd]],["resnet",["ResNetModel",dd]],["swin",["SwinModel",pd]],["swin2sr",["Swin2SRModel",hd]],["donut-swin",["DonutSwinModel",Da]],["yolos",["YolosModel",Ed]],["dpt",["DPTModel",Fa]],["glpn",["GLPNModel",_d]],["hifigan",["SpeechT5HifiGan",Qa]],["efficientnet",["EfficientNetModel",ic]],["mobilenet_v1",["MobileNetV1Model",sc]],["mobilenet_v2",["MobileNetV2Model",ac]],["mobilenet_v3",["MobileNetV3Model",uc]],["mobilenet_v4",["MobileNetV4Model",Wo]]]),nf=new Map([["t5",["T5Model",zo]],["longt5",["LongT5Model",Do]],["mt5",["MT5Model",Bo]],["bart",["BartModel",Se]],["mbart",["MBartModel",ye]],["marian",["MarianModel",qp]],["whisper",["WhisperModel",Ut]],["m2m_100",["M2M100Model",zd]],["blenderbot",["BlenderbotModel",vt]],["blenderbot-small",["BlenderbotSmallModel",$n]]]),rf=new Map([["bloom",["BloomModel",Iu]],["gpt2",["GPT2Model",lu]],["gptj",["GPTJModel",hu]],["gpt_bigcode",["GPTBigCodeModel",gu]],["gpt_neo",["GPTNeoModel",du]],["gpt_neox",["GPTNeoXModel",pu]],["codegen",["CodeGenModel",_u]],["llama",["LlamaModel",Jr]],["cohere",["CohereModel",wu]],["gemma",["GemmaModel",Mu]],["gemma2",["Gemma2Model",xu]],["openelm",["OpenELMModel",Su]],["qwen2",["Qwen2Model",Eu]],["phi",["PhiModel",$u]],["phi3",["Phi3Model",Au]],["mpt",["MptModel",Wp]],["opt",["OPTModel",Ou]],["mistral",["MistralModel",zs]],["starcoder2",["Starcoder2Model",Ds]],["falcon",["FalconModel",Xd]],["stablelm",["StableLmModel",nl]]]),Ls=new Map([["speecht5",["SpeechT5ForSpeechToText",Hd]],["whisper",["WhisperForConditionalGeneration",oa]]]),dc=new Map([["speecht5",["SpeechT5ForTextToSpeech",Xp]]]),cc=new Map([["vits",["VitsModel",el]],["musicgen",["MusicgenForConditionalGeneration",ol]]]),pc=new Map([["bert",["BertForSequenceClassification",rt]],["roformer",["RoFormerForSequenceClassification",He]],["electra",["ElectraForSequenceClassification",At]],["esm",["EsmForSequenceClassification",_i]],["convbert",["ConvBertForSequenceClassification",ie]],["camembert",["CamembertForSequenceClassification",Ne]],["deberta",["DebertaForSequenceClassification",ft]],["deberta-v2",["DebertaV2ForSequenceClassification",Kt]],["mpnet",["MPNetForSequenceClassification",Ao]],["albert",["AlbertForSequenceClassification",ao]],["distilbert",["DistilBertForSequenceClassification",Hn]],["roberta",["RobertaForSequenceClassification",ur]],["xlm",["XLMForSequenceClassification",Yt]],["xlm-roberta",["XLMRobertaForSequenceClassification",wn]],["bart",["BartForSequenceClassification",Q]],["mbart",["MBartForSequenceClassification",Le]],["mobilebert",["MobileBertForSequenceClassification",Fn]],["squeezebert",["SqueezeBertForSequenceClassification",ai]]]),of=new Map([["bert",["BertForTokenClassification",Tt]],["roformer",["RoFormerForTokenClassification",dt]],["electra",["ElectraForTokenClassification",_t]],["esm",["EsmForTokenClassification",Nn]],["convbert",["ConvBertForTokenClassification",q]],["camembert",["CamembertForTokenClassification",De]],["deberta",["DebertaForTokenClassification",St]],["deberta-v2",["DebertaV2ForTokenClassification",Qt]],["mpnet",["MPNetForTokenClassification",Io]],["distilbert",["DistilBertForTokenClassification",Cn]],["roberta",["RobertaForTokenClassification",Ve]],["xlm",["XLMForTokenClassification",Or]],["xlm-roberta",["XLMRobertaForTokenClassification",zn]]]),dl=new Map([["t5",["T5ForConditionalGeneration",Oo]],["longt5",["LongT5ForConditionalGeneration",Lo]],["mt5",["MT5ForConditionalGeneration",Rn]],["bart",["BartForConditionalGeneration",T]],["mbart",["MBartForConditionalGeneration",we]],["marian",["MarianMTModel",Fd]],["m2m_100",["M2M100ForConditionalGeneration",Od]],["blenderbot",["BlenderbotForConditionalGeneration",Pt]],["blenderbot-small",["BlenderbotSmallForConditionalGeneration",nn]]]),Bs=new Map([["bloom",["BloomForCausalLM",Fu]],["gpt2",["GPT2LMHeadModel",uu]],["gptj",["GPTJForCausalLM",mu]],["gpt_bigcode",["GPTBigCodeForCausalLM",Up]],["gpt_neo",["GPTNeoForCausalLM",cu]],["gpt_neox",["GPTNeoXForCausalLM",fu]],["codegen",["CodeGenForCausalLM",xs]],["llama",["LlamaForCausalLM",yu]],["cohere",["CohereForCausalLM",vu]],["gemma",["GemmaForCausalLM",bu]],["gemma2",["Gemma2ForCausalLM",Tu]],["openelm",["OpenELMForCausalLM",ku]],["qwen2",["Qwen2ForCausalLM",Cu]],["phi",["PhiForCausalLM",Pu]],["phi3",["Phi3ForCausalLM",va]],["mpt",["MptForCausalLM",zu]],["opt",["OPTForCausalLM",Du]],["mbart",["MBartForCausalLM",yt]],["mistral",["MistralForCausalLM",Os]],["starcoder2",["Starcoder2ForCausalLM",Za]],["falcon",["FalconForCausalLM",Yd]],["trocr",["TrOCRForCausalLM",Qd]],["stablelm",["StableLmForCausalLM",rc]]]),fc=new Map([["bert",["BertForMaskedLM",Oe]],["roformer",["RoFormerForMaskedLM",We]],["electra",["ElectraForMaskedLM",nt]],["esm",["EsmForMaskedLM",Fi]],["convbert",["ConvBertForMaskedLM",O]],["camembert",["CamembertForMaskedLM",Te]],["deberta",["DebertaForMaskedLM",bt]],["deberta-v2",["DebertaV2ForMaskedLM",jt]],["mpnet",["MPNetForMaskedLM",Po]],["albert",["AlbertForMaskedLM",Xt]],["distilbert",["DistilBertForMaskedLM",Ct]],["roberta",["RobertaForMaskedLM",Mr]],["xlm",["XLMWithLMHeadModel",kr]],["xlm-roberta",["XLMRobertaForMaskedLM",Et]],["mobilebert",["MobileBertForMaskedLM",si]],["squeezebert",["SqueezeBertForMaskedLM",so]]]),hc=new Map([["bert",["BertForQuestionAnswering",Be]],["roformer",["RoFormerForQuestionAnswering",mt]],["electra",["ElectraForQuestionAnswering",Pe]],["convbert",["ConvBertForQuestionAnswering",de]],["camembert",["CamembertForQuestionAnswering",je]],["deberta",["DebertaForQuestionAnswering",Nt]],["deberta-v2",["DebertaV2ForQuestionAnswering",Jt]],["mpnet",["MPNetForQuestionAnswering",Fo]],["albert",["AlbertForQuestionAnswering",lo]],["distilbert",["DistilBertForQuestionAnswering",tt]],["roberta",["RobertaForQuestionAnswering",Vr]],["xlm",["XLMForQuestionAnswering",pr]],["xlm-roberta",["XLMRobertaForQuestionAnswering",Un]],["mobilebert",["MobileBertForQuestionAnswering",zi]],["squeezebert",["SqueezeBertForQuestionAnswering",wi]]]),cl=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",sa]]]),Jh=new Map([["llava",["LlavaForConditionalGeneration",po]],["moondream1",["Moondream1ForConditionalGeneration",sn]],["florence2",["Florence2ForConditionalGeneration",aa]]]),sf=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",sa]]]),mc=new Map([["vit",["ViTForImageClassification",Bu]],["fastvit",["FastViTForImageClassification",Nu]],["mobilevit",["MobileViTForImageClassification",Gu]],["mobilevitv2",["MobileViTV2ForImageClassification",qu]],["beit",["BeitForImageClassification",Zu]],["deit",["DeiTForImageClassification",ud]],["convnext",["ConvNextForImageClassification",Md]],["convnextv2",["ConvNextV2ForImageClassification",Td]],["dinov2",["Dinov2ForImageClassification",kd]],["resnet",["ResNetForImageClassification",cd]],["swin",["SwinForImageClassification",fd]],["segformer",["SegformerForImageClassification",tc]],["efficientnet",["EfficientNetForImageClassification",oc]],["mobilenet_v1",["MobileNetV1ForImageClassification",Jp]],["mobilenet_v2",["MobileNetV2ForImageClassification",lc]],["mobilenet_v3",["MobileNetV3ForImageClassification",ef]],["mobilenet_v4",["MobileNetV4ForImageClassification",ul]]]),af=new Map([["detr",["DetrForObjectDetection",ed]],["rt_detr",["RTDetrForObjectDetection",$s]],["table-transformer",["TableTransformerForObjectDetection",sd]],["yolos",["YolosForObjectDetection",Cd]]]),gc=new Map([["owlvit",["OwlViTForObjectDetection",Ku]],["owlv2",["Owlv2ForObjectDetection",Xu]]]),_c=new Map([["detr",["DetrForSegmentation",td]],["clipseg",["CLIPSegForImageSegmentation",au]]]),yc=new Map([["segformer",["SegformerForSemanticSegmentation",nc]]]),wc=new Map([["sam",["SamModel",Ad]]]),lf=new Map([["wav2vec2",["Wav2Vec2ForCTC",Hp]],["wav2vec2-bert",["Wav2Vec2BertForCTC",Fs]],["unispeech",["UniSpeechForCTC",Ld]],["unispeech-sat",["UniSpeechSatForCTC",Wa]],["wavlm",["WavLMForCTC",Ha]],["hubert",["HubertForCTC",jd]]]),vc=new Map([["wav2vec2",["Wav2Vec2ForSequenceClassification",Li]],["wav2vec2-bert",["Wav2Vec2BertForSequenceClassification",Nd]],["unispeech",["UniSpeechForSequenceClassification",Bd]],["unispeech-sat",["UniSpeechSatForSequenceClassification",Rd]],["wavlm",["WavLMForSequenceClassification",Ud]],["hubert",["HubertForSequenceClassification",qa]],["audio-spectrogram-transformer",["ASTForAudioClassification",bs]]]),Mc=new Map([["wavlm",["WavLMForXVector",Wd]]]),bc=new Map([["unispeech-sat",["UniSpeechSatForAudioFrameClassification",As]],["wavlm",["WavLMForAudioFrameClassification",Gd]],["wav2vec2",["Wav2Vec2ForAudioFrameClassification",Bi]],["pyannote",["PyAnnoteForAudioFrameClassification",Ri]]]),xc=new Map([["vitmatte",["VitMatteForImageMatting",Vu]]]),uf=new Map([["swin2sr",["Swin2SRForImageSuperResolution",Aa]]]),Tc=new Map([["dpt",["DPTForDepthEstimation",za]],["depth_anything",["DepthAnythingForDepthEstimation",gd]],["glpn",["GLPNForDepthEstimation",yd]]]),Sc=new Map([["clip",["CLIPVisionModelWithProjection",tu]],["siglip",["SiglipVisionModel",ru]]]),kc=[[tf,P.EncoderOnly],[nf,P.EncoderDecoder],[rf,P.DecoderOnly],[pc,P.EncoderOnly],[of,P.EncoderOnly],[dl,P.Seq2Seq],[Ls,P.Seq2Seq],[Bs,P.DecoderOnly],[fc,P.EncoderOnly],[hc,P.EncoderOnly],[cl,P.Vision2Seq],[Jh,P.ImageTextToText],[mc,P.EncoderOnly],[_c,P.EncoderOnly],[yc,P.EncoderOnly],[xc,P.EncoderOnly],[uf,P.EncoderOnly],[Tc,P.EncoderOnly],[af,P.EncoderOnly],[gc,P.EncoderOnly],[wc,P.MaskGeneration],[lf,P.EncoderOnly],[vc,P.EncoderOnly],[dc,P.Seq2Seq],[cc,P.EncoderOnly],[Mc,P.EncoderOnly],[bc,P.EncoderOnly],[Sc,P.EncoderOnly]];for(const[x,k]of kc)for(const[U,ue]of x.values())L.set(U,k),V.set(ue,U),Z.set(U,ue);const df=[["MusicgenForConditionalGeneration",ol,P.Musicgen],["CLIPTextModelWithProjection",li,P.EncoderOnly],["SiglipTextModel",nu,P.EncoderOnly],["ClapTextModelWithProjection",Jd,P.EncoderOnly],["ClapAudioModelWithProjection",ec,P.EncoderOnly]];for(const[x,k,U]of df)L.set(x,U),V.set(k,x),Z.set(x,k);class Ec extends On{}Ee(Ec,"MODEL_CLASS_MAPPINGS",kc.map(k=>k[0])),Ee(Ec,"BASE_IF_FAIL",!0);class br extends On{}Ee(br,"MODEL_CLASS_MAPPINGS",[pc]);class Cc extends On{}Ee(Cc,"MODEL_CLASS_MAPPINGS",[of]);class $c extends On{}Ee($c,"MODEL_CLASS_MAPPINGS",[dl]);class pl extends On{}Ee(pl,"MODEL_CLASS_MAPPINGS",[Ls]);class Pc extends On{}Ee(Pc,"MODEL_CLASS_MAPPINGS",[dc]);class Go extends On{}Ee(Go,"MODEL_CLASS_MAPPINGS",[cc]);class Ac extends On{}Ee(Ac,"MODEL_CLASS_MAPPINGS",[Bs]);class Ic extends On{}Ee(Ic,"MODEL_CLASS_MAPPINGS",[fc]);class fl extends On{}Ee(fl,"MODEL_CLASS_MAPPINGS",[hc]);class Fc extends On{}Ee(Fc,"MODEL_CLASS_MAPPINGS",[cl]);class zc extends On{}Ee(zc,"MODEL_CLASS_MAPPINGS",[mc]);class hl extends On{}Ee(hl,"MODEL_CLASS_MAPPINGS",[_c]);class Oc extends On{}Ee(Oc,"MODEL_CLASS_MAPPINGS",[yc]);class Dc extends On{}Ee(Dc,"MODEL_CLASS_MAPPINGS",[af]);class Lc extends On{}Ee(Lc,"MODEL_CLASS_MAPPINGS",[gc]);class ml extends On{}Ee(ml,"MODEL_CLASS_MAPPINGS",[wc]);class Bc extends On{}Ee(Bc,"MODEL_CLASS_MAPPINGS",[lf]);class Rc extends On{}Ee(Rc,"MODEL_CLASS_MAPPINGS",[vc]);class gl extends On{}Ee(gl,"MODEL_CLASS_MAPPINGS",[Mc]);class Nc extends On{}Ee(Nc,"MODEL_CLASS_MAPPINGS",[bc]);class cf extends On{}Ee(cf,"MODEL_CLASS_MAPPINGS",[sf]);class jc extends On{}Ee(jc,"MODEL_CLASS_MAPPINGS",[xc]);class Vc extends On{}Ee(Vc,"MODEL_CLASS_MAPPINGS",[uf]);class Uc extends On{}Ee(Uc,"MODEL_CLASS_MAPPINGS",[Tc]);class Wc extends On{}Ee(Wc,"MODEL_CLASS_MAPPINGS",[Sc]);class em extends Fe{constructor({logits:k,past_key_values:U,encoder_outputs:ue,decoder_attentions:Ie=null,cross_attentions:Re=null}){super(),this.logits=k,this.past_key_values=U,this.encoder_outputs=ue,this.decoder_attentions=Ie,this.cross_attentions=Re}}class dn extends Fe{constructor({logits:k}){super(),this.logits=k}}class Gc extends Fe{constructor({logits:k,embeddings:U}){super(),this.logits=k,this.embeddings=U}}class ar extends Fe{constructor({logits:k}){super(),this.logits=k}}class hr extends Fe{constructor({logits:k}){super(),this.logits=k}}class mr extends Fe{constructor({start_logits:k,end_logits:U}){super(),this.start_logits=k,this.end_logits=U}}class Xi extends Fe{constructor({logits:k}){super(),this.logits=k}}class pf extends Fe{constructor({logits:k,past_key_values:U}){super(),this.logits=k,this.past_key_values=U}}class qc extends Fe{constructor({alphas:k}){super(),this.alphas=k}}class ff extends Fe{constructor({waveform:k,spectrogram:U}){super(),this.waveform=k,this.spectrogram=U}}},"./src/models/whisper/common_whisper.js":(e,n,r)=>{r.r(n),r.d(n,{WHISPER_LANGUAGE_MAPPING:()=>l,WHISPER_TO_LANGUAGE_CODE_MAPPING:()=>p,whisper_language_to_code:()=>_});const o=[["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"]],l=new Map(o),p=new Map([...o.map(([C,M])=>[M,C]),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);function _(C){C=C.toLowerCase();let M=p.get(C);if(M===void 0)if(l.has(C))M=C;else{const F=C.length===2?l.keys():l.values();throw new Error(`Language "${C}" is not supported. Must be one of: ${JSON.stringify(F)}`)}return M}},"./src/models/whisper/generation_whisper.js":(e,n,r)=>{r.r(n),r.d(n,{WhisperGenerationConfig:()=>l});var o=r("./src/generation/configuration_utils.js");class l extends o.GenerationConfig{constructor(){super(...arguments);Ee(this,"return_timestamps",null);Ee(this,"return_token_timestamps",null);Ee(this,"num_frames",null);Ee(this,"alignment_heads",null);Ee(this,"task",null);Ee(this,"language",null);Ee(this,"no_timestamps_token_id",null);Ee(this,"prompt_ids",null);Ee(this,"is_multilingual",null);Ee(this,"lang_to_id",null);Ee(this,"task_to_id",null);Ee(this,"max_initial_timestamp_index",1)}}},"./src/ops/registry.js":(e,n,r)=>{r.r(n),r.d(n,{TensorOpRegistry:()=>_});var o=r("./src/backends/onnx.js"),l=r("./src/utils/tensor.js");const p=async(C,M,b)=>{const F=await(0,o.createInferenceSession)(new Uint8Array(C),M);return async S=>{const G=Object.fromEntries(Object.entries(S).map(([te,ne])=>[te,ne.ort_tensor])),J=await F.run(G);return Array.isArray(b)?b.map(te=>new l.Tensor(J[te])):new l.Tensor(J[b])}};class _{static get bilinear_interpolate_4d(){return this._bilinear_interpolate_4d||(this._bilinear_interpolate_4d=p([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=p([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=p([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=p([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=p([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=p([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}}Ee(_,"session_options",{})},"./src/pipelines.js":(e,n,r)=>{r.r(n),r.d(n,{AudioClassificationPipeline:()=>$e,AutomaticSpeechRecognitionPipeline:()=>Je,DepthEstimationPipeline:()=>Ye,DocumentQuestionAnsweringPipeline:()=>se,FeatureExtractionPipeline:()=>he,FillMaskPipeline:()=>L,ImageClassificationPipeline:()=>pt,ImageFeatureExtractionPipeline:()=>ke,ImageSegmentationPipeline:()=>xe,ImageToImagePipeline:()=>ut,ImageToTextPipeline:()=>Xe,ObjectDetectionPipeline:()=>pe,Pipeline:()=>ne,QuestionAnsweringPipeline:()=>P,SummarizationPipeline:()=>V,Text2TextGenerationPipeline:()=>Z,TextClassificationPipeline:()=>X,TextGenerationPipeline:()=>z,TextToAudioPipeline:()=>Fe,TokenClassificationPipeline:()=>A,TranslationPipeline:()=>D,ZeroShotAudioClassificationPipeline:()=>Ae,ZeroShotClassificationPipeline:()=>me,ZeroShotImageClassificationPipeline:()=>H,ZeroShotObjectDetectionPipeline:()=>Me,pipeline:()=>rt});var o=r("./src/tokenizers.js"),l=r("./src/models.js"),p=r("./src/processors.js"),_=r("./src/utils/generic.js"),C=r("./src/utils/core.js"),M=r("./src/utils/maths.js"),b=r("./src/utils/audio.js"),F=r("./src/utils/tensor.js"),S=r("./src/utils/image.js");async function G(Be){return Array.isArray(Be)||(Be=[Be]),await Promise.all(Be.map(fe=>S.RawImage.read(fe)))}async function J(Be,fe){return Array.isArray(Be)||(Be=[Be]),await Promise.all(Be.map(Ce=>typeof Ce=="string"||Ce instanceof URL?(0,b.read_audio)(Ce,fe):Ce instanceof Float64Array?new Float32Array(Ce):Ce))}function te(Be,fe){fe&&(Be=Be.map(He=>He|0));const[Ce,Ue,Ge,We]=Be;return{xmin:Ce,ymin:Ue,xmax:Ge,ymax:We}}class ne extends _.Callable{constructor({task:fe,model:Ce,tokenizer:Ue=null,processor:Ge=null}){super(),this.task=fe,this.model=Ce,this.tokenizer=Ue,this.processor=Ge}async dispose(){await this.model.dispose()}}class X extends ne{constructor(fe){super(fe)}async _call(fe,{top_k:Ce=1}={}){const Ue=this.tokenizer(fe,{padding:!0,truncation:!0}),Ge=await this.model(Ue),We=this.model.config.problem_type==="multi_label_classification"?mt=>mt.sigmoid():mt=>new F.Tensor("float32",(0,M.softmax)(mt.data),mt.dims),He=this.model.config.id2label,dt=[];for(const mt of Ge.logits){const wt=We(mt),xt=await(0,F.topk)(wt,Ce),O=xt[0].tolist(),q=xt[1].tolist().map((de,ve)=>({label:He?He[de]:`LABEL_${de}`,score:O[ve]}));Ce===1?dt.push(...q):dt.push(q)}return Array.isArray(fe)||Ce===1?dt:dt[0]}}class A extends ne{constructor(fe){super(fe)}async _call(fe,{ignore_labels:Ce=["O"]}={}){const Ue=Array.isArray(fe),Ge=this.tokenizer(Ue?fe:[fe],{padding:!0,truncation:!0}),He=(await this.model(Ge)).logits,dt=this.model.config.id2label,mt=[];for(let wt=0;wt_t==this.tokenizer.sep_token_id);mt[O].map((_t,Pe)=>_t==1&&(Pe===0||Pe>q&&wt.findIndex(j=>j==ie[Pe])===-1));const de=We[O].tolist(),ve=He[O].tolist();for(let _t=1;_tPe==ie[_t])!==-1)&&(de[_t]=-1/0,ve[_t]=-1/0);const et=(0,M.softmax)(de).map((_t,Pe)=>[_t,Pe]),nt=(0,M.softmax)(ve).map((_t,Pe)=>[_t,Pe]);et[0][0]=0,nt[0][0]=0;const At=(0,C.product)(et,nt).filter(_t=>_t[0][1]<=_t[1][1]).map(_t=>[_t[0][1],_t[1][1],_t[0][0]*_t[1][0]]).sort((_t,Pe)=>Pe[2]-_t[2]);for(let _t=0;_tde==this.tokenizer.mask_token_id);if(wt===-1)throw Error(`Mask token (${this.tokenizer.mask_token}) not found in text.`);const xt=Ge[dt][wt],O=await(0,F.topk)(new F.Tensor("float32",(0,M.softmax)(xt.data),xt.dims),Ce),ie=O[0].tolist(),q=O[1].tolist();We.push(q.map((de,ve)=>{const et=mt.slice();return et[wt]=de,{score:ie[ve],token:Number(de),token_str:this.tokenizer.model.vocab[de],sequence:this.tokenizer.decode(et,{skip_special_tokens:!0})}}))}return Array.isArray(fe)?We:We[0]}}class Z extends ne{constructor(Ce){super(Ce);Ee(this,"_key","generated_text")}async _call(Ce,Ue={}){Array.isArray(Ce)||(Ce=[Ce]),this.model.config.prefix&&(Ce=Ce.map(wt=>this.model.config.prefix+wt));const Ge=this.model.config.task_specific_params;Ge&&Ge[this.task]&&Ge[this.task].prefix&&(Ce=Ce.map(wt=>Ge[this.task].prefix+wt));const We=this.tokenizer,He={padding:!0,truncation:!0};let dt;this instanceof D&&"_build_translation_inputs"in We?dt=We._build_translation_inputs(Ce,He,Ue):dt=We(Ce,He);const mt=await this.model.generate({...dt,...Ue});return We.batch_decode(mt,{skip_special_tokens:!0}).map(wt=>({[this._key]:wt}))}}class V extends Z{constructor(Ce){super(Ce);Ee(this,"_key","summary_text")}}class D extends Z{constructor(Ce){super(Ce);Ee(this,"_key","translation_text")}}function N(Be){return Array.isArray(Be)&&Be.every(fe=>"role"in fe&&"content"in fe)}class z extends ne{constructor(fe){super(fe)}async _call(fe,Ce={}){let Ue=!1,Ge=!1,We;if(typeof fe=="string")We=fe=[fe];else if(Array.isArray(fe)&&fe.every(q=>typeof q=="string"))Ue=!0,We=fe;else{if(N(fe))fe=[fe];else if(Array.isArray(fe)&&fe.every(N))Ue=!0;else throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats");Ge=!0,We=fe.map(q=>this.tokenizer.apply_chat_template(q,{tokenize:!1,add_generation_prompt:!0}))}const He=Ce.add_special_tokens??!1,dt=Ge?!1:Ce.return_full_text??!0;this.tokenizer.padding_side="left";const mt=this.tokenizer(We,{add_special_tokens:He,padding:!0,truncation:!0}),wt=await this.model.generate({...mt,...Ce}),xt=this.tokenizer.batch_decode(wt,{skip_special_tokens:!0});let O;!dt&&mt.input_ids.dims.at(-1)>0&&(O=this.tokenizer.batch_decode(mt.input_ids,{skip_special_tokens:!0}).map(q=>q.length));const ie=Array.from({length:fe.length},q=>[]);for(let q=0;q[Ce.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(fe,Ce,{hypothesis_template:Ue="This example is {}.",multi_label:Ge=!1}={}){const We=Array.isArray(fe);We||(fe=[fe]),Array.isArray(Ce)||(Ce=[Ce]);const He=Ce.map(wt=>Ue.replace("{}",wt)),dt=Ge||Ce.length===1,mt=[];for(const wt of fe){const xt=[];for(const q of He){const de=this.tokenizer(wt,{text_pair:q,padding:!0,truncation:!0}),ve=await this.model(de);dt?xt.push([ve.logits.data[this.contradiction_id],ve.logits.data[this.entailment_id]]):xt.push(ve.logits.data[this.entailment_id])}const ie=(dt?xt.map(q=>(0,M.softmax)(q)[1]):(0,M.softmax)(xt)).map((q,de)=>[q,de]).sort((q,de)=>de[0]-q[0]);mt.push({sequence:wt,labels:ie.map(q=>Ce[q[1]]),scores:ie.map(q=>q[0])})}return We?mt:mt[0]}}class he extends ne{constructor(fe){super(fe)}async _call(fe,{pooling:Ce="none",normalize:Ue=!1,quantize:Ge=!1,precision:We="binary"}={}){const He=this.tokenizer(fe,{padding:!0,truncation:!0}),dt=await this.model(He);let mt=dt.last_hidden_state??dt.logits??dt.token_embeddings;if(Ce!=="none")if(Ce==="mean")mt=(0,F.mean_pooling)(mt,He.attention_mask);else if(Ce==="cls")mt=mt.slice(null,0);else throw Error(`Pooling method '${Ce}' not supported.`);return Ue&&(mt=mt.normalize(2,-1)),Ge&&(mt=(0,F.quantize_embeddings)(mt,We)),mt}}class ke extends ne{constructor(fe){super(fe)}async _call(fe,{pool:Ce=null}={}){const Ue=await G(fe),{pixel_values:Ge}=await this.processor(Ue),We=await this.model({pixel_values:Ge});let He;if(Ce){if(!("pooler_output"in We))throw Error("No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.");He=We.pooler_output}else He=We.last_hidden_state??We.logits??We.image_embeds;return He}}class $e extends ne{constructor(fe){super(fe)}async _call(fe,{top_k:Ce=5}={}){const Ue=this.processor.feature_extractor.config.sampling_rate,Ge=await J(fe,Ue),We=this.model.config.id2label,He=[];for(const dt of Ge){const mt=await this.processor(dt),xt=(await this.model(mt)).logits[0],O=await(0,F.topk)(new F.Tensor("float32",(0,M.softmax)(xt.data),xt.dims),Ce),ie=O[0].tolist(),de=O[1].tolist().map((ve,et)=>({label:We?We[ve]:`LABEL_${ve}`,score:ie[et]}));He.push(de)}return Array.isArray(fe)?He:He[0]}}class Ae extends ne{constructor(fe){super(fe)}async _call(fe,Ce,{hypothesis_template:Ue="This is a sound of {}."}={}){const Ge=!Array.isArray(fe);Ge&&(fe=[fe]);const We=Ce.map(xt=>Ue.replace("{}",xt)),He=this.tokenizer(We,{padding:!0,truncation:!0}),dt=this.processor.feature_extractor.config.sampling_rate,mt=await J(fe,dt),wt=[];for(const xt of mt){const O=await this.processor(xt),ie=await this.model({...He,...O}),q=(0,M.softmax)(ie.logits_per_audio.data);wt.push([...q].map((de,ve)=>({score:de,label:Ce[ve]})))}return Ge?wt[0]:wt}}class Je extends ne{constructor(fe){super(fe)}async _call(fe,Ce={}){switch(this.model.config.model_type){case"whisper":return this._call_whisper(fe,Ce);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":return this._call_wav2vec2(fe,Ce);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(fe,Ce){Ce.language&&console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),Ce.task&&console.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');const Ue=!Array.isArray(fe);Ue&&(fe=[fe]);const Ge=this.processor.feature_extractor.config.sampling_rate,We=await J(fe,Ge),He=[];for(const dt of We){const mt=await this.processor(dt),xt=(await this.model(mt)).logits[0],O=[];for(const q of xt)O.push((0,M.max)(q.data)[1]);const ie=this.tokenizer.decode(O);He.push({text:ie})}return Ue?He[0]:He}async _call_whisper(fe,Ce){const Ue=Ce.return_timestamps??!1,Ge=Ce.chunk_length_s??0,We=Ce.force_full_sequences??!1;let He=Ce.stride_length_s??null;const dt={...Ce};Ue==="word"&&(dt.return_token_timestamps=!0,dt.return_timestamps=!1);const mt=!Array.isArray(fe);mt&&(fe=[fe]);const wt=this.processor.feature_extractor.config.chunk_length/this.model.config.max_source_positions,xt=this.processor.feature_extractor.config.hop_length,O=this.processor.feature_extractor.config.sampling_rate,ie=await J(fe,O),q=[];for(const de of ie){let ve=[];if(Ge>0){if(He===null)He=Ge/6;else if(Ge<=He)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");const At=O*Ge,_t=O*He,Pe=At-2*_t;let j=0;for(;;){const le=j+At,Te=de.subarray(j,le),Ne=await this.processor(Te),De=j===0,je=le>=de.length;if(ve.push({stride:[Te.length,De?0:_t,je?0:_t],input_features:Ne.input_features,is_last:je}),je)break;j+=Pe}}else ve=[{stride:[de.length,0,0],input_features:(await this.processor(de)).input_features,is_last:!0}];for(const At of ve){dt.num_frames=Math.floor(At.stride[0]/xt);const _t=await this.model.generate({inputs:At.input_features,...dt});Ue==="word"?(At.tokens=_t.sequences.tolist()[0],At.token_timestamps=_t.token_timestamps.tolist()[0].map(Pe=>(0,M.round)(Pe,2))):At.tokens=_t[0].tolist(),At.stride=At.stride.map(Pe=>Pe/O)}const[et,nt]=this.tokenizer._decode_asr(ve,{time_precision:wt,return_timestamps:Ue,force_full_sequences:We});q.push({text:et,...nt})}return mt?q[0]:q}}class Xe extends ne{constructor(fe){super(fe)}async _call(fe,Ce={}){const Ue=Array.isArray(fe),Ge=await G(fe),{pixel_values:We}=await this.processor(Ge),He=[];for(const dt of We){dt.dims=[1,...dt.dims];const mt=await this.model.generate({inputs:dt,...Ce}),wt=this.tokenizer.batch_decode(mt,{skip_special_tokens:!0}).map(xt=>({generated_text:xt.trim()}));He.push(wt)}return Ue?He:He[0]}}class pt extends ne{constructor(fe){super(fe)}async _call(fe,{top_k:Ce=5}={}){const Ue=await G(fe),{pixel_values:Ge}=await this.processor(Ue),We=await this.model({pixel_values:Ge}),He=this.model.config.id2label,dt=[];for(const mt of We.logits){const wt=await(0,F.topk)(new F.Tensor("float32",(0,M.softmax)(mt.data),mt.dims),Ce),xt=wt[0].tolist(),ie=wt[1].tolist().map((q,de)=>({label:He?He[q]:`LABEL_${q}`,score:xt[de]}));dt.push(ie)}return Array.isArray(fe)?dt:dt[0]}}class xe extends ne{constructor(fe){super(fe),this.subtasks_mapping={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"}}async _call(fe,{threshold:Ce=.5,mask_threshold:Ue=.5,overlap_mask_area_threshold:Ge=.8,label_ids_to_fuse:We=null,target_sizes:He=null,subtask:dt=null}={}){if(Array.isArray(fe)&&fe.length!==1)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");const wt=await G(fe),xt=wt.map(nt=>[nt.height,nt.width]),{pixel_values:O,pixel_mask:ie}=await this.processor(wt),q=await this.model({pixel_values:O,pixel_mask:ie});let de=null;if(dt!==null)de=this.subtasks_mapping[dt];else for(let[nt,At]of Object.entries(this.subtasks_mapping))if(At in this.processor.feature_extractor){de=this.processor.feature_extractor[At].bind(this.processor.feature_extractor),dt=nt;break}const ve=this.model.config.id2label,et=[];if(dt==="panoptic"||dt==="instance"){const nt=de(q,Ce,Ue,Ge,We,He??xt)[0],At=nt.segmentation;for(const _t of nt.segments_info){const Pe=new Uint8ClampedArray(At.data.length);for(let le=0;leUe.replace("{}",ie)),dt=this.tokenizer(He,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:mt}=await this.processor(We),wt=await this.model({...dt,pixel_values:mt}),xt=this.model.config.model_type==="siglip"?ie=>ie.sigmoid().data:ie=>(0,M.softmax)(ie.data),O=[];for(const ie of wt.logits_per_image){const de=[...xt(ie)].map((ve,et)=>({score:ve,label:Ce[et]}));de.sort((ve,et)=>et.score-ve.score),O.push(de)}return Ge?O:O[0]}}class pe extends ne{constructor(fe){super(fe)}async _call(fe,{threshold:Ce=.9,percentage:Ue=!1}={}){const Ge=Array.isArray(fe);if(Ge&&fe.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");const We=await G(fe),He=Ue?null:We.map(q=>[q.height,q.width]),{pixel_values:dt,pixel_mask:mt}=await this.processor(We),wt=await this.model({pixel_values:dt,pixel_mask:mt}),xt=this.processor.feature_extractor.post_process_object_detection(wt,Ce,He),O=this.model.config.id2label,ie=xt.map(q=>q.boxes.map((de,ve)=>({score:q.scores[ve],label:O[q.classes[ve]],box:te(de,!Ue)})));return Ge?ie:ie[0]}}class Me extends ne{constructor(fe){super(fe)}async _call(fe,Ce,{threshold:Ue=.1,top_k:Ge=null,percentage:We=!1}={}){const He=Array.isArray(fe),dt=await G(fe),mt=this.tokenizer(Ce,{padding:!0,truncation:!0}),wt=await this.processor(dt),xt=[];for(let O=0;O({score:et.scores[_t],label:Ce[et.classes[_t]],box:te(At,!We)})).sort((At,_t)=>_t.score-At.score);Ge!==null&&(nt=nt.slice(0,Ge)),xt.push(nt)}return He?xt:xt[0]}}class se extends ne{constructor(fe){super(fe)}async _call(fe,Ce,Ue={}){throw new Error("This pipeline is not yet supported in Transformers.js v3.")}}class Fe extends ne{constructor(Ce){super(Ce);Ee(this,"DEFAULT_VOCODER_ID","Xenova/speecht5_hifigan");this.vocoder=Ce.vocoder??null}async _call(Ce,{speaker_embeddings:Ue=null}={}){return this.processor?this._call_text_to_spectrogram(Ce,{speaker_embeddings:Ue}):this._call_text_to_waveform(Ce)}async _call_text_to_waveform(Ce){const Ue=this.tokenizer(Ce,{padding:!0,truncation:!0}),{waveform:Ge}=await this.model(Ue),We=this.model.config.sampling_rate;return{audio:Ge.data,sampling_rate:We}}async _call_text_to_spectrogram(Ce,{speaker_embeddings:Ue}){if(this.vocoder||(console.log("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await l.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 F.Tensor("float32",Ue,[1,Ue.length]);else if(!(Ue instanceof F.Tensor))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");const{input_ids:Ge}=this.tokenizer(Ce,{padding:!0,truncation:!0}),{waveform:We}=await this.model.generate_speech(Ge,Ue,{vocoder:this.vocoder}),He=this.processor.feature_extractor.config.sampling_rate;return{audio:We.data,sampling_rate:He}}}class ut extends ne{constructor(fe){super(fe)}async _call(fe){const Ce=await G(fe),Ue=await this.processor(Ce),Ge=await this.model(Ue),We=[];for(const He of Ge.reconstruction){const dt=He.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");We.push(S.RawImage.fromTensor(dt))}return We.length>1?We:We[0]}}class Ye extends ne{constructor(fe){super(fe)}async _call(fe){const Ce=await G(fe),Ue=await this.processor(Ce),{predicted_depth:Ge}=await this.model(Ue),We=[];for(let He=0;He1?We:We[0]}}const st=Object.freeze({"text-classification":{tokenizer:o.AutoTokenizer,pipeline:X,model:l.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{tokenizer:o.AutoTokenizer,pipeline:A,model:l.AutoModelForTokenClassification,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{tokenizer:o.AutoTokenizer,pipeline:P,model:l.AutoModelForQuestionAnswering,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{tokenizer:o.AutoTokenizer,pipeline:L,model:l.AutoModelForMaskedLM,default:{model:"Xenova/bert-base-uncased"},type:"text"},summarization:{tokenizer:o.AutoTokenizer,pipeline:V,model:l.AutoModelForSeq2SeqLM,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{tokenizer:o.AutoTokenizer,pipeline:D,model:l.AutoModelForSeq2SeqLM,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{tokenizer:o.AutoTokenizer,pipeline:Z,model:l.AutoModelForSeq2SeqLM,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{tokenizer:o.AutoTokenizer,pipeline:z,model:l.AutoModelForCausalLM,default:{model:"Xenova/gpt2"},type:"text"},"zero-shot-classification":{tokenizer:o.AutoTokenizer,pipeline:me,model:l.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:$e,model:l.AutoModelForAudioClassification,processor:p.AutoProcessor,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{tokenizer:o.AutoTokenizer,pipeline:Ae,model:l.AutoModel,processor:p.AutoProcessor,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{tokenizer:o.AutoTokenizer,pipeline:Je,model:[l.AutoModelForSpeechSeq2Seq,l.AutoModelForCTC],processor:p.AutoProcessor,default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{tokenizer:o.AutoTokenizer,pipeline:Fe,model:[l.AutoModelForTextToWaveform,l.AutoModelForTextToSpectrogram],processor:[p.AutoProcessor,null],default:{model:"Xenova/speecht5_tts"},type:"text"},"image-to-text":{tokenizer:o.AutoTokenizer,pipeline:Xe,model:l.AutoModelForVision2Seq,processor:p.AutoProcessor,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:pt,model:l.AutoModelForImageClassification,processor:p.AutoProcessor,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:xe,model:[l.AutoModelForImageSegmentation,l.AutoModelForSemanticSegmentation],processor:p.AutoProcessor,default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"zero-shot-image-classification":{tokenizer:o.AutoTokenizer,pipeline:H,model:l.AutoModel,processor:p.AutoProcessor,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:pe,model:l.AutoModelForObjectDetection,processor:p.AutoProcessor,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{tokenizer:o.AutoTokenizer,pipeline:Me,model:l.AutoModelForZeroShotObjectDetection,processor:p.AutoProcessor,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{tokenizer:o.AutoTokenizer,pipeline:se,model:l.AutoModelForDocumentQuestionAnswering,processor:p.AutoProcessor,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:ut,model:l.AutoModelForImageToImage,processor:p.AutoProcessor,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:Ye,model:l.AutoModelForDepthEstimation,processor:p.AutoProcessor,default:{model:"Xenova/dpt-large"},type:"image"},"feature-extraction":{tokenizer:o.AutoTokenizer,pipeline:he,model:l.AutoModel,default:{model:"Xenova/all-MiniLM-L6-v2"},type:"text"},"image-feature-extraction":{processor:p.AutoProcessor,pipeline:ke,model:[l.AutoModelForImageFeatureExtraction,l.AutoModel],default:{model:"Xenova/vit-base-patch16-224-in21k"},type:"image"}}),Oe=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});async function rt(Be,fe=null,{progress_callback:Ce=null,config:Ue=null,cache_dir:Ge=null,local_files_only:We=!1,revision:He="main",device:dt=null,dtype:mt=null,model_file_name:wt=null,session_options:xt={}}={}){Be=Oe[Be]??Be;const O=st[Be.split("_",1)[0]];if(!O)throw Error(`Unsupported pipeline: ${Be}. Must be one of [${Object.keys(st)}]`);fe||(fe=O.default.model,console.log(`No model specified. Using default model: "${fe}".`));const ie={progress_callback:Ce,config:Ue,cache_dir:Ge,local_files_only:We,revision:He,device:dt,dtype:mt,model_file_name:wt,session_options:xt},q=new Map([["tokenizer",O.tokenizer],["model",O.model],["processor",O.processor]]),de=await Tt(q,fe,ie);de.task=Be,(0,C.dispatchCallback)(Ce,{status:"ready",task:Be,model:fe});const ve=O.pipeline;return new ve(de)}async function Tt(Be,fe,Ce){const Ue=Object.create(null),Ge=[];for(let[We,He]of Be.entries()){if(!He)continue;let dt;Array.isArray(He)?dt=new Promise(async(mt,wt)=>{var O,ie;let xt;for(let q of He){if(q===null){mt(null);return}try{mt(await q.from_pretrained(fe,Ce));return}catch(de){if((O=de.message)!=null&&O.includes("Unsupported model type"))xt=de;else if((ie=de.message)!=null&&ie.includes("Could not locate file"))xt=de;else{wt(de);return}}}wt(xt)}):dt=He.from_pretrained(fe,Ce),Ue[We]=dt,Ge.push(dt)}await Promise.all(Ge);for(let[We,He]of Object.entries(Ue))Ue[We]=await He;return Ue}},"./src/processors.js":(e,n,r)=>{r.r(n),r.d(n,{ASTFeatureExtractor:()=>He,AutoProcessor:()=>_t,BeitFeatureExtractor:()=>Ye,BitImageProcessor:()=>L,CLIPFeatureExtractor:()=>V,CLIPImageProcessor:()=>D,ChineseCLIPFeatureExtractor:()=>N,ClapFeatureExtractor:()=>dt,ConvNextFeatureExtractor:()=>me,ConvNextImageProcessor:()=>he,DPTFeatureExtractor:()=>A,DPTImageProcessor:()=>P,DeiTFeatureExtractor:()=>ut,DetrFeatureExtractor:()=>rt,DonutFeatureExtractor:()=>st,EfficientNetImageProcessor:()=>Ae,FeatureExtractor:()=>te,Florence2Processor:()=>At,GLPNFeatureExtractor:()=>Z,ImageFeatureExtractor:()=>ne,MobileNetV1FeatureExtractor:()=>Je,MobileNetV2FeatureExtractor:()=>Xe,MobileNetV3FeatureExtractor:()=>pt,MobileNetV4FeatureExtractor:()=>xe,MobileViTFeatureExtractor:()=>H,MobileViTImageProcessor:()=>pe,NougatImageProcessor:()=>Oe,OwlViTFeatureExtractor:()=>Me,OwlViTProcessor:()=>nt,Owlv2ImageProcessor:()=>se,Processor:()=>O,PyAnnoteFeatureExtractor:()=>mt,PyAnnoteProcessor:()=>ve,RTDetrImageProcessor:()=>Fe,SamImageProcessor:()=>Be,SamProcessor:()=>ie,SeamlessM4TFeatureExtractor:()=>We,SegformerFeatureExtractor:()=>X,SiglipImageProcessor:()=>z,SpeechT5FeatureExtractor:()=>xt,SpeechT5Processor:()=>et,Swin2SRImageProcessor:()=>fe,ViTFeatureExtractor:()=>ke,ViTImageProcessor:()=>$e,VitMatteImageProcessor:()=>Ce,Wav2Vec2FeatureExtractor:()=>Ge,Wav2Vec2ProcessorWithLM:()=>de,WeSpeakerFeatureExtractor:()=>wt,WhisperFeatureExtractor:()=>Ue,WhisperProcessor:()=>q,YolosFeatureExtractor:()=>Tt});var o=r("./src/utils/generic.js"),l=r("./src/utils/core.js"),p=r("./src/utils/hub.js"),_=r("./src/utils/maths.js"),C=r("./src/utils/tensor.js");r("./src/utils/image.js");var M=r("./src/utils/audio.js");function b([Pe,j,le,Te]){return[Pe-le/2,j-Te/2,Pe+le/2,j+Te/2]}function F(Pe,j=.5,le=null,Te=!1){const Ne=Pe.logits,De=Pe.pred_boxes,[je,ct,ot]=Ne.dims;if(le!==null&&le.length!==je)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let bt=[];for(let ft=0;ftj&&Qt.push(qt)}else{let qt=(0,_.max)(Kt.data)[1];if(qt===ot-1||(Jt=(0,_.softmax)(Kt.data),Jt[qt]Hn*St[(Cn+1)%2])),Nt.boxes.push(En),Nt.classes.push(qt),Nt.scores.push(Jt[qt])}}bt.push(Nt)}return bt}function S(Pe,j){var le;if(!(Pe instanceof Float32Array||Pe instanceof Float64Array))throw new Error(`${j} expects input to be a Float32Array or a Float64Array, but got ${((le=Pe==null?void 0:Pe.constructor)==null?void 0:le.name)??typeof Pe} 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.`)}function G(Pe,j,le=0,Te=null){const Ne=Pe/j;let De=(0,_.bankers_round)(Ne)*j;return Te!==null&&De>Te&&(De=Math.floor(Ne)*j),DeDe?bt=Math.floor(De*ot/Ne):De>Ne&&(ot=Math.floor(Ne*bt/De)),await j.resize(bt,ot,{resample:Te}))}async crop_margin(j,le=200){const Te=j.clone().grayscale(),Ne=(0,_.min)(Te.data)[0],je=(0,_.max)(Te.data)[0]-Ne;if(je===0)return j;const ct=le/255;let ot=Te.width,bt=Te.height,ft=0,St=0;const Nt=Te.data;for(let Ke=0;Kethis.preprocess(De)));return{pixel_values:(0,C.stack)(Te.map(De=>De.pixel_values),0),original_sizes:Te.map(De=>De.original_size),reshaped_input_sizes:Te.map(De=>De.reshaped_input_size)}}}class X extends ne{post_process_semantic_segmentation(j,le=null){const Te=j.logits,Ne=Te.dims[0];if(le!==null&&le.length!==Ne)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const De=[];for(let je=0;jeNt[qt]&&(Nt[qt]=Jt[qt],Ke[qt]=Qt)}const Vt=new Array(ot.dims[0]),jt=St.data;for(let Qt=0;QtQt!==void 0);De.push({segmentation:St,labels:Kt})}return De}}class A extends ne{}class P extends A{}class L extends ne{}class Z extends ne{}class V extends ne{}class D extends V{}class N extends ne{}class z extends ne{}class me extends ne{constructor(j){super(j),this.crop_pct=this.config.crop_pct??224/256}async resize(j){var Te;const le=(Te=this.size)==null?void 0:Te.shortest_edge;if(le===void 0)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(le<384){const Ne=Math.floor(le/this.crop_pct),[De,je]=this.get_resize_output_image_size(j,{shortest_edge:Ne});j=await j.resize(De,je,{resample:this.resample}),j=await j.center_crop(le,le)}else j=await j.resize(le,le,{resample:this.resample});return j}}class he extends me{}class ke extends ne{}class $e extends ne{}class Ae extends ne{constructor(j){super(j),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map(le=>le*le))}}class Je extends ne{}class Xe extends ne{}class pt extends ne{}class xe extends ne{}class H extends ne{}class pe extends H{}class Me extends ne{post_process_object_detection(...j){return F(...j)}}class se extends Me{}class Fe extends ne{post_process_object_detection(...j){return F(...j)}}class ut extends ne{}class Ye extends ne{}class st extends ne{pad_image(j,le,Te,Ne={}){const[De,je,ct]=le;let ot=this.image_mean;Array.isArray(this.image_mean)||(ot=new Array(ct).fill(ot));let bt=this.image_std;Array.isArray(bt)||(bt=new Array(ct).fill(ot));const ft=ot.map((St,Nt)=>-St/bt[Nt]);return super.pad_image(j,le,Te,{center:!0,constant_values:ft,...Ne})}}class Oe extends st{}class rt extends ne{async _call(j){const le=await super._call(j),Te=[le.pixel_values.dims[0],64,64],Ne=new C.Tensor("int64",new BigInt64Array(Te.reduce((De,je)=>De*je)).fill(1n),Te);return{...le,pixel_mask:Ne}}post_process_object_detection(...j){return F(...j)}remove_low_and_no_objects(j,le,Te,Ne){let De=[],je=[],ct=[];for(let ot=0;otTe&&(De.push(ft),je.push(Ke),ct.push(St))}return[De,je,ct]}check_segment_validity(j,le,Te,Ne=.5,De=.8){let je=[],ct=0,ot=0;const bt=le[Te].data;for(let St=0;St=Ne&&++ot;let ft=ct>0&&ot>0;return ft&&(ft=ct/ot>De),[ft,je]}compute_segments(j,le,Te,Ne,De,je=null,ct=null){let[ot,bt]=ct??j[0].dims,ft=new C.Tensor("int32",new Int32Array(ot*bt),[ot,bt]),St=[];if(ct!==null)for(let Kt=0;KtKe[qt]&&(Nt[qt]=Kt,Ke[qt]=Jt[qt])}let Vt=0;const jt=ft.data;for(let Kt=0;KtNe!==le.dims[De]))throw Error(`The first ${Te.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new C.Tensor("int64",j.flat(1/0).map(BigInt),Te)}async _call(j,{input_points:le=null,input_labels:Te=null,input_boxes:Ne=null}={}){const De=await super._call(j);if(le&&(De.input_points=this.reshape_input_points(le,De.original_sizes,De.reshaped_input_sizes)),Te){if(!De.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");De.input_labels=this.add_input_labels(Te,De.input_points)}return Ne&&(De.input_boxes=this.reshape_input_points(Ne,De.original_sizes,De.reshaped_input_sizes,!0)),De}async post_process_masks(j,le,Te,{mask_threshold:Ne=0,binarize:De=!0,pad_size:je=null}={}){const ct=[];je=je??this.pad_size;const ot=[je.height,je.width];for(let bt=0;btNe&&(Vt[jt]=1);Nt=new C.Tensor("bool",Vt,Nt.dims)}ct.push(Nt)}return ct}generate_crop_boxes(j,le,{crop_n_layers:Te=0,overlap_ratio:Ne=512/1500,points_per_crop:De=32,crop_n_points_downscale_factor:je=1}={}){}}class fe extends ne{pad_image(j,le,Te,Ne={}){const[De,je,ct]=le;return super.pad_image(j,le,{width:je+(Te-je%Te)%Te,height:De+(Te-De%Te)%Te},{mode:"symmetric",center:!1,constant_values:-1,...Ne})}}class Ce extends ne{async _call(j,le){Array.isArray(j)||(j=[j]),Array.isArray(le)||(le=[le]);const Te=await Promise.all(j.map(je=>this.preprocess(je))),Ne=await Promise.all(le.map(je=>this.preprocess(je,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:(0,C.stack)(Te.map((je,ct)=>(0,C.cat)([je.pixel_values,Ne[ct].pixel_values],0)),0),original_sizes:Te.map(je=>je.original_size),reshaped_input_sizes:Te.map(je=>je.reshaped_input_size)}}}class Ue extends te{constructor(j){var le;super(j),(le=this.config).mel_filters??(le.mel_filters=(0,M.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,M.window_function)(this.config.n_fft,"hann")}async _extract_fbank_features(j){const le=await(0,M.spectrogram)(j,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}),Te=le.data,Ne=(0,_.max)(Te)[0];for(let De=0;Dethis.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`."),le=j.slice(0,this.config.n_samples)):(le=new Float32Array(this.config.n_samples),le.set(j)),{input_features:(await this._extract_fbank_features(le)).unsqueeze_(0)}}}class Ge extends te{_zero_mean_unit_var_norm(j){const Te=j.reduce((De,je)=>De+je,0)/j.length,Ne=j.reduce((De,je)=>De+(je-Te)**2,0)/j.length;return j.map(De=>(De-Te)/Math.sqrt(Ne+1e-7))}async _call(j){S(j,"Wav2Vec2FeatureExtractor"),j instanceof Float64Array&&(j=new Float32Array(j));let le=j;this.config.do_normalize&&(le=this._zero_mean_unit_var_norm(le));const Te=[1,le.length];return{input_values:new C.Tensor("float32",le,Te),attention_mask:new C.Tensor("int64",new BigInt64Array(le.length).fill(1n),Te)}}}class We extends te{constructor(j){super(j);const le=this.config.sampling_rate,Te=(0,M.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(le/2),le,null,"kaldi",!0);for(let Ne=0;NeTe*32768),(0,M.spectrogram)(j,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:le,transpose:!0})}async _call(j,{padding:le=!0,pad_to_multiple_of:Te=2,do_normalize_per_mel_bins:Ne=!0,return_attention_mask:De=!0}={}){S(j,"SeamlessM4TFeatureExtractor");let je=await this._extract_fbank_features(j,this.config.max_length);if(Ne){const[Vt,jt]=je.dims,Kt=je.data;for(let Qt=0;Qt0){const Jt=new Float32Array(jt*(Vt+Qt));Jt.set(Kt),Jt.fill(this.config.padding_value,Kt.length);const qt=Vt+Qt;je=new C.Tensor(je.type,Jt,[qt,jt]),De&&(ct=new C.Tensor("int64",new BigInt64Array(qt),[1,qt]),ct.data.fill(1n,0,Vt))}}const[ot,bt]=je.dims,ft=this.config.stride;if(ot%ft!==0)throw new Error(`The number of frames (${ot}) must be a multiple of the stride (${ft}).`);const Nt=je.view(1,Math.floor(ot/ft),bt*ft),Ke={input_features:Nt};if(De){const Vt=Nt.dims[1],jt=new BigInt64Array(Vt);if(ct){const Kt=ct.data;for(let Qt=1,Jt=0;Qt0)if(Te==="rand_trunc"){const ct=Math.floor(Math.random()*(je+1));j=j.subarray(ct,ct+le),De=await this._extract_fbank_features(j,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${Te}" not implemented`);else{if(je<0){let ct=new Float64Array(le);if(ct.set(j),Ne==="repeat")for(let ot=j.length;ot({id:ot,start:bt*Te,end:ft*Te,confidence:St/(ft-bt)})))}return Ne}}class wt extends te{constructor(j){super(j);const le=this.config.sampling_rate,Te=(0,M.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(le/2),le,null,"kaldi",!0);for(let Ne=0;Nele*32768),(0,M.spectrogram)(j,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(j){S(j,"WeSpeakerFeatureExtractor");const le=(await this._extract_fbank_features(j)).unsqueeze_(0);if(this.config.fbank_centering_span===null){const Te=le.mean(1).data,Ne=le.data,[De,je,ct]=le.dims;for(let ot=0;ot/gm,bboxes:/([^<]+)?/gm},this.size_per_bin=1e3}construct_prompts(j){typeof j=="string"&&(j=[j]);const le=[];for(const Te of j)if(this.task_prompts_without_inputs.has(Te))le.push(this.task_prompts_without_inputs.get(Te));else{for(const[Ne,De]of this.task_prompts_with_input)if(Te.includes(Ne)){le.push(De.replaceAll("{input}",Te).replaceAll(Ne,""));break}le.length!==j.length&&le.push(Te)}return le}post_process_generation(j,le,Te){const Ne=this.tasks_answer_post_processing_type.get(le)??"pure_text";j=j.replaceAll("","").replaceAll("","");let De;switch(Ne){case"pure_text":De=j;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":const je=Ne==="ocr"?"quad_boxes":"bboxes",ct=j.matchAll(this.regexes[je]),ot=[],bt=[];for(const[ft,St,...Nt]of ct)ot.push(St?St.trim():ot.at(-1)??""),bt.push(Nt.map((Ke,Vt)=>(Number(Ke)+.5)/this.size_per_bin*Te[Vt%2]));De={labels:ot,[je]:bt};break;default:throw new Error(`Task "${le}" (of type "${Ne}") not yet implemented.`)}return{[le]:De}}}class _t{static async from_pretrained(j,{progress_callback:le=null,config:Te=null,cache_dir:Ne=null,local_files_only:De=!1,revision:je="main"}={}){let ct=Te??await(0,p.getModelJSON)(j,"preprocessor_config.json",!0,{progress_callback:le,config:Te,cache_dir:Ne,local_files_only:De,revision:je}),ot=ct.feature_extractor_type??ct.image_processor_type,bt=this.FEATURE_EXTRACTOR_CLASS_MAPPING[ot];if(!bt)if(ct.size!==void 0)console.warn(`Feature extractor type "${ot}" not found, assuming ImageFeatureExtractor due to size parameter in config.`),bt=ne;else throw new Error(`Unknown Feature Extractor type: ${ot}`);let ft=this.PROCESSOR_CLASS_MAPPING[ct.processor_class]??O,St=new bt(ct);return new ft(St)}}Ee(_t,"FEATURE_EXTRACTOR_CLASS_MAPPING",{ImageFeatureExtractor:ne,WhisperFeatureExtractor:Ue,ViTFeatureExtractor:ke,MobileViTFeatureExtractor:H,MobileViTImageProcessor:pe,MobileNetV1FeatureExtractor:Je,MobileNetV2FeatureExtractor:Xe,MobileNetV3FeatureExtractor:pt,MobileNetV4FeatureExtractor:xe,OwlViTFeatureExtractor:Me,Owlv2ImageProcessor:se,CLIPFeatureExtractor:V,CLIPImageProcessor:D,Florence2Processor:At,ChineseCLIPFeatureExtractor:N,SiglipImageProcessor:z,ConvNextFeatureExtractor:me,ConvNextImageProcessor:he,SegformerFeatureExtractor:X,BitImageProcessor:L,DPTImageProcessor:P,DPTFeatureExtractor:A,GLPNFeatureExtractor:Z,BeitFeatureExtractor:Ye,DeiTFeatureExtractor:ut,DetrFeatureExtractor:rt,RTDetrImageProcessor:Fe,YolosFeatureExtractor:Tt,DonutFeatureExtractor:st,NougatImageProcessor:Oe,EfficientNetImageProcessor:Ae,ViTImageProcessor:$e,VitMatteImageProcessor:Ce,SamImageProcessor:Be,Swin2SRImageProcessor:fe,Wav2Vec2FeatureExtractor:Ge,SeamlessM4TFeatureExtractor:We,SpeechT5FeatureExtractor:xt,ASTFeatureExtractor:He,ClapFeatureExtractor:dt,PyAnnoteFeatureExtractor:mt,WeSpeakerFeatureExtractor:wt}),Ee(_t,"PROCESSOR_CLASS_MAPPING",{WhisperProcessor:q,Wav2Vec2ProcessorWithLM:de,PyAnnoteProcessor:ve,SamProcessor:ie,SpeechT5Processor:et,OwlViTProcessor:nt,Florence2Processor:At})},"./src/tokenizers.js":(e,n,r)=>{r.r(n),r.d(n,{AlbertTokenizer:()=>jt,AutoTokenizer:()=>zr,BartTokenizer:()=>Nn,BertTokenizer:()=>Vt,BlenderbotSmallTokenizer:()=>Do,BlenderbotTokenizer:()=>uo,BloomTokenizer:()=>Fn,CLIPTokenizer:()=>Xt,CamembertTokenizer:()=>Ct,CodeGenTokenizer:()=>lo,CodeLlamaTokenizer:()=>vs,CohereTokenizer:()=>Rn,ConvBertTokenizer:()=>Hn,DebertaTokenizer:()=>Jt,DebertaV2Tokenizer:()=>qt,DistilBertTokenizer:()=>tt,ElectraTokenizer:()=>nr,EsmTokenizer:()=>Oi,FalconTokenizer:()=>Io,GPT2Tokenizer:()=>_i,GPTNeoXTokenizer:()=>Fo,GemmaTokenizer:()=>so,Grok1Tokenizer:()=>ai,HerbertTokenizer:()=>En,LlamaTokenizer:()=>yi,M2M100Tokenizer:()=>Ki,MBart50Tokenizer:()=>Vn,MBartTokenizer:()=>cr,MPNetTokenizer:()=>Ao,MarianTokenizer:()=>zo,MobileBertTokenizer:()=>Kt,NllbTokenizer:()=>vi,NougatTokenizer:()=>co,PreTrainedTokenizer:()=>Ke,Qwen2Tokenizer:()=>Ms,RoFormerTokenizer:()=>Cn,RobertaTokenizer:()=>si,SiglipTokenizer:()=>Qi,SpeechT5Tokenizer:()=>Lo,SqueezeBertTokenizer:()=>Qt,T5Tokenizer:()=>Fi,TokenizerModel:()=>ke,VitsTokenizer:()=>Bo,Wav2Vec2CTCTokenizer:()=>Oo,WhisperTokenizer:()=>ao,XLMRobertaTokenizer:()=>Po,XLMTokenizer:()=>Lt,is_chinese_char:()=>Z});var o=r("./src/utils/generic.js"),l=r("./src/utils/core.js"),p=r("./src/utils/hub.js"),_=r("./src/utils/maths.js"),C=r("./src/utils/tensor.js"),M=r("./src/utils/data-structures.js"),b=r("./node_modules/@huggingface/jinja/dist/index.js"),F=r("./src/models/whisper/common_whisper.js"),S=r("./src/utils/constants.js");async function G(Se,T){const Q=await Promise.all([(0,p.getModelJSON)(Se,"tokenizer.json",!0,T),(0,p.getModelJSON)(Se,"tokenizer_config.json",!0,T)]);return T.legacy!==null&&(Q[1].legacy=T.legacy),Q}function J(Se,T){const Q=[];let ce=0;for(const ye of Se.matchAll(T)){const we=ye[0];ce0&&Q.push(we),ce=ye.index+we.length}return ce=19968&&Se<=40959||Se>=13312&&Se<=19903||Se>=131072&&Se<=173791||Se>=173824&&Se<=177983||Se>=177984&&Se<=178207||Se>=178208&&Se<=183983||Se>=63744&&Se<=64255||Se>=194560&&Se<=195103}function V(Se,T,Q){const ce=[];let ye=0;for(;yethis.tokens_to_ids.get(Q)??this.unk_token_id)}convert_ids_to_tokens(T){return T.map(Q=>this.vocab[Q]??this.unk_token)}}class $e extends ke{constructor(T){super(T),this.tokens_to_ids=ne(T.vocab),this.unk_token_id=this.tokens_to_ids.get(T.unk_token),this.unk_token=T.unk_token,this.max_input_chars_per_word=T.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(const[Q,ce]of this.tokens_to_ids)this.vocab[ce]=Q}encode(T){const Q=[];for(const ce of T){const ye=[...ce];if(ye.length>this.max_input_chars_per_word){Q.push(this.unk_token);continue}let we=!1,Le=0;const yt=[];for(;Le0&&(Pt=this.config.continuing_subword_prefix+Pt),this.tokens_to_ids.has(Pt)){vt=Pt;break}--Mt}if(vt===null){we=!0;break}yt.push(vt),Le=Mt}we?Q.push(this.unk_token):Q.push(...yt)}return Q}}class Ae extends ke{constructor(T,Q){super(T);const ce=T.vocab.length;this.vocab=new Array(ce),this.scores=new Array(ce);for(let ye=0;ye[ye,we])),this.bosToken=" ",this.bosTokenId=this.tokens_to_ids.get(this.bosToken),this.eosToken=Q.eos_token,this.eosTokenId=this.tokens_to_ids.get(this.eosToken),this.unkToken=this.vocab[this.unk_token_id],this.minScore=(0,_.min)(this.scores)[0],this.unkScore=this.minScore-10,this.scores[this.unk_token_id]=this.unkScore,this.trie=new M.CharTrie,this.trie.extend(this.vocab),this.fuse_unk=!0}populateNodes(T){const Q=T.sentence,ce=Q.length;let ye=0;for(;ye{const Se=[...Array.from({length:94},(ye,we)=>we+33),...Array.from({length:12},(ye,we)=>we+161),...Array.from({length:82},(ye,we)=>we+174)],T=Se.slice();let Q=0;for(let ye=0;ye<256;++ye)Se.includes(ye)||(Se.push(ye),T.push(256+Q),Q+=1);const ce=T.map(ye=>String.fromCharCode(ye));return Object.fromEntries(Se.map((ye,we)=>[ye,ce[we]]))})(),Xe=(0,l.reverseDictionary)(Je);class pt extends ke{constructor(T){super(T),this.BPE_SPLIT_TOKEN=" ",this.tokens_to_ids=ne(T.vocab),this.unk_token_id=this.tokens_to_ids.get(T.unk_token),this.unk_token=T.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(const[Q,ce]of this.tokens_to_ids)this.vocab[ce]=Q;this.bpe_ranks=new Map(T.merges.map((Q,ce)=>[Q,ce])),this.merges=T.merges.map(Q=>Q.split(this.BPE_SPLIT_TOKEN)),this.end_of_word_suffix=T.end_of_word_suffix,this.continuing_subword_suffix=T.continuing_subword_suffix??null,this.byte_fallback=this.config.byte_fallback??!1,this.byte_fallback&&(this.text_encoder=new TextEncoder),this.ignore_merges=this.config.ignore_merges??!1,this.cache=new Map}bpe(T){if(T.length===0)return[];const Q=this.cache.get(T);if(Q!==void 0)return Q;const ce=Array.from(T);this.end_of_word_suffix&&(ce[ce.length-1]+=this.end_of_word_suffix);let ye=[];if(ce.length>1){const we=new M.PriorityQueue((Mt,vt)=>Mt.score`<0x${Le.toString(16).toUpperCase().padStart(2,"0")}>`)):Q.push(this.unk_token)}return Q}}class xe extends ke{constructor(T,Q){super(T),this.tokens_to_ids=ne(Q.target_lang?T.vocab[Q.target_lang]:T.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[ce,ye]of this.tokens_to_ids)this.vocab[ye]=ce}encode(T){return T}}class H extends o.Callable{constructor(T){super(),this.config=T}static fromConfig(T){if(T===null)return null;switch(T.type){case"BertNormalizer":return new Tt(T);case"Precompiled":return new De(T);case"Sequence":return new rt(T);case"Replace":return new pe(T);case"NFC":return new Me(T);case"NFKC":return new se(T);case"NFKD":return new Fe(T);case"Strip":return new ut(T);case"StripAccents":return new Ye(T);case"Lowercase":return new st(T);case"Prepend":return new Oe(T);default:throw new Error(`Unknown Normalizer type: ${T.type}`)}}normalize(T){throw Error("normalize should be implemented in subclass.")}_call(T){return this.normalize(T)}}class pe extends H{normalize(T){const Q=te(this.config.pattern);return Q===null?T:T.replaceAll(Q,this.config.content)}}class Me extends H{normalize(T){return T=T.normalize("NFC"),T}}class se extends H{normalize(T){return T=T.normalize("NFKC"),T}}class Fe extends H{normalize(T){return T=T.normalize("NFKD"),T}}class ut extends H{normalize(T){return this.config.strip_left&&this.config.strip_right?T=T.trim():(this.config.strip_left&&(T=T.trimStart()),this.config.strip_right&&(T=T.trimEnd())),T}}class Ye extends H{normalize(T){return T=P(T),T}}class st extends H{normalize(T){return T=T.toLowerCase(),T}}class Oe extends H{normalize(T){return T=this.config.prepend+T,T}}class rt extends H{constructor(T){super(T),this.normalizers=T.normalizers.map(Q=>H.fromConfig(Q))}normalize(T){return this.normalizers.reduce((Q,ce)=>ce.normalize(Q),T)}}class Tt extends H{_tokenize_chinese_chars(T){const Q=[];for(let ce=0;cethis.pre_tokenize_text(ce,Q)):this.pre_tokenize_text(T,Q)).flat()}_call(T,Q){return this.pre_tokenize(T,Q)}}class fe extends Be{constructor(T){super(),this.pattern=new RegExp(`[^\\s${N}]+|[${N}]`,"gu")}pre_tokenize_text(T,Q){return T.trim().match(this.pattern)||[]}}class Ce extends Be{constructor(T){super(),this.config=T,this.add_prefix_space=this.config.add_prefix_space,this.trim_offsets=this.config.trim_offsets,this.use_regex=this.config.use_regex??!0,this.pattern=new RegExp("'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)|\\s+","gu"),this.byte_encoder=Je,this.text_encoder=new TextEncoder}pre_tokenize_text(T,Q){return this.add_prefix_space&&!T.startsWith(" ")&&(T=" "+T),(this.use_regex?T.match(this.pattern)||[]:[T]).map(ye=>Array.from(this.text_encoder.encode(ye),we=>this.byte_encoder[we]).join(""))}}class Ue extends Be{constructor(T){super(),this.config=T,this.pattern=te(this.config.pattern,this.config.invert)}pre_tokenize_text(T,Q){return this.pattern===null?[]:this.config.invert?T.match(this.pattern)||[]:J(T,this.pattern)}}class Ge extends Be{constructor(T){super(),this.config=T,this.pattern=new RegExp(`[^${N}]+|[${N}]+`,"gu")}pre_tokenize_text(T,Q){return T.match(this.pattern)||[]}}class We extends Be{constructor(T){super(),this.config=T;const Q=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(Q,"gu")}pre_tokenize_text(T,Q){return T.match(this.pattern)||[]}}class He extends o.Callable{constructor(T){super(),this.config=T}static fromConfig(T){if(T===null)return null;switch(T.type){case"TemplateProcessing":return new wt(T);case"ByteLevel":return new xt(T);case"RobertaProcessing":return new mt(T);case"BertProcessing":return new dt(T);case"Sequence":return new O(T);default:throw new Error(`Unknown PostProcessor type: ${T.type}`)}}post_process(T,...Q){throw Error("post_process should be implemented in subclass.")}_call(T,...Q){return this.post_process(T,...Q)}}class dt extends He{constructor(T){super(T),this.cls=T.cls[0],this.sep=T.sep[0]}post_process(T,Q=null,{add_special_tokens:ce=!0}={}){ce&&(T=(0,l.mergeArrays)([this.cls],T,[this.sep]));let ye=new Array(T.length).fill(0);if(Q!==null){const we=ce&&this instanceof mt?[this.sep]:[],Le=ce?[this.sep]:[];T=(0,l.mergeArrays)(T,we,Q,Le),ye=(0,l.mergeArrays)(ye,new Array(Q.length+we.length+Le.length).fill(1))}return{tokens:T,token_type_ids:ye}}}class mt extends dt{}class wt extends He{constructor(T){super(T),this.single=T.single,this.pair=T.pair}post_process(T,Q=null,{add_special_tokens:ce=!0}={}){const ye=Q===null?this.single:this.pair;let we=[],Le=[];for(const yt of ye)"SpecialToken"in yt?ce&&(we.push(yt.SpecialToken.id),Le.push(yt.SpecialToken.type_id)):"Sequence"in yt&&(yt.Sequence.id==="A"?(we=(0,l.mergeArrays)(we,T),Le=(0,l.mergeArrays)(Le,new Array(T.length).fill(yt.Sequence.type_id))):yt.Sequence.id==="B"&&(we=(0,l.mergeArrays)(we,Q),Le=(0,l.mergeArrays)(Le,new Array(Q.length).fill(yt.Sequence.type_id))));return{tokens:we,token_type_ids:Le}}}class xt extends He{post_process(T,Q=null){return Q&&(T=(0,l.mergeArrays)(T,Q)),{tokens:T}}}class O extends He{constructor(T){super(T),this.processors=T.processors.map(Q=>He.fromConfig(Q))}post_process(T,Q=null,ce={}){let ye;for(const we of this.processors)if(we instanceof xt)T=we.post_process(T).tokens,Q&&(Q=we.post_process(Q).tokens);else{const Le=we.post_process(T,Q,ce);T=Le.tokens,ye=Le.token_type_ids}return{tokens:T,token_type_ids:ye}}}class ie extends o.Callable{constructor(T){super(),this.config=T,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets=T.trim_offsets}static fromConfig(T){if(T===null)return null;switch(T.type){case"WordPiece":return new nt(T);case"Metaspace":return new Ne(T);case"ByteLevel":return new At(T);case"Replace":return new q(T);case"ByteFallback":return new de(T);case"Fuse":return new ve(T);case"Strip":return new et(T);case"Sequence":return new Pe(T);case"CTC":return new _t(T);case"BPEDecoder":return new j(T);default:throw new Error(`Unknown Decoder type: ${T.type}`)}}_call(T){return this.decode(T)}decode(T){return this.decode_chain(T).join("")}decode_chain(T){throw Error("`decode_chain` should be implemented in subclass.")}}class q extends ie{decode_chain(T){const Q=te(this.config.pattern);return Q===null?T:T.map(ce=>ce.replaceAll(Q,this.config.content))}}class de extends ie{constructor(T){super(T),this.text_decoder=new TextDecoder}decode_chain(T){const Q=[];let ce=[];for(const ye of T){let we=null;if(ye.length===6&&ye.startsWith("<0x")&&ye.endsWith(">")){const Le=parseInt(ye.slice(3,5),16);isNaN(Le)||(we=Le)}if(we!==null)ce.push(we);else{if(ce.length>0){const Le=this.text_decoder.decode(Uint8Array.from(ce));Q.push(Le),ce=[]}Q.push(ye)}}if(ce.length>0){const ye=this.text_decoder.decode(Uint8Array.from(ce));Q.push(ye),ce=[]}return Q}}class ve extends ie{decode_chain(T){return[T.join("")]}}class et extends ie{constructor(T){super(T),this.content=this.config.content,this.start=this.config.start,this.stop=this.config.stop}decode_chain(T){return T.map(Q=>{let ce=0;for(let we=0;we(ce!==0&&(Q.startsWith(this.config.prefix)?Q=Q.replace(this.config.prefix,""):Q=" "+Q),this.cleanup&&(Q=A(Q)),Q))}}class At extends ie{constructor(T){super(T),this.byte_decoder=Xe,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(T){const Q=T.join(""),ce=new Uint8Array([...Q].map(we=>this.byte_decoder[we]));return this.text_decoder.decode(ce)}decode_chain(T){const Q=[];let ce=[];for(const ye of T)this.added_tokens.find(we=>we.content===ye)!==void 0?(ce.length>0&&(Q.push(this.convert_tokens_to_string(ce)),ce=[]),Q.push(ye)):ce.push(ye);return ce.length>0&&Q.push(this.convert_tokens_to_string(ce)),Q}}class _t extends ie{constructor(T){super(T),this.pad_token=this.config.pad_token,this.word_delimiter_token=this.config.word_delimiter_token,this.cleanup=this.config.cleanup}convert_tokens_to_string(T){if(T.length===0)return"";const Q=[T[0]];for(let we=1;wewe!==this.pad_token).join("");return this.cleanup&&(ye=A(ye).replaceAll(this.word_delimiter_token," ").trim()),ye}decode_chain(T){return[this.convert_tokens_to_string(T)]}}class Pe extends ie{constructor(T){super(T),this.decoders=T.decoders.map(Q=>ie.fromConfig(Q))}decode_chain(T){return this.decoders.reduce((Q,ce)=>ce.decode_chain(Q),T)}}class j extends ie{constructor(T){super(T),this.suffix=this.config.suffix}decode_chain(T){return T.map((Q,ce)=>Q.replaceAll(this.suffix,ce===T.length-1?"":" "))}}class le extends ie{decode_chain(T){let Q="";for(let ce=1;cece.normalize("NFKC")).join("~"):T=T.normalize("NFKC"),T}}class je extends Be{constructor(T){super(),this.tokenizers=T.pretokenizers.map(Q=>Be.fromConfig(Q))}pre_tokenize_text(T,Q){return this.tokenizers.reduce((ce,ye)=>ye.pre_tokenize(ce,Q),[T])}}class ct extends Be{constructor(T){super()}pre_tokenize_text(T,Q){return T.match(/\w+|[^\w\s]+/g)||[]}}class ot extends Be{constructor(T){super()}pre_tokenize_text(T,Q){return D(T)}}class bt extends Be{constructor(T){super(),this.config=T,this.pattern=te(this.config.pattern),this.content=this.config.content}pre_tokenize_text(T,Q){return this.pattern===null?[T]:[T.replaceAll(this.pattern,this.config.content)]}}const ft=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function St(Se,T,Q,ce){for(const ye of Object.keys(Se)){const we=T-Se[ye].length,Le=Q(ye),yt=new Array(we).fill(Le);Se[ye]=ce==="right"?(0,l.mergeArrays)(Se[ye],yt):(0,l.mergeArrays)(yt,Se[ye])}}function Nt(Se,T){for(const Q of Object.keys(Se))Se[Q].length=T}class Ke extends o.Callable{constructor(Q,ce){super();Ee(this,"return_token_type_ids",!1);Ee(this,"padding_side","right");this._tokenizer_config=ce,this.normalizer=H.fromConfig(Q.normalizer),this.pre_tokenizer=Be.fromConfig(Q.pre_tokenizer),this.model=ke.fromConfig(Q.model,ce),this.post_processor=He.fromConfig(Q.post_processor),this.decoder=ie.fromConfig(Q.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];for(const ye of Q.added_tokens){const we=new he(ye);this.added_tokens.push(we),this.model.tokens_to_ids.set(we.content,we.id),this.model.vocab[we.id]=we.content,we.special&&(this.special_tokens.push(we.content),this.all_special_ids.push(we.id))}if(this.additional_special_tokens=ce.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.toSorted((ye,we)=>we.content.length-ye.content.length).map(ye=>`${ye.lstrip?"\\s*":""}(${(0,l.escapeRegExp)(ye.content)})${ye.rstrip?"\\s*":""}`).join("|")):null,this.mask_token=this.getToken("mask_token"),this.mask_token_id=this.model.tokens_to_ids.get(this.mask_token),this.pad_token=this.getToken("pad_token","eos_token"),this.pad_token_id=this.model.tokens_to_ids.get(this.pad_token),this.sep_token=this.getToken("sep_token"),this.sep_token_id=this.model.tokens_to_ids.get(this.sep_token),this.unk_token=this.getToken("unk_token"),this.unk_token_id=this.model.tokens_to_ids.get(this.unk_token),this.model_max_length=ce.model_max_length,this.remove_space=ce.remove_space,this.clean_up_tokenization_spaces=ce.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=ce.do_lowercase_and_remove_accent??!1,ce.padding_side&&(this.padding_side=ce.padding_side),this.legacy=!1,this.chat_template=ce.chat_template??null,Array.isArray(this.chat_template)){const ye=Object.create(null);for(const{name:we,template:Le}of this.chat_template){if(typeof we!="string"||typeof Le!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');ye[we]=Le}this.chat_template=ye}this._compiled_template_cache=new Map}getToken(...Q){for(const ce of Q){const ye=this._tokenizer_config[ce];if(ye)if(typeof ye=="object"){if(ye.__type==="AddedToken")return ye.content;throw Error(`Unknown token: ${ye}`)}else return ye}return null}static async from_pretrained(Q,{progress_callback:ce=null,config:ye=null,cache_dir:we=null,local_files_only:Le=!1,revision:yt="main",legacy:Mt=null}={}){const vt=await G(Q,{progress_callback:ce,config:ye,cache_dir:we,local_files_only:Le,revision:yt,legacy:Mt});return new this(...vt)}_call(Q,{text_pair:ce=null,add_special_tokens:ye=!0,padding:we=!1,truncation:Le=null,max_length:yt=null,return_tensor:Mt=!0,return_token_type_ids:vt=null}={}){const Pt=Array.isArray(Q);let Zt;if(Pt){if(Q.length===0)throw Error("text array must be non-empty");if(ce!==null){if(Array.isArray(ce)){if(Q.length!==ce.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");Zt=Q.map((nn,Gt)=>this._encode_plus(nn,{text_pair:ce[Gt],add_special_tokens:ye,return_token_type_ids:vt}))}else Zt=Q.map(nn=>this._encode_plus(nn,{add_special_tokens:ye,return_token_type_ids:vt}))}else{if(Q==null)throw Error("text may not be null or undefined");if(Array.isArray(ce))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");Zt=[this._encode_plus(Q,{text_pair:ce,add_special_tokens:ye,return_token_type_ids:vt})]}if(yt===null?we==="max_length"?yt=this.model_max_length:yt=(0,_.max)(Zt.map(nn=>nn.input_ids.length))[0]:Le||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."),yt=Math.min(yt,this.model_max_length??1/0),we||Le)for(let nn=0;nnyt?Le&&Nt(Zt[nn],yt):we&&St(Zt[nn],yt,Gt=>Gt==="input_ids"?this.pad_token_id:0,this.padding_side));const $n={};if(Mt){if(!(we&&Le)&&Zt.some(Gt=>{var mn;for(const Mr of Object.keys(Gt))if(Gt[Mr].length!==((mn=Zt[0][Mr])==null?void 0:mn.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 nn=[Zt.length,Zt[0].input_ids.length];for(const Gt of Object.keys(Zt[0]))$n[Gt]=new C.Tensor("int64",BigInt64Array.from(Zt.flatMap(mn=>mn[Gt]).map(BigInt)),nn)}else{for(const nn of Object.keys(Zt[0]))$n[nn]=Zt.map(Gt=>Gt[nn]);if(!Pt)for(const nn of Object.keys($n))$n[nn]=$n[nn][0]}return $n}_encode_text(Q){return Q===null?null:(this.added_tokens_regex?Q.split(this.added_tokens_regex).filter(we=>we):[Q]).map((we,Le)=>{if(this.added_tokens.find(Mt=>Mt.content===we)!==void 0)return we;{if(this.remove_space===!0&&(we=we.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(we=L(we)),this.normalizer!==null&&(we=this.normalizer(we)),we.length===0)return[];const Mt=this.pre_tokenizer!==null?this.pre_tokenizer(we,{section_index:Le}):[we];return this.model(Mt)}}).flat()}_encode_plus(Q,{text_pair:ce=null,add_special_tokens:ye=!0,return_token_type_ids:we=null}={}){const{tokens:Le,token_type_ids:yt}=this._tokenize_helper(Q,{pair:ce,add_special_tokens:ye}),Mt=this.model.convert_tokens_to_ids(Le),vt={input_ids:Mt,attention_mask:new Array(Mt.length).fill(1)};return(we??this.return_token_type_ids)&&yt&&(vt.token_type_ids=yt),vt}_tokenize_helper(Q,{pair:ce=null,add_special_tokens:ye=!1}={}){const we=this._encode_text(Q),Le=this._encode_text(ce);return this.post_processor?this.post_processor(we,Le,{add_special_tokens:ye}):{tokens:(0,l.mergeArrays)(we??[],Le??[])}}tokenize(Q,{pair:ce=null,add_special_tokens:ye=!1}={}){return this._tokenize_helper(Q,{pair:ce,add_special_tokens:ye}).tokens}encode(Q,{text_pair:ce=null,add_special_tokens:ye=!0,return_token_type_ids:we=null}={}){return this._encode_plus(Q,{text_pair:ce,add_special_tokens:ye,return_token_type_ids:we}).input_ids}batch_decode(Q,ce={}){return Q instanceof C.Tensor&&(Q=Q.tolist()),Q.map(ye=>this.decode(ye,ce))}decode(Q,ce={}){if(Q instanceof C.Tensor&&(Q=X(Q)),!Array.isArray(Q)||Q.length===0||!(0,l.isIntegralNumber)(Q[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(Q,ce)}decode_single(Q,{skip_special_tokens:ce=!1,clean_up_tokenization_spaces:ye=null}){let we=this.model.convert_ids_to_tokens(Q);ce&&(we=we.filter(yt=>!this.special_tokens.includes(yt)));let Le=this.decoder?this.decoder(we):we.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(Le=Le.replaceAll(this.decoder.end_of_word_suffix," "),ce&&(Le=Le.trim())),(ye??this.clean_up_tokenization_spaces)&&(Le=A(Le)),Le}apply_chat_template(Q,{tools:ce=null,documents:ye=null,chat_template:we=null,add_generation_prompt:Le=!1,tokenize:yt=!0,padding:Mt=!1,truncation:vt=!1,max_length:Pt=null,return_tensor:Zt=!0,return_dict:$n=!1,tokenizer_kwargs:nn={},...Gt}={}){if(this.chat_template&&typeof this.chat_template=="object"||this.chat_template===null){const Ve=this.chat_template;if(we!==null&&Object.hasOwn(Ve,we))we=Ve[we];else if(we===null&&"default"in Ve)we=Ve.default;else if(we===null)throw Error(`This model has multiple chat templates with no default specified! Please either pass a chat template or the name of the template you wish to use to the 'chat_template' argument. Available template names are ${Object.keys(Ve).sort()}.`)}else if(this.chat_template)we=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");if(typeof we!="string")throw Error(`chat_template must be a string, but got ${typeof we}`);let mn=this._compiled_template_cache.get(we);mn===void 0&&(mn=new b.Template(we),this._compiled_template_cache.set(we,mn));const Mr=Object.create(null);for(const Ve of ft){const Vr=this.getToken(Ve);Vr&&(Mr[Ve]=Vr)}const ur=mn.render({messages:Q,add_generation_prompt:Le,tools:ce,documents:ye,...Mr,...Gt});if(yt){const Ve=this._call(ur,{add_special_tokens:!1,padding:Mt,truncation:vt,max_length:Pt,return_tensor:Zt,...nn});return $n?Ve:Ve.input_ids}return ur}}class Vt extends Ke{constructor(){super(...arguments);Ee(this,"return_token_type_ids",!0)}}class jt extends Ke{constructor(){super(...arguments);Ee(this,"return_token_type_ids",!0)}}class Kt extends Ke{constructor(){super(...arguments);Ee(this,"return_token_type_ids",!0)}}class Qt extends Ke{constructor(){super(...arguments);Ee(this,"return_token_type_ids",!0)}}class Jt extends Ke{constructor(){super(...arguments);Ee(this,"return_token_type_ids",!0)}}class qt extends Ke{constructor(){super(...arguments);Ee(this,"return_token_type_ids",!0)}}class En extends Ke{constructor(){super(...arguments);Ee(this,"return_token_type_ids",!0)}}class Hn extends Ke{constructor(){super(...arguments);Ee(this,"return_token_type_ids",!0)}}class Cn extends Ke{constructor(){super(...arguments);Ee(this,"return_token_type_ids",!0)}}class tt extends Ke{}class Ct extends Ke{}class Lt extends Ke{constructor(Q,ce){super(Q,ce);Ee(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 nr extends Ke{constructor(){super(...arguments);Ee(this,"return_token_type_ids",!0)}}class Fi extends Ke{}class _i extends Ke{}class Nn extends Ke{}class cr extends Ke{constructor(T,Q){super(T,Q),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.special_tokens.filter(ce=>this.languageRegex.test(ce)),this.lang_to_token=ce=>ce}_build_translation_inputs(T,Q,ce){return wi(this,T,Q,ce)}}class Vn extends cr{}class si extends Ke{}class Fn extends Ke{constructor(T,Q){var we,Le;const ce=".,!?…。,、।۔،",ye=(Le=(we=T.pre_tokenizer)==null?void 0:we.pretokenizers[0])==null?void 0:Le.pattern;ye&&ye.Regex===` ?[^(\\s|[${ce}])]+`&&(ye.Regex=` ?[^\\s${ce}]+`),super(T,Q)}}const zi="▁";class yi extends Ke{constructor(Q,ce){super(Q,ce);Ee(this,"padding_side","left");this.legacy=ce.legacy??!0,this.legacy||(this.normalizer=null,this.pre_tokenizer=new Te({replacement:zi,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 ce=super._encode_text(zi+Q.replaceAll(zi," "));return ce.length>1&&ce[0]===zi&&this.special_tokens.includes(ce[1])&&(ce=ce.slice(1)),ce}}class vs extends Ke{}class Po extends Ke{}class Ao extends Ke{}class Io extends Ke{}class Fo extends Ke{}class Oi extends Ke{}class Ms extends Ke{}class so extends Ke{}class ai extends Ke{}function wi(Se,T,Q,ce){if(!("language_codes"in Se)||!Array.isArray(Se.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in Se)||!(Se.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in Se)||typeof Se.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");const ye=ce.src_lang,we=ce.tgt_lang;if(!Se.language_codes.includes(we))throw new Error(`Target language code "${we}" is not valid. Must be one of: {${Se.language_codes.join(", ")}}`);if(ye!==void 0){if(!Se.language_codes.includes(ye))throw new Error(`Source language code "${ye}" is not valid. Must be one of: {${Se.language_codes.join(", ")}}`);for(const Le of Se.post_processor.config.single)if("SpecialToken"in Le&&Se.languageRegex.test(Le.SpecialToken.id)){Le.SpecialToken.id=Se.lang_to_token(ye);break}}return ce.forced_bos_token_id=Se.model.convert_tokens_to_ids([Se.lang_to_token(we)])[0],Se._call(T,Q)}class vi extends Ke{constructor(T,Q){super(T,Q),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.special_tokens.filter(ce=>this.languageRegex.test(ce)),this.lang_to_token=ce=>ce}_build_translation_inputs(T,Q,ce){return wi(this,T,Q,ce)}}class Ki extends Ke{constructor(T,Q){super(T,Q),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.special_tokens.filter(ce=>this.languageRegex.test(ce)).map(ce=>ce.slice(2,-2)),this.lang_to_token=ce=>`__${ce}__`}_build_translation_inputs(T,Q,ce){return wi(this,T,Q,ce)}}class ao extends Ke{get timestamp_begin(){return this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0]+1}_decode_asr(T,{return_timestamps:Q=!1,return_language:ce=!1,time_precision:ye=null,force_full_sequences:we=!0}={}){if(ye===null)throw Error("Must specify time_precision");let Le=null;const yt=Q==="word";function Mt(){return{language:Le,timestamp:[null,null],text:""}}const vt=[];let Pt=Mt(),Zt=0;const $n=this.timestamp_begin;let nn=[],Gt=[],mn=!1,Mr=null;const ur=new Set(this.all_special_ids);for(const bn of T){const rr=bn.tokens,kr=yt?bn.token_timestamps:null;let Yt=null,Or=$n;if("stride"in bn){const[Sn,Et,wn]=bn.stride;if(Zt-=Et,Mr=Sn-wn,Et&&(Or=Et/ye+$n),wn)for(let zn=rr.length-1;zn>=0;--zn){const Un=Number(rr[zn]);if(Un>=$n){if(Yt!==null&&(Un-$n)*ye=$n){const wn=(Et-$n)*ye+Zt,zn=(0,_.round)(wn,2);if(Yt!==null&&Et>=Yt)mn=!0;else if(mn||nn.length>0&&Et0?(nn.push(pr),yt&&Gt.push(Tn)):nn.every(Sn=>Sn.length===0)&&(Pt=Mt(),nn=[],pr=[],Gt=[],Tn=[])}if(nn.length>0){if(we&&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[bn,rr]=this.findLongestCommonSequence(nn,Gt),kr=this.decode(bn);Pt.text=kr,yt&&(Pt.words=this.collateWordTimestamps(bn,rr,Le)),vt.push(Pt)}let Ve=Object.create(null);const Vr=vt.map(bn=>bn.text).join("");if(Q||ce){for(let bn=0;bn0;let yt=Le?[]:null,Mt=Le?Q[0]:null;for(let vt=1;vtzn===Tn[Un]&&Mt[rr+Un]<=Q[vt][Or+Un]).length:Sn=Yt.filter((zn,Un)=>zn===Tn[Un]).length;const Et=bn/1e4,wn=Sn/bn+Et;Sn>1&&wn>Zt&&(Zt=wn,$n=[rr,kr,Or,pr])}const[Gt,mn,Mr,ur]=$n,Ve=Math.floor((mn+Gt)/2),Vr=Math.floor((ur+Mr)/2);we.push(...ce.slice(0,Ve)),ce=Pt.slice(Vr),ye=ce.length,Le&&(yt.push(...Mt.slice(0,Ve)),Mt=Q[vt].slice(Vr))}return we.push(...ce),Le?(yt.push(...Mt),[we,yt]):[we,[]]}collateWordTimestamps(T,Q,ce){const[ye,we,Le]=this.combineTokensIntoWords(T,ce),yt=[];for(let Mt=0;Mt=ye){const yt=((Le-ye)*ce).toFixed(2);we.push(`<|${yt}|>`),we.push([])}else we[we.length-1].push(Le);return we=we.map(Le=>typeof Le=="string"?Le:super.decode(Le,Q)),we.join("")}splitTokensOnUnicode(T){const Q=this.decode(T,{decode_with_timestamps:!0}),ce="�",ye=[],we=[],Le=[];let yt=[],Mt=[],vt=0;for(let Pt=0;Pt=this.model.tokens_to_ids.get("<|endoftext|>"),Gt=Pt.startsWith(" "),mn=Pt.trim(),Mr=Mt.test(mn);if(nn||Gt||Mr||we.length===0)we.push(Pt),Le.push(Zt),yt.push($n);else{const ur=we.length-1;we[ur]+=Pt,Le[ur].push(...Zt),yt[ur].push(...$n)}}return[we,Le,yt]}mergePunctuations(T,Q,ce,ye,we){const Le=structuredClone(T),yt=structuredClone(Q),Mt=structuredClone(ce);let vt=Le.length-2,Pt=Le.length-1;for(;vt>=0;)Le[vt].startsWith(" ")&&ye.includes(Le[vt].trim())?(Le[Pt]=Le[vt]+Le[Pt],yt[Pt]=(0,l.mergeArrays)(yt[vt],yt[Pt]),Mt[Pt]=(0,l.mergeArrays)(Mt[vt],Mt[Pt]),Le[vt]="",yt[vt]=[],Mt[vt]=[]):Pt=vt,--vt;for(vt=0,Pt=1;PtZt),yt.filter(Zt=>Zt.length>0),Mt.filter(Zt=>Zt.length>0)]}get_decoder_prompt_ids({language:T=null,task:Q=null,no_timestamps:ce=!0}={}){const ye=[];if(T){const we=(0,F.whisper_language_to_code)(T),Le=this.model.tokens_to_ids.get(`<|${we}|>`);if(Le===void 0)throw new Error(`Unable to find language "${we}" in model vocabulary. Please report this issue at ${S.GITHUB_ISSUE_URL}.`);ye.push(Le)}else ye.push(null);if(Q){if(Q=Q.toLowerCase(),Q!=="transcribe"&&Q!=="translate")throw new Error(`Task "${Q}" is not supported. Must be one of: ["transcribe", "translate"]`);const we=this.model.tokens_to_ids.get(`<|${Q}|>`);if(we===void 0)throw new Error(`Unable to find task "${Q}" in model vocabulary. Please report this issue at ${S.GITHUB_ISSUE_URL}.`);ye.push(we)}else ye.push(null);if(ce){const we=this.model.tokens_to_ids.get("<|notimestamps|>");if(we===void 0)throw new Error(`Unable to find "<|notimestamps|>" in model vocabulary. Please report this issue at ${S.GITHUB_ISSUE_URL}.`);ye.push(we)}return ye.map((we,Le)=>[Le+1,we]).filter(we=>we[1]!==null)}}class lo extends Ke{}class Xt extends Ke{}class Qi extends Ke{}class zo extends Ke{constructor(T,Q){super(T,Q),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=this.model.vocab.filter(ce=>this.languageRegex.test(ce)),console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(T){if(T===null)return null;const[Q,...ce]=T.trim().split(this.languageRegex);if(ce.length===0)return super._encode_text(Q);if(ce.length===2){const[ye,we]=ce;return this.supported_language_codes.includes(ye)||console.warn(`Unsupported language code "${ye}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),(0,l.mergeArrays)([ye],super._encode_text(we))}}}class Oo extends Ke{}class uo extends Ke{}class Do extends Ke{}class Lo extends Ke{}class co extends Ke{}class Bo extends Ke{constructor(T,Q){super(T,Q),this.decoder=new le({})}}class Rn extends Ke{}class zr{static async from_pretrained(T,{progress_callback:Q=null,config:ce=null,cache_dir:ye=null,local_files_only:we=!1,revision:Le="main",legacy:yt=null}={}){var $n;const[Mt,vt]=await G(T,{progress_callback:Q,config:ce,cache_dir:ye,local_files_only:we,revision:Le,legacy:yt}),Pt=(($n=vt.tokenizer_class)==null?void 0:$n.replace(/Fast$/,""))??"PreTrainedTokenizer";let Zt=this.TOKENIZER_CLASS_MAPPING[Pt];return Zt||(console.warn(`Unknown tokenizer class "${Pt}", attempting to construct from base class.`),Zt=Ke),new Zt(Mt,vt)}}Ee(zr,"TOKENIZER_CLASS_MAPPING",{T5Tokenizer:Fi,DistilBertTokenizer:tt,CamembertTokenizer:Ct,DebertaTokenizer:Jt,DebertaV2Tokenizer:qt,BertTokenizer:Vt,HerbertTokenizer:En,ConvBertTokenizer:Hn,RoFormerTokenizer:Cn,XLMTokenizer:Lt,ElectraTokenizer:nr,MobileBertTokenizer:Kt,SqueezeBertTokenizer:Qt,AlbertTokenizer:jt,GPT2Tokenizer:_i,BartTokenizer:Nn,MBartTokenizer:cr,MBart50Tokenizer:Vn,RobertaTokenizer:si,WhisperTokenizer:ao,CodeGenTokenizer:lo,CLIPTokenizer:Xt,SiglipTokenizer:Qi,MarianTokenizer:zo,BloomTokenizer:Fn,NllbTokenizer:vi,M2M100Tokenizer:Ki,LlamaTokenizer:yi,CodeLlamaTokenizer:vs,XLMRobertaTokenizer:Po,MPNetTokenizer:Ao,FalconTokenizer:Io,GPTNeoXTokenizer:Fo,EsmTokenizer:Oi,Wav2Vec2CTCTokenizer:Oo,BlenderbotTokenizer:uo,BlenderbotSmallTokenizer:Do,SpeechT5Tokenizer:Lo,NougatTokenizer:co,VitsTokenizer:Bo,Qwen2Tokenizer:Ms,GemmaTokenizer:so,Grok1Tokenizer:ai,CohereTokenizer:Rn,PreTrainedTokenizer:Ke})},"./src/utils/audio.js":(e,n,r)=>{r.r(n),r.d(n,{hamming:()=>F,hanning:()=>b,mel_filter_bank:()=>A,read_audio:()=>C,spectrogram:()=>D,window_function:()=>N});var o=r("./src/utils/hub.js"),l=r("./src/utils/maths.js"),p=r("./src/utils/core.js"),_=r("./src/utils/tensor.js");async function C(z,me){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 he=await(await(0,o.getFile)(z)).arrayBuffer(),ke=new AudioContext({sampleRate:me});typeof me>"u"&&console.warn(`No sampling rate provided, using default of ${ke.sampleRate}Hz.`);const $e=await ke.decodeAudioData(he);let Ae;if($e.numberOfChannels===2){const Je=Math.sqrt(2),Xe=$e.getChannelData(0),pt=$e.getChannelData(1);Ae=new Float32Array(Xe.length);for(let xe=0;xe<$e.length;++xe)Ae[xe]=Je*(Xe[xe]+pt[xe])/2}else Ae=$e.getChannelData(0);return Ae}function M(z,me){if(z<1)return new Float64Array;if(z===1)return new Float64Array([1]);const he=1-me,ke=2*Math.PI/(z-1),$e=new Float64Array(z);for(let Ae=0;Ae2595*Math.log10(1+z/700),kaldi:z=>1127*Math.log(1+z/700),slaney:(z,me=1e3,he=15,ke=27/Math.log(6.4))=>z>=me?he+Math.log(z/me)*ke:3*z/200};function G(z,me="htk"){const he=S[me];if(!he)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof z=="number"?he(z):z.map(ke=>he(ke))}const J={htk:z=>700*(10**(z/2595)-1),kaldi:z=>700*(Math.exp(z/1127)-1),slaney:(z,me=1e3,he=15,ke=Math.log(6.4)/27)=>z>=he?me*Math.exp(ke*(z-he)):200*z/3};function te(z,me="htk"){const he=J[me];if(!he)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof z=="number"?he(z):z.map(ke=>he(ke))}function ne(z,me){const he=Float64Array.from({length:me.length-1},(Je,Xe)=>me[Xe+1]-me[Xe]),ke=Array.from({length:z.length},()=>new Array(me.length));for(let Je=0;Jenew Array(z.length));for(let Je=0;Jez+ke*Ae)}function A(z,me,he,ke,$e,Ae=null,Je="htk",Xe=!1){if(Ae!==null&&Ae!=="slaney")throw new Error('norm must be one of null or "slaney"');const pt=G(he,Je),xe=G(ke,Je),H=X(pt,xe,me+2);let pe=te(H,Je),Me;if(Xe){const Fe=$e/(z*2);Me=G(Float64Array.from({length:z},(ut,Ye)=>Ye*Fe),Je),pe=H}else Me=X(0,Math.floor($e/2),z);const se=ne(Me,pe);if(Ae!==null&&Ae==="slaney")for(let Fe=0;Fe$e)throw Error(`frame_length (${he}) may not be larger than fft_length (${$e})`);if(Be!==he)throw new Error(`Length of the window (${Be}) must equal frame_length (${he})`);if(ke<=0)throw new Error("hop_length must be greater than zero");if(Ae===null&&H!==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(Je){if(Xe!=="reflect")throw new Error(`pad_mode="${Xe}" not implemented yet.`);const ie=Math.floor(($e-1)/2)+1;z=P(z,ie,ie)}let fe=Math.floor(1+Math.floor((z.length-he)/ke));st!==null&&fefe?rt&&(Ge=Oe):Ge=Ue=Oe);const We=new l.FFT($e),He=new Float64Array($e),dt=new Float64Array(We.outputBufferSize),mt=new Float32Array(Ce*Ge);for(let ie=0;ie=1;--ve)He[ve]-=xe*He[ve-1];He[0]*=1-xe}for(let ve=0;veMath.pow(Xe,.85));break;default:throw new Error(`Unknown window type ${me}.`)}if(he&&(Je=Je.subarray(0,z)),ke===null)return Je;if(z>ke)throw new Error(`Length of the window (${z}) may not be larger than frame_length (${ke})`);return Je}},"./src/utils/constants.js":(e,n,r)=>{r.r(n),r.d(n,{GITHUB_ISSUE_URL:()=>o});const o="https://github.com/xenova/transformers.js/issues/new/choose"},"./src/utils/core.js":(e,n,r)=>{r.r(n),r.d(n,{calculateDimensions:()=>M,calculateReflectOffset:()=>G,dispatchCallback:()=>o,escapeRegExp:()=>p,isIntegralNumber:()=>C,isTypedArray:()=>_,mergeArrays:()=>F,pick:()=>J,pop:()=>b,product:()=>S,reverseDictionary:()=>l});function o(te,ne){te&&te(ne)}function l(te){return Object.fromEntries(Object.entries(te).map(([ne,X])=>[X,ne]))}function p(te){return te.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function _(te){var ne,X,A;return((A=(X=(ne=te==null?void 0:te.prototype)==null?void 0:ne.__proto__)==null?void 0:X.constructor)==null?void 0:A.name)==="TypedArray"}function C(te){return Number.isInteger(te)||typeof te=="bigint"}function M(te){const ne=[];let X=te;for(;Array.isArray(X);)ne.push(X.length),X=X[0];return ne}function b(te,ne,X=void 0){const A=te[ne];if(A!==void 0)return delete te[ne],A;if(X===void 0)throw Error(`Key ${ne} does not exist in object.`);return X}function F(...te){return Array.prototype.concat.apply([],te)}function S(...te){return te.reduce((ne,X)=>ne.flatMap(A=>X.map(P=>[A,P])))}function G(te,ne){return Math.abs((te+ne)%(2*ne)-ne)}function J(te,ne){return Object.assign({},...ne.map(X=>{if(te[X]!==void 0)return{[X]:te[X]}}))}},"./src/utils/data-structures.js":(e,n,r)=>{r.r(n),r.d(n,{CharTrie:()=>l,PriorityQueue:()=>o,TokenLattice:()=>_});class o{constructor(b=(S,G)=>S>G,F=1/0){this._heap=[],this._comparator=b,this._maxSize=F}get size(){return this._heap.length}isEmpty(){return this.size===0}peek(){return this._heap[0]}push(...b){return this.extend(b)}extend(b){for(const F of b)if(this.size0&&this._swap(0,F),this._heap.pop(),this._siftDown(),b}replace(b){const F=this.peek();return this._heap[0]=b,this._siftDown(),F}_parent(b){return(b+1>>>1)-1}_left(b){return(b<<1)+1}_right(b){return b+1<<1}_greater(b,F){return this._comparator(this._heap[b],this._heap[F])}_swap(b,F){const S=this._heap[b];this._heap[b]=this._heap[F],this._heap[F]=S}_siftUp(){this._siftUpFrom(this.size-1)}_siftUpFrom(b){for(;b>0&&this._greater(b,this._parent(b));)this._swap(b,this._parent(b)),b=this._parent(b)}_siftDown(){let b=0;for(;this._left(b)[]),this.endNodes=Array.from({length:this.len+1},()=>[]);const G=new C(this.bosTokenId,0,0,0,0),J=new C(this.eosTokenId,1,this.len,0,0);this.nodes.push(G.clone()),this.nodes.push(J.clone()),this.beginNodes[this.len].push(J),this.endNodes[0].push(G)}insert(b,F,S,G){const J=this.nodes.length,te=new C(G,J,b,F,S);this.beginNodes[b].push(te),this.endNodes[b+F].push(te),this.nodes.push(te)}viterbi(){const b=this.len;let F=0;for(;F<=b;){if(this.beginNodes[F].length==0)return[];for(let ne of this.beginNodes[F]){ne.prev=null;let X=0,A=null;for(let P of this.endNodes[F]){const L=P.backtraceScore+ne.score;(A===null||L>X)&&(A=P.clone(),X=L)}if(A!==null)ne.prev=A,ne.backtraceScore=X;else return[]}++F}const S=[],J=this.beginNodes[b][0].prev;if(J===null)return[];let te=J.clone();for(;te.prev!==null;)S.push(te.clone()),te=te.clone().prev.clone();return S.reverse(),S}piece(b){return this.sentence.slice(b.pos,b.pos+b.length)}tokens(){return this.viterbi().map(F=>this.piece(F))}tokenIds(){return this.viterbi().map(F=>F.tokenId)}}class C{constructor(b,F,S,G,J){this.tokenId=b,this.nodeId=F,this.pos=S,this.length=G,this.score=J,this.prev=null,this.backtraceScore=0}clone(){const b=new C(this.tokenId,this.nodeId,this.pos,this.length,this.score);return b.prev=this.prev,b.backtraceScore=this.backtraceScore,b}}},"./src/utils/devices.js":(e,n,r)=>{r.r(n),r.d(n,{DEVICE_TYPES:()=>o});const o=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,n,r)=>{r.r(n),r.d(n,{DATA_TYPES:()=>_,DEFAULT_DEVICE_DTYPE_MAPPING:()=>C,DEFAULT_DTYPE_SUFFIX_MAPPING:()=>M,isWebGpuFp16Supported:()=>p});var o=r("./src/env.js"),l=r("./src/utils/devices.js");const p=function(){let b;return async function(){if(b===void 0)if(!o.apis.IS_WEBGPU_AVAILABLE)b=!1;else try{b=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{b=!1}return b}}(),_=Object.freeze({fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16"}),C=Object.freeze({[l.DEVICE_TYPES.wasm]:_.q8}),M=Object.freeze({[_.fp32]:"",[_.fp16]:"_fp16",[_.int8]:"_int8",[_.uint8]:"_uint8",[_.q8]:"_quantized",[_.q4]:"_q4",[_.q4f16]:"_q4f16",[_.bnb4]:"_bnb4"})},"./src/utils/generic.js":(e,n,r)=>{r.r(n),r.d(n,{Callable:()=>o});const o=class{constructor(){let l=function(...p){return l._call(...p)};return Object.setPrototypeOf(l,new.target.prototype)}_call(...l){throw Error("Must implement _call method in subclass")}}},"./src/utils/hub.js":(e,n,r)=>{r.r(n),r.d(n,{getFile:()=>F,getModelFile:()=>ne,getModelJSON:()=>X});var o=r("?7a2c"),l=r("?a42a"),p=r("./src/env.js"),_=r("./src/utils/core.js");const C={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 M{constructor(Z){if(this.filePath=Z,this.headers=new Headers,this.exists=o.existsSync(Z),this.exists){this.status=200,this.statusText="OK";let V=o.statSync(Z);this.headers.set("content-length",V.size.toString()),this.updateContentType();let D=this;this.body=new ReadableStream({start(N){D.arrayBuffer().then(z=>{N.enqueue(new Uint8Array(z)),N.close()})}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){const Z=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",C[Z]??"application/octet-stream")}clone(){let Z=new M(this.filePath);return Z.exists=this.exists,Z.status=this.status,Z.statusText=this.statusText,Z.headers=new Headers(this.headers),Z}async arrayBuffer(){return(await o.promises.readFile(this.filePath)).buffer}async blob(){const Z=await o.promises.readFile(this.filePath);return new Blob([Z],{type:this.headers.get("content-type")})}async text(){return await o.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}}function b(L,Z=null,V=null){let D;try{D=new URL(L)}catch{return!1}return!(Z&&!Z.includes(D.protocol)||V&&!V.includes(D.hostname))}async function F(L){var Z;if(p.env.useFS&&!b(L,["http:","https:","blob:"]))return new M(L);if(typeof process<"u"&&((Z=process==null?void 0:process.release)==null?void 0:Z.name)==="node"){const V=!!(wo!=null&&wo.TESTING_REMOTELY),D=p.env.version,N=new Headers;if(N.set("User-Agent",`transformers.js/${D}; is_ci/${V};`),b(L,["http:","https:"],["huggingface.co","hf.co"])){const me=(wo==null?void 0:wo.HF_TOKEN)??(wo==null?void 0:wo.HF_ACCESS_TOKEN);me&&N.set("Authorization",`Bearer ${me}`)}return fetch(L,{headers:N})}else return fetch(L)}const S={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 G(L,Z,V){if(!V)return null;const D=S[L]??`Error (${L}) occurred while trying to load file`;throw Error(`${D}: "${Z}".`)}class J{constructor(Z){this.path=Z}async match(Z){let V=l.join(this.path,Z),D=new M(V);if(D.exists)return D}async put(Z,V){const D=Buffer.from(await V.arrayBuffer());let N=l.join(this.path,Z);try{await o.promises.mkdir(l.dirname(N),{recursive:!0}),await o.promises.writeFile(N,D)}catch(z){console.warn("An error occurred while writing the file to cache:",z)}}}async function te(L,...Z){for(let V of Z)try{let D=await L.match(V);if(D)return D}catch{continue}}async function ne(L,Z,V=!0,D={}){if(!p.env.allowLocalModels){if(D.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(!p.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,_.dispatchCallback)(D.progress_callback,{status:"initiate",name:L,file:Z});let N;if(!N&&p.env.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{N=await caches.open("transformers-cache")}catch(Me){console.warn("An error occurred while opening the browser cache:",Me)}}if(!N&&p.env.useFSCache&&(N=new J(D.cache_dir??p.env.cacheDir)),!N&&p.env.useCustomCache){if(!p.env.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!p.env.customCache.match||!p.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");N=p.env.customCache}const z=D.revision??"main";let me=P(L,Z),he=P(p.env.localModelPath,me),ke=P(p.env.remoteHost,p.env.remotePathTemplate.replaceAll("{model}",L).replaceAll("{revision}",encodeURIComponent(z)),Z),$e=z==="main"?me:P(L,z,Z),Ae,Je=N instanceof J?$e:ke,Xe=!1,pt;N&&(pt=await te(N,he,Je));const xe=pt!==void 0;if(pt===void 0){if(p.env.allowLocalModels)if(b(me,["http:","https:"])){if(D.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${me}.`);if(!p.env.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${me}.`)}else try{pt=await F(he),Ae=he}catch(se){console.warn(`Unable to load from local path "${he}": "${se}"`)}if(pt===void 0||pt.status===404){if(D.local_files_only||!p.env.allowRemoteModels){if(V)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${he}".`);return null}if(pt=await F(ke),pt.status!==200)return G(pt.status,ke,V);Ae=Je}Xe=N&&typeof Response<"u"&&pt instanceof Response&&pt.status===200}(0,_.dispatchCallback)(D.progress_callback,{status:"download",name:L,file:Z});const H={status:"progress",name:L,file:Z};let pe;return D.progress_callback?xe&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent)?(pe=new Uint8Array(await pt.arrayBuffer()),(0,_.dispatchCallback)(D.progress_callback,{...H,progress:100,loaded:pe.length,total:pe.length})):pe=await A(pt,Me=>{(0,_.dispatchCallback)(D.progress_callback,{...H,...Me})}):pe=new Uint8Array(await pt.arrayBuffer()),Xe&&Ae&&await N.match(Ae)===void 0&&await N.put(Ae,new Response(pe,{headers:pt.headers})).catch(Me=>{console.warn(`Unable to add response to browser cache: ${Me}.`)}),(0,_.dispatchCallback)(D.progress_callback,{status:"done",name:L,file:Z}),pe}async function X(L,Z,V=!0,D={}){let N=await ne(L,Z,V,D);if(N===null)return{};let me=new TextDecoder("utf-8").decode(N);return JSON.parse(me)}async function A(L,Z){const V=L.headers.get("Content-Length");V===null&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let D=parseInt(V??"0"),N=new Uint8Array(D),z=0;const me=L.body.getReader();async function he(){const{done:ke,value:$e}=await me.read();if(ke)return;let Ae=z+$e.length;if(Ae>D){D=Ae;let Xe=new Uint8Array(D);Xe.set(N),N=Xe}N.set($e,z),z=Ae;const Je=z/D*100;return Z({progress:Je,loaded:z,total:D}),he()}return await he(),N}function P(...L){return L=L.map((Z,V)=>(V&&(Z=Z.replace(new RegExp("^/"),"")),V!==L.length-1&&(Z=Z.replace(new RegExp("/$"),"")),Z)),L.join("/")}},"./src/utils/image.js":(e,n,r)=>{r.r(n),r.d(n,{RawImage:()=>te});var o=r("./src/utils/hub.js"),l=r("./src/env.js"),p=r("./src/utils/tensor.js"),_=r("?2b25");const C=typeof self<"u",M=C&&self.constructor.name==="DedicatedWorkerGlobalScope";let b,F,S;if(C)b=(ne,X)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(ne,X)},S=self.createImageBitmap,F=self.ImageData;else if(_)S=async ne=>{const A=(await ne.metadata()).channels,{data:P,info:L}=await ne.rotate().raw().toBuffer({resolveWithObject:!0}),Z=new te(new Uint8ClampedArray(P),L.width,L.height,L.channels);return A!==void 0&&A!==L.channels&&Z.convert(A),Z};else throw new Error("Unable to load image processing library.");const G={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},J=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]);class te{constructor(X,A,P,L){this.data=X,this.width=A,this.height=P,this.channels=L}get size(){return[this.width,this.height]}static async read(X){if(X instanceof te)return X;if(typeof X=="string"||X instanceof URL)return await this.fromURL(X);throw new Error(`Unsupported input type: ${typeof X}`)}static fromCanvas(X){if(!C)throw new Error("fromCanvas() is only supported in browser environments.");const P=X.getContext("2d").getImageData(0,0,X.width,X.height).data;return new te(P,X.width,X.height,4)}static async fromURL(X){const A=await(0,o.getFile)(X);if(A.status!==200)throw new Error(`Unable to read image from "${X}" (${A.status} ${A.statusText})`);const P=await A.blob();return this.fromBlob(P)}static async fromBlob(X){if(C){const A=await S(X),P=b(A.width,A.height).getContext("2d");return P.drawImage(A,0,0),new this(P.getImageData(0,0,A.width,A.height).data,A.width,A.height,4)}else{const A=_(await X.arrayBuffer());return await S(A)}}static fromTensor(X,A="CHW"){if(X.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${X.dims.length} dimensions.`);if(A==="CHW")X=X.transpose(1,2,0);else if(A!=="HWC")throw new Error(`Unsupported channel format: ${A}`);if(!(X.data instanceof Uint8ClampedArray||X.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${X.type}`);switch(X.dims[2]){case 1:case 2:case 3:case 4:return new te(X.data,X.dims[1],X.dims[0],X.dims[2]);default:throw new Error(`Unsupported number of channels: ${X.dims[2]}`)}}grayscale(){if(this.channels===1)return this;const X=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let A=0,P=0;A=0?N=P:me=-P,L>=0?z=L:he=-L,D.drawImage(V,N,z,X,A,me,he,X,A),new te(D.getImageData(0,0,X,A).data,X,A,4).convert(Z)}else{let Z=this.toSharp();if(P>=0&&L>=0)Z=Z.extract({left:Math.floor(P),top:Math.floor(L),width:X,height:A});else if(P<=0&&L<=0){const V=Math.floor(-L),D=Math.floor(-P);Z=Z.extend({top:V,left:D,right:X-this.width-D,bottom:A-this.height-V})}else{let V=[0,0],D=0;L<0?(V[0]=Math.floor(-L),V[1]=A-this.height-V[0]):D=Math.floor(L);let N=[0,0],z=0;P<0?(N[0]=Math.floor(-P),N[1]=X-this.width-N[0]):z=Math.floor(P),Z=Z.extend({top:V[0],bottom:V[1],left:N[0],right:N[1]}).extract({left:z,top:D,width:X,height:A})}return await S(Z)}}async toBlob(X="image/png",A=1){if(!C)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:X,quality:A})}toTensor(X="CHW"){let A=new p.Tensor("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(X!=="HWC")if(X==="CHW")A=A.permute(2,0,1);else throw new Error(`Unsupported channel format: ${X}`);return A}toCanvas(){if(!C)throw new Error("toCanvas() is only supported in browser environments.");const X=this.clone().rgba(),A=b(X.width,X.height),P=new F(X.data,X.width,X.height);return A.getContext("2d").putImageData(P,0,0),A}_update(X,A,P,L=null){return this.data=X,this.width=A,this.height=P,L!==null&&(this.channels=L),this}clone(){return new te(this.data.slice(),this.width,this.height,this.channels)}convert(X){if(this.channels===X)return this;switch(X){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(X){if(C){if(M)throw new Error("Unable to save an image from a Web Worker.");const A=X.split(".").pop().toLowerCase(),P=J.get(A)??"image/png",L=await this.toBlob(P),Z=URL.createObjectURL(L),V=document.createElement("a");V.href=Z,V.download=X,V.click(),V.remove()}else{if(l.env.useFS)return await this.toSharp().toFile(X);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 _(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}}},"./src/utils/maths.js":(e,n,r)=>{r.r(n),r.d(n,{FFT:()=>ne,bankers_round:()=>P,cos_sim:()=>M,dot:()=>C,dynamic_time_warping:()=>L,interpolate_data:()=>o,log_softmax:()=>_,magnitude:()=>b,max:()=>S,medianFilter:()=>X,min:()=>F,permute_data:()=>l,round:()=>A,softmax:()=>p});function o(Z,[V,D,N],[z,me],he="bilinear",ke=!1){const $e=me/N,Ae=z/D,Je=new Z.constructor(z*me*V),Xe=D*N,pt=z*me;for(let xe=0;xe=0;--ke)z[ke]=$e,N[ke]=V[D[ke]],$e*=N[ke];const me=D.map((ke,$e)=>z[D.indexOf($e)]),he=new Z.constructor(Z.length);for(let ke=0;ke=0;--Ae)$e+=Je%V[Ae]*me[Ae],Je=Math.floor(Je/V[Ae]);he[$e]=Z[ke]}return[he,N]}function p(Z){const V=S(Z)[0],D=Z.map(me=>Math.exp(me-V)),N=D.reduce((me,he)=>me+he,0);return D.map(me=>me/N)}function _(Z){return p(Z).map(N=>Math.log(N))}function C(Z,V){let D=0;for(let N=0;NV+D*D,0))}function F(Z){if(Z.length===0)throw Error("Array must not be empty");let V=Z[0],D=0;for(let N=1;NV&&(V=Z[N],D=N);return[Number(V),D]}function G(Z){return Z>0&&(Z&Z-1)===0}class J{constructor(V){if(this.size=V|0,this.size<=1||!G(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=V<<1,this.table=new Float64Array(this.size*2);for(let N=0;NN;N<<=1)++D;this._width=D%2===0?D-1:D,this._bitrev=new Int32Array(1<>>z&3)<>>1);for(let z=0;z>>1]=V[z];return N}toComplexArray(V,D){const N=D||this.createComplexArray();for(let z=0;z>>1],N[z+1]=0;return N}transform(V,D){if(V===D)throw new Error("Input and output buffers must be different");this._transform4(V,D,1)}realTransform(V,D){if(V===D)throw new Error("Input and output buffers must be different");this._realTransform4(V,D,1)}inverseTransform(V,D){if(V===D)throw new Error("Input and output buffers must be different");this._transform4(V,D,-1);for(let N=0;N>=2;he>=2;he>>=2){ke=z/he<<1;const pt=ke>>>2;for($e=0;$e>>1,he>>>1)}else for($e=0,Ae=0;$e>>1,he>>>1,N)}const Xe=this.table;for(he>>=2;he>=2;he>>=2){ke=z/he<<1;const xe=ke>>>1,H=xe>>>1,pe=H>>>1;for($e=0;$e>>1;for(let xe=2;xe>1;++Je){const Xe=(Je+1-V)**2/2,pt=Math.sqrt($e**2+Ae**2)**Xe,xe=Xe*Math.atan2(Ae,$e),H=2*Je;me[H]=pt*Math.cos(xe),me[H+1]=pt*Math.sin(xe),he[H]=me[H],he[H+1]=-me[H+1]}this._slicedChirpBuffer=me.subarray(D,N),this._f=new J(z>>1),this._f.transform(this._chirpBuffer,he)}_transform(V,D,N){const z=this._buffer1,me=this._buffer2,he=this._outBuffer1,ke=this._outBuffer2,$e=this._chirpBuffer,Ae=this._slicedChirpBuffer,Je=this._a;if(N)for(let Xe=0;Xe>1,H=D[xe];z[Xe]=H*Ae[Xe],z[pt]=H*Ae[pt]}else for(let Xe=0;Xe=Z.length&&($e=2*(Z.length-1)-$e),N[he++]=Z[$e]}N.sort(),D[me]=N[z]}return D}function A(Z,V){const D=Math.pow(10,V);return Math.round(Z*D)/D}function P(Z){const V=Math.round(Z);return Math.abs(Z)%1===.5?V%2===0?V:V-1:V}function L(Z){const V=Z.length,D=Z[0].length,N=[V+1,D+1],z=Array.from({length:N[0]},()=>Array(N[1]).fill(1/0));z[0][0]=0;const me=Array.from({length:N[0]},()=>Array(N[1]).fill(-1));for(let Je=1;Je0||ke>0;)switch($e.push(he-1),Ae.push(ke-1),me[he][ke]){case 0:--he,--ke;break;case 1:--he;break;case 2:--ke;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${he}, ${ke}]. Please file a bug report.`)}return $e.reverse(),Ae.reverse(),[$e,Ae]}},"./src/utils/tensor.js":(e,n,r)=>{r.r(n),r.d(n,{Tensor:()=>C,cat:()=>Z,full:()=>he,full_like:()=>ke,interpolate:()=>F,interpolate_4d:()=>S,layer_norm:()=>X,matmul:()=>G,mean:()=>N,mean_pooling:()=>ne,ones:()=>$e,ones_like:()=>Ae,permute:()=>b,quantize_embeddings:()=>pt,rfft:()=>J,stack:()=>V,std_mean:()=>D,topk:()=>te,zeros:()=>Je,zeros_like:()=>Xe});var o=r("./src/utils/maths.js"),l=r("./src/backends/onnx.js"),p=r("./src/ops/registry.js");const _=Object.freeze({float32:Float32Array,float16:Uint16Array,float64:Float64Array,string:Array,int8:Int8Array,uint8:Uint8Array,int16:Int16Array,uint16:Uint16Array,int32:Int32Array,uint32:Uint32Array,int64:BigInt64Array,uint64:BigUint64Array,bool:Uint8Array});class C{constructor(...H){Ee(this,"ort_tensor");return(0,l.isONNXTensor)(H[0])?this.ort_tensor=H[0]:this.ort_tensor=new l.Tensor(H[0],H[1],H[2]),new Proxy(this,{get:(pe,Me)=>{if(typeof Me=="string"){let se=Number(Me);if(Number.isInteger(se))return pe._getitem(se)}return pe[Me]},set:(pe,Me,se)=>pe[Me]=se})}get dims(){return this.ort_tensor.dims}set dims(H){this.ort_tensor.dims=H}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[H,...pe]=this.dims;if(pe.length>0){const Me=pe.reduce((se,Fe)=>se*Fe);for(let se=0;se0){const se=Me.reduce((Fe,ut)=>Fe*ut);return this._subarray(H,se,Me)}else return new C(this.type,[this.data[H]],Me)}indexOf(H){const pe=this.data;for(let Me=0;MeBe)throw new Error(`Invalid slice: ${rt}`);const fe=[Math.max(Tt,0),Math.min(Be,this.dims[Oe])];Me.push(fe),pe.push(fe[1]-fe[0])}else throw new Error(`Invalid slice: ${rt}`)}const se=Me.map(([Oe,rt])=>rt-Oe),Fe=se.reduce((Oe,rt)=>Oe*rt),ut=this.data,Ye=new ut.constructor(Fe),st=this.stride();for(let Oe=0;Oe=0;--Tt){const fe=se[Tt];rt+=(Be%fe+Me[Tt][0])*st[Tt],Be=Math.floor(Be/fe)}Ye[Oe]=ut[rt]}return new C(this.type,Ye,pe)}permute(...H){return b(this,H)}transpose(...H){return this.permute(...H)}sum(H=null,pe=!1){return this.norm(1,H,pe)}norm(H="fro",pe=null,Me=!1){if(H==="fro")H=2;else if(typeof H=="string")throw Error(`Unsupported norm: ${H}`);const se=this.data;if(pe===null){let Ye=se.reduce((st,Oe)=>st+Oe**H,0)**(1/H);return new C(this.type,[Ye],[])}pe=L(pe,this.dims.length);const Fe=this.dims.slice();Fe[pe]=1;const ut=new se.constructor(se.length/this.dims[pe]);for(let Ye=0;Ye=0;--Oe){const Be=this.dims[Oe];if(Oe!==pe){const fe=rt%Be;st+=fe*Tt,Tt*=Fe[Oe]}rt=Math.floor(rt/Be)}ut[st]+=se[Ye]**H}if(H!==1)for(let Ye=0;Ye=0;--st){const Tt=this.dims[st];if(st!==pe){const Be=Oe%Tt;Ye+=Be*rt,rt*=this.dims[st]}Oe=Math.floor(Oe/Tt)}se[ut]/=Fe[Ye]}return this}normalize(H=2,pe=1){return this.clone().normalize_(H,pe)}stride(){return z(this.dims)}squeeze(H=null){return new C(this.type,this.data,A(this.dims,H))}squeeze_(H=null){return this.dims=A(this.dims,H),this}unsqueeze(H=null){return new C(this.type,this.data,P(this.dims,H))}unsqueeze_(H=null){return this.dims=P(this.dims,H),this}flatten_(H=0,pe=-1){pe=(pe+this.dims.length)%this.dims.length;let Me=this.dims.slice(0,H),se=this.dims.slice(H,pe+1),Fe=this.dims.slice(pe+1);return this.dims=[...Me,se.reduce((ut,Ye)=>ut*Ye,1),...Fe],this}flatten(H=0,pe=-1){return this.clone().flatten_(H,pe)}view(...H){let pe=-1;for(let se=0;seYe!==pe?Fe*ut:Fe,1);H[pe]=Me.length/se}return new C(this.type,Me,H)}neg_(){const H=this.data;for(let pe=0;peFe*ut);if(pe!==Me)throw Error(`cannot reshape array of size ${pe} into shape (${H})`);let se=xe;for(let Fe=H.length-1;Fe>=0;Fe--)se=se.reduce((ut,Ye)=>{let st=ut[ut.length-1];return st.lengthpe!==1):typeof H=="number"?xe[H]===1&&xe.splice(H,1):Array.isArray(H)&&(xe=xe.filter((pe,Me)=>pe!==1||!H.includes(Me))),xe}function P(xe,H){return H=L(H,xe.length+1),xe=xe.slice(),xe.splice(H,0,1),xe}function L(xe,H,pe=null,Me=!0){if(Me&&(xe<-H||xe>=H))throw new Error(`IndexError: index ${xe} is out of bounds for dimension${pe===null?"":" "+pe} with size ${H}`);return xe<0&&(xe=(xe%H+H)%H),xe}function Z(xe,H=0){H=L(H,xe[0].dims.length);const pe=xe[0].dims.slice();pe[H]=xe.reduce((ut,Ye)=>ut+Ye.dims[H],0);const Me=pe.reduce((ut,Ye)=>ut*Ye,1),se=new xe[0].data.constructor(Me),Fe=xe[0].type;if(H===0){let ut=0;for(const Ye of xe){const st=Ye.data;se.set(st,ut),ut+=st.length}}else{let ut=0;for(let Ye=0;Ye=0;--Be){const Ue=Oe[Be];let Ge=fe%Ue;Be===H&&(Ge+=ut),Tt+=Ge*Ce,Ce*=pe[Be],fe=Math.floor(fe/Ue)}se[Tt]=st[rt]}ut+=Oe[H]}}return new C(Fe,se,pe)}function V(xe,H=0){return Z(xe.map(pe=>pe.unsqueeze(H)),H)}function D(xe,H=null,pe=1,Me=!1){const se=xe.data,Fe=xe.dims;if(H===null){const Be=se.reduce((Ge,We)=>Ge+We,0)/se.length,fe=Math.sqrt(se.reduce((Ge,We)=>Ge+(We-Be)**2,0)/(se.length-pe)),Ce=new C(xe.type,[Be],[]);return[new C(xe.type,[fe],[]),Ce]}H=L(H,Fe.length);const ut=N(xe,H,Me),Ye=ut.data,st=Fe.slice();st[H]=1;const Oe=new se.constructor(se.length/Fe[H]);for(let Tt=0;Tt=0;--fe){const Ge=Fe[fe];if(fe!==H){const We=Ce%Ge;Be+=We*Ue,Ue*=st[fe]}Ce=Math.floor(Ce/Ge)}Oe[Be]+=(se[Tt]-Ye[Be])**2}for(let Tt=0;Ttst+Oe,0);return new C(xe.type,[Ye/Me.length],[])}const se=xe.dims;H=L(H,se.length);const Fe=se.slice();Fe[H]=1;const ut=new Me.constructor(Me.length/se[H]);for(let Ye=0;Ye=0;--Oe){const Be=se[Oe];if(Oe!==H){const fe=rt%Be;st+=fe*Tt,Tt*=Fe[Oe]}rt=Math.floor(rt/Be)}ut[st]+=Me[Ye]}if(se[H]!==1)for(let Ye=0;Ye=0;--pe)H[pe]=Me,Me*=xe[pe];return H}function me(xe,H,pe,Me){const se=xe.reduce((Fe,ut)=>Fe*ut,1);return new C(pe,new Me(se).fill(H),xe)}function he(xe,H){let pe,Me;if(typeof H=="number")pe="float32",Me=Float32Array;else if(typeof H=="bigint")pe="int64",Me=BigInt64Array;else throw new Error(`Unsupported data type: ${typeof H}`);return me(xe,H,pe,Me)}function ke(xe,H){return he(xe.dims,H)}function $e(xe){return me(xe,1n,"int64",BigInt64Array)}function Ae(xe){return $e(xe.dims)}function Je(xe){return me(xe,0n,"int64",BigInt64Array)}function Xe(xe){return Je(xe.dims)}function pt(xe,H){if(xe.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(xe.dims.at(-1)%8!==0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(H))throw new Error("The precision must be either 'binary' or 'ubinary'");const pe=H==="binary",Me=pe?"int8":"uint8",se=pe?Int8Array:Uint8Array,Fe=xe.data,ut=new se(Fe.length/8);for(let Ye=0;Ye0?1:0,Oe=Math.floor(Ye/8),rt=Ye%8;ut[Oe]|=st<<7-rt,pe&&rt===0&&(ut[Oe]-=128)}return new C(Me,ut,[xe.dims[0],xe.dims[1]/8])}}},Rv={};function Qn(e){var n=Rv[e];if(n!==void 0)return n.exports;var r=Rv[e]={exports:{}};return dS[e](r,r.exports,Qn),r.exports}(()=>{var e=Object.getPrototypeOf?r=>Object.getPrototypeOf(r):r=>r.__proto__,n;Qn.t=function(r,o){if(o&1&&(r=this(r)),o&8||typeof r=="object"&&r&&(o&4&&r.__esModule||o&16&&typeof r.then=="function"))return r;var l=Object.create(null);Qn.r(l);var p={};n=n||[null,e({}),e([]),e(e)];for(var _=o&2&&r;typeof _=="object"&&!~n.indexOf(_);_=e(_))Object.getOwnPropertyNames(_).forEach(C=>p[C]=()=>r[C]);return p.default=()=>r,Qn.d(l,p),l}})();Qn.d=(e,n)=>{for(var r in n)Qn.o(n,r)&&!Qn.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:n[r]})};Qn.o=(e,n)=>Object.prototype.hasOwnProperty.call(e,n);Qn.r=e=>{typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};(()=>{var e;if(typeof import.meta.url=="string"&&(e=import.meta.url),!e)throw new Error("Automatic publicPath is not supported in this browser");e=e.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),Qn.p=e})();Qn.b=void 0;var w={};(()=>{/*!*****************************!*\ + !*** ./src/transformers.js ***! + \*****************************/Qn.r(w),Qn.d(w,{ASTFeatureExtractor:()=>l.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:()=>o.AlbertTokenizer,AudioClassificationPipeline:()=>n.AudioClassificationPipeline,AutoConfig:()=>p.AutoConfig,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,AutoModelForObjectDetection:()=>r.AutoModelForObjectDetection,AutoModelForQuestionAnswering:()=>r.AutoModelForQuestionAnswering,AutoModelForSemanticSegmentation:()=>r.AutoModelForSemanticSegmentation,AutoModelForSeq2SeqLM:()=>r.AutoModelForSeq2SeqLM,AutoModelForSequenceClassification:()=>r.AutoModelForSequenceClassification,AutoModelForSpeechSeq2Seq:()=>r.AutoModelForSpeechSeq2Seq,AutoModelForTextToSpectrogram:()=>r.AutoModelForTextToSpectrogram,AutoModelForTextToWaveform:()=>r.AutoModelForTextToWaveform,AutoModelForTokenClassification:()=>r.AutoModelForTokenClassification,AutoModelForVision2Seq:()=>r.AutoModelForVision2Seq,AutoModelForXVector:()=>r.AutoModelForXVector,AutoModelForZeroShotObjectDetection:()=>r.AutoModelForZeroShotObjectDetection,AutoProcessor:()=>l.AutoProcessor,AutoTokenizer:()=>o.AutoTokenizer,AutomaticSpeechRecognitionPipeline:()=>n.AutomaticSpeechRecognitionPipeline,BartForConditionalGeneration:()=>r.BartForConditionalGeneration,BartForSequenceClassification:()=>r.BartForSequenceClassification,BartModel:()=>r.BartModel,BartPretrainedModel:()=>r.BartPretrainedModel,BartTokenizer:()=>o.BartTokenizer,BaseModelOutput:()=>r.BaseModelOutput,BaseStreamer:()=>F.BaseStreamer,BeitFeatureExtractor:()=>l.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:()=>o.BertTokenizer,BitImageProcessor:()=>l.BitImageProcessor,BlenderbotForConditionalGeneration:()=>r.BlenderbotForConditionalGeneration,BlenderbotModel:()=>r.BlenderbotModel,BlenderbotPreTrainedModel:()=>r.BlenderbotPreTrainedModel,BlenderbotSmallForConditionalGeneration:()=>r.BlenderbotSmallForConditionalGeneration,BlenderbotSmallModel:()=>r.BlenderbotSmallModel,BlenderbotSmallPreTrainedModel:()=>r.BlenderbotSmallPreTrainedModel,BlenderbotSmallTokenizer:()=>o.BlenderbotSmallTokenizer,BlenderbotTokenizer:()=>o.BlenderbotTokenizer,BloomForCausalLM:()=>r.BloomForCausalLM,BloomModel:()=>r.BloomModel,BloomPreTrainedModel:()=>r.BloomPreTrainedModel,BloomTokenizer:()=>o.BloomTokenizer,CLIPFeatureExtractor:()=>l.CLIPFeatureExtractor,CLIPImageProcessor:()=>l.CLIPImageProcessor,CLIPModel:()=>r.CLIPModel,CLIPPreTrainedModel:()=>r.CLIPPreTrainedModel,CLIPSegForImageSegmentation:()=>r.CLIPSegForImageSegmentation,CLIPSegModel:()=>r.CLIPSegModel,CLIPSegPreTrainedModel:()=>r.CLIPSegPreTrainedModel,CLIPTextModelWithProjection:()=>r.CLIPTextModelWithProjection,CLIPTokenizer:()=>o.CLIPTokenizer,CLIPVisionModelWithProjection:()=>r.CLIPVisionModelWithProjection,CamembertForMaskedLM:()=>r.CamembertForMaskedLM,CamembertForQuestionAnswering:()=>r.CamembertForQuestionAnswering,CamembertForSequenceClassification:()=>r.CamembertForSequenceClassification,CamembertForTokenClassification:()=>r.CamembertForTokenClassification,CamembertModel:()=>r.CamembertModel,CamembertPreTrainedModel:()=>r.CamembertPreTrainedModel,CamembertTokenizer:()=>o.CamembertTokenizer,CausalLMOutput:()=>r.CausalLMOutput,CausalLMOutputWithPast:()=>r.CausalLMOutputWithPast,ChineseCLIPFeatureExtractor:()=>l.ChineseCLIPFeatureExtractor,ChineseCLIPModel:()=>r.ChineseCLIPModel,ChineseCLIPPreTrainedModel:()=>r.ChineseCLIPPreTrainedModel,ClapAudioModelWithProjection:()=>r.ClapAudioModelWithProjection,ClapFeatureExtractor:()=>l.ClapFeatureExtractor,ClapModel:()=>r.ClapModel,ClapPreTrainedModel:()=>r.ClapPreTrainedModel,ClapTextModelWithProjection:()=>r.ClapTextModelWithProjection,CodeGenForCausalLM:()=>r.CodeGenForCausalLM,CodeGenModel:()=>r.CodeGenModel,CodeGenPreTrainedModel:()=>r.CodeGenPreTrainedModel,CodeGenTokenizer:()=>o.CodeGenTokenizer,CodeLlamaTokenizer:()=>o.CodeLlamaTokenizer,CohereForCausalLM:()=>r.CohereForCausalLM,CohereModel:()=>r.CohereModel,CoherePreTrainedModel:()=>r.CoherePreTrainedModel,CohereTokenizer:()=>o.CohereTokenizer,ConvBertForMaskedLM:()=>r.ConvBertForMaskedLM,ConvBertForQuestionAnswering:()=>r.ConvBertForQuestionAnswering,ConvBertForSequenceClassification:()=>r.ConvBertForSequenceClassification,ConvBertForTokenClassification:()=>r.ConvBertForTokenClassification,ConvBertModel:()=>r.ConvBertModel,ConvBertPreTrainedModel:()=>r.ConvBertPreTrainedModel,ConvBertTokenizer:()=>o.ConvBertTokenizer,ConvNextFeatureExtractor:()=>l.ConvNextFeatureExtractor,ConvNextForImageClassification:()=>r.ConvNextForImageClassification,ConvNextImageProcessor:()=>l.ConvNextImageProcessor,ConvNextModel:()=>r.ConvNextModel,ConvNextPreTrainedModel:()=>r.ConvNextPreTrainedModel,ConvNextV2ForImageClassification:()=>r.ConvNextV2ForImageClassification,ConvNextV2Model:()=>r.ConvNextV2Model,ConvNextV2PreTrainedModel:()=>r.ConvNextV2PreTrainedModel,DPTFeatureExtractor:()=>l.DPTFeatureExtractor,DPTForDepthEstimation:()=>r.DPTForDepthEstimation,DPTImageProcessor:()=>l.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:()=>o.DebertaTokenizer,DebertaV2ForMaskedLM:()=>r.DebertaV2ForMaskedLM,DebertaV2ForQuestionAnswering:()=>r.DebertaV2ForQuestionAnswering,DebertaV2ForSequenceClassification:()=>r.DebertaV2ForSequenceClassification,DebertaV2ForTokenClassification:()=>r.DebertaV2ForTokenClassification,DebertaV2Model:()=>r.DebertaV2Model,DebertaV2PreTrainedModel:()=>r.DebertaV2PreTrainedModel,DebertaV2Tokenizer:()=>o.DebertaV2Tokenizer,DeiTFeatureExtractor:()=>l.DeiTFeatureExtractor,DeiTForImageClassification:()=>r.DeiTForImageClassification,DeiTModel:()=>r.DeiTModel,DeiTPreTrainedModel:()=>r.DeiTPreTrainedModel,DepthAnythingForDepthEstimation:()=>r.DepthAnythingForDepthEstimation,DepthAnythingPreTrainedModel:()=>r.DepthAnythingPreTrainedModel,DepthEstimationPipeline:()=>n.DepthEstimationPipeline,DetrFeatureExtractor:()=>l.DetrFeatureExtractor,DetrForObjectDetection:()=>r.DetrForObjectDetection,DetrForSegmentation:()=>r.DetrForSegmentation,DetrModel:()=>r.DetrModel,DetrObjectDetectionOutput:()=>r.DetrObjectDetectionOutput,DetrPreTrainedModel:()=>r.DetrPreTrainedModel,DetrSegmentationOutput:()=>r.DetrSegmentationOutput,Dinov2ForImageClassification:()=>r.Dinov2ForImageClassification,Dinov2Model:()=>r.Dinov2Model,Dinov2PreTrainedModel:()=>r.Dinov2PreTrainedModel,DistilBertForMaskedLM:()=>r.DistilBertForMaskedLM,DistilBertForQuestionAnswering:()=>r.DistilBertForQuestionAnswering,DistilBertForSequenceClassification:()=>r.DistilBertForSequenceClassification,DistilBertForTokenClassification:()=>r.DistilBertForTokenClassification,DistilBertModel:()=>r.DistilBertModel,DistilBertPreTrainedModel:()=>r.DistilBertPreTrainedModel,DistilBertTokenizer:()=>o.DistilBertTokenizer,DocumentQuestionAnsweringPipeline:()=>n.DocumentQuestionAnsweringPipeline,DonutFeatureExtractor:()=>l.DonutFeatureExtractor,DonutSwinModel:()=>r.DonutSwinModel,DonutSwinPreTrainedModel:()=>r.DonutSwinPreTrainedModel,EfficientNetForImageClassification:()=>r.EfficientNetForImageClassification,EfficientNetImageProcessor:()=>l.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:()=>o.ElectraTokenizer,EosTokenCriteria:()=>S.EosTokenCriteria,EsmForMaskedLM:()=>r.EsmForMaskedLM,EsmForSequenceClassification:()=>r.EsmForSequenceClassification,EsmForTokenClassification:()=>r.EsmForTokenClassification,EsmModel:()=>r.EsmModel,EsmPreTrainedModel:()=>r.EsmPreTrainedModel,EsmTokenizer:()=>o.EsmTokenizer,FFT:()=>b.FFT,FalconForCausalLM:()=>r.FalconForCausalLM,FalconModel:()=>r.FalconModel,FalconPreTrainedModel:()=>r.FalconPreTrainedModel,FalconTokenizer:()=>o.FalconTokenizer,FastViTForImageClassification:()=>r.FastViTForImageClassification,FastViTModel:()=>r.FastViTModel,FastViTPreTrainedModel:()=>r.FastViTPreTrainedModel,FeatureExtractionPipeline:()=>n.FeatureExtractionPipeline,FeatureExtractor:()=>l.FeatureExtractor,FillMaskPipeline:()=>n.FillMaskPipeline,Florence2ForConditionalGeneration:()=>r.Florence2ForConditionalGeneration,Florence2PreTrainedModel:()=>r.Florence2PreTrainedModel,Florence2Processor:()=>l.Florence2Processor,GLPNFeatureExtractor:()=>l.GLPNFeatureExtractor,GLPNForDepthEstimation:()=>r.GLPNForDepthEstimation,GLPNModel:()=>r.GLPNModel,GLPNPreTrainedModel:()=>r.GLPNPreTrainedModel,GPT2LMHeadModel:()=>r.GPT2LMHeadModel,GPT2Model:()=>r.GPT2Model,GPT2PreTrainedModel:()=>r.GPT2PreTrainedModel,GPT2Tokenizer:()=>o.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:()=>o.GPTNeoXTokenizer,Gemma2ForCausalLM:()=>r.Gemma2ForCausalLM,Gemma2Model:()=>r.Gemma2Model,Gemma2PreTrainedModel:()=>r.Gemma2PreTrainedModel,GemmaForCausalLM:()=>r.GemmaForCausalLM,GemmaModel:()=>r.GemmaModel,GemmaPreTrainedModel:()=>r.GemmaPreTrainedModel,GemmaTokenizer:()=>o.GemmaTokenizer,Grok1Tokenizer:()=>o.Grok1Tokenizer,HerbertTokenizer:()=>o.HerbertTokenizer,HubertForCTC:()=>r.HubertForCTC,HubertForSequenceClassification:()=>r.HubertForSequenceClassification,HubertModel:()=>r.HubertModel,HubertPreTrainedModel:()=>r.HubertPreTrainedModel,ImageClassificationPipeline:()=>n.ImageClassificationPipeline,ImageFeatureExtractionPipeline:()=>n.ImageFeatureExtractionPipeline,ImageFeatureExtractor:()=>l.ImageFeatureExtractor,ImageMattingOutput:()=>r.ImageMattingOutput,ImageSegmentationPipeline:()=>n.ImageSegmentationPipeline,ImageToImagePipeline:()=>n.ImageToImagePipeline,ImageToTextPipeline:()=>n.ImageToTextPipeline,InterruptableStoppingCriteria:()=>S.InterruptableStoppingCriteria,LlamaForCausalLM:()=>r.LlamaForCausalLM,LlamaModel:()=>r.LlamaModel,LlamaPreTrainedModel:()=>r.LlamaPreTrainedModel,LlamaTokenizer:()=>o.LlamaTokenizer,LlavaForConditionalGeneration:()=>r.LlavaForConditionalGeneration,LlavaPreTrainedModel:()=>r.LlavaPreTrainedModel,LongT5ForConditionalGeneration:()=>r.LongT5ForConditionalGeneration,LongT5Model:()=>r.LongT5Model,LongT5PreTrainedModel:()=>r.LongT5PreTrainedModel,M2M100ForConditionalGeneration:()=>r.M2M100ForConditionalGeneration,M2M100Model:()=>r.M2M100Model,M2M100PreTrainedModel:()=>r.M2M100PreTrainedModel,M2M100Tokenizer:()=>o.M2M100Tokenizer,MBart50Tokenizer:()=>o.MBart50Tokenizer,MBartForCausalLM:()=>r.MBartForCausalLM,MBartForConditionalGeneration:()=>r.MBartForConditionalGeneration,MBartForSequenceClassification:()=>r.MBartForSequenceClassification,MBartModel:()=>r.MBartModel,MBartPreTrainedModel:()=>r.MBartPreTrainedModel,MBartTokenizer:()=>o.MBartTokenizer,MPNetForMaskedLM:()=>r.MPNetForMaskedLM,MPNetForQuestionAnswering:()=>r.MPNetForQuestionAnswering,MPNetForSequenceClassification:()=>r.MPNetForSequenceClassification,MPNetForTokenClassification:()=>r.MPNetForTokenClassification,MPNetModel:()=>r.MPNetModel,MPNetPreTrainedModel:()=>r.MPNetPreTrainedModel,MPNetTokenizer:()=>o.MPNetTokenizer,MT5ForConditionalGeneration:()=>r.MT5ForConditionalGeneration,MT5Model:()=>r.MT5Model,MT5PreTrainedModel:()=>r.MT5PreTrainedModel,MarianMTModel:()=>r.MarianMTModel,MarianModel:()=>r.MarianModel,MarianPreTrainedModel:()=>r.MarianPreTrainedModel,MarianTokenizer:()=>o.MarianTokenizer,MaskedLMOutput:()=>r.MaskedLMOutput,MaxLengthCriteria:()=>S.MaxLengthCriteria,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:()=>o.MobileBertTokenizer,MobileNetV1FeatureExtractor:()=>l.MobileNetV1FeatureExtractor,MobileNetV1ForImageClassification:()=>r.MobileNetV1ForImageClassification,MobileNetV1Model:()=>r.MobileNetV1Model,MobileNetV1PreTrainedModel:()=>r.MobileNetV1PreTrainedModel,MobileNetV2FeatureExtractor:()=>l.MobileNetV2FeatureExtractor,MobileNetV2ForImageClassification:()=>r.MobileNetV2ForImageClassification,MobileNetV2Model:()=>r.MobileNetV2Model,MobileNetV2PreTrainedModel:()=>r.MobileNetV2PreTrainedModel,MobileNetV3FeatureExtractor:()=>l.MobileNetV3FeatureExtractor,MobileNetV3ForImageClassification:()=>r.MobileNetV3ForImageClassification,MobileNetV3Model:()=>r.MobileNetV3Model,MobileNetV3PreTrainedModel:()=>r.MobileNetV3PreTrainedModel,MobileNetV4FeatureExtractor:()=>l.MobileNetV4FeatureExtractor,MobileNetV4ForImageClassification:()=>r.MobileNetV4ForImageClassification,MobileNetV4Model:()=>r.MobileNetV4Model,MobileNetV4PreTrainedModel:()=>r.MobileNetV4PreTrainedModel,MobileViTFeatureExtractor:()=>l.MobileViTFeatureExtractor,MobileViTForImageClassification:()=>r.MobileViTForImageClassification,MobileViTImageProcessor:()=>l.MobileViTImageProcessor,MobileViTModel:()=>r.MobileViTModel,MobileViTPreTrainedModel:()=>r.MobileViTPreTrainedModel,MobileViTV2ForImageClassification:()=>r.MobileViTV2ForImageClassification,MobileViTV2Model:()=>r.MobileViTV2Model,MobileViTV2PreTrainedModel:()=>r.MobileViTV2PreTrainedModel,ModelOutput:()=>r.ModelOutput,Moondream1ForConditionalGeneration:()=>r.Moondream1ForConditionalGeneration,MptForCausalLM:()=>r.MptForCausalLM,MptModel:()=>r.MptModel,MptPreTrainedModel:()=>r.MptPreTrainedModel,MusicgenForCausalLM:()=>r.MusicgenForCausalLM,MusicgenForConditionalGeneration:()=>r.MusicgenForConditionalGeneration,MusicgenModel:()=>r.MusicgenModel,MusicgenPreTrainedModel:()=>r.MusicgenPreTrainedModel,NllbTokenizer:()=>o.NllbTokenizer,NomicBertModel:()=>r.NomicBertModel,NomicBertPreTrainedModel:()=>r.NomicBertPreTrainedModel,NougatImageProcessor:()=>l.NougatImageProcessor,NougatTokenizer:()=>o.NougatTokenizer,OPTForCausalLM:()=>r.OPTForCausalLM,OPTModel:()=>r.OPTModel,OPTPreTrainedModel:()=>r.OPTPreTrainedModel,ObjectDetectionPipeline:()=>n.ObjectDetectionPipeline,OpenELMForCausalLM:()=>r.OpenELMForCausalLM,OpenELMModel:()=>r.OpenELMModel,OpenELMPreTrainedModel:()=>r.OpenELMPreTrainedModel,OwlViTFeatureExtractor:()=>l.OwlViTFeatureExtractor,OwlViTForObjectDetection:()=>r.OwlViTForObjectDetection,OwlViTModel:()=>r.OwlViTModel,OwlViTPreTrainedModel:()=>r.OwlViTPreTrainedModel,OwlViTProcessor:()=>l.OwlViTProcessor,Owlv2ForObjectDetection:()=>r.Owlv2ForObjectDetection,Owlv2ImageProcessor:()=>l.Owlv2ImageProcessor,Owlv2Model:()=>r.Owlv2Model,Owlv2PreTrainedModel:()=>r.Owlv2PreTrainedModel,Phi3ForCausalLM:()=>r.Phi3ForCausalLM,Phi3Model:()=>r.Phi3Model,Phi3PreTrainedModel:()=>r.Phi3PreTrainedModel,PhiForCausalLM:()=>r.PhiForCausalLM,PhiModel:()=>r.PhiModel,PhiPreTrainedModel:()=>r.PhiPreTrainedModel,Pipeline:()=>n.Pipeline,PreTrainedModel:()=>r.PreTrainedModel,PreTrainedTokenizer:()=>o.PreTrainedTokenizer,PretrainedConfig:()=>p.PretrainedConfig,PretrainedMixin:()=>r.PretrainedMixin,Processor:()=>l.Processor,PyAnnoteFeatureExtractor:()=>l.PyAnnoteFeatureExtractor,PyAnnoteForAudioFrameClassification:()=>r.PyAnnoteForAudioFrameClassification,PyAnnoteModel:()=>r.PyAnnoteModel,PyAnnotePreTrainedModel:()=>r.PyAnnotePreTrainedModel,PyAnnoteProcessor:()=>l.PyAnnoteProcessor,QuestionAnsweringModelOutput:()=>r.QuestionAnsweringModelOutput,QuestionAnsweringPipeline:()=>n.QuestionAnsweringPipeline,Qwen2ForCausalLM:()=>r.Qwen2ForCausalLM,Qwen2Model:()=>r.Qwen2Model,Qwen2PreTrainedModel:()=>r.Qwen2PreTrainedModel,Qwen2Tokenizer:()=>o.Qwen2Tokenizer,RTDetrForObjectDetection:()=>r.RTDetrForObjectDetection,RTDetrImageProcessor:()=>l.RTDetrImageProcessor,RTDetrModel:()=>r.RTDetrModel,RTDetrObjectDetectionOutput:()=>r.RTDetrObjectDetectionOutput,RTDetrPreTrainedModel:()=>r.RTDetrPreTrainedModel,RawImage:()=>C.RawImage,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:()=>o.RoFormerTokenizer,RobertaForMaskedLM:()=>r.RobertaForMaskedLM,RobertaForQuestionAnswering:()=>r.RobertaForQuestionAnswering,RobertaForSequenceClassification:()=>r.RobertaForSequenceClassification,RobertaForTokenClassification:()=>r.RobertaForTokenClassification,RobertaModel:()=>r.RobertaModel,RobertaPreTrainedModel:()=>r.RobertaPreTrainedModel,RobertaTokenizer:()=>o.RobertaTokenizer,SamImageProcessor:()=>l.SamImageProcessor,SamImageSegmentationOutput:()=>r.SamImageSegmentationOutput,SamModel:()=>r.SamModel,SamPreTrainedModel:()=>r.SamPreTrainedModel,SamProcessor:()=>l.SamProcessor,SeamlessM4TFeatureExtractor:()=>l.SeamlessM4TFeatureExtractor,SegformerFeatureExtractor:()=>l.SegformerFeatureExtractor,SegformerForImageClassification:()=>r.SegformerForImageClassification,SegformerForSemanticSegmentation:()=>r.SegformerForSemanticSegmentation,SegformerModel:()=>r.SegformerModel,SegformerPreTrainedModel:()=>r.SegformerPreTrainedModel,Seq2SeqLMOutput:()=>r.Seq2SeqLMOutput,SequenceClassifierOutput:()=>r.SequenceClassifierOutput,SiglipImageProcessor:()=>l.SiglipImageProcessor,SiglipModel:()=>r.SiglipModel,SiglipPreTrainedModel:()=>r.SiglipPreTrainedModel,SiglipTextModel:()=>r.SiglipTextModel,SiglipTokenizer:()=>o.SiglipTokenizer,SiglipVisionModel:()=>r.SiglipVisionModel,SpeechT5FeatureExtractor:()=>l.SpeechT5FeatureExtractor,SpeechT5ForSpeechToText:()=>r.SpeechT5ForSpeechToText,SpeechT5ForTextToSpeech:()=>r.SpeechT5ForTextToSpeech,SpeechT5HifiGan:()=>r.SpeechT5HifiGan,SpeechT5Model:()=>r.SpeechT5Model,SpeechT5PreTrainedModel:()=>r.SpeechT5PreTrainedModel,SpeechT5Processor:()=>l.SpeechT5Processor,SpeechT5Tokenizer:()=>o.SpeechT5Tokenizer,SqueezeBertForMaskedLM:()=>r.SqueezeBertForMaskedLM,SqueezeBertForQuestionAnswering:()=>r.SqueezeBertForQuestionAnswering,SqueezeBertForSequenceClassification:()=>r.SqueezeBertForSequenceClassification,SqueezeBertModel:()=>r.SqueezeBertModel,SqueezeBertPreTrainedModel:()=>r.SqueezeBertPreTrainedModel,SqueezeBertTokenizer:()=>o.SqueezeBertTokenizer,StableLmForCausalLM:()=>r.StableLmForCausalLM,StableLmModel:()=>r.StableLmModel,StableLmPreTrainedModel:()=>r.StableLmPreTrainedModel,Starcoder2ForCausalLM:()=>r.Starcoder2ForCausalLM,Starcoder2Model:()=>r.Starcoder2Model,Starcoder2PreTrainedModel:()=>r.Starcoder2PreTrainedModel,StoppingCriteria:()=>S.StoppingCriteria,StoppingCriteriaList:()=>S.StoppingCriteriaList,SummarizationPipeline:()=>n.SummarizationPipeline,Swin2SRForImageSuperResolution:()=>r.Swin2SRForImageSuperResolution,Swin2SRImageProcessor:()=>l.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:()=>o.T5Tokenizer,TableTransformerForObjectDetection:()=>r.TableTransformerForObjectDetection,TableTransformerModel:()=>r.TableTransformerModel,TableTransformerObjectDetectionOutput:()=>r.TableTransformerObjectDetectionOutput,TableTransformerPreTrainedModel:()=>r.TableTransformerPreTrainedModel,Tensor:()=>M.Tensor,Text2TextGenerationPipeline:()=>n.Text2TextGenerationPipeline,TextClassificationPipeline:()=>n.TextClassificationPipeline,TextGenerationPipeline:()=>n.TextGenerationPipeline,TextStreamer:()=>F.TextStreamer,TextToAudioPipeline:()=>n.TextToAudioPipeline,TokenClassificationPipeline:()=>n.TokenClassificationPipeline,TokenClassifierOutput:()=>r.TokenClassifierOutput,TokenizerModel:()=>o.TokenizerModel,TrOCRForCausalLM:()=>r.TrOCRForCausalLM,TrOCRPreTrainedModel:()=>r.TrOCRPreTrainedModel,TranslationPipeline:()=>n.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,ViTFeatureExtractor:()=>l.ViTFeatureExtractor,ViTForImageClassification:()=>r.ViTForImageClassification,ViTImageProcessor:()=>l.ViTImageProcessor,ViTModel:()=>r.ViTModel,ViTPreTrainedModel:()=>r.ViTPreTrainedModel,VisionEncoderDecoderModel:()=>r.VisionEncoderDecoderModel,VitMatteForImageMatting:()=>r.VitMatteForImageMatting,VitMatteImageProcessor:()=>l.VitMatteImageProcessor,VitMattePreTrainedModel:()=>r.VitMattePreTrainedModel,VitsModel:()=>r.VitsModel,VitsModelOutput:()=>r.VitsModelOutput,VitsPreTrainedModel:()=>r.VitsPreTrainedModel,VitsTokenizer:()=>o.VitsTokenizer,Wav2Vec2BertForCTC:()=>r.Wav2Vec2BertForCTC,Wav2Vec2BertForSequenceClassification:()=>r.Wav2Vec2BertForSequenceClassification,Wav2Vec2BertModel:()=>r.Wav2Vec2BertModel,Wav2Vec2BertPreTrainedModel:()=>r.Wav2Vec2BertPreTrainedModel,Wav2Vec2CTCTokenizer:()=>o.Wav2Vec2CTCTokenizer,Wav2Vec2FeatureExtractor:()=>l.Wav2Vec2FeatureExtractor,Wav2Vec2ForAudioFrameClassification:()=>r.Wav2Vec2ForAudioFrameClassification,Wav2Vec2ForCTC:()=>r.Wav2Vec2ForCTC,Wav2Vec2ForSequenceClassification:()=>r.Wav2Vec2ForSequenceClassification,Wav2Vec2Model:()=>r.Wav2Vec2Model,Wav2Vec2PreTrainedModel:()=>r.Wav2Vec2PreTrainedModel,Wav2Vec2ProcessorWithLM:()=>l.Wav2Vec2ProcessorWithLM,WavLMForAudioFrameClassification:()=>r.WavLMForAudioFrameClassification,WavLMForCTC:()=>r.WavLMForCTC,WavLMForSequenceClassification:()=>r.WavLMForSequenceClassification,WavLMForXVector:()=>r.WavLMForXVector,WavLMModel:()=>r.WavLMModel,WavLMPreTrainedModel:()=>r.WavLMPreTrainedModel,WeSpeakerFeatureExtractor:()=>l.WeSpeakerFeatureExtractor,WeSpeakerResNetModel:()=>r.WeSpeakerResNetModel,WeSpeakerResNetPreTrainedModel:()=>r.WeSpeakerResNetPreTrainedModel,WhisperFeatureExtractor:()=>l.WhisperFeatureExtractor,WhisperForConditionalGeneration:()=>r.WhisperForConditionalGeneration,WhisperModel:()=>r.WhisperModel,WhisperPreTrainedModel:()=>r.WhisperPreTrainedModel,WhisperProcessor:()=>l.WhisperProcessor,WhisperTextStreamer:()=>F.WhisperTextStreamer,WhisperTokenizer:()=>o.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:()=>o.XLMRobertaTokenizer,XLMTokenizer:()=>o.XLMTokenizer,XLMWithLMHeadModel:()=>r.XLMWithLMHeadModel,XVectorOutput:()=>r.XVectorOutput,YolosFeatureExtractor:()=>l.YolosFeatureExtractor,YolosForObjectDetection:()=>r.YolosForObjectDetection,YolosModel:()=>r.YolosModel,YolosObjectDetectionOutput:()=>r.YolosObjectDetectionOutput,YolosPreTrainedModel:()=>r.YolosPreTrainedModel,ZeroShotAudioClassificationPipeline:()=>n.ZeroShotAudioClassificationPipeline,ZeroShotClassificationPipeline:()=>n.ZeroShotClassificationPipeline,ZeroShotImageClassificationPipeline:()=>n.ZeroShotImageClassificationPipeline,ZeroShotObjectDetectionPipeline:()=>n.ZeroShotObjectDetectionPipeline,bankers_round:()=>b.bankers_round,cat:()=>M.cat,cos_sim:()=>b.cos_sim,dot:()=>b.dot,dynamic_time_warping:()=>b.dynamic_time_warping,env:()=>e.env,full:()=>M.full,full_like:()=>M.full_like,getKeyValueShapes:()=>p.getKeyValueShapes,hamming:()=>_.hamming,hanning:()=>_.hanning,interpolate:()=>M.interpolate,interpolate_4d:()=>M.interpolate_4d,interpolate_data:()=>b.interpolate_data,is_chinese_char:()=>o.is_chinese_char,layer_norm:()=>M.layer_norm,log_softmax:()=>b.log_softmax,magnitude:()=>b.magnitude,matmul:()=>M.matmul,max:()=>b.max,mean:()=>M.mean,mean_pooling:()=>M.mean_pooling,medianFilter:()=>b.medianFilter,mel_filter_bank:()=>_.mel_filter_bank,min:()=>b.min,ones:()=>M.ones,ones_like:()=>M.ones_like,permute:()=>M.permute,permute_data:()=>b.permute_data,pipeline:()=>n.pipeline,quantize_embeddings:()=>M.quantize_embeddings,read_audio:()=>_.read_audio,rfft:()=>M.rfft,round:()=>b.round,softmax:()=>b.softmax,spectrogram:()=>_.spectrogram,stack:()=>M.stack,std_mean:()=>M.std_mean,topk:()=>M.topk,window_function:()=>_.window_function,zeros:()=>M.zeros,zeros_like:()=>M.zeros_like});var e=Qn("./src/env.js"),n=Qn("./src/pipelines.js"),r=Qn("./src/models.js"),o=Qn("./src/tokenizers.js"),l=Qn("./src/processors.js"),p=Qn("./src/configs.js"),_=Qn("./src/utils/audio.js"),C=Qn("./src/utils/image.js"),M=Qn("./src/utils/tensor.js"),b=Qn("./src/utils/maths.js"),F=Qn("./src/generation/streamers.js"),S=Qn("./src/generation/stopping_criteria.js")})();w.ASTFeatureExtractor;w.ASTForAudioClassification;w.ASTModel;w.ASTPreTrainedModel;w.AlbertForMaskedLM;w.AlbertForQuestionAnswering;w.AlbertForSequenceClassification;w.AlbertModel;w.AlbertPreTrainedModel;w.AlbertTokenizer;w.AudioClassificationPipeline;w.AutoConfig;var cS=w.AutoModel;w.AutoModelForAudioClassification;w.AutoModelForAudioFrameClassification;w.AutoModelForCTC;w.AutoModelForCausalLM;w.AutoModelForDepthEstimation;w.AutoModelForDocumentQuestionAnswering;w.AutoModelForImageClassification;w.AutoModelForImageFeatureExtraction;w.AutoModelForImageMatting;w.AutoModelForImageSegmentation;w.AutoModelForImageToImage;w.AutoModelForMaskGeneration;w.AutoModelForMaskedLM;w.AutoModelForObjectDetection;w.AutoModelForQuestionAnswering;w.AutoModelForSemanticSegmentation;w.AutoModelForSeq2SeqLM;w.AutoModelForSequenceClassification;w.AutoModelForSpeechSeq2Seq;w.AutoModelForTextToSpectrogram;w.AutoModelForTextToWaveform;w.AutoModelForTokenClassification;w.AutoModelForVision2Seq;w.AutoModelForXVector;w.AutoModelForZeroShotObjectDetection;var pS=w.AutoProcessor;w.AutoTokenizer;w.AutomaticSpeechRecognitionPipeline;w.BartForConditionalGeneration;w.BartForSequenceClassification;w.BartModel;w.BartPretrainedModel;w.BartTokenizer;w.BaseModelOutput;w.BaseStreamer;w.BeitFeatureExtractor;w.BeitForImageClassification;w.BeitModel;w.BeitPreTrainedModel;w.BertForMaskedLM;w.BertForQuestionAnswering;w.BertForSequenceClassification;w.BertForTokenClassification;w.BertModel;w.BertPreTrainedModel;w.BertTokenizer;w.BitImageProcessor;w.BlenderbotForConditionalGeneration;w.BlenderbotModel;w.BlenderbotPreTrainedModel;w.BlenderbotSmallForConditionalGeneration;w.BlenderbotSmallModel;w.BlenderbotSmallPreTrainedModel;w.BlenderbotSmallTokenizer;w.BlenderbotTokenizer;w.BloomForCausalLM;w.BloomModel;w.BloomPreTrainedModel;w.BloomTokenizer;w.CLIPFeatureExtractor;w.CLIPImageProcessor;w.CLIPModel;w.CLIPPreTrainedModel;w.CLIPSegForImageSegmentation;w.CLIPSegModel;w.CLIPSegPreTrainedModel;w.CLIPTextModelWithProjection;w.CLIPTokenizer;w.CLIPVisionModelWithProjection;w.CamembertForMaskedLM;w.CamembertForQuestionAnswering;w.CamembertForSequenceClassification;w.CamembertForTokenClassification;w.CamembertModel;w.CamembertPreTrainedModel;w.CamembertTokenizer;w.CausalLMOutput;w.CausalLMOutputWithPast;w.ChineseCLIPFeatureExtractor;w.ChineseCLIPModel;w.ChineseCLIPPreTrainedModel;w.ClapAudioModelWithProjection;w.ClapFeatureExtractor;w.ClapModel;w.ClapPreTrainedModel;w.ClapTextModelWithProjection;w.CodeGenForCausalLM;w.CodeGenModel;w.CodeGenPreTrainedModel;w.CodeGenTokenizer;w.CodeLlamaTokenizer;w.CohereForCausalLM;w.CohereModel;w.CoherePreTrainedModel;w.CohereTokenizer;w.ConvBertForMaskedLM;w.ConvBertForQuestionAnswering;w.ConvBertForSequenceClassification;w.ConvBertForTokenClassification;w.ConvBertModel;w.ConvBertPreTrainedModel;w.ConvBertTokenizer;w.ConvNextFeatureExtractor;w.ConvNextForImageClassification;w.ConvNextImageProcessor;w.ConvNextModel;w.ConvNextPreTrainedModel;w.ConvNextV2ForImageClassification;w.ConvNextV2Model;w.ConvNextV2PreTrainedModel;w.DPTFeatureExtractor;w.DPTForDepthEstimation;w.DPTImageProcessor;w.DPTModel;w.DPTPreTrainedModel;w.DebertaForMaskedLM;w.DebertaForQuestionAnswering;w.DebertaForSequenceClassification;w.DebertaForTokenClassification;w.DebertaModel;w.DebertaPreTrainedModel;w.DebertaTokenizer;w.DebertaV2ForMaskedLM;w.DebertaV2ForQuestionAnswering;w.DebertaV2ForSequenceClassification;w.DebertaV2ForTokenClassification;w.DebertaV2Model;w.DebertaV2PreTrainedModel;w.DebertaV2Tokenizer;w.DeiTFeatureExtractor;w.DeiTForImageClassification;w.DeiTModel;w.DeiTPreTrainedModel;w.DepthAnythingForDepthEstimation;w.DepthAnythingPreTrainedModel;w.DepthEstimationPipeline;w.DetrFeatureExtractor;w.DetrForObjectDetection;w.DetrForSegmentation;w.DetrModel;w.DetrObjectDetectionOutput;w.DetrPreTrainedModel;w.DetrSegmentationOutput;w.Dinov2ForImageClassification;w.Dinov2Model;w.Dinov2PreTrainedModel;w.DistilBertForMaskedLM;w.DistilBertForQuestionAnswering;w.DistilBertForSequenceClassification;w.DistilBertForTokenClassification;w.DistilBertModel;w.DistilBertPreTrainedModel;w.DistilBertTokenizer;w.DocumentQuestionAnsweringPipeline;w.DonutFeatureExtractor;w.DonutSwinModel;w.DonutSwinPreTrainedModel;w.EfficientNetForImageClassification;w.EfficientNetImageProcessor;w.EfficientNetModel;w.EfficientNetPreTrainedModel;w.ElectraForMaskedLM;w.ElectraForQuestionAnswering;w.ElectraForSequenceClassification;w.ElectraForTokenClassification;w.ElectraModel;w.ElectraPreTrainedModel;w.ElectraTokenizer;w.EosTokenCriteria;w.EsmForMaskedLM;w.EsmForSequenceClassification;w.EsmForTokenClassification;w.EsmModel;w.EsmPreTrainedModel;w.EsmTokenizer;w.FFT;w.FalconForCausalLM;w.FalconModel;w.FalconPreTrainedModel;w.FalconTokenizer;w.FastViTForImageClassification;w.FastViTModel;w.FastViTPreTrainedModel;w.FeatureExtractionPipeline;w.FeatureExtractor;w.FillMaskPipeline;w.Florence2ForConditionalGeneration;w.Florence2PreTrainedModel;w.Florence2Processor;w.GLPNFeatureExtractor;w.GLPNForDepthEstimation;w.GLPNModel;w.GLPNPreTrainedModel;w.GPT2LMHeadModel;w.GPT2Model;w.GPT2PreTrainedModel;w.GPT2Tokenizer;w.GPTBigCodeForCausalLM;w.GPTBigCodeModel;w.GPTBigCodePreTrainedModel;w.GPTJForCausalLM;w.GPTJModel;w.GPTJPreTrainedModel;w.GPTNeoForCausalLM;w.GPTNeoModel;w.GPTNeoPreTrainedModel;w.GPTNeoXForCausalLM;w.GPTNeoXModel;w.GPTNeoXPreTrainedModel;w.GPTNeoXTokenizer;w.Gemma2ForCausalLM;w.Gemma2Model;w.Gemma2PreTrainedModel;w.GemmaForCausalLM;w.GemmaModel;w.GemmaPreTrainedModel;w.GemmaTokenizer;w.Grok1Tokenizer;w.HerbertTokenizer;w.HubertForCTC;w.HubertForSequenceClassification;w.HubertModel;w.HubertPreTrainedModel;w.ImageClassificationPipeline;w.ImageFeatureExtractionPipeline;w.ImageFeatureExtractor;w.ImageMattingOutput;w.ImageSegmentationPipeline;w.ImageToImagePipeline;w.ImageToTextPipeline;w.InterruptableStoppingCriteria;w.LlamaForCausalLM;w.LlamaModel;w.LlamaPreTrainedModel;w.LlamaTokenizer;w.LlavaForConditionalGeneration;w.LlavaPreTrainedModel;w.LongT5ForConditionalGeneration;w.LongT5Model;w.LongT5PreTrainedModel;w.M2M100ForConditionalGeneration;w.M2M100Model;w.M2M100PreTrainedModel;w.M2M100Tokenizer;w.MBart50Tokenizer;w.MBartForCausalLM;w.MBartForConditionalGeneration;w.MBartForSequenceClassification;w.MBartModel;w.MBartPreTrainedModel;w.MBartTokenizer;w.MPNetForMaskedLM;w.MPNetForQuestionAnswering;w.MPNetForSequenceClassification;w.MPNetForTokenClassification;w.MPNetModel;w.MPNetPreTrainedModel;w.MPNetTokenizer;w.MT5ForConditionalGeneration;w.MT5Model;w.MT5PreTrainedModel;w.MarianMTModel;w.MarianModel;w.MarianPreTrainedModel;w.MarianTokenizer;w.MaskedLMOutput;w.MaxLengthCriteria;w.MistralForCausalLM;w.MistralModel;w.MistralPreTrainedModel;w.MobileBertForMaskedLM;w.MobileBertForQuestionAnswering;w.MobileBertForSequenceClassification;w.MobileBertModel;w.MobileBertPreTrainedModel;w.MobileBertTokenizer;w.MobileNetV1FeatureExtractor;w.MobileNetV1ForImageClassification;w.MobileNetV1Model;w.MobileNetV1PreTrainedModel;w.MobileNetV2FeatureExtractor;w.MobileNetV2ForImageClassification;w.MobileNetV2Model;w.MobileNetV2PreTrainedModel;w.MobileNetV3FeatureExtractor;w.MobileNetV3ForImageClassification;w.MobileNetV3Model;w.MobileNetV3PreTrainedModel;w.MobileNetV4FeatureExtractor;w.MobileNetV4ForImageClassification;w.MobileNetV4Model;w.MobileNetV4PreTrainedModel;w.MobileViTFeatureExtractor;w.MobileViTForImageClassification;w.MobileViTImageProcessor;w.MobileViTModel;w.MobileViTPreTrainedModel;w.MobileViTV2ForImageClassification;w.MobileViTV2Model;w.MobileViTV2PreTrainedModel;w.ModelOutput;w.Moondream1ForConditionalGeneration;w.MptForCausalLM;w.MptModel;w.MptPreTrainedModel;w.MusicgenForCausalLM;w.MusicgenForConditionalGeneration;w.MusicgenModel;w.MusicgenPreTrainedModel;w.NllbTokenizer;w.NomicBertModel;w.NomicBertPreTrainedModel;w.NougatImageProcessor;w.NougatTokenizer;w.OPTForCausalLM;w.OPTModel;w.OPTPreTrainedModel;w.ObjectDetectionPipeline;w.OpenELMForCausalLM;w.OpenELMModel;w.OpenELMPreTrainedModel;w.OwlViTFeatureExtractor;w.OwlViTForObjectDetection;w.OwlViTModel;w.OwlViTPreTrainedModel;w.OwlViTProcessor;w.Owlv2ForObjectDetection;w.Owlv2ImageProcessor;w.Owlv2Model;w.Owlv2PreTrainedModel;w.Phi3ForCausalLM;w.Phi3Model;w.Phi3PreTrainedModel;w.PhiForCausalLM;w.PhiModel;w.PhiPreTrainedModel;w.Pipeline;w.PreTrainedModel;w.PreTrainedTokenizer;w.PretrainedConfig;w.PretrainedMixin;w.Processor;w.PyAnnoteFeatureExtractor;w.PyAnnoteForAudioFrameClassification;w.PyAnnoteModel;w.PyAnnotePreTrainedModel;w.PyAnnoteProcessor;w.QuestionAnsweringModelOutput;w.QuestionAnsweringPipeline;w.Qwen2ForCausalLM;w.Qwen2Model;w.Qwen2PreTrainedModel;w.Qwen2Tokenizer;w.RTDetrForObjectDetection;w.RTDetrImageProcessor;w.RTDetrModel;w.RTDetrObjectDetectionOutput;w.RTDetrPreTrainedModel;w.RawImage;w.ResNetForImageClassification;w.ResNetModel;w.ResNetPreTrainedModel;w.RoFormerForMaskedLM;w.RoFormerForQuestionAnswering;w.RoFormerForSequenceClassification;w.RoFormerForTokenClassification;w.RoFormerModel;w.RoFormerPreTrainedModel;w.RoFormerTokenizer;w.RobertaForMaskedLM;w.RobertaForQuestionAnswering;w.RobertaForSequenceClassification;w.RobertaForTokenClassification;w.RobertaModel;w.RobertaPreTrainedModel;w.RobertaTokenizer;w.SamImageProcessor;w.SamImageSegmentationOutput;w.SamModel;w.SamPreTrainedModel;w.SamProcessor;w.SeamlessM4TFeatureExtractor;w.SegformerFeatureExtractor;w.SegformerForImageClassification;w.SegformerForSemanticSegmentation;w.SegformerModel;w.SegformerPreTrainedModel;w.Seq2SeqLMOutput;w.SequenceClassifierOutput;w.SiglipImageProcessor;w.SiglipModel;w.SiglipPreTrainedModel;w.SiglipTextModel;w.SiglipTokenizer;w.SiglipVisionModel;w.SpeechT5FeatureExtractor;w.SpeechT5ForSpeechToText;w.SpeechT5ForTextToSpeech;w.SpeechT5HifiGan;w.SpeechT5Model;w.SpeechT5PreTrainedModel;w.SpeechT5Processor;w.SpeechT5Tokenizer;w.SqueezeBertForMaskedLM;w.SqueezeBertForQuestionAnswering;w.SqueezeBertForSequenceClassification;w.SqueezeBertModel;w.SqueezeBertPreTrainedModel;w.SqueezeBertTokenizer;w.StableLmForCausalLM;w.StableLmModel;w.StableLmPreTrainedModel;w.Starcoder2ForCausalLM;w.Starcoder2Model;w.Starcoder2PreTrainedModel;w.StoppingCriteria;w.StoppingCriteriaList;w.SummarizationPipeline;w.Swin2SRForImageSuperResolution;w.Swin2SRImageProcessor;w.Swin2SRModel;w.Swin2SRPreTrainedModel;w.SwinForImageClassification;w.SwinModel;w.SwinPreTrainedModel;w.T5ForConditionalGeneration;w.T5Model;w.T5PreTrainedModel;w.T5Tokenizer;w.TableTransformerForObjectDetection;w.TableTransformerModel;w.TableTransformerObjectDetectionOutput;w.TableTransformerPreTrainedModel;w.Tensor;w.Text2TextGenerationPipeline;w.TextClassificationPipeline;w.TextGenerationPipeline;w.TextStreamer;w.TextToAudioPipeline;w.TokenClassificationPipeline;w.TokenClassifierOutput;w.TokenizerModel;w.TrOCRForCausalLM;w.TrOCRPreTrainedModel;w.TranslationPipeline;w.UniSpeechForCTC;w.UniSpeechForSequenceClassification;w.UniSpeechModel;w.UniSpeechPreTrainedModel;w.UniSpeechSatForAudioFrameClassification;w.UniSpeechSatForCTC;w.UniSpeechSatForSequenceClassification;w.UniSpeechSatModel;w.UniSpeechSatPreTrainedModel;w.ViTFeatureExtractor;w.ViTForImageClassification;w.ViTImageProcessor;w.ViTModel;w.ViTPreTrainedModel;w.VisionEncoderDecoderModel;w.VitMatteForImageMatting;w.VitMatteImageProcessor;w.VitMattePreTrainedModel;w.VitsModel;w.VitsModelOutput;w.VitsPreTrainedModel;w.VitsTokenizer;w.Wav2Vec2BertForCTC;w.Wav2Vec2BertForSequenceClassification;w.Wav2Vec2BertModel;w.Wav2Vec2BertPreTrainedModel;w.Wav2Vec2CTCTokenizer;w.Wav2Vec2FeatureExtractor;w.Wav2Vec2ForAudioFrameClassification;w.Wav2Vec2ForCTC;w.Wav2Vec2ForSequenceClassification;w.Wav2Vec2Model;w.Wav2Vec2PreTrainedModel;w.Wav2Vec2ProcessorWithLM;w.WavLMForAudioFrameClassification;w.WavLMForCTC;w.WavLMForSequenceClassification;w.WavLMForXVector;w.WavLMModel;w.WavLMPreTrainedModel;w.WeSpeakerFeatureExtractor;w.WeSpeakerResNetModel;w.WeSpeakerResNetPreTrainedModel;w.WhisperFeatureExtractor;w.WhisperForConditionalGeneration;w.WhisperModel;w.WhisperPreTrainedModel;w.WhisperProcessor;w.WhisperTextStreamer;w.WhisperTokenizer;w.XLMForQuestionAnswering;w.XLMForSequenceClassification;w.XLMForTokenClassification;w.XLMModel;w.XLMPreTrainedModel;w.XLMRobertaForMaskedLM;w.XLMRobertaForQuestionAnswering;w.XLMRobertaForSequenceClassification;w.XLMRobertaForTokenClassification;w.XLMRobertaModel;w.XLMRobertaPreTrainedModel;w.XLMRobertaTokenizer;w.XLMTokenizer;w.XLMWithLMHeadModel;w.XVectorOutput;w.YolosFeatureExtractor;w.YolosForObjectDetection;w.YolosModel;w.YolosObjectDetectionOutput;w.YolosPreTrainedModel;w.ZeroShotAudioClassificationPipeline;w.ZeroShotClassificationPipeline;w.ZeroShotImageClassificationPipeline;w.ZeroShotObjectDetectionPipeline;w.bankers_round;w.cat;w.cos_sim;w.dot;w.dynamic_time_warping;w.env;w.full;w.full_like;w.getKeyValueShapes;w.hamming;w.hanning;w.interpolate;w.interpolate_4d;w.interpolate_data;w.is_chinese_char;w.layer_norm;w.log_softmax;w.magnitude;w.matmul;w.max;w.mean;w.mean_pooling;w.medianFilter;w.mel_filter_bank;w.min;w.ones;w.ones_like;w.permute;w.permute_data;w.pipeline;w.quantize_embeddings;w.read_audio;w.rfft;w.round;w.softmax;w.spectrogram;w.stack;w.std_mean;w.topk;w.window_function;w.zeros;w.zeros_like;function fS(){ji.useState([]),ji.useState([]),ji.useState(!1),ji.useState(!1);const[e,n]=ji.useState(!0),r=ji.useRef(null),o=ji.useRef(null);return ji.useEffect(()=>{(async()=>{const l="Xenova/modnet";r.current??(r.current=await cS.from_pretrained(l,{})),o.current??(o.current=await pS.from_pretrained(l)),n(!1)})()},[]),"hi"}ZM(document.getElementById("root")).render(I0.jsx(ji.StrictMode,{children:I0.jsx(fS,{})}));