diff --git "a/assets/index-C-k-PxxY.js" "b/assets/index-C-k-PxxY.js" new file mode 100644--- /dev/null +++ "b/assets/index-C-k-PxxY.js" @@ -0,0 +1,2688 @@ +var FM=Object.defineProperty;var zM=(e,t,n)=>t in e?FM(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var qe=(e,t,n)=>zM(e,typeof t!="symbol"?t+"":t,n);(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))o(a);new MutationObserver(a=>{for(const l of a)if(l.type==="childList")for(const f of l.addedNodes)f.tagName==="LINK"&&f.rel==="modulepreload"&&o(f)}).observe(document,{childList:!0,subtree:!0});function n(a){const l={};return a.integrity&&(l.integrity=a.integrity),a.referrerPolicy&&(l.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?l.credentials="include":a.crossOrigin==="anonymous"?l.credentials="omit":l.credentials="same-origin",l}function o(a){if(a.ep)return;a.ep=!0;const l=n(a);fetch(a.href,l)}})();var So=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function b_(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var b1={exports:{}},Xh={},x1={exports:{}},Mr={};/** + * @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 Kf=Symbol.for("react.element"),OM=Symbol.for("react.portal"),DM=Symbol.for("react.fragment"),LM=Symbol.for("react.strict_mode"),RM=Symbol.for("react.profiler"),BM=Symbol.for("react.provider"),NM=Symbol.for("react.context"),jM=Symbol.for("react.forward_ref"),UM=Symbol.for("react.suspense"),VM=Symbol.for("react.memo"),WM=Symbol.for("react.lazy"),Zw=Symbol.iterator;function GM(e){return e===null||typeof e!="object"?null:(e=Zw&&e[Zw]||e["@@iterator"],typeof e=="function"?e:null)}var M1={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},T1=Object.assign,k1={};function tu(e,t,n){this.props=e,this.context=t,this.refs=k1,this.updater=n||M1}tu.prototype.isReactComponent={};tu.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")};tu.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function S1(){}S1.prototype=tu.prototype;function x_(e,t,n){this.props=e,this.context=t,this.refs=k1,this.updater=n||M1}var M_=x_.prototype=new S1;M_.constructor=x_;T1(M_,tu.prototype);M_.isPureReactComponent=!0;var Jw=Array.isArray,E1=Object.prototype.hasOwnProperty,T_={current:null},C1={key:!0,ref:!0,__self:!0,__source:!0};function P1(e,t,n){var o,a={},l=null,f=null;if(t!=null)for(o in t.ref!==void 0&&(f=t.ref),t.key!==void 0&&(l=""+t.key),t)E1.call(t,o)&&!C1.hasOwnProperty(o)&&(a[o]=t[o]);var _=arguments.length-2;if(_===1)a.children=n;else if(1<_){for(var h=Array(_),g=0;g<_;g++)h[g]=arguments[g+2];a.children=h}if(e&&e.defaultProps)for(o in _=e.defaultProps,_)a[o]===void 0&&(a[o]=_[o]);return{$$typeof:Kf,type:e,key:l,ref:f,props:a,_owner:T_.current}}function qM(e,t){return{$$typeof:Kf,type:e.type,key:t,ref:e.ref,props:e.props,_owner:e._owner}}function k_(e){return typeof e=="object"&&e!==null&&e.$$typeof===Kf}function HM(e){var t={"=":"=0",":":"=2"};return"$"+e.replace(/[=:]/g,function(n){return t[n]})}var ev=/\/+/g;function Ym(e,t){return typeof e=="object"&&e!==null&&e.key!=null?HM(""+e.key):t.toString(36)}function ch(e,t,n,o,a){var l=typeof e;(l==="undefined"||l==="boolean")&&(e=null);var f=!1;if(e===null)f=!0;else switch(l){case"string":case"number":f=!0;break;case"object":switch(e.$$typeof){case Kf:case OM:f=!0}}if(f)return f=e,a=a(f),e=o===""?"."+Ym(f,0):o,Jw(a)?(n="",e!=null&&(n=e.replace(ev,"$&/")+"/"),ch(a,t,n,"",function(g){return g})):a!=null&&(k_(a)&&(a=qM(a,n+(!a.key||f&&f.key===a.key?"":(""+a.key).replace(ev,"$&/")+"/")+e)),t.push(a)),1;if(f=0,o=o===""?".":o+":",Jw(e))for(var _=0;_>>1,me=Q[X];if(0>>1;Xa(Be,Se))Wea(ot,Be)?(Q[X]=ot,Q[We]=Se,X=We):(Q[X]=Be,Q[De]=Se,X=De);else if(Wea(ot,Se))Q[X]=ot,Q[We]=Se,X=We;else break e}}return ae}function a(Q,ae){var Se=Q.sortIndex-ae.sortIndex;return Se!==0?Se:Q.id-ae.id}if(typeof performance=="object"&&typeof performance.now=="function"){var l=performance;e.unstable_now=function(){return l.now()}}else{var f=Date,_=f.now();e.unstable_now=function(){return f.now()-_}}var h=[],g=[],M=1,w=null,C=3,k=!1,z=!1,S=!1,P=typeof setTimeout=="function"?setTimeout:null,y=typeof clearTimeout=="function"?clearTimeout:null,x=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function I(Q){for(var ae=n(g);ae!==null;){if(ae.callback===null)o(g);else if(ae.startTime<=Q)o(g),ae.sortIndex=ae.expirationTime,t(h,ae);else break;ae=n(g)}}function U(Q){if(S=!1,I(Q),!z)if(n(h)!==null)z=!0,Qe(O);else{var ae=n(g);ae!==null&&ge(U,ae.startTime-Q)}}function O(Q,ae){z=!1,S&&(S=!1,y(D),D=-1),k=!0;var Se=C;try{for(I(ae),w=n(h);w!==null&&(!(w.expirationTime>ae)||Q&&!Ce());){var X=w.callback;if(typeof X=="function"){w.callback=null,C=w.priorityLevel;var me=X(w.expirationTime<=ae);ae=e.unstable_now(),typeof me=="function"?w.callback=me:w===n(h)&&o(h),I(ae)}else o(h);w=n(h)}if(w!==null)var Ke=!0;else{var De=n(g);De!==null&&ge(U,De.startTime-ae),Ke=!1}return Ke}finally{w=null,C=Se,k=!1}}var N=!1,j=null,D=-1,Y=5,de=-1;function Ce(){return!(e.unstable_now()-deQ||125X?(Q.sortIndex=Se,t(g,Q),n(h)===null&&Q===n(g)&&(S?(y(D),D=-1):S=!0,ge(U,Se-X))):(Q.sortIndex=me,t(h,Q),z||k||(z=!0,Qe(O))),Q},e.unstable_shouldYield=Ce,e.unstable_wrapCallback=function(Q){var ae=C;return function(){var Se=C;C=ae;try{return Q.apply(this,arguments)}finally{C=Se}}}})(z1);F1.exports=z1;var nT=F1.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 iT=hr,yi=nT;function bt(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),Tg=Object.prototype.hasOwnProperty,oT=/^[: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]*$/,tv={},rv={};function sT(e){return Tg.call(rv,e)?!0:Tg.call(tv,e)?!1:oT.test(e)?rv[e]=!0:(tv[e]=!0,!1)}function aT(e,t,n,o){if(n!==null&&n.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return o?!1:n!==null?!n.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function lT(e,t,n,o){if(t===null||typeof t>"u"||aT(e,t,n,o))return!0;if(o)return!1;if(n!==null)switch(n.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function ri(e,t,n,o,a,l,f){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=o,this.attributeNamespace=a,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=l,this.removeEmptyString=f}var Ln={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){Ln[e]=new ri(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];Ln[t]=new ri(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){Ln[e]=new ri(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){Ln[e]=new ri(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){Ln[e]=new ri(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){Ln[e]=new ri(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){Ln[e]=new ri(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){Ln[e]=new ri(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){Ln[e]=new ri(e,5,!1,e.toLowerCase(),null,!1,!1)});var S_=/[\-:]([a-z])/g;function E_(e){return e[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e){var t=e.replace(S_,E_);Ln[t]=new ri(t,1,!1,e,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(S_,E_);Ln[t]=new ri(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(S_,E_);Ln[t]=new ri(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){Ln[e]=new ri(e,1,!1,e.toLowerCase(),null,!1,!1)});Ln.xlinkHref=new ri("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){Ln[e]=new ri(e,1,!1,e.toLowerCase(),null,!0,!0)});function C_(e,t,n,o){var a=Ln.hasOwnProperty(t)?Ln[t]:null;(a!==null?a.type!==0:o||!(2_||a[f]!==l[_]){var h=` +`+a[f].replace(" at new "," at ");return e.displayName&&h.includes("")&&(h=h.replace("",e.displayName)),h}while(1<=f&&0<=_);break}}}finally{Jm=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?gf(e):""}function uT(e){switch(e.tag){case 5:return gf(e.type);case 16:return gf("Lazy");case 13:return gf("Suspense");case 19:return gf("SuspenseList");case 0:case 2:case 15:return e=eg(e.type,!1),e;case 11:return e=eg(e.type.render,!1),e;case 1:return e=eg(e.type,!0),e;default:return""}}function Cg(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 Al:return"Fragment";case $l:return"Portal";case kg:return"Profiler";case P_:return"StrictMode";case Sg:return"Suspense";case Eg:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case L1:return(e.displayName||"Context")+".Consumer";case D1:return(e._context.displayName||"Context")+".Provider";case $_:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case A_:return t=e.displayName||null,t!==null?t:Cg(e.type)||"Memo";case ss:t=e._payload,e=e._init;try{return Cg(e(t))}catch{}}return null}function cT(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return Cg(t);case 8:return t===P_?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function vs(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function B1(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function dT(e){var t=B1(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),o=""+e[t];if(!e.hasOwnProperty(t)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var a=n.get,l=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return a.call(this)},set:function(f){o=""+f,l.call(this,f)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return o},setValue:function(f){o=""+f},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function Hp(e){e._valueTracker||(e._valueTracker=dT(e))}function N1(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),o="";return e&&(o=B1(e)?e.checked?"true":"false":e.value),e=o,e!==n?(t.setValue(e),!0):!1}function Mh(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 Pg(e,t){var n=t.checked;return on({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function iv(e,t){var n=t.defaultValue==null?"":t.defaultValue,o=t.checked!=null?t.checked:t.defaultChecked;n=vs(t.value!=null?t.value:n),e._wrapperState={initialChecked:o,initialValue:n,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function j1(e,t){t=t.checked,t!=null&&C_(e,"checked",t,!1)}function $g(e,t){j1(e,t);var n=vs(t.value),o=t.type;if(n!=null)o==="number"?(n===0&&e.value===""||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if(o==="submit"||o==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?Ag(e,t.type,n):t.hasOwnProperty("defaultValue")&&Ag(e,t.type,vs(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function ov(e,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var o=t.type;if(!(o!=="submit"&&o!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}n=e.name,n!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,n!==""&&(e.name=n)}function Ag(e,t,n){(t!=="number"||Mh(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var _f=Array.isArray;function Ul(e,t,n,o){if(e=e.options,t){t={};for(var a=0;a"+t.valueOf().toString()+"",t=Kp.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function Af(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var bf={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},fT=["Webkit","ms","Moz","O"];Object.keys(bf).forEach(function(e){fT.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),bf[t]=bf[e]})});function G1(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||bf.hasOwnProperty(e)&&bf[e]?(""+t).trim():t+"px"}function q1(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var o=n.indexOf("--")===0,a=G1(n,t[n],o);n==="float"&&(n="cssFloat"),o?e.setProperty(n,a):e[n]=a}}var pT=on({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 zg(e,t){if(t){if(pT[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(bt(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(bt(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(bt(61))}if(t.style!=null&&typeof t.style!="object")throw Error(bt(62))}}function Og(e,t){if(e.indexOf("-")===-1)return typeof t.is=="string";switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var Dg=null;function I_(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var Lg=null,Vl=null,Wl=null;function lv(e){if(e=Yf(e)){if(typeof Lg!="function")throw Error(bt(280));var t=e.stateNode;t&&(t=tm(t),Lg(e.stateNode,e.type,t))}}function H1(e){Vl?Wl?Wl.push(e):Wl=[e]:Vl=e}function K1(){if(Vl){var e=Vl,t=Wl;if(Wl=Vl=null,lv(e),t)for(e=0;e>>=0,e===0?32:31-(TT(e)/kT|0)|0}var Qp=64,Xp=4194304;function yf(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 Eh(e,t){var n=e.pendingLanes;if(n===0)return 0;var o=0,a=e.suspendedLanes,l=e.pingedLanes,f=n&268435455;if(f!==0){var _=f&~a;_!==0?o=yf(_):(l&=f,l!==0&&(o=yf(l)))}else f=n&~a,f!==0?o=yf(f):l!==0&&(o=yf(l));if(o===0)return 0;if(t!==0&&t!==o&&!(t&a)&&(a=o&-o,l=t&-t,a>=l||a===16&&(l&4194240)!==0))return t;if(o&4&&(o|=n&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=o;0n;n++)t.push(e);return t}function Qf(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-Ki(t),e[t]=n}function PT(e,t){var n=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var o=e.eventTimes;for(e=e.expirationTimes;0=Mf),_v=" ",yv=!1;function hb(e,t){switch(e){case"keyup":return nk.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function mb(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var Il=!1;function ok(e,t){switch(e){case"compositionend":return mb(t);case"keypress":return t.which!==32?null:(yv=!0,_v);case"textInput":return e=t.data,e===_v&&yv?null:e;default:return null}}function sk(e,t){if(Il)return e==="compositionend"||!N_&&hb(e,t)?(e=fb(),ph=L_=cs=null,Il=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=o}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=xv(n)}}function wb(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?wb(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function vb(){for(var e=window,t=Mh();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=Mh(e.document)}return t}function j_(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}function mk(e){var t=vb(),n=e.focusedElem,o=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&wb(n.ownerDocument.documentElement,n)){if(o!==null&&j_(n)){if(t=o.start,e=o.end,e===void 0&&(e=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(e,n.value.length);else if(e=(t=n.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var a=n.textContent.length,l=Math.min(o.start,a);o=o.end===void 0?l:Math.min(o.end,a),!e.extend&&l>o&&(a=o,o=l,l=a),a=Mv(n,l);var f=Mv(n,o);a&&f&&(e.rangeCount!==1||e.anchorNode!==a.node||e.anchorOffset!==a.offset||e.focusNode!==f.node||e.focusOffset!==f.offset)&&(t=t.createRange(),t.setStart(a.node,a.offset),e.removeAllRanges(),l>o?(e.addRange(t),e.extend(f.node,f.offset)):(t.setEnd(f.node,f.offset),e.addRange(t)))}}for(t=[],e=n;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n=document.documentMode,Fl=null,Vg=null,kf=null,Wg=!1;function Tv(e,t,n){var o=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;Wg||Fl==null||Fl!==Mh(o)||(o=Fl,"selectionStart"in o&&j_(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}),kf&&Lf(kf,o)||(kf=o,o=$h(Vg,"onSelect"),0Dl||(e.current=Xg[Dl],Xg[Dl]=null,Dl--)}function Kr(e,t){Dl++,Xg[Dl]=e.current,e.current=t}var bs={},Gn=Ms(bs),ai=Ms(!1),ia=bs;function Ql(e,t){var n=e.type.contextTypes;if(!n)return bs;var o=e.stateNode;if(o&&o.__reactInternalMemoizedUnmaskedChildContext===t)return o.__reactInternalMemoizedMaskedChildContext;var a={},l;for(l in n)a[l]=t[l];return o&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=a),a}function li(e){return e=e.childContextTypes,e!=null}function Ih(){Zr(ai),Zr(Gn)}function Av(e,t,n){if(Gn.current!==bs)throw Error(bt(168));Kr(Gn,t),Kr(ai,n)}function Pb(e,t,n){var o=e.stateNode;if(t=t.childContextTypes,typeof o.getChildContext!="function")return n;o=o.getChildContext();for(var a in o)if(!(a in t))throw Error(bt(108,cT(e)||"Unknown",a));return on({},n,o)}function Fh(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||bs,ia=Gn.current,Kr(Gn,e),Kr(ai,ai.current),!0}function Iv(e,t,n){var o=e.stateNode;if(!o)throw Error(bt(169));n?(e=Pb(e,t,ia),o.__reactInternalMemoizedMergedChildContext=e,Zr(ai),Zr(Gn),Kr(Gn,e)):Zr(ai),Kr(ai,n)}var ko=null,rm=!1,hg=!1;function $b(e){ko===null?ko=[e]:ko.push(e)}function Ek(e){rm=!0,$b(e)}function Ts(){if(!hg&&ko!==null){hg=!0;var e=0,t=Rr;try{var n=ko;for(Rr=1;e>=f,a-=f,Eo=1<<32-Ki(t)+a|n<D?(Y=j,j=null):Y=j.sibling;var de=C(y,j,I[D],U);if(de===null){j===null&&(j=Y);break}e&&j&&de.alternate===null&&t(y,j),x=l(de,x,D),N===null?O=de:N.sibling=de,N=de,j=Y}if(D===I.length)return n(y,j),en&&Xs(y,D),O;if(j===null){for(;DD?(Y=j,j=null):Y=j.sibling;var Ce=C(y,j,de.value,U);if(Ce===null){j===null&&(j=Y);break}e&&j&&Ce.alternate===null&&t(y,j),x=l(Ce,x,D),N===null?O=Ce:N.sibling=Ce,N=Ce,j=Y}if(de.done)return n(y,j),en&&Xs(y,D),O;if(j===null){for(;!de.done;D++,de=I.next())de=w(y,de.value,U),de!==null&&(x=l(de,x,D),N===null?O=de:N.sibling=de,N=de);return en&&Xs(y,D),O}for(j=o(y,j);!de.done;D++,de=I.next())de=k(j,y,D,de.value,U),de!==null&&(e&&de.alternate!==null&&j.delete(de.key===null?D:de.key),x=l(de,x,D),N===null?O=de:N.sibling=de,N=de);return e&&j.forEach(function(ee){return t(y,ee)}),en&&Xs(y,D),O}function P(y,x,I,U){if(typeof I=="object"&&I!==null&&I.type===Al&&I.key===null&&(I=I.props.children),typeof I=="object"&&I!==null){switch(I.$$typeof){case qp:e:{for(var O=I.key,N=x;N!==null;){if(N.key===O){if(O=I.type,O===Al){if(N.tag===7){n(y,N.sibling),x=a(N,I.props.children),x.return=y,y=x;break e}}else if(N.elementType===O||typeof O=="object"&&O!==null&&O.$$typeof===ss&&Ov(O)===N.type){n(y,N.sibling),x=a(N,I.props),x.ref=pf(y,N,I),x.return=y,y=x;break e}n(y,N);break}else t(y,N);N=N.sibling}I.type===Al?(x=na(I.props.children,y.mode,U,I.key),x.return=y,y=x):(U=bh(I.type,I.key,I.props,null,y.mode,U),U.ref=pf(y,x,I),U.return=y,y=U)}return f(y);case $l:e:{for(N=I.key;x!==null;){if(x.key===N)if(x.tag===4&&x.stateNode.containerInfo===I.containerInfo&&x.stateNode.implementation===I.implementation){n(y,x.sibling),x=a(x,I.children||[]),x.return=y,y=x;break e}else{n(y,x);break}else t(y,x);x=x.sibling}x=xg(I,y.mode,U),x.return=y,y=x}return f(y);case ss:return N=I._init,P(y,x,N(I._payload),U)}if(_f(I))return z(y,x,I,U);if(lf(I))return S(y,x,I,U);nh(y,I)}return typeof I=="string"&&I!==""||typeof I=="number"?(I=""+I,x!==null&&x.tag===6?(n(y,x.sibling),x=a(x,I),x.return=y,y=x):(n(y,x),x=bg(I,y.mode,U),x.return=y,y=x),f(y)):n(y,x)}return P}var Yl=zb(!0),Ob=zb(!1),Dh=Ms(null),Lh=null,Bl=null,G_=null;function q_(){G_=Bl=Lh=null}function H_(e){var t=Dh.current;Zr(Dh),e._currentValue=t}function Jg(e,t,n){for(;e!==null;){var o=e.alternate;if((e.childLanes&t)!==t?(e.childLanes|=t,o!==null&&(o.childLanes|=t)):o!==null&&(o.childLanes&t)!==t&&(o.childLanes|=t),e===n)break;e=e.return}}function ql(e,t){Lh=e,G_=Bl=null,e=e.dependencies,e!==null&&e.firstContext!==null&&(e.lanes&t&&(si=!0),e.firstContext=null)}function Oi(e){var t=e._currentValue;if(G_!==e)if(e={context:e,memoizedValue:t,next:null},Bl===null){if(Lh===null)throw Error(bt(308));Bl=e,Lh.dependencies={lanes:0,firstContext:e}}else Bl=Bl.next=e;return t}var ea=null;function K_(e){ea===null?ea=[e]:ea.push(e)}function Db(e,t,n,o){var a=t.interleaved;return a===null?(n.next=n,K_(t)):(n.next=a.next,a.next=n),t.interleaved=n,Io(e,o)}function Io(e,t){e.lanes|=t;var n=e.alternate;for(n!==null&&(n.lanes|=t),n=e,e=e.return;e!==null;)e.childLanes|=t,n=e.alternate,n!==null&&(n.childLanes|=t),n=e,e=e.return;return n.tag===3?n.stateNode:null}var as=!1;function Q_(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function Lb(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function Po(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function gs(e,t,n){var o=e.updateQueue;if(o===null)return null;if(o=o.shared,Ir&2){var a=o.pending;return a===null?t.next=t:(t.next=a.next,a.next=t),o.pending=t,Io(e,n)}return a=o.interleaved,a===null?(t.next=t,K_(o)):(t.next=a.next,a.next=t),o.interleaved=t,Io(e,n)}function mh(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,(n&4194240)!==0)){var o=t.lanes;o&=e.pendingLanes,n|=o,t.lanes=n,z_(e,n)}}function Dv(e,t){var n=e.updateQueue,o=e.alternate;if(o!==null&&(o=o.updateQueue,n===o)){var a=null,l=null;if(n=n.firstBaseUpdate,n!==null){do{var f={eventTime:n.eventTime,lane:n.lane,tag:n.tag,payload:n.payload,callback:n.callback,next:null};l===null?a=l=f:l=l.next=f,n=n.next}while(n!==null);l===null?a=l=t:l=l.next=t}else a=l=t;n={baseState:o.baseState,firstBaseUpdate:a,lastBaseUpdate:l,shared:o.shared,effects:o.effects},e.updateQueue=n;return}e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}function Rh(e,t,n,o){var a=e.updateQueue;as=!1;var l=a.firstBaseUpdate,f=a.lastBaseUpdate,_=a.shared.pending;if(_!==null){a.shared.pending=null;var h=_,g=h.next;h.next=null,f===null?l=g:f.next=g,f=h;var M=e.alternate;M!==null&&(M=M.updateQueue,_=M.lastBaseUpdate,_!==f&&(_===null?M.firstBaseUpdate=g:_.next=g,M.lastBaseUpdate=h))}if(l!==null){var w=a.baseState;f=0,M=g=h=null,_=l;do{var C=_.lane,k=_.eventTime;if((o&C)===C){M!==null&&(M=M.next={eventTime:k,lane:0,tag:_.tag,payload:_.payload,callback:_.callback,next:null});e:{var z=e,S=_;switch(C=t,k=n,S.tag){case 1:if(z=S.payload,typeof z=="function"){w=z.call(k,w,C);break e}w=z;break e;case 3:z.flags=z.flags&-65537|128;case 0:if(z=S.payload,C=typeof z=="function"?z.call(k,w,C):z,C==null)break e;w=on({},w,C);break e;case 2:as=!0}}_.callback!==null&&_.lane!==0&&(e.flags|=64,C=a.effects,C===null?a.effects=[_]:C.push(_))}else k={eventTime:k,lane:C,tag:_.tag,payload:_.payload,callback:_.callback,next:null},M===null?(g=M=k,h=w):M=M.next=k,f|=C;if(_=_.next,_===null){if(_=a.shared.pending,_===null)break;C=_,_=C.next,C.next=null,a.lastBaseUpdate=C,a.shared.pending=null}}while(!0);if(M===null&&(h=w),a.baseState=h,a.firstBaseUpdate=g,a.lastBaseUpdate=M,t=a.shared.interleaved,t!==null){a=t;do f|=a.lane,a=a.next;while(a!==t)}else l===null&&(a.shared.lanes=0);aa|=f,e.lanes=f,e.memoizedState=w}}function Lv(e,t,n){if(e=t.effects,t.effects=null,e!==null)for(t=0;tn?n:4,e(!0);var o=gg.transition;gg.transition={};try{e(!1),t()}finally{Rr=n,gg.transition=o}}function e2(){return Di().memoizedState}function Ak(e,t,n){var o=ys(e);if(n={lane:o,action:n,hasEagerState:!1,eagerState:null,next:null},t2(e))r2(t,n);else if(n=Db(e,t,n,o),n!==null){var a=ei();Qi(n,e,o,a),n2(n,t,o)}}function Ik(e,t,n){var o=ys(e),a={lane:o,action:n,hasEagerState:!1,eagerState:null,next:null};if(t2(e))r2(t,a);else{var l=e.alternate;if(e.lanes===0&&(l===null||l.lanes===0)&&(l=t.lastRenderedReducer,l!==null))try{var f=t.lastRenderedState,_=l(f,n);if(a.hasEagerState=!0,a.eagerState=_,Xi(_,f)){var h=t.interleaved;h===null?(a.next=a,K_(t)):(a.next=h.next,h.next=a),t.interleaved=a;return}}catch{}finally{}n=Db(e,t,a,o),n!==null&&(a=ei(),Qi(n,e,o,a),n2(n,t,o))}}function t2(e){var t=e.alternate;return e===nn||t!==null&&t===nn}function r2(e,t){Sf=Nh=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function n2(e,t,n){if(n&4194240){var o=t.lanes;o&=e.pendingLanes,n|=o,t.lanes=n,z_(e,n)}}var jh={readContext:Oi,useCallback:Un,useContext:Un,useEffect:Un,useImperativeHandle:Un,useInsertionEffect:Un,useLayoutEffect:Un,useMemo:Un,useReducer:Un,useRef:Un,useState:Un,useDebugValue:Un,useDeferredValue:Un,useTransition:Un,useMutableSource:Un,useSyncExternalStore:Un,useId:Un,unstable_isNewReconciler:!1},Fk={readContext:Oi,useCallback:function(e,t){return so().memoizedState=[e,t===void 0?null:t],e},useContext:Oi,useEffect:Bv,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,_h(4194308,4,Qb.bind(null,t,e),n)},useLayoutEffect:function(e,t){return _h(4194308,4,e,t)},useInsertionEffect:function(e,t){return _h(4,2,e,t)},useMemo:function(e,t){var n=so();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var o=so();return t=n!==void 0?n(t):t,o.memoizedState=o.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},o.queue=e,e=e.dispatch=Ak.bind(null,nn,e),[o.memoizedState,e]},useRef:function(e){var t=so();return e={current:e},t.memoizedState=e},useState:Rv,useDebugValue:n0,useDeferredValue:function(e){return so().memoizedState=e},useTransition:function(){var e=Rv(!1),t=e[0];return e=$k.bind(null,e[1]),so().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var o=nn,a=so();if(en){if(n===void 0)throw Error(bt(407));n=n()}else{if(n=t(),Pn===null)throw Error(bt(349));sa&30||jb(o,t,n)}a.memoizedState=n;var l={value:n,getSnapshot:t};return a.queue=l,Bv(Vb.bind(null,o,l,e),[e]),o.flags|=2048,Gf(9,Ub.bind(null,o,l,n,t),void 0,null),n},useId:function(){var e=so(),t=Pn.identifierPrefix;if(en){var n=Co,o=Eo;n=(o&~(1<<32-Ki(o)-1)).toString(32)+n,t=":"+t+"R"+n,n=Vf++,0<\/script>",e=e.removeChild(e.firstChild)):typeof o.is=="string"?e=f.createElement(n,{is:o.is}):(e=f.createElement(n),n==="select"&&(f=e,o.multiple?f.multiple=!0:o.size&&(f.size=o.size))):e=f.createElementNS(e,n),e[ao]=t,e[Nf]=o,p2(e,t,!1,!1),t.stateNode=e;e:{switch(f=Og(n,o),n){case"dialog":Xr("cancel",e),Xr("close",e),a=o;break;case"iframe":case"object":case"embed":Xr("load",e),a=o;break;case"video":case"audio":for(a=0;aeu&&(t.flags|=128,o=!0,hf(l,!1),t.lanes=4194304)}else{if(!o)if(e=Bh(f),e!==null){if(t.flags|=128,o=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),hf(l,!0),l.tail===null&&l.tailMode==="hidden"&&!f.alternate&&!en)return Vn(t),null}else 2*fn()-l.renderingStartTime>eu&&n!==1073741824&&(t.flags|=128,o=!0,hf(l,!1),t.lanes=4194304);l.isBackwards?(f.sibling=t.child,t.child=f):(n=l.last,n!==null?n.sibling=f:t.child=f,l.last=f)}return l.tail!==null?(t=l.tail,l.rendering=t,l.tail=t.sibling,l.renderingStartTime=fn(),t.sibling=null,n=rn.current,Kr(rn,o?n&1|2:n&1),t):(Vn(t),null);case 22:case 23:return u0(),o=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==o&&(t.flags|=8192),o&&t.mode&1?mi&1073741824&&(Vn(t),t.subtreeFlags&6&&(t.flags|=8192)):Vn(t),null;case 24:return null;case 25:return null}throw Error(bt(156,t.tag))}function jk(e,t){switch(V_(t),t.tag){case 1:return li(t.type)&&Ih(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return Zl(),Zr(ai),Zr(Gn),Z_(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return Y_(t),null;case 13:if(Zr(rn),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(bt(340));Xl()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return Zr(rn),null;case 4:return Zl(),null;case 10:return H_(t.type._context),null;case 22:case 23:return u0(),null;case 24:return null;default:return null}}var oh=!1,Wn=!1,Uk=typeof WeakSet=="function"?WeakSet:Set,jt=null;function Nl(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(o){cn(e,t,o)}else n.current=null}function l_(e,t,n){try{n()}catch(o){cn(e,t,o)}}var Xv=!1;function Vk(e,t){if(Gg=Ch,e=vb(),j_(e)){if("selectionStart"in e)var n={start:e.selectionStart,end:e.selectionEnd};else e:{n=(n=e.ownerDocument)&&n.defaultView||window;var o=n.getSelection&&n.getSelection();if(o&&o.rangeCount!==0){n=o.anchorNode;var a=o.anchorOffset,l=o.focusNode;o=o.focusOffset;try{n.nodeType,l.nodeType}catch{n=null;break e}var f=0,_=-1,h=-1,g=0,M=0,w=e,C=null;t:for(;;){for(var k;w!==n||a!==0&&w.nodeType!==3||(_=f+a),w!==l||o!==0&&w.nodeType!==3||(h=f+o),w.nodeType===3&&(f+=w.nodeValue.length),(k=w.firstChild)!==null;)C=w,w=k;for(;;){if(w===e)break t;if(C===n&&++g===a&&(_=f),C===l&&++M===o&&(h=f),(k=w.nextSibling)!==null)break;w=C,C=w.parentNode}w=k}n=_===-1||h===-1?null:{start:_,end:h}}else n=null}n=n||{start:0,end:0}}else n=null;for(qg={focusedElem:e,selectionRange:n},Ch=!1,jt=t;jt!==null;)if(t=jt,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,jt=e;else for(;jt!==null;){t=jt;try{var z=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(z!==null){var S=z.memoizedProps,P=z.memoizedState,y=t.stateNode,x=y.getSnapshotBeforeUpdate(t.elementType===t.type?S:Gi(t.type,S),P);y.__reactInternalSnapshotBeforeUpdate=x}break;case 3:var I=t.stateNode.containerInfo;I.nodeType===1?I.textContent="":I.nodeType===9&&I.documentElement&&I.removeChild(I.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(bt(163))}}catch(U){cn(t,t.return,U)}if(e=t.sibling,e!==null){e.return=t.return,jt=e;break}jt=t.return}return z=Xv,Xv=!1,z}function Ef(e,t,n){var o=t.updateQueue;if(o=o!==null?o.lastEffect:null,o!==null){var a=o=o.next;do{if((a.tag&e)===e){var l=a.destroy;a.destroy=void 0,l!==void 0&&l_(t,n,l)}a=a.next}while(a!==o)}}function om(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var n=t=t.next;do{if((n.tag&e)===e){var o=n.create;n.destroy=o()}n=n.next}while(n!==t)}}function u_(e){var t=e.ref;if(t!==null){var n=e.stateNode;switch(e.tag){case 5:e=n;break;default:e=n}typeof t=="function"?t(e):t.current=e}}function g2(e){var t=e.alternate;t!==null&&(e.alternate=null,g2(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[ao],delete t[Nf],delete t[Qg],delete t[kk],delete t[Sk])),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 _2(e){return e.tag===5||e.tag===3||e.tag===4}function Yv(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||_2(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 c_(e,t,n){var o=e.tag;if(o===5||o===6)e=e.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(e,t):n.insertBefore(e,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(e,n)):(t=n,t.appendChild(e)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=Ah));else if(o!==4&&(e=e.child,e!==null))for(c_(e,t,n),e=e.sibling;e!==null;)c_(e,t,n),e=e.sibling}function d_(e,t,n){var o=e.tag;if(o===5||o===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(o!==4&&(e=e.child,e!==null))for(d_(e,t,n),e=e.sibling;e!==null;)d_(e,t,n),e=e.sibling}var On=null,qi=!1;function os(e,t,n){for(n=n.child;n!==null;)y2(e,t,n),n=n.sibling}function y2(e,t,n){if(lo&&typeof lo.onCommitFiberUnmount=="function")try{lo.onCommitFiberUnmount(Yh,n)}catch{}switch(n.tag){case 5:Wn||Nl(n,t);case 6:var o=On,a=qi;On=null,os(e,t,n),On=o,qi=a,On!==null&&(qi?(e=On,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):On.removeChild(n.stateNode));break;case 18:On!==null&&(qi?(e=On,n=n.stateNode,e.nodeType===8?pg(e.parentNode,n):e.nodeType===1&&pg(e,n),Of(e)):pg(On,n.stateNode));break;case 4:o=On,a=qi,On=n.stateNode.containerInfo,qi=!0,os(e,t,n),On=o,qi=a;break;case 0:case 11:case 14:case 15:if(!Wn&&(o=n.updateQueue,o!==null&&(o=o.lastEffect,o!==null))){a=o=o.next;do{var l=a,f=l.destroy;l=l.tag,f!==void 0&&(l&2||l&4)&&l_(n,t,f),a=a.next}while(a!==o)}os(e,t,n);break;case 1:if(!Wn&&(Nl(n,t),o=n.stateNode,typeof o.componentWillUnmount=="function"))try{o.props=n.memoizedProps,o.state=n.memoizedState,o.componentWillUnmount()}catch(_){cn(n,t,_)}os(e,t,n);break;case 21:os(e,t,n);break;case 22:n.mode&1?(Wn=(o=Wn)||n.memoizedState!==null,os(e,t,n),Wn=o):os(e,t,n);break;default:os(e,t,n)}}function Zv(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new Uk),t.forEach(function(o){var a=Zk.bind(null,e,o);n.has(o)||(n.add(o),o.then(a,a))})}}function Wi(e,t){var n=t.deletions;if(n!==null)for(var o=0;oa&&(a=f),o&=~l}if(o=a,o=fn()-o,o=(120>o?120:480>o?480:1080>o?1080:1920>o?1920:3e3>o?3e3:4320>o?4320:1960*Gk(o/1960))-o,10e?16:e,ds===null)var o=!1;else{if(e=ds,ds=null,Wh=0,Ir&6)throw Error(bt(331));var a=Ir;for(Ir|=4,jt=e.current;jt!==null;){var l=jt,f=l.child;if(jt.flags&16){var _=l.deletions;if(_!==null){for(var h=0;h<_.length;h++){var g=_[h];for(jt=g;jt!==null;){var M=jt;switch(M.tag){case 0:case 11:case 15:Ef(8,M,l)}var w=M.child;if(w!==null)w.return=M,jt=w;else for(;jt!==null;){M=jt;var C=M.sibling,k=M.return;if(g2(M),M===g){jt=null;break}if(C!==null){C.return=k,jt=C;break}jt=k}}}var z=l.alternate;if(z!==null){var S=z.child;if(S!==null){z.child=null;do{var P=S.sibling;S.sibling=null,S=P}while(S!==null)}}jt=l}}if(l.subtreeFlags&2064&&f!==null)f.return=l,jt=f;else e:for(;jt!==null;){if(l=jt,l.flags&2048)switch(l.tag){case 0:case 11:case 15:Ef(9,l,l.return)}var y=l.sibling;if(y!==null){y.return=l.return,jt=y;break e}jt=l.return}}var x=e.current;for(jt=x;jt!==null;){f=jt;var I=f.child;if(f.subtreeFlags&2064&&I!==null)I.return=f,jt=I;else e:for(f=x;jt!==null;){if(_=jt,_.flags&2048)try{switch(_.tag){case 0:case 11:case 15:om(9,_)}}catch(O){cn(_,_.return,O)}if(_===f){jt=null;break e}var U=_.sibling;if(U!==null){U.return=_.return,jt=U;break e}jt=_.return}}if(Ir=a,Ts(),lo&&typeof lo.onPostCommitFiberRoot=="function")try{lo.onPostCommitFiberRoot(Yh,e)}catch{}o=!0}return o}finally{Rr=n,zi.transition=t}}return!1}function n1(e,t,n){t=Jl(n,t),t=o2(e,t,1),e=gs(e,t,1),t=ei(),e!==null&&(Qf(e,1,t),ui(e,t))}function cn(e,t,n){if(e.tag===3)n1(e,e,n);else for(;t!==null;){if(t.tag===3){n1(t,e,n);break}else if(t.tag===1){var o=t.stateNode;if(typeof t.type.getDerivedStateFromError=="function"||typeof o.componentDidCatch=="function"&&(_s===null||!_s.has(o))){e=Jl(n,e),e=s2(t,e,1),t=gs(t,e,1),e=ei(),t!==null&&(Qf(t,1,e),ui(t,e));break}}t=t.return}}function Xk(e,t,n){var o=e.pingCache;o!==null&&o.delete(t),t=ei(),e.pingedLanes|=e.suspendedLanes&n,Pn===e&&(Dn&n)===n&&(Tn===4||Tn===3&&(Dn&130023424)===Dn&&500>fn()-a0?ra(e,0):s0|=n),ui(e,t)}function S2(e,t){t===0&&(e.mode&1?(t=Xp,Xp<<=1,!(Xp&130023424)&&(Xp=4194304)):t=1);var n=ei();e=Io(e,t),e!==null&&(Qf(e,t,n),ui(e,n))}function Yk(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),S2(e,n)}function Zk(e,t){var n=0;switch(e.tag){case 13:var o=e.stateNode,a=e.memoizedState;a!==null&&(n=a.retryLane);break;case 19:o=e.stateNode;break;default:throw Error(bt(314))}o!==null&&o.delete(t),S2(e,n)}var E2;E2=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||ai.current)si=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return si=!1,Bk(e,t,n);si=!!(e.flags&131072)}else si=!1,en&&t.flags&1048576&&Ab(t,Oh,t.index);switch(t.lanes=0,t.tag){case 2:var o=t.type;yh(e,t),e=t.pendingProps;var a=Ql(t,Gn.current);ql(t,n),a=e0(null,t,o,e,a,n);var l=t0();return t.flags|=1,typeof a=="object"&&a!==null&&typeof a.render=="function"&&a.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,li(o)?(l=!0,Fh(t)):l=!1,t.memoizedState=a.state!==null&&a.state!==void 0?a.state:null,Q_(t),a.updater=im,t.stateNode=a,a._reactInternals=t,t_(t,o,e,n),t=i_(null,t,o,!0,l,n)):(t.tag=0,en&&l&&U_(t),Jn(null,t,a,n),t=t.child),t;case 16:o=t.elementType;e:{switch(yh(e,t),e=t.pendingProps,a=o._init,o=a(o._payload),t.type=o,a=t.tag=eS(o),e=Gi(o,e),a){case 0:t=n_(null,t,o,e,n);break e;case 1:t=Hv(null,t,o,e,n);break e;case 11:t=Gv(null,t,o,e,n);break e;case 14:t=qv(null,t,o,Gi(o.type,e),n);break e}throw Error(bt(306,o,""))}return t;case 0:return o=t.type,a=t.pendingProps,a=t.elementType===o?a:Gi(o,a),n_(e,t,o,a,n);case 1:return o=t.type,a=t.pendingProps,a=t.elementType===o?a:Gi(o,a),Hv(e,t,o,a,n);case 3:e:{if(c2(t),e===null)throw Error(bt(387));o=t.pendingProps,l=t.memoizedState,a=l.element,Lb(e,t),Rh(t,o,null,n);var f=t.memoizedState;if(o=f.element,l.isDehydrated)if(l={element:o,isDehydrated:!1,cache:f.cache,pendingSuspenseBoundaries:f.pendingSuspenseBoundaries,transitions:f.transitions},t.updateQueue.baseState=l,t.memoizedState=l,t.flags&256){a=Jl(Error(bt(423)),t),t=Kv(e,t,o,n,a);break e}else if(o!==a){a=Jl(Error(bt(424)),t),t=Kv(e,t,o,n,a);break e}else for(gi=ms(t.stateNode.containerInfo.firstChild),_i=t,en=!0,Hi=null,n=Ob(t,null,o,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(Xl(),o===a){t=Fo(e,t,n);break e}Jn(e,t,o,n)}t=t.child}return t;case 5:return Rb(t),e===null&&Zg(t),o=t.type,a=t.pendingProps,l=e!==null?e.memoizedProps:null,f=a.children,Hg(o,a)?f=null:l!==null&&Hg(o,l)&&(t.flags|=32),u2(e,t),Jn(e,t,f,n),t.child;case 6:return e===null&&Zg(t),null;case 13:return d2(e,t,n);case 4:return X_(t,t.stateNode.containerInfo),o=t.pendingProps,e===null?t.child=Yl(t,null,o,n):Jn(e,t,o,n),t.child;case 11:return o=t.type,a=t.pendingProps,a=t.elementType===o?a:Gi(o,a),Gv(e,t,o,a,n);case 7:return Jn(e,t,t.pendingProps,n),t.child;case 8:return Jn(e,t,t.pendingProps.children,n),t.child;case 12:return Jn(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(o=t.type._context,a=t.pendingProps,l=t.memoizedProps,f=a.value,Kr(Dh,o._currentValue),o._currentValue=f,l!==null)if(Xi(l.value,f)){if(l.children===a.children&&!ai.current){t=Fo(e,t,n);break e}}else for(l=t.child,l!==null&&(l.return=t);l!==null;){var _=l.dependencies;if(_!==null){f=l.child;for(var h=_.firstContext;h!==null;){if(h.context===o){if(l.tag===1){h=Po(-1,n&-n),h.tag=2;var g=l.updateQueue;if(g!==null){g=g.shared;var M=g.pending;M===null?h.next=h:(h.next=M.next,M.next=h),g.pending=h}}l.lanes|=n,h=l.alternate,h!==null&&(h.lanes|=n),Jg(l.return,n,t),_.lanes|=n;break}h=h.next}}else if(l.tag===10)f=l.type===t.type?null:l.child;else if(l.tag===18){if(f=l.return,f===null)throw Error(bt(341));f.lanes|=n,_=f.alternate,_!==null&&(_.lanes|=n),Jg(f,n,t),f=l.sibling}else f=l.child;if(f!==null)f.return=l;else for(f=l;f!==null;){if(f===t){f=null;break}if(l=f.sibling,l!==null){l.return=f.return,f=l;break}f=f.return}l=f}Jn(e,t,a.children,n),t=t.child}return t;case 9:return a=t.type,o=t.pendingProps.children,ql(t,n),a=Oi(a),o=o(a),t.flags|=1,Jn(e,t,o,n),t.child;case 14:return o=t.type,a=Gi(o,t.pendingProps),a=Gi(o.type,a),qv(e,t,o,a,n);case 15:return a2(e,t,t.type,t.pendingProps,n);case 17:return o=t.type,a=t.pendingProps,a=t.elementType===o?a:Gi(o,a),yh(e,t),t.tag=1,li(o)?(e=!0,Fh(t)):e=!1,ql(t,n),i2(t,o,a),t_(t,o,a,n),i_(null,t,o,!0,e,n);case 19:return f2(e,t,n);case 22:return l2(e,t,n)}throw Error(bt(156,t.tag))};function C2(e,t){return tb(e,t)}function Jk(e,t,n,o){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=o,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Fi(e,t,n,o){return new Jk(e,t,n,o)}function d0(e){return e=e.prototype,!(!e||!e.isReactComponent)}function eS(e){if(typeof e=="function")return d0(e)?1:0;if(e!=null){if(e=e.$$typeof,e===$_)return 11;if(e===A_)return 14}return 2}function ws(e,t){var n=e.alternate;return n===null?(n=Fi(e.tag,t,e.key,e.mode),n.elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=e.flags&14680064,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function bh(e,t,n,o,a,l){var f=2;if(o=e,typeof e=="function")d0(e)&&(f=1);else if(typeof e=="string")f=5;else e:switch(e){case Al:return na(n.children,a,l,t);case P_:f=8,a|=8;break;case kg:return e=Fi(12,n,t,a|2),e.elementType=kg,e.lanes=l,e;case Sg:return e=Fi(13,n,t,a),e.elementType=Sg,e.lanes=l,e;case Eg:return e=Fi(19,n,t,a),e.elementType=Eg,e.lanes=l,e;case R1:return am(n,a,l,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case D1:f=10;break e;case L1:f=9;break e;case $_:f=11;break e;case A_:f=14;break e;case ss:f=16,o=null;break e}throw Error(bt(130,e==null?e:typeof e,""))}return t=Fi(f,n,t,a),t.elementType=e,t.type=o,t.lanes=l,t}function na(e,t,n,o){return e=Fi(7,e,o,t),e.lanes=n,e}function am(e,t,n,o){return e=Fi(22,e,o,t),e.elementType=R1,e.lanes=n,e.stateNode={isHidden:!1},e}function bg(e,t,n){return e=Fi(6,e,null,t),e.lanes=n,e}function xg(e,t,n){return t=Fi(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function tS(e,t,n,o,a){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=rg(0),this.expirationTimes=rg(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=rg(0),this.identifierPrefix=o,this.onRecoverableError=a,this.mutableSourceEagerHydrationData=null}function f0(e,t,n,o,a,l,f,_,h){return e=new tS(e,t,n,_,h),t===1?(t=1,l===!0&&(t|=8)):t=0,l=Fi(3,null,null,t),e.current=l,l.stateNode=e,l.memoizedState={element:o,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},Q_(l),e}function rS(e,t,n){var o=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(I2)}catch(e){console.error(e)}}I2(),I1.exports=wi;var aS=I1.exports,F2,s1=aS;F2=s1.createRoot,s1.hydrateRoot;var z2={exports:{}},lS="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED",uS=lS,cS=uS;function O2(){}function D2(){}D2.resetWarningCache=O2;var dS=function(){function e(o,a,l,f,_,h){if(h!==cS){var g=new Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types");throw g.name="Invariant Violation",g}}e.isRequired=e;function t(){return e}var n={array:e,bigint:e,bool:e,func:e,number:e,object:e,string:e,symbol:e,any:e,arrayOf:t,element:e,elementType:e,instanceOf:t,node:e,objectOf:t,oneOf:t,oneOfType:t,shape:t,exact:t,checkPropTypes:D2,resetWarningCache:O2};return n.PropTypes=n,n};z2.exports=dS();var fS=z2.exports;const Ur=b_(fS);function iu(e,t,n,o){function a(l){return l instanceof n?l:new n(function(f){f(l)})}return new(n||(n=Promise))(function(l,f){function _(M){try{g(o.next(M))}catch(w){f(w)}}function h(M){try{g(o.throw(M))}catch(w){f(w)}}function g(M){M.done?l(M.value):a(M.value).then(_,h)}g((o=o.apply(e,t||[])).next())})}function ou(e,t){var n={label:0,sent:function(){if(l[0]&1)throw l[1];return l[1]},trys:[],ops:[]},o,a,l,f=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return f.next=_(0),f.throw=_(1),f.return=_(2),typeof Symbol=="function"&&(f[Symbol.iterator]=function(){return this}),f;function _(g){return function(M){return h([g,M])}}function h(g){if(o)throw new TypeError("Generator is already executing.");for(;f&&(f=0,g[0]&&(n=0)),n;)try{if(o=1,a&&(l=g[0]&2?a.return:g[0]?a.throw||((l=a.return)&&l.call(a),0):a.next)&&!(l=l.call(a,g[1])).done)return l;switch(a=0,l&&(g=[g[0]&2,l.value]),g[0]){case 0:case 1:l=g;break;case 4:return n.label++,{value:g[1],done:!1};case 5:n.label++,a=g[1],g=[0];continue;case 7:g=n.ops.pop(),n.trys.pop();continue;default:if(l=n.trys,!(l=l.length>0&&l[l.length-1])&&(g[0]===6||g[0]===2)){n=0;continue}if(g[0]===3&&(!l||g[1]>l[0]&&g[1]0)&&!(a=o.next()).done;)l.push(a.value)}catch(_){f={error:_}}finally{try{a&&!a.done&&(n=o.return)&&n.call(o)}finally{if(f)throw f.error}}return l}function l1(e,t,n){if(n||arguments.length===2)for(var o=0,a=t.length,l;o0?o:e.name,writable:!1,configurable:!1,enumerable:!0})}return n}function hS(e){var t=e.name,n=t&&t.lastIndexOf(".")!==-1;if(n&&!e.type){var o=t.split(".").pop().toLowerCase(),a=pS.get(o);a&&Object.defineProperty(e,"type",{value:a,writable:!1,configurable:!1,enumerable:!0})}return e}var mS=[".DS_Store","Thumbs.db"];function gS(e){return iu(this,void 0,void 0,function(){return ou(this,function(t){return Hh(e)&&_S(e.dataTransfer)?[2,bS(e.dataTransfer,e.type)]:yS(e)?[2,wS(e)]:Array.isArray(e)&&e.every(function(n){return"getFile"in n&&typeof n.getFile=="function"})?[2,vS(e)]:[2,[]]})})}function _S(e){return Hh(e)}function yS(e){return Hh(e)&&Hh(e.target)}function Hh(e){return typeof e=="object"&&e!==null}function wS(e){return g_(e.target.files).map(function(t){return Jf(t)})}function vS(e){return iu(this,void 0,void 0,function(){var t;return ou(this,function(n){switch(n.label){case 0:return[4,Promise.all(e.map(function(o){return o.getFile()}))];case 1:return t=n.sent(),[2,t.map(function(o){return Jf(o)})]}})})}function bS(e,t){return iu(this,void 0,void 0,function(){var n,o;return ou(this,function(a){switch(a.label){case 0:return e.items?(n=g_(e.items).filter(function(l){return l.kind==="file"}),t!=="drop"?[2,n]:[4,Promise.all(n.map(xS))]):[3,2];case 1:return o=a.sent(),[2,u1(L2(o))];case 2:return[2,u1(g_(e.files).map(function(l){return Jf(l)}))]}})})}function u1(e){return e.filter(function(t){return mS.indexOf(t.name)===-1})}function g_(e){if(e===null)return[];for(var t=[],n=0;ne.length)&&(t=e.length);for(var n=0,o=new Array(t);nn)return[!1,h1(n)];if(e.sizen)return[!1,h1(n)]}return[!0,null]}function Zs(e){return e!=null}function RS(e){var t=e.files,n=e.accept,o=e.minSize,a=e.maxSize,l=e.multiple,f=e.maxFiles,_=e.validator;return!l&&t.length>1||l&&f>=1&&t.length>f?!1:t.every(function(h){var g=j2(h,n),M=Hf(g,1),w=M[0],C=U2(h,o,a),k=Hf(C,1),z=k[0],S=_?_(h):null;return w&&z&&!S})}function Kh(e){return typeof e.isPropagationStopped=="function"?e.isPropagationStopped():typeof e.cancelBubble<"u"?e.cancelBubble:!1}function lh(e){return e.dataTransfer?Array.prototype.some.call(e.dataTransfer.types,function(t){return t==="Files"||t==="application/x-moz-file"}):!!e.target&&!!e.target.files}function g1(e){e.preventDefault()}function BS(e){return e.indexOf("MSIE")!==-1||e.indexOf("Trident/")!==-1}function NS(e){return e.indexOf("Edge/")!==-1}function jS(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:window.navigator.userAgent;return BS(e)||NS(e)}function oo(){for(var e=arguments.length,t=new Array(e),n=0;n1?a-1:0),f=1;fe.length)&&(t=e.length);for(var n=0,o=new Array(t);n=0)&&Object.prototype.propertyIsEnumerable.call(e,o)&&(n[o]=e[o])}return n}function iE(e,t){if(e==null)return{};var n={},o=Object.keys(e),a,l;for(l=0;l=0)&&(n[a]=e[a]);return n}var g0=hr.forwardRef(function(e,t){var n=e.children,o=Qh(e,HS),a=H2(o),l=a.open,f=Qh(a,KS);return hr.useImperativeHandle(t,function(){return{open:l}},[l]),XM.createElement(hr.Fragment,null,n(tn(tn({},f),{},{open:l})))});g0.displayName="Dropzone";var q2={disabled:!1,getFilesFromEvent:gS,maxSize:1/0,minSize:0,multiple:!0,maxFiles:0,preventDropOnDocument:!0,noClick:!1,noKeyboard:!1,noDrag:!1,noDragEventsBubbling:!1,validator:null,useFsAccessApi:!0,autoFocus:!1};g0.defaultProps=q2;g0.propTypes={children:Ur.func,accept:Ur.objectOf(Ur.arrayOf(Ur.string)),multiple:Ur.bool,preventDropOnDocument:Ur.bool,noClick:Ur.bool,noKeyboard:Ur.bool,noDrag:Ur.bool,noDragEventsBubbling:Ur.bool,minSize:Ur.number,maxSize:Ur.number,maxFiles:Ur.number,disabled:Ur.bool,getFilesFromEvent:Ur.func,onFileDialogCancel:Ur.func,onFileDialogOpen:Ur.func,useFsAccessApi:Ur.bool,autoFocus:Ur.bool,onDragEnter:Ur.func,onDragLeave:Ur.func,onDragOver:Ur.func,onDrop:Ur.func,onDropAccepted:Ur.func,onDropRejected:Ur.func,onError:Ur.func,validator:Ur.func};var v_={isFocused:!1,isFileDialogActive:!1,isDragActive:!1,isDragAccept:!1,isDragReject:!1,acceptedFiles:[],fileRejections:[]};function H2(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=tn(tn({},q2),e),n=t.accept,o=t.disabled,a=t.getFilesFromEvent,l=t.maxSize,f=t.minSize,_=t.multiple,h=t.maxFiles,g=t.onDragEnter,M=t.onDragLeave,w=t.onDragOver,C=t.onDrop,k=t.onDropAccepted,z=t.onDropRejected,S=t.onFileDialogCancel,P=t.onFileDialogOpen,y=t.useFsAccessApi,x=t.autoFocus,I=t.preventDropOnDocument,U=t.noClick,O=t.noKeyboard,N=t.noDrag,j=t.noDragEventsBubbling,D=t.onError,Y=t.validator,de=hr.useMemo(function(){return WS(n)},[n]),Ce=hr.useMemo(function(){return VS(n)},[n]),ee=hr.useMemo(function(){return typeof P=="function"?P:y1},[P]),ye=hr.useMemo(function(){return typeof S=="function"?S:y1},[S]),R=hr.useRef(null),Me=hr.useRef(null),Qe=hr.useReducer(oE,v_),ge=Mg(Qe,2),Q=ge[0],ae=ge[1],Se=Q.isFocused,X=Q.isFileDialogActive,me=hr.useRef(typeof window<"u"&&window.isSecureContext&&y&&US()),Ke=function(){!me.current&&X&&setTimeout(function(){if(Me.current){var ke=Me.current.files;ke.length||(ae({type:"closeDialog"}),ye())}},300)};hr.useEffect(function(){return window.addEventListener("focus",Ke,!1),function(){window.removeEventListener("focus",Ke,!1)}},[Me,X,ye,me]);var De=hr.useRef([]),Be=function(ke){R.current&&R.current.contains(ke.target)||(ke.preventDefault(),De.current=[])};hr.useEffect(function(){return I&&(document.addEventListener("dragover",g1,!1),document.addEventListener("drop",Be,!1)),function(){I&&(document.removeEventListener("dragover",g1),document.removeEventListener("drop",Be))}},[R,I]),hr.useEffect(function(){return!o&&x&&R.current&&R.current.focus(),function(){}},[R,x,o]);var We=hr.useCallback(function(le){D?D(le):console.error(le)},[D]),ot=hr.useCallback(function(le){le.preventDefault(),le.persist(),B(le),De.current=[].concat(YS(De.current),[le.target]),lh(le)&&Promise.resolve(a(le)).then(function(ke){if(!(Kh(le)&&!j)){var Ne=ke.length,ut=Ne>0&&RS({files:ke,accept:de,minSize:f,maxSize:l,multiple:_,maxFiles:h,validator:Y}),Je=Ne>0&&!ut;ae({isDragAccept:ut,isDragReject:Je,isDragActive:!0,type:"setDraggedFiles"}),g&&g(le)}}).catch(function(ke){return We(ke)})},[a,g,We,j,de,f,l,_,h,Y]),dt=hr.useCallback(function(le){le.preventDefault(),le.persist(),B(le);var ke=lh(le);if(ke&&le.dataTransfer)try{le.dataTransfer.dropEffect="copy"}catch{}return ke&&w&&w(le),!1},[w,j]),Ge=hr.useCallback(function(le){le.preventDefault(),le.persist(),B(le);var ke=De.current.filter(function(ut){return R.current&&R.current.contains(ut)}),Ne=ke.indexOf(le.target);Ne!==-1&&ke.splice(Ne,1),De.current=ke,!(ke.length>0)&&(ae({type:"setDraggedFiles",isDragActive:!1,isDragAccept:!1,isDragReject:!1}),lh(le)&&M&&M(le))},[R,M,j]),Te=hr.useCallback(function(le,ke){var Ne=[],ut=[];le.forEach(function(Je){var Ve=j2(Je,de),Z=Mg(Ve,2),ve=Z[0],Re=Z[1],He=U2(Je,f,l),Xe=Mg(He,2),rt=Xe[0],ft=Xe[1],ht=Y?Y(Je):null;if(ve&&rt&&!ht)Ne.push(Je);else{var Mt=[Re,ft];ht&&(Mt=Mt.concat(ht)),ut.push({file:Je,errors:Mt.filter(function(wt){return wt})})}}),(!_&&Ne.length>1||_&&h>=1&&Ne.length>h)&&(Ne.forEach(function(Je){ut.push({file:Je,errors:[LS]})}),Ne.splice(0)),ae({acceptedFiles:Ne,fileRejections:ut,type:"setFiles"}),C&&C(Ne,ut,ke),ut.length>0&&z&&z(ut,ke),Ne.length>0&&k&&k(Ne,ke)},[ae,_,de,f,l,h,C,k,z,Y]),je=hr.useCallback(function(le){le.preventDefault(),le.persist(),B(le),De.current=[],lh(le)&&Promise.resolve(a(le)).then(function(ke){Kh(le)&&!j||Te(ke,le)}).catch(function(ke){return We(ke)}),ae({type:"reset"})},[a,Te,We,j]),Ye=hr.useCallback(function(){if(me.current){ae({type:"openDialog"}),ee();var le={multiple:_,types:Ce};window.showOpenFilePicker(le).then(function(ke){return a(ke)}).then(function(ke){Te(ke,null),ae({type:"closeDialog"})}).catch(function(ke){GS(ke)?(ye(ke),ae({type:"closeDialog"})):qS(ke)?(me.current=!1,Me.current?(Me.current.value=null,Me.current.click()):We(new Error("Cannot open the file picker because the https://developer.mozilla.org/en-US/docs/Web/API/File_System_Access_API is not supported and no was provided."))):We(ke)});return}Me.current&&(ae({type:"openDialog"}),ee(),Me.current.value=null,Me.current.click())},[ae,ee,ye,y,Te,We,Ce,_]),tt=hr.useCallback(function(le){!R.current||!R.current.isEqualNode(le.target)||(le.key===" "||le.key==="Enter"||le.keyCode===32||le.keyCode===13)&&(le.preventDefault(),Ye())},[R,Ye]),A=hr.useCallback(function(){ae({type:"focus"})},[]),Ae=hr.useCallback(function(){ae({type:"blur"})},[]),$e=hr.useCallback(function(){U||(jS()?setTimeout(Ye,0):Ye())},[U,Ye]),se=function(ke){return o?null:ke},te=function(ke){return O?null:se(ke)},we=function(ke){return N?null:se(ke)},B=function(ke){j&&ke.stopPropagation()},J=hr.useMemo(function(){return function(){var le=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},ke=le.refKey,Ne=ke===void 0?"ref":ke,ut=le.role,Je=le.onKeyDown,Ve=le.onFocus,Z=le.onBlur,ve=le.onClick,Re=le.onDragEnter,He=le.onDragOver,Xe=le.onDragLeave,rt=le.onDrop,ft=Qh(le,QS);return tn(tn(w_({onKeyDown:te(oo(Je,tt)),onFocus:te(oo(Ve,A)),onBlur:te(oo(Z,Ae)),onClick:se(oo(ve,$e)),onDragEnter:we(oo(Re,ot)),onDragOver:we(oo(He,dt)),onDragLeave:we(oo(Xe,Ge)),onDrop:we(oo(rt,je)),role:typeof ut=="string"&&ut!==""?ut:"presentation"},Ne,R),!o&&!O?{tabIndex:0}:{}),ft)}},[R,tt,A,Ae,$e,ot,dt,Ge,je,O,N,o]),L=hr.useCallback(function(le){le.stopPropagation()},[]),ue=hr.useMemo(function(){return function(){var le=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},ke=le.refKey,Ne=ke===void 0?"ref":ke,ut=le.onChange,Je=le.onClick,Ve=Qh(le,XS),Z=w_({accept:de,multiple:_,type:"file",style:{display:"none"},onChange:se(oo(ut,je)),onClick:se(oo(Je,L)),tabIndex:-1},Ne,Me);return tn(tn({},Z),Ve)}},[Me,n,_,je,o]);return tn(tn({},Q),{},{isFocused:Se&&!o,getRootProps:J,getInputProps:ue,rootRef:R,inputRef:Me,open:se(Ye)})}function oE(e,t){switch(t.type){case"focus":return tn(tn({},e),{},{isFocused:!0});case"blur":return tn(tn({},e),{},{isFocused:!1});case"openDialog":return tn(tn({},v_),{},{isFileDialogActive:!0});case"closeDialog":return tn(tn({},e),{},{isFileDialogActive:!1});case"setDraggedFiles":return tn(tn({},e),{},{isDragActive:t.isDragActive,isDragAccept:t.isDragAccept,isDragReject:t.isDragReject});case"setFiles":return tn(tn({},e),{},{acceptedFiles:t.acceptedFiles,fileRejections:t.fileRejections});case"reset":return tn({},v_);default:return e}}function y1(){}var Mo={},sE={"./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm":(e,t,n)=>{e.exports=n.p+"ort-wasm-simd-threaded.jsep.wasm"},"?2ce3":()=>{},"?7a2c":()=>{},"?a42a":()=>{},"?2b25":()=>{},"?569f":()=>{},"?3f59":()=>{},"?154a":()=>{},"./node_modules/@huggingface/jinja/dist/index.js":(e,t,n)=>{n.r(t),n.d(t,{Environment:()=>Ae,Interpreter:()=>$e,Template:()=>we,parse:()=>Se,tokenize:()=>w});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"}),a=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}),l=class{constructor(B,J){this.value=B,this.type=J}};function f(B){return/\w/.test(B)}function _(B){return/[0-9]/.test(B)}var h=[["{%",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]],g=new Map([["n",` +`],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function M(B,J={}){return B.endsWith(` +`)&&(B=B.slice(0,-1)),B=B.replace(/{#.*?#}/gs,"{##}"),J.lstrip_blocks&&(B=B.replace(/^[ \t]*({[#%])/gm,"$1")),J.trim_blocks&&(B=B.replace(/([#%]})\n/g,"$1")),B.replace(/{##}/g,"").replace(/-%}\s*/g,"%}").replace(/\s*{%-/g,"{%").replace(/-}}\s*/g,"}}").replace(/\s*{{-/g,"{{")}function w(B,J={}){var Ne,ut,Je;const L=[],ue=M(B,J);let le=0;const ke=Ve=>{let Z="";for(;Ve(ue[le]);){if(ue[le]==="\\"){if(++le,le>=ue.length)throw new SyntaxError("Unexpected end of input");const ve=ue[le++],Re=g.get(ve);if(Re===void 0)throw new SyntaxError(`Unexpected escaped character: ${ve}`);Z+=Re;continue}if(Z+=ue[le++],le>=ue.length)throw new SyntaxError("Unexpected end of input")}return Z};e:for(;le0){L.push(new l(ve,o.Text));continue}}ke(ve=>/\s/.test(ve));const Z=ue[le];if(Z==="-"||Z==="+"){const ve=(ut=L.at(-1))==null?void 0:ut.type;if(ve===o.Text||ve===void 0)throw new SyntaxError(`Unexpected character: ${Z}`);switch(ve){case o.Identifier:case o.NumericLiteral:case o.BooleanLiteral:case o.StringLiteral:case o.CloseParen:case o.CloseSquareBracket:break;default:{++le;const Re=ke(_);L.push(new l(`${Z}${Re}`,Re.length>0?o.NumericLiteral:o.UnaryOperator));continue}}}for(const[ve,Re]of h)if(ue.slice(le,le+ve.length)===ve){L.push(new l(ve,Re)),le+=ve.length;continue e}if(Z==="'"||Z==='"'){++le;const ve=ke(Re=>Re!==Z);L.push(new l(ve,o.StringLiteral)),++le;continue}if(_(Z)){const ve=ke(_);L.push(new l(ve,o.NumericLiteral));continue}if(f(Z)){const ve=ke(f),Re=Object.hasOwn(a,ve)?a[ve]:o.Identifier;Re===o.In&&((Je=L.at(-1))==null?void 0:Je.type)===o.Not?(L.pop(),L.push(new l("not in",o.NotIn))):L.push(new l(ve,Re));continue}throw new SyntaxError(`Unexpected character: ${Z}`)}return L}var C=class{constructor(){qe(this,"type","Statement")}},k=class extends C{constructor(J){super();qe(this,"type","Program");this.body=J}},z=class extends C{constructor(J,L,ue){super();qe(this,"type","If");this.test=J,this.body=L,this.alternate=ue}},S=class extends C{constructor(J,L,ue,le){super();qe(this,"type","For");this.loopvar=J,this.iterable=L,this.body=ue,this.defaultBlock=le}},P=class extends C{constructor(J,L){super();qe(this,"type","Set");this.assignee=J,this.value=L}},y=class extends C{constructor(J,L,ue){super();qe(this,"type","Macro");this.name=J,this.args=L,this.body=ue}},x=class extends C{constructor(){super(...arguments);qe(this,"type","Expression")}},I=class extends x{constructor(J,L,ue){super();qe(this,"type","MemberExpression");this.object=J,this.property=L,this.computed=ue}},U=class extends x{constructor(J,L){super();qe(this,"type","CallExpression");this.callee=J,this.args=L}},O=class extends x{constructor(J){super();qe(this,"type","Identifier");this.value=J}},N=class extends x{constructor(J){super();qe(this,"type","Literal");this.value=J}},j=class extends N{constructor(){super(...arguments);qe(this,"type","NumericLiteral")}},D=class extends N{constructor(){super(...arguments);qe(this,"type","StringLiteral")}},Y=class extends N{constructor(){super(...arguments);qe(this,"type","BooleanLiteral")}},de=class extends N{constructor(){super(...arguments);qe(this,"type","ArrayLiteral")}},Ce=class extends N{constructor(){super(...arguments);qe(this,"type","TupleLiteral")}},ee=class extends N{constructor(){super(...arguments);qe(this,"type","ObjectLiteral")}},ye=class extends x{constructor(J,L,ue){super();qe(this,"type","BinaryExpression");this.operator=J,this.left=L,this.right=ue}},R=class extends x{constructor(J,L){super();qe(this,"type","FilterExpression");this.operand=J,this.filter=L}},Me=class extends x{constructor(J,L){super();qe(this,"type","SelectExpression");this.iterable=J,this.test=L}},Qe=class extends x{constructor(J,L,ue){super();qe(this,"type","TestExpression");this.operand=J,this.negate=L,this.test=ue}},ge=class extends x{constructor(J,L){super();qe(this,"type","UnaryExpression");this.operator=J,this.argument=L}},Q=class extends x{constructor(J=void 0,L=void 0,ue=void 0){super();qe(this,"type","SliceExpression");this.start=J,this.stop=L,this.step=ue}},ae=class extends x{constructor(J,L){super();qe(this,"type","KeywordArgumentExpression");this.key=J,this.value=L}};function Se(B){const J=new k([]);let L=0;function ue(mt,Pt){const Bt=B[L++];if(!Bt||Bt.type!==mt)throw new Error(`Parser Error: ${Pt}. ${Bt.type} !== ${mt}.`);return Bt}function le(){switch(B[L].type){case o.Text:return ut();case o.OpenStatement:return Je();case o.OpenExpression:return Ve();default:throw new SyntaxError(`Unexpected token type: ${B[L].type}`)}}function ke(...mt){return L+mt.length<=B.length&&mt.some((Pt,Bt)=>Pt!==B[L+Bt].type)}function Ne(...mt){return L+mt.length<=B.length&&mt.every((Pt,Bt)=>Pt===B[L+Bt].type)}function ut(){return new D(ue(o.Text,"Expected text token").value)}function Je(){ue(o.OpenStatement,"Expected opening statement token");let mt;switch(B[L].type){case o.Set:++L,mt=Z(),ue(o.CloseStatement,"Expected closing statement token");break;case o.If:++L,mt=ve(),ue(o.OpenStatement,"Expected {% token"),ue(o.EndIf,"Expected endif token"),ue(o.CloseStatement,"Expected %} token");break;case o.Macro:++L,mt=Re(),ue(o.OpenStatement,"Expected {% token"),ue(o.EndMacro,"Expected endmacro token"),ue(o.CloseStatement,"Expected %} token");break;case o.For:++L,mt=Xe(),ue(o.OpenStatement,"Expected {% token"),ue(o.EndFor,"Expected endfor token"),ue(o.CloseStatement,"Expected %} token");break;default:throw new SyntaxError(`Unknown statement type: ${B[L].type}`)}return mt}function Ve(){ue(o.OpenExpression,"Expected opening expression token");const mt=rt();return ue(o.CloseExpression,"Expected closing expression token"),mt}function Z(){const mt=rt();if(Ne(o.Equals)){++L;const Pt=Z();return new P(mt,Pt)}return mt}function ve(){var sn,Li,bi,Nr,mn,Wr,ci,Fr;const mt=rt();ue(o.CloseStatement,"Expected closing statement token");const Pt=[],Bt=[];for(;!(((sn=B[L])==null?void 0:sn.type)===o.OpenStatement&&(((Li=B[L+1])==null?void 0:Li.type)===o.ElseIf||((bi=B[L+1])==null?void 0:bi.type)===o.Else||((Nr=B[L+1])==null?void 0:Nr.type)===o.EndIf));)Pt.push(le());if(((mn=B[L])==null?void 0:mn.type)===o.OpenStatement&&((Wr=B[L+1])==null?void 0:Wr.type)!==o.EndIf)if(++L,Ne(o.ElseIf))ue(o.ElseIf,"Expected elseif token"),Bt.push(ve());else for(ue(o.Else,"Expected else token"),ue(o.CloseStatement,"Expected closing statement token");!(((ci=B[L])==null?void 0:ci.type)===o.OpenStatement&&((Fr=B[L+1])==null?void 0:Fr.type)===o.EndIf);)Bt.push(le());return new z(mt,Pt,Bt)}function Re(){const mt=Cr();if(mt.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");const Pt=Ut();ue(o.CloseStatement,"Expected closing statement token");const Bt=[];for(;ke(o.OpenStatement,o.EndMacro);)Bt.push(le());return new y(mt,Pt,Bt)}function He(mt=!1){const Pt=mt?Cr:rt,Bt=[Pt()],sn=Ne(o.Comma);for(;sn&&(++L,Bt.push(Pt()),!!Ne(o.Comma)););return sn?new Ce(Bt):Bt[0]}function Xe(){const mt=He(!0);if(!(mt instanceof O||mt instanceof Ce))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${mt.type} instead`);ue(o.In,"Expected `in` keyword following loop variable");const Pt=rt();ue(o.CloseStatement,"Expected closing statement token");const Bt=[];for(;ke(o.OpenStatement,o.EndFor)&&ke(o.OpenStatement,o.Else);)Bt.push(le());const sn=[];if(Ne(o.OpenStatement,o.Else))for(++L,++L,ue(o.CloseStatement,"Expected closing statement token");ke(o.OpenStatement,o.EndFor);)sn.push(le());return new S(mt,Pt,Bt,sn)}function rt(){return ft()}function ft(){const mt=ht();if(Ne(o.If)){++L;const Pt=ht();if(Ne(o.Else)){++L;const Bt=ht();return new z(Pt,[mt],[Bt])}else return new Me(mt,Pt)}return mt}function ht(){let mt=Mt();for(;Ne(o.Or);){const Pt=B[L];++L;const Bt=Mt();mt=new ye(Pt,mt,Bt)}return mt}function Mt(){let mt=wt();for(;Ne(o.And);){const Pt=B[L];++L;const Bt=wt();mt=new ye(Pt,mt,Bt)}return mt}function wt(){let mt;for(;Ne(o.Not);){const Pt=B[L];++L;const Bt=wt();mt=new ge(Pt,Bt)}return mt??St()}function St(){let mt=Rt();for(;Ne(o.ComparisonBinaryOperator)||Ne(o.In)||Ne(o.NotIn);){const Pt=B[L];++L;const Bt=Rt();mt=new ye(Pt,mt,Bt)}return mt}function Rt(){let mt=qt();for(;Ne(o.AdditiveBinaryOperator);){const Pt=B[L];++L;const Bt=qt();mt=new ye(Pt,mt,Bt)}return mt}function at(){const mt=Jt();return Ne(o.OpenParen)?Ot(mt):mt}function Ot(mt){let Pt=new U(mt,Ut());return Ne(o.OpenParen)&&(Pt=Ot(Pt)),Pt}function Ut(){ue(o.OpenParen,"Expected opening parenthesis for arguments list");const mt=Kt();return ue(o.CloseParen,"Expected closing parenthesis for arguments list"),mt}function Kt(){const mt=[];for(;!Ne(o.CloseParen);){let Pt=rt();if(Ne(o.Equals)){if(++L,!(Pt instanceof O))throw new SyntaxError("Expected identifier for keyword argument");const Bt=rt();Pt=new ae(Pt,Bt)}mt.push(Pt),Ne(o.Comma)&&++L}return mt}function Qt(){const mt=[];let Pt=!1;for(;!Ne(o.CloseSquareBracket);)Ne(o.Colon)?(mt.push(void 0),++L,Pt=!0):(mt.push(rt()),Ne(o.Colon)&&(++L,Pt=!0));if(mt.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(Pt){if(mt.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new Q(...mt)}return mt[0]}function Jt(){let mt=Cr();for(;Ne(o.Dot)||Ne(o.OpenSquareBracket);){const Pt=B[L];++L;let Bt;const sn=Pt.type!==o.Dot;if(sn)Bt=Qt(),ue(o.CloseSquareBracket,"Expected closing square bracket");else if(Bt=Cr(),Bt.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");mt=new I(mt,Bt,sn)}return mt}function qt(){let mt=Er();for(;Ne(o.MultiplicativeBinaryOperator);){const Pt=B[L];++L;const Bt=Er();mt=new ye(Pt,mt,Bt)}return mt}function Er(){let mt=Qr();for(;Ne(o.Is);){++L;const Pt=Ne(o.Not);Pt&&++L;let Bt=Cr();if(Bt instanceof Y&&(Bt=new O(Bt.value.toString())),!(Bt instanceof O))throw new SyntaxError("Expected identifier for the test");mt=new Qe(mt,Pt,Bt)}return mt}function Qr(){let mt=at();for(;Ne(o.Pipe);){++L;let Pt=Cr();if(!(Pt instanceof O))throw new SyntaxError("Expected identifier for the filter");Ne(o.OpenParen)&&(Pt=Ot(Pt)),mt=new R(mt,Pt)}return mt}function Cr(){const mt=B[L];switch(mt.type){case o.NumericLiteral:return++L,new j(Number(mt.value));case o.StringLiteral:return++L,new D(mt.value);case o.BooleanLiteral:return++L,new Y(mt.value.toLowerCase()==="true");case o.Identifier:return++L,new O(mt.value);case o.OpenParen:{++L;const Pt=He();if(B[L].type!==o.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${B[L].type} instead`);return++L,Pt}case o.OpenSquareBracket:{++L;const Pt=[];for(;!Ne(o.CloseSquareBracket);)Pt.push(rt()),Ne(o.Comma)&&++L;return++L,new de(Pt)}case o.OpenCurlyBracket:{++L;const Pt=new Map;for(;!Ne(o.CloseCurlyBracket);){const Bt=rt();ue(o.Colon,"Expected colon between key and value in object literal");const sn=rt();Pt.set(Bt,sn),Ne(o.Comma)&&++L}return++L,new ee(Pt)}default:throw new SyntaxError(`Unexpected token: ${mt.type}`)}}for(;L=0?(J=(J??(J=0))<0?Math.max(B.length+J,0):Math.min(J,B.length),L=(L??(L=B.length))<0?Math.max(B.length+L,0):Math.min(L,B.length)):(J=(J??(J=B.length-1))<0?Math.max(B.length+J,-1):Math.min(J,B.length-1),L=(L??(L=-1))<-1?Math.max(B.length+L,-1):Math.min(L,B.length-1));const ke=[];for(let Ne=J;le*NeJ.toUpperCase())}var De=class{constructor(B=void 0){qe(this,"type","RuntimeValue");qe(this,"value");qe(this,"builtins",new Map);this.value=B}__bool__(){return new ot(!!this.value)}},Be=class extends De{constructor(){super(...arguments);qe(this,"type","NumericValue")}},We=class extends De{constructor(){super(...arguments);qe(this,"type","StringValue");qe(this,"builtins",new Map([["upper",new Ye(()=>new We(this.value.toUpperCase()))],["lower",new Ye(()=>new We(this.value.toLowerCase()))],["strip",new Ye(()=>new We(this.value.trim()))],["title",new Ye(()=>new We(Ke(this.value)))],["length",new Be(this.value.length)]]))}},ot=class extends De{constructor(){super(...arguments);qe(this,"type","BooleanValue")}},dt=class extends De{constructor(){super(...arguments);qe(this,"type","ObjectValue");qe(this,"builtins",new Map([["get",new Ye(([J,L])=>{if(!(J instanceof We))throw new Error(`Object key must be a string: got ${J.type}`);return this.value.get(J.value)??L??new tt})],["items",new Ye(()=>new Te(Array.from(this.value.entries()).map(([J,L])=>new Te([new We(J),L]))))]]))}__bool__(){return new ot(this.value.size>0)}},Ge=class extends dt{constructor(){super(...arguments);qe(this,"type","KeywordArgumentsValue")}},Te=class extends De{constructor(){super(...arguments);qe(this,"type","ArrayValue");qe(this,"builtins",new Map([["length",new Be(this.value.length)]]))}__bool__(){return new ot(this.value.length>0)}},je=class extends Te{constructor(){super(...arguments);qe(this,"type","TupleValue")}},Ye=class extends De{constructor(){super(...arguments);qe(this,"type","FunctionValue")}},tt=class extends De{constructor(){super(...arguments);qe(this,"type","NullValue")}},A=class extends De{constructor(){super(...arguments);qe(this,"type","UndefinedValue")}},Ae=class{constructor(B){qe(this,"variables",new Map([["namespace",new Ye(B=>{if(B.length===0)return new dt(new Map);if(B.length!==1||!(B[0]instanceof dt))throw new Error("`namespace` expects either zero arguments or a single object argument");return B[0]})]]));qe(this,"tests",new Map([["boolean",B=>B.type==="BooleanValue"],["callable",B=>B instanceof Ye],["odd",B=>{if(B.type!=="NumericValue")throw new Error(`Cannot apply test "odd" to type: ${B.type}`);return B.value%2!==0}],["even",B=>{if(B.type!=="NumericValue")throw new Error(`Cannot apply test "even" to type: ${B.type}`);return B.value%2===0}],["false",B=>B.type==="BooleanValue"&&!B.value],["true",B=>B.type==="BooleanValue"&&B.value],["string",B=>B.type==="StringValue"],["number",B=>B.type==="NumericValue"],["integer",B=>B.type==="NumericValue"&&Number.isInteger(B.value)],["iterable",B=>B instanceof Te||B instanceof We],["lower",B=>{const J=B.value;return B.type==="StringValue"&&J===J.toLowerCase()}],["upper",B=>{const J=B.value;return B.type==="StringValue"&&J===J.toUpperCase()}],["none",B=>B.type==="NullValue"],["defined",B=>B.type!=="UndefinedValue"],["undefined",B=>B.type==="UndefinedValue"],["equalto",(B,J)=>B.value===J.value],["eq",(B,J)=>B.value===J.value]]));this.parent=B}set(B,J){return this.declareVariable(B,se(J))}declareVariable(B,J){if(this.variables.has(B))throw new SyntaxError(`Variable already declared: ${B}`);return this.variables.set(B,J),J}setVariable(B,J){return this.variables.set(B,J),J}resolve(B){if(this.variables.has(B))return this;if(this.parent)return this.parent.resolve(B);throw new Error(`Unknown variable: ${B}`)}lookupVariable(B){try{return this.resolve(B).variables.get(B)??new A}catch{return new A}}},$e=class{constructor(B){qe(this,"global");this.global=B??new Ae}run(B){return this.evaluate(B,this.global)}evaluateBinaryExpression(B,J){const L=this.evaluate(B.left,J);switch(B.operator.value){case"and":return L.__bool__().value?this.evaluate(B.right,J):L;case"or":return L.__bool__().value?L:this.evaluate(B.right,J)}const ue=this.evaluate(B.right,J);switch(B.operator.value){case"==":return new ot(L.value==ue.value);case"!=":return new ot(L.value!=ue.value)}if(L instanceof A||ue instanceof A)throw new Error("Cannot perform operation on undefined values");if(L instanceof tt||ue instanceof tt)throw new Error("Cannot perform operation on null values");if(L instanceof Be&&ue instanceof Be)switch(B.operator.value){case"+":return new Be(L.value+ue.value);case"-":return new Be(L.value-ue.value);case"*":return new Be(L.value*ue.value);case"/":return new Be(L.value/ue.value);case"%":return new Be(L.value%ue.value);case"<":return new ot(L.value":return new ot(L.value>ue.value);case">=":return new ot(L.value>=ue.value);case"<=":return new ot(L.value<=ue.value)}else if(L instanceof Te&&ue instanceof Te)switch(B.operator.value){case"+":return new Te(L.value.concat(ue.value))}else if(ue instanceof Te){const le=ue.value.find(ke=>ke.value===L.value)!==void 0;switch(B.operator.value){case"in":return new ot(le);case"not in":return new ot(!le)}}if(L instanceof We||ue instanceof We)switch(B.operator.value){case"+":return new We(L.value.toString()+ue.value.toString())}if(L instanceof We&&ue instanceof We)switch(B.operator.value){case"in":return new ot(ue.value.includes(L.value));case"not in":return new ot(!ue.value.includes(L.value))}if(L instanceof We&&ue instanceof dt)switch(B.operator.value){case"in":return new ot(ue.value.has(L.value));case"not in":return new ot(!ue.value.has(L.value))}throw new SyntaxError(`Unknown operator "${B.operator.value}" between ${L.type} and ${ue.type}`)}evaluateArguments(B,J){const L=[],ue=new Map;for(const le of B)if(le.type==="KeywordArgumentExpression"){const ke=le;ue.set(ke.key.value,this.evaluate(ke.value,J))}else{if(ue.size>0)throw new Error("Positional arguments must come before keyword arguments");L.push(this.evaluate(le,J))}return[L,ue]}evaluateFilterExpression(B,J){const L=this.evaluate(B.operand,J);if(B.filter.type==="Identifier"){const ue=B.filter;if(ue.value==="tojson")return new We(te(L));if(L instanceof Te)switch(ue.value){case"list":return L;case"first":return L.value[0];case"last":return L.value[L.value.length-1];case"length":return new Be(L.value.length);case"reverse":return new Te(L.value.reverse());case"sort":return new Te(L.value.sort((le,ke)=>{if(le.type!==ke.type)throw new Error(`Cannot compare different types: ${le.type} and ${ke.type}`);switch(le.type){case"NumericValue":return le.value-ke.value;case"StringValue":return le.value.localeCompare(ke.value);default:throw new Error(`Cannot compare type: ${le.type}`)}}));default:throw new Error(`Unknown ArrayValue filter: ${ue.value}`)}else if(L instanceof We)switch(ue.value){case"length":return new Be(L.value.length);case"upper":return new We(L.value.toUpperCase());case"lower":return new We(L.value.toLowerCase());case"title":return new We(Ke(L.value));case"capitalize":return new We(L.value.charAt(0).toUpperCase()+L.value.slice(1));case"trim":return new We(L.value.trim());case"indent":return new We(L.value.split(` +`).map((le,ke)=>ke===0||le.length===0?le:" "+le).join(` +`));case"string":return L;default:throw new Error(`Unknown StringValue filter: ${ue.value}`)}else if(L instanceof Be)switch(ue.value){case"abs":return new Be(Math.abs(L.value));default:throw new Error(`Unknown NumericValue filter: ${ue.value}`)}else if(L instanceof dt)switch(ue.value){case"items":return new Te(Array.from(L.value.entries()).map(([le,ke])=>new Te([new We(le),ke])));case"length":return new Be(L.value.size);default:throw new Error(`Unknown ObjectValue filter: ${ue.value}`)}throw new Error(`Cannot apply filter "${ue.value}" to type: ${L.type}`)}else if(B.filter.type==="CallExpression"){const ue=B.filter;if(ue.callee.type!=="Identifier")throw new Error(`Unknown filter: ${ue.callee.type}`);const le=ue.callee.value;if(le==="tojson"){const[,ke]=this.evaluateArguments(ue.args,J),Ne=ke.get("indent")??new tt;if(!(Ne instanceof Be||Ne instanceof tt))throw new Error("If set, indent must be a number");return new We(te(L,Ne.value))}if(L instanceof Te){switch(le){case"selectattr":{if(L.value.some(Z=>!(Z instanceof dt)))throw new Error("`selectattr` can only be applied to array of objects");if(ue.args.some(Z=>Z.type!=="StringLiteral"))throw new Error("arguments of `selectattr` must be strings");const[ke,Ne,ut]=ue.args.map(Z=>this.evaluate(Z,J));let Je;if(Ne){const Z=J.tests.get(Ne.value);if(!Z)throw new Error(`Unknown test: ${Ne.value}`);Je=Z}else Je=(...Z)=>Z[0].__bool__().value;const Ve=L.value.filter(Z=>{const ve=Z.value.get(ke.value);return ve?Je(ve,ut):!1});return new Te(Ve)}case"map":{const[,ke]=this.evaluateArguments(ue.args,J);if(ke.has("attribute")){const Ne=ke.get("attribute");if(!(Ne instanceof We))throw new Error("attribute must be a string");const ut=ke.get("default"),Je=L.value.map(Ve=>{if(!(Ve instanceof dt))throw new Error("items in map must be an object");return Ve.value.get(Ne.value)??ut??new A});return new Te(Je)}else throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${le}`)}else if(L instanceof We){switch(le){case"indent":{const[ke,Ne]=this.evaluateArguments(ue.args,J),ut=ke.at(0)??Ne.get("width")??new Be(4);if(!(ut instanceof Be))throw new Error("width must be a number");const Je=ke.at(1)??Ne.get("first")??new ot(!1),Ve=ke.at(2)??Ne.get("blank")??new ot(!1),Z=L.value.split(` +`),ve=" ".repeat(ut.value),Re=Z.map((He,Xe)=>!Je.value&&Xe===0||!Ve.value&&He.length===0?He:ve+He);return new We(Re.join(` +`))}}throw new Error(`Unknown StringValue filter: ${le}`)}else throw new Error(`Cannot apply filter "${le}" to type: ${L.type}`)}throw new Error(`Unknown filter: ${B.filter.type}`)}evaluateTestExpression(B,J){const L=this.evaluate(B.operand,J),ue=J.tests.get(B.test.value);if(!ue)throw new Error(`Unknown test: ${B.test.value}`);const le=ue(L);return new ot(B.negate?!le:le)}evaluateUnaryExpression(B,J){const L=this.evaluate(B.argument,J);switch(B.operator.value){case"not":return new ot(!L.value);default:throw new SyntaxError(`Unknown operator: ${B.operator.value}`)}}evalProgram(B,J){return this.evaluateBlock(B.body,J)}evaluateBlock(B,J){let L="";for(const ue of B){const le=this.evaluate(ue,J);le.type!=="NullValue"&&le.type!=="UndefinedValue"&&(L+=le.value)}return new We(L)}evaluateIdentifier(B,J){return J.lookupVariable(B.value)}evaluateCallExpression(B,J){const[L,ue]=this.evaluateArguments(B.args,J);ue.size>0&&L.push(new Ge(ue));const le=this.evaluate(B.callee,J);if(le.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${le.type}`);return le.value(L,J)}evaluateSliceExpression(B,J,L){if(!(B instanceof Te||B instanceof We))throw new Error("Slice object must be an array or string");const ue=this.evaluate(J.start,L),le=this.evaluate(J.stop,L),ke=this.evaluate(J.step,L);if(!(ue instanceof Be||ue instanceof A))throw new Error("Slice start must be numeric or undefined");if(!(le instanceof Be||le instanceof A))throw new Error("Slice stop must be numeric or undefined");if(!(ke instanceof Be||ke instanceof A))throw new Error("Slice step must be numeric or undefined");return B instanceof Te?new Te(me(B.value,ue.value,le.value,ke.value)):new We(me(Array.from(B.value),ue.value,le.value,ke.value).join(""))}evaluateMemberExpression(B,J){const L=this.evaluate(B.object,J);let ue;if(B.computed){if(B.property.type==="SliceExpression")return this.evaluateSliceExpression(L,B.property,J);ue=this.evaluate(B.property,J)}else ue=new We(B.property.value);let le;if(L instanceof dt){if(!(ue instanceof We))throw new Error(`Cannot access property with non-string: got ${ue.type}`);le=L.value.get(ue.value)??L.builtins.get(ue.value)}else if(L instanceof Te||L instanceof We)if(ue instanceof Be)le=L.value.at(ue.value),L instanceof We&&(le=new We(L.value.at(ue.value)));else if(ue instanceof We)le=L.builtins.get(ue.value);else throw new Error(`Cannot access property with non-string/non-number: got ${ue.type}`);else{if(!(ue instanceof We))throw new Error(`Cannot access property with non-string: got ${ue.type}`);le=L.builtins.get(ue.value)}return le instanceof De?le:new A}evaluateSet(B,J){const L=this.evaluate(B.value,J);if(B.assignee.type==="Identifier"){const ue=B.assignee.value;J.setVariable(ue,L)}else if(B.assignee.type==="MemberExpression"){const ue=B.assignee,le=this.evaluate(ue.object,J);if(!(le instanceof dt))throw new Error("Cannot assign to member of non-object");if(ue.property.type!=="Identifier")throw new Error("Cannot assign to member with non-identifier property");le.value.set(ue.property.value,L)}else throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(B.assignee)}`);return new tt}evaluateIf(B,J){const L=this.evaluate(B.test,J);return this.evaluateBlock(L.__bool__().value?B.body:B.alternate,J)}evaluateFor(B,J){const L=new Ae(J);let ue,le;if(B.iterable.type==="SelectExpression"){const Ve=B.iterable;le=this.evaluate(Ve.iterable,L),ue=Ve.test}else le=this.evaluate(B.iterable,L);if(!(le instanceof Te))throw new Error(`Expected iterable type in for loop: got ${le.type}`);const ke=[],Ne=[];for(let Ve=0;VeHe.setVariable(B.loopvar.value,ve);else if(B.loopvar.type==="TupleLiteral"){const He=B.loopvar;if(ve.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${ve.type}`);const Xe=ve;if(He.value.length!==Xe.value.length)throw new Error(`Too ${He.value.length>Xe.value.length?"few":"many"} items to unpack`);Re=rt=>{for(let ft=0;ft0?ke[Ve-1]:new A],["nextitem",Ve{var Ne;const le=new Ae(ue);L=L.slice();let ke;((Ne=L.at(-1))==null?void 0:Ne.type)==="KeywordArgumentsValue"&&(ke=L.pop());for(let ut=0;utthis.evaluate(L,J)));case"TupleLiteral":return new je(B.value.map(L=>this.evaluate(L,J)));case"ObjectLiteral":{const L=new Map;for(const[ue,le]of B.value){const ke=this.evaluate(ue,J);if(!(ke instanceof We))throw new Error(`Object keys must be strings: got ${ke.type}`);L.set(ke.value,this.evaluate(le,J))}return new dt(L)}case"Identifier":return this.evaluateIdentifier(B,J);case"CallExpression":return this.evaluateCallExpression(B,J);case"MemberExpression":return this.evaluateMemberExpression(B,J);case"UnaryExpression":return this.evaluateUnaryExpression(B,J);case"BinaryExpression":return this.evaluateBinaryExpression(B,J);case"FilterExpression":return this.evaluateFilterExpression(B,J);case"TestExpression":return this.evaluateTestExpression(B,J);default:throw new SyntaxError(`Unknown node type: ${B.type}`)}}};function se(B){switch(typeof B){case"number":return new Be(B);case"string":return new We(B);case"boolean":return new ot(B);case"undefined":return new A;case"object":return B===null?new tt:Array.isArray(B)?new Te(B.map(se)):new dt(new Map(Object.entries(B).map(([J,L])=>[J,se(L)])));case"function":return new Ye((J,L)=>{const ue=B(...J.map(le=>le.value))??null;return se(ue)});default:throw new Error(`Cannot convert to runtime value: ${B}`)}}function te(B,J,L){const ue=L??0;switch(B.type){case"NullValue":case"UndefinedValue":return"null";case"NumericValue":case"StringValue":case"BooleanValue":return JSON.stringify(B.value);case"ArrayValue":case"ObjectValue":{const le=J?" ".repeat(J):"",ke=` +`+le.repeat(ue),Ne=ke+le;if(B.type==="ArrayValue"){const ut=B.value.map(Je=>te(Je,J,ue+1));return J?`[${Ne}${ut.join(`,${Ne}`)}${ke}]`:`[${ut.join(", ")}]`}else{const ut=Array.from(B.value.entries()).map(([Je,Ve])=>{const Z=`"${Je}": ${te(Ve,J,ue+1)}`;return J?`${Ne}${Z}`:Z});return J?`{${ut.join(",")}${ke}}`:`{${ut.join(", ")}}`}}default:throw new Error(`Cannot convert to JSON: ${B.type}`)}}var we=class{constructor(B){qe(this,"parsed");const J=w(B,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=Se(J)}render(B){const J=new Ae;J.set("false",!1),J.set("true",!0),J.set("raise_exception",le=>{throw new Error(le)}),J.set("range",X);for(const[le,ke]of Object.entries(B))J.set(le,ke);return new $e(J).run(this.parsed).value}}},"./node_modules/onnxruntime-common/dist/esm/backend-impl.js":(e,t,n)=>{n.r(t),n.d(t,{registerBackend:()=>l,resolveBackendAndExecutionProviders:()=>_});const o=new Map,a=[],l=(h,g,M)=>{if(g&&typeof g.init=="function"&&typeof g.createInferenceSessionHandler=="function"){const w=o.get(h);if(w===void 0)o.set(h,{backend:g,priority:M});else{if(w.priority>M)return;if(w.priority===M&&w.backend!==g)throw new Error(`cannot register backend "${h}" using priority ${M}`)}if(M>=0){const C=a.indexOf(h);C!==-1&&a.splice(C,1);for(let k=0;k{const g=o.get(h);if(!g)return"backend not found.";if(g.initialized)return g.backend;if(g.aborted)return g.error;{const M=!!g.initPromise;try{return M||(g.initPromise=g.backend.init(h)),await g.initPromise,g.initialized=!0,g.backend}catch(w){return M||(g.error=`${w}`,g.aborted=!0),g.error}finally{delete g.initPromise}}},_=async h=>{const g=h.executionProviders||[],M=g.map(P=>typeof P=="string"?P:P.name),w=M.length===0?a:M;let C;const k=[],z=new Set;for(const P of w){const y=await f(P);typeof y=="string"?k.push({name:P,err:y}):(C||(C=y),C===y&&z.add(P))}if(!C)throw new Error(`no available backend found. ERR: ${k.map(P=>`[${P.name}] ${P.err}`).join(", ")}`);for(const{name:P,err:y}of k)M.includes(P)&&console.warn(`removing requested execution provider "${P}" from session options because it is not available: ${y}`);const S=g.filter(P=>z.has(typeof P=="string"?P:P.name));return[C,new Proxy(h,{get:(P,y)=>y==="executionProviders"?S:Reflect.get(P,y)})]}},"./node_modules/onnxruntime-common/dist/esm/backend.js":(e,t,n)=>{n.r(t),n.d(t,{registerBackend:()=>o.registerBackend});var o=n("./node_modules/onnxruntime-common/dist/esm/backend-impl.js")},"./node_modules/onnxruntime-common/dist/esm/env-impl.js":(e,t,n)=>{n.r(t),n.d(t,{env:()=>l});var o=n("./node_modules/onnxruntime-common/dist/esm/version.js");let a="warning";const l={wasm:{},webgl:{},webgpu:{},versions:{common:o.version},set logLevel(f){if(f!==void 0){if(typeof f!="string"||["verbose","info","warning","error","fatal"].indexOf(f)===-1)throw new Error(`Unsupported logging level: ${f}`);a=f}},get logLevel(){return a}};Object.defineProperty(l,"logLevel",{enumerable:!0})},"./node_modules/onnxruntime-common/dist/esm/env.js":(e,t,n)=>{n.r(t),n.d(t,{env:()=>a});var o=n("./node_modules/onnxruntime-common/dist/esm/env-impl.js");const a=o.env},"./node_modules/onnxruntime-common/dist/esm/index.js":(e,t,n)=>{n.r(t),n.d(t,{InferenceSession:()=>l.InferenceSession,TRACE:()=>_.TRACE,TRACE_FUNC_BEGIN:()=>_.TRACE_FUNC_BEGIN,TRACE_FUNC_END:()=>_.TRACE_FUNC_END,Tensor:()=>f.Tensor,TrainingSession:()=>h.TrainingSession,env:()=>a.env,registerBackend:()=>o.registerBackend});var o=n("./node_modules/onnxruntime-common/dist/esm/backend.js"),a=n("./node_modules/onnxruntime-common/dist/esm/env.js"),l=n("./node_modules/onnxruntime-common/dist/esm/inference-session.js"),f=n("./node_modules/onnxruntime-common/dist/esm/tensor.js");n("./node_modules/onnxruntime-common/dist/esm/tensor-conversion.js"),n("./node_modules/onnxruntime-common/dist/esm/tensor-factory.js");var _=n("./node_modules/onnxruntime-common/dist/esm/trace.js");n("./node_modules/onnxruntime-common/dist/esm/onnx-model.js"),n("./node_modules/onnxruntime-common/dist/esm/onnx-value.js");var h=n("./node_modules/onnxruntime-common/dist/esm/training-session.js")},"./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js":(e,t,n)=>{n.r(t),n.d(t,{InferenceSession:()=>f});var o=n("./node_modules/onnxruntime-common/dist/esm/backend-impl.js"),a=n("./node_modules/onnxruntime-common/dist/esm/tensor.js"),l=n("./node_modules/onnxruntime-common/dist/esm/trace.js");class f{constructor(h){this.handler=h}async run(h,g,M){(0,l.TRACE_FUNC_BEGIN)();const w={};let C={};if(typeof h!="object"||h===null||h instanceof a.Tensor||Array.isArray(h))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let k=!0;if(typeof g=="object"){if(g===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(g instanceof a.Tensor)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(g)){if(g.length===0)throw new TypeError("'fetches' cannot be an empty array.");k=!1;for(const P of g){if(typeof P!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(P)===-1)throw new RangeError(`'fetches' contains invalid output name: ${P}.`);w[P]=null}if(typeof M=="object"&&M!==null)C=M;else if(typeof M<"u")throw new TypeError("'options' must be an object.")}else{let P=!1;const y=Object.getOwnPropertyNames(g);for(const x of this.outputNames)if(y.indexOf(x)!==-1){const I=g[x];(I===null||I instanceof a.Tensor)&&(P=!0,k=!1,w[x]=I)}if(P){if(typeof M=="object"&&M!==null)C=M;else if(typeof M<"u")throw new TypeError("'options' must be an object.")}else C=g}}else if(typeof g<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const P of this.inputNames)if(typeof h[P]>"u")throw new Error(`input '${P}' is missing in 'feeds'.`);if(k)for(const P of this.outputNames)w[P]=null;const z=await this.handler.run(h,w,C),S={};for(const P in z)if(Object.hasOwnProperty.call(z,P)){const y=z[P];y instanceof a.Tensor?S[P]=y:S[P]=new a.Tensor(y.type,y.data,y.dims)}return(0,l.TRACE_FUNC_END)(),S}async release(){return this.handler.dispose()}static async create(h,g,M,w){(0,l.TRACE_FUNC_BEGIN)();let C,k={};if(typeof h=="string"){if(C=h,typeof g=="object"&&g!==null)k=g;else if(typeof g<"u")throw new TypeError("'options' must be an object.")}else if(h instanceof Uint8Array){if(C=h,typeof g=="object"&&g!==null)k=g;else if(typeof g<"u")throw new TypeError("'options' must be an object.")}else if(h instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&h instanceof SharedArrayBuffer){const y=h;let x=0,I=h.byteLength;if(typeof g=="object"&&g!==null)k=g;else if(typeof g=="number"){if(x=g,!Number.isSafeInteger(x))throw new RangeError("'byteOffset' must be an integer.");if(x<0||x>=y.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${y.byteLength}).`);if(I=h.byteLength-x,typeof M=="number"){if(I=M,!Number.isSafeInteger(I))throw new RangeError("'byteLength' must be an integer.");if(I<=0||x+I>y.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${y.byteLength-x}].`);if(typeof w=="object"&&w!==null)k=w;else if(typeof w<"u")throw new TypeError("'options' must be an object.")}else if(typeof M<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof g<"u")throw new TypeError("'options' must be an object.");C=new Uint8Array(y,x,I)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");const[z,S]=await(0,o.resolveBackendAndExecutionProviders)(k),P=await z.createInferenceSessionHandler(C,S);return(0,l.TRACE_FUNC_END)(),new f(P)}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,t,n)=>{n.r(t),n.d(t,{InferenceSession:()=>a});var o=n("./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js");const a=o.InferenceSession},"./node_modules/onnxruntime-common/dist/esm/onnx-model.js":(e,t,n)=>{n.r(t)},"./node_modules/onnxruntime-common/dist/esm/onnx-value.js":(e,t,n)=>{n.r(t)},"./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js":(e,t,n)=>{n.r(t),n.d(t,{tensorToDataURL:()=>o,tensorToImageData:()=>a});const o=(l,f)=>{const _=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);_.width=l.dims[3],_.height=l.dims[2];const h=_.getContext("2d");if(h!=null){let g,M;(f==null?void 0:f.tensorLayout)!==void 0&&f.tensorLayout==="NHWC"?(g=l.dims[2],M=l.dims[3]):(g=l.dims[3],M=l.dims[2]);const w=(f==null?void 0:f.format)!==void 0?f.format:"RGB",C=f==null?void 0:f.norm;let k,z;C===void 0||C.mean===void 0?k=[255,255,255,255]:typeof C.mean=="number"?k=[C.mean,C.mean,C.mean,C.mean]:(k=[C.mean[0],C.mean[1],C.mean[2],0],C.mean[3]!==void 0&&(k[3]=C.mean[3])),C===void 0||C.bias===void 0?z=[0,0,0,0]:typeof C.bias=="number"?z=[C.bias,C.bias,C.bias,C.bias]:(z=[C.bias[0],C.bias[1],C.bias[2],0],C.bias[3]!==void 0&&(z[3]=C.bias[3]));const S=M*g;let P=0,y=S,x=S*2,I=-1;w==="RGBA"?(P=0,y=S,x=S*2,I=S*3):w==="RGB"?(P=0,y=S,x=S*2):w==="RBG"&&(P=0,x=S,y=S*2);for(let U=0;U{const _=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");let h;if(_!=null){let g,M,w;(f==null?void 0:f.tensorLayout)!==void 0&&f.tensorLayout==="NHWC"?(g=l.dims[2],M=l.dims[1],w=l.dims[3]):(g=l.dims[3],M=l.dims[2],w=l.dims[1]);const C=f!==void 0&&f.format!==void 0?f.format:"RGB",k=f==null?void 0:f.norm;let z,S;k===void 0||k.mean===void 0?z=[255,255,255,255]:typeof k.mean=="number"?z=[k.mean,k.mean,k.mean,k.mean]:(z=[k.mean[0],k.mean[1],k.mean[2],255],k.mean[3]!==void 0&&(z[3]=k.mean[3])),k===void 0||k.bias===void 0?S=[0,0,0,0]:typeof k.bias=="number"?S=[k.bias,k.bias,k.bias,k.bias]:(S=[k.bias[0],k.bias[1],k.bias[2],0],k.bias[3]!==void 0&&(S[3]=k.bias[3]));const P=M*g;if(f!==void 0&&(f.format!==void 0&&w===4&&f.format!=="RGBA"||w===3&&f.format!=="RGB"&&f.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");const y=4;let x=0,I=1,U=2,O=3,N=0,j=P,D=P*2,Y=-1;C==="RGBA"?(N=0,j=P,D=P*2,Y=P*3):C==="RGB"?(N=0,j=P,D=P*2):C==="RBG"&&(N=0,D=P,j=P*2),h=_.createImageData(g,M);for(let de=0;de{n.r(t)},"./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js":(e,t,n)=>{n.r(t),n.d(t,{bufferToTensor:()=>a,tensorFromGpuBuffer:()=>_,tensorFromImage:()=>l,tensorFromPinnedBuffer:()=>h,tensorFromTexture:()=>f});var o=n("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const a=(g,M)=>{if(g===void 0)throw new Error("Image buffer must be defined");if(M.height===void 0||M.width===void 0)throw new Error("Image height and width must be defined");if(M.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");const{height:w,width:C}=M,k=M.norm??{mean:255,bias:0};let z,S;typeof k.mean=="number"?z=[k.mean,k.mean,k.mean,k.mean]:z=[k.mean[0],k.mean[1],k.mean[2],k.mean[3]??255],typeof k.bias=="number"?S=[k.bias,k.bias,k.bias,k.bias]:S=[k.bias[0],k.bias[1],k.bias[2],k.bias[3]??0];const P=M.format!==void 0?M.format:"RGBA",y=M.tensorFormat!==void 0&&M.tensorFormat!==void 0?M.tensorFormat:"RGB",x=w*C,I=y==="RGBA"?new Float32Array(x*4):new Float32Array(x*3);let U=4,O=0,N=1,j=2,D=3,Y=0,de=x,Ce=x*2,ee=-1;P==="RGB"&&(U=3,O=0,N=1,j=2,D=-1),y==="RGBA"?ee=x*3:y==="RBG"?(Y=0,Ce=x,de=x*2):y==="BGR"&&(Ce=0,de=x,Y=x*2);for(let R=0;R{const w=typeof HTMLImageElement<"u"&&g instanceof HTMLImageElement,C=typeof ImageData<"u"&&g instanceof ImageData,k=typeof ImageBitmap<"u"&&g instanceof ImageBitmap,z=typeof g=="string";let S,P=M??{};const y=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},x=I=>I instanceof HTMLCanvasElement||I instanceof OffscreenCanvas?I.getContext("2d"):null;if(w){const I=y();I.width=g.width,I.height=g.height;const U=x(I);if(U!=null){let O=g.height,N=g.width;if(M!==void 0&&M.resizedHeight!==void 0&&M.resizedWidth!==void 0&&(O=M.resizedHeight,N=M.resizedWidth),M!==void 0){if(P=M,M.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");P.tensorFormat="RGBA",P.height=O,P.width=N}else P.tensorFormat="RGBA",P.height=O,P.width=N;U.drawImage(g,0,0),S=U.getImageData(0,0,N,O).data}else throw new Error("Can not access image data")}else if(C){let I,U;if(M!==void 0&&M.resizedWidth!==void 0&&M.resizedHeight!==void 0?(I=M.resizedHeight,U=M.resizedWidth):(I=g.height,U=g.width),M!==void 0&&(P=M),P.format="RGBA",P.height=I,P.width=U,M!==void 0){const O=y();O.width=U,O.height=I;const N=x(O);if(N!=null)N.putImageData(g,0,0),S=N.getImageData(0,0,U,I).data;else throw new Error("Can not access image data")}else S=g.data}else if(k){if(M===void 0)throw new Error("Please provide image config with format for Imagebitmap");const I=y();I.width=g.width,I.height=g.height;const U=x(I);if(U!=null){const O=g.height,N=g.width;return U.drawImage(g,0,0,N,O),S=U.getImageData(0,0,N,O).data,P.height=O,P.width=N,a(S,P)}else throw new Error("Can not access image data")}else{if(z)return new Promise((I,U)=>{const O=y(),N=x(O);if(!g||!N)return U();const j=new Image;j.crossOrigin="Anonymous",j.src=g,j.onload=()=>{O.width=j.width,O.height=j.height,N.drawImage(j,0,0,O.width,O.height);const D=N.getImageData(0,0,O.width,O.height);P.height=O.height,P.width=O.width,I(a(D.data,P))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(S!==void 0)return a(S,P);throw new Error("Input data provided is not supported - aborted tensor creation")},f=(g,M)=>{const{width:w,height:C,download:k,dispose:z}=M,S=[1,C,w,4];return new o.Tensor({location:"texture",type:"float32",texture:g,dims:S,download:k,dispose:z})},_=(g,M)=>{const{dataType:w,dims:C,download:k,dispose:z}=M;return new o.Tensor({location:"gpu-buffer",type:w??"float32",gpuBuffer:g,dims:C,download:k,dispose:z})},h=(g,M,w)=>new o.Tensor({location:"cpu-pinned",type:g,data:M,dims:w??[M.length]})},"./node_modules/onnxruntime-common/dist/esm/tensor-factory.js":(e,t,n)=>{n.r(t)},"./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js":(e,t,n)=>{n.r(t),n.d(t,{NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP:()=>a,NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP:()=>o,checkTypedArray:()=>f});const o=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array]]),a=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);let l=!1;const f=()=>{if(!l){l=!0;const _=typeof BigInt64Array<"u"&&BigInt64Array.from,h=typeof BigUint64Array<"u"&&BigUint64Array.from,g=typeof Float16Array<"u"&&Float16Array.from;_&&(o.set("int64",BigInt64Array),a.set(BigInt64Array,"int64")),h&&(o.set("uint64",BigUint64Array),a.set(BigUint64Array,"uint64")),g?(o.set("float16",Float16Array),a.set(Float16Array,"float16")):o.set("float16",Uint16Array)}}},"./node_modules/onnxruntime-common/dist/esm/tensor-impl.js":(e,t,n)=>{n.r(t),n.d(t,{Tensor:()=>_});var o=n("./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js"),a=n("./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js"),l=n("./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js"),f=n("./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js");class _{constructor(g,M,w){(0,l.checkTypedArray)();let C,k;if(typeof g=="object"&&"location"in g)switch(this.dataLocation=g.location,C=g.type,k=g.dims,g.location){case"cpu-pinned":{const S=l.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(C);if(!S)throw new TypeError(`unsupported type "${C}" to create tensor from pinned buffer`);if(!(g.data instanceof S))throw new TypeError(`buffer should be of type ${S.name}`);this.cpuData=g.data;break}case"texture":{if(C!=="float32")throw new TypeError(`unsupported type "${C}" to create tensor from texture`);this.gpuTextureData=g.texture,this.downloader=g.download,this.disposer=g.dispose;break}case"gpu-buffer":{if(C!=="float32"&&C!=="float16"&&C!=="int32"&&C!=="int64"&&C!=="uint32"&&C!=="uint8"&&C!=="bool")throw new TypeError(`unsupported type "${C}" to create tensor from gpu buffer`);this.gpuBufferData=g.gpuBuffer,this.downloader=g.download,this.disposer=g.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let S,P;if(typeof g=="string")if(C=g,P=w,g==="string"){if(!Array.isArray(M))throw new TypeError("A string tensor's data must be a string array.");S=M}else{const y=l.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(g);if(y===void 0)throw new TypeError(`Unsupported tensor type: ${g}.`);if(Array.isArray(M)){if(g==="float16"&&y===Uint16Array)throw new TypeError("Creating a float16 tensor from number array is not supported. Please use Uint16Array as data.");g==="uint64"||g==="int64"?S=y.from(M,BigInt):S=y.from(M)}else if(M instanceof y)S=M;else throw new TypeError(`A ${C} tensor's data must be type of ${y}`)}else if(P=M,Array.isArray(g)){if(g.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");const y=typeof g[0];if(y==="string")C="string",S=g;else if(y==="boolean")C="bool",S=Uint8Array.from(g);else throw new TypeError(`Invalid element type of data array: ${y}.`)}else{const y=l.NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.get(g.constructor);if(y===void 0)throw new TypeError(`Unsupported type for tensor data: ${g.constructor}.`);C=y,S=g}if(P===void 0)P=[S.length];else if(!Array.isArray(P))throw new TypeError("A tensor's dims must be a number array");k=P,this.cpuData=S,this.dataLocation="cpu"}const z=(0,f.calculateSize)(k);if(this.cpuData&&z!==this.cpuData.length)throw new Error(`Tensor's size(${z}) does not match data length(${this.cpuData.length}).`);this.type=C,this.dims=k,this.size=z}static async fromImage(g,M){return(0,a.tensorFromImage)(g,M)}static fromTexture(g,M){return(0,a.tensorFromTexture)(g,M)}static fromGpuBuffer(g,M){return(0,a.tensorFromGpuBuffer)(g,M)}static fromPinnedBuffer(g,M,w){return(0,a.tensorFromPinnedBuffer)(g,M,w)}toDataURL(g){return(0,o.tensorToDataURL)(this,g)}toImageData(g){return(0,o.tensorToImageData)(this,g)}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(g){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 M=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=M,g&&this.disposer&&(this.disposer(),this.disposer=void 0),M}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(g){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return(0,f.tensorReshape)(this,g)}}},"./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js":(e,t,n)=>{n.r(t),n.d(t,{calculateSize:()=>a,tensorReshape:()=>l});var o=n("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const a=f=>{let _=1;for(let h=0;h{switch(f.location){case"cpu":return new o.Tensor(f.type,f.data,_);case"cpu-pinned":return new o.Tensor({location:"cpu-pinned",data:f.data,type:f.type,dims:_});case"texture":return new o.Tensor({location:"texture",texture:f.texture,type:f.type,dims:_});case"gpu-buffer":return new o.Tensor({location:"gpu-buffer",gpuBuffer:f.gpuBuffer,type:f.type,dims:_});default:throw new Error(`tensorReshape: tensor location ${f.location} is not supported`)}}},"./node_modules/onnxruntime-common/dist/esm/tensor.js":(e,t,n)=>{n.r(t),n.d(t,{Tensor:()=>a});var o=n("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const a=o.Tensor},"./node_modules/onnxruntime-common/dist/esm/trace.js":(e,t,n)=>{n.r(t),n.d(t,{TRACE:()=>a,TRACE_FUNC_BEGIN:()=>f,TRACE_FUNC_END:()=>_});var o=n("./node_modules/onnxruntime-common/dist/esm/env-impl.js");const a=(h,g)=>{(typeof o.env.trace>"u"?!o.env.wasm.trace:!o.env.trace)||console.timeStamp(`${h}::ORT::${g}`)},l=(h,g)=>{var C;const M=((C=new Error().stack)==null?void 0:C.split(/\r\n|\r|\n/g))||[];let w=!1;for(let k=0;k{(typeof o.env.trace>"u"?!o.env.wasm.trace:!o.env.trace)||l("BEGIN",h)},_=h=>{(typeof o.env.trace>"u"?!o.env.wasm.trace:!o.env.trace)||l("END",h)}},"./node_modules/onnxruntime-common/dist/esm/training-session-impl.js":(e,t,n)=>{n.r(t),n.d(t,{TrainingSession:()=>f});var o=n("./node_modules/onnxruntime-common/dist/esm/backend-impl.js"),a=n("./node_modules/onnxruntime-common/dist/esm/tensor.js");const l="Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.";class f{constructor(h,g,M){this.handler=h,this.hasOptimizerModel=g,this.hasEvalModel=M}get trainingInputNames(){return this.handler.inputNames}get trainingOutputNames(){return this.handler.outputNames}get evalInputNames(){if(this.hasEvalModel)return this.handler.evalInputNames;throw new Error("This training session has no evalModel loaded.")}get evalOutputNames(){if(this.hasEvalModel)return this.handler.evalOutputNames;throw new Error("This training session has no evalModel loaded.")}static async create(h,g){const M=h.evalModel||"",w=h.optimizerModel||"",C=g||{},[k,z]=await(0,o.resolveBackendAndExecutionProviders)(C);if(k.createTrainingSessionHandler){const S=await k.createTrainingSessionHandler(h.checkpointState,h.trainModel,M,w,z);return new f(S,!!h.optimizerModel,!!h.evalModel)}else throw new Error(l)}typeNarrowingForRunStep(h,g,M,w,C){const k={};let z={};if(typeof M!="object"||M===null||M instanceof a.Tensor||Array.isArray(M))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let S=!0;if(typeof w=="object"){if(w===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(w instanceof a.Tensor)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(w)){if(w.length===0)throw new TypeError("'fetches' cannot be an empty array.");S=!1;for(const P of w){if(typeof P!="string")throw new TypeError("'fetches' must be a string array or an object.");if(g.indexOf(P)===-1)throw new RangeError(`'fetches' contains invalid output name: ${P}.`);k[P]=null}if(typeof C=="object"&&C!==null)z=C;else if(typeof C<"u")throw new TypeError("'options' must be an object.")}else{let P=!1;const y=Object.getOwnPropertyNames(w);for(const x of g)if(y.indexOf(x)!==-1){const I=w[x];(I===null||I instanceof a.Tensor)&&(P=!0,S=!1,k[x]=I)}if(P){if(typeof C=="object"&&C!==null)z=C;else if(typeof C<"u")throw new TypeError("'options' must be an object.")}else z=w}}else if(typeof w<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const P of h)if(typeof M[P]>"u")throw new Error(`input '${P}' is missing in 'feeds'.`);if(S)for(const P of g)k[P]=null;return[k,z]}convertHandlerReturnTypeToMapOfTensors(h){const g={};for(const M in h)if(Object.hasOwnProperty.call(h,M)){const w=h[M];w instanceof a.Tensor?g[M]=w:g[M]=new a.Tensor(w.type,w.data,w.dims)}return g}async lazyResetGrad(){await this.handler.lazyResetGrad()}async runTrainStep(h,g,M){const[w,C]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,h,g,M),k=await this.handler.runTrainStep(h,w,C);return this.convertHandlerReturnTypeToMapOfTensors(k)}async runOptimizerStep(h){if(this.hasOptimizerModel)await this.handler.runOptimizerStep(h||{});else throw new Error("This TrainingSession has no OptimizerModel loaded.")}async runEvalStep(h,g,M){if(this.hasEvalModel){const[w,C]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,h,g,M),k=await this.handler.runEvalStep(h,w,C);return this.convertHandlerReturnTypeToMapOfTensors(k)}else throw new Error("This TrainingSession has no EvalModel loaded.")}async getParametersSize(h=!0){return this.handler.getParametersSize(h)}async loadParametersBuffer(h,g=!0){const M=await this.getParametersSize(g);if(h.length!==4*M)throw new Error("Size of the buffer passed into loadParametersBuffer must match the number of parameters in the model. Please use getParametersSize method to check.");return this.handler.loadParametersBuffer(h,g)}async getContiguousParameters(h=!0){return this.handler.getContiguousParameters(h)}async release(){return this.handler.dispose()}}},"./node_modules/onnxruntime-common/dist/esm/training-session.js":(e,t,n)=>{n.r(t),n.d(t,{TrainingSession:()=>a});var o=n("./node_modules/onnxruntime-common/dist/esm/training-session-impl.js");const a=o.TrainingSession},"./node_modules/onnxruntime-common/dist/esm/version.js":(e,t,n)=>{n.r(t),n.d(t,{version:()=>o});const o="1.19.0"},"./node_modules/onnxruntime-web/dist/ort.webgpu.bundle.min.mjs":(e,t,n)=>{n.r(t),n.d(t,{InferenceSession:()=>te,TRACE:()=>je,TRACE_FUNC_BEGIN:()=>tt,TRACE_FUNC_END:()=>A,Tensor:()=>Ge,TrainingSession:()=>ut,default:()=>gx,env:()=>D,registerBackend:()=>z});/*! + * 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,a=Object.getOwnPropertyDescriptor,l=Object.getOwnPropertyNames,f=Object.prototype.hasOwnProperty,_=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(i,s)=>(typeof require<"u"?require:i)[s]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')}),h=(r,i)=>()=>(r&&(i=r(r=0)),i),g=(r,i)=>{for(var s in i)o(r,s,{get:i[s],enumerable:!0})},M=(r,i,s,u)=>{if(i&&typeof i=="object"||typeof i=="function")for(let c of l(i))!f.call(r,c)&&c!==s&&o(r,c,{get:()=>i[c],enumerable:!(u=a(i,c))||u.enumerable});return r},w=r=>M(o({},"__esModule",{value:!0}),r),C,k,z,S,P,y=h(()=>{C=new Map,k=[],z=(r,i,s)=>{if(i&&typeof i.init=="function"&&typeof i.createInferenceSessionHandler=="function"){let u=C.get(r);if(u===void 0)C.set(r,{backend:i,priority:s});else{if(u.priority>s)return;if(u.priority===s&&u.backend!==i)throw new Error(`cannot register backend "${r}" using priority ${s}`)}if(s>=0){let c=k.indexOf(r);c!==-1&&k.splice(c,1);for(let p=0;p{let i=C.get(r);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(r)),await i.initPromise,i.initialized=!0,i.backend}catch(u){return s||(i.error=`${u}`,i.aborted=!0),i.error}finally{delete i.initPromise}}},P=async r=>{let i=r.executionProviders||[],s=i.map(T=>typeof T=="string"?T:T.name),u=s.length===0?k:s,c,p=[],d=new Set;for(let T of u){let E=await S(T);typeof E=="string"?p.push({name:T,err:E}):(c||(c=E),c===E&&d.add(T))}if(!c)throw new Error(`no available backend found. ERR: ${p.map(T=>`[${T.name}] ${T.err}`).join(", ")}`);for(let{name:T,err:E}of p)s.includes(T)&&console.warn(`removing requested execution provider "${T}" from session options because it is not available: ${E}`);let b=i.filter(T=>d.has(typeof T=="string"?T:T.name));return[c,new Proxy(r,{get:(T,E)=>E==="executionProviders"?b:Reflect.get(T,E)})]}}),x=h(()=>{y()}),I,U=h(()=>{I="1.20.0-dev.20240816-b2d603abda"}),O,N,j=h(()=>{U(),O="warning",N={wasm:{},webgl:{},webgpu:{},versions:{common:I},set logLevel(r){if(r!==void 0){if(typeof r!="string"||["verbose","info","warning","error","fatal"].indexOf(r)===-1)throw new Error(`Unsupported logging level: ${r}`);O=r}},get logLevel(){return O}},Object.defineProperty(N,"logLevel",{enumerable:!0})}),D,Y=h(()=>{j(),D=N}),de,Ce,ee=h(()=>{de=(r,i)=>{let s=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);s.width=r.dims[3],s.height=r.dims[2];let u=s.getContext("2d");if(u!=null){let c,p;(i==null?void 0:i.tensorLayout)!==void 0&&i.tensorLayout==="NHWC"?(c=r.dims[2],p=r.dims[3]):(c=r.dims[3],p=r.dims[2]);let d=(i==null?void 0:i.format)!==void 0?i.format:"RGB",b=i==null?void 0:i.norm,T,E;b===void 0||b.mean===void 0?T=[255,255,255,255]:typeof b.mean=="number"?T=[b.mean,b.mean,b.mean,b.mean]:(T=[b.mean[0],b.mean[1],b.mean[2],0],b.mean[3]!==void 0&&(T[3]=b.mean[3])),b===void 0||b.bias===void 0?E=[0,0,0,0]:typeof b.bias=="number"?E=[b.bias,b.bias,b.bias,b.bias]:(E=[b.bias[0],b.bias[1],b.bias[2],0],b.bias[3]!==void 0&&(E[3]=b.bias[3]));let q=p*c,H=0,v=q,ne=q*2,re=-1;d==="RGBA"?(H=0,v=q,ne=q*2,re=q*3):d==="RGB"?(H=0,v=q,ne=q*2):d==="RBG"&&(H=0,ne=q,v=q*2);for(let ce=0;ce{let s=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),u;if(s!=null){let c,p,d;(i==null?void 0:i.tensorLayout)!==void 0&&i.tensorLayout==="NHWC"?(c=r.dims[2],p=r.dims[1],d=r.dims[3]):(c=r.dims[3],p=r.dims[2],d=r.dims[1]);let b=i!==void 0&&i.format!==void 0?i.format:"RGB",T=i==null?void 0:i.norm,E,q;T===void 0||T.mean===void 0?E=[255,255,255,255]:typeof T.mean=="number"?E=[T.mean,T.mean,T.mean,T.mean]:(E=[T.mean[0],T.mean[1],T.mean[2],255],T.mean[3]!==void 0&&(E[3]=T.mean[3])),T===void 0||T.bias===void 0?q=[0,0,0,0]:typeof T.bias=="number"?q=[T.bias,T.bias,T.bias,T.bias]:(q=[T.bias[0],T.bias[1],T.bias[2],0],T.bias[3]!==void 0&&(q[3]=T.bias[3]));let H=p*c;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 v=4,ne=0,re=1,ce=2,_e=3,be=0,he=H,Fe=H*2,xe=-1;b==="RGBA"?(be=0,he=H,Fe=H*2,xe=H*3):b==="RGB"?(be=0,he=H,Fe=H*2):b==="RBG"&&(be=0,Fe=H,he=H*2),u=s.createImageData(c,p);for(let Ie=0;Ie{dt(),ye=(r,i)=>{if(r===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:u}=i,c=i.norm??{mean:255,bias:0},p,d;typeof c.mean=="number"?p=[c.mean,c.mean,c.mean,c.mean]:p=[c.mean[0],c.mean[1],c.mean[2],c.mean[3]??255],typeof c.bias=="number"?d=[c.bias,c.bias,c.bias,c.bias]:d=[c.bias[0],c.bias[1],c.bias[2],c.bias[3]??0];let b=i.format!==void 0?i.format:"RGBA",T=i.tensorFormat!==void 0&&i.tensorFormat!==void 0?i.tensorFormat:"RGB",E=s*u,q=T==="RGBA"?new Float32Array(E*4):new Float32Array(E*3),H=4,v=0,ne=1,re=2,ce=3,_e=0,be=E,he=E*2,Fe=-1;b==="RGB"&&(H=3,v=0,ne=1,re=2,ce=-1),T==="RGBA"?Fe=E*3:T==="RBG"?(_e=0,he=E,be=E*2):T==="BGR"&&(he=0,be=E,_e=E*2);for(let xe=0;xe{let s=typeof HTMLImageElement<"u"&&r instanceof HTMLImageElement,u=typeof ImageData<"u"&&r instanceof ImageData,c=typeof ImageBitmap<"u"&&r instanceof ImageBitmap,p=typeof r=="string",d,b=i??{},T=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},E=q=>q instanceof HTMLCanvasElement||q instanceof OffscreenCanvas?q.getContext("2d"):null;if(s){let q=T();q.width=r.width,q.height=r.height;let H=E(q);if(H!=null){let v=r.height,ne=r.width;if(i!==void 0&&i.resizedHeight!==void 0&&i.resizedWidth!==void 0&&(v=i.resizedHeight,ne=i.resizedWidth),i!==void 0){if(b=i,i.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");b.tensorFormat="RGBA",b.height=v,b.width=ne}else b.tensorFormat="RGBA",b.height=v,b.width=ne;H.drawImage(r,0,0),d=H.getImageData(0,0,ne,v).data}else throw new Error("Can not access image data")}else if(u){let q,H;if(i!==void 0&&i.resizedWidth!==void 0&&i.resizedHeight!==void 0?(q=i.resizedHeight,H=i.resizedWidth):(q=r.height,H=r.width),i!==void 0&&(b=i),b.format="RGBA",b.height=q,b.width=H,i!==void 0){let v=T();v.width=H,v.height=q;let ne=E(v);if(ne!=null)ne.putImageData(r,0,0),d=ne.getImageData(0,0,H,q).data;else throw new Error("Can not access image data")}else d=r.data}else if(c){if(i===void 0)throw new Error("Please provide image config with format for Imagebitmap");let q=T();q.width=r.width,q.height=r.height;let H=E(q);if(H!=null){let v=r.height,ne=r.width;return H.drawImage(r,0,0,ne,v),d=H.getImageData(0,0,ne,v).data,b.height=v,b.width=ne,ye(d,b)}else throw new Error("Can not access image data")}else{if(p)return new Promise((q,H)=>{let v=T(),ne=E(v);if(!r||!ne)return H();let re=new Image;re.crossOrigin="Anonymous",re.src=r,re.onload=()=>{v.width=re.width,v.height=re.height,ne.drawImage(re,0,0,v.width,v.height);let ce=ne.getImageData(0,0,v.width,v.height);b.height=v.height,b.width=v.width,q(ye(ce.data,b))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(d!==void 0)return ye(d,b);throw new Error("Input data provided is not supported - aborted tensor creation")},Me=(r,i)=>{let{width:s,height:u,download:c,dispose:p}=i,d=[1,u,s,4];return new ot({location:"texture",type:"float32",texture:r,dims:d,download:c,dispose:p})},Qe=(r,i)=>{let{dataType:s,dims:u,download:c,dispose:p}=i;return new ot({location:"gpu-buffer",type:s??"float32",gpuBuffer:r,dims:u,download:c,dispose:p})},ge=(r,i,s)=>new ot({location:"cpu-pinned",type:r,data:i,dims:s??[i.length]})}),ae,Se,X,me,Ke=h(()=>{ae=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),Se=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),X=!1,me=()=>{if(!X){X=!0;let r=typeof BigInt64Array<"u"&&BigInt64Array.from,i=typeof BigUint64Array<"u"&&BigUint64Array.from,s=typeof Float16Array<"u"&&Float16Array.from;r&&(ae.set("int64",BigInt64Array),Se.set(BigInt64Array,"int64")),i&&(ae.set("uint64",BigUint64Array),Se.set(BigUint64Array,"uint64")),s?(ae.set("float16",Float16Array),Se.set(Float16Array,"float16")):ae.set("float16",Uint16Array)}}}),De,Be,We=h(()=>{dt(),De=r=>{let i=1;for(let s=0;s{switch(r.location){case"cpu":return new ot(r.type,r.data,i);case"cpu-pinned":return new ot({location:"cpu-pinned",data:r.data,type:r.type,dims:i});case"texture":return new ot({location:"texture",texture:r.texture,type:r.type,dims:i});case"gpu-buffer":return new ot({location:"gpu-buffer",gpuBuffer:r.gpuBuffer,type:r.type,dims:i});default:throw new Error(`tensorReshape: tensor location ${r.location} is not supported`)}}}),ot,dt=h(()=>{ee(),Q(),Ke(),We(),ot=class{constructor(r,i,s){me();let u,c;if(typeof r=="object"&&"location"in r)switch(this.dataLocation=r.location,u=r.type,c=r.dims,r.location){case"cpu-pinned":{let d=ae.get(u);if(!d)throw new TypeError(`unsupported type "${u}" to create tensor from pinned buffer`);if(!(r.data instanceof d))throw new TypeError(`buffer should be of type ${d.name}`);this.cpuData=r.data;break}case"texture":{if(u!=="float32")throw new TypeError(`unsupported type "${u}" to create tensor from texture`);this.gpuTextureData=r.texture,this.downloader=r.download,this.disposer=r.dispose;break}case"gpu-buffer":{if(u!=="float32"&&u!=="float16"&&u!=="int32"&&u!=="int64"&&u!=="uint32"&&u!=="uint8"&&u!=="bool")throw new TypeError(`unsupported type "${u}" to create tensor from gpu buffer`);this.gpuBufferData=r.gpuBuffer,this.downloader=r.download,this.disposer=r.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let d,b;if(typeof r=="string")if(u=r,b=s,r==="string"){if(!Array.isArray(i))throw new TypeError("A string tensor's data must be a string array.");d=i}else{let T=ae.get(r);if(T===void 0)throw new TypeError(`Unsupported tensor type: ${r}.`);if(Array.isArray(i)){if(r==="float16"&&T===Uint16Array||r==="uint4"||r==="int4")throw new TypeError(`Creating a ${r} tensor from number array is not supported. Please use ${T.name} as data.`);r==="uint64"||r==="int64"?d=T.from(i,BigInt):d=T.from(i)}else if(i instanceof T)d=i;else throw new TypeError(`A ${u} tensor's data must be type of ${T}`)}else if(b=i,Array.isArray(r)){if(r.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let T=typeof r[0];if(T==="string")u="string",d=r;else if(T==="boolean")u="bool",d=Uint8Array.from(r);else throw new TypeError(`Invalid element type of data array: ${T}.`)}else{let T=Se.get(r.constructor);if(T===void 0)throw new TypeError(`Unsupported type for tensor data: ${r.constructor}.`);u=T,d=r}if(b===void 0)b=[d.length];else if(!Array.isArray(b))throw new TypeError("A tensor's dims must be a number array");c=b,this.cpuData=d,this.dataLocation="cpu"}let p=De(c);if(this.cpuData&&p!==this.cpuData.length&&!((u==="uint4"||u==="int4")&&Math.ceil(p/2)===this.cpuData.length))throw new Error(`Tensor's size(${p}) does not match data length(${this.cpuData.length}).`);this.type=u,this.dims=c,this.size=p}static async fromImage(r,i){return R(r,i)}static fromTexture(r,i){return Me(r,i)}static fromGpuBuffer(r,i){return Qe(r,i)}static fromPinnedBuffer(r,i,s){return ge(r,i,s)}toDataURL(r){return de(this,r)}toImageData(r){return Ce(this,r)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}async getData(r){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,r&&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(r){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return Be(this,r)}}}),Ge,Te=h(()=>{dt(),Ge=ot}),je,Ye,tt,A,Ae=h(()=>{j(),je=(r,i)=>{(typeof N.trace>"u"?!N.wasm.trace:!N.trace)||console.timeStamp(`${r}::ORT::${i}`)},Ye=(r,i)=>{var c;let s=((c=new Error().stack)==null?void 0:c.split(/\r\n|\r|\n/g))||[],u=!1;for(let p=0;p{(typeof N.trace>"u"?!N.wasm.trace:!N.trace)||Ye("BEGIN",r)},A=r=>{(typeof N.trace>"u"?!N.wasm.trace:!N.trace)||Ye("END",r)}}),$e,se=h(()=>{y(),Te(),Ae(),$e=class K2{constructor(i){this.handler=i}async run(i,s,u){tt();let c={},p={};if(typeof i!="object"||i===null||i instanceof Ge||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 Ge)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 E of s){if(typeof E!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(E)===-1)throw new RangeError(`'fetches' contains invalid output name: ${E}.`);c[E]=null}if(typeof u=="object"&&u!==null)p=u;else if(typeof u<"u")throw new TypeError("'options' must be an object.")}else{let E=!1,q=Object.getOwnPropertyNames(s);for(let H of this.outputNames)if(q.indexOf(H)!==-1){let v=s[H];(v===null||v instanceof Ge)&&(E=!0,d=!1,c[H]=v)}if(E){if(typeof u=="object"&&u!==null)p=u;else if(typeof u<"u")throw new TypeError("'options' must be an object.")}else p=s}}else if(typeof s<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let E of this.inputNames)if(typeof i[E]>"u")throw new Error(`input '${E}' is missing in 'feeds'.`);if(d)for(let E of this.outputNames)c[E]=null;let b=await this.handler.run(i,c,p),T={};for(let E in b)if(Object.hasOwnProperty.call(b,E)){let q=b[E];q instanceof Ge?T[E]=q:T[E]=new Ge(q.type,q.data,q.dims)}return A(),T}async release(){return this.handler.dispose()}static async create(i,s,u,c){tt();let p,d={};if(typeof i=="string"){if(p=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(p=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 q=i,H=0,v=i.byteLength;if(typeof s=="object"&&s!==null)d=s;else if(typeof s=="number"){if(H=s,!Number.isSafeInteger(H))throw new RangeError("'byteOffset' must be an integer.");if(H<0||H>=q.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${q.byteLength}).`);if(v=i.byteLength-H,typeof u=="number"){if(v=u,!Number.isSafeInteger(v))throw new RangeError("'byteLength' must be an integer.");if(v<=0||H+v>q.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${q.byteLength-H}].`);if(typeof c=="object"&&c!==null)d=c;else if(typeof c<"u")throw new TypeError("'options' must be an object.")}else if(typeof u<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof s<"u")throw new TypeError("'options' must be an object.");p=new Uint8Array(q,H,v)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[b,T]=await P(d),E=await b.createInferenceSessionHandler(p,T);return A(),new K2(E)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}}),te,we=h(()=>{se(),te=$e}),B=h(()=>{}),J=h(()=>{}),L=h(()=>{}),ue=h(()=>{}),le,ke,Ne=h(()=>{y(),Te(),le="Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.",ke=class Q2{constructor(i,s,u){this.handler=i,this.hasOptimizerModel=s,this.hasEvalModel=u}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 u=i.evalModel||"",c=i.optimizerModel||"",p=s||{},[d,b]=await P(p);if(d.createTrainingSessionHandler){let T=await d.createTrainingSessionHandler(i.checkpointState,i.trainModel,u,c,b);return new Q2(T,!!i.optimizerModel,!!i.evalModel)}else throw new Error(le)}typeNarrowingForRunStep(i,s,u,c,p){let d={},b={};if(typeof u!="object"||u===null||u instanceof Ge||Array.isArray(u))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let T=!0;if(typeof c=="object"){if(c===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(c instanceof Ge)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(c)){if(c.length===0)throw new TypeError("'fetches' cannot be an empty array.");T=!1;for(let E of c){if(typeof E!="string")throw new TypeError("'fetches' must be a string array or an object.");if(s.indexOf(E)===-1)throw new RangeError(`'fetches' contains invalid output name: ${E}.`);d[E]=null}if(typeof p=="object"&&p!==null)b=p;else if(typeof p<"u")throw new TypeError("'options' must be an object.")}else{let E=!1,q=Object.getOwnPropertyNames(c);for(let H of s)if(q.indexOf(H)!==-1){let v=c[H];(v===null||v instanceof Ge)&&(E=!0,T=!1,d[H]=v)}if(E){if(typeof p=="object"&&p!==null)b=p;else if(typeof p<"u")throw new TypeError("'options' must be an object.")}else b=c}}else if(typeof c<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let E of i)if(typeof u[E]>"u")throw new Error(`input '${E}' is missing in 'feeds'.`);if(T)for(let E of s)d[E]=null;return[d,b]}convertHandlerReturnTypeToMapOfTensors(i){let s={};for(let u in i)if(Object.hasOwnProperty.call(i,u)){let c=i[u];c instanceof Ge?s[u]=c:s[u]=new Ge(c.type,c.data,c.dims)}return s}async lazyResetGrad(){await this.handler.lazyResetGrad()}async runTrainStep(i,s,u){let[c,p]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,i,s,u),d=await this.handler.runTrainStep(i,c,p);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,u){if(this.hasEvalModel){let[c,p]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,i,s,u),d=await this.handler.runEvalStep(i,c,p);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 u=await this.getParametersSize(s);if(i.length!==4*u)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()}}}),ut,Je=h(()=>{Ne(),ut=ke}),Ve={};g(Ve,{InferenceSession:()=>te,TRACE:()=>je,TRACE_FUNC_BEGIN:()=>tt,TRACE_FUNC_END:()=>A,Tensor:()=>Ge,TrainingSession:()=>ut,env:()=>D,registerBackend:()=>z});var Z=h(()=>{x(),Y(),we(),Te(),B(),J(),Ae(),L(),ue(),Je()}),ve=h(()=>{}),Re={};g(Re,{default:()=>rt});var He,Xe,rt,ft=h(()=>{var r;by(),mn(),Qr(),He="ort-wasm-proxy-worker",Xe=((r=globalThis.self)==null?void 0:r.name)===He,Xe&&(self.onmessage=i=>{let{type:s,in:u}=i.data;try{switch(s){case"init-wasm":bi(u.wasm).then(()=>{wm(u).then(()=>{postMessage({type:s})},c=>{postMessage({type:s,err:c})})},c=>{postMessage({type:s,err:c})});break;case"init-ep":{let{epName:c,env:p}=u;vm(p,c).then(()=>{postMessage({type:s})},d=>{postMessage({type:s,err:d})});break}case"copy-from":{let{buffer:c}=u,p=Cp(c);postMessage({type:s,out:p});break}case"create":{let{model:c,options:p}=u;bm(c,p).then(d=>{postMessage({type:s,out:d})},d=>{postMessage({type:s,err:d})});break}case"release":xm(u),postMessage({type:s});break;case"run":{let{sessionId:c,inputIndices:p,inputs:d,outputIndices:b,options:T}=u;Tm(c,p,d,b,new Array(b.length).fill(null),T).then(E=>{E.some(q=>q[3]!=="cpu")?postMessage({type:s,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:s,out:E},Sm([...d,...E]))},E=>{postMessage({type:s,err:E})});break}case"end-profiling":km(u),postMessage({type:s});break;default:}}catch(c){postMessage({type:s,err:c})}}),rt=Xe?null:i=>new Worker(i??at,{type:"module",name:He})}),ht={};g(ht,{default:()=>St});var Mt,wt,St,Rt=h(()=>{var r;wt=(Mt=import.meta.url,async function(i={}){function s(){return Sr.buffer!=tr.buffer&&In(),tr}function u(){return Sr.buffer!=tr.buffer&&In(),er}function c(){return Sr.buffer!=tr.buffer&&In(),pt}function p(){return Sr.buffer!=tr.buffer&&In(),zt}function d(){return Sr.buffer!=tr.buffer&&In(),ir}function b(){return Sr.buffer!=tr.buffer&&In(),Hr}function T(){return Sr.buffer!=tr.buffer&&In(),un}function E(){return Sr.buffer!=tr.buffer&&In(),Ap}var q,H,v=i,ne=new Promise((m,F)=>{q=m,H=F}),re=typeof window=="object",ce=typeof importScripts=="function",_e=ce&&self.name=="em-pthread";v.mountExternalData=(m,F)=>{m.startsWith("./")&&(m=m.substring(2)),(v.Ab||(v.Ab=new Map)).set(m,F)},v.unmountExternalData=()=>{delete v.Ab};var be=globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,shared:!0}).buffer.constructor;let he=()=>{let m=(K,oe,pe)=>(...Le)=>{let lt=ro,yt=oe==null?void 0:oe();Le=K(...Le);let $t=oe==null?void 0:oe();return yt!==$t&&(K=$t,pe(yt),oe=pe=null),ro!=lt?new Promise((Nt,lr)=>{Vm={resolve:Nt,reject:lr}}):Le},F=K=>async(...oe)=>{var pe;try{if(v.zb)throw Error("Session already started");let Le=v.zb={Ub:oe[0],errors:[]},lt=await K(...oe);if(v.zb!==Le)throw Error("Session mismatch");(pe=v.Eb)==null||pe.flush();let yt=Le.errors;if(0Nt),0<$t.length)throw Error($t.join(` +`))}return lt}finally{v.zb=null}};v._OrtCreateSession=m(v._OrtCreateSession,()=>v._OrtCreateSession,K=>v._OrtCreateSession=K),v._OrtRun=F(m(v._OrtRun,()=>v._OrtRun,K=>v._OrtRun=K)),v._OrtRunWithBinding=F(m(v._OrtRunWithBinding,()=>v._OrtRunWithBinding,K=>v._OrtRunWithBinding=K)),v._OrtBindInput=m(v._OrtBindInput,()=>v._OrtBindInput,K=>v._OrtBindInput=K),he=void 0};v.jsepInit=(m,F)=>{if(he==null||he(),m==="webgpu"){[v.Eb,v.Lb,v.Pb,v.Fb,v.Ob,v.hb,v.Qb,v.Sb,v.Mb,v.Nb,v.Rb]=F;let K=v.Eb;v.jsepRegisterBuffer=(oe,pe,Le,lt)=>K.registerBuffer(oe,pe,Le,lt),v.jsepGetBuffer=oe=>K.getBuffer(oe),v.jsepCreateDownloader=(oe,pe,Le)=>K.createDownloader(oe,pe,Le),v.jsepOnReleaseSession=oe=>{K.onReleaseSession(oe)},v.jsepOnRunStart=oe=>K.onRunStart(oe)}};var Fe,xe,Ie=Object.assign({},v),ct="./this.program",et=(m,F)=>{throw F},vt="";(re||ce)&&(ce?vt=self.location.href:typeof document<"u"&&document.currentScript&&(vt=document.currentScript.src),Mt&&(vt=Mt),vt=vt.startsWith("blob:")?"":vt.substr(0,vt.replace(/[?#].*/,"").lastIndexOf("/")+1),ce&&(xe=m=>{var F=new XMLHttpRequest;return F.open("GET",m,!1),F.responseType="arraybuffer",F.send(null),new Uint8Array(F.response)}),Fe=m=>Ry(m)?new Promise((F,K)=>{var oe=new XMLHttpRequest;oe.open("GET",m,!0),oe.responseType="arraybuffer",oe.onload=()=>{(oe.status==200||oe.status==0&&oe.response)&&K(oe.response),F(oe.status)},oe.onerror=F,oe.send(null)}):fetch(m,{credentials:"same-origin"}).then(F=>F.ok?F.arrayBuffer():Promise.reject(Error(F.status+" : "+F.url))));var Ft,Lt=console.log.bind(console),pr=console.error.bind(console),ar=Lt,nr=pr;if(Object.assign(v,Ie),Ie=null,_e){let m=function(F){try{var K=F.data,oe=K.cmd;if(oe==="load"){let pe=[];self.onmessage=Le=>pe.push(Le),self.startWorker=()=>{postMessage({cmd:"loaded"});for(let Le of pe)m(Le);self.onmessage=m};for(let Le of K.handlers)v[Le]&&!v[Le].proxy||(v[Le]=(...lt)=>{postMessage({Db:"callHandler",Yb:Le,args:lt})},Le=="print"&&(ar=v[Le]),Le=="printErr"&&(nr=v[Le]));Sr=K.wasmMemory,In(),yr(K.wasmModule)}else if(oe==="run"){Hm(K.pthread_ptr,0,0,1,0,0),Nm(K.pthread_ptr),wx(),qy(),qr||(jw(),qr=!0);try{vx(K.start_routine,K.arg)}catch(pe){if(pe!="unwind")throw pe}}else oe==="cancel"?El()&&Vp(-1):K.target!=="setimmediate"&&(oe==="checkMailbox"?qr&&zp():oe&&(nr(`worker: received unknown command ${oe}`),nr(K)))}catch(pe){throw Uw(),pe}};var yr,qr=!1;nr=function(...F){F=F.join(" "),console.error(F)},self.alert=function(...F){postMessage({Db:"alert",text:F.join(" "),$b:El()})},v.instantiateWasm=(F,K)=>new Promise(oe=>{yr=pe=>{pe=new WebAssembly.Instance(pe,jy()),K(pe),oe()}}),self.onunhandledrejection=F=>{throw F.reason||F},self.onmessage=m}v.wasmBinary&&(Ft=v.wasmBinary);var Sr,jr,It,tr,er,pt,zt,ir,Hr,un,xn,Yn,Ap,hi=!1;function In(){var m=Sr.buffer;v.HEAP8=tr=new Int8Array(m),v.HEAP16=pt=new Int16Array(m),v.HEAPU8=er=new Uint8Array(m),v.HEAPU16=zt=new Uint16Array(m),v.HEAP32=ir=new Int32Array(m),v.HEAPU32=Hr=new Uint32Array(m),v.HEAPF32=un=new Float32Array(m),v.HEAPF64=Ap=new Float64Array(m),v.HEAP64=xn=new BigInt64Array(m),v.HEAPU64=Yn=new BigUint64Array(m)}if(!_e){if(!((Sr=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0})).buffer instanceof be))throw nr("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");In()}var sf=[],Fn=[],Zn=[],Ci=0,es=null;function Ip(){if(--Ci==0&&es){var m=es;es=null,m()}}function kl(m){throw nr(m="Aborted("+m+")"),hi=!0,It=1,m=new WebAssembly.RuntimeError(m+". Build with -sASSERTIONS for more info."),H(m),m}var Pm,Ly=m=>m.startsWith("data:application/octet-stream;base64,"),Ry=m=>m.startsWith("file://");function By(m){if(m==Pm&&Ft)return new Uint8Array(Ft);if(xe)return xe(m);throw"both async and sync fetching of the wasm failed"}function Ny(m,F,K){return function(oe){return Ft?Promise.resolve().then(()=>By(oe)):Fe(oe).then(pe=>new Uint8Array(pe),()=>By(oe))}(m).then(oe=>WebAssembly.instantiate(oe,F)).then(K,oe=>{nr(`failed to asynchronously prepare wasm: ${oe}`),kl(oe)})}function jy(){return{a:{L:yx,xa:_x,b:xx,Z:Xy,y:Jy,na:ew,V:rw,X:nw,oa:iw,la:ow,ea:sw,ka:aw,I:lw,W:uw,T:cw,ma:dw,U:fw,sa:Mx,B:Tx,O:kx,N:Ex,A:Px,r:$x,p:Ax,C:Ix,x:Bx,P:Nx,ra:jx,ha:Ux,R:Vx,_:Wx,E:Gx,ga:Nm,qa:qx,t:Hx,D:Xx,o:Yx,m:Jx,c:Rm,n:eM,k:nM,ya:iM,q:oM,g:sM,u:aM,l:lM,f:uM,i:cM,j:dM,h:fM,e:pM,ba:hM,ca:mM,da:gM,$:Ew,aa:Cw,ua:_M,d:yM,M:wM,F:vM,J:bM,v:xM,pa:MM,S:TM,s:$w,w:kM,K:SM,Q:EM,wa:CM,va:PM,ia:Fw,ja:zw,Y:zm,z:Ow,H:Dw,fa:Lw,G:Rw,a:Sr,ta:Fm}}}var $m={858772:(m,F,K,oe)=>{if(v===void 0||!v.Ab)return 1;if((m=jn(m>>>0)).startsWith("./")&&(m=m.substring(2)),!(m=v.Ab.get(m)))return 2;if(oe>>>=0,(F>>>=0)+(K>>>=0)>m.byteLength)return 3;try{return u().set(m.subarray(F,F+K),oe>>>0),0}catch{return 4}},859273:()=>{v.Mb()},859304:()=>{v.Nb()},859333:()=>{v.Rb()},859358:m=>v.Lb(m),859391:m=>v.Pb(m),859423:(m,F,K)=>{v.Fb(m,F,K,!0)},859462:(m,F,K)=>{v.Fb(m,F,K)},859495:()=>typeof wasmOffsetConverter<"u",859552:m=>{v.hb("Abs",m,void 0)},859603:m=>{v.hb("Neg",m,void 0)},859654:m=>{v.hb("Floor",m,void 0)},859707:m=>{v.hb("Ceil",m,void 0)},859759:m=>{v.hb("Reciprocal",m,void 0)},859817:m=>{v.hb("Sqrt",m,void 0)},859869:m=>{v.hb("Exp",m,void 0)},859920:m=>{v.hb("Erf",m,void 0)},859971:m=>{v.hb("Sigmoid",m,void 0)},860026:(m,F,K)=>{v.hb("HardSigmoid",m,{alpha:F,beta:K})},860105:m=>{v.hb("Log",m,void 0)},860156:m=>{v.hb("Sin",m,void 0)},860207:m=>{v.hb("Cos",m,void 0)},860258:m=>{v.hb("Tan",m,void 0)},860309:m=>{v.hb("Asin",m,void 0)},860361:m=>{v.hb("Acos",m,void 0)},860413:m=>{v.hb("Atan",m,void 0)},860465:m=>{v.hb("Sinh",m,void 0)},860517:m=>{v.hb("Cosh",m,void 0)},860569:m=>{v.hb("Asinh",m,void 0)},860622:m=>{v.hb("Acosh",m,void 0)},860675:m=>{v.hb("Atanh",m,void 0)},860728:m=>{v.hb("Tanh",m,void 0)},860780:m=>{v.hb("Not",m,void 0)},860831:(m,F,K)=>{v.hb("Clip",m,{min:F,max:K})},860900:m=>{v.hb("Clip",m,void 0)},860952:(m,F)=>{v.hb("Elu",m,{alpha:F})},861010:m=>{v.hb("Gelu",m,void 0)},861062:m=>{v.hb("Relu",m,void 0)},861114:(m,F)=>{v.hb("LeakyRelu",m,{alpha:F})},861178:(m,F)=>{v.hb("ThresholdedRelu",m,{alpha:F})},861248:(m,F)=>{v.hb("Cast",m,{to:F})},861306:m=>{v.hb("Add",m,void 0)},861357:m=>{v.hb("Sub",m,void 0)},861408:m=>{v.hb("Mul",m,void 0)},861459:m=>{v.hb("Div",m,void 0)},861510:m=>{v.hb("Pow",m,void 0)},861561:m=>{v.hb("Equal",m,void 0)},861614:m=>{v.hb("Greater",m,void 0)},861669:m=>{v.hb("GreaterOrEqual",m,void 0)},861731:m=>{v.hb("Less",m,void 0)},861783:m=>{v.hb("LessOrEqual",m,void 0)},861842:(m,F,K,oe,pe)=>{v.hb("ReduceMean",m,{keepDims:!!F,noopWithEmptyAxes:!!K,axes:oe?Array.from(d().subarray(oe>>>0,pe>>>0)):[]})},862001:(m,F,K,oe,pe)=>{v.hb("ReduceMax",m,{keepDims:!!F,noopWithEmptyAxes:!!K,axes:oe?Array.from(d().subarray(oe>>>0,pe>>>0)):[]})},862159:(m,F,K,oe,pe)=>{v.hb("ReduceMin",m,{keepDims:!!F,noopWithEmptyAxes:!!K,axes:oe?Array.from(d().subarray(oe>>>0,pe>>>0)):[]})},862317:(m,F,K,oe,pe)=>{v.hb("ReduceProd",m,{keepDims:!!F,noopWithEmptyAxes:!!K,axes:oe?Array.from(d().subarray(oe>>>0,pe>>>0)):[]})},862476:(m,F,K,oe,pe)=>{v.hb("ReduceSum",m,{keepDims:!!F,noopWithEmptyAxes:!!K,axes:oe?Array.from(d().subarray(oe>>>0,pe>>>0)):[]})},862634:(m,F,K,oe,pe)=>{v.hb("ReduceL1",m,{keepDims:!!F,noopWithEmptyAxes:!!K,axes:oe?Array.from(d().subarray(oe>>>0,pe>>>0)):[]})},862791:(m,F,K,oe,pe)=>{v.hb("ReduceL2",m,{keepDims:!!F,noopWithEmptyAxes:!!K,axes:oe?Array.from(d().subarray(oe>>>0,pe>>>0)):[]})},862948:(m,F,K,oe,pe)=>{v.hb("ReduceLogSum",m,{keepDims:!!F,noopWithEmptyAxes:!!K,axes:oe?Array.from(d().subarray(oe>>>0,pe>>>0)):[]})},863109:(m,F,K,oe,pe)=>{v.hb("ReduceSumSquare",m,{keepDims:!!F,noopWithEmptyAxes:!!K,axes:oe?Array.from(d().subarray(oe>>>0,pe>>>0)):[]})},863273:(m,F,K,oe,pe)=>{v.hb("ReduceLogSumExp",m,{keepDims:!!F,noopWithEmptyAxes:!!K,axes:oe?Array.from(d().subarray(oe>>>0,pe>>>0)):[]})},863437:m=>{v.hb("Where",m,void 0)},863490:(m,F,K)=>{v.hb("Transpose",m,{perm:F?Array.from(d().subarray(F>>>0,K>>>0)):[]})},863598:(m,F,K,oe)=>{v.hb("DepthToSpace",m,{blocksize:F,mode:jn(K),format:oe?"NHWC":"NCHW"})},863731:(m,F,K,oe)=>{v.hb("DepthToSpace",m,{blocksize:F,mode:jn(K),format:oe?"NHWC":"NCHW"})},863864:(m,F,K,oe,pe,Le,lt,yt,$t,Nt,lr,Ar,Lr,zn,Cl)=>{v.hb("ConvTranspose",m,{format:$t?"NHWC":"NCHW",autoPad:F,dilations:[K],group:oe,kernelShape:[pe],pads:[Le,lt],strides:[yt],wIsConst:()=>!!s()[Nt>>>0],outputPadding:lr?Array.from(d().subarray(lr>>>0,Ar>>>0)):[],outputShape:Lr?Array.from(d().subarray(Lr>>>0,zn>>>0)):[],activation:jn(Cl)})},864265:(m,F,K,oe,pe,Le,lt,yt,$t,Nt,lr,Ar,Lr,zn)=>{v.hb("ConvTranspose",m,{format:yt?"NHWC":"NCHW",autoPad:F,dilations:Array.from(d().subarray(K>>>0,2+(K>>>0)>>>0)),group:oe,kernelShape:Array.from(d().subarray(pe>>>0,2+(pe>>>0)>>>0)),pads:Array.from(d().subarray(Le>>>0,4+(Le>>>0)>>>0)),strides:Array.from(d().subarray(lt>>>0,2+(lt>>>0)>>>0)),wIsConst:()=>!!s()[$t>>>0],outputPadding:Nt?Array.from(d().subarray(Nt>>>0,lr>>>0)):[],outputShape:Ar?Array.from(d().subarray(Ar>>>0,Lr>>>0)):[],activation:jn(zn)})},864830:(m,F,K,oe,pe,Le,lt,yt,$t,Nt,lr,Ar,Lr,zn,Cl)=>{v.hb("ConvTranspose",m,{format:$t?"NHWC":"NCHW",autoPad:F,dilations:[K],group:oe,kernelShape:[pe],pads:[Le,lt],strides:[yt],wIsConst:()=>!!s()[Nt>>>0],outputPadding:lr?Array.from(d().subarray(lr>>>0,Ar>>>0)):[],outputShape:Lr?Array.from(d().subarray(Lr>>>0,zn>>>0)):[],activation:jn(Cl)})},865231:(m,F,K,oe,pe,Le,lt,yt,$t,Nt,lr,Ar,Lr,zn)=>{v.hb("ConvTranspose",m,{format:yt?"NHWC":"NCHW",autoPad:F,dilations:Array.from(d().subarray(K>>>0,2+(K>>>0)>>>0)),group:oe,kernelShape:Array.from(d().subarray(pe>>>0,2+(pe>>>0)>>>0)),pads:Array.from(d().subarray(Le>>>0,4+(Le>>>0)>>>0)),strides:Array.from(d().subarray(lt>>>0,2+(lt>>>0)>>>0)),wIsConst:()=>!!s()[$t>>>0],outputPadding:Nt?Array.from(d().subarray(Nt>>>0,lr>>>0)):[],outputShape:Ar?Array.from(d().subarray(Ar>>>0,Lr>>>0)):[],activation:jn(zn)})},865796:(m,F)=>{v.hb("GlobalAveragePool",m,{format:F?"NHWC":"NCHW"})},865887:(m,F,K,oe,pe,Le,lt,yt,$t,Nt,lr,Ar,Lr,zn)=>{v.hb("AveragePool",m,{format:zn?"NHWC":"NCHW",auto_pad:F,ceil_mode:K,count_include_pad:oe,storage_order:pe,dilations:Le?Array.from(d().subarray(Le>>>0,lt>>>0)):[],kernel_shape:yt?Array.from(d().subarray(yt>>>0,$t>>>0)):[],pads:Nt?Array.from(d().subarray(Nt>>>0,lr>>>0)):[],strides:Ar?Array.from(d().subarray(Ar>>>0,Lr>>>0)):[]})},866302:(m,F)=>{v.hb("GlobalAveragePool",m,{format:F?"NHWC":"NCHW"})},866393:(m,F,K,oe,pe,Le,lt,yt,$t,Nt,lr,Ar,Lr,zn)=>{v.hb("AveragePool",m,{format:zn?"NHWC":"NCHW",auto_pad:F,ceil_mode:K,count_include_pad:oe,storage_order:pe,dilations:Le?Array.from(d().subarray(Le>>>0,lt>>>0)):[],kernel_shape:yt?Array.from(d().subarray(yt>>>0,$t>>>0)):[],pads:Nt?Array.from(d().subarray(Nt>>>0,lr>>>0)):[],strides:Ar?Array.from(d().subarray(Ar>>>0,Lr>>>0)):[]})},866808:(m,F)=>{v.hb("GlobalMaxPool",m,{format:F?"NHWC":"NCHW"})},866895:(m,F,K,oe,pe,Le,lt,yt,$t,Nt,lr,Ar,Lr,zn)=>{v.hb("MaxPool",m,{format:zn?"NHWC":"NCHW",auto_pad:F,ceil_mode:K,count_include_pad:oe,storage_order:pe,dilations:Le?Array.from(d().subarray(Le>>>0,lt>>>0)):[],kernel_shape:yt?Array.from(d().subarray(yt>>>0,$t>>>0)):[],pads:Nt?Array.from(d().subarray(Nt>>>0,lr>>>0)):[],strides:Ar?Array.from(d().subarray(Ar>>>0,Lr>>>0)):[]})},867306:(m,F)=>{v.hb("GlobalMaxPool",m,{format:F?"NHWC":"NCHW"})},867393:(m,F,K,oe,pe,Le,lt,yt,$t,Nt,lr,Ar,Lr,zn)=>{v.hb("MaxPool",m,{format:zn?"NHWC":"NCHW",auto_pad:F,ceil_mode:K,count_include_pad:oe,storage_order:pe,dilations:Le?Array.from(d().subarray(Le>>>0,lt>>>0)):[],kernel_shape:yt?Array.from(d().subarray(yt>>>0,$t>>>0)):[],pads:Nt?Array.from(d().subarray(Nt>>>0,lr>>>0)):[],strides:Ar?Array.from(d().subarray(Ar>>>0,Lr>>>0)):[]})},867804:(m,F,K,oe,pe)=>{v.hb("Gemm",m,{alpha:F,beta:K,transA:oe,transB:pe})},867908:m=>{v.hb("MatMul",m,void 0)},867962:(m,F,K,oe)=>{v.hb("ArgMax",m,{keepDims:!!F,selectLastIndex:!!K,axis:oe})},868070:(m,F,K,oe)=>{v.hb("ArgMin",m,{keepDims:!!F,selectLastIndex:!!K,axis:oe})},868178:(m,F)=>{v.hb("Softmax",m,{axis:F})},868241:(m,F)=>{v.hb("Concat",m,{axis:F})},868301:(m,F,K,oe,pe)=>{v.hb("Split",m,{axis:F,numOutputs:K,splitSizes:oe?Array.from(d().subarray(oe>>>0,pe>>>0)):[]})},868441:m=>{v.hb("Expand",m,void 0)},868495:(m,F)=>{v.hb("Gather",m,{axis:Number(F)})},868566:(m,F)=>{v.hb("GatherElements",m,{axis:Number(F)})},868645:(m,F,K,oe,pe,Le,lt,yt,$t,Nt,lr)=>{v.hb("Resize",m,{antialias:F,axes:K?Array.from(d().subarray(K>>>0,oe>>>0)):[],coordinateTransformMode:jn(pe),cubicCoeffA:Le,excludeOutside:lt,extrapolationValue:yt,keepAspectRatioPolicy:jn($t),mode:jn(Nt),nearestMode:jn(lr)})},868991:(m,F,K,oe,pe,Le,lt)=>{v.hb("Slice",m,{starts:F?Array.from(d().subarray(F>>>0,K>>>0)):[],ends:oe?Array.from(d().subarray(oe>>>0,pe>>>0)):[],axes:Le?Array.from(d().subarray(Le>>>0,lt>>>0)):[]})},869207:m=>{v.hb("Tile",m,void 0)},869259:(m,F,K)=>{v.hb("InstanceNormalization",m,{epsilon:F,format:K?"NHWC":"NCHW"})},869373:(m,F,K)=>{v.hb("InstanceNormalization",m,{epsilon:F,format:K?"NHWC":"NCHW"})},869487:m=>{v.hb("Range",m,void 0)},869540:(m,F)=>{v.hb("Einsum",m,{equation:jn(F)})},869621:(m,F,K,oe,pe)=>{v.hb("Pad",m,{mode:F,value:K,pads:oe?Array.from(d().subarray(oe>>>0,pe>>>0)):[]})},869748:(m,F,K,oe,pe,Le)=>{v.hb("BatchNormalization",m,{epsilon:F,momentum:K,spatial:!!pe,trainingMode:!!oe,format:Le?"NHWC":"NCHW"})},869917:(m,F,K,oe,pe,Le)=>{v.hb("BatchNormalization",m,{epsilon:F,momentum:K,spatial:!!pe,trainingMode:!!oe,format:Le?"NHWC":"NCHW"})},870086:(m,F,K)=>{v.hb("CumSum",m,{exclusive:Number(F),reverse:Number(K)})},870183:(m,F,K)=>{v.hb("DequantizeLinear",m,{axis:F,blockSize:K})},870273:(m,F,K,oe,pe,Le,lt,yt,$t)=>{v.hb("Attention",m,{numHeads:F,isUnidirectional:K,maskFilterValue:oe,scale:pe,doRotary:Le,qkvHiddenSizes:lt?Array.from(d().subarray(Number(yt)>>>0,Number(yt)+lt>>>0)):[],pastPresentShareBuffer:!!$t})},870545:m=>{v.hb("BiasAdd",m,void 0)},870600:m=>{v.hb("BiasSplitGelu",m,void 0)},870661:m=>{v.hb("FastGelu",m,void 0)},870717:(m,F,K,oe,pe,Le,lt,yt,$t,Nt,lr,Ar,Lr,zn,Cl,IM)=>{v.hb("Conv",m,{format:Ar?"NHWC":"NCHW",auto_pad:F,dilations:K?Array.from(d().subarray(K>>>0,oe>>>0)):[],group:pe,kernel_shape:Le?Array.from(d().subarray(Le>>>0,lt>>>0)):[],pads:yt?Array.from(d().subarray(yt>>>0,$t>>>0)):[],strides:Nt?Array.from(d().subarray(Nt>>>0,lr>>>0)):[],w_is_const:()=>!!s()[Lr>>>0],activation:jn(zn),activation_params:Cl?Array.from(T().subarray(Cl>>>0,IM>>>0)):[]})},871213:m=>{v.hb("Gelu",m,void 0)},871265:(m,F,K,oe)=>{v.hb("GroupQueryAttention",m,{numHeads:F,kvNumHeads:K,scale:oe})},871378:(m,F,K,oe)=>{v.hb("LayerNormalization",m,{axis:F,epsilon:K,simplified:!!oe})},871489:(m,F,K,oe)=>{v.hb("LayerNormalization",m,{axis:F,epsilon:K,simplified:!!oe})},871600:(m,F,K,oe,pe,Le)=>{v.hb("MatMulNBits",m,{k:F,n:K,accuracyLevel:oe,bits:pe,blockSize:Le})},871727:(m,F,K,oe,pe,Le)=>{v.hb("MultiHeadAttention",m,{numHeads:F,isUnidirectional:K,maskFilterValue:oe,scale:pe,doRotary:Le})},871886:(m,F)=>{v.hb("QuickGelu",m,{alpha:F})},871950:(m,F,K,oe,pe)=>{v.hb("RotaryEmbedding",m,{interleaved:!!F,numHeads:K,rotaryEmbeddingDim:oe,scale:pe})},872089:(m,F,K)=>{v.hb("SkipLayerNormalization",m,{epsilon:F,simplified:!!K})},872191:m=>{v.Qb(m)},872225:(m,F)=>v.Sb(m,F,v.zb.Ub,v.zb.errors),872337:(m,F,K)=>{v.hb("SkipLayerNormalization",m,{epsilon:F,simplified:!!K})}};function _x(m,F,K){return bw(async()=>{await v.Ob(m,F,K)})}function yx(){return typeof wasmOffsetConverter<"u"}function Am(m){this.name="ExitStatus",this.message=`Program terminated with exit(${m})`,this.status=m}var Im=m=>{m.terminate(),m.onmessage=()=>{}},Uy=m=>{ts.length==0&&(Ky(),Hy(ts[0]));var F=ts.pop();if(!F)return 6;Qs.push(F),eo[m.sb]=F,F.sb=m.sb;var K={cmd:"run",start_routine:m.Vb,arg:m.Hb,pthread_ptr:m.sb};return F.postMessage(K,m.Wb),0},Ks=0,Jr=(m,F,...K)=>{for(var oe=2*K.length,pe=Xm(),Le=Qm(8*oe),lt=Le>>>3,yt=0;yt>>0]=$t)}return m=Vw(m,0,oe,Le,F),Wp(pe),m};function Fm(m){if(_e)return Jr(0,1,m);if(It=m,!(0{if(It=m,_e)throw Vy(m),"unwind";Fm(m)},ts=[],Qs=[],Wy=[],eo={},Gy=m=>{var F=m.sb;delete eo[F],ts.push(m),Qs.splice(Qs.indexOf(m),1),m.sb=0,Km(F)};function qy(){Wy.forEach(m=>m())}var Hy=m=>new Promise(F=>{m.onmessage=pe=>{var Le=(pe=pe.data).cmd;if(pe.targetThread&&pe.targetThread!=El()){var lt=eo[pe.targetThread];lt?lt.postMessage(pe,pe.transferList):nr(`Internal error! Worker sent a message "${Le}" to target pthread ${pe.targetThread}, but that thread no longer exists!`)}else Le==="checkMailbox"?zp():Le==="spawnThread"?Uy(pe):Le==="cleanupThread"?Gy(eo[pe.thread]):Le==="killThread"?(pe=pe.thread,Le=eo[pe],delete eo[pe],Im(Le),Km(pe),Qs.splice(Qs.indexOf(Le),1),Le.sb=0):Le==="cancelThread"?eo[pe.thread].postMessage({cmd:"cancel"}):Le==="loaded"?(m.loaded=!0,F(m)):Le==="alert"?alert(`Thread ${pe.threadId}: ${pe.text}`):pe.target==="setimmediate"?m.postMessage(pe):Le==="callHandler"?v[pe.handler](...pe.args):Le&&nr(`worker sent an unknown command ${Le}`)},m.onerror=pe=>{throw nr(`worker sent an error! ${pe.filename}:${pe.lineno}: ${pe.message}`),pe};var K,oe=[];for(K of[])v.propertyIsEnumerable(K)&&oe.push(K);m.postMessage({cmd:"load",handlers:oe,wasmMemory:Sr,wasmModule:jr})});function Ky(){var m=new Worker(new URL(import.meta.url),{type:"module",workerData:"em-pthread",name:"em-pthread"});ts.push(m)}var Fp=m=>{for(;0{var m=El(),F=b()[m+52>>>2>>>0];m=b()[m+56>>>2>>>0],Gw(F,F-m),Wp(F)},vx=(m,F)=>{Ks=0,m=qw(m,F),0>>=0);throw F>>>=0,K>>>=0,b()[oe.Bb+16>>>2>>>0]=0,b()[oe.Bb+4>>>2>>>0]=F,b()[oe.Bb+8>>>2>>>0]=K,m}function Qy(m,F,K,oe){return _e?Jr(2,1,m,F,K,oe):Xy(m,F,K,oe)}function Xy(m,F,K,oe){if(m>>>=0,F>>>=0,K>>>=0,oe>>>=0,be===void 0)return nr("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var pe=[];return _e&&pe.length===0?Qy(m,F,K,oe):(m={Vb:K,sb:m,Hb:oe,Wb:pe},_e?(m.Db="spawnThread",postMessage(m,pe),0):Uy(m))}var Yy=typeof TextDecoder<"u"?new TextDecoder:void 0,Zy=(m,F,K)=>{var oe=(F>>>=0)+K;for(K=F;m[K]&&!(K>=oe);)++K;if(16(pe=(240&pe)==224?(15&pe)<<12|Le<<6|lt:(7&pe)<<18|Le<<12|lt<<6|63&m[F++])?oe+=String.fromCharCode(pe):(pe-=65536,oe+=String.fromCharCode(55296|pe>>10,56320|1023&pe))}}else oe+=String.fromCharCode(pe)}return oe},jn=(m,F)=>(m>>>=0)?Zy(u(),m,F):"";function Jy(m,F,K){return _e?Jr(3,1,m,F,K):0}function ew(m,F){if(_e)return Jr(4,1,m,F)}var tw=m=>{for(var F=0,K=0;K=oe?F++:2047>=oe?F+=2:55296<=oe&&57343>=oe?(F+=4,++K):F+=3}return F},Sl=(m,F,K)=>{var oe=u();if(F>>>=0,0=lt&&(lt=65536+((1023<)<<10)|1023&m.charCodeAt(++Le)),127>=lt){if(F>=K)break;oe[F++>>>0]=lt}else{if(2047>=lt){if(F+1>=K)break;oe[F++>>>0]=192|lt>>6}else{if(65535>=lt){if(F+2>=K)break;oe[F++>>>0]=224|lt>>12}else{if(F+3>=K)break;oe[F++>>>0]=240|lt>>18,oe[F++>>>0]=128|lt>>12&63}oe[F++>>>0]=128|lt>>6&63}oe[F++>>>0]=128|63<}}oe[F>>>0]=0,m=F-pe}else m=0;return m};function rw(m,F){if(_e)return Jr(5,1,m,F)}function nw(m,F,K){if(_e)return Jr(6,1,m,F,K)}function iw(m,F,K){return _e?Jr(7,1,m,F,K):0}function ow(m,F){if(_e)return Jr(8,1,m,F)}function sw(m,F,K){if(_e)return Jr(9,1,m,F,K)}function aw(m,F,K,oe){if(_e)return Jr(10,1,m,F,K,oe)}function lw(m,F,K,oe){if(_e)return Jr(11,1,m,F,K,oe)}function uw(m,F,K,oe){if(_e)return Jr(12,1,m,F,K,oe)}function cw(m){if(_e)return Jr(13,1,m)}function dw(m,F){if(_e)return Jr(14,1,m,F)}function fw(m,F,K){if(_e)return Jr(15,1,m,F,K)}var pw,rs,Mx=()=>{kl("")},to=m=>{for(var F="";u()[m>>>0];)F+=pw[u()[m++>>>0]];return F},Om={},Dm={};function bo(m,F,K={}){if(!("argPackAdvance"in F))throw new TypeError("registerType registeredInstance requires argPackAdvance");return function(oe,pe,Le={}){var lt=pe.name;if(!oe)throw new rs(`type "${lt}" must have a positive integer typeid pointer`);if(Dm.hasOwnProperty(oe)){if(Le.Jb)return;throw new rs(`Cannot register type '${lt}' twice`)}Dm[oe]=pe,Om.hasOwnProperty(oe)&&(pe=Om[oe],delete Om[oe],pe.forEach(yt=>yt()))}(m,F,K)}var hw=(m,F,K)=>{switch(F){case 1:return K?oe=>s()[oe>>>0]:oe=>u()[oe>>>0];case 2:return K?oe=>c()[oe>>>1>>>0]:oe=>p()[oe>>>1>>>0];case 4:return K?oe=>d()[oe>>>2>>>0]:oe=>b()[oe>>>2>>>0];case 8:return K?oe=>xn[oe>>>3]:oe=>Yn[oe>>>3];default:throw new TypeError(`invalid integer width (${F}): ${m}`)}};function Tx(m,F,K){K>>>=0,bo(m>>>=0,{name:F=to(F>>>0),fromWireType:oe=>oe,toWireType:function(oe,pe){if(typeof pe!="bigint"&&typeof pe!="number")throw pe=pe===null?"null":(oe=typeof pe)=="object"||oe==="array"||oe==="function"?pe.toString():""+pe,new TypeError(`Cannot convert "${pe}" to ${this.name}`);return typeof pe=="number"&&(pe=BigInt(pe)),pe},argPackAdvance:ns,readValueFromPointer:hw(F,K,F.indexOf("u")==-1),yb:null})}var ns=8;function kx(m,F,K,oe){bo(m>>>=0,{name:F=to(F>>>0),fromWireType:function(pe){return!!pe},toWireType:function(pe,Le){return Le?K:oe},argPackAdvance:ns,readValueFromPointer:function(pe){return this.fromWireType(u()[pe>>>0])},yb:null})}var Lm=[],xo=[];function Rm(m){9<(m>>>=0)&&--xo[m+1]==0&&(xo[m]=void 0,Lm.push(m))}var Pi=m=>{if(!m)throw new rs("Cannot use deleted val. handle = "+m);return xo[m]},$i=m=>{switch(m){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let F=Lm.pop()||xo.length;return xo[F]=m,xo[F+1]=1,F}};function Bm(m){return this.fromWireType(b()[m>>>2>>>0])}var Sx={name:"emscripten::val",fromWireType:m=>{var F=Pi(m);return Rm(m),F},toWireType:(m,F)=>$i(F),argPackAdvance:ns,readValueFromPointer:Bm,yb:null};function Ex(m){return bo(m>>>0,Sx)}var Cx=(m,F)=>{switch(F){case 4:return function(K){return this.fromWireType(T()[K>>>2>>>0])};case 8:return function(K){return this.fromWireType(E()[K>>>3>>>0])};default:throw new TypeError(`invalid float width (${F}): ${m}`)}};function Px(m,F,K){K>>>=0,bo(m>>>=0,{name:F=to(F>>>0),fromWireType:oe=>oe,toWireType:(oe,pe)=>pe,argPackAdvance:ns,readValueFromPointer:Cx(F,K),yb:null})}function $x(m,F,K,oe,pe){if(m>>>=0,K>>>=0,F=to(F>>>0),pe===-1&&(pe=4294967295),pe=yt=>yt,oe===0){var Le=32-8*K;pe=yt=>yt<>>Le}var lt=F.includes("unsigned")?function(yt,$t){return $t>>>0}:function(yt,$t){return $t};bo(m,{name:F,fromWireType:pe,toWireType:lt,argPackAdvance:ns,readValueFromPointer:hw(F,K,oe!==0),yb:null})}function Ax(m,F,K){function oe(Le){var lt=b()[Le>>>2>>>0];return Le=b()[Le+4>>>2>>>0],new pe(s().buffer,Le,lt)}var pe=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][F];bo(m>>>=0,{name:K=to(K>>>0),fromWireType:oe,argPackAdvance:ns,readValueFromPointer:oe},{Jb:!0})}function Ix(m,F){m>>>=0;var K=(F=to(F>>>0))==="std::string";bo(m,{name:F,fromWireType:function(oe){var pe=b()[oe>>>2>>>0],Le=oe+4;if(K)for(var lt=Le,yt=0;yt<=pe;++yt){var $t=Le+yt;if(yt==pe||u()[$t>>>0]==0){if(lt=jn(lt,$t-lt),Nt===void 0)var Nt=lt;else Nt+="\0",Nt+=lt;lt=$t+1}}else{for(Nt=Array(pe),yt=0;yt>>0]);Nt=Nt.join("")}return no(oe),Nt},toWireType:function(oe,pe){pe instanceof ArrayBuffer&&(pe=new Uint8Array(pe));var Le=typeof pe=="string";if(!(Le||pe instanceof Uint8Array||pe instanceof Uint8ClampedArray||pe instanceof Int8Array))throw new rs("Cannot pass non-string to std::string");var lt=K&&Le?tw(pe):pe.length,yt=Up(4+lt+1),$t=yt+4;if(b()[yt>>>2>>>0]=lt,K&&Le)Sl(pe,$t,lt+1);else if(Le)for(Le=0;Le>>0]=Nt}else for(Le=0;Le>>0]=pe[Le];return oe!==null&&oe.push(no,yt),yt},argPackAdvance:ns,readValueFromPointer:Bm,yb(oe){no(oe)}})}var mw=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,Fx=(m,F)=>{for(var K=m>>1,oe=K+F/2;!(K>=oe)&&p()[K>>>0];)++K;if(32<(K<<=1)-m&&mw)return mw.decode(u().slice(m,K));for(K="",oe=0;!(oe>=F/2);++oe){var pe=c()[m+2*oe>>>1>>>0];if(pe==0)break;K+=String.fromCharCode(pe)}return K},zx=(m,F,K)=>{if(K??(K=2147483647),2>K)return 0;var oe=F;K=(K-=2)<2*m.length?K/2:m.length;for(var pe=0;pe>>1>>>0]=Le,F+=2}return c()[F>>>1>>>0]=0,F-oe},Ox=m=>2*m.length,Dx=(m,F)=>{for(var K=0,oe="";!(K>=F/4);){var pe=d()[m+4*K>>>2>>>0];if(pe==0)break;++K,65536<=pe?(pe-=65536,oe+=String.fromCharCode(55296|pe>>10,56320|1023&pe)):oe+=String.fromCharCode(pe)}return oe},Lx=(m,F,K)=>{if(F>>>=0,K??(K=2147483647),4>K)return 0;var oe=F;K=oe+K-4;for(var pe=0;pe=Le&&(Le=65536+((1023&Le)<<10)|1023&m.charCodeAt(++pe)),d()[F>>>2>>>0]=Le,(F+=4)+4>K)break}return d()[F>>>2>>>0]=0,F-oe},Rx=m=>{for(var F=0,K=0;K=oe&&++K,F+=4}return F};function Bx(m,F,K){if(m>>>=0,F>>>=0,K=to(K>>>=0),F===2)var oe=Fx,pe=zx,Le=Ox,lt=yt=>p()[yt>>>1>>>0];else F===4&&(oe=Dx,pe=Lx,Le=Rx,lt=yt=>b()[yt>>>2>>>0]);bo(m,{name:K,fromWireType:yt=>{for(var $t,Nt=b()[yt>>>2>>>0],lr=yt+4,Ar=0;Ar<=Nt;++Ar){var Lr=yt+4+Ar*F;Ar!=Nt&<(Lr)!=0||(lr=oe(lr,Lr-lr),$t===void 0?$t=lr:($t+="\0",$t+=lr),lr=Lr+F)}return no(yt),$t},toWireType:(yt,$t)=>{if(typeof $t!="string")throw new rs(`Cannot pass non-string to C++ string type ${K}`);var Nt=Le($t),lr=Up(4+Nt+F);return b()[lr>>>2>>>0]=Nt/F,pe($t,lr+4,Nt+F),yt!==null&&yt.push(no,lr),lr},argPackAdvance:ns,readValueFromPointer:Bm,yb(yt){no(yt)}})}function Nx(m,F){bo(m>>>=0,{Kb:!0,name:F=to(F>>>0),argPackAdvance:0,fromWireType:()=>{},toWireType:()=>{}})}var jx=()=>1;function Ux(m){Hm(m>>>0,!ce,1,!re,131072,!1),qy()}var gw=m=>{if(!hi)try{if(m(),!(0>>=0,typeof Atomics.Xb=="function"&&(Atomics.Xb(d(),m>>>2,m).value.then(zp),m+=128,Atomics.store(d(),m>>>2,1))}var zp=()=>{var m=El();m&&(Nm(m),gw(Ww))};function Vx(m,F){(m>>>=0)==F>>>0?setTimeout(zp):_e?postMessage({targetThread:m,cmd:"checkMailbox"}):(m=eo[m])&&m.postMessage({cmd:"checkMailbox"})}var jm=[];function Wx(m,F,K,oe,pe){for(F>>>=0,oe/=2,jm.length=oe,K=pe>>>0>>>3,pe=0;pe>>0];return(F?$m[F]:AM[m])(...jm)}function Gx(m){m>>>=0,_e?postMessage({cmd:"cleanupThread",thread:m}):Gy(eo[m])}function qx(m){}var Um=(m,F)=>{var K=Dm[m];if(K===void 0)throw m=Nw(m),K=to(m),no(m),new rs(`${F} has unknown type ${K}`);return K},_w=(m,F,K)=>{var oe=[];return m=m.toWireType(oe,K),oe.length&&(b()[F>>>2>>>0]=$i(oe)),m};function Hx(m,F,K){return F>>>=0,K>>>=0,m=Pi(m>>>0),F=Um(F,"emval::as"),_w(F,K,m)}var Op=m=>{try{m()}catch(F){kl(F)}},is=0,ro=null,yw=0,Dp=[],ww={},vw={},Kx=0,Vm=null,Qx=[];function bw(m){return function(F){if(!hi){if(is===0){var K=!1,oe=!1;F((pe=0)=>{if(!hi&&(yw=pe,K=!0,oe)){is=2,Op(()=>Qw(ro)),typeof Browser<"u"&&Browser.Cb.Ib&&Browser.Cb.resume(),pe=!1;try{var Le=function(){var $t=d()[ro+8>>>2>>>0];return $t=Ht[vw[$t]],--Ks,$t()}()}catch($t){Le=$t,pe=!0}var lt=!1;if(!ro){var yt=Vm;yt&&(Vm=null,(pe?yt.reject:yt.resolve)(Le),lt=!0)}if(pe&&!lt)throw Le}}),oe=!0,K||(is=1,ro=function(){var pe=Up(65548),Le=pe+12;b()[pe>>>2>>>0]=Le,b()[pe+4>>>2>>>0]=Le+65536,Le=Dp[0];var lt=ww[Le];return lt===void 0&&(lt=Kx++,ww[Le]=lt,vw[lt]=Le),Le=lt,d()[pe+8>>>2>>>0]=Le,pe}(),typeof Browser<"u"&&Browser.Cb.Ib&&Browser.Cb.pause(),Op(()=>Hw(ro)))}else is===2?(is=0,Op(Xw),no(ro),ro=null,Qx.forEach(gw)):kl(`invalid state: ${is}`);return yw}}(F=>{m().then(F)})}function Xx(m){return m>>>=0,bw(()=>(m=Pi(m)).then($i))}var Lp=[];function Yx(m,F,K,oe){return K>>>=0,oe>>>=0,(m=Lp[m>>>0])(null,F=Pi(F>>>0),K,oe)}var Zx={},Rp=m=>{var F=Zx[m];return F===void 0?to(m):F};function Jx(m,F,K,oe,pe){return K>>>=0,oe>>>=0,pe>>>=0,(m=Lp[m>>>0])(F=Pi(F>>>0),F[K=Rp(K)],oe,pe)}var xw=()=>typeof globalThis=="object"?globalThis:Function("return this")();function eM(m){return(m>>>=0)==0?$i(xw()):(m=Rp(m),$i(xw()[m]))}var tM=m=>{var F=Lp.length;return Lp.push(m),F},rM=(m,F)=>{for(var K=Array(m),oe=0;oe>>2>>>0],"parameter "+oe);return K},Mw=(m,F)=>Object.defineProperty(F,"name",{value:m});function nM(m,F,K){var oe=(F=rM(m,F>>>0)).shift();m--;var pe=`return function (obj, func, destructorsRef, args) { +`,Le=0,lt=[];K===0&<.push("obj");for(var yt=["retType"],$t=[oe],Nt=0;Ntlr.name).join(", ")}) => ${oe.name}>`,tM(Mw(K,m))}function iM(m){return m=Rp(m>>>0),$i(v[m])}function oM(m,F){return F>>>=0,m=Pi(m>>>0),F=Pi(F),$i(m[F])}function sM(m){9<(m>>>=0)&&(xo[m+1]+=1)}function aM(){return $i([])}function lM(m){m=Pi(m>>>0);for(var F=Array(m.length),K=0;K>>0))}function cM(){return $i({})}function dM(m){for(var F=Pi(m>>>=0);F.length;){var K=F.pop();F.pop()(K)}Rm(m)}function fM(m,F,K){F>>>=0,K>>>=0,m=Pi(m>>>0),F=Pi(F),K=Pi(K),m[F]=K}function pM(m,F){return F>>>=0,m=(m=Um(m>>>0,"_emval_take_value")).readValueFromPointer(F),$i(m)}function hM(m,F){m=-9007199254740992>m||9007199254740992>>=0,m=new Date(1e3*m),d()[F>>>2>>>0]=m.getUTCSeconds(),d()[F+4>>>2>>>0]=m.getUTCMinutes(),d()[F+8>>>2>>>0]=m.getUTCHours(),d()[F+12>>>2>>>0]=m.getUTCDate(),d()[F+16>>>2>>>0]=m.getUTCMonth(),d()[F+20>>>2>>>0]=m.getUTCFullYear()-1900,d()[F+24>>>2>>>0]=m.getUTCDay(),m=(m.getTime()-Date.UTC(m.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,d()[F+28>>>2>>>0]=m}var Tw=m=>m%4==0&&(m%100!=0||m%400==0),kw=[0,31,60,91,121,152,182,213,244,274,305,335],Sw=[0,31,59,90,120,151,181,212,243,273,304,334];function mM(m,F){m=-9007199254740992>m||9007199254740992>>=0,m=new Date(1e3*m),d()[F>>>2>>>0]=m.getSeconds(),d()[F+4>>>2>>>0]=m.getMinutes(),d()[F+8>>>2>>>0]=m.getHours(),d()[F+12>>>2>>>0]=m.getDate(),d()[F+16>>>2>>>0]=m.getMonth(),d()[F+20>>>2>>>0]=m.getFullYear()-1900,d()[F+24>>>2>>>0]=m.getDay();var K=(Tw(m.getFullYear())?kw:Sw)[m.getMonth()]+m.getDate()-1|0;d()[F+28>>>2>>>0]=K,d()[F+36>>>2>>>0]=-60*m.getTimezoneOffset(),K=new Date(m.getFullYear(),6,1).getTimezoneOffset();var oe=new Date(m.getFullYear(),0,1).getTimezoneOffset();m=0|(K!=oe&&m.getTimezoneOffset()==Math.min(oe,K)),d()[F+32>>>2>>>0]=m}function gM(m){m>>>=0;var F=new Date(d()[m+20>>>2>>>0]+1900,d()[m+16>>>2>>>0],d()[m+12>>>2>>>0],d()[m+8>>>2>>>0],d()[m+4>>>2>>>0],d()[m>>>2>>>0],0),K=d()[m+32>>>2>>>0],oe=F.getTimezoneOffset(),pe=new Date(F.getFullYear(),6,1).getTimezoneOffset(),Le=new Date(F.getFullYear(),0,1).getTimezoneOffset(),lt=Math.min(Le,pe);return 0>K?d()[m+32>>>2>>>0]=+(pe!=Le&<==oe):0>>2>>>0]=F.getDay(),K=(Tw(F.getFullYear())?kw:Sw)[F.getMonth()]+F.getDate()-1|0,d()[m+28>>>2>>>0]=K,d()[m>>>2>>>0]=F.getSeconds(),d()[m+4>>>2>>>0]=F.getMinutes(),d()[m+8>>>2>>>0]=F.getHours(),d()[m+12>>>2>>>0]=F.getDate(),d()[m+16>>>2>>>0]=F.getMonth(),d()[m+20>>>2>>>0]=F.getYear(),m=F.getTime(),BigInt(isNaN(m)?-1:m/1e3)}function Ew(m,F,K,oe,pe,Le,lt){return _e?Jr(16,1,m,F,K,oe,pe,Le,lt):-52}function Cw(m,F,K,oe,pe,Le){if(_e)return Jr(17,1,m,F,K,oe,pe,Le)}function _M(m,F,K,oe){m>>>=0,F>>>=0,K>>>=0,oe>>>=0;var pe=new Date().getFullYear(),Le=new Date(pe,0,1),lt=new Date(pe,6,1);pe=Le.getTimezoneOffset();var yt=lt.getTimezoneOffset(),$t=Math.max(pe,yt);b()[m>>>2>>>0]=60*$t,d()[F>>>2>>>0]=+(pe!=yt),Le=(m=Nt=>Nt.toLocaleTimeString(void 0,{hour12:!1,timeZoneName:"short"}).split(" ")[1])(Le),lt=m(lt),yt{Wm.length=0;for(var K;K=u()[m++>>>0];){var oe=K!=105;F+=(oe&=K!=112)&&F%8?4:0,Wm.push(K==112?b()[F>>>2>>>0]:K==106?xn[F>>>3]:K==105?d()[F>>>2>>>0]:E()[F>>>3>>>0]),F+=oe?8:4}return Wm};function yM(m,F,K){return m>>>=0,F=Pw(F>>>0,K>>>0),$m[m](...F)}function wM(m,F,K){return m>>>=0,F=Pw(F>>>0,K>>>0),$m[m](...F)}var vM=()=>{},bM=()=>Date.now();function xM(m,F){return nr(jn(m>>>0,F>>>0))}var $w,MM=()=>{throw Ks+=1,"unwind"};function TM(){return 4294901760}$w=()=>performance.timeOrigin+performance.now();var kM=()=>navigator.hardwareConcurrency;function SM(){return kl("Cannot use emscripten_pc_get_function without -sUSE_OFFSET_CONVERTER"),0}function EM(m){m>>>=0;var F=u().length;if(m<=F||4294901760=K;K*=2){var oe=F*(1+.2/K);oe=Math.min(oe,m+100663296);var pe=Math;oe=Math.max(m,oe);e:{pe=(pe.min.call(pe,4294901760,oe+(65536-oe%65536)%65536)-Sr.buffer.byteLength+65535)/65536;try{Sr.grow(pe),In();var Le=1;break e}catch{}Le=void 0}if(Le)return!0}return!1}var Bp=()=>(kl("Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER"),0),af={},Aw=m=>{m.forEach(F=>{Bp()})};function CM(){var m=Error().stack.toString().split(` +`);return m[0]=="Error"&&m.shift(),Aw(m),af.Gb=Bp(),af.Tb=m,af.Gb}function PM(m,F,K){if(m>>>=0,F>>>=0,af.Gb==m)var oe=af.Tb;else(oe=Error().stack.toString().split(` +`))[0]=="Error"&&oe.shift(),Aw(oe);for(var pe=3;oe[pe]&&Bp()!=m;)++pe;for(m=0;m>>2>>>0]=Bp();return m}var Gm,qm={},Iw=()=>{if(!Gm){var m,F={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:ct};for(m in qm)qm[m]===void 0?delete F[m]:F[m]=qm[m];var K=[];for(m in F)K.push(`${m}=${F[m]}`);Gm=K}return Gm};function Fw(m,F){if(_e)return Jr(18,1,m,F);m>>>=0,F>>>=0;var K=0;return Iw().forEach((oe,pe)=>{var Le=F+K;for(pe=b()[m+4*pe>>>2>>>0]=Le,Le=0;Le>>0]=oe.charCodeAt(Le);s()[pe>>>0]=0,K+=oe.length+1}),0}function zw(m,F){if(_e)return Jr(19,1,m,F);m>>>=0,F>>>=0;var K=Iw();b()[m>>>2>>>0]=K.length;var oe=0;return K.forEach(pe=>oe+=pe.length+1),b()[F>>>2>>>0]=oe,0}function Ow(m){return _e?Jr(20,1,m):52}function Dw(m,F,K,oe){return _e?Jr(21,1,m,F,K,oe):52}function Lw(m,F,K,oe){return _e?Jr(22,1,m,F,K,oe):70}var $M=[null,[],[]];function Rw(m,F,K,oe){if(_e)return Jr(23,1,m,F,K,oe);F>>>=0,K>>>=0,oe>>>=0;for(var pe=0,Le=0;Le>>2>>>0],yt=b()[F+4>>>2>>>0];F+=8;for(var $t=0;$t>>0],lr=$M[m];Nt===0||Nt===10?((m===1?ar:nr)(Zy(lr,0)),lr.length=0):lr.push(Nt)}pe+=yt}return b()[oe>>>2>>>0]=pe,0}_e||function(){for(var m=v.numThreads-1;m--;)Ky();sf.unshift(()=>{Ci++,function(F){_e?F():Promise.all(ts.map(Hy)).then(F)}(()=>Ip())})}();for(var Bw=Array(256),Np=0;256>Np;++Np)Bw[Np]=String.fromCharCode(Np);pw=Bw,rs=v.BindingError=class extends Error{constructor(m){super(m),this.name="BindingError"}},v.InternalError=class extends Error{constructor(m){super(m),this.name="InternalError"}},xo.push(0,1,void 0,1,null,1,!0,1,!1,1),v.count_emval_handles=()=>xo.length/2-5-Lm.length;var AM=[Fm,Vy,Qy,Jy,ew,rw,nw,iw,ow,sw,aw,lw,uw,cw,dw,fw,Ew,Cw,Fw,zw,Ow,Dw,Lw,Rw],Ht=function(){function m(K,oe){return Ht=K.exports,Ht=function(){var pe=Ht,Le={};for(let[lt,yt]of Object.entries(pe))Le[lt]=typeof yt=="function"?(...$t)=>{Dp.push(lt);try{return yt(...$t)}finally{hi||(Dp.pop(),ro&&is===1&&Dp.length===0&&(is=0,Ks+=1,Op(Kw),typeof Fibers<"u"&&Fibers.ac()))}}:yt;return Le}(),Ht=function(){var pe=Ht,Le=yt=>$t=>yt($t)>>>0,lt=yt=>()=>yt()>>>0;return(pe=Object.assign({},pe)).Aa=Le(pe.Aa),pe.db=lt(pe.db),pe.eb=Le(pe.eb),pe.emscripten_main_runtime_thread_id=lt(pe.emscripten_main_runtime_thread_id),pe.qb=Le(pe.qb),pe.rb=lt(pe.rb),pe}(),Wy.push(Ht.gb),Fn.unshift(Ht.za),jr=oe,Ip(),Ht}var F=jy();if(Ci++,v.instantiateWasm)try{return v.instantiateWasm(F,m)}catch(K){nr(`Module.instantiateWasm callback failed with error: ${K}`),H(K)}return Pm||(Pm=v.locateFile?Ly("ort-wasm-simd-threaded.jsep.wasm")?"ort-wasm-simd-threaded.jsep.wasm":v.locateFile?v.locateFile("ort-wasm-simd-threaded.jsep.wasm",vt):vt+"ort-wasm-simd-threaded.jsep.wasm":new URL(n("./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm"),n.b).href),function(K,oe){var pe=Pm;return Ft||typeof WebAssembly.instantiateStreaming!="function"||Ly(pe)||Ry(pe)||typeof fetch!="function"?Ny(pe,K,oe):fetch(pe,{credentials:"same-origin"}).then(Le=>WebAssembly.instantiateStreaming(Le,K).then(oe,function(lt){return nr(`wasm streaming compile failed: ${lt}`),nr("falling back to ArrayBuffer instantiation"),Ny(pe,K,oe)}))}(F,function(K){m(K.instance,K.module)}).catch(H),{}}(),Nw=m=>(Nw=Ht.Aa)(m),jw=()=>(jw=Ht.Ba)();v._OrtInit=(m,F)=>(v._OrtInit=Ht.Ca)(m,F),v._OrtGetLastError=(m,F)=>(v._OrtGetLastError=Ht.Da)(m,F),v._OrtCreateSessionOptions=(m,F,K,oe,pe,Le,lt,yt,$t,Nt)=>(v._OrtCreateSessionOptions=Ht.Ea)(m,F,K,oe,pe,Le,lt,yt,$t,Nt),v._OrtAppendExecutionProvider=(m,F)=>(v._OrtAppendExecutionProvider=Ht.Fa)(m,F),v._OrtAddFreeDimensionOverride=(m,F,K)=>(v._OrtAddFreeDimensionOverride=Ht.Ga)(m,F,K),v._OrtAddSessionConfigEntry=(m,F,K)=>(v._OrtAddSessionConfigEntry=Ht.Ha)(m,F,K),v._OrtReleaseSessionOptions=m=>(v._OrtReleaseSessionOptions=Ht.Ia)(m),v._OrtCreateSession=(m,F,K)=>(v._OrtCreateSession=Ht.Ja)(m,F,K),v._OrtReleaseSession=m=>(v._OrtReleaseSession=Ht.Ka)(m),v._OrtGetInputOutputCount=(m,F,K)=>(v._OrtGetInputOutputCount=Ht.La)(m,F,K),v._OrtGetInputName=(m,F)=>(v._OrtGetInputName=Ht.Ma)(m,F),v._OrtGetOutputName=(m,F)=>(v._OrtGetOutputName=Ht.Na)(m,F),v._OrtFree=m=>(v._OrtFree=Ht.Oa)(m),v._OrtCreateTensor=(m,F,K,oe,pe,Le)=>(v._OrtCreateTensor=Ht.Pa)(m,F,K,oe,pe,Le),v._OrtGetTensorData=(m,F,K,oe,pe)=>(v._OrtGetTensorData=Ht.Qa)(m,F,K,oe,pe),v._OrtReleaseTensor=m=>(v._OrtReleaseTensor=Ht.Ra)(m),v._OrtCreateRunOptions=(m,F,K,oe)=>(v._OrtCreateRunOptions=Ht.Sa)(m,F,K,oe),v._OrtAddRunConfigEntry=(m,F,K)=>(v._OrtAddRunConfigEntry=Ht.Ta)(m,F,K),v._OrtReleaseRunOptions=m=>(v._OrtReleaseRunOptions=Ht.Ua)(m),v._OrtCreateBinding=m=>(v._OrtCreateBinding=Ht.Va)(m),v._OrtBindInput=(m,F,K)=>(v._OrtBindInput=Ht.Wa)(m,F,K),v._OrtBindOutput=(m,F,K,oe)=>(v._OrtBindOutput=Ht.Xa)(m,F,K,oe),v._OrtClearBoundOutputs=m=>(v._OrtClearBoundOutputs=Ht.Ya)(m),v._OrtReleaseBinding=m=>(v._OrtReleaseBinding=Ht.Za)(m),v._OrtRunWithBinding=(m,F,K,oe,pe)=>(v._OrtRunWithBinding=Ht._a)(m,F,K,oe,pe),v._OrtRun=(m,F,K,oe,pe,Le,lt,yt)=>(v._OrtRun=Ht.$a)(m,F,K,oe,pe,Le,lt,yt),v._OrtEndProfiling=m=>(v._OrtEndProfiling=Ht.ab)(m),v._JsepOutput=(m,F,K)=>(v._JsepOutput=Ht.bb)(m,F,K),v._JsepGetNodeName=m=>(v._JsepGetNodeName=Ht.cb)(m);var jp,El=()=>(El=Ht.db)(),Up=v._malloc=m=>(Up=v._malloc=Ht.eb)(m),no=v._free=m=>(no=v._free=Ht.fb)(m),Hm=(m,F,K,oe,pe,Le)=>(Hm=Ht.ib)(m,F,K,oe,pe,Le),Uw=()=>(Uw=Ht.jb)(),Vw=(m,F,K,oe,pe)=>(Vw=Ht.kb)(m,F,K,oe,pe),Km=m=>(Km=Ht.lb)(m),Vp=m=>(Vp=Ht.mb)(m),Ww=()=>(Ww=Ht.nb)(),Gw=(m,F)=>(Gw=Ht.ob)(m,F),Wp=m=>(Wp=Ht.pb)(m),Qm=m=>(Qm=Ht.qb)(m),Xm=()=>(Xm=Ht.rb)(),qw=v.dynCall_ii=(m,F)=>(qw=v.dynCall_ii=Ht.tb)(m,F),Hw=m=>(Hw=Ht.ub)(m),Kw=()=>(Kw=Ht.vb)(),Qw=m=>(Qw=Ht.wb)(m),Xw=()=>(Xw=Ht.xb)();function Yw(){0Xm(),v.stackRestore=m=>Wp(m),v.stackAlloc=m=>Qm(m),v.UTF8ToString=jn,v.stringToUTF8=Sl,v.lengthBytesUTF8=tw,es=function m(){jp||Yw(),jp||(es=m)},Yw(),ne}),St=wt,((r=globalThis.self)==null?void 0:r.name)==="em-pthread"&&wt()}),at,Ot,Ut,Kt,Qt,Jt,qt,Er,Qr=h(()=>{var r,i;ve(),at=import.meta.url??(typeof document<"u"?(r=document.currentScript)==null?void 0:r.src:typeof self<"u"?(i=self.location)==null?void 0:i.href:void 0),Ot=typeof location>"u"?void 0:location.origin,Ut=(s,u)=>{try{let c=u??at;return(c?new URL(s,c):new URL(s)).origin===Ot}catch{return!1}},Kt=async s=>{let u=await(await fetch(s,{credentials:"same-origin"})).blob();return URL.createObjectURL(u)},Qt=(ft(),w(Re)).default,Jt=async()=>{if(!at)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(Ut(at))return[void 0,Qt()];let s=await Kt(at);return[s,Qt(s)]},qt=(Rt(),w(ht)).default,Er=async(s,u,c)=>[void 0,qt]}),Cr,mt,Pt,Bt,sn,Li,bi,Nr,mn=h(()=>{Qr(),mt=!1,Pt=!1,Bt=!1,sn=()=>{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}},Li=()=>{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}},bi=async r=>{if(mt)return Promise.resolve();if(Pt)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Bt)throw new Error("previous call to 'initializeWebAssembly()' failed.");Pt=!0;let i=r.initTimeout,s=r.numThreads;if(!Li())throw new Error("WebAssembly SIMD is not supported in the current environment.");let u=sn();s>1&&!u&&(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."),r.numThreads=s=1);let c=r.wasmPaths,p=typeof c=="string"?c:void 0,d=c==null?void 0:c.mjs,b=(d==null?void 0:d.href)??d,T=c==null?void 0:c.wasm,E=(T==null?void 0:T.href)??T,q=r.wasmBinary,[H,v]=await Er(b,p,s>1),ne=!1,re=[];if(i>0&&re.push(new Promise(ce=>{setTimeout(()=>{ne=!0,ce()},i)})),re.push(new Promise((ce,_e)=>{let be={numThreads:s};q?be.wasmBinary=q:(E||p)&&(be.locateFile=(he,Fe)=>E??(p??Fe)+he),v(be).then(he=>{Pt=!1,mt=!0,Cr=he,ce(),H&&URL.revokeObjectURL(H)},he=>{Pt=!1,Bt=!0,_e(he)})})),await Promise.race(re),ne)throw new Error(`WebAssembly backend initializing failed due to timeout: ${i}ms`)},Nr=()=>{if(mt&&Cr)return Cr;throw new Error("WebAssembly is not initialized yet.")}}),Wr,ci,Fr,Ri=h(()=>{mn(),Wr=(r,i)=>{let s=Nr(),u=s.lengthBytesUTF8(r)+1,c=s._malloc(u);return s.stringToUTF8(r,c,u),i.push(c),c},ci=(r,i,s,u)=>{if(typeof r=="object"&&r!==null){if(s.has(r))throw new Error("Circular reference in options");s.add(r)}Object.entries(r).forEach(([c,p])=>{let d=i?i+c:c;if(typeof p=="object")ci(p,d+".",s,u);else if(typeof p=="string"||typeof p=="number")u(d,p.toString());else if(typeof p=="boolean")u(d,p?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof p}`)})},Fr=r=>{let i=Nr(),s=i.stackSave();try{let u=i.stackAlloc(8);i._OrtGetLastError(u,u+4);let c=i.HEAP32[u/4],p=i.HEAPU32[u/4+1],d=p?i.UTF8ToString(p):"";throw new Error(`${r} ERROR_CODE: ${c}, ERROR_MESSAGE: ${d}`)}finally{i.stackRestore(s)}}}),xi,ks=h(()=>{mn(),Ri(),xi=r=>{let i=Nr(),s=0,u=[],c=r||{};try{if((r==null?void 0:r.logSeverityLevel)===void 0)c.logSeverityLevel=2;else if(typeof r.logSeverityLevel!="number"||!Number.isInteger(r.logSeverityLevel)||r.logSeverityLevel<0||r.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${r.logSeverityLevel}`);if((r==null?void 0:r.logVerbosityLevel)===void 0)c.logVerbosityLevel=0;else if(typeof r.logVerbosityLevel!="number"||!Number.isInteger(r.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${r.logVerbosityLevel}`);(r==null?void 0:r.terminate)===void 0&&(c.terminate=!1);let p=0;return(r==null?void 0:r.tag)!==void 0&&(p=Wr(r.tag,u)),s=i._OrtCreateRunOptions(c.logSeverityLevel,c.logVerbosityLevel,!!c.terminate,p),s===0&&Fr("Can't create run options."),(r==null?void 0:r.extra)!==void 0&&ci(r.extra,"",new WeakSet,(d,b)=>{let T=Wr(d,u),E=Wr(b,u);i._OrtAddRunConfigEntry(s,T,E)!==0&&Fr(`Can't set a run config entry: ${d} - ${b}.`)}),[s,u]}catch(p){throw s!==0&&i._OrtReleaseRunOptions(s),u.forEach(d=>i._free(d)),p}}}),Oo,Do,Lo,Ro,Bi,Ss=h(()=>{mn(),Ri(),Oo=r=>{switch(r){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${r}`)}},Do=r=>{switch(r){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${r}`)}},Lo=r=>{r.extra||(r.extra={}),r.extra.session||(r.extra.session={});let i=r.extra.session;i.use_ort_model_bytes_directly||(i.use_ort_model_bytes_directly="1"),r.executionProviders&&r.executionProviders.some(s=>(typeof s=="string"?s:s.name)==="webgpu")&&(r.enableMemPattern=!1)},Ro=(r,i,s)=>{for(let u of i){let c=typeof u=="string"?u:u.name;switch(c){case"webnn":if(c="WEBNN",typeof u!="string"){let d=u==null?void 0:u.deviceType;if(d){let b=Wr("deviceType",s),T=Wr(d,s);Nr()._OrtAddSessionConfigEntry(r,b,T)!==0&&Fr(`Can't set a session config entry: 'deviceType' - ${d}.`)}}break;case"webgpu":if(c="JS",typeof u!="string"){let d=u;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 b=Wr("preferredLayout",s),T=Wr(d.preferredLayout,s);Nr()._OrtAddSessionConfigEntry(r,b,T)!==0&&Fr(`Can't set a session config entry: 'preferredLayout' - ${d.preferredLayout}.`)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${c}`)}let p=Wr(c,s);Nr()._OrtAppendExecutionProvider(r,p)!==0&&Fr(`Can't append execution provider: ${c}.`)}},Bi=r=>{let i=Nr(),s=0,u=[],c=r||{};Lo(c);try{let p=Oo(c.graphOptimizationLevel??"all"),d=Do(c.executionMode??"sequential"),b=typeof c.logId=="string"?Wr(c.logId,u):0,T=c.logSeverityLevel??2;if(!Number.isInteger(T)||T<0||T>4)throw new Error(`log serverity level is not valid: ${T}`);let E=c.logVerbosityLevel??0;if(!Number.isInteger(E)||E<0||E>4)throw new Error(`log verbosity level is not valid: ${E}`);let q=typeof c.optimizedModelFilePath=="string"?Wr(c.optimizedModelFilePath,u):0;if(s=i._OrtCreateSessionOptions(p,!!c.enableCpuMemArena,!!c.enableMemPattern,d,!!c.enableProfiling,0,b,T,E,q),s===0&&Fr("Can't create session options."),c.executionProviders&&Ro(s,c.executionProviders,u),c.enableGraphCapture!==void 0){if(typeof c.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${c.enableGraphCapture}`);let H=Wr("enableGraphCapture",u),v=Wr(c.enableGraphCapture.toString(),u);i._OrtAddSessionConfigEntry(s,H,v)!==0&&Fr(`Can't set a session config entry: 'enableGraphCapture' - ${c.enableGraphCapture}.`)}if(c.freeDimensionOverrides)for(let[H,v]of Object.entries(c.freeDimensionOverrides)){if(typeof H!="string")throw new Error(`free dimension override name must be a string: ${H}`);if(typeof v!="number"||!Number.isInteger(v)||v<0)throw new Error(`free dimension override value must be a non-negative integer: ${v}`);let ne=Wr(H,u);i._OrtAddFreeDimensionOverride(s,ne,v)!==0&&Fr(`Can't set a free dimension override: ${H} - ${v}.`)}return c.extra!==void 0&&ci(c.extra,"",new WeakSet,(H,v)=>{let ne=Wr(H,u),re=Wr(v,u);i._OrtAddSessionConfigEntry(s,ne,re)!==0&&Fr(`Can't set a session config entry: ${H} - ${v}.`)}),[s,u]}catch(p){throw s!==0&&i._OrtReleaseSessionOptions(s),u.forEach(d=>i._free(d)),p}}}),co,di,Mi,Ti,Yi,fo,po,Xt=h(()=>{co=r=>{switch(r){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: ${r}`)}},di=r=>{switch(r){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: ${r}`)}},Mi=(r,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][r],u=typeof i=="number"?i:i.reduce((c,p)=>c*p,1);return s>0?Math.ceil(u*s):void 0},Ti=r=>{switch(r){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: ${r}`)}},Yi=r=>{switch(r){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: ${r}`)}},fo=r=>r==="float32"||r==="float16"||r==="int32"||r==="int64"||r==="uint32"||r==="uint8"||r==="bool",po=r=>{switch(r){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: ${r}`)}}}),Zi,Bo=h(()=>{ve(),Zi=async r=>{if(typeof r=="string"){let i=await fetch(r);if(!i.ok)throw new Error(`failed to load external data file: ${r}`);let s=i.headers.get("Content-Length"),u=s?parseInt(s,10):0;if(u<1073741824)return new Uint8Array(await i.arrayBuffer());{if(!i.body)throw new Error(`failed to load external data file: ${r}, no response body.`);let c=i.body.getReader(),p;try{p=new ArrayBuffer(u)}catch(b){if(b instanceof RangeError){let T=Math.ceil(u/65536);p=new WebAssembly.Memory({initial:T,maximum:T}).buffer}else throw b}let d=0;for(;;){let{done:b,value:T}=await c.read();if(b)break;let E=T.byteLength;new Uint8Array(p,d,E).set(T),d+=E}return new Uint8Array(p,0,u)}}else return r instanceof Blob?new Uint8Array(await r.arrayBuffer()):r instanceof Uint8Array?r:new Uint8Array(r)}}),No,ho,jo,Uo,mo,Vo,Br,Rn=h(()=>{Xt(),No=["V","I","W","E","F"],ho=(r,i)=>{console.log(`[${No[r]},${new Date().toISOString()}]${i}`)},mo=(r,i)=>{jo=r,Uo=i},Vo=(r,i)=>{let s=Yi(r),u=Yi(jo);s>=u&&ho(s,typeof i=="function"?i():i)},Br=(...r)=>{Uo&&Vo(...r)}}),Ue,W=h(()=>{Xt(),Ue=(r,i)=>new(Ti(i))(r)}),fe=h(()=>{}),Pe,ze,Oe,nt,xt,kt,Tt,At,Zt,Pr=h(()=>{Rn(),fe(),Pe=new Map([[64,250],[128,200],[256,200],[512,200],[2048,230],[4096,200],[8192,50],[16384,50],[32768,50],[65536,50],[131072,50],[262144,50],[524288,50],[1048576,50],[2097152,30],[4194304,20],[8388608,10],[12582912,10],[16777216,10],[26214400,15],[33554432,22],[44236800,2],[58982400,6],[67108864,6],[134217728,6],[167772160,6]]),ze=[],Oe=r=>Math.ceil(r/16)*16,nt=r=>{for(let i=0;ixt++,Tt=async(r,i,s,u)=>{let c=Oe(s),p=r.device.createBuffer({size:c,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let d=r.getCommandEncoder();r.endComputePass(),d.copyBufferToBuffer(i,0,p,0,c),r.flush(),await p.mapAsync(GPUMapMode.READ);let b=p.getMappedRange();if(u){let T=u();return T.set(new Uint8Array(b,0,s)),T}else return new Uint8Array(b.slice(0,s))}finally{p.destroy()}},At=class{constructor(r){this.backend=r,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 Pe)ze.push(i),this.freeBuffers.set(i,[]),this.freeUniformBuffers.set(i,[])}upload(r,i){let s=i.buffer,u=i.byteOffset,c=i.byteLength,p=Oe(c),d=this.storageCache.get(r);if(!d)throw new Error("gpu data for uploading does not exist");if(d.originalSize!==c)throw new Error(`inconsistent data size. gpu data size=${d.originalSize}, data size=${c}`);let b=this.backend.device.createBuffer({mappedAtCreation:!0,size:p,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),T=b.getMappedRange();new Uint8Array(T).set(new Uint8Array(s,u,c)),b.unmap();let E=this.backend.getCommandEncoder();this.backend.endComputePass(),E.copyBufferToBuffer(b,0,d.gpuData.buffer,0,p),Br("verbose",()=>`[WebGPU] GpuDataManager.upload(id=${r})`),this.buffersForUploadingPending.push(b)}memcpy(r,i){let s=this.storageCache.get(r);if(!s)throw new Error("source gpu data for memcpy does not exist");let u=this.storageCache.get(i);if(!u)throw new Error("destination gpu data for memcpy does not exist");if(s.originalSize!==u.originalSize)throw new Error("inconsistent source and destination gpu data size");let c=Oe(s.originalSize),p=this.backend.getCommandEncoder();this.backend.endComputePass(),p.copyBufferToBuffer(s.gpuData.buffer,0,u.gpuData.buffer,0,c)}registerExternalBuffer(r,i,s){let u;if(s){if(u=this.externalBuffers.get(s),u===void 0)throw new Error("previous buffer is not registered");if(r===s)return Br("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${i}) => id=${u}, buffer is the same, skip.`),u;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 u=kt();return this.storageCache.set(u,{gpuData:{id:u,type:0,buffer:r},originalSize:i}),this.externalBuffers.set(r,u),Br("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${i}) => id=${u}, registered.`),u}unregisterExternalBuffer(r){let i=this.externalBuffers.get(r);i!==void 0&&(this.storageCache.delete(i),this.externalBuffers.delete(r),Br("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${i}`))}create(r,i=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let s=nt(r),u,c=(i&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,p=(i&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(c||p){let b=(c?this.freeBuffers:this.freeUniformBuffers).get(s);b?b.length>0?u=b.pop():u=this.backend.device.createBuffer({size:s,usage:i}):u=this.backend.device.createBuffer({size:s,usage:i})}else u=this.backend.device.createBuffer({size:s,usage:i});let d={id:kt(),type:0,buffer:u};return this.storageCache.set(d.id,{gpuData:d,originalSize:r}),Br("verbose",()=>`[WebGPU] GpuDataManager.create(size=${r}) => id=${d.id}`),d}get(r){var i;return(i=this.storageCache.get(r))==null?void 0:i.gpuData}release(r){let i=this.storageCache.get(r);if(!i)throw new Error("releasing data does not exist");return Br("verbose",()=>`[WebGPU] GpuDataManager.release(id=${r}), gpuDataId=${i.gpuData.id}`),this.storageCache.delete(r),this.buffersPending.push(i.gpuData.buffer),i.originalSize}async download(r,i){let s=this.storageCache.get(r);if(!s)throw new Error("data does not exist");await Tt(this.backend,s.gpuData.buffer,s.originalSize,i)}refreshPendingBuffers(){for(let r of this.buffersForUploadingPending)r.destroy();if(this.buffersForUploadingPending=[],this.buffersPending.length!==0)if(this.backend.sessionStatus==="default"){for(let r of this.buffersPending){let i=Pe.get(r.size);if((r.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE){let s=this.freeBuffers.get(r.size)||[];i===void 0||s.length>=i?r.destroy():s.push(r)}else if((r.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM){let s=this.freeUniformBuffers.get(r.size)||[];i===void 0||s.length>=i?r.destroy():s.push(r)}else r.destroy()}this.buffersPending=[]}else{let r=this.capturedPendingBuffers.get(this.backend.currentSessionId);r||(r=[],this.capturedPendingBuffers.set(this.backend.currentSessionId,r));for(let i of this.buffersPending)r.push(i);this.buffersPending=[]}}dispose(){this.freeBuffers.forEach(r=>{r.forEach(i=>{i.destroy()})}),this.freeUniformBuffers.forEach(r=>{r.forEach(i=>{i.destroy()})}),this.storageCache.forEach(r=>{r.gpuData.buffer.destroy()}),this.capturedPendingBuffers.forEach(r=>{r.forEach(i=>{i.destroy()})}),this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.capturedPendingBuffers=new Map}onReleaseSession(r){let i=this.capturedPendingBuffers.get(r);i&&(i.forEach(s=>{s.destroy()}),this.capturedPendingBuffers.delete(r))}},Zt=(...r)=>new At(...r)}),rr,Gt,mr=h(()=>{rr=class{constructor(r){Object.assign(this,r)}get cacheKey(){return this.key||(this.key=Object.getOwnPropertyNames(this).sort().map(r=>`${this[r]}`).join(";")),this.key}},Gt=r=>new rr(r)}),kn,pn,st,qn,xr,an,$n,Yt=h(()=>{kn=class{static calcMatMulShape(r,i){return r[1]!==i[0]?void 0:[r[0],i[1]]}},pn=class{static calcShape(r,i,s=!1){let u=r.length,c=i.length;if(u===0)return i;if(c===0)return r;let p=Math.max(r.length,i.length),d=new Array(p);if(s){if(u<2||c<2)return;let b=kn.calcMatMulShape([r[u-2],r[u-1]],[i[c-2],i[c-1]]);if(b===void 0)return;[d[p-2],d[p-1]]=b}for(let b=s?3:1;b<=p;b++){let T=u-b<0?1:r[u-b],E=c-b<0?1:i[c-b];if(T!==E&&T>1&&E>1)return;let q=Math.max(T,E);if(T&&E)d[p-b]=Math.max(T,E);else{if(q>1)return;d[p-b]=0}}return d}static isValidBroadcast(r,i){let s=r.length,u=i.length;if(s>u)return!1;for(let c=1;c<=s;c++)if(r[s-c]!==1&&r[s-c]!==i[u-c])return!1;return!0}},st=class xh{static size(i){return xh.getSizeFromDimensionRange(i,0,i.length)}static convertShape(i,s=4){let u=i.length;if(u===0)return[];let c=new Array(u),p=u-1;for(;p>=0;){if(i[p]%s===0){c[p]=i[p]/s;break}if(s%i[p]!==0)throw new Error("cannot convert shape");c[p]=1,s/=i[p],p--}for(p--;p>=0;p--)c[p]=i[p];return c}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 xh.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 xh.getSizeFromDimensionRange(i,0,s)}static getSizeFromDimensionRange(i,s,u){let c=1;for(let p=s;p=0;--c)u[c]=u[c+1]*i[c+1];return u}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(u=>this.normalizeAxis(u,s??i.length))}static sortBasedOnPerm(i,s){return s?s.map(u=>i[u]):i.slice().reverse()}static padShape(i,s){let u=i.length;return i.map((c,p)=>c+s[p]+s[p+u])}static areEqual(i,s){return i.length!==s.length?!1:i.every((u,c)=>u===s[c])}},qn=class vf{static adjustPoolAttributes(i,s,u,c,p,d){if(!i&&u.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 b=0;b=u.length?u.push(s[b+2]):u[b]=s[b+2];for(let b=0;b=u[b]||d[b+u.length]>=u[b])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(i,s,u,c,p,d,b){if(b){if(p.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(c.length!==i.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let T=0;T{Xt(),Yt(),Bn=64,gn=(r,i)=>{if(i===3)throw new Error("vec3 has same alignment as vec4, use vec4 instead");switch(r){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: ${r}`)}},Tr=(r,i=1)=>{let s=gn(r,i);return typeof s=="string"?s:s[0]},kr=(r,i=1)=>{let s=gn(r,i);return typeof s=="string"?s:s[1]},Ct=(...r)=>{let i=[];return r.forEach(s=>{s.length!==0&&i.push({type:12,data:s},{type:12,data:st.computeStrides(s)})}),i},wr=r=>r%4===0?4:r%2===0?2:1,zr=(r="f32",i,s="0")=>!i||i===1?`${r}(${s})`:`vec${i}<${r}>(${s})`,Gr=(r,i,s)=>r==="f32"?s:i===1?`f32(${s})`:`vec${i}(${s})`,Nn=(r,i)=>i===4?`(${r}.x + ${r}.y + ${r}.z + ${r}.w)`:i===2?`(${r}.x + ${r}.y)`:i===3?`(${r}.x + ${r}.y + ${r}.z)`:r,Dt=(r,i,s,u)=>r.startsWith("uniforms.")&&s>4?typeof i=="string"?u==="f16"?`${r}[(${i}) / 8][(${i}) % 8 / 4][(${i}) % 8 % 4]`:`${r}[(${i}) / 4][(${i}) % 4]`:u==="f16"?`${r}[${Math.floor(i/8)}][${Math.floor(i%8/4)}][${i%8%4}]`:`${r}[${Math.floor(i/4)}][${i%4}]`:s>1?`${r}[${i}]`:r,Es=(r,i,s,u,c)=>{let p=typeof s=="number",d=p?s:s.length,b=[...new Array(d).keys()],T=d<2?"u32":d<=4?`vec${d}`:`array`,E=gn(i,c),q=typeof E=="string"?E:E[1],H=typeof E=="string"?E:E[0],v={indices:T,value:q,storage:H,tensor:i},ne=pt=>typeof pt=="string"?pt:`${pt}u`,re={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},ce=p?"uniforms.":"",_e=`${ce}${r}_shape`,be=`${ce}${r}_strides`,he="";for(let pt=0;pt ${v.indices} { + var indices: ${v.indices}; + var current = offset; + ${he} + return indices; + }`,xe=pt=>(re.offsetToIndices=!0,d<2?pt:`o2i_${r}(${pt})`),Ie=[];if(d>=2)for(let pt=d-1;pt>=0;pt--)Ie.push(`${Dt(be,pt,d)} * (indices[${pt}])`);let ct=d<2?"":` + fn i2o_${r}(indices: ${v.indices}) -> u32 { + return ${Ie.join("+")}; + }`,et=pt=>(re.indicesToOffset=!0,d<2?pt:`i2o_${r}(${pt})`),vt=(...pt)=>d===0?"0u":`${v.indices}(${pt.map(ne).join(",")})`,Ft=(pt,zt)=>d<2?`${pt}`:`${Dt(pt,zt,d)}`,Lt=(pt,zt,ir)=>d<2?`${pt}=${ir};`:`${Dt(pt,zt,d)}=${ir};`,pr={},ar=(pt,zt)=>{re.broadcastedIndicesToOffset=!0;let ir=`${zt.name}broadcastedIndicesTo${r}Offset`;if(ir in pr)return`${ir}(${pt})`;let Hr=[];for(let un=d-1;un>=0;un--){let xn=zt.indicesGet("outputIndices",un+zt.rank-d);Hr.push(`${Ft(be,un)} * (${xn} % ${Ft(_e,un)})`)}return pr[ir]=`fn ${ir}(outputIndices: ${zt.type.indices}) -> u32 { + return ${Hr.length>0?Hr.join("+"):"0u"}; + }`,`${ir}(${pt})`},nr=(pt,zt)=>(()=>{if(v.storage===v.value)return`${r}[${pt}]=${zt};`;if(v.storage==="vec2"&&v.value==="i32")return`${r}[${pt}]=vec2(u32(${zt}), select(0u, 0xFFFFFFFFu, ${zt} < 0));`;if(v.storage==="vec2"&&v.value==="u32")return`${r}[${pt}]=vec2(u32(${zt}), 0u);`;if(v.storage==="u32"&&v.value==="vec4")return`${r}[${pt}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${zt}));`;throw new Error(`not supported combination of storage type ${v.storage} and value type ${v.value} yet`)})(),yr=pt=>(()=>{if(v.storage===v.value)return`${r}[${pt}]`;if(v.storage==="vec2"&&v.value==="i32")return`i32(${r}[${pt}].x)`;if(v.storage==="vec2"&&v.value==="u32")return`u32(${r}[${pt}].x)`;if(v.storage==="u32"&&v.value==="vec4")return`vec4(bool(${r}[${pt}] & 0xFFu), bool(${r}[${pt}] & 0xFF00u), bool(${r}[${pt}] & 0xFF0000u), bool(${r}[${pt}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${v.storage} and value type ${v.value} yet`)})(),qr=d<2?"":` + fn get_${r}ByIndices(indices: ${v.indices}) -> ${q} { + return ${yr(`i2o_${r}(indices)`)}; + }`,Sr=d<2?"":(()=>{let pt=b.map(ir=>`d${ir}: u32`).join(", "),zt=b.map(ir=>`d${ir}`).join(", ");return` + fn get_${r}(${pt}) -> ${q} { + return get_${r}ByIndices(${vt(zt)}); + }`})(),jr=(...pt)=>{if(pt.length!==d)throw new Error(`indices length must be ${d}`);let zt=pt.map(ne).join(",");return d===0?yr("0u"):d===1?yr(zt[0]):(re.get=!0,re.getByIndices=!0,re.indicesToOffset=!0,`get_${r}(${zt})`)},It=pt=>d<2?yr(pt):(re.getByIndices=!0,re.indicesToOffset=!0,`get_${r}ByIndices(${pt})`),tr=d<2?"":` + fn set_${r}ByIndices(indices: ${v.indices}, value: ${q}) { + ${nr(`i2o_${r}(indices)`,"value")} + }`,er=d<2?"":(()=>{let pt=b.map(ir=>`d${ir}: u32`).join(", "),zt=b.map(ir=>`d${ir}`).join(", ");return` + fn set_${r}(${pt}, value: ${q}) { + set_${r}ByIndices(${vt(zt)}, value); + }`})();return{impl:()=>{let pt=[],zt=!1;return re.offsetToIndices&&(pt.push(Fe),zt=!0),re.indicesToOffset&&(pt.push(ct),zt=!0),re.broadcastedIndicesToOffset&&(Object.values(pr).forEach(ir=>pt.push(ir)),zt=!0),re.set&&(pt.push(er),zt=!0),re.setByIndices&&(pt.push(tr),zt=!0),re.get&&(pt.push(Sr),zt=!0),re.getByIndices&&(pt.push(qr),zt=!0),!p&&zt&&pt.unshift(`const ${_e} = ${v.indices}(${s.join(",")});`,`const ${be} = ${v.indices}(${st.computeStrides(s).join(",")});`),pt.join(` +`)},type:v,offsetToIndices:xe,indicesToOffset:et,broadcastedIndicesToOffset:ar,indices:vt,indicesGet:Ft,indicesSet:Lt,set:(...pt)=>{if(pt.length!==d+1)throw new Error(`indices length must be ${d}`);let zt=pt[d];if(typeof zt!="string")throw new Error("value must be string");let ir=pt.slice(0,d).map(ne).join(",");return d===0?nr("0u",zt):d===1?nr(ir[0],zt):(re.set=!0,re.setByIndices=!0,re.indicesToOffset=!0,`set_${r}(${ir}, ${zt})`)},setByOffset:nr,setByIndices:(pt,zt)=>d<2?nr(pt,zt):(re.setByIndices=!0,re.indicesToOffset=!0,`set_${r}ByIndices(${pt}, ${zt});`),get:jr,getByOffset:yr,getByIndices:It,usage:u,name:r,strides:be,shape:_e,rank:d}},gt=(r,i,s,u=1)=>Es(r,i,s,"input",u),Vt=(r,i,s,u=1)=>Es(r,i,s,"output",u),da=(r,i,s,u=1)=>Es(r,i,s,"internal",u),fa=class{constructor(r,i){this.normalizedDispatchGroup=r,this.limits=i,this.internalVariables=[],this.variables=[],this.uniforms=[],this.variableIndex=0}guardAgainstOutOfBoundsWorkgroupSizes(r){return`if (global_idx >= ${typeof r=="number"?`${r}u`:r}) { return; }`}mainStart(r=Bn){let i=typeof r=="number"?r:r[0],s=typeof r=="number"?1:r[1],u=typeof r=="number"?1:r[2];if(i>this.limits.maxComputeWorkgroupSizeX||s>this.limits.maxComputeWorkgroupSizeY||u>this.limits.maxComputeWorkgroupSizeZ)throw new Error(`workgroup size [${i}, ${s}, ${u}] exceeds the maximum workgroup size [${this.limits.maxComputeWorkgroupSizeX}, ${this.limits.maxComputeWorkgroupSizeY}, ${this.limits.maxComputeWorkgroupSizeZ}].`);if(i*s*u>this.limits.maxComputeInvocationsPerWorkgroup)throw new Error(`workgroup size [${i}, ${s}, ${u}] exceeds the maximum workgroup invocations ${this.limits.maxComputeInvocationsPerWorkgroup}.`);let c=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1,p=c?`@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=c?"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*u}u + local_idx;`;return`@compute @workgroup_size(${i}, ${s}, ${u}) + fn main(${p}) { + ${d} + `}appendVariableUniforms(r){r.rank!==0&&(r.shape.startsWith("uniforms.")&&this.uniforms.push({name:r.shape.replace("uniforms.",""),type:"u32",length:r.rank}),r.strides.startsWith("uniforms.")&&this.uniforms.push({name:r.strides.replace("uniforms.",""),type:"u32",length:r.rank}))}declareVariable(r,i){if(r.usage==="internal")throw new Error("cannot use internal variable with declareVariable(). use registerInternalVariables() instead.");this.variables.push(r),this.appendVariableUniforms(r);let s=r.usage==="input"?"read":"read_write",u=r.type.storage;return`@group(0) @binding(${i}) var ${r.name}: array<${u}>;`}declareVariables(...r){return r.map(i=>this.declareVariable(i,this.variableIndex++)).join(` +`)}registerInternalVariable(r){if(r.usage!=="internal")throw new Error("cannot use input or output variable with registerInternalVariable(). use declareVariables() instead.");this.internalVariables.push(r),this.appendVariableUniforms(r)}registerInternalVariables(...r){return r.forEach(i=>this.registerInternalVariable(i)),this}registerUniform(r,i,s=1){return this.uniforms.push({name:r,type:i,length:s}),this}registerUniforms(r){return this.uniforms=this.uniforms.concat(r),this}uniformDeclaration(){if(this.uniforms.length===0)return"";let r=[];for(let{name:i,type:s,length:u}of this.uniforms)if(u&&u>4)s==="f16"?r.push(`@align(16) ${i}:array, ${Math.ceil(u/8)}>`):r.push(`${i}:array, ${Math.ceil(u/4)}>`);else{let c=u==null||u===1?s:`vec${u}<${s}>`;r.push(`${i}:${c}`)}return` + struct Uniforms { ${r.join(", ")} }; + @group(0) @binding(${this.variableIndex}) var uniforms: Uniforms;`}get additionalImplementations(){return this.uniformDeclaration()+this.variables.map(r=>r.impl()).join(` +`)+this.internalVariables.map(r=>r.impl()).join(` +`)}get variablesInfo(){if(this.uniforms.length===0)return;let r=i=>[12,10,1,6][["u32","f16","f32","i32"].indexOf(i)];return this.uniforms.map(i=>[r(i.type),i.length??1])}},su=(r,i)=>new fa(r,i),go=(r,i)=>{let s=r.length,u=[];for(let c=0;c1&&d===1&&u.unshift(p)}return u}}),au,pa,Wo,lu,fi,uu,ha,_o=h(()=>{Xt(),Yt(),mr(),or(),au=r=>{if(!r||r.length!==1)throw new Error("Transpose requires 1 input.")},pa=(r,i)=>i&&i.length!==r?[...new Array(r).keys()].reverse():i,Wo=(r,i)=>st.sortBasedOnPerm(r,pa(r.length,i)),lu=(r,i,s,u)=>{let c=[];c.push(`fn perm(i: ${u.type.indices}) -> ${s.type.indices} { + var a: ${s.type.indices};`);for(let p=0;p{let s=r.dataType,u=r.dims.length,c=pa(u,i),p=Wo(r.dims,c),d=Vt("output",s,p.length),b=gt("a",s,u),T;if(c.length===2&&c[0]===1&&c[1]===0){let E=d.type.value,q=[16,16,1];T=H=>` + ${H.registerUniform("output_size","u32").declareVariables(b,d)} + var tile : array, ${q[0]}>; + ${H.mainStart(q)} + var x = workgroup_id.x * ${q[0]}u + local_id.x; + var y = workgroup_id.y * ${q[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] = ${b.getByOffset("y * width + x")}; + } + workgroupBarrier(); + x = workgroup_id.y * ${q[0]}u + local_id.x; + y = workgroup_id.x * ${q[0]}u + local_id.y; + if (x < height && y < width) { + ${d.setByOffset("y * height + x","tile[local_id.x][local_id.y]")} + } + }`}else T=E=>` + ${E.registerUniform("output_size","u32").declareVariables(b,d)} + + ${lu(c,u,b,d)} + + ${E.mainStart()} + ${E.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${d.offsetToIndices("global_idx")}; + let aIndices = perm(indices); + + ${d.setByOffset("global_idx",b.getByIndices("aIndices"))} + }`;return{name:"Transpose",shaderCache:{hint:`${i}`,inputDependencies:["rank"]},getRunData:E=>{let q=st.size(p);return{outputs:[{dims:p,dataType:E[0].dataType}],dispatchGroup:{x:Math.ceil(q/64)},programUniforms:[{type:12,data:q},...Ct(E[0].dims,p)]}},getShaderSource:T}},uu=(r,i)=>{au(r.inputs),r.compute(fi(r.inputs[0],i.perm))},ha=r=>Gt({perm:r.perm})}),cu,du,fu,pu,ma,hu,mu,ga,gu,_u,Hn,yu,wu,_a,vu,bu,ya,xu,Mu,wa,Tu,ep=h(()=>{Xt(),Yt(),or(),Sa(),_o(),cu={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"},du={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"},fu={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},pu={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},ma=(r,i)=>{let s=[];for(let u=i-r;u{let s=[],u=r.length;for(let p=0;pr[p]);return[s,c]},mu=(r,i)=>{let s=r.length+i.length,u=[],c=0;for(let p=0;p{for(let s=0;s{let s=[];if(!ga(r,i)){for(let u=0;us.push(u))}return s},_u=(r,i,s,u,c,p,d)=>{let b=s[0].dims,T=st.size(p),E=st.size(d),q=gt("_A",s[0].dataType,b),H=Vt("output",c,p),v=32,ne=` + var aBestValues : array; + `;return{name:r,shaderCache:i,getShaderSource:re=>` + ${re.registerUniform("reduceSize","u32").declareVariables(q,H)} + ${ne} + fn DIV_CEIL(a : u32, b : u32) -> u32 { + return ((a - 1u) / b + 1u); + } + ${re.mainStart(v)} + + let outputIndex = global_idx / ${v}; + let offset = outputIndex * uniforms.reduceSize; + + var bestValue = f32(${fu[u]}); + let Length = uniforms.reduceSize; + for (var k = local_idx; k < Length; k = k + ${v}) { + let candidate = f32(${q.getByOffset("offset + k")}); + bestValue = ${cu[u]}; + } + aBestValues[local_idx] = bestValue; + workgroupBarrier(); + + var reduceSize = min(Length, ${v}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 = ${du[u]}; + aBestValues[local_idx] = bestValue; + } + reduceSize = interval; + workgroupBarrier(); + } + + if (local_idx == 0u) { + ${H.setByOffset("outputIndex",`${u==="mean"?`${H.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${H.type.storage}(${pu[u]})`}`)}; + } + }`,getRunData:()=>({outputs:[{dims:p,dataType:c}],dispatchGroup:{x:T},programUniforms:[{type:12,data:E}]})}},Hn=(r,i,s,u)=>{let c=r.inputs.length===1?s:Ps(r.inputs,s),p=c.axes;p.length===0&&!c.noopWithEmptyAxes&&(p=r.inputs[0].dims.map((ne,re)=>re));let d=st.normalizeAxes(p,r.inputs[0].dims.length),b=d,T=r.inputs[0],E=gu(b,r.inputs[0].dims.length);E.length>0&&(T=r.compute(fi(r.inputs[0],E),{inputs:[0],outputs:[-1]})[0],b=ma(b.length,T.dims.length));let[q,H]=hu(T.dims,b),v=q;c.keepDims&&(v=mu(q,d)),r.compute(_u(i,{hint:c.cacheKey,inputDependencies:["type"]},[T],u,r.inputs[0].dataType,v,H),{inputs:[T]})},yu=(r,i)=>{Hn(r,"ReduceMeanShared",i,"mean")},wu=(r,i)=>{Hn(r,"ReduceL1Shared",i,"l1")},_a=(r,i)=>{Hn(r,"ReduceL2Shared",i,"l2")},vu=(r,i)=>{Hn(r,"ReduceLogSumExpShared",i,"logSumExp")},bu=(r,i)=>{Hn(r,"ReduceMaxShared",i,"max")},ya=(r,i)=>{Hn(r,"ReduceMinShared",i,"min")},xu=(r,i)=>{Hn(r,"ReduceProdShared",i,"prod")},Mu=(r,i)=>{Hn(r,"ReduceSumShared",i,"sum")},wa=(r,i)=>{Hn(r,"ReduceSumSquareShared",i,"sumSquare")},Tu=(r,i)=>{Hn(r,"ReduceLogSumShared",i,"logSum")}}),Kn,ku,Cs,Ps,ni,Su,va,Eu,Cu,ba,Pu,$u,xa,Au,Iu,Qn,Fu,zu,Ma,Ou,Du,Ta,Lu,Ru,ka,Bu,Sa=h(()=>{Xt(),Yt(),mr(),or(),ep(),Kn=r=>{if(!r||r.length===0||r.length>2)throw new Error("Reduce op requires 1 or 2 inputs.");if(r.length===2&&r[1].dims.length!==1)throw new Error("Invalid axes input dims.")},ku=r=>["","",`var value = ${r.getByIndices("input_indices")};`,""],Cs=(r,i,s,u,c,p,d=!1,b=!1)=>{let T=[],E=s[0].dims,q=E.length,H=st.normalizeAxes(c,q),v=!b&&H.length===0;E.forEach((ce,_e)=>{v||H.indexOf(_e)>=0?d&&T.push(1):T.push(ce)});let ne=T.length,re=st.size(T);return{name:r,shaderCache:i,getShaderSource:ce=>{let _e=[],be=gt("_A",s[0].dataType,q),he=Vt("output",p,ne),Fe=u(be,he,H),xe=Fe[2];for(let Ie=0,ct=0;Ie=0?(d&&ct++,xe=`for(var j${Ie}: u32 = 0; j${Ie} < ${E[Ie]}; j${Ie}++) { + ${Fe[2].includes("last_index")?`let last_index = j${Ie};`:""} + ${be.indicesSet("input_indices",Ie,`j${Ie}`)} + ${xe} + }`):(_e.push(`${be.indicesSet("input_indices",Ie,he.indicesGet("output_indices",ct))};`),ct++);return` + + ${ce.registerUniform("output_size","u32").declareVariables(be,he)} + + ${ce.mainStart()} + ${ce.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + var input_indices: ${be.type.indices}; + let output_indices = ${he.offsetToIndices("global_idx")}; + + ${_e.join(` +`)} + ${Fe[0]} // init ops for reduce max/min + ${Fe[1]} + ${xe} + ${Fe[3]} + ${Fe.length===4?he.setByOffset("global_idx","value"):Fe.slice(4).join(` +`)} + }`},getRunData:()=>({outputs:[{dims:T,dataType:p}],dispatchGroup:{x:Math.ceil(re/64)},programUniforms:[{type:12,data:re},...Ct(E,T)]})}},Ps=(r,i)=>{let s=[];return r[1].dims[0]>0&&r[1].getBigInt64Array().forEach(u=>s.push(Number(u))),Gt({axes:s,keepDims:i.keepDims,noopWithEmptyAxes:i.noopWithEmptyAxes})},ni=(r,i,s,u)=>{let c=r.inputs,p=c.length===1?s:Ps(c,s);r.compute(Cs(i,{hint:p.cacheKey,inputDependencies:["rank"]},[c[0]],p.noopWithEmptyAxes&&p.axes.length===0?ku:u,p.axes,c[0].dataType,p.keepDims,p.noopWithEmptyAxes),{inputs:[0]})},Su=(r,i)=>{Kn(r.inputs),ni(r,"ReduceLogSum",i,(s,u)=>[`var value = ${u.type.storage}(0);`,"",`value += ${s.getByIndices("input_indices")};`,"value = log(value);"])},va=(r,i)=>{Kn(r.inputs),ni(r,"ReduceL1",i,(s,u)=>[`var value = ${u.type.storage}(0);`,"",`value += abs(${s.getByIndices("input_indices")});`,""])},Eu=(r,i)=>{Kn(r.inputs),ni(r,"ReduceL2",i,(s,u)=>[`var t = ${u.type.value}(0); var value = ${u.type.value}(0);`,"",`t = ${s.getByIndices("input_indices")}; value += (t * t);`,"value = sqrt(value);"])},Cu=(r,i)=>{Kn(r.inputs),ni(r,"ReduceLogSumExp",i,(s,u)=>[`var value = ${u.type.storage}(0);`,"",`value += exp(${s.getByIndices("input_indices")});`,"value = log(value);"])},ba=(r,i)=>{Kn(r.inputs),ni(r,"ReduceMax",i,(s,u,c)=>{let p=[];for(let d=0;d=0||c.length===0)&&p.push(s.indicesSet("input_indices",d,0));return[`${p.join(` +`)}`,`var value = ${s.getByIndices("input_indices")};`,`value = max(value, ${s.getByIndices("input_indices")});`,""]})},Pu=(r,i)=>{Kn(r.inputs),ni(r,"ReduceMean",i,(s,u,c)=>{let p=1;for(let d=0;d=0||c.length===0)&&(p*=r.inputs[0].dims[d]);return["var sum = f32(0);","",`sum += f32(${s.getByIndices("input_indices")});`,`let value = ${u.type.value}(sum / ${p});`]})},$u=(r,i)=>{Kn(r.inputs),ni(r,"ReduceMin",i,(s,u,c)=>{let p=[];for(let d=0;d=0||c.length===0)&&p.push(`input_indices[${d}] = 0;`);return[`${p.join(` +`)}`,`var value = ${s.getByIndices("input_indices")};`,`value = min(value, ${s.getByIndices("input_indices")});`,""]})},xa=(r,i)=>{Kn(r.inputs),ni(r,"ReduceProd",i,(s,u)=>[`var value = ${u.type.storage}(1);`,"",`value *= ${s.getByIndices("input_indices")};`,""])},Au=(r,i)=>{Kn(r.inputs),ni(r,"ReduceSum",i,(s,u)=>[`var value = ${u.type.storage}(0);`,"",`value += ${s.getByIndices("input_indices")};`,""])},Iu=(r,i)=>{Kn(r.inputs),ni(r,"ReduceSumSquare",i,(s,u)=>[`var t = ${u.type.value}(0); var value = ${u.type.value}(0);`,"",`t = ${s.getByIndices("input_indices")}; value += t * t;`,""])},Qn=(r,i,s)=>{if(i.length===0)return s;let u=1,c=1;for(let p=0;p1024},Fu=(r,i)=>{Qn(r.inputs[0].dims,i.axes,i.noopWithEmptyAxes)?Pu(r,i):yu(r,i)},zu=(r,i)=>{Qn(r.inputs[0].dims,i.axes,i.noopWithEmptyAxes)?va(r,i):wu(r,i)},Ma=(r,i)=>{Qn(r.inputs[0].dims,i.axes,i.noopWithEmptyAxes)?Eu(r,i):_a(r,i)},Ou=(r,i)=>{Qn(r.inputs[0].dims,i.axes,i.noopWithEmptyAxes)?Cu(r,i):vu(r,i)},Du=(r,i)=>{Qn(r.inputs[0].dims,i.axes,i.noopWithEmptyAxes)?ba(r,i):bu(r,i)},Ta=(r,i)=>{Qn(r.inputs[0].dims,i.axes,i.noopWithEmptyAxes)?$u(r,i):ya(r,i)},Lu=(r,i)=>{Qn(r.inputs[0].dims,i.axes,i.noopWithEmptyAxes)?xa(r,i):xu(r,i)},Ru=(r,i)=>{Qn(r.inputs[0].dims,i.axes,i.noopWithEmptyAxes)?Au(r,i):Mu(r,i)},ka=(r,i)=>{Qn(r.inputs[0].dims,i.axes,i.noopWithEmptyAxes)?Iu(r,i):wa(r,i)},Bu=(r,i)=>{Qn(r.inputs[0].dims,i.axes,i.noopWithEmptyAxes)?Su(r,i):Tu(r,i)}}),$s,Nu,ju,As,tp=h(()=>{Xt(),mr(),Sa(),$s=r=>{if(!r||r.length===0||r.length>2)throw new Error("ArgMinMaxOp op requires 1 or 2 inputs.");if(r[0].dataType!==1)throw new Error("Invalid input type.")},Nu=(r,i)=>{$s(r.inputs);let s=(u,c,p)=>{let d=[];for(let b=0;b=0||p.length===0)&&d.push(`input_indices[${b}] = 0;`);return[`${d.join(` +`)}`,`var value = ${u.getByIndices("input_indices")}; +var best_index : i32 = 0;`,`if (${u.getByIndices("input_indices")} ${i.selectLastIndex>0?"<=":"<"} value) { + value = ${u.getByIndices("input_indices")}; + best_index = i32(last_index); + }`,"",c.setByOffset("global_idx","best_index")]};r.compute(Cs("ArgMin",{hint:i.cacheKey,inputDependencies:["rank"]},[r.inputs[0]],s,[i.axis],7,i.keepDims),{inputs:[0]})},ju=(r,i)=>{$s(r.inputs);let s=(u,c,p)=>{let d=[];for(let b=0;b=0||p.length===0)&&d.push(`input_indices[${b}] = 0;`);return[`${d.join(` +`)}`,`var value = ${u.getByIndices("input_indices")}; +var best_index : i32 = 0;`,`if (${u.getByIndices("input_indices")} ${i.selectLastIndex>0?">=":">"} value) { + value = ${u.getByIndices("input_indices")}; + best_index = i32(last_index); + }`,"",c.setByOffset("global_idx","best_index")]};r.compute(Cs("argMax",{hint:i.cacheKey,inputDependencies:["rank"]},[r.inputs[0]],s,[i.axis],7,i.keepDims),{inputs:[0]})},As=r=>Gt(r)}),Uu,Ea,Vu,Wu,yo,Gu,qu,Is=h(()=>{Xt(),Yt(),fe(),or(),Uu=(r,i)=>{let s=r[0],u=r[1],c=r[2],p=r[3],d=r[4],b=r[5];if(d&&b)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 T=s.dims[0],E=s.dims[1],q=s.dims[2];if(c.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimensions');if(u.dims.length!==2)throw new Error('Input "weights" is expected to have 2 dimensions');if(u.dims[0]!==q)throw new Error("Input 1 dimension 0 should have same length as dimension 2 of input 0");if(c.dims[0]!==u.dims[1])throw new Error('Input "bias" dimension 0 should have same length as dimension 1 of input "weights"');let H=c.dims[0]/3,v=H,ne=v;if(i.qkvHiddenSizes.length>0){if(i.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let Fe of i.qkvHiddenSizes)if(Fe%i.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");H=i.qkvHiddenSizes[0],v=i.qkvHiddenSizes[1],ne=i.qkvHiddenSizes[2]}let re=E;if(H!==v)throw new Error("qkv_hidden_sizes first element should be same as the second");if(c.dims[0]!==H+v+ne)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let ce=0;if(d){if(v!==ne)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]!==T)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]!==v/i.numHeads)throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads');i.pastPresentShareBuffer||(ce=d.dims[3])}let _e=re+ce,be=-1,he=0;if(p)throw new Error("Mask not supported");if(d)throw new Error("past is not supported");if(b){if(b.dims.length!==4)throw new Error('Input "attention_bias" must have 4 dimensions');if(b.dims[0]!==T||b.dims[1]!==i.numHeads||b.dims[2]!==E||b.dims[3]!==_e)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:T,sequenceLength:E,pastSequenceLength:ce,kvSequenceLength:re,totalSequenceLength:_e,maxSequenceLength:be,inputHiddenSize:q,hiddenSize:H,vHiddenSize:ne,headSize:Math.floor(H/i.numHeads),vHeadSize:Math.floor(ne/i.numHeads),numHeads:i.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:i.maskFilterValue,maskType:he,scale:i.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},Ea=(r,i,s)=>{let u=wr(s),c=64,p=s/u;p{let ne=Vt("x",r.dataType,r.dims,u),re=kr(r.dataType),ce=[{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; + ${v.registerUniforms(ce).declareVariables(ne)} + ${v.mainStart([c,1,1])} + let local_offset = local_idx * uniforms.elements_per_thread; + let offset = (global_idx / ${c}) * uniforms.d_comp + local_offset; + + var thread_max_vector = ${E}(-3.402823e+38f); + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { + thread_max_vector = max(${E}(x[offset + i]), thread_max_vector); + } + thread_max[local_idx] = ${(()=>{switch(u){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: ${u}`)}})()}; + workgroupBarrier(); + + var max_value = f32(-3.402823e+38f); + for (var i = 0u; i < ${c}; i++) { + max_value = max(thread_max[i], max_value); + } + + var sum_vector = ${E}(0); + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { + sum_vector += exp(${E}(x[offset + i]) - max_value); + } + thread_sum[local_idx] = ${(()=>{switch(u){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: ${u}`)}})()}; + workgroupBarrier(); + + var sum: f32 = 0; + for (var i = 0u; i < ${c}; 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] = ${ne.type.value}(${re}(uniforms.d_inv)); + } + } else { + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { + var f32input = ${E}(x[offset + i]); + x[offset + i] = ${ne.type.value}(exp(f32input - max_value) / sum); + } + } + }`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${c};${T};${u}`,inputDependencies:q},getShaderSource:H,getRunData:()=>({outputs:[],dispatchGroup:{x:i},programUniforms:b})}},Vu=(r,i,s,u,c,p,d,b)=>{let T=b+p.kvSequenceLength,E=[p.batchSize,p.numHeads,p.sequenceLength,T],q=p.kvNumHeads===void 0&&r>1&&u,H=q?[p.batchSize,p.numHeads,T,p.headSize]:void 0,v=d.scale===0?1/Math.sqrt(p.headSize):d.scale,ne=wr(p.headSize),re=p.headSize/ne,ce=12,_e={x:Math.ceil(T/ce),y:Math.ceil(p.sequenceLength/ce),z:p.batchSize*p.numHeads},be=[{type:12,data:p.sequenceLength},{type:12,data:re},{type:12,data:T},{type:12,data:p.numHeads},{type:1,data:v},{type:12,data:b},{type:12,data:p.kvSequenceLength}],he=q&&u&&st.size(u.dims)>0,Fe=["type","type"];he&&Fe.push("type"),c&&Fe.push("type");let xe=[{dims:E,dataType:i.dataType,gpuDataType:0}];q&&xe.push({dims:H,dataType:i.dataType,gpuDataType:0});let Ie=ct=>{let et=gt("q",i.dataType,i.dims,ne),vt=gt("key",s.dataType,s.dims,ne),Ft=[et,vt];if(he){let yr=gt("past_key",u.dataType,u.dims,ne);Ft.push(yr)}c&&Ft.push(gt("attention_bias",c.dataType,c.dims));let Lt=Vt("output",i.dataType,E),pr=[Lt];q&&pr.push(Vt("present_key",i.dataType,H,ne));let ar=kr(1,ne),nr=[{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 = ${ce}u; + + var tileQ: array<${et.type.storage}, ${ce*ce}>; + var tileK: array<${et.type.storage}, ${ce*ce}>; + ${ct.registerUniforms(nr).declareVariables(...Ft,...pr)} + ${ct.mainStart([ce,ce,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; + ${he&&q?` + 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;`} + ${q?"let presentKeyOffset = headIdx * uniforms.N * uniforms.K;":""} + var value = ${ar}(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; + ${he&&q?` + 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];"} + ${q?"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 += ${ar}(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(ne){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: ${ne}`)}})()}; + output[outputIdx] = ${Lt.type.value} (sum * uniforms.alpha) + ${c?"attention_bias[outputIdx]":"0.0"}; + } + }`};return{name:"AttentionProbs",shaderCache:{hint:`${ne};${c!==void 0};${u!==void 0};${r}`,inputDependencies:Fe},getRunData:()=>({outputs:xe,dispatchGroup:_e,programUniforms:be}),getShaderSource:Ie}},Wu=(r,i,s,u,c,p)=>{let d=p+c.kvSequenceLength,b=c.nReps?c.nReps:1,T=c.vHiddenSize*b,E=c.kvNumHeads==null&&r>1&&u,q=E?[c.batchSize,c.numHeads,d,c.headSize]:void 0,H=[c.batchSize,c.sequenceLength,T],v=12,ne={x:Math.ceil(c.vHeadSize/v),y:Math.ceil(c.sequenceLength/v),z:c.batchSize*c.numHeads},re=[{type:12,data:c.sequenceLength},{type:12,data:d},{type:12,data:c.vHeadSize},{type:12,data:c.numHeads},{type:12,data:T},{type:12,data:p},{type:12,data:c.kvSequenceLength}],ce=E&&u&&st.size(u.dims)>0,_e=["type","type"];ce&&_e.push("type");let be=[{dims:H,dataType:i.dataType,gpuDataType:0}];E&&be.push({dims:q,dataType:i.dataType,gpuDataType:0});let he=Fe=>{let xe=gt("probs",i.dataType,i.dims),Ie=gt("v",s.dataType,s.dims),ct=[xe,Ie];ce&&ct.push(gt("past_value",u.dataType,u.dims));let et=[Vt("output",i.dataType,H)];E&&et.push(Vt("present_value",i.dataType,q));let vt=[{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 = ${v}u; + var tileQ: array<${xe.type.value}, ${v*v}>; + var tileK: array<${xe.type.value}, ${v*v}>; + ${Fe.registerUniforms(vt).declareVariables(...ct,...et)} + ${Fe.mainStart([v,v,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; + ${ce&&E?` + 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; + `} + ${E?"let presentValueOffset = headIdx * uniforms.N * uniforms.K + n;":""} + var value = ${xe.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; + ${ce&&E?` + 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]; + `} + ${E?"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:`${u!==void 0};${r}`,inputDependencies:_e},getRunData:()=>({outputs:be,dispatchGroup:ne,programUniforms:re}),getShaderSource:he}},yo=(r,i,s,u,c,p,d,b,T,E,q)=>{let H=Math.min(r.outputCount,1+(d?1:0)+(b?1:0)),v=E.kvNumHeads!==void 0||H>1?E.pastSequenceLength:0,ne=v+E.kvSequenceLength,re=T&&st.size(T.dims)>0?T:void 0,ce=[i,s];E.kvNumHeads===void 0&&H>1&&d&&st.size(d.dims)>0&&ce.push(d),re&&ce.push(re);let _e=r.compute(Vu(H,i,s,d,re,E,q,v),{inputs:ce,outputs:E.kvNumHeads===void 0&&H>1?[-1,1]:[-1]})[0];r.compute(Ea(_e,E.batchSize*E.numHeads*E.sequenceLength,ne),{inputs:[_e],outputs:[]});let be=[_e,u];E.kvNumHeads===void 0&&H>1&&b&&st.size(b.dims)>0&&be.push(b),r.compute(Wu(H,_e,u,b,E,v),{inputs:be,outputs:E.kvNumHeads===void 0&&H>1?[0,2]:[0]})},Gu=(r,i)=>{let s=[i.batchSize,i.numHeads,i.sequenceLength,i.headSize],u=i.sequenceLength,c=i.inputHiddenSize,p=i.headSize,d=12,b={x:Math.ceil(i.headSize/d),y:Math.ceil(i.sequenceLength/d),z:i.batchSize*i.numHeads},T=[r.inputs[0],r.inputs[1],r.inputs[2]],E=[{type:12,data:u},{type:12,data:c},{type:12,data:p},{type:12,data:i.numHeads},{type:12,data:i.headSize},{type:12,data:i.hiddenSize},{type:12,data:i.hiddenSize+i.hiddenSize+i.vHiddenSize}],q=H=>{let v=Vt("output_q",T[0].dataType,s),ne=Vt("output_k",T[0].dataType,s),re=Vt("output_v",T[0].dataType,s),ce=gt("input",T[0].dataType,T[0].dims),_e=gt("weight",T[1].dataType,T[1].dims),be=gt("bias",T[2].dataType,T[2].dims),he=ce.type.storage,Fe=[{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<${he}, ${d*d}>; + var tileWeightQ: array<${he}, ${d*d}>; + var tileWeightK: array<${he}, ${d*d}>; + var tileWeightV: array<${he}, ${d*d}>; + ${H.registerUniforms(Fe).declareVariables(ce,_e,be,v,ne,re)} + ${H.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 = ${he}(0); + var valueK = ${he}(0); + var valueV = ${he}(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:r.inputs[0].dataType,gpuDataType:0},{dims:s,dataType:r.inputs[0].dataType,gpuDataType:0},{dims:s,dataType:r.inputs[0].dataType,gpuDataType:0}],dispatchGroup:b,programUniforms:E}),getShaderSource:q},{inputs:T,outputs:[-1,-1,-1]})},qu=(r,i)=>{let s=Uu(r.inputs,i),[u,c,p]=Gu(r,s);return yo(r,u,c,p,r.inputs[4],void 0,void 0,void 0,r.inputs[5],s,i)}}),Hu,Ku,Qu,Xu,Yu=h(()=>{Z(),Xt(),Yt(),mr(),or(),Hu=(r,i)=>{if(!r||r.length!==5)throw new Error("BatchNormalization requires 5 inputs");let s=(u,c,p)=>{let d=c.length;if(d!==u.length)throw new Error(`${p}: num dimensions != ${d}`);c.forEach((b,T)=>{if(b!==u[T])throw new Error(`${p}: dim[${T}] do not match`)})};if(r[0].dims.length>1){let u=i.format==="NHWC"?i.spatial?r[0].dims.slice(-1):r[0].dims.slice(-1).concat(r[0].dims.slice(1,r[0].dims.length-1)):r[0].dims.slice(1,i.spatial?2:void 0);s(r[1].dims,u,"Invalid input scale"),s(r[2].dims,u,"Invalid input B"),s(r[3].dims,u,"Invalid input mean"),s(r[4].dims,u,"Invalid input var")}else s(r[1].dims,[1],"Invalid input scale"),s(r[2].dims,[1],"Invalid input B"),s(r[3].dims,[1],"Invalid input mean"),s(r[4].dims,[1],"Invalid input var")},Ku=(r,i)=>{let{epsilon:s,spatial:u,format:c}=i,p=r[0].dims,d=u?wr(p[p.length-1]):1,b=c==="NHWC"&&p.length>1?d:1,T=st.size(p)/d,E=u,q=E?p.length:p,H=gt("x",r[0].dataType,r[0].dims,d),v=gt("scale",r[1].dataType,r[1].dims,b),ne=gt("bias",r[2].dataType,r[2].dims,b),re=gt("inputMean",r[3].dataType,r[3].dims,b),ce=gt("inputVar",r[4].dataType,r[4].dims,b),_e=Vt("y",r[0].dataType,q,d),be=()=>{let Fe="";if(u)Fe=`let cOffset = ${p.length===1?"0u":c==="NHWC"?`outputIndices[${p.length-1}] / ${d}`:"outputIndices[1]"};`;else if(c==="NCHW")Fe=` + ${_e.indicesSet("outputIndices","0","0")} + let cOffset = ${_e.indicesToOffset("outputIndices")};`;else{Fe=`var cIndices = ${v.type.indices}(0); + cIndices[0] = outputIndices[${p.length-1}];`;for(let xe=1;xe` + const epsilon = ${s}; + ${Fe.registerUniform("outputSize","u32").declareVariables(H,v,ne,re,ce,_e)} + ${Fe.mainStart()} + ${Fe.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var outputIndices = ${_e.offsetToIndices(`global_idx * ${d}`)}; + ${be()} + let scale = ${v.getByOffset("cOffset")}; + let bias = ${ne.getByOffset("cOffset")}; + let inputMean = ${re.getByOffset("cOffset")}; + let inputVar = ${ce.getByOffset("cOffset")}; + let x = ${H.getByOffset("global_idx")}; + let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias; + ${_e.setByOffset("global_idx","value")} + }`;return{name:"BatchNormalization",shaderCache:{hint:`${i.epsilon}_${i.format}_${u}_${d}`,inputDependencies:E?["rank","type","type","type","type"]:void 0},getShaderSource:he,getRunData:()=>({outputs:[{dims:r[0].dims,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(T/64)},programUniforms:E?[{type:12,data:T},...Ct(p)]:[{type:12,data:T}]})}},Qu=r=>Gt(r),Xu=(r,i)=>{let{inputs:s,outputCount:u}=r,c=Qu({...i,outputCount:u});if(D.webgpu.validateInputContent&&Hu(s,c),i.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");r.compute(Ku(s,c))}}),Zu,Ju,Ca,rp=h(()=>{Yt(),or(),Zu=r=>{if(r[0].dims.length!==3)throw new Error("input should have 3 dimensions");if(![320,640,1280].includes(r[0].dims[2]))throw new Error("number of channels should be 320, 640 or 1280");if(r[1].dims.length!==1)throw new Error("bias is expected to have 1 dimensions");if(r[0].dims[2]!==r[1].dims[0])throw new Error("last dimension of input and bias are not the same")},Ju=r=>{let i=r[0].dims,s=r[0].dims[2],u=st.size(i)/4,c=r[0].dataType,p=gt("input",c,i,4),d=gt("bias",c,[s],4),b=gt("residual",c,i,4),T=Vt("output",c,i,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:i,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)}}),getShaderSource:E=>` + const channels = ${s}u / 4; + ${E.declareVariables(p,d,b,T)} + + ${E.mainStart()} + ${E.guardAgainstOutOfBoundsWorkgroupSizes(u)} + let value = ${p.getByOffset("global_idx")} + + ${d.getByOffset("global_idx % channels")} + ${b.getByOffset("global_idx")}; + ${T.setByOffset("global_idx","value")} + }`}},Ca=r=>{Zu(r.inputs),r.compute(Ju(r.inputs))}}),ec,vr,tc,rc,Pa,nc,ic,$a,oc,sc,Fs,ac,lc,uc,Aa,cc,wo,dc,zs,fc,Ia,pc,hc,mc,Fa,gc,_c,za,yc,wc,Oa,vc,bc,Da,xc,La,Ra,Ba,Na,Mc,Tc,ja,kc,Sc,Ec,Ua=h(()=>{Xt(),Yt(),mr(),or(),ec=(r,i,s,u,c,p)=>{let d=Math.ceil(i/4),b="";typeof c=="string"?b=`${c}(a)`:b=c("a");let T=gt("inputData",s,[d],4),E=Vt("outputData",u,[d],4);return` + ${r.registerUniform("vec_size","u32").declareVariables(T,E)} + + ${p??""} + + ${r.mainStart()} + ${r.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + + let a = ${T.getByOffset("global_idx")}; + ${E.setByOffset("global_idx",b)} + }`},vr=(r,i,s,u,c,p=r.dataType)=>({name:i,shaderCache:{hint:c,inputDependencies:["type"]},getShaderSource:d=>ec(d,st.size(r.dims),r.dataType,p,s,u),getRunData:d=>({outputs:[{dims:r.dims,dataType:p}],dispatchGroup:{x:Math.ceil(st.size(d[0].dims)/64/4)},programUniforms:[{type:12,data:Math.ceil(st.size(r.dims)/4)}]})}),tc=r=>{r.compute(vr(r.inputs[0],"Abs","abs"))},rc=r=>{r.compute(vr(r.inputs[0],"Acos","acos"))},Pa=r=>{r.compute(vr(r.inputs[0],"Acosh","acosh"))},nc=r=>{r.compute(vr(r.inputs[0],"Asin","asin"))},ic=r=>{r.compute(vr(r.inputs[0],"Asinh","asinh"))},$a=r=>{r.compute(vr(r.inputs[0],"Atan","atan"))},oc=r=>{r.compute(vr(r.inputs[0],"Atanh","atanh"))},sc=r=>Gt(r),Fs=(r,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}`)}r.compute(vr(r.inputs[0],"Cast",s,void 0,i.cacheKey,i.to))},ac=r=>{let i=r.length>=2&&r[1].data!==0?r[1].getFloat32Array()[0]:an,s=r.length>=3&&r[2].data!==0?r[2].getFloat32Array()[0]:$n;return Gt({min:i,max:s})},lc=(r,i)=>{let s=r.inputs.length===1?i:ac(r.inputs),u=kr(r.inputs[0].dataType);r.compute(vr(r.inputs[0],"Clip",c=>`clamp(${c}, clip_min_, clip_max_)`,` + const clip_min_: vec4<${u}> = vec4(${u}(${s.min})); + const clip_max_: vec4<${u}> = vec4(${u}(${s.max})); +`,s.cacheKey),{inputs:[0]})},uc=r=>{r.compute(vr(r.inputs[0],"Ceil","ceil"))},Aa=r=>{r.compute(vr(r.inputs[0],"Cos","cos"))},cc=r=>{r.compute(vr(r.inputs[0],"Cosh","cosh"))},wo=r=>Gt(r),dc=(r,i)=>{let s=kr(r.inputs[0].dataType);r.compute(vr(r.inputs[0],"Elu",u=>`elu_vf32(${u})`,` + 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))},zs=(r="f32")=>` +const r0: ${r} = 0.3275911; +const r1: ${r} = 0.254829592; +const r2: ${r} = -0.284496736; +const r3: ${r} = 1.421413741; +const r4: ${r} = -1.453152027; +const r5: ${r} = 1.061405429; + +fn erf_vf32(v: vec4<${r}>) -> vec4<${r}> { + 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)); +}`,fc=r=>{let i=kr(r.inputs[0].dataType);r.compute(vr(r.inputs[0],"Erf",s=>`erf_vf32(${s})`,zs(i)))},Ia=r=>{r.compute(vr(r.inputs[0],"Exp","exp"))},pc=r=>{r.compute(vr(r.inputs[0],"Floor","floor"))},hc=r=>{let i=kr(r.inputs[0].dataType);r.compute(vr(r.inputs[0],"Gelu",s=>`0.5 * ${s} * (1.0 + erf_vf32(${s} * 0.7071067811865475))`,zs(i)))},mc=(r,i)=>{let s=kr(r.inputs[0].dataType);r.compute(vr(r.inputs[0],"LeakyRelu",u=>`select(leaky_relu_alpha_ * ${u}, ${u}, ${u} >= vec4<${s}>(0.0))`,`const leaky_relu_alpha_ = ${s}(${i.alpha});`,i.cacheKey))},Fa=r=>{r.compute(vr(r.inputs[0],"Not",i=>`!${i}`))},gc=r=>{r.compute(vr(r.inputs[0],"Neg",i=>`-${i}`))},_c=r=>{r.compute(vr(r.inputs[0],"Reciprocal",i=>`1.0/${i}`))},za=r=>{let i=kr(r.inputs[0].dataType);r.compute(vr(r.inputs[0],"Relu",s=>`select(vec4<${i}>(0.0), ${s}, ${s} > vec4<${i}>(0.0))`))},yc=r=>{r.compute(vr(r.inputs[0],"Sigmoid",i=>`(1.0 / (1.0 + exp(-${i})))`))},wc=r=>Gt(r),Oa=(r,i)=>{let s=kr(r.inputs[0].dataType);r.compute(vr(r.inputs[0],"HardSigmoid",u=>`max(vec4<${s}>(0.0), min(vec4<${s}>(1.0), ${i.alpha} * ${u} + vec4<${s}>(${i.beta})))`,void 0,i.cacheKey))},vc=r=>{r.compute(vr(r.inputs[0],"Sin","sin"))},bc=r=>{r.compute(vr(r.inputs[0],"Sinh","sinh"))},Da=r=>{r.compute(vr(r.inputs[0],"Sqrt","sqrt"))},xc=r=>{r.compute(vr(r.inputs[0],"Tan","tan"))},La=r=>`sign(${r}) * (1 - exp(-2 * abs(${r}))) / (1 + exp(-2 * abs(${r})))`,Ra=r=>{r.compute(vr(r.inputs[0],"Tanh",La))},Ba=(r="f32")=>` +const fast_gelu_a: ${r} = 0.5; +const fast_gelu_b: ${r} = 0.7978845608028654; +const fast_gelu_c: ${r} = 0.035677408136300125; + +fn tanh_v(v: vec4<${r}>) -> vec4<${r}> { + return ${La("v")}; +} +`,Na=r=>`(fast_gelu_a + fast_gelu_a * tanh_v(${r} * (fast_gelu_c * ${r} * ${r} + fast_gelu_b))) * ${r}`,Mc=r=>{let i=kr(r.inputs[0].dataType);r.compute(vr(r.inputs[0],"FastGelu",Na,Ba(i),void 0,r.inputs[0].dataType))},Tc=(r,i)=>{let s=kr(r.inputs[0].dataType);return r.compute(vr(r.inputs[0],"ThresholdedRelu",u=>`select(vec4<${s}>(0.0), ${u}, ${u} > thresholded_relu_alpha_)`,`const thresholded_relu_alpha_ = vec4<${s}>(${i.alpha});`,i.cacheKey)),0},ja=r=>{r.compute(vr(r.inputs[0],"Log","log"))},kc=(r,i)=>` +const alpha = vec4<${r}>(${i}); +const one = ${r}(1.0); +const zero = ${r}(0.0); + +fn quick_gelu_impl(x: vec4<${r}>) -> vec4<${r}> { + let v = x *alpha; + var x1 : vec4<${r}>; + 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; +} +`,Sc=r=>`quick_gelu_impl(${r})`,Ec=(r,i)=>{let s=kr(r.inputs[0].dataType);r.compute(vr(r.inputs[0],"QuickGelu",Sc,kc(s,i.alpha),i.cacheKey,r.inputs[0].dataType))}}),Va,Cc,Pc,$c=h(()=>{Yt(),or(),Ua(),Va=r=>{if(r[0].dims.length!==3)throw new Error("input should have 3 dimensions");if(![2560,5120,10240].includes(r[0].dims[2]))throw new Error("hidden state should be 2560, 5120 or 10240");if(r[1].dims.length!==1)throw new Error("bias is expected to have 1 dimensions");if(r[0].dims[2]!==r[1].dims[0])throw new Error("last dimension of input and bias are not the same")},Cc=r=>{let i=r[0].dims.slice();i[2]=i[2]/2;let s=gt("input",r[0].dataType,r[0].dims,4),u=gt("bias",r[0].dataType,[r[0].dims[2]],4),c=Vt("output",r[0].dataType,i,4),p=st.size(i)/4,d=Tr(r[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:i,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)}}),getShaderSource:b=>` + const M_SQRT2 = sqrt(2.0); + const halfChannels = ${r[0].dims[2]/4/2}u; + + ${b.declareVariables(s,u,c)} + + ${zs(d)} + + ${b.mainStart()} + ${b.guardAgainstOutOfBoundsWorkgroupSizes(p)} + 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); + + ${c.setByOffset("global_idx","valueLeft * geluRight")} + }`}},Pc=r=>{Va(r.inputs),r.compute(Cc(r.inputs))}}),Ac,Ic,Xn,Fc,zc,Wa,Oc,Dc,Lc,Rc,Bc,Nc,Ga,np=h(()=>{Xt(),Yt(),or(),Ac=(r,i,s,u,c,p,d,b,T,E,q,H)=>{let v,ne;typeof b=="string"?v=ne=(he,Fe)=>`${b}((${he}),(${Fe}))`:typeof b=="function"?v=ne=b:(v=b.scalar,ne=b.vector);let re=Vt("outputData",q,u.length,4),ce=gt("aData",T,i.length,4),_e=gt("bData",E,s.length,4),be;if(c)if(p){let he=st.size(i)===1,Fe=st.size(s)===1,xe=i.length>0&&i[i.length-1]%4===0,Ie=s.length>0&&s[s.length-1]%4===0;he||Fe?be=re.setByOffset("global_idx",ne(he?`${ce.type.value}(${ce.getByOffset("0")}.x)`:ce.getByOffset("global_idx"),Fe?`${_e.type.value}(${_e.getByOffset("0")}.x)`:_e.getByOffset("global_idx"))):be=` + let outputIndices = ${re.offsetToIndices("global_idx * 4u")}; + let offsetA = ${ce.broadcastedIndicesToOffset("outputIndices",re)}; + let offsetB = ${_e.broadcastedIndicesToOffset("outputIndices",re)}; + ${re.setByOffset("global_idx",ne(d||xe?ce.getByOffset("offsetA / 4u"):`${ce.type.value}(${ce.getByOffset("offsetA / 4u")}[offsetA % 4u])`,d||Ie?_e.getByOffset("offsetB / 4u"):`${_e.type.value}(${_e.getByOffset("offsetB / 4u")}[offsetB % 4u])`))} + `}else be=re.setByOffset("global_idx",ne(ce.getByOffset("global_idx"),_e.getByOffset("global_idx")));else{if(!p)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let he=(Fe,xe,Ie="")=>{let ct=`aData[indexA${xe}][componentA${xe}]`,et=`bData[indexB${xe}][componentB${xe}]`;return` + let outputIndices${xe} = ${re.offsetToIndices(`global_idx * 4u + ${xe}u`)}; + let offsetA${xe} = ${ce.broadcastedIndicesToOffset(`outputIndices${xe}`,re)}; + let offsetB${xe} = ${_e.broadcastedIndicesToOffset(`outputIndices${xe}`,re)}; + let indexA${xe} = offsetA${xe} / 4u; + let indexB${xe} = offsetB${xe} / 4u; + let componentA${xe} = offsetA${xe} % 4u; + let componentB${xe} = offsetB${xe} % 4u; + ${Fe}[${xe}] = ${Ie}(${v(ct,et)}); + `};q===9?be=` + var data = vec4(0); + ${he("data",0,"u32")} + ${he("data",1,"u32")} + ${he("data",2,"u32")} + ${he("data",3,"u32")} + outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:be=` + ${he("outputData[global_idx]",0)} + ${he("outputData[global_idx]",1)} + ${he("outputData[global_idx]",2)} + ${he("outputData[global_idx]",3)} + `}return` + ${r.registerUniform("vec_size","u32").declareVariables(ce,_e,re)} + + ${H??""} + + ${r.mainStart()} + ${r.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${be} + }`},Ic=(r,i,s,u,c,p,d=s.dataType)=>{let b=!st.areEqual(s.dims,u.dims),T=s.dims,E=st.size(s.dims),q=!1,H=!1,v=[b];if(b){let ne=pn.calcShape(s.dims,u.dims,!1);if(!ne)throw new Error("Can't perform binary op on the given tensors");T=ne,E=st.size(T);let re=st.size(s.dims)===1,ce=st.size(u.dims)===1,_e=s.dims.length>0&&s.dims[s.dims.length-1]%4===0,be=u.dims.length>0&&u.dims[u.dims.length-1]%4===0;v.push(re),v.push(ce),v.push(_e),v.push(be);let he=1;for(let Fe=1;Fene.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:ne=>Ac(ne,s.dims,u.dims,T,q,b,H,c,s.dataType,u.dataType,d,p),getRunData:()=>({outputs:[{dims:T,dataType:d}],dispatchGroup:{x:Math.ceil(E/64/4)},programUniforms:[{type:12,data:Math.ceil(st.size(T)/4)},...Ct(s.dims,u.dims,T)]})}},Xn=(r,i,s,u,c,p)=>{r.compute(Ic(i,c??"",r.inputs[0],r.inputs[1],s,u,p))},Fc=r=>{Xn(r,"Add",(i,s)=>`${i}+${s}`)},zc=r=>{Xn(r,"Div",(i,s)=>`${i}/${s}`)},Wa=r=>{Xn(r,"Equal",{scalar:(i,s)=>`u32(${i}==${s})`,vector:(i,s)=>`vec4(${i}==${s})`},void 0,void 0,9)},Oc=r=>{Xn(r,"Mul",(i,s)=>`${i}*${s}`)},Dc=r=>{let i=gt("input",r.inputs[0].dataType,r.inputs[0].dims).type.value;Xn(r,"Pow",{scalar:(s,u)=>`pow_custom(${s},${u})`,vector:(s,u)=>`pow_vector_custom(${s},${u})`},` + 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)); + } + `)},Lc=r=>{Xn(r,"Sub",(i,s)=>`${i}-${s}`)},Rc=r=>{Xn(r,"Greater",{scalar:(i,s)=>`u32(${i}>${s})`,vector:(i,s)=>`vec4(${i}>${s})`},void 0,void 0,9)},Bc=r=>{Xn(r,"Less",{scalar:(i,s)=>`u32(${i}<${s})`,vector:(i,s)=>`vec4(${i}<${s})`},void 0,void 0,9)},Nc=r=>{Xn(r,"GreaterOrEqual",{scalar:(i,s)=>`u32(${i}>=${s})`,vector:(i,s)=>`vec4(${i}>=${s})`},void 0,void 0,9)},Ga=r=>{Xn(r,"LessOrEqual",{scalar:(i,s)=>`u32(${i}<=${s})`,vector:(i,s)=>`vec4(${i}<=${s})`},void 0,void 0,9)}}),jc,qa,Uc,Vc,Ni,Wc,ip=h(()=>{Xt(),Yt(),mr(),or(),jc=(r,i)=>{if(!r||r.length<1)throw new Error("too few inputs");let s=0,u=r[s],c=u.dataType,p=u.dims.length;r.forEach((d,b)=>{if(b!==s){if(d.dataType!==c)throw new Error("input tensors should be one type");if(d.dims.length!==p)throw new Error("input tensors should have the same shape");d.dims.forEach((T,E)=>{if(E!==i&&T!==u.dims[E])throw new Error("non concat dimensions must match")})}})},qa=(r,i)=>` + fn calculateInputIndex(index: u32) -> u32 { + let sizeInConcatAxis = array(${i}); + for (var i: u32 = 0u; i < ${r}; i += 1u ) { + if (index < sizeInConcatAxis[i]) { + return i; + } + } + return ${r}u; + }`,Uc=(r,i)=>{let s=r.length,u=[];for(let c=0;c{let c=st.size(s),p=new Array(r.length),d=new Array(r.length),b=0,T=[],E=[],q=[{type:12,data:c}];for(let ce=0;ce`uniforms.sizeInConcatAxis${ce}`).join(","),re=ce=>` + + ${(()=>{ce.registerUniform("outputSize","u32");for(let _e=0;_e(${ne}); + ${v} -= sizeInConcatAxis[inputIndex - 1u]; + } + + ${Uc(d,H)} + }`;return{name:"Concat",shaderCache:{hint:`${i}`,inputDependencies:T},getRunData:()=>({outputs:[{dims:s,dataType:u}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:q}),getShaderSource:re}},Ni=(r,i)=>{let s=r.inputs,u=s[0].dims,c=st.normalizeAxis(i.axis,u.length);jc(s,c);let p=u.slice();p[c]=s.reduce((b,T)=>b+(T.dims.length>c?T.dims[c]:0),0);let d=s.filter(b=>st.size(b.dims)>0);r.compute(Vc(d,c,p,s[0].dataType),{inputs:d})},Wc=r=>Gt({axis:r.axis})}),ji,Ui,ki,Ha,Vi=h(()=>{Xt(),Yt(),ji=(r,i,s="f32")=>{switch(r.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 ${r.activation}`)}},Ui=(r,i)=>{r.activation==="Clip"?i.push({type:1,data:r.clipMax},{type:1,data:r.clipMin}):r.activation==="HardSigmoid"?i.push({type:1,data:r.alpha},{type:1,data:r.beta}):r.activation==="LeakyRelu"&&i.push({type:1,data:r.alpha})},ki=(r,i)=>{r.activation==="Clip"?i.push({name:"clip_max",type:"f32"},{name:"clip_min",type:"f32"}):r.activation==="HardSigmoid"?i.push({name:"alpha",type:"f32"},{name:"beta",type:"f32"}):r.activation==="LeakyRelu"&&i.push({name:"alpha",type:"f32"})},Ha=r=>{let i=(r==null?void 0:r.activation)||"";if(i==="HardSigmoid"){let[s,u]=(r==null?void 0:r.activation_params)||[.2,.5];return{activation:i,alpha:s,beta:u}}else if(i==="Clip"){let[s,u]=(r==null?void 0:r.activation_params)||[an,$n];return{activation:i,clipMax:u,clipMin:s}}else if(i==="LeakyRelu"){let[s]=(r==null?void 0:r.activation_params)||[.01];return{activation:i,alpha:s}}return{activation:i}}}),_n,Ka,vo=h(()=>{_n=(r,i)=>{switch(r){case 1:return i;case 2:return`vec2<${i}>`;case 3:return`vec3<${i}>`;case 4:return`vec4<${i}>`;default:throw new Error(`${r}-component is not supported.`)}},Ka=r=>` + ${r?"value = value + getBiasByOutputCoords(coords);":""} + `}),Qa,Gc=h(()=>{Qa=r=>` +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(${r}.x), i32(${r}.y), i32(${r}.z), 1)); +} +`}),qc,Go,Os,Xa,Hc,Ds,Ls,Ya,Rs=h(()=>{Xt(),Yt(),or(),Vi(),vo(),qc=(r,i)=>r?` + 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":""}); + `,Go=(r,i)=>r?` + 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];"} + }`,Os=(r,i,s="f32",u,c=!1,p=32,d=!1,b=32)=>{let T=i[1]*r[1],E=i[0]*r[0],q=c?T:p,H=c?p:T,v=q/i[0],ne=p/i[1];if(!((c&&v===4&&r[1]===4||!c&&(v===3||v===4))&&q%i[0]===0&&p%i[1]===0&&r[0]===4))throw new Error(`If transposeA ${c} is true, innerElementSize ${v} and workPerThread[1] ${r[1]} must be 4. + Otherwise, innerElementSize ${v} must be 3 or 4. + tileAWidth ${q} must be divisible by workgroupSize[0]${i[0]}. tileInner ${p} must be divisible by workgroupSize[1] ${i[1]}. colPerThread ${r[0]} must be 4.`);return` +var mm_Asub: array, ${q/v}>, ${H}>; +var mm_Bsub: array, ${E/r[0]}>, ${p}>; + +const rowPerThread = ${r[1]}; +const colPerThread = ${r[0]}; +const innerElementSize = ${v}; +const tileInner = ${p}; + +@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)"}; + ${u?`let batchIndices = ${u.offsetToIndices("u32(batch)")};`:""} + let globalRowStart = i32(workgroupId.y) * ${T}; + + let num_tiles = ${d?`${Math.ceil(b/p)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; + var kStart = ${d?`i32(globalId.z) * ${b}`:"0"}; + + var acc: array, rowPerThread>; + + // Loop over shared dimension. + let tileRowB = localRow * ${ne}; + 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; + ${qc(c,u)} + } + + // Load one tile of B into local memory. + for (var innerRow = 0; innerRow < ${ne}; innerRow = innerRow + 1) { + let inputRow = tileRowB + innerRow; + let inputCol = tileCol; + mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol${u?", 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]; + ${v===3?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"} + + ${Go(c,v)} + } + + workgroupBarrier(); + } + + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]); + } +}`},Xa=(r,i)=>r?` + 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":""}); + `,Hc=r=>r?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",Ds=(r,i,s="f32",u,c=!1,p=32,d=!1,b=32,T=!1)=>{let E=r[1]*i[1],q=r[0]*i[0],H=c?E:p,v=c?p:E;if(!(v%i[1]===0&&H%i[0]===0&&p%i[1]===0))throw new Error(`tileAHight ${v} must be divisible by workgroupSize[1]${i[1]}, tileAWidth ${H} must be divisible by workgroupSize[0]${i[0]}, tileInner ${p} must be divisible by workgroupSize[1]${i[1]}`);let ne=v/i[1],re=H/i[0],ce=p/i[1],_e=T?` + let localRow = i32(localId.y); + let localCol = i32(localId.x); + let globalRowStart = i32(workgroupId.y) * ${E}; + let globalColStart = i32(workgroupId.x) * ${q}; + + // 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 < ${v}; inputRow = inputRow + ${i[1]}) { + for (var inputCol = localCol; inputCol < ${H}; inputCol = inputCol + ${i[0]}) { + ${Xa(c,u)} + } + } + // Load one tile of B into local memory. + for (var inputRow = localRow; inputRow < ${p}; inputRow = inputRow + ${i[1]}) { + for (var inputCol = localCol; inputCol < ${q}; inputCol = inputCol + ${i[0]}) { + mm_Bsub[inputRow][inputCol] = mm_readB(batch, + kStart + inputRow, + globalColStart + inputCol${u?", 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 = ${c?`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) * ${E}; + +let tileRowA = i32(localId.y) * ${ne}; +let tileColA = i32(localId.x) * ${re}; +let tileRowB = i32(localId.y) * ${ce}; +// 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 < ${ne}; innerRow = innerRow + 1) { + for (var innerCol = 0; innerCol < ${re}; innerCol = innerCol + 1) { + let inputRow = tileRowA + innerRow; + let inputCol = tileColA + innerCol; + ${Xa(c,u)} + } + } + + // Load one tile of B into local memory. + for (var innerRow = 0; innerRow < ${ce}; 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${u?", 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) { + ${Hc(c)} + 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, ${v}>; + var mm_Bsub : array, ${p}>; + const rowPerThread = ${r[1]}; + const colPerThread = ${r[0]}; + const tileInner = ${p}; + +@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)"}; + ${u?`let batchIndices = ${u.offsetToIndices("u32(batch)")};`:""} + let num_tiles = ${d?`${Math.ceil(b/p)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; + var kStart = ${d?`i32(globalId.z) * ${b}`:"0"}; + + var acc : array, rowPerThread>; + ${_e} + } +`},Ls=(r,i,s,u,c,p=!1)=>{let[d,b,T]=c,[E,q,H,v]=u,ne=go(d,T),re=go(b,T),ce=Tr(u[0].type.tensor),_e=()=>{let he=q.rank,Fe=E.rank,xe=`var aIndices: ${q.type.indices};`;for(let Ie=he-2-1,ct=Fe-1;Ie>=0;Ie--,ct--)xe+=` +aIndices[${Ie}] = ${Fe>1?`batchIndices[${ct}]`:"batchIndices"};`;return ne.forEach(Ie=>{xe+=` +aIndices[${Ie}] = 0;`}),xe+=` +aIndices[${he-2}] = u32(row); + aIndices[${he-1}] = u32(colIn);`,xe},be=()=>{let he=H.rank,Fe=E.rank,xe=`var bIndices: ${H.type.indices};`;for(let Ie=he-2-1,ct=Fe-1;Ie>=0;Ie--,ct--)xe+=` +bIndices[${Ie}] = ${Fe>1?`batchIndices[${ct}]`:"batchIndices"};`;return re.forEach(Ie=>{xe+=` +bIndices[${Ie}] = 0;`}),xe+=` +bIndices[${he-2}] = u32(row); + bIndices[${he-1}] = u32(colIn);`,xe};return` + fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${E.type.indices}) -> ${_n(r,ce)} { + var value = ${_n(r,ce)}(0.0); + let col = colIn * ${r}; + if(row < uniforms.dim_a_outer && col < uniforms.dim_inner) + { + ${_e()} + value = ${q.getByIndices("aIndices")}; + } + return value; + } + + fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${E.type.indices}) -> ${_n(r,ce)} { + var value = ${_n(r,ce)}(0.0); + let col = colIn * ${r}; + if(row < uniforms.dim_inner && col < uniforms.dim_b_outer) + { + ${be()} + value = ${H.getByIndices("bIndices")}; + } + return value; + } + + fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${_n(r,ce)}) { + let col = colIn * ${r}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) { + var value = valueIn; + let coords = vec3(batch, row, colIn); + ${i?`value = value + ${p?"bias[colIn]":`${_n(r,ce)}(bias[row])`};`:""} + ${s} + ${v.setByIndices("vec3(coords)","value")} + } + } + `},Ya=(r,i,s,u,c=!1)=>{let p=r[0].dims,d=r[1].dims,b=p.slice(0,-2),T=d.slice(0,-2),E=u?u.slice(0,-2):s.slice(0,-2),q=st.size(E),H=p[p.length-2],v=p[p.length-1],ne=d[d.length-1],re=v%4===0&&ne%4===0,ce=H<=8?[4,1,1]:[4,4,1],_e=[8,8,1],be=[Math.ceil(ne/_e[0]/ce[0]),Math.ceil(H/_e[1]/ce[1]),Math.ceil(q/_e[2]/ce[2])],he=re?4:1,Fe=[...b,H,v/he],xe=Fe.length,Ie=[...T,v,ne/he],ct=Ie.length,et=[q,H,ne/he],vt=[{type:6,data:H},{type:6,data:ne},{type:6,data:v}];Ui(i,vt),vt.push(...Ct(E,Fe,Ie));let Ft=["rank","rank"],Lt=r.length>2;Lt&&(vt.push(...Ct(r[2].dims)),Ft.push("rank")),vt.push(...Ct(et));let pr=ar=>{let nr=E.length,yr=da("batchDims",r[0].dataType,nr,1),qr=Tr(r[0].dataType),Sr=gt("a",r[0].dataType,xe,he),jr=gt("b",r[1].dataType,ct,he),It=Vt("result",r[0].dataType,et.length,he),tr=[Sr,jr];if(Lt){let Hr=c?he:1;tr.push(gt("bias",r[2].dataType,r[2].dims.length,Hr))}let er=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];ki(i,er);let pt=Tr(It.type.tensor),zt=ji(i,It.type.value,pt),ir=Ls(he,Lt,zt,[yr,Sr,jr,It],[b,T,E],c);return` + ${ar.registerUniforms(er).registerInternalVariables(yr).declareVariables(...tr,It)} + ${ir} + ${re?Os(ce,_e,qr,yr):Ds(ce,_e,qr,yr)} + `};return{name:"MatMul",shaderCache:{hint:`${ce};${i.activation};${re};${c}`,inputDependencies:Ft},getRunData:()=>({outputs:[{dims:s,dataType:r[0].dataType}],dispatchGroup:{x:be[0],y:be[1],z:be[2]},programUniforms:vt}),getShaderSource:pr}}}),Kc,op,sp=h(()=>{Xt(),Rn(),or(),Vi(),vo(),Gc(),Rs(),Kc=(r,i,s,u,c=!1,p,d=4,b=4,T=4,E="f32")=>{let q=Ft=>{switch(Ft){case 1:return"resData = x[xIndex];";case 3:return`resData = vec3<${E}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return"resData = x[xIndex / 4];";default:throw new Error(`innerElementSize ${Ft} is not supported.`)}},H=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.`)}},v=r?` + let coord = vec4(batch, xRow, xCol, xCh); + `:` + let coord = vec4(batch, xCh, xRow, xCol); + `,ne=r?` + let coords = vec4( + batch, + row / outWidth, + row % outWidth, + col); + `:` + let coords = vec4( + batch, + row, + col / outWidth, + col % outWidth); + `,re=r?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",ce=r?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",_e=r?"row":"col",be=r?"col":"row",he=` + let inChannels = i32(uniforms.w_shape[2]); + let outWidth = ${r?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; + let outRow = ${_e} / outWidth; + let outCol = ${_e} % outWidth; + + let WRow = ${be} / (i32(uniforms.w_shape[1]) * inChannels); + let WCol = ${be} / 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 = ${be} % inChannels; + var resData = ${_n(d,E)}(0.0); + // The bounds checking is always needed since we use it to pad zero for + // the 'same' padding type. + if (xRow >= 0 && xRow < ${re} && xCol >= 0 && xCol < ${ce}) { + ${v} + let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape)); + ${q(d)} + } + return resData;`,Fe=r?i&&u?` + let col = colIn * ${d}; + ${he}`:` + let col = colIn * ${d}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { + ${he} + } + return ${_n(d,E)}(0.0);`:u&&s?` + let col = colIn * ${d}; + ${he}`:` + let col = colIn * ${d}; + if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { + ${he} + } + return ${_n(d,E)}(0.0);`,xe=`${H(b)}`,Ie=_n(T,E),ct=_n(r?d:b,E),et=_n(r?b:d,E),vt=ji(p,Ie,E);return` + fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${ct} { + ${r?Fe:xe} + } + + fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${et} { + ${r?xe:Fe} + } + + fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${Ie}) { + let col = colIn * ${T}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) + { + var value = valueIn; + let outWidth = ${r?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; + ${ne} + ${Ka(c)} + ${vt} + setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); + } + }`},op=(r,i,s,u,c,p,d,b)=>{let T=i.format==="NHWC",E=T?r[0].dims[3]:r[0].dims[1],q=s[0],H=T?s[2]:s[3],v=T?s[1]:s[2],ne=T?s[3]:s[1],re=T&&(E%4===0||E%3===0)&&ne%4===0,ce=T?ne:H*v,_e=T?H*v:ne,be=[8,8,1],he=u<=8?[4,1,1]:[4,4,1],Fe=[Math.ceil(ce/be[0]/he[0]),Math.ceil(_e/be[1]/he[1]),Math.ceil(q/be[2]/he[2])];Br("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${Fe}`);let xe=re?T&&E%4!==0?3:4:1,Ie=be[1]*he[1],ct=be[0]*he[0],et=Math.max(be[0]*xe,be[1]),vt=u%Ie===0,Ft=c%ct===0,Lt=p%et===0,pr=re?[xe,4,4]:[1,1,1],ar=[{type:6,data:u},{type:6,data:c},{type:6,data:p},{type:6,data:[i.pads[0],i.pads[1]]},{type:6,data:i.strides},{type:6,data:i.dilations}];Ui(i,ar),ar.push(...Ct(r[0].dims,r[1].dims));let nr=["rank","rank"];d&&(ar.push(...Ct(r[2].dims)),nr.push("rank")),ar.push(...Ct(s));let yr=qr=>{let Sr=[{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}];ki(i,Sr);let jr=re?4:1,It=Tr(r[0].dataType),tr=` + fn setOutputAtIndex(flatIndex : i32, value : ${re?`vec4<${It}>`:It}) { + result[flatIndex] = ${re?`vec4<${It}>`:It}(value); + } + fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${re?`vec4<${It}>`:It}) { + let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3)); + setOutputAtIndex(flatIndex ${re?"/ 4":""}, value); + }`,er=gt("x",r[0].dataType,r[0].dims.length,xe===3?1:xe),pt=gt("w",r[1].dataType,r[1].dims.length,jr),zt=[er,pt],ir=Vt("result",r[0].dataType,s.length,jr);if(d){let Hr=gt("bias",r[2].dataType,r[2].dims.length,jr);zt.push(Hr),tr+=` + fn getBiasByOutputCoords(coords : vec4) -> ${re?`vec4<${It}>`:It} { + return bias[coords.${T?"w":"y"}${re?"/ 4":""}]; + }`}return` + ${Qa("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 }; + ${qr.registerUniforms(Sr).declareVariables(...zt,ir)} + ${tr} + ${Kc(T,vt,Ft,Lt,d,i,pr[0],pr[1],pr[2],It)} + ${re?Os(he,be,It,void 0,!T,et):Ds(he,be,It,void 0,!T,et,!1,void 0,b)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${i.cacheKey};${xe};${re};${vt};${Ft};${Lt};${Ie};${ct};${et}`,inputDependencies:nr},getRunData:()=>({outputs:[{dims:s,dataType:r[0].dataType}],dispatchGroup:{x:Fe[0],y:Fe[1],z:Fe[2]},programUniforms:ar}),getShaderSource:yr}}}),Qc,Za,Si,Xc,Ja,Yc,Zc,Jc,el=h(()=>{Xt(),Rn(),Yt(),or(),Vi(),vo(),Qc=r=>{let i=1;for(let s=0;stypeof r=="number"?[r,r,r]:r,Si=(r,i)=>i<=1?r:r+(r-1)*(i-1),Xc=(r,i,s,u=1)=>{let c=Si(i,u);return Math.floor((r[0]*(s-1)-s+c)/2)},Ja=(r,i,s,u,c)=>{c==null&&(c=Xc(r,i[0],u[0]));let p=[0,0,0,s];for(let d=0;d<3;d++)r[d]+2*c>=i[d]&&(p[d]=Math.trunc((r[d]-i[d]+2*c)/u[d]+1));return p},Yc=(r,i,s,u,c,p,d,b,T,E)=>{let q,H,v,ne;if(r==="VALID"&&(r=0),typeof r=="number"){q={top:r,bottom:r,left:r,right:r,front:r,back:r};let re=Ja([i,s,u,1],[b,T,E],1,[c,p,d],r);H=re[0],v=re[1],ne=re[2]}else if(Array.isArray(r)){if(!r.every((ce,_e,be)=>ce===be[0]))throw Error(`Unsupported padding parameter: ${r}`);q={top:r[0],bottom:r[1],left:r[2],right:r[3],front:r[4],back:r[5]};let re=Ja([i,s,u,1],[b,T,E],1,[c,p,d],r[0]);H=re[0],v=re[1],ne=re[2]}else if(r==="SAME_UPPER"){H=Math.ceil(i/c),v=Math.ceil(s/p),ne=Math.ceil(u/d);let re=(H-1)*c+b-i,ce=(v-1)*p+T-s,_e=(ne-1)*d+E-u,be=Math.floor(re/2),he=re-be,Fe=Math.floor(ce/2),xe=ce-Fe,Ie=Math.floor(_e/2),ct=_e-Ie;q={top:Fe,bottom:xe,left:Ie,right:ct,front:be,back:he}}else throw Error(`Unknown padding parameter: ${r}`);return{padInfo:q,outDepth:H,outHeight:v,outWidth:ne}},Zc=(r,i,s,u,c,p=!1,d="channelsLast")=>{let b,T,E,q,H;if(d==="channelsLast")[b,T,E,q,H]=r;else if(d==="channelsFirst")[b,H,T,E,q]=r;else throw new Error(`Unknown dataFormat ${d}`);let[v,,ne,re,ce]=i,[_e,be,he]=Za(s),[Fe,xe,Ie]=Za(u),ct=Si(ne,Fe),et=Si(re,xe),vt=Si(ce,Ie),{padInfo:Ft,outDepth:Lt,outHeight:pr,outWidth:ar}=Yc(c,T,E,q,_e,be,he,ct,et,vt),nr=p?v*H:v,yr=[0,0,0,0,0];return d==="channelsFirst"?yr=[b,nr,Lt,pr,ar]:d==="channelsLast"&&(yr=[b,Lt,pr,ar,nr]),{batchSize:b,dataFormat:d,inDepth:T,inHeight:E,inWidth:q,inChannels:H,outDepth:Lt,outHeight:pr,outWidth:ar,outChannels:nr,padInfo:Ft,strideDepth:_e,strideHeight:be,strideWidth:he,filterDepth:ne,filterHeight:re,filterWidth:ce,effectiveFilterDepth:ct,effectiveFilterHeight:et,effectiveFilterWidth:vt,dilationDepth:Fe,dilationHeight:xe,dilationWidth:Ie,inShape:r,outShape:yr,filterShape:i}},Jc=(r,i,s,u,c,p)=>{let d=p==="channelsLast";d?r[0].dims[3]:r[0].dims[1];let b=[64,1,1],T={x:s.map((_e,be)=>be)},E=[Math.ceil(Qc(T.x.map(_e=>s[_e]))/b[0]),1,1];Br("verbose",()=>`[conv3d_naive_webgpu] dispatch = ${E}`);let q=1,H=st.size(s),v=[{type:12,data:H},{type:12,data:u},{type:12,data:c},{type:12,data:i.strides},{type:12,data:i.dilations}];Ui(i,v),v.push(...Ct(r[0].dims,r[1].dims));let ne=["rank","rank"],re=r.length===3;re&&(v.push(...Ct(r[2].dims)),ne.push("rank")),v.push(...Ct(s));let ce=_e=>{let be=[{name:"output_size",type:"u32"},{name:"filter_dims",type:"u32",length:u.length},{name:"pads",type:"u32",length:c.length},{name:"strides",type:"u32",length:i.strides.length},{name:"dilations",type:"u32",length:i.dilations.length}];ki(i,be);let he=1,Fe=Tr(r[0].dataType),xe=gt("x",r[0].dataType,r[0].dims.length,q),Ie=gt("W",r[1].dataType,r[1].dims.length,he),ct=[xe,Ie],et=Vt("result",r[0].dataType,s.length,he),vt="";if(re){let pr=gt("bias",r[2].dataType,r[2].dims.length,he);ct.push(pr),vt+=` + fn getBiasByOutputCoords(coords : array) -> ${Fe} { + return bias[${d?Dt("coords",4,5):Dt("coords",1,5)}]; + }`}let Ft=_n(q,Fe),Lt=ji(i,Ft,Fe);return` + ${vt} + fn getX(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { + let aIndices = array(d0, d1, d2, d3, d4); + return ${xe.getByIndices("aIndices")}; + } + fn getW(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { + let aIndices = array(d0, d1, d2, d3, d4); + return ${Ie.getByIndices("aIndices")}; + } + ${_e.registerUniforms(be).declareVariables(...ct,et)} + ${_e.mainStart()} + ${_e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let coords = ${et.offsetToIndices("global_idx")}; + let batch = ${Dt("coords",0,xe.rank)}; + let d2 = ${d?Dt("coords",xe.rank-1,xe.rank):Dt("coords",1,xe.rank)}; + let xFRCCorner = vec3(${d?Dt("coords",1,xe.rank):Dt("coords",2,xe.rank)}, + ${d?Dt("coords",2,xe.rank):Dt("coords",3,xe.rank)}, + ${d?Dt("coords",3,xe.rank):Dt("coords",4,xe.rank)}) * uniforms.strides - uniforms.pads; + let xFCorner = xFRCCorner.x; + let xRCorner = xFRCCorner.y; + let xCCorner = xFRCCorner.z; + let xShapeY = ${d?Dt("uniforms.x_shape",1,xe.rank):Dt("uniforms.x_shape",2,xe.rank)}; + let xShapeZ = ${d?Dt("uniforms.x_shape",2,xe.rank):Dt("uniforms.x_shape",3,xe.rank)}; + let xShapeW = ${d?Dt("uniforms.x_shape",3,xe.rank):Dt("uniforms.x_shape",4,xe.rank)}; + let xShapeU = ${d?Dt("uniforms.x_shape",4,xe.rank):Dt("uniforms.x_shape",1,xe.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); + } + } + } + } + ${re?"value = value + getBiasByOutputCoords(coords)":""}; + ${Lt} + result[global_idx] = f32(value); + }`};return{name:"Conv3DNaive",shaderCache:{hint:`${i.cacheKey};${d};${q};${re}`,inputDependencies:ne},getRunData:()=>({outputs:[{dims:s,dataType:r[0].dataType}],dispatchGroup:{x:E[0],y:E[1],z:E[2]},programUniforms:v}),getShaderSource:ce}}}),ed,td,ap=h(()=>{Xt(),Yt(),or(),sd(),Vi(),ed=(r,i,s)=>{let u=r.length>2,c=u?"value += b[output_channel];":"",p=r[0].dims,d=r[1].dims,b=d[0]/i.group,T=i.format==="NHWC",E=Bs(p,d,i.dilations,i.pads,i.strides,T),q=st.size(E),H=[{type:12,data:q},{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:b}];Ui(i,H),H.push(...Ct(p,d));let v=["rank","rank"];u&&(H.push(...Ct(r[2].dims)),v.push("rank")),H.push(...Ct(E));let ne=re=>{let ce=Vt("output",r[0].dataType,E.length),_e=Tr(ce.type.tensor),be=ji(i,ce.type.value,_e),he=gt("x",r[0].dataType,p.length),Fe=gt("w",r[1].dataType,d.length),xe=[he,Fe];u&&xe.push(gt("b",r[2].dataType,r[2].dims.length));let Ie=[{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 ki(i,Ie),` + ${re.registerUniforms(Ie).declareVariables(...xe,ce)} + + ${re.mainStart()} + ${re.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let outputIndices = ${ce.offsetToIndices("global_idx")}; + let batch: u32 = outputIndices[0]; + let output_channel: u32 = outputIndices[${T?3:1}]; + let xRCCorner: vec2 = vec2(outputIndices[${T?1:2}], outputIndices[${T?2:3}]) * uniforms.strides - uniforms.pads; + let group_id: u32 = output_channel / uniforms.output_channels_per_group; + + var value: ${ce.type.value} = ${ce.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[${T?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[${T?2:3}]) { + continue; + } + + let xVal = ${T?he.get("batch","xHeight","xWidth","input_channel"):he.get("batch","input_channel","xHeight","xWidth")}; + let wVal = ${Fe.get("output_channel","wInChannel","wHeight","wWidth")}; + value += xVal*wVal; + } + } + } + ${c} + ${be} + ${ce.setByOffset("global_idx","value")} + }`};return{name:"GroupedConv",shaderCache:{hint:i.cacheKey,inputDependencies:v},getRunData:()=>({outputs:[{dims:s?s(E):E,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(q/64)},programUniforms:H}),getShaderSource:ne}},td=(r,i,s)=>{let u=r.length>2,c=wr(s[3]),p=wr(s[2]),d=st.size(s)/c/p,b=[r[0].dims[0],r[0].dims[1],r[0].dims[2],r[0].dims[3]/c],T=[r[1].dims[0],r[1].dims[1],r[1].dims[2],r[1].dims[3]/c],E=[s[0],s[1],s[2],s[3]/c],q=[{type:12,data:d},{type:6,data:[i.strides[0],i.strides[1]]},{type:6,data:[i.pads[0],i.pads[1]]}];Ui(i,q),q.push(...Ct(b,T,E));let H=(p-1)*i.strides[1]+T[1],v=ne=>{let re=Vt("output",r[0].dataType,E.length,c),ce=Tr(re.type.tensor),_e=ji(i,re.type.value,ce),be=gt("x",r[0].dataType,b.length,c),he=gt("w",r[1].dataType,T.length,c),Fe=[be,he];u&&Fe.push(gt("b",r[2].dataType,r[2].dims,c));let xe=u?"value += b[output_channel];":"",Ie=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return ki(i,Ie),` + ${ne.registerUniforms(Ie).declareVariables(...Fe,re)} + ${ne.mainStart()} + ${ne.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] / ${p}u; + let col = (index1 % width1) * ${p}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<${be.type.value}, ${H}>; + var values: array<${re.type.value}, ${p}>; + 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 < ${T[0]}; w_height++) { + let x_height = x_corner.x + i32(w_height); + if (x_height >= 0 && u32(x_height) < uniforms.x_shape[1]) { + for (var i = 0; i < ${H}; i++) { + let x_width = x_corner.y + i; + if (x_width >= 0 && u32(x_width) < uniforms.x_shape[2]) { + x_vals[i] = ${be.get("batch","u32(x_height)","u32(x_width)","input_channel")}; + } else { + x_vals[i] = ${be.type.value}(0); + } + } + for (var w_width: u32 = 0u; w_width < ${T[1]}; w_width++) { + let w_val = ${he.get("w_height","w_width","0","output_channel")}; + for (var i = 0u; i < ${p}u; i++) { + values[i] = fma(x_vals[i * u32(uniforms.strides[1]) + w_width], w_val, values[i]); + } + } + } + } + + for (var i = 0u; i < ${p}u; i++) { + var value = values[i]; + ${xe} + ${_e} + ${re.set("batch","row","col + i","output_channel","value")}; + } + }`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${i.cacheKey};${c};${p};${H};${T[0]};${T[1]}`,inputDependencies:u?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:s,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:q}),getShaderSource:v}}}),tl,rd,nd,rl=h(()=>{Xt(),Yt(),Rs(),or(),Vi(),tl=(r,i,s,u,c=!1)=>{let p=r[0].dims,d=r[1].dims,b=p[p.length-2],T=d[d.length-1],E=p[p.length-1],q=wr(T),H=wr(E),v=wr(b),ne=st.size(s)/q/v,re=r.length>2,ce=u?u.slice(0,-2):s.slice(0,-2),_e=[st.size(ce),b,T],be=[{type:12,data:ne},{type:12,data:b},{type:12,data:T},{type:12,data:E}];Ui(i,be),be.push(...Ct(ce,p,d)),re&&be.push(...Ct(r[2].dims)),be.push(...Ct(_e));let he=Fe=>{let xe=da("batch_dims",r[0].dataType,ce.length),Ie=gt("a",r[0].dataType,p.length,H),ct=gt("b",r[1].dataType,d.length,q),et=Vt("output",r[0].dataType,_e.length,q),vt=Tr(et.type.tensor),Ft=ji(i,et.type.value,vt),Lt=[Ie,ct],pr="";if(re){let tr=c?q:1;Lt.push(gt("bias",r[2].dataType,r[2].dims.length,tr)),pr=`${c?`value += bias[col / ${tr}];`:`value += ${et.type.value}(bias[row + i]);`}`}let ar=p.slice(0,-2),nr=d.slice(0,-2),yr=go(ar,ce),qr=go(nr,ce),Sr=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];ki(i,Sr);let jr=(tr,er)=>{let pt=tr.rank,zt=tr.name;if(pt===2)return`var ${zt}_indices = ${tr.type.indices}(0u, 0u);`;let ir=xe.rank,Hr=`var ${zt}_indices: ${tr.type.indices};`;for(let un=pt-2-1,xn=ir-1;un>=0;un--,xn--)Hr+=` +${zt}_indices[${un}] = ${ir>1?`batch_indices[${xn}]`:"batch_indices"};`;return er.forEach(un=>{Hr+=` +${zt}_indices[${un}] = 0;`}),Hr+=`${zt}_indices[${pt-2}] = 0u; + ${zt}_indices[${pt-1}] = 0u;`,Hr},It=()=>{let tr=`var a_data: ${Ie.type.value};`;for(let er=0;er; + for (var k: u32 = 0u; k < uniforms.K; k = k + ${H}) { + ${It()} + } + for (var i = 0u; i < ${v}u; i++) { + var value = values[i]; + ${pr} + ${Ft} + let cur_indices = ${et.type.indices}(batch, row + i, col); + let offset = ${et.indicesToOffset("cur_indices")}; + ${et.setByOffset(`offset / ${q}`,"value")}; + } + } + `};return{name:"MatMulNaive",shaderCache:{hint:`${i.activation};${q};${H};${v};${c}`,inputDependencies:re?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:s,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(ne/64)},programUniforms:be}),getShaderSource:he}},rd=r=>{if(!r||r.length!==2)throw new Error("MatMul requires 2 inputs.");if(r[0].dims[r[0].dims.length-1]!==r[1].dims[r[1].dims.length-2])throw new Error("shared dimension does not match.")},nd=r=>{rd(r.inputs);let i=pn.calcShape(r.inputs[0].dims,r.inputs[1].dims,!0);if(!i)throw new Error("Can't use matmul on the given tensors");let s=i[i.length-1],u=r.inputs[0].dims[r.inputs[0].dims.length-1];s<8&&u<8?r.compute(tl(r.inputs,{activation:""},i)):r.compute(Ya(r.inputs,{activation:""},i))}}),Bs,Ns,nl,js,il,ol,id,od,qo,sd=h(()=>{Yt(),sp(),el(),Rs(),ap(),Vi(),rl(),_o(),Bs=(r,i,s,u,c,p)=>{let d=r[0],b=r.slice(p?1:2,p?3:4),T=b.length,E=i[0],q=i.slice(2).map((v,ne)=>v+(v-1)*(s[ne]-1)),H=b.map((v,ne)=>v+u[ne]+u[ne+T]).map((v,ne)=>Math.floor((v-q[ne]+c[ne])/c[ne]));return H.splice(0,0,d),H.splice(p?3:1,0,E),H},Ns=[2,3,1,0],nl=(r,i)=>{if(!r||r.length!==2&&r.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(r[0].dims.length>5)throw new Error("greater than 5D is not supported");if(r[0].dims.length!==r[1].dims.length)throw new Error("filter does not have same dimension as input");let s=r[0].dims[i.format==="NHWC"?r[0].dims.length-1:1],u=r[1].dims[1]*i.group;if(s!==u)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");if(r.length===3&&(r[2].dims.length!==1||r[1].dims[0]!==r[2].dims[0]))throw new Error("invalid bias");let c=r[0].dims.length-2;if(i.dilations.length!==c)throw new Error(`dilations should be ${c}D`);if(i.strides.length!==c)throw new Error(`strides should be ${c}D`);if(i.pads.length!==c*2)throw new Error(`pads should be ${c*2}D`);if(i.kernelShape.length!==0&&i.kernelShape.length!==r[1].dims.length-2)throw new Error("invalid kernel shape")},js=(r,i)=>{let s=r.kernelShape.slice();for(let p=2;p{let i=Ha(r),s=r.format,u=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][r.auto_pad],c=r.dilations,p=r.group,d=r.kernel_shape,b=r.pads,T=r.strides,E=r.w_is_const();return{autoPad:u,format:s,dilations:c,group:p,kernelShape:d,pads:b,strides:T,wIsConst:E,...i,cacheKey:`${r.format};${i.activation};`}},ol=(r,i,s)=>{let u=js(s,i),c=s.format==="NHWC";if(s.group!==1){if(!r.adapterInfo.isArchitecture("ampere")&&c&&i[1].dims[0]===s.group&&i[1].dims[1]===1&&s.dilations[0]===1&&s.dilations[1]===1){let ct=Bs(i[0].dims,i[1].dims,s.dilations,u.pads,s.strides,c),et=r.kernelCustomData.wT??r.compute(fi(i[1],Ns),{inputs:[1],outputs:[s.wIsConst?-2:-1]})[0];s.wIsConst&&!r.kernelCustomData.wT&&(r.kernelCustomData.wT=et);let vt=[i[0],et];i.length===3&&vt.push(i[2]),r.compute(td(vt,u,ct),{inputs:vt})}else r.compute(ed(i,u));return}let p=i.length===3,d=i[0].dims[c?1:2],b=i[0].dims[c?2:3],T=i[0].dims[c?3:1],E=i[1].dims[2],q=i[1].dims[3],H=Bs(i[0].dims,i[1].dims,s.dilations,u.pads,s.strides,c),v=H[c?1:2],ne=H[c?2:3],re=H[c?3:1],ce=c&&E===d&&q===b&&s.pads[0]===0&&s.pads[1]===0;if(ce||E===1&&q===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 ct=H[0],et,vt,Ft,Lt=[];if(c){let nr=r.kernelCustomData.wT??r.compute(fi(i[1],Ns),{inputs:[1],outputs:[s.wIsConst?-2:-1]})[0];if(s.wIsConst&&!r.kernelCustomData.wT&&(r.kernelCustomData.wT=nr),ce){let yr=d*b*T;et=i[0].reshape([1,ct,yr]),vt=nr.reshape([1,yr,re]),Ft=[1,ct,re]}else et=i[0].reshape([ct,d*b,T]),vt=nr.reshape([1,T,re]),Ft=[ct,v*ne,re];Lt.push(et),Lt.push(vt)}else et=i[0].reshape([ct,T,d*b]),vt=i[1].reshape([1,re,T]),Ft=[ct,re,v*ne],Lt.push(vt),Lt.push(et);p&&Lt.push(i[2]);let pr=Ft[2],ar=Lt[0].dims[Lt[0].dims.length-1];pr<8&&ar<8?r.compute(tl(Lt,u,H,Ft,c),{inputs:Lt}):r.compute(Ya(Lt,u,H,Ft,c),{inputs:Lt});return}let _e=!0,be=r.kernelCustomData.wT??r.compute(fi(i[1],Ns),{inputs:[1],outputs:[s.wIsConst?-2:-1]})[0];s.wIsConst&&!r.kernelCustomData.wT&&(r.kernelCustomData.wT=be);let he=[i[0],be];p&&he.push(i[2]);let Fe=c?v*ne:re,xe=c?re:v*ne,Ie=E*q*T;r.compute(op(he,u,H,Fe,xe,Ie,p,_e),{inputs:he})},id=(r,i)=>{let s=i.format==="NHWC",u=[r.inputs[0].reshape(s?[r.inputs[0].dims[0],1,r.inputs[0].dims[1],r.inputs[0].dims[2]]:[r.inputs[0].dims[0],r.inputs[0].dims[1],1,r.inputs[0].dims[2]]),r.inputs[1].reshape([r.inputs[1].dims[0],r.inputs[1].dims[1],1,r.inputs[1].dims[2]])];r.inputs.length===3&&u.push(r.inputs[2]);let c=[0,i.pads[0],0,i.pads[1]],p=[1].concat(i.strides),d=[1].concat(i.dilations),b=[1].concat(i.kernelShape),T=js({...i,pads:c,strides:p,dilations:d,kernelShape:b},u);r.compute(ed(u,T,E=>s?[E[0],E[2],E[3]]:[E[0],E[1],E[3]]))},od=(r,i,s)=>{let u=s.format==="NHWC"?"channelsLast":"channelsFirst",c=js(s,i),p=s.autoPad==="NOTSET"?s.pads:s.autoPad,d=Zc(i[0].dims,i[1].dims,s.strides,s.dilations,p,!1,u);r.compute(Jc(i,c,d.outShape,[d.filterDepth,d.filterHeight,d.filterWidth],[d.padInfo.front,d.padInfo.top,d.padInfo.left],u))},qo=(r,i)=>{nl(r.inputs,i),r.inputs[0].dims.length===3?id(r,i):r.inputs[0].dims.length===5?od(r,r.inputs,i):ol(r,r.inputs,i)}}),ad,ld,lp=h(()=>{Xt(),Rn(),or(),Vi(),vo(),Gc(),Rs(),ad=(r,i=!1,s,u,c=4)=>{let p=_e=>{switch(_e){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 ${u}(v0, v1, v2, v3); + `;default:throw new Error(`innerElementSize ${_e} is not supported.`)}},d=r?` + let coord = vec4(batch, iXR, iXC, xCh); + `:` + let coord = vec4(batch, xCh, iXR, iXC); + `,b=r?` + let coords = vec4( + batch, + row / outWidth, + row % outWidth, + col); + `:` + let coords = vec4( + batch, + row, + col / outWidth, + col % outWidth); + `,T=r?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",E=r?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",q=r?"row":"col",H=r?"col":"row",v=` + let inChannels = ${r?"i32(uniforms.x_shape[3])":"i32(uniforms.x_shape[1])"}; + let outWidth = ${r?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; + let outRow = ${q} / outWidth; + let outCol = ${q} % outWidth; + + let WRow = ${H} / (uniforms.filter_dims[1] * inChannels); + let WCol = ${H} / 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(${T}) || fract(xR) > 0.0) { + return ${u}(0.0); + } + if (xC < 0.0 || xC >= f32(${E}) || fract(xC) > 0.0) { + return ${u}(0.0); + } + let iXR = i32(xR); + let iXC = i32(xC); + let xCh = ${H} % inChannels; + ${d} + return x[getIndexFromCoords4D(coord, vec4(uniforms.x_shape))/${c}];`,ne=r?` + let col = colIn * ${c}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { + ${v} + } + return ${u}(0.0);`:` + let col = colIn * ${c}; + if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { + ${v} + } + return ${u}(0.0);`,re=` + let col = colIn * ${c}; + let inChannels = ${r?"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 (${r?"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); + ${p(c)} + } + return ${u}(0.0); + `,ce=ji(s,u);return` + fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${u} { + ${r?ne:re} + } + + fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${u} { + ${r?re:ne} + } + + fn mm_write(batch: i32, row : i32, colIn : i32, valueInput : ${u}) { + let col = colIn * ${c}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) { + var value = valueInput; + let outWidth = ${r?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; + ${b} + ${Ka(i)} + ${ce} + result[getIndexFromCoords4D(coords, vec4(uniforms.result_shape))/${c}] = value; + } + }`},ld=(r,i,s,u,c,p,d,b)=>{let T=i.format==="NHWC",E=T?r[0].dims[3]:r[0].dims[1],q=s[0],H=T?s[2]:s[3],v=T?s[1]:s[2],ne=T?s[3]:s[1],re=T&&E%4===0&&E%3&&ne%4===0,ce=T?ne:H*v,_e=T?H*v:ne,be=[8,8,1],he=u<=8?[4,1,1]:[4,4,1],Fe=[Math.ceil(ce/be[0]/he[0]),Math.ceil(_e/be[1]/he[1]),Math.ceil(q/be[2]/he[2])];Br("verbose",()=>`[conv_backprop_mm_webgpu] dispatch = ${Fe}`);let xe=re?4:1,Ie=Math.max(be[0]*xe,be[1]),ct=re?4:1,et=[i.kernelShape[T?1:2],i.kernelShape[T?2:3]],vt=[et[0]+(i.dilations[0]<=1?0:(et[0]-1)*(i.dilations[0]-1)),et[1]+(i.dilations[1]<=1?0:(et[1]-1)*(i.dilations[1]-1))],Ft=[vt[0]-1-Math.floor((i.pads[0]+i.pads[2])/2),vt[1]-1-Math.floor((i.pads[1]+i.pads[3])/2)],Lt=[{type:6,data:u},{type:6,data:c},{type:6,data:p},{type:6,data:i.strides},{type:6,data:i.dilations},{type:6,data:et},{type:6,data:Ft}];Ui(i,Lt),Lt.push(...Ct(r[0].dims,r[1].dims));let pr=["rank","rank"];d&&(Lt.push(...Ct(r[2].dims)),pr.push("rank")),Lt.push(...Ct(s));let ar=nr=>{let yr=gt("x",r[0].dataType,r[0].dims.length,ct),qr=gt("w",r[1].dataType,r[1].dims.length,1),Sr=Vt("result",r[0].dataType,s.length,ct),jr=[yr,qr],It="";if(d){let pt=gt("bias",r[2].dataType,r[2].dims.length,ct);jr.push(pt),It+=` + fn getBiasByOutputCoords(coords : vec4) -> ${pt.type.value} { + return bias[coords.${T?"w":"y"}${re?"/ 4":""}]; + }`}let tr=[{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:et.length},{name:"pads",type:"i32",length:Ft.length}];ki(i,tr);let er=Tr(r[0].dataType,1);if(er!=="f16"&&er!=="f32")throw new Error(`elemType ${er} is not supported.`);return` + ${Qa("uniforms.result_strides")} + ${nr.registerUniforms(tr).declareVariables(...jr,Sr)}; + ${It} + ${ad(T,d,i,yr.type.value,xe)} + ${re?Os(he,be,er,void 0,!T,Ie):Ds(he,be,er,void 0,!T,Ie,!1,void 0,b)}`};return{name:"Conv2DTransposeMatMul",shaderCache:{hint:`${i.cacheKey};${he};${be};${re}`,inputDependencies:pr},getRunData:()=>({outputs:[{dims:s,dataType:r[0].dataType}],dispatchGroup:{x:Fe[0],y:Fe[1],z:Fe[2]},programUniforms:Lt}),getShaderSource:ar}}}),sl,Ho,fm=h(()=>{Xt(),Rn(),Yt(),or(),sl=(r,i,s,u,c,p=!1,d,b,T=!1)=>{let E=T?1:2,q=T?2:3,H=T?3:1,v=p?2:1,ne=` + fn setOutputAtIndex(flatIndex : u32, value : ${p?`vec4<${d}>`:d}) { + result[flatIndex] = ${p?`vec4<${d}>`:d}(value); + }`;u&&(ne+=` + fn getBiasByOutputCoords(coords : vec4) -> ${p?`vec4<${d}>`:d} { + return bias[coords.${T?"w":"y"}${p?"/ 4":""}]; + }`);let re=p?4:1,ce=gt("W",i[1].dataType,i[1].dims.length,re),_e=gt("Dy",i[0].dataType,i[0].dims.length,re),be=[_e,ce];u&&be.push(gt("bias",i[2].dataType,[s[H]].length,re));let he=Vt("result",i[0].dataType,s.length,re),Fe=`{ + let batch: u32 = ${c?"global_id.z":"workgroup_id.z"} / uniforms.result_shape[1]; + let r = ${c?"global_id.z":"workgroup_id.z"} % uniforms.result_shape[1]; + let c = ${c?"global_id.y":"workgroup_id.y"} * ${v}; + let d1: u32 = ${c?"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, ${v}>; + for (var i = 0; i < ${v}; 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 = ${ce.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; + let wValue1 = ${ce.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; + let wValue2 = ${ce.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; + let wValue3 = ${ce.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; + + var xValue = ${_e.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 = ${_e.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[${H}]; + for (var d2: u32 = 0; d2 < d2Length; d2 = d2 + 4) { + let wValue0 = ${ce.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; + let wValue1 = ${ce.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; + let wValue2 = ${ce.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; + let wValue3 = ${ce.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; + + var xValue = ${_e.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 = ${ce.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; + let wValue1 = ${ce.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; + let wValue2 = ${ce.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; + let wValue3 = ${ce.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; + + var xValue = ${_e.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 < ${v}; i = i + 1) { + let value = dotProd[i] + ${u?"bias[c+i]":`vec4<${d}>(0.0)`}; + ${he.set("batch","r","c + i","d1","value")}; + } + }`,xe=` + let outputIndices = ${he.offsetToIndices("global_idx")}; + let batch = ${he.indicesGet("outputIndices",0)}; + let d1 = ${he.indicesGet("outputIndices",H)}; + let r = ${he.indicesGet("outputIndices",E)}; + let c = ${he.indicesGet("outputIndices",q)}; + 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[${E}]) || 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[${q}]) || + 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 = ${T?_e.get("batch","idyR","idyC","inputChannel"):_e.get("batch","inputChannel","idyR","idyC")}; + let wValue = ${ce.get("inputChannel","wOutChannel","u32(wRPerm)","u32(wCPerm)")}; + dotProd = dotProd + xValue * wValue; + inputChannel = inputChannel + 1; + } + } + } + let value = dotProd + ${u?"bias[d1]":`${d}(0.0)`}; + ${he.setByOffset("global_idx","value")}; + `;return` + ${r.registerUniforms(b).declareVariables(...be,he)} + ${ne} + + ${r.mainStart()} + ${r.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}; + ${p?Fe:xe}}`},Ho=(r,i,s)=>{let u=r.length>2,c=i.outputShape,p=st.size(c),d=[Math.ceil(p/64),1,1];Br("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${d}`);let b=i.format==="NHWC",T=["rank","rank"],E=[i.strides[0],i.strides[1]],q=[i.kernelShape[b?1:2],i.kernelShape[b?2:3]],H=[i.dilations[0],i.dilations[1]],v=[q[0]+(i.dilations[0]<=1?0:(i.kernelShape[b?1:2]-1)*(i.dilations[0]-1)),q[1]+(i.dilations[1]<=1?0:(i.kernelShape[b?2:3]-1)*(i.dilations[1]-1))],ne=[v[0]-1-Math.floor((i.pads[0]+i.pads[2])/2),v[1]-1-Math.floor(i.pads[1]+i.pads[3])/2],re=!1,ce=i.group,_e=r[1].dims,be=_e[0]/ce,he=_e[1],Fe=[{type:12,data:p},{type:12,data:E},{type:12,data:q},{type:12,data:H},{type:12,data:v},{type:6,data:ne},{type:12,data:be},{type:12,data:he},...Ct(r[0].dims,r[1].dims)];u&&(Fe.push(...Ct(r[2].dims)),T.push("rank")),Fe.push(...Ct(c));let xe=d[1]===1&&d[2]===1,Ie=ct=>{let et=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:E.length},{name:"filter_dims",type:"u32",length:q.length},{name:"dilations",type:"u32",length:q.length},{name:"effective_filter_dims",type:"u32",length:v.length},{name:"pads",type:"i32",length:ne.length},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],vt=Tr(r[0].dataType);return`${sl(ct,r,c,u,xe,re,vt,et,b)}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${i.cacheKey};`,inputDependencies:T},getRunData:()=>({dispatchGroup:{x:d[0],y:d[1],z:d[2]},outputs:[{dims:s?s(c):c,dataType:r[0].dataType}],programUniforms:Fe}),getShaderSource:Ie}}}),ud,cd,al,ll,dd,ul,fd,pd,cl,up,pm=h(()=>{lp(),fm(),Vi(),_o(),ud=(r,i,s,u,c,p)=>(r-1)*i+s+(u-1)*c+1-p,cd=(r,i,s,u,c)=>{let p=Math.floor(r/2);i==="SAME_UPPER"?(s[u]=p,s[c]=r-p):i==="SAME_LOWER"&&(s[u]=r-p,s[c]=p)},al=(r,i,s,u,c,p,d,b,T,E)=>{let q=r.length-2,H=E.length===0;if(T.length===0)for(let re=0;re{let s=r.kernelShape.slice();if(r.kernelShape.length===0||r.kernelShape.reduce((H,v)=>H*v,1)===0){s.length=0;for(let H=2;HH+v,0)===0){let H=i[0].dims.length-2;T=new Array(H).fill(1)}let E=r.strides.slice();if(E.reduce((H,v)=>H+v,0)===0){let H=i[0].dims.length-2;E=new Array(H).fill(1)}al(b,s,T,r.autoPad,r.group,c,E,u,d,p);let q=Object.assign({},r);return Object.assign(q,{kernelShape:s,pads:c,outputPadding:d,outputShape:p,dilations:T,strides:E}),q},dd=r=>{let i=Ha(r),s=r.format,u=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof r.autoPad>"u"?0:r.autoPad],c=r.dilations,p=r.group,d=r.kernelShape,b=r.pads,T=r.strides,E=r.wIsConst(),q=r.outputPadding,H=r.outputShape;return{autoPad:u,format:s,dilations:c,group:p,kernelShape:d,outputPadding:q,outputShape:H,pads:b,strides:T,wIsConst:E,...i,cacheKey:`${r.format};${i.activation};`}},ul=(r,i)=>{if(!r||r.length!==2&&r.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(r[0].dims.length!==4&&r[0].dims.length!==3)throw new Error("currently only support 2-dimensional conv");if(r[0].dims.length!==r[1].dims.length)throw new Error("filter does not have same dimension as input");let s=r[0].dims[i.format==="NHWC"?r[0].dims.length-1:1],u=r[1].dims[0];if(s!==u)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");let c=r[1].dims[1]*i.group;if(r.length===3&&(r[2].dims.length!==1||r[2].dims[0]!==c))throw new Error("invalid bias");let p=r[0].dims.length-2;if(i.dilations.reduce((d,b)=>d+b,0)>0&&i.dilations.length!==p)throw new Error(`dilations should be ${p}D`);if(i.strides.reduce((d,b)=>d+b,0)>0&&i.strides.length!==p)throw new Error(`strides should be ${p}D`);if(i.pads.reduce((d,b)=>d+b,0)>0&&i.pads.length!==p*2)throw new Error(`pads should be ${p*2}D`);if(i.outputPadding.length!==p&&i.outputPadding.length!==0)throw new Error(`output_padding should be ${p}D`);if(i.kernelShape.reduce((d,b)=>d+b,0)>0&&i.kernelShape.length!==0&&i.kernelShape.length!==r[1].dims.length-2)throw new Error("invalid kernel shape");if(i.outputShape.length!==0&&i.outputShape.length!==r[0].dims.length-2)throw new Error("invalid output shape")},fd=[2,3,1,0],pd=(r,i,s)=>{let u=ll(s,i),c=s.format==="NHWC",p=u.outputShape,d=p[c?3:1],b=i[0].dims[c?3:1];if(u.group!==1||d===1&&b===1){r.compute(Ho(i,u));return}let T=p[c?1:2],E=p[c?2:3],q=i[1].dims[2],H=i[1].dims[3],v=c?T*E:d,ne=c?d:T*E,re=q*H*b,ce=!0,_e=r.kernelCustomData.wT??r.compute(fi(i[1],fd),{inputs:[1],outputs:[s.wIsConst?-2:-1]})[0];s.wIsConst&&!r.kernelCustomData.wT&&(r.kernelCustomData.wT=_e);let be=[i[0],_e],he=i.length===3;he&&(!c&&i[2].dims.length===1?be.push(i[2].reshape([i[2].dims[0],1,1])):be.push(i[2])),r.compute(ld(be,u,p,v,ne,re,he,ce),{inputs:be})},cl=(r,i)=>{let s=i.format==="NHWC",u=[r.inputs[0].reshape(s?[r.inputs[0].dims[0],1,r.inputs[0].dims[1],r.inputs[0].dims[2]]:[r.inputs[0].dims[0],r.inputs[0].dims[1],1,r.inputs[0].dims[2]]),r.inputs[1].reshape([r.inputs[1].dims[0],r.inputs[1].dims[1],1,r.inputs[1].dims[2]])];r.inputs.length===3&&u.push(r.inputs[2]);let c=i.kernelShape;(c.length===0||c[0]===0)&&(c=[r.inputs[1].dims[2]]);let p=i.dilations;(p.length===0||p[0]===0)&&(p=[1]);let d=i.strides;(d.length===0||d[0]===0)&&(d=[1]);let b=i.pads;b.length===0&&(b=[0,0]),b=[0,b[0],0,b[1]],d=[1].concat(d),p=[1].concat(p),c=[1].concat(c);let T=ll({...i,pads:b,strides:d,dilations:p,kernelShape:c},u);r.compute(Ho(u,T,E=>s?[E[0],E[2],E[3]]:[E[0],E[1],E[3]]))},up=(r,i)=>{ul(r.inputs,i),r.inputs[0].dims.length===3?cl(r,i):pd(r,r.inputs,i)}}),dl,fl,hd,cp=h(()=>{Xt(),Yt(),mr(),or(),dl=(r,i,s,u)=>{let c=st.size(i),p=i.length,d=gt("input",r,p),b=Vt("output",r,p),T=s.dataType===6?s.getInt32Array()[0]:Number(s.getBigInt64Array()[0]),E=st.normalizeAxis(T,p),q=H=>{let v=` i32(${d.indicesGet("inputIndices","uniforms.axis")}) `,ne=Dt("uniforms.input_shape","uniforms.axis",p),re=u.reverse?v+(u.exclusive?" + 1":""):"0",ce=u.reverse?ne:v+(u.exclusive?"":" + 1");return` + ${H.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(d,b)} + ${H.mainStart()} + ${H.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var inputIndices = ${b.offsetToIndices("global_idx")}; + var sum = ${b.type.value}(0); + let first : i32 = ${re}; + let last : i32 = ${ce}; + for (var i : i32 = first; i < last; i++) { + ${d.indicesSet("inputIndices","uniforms.axis","u32(i)")}; + sum = sum + ${d.getByIndices("inputIndices")}; + } + ${b.setByOffset("global_idx","sum")}; + }`};return{name:"CumSum",shaderCache:{hint:u.cacheKey,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:i,dataType:r}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:[{type:12,data:c},{type:12,data:E},...Ct(i,i)]}),getShaderSource:q}},fl=(r,i)=>{let s=r.inputs[0].dims,u=r.inputs[0].dataType,c=r.inputs[1];r.compute(dl(u,s,c,i),{inputs:[0]})},hd=r=>{let i=r.exclusive===1,s=r.reverse===1;return Gt({exclusive:i,reverse:s})}}),pl,md,gd,hl,_d,dp=h(()=>{Xt(),Yt(),mr(),or(),pl=r=>{if(!r||r.length!==1)throw new Error("DepthToSpace requires 1 input.");if(r[0].dims.length!==4)throw new Error("DepthToSpace requires 4D input.")},md=(r,i,s,u)=>{let c=[];c.push(`fn perm(i: ${u.type.indices}) -> ${s.type.indices} { + var a: ${s.type.indices};`);for(let p=0;p{let s,u,c,p,d,b,T=i.format==="NHWC",E=i.blocksize,q=i.mode==="DCR";T?([s,u,c,p]=r.dims,d=q?[s,u,c,E,E,p/E**2]:[s,u,c,p/E**2,E,E],b=q?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([s,u,c,p]=[r.dims[0],r.dims[2],r.dims[3],r.dims[1]],d=q?[s,E,E,p/E**2,u,c]:[s,p/E**2,E,E,u,c],b=q?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let H=r.reshape(d),v=H.dims.length,ne=r.dataType,re=gt("a",ne,v),ce=Vt("output",ne,v),_e=be=>` + ${be.registerUniform("output_size","u32").declareVariables(re,ce)} + + ${md(b,v,re,ce)} + + ${be.mainStart()} + ${be.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${ce.offsetToIndices("global_idx")}; + let aIndices = perm(indices); + + ${ce.setByOffset("global_idx",re.getByIndices("aIndices"))} + }`;return{name:"DepthToSpace",shaderCache:{hint:`${r.dims};${i.blocksize};${i.mode}`,inputDependencies:["rank"]},getRunData:be=>{let he=T?[s,u*E,c*E,p/E**2]:[s,p/E**2,u*E,c*E],Fe=st.size(he),xe=H.dims,Ie=st.sortBasedOnPerm(xe,b);return{outputs:[{dims:he,dataType:be[0].dataType}],dispatchGroup:{x:Math.ceil(Fe/64)},programUniforms:[{type:12,data:Fe},...Ct(xe,Ie)]}},getShaderSource:_e}},hl=(r,i)=>{pl(r.inputs),r.compute(gd(r.inputs[0],i))},_d=r=>Gt({blocksize:r.blocksize,mode:r.mode,format:r.format})}),Ko,Qo,ml,Or,fp,pp,hp,Us,yd,wd,vd,mp=h(()=>{Xt(),Yt(),mr(),or(),Ko="[a-zA-Z]|\\.\\.\\.",Qo="("+Ko+")+",ml="^"+Qo+"$",Or="("+Qo+",)*"+Qo,fp="^"+Or+"$",pp=class{constructor(r=-1){this.symbolToIndices=new Map,this.inputIndex=r}addSymbol(r,i){let s=this.symbolToIndices.get(r);s===void 0?s=[i]:s.push(i),this.symbolToIndices.set(r,s)}},hp=class{constructor(r,i){var c;this.equation=i,this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=new Array,this.outputDims=[];let[s,u]=i.includes("->")?i.split("->",2):[i,""];if(!s.match(RegExp(fp)))throw new Error("Invalid LHS term");if(s.split(",").forEach((p,d)=>{let b=r[d].dims.slice();if(!p.match(RegExp(ml)))throw new Error("Invalid LHS term");let T=this.processTerm(p,!0,b,d);this.lhs.push(T)}),u==="")u+=[...this.symbolToInfo.entries()].filter(([p,d])=>d.count===1||p==="...").map(([p])=>p).join("");else if(!u.match(RegExp(Qo)))throw new Error("Invalid RHS");(c=u.match(RegExp(Ko,"g")))==null||c.forEach(p=>{if(p==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let d=this.symbolToInfo.get(p);if(d===void 0)throw new Error("Invalid RHS symbol");this.outputDims.push(d.dimValue)}}),this.rhs=this.processTerm(u,!1,this.outputDims)}addSymbol(r,i,s){let u=this.symbolToInfo.get(r);if(u!==void 0){if(u.dimValue!==i&&u.count!==1)throw new Error("Dimension mismatch");u.count++,u.inputIndices.push(s)}else u={count:1,dimValue:i,inputIndices:[s]};this.symbolToInfo.set(r,u)}processTerm(r,i,s,u=-1){let c=s.length,p=!1,d=[],b=0;if(!r.match(RegExp(ml))&&!i&&r!=="")throw new Error("Invalid LHS term");let T=r.match(RegExp(Ko,"g")),E=new pp(u);return T==null||T.forEach((q,H)=>{if(q==="..."){if(p)throw new Error("Only one ellipsis is allowed per input term");p=!0;let v=c-T.length+1;if(v<0)throw new Error("Ellipsis out of bounds");if(d=s.slice(b,b+v),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 ne=0;ner+"_max",yd=(r,i,s,u)=>{let c=r.map(E=>E.length).map((E,q)=>gt(`input${q}`,i,E)),p=st.size(u),d=Vt("output",i,u.length),b=[...s.symbolToInfo.keys()].filter(E=>!s.rhs.symbolToIndices.has(E)),T=E=>{let q=[],H="var prod = 1.0;",v="var sum = 0.0;",ne="sum += prod;",re=[],ce=[],_e=[],be=[],he=s.symbolToInfo.size===s.rhs.symbolToIndices.size;s.symbolToInfo.forEach((xe,Ie)=>{var ct;if(s.rhs.symbolToIndices.has(Ie)){let et=(ct=s.rhs.symbolToIndices.get(Ie))==null?void 0:ct[0];et!==void 0&&s.lhs.forEach((vt,Ft)=>{if(xe.inputIndices.includes(Ft)){let Lt=vt.symbolToIndices.get(Ie);if(Lt===void 0)throw new Error("Invalid symbol error");Lt.forEach(pr=>{q.push(`${c[Ft].indicesSet(`input${Ft}Indices`,pr,d.indicesGet("outputIndices",et))}`)})}})}else s.lhs.forEach((et,vt)=>{if(xe.inputIndices.includes(vt)){let Ft=et.symbolToIndices.get(Ie);if(Ft===void 0)throw new Error("Invalid symbol error");Ft.forEach(Lt=>{re.push(`${c[vt].indicesSet(`input${vt}Indices`,Lt,`${Ie}`)}`)}),be.push(`prod *= ${c[vt].getByIndices(`input${vt}Indices`)};`)}}),ce.push(`for(var ${Ie}: u32 = 0; ${Ie} < uniforms.${Us(Ie)}; ${Ie}++) {`),_e.push("}")});let Fe=he?[...q,`let sum = ${c.map((xe,Ie)=>xe.getByIndices(`input${Ie}Indices`)).join(" * ")};`]:[...q,v,...ce,...re,H,...be,ne,..._e];return` + ${E.registerUniforms(b.map(xe=>({name:`${Us(xe)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...c,d)} + + ${E.mainStart()} + ${E.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var outputIndices = ${d.offsetToIndices("global_idx")}; + ${c.map((xe,Ie)=>`var input${Ie}Indices: ${c[Ie].type.indices};`).join(` +`)} + ${Fe.join(` +`)}; + ${d.setByOffset("global_idx","sum")}; + }`};return{name:"Einsum",shaderCache:{hint:s.equation,inputDependencies:r.map(()=>"rank")},getRunData:()=>{let E=b.filter(H=>s.symbolToInfo.has(H)).map(H=>{var v;return{type:12,data:((v=s.symbolToInfo.get(H))==null?void 0:v.dimValue)||0}});E.push({type:12,data:p});let q=r.map((H,v)=>[...Ct(H)]).reduce((H,v)=>H.concat(v),E);return q.push(...Ct(u)),{outputs:[{dims:u,dataType:i}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:q}},getShaderSource:T}},wd=(r,i)=>{let s=new hp(r.inputs,i.equation),u=s.outputDims,c=r.inputs.map((p,d)=>p.dims);r.compute(yd(c,r.inputs[0].dataType,s,u))},vd=r=>{let i=r.equation.replace(/\s+/g,"");return Gt({equation:i})}}),gl,Vs,bd,xd,_l,hm=h(()=>{Xt(),Yt(),or(),gl=r=>{if(!r||r.length!==2)throw new Error("Expand requires 2 input.");let i=r[0].dims,s=Array.from(r[1].getBigInt64Array(),Number),u=s.length{let s=r.length-i.length,u=[];for(let c=0;cr.length>i.length?Vs(r,i):Vs(i,r),xd=r=>{let i=r[0].dims,s=Array.from(r[1].getBigInt64Array(),Number),u=bd(i,s),c=r[0].dataType,p=c===9?4:1,d=Math.ceil(st.size(u)/p),b=E=>{let q=gt("input",c,i.length,p),H=Vt("output",c,u.length,p),v;if(c===9){let ne=(re,ce,_e="")=>` + let outputIndices${ce} = ${H.offsetToIndices(`outputOffset + ${ce}u`)}; + let offset${ce} = ${q.broadcastedIndicesToOffset(`outputIndices${ce}`,H)}; + let index${ce} = offset${ce} / 4u; + let component${ce} = offset${ce} % 4u; + ${re}[${ce}] = ${_e}(${q.getByOffset(`index${ce}`)}[component${ce}]); + `;v=` + let outputOffset = global_idx * ${p}; + var data = vec4(0); + ${ne("data",0,"u32")} + ${ne("data",1,"u32")} + ${ne("data",2,"u32")} + ${ne("data",3,"u32")} + ${H.setByOffset("global_idx","data")} + }`}else v=` + let outputIndices = ${H.offsetToIndices("global_idx")}; + let inputOffset = ${q.broadcastedIndicesToOffset("outputIndices",H)}; + ${H.setByOffset("global_idx",q.getByOffset("inputOffset"))} + }`;return` + ${E.registerUniform("vec_size","u32").declareVariables(q,H)} + ${E.mainStart()} + ${E.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${v}`},T=[{type:12,data:d},...Ct(i,u)];return{name:"Expand",shaderCache:{hint:`${u.length}`,inputDependencies:["rank"]},getShaderSource:b,getRunData:()=>({outputs:[{dims:u,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:T})}},_l=r=>{gl(r.inputs),r.compute(xd(r.inputs),{inputs:[0]})}}),gp,Md,_p=h(()=>{Xt(),Yt(),or(),Ua(),gp=r=>{let i=r[0].dataType,s=st.size(r[0].dims),u=st.size(r[1].dims),c=u%4===0,p=d=>{let b=gt("x",i,[1],4),T=gt("bias",i,[1],4),E=Vt("y",i,[1],4),q=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],H=ne=>` + let bias${ne}_offset: u32 = (global_idx * 4 + ${ne}) % uniforms.bias_size; + let bias${ne} = ${T.getByOffset(`bias${ne}_offset / 4`)}[bias${ne}_offset % 4];`,v=c?` + let bias = ${T.getByOffset("global_idx % (uniforms.bias_size / 4)")};`:`${H(0)}${H(1)}${H(2)}${H(3)} + let bias = ${b.type.value}(bias0, bias1, bias2, bias3);`;return`${d.registerUniforms(q).declareVariables(b,T,E)} + + ${Ba(kr(i))} + + ${d.mainStart(Bn)} + ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")} + + let x = ${b.getByOffset("global_idx")}; + ${v} + let x_in = x + bias; + ${E.setByOffset("global_idx",Na("x_in"))} + }`};return{name:"FastGeluWithBias",shaderCache:{hint:`${c}`,inputDependencies:["type","type"]},getShaderSource:p,getRunData:d=>({outputs:[{dims:d[0].dims,dataType:d[0].dataType}],programUniforms:[{type:12,data:Math.ceil(s/4)},{type:12,data:u}],dispatchGroup:{x:Math.ceil(s/Bn/4)}})}},Md=r=>{r.inputs.length<2||st.size(r.inputs[1].dims)===0?Mc(r):r.compute(gp(r.inputs))}}),Td,kd,Sd,Ed,yp=h(()=>{Xt(),Yt(),mr(),or(),Td=r=>{if(!r||r.length!==2)throw new Error("Gather requires 2 inputs.")},kd=(r,i)=>{let s=r[0].dims,u=r[1].dims,c=s.length,p=st.normalizeAxis(i.axis,c),d=s.slice(0);d.splice(p,1,...u);let b=s[p],T=r[0].dataType===9?4:1,E=Math.ceil(st.size(d)/T),q=[{type:12,data:E},{type:6,data:b},{type:12,data:p},...Ct(r[0].dims,r[1].dims,d)],H=v=>{let ne=gt("data",r[0].dataType,r[0].dims.length,T),re=gt("inputIndices",r[1].dataType,r[1].dims.length),ce=Vt("output",r[0].dataType,d.length,T),_e=he=>{let Fe=u.length,xe=`var indicesIndices${he} = ${re.type.indices}(0);`;for(let Ie=0;Ie1?`indicesIndices${he}[${Ie}]`:`indicesIndices${he}`} = ${d.length>1?`outputIndices${he}[uniforms.axis + ${Ie}]`:`outputIndices${he}`};`;xe+=` + var idx${he} = ${re.getByIndices(`indicesIndices${he}`)}; + if (idx${he} < 0) { + idx${he} = idx${he} + uniforms.axisDimLimit; + } + var dataIndices${he} : ${ne.type.indices}; + `;for(let Ie=0,ct=0;Ie1?`dataIndices${he}[${Ie}]`:`dataIndices${he}`} = u32(idx${he});`,ct+=Fe):(xe+=`${c>1?`dataIndices${he}[${Ie}]`:`dataIndices${he}`} = ${d.length>1?`outputIndices${he}[${ct}]`:`outputIndices${he}`};`,ct++);return xe},be;if(r[0].dataType===9){let he=(Fe,xe,Ie="")=>` + let outputIndices${xe} = ${ce.offsetToIndices(`outputOffset + ${xe}u`)}; + ${_e(xe)}; + let offset${xe} = ${ne.indicesToOffset(`dataIndices${xe}`)}; + let index${xe} = offset${xe} / 4u; + let component${xe} = offset${xe} % 4u; + ${Fe}[${xe}] = ${Ie}(${ne.getByOffset(`index${xe}`)}[component${xe}]); + `;be=` + let outputOffset = global_idx * ${T}; + var value = vec4(0); + ${he("value",0,"u32")} + ${he("value",1,"u32")} + ${he("value",2,"u32")} + ${he("value",3,"u32")} + ${ce.setByOffset("global_idx","value")} + `}else be=` + let outputIndices = ${ce.offsetToIndices("global_idx")}; + ${_e("")}; + let value = ${ne.getByIndices("dataIndices")}; + ${ce.setByOffset("global_idx","value")}; + `;return` + ${v.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(ne,re,ce)} + ${v.mainStart()} + ${v.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + ${be} + }`};return{name:"Gather",shaderCache:{hint:i.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:d,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(E/64)},programUniforms:q}),getShaderSource:H}},Sd=r=>Gt({axis:r.axis}),Ed=(r,i)=>{let s=r.inputs;Td(s),r.compute(kd(r.inputs,i))}}),Cd,Pd,$d,Ad,wp=h(()=>{Xt(),Yt(),mr(),or(),Cd=r=>{if(!r||r.length!==2)throw new Error("GatherElements requires 2 inputs.");if(r[0].dims.length<1)throw new Error("GatherElements requires that the data input be rank >= 1.");if(r[0].dims.length!==r[1].dims.length)throw new Error(`GatherElements requires that the data input and + indices input tensors be of same rank.`)},Pd=(r,i)=>{let s=r[0].dims,u=r[0].dataType,c=s.length,p=r[1].dims,d=r[1].dataType,b=st.normalizeAxis(i.axis,c),T=s[b],E=p.slice(0),q=st.size(E),H=gt("input",u,c),v=gt("indicesInput",d,p.length),ne=Vt("output",u,E.length),re=[{type:12,data:q},{type:6,data:T},{type:12,data:b}];return re.push(...Ct(s,p,E)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:E,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(q/64)},programUniforms:re}),getShaderSource:ce=>` + ${ce.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(H,v,ne)} + ${ce.mainStart()} + ${ce.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + + let outputIndices = ${ne.offsetToIndices("global_idx")}; + + var idx = ${v.getByOffset("global_idx")}; + if (idx < 0) { + idx = idx + uniforms.axisDimLimit; + } + var inputIndices = ${H.type.indices}(outputIndices); + ${H.indicesSet("inputIndices","uniforms.axis","u32(idx)")}; + let value = ${H.getByIndices("inputIndices")}; + + ${ne.setByOffset("global_idx","value")}; + }`}},$d=r=>Gt({axis:r.axis}),Ad=(r,i)=>{let s=r.inputs;Cd(s),r.compute(Pd(r.inputs,i))}}),Id,Fd,zd,vp,Od=h(()=>{Xt(),Yt(),or(),Id=r=>{if(!r)throw new Error("Input is missing");if(r.length<2||r.length>3)throw new Error("Invaid input number.");if(r.length===3&&r[2].dims.length>2)throw new Error("Invalid input shape of C");if(r[0].dataType!==r[1].dataType||r.length===3&&r[0].dataType!==r[2].dataType)throw new Error("Input types are mismatched")},Fd=(r,i)=>{let s=r[0].dims.slice(),u=r[1].dims.slice(),[c,p,d]=xr.getShapeOfGemmResult(s,i.transA,u,i.transB,r.length===3?r[2].dims:void 0),b=[c,p];if(!b)throw new Error("Can't use gemm on the given tensors");let T=st.size(b),E=[{type:12,data:T},{type:12,data:c},{type:12,data:p},{type:12,data:d},{type:1,data:i.alpha},{type:1,data:i.beta}],q=["type","type"];r.length===3&&(E.push(...Ct(r[2].dims)),q.push("rank")),E.push(...Ct(b));let H=v=>{let ne="";i.transA&&i.transB?ne="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":i.transA&&!i.transB?ne="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!i.transA&&i.transB?ne="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!i.transA&&!i.transB&&(ne="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let re=i.alpha===1?"":"value *= uniforms.alpha;",ce=gt("a",r[0].dataType,r[0].dims),_e=gt("b",r[1].dataType,r[1].dims),be=ce.type.value,he=null,Fe=[ce,_e];r.length===3&&(he=gt("c",r[2].dataType,r[2].dims.length),Fe.push(he));let xe=Vt("output",r[0].dataType,b.length);Fe.push(xe);let Ie=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"},{name:"alpha",type:"f32"},{name:"beta",type:"f32"}];return` + ${v.registerUniforms(Ie).declareVariables(...Fe)} + + ${v.mainStart()} + ${v.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let m = global_idx / uniforms.N; + let n = global_idx % uniforms.N; + + var value = ${be}(0); + for (var k: u32 = 0u; k < uniforms.K; k++) { + ${ne} + } + + ${re} + ${he!=null?`let cOffset = ${he.broadcastedIndicesToOffset("vec2(m, n)",xe)}; value += ${be}(uniforms.beta) * ${he.getByOffset("cOffset")};`:""} + output[global_idx] = value; + }`};return{name:"Gemm",shaderCache:{hint:`${i.cacheKey}`,inputDependencies:q},getRunData:()=>({outputs:[{dims:b,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(T/64)},programUniforms:E}),getShaderSource:H}},zd=r=>{let i=r.transA,s=r.transB,u=r.alpha,c=r.beta;return{transA:i,transB:s,alpha:u,beta:c,cacheKey:`${r.transA};${r.transB};${r.alpha===1}`}},vp=(r,i)=>{Id(r.inputs),r.compute(Fd(r.inputs,i))}}),Sn,Dd,Ld,yl,Rd,Xo,Bd,Nd=h(()=>{Xt(),Yt(),mr(),fe(),Is(),or(),_o(),Sn=(r,i)=>r.length>i&&r[i].dims.length>0?r[i]:void 0,Dd=(r,i)=>{let s=r[0],u=Sn(r,1),c=Sn(r,2),p=Sn(r,3),d=Sn(r,4),b=Sn(r,5),T=Sn(r,6),E=Sn(r,7);if(s.dims.length!==3&&s.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let q=s.dims[0],H=s.dims[1],v=s.dims.length===3?s.dims[2]:i.numHeads*s.dims[4],ne=H,re=0,ce=0,_e=Math.floor(v/i.numHeads);if(T&&E){if(T.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(T.dims[0]!==q||T.dims[1]!==i.numHeads||T.dims[3]!==_e)throw new Error('Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)');if(E.dims[0]!==q||E.dims[1]!==i.numHeads||E.dims[3]!==_e)throw new Error('Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)');if(T.dims[2]!==E.dims[2])throw new Error('Input "past_key" and "past_value" shall have same dim 2 (past_sequence_length)');if(E.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');re=T.dims[2],ce=T.dims[2]}else if(T||E)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let be;if(u){if(s.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(u.dims.length<3||u.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(s.dims[0]!==u.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(u.dims.length===3){if(u.dims[2]!==s.dims[2])throw new Error('Input "query" and "key" shall have same dim 2 (hidden_size)');be=2,ne=u.dims[1]}else if(u.dims.length===5){if(u.dims[2]!==i.numHeads||u.dims[3]!==2||u.dims[4]!==_e)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(c)throw new Error('Expect "value" be none when "key" has packed kv format.');be=5,ne=u.dims[1]}else{if(u.dims[1]!==i.numHeads||u.dims[3]!==_e)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');be=0,ne=u.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');be=3}if(p){if(p.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimension');if(u&&u.dims.length===5&&u.dims[3]===2)throw new Error("bias is not allowed for packed kv.")}let he=re+ne,Fe=0;if(d){Fe=8;let et=d.dims;throw et.length===1?et[0]===q?Fe=1:et[0]===3*q+2&&(Fe=3):et.length===2&&et[0]===q&&et[1]===he&&(Fe=5),Fe===8?new Error('Input "key_padding_mask" shape shall be (batch_size) or (batch_size, total_sequence_length)'):new Error("Mask not supported")}let xe=!1,Ie=v;if(c){if(c.dims.length!==3&&c.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(s.dims[0]!==c.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(c.dims.length===3){if(ne!==c.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');Ie=c.dims[2]}else{if(ne!==c.dims[2])throw new Error('Input "key" and "value" shall have the same dim 2 (kv_sequence_length)');Ie=c.dims[1]*c.dims[3],xe=!0}}let ct=!1;if(d)throw new Error("Key padding mask is not supported");if(b){if(b.dims.length!==4)throw new Error('Input "attention_bias" is expected to have 4 dimensions');if(b.dims[0]!==q||b.dims[1]!==i.numHeads||b.dims[2]!==H||b.dims[3]!==he)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:q,sequenceLength:H,pastSequenceLength:re,kvSequenceLength:ne,totalSequenceLength:he,maxSequenceLength:ce,inputHiddenSize:0,hiddenSize:v,vHiddenSize:Ie,headSize:_e,vHeadSize:Math.floor(Ie/i.numHeads),numHeads:i.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:i.maskFilterValue,maskType:Fe,scale:i.scale,broadcastResPosBias:ct,passPastInKv:xe,qkvFormat:be}},Ld=r=>Gt({...r}),yl=Gt({perm:[0,2,1,3]}),Rd=(r,i,s,u,c,p,d)=>{let b=[u,c,p],T=st.size(b),E=[{type:12,data:T},{type:12,data:d},{type:12,data:p}],q=H=>{let v=Vt("qkv_with_bias",i.dataType,b),ne=gt("qkv",i.dataType,b),re=gt("bias",s.dataType,b),ce=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return` + ${H.registerUniforms(ce).declareVariables(ne,re,v)} + ${H.mainStart()} + ${H.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 r.compute({name:"MultiHeadAttentionAddBias",shaderCache:{inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:b,dataType:i.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(T/64)},programUniforms:E}),getShaderSource:q},{inputs:[i,s],outputs:[-1]})[0]},Xo=(r,i,s,u,c,p,d,b)=>{let T=p;if(d){if(u===1)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return T=Rd(r,p,d,i,u,s*c,b),T=T.reshape([i,u,s,c]),r.compute(fi(T,yl.perm),{inputs:[T],outputs:[-1]})[0]}else return p.dims.length===3&&(T=p.reshape([i,u,s,c])),r.compute(fi(T,yl.perm),{inputs:[T],outputs:[-1]})[0]},Bd=(r,i)=>{let s=Dd(r.inputs,i),u=r.inputs[0],c=Sn(r.inputs,1),p=Sn(r.inputs,2),d=Sn(r.inputs,3),b=Sn(r.inputs,4),T=Sn(r.inputs,5),E=Sn(r.inputs,6),q=Sn(r.inputs,7);if(u.dims.length===5)throw new Error("Packed QKV is not implemented");if((c==null?void 0:c.dims.length)===5)throw new Error("Packed KV is not implemented");let H=c&&p&&c.dims.length===4&&p.dims.length===4,v=Xo(r,s.batchSize,s.numHeads,s.sequenceLength,s.headSize,u,d,0);if(H)return yo(r,v,c,p,b,void 0,E,q,T,s,i);if(!c||!p)throw new Error("key and value must be provided");let ne=Xo(r,s.batchSize,s.numHeads,s.kvSequenceLength,s.headSize,c,d,s.hiddenSize),re=Xo(r,s.batchSize,s.numHeads,s.kvSequenceLength,s.vHeadSize,p,d,2*s.hiddenSize);yo(r,v,ne,re,b,void 0,E,q,T,s,i)}}),wl,jd,Ud,vl,Vd,Wd=h(()=>{Xt(),Yt(),or(),wl=r=>Array.from(r.getBigInt64Array(),Number),jd=r=>{if(!r||r.length!==2)throw new Error("Tile requires 2 inputs.");if(r[0].dataType!==1&&r[0].dataType!==10&&r[0].dataType!==6&&r[0].dataType!==12)throw new Error("Tile only support float, float16, int32, and uint32 data types");if(r[1].dataType!==7)throw new Error("Tile `repeats` input should be of int64 data type");if(r[1].dims.length!==1)throw new Error("Tile `repeats` input should be 1-D");if(wl(r[1]).length!==r[0].dims.length)throw new Error("Tile `repeats` input should have same number of elements as rank of input data tensor")},Ud=(r,i)=>{let s=[];for(let u=0;u{let s=r[0].dims,u=i??wl(r[1]),c=Ud(s,u),p=st.size(c),d=r[0].dataType,b=gt("input",d,s.length),T=Vt("output",d,c.length),E=q=>` + const inputShape = ${b.indices(...s)}; + ${q.registerUniform("output_size","u32").declareVariables(b,T)} + ${q.mainStart()} + ${q.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let output_indices = ${T.offsetToIndices("global_idx")}; + var input_indices: ${b.type.indices}; + for (var i = 0; i < ${s.length}; i++) { + let input_dim_i = ${b.indicesGet("uniforms.input_shape","i")}; + let input_dim_value = ${T.indicesGet("output_indices","i")} % input_dim_i; + + ${b.indicesSet("input_indices","i","input_dim_value")} + } + ${T.setByOffset("global_idx",b.getByIndices("input_indices"))} + }`;return{name:"Tile",shaderCache:{hint:`${u}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:c,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:[{type:12,data:p},...Ct(r[0].dims,c)]}),getShaderSource:E}},Vd=r=>{jd(r.inputs),r.compute(vl(r.inputs),{inputs:[0]})}}),Gd,bl,qd,Hd,xl,Kd,bp=h(()=>{Xt(),Yt(),mr(),Is(),or(),Nd(),Wd(),_o(),Gd=(r,i)=>{let s=r[0],u=r[1],c=r[2],p=r[3],d=r[4];if(s.dims.length!==3&&s.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let b=!1,T=s.dims[0],E=s.dims[1],q=s.dims.length===3?b?s.dims[2]/3:s.dims[2]:i.numHeads*s.dims[4],H=E,v=0,ne=0,re=Math.floor(q/i.numHeads),ce=p&&p.dims.length!==0,_e=d&&d.dims.length!==0,be=!0;if(ce&&_e){if(p.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');v=p.dims[1],ne=p.dims[1]}else if(ce||_e)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let he;if(u){if(s.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(u.dims.length<3||u.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(s.dims[0]!==u.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(u.dims.length===3){if(s.dims[2]%u.dims[2]!==0)throw new Error('Dimension 2 of "query" should be a multiple of "key"');he=2,H=u.dims[1]}else if(u.dims.length===5){if(u.dims[2]!==i.numHeads||u.dims[3]!==2||u.dims[4]!==re)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(c)throw new Error('Expect "value" be none when "key" has packed kv format.');he=5,H=u.dims[1]}else{if(u.dims[1]!==i.numHeads||u.dims[3]!==re)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');he=0,H=u.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');he=3}let Fe=0,xe=!1,Ie=q;if(c){if(c.dims.length!==3&&c.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(s.dims[0]!==c.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(c.dims.length===3){if(H!==c.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');Ie=c.dims[2]}else{if(H!==c.dims[2])throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');Ie=c.dims[1]*c.dims[3],xe=!0}}let ct=v+H;return{batchSize:T,sequenceLength:E,pastSequenceLength:v,kvSequenceLength:H,totalSequenceLength:ct,maxSequenceLength:ne,inputHiddenSize:0,hiddenSize:q,vHiddenSize:Ie,headSize:re,vHeadSize:Math.floor(Ie/i.kvNumHeads),numHeads:i.numHeads,kvNumHeads:i.kvNumHeads,nReps:i.numHeads/i.kvNumHeads,pastPresentShareBuffer:!1,maskType:Fe,scale:i.scale,broadcastResPosBias:!1,passPastInKv:xe,qkvFormat:he,isPastkvBSNH:be}},bl=(r,i,s,u)=>{let c=[u.batchSize,u.totalSequenceLength,u.kvNumHeads,u.headSize],p=4,d=st.size(c)/p,b=u.totalSequenceLength,T=Vt("present_kv",s,c.length,p),E=gt("new_kv",r.dataType,r.dims.length,p),q=i?gt("past_kv",i.dataType,i.dims.length,p):void 0,H=Math.ceil(u.headSize/p),v={x:b,y:r.dims[0],z:1},ne=i?["rank","rank"]:["rank"],re=[{type:12,data:d},{type:12,data:u.pastSequenceLength},{type:12,data:u.kvSequenceLength},{type:12,data:u.totalSequenceLength}],ce=[E];q?(re.push(...Ct(r.dims),...Ct(i.dims),...Ct(c)),ce.push(q)):re.push(...Ct(r.dims),...Ct(c));let _e=[{name:"output_size",type:"u32"},{name:"past_seqlen",type:"u32"},{name:"new_seqlen",type:"u32"},{name:"present_seqlen",type:"u32"}],be=` 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];`,he=` 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];`,Fe=i?`if (s < past_seqlen) { + ${be} + } else if (s < past_seqlen + uniforms.new_seqlen) { + ${he} + }`:`if (s < past_seqlen + uniforms.new_seqlen) { + ${he} + }`,xe=Ie=>` + + ${Ie.registerUniforms(_e).declareVariables(...ce,T)} + ${Ie.mainStart([H,u.kvNumHeads,1])} + ${Ie.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + var indices = ${T.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 = ${u.kvNumHeads}u; + let H = ${H}u; + + let present_seqlen = uniforms.present_seqlen; + let present_batch_stride = present_seqlen * num_heads * H; + var row_stride = H; + let is_bsnh = ${u.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; + ${Fe} + }`;return{name:"ConcatPastNew",shaderCache:{hint:`${u.kvNumHeads}${H}${!!i}`,inputDependencies:ne},getRunData:()=>({outputs:[{dims:c,dataType:s}],dispatchGroup:v,programUniforms:re}),getShaderSource:xe}},qd=r=>Gt({...r}),Hd=Gt({perm:[0,2,1,3]}),xl=(r,i,s,u,c)=>{let p=i,d=u.kvNumHeads,b=u.nReps;return i.dims.length===3&&u.kvSequenceLength!==0&&(p=i.reshape([u.batchSize,u.kvSequenceLength,d,u.headSize])),s?p=r.compute(bl(p,s,p.dataType,u),{inputs:[p,s],outputs:[u.isPastkvBSNH?c:-1]})[0]:p=r.compute(bl(p,void 0,p.dataType,u),{inputs:[p],outputs:[u.isPastkvBSNH?c:-1]})[0],b!==1&&(p=r.compute(vl([p],[1,1,1,b]),{inputs:[p],outputs:[-1]})[0],p=p.reshape([u.batchSize,u.totalSequenceLength,d*b,u.headSize])),r.compute(fi(p,Hd.perm),{inputs:[p],outputs:[-1]})[0]},Kd=(r,i)=>{var T;let s=Gd(r.inputs,i);if(r.inputs[0].dims.length===5)throw new Error("Packed QKV is not implemented");if(((T=r.inputs[1])==null?void 0:T.dims.length)===5)throw new Error("Packed KV is not implemented");let u=Xo(r,s.batchSize,s.numHeads,s.sequenceLength,s.headSize,r.inputs[0],void 0,0),c=r.inputs[3]&&r.inputs[3].dims.length!==0?r.inputs[3]:void 0,p=r.inputs[4]&&r.inputs[4].dims.length!==0?r.inputs[4]:void 0,d=xl(r,r.inputs[1],c,s,1),b=xl(r,r.inputs[2],p,s,2);yo(r,u,d,b,void 0,void 0,void 0,void 0,void 0,s,i)}}),Qd,Xd,Yd,Zd,mm=h(()=>{Xt(),Yt(),or(),Qd=(r,i)=>{let s=r[0].dims,u=s,c=2,p=st.sizeToDimension(s,c),d=st.sizeFromDimension(s,c),b=wr(d),T=d/b,E=[s[0],s[1],T],q=["rank","type","type"],H=[{type:12,data:d},{type:12,data:T}];H.push(...Ct(E,E));let v=ne=>{let re=gt("x",r[0].dataType,E.length,b),ce=gt("scale",r[1].dataType,r[1].dims),_e=gt("bias",r[2].dataType,r[2].dims),be=Vt("output",r[0].dataType,E.length,b),he=[re,ce,_e,be],Fe=re.type.value,xe=b===1?"f32":`vec${b}`,Ie=64,ct=[{name:"normSize",type:"u32"},{name:"normPackedSize",type:"u32"}];return` + var meanShared : f32; + var squaredNormShared : f32; + var workgroupShared : array<${xe}, ${Ie}>; + const workgroupSize = ${Ie}u; + ${ne.registerUniforms(ct).declareVariables(...he)} + ${ne.mainStart(Ie)} + 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 = ${xe}(0); + for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) { + initial = initial + ${xe}(${re.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 = ${Nn("workgroupShared[0]",b)} / f32(uniforms.normSize); + } + workgroupBarrier(); + + // reinitialize workgroup memory. + initial = ${xe}(0); + for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) { + let deviation = ${xe}(${re.get("batch","channel","h")}) - ${xe}(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 = ${Nn("workgroupShared[0]",b)}; + } + workgroupBarrier(); + + let invStdDev = inverseSqrt(squaredNormShared / f32(uniforms.normSize) + f32(${i.epsilon})); + let channelScale = invStdDev * f32(${ce.getByOffset("channel")}); + let channelShift = f32(${_e.getByOffset("channel")}) - meanShared * channelScale; + for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) { + let value = ${re.get("batch","channel","h")} * ${Fe}(${xe}(channelScale)) + ${Fe}(${xe}(channelShift)); + ${be.set("batch","channel","h","value")}; + } + }`};return{name:"InstanceNormalization",shaderCache:{hint:`${i.epsilon};${b}`,inputDependencies:q},getRunData:()=>({outputs:[{dims:u,dataType:r[0].dataType}],dispatchGroup:{x:p},programUniforms:H}),getShaderSource:v}},Xd=(r,i,s,u,c,p,d,b)=>{let T=wr(d),E=64,q=T===1?"vec2f":`mat2x${T}f`,H=T===1?"f32":`vec${T}f`,v=(ct,et)=>`${q}(${ct}, ${et})`,ne=c*d/T,re=Math.ceil(p/E),ce=["type"],_e=[{type:12,data:re},{type:12,data:p},{type:12,data:Math.floor(d/T)},{type:12,data:Math.floor(p*d/T)}],be=ct=>{let et=gt("input",i.dataType,i.dims,T);return` + ${ct.declareVariables(et)} + @group(0) @binding(1) var output : array<${q}>; + struct Uniforms {wg_size:u32, H:u32, C:u32, image_size:u32}; + @group(0) @binding(2) var uniforms: Uniforms; + + ${ct.mainStart(E)} + let currentImageNumber = global_idx / ${E} / uniforms.C; + let currentChannelNumber = (global_idx / ${E}) % 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 = ${zr("f32",T)}; + var squaredSum = ${zr("f32",T)}; + for (var i: u32 = wgOffset; i < wgMax; i++) { + let value = ${H}(input[offset + i * uniforms.C]); + sum += value; + squaredSum += value * value; + } + output[global_idx] = ${v("sum","squaredSum")}; + }`},he=r.compute({name:"InstanceNormComputeMean",shaderCache:{hint:`${T}`,inputDependencies:ce},getRunData:()=>({outputs:[{dims:[c,d,E,2],dataType:1}],dispatchGroup:{x:c*d/T},programUniforms:_e}),getShaderSource:be},{inputs:[i],outputs:[-1]})[0],Fe=[{type:12,data:ne},{type:12,data:p},{type:12,data:Math.floor(d/T)},{type:12,data:Math.floor(E*d/T)}],xe=["type","type","type"],Ie=ct=>{let et=gt("scale",s.dataType,s.dims,T),vt=gt("bias",u.dataType,u.dims,T);return` + @group(0) @binding(0) var input : array<${q}>; + @group(0) @binding(1) var scale : array<${et.type.storage}>; + @group(0) @binding(2) var bias : array<${vt.type.storage}>; + @group(0) @binding(3) var output : array<${q}>; + struct Uniforms {units_of_work : u32, H: u32, C : u32, image_size : u32}; + @group(0) @binding(4) var uniforms: Uniforms; + + ${ct.mainStart()} + ${ct.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 = ${zr("f32",T)}; + var squaredSum = ${zr("f32",T)}; + for (var i: u32 = 0; i < min(${E}, uniforms.H); i++) { + let value = input[offset + i + currentChannelNumber * ${E}]; + sum += value[0]; + squaredSum += value[1]; + } + sum = sum / f32(uniforms.H); + squaredSum = squaredSum / f32(uniforms.H); + let invStdDev = inverseSqrt(squaredSum - sum * sum + f32(${b})); + let channelScale = invStdDev * ${H}(scale[currentChannelNumber]); + let channelShift = ${H}(bias[currentChannelNumber]) - sum * channelScale; + + output[global_idx] = ${v("channelScale","channelShift")}; + }`};return r.compute({name:"InstanceNormComputeChannelScaleShift",shaderCache:{hint:`${T};${b}`,inputDependencies:xe},getRunData:()=>({outputs:[{dims:[c,d,2],dataType:1}],dispatchGroup:{x:Math.ceil(ne/64)},programUniforms:Fe}),getShaderSource:Ie},{inputs:[he,s,u],outputs:[-1]})[0]},Yd=(r,i,s)=>{let u=i[0].dims,c=u,p=u[0],d=u[u.length-1],b=st.sizeFromDimension(u,1)/d,T=wr(d),E=st.size(c)/T,q=[{type:12,data:b},{type:12,data:Math.floor(d/T)}],H=["type","type"],v=Xd(r,i[0],i[1],i[2],p,b,d,s.epsilon),ne=re=>{let ce=Tr(i[0].dataType),_e=T===1?"vec2f":`mat2x${T}f`,be=T===1?ce:`vec${T}<${ce}>`,he=gt("input",i[0].dataType,i[0].dims,T),Fe=Vt("output",i[0].dataType,c,T);return` + @group(0) @binding(0) var input : array<${he.type.storage}>; + @group(0) @binding(1) var scaleInput : array<${_e}>; + @group(0) @binding(2) var output : array<${Fe.type.storage}>; + struct Uniforms {H: u32, C : u32}; + @group(0) @binding(3) var uniforms: Uniforms; + + ${re.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], ${be}(scale[0]), ${be}(scale[1])); + }`};r.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${T}`,inputDependencies:H},getRunData:()=>({outputs:[{dims:c,dataType:i[0].dataType}],dispatchGroup:{x:Math.ceil(E/64)},programUniforms:q}),getShaderSource:ne},{inputs:[i[0],v]})},Zd=(r,i)=>{i.format==="NHWC"?Yd(r,r.inputs,i):r.compute(Qd(r.inputs,i))}}),ur,Jd,dn,yn=h(()=>{Xt(),Yt(),or(),ur=r=>{if(!r||r.length<2)throw new Error("layerNorm requires at least 2 inputs.")},Jd=(r,i,s)=>{let u=i.simplified,c=r[0].dims,p=r[1],d=!u&&r[2],b=c,T=st.normalizeAxis(i.axis,c.length),E=st.sizeToDimension(c,T),q=st.sizeFromDimension(c,T),H=st.size(p.dims),v=d?st.size(d.dims):0;if(H!==q||d&&v!==q)throw new Error(`Size of X.shape()[axis:] == ${q}. + Size of scale and bias (if provided) must match this. + Got scale size of ${H} and bias size of ${v}`);let ne=[];for(let Ie=0;Ie1,he=s>2,Fe=Ie=>{let ct=Tr(r[0].dataType),et=[gt("x",r[0].dataType,r[0].dims,re),gt("scale",p.dataType,p.dims,re)];d&&et.push(gt("bias",d.dataType,d.dims,re)),et.push(Vt("output",r[0].dataType,b,re)),be&&et.push(Vt("mean_data_output",1,ne)),he&&et.push(Vt("inv_std_output",1,ne));let vt=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return` + ${Ie.registerUniforms(vt).declareVariables(...et)} + ${Ie.mainStart()} + ${Ie.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")} + let offset = global_idx * uniforms.norm_size_vectorized; + var mean_vector = ${zr("f32",re)}; + var mean_square_vector = ${zr("f32",re)}; + + for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) { + let value = ${Gr(ct,re,"x[h + offset]")}; + mean_vector += value; + mean_square_vector += value * value; + } + let mean = ${Nn("mean_vector",re)} / uniforms.norm_size; + let inv_std_dev = inverseSqrt(${Nn("mean_square_vector",re)} / uniforms.norm_size ${u?"":"- mean * mean"} + uniforms.epsilon); + + for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) { + let f32input = ${Gr(ct,re,"x[j + offset]")}; + let f32scale = ${Gr(ct,re,"scale[j]")}; + output[j + offset] = ${et[0].type.value}((f32input ${u?"":"- mean"}) * inv_std_dev * f32scale + ${d?`+ ${Gr(ct,re,"bias[j]")}`:""} + ); + } + + ${be?"mean_data_output[global_idx] = mean":""}; + ${he?"inv_std_output[global_idx] = inv_std_dev":""}; + }`},xe=[{dims:b,dataType:r[0].dataType}];return be&&xe.push({dims:ne,dataType:1}),he&&xe.push({dims:ne,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${re};${s};${u}`,inputDependencies:ce},getRunData:()=>({outputs:xe,dispatchGroup:{x:Math.ceil(E/64)},programUniforms:_e}),getShaderSource:Fe}},dn=(r,i)=>{ur(r.inputs),r.compute(Jd(r.inputs,i,r.outputCount))}}),wn,Ji,xp,ef,Mp=h(()=>{Xt(),Yt(),mr(),or(),wn=(r,i)=>{if(r.length<3||r.length>4)throw new Error("MatMulNBits requires 3 or 4 inputs");let s=r[0],u=s.dims.length;if(s.dims[u-1]!==i.k)throw new Error("The last dim of input shape does not match the k value");let c=Math.floor((i.k+i.blockSize-1)/i.blockSize),p=i.blockSize/8*i.bits,d=r[1];if(!st.areEqual(d.dims,[i.n,c,p]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let b=r[2].dims;if(st.size(b)!==i.n*c)throw new Error("scales input size error.");if(r.length===4){let T=r[3].dims,E=i.bits>4?i.n*c:i.n*Math.floor((c+1)/2);if(st.size(T)!==E)throw new Error("zeroPoints input size error.")}},Ji=(r,i,s,u)=>{let c=r[0].dims,p=c.length,d=Math.floor((i.k+i.blockSize-1)/i.blockSize),b=c[p-2],T=i.k,E=i.n,q=c.slice(0,p-2),H=st.size(q),v=i.blockSize/8*i.bits/4,ne=r[0].dataType,re=wr(b),ce=wr(i.k),_e=wr(v),be=Mi(ne,b*d),he=Math.floor(u/be),Fe=d<=s[0]&&he>0,xe=!Fe||he>=4?wr(E):he>=2&&wr(E)>=2?2:1,Ie=q.concat([b,E]),ct=st.size(Ie)/xe/re,et=Fe?[]:[{type:12,data:ct},{type:12,data:i.blockSize}],vt=[H,b,T/ce],Ft=st.convertShape(r[1].dims).slice();Ft.splice(-1,1,v/_e),et.push(...Ct(vt)),et.push(...Ct(Ft)),et.push(...Ct(r[2].dims)),r.length===4&&et.push(...Ct(st.convertShape(r[3].dims)));let Lt=[H,b,E/xe];et.push(...Ct(Lt));let pr=ar=>{let nr=vt.length,yr=gt("a",r[0].dataType,nr,ce),qr=gt("b",12,Ft.length,_e),Sr=gt("scales",r[2].dataType,r[2].dims.length),jr=[yr,qr,Sr],It=r.length===4?gt("zero_points",12,r[3].dims.length):void 0;It&&jr.push(It);let tr=Lt.length,er=Vt("output",r[0].dataType,tr,xe),pt=[{name:"output_size",type:"u32"},{name:"block_size",type:"u32"}],zt=Tr(r[0].dataType),ir=(()=>{switch(ce){case 1:return`array<${zt}, 8>`;case 2:return`mat4x2<${zt}>`;case 4:return`mat2x4<${zt}>`;default:throw new Error(`${ce}-component is not supported.`)}})(),Hr=` + for (var word: u32 = 0; word < ${v}; word += ${_e}) { + ${qr.indicesSet("b_indices","2","word")}; + let b_data = ${qr.getByIndices("b_indices")}; + for (var i: u32 = 0; i < ${_e}; i++) { + let b_value: u32 = ${_e===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 = ${ir}(${Array.from({length:4},(xn,Yn)=>`${zt}(b_value_lower[${Yn}]), ${zt}(b_value_upper[${Yn}])`).join(", ")}); + let b_dequantized_values = ${ce===1?`${ir}(${Array.from({length:8},(xn,Yn)=>`(b_quantized_values[${Yn}] - zero_point) * scale`).join(", ")});`:`(b_quantized_values - ${ir}(${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 < ${Fe?b:re}u; m++) { + ${yr.indicesSet("a_indices",nr-2,Fe?"m":`row * ${re} + m`)}; + ${yr.indicesSet("a_indices",nr-1,"word_offset")}; + var input_offset = ${yr.indicesToOffset("a_indices")}; + var a_data: ${ir}; + for (var j: u32 = 0; j < ${8/ce}; j++) { + a_data[j] = ${yr.getByOffset("input_offset")}; + input_offset++; + } + ${Fe?"workgroup_shared[workgroup_shared_offset + m]":"output_values[m]"}${xe>1?"[c]":""} += ${Array.from({length:8/ce},(xn,Yn)=>`${ce===1?`a_data[${Yn}] * b_dequantized_values[${Yn}]`:`dot(a_data[${Yn}], b_dequantized_values[${Yn}])`}`).join(" + ")}; + } + word_offset += ${8/ce}; + } + }`,un=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 Fe?` + var workgroup_shared: array<${er.type.value}, ${b*d}>; + ${ar.declareVariables(...jr,er)} + ${ar.mainStart([d,1,1])} + var a_indices: ${yr.type.indices}; + var block = local_id.x; + var col = workgroup_id.y; + var batch = workgroup_id.z; + ${yr.indicesSet("a_indices","0","batch")}; + // Two zero points are packed into one byte when uniforms.bits is 4. + for (var c: u32 = 0; c < ${xe}; c++) { + let col_times_components_plus_c = col * ${xe} + 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: ${qr.type.indices}; + ${qr.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 = ${Sr.getByOffset("scales_index")}; + // The default zero point is 8 for unsigned 4-bit quantization. + let zero_point = ${zt}(${It?"(zero_point_word) & 0xFu":8}); + ${qr.indicesSet("b_indices","1","block")}; + var word_offset: u32 = block * ${i.blockSize/ce}; + var workgroup_shared_offset: u32 = block * ${b}; + ${Hr} + } + workgroupBarrier(); + var output_indices: ${er.type.indices}; + var elements_per_thread: u32 = ${Math.ceil(b/d)}; + ${er.indicesSet("output_indices","0","batch")}; + ${er.indicesSet("output_indices",tr-1,"col")}; + ${er.indicesSet("output_indices",tr-2,"local_id.x * elements_per_thread")}; + var output_offset = ${er.indicesToOffset("output_indices")}; + for (var m: u32 = 0u; m < elements_per_thread; m++) { + var row = m + local_id.x * elements_per_thread; + if (row < ${b}) { + var output_value: ${er.type.value} = ${er.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 += ${b}; + } + ${er.setByOffset("output_offset","output_value")}; + output_offset += ${E/xe}; + } + } + }`:` + ${ar.registerUniforms(pt).declareVariables(...jr,er)} + ${ar.mainStart()} + ${ar.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + var output_values: array<${er.type.value}, ${re}>; + var output_indices = ${er.offsetToIndices("global_idx")}; + var col = ${er.indicesGet("output_indices",tr-1)}; + var row = ${er.indicesGet("output_indices",tr-2)}; + var a_indices: ${yr.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 * ${xe} * ((${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*xe}; + var b_indices: ${qr.type.indices}; + for (var c: u32 = 0; c < ${xe}; c++) { + ${qr.indicesSet("b_indices","0",`col * ${xe} + 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 = ${Sr.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}); + ${qr.indicesSet("b_indices","1","block")}; + var word_offset: u32 = block_offset; + ${Hr} + scale_index++; + ${un} + block_offset += uniforms.block_size / ${ce}; + } + // 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) { + ${un} + }`:""} + } + for (var k: u32 = 0u; k < ${re}u; k++) { + ${er.indicesSet("output_indices",tr-2,`${re} * row + k`)}; + ${er.setByIndices("output_indices","output_values[k]")} + } + }`};return{name:Fe?"BlockwiseMatMulNBits":"MatMulNBits",shaderCache:{hint:`${i.cacheKey};${b};${ne};${r.length}`,inputDependencies:Array(r.length).fill("rank")},getRunData:()=>({outputs:[{dims:Ie,dataType:ne}],name:Fe?"BlockwiseMatMulNBits":"MatMulNBits",dispatchGroup:Fe?{x:1,y:Math.ceil(E/xe),z:H}:{x:Math.ceil(ct/64)},programUniforms:et}),getShaderSource:pr}},xp=(r,i)=>{wn(r.inputs,i);let s=r.getMaxComputeWorkgroupSizes(),u=r.getMaxComputeWorkgroupStoragesize();r.compute(Ji(r.inputs,i,s,u))},ef=r=>Gt(r)}),V,G,ie,Ee,Ze,it,_t,Et,Wt,cr=h(()=>{Xt(),Yt(),or(),V=r=>{if(!r||r.length<1)throw new Error("Too few inputs");if(r[0].dataType!==1&&r[0].dataType!==10)throw new Error("Input type must be float or float16.");if(r.length>=2){let i=r[0].dims.length*2===r[1].dims[0];if(r.length===4&&(i=r[3].dims[0]*2===r[1].dims[0]),!i)throw new Error("The pads should be a 1D tensor of shape [2 * input_rank] or [2 * num_axes].")}},G=(r,i,s)=>{let u="";for(let c=i-1;c>=0;--c)u+=` + k = i32(${r.indicesGet("indices",c)}) - ${Dt("uniforms.pads",c,s)}; + if (k < 0) { + break; + } + if (k >= i32(${Dt("uniforms.x_shape",c,i)})) { + break; + } + offset += k * i32(${Dt("uniforms.x_strides",c,i)}); + `;return` + value = ${r.type.value}(uniforms.constant_value); + for (var i = 0; i < 1; i++) { + var offset = 0; + var k = 0; + ${u} + value = x[offset]; + } + `},ie=(r,i,s)=>{let u="";for(let c=i-1;c>=0;--c)u+=` + k = i32(${r.indicesGet("indices",c)}) - ${Dt("uniforms.pads",c,s)}; + if (k < 0) { + k = -k; + } + { + let _2n_1 = 2 * (i32(${Dt("uniforms.x_shape",c,i)}) - 1); + k = k % _2n_1; + if(k >= i32(${Dt("uniforms.x_shape",c,i)})) { + k = _2n_1 - k; + } + } + offset += k * i32(${Dt("uniforms.x_strides",c,i)}); + `;return` + var offset = 0; + var k = 0; + ${u} + value = x[offset]; + `},Ee=(r,i,s)=>{let u="";for(let c=i-1;c>=0;--c)u+=` + k = i32(${r.indicesGet("indices",c)}) - ${Dt("uniforms.pads",c,s)}; + if (k < 0) { + k = 0; + } + if (k >= i32(${Dt("uniforms.x_shape",c,i)})) { + k = i32(${Dt("uniforms.x_shape",c,i)}) - 1; + } + offset += k * i32(${Dt("uniforms.x_strides",c,i)}); + `;return` + var offset = 0; + var k = 0; + ${u} + value = x[offset]; + `},Ze=(r,i,s)=>{let u="";for(let c=i-1;c>=0;--c)u+=` + k = i32(${r.indicesGet("indices",c)}) - ${Dt("uniforms.pads",c,s)}; + if (k < 0) { + k += i32(${Dt("uniforms.x_shape",c,i)}]); + } + if (k >= i32(${Dt("uniforms.x_shape",c,i)})) { + k -= i32(${Dt("uniforms.x_shape",c,i)}); + } + offset += k * i32(${Dt("uniforms.x_strides",c,i)}); + `;return` + var offset = 0; + var k = 0; + ${u} + value = x[offset]; + `},it=(r,i,s)=>{switch(s.mode){case 0:return G(r,i,s.pads.length);case 1:return ie(r,i,s.pads.length);case 2:return Ee(r,i,s.pads.length);case 3:return Ze(r,i,s.pads.length);default:throw new Error("Invalid mode")}},_t=(r,i)=>{let s=st.padShape(r[0].dims.slice(),i.pads),u=r[0].dims,c=st.size(s),p=[{type:12,data:c},{type:6,data:i.pads}];i.mode===0&&p.push({type:r[0].dataType,data:i.value}),p.push(...Ct(r[0].dims,s));let d=["rank"],b=T=>{let E=Vt("output",r[0].dataType,s.length),q=gt("x",r[0].dataType,u.length),H=q.type.value,v=it(E,u.length,i),ne=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:i.pads.length}];return i.mode===0&&ne.push({name:"constant_value",type:H}),` + ${T.registerUniforms(ne).declareVariables(q,E)} + ${T.mainStart()} + ${T.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${E.offsetToIndices("global_idx")}; + + var value = ${H}(0); + ${v} + output[global_idx] = value; + }`};return{name:"Pad",shaderCache:{hint:`${i.mode}`,inputDependencies:d},getRunData:()=>({outputs:[{dims:s,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(st.size(s)/64)},programUniforms:p}),getShaderSource:b}},Et=(r,i)=>{if(r.length>1){let s=r[1].getBigInt64Array(),u=r.length>=3&&r[2].data?r[2].getFloat32Array()[0]:0,c=r[0].dims.length,p=new Int32Array(2*c).fill(0);if(r.length>=4){let b=r[3].getBigInt64Array();for(let T=0;Tp[Number(T)]=Number(b));let d=[];return p.forEach(b=>d.push(b)),{mode:i.mode,value:u,pads:d}}else return i},Wt=(r,i)=>{V(r.inputs);let s=Et(r.inputs,i);r.compute(_t(r.inputs,s),{inputs:[0]})}}),sr,$r,dr,_r,fr,gr,br,Dr,En,An,Ei,vn,ln,bn,Ws,Gs,Ml,gm,pi,Yo=h(()=>{Z(),Xt(),Yt(),or(),sr=r=>{if(D.webgpu.validateInputContent&&(!r||r.length!==1))throw new Error("Pool ops requires 1 input.")},$r=(r,i,s)=>{let u=i.format==="NHWC",c=r.dims.slice();u&&c.splice(1,0,c.pop());let p=Object.hasOwnProperty.call(i,"dilations"),d=i.kernelShape.slice(),b=i.strides.slice(),T=p?i.dilations.slice():[],E=i.pads.slice();qn.adjustPoolAttributes(s,c,d,b,T,E);let q=qn.computePoolOutputShape(s,c,b,T,d,E,i.autoPad),H=Object.assign({},i);p?Object.assign(H,{kernelShape:d,strides:b,pads:E,dilations:T,cacheKey:i.cacheKey}):Object.assign(H,{kernelShape:d,strides:b,pads:E,cacheKey:i.cacheKey});let v=q.slice();return v.push(v.splice(1,1)[0]),[H,u?v:q]},dr=(r,i)=>{let s=i.format==="NHWC",u=st.size(r),c=st.size(i.kernelShape),p=[{type:12,data:u},{type:12,data:c}],d=[{name:"outputSize",type:"u32"},{name:"kernelSize",type:"u32"}];if(i.kernelShape.length<=2){let b=i.kernelShape[i.kernelShape.length-1],T=i.strides[i.strides.length-1],E=i.pads[i.pads.length/2-1],q=i.pads[i.pads.length-1],H=!!(E+q);p.push({type:12,data:b},{type:12,data:T},{type:12,data:E},{type:12,data:q}),d.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let v=!1;if(i.kernelShape.length===2){let ne=i.kernelShape[i.kernelShape.length-2],re=i.strides[i.strides.length-2],ce=i.pads[i.pads.length/2-2],_e=i.pads[i.pads.length-2];v=!!(ce+_e),p.push({type:12,data:ne},{type:12,data:re},{type:12,data:ce},{type:12,data:_e}),d.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[p,d,!0,H,v]}else{if(s)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let b=st.computeStrides(i.kernelShape);p.push({type:12,data:b},{type:12,data:i.pads},{type:12,data:i.strides}),d.push({name:"kernelStrides",type:"u32",length:b.length},{name:"pads",type:"u32",length:i.pads.length},{name:"strides",type:"u32",length:i.strides.length});let T=i.pads.reduce((E,q)=>E+q);return[p,d,!!T,!1,!1]}},_r=(r,i,s,u,c,p,d,b,T,E,q,H)=>{let v=c.format==="NHWC",ne=i.type.value,re=Vt("output",i.type.tensor,u);if(c.kernelShape.length<=2){let ce="",_e="",be="",he=s-(v?2:1);if(q?ce=` + for (var i: u32 = 0u; i < uniforms.kw; i++) { + xIndices[${he}] = indices[${he}] * uniforms.sw - uniforms.pwStart + i; + if (xIndices[${he}] < 0 || xIndices[${he}] + >= uniforms.x_shape[${he}]) { + pad++; + continue; + } + let x_val = x[${i.indicesToOffset("xIndices")}]; + ${p} + }`:ce=` + for (var i: u32 = 0u; i < uniforms.kw; i++) { + xIndices[${he}] = indices[${he}] * uniforms.sw - uniforms.pwStart + i; + let x_val = x[${i.indicesToOffset("xIndices")}]; + ${p} + }`,c.kernelShape.length===2){let Fe=s-(v?3:2);H?_e=` + for (var j: u32 = 0u; j < uniforms.kh; j++) { + xIndices[${Fe}] = indices[${Fe}] * uniforms.sh - uniforms.phStart + j; + if (xIndices[${Fe}] < 0 || xIndices[${Fe}] >= uniforms.x_shape[${Fe}]) { + pad += i32(uniforms.kw); + continue; + } + `:_e=` + for (var j: u32 = 0u; j < uniforms.kh; j++) { + xIndices[${Fe}] = indices[${Fe}] * uniforms.sh - uniforms.phStart + j; + `,be=` + } + `}return` + ${r.registerUniforms(T).declareVariables(i,re)} + + ${r.mainStart()} + ${r.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + + let indices = ${re.offsetToIndices("global_idx")}; + var xIndices = ${re.offsetToIndices("global_idx")}; + + var value = ${ne}(${b}); + var pad = 0; + ${_e} + ${ce} + ${be} + ${d} + + output[global_idx] = value; + }`}else{if(v)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let ce=c.kernelShape.length,_e=c.pads.length,be="";return E?be=` + if (xIndices[j] >= uniforms.x_shape[j]) { + pad++; + isPad = true; + break; + } + } + if (!isPad) { + let x_val = x[${i.indicesToOffset("xIndices")}]; + ${p} + }`:be=` + } + let x_val = x[${i.indicesToOffset("xIndices")}]; + ${p} + `,` + ${r.registerUniforms(T).declareVariables(i,re)} + + ${r.mainStart()} + ${r.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + let indices = ${re.offsetToIndices("global_idx")}; + var xIndices = ${re.offsetToIndices("global_idx")}; + + var offsets: array; + + var value = ${ne}(${b}); + var pad = 0; + var isPad = false; + + for (var i: u32 = 0u; i < uniforms.kernelSize; i++) { + var offset = i; + for (var j = 0u; j < ${ce-1}u; j++) { + offsets[j] = offset / ${Dt("uniforms.kernelStrides","j",ce)}; + offset -= offsets[j] * ${Dt("uniforms.kernelStrides","j",ce)}; + } + offsets[${ce-1}] = offset; + + isPad = false; + for (var j = ${s-ce}u; j < ${s}u; j++) { + xIndices[j] = indices[j] * ${Dt("uniforms.strides",`j - ${s-ce}u`,ce)} + + offsets[j - ${s-ce}u] - ${Dt("uniforms.pads","j - 2u",_e)}; + ${be} + } + ${d} + + output[global_idx] = value; + }`}},fr=r=>`${r.format};${r.ceilMode};${r.autoPad};${r.kernelShape.length}`,gr=r=>`${fr(r)};${r.countIncludePad}`,br=r=>`${fr(r)};${r.storageOrder};${r.dilations}`,Dr=r=>({format:r.format,autoPad:["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][r.auto_pad],ceilMode:r.ceil_mode,kernelShape:r.kernel_shape,strides:r.strides,pads:r.pads}),En=(r,i,s,u)=>{let[c,p]=$r(i,u,s),d=gt("x",i.dataType,i.dims.length),b=d.type.value,T="value += x_val;",E="";c.countIncludePad?E+=`value /= ${b}(uniforms.kernelSize);`:E+=`value /= ${b}(i32(uniforms.kernelSize) - pad);`;let[q,H,v,ne,re]=dr(p,c);q.push(...Ct(i.dims,p));let ce=["rank"];return{name:r,shaderCache:{hint:`${u.cacheKey};${v};${ne};${re}`,inputDependencies:ce},getRunData:()=>({outputs:[{dims:p,dataType:i.dataType}],dispatchGroup:{x:Math.ceil(st.size(p)/64)},programUniforms:q}),getShaderSource:_e=>_r(_e,d,i.dims.length,p.length,c,T,E,0,H,v,ne,re)}},An=r=>{let i=r.count_include_pad!==0,s=Dr(r);if(s.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");let u={countIncludePad:i,...s,cacheKey:""};return{...u,cacheKey:gr(u)}},Ei=(r,i)=>{sr(r.inputs),r.compute(En("AveragePool",r.inputs[0],!1,i))},vn={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},ln=r=>{let i=r.format;return{format:i,...vn,cacheKey:i}},bn=(r,i)=>{sr(r.inputs),r.compute(En("GlobalAveragePool",r.inputs[0],!0,i))},Ws=(r,i,s,u)=>{let[c,p]=$r(i,u,s),d=` + value = max(x_val, value); + `,b="",T=gt("x",i.dataType,i.dims.length),E=["rank"],[q,H,v,ne,re]=dr(p,c);return q.push(...Ct(i.dims,p)),{name:r,shaderCache:{hint:`${u.cacheKey};${v};${ne};${re}`,inputDependencies:E},getRunData:()=>({outputs:[{dims:p,dataType:i.dataType}],dispatchGroup:{x:Math.ceil(st.size(p)/64)},programUniforms:q}),getShaderSource:ce=>_r(ce,T,i.dims.length,p.length,c,d,b,i.dataType===10?-65504:-1e5,H,v,ne,re)}},Gs=(r,i)=>{sr(r.inputs),r.compute(Ws("MaxPool",r.inputs[0],!1,i))},Ml=r=>{let i=r.storage_order,s=r.dilations,u=Dr(r);if(i!==0)throw new Error("column major storage order is not yet supported for MaxPool");if(u.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");let c={storageOrder:i,dilations:s,...u,cacheKey:""};return{...c,cacheKey:br(c)}},gm=r=>{let i=r.format;return{format:i,...vn,cacheKey:i}},pi=(r,i)=>{sr(r.inputs),r.compute(Ws("GlobalMaxPool",r.inputs[0],!0,i))}}),Tp,kp,Sp,tf,J2=h(()=>{Xt(),Yt(),mr(),or(),Tp=(r,i)=>{if(r.length<2||r.length>3)throw new Error("DequantizeLinear requires 2 or 3 inputs.");if(r.length===3&&r[1].dims===r[2].dims)throw new Error("x-scale and x-zero-point must have the same shape.");if(r.length===3&&r[0].dataType!==r[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(r[0].dataType===6&&r.length>2)throw new Error("In the case of dequantizing int32 there is no zero point.");if(r[1].dims.length!==0&&r[1].dims.length!==1&&r[1].dims.length!==r[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(r.length>2){if(r[0].dataType!==r[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(r[1].dims.length!==r[2].dims.length)throw new Error("scale and zero-point inputs must have the same rank.");if(!r[1].dims.map((s,u)=>s===r[2].dims[u]).reduce((s,u)=>s&&u,!0))throw new Error("scale and zero-point inputs must have the same shape.")}if(i.blockSize>0){if(r[1].dims.length===0||r[1].dims.length===1&&r[1].dims[0]===1)throw new Error("blockSize must be set only for block quantization.");if(!r[1].dims.map((c,p)=>p===i.axis||c===r[0].dims[p]).reduce((c,p)=>c&&p,!0))throw new Error("For block qunatization, scale input shape to match the input shape except for the axis");if(r[1].dims.length!==r[0].dims.length)throw new Error("For block qunatization the scale input rank must be the same as the x rank.");let s=r[0].dims[i.axis],u=r[1].dims[i.axis];if(i.blockSizeMath.ceil(s/(u-1)-1))throw new Error("blockSize must be with in the range [ceil(dI / Si), ceil(dI / (Si - 1) - 1)].")}},kp=(r,i)=>{let s=st.normalizeAxis(i.axis,r[0].dims.length),u=r[0].dataType,c=u===3,p=r[0].dims,d=r[1].dataType,b=st.size(p),T=u===3||u===2,E=T?[Math.ceil(st.size(r[0].dims)/4)]:r[0].dims,q=r[1].dims,H=r.length>2?r[2]:void 0,v=H?T?[Math.ceil(st.size(H.dims)/4)]:H.dims:void 0,ne=q.length===0||q.length===1&&q[0]===1,re=ne===!1&&q.length===1,ce=wr(b),_e=ne&&(!T||ce===4),be=_e?ce:1,he=_e&&!T?ce:1,Fe=gt("input",T?12:u,E.length,he),xe=gt("scale",d,q.length),Ie=H?gt("zero_point",T?12:u,v.length):void 0,ct=Vt("output",d,p.length,be),et=[Fe,xe];Ie&&et.push(Ie);let vt=[E,q];H&&vt.push(v);let Ft=[{type:12,data:b/be},{type:12,data:s},{type:12,data:i.blockSize},...Ct(...vt,p)],Lt=pr=>{let ar=[{name:"output_size",type:"u32"},{name:"axis",type:"u32"},{name:"block_size",type:"u32"}];return` + ${pr.registerUniforms(ar).declareVariables(...et,ct)} + ${pr.mainStart()} + ${pr.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let output_indices = ${ct.offsetToIndices("global_idx")}; + + // Set input x + ${T?` + let input = ${Fe.getByOffset("global_idx / 4")}; + let x_vec = ${c?"unpack4xI8(input)":"unpack4xU8(input)"}; + let x_value = ${be===1?"x_vec[global_idx % 4]":"x_vec"};`:`let x_value = ${Fe.getByOffset("global_idx")};`}; + + // Set scale input + ${ne?`let scale_value= ${xe.getByOffset("0")}`:re?` + let scale_index = ${ct.indicesGet("output_indices","uniforms.axis")}; + let scale_value= ${xe.getByOffset("scale_index")};`:` + var scale_indices: ${xe.type.indices} = output_indices; + let index = ${xe.indicesGet("scale_indices","uniforms.axis")} / uniforms.block_size; + ${xe.indicesSet("scale_indices","uniforms.axis","index")}; + let scale_value= ${xe.getByIndices("scale_indices")};`}; + + // Set zero-point input + ${Ie?ne?T?` + let zero_point_input = ${Ie.getByOffset("0")}; + let zero_point_vec = ${c?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; + let zero_point_value= zero_point_vec[0]`:`let zero_point_value = ${Ie.getByOffset("0")}`:re?T?` + let zero_point_index = ${ct.indicesGet("output_indices","uniforms.axis")}; + let zero_point_input = ${Ie.getByOffset("zero_point_index / 4")}; + let zero_point_vec = ${c?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; + let zero_point_value = zero_point_vec[zero_point_index % 4]`:` + let zero_point_index = ${ct.indicesGet("output_indices","uniforms.axis")}; + let zero_point_value = ${Ie.getByOffset("zero_point_index")};`:T?` + let zero_point_offset = ${xe.indicesToOffset("scale_indices")}; + let zero_point_input = ${Ie.getByOffset("zero_point_offset / 4")}; + let zero_point_vec = ${c?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; + let zero_point_value = zero_point_vec[zero_point_offset % 4];`:`let zero_point_value = ${Ie.getByIndices("scale_indices")};`:`let zero_point_value = ${T?c?"i32":"u32":Fe.type.value}(0);`}; + // Compute and write output + ${ct.setByOffset("global_idx",`${ct.type.value}(x_value - zero_point_value) * scale_value`)}; + }`};return{name:"DequantizeLinear",shaderCache:{hint:i.cacheKey,inputDependencies:Ie?["rank","rank","rank"]:["rank","rank"]},getShaderSource:Lt,getRunData:()=>({outputs:[{dims:p,dataType:d}],dispatchGroup:{x:Math.ceil(b/be/64),y:1,z:1},programUniforms:Ft})}},Sp=(r,i)=>{Tp(r.inputs,i),r.compute(kp(r.inputs,i))},tf=r=>Gt({axis:r.axis,blockSize:r.blockSize})}),_0,y0,w0,ex=h(()=>{Z(),Xt(),or(),_0=(r,i,s)=>{let u=r===i,c=ri&&s>0;if(u||c||p)throw new Error("Range these inputs' contents are invalid.")},y0=(r,i,s,u)=>{let c=Math.abs(Math.ceil((i-r)/s)),p=[c],d=c,b=[{type:12,data:d},{type:u,data:r},{type:u,data:s},...Ct(p)],T=E=>{let q=Vt("output",u,p.length),H=q.type.value,v=[{name:"outputSize",type:"u32"},{name:"start",type:H},{name:"delta",type:H}];return` + ${E.registerUniforms(v).declareVariables(q)} + ${E.mainStart()} + ${E.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + output[global_idx] = uniforms.start + ${H}(global_idx) * uniforms.delta; + }`};return{name:"Range",shaderCache:{hint:`${u}`},getShaderSource:T,getRunData:()=>({outputs:[{dims:p,dataType:u}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:b})}},w0=r=>{let i=0,s=0,u=0;r.inputs[0].dataType===6?(i=r.inputs[0].getInt32Array()[0],s=r.inputs[1].getInt32Array()[0],u=r.inputs[2].getInt32Array()[0]):r.inputs[0].dataType===1&&(i=r.inputs[0].getFloat32Array()[0],s=r.inputs[1].getFloat32Array()[0],u=r.inputs[2].getFloat32Array()[0]),D.webgpu.validateInputContent&&_0(i,s,u),r.compute(y0(i,s,u,r.inputs[0].dataType),{inputs:[]})}}),v0,b0,x0,M0,T0,k0,S0,E0,C0,P0,$0,_m,A0,I0,F0,z0,O0,D0,L0,tx=h(()=>{Xt(),Yt(),mr(),or(),v0=(r,i)=>{if(r.every(s=>s>0||(()=>{throw new Error("Resize requires scales input values to be positive")})),r.length>0){if(i.mode==="linear"){if(!(r.length===2||r.length===3||r.length===4&&r[0]===1&&r[1]===1||r.length===4&&r[0]===1&&r[3]===1||r.length===5&&r[0]===1&&r[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"&&!(r.length===2||r.length===4&&r[0]===1&&r[1]===1||r.length===4&&r[0]===1&&r[3]===1))throw new Error("Resize requires scales input size to be 2 or 4 for cubic mode")}},b0=(r,i,s)=>{i.every(c=>c>=0&&c{throw new Error("Resize requires axes input values to be positive and less than rank")}));let u=new Array(s).fill(1);return i.forEach((c,p)=>u[c]=r[p]),u},x0=(r,i,s,u,c,p)=>{let[d,b,T]=s>10?[1,2,3]:[-1,r.length>1?1:-1,-1],E=r[0].dims.length;if(d>0&&r.length>d&&r[d].dims.length>0)r[d].getFloat32Array().forEach(q=>p.push(q));else if(i.coordinateTransformMode==="tf_crop_and_resize")throw new Error("Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize");if(b>0&&r.length>b&&r[b].dims.length>0){if(r[b].getFloat32Array().forEach(q=>u.push(q)),u.length!==0&&u.length!==E&&s>=18&&u.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");v0(u,i),i.axes.length>0&&b0(u,i.axes,E).forEach((q,H)=>u[H]=q)}if(T>0&&r.length>T&&(r[T].getBigInt64Array().forEach(q=>c.push(Number(q))),c.length!==E||s>=18&&c.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(u.length!==i.axes.length)throw new Error('Resize requires "scales" input size to be of axes rank when axes attributes is specified');if(c.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 u<"u"&&typeof c<"u"&&u.length>0&&c.length>E)throw new Error("Resize requires only of scales or sizes to be specified")},M0=(r,i)=>`fn getOriginalCoordinateFromResizedCoordinate(xResized: u32, xScale: f32, lengthResized: u32, + lengthOriginal: u32, roiStart: f32, roiEnd: f32) -> ${i} { `+(()=>{switch(r){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 ${r} is not supported`)}})()+"}",T0=(r,i,s)=>`fn getNearestPixelFromOriginal(xOriginal: ${s}, isDownSample: bool) -> ${s} {`+(()=>{switch(r){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 ${r} is not supported`)}})()+"}",k0=(r,i,s)=>{let u=new Array(s).fill(0).concat(new Array(s).fill(1)),c=r.length===0?u:r.slice();return i.length>0?(i.forEach((p,d)=>{u[p]=c[d],u[d+s]=c[i.length+d]}),u):c},S0=(r,i,s,u)=>{let c=[];if(s.length>0)if(u.length>0){if(r.forEach(p=>c.push(p)),Math.max(...u)>r.length)throw new Error("axes is out of bound");u.forEach((p,d)=>c[p]=s[d])}else s.forEach(p=>c.push(p));else{if(i.length===0)throw new Error("Resize requires either scales or sizes.");c=r.map((p,d)=>Math.round(p*i[d]))}return c},E0=(r,i,s)=>{let u=(()=>{switch(s.keepAspectRatioPolicy){case"not_larger":return s.axes.length>0?Math.min(...s.axes.map(p=>i[p]),Number.MAX_VALUE):Math.min(...i,Number.MAX_VALUE);case"not_smaller":return s.axes.length>0?Math.max(...s.axes.map(p=>i[p]),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 c=r.slice();return s.axes.length>0?(s.axes.forEach(p=>i[p]=u),s.axes.forEach(p=>c[p]=Math.round(r[p]*i[p]))):(i.fill(u,0,i.length),c.forEach((p,d)=>c[d]=Math.round(p*i[d]))),c},C0=(r,i,s,u,c)=>` + fn calculateOriginalIndicesFromOutputIndices(output_indices: ${r.type.indices}) -> array<${r.type.value}, ${s.length}> { + var original_indices: array<${r.type.value}, ${s.length}>; + for (var i:u32 = 0; i < ${s.length}; i++) { + var output_index = ${r.indicesGet("output_indices","i")}; + var scale = ${Dt("uniforms.scales","i",u)}; + var roi_low = ${Dt("uniforms.roi","i",c)}; + var roi_hi = ${Dt("uniforms.roi",`i + ${i.length}`,c)}; + if (scale == 1.0) { + original_indices[i] = ${r.type.value}(output_index); + } else { + var input_shape_i = ${Dt("uniforms.input_shape","i",i.length)}; + var output_shape_i = ${Dt("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; + }`,P0=(r,i,s,u,c,p,d)=>` + fn calculateInputIndicesFromOutputIndices(output_indices: ${i.type.indices}) -> ${r.type.indices} { + var input_indices: ${r.type.indices}; + for (var i:u32 = 0; i < ${u.length}; i++) { + var output_index = ${i.indicesGet("output_indices","i")}; + var input_index: u32; + var scale = ${Dt("uniforms.scales","i",c)}; + if (scale == 1.0) { + input_index = output_index; + } else { + var roi_low = ${Dt("uniforms.roi","i",p)}; + var roi_hi = ${Dt("uniforms.roi",`i + ${s.length}`,p)}; + var input_shape_i = ${Dt("uniforms.input_shape","i",s.length)}; + var output_shape_i = ${Dt("uniforms.output_shape","i",u.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); + } + } + ${r.indicesSet("input_indices","i"," input_index")} + } + return input_indices; + }`,$0=(r,i)=>` + fn checkInputIndices(input_indices: ${r.type.indices}) -> bool { + for (var i:u32 = 0; i < ${i.length}; i++) { + var input_index = ${r.indicesGet("input_indices","i")}; + if (input_index < 0 || input_index >= ${Dt("uniforms.input_shape","i",i.length)}) { + return false; + } + } + return true; + }`,_m=(r,i,s,u)=>r.rank>u?` + ${r.indicesSet("input_indices",i,"channel")}; + ${r.indicesSet("input_indices",s,"batch")}; +`:"",A0=(r,i,s,u,c)=>{let[p,d,b,T]=s.length===2?[-1,0,1,-1]:[0,2,3,1],E=r.type.value;return` + fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${E} { + var input_indices: ${r.type.indices}; + ${r.indicesSet("input_indices",d,`max(0, min(row, ${s[d]} - 1))`)}; + ${r.indicesSet("input_indices",b,`max(0, min(col, ${s[b]} - 1))`)}; + ${_m(r,T,p,2)} + return ${r.getByIndices("input_indices")}; + } + + fn bilinearInterpolation(output_indices: ${i.type.indices}) -> ${E} { + var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); + var row:${E} = originalIndices[${d}]; + var col:${E} = originalIndices[${b}]; + ${u?`if (row < 0 || row > (${s[d]} - 1) || col < 0 || col > (${s[b]} - 1)) { + return ${c}; + }`:""}; + row = max(0, min(row, ${s[d]} - 1)); + col = max(0, min(col, ${s[b]} - 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[${T}])`:"0"}; + var batch: u32 = ${s.length>2?`u32(originalIndices[${p}])`:"0"}; + var x11: ${E} = getInputValue(batch, channel, row1, col1); + var x12: ${E} = getInputValue(batch, channel, row1, col2); + var x21: ${E} = getInputValue(batch, channel, row2, col1); + var x22: ${E} = getInputValue(batch, channel, row2, col2); + var dx1: ${E} = abs(row - ${E}(row1)); + var dx2: ${E} = abs(${E}(row2) - row); + var dy1: ${E} = abs(col - ${E}(col1)); + var dy2: ${E} = abs(${E}(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); + }`},I0=(r,i,s,u,c,p,d,b,T,E)=>{let q=s.length===2,[H,v]=q?[0,1]:[2,3],ne=r.type.value,re=ce=>{let _e=ce===H?"row":"col";return` + fn ${_e}CubicInterpolation(input_indices: ${r.type.indices}, output_indices: ${i.type.indices}) -> ${ne} { + var output_index = ${i.indicesGet("output_indices",ce)}; + var originalIdx: ${ne} = getOriginalCoordinateFromResizedCoordinate(output_index, ${c[ce]}, + ${u[ce]}, ${s[ce]}, ${p[ce]}, ${p[ce]} + ${s.length}); + var fractOriginalIdx: ${ne} = originalIdx - floor(originalIdx); + var coefs = getCubicInterpolationCoefs(fractOriginalIdx); + + if (${b} && (originalIdx < 0 || originalIdx > (${s[ce]} - 1))) { + return ${T}; + } + var data: array<${ne}, 4> = array<${ne}, 4>(0.0, 0.0, 0.0, 0.0); + for (var i: i32 = -1; i < 3; i++) { + var ${_e}: ${ne} = originalIdx + ${ne}(i); + if (${_e} < 0 || ${_e} >= ${s[ce]}) { + ${E?`coefs[i + 1] = 0.0; + continue;`:b?`return ${T};`:`${_e} = max(0, min(${_e}, ${s[ce]} - 1));`}; + } + var input_indices_copy: ${r.type.indices} = input_indices; + ${r.indicesSet("input_indices_copy",ce,`u32(${_e})`)}; + data[i + 1] = ${ce===H?r.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"}; + } + return cubicInterpolation1D(data, coefs); + }`};return` + ${re(H)}; + ${re(v)}; + fn getCubicInterpolationCoefs(s: ${ne}) -> array<${ne}, 4> { + var absS = abs(s); + var coeffs: array<${ne}, 4> = array<${ne}, 4>(0.0, 0.0, 0.0, 0.0); + var oneMinusAbsS: ${ne} = 1.0 - absS; + var twoMinusAbsS: ${ne} = 2.0 - absS; + var onePlusAbsS: ${ne} = 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<${ne}, 4>, coefs: array<${ne}, 4>) -> ${ne} { + var coefsSum: ${ne} = 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}) -> ${ne} { + var input_indices: ${r.type.indices} = output_indices; + return colCubicInterpolation(input_indices, output_indices); + } + `},F0=(r,i,s,u,c)=>{let[p,d,b,T,E]=s.length===3?[-1,0,1,2,-1]:[0,2,3,4,1],q=r.type.value;return` + fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${q} { + var input_indices: ${r.type.indices}; + ${r.indicesSet("input_indices",d,`max(0, min(depth, ${s[d]} - 1))`)}; + ${r.indicesSet("input_indices",b,`max(0, min(height, ${s[b]} - 1))`)}; + ${r.indicesSet("input_indices",T,`max(0, min(width, ${s[T]} - 1))`)}; + ${_m(r,E,p,3)} + return ${r.getByIndices("input_indices")}; + } + + fn trilinearInterpolation(output_indices: ${i.type.indices}) -> ${q} { + var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); + var depth:${q} = originalIndices[${d}]; + var height:${q} = originalIndices[${b}]; + var width:${q} = originalIndices[${T}]; + ${u?`if (depth < 0 || depth > (${s[d]} - 1) || height < 0 || height > (${s[b]} - 1) || width < 0 || (width > ${s[T]} - 1)) { + return ${c}; + }`:""}; + + depth = max(0, min(depth, ${s[d]} - 1)); + height = max(0, min(height, ${s[b]} - 1)); + width = max(0, min(width, ${s[T]} - 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[${E}])`:"0"}; + var batch: u32 = ${s.length>3?`u32(originalIndices[${p}])`:"0"}; + + var x111: ${q} = getInputValue(batch, channel, depth1, height1, width1); + var x112: ${q} = getInputValue(batch, channel, depth1, height1, width2); + var x121: ${q} = getInputValue(batch, channel, depth1, height2, width1); + var x122: ${q} = getInputValue(batch, channel, depth1, height2, width2); + var x211: ${q} = getInputValue(batch, channel, depth2, height1, width1); + var x212: ${q} = getInputValue(batch, channel, depth2, height1, width2); + var x221: ${q} = getInputValue(batch, channel, depth2, height2, width1); + var x222: ${q} = getInputValue(batch, channel, depth2, height2, width2); + var dx1: ${q} = abs(depth - ${q}(depth1)); + var dx2: ${q} = abs(${q}(depth2) - depth); + var dy1: ${q} = abs(height - ${q}(height1)); + var dy2: ${q} = abs(${q}(height2) - height); + var dz1: ${q} = abs(width - ${q}(width1)); + var dz2: ${q} = abs(${q}(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); + }`},z0=(r,i,s,u,c,p)=>{let d=r.dims,b=k0(p,i.axes,d.length),T=S0(d,u,c,i.axes),E=u.slice();u.length===0&&(E=d.map((he,Fe)=>he===0?1:T[Fe]/he),i.keepAspectRatioPolicy!=="stretch"&&(T=E0(d,E,i)));let q=Vt("output",r.dataType,T.length),H=gt("input",r.dataType,d.length),v=st.size(T),ne=d.length===T.length&&d.every((he,Fe)=>he===T[Fe]),re=i.coordinateTransformMode==="tf_crop_and_resize",ce=i.extrapolationValue,_e=H.type.value,be=he=>` + ${ne?"":` + ${M0(i.coordinateTransformMode,_e)}; + ${(()=>{switch(i.mode){case"nearest":return` + ${$0(H,d)}; + ${T0(i.nearestMode,s,_e)}; + ${P0(H,q,d,T,E.length,b.length,re)}; + `;case"linear":return` + ${C0(q,d,T,E.length,b.length)}; + ${(()=>{if(d.length===2||d.length===4)return`${A0(H,q,d,re,ce)}`;if(d.length===3||d.length===5)return`${F0(H,q,d,re,ce)}`;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`${I0(H,q,d,T,E,b,i.cubicCoeffA,re,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")}})()}; + `} + ${he.registerUniform("output_size","u32").registerUniform("scales","f32",E.length).registerUniform("roi","f32",b.length).declareVariables(H,q)} + ${he.mainStart()} + ${he.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + ${ne?"output[global_idx] = input[global_idx];":` + let output_indices = ${q.offsetToIndices("global_idx")}; + var input_indices: ${H.type.indices}; + ${(()=>{switch(i.mode){case"nearest":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices); + if (checkInputIndices(input_indices)) { + output[global_idx] = ${H.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}|${E.length>0?E:""}|${c.length>0?c:""}|${b.length>0?b:""}|${ne}|${d}`,inputDependencies:["rank"]},getShaderSource:be,getRunData:()=>({outputs:[{dims:T,dataType:r.dataType}],dispatchGroup:{x:Math.ceil(v/64)},programUniforms:[{type:12,data:v},{type:1,data:E},{type:1,data:b},...Ct(d,T)]})}},O0=r=>{let i=r.customDataBuffer;return new Uint32Array(i,i.byteOffset,1)[0]},D0=(r,i)=>{let s=[],u=[],c=[],p=O0(r);if(i.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");x0(r.inputs,i,p,s,u,c),r.compute(z0(r.inputs[0],i,p,s,u,c),{inputs:[0]})},L0=r=>{let i=r.antialias,s=r.axes,u=r.coordinateTransformMode,c=r.cubicCoeffA,p=r.excludeOutside!==0,d=r.extrapolationValue,b=r.keepAspectRatioPolicy,T=r.mode,E=r.nearestMode===""?"simple":r.nearestMode;return Gt({antialias:i,axes:s,coordinateTransformMode:u,cubicCoeffA:c,excludeOutside:p,extrapolationValue:d,keepAspectRatioPolicy:b,mode:T,nearestMode:E})}}),R0,B0,N0,rx=h(()=>{Xt(),Yt(),mr(),or(),R0=(r,i)=>{let[s,u,c,p]=r,{numHeads:d,rotaryEmbeddingDim:b}=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(!st.areEqual(u.dims,[])&&!st.areEqual(u.dims,[1])&&u.dims.length!==2)throw new Error(`Input 'position_ids' is expected to have 0, 1, or 2 dimensions, got ${u.dims.length}`);if(c.dims.length!==2)throw new Error(`Input 'cos_cache' is expected to have 2 dimensions, got ${c.dims.length}`);if(p.dims.length!==2)throw new Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${p.dims.length}`);if(!st.areEqual(c.dims,p.dims))throw new Error("Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape");if(b>0&&d===0)throw new Error("num_heads must be provided if rotary_embedding_dim is specified");let T=s.dims[0],E=s.dims[s.dims.length-2],q=c.dims[0],H=st.sizeFromDimension(s.dims,1)/E,v=b===0?c.dims[1]*2:H/d;if(b>v)throw new Error("rotary_embedding_dim must be less than or equal to head_size");if(u.dims.length===2){if(T!==u.dims[0])throw new Error(`Input 'position_ids' dimension 0 should be of size batch_size, got ${u.dims[0]}`);if(E!==u.dims[1])throw new Error(`Input 'position_ids' dimension 1 should be of size sequence_length, got ${u.dims[1]}`)}if(v/2!==c.dims[1]&&b/2!==c.dims[1])throw new Error(`Input 'cos_cache' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${c.dims[1]}`);if(E>q)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported")},B0=(r,i)=>{let{interleaved:s,numHeads:u,rotaryEmbeddingDim:c,scale:p}=i,d=r[0].dims[0],b=st.sizeFromDimension(r[0].dims,1),T=r[0].dims[r[0].dims.length-2],E=b/T,q=r[2].dims[1],H=c===0?q*2:E/u,v=new Array(d,T,E/H,H-q),ne=st.computeStrides(v),re=[{type:1,data:p},{type:12,data:v},{type:12,data:ne},...r[0].dims.length===3?new Array({type:12,data:[b,E,H,1]}):[],...r[0].dims.length===4?new Array({type:12,data:[b,H,T*H,1]}):[],...Ct(r[0].dims,r[1].dims,r[2].dims,r[3].dims,r[0].dims)],ce=_e=>{let be=gt("input",r[0].dataType,r[0].dims.length),he=gt("position_ids",r[1].dataType,r[1].dims.length),Fe=gt("cos_cache",r[2].dataType,r[2].dims.length),xe=gt("sin_cache",r[3].dataType,r[3].dims.length),Ie=Vt("output",r[0].dataType,r[0].dims.length);return _e.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:v.length},{name:"global_strides",type:"u32",length:ne.length},{name:"input_output_strides",type:"u32",length:ne.length}]),` + ${_e.declareVariables(be,he,Fe,xe,Ie)} + + ${_e.mainStart(Bn)} + let half_rotary_emb_dim = uniforms.${Fe.name}_shape[1]; + let bsnh = global_idx / uniforms.global_strides % uniforms.global_shape; + let size = uniforms.global_shape[0] * uniforms.global_strides[0]; + ${_e.guardAgainstOutOfBoundsWorkgroupSizes("size")} + + if (bsnh[3] < half_rotary_emb_dim) { + let position_ids_idx = + ${he.broadcastedIndicesToOffset("bsnh.xy",Vt("",he.type.tensor,2))}; + let position_id = + u32(${he.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 = ${be.getByOffset("i")} * ${Fe.get("position_id","bsnh[3]")} - + ${be.getByOffset("j")} * ${xe.get("position_id","bsnh[3]")}; + ${Ie.setByOffset("i","re")} + let im = ${be.getByOffset("i")} * ${xe.get("position_id","bsnh[3]")} + + ${be.getByOffset("j")} * ${Fe.get("position_id","bsnh[3]")}; + ${Ie.setByOffset("j","im")} + } else { + let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim; + ${Ie.setByOffset("k",be.getByOffset("k"))} + } + }`};return{name:"RotaryEmbedding",shaderCache:{hint:Gt({interleaved:s}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:ce,getRunData:()=>({outputs:[{dims:r[0].dims,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(st.size(v)/Bn)},programUniforms:re})}},N0=(r,i)=>{R0(r.inputs,i),r.compute(B0(r.inputs,i))}}),j0,U0,V0,nx=h(()=>{Xt(),Yt(),or(),j0=r=>{if(!r||r.length<3)throw new Error("layerNorm requires at least 3 inputs.");let i=r[0],s=r[1],u=r[2];if(i.dataType!==s.dataType||i.dataType!==u.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 c=i.dims[i.dims.length-1],p=i.dims[i.dims.length-2];if(s.dims[s.dims.length-1]!==c)throw new Error("Skip must have the same hidden size as input");if(s.dims[s.dims.length-2]!==p)throw new Error("Skip must have the same sequence length as input");if(u.dims.length!==1)throw new Error("Gamma must be 1D");if(u.dims[u.dims.length-1]!==c)throw new Error("Gamma must have the same hidden size as input");if(r.length>3){let d=r[3];if(d.dims.length!==1)throw new Error("Beta must be 1D");if(d.dims[d.dims.length-1]!==c)throw new Error("Beta must have the same hidden size as input")}if(r.length>4){let d=r[4];if(d.dims.length!==1)throw new Error("Bias must be 1D");if(d.dims[d.dims.length-1]!==c)throw new Error("Bias must have the same hidden size as input")}},U0=(r,i,s,u)=>{let c=i.simplified,p=r[0].dims,d=st.size(p),b=p,T=d,E=p.slice(-1)[0],q=u?p.slice(0,-1).concat(1):[],H=!c&&r.length>3,v=r.length>4,ne=u&&s>1,re=u&&s>2,ce=s>3,_e=64,be=wr(E),he=[{type:12,data:T},{type:12,data:be},{type:12,data:E},{type:1,data:i.epsilon}],Fe=Ie=>{let ct=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],et=[gt("x",r[0].dataType,r[0].dims,be),gt("skip",r[1].dataType,r[1].dims,be),gt("gamma",r[2].dataType,r[2].dims,be)];H&&et.push(gt("beta",r[3].dataType,r[3].dims,be)),v&&et.push(gt("bias",r[4].dataType,r[4].dims,be)),et.push(Vt("output",r[0].dataType,b,be)),ne&&et.push(Vt("mean_output",1,q)),re&&et.push(Vt("inv_std_output",1,q)),ce&&et.push(Vt("input_skip_bias_sum",r[0].dataType,b,be));let vt=Tr(r[0].dataType),Ft=Tr(1,be);return` + + ${Ie.registerUniforms(ct).declareVariables(...et)} + var sum_shared : array<${Ft}, ${_e}>; + var sum_squared_shared : array<${Ft}, ${_e}>; + + ${Ie.mainStart([_e,1,1])} + let ix = local_id.x; + let iy = global_id.x / ${_e}; + + let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components; + var stride = hidden_size_vectorized / ${_e}; + let offset = ix * stride + iy * hidden_size_vectorized; + let offset1d = stride * ix; + if (ix == ${_e-1}) { + stride = hidden_size_vectorized - stride * ix; + } + for (var i: u32 = 0; i < stride; i++) { + let skip_value = skip[offset + i]; + let bias_value = ${v?"bias[offset1d + i]":vt+"(0.0)"}; + let input_value = x[offset + i]; + let value = input_value + skip_value + bias_value; + ${ce?"input_skip_bias_sum[offset + i] = value;":""} + output[offset + i] = value; + let f32_value = ${Gr(vt,be,"value")}; + sum_shared[ix] += f32_value; + sum_squared_shared[ix] += f32_value * f32_value; + } + workgroupBarrier(); + + var reduce_size : u32 = ${_e}; + 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 = ${Nn("sum",be)} / f32(uniforms.hidden_size); + let inv_std_dev = inverseSqrt(${Nn("square_sum",be)} / f32(uniforms.hidden_size) ${c?"":"- mean * mean"} + uniforms.epsilon); + ${ne?"mean_output[global_idx] = mean;":""} + ${re?"inv_std_output[global_idx] = inv_std_dev;":""} + + for (var i: u32 = 0; i < stride; i++) { + output[offset + i] = (output[offset + i] ${c?"":`- ${vt}(mean)`}) * + ${vt}(inv_std_dev) * gamma[offset1d + i] + ${H?"+ beta[offset1d + i]":""}; + } + }`},xe=[{dims:b,dataType:r[0].dataType}];return s>1&&xe.push({dims:q,dataType:1}),s>2&&xe.push({dims:q,dataType:1}),s>3&&xe.push({dims:p,dataType:r[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${be};${ne};${re};${ce}`,inputDependencies:r.map((Ie,ct)=>"type")},getShaderSource:Fe,getRunData:()=>({outputs:xe,dispatchGroup:{x:Math.ceil(T/E)},programUniforms:he})}},V0=(r,i)=>{j0(r.inputs);let s=[0];r.outputCount>1&&s.push(-3),r.outputCount>2&&s.push(-3),r.outputCount>3&&s.push(3),r.compute(U0(r.inputs,i,r.outputCount,!1),{outputs:s})}}),W0,rf,G0,ym,q0,H0,K0,Q0,ix=h(()=>{Xt(),Yt(),mr(),or(),W0=(r,i)=>{if(!r||r.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");r.slice(1).forEach((s,u)=>{if(r[u+1].dataType!==6&&r[u+1].dataType!==7)throw new Error(`Input ${u} must be an array of int32 or int64`)})},rf=(r,i)=>{let s=[];if(r.length>i)if(r[i].dataType===7)r[i].getBigInt64Array().forEach(u=>s.push(Number(u)));else if(r[i].dataType===6)r[i].getInt32Array().forEach(u=>s.push(Number(u)));else throw new Error(`Input ${i} must be an array of int32 or int64`);return s},G0=(r,i)=>{if(r.length>1){let s=rf(r,1),u=rf(r,2),c=rf(r,3);return c.length===0&&(c=[...Array(r[0].dims.length).keys()]),Gt({starts:s,ends:u,axes:c})}else return i},ym=(r,i,s,u,c)=>{let p=r;return r<0&&(p+=s[u[i]]),c[i]<0?Math.max(0,Math.min(p,s[u[i]]-1)):Math.max(0,Math.min(p,s[u[i]]))},q0=(r,i,s)=>`fn calculateInputIndices(output_indices: ${i.type.indices}) -> ${r.type.indices} { + var input_indices: ${r.type.indices}; + var carry = 0u; + for (var i = ${s.length}; i >= 0; i--) { + let input_shape_i = ${Dt("uniforms.input_shape","i",s.length)}; + let steps_i = ${Dt("uniforms.steps","i",s.length)}; + let signs_i = ${Dt("uniforms.signs","i",s.length)}; + let starts_i = ${Dt("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; + } + ${r.indicesSet("input_indices","i","input_index")}; + } + return input_indices; + }`,H0=(r,i)=>{let s=r[0].dims,u=st.size(s),c=i.axes.length>0?st.normalizeAxes(i.axes,s.length):[...Array(s.length).keys()],p=rf(r,4);p.forEach(be=>be!==0||(()=>{throw new Error("step cannot be 0")})),p.length===0&&(p=Array(c.length).fill(1));let d=i.starts.map((be,he)=>ym(be,he,s,c,p)),b=i.ends.map((be,he)=>ym(be,he,s,c,p));if(c.length!==d.length||c.length!==b.length)throw new Error("start, ends and axes should have the same number of elements");if(c.length!==s.length)for(let be=0;beMath.sign(be));p.forEach((be,he,Fe)=>{if(be<0){let xe=(b[he]-d[he])/be,Ie=d[he],ct=Ie+xe*p[he];d[he]=ct,b[he]=Ie,Fe[he]=-be}});let E=s.slice(0);c.forEach((be,he)=>{E[be]=Math.ceil((b[be]-d[be])/p[be])});let q={dims:E,dataType:r[0].dataType},H=Vt("output",r[0].dataType,E.length),v=gt("input",r[0].dataType,r[0].dims.length),ne=st.size(E),re=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:d.length},{name:"signs",type:"i32",length:T.length},{name:"steps",type:"u32",length:p.length}],ce=[{type:12,data:ne},{type:12,data:d},{type:6,data:T},{type:12,data:p},...Ct(r[0].dims,E)],_e=be=>` + ${be.registerUniforms(re).declareVariables(v,H)} + ${q0(v,H,s)} + ${be.mainStart()} + ${be.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + let output_indices = ${H.offsetToIndices("global_idx")}; + let input_indices = calculateInputIndices(output_indices); + ${H.setByOffset("global_idx",v.getByIndices("input_indices"))} + }`;return{name:"Slice",shaderCache:{hint:`${T.length}_${d.length}_${p.length}`,inputDependencies:["rank"]},getShaderSource:_e,getRunData:()=>({outputs:[q],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:ce})}},K0=(r,i)=>{W0(r.inputs,i);let s=G0(r.inputs,i);r.compute(H0(r.inputs,s),{inputs:[0]})},Q0=r=>{let i=r.starts,s=r.ends,u=r.axes;return Gt({starts:i,ends:s,axes:u})}}),X0,Y0,Z0,J0,ox=h(()=>{Xt(),Yt(),mr(),or(),X0=r=>{if(!r||r.length!==1)throw new Error("Softmax op requires 1 input.")},Y0=(r,i)=>{let s=r.dims,u=st.size(s),c=64,p=i.axis;if(p<0&&(p=s.length+p),pbe===4?`max(max(${_e}.x, ${_e}.y), max(${_e}.z, ${_e}.w))`:be===2?`max(${_e}.x, ${_e}.y)`:be===3?`max(max(${_e}.x, ${_e}.y), ${_e}.z)`:_e,H=gt("x",r.dataType,r.dims,T),v=Vt("result",r.dataType,r.dims,T),ne=H.type.value,re=Tr(r.dataType)==="f32"?`var threadMax = ${ne}(-3.402823e+38f);`:`var threadMax = ${ne}(-65504.0h);`,ce=_e=>` + var rowMaxShared : ${ne}; + var rowSumShared : ${ne}; + var threadShared : array<${ne}, ${c}>; + + fn getValue(row: i32, col: i32, row_stride: i32) -> ${ne} { + let index = row * row_stride + col; + return x[index]; + } + + fn setValue(row: i32, col: i32, row_stride: i32, value: ${ne}) { + let index = row * row_stride + col; + result[index] = value; + } + ${_e.registerUniform("packedCols","i32").declareVariables(H,v)} + ${_e.mainStart()} + let gindex = i32(global_idx); + let lindex = i32(local_idx); + const wg = ${c}; + let row = gindex / wg; + let cols = uniforms.packedCols; + let row_stride : i32 = uniforms.packedCols; + + // find the rows max + ${re} + 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 = ${ne}(${q("threadShared[0]",T)}); + } + workgroupBarrier(); + + // find the rows sum + var threadSum = ${ne}(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 = ${ne}(${Nn("threadShared[0]",T)}); + } + 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:`${T}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:s,dataType:r.dataType}],dispatchGroup:{x:b},programUniforms:[{type:6,data:E}]}),getShaderSource:ce}},Z0=(r,i)=>{X0(r.inputs),r.compute(Y0(r.inputs[0],i))},J0=r=>Gt({axis:r.axis})}),ey,ty,ry,ny,iy,oy,sy,sx=h(()=>{Xt(),Yt(),mr(),or(),ey=r=>{if(!r||r.length<1)throw new Error("too few inputs")},ty=(r,i)=>{let s=[],u=i.numOutputs;return r[1].dims[0]>0&&(r[1].getBigInt64Array().forEach(c=>s.push(Number(c))),u=s.length),Gt({numOutputs:u,axis:i.axis,splitSizes:s})},ry=r=>` +fn calculateOutputIndex(index: u32) -> u32 { + for (var i: u32 = 0u; i < ${r}u; i += 1u ) { + if (index < ${Dt("uniforms.size_in_split_axis","i",r)}) { + return i; + } + } + return ${r}u; +}`,ny=r=>{let i=r.length,s=[];for(let u=0;u{let s=r[0].dims,u=st.size(s),c=r[0].dataType,p=st.normalizeAxis(i.axis,s.length),d=new Array(i.numOutputs),b=gt("input",c,s.length),T=new Array(i.numOutputs),E=[],q=[],H=0,v=[{type:12,data:u}];for(let re=0;re` + ${re.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",T.length).declareVariables(b,...d)} + ${ry(T.length)} + ${ny(d)} + + ${re.mainStart()} + ${re.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")} + + var indices = ${b.offsetToIndices("global_idx")}; + var index = ${b.indicesGet("indices",p)}; + let output_number = calculateOutputIndex(index); + if (output_number != 0) { + index -= ${Dt("uniforms.size_in_split_axis","output_number - 1u",T.length)}; + ${b.indicesSet("indices",p,"index")}; + } + writeBufferData(output_number, indices, global_idx); + }`;return{name:"Split",shaderCache:{hint:i.cacheKey,inputDependencies:["rank"]},getShaderSource:ne,getRunData:()=>({outputs:E,dispatchGroup:{x:Math.ceil(u/64)},programUniforms:v})}},oy=(r,i)=>{ey(r.inputs);let s=r.inputs.length===1?i:ty(r.inputs,i);r.compute(iy(r.inputs,s),{inputs:[0]})},sy=r=>{let i=r.axis,s=r.splitSizes,u=r.numOutputs<0?s.length:r.numOutputs;if(u!==s.length)throw new Error("numOutputs and splitSizes lengh must be equal");return Gt({axis:i,numOutputs:u,splitSizes:s})}}),ay,ly,uy,ax=h(()=>{Xt(),Yt(),or(),ay=(r,i,s,u,c)=>{let p=Vt("output_data",c,s.length,4),d=gt("a_data",i[1].dataType,i[1].dims.length,4),b=gt("b_data",i[2].dataType,i[2].dims.length,4),T=gt("c_data",i[0].dataType,i[0].dims.length,4),E,q=(H,v,ne)=>`select(${v}, ${H}, ${ne})`;if(!u)E=p.setByOffset("global_idx",q(d.getByOffset("global_idx"),b.getByOffset("global_idx"),T.getByOffset("global_idx")));else{let H=(v,ne,re="")=>{let ce=`a_data[index_a${ne}][component_a${ne}]`,_e=`b_data[index_b${ne}][component_b${ne}]`,be=`bool(c_data[index_c${ne}] & (0xffu << (component_c${ne} * 8)))`;return` + let output_indices${ne} = ${p.offsetToIndices(`global_idx * 4u + ${ne}u`)}; + let offset_a${ne} = ${d.broadcastedIndicesToOffset(`output_indices${ne}`,p)}; + let offset_b${ne} = ${b.broadcastedIndicesToOffset(`output_indices${ne}`,p)}; + let offset_c${ne} = ${T.broadcastedIndicesToOffset(`output_indices${ne}`,p)}; + let index_a${ne} = offset_a${ne} / 4u; + let index_b${ne} = offset_b${ne} / 4u; + let index_c${ne} = offset_c${ne} / 4u; + let component_a${ne} = offset_a${ne} % 4u; + let component_b${ne} = offset_b${ne} % 4u; + let component_c${ne} = offset_c${ne} % 4u; + ${v}[${ne}] = ${re}(${q(ce,_e,be)}); + `};c===9?E=` + var data = vec4(0); + ${H("data",0,"u32")} + ${H("data",1,"u32")} + ${H("data",2,"u32")} + ${H("data",3,"u32")} + output_data[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:E=` + ${H("output_data[global_idx]",0)} + ${H("output_data[global_idx]",1)} + ${H("output_data[global_idx]",2)} + ${H("output_data[global_idx]",3)} + `}return` + ${r.registerUniform("vec_size","u32").declareVariables(T,d,b,p)} + ${r.mainStart()} + ${r.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${E} + }`},ly=r=>{let i=r[1].dims,s=r[2].dims,u=r[0].dims,c=r[1].dataType,p=!(st.areEqual(i,s)&&st.areEqual(s,u)),d=i,b=st.size(i);if(p){let E=pn.calcShape(pn.calcShape(i,s,!1),u,!1);if(!E)throw new Error("Can't perform where op on the given tensors");d=E,b=st.size(d)}let T=Math.ceil(b/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:E=>ay(E,r,d,p,c),getRunData:()=>({outputs:[{dims:d,dataType:c}],dispatchGroup:{x:Math.ceil(b/64/4)},programUniforms:[{type:12,data:T},...Ct(u,i,s,d)]})}},uy=r=>{r.compute(ly(r.inputs))}}),cy,lx=h(()=>{tp(),Is(),Yu(),rp(),$c(),np(),ip(),sd(),pm(),cp(),dp(),mp(),hm(),_p(),yp(),wp(),Od(),bp(),mm(),yn(),rl(),Mp(),Nd(),cr(),Yo(),J2(),ex(),Sa(),tx(),rx(),nx(),ix(),ox(),sx(),Wd(),_o(),Ua(),ax(),cy=new Map([["Abs",[tc]],["Acos",[rc]],["Acosh",[Pa]],["Add",[Fc]],["ArgMax",[ju,As]],["ArgMin",[Nu,As]],["Asin",[nc]],["Asinh",[ic]],["Atan",[$a]],["Atanh",[oc]],["Attention",[qu]],["AveragePool",[Ei,An]],["BatchNormalization",[Xu]],["BiasAdd",[Ca]],["BiasSplitGelu",[Pc]],["Cast",[Fs,sc]],["Ceil",[uc]],["Clip",[lc]],["Concat",[Ni,Wc]],["Conv",[qo,il]],["ConvTranspose",[up,dd]],["Cos",[Aa]],["Cosh",[cc]],["CumSum",[fl,hd]],["DepthToSpace",[hl,_d]],["DequantizeLinear",[Sp,tf]],["Div",[zc]],["Einsum",[wd,vd]],["Elu",[dc,wo]],["Equal",[Wa]],["Erf",[fc]],["Exp",[Ia]],["Expand",[_l]],["FastGelu",[Md]],["Floor",[pc]],["FusedConv",[qo,il]],["Gather",[Ed,Sd]],["GatherElements",[Ad,$d]],["Gelu",[hc]],["Gemm",[vp,zd]],["GlobalAveragePool",[bn,ln]],["GlobalMaxPool",[pi,gm]],["Greater",[Rc]],["GreaterOrEqual",[Nc]],["GroupQueryAttention",[Kd,qd]],["HardSigmoid",[Oa,wc]],["InstanceNormalization",[Zd]],["LayerNormalization",[dn]],["LeakyRelu",[mc,wo]],["Less",[Bc]],["LessOrEqual",[Ga]],["Log",[ja]],["MatMul",[nd]],["MatMulNBits",[xp,ef]],["MaxPool",[Gs,Ml]],["Mul",[Oc]],["MultiHeadAttention",[Bd,Ld]],["Neg",[gc]],["Not",[Fa]],["Pad",[Wt]],["Pow",[Dc]],["QuickGelu",[Ec,wo]],["Range",[w0]],["Reciprocal",[_c]],["ReduceMin",[Ta]],["ReduceMean",[Fu]],["ReduceMax",[Du]],["ReduceSum",[Ru]],["ReduceProd",[Lu]],["ReduceL1",[zu]],["ReduceL2",[Ma]],["ReduceLogSum",[Bu]],["ReduceLogSumExp",[Ou]],["ReduceSumSquare",[ka]],["Relu",[za]],["Resize",[D0,L0]],["RotaryEmbedding",[N0]],["Sigmoid",[yc]],["Sin",[vc]],["Sinh",[bc]],["Slice",[K0,Q0]],["SkipLayerNormalization",[V0]],["Split",[oy,sy]],["Sqrt",[Da]],["Softmax",[Z0,J0]],["Sub",[Lc]],["Tan",[xc]],["Tanh",[Ra]],["ThresholdedRelu",[Tc,wo]],["Tile",[Vd]],["Transpose",[uu,ha]],["Where",[uy]]])}),dy,ux=h(()=>{Z(),Rn(),or(),dy=class{constructor(r){this.backend=r,this.repo=new Map,this.attributesBound=!1}getArtifact(r){return this.repo.get(r)}setArtifact(r,i){this.repo.set(r,i)}run(r,i,s,u,c){tt(r.programInfo.name);let p=this.backend.device,d=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let b=[];for(let E of i)b.push({binding:b.length,resource:{buffer:E.buffer}});for(let E of s)b.push({binding:b.length,resource:{buffer:E.buffer}});c&&b.push({binding:b.length,resource:c});let T=p.createBindGroup({layout:r.computePipeline.getBindGroupLayout(0),entries:b,label:r.programInfo.name});if(this.backend.sessionStatus==="capturing"){let E={kernelId:this.backend.currentKernelId,computePipeline:r.computePipeline,bindGroup:T,dispatchGroup:u};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(E)}d.setPipeline(r.computePipeline),d.setBindGroup(0,T),d.dispatchWorkgroups(...u),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(),A(r.programInfo.name)}dispose(){}build(r,i){tt(r.name);let s=this.backend.device,u=[];s.features.has("shader-f16")&&u.push("enable f16;");let c=su(i,this.backend.device.limits),p=r.getShaderSource(c),d=`${u.join(` +`)} +${c.additionalImplementations} +${p}`,b=s.createShaderModule({code:d,label:r.name});Br("verbose",()=>`[WebGPU] ${r.name} shader code: ${d}`);let T=s.createComputePipeline({compute:{module:b,entryPoint:"main"},layout:"auto",label:r.name});return A(r.name),{programInfo:r,computePipeline:T,uniformVariablesInfo:c.variablesInfo}}normalizeDispatchGroupSize(r){let i=typeof r=="number"?r:r.x,s=typeof r=="number"?1:r.y||1,u=typeof r=="number"?1:r.z||1,c=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(i<=c&&s<=c&&u<=c)return[i,s,u];let p=i*s*u,d=Math.ceil(Math.sqrt(p));if(d>c){if(d=Math.ceil(Math.cbrt(p)),d>c)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[d,d,d]}else return[d,d,1]}}}),fy,py,hy,my,cx=h(()=>{Z(),Xt(),Rn(),W(),Pr(),lx(),ux(),fy=(r,i)=>{if(i.length!==r.length)throw new Error(`inputDependencies length ${i.length} is not equal to inputTensors length ${r.length}.`);let s=[];for(let u=0;u{var c,p;let u=r.name;return(c=r.shaderCache)!=null&&c.hint&&(u+="["+r.shaderCache.hint+"]"),u+=":"+s+`:${fy(i,((p=r.shaderCache)==null?void 0:p.inputDependencies)??new Array(i.length).fill("dims"))}`,u},hy=class{constructor(r){r&&(this.architecture=r.architecture,this.vendor=r.vendor)}isArchitecture(r){return this.architecture===r}isVendor(r){return this.vendor===r}},my=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 r=this.kernelCustomData.get(this.currentKernelId);return r||(r={},this.kernelCustomData.set(this.currentKernelId,r)),r}async initialize(r,i){this.env=r;let s=[],u={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(u),this.adapterInfo=new hy(i.info||await i.requestAdapterInfo()),this.gpuDataManager=Zt(this),this.programManager=new dy(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,mo(r.logLevel,!!r.debug),this.device.onuncapturederror=c=>{c.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${c.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 r=this.getCommandEncoder(),i={};this.queryType==="at-passes"&&(i.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=r.beginComputePass(i)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;tt(),this.endComputePass();let r;this.queryType!=="none"&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),r=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(r,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,r,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!=="none"&&r.mapAsync(GPUMapMode.READ).then(()=>{var u;let i=new BigUint64Array(r.getMappedRange()),s=this.pendingQueries.get(r);for(let c=0;c"u"&&(this.queryTimeBase=ne);let ce=Number(ne-this.queryTimeBase),_e=Number(re-this.queryTimeBase);if(!Number.isSafeInteger(ce)||!Number.isSafeInteger(_e))throw new RangeError("incorrect timestamp range");if((u=this.env.webgpu.profiling)!=null&&u.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:H.map(be=>({dims:be.dims,dataType:di(be.dataType)})),outputsMetadata:v.map(be=>({dims:be.dims,dataType:di(be.dataType)})),kernelId:d,kernelType:T,kernelName:E,programName:q,startTime:ce,endTime:_e});else{let be="";H.forEach((Fe,xe)=>{be+=`input[${xe}]: [${Fe.dims}] | ${di(Fe.dataType)}, `});let he="";v.forEach((Fe,xe)=>{he+=`output[${xe}]: [${Fe.dims}] | ${di(Fe.dataType)}, `}),console.log(`[profiling] kernel "${d}|${T}|${E}|${q}" ${be}${he}execution time: ${_e-ce} ns`)}je("GPU",`${q}::${ne}::${re}`)}r.unmap(),this.pendingQueries.delete(r)}),A()}run(r,i,s,u,c,p){tt(r.name);let d=[];for(let he=0;heFe):s;if(q.length!==b.length)throw new Error(`Output size ${q.length} must be equal to ${b.length}.`);let H=[],v=[];for(let he=0;he=p)throw new Error(`Invalid output index: ${q[he]}`);if(q[he]===-3)continue;let Fe=q[he]===-1,xe=q[he]===-2,Ie=Fe||xe?c(b[he].dataType,b[he].dims):u(q[he],b[he].dataType,b[he].dims);if(H.push(Ie),Ie.data===0)continue;let ct=this.gpuDataManager.get(Ie.data);if(!ct)throw new Error(`no GPU data for output: ${Ie.data}`);if(Fe&&this.temporaryData.push(ct),xe){let et=this.kernelPersistentData.get(this.currentKernelId);et||(et=[],this.kernelPersistentData.set(this.currentKernelId,et)),et.push(ct)}v.push(ct)}if(d.length!==i.length||v.length!==H.length){if(v.length===0)return A(r.name),H;throw new Error(`Program ${r.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let ne;if(E){let he=0,Fe=[];E.forEach(et=>{let vt=typeof et.data=="number"?[et.data]:et.data;if(vt.length===0)return;let Ft=et.type===10?2:4,Lt,pr;et.type===10?(pr=vt.length>4?16:vt.length>2?8:vt.length*Ft,Lt=vt.length>4?16:Ft*vt.length):(pr=vt.length<=2?vt.length*Ft:16,Lt=16),he=Math.ceil(he/pr)*pr,Fe.push(he);let ar=et.type===10?8:4;he+=vt.length>4?Math.ceil(vt.length/ar)*Lt:vt.length*Ft});let xe=16;he=Math.ceil(he/xe)*xe;let Ie=new ArrayBuffer(he);E.forEach((et,vt)=>{let Ft=Fe[vt],Lt=typeof et.data=="number"?[et.data]:et.data;if(et.type===6)new Int32Array(Ie,Ft,Lt.length).set(Lt);else if(et.type===12)new Uint32Array(Ie,Ft,Lt.length).set(Lt);else if(et.type===10)new Uint16Array(Ie,Ft,Lt.length).set(Lt);else if(et.type===1)new Float32Array(Ie,Ft,Lt.length).set(Lt);else throw new Error(`Unsupported uniform type: ${di(et.type)}`)});let ct=this.gpuDataManager.create(he,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(ct.buffer,0,Ie,0,he),this.gpuDataManager.release(ct.id),ne={offset:0,size:he,buffer:ct.buffer}}let re=this.programManager.normalizeDispatchGroupSize(T),ce=re[1]===1&&re[2]===1,_e=py(r,i,ce),be=this.programManager.getArtifact(_e);if(be||(be=this.programManager.build(r,re),this.programManager.setArtifact(_e,be),Br("info",()=>`[artifact] key: ${_e}, programName: ${r.name}`)),E&&be.uniformVariablesInfo){if(E.length!==be.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${be.uniformVariablesInfo.length}, got ${E.length} in program "${be.programInfo.name}".`);for(let he=0;he`[ProgramManager] run "${r.name}" (key=${_e}) with ${re[0]}x${re[1]}x${re[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let he={kernelId:this.currentKernelId,programName:be.programInfo.name,inputTensorViews:i,outputTensorViews:H};this.pendingKernels.push(he),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(he)}return this.programManager.run(be,d,v,re,ne),A(r.name),H}upload(r,i){this.gpuDataManager.upload(r,i)}memcpy(r,i){this.gpuDataManager.memcpy(r,i)}async download(r,i){await this.gpuDataManager.download(r,i)}alloc(r){return this.gpuDataManager.create(r).id}free(r){return this.gpuDataManager.release(r)}createKernel(r,i,s,u){let c=cy.get(r);if(!c)throw new Error(`kernel not implemented: ${r}`);let p={kernelType:r,kernelName:u,kernelEntry:c[0],attributes:[c[1],s]};this.kernels.set(i,p)}releaseKernel(r){let i=this.kernelPersistentData.get(r);if(i){for(let s of i)this.gpuDataManager.release(s.id);this.kernelPersistentData.delete(r)}this.kernelCustomData.delete(r),this.kernels.delete(r)}computeKernel(r,i,s){let u=this.kernels.get(r);if(!u)throw new Error(`kernel not created: ${r}`);let c=u.kernelType,p=u.kernelName,d=u.kernelEntry,b=u.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${c}] ${p}" is not allowed to be called recursively`);this.currentKernelId=r,b[0]&&(b[1]=b[0](b[1]),b[0]=void 0),Br("info",()=>`[WebGPU] Start to run kernel "[${c}] ${p}"...`);let T=this.env.debug;this.temporaryData=[];try{return T&&this.device.pushErrorScope("validation"),d(i,b[1]),0}catch(E){return s.push(Promise.resolve(`[WebGPU] Kernel "[${c}] ${p}" failed. ${E}`)),1}finally{T&&s.push(this.device.popErrorScope().then(E=>E?`GPU validation error for kernel "[${c}] ${p}": ${E.message}`:null));for(let E of this.temporaryData)this.gpuDataManager.release(E.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(r,i,s,u){let c=this.sessionExternalDataMapping.get(r);c||(c=new Map,this.sessionExternalDataMapping.set(r,c));let p=c.get(i),d=this.gpuDataManager.registerExternalBuffer(s,u,p==null?void 0:p[1]);return c.set(i,[d,s]),d}unregisterBuffers(r){let i=this.sessionExternalDataMapping.get(r);i&&(i.forEach(s=>this.gpuDataManager.unregisterExternalBuffer(s[1])),this.sessionExternalDataMapping.delete(r))}getBuffer(r){let i=this.gpuDataManager.get(r);if(!i)throw new Error(`no GPU data for buffer: ${r}`);return i.buffer}createDownloader(r,i,s){return async()=>{let u=await Tt(this,r,i);return Ue(u.buffer,s)}}writeTimestamp(r){this.queryType==="inside-passes"&&this.computePassEncoder.writeTimestamp(this.querySet,r)}setQueryType(){var r;this.queryType="none",(((r=this.env.webgpu.profiling)==null?void 0:r.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(){Br("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(){Br("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){Br("info","replay"),this.sessionStatus="replaying";let r=this.capturedCommandList.get(this.currentSessionId),i=this.capturedPendingKernels.get(this.currentSessionId),s=r.length;this.pendingKernels=[];for(let u=0;u=this.maxDispatchNumber||this.queryType==="at-passes")&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus="default"}onReleaseSession(r){this.unregisterBuffers(r),this.capturedCommandList.has(r)&&this.capturedCommandList.delete(r),this.capturedPendingKernels.has(r)&&this.capturedPendingKernels.delete(r),this.gpuDataManager.onReleaseSession(r)}onRunStart(r){this.currentSessionId=r,this.setQueryType()}}}),gy={};g(gy,{init:()=>yy});var Ep,_y,yy,dx=h(()=>{Xt(),cx(),Rn(),Yt(),Ep=class X2{constructor(i,s,u,c){this.module=i,this.dataType=s,this.data=u,this.dims=c}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let i=st.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=st.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=st.size(this.dims);return i===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,i)}reshape(i){if(st.size(i)!==st.size(this.dims))throw new Error("Invalid new shape");return new X2(this.module,this.dataType,this.data,i)}},_y=class{constructor(r,i,s){this.module=r,this.backend=i,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=i.adapterInfo;let u=r.HEAPU32,c=s>>>2;this.opKernelContext=u[c++];let p=u[c++];this.outputCount=u[c++],this.customDataOffset=u[c++],this.customDataSize=u[c++];let d=[];for(let b=0;btypeof b=="number"?this.inputs[b]:b))??this.inputs,u=(i==null?void 0:i.outputs)??[],c=(b,T,E)=>new Ep(this.module,T,this.output(b,E),E),p=(b,T)=>{let E=Mi(b,T);if(!E)throw new Error(`Unsupported data type: ${b}`);let q=E>0?this.backend.gpuDataManager.create(E).id:0;return new Ep(this.module,b,q,T)};return this.backend.run(r,s,u,c,p,this.outputCount)}output(r,i){let s=this.module.stackSave();try{let u=this.module.stackAlloc((1+i.length)*4),c=u>>2;this.module.HEAPU32[c++]=i.length;for(let p=0;p{let c=i.jsepInit;if(!c)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(r==="webgpu"){let p=new my;await p.initialize(s,u),c("webgpu",[p,d=>p.alloc(d),d=>p.free(d),(d,b,T,E=!1)=>{if(E)Br("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${d}, dst=${b}, size=${T}`),p.memcpy(d,b);else{Br("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${d}, gpuDataId=${b}, size=${T}`);let q=i.HEAPU8.subarray(d>>>0,(d>>>0)+T);p.upload(b,q)}},async(d,b,T)=>{Br("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${d}, dataOffset=${b}, size=${T}`),await p.download(d,()=>i.HEAPU8.subarray(b>>>0,(b>>>0)+T))},(d,b,T)=>p.createKernel(d,b,T,i.UTF8ToString(i._JsepGetNodeName(b))),d=>p.releaseKernel(d),(d,b,T,E)=>{Br("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${T}, kernel=${d}, contextDataOffset=${b}`);let q=new _y(i,p,b);return p.computeKernel(d,q,E)},()=>p.captureBegin(),()=>p.captureEnd(),()=>p.replay()])}else c("webnn")}}),wy,wm,vm,Zo,vy,Cp,bm,xm,Mm,Tm,km,Sm,by=h(()=>{ks(),Ss(),Xt(),mn(),Ri(),Bo(),wy=(r,i)=>{Nr()._OrtInit(r,i)!==0&&Fr("Can't initialize onnxruntime.")},wm=async r=>{wy(r.wasm.numThreads,Yi(r.logLevel))},vm=async(r,i)=>{{let s=(dx(),w(gy)).init;if(i==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");let u=r.webgpu.adapter;if(u){if(typeof u.limits!="object"||typeof u.features!="object"||typeof u.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let c=r.webgpu.powerPreference;if(c!==void 0&&c!=="low-power"&&c!=="high-performance")throw new Error(`Invalid powerPreference setting: "${c}"`);let p=r.webgpu.forceFallbackAdapter;if(p!==void 0&&typeof p!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${p}"`);if(u=await navigator.gpu.requestAdapter({powerPreference:c,forceFallbackAdapter:p}),!u)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",Nr(),r,u)}if(i==="webnn"){if(typeof navigator>"u"||!navigator.ml)throw new Error("WebNN is not supported in current environment");await s("webnn",Nr(),r)}}},Zo=new Map,vy=r=>{let i=Nr(),s=i.stackSave();try{let u=i.stackAlloc(8);return i._OrtGetInputOutputCount(r,u,u+4)!==0&&Fr("Can't get session input/output count."),[i.HEAP32[u/4],i.HEAP32[u/4+1]]}finally{i.stackRestore(s)}},Cp=r=>{let i=Nr(),s=i._malloc(r.byteLength);if(s===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${r.byteLength}.`);return i.HEAPU8.set(r,s),[s,r.byteLength]},bm=async(r,i)=>{var H,v;let s,u,c=Nr();Array.isArray(r)?[s,u]=r:r.buffer===c.HEAPU8.buffer?[s,u]=[r.byteOffset,r.byteLength]:[s,u]=Cp(r);let p=0,d=0,b=0,T=[],E=[],q=[];try{if([d,T]=Bi(i),(i==null?void 0:i.externalData)&&c.mountExternalData){let xe=[];for(let Ie of i.externalData){let ct=typeof Ie=="string"?Ie:Ie.path;xe.push(Zi(typeof Ie=="string"?Ie:Ie.data).then(et=>{c.mountExternalData(ct,et)}))}await Promise.all(xe)}for(let xe of(i==null?void 0:i.executionProviders)??[])if((typeof xe=="string"?xe:xe.name)==="webnn"){if(c.currentContext)throw new Error("WebNN execution provider is already set.");if(typeof xe!="string"){let Ie=xe,ct=Ie==null?void 0:Ie.context,et=Ie==null?void 0:Ie.gpuDevice,vt=Ie==null?void 0:Ie.deviceType,Ft=Ie==null?void 0:Ie.numThreads,Lt=Ie==null?void 0:Ie.powerPreference;ct?c.currentContext=ct:et?c.currentContext=await navigator.ml.createContext(et):c.currentContext=await navigator.ml.createContext({deviceType:vt,numThreads:Ft,powerPreference:Lt})}else c.currentContext=await navigator.ml.createContext();break}p=await c._OrtCreateSession(s,u,d),p===0&&Fr("Can't create a session."),c.currentContext&&(c.currentContext=void 0);let[ne,re]=vy(p),ce=!!(i!=null&&i.enableGraphCapture),_e=[],be=[],he=[];for(let xe=0;xexe==="gpu-buffer")&&(b=c._OrtCreateBinding(p),b===0&&Fr("Can't create IO binding."),Fe={handle:b,outputPreferredLocations:he,outputPreferredLocationsEncoded:he.map(xe=>po(xe))}),Zo.set(p,[p,E,q,Fe,ce,!1]),[p,_e,be]}catch(ne){throw E.forEach(re=>c._OrtFree(re)),q.forEach(re=>c._OrtFree(re)),b!==0&&c._OrtReleaseBinding(b),p!==0&&c._OrtReleaseSession(p),ne}finally{c._free(s),d!==0&&c._OrtReleaseSessionOptions(d),T.forEach(ne=>c._free(ne)),(v=c.unmountExternalData)==null||v.call(c)}},xm=r=>{var T;let i=Nr(),s=Zo.get(r);if(!s)throw new Error(`cannot release session. invalid session id: ${r}`);let[u,c,p,d,b]=s;d&&(b&&i._OrtClearBoundOutputs(d.handle),i._OrtReleaseBinding(d.handle)),(T=i.jsepOnReleaseSession)==null||T.call(i,r),c.forEach(E=>i._OrtFree(E)),p.forEach(E=>i._OrtFree(E)),i._OrtReleaseSession(u),Zo.delete(r)},Mm=(r,i,s,u,c,p=!1)=>{if(!r){i.push(0);return}let d=Nr(),b=r[0],T=r[1],E=r[3],q,H;if(b==="string"&&E==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");if(p&&E!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${c} when enableGraphCapture is true.`);if(E==="gpu-buffer"){let re=r[2].gpuBuffer;H=Mi(co(b),T);let ce=d.jsepRegisterBuffer;if(!ce)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');q=ce(u,c,re,H)}else{let re=r[2];if(Array.isArray(re)){H=4*re.length,q=d._malloc(H),s.push(q);let ce=q/4;for(let _e=0;_ed.HEAP32[re++]=_e);let ce=d._OrtCreateTensor(co(b),q,H,ne,T.length,po(E));ce===0&&Fr(`Can't create tensor for input/output. session=${u}, index=${c}.`),i.push(ce)}finally{d.stackRestore(v)}},Tm=async(r,i,s,u,c,p)=>{var Lt,pr;let d=Nr(),b=Zo.get(r);if(!b)throw new Error(`cannot run inference. invalid session id: ${r}`);let T=b[0],E=b[1],q=b[2],H=b[3],v=b[4],ne=b[5],re=i.length,ce=u.length,_e=0,be=[],he=[],Fe=[],xe=[],Ie=d.stackSave(),ct=d.stackAlloc(re*4),et=d.stackAlloc(re*4),vt=d.stackAlloc(ce*4),Ft=d.stackAlloc(ce*4);try{[_e,be]=xi(p);for(let It=0;ItFn*Zn,1);ir=di(xn);let sf=H==null?void 0:H.outputPreferredLocations[u[It]];if(ir==="string"){if(sf==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");let Fn=[],Zn=Hr/4;for(let Ci=0;Ci0){let Fn=d.jsepGetBuffer;if(!Fn)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let Zn=Fn(Hr),Ci=Mi(xn,In);if(Ci===void 0||!fo(ir))throw new Error(`Unsupported data type: ${ir}`);zt=!0,jr.push([ir,hi,{gpuBuffer:Zn,download:d.jsepCreateDownloader(Zn,Ci,ir),dispose:()=>{d._OrtReleaseTensor(tr)}},"gpu-buffer"])}else{let Fn=Ti(ir),Zn=new Fn(In);new Uint8Array(Zn.buffer,Zn.byteOffset,Zn.byteLength).set(d.HEAPU8.subarray(Hr,Hr+Zn.byteLength)),jr.push([ir,hi,Zn,"cpu"])}}finally{d.stackRestore(er),ir==="string"&&Hr&&d._free(Hr),zt||d._OrtReleaseTensor(tr)}}return H&&!v&&(d._OrtClearBoundOutputs(H.handle),Zo.set(r,[T,E,q,H,v,!1])),jr}finally{d.stackRestore(Ie),he.forEach(ar=>d._OrtReleaseTensor(ar)),Fe.forEach(ar=>d._OrtReleaseTensor(ar)),xe.forEach(ar=>d._free(ar)),_e!==0&&d._OrtReleaseRunOptions(_e),be.forEach(ar=>d._free(ar))}},km=r=>{let i=Nr(),s=Zo.get(r);if(!s)throw new Error("invalid session id");let u=s[0],c=i._OrtEndProfiling(u);c===0&&Fr("Can't get an profile file name."),i._OrtFree(c)},Sm=r=>{let i=[];for(let s of r){let u=s[2];!Array.isArray(u)&&"buffer"in u&&i.push(u.buffer)}return i}}),Jo,ii,Tl,nf,of,Pp,Em,$p,qs,Hs,xy,My,Ty,ky,Sy,Ey,Cy,Py,$y=h(()=>{Z(),by(),mn(),Qr(),Jo=()=>!!D.wasm.proxy&&typeof document<"u",Tl=!1,nf=!1,of=!1,$p=new Map,qs=(r,i)=>{let s=$p.get(r);s?s.push(i):$p.set(r,[i])},Hs=()=>{if(Tl||!nf||of||!ii)throw new Error("worker not ready")},xy=r=>{switch(r.data.type){case"init-wasm":Tl=!1,r.data.err?(of=!0,Em[1](r.data.err)):(nf=!0,Em[0]()),Pp&&(URL.revokeObjectURL(Pp),Pp=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let i=$p.get(r.data.type);r.data.err?i.shift()[1](r.data.err):i.shift()[0](r.data.out);break}}},My=async()=>{if(!nf){if(Tl)throw new Error("multiple calls to 'initWasm()' detected.");if(of)throw new Error("previous call to 'initWasm()' failed.");if(Tl=!0,Jo())return new Promise((r,i)=>{ii==null||ii.terminate(),Jt().then(([s,u])=>{try{ii=u,ii.onerror=p=>i(p),ii.onmessage=xy,Em=[r,i];let c={type:"init-wasm",in:D};ii.postMessage(c),Pp=s}catch(c){i(c)}},i)});try{await bi(D.wasm),await wm(D),nf=!0}catch(r){throw of=!0,r}finally{Tl=!1}}},Ty=async r=>{if(Jo())return Hs(),new Promise((i,s)=>{qs("init-ep",[i,s]);let u={type:"init-ep",in:{epName:r,env:D}};ii.postMessage(u)});await vm(D,r)},ky=async r=>Jo()?(Hs(),new Promise((i,s)=>{qs("copy-from",[i,s]);let u={type:"copy-from",in:{buffer:r}};ii.postMessage(u,[r.buffer])})):Cp(r),Sy=async(r,i)=>{if(Jo()){if(i!=null&&i.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return Hs(),new Promise((s,u)=>{qs("create",[s,u]);let c={type:"create",in:{model:r,options:{...i}}},p=[];r instanceof Uint8Array&&p.push(r.buffer),ii.postMessage(c,p)})}else return bm(r,i)},Ey=async r=>{if(Jo())return Hs(),new Promise((i,s)=>{qs("release",[i,s]);let u={type:"release",in:r};ii.postMessage(u)});xm(r)},Cy=async(r,i,s,u,c,p)=>{if(Jo()){if(s.some(d=>d[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(c.some(d=>d))throw new Error("pre-allocated output tensor is not supported for proxy.");return Hs(),new Promise((d,b)=>{qs("run",[d,b]);let T=s,E={type:"run",in:{sessionId:r,inputIndices:i,inputs:T,outputIndices:u,options:p}};ii.postMessage(E,Sm(T))})}else return Tm(r,i,s,u,c,p)},Py=async r=>{if(Jo())return Hs(),new Promise((i,s)=>{qs("end-profiling",[i,s]);let u={type:"end-profiling",in:r};ii.postMessage(u)});km(r)}}),Cm,Ay,Iy,fx=h(()=>{Z(),$y(),Xt(),ve(),Bo(),Cm=(r,i)=>{switch(r.location){case"cpu":return[r.type,r.dims,r.data,"cpu"];case"gpu-buffer":return[r.type,r.dims,{gpuBuffer:r.gpuBuffer},"gpu-buffer"];default:throw new Error(`invalid data location: ${r.location} for ${i()}`)}},Ay=r=>{switch(r[3]){case"cpu":return new Ge(r[0],r[2],r[1]);case"gpu-buffer":{let i=r[0];if(!fo(i))throw new Error(`not supported data type: ${i} for deserializing GPU tensor`);let{gpuBuffer:s,download:u,dispose:c}=r[2];return Ge.fromGpuBuffer(s,{dataType:i,dims:r[1],download:u,dispose:c})}default:throw new Error(`invalid data location: ${r[3]}`)}},Iy=class{async fetchModelAndCopyToWasmMemory(r){return ky(await Zi(r))}async loadModel(r,i){tt();let s;typeof r=="string"?s=await this.fetchModelAndCopyToWasmMemory(r):s=r,[this.sessionId,this.inputNames,this.outputNames]=await Sy(s,i),A()}async dispose(){return Ey(this.sessionId)}async run(r,i,s){tt();let u=[],c=[];Object.entries(r).forEach(H=>{let v=H[0],ne=H[1],re=this.inputNames.indexOf(v);if(re===-1)throw new Error(`invalid input '${v}'`);u.push(ne),c.push(re)});let p=[],d=[];Object.entries(i).forEach(H=>{let v=H[0],ne=H[1],re=this.outputNames.indexOf(v);if(re===-1)throw new Error(`invalid output '${v}'`);p.push(ne),d.push(re)});let b=u.map((H,v)=>Cm(H,()=>`input "${this.inputNames[c[v]]}"`)),T=p.map((H,v)=>H?Cm(H,()=>`output "${this.outputNames[d[v]]}"`):null),E=await Cy(this.sessionId,c,b,d,T,s),q={};for(let H=0;H{Z(),$y(),fx(),Qr(),Fy=()=>{if((typeof D.wasm.initTimeout!="number"||D.wasm.initTimeout<0)&&(D.wasm.initTimeout=0),D.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 D.wasm.proxy!="boolean"&&(D.wasm.proxy=!1),typeof D.wasm.trace!="boolean"&&(D.wasm.trace=!1),typeof D.wasm.numThreads!="number"||!Number.isInteger(D.wasm.numThreads)||D.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)D.wasm.numThreads=1;else{let r=typeof navigator>"u"?_("node:os").cpus().length:navigator.hardwareConcurrency;D.wasm.numThreads=Math.min(4,Math.ceil((r||1)/2))}},zy=class{async init(r){Fy(),await My(),await Ty(r)}async createInferenceSessionHandler(r,i){let s=new Iy;return await s.loadModel(r,i),Promise.resolve(s)}}}),Oy={};g(Oy,{wasmBackend:()=>Dy});var Dy,hx=h(()=>{px(),Dy=new zy});Z(),Z(),Z();var mx="1.20.0-dev.20240821-009209e016",gx=Ve;{let r=(hx(),w(Oy)).wasmBackend;z("webgpu",r,5),z("webnn",r,5),z("cpu",r,10),z("wasm",r,10)}Object.defineProperty(D.versions,"web",{value:mx,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,t,n)=>{var o;n.r(t),n.d(t,{Tensor:()=>_.Tensor,createInferenceSession:()=>S,deviceToExecutionProviders:()=>k,isONNXProxy:()=>x,isONNXTensor:()=>P});var a=n("./src/env.js"),l=n("?2ce3"),f=n("./node_modules/onnxruntime-web/dist/ort.webgpu.bundle.min.mjs"),_=n("./node_modules/onnxruntime-common/dist/esm/index.js");const h=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"}}),g=[];let M,w;if(a.apis.IS_NODE_ENV){switch(w=l??(o||(o=n.t(l,2))),process.platform){case"win32":g.push("dml");break;case"linux":process.arch==="x64"&&g.push("cuda");break}g.push("cpu"),M=["cpu"]}else w=f,a.apis.IS_WEBNN_AVAILABLE&&g.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),a.apis.IS_WEBGPU_AVAILABLE&&g.push("webgpu"),g.push("wasm"),M=["wasm"];const C=w.InferenceSession;function k(I=null){if(!I)return M;switch(I){case"auto":return g;case"gpu":return g.filter(U=>["webgpu","cuda","dml","webnn-gpu"].includes(U))}if(g.includes(I))return[h[I]??I];throw new Error(`Unsupported device: "${I}". Should be one of: ${g.join(", ")}.`)}let z=null;async function S(I,U){z&&await z;const O=C.create(I,U);return z??(z=O),await O}function P(I){return I instanceof w.Tensor}const y=w==null?void 0:w.env;y!=null&&y.wasm&&(y.wasm.wasmPaths=`https://cdn.jsdelivr.net/npm/@huggingface/transformers@${a.env.version}/dist/`,y.wasm.proxy=!a.apis.IS_WEBWORKER_ENV,(typeof crossOriginIsolated>"u"||!crossOriginIsolated)&&(y.wasm.numThreads=1),typeof navigator<"u"&&/iP(hone|od|ad).+16_4.+AppleWebKit/.test(navigator.userAgent)&&(y.wasm.simd=!1)),y!=null&&y.webgpu&&(y.webgpu.powerPreference="high-performance");function x(){var I;return(I=y==null?void 0:y.wasm)==null?void 0:I.proxy}a.env.backends.onnx=y},"./src/configs.js":(e,t,n)=>{n.r(t),n.d(t,{AutoConfig:()=>g,PretrainedConfig:()=>h,getKeyValueShapes:()=>_});var o=n("./src/utils/core.js"),a=n("./src/utils/hub.js");async function l(M,w){return await(0,a.getModelJSON)(M,"config.json",!0,w)}function f(M){const w={};let C={};switch(M.model_type){case"llava":case"paligemma":case"florence2":C=f(M.text_config);break;case"moondream1":C=f(M.phi_config);break;case"musicgen":C=f(M.decoder);break;case"gpt2":case"gptj":case"codegen":case"gpt_bigcode":w.num_heads="n_head",w.num_layers="n_layer",w.hidden_size="n_embd";break;case"gpt_neox":case"stablelm":case"opt":case"phi":case"phi3":case"falcon":w.num_heads="num_attention_heads",w.num_layers="num_hidden_layers",w.hidden_size="hidden_size";break;case"llama":case"cohere":case"mistral":case"starcoder2":case"qwen2":w.num_heads="num_key_value_heads",w.num_layers="num_hidden_layers",w.hidden_size="hidden_size",w.num_attention_heads="num_attention_heads";break;case"gemma":case"gemma2":w.num_heads="num_key_value_heads",w.num_layers="num_hidden_layers",w.dim_kv="head_dim";break;case"openelm":w.num_heads="num_kv_heads",w.num_layers="num_transformer_layers",w.dim_kv="head_dim";break;case"gpt_neo":case"donut-swin":w.num_heads="num_heads",w.num_layers="num_layers",w.hidden_size="hidden_size";break;case"bloom":w.num_heads="n_head",w.num_layers="n_layer",w.hidden_size="hidden_size";break;case"mpt":w.num_heads="n_heads",w.num_layers="n_layers",w.hidden_size="d_model";break;case"t5":case"mt5":case"longt5":w.num_decoder_layers="num_decoder_layers",w.num_decoder_heads="num_heads",w.decoder_dim_kv="d_kv",w.num_encoder_layers="num_layers",w.num_encoder_heads="num_heads",w.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":w.num_decoder_layers="decoder_layers",w.num_decoder_heads="decoder_attention_heads",w.decoder_hidden_size="d_model",w.num_encoder_layers="encoder_layers",w.num_encoder_heads="encoder_attention_heads",w.encoder_hidden_size="d_model";break;case"speecht5":w.num_decoder_layers="decoder_layers",w.num_decoder_heads="decoder_attention_heads",w.decoder_hidden_size="hidden_size",w.num_encoder_layers="encoder_layers",w.num_encoder_heads="encoder_attention_heads",w.encoder_hidden_size="hidden_size";break;case"trocr":w.num_encoder_layers=w.num_decoder_layers="decoder_layers",w.num_encoder_heads=w.num_decoder_heads="decoder_attention_heads",w.encoder_hidden_size=w.decoder_hidden_size="d_model";break;case"musicgen_decoder":w.num_encoder_layers=w.num_decoder_layers="num_hidden_layers",w.num_encoder_heads=w.num_decoder_heads="num_attention_heads",w.encoder_hidden_size=w.decoder_hidden_size="hidden_size";break;case"vision-encoder-decoder":const z=f(M.decoder),S="num_decoder_layers"in z,P=(0,o.pick)(M,["model_type","is_encoder_decoder"]);return S?(P.num_decoder_layers=z.num_decoder_layers,P.num_decoder_heads=z.num_decoder_heads,P.decoder_hidden_size=z.decoder_hidden_size,P.num_encoder_layers=z.num_encoder_layers,P.num_encoder_heads=z.num_encoder_heads,P.encoder_hidden_size=z.encoder_hidden_size):(P.num_layers=z.num_layers,P.num_heads=z.num_heads,P.hidden_size=z.hidden_size),P}const k={...C,...(0,o.pick)(M,["model_type","multi_query","is_encoder_decoder"])};for(const z in w)k[z]=M[w[z]];return k}function _(M,{prefix:w="past_key_values"}={}){const C={},k=M.normalized_config,z=1;if(k.is_encoder_decoder&&"num_encoder_heads"in k&&"num_decoder_heads"in k){const S=k.encoder_dim_kv??k.encoder_hidden_size/k.num_encoder_heads,P=k.decoder_dim_kv??k.decoder_hidden_size/k.num_decoder_heads,y=[z,k.num_encoder_heads,0,S],x=[z,k.num_decoder_heads,0,P];for(let I=0;I{var D;n.r(t),n.d(t,{apis:()=>P,env:()=>N});var o=n("?569f"),a=n("?3f59"),l=n("?154a");const f="3.0.0-alpha.9",_=typeof self<"u",h=_&&self.constructor.name==="DedicatedWorkerGlobalScope",g=_&&"caches"in self,M=typeof navigator<"u"&&"gpu"in navigator,w=typeof navigator<"u"&&"ml"in navigator,C=typeof process<"u",k=C&&((D=process==null?void 0:process.release)==null?void 0:D.name)==="node",z=!j(o),S=!j(a),P=Object.freeze({IS_BROWSER_ENV:_,IS_WEBWORKER_ENV:h,IS_WEB_CACHE_AVAILABLE:g,IS_WEBGPU_AVAILABLE:M,IS_WEBNN_AVAILABLE:w,IS_PROCESS_AVAILABLE:C,IS_NODE_ENV:k,IS_FS_AVAILABLE:z,IS_PATH_AVAILABLE:S}),y=z&&S,x=y?a.dirname(a.dirname(l.fileURLToPath(import.meta.url))):"./",I=y?a.join(x,"/.cache/"):null,U="/models/",O=y?a.join(x,U):U,N={version:f,backends:{onnx:{},tfjs:{}},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!_,localModelPath:O,useFS:z,useBrowserCache:g,useFSCache:z,cacheDir:I,useCustomCache:!1,customCache:null};function j(Y){return Object.keys(Y).length===0}},"./src/generation/configuration_utils.js":(e,t,n)=>{n.r(t),n.d(t,{GenerationConfig:()=>a});var o=n("./src/utils/core.js");class a{constructor(f){qe(this,"max_length",20);qe(this,"max_new_tokens",null);qe(this,"min_length",0);qe(this,"min_new_tokens",null);qe(this,"early_stopping",!1);qe(this,"max_time",null);qe(this,"do_sample",!1);qe(this,"num_beams",1);qe(this,"num_beam_groups",1);qe(this,"penalty_alpha",null);qe(this,"use_cache",!0);qe(this,"temperature",1);qe(this,"top_k",50);qe(this,"top_p",1);qe(this,"typical_p",1);qe(this,"epsilon_cutoff",0);qe(this,"eta_cutoff",0);qe(this,"diversity_penalty",0);qe(this,"repetition_penalty",1);qe(this,"encoder_repetition_penalty",1);qe(this,"length_penalty",1);qe(this,"no_repeat_ngram_size",0);qe(this,"bad_words_ids",null);qe(this,"force_words_ids",null);qe(this,"renormalize_logits",!1);qe(this,"constraints",null);qe(this,"forced_bos_token_id",null);qe(this,"forced_eos_token_id",null);qe(this,"remove_invalid_values",!1);qe(this,"exponential_decay_length_penalty",null);qe(this,"suppress_tokens",null);qe(this,"begin_suppress_tokens",null);qe(this,"forced_decoder_ids",null);qe(this,"guidance_scale",null);qe(this,"num_return_sequences",1);qe(this,"output_attentions",!1);qe(this,"output_hidden_states",!1);qe(this,"output_scores",!1);qe(this,"return_dict_in_generate",!1);qe(this,"pad_token_id",null);qe(this,"bos_token_id",null);qe(this,"eos_token_id",null);qe(this,"encoder_no_repeat_ngram_size",0);qe(this,"decoder_start_token_id",null);qe(this,"generation_kwargs",{});Object.assign(this,(0,o.pick)(f,Object.getOwnPropertyNames(this)))}}},"./src/generation/logits_process.js":(e,t,n)=>{n.r(t),n.d(t,{ClassifierFreeGuidanceLogitsProcessor:()=>y,ForcedBOSTokenLogitsProcessor:()=>h,ForcedEOSTokenLogitsProcessor:()=>g,LogitsProcessor:()=>l,LogitsProcessorList:()=>_,LogitsWarper:()=>f,MinLengthLogitsProcessor:()=>z,MinNewTokensLengthLogitsProcessor:()=>S,NoBadWordsLogitsProcessor:()=>P,NoRepeatNGramLogitsProcessor:()=>C,RepetitionPenaltyLogitsProcessor:()=>k,SuppressTokensAtBeginLogitsProcessor:()=>M,TemperatureLogitsWarper:()=>x,TopKLogitsWarper:()=>U,TopPLogitsWarper:()=>I,WhisperTimeStampLogitsProcessor:()=>w});var o=n("./src/utils/generic.js");n("./src/utils/tensor.js");var a=n("./src/utils/maths.js");class l extends o.Callable{_call(N,j){throw Error("`_call` should be implemented in a subclass")}}class f extends o.Callable{_call(N,j){throw Error("`_call` should be implemented in a subclass")}}class _ extends o.Callable{constructor(){super(),this.processors=[]}push(N){this.processors.push(N)}extend(N){this.processors.push(...N)}_call(N,j){let D=j;for(const Y of this.processors)D=Y(N,D);return D}[Symbol.iterator](){return this.processors.values()}}class h extends l{constructor(N){super(),this.bos_token_id=N}_call(N,j){for(let D=0;D=1&&Ce[Ce.length-1]>=this.timestamp_begin,ye=Ce.length<2||Ce[Ce.length-2]>=this.timestamp_begin;if(ee&&(ye?de.subarray(this.timestamp_begin).fill(-1/0):de.subarray(0,this.eos_token_id).fill(-1/0)),N[D].length===this.begin_index&&this.max_initial_timestamp_index!==null){const ge=this.timestamp_begin+this.max_initial_timestamp_index;de.subarray(ge+1).fill(-1/0)}const R=(0,a.log_softmax)(de),Me=Math.log(R.subarray(this.timestamp_begin).map(Math.exp).reduce((ge,Q)=>ge+Q)),Qe=(0,a.max)(R.subarray(0,this.timestamp_begin))[0];Me>Qe&&de.subarray(0,this.timestamp_begin).fill(-1/0)}return j}}class C extends l{constructor(N){super(),this.no_repeat_ngram_size=N}getNgrams(N){const j=N.length,D=[];for(let de=0;de1 to use the classifier free guidance processor, got guidance scale ${N}.`);this.guidance_scale=N}_call(N,j){if(j.dims[0]!==2*N.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 ${j.dims[0]} for the logits and ${N.length} for the input ids.`);const D=N.length,Y=j.slice([0,D],null),de=j.slice([D,j.dims[0]],null);for(let Ce=0;Ce1)throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${N}`);if(!Number.isInteger(D)||D<1)throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${D}`);this.top_p=N,this.filter_value=j,this.min_tokens_to_keep=D}}class U extends f{constructor(N,{filter_value:j=-1/0,min_tokens_to_keep:D=1}={}){if(super(),!Number.isInteger(N)||N<0)throw new Error(`\`top_k\` must be a positive integer, but is ${N}`);this.top_k=Math.max(N,D),this.filter_value=j}}},"./src/generation/logits_sampler.js":(e,t,n)=>{n.r(t),n.d(t,{LogitsSampler:()=>f});var o=n("./src/utils/generic.js"),a=n("./src/utils/tensor.js"),l=n("./src/utils/maths.js");n("./src/generation/configuration_utils.js");class f extends o.Callable{constructor(w){super(),this.generation_config=w}async _call(w){return this.sample(w)}async sample(w){throw Error("sample should be implemented in subclasses.")}getLogits(w,C){let k=w.dims.at(-1),z=w.data;if(C===-1)z=z.slice(-k);else{let S=C*k;z=z.slice(S,S+k)}return z}randomSelect(w){let C=0;for(let z=0;z1)return new g(w);if(w.num_return_sequences>1)throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${w.num_return_sequences}.`);return new _(w)}}class _ extends f{async sample(w){const C=(0,l.max)(w.data)[1];return[[BigInt(C),0]]}}class h extends f{async sample(w){let C=w.dims.at(-1);this.generation_config.top_k>0&&(C=Math.min(this.generation_config.top_k,C));const[k,z]=await(0,a.topk)(w,C),S=(0,l.softmax)(k.data);return Array.from({length:this.generation_config.num_beams},()=>{const P=this.randomSelect(S);return[z.data[P],Math.log(S[P])]})}}class g extends f{async sample(w){let C=w.dims.at(-1);this.generation_config.top_k>0&&(C=Math.min(this.generation_config.top_k,C));const[k,z]=await(0,a.topk)(w,C),S=(0,l.softmax)(k.data);return Array.from({length:this.generation_config.num_beams},(P,y)=>[z.data[y],Math.log(S[y])])}}},"./src/generation/stopping_criteria.js":(e,t,n)=>{n.r(t),n.d(t,{EosTokenCriteria:()=>_,InterruptableStoppingCriteria:()=>h,MaxLengthCriteria:()=>f,StoppingCriteria:()=>a,StoppingCriteriaList:()=>l});var o=n("./src/utils/generic.js");class a extends o.Callable{_call(M,w){throw Error("StoppingCriteria needs to be subclassed")}}class l extends o.Callable{constructor(){super(),this.criteria=[]}push(M){this.criteria.push(M)}extend(M){M instanceof l?M=M.criteria:M instanceof a&&(M=[M]),this.criteria.push(...M)}_call(M,w){const C=new Array(M.length).fill(!1);for(const k of this.criteria){const z=k(M,w);for(let S=0;Sw.length>=this.max_length)}}class _ extends a{constructor(M){super(),Array.isArray(M)||(M=[M]),this.eos_token_id=M}_call(M,w){return M.map(C=>{const k=C.at(-1);return this.eos_token_id.some(z=>k==z)})}}class h extends a{constructor(){super(),this.interrupted=!1}interrupt(){this.interrupted=!0}reset(){this.interrupted=!1}_call(M,w){return new Array(M.length).fill(this.interrupted)}}},"./src/generation/streamers.js":(e,t,n)=>{n.r(t),n.d(t,{BaseStreamer:()=>f,TextStreamer:()=>h,WhisperTextStreamer:()=>g});var o=n("./src/utils/core.js"),a=n("./src/tokenizers.js"),l=n("./src/env.js");class f{put(w){throw Error("Not implemented")}end(){throw Error("Not implemented")}}const _=l.apis.IS_PROCESS_AVAILABLE?M=>process.stdout.write(M):M=>console.log(M);class h extends f{constructor(w,{skip_prompt:C=!1,callback_function:k=null,token_callback_function:z=null,decode_kwargs:S={},...P}={}){super(),this.tokenizer=w,this.skip_prompt=C,this.callback_function=k??_,this.token_callback_function=z,this.decode_kwargs={...S,...P},this.token_cache=[],this.print_len=0,this.next_tokens_are_prompt=!0}put(w){var S;if(w.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 C=w[0];(S=this.token_callback_function)==null||S.call(this,C),this.token_cache=(0,o.mergeArrays)(this.token_cache,C);const k=this.tokenizer.decode(this.token_cache,this.decode_kwargs);let z;k.endsWith(` +`)?(z=k.slice(this.print_len),this.token_cache=[],this.print_len=0):k.length>0&&(0,a.is_chinese_char)(k.charCodeAt(k.length-1))?(z=k.slice(this.print_len),this.print_len+=z.length):(z=k.slice(this.print_len,k.lastIndexOf(" ")+1),this.print_len+=z.length),this.on_finalized_text(z,!1)}end(){let w;this.token_cache.length>0?(w=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len),this.token_cache=[],this.print_len=0):w="",this.next_tokens_are_prompt=!0,this.on_finalized_text(w,!0)}on_finalized_text(w,C){var k,z;w.length>0&&((k=this.callback_function)==null||k.call(this,w)),C&&this.callback_function===_&&l.apis.IS_PROCESS_AVAILABLE&&((z=this.callback_function)==null||z.call(this,` +`))}}class g extends h{constructor(w,{skip_prompt:C=!1,callback_function:k=null,token_callback_function:z=null,on_chunk_start:S=null,on_chunk_end:P=null,on_finalize:y=null,time_precision:x=.02,skip_special_tokens:I=!0,decode_kwargs:U={}}={}){super(w,{skip_prompt:C,callback_function:k,token_callback_function:z,decode_kwargs:{skip_special_tokens:I,...U}}),this.timestamp_begin=w.timestamp_begin,this.on_chunk_start=S,this.on_chunk_end=P,this.on_finalize=y,this.time_precision=x,this.waiting_for_timestamp=!1}put(w){var k,z;if(w.length>1)throw Error("WhisperTextStreamer only supports batch size of 1");const C=w[0];if(C.length===1){const S=Number(C[0])-this.timestamp_begin;if(S>=0){const P=S*this.time_precision;this.waiting_for_timestamp?(k=this.on_chunk_end)==null||k.call(this,P):(z=this.on_chunk_start)==null||z.call(this,P),this.waiting_for_timestamp=!this.waiting_for_timestamp,w=[[]]}}return super.put(w)}end(){var w;super.end(),(w=this.on_finalize)==null||w.call(this)}}},"./src/models.js":(e,t,n)=>{n.r(t),n.d(t,{ASTForAudioClassification:()=>Es,ASTModel:()=>Dt,ASTPreTrainedModel:()=>Nn,AlbertForMaskedLM:()=>Xt,AlbertForQuestionAnswering:()=>po,AlbertForSequenceClassification:()=>fo,AlbertModel:()=>Yi,AlbertPreTrainedModel:()=>Ti,AutoModel:()=>Od,AutoModelForAudioClassification:()=>Hd,AutoModelForAudioFrameClassification:()=>Kd,AutoModelForCTC:()=>qd,AutoModelForCausalLM:()=>Bd,AutoModelForDepthEstimation:()=>Yd,AutoModelForDocumentQuestionAnswering:()=>bp,AutoModelForImageClassification:()=>Ud,AutoModelForImageFeatureExtraction:()=>Zd,AutoModelForImageMatting:()=>Qd,AutoModelForImageSegmentation:()=>vl,AutoModelForImageToImage:()=>Xd,AutoModelForMaskGeneration:()=>bl,AutoModelForMaskedLM:()=>Nd,AutoModelForObjectDetection:()=>Wd,AutoModelForQuestionAnswering:()=>wl,AutoModelForSemanticSegmentation:()=>Vd,AutoModelForSeq2SeqLM:()=>Ld,AutoModelForSequenceClassification:()=>Sn,AutoModelForSpeechSeq2Seq:()=>yl,AutoModelForTextToSpectrogram:()=>Rd,AutoModelForTextToWaveform:()=>Xo,AutoModelForTokenClassification:()=>Dd,AutoModelForVision2Seq:()=>jd,AutoModelForXVector:()=>xl,AutoModelForZeroShotObjectDetection:()=>Gd,BartForConditionalGeneration:()=>W,BartForSequenceClassification:()=>fe,BartModel:()=>Ue,BartPretrainedModel:()=>Rn,BaseModelOutput:()=>Ke,BeitForImageClassification:()=>sc,BeitModel:()=>oc,BeitPreTrainedModel:()=>$a,BertForMaskedLM:()=>We,BertForQuestionAnswering:()=>Ge,BertForSequenceClassification:()=>ot,BertForTokenClassification:()=>dt,BertModel:()=>Be,BertPreTrainedModel:()=>De,BlenderbotForConditionalGeneration:()=>At,BlenderbotModel:()=>Tt,BlenderbotPreTrainedModel:()=>kt,BlenderbotSmallForConditionalGeneration:()=>rr,BlenderbotSmallModel:()=>Pr,BlenderbotSmallPreTrainedModel:()=>Zt,BloomForCausalLM:()=>ju,BloomModel:()=>Nu,BloomPreTrainedModel:()=>$s,CLIPModel:()=>lu,CLIPPreTrainedModel:()=>Wo,CLIPSegForImageSegmentation:()=>mu,CLIPSegModel:()=>hu,CLIPSegPreTrainedModel:()=>ma,CLIPTextModelWithProjection:()=>fi,CLIPVisionModelWithProjection:()=>uu,CamembertForMaskedLM:()=>Re,CamembertForQuestionAnswering:()=>rt,CamembertForSequenceClassification:()=>He,CamembertForTokenClassification:()=>Xe,CamembertModel:()=>ve,CamembertPreTrainedModel:()=>Z,CausalLMOutput:()=>Ji,CausalLMOutputWithPast:()=>xp,ChineseCLIPModel:()=>pu,ChineseCLIPPreTrainedModel:()=>fu,ClapAudioModelWithProjection:()=>ld,ClapModel:()=>sd,ClapPreTrainedModel:()=>qo,ClapTextModelWithProjection:()=>ad,CodeGenForCausalLM:()=>Cs,CodeGenModel:()=>ku,CodeGenPreTrainedModel:()=>Kn,CohereForCausalLM:()=>Cu,CohereModel:()=>Eu,CoherePreTrainedModel:()=>va,ConvBertForMaskedLM:()=>B,ConvBertForQuestionAnswering:()=>ue,ConvBertForSequenceClassification:()=>J,ConvBertForTokenClassification:()=>L,ConvBertModel:()=>we,ConvBertPreTrainedModel:()=>te,ConvNextForImageClassification:()=>Pc,ConvNextModel:()=>Cc,ConvNextPreTrainedModel:()=>Va,ConvNextV2ForImageClassification:()=>Ic,ConvNextV2Model:()=>Ac,ConvNextV2PreTrainedModel:()=>$c,DPTForDepthEstimation:()=>Na,DPTModel:()=>Ba,DPTPreTrainedModel:()=>Ra,DebertaForMaskedLM:()=>Mt,DebertaForQuestionAnswering:()=>Rt,DebertaForSequenceClassification:()=>wt,DebertaForTokenClassification:()=>St,DebertaModel:()=>ht,DebertaPreTrainedModel:()=>ft,DebertaV2ForMaskedLM:()=>Ut,DebertaV2ForQuestionAnswering:()=>Jt,DebertaV2ForSequenceClassification:()=>Kt,DebertaV2ForTokenClassification:()=>Qt,DebertaV2Model:()=>Ot,DebertaV2PreTrainedModel:()=>at,DeiTForImageClassification:()=>_c,DeiTModel:()=>gc,DeiTPreTrainedModel:()=>Fa,DepthAnythingForDepthEstimation:()=>Tc,DepthAnythingPreTrainedModel:()=>Mc,DetrForObjectDetection:()=>lc,DetrForSegmentation:()=>uc,DetrModel:()=>ac,DetrObjectDetectionOutput:()=>Aa,DetrPreTrainedModel:()=>Fs,DetrSegmentationOutput:()=>cc,Dinov2ForImageClassification:()=>zc,Dinov2Model:()=>Fc,Dinov2PreTrainedModel:()=>Xn,DistilBertForMaskedLM:()=>Pt,DistilBertForQuestionAnswering:()=>mt,DistilBertForSequenceClassification:()=>Qr,DistilBertForTokenClassification:()=>Cr,DistilBertModel:()=>Er,DistilBertPreTrainedModel:()=>qt,DonutSwinModel:()=>Ua,DonutSwinPreTrainedModel:()=>Ec,EfficientNetForImageClassification:()=>pd,EfficientNetModel:()=>fd,EfficientNetPreTrainedModel:()=>ul,ElectraForMaskedLM:()=>Ne,ElectraForQuestionAnswering:()=>Ve,ElectraForSequenceClassification:()=>ut,ElectraForTokenClassification:()=>Je,ElectraModel:()=>ke,ElectraPreTrainedModel:()=>le,EsmForMaskedLM:()=>Li,EsmForSequenceClassification:()=>bi,EsmForTokenClassification:()=>Nr,EsmModel:()=>sn,EsmPreTrainedModel:()=>Bt,FalconForCausalLM:()=>od,FalconModel:()=>id,FalconPreTrainedModel:()=>ol,FastViTForImageClassification:()=>Ku,FastViTModel:()=>Hu,FastViTPreTrainedModel:()=>Is,Florence2ForConditionalGeneration:()=>pa,Florence2PreTrainedModel:()=>au,GLPNForDepthEstimation:()=>Sc,GLPNModel:()=>kc,GLPNPreTrainedModel:()=>ja,GPT2LMHeadModel:()=>_u,GPT2Model:()=>gu,GPT2PreTrainedModel:()=>ga,GPTBigCodeForCausalLM:()=>ep,GPTBigCodeModel:()=>Tu,GPTBigCodePreTrainedModel:()=>wa,GPTJForCausalLM:()=>Mu,GPTJModel:()=>xu,GPTJPreTrainedModel:()=>ya,GPTNeoForCausalLM:()=>wu,GPTNeoModel:()=>yu,GPTNeoPreTrainedModel:()=>Hn,GPTNeoXForCausalLM:()=>bu,GPTNeoXModel:()=>vu,GPTNeoXPreTrainedModel:()=>_a,Gemma2ForCausalLM:()=>Iu,Gemma2Model:()=>Au,Gemma2PreTrainedModel:()=>xa,GemmaForCausalLM:()=>$u,GemmaModel:()=>Pu,GemmaPreTrainedModel:()=>ba,HubertForCTC:()=>Qc,HubertForSequenceClassification:()=>Za,HubertModel:()=>sp,HubertPreTrainedModel:()=>op,ImageMattingOutput:()=>ef,LlamaForCausalLM:()=>Su,LlamaModel:()=>ni,LlamaPreTrainedModel:()=>Ps,LlavaForConditionalGeneration:()=>go,LlavaPreTrainedModel:()=>su,LongT5ForConditionalGeneration:()=>Uo,LongT5Model:()=>jo,LongT5PreTrainedModel:()=>ho,M2M100ForConditionalGeneration:()=>Vc,M2M100Model:()=>Uc,M2M100PreTrainedModel:()=>qa,MBartForCausalLM:()=>xt,MBartForConditionalGeneration:()=>Oe,MBartForSequenceClassification:()=>nt,MBartModel:()=>ze,MBartPreTrainedModel:()=>Pe,MPNetForMaskedLM:()=>Oo,MPNetForQuestionAnswering:()=>Ro,MPNetForSequenceClassification:()=>Do,MPNetForTokenClassification:()=>Lo,MPNetModel:()=>ks,MPNetPreTrainedModel:()=>xi,MT5ForConditionalGeneration:()=>Br,MT5Model:()=>Vo,MT5PreTrainedModel:()=>mo,MarianMTModel:()=>jc,MarianModel:()=>np,MarianPreTrainedModel:()=>Ga,MaskedLMOutput:()=>yn,MistralForCausalLM:()=>Ns,MistralModel:()=>Bs,MistralPreTrainedModel:()=>rl,MobileBertForMaskedLM:()=>ci,MobileBertForQuestionAnswering:()=>Ri,MobileBertForSequenceClassification:()=>Fr,MobileBertModel:()=>Wr,MobileBertPreTrainedModel:()=>mn,MobileNetV1ForImageClassification:()=>cp,MobileNetV1Model:()=>hd,MobileNetV1PreTrainedModel:()=>fl,MobileNetV2ForImageClassification:()=>gd,MobileNetV2Model:()=>md,MobileNetV2PreTrainedModel:()=>pl,MobileNetV3ForImageClassification:()=>dp,MobileNetV3Model:()=>_d,MobileNetV3PreTrainedModel:()=>hl,MobileNetV4ForImageClassification:()=>ml,MobileNetV4Model:()=>Qo,MobileNetV4PreTrainedModel:()=>Ko,MobileViTForImageClassification:()=>Ju,MobileViTModel:()=>Zu,MobileViTPreTrainedModel:()=>Yu,MobileViTV2ForImageClassification:()=>ec,MobileViTV2Model:()=>rp,MobileViTV2PreTrainedModel:()=>Ca,ModelOutput:()=>me,Moondream1ForConditionalGeneration:()=>or,MptForCausalLM:()=>Uu,MptModel:()=>tp,MptPreTrainedModel:()=>As,MusicgenForCausalLM:()=>pm,MusicgenForConditionalGeneration:()=>dl,MusicgenModel:()=>up,MusicgenPreTrainedModel:()=>cl,NomicBertModel:()=>je,NomicBertPreTrainedModel:()=>Te,OPTForCausalLM:()=>Wu,OPTModel:()=>Vu,OPTPreTrainedModel:()=>Ea,OpenELMForCausalLM:()=>zu,OpenELMModel:()=>Fu,OpenELMPreTrainedModel:()=>Qn,OwlViTForObjectDetection:()=>rc,OwlViTModel:()=>tc,OwlViTPreTrainedModel:()=>vr,Owlv2ForObjectDetection:()=>ic,Owlv2Model:()=>nc,Owlv2PreTrainedModel:()=>Pa,Phi3ForCausalLM:()=>Sa,Phi3Model:()=>Bu,Phi3PreTrainedModel:()=>ka,PhiForCausalLM:()=>Ru,PhiModel:()=>Lu,PhiPreTrainedModel:()=>Ta,PreTrainedModel:()=>X,PretrainedMixin:()=>Or,PyAnnoteForAudioFrameClassification:()=>Vi,PyAnnoteModel:()=>Ha,PyAnnotePreTrainedModel:()=>ki,QuestionAnsweringModelOutput:()=>wn,Qwen2ForCausalLM:()=>Du,Qwen2Model:()=>Ou,Qwen2PreTrainedModel:()=>Ma,RTDetrForObjectDetection:()=>zs,RTDetrModel:()=>dc,RTDetrObjectDetectionOutput:()=>fc,RTDetrPreTrainedModel:()=>wo,ResNetForImageClassification:()=>wc,ResNetModel:()=>yc,ResNetPreTrainedModel:()=>za,RoFormerForMaskedLM:()=>A,RoFormerForQuestionAnswering:()=>se,RoFormerForSequenceClassification:()=>Ae,RoFormerForTokenClassification:()=>$e,RoFormerModel:()=>tt,RoFormerPreTrainedModel:()=>Ye,RobertaForMaskedLM:()=>kn,RobertaForQuestionAnswering:()=>qn,RobertaForSequenceClassification:()=>pn,RobertaForTokenClassification:()=>st,RobertaModel:()=>mr,RobertaPreTrainedModel:()=>Gt,SamImageSegmentationOutput:()=>Nc,SamModel:()=>Bc,SamPreTrainedModel:()=>Rc,SegformerForImageClassification:()=>ud,SegformerForSemanticSegmentation:()=>cd,SegformerModel:()=>fm,SegformerPreTrainedModel:()=>Ho,Seq2SeqLMOutput:()=>mm,SequenceClassifierOutput:()=>ur,SiglipModel:()=>_o,SiglipPreTrainedModel:()=>ha,SiglipTextModel:()=>cu,SiglipVisionModel:()=>du,SpeechT5ForSpeechToText:()=>td,SpeechT5ForTextToSpeech:()=>ap,SpeechT5HifiGan:()=>tl,SpeechT5Model:()=>ed,SpeechT5PreTrainedModel:()=>el,SqueezeBertForMaskedLM:()=>co,SqueezeBertForQuestionAnswering:()=>Mi,SqueezeBertForSequenceClassification:()=>di,SqueezeBertModel:()=>Ss,SqueezeBertPreTrainedModel:()=>Bi,StableLmForCausalLM:()=>dd,StableLmModel:()=>ll,StableLmPreTrainedModel:()=>al,Starcoder2ForCausalLM:()=>il,Starcoder2Model:()=>js,Starcoder2PreTrainedModel:()=>nl,Swin2SRForImageSuperResolution:()=>La,Swin2SRModel:()=>xc,Swin2SRPreTrainedModel:()=>Da,SwinForImageClassification:()=>bc,SwinModel:()=>vc,SwinPreTrainedModel:()=>Oa,T5ForConditionalGeneration:()=>No,T5Model:()=>Bo,T5PreTrainedModel:()=>Zi,TableTransformerForObjectDetection:()=>hc,TableTransformerModel:()=>pc,TableTransformerObjectDetectionOutput:()=>mc,TableTransformerPreTrainedModel:()=>Ia,TokenClassifierOutput:()=>dn,TrOCRForCausalLM:()=>nd,TrOCRPreTrainedModel:()=>rd,UniSpeechForCTC:()=>Gc,UniSpeechForSequenceClassification:()=>qc,UniSpeechModel:()=>Qa,UniSpeechPreTrainedModel:()=>vo,UniSpeechSatForAudioFrameClassification:()=>Ds,UniSpeechSatForCTC:()=>Xa,UniSpeechSatForSequenceClassification:()=>Hc,UniSpeechSatModel:()=>Os,UniSpeechSatPreTrainedModel:()=>Go,ViTForImageClassification:()=>qu,ViTModel:()=>Gu,ViTPreTrainedModel:()=>yo,VisionEncoderDecoderModel:()=>fa,VitMatteForImageMatting:()=>Xu,VitMattePreTrainedModel:()=>Qu,VitsModel:()=>sl,VitsModelOutput:()=>Mp,VitsPreTrainedModel:()=>lp,Wav2Vec2BertForCTC:()=>Rs,Wav2Vec2BertForSequenceClassification:()=>Kc,Wav2Vec2BertModel:()=>Ya,Wav2Vec2BertPreTrainedModel:()=>Ls,Wav2Vec2ForAudioFrameClassification:()=>Ui,Wav2Vec2ForCTC:()=>ip,Wav2Vec2ForSequenceClassification:()=>ji,Wav2Vec2Model:()=>Wc,Wav2Vec2PreTrainedModel:()=>Ni,WavLMForAudioFrameClassification:()=>Jc,WavLMForCTC:()=>Ja,WavLMForSequenceClassification:()=>Yc,WavLMForXVector:()=>Zc,WavLMModel:()=>Xc,WavLMPreTrainedModel:()=>Si,WeSpeakerResNetModel:()=>Ka,WeSpeakerResNetPreTrainedModel:()=>_n,WhisperForConditionalGeneration:()=>da,WhisperModel:()=>Vt,WhisperPreTrainedModel:()=>gt,XLMForQuestionAnswering:()=>gn,XLMForSequenceClassification:()=>Yt,XLMForTokenClassification:()=>Bn,XLMModel:()=>an,XLMPreTrainedModel:()=>xr,XLMRobertaForMaskedLM:()=>Ct,XLMRobertaForQuestionAnswering:()=>Gr,XLMRobertaForSequenceClassification:()=>wr,XLMRobertaForTokenClassification:()=>zr,XLMRobertaModel:()=>kr,XLMRobertaPreTrainedModel:()=>Tr,XLMWithLMHeadModel:()=>$n,XVectorOutput:()=>Jd,YolosForObjectDetection:()=>Dc,YolosModel:()=>Oc,YolosObjectDetectionOutput:()=>Lc,YolosPreTrainedModel:()=>Wa});var o=n("./src/configs.js"),a=n("./src/backends/onnx.js"),l=n("./src/utils/dtypes.js"),f=n("./src/utils/generic.js"),_=n("./src/utils/core.js"),h=n("./src/utils/hub.js"),g=n("./src/generation/logits_process.js"),M=n("./src/generation/configuration_utils.js"),w=n("./src/utils/tensor.js"),C=n("./src/utils/maths.js"),k=n("./src/generation/stopping_criteria.js"),z=n("./src/generation/logits_sampler.js"),S=n("./src/env.js"),P=n("./src/models/whisper/generation_whisper.js"),y=n("./src/models/whisper/common_whisper.js");const x={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,MaskGeneration:5,ImageTextToText:6,Musicgen:7},I=new Map,U=new Map,O=new Map;async function N(V,G,ie){let Ee=ie.device;Ee&&typeof Ee!="string"&&(Ee.hasOwnProperty(G)?Ee=Ee[G]:(console.warn(`device not specified for "${G}". Using the default device.`),Ee=null));const Ze=Ee??(S.apis.IS_NODE_ENV?"cpu":"wasm"),it=(0,a.deviceToExecutionProviders)(Ze);let _t=ie.dtype;typeof _t!="string"&&(_t&&_t.hasOwnProperty(G)?_t=_t[G]:(_t=l.DEFAULT_DEVICE_DTYPE_MAPPING[Ze]??l.DATA_TYPES.fp32,console.warn(`dtype not specified for "${G}". Using the default dtype (${_t}) for this device (${Ze}).`)));const Et=_t;if(l.DEFAULT_DTYPE_SUFFIX_MAPPING.hasOwnProperty(Et)){if(Et===l.DATA_TYPES.fp16&&Ze==="webgpu"&&!await(0,l.isWebGpuFp16Supported)())throw new Error(`The device (${Ze}) does not support fp16.`)}else throw new Error(`Invalid dtype: ${Et}. Should be one of: ${Object.keys(l.DATA_TYPES).join(", ")}`);const Wt=l.DEFAULT_DTYPE_SUFFIX_MAPPING[Et],cr=`${ie.subfolder??""}/${G}${Wt}.onnx`,sr={...ie.session_options};sr.executionProviders??(sr.executionProviders=it);const $r=(0,h.getModelFile)(V,cr,!0,ie);let dr=[];if(ie.use_external_data_format&&(ie.use_external_data_format===!0||typeof ie.use_external_data_format=="object"&&ie.use_external_data_format.hasOwnProperty(G)&&ie.use_external_data_format[G]===!0)){if(S.apis.IS_NODE_ENV)throw new Error("External data format is not yet supported in Node.js");const fr=`${G}${Wt}.onnx_data`,gr=`${ie.subfolder??""}/${fr}`;dr.push(new Promise(async(br,Dr)=>{const En=await(0,h.getModelFile)(V,gr,!0,ie);br({path:fr,data:En})}))}else sr.externalData!==void 0&&(dr=sr.externalData.map(async fr=>{if(typeof fr.data=="string"){const gr=await(0,h.getModelFile)(V,fr.data,!0,ie);return{...fr,data:gr}}return fr}));if(dr.length>0&&(sr.externalData=await Promise.all(dr)),Ze==="webgpu"){const fr=(0,o.getKeyValueShapes)(ie.config,{prefix:"present"});if(Object.keys(fr).length>0&&!(0,a.isONNXProxy)()){const gr={};for(const br in fr)gr[br]="gpu-buffer";sr.preferredOutputLocation=gr}}return{buffer:await $r,session_options:sr}}async function j(V,G,ie){return Object.fromEntries(await Promise.all(Object.keys(G).map(async Ee=>{const{buffer:Ze,session_options:it}=await N(V,G[Ee],ie),_t=await(0,a.createInferenceSession)(Ze,it);return[Ee,_t]})))}function D(V,G){const ie=Object.create(null),Ee=[];for(const _t of V.inputNames){const Et=G[_t];if(!(Et instanceof w.Tensor)){Ee.push(_t);continue}ie[_t]=(0,a.isONNXProxy)()?Et.clone():Et}if(Ee.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${Ee.join(", ")}.`);const Ze=Object.keys(G).length,it=V.inputNames.length;if(Ze>it){let _t=Object.keys(G).filter(Et=>!V.inputNames.includes(Et));console.warn(`WARNING: Too many inputs were provided (${Ze} > ${it}). The following inputs will be ignored: "${_t.join(", ")}".`)}return ie}async function Y(V,G){const ie=D(V,G);try{const Ee=Object.fromEntries(Object.entries(ie).map(([it,_t])=>[it,_t.ort_tensor]));let Ze=await V.run(Ee);return Ze=de(Ze),Ze}catch(Ee){throw console.error(`An error occurred during model execution: "${Ee}".`),console.error("Inputs given to model:",ie),Ee}}function de(V){for(let G in V)(0,a.isONNXTensor)(V[G])?V[G]=new w.Tensor(V[G]):typeof V[G]=="object"&&de(V[G]);return V}function Ce(V){if(V instanceof w.Tensor)return V;if(V.length===0)throw Error("items must be non-empty");if(Array.isArray(V[0])){if(V.some(G=>G.length!==V[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 w.Tensor("int64",BigInt64Array.from(V.flat().map(G=>BigInt(G))),[V.length,V[0].length])}else return new w.Tensor("int64",BigInt64Array.from(V.map(G=>BigInt(G))),[1,V.length])}function ee(V){return new w.Tensor("bool",[V],[1])}async function ye(V,G){let{encoder_outputs:ie,input_ids:Ee,decoder_input_ids:Ze,...it}=G;if(!ie){const Et=(0,_.pick)(G,V.sessions.model.inputNames);ie=(await R(V,Et)).last_hidden_state}return it.input_ids=Ze,it.encoder_hidden_states=ie,V.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(it.encoder_attention_mask=G.attention_mask),await Me(V,it,!0)}async function R(V,G){const ie=V.sessions.model,Ee=(0,_.pick)(G,ie.inputNames);if(ie.inputNames.includes("inputs_embeds")&&!Ee.inputs_embeds){if(!G.input_ids)throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");Ee.inputs_embeds=await V.encode_text({input_ids:G.input_ids})}return ie.inputNames.includes("token_type_ids")&&!Ee.token_type_ids&&(Ee.token_type_ids=new w.Tensor("int64",new BigInt64Array(Ee.input_ids.data.length),Ee.input_ids.dims)),await Y(ie,Ee)}async function Me(V,G,ie=!1){const Ee=V.sessions[ie?"decoder_model_merged":"model"],{past_key_values:Ze,...it}=G;Ee.inputNames.includes("use_cache_branch")&&(it.use_cache_branch=ee(!!Ze)),Ee.inputNames.includes("position_ids")&&it.attention_mask&&!it.position_ids&&(it.position_ids=ge(it,Ze)),V.addPastKeyValues(it,Ze);const _t=(0,_.pick)(it,Ee.inputNames);return await Y(Ee,_t)}async function Qe(V,{input_ids:G=null,attention_mask:ie=null,pixel_values:Ee=null,position_ids:Ze=null,inputs_embeds:it=null,past_key_values:_t=null,generation_config:Et=null,logits_processor:Wt=null,...cr}){if(!it){if(it=await V.encode_text({input_ids:G}),Ee&&G.dims[1]!==1){const $r=await V.encode_image({pixel_values:Ee});({inputs_embeds:it,attention_mask:ie}=V._merge_input_ids_with_image_features({image_features:$r,inputs_embeds:it,input_ids:G,attention_mask:ie}))}else if(_t&&Ee&&G.dims[1]===1){const $r=G.dims[1],dr=Object.values(_t)[0].dims.at(-2);ie=(0,w.cat)([(0,w.ones)([G.dims[0],dr]),ie.slice(null,[ie.dims[1]-$r,ie.dims[1]])],1)}}return await Me(V,{inputs_embeds:it,past_key_values:_t,attention_mask:ie,position_ids:Ze,generation_config:Et,logits_processor:Wt},!0)}function ge(V,G=null){const{input_ids:ie,inputs_embeds:Ee,attention_mask:Ze}=V,[it,_t]=Ze.dims,Et=new BigInt64Array(Ze.data.length);for(let cr=0;crit.dims[1])){if(ZeEt==V.config.image_token_index)){const Et=V.config.num_image_tokens;if(!Et)throw new Error("`num_image_tokens` is missing in the model configuration.");const Wt=it.dims[1]-(Ze-Et);ie.input_ids=it.slice(null,[-Wt,null]),ie.attention_mask=(0,w.ones)([1,Ze+Wt])}}}return ie}function ae(V,G,ie,Ee){return ie.past_key_values&&(G=G.map(Ze=>[Ze.at(-1)])),{...ie,decoder_input_ids:Ce(G)}}function Se(V,...G){return V.config.is_encoder_decoder?ae(V,...G):Q(V,...G)}class X extends f.Callable{constructor(ie,Ee){super();qe(this,"main_input_name","input_ids");qe(this,"forward_params",["input_ids","attention_mask"]);this.config=ie,this.sessions=Ee;const Ze=O.get(this.constructor),it=I.get(Ze);switch(this.can_generate=!1,this._forward=null,this._prepare_inputs_for_generation=null,it){case x.DecoderOnly:this.can_generate=!0,this._forward=Me,this._prepare_inputs_for_generation=Q;break;case x.Seq2Seq:case x.Vision2Seq:case x.Musicgen:this.can_generate=!0,this._forward=ye,this._prepare_inputs_for_generation=ae;break;case x.EncoderDecoder:this._forward=ye;break;case x.ImageTextToText:this.can_generate=!0,this._forward=Qe,this._prepare_inputs_for_generation=Se;break;default:this._forward=R;break}this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){var Ee;const ie=[];for(const Ze of Object.values(this.sessions))(Ee=Ze==null?void 0:Ze.handler)!=null&&Ee.dispose&&ie.push(Ze.handler.dispose());return await Promise.all(ie)}static async from_pretrained(ie,{progress_callback:Ee=null,config:Ze=null,cache_dir:it=null,local_files_only:_t=!1,revision:Et="main",model_file_name:Wt=null,subfolder:cr="onnx",device:sr=null,dtype:$r=null,use_external_data_format:dr=null,session_options:_r={}}={}){let fr={progress_callback:Ee,config:Ze,cache_dir:it,local_files_only:_t,revision:Et,model_file_name:Wt,subfolder:cr,device:sr,dtype:$r,use_external_data_format:dr,session_options:_r};const gr=O.get(this),br=I.get(gr);Ze=fr.config=await o.AutoConfig.from_pretrained(ie,fr);let Dr;if(br===x.DecoderOnly)Dr=await Promise.all([j(ie,{model:fr.model_file_name??"model"},fr),(0,h.getModelJSON)(ie,"generation_config.json",!1,fr)]);else if(br===x.Seq2Seq||br===x.Vision2Seq)Dr=await Promise.all([j(ie,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},fr),(0,h.getModelJSON)(ie,"generation_config.json",!1,fr)]);else if(br===x.MaskGeneration)Dr=await Promise.all([j(ie,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},fr)]);else if(br===x.EncoderDecoder)Dr=await Promise.all([j(ie,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},fr)]);else if(br===x.ImageTextToText){const En={embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};Ze.is_encoder_decoder&&(En.model="encoder_model"),Dr=await Promise.all([j(ie,En,fr),(0,h.getModelJSON)(ie,"generation_config.json",!1,fr)])}else br===x.Musicgen?Dr=await Promise.all([j(ie,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},fr),(0,h.getModelJSON)(ie,"generation_config.json",!1,fr)]):(br!==x.EncoderOnly&&console.warn(`Model type for '${gr??(Ze==null?void 0:Ze.model_type)}' not found, assuming encoder-only architecture. Please report this at https://github.com/xenova/transformers.js/issues/new/choose.`),Dr=await Promise.all([j(ie,{model:fr.model_file_name??"model"},fr)]));return new this(Ze,...Dr)}async _call(ie){return await this.forward(ie)}async forward(ie){return await this._forward(this,ie)}_get_logits_warper(ie){const Ee=new g.LogitsProcessorList;return ie.temperature!==null&&ie.temperature!==1&&Ee.push(new g.TemperatureLogitsWarper(ie.temperature)),ie.top_k!==null&&ie.top_k!==0&&Ee.push(new g.TopKLogitsWarper(ie.top_k)),ie.top_p!==null&&ie.top_p<1&&Ee.push(new g.TopPLogitsWarper(ie.top_p)),Ee}_get_logits_processor(ie,Ee,Ze=null){const it=new g.LogitsProcessorList;if(ie.repetition_penalty!==null&&ie.repetition_penalty!==1&&it.push(new g.RepetitionPenaltyLogitsProcessor(ie.repetition_penalty)),ie.no_repeat_ngram_size!==null&&ie.no_repeat_ngram_size>0&&it.push(new g.NoRepeatNGramLogitsProcessor(ie.no_repeat_ngram_size)),ie.bad_words_ids!==null&&it.push(new g.NoBadWordsLogitsProcessor(ie.bad_words_ids,ie.eos_token_id)),ie.min_length!==null&&ie.eos_token_id!==null&&ie.min_length>0&&it.push(new g.MinLengthLogitsProcessor(ie.min_length,ie.eos_token_id)),ie.min_new_tokens!==null&&ie.eos_token_id!==null&&ie.min_new_tokens>0&&it.push(new g.MinNewTokensLengthLogitsProcessor(Ee,ie.min_new_tokens,ie.eos_token_id)),ie.forced_bos_token_id!==null&&it.push(new g.ForcedBOSTokenLogitsProcessor(ie.forced_bos_token_id)),ie.forced_eos_token_id!==null&&it.push(new g.ForcedEOSTokenLogitsProcessor(ie.max_length,ie.forced_eos_token_id)),ie.begin_suppress_tokens!==null){const _t=Ee>1||ie.forced_bos_token_id===null?Ee:Ee+1;it.push(new g.SuppressTokensAtBeginLogitsProcessor(ie.begin_suppress_tokens,_t))}return ie.guidance_scale!==null&&ie.guidance_scale>1&&it.push(new g.ClassifierFreeGuidanceLogitsProcessor(ie.guidance_scale)),Ze!==null&&it.extend(Ze),it}_prepare_generation_config(ie,Ee,Ze=M.GenerationConfig){const it={...this.config};for(const Et of["decoder","generator","text_config"])Et in it&&Object.assign(it,it[Et]);const _t=new Ze(it);return"generation_config"in this&&Object.assign(_t,this.generation_config),ie&&Object.assign(_t,ie),Ee&&Object.assign(_t,(0,_.pick)(Ee,Object.getOwnPropertyNames(_t))),_t}_get_stopping_criteria(ie,Ee=null){const Ze=new k.StoppingCriteriaList;return ie.max_length!==null&&Ze.push(new k.MaxLengthCriteria(ie.max_length,this.config.max_position_embeddings??null)),ie.eos_token_id!==null&&Ze.push(new k.EosTokenCriteria(ie.eos_token_id)),Ee&&Ze.extend(Ee),Ze}_validate_model_class(){if(!this.can_generate){const ie=[Vs,_l,gl,Us],Ee=O.get(this.constructor),Ze=new Set,it=this.config.model_type;for(const Et of ie){const Wt=Et.get(it);Wt&&Ze.add(Wt[0])}let _t=`The current model class (${Ee}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw Ze.size>0&&(_t+=` Please use the following class instead: ${[...Ze].join(", ")}`),Error(_t)}}prepare_inputs_for_generation(...ie){return this._prepare_inputs_for_generation(this,...ie)}_update_model_kwargs_for_generation({generated_input_ids:ie,outputs:Ee,model_inputs:Ze,is_encoder_decoder:it}){return Ze.past_key_values=this.getPastKeyValues(Ee,Ze.past_key_values),Ze.input_ids=new w.Tensor("int64",ie.flat(),[ie.length,1]),it||(Ze.attention_mask=(0,w.cat)([Ze.attention_mask,(0,w.ones)([Ze.attention_mask.dims[0],1])],1)),Ze.position_ids=null,Ze}_prepare_model_inputs({inputs:ie,bos_token_id:Ee,model_kwargs:Ze}){const it=(0,_.pick)(Ze,this.forward_params),_t=this.main_input_name;if(_t in it){if(ie)throw new Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else it[_t]=ie;return{inputs_tensor:it[_t],model_inputs:it,model_input_name:_t}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:ie,model_inputs:Ee,model_input_name:Ze,generation_config:it}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!Ee.inputs_embeds&&"_prepare_inputs_embeds"in this){const{input_ids:Et,pixel_values:Wt,attention_mask:cr,...sr}=Ee,$r=await this._prepare_inputs_embeds(Ee);Ee={...sr,...(0,_.pick)($r,["inputs_embeds","attention_mask"])}}let{last_hidden_state:_t}=await R(this,Ee);if(it.guidance_scale!==null&&it.guidance_scale>1)_t=(0,w.cat)([_t,(0,w.full_like)(_t,0)],0),"attention_mask"in Ee&&(Ee.attention_mask=(0,w.cat)([Ee.attention_mask,(0,w.zeros_like)(Ee.attention_mask)],0));else if(Ee.decoder_input_ids){const Et=Ce(Ee.decoder_input_ids).dims[0];if(Et!==_t.dims[0]){if(_t.dims[0]!==1)throw new Error(`The encoder outputs have a different batch size (${_t.dims[0]}) than the decoder inputs (${Et}).`);_t=(0,w.cat)(Array.from({length:Et},()=>_t),0)}}return Ee.encoder_outputs=_t,Ee}_prepare_decoder_input_ids_for_generation({batch_size:ie,model_input_name:Ee,model_kwargs:Ze,decoder_start_token_id:it,bos_token_id:_t,generation_config:Et}){let{decoder_input_ids:Wt,...cr}=Ze;if(Wt)Array.isArray(Wt[0])||(Wt=Array.from({length:ie},()=>Wt));else if(it??(it=_t),this.config.model_type==="musicgen")Wt=Array.from({length:ie*this.config.decoder.num_codebooks},()=>[it]);else if(Array.isArray(it)){if(it.length!==ie)throw new Error(`\`decoder_start_token_id\` expcted to have length ${ie} but got ${it.length}`);Wt=it}else Wt=Array.from({length:ie},()=>[it]);return Wt=Ce(Wt),Ze.decoder_attention_mask=(0,w.ones_like)(Wt),{input_ids:Wt,model_inputs:cr}}async generate({inputs:ie=null,generation_config:Ee=null,logits_processor:Ze=null,stopping_criteria:it=null,streamer:_t=null,...Et}){this._validate_model_class(),Ee=this._prepare_generation_config(Ee,Et);let{inputs_tensor:Wt,model_inputs:cr,model_input_name:sr}=this._prepare_model_inputs({inputs:ie,model_kwargs:Et});const $r=this.config.is_encoder_decoder;$r&&("encoder_outputs"in cr||(cr=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:Wt,model_inputs:cr,model_input_name:sr,generation_config:Ee})));let dr;$r?{input_ids:dr,model_inputs:cr}=this._prepare_decoder_input_ids_for_generation({batch_size:cr[sr].dims.at(0),model_input_name:sr,model_kwargs:cr,decoder_start_token_id:Ee.decoder_start_token_id,bos_token_id:Ee.bos_token_id,generation_config:Ee}):dr=cr[sr];let _r=dr.dims.at(-1);Ee.max_new_tokens!==null&&(Ee.max_length=_r+Ee.max_new_tokens);const fr=this._get_logits_processor(Ee,_r,Ze),gr=this._get_stopping_criteria(Ee,it),br=cr[sr].dims.at(0),Dr=z.LogitsSampler.getSampler(Ee),En=new Array(br).fill(0),An=dr.tolist();_t&&_t.put(An);let Ei=null,vn={};for(;;){cr=this.prepare_inputs_for_generation(An,cr,Ee);const bn=await this.forward(cr);if(Ee.output_attentions&&Ee.return_dict_in_generate){const pi=this.getAttentions(bn);for(const Yo in pi)Yo in vn||(vn[Yo]=[]),vn[Yo].push(pi[Yo])}const Ws=bn.logits.slice(null,-1,null),Gs=fr(An,Ws),Ml=[];for(let pi=0;pipi)){Ee.return_dict_in_generate&&(Ei=this.getPastKeyValues(bn,cr.past_key_values,!1));break}cr=this._update_model_kwargs_for_generation({generated_input_ids:Ml,outputs:bn,model_inputs:cr,is_encoder_decoder:$r})}_t&&_t.end();const ln=new w.Tensor("int64",An.flat(),[An.length,An[0].length]);return Ee.return_dict_in_generate?{sequences:ln,past_key_values:Ei,...vn}:ln}getPastKeyValues(ie,Ee,Ze=!0){const it=Object.create(null);for(const _t in ie)if(_t.startsWith("present")){const Et=_t.replace("present","past_key_values");if(Ee&&_t.includes("encoder"))it[Et]=Ee[Et];else{if(Ze&&Ee){const Wt=Ee[Et];Wt.location==="gpu-buffer"&&Wt.dispose()}it[Et]=ie[_t]}}return it}getAttentions(ie){const Ee={};for(const Ze of["cross_attentions","encoder_attentions","decoder_attentions"])for(const it in ie)it.startsWith(Ze)&&(Ze in Ee||(Ee[Ze]=[]),Ee[Ze].push(ie[it]));return Ee}addPastKeyValues(ie,Ee){if(Ee)Object.assign(ie,Ee);else{const Ze=this.custom_config.kv_cache_dtype??"float32",it=Ze==="float16"?new Uint16Array:[],_t=(0,o.getKeyValueShapes)(this.config);for(const Et in _t)ie[Et]=new w.Tensor(Ze,it,_t[Et])}}async encode_image({pixel_values:ie}){const Ee=(await Y(this.sessions.vision_encoder,{pixel_values:ie})).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 (${Ee.dims[1]}).`),this.config.num_image_tokens=Ee.dims[1]),Ee}async encode_text({input_ids:ie}){return(await Y(this.sessions.embed_tokens,{input_ids:ie})).inputs_embeds}}class me{}class Ke extends me{constructor({last_hidden_state:G,hidden_states:ie=null,attentions:Ee=null}){super(),this.last_hidden_state=G,this.hidden_states=ie,this.attentions=Ee}}class De extends X{}class Be extends De{}class We extends De{async _call(G){return new yn(await super._call(G))}}class ot extends De{async _call(G){return new ur(await super._call(G))}}class dt extends De{async _call(G){return new dn(await super._call(G))}}class Ge extends De{async _call(G){return new wn(await super._call(G))}}class Te extends X{}class je extends Te{}class Ye extends X{}class tt extends Ye{}class A extends Ye{async _call(G){return new yn(await super._call(G))}}class Ae extends Ye{async _call(G){return new ur(await super._call(G))}}class $e extends Ye{async _call(G){return new dn(await super._call(G))}}class se extends Ye{async _call(G){return new wn(await super._call(G))}}class te extends X{}class we extends te{}class B extends te{async _call(G){return new yn(await super._call(G))}}class J extends te{async _call(G){return new ur(await super._call(G))}}class L extends te{async _call(G){return new dn(await super._call(G))}}class ue extends te{async _call(G){return new wn(await super._call(G))}}class le extends X{}class ke extends le{}class Ne extends le{async _call(G){return new yn(await super._call(G))}}class ut extends le{async _call(G){return new ur(await super._call(G))}}class Je extends le{async _call(G){return new dn(await super._call(G))}}class Ve extends le{async _call(G){return new wn(await super._call(G))}}class Z extends X{}class ve extends Z{}class Re extends Z{async _call(G){return new yn(await super._call(G))}}class He extends Z{async _call(G){return new ur(await super._call(G))}}class Xe extends Z{async _call(G){return new dn(await super._call(G))}}class rt extends Z{async _call(G){return new wn(await super._call(G))}}class ft extends X{}class ht extends ft{}class Mt extends ft{async _call(G){return new yn(await super._call(G))}}class wt extends ft{async _call(G){return new ur(await super._call(G))}}class St extends ft{async _call(G){return new dn(await super._call(G))}}class Rt extends ft{async _call(G){return new wn(await super._call(G))}}class at extends X{}class Ot extends at{}class Ut extends at{async _call(G){return new yn(await super._call(G))}}class Kt extends at{async _call(G){return new ur(await super._call(G))}}class Qt extends at{async _call(G){return new dn(await super._call(G))}}class Jt extends at{async _call(G){return new wn(await super._call(G))}}class qt extends X{}class Er extends qt{}class Qr extends qt{async _call(G){return new ur(await super._call(G))}}class Cr extends qt{async _call(G){return new dn(await super._call(G))}}class mt extends qt{async _call(G){return new wn(await super._call(G))}}class Pt extends qt{async _call(G){return new yn(await super._call(G))}}class Bt extends X{}class sn extends Bt{}class Li extends Bt{async _call(G){return new yn(await super._call(G))}}class bi extends Bt{async _call(G){return new ur(await super._call(G))}}class Nr extends Bt{async _call(G){return new dn(await super._call(G))}}class mn extends X{}class Wr extends mn{}class ci extends mn{async _call(G){return new yn(await super._call(G))}}class Fr extends mn{async _call(G){return new ur(await super._call(G))}}class Ri extends mn{async _call(G){return new wn(await super._call(G))}}class xi extends X{}class ks extends xi{}class Oo extends xi{async _call(G){return new yn(await super._call(G))}}class Do extends xi{async _call(G){return new ur(await super._call(G))}}class Lo extends xi{async _call(G){return new dn(await super._call(G))}}class Ro extends xi{async _call(G){return new wn(await super._call(G))}}class Bi extends X{}class Ss extends Bi{}class co extends Bi{async _call(G){return new yn(await super._call(G))}}class di extends Bi{async _call(G){return new ur(await super._call(G))}}class Mi extends Bi{async _call(G){return new wn(await super._call(G))}}class Ti extends X{}class Yi extends Ti{}class fo extends Ti{async _call(G){return new ur(await super._call(G))}}class po extends Ti{async _call(G){return new wn(await super._call(G))}}class Xt extends Ti{async _call(G){return new yn(await super._call(G))}}class Zi extends X{constructor(ie,Ee,Ze){super(ie,Ee);qe(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"]);this.generation_config=Ze}}class Bo extends Zi{}class No extends Zi{}class ho extends X{constructor(G,ie,Ee){super(G,ie),this.generation_config=Ee}}class jo extends ho{}class Uo extends ho{}class mo extends X{constructor(G,ie,Ee){super(G,ie),this.generation_config=Ee}}class Vo extends mo{}class Br extends mo{}class Rn extends X{constructor(G,ie,Ee){super(G,ie),this.generation_config=Ee}}class Ue extends Rn{}class W extends Rn{}class fe extends Rn{async _call(G){return new ur(await super._call(G))}}class Pe extends X{constructor(G,ie,Ee){super(G,ie),this.generation_config=Ee}}class ze extends Pe{}class Oe extends Pe{}class nt extends Pe{async _call(G){return new ur(await super._call(G))}}class xt extends Pe{}class kt extends X{constructor(G,ie,Ee){super(G,ie),this.generation_config=Ee}}class Tt extends kt{}class At extends kt{}class Zt extends X{constructor(G,ie,Ee){super(G,ie),this.generation_config=Ee}}class Pr extends Zt{}class rr extends Zt{}class Gt extends X{}class mr extends Gt{}class kn extends Gt{async _call(G){return new yn(await super._call(G))}}class pn extends Gt{async _call(G){return new ur(await super._call(G))}}class st extends Gt{async _call(G){return new dn(await super._call(G))}}class qn extends Gt{async _call(G){return new wn(await super._call(G))}}class xr extends X{}class an extends xr{}class $n extends xr{async _call(G){return new yn(await super._call(G))}}class Yt extends xr{async _call(G){return new ur(await super._call(G))}}class Bn extends xr{async _call(G){return new dn(await super._call(G))}}class gn extends xr{async _call(G){return new wn(await super._call(G))}}class Tr extends X{}class kr extends Tr{}class Ct extends Tr{async _call(G){return new yn(await super._call(G))}}class wr extends Tr{async _call(G){return new ur(await super._call(G))}}class zr extends Tr{async _call(G){return new dn(await super._call(G))}}class Gr extends Tr{async _call(G){return new wn(await super._call(G))}}class Nn extends X{}class Dt extends Nn{}class Es extends Nn{}class gt extends X{constructor(ie,Ee,Ze){super(ie,Ee);qe(this,"requires_attention_mask",!1);qe(this,"main_input_name","input_features");qe(this,"forward_params",["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"]);this.generation_config=Ze}}class Vt extends gt{}class da extends gt{_prepare_generation_config(G,ie){return super._prepare_generation_config(G,ie,P.WhisperGenerationConfig)}_retrieve_init_tokens(G){const ie=[G.decoder_start_token_id];let Ee=G.language;const Ze=G.task;if(G.is_multilingual){Ee||(console.warn("No language specified - defaulting to English (en)."),Ee="en");const _t=`<|${(0,y.whisper_language_to_code)(Ee)}|>`;ie.push(G.lang_to_id[_t]),ie.push(G.task_to_id[Ze??"transcribe"])}else if(Ee||Ze)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!G.return_timestamps&&G.no_timestamps_token_id&&ie.at(-1)!==G.no_timestamps_token_id?ie.push(G.no_timestamps_token_id):G.return_timestamps&&ie.at(-1)===G.no_timestamps_token_id&&(console.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),ie.pop()),ie.filter(it=>it!=null)}async generate({inputs:G=null,generation_config:ie=null,logits_processor:Ee=null,stopping_criteria:Ze=null,...it}){ie=this._prepare_generation_config(ie,it);const _t=it.decoder_input_ids??this._retrieve_init_tokens(ie);if(ie.return_timestamps&&(Ee??(Ee=new g.LogitsProcessorList),Ee.push(new g.WhisperTimeStampLogitsProcessor(ie,_t))),ie.begin_suppress_tokens&&(Ee??(Ee=new g.LogitsProcessorList),Ee.push(new g.SuppressTokensAtBeginLogitsProcessor(ie.begin_suppress_tokens,_t.length))),ie.return_token_timestamps){if(!ie.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.");ie.task==="translate"&&console.warn("Token-level timestamps may not be reliable for task 'translate'."),ie.output_attentions=!0,ie.return_dict_in_generate=!0}const Et=await super.generate({inputs:G,generation_config:ie,logits_processor:Ee,decoder_input_ids:_t,...it});return ie.return_token_timestamps&&(Et.token_timestamps=this._extract_token_timestamps(Et,ie.alignment_heads,ie.num_frames)),Et}_extract_token_timestamps(G,ie,Ee=null,Ze=.02){if(!G.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`.");Ee==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 it=this.config.median_filter_width;it===void 0&&(console.warn("Model config has no `median_filter_width`, using default value of 7."),it=7);const _t=G.cross_attentions,Et=Array.from({length:this.config.decoder_layers},(gr,br)=>(0,w.cat)(_t.map(Dr=>Dr[br]),2)),Wt=(0,w.stack)(ie.map(([gr,br])=>{if(gr>=Et.length)throw new Error(`Layer index ${gr} is out of bounds for cross attentions (length ${Et.length}).`);return Ee?Et[gr].slice(null,br,null,[0,Ee]):Et[gr].slice(null,br)})).transpose(1,0,2,3),[cr,sr]=(0,w.std_mean)(Wt,-2,0,!0),$r=Wt.clone();for(let gr=0;gr<$r.dims[0];++gr){const br=$r[gr];for(let Dr=0;DrDr[bn+1]-Dr[bn]),Ei=(0,_.mergeArrays)([1],An).map(ln=>!!ln),vn=[];for(let ln=0;lndr.findIndex(_r=>_r==it)),Wt=Et.every(dr=>dr===-1),cr=Et.every(dr=>dr!==-1);if(!Wt&&!cr)throw new Error("Every input should contain either 0 or 1 image token.");if(Wt)return{inputs_embeds:G,attention_mask:Ze};const sr=[],$r=[];for(let dr=0;drit*_t,1);G.input_labels=new w.Tensor("int64",new BigInt64Array(Ze).fill(1n),Ee)}const ie={image_embeddings:G.image_embeddings,image_positional_embeddings:G.image_positional_embeddings};return G.input_points&&(ie.input_points=G.input_points),G.input_labels&&(ie.input_labels=G.input_labels),G.input_boxes&&(ie.input_boxes=G.input_boxes),await Y(this.sessions.prompt_encoder_mask_decoder,ie)}async _call(G){return new Nc(await super._call(G))}}class Nc extends me{constructor({iou_scores:G,pred_masks:ie}){super(),this.iou_scores=G,this.pred_masks=ie}}class Ga extends X{constructor(G,ie,Ee){super(G,ie),this.generation_config=Ee}}class np extends Ga{}class jc extends Ga{}class qa extends X{constructor(G,ie,Ee){super(G,ie),this.generation_config=Ee}}class Uc extends qa{}class Vc extends qa{}class Ni extends X{}class Wc extends Ni{}class ip extends Ni{async _call(G){return new Ji(await super._call(G))}}class ji extends Ni{async _call(G){return new ur(await super._call(G))}}class Ui extends Ni{async _call(G){return new dn(await super._call(G))}}class ki extends X{}class Ha extends ki{}class Vi extends ki{async _call(G){return new dn(await super._call(G))}}class _n extends X{}class Ka extends _n{}class vo extends X{}class Qa extends vo{}class Gc extends vo{async _call(G){return new Ji(await super._call(G))}}class qc extends vo{async _call(G){return new ur(await super._call(G))}}class Go extends X{}class Os extends Go{}class Xa extends Go{async _call(G){return new Ji(await super._call(G))}}class Hc extends Go{async _call(G){return new ur(await super._call(G))}}class Ds extends Go{async _call(G){return new dn(await super._call(G))}}class Ls extends X{}class Ya extends Ls{}class Rs extends Ls{async _call(G){return new Ji(await super._call(G))}}class Kc extends Ls{async _call(G){return new ur(await super._call(G))}}class op extends X{}class sp extends Ni{}class Qc extends Ni{async _call(G){return new Ji(await super._call(G))}}class Za extends Ni{async _call(G){return new ur(await super._call(G))}}class Si extends X{}class Xc extends Si{}class Ja extends Si{async _call(G){return new Ji(await super._call(G))}}class Yc extends Si{async _call(G){return new ur(await super._call(G))}}class Zc extends Si{async _call(G){return new Jd(await super._call(G))}}class Jc extends Si{async _call(G){return new dn(await super._call(G))}}class el extends X{constructor(G,ie,Ee){super(G,ie),this.generation_config=Ee}}class ed extends el{}class td extends el{}class ap extends el{async generate_speech(G,ie,{threshold:Ee=.5,minlenratio:Ze=0,maxlenratio:it=20,vocoder:_t=null}={}){const Et={input_ids:G},{encoder_outputs:Wt,encoder_attention_mask:cr}=await R(this,Et),sr=Wt.dims[1]/this.config.reduction_factor,$r=Math.floor(sr*it),dr=Math.floor(sr*Ze),_r=this.config.num_mel_bins;let fr=[],gr=null,br=null,Dr=0;for(;;){++Dr;const Ei=ee(!!br);let vn;br?vn=br.output_sequence_out:vn=new w.Tensor("float32",new Float32Array(_r),[1,1,_r]);let ln={use_cache_branch:Ei,output_sequence:vn,encoder_attention_mask:cr,speaker_embeddings:ie,encoder_hidden_states:Wt};this.addPastKeyValues(ln,gr),br=await Y(this.sessions.decoder_model_merged,ln),gr=this.getPastKeyValues(br,gr);const{prob:bn,spectrum:Ws}=br;if(fr.push(Ws),Dr>=dr&&(Array.from(bn.data).filter(Gs=>Gs>=Ee).length>0||Dr>=$r))break}const En=(0,w.cat)(fr),{waveform:An}=await Y(_t.sessions.model,{spectrogram:En});return{spectrogram:En,waveform:An}}}class tl extends X{constructor(){super(...arguments);qe(this,"main_input_name","spectrogram")}}class rd extends X{constructor(G,ie,Ee){super(G,ie),this.generation_config=Ee}}class nd extends rd{}class rl extends X{constructor(G,ie,Ee){super(G,ie),this.generation_config=Ee}}class Bs extends rl{}class Ns extends rl{}class nl extends X{constructor(G,ie,Ee){super(G,ie),this.generation_config=Ee}}class js extends nl{}class il extends nl{}class ol extends X{constructor(G,ie,Ee){super(G,ie),this.generation_config=Ee}}class id extends ol{}class od extends ol{}class qo extends X{}class sd extends qo{}class ad extends qo{static async from_pretrained(G,ie={}){return ie.model_file_name??(ie.model_file_name="text_model"),super.from_pretrained(G,ie)}}class ld extends qo{static async from_pretrained(G,ie={}){return ie.model_file_name??(ie.model_file_name="audio_model"),super.from_pretrained(G,ie)}}class lp extends X{}class sl extends lp{async _call(G){return new Mp(await super._call(G))}}class Ho extends X{}class fm extends Ho{}class ud extends Ho{}class cd extends Ho{}class al extends X{constructor(G,ie,Ee){super(G,ie),this.generation_config=Ee}}class ll extends al{}class dd extends al{}class ul extends X{}class fd extends ul{}class pd extends ul{async _call(G){return new ur(await super._call(G))}}class cl extends X{}class up extends cl{}class pm extends cl{}class dl extends X{constructor(ie,Ee,Ze){super(ie,Ee);qe(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"]);this.generation_config=Ze}_apply_and_filter_by_delay_pattern_mask(ie){const[Ee,Ze]=ie.dims,it=this.config.decoder.num_codebooks,_t=Ze-it;let Et=0;for(let sr=0;sr0&&_r<=_t&&(ie.data[Et++]=ie.data[sr])}const Wt=Math.floor(Ee/it),cr=Et/(Wt*it);return new w.Tensor(ie.type,ie.data.slice(0,Et),[Wt,it,cr])}prepare_inputs_for_generation(ie,Ee,Ze){let it=structuredClone(ie);for(let Et=0;Et=Wt&&(it[Et][Wt]=BigInt(this.config.decoder.pad_token_id));return Ze.guidance_scale!==null&&Ze.guidance_scale>1&&(it=it.concat(it)),super.prepare_inputs_for_generation(it,Ee,Ze)}async generate(ie){const Ee=await super.generate(ie),Ze=this._apply_and_filter_by_delay_pattern_mask(Ee).unsqueeze_(0),{audio_values:it}=await Y(this.sessions.encodec_decode,{audio_codes:Ze});return it}}class fl extends X{}class hd extends fl{}class cp extends fl{async _call(G){return new ur(await super._call(G))}}class pl extends X{}class md extends pl{}class gd extends pl{async _call(G){return new ur(await super._call(G))}}class hl extends X{}class _d extends hl{}class dp extends hl{async _call(G){return new ur(await super._call(G))}}class Ko extends X{}class Qo extends Ko{}class ml extends Ko{async _call(G){return new ur(await super._call(G))}}class Or{static async from_pretrained(G,{progress_callback:ie=null,config:Ee=null,cache_dir:Ze=null,local_files_only:it=!1,revision:_t="main",model_file_name:Et=null,subfolder:Wt="onnx",device:cr=null,dtype:sr=null,use_external_data_format:$r=null,session_options:dr={}}={}){let _r={progress_callback:ie,config:Ee,cache_dir:Ze,local_files_only:it,revision:_t,model_file_name:Et,subfolder:Wt,device:cr,dtype:sr,use_external_data_format:$r,session_options:dr};if(_r.config=await o.AutoConfig.from_pretrained(G,_r),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);for(let fr of this.MODEL_CLASS_MAPPINGS){const gr=fr.get(_r.config.model_type);if(gr)return await gr[1].from_pretrained(G,_r)}if(this.BASE_IF_FAIL)return console.warn(`Unknown model class "${_r.config.model_type}", attempting to construct from base class.`),await X.from_pretrained(G,_r);throw Error(`Unsupported model type: ${_r.config.model_type}`)}}qe(Or,"MODEL_CLASS_MAPPINGS",null),qe(Or,"BASE_IF_FAIL",!1);const fp=new Map([["bert",["BertModel",Be]],["nomic_bert",["NomicBertModel",je]],["roformer",["RoFormerModel",tt]],["electra",["ElectraModel",ke]],["esm",["EsmModel",sn]],["convbert",["ConvBertModel",we]],["camembert",["CamembertModel",ve]],["deberta",["DebertaModel",ht]],["deberta-v2",["DebertaV2Model",Ot]],["mpnet",["MPNetModel",ks]],["albert",["AlbertModel",Yi]],["distilbert",["DistilBertModel",Er]],["roberta",["RobertaModel",mr]],["xlm",["XLMModel",an]],["xlm-roberta",["XLMRobertaModel",kr]],["clap",["ClapModel",sd]],["clip",["CLIPModel",lu]],["clipseg",["CLIPSegModel",hu]],["chinese_clip",["ChineseCLIPModel",pu]],["siglip",["SiglipModel",_o]],["mobilebert",["MobileBertModel",Wr]],["squeezebert",["SqueezeBertModel",Ss]],["wav2vec2",["Wav2Vec2Model",Wc]],["wav2vec2-bert",["Wav2Vec2BertModel",Ya]],["unispeech",["UniSpeechModel",Qa]],["unispeech-sat",["UniSpeechSatModel",Os]],["hubert",["HubertModel",sp]],["wavlm",["WavLMModel",Xc]],["audio-spectrogram-transformer",["ASTModel",Dt]],["vits",["VitsModel",sl]],["pyannote",["PyAnnoteModel",Ha]],["wespeaker-resnet",["WeSpeakerResNetModel",Ka]],["detr",["DetrModel",ac]],["rt_detr",["RTDetrModel",dc]],["table-transformer",["TableTransformerModel",pc]],["vit",["ViTModel",Gu]],["fastvit",["FastViTModel",Hu]],["mobilevit",["MobileViTModel",Zu]],["mobilevitv2",["MobileViTV2Model",rp]],["owlvit",["OwlViTModel",tc]],["owlv2",["Owlv2Model",nc]],["beit",["BeitModel",oc]],["deit",["DeiTModel",gc]],["convnext",["ConvNextModel",Cc]],["convnextv2",["ConvNextV2Model",Ac]],["dinov2",["Dinov2Model",Fc]],["resnet",["ResNetModel",yc]],["swin",["SwinModel",vc]],["swin2sr",["Swin2SRModel",xc]],["donut-swin",["DonutSwinModel",Ua]],["yolos",["YolosModel",Oc]],["dpt",["DPTModel",Ba]],["glpn",["GLPNModel",kc]],["hifigan",["SpeechT5HifiGan",tl]],["efficientnet",["EfficientNetModel",fd]],["mobilenet_v1",["MobileNetV1Model",hd]],["mobilenet_v2",["MobileNetV2Model",md]],["mobilenet_v3",["MobileNetV3Model",_d]],["mobilenet_v4",["MobileNetV4Model",Qo]]]),pp=new Map([["t5",["T5Model",Bo]],["longt5",["LongT5Model",jo]],["mt5",["MT5Model",Vo]],["bart",["BartModel",Ue]],["mbart",["MBartModel",ze]],["marian",["MarianModel",np]],["whisper",["WhisperModel",Vt]],["m2m_100",["M2M100Model",Uc]],["blenderbot",["BlenderbotModel",Tt]],["blenderbot-small",["BlenderbotSmallModel",Pr]]]),hp=new Map([["bloom",["BloomModel",Nu]],["gpt2",["GPT2Model",gu]],["gptj",["GPTJModel",xu]],["gpt_bigcode",["GPTBigCodeModel",Tu]],["gpt_neo",["GPTNeoModel",yu]],["gpt_neox",["GPTNeoXModel",vu]],["codegen",["CodeGenModel",ku]],["llama",["LlamaModel",ni]],["cohere",["CohereModel",Eu]],["gemma",["GemmaModel",Pu]],["gemma2",["Gemma2Model",Au]],["openelm",["OpenELMModel",Fu]],["qwen2",["Qwen2Model",Ou]],["phi",["PhiModel",Lu]],["phi3",["Phi3Model",Bu]],["mpt",["MptModel",tp]],["opt",["OPTModel",Vu]],["mistral",["MistralModel",Bs]],["starcoder2",["Starcoder2Model",js]],["falcon",["FalconModel",id]],["stablelm",["StableLmModel",ll]]]),Us=new Map([["speecht5",["SpeechT5ForSpeechToText",td]],["whisper",["WhisperForConditionalGeneration",da]]]),yd=new Map([["speecht5",["SpeechT5ForTextToSpeech",ap]]]),wd=new Map([["vits",["VitsModel",sl]],["musicgen",["MusicgenForConditionalGeneration",dl]]]),vd=new Map([["bert",["BertForSequenceClassification",ot]],["roformer",["RoFormerForSequenceClassification",Ae]],["electra",["ElectraForSequenceClassification",ut]],["esm",["EsmForSequenceClassification",bi]],["convbert",["ConvBertForSequenceClassification",J]],["camembert",["CamembertForSequenceClassification",He]],["deberta",["DebertaForSequenceClassification",wt]],["deberta-v2",["DebertaV2ForSequenceClassification",Kt]],["mpnet",["MPNetForSequenceClassification",Do]],["albert",["AlbertForSequenceClassification",fo]],["distilbert",["DistilBertForSequenceClassification",Qr]],["roberta",["RobertaForSequenceClassification",pn]],["xlm",["XLMForSequenceClassification",Yt]],["xlm-roberta",["XLMRobertaForSequenceClassification",wr]],["bart",["BartForSequenceClassification",fe]],["mbart",["MBartForSequenceClassification",nt]],["mobilebert",["MobileBertForSequenceClassification",Fr]],["squeezebert",["SqueezeBertForSequenceClassification",di]]]),mp=new Map([["bert",["BertForTokenClassification",dt]],["roformer",["RoFormerForTokenClassification",$e]],["electra",["ElectraForTokenClassification",Je]],["esm",["EsmForTokenClassification",Nr]],["convbert",["ConvBertForTokenClassification",L]],["camembert",["CamembertForTokenClassification",Xe]],["deberta",["DebertaForTokenClassification",St]],["deberta-v2",["DebertaV2ForTokenClassification",Qt]],["mpnet",["MPNetForTokenClassification",Lo]],["distilbert",["DistilBertForTokenClassification",Cr]],["roberta",["RobertaForTokenClassification",st]],["xlm",["XLMForTokenClassification",Bn]],["xlm-roberta",["XLMRobertaForTokenClassification",zr]]]),gl=new Map([["t5",["T5ForConditionalGeneration",No]],["longt5",["LongT5ForConditionalGeneration",Uo]],["mt5",["MT5ForConditionalGeneration",Br]],["bart",["BartForConditionalGeneration",W]],["mbart",["MBartForConditionalGeneration",Oe]],["marian",["MarianMTModel",jc]],["m2m_100",["M2M100ForConditionalGeneration",Vc]],["blenderbot",["BlenderbotForConditionalGeneration",At]],["blenderbot-small",["BlenderbotSmallForConditionalGeneration",rr]]]),Vs=new Map([["bloom",["BloomForCausalLM",ju]],["gpt2",["GPT2LMHeadModel",_u]],["gptj",["GPTJForCausalLM",Mu]],["gpt_bigcode",["GPTBigCodeForCausalLM",ep]],["gpt_neo",["GPTNeoForCausalLM",wu]],["gpt_neox",["GPTNeoXForCausalLM",bu]],["codegen",["CodeGenForCausalLM",Cs]],["llama",["LlamaForCausalLM",Su]],["cohere",["CohereForCausalLM",Cu]],["gemma",["GemmaForCausalLM",$u]],["gemma2",["Gemma2ForCausalLM",Iu]],["openelm",["OpenELMForCausalLM",zu]],["qwen2",["Qwen2ForCausalLM",Du]],["phi",["PhiForCausalLM",Ru]],["phi3",["Phi3ForCausalLM",Sa]],["mpt",["MptForCausalLM",Uu]],["opt",["OPTForCausalLM",Wu]],["mbart",["MBartForCausalLM",xt]],["mistral",["MistralForCausalLM",Ns]],["starcoder2",["Starcoder2ForCausalLM",il]],["falcon",["FalconForCausalLM",od]],["trocr",["TrOCRForCausalLM",nd]],["stablelm",["StableLmForCausalLM",dd]]]),bd=new Map([["bert",["BertForMaskedLM",We]],["roformer",["RoFormerForMaskedLM",A]],["electra",["ElectraForMaskedLM",Ne]],["esm",["EsmForMaskedLM",Li]],["convbert",["ConvBertForMaskedLM",B]],["camembert",["CamembertForMaskedLM",Re]],["deberta",["DebertaForMaskedLM",Mt]],["deberta-v2",["DebertaV2ForMaskedLM",Ut]],["mpnet",["MPNetForMaskedLM",Oo]],["albert",["AlbertForMaskedLM",Xt]],["distilbert",["DistilBertForMaskedLM",Pt]],["roberta",["RobertaForMaskedLM",kn]],["xlm",["XLMWithLMHeadModel",$n]],["xlm-roberta",["XLMRobertaForMaskedLM",Ct]],["mobilebert",["MobileBertForMaskedLM",ci]],["squeezebert",["SqueezeBertForMaskedLM",co]]]),xd=new Map([["bert",["BertForQuestionAnswering",Ge]],["roformer",["RoFormerForQuestionAnswering",se]],["electra",["ElectraForQuestionAnswering",Ve]],["convbert",["ConvBertForQuestionAnswering",ue]],["camembert",["CamembertForQuestionAnswering",rt]],["deberta",["DebertaForQuestionAnswering",Rt]],["deberta-v2",["DebertaV2ForQuestionAnswering",Jt]],["mpnet",["MPNetForQuestionAnswering",Ro]],["albert",["AlbertForQuestionAnswering",po]],["distilbert",["DistilBertForQuestionAnswering",mt]],["roberta",["RobertaForQuestionAnswering",qn]],["xlm",["XLMForQuestionAnswering",gn]],["xlm-roberta",["XLMRobertaForQuestionAnswering",Gr]],["mobilebert",["MobileBertForQuestionAnswering",Ri]],["squeezebert",["SqueezeBertForQuestionAnswering",Mi]]]),_l=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",fa]]]),hm=new Map([["llava",["LlavaForConditionalGeneration",go]],["moondream1",["Moondream1ForConditionalGeneration",or]],["florence2",["Florence2ForConditionalGeneration",pa]]]),gp=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",fa]]]),Md=new Map([["vit",["ViTForImageClassification",qu]],["fastvit",["FastViTForImageClassification",Ku]],["mobilevit",["MobileViTForImageClassification",Ju]],["mobilevitv2",["MobileViTV2ForImageClassification",ec]],["beit",["BeitForImageClassification",sc]],["deit",["DeiTForImageClassification",_c]],["convnext",["ConvNextForImageClassification",Pc]],["convnextv2",["ConvNextV2ForImageClassification",Ic]],["dinov2",["Dinov2ForImageClassification",zc]],["resnet",["ResNetForImageClassification",wc]],["swin",["SwinForImageClassification",bc]],["segformer",["SegformerForImageClassification",ud]],["efficientnet",["EfficientNetForImageClassification",pd]],["mobilenet_v1",["MobileNetV1ForImageClassification",cp]],["mobilenet_v2",["MobileNetV2ForImageClassification",gd]],["mobilenet_v3",["MobileNetV3ForImageClassification",dp]],["mobilenet_v4",["MobileNetV4ForImageClassification",ml]]]),_p=new Map([["detr",["DetrForObjectDetection",lc]],["rt_detr",["RTDetrForObjectDetection",zs]],["table-transformer",["TableTransformerForObjectDetection",hc]],["yolos",["YolosForObjectDetection",Dc]]]),Td=new Map([["owlvit",["OwlViTForObjectDetection",rc]],["owlv2",["Owlv2ForObjectDetection",ic]]]),kd=new Map([["detr",["DetrForSegmentation",uc]],["clipseg",["CLIPSegForImageSegmentation",mu]]]),Sd=new Map([["segformer",["SegformerForSemanticSegmentation",cd]]]),Ed=new Map([["sam",["SamModel",Bc]]]),yp=new Map([["wav2vec2",["Wav2Vec2ForCTC",ip]],["wav2vec2-bert",["Wav2Vec2BertForCTC",Rs]],["unispeech",["UniSpeechForCTC",Gc]],["unispeech-sat",["UniSpeechSatForCTC",Xa]],["wavlm",["WavLMForCTC",Ja]],["hubert",["HubertForCTC",Qc]]]),Cd=new Map([["wav2vec2",["Wav2Vec2ForSequenceClassification",ji]],["wav2vec2-bert",["Wav2Vec2BertForSequenceClassification",Kc]],["unispeech",["UniSpeechForSequenceClassification",qc]],["unispeech-sat",["UniSpeechSatForSequenceClassification",Hc]],["wavlm",["WavLMForSequenceClassification",Yc]],["hubert",["HubertForSequenceClassification",Za]],["audio-spectrogram-transformer",["ASTForAudioClassification",Es]]]),Pd=new Map([["wavlm",["WavLMForXVector",Zc]]]),$d=new Map([["unispeech-sat",["UniSpeechSatForAudioFrameClassification",Ds]],["wavlm",["WavLMForAudioFrameClassification",Jc]],["wav2vec2",["Wav2Vec2ForAudioFrameClassification",Ui]],["pyannote",["PyAnnoteForAudioFrameClassification",Vi]]]),Ad=new Map([["vitmatte",["VitMatteForImageMatting",Xu]]]),wp=new Map([["swin2sr",["Swin2SRForImageSuperResolution",La]]]),Id=new Map([["dpt",["DPTForDepthEstimation",Na]],["depth_anything",["DepthAnythingForDepthEstimation",Tc]],["glpn",["GLPNForDepthEstimation",Sc]]]),Fd=new Map([["clip",["CLIPVisionModelWithProjection",uu]],["siglip",["SiglipVisionModel",du]]]),zd=[[fp,x.EncoderOnly],[pp,x.EncoderDecoder],[hp,x.DecoderOnly],[vd,x.EncoderOnly],[mp,x.EncoderOnly],[gl,x.Seq2Seq],[Us,x.Seq2Seq],[Vs,x.DecoderOnly],[bd,x.EncoderOnly],[xd,x.EncoderOnly],[_l,x.Vision2Seq],[hm,x.ImageTextToText],[Md,x.EncoderOnly],[kd,x.EncoderOnly],[Sd,x.EncoderOnly],[Ad,x.EncoderOnly],[wp,x.EncoderOnly],[Id,x.EncoderOnly],[_p,x.EncoderOnly],[Td,x.EncoderOnly],[Ed,x.MaskGeneration],[yp,x.EncoderOnly],[Cd,x.EncoderOnly],[yd,x.Seq2Seq],[wd,x.EncoderOnly],[Pd,x.EncoderOnly],[$d,x.EncoderOnly],[Fd,x.EncoderOnly]];for(const[V,G]of zd)for(const[ie,Ee]of V.values())I.set(ie,G),O.set(Ee,ie),U.set(ie,Ee);const vp=[["MusicgenForConditionalGeneration",dl,x.Musicgen],["CLIPTextModelWithProjection",fi,x.EncoderOnly],["SiglipTextModel",cu,x.EncoderOnly],["ClapTextModelWithProjection",ad,x.EncoderOnly],["ClapAudioModelWithProjection",ld,x.EncoderOnly]];for(const[V,G,ie]of vp)I.set(V,ie),O.set(G,V),U.set(V,G);class Od extends Or{}qe(Od,"MODEL_CLASS_MAPPINGS",zd.map(G=>G[0])),qe(Od,"BASE_IF_FAIL",!0);class Sn extends Or{}qe(Sn,"MODEL_CLASS_MAPPINGS",[vd]);class Dd extends Or{}qe(Dd,"MODEL_CLASS_MAPPINGS",[mp]);class Ld extends Or{}qe(Ld,"MODEL_CLASS_MAPPINGS",[gl]);class yl extends Or{}qe(yl,"MODEL_CLASS_MAPPINGS",[Us]);class Rd extends Or{}qe(Rd,"MODEL_CLASS_MAPPINGS",[yd]);class Xo extends Or{}qe(Xo,"MODEL_CLASS_MAPPINGS",[wd]);class Bd extends Or{}qe(Bd,"MODEL_CLASS_MAPPINGS",[Vs]);class Nd extends Or{}qe(Nd,"MODEL_CLASS_MAPPINGS",[bd]);class wl extends Or{}qe(wl,"MODEL_CLASS_MAPPINGS",[xd]);class jd extends Or{}qe(jd,"MODEL_CLASS_MAPPINGS",[_l]);class Ud extends Or{}qe(Ud,"MODEL_CLASS_MAPPINGS",[Md]);class vl extends Or{}qe(vl,"MODEL_CLASS_MAPPINGS",[kd]);class Vd extends Or{}qe(Vd,"MODEL_CLASS_MAPPINGS",[Sd]);class Wd extends Or{}qe(Wd,"MODEL_CLASS_MAPPINGS",[_p]);class Gd extends Or{}qe(Gd,"MODEL_CLASS_MAPPINGS",[Td]);class bl extends Or{}qe(bl,"MODEL_CLASS_MAPPINGS",[Ed]);class qd extends Or{}qe(qd,"MODEL_CLASS_MAPPINGS",[yp]);class Hd extends Or{}qe(Hd,"MODEL_CLASS_MAPPINGS",[Cd]);class xl extends Or{}qe(xl,"MODEL_CLASS_MAPPINGS",[Pd]);class Kd extends Or{}qe(Kd,"MODEL_CLASS_MAPPINGS",[$d]);class bp extends Or{}qe(bp,"MODEL_CLASS_MAPPINGS",[gp]);class Qd extends Or{}qe(Qd,"MODEL_CLASS_MAPPINGS",[Ad]);class Xd extends Or{}qe(Xd,"MODEL_CLASS_MAPPINGS",[wp]);class Yd extends Or{}qe(Yd,"MODEL_CLASS_MAPPINGS",[Id]);class Zd extends Or{}qe(Zd,"MODEL_CLASS_MAPPINGS",[Fd]);class mm extends me{constructor({logits:G,past_key_values:ie,encoder_outputs:Ee,decoder_attentions:Ze=null,cross_attentions:it=null}){super(),this.logits=G,this.past_key_values=ie,this.encoder_outputs=Ee,this.decoder_attentions=Ze,this.cross_attentions=it}}class ur extends me{constructor({logits:G}){super(),this.logits=G}}class Jd extends me{constructor({logits:G,embeddings:ie}){super(),this.logits=G,this.embeddings=ie}}class dn extends me{constructor({logits:G}){super(),this.logits=G}}class yn extends me{constructor({logits:G}){super(),this.logits=G}}class wn extends me{constructor({start_logits:G,end_logits:ie}){super(),this.start_logits=G,this.end_logits=ie}}class Ji extends me{constructor({logits:G}){super(),this.logits=G}}class xp extends me{constructor({logits:G,past_key_values:ie}){super(),this.logits=G,this.past_key_values=ie}}class ef extends me{constructor({alphas:G}){super(),this.alphas=G}}class Mp extends me{constructor({waveform:G,spectrogram:ie}){super(),this.waveform=G,this.spectrogram=ie}}},"./src/models/whisper/common_whisper.js":(e,t,n)=>{n.r(t),n.d(t,{WHISPER_LANGUAGE_MAPPING:()=>a,WHISPER_TO_LANGUAGE_CODE_MAPPING:()=>l,whisper_language_to_code:()=>f});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"]],a=new Map(o),l=new Map([...o.map(([_,h])=>[h,_]),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);function f(_){_=_.toLowerCase();let h=l.get(_);if(h===void 0)if(a.has(_))h=_;else{const M=_.length===2?a.keys():a.values();throw new Error(`Language "${_}" is not supported. Must be one of: ${JSON.stringify(M)}`)}return h}},"./src/models/whisper/generation_whisper.js":(e,t,n)=>{n.r(t),n.d(t,{WhisperGenerationConfig:()=>a});var o=n("./src/generation/configuration_utils.js");class a extends o.GenerationConfig{constructor(){super(...arguments);qe(this,"return_timestamps",null);qe(this,"return_token_timestamps",null);qe(this,"num_frames",null);qe(this,"alignment_heads",null);qe(this,"task",null);qe(this,"language",null);qe(this,"no_timestamps_token_id",null);qe(this,"prompt_ids",null);qe(this,"is_multilingual",null);qe(this,"lang_to_id",null);qe(this,"task_to_id",null);qe(this,"max_initial_timestamp_index",1)}}},"./src/ops/registry.js":(e,t,n)=>{n.r(t),n.d(t,{TensorOpRegistry:()=>f});var o=n("./src/backends/onnx.js"),a=n("./src/utils/tensor.js");const l=async(_,h,g)=>{const M=await(0,o.createInferenceSession)(new Uint8Array(_),h);return async w=>{const C=Object.fromEntries(Object.entries(w).map(([z,S])=>[z,S.ort_tensor])),k=await M.run(C);return Array.isArray(g)?g.map(z=>new a.Tensor(k[z])):new a.Tensor(k[g])}};class f{static get bilinear_interpolate_4d(){return this._bilinear_interpolate_4d||(this._bilinear_interpolate_4d=l([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=l([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=l([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=l([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=l([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=l([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}}qe(f,"session_options",{})},"./src/pipelines.js":(e,t,n)=>{n.r(t),n.d(t,{AudioClassificationPipeline:()=>ee,AutomaticSpeechRecognitionPipeline:()=>R,DepthEstimationPipeline:()=>De,DocumentQuestionAnsweringPipeline:()=>X,FeatureExtractionPipeline:()=>de,FillMaskPipeline:()=>I,ImageClassificationPipeline:()=>Qe,ImageFeatureExtractionPipeline:()=>Ce,ImageSegmentationPipeline:()=>ge,ImageToImagePipeline:()=>Ke,ImageToTextPipeline:()=>Me,ObjectDetectionPipeline:()=>ae,Pipeline:()=>S,QuestionAnsweringPipeline:()=>x,SummarizationPipeline:()=>O,Text2TextGenerationPipeline:()=>U,TextClassificationPipeline:()=>P,TextGenerationPipeline:()=>D,TextToAudioPipeline:()=>me,TokenClassificationPipeline:()=>y,TranslationPipeline:()=>N,ZeroShotAudioClassificationPipeline:()=>ye,ZeroShotClassificationPipeline:()=>Y,ZeroShotImageClassificationPipeline:()=>Q,ZeroShotObjectDetectionPipeline:()=>Se,pipeline:()=>ot});var o=n("./src/tokenizers.js"),a=n("./src/models.js"),l=n("./src/processors.js"),f=n("./src/utils/generic.js"),_=n("./src/utils/core.js"),h=n("./src/utils/maths.js"),g=n("./src/utils/audio.js"),M=n("./src/utils/tensor.js"),w=n("./src/utils/image.js");async function C(Ge){return Array.isArray(Ge)||(Ge=[Ge]),await Promise.all(Ge.map(Te=>w.RawImage.read(Te)))}async function k(Ge,Te){return Array.isArray(Ge)||(Ge=[Ge]),await Promise.all(Ge.map(je=>typeof je=="string"||je instanceof URL?(0,g.read_audio)(je,Te):je instanceof Float64Array?new Float32Array(je):je))}function z(Ge,Te){Te&&(Ge=Ge.map(Ae=>Ae|0));const[je,Ye,tt,A]=Ge;return{xmin:je,ymin:Ye,xmax:tt,ymax:A}}class S extends f.Callable{constructor({task:Te,model:je,tokenizer:Ye=null,processor:tt=null}){super(),this.task=Te,this.model=je,this.tokenizer=Ye,this.processor=tt}async dispose(){await this.model.dispose()}}class P extends S{constructor(Te){super(Te)}async _call(Te,{top_k:je=1}={}){const Ye=this.tokenizer(Te,{padding:!0,truncation:!0}),tt=await this.model(Ye),A=this.model.config.problem_type==="multi_label_classification"?se=>se.sigmoid():se=>new M.Tensor("float32",(0,h.softmax)(se.data),se.dims),Ae=this.model.config.id2label,$e=[];for(const se of tt.logits){const te=A(se),we=await(0,M.topk)(te,je),B=we[0].tolist(),L=we[1].tolist().map((ue,le)=>({label:Ae?Ae[ue]:`LABEL_${ue}`,score:B[le]}));je===1?$e.push(...L):$e.push(L)}return Array.isArray(Te)||je===1?$e:$e[0]}}class y extends S{constructor(Te){super(Te)}async _call(Te,{ignore_labels:je=["O"]}={}){const Ye=Array.isArray(Te),tt=this.tokenizer(Ye?Te:[Te],{padding:!0,truncation:!0}),Ae=(await this.model(tt)).logits,$e=this.model.config.id2label,se=[];for(let te=0;teJe==this.tokenizer.sep_token_id);se[B].map((Je,Ve)=>Je==1&&(Ve===0||Ve>L&&te.findIndex(Z=>Z==J[Ve])===-1));const ue=A[B].tolist(),le=Ae[B].tolist();for(let Je=1;JeVe==J[Je])!==-1)&&(ue[Je]=-1/0,le[Je]=-1/0);const ke=(0,h.softmax)(ue).map((Je,Ve)=>[Je,Ve]),Ne=(0,h.softmax)(le).map((Je,Ve)=>[Je,Ve]);ke[0][0]=0,Ne[0][0]=0;const ut=(0,_.product)(ke,Ne).filter(Je=>Je[0][1]<=Je[1][1]).map(Je=>[Je[0][1],Je[1][1],Je[0][0]*Je[1][0]]).sort((Je,Ve)=>Ve[2]-Je[2]);for(let Je=0;Jeue==this.tokenizer.mask_token_id);if(te===-1)throw Error(`Mask token (${this.tokenizer.mask_token}) not found in text.`);const we=tt[$e][te],B=await(0,M.topk)(new M.Tensor("float32",(0,h.softmax)(we.data),we.dims),je),J=B[0].tolist(),L=B[1].tolist();A.push(L.map((ue,le)=>{const ke=se.slice();return ke[te]=ue,{score:J[le],token:Number(ue),token_str:this.tokenizer.model.vocab[ue],sequence:this.tokenizer.decode(ke,{skip_special_tokens:!0})}}))}return Array.isArray(Te)?A:A[0]}}class U extends S{constructor(je){super(je);qe(this,"_key","generated_text")}async _call(je,Ye={}){Array.isArray(je)||(je=[je]),this.model.config.prefix&&(je=je.map(te=>this.model.config.prefix+te));const tt=this.model.config.task_specific_params;tt&&tt[this.task]&&tt[this.task].prefix&&(je=je.map(te=>tt[this.task].prefix+te));const A=this.tokenizer,Ae={padding:!0,truncation:!0};let $e;this instanceof N&&"_build_translation_inputs"in A?$e=A._build_translation_inputs(je,Ae,Ye):$e=A(je,Ae);const se=await this.model.generate({...$e,...Ye});return A.batch_decode(se,{skip_special_tokens:!0}).map(te=>({[this._key]:te}))}}class O extends U{constructor(je){super(je);qe(this,"_key","summary_text")}}class N extends U{constructor(je){super(je);qe(this,"_key","translation_text")}}function j(Ge){return Array.isArray(Ge)&&Ge.every(Te=>"role"in Te&&"content"in Te)}class D extends S{constructor(Te){super(Te)}async _call(Te,je={}){let Ye=!1,tt=!1,A;if(typeof Te=="string")A=Te=[Te];else if(Array.isArray(Te)&&Te.every(L=>typeof L=="string"))Ye=!0,A=Te;else{if(j(Te))Te=[Te];else if(Array.isArray(Te)&&Te.every(j))Ye=!0;else throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats");tt=!0,A=Te.map(L=>this.tokenizer.apply_chat_template(L,{tokenize:!1,add_generation_prompt:!0}))}const Ae=je.add_special_tokens??!1,$e=tt?!1:je.return_full_text??!0;this.tokenizer.padding_side="left";const se=this.tokenizer(A,{add_special_tokens:Ae,padding:!0,truncation:!0}),te=await this.model.generate({...se,...je}),we=this.tokenizer.batch_decode(te,{skip_special_tokens:!0});let B;!$e&&se.input_ids.dims.at(-1)>0&&(B=this.tokenizer.batch_decode(se.input_ids,{skip_special_tokens:!0}).map(L=>L.length));const J=Array.from({length:Te.length},L=>[]);for(let L=0;L[je.toLowerCase(),Ye])),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(Te,je,{hypothesis_template:Ye="This example is {}.",multi_label:tt=!1}={}){const A=Array.isArray(Te);A||(Te=[Te]),Array.isArray(je)||(je=[je]);const Ae=je.map(te=>Ye.replace("{}",te)),$e=tt||je.length===1,se=[];for(const te of Te){const we=[];for(const L of Ae){const ue=this.tokenizer(te,{text_pair:L,padding:!0,truncation:!0}),le=await this.model(ue);$e?we.push([le.logits.data[this.contradiction_id],le.logits.data[this.entailment_id]]):we.push(le.logits.data[this.entailment_id])}const J=($e?we.map(L=>(0,h.softmax)(L)[1]):(0,h.softmax)(we)).map((L,ue)=>[L,ue]).sort((L,ue)=>ue[0]-L[0]);se.push({sequence:te,labels:J.map(L=>je[L[1]]),scores:J.map(L=>L[0])})}return A?se:se[0]}}class de extends S{constructor(Te){super(Te)}async _call(Te,{pooling:je="none",normalize:Ye=!1,quantize:tt=!1,precision:A="binary"}={}){const Ae=this.tokenizer(Te,{padding:!0,truncation:!0}),$e=await this.model(Ae);let se=$e.last_hidden_state??$e.logits??$e.token_embeddings;if(je!=="none")if(je==="mean")se=(0,M.mean_pooling)(se,Ae.attention_mask);else if(je==="cls")se=se.slice(null,0);else throw Error(`Pooling method '${je}' not supported.`);return Ye&&(se=se.normalize(2,-1)),tt&&(se=(0,M.quantize_embeddings)(se,A)),se}}class Ce extends S{constructor(Te){super(Te)}async _call(Te,{pool:je=null}={}){const Ye=await C(Te),{pixel_values:tt}=await this.processor(Ye),A=await this.model({pixel_values:tt});let Ae;if(je){if(!("pooler_output"in A))throw Error("No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.");Ae=A.pooler_output}else Ae=A.last_hidden_state??A.logits??A.image_embeds;return Ae}}class ee extends S{constructor(Te){super(Te)}async _call(Te,{top_k:je=5}={}){const Ye=this.processor.feature_extractor.config.sampling_rate,tt=await k(Te,Ye),A=this.model.config.id2label,Ae=[];for(const $e of tt){const se=await this.processor($e),we=(await this.model(se)).logits[0],B=await(0,M.topk)(new M.Tensor("float32",(0,h.softmax)(we.data),we.dims),je),J=B[0].tolist(),ue=B[1].tolist().map((le,ke)=>({label:A?A[le]:`LABEL_${le}`,score:J[ke]}));Ae.push(ue)}return Array.isArray(Te)?Ae:Ae[0]}}class ye extends S{constructor(Te){super(Te)}async _call(Te,je,{hypothesis_template:Ye="This is a sound of {}."}={}){const tt=!Array.isArray(Te);tt&&(Te=[Te]);const A=je.map(we=>Ye.replace("{}",we)),Ae=this.tokenizer(A,{padding:!0,truncation:!0}),$e=this.processor.feature_extractor.config.sampling_rate,se=await k(Te,$e),te=[];for(const we of se){const B=await this.processor(we),J=await this.model({...Ae,...B}),L=(0,h.softmax)(J.logits_per_audio.data);te.push([...L].map((ue,le)=>({score:ue,label:je[le]})))}return tt?te[0]:te}}class R extends S{constructor(Te){super(Te)}async _call(Te,je={}){switch(this.model.config.model_type){case"whisper":return this._call_whisper(Te,je);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":return this._call_wav2vec2(Te,je);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(Te,je){je.language&&console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),je.task&&console.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');const Ye=!Array.isArray(Te);Ye&&(Te=[Te]);const tt=this.processor.feature_extractor.config.sampling_rate,A=await k(Te,tt),Ae=[];for(const $e of A){const se=await this.processor($e),we=(await this.model(se)).logits[0],B=[];for(const L of we)B.push((0,h.max)(L.data)[1]);const J=this.tokenizer.decode(B);Ae.push({text:J})}return Ye?Ae[0]:Ae}async _call_whisper(Te,je){const Ye=je.return_timestamps??!1,tt=je.chunk_length_s??0,A=je.force_full_sequences??!1;let Ae=je.stride_length_s??null;const $e={...je};Ye==="word"&&($e.return_token_timestamps=!0,$e.return_timestamps=!1);const se=!Array.isArray(Te);se&&(Te=[Te]);const te=this.processor.feature_extractor.config.chunk_length/this.model.config.max_source_positions,we=this.processor.feature_extractor.config.hop_length,B=this.processor.feature_extractor.config.sampling_rate,J=await k(Te,B),L=[];for(const ue of J){let le=[];if(tt>0){if(Ae===null)Ae=tt/6;else if(tt<=Ae)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");const ut=B*tt,Je=B*Ae,Ve=ut-2*Je;let Z=0;for(;;){const ve=Z+ut,Re=ue.subarray(Z,ve),He=await this.processor(Re),Xe=Z===0,rt=ve>=ue.length;if(le.push({stride:[Re.length,Xe?0:Je,rt?0:Je],input_features:He.input_features,is_last:rt}),rt)break;Z+=Ve}}else le=[{stride:[ue.length,0,0],input_features:(await this.processor(ue)).input_features,is_last:!0}];for(const ut of le){$e.num_frames=Math.floor(ut.stride[0]/we);const Je=await this.model.generate({inputs:ut.input_features,...$e});Ye==="word"?(ut.tokens=Je.sequences.tolist()[0],ut.token_timestamps=Je.token_timestamps.tolist()[0].map(Ve=>(0,h.round)(Ve,2))):ut.tokens=Je[0].tolist(),ut.stride=ut.stride.map(Ve=>Ve/B)}const[ke,Ne]=this.tokenizer._decode_asr(le,{time_precision:te,return_timestamps:Ye,force_full_sequences:A});L.push({text:ke,...Ne})}return se?L[0]:L}}class Me extends S{constructor(Te){super(Te)}async _call(Te,je={}){const Ye=Array.isArray(Te),tt=await C(Te),{pixel_values:A}=await this.processor(tt),Ae=[];for(const $e of A){$e.dims=[1,...$e.dims];const se=await this.model.generate({inputs:$e,...je}),te=this.tokenizer.batch_decode(se,{skip_special_tokens:!0}).map(we=>({generated_text:we.trim()}));Ae.push(te)}return Ye?Ae:Ae[0]}}class Qe extends S{constructor(Te){super(Te)}async _call(Te,{top_k:je=5}={}){const Ye=await C(Te),{pixel_values:tt}=await this.processor(Ye),A=await this.model({pixel_values:tt}),Ae=this.model.config.id2label,$e=[];for(const se of A.logits){const te=await(0,M.topk)(new M.Tensor("float32",(0,h.softmax)(se.data),se.dims),je),we=te[0].tolist(),J=te[1].tolist().map((L,ue)=>({label:Ae?Ae[L]:`LABEL_${L}`,score:we[ue]}));$e.push(J)}return Array.isArray(Te)?$e:$e[0]}}class ge extends S{constructor(Te){super(Te),this.subtasks_mapping={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"}}async _call(Te,{threshold:je=.5,mask_threshold:Ye=.5,overlap_mask_area_threshold:tt=.8,label_ids_to_fuse:A=null,target_sizes:Ae=null,subtask:$e=null}={}){if(Array.isArray(Te)&&Te.length!==1)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");const te=await C(Te),we=te.map(Ne=>[Ne.height,Ne.width]),{pixel_values:B,pixel_mask:J}=await this.processor(te),L=await this.model({pixel_values:B,pixel_mask:J});let ue=null;if($e!==null)ue=this.subtasks_mapping[$e];else for(let[Ne,ut]of Object.entries(this.subtasks_mapping))if(ut in this.processor.feature_extractor){ue=this.processor.feature_extractor[ut].bind(this.processor.feature_extractor),$e=Ne;break}const le=this.model.config.id2label,ke=[];if($e==="panoptic"||$e==="instance"){const Ne=ue(L,je,Ye,tt,A,Ae??we)[0],ut=Ne.segmentation;for(const Je of Ne.segments_info){const Ve=new Uint8ClampedArray(ut.data.length);for(let ve=0;veYe.replace("{}",J)),$e=this.tokenizer(Ae,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:se}=await this.processor(A),te=await this.model({...$e,pixel_values:se}),we=this.model.config.model_type==="siglip"?J=>J.sigmoid().data:J=>(0,h.softmax)(J.data),B=[];for(const J of te.logits_per_image){const ue=[...we(J)].map((le,ke)=>({score:le,label:je[ke]}));ue.sort((le,ke)=>ke.score-le.score),B.push(ue)}return tt?B:B[0]}}class ae extends S{constructor(Te){super(Te)}async _call(Te,{threshold:je=.9,percentage:Ye=!1}={}){const tt=Array.isArray(Te);if(tt&&Te.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");const A=await C(Te),Ae=Ye?null:A.map(L=>[L.height,L.width]),{pixel_values:$e,pixel_mask:se}=await this.processor(A),te=await this.model({pixel_values:$e,pixel_mask:se}),we=this.processor.feature_extractor.post_process_object_detection(te,je,Ae),B=this.model.config.id2label,J=we.map(L=>L.boxes.map((ue,le)=>({score:L.scores[le],label:B[L.classes[le]],box:z(ue,!Ye)})));return tt?J:J[0]}}class Se extends S{constructor(Te){super(Te)}async _call(Te,je,{threshold:Ye=.1,top_k:tt=null,percentage:A=!1}={}){const Ae=Array.isArray(Te),$e=await C(Te),se=this.tokenizer(je,{padding:!0,truncation:!0}),te=await this.processor($e),we=[];for(let B=0;B<$e.length;++B){const J=$e[B],L=A?null:[[J.height,J.width]],ue=te.pixel_values[B].unsqueeze_(0),le=await this.model({...se,pixel_values:ue}),ke=this.processor.feature_extractor.post_process_object_detection(le,Ye,L,!0)[0];let Ne=ke.boxes.map((ut,Je)=>({score:ke.scores[Je],label:je[ke.classes[Je]],box:z(ut,!A)})).sort((ut,Je)=>Je.score-ut.score);tt!==null&&(Ne=Ne.slice(0,tt)),we.push(Ne)}return Ae?we:we[0]}}class X extends S{constructor(Te){super(Te)}async _call(Te,je,Ye={}){throw new Error("This pipeline is not yet supported in Transformers.js v3.")}}class me extends S{constructor(je){super(je);qe(this,"DEFAULT_VOCODER_ID","Xenova/speecht5_hifigan");this.vocoder=je.vocoder??null}async _call(je,{speaker_embeddings:Ye=null}={}){return this.processor?this._call_text_to_spectrogram(je,{speaker_embeddings:Ye}):this._call_text_to_waveform(je)}async _call_text_to_waveform(je){const Ye=this.tokenizer(je,{padding:!0,truncation:!0}),{waveform:tt}=await this.model(Ye),A=this.model.config.sampling_rate;return{audio:tt.data,sampling_rate:A}}async _call_text_to_spectrogram(je,{speaker_embeddings:Ye}){if(this.vocoder||(console.log("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await a.AutoModel.from_pretrained(this.DEFAULT_VOCODER_ID,{dtype:"fp32"})),(typeof Ye=="string"||Ye instanceof URL)&&(Ye=new Float32Array(await(await fetch(Ye)).arrayBuffer())),Ye instanceof Float32Array)Ye=new M.Tensor("float32",Ye,[1,Ye.length]);else if(!(Ye instanceof M.Tensor))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");const{input_ids:tt}=this.tokenizer(je,{padding:!0,truncation:!0}),{waveform:A}=await this.model.generate_speech(tt,Ye,{vocoder:this.vocoder}),Ae=this.processor.feature_extractor.config.sampling_rate;return{audio:A.data,sampling_rate:Ae}}}class Ke extends S{constructor(Te){super(Te)}async _call(Te){const je=await C(Te),Ye=await this.processor(je),tt=await this.model(Ye),A=[];for(const Ae of tt.reconstruction){const $e=Ae.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");A.push(w.RawImage.fromTensor($e))}return A.length>1?A:A[0]}}class De extends S{constructor(Te){super(Te)}async _call(Te){const je=await C(Te),Ye=await this.processor(je),{predicted_depth:tt}=await this.model(Ye),A=[];for(let Ae=0;Ae1?A:A[0]}}const Be=Object.freeze({"text-classification":{tokenizer:o.AutoTokenizer,pipeline:P,model:a.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{tokenizer:o.AutoTokenizer,pipeline:y,model:a.AutoModelForTokenClassification,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{tokenizer:o.AutoTokenizer,pipeline:x,model:a.AutoModelForQuestionAnswering,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{tokenizer:o.AutoTokenizer,pipeline:I,model:a.AutoModelForMaskedLM,default:{model:"Xenova/bert-base-uncased"},type:"text"},summarization:{tokenizer:o.AutoTokenizer,pipeline:O,model:a.AutoModelForSeq2SeqLM,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{tokenizer:o.AutoTokenizer,pipeline:N,model:a.AutoModelForSeq2SeqLM,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{tokenizer:o.AutoTokenizer,pipeline:U,model:a.AutoModelForSeq2SeqLM,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{tokenizer:o.AutoTokenizer,pipeline:D,model:a.AutoModelForCausalLM,default:{model:"Xenova/gpt2"},type:"text"},"zero-shot-classification":{tokenizer:o.AutoTokenizer,pipeline:Y,model:a.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:ee,model:a.AutoModelForAudioClassification,processor:l.AutoProcessor,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{tokenizer:o.AutoTokenizer,pipeline:ye,model:a.AutoModel,processor:l.AutoProcessor,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{tokenizer:o.AutoTokenizer,pipeline:R,model:[a.AutoModelForSpeechSeq2Seq,a.AutoModelForCTC],processor:l.AutoProcessor,default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{tokenizer:o.AutoTokenizer,pipeline:me,model:[a.AutoModelForTextToWaveform,a.AutoModelForTextToSpectrogram],processor:[l.AutoProcessor,null],default:{model:"Xenova/speecht5_tts"},type:"text"},"image-to-text":{tokenizer:o.AutoTokenizer,pipeline:Me,model:a.AutoModelForVision2Seq,processor:l.AutoProcessor,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:Qe,model:a.AutoModelForImageClassification,processor:l.AutoProcessor,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:ge,model:[a.AutoModelForImageSegmentation,a.AutoModelForSemanticSegmentation],processor:l.AutoProcessor,default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"zero-shot-image-classification":{tokenizer:o.AutoTokenizer,pipeline:Q,model:a.AutoModel,processor:l.AutoProcessor,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:ae,model:a.AutoModelForObjectDetection,processor:l.AutoProcessor,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{tokenizer:o.AutoTokenizer,pipeline:Se,model:a.AutoModelForZeroShotObjectDetection,processor:l.AutoProcessor,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{tokenizer:o.AutoTokenizer,pipeline:X,model:a.AutoModelForDocumentQuestionAnswering,processor:l.AutoProcessor,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:Ke,model:a.AutoModelForImageToImage,processor:l.AutoProcessor,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:De,model:a.AutoModelForDepthEstimation,processor:l.AutoProcessor,default:{model:"Xenova/dpt-large"},type:"image"},"feature-extraction":{tokenizer:o.AutoTokenizer,pipeline:de,model:a.AutoModel,default:{model:"Xenova/all-MiniLM-L6-v2"},type:"text"},"image-feature-extraction":{processor:l.AutoProcessor,pipeline:Ce,model:[a.AutoModelForImageFeatureExtraction,a.AutoModel],default:{model:"Xenova/vit-base-patch16-224-in21k"},type:"image"}}),We=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});async function ot(Ge,Te=null,{progress_callback:je=null,config:Ye=null,cache_dir:tt=null,local_files_only:A=!1,revision:Ae="main",device:$e=null,dtype:se=null,model_file_name:te=null,session_options:we={}}={}){Ge=We[Ge]??Ge;const B=Be[Ge.split("_",1)[0]];if(!B)throw Error(`Unsupported pipeline: ${Ge}. Must be one of [${Object.keys(Be)}]`);Te||(Te=B.default.model,console.log(`No model specified. Using default model: "${Te}".`));const J={progress_callback:je,config:Ye,cache_dir:tt,local_files_only:A,revision:Ae,device:$e,dtype:se,model_file_name:te,session_options:we},L=new Map([["tokenizer",B.tokenizer],["model",B.model],["processor",B.processor]]),ue=await dt(L,Te,J);ue.task=Ge,(0,_.dispatchCallback)(je,{status:"ready",task:Ge,model:Te});const le=B.pipeline;return new le(ue)}async function dt(Ge,Te,je){const Ye=Object.create(null),tt=[];for(let[A,Ae]of Ge.entries()){if(!Ae)continue;let $e;Array.isArray(Ae)?$e=new Promise(async(se,te)=>{var B,J;let we;for(let L of Ae){if(L===null){se(null);return}try{se(await L.from_pretrained(Te,je));return}catch(ue){if((B=ue.message)!=null&&B.includes("Unsupported model type"))we=ue;else if((J=ue.message)!=null&&J.includes("Could not locate file"))we=ue;else{te(ue);return}}}te(we)}):$e=Ae.from_pretrained(Te,je),Ye[A]=$e,tt.push($e)}await Promise.all(tt);for(let[A,Ae]of Object.entries(Ye))Ye[A]=await Ae;return Ye}},"./src/processors.js":(e,t,n)=>{n.r(t),n.d(t,{ASTFeatureExtractor:()=>Ae,AutoProcessor:()=>Je,BeitFeatureExtractor:()=>De,BitImageProcessor:()=>I,CLIPFeatureExtractor:()=>O,CLIPImageProcessor:()=>N,ChineseCLIPFeatureExtractor:()=>j,ClapFeatureExtractor:()=>$e,ConvNextFeatureExtractor:()=>Y,ConvNextImageProcessor:()=>de,DPTFeatureExtractor:()=>y,DPTImageProcessor:()=>x,DeiTFeatureExtractor:()=>Ke,DetrFeatureExtractor:()=>ot,DonutFeatureExtractor:()=>Be,EfficientNetImageProcessor:()=>ye,FeatureExtractor:()=>z,Florence2Processor:()=>ut,GLPNFeatureExtractor:()=>U,ImageFeatureExtractor:()=>S,MobileNetV1FeatureExtractor:()=>R,MobileNetV2FeatureExtractor:()=>Me,MobileNetV3FeatureExtractor:()=>Qe,MobileNetV4FeatureExtractor:()=>ge,MobileViTFeatureExtractor:()=>Q,MobileViTImageProcessor:()=>ae,NougatImageProcessor:()=>We,OwlViTFeatureExtractor:()=>Se,OwlViTProcessor:()=>Ne,Owlv2ImageProcessor:()=>X,Processor:()=>B,PyAnnoteFeatureExtractor:()=>se,PyAnnoteProcessor:()=>le,RTDetrImageProcessor:()=>me,SamImageProcessor:()=>Ge,SamProcessor:()=>J,SeamlessM4TFeatureExtractor:()=>A,SegformerFeatureExtractor:()=>P,SiglipImageProcessor:()=>D,SpeechT5FeatureExtractor:()=>we,SpeechT5Processor:()=>ke,Swin2SRImageProcessor:()=>Te,ViTFeatureExtractor:()=>Ce,ViTImageProcessor:()=>ee,VitMatteImageProcessor:()=>je,Wav2Vec2FeatureExtractor:()=>tt,Wav2Vec2ProcessorWithLM:()=>ue,WeSpeakerFeatureExtractor:()=>te,WhisperFeatureExtractor:()=>Ye,WhisperProcessor:()=>L,YolosFeatureExtractor:()=>dt});var o=n("./src/utils/generic.js"),a=n("./src/utils/core.js"),l=n("./src/utils/hub.js"),f=n("./src/utils/maths.js"),_=n("./src/utils/tensor.js");n("./src/utils/image.js");var h=n("./src/utils/audio.js");function g([Ve,Z,ve,Re]){return[Ve-ve/2,Z-Re/2,Ve+ve/2,Z+Re/2]}function M(Ve,Z=.5,ve=null,Re=!1){const He=Ve.logits,Xe=Ve.pred_boxes,[rt,ft,ht]=He.dims;if(ve!==null&&ve.length!==rt)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let Mt=[];for(let wt=0;wtZ&&Qt.push(qt)}else{let qt=(0,f.max)(Kt.data)[1];if(qt===ht-1||(Jt=(0,f.softmax)(Kt.data),Jt[qt]Qr*St[(Cr+1)%2])),Rt.boxes.push(Er),Rt.classes.push(qt),Rt.scores.push(Jt[qt])}}Mt.push(Rt)}return Mt}function w(Ve,Z){var ve;if(!(Ve instanceof Float32Array||Ve instanceof Float64Array))throw new Error(`${Z} expects input to be a Float32Array or a Float64Array, but got ${((ve=Ve==null?void 0:Ve.constructor)==null?void 0:ve.name)??typeof Ve} 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 C(Ve,Z,ve=0,Re=null){const He=Ve/Z;let Xe=(0,f.bankers_round)(He)*Z;return Re!==null&&Xe>Re&&(Xe=Math.floor(He)*Z),XeXe?Mt=Math.floor(Xe*ht/He):Xe>He&&(ht=Math.floor(He*Mt/Xe)),await Z.resize(Mt,ht,{resample:Re}))}async crop_margin(Z,ve=200){const Re=Z.clone().grayscale(),He=(0,f.min)(Re.data)[0],rt=(0,f.max)(Re.data)[0]-He;if(rt===0)return Z;const ft=ve/255;let ht=Re.width,Mt=Re.height,wt=0,St=0;const Rt=Re.data;for(let at=0;atthis.preprocess(Xe)));return{pixel_values:(0,_.stack)(Re.map(Xe=>Xe.pixel_values),0),original_sizes:Re.map(Xe=>Xe.original_size),reshaped_input_sizes:Re.map(Xe=>Xe.reshaped_input_size)}}}class P extends S{post_process_semantic_segmentation(Z,ve=null){const Re=Z.logits,He=Re.dims[0];if(ve!==null&&ve.length!==He)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const Xe=[];for(let rt=0;rtRt[qt]&&(Rt[qt]=Jt[qt],at[qt]=Qt)}const Ot=new Array(ht.dims[0]),Ut=St.data;for(let Qt=0;QtQt!==void 0);Xe.push({segmentation:St,labels:Kt})}return Xe}}class y extends S{}class x extends y{}class I extends S{}class U extends S{}class O extends S{}class N extends O{}class j extends S{}class D extends S{}class Y extends S{constructor(Z){super(Z),this.crop_pct=this.config.crop_pct??224/256}async resize(Z){var Re;const ve=(Re=this.size)==null?void 0:Re.shortest_edge;if(ve===void 0)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(ve<384){const He=Math.floor(ve/this.crop_pct),[Xe,rt]=this.get_resize_output_image_size(Z,{shortest_edge:He});Z=await Z.resize(Xe,rt,{resample:this.resample}),Z=await Z.center_crop(ve,ve)}else Z=await Z.resize(ve,ve,{resample:this.resample});return Z}}class de extends Y{}class Ce extends S{}class ee extends S{}class ye extends S{constructor(Z){super(Z),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map(ve=>ve*ve))}}class R extends S{}class Me extends S{}class Qe extends S{}class ge extends S{}class Q extends S{}class ae extends Q{}class Se extends S{post_process_object_detection(...Z){return M(...Z)}}class X extends Se{}class me extends S{post_process_object_detection(...Z){return M(...Z)}}class Ke extends S{}class De extends S{}class Be extends S{pad_image(Z,ve,Re,He={}){const[Xe,rt,ft]=ve;let ht=this.image_mean;Array.isArray(this.image_mean)||(ht=new Array(ft).fill(ht));let Mt=this.image_std;Array.isArray(Mt)||(Mt=new Array(ft).fill(ht));const wt=ht.map((St,Rt)=>-St/Mt[Rt]);return super.pad_image(Z,ve,Re,{center:!0,constant_values:wt,...He})}}class We extends Be{}class ot extends S{async _call(Z){const ve=await super._call(Z),Re=[ve.pixel_values.dims[0],64,64],He=new _.Tensor("int64",new BigInt64Array(Re.reduce((Xe,rt)=>Xe*rt)).fill(1n),Re);return{...ve,pixel_mask:He}}post_process_object_detection(...Z){return M(...Z)}remove_low_and_no_objects(Z,ve,Re,He){let Xe=[],rt=[],ft=[];for(let ht=0;htRe&&(Xe.push(wt),rt.push(at),ft.push(St))}return[Xe,rt,ft]}check_segment_validity(Z,ve,Re,He=.5,Xe=.8){let rt=[],ft=0,ht=0;const Mt=ve[Re].data;for(let St=0;St=He&&++ht;let wt=ft>0&&ht>0;return wt&&(wt=ft/ht>Xe),[wt,rt]}compute_segments(Z,ve,Re,He,Xe,rt=null,ft=null){let[ht,Mt]=ft??Z[0].dims,wt=new _.Tensor("int32",new Int32Array(ht*Mt),[ht,Mt]),St=[];if(ft!==null)for(let Kt=0;Ktat[qt]&&(Rt[qt]=Kt,at[qt]=Jt[qt])}let Ot=0;const Ut=wt.data;for(let Kt=0;KtHe!==ve.dims[Xe]))throw Error(`The first ${Re.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new _.Tensor("int64",Z.flat(1/0).map(BigInt),Re)}async _call(Z,{input_points:ve=null,input_labels:Re=null,input_boxes:He=null}={}){const Xe=await super._call(Z);if(ve&&(Xe.input_points=this.reshape_input_points(ve,Xe.original_sizes,Xe.reshaped_input_sizes)),Re){if(!Xe.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");Xe.input_labels=this.add_input_labels(Re,Xe.input_points)}return He&&(Xe.input_boxes=this.reshape_input_points(He,Xe.original_sizes,Xe.reshaped_input_sizes,!0)),Xe}async post_process_masks(Z,ve,Re,{mask_threshold:He=0,binarize:Xe=!0,pad_size:rt=null}={}){const ft=[];rt=rt??this.pad_size;const ht=[rt.height,rt.width];for(let Mt=0;MtHe&&(Ot[Ut]=1);Rt=new _.Tensor("bool",Ot,Rt.dims)}ft.push(Rt)}return ft}generate_crop_boxes(Z,ve,{crop_n_layers:Re=0,overlap_ratio:He=512/1500,points_per_crop:Xe=32,crop_n_points_downscale_factor:rt=1}={}){}}class Te extends S{pad_image(Z,ve,Re,He={}){const[Xe,rt,ft]=ve;return super.pad_image(Z,ve,{width:rt+(Re-rt%Re)%Re,height:Xe+(Re-Xe%Re)%Re},{mode:"symmetric",center:!1,constant_values:-1,...He})}}class je extends S{async _call(Z,ve){Array.isArray(Z)||(Z=[Z]),Array.isArray(ve)||(ve=[ve]);const Re=await Promise.all(Z.map(rt=>this.preprocess(rt))),He=await Promise.all(ve.map(rt=>this.preprocess(rt,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:(0,_.stack)(Re.map((rt,ft)=>(0,_.cat)([rt.pixel_values,He[ft].pixel_values],0)),0),original_sizes:Re.map(rt=>rt.original_size),reshaped_input_sizes:Re.map(rt=>rt.reshaped_input_size)}}}class Ye extends z{constructor(Z){var ve;super(Z),(ve=this.config).mel_filters??(ve.mel_filters=(0,h.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,h.window_function)(this.config.n_fft,"hann")}async _extract_fbank_features(Z){const ve=await(0,h.spectrogram)(Z,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}),Re=ve.data,He=(0,f.max)(Re)[0];for(let Xe=0;Xethis.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`."),ve=Z.slice(0,this.config.n_samples)):(ve=new Float32Array(this.config.n_samples),ve.set(Z)),{input_features:(await this._extract_fbank_features(ve)).unsqueeze_(0)}}}class tt extends z{_zero_mean_unit_var_norm(Z){const Re=Z.reduce((Xe,rt)=>Xe+rt,0)/Z.length,He=Z.reduce((Xe,rt)=>Xe+(rt-Re)**2,0)/Z.length;return Z.map(Xe=>(Xe-Re)/Math.sqrt(He+1e-7))}async _call(Z){w(Z,"Wav2Vec2FeatureExtractor"),Z instanceof Float64Array&&(Z=new Float32Array(Z));let ve=Z;this.config.do_normalize&&(ve=this._zero_mean_unit_var_norm(ve));const Re=[1,ve.length];return{input_values:new _.Tensor("float32",ve,Re),attention_mask:new _.Tensor("int64",new BigInt64Array(ve.length).fill(1n),Re)}}}class A extends z{constructor(Z){super(Z);const ve=this.config.sampling_rate,Re=(0,h.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(ve/2),ve,null,"kaldi",!0);for(let He=0;HeRe*32768),(0,h.spectrogram)(Z,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:ve,transpose:!0})}async _call(Z,{padding:ve=!0,pad_to_multiple_of:Re=2,do_normalize_per_mel_bins:He=!0,return_attention_mask:Xe=!0}={}){w(Z,"SeamlessM4TFeatureExtractor");let rt=await this._extract_fbank_features(Z,this.config.max_length);if(He){const[Ot,Ut]=rt.dims,Kt=rt.data;for(let Qt=0;Qt0){const Jt=new Float32Array(Ut*(Ot+Qt));Jt.set(Kt),Jt.fill(this.config.padding_value,Kt.length);const qt=Ot+Qt;rt=new _.Tensor(rt.type,Jt,[qt,Ut]),Xe&&(ft=new _.Tensor("int64",new BigInt64Array(qt),[1,qt]),ft.data.fill(1n,0,Ot))}}const[ht,Mt]=rt.dims,wt=this.config.stride;if(ht%wt!==0)throw new Error(`The number of frames (${ht}) must be a multiple of the stride (${wt}).`);const Rt=rt.view(1,Math.floor(ht/wt),Mt*wt),at={input_features:Rt};if(Xe){const Ot=Rt.dims[1],Ut=new BigInt64Array(Ot);if(ft){const Kt=ft.data;for(let Qt=1,Jt=0;Qt0)if(Re==="rand_trunc"){const ft=Math.floor(Math.random()*(rt+1));Z=Z.subarray(ft,ft+ve),Xe=await this._extract_fbank_features(Z,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${Re}" not implemented`);else{if(rt<0){let ft=new Float64Array(ve);if(ft.set(Z),He==="repeat")for(let ht=Z.length;ht({id:ht,start:Mt*Re,end:wt*Re,confidence:St/(wt-Mt)})))}return He}}class te extends z{constructor(Z){super(Z);const ve=this.config.sampling_rate,Re=(0,h.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(ve/2),ve,null,"kaldi",!0);for(let He=0;Heve*32768),(0,h.spectrogram)(Z,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(Z){w(Z,"WeSpeakerFeatureExtractor");const ve=(await this._extract_fbank_features(Z)).unsqueeze_(0);if(this.config.fbank_centering_span===null){const Re=ve.mean(1).data,He=ve.data,[Xe,rt,ft]=ve.dims;for(let ht=0;ht/gm,bboxes:/([^<]+)?/gm},this.size_per_bin=1e3}construct_prompts(Z){typeof Z=="string"&&(Z=[Z]);const ve=[];for(const Re of Z)if(this.task_prompts_without_inputs.has(Re))ve.push(this.task_prompts_without_inputs.get(Re));else{for(const[He,Xe]of this.task_prompts_with_input)if(Re.includes(He)){ve.push(Xe.replaceAll("{input}",Re).replaceAll(He,""));break}ve.length!==Z.length&&ve.push(Re)}return ve}post_process_generation(Z,ve,Re){const He=this.tasks_answer_post_processing_type.get(ve)??"pure_text";Z=Z.replaceAll("","").replaceAll("","");let Xe;switch(He){case"pure_text":Xe=Z;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":const rt=He==="ocr"?"quad_boxes":"bboxes",ft=Z.matchAll(this.regexes[rt]),ht=[],Mt=[];for(const[wt,St,...Rt]of ft)ht.push(St?St.trim():ht.at(-1)??""),Mt.push(Rt.map((at,Ot)=>(Number(at)+.5)/this.size_per_bin*Re[Ot%2]));Xe={labels:ht,[rt]:Mt};break;default:throw new Error(`Task "${ve}" (of type "${He}") not yet implemented.`)}return{[ve]:Xe}}}class Je{static async from_pretrained(Z,{progress_callback:ve=null,config:Re=null,cache_dir:He=null,local_files_only:Xe=!1,revision:rt="main"}={}){let ft=Re??await(0,l.getModelJSON)(Z,"preprocessor_config.json",!0,{progress_callback:ve,config:Re,cache_dir:He,local_files_only:Xe,revision:rt}),ht=ft.feature_extractor_type??ft.image_processor_type,Mt=this.FEATURE_EXTRACTOR_CLASS_MAPPING[ht];if(!Mt)if(ft.size!==void 0)console.warn(`Feature extractor type "${ht}" not found, assuming ImageFeatureExtractor due to size parameter in config.`),Mt=S;else throw new Error(`Unknown Feature Extractor type: ${ht}`);let wt=this.PROCESSOR_CLASS_MAPPING[ft.processor_class]??B,St=new Mt(ft);return new wt(St)}}qe(Je,"FEATURE_EXTRACTOR_CLASS_MAPPING",{ImageFeatureExtractor:S,WhisperFeatureExtractor:Ye,ViTFeatureExtractor:Ce,MobileViTFeatureExtractor:Q,MobileViTImageProcessor:ae,MobileNetV1FeatureExtractor:R,MobileNetV2FeatureExtractor:Me,MobileNetV3FeatureExtractor:Qe,MobileNetV4FeatureExtractor:ge,OwlViTFeatureExtractor:Se,Owlv2ImageProcessor:X,CLIPFeatureExtractor:O,CLIPImageProcessor:N,Florence2Processor:ut,ChineseCLIPFeatureExtractor:j,SiglipImageProcessor:D,ConvNextFeatureExtractor:Y,ConvNextImageProcessor:de,SegformerFeatureExtractor:P,BitImageProcessor:I,DPTImageProcessor:x,DPTFeatureExtractor:y,GLPNFeatureExtractor:U,BeitFeatureExtractor:De,DeiTFeatureExtractor:Ke,DetrFeatureExtractor:ot,RTDetrImageProcessor:me,YolosFeatureExtractor:dt,DonutFeatureExtractor:Be,NougatImageProcessor:We,EfficientNetImageProcessor:ye,ViTImageProcessor:ee,VitMatteImageProcessor:je,SamImageProcessor:Ge,Swin2SRImageProcessor:Te,Wav2Vec2FeatureExtractor:tt,SeamlessM4TFeatureExtractor:A,SpeechT5FeatureExtractor:we,ASTFeatureExtractor:Ae,ClapFeatureExtractor:$e,PyAnnoteFeatureExtractor:se,WeSpeakerFeatureExtractor:te}),qe(Je,"PROCESSOR_CLASS_MAPPING",{WhisperProcessor:L,Wav2Vec2ProcessorWithLM:ue,PyAnnoteProcessor:le,SamProcessor:J,SpeechT5Processor:ke,OwlViTProcessor:Ne,Florence2Processor:ut})},"./src/tokenizers.js":(e,t,n)=>{n.r(t),n.d(t,{AlbertTokenizer:()=>Ut,AutoTokenizer:()=>Rn,BartTokenizer:()=>Nr,BertTokenizer:()=>Ot,BlenderbotSmallTokenizer:()=>jo,BlenderbotTokenizer:()=>ho,BloomTokenizer:()=>Fr,CLIPTokenizer:()=>Xt,CamembertTokenizer:()=>Pt,CodeGenTokenizer:()=>po,CodeLlamaTokenizer:()=>ks,CohereTokenizer:()=>Br,ConvBertTokenizer:()=>Qr,DebertaTokenizer:()=>Jt,DebertaV2Tokenizer:()=>qt,DistilBertTokenizer:()=>mt,ElectraTokenizer:()=>sn,EsmTokenizer:()=>Bi,FalconTokenizer:()=>Lo,GPT2Tokenizer:()=>bi,GPTNeoXTokenizer:()=>Ro,GemmaTokenizer:()=>co,Grok1Tokenizer:()=>di,HerbertTokenizer:()=>Er,LlamaTokenizer:()=>xi,M2M100Tokenizer:()=>Yi,MBart50Tokenizer:()=>Wr,MBartTokenizer:()=>mn,MPNetTokenizer:()=>Do,MarianTokenizer:()=>Bo,MobileBertTokenizer:()=>Kt,NllbTokenizer:()=>Ti,NougatTokenizer:()=>mo,PreTrainedTokenizer:()=>at,Qwen2Tokenizer:()=>Ss,RoFormerTokenizer:()=>Cr,RobertaTokenizer:()=>ci,SiglipTokenizer:()=>Zi,SpeechT5Tokenizer:()=>Uo,SqueezeBertTokenizer:()=>Qt,T5Tokenizer:()=>Li,TokenizerModel:()=>Ce,VitsTokenizer:()=>Vo,Wav2Vec2CTCTokenizer:()=>No,WhisperTokenizer:()=>fo,XLMRobertaTokenizer:()=>Oo,XLMTokenizer:()=>Bt,is_chinese_char:()=>U});var o=n("./src/utils/generic.js"),a=n("./src/utils/core.js"),l=n("./src/utils/hub.js"),f=n("./src/utils/maths.js"),_=n("./src/utils/tensor.js"),h=n("./src/utils/data-structures.js"),g=n("./node_modules/@huggingface/jinja/dist/index.js"),M=n("./src/models/whisper/common_whisper.js"),w=n("./src/utils/constants.js");async function C(Ue,W){const fe=await Promise.all([(0,l.getModelJSON)(Ue,"tokenizer.json",!0,W),(0,l.getModelJSON)(Ue,"tokenizer_config.json",!0,W)]);return W.legacy!==null&&(fe[1].legacy=W.legacy),fe}function k(Ue,W){const fe=[];let Pe=0;for(const ze of Ue.matchAll(W)){const Oe=ze[0];Pe0&&fe.push(Oe),Pe=ze.index+Oe.length}return Pe=19968&&Ue<=40959||Ue>=13312&&Ue<=19903||Ue>=131072&&Ue<=173791||Ue>=173824&&Ue<=177983||Ue>=177984&&Ue<=178207||Ue>=178208&&Ue<=183983||Ue>=63744&&Ue<=64255||Ue>=194560&&Ue<=195103}function O(Ue,W,fe){const Pe=[];let ze=0;for(;zethis.tokens_to_ids.get(fe)??this.unk_token_id)}convert_ids_to_tokens(W){return W.map(fe=>this.vocab[fe]??this.unk_token)}}class ee extends Ce{constructor(W){super(W),this.tokens_to_ids=S(W.vocab),this.unk_token_id=this.tokens_to_ids.get(W.unk_token),this.unk_token=W.unk_token,this.max_input_chars_per_word=W.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(const[fe,Pe]of this.tokens_to_ids)this.vocab[Pe]=fe}encode(W){const fe=[];for(const Pe of W){const ze=[...Pe];if(ze.length>this.max_input_chars_per_word){fe.push(this.unk_token);continue}let Oe=!1,nt=0;const xt=[];for(;nt0&&(At=this.config.continuing_subword_prefix+At),this.tokens_to_ids.has(At)){Tt=At;break}--kt}if(Tt===null){Oe=!0;break}xt.push(Tt),nt=kt}Oe?fe.push(this.unk_token):fe.push(...xt)}return fe}}class ye extends Ce{constructor(W,fe){super(W);const Pe=W.vocab.length;this.vocab=new Array(Pe),this.scores=new Array(Pe);for(let ze=0;ze[ze,Oe])),this.bosToken=" ",this.bosTokenId=this.tokens_to_ids.get(this.bosToken),this.eosToken=fe.eos_token,this.eosTokenId=this.tokens_to_ids.get(this.eosToken),this.unkToken=this.vocab[this.unk_token_id],this.minScore=(0,f.min)(this.scores)[0],this.unkScore=this.minScore-10,this.scores[this.unk_token_id]=this.unkScore,this.trie=new h.CharTrie,this.trie.extend(this.vocab),this.fuse_unk=!0}populateNodes(W){const fe=W.sentence,Pe=fe.length;let ze=0;for(;ze{const Ue=[...Array.from({length:94},(ze,Oe)=>Oe+33),...Array.from({length:12},(ze,Oe)=>Oe+161),...Array.from({length:82},(ze,Oe)=>Oe+174)],W=Ue.slice();let fe=0;for(let ze=0;ze<256;++ze)Ue.includes(ze)||(Ue.push(ze),W.push(256+fe),fe+=1);const Pe=W.map(ze=>String.fromCharCode(ze));return Object.fromEntries(Ue.map((ze,Oe)=>[ze,Pe[Oe]]))})(),Me=(0,a.reverseDictionary)(R);class Qe extends Ce{constructor(W){super(W),this.BPE_SPLIT_TOKEN=" ",this.tokens_to_ids=S(W.vocab),this.unk_token_id=this.tokens_to_ids.get(W.unk_token),this.unk_token=W.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(const[fe,Pe]of this.tokens_to_ids)this.vocab[Pe]=fe;this.bpe_ranks=new Map(W.merges.map((fe,Pe)=>[fe,Pe])),this.merges=W.merges.map(fe=>fe.split(this.BPE_SPLIT_TOKEN)),this.end_of_word_suffix=W.end_of_word_suffix,this.continuing_subword_suffix=W.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(W){if(W.length===0)return[];const fe=this.cache.get(W);if(fe!==void 0)return fe;const Pe=Array.from(W);this.end_of_word_suffix&&(Pe[Pe.length-1]+=this.end_of_word_suffix);let ze=[];if(Pe.length>1){const Oe=new h.PriorityQueue((kt,Tt)=>kt.score`<0x${nt.toString(16).toUpperCase().padStart(2,"0")}>`)):fe.push(this.unk_token)}return fe}}class ge extends Ce{constructor(W,fe){super(W),this.tokens_to_ids=S(fe.target_lang?W.vocab[fe.target_lang]:W.vocab),this.bos_token=fe.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=fe.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=fe.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=fe.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[Pe,ze]of this.tokens_to_ids)this.vocab[ze]=Pe}encode(W){return W}}class Q extends o.Callable{constructor(W){super(),this.config=W}static fromConfig(W){if(W===null)return null;switch(W.type){case"BertNormalizer":return new dt(W);case"Precompiled":return new Xe(W);case"Sequence":return new ot(W);case"Replace":return new ae(W);case"NFC":return new Se(W);case"NFKC":return new X(W);case"NFKD":return new me(W);case"Strip":return new Ke(W);case"StripAccents":return new De(W);case"Lowercase":return new Be(W);case"Prepend":return new We(W);default:throw new Error(`Unknown Normalizer type: ${W.type}`)}}normalize(W){throw Error("normalize should be implemented in subclass.")}_call(W){return this.normalize(W)}}class ae extends Q{normalize(W){const fe=z(this.config.pattern);return fe===null?W:W.replaceAll(fe,this.config.content)}}class Se extends Q{normalize(W){return W=W.normalize("NFC"),W}}class X extends Q{normalize(W){return W=W.normalize("NFKC"),W}}class me extends Q{normalize(W){return W=W.normalize("NFKD"),W}}class Ke extends Q{normalize(W){return this.config.strip_left&&this.config.strip_right?W=W.trim():(this.config.strip_left&&(W=W.trimStart()),this.config.strip_right&&(W=W.trimEnd())),W}}class De extends Q{normalize(W){return W=x(W),W}}class Be extends Q{normalize(W){return W=W.toLowerCase(),W}}class We extends Q{normalize(W){return W=this.config.prepend+W,W}}class ot extends Q{constructor(W){super(W),this.normalizers=W.normalizers.map(fe=>Q.fromConfig(fe))}normalize(W){return this.normalizers.reduce((fe,Pe)=>Pe.normalize(fe),W)}}class dt extends Q{_tokenize_chinese_chars(W){const fe=[];for(let Pe=0;Pethis.pre_tokenize_text(Pe,fe)):this.pre_tokenize_text(W,fe)).flat()}_call(W,fe){return this.pre_tokenize(W,fe)}}class Te extends Ge{constructor(W){super(),this.pattern=new RegExp(`[^\\s${j}]+|[${j}]`,"gu")}pre_tokenize_text(W,fe){return W.trim().match(this.pattern)||[]}}class je extends Ge{constructor(W){super(),this.config=W,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=R,this.text_encoder=new TextEncoder}pre_tokenize_text(W,fe){return this.add_prefix_space&&!W.startsWith(" ")&&(W=" "+W),(this.use_regex?W.match(this.pattern)||[]:[W]).map(ze=>Array.from(this.text_encoder.encode(ze),Oe=>this.byte_encoder[Oe]).join(""))}}class Ye extends Ge{constructor(W){super(),this.config=W,this.pattern=z(this.config.pattern,this.config.invert)}pre_tokenize_text(W,fe){return this.pattern===null?[]:this.config.invert?W.match(this.pattern)||[]:k(W,this.pattern)}}class tt extends Ge{constructor(W){super(),this.config=W,this.pattern=new RegExp(`[^${j}]+|[${j}]+`,"gu")}pre_tokenize_text(W,fe){return W.match(this.pattern)||[]}}class A extends Ge{constructor(W){super(),this.config=W;const fe=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(fe,"gu")}pre_tokenize_text(W,fe){return W.match(this.pattern)||[]}}class Ae extends o.Callable{constructor(W){super(),this.config=W}static fromConfig(W){if(W===null)return null;switch(W.type){case"TemplateProcessing":return new te(W);case"ByteLevel":return new we(W);case"RobertaProcessing":return new se(W);case"BertProcessing":return new $e(W);case"Sequence":return new B(W);default:throw new Error(`Unknown PostProcessor type: ${W.type}`)}}post_process(W,...fe){throw Error("post_process should be implemented in subclass.")}_call(W,...fe){return this.post_process(W,...fe)}}class $e extends Ae{constructor(W){super(W),this.cls=W.cls[0],this.sep=W.sep[0]}post_process(W,fe=null,{add_special_tokens:Pe=!0}={}){Pe&&(W=(0,a.mergeArrays)([this.cls],W,[this.sep]));let ze=new Array(W.length).fill(0);if(fe!==null){const Oe=Pe&&this instanceof se?[this.sep]:[],nt=Pe?[this.sep]:[];W=(0,a.mergeArrays)(W,Oe,fe,nt),ze=(0,a.mergeArrays)(ze,new Array(fe.length+Oe.length+nt.length).fill(1))}return{tokens:W,token_type_ids:ze}}}class se extends $e{}class te extends Ae{constructor(W){super(W),this.single=W.single,this.pair=W.pair}post_process(W,fe=null,{add_special_tokens:Pe=!0}={}){const ze=fe===null?this.single:this.pair;let Oe=[],nt=[];for(const xt of ze)"SpecialToken"in xt?Pe&&(Oe.push(xt.SpecialToken.id),nt.push(xt.SpecialToken.type_id)):"Sequence"in xt&&(xt.Sequence.id==="A"?(Oe=(0,a.mergeArrays)(Oe,W),nt=(0,a.mergeArrays)(nt,new Array(W.length).fill(xt.Sequence.type_id))):xt.Sequence.id==="B"&&(Oe=(0,a.mergeArrays)(Oe,fe),nt=(0,a.mergeArrays)(nt,new Array(fe.length).fill(xt.Sequence.type_id))));return{tokens:Oe,token_type_ids:nt}}}class we extends Ae{post_process(W,fe=null){return fe&&(W=(0,a.mergeArrays)(W,fe)),{tokens:W}}}class B extends Ae{constructor(W){super(W),this.processors=W.processors.map(fe=>Ae.fromConfig(fe))}post_process(W,fe=null,Pe={}){let ze;for(const Oe of this.processors)if(Oe instanceof we)W=Oe.post_process(W).tokens,fe&&(fe=Oe.post_process(fe).tokens);else{const nt=Oe.post_process(W,fe,Pe);W=nt.tokens,ze=nt.token_type_ids}return{tokens:W,token_type_ids:ze}}}class J extends o.Callable{constructor(W){super(),this.config=W,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets=W.trim_offsets}static fromConfig(W){if(W===null)return null;switch(W.type){case"WordPiece":return new Ne(W);case"Metaspace":return new He(W);case"ByteLevel":return new ut(W);case"Replace":return new L(W);case"ByteFallback":return new ue(W);case"Fuse":return new le(W);case"Strip":return new ke(W);case"Sequence":return new Ve(W);case"CTC":return new Je(W);case"BPEDecoder":return new Z(W);default:throw new Error(`Unknown Decoder type: ${W.type}`)}}_call(W){return this.decode(W)}decode(W){return this.decode_chain(W).join("")}decode_chain(W){throw Error("`decode_chain` should be implemented in subclass.")}}class L extends J{decode_chain(W){const fe=z(this.config.pattern);return fe===null?W:W.map(Pe=>Pe.replaceAll(fe,this.config.content))}}class ue extends J{constructor(W){super(W),this.text_decoder=new TextDecoder}decode_chain(W){const fe=[];let Pe=[];for(const ze of W){let Oe=null;if(ze.length===6&&ze.startsWith("<0x")&&ze.endsWith(">")){const nt=parseInt(ze.slice(3,5),16);isNaN(nt)||(Oe=nt)}if(Oe!==null)Pe.push(Oe);else{if(Pe.length>0){const nt=this.text_decoder.decode(Uint8Array.from(Pe));fe.push(nt),Pe=[]}fe.push(ze)}}if(Pe.length>0){const ze=this.text_decoder.decode(Uint8Array.from(Pe));fe.push(ze),Pe=[]}return fe}}class le extends J{decode_chain(W){return[W.join("")]}}class ke extends J{constructor(W){super(W),this.content=this.config.content,this.start=this.config.start,this.stop=this.config.stop}decode_chain(W){return W.map(fe=>{let Pe=0;for(let Oe=0;Oe(Pe!==0&&(fe.startsWith(this.config.prefix)?fe=fe.replace(this.config.prefix,""):fe=" "+fe),this.cleanup&&(fe=y(fe)),fe))}}class ut extends J{constructor(W){super(W),this.byte_decoder=Me,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(W){const fe=W.join(""),Pe=new Uint8Array([...fe].map(Oe=>this.byte_decoder[Oe]));return this.text_decoder.decode(Pe)}decode_chain(W){const fe=[];let Pe=[];for(const ze of W)this.added_tokens.find(Oe=>Oe.content===ze)!==void 0?(Pe.length>0&&(fe.push(this.convert_tokens_to_string(Pe)),Pe=[]),fe.push(ze)):Pe.push(ze);return Pe.length>0&&fe.push(this.convert_tokens_to_string(Pe)),fe}}class Je extends J{constructor(W){super(W),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(W){if(W.length===0)return"";const fe=[W[0]];for(let Oe=1;OeOe!==this.pad_token).join("");return this.cleanup&&(ze=y(ze).replaceAll(this.word_delimiter_token," ").trim()),ze}decode_chain(W){return[this.convert_tokens_to_string(W)]}}class Ve extends J{constructor(W){super(W),this.decoders=W.decoders.map(fe=>J.fromConfig(fe))}decode_chain(W){return this.decoders.reduce((fe,Pe)=>Pe.decode_chain(fe),W)}}class Z extends J{constructor(W){super(W),this.suffix=this.config.suffix}decode_chain(W){return W.map((fe,Pe)=>fe.replaceAll(this.suffix,Pe===W.length-1?"":" "))}}class ve extends J{decode_chain(W){let fe="";for(let Pe=1;PePe.normalize("NFKC")).join("~"):W=W.normalize("NFKC"),W}}class rt extends Ge{constructor(W){super(),this.tokenizers=W.pretokenizers.map(fe=>Ge.fromConfig(fe))}pre_tokenize_text(W,fe){return this.tokenizers.reduce((Pe,ze)=>ze.pre_tokenize(Pe,fe),[W])}}class ft extends Ge{constructor(W){super()}pre_tokenize_text(W,fe){return W.match(/\w+|[^\w\s]+/g)||[]}}class ht extends Ge{constructor(W){super()}pre_tokenize_text(W,fe){return N(W)}}class Mt extends Ge{constructor(W){super(),this.config=W,this.pattern=z(this.config.pattern),this.content=this.config.content}pre_tokenize_text(W,fe){return this.pattern===null?[W]:[W.replaceAll(this.pattern,this.config.content)]}}const wt=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function St(Ue,W,fe,Pe){for(const ze of Object.keys(Ue)){const Oe=W-Ue[ze].length,nt=fe(ze),xt=new Array(Oe).fill(nt);Ue[ze]=Pe==="right"?(0,a.mergeArrays)(Ue[ze],xt):(0,a.mergeArrays)(xt,Ue[ze])}}function Rt(Ue,W){for(const fe of Object.keys(Ue))Ue[fe].length=W}class at extends o.Callable{constructor(fe,Pe){super();qe(this,"return_token_type_ids",!1);qe(this,"padding_side","right");this._tokenizer_config=Pe,this.normalizer=Q.fromConfig(fe.normalizer),this.pre_tokenizer=Ge.fromConfig(fe.pre_tokenizer),this.model=Ce.fromConfig(fe.model,Pe),this.post_processor=Ae.fromConfig(fe.post_processor),this.decoder=J.fromConfig(fe.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];for(const ze of fe.added_tokens){const Oe=new de(ze);this.added_tokens.push(Oe),this.model.tokens_to_ids.set(Oe.content,Oe.id),this.model.vocab[Oe.id]=Oe.content,Oe.special&&(this.special_tokens.push(Oe.content),this.all_special_ids.push(Oe.id))}if(this.additional_special_tokens=Pe.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((ze,Oe)=>Oe.content.length-ze.content.length).map(ze=>`${ze.lstrip?"\\s*":""}(${(0,a.escapeRegExp)(ze.content)})${ze.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=Pe.model_max_length,this.remove_space=Pe.remove_space,this.clean_up_tokenization_spaces=Pe.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=Pe.do_lowercase_and_remove_accent??!1,Pe.padding_side&&(this.padding_side=Pe.padding_side),this.legacy=!1,this.chat_template=Pe.chat_template??null,Array.isArray(this.chat_template)){const ze=Object.create(null);for(const{name:Oe,template:nt}of this.chat_template){if(typeof Oe!="string"||typeof nt!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');ze[Oe]=nt}this.chat_template=ze}this._compiled_template_cache=new Map}getToken(...fe){for(const Pe of fe){const ze=this._tokenizer_config[Pe];if(ze)if(typeof ze=="object"){if(ze.__type==="AddedToken")return ze.content;throw Error(`Unknown token: ${ze}`)}else return ze}return null}static async from_pretrained(fe,{progress_callback:Pe=null,config:ze=null,cache_dir:Oe=null,local_files_only:nt=!1,revision:xt="main",legacy:kt=null}={}){const Tt=await C(fe,{progress_callback:Pe,config:ze,cache_dir:Oe,local_files_only:nt,revision:xt,legacy:kt});return new this(...Tt)}_call(fe,{text_pair:Pe=null,add_special_tokens:ze=!0,padding:Oe=!1,truncation:nt=null,max_length:xt=null,return_tensor:kt=!0,return_token_type_ids:Tt=null}={}){const At=Array.isArray(fe);let Zt;if(At){if(fe.length===0)throw Error("text array must be non-empty");if(Pe!==null){if(Array.isArray(Pe)){if(fe.length!==Pe.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");Zt=fe.map((rr,Gt)=>this._encode_plus(rr,{text_pair:Pe[Gt],add_special_tokens:ze,return_token_type_ids:Tt}))}else Zt=fe.map(rr=>this._encode_plus(rr,{add_special_tokens:ze,return_token_type_ids:Tt}))}else{if(fe==null)throw Error("text may not be null or undefined");if(Array.isArray(Pe))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(fe,{text_pair:Pe,add_special_tokens:ze,return_token_type_ids:Tt})]}if(xt===null?Oe==="max_length"?xt=this.model_max_length:xt=(0,f.max)(Zt.map(rr=>rr.input_ids.length))[0]:nt||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."),xt=Math.min(xt,this.model_max_length??1/0),Oe||nt)for(let rr=0;rrxt?nt&&Rt(Zt[rr],xt):Oe&&St(Zt[rr],xt,Gt=>Gt==="input_ids"?this.pad_token_id:0,this.padding_side));const Pr={};if(kt){if(!(Oe&&nt)&&Zt.some(Gt=>{var mr;for(const kn of Object.keys(Gt))if(Gt[kn].length!==((mr=Zt[0][kn])==null?void 0:mr.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 rr=[Zt.length,Zt[0].input_ids.length];for(const Gt of Object.keys(Zt[0]))Pr[Gt]=new _.Tensor("int64",BigInt64Array.from(Zt.flatMap(mr=>mr[Gt]).map(BigInt)),rr)}else{for(const rr of Object.keys(Zt[0]))Pr[rr]=Zt.map(Gt=>Gt[rr]);if(!At)for(const rr of Object.keys(Pr))Pr[rr]=Pr[rr][0]}return Pr}_encode_text(fe){return fe===null?null:(this.added_tokens_regex?fe.split(this.added_tokens_regex).filter(Oe=>Oe):[fe]).map((Oe,nt)=>{if(this.added_tokens.find(kt=>kt.content===Oe)!==void 0)return Oe;{if(this.remove_space===!0&&(Oe=Oe.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(Oe=I(Oe)),this.normalizer!==null&&(Oe=this.normalizer(Oe)),Oe.length===0)return[];const kt=this.pre_tokenizer!==null?this.pre_tokenizer(Oe,{section_index:nt}):[Oe];return this.model(kt)}}).flat()}_encode_plus(fe,{text_pair:Pe=null,add_special_tokens:ze=!0,return_token_type_ids:Oe=null}={}){const{tokens:nt,token_type_ids:xt}=this._tokenize_helper(fe,{pair:Pe,add_special_tokens:ze}),kt=this.model.convert_tokens_to_ids(nt),Tt={input_ids:kt,attention_mask:new Array(kt.length).fill(1)};return(Oe??this.return_token_type_ids)&&xt&&(Tt.token_type_ids=xt),Tt}_tokenize_helper(fe,{pair:Pe=null,add_special_tokens:ze=!1}={}){const Oe=this._encode_text(fe),nt=this._encode_text(Pe);return this.post_processor?this.post_processor(Oe,nt,{add_special_tokens:ze}):{tokens:(0,a.mergeArrays)(Oe??[],nt??[])}}tokenize(fe,{pair:Pe=null,add_special_tokens:ze=!1}={}){return this._tokenize_helper(fe,{pair:Pe,add_special_tokens:ze}).tokens}encode(fe,{text_pair:Pe=null,add_special_tokens:ze=!0,return_token_type_ids:Oe=null}={}){return this._encode_plus(fe,{text_pair:Pe,add_special_tokens:ze,return_token_type_ids:Oe}).input_ids}batch_decode(fe,Pe={}){return fe instanceof _.Tensor&&(fe=fe.tolist()),fe.map(ze=>this.decode(ze,Pe))}decode(fe,Pe={}){if(fe instanceof _.Tensor&&(fe=P(fe)),!Array.isArray(fe)||fe.length===0||!(0,a.isIntegralNumber)(fe[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(fe,Pe)}decode_single(fe,{skip_special_tokens:Pe=!1,clean_up_tokenization_spaces:ze=null}){let Oe=this.model.convert_ids_to_tokens(fe);Pe&&(Oe=Oe.filter(xt=>!this.special_tokens.includes(xt)));let nt=this.decoder?this.decoder(Oe):Oe.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(nt=nt.replaceAll(this.decoder.end_of_word_suffix," "),Pe&&(nt=nt.trim())),(ze??this.clean_up_tokenization_spaces)&&(nt=y(nt)),nt}apply_chat_template(fe,{tools:Pe=null,documents:ze=null,chat_template:Oe=null,add_generation_prompt:nt=!1,tokenize:xt=!0,padding:kt=!1,truncation:Tt=!1,max_length:At=null,return_tensor:Zt=!0,return_dict:Pr=!1,tokenizer_kwargs:rr={},...Gt}={}){if(this.chat_template&&typeof this.chat_template=="object"||this.chat_template===null){const st=this.chat_template;if(Oe!==null&&Object.hasOwn(st,Oe))Oe=st[Oe];else if(Oe===null&&"default"in st)Oe=st.default;else if(Oe===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(st).sort()}.`)}else if(this.chat_template)Oe=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 Oe!="string")throw Error(`chat_template must be a string, but got ${typeof Oe}`);let mr=this._compiled_template_cache.get(Oe);mr===void 0&&(mr=new g.Template(Oe),this._compiled_template_cache.set(Oe,mr));const kn=Object.create(null);for(const st of wt){const qn=this.getToken(st);qn&&(kn[st]=qn)}const pn=mr.render({messages:fe,add_generation_prompt:nt,tools:Pe,documents:ze,...kn,...Gt});if(xt){const st=this._call(pn,{add_special_tokens:!1,padding:kt,truncation:Tt,max_length:At,return_tensor:Zt,...rr});return Pr?st:st.input_ids}return pn}}class Ot extends at{constructor(){super(...arguments);qe(this,"return_token_type_ids",!0)}}class Ut extends at{constructor(){super(...arguments);qe(this,"return_token_type_ids",!0)}}class Kt extends at{constructor(){super(...arguments);qe(this,"return_token_type_ids",!0)}}class Qt extends at{constructor(){super(...arguments);qe(this,"return_token_type_ids",!0)}}class Jt extends at{constructor(){super(...arguments);qe(this,"return_token_type_ids",!0)}}class qt extends at{constructor(){super(...arguments);qe(this,"return_token_type_ids",!0)}}class Er extends at{constructor(){super(...arguments);qe(this,"return_token_type_ids",!0)}}class Qr extends at{constructor(){super(...arguments);qe(this,"return_token_type_ids",!0)}}class Cr extends at{constructor(){super(...arguments);qe(this,"return_token_type_ids",!0)}}class mt extends at{}class Pt extends at{}class Bt extends at{constructor(fe,Pe){super(fe,Pe);qe(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 sn extends at{constructor(){super(...arguments);qe(this,"return_token_type_ids",!0)}}class Li extends at{}class bi extends at{}class Nr extends at{}class mn extends at{constructor(W,fe){super(W,fe),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.special_tokens.filter(Pe=>this.languageRegex.test(Pe)),this.lang_to_token=Pe=>Pe}_build_translation_inputs(W,fe,Pe){return Mi(this,W,fe,Pe)}}class Wr extends mn{}class ci extends at{}class Fr extends at{constructor(W,fe){var Oe,nt;const Pe=".,!?…。,、।۔،",ze=(nt=(Oe=W.pre_tokenizer)==null?void 0:Oe.pretokenizers[0])==null?void 0:nt.pattern;ze&&ze.Regex===` ?[^(\\s|[${Pe}])]+`&&(ze.Regex=` ?[^\\s${Pe}]+`),super(W,fe)}}const Ri="▁";class xi extends at{constructor(fe,Pe){super(fe,Pe);qe(this,"padding_side","left");this.legacy=Pe.legacy??!0,this.legacy||(this.normalizer=null,this.pre_tokenizer=new Re({replacement:Ri,add_prefix_space:!0,prepend_scheme:"first"}))}_encode_text(fe){if(fe===null)return null;if(this.legacy||fe.length===0)return super._encode_text(fe);let Pe=super._encode_text(Ri+fe.replaceAll(Ri," "));return Pe.length>1&&Pe[0]===Ri&&this.special_tokens.includes(Pe[1])&&(Pe=Pe.slice(1)),Pe}}class ks extends at{}class Oo extends at{}class Do extends at{}class Lo extends at{}class Ro extends at{}class Bi extends at{}class Ss extends at{}class co extends at{}class di extends at{}function Mi(Ue,W,fe,Pe){if(!("language_codes"in Ue)||!Array.isArray(Ue.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in Ue)||!(Ue.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in Ue)||typeof Ue.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");const ze=Pe.src_lang,Oe=Pe.tgt_lang;if(!Ue.language_codes.includes(Oe))throw new Error(`Target language code "${Oe}" is not valid. Must be one of: {${Ue.language_codes.join(", ")}}`);if(ze!==void 0){if(!Ue.language_codes.includes(ze))throw new Error(`Source language code "${ze}" is not valid. Must be one of: {${Ue.language_codes.join(", ")}}`);for(const nt of Ue.post_processor.config.single)if("SpecialToken"in nt&&Ue.languageRegex.test(nt.SpecialToken.id)){nt.SpecialToken.id=Ue.lang_to_token(ze);break}}return Pe.forced_bos_token_id=Ue.model.convert_tokens_to_ids([Ue.lang_to_token(Oe)])[0],Ue._call(W,fe)}class Ti extends at{constructor(W,fe){super(W,fe),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.special_tokens.filter(Pe=>this.languageRegex.test(Pe)),this.lang_to_token=Pe=>Pe}_build_translation_inputs(W,fe,Pe){return Mi(this,W,fe,Pe)}}class Yi extends at{constructor(W,fe){super(W,fe),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.special_tokens.filter(Pe=>this.languageRegex.test(Pe)).map(Pe=>Pe.slice(2,-2)),this.lang_to_token=Pe=>`__${Pe}__`}_build_translation_inputs(W,fe,Pe){return Mi(this,W,fe,Pe)}}class fo extends at{get timestamp_begin(){return this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0]+1}_decode_asr(W,{return_timestamps:fe=!1,return_language:Pe=!1,time_precision:ze=null,force_full_sequences:Oe=!0}={}){if(ze===null)throw Error("Must specify time_precision");let nt=null;const xt=fe==="word";function kt(){return{language:nt,timestamp:[null,null],text:""}}const Tt=[];let At=kt(),Zt=0;const Pr=this.timestamp_begin;let rr=[],Gt=[],mr=!1,kn=null;const pn=new Set(this.all_special_ids);for(const xr of W){const an=xr.tokens,$n=xt?xr.token_timestamps:null;let Yt=null,Bn=Pr;if("stride"in xr){const[kr,Ct,wr]=xr.stride;if(Zt-=Ct,kn=kr-wr,Ct&&(Bn=Ct/ze+Pr),wr)for(let zr=an.length-1;zr>=0;--zr){const Gr=Number(an[zr]);if(Gr>=Pr){if(Yt!==null&&(Gr-Pr)*ze=Pr){const wr=(Ct-Pr)*ze+Zt,zr=(0,f.round)(wr,2);if(Yt!==null&&Ct>=Yt)mr=!0;else if(mr||rr.length>0&&Ct0?(rr.push(gn),xt&&Gt.push(Tr)):rr.every(kr=>kr.length===0)&&(At=kt(),rr=[],gn=[],Gt=[],Tr=[])}if(rr.length>0){if(Oe&&fe)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[xr,an]=this.findLongestCommonSequence(rr,Gt),$n=this.decode(xr);At.text=$n,xt&&(At.words=this.collateWordTimestamps(xr,an,nt)),Tt.push(At)}let st=Object.create(null);const qn=Tt.map(xr=>xr.text).join("");if(fe||Pe){for(let xr=0;xr0;let xt=nt?[]:null,kt=nt?fe[0]:null;for(let Tt=1;Ttzr===Tr[Gr]&&kt[an+Gr]<=fe[Tt][Bn+Gr]).length:kr=Yt.filter((zr,Gr)=>zr===Tr[Gr]).length;const Ct=xr/1e4,wr=kr/xr+Ct;kr>1&&wr>Zt&&(Zt=wr,Pr=[an,$n,Bn,gn])}const[Gt,mr,kn,pn]=Pr,st=Math.floor((mr+Gt)/2),qn=Math.floor((pn+kn)/2);Oe.push(...Pe.slice(0,st)),Pe=At.slice(qn),ze=Pe.length,nt&&(xt.push(...kt.slice(0,st)),kt=fe[Tt].slice(qn))}return Oe.push(...Pe),nt?(xt.push(...kt),[Oe,xt]):[Oe,[]]}collateWordTimestamps(W,fe,Pe){const[ze,Oe,nt]=this.combineTokensIntoWords(W,Pe),xt=[];for(let kt=0;kt=ze){const xt=((nt-ze)*Pe).toFixed(2);Oe.push(`<|${xt}|>`),Oe.push([])}else Oe[Oe.length-1].push(nt);return Oe=Oe.map(nt=>typeof nt=="string"?nt:super.decode(nt,fe)),Oe.join("")}splitTokensOnUnicode(W){const fe=this.decode(W,{decode_with_timestamps:!0}),Pe="�",ze=[],Oe=[],nt=[];let xt=[],kt=[],Tt=0;for(let At=0;At=this.model.tokens_to_ids.get("<|endoftext|>"),Gt=At.startsWith(" "),mr=At.trim(),kn=kt.test(mr);if(rr||Gt||kn||Oe.length===0)Oe.push(At),nt.push(Zt),xt.push(Pr);else{const pn=Oe.length-1;Oe[pn]+=At,nt[pn].push(...Zt),xt[pn].push(...Pr)}}return[Oe,nt,xt]}mergePunctuations(W,fe,Pe,ze,Oe){const nt=structuredClone(W),xt=structuredClone(fe),kt=structuredClone(Pe);let Tt=nt.length-2,At=nt.length-1;for(;Tt>=0;)nt[Tt].startsWith(" ")&&ze.includes(nt[Tt].trim())?(nt[At]=nt[Tt]+nt[At],xt[At]=(0,a.mergeArrays)(xt[Tt],xt[At]),kt[At]=(0,a.mergeArrays)(kt[Tt],kt[At]),nt[Tt]="",xt[Tt]=[],kt[Tt]=[]):At=Tt,--Tt;for(Tt=0,At=1;AtZt),xt.filter(Zt=>Zt.length>0),kt.filter(Zt=>Zt.length>0)]}get_decoder_prompt_ids({language:W=null,task:fe=null,no_timestamps:Pe=!0}={}){const ze=[];if(W){const Oe=(0,M.whisper_language_to_code)(W),nt=this.model.tokens_to_ids.get(`<|${Oe}|>`);if(nt===void 0)throw new Error(`Unable to find language "${Oe}" in model vocabulary. Please report this issue at ${w.GITHUB_ISSUE_URL}.`);ze.push(nt)}else ze.push(null);if(fe){if(fe=fe.toLowerCase(),fe!=="transcribe"&&fe!=="translate")throw new Error(`Task "${fe}" is not supported. Must be one of: ["transcribe", "translate"]`);const Oe=this.model.tokens_to_ids.get(`<|${fe}|>`);if(Oe===void 0)throw new Error(`Unable to find task "${fe}" in model vocabulary. Please report this issue at ${w.GITHUB_ISSUE_URL}.`);ze.push(Oe)}else ze.push(null);if(Pe){const Oe=this.model.tokens_to_ids.get("<|notimestamps|>");if(Oe===void 0)throw new Error(`Unable to find "<|notimestamps|>" in model vocabulary. Please report this issue at ${w.GITHUB_ISSUE_URL}.`);ze.push(Oe)}return ze.map((Oe,nt)=>[nt+1,Oe]).filter(Oe=>Oe[1]!==null)}}class po extends at{}class Xt extends at{}class Zi extends at{}class Bo extends at{constructor(W,fe){super(W,fe),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=this.model.vocab.filter(Pe=>this.languageRegex.test(Pe)),console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(W){if(W===null)return null;const[fe,...Pe]=W.trim().split(this.languageRegex);if(Pe.length===0)return super._encode_text(fe);if(Pe.length===2){const[ze,Oe]=Pe;return this.supported_language_codes.includes(ze)||console.warn(`Unsupported language code "${ze}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),(0,a.mergeArrays)([ze],super._encode_text(Oe))}}}class No extends at{}class ho extends at{}class jo extends at{}class Uo extends at{}class mo extends at{}class Vo extends at{constructor(W,fe){super(W,fe),this.decoder=new ve({})}}class Br extends at{}class Rn{static async from_pretrained(W,{progress_callback:fe=null,config:Pe=null,cache_dir:ze=null,local_files_only:Oe=!1,revision:nt="main",legacy:xt=null}={}){var Pr;const[kt,Tt]=await C(W,{progress_callback:fe,config:Pe,cache_dir:ze,local_files_only:Oe,revision:nt,legacy:xt}),At=((Pr=Tt.tokenizer_class)==null?void 0:Pr.replace(/Fast$/,""))??"PreTrainedTokenizer";let Zt=this.TOKENIZER_CLASS_MAPPING[At];return Zt||(console.warn(`Unknown tokenizer class "${At}", attempting to construct from base class.`),Zt=at),new Zt(kt,Tt)}}qe(Rn,"TOKENIZER_CLASS_MAPPING",{T5Tokenizer:Li,DistilBertTokenizer:mt,CamembertTokenizer:Pt,DebertaTokenizer:Jt,DebertaV2Tokenizer:qt,BertTokenizer:Ot,HerbertTokenizer:Er,ConvBertTokenizer:Qr,RoFormerTokenizer:Cr,XLMTokenizer:Bt,ElectraTokenizer:sn,MobileBertTokenizer:Kt,SqueezeBertTokenizer:Qt,AlbertTokenizer:Ut,GPT2Tokenizer:bi,BartTokenizer:Nr,MBartTokenizer:mn,MBart50Tokenizer:Wr,RobertaTokenizer:ci,WhisperTokenizer:fo,CodeGenTokenizer:po,CLIPTokenizer:Xt,SiglipTokenizer:Zi,MarianTokenizer:Bo,BloomTokenizer:Fr,NllbTokenizer:Ti,M2M100Tokenizer:Yi,LlamaTokenizer:xi,CodeLlamaTokenizer:ks,XLMRobertaTokenizer:Oo,MPNetTokenizer:Do,FalconTokenizer:Lo,GPTNeoXTokenizer:Ro,EsmTokenizer:Bi,Wav2Vec2CTCTokenizer:No,BlenderbotTokenizer:ho,BlenderbotSmallTokenizer:jo,SpeechT5Tokenizer:Uo,NougatTokenizer:mo,VitsTokenizer:Vo,Qwen2Tokenizer:Ss,GemmaTokenizer:co,Grok1Tokenizer:di,CohereTokenizer:Br,PreTrainedTokenizer:at})},"./src/utils/audio.js":(e,t,n)=>{n.r(t),n.d(t,{hamming:()=>M,hanning:()=>g,mel_filter_bank:()=>y,read_audio:()=>_,spectrogram:()=>N,window_function:()=>j});var o=n("./src/utils/hub.js"),a=n("./src/utils/maths.js"),l=n("./src/utils/core.js"),f=n("./src/utils/tensor.js");async function _(D,Y){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 de=await(await(0,o.getFile)(D)).arrayBuffer(),Ce=new AudioContext({sampleRate:Y});typeof Y>"u"&&console.warn(`No sampling rate provided, using default of ${Ce.sampleRate}Hz.`);const ee=await Ce.decodeAudioData(de);let ye;if(ee.numberOfChannels===2){const R=Math.sqrt(2),Me=ee.getChannelData(0),Qe=ee.getChannelData(1);ye=new Float32Array(Me.length);for(let ge=0;ge2595*Math.log10(1+D/700),kaldi:D=>1127*Math.log(1+D/700),slaney:(D,Y=1e3,de=15,Ce=27/Math.log(6.4))=>D>=Y?de+Math.log(D/Y)*Ce:3*D/200};function C(D,Y="htk"){const de=w[Y];if(!de)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof D=="number"?de(D):D.map(Ce=>de(Ce))}const k={htk:D=>700*(10**(D/2595)-1),kaldi:D=>700*(Math.exp(D/1127)-1),slaney:(D,Y=1e3,de=15,Ce=Math.log(6.4)/27)=>D>=de?Y*Math.exp(Ce*(D-de)):200*D/3};function z(D,Y="htk"){const de=k[Y];if(!de)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof D=="number"?de(D):D.map(Ce=>de(Ce))}function S(D,Y){const de=Float64Array.from({length:Y.length-1},(R,Me)=>Y[Me+1]-Y[Me]),Ce=Array.from({length:D.length},()=>new Array(Y.length));for(let R=0;Rnew Array(D.length));for(let R=0;RD+Ce*ye)}function y(D,Y,de,Ce,ee,ye=null,R="htk",Me=!1){if(ye!==null&&ye!=="slaney")throw new Error('norm must be one of null or "slaney"');const Qe=C(de,R),ge=C(Ce,R),Q=P(Qe,ge,Y+2);let ae=z(Q,R),Se;if(Me){const me=ee/(D*2);Se=C(Float64Array.from({length:D},(Ke,De)=>De*me),R),ae=Q}else Se=P(0,Math.floor(ee/2),D);const X=S(Se,ae);if(ye!==null&&ye==="slaney")for(let me=0;meee)throw Error(`frame_length (${de}) may not be larger than fft_length (${ee})`);if(Ge!==de)throw new Error(`Length of the window (${Ge}) must equal frame_length (${de})`);if(Ce<=0)throw new Error("hop_length must be greater than zero");if(ye===null&&Q!==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(R){if(Me!=="reflect")throw new Error(`pad_mode="${Me}" not implemented yet.`);const J=Math.floor((ee-1)/2)+1;D=x(D,J,J)}let Te=Math.floor(1+Math.floor((D.length-de)/Ce));Be!==null&&TeTe?ot&&(tt=We):tt=Ye=We);const A=new a.FFT(ee),Ae=new Float64Array(ee),$e=new Float64Array(A.outputBufferSize),se=new Float32Array(je*tt);for(let J=0;J=1;--le)Ae[le]-=ge*Ae[le-1];Ae[0]*=1-ge}for(let le=0;leMath.pow(Me,.85));break;default:throw new Error(`Unknown window type ${Y}.`)}if(de&&(R=R.subarray(0,D)),Ce===null)return R;if(D>Ce)throw new Error(`Length of the window (${D}) may not be larger than frame_length (${Ce})`);return R}},"./src/utils/constants.js":(e,t,n)=>{n.r(t),n.d(t,{GITHUB_ISSUE_URL:()=>o});const o="https://github.com/xenova/transformers.js/issues/new/choose"},"./src/utils/core.js":(e,t,n)=>{n.r(t),n.d(t,{calculateDimensions:()=>h,calculateReflectOffset:()=>C,dispatchCallback:()=>o,escapeRegExp:()=>l,isIntegralNumber:()=>_,isTypedArray:()=>f,mergeArrays:()=>M,pick:()=>k,pop:()=>g,product:()=>w,reverseDictionary:()=>a});function o(z,S){z&&z(S)}function a(z){return Object.fromEntries(Object.entries(z).map(([S,P])=>[P,S]))}function l(z){return z.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function f(z){var S,P,y;return((y=(P=(S=z==null?void 0:z.prototype)==null?void 0:S.__proto__)==null?void 0:P.constructor)==null?void 0:y.name)==="TypedArray"}function _(z){return Number.isInteger(z)||typeof z=="bigint"}function h(z){const S=[];let P=z;for(;Array.isArray(P);)S.push(P.length),P=P[0];return S}function g(z,S,P=void 0){const y=z[S];if(y!==void 0)return delete z[S],y;if(P===void 0)throw Error(`Key ${S} does not exist in object.`);return P}function M(...z){return Array.prototype.concat.apply([],z)}function w(...z){return z.reduce((S,P)=>S.flatMap(y=>P.map(x=>[y,x])))}function C(z,S){return Math.abs((z+S)%(2*S)-S)}function k(z,S){return Object.assign({},...S.map(P=>{if(z[P]!==void 0)return{[P]:z[P]}}))}},"./src/utils/data-structures.js":(e,t,n)=>{n.r(t),n.d(t,{CharTrie:()=>a,PriorityQueue:()=>o,TokenLattice:()=>f});class o{constructor(g=(w,C)=>w>C,M=1/0){this._heap=[],this._comparator=g,this._maxSize=M}get size(){return this._heap.length}isEmpty(){return this.size===0}peek(){return this._heap[0]}push(...g){return this.extend(g)}extend(g){for(const M of g)if(this.size0&&this._swap(0,M),this._heap.pop(),this._siftDown(),g}replace(g){const M=this.peek();return this._heap[0]=g,this._siftDown(),M}_parent(g){return(g+1>>>1)-1}_left(g){return(g<<1)+1}_right(g){return g+1<<1}_greater(g,M){return this._comparator(this._heap[g],this._heap[M])}_swap(g,M){const w=this._heap[g];this._heap[g]=this._heap[M],this._heap[M]=w}_siftUp(){this._siftUpFrom(this.size-1)}_siftUpFrom(g){for(;g>0&&this._greater(g,this._parent(g));)this._swap(g,this._parent(g)),g=this._parent(g)}_siftDown(){let g=0;for(;this._left(g)[]),this.endNodes=Array.from({length:this.len+1},()=>[]);const C=new _(this.bosTokenId,0,0,0,0),k=new _(this.eosTokenId,1,this.len,0,0);this.nodes.push(C.clone()),this.nodes.push(k.clone()),this.beginNodes[this.len].push(k),this.endNodes[0].push(C)}insert(g,M,w,C){const k=this.nodes.length,z=new _(C,k,g,M,w);this.beginNodes[g].push(z),this.endNodes[g+M].push(z),this.nodes.push(z)}viterbi(){const g=this.len;let M=0;for(;M<=g;){if(this.beginNodes[M].length==0)return[];for(let S of this.beginNodes[M]){S.prev=null;let P=0,y=null;for(let x of this.endNodes[M]){const I=x.backtraceScore+S.score;(y===null||I>P)&&(y=x.clone(),P=I)}if(y!==null)S.prev=y,S.backtraceScore=P;else return[]}++M}const w=[],k=this.beginNodes[g][0].prev;if(k===null)return[];let z=k.clone();for(;z.prev!==null;)w.push(z.clone()),z=z.clone().prev.clone();return w.reverse(),w}piece(g){return this.sentence.slice(g.pos,g.pos+g.length)}tokens(){return this.viterbi().map(M=>this.piece(M))}tokenIds(){return this.viterbi().map(M=>M.tokenId)}}class _{constructor(g,M,w,C,k){this.tokenId=g,this.nodeId=M,this.pos=w,this.length=C,this.score=k,this.prev=null,this.backtraceScore=0}clone(){const g=new _(this.tokenId,this.nodeId,this.pos,this.length,this.score);return g.prev=this.prev,g.backtraceScore=this.backtraceScore,g}}},"./src/utils/devices.js":(e,t,n)=>{n.r(t),n.d(t,{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,t,n)=>{n.r(t),n.d(t,{DATA_TYPES:()=>f,DEFAULT_DEVICE_DTYPE_MAPPING:()=>_,DEFAULT_DTYPE_SUFFIX_MAPPING:()=>h,isWebGpuFp16Supported:()=>l});var o=n("./src/env.js"),a=n("./src/utils/devices.js");const l=function(){let g;return async function(){if(g===void 0)if(!o.apis.IS_WEBGPU_AVAILABLE)g=!1;else try{g=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{g=!1}return g}}(),f=Object.freeze({fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16"}),_=Object.freeze({[a.DEVICE_TYPES.wasm]:f.q8}),h=Object.freeze({[f.fp32]:"",[f.fp16]:"_fp16",[f.int8]:"_int8",[f.uint8]:"_uint8",[f.q8]:"_quantized",[f.q4]:"_q4",[f.q4f16]:"_q4f16",[f.bnb4]:"_bnb4"})},"./src/utils/generic.js":(e,t,n)=>{n.r(t),n.d(t,{Callable:()=>o});const o=class{constructor(){let a=function(...l){return a._call(...l)};return Object.setPrototypeOf(a,new.target.prototype)}_call(...a){throw Error("Must implement _call method in subclass")}}},"./src/utils/hub.js":(e,t,n)=>{n.r(t),n.d(t,{getFile:()=>M,getModelFile:()=>S,getModelJSON:()=>P});var o=n("?7a2c"),a=n("?a42a"),l=n("./src/env.js"),f=n("./src/utils/core.js");const _={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 h{constructor(U){if(this.filePath=U,this.headers=new Headers,this.exists=o.existsSync(U),this.exists){this.status=200,this.statusText="OK";let O=o.statSync(U);this.headers.set("content-length",O.size.toString()),this.updateContentType();let N=this;this.body=new ReadableStream({start(j){N.arrayBuffer().then(D=>{j.enqueue(new Uint8Array(D)),j.close()})}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){const U=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",_[U]??"application/octet-stream")}clone(){let U=new h(this.filePath);return U.exists=this.exists,U.status=this.status,U.statusText=this.statusText,U.headers=new Headers(this.headers),U}async arrayBuffer(){return(await o.promises.readFile(this.filePath)).buffer}async blob(){const U=await o.promises.readFile(this.filePath);return new Blob([U],{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 g(I,U=null,O=null){let N;try{N=new URL(I)}catch{return!1}return!(U&&!U.includes(N.protocol)||O&&!O.includes(N.hostname))}async function M(I){var U;if(l.env.useFS&&!g(I,["http:","https:","blob:"]))return new h(I);if(typeof process<"u"&&((U=process==null?void 0:process.release)==null?void 0:U.name)==="node"){const O=!!(Mo!=null&&Mo.TESTING_REMOTELY),N=l.env.version,j=new Headers;if(j.set("User-Agent",`transformers.js/${N}; is_ci/${O};`),g(I,["http:","https:"],["huggingface.co","hf.co"])){const Y=(Mo==null?void 0:Mo.HF_TOKEN)??(Mo==null?void 0:Mo.HF_ACCESS_TOKEN);Y&&j.set("Authorization",`Bearer ${Y}`)}return fetch(I,{headers:j})}else return fetch(I)}const w={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 C(I,U,O){if(!O)return null;const N=w[I]??`Error (${I}) occurred while trying to load file`;throw Error(`${N}: "${U}".`)}class k{constructor(U){this.path=U}async match(U){let O=a.join(this.path,U),N=new h(O);if(N.exists)return N}async put(U,O){const N=Buffer.from(await O.arrayBuffer());let j=a.join(this.path,U);try{await o.promises.mkdir(a.dirname(j),{recursive:!0}),await o.promises.writeFile(j,N)}catch(D){console.warn("An error occurred while writing the file to cache:",D)}}}async function z(I,...U){for(let O of U)try{let N=await I.match(O);if(N)return N}catch{continue}}async function S(I,U,O=!0,N={}){if(!l.env.allowLocalModels){if(N.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(!l.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,f.dispatchCallback)(N.progress_callback,{status:"initiate",name:I,file:U});let j;if(!j&&l.env.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{j=await caches.open("transformers-cache")}catch(Se){console.warn("An error occurred while opening the browser cache:",Se)}}if(!j&&l.env.useFSCache&&(j=new k(N.cache_dir??l.env.cacheDir)),!j&&l.env.useCustomCache){if(!l.env.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!l.env.customCache.match||!l.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");j=l.env.customCache}const D=N.revision??"main";let Y=x(I,U),de=x(l.env.localModelPath,Y),Ce=x(l.env.remoteHost,l.env.remotePathTemplate.replaceAll("{model}",I).replaceAll("{revision}",encodeURIComponent(D)),U),ee=D==="main"?Y:x(I,D,U),ye,R=j instanceof k?ee:Ce,Me=!1,Qe;j&&(Qe=await z(j,de,R));const ge=Qe!==void 0;if(Qe===void 0){if(l.env.allowLocalModels)if(g(Y,["http:","https:"])){if(N.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${Y}.`);if(!l.env.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${Y}.`)}else try{Qe=await M(de),ye=de}catch(X){console.warn(`Unable to load from local path "${de}": "${X}"`)}if(Qe===void 0||Qe.status===404){if(N.local_files_only||!l.env.allowRemoteModels){if(O)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${de}".`);return null}if(Qe=await M(Ce),Qe.status!==200)return C(Qe.status,Ce,O);ye=R}Me=j&&typeof Response<"u"&&Qe instanceof Response&&Qe.status===200}(0,f.dispatchCallback)(N.progress_callback,{status:"download",name:I,file:U});const Q={status:"progress",name:I,file:U};let ae;return N.progress_callback?ge&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent)?(ae=new Uint8Array(await Qe.arrayBuffer()),(0,f.dispatchCallback)(N.progress_callback,{...Q,progress:100,loaded:ae.length,total:ae.length})):ae=await y(Qe,Se=>{(0,f.dispatchCallback)(N.progress_callback,{...Q,...Se})}):ae=new Uint8Array(await Qe.arrayBuffer()),Me&&ye&&await j.match(ye)===void 0&&await j.put(ye,new Response(ae,{headers:Qe.headers})).catch(Se=>{console.warn(`Unable to add response to browser cache: ${Se}.`)}),(0,f.dispatchCallback)(N.progress_callback,{status:"done",name:I,file:U}),ae}async function P(I,U,O=!0,N={}){let j=await S(I,U,O,N);if(j===null)return{};let Y=new TextDecoder("utf-8").decode(j);return JSON.parse(Y)}async function y(I,U){const O=I.headers.get("Content-Length");O===null&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let N=parseInt(O??"0"),j=new Uint8Array(N),D=0;const Y=I.body.getReader();async function de(){const{done:Ce,value:ee}=await Y.read();if(Ce)return;let ye=D+ee.length;if(ye>N){N=ye;let Me=new Uint8Array(N);Me.set(j),j=Me}j.set(ee,D),D=ye;const R=D/N*100;return U({progress:R,loaded:D,total:N}),de()}return await de(),j}function x(...I){return I=I.map((U,O)=>(O&&(U=U.replace(new RegExp("^/"),"")),O!==I.length-1&&(U=U.replace(new RegExp("/$"),"")),U)),I.join("/")}},"./src/utils/image.js":(e,t,n)=>{n.r(t),n.d(t,{RawImage:()=>z});var o=n("./src/utils/hub.js"),a=n("./src/env.js"),l=n("./src/utils/tensor.js"),f=n("?2b25");const _=typeof self<"u",h=_&&self.constructor.name==="DedicatedWorkerGlobalScope";let g,M,w;if(_)g=(S,P)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(S,P)},w=self.createImageBitmap,M=self.ImageData;else if(f)w=async S=>{const y=(await S.metadata()).channels,{data:x,info:I}=await S.rotate().raw().toBuffer({resolveWithObject:!0}),U=new z(new Uint8ClampedArray(x),I.width,I.height,I.channels);return y!==void 0&&y!==I.channels&&U.convert(y),U};else throw new Error("Unable to load image processing library.");const C={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},k=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]);class z{constructor(P,y,x,I){this.data=P,this.width=y,this.height=x,this.channels=I}get size(){return[this.width,this.height]}static async read(P){if(P instanceof z)return P;if(typeof P=="string"||P instanceof URL)return await this.fromURL(P);throw new Error(`Unsupported input type: ${typeof P}`)}static fromCanvas(P){if(!_)throw new Error("fromCanvas() is only supported in browser environments.");const x=P.getContext("2d").getImageData(0,0,P.width,P.height).data;return new z(x,P.width,P.height,4)}static async fromURL(P){const y=await(0,o.getFile)(P);if(y.status!==200)throw new Error(`Unable to read image from "${P}" (${y.status} ${y.statusText})`);const x=await y.blob();return this.fromBlob(x)}static async fromBlob(P){if(_){const y=await w(P),x=g(y.width,y.height).getContext("2d");return x.drawImage(y,0,0),new this(x.getImageData(0,0,y.width,y.height).data,y.width,y.height,4)}else{const y=f(await P.arrayBuffer());return await w(y)}}static fromTensor(P,y="CHW"){if(P.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${P.dims.length} dimensions.`);if(y==="CHW")P=P.transpose(1,2,0);else if(y!=="HWC")throw new Error(`Unsupported channel format: ${y}`);if(!(P.data instanceof Uint8ClampedArray||P.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${P.type}`);switch(P.dims[2]){case 1:case 2:case 3:case 4:return new z(P.data,P.dims[1],P.dims[0],P.dims[2]);default:throw new Error(`Unsupported number of channels: ${P.dims[2]}`)}}grayscale(){if(this.channels===1)return this;const P=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let y=0,x=0;y=0?j=x:Y=-x,I>=0?D=I:de=-I,N.drawImage(O,j,D,P,y,Y,de,P,y),new z(N.getImageData(0,0,P,y).data,P,y,4).convert(U)}else{let U=this.toSharp();if(x>=0&&I>=0)U=U.extract({left:Math.floor(x),top:Math.floor(I),width:P,height:y});else if(x<=0&&I<=0){const O=Math.floor(-I),N=Math.floor(-x);U=U.extend({top:O,left:N,right:P-this.width-N,bottom:y-this.height-O})}else{let O=[0,0],N=0;I<0?(O[0]=Math.floor(-I),O[1]=y-this.height-O[0]):N=Math.floor(I);let j=[0,0],D=0;x<0?(j[0]=Math.floor(-x),j[1]=P-this.width-j[0]):D=Math.floor(x),U=U.extend({top:O[0],bottom:O[1],left:j[0],right:j[1]}).extract({left:D,top:N,width:P,height:y})}return await w(U)}}async toBlob(P="image/png",y=1){if(!_)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:P,quality:y})}toTensor(P="CHW"){let y=new l.Tensor("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(P!=="HWC")if(P==="CHW")y=y.permute(2,0,1);else throw new Error(`Unsupported channel format: ${P}`);return y}toCanvas(){if(!_)throw new Error("toCanvas() is only supported in browser environments.");const P=this.clone().rgba(),y=g(P.width,P.height),x=new M(P.data,P.width,P.height);return y.getContext("2d").putImageData(x,0,0),y}_update(P,y,x,I=null){return this.data=P,this.width=y,this.height=x,I!==null&&(this.channels=I),this}clone(){return new z(this.data.slice(),this.width,this.height,this.channels)}convert(P){if(this.channels===P)return this;switch(P){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(P){if(_){if(h)throw new Error("Unable to save an image from a Web Worker.");const y=P.split(".").pop().toLowerCase(),x=k.get(y)??"image/png",I=await this.toBlob(x),U=URL.createObjectURL(I),O=document.createElement("a");O.href=U,O.download=P,O.click(),O.remove()}else{if(a.env.useFS)return await this.toSharp().toFile(P);throw new Error("Unable to save the image because filesystem is disabled in this environment.")}}toSharp(){if(_)throw new Error("toSharp() is only supported in server-side environments.");return f(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}}},"./src/utils/maths.js":(e,t,n)=>{n.r(t),n.d(t,{FFT:()=>S,bankers_round:()=>x,cos_sim:()=>h,dot:()=>_,dynamic_time_warping:()=>I,interpolate_data:()=>o,log_softmax:()=>f,magnitude:()=>g,max:()=>w,medianFilter:()=>P,min:()=>M,permute_data:()=>a,round:()=>y,softmax:()=>l});function o(U,[O,N,j],[D,Y],de="bilinear",Ce=!1){const ee=Y/j,ye=D/N,R=new U.constructor(D*Y*O),Me=N*j,Qe=D*Y;for(let ge=0;ge=0;--Ce)D[Ce]=ee,j[Ce]=O[N[Ce]],ee*=j[Ce];const Y=N.map((Ce,ee)=>D[N.indexOf(ee)]),de=new U.constructor(U.length);for(let Ce=0;Ce=0;--ye)ee+=R%O[ye]*Y[ye],R=Math.floor(R/O[ye]);de[ee]=U[Ce]}return[de,j]}function l(U){const O=w(U)[0],N=U.map(Y=>Math.exp(Y-O)),j=N.reduce((Y,de)=>Y+de,0);return N.map(Y=>Y/j)}function f(U){return l(U).map(j=>Math.log(j))}function _(U,O){let N=0;for(let j=0;jO+N*N,0))}function M(U){if(U.length===0)throw Error("Array must not be empty");let O=U[0],N=0;for(let j=1;jO&&(O=U[j],N=j);return[Number(O),N]}function C(U){return U>0&&(U&U-1)===0}class k{constructor(O){if(this.size=O|0,this.size<=1||!C(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=O<<1,this.table=new Float64Array(this.size*2);for(let j=0;jj;j<<=1)++N;this._width=N%2===0?N-1:N,this._bitrev=new Int32Array(1<>>D&3)<>>1);for(let D=0;D>>1]=O[D];return j}toComplexArray(O,N){const j=N||this.createComplexArray();for(let D=0;D>>1],j[D+1]=0;return j}transform(O,N){if(O===N)throw new Error("Input and output buffers must be different");this._transform4(O,N,1)}realTransform(O,N){if(O===N)throw new Error("Input and output buffers must be different");this._realTransform4(O,N,1)}inverseTransform(O,N){if(O===N)throw new Error("Input and output buffers must be different");this._transform4(O,N,-1);for(let j=0;j>=2;de>=2;de>>=2){Ce=D/de<<1;const Qe=Ce>>>2;for(ee=0;ee>>1,de>>>1)}else for(ee=0,ye=0;ee>>1,de>>>1,j)}const Me=this.table;for(de>>=2;de>=2;de>>=2){Ce=D/de<<1;const ge=Ce>>>1,Q=ge>>>1,ae=Q>>>1;for(ee=0;ee>>1;for(let ge=2;ge>1;++R){const Me=(R+1-O)**2/2,Qe=Math.sqrt(ee**2+ye**2)**Me,ge=Me*Math.atan2(ye,ee),Q=2*R;Y[Q]=Qe*Math.cos(ge),Y[Q+1]=Qe*Math.sin(ge),de[Q]=Y[Q],de[Q+1]=-Y[Q+1]}this._slicedChirpBuffer=Y.subarray(N,j),this._f=new k(D>>1),this._f.transform(this._chirpBuffer,de)}_transform(O,N,j){const D=this._buffer1,Y=this._buffer2,de=this._outBuffer1,Ce=this._outBuffer2,ee=this._chirpBuffer,ye=this._slicedChirpBuffer,R=this._a;if(j)for(let Me=0;Me>1,Q=N[ge];D[Me]=Q*ye[Me],D[Qe]=Q*ye[Qe]}else for(let Me=0;Me=U.length&&(ee=2*(U.length-1)-ee),j[de++]=U[ee]}j.sort(),N[Y]=j[D]}return N}function y(U,O){const N=Math.pow(10,O);return Math.round(U*N)/N}function x(U){const O=Math.round(U);return Math.abs(U)%1===.5?O%2===0?O:O-1:O}function I(U){const O=U.length,N=U[0].length,j=[O+1,N+1],D=Array.from({length:j[0]},()=>Array(j[1]).fill(1/0));D[0][0]=0;const Y=Array.from({length:j[0]},()=>Array(j[1]).fill(-1));for(let R=1;R0||Ce>0;)switch(ee.push(de-1),ye.push(Ce-1),Y[de][Ce]){case 0:--de,--Ce;break;case 1:--de;break;case 2:--Ce;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${de}, ${Ce}]. Please file a bug report.`)}return ee.reverse(),ye.reverse(),[ee,ye]}},"./src/utils/tensor.js":(e,t,n)=>{n.r(t),n.d(t,{Tensor:()=>_,cat:()=>U,full:()=>de,full_like:()=>Ce,interpolate:()=>M,interpolate_4d:()=>w,layer_norm:()=>P,matmul:()=>C,mean:()=>j,mean_pooling:()=>S,ones:()=>ee,ones_like:()=>ye,permute:()=>g,quantize_embeddings:()=>Qe,rfft:()=>k,stack:()=>O,std_mean:()=>N,topk:()=>z,zeros:()=>R,zeros_like:()=>Me});var o=n("./src/utils/maths.js"),a=n("./src/backends/onnx.js"),l=n("./src/ops/registry.js");const f=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 _{constructor(...Q){qe(this,"ort_tensor");return(0,a.isONNXTensor)(Q[0])?this.ort_tensor=Q[0]:this.ort_tensor=new a.Tensor(Q[0],Q[1],Q[2]),new Proxy(this,{get:(ae,Se)=>{if(typeof Se=="string"){let X=Number(Se);if(Number.isInteger(X))return ae._getitem(X)}return ae[Se]},set:(ae,Se,X)=>ae[Se]=X})}get dims(){return this.ort_tensor.dims}set dims(Q){this.ort_tensor.dims=Q}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[Q,...ae]=this.dims;if(ae.length>0){const Se=ae.reduce((X,me)=>X*me);for(let X=0;X0){const X=Se.reduce((me,Ke)=>me*Ke);return this._subarray(Q,X,Se)}else return new _(this.type,[this.data[Q]],Se)}indexOf(Q){const ae=this.data;for(let Se=0;SeGe)throw new Error(`Invalid slice: ${ot}`);const Te=[Math.max(dt,0),Math.min(Ge,this.dims[We])];Se.push(Te),ae.push(Te[1]-Te[0])}else throw new Error(`Invalid slice: ${ot}`)}const X=Se.map(([We,ot])=>ot-We),me=X.reduce((We,ot)=>We*ot),Ke=this.data,De=new Ke.constructor(me),Be=this.stride();for(let We=0;We=0;--dt){const Te=X[dt];ot+=(Ge%Te+Se[dt][0])*Be[dt],Ge=Math.floor(Ge/Te)}De[We]=Ke[ot]}return new _(this.type,De,ae)}permute(...Q){return g(this,Q)}transpose(...Q){return this.permute(...Q)}sum(Q=null,ae=!1){return this.norm(1,Q,ae)}norm(Q="fro",ae=null,Se=!1){if(Q==="fro")Q=2;else if(typeof Q=="string")throw Error(`Unsupported norm: ${Q}`);const X=this.data;if(ae===null){let De=X.reduce((Be,We)=>Be+We**Q,0)**(1/Q);return new _(this.type,[De],[])}ae=I(ae,this.dims.length);const me=this.dims.slice();me[ae]=1;const Ke=new X.constructor(X.length/this.dims[ae]);for(let De=0;De=0;--We){const Ge=this.dims[We];if(We!==ae){const Te=ot%Ge;Be+=Te*dt,dt*=me[We]}ot=Math.floor(ot/Ge)}Ke[Be]+=X[De]**Q}if(Q!==1)for(let De=0;De=0;--Be){const dt=this.dims[Be];if(Be!==ae){const Ge=We%dt;De+=Ge*ot,ot*=this.dims[Be]}We=Math.floor(We/dt)}X[Ke]/=me[De]}return this}normalize(Q=2,ae=1){return this.clone().normalize_(Q,ae)}stride(){return D(this.dims)}squeeze(Q=null){return new _(this.type,this.data,y(this.dims,Q))}squeeze_(Q=null){return this.dims=y(this.dims,Q),this}unsqueeze(Q=null){return new _(this.type,this.data,x(this.dims,Q))}unsqueeze_(Q=null){return this.dims=x(this.dims,Q),this}flatten_(Q=0,ae=-1){ae=(ae+this.dims.length)%this.dims.length;let Se=this.dims.slice(0,Q),X=this.dims.slice(Q,ae+1),me=this.dims.slice(ae+1);return this.dims=[...Se,X.reduce((Ke,De)=>Ke*De,1),...me],this}flatten(Q=0,ae=-1){return this.clone().flatten_(Q,ae)}view(...Q){let ae=-1;for(let X=0;XDe!==ae?me*Ke:me,1);Q[ae]=Se.length/X}return new _(this.type,Se,Q)}neg_(){const Q=this.data;for(let ae=0;aeme*Ke);if(ae!==Se)throw Error(`cannot reshape array of size ${ae} into shape (${Q})`);let X=ge;for(let me=Q.length-1;me>=0;me--)X=X.reduce((Ke,De)=>{let Be=Ke[Ke.length-1];return Be.lengthae!==1):typeof Q=="number"?ge[Q]===1&&ge.splice(Q,1):Array.isArray(Q)&&(ge=ge.filter((ae,Se)=>ae!==1||!Q.includes(Se))),ge}function x(ge,Q){return Q=I(Q,ge.length+1),ge=ge.slice(),ge.splice(Q,0,1),ge}function I(ge,Q,ae=null,Se=!0){if(Se&&(ge<-Q||ge>=Q))throw new Error(`IndexError: index ${ge} is out of bounds for dimension${ae===null?"":" "+ae} with size ${Q}`);return ge<0&&(ge=(ge%Q+Q)%Q),ge}function U(ge,Q=0){Q=I(Q,ge[0].dims.length);const ae=ge[0].dims.slice();ae[Q]=ge.reduce((Ke,De)=>Ke+De.dims[Q],0);const Se=ae.reduce((Ke,De)=>Ke*De,1),X=new ge[0].data.constructor(Se),me=ge[0].type;if(Q===0){let Ke=0;for(const De of ge){const Be=De.data;X.set(Be,Ke),Ke+=Be.length}}else{let Ke=0;for(let De=0;De=0;--Ge){const Ye=We[Ge];let tt=Te%Ye;Ge===Q&&(tt+=Ke),dt+=tt*je,je*=ae[Ge],Te=Math.floor(Te/Ye)}X[dt]=Be[ot]}Ke+=We[Q]}}return new _(me,X,ae)}function O(ge,Q=0){return U(ge.map(ae=>ae.unsqueeze(Q)),Q)}function N(ge,Q=null,ae=1,Se=!1){const X=ge.data,me=ge.dims;if(Q===null){const Ge=X.reduce((tt,A)=>tt+A,0)/X.length,Te=Math.sqrt(X.reduce((tt,A)=>tt+(A-Ge)**2,0)/(X.length-ae)),je=new _(ge.type,[Ge],[]);return[new _(ge.type,[Te],[]),je]}Q=I(Q,me.length);const Ke=j(ge,Q,Se),De=Ke.data,Be=me.slice();Be[Q]=1;const We=new X.constructor(X.length/me[Q]);for(let dt=0;dt=0;--Te){const tt=me[Te];if(Te!==Q){const A=je%tt;Ge+=A*Ye,Ye*=Be[Te]}je=Math.floor(je/tt)}We[Ge]+=(X[dt]-De[Ge])**2}for(let dt=0;dtBe+We,0);return new _(ge.type,[De/Se.length],[])}const X=ge.dims;Q=I(Q,X.length);const me=X.slice();me[Q]=1;const Ke=new Se.constructor(Se.length/X[Q]);for(let De=0;De=0;--We){const Ge=X[We];if(We!==Q){const Te=ot%Ge;Be+=Te*dt,dt*=me[We]}ot=Math.floor(ot/Ge)}Ke[Be]+=Se[De]}if(X[Q]!==1)for(let De=0;De=0;--ae)Q[ae]=Se,Se*=ge[ae];return Q}function Y(ge,Q,ae,Se){const X=ge.reduce((me,Ke)=>me*Ke,1);return new _(ae,new Se(X).fill(Q),ge)}function de(ge,Q){let ae,Se;if(typeof Q=="number")ae="float32",Se=Float32Array;else if(typeof Q=="bigint")ae="int64",Se=BigInt64Array;else throw new Error(`Unsupported data type: ${typeof Q}`);return Y(ge,Q,ae,Se)}function Ce(ge,Q){return de(ge.dims,Q)}function ee(ge){return Y(ge,1n,"int64",BigInt64Array)}function ye(ge){return ee(ge.dims)}function R(ge){return Y(ge,0n,"int64",BigInt64Array)}function Me(ge){return R(ge.dims)}function Qe(ge,Q){if(ge.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(ge.dims.at(-1)%8!==0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(Q))throw new Error("The precision must be either 'binary' or 'ubinary'");const ae=Q==="binary",Se=ae?"int8":"uint8",X=ae?Int8Array:Uint8Array,me=ge.data,Ke=new X(me.length/8);for(let De=0;De0?1:0,We=Math.floor(De/8),ot=De%8;Ke[We]|=Be<<7-ot,ae&&ot===0&&(Ke[We]-=128)}return new _(Se,Ke,[ge.dims[0],ge.dims[1]/8])}}},w1={};function Yr(e){var t=w1[e];if(t!==void 0)return t.exports;var n=w1[e]={exports:{}};return sE[e](n,n.exports,Yr),n.exports}(()=>{var e=Object.getPrototypeOf?n=>Object.getPrototypeOf(n):n=>n.__proto__,t;Yr.t=function(n,o){if(o&1&&(n=this(n)),o&8||typeof n=="object"&&n&&(o&4&&n.__esModule||o&16&&typeof n.then=="function"))return n;var a=Object.create(null);Yr.r(a);var l={};t=t||[null,e({}),e([]),e(e)];for(var f=o&2&&n;typeof f=="object"&&!~t.indexOf(f);f=e(f))Object.getOwnPropertyNames(f).forEach(_=>l[_]=()=>n[_]);return l.default=()=>n,Yr.d(a,l),a}})();Yr.d=(e,t)=>{for(var n in t)Yr.o(t,n)&&!Yr.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})};Yr.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);Yr.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(/\/[^\/]+$/,"/"),Yr.p=e})();Yr.b=void 0;var $={};(()=>{/*!*****************************!*\ + !*** ./src/transformers.js ***! + \*****************************/Yr.r($),Yr.d($,{ASTFeatureExtractor:()=>a.ASTFeatureExtractor,ASTForAudioClassification:()=>n.ASTForAudioClassification,ASTModel:()=>n.ASTModel,ASTPreTrainedModel:()=>n.ASTPreTrainedModel,AlbertForMaskedLM:()=>n.AlbertForMaskedLM,AlbertForQuestionAnswering:()=>n.AlbertForQuestionAnswering,AlbertForSequenceClassification:()=>n.AlbertForSequenceClassification,AlbertModel:()=>n.AlbertModel,AlbertPreTrainedModel:()=>n.AlbertPreTrainedModel,AlbertTokenizer:()=>o.AlbertTokenizer,AudioClassificationPipeline:()=>t.AudioClassificationPipeline,AutoConfig:()=>l.AutoConfig,AutoModel:()=>n.AutoModel,AutoModelForAudioClassification:()=>n.AutoModelForAudioClassification,AutoModelForAudioFrameClassification:()=>n.AutoModelForAudioFrameClassification,AutoModelForCTC:()=>n.AutoModelForCTC,AutoModelForCausalLM:()=>n.AutoModelForCausalLM,AutoModelForDepthEstimation:()=>n.AutoModelForDepthEstimation,AutoModelForDocumentQuestionAnswering:()=>n.AutoModelForDocumentQuestionAnswering,AutoModelForImageClassification:()=>n.AutoModelForImageClassification,AutoModelForImageFeatureExtraction:()=>n.AutoModelForImageFeatureExtraction,AutoModelForImageMatting:()=>n.AutoModelForImageMatting,AutoModelForImageSegmentation:()=>n.AutoModelForImageSegmentation,AutoModelForImageToImage:()=>n.AutoModelForImageToImage,AutoModelForMaskGeneration:()=>n.AutoModelForMaskGeneration,AutoModelForMaskedLM:()=>n.AutoModelForMaskedLM,AutoModelForObjectDetection:()=>n.AutoModelForObjectDetection,AutoModelForQuestionAnswering:()=>n.AutoModelForQuestionAnswering,AutoModelForSemanticSegmentation:()=>n.AutoModelForSemanticSegmentation,AutoModelForSeq2SeqLM:()=>n.AutoModelForSeq2SeqLM,AutoModelForSequenceClassification:()=>n.AutoModelForSequenceClassification,AutoModelForSpeechSeq2Seq:()=>n.AutoModelForSpeechSeq2Seq,AutoModelForTextToSpectrogram:()=>n.AutoModelForTextToSpectrogram,AutoModelForTextToWaveform:()=>n.AutoModelForTextToWaveform,AutoModelForTokenClassification:()=>n.AutoModelForTokenClassification,AutoModelForVision2Seq:()=>n.AutoModelForVision2Seq,AutoModelForXVector:()=>n.AutoModelForXVector,AutoModelForZeroShotObjectDetection:()=>n.AutoModelForZeroShotObjectDetection,AutoProcessor:()=>a.AutoProcessor,AutoTokenizer:()=>o.AutoTokenizer,AutomaticSpeechRecognitionPipeline:()=>t.AutomaticSpeechRecognitionPipeline,BartForConditionalGeneration:()=>n.BartForConditionalGeneration,BartForSequenceClassification:()=>n.BartForSequenceClassification,BartModel:()=>n.BartModel,BartPretrainedModel:()=>n.BartPretrainedModel,BartTokenizer:()=>o.BartTokenizer,BaseModelOutput:()=>n.BaseModelOutput,BaseStreamer:()=>M.BaseStreamer,BeitFeatureExtractor:()=>a.BeitFeatureExtractor,BeitForImageClassification:()=>n.BeitForImageClassification,BeitModel:()=>n.BeitModel,BeitPreTrainedModel:()=>n.BeitPreTrainedModel,BertForMaskedLM:()=>n.BertForMaskedLM,BertForQuestionAnswering:()=>n.BertForQuestionAnswering,BertForSequenceClassification:()=>n.BertForSequenceClassification,BertForTokenClassification:()=>n.BertForTokenClassification,BertModel:()=>n.BertModel,BertPreTrainedModel:()=>n.BertPreTrainedModel,BertTokenizer:()=>o.BertTokenizer,BitImageProcessor:()=>a.BitImageProcessor,BlenderbotForConditionalGeneration:()=>n.BlenderbotForConditionalGeneration,BlenderbotModel:()=>n.BlenderbotModel,BlenderbotPreTrainedModel:()=>n.BlenderbotPreTrainedModel,BlenderbotSmallForConditionalGeneration:()=>n.BlenderbotSmallForConditionalGeneration,BlenderbotSmallModel:()=>n.BlenderbotSmallModel,BlenderbotSmallPreTrainedModel:()=>n.BlenderbotSmallPreTrainedModel,BlenderbotSmallTokenizer:()=>o.BlenderbotSmallTokenizer,BlenderbotTokenizer:()=>o.BlenderbotTokenizer,BloomForCausalLM:()=>n.BloomForCausalLM,BloomModel:()=>n.BloomModel,BloomPreTrainedModel:()=>n.BloomPreTrainedModel,BloomTokenizer:()=>o.BloomTokenizer,CLIPFeatureExtractor:()=>a.CLIPFeatureExtractor,CLIPImageProcessor:()=>a.CLIPImageProcessor,CLIPModel:()=>n.CLIPModel,CLIPPreTrainedModel:()=>n.CLIPPreTrainedModel,CLIPSegForImageSegmentation:()=>n.CLIPSegForImageSegmentation,CLIPSegModel:()=>n.CLIPSegModel,CLIPSegPreTrainedModel:()=>n.CLIPSegPreTrainedModel,CLIPTextModelWithProjection:()=>n.CLIPTextModelWithProjection,CLIPTokenizer:()=>o.CLIPTokenizer,CLIPVisionModelWithProjection:()=>n.CLIPVisionModelWithProjection,CamembertForMaskedLM:()=>n.CamembertForMaskedLM,CamembertForQuestionAnswering:()=>n.CamembertForQuestionAnswering,CamembertForSequenceClassification:()=>n.CamembertForSequenceClassification,CamembertForTokenClassification:()=>n.CamembertForTokenClassification,CamembertModel:()=>n.CamembertModel,CamembertPreTrainedModel:()=>n.CamembertPreTrainedModel,CamembertTokenizer:()=>o.CamembertTokenizer,CausalLMOutput:()=>n.CausalLMOutput,CausalLMOutputWithPast:()=>n.CausalLMOutputWithPast,ChineseCLIPFeatureExtractor:()=>a.ChineseCLIPFeatureExtractor,ChineseCLIPModel:()=>n.ChineseCLIPModel,ChineseCLIPPreTrainedModel:()=>n.ChineseCLIPPreTrainedModel,ClapAudioModelWithProjection:()=>n.ClapAudioModelWithProjection,ClapFeatureExtractor:()=>a.ClapFeatureExtractor,ClapModel:()=>n.ClapModel,ClapPreTrainedModel:()=>n.ClapPreTrainedModel,ClapTextModelWithProjection:()=>n.ClapTextModelWithProjection,CodeGenForCausalLM:()=>n.CodeGenForCausalLM,CodeGenModel:()=>n.CodeGenModel,CodeGenPreTrainedModel:()=>n.CodeGenPreTrainedModel,CodeGenTokenizer:()=>o.CodeGenTokenizer,CodeLlamaTokenizer:()=>o.CodeLlamaTokenizer,CohereForCausalLM:()=>n.CohereForCausalLM,CohereModel:()=>n.CohereModel,CoherePreTrainedModel:()=>n.CoherePreTrainedModel,CohereTokenizer:()=>o.CohereTokenizer,ConvBertForMaskedLM:()=>n.ConvBertForMaskedLM,ConvBertForQuestionAnswering:()=>n.ConvBertForQuestionAnswering,ConvBertForSequenceClassification:()=>n.ConvBertForSequenceClassification,ConvBertForTokenClassification:()=>n.ConvBertForTokenClassification,ConvBertModel:()=>n.ConvBertModel,ConvBertPreTrainedModel:()=>n.ConvBertPreTrainedModel,ConvBertTokenizer:()=>o.ConvBertTokenizer,ConvNextFeatureExtractor:()=>a.ConvNextFeatureExtractor,ConvNextForImageClassification:()=>n.ConvNextForImageClassification,ConvNextImageProcessor:()=>a.ConvNextImageProcessor,ConvNextModel:()=>n.ConvNextModel,ConvNextPreTrainedModel:()=>n.ConvNextPreTrainedModel,ConvNextV2ForImageClassification:()=>n.ConvNextV2ForImageClassification,ConvNextV2Model:()=>n.ConvNextV2Model,ConvNextV2PreTrainedModel:()=>n.ConvNextV2PreTrainedModel,DPTFeatureExtractor:()=>a.DPTFeatureExtractor,DPTForDepthEstimation:()=>n.DPTForDepthEstimation,DPTImageProcessor:()=>a.DPTImageProcessor,DPTModel:()=>n.DPTModel,DPTPreTrainedModel:()=>n.DPTPreTrainedModel,DebertaForMaskedLM:()=>n.DebertaForMaskedLM,DebertaForQuestionAnswering:()=>n.DebertaForQuestionAnswering,DebertaForSequenceClassification:()=>n.DebertaForSequenceClassification,DebertaForTokenClassification:()=>n.DebertaForTokenClassification,DebertaModel:()=>n.DebertaModel,DebertaPreTrainedModel:()=>n.DebertaPreTrainedModel,DebertaTokenizer:()=>o.DebertaTokenizer,DebertaV2ForMaskedLM:()=>n.DebertaV2ForMaskedLM,DebertaV2ForQuestionAnswering:()=>n.DebertaV2ForQuestionAnswering,DebertaV2ForSequenceClassification:()=>n.DebertaV2ForSequenceClassification,DebertaV2ForTokenClassification:()=>n.DebertaV2ForTokenClassification,DebertaV2Model:()=>n.DebertaV2Model,DebertaV2PreTrainedModel:()=>n.DebertaV2PreTrainedModel,DebertaV2Tokenizer:()=>o.DebertaV2Tokenizer,DeiTFeatureExtractor:()=>a.DeiTFeatureExtractor,DeiTForImageClassification:()=>n.DeiTForImageClassification,DeiTModel:()=>n.DeiTModel,DeiTPreTrainedModel:()=>n.DeiTPreTrainedModel,DepthAnythingForDepthEstimation:()=>n.DepthAnythingForDepthEstimation,DepthAnythingPreTrainedModel:()=>n.DepthAnythingPreTrainedModel,DepthEstimationPipeline:()=>t.DepthEstimationPipeline,DetrFeatureExtractor:()=>a.DetrFeatureExtractor,DetrForObjectDetection:()=>n.DetrForObjectDetection,DetrForSegmentation:()=>n.DetrForSegmentation,DetrModel:()=>n.DetrModel,DetrObjectDetectionOutput:()=>n.DetrObjectDetectionOutput,DetrPreTrainedModel:()=>n.DetrPreTrainedModel,DetrSegmentationOutput:()=>n.DetrSegmentationOutput,Dinov2ForImageClassification:()=>n.Dinov2ForImageClassification,Dinov2Model:()=>n.Dinov2Model,Dinov2PreTrainedModel:()=>n.Dinov2PreTrainedModel,DistilBertForMaskedLM:()=>n.DistilBertForMaskedLM,DistilBertForQuestionAnswering:()=>n.DistilBertForQuestionAnswering,DistilBertForSequenceClassification:()=>n.DistilBertForSequenceClassification,DistilBertForTokenClassification:()=>n.DistilBertForTokenClassification,DistilBertModel:()=>n.DistilBertModel,DistilBertPreTrainedModel:()=>n.DistilBertPreTrainedModel,DistilBertTokenizer:()=>o.DistilBertTokenizer,DocumentQuestionAnsweringPipeline:()=>t.DocumentQuestionAnsweringPipeline,DonutFeatureExtractor:()=>a.DonutFeatureExtractor,DonutSwinModel:()=>n.DonutSwinModel,DonutSwinPreTrainedModel:()=>n.DonutSwinPreTrainedModel,EfficientNetForImageClassification:()=>n.EfficientNetForImageClassification,EfficientNetImageProcessor:()=>a.EfficientNetImageProcessor,EfficientNetModel:()=>n.EfficientNetModel,EfficientNetPreTrainedModel:()=>n.EfficientNetPreTrainedModel,ElectraForMaskedLM:()=>n.ElectraForMaskedLM,ElectraForQuestionAnswering:()=>n.ElectraForQuestionAnswering,ElectraForSequenceClassification:()=>n.ElectraForSequenceClassification,ElectraForTokenClassification:()=>n.ElectraForTokenClassification,ElectraModel:()=>n.ElectraModel,ElectraPreTrainedModel:()=>n.ElectraPreTrainedModel,ElectraTokenizer:()=>o.ElectraTokenizer,EosTokenCriteria:()=>w.EosTokenCriteria,EsmForMaskedLM:()=>n.EsmForMaskedLM,EsmForSequenceClassification:()=>n.EsmForSequenceClassification,EsmForTokenClassification:()=>n.EsmForTokenClassification,EsmModel:()=>n.EsmModel,EsmPreTrainedModel:()=>n.EsmPreTrainedModel,EsmTokenizer:()=>o.EsmTokenizer,FFT:()=>g.FFT,FalconForCausalLM:()=>n.FalconForCausalLM,FalconModel:()=>n.FalconModel,FalconPreTrainedModel:()=>n.FalconPreTrainedModel,FalconTokenizer:()=>o.FalconTokenizer,FastViTForImageClassification:()=>n.FastViTForImageClassification,FastViTModel:()=>n.FastViTModel,FastViTPreTrainedModel:()=>n.FastViTPreTrainedModel,FeatureExtractionPipeline:()=>t.FeatureExtractionPipeline,FeatureExtractor:()=>a.FeatureExtractor,FillMaskPipeline:()=>t.FillMaskPipeline,Florence2ForConditionalGeneration:()=>n.Florence2ForConditionalGeneration,Florence2PreTrainedModel:()=>n.Florence2PreTrainedModel,Florence2Processor:()=>a.Florence2Processor,GLPNFeatureExtractor:()=>a.GLPNFeatureExtractor,GLPNForDepthEstimation:()=>n.GLPNForDepthEstimation,GLPNModel:()=>n.GLPNModel,GLPNPreTrainedModel:()=>n.GLPNPreTrainedModel,GPT2LMHeadModel:()=>n.GPT2LMHeadModel,GPT2Model:()=>n.GPT2Model,GPT2PreTrainedModel:()=>n.GPT2PreTrainedModel,GPT2Tokenizer:()=>o.GPT2Tokenizer,GPTBigCodeForCausalLM:()=>n.GPTBigCodeForCausalLM,GPTBigCodeModel:()=>n.GPTBigCodeModel,GPTBigCodePreTrainedModel:()=>n.GPTBigCodePreTrainedModel,GPTJForCausalLM:()=>n.GPTJForCausalLM,GPTJModel:()=>n.GPTJModel,GPTJPreTrainedModel:()=>n.GPTJPreTrainedModel,GPTNeoForCausalLM:()=>n.GPTNeoForCausalLM,GPTNeoModel:()=>n.GPTNeoModel,GPTNeoPreTrainedModel:()=>n.GPTNeoPreTrainedModel,GPTNeoXForCausalLM:()=>n.GPTNeoXForCausalLM,GPTNeoXModel:()=>n.GPTNeoXModel,GPTNeoXPreTrainedModel:()=>n.GPTNeoXPreTrainedModel,GPTNeoXTokenizer:()=>o.GPTNeoXTokenizer,Gemma2ForCausalLM:()=>n.Gemma2ForCausalLM,Gemma2Model:()=>n.Gemma2Model,Gemma2PreTrainedModel:()=>n.Gemma2PreTrainedModel,GemmaForCausalLM:()=>n.GemmaForCausalLM,GemmaModel:()=>n.GemmaModel,GemmaPreTrainedModel:()=>n.GemmaPreTrainedModel,GemmaTokenizer:()=>o.GemmaTokenizer,Grok1Tokenizer:()=>o.Grok1Tokenizer,HerbertTokenizer:()=>o.HerbertTokenizer,HubertForCTC:()=>n.HubertForCTC,HubertForSequenceClassification:()=>n.HubertForSequenceClassification,HubertModel:()=>n.HubertModel,HubertPreTrainedModel:()=>n.HubertPreTrainedModel,ImageClassificationPipeline:()=>t.ImageClassificationPipeline,ImageFeatureExtractionPipeline:()=>t.ImageFeatureExtractionPipeline,ImageFeatureExtractor:()=>a.ImageFeatureExtractor,ImageMattingOutput:()=>n.ImageMattingOutput,ImageSegmentationPipeline:()=>t.ImageSegmentationPipeline,ImageToImagePipeline:()=>t.ImageToImagePipeline,ImageToTextPipeline:()=>t.ImageToTextPipeline,InterruptableStoppingCriteria:()=>w.InterruptableStoppingCriteria,LlamaForCausalLM:()=>n.LlamaForCausalLM,LlamaModel:()=>n.LlamaModel,LlamaPreTrainedModel:()=>n.LlamaPreTrainedModel,LlamaTokenizer:()=>o.LlamaTokenizer,LlavaForConditionalGeneration:()=>n.LlavaForConditionalGeneration,LlavaPreTrainedModel:()=>n.LlavaPreTrainedModel,LongT5ForConditionalGeneration:()=>n.LongT5ForConditionalGeneration,LongT5Model:()=>n.LongT5Model,LongT5PreTrainedModel:()=>n.LongT5PreTrainedModel,M2M100ForConditionalGeneration:()=>n.M2M100ForConditionalGeneration,M2M100Model:()=>n.M2M100Model,M2M100PreTrainedModel:()=>n.M2M100PreTrainedModel,M2M100Tokenizer:()=>o.M2M100Tokenizer,MBart50Tokenizer:()=>o.MBart50Tokenizer,MBartForCausalLM:()=>n.MBartForCausalLM,MBartForConditionalGeneration:()=>n.MBartForConditionalGeneration,MBartForSequenceClassification:()=>n.MBartForSequenceClassification,MBartModel:()=>n.MBartModel,MBartPreTrainedModel:()=>n.MBartPreTrainedModel,MBartTokenizer:()=>o.MBartTokenizer,MPNetForMaskedLM:()=>n.MPNetForMaskedLM,MPNetForQuestionAnswering:()=>n.MPNetForQuestionAnswering,MPNetForSequenceClassification:()=>n.MPNetForSequenceClassification,MPNetForTokenClassification:()=>n.MPNetForTokenClassification,MPNetModel:()=>n.MPNetModel,MPNetPreTrainedModel:()=>n.MPNetPreTrainedModel,MPNetTokenizer:()=>o.MPNetTokenizer,MT5ForConditionalGeneration:()=>n.MT5ForConditionalGeneration,MT5Model:()=>n.MT5Model,MT5PreTrainedModel:()=>n.MT5PreTrainedModel,MarianMTModel:()=>n.MarianMTModel,MarianModel:()=>n.MarianModel,MarianPreTrainedModel:()=>n.MarianPreTrainedModel,MarianTokenizer:()=>o.MarianTokenizer,MaskedLMOutput:()=>n.MaskedLMOutput,MaxLengthCriteria:()=>w.MaxLengthCriteria,MistralForCausalLM:()=>n.MistralForCausalLM,MistralModel:()=>n.MistralModel,MistralPreTrainedModel:()=>n.MistralPreTrainedModel,MobileBertForMaskedLM:()=>n.MobileBertForMaskedLM,MobileBertForQuestionAnswering:()=>n.MobileBertForQuestionAnswering,MobileBertForSequenceClassification:()=>n.MobileBertForSequenceClassification,MobileBertModel:()=>n.MobileBertModel,MobileBertPreTrainedModel:()=>n.MobileBertPreTrainedModel,MobileBertTokenizer:()=>o.MobileBertTokenizer,MobileNetV1FeatureExtractor:()=>a.MobileNetV1FeatureExtractor,MobileNetV1ForImageClassification:()=>n.MobileNetV1ForImageClassification,MobileNetV1Model:()=>n.MobileNetV1Model,MobileNetV1PreTrainedModel:()=>n.MobileNetV1PreTrainedModel,MobileNetV2FeatureExtractor:()=>a.MobileNetV2FeatureExtractor,MobileNetV2ForImageClassification:()=>n.MobileNetV2ForImageClassification,MobileNetV2Model:()=>n.MobileNetV2Model,MobileNetV2PreTrainedModel:()=>n.MobileNetV2PreTrainedModel,MobileNetV3FeatureExtractor:()=>a.MobileNetV3FeatureExtractor,MobileNetV3ForImageClassification:()=>n.MobileNetV3ForImageClassification,MobileNetV3Model:()=>n.MobileNetV3Model,MobileNetV3PreTrainedModel:()=>n.MobileNetV3PreTrainedModel,MobileNetV4FeatureExtractor:()=>a.MobileNetV4FeatureExtractor,MobileNetV4ForImageClassification:()=>n.MobileNetV4ForImageClassification,MobileNetV4Model:()=>n.MobileNetV4Model,MobileNetV4PreTrainedModel:()=>n.MobileNetV4PreTrainedModel,MobileViTFeatureExtractor:()=>a.MobileViTFeatureExtractor,MobileViTForImageClassification:()=>n.MobileViTForImageClassification,MobileViTImageProcessor:()=>a.MobileViTImageProcessor,MobileViTModel:()=>n.MobileViTModel,MobileViTPreTrainedModel:()=>n.MobileViTPreTrainedModel,MobileViTV2ForImageClassification:()=>n.MobileViTV2ForImageClassification,MobileViTV2Model:()=>n.MobileViTV2Model,MobileViTV2PreTrainedModel:()=>n.MobileViTV2PreTrainedModel,ModelOutput:()=>n.ModelOutput,Moondream1ForConditionalGeneration:()=>n.Moondream1ForConditionalGeneration,MptForCausalLM:()=>n.MptForCausalLM,MptModel:()=>n.MptModel,MptPreTrainedModel:()=>n.MptPreTrainedModel,MusicgenForCausalLM:()=>n.MusicgenForCausalLM,MusicgenForConditionalGeneration:()=>n.MusicgenForConditionalGeneration,MusicgenModel:()=>n.MusicgenModel,MusicgenPreTrainedModel:()=>n.MusicgenPreTrainedModel,NllbTokenizer:()=>o.NllbTokenizer,NomicBertModel:()=>n.NomicBertModel,NomicBertPreTrainedModel:()=>n.NomicBertPreTrainedModel,NougatImageProcessor:()=>a.NougatImageProcessor,NougatTokenizer:()=>o.NougatTokenizer,OPTForCausalLM:()=>n.OPTForCausalLM,OPTModel:()=>n.OPTModel,OPTPreTrainedModel:()=>n.OPTPreTrainedModel,ObjectDetectionPipeline:()=>t.ObjectDetectionPipeline,OpenELMForCausalLM:()=>n.OpenELMForCausalLM,OpenELMModel:()=>n.OpenELMModel,OpenELMPreTrainedModel:()=>n.OpenELMPreTrainedModel,OwlViTFeatureExtractor:()=>a.OwlViTFeatureExtractor,OwlViTForObjectDetection:()=>n.OwlViTForObjectDetection,OwlViTModel:()=>n.OwlViTModel,OwlViTPreTrainedModel:()=>n.OwlViTPreTrainedModel,OwlViTProcessor:()=>a.OwlViTProcessor,Owlv2ForObjectDetection:()=>n.Owlv2ForObjectDetection,Owlv2ImageProcessor:()=>a.Owlv2ImageProcessor,Owlv2Model:()=>n.Owlv2Model,Owlv2PreTrainedModel:()=>n.Owlv2PreTrainedModel,Phi3ForCausalLM:()=>n.Phi3ForCausalLM,Phi3Model:()=>n.Phi3Model,Phi3PreTrainedModel:()=>n.Phi3PreTrainedModel,PhiForCausalLM:()=>n.PhiForCausalLM,PhiModel:()=>n.PhiModel,PhiPreTrainedModel:()=>n.PhiPreTrainedModel,Pipeline:()=>t.Pipeline,PreTrainedModel:()=>n.PreTrainedModel,PreTrainedTokenizer:()=>o.PreTrainedTokenizer,PretrainedConfig:()=>l.PretrainedConfig,PretrainedMixin:()=>n.PretrainedMixin,Processor:()=>a.Processor,PyAnnoteFeatureExtractor:()=>a.PyAnnoteFeatureExtractor,PyAnnoteForAudioFrameClassification:()=>n.PyAnnoteForAudioFrameClassification,PyAnnoteModel:()=>n.PyAnnoteModel,PyAnnotePreTrainedModel:()=>n.PyAnnotePreTrainedModel,PyAnnoteProcessor:()=>a.PyAnnoteProcessor,QuestionAnsweringModelOutput:()=>n.QuestionAnsweringModelOutput,QuestionAnsweringPipeline:()=>t.QuestionAnsweringPipeline,Qwen2ForCausalLM:()=>n.Qwen2ForCausalLM,Qwen2Model:()=>n.Qwen2Model,Qwen2PreTrainedModel:()=>n.Qwen2PreTrainedModel,Qwen2Tokenizer:()=>o.Qwen2Tokenizer,RTDetrForObjectDetection:()=>n.RTDetrForObjectDetection,RTDetrImageProcessor:()=>a.RTDetrImageProcessor,RTDetrModel:()=>n.RTDetrModel,RTDetrObjectDetectionOutput:()=>n.RTDetrObjectDetectionOutput,RTDetrPreTrainedModel:()=>n.RTDetrPreTrainedModel,RawImage:()=>_.RawImage,ResNetForImageClassification:()=>n.ResNetForImageClassification,ResNetModel:()=>n.ResNetModel,ResNetPreTrainedModel:()=>n.ResNetPreTrainedModel,RoFormerForMaskedLM:()=>n.RoFormerForMaskedLM,RoFormerForQuestionAnswering:()=>n.RoFormerForQuestionAnswering,RoFormerForSequenceClassification:()=>n.RoFormerForSequenceClassification,RoFormerForTokenClassification:()=>n.RoFormerForTokenClassification,RoFormerModel:()=>n.RoFormerModel,RoFormerPreTrainedModel:()=>n.RoFormerPreTrainedModel,RoFormerTokenizer:()=>o.RoFormerTokenizer,RobertaForMaskedLM:()=>n.RobertaForMaskedLM,RobertaForQuestionAnswering:()=>n.RobertaForQuestionAnswering,RobertaForSequenceClassification:()=>n.RobertaForSequenceClassification,RobertaForTokenClassification:()=>n.RobertaForTokenClassification,RobertaModel:()=>n.RobertaModel,RobertaPreTrainedModel:()=>n.RobertaPreTrainedModel,RobertaTokenizer:()=>o.RobertaTokenizer,SamImageProcessor:()=>a.SamImageProcessor,SamImageSegmentationOutput:()=>n.SamImageSegmentationOutput,SamModel:()=>n.SamModel,SamPreTrainedModel:()=>n.SamPreTrainedModel,SamProcessor:()=>a.SamProcessor,SeamlessM4TFeatureExtractor:()=>a.SeamlessM4TFeatureExtractor,SegformerFeatureExtractor:()=>a.SegformerFeatureExtractor,SegformerForImageClassification:()=>n.SegformerForImageClassification,SegformerForSemanticSegmentation:()=>n.SegformerForSemanticSegmentation,SegformerModel:()=>n.SegformerModel,SegformerPreTrainedModel:()=>n.SegformerPreTrainedModel,Seq2SeqLMOutput:()=>n.Seq2SeqLMOutput,SequenceClassifierOutput:()=>n.SequenceClassifierOutput,SiglipImageProcessor:()=>a.SiglipImageProcessor,SiglipModel:()=>n.SiglipModel,SiglipPreTrainedModel:()=>n.SiglipPreTrainedModel,SiglipTextModel:()=>n.SiglipTextModel,SiglipTokenizer:()=>o.SiglipTokenizer,SiglipVisionModel:()=>n.SiglipVisionModel,SpeechT5FeatureExtractor:()=>a.SpeechT5FeatureExtractor,SpeechT5ForSpeechToText:()=>n.SpeechT5ForSpeechToText,SpeechT5ForTextToSpeech:()=>n.SpeechT5ForTextToSpeech,SpeechT5HifiGan:()=>n.SpeechT5HifiGan,SpeechT5Model:()=>n.SpeechT5Model,SpeechT5PreTrainedModel:()=>n.SpeechT5PreTrainedModel,SpeechT5Processor:()=>a.SpeechT5Processor,SpeechT5Tokenizer:()=>o.SpeechT5Tokenizer,SqueezeBertForMaskedLM:()=>n.SqueezeBertForMaskedLM,SqueezeBertForQuestionAnswering:()=>n.SqueezeBertForQuestionAnswering,SqueezeBertForSequenceClassification:()=>n.SqueezeBertForSequenceClassification,SqueezeBertModel:()=>n.SqueezeBertModel,SqueezeBertPreTrainedModel:()=>n.SqueezeBertPreTrainedModel,SqueezeBertTokenizer:()=>o.SqueezeBertTokenizer,StableLmForCausalLM:()=>n.StableLmForCausalLM,StableLmModel:()=>n.StableLmModel,StableLmPreTrainedModel:()=>n.StableLmPreTrainedModel,Starcoder2ForCausalLM:()=>n.Starcoder2ForCausalLM,Starcoder2Model:()=>n.Starcoder2Model,Starcoder2PreTrainedModel:()=>n.Starcoder2PreTrainedModel,StoppingCriteria:()=>w.StoppingCriteria,StoppingCriteriaList:()=>w.StoppingCriteriaList,SummarizationPipeline:()=>t.SummarizationPipeline,Swin2SRForImageSuperResolution:()=>n.Swin2SRForImageSuperResolution,Swin2SRImageProcessor:()=>a.Swin2SRImageProcessor,Swin2SRModel:()=>n.Swin2SRModel,Swin2SRPreTrainedModel:()=>n.Swin2SRPreTrainedModel,SwinForImageClassification:()=>n.SwinForImageClassification,SwinModel:()=>n.SwinModel,SwinPreTrainedModel:()=>n.SwinPreTrainedModel,T5ForConditionalGeneration:()=>n.T5ForConditionalGeneration,T5Model:()=>n.T5Model,T5PreTrainedModel:()=>n.T5PreTrainedModel,T5Tokenizer:()=>o.T5Tokenizer,TableTransformerForObjectDetection:()=>n.TableTransformerForObjectDetection,TableTransformerModel:()=>n.TableTransformerModel,TableTransformerObjectDetectionOutput:()=>n.TableTransformerObjectDetectionOutput,TableTransformerPreTrainedModel:()=>n.TableTransformerPreTrainedModel,Tensor:()=>h.Tensor,Text2TextGenerationPipeline:()=>t.Text2TextGenerationPipeline,TextClassificationPipeline:()=>t.TextClassificationPipeline,TextGenerationPipeline:()=>t.TextGenerationPipeline,TextStreamer:()=>M.TextStreamer,TextToAudioPipeline:()=>t.TextToAudioPipeline,TokenClassificationPipeline:()=>t.TokenClassificationPipeline,TokenClassifierOutput:()=>n.TokenClassifierOutput,TokenizerModel:()=>o.TokenizerModel,TrOCRForCausalLM:()=>n.TrOCRForCausalLM,TrOCRPreTrainedModel:()=>n.TrOCRPreTrainedModel,TranslationPipeline:()=>t.TranslationPipeline,UniSpeechForCTC:()=>n.UniSpeechForCTC,UniSpeechForSequenceClassification:()=>n.UniSpeechForSequenceClassification,UniSpeechModel:()=>n.UniSpeechModel,UniSpeechPreTrainedModel:()=>n.UniSpeechPreTrainedModel,UniSpeechSatForAudioFrameClassification:()=>n.UniSpeechSatForAudioFrameClassification,UniSpeechSatForCTC:()=>n.UniSpeechSatForCTC,UniSpeechSatForSequenceClassification:()=>n.UniSpeechSatForSequenceClassification,UniSpeechSatModel:()=>n.UniSpeechSatModel,UniSpeechSatPreTrainedModel:()=>n.UniSpeechSatPreTrainedModel,ViTFeatureExtractor:()=>a.ViTFeatureExtractor,ViTForImageClassification:()=>n.ViTForImageClassification,ViTImageProcessor:()=>a.ViTImageProcessor,ViTModel:()=>n.ViTModel,ViTPreTrainedModel:()=>n.ViTPreTrainedModel,VisionEncoderDecoderModel:()=>n.VisionEncoderDecoderModel,VitMatteForImageMatting:()=>n.VitMatteForImageMatting,VitMatteImageProcessor:()=>a.VitMatteImageProcessor,VitMattePreTrainedModel:()=>n.VitMattePreTrainedModel,VitsModel:()=>n.VitsModel,VitsModelOutput:()=>n.VitsModelOutput,VitsPreTrainedModel:()=>n.VitsPreTrainedModel,VitsTokenizer:()=>o.VitsTokenizer,Wav2Vec2BertForCTC:()=>n.Wav2Vec2BertForCTC,Wav2Vec2BertForSequenceClassification:()=>n.Wav2Vec2BertForSequenceClassification,Wav2Vec2BertModel:()=>n.Wav2Vec2BertModel,Wav2Vec2BertPreTrainedModel:()=>n.Wav2Vec2BertPreTrainedModel,Wav2Vec2CTCTokenizer:()=>o.Wav2Vec2CTCTokenizer,Wav2Vec2FeatureExtractor:()=>a.Wav2Vec2FeatureExtractor,Wav2Vec2ForAudioFrameClassification:()=>n.Wav2Vec2ForAudioFrameClassification,Wav2Vec2ForCTC:()=>n.Wav2Vec2ForCTC,Wav2Vec2ForSequenceClassification:()=>n.Wav2Vec2ForSequenceClassification,Wav2Vec2Model:()=>n.Wav2Vec2Model,Wav2Vec2PreTrainedModel:()=>n.Wav2Vec2PreTrainedModel,Wav2Vec2ProcessorWithLM:()=>a.Wav2Vec2ProcessorWithLM,WavLMForAudioFrameClassification:()=>n.WavLMForAudioFrameClassification,WavLMForCTC:()=>n.WavLMForCTC,WavLMForSequenceClassification:()=>n.WavLMForSequenceClassification,WavLMForXVector:()=>n.WavLMForXVector,WavLMModel:()=>n.WavLMModel,WavLMPreTrainedModel:()=>n.WavLMPreTrainedModel,WeSpeakerFeatureExtractor:()=>a.WeSpeakerFeatureExtractor,WeSpeakerResNetModel:()=>n.WeSpeakerResNetModel,WeSpeakerResNetPreTrainedModel:()=>n.WeSpeakerResNetPreTrainedModel,WhisperFeatureExtractor:()=>a.WhisperFeatureExtractor,WhisperForConditionalGeneration:()=>n.WhisperForConditionalGeneration,WhisperModel:()=>n.WhisperModel,WhisperPreTrainedModel:()=>n.WhisperPreTrainedModel,WhisperProcessor:()=>a.WhisperProcessor,WhisperTextStreamer:()=>M.WhisperTextStreamer,WhisperTokenizer:()=>o.WhisperTokenizer,XLMForQuestionAnswering:()=>n.XLMForQuestionAnswering,XLMForSequenceClassification:()=>n.XLMForSequenceClassification,XLMForTokenClassification:()=>n.XLMForTokenClassification,XLMModel:()=>n.XLMModel,XLMPreTrainedModel:()=>n.XLMPreTrainedModel,XLMRobertaForMaskedLM:()=>n.XLMRobertaForMaskedLM,XLMRobertaForQuestionAnswering:()=>n.XLMRobertaForQuestionAnswering,XLMRobertaForSequenceClassification:()=>n.XLMRobertaForSequenceClassification,XLMRobertaForTokenClassification:()=>n.XLMRobertaForTokenClassification,XLMRobertaModel:()=>n.XLMRobertaModel,XLMRobertaPreTrainedModel:()=>n.XLMRobertaPreTrainedModel,XLMRobertaTokenizer:()=>o.XLMRobertaTokenizer,XLMTokenizer:()=>o.XLMTokenizer,XLMWithLMHeadModel:()=>n.XLMWithLMHeadModel,XVectorOutput:()=>n.XVectorOutput,YolosFeatureExtractor:()=>a.YolosFeatureExtractor,YolosForObjectDetection:()=>n.YolosForObjectDetection,YolosModel:()=>n.YolosModel,YolosObjectDetectionOutput:()=>n.YolosObjectDetectionOutput,YolosPreTrainedModel:()=>n.YolosPreTrainedModel,ZeroShotAudioClassificationPipeline:()=>t.ZeroShotAudioClassificationPipeline,ZeroShotClassificationPipeline:()=>t.ZeroShotClassificationPipeline,ZeroShotImageClassificationPipeline:()=>t.ZeroShotImageClassificationPipeline,ZeroShotObjectDetectionPipeline:()=>t.ZeroShotObjectDetectionPipeline,bankers_round:()=>g.bankers_round,cat:()=>h.cat,cos_sim:()=>g.cos_sim,dot:()=>g.dot,dynamic_time_warping:()=>g.dynamic_time_warping,env:()=>e.env,full:()=>h.full,full_like:()=>h.full_like,getKeyValueShapes:()=>l.getKeyValueShapes,hamming:()=>f.hamming,hanning:()=>f.hanning,interpolate:()=>h.interpolate,interpolate_4d:()=>h.interpolate_4d,interpolate_data:()=>g.interpolate_data,is_chinese_char:()=>o.is_chinese_char,layer_norm:()=>h.layer_norm,log_softmax:()=>g.log_softmax,magnitude:()=>g.magnitude,matmul:()=>h.matmul,max:()=>g.max,mean:()=>h.mean,mean_pooling:()=>h.mean_pooling,medianFilter:()=>g.medianFilter,mel_filter_bank:()=>f.mel_filter_bank,min:()=>g.min,ones:()=>h.ones,ones_like:()=>h.ones_like,permute:()=>h.permute,permute_data:()=>g.permute_data,pipeline:()=>t.pipeline,quantize_embeddings:()=>h.quantize_embeddings,read_audio:()=>f.read_audio,rfft:()=>h.rfft,round:()=>g.round,softmax:()=>g.softmax,spectrogram:()=>f.spectrogram,stack:()=>h.stack,std_mean:()=>h.std_mean,topk:()=>h.topk,window_function:()=>f.window_function,zeros:()=>h.zeros,zeros_like:()=>h.zeros_like});var e=Yr("./src/env.js"),t=Yr("./src/pipelines.js"),n=Yr("./src/models.js"),o=Yr("./src/tokenizers.js"),a=Yr("./src/processors.js"),l=Yr("./src/configs.js"),f=Yr("./src/utils/audio.js"),_=Yr("./src/utils/image.js"),h=Yr("./src/utils/tensor.js"),g=Yr("./src/utils/maths.js"),M=Yr("./src/generation/streamers.js"),w=Yr("./src/generation/stopping_criteria.js")})();$.ASTFeatureExtractor;$.ASTForAudioClassification;$.ASTModel;$.ASTPreTrainedModel;$.AlbertForMaskedLM;$.AlbertForQuestionAnswering;$.AlbertForSequenceClassification;$.AlbertModel;$.AlbertPreTrainedModel;$.AlbertTokenizer;$.AudioClassificationPipeline;$.AutoConfig;var aE=$.AutoModel;$.AutoModelForAudioClassification;$.AutoModelForAudioFrameClassification;$.AutoModelForCTC;$.AutoModelForCausalLM;$.AutoModelForDepthEstimation;$.AutoModelForDocumentQuestionAnswering;$.AutoModelForImageClassification;$.AutoModelForImageFeatureExtraction;$.AutoModelForImageMatting;$.AutoModelForImageSegmentation;$.AutoModelForImageToImage;$.AutoModelForMaskGeneration;$.AutoModelForMaskedLM;$.AutoModelForObjectDetection;$.AutoModelForQuestionAnswering;$.AutoModelForSemanticSegmentation;$.AutoModelForSeq2SeqLM;$.AutoModelForSequenceClassification;$.AutoModelForSpeechSeq2Seq;$.AutoModelForTextToSpectrogram;$.AutoModelForTextToWaveform;$.AutoModelForTokenClassification;$.AutoModelForVision2Seq;$.AutoModelForXVector;$.AutoModelForZeroShotObjectDetection;var lE=$.AutoProcessor;$.AutoTokenizer;$.AutomaticSpeechRecognitionPipeline;$.BartForConditionalGeneration;$.BartForSequenceClassification;$.BartModel;$.BartPretrainedModel;$.BartTokenizer;$.BaseModelOutput;$.BaseStreamer;$.BeitFeatureExtractor;$.BeitForImageClassification;$.BeitModel;$.BeitPreTrainedModel;$.BertForMaskedLM;$.BertForQuestionAnswering;$.BertForSequenceClassification;$.BertForTokenClassification;$.BertModel;$.BertPreTrainedModel;$.BertTokenizer;$.BitImageProcessor;$.BlenderbotForConditionalGeneration;$.BlenderbotModel;$.BlenderbotPreTrainedModel;$.BlenderbotSmallForConditionalGeneration;$.BlenderbotSmallModel;$.BlenderbotSmallPreTrainedModel;$.BlenderbotSmallTokenizer;$.BlenderbotTokenizer;$.BloomForCausalLM;$.BloomModel;$.BloomPreTrainedModel;$.BloomTokenizer;$.CLIPFeatureExtractor;$.CLIPImageProcessor;$.CLIPModel;$.CLIPPreTrainedModel;$.CLIPSegForImageSegmentation;$.CLIPSegModel;$.CLIPSegPreTrainedModel;$.CLIPTextModelWithProjection;$.CLIPTokenizer;$.CLIPVisionModelWithProjection;$.CamembertForMaskedLM;$.CamembertForQuestionAnswering;$.CamembertForSequenceClassification;$.CamembertForTokenClassification;$.CamembertModel;$.CamembertPreTrainedModel;$.CamembertTokenizer;$.CausalLMOutput;$.CausalLMOutputWithPast;$.ChineseCLIPFeatureExtractor;$.ChineseCLIPModel;$.ChineseCLIPPreTrainedModel;$.ClapAudioModelWithProjection;$.ClapFeatureExtractor;$.ClapModel;$.ClapPreTrainedModel;$.ClapTextModelWithProjection;$.CodeGenForCausalLM;$.CodeGenModel;$.CodeGenPreTrainedModel;$.CodeGenTokenizer;$.CodeLlamaTokenizer;$.CohereForCausalLM;$.CohereModel;$.CoherePreTrainedModel;$.CohereTokenizer;$.ConvBertForMaskedLM;$.ConvBertForQuestionAnswering;$.ConvBertForSequenceClassification;$.ConvBertForTokenClassification;$.ConvBertModel;$.ConvBertPreTrainedModel;$.ConvBertTokenizer;$.ConvNextFeatureExtractor;$.ConvNextForImageClassification;$.ConvNextImageProcessor;$.ConvNextModel;$.ConvNextPreTrainedModel;$.ConvNextV2ForImageClassification;$.ConvNextV2Model;$.ConvNextV2PreTrainedModel;$.DPTFeatureExtractor;$.DPTForDepthEstimation;$.DPTImageProcessor;$.DPTModel;$.DPTPreTrainedModel;$.DebertaForMaskedLM;$.DebertaForQuestionAnswering;$.DebertaForSequenceClassification;$.DebertaForTokenClassification;$.DebertaModel;$.DebertaPreTrainedModel;$.DebertaTokenizer;$.DebertaV2ForMaskedLM;$.DebertaV2ForQuestionAnswering;$.DebertaV2ForSequenceClassification;$.DebertaV2ForTokenClassification;$.DebertaV2Model;$.DebertaV2PreTrainedModel;$.DebertaV2Tokenizer;$.DeiTFeatureExtractor;$.DeiTForImageClassification;$.DeiTModel;$.DeiTPreTrainedModel;$.DepthAnythingForDepthEstimation;$.DepthAnythingPreTrainedModel;$.DepthEstimationPipeline;$.DetrFeatureExtractor;$.DetrForObjectDetection;$.DetrForSegmentation;$.DetrModel;$.DetrObjectDetectionOutput;$.DetrPreTrainedModel;$.DetrSegmentationOutput;$.Dinov2ForImageClassification;$.Dinov2Model;$.Dinov2PreTrainedModel;$.DistilBertForMaskedLM;$.DistilBertForQuestionAnswering;$.DistilBertForSequenceClassification;$.DistilBertForTokenClassification;$.DistilBertModel;$.DistilBertPreTrainedModel;$.DistilBertTokenizer;$.DocumentQuestionAnsweringPipeline;$.DonutFeatureExtractor;$.DonutSwinModel;$.DonutSwinPreTrainedModel;$.EfficientNetForImageClassification;$.EfficientNetImageProcessor;$.EfficientNetModel;$.EfficientNetPreTrainedModel;$.ElectraForMaskedLM;$.ElectraForQuestionAnswering;$.ElectraForSequenceClassification;$.ElectraForTokenClassification;$.ElectraModel;$.ElectraPreTrainedModel;$.ElectraTokenizer;$.EosTokenCriteria;$.EsmForMaskedLM;$.EsmForSequenceClassification;$.EsmForTokenClassification;$.EsmModel;$.EsmPreTrainedModel;$.EsmTokenizer;$.FFT;$.FalconForCausalLM;$.FalconModel;$.FalconPreTrainedModel;$.FalconTokenizer;$.FastViTForImageClassification;$.FastViTModel;$.FastViTPreTrainedModel;$.FeatureExtractionPipeline;$.FeatureExtractor;$.FillMaskPipeline;$.Florence2ForConditionalGeneration;$.Florence2PreTrainedModel;$.Florence2Processor;$.GLPNFeatureExtractor;$.GLPNForDepthEstimation;$.GLPNModel;$.GLPNPreTrainedModel;$.GPT2LMHeadModel;$.GPT2Model;$.GPT2PreTrainedModel;$.GPT2Tokenizer;$.GPTBigCodeForCausalLM;$.GPTBigCodeModel;$.GPTBigCodePreTrainedModel;$.GPTJForCausalLM;$.GPTJModel;$.GPTJPreTrainedModel;$.GPTNeoForCausalLM;$.GPTNeoModel;$.GPTNeoPreTrainedModel;$.GPTNeoXForCausalLM;$.GPTNeoXModel;$.GPTNeoXPreTrainedModel;$.GPTNeoXTokenizer;$.Gemma2ForCausalLM;$.Gemma2Model;$.Gemma2PreTrainedModel;$.GemmaForCausalLM;$.GemmaModel;$.GemmaPreTrainedModel;$.GemmaTokenizer;$.Grok1Tokenizer;$.HerbertTokenizer;$.HubertForCTC;$.HubertForSequenceClassification;$.HubertModel;$.HubertPreTrainedModel;$.ImageClassificationPipeline;$.ImageFeatureExtractionPipeline;$.ImageFeatureExtractor;$.ImageMattingOutput;$.ImageSegmentationPipeline;$.ImageToImagePipeline;$.ImageToTextPipeline;$.InterruptableStoppingCriteria;$.LlamaForCausalLM;$.LlamaModel;$.LlamaPreTrainedModel;$.LlamaTokenizer;$.LlavaForConditionalGeneration;$.LlavaPreTrainedModel;$.LongT5ForConditionalGeneration;$.LongT5Model;$.LongT5PreTrainedModel;$.M2M100ForConditionalGeneration;$.M2M100Model;$.M2M100PreTrainedModel;$.M2M100Tokenizer;$.MBart50Tokenizer;$.MBartForCausalLM;$.MBartForConditionalGeneration;$.MBartForSequenceClassification;$.MBartModel;$.MBartPreTrainedModel;$.MBartTokenizer;$.MPNetForMaskedLM;$.MPNetForQuestionAnswering;$.MPNetForSequenceClassification;$.MPNetForTokenClassification;$.MPNetModel;$.MPNetPreTrainedModel;$.MPNetTokenizer;$.MT5ForConditionalGeneration;$.MT5Model;$.MT5PreTrainedModel;$.MarianMTModel;$.MarianModel;$.MarianPreTrainedModel;$.MarianTokenizer;$.MaskedLMOutput;$.MaxLengthCriteria;$.MistralForCausalLM;$.MistralModel;$.MistralPreTrainedModel;$.MobileBertForMaskedLM;$.MobileBertForQuestionAnswering;$.MobileBertForSequenceClassification;$.MobileBertModel;$.MobileBertPreTrainedModel;$.MobileBertTokenizer;$.MobileNetV1FeatureExtractor;$.MobileNetV1ForImageClassification;$.MobileNetV1Model;$.MobileNetV1PreTrainedModel;$.MobileNetV2FeatureExtractor;$.MobileNetV2ForImageClassification;$.MobileNetV2Model;$.MobileNetV2PreTrainedModel;$.MobileNetV3FeatureExtractor;$.MobileNetV3ForImageClassification;$.MobileNetV3Model;$.MobileNetV3PreTrainedModel;$.MobileNetV4FeatureExtractor;$.MobileNetV4ForImageClassification;$.MobileNetV4Model;$.MobileNetV4PreTrainedModel;$.MobileViTFeatureExtractor;$.MobileViTForImageClassification;$.MobileViTImageProcessor;$.MobileViTModel;$.MobileViTPreTrainedModel;$.MobileViTV2ForImageClassification;$.MobileViTV2Model;$.MobileViTV2PreTrainedModel;$.ModelOutput;$.Moondream1ForConditionalGeneration;$.MptForCausalLM;$.MptModel;$.MptPreTrainedModel;$.MusicgenForCausalLM;$.MusicgenForConditionalGeneration;$.MusicgenModel;$.MusicgenPreTrainedModel;$.NllbTokenizer;$.NomicBertModel;$.NomicBertPreTrainedModel;$.NougatImageProcessor;$.NougatTokenizer;$.OPTForCausalLM;$.OPTModel;$.OPTPreTrainedModel;$.ObjectDetectionPipeline;$.OpenELMForCausalLM;$.OpenELMModel;$.OpenELMPreTrainedModel;$.OwlViTFeatureExtractor;$.OwlViTForObjectDetection;$.OwlViTModel;$.OwlViTPreTrainedModel;$.OwlViTProcessor;$.Owlv2ForObjectDetection;$.Owlv2ImageProcessor;$.Owlv2Model;$.Owlv2PreTrainedModel;$.Phi3ForCausalLM;$.Phi3Model;$.Phi3PreTrainedModel;$.PhiForCausalLM;$.PhiModel;$.PhiPreTrainedModel;$.Pipeline;$.PreTrainedModel;$.PreTrainedTokenizer;$.PretrainedConfig;$.PretrainedMixin;$.Processor;$.PyAnnoteFeatureExtractor;$.PyAnnoteForAudioFrameClassification;$.PyAnnoteModel;$.PyAnnotePreTrainedModel;$.PyAnnoteProcessor;$.QuestionAnsweringModelOutput;$.QuestionAnsweringPipeline;$.Qwen2ForCausalLM;$.Qwen2Model;$.Qwen2PreTrainedModel;$.Qwen2Tokenizer;$.RTDetrForObjectDetection;$.RTDetrImageProcessor;$.RTDetrModel;$.RTDetrObjectDetectionOutput;$.RTDetrPreTrainedModel;var v1=$.RawImage;$.ResNetForImageClassification;$.ResNetModel;$.ResNetPreTrainedModel;$.RoFormerForMaskedLM;$.RoFormerForQuestionAnswering;$.RoFormerForSequenceClassification;$.RoFormerForTokenClassification;$.RoFormerModel;$.RoFormerPreTrainedModel;$.RoFormerTokenizer;$.RobertaForMaskedLM;$.RobertaForQuestionAnswering;$.RobertaForSequenceClassification;$.RobertaForTokenClassification;$.RobertaModel;$.RobertaPreTrainedModel;$.RobertaTokenizer;$.SamImageProcessor;$.SamImageSegmentationOutput;$.SamModel;$.SamPreTrainedModel;$.SamProcessor;$.SeamlessM4TFeatureExtractor;$.SegformerFeatureExtractor;$.SegformerForImageClassification;$.SegformerForSemanticSegmentation;$.SegformerModel;$.SegformerPreTrainedModel;$.Seq2SeqLMOutput;$.SequenceClassifierOutput;$.SiglipImageProcessor;$.SiglipModel;$.SiglipPreTrainedModel;$.SiglipTextModel;$.SiglipTokenizer;$.SiglipVisionModel;$.SpeechT5FeatureExtractor;$.SpeechT5ForSpeechToText;$.SpeechT5ForTextToSpeech;$.SpeechT5HifiGan;$.SpeechT5Model;$.SpeechT5PreTrainedModel;$.SpeechT5Processor;$.SpeechT5Tokenizer;$.SqueezeBertForMaskedLM;$.SqueezeBertForQuestionAnswering;$.SqueezeBertForSequenceClassification;$.SqueezeBertModel;$.SqueezeBertPreTrainedModel;$.SqueezeBertTokenizer;$.StableLmForCausalLM;$.StableLmModel;$.StableLmPreTrainedModel;$.Starcoder2ForCausalLM;$.Starcoder2Model;$.Starcoder2PreTrainedModel;$.StoppingCriteria;$.StoppingCriteriaList;$.SummarizationPipeline;$.Swin2SRForImageSuperResolution;$.Swin2SRImageProcessor;$.Swin2SRModel;$.Swin2SRPreTrainedModel;$.SwinForImageClassification;$.SwinModel;$.SwinPreTrainedModel;$.T5ForConditionalGeneration;$.T5Model;$.T5PreTrainedModel;$.T5Tokenizer;$.TableTransformerForObjectDetection;$.TableTransformerModel;$.TableTransformerObjectDetectionOutput;$.TableTransformerPreTrainedModel;$.Tensor;$.Text2TextGenerationPipeline;$.TextClassificationPipeline;$.TextGenerationPipeline;$.TextStreamer;$.TextToAudioPipeline;$.TokenClassificationPipeline;$.TokenClassifierOutput;$.TokenizerModel;$.TrOCRForCausalLM;$.TrOCRPreTrainedModel;$.TranslationPipeline;$.UniSpeechForCTC;$.UniSpeechForSequenceClassification;$.UniSpeechModel;$.UniSpeechPreTrainedModel;$.UniSpeechSatForAudioFrameClassification;$.UniSpeechSatForCTC;$.UniSpeechSatForSequenceClassification;$.UniSpeechSatModel;$.UniSpeechSatPreTrainedModel;$.ViTFeatureExtractor;$.ViTForImageClassification;$.ViTImageProcessor;$.ViTModel;$.ViTPreTrainedModel;$.VisionEncoderDecoderModel;$.VitMatteForImageMatting;$.VitMatteImageProcessor;$.VitMattePreTrainedModel;$.VitsModel;$.VitsModelOutput;$.VitsPreTrainedModel;$.VitsTokenizer;$.Wav2Vec2BertForCTC;$.Wav2Vec2BertForSequenceClassification;$.Wav2Vec2BertModel;$.Wav2Vec2BertPreTrainedModel;$.Wav2Vec2CTCTokenizer;$.Wav2Vec2FeatureExtractor;$.Wav2Vec2ForAudioFrameClassification;$.Wav2Vec2ForCTC;$.Wav2Vec2ForSequenceClassification;$.Wav2Vec2Model;$.Wav2Vec2PreTrainedModel;$.Wav2Vec2ProcessorWithLM;$.WavLMForAudioFrameClassification;$.WavLMForCTC;$.WavLMForSequenceClassification;$.WavLMForXVector;$.WavLMModel;$.WavLMPreTrainedModel;$.WeSpeakerFeatureExtractor;$.WeSpeakerResNetModel;$.WeSpeakerResNetPreTrainedModel;$.WhisperFeatureExtractor;$.WhisperForConditionalGeneration;$.WhisperModel;$.WhisperPreTrainedModel;$.WhisperProcessor;$.WhisperTextStreamer;$.WhisperTokenizer;$.XLMForQuestionAnswering;$.XLMForSequenceClassification;$.XLMForTokenClassification;$.XLMModel;$.XLMPreTrainedModel;$.XLMRobertaForMaskedLM;$.XLMRobertaForQuestionAnswering;$.XLMRobertaForSequenceClassification;$.XLMRobertaForTokenClassification;$.XLMRobertaModel;$.XLMRobertaPreTrainedModel;$.XLMRobertaTokenizer;$.XLMTokenizer;$.XLMWithLMHeadModel;$.XVectorOutput;$.YolosFeatureExtractor;$.YolosForObjectDetection;$.YolosModel;$.YolosObjectDetectionOutput;$.YolosPreTrainedModel;$.ZeroShotAudioClassificationPipeline;$.ZeroShotClassificationPipeline;$.ZeroShotImageClassificationPipeline;$.ZeroShotObjectDetectionPipeline;$.bankers_round;$.cat;$.cos_sim;$.dot;$.dynamic_time_warping;var uE=$.env;$.full;$.full_like;$.getKeyValueShapes;$.hamming;$.hanning;$.interpolate;$.interpolate_4d;$.interpolate_data;$.is_chinese_char;$.layer_norm;$.log_softmax;$.magnitude;$.matmul;$.max;$.mean;$.mean_pooling;$.medianFilter;$.mel_filter_bank;$.min;$.ones;$.ones_like;$.permute;$.permute_data;$.pipeline;$.quantize_embeddings;$.read_audio;$.rfft;$.round;$.softmax;$.spectrogram;$.stack;$.std_mean;$.topk;$.window_function;$.zeros;$.zeros_like;function uh(e){throw new Error('Could not dynamically require "'+e+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var Y2={exports:{}};/*! + +JSZip v3.10.1 - A JavaScript class for generating and reading zip files + + +(c) 2009-2016 Stuart Knightley +Dual licenced under the MIT license or GPLv3. See https://raw.github.com/Stuk/jszip/main/LICENSE.markdown. + +JSZip uses the library pako released under the MIT license : +https://github.com/nodeca/pako/blob/main/LICENSE +*/(function(e,t){(function(n){e.exports=n()})(function(){return function n(o,a,l){function f(g,M){if(!a[g]){if(!o[g]){var w=typeof uh=="function"&&uh;if(!M&&w)return w(g,!0);if(_)return _(g,!0);var C=new Error("Cannot find module '"+g+"'");throw C.code="MODULE_NOT_FOUND",C}var k=a[g]={exports:{}};o[g][0].call(k.exports,function(z){var S=o[g][1][z];return f(S||z)},k,k.exports,n,o,a,l)}return a[g].exports}for(var _=typeof uh=="function"&&uh,h=0;h>2,k=(3&g)<<4|M>>4,z=1>6:64,S=2>4,M=(15&C)<<4|(k=_.indexOf(h.charAt(S++)))>>2,w=(3&k)<<6|(z=_.indexOf(h.charAt(S++))),x[P++]=g,k!==64&&(x[P++]=M),z!==64&&(x[P++]=w);return x}},{"./support":30,"./utils":32}],2:[function(n,o,a){var l=n("./external"),f=n("./stream/DataWorker"),_=n("./stream/Crc32Probe"),h=n("./stream/DataLengthProbe");function g(M,w,C,k,z){this.compressedSize=M,this.uncompressedSize=w,this.crc32=C,this.compression=k,this.compressedContent=z}g.prototype={getContentWorker:function(){var M=new f(l.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new h("data_length")),w=this;return M.on("end",function(){if(this.streamInfo.data_length!==w.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),M},getCompressedWorker:function(){return new f(l.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},g.createWorkerFrom=function(M,w,C){return M.pipe(new _).pipe(new h("uncompressedSize")).pipe(w.compressWorker(C)).pipe(new h("compressedSize")).withStreamInfo("compression",w)},o.exports=g},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(n,o,a){var l=n("./stream/GenericWorker");a.STORE={magic:"\0\0",compressWorker:function(){return new l("STORE compression")},uncompressWorker:function(){return new l("STORE decompression")}},a.DEFLATE=n("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(n,o,a){var l=n("./utils"),f=function(){for(var _,h=[],g=0;g<256;g++){_=g;for(var M=0;M<8;M++)_=1&_?3988292384^_>>>1:_>>>1;h[g]=_}return h}();o.exports=function(_,h){return _!==void 0&&_.length?l.getTypeOf(_)!=="string"?function(g,M,w,C){var k=f,z=C+w;g^=-1;for(var S=C;S>>8^k[255&(g^M[S])];return-1^g}(0|h,_,_.length,0):function(g,M,w,C){var k=f,z=C+w;g^=-1;for(var S=C;S>>8^k[255&(g^M.charCodeAt(S))];return-1^g}(0|h,_,_.length,0):0}},{"./utils":32}],5:[function(n,o,a){a.base64=!1,a.binary=!1,a.dir=!1,a.createFolders=!0,a.date=null,a.compression=null,a.compressionOptions=null,a.comment=null,a.unixPermissions=null,a.dosPermissions=null},{}],6:[function(n,o,a){var l=null;l=typeof Promise<"u"?Promise:n("lie"),o.exports={Promise:l}},{lie:37}],7:[function(n,o,a){var l=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Uint32Array<"u",f=n("pako"),_=n("./utils"),h=n("./stream/GenericWorker"),g=l?"uint8array":"array";function M(w,C){h.call(this,"FlateWorker/"+w),this._pako=null,this._pakoAction=w,this._pakoOptions=C,this.meta={}}a.magic="\b\0",_.inherits(M,h),M.prototype.processChunk=function(w){this.meta=w.meta,this._pako===null&&this._createPako(),this._pako.push(_.transformTo(g,w.data),!1)},M.prototype.flush=function(){h.prototype.flush.call(this),this._pako===null&&this._createPako(),this._pako.push([],!0)},M.prototype.cleanUp=function(){h.prototype.cleanUp.call(this),this._pako=null},M.prototype._createPako=function(){this._pako=new f[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var w=this;this._pako.onData=function(C){w.push({data:C,meta:w.meta})}},a.compressWorker=function(w){return new M("Deflate",w)},a.uncompressWorker=function(){return new M("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(n,o,a){function l(k,z){var S,P="";for(S=0;S>>=8;return P}function f(k,z,S,P,y,x){var I,U,O=k.file,N=k.compression,j=x!==g.utf8encode,D=_.transformTo("string",x(O.name)),Y=_.transformTo("string",g.utf8encode(O.name)),de=O.comment,Ce=_.transformTo("string",x(de)),ee=_.transformTo("string",g.utf8encode(de)),ye=Y.length!==O.name.length,R=ee.length!==de.length,Me="",Qe="",ge="",Q=O.dir,ae=O.date,Se={crc32:0,compressedSize:0,uncompressedSize:0};z&&!S||(Se.crc32=k.crc32,Se.compressedSize=k.compressedSize,Se.uncompressedSize=k.uncompressedSize);var X=0;z&&(X|=8),j||!ye&&!R||(X|=2048);var me=0,Ke=0;Q&&(me|=16),y==="UNIX"?(Ke=798,me|=function(Be,We){var ot=Be;return Be||(ot=We?16893:33204),(65535&ot)<<16}(O.unixPermissions,Q)):(Ke=20,me|=function(Be){return 63&(Be||0)}(O.dosPermissions)),I=ae.getUTCHours(),I<<=6,I|=ae.getUTCMinutes(),I<<=5,I|=ae.getUTCSeconds()/2,U=ae.getUTCFullYear()-1980,U<<=4,U|=ae.getUTCMonth()+1,U<<=5,U|=ae.getUTCDate(),ye&&(Qe=l(1,1)+l(M(D),4)+Y,Me+="up"+l(Qe.length,2)+Qe),R&&(ge=l(1,1)+l(M(Ce),4)+ee,Me+="uc"+l(ge.length,2)+ge);var De="";return De+=` +\0`,De+=l(X,2),De+=N.magic,De+=l(I,2),De+=l(U,2),De+=l(Se.crc32,4),De+=l(Se.compressedSize,4),De+=l(Se.uncompressedSize,4),De+=l(D.length,2),De+=l(Me.length,2),{fileRecord:w.LOCAL_FILE_HEADER+De+D+Me,dirRecord:w.CENTRAL_FILE_HEADER+l(Ke,2)+De+l(Ce.length,2)+"\0\0\0\0"+l(me,4)+l(P,4)+D+Me+Ce}}var _=n("../utils"),h=n("../stream/GenericWorker"),g=n("../utf8"),M=n("../crc32"),w=n("../signature");function C(k,z,S,P){h.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=z,this.zipPlatform=S,this.encodeFileName=P,this.streamFiles=k,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}_.inherits(C,h),C.prototype.push=function(k){var z=k.meta.percent||0,S=this.entriesCount,P=this._sources.length;this.accumulate?this.contentBuffer.push(k):(this.bytesWritten+=k.data.length,h.prototype.push.call(this,{data:k.data,meta:{currentFile:this.currentFile,percent:S?(z+100*(S-P-1))/S:100}}))},C.prototype.openedSource=function(k){this.currentSourceOffset=this.bytesWritten,this.currentFile=k.file.name;var z=this.streamFiles&&!k.file.dir;if(z){var S=f(k,z,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:S.fileRecord,meta:{percent:0}})}else this.accumulate=!0},C.prototype.closedSource=function(k){this.accumulate=!1;var z=this.streamFiles&&!k.file.dir,S=f(k,z,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(S.dirRecord),z)this.push({data:function(P){return w.DATA_DESCRIPTOR+l(P.crc32,4)+l(P.compressedSize,4)+l(P.uncompressedSize,4)}(k),meta:{percent:100}});else for(this.push({data:S.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},C.prototype.flush=function(){for(var k=this.bytesWritten,z=0;z=this.index;h--)g=(g<<8)+this.byteAt(h);return this.index+=_,g},readString:function(_){return l.transformTo("string",this.readData(_))},readData:function(){},lastIndexOfSignature:function(){},readAndCheckSignature:function(){},readDate:function(){var _=this.readInt(4);return new Date(Date.UTC(1980+(_>>25&127),(_>>21&15)-1,_>>16&31,_>>11&31,_>>5&63,(31&_)<<1))}},o.exports=f},{"../utils":32}],19:[function(n,o,a){var l=n("./Uint8ArrayReader");function f(_){l.call(this,_)}n("../utils").inherits(f,l),f.prototype.readData=function(_){this.checkOffset(_);var h=this.data.slice(this.zero+this.index,this.zero+this.index+_);return this.index+=_,h},o.exports=f},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(n,o,a){var l=n("./DataReader");function f(_){l.call(this,_)}n("../utils").inherits(f,l),f.prototype.byteAt=function(_){return this.data.charCodeAt(this.zero+_)},f.prototype.lastIndexOfSignature=function(_){return this.data.lastIndexOf(_)-this.zero},f.prototype.readAndCheckSignature=function(_){return _===this.readData(4)},f.prototype.readData=function(_){this.checkOffset(_);var h=this.data.slice(this.zero+this.index,this.zero+this.index+_);return this.index+=_,h},o.exports=f},{"../utils":32,"./DataReader":18}],21:[function(n,o,a){var l=n("./ArrayReader");function f(_){l.call(this,_)}n("../utils").inherits(f,l),f.prototype.readData=function(_){if(this.checkOffset(_),_===0)return new Uint8Array(0);var h=this.data.subarray(this.zero+this.index,this.zero+this.index+_);return this.index+=_,h},o.exports=f},{"../utils":32,"./ArrayReader":17}],22:[function(n,o,a){var l=n("../utils"),f=n("../support"),_=n("./ArrayReader"),h=n("./StringReader"),g=n("./NodeBufferReader"),M=n("./Uint8ArrayReader");o.exports=function(w){var C=l.getTypeOf(w);return l.checkSupport(C),C!=="string"||f.uint8array?C==="nodebuffer"?new g(w):f.uint8array?new M(l.transformTo("uint8array",w)):new _(l.transformTo("array",w)):new h(w)}},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(n,o,a){a.LOCAL_FILE_HEADER="PK",a.CENTRAL_FILE_HEADER="PK",a.CENTRAL_DIRECTORY_END="PK",a.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK\x07",a.ZIP64_CENTRAL_DIRECTORY_END="PK",a.DATA_DESCRIPTOR="PK\x07\b"},{}],24:[function(n,o,a){var l=n("./GenericWorker"),f=n("../utils");function _(h){l.call(this,"ConvertWorker to "+h),this.destType=h}f.inherits(_,l),_.prototype.processChunk=function(h){this.push({data:f.transformTo(this.destType,h.data),meta:h.meta})},o.exports=_},{"../utils":32,"./GenericWorker":28}],25:[function(n,o,a){var l=n("./GenericWorker"),f=n("../crc32");function _(){l.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}n("../utils").inherits(_,l),_.prototype.processChunk=function(h){this.streamInfo.crc32=f(h.data,this.streamInfo.crc32||0),this.push(h)},o.exports=_},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(n,o,a){var l=n("../utils"),f=n("./GenericWorker");function _(h){f.call(this,"DataLengthProbe for "+h),this.propName=h,this.withStreamInfo(h,0)}l.inherits(_,f),_.prototype.processChunk=function(h){if(h){var g=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=g+h.data.length}f.prototype.processChunk.call(this,h)},o.exports=_},{"../utils":32,"./GenericWorker":28}],27:[function(n,o,a){var l=n("../utils"),f=n("./GenericWorker");function _(h){f.call(this,"DataWorker");var g=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,h.then(function(M){g.dataIsReady=!0,g.data=M,g.max=M&&M.length||0,g.type=l.getTypeOf(M),g.isPaused||g._tickAndRepeat()},function(M){g.error(M)})}l.inherits(_,f),_.prototype.cleanUp=function(){f.prototype.cleanUp.call(this),this.data=null},_.prototype.resume=function(){return!!f.prototype.resume.call(this)&&(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,l.delay(this._tickAndRepeat,[],this)),!0)},_.prototype._tickAndRepeat=function(){this._tickScheduled=!1,this.isPaused||this.isFinished||(this._tick(),this.isFinished||(l.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0))},_.prototype._tick=function(){if(this.isPaused||this.isFinished)return!1;var h=null,g=Math.min(this.max,this.index+16384);if(this.index>=this.max)return this.end();switch(this.type){case"string":h=this.data.substring(this.index,g);break;case"uint8array":h=this.data.subarray(this.index,g);break;case"array":case"nodebuffer":h=this.data.slice(this.index,g)}return this.index=g,this.push({data:h,meta:{percent:this.max?this.index/this.max*100:0}})},o.exports=_},{"../utils":32,"./GenericWorker":28}],28:[function(n,o,a){function l(f){this.name=f||"default",this.streamInfo={},this.generatedError=null,this.extraStreamInfo={},this.isPaused=!0,this.isFinished=!1,this.isLocked=!1,this._listeners={data:[],end:[],error:[]},this.previous=null}l.prototype={push:function(f){this.emit("data",f)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0}catch(f){this.emit("error",f)}return!0},error:function(f){return!this.isFinished&&(this.isPaused?this.generatedError=f:(this.isFinished=!0,this.emit("error",f),this.previous&&this.previous.error(f),this.cleanUp()),!0)},on:function(f,_){return this._listeners[f].push(_),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(f,_){if(this._listeners[f])for(var h=0;h "+f:f}},o.exports=l},{}],29:[function(n,o,a){var l=n("../utils"),f=n("./ConvertWorker"),_=n("./GenericWorker"),h=n("../base64"),g=n("../support"),M=n("../external"),w=null;if(g.nodestream)try{w=n("../nodejs/NodejsStreamOutputAdapter")}catch{}function C(z,S){return new M.Promise(function(P,y){var x=[],I=z._internalType,U=z._outputType,O=z._mimeType;z.on("data",function(N,j){x.push(N),S&&S(j)}).on("error",function(N){x=[],y(N)}).on("end",function(){try{var N=function(j,D,Y){switch(j){case"blob":return l.newBlob(l.transformTo("arraybuffer",D),Y);case"base64":return h.encode(D);default:return l.transformTo(j,D)}}(U,function(j,D){var Y,de=0,Ce=null,ee=0;for(Y=0;Y"u")a.blob=!1;else{var l=new ArrayBuffer(0);try{a.blob=new Blob([l],{type:"application/zip"}).size===0}catch{try{var f=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);f.append(l),a.blob=f.getBlob("application/zip").size===0}catch{a.blob=!1}}}try{a.nodestream=!!n("readable-stream").Readable}catch{a.nodestream=!1}},{"readable-stream":16}],31:[function(n,o,a){for(var l=n("./utils"),f=n("./support"),_=n("./nodejsUtils"),h=n("./stream/GenericWorker"),g=new Array(256),M=0;M<256;M++)g[M]=252<=M?6:248<=M?5:240<=M?4:224<=M?3:192<=M?2:1;g[254]=g[254]=1;function w(){h.call(this,"utf-8 decode"),this.leftOver=null}function C(){h.call(this,"utf-8 encode")}a.utf8encode=function(k){return f.nodebuffer?_.newBufferFrom(k,"utf-8"):function(z){var S,P,y,x,I,U=z.length,O=0;for(x=0;x>>6:(P<65536?S[I++]=224|P>>>12:(S[I++]=240|P>>>18,S[I++]=128|P>>>12&63),S[I++]=128|P>>>6&63),S[I++]=128|63&P);return S}(k)},a.utf8decode=function(k){return f.nodebuffer?l.transformTo("nodebuffer",k).toString("utf-8"):function(z){var S,P,y,x,I=z.length,U=new Array(2*I);for(S=P=0;S>10&1023,U[P++]=56320|1023&y)}return U.length!==P&&(U.subarray?U=U.subarray(0,P):U.length=P),l.applyFromCharCode(U)}(k=l.transformTo(f.uint8array?"uint8array":"array",k))},l.inherits(w,h),w.prototype.processChunk=function(k){var z=l.transformTo(f.uint8array?"uint8array":"array",k.data);if(this.leftOver&&this.leftOver.length){if(f.uint8array){var S=z;(z=new Uint8Array(S.length+this.leftOver.length)).set(this.leftOver,0),z.set(S,this.leftOver.length)}else z=this.leftOver.concat(z);this.leftOver=null}var P=function(x,I){var U;for((I=I||x.length)>x.length&&(I=x.length),U=I-1;0<=U&&(192&x[U])==128;)U--;return U<0||U===0?I:U+g[x[U]]>I?U:I}(z),y=z;P!==z.length&&(f.uint8array?(y=z.subarray(0,P),this.leftOver=z.subarray(P,z.length)):(y=z.slice(0,P),this.leftOver=z.slice(P,z.length))),this.push({data:a.utf8decode(y),meta:k.meta})},w.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:a.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},a.Utf8DecodeWorker=w,l.inherits(C,h),C.prototype.processChunk=function(k){this.push({data:a.utf8encode(k.data),meta:k.meta})},a.Utf8EncodeWorker=C},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(n,o,a){var l=n("./support"),f=n("./base64"),_=n("./nodejsUtils"),h=n("./external");function g(S){return S}function M(S,P){for(var y=0;y>8;this.dir=!!(16&this.externalFileAttributes),k==0&&(this.dosPermissions=63&this.externalFileAttributes),k==3&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||this.fileNameStr.slice(-1)!=="/"||(this.dir=!0)},parseZIP64ExtraField:function(){if(this.extraFields[1]){var k=l(this.extraFields[1].value);this.uncompressedSize===f.MAX_VALUE_32BITS&&(this.uncompressedSize=k.readInt(8)),this.compressedSize===f.MAX_VALUE_32BITS&&(this.compressedSize=k.readInt(8)),this.localHeaderOffset===f.MAX_VALUE_32BITS&&(this.localHeaderOffset=k.readInt(8)),this.diskNumberStart===f.MAX_VALUE_32BITS&&(this.diskNumberStart=k.readInt(4))}},readExtraFields:function(k){var z,S,P,y=k.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});k.index+4>>6:(k<65536?C[P++]=224|k>>>12:(C[P++]=240|k>>>18,C[P++]=128|k>>>12&63),C[P++]=128|k>>>6&63),C[P++]=128|63&k);return C},a.buf2binstring=function(w){return M(w,w.length)},a.binstring2buf=function(w){for(var C=new l.Buf8(w.length),k=0,z=C.length;k>10&1023,x[z++]=56320|1023&S)}return M(x,z)},a.utf8border=function(w,C){var k;for((C=C||w.length)>w.length&&(C=w.length),k=C-1;0<=k&&(192&w[k])==128;)k--;return k<0||k===0?C:k+h[w[k]]>C?k:C}},{"./common":41}],43:[function(n,o,a){o.exports=function(l,f,_,h){for(var g=65535&l|0,M=l>>>16&65535|0,w=0;_!==0;){for(_-=w=2e3<_?2e3:_;M=M+(g=g+f[h++]|0)|0,--w;);g%=65521,M%=65521}return g|M<<16|0}},{}],44:[function(n,o,a){o.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],45:[function(n,o,a){var l=function(){for(var f,_=[],h=0;h<256;h++){f=h;for(var g=0;g<8;g++)f=1&f?3988292384^f>>>1:f>>>1;_[h]=f}return _}();o.exports=function(f,_,h,g){var M=l,w=g+h;f^=-1;for(var C=g;C>>8^M[255&(f^_[C])];return-1^f}},{}],46:[function(n,o,a){var l,f=n("../utils/common"),_=n("./trees"),h=n("./adler32"),g=n("./crc32"),M=n("./messages"),w=0,C=4,k=0,z=-2,S=-1,P=4,y=2,x=8,I=9,U=286,O=30,N=19,j=2*U+1,D=15,Y=3,de=258,Ce=de+Y+1,ee=42,ye=113,R=1,Me=2,Qe=3,ge=4;function Q(A,Ae){return A.msg=M[Ae],Ae}function ae(A){return(A<<1)-(4A.avail_out&&($e=A.avail_out),$e!==0&&(f.arraySet(A.output,Ae.pending_buf,Ae.pending_out,$e,A.next_out),A.next_out+=$e,Ae.pending_out+=$e,A.total_out+=$e,A.avail_out-=$e,Ae.pending-=$e,Ae.pending===0&&(Ae.pending_out=0))}function me(A,Ae){_._tr_flush_block(A,0<=A.block_start?A.block_start:-1,A.strstart-A.block_start,Ae),A.block_start=A.strstart,X(A.strm)}function Ke(A,Ae){A.pending_buf[A.pending++]=Ae}function De(A,Ae){A.pending_buf[A.pending++]=Ae>>>8&255,A.pending_buf[A.pending++]=255&Ae}function Be(A,Ae){var $e,se,te=A.max_chain_length,we=A.strstart,B=A.prev_length,J=A.nice_match,L=A.strstart>A.w_size-Ce?A.strstart-(A.w_size-Ce):0,ue=A.window,le=A.w_mask,ke=A.prev,Ne=A.strstart+de,ut=ue[we+B-1],Je=ue[we+B];A.prev_length>=A.good_match&&(te>>=2),J>A.lookahead&&(J=A.lookahead);do if(ue[($e=Ae)+B]===Je&&ue[$e+B-1]===ut&&ue[$e]===ue[we]&&ue[++$e]===ue[we+1]){we+=2,$e++;do;while(ue[++we]===ue[++$e]&&ue[++we]===ue[++$e]&&ue[++we]===ue[++$e]&&ue[++we]===ue[++$e]&&ue[++we]===ue[++$e]&&ue[++we]===ue[++$e]&&ue[++we]===ue[++$e]&&ue[++we]===ue[++$e]&&weL&&--te!=0);return B<=A.lookahead?B:A.lookahead}function We(A){var Ae,$e,se,te,we,B,J,L,ue,le,ke=A.w_size;do{if(te=A.window_size-A.lookahead-A.strstart,A.strstart>=ke+(ke-Ce)){for(f.arraySet(A.window,A.window,ke,ke,0),A.match_start-=ke,A.strstart-=ke,A.block_start-=ke,Ae=$e=A.hash_size;se=A.head[--Ae],A.head[Ae]=ke<=se?se-ke:0,--$e;);for(Ae=$e=ke;se=A.prev[--Ae],A.prev[Ae]=ke<=se?se-ke:0,--$e;);te+=ke}if(A.strm.avail_in===0)break;if(B=A.strm,J=A.window,L=A.strstart+A.lookahead,ue=te,le=void 0,le=B.avail_in,ue=Y)for(we=A.strstart-A.insert,A.ins_h=A.window[we],A.ins_h=(A.ins_h<=Y&&(A.ins_h=(A.ins_h<=Y)if(se=_._tr_tally(A,A.strstart-A.match_start,A.match_length-Y),A.lookahead-=A.match_length,A.match_length<=A.max_lazy_match&&A.lookahead>=Y){for(A.match_length--;A.strstart++,A.ins_h=(A.ins_h<=Y&&(A.ins_h=(A.ins_h<=Y&&A.match_length<=A.prev_length){for(te=A.strstart+A.lookahead-Y,se=_._tr_tally(A,A.strstart-1-A.prev_match,A.prev_length-Y),A.lookahead-=A.prev_length-1,A.prev_length-=2;++A.strstart<=te&&(A.ins_h=(A.ins_h<A.pending_buf_size-5&&($e=A.pending_buf_size-5);;){if(A.lookahead<=1){if(We(A),A.lookahead===0&&Ae===w)return R;if(A.lookahead===0)break}A.strstart+=A.lookahead,A.lookahead=0;var se=A.block_start+$e;if((A.strstart===0||A.strstart>=se)&&(A.lookahead=A.strstart-se,A.strstart=se,me(A,!1),A.strm.avail_out===0)||A.strstart-A.block_start>=A.w_size-Ce&&(me(A,!1),A.strm.avail_out===0))return R}return A.insert=0,Ae===C?(me(A,!0),A.strm.avail_out===0?Qe:ge):(A.strstart>A.block_start&&(me(A,!1),A.strm.avail_out),R)}),new Ge(4,4,8,4,ot),new Ge(4,5,16,8,ot),new Ge(4,6,32,32,ot),new Ge(4,4,16,16,dt),new Ge(8,16,32,32,dt),new Ge(8,16,128,128,dt),new Ge(8,32,128,256,dt),new Ge(32,128,258,1024,dt),new Ge(32,258,258,4096,dt)],a.deflateInit=function(A,Ae){return tt(A,Ae,x,15,8,0)},a.deflateInit2=tt,a.deflateReset=Ye,a.deflateResetKeep=je,a.deflateSetHeader=function(A,Ae){return A&&A.state?A.state.wrap!==2?z:(A.state.gzhead=Ae,k):z},a.deflate=function(A,Ae){var $e,se,te,we;if(!A||!A.state||5>8&255),Ke(se,se.gzhead.time>>16&255),Ke(se,se.gzhead.time>>24&255),Ke(se,se.level===9?2:2<=se.strategy||se.level<2?4:0),Ke(se,255&se.gzhead.os),se.gzhead.extra&&se.gzhead.extra.length&&(Ke(se,255&se.gzhead.extra.length),Ke(se,se.gzhead.extra.length>>8&255)),se.gzhead.hcrc&&(A.adler=g(A.adler,se.pending_buf,se.pending,0)),se.gzindex=0,se.status=69):(Ke(se,0),Ke(se,0),Ke(se,0),Ke(se,0),Ke(se,0),Ke(se,se.level===9?2:2<=se.strategy||se.level<2?4:0),Ke(se,3),se.status=ye);else{var B=x+(se.w_bits-8<<4)<<8;B|=(2<=se.strategy||se.level<2?0:se.level<6?1:se.level===6?2:3)<<6,se.strstart!==0&&(B|=32),B+=31-B%31,se.status=ye,De(se,B),se.strstart!==0&&(De(se,A.adler>>>16),De(se,65535&A.adler)),A.adler=1}if(se.status===69)if(se.gzhead.extra){for(te=se.pending;se.gzindex<(65535&se.gzhead.extra.length)&&(se.pending!==se.pending_buf_size||(se.gzhead.hcrc&&se.pending>te&&(A.adler=g(A.adler,se.pending_buf,se.pending-te,te)),X(A),te=se.pending,se.pending!==se.pending_buf_size));)Ke(se,255&se.gzhead.extra[se.gzindex]),se.gzindex++;se.gzhead.hcrc&&se.pending>te&&(A.adler=g(A.adler,se.pending_buf,se.pending-te,te)),se.gzindex===se.gzhead.extra.length&&(se.gzindex=0,se.status=73)}else se.status=73;if(se.status===73)if(se.gzhead.name){te=se.pending;do{if(se.pending===se.pending_buf_size&&(se.gzhead.hcrc&&se.pending>te&&(A.adler=g(A.adler,se.pending_buf,se.pending-te,te)),X(A),te=se.pending,se.pending===se.pending_buf_size)){we=1;break}we=se.gzindexte&&(A.adler=g(A.adler,se.pending_buf,se.pending-te,te)),we===0&&(se.gzindex=0,se.status=91)}else se.status=91;if(se.status===91)if(se.gzhead.comment){te=se.pending;do{if(se.pending===se.pending_buf_size&&(se.gzhead.hcrc&&se.pending>te&&(A.adler=g(A.adler,se.pending_buf,se.pending-te,te)),X(A),te=se.pending,se.pending===se.pending_buf_size)){we=1;break}we=se.gzindexte&&(A.adler=g(A.adler,se.pending_buf,se.pending-te,te)),we===0&&(se.status=103)}else se.status=103;if(se.status===103&&(se.gzhead.hcrc?(se.pending+2>se.pending_buf_size&&X(A),se.pending+2<=se.pending_buf_size&&(Ke(se,255&A.adler),Ke(se,A.adler>>8&255),A.adler=0,se.status=ye)):se.status=ye),se.pending!==0){if(X(A),A.avail_out===0)return se.last_flush=-1,k}else if(A.avail_in===0&&ae(Ae)<=ae($e)&&Ae!==C)return Q(A,-5);if(se.status===666&&A.avail_in!==0)return Q(A,-5);if(A.avail_in!==0||se.lookahead!==0||Ae!==w&&se.status!==666){var J=se.strategy===2?function(L,ue){for(var le;;){if(L.lookahead===0&&(We(L),L.lookahead===0)){if(ue===w)return R;break}if(L.match_length=0,le=_._tr_tally(L,0,L.window[L.strstart]),L.lookahead--,L.strstart++,le&&(me(L,!1),L.strm.avail_out===0))return R}return L.insert=0,ue===C?(me(L,!0),L.strm.avail_out===0?Qe:ge):L.last_lit&&(me(L,!1),L.strm.avail_out===0)?R:Me}(se,Ae):se.strategy===3?function(L,ue){for(var le,ke,Ne,ut,Je=L.window;;){if(L.lookahead<=de){if(We(L),L.lookahead<=de&&ue===w)return R;if(L.lookahead===0)break}if(L.match_length=0,L.lookahead>=Y&&0L.lookahead&&(L.match_length=L.lookahead)}if(L.match_length>=Y?(le=_._tr_tally(L,1,L.match_length-Y),L.lookahead-=L.match_length,L.strstart+=L.match_length,L.match_length=0):(le=_._tr_tally(L,0,L.window[L.strstart]),L.lookahead--,L.strstart++),le&&(me(L,!1),L.strm.avail_out===0))return R}return L.insert=0,ue===C?(me(L,!0),L.strm.avail_out===0?Qe:ge):L.last_lit&&(me(L,!1),L.strm.avail_out===0)?R:Me}(se,Ae):l[se.level].func(se,Ae);if(J!==Qe&&J!==ge||(se.status=666),J===R||J===Qe)return A.avail_out===0&&(se.last_flush=-1),k;if(J===Me&&(Ae===1?_._tr_align(se):Ae!==5&&(_._tr_stored_block(se,0,0,!1),Ae===3&&(Se(se.head),se.lookahead===0&&(se.strstart=0,se.block_start=0,se.insert=0))),X(A),A.avail_out===0))return se.last_flush=-1,k}return Ae!==C?k:se.wrap<=0?1:(se.wrap===2?(Ke(se,255&A.adler),Ke(se,A.adler>>8&255),Ke(se,A.adler>>16&255),Ke(se,A.adler>>24&255),Ke(se,255&A.total_in),Ke(se,A.total_in>>8&255),Ke(se,A.total_in>>16&255),Ke(se,A.total_in>>24&255)):(De(se,A.adler>>>16),De(se,65535&A.adler)),X(A),0=$e.w_size&&(we===0&&(Se($e.head),$e.strstart=0,$e.block_start=0,$e.insert=0),ue=new f.Buf8($e.w_size),f.arraySet(ue,Ae,le-$e.w_size,$e.w_size,0),Ae=ue,le=$e.w_size),B=A.avail_in,J=A.next_in,L=A.input,A.avail_in=le,A.next_in=0,A.input=Ae,We($e);$e.lookahead>=Y;){for(se=$e.strstart,te=$e.lookahead-(Y-1);$e.ins_h=($e.ins_h<<$e.hash_shift^$e.window[se+Y-1])&$e.hash_mask,$e.prev[se&$e.w_mask]=$e.head[$e.ins_h],$e.head[$e.ins_h]=se,se++,--te;);$e.strstart=se,$e.lookahead=Y-1,We($e)}return $e.strstart+=$e.lookahead,$e.block_start=$e.strstart,$e.insert=$e.lookahead,$e.lookahead=0,$e.match_length=$e.prev_length=Y-1,$e.match_available=0,A.next_in=J,A.input=L,A.avail_in=B,$e.wrap=we,k},a.deflateInfo="pako deflate (from Nodeca project)"},{"../utils/common":41,"./adler32":43,"./crc32":45,"./messages":51,"./trees":52}],47:[function(n,o,a){o.exports=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}},{}],48:[function(n,o,a){o.exports=function(l,f){var _,h,g,M,w,C,k,z,S,P,y,x,I,U,O,N,j,D,Y,de,Ce,ee,ye,R,Me;_=l.state,h=l.next_in,R=l.input,g=h+(l.avail_in-5),M=l.next_out,Me=l.output,w=M-(f-l.avail_out),C=M+(l.avail_out-257),k=_.dmax,z=_.wsize,S=_.whave,P=_.wnext,y=_.window,x=_.hold,I=_.bits,U=_.lencode,O=_.distcode,N=(1<<_.lenbits)-1,j=(1<<_.distbits)-1;e:do{I<15&&(x+=R[h++]<>>=Y=D>>>24,I-=Y,(Y=D>>>16&255)===0)Me[M++]=65535&D;else{if(!(16&Y)){if(!(64&Y)){D=U[(65535&D)+(x&(1<>>=Y,I-=Y),I<15&&(x+=R[h++]<>>=Y=D>>>24,I-=Y,!(16&(Y=D>>>16&255))){if(!(64&Y)){D=O[(65535&D)+(x&(1<>>=Y,I-=Y,(Y=M-w)>3,x&=(1<<(I-=de<<3))-1,l.next_in=h,l.next_out=M,l.avail_in=h>>24&255)+(ee>>>8&65280)+((65280&ee)<<8)+((255&ee)<<24)}function x(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new l.Buf16(320),this.work=new l.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function I(ee){var ye;return ee&&ee.state?(ye=ee.state,ee.total_in=ee.total_out=ye.total=0,ee.msg="",ye.wrap&&(ee.adler=1&ye.wrap),ye.mode=z,ye.last=0,ye.havedict=0,ye.dmax=32768,ye.head=null,ye.hold=0,ye.bits=0,ye.lencode=ye.lendyn=new l.Buf32(S),ye.distcode=ye.distdyn=new l.Buf32(P),ye.sane=1,ye.back=-1,C):k}function U(ee){var ye;return ee&&ee.state?((ye=ee.state).wsize=0,ye.whave=0,ye.wnext=0,I(ee)):k}function O(ee,ye){var R,Me;return ee&&ee.state?(Me=ee.state,ye<0?(R=0,ye=-ye):(R=1+(ye>>4),ye<48&&(ye&=15)),ye&&(ye<8||15=ge.wsize?(l.arraySet(ge.window,ye,R-ge.wsize,ge.wsize,0),ge.wnext=0,ge.whave=ge.wsize):(Me<(Qe=ge.wsize-ge.wnext)&&(Qe=Me),l.arraySet(ge.window,ye,R-Me,Qe,ge.wnext),(Me-=Qe)?(l.arraySet(ge.window,ye,R-Me,Me,0),ge.wnext=Me,ge.whave=ge.wsize):(ge.wnext+=Qe,ge.wnext===ge.wsize&&(ge.wnext=0),ge.whave>>8&255,R.check=_(R.check,we,2,0),me=X=0,R.mode=2;break}if(R.flags=0,R.head&&(R.head.done=!1),!(1&R.wrap)||(((255&X)<<8)+(X>>8))%31){ee.msg="incorrect header check",R.mode=30;break}if((15&X)!=8){ee.msg="unknown compression method",R.mode=30;break}if(me-=4,A=8+(15&(X>>>=4)),R.wbits===0)R.wbits=A;else if(A>R.wbits){ee.msg="invalid window size",R.mode=30;break}R.dmax=1<>8&1),512&R.flags&&(we[0]=255&X,we[1]=X>>>8&255,R.check=_(R.check,we,2,0)),me=X=0,R.mode=3;case 3:for(;me<32;){if(ae===0)break e;ae--,X+=Me[ge++]<>>8&255,we[2]=X>>>16&255,we[3]=X>>>24&255,R.check=_(R.check,we,4,0)),me=X=0,R.mode=4;case 4:for(;me<16;){if(ae===0)break e;ae--,X+=Me[ge++]<>8),512&R.flags&&(we[0]=255&X,we[1]=X>>>8&255,R.check=_(R.check,we,2,0)),me=X=0,R.mode=5;case 5:if(1024&R.flags){for(;me<16;){if(ae===0)break e;ae--,X+=Me[ge++]<>>8&255,R.check=_(R.check,we,2,0)),me=X=0}else R.head&&(R.head.extra=null);R.mode=6;case 6:if(1024&R.flags&&(ae<(Be=R.length)&&(Be=ae),Be&&(R.head&&(A=R.head.extra_len-R.length,R.head.extra||(R.head.extra=new Array(R.head.extra_len)),l.arraySet(R.head.extra,Me,ge,Be,A)),512&R.flags&&(R.check=_(R.check,Me,Be,ge)),ae-=Be,ge+=Be,R.length-=Be),R.length))break e;R.length=0,R.mode=7;case 7:if(2048&R.flags){if(ae===0)break e;for(Be=0;A=Me[ge+Be++],R.head&&A&&R.length<65536&&(R.head.name+=String.fromCharCode(A)),A&&Be>9&1,R.head.done=!0),ee.adler=R.check=0,R.mode=12;break;case 10:for(;me<32;){if(ae===0)break e;ae--,X+=Me[ge++]<>>=7&me,me-=7&me,R.mode=27;break}for(;me<3;){if(ae===0)break e;ae--,X+=Me[ge++]<>>=1)){case 0:R.mode=14;break;case 1:if(de(R),R.mode=20,ye!==6)break;X>>>=2,me-=2;break e;case 2:R.mode=17;break;case 3:ee.msg="invalid block type",R.mode=30}X>>>=2,me-=2;break;case 14:for(X>>>=7&me,me-=7&me;me<32;){if(ae===0)break e;ae--,X+=Me[ge++]<>>16^65535)){ee.msg="invalid stored block lengths",R.mode=30;break}if(R.length=65535&X,me=X=0,R.mode=15,ye===6)break e;case 15:R.mode=16;case 16:if(Be=R.length){if(ae>>=5,me-=5,R.ndist=1+(31&X),X>>>=5,me-=5,R.ncode=4+(15&X),X>>>=4,me-=4,286>>=3,me-=3}for(;R.have<19;)R.lens[B[R.have++]]=0;if(R.lencode=R.lendyn,R.lenbits=7,$e={bits:R.lenbits},Ae=g(0,R.lens,0,19,R.lencode,0,R.work,$e),R.lenbits=$e.bits,Ae){ee.msg="invalid code lengths set",R.mode=30;break}R.have=0,R.mode=19;case 19:for(;R.have>>16&255,Te=65535&te,!((dt=te>>>24)<=me);){if(ae===0)break e;ae--,X+=Me[ge++]<>>=dt,me-=dt,R.lens[R.have++]=Te;else{if(Te===16){for(se=dt+2;me>>=dt,me-=dt,R.have===0){ee.msg="invalid bit length repeat",R.mode=30;break}A=R.lens[R.have-1],Be=3+(3&X),X>>>=2,me-=2}else if(Te===17){for(se=dt+3;me>>=dt)),X>>>=3,me-=3}else{for(se=dt+7;me>>=dt)),X>>>=7,me-=7}if(R.have+Be>R.nlen+R.ndist){ee.msg="invalid bit length repeat",R.mode=30;break}for(;Be--;)R.lens[R.have++]=A}}if(R.mode===30)break;if(R.lens[256]===0){ee.msg="invalid code -- missing end-of-block",R.mode=30;break}if(R.lenbits=9,$e={bits:R.lenbits},Ae=g(M,R.lens,0,R.nlen,R.lencode,0,R.work,$e),R.lenbits=$e.bits,Ae){ee.msg="invalid literal/lengths set",R.mode=30;break}if(R.distbits=6,R.distcode=R.distdyn,$e={bits:R.distbits},Ae=g(w,R.lens,R.nlen,R.ndist,R.distcode,0,R.work,$e),R.distbits=$e.bits,Ae){ee.msg="invalid distances set",R.mode=30;break}if(R.mode=20,ye===6)break e;case 20:R.mode=21;case 21:if(6<=ae&&258<=Se){ee.next_out=Q,ee.avail_out=Se,ee.next_in=ge,ee.avail_in=ae,R.hold=X,R.bits=me,h(ee,De),Q=ee.next_out,Qe=ee.output,Se=ee.avail_out,ge=ee.next_in,Me=ee.input,ae=ee.avail_in,X=R.hold,me=R.bits,R.mode===12&&(R.back=-1);break}for(R.back=0;Ge=(te=R.lencode[X&(1<>>16&255,Te=65535&te,!((dt=te>>>24)<=me);){if(ae===0)break e;ae--,X+=Me[ge++]<>je)])>>>16&255,Te=65535&te,!(je+(dt=te>>>24)<=me);){if(ae===0)break e;ae--,X+=Me[ge++]<>>=je,me-=je,R.back+=je}if(X>>>=dt,me-=dt,R.back+=dt,R.length=Te,Ge===0){R.mode=26;break}if(32&Ge){R.back=-1,R.mode=12;break}if(64&Ge){ee.msg="invalid literal/length code",R.mode=30;break}R.extra=15&Ge,R.mode=22;case 22:if(R.extra){for(se=R.extra;me>>=R.extra,me-=R.extra,R.back+=R.extra}R.was=R.length,R.mode=23;case 23:for(;Ge=(te=R.distcode[X&(1<>>16&255,Te=65535&te,!((dt=te>>>24)<=me);){if(ae===0)break e;ae--,X+=Me[ge++]<>je)])>>>16&255,Te=65535&te,!(je+(dt=te>>>24)<=me);){if(ae===0)break e;ae--,X+=Me[ge++]<>>=je,me-=je,R.back+=je}if(X>>>=dt,me-=dt,R.back+=dt,64&Ge){ee.msg="invalid distance code",R.mode=30;break}R.offset=Te,R.extra=15&Ge,R.mode=24;case 24:if(R.extra){for(se=R.extra;me>>=R.extra,me-=R.extra,R.back+=R.extra}if(R.offset>R.dmax){ee.msg="invalid distance too far back",R.mode=30;break}R.mode=25;case 25:if(Se===0)break e;if(Be=De-Se,R.offset>Be){if((Be=R.offset-Be)>R.whave&&R.sane){ee.msg="invalid distance too far back",R.mode=30;break}We=Be>R.wnext?(Be-=R.wnext,R.wsize-Be):R.wnext-Be,Be>R.length&&(Be=R.length),ot=R.window}else ot=Qe,We=Q-R.offset,Be=R.length;for(Sej?(Y=We[ot+P[ye]],me[Ke+P[ye]]):(Y=96,0),x=1<>Q)+(I-=x)]=D<<24|Y<<16|de|0,I!==0;);for(x=1<>=1;if(x!==0?(X&=x-1,X+=x):X=0,ye++,--De[ee]==0){if(ee===Me)break;ee=w[C+P[ye]]}if(Qe>>7)]}function Ke(te,we){te.pending_buf[te.pending++]=255&we,te.pending_buf[te.pending++]=we>>>8&255}function De(te,we,B){te.bi_valid>y-B?(te.bi_buf|=we<>y-te.bi_valid,te.bi_valid+=B-y):(te.bi_buf|=we<>>=1,B<<=1,0<--we;);return B>>>1}function ot(te,we,B){var J,L,ue=new Array(P+1),le=0;for(J=1;J<=P;J++)ue[J]=le=le+B[J-1]<<1;for(L=0;L<=we;L++){var ke=te[2*L+1];ke!==0&&(te[2*L]=We(ue[ke]++,ke))}}function dt(te){var we;for(we=0;we>1;1<=B;B--)je(te,ue,B);for(L=Ne;B=te.heap[1],te.heap[1]=te.heap[te.heap_len--],je(te,ue,1),J=te.heap[1],te.heap[--te.heap_max]=B,te.heap[--te.heap_max]=J,ue[2*L]=ue[2*B]+ue[2*J],te.depth[L]=(te.depth[B]>=te.depth[J]?te.depth[B]:te.depth[J])+1,ue[2*B+1]=ue[2*J+1]=L,te.heap[1]=L++,je(te,ue,1),2<=te.heap_len;);te.heap[--te.heap_max]=te.heap[1],function(Je,Ve){var Z,ve,Re,He,Xe,rt,ft=Ve.dyn_tree,ht=Ve.max_code,Mt=Ve.stat_desc.static_tree,wt=Ve.stat_desc.has_stree,St=Ve.stat_desc.extra_bits,Rt=Ve.stat_desc.extra_base,at=Ve.stat_desc.max_length,Ot=0;for(He=0;He<=P;He++)Je.bl_count[He]=0;for(ft[2*Je.heap[Je.heap_max]+1]=0,Z=Je.heap_max+1;Z>=7;L>>=1)if(1&ut&&ke.dyn_ltree[2*Ne]!==0)return f;if(ke.dyn_ltree[18]!==0||ke.dyn_ltree[20]!==0||ke.dyn_ltree[26]!==0)return _;for(Ne=32;Ne>>3,(ue=te.static_len+3+7>>>3)<=L&&(L=ue)):L=ue=B+5,B+4<=L&&we!==-1?se(te,we,B,J):te.strategy===4||ue===L?(De(te,2+(J?1:0),3),Ye(te,Ce,ee)):(De(te,4+(J?1:0),3),function(ke,Ne,ut,Je){var Ve;for(De(ke,Ne-257,5),De(ke,ut-1,5),De(ke,Je-4,4),Ve=0;Ve>>8&255,te.pending_buf[te.d_buf+2*te.last_lit+1]=255&we,te.pending_buf[te.l_buf+te.last_lit]=255&B,te.last_lit++,we===0?te.dyn_ltree[2*B]++:(te.matches++,we--,te.dyn_ltree[2*(R[B]+w+1)]++,te.dyn_dtree[2*me(we)]++),te.last_lit===te.lit_bufsize-1},a._tr_align=function(te){De(te,2,3),Be(te,I,Ce),function(we){we.bi_valid===16?(Ke(we,we.bi_buf),we.bi_buf=0,we.bi_valid=0):8<=we.bi_valid&&(we.pending_buf[we.pending++]=255&we.bi_buf,we.bi_buf>>=8,we.bi_valid-=8)}(te)}},{"../utils/common":41}],53:[function(n,o,a){o.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],54:[function(n,o,a){(function(l){(function(f,_){if(!f.setImmediate){var h,g,M,w,C=1,k={},z=!1,S=f.document,P=Object.getPrototypeOf&&Object.getPrototypeOf(f);P=P&&P.setTimeout?P:f,h={}.toString.call(f.process)==="[object process]"?function(U){process.nextTick(function(){x(U)})}:function(){if(f.postMessage&&!f.importScripts){var U=!0,O=f.onmessage;return f.onmessage=function(){U=!1},f.postMessage("","*"),f.onmessage=O,U}}()?(w="setImmediate$"+Math.random()+"$",f.addEventListener?f.addEventListener("message",I,!1):f.attachEvent("onmessage",I),function(U){f.postMessage(w+U,"*")}):f.MessageChannel?((M=new MessageChannel).port1.onmessage=function(U){x(U.data)},function(U){M.port2.postMessage(U)}):S&&"onreadystatechange"in S.createElement("script")?(g=S.documentElement,function(U){var O=S.createElement("script");O.onreadystatechange=function(){x(U),O.onreadystatechange=null,g.removeChild(O),O=null},g.appendChild(O)}):function(U){setTimeout(x,0,U)},P.setImmediate=function(U){typeof U!="function"&&(U=new Function(""+U));for(var O=new Array(arguments.length-1),N=0;N"u"?l===void 0?this:l:self)}).call(this,typeof So<"u"?So:typeof self<"u"?self:typeof window<"u"?window:{})},{}]},{},[10])(10)})})(Y2);var cE=Y2.exports;const dE=b_(cE);var Z2={exports:{}};(function(e,t){(function(n,o){o()})(So,function(){function n(g,M){return typeof M>"u"?M={autoBom:!1}:typeof M!="object"&&(console.warn("Deprecated: Expected third argument to be a object"),M={autoBom:!M}),M.autoBom&&/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(g.type)?new Blob(["\uFEFF",g],{type:g.type}):g}function o(g,M,w){var C=new XMLHttpRequest;C.open("GET",g),C.responseType="blob",C.onload=function(){h(C.response,M,w)},C.onerror=function(){console.error("could not download file")},C.send()}function a(g){var M=new XMLHttpRequest;M.open("HEAD",g,!1);try{M.send()}catch{}return 200<=M.status&&299>=M.status}function l(g){try{g.dispatchEvent(new MouseEvent("click"))}catch{var M=document.createEvent("MouseEvents");M.initMouseEvent("click",!0,!0,window,0,0,0,80,20,!1,!1,!1,!1,0,null),g.dispatchEvent(M)}}var f=typeof window=="object"&&window.window===window?window:typeof self=="object"&&self.self===self?self:typeof So=="object"&&So.global===So?So:void 0,_=f.navigator&&/Macintosh/.test(navigator.userAgent)&&/AppleWebKit/.test(navigator.userAgent)&&!/Safari/.test(navigator.userAgent),h=f.saveAs||(typeof window!="object"||window!==f?function(){}:"download"in HTMLAnchorElement.prototype&&!_?function(g,M,w){var C=f.URL||f.webkitURL,k=document.createElement("a");M=M||g.name||"download",k.download=M,k.rel="noopener",typeof g=="string"?(k.href=g,k.origin===location.origin?l(k):a(k.href)?o(g,M,w):l(k,k.target="_blank")):(k.href=C.createObjectURL(g),setTimeout(function(){C.revokeObjectURL(k.href)},4e4),setTimeout(function(){l(k)},0))}:"msSaveOrOpenBlob"in navigator?function(g,M,w){if(M=M||g.name||"download",typeof g!="string")navigator.msSaveOrOpenBlob(n(g,w),M);else if(a(g))o(g,M,w);else{var C=document.createElement("a");C.href=g,C.target="_blank",setTimeout(function(){l(C)})}}:function(g,M,w,C){if(C=C||open("","_blank"),C&&(C.document.title=C.document.body.innerText="downloading..."),typeof g=="string")return o(g,M,w);var k=g.type==="application/octet-stream",z=/constructor/i.test(f.HTMLElement)||f.safari,S=/CriOS\/[\d]+/.test(navigator.userAgent);if((S||k&&z||_)&&typeof FileReader<"u"){var P=new FileReader;P.onloadend=function(){var I=P.result;I=S?I:I.replace(/^data:[^;]*;/,"data:attachment/file;"),C?C.location.href=I:location=I,C=null},P.readAsDataURL(g)}else{var y=f.URL||f.webkitURL,x=y.createObjectURL(g);C?C.location=x:location.href=x,C=null,setTimeout(function(){y.revokeObjectURL(x)},4e4)}});f.saveAs=h.saveAs=h,e.exports=h})})(Z2);var fE=Z2.exports;function pE(){const[e,t]=hr.useState([]),[n,o]=hr.useState([]),[a,l]=hr.useState(!1),[f,_]=hr.useState(!1),[h,g]=hr.useState(!0),M=hr.useRef(null),w=hr.useRef(null);hr.useEffect(()=>{(async()=>{const D="Xenova/modnet";uE.backends.onnx.wasm.proxy=!1,M.current??(M.current=await aE.from_pretrained(D,{device:"webgpu"})),w.current??(w.current=await lE.from_pretrained(D)),g(!1)})()},[]);const C=hr.useCallback(D=>{t(Y=>[...Y,...D.map(de=>URL.createObjectURL(de))])},[]),{getRootProps:k,getInputProps:z,isDragActive:S,isDragAccept:P,isDragReject:y}=H2({onDrop:C,accept:{"image/*":[".jpeg",".jpg",".png"]}}),x=D=>{t(Y=>Y.filter((de,Ce)=>Ce!==D)),o(Y=>Y.filter((de,Ce)=>Ce!==D))},I=async()=>{l(!0),o([]);const D=M.current,Y=w.current;for(let de=0;de[...Q,Me.toDataURL("image/png")])}l(!1),_(!0)},U=async()=>{const D=new dE;for(let de=0;de{ye.onload=()=>{Ce.width=ye.width,Ce.height=ye.height,ee.drawImage(ye,0,0),Ce.toBlob(Me=>{Me&&D.file(`image${de+1}.png`,Me),R(null)},"image/png")}})}const Y=await D.generateAsync({type:"blob"});fE.saveAs(Y,"images.zip")},O=()=>{t([]),o([]),_(!1)},N=async D=>{try{const de=await(await fetch(D)).blob(),Ce=new ClipboardItem({[de.type]:de});await navigator.clipboard.write([Ce]),console.log("Image copied to clipboard")}catch(Y){console.error("Failed to copy image: ",Y)}},j=D=>{const Y=document.createElement("a");Y.href=D,Y.download="image.png",document.body.appendChild(Y),Y.click(),document.body.removeChild(Y)};return h?Vr.jsx("div",{className:"min-h-screen bg-black text-white flex items-center justify-center",children:Vr.jsxs("div",{className:"text-center",children:[Vr.jsx("div",{className:"inline-block animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-white mb-4"}),Vr.jsx("p",{className:"text-lg",children:"Loading background removal model..."})]})}):Vr.jsx("div",{className:"min-h-screen bg-black text-white p-8",children:Vr.jsxs("div",{className:"max-w-4xl mx-auto",children:[Vr.jsx("h1",{className:"text-4xl font-bold mb-2 text-center",children:"Remove Background WebGPU"}),Vr.jsxs("h2",{className:"text-lg font-semibold mb-8 text-center",children:["In-browser background removal, powered by"," ",Vr.jsx("a",{className:"underline",target:"_blank",href:"https://github.com/xenova/transformers.js",children:"🤗 Transformers.js"})]}),Vr.jsxs("div",{...k(),className:`p-8 mb-8 border-2 border-dashed rounded-lg text-center cursor-pointer transition-colors duration-300 ease-in-out + ${P?"border-green-500 bg-green-900/20":""} + ${y?"border-red-500 bg-red-900/20":""} + ${S?"border-blue-500 bg-blue-900/20":"border-gray-700 hover:border-blue-500 hover:bg-blue-900/10"} + `,children:[Vr.jsx("input",{...z(),className:"hidden"}),Vr.jsx("p",{className:"text-lg mb-2",children:S?"Drop the images here...":"Drag and drop some images here"}),Vr.jsx("p",{className:"text-sm text-gray-400",children:"or click to select files"})]}),Vr.jsxs("div",{className:"flex flex-col items-center gap-4 mb-8",children:[Vr.jsx("button",{onClick:I,disabled:a||e.length===0,className:"px-6 py-3 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 focus:ring-offset-black disabled:bg-gray-700 disabled:cursor-not-allowed transition-colors duration-200 text-lg font-semibold",children:a?"Processing...":"Process"}),Vr.jsxs("div",{className:"flex gap-4",children:[Vr.jsx("button",{onClick:U,disabled:!f,className:"px-3 py-1 bg-green-600 text-white rounded-md hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-green-500 focus:ring-offset-2 focus:ring-offset-black disabled:bg-gray-700 disabled:cursor-not-allowed transition-colors duration-200 text-sm",children:"Download as ZIP"}),Vr.jsx("button",{onClick:O,className:"px-3 py-1 bg-red-600 text-white rounded-md hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-offset-2 focus:ring-offset-black transition-colors duration-200 text-sm",children:"Clear All"})]})]}),Vr.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6",children:e.map((D,Y)=>Vr.jsxs("div",{className:"relative group",children:[Vr.jsx("img",{src:n[Y]||D,alt:`Image ${Y+1}`,className:"rounded-lg object-cover w-full h-48"}),n[Y]&&Vr.jsxs("div",{className:"absolute inset-0 bg-black bg-opacity-70 opacity-0 group-hover:opacity-100 transition-opacity duration-300 rounded-lg flex items-center justify-center",children:[Vr.jsx("button",{onClick:()=>N(n[Y]||D),className:"mx-2 px-3 py-1 bg-white text-gray-900 rounded-md hover:bg-gray-200 transition-colors duration-200 text-sm","aria-label":`Copy image ${Y+1} to clipboard`,children:"Copy"}),Vr.jsx("button",{onClick:()=>j(n[Y]||D),className:"mx-2 px-3 py-1 bg-white text-gray-900 rounded-md hover:bg-gray-200 transition-colors duration-200 text-sm","aria-label":`Download image ${Y+1}`,children:"Download"})]}),Vr.jsx("button",{onClick:()=>x(Y),className:"absolute top-2 right-2 bg-black bg-opacity-50 text-white w-6 h-6 rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity duration-300 hover:bg-opacity-70","aria-label":`Remove image ${Y+1}`,children:"✕"})]},Y))})]})})}F2(document.getElementById("root")).render(Vr.jsx(hr.StrictMode,{children:Vr.jsx(pE,{})}));