diff --git "a/assets/index-B4bwwfKQ.js" "b/assets/index-B4bwwfKQ.js" new file mode 100644--- /dev/null +++ "b/assets/index-B4bwwfKQ.js" @@ -0,0 +1,2651 @@ +var DM=Object.defineProperty;var LM=(e,t,r)=>t in e?DM(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var He=(e,t,r)=>LM(e,typeof t!="symbol"?t+"":t,r);(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 p of l.addedNodes)p.tagName==="LINK"&&p.rel==="modulepreload"&&o(p)}).observe(document,{childList:!0,subtree:!0});function r(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=r(a);fetch(a.href,l)}})();var Co=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function k_(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var k1={exports:{}},Jh={},S1={exports:{}},kr={};/** + * @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 Qp=Symbol.for("react.element"),RM=Symbol.for("react.portal"),BM=Symbol.for("react.fragment"),NM=Symbol.for("react.strict_mode"),jM=Symbol.for("react.profiler"),UM=Symbol.for("react.provider"),VM=Symbol.for("react.context"),WM=Symbol.for("react.forward_ref"),GM=Symbol.for("react.suspense"),HM=Symbol.for("react.memo"),qM=Symbol.for("react.lazy"),rv=Symbol.iterator;function KM(e){return e===null||typeof e!="object"?null:(e=rv&&e[rv]||e["@@iterator"],typeof e=="function"?e:null)}var E1={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},C1=Object.assign,P1={};function ou(e,t,r){this.props=e,this.context=t,this.refs=P1,this.updater=r||E1}ou.prototype.isReactComponent={};ou.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")};ou.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function $1(){}$1.prototype=ou.prototype;function S_(e,t,r){this.props=e,this.context=t,this.refs=P1,this.updater=r||E1}var E_=S_.prototype=new $1;E_.constructor=S_;C1(E_,ou.prototype);E_.isPureReactComponent=!0;var nv=Array.isArray,A1=Object.prototype.hasOwnProperty,C_={current:null},I1={key:!0,ref:!0,__self:!0,__source:!0};function F1(e,t,r){var o,a={},l=null,p=null;if(t!=null)for(o in t.ref!==void 0&&(p=t.ref),t.key!==void 0&&(l=""+t.key),t)A1.call(t,o)&&!I1.hasOwnProperty(o)&&(a[o]=t[o]);var _=arguments.length-2;if(_===1)a.children=r;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:Qp,type:e,key:l,ref:p,props:a,_owner:C_.current}}function XM(e,t){return{$$typeof:Qp,type:e.type,key:t,ref:e.ref,props:e.props,_owner:e._owner}}function P_(e){return typeof e=="object"&&e!==null&&e.$$typeof===Qp}function QM(e){var t={"=":"=0",":":"=2"};return"$"+e.replace(/[=:]/g,function(r){return t[r]})}var iv=/\/+/g;function tg(e,t){return typeof e=="object"&&e!==null&&e.key!=null?QM(""+e.key):t.toString(36)}function fh(e,t,r,o,a){var l=typeof e;(l==="undefined"||l==="boolean")&&(e=null);var p=!1;if(e===null)p=!0;else switch(l){case"string":case"number":p=!0;break;case"object":switch(e.$$typeof){case Qp:case RM:p=!0}}if(p)return p=e,a=a(p),e=o===""?"."+tg(p,0):o,nv(a)?(r="",e!=null&&(r=e.replace(iv,"$&/")+"/"),fh(a,t,r,"",function(g){return g})):a!=null&&(P_(a)&&(a=XM(a,r+(!a.key||p&&p.key===a.key?"":(""+a.key).replace(iv,"$&/")+"/")+e)),t.push(a)),1;if(p=0,o=o===""?".":o+":",nv(e))for(var _=0;_>>1,ge=X[Q];if(0>>1;Qa(Be,Me))Wea(st,Be)?(X[Q]=st,X[We]=Me,Q=We):(X[Q]=Be,X[Le]=Me,Q=Le);else if(Wea(st,Me))X[Q]=st,X[We]=Me,Q=We;else break e}}return ie}function a(X,ie){var Me=X.sortIndex-ie.sortIndex;return Me!==0?Me:X.id-ie.id}if(typeof performance=="object"&&typeof performance.now=="function"){var l=performance;e.unstable_now=function(){return l.now()}}else{var p=Date,_=p.now();e.unstable_now=function(){return p.now()-_}}var h=[],g=[],M=1,y=null,E=3,T=!1,O=!1,S=!1,C=typeof setTimeout=="function"?setTimeout:null,w=typeof clearTimeout=="function"?clearTimeout:null,b=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(X){for(var ie=r(g);ie!==null;){if(ie.callback===null)o(g);else if(ie.startTime<=X)o(g),ie.sortIndex=ie.expirationTime,t(h,ie);else break;ie=r(g)}}function U(X){if(S=!1,I(X),!O)if(r(h)!==null)O=!0,Xe(z);else{var ie=r(g);ie!==null&&me(U,ie.startTime-X)}}function z(X,ie){O=!1,S&&(S=!1,w(N),N=-1),T=!0;var Me=E;try{for(I(ie),y=r(h);y!==null&&(!(y.expirationTime>ie)||X&&!xe());){var Q=y.callback;if(typeof Q=="function"){y.callback=null,E=y.priorityLevel;var ge=Q(y.expirationTime<=ie);ie=e.unstable_now(),typeof ge=="function"?y.callback=ge:y===r(h)&&o(h),I(ie)}else o(h);y=r(h)}if(y!==null)var Ke=!0;else{var Le=r(g);Le!==null&&me(U,Le.startTime-ie),Ke=!1}return Ke}finally{y=null,E=Me,T=!1}}var B=!1,j=null,N=-1,ae=5,ce=-1;function xe(){return!(e.unstable_now()-ceX||125Q?(X.sortIndex=Me,t(g,X),r(h)===null&&X===r(g)&&(S?(w(N),N=-1):S=!0,me(U,Me-Q))):(X.sortIndex=ge,t(h,X),O||T||(O=!0,Xe(z))),X},e.unstable_shouldYield=xe,e.unstable_wrapCallback=function(X){var ie=E;return function(){var Me=E;E=ie;try{return X.apply(this,arguments)}finally{E=Me}}}})(R1);L1.exports=R1;var sT=L1.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 aT=fr,vi=sT;function xt(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,r=1;r"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),Cg=Object.prototype.hasOwnProperty,lT=/^[: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]*$/,ov={},sv={};function uT(e){return Cg.call(sv,e)?!0:Cg.call(ov,e)?!1:lT.test(e)?sv[e]=!0:(ov[e]=!0,!1)}function cT(e,t,r,o){if(r!==null&&r.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return o?!1:r!==null?!r.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function dT(e,t,r,o){if(t===null||typeof t>"u"||cT(e,t,r,o))return!0;if(o)return!1;if(r!==null)switch(r.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function ni(e,t,r,o,a,l,p){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=o,this.attributeNamespace=a,this.mustUseProperty=r,this.propertyName=e,this.type=t,this.sanitizeURL=l,this.removeEmptyString=p}var Nn={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){Nn[e]=new ni(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];Nn[t]=new ni(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){Nn[e]=new ni(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){Nn[e]=new ni(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){Nn[e]=new ni(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){Nn[e]=new ni(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){Nn[e]=new ni(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){Nn[e]=new ni(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){Nn[e]=new ni(e,5,!1,e.toLowerCase(),null,!1,!1)});var $_=/[\-:]([a-z])/g;function A_(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($_,A_);Nn[t]=new ni(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($_,A_);Nn[t]=new ni(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($_,A_);Nn[t]=new ni(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){Nn[e]=new ni(e,1,!1,e.toLowerCase(),null,!1,!1)});Nn.xlinkHref=new ni("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){Nn[e]=new ni(e,1,!1,e.toLowerCase(),null,!0,!0)});function I_(e,t,r,o){var a=Nn.hasOwnProperty(t)?Nn[t]:null;(a!==null?a.type!==0:o||!(2_||a[p]!==l[_]){var h=` +`+a[p].replace(" at new "," at ");return e.displayName&&h.includes("")&&(h=h.replace("",e.displayName)),h}while(1<=p&&0<=_);break}}}finally{ng=!1,Error.prepareStackTrace=r}return(e=e?e.displayName||e.name:"")?wp(e):""}function pT(e){switch(e.tag){case 5:return wp(e.type);case 16:return wp("Lazy");case 13:return wp("Suspense");case 19:return wp("SuspenseList");case 0:case 2:case 15:return e=ig(e.type,!1),e;case 11:return e=ig(e.type.render,!1),e;case 1:return e=ig(e.type,!0),e;default:return""}}function Ig(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 zl:return"Fragment";case Ol:return"Portal";case Pg:return"Profiler";case F_:return"StrictMode";case $g:return"Suspense";case Ag:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case j1:return(e.displayName||"Context")+".Consumer";case N1:return(e._context.displayName||"Context")+".Provider";case O_:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case z_:return t=e.displayName||null,t!==null?t:Ig(e.type)||"Memo";case us:t=e._payload,e=e._init;try{return Ig(e(t))}catch{}}return null}function fT(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 Ig(t);case 8:return t===F_?"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 Ms(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function V1(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function hT(e){var t=V1(e)?"checked":"value",r=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),o=""+e[t];if(!e.hasOwnProperty(t)&&typeof r<"u"&&typeof r.get=="function"&&typeof r.set=="function"){var a=r.get,l=r.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return a.call(this)},set:function(p){o=""+p,l.call(this,p)}}),Object.defineProperty(e,t,{enumerable:r.enumerable}),{getValue:function(){return o},setValue:function(p){o=""+p},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function Qf(e){e._valueTracker||(e._valueTracker=hT(e))}function W1(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var r=t.getValue(),o="";return e&&(o=V1(e)?e.checked?"true":"false":e.value),e=o,e!==r?(t.setValue(e),!0):!1}function Sh(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function Fg(e,t){var r=t.checked;return ln({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:r??e._wrapperState.initialChecked})}function lv(e,t){var r=t.defaultValue==null?"":t.defaultValue,o=t.checked!=null?t.checked:t.defaultChecked;r=Ms(t.value!=null?t.value:r),e._wrapperState={initialChecked:o,initialValue:r,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function G1(e,t){t=t.checked,t!=null&&I_(e,"checked",t,!1)}function Og(e,t){G1(e,t);var r=Ms(t.value),o=t.type;if(r!=null)o==="number"?(r===0&&e.value===""||e.value!=r)&&(e.value=""+r):e.value!==""+r&&(e.value=""+r);else if(o==="submit"||o==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?zg(e,t.type,r):t.hasOwnProperty("defaultValue")&&zg(e,t.type,Ms(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function uv(e,t,r){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,r||t===e.value||(e.value=t),e.defaultValue=t}r=e.name,r!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,r!==""&&(e.name=r)}function zg(e,t,r){(t!=="number"||Sh(e.ownerDocument)!==e)&&(r==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+r&&(e.defaultValue=""+r))}var yp=Array.isArray;function Hl(e,t,r,o){if(e=e.options,t){t={};for(var a=0;a"+t.valueOf().toString()+"",t=Yf.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function Fp(e,t){if(t){var r=e.firstChild;if(r&&r===e.lastChild&&r.nodeType===3){r.nodeValue=t;return}}e.textContent=t}var Mp={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},mT=["Webkit","ms","Moz","O"];Object.keys(Mp).forEach(function(e){mT.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),Mp[t]=Mp[e]})});function X1(e,t,r){return t==null||typeof t=="boolean"||t===""?"":r||typeof t!="number"||t===0||Mp.hasOwnProperty(e)&&Mp[e]?(""+t).trim():t+"px"}function Q1(e,t){e=e.style;for(var r in t)if(t.hasOwnProperty(r)){var o=r.indexOf("--")===0,a=X1(r,t[r],o);r==="float"&&(r="cssFloat"),o?e.setProperty(r,a):e[r]=a}}var gT=ln({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 Rg(e,t){if(t){if(gT[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(xt(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(xt(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(xt(61))}if(t.style!=null&&typeof t.style!="object")throw Error(xt(62))}}function Bg(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 Ng=null;function D_(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var jg=null,ql=null,Kl=null;function pv(e){if(e=Jp(e)){if(typeof jg!="function")throw Error(xt(280));var t=e.stateNode;t&&(t=im(t),jg(e.stateNode,e.type,t))}}function Y1(e){ql?Kl?Kl.push(e):Kl=[e]:ql=e}function Z1(){if(ql){var e=ql,t=Kl;if(Kl=ql=null,pv(e),t)for(e=0;e>>=0,e===0?32:31-(ET(e)/CT|0)|0}var Zf=64,Jf=4194304;function vp(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 $h(e,t){var r=e.pendingLanes;if(r===0)return 0;var o=0,a=e.suspendedLanes,l=e.pingedLanes,p=r&268435455;if(p!==0){var _=p&~a;_!==0?o=vp(_):(l&=p,l!==0&&(o=vp(l)))}else p=r&~a,p!==0?o=vp(p):l!==0&&(o=vp(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|=r&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=o;0r;r++)t.push(e);return t}function Yp(e,t,r){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-Qi(t),e[t]=r}function IT(e,t){var r=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var o=e.eventTimes;for(e=e.expirationTimes;0=kp),bv=" ",xv=!1;function wb(e,t){switch(e){case"keyup":return sk.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function yb(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var Dl=!1;function lk(e,t){switch(e){case"compositionend":return yb(t);case"keypress":return t.which!==32?null:(xv=!0,bv);case"textInput":return e=t.data,e===bv&&xv?null:e;default:return null}}function uk(e,t){if(Dl)return e==="compositionend"||!W_&&wb(e,t)?(e=gb(),gh=j_=fs=null,Dl=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:r,offset:t-e};e=o}e:{for(;r;){if(r.nextSibling){r=r.nextSibling;break e}r=r.parentNode}r=void 0}r=Sv(r)}}function Mb(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?Mb(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function Tb(){for(var e=window,t=Sh();t instanceof e.HTMLIFrameElement;){try{var r=typeof t.contentWindow.location.href=="string"}catch{r=!1}if(r)e=t.contentWindow;else break;t=Sh(e.document)}return t}function G_(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 wk(e){var t=Tb(),r=e.focusedElem,o=e.selectionRange;if(t!==r&&r&&r.ownerDocument&&Mb(r.ownerDocument.documentElement,r)){if(o!==null&&G_(r)){if(t=o.start,e=o.end,e===void 0&&(e=t),"selectionStart"in r)r.selectionStart=t,r.selectionEnd=Math.min(e,r.value.length);else if(e=(t=r.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var a=r.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=Ev(r,l);var p=Ev(r,o);a&&p&&(e.rangeCount!==1||e.anchorNode!==a.node||e.anchorOffset!==a.offset||e.focusNode!==p.node||e.focusOffset!==p.offset)&&(t=t.createRange(),t.setStart(a.node,a.offset),e.removeAllRanges(),l>o?(e.addRange(t),e.extend(p.node,p.offset)):(t.setEnd(p.node,p.offset),e.addRange(t)))}}for(t=[],e=r;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof r.focus=="function"&&r.focus(),r=0;r=document.documentMode,Ll=null,qg=null,Ep=null,Kg=!1;function Cv(e,t,r){var o=r.window===r?r.document:r.nodeType===9?r:r.ownerDocument;Kg||Ll==null||Ll!==Sh(o)||(o=Ll,"selectionStart"in o&&G_(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}),Ep&&Bp(Ep,o)||(Ep=o,o=Fh(qg,"onSelect"),0Nl||(e.current=e_[Nl],e_[Nl]=null,Nl--)}function Qr(e,t){Nl++,e_[Nl]=e.current,e.current=t}var Ts={},qn=Ss(Ts),ui=Ss(!1),la=Ts;function Jl(e,t){var r=e.type.contextTypes;if(!r)return Ts;var o=e.stateNode;if(o&&o.__reactInternalMemoizedUnmaskedChildContext===t)return o.__reactInternalMemoizedMaskedChildContext;var a={},l;for(l in r)a[l]=t[l];return o&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=a),a}function ci(e){return e=e.childContextTypes,e!=null}function zh(){tn(ui),tn(qn)}function zv(e,t,r){if(qn.current!==Ts)throw Error(xt(168));Qr(qn,t),Qr(ui,r)}function Fb(e,t,r){var o=e.stateNode;if(t=t.childContextTypes,typeof o.getChildContext!="function")return r;o=o.getChildContext();for(var a in o)if(!(a in t))throw Error(xt(108,fT(e)||"Unknown",a));return ln({},r,o)}function Dh(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||Ts,la=qn.current,Qr(qn,e),Qr(ui,ui.current),!0}function Dv(e,t,r){var o=e.stateNode;if(!o)throw Error(xt(169));r?(e=Fb(e,t,la),o.__reactInternalMemoizedMergedChildContext=e,tn(ui),tn(qn),Qr(qn,e)):tn(ui),Qr(ui,r)}var Eo=null,om=!1,wg=!1;function Ob(e){Eo===null?Eo=[e]:Eo.push(e)}function $k(e){om=!0,Ob(e)}function Es(){if(!wg&&Eo!==null){wg=!0;var e=0,t=Ur;try{var r=Eo;for(Ur=1;e>=p,a-=p,Po=1<<32-Qi(t)+a|r<N?(ae=j,j=null):ae=j.sibling;var ce=E(w,j,I[N],U);if(ce===null){j===null&&(j=ae);break}e&&j&&ce.alternate===null&&t(w,j),b=l(ce,b,N),B===null?z=ce:B.sibling=ce,B=ce,j=ae}if(N===I.length)return r(w,j),nn&&ea(w,N),z;if(j===null){for(;NN?(ae=j,j=null):ae=j.sibling;var xe=E(w,j,ce.value,U);if(xe===null){j===null&&(j=ae);break}e&&j&&xe.alternate===null&&t(w,j),b=l(xe,b,N),B===null?z=xe:B.sibling=xe,B=xe,j=ae}if(ce.done)return r(w,j),nn&&ea(w,N),z;if(j===null){for(;!ce.done;N++,ce=I.next())ce=y(w,ce.value,U),ce!==null&&(b=l(ce,b,N),B===null?z=ce:B.sibling=ce,B=ce);return nn&&ea(w,N),z}for(j=o(w,j);!ce.done;N++,ce=I.next())ce=T(j,w,N,ce.value,U),ce!==null&&(e&&ce.alternate!==null&&j.delete(ce.key===null?N:ce.key),b=l(ce,b,N),B===null?z=ce:B.sibling=ce,B=ce);return e&&j.forEach(function(Y){return t(w,Y)}),nn&&ea(w,N),z}function C(w,b,I,U){if(typeof I=="object"&&I!==null&&I.type===zl&&I.key===null&&(I=I.props.children),typeof I=="object"&&I!==null){switch(I.$$typeof){case Xf:e:{for(var z=I.key,B=b;B!==null;){if(B.key===z){if(z=I.type,z===zl){if(B.tag===7){r(w,B.sibling),b=a(B,I.props.children),b.return=w,w=b;break e}}else if(B.elementType===z||typeof z=="object"&&z!==null&&z.$$typeof===us&&Bv(z)===B.type){r(w,B.sibling),b=a(B,I.props),b.ref=mp(w,B,I),b.return=w,w=b;break e}r(w,B);break}else t(w,B);B=B.sibling}I.type===zl?(b=aa(I.props.children,w.mode,U,I.key),b.return=w,w=b):(U=Th(I.type,I.key,I.props,null,w.mode,U),U.ref=mp(w,b,I),U.return=w,w=U)}return p(w);case Ol:e:{for(B=I.key;b!==null;){if(b.key===B)if(b.tag===4&&b.stateNode.containerInfo===I.containerInfo&&b.stateNode.implementation===I.implementation){r(w,b.sibling),b=a(b,I.children||[]),b.return=w,w=b;break e}else{r(w,b);break}else t(w,b);b=b.sibling}b=Sg(I,w.mode,U),b.return=w,w=b}return p(w);case us:return B=I._init,C(w,b,B(I._payload),U)}if(yp(I))return O(w,b,I,U);if(cp(I))return S(w,b,I,U);sh(w,I)}return typeof I=="string"&&I!==""||typeof I=="number"?(I=""+I,b!==null&&b.tag===6?(r(w,b.sibling),b=a(b,I),b.return=w,w=b):(r(w,b),b=kg(I,w.mode,U),b.return=w,w=b),p(w)):r(w,b)}return C}var tu=Rb(!0),Bb=Rb(!1),Bh=Ss(null),Nh=null,Vl=null,X_=null;function Q_(){X_=Vl=Nh=null}function Y_(e){var t=Bh.current;tn(Bh),e._currentValue=t}function n_(e,t,r){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===r)break;e=e.return}}function Ql(e,t){Nh=e,X_=Vl=null,e=e.dependencies,e!==null&&e.firstContext!==null&&(e.lanes&t&&(li=!0),e.firstContext=null)}function Li(e){var t=e._currentValue;if(X_!==e)if(e={context:e,memoizedValue:t,next:null},Vl===null){if(Nh===null)throw Error(xt(308));Vl=e,Nh.dependencies={lanes:0,firstContext:e}}else Vl=Vl.next=e;return t}var ia=null;function Z_(e){ia===null?ia=[e]:ia.push(e)}function Nb(e,t,r,o){var a=t.interleaved;return a===null?(r.next=r,Z_(t)):(r.next=a.next,a.next=r),t.interleaved=r,Oo(e,o)}function Oo(e,t){e.lanes|=t;var r=e.alternate;for(r!==null&&(r.lanes|=t),r=e,e=e.return;e!==null;)e.childLanes|=t,r=e.alternate,r!==null&&(r.childLanes|=t),r=e,e=e.return;return r.tag===3?r.stateNode:null}var cs=!1;function J_(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function jb(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 Ao(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function ys(e,t,r){var o=e.updateQueue;if(o===null)return null;if(o=o.shared,zr&2){var a=o.pending;return a===null?t.next=t:(t.next=a.next,a.next=t),o.pending=t,Oo(e,r)}return a=o.interleaved,a===null?(t.next=t,Z_(o)):(t.next=a.next,a.next=t),o.interleaved=t,Oo(e,r)}function wh(e,t,r){if(t=t.updateQueue,t!==null&&(t=t.shared,(r&4194240)!==0)){var o=t.lanes;o&=e.pendingLanes,r|=o,t.lanes=r,R_(e,r)}}function Nv(e,t){var r=e.updateQueue,o=e.alternate;if(o!==null&&(o=o.updateQueue,r===o)){var a=null,l=null;if(r=r.firstBaseUpdate,r!==null){do{var p={eventTime:r.eventTime,lane:r.lane,tag:r.tag,payload:r.payload,callback:r.callback,next:null};l===null?a=l=p:l=l.next=p,r=r.next}while(r!==null);l===null?a=l=t:l=l.next=t}else a=l=t;r={baseState:o.baseState,firstBaseUpdate:a,lastBaseUpdate:l,shared:o.shared,effects:o.effects},e.updateQueue=r;return}e=r.lastBaseUpdate,e===null?r.firstBaseUpdate=t:e.next=t,r.lastBaseUpdate=t}function jh(e,t,r,o){var a=e.updateQueue;cs=!1;var l=a.firstBaseUpdate,p=a.lastBaseUpdate,_=a.shared.pending;if(_!==null){a.shared.pending=null;var h=_,g=h.next;h.next=null,p===null?l=g:p.next=g,p=h;var M=e.alternate;M!==null&&(M=M.updateQueue,_=M.lastBaseUpdate,_!==p&&(_===null?M.firstBaseUpdate=g:_.next=g,M.lastBaseUpdate=h))}if(l!==null){var y=a.baseState;p=0,M=g=h=null,_=l;do{var E=_.lane,T=_.eventTime;if((o&E)===E){M!==null&&(M=M.next={eventTime:T,lane:0,tag:_.tag,payload:_.payload,callback:_.callback,next:null});e:{var O=e,S=_;switch(E=t,T=r,S.tag){case 1:if(O=S.payload,typeof O=="function"){y=O.call(T,y,E);break e}y=O;break e;case 3:O.flags=O.flags&-65537|128;case 0:if(O=S.payload,E=typeof O=="function"?O.call(T,y,E):O,E==null)break e;y=ln({},y,E);break e;case 2:cs=!0}}_.callback!==null&&_.lane!==0&&(e.flags|=64,E=a.effects,E===null?a.effects=[_]:E.push(_))}else T={eventTime:T,lane:E,tag:_.tag,payload:_.payload,callback:_.callback,next:null},M===null?(g=M=T,h=y):M=M.next=T,p|=E;if(_=_.next,_===null){if(_=a.shared.pending,_===null)break;E=_,_=E.next,E.next=null,a.lastBaseUpdate=E,a.shared.pending=null}}while(!0);if(M===null&&(h=y),a.baseState=h,a.firstBaseUpdate=g,a.lastBaseUpdate=M,t=a.shared.interleaved,t!==null){a=t;do p|=a.lane,a=a.next;while(a!==t)}else l===null&&(a.shared.lanes=0);da|=p,e.lanes=p,e.memoizedState=y}}function jv(e,t,r){if(e=t.effects,t.effects=null,e!==null)for(t=0;tr?r:4,e(!0);var o=vg.transition;vg.transition={};try{e(!1),t()}finally{Ur=r,vg.transition=o}}function i2(){return Ri().memoizedState}function Ok(e,t,r){var o=bs(e);if(r={lane:o,action:r,hasEagerState:!1,eagerState:null,next:null},o2(e))s2(t,r);else if(r=Nb(e,t,r,o),r!==null){var a=ti();Yi(r,e,o,a),a2(r,t,o)}}function zk(e,t,r){var o=bs(e),a={lane:o,action:r,hasEagerState:!1,eagerState:null,next:null};if(o2(e))s2(t,a);else{var l=e.alternate;if(e.lanes===0&&(l===null||l.lanes===0)&&(l=t.lastRenderedReducer,l!==null))try{var p=t.lastRenderedState,_=l(p,r);if(a.hasEagerState=!0,a.eagerState=_,Zi(_,p)){var h=t.interleaved;h===null?(a.next=a,Z_(t)):(a.next=h.next,h.next=a),t.interleaved=a;return}}catch{}finally{}r=Nb(e,t,a,o),r!==null&&(a=ti(),Yi(r,e,o,a),a2(r,t,o))}}function o2(e){var t=e.alternate;return e===an||t!==null&&t===an}function s2(e,t){Cp=Vh=!0;var r=e.pending;r===null?t.next=t:(t.next=r.next,r.next=t),e.pending=t}function a2(e,t,r){if(r&4194240){var o=t.lanes;o&=e.pendingLanes,r|=o,t.lanes=r,R_(e,r)}}var Wh={readContext:Li,useCallback:Wn,useContext:Wn,useEffect:Wn,useImperativeHandle:Wn,useInsertionEffect:Wn,useLayoutEffect:Wn,useMemo:Wn,useReducer:Wn,useRef:Wn,useState:Wn,useDebugValue:Wn,useDeferredValue:Wn,useTransition:Wn,useMutableSource:Wn,useSyncExternalStore:Wn,useId:Wn,unstable_isNewReconciler:!1},Dk={readContext:Li,useCallback:function(e,t){return lo().memoizedState=[e,t===void 0?null:t],e},useContext:Li,useEffect:Vv,useImperativeHandle:function(e,t,r){return r=r!=null?r.concat([e]):null,vh(4194308,4,Jb.bind(null,t,e),r)},useLayoutEffect:function(e,t){return vh(4194308,4,e,t)},useInsertionEffect:function(e,t){return vh(4,2,e,t)},useMemo:function(e,t){var r=lo();return t=t===void 0?null:t,e=e(),r.memoizedState=[e,t],e},useReducer:function(e,t,r){var o=lo();return t=r!==void 0?r(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=Ok.bind(null,an,e),[o.memoizedState,e]},useRef:function(e){var t=lo();return e={current:e},t.memoizedState=e},useState:Uv,useDebugValue:a0,useDeferredValue:function(e){return lo().memoizedState=e},useTransition:function(){var e=Uv(!1),t=e[0];return e=Fk.bind(null,e[1]),lo().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,r){var o=an,a=lo();if(nn){if(r===void 0)throw Error(xt(407));r=r()}else{if(r=t(),Fn===null)throw Error(xt(349));ca&30||Gb(o,t,r)}a.memoizedState=r;var l={value:r,getSnapshot:t};return a.queue=l,Vv(qb.bind(null,o,l,e),[e]),o.flags|=2048,qp(9,Hb.bind(null,o,l,r,t),void 0,null),r},useId:function(){var e=lo(),t=Fn.identifierPrefix;if(nn){var r=$o,o=Po;r=(o&~(1<<32-Qi(o)-1)).toString(32)+r,t=":"+t+"R"+r,r=Gp++,0<\/script>",e=e.removeChild(e.firstChild)):typeof o.is=="string"?e=p.createElement(r,{is:o.is}):(e=p.createElement(r),r==="select"&&(p=e,o.multiple?p.multiple=!0:o.size&&(p.size=o.size))):e=p.createElementNS(e,r),e[uo]=t,e[Up]=o,_2(e,t,!1,!1),t.stateNode=e;e:{switch(p=Bg(r,o),r){case"dialog":Jr("cancel",e),Jr("close",e),a=o;break;case"iframe":case"object":case"embed":Jr("load",e),a=o;break;case"video":case"audio":for(a=0;aiu&&(t.flags|=128,o=!0,gp(l,!1),t.lanes=4194304)}else{if(!o)if(e=Uh(p),e!==null){if(t.flags|=128,o=!0,r=e.updateQueue,r!==null&&(t.updateQueue=r,t.flags|=4),gp(l,!0),l.tail===null&&l.tailMode==="hidden"&&!p.alternate&&!nn)return Gn(t),null}else 2*mn()-l.renderingStartTime>iu&&r!==1073741824&&(t.flags|=128,o=!0,gp(l,!1),t.lanes=4194304);l.isBackwards?(p.sibling=t.child,t.child=p):(r=l.last,r!==null?r.sibling=p:t.child=p,l.last=p)}return l.tail!==null?(t=l.tail,l.rendering=t,l.tail=t.sibling,l.renderingStartTime=mn(),t.sibling=null,r=sn.current,Qr(sn,o?r&1|2:r&1),t):(Gn(t),null);case 22:case 23:return f0(),o=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==o&&(t.flags|=8192),o&&t.mode&1?_i&1073741824&&(Gn(t),t.subtreeFlags&6&&(t.flags|=8192)):Gn(t),null;case 24:return null;case 25:return null}throw Error(xt(156,t.tag))}function Wk(e,t){switch(q_(t),t.tag){case 1:return ci(t.type)&&zh(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return ru(),tn(ui),tn(qn),r0(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return t0(t),null;case 13:if(tn(sn),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(xt(340));eu()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return tn(sn),null;case 4:return ru(),null;case 10:return Y_(t.type._context),null;case 22:case 23:return f0(),null;case 24:return null;default:return null}}var lh=!1,Hn=!1,Gk=typeof WeakSet=="function"?WeakSet:Set,jt=null;function Wl(e,t){var r=e.ref;if(r!==null)if(typeof r=="function")try{r(null)}catch(o){fn(e,t,o)}else r.current=null}function p_(e,t,r){try{r()}catch(o){fn(e,t,o)}}var e1=!1;function Hk(e,t){if(Xg=Ah,e=Tb(),G_(e)){if("selectionStart"in e)var r={start:e.selectionStart,end:e.selectionEnd};else e:{r=(r=e.ownerDocument)&&r.defaultView||window;var o=r.getSelection&&r.getSelection();if(o&&o.rangeCount!==0){r=o.anchorNode;var a=o.anchorOffset,l=o.focusNode;o=o.focusOffset;try{r.nodeType,l.nodeType}catch{r=null;break e}var p=0,_=-1,h=-1,g=0,M=0,y=e,E=null;t:for(;;){for(var T;y!==r||a!==0&&y.nodeType!==3||(_=p+a),y!==l||o!==0&&y.nodeType!==3||(h=p+o),y.nodeType===3&&(p+=y.nodeValue.length),(T=y.firstChild)!==null;)E=y,y=T;for(;;){if(y===e)break t;if(E===r&&++g===a&&(_=p),E===l&&++M===o&&(h=p),(T=y.nextSibling)!==null)break;y=E,E=y.parentNode}y=T}r=_===-1||h===-1?null:{start:_,end:h}}else r=null}r=r||{start:0,end:0}}else r=null;for(Qg={focusedElem:e,selectionRange:r},Ah=!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 O=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(O!==null){var S=O.memoizedProps,C=O.memoizedState,w=t.stateNode,b=w.getSnapshotBeforeUpdate(t.elementType===t.type?S:qi(t.type,S),C);w.__reactInternalSnapshotBeforeUpdate=b}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(xt(163))}}catch(U){fn(t,t.return,U)}if(e=t.sibling,e!==null){e.return=t.return,jt=e;break}jt=t.return}return O=e1,e1=!1,O}function Pp(e,t,r){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&&p_(t,r,l)}a=a.next}while(a!==o)}}function lm(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var r=t=t.next;do{if((r.tag&e)===e){var o=r.create;r.destroy=o()}r=r.next}while(r!==t)}}function f_(e){var t=e.ref;if(t!==null){var r=e.stateNode;switch(e.tag){case 5:e=r;break;default:e=r}typeof t=="function"?t(e):t.current=e}}function v2(e){var t=e.alternate;t!==null&&(e.alternate=null,v2(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[uo],delete t[Up],delete t[Jg],delete t[Ck],delete t[Pk])),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 b2(e){return e.tag===5||e.tag===3||e.tag===4}function t1(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||b2(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 h_(e,t,r){var o=e.tag;if(o===5||o===6)e=e.stateNode,t?r.nodeType===8?r.parentNode.insertBefore(e,t):r.insertBefore(e,t):(r.nodeType===8?(t=r.parentNode,t.insertBefore(e,r)):(t=r,t.appendChild(e)),r=r._reactRootContainer,r!=null||t.onclick!==null||(t.onclick=Oh));else if(o!==4&&(e=e.child,e!==null))for(h_(e,t,r),e=e.sibling;e!==null;)h_(e,t,r),e=e.sibling}function m_(e,t,r){var o=e.tag;if(o===5||o===6)e=e.stateNode,t?r.insertBefore(e,t):r.appendChild(e);else if(o!==4&&(e=e.child,e!==null))for(m_(e,t,r),e=e.sibling;e!==null;)m_(e,t,r),e=e.sibling}var Rn=null,Ki=!1;function ls(e,t,r){for(r=r.child;r!==null;)x2(e,t,r),r=r.sibling}function x2(e,t,r){if(co&&typeof co.onCommitFiberUnmount=="function")try{co.onCommitFiberUnmount(em,r)}catch{}switch(r.tag){case 5:Hn||Wl(r,t);case 6:var o=Rn,a=Ki;Rn=null,ls(e,t,r),Rn=o,Ki=a,Rn!==null&&(Ki?(e=Rn,r=r.stateNode,e.nodeType===8?e.parentNode.removeChild(r):e.removeChild(r)):Rn.removeChild(r.stateNode));break;case 18:Rn!==null&&(Ki?(e=Rn,r=r.stateNode,e.nodeType===8?_g(e.parentNode,r):e.nodeType===1&&_g(e,r),Lp(e)):_g(Rn,r.stateNode));break;case 4:o=Rn,a=Ki,Rn=r.stateNode.containerInfo,Ki=!0,ls(e,t,r),Rn=o,Ki=a;break;case 0:case 11:case 14:case 15:if(!Hn&&(o=r.updateQueue,o!==null&&(o=o.lastEffect,o!==null))){a=o=o.next;do{var l=a,p=l.destroy;l=l.tag,p!==void 0&&(l&2||l&4)&&p_(r,t,p),a=a.next}while(a!==o)}ls(e,t,r);break;case 1:if(!Hn&&(Wl(r,t),o=r.stateNode,typeof o.componentWillUnmount=="function"))try{o.props=r.memoizedProps,o.state=r.memoizedState,o.componentWillUnmount()}catch(_){fn(r,t,_)}ls(e,t,r);break;case 21:ls(e,t,r);break;case 22:r.mode&1?(Hn=(o=Hn)||r.memoizedState!==null,ls(e,t,r),Hn=o):ls(e,t,r);break;default:ls(e,t,r)}}function r1(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var r=e.stateNode;r===null&&(r=e.stateNode=new Gk),t.forEach(function(o){var a=tS.bind(null,e,o);r.has(o)||(r.add(o),o.then(a,a))})}}function Hi(e,t){var r=t.deletions;if(r!==null)for(var o=0;oa&&(a=p),o&=~l}if(o=a,o=mn()-o,o=(120>o?120:480>o?480:1080>o?1080:1920>o?1920:3e3>o?3e3:4320>o?4320:1960*Kk(o/1960))-o,10e?16:e,hs===null)var o=!1;else{if(e=hs,hs=null,qh=0,zr&6)throw Error(xt(331));var a=zr;for(zr|=4,jt=e.current;jt!==null;){var l=jt,p=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:Pp(8,M,l)}var y=M.child;if(y!==null)y.return=M,jt=y;else for(;jt!==null;){M=jt;var E=M.sibling,T=M.return;if(v2(M),M===g){jt=null;break}if(E!==null){E.return=T,jt=E;break}jt=T}}}var O=l.alternate;if(O!==null){var S=O.child;if(S!==null){O.child=null;do{var C=S.sibling;S.sibling=null,S=C}while(S!==null)}}jt=l}}if(l.subtreeFlags&2064&&p!==null)p.return=l,jt=p;else e:for(;jt!==null;){if(l=jt,l.flags&2048)switch(l.tag){case 0:case 11:case 15:Pp(9,l,l.return)}var w=l.sibling;if(w!==null){w.return=l.return,jt=w;break e}jt=l.return}}var b=e.current;for(jt=b;jt!==null;){p=jt;var I=p.child;if(p.subtreeFlags&2064&&I!==null)I.return=p,jt=I;else e:for(p=b;jt!==null;){if(_=jt,_.flags&2048)try{switch(_.tag){case 0:case 11:case 15:lm(9,_)}}catch(z){fn(_,_.return,z)}if(_===p){jt=null;break e}var U=_.sibling;if(U!==null){U.return=_.return,jt=U;break e}jt=_.return}}if(zr=a,Es(),co&&typeof co.onPostCommitFiberRoot=="function")try{co.onPostCommitFiberRoot(em,e)}catch{}o=!0}return o}finally{Ur=r,Di.transition=t}}return!1}function a1(e,t,r){t=nu(r,t),t=u2(e,t,1),e=ys(e,t,1),t=ti(),e!==null&&(Yp(e,1,t),di(e,t))}function fn(e,t,r){if(e.tag===3)a1(e,e,r);else for(;t!==null;){if(t.tag===3){a1(t,e,r);break}else if(t.tag===1){var o=t.stateNode;if(typeof t.type.getDerivedStateFromError=="function"||typeof o.componentDidCatch=="function"&&(vs===null||!vs.has(o))){e=nu(r,e),e=c2(t,e,1),t=ys(t,e,1),e=ti(),t!==null&&(Yp(t,1,e),di(t,e));break}}t=t.return}}function Jk(e,t,r){var o=e.pingCache;o!==null&&o.delete(t),t=ti(),e.pingedLanes|=e.suspendedLanes&r,Fn===e&&(Bn&r)===r&&(En===4||En===3&&(Bn&130023424)===Bn&&500>mn()-d0?sa(e,0):c0|=r),di(e,t)}function $2(e,t){t===0&&(e.mode&1?(t=Jf,Jf<<=1,!(Jf&130023424)&&(Jf=4194304)):t=1);var r=ti();e=Oo(e,t),e!==null&&(Yp(e,t,r),di(e,r))}function eS(e){var t=e.memoizedState,r=0;t!==null&&(r=t.retryLane),$2(e,r)}function tS(e,t){var r=0;switch(e.tag){case 13:var o=e.stateNode,a=e.memoizedState;a!==null&&(r=a.retryLane);break;case 19:o=e.stateNode;break;default:throw Error(xt(314))}o!==null&&o.delete(t),$2(e,r)}var A2;A2=function(e,t,r){if(e!==null)if(e.memoizedProps!==t.pendingProps||ui.current)li=!0;else{if(!(e.lanes&r)&&!(t.flags&128))return li=!1,Uk(e,t,r);li=!!(e.flags&131072)}else li=!1,nn&&t.flags&1048576&&zb(t,Rh,t.index);switch(t.lanes=0,t.tag){case 2:var o=t.type;bh(e,t),e=t.pendingProps;var a=Jl(t,qn.current);Ql(t,r),a=i0(null,t,o,e,a,r);var l=o0();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,ci(o)?(l=!0,Dh(t)):l=!1,t.memoizedState=a.state!==null&&a.state!==void 0?a.state:null,J_(t),a.updater=am,t.stateNode=a,a._reactInternals=t,o_(t,o,e,r),t=l_(null,t,o,!0,l,r)):(t.tag=0,nn&&l&&H_(t),ei(null,t,a,r),t=t.child),t;case 16:o=t.elementType;e:{switch(bh(e,t),e=t.pendingProps,a=o._init,o=a(o._payload),t.type=o,a=t.tag=nS(o),e=qi(o,e),a){case 0:t=a_(null,t,o,e,r);break e;case 1:t=Yv(null,t,o,e,r);break e;case 11:t=Xv(null,t,o,e,r);break e;case 14:t=Qv(null,t,o,qi(o.type,e),r);break e}throw Error(xt(306,o,""))}return t;case 0:return o=t.type,a=t.pendingProps,a=t.elementType===o?a:qi(o,a),a_(e,t,o,a,r);case 1:return o=t.type,a=t.pendingProps,a=t.elementType===o?a:qi(o,a),Yv(e,t,o,a,r);case 3:e:{if(h2(t),e===null)throw Error(xt(387));o=t.pendingProps,l=t.memoizedState,a=l.element,jb(e,t),jh(t,o,null,r);var p=t.memoizedState;if(o=p.element,l.isDehydrated)if(l={element:o,isDehydrated:!1,cache:p.cache,pendingSuspenseBoundaries:p.pendingSuspenseBoundaries,transitions:p.transitions},t.updateQueue.baseState=l,t.memoizedState=l,t.flags&256){a=nu(Error(xt(423)),t),t=Zv(e,t,o,r,a);break e}else if(o!==a){a=nu(Error(xt(424)),t),t=Zv(e,t,o,r,a);break e}else for(wi=ws(t.stateNode.containerInfo.firstChild),yi=t,nn=!0,Xi=null,r=Bb(t,null,o,r),t.child=r;r;)r.flags=r.flags&-3|4096,r=r.sibling;else{if(eu(),o===a){t=zo(e,t,r);break e}ei(e,t,o,r)}t=t.child}return t;case 5:return Ub(t),e===null&&r_(t),o=t.type,a=t.pendingProps,l=e!==null?e.memoizedProps:null,p=a.children,Yg(o,a)?p=null:l!==null&&Yg(o,l)&&(t.flags|=32),f2(e,t),ei(e,t,p,r),t.child;case 6:return e===null&&r_(t),null;case 13:return m2(e,t,r);case 4:return e0(t,t.stateNode.containerInfo),o=t.pendingProps,e===null?t.child=tu(t,null,o,r):ei(e,t,o,r),t.child;case 11:return o=t.type,a=t.pendingProps,a=t.elementType===o?a:qi(o,a),Xv(e,t,o,a,r);case 7:return ei(e,t,t.pendingProps,r),t.child;case 8:return ei(e,t,t.pendingProps.children,r),t.child;case 12:return ei(e,t,t.pendingProps.children,r),t.child;case 10:e:{if(o=t.type._context,a=t.pendingProps,l=t.memoizedProps,p=a.value,Qr(Bh,o._currentValue),o._currentValue=p,l!==null)if(Zi(l.value,p)){if(l.children===a.children&&!ui.current){t=zo(e,t,r);break e}}else for(l=t.child,l!==null&&(l.return=t);l!==null;){var _=l.dependencies;if(_!==null){p=l.child;for(var h=_.firstContext;h!==null;){if(h.context===o){if(l.tag===1){h=Ao(-1,r&-r),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|=r,h=l.alternate,h!==null&&(h.lanes|=r),n_(l.return,r,t),_.lanes|=r;break}h=h.next}}else if(l.tag===10)p=l.type===t.type?null:l.child;else if(l.tag===18){if(p=l.return,p===null)throw Error(xt(341));p.lanes|=r,_=p.alternate,_!==null&&(_.lanes|=r),n_(p,r,t),p=l.sibling}else p=l.child;if(p!==null)p.return=l;else for(p=l;p!==null;){if(p===t){p=null;break}if(l=p.sibling,l!==null){l.return=p.return,p=l;break}p=p.return}l=p}ei(e,t,a.children,r),t=t.child}return t;case 9:return a=t.type,o=t.pendingProps.children,Ql(t,r),a=Li(a),o=o(a),t.flags|=1,ei(e,t,o,r),t.child;case 14:return o=t.type,a=qi(o,t.pendingProps),a=qi(o.type,a),Qv(e,t,o,a,r);case 15:return d2(e,t,t.type,t.pendingProps,r);case 17:return o=t.type,a=t.pendingProps,a=t.elementType===o?a:qi(o,a),bh(e,t),t.tag=1,ci(o)?(e=!0,Dh(t)):e=!1,Ql(t,r),l2(t,o,a),o_(t,o,a,r),l_(null,t,o,!0,e,r);case 19:return g2(e,t,r);case 22:return p2(e,t,r)}throw Error(xt(156,t.tag))};function I2(e,t){return ob(e,t)}function rS(e,t,r,o){this.tag=e,this.key=r,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=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 zi(e,t,r,o){return new rS(e,t,r,o)}function m0(e){return e=e.prototype,!(!e||!e.isReactComponent)}function nS(e){if(typeof e=="function")return m0(e)?1:0;if(e!=null){if(e=e.$$typeof,e===O_)return 11;if(e===z_)return 14}return 2}function xs(e,t){var r=e.alternate;return r===null?(r=zi(e.tag,t,e.key,e.mode),r.elementType=e.elementType,r.type=e.type,r.stateNode=e.stateNode,r.alternate=e,e.alternate=r):(r.pendingProps=t,r.type=e.type,r.flags=0,r.subtreeFlags=0,r.deletions=null),r.flags=e.flags&14680064,r.childLanes=e.childLanes,r.lanes=e.lanes,r.child=e.child,r.memoizedProps=e.memoizedProps,r.memoizedState=e.memoizedState,r.updateQueue=e.updateQueue,t=e.dependencies,r.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},r.sibling=e.sibling,r.index=e.index,r.ref=e.ref,r}function Th(e,t,r,o,a,l){var p=2;if(o=e,typeof e=="function")m0(e)&&(p=1);else if(typeof e=="string")p=5;else e:switch(e){case zl:return aa(r.children,a,l,t);case F_:p=8,a|=8;break;case Pg:return e=zi(12,r,t,a|2),e.elementType=Pg,e.lanes=l,e;case $g:return e=zi(13,r,t,a),e.elementType=$g,e.lanes=l,e;case Ag:return e=zi(19,r,t,a),e.elementType=Ag,e.lanes=l,e;case U1:return cm(r,a,l,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case N1:p=10;break e;case j1:p=9;break e;case O_:p=11;break e;case z_:p=14;break e;case us:p=16,o=null;break e}throw Error(xt(130,e==null?e:typeof e,""))}return t=zi(p,r,t,a),t.elementType=e,t.type=o,t.lanes=l,t}function aa(e,t,r,o){return e=zi(7,e,o,t),e.lanes=r,e}function cm(e,t,r,o){return e=zi(22,e,o,t),e.elementType=U1,e.lanes=r,e.stateNode={isHidden:!1},e}function kg(e,t,r){return e=zi(6,e,null,t),e.lanes=r,e}function Sg(e,t,r){return t=zi(4,e.children!==null?e.children:[],e.key,t),t.lanes=r,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function iS(e,t,r,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=sg(0),this.expirationTimes=sg(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=sg(0),this.identifierPrefix=o,this.onRecoverableError=a,this.mutableSourceEagerHydrationData=null}function g0(e,t,r,o,a,l,p,_,h){return e=new iS(e,t,r,_,h),t===1?(t=1,l===!0&&(t|=8)):t=0,l=zi(3,null,null,t),e.current=l,l.stateNode=e,l.memoizedState={element:o,isDehydrated:r,cache:null,transitions:null,pendingSuspenseBoundaries:null},J_(l),e}function oS(e,t,r){var o=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(D2)}catch(e){console.error(e)}}D2(),D1.exports=bi;var cS=D1.exports,L2,c1=cS;L2=c1.createRoot,c1.hydrateRoot;var R2={exports:{}},dS="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED",pS=dS,fS=pS;function B2(){}function N2(){}N2.resetWarningCache=B2;var hS=function(){function e(o,a,l,p,_,h){if(h!==fS){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 r={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:N2,resetWarningCache:B2};return r.PropTypes=r,r};R2.exports=hS();var mS=R2.exports;const qr=k_(mS);function lu(e,t,r,o){function a(l){return l instanceof r?l:new r(function(p){p(l)})}return new(r||(r=Promise))(function(l,p){function _(M){try{g(o.next(M))}catch(y){p(y)}}function h(M){try{g(o.throw(M))}catch(y){p(y)}}function g(M){M.done?l(M.value):a(M.value).then(_,h)}g((o=o.apply(e,t||[])).next())})}function uu(e,t){var r={label:0,sent:function(){if(l[0]&1)throw l[1];return l[1]},trys:[],ops:[]},o,a,l,p=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return p.next=_(0),p.throw=_(1),p.return=_(2),typeof Symbol=="function"&&(p[Symbol.iterator]=function(){return this}),p;function _(g){return function(M){return h([g,M])}}function h(g){if(o)throw new TypeError("Generator is already executing.");for(;p&&(p=0,g[0]&&(r=0)),r;)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 r.label++,{value:g[1],done:!1};case 5:r.label++,a=g[1],g=[0];continue;case 7:g=r.ops.pop(),r.trys.pop();continue;default:if(l=r.trys,!(l=l.length>0&&l[l.length-1])&&(g[0]===6||g[0]===2)){r=0;continue}if(g[0]===3&&(!l||g[1]>l[0]&&g[1]0)&&!(a=o.next()).done;)l.push(a.value)}catch(_){p={error:_}}finally{try{a&&!a.done&&(r=o.return)&&r.call(o)}finally{if(p)throw p.error}}return l}function p1(e,t,r){if(r||arguments.length===2)for(var o=0,a=t.length,l;o0?o:e.name,writable:!1,configurable:!1,enumerable:!0})}return r}function _S(e){var t=e.name,r=t&&t.lastIndexOf(".")!==-1;if(r&&!e.type){var o=t.split(".").pop().toLowerCase(),a=gS.get(o);a&&Object.defineProperty(e,"type",{value:a,writable:!1,configurable:!1,enumerable:!0})}return e}var wS=[".DS_Store","Thumbs.db"];function yS(e){return lu(this,void 0,void 0,function(){return uu(this,function(t){return Qh(e)&&vS(e.dataTransfer)?[2,TS(e.dataTransfer,e.type)]:bS(e)?[2,xS(e)]:Array.isArray(e)&&e.every(function(r){return"getFile"in r&&typeof r.getFile=="function"})?[2,MS(e)]:[2,[]]})})}function vS(e){return Qh(e)}function bS(e){return Qh(e)&&Qh(e.target)}function Qh(e){return typeof e=="object"&&e!==null}function xS(e){return v_(e.target.files).map(function(t){return tf(t)})}function MS(e){return lu(this,void 0,void 0,function(){var t;return uu(this,function(r){switch(r.label){case 0:return[4,Promise.all(e.map(function(o){return o.getFile()}))];case 1:return t=r.sent(),[2,t.map(function(o){return tf(o)})]}})})}function TS(e,t){return lu(this,void 0,void 0,function(){var r,o;return uu(this,function(a){switch(a.label){case 0:return e.items?(r=v_(e.items).filter(function(l){return l.kind==="file"}),t!=="drop"?[2,r]:[4,Promise.all(r.map(kS))]):[3,2];case 1:return o=a.sent(),[2,f1(j2(o))];case 2:return[2,f1(v_(e.files).map(function(l){return tf(l)}))]}})})}function f1(e){return e.filter(function(t){return wS.indexOf(t.name)===-1})}function v_(e){if(e===null)return[];for(var t=[],r=0;re.length)&&(t=e.length);for(var r=0,o=new Array(t);rr)return[!1,w1(r)];if(e.sizer)return[!1,w1(r)]}return[!0,null]}function ra(e){return e!=null}function jS(e){var t=e.files,r=e.accept,o=e.minSize,a=e.maxSize,l=e.multiple,p=e.maxFiles,_=e.validator;return!l&&t.length>1||l&&p>=1&&t.length>p?!1:t.every(function(h){var g=G2(h,r),M=Xp(g,1),y=M[0],E=H2(h,o,a),T=Xp(E,1),O=T[0],S=_?_(h):null;return y&&O&&!S})}function Yh(e){return typeof e.isPropagationStopped=="function"?e.isPropagationStopped():typeof e.cancelBubble<"u"?e.cancelBubble:!1}function dh(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 v1(e){e.preventDefault()}function US(e){return e.indexOf("MSIE")!==-1||e.indexOf("Trident/")!==-1}function VS(e){return e.indexOf("Edge/")!==-1}function WS(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:window.navigator.userAgent;return US(e)||VS(e)}function ao(){for(var e=arguments.length,t=new Array(e),r=0;r1?a-1:0),p=1;pe.length)&&(t=e.length);for(var r=0,o=new Array(t);r=0)&&Object.prototype.propertyIsEnumerable.call(e,o)&&(r[o]=e[o])}return r}function aE(e,t){if(e==null)return{};var r={},o=Object.keys(e),a,l;for(l=0;l=0)&&(r[a]=e[a]);return r}var v0=fr.forwardRef(function(e,t){var r=e.children,o=Zh(e,QS),a=Y2(o),l=a.open,p=Zh(a,YS);return fr.useImperativeHandle(t,function(){return{open:l}},[l]),JM.createElement(fr.Fragment,null,r(on(on({},p),{},{open:l})))});v0.displayName="Dropzone";var Q2={disabled:!1,getFilesFromEvent:yS,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};v0.defaultProps=Q2;v0.propTypes={children:qr.func,accept:qr.objectOf(qr.arrayOf(qr.string)),multiple:qr.bool,preventDropOnDocument:qr.bool,noClick:qr.bool,noKeyboard:qr.bool,noDrag:qr.bool,noDragEventsBubbling:qr.bool,minSize:qr.number,maxSize:qr.number,maxFiles:qr.number,disabled:qr.bool,getFilesFromEvent:qr.func,onFileDialogCancel:qr.func,onFileDialogOpen:qr.func,useFsAccessApi:qr.bool,autoFocus:qr.bool,onDragEnter:qr.func,onDragLeave:qr.func,onDragOver:qr.func,onDrop:qr.func,onDropAccepted:qr.func,onDropRejected:qr.func,onError:qr.func,validator:qr.func};var T_={isFocused:!1,isFileDialogActive:!1,isDragActive:!1,isDragAccept:!1,isDragReject:!1,acceptedFiles:[],fileRejections:[]};function Y2(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=on(on({},Q2),e),r=t.accept,o=t.disabled,a=t.getFilesFromEvent,l=t.maxSize,p=t.minSize,_=t.multiple,h=t.maxFiles,g=t.onDragEnter,M=t.onDragLeave,y=t.onDragOver,E=t.onDrop,T=t.onDropAccepted,O=t.onDropRejected,S=t.onFileDialogCancel,C=t.onFileDialogOpen,w=t.useFsAccessApi,b=t.autoFocus,I=t.preventDropOnDocument,U=t.noClick,z=t.noKeyboard,B=t.noDrag,j=t.noDragEventsBubbling,N=t.onError,ae=t.validator,ce=fr.useMemo(function(){return qS(r)},[r]),xe=fr.useMemo(function(){return HS(r)},[r]),Y=fr.useMemo(function(){return typeof C=="function"?C:x1},[C]),_e=fr.useMemo(function(){return typeof S=="function"?S:x1},[S]),L=fr.useRef(null),Se=fr.useRef(null),Xe=fr.useReducer(lE,T_),me=Eg(Xe,2),X=me[0],ie=me[1],Me=X.isFocused,Q=X.isFileDialogActive,ge=fr.useRef(typeof window<"u"&&window.isSecureContext&&w&&GS()),Ke=function(){!ge.current&&Q&&setTimeout(function(){if(Se.current){var ke=Se.current.files;ke.length||(ie({type:"closeDialog"}),_e())}},300)};fr.useEffect(function(){return window.addEventListener("focus",Ke,!1),function(){window.removeEventListener("focus",Ke,!1)}},[Se,Q,_e,ge]);var Le=fr.useRef([]),Be=function(ke){L.current&&L.current.contains(ke.target)||(ke.preventDefault(),Le.current=[])};fr.useEffect(function(){return I&&(document.addEventListener("dragover",v1,!1),document.addEventListener("drop",Be,!1)),function(){I&&(document.removeEventListener("dragover",v1),document.removeEventListener("drop",Be))}},[L,I]),fr.useEffect(function(){return!o&&b&&L.current&&L.current.focus(),function(){}},[L,b,o]);var We=fr.useCallback(function(le){N?N(le):console.error(le)},[N]),st=fr.useCallback(function(le){le.preventDefault(),le.persist(),R(le),Le.current=[].concat(eE(Le.current),[le.target]),dh(le)&&Promise.resolve(a(le)).then(function(ke){if(!(Yh(le)&&!j)){var Ne=ke.length,dt=Ne>0&&jS({files:ke,accept:ce,minSize:p,maxSize:l,multiple:_,maxFiles:h,validator:ae}),Je=Ne>0&&!dt;ie({isDragAccept:dt,isDragReject:Je,isDragActive:!0,type:"setDraggedFiles"}),g&&g(le)}}).catch(function(ke){return We(ke)})},[a,g,We,j,ce,p,l,_,h,ae]),pt=fr.useCallback(function(le){le.preventDefault(),le.persist(),R(le);var ke=dh(le);if(ke&&le.dataTransfer)try{le.dataTransfer.dropEffect="copy"}catch{}return ke&&y&&y(le),!1},[y,j]),Ge=fr.useCallback(function(le){le.preventDefault(),le.persist(),R(le);var ke=Le.current.filter(function(dt){return L.current&&L.current.contains(dt)}),Ne=ke.indexOf(le.target);Ne!==-1&&ke.splice(Ne,1),Le.current=ke,!(ke.length>0)&&(ie({type:"setDraggedFiles",isDragActive:!1,isDragAccept:!1,isDragReject:!1}),dh(le)&&M&&M(le))},[L,M,j]),Te=fr.useCallback(function(le,ke){var Ne=[],dt=[];le.forEach(function(Je){var Ve=G2(Je,ce),Z=Eg(Ve,2),ve=Z[0],Re=Z[1],qe=H2(Je,p,l),Qe=Eg(qe,2),tt=Qe[0],ft=Qe[1],ht=ae?ae(Je):null;if(ve&&tt&&!ht)Ne.push(Je);else{var Tt=[Re,ft];ht&&(Tt=Tt.concat(ht)),dt.push({file:Je,errors:Tt.filter(function(bt){return bt})})}}),(!_&&Ne.length>1||_&&h>=1&&Ne.length>h)&&(Ne.forEach(function(Je){dt.push({file:Je,errors:[NS]})}),Ne.splice(0)),ie({acceptedFiles:Ne,fileRejections:dt,type:"setFiles"}),E&&E(Ne,dt,ke),dt.length>0&&O&&O(dt,ke),Ne.length>0&&T&&T(Ne,ke)},[ie,_,ce,p,l,h,E,T,O,ae]),je=fr.useCallback(function(le){le.preventDefault(),le.persist(),R(le),Le.current=[],dh(le)&&Promise.resolve(a(le)).then(function(ke){Yh(le)&&!j||Te(ke,le)}).catch(function(ke){return We(ke)}),ie({type:"reset"})},[a,Te,We,j]),Ye=fr.useCallback(function(){if(ge.current){ie({type:"openDialog"}),Y();var le={multiple:_,types:xe};window.showOpenFilePicker(le).then(function(ke){return a(ke)}).then(function(ke){Te(ke,null),ie({type:"closeDialog"})}).catch(function(ke){KS(ke)?(_e(ke),ie({type:"closeDialog"})):XS(ke)?(ge.current=!1,Se.current?(Se.current.value=null,Se.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}Se.current&&(ie({type:"openDialog"}),Y(),Se.current.value=null,Se.current.click())},[ie,Y,_e,w,Te,We,xe,_]),et=fr.useCallback(function(le){!L.current||!L.current.isEqualNode(le.target)||(le.key===" "||le.key==="Enter"||le.keyCode===32||le.keyCode===13)&&(le.preventDefault(),Ye())},[L,Ye]),A=fr.useCallback(function(){ie({type:"focus"})},[]),$e=fr.useCallback(function(){ie({type:"blur"})},[]),Pe=fr.useCallback(function(){U||(WS()?setTimeout(Ye,0):Ye())},[U,Ye]),se=function(ke){return o?null:ke},re=function(ke){return z?null:se(ke)},ye=function(ke){return B?null:se(ke)},R=function(ke){j&&ke.stopPropagation()},ee=fr.useMemo(function(){return function(){var le=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},ke=le.refKey,Ne=ke===void 0?"ref":ke,dt=le.role,Je=le.onKeyDown,Ve=le.onFocus,Z=le.onBlur,ve=le.onClick,Re=le.onDragEnter,qe=le.onDragOver,Qe=le.onDragLeave,tt=le.onDrop,ft=Zh(le,ZS);return on(on(M_({onKeyDown:re(ao(Je,et)),onFocus:re(ao(Ve,A)),onBlur:re(ao(Z,$e)),onClick:se(ao(ve,Pe)),onDragEnter:ye(ao(Re,st)),onDragOver:ye(ao(qe,pt)),onDragLeave:ye(ao(Qe,Ge)),onDrop:ye(ao(tt,je)),role:typeof dt=="string"&&dt!==""?dt:"presentation"},Ne,L),!o&&!z?{tabIndex:0}:{}),ft)}},[L,et,A,$e,Pe,st,pt,Ge,je,z,B,o]),D=fr.useCallback(function(le){le.stopPropagation()},[]),ue=fr.useMemo(function(){return function(){var le=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},ke=le.refKey,Ne=ke===void 0?"ref":ke,dt=le.onChange,Je=le.onClick,Ve=Zh(le,JS),Z=M_({accept:ce,multiple:_,type:"file",style:{display:"none"},onChange:se(ao(dt,je)),onClick:se(ao(Je,D)),tabIndex:-1},Ne,Se);return on(on({},Z),Ve)}},[Se,r,_,je,o]);return on(on({},X),{},{isFocused:Me&&!o,getRootProps:ee,getInputProps:ue,rootRef:L,inputRef:Se,open:se(Ye)})}function lE(e,t){switch(t.type){case"focus":return on(on({},e),{},{isFocused:!0});case"blur":return on(on({},e),{},{isFocused:!1});case"openDialog":return on(on({},T_),{},{isFileDialogActive:!0});case"closeDialog":return on(on({},e),{},{isFileDialogActive:!1});case"setDraggedFiles":return on(on({},e),{},{isDragActive:t.isDragActive,isDragAccept:t.isDragAccept,isDragReject:t.isDragReject});case"setFiles":return on(on({},e),{},{acceptedFiles:t.acceptedFiles,fileRejections:t.fileRejections});case"reset":return on({},T_);default:return e}}function x1(){}var ko={},uE={"./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm":(e,t,r)=>{e.exports=r.p+"ort-wasm-simd-threaded.jsep.wasm"},"?2ce3":()=>{},"?7a2c":()=>{},"?a42a":()=>{},"?2b25":()=>{},"?569f":()=>{},"?3f59":()=>{},"?154a":()=>{},"./node_modules/@huggingface/jinja/dist/index.js":(e,t,r)=>{r.r(t),r.d(t,{Environment:()=>$e,Interpreter:()=>Pe,Template:()=>ye,parse:()=>Me,tokenize:()=>y});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(R,ee){this.value=R,this.type=ee}};function p(R){return/\w/.test(R)}function _(R){return/[0-9]/.test(R)}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(R,ee={}){return R.endsWith(` +`)&&(R=R.slice(0,-1)),R=R.replace(/{#.*?#}/gs,"{##}"),ee.lstrip_blocks&&(R=R.replace(/^[ \t]*({[#%])/gm,"$1")),ee.trim_blocks&&(R=R.replace(/([#%]})\n/g,"$1")),R.replace(/{##}/g,"").replace(/-%}\s*/g,"%}").replace(/\s*{%-/g,"{%").replace(/-}}\s*/g,"}}").replace(/\s*{{-/g,"{{")}function y(R,ee={}){var Ne,dt,Je;const D=[],ue=M(R,ee);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){D.push(new l(ve,o.Text));continue}}ke(ve=>/\s/.test(ve));const Z=ue[le];if(Z==="-"||Z==="+"){const ve=(dt=D.at(-1))==null?void 0:dt.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(_);D.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){D.push(new l(ve,Re)),le+=ve.length;continue e}if(Z==="'"||Z==='"'){++le;const ve=ke(Re=>Re!==Z);D.push(new l(ve,o.StringLiteral)),++le;continue}if(_(Z)){const ve=ke(_);D.push(new l(ve,o.NumericLiteral));continue}if(p(Z)){const ve=ke(p),Re=Object.hasOwn(a,ve)?a[ve]:o.Identifier;Re===o.In&&((Je=D.at(-1))==null?void 0:Je.type)===o.Not?(D.pop(),D.push(new l("not in",o.NotIn))):D.push(new l(ve,Re));continue}throw new SyntaxError(`Unexpected character: ${Z}`)}return D}var E=class{constructor(){He(this,"type","Statement")}},T=class extends E{constructor(ee){super();He(this,"type","Program");this.body=ee}},O=class extends E{constructor(ee,D,ue){super();He(this,"type","If");this.test=ee,this.body=D,this.alternate=ue}},S=class extends E{constructor(ee,D,ue,le){super();He(this,"type","For");this.loopvar=ee,this.iterable=D,this.body=ue,this.defaultBlock=le}},C=class extends E{constructor(ee,D){super();He(this,"type","Set");this.assignee=ee,this.value=D}},w=class extends E{constructor(ee,D,ue){super();He(this,"type","Macro");this.name=ee,this.args=D,this.body=ue}},b=class extends E{constructor(){super(...arguments);He(this,"type","Expression")}},I=class extends b{constructor(ee,D,ue){super();He(this,"type","MemberExpression");this.object=ee,this.property=D,this.computed=ue}},U=class extends b{constructor(ee,D){super();He(this,"type","CallExpression");this.callee=ee,this.args=D}},z=class extends b{constructor(ee){super();He(this,"type","Identifier");this.value=ee}},B=class extends b{constructor(ee){super();He(this,"type","Literal");this.value=ee}},j=class extends B{constructor(){super(...arguments);He(this,"type","NumericLiteral")}},N=class extends B{constructor(){super(...arguments);He(this,"type","StringLiteral")}},ae=class extends B{constructor(){super(...arguments);He(this,"type","BooleanLiteral")}},ce=class extends B{constructor(){super(...arguments);He(this,"type","ArrayLiteral")}},xe=class extends B{constructor(){super(...arguments);He(this,"type","TupleLiteral")}},Y=class extends B{constructor(){super(...arguments);He(this,"type","ObjectLiteral")}},_e=class extends b{constructor(ee,D,ue){super();He(this,"type","BinaryExpression");this.operator=ee,this.left=D,this.right=ue}},L=class extends b{constructor(ee,D){super();He(this,"type","FilterExpression");this.operand=ee,this.filter=D}},Se=class extends b{constructor(ee,D){super();He(this,"type","SelectExpression");this.iterable=ee,this.test=D}},Xe=class extends b{constructor(ee,D,ue){super();He(this,"type","TestExpression");this.operand=ee,this.negate=D,this.test=ue}},me=class extends b{constructor(ee,D){super();He(this,"type","UnaryExpression");this.operator=ee,this.argument=D}},X=class extends b{constructor(ee=void 0,D=void 0,ue=void 0){super();He(this,"type","SliceExpression");this.start=ee,this.stop=D,this.step=ue}},ie=class extends b{constructor(ee,D){super();He(this,"type","KeywordArgumentExpression");this.key=ee,this.value=D}};function Me(R){const ee=new T([]);let D=0;function ue(mt,$t){const Bt=R[D++];if(!Bt||Bt.type!==mt)throw new Error(`Parser Error: ${$t}. ${Bt.type} !== ${mt}.`);return Bt}function le(){switch(R[D].type){case o.Text:return dt();case o.OpenStatement:return Je();case o.OpenExpression:return Ve();default:throw new SyntaxError(`Unexpected token type: ${R[D].type}`)}}function ke(...mt){return D+mt.length<=R.length&&mt.some(($t,Bt)=>$t!==R[D+Bt].type)}function Ne(...mt){return D+mt.length<=R.length&&mt.every(($t,Bt)=>$t===R[D+Bt].type)}function dt(){return new N(ue(o.Text,"Expected text token").value)}function Je(){ue(o.OpenStatement,"Expected opening statement token");let mt;switch(R[D].type){case o.Set:++D,mt=Z(),ue(o.CloseStatement,"Expected closing statement token");break;case o.If:++D,mt=ve(),ue(o.OpenStatement,"Expected {% token"),ue(o.EndIf,"Expected endif token"),ue(o.CloseStatement,"Expected %} token");break;case o.Macro:++D,mt=Re(),ue(o.OpenStatement,"Expected {% token"),ue(o.EndMacro,"Expected endmacro token"),ue(o.CloseStatement,"Expected %} token");break;case o.For:++D,mt=Qe(),ue(o.OpenStatement,"Expected {% token"),ue(o.EndFor,"Expected endfor token"),ue(o.CloseStatement,"Expected %} token");break;default:throw new SyntaxError(`Unknown statement type: ${R[D].type}`)}return mt}function Ve(){ue(o.OpenExpression,"Expected opening expression token");const mt=tt();return ue(o.CloseExpression,"Expected closing expression token"),mt}function Z(){const mt=tt();if(Ne(o.Equals)){++D;const $t=Z();return new C(mt,$t)}return mt}function ve(){var un,Bi,Mi,Gr,wn,Kr,pi,Dr;const mt=tt();ue(o.CloseStatement,"Expected closing statement token");const $t=[],Bt=[];for(;!(((un=R[D])==null?void 0:un.type)===o.OpenStatement&&(((Bi=R[D+1])==null?void 0:Bi.type)===o.ElseIf||((Mi=R[D+1])==null?void 0:Mi.type)===o.Else||((Gr=R[D+1])==null?void 0:Gr.type)===o.EndIf));)$t.push(le());if(((wn=R[D])==null?void 0:wn.type)===o.OpenStatement&&((Kr=R[D+1])==null?void 0:Kr.type)!==o.EndIf)if(++D,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");!(((pi=R[D])==null?void 0:pi.type)===o.OpenStatement&&((Dr=R[D+1])==null?void 0:Dr.type)===o.EndIf);)Bt.push(le());return new O(mt,$t,Bt)}function Re(){const mt=$r();if(mt.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");const $t=Ut();ue(o.CloseStatement,"Expected closing statement token");const Bt=[];for(;ke(o.OpenStatement,o.EndMacro);)Bt.push(le());return new w(mt,$t,Bt)}function qe(mt=!1){const $t=mt?$r:tt,Bt=[$t()],un=Ne(o.Comma);for(;un&&(++D,Bt.push($t()),!!Ne(o.Comma)););return un?new xe(Bt):Bt[0]}function Qe(){const mt=qe(!0);if(!(mt instanceof z||mt instanceof xe))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${mt.type} instead`);ue(o.In,"Expected `in` keyword following loop variable");const $t=tt();ue(o.CloseStatement,"Expected closing statement token");const Bt=[];for(;ke(o.OpenStatement,o.EndFor)&&ke(o.OpenStatement,o.Else);)Bt.push(le());const un=[];if(Ne(o.OpenStatement,o.Else))for(++D,++D,ue(o.CloseStatement,"Expected closing statement token");ke(o.OpenStatement,o.EndFor);)un.push(le());return new S(mt,$t,Bt,un)}function tt(){return ft()}function ft(){const mt=ht();if(Ne(o.If)){++D;const $t=ht();if(Ne(o.Else)){++D;const Bt=ht();return new O($t,[mt],[Bt])}else return new Se(mt,$t)}return mt}function ht(){let mt=Tt();for(;Ne(o.Or);){const $t=R[D];++D;const Bt=Tt();mt=new _e($t,mt,Bt)}return mt}function Tt(){let mt=bt();for(;Ne(o.And);){const $t=R[D];++D;const Bt=bt();mt=new _e($t,mt,Bt)}return mt}function bt(){let mt;for(;Ne(o.Not);){const $t=R[D];++D;const Bt=bt();mt=new me($t,Bt)}return mt??Et()}function Et(){let mt=Lt();for(;Ne(o.ComparisonBinaryOperator)||Ne(o.In)||Ne(o.NotIn);){const $t=R[D];++D;const Bt=Lt();mt=new _e($t,mt,Bt)}return mt}function Lt(){let mt=Ht();for(;Ne(o.AdditiveBinaryOperator);){const $t=R[D];++D;const Bt=Ht();mt=new _e($t,mt,Bt)}return mt}function at(){const mt=rr();return Ne(o.OpenParen)?Ot(mt):mt}function Ot(mt){let $t=new U(mt,Ut());return Ne(o.OpenParen)&&($t=Ot($t)),$t}function Ut(){ue(o.OpenParen,"Expected opening parenthesis for arguments list");const mt=Xt();return ue(o.CloseParen,"Expected closing parenthesis for arguments list"),mt}function Xt(){const mt=[];for(;!Ne(o.CloseParen);){let $t=tt();if(Ne(o.Equals)){if(++D,!($t instanceof z))throw new SyntaxError("Expected identifier for keyword argument");const Bt=tt();$t=new ie($t,Bt)}mt.push($t),Ne(o.Comma)&&++D}return mt}function Yt(){const mt=[];let $t=!1;for(;!Ne(o.CloseSquareBracket);)Ne(o.Colon)?(mt.push(void 0),++D,$t=!0):(mt.push(tt()),Ne(o.Colon)&&(++D,$t=!0));if(mt.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if($t){if(mt.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new X(...mt)}return mt[0]}function rr(){let mt=$r();for(;Ne(o.Dot)||Ne(o.OpenSquareBracket);){const $t=R[D];++D;let Bt;const un=$t.type!==o.Dot;if(un)Bt=Yt(),ue(o.CloseSquareBracket,"Expected closing square bracket");else if(Bt=$r(),Bt.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");mt=new I(mt,Bt,un)}return mt}function Ht(){let mt=Pr();for(;Ne(o.MultiplicativeBinaryOperator);){const $t=R[D];++D;const Bt=Pr();mt=new _e($t,mt,Bt)}return mt}function Pr(){let mt=Yr();for(;Ne(o.Is);){++D;const $t=Ne(o.Not);$t&&++D;let Bt=$r();if(Bt instanceof ae&&(Bt=new z(Bt.value.toString())),!(Bt instanceof z))throw new SyntaxError("Expected identifier for the test");mt=new Xe(mt,$t,Bt)}return mt}function Yr(){let mt=at();for(;Ne(o.Pipe);){++D;let $t=$r();if(!($t instanceof z))throw new SyntaxError("Expected identifier for the filter");Ne(o.OpenParen)&&($t=Ot($t)),mt=new L(mt,$t)}return mt}function $r(){const mt=R[D];switch(mt.type){case o.NumericLiteral:return++D,new j(Number(mt.value));case o.StringLiteral:return++D,new N(mt.value);case o.BooleanLiteral:return++D,new ae(mt.value.toLowerCase()==="true");case o.Identifier:return++D,new z(mt.value);case o.OpenParen:{++D;const $t=qe();if(R[D].type!==o.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${R[D].type} instead`);return++D,$t}case o.OpenSquareBracket:{++D;const $t=[];for(;!Ne(o.CloseSquareBracket);)$t.push(tt()),Ne(o.Comma)&&++D;return++D,new ce($t)}case o.OpenCurlyBracket:{++D;const $t=new Map;for(;!Ne(o.CloseCurlyBracket);){const Bt=tt();ue(o.Colon,"Expected colon between key and value in object literal");const un=tt();$t.set(Bt,un),Ne(o.Comma)&&++D}return++D,new Y($t)}default:throw new SyntaxError(`Unexpected token: ${mt.type}`)}}for(;D=0?(ee=(ee??(ee=0))<0?Math.max(R.length+ee,0):Math.min(ee,R.length),D=(D??(D=R.length))<0?Math.max(R.length+D,0):Math.min(D,R.length)):(ee=(ee??(ee=R.length-1))<0?Math.max(R.length+ee,-1):Math.min(ee,R.length-1),D=(D??(D=-1))<-1?Math.max(R.length+D,-1):Math.min(D,R.length-1));const ke=[];for(let Ne=ee;le*Neee.toUpperCase())}var Le=class{constructor(R=void 0){He(this,"type","RuntimeValue");He(this,"value");He(this,"builtins",new Map);this.value=R}__bool__(){return new st(!!this.value)}},Be=class extends Le{constructor(){super(...arguments);He(this,"type","NumericValue")}},We=class extends Le{constructor(){super(...arguments);He(this,"type","StringValue");He(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)]]))}},st=class extends Le{constructor(){super(...arguments);He(this,"type","BooleanValue")}},pt=class extends Le{constructor(){super(...arguments);He(this,"type","ObjectValue");He(this,"builtins",new Map([["get",new Ye(([ee,D])=>{if(!(ee instanceof We))throw new Error(`Object key must be a string: got ${ee.type}`);return this.value.get(ee.value)??D??new et})],["items",new Ye(()=>new Te(Array.from(this.value.entries()).map(([ee,D])=>new Te([new We(ee),D]))))]]))}__bool__(){return new st(this.value.size>0)}},Ge=class extends pt{constructor(){super(...arguments);He(this,"type","KeywordArgumentsValue")}},Te=class extends Le{constructor(){super(...arguments);He(this,"type","ArrayValue");He(this,"builtins",new Map([["length",new Be(this.value.length)]]))}__bool__(){return new st(this.value.length>0)}},je=class extends Te{constructor(){super(...arguments);He(this,"type","TupleValue")}},Ye=class extends Le{constructor(){super(...arguments);He(this,"type","FunctionValue")}},et=class extends Le{constructor(){super(...arguments);He(this,"type","NullValue")}},A=class extends Le{constructor(){super(...arguments);He(this,"type","UndefinedValue")}},$e=class{constructor(R){He(this,"variables",new Map([["namespace",new Ye(R=>{if(R.length===0)return new pt(new Map);if(R.length!==1||!(R[0]instanceof pt))throw new Error("`namespace` expects either zero arguments or a single object argument");return R[0]})]]));He(this,"tests",new Map([["boolean",R=>R.type==="BooleanValue"],["callable",R=>R instanceof Ye],["odd",R=>{if(R.type!=="NumericValue")throw new Error(`Cannot apply test "odd" to type: ${R.type}`);return R.value%2!==0}],["even",R=>{if(R.type!=="NumericValue")throw new Error(`Cannot apply test "even" to type: ${R.type}`);return R.value%2===0}],["false",R=>R.type==="BooleanValue"&&!R.value],["true",R=>R.type==="BooleanValue"&&R.value],["string",R=>R.type==="StringValue"],["number",R=>R.type==="NumericValue"],["integer",R=>R.type==="NumericValue"&&Number.isInteger(R.value)],["iterable",R=>R instanceof Te||R instanceof We],["lower",R=>{const ee=R.value;return R.type==="StringValue"&&ee===ee.toLowerCase()}],["upper",R=>{const ee=R.value;return R.type==="StringValue"&&ee===ee.toUpperCase()}],["none",R=>R.type==="NullValue"],["defined",R=>R.type!=="UndefinedValue"],["undefined",R=>R.type==="UndefinedValue"],["equalto",(R,ee)=>R.value===ee.value],["eq",(R,ee)=>R.value===ee.value]]));this.parent=R}set(R,ee){return this.declareVariable(R,se(ee))}declareVariable(R,ee){if(this.variables.has(R))throw new SyntaxError(`Variable already declared: ${R}`);return this.variables.set(R,ee),ee}setVariable(R,ee){return this.variables.set(R,ee),ee}resolve(R){if(this.variables.has(R))return this;if(this.parent)return this.parent.resolve(R);throw new Error(`Unknown variable: ${R}`)}lookupVariable(R){try{return this.resolve(R).variables.get(R)??new A}catch{return new A}}},Pe=class{constructor(R){He(this,"global");this.global=R??new $e}run(R){return this.evaluate(R,this.global)}evaluateBinaryExpression(R,ee){const D=this.evaluate(R.left,ee);switch(R.operator.value){case"and":return D.__bool__().value?this.evaluate(R.right,ee):D;case"or":return D.__bool__().value?D:this.evaluate(R.right,ee)}const ue=this.evaluate(R.right,ee);switch(R.operator.value){case"==":return new st(D.value==ue.value);case"!=":return new st(D.value!=ue.value)}if(D instanceof A||ue instanceof A)throw new Error("Cannot perform operation on undefined values");if(D instanceof et||ue instanceof et)throw new Error("Cannot perform operation on null values");if(D instanceof Be&&ue instanceof Be)switch(R.operator.value){case"+":return new Be(D.value+ue.value);case"-":return new Be(D.value-ue.value);case"*":return new Be(D.value*ue.value);case"/":return new Be(D.value/ue.value);case"%":return new Be(D.value%ue.value);case"<":return new st(D.value":return new st(D.value>ue.value);case">=":return new st(D.value>=ue.value);case"<=":return new st(D.value<=ue.value)}else if(D instanceof Te&&ue instanceof Te)switch(R.operator.value){case"+":return new Te(D.value.concat(ue.value))}else if(ue instanceof Te){const le=ue.value.find(ke=>ke.value===D.value)!==void 0;switch(R.operator.value){case"in":return new st(le);case"not in":return new st(!le)}}if(D instanceof We||ue instanceof We)switch(R.operator.value){case"+":return new We(D.value.toString()+ue.value.toString())}if(D instanceof We&&ue instanceof We)switch(R.operator.value){case"in":return new st(ue.value.includes(D.value));case"not in":return new st(!ue.value.includes(D.value))}if(D instanceof We&&ue instanceof pt)switch(R.operator.value){case"in":return new st(ue.value.has(D.value));case"not in":return new st(!ue.value.has(D.value))}throw new SyntaxError(`Unknown operator "${R.operator.value}" between ${D.type} and ${ue.type}`)}evaluateArguments(R,ee){const D=[],ue=new Map;for(const le of R)if(le.type==="KeywordArgumentExpression"){const ke=le;ue.set(ke.key.value,this.evaluate(ke.value,ee))}else{if(ue.size>0)throw new Error("Positional arguments must come before keyword arguments");D.push(this.evaluate(le,ee))}return[D,ue]}evaluateFilterExpression(R,ee){const D=this.evaluate(R.operand,ee);if(R.filter.type==="Identifier"){const ue=R.filter;if(ue.value==="tojson")return new We(re(D));if(D instanceof Te)switch(ue.value){case"list":return D;case"first":return D.value[0];case"last":return D.value[D.value.length-1];case"length":return new Be(D.value.length);case"reverse":return new Te(D.value.reverse());case"sort":return new Te(D.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(D instanceof We)switch(ue.value){case"length":return new Be(D.value.length);case"upper":return new We(D.value.toUpperCase());case"lower":return new We(D.value.toLowerCase());case"title":return new We(Ke(D.value));case"capitalize":return new We(D.value.charAt(0).toUpperCase()+D.value.slice(1));case"trim":return new We(D.value.trim());case"indent":return new We(D.value.split(` +`).map((le,ke)=>ke===0||le.length===0?le:" "+le).join(` +`));case"string":return D;default:throw new Error(`Unknown StringValue filter: ${ue.value}`)}else if(D instanceof Be)switch(ue.value){case"abs":return new Be(Math.abs(D.value));default:throw new Error(`Unknown NumericValue filter: ${ue.value}`)}else if(D instanceof pt)switch(ue.value){case"items":return new Te(Array.from(D.value.entries()).map(([le,ke])=>new Te([new We(le),ke])));case"length":return new Be(D.value.size);default:throw new Error(`Unknown ObjectValue filter: ${ue.value}`)}throw new Error(`Cannot apply filter "${ue.value}" to type: ${D.type}`)}else if(R.filter.type==="CallExpression"){const ue=R.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,ee),Ne=ke.get("indent")??new et;if(!(Ne instanceof Be||Ne instanceof et))throw new Error("If set, indent must be a number");return new We(re(D,Ne.value))}if(D instanceof Te){switch(le){case"selectattr":{if(D.value.some(Z=>!(Z instanceof pt)))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,dt]=ue.args.map(Z=>this.evaluate(Z,ee));let Je;if(Ne){const Z=ee.tests.get(Ne.value);if(!Z)throw new Error(`Unknown test: ${Ne.value}`);Je=Z}else Je=(...Z)=>Z[0].__bool__().value;const Ve=D.value.filter(Z=>{const ve=Z.value.get(ke.value);return ve?Je(ve,dt):!1});return new Te(Ve)}case"map":{const[,ke]=this.evaluateArguments(ue.args,ee);if(ke.has("attribute")){const Ne=ke.get("attribute");if(!(Ne instanceof We))throw new Error("attribute must be a string");const dt=ke.get("default"),Je=D.value.map(Ve=>{if(!(Ve instanceof pt))throw new Error("items in map must be an object");return Ve.value.get(Ne.value)??dt??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(D instanceof We){switch(le){case"indent":{const[ke,Ne]=this.evaluateArguments(ue.args,ee),dt=ke.at(0)??Ne.get("width")??new Be(4);if(!(dt instanceof Be))throw new Error("width must be a number");const Je=ke.at(1)??Ne.get("first")??new st(!1),Ve=ke.at(2)??Ne.get("blank")??new st(!1),Z=D.value.split(` +`),ve=" ".repeat(dt.value),Re=Z.map((qe,Qe)=>!Je.value&&Qe===0||!Ve.value&&qe.length===0?qe:ve+qe);return new We(Re.join(` +`))}}throw new Error(`Unknown StringValue filter: ${le}`)}else throw new Error(`Cannot apply filter "${le}" to type: ${D.type}`)}throw new Error(`Unknown filter: ${R.filter.type}`)}evaluateTestExpression(R,ee){const D=this.evaluate(R.operand,ee),ue=ee.tests.get(R.test.value);if(!ue)throw new Error(`Unknown test: ${R.test.value}`);const le=ue(D);return new st(R.negate?!le:le)}evaluateUnaryExpression(R,ee){const D=this.evaluate(R.argument,ee);switch(R.operator.value){case"not":return new st(!D.value);default:throw new SyntaxError(`Unknown operator: ${R.operator.value}`)}}evalProgram(R,ee){return this.evaluateBlock(R.body,ee)}evaluateBlock(R,ee){let D="";for(const ue of R){const le=this.evaluate(ue,ee);le.type!=="NullValue"&&le.type!=="UndefinedValue"&&(D+=le.value)}return new We(D)}evaluateIdentifier(R,ee){return ee.lookupVariable(R.value)}evaluateCallExpression(R,ee){const[D,ue]=this.evaluateArguments(R.args,ee);ue.size>0&&D.push(new Ge(ue));const le=this.evaluate(R.callee,ee);if(le.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${le.type}`);return le.value(D,ee)}evaluateSliceExpression(R,ee,D){if(!(R instanceof Te||R instanceof We))throw new Error("Slice object must be an array or string");const ue=this.evaluate(ee.start,D),le=this.evaluate(ee.stop,D),ke=this.evaluate(ee.step,D);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 R instanceof Te?new Te(ge(R.value,ue.value,le.value,ke.value)):new We(ge(Array.from(R.value),ue.value,le.value,ke.value).join(""))}evaluateMemberExpression(R,ee){const D=this.evaluate(R.object,ee);let ue;if(R.computed){if(R.property.type==="SliceExpression")return this.evaluateSliceExpression(D,R.property,ee);ue=this.evaluate(R.property,ee)}else ue=new We(R.property.value);let le;if(D instanceof pt){if(!(ue instanceof We))throw new Error(`Cannot access property with non-string: got ${ue.type}`);le=D.value.get(ue.value)??D.builtins.get(ue.value)}else if(D instanceof Te||D instanceof We)if(ue instanceof Be)le=D.value.at(ue.value),D instanceof We&&(le=new We(D.value.at(ue.value)));else if(ue instanceof We)le=D.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=D.builtins.get(ue.value)}return le instanceof Le?le:new A}evaluateSet(R,ee){const D=this.evaluate(R.value,ee);if(R.assignee.type==="Identifier"){const ue=R.assignee.value;ee.setVariable(ue,D)}else if(R.assignee.type==="MemberExpression"){const ue=R.assignee,le=this.evaluate(ue.object,ee);if(!(le instanceof pt))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,D)}else throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(R.assignee)}`);return new et}evaluateIf(R,ee){const D=this.evaluate(R.test,ee);return this.evaluateBlock(D.__bool__().value?R.body:R.alternate,ee)}evaluateFor(R,ee){const D=new $e(ee);let ue,le;if(R.iterable.type==="SelectExpression"){const Ve=R.iterable;le=this.evaluate(Ve.iterable,D),ue=Ve.test}else le=this.evaluate(R.iterable,D);if(!(le instanceof Te))throw new Error(`Expected iterable type in for loop: got ${le.type}`);const ke=[],Ne=[];for(let Ve=0;Veqe.setVariable(R.loopvar.value,ve);else if(R.loopvar.type==="TupleLiteral"){const qe=R.loopvar;if(ve.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${ve.type}`);const Qe=ve;if(qe.value.length!==Qe.value.length)throw new Error(`Too ${qe.value.length>Qe.value.length?"few":"many"} items to unpack`);Re=tt=>{for(let ft=0;ft0?ke[Ve-1]:new A],["nextitem",Ve{var Ne;const le=new $e(ue);D=D.slice();let ke;((Ne=D.at(-1))==null?void 0:Ne.type)==="KeywordArgumentsValue"&&(ke=D.pop());for(let dt=0;dtthis.evaluate(D,ee)));case"TupleLiteral":return new je(R.value.map(D=>this.evaluate(D,ee)));case"ObjectLiteral":{const D=new Map;for(const[ue,le]of R.value){const ke=this.evaluate(ue,ee);if(!(ke instanceof We))throw new Error(`Object keys must be strings: got ${ke.type}`);D.set(ke.value,this.evaluate(le,ee))}return new pt(D)}case"Identifier":return this.evaluateIdentifier(R,ee);case"CallExpression":return this.evaluateCallExpression(R,ee);case"MemberExpression":return this.evaluateMemberExpression(R,ee);case"UnaryExpression":return this.evaluateUnaryExpression(R,ee);case"BinaryExpression":return this.evaluateBinaryExpression(R,ee);case"FilterExpression":return this.evaluateFilterExpression(R,ee);case"TestExpression":return this.evaluateTestExpression(R,ee);default:throw new SyntaxError(`Unknown node type: ${R.type}`)}}};function se(R){switch(typeof R){case"number":return new Be(R);case"string":return new We(R);case"boolean":return new st(R);case"undefined":return new A;case"object":return R===null?new et:Array.isArray(R)?new Te(R.map(se)):new pt(new Map(Object.entries(R).map(([ee,D])=>[ee,se(D)])));case"function":return new Ye((ee,D)=>{const ue=R(...ee.map(le=>le.value))??null;return se(ue)});default:throw new Error(`Cannot convert to runtime value: ${R}`)}}function re(R,ee,D){const ue=D??0;switch(R.type){case"NullValue":case"UndefinedValue":return"null";case"NumericValue":case"StringValue":case"BooleanValue":return JSON.stringify(R.value);case"ArrayValue":case"ObjectValue":{const le=ee?" ".repeat(ee):"",ke=` +`+le.repeat(ue),Ne=ke+le;if(R.type==="ArrayValue"){const dt=R.value.map(Je=>re(Je,ee,ue+1));return ee?`[${Ne}${dt.join(`,${Ne}`)}${ke}]`:`[${dt.join(", ")}]`}else{const dt=Array.from(R.value.entries()).map(([Je,Ve])=>{const Z=`"${Je}": ${re(Ve,ee,ue+1)}`;return ee?`${Ne}${Z}`:Z});return ee?`{${dt.join(",")}${ke}}`:`{${dt.join(", ")}}`}}default:throw new Error(`Cannot convert to JSON: ${R.type}`)}}var ye=class{constructor(R){He(this,"parsed");const ee=y(R,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=Me(ee)}render(R){const ee=new $e;ee.set("false",!1),ee.set("true",!0),ee.set("raise_exception",le=>{throw new Error(le)}),ee.set("range",Q);for(const[le,ke]of Object.entries(R))ee.set(le,ke);return new Pe(ee).run(this.parsed).value}}},"./node_modules/onnxruntime-common/dist/esm/backend-impl.js":(e,t,r)=>{r.r(t),r.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 y=o.get(h);if(y===void 0)o.set(h,{backend:g,priority:M});else{if(y.priority>M)return;if(y.priority===M&&y.backend!==g)throw new Error(`cannot register backend "${h}" using priority ${M}`)}if(M>=0){const E=a.indexOf(h);E!==-1&&a.splice(E,1);for(let T=0;T{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(y){return M||(g.error=`${y}`,g.aborted=!0),g.error}finally{delete g.initPromise}}},_=async h=>{const g=h.executionProviders||[],M=g.map(C=>typeof C=="string"?C:C.name),y=M.length===0?a:M;let E;const T=[],O=new Set;for(const C of y){const w=await p(C);typeof w=="string"?T.push({name:C,err:w}):(E||(E=w),E===w&&O.add(C))}if(!E)throw new Error(`no available backend found. ERR: ${T.map(C=>`[${C.name}] ${C.err}`).join(", ")}`);for(const{name:C,err:w}of T)M.includes(C)&&console.warn(`removing requested execution provider "${C}" from session options because it is not available: ${w}`);const S=g.filter(C=>O.has(typeof C=="string"?C:C.name));return[E,new Proxy(h,{get:(C,w)=>w==="executionProviders"?S:Reflect.get(C,w)})]}},"./node_modules/onnxruntime-common/dist/esm/backend.js":(e,t,r)=>{r.r(t),r.d(t,{registerBackend:()=>o.registerBackend});var o=r("./node_modules/onnxruntime-common/dist/esm/backend-impl.js")},"./node_modules/onnxruntime-common/dist/esm/env-impl.js":(e,t,r)=>{r.r(t),r.d(t,{env:()=>l});var o=r("./node_modules/onnxruntime-common/dist/esm/version.js");let a="warning";const l={wasm:{},webgl:{},webgpu:{},versions:{common:o.version},set logLevel(p){if(p!==void 0){if(typeof p!="string"||["verbose","info","warning","error","fatal"].indexOf(p)===-1)throw new Error(`Unsupported logging level: ${p}`);a=p}},get logLevel(){return a}};Object.defineProperty(l,"logLevel",{enumerable:!0})},"./node_modules/onnxruntime-common/dist/esm/env.js":(e,t,r)=>{r.r(t),r.d(t,{env:()=>a});var o=r("./node_modules/onnxruntime-common/dist/esm/env-impl.js");const a=o.env},"./node_modules/onnxruntime-common/dist/esm/index.js":(e,t,r)=>{r.r(t),r.d(t,{InferenceSession:()=>l.InferenceSession,TRACE:()=>_.TRACE,TRACE_FUNC_BEGIN:()=>_.TRACE_FUNC_BEGIN,TRACE_FUNC_END:()=>_.TRACE_FUNC_END,Tensor:()=>p.Tensor,TrainingSession:()=>h.TrainingSession,env:()=>a.env,registerBackend:()=>o.registerBackend});var o=r("./node_modules/onnxruntime-common/dist/esm/backend.js"),a=r("./node_modules/onnxruntime-common/dist/esm/env.js"),l=r("./node_modules/onnxruntime-common/dist/esm/inference-session.js"),p=r("./node_modules/onnxruntime-common/dist/esm/tensor.js");r("./node_modules/onnxruntime-common/dist/esm/tensor-conversion.js"),r("./node_modules/onnxruntime-common/dist/esm/tensor-factory.js");var _=r("./node_modules/onnxruntime-common/dist/esm/trace.js");r("./node_modules/onnxruntime-common/dist/esm/onnx-model.js"),r("./node_modules/onnxruntime-common/dist/esm/onnx-value.js");var h=r("./node_modules/onnxruntime-common/dist/esm/training-session.js")},"./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js":(e,t,r)=>{r.r(t),r.d(t,{InferenceSession:()=>p});var o=r("./node_modules/onnxruntime-common/dist/esm/backend-impl.js"),a=r("./node_modules/onnxruntime-common/dist/esm/tensor.js"),l=r("./node_modules/onnxruntime-common/dist/esm/trace.js");class p{constructor(h){this.handler=h}async run(h,g,M){(0,l.TRACE_FUNC_BEGIN)();const y={};let E={};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 T=!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.");T=!1;for(const C of g){if(typeof C!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(C)===-1)throw new RangeError(`'fetches' contains invalid output name: ${C}.`);y[C]=null}if(typeof M=="object"&&M!==null)E=M;else if(typeof M<"u")throw new TypeError("'options' must be an object.")}else{let C=!1;const w=Object.getOwnPropertyNames(g);for(const b of this.outputNames)if(w.indexOf(b)!==-1){const I=g[b];(I===null||I instanceof a.Tensor)&&(C=!0,T=!1,y[b]=I)}if(C){if(typeof M=="object"&&M!==null)E=M;else if(typeof M<"u")throw new TypeError("'options' must be an object.")}else E=g}}else if(typeof g<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const C of this.inputNames)if(typeof h[C]>"u")throw new Error(`input '${C}' is missing in 'feeds'.`);if(T)for(const C of this.outputNames)y[C]=null;const O=await this.handler.run(h,y,E),S={};for(const C in O)if(Object.hasOwnProperty.call(O,C)){const w=O[C];w instanceof a.Tensor?S[C]=w:S[C]=new a.Tensor(w.type,w.data,w.dims)}return(0,l.TRACE_FUNC_END)(),S}async release(){return this.handler.dispose()}static async create(h,g,M,y){(0,l.TRACE_FUNC_BEGIN)();let E,T={};if(typeof h=="string"){if(E=h,typeof g=="object"&&g!==null)T=g;else if(typeof g<"u")throw new TypeError("'options' must be an object.")}else if(h instanceof Uint8Array){if(E=h,typeof g=="object"&&g!==null)T=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 w=h;let b=0,I=h.byteLength;if(typeof g=="object"&&g!==null)T=g;else if(typeof g=="number"){if(b=g,!Number.isSafeInteger(b))throw new RangeError("'byteOffset' must be an integer.");if(b<0||b>=w.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${w.byteLength}).`);if(I=h.byteLength-b,typeof M=="number"){if(I=M,!Number.isSafeInteger(I))throw new RangeError("'byteLength' must be an integer.");if(I<=0||b+I>w.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${w.byteLength-b}].`);if(typeof y=="object"&&y!==null)T=y;else if(typeof y<"u")throw new TypeError("'options' must be an object.")}else if(typeof M<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof g<"u")throw new TypeError("'options' must be an object.");E=new Uint8Array(w,b,I)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");const[O,S]=await(0,o.resolveBackendAndExecutionProviders)(T),C=await O.createInferenceSessionHandler(E,S);return(0,l.TRACE_FUNC_END)(),new p(C)}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,r)=>{r.r(t),r.d(t,{InferenceSession:()=>a});var o=r("./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,r)=>{r.r(t)},"./node_modules/onnxruntime-common/dist/esm/onnx-value.js":(e,t,r)=>{r.r(t)},"./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js":(e,t,r)=>{r.r(t),r.d(t,{tensorToDataURL:()=>o,tensorToImageData:()=>a});const o=(l,p)=>{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;(p==null?void 0:p.tensorLayout)!==void 0&&p.tensorLayout==="NHWC"?(g=l.dims[2],M=l.dims[3]):(g=l.dims[3],M=l.dims[2]);const y=(p==null?void 0:p.format)!==void 0?p.format:"RGB",E=p==null?void 0:p.norm;let T,O;E===void 0||E.mean===void 0?T=[255,255,255,255]:typeof E.mean=="number"?T=[E.mean,E.mean,E.mean,E.mean]:(T=[E.mean[0],E.mean[1],E.mean[2],0],E.mean[3]!==void 0&&(T[3]=E.mean[3])),E===void 0||E.bias===void 0?O=[0,0,0,0]:typeof E.bias=="number"?O=[E.bias,E.bias,E.bias,E.bias]:(O=[E.bias[0],E.bias[1],E.bias[2],0],E.bias[3]!==void 0&&(O[3]=E.bias[3]));const S=M*g;let C=0,w=S,b=S*2,I=-1;y==="RGBA"?(C=0,w=S,b=S*2,I=S*3):y==="RGB"?(C=0,w=S,b=S*2):y==="RBG"&&(C=0,b=S,w=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,y;(p==null?void 0:p.tensorLayout)!==void 0&&p.tensorLayout==="NHWC"?(g=l.dims[2],M=l.dims[1],y=l.dims[3]):(g=l.dims[3],M=l.dims[2],y=l.dims[1]);const E=p!==void 0&&p.format!==void 0?p.format:"RGB",T=p==null?void 0:p.norm;let O,S;T===void 0||T.mean===void 0?O=[255,255,255,255]:typeof T.mean=="number"?O=[T.mean,T.mean,T.mean,T.mean]:(O=[T.mean[0],T.mean[1],T.mean[2],255],T.mean[3]!==void 0&&(O[3]=T.mean[3])),T===void 0||T.bias===void 0?S=[0,0,0,0]:typeof T.bias=="number"?S=[T.bias,T.bias,T.bias,T.bias]:(S=[T.bias[0],T.bias[1],T.bias[2],0],T.bias[3]!==void 0&&(S[3]=T.bias[3]));const C=M*g;if(p!==void 0&&(p.format!==void 0&&y===4&&p.format!=="RGBA"||y===3&&p.format!=="RGB"&&p.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");const w=4;let b=0,I=1,U=2,z=3,B=0,j=C,N=C*2,ae=-1;E==="RGBA"?(B=0,j=C,N=C*2,ae=C*3):E==="RGB"?(B=0,j=C,N=C*2):E==="RBG"&&(B=0,N=C,j=C*2),h=_.createImageData(g,M);for(let ce=0;ce{r.r(t)},"./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js":(e,t,r)=>{r.r(t),r.d(t,{bufferToTensor:()=>a,tensorFromGpuBuffer:()=>_,tensorFromImage:()=>l,tensorFromPinnedBuffer:()=>h,tensorFromTexture:()=>p});var o=r("./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:y,width:E}=M,T=M.norm??{mean:255,bias:0};let O,S;typeof T.mean=="number"?O=[T.mean,T.mean,T.mean,T.mean]:O=[T.mean[0],T.mean[1],T.mean[2],T.mean[3]??255],typeof T.bias=="number"?S=[T.bias,T.bias,T.bias,T.bias]:S=[T.bias[0],T.bias[1],T.bias[2],T.bias[3]??0];const C=M.format!==void 0?M.format:"RGBA",w=M.tensorFormat!==void 0&&M.tensorFormat!==void 0?M.tensorFormat:"RGB",b=y*E,I=w==="RGBA"?new Float32Array(b*4):new Float32Array(b*3);let U=4,z=0,B=1,j=2,N=3,ae=0,ce=b,xe=b*2,Y=-1;C==="RGB"&&(U=3,z=0,B=1,j=2,N=-1),w==="RGBA"?Y=b*3:w==="RBG"?(ae=0,xe=b,ce=b*2):w==="BGR"&&(xe=0,ce=b,ae=b*2);for(let L=0;L{const y=typeof HTMLImageElement<"u"&&g instanceof HTMLImageElement,E=typeof ImageData<"u"&&g instanceof ImageData,T=typeof ImageBitmap<"u"&&g instanceof ImageBitmap,O=typeof g=="string";let S,C=M??{};const w=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},b=I=>I instanceof HTMLCanvasElement||I instanceof OffscreenCanvas?I.getContext("2d"):null;if(y){const I=w();I.width=g.width,I.height=g.height;const U=b(I);if(U!=null){let z=g.height,B=g.width;if(M!==void 0&&M.resizedHeight!==void 0&&M.resizedWidth!==void 0&&(z=M.resizedHeight,B=M.resizedWidth),M!==void 0){if(C=M,M.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");C.tensorFormat="RGBA",C.height=z,C.width=B}else C.tensorFormat="RGBA",C.height=z,C.width=B;U.drawImage(g,0,0),S=U.getImageData(0,0,B,z).data}else throw new Error("Can not access image data")}else if(E){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&&(C=M),C.format="RGBA",C.height=I,C.width=U,M!==void 0){const z=w();z.width=U,z.height=I;const B=b(z);if(B!=null)B.putImageData(g,0,0),S=B.getImageData(0,0,U,I).data;else throw new Error("Can not access image data")}else S=g.data}else if(T){if(M===void 0)throw new Error("Please provide image config with format for Imagebitmap");const I=w();I.width=g.width,I.height=g.height;const U=b(I);if(U!=null){const z=g.height,B=g.width;return U.drawImage(g,0,0,B,z),S=U.getImageData(0,0,B,z).data,C.height=z,C.width=B,a(S,C)}else throw new Error("Can not access image data")}else{if(O)return new Promise((I,U)=>{const z=w(),B=b(z);if(!g||!B)return U();const j=new Image;j.crossOrigin="Anonymous",j.src=g,j.onload=()=>{z.width=j.width,z.height=j.height,B.drawImage(j,0,0,z.width,z.height);const N=B.getImageData(0,0,z.width,z.height);C.height=z.height,C.width=z.width,I(a(N.data,C))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(S!==void 0)return a(S,C);throw new Error("Input data provided is not supported - aborted tensor creation")},p=(g,M)=>{const{width:y,height:E,download:T,dispose:O}=M,S=[1,E,y,4];return new o.Tensor({location:"texture",type:"float32",texture:g,dims:S,download:T,dispose:O})},_=(g,M)=>{const{dataType:y,dims:E,download:T,dispose:O}=M;return new o.Tensor({location:"gpu-buffer",type:y??"float32",gpuBuffer:g,dims:E,download:T,dispose:O})},h=(g,M,y)=>new o.Tensor({location:"cpu-pinned",type:g,data:M,dims:y??[M.length]})},"./node_modules/onnxruntime-common/dist/esm/tensor-factory.js":(e,t,r)=>{r.r(t)},"./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js":(e,t,r)=>{r.r(t),r.d(t,{NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP:()=>a,NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP:()=>o,checkTypedArray:()=>p});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 p=()=>{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,r)=>{r.r(t),r.d(t,{Tensor:()=>_});var o=r("./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js"),a=r("./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js"),l=r("./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js"),p=r("./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js");class _{constructor(g,M,y){(0,l.checkTypedArray)();let E,T;if(typeof g=="object"&&"location"in g)switch(this.dataLocation=g.location,E=g.type,T=g.dims,g.location){case"cpu-pinned":{const S=l.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(E);if(!S)throw new TypeError(`unsupported type "${E}" 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(E!=="float32")throw new TypeError(`unsupported type "${E}" to create tensor from texture`);this.gpuTextureData=g.texture,this.downloader=g.download,this.disposer=g.dispose;break}case"gpu-buffer":{if(E!=="float32"&&E!=="float16"&&E!=="int32"&&E!=="int64"&&E!=="uint32"&&E!=="uint8"&&E!=="bool")throw new TypeError(`unsupported type "${E}" 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,C;if(typeof g=="string")if(E=g,C=y,g==="string"){if(!Array.isArray(M))throw new TypeError("A string tensor's data must be a string array.");S=M}else{const w=l.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(g);if(w===void 0)throw new TypeError(`Unsupported tensor type: ${g}.`);if(Array.isArray(M)){if(g==="float16"&&w===Uint16Array)throw new TypeError("Creating a float16 tensor from number array is not supported. Please use Uint16Array as data.");g==="uint64"||g==="int64"?S=w.from(M,BigInt):S=w.from(M)}else if(M instanceof w)S=M;else throw new TypeError(`A ${E} tensor's data must be type of ${w}`)}else if(C=M,Array.isArray(g)){if(g.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");const w=typeof g[0];if(w==="string")E="string",S=g;else if(w==="boolean")E="bool",S=Uint8Array.from(g);else throw new TypeError(`Invalid element type of data array: ${w}.`)}else{const w=l.NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.get(g.constructor);if(w===void 0)throw new TypeError(`Unsupported type for tensor data: ${g.constructor}.`);E=w,S=g}if(C===void 0)C=[S.length];else if(!Array.isArray(C))throw new TypeError("A tensor's dims must be a number array");T=C,this.cpuData=S,this.dataLocation="cpu"}const O=(0,p.calculateSize)(T);if(this.cpuData&&O!==this.cpuData.length)throw new Error(`Tensor's size(${O}) does not match data length(${this.cpuData.length}).`);this.type=E,this.dims=T,this.size=O}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,y){return(0,a.tensorFromPinnedBuffer)(g,M,y)}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,p.tensorReshape)(this,g)}}},"./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js":(e,t,r)=>{r.r(t),r.d(t,{calculateSize:()=>a,tensorReshape:()=>l});var o=r("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const a=p=>{let _=1;for(let h=0;h{switch(p.location){case"cpu":return new o.Tensor(p.type,p.data,_);case"cpu-pinned":return new o.Tensor({location:"cpu-pinned",data:p.data,type:p.type,dims:_});case"texture":return new o.Tensor({location:"texture",texture:p.texture,type:p.type,dims:_});case"gpu-buffer":return new o.Tensor({location:"gpu-buffer",gpuBuffer:p.gpuBuffer,type:p.type,dims:_});default:throw new Error(`tensorReshape: tensor location ${p.location} is not supported`)}}},"./node_modules/onnxruntime-common/dist/esm/tensor.js":(e,t,r)=>{r.r(t),r.d(t,{Tensor:()=>a});var o=r("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const a=o.Tensor},"./node_modules/onnxruntime-common/dist/esm/trace.js":(e,t,r)=>{r.r(t),r.d(t,{TRACE:()=>a,TRACE_FUNC_BEGIN:()=>p,TRACE_FUNC_END:()=>_});var o=r("./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 E;const M=((E=new Error().stack)==null?void 0:E.split(/\r\n|\r|\n/g))||[];let y=!1;for(let T=0;T{(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,r)=>{r.r(t),r.d(t,{TrainingSession:()=>p});var o=r("./node_modules/onnxruntime-common/dist/esm/backend-impl.js"),a=r("./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 p{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||"",y=h.optimizerModel||"",E=g||{},[T,O]=await(0,o.resolveBackendAndExecutionProviders)(E);if(T.createTrainingSessionHandler){const S=await T.createTrainingSessionHandler(h.checkpointState,h.trainModel,M,y,O);return new p(S,!!h.optimizerModel,!!h.evalModel)}else throw new Error(l)}typeNarrowingForRunStep(h,g,M,y,E){const T={};let O={};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 y=="object"){if(y===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(y instanceof a.Tensor)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(y)){if(y.length===0)throw new TypeError("'fetches' cannot be an empty array.");S=!1;for(const C of y){if(typeof C!="string")throw new TypeError("'fetches' must be a string array or an object.");if(g.indexOf(C)===-1)throw new RangeError(`'fetches' contains invalid output name: ${C}.`);T[C]=null}if(typeof E=="object"&&E!==null)O=E;else if(typeof E<"u")throw new TypeError("'options' must be an object.")}else{let C=!1;const w=Object.getOwnPropertyNames(y);for(const b of g)if(w.indexOf(b)!==-1){const I=y[b];(I===null||I instanceof a.Tensor)&&(C=!0,S=!1,T[b]=I)}if(C){if(typeof E=="object"&&E!==null)O=E;else if(typeof E<"u")throw new TypeError("'options' must be an object.")}else O=y}}else if(typeof y<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const C of h)if(typeof M[C]>"u")throw new Error(`input '${C}' is missing in 'feeds'.`);if(S)for(const C of g)T[C]=null;return[T,O]}convertHandlerReturnTypeToMapOfTensors(h){const g={};for(const M in h)if(Object.hasOwnProperty.call(h,M)){const y=h[M];y instanceof a.Tensor?g[M]=y:g[M]=new a.Tensor(y.type,y.data,y.dims)}return g}async lazyResetGrad(){await this.handler.lazyResetGrad()}async runTrainStep(h,g,M){const[y,E]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,h,g,M),T=await this.handler.runTrainStep(h,y,E);return this.convertHandlerReturnTypeToMapOfTensors(T)}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[y,E]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,h,g,M),T=await this.handler.runEvalStep(h,y,E);return this.convertHandlerReturnTypeToMapOfTensors(T)}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,r)=>{r.r(t),r.d(t,{TrainingSession:()=>a});var o=r("./node_modules/onnxruntime-common/dist/esm/training-session-impl.js");const a=o.TrainingSession},"./node_modules/onnxruntime-common/dist/esm/version.js":(e,t,r)=>{r.r(t),r.d(t,{version:()=>o});const o="1.18.0"},"./node_modules/onnxruntime-web/dist/ort.webgpu.bundle.min.mjs":(e,t,r)=>{r.r(t),r.d(t,{InferenceSession:()=>re,TRACE:()=>je,TRACE_FUNC_BEGIN:()=>et,TRACE_FUNC_END:()=>A,Tensor:()=>Ge,TrainingSession:()=>dt,default:()=>wx,env:()=>N,registerBackend:()=>O});/*! + * ONNX Runtime Web v1.19.0 + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */var o=Object.defineProperty,a=Object.getOwnPropertyDescriptor,l=Object.getOwnPropertyNames,p=Object.prototype.hasOwnProperty,_=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(i,s)=>(typeof require<"u"?require:i)[s]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')}),h=(n,i)=>()=>(n&&(i=n(n=0)),i),g=(n,i)=>{for(var s in i)o(n,s,{get:i[s],enumerable:!0})},M=(n,i,s,u)=>{if(i&&typeof i=="object"||typeof i=="function")for(let c of l(i))!p.call(n,c)&&c!==s&&o(n,c,{get:()=>i[c],enumerable:!(u=a(i,c))||u.enumerable});return n},y=n=>M(o({},"__esModule",{value:!0}),n),E,T,O,S,C,w=h(()=>{E=new Map,T=[],O=(n,i,s)=>{if(i&&typeof i.init=="function"&&typeof i.createInferenceSessionHandler=="function"){let u=E.get(n);if(u===void 0)E.set(n,{backend:i,priority:s});else{if(u.priority>s)return;if(u.priority===s&&u.backend!==i)throw new Error(`cannot register backend "${n}" using priority ${s}`)}if(s>=0){let c=T.indexOf(n);c!==-1&&T.splice(c,1);for(let f=0;f{let i=E.get(n);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(n)),await i.initPromise,i.initialized=!0,i.backend}catch(u){return s||(i.error=`${u}`,i.aborted=!0),i.error}finally{delete i.initPromise}}},C=async n=>{let i=n.executionProviders||[],s=i.map(k=>typeof k=="string"?k:k.name),u=s.length===0?T:s,c,f=[],d=new Set;for(let k of u){let $=await S(k);typeof $=="string"?f.push({name:k,err:$}):(c||(c=$),c===$&&d.add(k))}if(!c)throw new Error(`no available backend found. ERR: ${f.map(k=>`[${k.name}] ${k.err}`).join(", ")}`);for(let{name:k,err:$}of f)s.includes(k)&&console.warn(`removing requested execution provider "${k}" from session options because it is not available: ${$}`);let x=i.filter(k=>d.has(typeof k=="string"?k:k.name));return[c,new Proxy(n,{get:(k,$)=>$==="executionProviders"?x:Reflect.get(k,$)})]}}),b=h(()=>{w()}),I,U=h(()=>{I="1.19.0"}),z,B,j=h(()=>{U(),z="warning",B={wasm:{},webgl:{},webgpu:{},versions:{common:I},set logLevel(n){if(n!==void 0){if(typeof n!="string"||["verbose","info","warning","error","fatal"].indexOf(n)===-1)throw new Error(`Unsupported logging level: ${n}`);z=n}},get logLevel(){return z}},Object.defineProperty(B,"logLevel",{enumerable:!0})}),N,ae=h(()=>{j(),N=B}),ce,xe,Y=h(()=>{ce=(n,i)=>{let s=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);s.width=n.dims[3],s.height=n.dims[2];let u=s.getContext("2d");if(u!=null){let c,f;(i==null?void 0:i.tensorLayout)!==void 0&&i.tensorLayout==="NHWC"?(c=n.dims[2],f=n.dims[3]):(c=n.dims[3],f=n.dims[2]);let d=(i==null?void 0:i.format)!==void 0?i.format:"RGB",x=i==null?void 0:i.norm,k,$;x===void 0||x.mean===void 0?k=[255,255,255,255]:typeof x.mean=="number"?k=[x.mean,x.mean,x.mean,x.mean]:(k=[x.mean[0],x.mean[1],x.mean[2],0],x.mean[3]!==void 0&&(k[3]=x.mean[3])),x===void 0||x.bias===void 0?$=[0,0,0,0]:typeof x.bias=="number"?$=[x.bias,x.bias,x.bias,x.bias]:($=[x.bias[0],x.bias[1],x.bias[2],0],x.bias[3]!==void 0&&($[3]=x.bias[3]));let H=f*c,q=0,v=H,oe=H*2,te=-1;d==="RGBA"?(q=0,v=H,oe=H*2,te=H*3):d==="RGB"?(q=0,v=H,oe=H*2):d==="RBG"&&(q=0,oe=H,v=H*2);for(let de=0;de{let s=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),u;if(s!=null){let c,f,d;(i==null?void 0:i.tensorLayout)!==void 0&&i.tensorLayout==="NHWC"?(c=n.dims[2],f=n.dims[1],d=n.dims[3]):(c=n.dims[3],f=n.dims[2],d=n.dims[1]);let x=i!==void 0&&i.format!==void 0?i.format:"RGB",k=i==null?void 0:i.norm,$,H;k===void 0||k.mean===void 0?$=[255,255,255,255]:typeof k.mean=="number"?$=[k.mean,k.mean,k.mean,k.mean]:($=[k.mean[0],k.mean[1],k.mean[2],255],k.mean[3]!==void 0&&($[3]=k.mean[3])),k===void 0||k.bias===void 0?H=[0,0,0,0]:typeof k.bias=="number"?H=[k.bias,k.bias,k.bias,k.bias]:(H=[k.bias[0],k.bias[1],k.bias[2],0],k.bias[3]!==void 0&&(H[3]=k.bias[3]));let q=f*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,oe=0,te=1,de=2,we=3,be=0,he=q,De=q*2,Ae=-1;x==="RGBA"?(be=0,he=q,De=q*2,Ae=q*3):x==="RGB"?(be=0,he=q,De=q*2):x==="RBG"&&(be=0,De=q,he=q*2),u=s.createImageData(c,f);for(let Ie=0;Ie{pt(),_e=(n,i)=>{if(n===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},f,d;typeof c.mean=="number"?f=[c.mean,c.mean,c.mean,c.mean]:f=[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 x=i.format!==void 0?i.format:"RGBA",k=i.tensorFormat!==void 0&&i.tensorFormat!==void 0?i.tensorFormat:"RGB",$=s*u,H=k==="RGBA"?new Float32Array($*4):new Float32Array($*3),q=4,v=0,oe=1,te=2,de=3,we=0,be=$,he=$*2,De=-1;x==="RGB"&&(q=3,v=0,oe=1,te=2,de=-1),k==="RGBA"?De=$*3:k==="RBG"?(we=0,he=$,be=$*2):k==="BGR"&&(he=0,be=$,we=$*2);for(let Ae=0;Ae<$;Ae++,v+=q,te+=q,oe+=q,de+=q)H[we++]=(n[v]+d[0])/f[0],H[be++]=(n[oe]+d[1])/f[1],H[he++]=(n[te]+d[2])/f[2],De!==-1&&de!==-1&&(H[De++]=(n[de]+d[3])/f[3]);return k==="RGBA"?new st("float32",H,[1,4,s,u]):new st("float32",H,[1,3,s,u])},L=async(n,i)=>{let s=typeof HTMLImageElement<"u"&&n instanceof HTMLImageElement,u=typeof ImageData<"u"&&n instanceof ImageData,c=typeof ImageBitmap<"u"&&n instanceof ImageBitmap,f=typeof n=="string",d,x=i??{},k=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},$=H=>H instanceof HTMLCanvasElement||H instanceof OffscreenCanvas?H.getContext("2d"):null;if(s){let H=k();H.width=n.width,H.height=n.height;let q=$(H);if(q!=null){let v=n.height,oe=n.width;if(i!==void 0&&i.resizedHeight!==void 0&&i.resizedWidth!==void 0&&(v=i.resizedHeight,oe=i.resizedWidth),i!==void 0){if(x=i,i.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");x.tensorFormat="RGBA",x.height=v,x.width=oe}else x.tensorFormat="RGBA",x.height=v,x.width=oe;q.drawImage(n,0,0),d=q.getImageData(0,0,oe,v).data}else throw new Error("Can not access image data")}else if(u){let H,q;if(i!==void 0&&i.resizedWidth!==void 0&&i.resizedHeight!==void 0?(H=i.resizedHeight,q=i.resizedWidth):(H=n.height,q=n.width),i!==void 0&&(x=i),x.format="RGBA",x.height=H,x.width=q,i!==void 0){let v=k();v.width=q,v.height=H;let oe=$(v);if(oe!=null)oe.putImageData(n,0,0),d=oe.getImageData(0,0,q,H).data;else throw new Error("Can not access image data")}else d=n.data}else if(c){if(i===void 0)throw new Error("Please provide image config with format for Imagebitmap");let H=k();H.width=n.width,H.height=n.height;let q=$(H);if(q!=null){let v=n.height,oe=n.width;return q.drawImage(n,0,0,oe,v),d=q.getImageData(0,0,oe,v).data,x.height=v,x.width=oe,_e(d,x)}else throw new Error("Can not access image data")}else{if(f)return new Promise((H,q)=>{let v=k(),oe=$(v);if(!n||!oe)return q();let te=new Image;te.crossOrigin="Anonymous",te.src=n,te.onload=()=>{v.width=te.width,v.height=te.height,oe.drawImage(te,0,0,v.width,v.height);let de=oe.getImageData(0,0,v.width,v.height);x.height=v.height,x.width=v.width,H(_e(de.data,x))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(d!==void 0)return _e(d,x);throw new Error("Input data provided is not supported - aborted tensor creation")},Se=(n,i)=>{let{width:s,height:u,download:c,dispose:f}=i,d=[1,u,s,4];return new st({location:"texture",type:"float32",texture:n,dims:d,download:c,dispose:f})},Xe=(n,i)=>{let{dataType:s,dims:u,download:c,dispose:f}=i;return new st({location:"gpu-buffer",type:s??"float32",gpuBuffer:n,dims:u,download:c,dispose:f})},me=(n,i,s)=>new st({location:"cpu-pinned",type:n,data:i,dims:s??[i.length]})}),ie,Me,Q,ge,Ke=h(()=>{ie=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array]]),Me=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),Q=!1,ge=()=>{if(!Q){Q=!0;let n=typeof BigInt64Array<"u"&&BigInt64Array.from,i=typeof BigUint64Array<"u"&&BigUint64Array.from,s=typeof Float16Array<"u"&&Float16Array.from;n&&(ie.set("int64",BigInt64Array),Me.set(BigInt64Array,"int64")),i&&(ie.set("uint64",BigUint64Array),Me.set(BigUint64Array,"uint64")),s?(ie.set("float16",Float16Array),Me.set(Float16Array,"float16")):ie.set("float16",Uint16Array)}}}),Le,Be,We=h(()=>{pt(),Le=n=>{let i=1;for(let s=0;s{switch(n.location){case"cpu":return new st(n.type,n.data,i);case"cpu-pinned":return new st({location:"cpu-pinned",data:n.data,type:n.type,dims:i});case"texture":return new st({location:"texture",texture:n.texture,type:n.type,dims:i});case"gpu-buffer":return new st({location:"gpu-buffer",gpuBuffer:n.gpuBuffer,type:n.type,dims:i});default:throw new Error(`tensorReshape: tensor location ${n.location} is not supported`)}}}),st,pt=h(()=>{Y(),X(),Ke(),We(),st=class{constructor(n,i,s){ge();let u,c;if(typeof n=="object"&&"location"in n)switch(this.dataLocation=n.location,u=n.type,c=n.dims,n.location){case"cpu-pinned":{let d=ie.get(u);if(!d)throw new TypeError(`unsupported type "${u}" to create tensor from pinned buffer`);if(!(n.data instanceof d))throw new TypeError(`buffer should be of type ${d.name}`);this.cpuData=n.data;break}case"texture":{if(u!=="float32")throw new TypeError(`unsupported type "${u}" to create tensor from texture`);this.gpuTextureData=n.texture,this.downloader=n.download,this.disposer=n.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=n.gpuBuffer,this.downloader=n.download,this.disposer=n.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let d,x;if(typeof n=="string")if(u=n,x=s,n==="string"){if(!Array.isArray(i))throw new TypeError("A string tensor's data must be a string array.");d=i}else{let k=ie.get(n);if(k===void 0)throw new TypeError(`Unsupported tensor type: ${n}.`);if(Array.isArray(i)){if(n==="float16"&&k===Uint16Array)throw new TypeError("Creating a float16 tensor from number array is not supported. Please use Uint16Array as data.");n==="uint64"||n==="int64"?d=k.from(i,BigInt):d=k.from(i)}else if(i instanceof k)d=i;else throw new TypeError(`A ${u} tensor's data must be type of ${k}`)}else if(x=i,Array.isArray(n)){if(n.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let k=typeof n[0];if(k==="string")u="string",d=n;else if(k==="boolean")u="bool",d=Uint8Array.from(n);else throw new TypeError(`Invalid element type of data array: ${k}.`)}else{let k=Me.get(n.constructor);if(k===void 0)throw new TypeError(`Unsupported type for tensor data: ${n.constructor}.`);u=k,d=n}if(x===void 0)x=[d.length];else if(!Array.isArray(x))throw new TypeError("A tensor's dims must be a number array");c=x,this.cpuData=d,this.dataLocation="cpu"}let f=Le(c);if(this.cpuData&&f!==this.cpuData.length)throw new Error(`Tensor's size(${f}) does not match data length(${this.cpuData.length}).`);this.type=u,this.dims=c,this.size=f}static async fromImage(n,i){return L(n,i)}static fromTexture(n,i){return Se(n,i)}static fromGpuBuffer(n,i){return Xe(n,i)}static fromPinnedBuffer(n,i,s){return me(n,i,s)}toDataURL(n){return ce(this,n)}toImageData(n){return xe(this,n)}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(n){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,n&&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(n){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return Be(this,n)}}}),Ge,Te=h(()=>{pt(),Ge=st}),je,Ye,et,A,$e=h(()=>{j(),je=(n,i)=>{(typeof B.trace>"u"?!B.wasm.trace:!B.trace)||console.timeStamp(`${n}::ORT::${i}`)},Ye=(n,i)=>{var c;let s=((c=new Error().stack)==null?void 0:c.split(/\r\n|\r|\n/g))||[],u=!1;for(let f=0;f{(typeof B.trace>"u"?!B.wasm.trace:!B.trace)||Ye("BEGIN",n)},A=n=>{(typeof B.trace>"u"?!B.wasm.trace:!B.trace)||Ye("END",n)}}),Pe,se=h(()=>{w(),Te(),$e(),Pe=class Z2{constructor(i){this.handler=i}async run(i,s,u){et();let c={},f={};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 $ of s){if(typeof $!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf($)===-1)throw new RangeError(`'fetches' contains invalid output name: ${$}.`);c[$]=null}if(typeof u=="object"&&u!==null)f=u;else if(typeof u<"u")throw new TypeError("'options' must be an object.")}else{let $=!1,H=Object.getOwnPropertyNames(s);for(let q of this.outputNames)if(H.indexOf(q)!==-1){let v=s[q];(v===null||v instanceof Ge)&&($=!0,d=!1,c[q]=v)}if($){if(typeof u=="object"&&u!==null)f=u;else if(typeof u<"u")throw new TypeError("'options' must be an object.")}else f=s}}else if(typeof s<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let $ of this.inputNames)if(typeof i[$]>"u")throw new Error(`input '${$}' is missing in 'feeds'.`);if(d)for(let $ of this.outputNames)c[$]=null;let x=await this.handler.run(i,c,f),k={};for(let $ in x)if(Object.hasOwnProperty.call(x,$)){let H=x[$];H instanceof Ge?k[$]=H:k[$]=new Ge(H.type,H.data,H.dims)}return A(),k}async release(){return this.handler.dispose()}static async create(i,s,u,c){et();let f,d={};if(typeof i=="string"){if(f=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(f=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 H=i,q=0,v=i.byteLength;if(typeof s=="object"&&s!==null)d=s;else if(typeof s=="number"){if(q=s,!Number.isSafeInteger(q))throw new RangeError("'byteOffset' must be an integer.");if(q<0||q>=H.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${H.byteLength}).`);if(v=i.byteLength-q,typeof u=="number"){if(v=u,!Number.isSafeInteger(v))throw new RangeError("'byteLength' must be an integer.");if(v<=0||q+v>H.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${H.byteLength-q}].`);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.");f=new Uint8Array(H,q,v)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[x,k]=await C(d),$=await x.createInferenceSessionHandler(f,k);return A(),new Z2($)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}}),re,ye=h(()=>{se(),re=Pe}),R=h(()=>{}),ee=h(()=>{}),D=h(()=>{}),ue=h(()=>{}),le,ke,Ne=h(()=>{w(),Te(),le="Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.",ke=class J2{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||"",f=s||{},[d,x]=await C(f);if(d.createTrainingSessionHandler){let k=await d.createTrainingSessionHandler(i.checkpointState,i.trainModel,u,c,x);return new J2(k,!!i.optimizerModel,!!i.evalModel)}else throw new Error(le)}typeNarrowingForRunStep(i,s,u,c,f){let d={},x={};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 k=!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.");k=!1;for(let $ of c){if(typeof $!="string")throw new TypeError("'fetches' must be a string array or an object.");if(s.indexOf($)===-1)throw new RangeError(`'fetches' contains invalid output name: ${$}.`);d[$]=null}if(typeof f=="object"&&f!==null)x=f;else if(typeof f<"u")throw new TypeError("'options' must be an object.")}else{let $=!1,H=Object.getOwnPropertyNames(c);for(let q of s)if(H.indexOf(q)!==-1){let v=c[q];(v===null||v instanceof Ge)&&($=!0,k=!1,d[q]=v)}if($){if(typeof f=="object"&&f!==null)x=f;else if(typeof f<"u")throw new TypeError("'options' must be an object.")}else x=c}}else if(typeof c<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let $ of i)if(typeof u[$]>"u")throw new Error(`input '${$}' is missing in 'feeds'.`);if(k)for(let $ of s)d[$]=null;return[d,x]}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,f]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,i,s,u),d=await this.handler.runTrainStep(i,c,f);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,f]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,i,s,u),d=await this.handler.runEvalStep(i,c,f);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()}}}),dt,Je=h(()=>{Ne(),dt=ke}),Ve={};g(Ve,{InferenceSession:()=>re,TRACE:()=>je,TRACE_FUNC_BEGIN:()=>et,TRACE_FUNC_END:()=>A,Tensor:()=>Ge,TrainingSession:()=>dt,env:()=>N,registerBackend:()=>O});var Z=h(()=>{b(),ae(),ye(),Te(),R(),ee(),$e(),D(),ue(),Je()}),ve=h(()=>{}),Re={};g(Re,{default:()=>tt});var qe,Qe,tt,ft=h(()=>{var n;xw(),wn(),Yr(),qe="ort-wasm-proxy-worker",Qe=((n=globalThis.self)==null?void 0:n.name)===qe,Qe&&(self.onmessage=i=>{let{type:s,in:u}=i.data;try{switch(s){case"init-wasm":Mi(u.wasm).then(()=>{xm(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:f}=u;Mm(f,c).then(()=>{postMessage({type:s})},d=>{postMessage({type:s,err:d})});break}case"copy-from":{let{buffer:c}=u,f=If(c);postMessage({type:s,out:f});break}case"create":{let{model:c,options:f}=u;Tm(c,f).then(d=>{postMessage({type:s,out:d})},d=>{postMessage({type:s,err:d})});break}case"release":km(u),postMessage({type:s});break;case"run":{let{sessionId:c,inputIndices:f,inputs:d,outputIndices:x,options:k}=u;Em(c,f,d,x,new Array(x.length).fill(null),k).then($=>{$.some(H=>H[3]!=="cpu")?postMessage({type:s,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:s,out:$},Pm([...d,...$]))},$=>{postMessage({type:s,err:$})});break}case"end-profiling":Cm(u),postMessage({type:s});break;default:}}catch(c){postMessage({type:s,err:c})}}),tt=Qe?null:i=>new Worker(i??at,{type:"module",name:qe})}),ht={};g(ht,{default:()=>Et});var Tt,bt,Et,Lt=h(()=>{var n;bt=(Tt=import.meta.url,async function(i={}){function s(){return hr.buffer!=er.buffer&&Dn(),er}function u(){return hr.buffer!=er.buffer&&Dn(),yr}function c(){return hr.buffer!=er.buffer&&Dn(),ot}function f(){return hr.buffer!=er.buffer&&Dn(),Vt}function d(){return hr.buffer!=er.buffer&&Dn(),nr}function x(){return hr.buffer!=er.buffer&&Dn(),Wr}function k(){return hr.buffer!=er.buffer&&Dn(),pn}function $(){return hr.buffer!=er.buffer&&Dn(),si}var H,q,v=Object.assign({},i),oe=new Promise((m,F)=>{H=m,q=F}),te=typeof window=="object",de=typeof importScripts=="function",we=de&&self.name=="em-pthread";v.mountExternalData=(m,F)=>{(v.Fb||(v.Fb=new Map)).set(m,F)},v.unmountExternalData=()=>{delete v.Fb};var be=globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,shared:!0}).buffer.constructor;let he=()=>{let m=(K,J,fe)=>(...ze)=>{let lt=io,yt=J==null?void 0:J();ze=K(...ze);let Pt=J==null?void 0:J();return yt!==Pt&&(K=Pt,fe(yt),J=fe=null),io!=lt?new Promise((Ft,Qt)=>{qm={resolve:Ft,reject:Qt}}):ze},F=K=>async(...J)=>{var fe;try{if(v.Eb)throw Error("Session already started");let ze=v.Eb={bc:J[0],errors:[]},lt=await K(...J);if(v.Eb!==ze)throw Error("Session mismatch");(fe=v.Mb)==null||fe.flush();let yt=ze.errors;if(0Ft),0v._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.Mb,v.Tb,v.Xb,v.Nb,v.Wb,v.jb,v.Yb,v.$b,v.Ub,v.Vb,v.Zb]=F;let K=v.Mb;v.jsepRegisterBuffer=(J,fe,ze,lt)=>K.registerBuffer(J,fe,ze,lt),v.jsepGetBuffer=J=>K.getBuffer(J),v.jsepCreateDownloader=(J,fe,ze)=>K.createDownloader(J,fe,ze),v.jsepOnReleaseSession=J=>{K.onReleaseSession(J)},v.jsepOnRunStart=J=>K.onRunStart(J)}};var De,Ae,Ie=Object.assign({},v),gt="./this.program",ut=(m,F)=>{throw F},vt="";(te||de)&&(de?vt=self.location.href:typeof document<"u"&&document.currentScript&&(vt=document.currentScript.src),Tt&&(vt=Tt),vt=vt.startsWith("blob:")?"":vt.substr(0,vt.replace(/[?#].*/,"").lastIndexOf("/")+1),de&&(Ae=m=>{var F=new XMLHttpRequest;return F.open("GET",m,!1),F.responseType="arraybuffer",F.send(null),new Uint8Array(F.response)}),De=(m,F,K)=>{var J=new XMLHttpRequest;J.open("GET",m,!0),J.responseType="arraybuffer",J.onload=()=>{J.status==200||J.status==0&&J.response?F(J.response):K()},J.onerror=K,J.send(null)});var Dt,Rt=console.log.bind(console),gr=console.error.bind(console),Mr=Rt,ir=gr;if(Object.assign(v,Ie),Ie=null,we){let m=function(F){try{var K=F.data,J=K.cmd;if(J==="load"){let fe=[];self.onmessage=ze=>fe.push(ze),self.startWorker=()=>{postMessage({cmd:"loaded"});for(let ze of fe)m(ze);self.onmessage=m};for(let ze of K.handlers)v[ze]&&!v[ze].proxy||(v[ze]=(...lt)=>{postMessage({Lb:"callHandler",kc:ze,args:lt})},ze=="print"&&(Mr=v[ze]),ze=="printErr"&&(ir=v[ze]));hr=K.wasmMemory,Dn(),Fr(K.wasmModule)}else if(J==="run"){Ym(K.pthread_ptr,0,0,1,0,0),Wm(K.pthread_ptr),bx(),qw(),Zr||(Wy(),Zr=!0);try{xx(K.start_routine,K.arg)}catch(fe){if(fe!="unwind")throw fe}}else J==="cancel"?Il()&&Hf(-1):K.target!=="setimmediate"&&(J==="checkMailbox"?Zr&&Lf():J&&(ir(`worker: received unknown command ${J}`),ir(K)))}catch(fe){throw Gy(),fe}};var Fr,Zr=!1;ir=function(...F){F=F.join(" "),console.error(F)},self.alert=function(...F){postMessage({Lb:"alert",text:F.join(" "),mc:Il()})},v.instantiateWasm=(F,K)=>new Promise(J=>{Fr=fe=>{fe=new WebAssembly.Instance(fe,Uw()),K(fe),J()}}),self.onunhandledrejection=F=>{throw F.reason||F},self.onmessage=m}v.wasmBinary&&(Dt=v.wasmBinary);var hr,Hr,Nt,er,yr,ot,Vt,nr,Wr,pn,kn,rs,si,gi=!1;function Dn(){var m=hr.buffer;v.HEAP8=er=new Int8Array(m),v.HEAP16=ot=new Int16Array(m),v.HEAPU8=yr=new Uint8Array(m),v.HEAPU16=Vt=new Uint16Array(m),v.HEAP32=nr=new Int32Array(m),v.HEAPU32=Wr=new Uint32Array(m),v.HEAPF32=pn=new Float32Array(m),v.HEAPF64=si=new Float64Array(m),v.HEAP64=kn=new BigInt64Array(m),v.HEAPU64=rs=new BigUint64Array(m)}if(!we){if(!((hr=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0})).buffer instanceof be))throw ir("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");Dn()}var lp=[],Ln=[],Jn=[],$i=0,ns=null;function zf(){if(--$i==0&&ns){var m=ns;ns=null,m()}}function Pl(m){throw ir(m="Aborted("+m+")"),gi=!0,Nt=1,m=new WebAssembly.RuntimeError(m+". Build with -sASSERTIONS for more info."),q(m),m}var Im,Rw=m=>m.startsWith("data:application/octet-stream;base64,"),Bw=m=>m.startsWith("file://");function Nw(m){if(m==Im&&Dt)return new Uint8Array(Dt);if(Ae)return Ae(m);throw"both async and sync fetching of the wasm failed"}function jw(m,F,K){return function(J){if(!Dt&&(te||de)){if(typeof fetch=="function"&&!Bw(J))return fetch(J,{credentials:"same-origin"}).then(fe=>{if(!fe.ok)throw`failed to load wasm binary file at '${J}'`;return fe.arrayBuffer()}).catch(()=>Nw(J));if(De)return new Promise((fe,ze)=>{De(J,lt=>fe(new Uint8Array(lt)),ze)})}return Promise.resolve().then(()=>Nw(J))}(m).then(J=>WebAssembly.instantiate(J,F)).then(K,J=>{ir(`failed to asynchronously prepare wasm: ${J}`),Pl(J)})}function Uw(){return{a:{M:vx,za:yx,b:Tx,$:Yw,z:ey,pa:ty,X:ny,Z:iy,qa:oy,na:sy,ga:ay,ma:ly,J:uy,Y:cy,V:dy,oa:py,W:fy,va:kx,D:Sx,P:Ex,O:Px,C:Ax,s:Ix,p:Fx,E:Ox,y:jx,Q:Ux,ta:Vx,ja:Wx,T:Gx,aa:Hx,F:qx,ia:Wm,sa:Kx,u:Xx,B:Zx,o:Jx,m:tM,c:Um,n:rM,k:oM,Aa:sM,r:aM,f:lM,v:uM,l:cM,g:dM,i:pM,j:fM,h:hM,e:mM,da:gM,ea:_M,fa:wM,ba:Ey,ca:Cy,S:yM,d:vM,N:bM,G:xM,K:MM,w:TM,ra:kM,U:SM,t:$y,x:EM,L:CM,R:PM,ya:$M,xa:AM,ka:Fy,la:Oy,_:Lm,A:zy,I:Dy,ha:Ly,H:Ry,a:hr,wa:Dm,ua:jy,q:OM}}}var Fm={849460:(m,F,K,J)=>{if(v===void 0||!v.Fb)return 1;if((m=An(m>>>0)).startsWith("./")&&(m=m.substring(2)),!(m=v.Fb.get(m)))return 2;if(J>>>=0,(F>>>=0)+(K>>>=0)>m.byteLength)return 3;try{return u().set(m.subarray(F,F+K),J>>>0),0}catch{return 4}},849961:()=>{v.Ub()},849992:()=>{v.Vb()},850021:()=>{v.Zb()},850046:m=>v.Tb(m),850079:m=>v.Xb(m),850111:(m,F,K)=>{v.Nb(m,F,K,!0)},850150:(m,F,K)=>{v.Nb(m,F,K)},850183:()=>typeof wasmOffsetConverter<"u",850240:m=>{v.jb("Abs",m,void 0)},850291:m=>{v.jb("Neg",m,void 0)},850342:m=>{v.jb("Floor",m,void 0)},850395:m=>{v.jb("Ceil",m,void 0)},850447:m=>{v.jb("Reciprocal",m,void 0)},850505:m=>{v.jb("Sqrt",m,void 0)},850557:m=>{v.jb("Exp",m,void 0)},850608:m=>{v.jb("Erf",m,void 0)},850659:m=>{v.jb("Sigmoid",m,void 0)},850714:(m,F,K)=>{v.jb("HardSigmoid",m,{alpha:F,beta:K})},850793:m=>{v.jb("Log",m,void 0)},850844:m=>{v.jb("Sin",m,void 0)},850895:m=>{v.jb("Cos",m,void 0)},850946:m=>{v.jb("Tan",m,void 0)},850997:m=>{v.jb("Asin",m,void 0)},851049:m=>{v.jb("Acos",m,void 0)},851101:m=>{v.jb("Atan",m,void 0)},851153:m=>{v.jb("Sinh",m,void 0)},851205:m=>{v.jb("Cosh",m,void 0)},851257:m=>{v.jb("Asinh",m,void 0)},851310:m=>{v.jb("Acosh",m,void 0)},851363:m=>{v.jb("Atanh",m,void 0)},851416:m=>{v.jb("Tanh",m,void 0)},851468:m=>{v.jb("Not",m,void 0)},851519:(m,F,K)=>{v.jb("Clip",m,{min:F,max:K})},851588:m=>{v.jb("Clip",m,void 0)},851640:(m,F)=>{v.jb("Elu",m,{alpha:F})},851698:m=>{v.jb("Relu",m,void 0)},851750:(m,F)=>{v.jb("LeakyRelu",m,{alpha:F})},851814:(m,F)=>{v.jb("ThresholdedRelu",m,{alpha:F})},851884:(m,F)=>{v.jb("Cast",m,{to:F})},851942:m=>{v.jb("Add",m,void 0)},851993:m=>{v.jb("Sub",m,void 0)},852044:m=>{v.jb("Mul",m,void 0)},852095:m=>{v.jb("Div",m,void 0)},852146:m=>{v.jb("Pow",m,void 0)},852197:m=>{v.jb("Equal",m,void 0)},852250:m=>{v.jb("Greater",m,void 0)},852305:m=>{v.jb("GreaterOrEqual",m,void 0)},852367:m=>{v.jb("Less",m,void 0)},852419:m=>{v.jb("LessOrEqual",m,void 0)},852478:(m,F,K,J,fe)=>{v.jb("ReduceMean",m,{keepDims:!!F,noopWithEmptyAxes:!!K,axes:J?Array.from(d().subarray(J>>>0,fe>>>0)):[]})},852637:(m,F,K,J,fe)=>{v.jb("ReduceMax",m,{keepDims:!!F,noopWithEmptyAxes:!!K,axes:J?Array.from(d().subarray(J>>>0,fe>>>0)):[]})},852795:(m,F,K,J,fe)=>{v.jb("ReduceMin",m,{keepDims:!!F,noopWithEmptyAxes:!!K,axes:J?Array.from(d().subarray(J>>>0,fe>>>0)):[]})},852953:(m,F,K,J,fe)=>{v.jb("ReduceProd",m,{keepDims:!!F,noopWithEmptyAxes:!!K,axes:J?Array.from(d().subarray(J>>>0,fe>>>0)):[]})},853112:(m,F,K,J,fe)=>{v.jb("ReduceSum",m,{keepDims:!!F,noopWithEmptyAxes:!!K,axes:J?Array.from(d().subarray(J>>>0,fe>>>0)):[]})},853270:(m,F,K,J,fe)=>{v.jb("ReduceL1",m,{keepDims:!!F,noopWithEmptyAxes:!!K,axes:J?Array.from(d().subarray(J>>>0,fe>>>0)):[]})},853427:(m,F,K,J,fe)=>{v.jb("ReduceL2",m,{keepDims:!!F,noopWithEmptyAxes:!!K,axes:J?Array.from(d().subarray(J>>>0,fe>>>0)):[]})},853584:(m,F,K,J,fe)=>{v.jb("ReduceLogSum",m,{keepDims:!!F,noopWithEmptyAxes:!!K,axes:J?Array.from(d().subarray(J>>>0,fe>>>0)):[]})},853745:(m,F,K,J,fe)=>{v.jb("ReduceSumSquare",m,{keepDims:!!F,noopWithEmptyAxes:!!K,axes:J?Array.from(d().subarray(J>>>0,fe>>>0)):[]})},853909:(m,F,K,J,fe)=>{v.jb("ReduceLogSumExp",m,{keepDims:!!F,noopWithEmptyAxes:!!K,axes:J?Array.from(d().subarray(J>>>0,fe>>>0)):[]})},854073:m=>{v.jb("Where",m,void 0)},854126:(m,F,K)=>{v.jb("Transpose",m,{perm:F?Array.from(d().subarray(F>>>0,K>>>0)):[]})},854234:(m,F,K,J)=>{v.jb("DepthToSpace",m,{blocksize:F,mode:An(K),format:J?"NHWC":"NCHW"})},854367:(m,F,K,J)=>{v.jb("DepthToSpace",m,{blocksize:F,mode:An(K),format:J?"NHWC":"NCHW"})},854500:(m,F,K,J,fe,ze,lt,yt,Pt,Ft,Qt,Or,Br,nt,sr)=>{v.jb("ConvTranspose",m,{format:Pt?"NHWC":"NCHW",autoPad:F,dilations:[K],group:J,kernelShape:[fe],pads:[ze,lt],strides:[yt],wIsConst:()=>!!s()[Ft>>>0],outputPadding:Qt?Array.from(d().subarray(Qt>>>0,Or>>>0)):[],outputShape:Br?Array.from(d().subarray(Br>>>0,nt>>>0)):[],activation:An(sr)})},854901:(m,F,K,J,fe,ze,lt,yt,Pt,Ft,Qt,Or,Br,nt)=>{v.jb("ConvTranspose",m,{format:yt?"NHWC":"NCHW",autoPad:F,dilations:Array.from(d().subarray(K>>>0,2+(K>>>0)>>>0)),group:J,kernelShape:Array.from(d().subarray(fe>>>0,2+(fe>>>0)>>>0)),pads:Array.from(d().subarray(ze>>>0,4+(ze>>>0)>>>0)),strides:Array.from(d().subarray(lt>>>0,2+(lt>>>0)>>>0)),wIsConst:()=>!!s()[Pt>>>0],outputPadding:Ft?Array.from(d().subarray(Ft>>>0,Qt>>>0)):[],outputShape:Or?Array.from(d().subarray(Or>>>0,Br>>>0)):[],activation:An(nt)})},855466:(m,F,K,J,fe,ze,lt,yt,Pt,Ft,Qt,Or,Br,nt,sr)=>{v.jb("ConvTranspose",m,{format:Pt?"NHWC":"NCHW",autoPad:F,dilations:[K],group:J,kernelShape:[fe],pads:[ze,lt],strides:[yt],wIsConst:()=>!!s()[Ft>>>0],outputPadding:Qt?Array.from(d().subarray(Qt>>>0,Or>>>0)):[],outputShape:Br?Array.from(d().subarray(Br>>>0,nt>>>0)):[],activation:An(sr)})},855867:(m,F,K,J,fe,ze,lt,yt,Pt,Ft,Qt,Or,Br,nt)=>{v.jb("ConvTranspose",m,{format:yt?"NHWC":"NCHW",autoPad:F,dilations:Array.from(d().subarray(K>>>0,2+(K>>>0)>>>0)),group:J,kernelShape:Array.from(d().subarray(fe>>>0,2+(fe>>>0)>>>0)),pads:Array.from(d().subarray(ze>>>0,4+(ze>>>0)>>>0)),strides:Array.from(d().subarray(lt>>>0,2+(lt>>>0)>>>0)),wIsConst:()=>!!s()[Pt>>>0],outputPadding:Ft?Array.from(d().subarray(Ft>>>0,Qt>>>0)):[],outputShape:Or?Array.from(d().subarray(Or>>>0,Br>>>0)):[],activation:An(nt)})},856432:(m,F)=>{v.jb("GlobalAveragePool",m,{format:F?"NHWC":"NCHW"})},856523:(m,F,K,J,fe,ze,lt,yt,Pt,Ft,Qt,Or,Br,nt,sr,jr)=>{v.jb("AveragePool",m,{format:jr?"NHWC":"NCHW",auto_pad:F,ceil_mode:K,count_include_pad:J,storage_order:fe,dilations:[ze,lt],kernel_shape:[yt,Pt],pads:[Ft,Qt,Or,Br],strides:[nt,sr]})},856807:(m,F)=>{v.jb("GlobalAveragePool",m,{format:F?"NHWC":"NCHW"})},856898:(m,F,K,J,fe,ze,lt,yt,Pt,Ft,Qt,Or,Br,nt,sr,jr)=>{v.jb("AveragePool",m,{format:jr?"NHWC":"NCHW",auto_pad:F,ceil_mode:K,count_include_pad:J,storage_order:fe,dilations:[ze,lt],kernel_shape:[yt,Pt],pads:[Ft,Qt,Or,Br],strides:[nt,sr]})},857182:(m,F)=>{v.jb("GlobalMaxPool",m,{format:F?"NHWC":"NCHW"})},857269:(m,F,K,J,fe,ze,lt,yt,Pt,Ft,Qt,Or,Br,nt,sr,jr)=>{v.jb("MaxPool",m,{format:jr?"NHWC":"NCHW",auto_pad:F,ceil_mode:K,count_include_pad:J,storage_order:fe,dilations:[ze,lt],kernel_shape:[yt,Pt],pads:[Ft,Qt,Or,Br],strides:[nt,sr]})},857549:(m,F)=>{v.jb("GlobalMaxPool",m,{format:F?"NHWC":"NCHW"})},857636:(m,F,K,J,fe,ze,lt,yt,Pt,Ft,Qt,Or,Br,nt,sr,jr)=>{v.jb("MaxPool",m,{format:jr?"NHWC":"NCHW",auto_pad:F,ceil_mode:K,count_include_pad:J,storage_order:fe,dilations:[ze,lt],kernel_shape:[yt,Pt],pads:[Ft,Qt,Or,Br],strides:[nt,sr]})},857916:(m,F,K,J,fe)=>{v.jb("Gemm",m,{alpha:F,beta:K,transA:J,transB:fe})},858020:m=>{v.jb("MatMul",m,void 0)},858074:(m,F,K,J)=>{v.jb("ArgMax",m,{keepDims:!!F,selectLastIndex:!!K,axis:J})},858182:(m,F,K,J)=>{v.jb("ArgMin",m,{keepDims:!!F,selectLastIndex:!!K,axis:J})},858290:(m,F)=>{v.jb("Softmax",m,{axis:F})},858353:(m,F)=>{v.jb("Concat",m,{axis:F})},858413:(m,F,K,J,fe)=>{v.jb("Split",m,{axis:F,numOutputs:K,splitSizes:J?Array.from(d().subarray(J>>>0,fe>>>0)):[]})},858553:m=>{v.jb("Expand",m,void 0)},858607:(m,F)=>{v.jb("Gather",m,{axis:Number(F)})},858678:(m,F)=>{v.jb("GatherElements",m,{axis:Number(F)})},858757:(m,F,K,J,fe,ze,lt,yt,Pt,Ft,Qt)=>{v.jb("Resize",m,{antialias:F,axes:K?Array.from(d().subarray(K>>>0,J>>>0)):[],coordinateTransformMode:An(fe),cubicCoeffA:ze,excludeOutside:lt,extrapolationValue:yt,keepAspectRatioPolicy:An(Pt),mode:An(Ft),nearestMode:An(Qt)})},859103:(m,F,K,J,fe,ze,lt)=>{v.jb("Slice",m,{starts:F?Array.from(d().subarray(F>>>0,K>>>0)):[],ends:J?Array.from(d().subarray(J>>>0,fe>>>0)):[],axes:ze?Array.from(d().subarray(ze>>>0,lt>>>0)):[]})},859319:m=>{v.jb("Tile",m,void 0)},859371:(m,F,K)=>{v.jb("InstanceNormalization",m,{epsilon:F,format:K?"NHWC":"NCHW"})},859485:(m,F,K)=>{v.jb("InstanceNormalization",m,{epsilon:F,format:K?"NHWC":"NCHW"})},859599:m=>{v.jb("Range",m,void 0)},859652:(m,F)=>{v.jb("Einsum",m,{equation:An(F)})},859733:(m,F,K,J,fe)=>{v.jb("Pad",m,{mode:F,value:K,pads:J?Array.from(d().subarray(J>>>0,fe>>>0)):[]})},859860:(m,F,K,J,fe,ze)=>{v.jb("BatchNormalization",m,{epsilon:F,momentum:K,spatial:!!fe,trainingMode:!!J,format:ze?"NHWC":"NCHW"})},860029:(m,F,K,J,fe,ze)=>{v.jb("BatchNormalization",m,{epsilon:F,momentum:K,spatial:!!fe,trainingMode:!!J,format:ze?"NHWC":"NCHW"})},860198:(m,F,K)=>{v.jb("CumSum",m,{exclusive:Number(F),reverse:Number(K)})},860295:(m,F,K,J,fe,ze,lt,yt,Pt)=>{v.jb("Attention",m,{numHeads:F,isUnidirectional:K,maskFilterValue:J,scale:fe,doRotary:ze,qkvHiddenSizes:lt?Array.from(d().subarray(Number(yt)>>>0,Number(yt)+lt>>>0)):[],pastPresentShareBuffer:!!Pt})},860567:m=>{v.jb("BiasAdd",m,void 0)},860622:m=>{v.jb("BiasSplitGelu",m,void 0)},860683:m=>{v.jb("FastGelu",m,void 0)},860739:(m,F,K,J,fe,ze,lt,yt,Pt,Ft,Qt,Or,Br,nt,sr,jr)=>{v.jb("Conv",m,{format:Or?"NHWC":"NCHW",auto_pad:F,dilations:K?Array.from(d().subarray(K>>>0,J>>>0)):[],group:fe,kernel_shape:ze?Array.from(d().subarray(ze>>>0,lt>>>0)):[],pads:yt?Array.from(d().subarray(yt>>>0,Pt>>>0)):[],strides:Ft?Array.from(d().subarray(Ft>>>0,Qt>>>0)):[],w_is_const:()=>!!s()[Br>>>0],activation:An(nt),activation_params:sr?Array.from(k().subarray(sr>>>0,jr>>>0)):[]})},861235:m=>{v.jb("Gelu",m,void 0)},861287:(m,F,K,J)=>{v.jb("GroupQueryAttention",m,{numHeads:F,kvNumHeads:K,scale:J})},861400:(m,F,K,J)=>{v.jb("LayerNormalization",m,{axis:F,epsilon:K,simplified:!!J})},861511:(m,F,K,J)=>{v.jb("LayerNormalization",m,{axis:F,epsilon:K,simplified:!!J})},861622:(m,F,K,J,fe,ze)=>{v.jb("MatMulNBits",m,{k:F,n:K,accuracyLevel:J,bits:fe,blockSize:ze})},861749:(m,F,K,J,fe,ze)=>{v.jb("MultiHeadAttention",m,{numHeads:F,isUnidirectional:K,maskFilterValue:J,scale:fe,doRotary:ze})},861908:(m,F)=>{v.jb("QuickGelu",m,{alpha:F})},861972:(m,F,K,J,fe)=>{v.jb("RotaryEmbedding",m,{interleaved:!!F,numHeads:K,rotaryEmbeddingDim:J,scale:fe})},862111:(m,F,K)=>{v.jb("SkipLayerNormalization",m,{epsilon:F,simplified:!!K})},862213:m=>{v.Yb(m)},862247:(m,F)=>v.$b(m,F,v.Eb.bc,v.Eb.errors),862359:(m,F,K)=>{v.jb("SkipLayerNormalization",m,{epsilon:F,simplified:!!K})}};function yx(m,F,K){return xy(async()=>{await v.Wb(m,F,K)})}function vx(){return typeof wasmOffsetConverter<"u"}function Om(m){this.name="ExitStatus",this.message=`Program terminated with exit(${m})`,this.status=m}var zm=m=>{m.terminate(),m.onmessage=()=>{}},Vw=m=>{is.length==0&&(Xw(),Kw(is[0]));var F=is.pop();if(!F)return 6;Zs.push(F),ro[m.Ab]=F,F.Ab=m.Ab;var K={cmd:"run",start_routine:m.cc,arg:m.Pb,pthread_ptr:m.Ab};return F.postMessage(K,m.ic),0},Ys=0,rn=(m,F,...K)=>{for(var J=2*K.length,fe=eg(),ze=Jm(8*J),lt=ze>>>3,yt=0;yt>>0]=Pt)}return m=Hy(m,0,J,ze,F),qf(fe),m};function Dm(m){if(we)return rn(0,1,m);if(Nt=m,!(0{if(Nt=m,we)throw Ww(m),"unwind";Dm(m)},is=[],Zs=[],Gw=[],ro={},Hw=m=>{var F=m.Ab;delete ro[F],is.push(m),Zs.splice(Zs.indexOf(m),1),m.Ab=0,Zm(F)};function qw(){Gw.forEach(m=>m())}var Kw=m=>new Promise(F=>{m.onmessage=fe=>{var ze=(fe=fe.data).cmd;if(fe.targetThread&&fe.targetThread!=Il()){var lt=ro[fe.targetThread];lt?lt.postMessage(fe,fe.transferList):ir(`Internal error! Worker sent a message "${ze}" to target pthread ${fe.targetThread}, but that thread no longer exists!`)}else ze==="checkMailbox"?Lf():ze==="spawnThread"?Vw(fe):ze==="cleanupThread"?Hw(ro[fe.thread]):ze==="killThread"?(fe=fe.thread,ze=ro[fe],delete ro[fe],zm(ze),Zm(fe),Zs.splice(Zs.indexOf(ze),1),ze.Ab=0):ze==="cancelThread"?ro[fe.thread].postMessage({cmd:"cancel"}):ze==="loaded"?(m.loaded=!0,F(m)):ze==="alert"?alert(`Thread ${fe.threadId}: ${fe.text}`):fe.target==="setimmediate"?m.postMessage(fe):ze==="callHandler"?v[fe.handler](...fe.args):ze&&ir(`worker sent an unknown command ${ze}`)},m.onerror=fe=>{throw ir(`worker sent an error! ${fe.filename}:${fe.lineno}: ${fe.message}`),fe};var K,J=[];for(K of[])v.hasOwnProperty(K)&&J.push(K);m.postMessage({cmd:"load",handlers:J,wasmMemory:hr,wasmModule:Hr})});function Xw(){var m=new Worker(new URL(import.meta.url),{type:"module",workerData:"em-pthread",name:"em-pthread"});is.push(m)}var Df=m=>{for(;0{var m=Il(),F=x()[m+52>>>2>>>0];m=x()[m+56>>>2>>>0],Ky(F,F-m),qf(F)},xx=(m,F)=>{Ys=0,m=Xy(m,F),0>>=0);throw F>>>=0,K>>>=0,x()[J.Ib+16>>>2>>>0]=0,x()[J.Ib+4>>>2>>>0]=F,x()[J.Ib+8>>>2>>>0]=K,m}function Qw(m,F,K,J){return we?rn(2,1,m,F,K,J):Yw(m,F,K,J)}function Yw(m,F,K,J){if(m>>>=0,F>>>=0,K>>>=0,J>>>=0,be===void 0)return ir("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var fe=[];return we&&fe.length===0?Qw(m,F,K,J):(m={cc:K,Ab:m,Pb:J,ic:fe},we?(m.Lb="spawnThread",postMessage(m,fe),0):Vw(m))}var Zw=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,Jw=(m,F,K)=>{var J=(F>>>=0)+K;for(K=F;m[K]&&!(K>=J);)++K;if(16(fe=(240&fe)==224?(15&fe)<<12|ze<<6|lt:(7&fe)<<18|ze<<12|lt<<6|63&m[F++])?J+=String.fromCharCode(fe):(fe-=65536,J+=String.fromCharCode(55296|fe>>10,56320|1023&fe))}}else J+=String.fromCharCode(fe)}return J},An=(m,F)=>(m>>>=0)?Jw(u(),m,F):"";function ey(m,F,K){return we?rn(3,1,m,F,K):0}function ty(m,F){if(we)return rn(4,1,m,F)}var Rm=m=>{for(var F=0,K=0;K=J?F++:2047>=J?F+=2:55296<=J&&57343>=J?(F+=4,++K):F+=3}return F},ry=(m,F,K,J)=>{if(!(0>>=0;J=K+J-1;for(var ze=0;ze=lt&&(lt=65536+((1023<)<<10)|1023&m.charCodeAt(++ze)),127>=lt){if(K>=J)break;F[K++>>>0]=lt}else{if(2047>=lt){if(K+1>=J)break;F[K++>>>0]=192|lt>>6}else{if(65535>=lt){if(K+2>=J)break;F[K++>>>0]=224|lt>>12}else{if(K+3>=J)break;F[K++>>>0]=240|lt>>18,F[K++>>>0]=128|lt>>12&63}F[K++>>>0]=128|lt>>6&63}F[K++>>>0]=128|63<}}return F[K>>>0]=0,K-fe},$l=(m,F,K)=>ry(m,u(),F,K);function ny(m,F){if(we)return rn(5,1,m,F)}function iy(m,F,K){if(we)return rn(6,1,m,F,K)}function oy(m,F,K){return we?rn(7,1,m,F,K):0}function sy(m,F){if(we)return rn(8,1,m,F)}function ay(m,F,K){if(we)return rn(9,1,m,F,K)}function ly(m,F,K,J){if(we)return rn(10,1,m,F,K,J)}function uy(m,F,K,J){if(we)return rn(11,1,m,F,K,J)}function cy(m,F,K,J){if(we)return rn(12,1,m,F,K,J)}function dy(m){if(we)return rn(13,1,m)}function py(m,F){if(we)return rn(14,1,m,F)}function fy(m,F,K){if(we)return rn(15,1,m,F,K)}var hy,os,kx=()=>{Pl("")},no=m=>{for(var F="";u()[m>>>0];)F+=hy[u()[m++>>>0]];return F},Bm={},Nm={};function Mo(m,F,K={}){if(!("argPackAdvance"in F))throw new TypeError("registerType registeredInstance requires argPackAdvance");return function(J,fe,ze={}){var lt=fe.name;if(!J)throw new os(`type "${lt}" must have a positive integer typeid pointer`);if(Nm.hasOwnProperty(J)){if(ze.Rb)return;throw new os(`Cannot register type '${lt}' twice`)}Nm[J]=fe,Bm.hasOwnProperty(J)&&(fe=Bm[J],delete Bm[J],fe.forEach(yt=>yt()))}(m,F,K)}var my=(m,F,K)=>{switch(F){case 1:return K?J=>s()[J>>>0]:J=>u()[J>>>0];case 2:return K?J=>c()[J>>>1>>>0]:J=>f()[J>>>1>>>0];case 4:return K?J=>d()[J>>>2>>>0]:J=>x()[J>>>2>>>0];case 8:return K?J=>kn[J>>>3]:J=>rs[J>>>3];default:throw new TypeError(`invalid integer width (${F}): ${m}`)}};function Sx(m,F,K){K>>>=0,Mo(m>>>=0,{name:F=no(F>>>0),fromWireType:J=>J,toWireType:function(J,fe){if(typeof fe!="bigint"&&typeof fe!="number")throw fe=fe===null?"null":(J=typeof fe)=="object"||J==="array"||J==="function"?fe.toString():""+fe,new TypeError(`Cannot convert "${fe}" to ${this.name}`);return typeof fe=="number"&&(fe=BigInt(fe)),fe},argPackAdvance:ss,readValueFromPointer:my(F,K,F.indexOf("u")==-1),Db:null})}var ss=8;function Ex(m,F,K,J){Mo(m>>>=0,{name:F=no(F>>>0),fromWireType:function(fe){return!!fe},toWireType:function(fe,ze){return ze?K:J},argPackAdvance:ss,readValueFromPointer:function(fe){return this.fromWireType(u()[fe>>>0])},Db:null})}var jm=[],To=[];function Um(m){9<(m>>>=0)&&--To[m+1]==0&&(To[m]=void 0,jm.push(m))}var Ai=m=>{if(!m)throw new os("Cannot use deleted val. handle = "+m);return To[m]},Ii=m=>{switch(m){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let F=jm.pop()||To.length;return To[F]=m,To[F+1]=1,F}};function Vm(m){return this.fromWireType(x()[m>>>2>>>0])}var Cx={name:"emscripten::val",fromWireType:m=>{var F=Ai(m);return Um(m),F},toWireType:(m,F)=>Ii(F),argPackAdvance:ss,readValueFromPointer:Vm,Db:null};function Px(m){return Mo(m>>>0,Cx)}var $x=(m,F)=>{switch(F){case 4:return function(K){return this.fromWireType(k()[K>>>2>>>0])};case 8:return function(K){return this.fromWireType($()[K>>>3>>>0])};default:throw new TypeError(`invalid float width (${F}): ${m}`)}};function Ax(m,F,K){K>>>=0,Mo(m>>>=0,{name:F=no(F>>>0),fromWireType:J=>J,toWireType:(J,fe)=>fe,argPackAdvance:ss,readValueFromPointer:$x(F,K),Db:null})}function Ix(m,F,K,J,fe){if(m>>>=0,K>>>=0,F=no(F>>>0),fe===-1&&(fe=4294967295),fe=yt=>yt,J===0){var ze=32-8*K;fe=yt=>yt<>>ze}var lt=F.includes("unsigned")?function(yt,Pt){return Pt>>>0}:function(yt,Pt){return Pt};Mo(m,{name:F,fromWireType:fe,toWireType:lt,argPackAdvance:ss,readValueFromPointer:my(F,K,J!==0),Db:null})}function Fx(m,F,K){function J(ze){var lt=x()[ze>>>2>>>0];return ze=x()[ze+4>>>2>>>0],new fe(s().buffer,ze,lt)}var fe=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][F];Mo(m>>>=0,{name:K=no(K>>>0),fromWireType:J,argPackAdvance:ss,readValueFromPointer:J},{Rb:!0})}function Ox(m,F){m>>>=0;var K=(F=no(F>>>0))==="std::string";Mo(m,{name:F,fromWireType:function(J){var fe=x()[J>>>2>>>0],ze=J+4;if(K)for(var lt=ze,yt=0;yt<=fe;++yt){var Pt=ze+yt;if(yt==fe||u()[Pt>>>0]==0){if(lt=An(lt,Pt-lt),Ft===void 0)var Ft=lt;else Ft+="\0",Ft+=lt;lt=Pt+1}}else{for(Ft=Array(fe),yt=0;yt>>0]);Ft=Ft.join("")}return oo(J),Ft},toWireType:function(J,fe){fe instanceof ArrayBuffer&&(fe=new Uint8Array(fe));var ze=typeof fe=="string";if(!(ze||fe instanceof Uint8Array||fe instanceof Uint8ClampedArray||fe instanceof Int8Array))throw new os("Cannot pass non-string to std::string");var lt=K&&ze?Rm(fe):fe.length,yt=Gf(4+lt+1),Pt=yt+4;if(x()[yt>>>2>>>0]=lt,K&&ze)$l(fe,Pt,lt+1);else if(ze)for(ze=0;ze>>0]=Ft}else for(ze=0;ze>>0]=fe[ze];return J!==null&&J.push(oo,yt),yt},argPackAdvance:ss,readValueFromPointer:Vm,Db(J){oo(J)}})}var gy=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,zx=(m,F)=>{for(var K=m>>1,J=K+F/2;!(K>=J)&&f()[K>>>0];)++K;if(32<(K<<=1)-m&&gy)return gy.decode(u().slice(m,K));for(K="",J=0;!(J>=F/2);++J){var fe=c()[m+2*J>>>1>>>0];if(fe==0)break;K+=String.fromCharCode(fe)}return K},Dx=(m,F,K)=>{if(K??(K=2147483647),2>K)return 0;var J=F;K=(K-=2)<2*m.length?K/2:m.length;for(var fe=0;fe>>1>>>0]=ze,F+=2}return c()[F>>>1>>>0]=0,F-J},Lx=m=>2*m.length,Rx=(m,F)=>{for(var K=0,J="";!(K>=F/4);){var fe=d()[m+4*K>>>2>>>0];if(fe==0)break;++K,65536<=fe?(fe-=65536,J+=String.fromCharCode(55296|fe>>10,56320|1023&fe)):J+=String.fromCharCode(fe)}return J},Bx=(m,F,K)=>{if(F>>>=0,K??(K=2147483647),4>K)return 0;var J=F;K=J+K-4;for(var fe=0;fe=ze&&(ze=65536+((1023&ze)<<10)|1023&m.charCodeAt(++fe)),d()[F>>>2>>>0]=ze,(F+=4)+4>K)break}return d()[F>>>2>>>0]=0,F-J},Nx=m=>{for(var F=0,K=0;K=J&&++K,F+=4}return F};function jx(m,F,K){if(m>>>=0,F>>>=0,K=no(K>>>=0),F===2)var J=zx,fe=Dx,ze=Lx,lt=yt=>f()[yt>>>1>>>0];else F===4&&(J=Rx,fe=Bx,ze=Nx,lt=yt=>x()[yt>>>2>>>0]);Mo(m,{name:K,fromWireType:yt=>{for(var Pt,Ft=x()[yt>>>2>>>0],Qt=yt+4,Or=0;Or<=Ft;++Or){var Br=yt+4+Or*F;Or!=Ft&<(Br)!=0||(Qt=J(Qt,Br-Qt),Pt===void 0?Pt=Qt:(Pt+="\0",Pt+=Qt),Qt=Br+F)}return oo(yt),Pt},toWireType:(yt,Pt)=>{if(typeof Pt!="string")throw new os(`Cannot pass non-string to C++ string type ${K}`);var Ft=ze(Pt),Qt=Gf(4+Ft+F);return x()[Qt>>>2>>>0]=Ft/F,fe(Pt,Qt+4,Ft+F),yt!==null&&yt.push(oo,Qt),Qt},argPackAdvance:ss,readValueFromPointer:Vm,Db(yt){oo(yt)}})}function Ux(m,F){Mo(m>>>=0,{Sb:!0,name:F=no(F>>>0),argPackAdvance:0,fromWireType:()=>{},toWireType:()=>{}})}var Vx=()=>1;function Wx(m){Ym(m>>>0,!de,1,!te,131072,!1),qw()}var _y=m=>{if(!gi)try{if(m(),!(0>>=0,typeof Atomics.jc=="function"&&(Atomics.jc(d(),m>>>2,m).value.then(Lf),m+=128,Atomics.store(d(),m>>>2,1))}var Lf=()=>{var m=Il();m&&(Wm(m),_y(qy))};function Gx(m,F){(m>>>=0)==F>>>0?setTimeout(Lf):we?postMessage({targetThread:m,cmd:"checkMailbox"}):(m=ro[m])&&m.postMessage({cmd:"checkMailbox"})}var Gm=[];function Hx(m,F,K,J,fe){for(F>>>=0,J/=2,Gm.length=J,K=fe>>>0>>>3,fe=0;fe>>0];return(F?Fm[F]:zM[m])(...Gm)}function qx(m){m>>>=0,we?postMessage({cmd:"cleanupThread",thread:m}):Hw(ro[m])}function Kx(m){}var Hm=(m,F)=>{var K=Nm[m];if(K===void 0)throw m=Vy(m),K=no(m),oo(m),new os(`${F} has unknown type ${K}`);return K},wy=(m,F,K)=>{var J=[];return m=m.toWireType(J,K),J.length&&(x()[F>>>2>>>0]=Ii(J)),m};function Xx(m,F,K){return F>>>=0,K>>>=0,m=Ai(m>>>0),F=Hm(F,"emval::as"),wy(F,K,m)}var Rf=m=>{try{m()}catch(F){Pl(F)}},as=0,io=null,yy=0,Bf=[],vy={},by={},Qx=0,qm=null,Yx=[];function xy(m){return function(F){if(!gi){if(as===0){var K=!1,J=!1;F((fe=0)=>{if(!gi&&(yy=fe,K=!0,J)){as=2,Rf(()=>Zy(io)),typeof Browser<"u"&&Browser.Jb.Qb&&Browser.Jb.resume(),fe=!1;try{var ze=function(){var Pt=d()[io+8>>>2>>>0];return Pt=Kt[by[Pt]],--Ys,Pt()}()}catch(Pt){ze=Pt,fe=!0}var lt=!1;if(!io){var yt=qm;yt&&(qm=null,(fe?yt.reject:yt.resolve)(ze),lt=!0)}if(fe&&!lt)throw ze}}),J=!0,K||(as=1,io=function(){var fe=Gf(65548),ze=fe+12;x()[fe>>>2>>>0]=ze,x()[fe+4>>>2>>>0]=ze+65536,ze=Bf[0];var lt=vy[ze];return lt===void 0&&(lt=Qx++,vy[ze]=lt,by[lt]=ze),ze=lt,d()[fe+8>>>2>>>0]=ze,fe}(),typeof Browser<"u"&&Browser.Jb.Qb&&Browser.Jb.pause(),Rf(()=>Qy(io)))}else as===2?(as=0,Rf(Jy),oo(io),io=null,Yx.forEach(_y)):Pl(`invalid state: ${as}`);return yy}}(F=>{m().then(F)})}function Zx(m){return m>>>=0,xy(()=>(m=Ai(m)).then(Ii))}var Nf=[];function Jx(m,F,K,J){return K>>>=0,J>>>=0,(m=Nf[m>>>0])(null,F=Ai(F>>>0),K,J)}var eM={},jf=m=>{var F=eM[m];return F===void 0?no(m):F};function tM(m,F,K,J,fe){return K>>>=0,J>>>=0,fe>>>=0,(m=Nf[m>>>0])(F=Ai(F>>>0),F[K=jf(K)],J,fe)}var My=()=>typeof globalThis=="object"?globalThis:Function("return this")();function rM(m){return(m>>>=0)==0?Ii(My()):(m=jf(m),Ii(My()[m]))}var nM=m=>{var F=Nf.length;return Nf.push(m),F},iM=(m,F)=>{for(var K=Array(m),J=0;J>>2>>>0],"parameter "+J);return K},Ty=(m,F)=>Object.defineProperty(F,"name",{value:m});function oM(m,F,K){var J=(F=iM(m,F>>>0)).shift();m--;var fe=`return function (obj, func, destructorsRef, args) { +`,ze=0,lt=[];K===0&<.push("obj");for(var yt=["retType"],Pt=[J],Ft=0;FtQt.name).join(", ")}) => ${J.name}>`,nM(Ty(K,m))}function sM(m){return m=jf(m>>>0),Ii(v[m])}function aM(m,F){return F>>>=0,m=Ai(m>>>0),F=Ai(F),Ii(m[F])}function lM(m){9<(m>>>=0)&&(To[m+1]+=1)}function uM(){return Ii([])}function cM(m){m=Ai(m>>>0);for(var F=Array(m.length),K=0;K>>0))}function pM(){return Ii({})}function fM(m){for(var F=Ai(m>>>=0);F.length;){var K=F.pop();F.pop()(K)}Um(m)}function hM(m,F,K){F>>>=0,K>>>=0,m=Ai(m>>>0),F=Ai(F),K=Ai(K),m[F]=K}function mM(m,F){return F>>>=0,m=(m=Hm(m>>>0,"_emval_take_value")).readValueFromPointer(F),Ii(m)}function gM(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 Al=m=>m%4==0&&(m%100!=0||m%400==0),ky=[0,31,60,91,121,152,182,213,244,274,305,335],Sy=[0,31,59,90,120,151,181,212,243,273,304,334];function _M(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=(Al(m.getFullYear())?ky:Sy)[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 J=new Date(m.getFullYear(),0,1).getTimezoneOffset();m=0|(K!=J&&m.getTimezoneOffset()==Math.min(J,K)),d()[F+32>>>2>>>0]=m}function wM(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],J=F.getTimezoneOffset(),fe=new Date(F.getFullYear(),6,1).getTimezoneOffset(),ze=new Date(F.getFullYear(),0,1).getTimezoneOffset(),lt=Math.min(ze,fe);return 0>K?d()[m+32>>>2>>>0]=+(fe!=ze&<==J):0>>2>>>0]=F.getDay(),K=(Al(F.getFullYear())?ky:Sy)[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 Ey(m,F,K,J,fe,ze,lt){return we?rn(16,1,m,F,K,J,fe,ze,lt):-52}function Cy(m,F,K,J,fe,ze){if(we)return rn(17,1,m,F,K,J,fe,ze)}function yM(m,F,K,J){m>>>=0,F>>>=0,K>>>=0,J>>>=0;var fe=new Date().getFullYear(),ze=new Date(fe,0,1),lt=new Date(fe,6,1);fe=ze.getTimezoneOffset();var yt=lt.getTimezoneOffset(),Pt=Math.max(fe,yt);x()[m>>>2>>>0]=60*Pt,d()[F>>>2>>>0]=+(fe!=yt),ze=(m=Ft=>Ft.toLocaleTimeString(void 0,{hour12:!1,timeZoneName:"short"}).split(" ")[1])(ze),lt=m(lt),yt{Km.length=0;for(var K;K=u()[m++>>>0];){var J=K!=105;F+=(J&=K!=112)&&F%8?4:0,Km.push(K==112?x()[F>>>2>>>0]:K==106?kn[F>>>3]:K==105?d()[F>>>2>>>0]:$()[F>>>3>>>0]),F+=J?8:4}return Km};function vM(m,F,K){return m>>>=0,F=Py(F>>>0,K>>>0),Fm[m](...F)}function bM(m,F,K){return m>>>=0,F=Py(F>>>0,K>>>0),Fm[m](...F)}var xM=()=>{},MM=()=>Date.now();function TM(m,F){return ir(An(m>>>0,F>>>0))}var $y,kM=()=>{throw Ys+=1,"unwind"};function SM(){return 4294901760}$y=()=>performance.timeOrigin+performance.now();var EM=()=>navigator.hardwareConcurrency;function CM(){return Pl("Cannot use emscripten_pc_get_function without -sUSE_OFFSET_CONVERTER"),0}function PM(m){m>>>=0;var F=u().length;if(m<=F||4294901760=K;K*=2){var J=F*(1+.2/K);J=Math.min(J,m+100663296);var fe=Math;J=Math.max(m,J);e:{fe=(fe.min.call(fe,4294901760,J+(65536-J%65536)%65536)-hr.buffer.byteLength+65535)/65536;try{hr.grow(fe),Dn();var ze=1;break e}catch{}ze=void 0}if(ze)return!0}return!1}var Uf=()=>(Pl("Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER"),0),up={},Ay=m=>{m.forEach(F=>{Uf()})};function $M(){var m=Error().stack.toString().split(` +`);return m[0]=="Error"&&m.shift(),Ay(m),up.Ob=Uf(),up.ac=m,up.Ob}function AM(m,F,K){if(m>>>=0,F>>>=0,up.Ob==m)var J=up.ac;else(J=Error().stack.toString().split(` +`))[0]=="Error"&&J.shift(),Ay(J);for(var fe=3;J[fe]&&Uf()!=m;)++fe;for(m=0;m>>2>>>0]=Uf();return m}var Xm,Qm={},Iy=()=>{if(!Xm){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",_:gt};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]}`);Xm=K}return Xm};function Fy(m,F){if(we)return rn(18,1,m,F);m>>>=0,F>>>=0;var K=0;return Iy().forEach((J,fe)=>{var ze=F+K;for(fe=x()[m+4*fe>>>2>>>0]=ze,ze=0;ze>>0]=J.charCodeAt(ze);s()[fe>>>0]=0,K+=J.length+1}),0}function Oy(m,F){if(we)return rn(19,1,m,F);m>>>=0,F>>>=0;var K=Iy();x()[m>>>2>>>0]=K.length;var J=0;return K.forEach(fe=>J+=fe.length+1),x()[F>>>2>>>0]=J,0}function zy(m){return we?rn(20,1,m):52}function Dy(m,F,K,J){return we?rn(21,1,m,F,K,J):52}function Ly(m,F,K,J){return we?rn(22,1,m,F,K,J):70}var IM=[null,[],[]];function Ry(m,F,K,J){if(we)return rn(23,1,m,F,K,J);F>>>=0,K>>>=0,J>>>=0;for(var fe=0,ze=0;ze>>2>>>0],yt=x()[F+4>>>2>>>0];F+=8;for(var Pt=0;Pt>>0],Qt=IM[m];Ft===0||Ft===10?((m===1?Mr:ir)(Jw(Qt,0)),Qt.length=0):Qt.push(Ft)}fe+=yt}return x()[J>>>2>>>0]=fe,0}var By=[31,29,31,30,31,30,31,31,30,31,30,31],Ny=[31,28,31,30,31,30,31,31,30,31,30,31],FM=(m,F)=>{s().set(m,F>>>0)};function jy(m,F,K,J){function fe(nt,sr,jr){for(nt=typeof nt=="number"?nt.toString():nt||"";nt.lengthtv?-1:0Js-nt.getDate())){nt.setDate(nt.getDate()+sr);break}sr-=Js-nt.getDate()+1,nt.setDate(1),11>jr?nt.setMonth(jr+1):(nt.setMonth(0),nt.setFullYear(nt.getFullYear()+1))}return jr=new Date(nt.getFullYear()+1,0,4),sr=yt(new Date(nt.getFullYear(),0,4)),jr=yt(jr),0>=lt(sr,nt)?0>=lt(jr,nt)?nt.getFullYear()+1:nt.getFullYear():nt.getFullYear()-1}m>>>=0,F>>>=0,K>>>=0,J>>>=0;var Ft=x()[J+40>>>2>>>0];for(var Qt in J={fc:d()[J>>>2>>>0],ec:d()[J+4>>>2>>>0],Gb:d()[J+8>>>2>>>0],Kb:d()[J+12>>>2>>>0],Hb:d()[J+16>>>2>>>0],Cb:d()[J+20>>>2>>>0],ub:d()[J+24>>>2>>>0],Bb:d()[J+28>>>2>>>0],nc:d()[J+32>>>2>>>0],dc:d()[J+36>>>2>>>0],hc:Ft?An(Ft):""},K=An(K),Ft={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"})K=K.replace(new RegExp(Qt,"g"),Ft[Qt]);var Or="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),Br="January February March April May June July August September October November December".split(" ");for(Qt in Ft={"%a":nt=>Or[nt.ub].substring(0,3),"%A":nt=>Or[nt.ub],"%b":nt=>Br[nt.Hb].substring(0,3),"%B":nt=>Br[nt.Hb],"%C":nt=>ze((nt.Cb+1900)/100|0,2),"%d":nt=>ze(nt.Kb,2),"%e":nt=>fe(nt.Kb,2," "),"%g":nt=>Pt(nt).toString().substring(2),"%G":Pt,"%H":nt=>ze(nt.Gb,2),"%I":nt=>((nt=nt.Gb)==0?nt=12:12{for(var sr=0,jr=0;jr<=nt.Hb-1;sr+=(Al(nt.Cb+1900)?By:Ny)[jr++]);return ze(nt.Kb+sr,3)},"%m":nt=>ze(nt.Hb+1,2),"%M":nt=>ze(nt.ec,2),"%n":()=>` +`,"%p":nt=>0<=nt.Gb&&12>nt.Gb?"AM":"PM","%S":nt=>ze(nt.fc,2),"%t":()=>" ","%u":nt=>nt.ub||7,"%U":nt=>ze(Math.floor((nt.Bb+7-nt.ub)/7),2),"%V":nt=>{var sr=Math.floor((nt.Bb+7-(nt.ub+6)%7)/7);if(2>=(nt.ub+371-nt.Bb-2)%7&&sr++,sr)sr==53&&((jr=(nt.ub+371-nt.Bb)%7)==4||jr==3&&Al(nt.Cb)||(sr=1));else{sr=52;var jr=(nt.ub+7-nt.Bb-1)%7;(jr==4||jr==5&&Al(nt.Cb%400-1))&&sr++}return ze(sr,2)},"%w":nt=>nt.ub,"%W":nt=>ze(Math.floor((nt.Bb+7-(nt.ub+6)%7)/7),2),"%y":nt=>(nt.Cb+1900).toString().substring(2),"%Y":nt=>nt.Cb+1900,"%z":nt=>{var sr=0<=(nt=nt.dc);return nt=Math.abs(nt)/60,(sr?"+":"-")+("0000"+(nt/60*100+nt%60)).slice(-4)},"%Z":nt=>nt.hc,"%%":()=>"%"},K=K.replace(/%%/g,"\0\0"),Ft)K.includes(Qt)&&(K=K.replace(new RegExp(Qt,"g"),Ft[Qt](J)));return Qt=function(nt){var sr=Array(Rm(nt)+1);return ry(nt,sr,0,sr.length),sr}(K=K.replace(/\0\0/g,"%")),Qt.length>F?0:(FM(Qt,m),Qt.length-1)}function OM(m,F,K,J){return jy(m>>>0,F>>>0,K>>>0,J>>>0)}we||function(){for(var m=v.numThreads-1;m--;)Xw();lp.unshift(()=>{$i++,function(F){we?F():Promise.all(is.map(Kw)).then(F)}(()=>zf())})}();for(var Uy=Array(256),Vf=0;256>Vf;++Vf)Uy[Vf]=String.fromCharCode(Vf);hy=Uy,os=v.BindingError=class extends Error{constructor(m){super(m),this.name="BindingError"}},v.InternalError=class extends Error{constructor(m){super(m),this.name="InternalError"}},To.push(0,1,void 0,1,null,1,!0,1,!1,1),v.count_emval_handles=()=>To.length/2-5-jm.length;var zM=[Dm,Ww,Qw,ey,ty,ny,iy,oy,sy,ay,ly,uy,cy,dy,py,fy,Ey,Cy,Fy,Oy,zy,Dy,Ly,Ry],Kt=function(){function m(K,J){return Kt=K.exports,Kt=function(){var fe=Kt,ze={};for(let[lt,yt]of Object.entries(fe))ze[lt]=typeof yt=="function"?(...Pt)=>{Bf.push(lt);try{return yt(...Pt)}finally{gi||(Bf.pop(),io&&as===1&&Bf.length===0&&(as=0,Ys+=1,Rf(Yy),typeof Fibers<"u"&&Fibers.oc()))}}:yt;return ze}(),Kt=function(){var fe=Kt,ze=yt=>Pt=>yt(Pt)>>>0,lt=yt=>()=>yt()>>>0;return(fe=Object.assign({},fe)).Ca=ze(fe.Ca),fe.fb=lt(fe.fb),fe.gb=ze(fe.gb),fe.emscripten_main_runtime_thread_id=lt(fe.emscripten_main_runtime_thread_id),fe.sb=ze(fe.sb),fe.tb=lt(fe.tb),fe}(),Gw.push(Kt.ib),Ln.unshift(Kt.Ba),Hr=J,zf(),Kt}var F=Uw();if($i++,v.instantiateWasm)try{return v.instantiateWasm(F,m)}catch(K){ir(`Module.instantiateWasm callback failed with error: ${K}`),q(K)}return Im||(Im=v.locateFile?Rw("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(r("./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm"),r.b).href),function(K,J){var fe=Im;return Dt||typeof WebAssembly.instantiateStreaming!="function"||Rw(fe)||Bw(fe)||typeof fetch!="function"?jw(fe,K,J):fetch(fe,{credentials:"same-origin"}).then(ze=>WebAssembly.instantiateStreaming(ze,K).then(J,function(lt){return ir(`wasm streaming compile failed: ${lt}`),ir("falling back to ArrayBuffer instantiation"),jw(fe,K,J)}))}(F,function(K){m(K.instance,K.module)}).catch(q),{}}(),Vy=m=>(Vy=Kt.Ca)(m),Wy=()=>(Wy=Kt.Da)();v._OrtInit=(m,F)=>(v._OrtInit=Kt.Ea)(m,F),v._OrtGetLastError=(m,F)=>(v._OrtGetLastError=Kt.Fa)(m,F),v._OrtCreateSessionOptions=(m,F,K,J,fe,ze,lt,yt,Pt,Ft)=>(v._OrtCreateSessionOptions=Kt.Ga)(m,F,K,J,fe,ze,lt,yt,Pt,Ft),v._OrtAppendExecutionProvider=(m,F)=>(v._OrtAppendExecutionProvider=Kt.Ha)(m,F),v._OrtAddFreeDimensionOverride=(m,F,K)=>(v._OrtAddFreeDimensionOverride=Kt.Ia)(m,F,K),v._OrtAddSessionConfigEntry=(m,F,K)=>(v._OrtAddSessionConfigEntry=Kt.Ja)(m,F,K),v._OrtReleaseSessionOptions=m=>(v._OrtReleaseSessionOptions=Kt.Ka)(m),v._OrtCreateSession=(m,F,K)=>(v._OrtCreateSession=Kt.La)(m,F,K),v._OrtReleaseSession=m=>(v._OrtReleaseSession=Kt.Ma)(m),v._OrtGetInputOutputCount=(m,F,K)=>(v._OrtGetInputOutputCount=Kt.Na)(m,F,K),v._OrtGetInputName=(m,F)=>(v._OrtGetInputName=Kt.Oa)(m,F),v._OrtGetOutputName=(m,F)=>(v._OrtGetOutputName=Kt.Pa)(m,F),v._OrtFree=m=>(v._OrtFree=Kt.Qa)(m),v._OrtCreateTensor=(m,F,K,J,fe,ze)=>(v._OrtCreateTensor=Kt.Ra)(m,F,K,J,fe,ze),v._OrtGetTensorData=(m,F,K,J,fe)=>(v._OrtGetTensorData=Kt.Sa)(m,F,K,J,fe),v._OrtReleaseTensor=m=>(v._OrtReleaseTensor=Kt.Ta)(m),v._OrtCreateRunOptions=(m,F,K,J)=>(v._OrtCreateRunOptions=Kt.Ua)(m,F,K,J),v._OrtAddRunConfigEntry=(m,F,K)=>(v._OrtAddRunConfigEntry=Kt.Va)(m,F,K),v._OrtReleaseRunOptions=m=>(v._OrtReleaseRunOptions=Kt.Wa)(m),v._OrtCreateBinding=m=>(v._OrtCreateBinding=Kt.Xa)(m),v._OrtBindInput=(m,F,K)=>(v._OrtBindInput=Kt.Ya)(m,F,K),v._OrtBindOutput=(m,F,K,J)=>(v._OrtBindOutput=Kt.Za)(m,F,K,J),v._OrtClearBoundOutputs=m=>(v._OrtClearBoundOutputs=Kt._a)(m),v._OrtReleaseBinding=m=>(v._OrtReleaseBinding=Kt.$a)(m),v._OrtRunWithBinding=(m,F,K,J,fe)=>(v._OrtRunWithBinding=Kt.ab)(m,F,K,J,fe),v._OrtRun=(m,F,K,J,fe,ze,lt,yt)=>(v._OrtRun=Kt.bb)(m,F,K,J,fe,ze,lt,yt),v._OrtEndProfiling=m=>(v._OrtEndProfiling=Kt.cb)(m),v._JsepOutput=(m,F,K)=>(v._JsepOutput=Kt.db)(m,F,K),v._JsepGetNodeName=m=>(v._JsepGetNodeName=Kt.eb)(m);var Wf,Il=()=>(Il=Kt.fb)(),Gf=v._malloc=m=>(Gf=v._malloc=Kt.gb)(m),oo=v._free=m=>(oo=v._free=Kt.hb)(m),Ym=(m,F,K,J,fe,ze)=>(Ym=Kt.kb)(m,F,K,J,fe,ze),Gy=()=>(Gy=Kt.lb)(),Hy=(m,F,K,J,fe)=>(Hy=Kt.mb)(m,F,K,J,fe),Zm=m=>(Zm=Kt.nb)(m),Hf=m=>(Hf=Kt.ob)(m),qy=()=>(qy=Kt.pb)(),Ky=(m,F)=>(Ky=Kt.qb)(m,F),qf=m=>(qf=Kt.rb)(m),Jm=m=>(Jm=Kt.sb)(m),eg=()=>(eg=Kt.tb)(),Xy=v.dynCall_ii=(m,F)=>(Xy=v.dynCall_ii=Kt.vb)(m,F),Qy=m=>(Qy=Kt.wb)(m),Yy=()=>(Yy=Kt.xb)(),Zy=m=>(Zy=Kt.yb)(m),Jy=()=>(Jy=Kt.zb)();function ev(){0<$i||(we?(H(v),we||Df(Ln),startWorker(v)):(Df(lp),0<$i||Wf||(Wf=!0,v.calledRun=!0,gi||(we||Df(Ln),H(v),we||Df(Jn)))))}return v.___start_em_js=862461,v.___stop_em_js=862683,v.stackSave=()=>eg(),v.stackRestore=m=>qf(m),v.stackAlloc=m=>Jm(m),v.UTF8ToString=An,v.stringToUTF8=$l,v.lengthBytesUTF8=Rm,ns=function m(){Wf||ev(),Wf||(ns=m)},ev(),oe}),Et=bt,((n=globalThis.self)==null?void 0:n.name)==="em-pthread"&&bt()}),at,Ot,Ut,Xt,Yt,rr,Ht,Pr,Yr=h(()=>{var n,i;ve(),at=import.meta.url??(typeof document<"u"?(n=document.currentScript)==null?void 0:n.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}},Xt=async s=>{let u=await(await fetch(s,{credentials:"same-origin"})).blob();return URL.createObjectURL(u)},Yt=(ft(),y(Re)).default,rr=async()=>{if(!at)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(Ut(at))return[void 0,Yt()];let s=await Xt(at);return[s,Yt(s)]},Ht=(Lt(),y(ht)).default,Pr=async(s,u,c)=>[void 0,Ht]}),$r,mt,$t,Bt,un,Bi,Mi,Gr,wn=h(()=>{Yr(),mt=!1,$t=!1,Bt=!1,un=()=>{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}},Bi=()=>{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}},Mi=async n=>{if(mt)return Promise.resolve();if($t)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Bt)throw new Error("previous call to 'initializeWebAssembly()' failed.");$t=!0;let i=n.initTimeout,s=n.numThreads;if(!Bi())throw new Error("WebAssembly SIMD is not supported in the current environment.");let u=un();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."),n.numThreads=s=1);let c=n.wasmPaths,f=typeof c=="string"?c:void 0,d=c==null?void 0:c.mjs,x=(d==null?void 0:d.href)??d,k=c==null?void 0:c.wasm,$=(k==null?void 0:k.href)??k,H=n.wasmBinary,[q,v]=await Pr(x,f,s>1),oe=!1,te=[];if(i>0&&te.push(new Promise(de=>{setTimeout(()=>{oe=!0,de()},i)})),te.push(new Promise((de,we)=>{let be={numThreads:s};H?be.wasmBinary=H:($||f)&&(be.locateFile=(he,De)=>$??(f??De)+he),v(be).then(he=>{$t=!1,mt=!0,$r=he,de(),q&&URL.revokeObjectURL(q)},he=>{$t=!1,Bt=!0,we(he)})})),await Promise.race(te),oe)throw new Error(`WebAssembly backend initializing failed due to timeout: ${i}ms`)},Gr=()=>{if(mt&&$r)return $r;throw new Error("WebAssembly is not initialized yet.")}}),Kr,pi,Dr,Ni=h(()=>{wn(),Kr=(n,i)=>{let s=Gr(),u=s.lengthBytesUTF8(n)+1,c=s._malloc(u);return s.stringToUTF8(n,c,u),i.push(c),c},pi=(n,i,s,u)=>{if(typeof n=="object"&&n!==null){if(s.has(n))throw new Error("Circular reference in options");s.add(n)}Object.entries(n).forEach(([c,f])=>{let d=i?i+c:c;if(typeof f=="object")pi(f,d+".",s,u);else if(typeof f=="string"||typeof f=="number")u(d,f.toString());else if(typeof f=="boolean")u(d,f?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof f}`)})},Dr=n=>{let i=Gr(),s=i.stackSave();try{let u=i.stackAlloc(8);i._OrtGetLastError(u,u+4);let c=i.HEAP32[u/4],f=i.HEAPU32[u/4+1],d=f?i.UTF8ToString(f):"";throw new Error(`${n} ERROR_CODE: ${c}, ERROR_MESSAGE: ${d}`)}finally{i.stackRestore(s)}}}),Ti,Cs=h(()=>{wn(),Ni(),Ti=n=>{let i=Gr(),s=0,u=[],c=n||{};try{if((n==null?void 0:n.logSeverityLevel)===void 0)c.logSeverityLevel=2;else if(typeof n.logSeverityLevel!="number"||!Number.isInteger(n.logSeverityLevel)||n.logSeverityLevel<0||n.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${n.logSeverityLevel}`);if((n==null?void 0:n.logVerbosityLevel)===void 0)c.logVerbosityLevel=0;else if(typeof n.logVerbosityLevel!="number"||!Number.isInteger(n.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${n.logVerbosityLevel}`);(n==null?void 0:n.terminate)===void 0&&(c.terminate=!1);let f=0;return(n==null?void 0:n.tag)!==void 0&&(f=Kr(n.tag,u)),s=i._OrtCreateRunOptions(c.logSeverityLevel,c.logVerbosityLevel,!!c.terminate,f),s===0&&Dr("Can't create run options."),(n==null?void 0:n.extra)!==void 0&&pi(n.extra,"",new WeakSet,(d,x)=>{let k=Kr(d,u),$=Kr(x,u);i._OrtAddRunConfigEntry(s,k,$)!==0&&Dr(`Can't set a run config entry: ${d} - ${x}.`)}),[s,u]}catch(f){throw s!==0&&i._OrtReleaseRunOptions(s),u.forEach(d=>i._free(d)),f}}}),Lo,Ro,Bo,No,ji,Ps=h(()=>{wn(),Ni(),Lo=n=>{switch(n){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${n}`)}},Ro=n=>{switch(n){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${n}`)}},Bo=n=>{n.extra||(n.extra={}),n.extra.session||(n.extra.session={});let i=n.extra.session;i.use_ort_model_bytes_directly||(i.use_ort_model_bytes_directly="1"),n.executionProviders&&n.executionProviders.some(s=>(typeof s=="string"?s:s.name)==="webgpu")&&(n.enableMemPattern=!1)},No=(n,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 x=Kr("deviceType",s),k=Kr(d,s);Gr()._OrtAddSessionConfigEntry(n,x,k)!==0&&Dr(`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 x=Kr("preferredLayout",s),k=Kr(d.preferredLayout,s);Gr()._OrtAddSessionConfigEntry(n,x,k)!==0&&Dr(`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 f=Kr(c,s);Gr()._OrtAppendExecutionProvider(n,f)!==0&&Dr(`Can't append execution provider: ${c}.`)}},ji=n=>{let i=Gr(),s=0,u=[],c=n||{};Bo(c);try{let f=Lo(c.graphOptimizationLevel??"all"),d=Ro(c.executionMode??"sequential"),x=typeof c.logId=="string"?Kr(c.logId,u):0,k=c.logSeverityLevel??2;if(!Number.isInteger(k)||k<0||k>4)throw new Error(`log serverity level is not valid: ${k}`);let $=c.logVerbosityLevel??0;if(!Number.isInteger($)||$<0||$>4)throw new Error(`log verbosity level is not valid: ${$}`);let H=typeof c.optimizedModelFilePath=="string"?Kr(c.optimizedModelFilePath,u):0;if(s=i._OrtCreateSessionOptions(f,!!c.enableCpuMemArena,!!c.enableMemPattern,d,!!c.enableProfiling,0,x,k,$,H),s===0&&Dr("Can't create session options."),c.executionProviders&&No(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 q=Kr("enableGraphCapture",u),v=Kr(c.enableGraphCapture.toString(),u);i._OrtAddSessionConfigEntry(s,q,v)!==0&&Dr(`Can't set a session config entry: 'enableGraphCapture' - ${c.enableGraphCapture}.`)}if(c.freeDimensionOverrides)for(let[q,v]of Object.entries(c.freeDimensionOverrides)){if(typeof q!="string")throw new Error(`free dimension override name must be a string: ${q}`);if(typeof v!="number"||!Number.isInteger(v)||v<0)throw new Error(`free dimension override value must be a non-negative integer: ${v}`);let oe=Kr(q,u);i._OrtAddFreeDimensionOverride(s,oe,v)!==0&&Dr(`Can't set a free dimension override: ${q} - ${v}.`)}return c.extra!==void 0&&pi(c.extra,"",new WeakSet,(q,v)=>{let oe=Kr(q,u),te=Kr(v,u);i._OrtAddSessionConfigEntry(s,oe,te)!==0&&Dr(`Can't set a session config entry: ${q} - ${v}.`)}),[s,u]}catch(f){throw s!==0&&i._OrtReleaseSessionOptions(s),u.forEach(d=>i._free(d)),f}}}),fo,fi,ki,Si,Ji,ho,mo,Zt=h(()=>{fo=n=>{switch(n){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float16":return 10;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;default:throw new Error(`unsupported data type: ${n}`)}},fi=n=>{switch(n){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 10:return"float16";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";default:throw new Error(`unsupported data type: ${n}`)}},ki=n=>[void 0,4,1,1,2,2,4,8,void 0,1,2,8,4,8,void 0,void 0,void 0][n],Si=n=>{switch(n){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: ${n}`)}},Ji=n=>{switch(n){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: ${n}`)}},ho=n=>n==="float32"||n==="float16"||n==="int32"||n==="int64"||n==="uint32"||n==="uint8"||n==="bool",mo=n=>{switch(n){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: ${n}`)}}}),eo,jo=h(()=>{ve(),eo=async n=>{if(typeof n=="string"){let i=await fetch(n);if(!i.ok)throw new Error(`failed to load external data file: ${n}`);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: ${n}, no response body.`);let c=i.body.getReader(),f;try{f=new ArrayBuffer(u)}catch(x){if(x instanceof RangeError){let k=Math.ceil(u/65536);f=new WebAssembly.Memory({initial:k,maximum:k}).buffer}else throw x}let d=0;for(;;){let{done:x,value:k}=await c.read();if(x)break;let $=k.byteLength;new Uint8Array(f,d,$).set(k),d+=$}return new Uint8Array(f,0,u)}}else return n instanceof Blob?new Uint8Array(await n.arrayBuffer()):n instanceof Uint8Array?n:new Uint8Array(n)}}),Uo,go,Vo,Wo,_o,Go,Vr,jn=h(()=>{Zt(),Uo=["V","I","W","E","F"],go=(n,i)=>{console.log(`[${Uo[n]},${new Date().toISOString()}]${i}`)},_o=(n,i)=>{Vo=n,Wo=i},Go=(n,i)=>{let s=Ji(n),u=Ji(Vo);s>=u&&go(s,typeof i=="function"?i():i)},Vr=(...n)=>{Wo&&Go(...n)}}),Ue,W=h(()=>{Zt(),Ue=(n,i)=>new(Si(i))(n)}),pe=h(()=>{}),Ce,Fe,Oe,rt,Mt,St,kt,It,tr,Ar=h(()=>{jn(),pe(),Ce=new Map([[64,250],[128,200],[256,200],[512,200],[2048,230],[4096,200],[8192,50],[16384,50],[32768,50],[65536,50],[131072,50],[262144,50],[524288,50],[1048576,50],[2097152,30],[4194304,20],[8388608,10],[12582912,10],[16777216,10],[26214400,15],[33554432,22],[44236800,2],[58982400,6],[67108864,6],[134217728,6],[167772160,6]]),Fe=[],Oe=n=>Math.ceil(n/16)*16,rt=n=>{for(let i=0;iMt++,kt=async(n,i,s,u)=>{let c=Oe(s),f=n.device.createBuffer({size:c,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let d=n.getCommandEncoder();n.endComputePass(),d.copyBufferToBuffer(i,0,f,0,c),n.flush(),await f.mapAsync(GPUMapMode.READ);let x=f.getMappedRange();if(u){let k=u();return k.set(new Uint8Array(x,0,s)),k}else return new Uint8Array(x.slice(0,s))}finally{f.destroy()}},It=class{constructor(n){this.backend=n,this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.buffersForUploadingPending=[],this.buffersPending=[],this.externalBuffers=new Map,this.capturedPendingBuffers=new Map;for(let[i]of Ce)Fe.push(i),this.freeBuffers.set(i,[]),this.freeUniformBuffers.set(i,[])}upload(n,i){let s=i.buffer,u=i.byteOffset,c=i.byteLength,f=Oe(c),d=this.storageCache.get(n);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 x=this.backend.device.createBuffer({mappedAtCreation:!0,size:f,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),k=x.getMappedRange();new Uint8Array(k).set(new Uint8Array(s,u,c)),x.unmap();let $=this.backend.getCommandEncoder();this.backend.endComputePass(),$.copyBufferToBuffer(x,0,d.gpuData.buffer,0,f),Vr("verbose",()=>`[WebGPU] GpuDataManager.upload(id=${n})`),this.buffersForUploadingPending.push(x)}memcpy(n,i){let s=this.storageCache.get(n);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),f=this.backend.getCommandEncoder();this.backend.endComputePass(),f.copyBufferToBuffer(s.gpuData.buffer,0,u.gpuData.buffer,0,c)}registerExternalBuffer(n,i,s){let u;if(s){if(u=this.externalBuffers.get(s),u===void 0)throw new Error("previous buffer is not registered");if(n===s)return Vr("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=St();return this.storageCache.set(u,{gpuData:{id:u,type:0,buffer:n},originalSize:i}),this.externalBuffers.set(n,u),Vr("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${i}) => id=${u}, registered.`),u}unregisterExternalBuffer(n){let i=this.externalBuffers.get(n);i!==void 0&&(this.storageCache.delete(i),this.externalBuffers.delete(n),Vr("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${i}`))}create(n,i=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let s=rt(n),u,c=(i&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,f=(i&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(c||f){let x=(c?this.freeBuffers:this.freeUniformBuffers).get(s);x?x.length>0?u=x.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:St(),type:0,buffer:u};return this.storageCache.set(d.id,{gpuData:d,originalSize:n}),Vr("verbose",()=>`[WebGPU] GpuDataManager.create(size=${n}) => id=${d.id}`),d}get(n){var i;return(i=this.storageCache.get(n))==null?void 0:i.gpuData}release(n){let i=this.storageCache.get(n);if(!i)throw new Error("releasing data does not exist");return Vr("verbose",()=>`[WebGPU] GpuDataManager.release(id=${n}), gpuDataId=${i.gpuData.id}`),this.storageCache.delete(n),this.buffersPending.push(i.gpuData.buffer),i.originalSize}async download(n,i){let s=this.storageCache.get(n);if(!s)throw new Error("data does not exist");await kt(this.backend,s.gpuData.buffer,s.originalSize,i)}refreshPendingBuffers(){for(let n of this.buffersForUploadingPending)n.destroy();if(this.buffersForUploadingPending=[],this.buffersPending.length!==0)if(this.backend.sessionStatus==="default"){for(let n of this.buffersPending){let i=Ce.get(n.size);if((n.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE){let s=this.freeBuffers.get(n.size)||[];i===void 0||s.length>=i?n.destroy():s.push(n)}else if((n.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM){let s=this.freeUniformBuffers.get(n.size)||[];i===void 0||s.length>=i?n.destroy():s.push(n)}else n.destroy()}this.buffersPending=[]}else{let n=this.capturedPendingBuffers.get(this.backend.currentSessionId);n||(n=[],this.capturedPendingBuffers.set(this.backend.currentSessionId,n));for(let i of this.buffersPending)n.push(i);this.buffersPending=[]}}dispose(){this.freeBuffers.forEach(n=>{n.forEach(i=>{i.destroy()})}),this.freeUniformBuffers.forEach(n=>{n.forEach(i=>{i.destroy()})}),this.storageCache.forEach(n=>{n.gpuData.buffer.destroy()}),this.capturedPendingBuffers.forEach(n=>{n.forEach(i=>{i.destroy()})}),this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.capturedPendingBuffers=new Map}onReleaseSession(n){let i=this.capturedPendingBuffers.get(n);i&&(i.forEach(s=>{s.destroy()}),this.capturedPendingBuffers.delete(n))}},tr=(...n)=>new It(...n)}),or,qt,_r=h(()=>{or=class{constructor(n){Object.assign(this,n)}get cacheKey(){return this.key||(this.key=Object.getOwnPropertyNames(this).sort().map(n=>`${this[n]}`).join(";")),this.key}},qt=n=>new or(n)}),Cn,gn,ct,Kn,Tr,cn,On,Jt=h(()=>{Cn=class{static calcMatMulShape(n,i){return n[1]!==i[0]?void 0:[n[0],i[1]]}},gn=class{static calcShape(n,i,s=!1){let u=n.length,c=i.length;if(u===0)return i;if(c===0)return n;let f=Math.max(n.length,i.length),d=new Array(f);if(s){if(u<2||c<2)return;let x=Cn.calcMatMulShape([n[u-2],n[u-1]],[i[c-2],i[c-1]]);if(x===void 0)return;[d[f-2],d[f-1]]=x}for(let x=s?3:1;x<=f;x++){let k=u-x<0?1:n[u-x],$=c-x<0?1:i[c-x];if(k!==$&&k>1&&$>1)return;let H=Math.max(k,$);if(k&&$)d[f-x]=Math.max(k,$);else{if(H>1)return;d[f-x]=0}}return d}static isValidBroadcast(n,i){let s=n.length,u=i.length;if(s>u)return!1;for(let c=1;c<=s;c++)if(n[s-c]!==1&&n[s-c]!==i[u-c])return!1;return!0}},ct=class kh{static size(i){return kh.getSizeFromDimensionRange(i,0,i.length)}static convertShape(i,s=4){let u=i.length;if(u===0)return[];let c=new Array(u),f=u-1;for(;f>=0;){if(i[f]%s===0){c[f]=i[f]/s;break}if(s%i[f]!==0)throw new Error("cannot convert shape");c[f]=1,s/=i[f],f--}for(f--;f>=0;f--)c[f]=i[f];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 kh.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 kh.getSizeFromDimensionRange(i,0,s)}static getSizeFromDimensionRange(i,s,u){let c=1;for(let f=s;f=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,f)=>c+s[f]+s[f+u])}static areEqual(i,s){return i.length!==s.length?!1:i.every((u,c)=>u===s[c])}},Kn=class xp{static adjustPoolAttributes(i,s,u,c,f,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 x=0;x=u.length?u.push(s[x+2]):u[x]=s[x+2];for(let x=0;x=u[x]||d[x+u.length]>=u[x])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(i,s,u,c,f,d,x){if(x){if(f.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 k=0;k{Zt(),Jt(),Un=64,yn=(n,i)=>{if(i===3)throw new Error("vec3 has same alignment as vec4, use vec4 instead");switch(n){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: ${n}`)}},Sr=(n,i=1)=>{let s=yn(n,i);return typeof s=="string"?s:s[0]},Er=(n,i=1)=>{let s=yn(n,i);return typeof s=="string"?s:s[1]},At=(...n)=>{let i=[];return n.forEach(s=>{s.length!==0&&i.push({type:12,data:s},{type:12,data:ct.computeStrides(s)})}),i},vr=n=>n%4===0?4:n%2===0?2:1,Lr=(n="f32",i,s="0")=>!i||i===1?`${n}(${s})`:`vec${i}<${n}>(${s})`,Xr=(n,i,s)=>n==="f32"?s:i===1?`f32(${s})`:`vec${i}(${s})`,Vn=(n,i)=>i===4?`(${n}.x + ${n}.y + ${n}.z + ${n}.w)`:i===2?`(${n}.x + ${n}.y)`:i===3?`(${n}.x + ${n}.y + ${n}.z)`:n,zt=(n,i,s,u)=>n.startsWith("uniforms.")&&s>4?typeof i=="string"?u==="f16"?`${n}[(${i}) / 8][(${i}) % 8 / 4][(${i}) % 8 % 4]`:`${n}[(${i}) / 4][(${i}) % 4]`:u==="f16"?`${n}[${Math.floor(i/8)}][${Math.floor(i%8/4)}][${i%8%4}]`:`${n}[${Math.floor(i/4)}][${i%4}]`:s>1?`${n}[${i}]`:n,$s=(n,i,s,u,c)=>{let f=typeof s=="number",d=f?s:s.length,x=[...new Array(d).keys()],k=d<2?"u32":d<=4?`vec${d}`:`array`,$=yn(i,c),H=typeof $=="string"?$:$[1],q=typeof $=="string"?$:$[0],v={indices:k,value:H,storage:q,tensor:i},oe=ot=>typeof ot=="string"?ot:`${ot}u`,te={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},de=f?"uniforms.":"",we=`${de}${n}_shape`,be=`${de}${n}_strides`,he="";for(let ot=0;ot ${v.indices} { + var indices: ${v.indices}; + var current = offset; + ${he} + return indices; + }`,Ae=ot=>(te.offsetToIndices=!0,d<2?ot:`o2i_${n}(${ot})`),Ie=[];if(d>=2)for(let ot=d-1;ot>=0;ot--)Ie.push(`${zt(be,ot,d)} * (indices[${ot}])`);let gt=d<2?"":` + fn i2o_${n}(indices: ${v.indices}) -> u32 { + return ${Ie.join("+")}; + }`,ut=ot=>(te.indicesToOffset=!0,d<2?ot:`i2o_${n}(${ot})`),vt=(...ot)=>d===0?"0u":`${v.indices}(${ot.map(oe).join(",")})`,Dt=(ot,Vt)=>d<2?`${ot}`:`${zt(ot,Vt,d)}`,Rt=(ot,Vt,nr)=>d<2?`${ot}=${nr};`:`${zt(ot,Vt,d)}=${nr};`,gr={},Mr=(ot,Vt)=>{te.broadcastedIndicesToOffset=!0;let nr=`${Vt.name}broadcastedIndicesTo${n}Offset`;if(nr in gr)return`${nr}(${ot})`;let Wr=[];for(let pn=d-1;pn>=0;pn--){let kn=Vt.indicesGet("outputIndices",pn+Vt.rank-d);Wr.push(`${Dt(be,pn)} * (${kn} % ${Dt(we,pn)})`)}return gr[nr]=`fn ${nr}(outputIndices: ${Vt.type.indices}) -> u32 { + return ${Wr.length>0?Wr.join("+"):"0u"}; + }`,`${nr}(${ot})`},ir=(ot,Vt)=>(()=>{if(v.storage===v.value)return`${n}[${ot}]=${Vt};`;if(v.storage==="vec2"&&v.value==="i32")return`${n}[${ot}]=vec2(u32(${Vt}), select(0u, 0xFFFFFFFFu, ${Vt} < 0));`;if(v.storage==="vec2"&&v.value==="u32")return`${n}[${ot}]=vec2(u32(${Vt}), 0u);`;if(v.storage==="u32"&&v.value==="vec4")return`${n}[${ot}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${Vt}));`;throw new Error(`not supported combination of storage type ${v.storage} and value type ${v.value} yet`)})(),Fr=ot=>(()=>{if(v.storage===v.value)return`${n}[${ot}]`;if(v.storage==="vec2"&&v.value==="i32")return`i32(${n}[${ot}].x)`;if(v.storage==="vec2"&&v.value==="u32")return`u32(${n}[${ot}].x)`;if(v.storage==="u32"&&v.value==="vec4")return`vec4(bool(${n}[${ot}] & 0xFFu), bool(${n}[${ot}] & 0xFF00u), bool(${n}[${ot}] & 0xFF0000u), bool(${n}[${ot}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${v.storage} and value type ${v.value} yet`)})(),Zr=d<2?"":` + fn get_${n}ByIndices(indices: ${v.indices}) -> ${H} { + return ${Fr(`i2o_${n}(indices)`)}; + }`,hr=d<2?"":(()=>{let ot=x.map(nr=>`d${nr}: u32`).join(", "),Vt=x.map(nr=>`d${nr}`).join(", ");return` + fn get_${n}(${ot}) -> ${H} { + return get_${n}ByIndices(${vt(Vt)}); + }`})(),Hr=(...ot)=>{if(ot.length!==d)throw new Error(`indices length must be ${d}`);let Vt=ot.map(oe).join(",");return d===0?Fr("0u"):d===1?Fr(Vt[0]):(te.get=!0,te.getByIndices=!0,te.indicesToOffset=!0,`get_${n}(${Vt})`)},Nt=ot=>d<2?Fr(ot):(te.getByIndices=!0,te.indicesToOffset=!0,`get_${n}ByIndices(${ot})`),er=d<2?"":` + fn set_${n}ByIndices(indices: ${v.indices}, value: ${H}) { + ${ir(`i2o_${n}(indices)`,"value")} + }`,yr=d<2?"":(()=>{let ot=x.map(nr=>`d${nr}: u32`).join(", "),Vt=x.map(nr=>`d${nr}`).join(", ");return` + fn set_${n}(${ot}, value: ${H}) { + set_${n}ByIndices(${vt(Vt)}, value); + }`})();return{impl:()=>{let ot=[],Vt=!1;return te.offsetToIndices&&(ot.push(De),Vt=!0),te.indicesToOffset&&(ot.push(gt),Vt=!0),te.broadcastedIndicesToOffset&&(Object.values(gr).forEach(nr=>ot.push(nr)),Vt=!0),te.set&&(ot.push(yr),Vt=!0),te.setByIndices&&(ot.push(er),Vt=!0),te.get&&(ot.push(hr),Vt=!0),te.getByIndices&&(ot.push(Zr),Vt=!0),!f&&Vt&&ot.unshift(`const ${we} = ${v.indices}(${s.join(",")});`,`const ${be} = ${v.indices}(${ct.computeStrides(s).join(",")});`),ot.join(` +`)},type:v,offsetToIndices:Ae,indicesToOffset:ut,broadcastedIndicesToOffset:Mr,indices:vt,indicesGet:Dt,indicesSet:Rt,set:(...ot)=>{if(ot.length!==d+1)throw new Error(`indices length must be ${d}`);let Vt=ot[d];if(typeof Vt!="string")throw new Error("value must be string");let nr=ot.slice(0,d).map(oe).join(",");return d===0?ir("0u",Vt):d===1?ir(nr[0],Vt):(te.set=!0,te.setByIndices=!0,te.indicesToOffset=!0,`set_${n}(${nr}, ${Vt})`)},setByOffset:ir,setByIndices:(ot,Vt)=>d<2?ir(ot,Vt):(te.setByIndices=!0,te.indicesToOffset=!0,`set_${n}ByIndices(${ot}, ${Vt});`),get:Hr,getByOffset:Fr,getByIndices:Nt,usage:u,name:n,strides:be,shape:we,rank:d}},_t=(n,i,s,u=1)=>$s(n,i,s,"input",u),Gt=(n,i,s,u=1)=>$s(n,i,s,"output",u),ma=(n,i,s,u=1)=>$s(n,i,s,"internal",u),ga=class{constructor(n,i){this.normalizedDispatchGroup=n,this.limits=i,this.internalVariables=[],this.variables=[],this.uniforms=[],this.variableIndex=0}guardAgainstOutOfBoundsWorkgroupSizes(n){return`if (global_idx >= ${typeof n=="number"?`${n}u`:n}) { return; }`}mainStart(n=Un){let i=typeof n=="number"?n:n[0],s=typeof n=="number"?1:n[1],u=typeof n=="number"?1:n[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,f=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(${f}) { + ${d} + `}appendVariableUniforms(n){n.rank!==0&&(n.shape.startsWith("uniforms.")&&this.uniforms.push({name:n.shape.replace("uniforms.",""),type:"u32",length:n.rank}),n.strides.startsWith("uniforms.")&&this.uniforms.push({name:n.strides.replace("uniforms.",""),type:"u32",length:n.rank}))}declareVariable(n,i){if(n.usage==="internal")throw new Error("cannot use internal variable with declareVariable(). use registerInternalVariables() instead.");this.variables.push(n),this.appendVariableUniforms(n);let s=n.usage==="input"?"read":"read_write",u=n.type.storage;return`@group(0) @binding(${i}) var ${n.name}: array<${u}>;`}declareVariables(...n){return n.map(i=>this.declareVariable(i,this.variableIndex++)).join(` +`)}registerInternalVariable(n){if(n.usage!=="internal")throw new Error("cannot use input or output variable with registerInternalVariable(). use declareVariables() instead.");this.internalVariables.push(n),this.appendVariableUniforms(n)}registerInternalVariables(...n){return n.forEach(i=>this.registerInternalVariable(i)),this}registerUniform(n,i,s=1){return this.uniforms.push({name:n,type:i,length:s}),this}registerUniforms(n){return this.uniforms=this.uniforms.concat(n),this}uniformDeclaration(){if(this.uniforms.length===0)return"";let n=[];for(let{name:i,type:s,length:u}of this.uniforms)if(u&&u>4)s==="f16"?n.push(`@align(16) ${i}:array, ${Math.ceil(u/8)}>`):n.push(`${i}:array, ${Math.ceil(u/4)}>`);else{let c=u==null||u===1?s:`vec${u}<${s}>`;n.push(`${i}:${c}`)}return` + struct Uniforms { ${n.join(", ")} }; + @group(0) @binding(${this.variableIndex}) var uniforms: Uniforms;`}get additionalImplementations(){return this.uniformDeclaration()+this.variables.map(n=>n.impl()).join(` +`)+this.internalVariables.map(n=>n.impl()).join(` +`)}get variablesInfo(){if(this.uniforms.length===0)return;let n=i=>[12,10,1,6][["u32","f16","f32","i32"].indexOf(i)];return this.uniforms.map(i=>[n(i.type),i.length??1])}},cu=(n,i)=>new ga(n,i),wo=(n,i)=>{let s=n.length,u=[];for(let c=0;c1&&d===1&&u.unshift(f)}return u}}),du,_a,Ho,pu,hi,fu,wa,yo=h(()=>{Zt(),Jt(),_r(),ar(),du=n=>{if(!n||n.length!==1)throw new Error("Transpose requires 1 input.")},_a=(n,i)=>i&&i.length!==n?[...new Array(n).keys()].reverse():i,Ho=(n,i)=>ct.sortBasedOnPerm(n,_a(n.length,i)),pu=(n,i,s,u)=>{let c=[];c.push(`fn perm(i: ${u.type.indices}) -> ${s.type.indices} { + var a: ${s.type.indices};`);for(let f=0;f{let s=n.dataType,u=n.dims.length,c=_a(u,i),f=Ho(n.dims,c),d=Gt("output",s,f.length),x=_t("a",s,u),k;if(c.length===2&&c[0]===1&&c[1]===0){let $=d.type.value,H=[16,16,1];k=q=>` + ${q.registerUniform("output_size","u32").declareVariables(x,d)} + var tile : array, ${H[0]}>; + ${q.mainStart(H)} + var x = workgroup_id.x * ${H[0]}u + local_id.x; + var y = workgroup_id.y * ${H[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] = ${x.getByOffset("y * width + x")}; + } + workgroupBarrier(); + x = workgroup_id.y * ${H[0]}u + local_id.x; + y = workgroup_id.x * ${H[0]}u + local_id.y; + if (x < height && y < width) { + ${d.setByOffset("y * height + x","tile[local_id.x][local_id.y]")} + } + }`}else k=$=>` + ${$.registerUniform("output_size","u32").declareVariables(x,d)} + + ${pu(c,u,x,d)} + + ${$.mainStart()} + ${$.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${d.offsetToIndices("global_idx")}; + let aIndices = perm(indices); + + ${d.setByOffset("global_idx",x.getByIndices("aIndices"))} + }`;return{name:"Transpose",shaderCache:{hint:`${i}`,inputDependencies:["rank"]},getRunData:$=>{let H=ct.size(f);return{outputs:[{dims:f,dataType:$[0].dataType}],dispatchGroup:{x:Math.ceil(H/64)},programUniforms:[{type:12,data:H},...At($[0].dims,f)]}},getShaderSource:k}},fu=(n,i)=>{du(n.inputs),n.compute(hi(n.inputs[0],i.perm))},wa=n=>qt({perm:n.perm})}),hu,mu,gu,_u,ya,wu,yu,va,vu,bu,Xn,xu,Mu,ba,Tu,ku,xa,Su,Eu,Ma,Cu,rf=h(()=>{Zt(),Jt(),ar(),$a(),yo(),hu={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"},mu={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"},gu={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},_u={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},ya=(n,i)=>{let s=[];for(let u=i-n;u{let s=[],u=n.length;for(let f=0;fn[f]);return[s,c]},yu=(n,i)=>{let s=n.length+i.length,u=[],c=0;for(let f=0;f{for(let s=0;s{let s=[];if(!va(n,i)){for(let u=0;us.push(u))}return s},bu=(n,i,s,u,c,f,d)=>{let x=s[0].dims,k=ct.size(f),$=ct.size(d),H=_t("_A",s[0].dataType,x),q=Gt("output",c,f),v=32,oe=` + var aBestValues : array; + `;return{name:n,shaderCache:i,getShaderSource:te=>` + ${te.registerUniform("reduceSize","u32").declareVariables(H,q)} + ${oe} + fn DIV_CEIL(a : u32, b : u32) -> u32 { + return ((a - 1u) / b + 1u); + } + ${te.mainStart(v)} + + let outputIndex = global_idx / ${v}; + let offset = outputIndex * uniforms.reduceSize; + + var bestValue = f32(${gu[u]}); + let Length = uniforms.reduceSize; + for (var k = local_idx; k < Length; k = k + ${v}) { + let candidate = f32(${H.getByOffset("offset + k")}); + bestValue = ${hu[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 = ${mu[u]}; + aBestValues[local_idx] = bestValue; + } + reduceSize = interval; + workgroupBarrier(); + } + + if (local_idx == 0u) { + ${q.setByOffset("outputIndex",`${u==="mean"?`${q.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${q.type.storage}(${_u[u]})`}`)}; + } + }`,getRunData:()=>({outputs:[{dims:f,dataType:c}],dispatchGroup:{x:k},programUniforms:[{type:12,data:$}]})}},Xn=(n,i,s,u)=>{let c=n.inputs.length===1?s:Is(n.inputs,s),f=c.axes;f.length===0&&!c.noopWithEmptyAxes&&(f=n.inputs[0].dims.map((oe,te)=>te));let d=ct.normalizeAxes(f,n.inputs[0].dims.length),x=d,k=n.inputs[0],$=vu(x,n.inputs[0].dims.length);$.length>0&&(k=n.compute(hi(n.inputs[0],$),{inputs:[0],outputs:[-1]})[0],x=ya(x.length,k.dims.length));let[H,q]=wu(k.dims,x),v=H;c.keepDims&&(v=yu(H,d)),n.compute(bu(i,{hint:c.cacheKey,inputDependencies:["type"]},[k],u,n.inputs[0].dataType,v,q),{inputs:[k]})},xu=(n,i)=>{Xn(n,"ReduceMeanShared",i,"mean")},Mu=(n,i)=>{Xn(n,"ReduceL1Shared",i,"l1")},ba=(n,i)=>{Xn(n,"ReduceL2Shared",i,"l2")},Tu=(n,i)=>{Xn(n,"ReduceLogSumExpShared",i,"logSumExp")},ku=(n,i)=>{Xn(n,"ReduceMaxShared",i,"max")},xa=(n,i)=>{Xn(n,"ReduceMinShared",i,"min")},Su=(n,i)=>{Xn(n,"ReduceProdShared",i,"prod")},Eu=(n,i)=>{Xn(n,"ReduceSumShared",i,"sum")},Ma=(n,i)=>{Xn(n,"ReduceSumSquareShared",i,"sumSquare")},Cu=(n,i)=>{Xn(n,"ReduceLogSumShared",i,"logSum")}}),Qn,Pu,As,Is,ii,$u,Ta,Au,Iu,ka,Fu,Ou,Sa,zu,Du,Yn,Lu,Ru,Ea,Bu,Nu,Ca,ju,Uu,Pa,Vu,$a=h(()=>{Zt(),Jt(),_r(),ar(),rf(),Qn=n=>{if(!n||n.length===0||n.length>2)throw new Error("Reduce op requires 1 or 2 inputs.");if(n.length===2&&n[1].dims.length!==1)throw new Error("Invalid axes input dims.")},Pu=n=>["","",`var value = ${n.getByIndices("input_indices")};`,""],As=(n,i,s,u,c,f,d=!1,x=!1)=>{let k=[],$=s[0].dims,H=$.length,q=ct.normalizeAxes(c,H),v=!x&&q.length===0;$.forEach((de,we)=>{v||q.indexOf(we)>=0?d&&k.push(1):k.push(de)});let oe=k.length,te=ct.size(k);return{name:n,shaderCache:i,getShaderSource:de=>{let we=[],be=_t("_A",s[0].dataType,H),he=Gt("output",f,oe),De=u(be,he,q),Ae=De[2];for(let Ie=0,gt=0;Ie=0?(d&>++,Ae=`for(var j${Ie}: u32 = 0; j${Ie} < ${$[Ie]}; j${Ie}++) { + ${De[2].includes("last_index")?`let last_index = j${Ie};`:""} + ${be.indicesSet("input_indices",Ie,`j${Ie}`)} + ${Ae} + }`):(we.push(`${be.indicesSet("input_indices",Ie,he.indicesGet("output_indices",gt))};`),gt++);return` + + ${de.registerUniform("output_size","u32").declareVariables(be,he)} + + ${de.mainStart()} + ${de.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + var input_indices: ${be.type.indices}; + let output_indices = ${he.offsetToIndices("global_idx")}; + + ${we.join(` +`)} + ${De[0]} // init ops for reduce max/min + ${De[1]} + ${Ae} + ${De[3]} + ${De.length===4?he.setByOffset("global_idx","value"):De.slice(4).join(` +`)} + }`},getRunData:()=>({outputs:[{dims:k,dataType:f}],dispatchGroup:{x:Math.ceil(te/64)},programUniforms:[{type:12,data:te},...At($,k)]})}},Is=(n,i)=>{let s=[];return n[1].dims[0]>0&&n[1].getBigInt64Array().forEach(u=>s.push(Number(u))),qt({axes:s,keepDims:i.keepDims,noopWithEmptyAxes:i.noopWithEmptyAxes})},ii=(n,i,s,u)=>{let c=n.inputs,f=c.length===1?s:Is(c,s);n.compute(As(i,{hint:f.cacheKey,inputDependencies:["rank"]},[c[0]],f.noopWithEmptyAxes&&f.axes.length===0?Pu:u,f.axes,c[0].dataType,f.keepDims,f.noopWithEmptyAxes),{inputs:[0]})},$u=(n,i)=>{Qn(n.inputs),ii(n,"ReduceLogSum",i,(s,u)=>[`var value = ${u.type.storage}(0);`,"",`value += ${s.getByIndices("input_indices")};`,"value = log(value);"])},Ta=(n,i)=>{Qn(n.inputs),ii(n,"ReduceL1",i,(s,u)=>[`var value = ${u.type.storage}(0);`,"",`value += abs(${s.getByIndices("input_indices")});`,""])},Au=(n,i)=>{Qn(n.inputs),ii(n,"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);"])},Iu=(n,i)=>{Qn(n.inputs),ii(n,"ReduceLogSumExp",i,(s,u)=>[`var value = ${u.type.storage}(0);`,"",`value += exp(${s.getByIndices("input_indices")});`,"value = log(value);"])},ka=(n,i)=>{Qn(n.inputs),ii(n,"ReduceMax",i,(s,u,c)=>{let f=[];for(let d=0;d=0||c.length===0)&&f.push(s.indicesSet("input_indices",d,0));return[`${f.join(` +`)}`,`var value = ${s.getByIndices("input_indices")};`,`value = max(value, ${s.getByIndices("input_indices")});`,""]})},Fu=(n,i)=>{Qn(n.inputs),ii(n,"ReduceMean",i,(s,u,c)=>{let f=1;for(let d=0;d=0||c.length===0)&&(f*=n.inputs[0].dims[d]);return["var sum = f32(0);","",`sum += f32(${s.getByIndices("input_indices")});`,`let value = ${u.type.value}(sum / ${f});`]})},Ou=(n,i)=>{Qn(n.inputs),ii(n,"ReduceMin",i,(s,u,c)=>{let f=[];for(let d=0;d=0||c.length===0)&&f.push(`input_indices[${d}] = 0;`);return[`${f.join(` +`)}`,`var value = ${s.getByIndices("input_indices")};`,`value = min(value, ${s.getByIndices("input_indices")});`,""]})},Sa=(n,i)=>{Qn(n.inputs),ii(n,"ReduceProd",i,(s,u)=>[`var value = ${u.type.storage}(1);`,"",`value *= ${s.getByIndices("input_indices")};`,""])},zu=(n,i)=>{Qn(n.inputs),ii(n,"ReduceSum",i,(s,u)=>[`var value = ${u.type.storage}(0);`,"",`value += ${s.getByIndices("input_indices")};`,""])},Du=(n,i)=>{Qn(n.inputs),ii(n,"ReduceSumSquare",i,(s,u)=>[`var t = ${u.type.value}(0); var value = ${u.type.value}(0);`,"",`t = ${s.getByIndices("input_indices")}; value += t * t;`,""])},Yn=(n,i,s)=>{if(i.length===0)return s;let u=1,c=1;for(let f=0;f1024},Lu=(n,i)=>{Yn(n.inputs[0].dims,i.axes,i.noopWithEmptyAxes)?Fu(n,i):xu(n,i)},Ru=(n,i)=>{Yn(n.inputs[0].dims,i.axes,i.noopWithEmptyAxes)?Ta(n,i):Mu(n,i)},Ea=(n,i)=>{Yn(n.inputs[0].dims,i.axes,i.noopWithEmptyAxes)?Au(n,i):ba(n,i)},Bu=(n,i)=>{Yn(n.inputs[0].dims,i.axes,i.noopWithEmptyAxes)?Iu(n,i):Tu(n,i)},Nu=(n,i)=>{Yn(n.inputs[0].dims,i.axes,i.noopWithEmptyAxes)?ka(n,i):ku(n,i)},Ca=(n,i)=>{Yn(n.inputs[0].dims,i.axes,i.noopWithEmptyAxes)?Ou(n,i):xa(n,i)},ju=(n,i)=>{Yn(n.inputs[0].dims,i.axes,i.noopWithEmptyAxes)?Sa(n,i):Su(n,i)},Uu=(n,i)=>{Yn(n.inputs[0].dims,i.axes,i.noopWithEmptyAxes)?zu(n,i):Eu(n,i)},Pa=(n,i)=>{Yn(n.inputs[0].dims,i.axes,i.noopWithEmptyAxes)?Du(n,i):Ma(n,i)},Vu=(n,i)=>{Yn(n.inputs[0].dims,i.axes,i.noopWithEmptyAxes)?$u(n,i):Cu(n,i)}}),Fs,Wu,Gu,Os,nf=h(()=>{Zt(),_r(),$a(),Fs=n=>{if(!n||n.length===0||n.length>2)throw new Error("ArgMinMaxOp op requires 1 or 2 inputs.");if(n[0].dataType!==1)throw new Error("Invalid input type.")},Wu=(n,i)=>{Fs(n.inputs);let s=(u,c,f)=>{let d=[];for(let x=0;x=0||f.length===0)&&d.push(`input_indices[${x}] = 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")]};n.compute(As("ArgMin",{hint:i.cacheKey,inputDependencies:["rank"]},[n.inputs[0]],s,[i.axis],7,i.keepDims),{inputs:[0]})},Gu=(n,i)=>{Fs(n.inputs);let s=(u,c,f)=>{let d=[];for(let x=0;x=0||f.length===0)&&d.push(`input_indices[${x}] = 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")]};n.compute(As("argMax",{hint:i.cacheKey,inputDependencies:["rank"]},[n.inputs[0]],s,[i.axis],7,i.keepDims),{inputs:[0]})},Os=n=>qt(n)}),Hu,Aa,qu,Ku,vo,Xu,Qu,zs=h(()=>{Zt(),pe(),ar(),Hu=(n,i)=>{let s=n[0],u=n[1],c=n[2],f=n[3],d=n[4],x=n[5];if(d&&x)throw new Error("Attention cannot have both past and relative_position_bias");if(s.dims.length!==3)throw new Error('Input "input" must have 3 dimensions');let k=s.dims[0],$=s.dims[1],H=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]!==H)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 q=c.dims[0]/3,v=q,oe=v;if(i.qkvHiddenSizes.length>0){if(i.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let De of i.qkvHiddenSizes)if(De%i.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");q=i.qkvHiddenSizes[0],v=i.qkvHiddenSizes[1],oe=i.qkvHiddenSizes[2]}let te=$;if(q!==v)throw new Error("qkv_hidden_sizes first element should be same as the second");if(c.dims[0]!==q+v+oe)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let de=0;if(d){if(v!==oe)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]!==k)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||(de=d.dims[3])}let we=te+de,be=-1,he=0;if(f)throw new Error("Mask not supported");if(d)throw new Error("past is not supported");return{batchSize:k,sequenceLength:$,pastSequenceLength:de,kvSequenceLength:te,totalSequenceLength:we,maxSequenceLength:be,inputHiddenSize:H,hiddenSize:q,vHiddenSize:oe,headSize:Math.floor(q/i.numHeads),vHeadSize:Math.floor(oe/i.numHeads),numHeads:i.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:i.maskFilterValue,maskType:he,scale:i.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},Aa=(n,i,s,u)=>{let c=vr(u),f=64,d=u/c;d{let oe=Gt("x",i.dataType,i.dims,c),te=[{name:"d_inv",type:Er(i.dataType)},{name:"d_comp",type:"u32"},{name:"elements_per_thread",type:"u32"}];return` + var thread_max: array; + var thread_sum: array; + ${v.registerUniforms(te).declareVariables(oe)} + ${v.mainStart([f,1,1])} + let local_offset = local_idx * uniforms.elements_per_thread; + let offset = workgroup_id.x * uniforms.d_comp + local_offset; + + var thread_max_vector = ${H}(-3.402823e+38f); + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { + thread_max_vector = max(${H}(x[offset + i]), thread_max_vector); + } + thread_max[local_idx] = ${(()=>{switch(c){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: ${c}`)}})()}; + workgroupBarrier(); + + var max_value = f32(-3.402823e+38f); + for (var i = 0u; i < ${f}; i++) { + max_value = max(thread_max[i], max_value); + } + + var sum_vector = ${H}(0); + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { + sum_vector += exp(${H}(x[offset + i]) - max_value); + } + thread_sum[local_idx] = ${(()=>{switch(c){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: ${c}`)}})()}; + workgroupBarrier(); + + var sum: f32 = 0; + for (var i = 0u; i < ${f}; 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] = ${oe.type.value}(uniforms.d_inv); + } + } else { + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < uniforms.d_comp; i++) { + var f32input = ${H}(x[offset + i]); + x[offset + i] = ${oe.type.value}(exp(f32input - max_value) / sum); + } + } + }`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${f};${$};${c}`},getShaderSource:q,getRunData:()=>({outputs:[],dispatchGroup:{x:s},programUniforms:k})}},qu=(n,i,s,u,c,f,d,x)=>{let k=x+f.kvSequenceLength,$=[f.batchSize,f.numHeads,f.sequenceLength,k],H=f.kvNumHeads===void 0&&n.outputCount>1,q=H?[f.batchSize,f.numHeads,k,f.headSize]:void 0,v=d.scale===0?1/Math.sqrt(f.headSize):d.scale,oe=vr(f.headSize),te=f.headSize/oe,de=12,we={x:Math.ceil(k/de),y:Math.ceil(f.sequenceLength/de),z:f.batchSize*f.numHeads},be=[{type:12,data:f.sequenceLength},{type:12,data:te},{type:12,data:k},{type:12,data:f.numHeads},{type:1,data:v},{type:12,data:x},{type:12,data:f.kvSequenceLength}],he=["type","type"];u&&he.push("type"),c&&he.push("type");let De=[{dims:$,dataType:i.dataType,gpuDataType:0}];H&&De.push({dims:q,dataType:i.dataType,gpuDataType:0});let Ae=Ie=>{let gt=_t("q",i.dataType,i.dims,oe),ut=_t("key",s.dataType,s.dims,oe),vt=[gt,ut];if(u){let ir=_t("past_key",u.dataType,u.dims,oe);vt.push(ir)}c&&vt.push(_t("relative_position_bias",c.dataType,c.dims));let Dt=Gt("output",i.dataType,$),Rt=[Dt];H&&Rt.push(Gt("present_key",i.dataType,q,oe));let gr=Er(1,oe),Mr=[{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 = ${de}u; + + var tileQ: array<${gt.type.storage}, ${de*de}>; + var tileK: array<${gt.type.storage}, ${de*de}>; + ${Ie.registerUniforms(Mr).declareVariables(...vt,...Rt)} + ${Ie.mainStart([de,de,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; + ${u&&H?` + 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;`} + ${H?"let presentKeyOffset = headIdx * uniforms.N * uniforms.K;":""} + var value = ${gr}(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; + ${u&&H?` + 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];"} + ${H?"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 += ${gr}(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(oe){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: ${oe}`)}})()}; + output[outputIdx] = ${Dt.type.value} (sum * uniforms.alpha) + ${c?"relative_position_bias[outputIdx]":"0.0"}; + } + }`};return{name:"AttentionProbs",shaderCache:{hint:`${oe};${c!==void 0};${u!==void 0};${n.outputCount}`,inputDependencies:he},getRunData:()=>({outputs:De,dispatchGroup:we,programUniforms:be}),getShaderSource:Ae}},Ku=(n,i,s,u,c,f)=>{let d=f+c.kvSequenceLength,x=c.nReps?c.nReps:1,k=c.vHiddenSize*x,$=c.kvNumHeads==null&&n.outputCount>1,H=$?[c.batchSize,c.numHeads,d,c.headSize]:void 0,q=[c.batchSize,c.sequenceLength,k],v=12,oe={x:Math.ceil(c.vHeadSize/v),y:Math.ceil(c.sequenceLength/v),z:c.batchSize*c.numHeads},te=[{type:12,data:c.sequenceLength},{type:12,data:d},{type:12,data:c.vHeadSize},{type:12,data:c.numHeads},{type:12,data:k},{type:12,data:f},{type:12,data:c.kvSequenceLength}],de=u?["type","type","type"]:["type","type"],we=[{dims:q,dataType:i.dataType,gpuDataType:0}];$&&we.push({dims:H,dataType:i.dataType,gpuDataType:0});let be=he=>{let De=_t("probs",i.dataType,i.dims),Ae=_t("v",s.dataType,s.dims),Ie=[De,Ae];u&&Ie.push(_t("past_value",u.dataType,u.dims));let gt=[Gt("output",i.dataType,q)];$&>.push(Gt("present_value",i.dataType,H));let ut=[{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<${De.type.value}, ${v*v}>; + var tileK: array<${De.type.value}, ${v*v}>; + ${he.registerUniforms(ut).declareVariables(...Ie,...gt)} + ${he.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; + ${u&&$?` + 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; + `} + ${$?"let presentValueOffset = headIdx * uniforms.N * uniforms.K + n;":""} + var value = ${De.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; + ${u&&$?` + 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]; + `} + ${$?"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};${n.outputCount}`,inputDependencies:de},getRunData:()=>({outputs:we,dispatchGroup:oe,programUniforms:te}),getShaderSource:be}},vo=(n,i,s,u,c,f,d,x,k,$,H)=>{let q=n.outputCount,v=$.kvNumHeads!==void 0||q>1?$.pastSequenceLength:0,oe=v+$.kvSequenceLength,te=$.kvNumHeads===void 0&&q>1&&d?[i,s,d]:[i,s];k&&te.push(k);let de=n.compute(qu(n,i,s,q>1?d:void 0,k,$,H,v),{inputs:te,outputs:$.kvNumHeads===void 0&&q>1?[-1,1]:[-1]})[0];n.compute(Aa(n,de,$.batchSize*$.numHeads*$.sequenceLength,oe),{inputs:[de],outputs:[]});let we=$.kvNumHeads===void 0&&q>1&&x?[de,u,x]:[de,u];n.compute(Ku(n,de,u,q>1&&x?x:void 0,$,v),{inputs:we,outputs:$.kvNumHeads===void 0&&q>1?[0,2]:[0]})},Xu=(n,i)=>{let s=[i.batchSize,i.numHeads,i.sequenceLength,i.headSize],u=i.sequenceLength,c=i.inputHiddenSize,f=i.headSize,d=12,x={x:Math.ceil(i.headSize/d),y:Math.ceil(i.sequenceLength/d),z:i.batchSize*i.numHeads},k=[n.inputs[0],n.inputs[1],n.inputs[2]],$=[{type:12,data:u},{type:12,data:c},{type:12,data:f},{type:12,data:i.numHeads},{type:12,data:i.headSize},{type:12,data:i.hiddenSize},{type:12,data:i.hiddenSize+i.hiddenSize+i.vHiddenSize}],H=q=>{let v=Gt("output_q",k[0].dataType,s),oe=Gt("output_k",k[0].dataType,s),te=Gt("output_v",k[0].dataType,s),de=_t("input",k[0].dataType,k[0].dims),we=_t("weight",k[1].dataType,k[1].dims),be=_t("bias",k[2].dataType,k[2].dims),he=de.type.storage,De=[{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}>; + ${q.registerUniforms(De).declareVariables(de,we,be,v,oe,te)} + ${q.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:n.inputs[0].dataType,gpuDataType:0},{dims:s,dataType:n.inputs[0].dataType,gpuDataType:0},{dims:s,dataType:n.inputs[0].dataType,gpuDataType:0}],dispatchGroup:x,programUniforms:$}),getShaderSource:H},{inputs:k,outputs:[-1,-1,-1]})},Qu=(n,i)=>{let s=Hu(n.inputs,i),[u,c,f]=Xu(n,s);return vo(n,u,c,f,n.inputs[4],void 0,void 0,void 0,n.inputs[5],s,i)}}),Yu,Zu,Ju,ec,tc=h(()=>{Z(),Zt(),Jt(),_r(),ar(),Yu=(n,i)=>{if(!n||n.length!==5)throw new Error("BatchNormalization requires 5 inputs");let s=(u,c,f)=>{let d=c.length;if(d!==u.length)throw new Error(`${f}: num dimensions != ${d}`);c.forEach((x,k)=>{if(x!==u[k])throw new Error(`${f}: dim[${k}] do not match`)})};if(n[0].dims.length>1){let u=i.format==="NHWC"?i.spatial?n[0].dims.slice(-1):n[0].dims.slice(-1).concat(n[0].dims.slice(1,n[0].dims.length-1)):n[0].dims.slice(1,i.spatial?2:void 0);s(n[1].dims,u,"Invalid input scale"),s(n[2].dims,u,"Invalid input B"),s(n[3].dims,u,"Invalid input mean"),s(n[4].dims,u,"Invalid input var")}else s(n[1].dims,[1],"Invalid input scale"),s(n[2].dims,[1],"Invalid input B"),s(n[3].dims,[1],"Invalid input mean"),s(n[4].dims,[1],"Invalid input var")},Zu=(n,i)=>{let{epsilon:s,spatial:u,format:c}=i,f=n[0].dims,d=u?vr(f[f.length-1]):1,x=c==="NHWC"&&f.length>1?d:1,k=ct.size(f)/d,$=u,H=$?f.length:f,q=_t("x",n[0].dataType,n[0].dims,d),v=_t("scale",n[1].dataType,n[1].dims,x),oe=_t("bias",n[2].dataType,n[2].dims,x),te=_t("inputMean",n[3].dataType,n[3].dims,x),de=_t("inputVar",n[4].dataType,n[4].dims,x),we=Gt("y",n[0].dataType,H,d),be=()=>{let De="";if(u)De=`let cOffset = ${f.length===1?"0u":c==="NHWC"?`outputIndices[${f.length-1}] / ${d}`:"outputIndices[1]"};`;else if(c==="NCHW")De=` + ${we.indicesSet("outputIndices","0","0")} + let cOffset = ${we.indicesToOffset("outputIndices")};`;else{De=`var cIndices = ${v.type.indices}(0); + cIndices[0] = outputIndices[${f.length-1}];`;for(let Ae=1;Ae` + const epsilon = ${s}; + ${De.registerUniform("outputSize","u32").declareVariables(q,v,oe,te,de,we)} + ${De.mainStart()} + ${De.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var outputIndices = ${we.offsetToIndices(`global_idx * ${d}`)}; + ${be()} + let scale = ${v.getByOffset("cOffset")}; + let bias = ${oe.getByOffset("cOffset")}; + let inputMean = ${te.getByOffset("cOffset")}; + let inputVar = ${de.getByOffset("cOffset")}; + let x = ${q.getByOffset("global_idx")}; + let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias; + ${we.setByOffset("global_idx","value")} + }`;return{name:"BatchNormalization",shaderCache:{hint:`${i.epsilon}_${i.format}_${u}_${d}`,inputDependencies:$?["rank","type","type","type","type"]:void 0},getShaderSource:he,getRunData:()=>({outputs:[{dims:n[0].dims,dataType:n[0].dataType}],dispatchGroup:{x:Math.ceil(k/64)},programUniforms:$?[{type:12,data:k},...At(f)]:[{type:12,data:k}]})}},Ju=n=>qt(n),ec=(n,i)=>{let{inputs:s,outputCount:u}=n,c=Ju({...i,outputCount:u});if(N.webgpu.validateInputContent&&Yu(s,c),i.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");n.compute(Zu(s,c))}}),rc,nc,Ia,of=h(()=>{Jt(),ar(),rc=n=>{if(n[0].dims.length!==3)throw new Error("input should have 3 dimensions");if(![320,640,1280].includes(n[0].dims[2]))throw new Error("number of channels should be 320, 640 or 1280");if(n[1].dims.length!==1)throw new Error("bias is expected to have 1 dimensions");if(n[0].dims[2]!==n[1].dims[0])throw new Error("last dimension of input and bias are not the same")},nc=n=>{let i=n[0].dims,s=n[0].dims[2],u=ct.size(i)/4,c=n[0].dataType,f=_t("input",c,i,4),d=_t("bias",c,[s],4),x=_t("residual",c,i,4),k=Gt("output",c,i,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:i,dataType:n[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)}}),getShaderSource:$=>` + const channels = ${s}u / 4; + ${$.declareVariables(f,d,x,k)} + + ${$.mainStart()} + ${$.guardAgainstOutOfBoundsWorkgroupSizes(u)} + let value = ${f.getByOffset("global_idx")} + + ${d.getByOffset("global_idx % channels")} + ${x.getByOffset("global_idx")}; + ${k.setByOffset("global_idx","value")} + }`}},Ia=n=>{rc(n.inputs),n.compute(nc(n.inputs))}}),ic,br,oc,sc,Fa,ac,lc,Oa,uc,cc,Ds,dc,pc,fc,za,hc,bo,mc,Ls,gc,Da,_c,wc,yc,La,vc,bc,Ra,xc,Mc,Ba,Tc,kc,Na,Sc,ja,Ua,Va,Wa,Ec,Cc,Ga,Pc,$c,Ac,Ha=h(()=>{Zt(),Jt(),_r(),ar(),ic=(n,i,s,u,c,f)=>{let d=Math.ceil(i/4),x="";typeof c=="string"?x=`${c}(a)`:x=c("a");let k=_t("inputData",s,[d],4),$=Gt("outputData",u,[d],4);return` + ${n.registerUniform("vec_size","u32").declareVariables(k,$)} + + ${f??""} + + ${n.mainStart()} + ${n.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + + let a = ${k.getByOffset("global_idx")}; + ${$.setByOffset("global_idx",x)} + }`},br=(n,i,s,u,c,f=n.dataType)=>({name:i,shaderCache:{hint:c,inputDependencies:["type"]},getShaderSource:d=>ic(d,ct.size(n.dims),n.dataType,f,s,u),getRunData:d=>({outputs:[{dims:n.dims,dataType:f}],dispatchGroup:{x:Math.ceil(ct.size(d[0].dims)/64/4)},programUniforms:[{type:12,data:Math.ceil(ct.size(n.dims)/4)}]})}),oc=n=>{n.compute(br(n.inputs[0],"Abs","abs"))},sc=n=>{n.compute(br(n.inputs[0],"Acos","acos"))},Fa=n=>{n.compute(br(n.inputs[0],"Acosh","acosh"))},ac=n=>{n.compute(br(n.inputs[0],"Asin","asin"))},lc=n=>{n.compute(br(n.inputs[0],"Asinh","asinh"))},Oa=n=>{n.compute(br(n.inputs[0],"Atan","atan"))},uc=n=>{n.compute(br(n.inputs[0],"Atanh","atanh"))},cc=n=>qt(n),Ds=(n,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}`)}n.compute(br(n.inputs[0],"Cast",s,void 0,i.cacheKey,i.to))},dc=n=>{let i=n.length>=2&&n[1].data!==0?n[1].getFloat32Array()[0]:cn,s=n.length>=3&&n[2].data!==0?n[2].getFloat32Array()[0]:On;return qt({min:i,max:s})},pc=(n,i)=>{let s=n.inputs.length===1?i:dc(n.inputs),u=Er(n.inputs[0].dataType);n.compute(br(n.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]})},fc=n=>{n.compute(br(n.inputs[0],"Ceil","ceil"))},za=n=>{n.compute(br(n.inputs[0],"Cos","cos"))},hc=n=>{n.compute(br(n.inputs[0],"Cosh","cosh"))},bo=n=>qt(n),mc=(n,i)=>{let s=Er(n.inputs[0].dataType);n.compute(br(n.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))},Ls=(n="f32")=>` +const r0: ${n} = 0.3275911; +const r1: ${n} = 0.254829592; +const r2: ${n} = -0.284496736; +const r3: ${n} = 1.421413741; +const r4: ${n} = -1.453152027; +const r5: ${n} = 1.061405429; + +fn erf_vf32(v: vec4<${n}>) -> vec4<${n}> { + 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)); +}`,gc=n=>{let i=Er(n.inputs[0].dataType);n.compute(br(n.inputs[0],"Erf",s=>`erf_vf32(${s})`,Ls(i)))},Da=n=>{n.compute(br(n.inputs[0],"Exp","exp"))},_c=n=>{n.compute(br(n.inputs[0],"Floor","floor"))},wc=n=>{let i=Er(n.inputs[0].dataType);n.compute(br(n.inputs[0],"Gelu",s=>`0.5 * ${s} * (1.0 + erf_vf32(${s} * 0.7071067811865475))`,Ls(i)))},yc=(n,i)=>{let s=Er(n.inputs[0].dataType);n.compute(br(n.inputs[0],"LeakyRelu",u=>`select(leaky_relu_alpha_ * ${u}, ${u}, ${u} >= vec4<${s}>(0.0))`,`const leaky_relu_alpha_ = ${s}(${i.alpha});`,i.cacheKey))},La=n=>{n.compute(br(n.inputs[0],"Not",i=>`!${i}`))},vc=n=>{n.compute(br(n.inputs[0],"Neg",i=>`-${i}`))},bc=n=>{n.compute(br(n.inputs[0],"Reciprocal",i=>`1.0/${i}`))},Ra=n=>{let i=Er(n.inputs[0].dataType);n.compute(br(n.inputs[0],"Relu",s=>`select(vec4<${i}>(0.0), ${s}, ${s} > vec4<${i}>(0.0))`))},xc=n=>{n.compute(br(n.inputs[0],"Sigmoid",i=>`(1.0 / (1.0 + exp(-${i})))`))},Mc=n=>qt(n),Ba=(n,i)=>{let s=Er(n.inputs[0].dataType);n.compute(br(n.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))},Tc=n=>{n.compute(br(n.inputs[0],"Sin","sin"))},kc=n=>{n.compute(br(n.inputs[0],"Sinh","sinh"))},Na=n=>{n.compute(br(n.inputs[0],"Sqrt","sqrt"))},Sc=n=>{n.compute(br(n.inputs[0],"Tan","tan"))},ja=n=>`sign(${n}) * (1 - exp(-2 * abs(${n}))) / (1 + exp(-2 * abs(${n})))`,Ua=n=>{n.compute(br(n.inputs[0],"Tanh",ja))},Va=(n="f32")=>` +const fast_gelu_a: ${n} = 0.5; +const fast_gelu_b: ${n} = 0.7978845608028654; +const fast_gelu_c: ${n} = 0.035677408136300125; + +fn tanh_v(v: vec4<${n}>) -> vec4<${n}> { + return ${ja("v")}; +} +`,Wa=n=>`(fast_gelu_a + fast_gelu_a * tanh_v(${n} * (fast_gelu_c * ${n} * ${n} + fast_gelu_b))) * ${n}`,Ec=n=>{let i=Er(n.inputs[0].dataType);n.compute(br(n.inputs[0],"FastGelu",Wa,Va(i),void 0,n.inputs[0].dataType))},Cc=(n,i)=>{let s=Er(n.inputs[0].dataType);return n.compute(br(n.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},Ga=n=>{n.compute(br(n.inputs[0],"Log","log"))},Pc=(n,i)=>` +const alpha = vec4<${n}>(${i}); +const one = ${n}(1.0); +const zero = ${n}(0.0); + +fn quick_gelu_impl(x: vec4<${n}>) -> vec4<${n}> { + let v = x *alpha; + var x1 : vec4<${n}>; + 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; +} +`,$c=n=>`quick_gelu_impl(${n})`,Ac=(n,i)=>{let s=Er(n.inputs[0].dataType);n.compute(br(n.inputs[0],"QuickGelu",$c,Pc(s,i.alpha),i.cacheKey,n.inputs[0].dataType))}}),qa,Ic,Fc,Oc=h(()=>{Jt(),ar(),Ha(),qa=n=>{if(n[0].dims.length!==3)throw new Error("input should have 3 dimensions");if(![2560,5120,10240].includes(n[0].dims[2]))throw new Error("hidden state should be 2560, 5120 or 10240");if(n[1].dims.length!==1)throw new Error("bias is expected to have 1 dimensions");if(n[0].dims[2]!==n[1].dims[0])throw new Error("last dimension of input and bias are not the same")},Ic=n=>{let i=n[0].dims.slice();i[2]=i[2]/2;let s=_t("input",n[0].dataType,n[0].dims,4),u=_t("bias",n[0].dataType,[n[0].dims[2]],4),c=Gt("output",n[0].dataType,i,4),f=ct.size(i)/4,d=Sr(n[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:i,dataType:n[0].dataType}],dispatchGroup:{x:Math.ceil(f/64)}}),getShaderSource:x=>` + const M_SQRT2 = sqrt(2.0); + const halfChannels = ${n[0].dims[2]/4/2}u; + + ${x.declareVariables(s,u,c)} + + ${Ls(d)} + + ${x.mainStart()} + ${x.guardAgainstOutOfBoundsWorkgroupSizes(f)} + 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")} + }`}},Fc=n=>{qa(n.inputs),n.compute(Ic(n.inputs))}}),zc,Dc,Zn,Lc,Rc,Ka,Bc,Nc,jc,Uc,Vc,Wc,Xa,sf=h(()=>{Zt(),Jt(),ar(),zc=(n,i,s,u,c,f,d,x,k,$,H,q)=>{let v,oe;typeof x=="string"?v=oe=(he,De)=>`${x}((${he}),(${De}))`:typeof x=="function"?v=oe=x:(v=x.scalar,oe=x.vector);let te=Gt("outputData",H,u.length,4),de=_t("aData",k,i.length,4),we=_t("bData",$,s.length,4),be;if(c)if(f){let he=ct.size(i)===1,De=ct.size(s)===1,Ae=i.length>0&&i[i.length-1]%4===0,Ie=s.length>0&&s[s.length-1]%4===0;he||De?be=te.setByOffset("global_idx",oe(he?`${de.type.value}(${de.getByOffset("0")}.x)`:de.getByOffset("global_idx"),De?`${we.type.value}(${we.getByOffset("0")}.x)`:we.getByOffset("global_idx"))):be=` + let outputIndices = ${te.offsetToIndices("global_idx * 4u")}; + let offsetA = ${de.broadcastedIndicesToOffset("outputIndices",te)}; + let offsetB = ${we.broadcastedIndicesToOffset("outputIndices",te)}; + ${te.setByOffset("global_idx",oe(d||Ae?de.getByOffset("offsetA / 4u"):`${de.type.value}(${de.getByOffset("offsetA / 4u")}[offsetA % 4u])`,d||Ie?we.getByOffset("offsetB / 4u"):`${we.type.value}(${we.getByOffset("offsetB / 4u")}[offsetB % 4u])`))} + `}else be=te.setByOffset("global_idx",oe(de.getByOffset("global_idx"),we.getByOffset("global_idx")));else{if(!f)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let he=(De,Ae,Ie="")=>{let gt=`aData[indexA${Ae}][componentA${Ae}]`,ut=`bData[indexB${Ae}][componentB${Ae}]`;return` + let outputIndices${Ae} = ${te.offsetToIndices(`global_idx * 4u + ${Ae}u`)}; + let offsetA${Ae} = ${de.broadcastedIndicesToOffset(`outputIndices${Ae}`,te)}; + let offsetB${Ae} = ${we.broadcastedIndicesToOffset(`outputIndices${Ae}`,te)}; + let indexA${Ae} = offsetA${Ae} / 4u; + let indexB${Ae} = offsetB${Ae} / 4u; + let componentA${Ae} = offsetA${Ae} % 4u; + let componentB${Ae} = offsetB${Ae} % 4u; + ${De}[${Ae}] = ${Ie}(${v(gt,ut)}); + `};H===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` + ${n.registerUniform("vec_size","u32").declareVariables(de,we,te)} + + ${q??""} + + ${n.mainStart()} + ${n.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${be} + }`},Dc=(n,i,s,u,c,f,d=s.dataType)=>{let x=!ct.areEqual(s.dims,u.dims),k=s.dims,$=ct.size(s.dims),H=!1,q=!1,v=[x];if(x){let oe=gn.calcShape(s.dims,u.dims,!1);if(!oe)throw new Error("Can't perform binary op on the given tensors");k=oe,$=ct.size(k);let te=ct.size(s.dims)===1,de=ct.size(u.dims)===1,we=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(te),v.push(de),v.push(we),v.push(be);let he=1;for(let De=1;Deoe.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:oe=>zc(oe,s.dims,u.dims,k,H,x,q,c,s.dataType,u.dataType,d,f),getRunData:()=>({outputs:[{dims:k,dataType:d}],dispatchGroup:{x:Math.ceil($/64/4)},programUniforms:[{type:12,data:Math.ceil(ct.size(k)/4)},...At(s.dims,u.dims,k)]})}},Zn=(n,i,s,u,c,f)=>{n.compute(Dc(i,c??"",n.inputs[0],n.inputs[1],s,u,f))},Lc=n=>{Zn(n,"Add",(i,s)=>`${i}+${s}`)},Rc=n=>{Zn(n,"Div",(i,s)=>`${i}/${s}`)},Ka=n=>{Zn(n,"Equal",{scalar:(i,s)=>`u32(${i}==${s})`,vector:(i,s)=>`vec4(${i}==${s})`},void 0,void 0,9)},Bc=n=>{Zn(n,"Mul",(i,s)=>`${i}*${s}`)},Nc=n=>{let i=_t("input",n.inputs[0].dataType,n.inputs[0].dims).type.value;Zn(n,"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)); + } + `)},jc=n=>{Zn(n,"Sub",(i,s)=>`${i}-${s}`)},Uc=n=>{Zn(n,"Greater",{scalar:(i,s)=>`u32(${i}>${s})`,vector:(i,s)=>`vec4(${i}>${s})`},void 0,void 0,9)},Vc=n=>{Zn(n,"Less",{scalar:(i,s)=>`u32(${i}<${s})`,vector:(i,s)=>`vec4(${i}<${s})`},void 0,void 0,9)},Wc=n=>{Zn(n,"GreaterOrEqual",{scalar:(i,s)=>`u32(${i}>=${s})`,vector:(i,s)=>`vec4(${i}>=${s})`},void 0,void 0,9)},Xa=n=>{Zn(n,"LessOrEqual",{scalar:(i,s)=>`u32(${i}<=${s})`,vector:(i,s)=>`vec4(${i}<=${s})`},void 0,void 0,9)}}),Gc,Qa,Hc,qc,Ui,Kc,af=h(()=>{Zt(),Jt(),_r(),ar(),Gc=(n,i)=>{if(!n||n.length<1)throw new Error("too few inputs");let s=0,u=n[s],c=u.dataType,f=u.dims.length;n.forEach((d,x)=>{if(x!==s){if(d.dataType!==c)throw new Error("input tensors should be one type");if(d.dims.length!==f)throw new Error("input tensors should have the same shape");d.dims.forEach((k,$)=>{if($!==i&&k!==u.dims[$])throw new Error("non concat dimensions must match")})}})},Qa=(n,i)=>` + fn calculateInputIndex(index: u32) -> u32 { + let sizeInConcatAxis = array(${i}); + for (var i: u32 = 0u; i < ${n}; i += 1u ) { + if (index < sizeInConcatAxis[i]) { + return i; + } + } + return ${n}u; + }`,Hc=(n,i)=>{let s=n.length,u=[];for(let c=0;c{let c=ct.size(s),f=new Array(n.length),d=new Array(n.length),x=0,k=[],$=[],H=[{type:12,data:c}];for(let de=0;de`uniforms.sizeInConcatAxis${de}`).join(","),te=de=>` + + ${(()=>{de.registerUniform("outputSize","u32");for(let we=0;we(${oe}); + ${v} -= sizeInConcatAxis[inputIndex - 1u]; + } + + ${Hc(d,q)} + }`;return{name:"Concat",shaderCache:{hint:`${i}`,inputDependencies:k},getRunData:()=>({outputs:[{dims:s,dataType:u}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:H}),getShaderSource:te}},Ui=(n,i)=>{let s=n.inputs,u=s[0].dims,c=ct.normalizeAxis(i.axis,u.length);Gc(s,c);let f=u.slice();f[c]=s.reduce((x,k)=>x+(k.dims.length>c?k.dims[c]:0),0);let d=s.filter(x=>ct.size(x.dims)>0);n.compute(qc(d,c,f,s[0].dataType),{inputs:d})},Kc=n=>qt({axis:n.axis})}),Vi,Wi,Ei,Ya,Gi=h(()=>{Zt(),Jt(),Vi=(n,i,s="f32")=>{switch(n.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 ${n.activation}`)}},Wi=(n,i)=>{n.activation==="Clip"?i.push({type:1,data:n.clipMax},{type:1,data:n.clipMin}):n.activation==="HardSigmoid"?i.push({type:1,data:n.alpha},{type:1,data:n.beta}):n.activation==="LeakyRelu"&&i.push({type:1,data:n.alpha})},Ei=(n,i)=>{n.activation==="Clip"?i.push({name:"clip_max",type:"f32"},{name:"clip_min",type:"f32"}):n.activation==="HardSigmoid"?i.push({name:"alpha",type:"f32"},{name:"beta",type:"f32"}):n.activation==="LeakyRelu"&&i.push({name:"alpha",type:"f32"})},Ya=n=>{let i=(n==null?void 0:n.activation)||"";if(i==="HardSigmoid"){let[s,u]=(n==null?void 0:n.activation_params)||[.2,.5];return{activation:i,alpha:s,beta:u}}else if(i==="Clip"){let[s,u]=(n==null?void 0:n.activation_params)||[cn,On];return{activation:i,clipMax:u,clipMin:s}}else if(i==="LeakyRelu"){let[s]=(n==null?void 0:n.activation_params)||[.01];return{activation:i,alpha:s}}return{activation:i}}}),vn,Za,xo=h(()=>{vn=(n,i)=>{switch(n){case 1:return i;case 2:return`vec2<${i}>`;case 3:return`vec3<${i}>`;case 4:return`vec4<${i}>`;default:throw new Error(`${n}-component is not supported.`)}},Za=n=>` + ${n?"value = value + getBiasByOutputCoords(coords);":""} + `}),Ja,Xc=h(()=>{Ja=n=>` +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(${n}.x), i32(${n}.y), i32(${n}.z), 1)); +} +`}),Qc,qo,Rs,el,Yc,Bs,Ns,tl,js=h(()=>{Zt(),Jt(),ar(),Gi(),xo(),Qc=(n,i)=>n?` + 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":""}); + `,qo=(n,i)=>n?` + 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];"} + }`,Rs=(n,i,s="f32",u,c=!1,f=32,d=!1,x=32)=>{let k=i[1]*n[1],$=i[0]*n[0],H=c?k:f,q=c?f:k,v=H/i[0],oe=f/i[1];if(!((c&&v===4&&n[1]===4||!c&&(v===3||v===4))&&H%i[0]===0&&f%i[1]===0&&n[0]===4))throw new Error(`If transposeA ${c} is true, innerElementSize ${v} and workPerThread[1] ${n[1]} must be 4. + Otherwise, innerElementSize ${v} must be 3 or 4. + tileAWidth ${H} must be divisible by workgroupSize[0]${i[0]}. tileInner ${f} must be divisible by workgroupSize[1] ${i[1]}. colPerThread ${n[0]} must be 4.`);return` +var mm_Asub: array, ${H/v}>, ${q}>; +var mm_Bsub: array, ${$/n[0]}>, ${f}>; + +const rowPerThread = ${n[1]}; +const colPerThread = ${n[0]}; +const innerElementSize = ${v}; +const tileInner = ${f}; + +@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) * ${k}; + + let num_tiles = ${d?`${Math.ceil(x/f)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; + var kStart = ${d?`i32(globalId.z) * ${x}`:"0"}; + + var acc: array, rowPerThread>; + + // Loop over shared dimension. + let tileRowB = localRow * ${oe}; + 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 < ${oe}; 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];"} + + ${qo(c,v)} + } + + workgroupBarrier(); + } + + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]); + } +}`},el=(n,i)=>n?` + 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":""}); + `,Yc=n=>n?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",Bs=(n,i,s="f32",u,c=!1,f=32,d=!1,x=32,k=!1)=>{let $=n[1]*i[1],H=n[0]*i[0],q=c?$:f,v=c?f:$;if(!(v%i[1]===0&&q%i[0]===0&&f%i[1]===0))throw new Error(`tileAHight ${v} must be divisible by workgroupSize[1]${i[1]}, tileAWidth ${q} must be divisible by workgroupSize[0]${i[0]}, tileInner ${f} must be divisible by workgroupSize[1]${i[1]}`);let oe=v/i[1],te=q/i[0],de=f/i[1],we=k?` + let localRow = i32(localId.y); + let localCol = i32(localId.x); + let globalRowStart = i32(workgroupId.y) * ${$}; + let globalColStart = i32(workgroupId.x) * ${H}; + + // 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 < ${q}; inputCol = inputCol + ${i[0]}) { + ${el(c,u)} + } + } + // Load one tile of B into local memory. + for (var inputRow = localRow; inputRow < ${f}; inputRow = inputRow + ${i[1]}) { + for (var inputCol = localCol; inputCol < ${H}; 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) * ${$}; + +let tileRowA = i32(localId.y) * ${oe}; +let tileColA = i32(localId.x) * ${te}; +let tileRowB = i32(localId.y) * ${de}; +// 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 < ${oe}; innerRow = innerRow + 1) { + for (var innerCol = 0; innerCol < ${te}; innerCol = innerCol + 1) { + let inputRow = tileRowA + innerRow; + let inputCol = tileColA + innerCol; + ${el(c,u)} + } + } + + // Load one tile of B into local memory. + for (var innerRow = 0; innerRow < ${de}; 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) { + ${Yc(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, ${f}>; + const rowPerThread = ${n[1]}; + const colPerThread = ${n[0]}; + const tileInner = ${f}; + +@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(x/f)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; + var kStart = ${d?`i32(globalId.z) * ${x}`:"0"}; + + var acc : array, rowPerThread>; + ${we} + } +`},Ns=(n,i,s,u,c,f=!1)=>{let[d,x,k]=c,[$,H,q,v]=u,oe=wo(d,k),te=wo(x,k),de=Sr(u[0].type.tensor),we=()=>{let he=H.rank,De=$.rank,Ae=`var aIndices: ${H.type.indices};`;for(let Ie=he-2-1,gt=De-1;Ie>=0;Ie--,gt--)Ae+=` +aIndices[${Ie}] = ${De>1?`batchIndices[${gt}]`:"batchIndices"};`;return oe.forEach(Ie=>{Ae+=` +aIndices[${Ie}] = 0;`}),Ae+=` +aIndices[${he-2}] = u32(row); + aIndices[${he-1}] = u32(colIn);`,Ae},be=()=>{let he=q.rank,De=$.rank,Ae=`var bIndices: ${q.type.indices};`;for(let Ie=he-2-1,gt=De-1;Ie>=0;Ie--,gt--)Ae+=` +bIndices[${Ie}] = ${De>1?`batchIndices[${gt}]`:"batchIndices"};`;return te.forEach(Ie=>{Ae+=` +bIndices[${Ie}] = 0;`}),Ae+=` +bIndices[${he-2}] = u32(row); + bIndices[${he-1}] = u32(colIn);`,Ae};return` + fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${$.type.indices}) -> ${vn(n,de)} { + var value = ${vn(n,de)}(0.0); + let col = colIn * ${n}; + if(row < uniforms.dim_a_outer && col < uniforms.dim_inner) + { + ${we()} + value = ${H.getByIndices("aIndices")}; + } + return value; + } + + fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${$.type.indices}) -> ${vn(n,de)} { + var value = ${vn(n,de)}(0.0); + let col = colIn * ${n}; + if(row < uniforms.dim_inner && col < uniforms.dim_b_outer) + { + ${be()} + value = ${q.getByIndices("bIndices")}; + } + return value; + } + + fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${vn(n,de)}) { + let col = colIn * ${n}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) { + var value = valueIn; + let coords = vec3(batch, row, colIn); + ${i?`value = value + ${f?"bias[colIn]":`${vn(n,de)}(bias[row])`};`:""} + ${s} + ${v.setByIndices("vec3(coords)","value")} + } + } + `},tl=(n,i,s,u,c=!1)=>{let f=n[0].dims,d=n[1].dims,x=f.slice(0,-2),k=d.slice(0,-2),$=u?u.slice(0,-2):s.slice(0,-2),H=ct.size($),q=f[f.length-2],v=f[f.length-1],oe=d[d.length-1],te=v%4===0&&oe%4===0,de=q<=8?[4,1,1]:[4,4,1],we=[8,8,1],be=[Math.ceil(oe/we[0]/de[0]),Math.ceil(q/we[1]/de[1]),Math.ceil(H/we[2]/de[2])],he=te?4:1,De=[...x,q,v/he],Ae=De.length,Ie=[...k,v,oe/he],gt=Ie.length,ut=[H,q,oe/he],vt=[{type:6,data:q},{type:6,data:oe},{type:6,data:v}];Wi(i,vt),vt.push(...At($,De,Ie));let Dt=["rank","rank"],Rt=n.length>2;Rt&&(vt.push(...At(n[2].dims)),Dt.push("rank")),vt.push(...At(ut));let gr=Mr=>{let ir=$.length,Fr=ma("batchDims",n[0].dataType,ir,1),Zr=Sr(n[0].dataType),hr=_t("a",n[0].dataType,Ae,he),Hr=_t("b",n[1].dataType,gt,he),Nt=Gt("result",n[0].dataType,ut.length,he),er=[hr,Hr];if(Rt){let Wr=c?he:1;er.push(_t("bias",n[2].dataType,n[2].dims.length,Wr))}let yr=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];Ei(i,yr);let ot=Sr(Nt.type.tensor),Vt=Vi(i,Nt.type.value,ot),nr=Ns(he,Rt,Vt,[Fr,hr,Hr,Nt],[x,k,$],c);return` + ${Mr.registerUniforms(yr).registerInternalVariables(Fr).declareVariables(...er,Nt)} + ${nr} + ${te?Rs(de,we,Zr,Fr):Bs(de,we,Zr,Fr)} + `};return{name:"MatMul",shaderCache:{hint:`${de};${i.activation};${te};${c}`,inputDependencies:Dt},getRunData:()=>({outputs:[{dims:s,dataType:n[0].dataType}],dispatchGroup:{x:be[0],y:be[1],z:be[2]},programUniforms:vt}),getShaderSource:gr}}}),Zc,lf,uf=h(()=>{Zt(),jn(),ar(),Gi(),xo(),Xc(),js(),Zc=(n,i,s,u,c=!1,f,d=4,x=4,k=4,$="f32")=>{let H=Dt=>{switch(Dt){case 1:return"resData = x[xIndex];";case 3:return`resData = vec3<${$}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return"resData = x[xIndex / 4];";default:throw new Error(`innerElementSize ${Dt} is not supported.`)}},q=Dt=>{switch(Dt){case 1:return"return w[row * i32(uniforms.w_shape[3]) + colIn];";case 4:return"return w[row * i32(uniforms.w_shape[3]) / 4 + colIn];";default:throw new Error(`innerElementSize ${Dt} is not supported.`)}},v=n?` + let coord = vec4(batch, xRow, xCol, xCh); + `:` + let coord = vec4(batch, xCh, xRow, xCol); + `,oe=n?` + let coords = vec4( + batch, + row / outWidth, + row % outWidth, + col); + `:` + let coords = vec4( + batch, + row, + col / outWidth, + col % outWidth); + `,te=n?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",de=n?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",we=n?"row":"col",be=n?"col":"row",he=` + let inChannels = i32(uniforms.w_shape[2]); + let outWidth = ${n?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; + let outRow = ${we} / outWidth; + let outCol = ${we} % 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 = ${vn(d,$)}(0.0); + // The bounds checking is always needed since we use it to pad zero for + // the 'same' padding type. + if (xRow >= 0 && xRow < ${te} && xCol >= 0 && xCol < ${de}) { + ${v} + let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape)); + ${H(d)} + } + return resData;`,De=n?i&&u?` + let col = colIn * ${d}; + ${he}`:` + let col = colIn * ${d}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { + ${he} + } + return ${vn(d,$)}(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 ${vn(d,$)}(0.0);`,Ae=`${q(x)}`,Ie=vn(k,$),gt=vn(n?d:x,$),ut=vn(n?x:d,$),vt=Vi(f,Ie,$);return` + fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${gt} { + ${n?De:Ae} + } + + fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${ut} { + ${n?Ae:De} + } + + fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${Ie}) { + let col = colIn * ${k}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) + { + var value = valueIn; + let outWidth = ${n?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; + ${oe} + ${Za(c)} + ${vt} + setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); + } + }`},lf=(n,i,s,u,c,f,d,x)=>{let k=i.format==="NHWC",$=k?n[0].dims[3]:n[0].dims[1],H=s[0],q=k?s[2]:s[3],v=k?s[1]:s[2],oe=k?s[3]:s[1],te=k&&($%4===0||$%3===0)&&oe%4===0,de=k?oe:q*v,we=k?q*v:oe,be=[8,8,1],he=u<=8?[4,1,1]:[4,4,1],De=[Math.ceil(de/be[0]/he[0]),Math.ceil(we/be[1]/he[1]),Math.ceil(H/be[2]/he[2])];Vr("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${De}`);let Ae=te?k&&$%4!==0?3:4:1,Ie=be[1]*he[1],gt=be[0]*he[0],ut=Math.max(be[0]*Ae,be[1]),vt=u%Ie===0,Dt=c%gt===0,Rt=f%ut===0,gr=te?[Ae,4,4]:[1,1,1],Mr=[{type:6,data:u},{type:6,data:c},{type:6,data:f},{type:6,data:[i.pads[0],i.pads[1]]},{type:6,data:i.strides},{type:6,data:i.dilations}];Wi(i,Mr),Mr.push(...At(n[0].dims,n[1].dims));let ir=["rank","rank"];d&&(Mr.push(...At(n[2].dims)),ir.push("rank")),Mr.push(...At(s));let Fr=Zr=>{let hr=[{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}];Ei(i,hr);let Hr=te?4:1,Nt=Sr(n[0].dataType),er=` + fn setOutputAtIndex(flatIndex : i32, value : ${te?`vec4<${Nt}>`:Nt}) { + result[flatIndex] = ${te?`vec4<${Nt}>`:Nt}(value); + } + fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${te?`vec4<${Nt}>`:Nt}) { + let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3)); + setOutputAtIndex(flatIndex ${te?"/ 4":""}, value); + }`,yr=_t("x",n[0].dataType,n[0].dims.length,Ae===3?1:Ae),ot=_t("w",n[1].dataType,n[1].dims.length,Hr),Vt=[yr,ot],nr=Gt("result",n[0].dataType,s.length,Hr);if(d){let Wr=_t("bias",n[2].dataType,n[2].dims.length,Hr);Vt.push(Wr),er+=` + fn getBiasByOutputCoords(coords : vec4) -> ${te?`vec4<${Nt}>`:Nt} { + return bias[coords.${k?"w":"y"}${te?"/ 4":""}]; + }`}return` + ${Ja("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 }; + ${Zr.registerUniforms(hr).declareVariables(...Vt,nr)} + ${er} + ${Zc(k,vt,Dt,Rt,d,i,gr[0],gr[1],gr[2],Nt)} + ${te?Rs(he,be,Nt,void 0,!k,ut):Bs(he,be,Nt,void 0,!k,ut,!1,void 0,x)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${i.cacheKey};${Ae};${te};${vt};${Dt};${Rt};${Ie};${gt};${ut}`,inputDependencies:ir},getRunData:()=>({outputs:[{dims:s,dataType:n[0].dataType}],dispatchGroup:{x:De[0],y:De[1],z:De[2]},programUniforms:Mr}),getShaderSource:Fr}}}),Jc,rl,Ci,ed,nl,td,rd,nd,il=h(()=>{Zt(),jn(),Jt(),ar(),Gi(),xo(),Jc=n=>{let i=1;for(let s=0;stypeof n=="number"?[n,n,n]:n,Ci=(n,i)=>i<=1?n:n+(n-1)*(i-1),ed=(n,i,s,u=1)=>{let c=Ci(i,u);return Math.floor((n[0]*(s-1)-s+c)/2)},nl=(n,i,s,u,c)=>{c==null&&(c=ed(n,i[0],u[0]));let f=[0,0,0,s];for(let d=0;d<3;d++)n[d]+2*c>=i[d]&&(f[d]=Math.trunc((n[d]-i[d]+2*c)/u[d]+1));return f},td=(n,i,s,u,c,f,d,x,k,$)=>{let H,q,v,oe;if(n==="VALID"&&(n=0),typeof n=="number"){H={top:n,bottom:n,left:n,right:n,front:n,back:n};let te=nl([i,s,u,1],[x,k,$],1,[c,f,d],n);q=te[0],v=te[1],oe=te[2]}else if(Array.isArray(n)){if(!n.every((de,we,be)=>de===be[0]))throw Error(`Unsupported padding parameter: ${n}`);H={top:n[0],bottom:n[1],left:n[2],right:n[3],front:n[4],back:n[5]};let te=nl([i,s,u,1],[x,k,$],1,[c,f,d],n[0]);q=te[0],v=te[1],oe=te[2]}else if(n==="SAME_UPPER"){q=Math.ceil(i/c),v=Math.ceil(s/f),oe=Math.ceil(u/d);let te=(q-1)*c+x-i,de=(v-1)*f+k-s,we=(oe-1)*d+$-u,be=Math.floor(te/2),he=te-be,De=Math.floor(de/2),Ae=de-De,Ie=Math.floor(we/2),gt=we-Ie;H={top:De,bottom:Ae,left:Ie,right:gt,front:be,back:he}}else throw Error(`Unknown padding parameter: ${n}`);return{padInfo:H,outDepth:q,outHeight:v,outWidth:oe}},rd=(n,i,s,u,c,f=!1,d="channelsLast")=>{let x,k,$,H,q;if(d==="channelsLast")[x,k,$,H,q]=n;else if(d==="channelsFirst")[x,q,k,$,H]=n;else throw new Error(`Unknown dataFormat ${d}`);let[v,,oe,te,de]=i,[we,be,he]=rl(s),[De,Ae,Ie]=rl(u),gt=Ci(oe,De),ut=Ci(te,Ae),vt=Ci(de,Ie),{padInfo:Dt,outDepth:Rt,outHeight:gr,outWidth:Mr}=td(c,k,$,H,we,be,he,gt,ut,vt),ir=f?v*q:v,Fr=[0,0,0,0,0];return d==="channelsFirst"?Fr=[x,ir,Rt,gr,Mr]:d==="channelsLast"&&(Fr=[x,Rt,gr,Mr,ir]),{batchSize:x,dataFormat:d,inDepth:k,inHeight:$,inWidth:H,inChannels:q,outDepth:Rt,outHeight:gr,outWidth:Mr,outChannels:ir,padInfo:Dt,strideDepth:we,strideHeight:be,strideWidth:he,filterDepth:oe,filterHeight:te,filterWidth:de,effectiveFilterDepth:gt,effectiveFilterHeight:ut,effectiveFilterWidth:vt,dilationDepth:De,dilationHeight:Ae,dilationWidth:Ie,inShape:n,outShape:Fr,filterShape:i}},nd=(n,i,s,u,c,f)=>{let d=f==="channelsLast";d?n[0].dims[3]:n[0].dims[1];let x=[64,1,1],k={x:s.map((we,be)=>be)},$=[Math.ceil(Jc(k.x.map(we=>s[we]))/x[0]),1,1];Vr("verbose",()=>`[conv3d_naive_webgpu] dispatch = ${$}`);let H=1,q=ct.size(s),v=[{type:12,data:q},{type:12,data:u},{type:12,data:c},{type:12,data:i.strides},{type:12,data:i.dilations}];Wi(i,v),v.push(...At(n[0].dims,n[1].dims));let oe=["rank","rank"],te=n.length===3;te&&(v.push(...At(n[2].dims)),oe.push("rank")),v.push(...At(s));let de=we=>{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}];Ei(i,be);let he=1,De=Sr(n[0].dataType),Ae=_t("x",n[0].dataType,n[0].dims.length,H),Ie=_t("W",n[1].dataType,n[1].dims.length,he),gt=[Ae,Ie],ut=Gt("result",n[0].dataType,s.length,he),vt="";if(te){let gr=_t("bias",n[2].dataType,n[2].dims.length,he);gt.push(gr),vt+=` + fn getBiasByOutputCoords(coords : array) -> ${De} { + return bias[${d?zt("coords",4,5):zt("coords",1,5)}]; + }`}let Dt=vn(H,De),Rt=Vi(i,Dt,De);return` + ${vt} + fn getX(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { + let aIndices = array(d0, d1, d2, d3, d4); + return ${Ae.getByIndices("aIndices")}; + } + fn getW(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { + let aIndices = array(d0, d1, d2, d3, d4); + return ${Ie.getByIndices("aIndices")}; + } + ${we.registerUniforms(be).declareVariables(...gt,ut)} + ${we.mainStart()} + ${we.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let coords = ${ut.offsetToIndices("global_idx")}; + let batch = ${zt("coords",0,Ae.rank)}; + let d2 = ${d?zt("coords",Ae.rank-1,Ae.rank):zt("coords",1,Ae.rank)}; + let xFRCCorner = vec3(${d?zt("coords",1,Ae.rank):zt("coords",2,Ae.rank)}, + ${d?zt("coords",2,Ae.rank):zt("coords",3,Ae.rank)}, + ${d?zt("coords",3,Ae.rank):zt("coords",4,Ae.rank)}) * uniforms.strides - uniforms.pads; + let xFCorner = xFRCCorner.x; + let xRCorner = xFRCCorner.y; + let xCCorner = xFRCCorner.z; + let xShapeY = ${d?zt("uniforms.x_shape",1,Ae.rank):zt("uniforms.x_shape",2,Ae.rank)}; + let xShapeZ = ${d?zt("uniforms.x_shape",2,Ae.rank):zt("uniforms.x_shape",3,Ae.rank)}; + let xShapeW = ${d?zt("uniforms.x_shape",3,Ae.rank):zt("uniforms.x_shape",4,Ae.rank)}; + let xShapeU = ${d?zt("uniforms.x_shape",4,Ae.rank):zt("uniforms.x_shape",1,Ae.rank)}; + let inputDepthNearestVec4 = (xShapeU / 4) * 4; + let inputDepthVec4Remainder = xShapeU % 4; + + var value = 0.0; + for (var wF = 0u; wF < uniforms.filter_dims[0]; wF++) { + let xF = xFCorner + wF * uniforms.dilations[0]; + if (xF < 0 || xF >= xShapeY) { + continue; + } + + for (var wR = 0u; wR < uniforms.filter_dims[1]; wR++) { + let xR = xRCorner + wR * uniforms.dilations[1]; + if (xR < 0 || xR >= xShapeZ) { + continue; + } + + for (var wC = 0u; wC < uniforms.filter_dims[2]; wC++) { + let xC = xCCorner + wC * uniforms.dilations[2]; + if (xC < 0 || xC >= xShapeW) { + continue; + } + + for (var d1 = 0u; d1 < inputDepthNearestVec4; d1 += 4) { + ${d?`let xValues = vec4( + getX(batch, xF, xR, xC, d1), + getX(batch, xF, xR, xC, d1 + 1), + getX(batch, xF, xR, xC, d1 + 2), + getX(batch, xF, xR, xC, d1 + 3)); + `:`let xValues = vec4( + getX(batch, d1, xF, xR, xC), + getX(batch, d1 + 1, xF, xR, xC), + getX(batch, d1 + 2, xF, xR, xC), + getX(batch, d1 + 3, xF, xR, xC)); + `} + let wValues = vec4( + getW(d2, d1, wF, wR, wC), + getW(d2, d1 + 1, wF, wR, wC), + getW(d2, d1 + 2, wF, wR, wC), + getW(d2, d1 + 3, wF, wR, wC)); + value += dot(xValues, wValues); + } + if (inputDepthVec4Remainder == 1) { + ${d?`value += getX(batch, xF, xR, xC, inputDepthNearestVec4) + * getW(d2, inputDepthNearestVec4, wF, wR, wC);`:`value += getX(batch, inputDepthNearestVec4, xF, xR, xC) + * getW(d2, inputDepthNearestVec4, wF, wR, wC);`} + } else if (inputDepthVec4Remainder == 2) { + ${d?`let xValues = vec2( + getX(batch, xF, xR, xC, inputDepthNearestVec4), + getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1)); + `:`let xValues = vec2( + getX(batch, inputDepthNearestVec4, xF, xR, xC), + getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC)); + `} + let wValues = vec2( + getW(d2, inputDepthNearestVec4, wF, wR, wC), + getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC)); + value += dot(xValues, wValues); + } else if (inputDepthVec4Remainder == 3) { + ${d?`let xValues = vec3( + getX(batch, xF, xR, xC, inputDepthNearestVec4), + getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1), + getX(batch, xF, xR, xC, inputDepthNearestVec4 + 2)); + `:`let xValues = vec3( + getX(batch, inputDepthNearestVec4, xF, xR, xC), + getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC), + getX(batch, inputDepthNearestVec4 + 2, xF, xR, xC)); + `} + let wValues = vec3( + getW(d2, inputDepthNearestVec4, wF, wR, wC), + getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC), + getW(d2, inputDepthNearestVec4 + 2, wF, wR, wC)); + value += dot(xValues, wValues); + } + } + } + } + ${te?"value = value + getBiasByOutputCoords(coords)":""}; + ${Rt} + result[global_idx] = f32(value); + }`};return{name:"Conv3DNaive",shaderCache:{hint:`${i.cacheKey};${d};${H};${te}`,inputDependencies:oe},getRunData:()=>({outputs:[{dims:s,dataType:n[0].dataType}],dispatchGroup:{x:$[0],y:$[1],z:$[2]},programUniforms:v}),getShaderSource:de}}}),id,od,cf=h(()=>{Zt(),Jt(),ar(),cd(),Gi(),id=(n,i,s)=>{let u=n.length>2,c=u?"value += b[output_channel];":"",f=n[0].dims,d=n[1].dims,x=d[0]/i.group,k=i.format==="NHWC",$=Us(f,d,i.dilations,i.pads,i.strides,k),H=ct.size($),q=[{type:12,data:H},{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:x}];Wi(i,q),q.push(...At(f,d));let v=["rank","rank"];u&&(q.push(...At(n[2].dims)),v.push("rank")),q.push(...At($));let oe=te=>{let de=Gt("output",n[0].dataType,$.length),we=Sr(de.type.tensor),be=Vi(i,de.type.value,we),he=_t("x",n[0].dataType,f.length),De=_t("w",n[1].dataType,d.length),Ae=[he,De];u&&Ae.push(_t("b",n[2].dataType,n[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 Ei(i,Ie),` + ${te.registerUniforms(Ie).declareVariables(...Ae,de)} + + ${te.mainStart()} + ${te.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let outputIndices = ${de.offsetToIndices("global_idx")}; + let batch: u32 = outputIndices[0]; + let output_channel: u32 = outputIndices[${k?3:1}]; + let xRCCorner: vec2 = vec2(outputIndices[${k?1:2}], outputIndices[${k?2:3}]) * uniforms.strides - uniforms.pads; + let group_id: u32 = output_channel / uniforms.output_channels_per_group; + + var value: ${de.type.value} = ${de.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[${k?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[${k?2:3}]) { + continue; + } + + let xVal = ${k?he.get("batch","xHeight","xWidth","input_channel"):he.get("batch","input_channel","xHeight","xWidth")}; + let wVal = ${De.get("output_channel","wInChannel","wHeight","wWidth")}; + value += xVal*wVal; + } + } + } + ${c} + ${be} + ${de.setByOffset("global_idx","value")} + }`};return{name:"GroupedConv",shaderCache:{hint:i.cacheKey,inputDependencies:v},getRunData:()=>({outputs:[{dims:s?s($):$,dataType:n[0].dataType}],dispatchGroup:{x:Math.ceil(H/64)},programUniforms:q}),getShaderSource:oe}},od=(n,i,s)=>{let u=n.length>2,c=vr(s[3]),f=vr(s[2]),d=ct.size(s)/c/f,x=[n[0].dims[0],n[0].dims[1],n[0].dims[2],n[0].dims[3]/c],k=[n[1].dims[0],n[1].dims[1],n[1].dims[2],n[1].dims[3]/c],$=[s[0],s[1],s[2],s[3]/c],H=[{type:12,data:d},{type:6,data:[i.strides[0],i.strides[1]]},{type:6,data:[i.pads[0],i.pads[1]]}];Wi(i,H),H.push(...At(x,k,$));let q=(f-1)*i.strides[1]+k[1],v=oe=>{let te=Gt("output",n[0].dataType,$.length,c),de=Sr(te.type.tensor),we=Vi(i,te.type.value,de),be=_t("x",n[0].dataType,x.length,c),he=_t("w",n[1].dataType,k.length,c),De=[be,he];u&&De.push(_t("b",n[2].dataType,n[2].dims,c));let Ae=u?"value += b[output_channel];":"",Ie=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return Ei(i,Ie),` + ${oe.registerUniforms(Ie).declareVariables(...De,te)} + ${oe.mainStart()} + ${oe.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] / ${f}u; + let col = (index1 % width1) * ${f}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}, ${q}>; + var values: array<${te.type.value}, ${f}>; + 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 < ${k[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 < ${q}; 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 < ${k[1]}; w_width++) { + let w_val = ${he.get("w_height","w_width","0","output_channel")}; + for (var i = 0u; i < ${f}u; i++) { + values[i] = fma(x_vals[i * u32(uniforms.strides[1]) + w_width], w_val, values[i]); + } + } + } + } + + for (var i = 0u; i < ${f}u; i++) { + var value = values[i]; + ${Ae} + ${we} + ${te.set("batch","row","col + i","output_channel","value")}; + } + }`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${i.cacheKey};${c};${f};${q};${k[0]};${k[1]}`,inputDependencies:u?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:s,dataType:n[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:H}),getShaderSource:v}}}),ol,sd,ad,sl=h(()=>{Zt(),Jt(),js(),ar(),Gi(),ol=(n,i,s,u,c=!1)=>{let f=n[0].dims,d=n[1].dims,x=f[f.length-2],k=d[d.length-1],$=f[f.length-1],H=vr(k),q=vr($),v=vr(x),oe=ct.size(s)/H/v,te=n.length>2,de=u?u.slice(0,-2):s.slice(0,-2),we=[ct.size(de),x,k],be=[{type:12,data:oe},{type:12,data:x},{type:12,data:k},{type:12,data:$}];Wi(i,be),be.push(...At(de,f,d)),te&&be.push(...At(n[2].dims)),be.push(...At(we));let he=De=>{let Ae=ma("batch_dims",n[0].dataType,de.length),Ie=_t("a",n[0].dataType,f.length,q),gt=_t("b",n[1].dataType,d.length,H),ut=Gt("output",n[0].dataType,we.length,H),vt=Sr(ut.type.tensor),Dt=Vi(i,ut.type.value,vt),Rt=[Ie,gt],gr="";if(te){let er=c?H:1;Rt.push(_t("bias",n[2].dataType,n[2].dims.length,er)),gr=`${c?`value += bias[col / ${er}];`:`value += ${ut.type.value}(bias[row + i]);`}`}let Mr=f.slice(0,-2),ir=d.slice(0,-2),Fr=wo(Mr,de),Zr=wo(ir,de),hr=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];Ei(i,hr);let Hr=(er,yr)=>{let ot=er.rank,Vt=er.name;if(ot===2)return`var ${Vt}_indices = ${er.type.indices}(0u, 0u);`;let nr=Ae.rank,Wr=`var ${Vt}_indices: ${er.type.indices};`;for(let pn=ot-2-1,kn=nr-1;pn>=0;pn--,kn--)Wr+=` +${Vt}_indices[${pn}] = ${nr>1?`batch_indices[${kn}]`:"batch_indices"};`;return yr.forEach(pn=>{Wr+=` +${Vt}_indices[${pn}] = 0;`}),Wr+=`${Vt}_indices[${ot-2}] = 0u; + ${Vt}_indices[${ot-1}] = 0u;`,Wr},Nt=()=>{let er=`var a_data: ${Ie.type.value};`;for(let yr=0;yr; + for (var k: u32 = 0u; k < uniforms.K; k = k + ${q}) { + ${Nt()} + } + for (var i = 0u; i < ${v}u; i++) { + var value = values[i]; + ${gr} + ${Dt} + let cur_indices = ${ut.type.indices}(batch, row + i, col); + let offset = ${ut.indicesToOffset("cur_indices")}; + ${ut.setByOffset(`offset / ${H}`,"value")}; + } + } + `};return{name:"MatMulNaive",shaderCache:{hint:`${i.activation};${H};${q};${v};${c}`,inputDependencies:te?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:s,dataType:n[0].dataType}],dispatchGroup:{x:Math.ceil(oe/64)},programUniforms:be}),getShaderSource:he}},sd=n=>{if(!n||n.length!==2)throw new Error("MatMul requires 2 inputs.");if(n[0].dims[n[0].dims.length-1]!==n[1].dims[n[1].dims.length-2])throw new Error("shared dimension does not match.")},ad=n=>{sd(n.inputs);let i=gn.calcShape(n.inputs[0].dims,n.inputs[1].dims,!0);if(!i)throw new Error("Can't use matmul on the given tensors");let s=i[i.length-1],u=n.inputs[0].dims[n.inputs[0].dims.length-1];s<8&&u<8?n.compute(ol(n.inputs,{activation:""},i)):n.compute(tl(n.inputs,{activation:""},i))}}),Us,Vs,al,Ws,ll,ul,ld,ud,Ko,cd=h(()=>{Jt(),uf(),il(),js(),cf(),Gi(),sl(),yo(),Us=(n,i,s,u,c,f)=>{let d=n[0],x=n.slice(f?1:2,f?3:4),k=x.length,$=i[0],H=i.slice(2).map((v,oe)=>v+(v-1)*(s[oe]-1)),q=x.map((v,oe)=>v+u[oe]+u[oe+k]).map((v,oe)=>Math.floor((v-H[oe]+c[oe])/c[oe]));return q.splice(0,0,d),q.splice(f?3:1,0,$),q},Vs=[2,3,1,0],al=(n,i)=>{if(!n||n.length!==2&&n.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(n[0].dims.length>5)throw new Error("greater than 5D is not supported");if(n[0].dims.length!==n[1].dims.length)throw new Error("filter does not have same dimension as input");let s=n[0].dims[i.format==="NHWC"?n[0].dims.length-1:1],u=n[1].dims[1]*i.group;if(s!==u)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");if(n.length===3&&(n[2].dims.length!==1||n[1].dims[0]!==n[2].dims[0]))throw new Error("invalid bias");let c=n[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!==n[1].dims.length-2)throw new Error("invalid kernel shape")},Ws=(n,i)=>{let s=n.kernelShape.slice();for(let f=2;f{let i=Ya(n),s=n.format,u=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][n.auto_pad],c=n.dilations,f=n.group,d=n.kernel_shape,x=n.pads,k=n.strides,$=n.w_is_const();return{autoPad:u,format:s,dilations:c,group:f,kernelShape:d,pads:x,strides:k,wIsConst:$,...i,cacheKey:`${n.format};${i.activation};`}},ul=(n,i,s)=>{let u=Ws(s,i),c=s.format==="NHWC";if(s.group!==1){if(!n.adapterInfo.isArchitecture("ampere")&&c&&i[1].dims[0]===s.group&&i[1].dims[1]===1&&s.dilations[0]===1&&s.dilations[1]===1){let gt=Us(i[0].dims,i[1].dims,s.dilations,u.pads,s.strides,c),ut=n.kernelCustomData.wT??n.compute(hi(i[1],Vs),{inputs:[1],outputs:[s.wIsConst?-2:-1]})[0];s.wIsConst&&!n.kernelCustomData.wT&&(n.kernelCustomData.wT=ut);let vt=[i[0],ut];i.length===3&&vt.push(i[2]),n.compute(od(vt,u,gt),{inputs:vt})}else n.compute(id(i,u));return}let f=i.length===3,d=i[0].dims[c?1:2],x=i[0].dims[c?2:3],k=i[0].dims[c?3:1],$=i[1].dims[2],H=i[1].dims[3],q=Us(i[0].dims,i[1].dims,s.dilations,u.pads,s.strides,c),v=q[c?1:2],oe=q[c?2:3],te=q[c?3:1],de=c&&$===d&&H===x&&s.pads[0]===0&&s.pads[1]===0;if(de||$===1&&H===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 gt=q[0],ut,vt,Dt,Rt=[];if(c){let ir=n.kernelCustomData.wT??n.compute(hi(i[1],Vs),{inputs:[1],outputs:[s.wIsConst?-2:-1]})[0];if(s.wIsConst&&!n.kernelCustomData.wT&&(n.kernelCustomData.wT=ir),de){let Fr=d*x*k;ut=i[0].reshape([1,gt,Fr]),vt=ir.reshape([1,Fr,te]),Dt=[1,gt,te]}else ut=i[0].reshape([gt,d*x,k]),vt=ir.reshape([1,k,te]),Dt=[gt,v*oe,te];Rt.push(ut),Rt.push(vt)}else ut=i[0].reshape([gt,k,d*x]),vt=i[1].reshape([1,te,k]),Dt=[gt,te,v*oe],Rt.push(vt),Rt.push(ut);f&&Rt.push(i[2]);let gr=Dt[2],Mr=Rt[0].dims[Rt[0].dims.length-1];gr<8&&Mr<8?n.compute(ol(Rt,u,q,Dt,c),{inputs:Rt}):n.compute(tl(Rt,u,q,Dt,c),{inputs:Rt});return}let we=!0,be=n.kernelCustomData.wT??n.compute(hi(i[1],Vs),{inputs:[1],outputs:[s.wIsConst?-2:-1]})[0];s.wIsConst&&!n.kernelCustomData.wT&&(n.kernelCustomData.wT=be);let he=[i[0],be];f&&he.push(i[2]);let De=c?v*oe:te,Ae=c?te:v*oe,Ie=$*H*k;n.compute(lf(he,u,q,De,Ae,Ie,f,we),{inputs:he})},ld=(n,i)=>{let s=i.format==="NHWC",u=[n.inputs[0].reshape(s?[n.inputs[0].dims[0],1,n.inputs[0].dims[1],n.inputs[0].dims[2]]:[n.inputs[0].dims[0],n.inputs[0].dims[1],1,n.inputs[0].dims[2]]),n.inputs[1].reshape([n.inputs[1].dims[0],n.inputs[1].dims[1],1,n.inputs[1].dims[2]])];n.inputs.length===3&&u.push(n.inputs[2]);let c=[0,i.pads[0],0,i.pads[1]],f=[1].concat(i.strides),d=[1].concat(i.dilations),x=[1].concat(i.kernelShape),k=Ws({...i,pads:c,strides:f,dilations:d,kernelShape:x},u);n.compute(id(u,k,$=>s?[$[0],$[2],$[3]]:[]))},ud=(n,i,s)=>{let u=s.format==="NHWC"?"channelsLast":"channelsFirst",c=Ws(s,i),f=s.autoPad==="NOTSET"?s.pads:s.autoPad,d=rd(i[0].dims,i[1].dims,s.strides,s.dilations,f,!1,u);n.compute(nd(i,c,d.outShape,[d.filterDepth,d.filterHeight,d.filterWidth],[d.padInfo.front,d.padInfo.top,d.padInfo.left],u))},Ko=(n,i)=>{al(n.inputs,i),n.inputs[0].dims.length===3?ld(n,i):n.inputs[0].dims.length===5?ud(n,n.inputs,i):ul(n,n.inputs,i)}}),dd,pd,df=h(()=>{Zt(),jn(),ar(),Gi(),xo(),Xc(),js(),dd=(n,i=!1,s,u,c=4)=>{let f=we=>{switch(we){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 ${we} is not supported.`)}},d=n?` + let coord = vec4(batch, iXR, iXC, xCh); + `:` + let coord = vec4(batch, xCh, iXR, iXC); + `,x=n?` + let coords = vec4( + batch, + row / outWidth, + row % outWidth, + col); + `:` + let coords = vec4( + batch, + row, + col / outWidth, + col % outWidth); + `,k=n?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",$=n?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",H=n?"row":"col",q=n?"col":"row",v=` + let inChannels = ${n?"i32(uniforms.x_shape[3])":"i32(uniforms.x_shape[1])"}; + let outWidth = ${n?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; + let outRow = ${H} / outWidth; + let outCol = ${H} % outWidth; + + let WRow = ${q} / (uniforms.filter_dims[1] * inChannels); + let WCol = ${q} / 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(${k}) || fract(xR) > 0.0) { + return ${u}(0.0); + } + if (xC < 0.0 || xC >= f32(${$}) || fract(xC) > 0.0) { + return ${u}(0.0); + } + let iXR = i32(xR); + let iXC = i32(xC); + let xCh = ${q} % inChannels; + ${d} + return x[getIndexFromCoords4D(coord, vec4(uniforms.x_shape))/${c}];`,oe=n?` + 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);`,te=` + let col = colIn * ${c}; + let inChannels = ${n?"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 (${n?"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); + ${f(c)} + } + return ${u}(0.0); + `,de=Vi(s,u);return` + fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${u} { + ${n?oe:te} + } + + fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${u} { + ${n?te:oe} + } + + 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 = ${n?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; + ${x} + ${Za(i)} + ${de} + result[getIndexFromCoords4D(coords, vec4(uniforms.result_shape))/${c}] = value; + } + }`},pd=(n,i,s,u,c,f,d,x)=>{let k=i.format==="NHWC",$=k?n[0].dims[3]:n[0].dims[1],H=s[0],q=k?s[2]:s[3],v=k?s[1]:s[2],oe=k?s[3]:s[1],te=k&&$%4===0&&$%3&&oe%4===0,de=k?oe:q*v,we=k?q*v:oe,be=[8,8,1],he=u<=8?[4,1,1]:[4,4,1],De=[Math.ceil(de/be[0]/he[0]),Math.ceil(we/be[1]/he[1]),Math.ceil(H/be[2]/he[2])];Vr("verbose",()=>`[conv_backprop_mm_webgpu] dispatch = ${De}`);let Ae=te?4:1,Ie=Math.max(be[0]*Ae,be[1]),gt=te?4:1,ut=[i.kernelShape[k?1:2],i.kernelShape[k?2:3]],vt=[ut[0]+(i.dilations[0]<=1?0:(ut[0]-1)*(i.dilations[0]-1)),ut[1]+(i.dilations[1]<=1?0:(ut[1]-1)*(i.dilations[1]-1))],Dt=[vt[0]-1-Math.floor((i.pads[0]+i.pads[2])/2),vt[1]-1-Math.floor((i.pads[1]+i.pads[3])/2)],Rt=[{type:6,data:u},{type:6,data:c},{type:6,data:f},{type:6,data:i.strides},{type:6,data:i.dilations},{type:6,data:ut},{type:6,data:Dt}];Wi(i,Rt),Rt.push(...At(n[0].dims,n[1].dims));let gr=["rank","rank"];d&&(Rt.push(...At(n[2].dims)),gr.push("rank")),Rt.push(...At(s));let Mr=ir=>{let Fr=_t("x",n[0].dataType,n[0].dims.length,gt),Zr=_t("w",n[1].dataType,n[1].dims.length,1),hr=Gt("result",n[0].dataType,s.length,gt),Hr=[Fr,Zr],Nt="";if(d){let ot=_t("bias",n[2].dataType,n[2].dims.length,gt);Hr.push(ot),Nt+=` + fn getBiasByOutputCoords(coords : vec4) -> ${ot.type.value} { + return bias[coords.${k?"w":"y"}${te?"/ 4":""}]; + }`}let er=[{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:ut.length},{name:"pads",type:"i32",length:Dt.length}];Ei(i,er);let yr=Sr(n[0].dataType,1);if(yr!=="f16"&&yr!=="f32")throw new Error(`elemType ${yr} is not supported.`);return` + ${Ja("uniforms.result_strides")} + ${ir.registerUniforms(er).declareVariables(...Hr,hr)}; + ${Nt} + ${dd(k,d,i,Fr.type.value,Ae)} + ${te?Rs(he,be,yr,void 0,!k,Ie):Bs(he,be,yr,void 0,!k,Ie,!1,void 0,x)}`};return{name:"Conv2DTransposeMatMul",shaderCache:{hint:`${i.cacheKey};${he};${be};${te}`,inputDependencies:gr},getRunData:()=>({outputs:[{dims:s,dataType:n[0].dataType}],dispatchGroup:{x:De[0],y:De[1],z:De[2]},programUniforms:Rt}),getShaderSource:Mr}}}),cl,Xo,mm=h(()=>{Zt(),jn(),Jt(),ar(),cl=(n,i,s,u,c,f=!1,d,x,k=!1)=>{let $=k?1:2,H=k?2:3,q=k?3:1,v=f?2:1,oe=` + fn setOutputAtIndex(flatIndex : u32, value : ${f?`vec4<${d}>`:d}) { + result[flatIndex] = ${f?`vec4<${d}>`:d}(value); + }`;u&&(oe+=` + fn getBiasByOutputCoords(coords : vec4) -> ${f?`vec4<${d}>`:d} { + return bias[coords.${k?"w":"y"}${f?"/ 4":""}]; + }`);let te=f?4:1,de=_t("W",i[1].dataType,i[1].dims.length,te),we=_t("Dy",i[0].dataType,i[0].dims.length,te),be=[we,de];u&&be.push(_t("bias",i[2].dataType,[s[q]].length,te));let he=Gt("result",i[0].dataType,s.length,te),De=`{ + 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 = ${de.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; + let wValue1 = ${de.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; + let wValue2 = ${de.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; + let wValue3 = ${de.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; + + var xValue = ${we.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 = ${we.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[${q}]; + for (var d2: u32 = 0; d2 < d2Length; d2 = d2 + 4) { + let wValue0 = ${de.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; + let wValue1 = ${de.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; + let wValue2 = ${de.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; + let wValue3 = ${de.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; + + var xValue = ${we.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 = ${de.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; + let wValue1 = ${de.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; + let wValue2 = ${de.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; + let wValue3 = ${de.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; + + var xValue = ${we.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")}; + } + }`,Ae=` + let outputIndices = ${he.offsetToIndices("global_idx")}; + let batch = ${he.indicesGet("outputIndices",0)}; + let d1 = ${he.indicesGet("outputIndices",q)}; + let r = ${he.indicesGet("outputIndices",$)}; + let c = ${he.indicesGet("outputIndices",H)}; + 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[${$}]) || 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[${H}]) || + 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 = ${k?we.get("batch","idyR","idyC","inputChannel"):we.get("batch","inputChannel","idyR","idyC")}; + let wValue = ${de.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` + ${n.registerUniforms(x).declareVariables(...be,he)} + ${oe} + + ${n.mainStart()} + ${n.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}; + ${f?De:Ae}}`},Xo=(n,i,s)=>{let u=n.length>2,c=i.outputShape,f=ct.size(c),d=[Math.ceil(f/64),1,1];Vr("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${d}`);let x=i.format==="NHWC",k=["rank","rank"],$=[i.strides[0],i.strides[1]],H=[i.kernelShape[x?1:2],i.kernelShape[x?2:3]],q=[i.dilations[0],i.dilations[1]],v=[H[0]+(i.dilations[0]<=1?0:(i.kernelShape[x?1:2]-1)*(i.dilations[0]-1)),H[1]+(i.dilations[1]<=1?0:(i.kernelShape[x?2:3]-1)*(i.dilations[1]-1))],oe=[v[0]-1-Math.floor((i.pads[0]+i.pads[2])/2),v[1]-1-Math.floor(i.pads[1]+i.pads[3])/2],te=!1,de=i.group,we=n[1].dims,be=we[0]/de,he=we[1],De=[{type:12,data:f},{type:12,data:$},{type:12,data:H},{type:12,data:q},{type:12,data:v},{type:6,data:oe},{type:12,data:be},{type:12,data:he},...At(n[0].dims,n[1].dims)];u&&(De.push(...At(n[2].dims)),k.push("rank")),De.push(...At(c));let Ae=d[1]===1&&d[2]===1,Ie=gt=>{let ut=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:$.length},{name:"filter_dims",type:"u32",length:H.length},{name:"dilations",type:"u32",length:H.length},{name:"effective_filter_dims",type:"u32",length:v.length},{name:"pads",type:"i32",length:oe.length},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],vt=Sr(n[0].dataType);return`${cl(gt,n,c,u,Ae,te,vt,ut,x)}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${i.cacheKey};`,inputDependencies:k},getRunData:()=>({dispatchGroup:{x:d[0],y:d[1],z:d[2]},outputs:[{dims:s?s(c):c,dataType:n[0].dataType}],programUniforms:De}),getShaderSource:Ie}}}),fd,hd,dl,pl,md,fl,gd,_d,hl,pf,gm=h(()=>{df(),mm(),Gi(),yo(),fd=(n,i,s,u,c,f)=>(n-1)*i+s+(u-1)*c+1-f,hd=(n,i,s,u,c)=>{let f=Math.floor(n/2);i==="SAME_UPPER"?(s[u]=f,s[c]=n-f):i==="SAME_LOWER"&&(s[u]=n-f,s[c]=f)},dl=(n,i,s,u,c,f,d,x,k,$)=>{let H=n.length-2,q=$.length===0;if(k.length===0)for(let te=0;te{let s=n.kernelShape.slice();if(n.kernelShape.length===0||n.kernelShape.reduce((q,v)=>q*v,1)===0){s.length=0;for(let q=2;qq+v,0)===0){let q=i[0].dims.length-2;k=new Array(q).fill(1)}let $=n.strides.slice();if($.reduce((q,v)=>q+v,0)===0){let q=i[0].dims.length-2;$=new Array(q).fill(1)}dl(x,s,k,n.autoPad,n.group,c,$,u,d,f);let H=Object.assign({},n);return Object.assign(H,{kernelShape:s,pads:c,outputPadding:d,outputShape:f,dilations:k,strides:$}),H},md=n=>{let i=Ya(n),s=n.format,u=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof n.autoPad>"u"?0:n.autoPad],c=n.dilations,f=n.group,d=n.kernelShape,x=n.pads,k=n.strides,$=n.wIsConst(),H=n.outputPadding,q=n.outputShape;return{autoPad:u,format:s,dilations:c,group:f,kernelShape:d,outputPadding:H,outputShape:q,pads:x,strides:k,wIsConst:$,...i,cacheKey:`${n.format};${i.activation};`}},fl=(n,i)=>{if(!n||n.length!==2&&n.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(n[0].dims.length!==4&&n[0].dims.length!==3)throw new Error("currently only support 2-dimensional conv");if(n[0].dims.length!==n[1].dims.length)throw new Error("filter does not have same dimension as input");let s=n[0].dims[i.format==="NHWC"?n[0].dims.length-1:1],u=n[1].dims[0];if(s!==u)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");let c=n[1].dims[1]*i.group;if(n.length===3&&(n[2].dims.length!==1||n[2].dims[0]!==c))throw new Error("invalid bias");let f=n[0].dims.length-2;if(i.dilations.reduce((d,x)=>d+x,0)>0&&i.dilations.length!==f)throw new Error(`dilations should be ${f}D`);if(i.strides.reduce((d,x)=>d+x,0)>0&&i.strides.length!==f)throw new Error(`strides should be ${f}D`);if(i.pads.reduce((d,x)=>d+x,0)>0&&i.pads.length!==f*2)throw new Error(`pads should be ${f*2}D`);if(i.outputPadding.length!==f&&i.outputPadding.length!==0)throw new Error(`output_padding should be ${f}D`);if(i.kernelShape.reduce((d,x)=>d+x,0)>0&&i.kernelShape.length!==0&&i.kernelShape.length!==n[1].dims.length-2)throw new Error("invalid kernel shape");if(i.outputShape.length!==0&&i.outputShape.length!==n[0].dims.length-2)throw new Error("invalid output shape")},gd=[2,3,1,0],_d=(n,i,s)=>{let u=pl(s,i),c=s.format==="NHWC",f=u.outputShape,d=f[c?3:1],x=i[0].dims[c?3:1];if(u.group!==1||d===1&&x===1){n.compute(Xo(i,u));return}let k=f[c?1:2],$=f[c?2:3],H=i[1].dims[2],q=i[1].dims[3],v=c?k*$:d,oe=c?d:k*$,te=H*q*x,de=!0,we=n.kernelCustomData.wT??n.compute(hi(i[1],gd),{inputs:[1],outputs:[s.wIsConst?-2:-1]})[0];s.wIsConst&&!n.kernelCustomData.wT&&(n.kernelCustomData.wT=we);let be=[i[0],we],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])),n.compute(pd(be,u,f,v,oe,te,he,de),{inputs:be})},hl=(n,i)=>{let s=i.format==="NHWC",u=[n.inputs[0].reshape(s?[n.inputs[0].dims[0],1,n.inputs[0].dims[1],n.inputs[0].dims[2]]:[n.inputs[0].dims[0],n.inputs[0].dims[1],1,n.inputs[0].dims[2]]),n.inputs[1].reshape([n.inputs[1].dims[0],n.inputs[1].dims[1],1,n.inputs[1].dims[2]])];n.inputs.length===3&&u.push(n.inputs[2]);let c=i.kernelShape;(c.length===0||c[0]===0)&&(c=[n.inputs[1].dims[2]]);let f=i.dilations;(f.length===0||f[0]===0)&&(f=[1]);let d=i.strides;(d.length===0||d[0]===0)&&(d=[1]);let x=i.pads;x.length===0&&(x=[0,0]),x=[0,x[0],0,x[1]],d=[1].concat(d),f=[1].concat(f),c=[1].concat(c);let k=pl({...i,pads:x,strides:d,dilations:f,kernelShape:c},u);n.compute(Xo(u,k,$=>s?[$[0],$[2],$[3]]:[$[0],$[1],$[3]]))},pf=(n,i)=>{fl(n.inputs,i),n.inputs[0].dims.length===3?hl(n,i):_d(n,n.inputs,i)}}),ml,gl,wd,ff=h(()=>{Zt(),Jt(),_r(),ar(),ml=(n,i,s,u)=>{let c=ct.size(i),f=i.length,d=_t("input",n,f),x=Gt("output",n,f),k=s.dataType===6?s.getInt32Array()[0]:Number(s.getBigInt64Array()[0]),$=ct.normalizeAxis(k,f),H=q=>{let v=` i32(${d.indicesGet("inputIndices","uniforms.axis")}) `,oe=zt("uniforms.input_shape","uniforms.axis",f),te=u.reverse?v+(u.exclusive?" + 1":""):"0",de=u.reverse?oe:v+(u.exclusive?"":" + 1");return` + ${q.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(d,x)} + ${q.mainStart()} + ${q.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var inputIndices = ${x.offsetToIndices("global_idx")}; + var sum = ${x.type.value}(0); + let first : i32 = ${te}; + let last : i32 = ${de}; + for (var i : i32 = first; i < last; i++) { + ${d.indicesSet("inputIndices","uniforms.axis","u32(i)")}; + sum = sum + ${d.getByIndices("inputIndices")}; + } + ${x.setByOffset("global_idx","sum")}; + }`};return{name:"CumSum",shaderCache:{hint:u.cacheKey,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:i,dataType:n}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:[{type:12,data:c},{type:12,data:$},...At(i,i)]}),getShaderSource:H}},gl=(n,i)=>{let s=n.inputs[0].dims,u=n.inputs[0].dataType,c=n.inputs[1];n.compute(ml(u,s,c,i),{inputs:[0]})},wd=n=>{let i=n.exclusive===1,s=n.reverse===1;return qt({exclusive:i,reverse:s})}}),_l,yd,vd,wl,bd,hf=h(()=>{Zt(),Jt(),_r(),ar(),_l=n=>{if(!n||n.length!==1)throw new Error("DepthToSpace requires 1 input.");if(n[0].dims.length!==4)throw new Error("DepthToSpace requires 4D input.")},yd=(n,i,s,u)=>{let c=[];c.push(`fn perm(i: ${u.type.indices}) -> ${s.type.indices} { + var a: ${s.type.indices};`);for(let f=0;f{let s,u,c,f,d,x,k=i.format==="NHWC",$=i.blocksize,H=i.mode==="DCR";k?([s,u,c,f]=n.dims,d=H?[s,u,c,$,$,f/$**2]:[s,u,c,f/$**2,$,$],x=H?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([s,u,c,f]=[n.dims[0],n.dims[2],n.dims[3],n.dims[1]],d=H?[s,$,$,f/$**2,u,c]:[s,f/$**2,$,$,u,c],x=H?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let q=n.reshape(d),v=q.dims.length,oe=n.dataType,te=_t("a",oe,v),de=Gt("output",oe,v),we=be=>` + ${be.registerUniform("output_size","u32").declareVariables(te,de)} + + ${yd(x,v,te,de)} + + ${be.mainStart()} + ${be.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${de.offsetToIndices("global_idx")}; + let aIndices = perm(indices); + + ${de.setByOffset("global_idx",te.getByIndices("aIndices"))} + }`;return{name:"DepthToSpace",shaderCache:{hint:`${n.dims};${i.blocksize};${i.mode}`,inputDependencies:["rank"]},getRunData:be=>{let he=k?[s,u*$,c*$,f/$**2]:[s,f/$**2,u*$,c*$],De=ct.size(he),Ae=q.dims,Ie=ct.sortBasedOnPerm(Ae,x);return{outputs:[{dims:he,dataType:be[0].dataType}],dispatchGroup:{x:Math.ceil(De/64)},programUniforms:[{type:12,data:De},...At(Ae,Ie)]}},getShaderSource:we}},wl=(n,i)=>{_l(n.inputs),n.compute(vd(n.inputs[0],i))},bd=n=>qt({blocksize:n.blocksize,mode:n.mode,format:n.format})}),Qo,Yo,yl,Rr,mf,gf,_f,Gs,xd,Md,Td,wf=h(()=>{Zt(),Jt(),_r(),ar(),Qo="[a-zA-Z]|\\.\\.\\.",Yo="("+Qo+")+",yl="^"+Yo+"$",Rr="("+Yo+",)*"+Yo,mf="^"+Rr+"$",gf=class{constructor(n=-1){this.symbolToIndices=new Map,this.inputIndex=n}addSymbol(n,i){let s=this.symbolToIndices.get(n);s===void 0?s=[i]:s.push(i),this.symbolToIndices.set(n,s)}},_f=class{constructor(n,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(mf)))throw new Error("Invalid LHS term");if(s.split(",").forEach((f,d)=>{let x=n[d].dims.slice();if(!f.match(RegExp(yl)))throw new Error("Invalid LHS term");let k=this.processTerm(f,!0,x,d);this.lhs.push(k)}),u==="")u+=[...this.symbolToInfo.entries()].filter(([f,d])=>d.count===1||f==="...").map(([f])=>f).join("");else if(!u.match(RegExp(Yo)))throw new Error("Invalid RHS");(c=u.match(RegExp(Qo,"g")))==null||c.forEach(f=>{if(f==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let d=this.symbolToInfo.get(f);if(d===void 0)throw new Error("Invalid RHS symbol");this.outputDims.push(d.dimValue)}}),this.rhs=this.processTerm(u,!1,this.outputDims)}addSymbol(n,i,s){let u=this.symbolToInfo.get(n);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(n,u)}processTerm(n,i,s,u=-1){let c=s.length,f=!1,d=[],x=0;if(!n.match(RegExp(yl))&&!i&&n!=="")throw new Error("Invalid LHS term");let k=n.match(RegExp(Qo,"g")),$=new gf(u);return k==null||k.forEach((H,q)=>{if(H==="..."){if(f)throw new Error("Only one ellipsis is allowed per input term");f=!0;let v=c-k.length+1;if(v<0)throw new Error("Ellipsis out of bounds");if(d=s.slice(x,x+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 oe=0;oen+"_max",xd=(n,i,s,u)=>{let c=n.map($=>$.length).map(($,H)=>_t(`input${H}`,i,$)),f=ct.size(u),d=Gt("output",i,u.length),x=[...s.symbolToInfo.keys()].filter($=>!s.rhs.symbolToIndices.has($)),k=$=>{let H=[],q="var prod = 1.0;",v="var sum = 0.0;",oe="sum += prod;",te=[],de=[],we=[],be=[],he=s.symbolToInfo.size===s.rhs.symbolToIndices.size;s.symbolToInfo.forEach((Ae,Ie)=>{var gt;if(s.rhs.symbolToIndices.has(Ie)){let ut=(gt=s.rhs.symbolToIndices.get(Ie))==null?void 0:gt[0];ut!==void 0&&s.lhs.forEach((vt,Dt)=>{if(Ae.inputIndices.includes(Dt)){let Rt=vt.symbolToIndices.get(Ie);if(Rt===void 0)throw new Error("Invalid symbol error");Rt.forEach(gr=>{H.push(`${c[Dt].indicesSet(`input${Dt}Indices`,gr,d.indicesGet("outputIndices",ut))}`)})}})}else s.lhs.forEach((ut,vt)=>{if(Ae.inputIndices.includes(vt)){let Dt=ut.symbolToIndices.get(Ie);if(Dt===void 0)throw new Error("Invalid symbol error");Dt.forEach(Rt=>{te.push(`${c[vt].indicesSet(`input${vt}Indices`,Rt,`${Ie}`)}`)}),be.push(`prod *= ${c[vt].getByIndices(`input${vt}Indices`)};`)}}),de.push(`for(var ${Ie}: u32 = 0; ${Ie} < uniforms.${Gs(Ie)}; ${Ie}++) {`),we.push("}")});let De=he?[...H,`let sum = ${c.map((Ae,Ie)=>Ae.getByIndices(`input${Ie}Indices`)).join(" * ")};`]:[...H,v,...de,...te,q,...be,oe,...we];return` + ${$.registerUniforms(x.map(Ae=>({name:`${Gs(Ae)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...c,d)} + + ${$.mainStart()} + ${$.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var outputIndices = ${d.offsetToIndices("global_idx")}; + ${c.map((Ae,Ie)=>`var input${Ie}Indices: ${c[Ie].type.indices};`).join(` +`)} + ${De.join(` +`)}; + ${d.setByOffset("global_idx","sum")}; + }`};return{name:"Einsum",shaderCache:{hint:s.equation,inputDependencies:n.map(()=>"rank")},getRunData:()=>{let $=x.filter(q=>s.symbolToInfo.has(q)).map(q=>{var v;return{type:12,data:((v=s.symbolToInfo.get(q))==null?void 0:v.dimValue)||0}});$.push({type:12,data:f});let H=n.map((q,v)=>[...At(q)]).reduce((q,v)=>q.concat(v),$);return H.push(...At(u)),{outputs:[{dims:u,dataType:i}],dispatchGroup:{x:Math.ceil(f/64)},programUniforms:H}},getShaderSource:k}},Md=(n,i)=>{let s=new _f(n.inputs,i.equation),u=s.outputDims,c=n.inputs.map((f,d)=>f.dims);n.compute(xd(c,n.inputs[0].dataType,s,u))},Td=n=>{let i=n.equation.replace(/\s+/g,"");return qt({equation:i})}}),vl,Hs,kd,Sd,bl,_m=h(()=>{Zt(),Jt(),ar(),vl=n=>{if(!n||n.length!==2)throw new Error("Expand requires 2 input.");let i=n[0].dims,s=Array.from(n[1].getBigInt64Array(),Number),u=s.length{let s=n.length-i.length,u=[];for(let c=0;cn.length>i.length?Hs(n,i):Hs(i,n),Sd=n=>{let i=n[0].dims,s=Array.from(n[1].getBigInt64Array(),Number),u=kd(i,s),c=n[0].dataType,f=c===9?4:1,d=Math.ceil(ct.size(u)/f),x=$=>{let H=_t("input",c,i.length,f),q=Gt("output",c,u.length,f),v;if(c===9){let oe=(te,de,we="")=>` + let outputIndices${de} = ${q.offsetToIndices(`outputOffset + ${de}u`)}; + let offset${de} = ${H.broadcastedIndicesToOffset(`outputIndices${de}`,q)}; + let index${de} = offset${de} / 4u; + let component${de} = offset${de} % 4u; + ${te}[${de}] = ${we}(${H.getByOffset(`index${de}`)}[component${de}]); + `;v=` + let outputOffset = global_idx * ${f}; + var data = vec4(0); + ${oe("data",0,"u32")} + ${oe("data",1,"u32")} + ${oe("data",2,"u32")} + ${oe("data",3,"u32")} + ${q.setByOffset("global_idx","data")} + }`}else v=` + let outputIndices = ${q.offsetToIndices("global_idx")}; + let inputOffset = ${H.broadcastedIndicesToOffset("outputIndices",q)}; + ${q.setByOffset("global_idx",H.getByOffset("inputOffset"))} + }`;return` + ${$.registerUniform("vec_size","u32").declareVariables(H,q)} + ${$.mainStart()} + ${$.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${v}`},k=[{type:12,data:d},...At(i,u)];return{name:"Expand",shaderCache:{hint:`${u.length}`,inputDependencies:["rank"]},getShaderSource:x,getRunData:()=>({outputs:[{dims:u,dataType:n[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:k})}},bl=n=>{vl(n.inputs),n.compute(Sd(n.inputs),{inputs:[0]})}}),yf,Ed,vf=h(()=>{Zt(),Jt(),ar(),Ha(),yf=n=>{let i=n[0].dataType,s=ct.size(n[0].dims),u=ct.size(n[1].dims),c=u%4===0,f=d=>{let x=_t("x",i,[1],4),k=_t("bias",i,[1],4),$=Gt("y",i,[1],4),H=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],q=oe=>` + let bias${oe}_offset: u32 = (global_idx * 4 + ${oe}) % uniforms.bias_size; + let bias${oe} = ${k.getByOffset(`bias${oe}_offset / 4`)}[bias${oe}_offset % 4];`,v=c?` + let bias = ${k.getByOffset("global_idx % (uniforms.bias_size / 4)")};`:`${q(0)}${q(1)}${q(2)}${q(3)} + let bias = ${x.type.value}(bias0, bias1, bias2, bias3);`;return`${d.registerUniforms(H).declareVariables(x,k,$)} + + ${Va(Er(i))} + + ${d.mainStart(Un)} + ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")} + + let x = ${x.getByOffset("global_idx")}; + ${v} + let x_in = x + bias; + ${$.setByOffset("global_idx",Wa("x_in"))} + }`};return{name:"FastGeluWithBias",shaderCache:{hint:`${c}`,inputDependencies:["type","type"]},getShaderSource:f,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/Un/4)}})}},Ed=n=>{n.inputs.length<2||ct.size(n.inputs[1].dims)===0?Ec(n):n.compute(yf(n.inputs))}}),Cd,Pd,$d,Ad,bf=h(()=>{Zt(),Jt(),_r(),ar(),Cd=n=>{if(!n||n.length!==2)throw new Error("Gather requires 2 inputs.")},Pd=(n,i)=>{let s=n[0].dims,u=n[1].dims,c=s.length,f=ct.normalizeAxis(i.axis,c),d=s.slice(0);d.splice(f,1,...u);let x=s[f],k=n[0].dataType===9?4:1,$=Math.ceil(ct.size(d)/k),H=[{type:12,data:$},{type:6,data:x},{type:12,data:f},...At(n[0].dims,n[1].dims,d)],q=v=>{let oe=_t("data",n[0].dataType,n[0].dims.length,k),te=_t("inputIndices",n[1].dataType,n[1].dims.length),de=Gt("output",n[0].dataType,d.length,k),we=he=>{let De=u.length,Ae=`var indicesIndices${he} = ${te.type.indices}(0);`;for(let Ie=0;Ie1?`indicesIndices${he}[${Ie}]`:`indicesIndices${he}`} = ${d.length>1?`outputIndices${he}[uniforms.axis + ${Ie}]`:`outputIndices${he}`};`;Ae+=` + var idx${he} = ${te.getByIndices(`indicesIndices${he}`)}; + if (idx${he} < 0) { + idx${he} = idx${he} + uniforms.axisDimLimit; + } + var dataIndices${he} : ${oe.type.indices}; + `;for(let Ie=0,gt=0;Ie1?`dataIndices${he}[${Ie}]`:`dataIndices${he}`} = u32(idx${he});`,gt+=De):(Ae+=`${c>1?`dataIndices${he}[${Ie}]`:`dataIndices${he}`} = ${d.length>1?`outputIndices${he}[${gt}]`:`outputIndices${he}`};`,gt++);return Ae},be;if(n[0].dataType===9){let he=(De,Ae,Ie="")=>` + let outputIndices${Ae} = ${de.offsetToIndices(`outputOffset + ${Ae}u`)}; + ${we(Ae)}; + let offset${Ae} = ${oe.indicesToOffset(`dataIndices${Ae}`)}; + let index${Ae} = offset${Ae} / 4u; + let component${Ae} = offset${Ae} % 4u; + ${De}[${Ae}] = ${Ie}(${oe.getByOffset(`index${Ae}`)}[component${Ae}]); + `;be=` + let outputOffset = global_idx * ${k}; + var value = vec4(0); + ${he("value",0,"u32")} + ${he("value",1,"u32")} + ${he("value",2,"u32")} + ${he("value",3,"u32")} + ${de.setByOffset("global_idx","value")} + `}else be=` + let outputIndices = ${de.offsetToIndices("global_idx")}; + ${we("")}; + let value = ${oe.getByIndices("dataIndices")}; + ${de.setByOffset("global_idx","value")}; + `;return` + ${v.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(oe,te,de)} + ${v.mainStart()} + ${v.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + ${be} + }`};return{name:"Gather",shaderCache:{hint:i.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:d,dataType:n[0].dataType}],dispatchGroup:{x:Math.ceil($/64)},programUniforms:H}),getShaderSource:q}},$d=n=>qt({axis:n.axis}),Ad=(n,i)=>{let s=n.inputs;Cd(s),n.compute(Pd(n.inputs,i))}}),Id,Fd,Od,zd,xf=h(()=>{Zt(),Jt(),_r(),ar(),Id=n=>{if(!n||n.length!==2)throw new Error("GatherElements requires 2 inputs.");if(n[0].dims.length<1)throw new Error("GatherElements requires that the data input be rank >= 1.");if(n[0].dims.length!==n[1].dims.length)throw new Error(`GatherElements requires that the data input and + indices input tensors be of same rank.`)},Fd=(n,i)=>{let s=n[0].dims,u=n[0].dataType,c=s.length,f=n[1].dims,d=n[1].dataType,x=ct.normalizeAxis(i.axis,c),k=s[x],$=f.slice(0),H=ct.size($),q=_t("input",u,c),v=_t("indicesInput",d,f.length),oe=Gt("output",u,$.length),te=[{type:12,data:H},{type:6,data:k},{type:12,data:x}];return te.push(...At(s,f,$)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:$,dataType:n[0].dataType}],dispatchGroup:{x:Math.ceil(H/64)},programUniforms:te}),getShaderSource:de=>` + ${de.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(q,v,oe)} + ${de.mainStart()} + ${de.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + + let outputIndices = ${oe.offsetToIndices("global_idx")}; + + var idx = ${v.getByOffset("global_idx")}; + if (idx < 0) { + idx = idx + uniforms.axisDimLimit; + } + var inputIndices = ${q.type.indices}(outputIndices); + ${q.indicesSet("inputIndices","uniforms.axis","u32(idx)")}; + let value = ${q.getByIndices("inputIndices")}; + + ${oe.setByOffset("global_idx","value")}; + }`}},Od=n=>qt({axis:n.axis}),zd=(n,i)=>{let s=n.inputs;Id(s),n.compute(Fd(n.inputs,i))}}),Dd,Ld,Rd,Mf,Bd=h(()=>{Zt(),Jt(),ar(),Dd=n=>{if(!n)throw new Error("Input is missing");if(n.length<2||n.length>3)throw new Error("Invaid input number.");if(n.length===3&&n[2].dims.length>2)throw new Error("Invalid input shape of C");if(n[0].dataType!==n[1].dataType||n.length===3&&n[0].dataType!==n[2].dataType)throw new Error("Input types are mismatched")},Ld=(n,i)=>{let s=n[0].dims.slice(),u=n[1].dims.slice(),[c,f,d]=Tr.getShapeOfGemmResult(s,i.transA,u,i.transB,n.length===3?n[2].dims:void 0),x=[c,f];if(!x)throw new Error("Can't use gemm on the given tensors");let k=ct.size(x),$=[{type:12,data:k},{type:12,data:c},{type:12,data:f},{type:12,data:d},{type:1,data:i.alpha},{type:1,data:i.beta}],H=["type","type"];n.length===3&&($.push(...At(n[2].dims)),H.push("rank")),$.push(...At(x));let q=v=>{let oe="";i.transA&&i.transB?oe="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":i.transA&&!i.transB?oe="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!i.transA&&i.transB?oe="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!i.transA&&!i.transB&&(oe="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let te=i.alpha===1?"":"value *= uniforms.alpha;",de=_t("a",n[0].dataType,n[0].dims),we=_t("b",n[1].dataType,n[1].dims),be=de.type.value,he=null,De=[de,we];n.length===3&&(he=_t("c",n[2].dataType,n[2].dims.length),De.push(he));let Ae=Gt("output",n[0].dataType,x.length);De.push(Ae);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(...De)} + + ${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++) { + ${oe} + } + + ${te} + ${he!=null?`let cOffset = ${he.broadcastedIndicesToOffset("vec2(m, n)",Ae)}; value += ${be}(uniforms.beta) * ${he.getByOffset("cOffset")};`:""} + output[global_idx] = value; + }`};return{name:"Gemm",shaderCache:{hint:`${i.cacheKey}`,inputDependencies:H},getRunData:()=>({outputs:[{dims:x,dataType:n[0].dataType}],dispatchGroup:{x:Math.ceil(k/64)},programUniforms:$}),getShaderSource:q}},Rd=n=>{let i=n.transA,s=n.transB,u=n.alpha,c=n.beta;return{transA:i,transB:s,alpha:u,beta:c,cacheKey:`${n.transA};${n.transB};${n.alpha===1}`}},Mf=(n,i)=>{Dd(n.inputs),n.compute(Ld(n.inputs,i))}}),Pn,Nd,jd,xl,Ud,Zo,Vd,Wd=h(()=>{Zt(),Jt(),_r(),pe(),zs(),ar(),yo(),Pn=(n,i)=>n.length>i&&n[i].dims.length>0&&ct.size(n[i].dims)>0?n[i]:void 0,Nd=(n,i)=>{let s=n[0],u=Pn(n,1),c=Pn(n,2),f=Pn(n,3),d=Pn(n,4),x=Pn(n,5),k=Pn(n,6),$=Pn(n,7);if(s.dims.length!==3&&s.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let H=!1,q=s.dims[0],v=s.dims[1],oe=s.dims.length===3?H?s.dims[2]/3:s.dims[2]:i.numHeads*s.dims[4],te=v,de=0,we=0,be=Math.floor(oe/i.numHeads);if(k&&$){if(k.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(k.dims[0]!==q||k.dims[1]!==i.numHeads||k.dims[3]!==be)throw new Error('Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)');if($.dims[0]!==q||$.dims[1]!==i.numHeads||$.dims[3]!==be)throw new Error('Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)');if(k.dims[2]!==$.dims[2])throw new Error('Input "past_key" and "past_value" shall have same dim 2 (past_sequence_length)');if($.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');de=k.dims[2],we=k.dims[2]}else if(k||$)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(u.dims[2]!==s.dims[2])throw new Error('Input "query" and "key" shall have same dim 2 (hidden_size)');he=2,te=u.dims[1]}else if(u.dims.length===5){if(u.dims[2]!==i.numHeads||u.dims[3]!==2||u.dims[4]!==be)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,te=u.dims[1]}else{if(u.dims[1]!==i.numHeads||u.dims[3]!==be)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');he=0,te=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}if(f){if(f.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimension');if(c&&s.dims.length===5&&s.dims[3]===2)throw new Error("bias is not allowed for packed kv.")}let De=0;if(d){De=8;let vt=d.dims;throw vt.length===1?vt[0]===q?De=1:vt[0]===3*q+2&&(De=3):vt.length===2&&vt[0]===q&&vt[1]===te&&(De=5),De===8?new Error('Input "key_padding_mask" shape shall be (batch_size) or (batch_size, kv_sequence_length)'):new Error("Mask not supported")}let Ae=!1,Ie=oe;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(te!==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(te!==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],Ae=!0}}let gt=de+te,ut=!1;if(d)throw new Error("Key padding mask is not supported");if(x){if(x.dims.length!==4)throw new Error('Input "relative_position_bias" is expected to have 4 dimensions');if(x.dims[0]!==q&&x.dims[0]!==1||x.dims[1]!==i.numHeads||x.dims[2]!==v||x.dims[3]!==gt)throw new Error('Input "relative_position_bias" shape (batch_size, 1, sequence_length, kv_sequence_length)')}return{batchSize:q,sequenceLength:v,pastSequenceLength:de,kvSequenceLength:te,totalSequenceLength:gt,maxSequenceLength:we,inputHiddenSize:0,hiddenSize:oe,vHiddenSize:Ie,headSize:be,vHeadSize:Math.floor(Ie/i.numHeads),numHeads:i.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:i.maskFilterValue,maskType:De,scale:i.scale,broadcastResPosBias:ut,passPastInKv:Ae,qkvFormat:he}},jd=n=>qt({...n}),xl=qt({perm:[0,2,1,3]}),Ud=(n,i,s,u,c,f,d)=>{let x=[u,c,f],k=ct.size(x),$=[{type:12,data:k},{type:12,data:d},{type:12,data:f}],H=q=>{let v=Gt("qkv_with_bias",i.dataType,x),oe=_t("qkv",i.dataType,x),te=_t("bias",s.dataType,x),de=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return` + ${q.registerUniforms(de).declareVariables(oe,te,v)} + ${q.mainStart()} + ${q.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 n.compute({name:"MultiHeadAttentionAddBias",shaderCache:{inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:x,dataType:i.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(k/64)},programUniforms:$}),getShaderSource:H},{inputs:[i,s],outputs:[-1]})[0]},Zo=(n,i,s,u,c,f,d,x)=>{let k=f;if(d){if(u===1)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return k=Ud(n,f,d,i,u,s*c,x),k=k.reshape([i,u,s,c]),n.compute(hi(k,xl.perm),{inputs:[k],outputs:[-1]})[0]}else return f.dims.length===3&&(k=f.reshape([i,u,s,c])),n.compute(hi(k,xl.perm),{inputs:[k],outputs:[-1]})[0]},Vd=(n,i)=>{let s=Nd(n.inputs,i),u=n.inputs[0],c=Pn(n.inputs,1),f=Pn(n.inputs,2),d=Pn(n.inputs,3),x=Pn(n.inputs,4),k=Pn(n.inputs,5),$=Pn(n.inputs,6),H=Pn(n.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 q=c&&f&&c.dims.length===4&&f.dims.length===4,v=Zo(n,s.batchSize,s.numHeads,s.sequenceLength,s.headSize,u,d,0);if(q)return vo(n,v,c,f,x,void 0,$,H,k,s,i);if(!c||!f)throw new Error("key and value must be provided");let oe=Zo(n,s.batchSize,s.numHeads,s.kvSequenceLength,s.headSize,c,d,s.hiddenSize),te=Zo(n,s.batchSize,s.numHeads,s.kvSequenceLength,s.vHeadSize,f,d,2*s.hiddenSize);vo(n,v,oe,te,x,void 0,$,H,k,s,i)}}),Ml,Gd,Hd,Tl,qd,Kd=h(()=>{Zt(),Jt(),ar(),Ml=n=>Array.from(n.getBigInt64Array(),Number),Gd=n=>{if(!n||n.length!==2)throw new Error("Tile requires 2 inputs.");if(n[0].dataType!==1&&n[0].dataType!==10&&n[0].dataType!==6&&n[0].dataType!==12)throw new Error("Tile only support float, float16, int32, and uint32 data types");if(n[1].dataType!==7)throw new Error("Tile `repeats` input should be of int64 data type");if(n[1].dims.length!==1)throw new Error("Tile `repeats` input should be 1-D");if(Ml(n[1]).length!==n[0].dims.length)throw new Error("Tile `repeats` input should have same number of elements as rank of input data tensor")},Hd=(n,i)=>{let s=[];for(let u=0;u{let s=n[0].dims,u=i??Ml(n[1]),c=Hd(s,u),f=ct.size(c),d=n[0].dataType,x=_t("input",d,s.length),k=Gt("output",d,c.length),$=H=>` + const inputShape = ${x.indices(...s)}; + ${H.registerUniform("output_size","u32").declareVariables(x,k)} + ${H.mainStart()} + ${H.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let output_indices = ${k.offsetToIndices("global_idx")}; + var input_indices: ${x.type.indices}; + for (var i = 0; i < ${s.length}; i++) { + let input_dim_i = ${x.indicesGet("uniforms.input_shape","i")}; + let input_dim_value = ${k.indicesGet("output_indices","i")} % input_dim_i; + + ${x.indicesSet("input_indices","i","input_dim_value")} + } + ${k.setByOffset("global_idx",x.getByIndices("input_indices"))} + }`;return{name:"Tile",shaderCache:{hint:`${u}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:c,dataType:n[0].dataType}],dispatchGroup:{x:Math.ceil(f/64)},programUniforms:[{type:12,data:f},...At(n[0].dims,c)]}),getShaderSource:$}},qd=n=>{Gd(n.inputs),n.compute(Tl(n.inputs),{inputs:[0]})}}),Xd,kl,Qd,Yd,Sl,Zd,Tf=h(()=>{Zt(),Jt(),_r(),zs(),ar(),Wd(),Kd(),yo(),Xd=(n,i)=>{let s=n[0],u=n[1],c=n[2],f=n[3],d=n[4];if(s.dims.length!==3&&s.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let x=!1,k=s.dims[0],$=s.dims[1],H=s.dims.length===3?x?s.dims[2]/3:s.dims[2]:i.numHeads*s.dims[4],q=$,v=0,oe=0,te=Math.floor(H/i.numHeads),de=f&&f.dims.length!==0,we=d&&d.dims.length!==0,be=!0;if(de&&we){if(f.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=f.dims[1],oe=f.dims[1]}else if(de||we)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,q=u.dims[1]}else if(u.dims.length===5){if(u.dims[2]!==i.numHeads||u.dims[3]!==2||u.dims[4]!==te)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,q=u.dims[1]}else{if(u.dims[1]!==i.numHeads||u.dims[3]!==te)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');he=0,q=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 De=0,Ae=!1,Ie=H;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(q!==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(q!==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],Ae=!0}}let gt=v+q;return{batchSize:k,sequenceLength:$,pastSequenceLength:v,kvSequenceLength:q,totalSequenceLength:gt,maxSequenceLength:oe,inputHiddenSize:0,hiddenSize:H,vHiddenSize:Ie,headSize:te,vHeadSize:Math.floor(Ie/i.kvNumHeads),numHeads:i.numHeads,kvNumHeads:i.kvNumHeads,nReps:i.numHeads/i.kvNumHeads,pastPresentShareBuffer:!1,maskType:De,scale:i.scale,broadcastResPosBias:!1,passPastInKv:Ae,qkvFormat:he,isPastkvBSNH:be}},kl=(n,i,s,u)=>{let c=[u.batchSize,u.totalSequenceLength,u.kvNumHeads,u.headSize],f=4,d=ct.size(c)/f,x=u.totalSequenceLength,k=Gt("present_kv",s,c.length,f),$=_t("new_kv",n.dataType,n.dims.length,f),H=i?_t("past_kv",i.dataType,i.dims.length,f):void 0,q=Math.ceil(u.headSize/f),v={x,y:n.dims[0],z:1},oe=i?["rank","rank"]:["rank"],te=[{type:12,data:d},{type:12,data:u.pastSequenceLength},{type:12,data:u.kvSequenceLength},{type:12,data:u.totalSequenceLength}],de=[$];H?(te.push(...At(n.dims),...At(i.dims),...At(c)),de.push(H)):te.push(...At(n.dims),...At(c));let we=[{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];`,De=i?`if (s < past_seqlen) { + ${be} + } else if (s < past_seqlen + uniforms.new_seqlen) { + ${he} + }`:`if (s < past_seqlen + uniforms.new_seqlen) { + ${he} + }`,Ae=Ie=>` + + ${Ie.registerUniforms(we).declareVariables(...de,k)} + ${Ie.mainStart([q,u.kvNumHeads,1])} + ${Ie.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + var indices = ${k.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 = ${q}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; + ${De} + }`;return{name:"ConcatPastNew",shaderCache:{hint:`${u.kvNumHeads}${q}${!!i}`,inputDependencies:oe},getRunData:()=>({outputs:[{dims:c,dataType:s}],dispatchGroup:v,programUniforms:te}),getShaderSource:Ae}},Qd=n=>qt({...n}),Yd=qt({perm:[0,2,1,3]}),Sl=(n,i,s,u,c)=>{let f=i,d=u.kvNumHeads,x=u.nReps;return i.dims.length===3&&u.kvSequenceLength!==0&&(f=i.reshape([u.batchSize,u.kvSequenceLength,d,u.headSize])),s?f=n.compute(kl(f,s,f.dataType,u),{inputs:[f,s],outputs:[u.isPastkvBSNH?c:-1]})[0]:f=n.compute(kl(f,void 0,f.dataType,u),{inputs:[f],outputs:[u.isPastkvBSNH?c:-1]})[0],x!==1&&(f=n.compute(Tl([f],[1,1,1,x]),{inputs:[f],outputs:[-1]})[0],f=f.reshape([u.batchSize,u.totalSequenceLength,d*x,u.headSize])),n.compute(hi(f,Yd.perm),{inputs:[f],outputs:[-1]})[0]},Zd=(n,i)=>{var k;let s=Xd(n.inputs,i);if(n.inputs[0].dims.length===5)throw new Error("Packed QKV is not implemented");if(((k=n.inputs[1])==null?void 0:k.dims.length)===5)throw new Error("Packed KV is not implemented");let u=Zo(n,s.batchSize,s.numHeads,s.sequenceLength,s.headSize,n.inputs[0],void 0,0),c=n.inputs[3]&&n.inputs[3].dims.length!==0?n.inputs[3]:void 0,f=n.inputs[4]&&n.inputs[4].dims.length!==0?n.inputs[4]:void 0,d=Sl(n,n.inputs[1],c,s,1),x=Sl(n,n.inputs[2],f,s,2);vo(n,u,d,x,void 0,void 0,void 0,void 0,void 0,s,i)}}),Jd,ep,tp,rp,wm=h(()=>{Zt(),Jt(),ar(),Jd=(n,i)=>{let s=n[0].dims,u=s,c=2,f=ct.sizeToDimension(s,c),d=ct.sizeFromDimension(s,c),x=vr(d),k=d/x,$=[s[0],s[1],k],H=["rank","type","type"],q=[{type:12,data:d},{type:12,data:k}];q.push(...At($,$));let v=oe=>{let te=_t("x",n[0].dataType,$.length,x),de=_t("scale",n[1].dataType,n[1].dims),we=_t("bias",n[2].dataType,n[2].dims),be=Gt("output",n[0].dataType,$.length,x),he=[te,de,we,be],De=te.type.value,Ae=x===1?"f32":`vec${x}`,Ie=64,gt=[{name:"normSize",type:"u32"},{name:"normPackedSize",type:"u32"}];return` + var meanShared : f32; + var squaredNormShared : f32; + var workgroupShared : array<${Ae}, ${Ie}>; + const workgroupSize = ${Ie}u; + ${oe.registerUniforms(gt).declareVariables(...he)} + ${oe.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 = ${Ae}(0); + for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) { + initial = initial + ${Ae}(${te.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 = ${Vn("workgroupShared[0]",x)} / f32(uniforms.normSize); + } + workgroupBarrier(); + + // reinitialize workgroup memory. + initial = ${Ae}(0); + for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) { + let deviation = ${Ae}(${te.get("batch","channel","h")}) - ${Ae}(meanShared); + initial = initial + deviation * deviation; + } + workgroupShared[localIndex] = initial; + workgroupBarrier(); + + // Calculate the sum of square of deviation of current channel data. + for (var currSize = workgroupSize >> 1; currSize > 0; currSize = currSize >> 1) { + if (localIndex < currSize) { + workgroupShared[localIndex] = workgroupShared[localIndex] + workgroupShared[localIndex + currSize]; + } + workgroupBarrier(); + } + if (localIndex == 0) { + squaredNormShared = ${Vn("workgroupShared[0]",x)}; + } + workgroupBarrier(); + + let invStdDev = inverseSqrt(squaredNormShared / f32(uniforms.normSize) + f32(${i.epsilon})); + let channelScale = invStdDev * f32(${de.getByOffset("channel")}); + let channelShift = f32(${we.getByOffset("channel")}) - meanShared * channelScale; + for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) { + let value = ${te.get("batch","channel","h")} * ${De}(${Ae}(channelScale)) + ${De}(${Ae}(channelShift)); + ${be.set("batch","channel","h","value")}; + } + }`};return{name:"InstanceNormalization",shaderCache:{hint:`${i.epsilon};${x}`,inputDependencies:H},getRunData:()=>({outputs:[{dims:u,dataType:n[0].dataType}],dispatchGroup:{x:f},programUniforms:q}),getShaderSource:v}},ep=(n,i,s,u,c,f,d,x)=>{let k=vr(d),$=64,H=k===1?"vec2f":`mat2x${k}f`,q=k===1?"f32":`vec${k}f`,v=(gt,ut)=>`${H}(${gt}, ${ut})`,oe=c*d/k,te=Math.ceil(f/$),de=["type"],we=[{type:12,data:te},{type:12,data:f},{type:12,data:Math.floor(d/k)},{type:12,data:Math.floor(f*d/k)}],be=gt=>{let ut=_t("input",i.dataType,i.dims,k);return` + ${gt.declareVariables(ut)} + @group(0) @binding(1) var output : array<${H}>; + struct Uniforms {wg_size:u32, H:u32, C:u32, image_size:u32}; + @group(0) @binding(2) var uniforms: Uniforms; + + ${gt.mainStart($)} + let currentImageNumber = global_idx / ${$} / uniforms.C; + let currentChannelNumber = (global_idx / ${$}) % 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 = ${Lr("f32",k)}; + var squaredSum = ${Lr("f32",k)}; + for (var i: u32 = wgOffset; i < wgMax; i++) { + let value = ${q}(input[offset + i * uniforms.C]); + sum += value; + squaredSum += value * value; + } + output[global_idx] = ${v("sum","squaredSum")}; + }`},he=n.compute({name:"InstanceNormComputeMean",shaderCache:{hint:`${k}`,inputDependencies:de},getRunData:()=>({outputs:[{dims:[c,d,$,2],dataType:1}],dispatchGroup:{x:c*d/k},programUniforms:we}),getShaderSource:be},{inputs:[i],outputs:[-1]})[0],De=[{type:12,data:oe},{type:12,data:f},{type:12,data:Math.floor(d/k)},{type:12,data:Math.floor($*d/k)}],Ae=["type","type","type"],Ie=gt=>{let ut=_t("scale",s.dataType,s.dims,k),vt=_t("bias",u.dataType,u.dims,k);return` + @group(0) @binding(0) var input : array<${H}>; + @group(0) @binding(1) var scale : array<${ut.type.storage}>; + @group(0) @binding(2) var bias : array<${vt.type.storage}>; + @group(0) @binding(3) var output : array<${H}>; + struct Uniforms {units_of_work : u32, H: u32, C : u32, image_size : u32}; + @group(0) @binding(4) var uniforms: Uniforms; + + ${gt.mainStart()} + ${gt.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 = ${Lr("f32",k)}; + var squaredSum = ${Lr("f32",k)}; + for (var i: u32 = 0; i < min(${$}, uniforms.H); i++) { + let value = input[offset + i + currentChannelNumber * ${$}]; + sum += value[0]; + squaredSum += value[1]; + } + sum = sum / f32(uniforms.H); + squaredSum = squaredSum / f32(uniforms.H); + let invStdDev = inverseSqrt(squaredSum - sum * sum + f32(${x})); + let channelScale = invStdDev * ${q}(scale[currentChannelNumber]); + let channelShift = ${q}(bias[currentChannelNumber]) - sum * channelScale; + + output[global_idx] = ${v("channelScale","channelShift")}; + }`};return n.compute({name:"InstanceNormComputeChannelScaleShift",shaderCache:{hint:`${k};${x}`,inputDependencies:Ae},getRunData:()=>({outputs:[{dims:[c,d,2],dataType:1}],dispatchGroup:{x:Math.ceil(oe/64)},programUniforms:De}),getShaderSource:Ie},{inputs:[he,s,u],outputs:[-1]})[0]},tp=(n,i,s)=>{let u=i[0].dims,c=u,f=u[0],d=u[u.length-1],x=ct.sizeFromDimension(u,1)/d,k=vr(d),$=ct.size(c)/k,H=[{type:12,data:x},{type:12,data:Math.floor(d/k)}],q=["type","type"],v=ep(n,i[0],i[1],i[2],f,x,d,s.epsilon),oe=te=>{let de=Sr(i[0].dataType),we=k===1?"vec2f":`mat2x${k}f`,be=k===1?de:`vec${k}<${de}>`,he=_t("input",i[0].dataType,i[0].dims,k),De=Gt("output",i[0].dataType,c,k);return` + @group(0) @binding(0) var input : array<${he.type.storage}>; + @group(0) @binding(1) var scaleInput : array<${we}>; + @group(0) @binding(2) var output : array<${De.type.storage}>; + struct Uniforms {H: u32, C : u32}; + @group(0) @binding(3) var uniforms: Uniforms; + + ${te.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])); + }`};n.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${k}`,inputDependencies:q},getRunData:()=>({outputs:[{dims:c,dataType:i[0].dataType}],dispatchGroup:{x:Math.ceil($/64)},programUniforms:H}),getShaderSource:oe},{inputs:[i[0],v]})},rp=(n,i)=>{i.format==="NHWC"?tp(n,n.inputs,i):n.compute(Jd(n.inputs,i))}}),ur,np,hn,bn=h(()=>{Zt(),Jt(),ar(),ur=n=>{if(!n||n.length<2)throw new Error("layerNorm requires at least 2 inputs.")},np=(n,i,s)=>{let u=i.simplified,c=n[0].dims,f=n[1],d=!u&&n[2],x=c,k=ct.normalizeAxis(i.axis,c.length),$=ct.sizeToDimension(c,k),H=ct.sizeFromDimension(c,k),q=ct.size(f.dims),v=d?ct.size(d.dims):0;if(q!==H||d&&v!==H)throw new Error(`Size of X.shape()[axis:] == ${H}. + Size of scale and bias (if provided) must match this. + Got scale size of ${q} and bias size of ${v}`);let oe=[];for(let Ie=0;Ie1,he=s>2,De=Ie=>{let gt=Sr(n[0].dataType),ut=[_t("x",n[0].dataType,n[0].dims,te),_t("scale",f.dataType,f.dims,te)];d&&ut.push(_t("bias",d.dataType,d.dims,te)),ut.push(Gt("output",n[0].dataType,x,te)),be&&ut.push(Gt("mean_data_output",1,oe)),he&&ut.push(Gt("inv_std_output",1,oe));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(...ut)} + ${Ie.mainStart()} + ${Ie.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")} + let offset = global_idx * uniforms.norm_size_vectorized; + var mean_vector = ${Lr("f32",te)}; + var mean_square_vector = ${Lr("f32",te)}; + + for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) { + let value = ${Xr(gt,te,"x[h + offset]")}; + mean_vector += value; + mean_square_vector += value * value; + } + let mean = ${Vn("mean_vector",te)} / uniforms.norm_size; + let inv_std_dev = inverseSqrt(${Vn("mean_square_vector",te)} / uniforms.norm_size ${u?"":"- mean * mean"} + uniforms.epsilon); + + for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) { + let f32input = ${Xr(gt,te,"x[j + offset]")}; + let f32scale = ${Xr(gt,te,"scale[j]")}; + output[j + offset] = ${ut[0].type.value}((f32input ${u?"":"- mean"}) * inv_std_dev * f32scale + ${d?`+ ${Xr(gt,te,"bias[j]")}`:""} + ); + } + + ${be?"mean_data_output[global_idx] = mean":""}; + ${he?"inv_std_output[global_idx] = inv_std_dev":""}; + }`},Ae=[{dims:x,dataType:n[0].dataType}];return be&&Ae.push({dims:oe,dataType:1}),he&&Ae.push({dims:oe,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${te};${s};${u}`,inputDependencies:de},getRunData:()=>({outputs:Ae,dispatchGroup:{x:Math.ceil($/64)},programUniforms:we}),getShaderSource:De}},hn=(n,i)=>{ur(n.inputs),n.compute(np(n.inputs,i,n.outputCount))}}),xn,to,kf,ip,Sf=h(()=>{Zt(),Jt(),_r(),ar(),xn=(n,i)=>{if(n.length<3||n.length>4)throw new Error("MatMulNBits requires 3 or 4 inputs");let s=n[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),f=i.blockSize/8*i.bits,d=n[1];if(!ct.areEqual(d.dims,[i.n,c,f]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let x=n[2].dims;if(ct.size(x)!==i.n*c)throw new Error("scales input size error.");if(n.length===4){let k=n[3].dims,$=i.bits>4?i.n*c:i.n*Math.floor((c+1)/2);if(ct.size(k)!==$)throw new Error("zeroPoints input size error.")}},to=(n,i,s,u)=>{let c=n[0].dims,f=c.length,d=Math.floor((i.k+i.blockSize-1)/i.blockSize),x=c[f-2],k=i.k,$=i.n,H=c.slice(0,f-2),q=ct.size(H),v=i.blockSize/8*i.bits/4,oe=n[0].dataType,te=vr(x),de=vr(i.k),we=vr(v),be=ki(oe),he=x*d*be,De=Math.floor(u/he),Ae=d<=s[0]&&De>0,Ie=!Ae||De>=4?vr($):De>=2&&vr($)>=2?2:1,gt=H.concat([x,$]),ut=ct.size(gt)/Ie/te,vt=Ae?[]:[{type:12,data:ut},{type:12,data:i.blockSize}],Dt=[q,x,k/de],Rt=ct.convertShape(n[1].dims).slice();Rt.splice(-1,1,v/we),vt.push(...At(Dt)),vt.push(...At(Rt)),vt.push(...At(n[2].dims)),n.length===4&&vt.push(...At(ct.convertShape(n[3].dims)));let gr=[q,x,$/Ie];vt.push(...At(gr));let Mr=ir=>{let Fr=Dt.length,Zr=_t("a",n[0].dataType,Fr,de),hr=_t("b",12,Rt.length,we),Hr=_t("scales",n[2].dataType,n[2].dims.length),Nt=[Zr,hr,Hr],er=n.length===4?_t("zero_points",12,n[3].dims.length):void 0;er&&Nt.push(er);let yr=gr.length,ot=Gt("output",n[0].dataType,yr,Ie),Vt=[{name:"output_size",type:"u32"},{name:"block_size",type:"u32"}],nr=Sr(n[0].dataType),Wr=(()=>{switch(de){case 1:return`array<${nr}, 8>`;case 2:return`mat4x2<${nr}>`;case 4:return`mat2x4<${nr}>`;default:throw new Error(`${de}-component is not supported.`)}})(),pn=` + for (var word: u32 = 0; word < ${v}; word += ${we}) { + ${hr.indicesSet("b_indices","2","word")}; + let b_data = ${hr.getByIndices("b_indices")}; + for (var i: u32 = 0; i < ${we}; i++) { + let b_value: u32 = ${we===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 = ${Wr}(${Array.from({length:4},(rs,si)=>`${nr}(b_value_lower[${si}]), ${nr}(b_value_upper[${si}])`).join(", ")}); + let b_dequantized_values = ${de===1?`${Wr}(${Array.from({length:8},(rs,si)=>`(b_quantized_values[${si}] - zero_point) * scale`).join(", ")});`:`(b_quantized_values - ${Wr}(${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 < ${Ae?x:te}u; m++) { + ${Zr.indicesSet("a_indices",Fr-2,Ae?"m":`row * ${te} + m`)}; + ${Zr.indicesSet("a_indices",Fr-1,"word_offset")}; + var input_offset = ${Zr.indicesToOffset("a_indices")}; + var a_data: ${Wr}; + for (var j: u32 = 0; j < ${8/de}; j++) { + a_data[j] = ${Zr.getByOffset("input_offset")}; + input_offset++; + } + ${Ae?"workgroup_shared[workgroup_shared_offset + m]":"output_values[m]"}${Ie>1?"[c]":""} += ${Array.from({length:8/de},(rs,si)=>`${de===1?`a_data[${si}] * b_dequantized_values[${si}]`:`dot(a_data[${si}], b_dequantized_values[${si}])`}`).join(" + ")}; + } + word_offset += ${8/de}; + } + }`,kn=er?` + zero_point_offset += 4; + if (zero_point_offset == 32) { + zero_point_offset = 0; + zero_point_index++; + zero_point_word = ${er.getByOffset("zero_point_index")}; + }`:"";return Ae?` + var workgroup_shared: array<${ot.type.value}, ${x*d}>; + ${ir.declareVariables(...Nt,ot)} + ${ir.mainStart([d,1,1])} + var a_indices: ${Zr.type.indices}; + var block = local_id.x; + var col = workgroup_id.y; + var batch = workgroup_id.z; + ${Zr.indicesSet("a_indices","0","batch")}; + // Two zero points are packed into one byte when uniforms.bits is 4. + for (var c: u32 = 0; c < ${Ie}; c++) { + let col_times_components_plus_c = col * ${Ie} + c; + ${er?` + 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 = ${er.getByOffset("zero_point_word_index")} >> zero_point_bits_offset;`:""} + var b_indices: ${hr.type.indices}; + ${hr.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 = ${Hr.getByOffset("scales_index")}; + // The default zero point is 8 for unsigned 4-bit quantization. + let zero_point = ${nr}(${er?"(zero_point_word) & 0xFu":8}); + ${hr.indicesSet("b_indices","1","block")}; + var word_offset: u32 = block * ${i.blockSize/de}; + var workgroup_shared_offset: u32 = block * ${x}; + ${pn} + } + workgroupBarrier(); + var output_indices: ${ot.type.indices}; + var elements_per_thread: u32 = ${Math.ceil(x/d)}; + ${ot.indicesSet("output_indices","0","batch")}; + ${ot.indicesSet("output_indices",yr-1,"col")}; + ${ot.indicesSet("output_indices",yr-2,"local_id.x * elements_per_thread")}; + var output_offset = ${ot.indicesToOffset("output_indices")}; + for (var m: u32 = 0u; m < elements_per_thread; m++) { + var row = m + local_id.x * elements_per_thread; + if (row < ${x}) { + var output_value: ${ot.type.value} = ${ot.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 += ${x}; + } + ${ot.setByOffset("output_offset","output_value")}; + output_offset += ${$/Ie}; + } + } + }`:` + ${ir.registerUniforms(Vt).declareVariables(...Nt,ot)} + ${ir.mainStart()} + ${ir.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + var output_values: array<${ot.type.value}, ${te}>; + var output_indices = ${ot.offsetToIndices("global_idx")}; + var col = ${ot.indicesGet("output_indices",yr-1)}; + var row = ${ot.indicesGet("output_indices",yr-2)}; + var a_indices: ${Zr.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 + ${er?` + var zero_point_abs_offset = col * ${Ie} * ((${d} + 1) / 2); + var zero_point_index: u32 = zero_point_abs_offset / 4; + var zero_point_word: u32 = ${er.getByOffset("zero_point_index")}; + var zero_point_offset: u32 = (zero_point_abs_offset % 4) * 8;`:""} + var scale_index = col * ${d*Ie}; + var b_indices: ${hr.type.indices}; + for (var c: u32 = 0; c < ${Ie}; c++) { + ${hr.indicesSet("b_indices","0",`col * ${Ie} + 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 = ${Hr.getByOffset("scale_index")}; + // The default zero point is 8 for unsigned 4-bit quantization. + let zero_point = ${nr}(${er?"extractBits(zero_point_word, zero_point_offset, 4)":8}); + ${hr.indicesSet("b_indices","1","block")}; + var word_offset: u32 = block_offset; + ${pn} + scale_index++; + ${kn} + block_offset += uniforms.block_size / ${de}; + } + // Drop the trailing 4 bits if the zero_poit_offset is not a byte boundary to align with the next byte. + ${er?`if (zero_point_offset % 8 > 0) { + ${kn} + }`:""} + } + for (var k: u32 = 0u; k < ${te}u; k++) { + ${ot.indicesSet("output_indices",yr-2,`${te} * row + k`)}; + ${ot.setByIndices("output_indices","output_values[k]")} + } + }`};return{name:Ae?"BlockwiseMatMulNBits":"MatMulNBits",shaderCache:{hint:`${i.cacheKey};${x};${oe};${n.length}`,inputDependencies:Array(n.length).fill("rank")},getRunData:()=>({outputs:[{dims:gt,dataType:oe}],name:Ae?"BlockwiseMatMulNBits":"MatMulNBits",dispatchGroup:Ae?{x:1,y:Math.ceil($/Ie),z:q}:{x:Math.ceil(ut/64)},programUniforms:vt}),getShaderSource:Mr}},kf=(n,i)=>{xn(n.inputs,i);let s=n.getMaxComputeWorkgroupSizes(),u=n.getMaxComputeWorkgroupStoragesize();n.compute(to(n.inputs,i,s,u))},ip=n=>qt(n)}),V,G,ne,Ee,Ze,it,wt,Ct,Wt,cr=h(()=>{Zt(),Jt(),ar(),V=n=>{if(!n||n.length<1)throw new Error("Too few inputs");if(n[0].dataType!==1&&n[0].dataType!==10)throw new Error("Input type must be float or float16.");if(n.length>=2){let i=n[0].dims.length*2===n[1].dims[0];if(n.length===4&&(i=n[3].dims[0]*2===n[1].dims[0]),!i)throw new Error("The pads should be a 1D tensor of shape [2 * input_rank] or [2 * num_axes].")}},G=(n,i,s)=>{let u="";for(let c=i-1;c>=0;--c)u+=` + k = i32(${n.indicesGet("indices",c)}) - ${zt("uniforms.pads",c,s)}; + if (k < 0) { + break; + } + if (k >= i32(${zt("uniforms.x_shape",c,i)})) { + break; + } + offset += k * i32(${zt("uniforms.x_strides",c,i)}); + `;return` + value = ${n.type.value}(uniforms.constant_value); + for (var i = 0; i < 1; i++) { + var offset = 0; + var k = 0; + ${u} + value = x[offset]; + } + `},ne=(n,i,s)=>{let u="";for(let c=i-1;c>=0;--c)u+=` + k = i32(${n.indicesGet("indices",c)}) - ${zt("uniforms.pads",c,s)}; + if (k < 0) { + k = -k; + } + { + let _2n_1 = 2 * (i32(${zt("uniforms.x_shape",c,i)}) - 1); + k = k % _2n_1; + if(k >= i32(${zt("uniforms.x_shape",c,i)})) { + k = _2n_1 - k; + } + } + offset += k * i32(${zt("uniforms.x_strides",c,i)}); + `;return` + var offset = 0; + var k = 0; + ${u} + value = x[offset]; + `},Ee=(n,i,s)=>{let u="";for(let c=i-1;c>=0;--c)u+=` + k = i32(${n.indicesGet("indices",c)}) - ${zt("uniforms.pads",c,s)}; + if (k < 0) { + k = 0; + } + if (k >= i32(${zt("uniforms.x_shape",c,i)})) { + k = i32(${zt("uniforms.x_shape",c,i)}) - 1; + } + offset += k * i32(${zt("uniforms.x_strides",c,i)}); + `;return` + var offset = 0; + var k = 0; + ${u} + value = x[offset]; + `},Ze=(n,i,s)=>{let u="";for(let c=i-1;c>=0;--c)u+=` + k = i32(${n.indicesGet("indices",c)}) - ${zt("uniforms.pads",c,s)}; + if (k < 0) { + k += i32(${zt("uniforms.x_shape",c,i)}]); + } + if (k >= i32(${zt("uniforms.x_shape",c,i)})) { + k -= i32(${zt("uniforms.x_shape",c,i)}); + } + offset += k * i32(${zt("uniforms.x_strides",c,i)}); + `;return` + var offset = 0; + var k = 0; + ${u} + value = x[offset]; + `},it=(n,i,s)=>{switch(s.mode){case 0:return G(n,i,s.pads.length);case 1:return ne(n,i,s.pads.length);case 2:return Ee(n,i,s.pads.length);case 3:return Ze(n,i,s.pads.length);default:throw new Error("Invalid mode")}},wt=(n,i)=>{let s=ct.padShape(n[0].dims.slice(),i.pads),u=n[0].dims,c=ct.size(s),f=[{type:12,data:c},{type:6,data:i.pads}];i.mode===0&&f.push({type:n[0].dataType,data:i.value}),f.push(...At(n[0].dims,s));let d=["rank"],x=k=>{let $=Gt("output",n[0].dataType,s.length),H=_t("x",n[0].dataType,u.length),q=H.type.value,v=it($,u.length,i),oe=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:i.pads.length}];return i.mode===0&&oe.push({name:"constant_value",type:q}),` + ${k.registerUniforms(oe).declareVariables(H,$)} + ${k.mainStart()} + ${k.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${$.offsetToIndices("global_idx")}; + + var value = ${q}(0); + ${v} + output[global_idx] = value; + }`};return{name:"Pad",shaderCache:{hint:`${i.mode}`,inputDependencies:d},getRunData:()=>({outputs:[{dims:s,dataType:n[0].dataType}],dispatchGroup:{x:Math.ceil(ct.size(s)/64)},programUniforms:f}),getShaderSource:x}},Ct=(n,i)=>{if(n.length>1){let s=n[1].getBigInt64Array(),u=n.length>=3&&n[2].data?n[2].getFloat32Array()[0]:0,c=n[0].dims.length,f=new Int32Array(2*c).fill(0);if(n.length>=4){let x=n[3].getBigInt64Array();for(let k=0;kf[Number(k)]=Number(x));let d=[];return f.forEach(x=>d.push(x)),{mode:i.mode,value:u,pads:d}}else return i},Wt=(n,i)=>{V(n.inputs);let s=Ct(n.inputs,i);n.compute(wt(n.inputs,s),{inputs:[0]})}}),lr,Ir,dr,wr,pr,mr,xr,Nr,$n,zn,Pi,Mn,dn,Tn,qs,Ks,El,ym,mi,Jo=h(()=>{Z(),Zt(),Jt(),ar(),lr=n=>{if(N.webgpu.validateInputContent&&(!n||n.length!==1))throw new Error("Pool ops requires 1 input.")},Ir=(n,i,s)=>{let u=i.format==="NHWC",c=n.dims.slice();u&&c.splice(1,0,c.pop());let f=Object.hasOwnProperty.call(i,"dilations"),d=i.kernelShape.slice(),x=i.strides.slice(),k=f?i.dilations.slice():[],$=i.pads.slice();Kn.adjustPoolAttributes(s,c,d,x,k,$);let H=Kn.computePoolOutputShape(s,c,x,k,d,$,i.autoPad),q=Object.assign({},i);f?Object.assign(q,{kernelShape:d,strides:x,pads:$,dilations:k,cacheKey:i.cacheKey}):Object.assign(q,{kernelShape:d,strides:x,pads:$,cacheKey:i.cacheKey});let v=H.slice();return v.push(v.splice(1,1)[0]),[q,u?v:H]},dr=(n,i)=>{let s=i.format==="NHWC",u=ct.size(n),c=ct.size(i.kernelShape),f=[{type:12,data:u},{type:12,data:c}],d=[{name:"outputSize",type:"u32"},{name:"kernelSize",type:"u32"}];if(i.kernelShape.length<=2){let x=i.kernelShape[i.kernelShape.length-1],k=i.strides[i.strides.length-1],$=i.pads[i.pads.length/2-1],H=i.pads[i.pads.length-1],q=!!($+H);f.push({type:12,data:x},{type:12,data:k},{type:12,data:$},{type:12,data:H}),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 oe=i.kernelShape[i.kernelShape.length-2],te=i.strides[i.strides.length-2],de=i.pads[i.pads.length/2-2],we=i.pads[i.pads.length-2];v=!!(de+we),f.push({type:12,data:oe},{type:12,data:te},{type:12,data:de},{type:12,data:we}),d.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[f,d,!0,q,v]}else{if(s)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let x=ct.computeStrides(i.kernelShape);f.push({type:12,data:x},{type:12,data:i.pads},{type:12,data:i.strides}),d.push({name:"kernelStrides",type:"u32",length:x.length},{name:"pads",type:"u32",length:i.pads.length},{name:"strides",type:"u32",length:i.strides.length});let k=i.pads.reduce(($,H)=>$+H);return[f,d,!!k,!1,!1]}},wr=(n,i,s,u,c,f,d,x,k,$,H,q)=>{let v=c.format==="NHWC",oe=i.type.value,te=Gt("output",i.type.tensor,u);if(c.kernelShape.length<=2){let de="",we="",be="",he=s-(v?2:1);if(H?de=` + 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")}]; + ${f} + }`:de=` + 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")}]; + ${f} + }`,c.kernelShape.length===2){let De=s-(v?3:2);q?we=` + for (var j: u32 = 0u; j < uniforms.kh; j++) { + xIndices[${De}] = indices[${De}] * uniforms.sh - uniforms.phStart + j; + if (xIndices[${De}] < 0 || xIndices[${De}] >= uniforms.x_shape[${De}]) { + pad += i32(uniforms.kw); + continue; + } + `:we=` + for (var j: u32 = 0u; j < uniforms.kh; j++) { + xIndices[${De}] = indices[${De}] * uniforms.sh - uniforms.phStart + j; + `,be=` + } + `}return` + ${n.registerUniforms(k).declareVariables(i,te)} + + ${n.mainStart()} + ${n.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + + let indices = ${te.offsetToIndices("global_idx")}; + var xIndices = ${te.offsetToIndices("global_idx")}; + + var value = ${oe}(${x}); + var pad = 0; + ${we} + ${de} + ${be} + ${d} + + output[global_idx] = value; + }`}else{if(v)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let de=c.kernelShape.length,we=c.pads.length,be="";return $?be=` + if (xIndices[j] >= uniforms.x_shape[j]) { + pad++; + isPad = true; + break; + } + } + if (!isPad) { + let x_val = x[${i.indicesToOffset("xIndices")}]; + ${f} + }`:be=` + } + let x_val = x[${i.indicesToOffset("xIndices")}]; + ${f} + `,` + ${n.registerUniforms(k).declareVariables(i,te)} + + ${n.mainStart()} + ${n.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + let indices = ${te.offsetToIndices("global_idx")}; + var xIndices = ${te.offsetToIndices("global_idx")}; + + var offsets: array; + + var value = ${oe}(${x}); + var pad = 0; + var isPad = false; + + for (var i: u32 = 0u; i < uniforms.kernelSize; i++) { + var offset = i; + for (var j = 0u; j < ${de-1}u; j++) { + offsets[j] = offset / ${zt("uniforms.kernelStrides","j",de)}; + offset -= offsets[j] * ${zt("uniforms.kernelStrides","j",de)}; + } + offsets[${de-1}] = offset; + + isPad = false; + for (var j = ${s-de}u; j < ${s}u; j++) { + xIndices[j] = indices[j] * ${zt("uniforms.strides",`j - ${s-de}u`,de)} + + offsets[j - ${s-de}u] - ${zt("uniforms.pads","j - 2u",we)}; + ${be} + } + ${d} + + output[global_idx] = value; + }`}},pr=n=>`${n.format};${n.ceilMode};${n.autoPad};${n.kernelShape.length}`,mr=n=>`${pr(n)};${n.countIncludePad}`,xr=n=>`${pr(n)};${n.storageOrder};${n.dilations}`,Nr=n=>({format:n.format,autoPad:["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][n.auto_pad],ceilMode:n.ceil_mode,kernelShape:n.kernel_shape,strides:n.strides,pads:n.pads}),$n=(n,i,s,u)=>{let[c,f]=Ir(i,u,s),d=_t("x",i.dataType,i.dims.length),x=d.type.value,k="value += x_val;",$="";c.countIncludePad?$+=`value /= ${x}(uniforms.kernelSize);`:$+=`value /= ${x}(i32(uniforms.kernelSize) - pad);`;let[H,q,v,oe,te]=dr(f,c);H.push(...At(i.dims,f));let de=["rank"];return{name:n,shaderCache:{hint:`${u.cacheKey};${v};${oe};${te}`,inputDependencies:de},getRunData:()=>({outputs:[{dims:f,dataType:i.dataType}],dispatchGroup:{x:Math.ceil(ct.size(f)/64)},programUniforms:H}),getShaderSource:we=>wr(we,d,i.dims.length,f.length,c,k,$,0,q,v,oe,te)}},zn=n=>{let i=n.count_include_pad!==0,s=Nr(n);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:mr(u)}},Pi=(n,i)=>{lr(n.inputs),n.compute($n("AveragePool",n.inputs[0],!1,i))},Mn={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},dn=n=>{let i=n.format;return{format:i,...Mn,cacheKey:i}},Tn=(n,i)=>{lr(n.inputs),n.compute($n("GlobalAveragePool",n.inputs[0],!0,i))},qs=(n,i,s,u)=>{let[c,f]=Ir(i,u,s),d=` + value = max(x_val, value); + `,x="",k=_t("x",i.dataType,i.dims.length),$=["rank"],[H,q,v,oe,te]=dr(f,c);return H.push(...At(i.dims,f)),{name:n,shaderCache:{hint:`${u.cacheKey};${v};${oe};${te}`,inputDependencies:$},getRunData:()=>({outputs:[{dims:f,dataType:i.dataType}],dispatchGroup:{x:Math.ceil(ct.size(f)/64)},programUniforms:H}),getShaderSource:de=>wr(de,k,i.dims.length,f.length,c,d,x,i.dataType===10?-65504:-1e5,q,v,oe,te)}},Ks=(n,i)=>{lr(n.inputs),n.compute(qs("MaxPool",n.inputs[0],!1,i))},El=n=>{let i=n.storage_order,s=n.dilations,u=Nr(n);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:xr(c)}},ym=n=>{let i=n.format;return{format:i,...Mn,cacheKey:i}},mi=(n,i)=>{lr(n.inputs),n.compute(qs("GlobalMaxPool",n.inputs[0],!0,i))}}),Ef,Cf,Pf,$f=h(()=>{Z(),Zt(),ar(),Ef=(n,i,s)=>{let u=n===i,c=ni&&s>0;if(u||c||f)throw new Error("Range these inputs' contents are invalid.")},Cf=(n,i,s,u)=>{let c=Math.abs(Math.ceil((i-n)/s)),f=[c],d=c,x=[{type:12,data:d},{type:u,data:n},{type:u,data:s},...At(f)],k=$=>{let H=Gt("output",u,f.length),q=H.type.value,v=[{name:"outputSize",type:"u32"},{name:"start",type:q},{name:"delta",type:q}];return` + ${$.registerUniforms(v).declareVariables(H)} + ${$.mainStart()} + ${$.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + output[global_idx] = uniforms.start + ${q}(global_idx) * uniforms.delta; + }`};return{name:"Range",shaderCache:{hint:`${u}`},getShaderSource:k,getRunData:()=>({outputs:[{dims:f,dataType:u}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:x})}},Pf=n=>{let i=0,s=0,u=0;n.inputs[0].dataType===6?(i=n.inputs[0].getInt32Array()[0],s=n.inputs[1].getInt32Array()[0],u=n.inputs[2].getInt32Array()[0]):n.inputs[0].dataType===1&&(i=n.inputs[0].getFloat32Array()[0],s=n.inputs[1].getFloat32Array()[0],u=n.inputs[2].getFloat32Array()[0]),N.webgpu.validateInputContent&&Ef(i,s,u),n.compute(Cf(i,s,u,n.inputs[0].dataType),{inputs:[]})}}),b0,x0,M0,T0,k0,S0,E0,C0,P0,$0,A0,vm,I0,F0,O0,z0,D0,L0,R0,nx=h(()=>{Zt(),Jt(),_r(),ar(),b0=(n,i)=>{if(n.every(s=>s>0||(()=>{throw new Error("Resize requires scales input values to be positive")})),n.length>0){if(i.mode==="linear"){if(!(n.length===2||n.length===3||n.length===4&&n[0]===1&&n[1]===1||n.length===4&&n[0]===1&&n[3]===1||n.length===5&&n[0]===1&&n[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"&&!(n.length===2||n.length===4&&n[0]===1&&n[1]===1||n.length===4&&n[0]===1&&n[3]===1))throw new Error("Resize requires scales input size to be 2 or 4 for cubic mode")}},x0=(n,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,f)=>u[c]=n[f]),u},M0=(n,i,s,u,c,f)=>{let[d,x,k]=s>10?[1,2,3]:[-1,n.length>1?1:-1,-1],$=n[0].dims.length;if(d>0&&n.length>d&&n[d].dims.length>0)n[d].getFloat32Array().forEach(H=>f.push(H));else if(i.coordinateTransformMode==="tf_crop_and_resize")throw new Error("Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize");if(x>0&&n.length>x&&n[x].dims.length>0){if(n[x].getFloat32Array().forEach(H=>u.push(H)),u.length!==0&&u.length!==$&&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");b0(u,i),i.axes.length>0&&x0(u,i.axes,$).forEach((H,q)=>u[q]=H)}if(k>0&&n.length>k&&(n[k].getBigInt64Array().forEach(H=>c.push(Number(H))),c.length!==$||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>$)throw new Error("Resize requires only of scales or sizes to be specified")},T0=(n,i)=>`fn getOriginalCoordinateFromResizedCoordinate(xResized: u32, xScale: f32, lengthResized: u32, + lengthOriginal: u32, roiStart: f32, roiEnd: f32) -> ${i} { `+(()=>{switch(n){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 ${n} is not supported`)}})()+"}",k0=(n,i,s)=>`fn getNearestPixelFromOriginal(xOriginal: ${s}, isDownSample: bool) -> ${s} {`+(()=>{switch(n){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 ${n} is not supported`)}})()+"}",S0=(n,i,s)=>{let u=new Array(s).fill(0).concat(new Array(s).fill(1)),c=n.length===0?u:n.slice();return i.length>0?(i.forEach((f,d)=>{u[f]=c[d],u[d+s]=c[i.length+d]}),u):c},E0=(n,i,s,u)=>{let c=[];if(s.length>0)if(u.length>0){if(n.forEach(f=>c.push(f)),Math.max(...u)>n.length)throw new Error("axes is out of bound");u.forEach((f,d)=>c[f]=s[d])}else s.forEach(f=>c.push(f));else{if(i.length===0)throw new Error("Resize requires either scales or sizes.");c=n.map((f,d)=>Math.round(f*i[d]))}return c},C0=(n,i,s)=>{let u=(()=>{switch(s.keepAspectRatioPolicy){case"not_larger":return s.axes.length>0?Math.min(...s.axes.map(f=>i[f]),Number.MAX_VALUE):Math.min(...i,Number.MAX_VALUE);case"not_smaller":return s.axes.length>0?Math.max(...s.axes.map(f=>i[f]),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=n.slice();return s.axes.length>0?(s.axes.forEach(f=>i[f]=u),s.axes.forEach(f=>c[f]=Math.round(n[f]*i[f]))):(i.fill(u,0,i.length),c.forEach((f,d)=>c[d]=Math.round(f*i[d]))),c},P0=(n,i,s,u,c)=>` + fn calculateOriginalIndicesFromOutputIndices(output_indices: ${n.type.indices}) -> array<${n.type.value}, ${s.length}> { + var original_indices: array<${n.type.value}, ${s.length}>; + for (var i:u32 = 0; i < ${s.length}; i++) { + var output_index = ${n.indicesGet("output_indices","i")}; + var scale = ${zt("uniforms.scales","i",u)}; + var roi_low = ${zt("uniforms.roi","i",c)}; + var roi_hi = ${zt("uniforms.roi",`i + ${i.length}`,c)}; + if (scale == 1.0) { + original_indices[i] = ${n.type.value}(output_index); + } else { + var input_shape_i = ${zt("uniforms.input_shape","i",i.length)}; + var output_shape_i = ${zt("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; + }`,$0=(n,i,s,u,c,f,d)=>` + fn calculateInputIndicesFromOutputIndices(output_indices: ${i.type.indices}) -> ${n.type.indices} { + var input_indices: ${n.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 = ${zt("uniforms.scales","i",c)}; + if (scale == 1.0) { + input_index = output_index; + } else { + var roi_low = ${zt("uniforms.roi","i",f)}; + var roi_hi = ${zt("uniforms.roi",`i + ${s.length}`,f)}; + var input_shape_i = ${zt("uniforms.input_shape","i",s.length)}; + var output_shape_i = ${zt("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); + } + } + ${n.indicesSet("input_indices","i"," input_index")} + } + return input_indices; + }`,A0=(n,i)=>` + fn checkInputIndices(input_indices: ${n.type.indices}) -> bool { + for (var i:u32 = 0; i < ${i.length}; i++) { + var input_index = ${n.indicesGet("input_indices","i")}; + if (input_index < 0 || input_index >= ${zt("uniforms.input_shape","i",i.length)}) { + return false; + } + } + return true; + }`,vm=(n,i,s,u)=>n.rank>u?` + ${n.indicesSet("input_indices",i,"channel")}; + ${n.indicesSet("input_indices",s,"batch")}; +`:"",I0=(n,i,s,u,c)=>{let[f,d,x,k]=s.length===2?[-1,0,1,-1]:[0,2,3,1],$=n.type.value;return` + fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${$} { + var input_indices: ${n.type.indices}; + ${n.indicesSet("input_indices",d,`max(0, min(row, ${s[d]} - 1))`)}; + ${n.indicesSet("input_indices",x,`max(0, min(col, ${s[x]} - 1))`)}; + ${vm(n,k,f,2)} + return ${n.getByIndices("input_indices")}; + } + + fn bilinearInterpolation(output_indices: ${i.type.indices}) -> ${$} { + var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); + var row:${$} = originalIndices[${d}]; + var col:${$} = originalIndices[${x}]; + ${u?`if (row < 0 || row > (${s[d]} - 1) || col < 0 || col > (${s[x]} - 1)) { + return ${c}; + }`:""}; + row = max(0, min(row, ${s[d]} - 1)); + col = max(0, min(col, ${s[x]} - 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[${k}])`:"0"}; + var batch: u32 = ${s.length>2?`u32(originalIndices[${f}])`:"0"}; + var x11: ${$} = getInputValue(batch, channel, row1, col1); + var x12: ${$} = getInputValue(batch, channel, row1, col2); + var x21: ${$} = getInputValue(batch, channel, row2, col1); + var x22: ${$} = getInputValue(batch, channel, row2, col2); + var dx1: ${$} = abs(row - ${$}(row1)); + var dx2: ${$} = abs(${$}(row2) - row); + var dy1: ${$} = abs(col - ${$}(col1)); + var dy2: ${$} = abs(${$}(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); + }`},F0=(n,i,s,u,c,f,d,x,k,$)=>{let H=s.length===2,[q,v]=H?[0,1]:[2,3],oe=n.type.value,te=de=>{let we=de===q?"row":"col";return` + fn ${we}CubicInterpolation(input_indices: ${n.type.indices}, output_indices: ${i.type.indices}) -> ${oe} { + var output_index = ${i.indicesGet("output_indices",de)}; + var originalIdx: ${oe} = getOriginalCoordinateFromResizedCoordinate(output_index, ${c[de]}, + ${u[de]}, ${s[de]}, ${f[de]}, ${f[de]} + ${s.length}); + var fractOriginalIdx: ${oe} = originalIdx - floor(originalIdx); + var coefs = getCubicInterpolationCoefs(fractOriginalIdx); + + if (${x} && (originalIdx < 0 || originalIdx > (${s[de]} - 1))) { + return ${k}; + } + var data: array<${oe}, 4> = array<${oe}, 4>(0.0, 0.0, 0.0, 0.0); + for (var i: i32 = -1; i < 3; i++) { + var ${we}: ${oe} = originalIdx + ${oe}(i); + if (${we} < 0 || ${we} >= ${s[de]}) { + ${$?`coefs[i + 1] = 0.0; + continue;`:x?`return ${k};`:`${we} = max(0, min(${we}, ${s[de]} - 1));`}; + } + var input_indices_copy: ${n.type.indices} = input_indices; + ${n.indicesSet("input_indices_copy",de,`u32(${we})`)}; + data[i + 1] = ${de===q?n.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"}; + } + return cubicInterpolation1D(data, coefs); + }`};return` + ${te(q)}; + ${te(v)}; + fn getCubicInterpolationCoefs(s: ${oe}) -> array<${oe}, 4> { + var absS = abs(s); + var coeffs: array<${oe}, 4> = array<${oe}, 4>(0.0, 0.0, 0.0, 0.0); + var oneMinusAbsS: ${oe} = 1.0 - absS; + var twoMinusAbsS: ${oe} = 2.0 - absS; + var onePlusAbsS: ${oe} = 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<${oe}, 4>, coefs: array<${oe}, 4>) -> ${oe} { + var coefsSum: ${oe} = 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}) -> ${oe} { + var input_indices: ${n.type.indices} = output_indices; + return colCubicInterpolation(input_indices, output_indices); + } + `},O0=(n,i,s,u,c)=>{let[f,d,x,k,$]=s.length===3?[-1,0,1,2,-1]:[0,2,3,4,1],H=n.type.value;return` + fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${H} { + var input_indices: ${n.type.indices}; + ${n.indicesSet("input_indices",d,`max(0, min(depth, ${s[d]} - 1))`)}; + ${n.indicesSet("input_indices",x,`max(0, min(height, ${s[x]} - 1))`)}; + ${n.indicesSet("input_indices",k,`max(0, min(width, ${s[k]} - 1))`)}; + ${vm(n,$,f,3)} + return ${n.getByIndices("input_indices")}; + } + + fn trilinearInterpolation(output_indices: ${i.type.indices}) -> ${H} { + var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); + var depth:${H} = originalIndices[${d}]; + var height:${H} = originalIndices[${x}]; + var width:${H} = originalIndices[${k}]; + ${u?`if (depth < 0 || depth > (${s[d]} - 1) || height < 0 || height > (${s[x]} - 1) || width < 0 || (width > ${s[k]} - 1)) { + return ${c}; + }`:""}; + + depth = max(0, min(depth, ${s[d]} - 1)); + height = max(0, min(height, ${s[x]} - 1)); + width = max(0, min(width, ${s[k]} - 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[${$}])`:"0"}; + var batch: u32 = ${s.length>3?`u32(originalIndices[${f}])`:"0"}; + + var x111: ${H} = getInputValue(batch, channel, depth1, height1, width1); + var x112: ${H} = getInputValue(batch, channel, depth1, height1, width2); + var x121: ${H} = getInputValue(batch, channel, depth1, height2, width1); + var x122: ${H} = getInputValue(batch, channel, depth1, height2, width2); + var x211: ${H} = getInputValue(batch, channel, depth2, height1, width1); + var x212: ${H} = getInputValue(batch, channel, depth2, height1, width2); + var x221: ${H} = getInputValue(batch, channel, depth2, height2, width1); + var x222: ${H} = getInputValue(batch, channel, depth2, height2, width2); + var dx1: ${H} = abs(depth - ${H}(depth1)); + var dx2: ${H} = abs(${H}(depth2) - depth); + var dy1: ${H} = abs(height - ${H}(height1)); + var dy2: ${H} = abs(${H}(height2) - height); + var dz1: ${H} = abs(width - ${H}(width1)); + var dz2: ${H} = abs(${H}(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=(n,i,s,u,c,f)=>{let d=n.dims,x=S0(f,i.axes,d.length),k=E0(d,u,c,i.axes),$=u.slice();u.length===0&&($=d.map((he,De)=>he===0?1:k[De]/he),i.keepAspectRatioPolicy!=="stretch"&&(k=C0(d,$,i)));let H=Gt("output",n.dataType,k.length),q=_t("input",n.dataType,d.length),v=ct.size(k),oe=d.length===k.length&&d.every((he,De)=>he===k[De]),te=i.coordinateTransformMode==="tf_crop_and_resize",de=i.extrapolationValue,we=q.type.value,be=he=>` + ${oe?"":` + ${T0(i.coordinateTransformMode,we)}; + ${(()=>{switch(i.mode){case"nearest":return` + ${A0(q,d)}; + ${k0(i.nearestMode,s,we)}; + ${$0(q,H,d,k,$.length,x.length,te)}; + `;case"linear":return` + ${P0(H,d,k,$.length,x.length)}; + ${(()=>{if(d.length===2||d.length===4)return`${I0(q,H,d,te,de)}`;if(d.length===3||d.length===5)return`${O0(q,H,d,te,de)}`;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`${F0(q,H,d,k,$,x,i.cubicCoeffA,te,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",$.length).registerUniform("roi","f32",x.length).declareVariables(q,H)} + ${he.mainStart()} + ${he.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + ${oe?"output[global_idx] = input[global_idx];":` + let output_indices = ${H.offsetToIndices("global_idx")}; + var input_indices: ${q.type.indices}; + ${(()=>{switch(i.mode){case"nearest":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices); + if (checkInputIndices(input_indices)) { + output[global_idx] = ${q.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}|${$.length>0?$:""}|${c.length>0?c:""}|${x.length>0?x:""}|${oe}|${d}`,inputDependencies:["rank"]},getShaderSource:be,getRunData:()=>({outputs:[{dims:k,dataType:n.dataType}],dispatchGroup:{x:Math.ceil(v/64)},programUniforms:[{type:12,data:v},{type:1,data:$},{type:1,data:x},...At(d,k)]})}},D0=n=>{let i=n.customDataBuffer;return new Uint32Array(i,i.byteOffset,1)[0]},L0=(n,i)=>{let s=[],u=[],c=[],f=D0(n);if(i.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");M0(n.inputs,i,f,s,u,c),n.compute(z0(n.inputs[0],i,f,s,u,c),{inputs:[0]})},R0=n=>{let i=n.antialias,s=n.axes,u=n.coordinateTransformMode,c=n.cubicCoeffA,f=n.excludeOutside!==0,d=n.extrapolationValue,x=n.keepAspectRatioPolicy,k=n.mode,$=n.nearestMode===""?"simple":n.nearestMode;return qt({antialias:i,axes:s,coordinateTransformMode:u,cubicCoeffA:c,excludeOutside:f,extrapolationValue:d,keepAspectRatioPolicy:x,mode:k,nearestMode:$})}}),B0,N0,j0,ix=h(()=>{Zt(),Jt(),_r(),ar(),B0=(n,i)=>{let[s,u,c,f]=n,{numHeads:d,rotaryEmbeddingDim:x}=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(!ct.areEqual(u.dims,[])&&!ct.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(f.dims.length!==2)throw new Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${f.dims.length}`);if(!ct.areEqual(c.dims,f.dims))throw new Error("Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape");if(x>0&&d===0)throw new Error("num_heads must be provided if rotary_embedding_dim is specified");let k=s.dims[0],$=s.dims[s.dims.length-2],H=c.dims[0],q=ct.sizeFromDimension(s.dims,1)/$,v=x===0?c.dims[1]*2:q/d;if(x>v)throw new Error("rotary_embedding_dim must be less than or equal to head_size");if(u.dims.length===2){if(k!==u.dims[0])throw new Error(`Input 'position_ids' dimension 0 should be of size batch_size, got ${u.dims[0]}`);if($!==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]&&x/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($>H)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported")},N0=(n,i)=>{let{interleaved:s,numHeads:u,rotaryEmbeddingDim:c,scale:f}=i,d=n[0].dims[0],x=ct.sizeFromDimension(n[0].dims,1),k=n[0].dims[n[0].dims.length-2],$=x/k,H=n[2].dims[1],q=c===0?H*2:$/u,v=new Array(d,k,$/q,q-H),oe=ct.computeStrides(v),te=[{type:1,data:f},{type:12,data:v},{type:12,data:oe},...n[0].dims.length===3?new Array({type:12,data:[x,$,q,1]}):[],...n[0].dims.length===4?new Array({type:12,data:[x,q,k*q,1]}):[],...At(n[0].dims,n[1].dims,n[2].dims,n[3].dims,n[0].dims)],de=we=>{let be=_t("input",n[0].dataType,n[0].dims.length),he=_t("position_ids",n[1].dataType,n[1].dims.length),De=_t("cos_cache",n[2].dataType,n[2].dims.length),Ae=_t("sin_cache",n[3].dataType,n[3].dims.length),Ie=Gt("output",n[0].dataType,n[0].dims.length);return we.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:v.length},{name:"global_strides",type:"u32",length:oe.length},{name:"input_output_strides",type:"u32",length:oe.length}]),` + ${we.declareVariables(be,he,De,Ae,Ie)} + + ${we.mainStart(Un)} + let half_rotary_emb_dim = uniforms.${De.name}_shape[1]; + let bsnh = global_idx / uniforms.global_strides % uniforms.global_shape; + let size = uniforms.global_shape[0] * uniforms.global_strides[0]; + ${we.guardAgainstOutOfBoundsWorkgroupSizes("size")} + + if (bsnh[3] < half_rotary_emb_dim) { + let position_ids_idx = + ${he.broadcastedIndicesToOffset("bsnh.xy",Gt("",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")} * ${De.get("position_id","bsnh[3]")} - + ${be.getByOffset("j")} * ${Ae.get("position_id","bsnh[3]")}; + ${Ie.setByOffset("i","re")} + let im = ${be.getByOffset("i")} * ${Ae.get("position_id","bsnh[3]")} + + ${be.getByOffset("j")} * ${De.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:qt({interleaved:s}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:de,getRunData:()=>({outputs:[{dims:n[0].dims,dataType:n[0].dataType}],dispatchGroup:{x:Math.ceil(ct.size(v)/Un)},programUniforms:te})}},j0=(n,i)=>{B0(n.inputs,i),n.compute(N0(n.inputs,i))}}),U0,V0,W0,ox=h(()=>{Zt(),Jt(),ar(),U0=n=>{if(!n||n.length<3)throw new Error("layerNorm requires at least 3 inputs.");let i=n[0],s=n[1],u=n[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],f=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]!==f)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(n.length>3){let d=n[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(n.length>4){let d=n[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")}},V0=(n,i,s,u)=>{let c=i.simplified,f=n[0].dims,d=ct.size(f),x=f,k=d,$=f.slice(-1)[0],H=u?f.slice(0,-1).concat(1):[],q=!c&&n.length>3,v=n.length>4,oe=u&&s>1,te=u&&s>2,de=s>3,we=64,be=vr($),he=[{type:12,data:k},{type:12,data:be},{type:12,data:$},{type:1,data:i.epsilon}],De=Ie=>{let gt=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],ut=[_t("x",n[0].dataType,n[0].dims,be),_t("skip",n[1].dataType,n[1].dims,be),_t("gamma",n[2].dataType,n[2].dims,be)];q&&ut.push(_t("beta",n[3].dataType,n[3].dims,be)),v&&ut.push(_t("bias",n[4].dataType,n[4].dims,be)),ut.push(Gt("output",n[0].dataType,x,be)),oe&&ut.push(Gt("mean_output",1,H)),te&&ut.push(Gt("inv_std_output",1,H)),de&&ut.push(Gt("input_skip_bias_sum",n[0].dataType,x,be));let vt=Sr(n[0].dataType),Dt=Sr(1,be);return` + + ${Ie.registerUniforms(gt).declareVariables(...ut)} + var sum_shared : array<${Dt}, ${we}>; + var sum_squared_shared : array<${Dt}, ${we}>; + + ${Ie.mainStart([we,1,1])} + let ix = local_id.x; + let iy = global_id.x / ${we}; + + let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components; + var stride = hidden_size_vectorized / ${we}; + let offset = ix * stride + iy * hidden_size_vectorized; + let offset1d = stride * ix; + if (ix == ${we-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; + ${de?"input_skip_bias_sum[offset + i] = value;":""} + output[offset + i] = value; + let f32_value = ${Xr(vt,be,"value")}; + sum_shared[ix] += f32_value; + sum_squared_shared[ix] += f32_value * f32_value; + } + workgroupBarrier(); + + var reduce_size : u32 = ${we}; + 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 = ${Vn("sum",be)} / f32(uniforms.hidden_size); + let inv_std_dev = inverseSqrt(${Vn("square_sum",be)} / f32(uniforms.hidden_size) ${c?"":"- mean * mean"} + uniforms.epsilon); + ${oe?"mean_output[global_idx] = mean;":""} + ${te?"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] + ${q?"+ beta[offset1d + i]":""}; + } + }`},Ae=[{dims:x,dataType:n[0].dataType}];return s>1&&Ae.push({dims:H,dataType:1}),s>2&&Ae.push({dims:H,dataType:1}),s>3&&Ae.push({dims:f,dataType:n[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${be};${oe};${te};${de}`,inputDependencies:n.map((Ie,gt)=>"type")},getShaderSource:De,getRunData:()=>({outputs:Ae,dispatchGroup:{x:Math.ceil(k/$)},programUniforms:he})}},W0=(n,i)=>{U0(n.inputs);let s=[0];n.outputCount>1&&s.push(-3),n.outputCount>2&&s.push(-3),n.outputCount>3&&s.push(3),n.compute(V0(n.inputs,i,n.outputCount,!1),{outputs:s})}}),G0,op,H0,bm,q0,K0,X0,Q0,sx=h(()=>{Zt(),Jt(),_r(),ar(),G0=(n,i)=>{if(!n||n.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");n.slice(1).forEach((s,u)=>{if(n[u+1].dataType!==6&&n[u+1].dataType!==7)throw new Error(`Input ${u} must be an array of int32 or int64`)})},op=(n,i)=>{let s=[];if(n.length>i)if(n[i].dataType===7)n[i].getBigInt64Array().forEach(u=>s.push(Number(u)));else if(n[i].dataType===6)n[i].getInt32Array().forEach(u=>s.push(Number(u)));else throw new Error(`Input ${i} must be an array of int32 or int64`);return s},H0=(n,i)=>{if(n.length>1){let s=op(n,1),u=op(n,2),c=op(n,3);return c.length===0&&(c=[...Array(n[0].dims.length).keys()]),qt({starts:s,ends:u,axes:c})}else return i},bm=(n,i,s,u,c)=>{let f=n;return n<0&&(f+=s[u[i]]),c[i]<0?Math.max(0,Math.min(f,s[u[i]]-1)):Math.max(0,Math.min(f,s[u[i]]))},q0=(n,i,s)=>`fn calculateInputIndices(output_indices: ${i.type.indices}) -> ${n.type.indices} { + var input_indices: ${n.type.indices}; + var carry = 0u; + for (var i = ${s.length}; i >= 0; i--) { + let input_shape_i = ${zt("uniforms.input_shape","i",s.length)}; + let steps_i = ${zt("uniforms.steps","i",s.length)}; + let signs_i = ${zt("uniforms.signs","i",s.length)}; + let starts_i = ${zt("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; + } + ${n.indicesSet("input_indices","i","input_index")}; + } + return input_indices; + }`,K0=(n,i)=>{let s=n[0].dims,u=ct.size(s),c=i.axes.length>0?ct.normalizeAxes(i.axes,s.length):[...Array(s.length).keys()],f=op(n,4);f.forEach(be=>be!==0||(()=>{throw new Error("step cannot be 0")})),f.length===0&&(f=Array(c.length).fill(1));let d=i.starts.map((be,he)=>bm(be,he,s,c,f)),x=i.ends.map((be,he)=>bm(be,he,s,c,f));if(c.length!==d.length||c.length!==x.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));f.forEach((be,he,De)=>{if(be<0){let Ae=(x[he]-d[he])/be,Ie=d[he],gt=Ie+Ae*f[he];d[he]=gt,x[he]=Ie,De[he]=-be}});let $=s.slice(0);c.forEach((be,he)=>{$[be]=Math.ceil((x[be]-d[be])/f[be])});let H={dims:$,dataType:n[0].dataType},q=Gt("output",n[0].dataType,$.length),v=_t("input",n[0].dataType,n[0].dims.length),oe=ct.size($),te=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:d.length},{name:"signs",type:"i32",length:k.length},{name:"steps",type:"u32",length:f.length}],de=[{type:12,data:oe},{type:12,data:d},{type:6,data:k},{type:12,data:f},...At(n[0].dims,$)],we=be=>` + ${be.registerUniforms(te).declareVariables(v,q)} + ${q0(v,q,s)} + ${be.mainStart()} + ${be.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + let output_indices = ${q.offsetToIndices("global_idx")}; + let input_indices = calculateInputIndices(output_indices); + ${q.setByOffset("global_idx",v.getByIndices("input_indices"))} + }`;return{name:"Slice",shaderCache:{hint:`${k.length}_${d.length}_${f.length}`,inputDependencies:["rank"]},getShaderSource:we,getRunData:()=>({outputs:[H],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:de})}},X0=(n,i)=>{G0(n.inputs,i);let s=H0(n.inputs,i);n.compute(K0(n.inputs,s),{inputs:[0]})},Q0=n=>{let i=n.starts,s=n.ends,u=n.axes;return qt({starts:i,ends:s,axes:u})}}),Y0,Z0,J0,ew,ax=h(()=>{Zt(),Jt(),_r(),ar(),Y0=n=>{if(!n||n.length!==1)throw new Error("Softmax op requires 1 input.")},Z0=(n,i)=>{let s=n.dims,u=ct.size(s),c=64,f=i.axis;if(f<0&&(f=s.length+f),fbe===4?`max(max(${we}.x, ${we}.y), max(${we}.z, ${we}.w))`:be===2?`max(${we}.x, ${we}.y)`:be===3?`max(max(${we}.x, ${we}.y), ${we}.z)`:we,q=_t("x",n.dataType,n.dims,k),v=Gt("result",n.dataType,n.dims,k),oe=q.type.value,te=Sr(n.dataType)==="f32"?`var threadMax = ${oe}(-3.402823e+38f);`:`var threadMax = ${oe}(-65504.0h);`,de=we=>` + var rowMaxShared : ${oe}; + var rowSumShared : ${oe}; + var threadShared : array<${oe}, ${c}>; + + fn getValue(row: i32, col: i32, row_stride: i32) -> ${oe} { + let index = row * row_stride + col; + return x[index]; + } + + fn setValue(row: i32, col: i32, row_stride: i32, value: ${oe}) { + let index = row * row_stride + col; + result[index] = value; + } + ${we.registerUniform("packedCols","i32").declareVariables(q,v)} + ${we.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 + ${te} + 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 = ${oe}(${H("threadShared[0]",k)}); + } + workgroupBarrier(); + + // find the rows sum + var threadSum = ${oe}(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 = ${oe}(${Vn("threadShared[0]",k)}); + } + 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:`${k}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:s,dataType:n.dataType}],dispatchGroup:{x},programUniforms:[{type:6,data:$}]}),getShaderSource:de}},J0=(n,i)=>{Y0(n.inputs),n.compute(Z0(n.inputs[0],i))},ew=n=>qt({axis:n.axis})}),tw,rw,nw,iw,ow,sw,aw,lx=h(()=>{Zt(),Jt(),_r(),ar(),tw=n=>{if(!n||n.length<1)throw new Error("too few inputs")},rw=(n,i)=>{let s=[],u=i.numOutputs;return n[1].dims[0]>0&&(n[1].getBigInt64Array().forEach(c=>s.push(Number(c))),u=s.length),qt({numOutputs:u,axis:i.axis,splitSizes:s})},nw=n=>` +fn calculateOutputIndex(index: u32) -> u32 { + for (var i: u32 = 0u; i < ${n}u; i += 1u ) { + if (index < ${zt("uniforms.size_in_split_axis","i",n)}) { + return i; + } + } + return ${n}u; +}`,iw=n=>{let i=n.length,s=[];for(let u=0;u{let s=n[0].dims,u=ct.size(s),c=n[0].dataType,f=ct.normalizeAxis(i.axis,s.length),d=new Array(i.numOutputs),x=_t("input",c,s.length),k=new Array(i.numOutputs),$=[],H=[],q=0,v=[{type:12,data:u}];for(let te=0;te` + ${te.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",k.length).declareVariables(x,...d)} + ${nw(k.length)} + ${iw(d)} + + ${te.mainStart()} + ${te.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")} + + var indices = ${x.offsetToIndices("global_idx")}; + var index = ${x.indicesGet("indices",f)}; + let output_number = calculateOutputIndex(index); + if (output_number != 0) { + index -= ${zt("uniforms.size_in_split_axis","output_number - 1u",k.length)}; + ${x.indicesSet("indices",f,"index")}; + } + writeBufferData(output_number, indices, global_idx); + }`;return{name:"Split",shaderCache:{hint:i.cacheKey,inputDependencies:["rank"]},getShaderSource:oe,getRunData:()=>({outputs:$,dispatchGroup:{x:Math.ceil(u/64)},programUniforms:v})}},sw=(n,i)=>{tw(n.inputs);let s=n.inputs.length===1?i:rw(n.inputs,i);n.compute(ow(n.inputs,s),{inputs:[0]})},aw=n=>{let i=n.axis,s=n.splitSizes,u=n.numOutputs<0?s.length:n.numOutputs;if(u!==s.length)throw new Error("numOutputs and splitSizes lengh must be equal");return qt({axis:i,numOutputs:u,splitSizes:s})}}),lw,uw,cw,ux=h(()=>{Zt(),Jt(),ar(),lw=(n,i,s,u,c)=>{let f=Gt("output_data",c,s.length,4),d=_t("a_data",i[1].dataType,i[1].dims.length,4),x=_t("b_data",i[2].dataType,i[2].dims.length,4),k=_t("c_data",i[0].dataType,i[0].dims.length,4),$,H=(q,v,oe)=>`select(${v}, ${q}, ${oe})`;if(!u)$=f.setByOffset("global_idx",H(d.getByOffset("global_idx"),x.getByOffset("global_idx"),k.getByOffset("global_idx")));else{let q=(v,oe,te="")=>{let de=`a_data[index_a${oe}][component_a${oe}]`,we=`b_data[index_b${oe}][component_b${oe}]`,be=`bool(c_data[index_c${oe}] & (0xffu << (component_c${oe} * 8)))`;return` + let output_indices${oe} = ${f.offsetToIndices(`global_idx * 4u + ${oe}u`)}; + let offset_a${oe} = ${d.broadcastedIndicesToOffset(`output_indices${oe}`,f)}; + let offset_b${oe} = ${x.broadcastedIndicesToOffset(`output_indices${oe}`,f)}; + let offset_c${oe} = ${k.broadcastedIndicesToOffset(`output_indices${oe}`,f)}; + let index_a${oe} = offset_a${oe} / 4u; + let index_b${oe} = offset_b${oe} / 4u; + let index_c${oe} = offset_c${oe} / 4u; + let component_a${oe} = offset_a${oe} % 4u; + let component_b${oe} = offset_b${oe} % 4u; + let component_c${oe} = offset_c${oe} % 4u; + ${v}[${oe}] = ${te}(${H(de,we,be)}); + `};c===9?$=` + var data = vec4(0); + ${q("data",0,"u32")} + ${q("data",1,"u32")} + ${q("data",2,"u32")} + ${q("data",3,"u32")} + output_data[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:$=` + ${q("output_data[global_idx]",0)} + ${q("output_data[global_idx]",1)} + ${q("output_data[global_idx]",2)} + ${q("output_data[global_idx]",3)} + `}return` + ${n.registerUniform("vec_size","u32").declareVariables(k,d,x,f)} + ${n.mainStart()} + ${n.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${$} + }`},uw=n=>{let i=n[1].dims,s=n[2].dims,u=n[0].dims,c=n[1].dataType,f=!(ct.areEqual(i,s)&&ct.areEqual(s,u)),d=i,x=ct.size(i);if(f){let $=gn.calcShape(gn.calcShape(i,s,!1),u,!1);if(!$)throw new Error("Can't perform where op on the given tensors");d=$,x=ct.size(d)}let k=Math.ceil(x/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:$=>lw($,n,d,f,c),getRunData:()=>({outputs:[{dims:d,dataType:c}],dispatchGroup:{x:Math.ceil(x/64/4)},programUniforms:[{type:12,data:k},...At(u,i,s,d)]})}},cw=n=>{n.compute(uw(n.inputs))}}),dw,cx=h(()=>{nf(),zs(),tc(),of(),Oc(),sf(),af(),cd(),gm(),ff(),hf(),wf(),_m(),vf(),bf(),xf(),Bd(),Tf(),wm(),bn(),sl(),Sf(),Wd(),cr(),Jo(),$f(),$a(),nx(),ix(),ox(),sx(),ax(),lx(),Kd(),yo(),Ha(),ux(),dw=new Map([["Abs",[oc]],["Acos",[sc]],["Acosh",[Fa]],["Add",[Lc]],["ArgMax",[Gu,Os]],["ArgMin",[Wu,Os]],["Asin",[ac]],["Asinh",[lc]],["Atan",[Oa]],["Atanh",[uc]],["Attention",[Qu]],["AveragePool",[Pi,zn]],["BatchNormalization",[ec]],["BiasAdd",[Ia]],["BiasSplitGelu",[Fc]],["Cast",[Ds,cc]],["Ceil",[fc]],["Clip",[pc]],["Concat",[Ui,Kc]],["Conv",[Ko,ll]],["ConvTranspose",[pf,md]],["Cos",[za]],["Cosh",[hc]],["CumSum",[gl,wd]],["DepthToSpace",[wl,bd]],["Div",[Rc]],["Einsum",[Md,Td]],["Elu",[mc,bo]],["Equal",[Ka]],["Erf",[gc]],["Exp",[Da]],["Expand",[bl]],["FastGelu",[Ed]],["Floor",[_c]],["FusedConv",[Ko,ll]],["Gather",[Ad,$d]],["GatherElements",[zd,Od]],["Gelu",[wc]],["Gemm",[Mf,Rd]],["GlobalAveragePool",[Tn,dn]],["GlobalMaxPool",[mi,ym]],["Greater",[Uc]],["GreaterOrEqual",[Wc]],["GroupQueryAttention",[Zd,Qd]],["HardSigmoid",[Ba,Mc]],["InstanceNormalization",[rp]],["LayerNormalization",[hn]],["LeakyRelu",[yc,bo]],["Less",[Vc]],["LessOrEqual",[Xa]],["Log",[Ga]],["MatMul",[ad]],["MatMulNBits",[kf,ip]],["MaxPool",[Ks,El]],["Mul",[Bc]],["MultiHeadAttention",[Vd,jd]],["Neg",[vc]],["Not",[La]],["Pad",[Wt]],["Pow",[Nc]],["QuickGelu",[Ac,bo]],["Range",[Pf]],["Reciprocal",[bc]],["ReduceMin",[Ca]],["ReduceMean",[Lu]],["ReduceMax",[Nu]],["ReduceSum",[Uu]],["ReduceProd",[ju]],["ReduceL1",[Ru]],["ReduceL2",[Ea]],["ReduceLogSum",[Vu]],["ReduceLogSumExp",[Bu]],["ReduceSumSquare",[Pa]],["Relu",[Ra]],["Resize",[L0,R0]],["RotaryEmbedding",[j0]],["Sigmoid",[xc]],["Sin",[Tc]],["Sinh",[kc]],["Slice",[X0,Q0]],["SkipLayerNormalization",[W0]],["Split",[sw,aw]],["Sqrt",[Na]],["Softmax",[J0,ew]],["Sub",[jc]],["Tan",[Sc]],["Tanh",[Ua]],["ThresholdedRelu",[Cc,bo]],["Tile",[qd]],["Transpose",[fu,wa]],["Where",[cw]]])}),pw,dx=h(()=>{Z(),jn(),ar(),pw=class{constructor(n){this.backend=n,this.repo=new Map,this.attributesBound=!1}getArtifact(n){return this.repo.get(n)}setArtifact(n,i){this.repo.set(n,i)}run(n,i,s,u,c){et(n.programInfo.name);let f=this.backend.device,d=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let x=[];for(let $ of i)x.push({binding:x.length,resource:{buffer:$.buffer}});for(let $ of s)x.push({binding:x.length,resource:{buffer:$.buffer}});c&&x.push({binding:x.length,resource:c});let k=f.createBindGroup({layout:n.computePipeline.getBindGroupLayout(0),entries:x,label:n.programInfo.name});if(this.backend.sessionStatus==="capturing"){let $={kernelId:this.backend.currentKernelId,computePipeline:n.computePipeline,bindGroup:k,dispatchGroup:u};this.backend.capturedCommandList.get(this.backend.currentSessionId).push($)}d.setPipeline(n.computePipeline),d.setBindGroup(0,k),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(n.programInfo.name)}dispose(){}build(n,i){et(n.name);let s=this.backend.device,u=[];s.features.has("shader-f16")&&u.push("enable f16;");let c=cu(i,this.backend.device.limits),f=n.getShaderSource(c),d=`${u.join(` +`)} +${c.additionalImplementations} +${f}`,x=s.createShaderModule({code:d,label:n.name});Vr("verbose",()=>`[WebGPU] ${n.name} shader code: ${d}`);let k=s.createComputePipeline({compute:{module:x,entryPoint:"main"},layout:"auto",label:n.name});return A(n.name),{programInfo:n,computePipeline:k,uniformVariablesInfo:c.variablesInfo}}normalizeDispatchGroupSize(n){let i=typeof n=="number"?n:n.x,s=typeof n=="number"?1:n.y||1,u=typeof n=="number"?1:n.z||1,c=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(i<=c&&s<=c&&u<=c)return[i,s,u];let f=i*s*u,d=Math.ceil(Math.sqrt(f));if(d>c){if(d=Math.ceil(Math.cbrt(f)),d>c)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[d,d,d]}else return[d,d,1]}}}),fw,hw,mw,gw,px=h(()=>{Z(),Zt(),jn(),W(),Ar(),cx(),dx(),fw=(n,i)=>{if(i.length!==n.length)throw new Error(`inputDependencies length ${i.length} is not equal to inputTensors length ${n.length}.`);let s=[];for(let u=0;u{var c,f;let u=n.name;return(c=n.shaderCache)!=null&&c.hint&&(u+="["+n.shaderCache.hint+"]"),u+=":"+s+`:${fw(i,((f=n.shaderCache)==null?void 0:f.inputDependencies)??new Array(i.length).fill("dims"))}`,u},mw=class{constructor(n){n&&(this.architecture=n.architecture,this.vendor=n.vendor)}isArchitecture(n){return this.architecture===n}isVendor(n){return this.vendor===n}},gw=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 n=this.kernelCustomData.get(this.currentKernelId);return n||(n={},this.kernelCustomData.set(this.currentKernelId,n)),n}async initialize(n,i){this.env=n;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 mw(i.info||await i.requestAdapterInfo()),this.gpuDataManager=tr(this),this.programManager=new pw(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,_o(n.logLevel,!!n.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 n=this.getCommandEncoder(),i={};this.queryType==="at-passes"&&(i.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=n.beginComputePass(i)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;et(),this.endComputePass();let n;this.queryType!=="none"&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),n=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(n,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,n,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!=="none"&&n.mapAsync(GPUMapMode.READ).then(()=>{var u;let i=new BigUint64Array(n.getMappedRange()),s=this.pendingQueries.get(n);for(let c=0;c"u"&&(this.queryTimeBase=oe);let de=Number(oe-this.queryTimeBase),we=Number(te-this.queryTimeBase);if(!Number.isSafeInteger(de)||!Number.isSafeInteger(we))throw new RangeError("incorrect timestamp range");if((u=this.env.webgpu.profiling)!=null&&u.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:q.map(be=>({dims:be.dims,dataType:fi(be.dataType)})),outputsMetadata:v.map(be=>({dims:be.dims,dataType:fi(be.dataType)})),kernelId:d,kernelType:k,kernelName:$,programName:H,startTime:de,endTime:we});else{let be="";q.forEach((De,Ae)=>{be+=`input[${Ae}]: [${De.dims}] | ${fi(De.dataType)}, `});let he="";v.forEach((De,Ae)=>{he+=`output[${Ae}]: [${De.dims}] | ${fi(De.dataType)}, `}),console.log(`[profiling] kernel "${d}|${k}|${$}|${H}" ${be}${he}execution time: ${we-de} ns`)}je("GPU",`${H}::${oe}::${te}`)}n.unmap(),this.pendingQueries.delete(n)}),A()}run(n,i,s,u,c,f){et(n.name);let d=[];for(let he=0;heDe):s;if(H.length!==x.length)throw new Error(`Output size ${H.length} must be equal to ${x.length}.`);let q=[],v=[];for(let he=0;he=f)throw new Error(`Invalid output index: ${H[he]}`);if(H[he]===-3)continue;let De=H[he]===-1,Ae=H[he]===-2,Ie=De||Ae?c(x[he].dataType,x[he].dims):u(H[he],x[he].dataType,x[he].dims);if(q.push(Ie),Ie.data===0)continue;let gt=this.gpuDataManager.get(Ie.data);if(!gt)throw new Error(`no GPU data for output: ${Ie.data}`);if(De&&this.temporaryData.push(gt),Ae){let ut=this.kernelPersistentData.get(this.currentKernelId);ut||(ut=[],this.kernelPersistentData.set(this.currentKernelId,ut)),ut.push(gt)}v.push(gt)}if(d.length!==i.length||v.length!==q.length){if(v.length===0)return A(n.name),q;throw new Error(`Program ${n.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let oe;if($){let he=0,De=[];$.forEach(ut=>{let vt=typeof ut.data=="number"?[ut.data]:ut.data;if(vt.length===0)return;let Dt=ut.type===10?2:4,Rt,gr;ut.type===10?(gr=vt.length>4?16:vt.length>2?8:vt.length*Dt,Rt=vt.length>4?16:Dt*vt.length):(gr=vt.length<=2?vt.length*Dt:16,Rt=16),he=Math.ceil(he/gr)*gr,De.push(he);let Mr=ut.type===10?8:4;he+=vt.length>4?Math.ceil(vt.length/Mr)*Rt:vt.length*Dt});let Ae=16;he=Math.ceil(he/Ae)*Ae;let Ie=new ArrayBuffer(he);$.forEach((ut,vt)=>{let Dt=De[vt],Rt=typeof ut.data=="number"?[ut.data]:ut.data;if(ut.type===6)new Int32Array(Ie,Dt,Rt.length).set(Rt);else if(ut.type===12)new Uint32Array(Ie,Dt,Rt.length).set(Rt);else if(ut.type===10)new Uint16Array(Ie,Dt,Rt.length).set(Rt);else if(ut.type===1)new Float32Array(Ie,Dt,Rt.length).set(Rt);else throw new Error(`Unsupported uniform type: ${fi(ut.type)}`)});let gt=this.gpuDataManager.create(he,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(gt.buffer,0,Ie,0,he),this.gpuDataManager.release(gt.id),oe={offset:0,size:he,buffer:gt.buffer}}let te=this.programManager.normalizeDispatchGroupSize(k),de=te[1]===1&&te[2]===1,we=hw(n,i,de),be=this.programManager.getArtifact(we);if(be||(be=this.programManager.build(n,te),this.programManager.setArtifact(we,be),Vr("info",()=>`[artifact] key: ${we}, programName: ${n.name}`)),$&&be.uniformVariablesInfo){if($.length!==be.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${be.uniformVariablesInfo.length}, got ${$.length} in program "${be.programInfo.name}".`);for(let he=0;he<$.length;he++){let De=$[he],Ae=De.type,Ie=typeof De.data=="number"?1:De.data.length,[gt,ut]=be.uniformVariablesInfo[he];if(Ae!==gt||Ie!==ut)throw new Error(`Uniform variable ${he} mismatch: expect type ${gt} with size ${ut}, got type ${Ae} with size ${Ie} in program "${be.programInfo.name}".`)}}if(Vr("info",()=>`[ProgramManager] run "${n.name}" (key=${we}) with ${te[0]}x${te[1]}x${te[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let he={kernelId:this.currentKernelId,programName:be.programInfo.name,inputTensorViews:i,outputTensorViews:q};this.pendingKernels.push(he),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(he)}return this.programManager.run(be,d,v,te,oe),A(n.name),q}upload(n,i){this.gpuDataManager.upload(n,i)}memcpy(n,i){this.gpuDataManager.memcpy(n,i)}async download(n,i){await this.gpuDataManager.download(n,i)}alloc(n){return this.gpuDataManager.create(n).id}free(n){return this.gpuDataManager.release(n)}createKernel(n,i,s,u){let c=dw.get(n);if(!c)throw new Error(`kernel not implemented: ${n}`);let f={kernelType:n,kernelName:u,kernelEntry:c[0],attributes:[c[1],s]};this.kernels.set(i,f)}releaseKernel(n){let i=this.kernelPersistentData.get(n);if(i){for(let s of i)this.gpuDataManager.release(s.id);this.kernelPersistentData.delete(n)}this.kernelCustomData.delete(n),this.kernels.delete(n)}computeKernel(n,i,s){let u=this.kernels.get(n);if(!u)throw new Error(`kernel not created: ${n}`);let c=u.kernelType,f=u.kernelName,d=u.kernelEntry,x=u.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${c}] ${f}" is not allowed to be called recursively`);this.currentKernelId=n,x[0]&&(x[1]=x[0](x[1]),x[0]=void 0),Vr("info",()=>`[WebGPU] Start to run kernel "[${c}] ${f}"...`);let k=this.env.debug;this.temporaryData=[];try{return k&&this.device.pushErrorScope("validation"),d(i,x[1]),0}catch($){return s.push(Promise.resolve(`[WebGPU] Kernel "[${c}] ${f}" failed. ${$}`)),1}finally{k&&s.push(this.device.popErrorScope().then($=>$?`GPU validation error for kernel "[${c}] ${f}": ${$.message}`:null));for(let $ of this.temporaryData)this.gpuDataManager.release($.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(n,i,s,u){let c=this.sessionExternalDataMapping.get(n);c||(c=new Map,this.sessionExternalDataMapping.set(n,c));let f=c.get(i),d=this.gpuDataManager.registerExternalBuffer(s,u,f==null?void 0:f[1]);return c.set(i,[d,s]),d}unregisterBuffers(n){let i=this.sessionExternalDataMapping.get(n);i&&(i.forEach(s=>this.gpuDataManager.unregisterExternalBuffer(s[1])),this.sessionExternalDataMapping.delete(n))}getBuffer(n){let i=this.gpuDataManager.get(n);if(!i)throw new Error(`no GPU data for buffer: ${n}`);return i.buffer}createDownloader(n,i,s){return async()=>{let u=await kt(this,n,i);return Ue(u.buffer,s)}}writeTimestamp(n){this.queryType==="inside-passes"&&this.computePassEncoder.writeTimestamp(this.querySet,n)}setQueryType(){var n;this.queryType="none",(((n=this.env.webgpu.profiling)==null?void 0:n.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(){Vr("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(){Vr("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){Vr("info","replay"),this.sessionStatus="replaying";let n=this.capturedCommandList.get(this.currentSessionId),i=this.capturedPendingKernels.get(this.currentSessionId),s=n.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(n){this.unregisterBuffers(n),this.capturedCommandList.has(n)&&this.capturedCommandList.delete(n),this.capturedPendingKernels.has(n)&&this.capturedPendingKernels.delete(n),this.gpuDataManager.onReleaseSession(n)}onRunStart(n){this.currentSessionId=n,this.setQueryType()}}}),_w={};g(_w,{init:()=>yw});var Af,ww,yw,fx=h(()=>{Zt(),px(),jn(),Jt(),Af=class ex{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=ct.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=ct.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=ct.size(this.dims);return i===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,i)}reshape(i){if(ct.size(i)!==ct.size(this.dims))throw new Error("Invalid new shape");return new ex(this.module,this.dataType,this.data,i)}},ww=class{constructor(n,i,s){this.module=n,this.backend=i,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=i.adapterInfo;let u=n.HEAPU32,c=s>>>2;this.opKernelContext=u[c++];let f=u[c++];this.outputCount=u[c++],this.customDataOffset=u[c++],this.customDataSize=u[c++];let d=[];for(let x=0;xtypeof x=="number"?this.inputs[x]:x))??this.inputs,u=(i==null?void 0:i.outputs)??[],c=(x,k,$)=>new Af(this.module,k,this.output(x,$),$),f=(x,k)=>{let $=ki(x);if(!$)throw new Error(`Unsupported data type: ${x}`);let H=$*ct.size(k),q=H>0?this.backend.gpuDataManager.create(H).id:0;return new Af(this.module,x,q,k)};return this.backend.run(n,s,u,c,f,this.outputCount)}output(n,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 f=0;f{let c=i.jsepInit;if(!c)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(n==="webgpu"){let f=new gw;await f.initialize(s,u),c("webgpu",[f,d=>f.alloc(d),d=>f.free(d),(d,x,k,$=!1)=>{if($)Vr("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${d}, dst=${x}, size=${k}`),f.memcpy(d,x);else{Vr("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${d}, gpuDataId=${x}, size=${k}`);let H=i.HEAPU8.subarray(d>>>0,(d>>>0)+k);f.upload(x,H)}},async(d,x,k)=>{Vr("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${d}, dataOffset=${x}, size=${k}`),await f.download(d,()=>i.HEAPU8.subarray(x>>>0,(x>>>0)+k))},(d,x,k)=>f.createKernel(d,x,k,i.UTF8ToString(i._JsepGetNodeName(x))),d=>f.releaseKernel(d),(d,x,k,$)=>{Vr("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${k}, kernel=${d}, contextDataOffset=${x}`);let H=new ww(i,f,x);return f.computeKernel(d,H,$)},()=>f.captureBegin(),()=>f.captureEnd(),()=>f.replay()])}else c("webnn")}}),vw,xm,Mm,es,bw,If,Tm,km,Sm,Em,Cm,Pm,xw=h(()=>{Cs(),Ps(),Zt(),wn(),Ni(),jo(),vw=(n,i)=>{Gr()._OrtInit(n,i)!==0&&Dr("Can't initialize onnxruntime.")},xm=async n=>{vw(n.wasm.numThreads,Ji(n.logLevel))},Mm=async(n,i)=>{{let s=(fx(),y(_w)).init;if(i==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");let u=n.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=n.webgpu.powerPreference;if(c!==void 0&&c!=="low-power"&&c!=="high-performance")throw new Error(`Invalid powerPreference setting: "${c}"`);let f=n.webgpu.forceFallbackAdapter;if(f!==void 0&&typeof f!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${f}"`);if(u=await navigator.gpu.requestAdapter({powerPreference:c,forceFallbackAdapter:f}),!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",Gr(),n,u)}if(i==="webnn"){if(typeof navigator>"u"||!navigator.ml)throw new Error("WebNN is not supported in current environment");await s("webnn",Gr(),n)}}},es=new Map,bw=n=>{let i=Gr(),s=i.stackSave();try{let u=i.stackAlloc(8);return i._OrtGetInputOutputCount(n,u,u+4)!==0&&Dr("Can't get session input/output count."),[i.HEAP32[u/4],i.HEAP32[u/4+1]]}finally{i.stackRestore(s)}},If=n=>{let i=Gr(),s=i._malloc(n.byteLength);if(s===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${n.byteLength}.`);return i.HEAPU8.set(n,s),[s,n.byteLength]},Tm=async(n,i)=>{var q,v;let s,u,c=Gr();Array.isArray(n)?[s,u]=n:n.buffer===c.HEAPU8.buffer?[s,u]=[n.byteOffset,n.byteLength]:[s,u]=If(n);let f=0,d=0,x=0,k=[],$=[],H=[];try{if([d,k]=ji(i),(i==null?void 0:i.externalData)&&c.mountExternalData){let Ae=[];for(let Ie of i.externalData){let gt=typeof Ie=="string"?Ie:Ie.path;Ae.push(eo(typeof Ie=="string"?Ie:Ie.data).then(ut=>{c.mountExternalData(gt,ut)}))}await Promise.all(Ae)}for(let Ae of(i==null?void 0:i.executionProviders)??[])if((typeof Ae=="string"?Ae:Ae.name)==="webnn"){if(c.currentContext)throw new Error("WebNN execution provider is already set.");if(typeof Ae!="string"){let Ie=Ae,gt=Ie==null?void 0:Ie.context,ut=Ie==null?void 0:Ie.gpuDevice,vt=Ie==null?void 0:Ie.deviceType,Dt=Ie==null?void 0:Ie.numThreads,Rt=Ie==null?void 0:Ie.powerPreference;gt?c.currentContext=gt:ut?c.currentContext=await navigator.ml.createContext(ut):c.currentContext=await navigator.ml.createContext({deviceType:vt,numThreads:Dt,powerPreference:Rt})}else c.currentContext=await navigator.ml.createContext();break}f=await c._OrtCreateSession(s,u,d),f===0&&Dr("Can't create a session."),c.currentContext&&(c.currentContext=void 0);let[oe,te]=bw(f),de=!!(i!=null&&i.enableGraphCapture),we=[],be=[],he=[];for(let Ae=0;AeAe==="gpu-buffer")&&(x=c._OrtCreateBinding(f),x===0&&Dr("Can't create IO binding."),De={handle:x,outputPreferredLocations:he,outputPreferredLocationsEncoded:he.map(Ae=>mo(Ae))}),es.set(f,[f,$,H,De,de,!1]),[f,we,be]}catch(oe){throw $.forEach(te=>c._OrtFree(te)),H.forEach(te=>c._OrtFree(te)),x!==0&&c._OrtReleaseBinding(x),f!==0&&c._OrtReleaseSession(f),oe}finally{c._free(s),d!==0&&c._OrtReleaseSessionOptions(d),k.forEach(oe=>c._free(oe)),(v=c.unmountExternalData)==null||v.call(c)}},km=n=>{var k;let i=Gr(),s=es.get(n);if(!s)throw new Error(`cannot release session. invalid session id: ${n}`);let[u,c,f,d,x]=s;d&&(x&&i._OrtClearBoundOutputs(d.handle),i._OrtReleaseBinding(d.handle)),(k=i.jsepOnReleaseSession)==null||k.call(i,n),c.forEach($=>i._OrtFree($)),f.forEach($=>i._OrtFree($)),i._OrtReleaseSession(u),es.delete(n)},Sm=(n,i,s,u,c,f=!1)=>{if(!n){i.push(0);return}let d=Gr(),x=n[0],k=n[1],$=n[3],H,q;if(x==="string"&&$==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");if(f&&$!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${c} when enableGraphCapture is true.`);if($==="gpu-buffer"){let te=n[2].gpuBuffer,de=ki(fo(x));q=k.reduce((be,he)=>be*he,1)*de;let we=d.jsepRegisterBuffer;if(!we)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');H=we(u,c,te,q)}else{let te=n[2];if(Array.isArray(te)){q=4*te.length,H=d._malloc(q),s.push(H);let de=H/4;for(let we=0;wed.HEAP32[te++]=we);let de=d._OrtCreateTensor(fo(x),H,q,oe,k.length,mo($));de===0&&Dr(`Can't create tensor for input/output. session=${u}, index=${c}.`),i.push(de)}finally{d.stackRestore(v)}},Em=async(n,i,s,u,c,f)=>{var Rt,gr;let d=Gr(),x=es.get(n);if(!x)throw new Error(`cannot run inference. invalid session id: ${n}`);let k=x[0],$=x[1],H=x[2],q=x[3],v=x[4],oe=x[5],te=i.length,de=u.length,we=0,be=[],he=[],De=[],Ae=[],Ie=d.stackSave(),gt=d.stackAlloc(te*4),ut=d.stackAlloc(te*4),vt=d.stackAlloc(de*4),Dt=d.stackAlloc(de*4);try{[we,be]=Ti(f);for(let Nt=0;NtLn*Jn,1);nr=fi(kn);let lp=q==null?void 0:q.outputPreferredLocations[u[Nt]];if(nr==="string"){if(lp==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");let Ln=[],Jn=Wr/4;for(let $i=0;$i0){let Ln=d.jsepGetBuffer;if(!Ln)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let Jn=Ln(Wr),$i=ki(kn);if($i===void 0||!ho(nr))throw new Error(`Unsupported data type: ${nr}`);Vt=!0,Hr.push([nr,gi,{gpuBuffer:Jn,download:d.jsepCreateDownloader(Jn,Dn*$i,nr),dispose:()=>{d._OrtReleaseTensor(er)}},"gpu-buffer"])}else{let Ln=Si(nr),Jn=new Ln(Dn);new Uint8Array(Jn.buffer,Jn.byteOffset,Jn.byteLength).set(d.HEAPU8.subarray(Wr,Wr+Jn.byteLength)),Hr.push([nr,gi,Jn,"cpu"])}}finally{d.stackRestore(yr),nr==="string"&&Wr&&d._free(Wr),Vt||d._OrtReleaseTensor(er)}}return q&&!v&&(d._OrtClearBoundOutputs(q.handle),es.set(n,[k,$,H,q,v,!1])),Hr}finally{d.stackRestore(Ie),he.forEach(Mr=>d._OrtReleaseTensor(Mr)),De.forEach(Mr=>d._OrtReleaseTensor(Mr)),Ae.forEach(Mr=>d._free(Mr)),we!==0&&d._OrtReleaseRunOptions(we),be.forEach(Mr=>d._free(Mr))}},Cm=n=>{let i=Gr(),s=es.get(n);if(!s)throw new Error("invalid session id");let u=s[0],c=i._OrtEndProfiling(u);c===0&&Dr("Can't get an profile file name."),i._OrtFree(c)},Pm=n=>{let i=[];for(let s of n){let u=s[2];!Array.isArray(u)&&"buffer"in u&&i.push(u.buffer)}return i}}),ts,oi,Cl,sp,ap,Ff,$m,Of,Xs,Qs,Mw,Tw,kw,Sw,Ew,Cw,Pw,$w,Aw=h(()=>{Z(),xw(),wn(),Yr(),ts=()=>!!N.wasm.proxy&&typeof document<"u",Cl=!1,sp=!1,ap=!1,Of=new Map,Xs=(n,i)=>{let s=Of.get(n);s?s.push(i):Of.set(n,[i])},Qs=()=>{if(Cl||!sp||ap||!oi)throw new Error("worker not ready")},Mw=n=>{switch(n.data.type){case"init-wasm":Cl=!1,n.data.err?(ap=!0,$m[1](n.data.err)):(sp=!0,$m[0]()),Ff&&(URL.revokeObjectURL(Ff),Ff=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let i=Of.get(n.data.type);n.data.err?i.shift()[1](n.data.err):i.shift()[0](n.data.out);break}}},Tw=async()=>{if(!sp){if(Cl)throw new Error("multiple calls to 'initWasm()' detected.");if(ap)throw new Error("previous call to 'initWasm()' failed.");if(Cl=!0,ts())return new Promise((n,i)=>{oi==null||oi.terminate(),rr().then(([s,u])=>{try{oi=u,oi.onerror=f=>i(f),oi.onmessage=Mw,$m=[n,i];let c={type:"init-wasm",in:N};oi.postMessage(c),Ff=s}catch(c){i(c)}},i)});try{await Mi(N.wasm),await xm(N),sp=!0}catch(n){throw ap=!0,n}finally{Cl=!1}}},kw=async n=>{if(ts())return Qs(),new Promise((i,s)=>{Xs("init-ep",[i,s]);let u={type:"init-ep",in:{epName:n,env:N}};oi.postMessage(u)});await Mm(N,n)},Sw=async n=>ts()?(Qs(),new Promise((i,s)=>{Xs("copy-from",[i,s]);let u={type:"copy-from",in:{buffer:n}};oi.postMessage(u,[n.buffer])})):If(n),Ew=async(n,i)=>{if(ts()){if(i!=null&&i.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return Qs(),new Promise((s,u)=>{Xs("create",[s,u]);let c={type:"create",in:{model:n,options:{...i}}},f=[];n instanceof Uint8Array&&f.push(n.buffer),oi.postMessage(c,f)})}else return Tm(n,i)},Cw=async n=>{if(ts())return Qs(),new Promise((i,s)=>{Xs("release",[i,s]);let u={type:"release",in:n};oi.postMessage(u)});km(n)},Pw=async(n,i,s,u,c,f)=>{if(ts()){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 Qs(),new Promise((d,x)=>{Xs("run",[d,x]);let k=s,$={type:"run",in:{sessionId:n,inputIndices:i,inputs:k,outputIndices:u,options:f}};oi.postMessage($,Pm(k))})}else return Em(n,i,s,u,c,f)},$w=async n=>{if(ts())return Qs(),new Promise((i,s)=>{Xs("end-profiling",[i,s]);let u={type:"end-profiling",in:n};oi.postMessage(u)});Cm(n)}}),Am,Iw,Fw,hx=h(()=>{Z(),Aw(),Zt(),ve(),jo(),Am=(n,i)=>{switch(n.location){case"cpu":return[n.type,n.dims,n.data,"cpu"];case"gpu-buffer":return[n.type,n.dims,{gpuBuffer:n.gpuBuffer},"gpu-buffer"];default:throw new Error(`invalid data location: ${n.location} for ${i()}`)}},Iw=n=>{switch(n[3]){case"cpu":return new Ge(n[0],n[2],n[1]);case"gpu-buffer":{let i=n[0];if(!ho(i))throw new Error(`not supported data type: ${i} for deserializing GPU tensor`);let{gpuBuffer:s,download:u,dispose:c}=n[2];return Ge.fromGpuBuffer(s,{dataType:i,dims:n[1],download:u,dispose:c})}default:throw new Error(`invalid data location: ${n[3]}`)}},Fw=class{async fetchModelAndCopyToWasmMemory(n){return Sw(await eo(n))}async loadModel(n,i){et();let s;typeof n=="string"?s=await this.fetchModelAndCopyToWasmMemory(n):s=n,[this.sessionId,this.inputNames,this.outputNames]=await Ew(s,i),A()}async dispose(){return Cw(this.sessionId)}async run(n,i,s){et();let u=[],c=[];Object.entries(n).forEach(q=>{let v=q[0],oe=q[1],te=this.inputNames.indexOf(v);if(te===-1)throw new Error(`invalid input '${v}'`);u.push(oe),c.push(te)});let f=[],d=[];Object.entries(i).forEach(q=>{let v=q[0],oe=q[1],te=this.outputNames.indexOf(v);if(te===-1)throw new Error(`invalid output '${v}'`);f.push(oe),d.push(te)});let x=u.map((q,v)=>Am(q,()=>`input "${this.inputNames[c[v]]}"`)),k=f.map((q,v)=>q?Am(q,()=>`output "${this.outputNames[d[v]]}"`):null),$=await Pw(this.sessionId,c,x,d,k,s),H={};for(let q=0;q<$.length;q++)H[this.outputNames[d[q]]]=f[q]??Iw($[q]);return A(),H}startProfiling(){}endProfiling(){$w(this.sessionId)}}}),Ow,zw,mx=h(()=>{Z(),Aw(),hx(),Yr(),Ow=()=>{if((typeof N.wasm.initTimeout!="number"||N.wasm.initTimeout<0)&&(N.wasm.initTimeout=0),N.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 N.wasm.proxy!="boolean"&&(N.wasm.proxy=!1),typeof N.wasm.trace!="boolean"&&(N.wasm.trace=!1),typeof N.wasm.numThreads!="number"||!Number.isInteger(N.wasm.numThreads)||N.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)N.wasm.numThreads=1;else{let n=typeof navigator>"u"?_("node:os").cpus().length:navigator.hardwareConcurrency;N.wasm.numThreads=Math.min(4,Math.ceil((n||1)/2))}},zw=class{async init(n){Ow(),await Tw(),await kw(n)}async createInferenceSessionHandler(n,i){let s=new Fw;return await s.loadModel(n,i),Promise.resolve(s)}}}),Dw={};g(Dw,{wasmBackend:()=>Lw});var Lw,gx=h(()=>{mx(),Lw=new zw});Z(),Z(),Z();var _x="1.19.0",wx=Ve;{let n=(gx(),y(Dw)).wasmBackend;O("webgpu",n,5),O("webnn",n,5),O("cpu",n,10),O("wasm",n,10)}Object.defineProperty(N.versions,"web",{value:_x,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,r)=>{var o;r.r(t),r.d(t,{Tensor:()=>_.Tensor,createInferenceSession:()=>S,deviceToExecutionProviders:()=>T,isONNXProxy:()=>b,isONNXTensor:()=>C});var a=r("./src/env.js"),l=r("?2ce3"),p=r("./node_modules/onnxruntime-web/dist/ort.webgpu.bundle.min.mjs"),_=r("./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,y;if(a.apis.IS_NODE_ENV){switch(y=l??(o||(o=r.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 y=p,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 E=y.InferenceSession;function T(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 O=null;async function S(I,U){O&&await O;const z=E.create(I,U);return O??(O=z),await z}function C(I){return I instanceof y.Tensor}const w=y==null?void 0:y.env;w!=null&&w.wasm&&(w.wasm.wasmPaths=`https://cdn.jsdelivr.net/npm/@huggingface/transformers@${a.env.version}/dist/`,w.wasm.proxy=!a.apis.IS_WEBWORKER_ENV,(typeof crossOriginIsolated>"u"||!crossOriginIsolated)&&(w.wasm.numThreads=1),typeof navigator<"u"&&/iP(hone|od|ad).+16_4.+AppleWebKit/.test(navigator.userAgent)&&(w.wasm.simd=!1)),w!=null&&w.webgpu&&(w.webgpu.powerPreference="high-performance");function b(){var I;return(I=w==null?void 0:w.wasm)==null?void 0:I.proxy}a.env.backends.onnx=w},"./src/configs.js":(e,t,r)=>{r.r(t),r.d(t,{AutoConfig:()=>g,PretrainedConfig:()=>h,getKeyValueShapes:()=>_});var o=r("./src/utils/core.js"),a=r("./src/utils/hub.js");async function l(M,y){return await(0,a.getModelJSON)(M,"config.json",!0,y)}function p(M){const y={};let E={};switch(M.model_type){case"llava":case"paligemma":case"florence2":E=p(M.text_config);break;case"moondream1":E=p(M.phi_config);break;case"musicgen":E=p(M.decoder);break;case"gpt2":case"gptj":case"codegen":case"gpt_bigcode":y.num_heads="n_head",y.num_layers="n_layer",y.hidden_size="n_embd";break;case"gpt_neox":case"stablelm":case"opt":case"phi":case"phi3":case"falcon":y.num_heads="num_attention_heads",y.num_layers="num_hidden_layers",y.hidden_size="hidden_size";break;case"llama":case"cohere":case"mistral":case"starcoder2":case"qwen2":y.num_heads="num_key_value_heads",y.num_layers="num_hidden_layers",y.hidden_size="hidden_size",y.num_attention_heads="num_attention_heads";break;case"gemma":case"gemma2":y.num_heads="num_key_value_heads",y.num_layers="num_hidden_layers",y.dim_kv="head_dim";break;case"openelm":y.num_heads="num_kv_heads",y.num_layers="num_transformer_layers",y.dim_kv="head_dim";break;case"gpt_neo":case"donut-swin":y.num_heads="num_heads",y.num_layers="num_layers",y.hidden_size="hidden_size";break;case"bloom":y.num_heads="n_head",y.num_layers="n_layer",y.hidden_size="hidden_size";break;case"mpt":y.num_heads="n_heads",y.num_layers="n_layers",y.hidden_size="d_model";break;case"t5":case"mt5":case"longt5":y.num_decoder_layers="num_decoder_layers",y.num_decoder_heads="num_heads",y.decoder_dim_kv="d_kv",y.num_encoder_layers="num_layers",y.num_encoder_heads="num_heads",y.encoder_dim_kv="d_kv";break;case"bart":case"mbart":case"marian":case"whisper":case"m2m_100":case"blenderbot":case"blenderbot-small":case"florence2_language":y.num_decoder_layers="decoder_layers",y.num_decoder_heads="decoder_attention_heads",y.decoder_hidden_size="d_model",y.num_encoder_layers="encoder_layers",y.num_encoder_heads="encoder_attention_heads",y.encoder_hidden_size="d_model";break;case"speecht5":y.num_decoder_layers="decoder_layers",y.num_decoder_heads="decoder_attention_heads",y.decoder_hidden_size="hidden_size",y.num_encoder_layers="encoder_layers",y.num_encoder_heads="encoder_attention_heads",y.encoder_hidden_size="hidden_size";break;case"trocr":y.num_encoder_layers=y.num_decoder_layers="decoder_layers",y.num_encoder_heads=y.num_decoder_heads="decoder_attention_heads",y.encoder_hidden_size=y.decoder_hidden_size="d_model";break;case"musicgen_decoder":y.num_encoder_layers=y.num_decoder_layers="num_hidden_layers",y.num_encoder_heads=y.num_decoder_heads="num_attention_heads",y.encoder_hidden_size=y.decoder_hidden_size="hidden_size";break;case"vision-encoder-decoder":const O=p(M.decoder),S="num_decoder_layers"in O,C=(0,o.pick)(M,["model_type","is_encoder_decoder"]);return S?(C.num_decoder_layers=O.num_decoder_layers,C.num_decoder_heads=O.num_decoder_heads,C.decoder_hidden_size=O.decoder_hidden_size,C.num_encoder_layers=O.num_encoder_layers,C.num_encoder_heads=O.num_encoder_heads,C.encoder_hidden_size=O.encoder_hidden_size):(C.num_layers=O.num_layers,C.num_heads=O.num_heads,C.hidden_size=O.hidden_size),C}const T={...E,...(0,o.pick)(M,["model_type","multi_query","is_encoder_decoder"])};for(const O in y)T[O]=M[y[O]];return T}function _(M,{prefix:y="past_key_values"}={}){const E={},T=M.normalized_config,O=1;if(T.is_encoder_decoder&&"num_encoder_heads"in T&&"num_decoder_heads"in T){const S=T.encoder_dim_kv??T.encoder_hidden_size/T.num_encoder_heads,C=T.decoder_dim_kv??T.decoder_hidden_size/T.num_decoder_heads,w=[O,T.num_encoder_heads,0,S],b=[O,T.num_decoder_heads,0,C];for(let I=0;I{var N;r.r(t),r.d(t,{apis:()=>C,env:()=>B});var o=r("?569f"),a=r("?3f59"),l=r("?154a");const p="3.0.0-alpha.7",_=typeof self<"u",h=_&&self.constructor.name==="DedicatedWorkerGlobalScope",g=_&&"caches"in self,M=typeof navigator<"u"&&"gpu"in navigator,y=typeof navigator<"u"&&"ml"in navigator,E=typeof process<"u",T=E&&((N=process==null?void 0:process.release)==null?void 0:N.name)==="node",O=!j(o),S=!j(a),C=Object.freeze({IS_BROWSER_ENV:_,IS_WEBWORKER_ENV:h,IS_WEB_CACHE_AVAILABLE:g,IS_WEBGPU_AVAILABLE:M,IS_WEBNN_AVAILABLE:y,IS_PROCESS_AVAILABLE:E,IS_NODE_ENV:T,IS_FS_AVAILABLE:O,IS_PATH_AVAILABLE:S}),w=O&&S,b=w?a.dirname(a.dirname(l.fileURLToPath(import.meta.url))):"./",I=w?a.join(b,"/.cache/"):null,U="/models/",z=w?a.join(b,U):U,B={version:p,backends:{onnx:{},tfjs:{}},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!_,localModelPath:z,useFS:O,useBrowserCache:g,useFSCache:O,cacheDir:I,useCustomCache:!1,customCache:null};function j(ae){return Object.keys(ae).length===0}},"./src/generation/configuration_utils.js":(e,t,r)=>{r.r(t),r.d(t,{GenerationConfig:()=>a});var o=r("./src/utils/core.js");class a{constructor(p){He(this,"max_length",20);He(this,"max_new_tokens",null);He(this,"min_length",0);He(this,"min_new_tokens",null);He(this,"early_stopping",!1);He(this,"max_time",null);He(this,"do_sample",!1);He(this,"num_beams",1);He(this,"num_beam_groups",1);He(this,"penalty_alpha",null);He(this,"use_cache",!0);He(this,"temperature",1);He(this,"top_k",50);He(this,"top_p",1);He(this,"typical_p",1);He(this,"epsilon_cutoff",0);He(this,"eta_cutoff",0);He(this,"diversity_penalty",0);He(this,"repetition_penalty",1);He(this,"encoder_repetition_penalty",1);He(this,"length_penalty",1);He(this,"no_repeat_ngram_size",0);He(this,"bad_words_ids",null);He(this,"force_words_ids",null);He(this,"renormalize_logits",!1);He(this,"constraints",null);He(this,"forced_bos_token_id",null);He(this,"forced_eos_token_id",null);He(this,"remove_invalid_values",!1);He(this,"exponential_decay_length_penalty",null);He(this,"suppress_tokens",null);He(this,"begin_suppress_tokens",null);He(this,"forced_decoder_ids",null);He(this,"guidance_scale",null);He(this,"num_return_sequences",1);He(this,"output_attentions",!1);He(this,"output_hidden_states",!1);He(this,"output_scores",!1);He(this,"return_dict_in_generate",!1);He(this,"pad_token_id",null);He(this,"bos_token_id",null);He(this,"eos_token_id",null);He(this,"encoder_no_repeat_ngram_size",0);He(this,"decoder_start_token_id",null);He(this,"generation_kwargs",{});Object.assign(this,(0,o.pick)(p,Object.getOwnPropertyNames(this)))}}},"./src/generation/logits_process.js":(e,t,r)=>{r.r(t),r.d(t,{ClassifierFreeGuidanceLogitsProcessor:()=>w,ForcedBOSTokenLogitsProcessor:()=>h,ForcedEOSTokenLogitsProcessor:()=>g,LogitsProcessor:()=>l,LogitsProcessorList:()=>_,LogitsWarper:()=>p,MinLengthLogitsProcessor:()=>O,MinNewTokensLengthLogitsProcessor:()=>S,NoBadWordsLogitsProcessor:()=>C,NoRepeatNGramLogitsProcessor:()=>E,RepetitionPenaltyLogitsProcessor:()=>T,SuppressTokensAtBeginLogitsProcessor:()=>M,TemperatureLogitsWarper:()=>b,TopKLogitsWarper:()=>U,TopPLogitsWarper:()=>I,WhisperTimeStampLogitsProcessor:()=>y});var o=r("./src/utils/generic.js");r("./src/utils/tensor.js");var a=r("./src/utils/maths.js");class l extends o.Callable{_call(B,j){throw Error("`_call` should be implemented in a subclass")}}class p extends o.Callable{_call(B,j){throw Error("`_call` should be implemented in a subclass")}}class _ extends o.Callable{constructor(){super(),this.processors=[]}push(B){this.processors.push(B)}extend(B){this.processors.push(...B)}_call(B,j){let N=j;for(const ae of this.processors)N=ae(B,N);return N}[Symbol.iterator](){return this.processors.values()}}class h extends l{constructor(B){super(),this.bos_token_id=B}_call(B,j){for(let N=0;N=1&&xe[xe.length-1]>=this.timestamp_begin,_e=xe.length<2||xe[xe.length-2]>=this.timestamp_begin;if(Y&&(_e?ce.subarray(this.timestamp_begin).fill(-1/0):ce.subarray(0,this.eos_token_id).fill(-1/0)),B[N].length===this.begin_index&&this.max_initial_timestamp_index!==null){const me=this.timestamp_begin+this.max_initial_timestamp_index;ce.subarray(me+1).fill(-1/0)}const L=(0,a.log_softmax)(ce),Se=Math.log(L.subarray(this.timestamp_begin).map(Math.exp).reduce((me,X)=>me+X)),Xe=(0,a.max)(L.subarray(0,this.timestamp_begin))[0];Se>Xe&&ce.subarray(0,this.timestamp_begin).fill(-1/0)}return j}}class E extends l{constructor(B){super(),this.no_repeat_ngram_size=B}getNgrams(B){const j=B.length,N=[];for(let ce=0;ce1 to use the classifier free guidance processor, got guidance scale ${B}.`);this.guidance_scale=B}_call(B,j){if(j.dims[0]!==2*B.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 ${B.length} for the input ids.`);const N=B.length,ae=j.slice([0,N],null),ce=j.slice([N,j.dims[0]],null);for(let xe=0;xe1)throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${B}`);if(!Number.isInteger(N)||N<1)throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${N}`);this.top_p=B,this.filter_value=j,this.min_tokens_to_keep=N}}class U extends p{constructor(B,{filter_value:j=-1/0,min_tokens_to_keep:N=1}={}){if(super(),!Number.isInteger(B)||B<0)throw new Error(`\`top_k\` must be a positive integer, but is ${B}`);this.top_k=Math.max(B,N),this.filter_value=j}}},"./src/generation/logits_sampler.js":(e,t,r)=>{r.r(t),r.d(t,{LogitsSampler:()=>p});var o=r("./src/utils/generic.js"),a=r("./src/utils/tensor.js"),l=r("./src/utils/maths.js");r("./src/generation/configuration_utils.js");class p extends o.Callable{constructor(y){super(),this.generation_config=y}async _call(y){return this.sample(y)}async sample(y){throw Error("sample should be implemented in subclasses.")}getLogits(y,E){let T=y.dims.at(-1),O=y.data;if(E===-1)O=O.slice(-T);else{let S=E*T;O=O.slice(S,S+T)}return O}randomSelect(y){let E=0;for(let O=0;O1)return new g(y);if(y.num_return_sequences>1)throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${y.num_return_sequences}.`);return new _(y)}}class _ extends p{async sample(y){const E=(0,l.max)(y.data)[1];return[[BigInt(E),0]]}}class h extends p{async sample(y){let E=y.dims.at(-1);this.generation_config.top_k>0&&(E=Math.min(this.generation_config.top_k,E));const[T,O]=await(0,a.topk)(y,E),S=(0,l.softmax)(T.data);return Array.from({length:this.generation_config.num_beams},()=>{const C=this.randomSelect(S);return[O.data[C],Math.log(S[C])]})}}class g extends p{async sample(y){let E=y.dims.at(-1);this.generation_config.top_k>0&&(E=Math.min(this.generation_config.top_k,E));const[T,O]=await(0,a.topk)(y,E),S=(0,l.softmax)(T.data);return Array.from({length:this.generation_config.num_beams},(C,w)=>[O.data[w],Math.log(S[w])])}}},"./src/generation/stopping_criteria.js":(e,t,r)=>{r.r(t),r.d(t,{EosTokenCriteria:()=>_,InterruptableStoppingCriteria:()=>h,MaxLengthCriteria:()=>p,StoppingCriteria:()=>a,StoppingCriteriaList:()=>l});var o=r("./src/utils/generic.js");class a extends o.Callable{_call(M,y){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,y){const E=new Array(M.length).fill(!1);for(const T of this.criteria){const O=T(M,y);for(let S=0;Sy.length>=this.max_length)}}class _ extends a{constructor(M){super(),Array.isArray(M)||(M=[M]),this.eos_token_id=M}_call(M,y){return M.map(E=>{const T=E.at(-1);return this.eos_token_id.some(O=>T==O)})}}class h extends a{constructor(){super(),this.interrupted=!1}interrupt(){this.interrupted=!0}reset(){this.interrupted=!1}_call(M,y){return new Array(M.length).fill(this.interrupted)}}},"./src/generation/streamers.js":(e,t,r)=>{r.r(t),r.d(t,{BaseStreamer:()=>p,TextStreamer:()=>h,WhisperTextStreamer:()=>g});var o=r("./src/utils/core.js"),a=r("./src/tokenizers.js"),l=r("./src/env.js");class p{put(y){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 p{constructor(y,{skip_prompt:E=!1,callback_function:T=null,token_callback_function:O=null,decode_kwargs:S={},...C}={}){super(),this.tokenizer=y,this.skip_prompt=E,this.callback_function=T??_,this.token_callback_function=O,this.decode_kwargs={...S,...C},this.token_cache=[],this.print_len=0,this.next_tokens_are_prompt=!0}put(y){var S;if(y.length>1)throw Error("TextStreamer only supports batch size of 1");if(this.skip_prompt&&this.next_tokens_are_prompt){this.next_tokens_are_prompt=!1;return}const E=y[0];(S=this.token_callback_function)==null||S.call(this,E),this.token_cache=(0,o.mergeArrays)(this.token_cache,E);const T=this.tokenizer.decode(this.token_cache,this.decode_kwargs);let O;T.endsWith(` +`)?(O=T.slice(this.print_len),this.token_cache=[],this.print_len=0):T.length>0&&(0,a.is_chinese_char)(T.charCodeAt(T.length-1))?(O=T.slice(this.print_len),this.print_len+=O.length):(O=T.slice(this.print_len,T.lastIndexOf(" ")+1),this.print_len+=O.length),this.on_finalized_text(O,!1)}end(){let y;this.token_cache.length>0?(y=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len),this.token_cache=[],this.print_len=0):y="",this.next_tokens_are_prompt=!0,this.on_finalized_text(y,!0)}on_finalized_text(y,E){var T,O;y.length>0&&((T=this.callback_function)==null||T.call(this,y)),E&&this.callback_function===_&&l.apis.IS_PROCESS_AVAILABLE&&((O=this.callback_function)==null||O.call(this,` +`))}}class g extends h{constructor(y,{skip_prompt:E=!1,callback_function:T=null,token_callback_function:O=null,on_chunk_start:S=null,on_chunk_end:C=null,on_finalize:w=null,time_precision:b=.02,skip_special_tokens:I=!0,decode_kwargs:U={}}={}){super(y,{skip_prompt:E,callback_function:T,token_callback_function:O,decode_kwargs:{skip_special_tokens:I,...U}}),this.timestamp_begin=y.timestamp_begin,this.on_chunk_start=S,this.on_chunk_end=C,this.on_finalize=w,this.time_precision=b,this.waiting_for_timestamp=!1}put(y){var T,O;if(y.length>1)throw Error("WhisperTextStreamer only supports batch size of 1");const E=y[0];if(E.length===1){const S=Number(E[0])-this.timestamp_begin;if(S>=0){const C=S*this.time_precision;this.waiting_for_timestamp?(T=this.on_chunk_end)==null||T.call(this,C):(O=this.on_chunk_start)==null||O.call(this,C),this.waiting_for_timestamp=!this.waiting_for_timestamp,y=[[]]}}return super.put(y)}end(){var y;super.end(),(y=this.on_finalize)==null||y.call(this)}}},"./src/models.js":(e,t,r)=>{r.r(t),r.d(t,{ASTForAudioClassification:()=>$s,ASTModel:()=>zt,ASTPreTrainedModel:()=>Vn,AlbertForMaskedLM:()=>Zt,AlbertForQuestionAnswering:()=>mo,AlbertForSequenceClassification:()=>ho,AlbertModel:()=>Ji,AlbertPreTrainedModel:()=>Si,AutoModel:()=>Bd,AutoModelForAudioClassification:()=>Yd,AutoModelForAudioFrameClassification:()=>Zd,AutoModelForCTC:()=>Qd,AutoModelForCausalLM:()=>Vd,AutoModelForDepthEstimation:()=>tp,AutoModelForDocumentQuestionAnswering:()=>Tf,AutoModelForImageClassification:()=>Hd,AutoModelForImageFeatureExtraction:()=>rp,AutoModelForImageMatting:()=>Jd,AutoModelForImageSegmentation:()=>Tl,AutoModelForImageToImage:()=>ep,AutoModelForMaskGeneration:()=>kl,AutoModelForMaskedLM:()=>Wd,AutoModelForObjectDetection:()=>Kd,AutoModelForQuestionAnswering:()=>Ml,AutoModelForSemanticSegmentation:()=>qd,AutoModelForSeq2SeqLM:()=>jd,AutoModelForSequenceClassification:()=>Pn,AutoModelForSpeechSeq2Seq:()=>xl,AutoModelForTextToSpectrogram:()=>Ud,AutoModelForTextToWaveform:()=>Zo,AutoModelForTokenClassification:()=>Nd,AutoModelForVision2Seq:()=>Gd,AutoModelForXVector:()=>Sl,AutoModelForZeroShotObjectDetection:()=>Xd,BartForConditionalGeneration:()=>W,BartForSequenceClassification:()=>pe,BartModel:()=>Ue,BartPretrainedModel:()=>jn,BaseModelOutput:()=>Ke,BeitForImageClassification:()=>cc,BeitModel:()=>uc,BeitPreTrainedModel:()=>Oa,BertForMaskedLM:()=>We,BertForQuestionAnswering:()=>Ge,BertForSequenceClassification:()=>st,BertForTokenClassification:()=>pt,BertModel:()=>Be,BertPreTrainedModel:()=>Le,BlenderbotForConditionalGeneration:()=>It,BlenderbotModel:()=>kt,BlenderbotPreTrainedModel:()=>St,BlenderbotSmallForConditionalGeneration:()=>or,BlenderbotSmallModel:()=>Ar,BlenderbotSmallPreTrainedModel:()=>tr,BloomForCausalLM:()=>Gu,BloomModel:()=>Wu,BloomPreTrainedModel:()=>Fs,CLIPModel:()=>pu,CLIPPreTrainedModel:()=>Ho,CLIPSegForImageSegmentation:()=>yu,CLIPSegModel:()=>wu,CLIPSegPreTrainedModel:()=>ya,CLIPTextModelWithProjection:()=>hi,CLIPVisionModelWithProjection:()=>fu,CamembertForMaskedLM:()=>Re,CamembertForQuestionAnswering:()=>tt,CamembertForSequenceClassification:()=>qe,CamembertForTokenClassification:()=>Qe,CamembertModel:()=>ve,CamembertPreTrainedModel:()=>Z,CausalLMOutput:()=>to,CausalLMOutputWithPast:()=>kf,ChineseCLIPModel:()=>_u,ChineseCLIPPreTrainedModel:()=>gu,ClapAudioModelWithProjection:()=>pd,ClapModel:()=>cd,ClapPreTrainedModel:()=>Ko,ClapTextModelWithProjection:()=>dd,CodeGenForCausalLM:()=>As,CodeGenModel:()=>Pu,CodeGenPreTrainedModel:()=>Qn,CohereForCausalLM:()=>Iu,CohereModel:()=>Au,CoherePreTrainedModel:()=>Ta,ConvBertForMaskedLM:()=>R,ConvBertForQuestionAnswering:()=>ue,ConvBertForSequenceClassification:()=>ee,ConvBertForTokenClassification:()=>D,ConvBertModel:()=>ye,ConvBertPreTrainedModel:()=>re,ConvNextForImageClassification:()=>Fc,ConvNextModel:()=>Ic,ConvNextPreTrainedModel:()=>qa,ConvNextV2ForImageClassification:()=>Dc,ConvNextV2Model:()=>zc,ConvNextV2PreTrainedModel:()=>Oc,DPTForDepthEstimation:()=>Wa,DPTModel:()=>Va,DPTPreTrainedModel:()=>Ua,DebertaForMaskedLM:()=>Tt,DebertaForQuestionAnswering:()=>Lt,DebertaForSequenceClassification:()=>bt,DebertaForTokenClassification:()=>Et,DebertaModel:()=>ht,DebertaPreTrainedModel:()=>ft,DebertaV2ForMaskedLM:()=>Ut,DebertaV2ForQuestionAnswering:()=>rr,DebertaV2ForSequenceClassification:()=>Xt,DebertaV2ForTokenClassification:()=>Yt,DebertaV2Model:()=>Ot,DebertaV2PreTrainedModel:()=>at,DeiTForImageClassification:()=>bc,DeiTModel:()=>vc,DeiTPreTrainedModel:()=>La,DepthAnythingForDepthEstimation:()=>Cc,DepthAnythingPreTrainedModel:()=>Ec,DetrForObjectDetection:()=>pc,DetrForSegmentation:()=>fc,DetrModel:()=>dc,DetrObjectDetectionOutput:()=>za,DetrPreTrainedModel:()=>Ds,DetrSegmentationOutput:()=>hc,Dinov2ForImageClassification:()=>Rc,Dinov2Model:()=>Lc,Dinov2PreTrainedModel:()=>Zn,DistilBertForMaskedLM:()=>$t,DistilBertForQuestionAnswering:()=>mt,DistilBertForSequenceClassification:()=>Yr,DistilBertForTokenClassification:()=>$r,DistilBertModel:()=>Pr,DistilBertPreTrainedModel:()=>Ht,DonutSwinModel:()=>Ha,DonutSwinPreTrainedModel:()=>Ac,EfficientNetForImageClassification:()=>_d,EfficientNetModel:()=>gd,EfficientNetPreTrainedModel:()=>fl,ElectraForMaskedLM:()=>Ne,ElectraForQuestionAnswering:()=>Ve,ElectraForSequenceClassification:()=>dt,ElectraForTokenClassification:()=>Je,ElectraModel:()=>ke,ElectraPreTrainedModel:()=>le,EsmForMaskedLM:()=>Bi,EsmForSequenceClassification:()=>Mi,EsmForTokenClassification:()=>Gr,EsmModel:()=>un,EsmPreTrainedModel:()=>Bt,FalconForCausalLM:()=>ud,FalconModel:()=>ld,FalconPreTrainedModel:()=>ul,FastViTForImageClassification:()=>Zu,FastViTModel:()=>Yu,FastViTPreTrainedModel:()=>zs,Florence2ForConditionalGeneration:()=>_a,Florence2PreTrainedModel:()=>du,GLPNForDepthEstimation:()=>$c,GLPNModel:()=>Pc,GLPNPreTrainedModel:()=>Ga,GPT2LMHeadModel:()=>bu,GPT2Model:()=>vu,GPT2PreTrainedModel:()=>va,GPTBigCodeForCausalLM:()=>rf,GPTBigCodeModel:()=>Cu,GPTBigCodePreTrainedModel:()=>Ma,GPTJForCausalLM:()=>Eu,GPTJModel:()=>Su,GPTJPreTrainedModel:()=>xa,GPTNeoForCausalLM:()=>Mu,GPTNeoModel:()=>xu,GPTNeoPreTrainedModel:()=>Xn,GPTNeoXForCausalLM:()=>ku,GPTNeoXModel:()=>Tu,GPTNeoXPreTrainedModel:()=>ba,Gemma2ForCausalLM:()=>Du,Gemma2Model:()=>zu,Gemma2PreTrainedModel:()=>Sa,GemmaForCausalLM:()=>Ou,GemmaModel:()=>Fu,GemmaPreTrainedModel:()=>ka,HubertForCTC:()=>Jc,HubertForSequenceClassification:()=>rl,HubertModel:()=>uf,HubertPreTrainedModel:()=>lf,ImageMattingOutput:()=>ip,LlamaForCausalLM:()=>$u,LlamaModel:()=>ii,LlamaPreTrainedModel:()=>Is,LlavaForConditionalGeneration:()=>wo,LlavaPreTrainedModel:()=>cu,LongT5ForConditionalGeneration:()=>Wo,LongT5Model:()=>Vo,LongT5PreTrainedModel:()=>go,M2M100ForConditionalGeneration:()=>qc,M2M100Model:()=>Hc,M2M100PreTrainedModel:()=>Qa,MBartForCausalLM:()=>Mt,MBartForConditionalGeneration:()=>Oe,MBartForSequenceClassification:()=>rt,MBartModel:()=>Fe,MBartPreTrainedModel:()=>Ce,MPNetForMaskedLM:()=>Lo,MPNetForQuestionAnswering:()=>No,MPNetForSequenceClassification:()=>Ro,MPNetForTokenClassification:()=>Bo,MPNetModel:()=>Cs,MPNetPreTrainedModel:()=>Ti,MT5ForConditionalGeneration:()=>Vr,MT5Model:()=>Go,MT5PreTrainedModel:()=>_o,MarianMTModel:()=>Gc,MarianModel:()=>sf,MarianPreTrainedModel:()=>Xa,MaskedLMOutput:()=>bn,MistralForCausalLM:()=>Vs,MistralModel:()=>Us,MistralPreTrainedModel:()=>sl,MobileBertForMaskedLM:()=>pi,MobileBertForQuestionAnswering:()=>Ni,MobileBertForSequenceClassification:()=>Dr,MobileBertModel:()=>Kr,MobileBertPreTrainedModel:()=>wn,MobileNetV1ForImageClassification:()=>ff,MobileNetV1Model:()=>wd,MobileNetV1PreTrainedModel:()=>gl,MobileNetV2ForImageClassification:()=>vd,MobileNetV2Model:()=>yd,MobileNetV2PreTrainedModel:()=>_l,MobileNetV3ForImageClassification:()=>hf,MobileNetV3Model:()=>bd,MobileNetV3PreTrainedModel:()=>wl,MobileNetV4ForImageClassification:()=>yl,MobileNetV4Model:()=>Yo,MobileNetV4PreTrainedModel:()=>Qo,MobileViTForImageClassification:()=>nc,MobileViTModel:()=>rc,MobileViTPreTrainedModel:()=>tc,MobileViTV2ForImageClassification:()=>ic,MobileViTV2Model:()=>of,MobileViTV2PreTrainedModel:()=>Ia,ModelOutput:()=>ge,Moondream1ForConditionalGeneration:()=>ar,MptForCausalLM:()=>Hu,MptModel:()=>nf,MptPreTrainedModel:()=>Os,MusicgenForCausalLM:()=>gm,MusicgenForConditionalGeneration:()=>ml,MusicgenModel:()=>pf,MusicgenPreTrainedModel:()=>hl,NomicBertModel:()=>je,NomicBertPreTrainedModel:()=>Te,OPTForCausalLM:()=>Ku,OPTModel:()=>qu,OPTPreTrainedModel:()=>Aa,OpenELMForCausalLM:()=>Ru,OpenELMModel:()=>Lu,OpenELMPreTrainedModel:()=>Yn,OwlViTForObjectDetection:()=>sc,OwlViTModel:()=>oc,OwlViTPreTrainedModel:()=>br,Owlv2ForObjectDetection:()=>lc,Owlv2Model:()=>ac,Owlv2PreTrainedModel:()=>Fa,Phi3ForCausalLM:()=>$a,Phi3Model:()=>Vu,Phi3PreTrainedModel:()=>Pa,PhiForCausalLM:()=>Uu,PhiModel:()=>ju,PhiPreTrainedModel:()=>Ca,PreTrainedModel:()=>Q,PretrainedMixin:()=>Rr,PyAnnoteForAudioFrameClassification:()=>Gi,PyAnnoteModel:()=>Ya,PyAnnotePreTrainedModel:()=>Ei,QuestionAnsweringModelOutput:()=>xn,Qwen2ForCausalLM:()=>Nu,Qwen2Model:()=>Bu,Qwen2PreTrainedModel:()=>Ea,RTDetrForObjectDetection:()=>Ls,RTDetrModel:()=>mc,RTDetrObjectDetectionOutput:()=>gc,RTDetrPreTrainedModel:()=>bo,ResNetForImageClassification:()=>Mc,ResNetModel:()=>xc,ResNetPreTrainedModel:()=>Ra,RoFormerForMaskedLM:()=>A,RoFormerForQuestionAnswering:()=>se,RoFormerForSequenceClassification:()=>$e,RoFormerForTokenClassification:()=>Pe,RoFormerModel:()=>et,RoFormerPreTrainedModel:()=>Ye,RobertaForMaskedLM:()=>Cn,RobertaForQuestionAnswering:()=>Kn,RobertaForSequenceClassification:()=>gn,RobertaForTokenClassification:()=>ct,RobertaModel:()=>_r,RobertaPreTrainedModel:()=>qt,SamImageSegmentationOutput:()=>Wc,SamModel:()=>Vc,SamPreTrainedModel:()=>Uc,SegformerForImageClassification:()=>fd,SegformerForSemanticSegmentation:()=>hd,SegformerModel:()=>mm,SegformerPreTrainedModel:()=>Xo,Seq2SeqLMOutput:()=>wm,SequenceClassifierOutput:()=>ur,SiglipModel:()=>yo,SiglipPreTrainedModel:()=>wa,SiglipTextModel:()=>hu,SiglipVisionModel:()=>mu,SpeechT5ForSpeechToText:()=>od,SpeechT5ForTextToSpeech:()=>cf,SpeechT5HifiGan:()=>ol,SpeechT5Model:()=>id,SpeechT5PreTrainedModel:()=>il,SqueezeBertForMaskedLM:()=>fo,SqueezeBertForQuestionAnswering:()=>ki,SqueezeBertForSequenceClassification:()=>fi,SqueezeBertModel:()=>Ps,SqueezeBertPreTrainedModel:()=>ji,StableLmForCausalLM:()=>md,StableLmModel:()=>pl,StableLmPreTrainedModel:()=>dl,Starcoder2ForCausalLM:()=>ll,Starcoder2Model:()=>Ws,Starcoder2PreTrainedModel:()=>al,Swin2SRForImageSuperResolution:()=>ja,Swin2SRModel:()=>Sc,Swin2SRPreTrainedModel:()=>Na,SwinForImageClassification:()=>kc,SwinModel:()=>Tc,SwinPreTrainedModel:()=>Ba,T5ForConditionalGeneration:()=>Uo,T5Model:()=>jo,T5PreTrainedModel:()=>eo,TableTransformerForObjectDetection:()=>wc,TableTransformerModel:()=>_c,TableTransformerObjectDetectionOutput:()=>yc,TableTransformerPreTrainedModel:()=>Da,TokenClassifierOutput:()=>hn,TrOCRForCausalLM:()=>ad,TrOCRPreTrainedModel:()=>sd,UniSpeechForCTC:()=>Xc,UniSpeechForSequenceClassification:()=>Qc,UniSpeechModel:()=>Ja,UniSpeechPreTrainedModel:()=>xo,UniSpeechSatForAudioFrameClassification:()=>Bs,UniSpeechSatForCTC:()=>el,UniSpeechSatForSequenceClassification:()=>Yc,UniSpeechSatModel:()=>Rs,UniSpeechSatPreTrainedModel:()=>qo,ViTForImageClassification:()=>Qu,ViTModel:()=>Xu,ViTPreTrainedModel:()=>vo,VisionEncoderDecoderModel:()=>ga,VitMatteForImageMatting:()=>ec,VitMattePreTrainedModel:()=>Ju,VitsModel:()=>cl,VitsModelOutput:()=>Sf,VitsPreTrainedModel:()=>df,Wav2Vec2BertForCTC:()=>js,Wav2Vec2BertForSequenceClassification:()=>Zc,Wav2Vec2BertModel:()=>tl,Wav2Vec2BertPreTrainedModel:()=>Ns,Wav2Vec2ForAudioFrameClassification:()=>Wi,Wav2Vec2ForCTC:()=>af,Wav2Vec2ForSequenceClassification:()=>Vi,Wav2Vec2Model:()=>Kc,Wav2Vec2PreTrainedModel:()=>Ui,WavLMForAudioFrameClassification:()=>nd,WavLMForCTC:()=>nl,WavLMForSequenceClassification:()=>td,WavLMForXVector:()=>rd,WavLMModel:()=>ed,WavLMPreTrainedModel:()=>Ci,WeSpeakerResNetModel:()=>Za,WeSpeakerResNetPreTrainedModel:()=>vn,WhisperForConditionalGeneration:()=>ma,WhisperModel:()=>Gt,WhisperPreTrainedModel:()=>_t,XLMForQuestionAnswering:()=>yn,XLMForSequenceClassification:()=>Jt,XLMForTokenClassification:()=>Un,XLMModel:()=>cn,XLMPreTrainedModel:()=>Tr,XLMRobertaForMaskedLM:()=>At,XLMRobertaForQuestionAnswering:()=>Xr,XLMRobertaForSequenceClassification:()=>vr,XLMRobertaForTokenClassification:()=>Lr,XLMRobertaModel:()=>Er,XLMRobertaPreTrainedModel:()=>Sr,XLMWithLMHeadModel:()=>On,XVectorOutput:()=>np,YolosForObjectDetection:()=>Nc,YolosModel:()=>Bc,YolosObjectDetectionOutput:()=>jc,YolosPreTrainedModel:()=>Ka});var o=r("./src/configs.js"),a=r("./src/backends/onnx.js"),l=r("./src/utils/dtypes.js"),p=r("./src/utils/generic.js"),_=r("./src/utils/core.js"),h=r("./src/utils/hub.js"),g=r("./src/generation/logits_process.js"),M=r("./src/generation/configuration_utils.js"),y=r("./src/utils/tensor.js"),E=r("./src/utils/maths.js"),T=r("./src/generation/stopping_criteria.js"),O=r("./src/generation/logits_sampler.js"),S=r("./src/env.js"),C=r("./src/models/whisper/generation_whisper.js"),w=r("./src/models/whisper/common_whisper.js");const b={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,MaskGeneration:5,ImageTextToText:6,Musicgen:7},I=new Map,U=new Map,z=new Map;async function B(V,G,ne){let Ee=ne.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 wt=ne.dtype;typeof wt!="string"&&(wt&&wt.hasOwnProperty(G)?wt=wt[G]:(wt=l.DEFAULT_DEVICE_DTYPE_MAPPING[Ze]??l.DATA_TYPES.fp32,console.warn(`dtype not specified for "${G}". Using the default dtype (${wt}) for this device (${Ze}).`)));const Ct=wt;if(l.DEFAULT_DTYPE_SUFFIX_MAPPING.hasOwnProperty(Ct)){if(Ct===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: ${Ct}. Should be one of: ${Object.keys(l.DATA_TYPES).join(", ")}`);const Wt=l.DEFAULT_DTYPE_SUFFIX_MAPPING[Ct],cr=`${ne.subfolder??""}/${G}${Wt}.onnx`,lr={...ne.session_options};lr.executionProviders??(lr.executionProviders=it);const Ir=(0,h.getModelFile)(V,cr,!0,ne);let dr=[];if(ne.use_external_data_format&&(ne.use_external_data_format===!0||typeof ne.use_external_data_format=="object"&&ne.use_external_data_format.hasOwnProperty(G)&&ne.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 pr=`${G}${Wt}.onnx_data`,mr=`${ne.subfolder??""}/${pr}`;dr.push(new Promise(async(xr,Nr)=>{const $n=await(0,h.getModelFile)(V,mr,!0,ne);xr({path:pr,data:$n})}))}else lr.externalData!==void 0&&(dr=lr.externalData.map(async pr=>{if(typeof pr.data=="string"){const mr=await(0,h.getModelFile)(V,pr.data,!0,ne);return{...pr,data:mr}}return pr}));if(dr.length>0&&(lr.externalData=await Promise.all(dr)),Ze==="webgpu"){const pr=(0,o.getKeyValueShapes)(ne.config,{prefix:"present"});if(Object.keys(pr).length>0&&!(0,a.isONNXProxy)()){const mr={};for(const xr in pr)mr[xr]="gpu-buffer";lr.preferredOutputLocation=mr}}return{buffer:await Ir,session_options:lr}}async function j(V,G,ne){return Object.fromEntries(await Promise.all(Object.keys(G).map(async Ee=>{const{buffer:Ze,session_options:it}=await B(V,G[Ee],ne),wt=await(0,a.createInferenceSession)(Ze,it);return[Ee,wt]})))}function N(V,G){const ne=Object.create(null),Ee=[];for(const wt of V.inputNames){const Ct=G[wt];if(!(Ct instanceof y.Tensor)){Ee.push(wt);continue}ne[wt]=(0,a.isONNXProxy)()?Ct.clone():Ct}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 wt=Object.keys(G).filter(Ct=>!V.inputNames.includes(Ct));console.warn(`WARNING: Too many inputs were provided (${Ze} > ${it}). The following inputs will be ignored: "${wt.join(", ")}".`)}return ne}async function ae(V,G){const ne=N(V,G);try{const Ee=Object.fromEntries(Object.entries(ne).map(([it,wt])=>[it,wt.ort_tensor]));let Ze=await V.run(Ee);return Ze=ce(Ze),Ze}catch(Ee){throw console.error(`An error occurred during model execution: "${Ee}".`),console.error("Inputs given to model:",ne),Ee}}function ce(V){for(let G in V)(0,a.isONNXTensor)(V[G])?V[G]=new y.Tensor(V[G]):typeof V[G]=="object"&&ce(V[G]);return V}function xe(V){if(V instanceof y.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 y.Tensor("int64",BigInt64Array.from(V.flat().map(G=>BigInt(G))),[V.length,V[0].length])}else return new y.Tensor("int64",BigInt64Array.from(V.map(G=>BigInt(G))),[1,V.length])}function Y(V){return new y.Tensor("bool",[V],[1])}async function _e(V,G){let{encoder_outputs:ne,input_ids:Ee,decoder_input_ids:Ze,...it}=G;if(!ne){const Ct=(0,_.pick)(G,V.sessions.model.inputNames);ne=(await L(V,Ct)).last_hidden_state}return it.input_ids=Ze,it.encoder_hidden_states=ne,V.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(it.encoder_attention_mask=G.attention_mask),await Se(V,it,!0)}async function L(V,G){const ne=V.sessions.model,Ee=(0,_.pick)(G,ne.inputNames);if(ne.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 ne.inputNames.includes("token_type_ids")&&!Ee.token_type_ids&&(Ee.token_type_ids=new y.Tensor("int64",new BigInt64Array(Ee.input_ids.data.length),Ee.input_ids.dims)),await ae(ne,Ee)}async function Se(V,G,ne=!1){const Ee=V.sessions[ne?"decoder_model_merged":"model"],{past_key_values:Ze,...it}=G;Ee.inputNames.includes("use_cache_branch")&&(it.use_cache_branch=Y(!!Ze)),Ee.inputNames.includes("position_ids")&&it.attention_mask&&!it.position_ids&&(it.position_ids=me(it,Ze)),V.addPastKeyValues(it,Ze);const wt=(0,_.pick)(it,Ee.inputNames);return await ae(Ee,wt)}async function Xe(V,{input_ids:G=null,attention_mask:ne=null,pixel_values:Ee=null,position_ids:Ze=null,inputs_embeds:it=null,past_key_values:wt=null,generation_config:Ct=null,logits_processor:Wt=null,...cr}){if(!it){if(it=await V.encode_text({input_ids:G}),Ee&&G.dims[1]!==1){const Ir=await V.encode_image({pixel_values:Ee});({inputs_embeds:it,attention_mask:ne}=V._merge_input_ids_with_image_features({image_features:Ir,inputs_embeds:it,input_ids:G,attention_mask:ne}))}else if(wt&&Ee&&G.dims[1]===1){const Ir=G.dims[1],dr=Object.values(wt)[0].dims.at(-2);ne=(0,y.cat)([(0,y.ones)([G.dims[0],dr]),ne.slice(null,[ne.dims[1]-Ir,ne.dims[1]])],1)}}return await Se(V,{inputs_embeds:it,past_key_values:wt,attention_mask:ne,position_ids:Ze,generation_config:Ct,logits_processor:Wt},!0)}function me(V,G=null){const{input_ids:ne,inputs_embeds:Ee,attention_mask:Ze}=V,[it,wt]=Ze.dims,Ct=new BigInt64Array(Ze.data.length);for(let cr=0;crit.dims[1])){if(ZeCt==V.config.image_token_index)){const Ct=V.config.num_image_tokens;if(!Ct)throw new Error("`num_image_tokens` is missing in the model configuration.");const Wt=it.dims[1]-(Ze-Ct);ne.input_ids=it.slice(null,[-Wt,null]),ne.attention_mask=(0,y.ones)([1,Ze+Wt])}}}return ne}function ie(V,G,ne,Ee){return ne.past_key_values&&(G=G.map(Ze=>[Ze.at(-1)])),{...ne,decoder_input_ids:xe(G)}}function Me(V,...G){return V.config.is_encoder_decoder?ie(V,...G):X(V,...G)}class Q extends p.Callable{constructor(ne,Ee){super();He(this,"main_input_name","input_ids");He(this,"forward_params",["input_ids","attention_mask"]);this.config=ne,this.sessions=Ee;const Ze=z.get(this.constructor),it=I.get(Ze);switch(this.can_generate=!1,this._forward=null,this._prepare_inputs_for_generation=null,it){case b.DecoderOnly:this.can_generate=!0,this._forward=Se,this._prepare_inputs_for_generation=X;break;case b.Seq2Seq:case b.Vision2Seq:case b.Musicgen:this.can_generate=!0,this._forward=_e,this._prepare_inputs_for_generation=ie;break;case b.EncoderDecoder:this._forward=_e;break;case b.ImageTextToText:this.can_generate=!0,this._forward=Xe,this._prepare_inputs_for_generation=Me;break;default:this._forward=L;break}this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){var Ee;const ne=[];for(const Ze of Object.values(this.sessions))(Ee=Ze==null?void 0:Ze.handler)!=null&&Ee.dispose&&ne.push(Ze.handler.dispose());return await Promise.all(ne)}static async from_pretrained(ne,{progress_callback:Ee=null,config:Ze=null,cache_dir:it=null,local_files_only:wt=!1,revision:Ct="main",model_file_name:Wt=null,subfolder:cr="onnx",device:lr=null,dtype:Ir=null,use_external_data_format:dr=null,session_options:wr={}}={}){let pr={progress_callback:Ee,config:Ze,cache_dir:it,local_files_only:wt,revision:Ct,model_file_name:Wt,subfolder:cr,device:lr,dtype:Ir,use_external_data_format:dr,session_options:wr};const mr=z.get(this),xr=I.get(mr);Ze=pr.config=await o.AutoConfig.from_pretrained(ne,pr);let Nr;if(xr===b.DecoderOnly)Nr=await Promise.all([j(ne,{model:pr.model_file_name??"model"},pr),(0,h.getModelJSON)(ne,"generation_config.json",!1,pr)]);else if(xr===b.Seq2Seq||xr===b.Vision2Seq)Nr=await Promise.all([j(ne,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},pr),(0,h.getModelJSON)(ne,"generation_config.json",!1,pr)]);else if(xr===b.MaskGeneration)Nr=await Promise.all([j(ne,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},pr)]);else if(xr===b.EncoderDecoder)Nr=await Promise.all([j(ne,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},pr)]);else if(xr===b.ImageTextToText){const $n={embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};Ze.is_encoder_decoder&&($n.model="encoder_model"),Nr=await Promise.all([j(ne,$n,pr),(0,h.getModelJSON)(ne,"generation_config.json",!1,pr)])}else xr===b.Musicgen?Nr=await Promise.all([j(ne,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},pr),(0,h.getModelJSON)(ne,"generation_config.json",!1,pr)]):(xr!==b.EncoderOnly&&console.warn(`Model type for '${mr??(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.`),Nr=await Promise.all([j(ne,{model:pr.model_file_name??"model"},pr)]));return new this(Ze,...Nr)}async _call(ne){return await this.forward(ne)}async forward(ne){return await this._forward(this,ne)}_get_logits_warper(ne){const Ee=new g.LogitsProcessorList;return ne.temperature!==null&&ne.temperature!==1&&Ee.push(new g.TemperatureLogitsWarper(ne.temperature)),ne.top_k!==null&&ne.top_k!==0&&Ee.push(new g.TopKLogitsWarper(ne.top_k)),ne.top_p!==null&&ne.top_p<1&&Ee.push(new g.TopPLogitsWarper(ne.top_p)),Ee}_get_logits_processor(ne,Ee,Ze=null){const it=new g.LogitsProcessorList;if(ne.repetition_penalty!==null&&ne.repetition_penalty!==1&&it.push(new g.RepetitionPenaltyLogitsProcessor(ne.repetition_penalty)),ne.no_repeat_ngram_size!==null&&ne.no_repeat_ngram_size>0&&it.push(new g.NoRepeatNGramLogitsProcessor(ne.no_repeat_ngram_size)),ne.bad_words_ids!==null&&it.push(new g.NoBadWordsLogitsProcessor(ne.bad_words_ids,ne.eos_token_id)),ne.min_length!==null&&ne.eos_token_id!==null&&ne.min_length>0&&it.push(new g.MinLengthLogitsProcessor(ne.min_length,ne.eos_token_id)),ne.min_new_tokens!==null&&ne.eos_token_id!==null&&ne.min_new_tokens>0&&it.push(new g.MinNewTokensLengthLogitsProcessor(Ee,ne.min_new_tokens,ne.eos_token_id)),ne.forced_bos_token_id!==null&&it.push(new g.ForcedBOSTokenLogitsProcessor(ne.forced_bos_token_id)),ne.forced_eos_token_id!==null&&it.push(new g.ForcedEOSTokenLogitsProcessor(ne.max_length,ne.forced_eos_token_id)),ne.begin_suppress_tokens!==null){const wt=Ee>1||ne.forced_bos_token_id===null?Ee:Ee+1;it.push(new g.SuppressTokensAtBeginLogitsProcessor(ne.begin_suppress_tokens,wt))}return ne.guidance_scale!==null&&ne.guidance_scale>1&&it.push(new g.ClassifierFreeGuidanceLogitsProcessor(ne.guidance_scale)),Ze!==null&&it.extend(Ze),it}_prepare_generation_config(ne,Ee,Ze=M.GenerationConfig){const it={...this.config};for(const Ct of["decoder","generator","text_config"])Ct in it&&Object.assign(it,it[Ct]);const wt=new Ze(it);return"generation_config"in this&&Object.assign(wt,this.generation_config),ne&&Object.assign(wt,ne),Ee&&Object.assign(wt,(0,_.pick)(Ee,Object.getOwnPropertyNames(wt))),wt}_get_stopping_criteria(ne,Ee=null){const Ze=new T.StoppingCriteriaList;return ne.max_length!==null&&Ze.push(new T.MaxLengthCriteria(ne.max_length,this.config.max_position_embeddings??null)),ne.eos_token_id!==null&&Ze.push(new T.EosTokenCriteria(ne.eos_token_id)),Ee&&Ze.extend(Ee),Ze}_validate_model_class(){if(!this.can_generate){const ne=[Hs,bl,vl,Gs],Ee=z.get(this.constructor),Ze=new Set,it=this.config.model_type;for(const Ct of ne){const Wt=Ct.get(it);Wt&&Ze.add(Wt[0])}let wt=`The current model class (${Ee}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw Ze.size>0&&(wt+=` Please use the following class instead: ${[...Ze].join(", ")}`),Error(wt)}}prepare_inputs_for_generation(...ne){return this._prepare_inputs_for_generation(this,...ne)}_update_model_kwargs_for_generation({generated_input_ids:ne,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 y.Tensor("int64",ne.flat(),[ne.length,1]),it||(Ze.attention_mask=(0,y.cat)([Ze.attention_mask,(0,y.ones)([Ze.attention_mask.dims[0],1])],1)),Ze.position_ids=null,Ze}_prepare_model_inputs({inputs:ne,bos_token_id:Ee,model_kwargs:Ze}){const it=(0,_.pick)(Ze,this.forward_params),wt=this.main_input_name;if(wt in it){if(ne)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[wt]=ne;return{inputs_tensor:it[wt],model_inputs:it,model_input_name:wt}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:ne,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:Ct,pixel_values:Wt,attention_mask:cr,...lr}=Ee,Ir=await this._prepare_inputs_embeds(Ee);Ee={...lr,...(0,_.pick)(Ir,["inputs_embeds","attention_mask"])}}let{last_hidden_state:wt}=await L(this,Ee);if(it.guidance_scale!==null&&it.guidance_scale>1)wt=(0,y.cat)([wt,(0,y.full_like)(wt,0)],0),"attention_mask"in Ee&&(Ee.attention_mask=(0,y.cat)([Ee.attention_mask,(0,y.zeros_like)(Ee.attention_mask)],0));else if(Ee.decoder_input_ids){const Ct=xe(Ee.decoder_input_ids).dims[0];if(Ct!==wt.dims[0]){if(wt.dims[0]!==1)throw new Error(`The encoder outputs have a different batch size (${wt.dims[0]}) than the decoder inputs (${Ct}).`);wt=(0,y.cat)(Array.from({length:Ct},()=>wt),0)}}return Ee.encoder_outputs=wt,Ee}_prepare_decoder_input_ids_for_generation({batch_size:ne,model_input_name:Ee,model_kwargs:Ze,decoder_start_token_id:it,bos_token_id:wt,generation_config:Ct}){let{decoder_input_ids:Wt,...cr}=Ze;if(Wt)Array.isArray(Wt[0])||(Wt=Array.from({length:ne},()=>Wt));else if(it??(it=wt),this.config.model_type==="musicgen")Wt=Array.from({length:ne*this.config.decoder.num_codebooks},()=>[it]);else if(Array.isArray(it)){if(it.length!==ne)throw new Error(`\`decoder_start_token_id\` expcted to have length ${ne} but got ${it.length}`);Wt=it}else Wt=Array.from({length:ne},()=>[it]);return Wt=xe(Wt),Ze.decoder_attention_mask=(0,y.ones_like)(Wt),{input_ids:Wt,model_inputs:cr}}async generate({inputs:ne=null,generation_config:Ee=null,logits_processor:Ze=null,stopping_criteria:it=null,streamer:wt=null,...Ct}){this._validate_model_class(),Ee=this._prepare_generation_config(Ee,Ct);let{inputs_tensor:Wt,model_inputs:cr,model_input_name:lr}=this._prepare_model_inputs({inputs:ne,model_kwargs:Ct});const Ir=this.config.is_encoder_decoder;Ir&&("encoder_outputs"in cr||(cr=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:Wt,model_inputs:cr,model_input_name:lr,generation_config:Ee})));let dr;Ir?{input_ids:dr,model_inputs:cr}=this._prepare_decoder_input_ids_for_generation({batch_size:cr[lr].dims.at(0),model_input_name:lr,model_kwargs:cr,decoder_start_token_id:Ee.decoder_start_token_id,bos_token_id:Ee.bos_token_id,generation_config:Ee}):dr=cr[lr];let wr=dr.dims.at(-1);Ee.max_new_tokens!==null&&(Ee.max_length=wr+Ee.max_new_tokens);const pr=this._get_logits_processor(Ee,wr,Ze),mr=this._get_stopping_criteria(Ee,it),xr=cr[lr].dims.at(0),Nr=O.LogitsSampler.getSampler(Ee),$n=new Array(xr).fill(0),zn=dr.tolist();wt&&wt.put(zn);let Pi=null,Mn={};for(;;){cr=this.prepare_inputs_for_generation(zn,cr,Ee);const Tn=await this.forward(cr);if(Ee.output_attentions&&Ee.return_dict_in_generate){const mi=this.getAttentions(Tn);for(const Jo in mi)Jo in Mn||(Mn[Jo]=[]),Mn[Jo].push(mi[Jo])}const qs=Tn.logits.slice(null,-1,null),Ks=pr(zn,qs),El=[];for(let mi=0;mimi)){Ee.return_dict_in_generate&&(Pi=this.getPastKeyValues(Tn,cr.past_key_values,!1));break}cr=this._update_model_kwargs_for_generation({generated_input_ids:El,outputs:Tn,model_inputs:cr,is_encoder_decoder:Ir})}wt&&wt.end();const dn=new y.Tensor("int64",zn.flat(),[zn.length,zn[0].length]);return Ee.return_dict_in_generate?{sequences:dn,past_key_values:Pi,...Mn}:dn}getPastKeyValues(ne,Ee,Ze=!0){const it=Object.create(null);for(const wt in ne)if(wt.startsWith("present")){const Ct=wt.replace("present","past_key_values");if(Ee&&wt.includes("encoder"))it[Ct]=Ee[Ct];else{if(Ze&&Ee){const Wt=Ee[Ct];Wt.location==="gpu-buffer"&&Wt.dispose()}it[Ct]=ne[wt]}}return it}getAttentions(ne){const Ee={};for(const Ze of["cross_attentions","encoder_attentions","decoder_attentions"])for(const it in ne)it.startsWith(Ze)&&(Ze in Ee||(Ee[Ze]=[]),Ee[Ze].push(ne[it]));return Ee}addPastKeyValues(ne,Ee){if(Ee)Object.assign(ne,Ee);else{const Ze=this.custom_config.kv_cache_dtype??"float32",it=Ze==="float16"?new Uint16Array:[],wt=(0,o.getKeyValueShapes)(this.config);for(const Ct in wt)ne[Ct]=new y.Tensor(Ze,it,wt[Ct])}}async encode_image({pixel_values:ne}){const Ee=(await ae(this.sessions.vision_encoder,{pixel_values:ne})).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:ne}){return(await ae(this.sessions.embed_tokens,{input_ids:ne})).inputs_embeds}}class ge{}class Ke extends ge{constructor({last_hidden_state:G,hidden_states:ne=null,attentions:Ee=null}){super(),this.last_hidden_state=G,this.hidden_states=ne,this.attentions=Ee}}class Le extends Q{}class Be extends Le{}class We extends Le{async _call(G){return new bn(await super._call(G))}}class st extends Le{async _call(G){return new ur(await super._call(G))}}class pt extends Le{async _call(G){return new hn(await super._call(G))}}class Ge extends Le{async _call(G){return new xn(await super._call(G))}}class Te extends Q{}class je extends Te{}class Ye extends Q{}class et extends Ye{}class A extends Ye{async _call(G){return new bn(await super._call(G))}}class $e extends Ye{async _call(G){return new ur(await super._call(G))}}class Pe extends Ye{async _call(G){return new hn(await super._call(G))}}class se extends Ye{async _call(G){return new xn(await super._call(G))}}class re extends Q{}class ye extends re{}class R extends re{async _call(G){return new bn(await super._call(G))}}class ee extends re{async _call(G){return new ur(await super._call(G))}}class D extends re{async _call(G){return new hn(await super._call(G))}}class ue extends re{async _call(G){return new xn(await super._call(G))}}class le extends Q{}class ke extends le{}class Ne extends le{async _call(G){return new bn(await super._call(G))}}class dt extends le{async _call(G){return new ur(await super._call(G))}}class Je extends le{async _call(G){return new hn(await super._call(G))}}class Ve extends le{async _call(G){return new xn(await super._call(G))}}class Z extends Q{}class ve extends Z{}class Re extends Z{async _call(G){return new bn(await super._call(G))}}class qe extends Z{async _call(G){return new ur(await super._call(G))}}class Qe extends Z{async _call(G){return new hn(await super._call(G))}}class tt extends Z{async _call(G){return new xn(await super._call(G))}}class ft extends Q{}class ht extends ft{}class Tt extends ft{async _call(G){return new bn(await super._call(G))}}class bt extends ft{async _call(G){return new ur(await super._call(G))}}class Et extends ft{async _call(G){return new hn(await super._call(G))}}class Lt extends ft{async _call(G){return new xn(await super._call(G))}}class at extends Q{}class Ot extends at{}class Ut extends at{async _call(G){return new bn(await super._call(G))}}class Xt extends at{async _call(G){return new ur(await super._call(G))}}class Yt extends at{async _call(G){return new hn(await super._call(G))}}class rr extends at{async _call(G){return new xn(await super._call(G))}}class Ht extends Q{}class Pr extends Ht{}class Yr extends Ht{async _call(G){return new ur(await super._call(G))}}class $r extends Ht{async _call(G){return new hn(await super._call(G))}}class mt extends Ht{async _call(G){return new xn(await super._call(G))}}class $t extends Ht{async _call(G){return new bn(await super._call(G))}}class Bt extends Q{}class un extends Bt{}class Bi extends Bt{async _call(G){return new bn(await super._call(G))}}class Mi extends Bt{async _call(G){return new ur(await super._call(G))}}class Gr extends Bt{async _call(G){return new hn(await super._call(G))}}class wn extends Q{}class Kr extends wn{}class pi extends wn{async _call(G){return new bn(await super._call(G))}}class Dr extends wn{async _call(G){return new ur(await super._call(G))}}class Ni extends wn{async _call(G){return new xn(await super._call(G))}}class Ti extends Q{}class Cs extends Ti{}class Lo extends Ti{async _call(G){return new bn(await super._call(G))}}class Ro extends Ti{async _call(G){return new ur(await super._call(G))}}class Bo extends Ti{async _call(G){return new hn(await super._call(G))}}class No extends Ti{async _call(G){return new xn(await super._call(G))}}class ji extends Q{}class Ps extends ji{}class fo extends ji{async _call(G){return new bn(await super._call(G))}}class fi extends ji{async _call(G){return new ur(await super._call(G))}}class ki extends ji{async _call(G){return new xn(await super._call(G))}}class Si extends Q{}class Ji extends Si{}class ho extends Si{async _call(G){return new ur(await super._call(G))}}class mo extends Si{async _call(G){return new xn(await super._call(G))}}class Zt extends Si{async _call(G){return new bn(await super._call(G))}}class eo extends Q{constructor(ne,Ee,Ze){super(ne,Ee);He(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"]);this.generation_config=Ze}}class jo extends eo{}class Uo extends eo{}class go extends Q{constructor(G,ne,Ee){super(G,ne),this.generation_config=Ee}}class Vo extends go{}class Wo extends go{}class _o extends Q{constructor(G,ne,Ee){super(G,ne),this.generation_config=Ee}}class Go extends _o{}class Vr extends _o{}class jn extends Q{constructor(G,ne,Ee){super(G,ne),this.generation_config=Ee}}class Ue extends jn{}class W extends jn{}class pe extends jn{async _call(G){return new ur(await super._call(G))}}class Ce extends Q{constructor(G,ne,Ee){super(G,ne),this.generation_config=Ee}}class Fe extends Ce{}class Oe extends Ce{}class rt extends Ce{async _call(G){return new ur(await super._call(G))}}class Mt extends Ce{}class St extends Q{constructor(G,ne,Ee){super(G,ne),this.generation_config=Ee}}class kt extends St{}class It extends St{}class tr extends Q{constructor(G,ne,Ee){super(G,ne),this.generation_config=Ee}}class Ar extends tr{}class or extends tr{}class qt extends Q{}class _r extends qt{}class Cn extends qt{async _call(G){return new bn(await super._call(G))}}class gn extends qt{async _call(G){return new ur(await super._call(G))}}class ct extends qt{async _call(G){return new hn(await super._call(G))}}class Kn extends qt{async _call(G){return new xn(await super._call(G))}}class Tr extends Q{}class cn extends Tr{}class On extends Tr{async _call(G){return new bn(await super._call(G))}}class Jt extends Tr{async _call(G){return new ur(await super._call(G))}}class Un extends Tr{async _call(G){return new hn(await super._call(G))}}class yn extends Tr{async _call(G){return new xn(await super._call(G))}}class Sr extends Q{}class Er extends Sr{}class At extends Sr{async _call(G){return new bn(await super._call(G))}}class vr extends Sr{async _call(G){return new ur(await super._call(G))}}class Lr extends Sr{async _call(G){return new hn(await super._call(G))}}class Xr extends Sr{async _call(G){return new xn(await super._call(G))}}class Vn extends Q{}class zt extends Vn{}class $s extends Vn{}class _t extends Q{constructor(ne,Ee,Ze){super(ne,Ee);He(this,"requires_attention_mask",!1);He(this,"main_input_name","input_features");He(this,"forward_params",["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"]);this.generation_config=Ze}}class Gt extends _t{}class ma extends _t{_prepare_generation_config(G,ne){return super._prepare_generation_config(G,ne,C.WhisperGenerationConfig)}_retrieve_init_tokens(G){const ne=[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 wt=`<|${(0,w.whisper_language_to_code)(Ee)}|>`;ne.push(G.lang_to_id[wt]),ne.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&&ne.at(-1)!==G.no_timestamps_token_id?ne.push(G.no_timestamps_token_id):G.return_timestamps&&ne.at(-1)===G.no_timestamps_token_id&&(console.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),ne.pop()),ne.filter(it=>it!=null)}async generate({inputs:G=null,generation_config:ne=null,logits_processor:Ee=null,stopping_criteria:Ze=null,...it}){ne=this._prepare_generation_config(ne,it);const wt=it.decoder_input_ids??this._retrieve_init_tokens(ne);if(ne.return_timestamps&&(Ee??(Ee=new g.LogitsProcessorList),Ee.push(new g.WhisperTimeStampLogitsProcessor(ne,wt))),ne.begin_suppress_tokens&&(Ee??(Ee=new g.LogitsProcessorList),Ee.push(new g.SuppressTokensAtBeginLogitsProcessor(ne.begin_suppress_tokens,wt.length))),ne.return_token_timestamps){if(!ne.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.");ne.task==="translate"&&console.warn("Token-level timestamps may not be reliable for task 'translate'."),ne.output_attentions=!0,ne.return_dict_in_generate=!0}const Ct=await super.generate({inputs:G,generation_config:ne,logits_processor:Ee,decoder_input_ids:wt,...it});return ne.return_token_timestamps&&(Ct.token_timestamps=this._extract_token_timestamps(Ct,ne.alignment_heads,ne.num_frames)),Ct}_extract_token_timestamps(G,ne,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 wt=G.cross_attentions,Ct=Array.from({length:this.config.decoder_layers},(mr,xr)=>(0,y.cat)(wt.map(Nr=>Nr[xr]),2)),Wt=(0,y.stack)(ne.map(([mr,xr])=>{if(mr>=Ct.length)throw new Error(`Layer index ${mr} is out of bounds for cross attentions (length ${Ct.length}).`);return Ee?Ct[mr].slice(null,xr,null,[0,Ee]):Ct[mr].slice(null,xr)})).transpose(1,0,2,3),[cr,lr]=(0,y.std_mean)(Wt,-2,0,!0),Ir=Wt.clone();for(let mr=0;mrNr[Tn+1]-Nr[Tn]),Pi=(0,_.mergeArrays)([1],zn).map(dn=>!!dn),Mn=[];for(let dn=0;dndr.findIndex(wr=>wr==it)),Wt=Ct.every(dr=>dr===-1),cr=Ct.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 lr=[],Ir=[];for(let dr=0;drit*wt,1);G.input_labels=new y.Tensor("int64",new BigInt64Array(Ze).fill(1n),Ee)}const ne={image_embeddings:G.image_embeddings,image_positional_embeddings:G.image_positional_embeddings};return G.input_points&&(ne.input_points=G.input_points),G.input_labels&&(ne.input_labels=G.input_labels),G.input_boxes&&(ne.input_boxes=G.input_boxes),await ae(this.sessions.prompt_encoder_mask_decoder,ne)}async _call(G){return new Wc(await super._call(G))}}class Wc extends ge{constructor({iou_scores:G,pred_masks:ne}){super(),this.iou_scores=G,this.pred_masks=ne}}class Xa extends Q{constructor(G,ne,Ee){super(G,ne),this.generation_config=Ee}}class sf extends Xa{}class Gc extends Xa{}class Qa extends Q{constructor(G,ne,Ee){super(G,ne),this.generation_config=Ee}}class Hc extends Qa{}class qc extends Qa{}class Ui extends Q{}class Kc extends Ui{}class af extends Ui{async _call(G){return new to(await super._call(G))}}class Vi extends Ui{async _call(G){return new ur(await super._call(G))}}class Wi extends Ui{async _call(G){return new hn(await super._call(G))}}class Ei extends Q{}class Ya extends Ei{}class Gi extends Ei{async _call(G){return new hn(await super._call(G))}}class vn extends Q{}class Za extends vn{}class xo extends Q{}class Ja extends xo{}class Xc extends xo{async _call(G){return new to(await super._call(G))}}class Qc extends xo{async _call(G){return new ur(await super._call(G))}}class qo extends Q{}class Rs extends qo{}class el extends qo{async _call(G){return new to(await super._call(G))}}class Yc extends qo{async _call(G){return new ur(await super._call(G))}}class Bs extends qo{async _call(G){return new hn(await super._call(G))}}class Ns extends Q{}class tl extends Ns{}class js extends Ns{async _call(G){return new to(await super._call(G))}}class Zc extends Ns{async _call(G){return new ur(await super._call(G))}}class lf extends Q{}class uf extends Ui{}class Jc extends Ui{async _call(G){return new to(await super._call(G))}}class rl extends Ui{async _call(G){return new ur(await super._call(G))}}class Ci extends Q{}class ed extends Ci{}class nl extends Ci{async _call(G){return new to(await super._call(G))}}class td extends Ci{async _call(G){return new ur(await super._call(G))}}class rd extends Ci{async _call(G){return new np(await super._call(G))}}class nd extends Ci{async _call(G){return new hn(await super._call(G))}}class il extends Q{constructor(G,ne,Ee){super(G,ne),this.generation_config=Ee}}class id extends il{}class od extends il{}class cf extends il{async generate_speech(G,ne,{threshold:Ee=.5,minlenratio:Ze=0,maxlenratio:it=20,vocoder:wt=null}={}){const Ct={input_ids:G},{encoder_outputs:Wt,encoder_attention_mask:cr}=await L(this,Ct),lr=Wt.dims[1]/this.config.reduction_factor,Ir=Math.floor(lr*it),dr=Math.floor(lr*Ze),wr=this.config.num_mel_bins;let pr=[],mr=null,xr=null,Nr=0;for(;;){++Nr;const Pi=Y(!!xr);let Mn;xr?Mn=xr.output_sequence_out:Mn=new y.Tensor("float32",new Float32Array(wr),[1,1,wr]);let dn={use_cache_branch:Pi,output_sequence:Mn,encoder_attention_mask:cr,speaker_embeddings:ne,encoder_hidden_states:Wt};this.addPastKeyValues(dn,mr),xr=await ae(this.sessions.decoder_model_merged,dn),mr=this.getPastKeyValues(xr,mr);const{prob:Tn,spectrum:qs}=xr;if(pr.push(qs),Nr>=dr&&(Array.from(Tn.data).filter(Ks=>Ks>=Ee).length>0||Nr>=Ir))break}const $n=(0,y.cat)(pr),{waveform:zn}=await ae(wt.sessions.model,{spectrogram:$n});return{spectrogram:$n,waveform:zn}}}class ol extends Q{constructor(){super(...arguments);He(this,"main_input_name","spectrogram")}}class sd extends Q{constructor(G,ne,Ee){super(G,ne),this.generation_config=Ee}}class ad extends sd{}class sl extends Q{constructor(G,ne,Ee){super(G,ne),this.generation_config=Ee}}class Us extends sl{}class Vs extends sl{}class al extends Q{constructor(G,ne,Ee){super(G,ne),this.generation_config=Ee}}class Ws extends al{}class ll extends al{}class ul extends Q{constructor(G,ne,Ee){super(G,ne),this.generation_config=Ee}}class ld extends ul{}class ud extends ul{}class Ko extends Q{}class cd extends Ko{}class dd extends Ko{static async from_pretrained(G,ne={}){return ne.model_file_name??(ne.model_file_name="text_model"),super.from_pretrained(G,ne)}}class pd extends Ko{static async from_pretrained(G,ne={}){return ne.model_file_name??(ne.model_file_name="audio_model"),super.from_pretrained(G,ne)}}class df extends Q{}class cl extends df{async _call(G){return new Sf(await super._call(G))}}class Xo extends Q{}class mm extends Xo{}class fd extends Xo{}class hd extends Xo{}class dl extends Q{constructor(G,ne,Ee){super(G,ne),this.generation_config=Ee}}class pl extends dl{}class md extends dl{}class fl extends Q{}class gd extends fl{}class _d extends fl{async _call(G){return new ur(await super._call(G))}}class hl extends Q{}class pf extends hl{}class gm extends hl{}class ml extends Q{constructor(ne,Ee,Ze){super(ne,Ee);He(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(ne){const[Ee,Ze]=ne.dims,it=this.config.decoder.num_codebooks,wt=Ze-it;let Ct=0;for(let lr=0;lr0&&wr<=wt&&(ne.data[Ct++]=ne.data[lr])}const Wt=Math.floor(Ee/it),cr=Ct/(Wt*it);return new y.Tensor(ne.type,ne.data.slice(0,Ct),[Wt,it,cr])}prepare_inputs_for_generation(ne,Ee,Ze){let it=structuredClone(ne);for(let Ct=0;Ct=Wt&&(it[Ct][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(ne){const Ee=await super.generate(ne),Ze=this._apply_and_filter_by_delay_pattern_mask(Ee).unsqueeze_(0),{audio_values:it}=await ae(this.sessions.encodec_decode,{audio_codes:Ze});return it}}class gl extends Q{}class wd extends gl{}class ff extends gl{async _call(G){return new ur(await super._call(G))}}class _l extends Q{}class yd extends _l{}class vd extends _l{async _call(G){return new ur(await super._call(G))}}class wl extends Q{}class bd extends wl{}class hf extends wl{async _call(G){return new ur(await super._call(G))}}class Qo extends Q{}class Yo extends Qo{}class yl extends Qo{async _call(G){return new ur(await super._call(G))}}class Rr{static async from_pretrained(G,{progress_callback:ne=null,config:Ee=null,cache_dir:Ze=null,local_files_only:it=!1,revision:wt="main",model_file_name:Ct=null,subfolder:Wt="onnx",device:cr=null,dtype:lr=null,use_external_data_format:Ir=null,session_options:dr={}}={}){let wr={progress_callback:ne,config:Ee,cache_dir:Ze,local_files_only:it,revision:wt,model_file_name:Ct,subfolder:Wt,device:cr,dtype:lr,use_external_data_format:Ir,session_options:dr};if(wr.config=await o.AutoConfig.from_pretrained(G,wr),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);for(let pr of this.MODEL_CLASS_MAPPINGS){const mr=pr.get(wr.config.model_type);if(mr)return await mr[1].from_pretrained(G,wr)}if(this.BASE_IF_FAIL)return console.warn(`Unknown model class "${wr.config.model_type}", attempting to construct from base class.`),await Q.from_pretrained(G,wr);throw Error(`Unsupported model type: ${wr.config.model_type}`)}}He(Rr,"MODEL_CLASS_MAPPINGS",null),He(Rr,"BASE_IF_FAIL",!1);const mf=new Map([["bert",["BertModel",Be]],["nomic_bert",["NomicBertModel",je]],["roformer",["RoFormerModel",et]],["electra",["ElectraModel",ke]],["esm",["EsmModel",un]],["convbert",["ConvBertModel",ye]],["camembert",["CamembertModel",ve]],["deberta",["DebertaModel",ht]],["deberta-v2",["DebertaV2Model",Ot]],["mpnet",["MPNetModel",Cs]],["albert",["AlbertModel",Ji]],["distilbert",["DistilBertModel",Pr]],["roberta",["RobertaModel",_r]],["xlm",["XLMModel",cn]],["xlm-roberta",["XLMRobertaModel",Er]],["clap",["ClapModel",cd]],["clip",["CLIPModel",pu]],["clipseg",["CLIPSegModel",wu]],["chinese_clip",["ChineseCLIPModel",_u]],["siglip",["SiglipModel",yo]],["mobilebert",["MobileBertModel",Kr]],["squeezebert",["SqueezeBertModel",Ps]],["wav2vec2",["Wav2Vec2Model",Kc]],["wav2vec2-bert",["Wav2Vec2BertModel",tl]],["unispeech",["UniSpeechModel",Ja]],["unispeech-sat",["UniSpeechSatModel",Rs]],["hubert",["HubertModel",uf]],["wavlm",["WavLMModel",ed]],["audio-spectrogram-transformer",["ASTModel",zt]],["vits",["VitsModel",cl]],["pyannote",["PyAnnoteModel",Ya]],["wespeaker-resnet",["WeSpeakerResNetModel",Za]],["detr",["DetrModel",dc]],["rt_detr",["RTDetrModel",mc]],["table-transformer",["TableTransformerModel",_c]],["vit",["ViTModel",Xu]],["fastvit",["FastViTModel",Yu]],["mobilevit",["MobileViTModel",rc]],["mobilevitv2",["MobileViTV2Model",of]],["owlvit",["OwlViTModel",oc]],["owlv2",["Owlv2Model",ac]],["beit",["BeitModel",uc]],["deit",["DeiTModel",vc]],["convnext",["ConvNextModel",Ic]],["convnextv2",["ConvNextV2Model",zc]],["dinov2",["Dinov2Model",Lc]],["resnet",["ResNetModel",xc]],["swin",["SwinModel",Tc]],["swin2sr",["Swin2SRModel",Sc]],["donut-swin",["DonutSwinModel",Ha]],["yolos",["YolosModel",Bc]],["dpt",["DPTModel",Va]],["glpn",["GLPNModel",Pc]],["hifigan",["SpeechT5HifiGan",ol]],["efficientnet",["EfficientNetModel",gd]],["mobilenet_v1",["MobileNetV1Model",wd]],["mobilenet_v2",["MobileNetV2Model",yd]],["mobilenet_v3",["MobileNetV3Model",bd]],["mobilenet_v4",["MobileNetV4Model",Yo]]]),gf=new Map([["t5",["T5Model",jo]],["longt5",["LongT5Model",Vo]],["mt5",["MT5Model",Go]],["bart",["BartModel",Ue]],["mbart",["MBartModel",Fe]],["marian",["MarianModel",sf]],["whisper",["WhisperModel",Gt]],["m2m_100",["M2M100Model",Hc]],["blenderbot",["BlenderbotModel",kt]],["blenderbot-small",["BlenderbotSmallModel",Ar]]]),_f=new Map([["bloom",["BloomModel",Wu]],["gpt2",["GPT2Model",vu]],["gptj",["GPTJModel",Su]],["gpt_bigcode",["GPTBigCodeModel",Cu]],["gpt_neo",["GPTNeoModel",xu]],["gpt_neox",["GPTNeoXModel",Tu]],["codegen",["CodeGenModel",Pu]],["llama",["LlamaModel",ii]],["cohere",["CohereModel",Au]],["gemma",["GemmaModel",Fu]],["gemma2",["Gemma2Model",zu]],["openelm",["OpenELMModel",Lu]],["qwen2",["Qwen2Model",Bu]],["phi",["PhiModel",ju]],["phi3",["Phi3Model",Vu]],["mpt",["MptModel",nf]],["opt",["OPTModel",qu]],["mistral",["MistralModel",Us]],["starcoder2",["Starcoder2Model",Ws]],["falcon",["FalconModel",ld]],["stablelm",["StableLmModel",pl]]]),Gs=new Map([["speecht5",["SpeechT5ForSpeechToText",od]],["whisper",["WhisperForConditionalGeneration",ma]]]),xd=new Map([["speecht5",["SpeechT5ForTextToSpeech",cf]]]),Md=new Map([["vits",["VitsModel",cl]],["musicgen",["MusicgenForConditionalGeneration",ml]]]),Td=new Map([["bert",["BertForSequenceClassification",st]],["roformer",["RoFormerForSequenceClassification",$e]],["electra",["ElectraForSequenceClassification",dt]],["esm",["EsmForSequenceClassification",Mi]],["convbert",["ConvBertForSequenceClassification",ee]],["camembert",["CamembertForSequenceClassification",qe]],["deberta",["DebertaForSequenceClassification",bt]],["deberta-v2",["DebertaV2ForSequenceClassification",Xt]],["mpnet",["MPNetForSequenceClassification",Ro]],["albert",["AlbertForSequenceClassification",ho]],["distilbert",["DistilBertForSequenceClassification",Yr]],["roberta",["RobertaForSequenceClassification",gn]],["xlm",["XLMForSequenceClassification",Jt]],["xlm-roberta",["XLMRobertaForSequenceClassification",vr]],["bart",["BartForSequenceClassification",pe]],["mbart",["MBartForSequenceClassification",rt]],["mobilebert",["MobileBertForSequenceClassification",Dr]],["squeezebert",["SqueezeBertForSequenceClassification",fi]]]),wf=new Map([["bert",["BertForTokenClassification",pt]],["roformer",["RoFormerForTokenClassification",Pe]],["electra",["ElectraForTokenClassification",Je]],["esm",["EsmForTokenClassification",Gr]],["convbert",["ConvBertForTokenClassification",D]],["camembert",["CamembertForTokenClassification",Qe]],["deberta",["DebertaForTokenClassification",Et]],["deberta-v2",["DebertaV2ForTokenClassification",Yt]],["mpnet",["MPNetForTokenClassification",Bo]],["distilbert",["DistilBertForTokenClassification",$r]],["roberta",["RobertaForTokenClassification",ct]],["xlm",["XLMForTokenClassification",Un]],["xlm-roberta",["XLMRobertaForTokenClassification",Lr]]]),vl=new Map([["t5",["T5ForConditionalGeneration",Uo]],["longt5",["LongT5ForConditionalGeneration",Wo]],["mt5",["MT5ForConditionalGeneration",Vr]],["bart",["BartForConditionalGeneration",W]],["mbart",["MBartForConditionalGeneration",Oe]],["marian",["MarianMTModel",Gc]],["m2m_100",["M2M100ForConditionalGeneration",qc]],["blenderbot",["BlenderbotForConditionalGeneration",It]],["blenderbot-small",["BlenderbotSmallForConditionalGeneration",or]]]),Hs=new Map([["bloom",["BloomForCausalLM",Gu]],["gpt2",["GPT2LMHeadModel",bu]],["gptj",["GPTJForCausalLM",Eu]],["gpt_bigcode",["GPTBigCodeForCausalLM",rf]],["gpt_neo",["GPTNeoForCausalLM",Mu]],["gpt_neox",["GPTNeoXForCausalLM",ku]],["codegen",["CodeGenForCausalLM",As]],["llama",["LlamaForCausalLM",$u]],["cohere",["CohereForCausalLM",Iu]],["gemma",["GemmaForCausalLM",Ou]],["gemma2",["Gemma2ForCausalLM",Du]],["openelm",["OpenELMForCausalLM",Ru]],["qwen2",["Qwen2ForCausalLM",Nu]],["phi",["PhiForCausalLM",Uu]],["phi3",["Phi3ForCausalLM",$a]],["mpt",["MptForCausalLM",Hu]],["opt",["OPTForCausalLM",Ku]],["mbart",["MBartForCausalLM",Mt]],["mistral",["MistralForCausalLM",Vs]],["starcoder2",["Starcoder2ForCausalLM",ll]],["falcon",["FalconForCausalLM",ud]],["trocr",["TrOCRForCausalLM",ad]],["stablelm",["StableLmForCausalLM",md]]]),kd=new Map([["bert",["BertForMaskedLM",We]],["roformer",["RoFormerForMaskedLM",A]],["electra",["ElectraForMaskedLM",Ne]],["esm",["EsmForMaskedLM",Bi]],["convbert",["ConvBertForMaskedLM",R]],["camembert",["CamembertForMaskedLM",Re]],["deberta",["DebertaForMaskedLM",Tt]],["deberta-v2",["DebertaV2ForMaskedLM",Ut]],["mpnet",["MPNetForMaskedLM",Lo]],["albert",["AlbertForMaskedLM",Zt]],["distilbert",["DistilBertForMaskedLM",$t]],["roberta",["RobertaForMaskedLM",Cn]],["xlm",["XLMWithLMHeadModel",On]],["xlm-roberta",["XLMRobertaForMaskedLM",At]],["mobilebert",["MobileBertForMaskedLM",pi]],["squeezebert",["SqueezeBertForMaskedLM",fo]]]),Sd=new Map([["bert",["BertForQuestionAnswering",Ge]],["roformer",["RoFormerForQuestionAnswering",se]],["electra",["ElectraForQuestionAnswering",Ve]],["convbert",["ConvBertForQuestionAnswering",ue]],["camembert",["CamembertForQuestionAnswering",tt]],["deberta",["DebertaForQuestionAnswering",Lt]],["deberta-v2",["DebertaV2ForQuestionAnswering",rr]],["mpnet",["MPNetForQuestionAnswering",No]],["albert",["AlbertForQuestionAnswering",mo]],["distilbert",["DistilBertForQuestionAnswering",mt]],["roberta",["RobertaForQuestionAnswering",Kn]],["xlm",["XLMForQuestionAnswering",yn]],["xlm-roberta",["XLMRobertaForQuestionAnswering",Xr]],["mobilebert",["MobileBertForQuestionAnswering",Ni]],["squeezebert",["SqueezeBertForQuestionAnswering",ki]]]),bl=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",ga]]]),_m=new Map([["llava",["LlavaForConditionalGeneration",wo]],["moondream1",["Moondream1ForConditionalGeneration",ar]],["florence2",["Florence2ForConditionalGeneration",_a]]]),yf=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",ga]]]),Ed=new Map([["vit",["ViTForImageClassification",Qu]],["fastvit",["FastViTForImageClassification",Zu]],["mobilevit",["MobileViTForImageClassification",nc]],["mobilevitv2",["MobileViTV2ForImageClassification",ic]],["beit",["BeitForImageClassification",cc]],["deit",["DeiTForImageClassification",bc]],["convnext",["ConvNextForImageClassification",Fc]],["convnextv2",["ConvNextV2ForImageClassification",Dc]],["dinov2",["Dinov2ForImageClassification",Rc]],["resnet",["ResNetForImageClassification",Mc]],["swin",["SwinForImageClassification",kc]],["segformer",["SegformerForImageClassification",fd]],["efficientnet",["EfficientNetForImageClassification",_d]],["mobilenet_v1",["MobileNetV1ForImageClassification",ff]],["mobilenet_v2",["MobileNetV2ForImageClassification",vd]],["mobilenet_v3",["MobileNetV3ForImageClassification",hf]],["mobilenet_v4",["MobileNetV4ForImageClassification",yl]]]),vf=new Map([["detr",["DetrForObjectDetection",pc]],["rt_detr",["RTDetrForObjectDetection",Ls]],["table-transformer",["TableTransformerForObjectDetection",wc]],["yolos",["YolosForObjectDetection",Nc]]]),Cd=new Map([["owlvit",["OwlViTForObjectDetection",sc]],["owlv2",["Owlv2ForObjectDetection",lc]]]),Pd=new Map([["detr",["DetrForSegmentation",fc]],["clipseg",["CLIPSegForImageSegmentation",yu]]]),$d=new Map([["segformer",["SegformerForSemanticSegmentation",hd]]]),Ad=new Map([["sam",["SamModel",Vc]]]),bf=new Map([["wav2vec2",["Wav2Vec2ForCTC",af]],["wav2vec2-bert",["Wav2Vec2BertForCTC",js]],["unispeech",["UniSpeechForCTC",Xc]],["unispeech-sat",["UniSpeechSatForCTC",el]],["wavlm",["WavLMForCTC",nl]],["hubert",["HubertForCTC",Jc]]]),Id=new Map([["wav2vec2",["Wav2Vec2ForSequenceClassification",Vi]],["wav2vec2-bert",["Wav2Vec2BertForSequenceClassification",Zc]],["unispeech",["UniSpeechForSequenceClassification",Qc]],["unispeech-sat",["UniSpeechSatForSequenceClassification",Yc]],["wavlm",["WavLMForSequenceClassification",td]],["hubert",["HubertForSequenceClassification",rl]],["audio-spectrogram-transformer",["ASTForAudioClassification",$s]]]),Fd=new Map([["wavlm",["WavLMForXVector",rd]]]),Od=new Map([["unispeech-sat",["UniSpeechSatForAudioFrameClassification",Bs]],["wavlm",["WavLMForAudioFrameClassification",nd]],["wav2vec2",["Wav2Vec2ForAudioFrameClassification",Wi]],["pyannote",["PyAnnoteForAudioFrameClassification",Gi]]]),zd=new Map([["vitmatte",["VitMatteForImageMatting",ec]]]),xf=new Map([["swin2sr",["Swin2SRForImageSuperResolution",ja]]]),Dd=new Map([["dpt",["DPTForDepthEstimation",Wa]],["depth_anything",["DepthAnythingForDepthEstimation",Cc]],["glpn",["GLPNForDepthEstimation",$c]]]),Ld=new Map([["clip",["CLIPVisionModelWithProjection",fu]],["siglip",["SiglipVisionModel",mu]]]),Rd=[[mf,b.EncoderOnly],[gf,b.EncoderDecoder],[_f,b.DecoderOnly],[Td,b.EncoderOnly],[wf,b.EncoderOnly],[vl,b.Seq2Seq],[Gs,b.Seq2Seq],[Hs,b.DecoderOnly],[kd,b.EncoderOnly],[Sd,b.EncoderOnly],[bl,b.Vision2Seq],[_m,b.ImageTextToText],[Ed,b.EncoderOnly],[Pd,b.EncoderOnly],[$d,b.EncoderOnly],[zd,b.EncoderOnly],[xf,b.EncoderOnly],[Dd,b.EncoderOnly],[vf,b.EncoderOnly],[Cd,b.EncoderOnly],[Ad,b.MaskGeneration],[bf,b.EncoderOnly],[Id,b.EncoderOnly],[xd,b.Seq2Seq],[Md,b.EncoderOnly],[Fd,b.EncoderOnly],[Od,b.EncoderOnly],[Ld,b.EncoderOnly]];for(const[V,G]of Rd)for(const[ne,Ee]of V.values())I.set(ne,G),z.set(Ee,ne),U.set(ne,Ee);const Mf=[["MusicgenForConditionalGeneration",ml,b.Musicgen],["CLIPTextModelWithProjection",hi,b.EncoderOnly],["SiglipTextModel",hu,b.EncoderOnly],["ClapTextModelWithProjection",dd,b.EncoderOnly],["ClapAudioModelWithProjection",pd,b.EncoderOnly]];for(const[V,G,ne]of Mf)I.set(V,ne),z.set(G,V),U.set(V,G);class Bd extends Rr{}He(Bd,"MODEL_CLASS_MAPPINGS",Rd.map(G=>G[0])),He(Bd,"BASE_IF_FAIL",!0);class Pn extends Rr{}He(Pn,"MODEL_CLASS_MAPPINGS",[Td]);class Nd extends Rr{}He(Nd,"MODEL_CLASS_MAPPINGS",[wf]);class jd extends Rr{}He(jd,"MODEL_CLASS_MAPPINGS",[vl]);class xl extends Rr{}He(xl,"MODEL_CLASS_MAPPINGS",[Gs]);class Ud extends Rr{}He(Ud,"MODEL_CLASS_MAPPINGS",[xd]);class Zo extends Rr{}He(Zo,"MODEL_CLASS_MAPPINGS",[Md]);class Vd extends Rr{}He(Vd,"MODEL_CLASS_MAPPINGS",[Hs]);class Wd extends Rr{}He(Wd,"MODEL_CLASS_MAPPINGS",[kd]);class Ml extends Rr{}He(Ml,"MODEL_CLASS_MAPPINGS",[Sd]);class Gd extends Rr{}He(Gd,"MODEL_CLASS_MAPPINGS",[bl]);class Hd extends Rr{}He(Hd,"MODEL_CLASS_MAPPINGS",[Ed]);class Tl extends Rr{}He(Tl,"MODEL_CLASS_MAPPINGS",[Pd]);class qd extends Rr{}He(qd,"MODEL_CLASS_MAPPINGS",[$d]);class Kd extends Rr{}He(Kd,"MODEL_CLASS_MAPPINGS",[vf]);class Xd extends Rr{}He(Xd,"MODEL_CLASS_MAPPINGS",[Cd]);class kl extends Rr{}He(kl,"MODEL_CLASS_MAPPINGS",[Ad]);class Qd extends Rr{}He(Qd,"MODEL_CLASS_MAPPINGS",[bf]);class Yd extends Rr{}He(Yd,"MODEL_CLASS_MAPPINGS",[Id]);class Sl extends Rr{}He(Sl,"MODEL_CLASS_MAPPINGS",[Fd]);class Zd extends Rr{}He(Zd,"MODEL_CLASS_MAPPINGS",[Od]);class Tf extends Rr{}He(Tf,"MODEL_CLASS_MAPPINGS",[yf]);class Jd extends Rr{}He(Jd,"MODEL_CLASS_MAPPINGS",[zd]);class ep extends Rr{}He(ep,"MODEL_CLASS_MAPPINGS",[xf]);class tp extends Rr{}He(tp,"MODEL_CLASS_MAPPINGS",[Dd]);class rp extends Rr{}He(rp,"MODEL_CLASS_MAPPINGS",[Ld]);class wm extends ge{constructor({logits:G,past_key_values:ne,encoder_outputs:Ee,decoder_attentions:Ze=null,cross_attentions:it=null}){super(),this.logits=G,this.past_key_values=ne,this.encoder_outputs=Ee,this.decoder_attentions=Ze,this.cross_attentions=it}}class ur extends ge{constructor({logits:G}){super(),this.logits=G}}class np extends ge{constructor({logits:G,embeddings:ne}){super(),this.logits=G,this.embeddings=ne}}class hn extends ge{constructor({logits:G}){super(),this.logits=G}}class bn extends ge{constructor({logits:G}){super(),this.logits=G}}class xn extends ge{constructor({start_logits:G,end_logits:ne}){super(),this.start_logits=G,this.end_logits=ne}}class to extends ge{constructor({logits:G}){super(),this.logits=G}}class kf extends ge{constructor({logits:G,past_key_values:ne}){super(),this.logits=G,this.past_key_values=ne}}class ip extends ge{constructor({alphas:G}){super(),this.alphas=G}}class Sf extends ge{constructor({waveform:G,spectrogram:ne}){super(),this.waveform=G,this.spectrogram=ne}}},"./src/models/whisper/common_whisper.js":(e,t,r)=>{r.r(t),r.d(t,{WHISPER_LANGUAGE_MAPPING:()=>a,WHISPER_TO_LANGUAGE_CODE_MAPPING:()=>l,whisper_language_to_code:()=>p});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 p(_){_=_.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,r)=>{r.r(t),r.d(t,{WhisperGenerationConfig:()=>a});var o=r("./src/generation/configuration_utils.js");class a extends o.GenerationConfig{constructor(){super(...arguments);He(this,"return_timestamps",null);He(this,"return_token_timestamps",null);He(this,"num_frames",null);He(this,"alignment_heads",null);He(this,"task",null);He(this,"language",null);He(this,"no_timestamps_token_id",null);He(this,"prompt_ids",null);He(this,"is_multilingual",null);He(this,"lang_to_id",null);He(this,"task_to_id",null);He(this,"max_initial_timestamp_index",1)}}},"./src/ops/registry.js":(e,t,r)=>{r.r(t),r.d(t,{TensorOpRegistry:()=>p});var o=r("./src/backends/onnx.js"),a=r("./src/utils/tensor.js");const l=async(_,h,g)=>{const M=await(0,o.createInferenceSession)(new Uint8Array(_),h);return async y=>{const E=Object.fromEntries(Object.entries(y).map(([O,S])=>[O,S.ort_tensor])),T=await M.run(E);return Array.isArray(g)?g.map(O=>new a.Tensor(T[O])):new a.Tensor(T[g])}};class p{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}}He(p,"session_options",{})},"./src/pipelines.js":(e,t,r)=>{r.r(t),r.d(t,{AudioClassificationPipeline:()=>Y,AutomaticSpeechRecognitionPipeline:()=>L,DepthEstimationPipeline:()=>Le,DocumentQuestionAnsweringPipeline:()=>Q,FeatureExtractionPipeline:()=>ce,FillMaskPipeline:()=>I,ImageClassificationPipeline:()=>Xe,ImageFeatureExtractionPipeline:()=>xe,ImageSegmentationPipeline:()=>me,ImageToImagePipeline:()=>Ke,ImageToTextPipeline:()=>Se,ObjectDetectionPipeline:()=>ie,Pipeline:()=>S,QuestionAnsweringPipeline:()=>b,SummarizationPipeline:()=>z,Text2TextGenerationPipeline:()=>U,TextClassificationPipeline:()=>C,TextGenerationPipeline:()=>N,TextToAudioPipeline:()=>ge,TokenClassificationPipeline:()=>w,TranslationPipeline:()=>B,ZeroShotAudioClassificationPipeline:()=>_e,ZeroShotClassificationPipeline:()=>ae,ZeroShotImageClassificationPipeline:()=>X,ZeroShotObjectDetectionPipeline:()=>Me,pipeline:()=>st});var o=r("./src/tokenizers.js"),a=r("./src/models.js"),l=r("./src/processors.js"),p=r("./src/utils/generic.js"),_=r("./src/utils/core.js"),h=r("./src/utils/maths.js"),g=r("./src/utils/audio.js"),M=r("./src/utils/tensor.js"),y=r("./src/utils/image.js");async function E(Ge){return Array.isArray(Ge)||(Ge=[Ge]),await Promise.all(Ge.map(Te=>y.RawImage.read(Te)))}async function T(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 O(Ge,Te){Te&&(Ge=Ge.map($e=>$e|0));const[je,Ye,et,A]=Ge;return{xmin:je,ymin:Ye,xmax:et,ymax:A}}class S extends p.Callable{constructor({task:Te,model:je,tokenizer:Ye=null,processor:et=null}){super(),this.task=Te,this.model=je,this.tokenizer=Ye,this.processor=et}async dispose(){await this.model.dispose()}}class C extends S{constructor(Te){super(Te)}async _call(Te,{top_k:je=1}={}){const Ye=this.tokenizer(Te,{padding:!0,truncation:!0}),et=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),$e=this.model.config.id2label,Pe=[];for(const se of et.logits){const re=A(se),ye=await(0,M.topk)(re,je),R=ye[0].tolist(),D=ye[1].tolist().map((ue,le)=>({label:$e?$e[ue]:`LABEL_${ue}`,score:R[le]}));je===1?Pe.push(...D):Pe.push(D)}return Array.isArray(Te)||je===1?Pe:Pe[0]}}class w extends S{constructor(Te){super(Te)}async _call(Te,{ignore_labels:je=["O"]}={}){const Ye=Array.isArray(Te),et=this.tokenizer(Ye?Te:[Te],{padding:!0,truncation:!0}),$e=(await this.model(et)).logits,Pe=this.model.config.id2label,se=[];for(let re=0;re<$e.dims[0];++re){const ye=et.input_ids[re],R=$e[re],ee=[];for(let D=0;DJe==this.tokenizer.sep_token_id);se[R].map((Je,Ve)=>Je==1&&(Ve===0||Ve>D&&re.findIndex(Z=>Z==ee[Ve])===-1));const ue=A[R].tolist(),le=$e[R].tolist();for(let Je=1;JeVe==ee[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 dt=(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(re===-1)throw Error(`Mask token (${this.tokenizer.mask_token}) not found in text.`);const ye=et[Pe][re],R=await(0,M.topk)(new M.Tensor("float32",(0,h.softmax)(ye.data),ye.dims),je),ee=R[0].tolist(),D=R[1].tolist();A.push(D.map((ue,le)=>{const ke=se.slice();return ke[re]=ue,{score:ee[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);He(this,"_key","generated_text")}async _call(je,Ye={}){Array.isArray(je)||(je=[je]),this.model.config.prefix&&(je=je.map(re=>this.model.config.prefix+re));const et=this.model.config.task_specific_params;et&&et[this.task]&&et[this.task].prefix&&(je=je.map(re=>et[this.task].prefix+re));const A=this.tokenizer,$e={padding:!0,truncation:!0};let Pe;this instanceof B&&"_build_translation_inputs"in A?Pe=A._build_translation_inputs(je,$e,Ye):Pe=A(je,$e);const se=await this.model.generate({...Pe,...Ye});return A.batch_decode(se,{skip_special_tokens:!0}).map(re=>({[this._key]:re}))}}class z extends U{constructor(je){super(je);He(this,"_key","summary_text")}}class B extends U{constructor(je){super(je);He(this,"_key","translation_text")}}function j(Ge){return Array.isArray(Ge)&&Ge.every(Te=>"role"in Te&&"content"in Te)}class N extends S{constructor(Te){super(Te)}async _call(Te,je={}){let Ye=!1,et=!1,A;if(typeof Te=="string")A=Te=[Te];else if(Array.isArray(Te)&&Te.every(D=>typeof D=="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");et=!0,A=Te.map(D=>this.tokenizer.apply_chat_template(D,{tokenize:!1,add_generation_prompt:!0}))}const $e=je.add_special_tokens??!1,Pe=et?!1:je.return_full_text??!0;this.tokenizer.padding_side="left";const se=this.tokenizer(A,{add_special_tokens:$e,padding:!0,truncation:!0}),re=await this.model.generate({...se,...je}),ye=this.tokenizer.batch_decode(re,{skip_special_tokens:!0});let R;!Pe&&se.input_ids.dims.at(-1)>0&&(R=this.tokenizer.batch_decode(se.input_ids,{skip_special_tokens:!0}).map(D=>D.length));const ee=Array.from({length:Te.length},D=>[]);for(let D=0;D[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:et=!1}={}){const A=Array.isArray(Te);A||(Te=[Te]),Array.isArray(je)||(je=[je]);const $e=je.map(re=>Ye.replace("{}",re)),Pe=et||je.length===1,se=[];for(const re of Te){const ye=[];for(const D of $e){const ue=this.tokenizer(re,{text_pair:D,padding:!0,truncation:!0}),le=await this.model(ue);Pe?ye.push([le.logits.data[this.contradiction_id],le.logits.data[this.entailment_id]]):ye.push(le.logits.data[this.entailment_id])}const ee=(Pe?ye.map(D=>(0,h.softmax)(D)[1]):(0,h.softmax)(ye)).map((D,ue)=>[D,ue]).sort((D,ue)=>ue[0]-D[0]);se.push({sequence:re,labels:ee.map(D=>je[D[1]]),scores:ee.map(D=>D[0])})}return A?se:se[0]}}class ce extends S{constructor(Te){super(Te)}async _call(Te,{pooling:je="none",normalize:Ye=!1,quantize:et=!1,precision:A="binary"}={}){const $e=this.tokenizer(Te,{padding:!0,truncation:!0}),Pe=await this.model($e);let se=Pe.last_hidden_state??Pe.logits??Pe.token_embeddings;if(je!=="none")if(je==="mean")se=(0,M.mean_pooling)(se,$e.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)),et&&(se=(0,M.quantize_embeddings)(se,A)),se}}class xe extends S{constructor(Te){super(Te)}async _call(Te,{pool:je=null}={}){const Ye=await E(Te),{pixel_values:et}=await this.processor(Ye),A=await this.model({pixel_values:et});let $e;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.");$e=A.pooler_output}else $e=A.last_hidden_state??A.logits??A.image_embeds;return $e}}class Y extends S{constructor(Te){super(Te)}async _call(Te,{top_k:je=5}={}){const Ye=this.processor.feature_extractor.config.sampling_rate,et=await T(Te,Ye),A=this.model.config.id2label,$e=[];for(const Pe of et){const se=await this.processor(Pe),ye=(await this.model(se)).logits[0],R=await(0,M.topk)(new M.Tensor("float32",(0,h.softmax)(ye.data),ye.dims),je),ee=R[0].tolist(),ue=R[1].tolist().map((le,ke)=>({label:A?A[le]:`LABEL_${le}`,score:ee[ke]}));$e.push(ue)}return Array.isArray(Te)?$e:$e[0]}}class _e extends S{constructor(Te){super(Te)}async _call(Te,je,{hypothesis_template:Ye="This is a sound of {}."}={}){const et=!Array.isArray(Te);et&&(Te=[Te]);const A=je.map(ye=>Ye.replace("{}",ye)),$e=this.tokenizer(A,{padding:!0,truncation:!0}),Pe=this.processor.feature_extractor.config.sampling_rate,se=await T(Te,Pe),re=[];for(const ye of se){const R=await this.processor(ye),ee=await this.model({...$e,...R}),D=(0,h.softmax)(ee.logits_per_audio.data);re.push([...D].map((ue,le)=>({score:ue,label:je[le]})))}return et?re[0]:re}}class L 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 et=this.processor.feature_extractor.config.sampling_rate,A=await T(Te,et),$e=[];for(const Pe of A){const se=await this.processor(Pe),ye=(await this.model(se)).logits[0],R=[];for(const D of ye)R.push((0,h.max)(D.data)[1]);const ee=this.tokenizer.decode(R);$e.push({text:ee})}return Ye?$e[0]:$e}async _call_whisper(Te,je){const Ye=je.return_timestamps??!1,et=je.chunk_length_s??0,A=je.force_full_sequences??!1;let $e=je.stride_length_s??null;const Pe={...je};Ye==="word"&&(Pe.return_token_timestamps=!0,Pe.return_timestamps=!1);const se=!Array.isArray(Te);se&&(Te=[Te]);const re=this.processor.feature_extractor.config.chunk_length/this.model.config.max_source_positions,ye=this.processor.feature_extractor.config.hop_length,R=this.processor.feature_extractor.config.sampling_rate,ee=await T(Te,R),D=[];for(const ue of ee){let le=[];if(et>0){if($e===null)$e=et/6;else if(et<=$e)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");const dt=R*et,Je=R*$e,Ve=dt-2*Je;let Z=0;for(;;){const ve=Z+dt,Re=ue.subarray(Z,ve),qe=await this.processor(Re),Qe=Z===0,tt=ve>=ue.length;if(le.push({stride:[Re.length,Qe?0:Je,tt?0:Je],input_features:qe.input_features,is_last:tt}),tt)break;Z+=Ve}}else le=[{stride:[ue.length,0,0],input_features:(await this.processor(ue)).input_features,is_last:!0}];for(const dt of le){Pe.num_frames=Math.floor(dt.stride[0]/ye);const Je=await this.model.generate({inputs:dt.input_features,...Pe});Ye==="word"?(dt.tokens=Je.sequences.tolist()[0],dt.token_timestamps=Je.token_timestamps.tolist()[0].map(Ve=>(0,h.round)(Ve,2))):dt.tokens=Je[0].tolist(),dt.stride=dt.stride.map(Ve=>Ve/R)}const[ke,Ne]=this.tokenizer._decode_asr(le,{time_precision:re,return_timestamps:Ye,force_full_sequences:A});D.push({text:ke,...Ne})}return se?D[0]:D}}class Se extends S{constructor(Te){super(Te)}async _call(Te,je={}){const Ye=Array.isArray(Te),et=await E(Te),{pixel_values:A}=await this.processor(et),$e=[];for(const Pe of A){Pe.dims=[1,...Pe.dims];const se=await this.model.generate({inputs:Pe,...je}),re=this.tokenizer.batch_decode(se,{skip_special_tokens:!0}).map(ye=>({generated_text:ye.trim()}));$e.push(re)}return Ye?$e:$e[0]}}class Xe extends S{constructor(Te){super(Te)}async _call(Te,{top_k:je=5}={}){const Ye=await E(Te),{pixel_values:et}=await this.processor(Ye),A=await this.model({pixel_values:et}),$e=this.model.config.id2label,Pe=[];for(const se of A.logits){const re=await(0,M.topk)(new M.Tensor("float32",(0,h.softmax)(se.data),se.dims),je),ye=re[0].tolist(),ee=re[1].tolist().map((D,ue)=>({label:$e?$e[D]:`LABEL_${D}`,score:ye[ue]}));Pe.push(ee)}return Array.isArray(Te)?Pe:Pe[0]}}class me 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:et=.8,label_ids_to_fuse:A=null,target_sizes:$e=null,subtask:Pe=null}={}){if(Array.isArray(Te)&&Te.length!==1)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");const re=await E(Te),ye=re.map(Ne=>[Ne.height,Ne.width]),{pixel_values:R,pixel_mask:ee}=await this.processor(re),D=await this.model({pixel_values:R,pixel_mask:ee});let ue=null;if(Pe!==null)ue=this.subtasks_mapping[Pe];else for(let[Ne,dt]of Object.entries(this.subtasks_mapping))if(dt in this.processor.feature_extractor){ue=this.processor.feature_extractor[dt].bind(this.processor.feature_extractor),Pe=Ne;break}const le=this.model.config.id2label,ke=[];if(Pe==="panoptic"||Pe==="instance"){const Ne=ue(D,je,Ye,et,A,$e??ye)[0],dt=Ne.segmentation;for(const Je of Ne.segments_info){const Ve=new Uint8ClampedArray(dt.data.length);for(let ve=0;veYe.replace("{}",ee)),Pe=this.tokenizer($e,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:se}=await this.processor(A),re=await this.model({...Pe,pixel_values:se}),ye=this.model.config.model_type==="siglip"?ee=>ee.sigmoid().data:ee=>(0,h.softmax)(ee.data),R=[];for(const ee of re.logits_per_image){const ue=[...ye(ee)].map((le,ke)=>({score:le,label:je[ke]}));ue.sort((le,ke)=>ke.score-le.score),R.push(ue)}return et?R:R[0]}}class ie extends S{constructor(Te){super(Te)}async _call(Te,{threshold:je=.9,percentage:Ye=!1}={}){const et=Array.isArray(Te);if(et&&Te.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");const A=await E(Te),$e=Ye?null:A.map(D=>[D.height,D.width]),{pixel_values:Pe,pixel_mask:se}=await this.processor(A),re=await this.model({pixel_values:Pe,pixel_mask:se}),ye=this.processor.feature_extractor.post_process_object_detection(re,je,$e),R=this.model.config.id2label,ee=ye.map(D=>D.boxes.map((ue,le)=>({score:D.scores[le],label:R[D.classes[le]],box:O(ue,!Ye)})));return et?ee:ee[0]}}class Me extends S{constructor(Te){super(Te)}async _call(Te,je,{threshold:Ye=.1,top_k:et=null,percentage:A=!1}={}){const $e=Array.isArray(Te),Pe=await E(Te),se=this.tokenizer(je,{padding:!0,truncation:!0}),re=await this.processor(Pe),ye=[];for(let R=0;R({score:ke.scores[Je],label:je[ke.classes[Je]],box:O(dt,!A)})).sort((dt,Je)=>Je.score-dt.score);et!==null&&(Ne=Ne.slice(0,et)),ye.push(Ne)}return $e?ye:ye[0]}}class Q 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 ge extends S{constructor(je){super(je);He(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:et}=await this.model(Ye),A=this.model.config.sampling_rate;return{audio:et.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:et}=this.tokenizer(je,{padding:!0,truncation:!0}),{waveform:A}=await this.model.generate_speech(et,Ye,{vocoder:this.vocoder}),$e=this.processor.feature_extractor.config.sampling_rate;return{audio:A.data,sampling_rate:$e}}}class Ke extends S{constructor(Te){super(Te)}async _call(Te){const je=await E(Te),Ye=await this.processor(je),et=await this.model(Ye),A=[];for(const $e of et.reconstruction){const Pe=$e.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");A.push(y.RawImage.fromTensor(Pe))}return A.length>1?A:A[0]}}class Le extends S{constructor(Te){super(Te)}async _call(Te){const je=await E(Te),Ye=await this.processor(je),{predicted_depth:et}=await this.model(Ye),A=[];for(let $e=0;$e1?A:A[0]}}const Be=Object.freeze({"text-classification":{tokenizer:o.AutoTokenizer,pipeline:C,model:a.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{tokenizer:o.AutoTokenizer,pipeline:w,model:a.AutoModelForTokenClassification,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{tokenizer:o.AutoTokenizer,pipeline:b,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:z,model:a.AutoModelForSeq2SeqLM,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{tokenizer:o.AutoTokenizer,pipeline:B,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:N,model:a.AutoModelForCausalLM,default:{model:"Xenova/gpt2"},type:"text"},"zero-shot-classification":{tokenizer:o.AutoTokenizer,pipeline:ae,model:a.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:Y,model:a.AutoModelForAudioClassification,processor:l.AutoProcessor,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{tokenizer:o.AutoTokenizer,pipeline:_e,model:a.AutoModel,processor:l.AutoProcessor,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{tokenizer:o.AutoTokenizer,pipeline:L,model:[a.AutoModelForSpeechSeq2Seq,a.AutoModelForCTC],processor:l.AutoProcessor,default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{tokenizer:o.AutoTokenizer,pipeline:ge,model:[a.AutoModelForTextToWaveform,a.AutoModelForTextToSpectrogram],processor:[l.AutoProcessor,null],default:{model:"Xenova/speecht5_tts"},type:"text"},"image-to-text":{tokenizer:o.AutoTokenizer,pipeline:Se,model:a.AutoModelForVision2Seq,processor:l.AutoProcessor,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:Xe,model:a.AutoModelForImageClassification,processor:l.AutoProcessor,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:me,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:X,model:a.AutoModel,processor:l.AutoProcessor,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:ie,model:a.AutoModelForObjectDetection,processor:l.AutoProcessor,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{tokenizer:o.AutoTokenizer,pipeline:Me,model:a.AutoModelForZeroShotObjectDetection,processor:l.AutoProcessor,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{tokenizer:o.AutoTokenizer,pipeline:Q,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:Le,model:a.AutoModelForDepthEstimation,processor:l.AutoProcessor,default:{model:"Xenova/dpt-large"},type:"image"},"feature-extraction":{tokenizer:o.AutoTokenizer,pipeline:ce,model:a.AutoModel,default:{model:"Xenova/all-MiniLM-L6-v2"},type:"text"},"image-feature-extraction":{processor:l.AutoProcessor,pipeline:xe,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 st(Ge,Te=null,{progress_callback:je=null,config:Ye=null,cache_dir:et=null,local_files_only:A=!1,revision:$e="main",device:Pe=null,dtype:se=null,model_file_name:re=null,session_options:ye={}}={}){Ge=We[Ge]??Ge;const R=Be[Ge.split("_",1)[0]];if(!R)throw Error(`Unsupported pipeline: ${Ge}. Must be one of [${Object.keys(Be)}]`);Te||(Te=R.default.model,console.log(`No model specified. Using default model: "${Te}".`));const ee={progress_callback:je,config:Ye,cache_dir:et,local_files_only:A,revision:$e,device:Pe,dtype:se,model_file_name:re,session_options:ye},D=new Map([["tokenizer",R.tokenizer],["model",R.model],["processor",R.processor]]),ue=await pt(D,Te,ee);ue.task=Ge,(0,_.dispatchCallback)(je,{status:"ready",task:Ge,model:Te});const le=R.pipeline;return new le(ue)}async function pt(Ge,Te,je){const Ye=Object.create(null),et=[];for(let[A,$e]of Ge.entries()){if(!$e)continue;let Pe;Array.isArray($e)?Pe=new Promise(async(se,re)=>{var R,ee;let ye;for(let D of $e){if(D===null){se(null);return}try{se(await D.from_pretrained(Te,je));return}catch(ue){if((R=ue.message)!=null&&R.includes("Unsupported model type"))ye=ue;else if((ee=ue.message)!=null&&ee.includes("Could not locate file"))ye=ue;else{re(ue);return}}}re(ye)}):Pe=$e.from_pretrained(Te,je),Ye[A]=Pe,et.push(Pe)}await Promise.all(et);for(let[A,$e]of Object.entries(Ye))Ye[A]=await $e;return Ye}},"./src/processors.js":(e,t,r)=>{r.r(t),r.d(t,{ASTFeatureExtractor:()=>$e,AutoProcessor:()=>Je,BeitFeatureExtractor:()=>Le,BitImageProcessor:()=>I,CLIPFeatureExtractor:()=>z,CLIPImageProcessor:()=>B,ChineseCLIPFeatureExtractor:()=>j,ClapFeatureExtractor:()=>Pe,ConvNextFeatureExtractor:()=>ae,ConvNextImageProcessor:()=>ce,DPTFeatureExtractor:()=>w,DPTImageProcessor:()=>b,DeiTFeatureExtractor:()=>Ke,DetrFeatureExtractor:()=>st,DonutFeatureExtractor:()=>Be,EfficientNetImageProcessor:()=>_e,FeatureExtractor:()=>O,Florence2Processor:()=>dt,GLPNFeatureExtractor:()=>U,ImageFeatureExtractor:()=>S,MobileNetV1FeatureExtractor:()=>L,MobileNetV2FeatureExtractor:()=>Se,MobileNetV3FeatureExtractor:()=>Xe,MobileNetV4FeatureExtractor:()=>me,MobileViTFeatureExtractor:()=>X,MobileViTImageProcessor:()=>ie,NougatImageProcessor:()=>We,OwlViTFeatureExtractor:()=>Me,OwlViTProcessor:()=>Ne,Owlv2ImageProcessor:()=>Q,Processor:()=>R,PyAnnoteFeatureExtractor:()=>se,PyAnnoteProcessor:()=>le,RTDetrImageProcessor:()=>ge,SamImageProcessor:()=>Ge,SamProcessor:()=>ee,SeamlessM4TFeatureExtractor:()=>A,SegformerFeatureExtractor:()=>C,SiglipImageProcessor:()=>N,SpeechT5FeatureExtractor:()=>ye,SpeechT5Processor:()=>ke,Swin2SRImageProcessor:()=>Te,ViTFeatureExtractor:()=>xe,ViTImageProcessor:()=>Y,VitMatteImageProcessor:()=>je,Wav2Vec2FeatureExtractor:()=>et,Wav2Vec2ProcessorWithLM:()=>ue,WeSpeakerFeatureExtractor:()=>re,WhisperFeatureExtractor:()=>Ye,WhisperProcessor:()=>D,YolosFeatureExtractor:()=>pt});var o=r("./src/utils/generic.js"),a=r("./src/utils/core.js"),l=r("./src/utils/hub.js"),p=r("./src/utils/maths.js"),_=r("./src/utils/tensor.js");r("./src/utils/image.js");var h=r("./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 qe=Ve.logits,Qe=Ve.pred_boxes,[tt,ft,ht]=qe.dims;if(ve!==null&&ve.length!==tt)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let Tt=[];for(let bt=0;btZ&&Yt.push(Ht)}else{let Ht=(0,p.max)(Xt.data)[1];if(Ht===ht-1||(rr=(0,p.softmax)(Xt.data),rr[Ht]Yr*Et[($r+1)%2])),Lt.boxes.push(Pr),Lt.classes.push(Ht),Lt.scores.push(rr[Ht])}}Tt.push(Lt)}return Tt}function y(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 E(Ve,Z,ve=0,Re=null){const qe=Ve/Z;let Qe=(0,p.bankers_round)(qe)*Z;return Re!==null&&Qe>Re&&(Qe=Math.floor(qe)*Z),QeQe?Tt=Math.floor(Qe*ht/qe):Qe>qe&&(ht=Math.floor(qe*Tt/Qe)),await Z.resize(Tt,ht,{resample:Re}))}async crop_margin(Z,ve=200){const Re=Z.clone().grayscale(),qe=(0,p.min)(Re.data)[0],tt=(0,p.max)(Re.data)[0]-qe;if(tt===0)return Z;const ft=ve/255;let ht=Re.width,Tt=Re.height,bt=0,Et=0;const Lt=Re.data;for(let at=0;atthis.preprocess(Qe)));return{pixel_values:(0,_.stack)(Re.map(Qe=>Qe.pixel_values),0),original_sizes:Re.map(Qe=>Qe.original_size),reshaped_input_sizes:Re.map(Qe=>Qe.reshaped_input_size)}}}class C extends S{post_process_semantic_segmentation(Z,ve=null){const Re=Z.logits,qe=Re.dims[0];if(ve!==null&&ve.length!==qe)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const Qe=[];for(let tt=0;ttLt[Ht]&&(Lt[Ht]=rr[Ht],at[Ht]=Yt)}const Ot=new Array(ht.dims[0]),Ut=Et.data;for(let Yt=0;YtYt!==void 0);Qe.push({segmentation:Et,labels:Xt})}return Qe}}class w extends S{}class b extends w{}class I extends S{}class U extends S{}class z extends S{}class B extends z{}class j extends S{}class N extends S{}class ae 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 qe=Math.floor(ve/this.crop_pct),[Qe,tt]=this.get_resize_output_image_size(Z,{shortest_edge:qe});Z=await Z.resize(Qe,tt,{resample:this.resample}),Z=await Z.center_crop(ve,ve)}else Z=await Z.resize(ve,ve,{resample:this.resample});return Z}}class ce extends ae{}class xe extends S{}class Y extends S{}class _e 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 L extends S{}class Se extends S{}class Xe extends S{}class me extends S{}class X extends S{}class ie extends X{}class Me extends S{post_process_object_detection(...Z){return M(...Z)}}class Q extends Me{}class ge extends S{post_process_object_detection(...Z){return M(...Z)}}class Ke extends S{}class Le extends S{}class Be extends S{pad_image(Z,ve,Re,qe={}){const[Qe,tt,ft]=ve;let ht=this.image_mean;Array.isArray(this.image_mean)||(ht=new Array(ft).fill(ht));let Tt=this.image_std;Array.isArray(Tt)||(Tt=new Array(ft).fill(ht));const bt=ht.map((Et,Lt)=>-Et/Tt[Lt]);return super.pad_image(Z,ve,Re,{center:!0,constant_values:bt,...qe})}}class We extends Be{}class st extends S{async _call(Z){const ve=await super._call(Z),Re=[ve.pixel_values.dims[0],64,64],qe=new _.Tensor("int64",new BigInt64Array(Re.reduce((Qe,tt)=>Qe*tt)).fill(1n),Re);return{...ve,pixel_mask:qe}}post_process_object_detection(...Z){return M(...Z)}remove_low_and_no_objects(Z,ve,Re,qe){let Qe=[],tt=[],ft=[];for(let ht=0;htRe&&(Qe.push(bt),tt.push(at),ft.push(Et))}return[Qe,tt,ft]}check_segment_validity(Z,ve,Re,qe=.5,Qe=.8){let tt=[],ft=0,ht=0;const Tt=ve[Re].data;for(let Et=0;Et=qe&&++ht;let bt=ft>0&&ht>0;return bt&&(bt=ft/ht>Qe),[bt,tt]}compute_segments(Z,ve,Re,qe,Qe,tt=null,ft=null){let[ht,Tt]=ft??Z[0].dims,bt=new _.Tensor("int32",new Int32Array(ht*Tt),[ht,Tt]),Et=[];if(ft!==null)for(let Xt=0;Xtat[Ht]&&(Lt[Ht]=Xt,at[Ht]=rr[Ht])}let Ot=0;const Ut=bt.data;for(let Xt=0;Xtqe!==ve.dims[Qe]))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:qe=null}={}){const Qe=await super._call(Z);if(ve&&(Qe.input_points=this.reshape_input_points(ve,Qe.original_sizes,Qe.reshaped_input_sizes)),Re){if(!Qe.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");Qe.input_labels=this.add_input_labels(Re,Qe.input_points)}return qe&&(Qe.input_boxes=this.reshape_input_points(qe,Qe.original_sizes,Qe.reshaped_input_sizes,!0)),Qe}async post_process_masks(Z,ve,Re,{mask_threshold:qe=0,binarize:Qe=!0,pad_size:tt=null}={}){const ft=[];tt=tt??this.pad_size;const ht=[tt.height,tt.width];for(let Tt=0;Ttqe&&(Ot[Ut]=1);Lt=new _.Tensor("bool",Ot,Lt.dims)}ft.push(Lt)}return ft}generate_crop_boxes(Z,ve,{crop_n_layers:Re=0,overlap_ratio:qe=512/1500,points_per_crop:Qe=32,crop_n_points_downscale_factor:tt=1}={}){}}class Te extends S{pad_image(Z,ve,Re,qe={}){const[Qe,tt,ft]=ve;return super.pad_image(Z,ve,{width:tt+(Re-tt%Re)%Re,height:Qe+(Re-Qe%Re)%Re},{mode:"symmetric",center:!1,constant_values:-1,...qe})}}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(tt=>this.preprocess(tt))),qe=await Promise.all(ve.map(tt=>this.preprocess(tt,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:(0,_.stack)(Re.map((tt,ft)=>(0,_.cat)([tt.pixel_values,qe[ft].pixel_values],0)),0),original_sizes:Re.map(tt=>tt.original_size),reshaped_input_sizes:Re.map(tt=>tt.reshaped_input_size)}}}class Ye extends O{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,qe=(0,p.max)(Re)[0];for(let Qe=0;Qethis.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 et extends O{_zero_mean_unit_var_norm(Z){const Re=Z.reduce((Qe,tt)=>Qe+tt,0)/Z.length,qe=Z.reduce((Qe,tt)=>Qe+(tt-Re)**2,0)/Z.length;return Z.map(Qe=>(Qe-Re)/Math.sqrt(qe+1e-7))}async _call(Z){y(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 O{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 qe=0;qeRe*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:qe=!0,return_attention_mask:Qe=!0}={}){y(Z,"SeamlessM4TFeatureExtractor");let tt=await this._extract_fbank_features(Z,this.config.max_length);if(qe){const[Ot,Ut]=tt.dims,Xt=tt.data;for(let Yt=0;Yt0){const rr=new Float32Array(Ut*(Ot+Yt));rr.set(Xt),rr.fill(this.config.padding_value,Xt.length);const Ht=Ot+Yt;tt=new _.Tensor(tt.type,rr,[Ht,Ut]),Qe&&(ft=new _.Tensor("int64",new BigInt64Array(Ht),[1,Ht]),ft.data.fill(1n,0,Ot))}}const[ht,Tt]=tt.dims,bt=this.config.stride;if(ht%bt!==0)throw new Error(`The number of frames (${ht}) must be a multiple of the stride (${bt}).`);const Lt=tt.view(1,Math.floor(ht/bt),Tt*bt),at={input_features:Lt};if(Qe){const Ot=Lt.dims[1],Ut=new BigInt64Array(Ot);if(ft){const Xt=ft.data;for(let Yt=1,rr=0;Yt0)if(Re==="rand_trunc"){const ft=Math.floor(Math.random()*(tt+1));Z=Z.subarray(ft,ft+ve),Qe=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(tt<0){let ft=new Float64Array(ve);if(ft.set(Z),qe==="repeat")for(let ht=Z.length;ht({id:ht,start:Tt*Re,end:bt*Re,confidence:Et/(bt-Tt)})))}return qe}}class re extends O{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 qe=0;qeve*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){y(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,qe=ve.data,[Qe,tt,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[qe,Qe]of this.task_prompts_with_input)if(Re.includes(qe)){ve.push(Qe.replaceAll("{input}",Re).replaceAll(qe,""));break}ve.length!==Z.length&&ve.push(Re)}return ve}post_process_generation(Z,ve,Re){const qe=this.tasks_answer_post_processing_type.get(ve)??"pure_text";Z=Z.replaceAll("","").replaceAll("","");let Qe;switch(qe){case"pure_text":Qe=Z;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":const tt=qe==="ocr"?"quad_boxes":"bboxes",ft=Z.matchAll(this.regexes[tt]),ht=[],Tt=[];for(const[bt,Et,...Lt]of ft)ht.push(Et?Et.trim():ht.at(-1)??""),Tt.push(Lt.map((at,Ot)=>(Number(at)+.5)/this.size_per_bin*Re[Ot%2]));Qe={labels:ht,[tt]:Tt};break;default:throw new Error(`Task "${ve}" (of type "${qe}") not yet implemented.`)}return{[ve]:Qe}}}class Je{static async from_pretrained(Z,{progress_callback:ve=null,config:Re=null,cache_dir:qe=null,local_files_only:Qe=!1,revision:tt="main"}={}){let ft=Re??await(0,l.getModelJSON)(Z,"preprocessor_config.json",!0,{progress_callback:ve,config:Re,cache_dir:qe,local_files_only:Qe,revision:tt}),ht=ft.feature_extractor_type??ft.image_processor_type,Tt=this.FEATURE_EXTRACTOR_CLASS_MAPPING[ht];if(!Tt)if(ft.size!==void 0)console.warn(`Feature extractor type "${ht}" not found, assuming ImageFeatureExtractor due to size parameter in config.`),Tt=S;else throw new Error(`Unknown Feature Extractor type: ${ht}`);let bt=this.PROCESSOR_CLASS_MAPPING[ft.processor_class]??R,Et=new Tt(ft);return new bt(Et)}}He(Je,"FEATURE_EXTRACTOR_CLASS_MAPPING",{ImageFeatureExtractor:S,WhisperFeatureExtractor:Ye,ViTFeatureExtractor:xe,MobileViTFeatureExtractor:X,MobileViTImageProcessor:ie,MobileNetV1FeatureExtractor:L,MobileNetV2FeatureExtractor:Se,MobileNetV3FeatureExtractor:Xe,MobileNetV4FeatureExtractor:me,OwlViTFeatureExtractor:Me,Owlv2ImageProcessor:Q,CLIPFeatureExtractor:z,CLIPImageProcessor:B,Florence2Processor:dt,ChineseCLIPFeatureExtractor:j,SiglipImageProcessor:N,ConvNextFeatureExtractor:ae,ConvNextImageProcessor:ce,SegformerFeatureExtractor:C,BitImageProcessor:I,DPTImageProcessor:b,DPTFeatureExtractor:w,GLPNFeatureExtractor:U,BeitFeatureExtractor:Le,DeiTFeatureExtractor:Ke,DetrFeatureExtractor:st,RTDetrImageProcessor:ge,YolosFeatureExtractor:pt,DonutFeatureExtractor:Be,NougatImageProcessor:We,EfficientNetImageProcessor:_e,ViTImageProcessor:Y,VitMatteImageProcessor:je,SamImageProcessor:Ge,Swin2SRImageProcessor:Te,Wav2Vec2FeatureExtractor:et,SeamlessM4TFeatureExtractor:A,SpeechT5FeatureExtractor:ye,ASTFeatureExtractor:$e,ClapFeatureExtractor:Pe,PyAnnoteFeatureExtractor:se,WeSpeakerFeatureExtractor:re}),He(Je,"PROCESSOR_CLASS_MAPPING",{WhisperProcessor:D,Wav2Vec2ProcessorWithLM:ue,PyAnnoteProcessor:le,SamProcessor:ee,SpeechT5Processor:ke,OwlViTProcessor:Ne,Florence2Processor:dt})},"./src/tokenizers.js":(e,t,r)=>{r.r(t),r.d(t,{AlbertTokenizer:()=>Ut,AutoTokenizer:()=>jn,BartTokenizer:()=>Gr,BertTokenizer:()=>Ot,BlenderbotSmallTokenizer:()=>Vo,BlenderbotTokenizer:()=>go,BloomTokenizer:()=>Dr,CLIPTokenizer:()=>Zt,CamembertTokenizer:()=>$t,CodeGenTokenizer:()=>mo,CodeLlamaTokenizer:()=>Cs,CohereTokenizer:()=>Vr,ConvBertTokenizer:()=>Yr,DebertaTokenizer:()=>rr,DebertaV2Tokenizer:()=>Ht,DistilBertTokenizer:()=>mt,ElectraTokenizer:()=>un,EsmTokenizer:()=>ji,FalconTokenizer:()=>Bo,GPT2Tokenizer:()=>Mi,GPTNeoXTokenizer:()=>No,GemmaTokenizer:()=>fo,Grok1Tokenizer:()=>fi,HerbertTokenizer:()=>Pr,LlamaTokenizer:()=>Ti,M2M100Tokenizer:()=>Ji,MBart50Tokenizer:()=>Kr,MBartTokenizer:()=>wn,MPNetTokenizer:()=>Ro,MarianTokenizer:()=>jo,MobileBertTokenizer:()=>Xt,NllbTokenizer:()=>Si,NougatTokenizer:()=>_o,PreTrainedTokenizer:()=>at,Qwen2Tokenizer:()=>Ps,RoFormerTokenizer:()=>$r,RobertaTokenizer:()=>pi,SiglipTokenizer:()=>eo,SpeechT5Tokenizer:()=>Wo,SqueezeBertTokenizer:()=>Yt,T5Tokenizer:()=>Bi,TokenizerModel:()=>xe,VitsTokenizer:()=>Go,Wav2Vec2CTCTokenizer:()=>Uo,WhisperTokenizer:()=>ho,XLMRobertaTokenizer:()=>Lo,XLMTokenizer:()=>Bt,is_chinese_char:()=>U});var o=r("./src/utils/generic.js"),a=r("./src/utils/core.js"),l=r("./src/utils/hub.js"),p=r("./src/utils/maths.js"),_=r("./src/utils/tensor.js"),h=r("./src/utils/data-structures.js"),g=r("./node_modules/@huggingface/jinja/dist/index.js"),M=r("./src/models/whisper/common_whisper.js"),y=r("./src/utils/constants.js");async function E(Ue,W){const pe=await Promise.all([(0,l.getModelJSON)(Ue,"tokenizer.json",!0,W),(0,l.getModelJSON)(Ue,"tokenizer_config.json",!0,W)]);return W.legacy!==null&&(pe[1].legacy=W.legacy),pe}function T(Ue,W){const pe=[];let Ce=0;for(const Fe of Ue.matchAll(W)){const Oe=Fe[0];Ce0&&pe.push(Oe),Ce=Fe.index+Oe.length}return Ce=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 z(Ue,W,pe){const Ce=[];let Fe=0;for(;Fethis.tokens_to_ids.get(pe)??this.unk_token_id)}convert_ids_to_tokens(W){return W.map(pe=>this.vocab[pe]??this.unk_token)}}class Y extends xe{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[pe,Ce]of this.tokens_to_ids)this.vocab[Ce]=pe}encode(W){const pe=[];for(const Ce of W){const Fe=[...Ce];if(Fe.length>this.max_input_chars_per_word){pe.push(this.unk_token);continue}let Oe=!1,rt=0;const Mt=[];for(;rt0&&(It=this.config.continuing_subword_prefix+It),this.tokens_to_ids.has(It)){kt=It;break}--St}if(kt===null){Oe=!0;break}Mt.push(kt),rt=St}Oe?pe.push(this.unk_token):pe.push(...Mt)}return pe}}class _e extends xe{constructor(W,pe){super(W);const Ce=W.vocab.length;this.vocab=new Array(Ce),this.scores=new Array(Ce);for(let Fe=0;Fe[Fe,Oe])),this.bosToken=" ",this.bosTokenId=this.tokens_to_ids.get(this.bosToken),this.eosToken=pe.eos_token,this.eosTokenId=this.tokens_to_ids.get(this.eosToken),this.unkToken=this.vocab[this.unk_token_id],this.minScore=(0,p.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 pe=W.sentence,Ce=pe.length;let Fe=0;for(;Fe{const Ue=[...Array.from({length:94},(Fe,Oe)=>Oe+33),...Array.from({length:12},(Fe,Oe)=>Oe+161),...Array.from({length:82},(Fe,Oe)=>Oe+174)],W=Ue.slice();let pe=0;for(let Fe=0;Fe<256;++Fe)Ue.includes(Fe)||(Ue.push(Fe),W.push(256+pe),pe+=1);const Ce=W.map(Fe=>String.fromCharCode(Fe));return Object.fromEntries(Ue.map((Fe,Oe)=>[Fe,Ce[Oe]]))})(),Se=(0,a.reverseDictionary)(L);class Xe extends xe{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[pe,Ce]of this.tokens_to_ids)this.vocab[Ce]=pe;this.bpe_ranks=new Map(W.merges.map((pe,Ce)=>[pe,Ce])),this.merges=W.merges.map(pe=>pe.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 pe=this.cache.get(W);if(pe!==void 0)return pe;const Ce=Array.from(W);this.end_of_word_suffix&&(Ce[Ce.length-1]+=this.end_of_word_suffix);let Fe=[];if(Ce.length>1){const Oe=new h.PriorityQueue((St,kt)=>St.score`<0x${rt.toString(16).toUpperCase().padStart(2,"0")}>`)):pe.push(this.unk_token)}return pe}}class me extends xe{constructor(W,pe){super(W),this.tokens_to_ids=S(pe.target_lang?W.vocab[pe.target_lang]:W.vocab),this.bos_token=pe.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=pe.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=pe.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=pe.unk_token,this.unk_token_id=this.tokens_to_ids.get(this.unk_token),this.vocab=new Array(this.tokens_to_ids.size);for(const[Ce,Fe]of this.tokens_to_ids)this.vocab[Fe]=Ce}encode(W){return W}}class X extends o.Callable{constructor(W){super(),this.config=W}static fromConfig(W){if(W===null)return null;switch(W.type){case"BertNormalizer":return new pt(W);case"Precompiled":return new Qe(W);case"Sequence":return new st(W);case"Replace":return new ie(W);case"NFC":return new Me(W);case"NFKC":return new Q(W);case"NFKD":return new ge(W);case"Strip":return new Ke(W);case"StripAccents":return new Le(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 ie extends X{normalize(W){const pe=O(this.config.pattern);return pe===null?W:W.replaceAll(pe,this.config.content)}}class Me extends X{normalize(W){return W=W.normalize("NFC"),W}}class Q extends X{normalize(W){return W=W.normalize("NFKC"),W}}class ge extends X{normalize(W){return W=W.normalize("NFKD"),W}}class Ke extends X{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 Le extends X{normalize(W){return W=b(W),W}}class Be extends X{normalize(W){return W=W.toLowerCase(),W}}class We extends X{normalize(W){return W=this.config.prepend+W,W}}class st extends X{constructor(W){super(W),this.normalizers=W.normalizers.map(pe=>X.fromConfig(pe))}normalize(W){return this.normalizers.reduce((pe,Ce)=>Ce.normalize(pe),W)}}class pt extends X{_tokenize_chinese_chars(W){const pe=[];for(let Ce=0;Cethis.pre_tokenize_text(Ce,pe)):this.pre_tokenize_text(W,pe)).flat()}_call(W,pe){return this.pre_tokenize(W,pe)}}class Te extends Ge{constructor(W){super(),this.pattern=new RegExp(`[^\\s${j}]+|[${j}]`,"gu")}pre_tokenize_text(W,pe){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=L,this.text_encoder=new TextEncoder}pre_tokenize_text(W,pe){return this.add_prefix_space&&!W.startsWith(" ")&&(W=" "+W),(this.use_regex?W.match(this.pattern)||[]:[W]).map(Fe=>Array.from(this.text_encoder.encode(Fe),Oe=>this.byte_encoder[Oe]).join(""))}}class Ye extends Ge{constructor(W){super(),this.config=W,this.pattern=O(this.config.pattern,this.config.invert)}pre_tokenize_text(W,pe){return this.pattern===null?[]:this.config.invert?W.match(this.pattern)||[]:T(W,this.pattern)}}class et extends Ge{constructor(W){super(),this.config=W,this.pattern=new RegExp(`[^${j}]+|[${j}]+`,"gu")}pre_tokenize_text(W,pe){return W.match(this.pattern)||[]}}class A extends Ge{constructor(W){super(),this.config=W;const pe=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(pe,"gu")}pre_tokenize_text(W,pe){return W.match(this.pattern)||[]}}class $e extends o.Callable{constructor(W){super(),this.config=W}static fromConfig(W){if(W===null)return null;switch(W.type){case"TemplateProcessing":return new re(W);case"ByteLevel":return new ye(W);case"RobertaProcessing":return new se(W);case"BertProcessing":return new Pe(W);case"Sequence":return new R(W);default:throw new Error(`Unknown PostProcessor type: ${W.type}`)}}post_process(W,...pe){throw Error("post_process should be implemented in subclass.")}_call(W,...pe){return this.post_process(W,...pe)}}class Pe extends $e{constructor(W){super(W),this.cls=W.cls[0],this.sep=W.sep[0]}post_process(W,pe=null,{add_special_tokens:Ce=!0}={}){Ce&&(W=(0,a.mergeArrays)([this.cls],W,[this.sep]));let Fe=new Array(W.length).fill(0);if(pe!==null){const Oe=Ce&&this instanceof se?[this.sep]:[],rt=Ce?[this.sep]:[];W=(0,a.mergeArrays)(W,Oe,pe,rt),Fe=(0,a.mergeArrays)(Fe,new Array(pe.length+Oe.length+rt.length).fill(1))}return{tokens:W,token_type_ids:Fe}}}class se extends Pe{}class re extends $e{constructor(W){super(W),this.single=W.single,this.pair=W.pair}post_process(W,pe=null,{add_special_tokens:Ce=!0}={}){const Fe=pe===null?this.single:this.pair;let Oe=[],rt=[];for(const Mt of Fe)"SpecialToken"in Mt?Ce&&(Oe.push(Mt.SpecialToken.id),rt.push(Mt.SpecialToken.type_id)):"Sequence"in Mt&&(Mt.Sequence.id==="A"?(Oe=(0,a.mergeArrays)(Oe,W),rt=(0,a.mergeArrays)(rt,new Array(W.length).fill(Mt.Sequence.type_id))):Mt.Sequence.id==="B"&&(Oe=(0,a.mergeArrays)(Oe,pe),rt=(0,a.mergeArrays)(rt,new Array(pe.length).fill(Mt.Sequence.type_id))));return{tokens:Oe,token_type_ids:rt}}}class ye extends $e{post_process(W,pe=null){return pe&&(W=(0,a.mergeArrays)(W,pe)),{tokens:W}}}class R extends $e{constructor(W){super(W),this.processors=W.processors.map(pe=>$e.fromConfig(pe))}post_process(W,pe=null,Ce={}){let Fe;for(const Oe of this.processors)if(Oe instanceof ye)W=Oe.post_process(W).tokens,pe&&(pe=Oe.post_process(pe).tokens);else{const rt=Oe.post_process(W,pe,Ce);W=rt.tokens,Fe=rt.token_type_ids}return{tokens:W,token_type_ids:Fe}}}class ee 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 qe(W);case"ByteLevel":return new dt(W);case"Replace":return new D(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 D extends ee{decode_chain(W){const pe=O(this.config.pattern);return pe===null?W:W.map(Ce=>Ce.replaceAll(pe,this.config.content))}}class ue extends ee{constructor(W){super(W),this.text_decoder=new TextDecoder}decode_chain(W){const pe=[];let Ce=[];for(const Fe of W){let Oe=null;if(Fe.length===6&&Fe.startsWith("<0x")&&Fe.endsWith(">")){const rt=parseInt(Fe.slice(3,5),16);isNaN(rt)||(Oe=rt)}if(Oe!==null)Ce.push(Oe);else{if(Ce.length>0){const rt=this.text_decoder.decode(Uint8Array.from(Ce));pe.push(rt),Ce=[]}pe.push(Fe)}}if(Ce.length>0){const Fe=this.text_decoder.decode(Uint8Array.from(Ce));pe.push(Fe),Ce=[]}return pe}}class le extends ee{decode_chain(W){return[W.join("")]}}class ke extends ee{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(pe=>{let Ce=0;for(let Oe=0;Oe(Ce!==0&&(pe.startsWith(this.config.prefix)?pe=pe.replace(this.config.prefix,""):pe=" "+pe),this.cleanup&&(pe=w(pe)),pe))}}class dt extends ee{constructor(W){super(W),this.byte_decoder=Se,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(W){const pe=W.join(""),Ce=new Uint8Array([...pe].map(Oe=>this.byte_decoder[Oe]));return this.text_decoder.decode(Ce)}decode_chain(W){const pe=[];let Ce=[];for(const Fe of W)this.added_tokens.find(Oe=>Oe.content===Fe)!==void 0?(Ce.length>0&&(pe.push(this.convert_tokens_to_string(Ce)),Ce=[]),pe.push(Fe)):Ce.push(Fe);return Ce.length>0&&pe.push(this.convert_tokens_to_string(Ce)),pe}}class Je extends ee{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 pe=[W[0]];for(let Oe=1;OeOe!==this.pad_token).join("");return this.cleanup&&(Fe=w(Fe).replaceAll(this.word_delimiter_token," ").trim()),Fe}decode_chain(W){return[this.convert_tokens_to_string(W)]}}class Ve extends ee{constructor(W){super(W),this.decoders=W.decoders.map(pe=>ee.fromConfig(pe))}decode_chain(W){return this.decoders.reduce((pe,Ce)=>Ce.decode_chain(pe),W)}}class Z extends ee{constructor(W){super(W),this.suffix=this.config.suffix}decode_chain(W){return W.map((pe,Ce)=>pe.replaceAll(this.suffix,Ce===W.length-1?"":" "))}}class ve extends ee{decode_chain(W){let pe="";for(let Ce=1;CeCe.normalize("NFKC")).join("~"):W=W.normalize("NFKC"),W}}class tt extends Ge{constructor(W){super(),this.tokenizers=W.pretokenizers.map(pe=>Ge.fromConfig(pe))}pre_tokenize_text(W,pe){return this.tokenizers.reduce((Ce,Fe)=>Fe.pre_tokenize(Ce,pe),[W])}}class ft extends Ge{constructor(W){super()}pre_tokenize_text(W,pe){return W.match(/\w+|[^\w\s]+/g)||[]}}class ht extends Ge{constructor(W){super()}pre_tokenize_text(W,pe){return B(W)}}class Tt extends Ge{constructor(W){super(),this.config=W,this.pattern=O(this.config.pattern),this.content=this.config.content}pre_tokenize_text(W,pe){return this.pattern===null?[W]:[W.replaceAll(this.pattern,this.config.content)]}}const bt=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function Et(Ue,W,pe,Ce){for(const Fe of Object.keys(Ue)){const Oe=W-Ue[Fe].length,rt=pe(Fe),Mt=new Array(Oe).fill(rt);Ue[Fe]=Ce==="right"?(0,a.mergeArrays)(Ue[Fe],Mt):(0,a.mergeArrays)(Mt,Ue[Fe])}}function Lt(Ue,W){for(const pe of Object.keys(Ue))Ue[pe].length=W}class at extends o.Callable{constructor(pe,Ce){super();He(this,"return_token_type_ids",!1);He(this,"padding_side","right");this._tokenizer_config=Ce,this.normalizer=X.fromConfig(pe.normalizer),this.pre_tokenizer=Ge.fromConfig(pe.pre_tokenizer),this.model=xe.fromConfig(pe.model,Ce),this.post_processor=$e.fromConfig(pe.post_processor),this.decoder=ee.fromConfig(pe.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];for(const Fe of pe.added_tokens){const Oe=new ce(Fe);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=Ce.additional_special_tokens??[],this.special_tokens.push(...this.additional_special_tokens),this.special_tokens=[...new Set(this.special_tokens)],this.decoder&&(this.decoder.added_tokens=this.added_tokens,this.decoder.end_of_word_suffix=this.model.end_of_word_suffix),this.added_tokens_regex=this.added_tokens.length>0?new RegExp(this.added_tokens.toSorted((Fe,Oe)=>Oe.content.length-Fe.content.length).map(Fe=>`${Fe.lstrip?"\\s*":""}(${(0,a.escapeRegExp)(Fe.content)})${Fe.rstrip?"\\s*":""}`).join("|")):null,this.mask_token=this.getToken("mask_token"),this.mask_token_id=this.model.tokens_to_ids.get(this.mask_token),this.pad_token=this.getToken("pad_token","eos_token"),this.pad_token_id=this.model.tokens_to_ids.get(this.pad_token),this.sep_token=this.getToken("sep_token"),this.sep_token_id=this.model.tokens_to_ids.get(this.sep_token),this.unk_token=this.getToken("unk_token"),this.unk_token_id=this.model.tokens_to_ids.get(this.unk_token),this.model_max_length=Ce.model_max_length,this.remove_space=Ce.remove_space,this.clean_up_tokenization_spaces=Ce.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=Ce.do_lowercase_and_remove_accent??!1,Ce.padding_side&&(this.padding_side=Ce.padding_side),this.legacy=!1,this.chat_template=Ce.chat_template??null,Array.isArray(this.chat_template)){const Fe=Object.create(null);for(const{name:Oe,template:rt}of this.chat_template){if(typeof Oe!="string"||typeof rt!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');Fe[Oe]=rt}this.chat_template=Fe}this._compiled_template_cache=new Map}getToken(...pe){for(const Ce of pe){const Fe=this._tokenizer_config[Ce];if(Fe)if(typeof Fe=="object"){if(Fe.__type==="AddedToken")return Fe.content;throw Error(`Unknown token: ${Fe}`)}else return Fe}return null}static async from_pretrained(pe,{progress_callback:Ce=null,config:Fe=null,cache_dir:Oe=null,local_files_only:rt=!1,revision:Mt="main",legacy:St=null}={}){const kt=await E(pe,{progress_callback:Ce,config:Fe,cache_dir:Oe,local_files_only:rt,revision:Mt,legacy:St});return new this(...kt)}_call(pe,{text_pair:Ce=null,add_special_tokens:Fe=!0,padding:Oe=!1,truncation:rt=null,max_length:Mt=null,return_tensor:St=!0,return_token_type_ids:kt=null}={}){const It=Array.isArray(pe);let tr;if(It){if(pe.length===0)throw Error("text array must be non-empty");if(Ce!==null){if(Array.isArray(Ce)){if(pe.length!==Ce.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");tr=pe.map((or,qt)=>this._encode_plus(or,{text_pair:Ce[qt],add_special_tokens:Fe,return_token_type_ids:kt}))}else tr=pe.map(or=>this._encode_plus(or,{add_special_tokens:Fe,return_token_type_ids:kt}))}else{if(pe==null)throw Error("text may not be null or undefined");if(Array.isArray(Ce))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");tr=[this._encode_plus(pe,{text_pair:Ce,add_special_tokens:Fe,return_token_type_ids:kt})]}if(Mt===null?Oe==="max_length"?Mt=this.model_max_length:Mt=(0,p.max)(tr.map(or=>or.input_ids.length))[0]:rt||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."),Mt=Math.min(Mt,this.model_max_length??1/0),Oe||rt)for(let or=0;orMt?rt&&Lt(tr[or],Mt):Oe&&Et(tr[or],Mt,qt=>qt==="input_ids"?this.pad_token_id:0,this.padding_side));const Ar={};if(St){if(!(Oe&&rt)&&tr.some(qt=>{var _r;for(const Cn of Object.keys(qt))if(qt[Cn].length!==((_r=tr[0][Cn])==null?void 0:_r.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 or=[tr.length,tr[0].input_ids.length];for(const qt of Object.keys(tr[0]))Ar[qt]=new _.Tensor("int64",BigInt64Array.from(tr.flatMap(_r=>_r[qt]).map(BigInt)),or)}else{for(const or of Object.keys(tr[0]))Ar[or]=tr.map(qt=>qt[or]);if(!It)for(const or of Object.keys(Ar))Ar[or]=Ar[or][0]}return Ar}_encode_text(pe){return pe===null?null:(this.added_tokens_regex?pe.split(this.added_tokens_regex).filter(Oe=>Oe):[pe]).map((Oe,rt)=>{if(this.added_tokens.find(St=>St.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 St=this.pre_tokenizer!==null?this.pre_tokenizer(Oe,{section_index:rt}):[Oe];return this.model(St)}}).flat()}_encode_plus(pe,{text_pair:Ce=null,add_special_tokens:Fe=!0,return_token_type_ids:Oe=null}={}){const{tokens:rt,token_type_ids:Mt}=this._tokenize_helper(pe,{pair:Ce,add_special_tokens:Fe}),St=this.model.convert_tokens_to_ids(rt),kt={input_ids:St,attention_mask:new Array(St.length).fill(1)};return(Oe??this.return_token_type_ids)&&Mt&&(kt.token_type_ids=Mt),kt}_tokenize_helper(pe,{pair:Ce=null,add_special_tokens:Fe=!1}={}){const Oe=this._encode_text(pe),rt=this._encode_text(Ce);return this.post_processor?this.post_processor(Oe,rt,{add_special_tokens:Fe}):{tokens:(0,a.mergeArrays)(Oe??[],rt??[])}}tokenize(pe,{pair:Ce=null,add_special_tokens:Fe=!1}={}){return this._tokenize_helper(pe,{pair:Ce,add_special_tokens:Fe}).tokens}encode(pe,{text_pair:Ce=null,add_special_tokens:Fe=!0,return_token_type_ids:Oe=null}={}){return this._encode_plus(pe,{text_pair:Ce,add_special_tokens:Fe,return_token_type_ids:Oe}).input_ids}batch_decode(pe,Ce={}){return pe instanceof _.Tensor&&(pe=pe.tolist()),pe.map(Fe=>this.decode(Fe,Ce))}decode(pe,Ce={}){if(pe instanceof _.Tensor&&(pe=C(pe)),!Array.isArray(pe)||pe.length===0||!(0,a.isIntegralNumber)(pe[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(pe,Ce)}decode_single(pe,{skip_special_tokens:Ce=!1,clean_up_tokenization_spaces:Fe=null}){let Oe=this.model.convert_ids_to_tokens(pe);Ce&&(Oe=Oe.filter(Mt=>!this.special_tokens.includes(Mt)));let rt=this.decoder?this.decoder(Oe):Oe.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(rt=rt.replaceAll(this.decoder.end_of_word_suffix," "),Ce&&(rt=rt.trim())),(Fe??this.clean_up_tokenization_spaces)&&(rt=w(rt)),rt}apply_chat_template(pe,{tools:Ce=null,documents:Fe=null,chat_template:Oe=null,add_generation_prompt:rt=!1,tokenize:Mt=!0,padding:St=!1,truncation:kt=!1,max_length:It=null,return_tensor:tr=!0,return_dict:Ar=!1,tokenizer_kwargs:or={},...qt}={}){if(this.chat_template&&typeof this.chat_template=="object"||this.chat_template===null){const ct=this.chat_template;if(Oe!==null&&Object.hasOwn(ct,Oe))Oe=ct[Oe];else if(Oe===null&&"default"in ct)Oe=ct.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(ct).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 _r=this._compiled_template_cache.get(Oe);_r===void 0&&(_r=new g.Template(Oe),this._compiled_template_cache.set(Oe,_r));const Cn=Object.create(null);for(const ct of bt){const Kn=this.getToken(ct);Kn&&(Cn[ct]=Kn)}const gn=_r.render({messages:pe,add_generation_prompt:rt,tools:Ce,documents:Fe,...Cn,...qt});if(Mt){const ct=this._call(gn,{add_special_tokens:!1,padding:St,truncation:kt,max_length:It,return_tensor:tr,...or});return Ar?ct:ct.input_ids}return gn}}class Ot extends at{constructor(){super(...arguments);He(this,"return_token_type_ids",!0)}}class Ut extends at{constructor(){super(...arguments);He(this,"return_token_type_ids",!0)}}class Xt extends at{constructor(){super(...arguments);He(this,"return_token_type_ids",!0)}}class Yt extends at{constructor(){super(...arguments);He(this,"return_token_type_ids",!0)}}class rr extends at{constructor(){super(...arguments);He(this,"return_token_type_ids",!0)}}class Ht extends at{constructor(){super(...arguments);He(this,"return_token_type_ids",!0)}}class Pr extends at{constructor(){super(...arguments);He(this,"return_token_type_ids",!0)}}class Yr extends at{constructor(){super(...arguments);He(this,"return_token_type_ids",!0)}}class $r extends at{constructor(){super(...arguments);He(this,"return_token_type_ids",!0)}}class mt extends at{}class $t extends at{}class Bt extends at{constructor(pe,Ce){super(pe,Ce);He(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 un extends at{constructor(){super(...arguments);He(this,"return_token_type_ids",!0)}}class Bi extends at{}class Mi extends at{}class Gr extends at{}class wn extends at{constructor(W,pe){super(W,pe),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.special_tokens.filter(Ce=>this.languageRegex.test(Ce)),this.lang_to_token=Ce=>Ce}_build_translation_inputs(W,pe,Ce){return ki(this,W,pe,Ce)}}class Kr extends wn{}class pi extends at{}class Dr extends at{constructor(W,pe){var Oe,rt;const Ce=".,!?…。,、।۔،",Fe=(rt=(Oe=W.pre_tokenizer)==null?void 0:Oe.pretokenizers[0])==null?void 0:rt.pattern;Fe&&Fe.Regex===` ?[^(\\s|[${Ce}])]+`&&(Fe.Regex=` ?[^\\s${Ce}]+`),super(W,pe)}}const Ni="▁";class Ti extends at{constructor(pe,Ce){super(pe,Ce);He(this,"padding_side","left");this.legacy=Ce.legacy??!0,this.legacy||(this.normalizer=null,this.pre_tokenizer=new Re({replacement:Ni,add_prefix_space:!0,prepend_scheme:"first"}))}_encode_text(pe){if(pe===null)return null;if(this.legacy||pe.length===0)return super._encode_text(pe);let Ce=super._encode_text(Ni+pe.replaceAll(Ni," "));return Ce.length>1&&Ce[0]===Ni&&this.special_tokens.includes(Ce[1])&&(Ce=Ce.slice(1)),Ce}}class Cs extends at{}class Lo extends at{}class Ro extends at{}class Bo extends at{}class No extends at{}class ji extends at{}class Ps extends at{}class fo extends at{}class fi extends at{}function ki(Ue,W,pe,Ce){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 Fe=Ce.src_lang,Oe=Ce.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(Fe!==void 0){if(!Ue.language_codes.includes(Fe))throw new Error(`Source language code "${Fe}" is not valid. Must be one of: {${Ue.language_codes.join(", ")}}`);for(const rt of Ue.post_processor.config.single)if("SpecialToken"in rt&&Ue.languageRegex.test(rt.SpecialToken.id)){rt.SpecialToken.id=Ue.lang_to_token(Fe);break}}return Ce.forced_bos_token_id=Ue.model.convert_tokens_to_ids([Ue.lang_to_token(Oe)])[0],Ue._call(W,pe)}class Si extends at{constructor(W,pe){super(W,pe),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.special_tokens.filter(Ce=>this.languageRegex.test(Ce)),this.lang_to_token=Ce=>Ce}_build_translation_inputs(W,pe,Ce){return ki(this,W,pe,Ce)}}class Ji extends at{constructor(W,pe){super(W,pe),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.special_tokens.filter(Ce=>this.languageRegex.test(Ce)).map(Ce=>Ce.slice(2,-2)),this.lang_to_token=Ce=>`__${Ce}__`}_build_translation_inputs(W,pe,Ce){return ki(this,W,pe,Ce)}}class ho extends at{get timestamp_begin(){return this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0]+1}_decode_asr(W,{return_timestamps:pe=!1,return_language:Ce=!1,time_precision:Fe=null,force_full_sequences:Oe=!0}={}){if(Fe===null)throw Error("Must specify time_precision");let rt=null;const Mt=pe==="word";function St(){return{language:rt,timestamp:[null,null],text:""}}const kt=[];let It=St(),tr=0;const Ar=this.timestamp_begin;let or=[],qt=[],_r=!1,Cn=null;const gn=new Set(this.all_special_ids);for(const Tr of W){const cn=Tr.tokens,On=Mt?Tr.token_timestamps:null;let Jt=null,Un=Ar;if("stride"in Tr){const[Er,At,vr]=Tr.stride;if(tr-=At,Cn=Er-vr,At&&(Un=At/Fe+Ar),vr)for(let Lr=cn.length-1;Lr>=0;--Lr){const Xr=Number(cn[Lr]);if(Xr>=Ar){if(Jt!==null&&(Xr-Ar)*Fe=Ar){const vr=(At-Ar)*Fe+tr,Lr=(0,p.round)(vr,2);if(Jt!==null&&At>=Jt)_r=!0;else if(_r||or.length>0&&At0?(or.push(yn),Mt&&qt.push(Sr)):or.every(Er=>Er.length===0)&&(It=St(),or=[],yn=[],qt=[],Sr=[])}if(or.length>0){if(Oe&&pe)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[Tr,cn]=this.findLongestCommonSequence(or,qt),On=this.decode(Tr);It.text=On,Mt&&(It.words=this.collateWordTimestamps(Tr,cn,rt)),kt.push(It)}let ct=Object.create(null);const Kn=kt.map(Tr=>Tr.text).join("");if(pe||Ce){for(let Tr=0;Tr0;let Mt=rt?[]:null,St=rt?pe[0]:null;for(let kt=1;ktLr===Sr[Xr]&&St[cn+Xr]<=pe[kt][Un+Xr]).length:Er=Jt.filter((Lr,Xr)=>Lr===Sr[Xr]).length;const At=Tr/1e4,vr=Er/Tr+At;Er>1&&vr>tr&&(tr=vr,Ar=[cn,On,Un,yn])}const[qt,_r,Cn,gn]=Ar,ct=Math.floor((_r+qt)/2),Kn=Math.floor((gn+Cn)/2);Oe.push(...Ce.slice(0,ct)),Ce=It.slice(Kn),Fe=Ce.length,rt&&(Mt.push(...St.slice(0,ct)),St=pe[kt].slice(Kn))}return Oe.push(...Ce),rt?(Mt.push(...St),[Oe,Mt]):[Oe,[]]}collateWordTimestamps(W,pe,Ce){const[Fe,Oe,rt]=this.combineTokensIntoWords(W,Ce),Mt=[];for(let St=0;St=Fe){const Mt=((rt-Fe)*Ce).toFixed(2);Oe.push(`<|${Mt}|>`),Oe.push([])}else Oe[Oe.length-1].push(rt);return Oe=Oe.map(rt=>typeof rt=="string"?rt:super.decode(rt,pe)),Oe.join("")}splitTokensOnUnicode(W){const pe=this.decode(W,{decode_with_timestamps:!0}),Ce="�",Fe=[],Oe=[],rt=[];let Mt=[],St=[],kt=0;for(let It=0;It=this.model.tokens_to_ids.get("<|endoftext|>"),qt=It.startsWith(" "),_r=It.trim(),Cn=St.test(_r);if(or||qt||Cn||Oe.length===0)Oe.push(It),rt.push(tr),Mt.push(Ar);else{const gn=Oe.length-1;Oe[gn]+=It,rt[gn].push(...tr),Mt[gn].push(...Ar)}}return[Oe,rt,Mt]}mergePunctuations(W,pe,Ce,Fe,Oe){const rt=structuredClone(W),Mt=structuredClone(pe),St=structuredClone(Ce);let kt=rt.length-2,It=rt.length-1;for(;kt>=0;)rt[kt].startsWith(" ")&&Fe.includes(rt[kt].trim())?(rt[It]=rt[kt]+rt[It],Mt[It]=(0,a.mergeArrays)(Mt[kt],Mt[It]),St[It]=(0,a.mergeArrays)(St[kt],St[It]),rt[kt]="",Mt[kt]=[],St[kt]=[]):It=kt,--kt;for(kt=0,It=1;Ittr),Mt.filter(tr=>tr.length>0),St.filter(tr=>tr.length>0)]}get_decoder_prompt_ids({language:W=null,task:pe=null,no_timestamps:Ce=!0}={}){const Fe=[];if(W){const Oe=(0,M.whisper_language_to_code)(W),rt=this.model.tokens_to_ids.get(`<|${Oe}|>`);if(rt===void 0)throw new Error(`Unable to find language "${Oe}" in model vocabulary. Please report this issue at ${y.GITHUB_ISSUE_URL}.`);Fe.push(rt)}else Fe.push(null);if(pe){if(pe=pe.toLowerCase(),pe!=="transcribe"&&pe!=="translate")throw new Error(`Task "${pe}" is not supported. Must be one of: ["transcribe", "translate"]`);const Oe=this.model.tokens_to_ids.get(`<|${pe}|>`);if(Oe===void 0)throw new Error(`Unable to find task "${pe}" in model vocabulary. Please report this issue at ${y.GITHUB_ISSUE_URL}.`);Fe.push(Oe)}else Fe.push(null);if(Ce){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 ${y.GITHUB_ISSUE_URL}.`);Fe.push(Oe)}return Fe.map((Oe,rt)=>[rt+1,Oe]).filter(Oe=>Oe[1]!==null)}}class mo extends at{}class Zt extends at{}class eo extends at{}class jo extends at{constructor(W,pe){super(W,pe),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=this.model.vocab.filter(Ce=>this.languageRegex.test(Ce)),console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(W){if(W===null)return null;const[pe,...Ce]=W.trim().split(this.languageRegex);if(Ce.length===0)return super._encode_text(pe);if(Ce.length===2){const[Fe,Oe]=Ce;return this.supported_language_codes.includes(Fe)||console.warn(`Unsupported language code "${Fe}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),(0,a.mergeArrays)([Fe],super._encode_text(Oe))}}}class Uo extends at{}class go extends at{}class Vo extends at{}class Wo extends at{}class _o extends at{}class Go extends at{constructor(W,pe){super(W,pe),this.decoder=new ve({})}}class Vr extends at{}class jn{static async from_pretrained(W,{progress_callback:pe=null,config:Ce=null,cache_dir:Fe=null,local_files_only:Oe=!1,revision:rt="main",legacy:Mt=null}={}){var Ar;const[St,kt]=await E(W,{progress_callback:pe,config:Ce,cache_dir:Fe,local_files_only:Oe,revision:rt,legacy:Mt}),It=((Ar=kt.tokenizer_class)==null?void 0:Ar.replace(/Fast$/,""))??"PreTrainedTokenizer";let tr=this.TOKENIZER_CLASS_MAPPING[It];return tr||(console.warn(`Unknown tokenizer class "${It}", attempting to construct from base class.`),tr=at),new tr(St,kt)}}He(jn,"TOKENIZER_CLASS_MAPPING",{T5Tokenizer:Bi,DistilBertTokenizer:mt,CamembertTokenizer:$t,DebertaTokenizer:rr,DebertaV2Tokenizer:Ht,BertTokenizer:Ot,HerbertTokenizer:Pr,ConvBertTokenizer:Yr,RoFormerTokenizer:$r,XLMTokenizer:Bt,ElectraTokenizer:un,MobileBertTokenizer:Xt,SqueezeBertTokenizer:Yt,AlbertTokenizer:Ut,GPT2Tokenizer:Mi,BartTokenizer:Gr,MBartTokenizer:wn,MBart50Tokenizer:Kr,RobertaTokenizer:pi,WhisperTokenizer:ho,CodeGenTokenizer:mo,CLIPTokenizer:Zt,SiglipTokenizer:eo,MarianTokenizer:jo,BloomTokenizer:Dr,NllbTokenizer:Si,M2M100Tokenizer:Ji,LlamaTokenizer:Ti,CodeLlamaTokenizer:Cs,XLMRobertaTokenizer:Lo,MPNetTokenizer:Ro,FalconTokenizer:Bo,GPTNeoXTokenizer:No,EsmTokenizer:ji,Wav2Vec2CTCTokenizer:Uo,BlenderbotTokenizer:go,BlenderbotSmallTokenizer:Vo,SpeechT5Tokenizer:Wo,NougatTokenizer:_o,VitsTokenizer:Go,Qwen2Tokenizer:Ps,GemmaTokenizer:fo,Grok1Tokenizer:fi,CohereTokenizer:Vr,PreTrainedTokenizer:at})},"./src/utils/audio.js":(e,t,r)=>{r.r(t),r.d(t,{hamming:()=>M,hanning:()=>g,mel_filter_bank:()=>w,read_audio:()=>_,spectrogram:()=>B,window_function:()=>j});var o=r("./src/utils/hub.js"),a=r("./src/utils/maths.js"),l=r("./src/utils/core.js"),p=r("./src/utils/tensor.js");async function _(N,ae){if(typeof AudioContext>"u")throw Error("Unable to load audio from path/URL since `AudioContext` is not available in your environment. Instead, audio data should be passed directly to the pipeline/processor. For more information and some example code, see https://huggingface.co/docs/transformers.js/guides/node-audio-processing.");const ce=await(await(0,o.getFile)(N)).arrayBuffer(),xe=new AudioContext({sampleRate:ae});typeof ae>"u"&&console.warn(`No sampling rate provided, using default of ${xe.sampleRate}Hz.`);const Y=await xe.decodeAudioData(ce);let _e;if(Y.numberOfChannels===2){const L=Math.sqrt(2),Se=Y.getChannelData(0),Xe=Y.getChannelData(1);_e=new Float32Array(Se.length);for(let me=0;me2595*Math.log10(1+N/700),kaldi:N=>1127*Math.log(1+N/700),slaney:(N,ae=1e3,ce=15,xe=27/Math.log(6.4))=>N>=ae?ce+Math.log(N/ae)*xe:3*N/200};function E(N,ae="htk"){const ce=y[ae];if(!ce)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof N=="number"?ce(N):N.map(xe=>ce(xe))}const T={htk:N=>700*(10**(N/2595)-1),kaldi:N=>700*(Math.exp(N/1127)-1),slaney:(N,ae=1e3,ce=15,xe=Math.log(6.4)/27)=>N>=ce?ae*Math.exp(xe*(N-ce)):200*N/3};function O(N,ae="htk"){const ce=T[ae];if(!ce)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof N=="number"?ce(N):N.map(xe=>ce(xe))}function S(N,ae){const ce=Float64Array.from({length:ae.length-1},(L,Se)=>ae[Se+1]-ae[Se]),xe=Array.from({length:N.length},()=>new Array(ae.length));for(let L=0;Lnew Array(N.length));for(let L=0;LN+xe*_e)}function w(N,ae,ce,xe,Y,_e=null,L="htk",Se=!1){if(_e!==null&&_e!=="slaney")throw new Error('norm must be one of null or "slaney"');const Xe=E(ce,L),me=E(xe,L),X=C(Xe,me,ae+2);let ie=O(X,L),Me;if(Se){const ge=Y/(N*2);Me=E(Float64Array.from({length:N},(Ke,Le)=>Le*ge),L),ie=X}else Me=C(0,Math.floor(Y/2),N);const Q=S(Me,ie);if(_e!==null&&_e==="slaney")for(let ge=0;geY)throw Error(`frame_length (${ce}) may not be larger than fft_length (${Y})`);if(Ge!==ce)throw new Error(`Length of the window (${Ge}) must equal frame_length (${ce})`);if(xe<=0)throw new Error("hop_length must be greater than zero");if(_e===null&&X!==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(L){if(Se!=="reflect")throw new Error(`pad_mode="${Se}" not implemented yet.`);const ee=Math.floor((Y-1)/2)+1;N=b(N,ee,ee)}let Te=Math.floor(1+Math.floor((N.length-ce)/xe));Be!==null&&TeTe?st&&(et=We):et=Ye=We);const A=new a.FFT(Y),$e=new Float64Array(Y),Pe=new Float64Array(A.outputBufferSize),se=new Float32Array(je*et);for(let ee=0;ee=1;--le)$e[le]-=me*$e[le-1];$e[0]*=1-me}for(let le=0;leMath.pow(Se,.85));break;default:throw new Error(`Unknown window type ${ae}.`)}if(ce&&(L=L.subarray(0,N)),xe===null)return L;if(N>xe)throw new Error(`Length of the window (${N}) may not be larger than frame_length (${xe})`);return L}},"./src/utils/constants.js":(e,t,r)=>{r.r(t),r.d(t,{GITHUB_ISSUE_URL:()=>o});const o="https://github.com/xenova/transformers.js/issues/new/choose"},"./src/utils/core.js":(e,t,r)=>{r.r(t),r.d(t,{calculateDimensions:()=>h,calculateReflectOffset:()=>E,dispatchCallback:()=>o,escapeRegExp:()=>l,isIntegralNumber:()=>_,isTypedArray:()=>p,mergeArrays:()=>M,pick:()=>T,pop:()=>g,product:()=>y,reverseDictionary:()=>a});function o(O,S){O&&O(S)}function a(O){return Object.fromEntries(Object.entries(O).map(([S,C])=>[C,S]))}function l(O){return O.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function p(O){var S,C,w;return((w=(C=(S=O==null?void 0:O.prototype)==null?void 0:S.__proto__)==null?void 0:C.constructor)==null?void 0:w.name)==="TypedArray"}function _(O){return Number.isInteger(O)||typeof O=="bigint"}function h(O){const S=[];let C=O;for(;Array.isArray(C);)S.push(C.length),C=C[0];return S}function g(O,S,C=void 0){const w=O[S];if(w!==void 0)return delete O[S],w;if(C===void 0)throw Error(`Key ${S} does not exist in object.`);return C}function M(...O){return Array.prototype.concat.apply([],O)}function y(...O){return O.reduce((S,C)=>S.flatMap(w=>C.map(b=>[w,b])))}function E(O,S){return Math.abs((O+S)%(2*S)-S)}function T(O,S){return Object.assign({},...S.map(C=>{if(O[C]!==void 0)return{[C]:O[C]}}))}},"./src/utils/data-structures.js":(e,t,r)=>{r.r(t),r.d(t,{CharTrie:()=>a,PriorityQueue:()=>o,TokenLattice:()=>p});class o{constructor(g=(y,E)=>y>E,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 y=this._heap[g];this._heap[g]=this._heap[M],this._heap[M]=y}_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 E=new _(this.bosTokenId,0,0,0,0),T=new _(this.eosTokenId,1,this.len,0,0);this.nodes.push(E.clone()),this.nodes.push(T.clone()),this.beginNodes[this.len].push(T),this.endNodes[0].push(E)}insert(g,M,y,E){const T=this.nodes.length,O=new _(E,T,g,M,y);this.beginNodes[g].push(O),this.endNodes[g+M].push(O),this.nodes.push(O)}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 C=0,w=null;for(let b of this.endNodes[M]){const I=b.backtraceScore+S.score;(w===null||I>C)&&(w=b.clone(),C=I)}if(w!==null)S.prev=w,S.backtraceScore=C;else return[]}++M}const y=[],T=this.beginNodes[g][0].prev;if(T===null)return[];let O=T.clone();for(;O.prev!==null;)y.push(O.clone()),O=O.clone().prev.clone();return y.reverse(),y}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,y,E,T){this.tokenId=g,this.nodeId=M,this.pos=y,this.length=E,this.score=T,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,r)=>{r.r(t),r.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,r)=>{r.r(t),r.d(t,{DATA_TYPES:()=>p,DEFAULT_DEVICE_DTYPE_MAPPING:()=>_,DEFAULT_DTYPE_SUFFIX_MAPPING:()=>h,isWebGpuFp16Supported:()=>l});var o=r("./src/env.js"),a=r("./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}}(),p=Object.freeze({fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16"}),_=Object.freeze({[a.DEVICE_TYPES.wasm]:p.q8}),h=Object.freeze({[p.fp32]:"",[p.fp16]:"_fp16",[p.int8]:"_int8",[p.uint8]:"_uint8",[p.q8]:"_quantized",[p.q4]:"_q4",[p.q4f16]:"_q4f16",[p.bnb4]:"_bnb4"})},"./src/utils/generic.js":(e,t,r)=>{r.r(t),r.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,r)=>{r.r(t),r.d(t,{getFile:()=>M,getModelFile:()=>S,getModelJSON:()=>C});var o=r("?7a2c"),a=r("?a42a"),l=r("./src/env.js"),p=r("./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 z=o.statSync(U);this.headers.set("content-length",z.size.toString()),this.updateContentType();let B=this;this.body=new ReadableStream({start(j){B.arrayBuffer().then(N=>{j.enqueue(new Uint8Array(N)),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,z=null){let B;try{B=new URL(I)}catch{return!1}return!(U&&!U.includes(B.protocol)||z&&!z.includes(B.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 z=!!(ko!=null&&ko.TESTING_REMOTELY),B=l.env.version,j=new Headers;if(j.set("User-Agent",`transformers.js/${B}; is_ci/${z};`),g(I,["http:","https:"],["huggingface.co","hf.co"])){const ae=(ko==null?void 0:ko.HF_TOKEN)??(ko==null?void 0:ko.HF_ACCESS_TOKEN);ae&&j.set("Authorization",`Bearer ${ae}`)}return fetch(I,{headers:j})}else return fetch(I)}const y={400:"Bad request error occurred while trying to load file",401:"Unauthorized access to file",403:"Forbidden access to file",404:"Could not locate file",408:"Request timeout error occurred while trying to load file",500:"Internal server error error occurred while trying to load file",502:"Bad gateway error occurred while trying to load file",503:"Service unavailable error occurred while trying to load file",504:"Gateway timeout error occurred while trying to load file"};function E(I,U,z){if(!z)return null;const B=y[I]??`Error (${I}) occurred while trying to load file`;throw Error(`${B}: "${U}".`)}class T{constructor(U){this.path=U}async match(U){let z=a.join(this.path,U),B=new h(z);if(B.exists)return B}async put(U,z){const B=Buffer.from(await z.arrayBuffer());let j=a.join(this.path,U);try{await o.promises.mkdir(a.dirname(j),{recursive:!0}),await o.promises.writeFile(j,B)}catch(N){console.warn("An error occurred while writing the file to cache:",N)}}}async function O(I,...U){for(let z of U)try{let B=await I.match(z);if(B)return B}catch{continue}}async function S(I,U,z=!0,B={}){if(!l.env.allowLocalModels){if(B.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,p.dispatchCallback)(B.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(Me){console.warn("An error occurred while opening the browser cache:",Me)}}if(!j&&l.env.useFSCache&&(j=new T(B.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 N=B.revision??"main";let ae=b(I,U),ce=b(l.env.localModelPath,ae),xe=b(l.env.remoteHost,l.env.remotePathTemplate.replaceAll("{model}",I).replaceAll("{revision}",encodeURIComponent(N)),U),Y=N==="main"?ae:b(I,N,U),_e,L=j instanceof T?Y:xe,Se=!1,Xe;j&&(Xe=await O(j,ce,L));const me=Xe!==void 0;if(Xe===void 0){if(l.env.allowLocalModels)if(g(ae,["http:","https:"])){if(B.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${ae}.`);if(!l.env.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${ae}.`)}else try{Xe=await M(ce),_e=ce}catch(Q){console.warn(`Unable to load from local path "${ce}": "${Q}"`)}if(Xe===void 0||Xe.status===404){if(B.local_files_only||!l.env.allowRemoteModels){if(z)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${ce}".`);return null}if(Xe=await M(xe),Xe.status!==200)return E(Xe.status,xe,z);_e=L}Se=j&&typeof Response<"u"&&Xe instanceof Response&&Xe.status===200}(0,p.dispatchCallback)(B.progress_callback,{status:"download",name:I,file:U});const X={status:"progress",name:I,file:U};let ie;return B.progress_callback?me&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent)?(ie=new Uint8Array(await Xe.arrayBuffer()),(0,p.dispatchCallback)(B.progress_callback,{...X,progress:100,loaded:ie.length,total:ie.length})):ie=await w(Xe,Me=>{(0,p.dispatchCallback)(B.progress_callback,{...X,...Me})}):ie=new Uint8Array(await Xe.arrayBuffer()),Se&&_e&&await j.match(_e)===void 0&&await j.put(_e,new Response(ie,{headers:Xe.headers})).catch(Me=>{console.warn(`Unable to add response to browser cache: ${Me}.`)}),(0,p.dispatchCallback)(B.progress_callback,{status:"done",name:I,file:U}),ie}async function C(I,U,z=!0,B={}){let j=await S(I,U,z,B);if(j===null)return{};let ae=new TextDecoder("utf-8").decode(j);return JSON.parse(ae)}async function w(I,U){const z=I.headers.get("Content-Length");z===null&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let B=parseInt(z??"0"),j=new Uint8Array(B),N=0;const ae=I.body.getReader();async function ce(){const{done:xe,value:Y}=await ae.read();if(xe)return;let _e=N+Y.length;if(_e>B){B=_e;let Se=new Uint8Array(B);Se.set(j),j=Se}j.set(Y,N),N=_e;const L=N/B*100;return U({progress:L,loaded:N,total:B}),ce()}return await ce(),j}function b(...I){return I=I.map((U,z)=>(z&&(U=U.replace(new RegExp("^/"),"")),z!==I.length-1&&(U=U.replace(new RegExp("/$"),"")),U)),I.join("/")}},"./src/utils/image.js":(e,t,r)=>{r.r(t),r.d(t,{RawImage:()=>O});var o=r("./src/utils/hub.js"),a=r("./src/env.js"),l=r("./src/utils/tensor.js"),p=r("?2b25");const _=typeof self<"u",h=_&&self.constructor.name==="DedicatedWorkerGlobalScope";let g,M,y;if(_)g=(S,C)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(S,C)},y=self.createImageBitmap,M=self.ImageData;else if(p)y=async S=>{const w=(await S.metadata()).channels,{data:b,info:I}=await S.rotate().raw().toBuffer({resolveWithObject:!0}),U=new O(new Uint8ClampedArray(b),I.width,I.height,I.channels);return w!==void 0&&w!==I.channels&&U.convert(w),U};else throw new Error("Unable to load image processing library.");const E={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},T=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]);class O{constructor(C,w,b,I){this.data=C,this.width=w,this.height=b,this.channels=I}get size(){return[this.width,this.height]}static async read(C){if(C instanceof O)return C;if(typeof C=="string"||C instanceof URL)return await this.fromURL(C);throw new Error(`Unsupported input type: ${typeof C}`)}static fromCanvas(C){if(!_)throw new Error("fromCanvas() is only supported in browser environments.");const b=C.getContext("2d").getImageData(0,0,C.width,C.height).data;return new O(b,C.width,C.height,4)}static async fromURL(C){const w=await(0,o.getFile)(C);if(w.status!==200)throw new Error(`Unable to read image from "${C}" (${w.status} ${w.statusText})`);const b=await w.blob();return this.fromBlob(b)}static async fromBlob(C){if(_){const w=await y(C),b=g(w.width,w.height).getContext("2d");return b.drawImage(w,0,0),new this(b.getImageData(0,0,w.width,w.height).data,w.width,w.height,4)}else{const w=p(await C.arrayBuffer());return await y(w)}}static fromTensor(C,w="CHW"){if(C.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${C.dims.length} dimensions.`);if(w==="CHW")C=C.transpose(1,2,0);else if(w!=="HWC")throw new Error(`Unsupported channel format: ${w}`);if(!(C.data instanceof Uint8ClampedArray||C.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${C.type}`);switch(C.dims[2]){case 1:case 2:case 3:case 4:return new O(C.data,C.dims[1],C.dims[0],C.dims[2]);default:throw new Error(`Unsupported number of channels: ${C.dims[2]}`)}}grayscale(){if(this.channels===1)return this;const C=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let w=0,b=0;w=0?j=b:ae=-b,I>=0?N=I:ce=-I,B.drawImage(z,j,N,C,w,ae,ce,C,w),new O(B.getImageData(0,0,C,w).data,C,w,4).convert(U)}else{let U=this.toSharp();if(b>=0&&I>=0)U=U.extract({left:Math.floor(b),top:Math.floor(I),width:C,height:w});else if(b<=0&&I<=0){const z=Math.floor(-I),B=Math.floor(-b);U=U.extend({top:z,left:B,right:C-this.width-B,bottom:w-this.height-z})}else{let z=[0,0],B=0;I<0?(z[0]=Math.floor(-I),z[1]=w-this.height-z[0]):B=Math.floor(I);let j=[0,0],N=0;b<0?(j[0]=Math.floor(-b),j[1]=C-this.width-j[0]):N=Math.floor(b),U=U.extend({top:z[0],bottom:z[1],left:j[0],right:j[1]}).extract({left:N,top:B,width:C,height:w})}return await y(U)}}async toBlob(C="image/png",w=1){if(!_)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:C,quality:w})}toTensor(C="CHW"){let w=new l.Tensor("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(C!=="HWC")if(C==="CHW")w=w.permute(2,0,1);else throw new Error(`Unsupported channel format: ${C}`);return w}toCanvas(){if(!_)throw new Error("toCanvas() is only supported in browser environments.");const C=this.clone().rgba(),w=g(C.width,C.height),b=new M(C.data,C.width,C.height);return w.getContext("2d").putImageData(b,0,0),w}_update(C,w,b,I=null){return this.data=C,this.width=w,this.height=b,I!==null&&(this.channels=I),this}clone(){return new O(this.data.slice(),this.width,this.height,this.channels)}convert(C){if(this.channels===C)return this;switch(C){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(C){if(_){if(h)throw new Error("Unable to save an image from a Web Worker.");const w=C.split(".").pop().toLowerCase(),b=T.get(w)??"image/png",I=await this.toBlob(b),U=URL.createObjectURL(I),z=document.createElement("a");z.href=U,z.download=C,z.click(),z.remove()}else{if(a.env.useFS)return await this.toSharp().toFile(C);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 p(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}}},"./src/utils/maths.js":(e,t,r)=>{r.r(t),r.d(t,{FFT:()=>S,bankers_round:()=>b,cos_sim:()=>h,dot:()=>_,dynamic_time_warping:()=>I,interpolate_data:()=>o,log_softmax:()=>p,magnitude:()=>g,max:()=>y,medianFilter:()=>C,min:()=>M,permute_data:()=>a,round:()=>w,softmax:()=>l});function o(U,[z,B,j],[N,ae],ce="bilinear",xe=!1){const Y=ae/j,_e=N/B,L=new U.constructor(N*ae*z),Se=B*j,Xe=N*ae;for(let me=0;me=0;--xe)N[xe]=Y,j[xe]=z[B[xe]],Y*=j[xe];const ae=B.map((xe,Y)=>N[B.indexOf(Y)]),ce=new U.constructor(U.length);for(let xe=0;xe=0;--_e)Y+=L%z[_e]*ae[_e],L=Math.floor(L/z[_e]);ce[Y]=U[xe]}return[ce,j]}function l(U){const z=y(U)[0],B=U.map(ae=>Math.exp(ae-z)),j=B.reduce((ae,ce)=>ae+ce,0);return B.map(ae=>ae/j)}function p(U){return l(U).map(j=>Math.log(j))}function _(U,z){let B=0;for(let j=0;jz+B*B,0))}function M(U){if(U.length===0)throw Error("Array must not be empty");let z=U[0],B=0;for(let j=1;jz&&(z=U[j],B=j);return[Number(z),B]}function E(U){return U>0&&(U&U-1)===0}class T{constructor(z){if(this.size=z|0,this.size<=1||!E(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=z<<1,this.table=new Float64Array(this.size*2);for(let j=0;jj;j<<=1)++B;this._width=B%2===0?B-1:B,this._bitrev=new Int32Array(1<>>N&3)<>>1);for(let N=0;N>>1]=z[N];return j}toComplexArray(z,B){const j=B||this.createComplexArray();for(let N=0;N>>1],j[N+1]=0;return j}transform(z,B){if(z===B)throw new Error("Input and output buffers must be different");this._transform4(z,B,1)}realTransform(z,B){if(z===B)throw new Error("Input and output buffers must be different");this._realTransform4(z,B,1)}inverseTransform(z,B){if(z===B)throw new Error("Input and output buffers must be different");this._transform4(z,B,-1);for(let j=0;j>=2;ce>=2;ce>>=2){xe=N/ce<<1;const Xe=xe>>>2;for(Y=0;Y>>1,ce>>>1)}else for(Y=0,_e=0;Y>>1,ce>>>1,j)}const Se=this.table;for(ce>>=2;ce>=2;ce>>=2){xe=N/ce<<1;const me=xe>>>1,X=me>>>1,ie=X>>>1;for(Y=0;Y>>1;for(let me=2;me>1;++L){const Se=(L+1-z)**2/2,Xe=Math.sqrt(Y**2+_e**2)**Se,me=Se*Math.atan2(_e,Y),X=2*L;ae[X]=Xe*Math.cos(me),ae[X+1]=Xe*Math.sin(me),ce[X]=ae[X],ce[X+1]=-ae[X+1]}this._slicedChirpBuffer=ae.subarray(B,j),this._f=new T(N>>1),this._f.transform(this._chirpBuffer,ce)}_transform(z,B,j){const N=this._buffer1,ae=this._buffer2,ce=this._outBuffer1,xe=this._outBuffer2,Y=this._chirpBuffer,_e=this._slicedChirpBuffer,L=this._a;if(j)for(let Se=0;Se<_e.length;Se+=2){const Xe=Se+1,me=Se>>1,X=B[me];N[Se]=X*_e[Se],N[Xe]=X*_e[Xe]}else for(let Se=0;Se<_e.length;Se+=2){const Xe=Se+1;N[Se]=B[Se]*_e[Se]-B[Xe]*_e[Xe],N[Xe]=B[Se]*_e[Xe]+B[Xe]*_e[Se]}this._f.transform(ce,N);for(let Se=0;Se=U.length&&(Y=2*(U.length-1)-Y),j[ce++]=U[Y]}j.sort(),B[ae]=j[N]}return B}function w(U,z){const B=Math.pow(10,z);return Math.round(U*B)/B}function b(U){const z=Math.round(U);return Math.abs(U)%1===.5?z%2===0?z:z-1:z}function I(U){const z=U.length,B=U[0].length,j=[z+1,B+1],N=Array.from({length:j[0]},()=>Array(j[1]).fill(1/0));N[0][0]=0;const ae=Array.from({length:j[0]},()=>Array(j[1]).fill(-1));for(let L=1;L0||xe>0;)switch(Y.push(ce-1),_e.push(xe-1),ae[ce][xe]){case 0:--ce,--xe;break;case 1:--ce;break;case 2:--xe;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${ce}, ${xe}]. Please file a bug report.`)}return Y.reverse(),_e.reverse(),[Y,_e]}},"./src/utils/tensor.js":(e,t,r)=>{r.r(t),r.d(t,{Tensor:()=>_,cat:()=>U,full:()=>ce,full_like:()=>xe,interpolate:()=>M,interpolate_4d:()=>y,layer_norm:()=>C,matmul:()=>E,mean:()=>j,mean_pooling:()=>S,ones:()=>Y,ones_like:()=>_e,permute:()=>g,quantize_embeddings:()=>Xe,rfft:()=>T,stack:()=>z,std_mean:()=>B,topk:()=>O,zeros:()=>L,zeros_like:()=>Se});var o=r("./src/utils/maths.js"),a=r("./src/backends/onnx.js"),l=r("./src/ops/registry.js");const p=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(...X){He(this,"ort_tensor");return(0,a.isONNXTensor)(X[0])?this.ort_tensor=X[0]:this.ort_tensor=new a.Tensor(X[0],X[1],X[2]),new Proxy(this,{get:(ie,Me)=>{if(typeof Me=="string"){let Q=Number(Me);if(Number.isInteger(Q))return ie._getitem(Q)}return ie[Me]},set:(ie,Me,Q)=>ie[Me]=Q})}get dims(){return this.ort_tensor.dims}set dims(X){this.ort_tensor.dims=X}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[X,...ie]=this.dims;if(ie.length>0){const Me=ie.reduce((Q,ge)=>Q*ge);for(let Q=0;Q0){const Q=Me.reduce((ge,Ke)=>ge*Ke);return this._subarray(X,Q,Me)}else return new _(this.type,[this.data[X]],Me)}indexOf(X){const ie=this.data;for(let Me=0;MeGe)throw new Error(`Invalid slice: ${st}`);const Te=[Math.max(pt,0),Math.min(Ge,this.dims[We])];Me.push(Te),ie.push(Te[1]-Te[0])}else throw new Error(`Invalid slice: ${st}`)}const Q=Me.map(([We,st])=>st-We),ge=Q.reduce((We,st)=>We*st),Ke=this.data,Le=new Ke.constructor(ge),Be=this.stride();for(let We=0;We=0;--pt){const Te=Q[pt];st+=(Ge%Te+Me[pt][0])*Be[pt],Ge=Math.floor(Ge/Te)}Le[We]=Ke[st]}return new _(this.type,Le,ie)}permute(...X){return g(this,X)}transpose(...X){return this.permute(...X)}sum(X=null,ie=!1){return this.norm(1,X,ie)}norm(X="fro",ie=null,Me=!1){if(X==="fro")X=2;else if(typeof X=="string")throw Error(`Unsupported norm: ${X}`);const Q=this.data;if(ie===null){let Le=Q.reduce((Be,We)=>Be+We**X,0)**(1/X);return new _(this.type,[Le],[])}ie=I(ie,this.dims.length);const ge=this.dims.slice();ge[ie]=1;const Ke=new Q.constructor(Q.length/this.dims[ie]);for(let Le=0;Le=0;--We){const Ge=this.dims[We];if(We!==ie){const Te=st%Ge;Be+=Te*pt,pt*=ge[We]}st=Math.floor(st/Ge)}Ke[Be]+=Q[Le]**X}if(X!==1)for(let Le=0;Le=0;--Be){const pt=this.dims[Be];if(Be!==ie){const Ge=We%pt;Le+=Ge*st,st*=this.dims[Be]}We=Math.floor(We/pt)}Q[Ke]/=ge[Le]}return this}normalize(X=2,ie=1){return this.clone().normalize_(X,ie)}stride(){return N(this.dims)}squeeze(X=null){return new _(this.type,this.data,w(this.dims,X))}squeeze_(X=null){return this.dims=w(this.dims,X),this}unsqueeze(X=null){return new _(this.type,this.data,b(this.dims,X))}unsqueeze_(X=null){return this.dims=b(this.dims,X),this}flatten_(X=0,ie=-1){ie=(ie+this.dims.length)%this.dims.length;let Me=this.dims.slice(0,X),Q=this.dims.slice(X,ie+1),ge=this.dims.slice(ie+1);return this.dims=[...Me,Q.reduce((Ke,Le)=>Ke*Le,1),...ge],this}flatten(X=0,ie=-1){return this.clone().flatten_(X,ie)}view(...X){let ie=-1;for(let Q=0;QLe!==ie?ge*Ke:ge,1);X[ie]=Me.length/Q}return new _(this.type,Me,X)}neg_(){const X=this.data;for(let ie=0;iege*Ke);if(ie!==Me)throw Error(`cannot reshape array of size ${ie} into shape (${X})`);let Q=me;for(let ge=X.length-1;ge>=0;ge--)Q=Q.reduce((Ke,Le)=>{let Be=Ke[Ke.length-1];return Be.lengthie!==1):typeof X=="number"?me[X]===1&&me.splice(X,1):Array.isArray(X)&&(me=me.filter((ie,Me)=>ie!==1||!X.includes(Me))),me}function b(me,X){return X=I(X,me.length+1),me=me.slice(),me.splice(X,0,1),me}function I(me,X,ie=null,Me=!0){if(Me&&(me<-X||me>=X))throw new Error(`IndexError: index ${me} is out of bounds for dimension${ie===null?"":" "+ie} with size ${X}`);return me<0&&(me=(me%X+X)%X),me}function U(me,X=0){X=I(X,me[0].dims.length);const ie=me[0].dims.slice();ie[X]=me.reduce((Ke,Le)=>Ke+Le.dims[X],0);const Me=ie.reduce((Ke,Le)=>Ke*Le,1),Q=new me[0].data.constructor(Me),ge=me[0].type;if(X===0){let Ke=0;for(const Le of me){const Be=Le.data;Q.set(Be,Ke),Ke+=Be.length}}else{let Ke=0;for(let Le=0;Le=0;--Ge){const Ye=We[Ge];let et=Te%Ye;Ge===X&&(et+=Ke),pt+=et*je,je*=ie[Ge],Te=Math.floor(Te/Ye)}Q[pt]=Be[st]}Ke+=We[X]}}return new _(ge,Q,ie)}function z(me,X=0){return U(me.map(ie=>ie.unsqueeze(X)),X)}function B(me,X=null,ie=1,Me=!1){const Q=me.data,ge=me.dims;if(X===null){const Ge=Q.reduce((et,A)=>et+A,0)/Q.length,Te=Math.sqrt(Q.reduce((et,A)=>et+(A-Ge)**2,0)/(Q.length-ie)),je=new _(me.type,[Ge],[]);return[new _(me.type,[Te],[]),je]}X=I(X,ge.length);const Ke=j(me,X,Me),Le=Ke.data,Be=ge.slice();Be[X]=1;const We=new Q.constructor(Q.length/ge[X]);for(let pt=0;pt=0;--Te){const et=ge[Te];if(Te!==X){const A=je%et;Ge+=A*Ye,Ye*=Be[Te]}je=Math.floor(je/et)}We[Ge]+=(Q[pt]-Le[Ge])**2}for(let pt=0;ptBe+We,0);return new _(me.type,[Le/Me.length],[])}const Q=me.dims;X=I(X,Q.length);const ge=Q.slice();ge[X]=1;const Ke=new Me.constructor(Me.length/Q[X]);for(let Le=0;Le=0;--We){const Ge=Q[We];if(We!==X){const Te=st%Ge;Be+=Te*pt,pt*=ge[We]}st=Math.floor(st/Ge)}Ke[Be]+=Me[Le]}if(Q[X]!==1)for(let Le=0;Le=0;--ie)X[ie]=Me,Me*=me[ie];return X}function ae(me,X,ie,Me){const Q=me.reduce((ge,Ke)=>ge*Ke,1);return new _(ie,new Me(Q).fill(X),me)}function ce(me,X){let ie,Me;if(typeof X=="number")ie="float32",Me=Float32Array;else if(typeof X=="bigint")ie="int64",Me=BigInt64Array;else throw new Error(`Unsupported data type: ${typeof X}`);return ae(me,X,ie,Me)}function xe(me,X){return ce(me.dims,X)}function Y(me){return ae(me,1n,"int64",BigInt64Array)}function _e(me){return Y(me.dims)}function L(me){return ae(me,0n,"int64",BigInt64Array)}function Se(me){return L(me.dims)}function Xe(me,X){if(me.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(me.dims.at(-1)%8!==0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(X))throw new Error("The precision must be either 'binary' or 'ubinary'");const ie=X==="binary",Me=ie?"int8":"uint8",Q=ie?Int8Array:Uint8Array,ge=me.data,Ke=new Q(ge.length/8);for(let Le=0;Le0?1:0,We=Math.floor(Le/8),st=Le%8;Ke[We]|=Be<<7-st,ie&&st===0&&(Ke[We]-=128)}return new _(Me,Ke,[me.dims[0],me.dims[1]/8])}}},M1={};function en(e){var t=M1[e];if(t!==void 0)return t.exports;var r=M1[e]={exports:{}};return uE[e](r,r.exports,en),r.exports}(()=>{var e=Object.getPrototypeOf?r=>Object.getPrototypeOf(r):r=>r.__proto__,t;en.t=function(r,o){if(o&1&&(r=this(r)),o&8||typeof r=="object"&&r&&(o&4&&r.__esModule||o&16&&typeof r.then=="function"))return r;var a=Object.create(null);en.r(a);var l={};t=t||[null,e({}),e([]),e(e)];for(var p=o&2&&r;typeof p=="object"&&!~t.indexOf(p);p=e(p))Object.getOwnPropertyNames(p).forEach(_=>l[_]=()=>r[_]);return l.default=()=>r,en.d(a,l),a}})();en.d=(e,t)=>{for(var r in t)en.o(t,r)&&!en.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})};en.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);en.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(/\/[^\/]+$/,"/"),en.p=e})();en.b=void 0;var P={};(()=>{/*!*****************************!*\ + !*** ./src/transformers.js ***! + \*****************************/en.r(P),en.d(P,{ASTFeatureExtractor:()=>a.ASTFeatureExtractor,ASTForAudioClassification:()=>r.ASTForAudioClassification,ASTModel:()=>r.ASTModel,ASTPreTrainedModel:()=>r.ASTPreTrainedModel,AlbertForMaskedLM:()=>r.AlbertForMaskedLM,AlbertForQuestionAnswering:()=>r.AlbertForQuestionAnswering,AlbertForSequenceClassification:()=>r.AlbertForSequenceClassification,AlbertModel:()=>r.AlbertModel,AlbertPreTrainedModel:()=>r.AlbertPreTrainedModel,AlbertTokenizer:()=>o.AlbertTokenizer,AudioClassificationPipeline:()=>t.AudioClassificationPipeline,AutoConfig:()=>l.AutoConfig,AutoModel:()=>r.AutoModel,AutoModelForAudioClassification:()=>r.AutoModelForAudioClassification,AutoModelForAudioFrameClassification:()=>r.AutoModelForAudioFrameClassification,AutoModelForCTC:()=>r.AutoModelForCTC,AutoModelForCausalLM:()=>r.AutoModelForCausalLM,AutoModelForDepthEstimation:()=>r.AutoModelForDepthEstimation,AutoModelForDocumentQuestionAnswering:()=>r.AutoModelForDocumentQuestionAnswering,AutoModelForImageClassification:()=>r.AutoModelForImageClassification,AutoModelForImageFeatureExtraction:()=>r.AutoModelForImageFeatureExtraction,AutoModelForImageMatting:()=>r.AutoModelForImageMatting,AutoModelForImageSegmentation:()=>r.AutoModelForImageSegmentation,AutoModelForImageToImage:()=>r.AutoModelForImageToImage,AutoModelForMaskGeneration:()=>r.AutoModelForMaskGeneration,AutoModelForMaskedLM:()=>r.AutoModelForMaskedLM,AutoModelForObjectDetection:()=>r.AutoModelForObjectDetection,AutoModelForQuestionAnswering:()=>r.AutoModelForQuestionAnswering,AutoModelForSemanticSegmentation:()=>r.AutoModelForSemanticSegmentation,AutoModelForSeq2SeqLM:()=>r.AutoModelForSeq2SeqLM,AutoModelForSequenceClassification:()=>r.AutoModelForSequenceClassification,AutoModelForSpeechSeq2Seq:()=>r.AutoModelForSpeechSeq2Seq,AutoModelForTextToSpectrogram:()=>r.AutoModelForTextToSpectrogram,AutoModelForTextToWaveform:()=>r.AutoModelForTextToWaveform,AutoModelForTokenClassification:()=>r.AutoModelForTokenClassification,AutoModelForVision2Seq:()=>r.AutoModelForVision2Seq,AutoModelForXVector:()=>r.AutoModelForXVector,AutoModelForZeroShotObjectDetection:()=>r.AutoModelForZeroShotObjectDetection,AutoProcessor:()=>a.AutoProcessor,AutoTokenizer:()=>o.AutoTokenizer,AutomaticSpeechRecognitionPipeline:()=>t.AutomaticSpeechRecognitionPipeline,BartForConditionalGeneration:()=>r.BartForConditionalGeneration,BartForSequenceClassification:()=>r.BartForSequenceClassification,BartModel:()=>r.BartModel,BartPretrainedModel:()=>r.BartPretrainedModel,BartTokenizer:()=>o.BartTokenizer,BaseModelOutput:()=>r.BaseModelOutput,BaseStreamer:()=>M.BaseStreamer,BeitFeatureExtractor:()=>a.BeitFeatureExtractor,BeitForImageClassification:()=>r.BeitForImageClassification,BeitModel:()=>r.BeitModel,BeitPreTrainedModel:()=>r.BeitPreTrainedModel,BertForMaskedLM:()=>r.BertForMaskedLM,BertForQuestionAnswering:()=>r.BertForQuestionAnswering,BertForSequenceClassification:()=>r.BertForSequenceClassification,BertForTokenClassification:()=>r.BertForTokenClassification,BertModel:()=>r.BertModel,BertPreTrainedModel:()=>r.BertPreTrainedModel,BertTokenizer:()=>o.BertTokenizer,BitImageProcessor:()=>a.BitImageProcessor,BlenderbotForConditionalGeneration:()=>r.BlenderbotForConditionalGeneration,BlenderbotModel:()=>r.BlenderbotModel,BlenderbotPreTrainedModel:()=>r.BlenderbotPreTrainedModel,BlenderbotSmallForConditionalGeneration:()=>r.BlenderbotSmallForConditionalGeneration,BlenderbotSmallModel:()=>r.BlenderbotSmallModel,BlenderbotSmallPreTrainedModel:()=>r.BlenderbotSmallPreTrainedModel,BlenderbotSmallTokenizer:()=>o.BlenderbotSmallTokenizer,BlenderbotTokenizer:()=>o.BlenderbotTokenizer,BloomForCausalLM:()=>r.BloomForCausalLM,BloomModel:()=>r.BloomModel,BloomPreTrainedModel:()=>r.BloomPreTrainedModel,BloomTokenizer:()=>o.BloomTokenizer,CLIPFeatureExtractor:()=>a.CLIPFeatureExtractor,CLIPImageProcessor:()=>a.CLIPImageProcessor,CLIPModel:()=>r.CLIPModel,CLIPPreTrainedModel:()=>r.CLIPPreTrainedModel,CLIPSegForImageSegmentation:()=>r.CLIPSegForImageSegmentation,CLIPSegModel:()=>r.CLIPSegModel,CLIPSegPreTrainedModel:()=>r.CLIPSegPreTrainedModel,CLIPTextModelWithProjection:()=>r.CLIPTextModelWithProjection,CLIPTokenizer:()=>o.CLIPTokenizer,CLIPVisionModelWithProjection:()=>r.CLIPVisionModelWithProjection,CamembertForMaskedLM:()=>r.CamembertForMaskedLM,CamembertForQuestionAnswering:()=>r.CamembertForQuestionAnswering,CamembertForSequenceClassification:()=>r.CamembertForSequenceClassification,CamembertForTokenClassification:()=>r.CamembertForTokenClassification,CamembertModel:()=>r.CamembertModel,CamembertPreTrainedModel:()=>r.CamembertPreTrainedModel,CamembertTokenizer:()=>o.CamembertTokenizer,CausalLMOutput:()=>r.CausalLMOutput,CausalLMOutputWithPast:()=>r.CausalLMOutputWithPast,ChineseCLIPFeatureExtractor:()=>a.ChineseCLIPFeatureExtractor,ChineseCLIPModel:()=>r.ChineseCLIPModel,ChineseCLIPPreTrainedModel:()=>r.ChineseCLIPPreTrainedModel,ClapAudioModelWithProjection:()=>r.ClapAudioModelWithProjection,ClapFeatureExtractor:()=>a.ClapFeatureExtractor,ClapModel:()=>r.ClapModel,ClapPreTrainedModel:()=>r.ClapPreTrainedModel,ClapTextModelWithProjection:()=>r.ClapTextModelWithProjection,CodeGenForCausalLM:()=>r.CodeGenForCausalLM,CodeGenModel:()=>r.CodeGenModel,CodeGenPreTrainedModel:()=>r.CodeGenPreTrainedModel,CodeGenTokenizer:()=>o.CodeGenTokenizer,CodeLlamaTokenizer:()=>o.CodeLlamaTokenizer,CohereForCausalLM:()=>r.CohereForCausalLM,CohereModel:()=>r.CohereModel,CoherePreTrainedModel:()=>r.CoherePreTrainedModel,CohereTokenizer:()=>o.CohereTokenizer,ConvBertForMaskedLM:()=>r.ConvBertForMaskedLM,ConvBertForQuestionAnswering:()=>r.ConvBertForQuestionAnswering,ConvBertForSequenceClassification:()=>r.ConvBertForSequenceClassification,ConvBertForTokenClassification:()=>r.ConvBertForTokenClassification,ConvBertModel:()=>r.ConvBertModel,ConvBertPreTrainedModel:()=>r.ConvBertPreTrainedModel,ConvBertTokenizer:()=>o.ConvBertTokenizer,ConvNextFeatureExtractor:()=>a.ConvNextFeatureExtractor,ConvNextForImageClassification:()=>r.ConvNextForImageClassification,ConvNextImageProcessor:()=>a.ConvNextImageProcessor,ConvNextModel:()=>r.ConvNextModel,ConvNextPreTrainedModel:()=>r.ConvNextPreTrainedModel,ConvNextV2ForImageClassification:()=>r.ConvNextV2ForImageClassification,ConvNextV2Model:()=>r.ConvNextV2Model,ConvNextV2PreTrainedModel:()=>r.ConvNextV2PreTrainedModel,DPTFeatureExtractor:()=>a.DPTFeatureExtractor,DPTForDepthEstimation:()=>r.DPTForDepthEstimation,DPTImageProcessor:()=>a.DPTImageProcessor,DPTModel:()=>r.DPTModel,DPTPreTrainedModel:()=>r.DPTPreTrainedModel,DebertaForMaskedLM:()=>r.DebertaForMaskedLM,DebertaForQuestionAnswering:()=>r.DebertaForQuestionAnswering,DebertaForSequenceClassification:()=>r.DebertaForSequenceClassification,DebertaForTokenClassification:()=>r.DebertaForTokenClassification,DebertaModel:()=>r.DebertaModel,DebertaPreTrainedModel:()=>r.DebertaPreTrainedModel,DebertaTokenizer:()=>o.DebertaTokenizer,DebertaV2ForMaskedLM:()=>r.DebertaV2ForMaskedLM,DebertaV2ForQuestionAnswering:()=>r.DebertaV2ForQuestionAnswering,DebertaV2ForSequenceClassification:()=>r.DebertaV2ForSequenceClassification,DebertaV2ForTokenClassification:()=>r.DebertaV2ForTokenClassification,DebertaV2Model:()=>r.DebertaV2Model,DebertaV2PreTrainedModel:()=>r.DebertaV2PreTrainedModel,DebertaV2Tokenizer:()=>o.DebertaV2Tokenizer,DeiTFeatureExtractor:()=>a.DeiTFeatureExtractor,DeiTForImageClassification:()=>r.DeiTForImageClassification,DeiTModel:()=>r.DeiTModel,DeiTPreTrainedModel:()=>r.DeiTPreTrainedModel,DepthAnythingForDepthEstimation:()=>r.DepthAnythingForDepthEstimation,DepthAnythingPreTrainedModel:()=>r.DepthAnythingPreTrainedModel,DepthEstimationPipeline:()=>t.DepthEstimationPipeline,DetrFeatureExtractor:()=>a.DetrFeatureExtractor,DetrForObjectDetection:()=>r.DetrForObjectDetection,DetrForSegmentation:()=>r.DetrForSegmentation,DetrModel:()=>r.DetrModel,DetrObjectDetectionOutput:()=>r.DetrObjectDetectionOutput,DetrPreTrainedModel:()=>r.DetrPreTrainedModel,DetrSegmentationOutput:()=>r.DetrSegmentationOutput,Dinov2ForImageClassification:()=>r.Dinov2ForImageClassification,Dinov2Model:()=>r.Dinov2Model,Dinov2PreTrainedModel:()=>r.Dinov2PreTrainedModel,DistilBertForMaskedLM:()=>r.DistilBertForMaskedLM,DistilBertForQuestionAnswering:()=>r.DistilBertForQuestionAnswering,DistilBertForSequenceClassification:()=>r.DistilBertForSequenceClassification,DistilBertForTokenClassification:()=>r.DistilBertForTokenClassification,DistilBertModel:()=>r.DistilBertModel,DistilBertPreTrainedModel:()=>r.DistilBertPreTrainedModel,DistilBertTokenizer:()=>o.DistilBertTokenizer,DocumentQuestionAnsweringPipeline:()=>t.DocumentQuestionAnsweringPipeline,DonutFeatureExtractor:()=>a.DonutFeatureExtractor,DonutSwinModel:()=>r.DonutSwinModel,DonutSwinPreTrainedModel:()=>r.DonutSwinPreTrainedModel,EfficientNetForImageClassification:()=>r.EfficientNetForImageClassification,EfficientNetImageProcessor:()=>a.EfficientNetImageProcessor,EfficientNetModel:()=>r.EfficientNetModel,EfficientNetPreTrainedModel:()=>r.EfficientNetPreTrainedModel,ElectraForMaskedLM:()=>r.ElectraForMaskedLM,ElectraForQuestionAnswering:()=>r.ElectraForQuestionAnswering,ElectraForSequenceClassification:()=>r.ElectraForSequenceClassification,ElectraForTokenClassification:()=>r.ElectraForTokenClassification,ElectraModel:()=>r.ElectraModel,ElectraPreTrainedModel:()=>r.ElectraPreTrainedModel,ElectraTokenizer:()=>o.ElectraTokenizer,EosTokenCriteria:()=>y.EosTokenCriteria,EsmForMaskedLM:()=>r.EsmForMaskedLM,EsmForSequenceClassification:()=>r.EsmForSequenceClassification,EsmForTokenClassification:()=>r.EsmForTokenClassification,EsmModel:()=>r.EsmModel,EsmPreTrainedModel:()=>r.EsmPreTrainedModel,EsmTokenizer:()=>o.EsmTokenizer,FFT:()=>g.FFT,FalconForCausalLM:()=>r.FalconForCausalLM,FalconModel:()=>r.FalconModel,FalconPreTrainedModel:()=>r.FalconPreTrainedModel,FalconTokenizer:()=>o.FalconTokenizer,FastViTForImageClassification:()=>r.FastViTForImageClassification,FastViTModel:()=>r.FastViTModel,FastViTPreTrainedModel:()=>r.FastViTPreTrainedModel,FeatureExtractionPipeline:()=>t.FeatureExtractionPipeline,FeatureExtractor:()=>a.FeatureExtractor,FillMaskPipeline:()=>t.FillMaskPipeline,Florence2ForConditionalGeneration:()=>r.Florence2ForConditionalGeneration,Florence2PreTrainedModel:()=>r.Florence2PreTrainedModel,Florence2Processor:()=>a.Florence2Processor,GLPNFeatureExtractor:()=>a.GLPNFeatureExtractor,GLPNForDepthEstimation:()=>r.GLPNForDepthEstimation,GLPNModel:()=>r.GLPNModel,GLPNPreTrainedModel:()=>r.GLPNPreTrainedModel,GPT2LMHeadModel:()=>r.GPT2LMHeadModel,GPT2Model:()=>r.GPT2Model,GPT2PreTrainedModel:()=>r.GPT2PreTrainedModel,GPT2Tokenizer:()=>o.GPT2Tokenizer,GPTBigCodeForCausalLM:()=>r.GPTBigCodeForCausalLM,GPTBigCodeModel:()=>r.GPTBigCodeModel,GPTBigCodePreTrainedModel:()=>r.GPTBigCodePreTrainedModel,GPTJForCausalLM:()=>r.GPTJForCausalLM,GPTJModel:()=>r.GPTJModel,GPTJPreTrainedModel:()=>r.GPTJPreTrainedModel,GPTNeoForCausalLM:()=>r.GPTNeoForCausalLM,GPTNeoModel:()=>r.GPTNeoModel,GPTNeoPreTrainedModel:()=>r.GPTNeoPreTrainedModel,GPTNeoXForCausalLM:()=>r.GPTNeoXForCausalLM,GPTNeoXModel:()=>r.GPTNeoXModel,GPTNeoXPreTrainedModel:()=>r.GPTNeoXPreTrainedModel,GPTNeoXTokenizer:()=>o.GPTNeoXTokenizer,Gemma2ForCausalLM:()=>r.Gemma2ForCausalLM,Gemma2Model:()=>r.Gemma2Model,Gemma2PreTrainedModel:()=>r.Gemma2PreTrainedModel,GemmaForCausalLM:()=>r.GemmaForCausalLM,GemmaModel:()=>r.GemmaModel,GemmaPreTrainedModel:()=>r.GemmaPreTrainedModel,GemmaTokenizer:()=>o.GemmaTokenizer,Grok1Tokenizer:()=>o.Grok1Tokenizer,HerbertTokenizer:()=>o.HerbertTokenizer,HubertForCTC:()=>r.HubertForCTC,HubertForSequenceClassification:()=>r.HubertForSequenceClassification,HubertModel:()=>r.HubertModel,HubertPreTrainedModel:()=>r.HubertPreTrainedModel,ImageClassificationPipeline:()=>t.ImageClassificationPipeline,ImageFeatureExtractionPipeline:()=>t.ImageFeatureExtractionPipeline,ImageFeatureExtractor:()=>a.ImageFeatureExtractor,ImageMattingOutput:()=>r.ImageMattingOutput,ImageSegmentationPipeline:()=>t.ImageSegmentationPipeline,ImageToImagePipeline:()=>t.ImageToImagePipeline,ImageToTextPipeline:()=>t.ImageToTextPipeline,InterruptableStoppingCriteria:()=>y.InterruptableStoppingCriteria,LlamaForCausalLM:()=>r.LlamaForCausalLM,LlamaModel:()=>r.LlamaModel,LlamaPreTrainedModel:()=>r.LlamaPreTrainedModel,LlamaTokenizer:()=>o.LlamaTokenizer,LlavaForConditionalGeneration:()=>r.LlavaForConditionalGeneration,LlavaPreTrainedModel:()=>r.LlavaPreTrainedModel,LongT5ForConditionalGeneration:()=>r.LongT5ForConditionalGeneration,LongT5Model:()=>r.LongT5Model,LongT5PreTrainedModel:()=>r.LongT5PreTrainedModel,M2M100ForConditionalGeneration:()=>r.M2M100ForConditionalGeneration,M2M100Model:()=>r.M2M100Model,M2M100PreTrainedModel:()=>r.M2M100PreTrainedModel,M2M100Tokenizer:()=>o.M2M100Tokenizer,MBart50Tokenizer:()=>o.MBart50Tokenizer,MBartForCausalLM:()=>r.MBartForCausalLM,MBartForConditionalGeneration:()=>r.MBartForConditionalGeneration,MBartForSequenceClassification:()=>r.MBartForSequenceClassification,MBartModel:()=>r.MBartModel,MBartPreTrainedModel:()=>r.MBartPreTrainedModel,MBartTokenizer:()=>o.MBartTokenizer,MPNetForMaskedLM:()=>r.MPNetForMaskedLM,MPNetForQuestionAnswering:()=>r.MPNetForQuestionAnswering,MPNetForSequenceClassification:()=>r.MPNetForSequenceClassification,MPNetForTokenClassification:()=>r.MPNetForTokenClassification,MPNetModel:()=>r.MPNetModel,MPNetPreTrainedModel:()=>r.MPNetPreTrainedModel,MPNetTokenizer:()=>o.MPNetTokenizer,MT5ForConditionalGeneration:()=>r.MT5ForConditionalGeneration,MT5Model:()=>r.MT5Model,MT5PreTrainedModel:()=>r.MT5PreTrainedModel,MarianMTModel:()=>r.MarianMTModel,MarianModel:()=>r.MarianModel,MarianPreTrainedModel:()=>r.MarianPreTrainedModel,MarianTokenizer:()=>o.MarianTokenizer,MaskedLMOutput:()=>r.MaskedLMOutput,MaxLengthCriteria:()=>y.MaxLengthCriteria,MistralForCausalLM:()=>r.MistralForCausalLM,MistralModel:()=>r.MistralModel,MistralPreTrainedModel:()=>r.MistralPreTrainedModel,MobileBertForMaskedLM:()=>r.MobileBertForMaskedLM,MobileBertForQuestionAnswering:()=>r.MobileBertForQuestionAnswering,MobileBertForSequenceClassification:()=>r.MobileBertForSequenceClassification,MobileBertModel:()=>r.MobileBertModel,MobileBertPreTrainedModel:()=>r.MobileBertPreTrainedModel,MobileBertTokenizer:()=>o.MobileBertTokenizer,MobileNetV1FeatureExtractor:()=>a.MobileNetV1FeatureExtractor,MobileNetV1ForImageClassification:()=>r.MobileNetV1ForImageClassification,MobileNetV1Model:()=>r.MobileNetV1Model,MobileNetV1PreTrainedModel:()=>r.MobileNetV1PreTrainedModel,MobileNetV2FeatureExtractor:()=>a.MobileNetV2FeatureExtractor,MobileNetV2ForImageClassification:()=>r.MobileNetV2ForImageClassification,MobileNetV2Model:()=>r.MobileNetV2Model,MobileNetV2PreTrainedModel:()=>r.MobileNetV2PreTrainedModel,MobileNetV3FeatureExtractor:()=>a.MobileNetV3FeatureExtractor,MobileNetV3ForImageClassification:()=>r.MobileNetV3ForImageClassification,MobileNetV3Model:()=>r.MobileNetV3Model,MobileNetV3PreTrainedModel:()=>r.MobileNetV3PreTrainedModel,MobileNetV4FeatureExtractor:()=>a.MobileNetV4FeatureExtractor,MobileNetV4ForImageClassification:()=>r.MobileNetV4ForImageClassification,MobileNetV4Model:()=>r.MobileNetV4Model,MobileNetV4PreTrainedModel:()=>r.MobileNetV4PreTrainedModel,MobileViTFeatureExtractor:()=>a.MobileViTFeatureExtractor,MobileViTForImageClassification:()=>r.MobileViTForImageClassification,MobileViTImageProcessor:()=>a.MobileViTImageProcessor,MobileViTModel:()=>r.MobileViTModel,MobileViTPreTrainedModel:()=>r.MobileViTPreTrainedModel,MobileViTV2ForImageClassification:()=>r.MobileViTV2ForImageClassification,MobileViTV2Model:()=>r.MobileViTV2Model,MobileViTV2PreTrainedModel:()=>r.MobileViTV2PreTrainedModel,ModelOutput:()=>r.ModelOutput,Moondream1ForConditionalGeneration:()=>r.Moondream1ForConditionalGeneration,MptForCausalLM:()=>r.MptForCausalLM,MptModel:()=>r.MptModel,MptPreTrainedModel:()=>r.MptPreTrainedModel,MusicgenForCausalLM:()=>r.MusicgenForCausalLM,MusicgenForConditionalGeneration:()=>r.MusicgenForConditionalGeneration,MusicgenModel:()=>r.MusicgenModel,MusicgenPreTrainedModel:()=>r.MusicgenPreTrainedModel,NllbTokenizer:()=>o.NllbTokenizer,NomicBertModel:()=>r.NomicBertModel,NomicBertPreTrainedModel:()=>r.NomicBertPreTrainedModel,NougatImageProcessor:()=>a.NougatImageProcessor,NougatTokenizer:()=>o.NougatTokenizer,OPTForCausalLM:()=>r.OPTForCausalLM,OPTModel:()=>r.OPTModel,OPTPreTrainedModel:()=>r.OPTPreTrainedModel,ObjectDetectionPipeline:()=>t.ObjectDetectionPipeline,OpenELMForCausalLM:()=>r.OpenELMForCausalLM,OpenELMModel:()=>r.OpenELMModel,OpenELMPreTrainedModel:()=>r.OpenELMPreTrainedModel,OwlViTFeatureExtractor:()=>a.OwlViTFeatureExtractor,OwlViTForObjectDetection:()=>r.OwlViTForObjectDetection,OwlViTModel:()=>r.OwlViTModel,OwlViTPreTrainedModel:()=>r.OwlViTPreTrainedModel,OwlViTProcessor:()=>a.OwlViTProcessor,Owlv2ForObjectDetection:()=>r.Owlv2ForObjectDetection,Owlv2ImageProcessor:()=>a.Owlv2ImageProcessor,Owlv2Model:()=>r.Owlv2Model,Owlv2PreTrainedModel:()=>r.Owlv2PreTrainedModel,Phi3ForCausalLM:()=>r.Phi3ForCausalLM,Phi3Model:()=>r.Phi3Model,Phi3PreTrainedModel:()=>r.Phi3PreTrainedModel,PhiForCausalLM:()=>r.PhiForCausalLM,PhiModel:()=>r.PhiModel,PhiPreTrainedModel:()=>r.PhiPreTrainedModel,Pipeline:()=>t.Pipeline,PreTrainedModel:()=>r.PreTrainedModel,PreTrainedTokenizer:()=>o.PreTrainedTokenizer,PretrainedConfig:()=>l.PretrainedConfig,PretrainedMixin:()=>r.PretrainedMixin,Processor:()=>a.Processor,PyAnnoteFeatureExtractor:()=>a.PyAnnoteFeatureExtractor,PyAnnoteForAudioFrameClassification:()=>r.PyAnnoteForAudioFrameClassification,PyAnnoteModel:()=>r.PyAnnoteModel,PyAnnotePreTrainedModel:()=>r.PyAnnotePreTrainedModel,PyAnnoteProcessor:()=>a.PyAnnoteProcessor,QuestionAnsweringModelOutput:()=>r.QuestionAnsweringModelOutput,QuestionAnsweringPipeline:()=>t.QuestionAnsweringPipeline,Qwen2ForCausalLM:()=>r.Qwen2ForCausalLM,Qwen2Model:()=>r.Qwen2Model,Qwen2PreTrainedModel:()=>r.Qwen2PreTrainedModel,Qwen2Tokenizer:()=>o.Qwen2Tokenizer,RTDetrForObjectDetection:()=>r.RTDetrForObjectDetection,RTDetrImageProcessor:()=>a.RTDetrImageProcessor,RTDetrModel:()=>r.RTDetrModel,RTDetrObjectDetectionOutput:()=>r.RTDetrObjectDetectionOutput,RTDetrPreTrainedModel:()=>r.RTDetrPreTrainedModel,RawImage:()=>_.RawImage,ResNetForImageClassification:()=>r.ResNetForImageClassification,ResNetModel:()=>r.ResNetModel,ResNetPreTrainedModel:()=>r.ResNetPreTrainedModel,RoFormerForMaskedLM:()=>r.RoFormerForMaskedLM,RoFormerForQuestionAnswering:()=>r.RoFormerForQuestionAnswering,RoFormerForSequenceClassification:()=>r.RoFormerForSequenceClassification,RoFormerForTokenClassification:()=>r.RoFormerForTokenClassification,RoFormerModel:()=>r.RoFormerModel,RoFormerPreTrainedModel:()=>r.RoFormerPreTrainedModel,RoFormerTokenizer:()=>o.RoFormerTokenizer,RobertaForMaskedLM:()=>r.RobertaForMaskedLM,RobertaForQuestionAnswering:()=>r.RobertaForQuestionAnswering,RobertaForSequenceClassification:()=>r.RobertaForSequenceClassification,RobertaForTokenClassification:()=>r.RobertaForTokenClassification,RobertaModel:()=>r.RobertaModel,RobertaPreTrainedModel:()=>r.RobertaPreTrainedModel,RobertaTokenizer:()=>o.RobertaTokenizer,SamImageProcessor:()=>a.SamImageProcessor,SamImageSegmentationOutput:()=>r.SamImageSegmentationOutput,SamModel:()=>r.SamModel,SamPreTrainedModel:()=>r.SamPreTrainedModel,SamProcessor:()=>a.SamProcessor,SeamlessM4TFeatureExtractor:()=>a.SeamlessM4TFeatureExtractor,SegformerFeatureExtractor:()=>a.SegformerFeatureExtractor,SegformerForImageClassification:()=>r.SegformerForImageClassification,SegformerForSemanticSegmentation:()=>r.SegformerForSemanticSegmentation,SegformerModel:()=>r.SegformerModel,SegformerPreTrainedModel:()=>r.SegformerPreTrainedModel,Seq2SeqLMOutput:()=>r.Seq2SeqLMOutput,SequenceClassifierOutput:()=>r.SequenceClassifierOutput,SiglipImageProcessor:()=>a.SiglipImageProcessor,SiglipModel:()=>r.SiglipModel,SiglipPreTrainedModel:()=>r.SiglipPreTrainedModel,SiglipTextModel:()=>r.SiglipTextModel,SiglipTokenizer:()=>o.SiglipTokenizer,SiglipVisionModel:()=>r.SiglipVisionModel,SpeechT5FeatureExtractor:()=>a.SpeechT5FeatureExtractor,SpeechT5ForSpeechToText:()=>r.SpeechT5ForSpeechToText,SpeechT5ForTextToSpeech:()=>r.SpeechT5ForTextToSpeech,SpeechT5HifiGan:()=>r.SpeechT5HifiGan,SpeechT5Model:()=>r.SpeechT5Model,SpeechT5PreTrainedModel:()=>r.SpeechT5PreTrainedModel,SpeechT5Processor:()=>a.SpeechT5Processor,SpeechT5Tokenizer:()=>o.SpeechT5Tokenizer,SqueezeBertForMaskedLM:()=>r.SqueezeBertForMaskedLM,SqueezeBertForQuestionAnswering:()=>r.SqueezeBertForQuestionAnswering,SqueezeBertForSequenceClassification:()=>r.SqueezeBertForSequenceClassification,SqueezeBertModel:()=>r.SqueezeBertModel,SqueezeBertPreTrainedModel:()=>r.SqueezeBertPreTrainedModel,SqueezeBertTokenizer:()=>o.SqueezeBertTokenizer,StableLmForCausalLM:()=>r.StableLmForCausalLM,StableLmModel:()=>r.StableLmModel,StableLmPreTrainedModel:()=>r.StableLmPreTrainedModel,Starcoder2ForCausalLM:()=>r.Starcoder2ForCausalLM,Starcoder2Model:()=>r.Starcoder2Model,Starcoder2PreTrainedModel:()=>r.Starcoder2PreTrainedModel,StoppingCriteria:()=>y.StoppingCriteria,StoppingCriteriaList:()=>y.StoppingCriteriaList,SummarizationPipeline:()=>t.SummarizationPipeline,Swin2SRForImageSuperResolution:()=>r.Swin2SRForImageSuperResolution,Swin2SRImageProcessor:()=>a.Swin2SRImageProcessor,Swin2SRModel:()=>r.Swin2SRModel,Swin2SRPreTrainedModel:()=>r.Swin2SRPreTrainedModel,SwinForImageClassification:()=>r.SwinForImageClassification,SwinModel:()=>r.SwinModel,SwinPreTrainedModel:()=>r.SwinPreTrainedModel,T5ForConditionalGeneration:()=>r.T5ForConditionalGeneration,T5Model:()=>r.T5Model,T5PreTrainedModel:()=>r.T5PreTrainedModel,T5Tokenizer:()=>o.T5Tokenizer,TableTransformerForObjectDetection:()=>r.TableTransformerForObjectDetection,TableTransformerModel:()=>r.TableTransformerModel,TableTransformerObjectDetectionOutput:()=>r.TableTransformerObjectDetectionOutput,TableTransformerPreTrainedModel:()=>r.TableTransformerPreTrainedModel,Tensor:()=>h.Tensor,Text2TextGenerationPipeline:()=>t.Text2TextGenerationPipeline,TextClassificationPipeline:()=>t.TextClassificationPipeline,TextGenerationPipeline:()=>t.TextGenerationPipeline,TextStreamer:()=>M.TextStreamer,TextToAudioPipeline:()=>t.TextToAudioPipeline,TokenClassificationPipeline:()=>t.TokenClassificationPipeline,TokenClassifierOutput:()=>r.TokenClassifierOutput,TokenizerModel:()=>o.TokenizerModel,TrOCRForCausalLM:()=>r.TrOCRForCausalLM,TrOCRPreTrainedModel:()=>r.TrOCRPreTrainedModel,TranslationPipeline:()=>t.TranslationPipeline,UniSpeechForCTC:()=>r.UniSpeechForCTC,UniSpeechForSequenceClassification:()=>r.UniSpeechForSequenceClassification,UniSpeechModel:()=>r.UniSpeechModel,UniSpeechPreTrainedModel:()=>r.UniSpeechPreTrainedModel,UniSpeechSatForAudioFrameClassification:()=>r.UniSpeechSatForAudioFrameClassification,UniSpeechSatForCTC:()=>r.UniSpeechSatForCTC,UniSpeechSatForSequenceClassification:()=>r.UniSpeechSatForSequenceClassification,UniSpeechSatModel:()=>r.UniSpeechSatModel,UniSpeechSatPreTrainedModel:()=>r.UniSpeechSatPreTrainedModel,ViTFeatureExtractor:()=>a.ViTFeatureExtractor,ViTForImageClassification:()=>r.ViTForImageClassification,ViTImageProcessor:()=>a.ViTImageProcessor,ViTModel:()=>r.ViTModel,ViTPreTrainedModel:()=>r.ViTPreTrainedModel,VisionEncoderDecoderModel:()=>r.VisionEncoderDecoderModel,VitMatteForImageMatting:()=>r.VitMatteForImageMatting,VitMatteImageProcessor:()=>a.VitMatteImageProcessor,VitMattePreTrainedModel:()=>r.VitMattePreTrainedModel,VitsModel:()=>r.VitsModel,VitsModelOutput:()=>r.VitsModelOutput,VitsPreTrainedModel:()=>r.VitsPreTrainedModel,VitsTokenizer:()=>o.VitsTokenizer,Wav2Vec2BertForCTC:()=>r.Wav2Vec2BertForCTC,Wav2Vec2BertForSequenceClassification:()=>r.Wav2Vec2BertForSequenceClassification,Wav2Vec2BertModel:()=>r.Wav2Vec2BertModel,Wav2Vec2BertPreTrainedModel:()=>r.Wav2Vec2BertPreTrainedModel,Wav2Vec2CTCTokenizer:()=>o.Wav2Vec2CTCTokenizer,Wav2Vec2FeatureExtractor:()=>a.Wav2Vec2FeatureExtractor,Wav2Vec2ForAudioFrameClassification:()=>r.Wav2Vec2ForAudioFrameClassification,Wav2Vec2ForCTC:()=>r.Wav2Vec2ForCTC,Wav2Vec2ForSequenceClassification:()=>r.Wav2Vec2ForSequenceClassification,Wav2Vec2Model:()=>r.Wav2Vec2Model,Wav2Vec2PreTrainedModel:()=>r.Wav2Vec2PreTrainedModel,Wav2Vec2ProcessorWithLM:()=>a.Wav2Vec2ProcessorWithLM,WavLMForAudioFrameClassification:()=>r.WavLMForAudioFrameClassification,WavLMForCTC:()=>r.WavLMForCTC,WavLMForSequenceClassification:()=>r.WavLMForSequenceClassification,WavLMForXVector:()=>r.WavLMForXVector,WavLMModel:()=>r.WavLMModel,WavLMPreTrainedModel:()=>r.WavLMPreTrainedModel,WeSpeakerFeatureExtractor:()=>a.WeSpeakerFeatureExtractor,WeSpeakerResNetModel:()=>r.WeSpeakerResNetModel,WeSpeakerResNetPreTrainedModel:()=>r.WeSpeakerResNetPreTrainedModel,WhisperFeatureExtractor:()=>a.WhisperFeatureExtractor,WhisperForConditionalGeneration:()=>r.WhisperForConditionalGeneration,WhisperModel:()=>r.WhisperModel,WhisperPreTrainedModel:()=>r.WhisperPreTrainedModel,WhisperProcessor:()=>a.WhisperProcessor,WhisperTextStreamer:()=>M.WhisperTextStreamer,WhisperTokenizer:()=>o.WhisperTokenizer,XLMForQuestionAnswering:()=>r.XLMForQuestionAnswering,XLMForSequenceClassification:()=>r.XLMForSequenceClassification,XLMForTokenClassification:()=>r.XLMForTokenClassification,XLMModel:()=>r.XLMModel,XLMPreTrainedModel:()=>r.XLMPreTrainedModel,XLMRobertaForMaskedLM:()=>r.XLMRobertaForMaskedLM,XLMRobertaForQuestionAnswering:()=>r.XLMRobertaForQuestionAnswering,XLMRobertaForSequenceClassification:()=>r.XLMRobertaForSequenceClassification,XLMRobertaForTokenClassification:()=>r.XLMRobertaForTokenClassification,XLMRobertaModel:()=>r.XLMRobertaModel,XLMRobertaPreTrainedModel:()=>r.XLMRobertaPreTrainedModel,XLMRobertaTokenizer:()=>o.XLMRobertaTokenizer,XLMTokenizer:()=>o.XLMTokenizer,XLMWithLMHeadModel:()=>r.XLMWithLMHeadModel,XVectorOutput:()=>r.XVectorOutput,YolosFeatureExtractor:()=>a.YolosFeatureExtractor,YolosForObjectDetection:()=>r.YolosForObjectDetection,YolosModel:()=>r.YolosModel,YolosObjectDetectionOutput:()=>r.YolosObjectDetectionOutput,YolosPreTrainedModel:()=>r.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:()=>p.hamming,hanning:()=>p.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:()=>p.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:()=>p.read_audio,rfft:()=>h.rfft,round:()=>g.round,softmax:()=>g.softmax,spectrogram:()=>p.spectrogram,stack:()=>h.stack,std_mean:()=>h.std_mean,topk:()=>h.topk,window_function:()=>p.window_function,zeros:()=>h.zeros,zeros_like:()=>h.zeros_like});var e=en("./src/env.js"),t=en("./src/pipelines.js"),r=en("./src/models.js"),o=en("./src/tokenizers.js"),a=en("./src/processors.js"),l=en("./src/configs.js"),p=en("./src/utils/audio.js"),_=en("./src/utils/image.js"),h=en("./src/utils/tensor.js"),g=en("./src/utils/maths.js"),M=en("./src/generation/streamers.js"),y=en("./src/generation/stopping_criteria.js")})();P.ASTFeatureExtractor;P.ASTForAudioClassification;P.ASTModel;P.ASTPreTrainedModel;P.AlbertForMaskedLM;P.AlbertForQuestionAnswering;P.AlbertForSequenceClassification;P.AlbertModel;P.AlbertPreTrainedModel;P.AlbertTokenizer;P.AudioClassificationPipeline;P.AutoConfig;var cE=P.AutoModel;P.AutoModelForAudioClassification;P.AutoModelForAudioFrameClassification;P.AutoModelForCTC;P.AutoModelForCausalLM;P.AutoModelForDepthEstimation;P.AutoModelForDocumentQuestionAnswering;P.AutoModelForImageClassification;P.AutoModelForImageFeatureExtraction;P.AutoModelForImageMatting;P.AutoModelForImageSegmentation;P.AutoModelForImageToImage;P.AutoModelForMaskGeneration;P.AutoModelForMaskedLM;P.AutoModelForObjectDetection;P.AutoModelForQuestionAnswering;P.AutoModelForSemanticSegmentation;P.AutoModelForSeq2SeqLM;P.AutoModelForSequenceClassification;P.AutoModelForSpeechSeq2Seq;P.AutoModelForTextToSpectrogram;P.AutoModelForTextToWaveform;P.AutoModelForTokenClassification;P.AutoModelForVision2Seq;P.AutoModelForXVector;P.AutoModelForZeroShotObjectDetection;var dE=P.AutoProcessor;P.AutoTokenizer;P.AutomaticSpeechRecognitionPipeline;P.BartForConditionalGeneration;P.BartForSequenceClassification;P.BartModel;P.BartPretrainedModel;P.BartTokenizer;P.BaseModelOutput;P.BaseStreamer;P.BeitFeatureExtractor;P.BeitForImageClassification;P.BeitModel;P.BeitPreTrainedModel;P.BertForMaskedLM;P.BertForQuestionAnswering;P.BertForSequenceClassification;P.BertForTokenClassification;P.BertModel;P.BertPreTrainedModel;P.BertTokenizer;P.BitImageProcessor;P.BlenderbotForConditionalGeneration;P.BlenderbotModel;P.BlenderbotPreTrainedModel;P.BlenderbotSmallForConditionalGeneration;P.BlenderbotSmallModel;P.BlenderbotSmallPreTrainedModel;P.BlenderbotSmallTokenizer;P.BlenderbotTokenizer;P.BloomForCausalLM;P.BloomModel;P.BloomPreTrainedModel;P.BloomTokenizer;P.CLIPFeatureExtractor;P.CLIPImageProcessor;P.CLIPModel;P.CLIPPreTrainedModel;P.CLIPSegForImageSegmentation;P.CLIPSegModel;P.CLIPSegPreTrainedModel;P.CLIPTextModelWithProjection;P.CLIPTokenizer;P.CLIPVisionModelWithProjection;P.CamembertForMaskedLM;P.CamembertForQuestionAnswering;P.CamembertForSequenceClassification;P.CamembertForTokenClassification;P.CamembertModel;P.CamembertPreTrainedModel;P.CamembertTokenizer;P.CausalLMOutput;P.CausalLMOutputWithPast;P.ChineseCLIPFeatureExtractor;P.ChineseCLIPModel;P.ChineseCLIPPreTrainedModel;P.ClapAudioModelWithProjection;P.ClapFeatureExtractor;P.ClapModel;P.ClapPreTrainedModel;P.ClapTextModelWithProjection;P.CodeGenForCausalLM;P.CodeGenModel;P.CodeGenPreTrainedModel;P.CodeGenTokenizer;P.CodeLlamaTokenizer;P.CohereForCausalLM;P.CohereModel;P.CoherePreTrainedModel;P.CohereTokenizer;P.ConvBertForMaskedLM;P.ConvBertForQuestionAnswering;P.ConvBertForSequenceClassification;P.ConvBertForTokenClassification;P.ConvBertModel;P.ConvBertPreTrainedModel;P.ConvBertTokenizer;P.ConvNextFeatureExtractor;P.ConvNextForImageClassification;P.ConvNextImageProcessor;P.ConvNextModel;P.ConvNextPreTrainedModel;P.ConvNextV2ForImageClassification;P.ConvNextV2Model;P.ConvNextV2PreTrainedModel;P.DPTFeatureExtractor;P.DPTForDepthEstimation;P.DPTImageProcessor;P.DPTModel;P.DPTPreTrainedModel;P.DebertaForMaskedLM;P.DebertaForQuestionAnswering;P.DebertaForSequenceClassification;P.DebertaForTokenClassification;P.DebertaModel;P.DebertaPreTrainedModel;P.DebertaTokenizer;P.DebertaV2ForMaskedLM;P.DebertaV2ForQuestionAnswering;P.DebertaV2ForSequenceClassification;P.DebertaV2ForTokenClassification;P.DebertaV2Model;P.DebertaV2PreTrainedModel;P.DebertaV2Tokenizer;P.DeiTFeatureExtractor;P.DeiTForImageClassification;P.DeiTModel;P.DeiTPreTrainedModel;P.DepthAnythingForDepthEstimation;P.DepthAnythingPreTrainedModel;P.DepthEstimationPipeline;P.DetrFeatureExtractor;P.DetrForObjectDetection;P.DetrForSegmentation;P.DetrModel;P.DetrObjectDetectionOutput;P.DetrPreTrainedModel;P.DetrSegmentationOutput;P.Dinov2ForImageClassification;P.Dinov2Model;P.Dinov2PreTrainedModel;P.DistilBertForMaskedLM;P.DistilBertForQuestionAnswering;P.DistilBertForSequenceClassification;P.DistilBertForTokenClassification;P.DistilBertModel;P.DistilBertPreTrainedModel;P.DistilBertTokenizer;P.DocumentQuestionAnsweringPipeline;P.DonutFeatureExtractor;P.DonutSwinModel;P.DonutSwinPreTrainedModel;P.EfficientNetForImageClassification;P.EfficientNetImageProcessor;P.EfficientNetModel;P.EfficientNetPreTrainedModel;P.ElectraForMaskedLM;P.ElectraForQuestionAnswering;P.ElectraForSequenceClassification;P.ElectraForTokenClassification;P.ElectraModel;P.ElectraPreTrainedModel;P.ElectraTokenizer;P.EosTokenCriteria;P.EsmForMaskedLM;P.EsmForSequenceClassification;P.EsmForTokenClassification;P.EsmModel;P.EsmPreTrainedModel;P.EsmTokenizer;P.FFT;P.FalconForCausalLM;P.FalconModel;P.FalconPreTrainedModel;P.FalconTokenizer;P.FastViTForImageClassification;P.FastViTModel;P.FastViTPreTrainedModel;P.FeatureExtractionPipeline;P.FeatureExtractor;P.FillMaskPipeline;P.Florence2ForConditionalGeneration;P.Florence2PreTrainedModel;P.Florence2Processor;P.GLPNFeatureExtractor;P.GLPNForDepthEstimation;P.GLPNModel;P.GLPNPreTrainedModel;P.GPT2LMHeadModel;P.GPT2Model;P.GPT2PreTrainedModel;P.GPT2Tokenizer;P.GPTBigCodeForCausalLM;P.GPTBigCodeModel;P.GPTBigCodePreTrainedModel;P.GPTJForCausalLM;P.GPTJModel;P.GPTJPreTrainedModel;P.GPTNeoForCausalLM;P.GPTNeoModel;P.GPTNeoPreTrainedModel;P.GPTNeoXForCausalLM;P.GPTNeoXModel;P.GPTNeoXPreTrainedModel;P.GPTNeoXTokenizer;P.Gemma2ForCausalLM;P.Gemma2Model;P.Gemma2PreTrainedModel;P.GemmaForCausalLM;P.GemmaModel;P.GemmaPreTrainedModel;P.GemmaTokenizer;P.Grok1Tokenizer;P.HerbertTokenizer;P.HubertForCTC;P.HubertForSequenceClassification;P.HubertModel;P.HubertPreTrainedModel;P.ImageClassificationPipeline;P.ImageFeatureExtractionPipeline;P.ImageFeatureExtractor;P.ImageMattingOutput;P.ImageSegmentationPipeline;P.ImageToImagePipeline;P.ImageToTextPipeline;P.InterruptableStoppingCriteria;P.LlamaForCausalLM;P.LlamaModel;P.LlamaPreTrainedModel;P.LlamaTokenizer;P.LlavaForConditionalGeneration;P.LlavaPreTrainedModel;P.LongT5ForConditionalGeneration;P.LongT5Model;P.LongT5PreTrainedModel;P.M2M100ForConditionalGeneration;P.M2M100Model;P.M2M100PreTrainedModel;P.M2M100Tokenizer;P.MBart50Tokenizer;P.MBartForCausalLM;P.MBartForConditionalGeneration;P.MBartForSequenceClassification;P.MBartModel;P.MBartPreTrainedModel;P.MBartTokenizer;P.MPNetForMaskedLM;P.MPNetForQuestionAnswering;P.MPNetForSequenceClassification;P.MPNetForTokenClassification;P.MPNetModel;P.MPNetPreTrainedModel;P.MPNetTokenizer;P.MT5ForConditionalGeneration;P.MT5Model;P.MT5PreTrainedModel;P.MarianMTModel;P.MarianModel;P.MarianPreTrainedModel;P.MarianTokenizer;P.MaskedLMOutput;P.MaxLengthCriteria;P.MistralForCausalLM;P.MistralModel;P.MistralPreTrainedModel;P.MobileBertForMaskedLM;P.MobileBertForQuestionAnswering;P.MobileBertForSequenceClassification;P.MobileBertModel;P.MobileBertPreTrainedModel;P.MobileBertTokenizer;P.MobileNetV1FeatureExtractor;P.MobileNetV1ForImageClassification;P.MobileNetV1Model;P.MobileNetV1PreTrainedModel;P.MobileNetV2FeatureExtractor;P.MobileNetV2ForImageClassification;P.MobileNetV2Model;P.MobileNetV2PreTrainedModel;P.MobileNetV3FeatureExtractor;P.MobileNetV3ForImageClassification;P.MobileNetV3Model;P.MobileNetV3PreTrainedModel;P.MobileNetV4FeatureExtractor;P.MobileNetV4ForImageClassification;P.MobileNetV4Model;P.MobileNetV4PreTrainedModel;P.MobileViTFeatureExtractor;P.MobileViTForImageClassification;P.MobileViTImageProcessor;P.MobileViTModel;P.MobileViTPreTrainedModel;P.MobileViTV2ForImageClassification;P.MobileViTV2Model;P.MobileViTV2PreTrainedModel;P.ModelOutput;P.Moondream1ForConditionalGeneration;P.MptForCausalLM;P.MptModel;P.MptPreTrainedModel;P.MusicgenForCausalLM;P.MusicgenForConditionalGeneration;P.MusicgenModel;P.MusicgenPreTrainedModel;P.NllbTokenizer;P.NomicBertModel;P.NomicBertPreTrainedModel;P.NougatImageProcessor;P.NougatTokenizer;P.OPTForCausalLM;P.OPTModel;P.OPTPreTrainedModel;P.ObjectDetectionPipeline;P.OpenELMForCausalLM;P.OpenELMModel;P.OpenELMPreTrainedModel;P.OwlViTFeatureExtractor;P.OwlViTForObjectDetection;P.OwlViTModel;P.OwlViTPreTrainedModel;P.OwlViTProcessor;P.Owlv2ForObjectDetection;P.Owlv2ImageProcessor;P.Owlv2Model;P.Owlv2PreTrainedModel;P.Phi3ForCausalLM;P.Phi3Model;P.Phi3PreTrainedModel;P.PhiForCausalLM;P.PhiModel;P.PhiPreTrainedModel;P.Pipeline;P.PreTrainedModel;P.PreTrainedTokenizer;P.PretrainedConfig;P.PretrainedMixin;P.Processor;P.PyAnnoteFeatureExtractor;P.PyAnnoteForAudioFrameClassification;P.PyAnnoteModel;P.PyAnnotePreTrainedModel;P.PyAnnoteProcessor;P.QuestionAnsweringModelOutput;P.QuestionAnsweringPipeline;P.Qwen2ForCausalLM;P.Qwen2Model;P.Qwen2PreTrainedModel;P.Qwen2Tokenizer;P.RTDetrForObjectDetection;P.RTDetrImageProcessor;P.RTDetrModel;P.RTDetrObjectDetectionOutput;P.RTDetrPreTrainedModel;var T1=P.RawImage;P.ResNetForImageClassification;P.ResNetModel;P.ResNetPreTrainedModel;P.RoFormerForMaskedLM;P.RoFormerForQuestionAnswering;P.RoFormerForSequenceClassification;P.RoFormerForTokenClassification;P.RoFormerModel;P.RoFormerPreTrainedModel;P.RoFormerTokenizer;P.RobertaForMaskedLM;P.RobertaForQuestionAnswering;P.RobertaForSequenceClassification;P.RobertaForTokenClassification;P.RobertaModel;P.RobertaPreTrainedModel;P.RobertaTokenizer;P.SamImageProcessor;P.SamImageSegmentationOutput;P.SamModel;P.SamPreTrainedModel;P.SamProcessor;P.SeamlessM4TFeatureExtractor;P.SegformerFeatureExtractor;P.SegformerForImageClassification;P.SegformerForSemanticSegmentation;P.SegformerModel;P.SegformerPreTrainedModel;P.Seq2SeqLMOutput;P.SequenceClassifierOutput;P.SiglipImageProcessor;P.SiglipModel;P.SiglipPreTrainedModel;P.SiglipTextModel;P.SiglipTokenizer;P.SiglipVisionModel;P.SpeechT5FeatureExtractor;P.SpeechT5ForSpeechToText;P.SpeechT5ForTextToSpeech;P.SpeechT5HifiGan;P.SpeechT5Model;P.SpeechT5PreTrainedModel;P.SpeechT5Processor;P.SpeechT5Tokenizer;P.SqueezeBertForMaskedLM;P.SqueezeBertForQuestionAnswering;P.SqueezeBertForSequenceClassification;P.SqueezeBertModel;P.SqueezeBertPreTrainedModel;P.SqueezeBertTokenizer;P.StableLmForCausalLM;P.StableLmModel;P.StableLmPreTrainedModel;P.Starcoder2ForCausalLM;P.Starcoder2Model;P.Starcoder2PreTrainedModel;P.StoppingCriteria;P.StoppingCriteriaList;P.SummarizationPipeline;P.Swin2SRForImageSuperResolution;P.Swin2SRImageProcessor;P.Swin2SRModel;P.Swin2SRPreTrainedModel;P.SwinForImageClassification;P.SwinModel;P.SwinPreTrainedModel;P.T5ForConditionalGeneration;P.T5Model;P.T5PreTrainedModel;P.T5Tokenizer;P.TableTransformerForObjectDetection;P.TableTransformerModel;P.TableTransformerObjectDetectionOutput;P.TableTransformerPreTrainedModel;P.Tensor;P.Text2TextGenerationPipeline;P.TextClassificationPipeline;P.TextGenerationPipeline;P.TextStreamer;P.TextToAudioPipeline;P.TokenClassificationPipeline;P.TokenClassifierOutput;P.TokenizerModel;P.TrOCRForCausalLM;P.TrOCRPreTrainedModel;P.TranslationPipeline;P.UniSpeechForCTC;P.UniSpeechForSequenceClassification;P.UniSpeechModel;P.UniSpeechPreTrainedModel;P.UniSpeechSatForAudioFrameClassification;P.UniSpeechSatForCTC;P.UniSpeechSatForSequenceClassification;P.UniSpeechSatModel;P.UniSpeechSatPreTrainedModel;P.ViTFeatureExtractor;P.ViTForImageClassification;P.ViTImageProcessor;P.ViTModel;P.ViTPreTrainedModel;P.VisionEncoderDecoderModel;P.VitMatteForImageMatting;P.VitMatteImageProcessor;P.VitMattePreTrainedModel;P.VitsModel;P.VitsModelOutput;P.VitsPreTrainedModel;P.VitsTokenizer;P.Wav2Vec2BertForCTC;P.Wav2Vec2BertForSequenceClassification;P.Wav2Vec2BertModel;P.Wav2Vec2BertPreTrainedModel;P.Wav2Vec2CTCTokenizer;P.Wav2Vec2FeatureExtractor;P.Wav2Vec2ForAudioFrameClassification;P.Wav2Vec2ForCTC;P.Wav2Vec2ForSequenceClassification;P.Wav2Vec2Model;P.Wav2Vec2PreTrainedModel;P.Wav2Vec2ProcessorWithLM;P.WavLMForAudioFrameClassification;P.WavLMForCTC;P.WavLMForSequenceClassification;P.WavLMForXVector;P.WavLMModel;P.WavLMPreTrainedModel;P.WeSpeakerFeatureExtractor;P.WeSpeakerResNetModel;P.WeSpeakerResNetPreTrainedModel;P.WhisperFeatureExtractor;P.WhisperForConditionalGeneration;P.WhisperModel;P.WhisperPreTrainedModel;P.WhisperProcessor;P.WhisperTextStreamer;P.WhisperTokenizer;P.XLMForQuestionAnswering;P.XLMForSequenceClassification;P.XLMForTokenClassification;P.XLMModel;P.XLMPreTrainedModel;P.XLMRobertaForMaskedLM;P.XLMRobertaForQuestionAnswering;P.XLMRobertaForSequenceClassification;P.XLMRobertaForTokenClassification;P.XLMRobertaModel;P.XLMRobertaPreTrainedModel;P.XLMRobertaTokenizer;P.XLMTokenizer;P.XLMWithLMHeadModel;P.XVectorOutput;P.YolosFeatureExtractor;P.YolosForObjectDetection;P.YolosModel;P.YolosObjectDetectionOutput;P.YolosPreTrainedModel;P.ZeroShotAudioClassificationPipeline;P.ZeroShotClassificationPipeline;P.ZeroShotImageClassificationPipeline;P.ZeroShotObjectDetectionPipeline;P.bankers_round;P.cat;P.cos_sim;P.dot;P.dynamic_time_warping;var pE=P.env;P.full;P.full_like;P.getKeyValueShapes;P.hamming;P.hanning;P.interpolate;P.interpolate_4d;P.interpolate_data;P.is_chinese_char;P.layer_norm;P.log_softmax;P.magnitude;P.matmul;P.max;P.mean;P.mean_pooling;P.medianFilter;P.mel_filter_bank;P.min;P.ones;P.ones_like;P.permute;P.permute_data;P.pipeline;P.quantize_embeddings;P.read_audio;P.rfft;P.round;P.softmax;P.spectrogram;P.stack;P.std_mean;P.topk;P.window_function;P.zeros;P.zeros_like;function ph(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 tx={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(r){e.exports=r()})(function(){return function r(o,a,l){function p(g,M){if(!a[g]){if(!o[g]){var y=typeof ph=="function"&&ph;if(!M&&y)return y(g,!0);if(_)return _(g,!0);var E=new Error("Cannot find module '"+g+"'");throw E.code="MODULE_NOT_FOUND",E}var T=a[g]={exports:{}};o[g][0].call(T.exports,function(O){var S=o[g][1][O];return p(S||O)},T,T.exports,r,o,a,l)}return a[g].exports}for(var _=typeof ph=="function"&&ph,h=0;h>2,T=(3&g)<<4|M>>4,O=1>6:64,S=2>4,M=(15&E)<<4|(T=_.indexOf(h.charAt(S++)))>>2,y=(3&T)<<6|(O=_.indexOf(h.charAt(S++))),b[C++]=g,T!==64&&(b[C++]=M),O!==64&&(b[C++]=y);return b}},{"./support":30,"./utils":32}],2:[function(r,o,a){var l=r("./external"),p=r("./stream/DataWorker"),_=r("./stream/Crc32Probe"),h=r("./stream/DataLengthProbe");function g(M,y,E,T,O){this.compressedSize=M,this.uncompressedSize=y,this.crc32=E,this.compression=T,this.compressedContent=O}g.prototype={getContentWorker:function(){var M=new p(l.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new h("data_length")),y=this;return M.on("end",function(){if(this.streamInfo.data_length!==y.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),M},getCompressedWorker:function(){return new p(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,y,E){return M.pipe(new _).pipe(new h("uncompressedSize")).pipe(y.compressWorker(E)).pipe(new h("compressedSize")).withStreamInfo("compression",y)},o.exports=g},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(r,o,a){var l=r("./stream/GenericWorker");a.STORE={magic:"\0\0",compressWorker:function(){return new l("STORE compression")},uncompressWorker:function(){return new l("STORE decompression")}},a.DEFLATE=r("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(r,o,a){var l=r("./utils"),p=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,y,E){var T=p,O=E+y;g^=-1;for(var S=E;S>>8^T[255&(g^M[S])];return-1^g}(0|h,_,_.length,0):function(g,M,y,E){var T=p,O=E+y;g^=-1;for(var S=E;S>>8^T[255&(g^M.charCodeAt(S))];return-1^g}(0|h,_,_.length,0):0}},{"./utils":32}],5:[function(r,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(r,o,a){var l=null;l=typeof Promise<"u"?Promise:r("lie"),o.exports={Promise:l}},{lie:37}],7:[function(r,o,a){var l=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Uint32Array<"u",p=r("pako"),_=r("./utils"),h=r("./stream/GenericWorker"),g=l?"uint8array":"array";function M(y,E){h.call(this,"FlateWorker/"+y),this._pako=null,this._pakoAction=y,this._pakoOptions=E,this.meta={}}a.magic="\b\0",_.inherits(M,h),M.prototype.processChunk=function(y){this.meta=y.meta,this._pako===null&&this._createPako(),this._pako.push(_.transformTo(g,y.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 p[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var y=this;this._pako.onData=function(E){y.push({data:E,meta:y.meta})}},a.compressWorker=function(y){return new M("Deflate",y)},a.uncompressWorker=function(){return new M("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(r,o,a){function l(T,O){var S,C="";for(S=0;S>>=8;return C}function p(T,O,S,C,w,b){var I,U,z=T.file,B=T.compression,j=b!==g.utf8encode,N=_.transformTo("string",b(z.name)),ae=_.transformTo("string",g.utf8encode(z.name)),ce=z.comment,xe=_.transformTo("string",b(ce)),Y=_.transformTo("string",g.utf8encode(ce)),_e=ae.length!==z.name.length,L=Y.length!==ce.length,Se="",Xe="",me="",X=z.dir,ie=z.date,Me={crc32:0,compressedSize:0,uncompressedSize:0};O&&!S||(Me.crc32=T.crc32,Me.compressedSize=T.compressedSize,Me.uncompressedSize=T.uncompressedSize);var Q=0;O&&(Q|=8),j||!_e&&!L||(Q|=2048);var ge=0,Ke=0;X&&(ge|=16),w==="UNIX"?(Ke=798,ge|=function(Be,We){var st=Be;return Be||(st=We?16893:33204),(65535&st)<<16}(z.unixPermissions,X)):(Ke=20,ge|=function(Be){return 63&(Be||0)}(z.dosPermissions)),I=ie.getUTCHours(),I<<=6,I|=ie.getUTCMinutes(),I<<=5,I|=ie.getUTCSeconds()/2,U=ie.getUTCFullYear()-1980,U<<=4,U|=ie.getUTCMonth()+1,U<<=5,U|=ie.getUTCDate(),_e&&(Xe=l(1,1)+l(M(N),4)+ae,Se+="up"+l(Xe.length,2)+Xe),L&&(me=l(1,1)+l(M(xe),4)+Y,Se+="uc"+l(me.length,2)+me);var Le="";return Le+=` +\0`,Le+=l(Q,2),Le+=B.magic,Le+=l(I,2),Le+=l(U,2),Le+=l(Me.crc32,4),Le+=l(Me.compressedSize,4),Le+=l(Me.uncompressedSize,4),Le+=l(N.length,2),Le+=l(Se.length,2),{fileRecord:y.LOCAL_FILE_HEADER+Le+N+Se,dirRecord:y.CENTRAL_FILE_HEADER+l(Ke,2)+Le+l(xe.length,2)+"\0\0\0\0"+l(ge,4)+l(C,4)+N+Se+xe}}var _=r("../utils"),h=r("../stream/GenericWorker"),g=r("../utf8"),M=r("../crc32"),y=r("../signature");function E(T,O,S,C){h.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=O,this.zipPlatform=S,this.encodeFileName=C,this.streamFiles=T,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}_.inherits(E,h),E.prototype.push=function(T){var O=T.meta.percent||0,S=this.entriesCount,C=this._sources.length;this.accumulate?this.contentBuffer.push(T):(this.bytesWritten+=T.data.length,h.prototype.push.call(this,{data:T.data,meta:{currentFile:this.currentFile,percent:S?(O+100*(S-C-1))/S:100}}))},E.prototype.openedSource=function(T){this.currentSourceOffset=this.bytesWritten,this.currentFile=T.file.name;var O=this.streamFiles&&!T.file.dir;if(O){var S=p(T,O,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:S.fileRecord,meta:{percent:0}})}else this.accumulate=!0},E.prototype.closedSource=function(T){this.accumulate=!1;var O=this.streamFiles&&!T.file.dir,S=p(T,O,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(S.dirRecord),O)this.push({data:function(C){return y.DATA_DESCRIPTOR+l(C.crc32,4)+l(C.compressedSize,4)+l(C.uncompressedSize,4)}(T),meta:{percent:100}});else for(this.push({data:S.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},E.prototype.flush=function(){for(var T=this.bytesWritten,O=0;O=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=p},{"../utils":32}],19:[function(r,o,a){var l=r("./Uint8ArrayReader");function p(_){l.call(this,_)}r("../utils").inherits(p,l),p.prototype.readData=function(_){this.checkOffset(_);var h=this.data.slice(this.zero+this.index,this.zero+this.index+_);return this.index+=_,h},o.exports=p},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(r,o,a){var l=r("./DataReader");function p(_){l.call(this,_)}r("../utils").inherits(p,l),p.prototype.byteAt=function(_){return this.data.charCodeAt(this.zero+_)},p.prototype.lastIndexOfSignature=function(_){return this.data.lastIndexOf(_)-this.zero},p.prototype.readAndCheckSignature=function(_){return _===this.readData(4)},p.prototype.readData=function(_){this.checkOffset(_);var h=this.data.slice(this.zero+this.index,this.zero+this.index+_);return this.index+=_,h},o.exports=p},{"../utils":32,"./DataReader":18}],21:[function(r,o,a){var l=r("./ArrayReader");function p(_){l.call(this,_)}r("../utils").inherits(p,l),p.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=p},{"../utils":32,"./ArrayReader":17}],22:[function(r,o,a){var l=r("../utils"),p=r("../support"),_=r("./ArrayReader"),h=r("./StringReader"),g=r("./NodeBufferReader"),M=r("./Uint8ArrayReader");o.exports=function(y){var E=l.getTypeOf(y);return l.checkSupport(E),E!=="string"||p.uint8array?E==="nodebuffer"?new g(y):p.uint8array?new M(l.transformTo("uint8array",y)):new _(l.transformTo("array",y)):new h(y)}},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(r,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(r,o,a){var l=r("./GenericWorker"),p=r("../utils");function _(h){l.call(this,"ConvertWorker to "+h),this.destType=h}p.inherits(_,l),_.prototype.processChunk=function(h){this.push({data:p.transformTo(this.destType,h.data),meta:h.meta})},o.exports=_},{"../utils":32,"./GenericWorker":28}],25:[function(r,o,a){var l=r("./GenericWorker"),p=r("../crc32");function _(){l.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}r("../utils").inherits(_,l),_.prototype.processChunk=function(h){this.streamInfo.crc32=p(h.data,this.streamInfo.crc32||0),this.push(h)},o.exports=_},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(r,o,a){var l=r("../utils"),p=r("./GenericWorker");function _(h){p.call(this,"DataLengthProbe for "+h),this.propName=h,this.withStreamInfo(h,0)}l.inherits(_,p),_.prototype.processChunk=function(h){if(h){var g=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=g+h.data.length}p.prototype.processChunk.call(this,h)},o.exports=_},{"../utils":32,"./GenericWorker":28}],27:[function(r,o,a){var l=r("../utils"),p=r("./GenericWorker");function _(h){p.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(_,p),_.prototype.cleanUp=function(){p.prototype.cleanUp.call(this),this.data=null},_.prototype.resume=function(){return!!p.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(r,o,a){function l(p){this.name=p||"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(p){this.emit("data",p)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0}catch(p){this.emit("error",p)}return!0},error:function(p){return!this.isFinished&&(this.isPaused?this.generatedError=p:(this.isFinished=!0,this.emit("error",p),this.previous&&this.previous.error(p),this.cleanUp()),!0)},on:function(p,_){return this._listeners[p].push(_),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(p,_){if(this._listeners[p])for(var h=0;h "+p:p}},o.exports=l},{}],29:[function(r,o,a){var l=r("../utils"),p=r("./ConvertWorker"),_=r("./GenericWorker"),h=r("../base64"),g=r("../support"),M=r("../external"),y=null;if(g.nodestream)try{y=r("../nodejs/NodejsStreamOutputAdapter")}catch{}function E(O,S){return new M.Promise(function(C,w){var b=[],I=O._internalType,U=O._outputType,z=O._mimeType;O.on("data",function(B,j){b.push(B),S&&S(j)}).on("error",function(B){b=[],w(B)}).on("end",function(){try{var B=function(j,N,ae){switch(j){case"blob":return l.newBlob(l.transformTo("arraybuffer",N),ae);case"base64":return h.encode(N);default:return l.transformTo(j,N)}}(U,function(j,N){var ae,ce=0,xe=null,Y=0;for(ae=0;ae"u")a.blob=!1;else{var l=new ArrayBuffer(0);try{a.blob=new Blob([l],{type:"application/zip"}).size===0}catch{try{var p=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);p.append(l),a.blob=p.getBlob("application/zip").size===0}catch{a.blob=!1}}}try{a.nodestream=!!r("readable-stream").Readable}catch{a.nodestream=!1}},{"readable-stream":16}],31:[function(r,o,a){for(var l=r("./utils"),p=r("./support"),_=r("./nodejsUtils"),h=r("./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 y(){h.call(this,"utf-8 decode"),this.leftOver=null}function E(){h.call(this,"utf-8 encode")}a.utf8encode=function(T){return p.nodebuffer?_.newBufferFrom(T,"utf-8"):function(O){var S,C,w,b,I,U=O.length,z=0;for(b=0;b>>6:(C<65536?S[I++]=224|C>>>12:(S[I++]=240|C>>>18,S[I++]=128|C>>>12&63),S[I++]=128|C>>>6&63),S[I++]=128|63&C);return S}(T)},a.utf8decode=function(T){return p.nodebuffer?l.transformTo("nodebuffer",T).toString("utf-8"):function(O){var S,C,w,b,I=O.length,U=new Array(2*I);for(S=C=0;S>10&1023,U[C++]=56320|1023&w)}return U.length!==C&&(U.subarray?U=U.subarray(0,C):U.length=C),l.applyFromCharCode(U)}(T=l.transformTo(p.uint8array?"uint8array":"array",T))},l.inherits(y,h),y.prototype.processChunk=function(T){var O=l.transformTo(p.uint8array?"uint8array":"array",T.data);if(this.leftOver&&this.leftOver.length){if(p.uint8array){var S=O;(O=new Uint8Array(S.length+this.leftOver.length)).set(this.leftOver,0),O.set(S,this.leftOver.length)}else O=this.leftOver.concat(O);this.leftOver=null}var C=function(b,I){var U;for((I=I||b.length)>b.length&&(I=b.length),U=I-1;0<=U&&(192&b[U])==128;)U--;return U<0||U===0?I:U+g[b[U]]>I?U:I}(O),w=O;C!==O.length&&(p.uint8array?(w=O.subarray(0,C),this.leftOver=O.subarray(C,O.length)):(w=O.slice(0,C),this.leftOver=O.slice(C,O.length))),this.push({data:a.utf8decode(w),meta:T.meta})},y.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:a.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},a.Utf8DecodeWorker=y,l.inherits(E,h),E.prototype.processChunk=function(T){this.push({data:a.utf8encode(T.data),meta:T.meta})},a.Utf8EncodeWorker=E},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(r,o,a){var l=r("./support"),p=r("./base64"),_=r("./nodejsUtils"),h=r("./external");function g(S){return S}function M(S,C){for(var w=0;w>8;this.dir=!!(16&this.externalFileAttributes),T==0&&(this.dosPermissions=63&this.externalFileAttributes),T==3&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||this.fileNameStr.slice(-1)!=="/"||(this.dir=!0)},parseZIP64ExtraField:function(){if(this.extraFields[1]){var T=l(this.extraFields[1].value);this.uncompressedSize===p.MAX_VALUE_32BITS&&(this.uncompressedSize=T.readInt(8)),this.compressedSize===p.MAX_VALUE_32BITS&&(this.compressedSize=T.readInt(8)),this.localHeaderOffset===p.MAX_VALUE_32BITS&&(this.localHeaderOffset=T.readInt(8)),this.diskNumberStart===p.MAX_VALUE_32BITS&&(this.diskNumberStart=T.readInt(4))}},readExtraFields:function(T){var O,S,C,w=T.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});T.index+4>>6:(T<65536?E[C++]=224|T>>>12:(E[C++]=240|T>>>18,E[C++]=128|T>>>12&63),E[C++]=128|T>>>6&63),E[C++]=128|63&T);return E},a.buf2binstring=function(y){return M(y,y.length)},a.binstring2buf=function(y){for(var E=new l.Buf8(y.length),T=0,O=E.length;T>10&1023,b[O++]=56320|1023&S)}return M(b,O)},a.utf8border=function(y,E){var T;for((E=E||y.length)>y.length&&(E=y.length),T=E-1;0<=T&&(192&y[T])==128;)T--;return T<0||T===0?E:T+h[y[T]]>E?T:E}},{"./common":41}],43:[function(r,o,a){o.exports=function(l,p,_,h){for(var g=65535&l|0,M=l>>>16&65535|0,y=0;_!==0;){for(_-=y=2e3<_?2e3:_;M=M+(g=g+p[h++]|0)|0,--y;);g%=65521,M%=65521}return g|M<<16|0}},{}],44:[function(r,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(r,o,a){var l=function(){for(var p,_=[],h=0;h<256;h++){p=h;for(var g=0;g<8;g++)p=1&p?3988292384^p>>>1:p>>>1;_[h]=p}return _}();o.exports=function(p,_,h,g){var M=l,y=g+h;p^=-1;for(var E=g;E>>8^M[255&(p^_[E])];return-1^p}},{}],46:[function(r,o,a){var l,p=r("../utils/common"),_=r("./trees"),h=r("./adler32"),g=r("./crc32"),M=r("./messages"),y=0,E=4,T=0,O=-2,S=-1,C=4,w=2,b=8,I=9,U=286,z=30,B=19,j=2*U+1,N=15,ae=3,ce=258,xe=ce+ae+1,Y=42,_e=113,L=1,Se=2,Xe=3,me=4;function X(A,$e){return A.msg=M[$e],$e}function ie(A){return(A<<1)-(4A.avail_out&&(Pe=A.avail_out),Pe!==0&&(p.arraySet(A.output,$e.pending_buf,$e.pending_out,Pe,A.next_out),A.next_out+=Pe,$e.pending_out+=Pe,A.total_out+=Pe,A.avail_out-=Pe,$e.pending-=Pe,$e.pending===0&&($e.pending_out=0))}function ge(A,$e){_._tr_flush_block(A,0<=A.block_start?A.block_start:-1,A.strstart-A.block_start,$e),A.block_start=A.strstart,Q(A.strm)}function Ke(A,$e){A.pending_buf[A.pending++]=$e}function Le(A,$e){A.pending_buf[A.pending++]=$e>>>8&255,A.pending_buf[A.pending++]=255&$e}function Be(A,$e){var Pe,se,re=A.max_chain_length,ye=A.strstart,R=A.prev_length,ee=A.nice_match,D=A.strstart>A.w_size-xe?A.strstart-(A.w_size-xe):0,ue=A.window,le=A.w_mask,ke=A.prev,Ne=A.strstart+ce,dt=ue[ye+R-1],Je=ue[ye+R];A.prev_length>=A.good_match&&(re>>=2),ee>A.lookahead&&(ee=A.lookahead);do if(ue[(Pe=$e)+R]===Je&&ue[Pe+R-1]===dt&&ue[Pe]===ue[ye]&&ue[++Pe]===ue[ye+1]){ye+=2,Pe++;do;while(ue[++ye]===ue[++Pe]&&ue[++ye]===ue[++Pe]&&ue[++ye]===ue[++Pe]&&ue[++ye]===ue[++Pe]&&ue[++ye]===ue[++Pe]&&ue[++ye]===ue[++Pe]&&ue[++ye]===ue[++Pe]&&ue[++ye]===ue[++Pe]&&yeD&&--re!=0);return R<=A.lookahead?R:A.lookahead}function We(A){var $e,Pe,se,re,ye,R,ee,D,ue,le,ke=A.w_size;do{if(re=A.window_size-A.lookahead-A.strstart,A.strstart>=ke+(ke-xe)){for(p.arraySet(A.window,A.window,ke,ke,0),A.match_start-=ke,A.strstart-=ke,A.block_start-=ke,$e=Pe=A.hash_size;se=A.head[--$e],A.head[$e]=ke<=se?se-ke:0,--Pe;);for($e=Pe=ke;se=A.prev[--$e],A.prev[$e]=ke<=se?se-ke:0,--Pe;);re+=ke}if(A.strm.avail_in===0)break;if(R=A.strm,ee=A.window,D=A.strstart+A.lookahead,ue=re,le=void 0,le=R.avail_in,ue=ae)for(ye=A.strstart-A.insert,A.ins_h=A.window[ye],A.ins_h=(A.ins_h<=ae&&(A.ins_h=(A.ins_h<=ae)if(se=_._tr_tally(A,A.strstart-A.match_start,A.match_length-ae),A.lookahead-=A.match_length,A.match_length<=A.max_lazy_match&&A.lookahead>=ae){for(A.match_length--;A.strstart++,A.ins_h=(A.ins_h<=ae&&(A.ins_h=(A.ins_h<=ae&&A.match_length<=A.prev_length){for(re=A.strstart+A.lookahead-ae,se=_._tr_tally(A,A.strstart-1-A.prev_match,A.prev_length-ae),A.lookahead-=A.prev_length-1,A.prev_length-=2;++A.strstart<=re&&(A.ins_h=(A.ins_h<A.pending_buf_size-5&&(Pe=A.pending_buf_size-5);;){if(A.lookahead<=1){if(We(A),A.lookahead===0&&$e===y)return L;if(A.lookahead===0)break}A.strstart+=A.lookahead,A.lookahead=0;var se=A.block_start+Pe;if((A.strstart===0||A.strstart>=se)&&(A.lookahead=A.strstart-se,A.strstart=se,ge(A,!1),A.strm.avail_out===0)||A.strstart-A.block_start>=A.w_size-xe&&(ge(A,!1),A.strm.avail_out===0))return L}return A.insert=0,$e===E?(ge(A,!0),A.strm.avail_out===0?Xe:me):(A.strstart>A.block_start&&(ge(A,!1),A.strm.avail_out),L)}),new Ge(4,4,8,4,st),new Ge(4,5,16,8,st),new Ge(4,6,32,32,st),new Ge(4,4,16,16,pt),new Ge(8,16,32,32,pt),new Ge(8,16,128,128,pt),new Ge(8,32,128,256,pt),new Ge(32,128,258,1024,pt),new Ge(32,258,258,4096,pt)],a.deflateInit=function(A,$e){return et(A,$e,b,15,8,0)},a.deflateInit2=et,a.deflateReset=Ye,a.deflateResetKeep=je,a.deflateSetHeader=function(A,$e){return A&&A.state?A.state.wrap!==2?O:(A.state.gzhead=$e,T):O},a.deflate=function(A,$e){var Pe,se,re,ye;if(!A||!A.state||5<$e||$e<0)return A?X(A,O):O;if(se=A.state,!A.output||!A.input&&A.avail_in!==0||se.status===666&&$e!==E)return X(A,A.avail_out===0?-5:O);if(se.strm=A,Pe=se.last_flush,se.last_flush=$e,se.status===Y)if(se.wrap===2)A.adler=0,Ke(se,31),Ke(se,139),Ke(se,8),se.gzhead?(Ke(se,(se.gzhead.text?1:0)+(se.gzhead.hcrc?2:0)+(se.gzhead.extra?4:0)+(se.gzhead.name?8:0)+(se.gzhead.comment?16:0)),Ke(se,255&se.gzhead.time),Ke(se,se.gzhead.time>>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=_e);else{var R=b+(se.w_bits-8<<4)<<8;R|=(2<=se.strategy||se.level<2?0:se.level<6?1:se.level===6?2:3)<<6,se.strstart!==0&&(R|=32),R+=31-R%31,se.status=_e,Le(se,R),se.strstart!==0&&(Le(se,A.adler>>>16),Le(se,65535&A.adler)),A.adler=1}if(se.status===69)if(se.gzhead.extra){for(re=se.pending;se.gzindex<(65535&se.gzhead.extra.length)&&(se.pending!==se.pending_buf_size||(se.gzhead.hcrc&&se.pending>re&&(A.adler=g(A.adler,se.pending_buf,se.pending-re,re)),Q(A),re=se.pending,se.pending!==se.pending_buf_size));)Ke(se,255&se.gzhead.extra[se.gzindex]),se.gzindex++;se.gzhead.hcrc&&se.pending>re&&(A.adler=g(A.adler,se.pending_buf,se.pending-re,re)),se.gzindex===se.gzhead.extra.length&&(se.gzindex=0,se.status=73)}else se.status=73;if(se.status===73)if(se.gzhead.name){re=se.pending;do{if(se.pending===se.pending_buf_size&&(se.gzhead.hcrc&&se.pending>re&&(A.adler=g(A.adler,se.pending_buf,se.pending-re,re)),Q(A),re=se.pending,se.pending===se.pending_buf_size)){ye=1;break}ye=se.gzindexre&&(A.adler=g(A.adler,se.pending_buf,se.pending-re,re)),ye===0&&(se.gzindex=0,se.status=91)}else se.status=91;if(se.status===91)if(se.gzhead.comment){re=se.pending;do{if(se.pending===se.pending_buf_size&&(se.gzhead.hcrc&&se.pending>re&&(A.adler=g(A.adler,se.pending_buf,se.pending-re,re)),Q(A),re=se.pending,se.pending===se.pending_buf_size)){ye=1;break}ye=se.gzindexre&&(A.adler=g(A.adler,se.pending_buf,se.pending-re,re)),ye===0&&(se.status=103)}else se.status=103;if(se.status===103&&(se.gzhead.hcrc?(se.pending+2>se.pending_buf_size&&Q(A),se.pending+2<=se.pending_buf_size&&(Ke(se,255&A.adler),Ke(se,A.adler>>8&255),A.adler=0,se.status=_e)):se.status=_e),se.pending!==0){if(Q(A),A.avail_out===0)return se.last_flush=-1,T}else if(A.avail_in===0&&ie($e)<=ie(Pe)&&$e!==E)return X(A,-5);if(se.status===666&&A.avail_in!==0)return X(A,-5);if(A.avail_in!==0||se.lookahead!==0||$e!==y&&se.status!==666){var ee=se.strategy===2?function(D,ue){for(var le;;){if(D.lookahead===0&&(We(D),D.lookahead===0)){if(ue===y)return L;break}if(D.match_length=0,le=_._tr_tally(D,0,D.window[D.strstart]),D.lookahead--,D.strstart++,le&&(ge(D,!1),D.strm.avail_out===0))return L}return D.insert=0,ue===E?(ge(D,!0),D.strm.avail_out===0?Xe:me):D.last_lit&&(ge(D,!1),D.strm.avail_out===0)?L:Se}(se,$e):se.strategy===3?function(D,ue){for(var le,ke,Ne,dt,Je=D.window;;){if(D.lookahead<=ce){if(We(D),D.lookahead<=ce&&ue===y)return L;if(D.lookahead===0)break}if(D.match_length=0,D.lookahead>=ae&&0D.lookahead&&(D.match_length=D.lookahead)}if(D.match_length>=ae?(le=_._tr_tally(D,1,D.match_length-ae),D.lookahead-=D.match_length,D.strstart+=D.match_length,D.match_length=0):(le=_._tr_tally(D,0,D.window[D.strstart]),D.lookahead--,D.strstart++),le&&(ge(D,!1),D.strm.avail_out===0))return L}return D.insert=0,ue===E?(ge(D,!0),D.strm.avail_out===0?Xe:me):D.last_lit&&(ge(D,!1),D.strm.avail_out===0)?L:Se}(se,$e):l[se.level].func(se,$e);if(ee!==Xe&&ee!==me||(se.status=666),ee===L||ee===Xe)return A.avail_out===0&&(se.last_flush=-1),T;if(ee===Se&&($e===1?_._tr_align(se):$e!==5&&(_._tr_stored_block(se,0,0,!1),$e===3&&(Me(se.head),se.lookahead===0&&(se.strstart=0,se.block_start=0,se.insert=0))),Q(A),A.avail_out===0))return se.last_flush=-1,T}return $e!==E?T: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)):(Le(se,A.adler>>>16),Le(se,65535&A.adler)),Q(A),0=Pe.w_size&&(ye===0&&(Me(Pe.head),Pe.strstart=0,Pe.block_start=0,Pe.insert=0),ue=new p.Buf8(Pe.w_size),p.arraySet(ue,$e,le-Pe.w_size,Pe.w_size,0),$e=ue,le=Pe.w_size),R=A.avail_in,ee=A.next_in,D=A.input,A.avail_in=le,A.next_in=0,A.input=$e,We(Pe);Pe.lookahead>=ae;){for(se=Pe.strstart,re=Pe.lookahead-(ae-1);Pe.ins_h=(Pe.ins_h<>>=ae=N>>>24,I-=ae,(ae=N>>>16&255)===0)Se[M++]=65535&N;else{if(!(16&ae)){if(!(64&ae)){N=U[(65535&N)+(b&(1<>>=ae,I-=ae),I<15&&(b+=L[h++]<>>=ae=N>>>24,I-=ae,!(16&(ae=N>>>16&255))){if(!(64&ae)){N=z[(65535&N)+(b&(1<>>=ae,I-=ae,(ae=M-y)>3,b&=(1<<(I-=ce<<3))-1,l.next_in=h,l.next_out=M,l.avail_in=h>>24&255)+(Y>>>8&65280)+((65280&Y)<<8)+((255&Y)<<24)}function b(){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(Y){var _e;return Y&&Y.state?(_e=Y.state,Y.total_in=Y.total_out=_e.total=0,Y.msg="",_e.wrap&&(Y.adler=1&_e.wrap),_e.mode=O,_e.last=0,_e.havedict=0,_e.dmax=32768,_e.head=null,_e.hold=0,_e.bits=0,_e.lencode=_e.lendyn=new l.Buf32(S),_e.distcode=_e.distdyn=new l.Buf32(C),_e.sane=1,_e.back=-1,E):T}function U(Y){var _e;return Y&&Y.state?((_e=Y.state).wsize=0,_e.whave=0,_e.wnext=0,I(Y)):T}function z(Y,_e){var L,Se;return Y&&Y.state?(Se=Y.state,_e<0?(L=0,_e=-_e):(L=1+(_e>>4),_e<48&&(_e&=15)),_e&&(_e<8||15<_e)?T:(Se.window!==null&&Se.wbits!==_e&&(Se.window=null),Se.wrap=L,Se.wbits=_e,U(Y))):T}function B(Y,_e){var L,Se;return Y?(Se=new b,(Y.state=Se).window=null,(L=z(Y,_e))!==E&&(Y.state=null),L):T}var j,N,ae=!0;function ce(Y){if(ae){var _e;for(j=new l.Buf32(512),N=new l.Buf32(32),_e=0;_e<144;)Y.lens[_e++]=8;for(;_e<256;)Y.lens[_e++]=9;for(;_e<280;)Y.lens[_e++]=7;for(;_e<288;)Y.lens[_e++]=8;for(g(M,Y.lens,0,288,j,0,Y.work,{bits:9}),_e=0;_e<32;)Y.lens[_e++]=5;g(y,Y.lens,0,32,N,0,Y.work,{bits:5}),ae=!1}Y.lencode=j,Y.lenbits=9,Y.distcode=N,Y.distbits=5}function xe(Y,_e,L,Se){var Xe,me=Y.state;return me.window===null&&(me.wsize=1<=me.wsize?(l.arraySet(me.window,_e,L-me.wsize,me.wsize,0),me.wnext=0,me.whave=me.wsize):(Se<(Xe=me.wsize-me.wnext)&&(Xe=Se),l.arraySet(me.window,_e,L-Se,Xe,me.wnext),(Se-=Xe)?(l.arraySet(me.window,_e,L-Se,Se,0),me.wnext=Se,me.whave=me.wsize):(me.wnext+=Xe,me.wnext===me.wsize&&(me.wnext=0),me.whave>>8&255,L.check=_(L.check,ye,2,0),ge=Q=0,L.mode=2;break}if(L.flags=0,L.head&&(L.head.done=!1),!(1&L.wrap)||(((255&Q)<<8)+(Q>>8))%31){Y.msg="incorrect header check",L.mode=30;break}if((15&Q)!=8){Y.msg="unknown compression method",L.mode=30;break}if(ge-=4,A=8+(15&(Q>>>=4)),L.wbits===0)L.wbits=A;else if(A>L.wbits){Y.msg="invalid window size",L.mode=30;break}L.dmax=1<>8&1),512&L.flags&&(ye[0]=255&Q,ye[1]=Q>>>8&255,L.check=_(L.check,ye,2,0)),ge=Q=0,L.mode=3;case 3:for(;ge<32;){if(ie===0)break e;ie--,Q+=Se[me++]<>>8&255,ye[2]=Q>>>16&255,ye[3]=Q>>>24&255,L.check=_(L.check,ye,4,0)),ge=Q=0,L.mode=4;case 4:for(;ge<16;){if(ie===0)break e;ie--,Q+=Se[me++]<>8),512&L.flags&&(ye[0]=255&Q,ye[1]=Q>>>8&255,L.check=_(L.check,ye,2,0)),ge=Q=0,L.mode=5;case 5:if(1024&L.flags){for(;ge<16;){if(ie===0)break e;ie--,Q+=Se[me++]<>>8&255,L.check=_(L.check,ye,2,0)),ge=Q=0}else L.head&&(L.head.extra=null);L.mode=6;case 6:if(1024&L.flags&&(ie<(Be=L.length)&&(Be=ie),Be&&(L.head&&(A=L.head.extra_len-L.length,L.head.extra||(L.head.extra=new Array(L.head.extra_len)),l.arraySet(L.head.extra,Se,me,Be,A)),512&L.flags&&(L.check=_(L.check,Se,Be,me)),ie-=Be,me+=Be,L.length-=Be),L.length))break e;L.length=0,L.mode=7;case 7:if(2048&L.flags){if(ie===0)break e;for(Be=0;A=Se[me+Be++],L.head&&A&&L.length<65536&&(L.head.name+=String.fromCharCode(A)),A&&Be>9&1,L.head.done=!0),Y.adler=L.check=0,L.mode=12;break;case 10:for(;ge<32;){if(ie===0)break e;ie--,Q+=Se[me++]<>>=7&ge,ge-=7&ge,L.mode=27;break}for(;ge<3;){if(ie===0)break e;ie--,Q+=Se[me++]<>>=1)){case 0:L.mode=14;break;case 1:if(ce(L),L.mode=20,_e!==6)break;Q>>>=2,ge-=2;break e;case 2:L.mode=17;break;case 3:Y.msg="invalid block type",L.mode=30}Q>>>=2,ge-=2;break;case 14:for(Q>>>=7&ge,ge-=7≥ge<32;){if(ie===0)break e;ie--,Q+=Se[me++]<>>16^65535)){Y.msg="invalid stored block lengths",L.mode=30;break}if(L.length=65535&Q,ge=Q=0,L.mode=15,_e===6)break e;case 15:L.mode=16;case 16:if(Be=L.length){if(ie>>=5,ge-=5,L.ndist=1+(31&Q),Q>>>=5,ge-=5,L.ncode=4+(15&Q),Q>>>=4,ge-=4,286>>=3,ge-=3}for(;L.have<19;)L.lens[R[L.have++]]=0;if(L.lencode=L.lendyn,L.lenbits=7,Pe={bits:L.lenbits},$e=g(0,L.lens,0,19,L.lencode,0,L.work,Pe),L.lenbits=Pe.bits,$e){Y.msg="invalid code lengths set",L.mode=30;break}L.have=0,L.mode=19;case 19:for(;L.have>>16&255,Te=65535&re,!((pt=re>>>24)<=ge);){if(ie===0)break e;ie--,Q+=Se[me++]<>>=pt,ge-=pt,L.lens[L.have++]=Te;else{if(Te===16){for(se=pt+2;ge>>=pt,ge-=pt,L.have===0){Y.msg="invalid bit length repeat",L.mode=30;break}A=L.lens[L.have-1],Be=3+(3&Q),Q>>>=2,ge-=2}else if(Te===17){for(se=pt+3;ge>>=pt)),Q>>>=3,ge-=3}else{for(se=pt+7;ge>>=pt)),Q>>>=7,ge-=7}if(L.have+Be>L.nlen+L.ndist){Y.msg="invalid bit length repeat",L.mode=30;break}for(;Be--;)L.lens[L.have++]=A}}if(L.mode===30)break;if(L.lens[256]===0){Y.msg="invalid code -- missing end-of-block",L.mode=30;break}if(L.lenbits=9,Pe={bits:L.lenbits},$e=g(M,L.lens,0,L.nlen,L.lencode,0,L.work,Pe),L.lenbits=Pe.bits,$e){Y.msg="invalid literal/lengths set",L.mode=30;break}if(L.distbits=6,L.distcode=L.distdyn,Pe={bits:L.distbits},$e=g(y,L.lens,L.nlen,L.ndist,L.distcode,0,L.work,Pe),L.distbits=Pe.bits,$e){Y.msg="invalid distances set",L.mode=30;break}if(L.mode=20,_e===6)break e;case 20:L.mode=21;case 21:if(6<=ie&&258<=Me){Y.next_out=X,Y.avail_out=Me,Y.next_in=me,Y.avail_in=ie,L.hold=Q,L.bits=ge,h(Y,Le),X=Y.next_out,Xe=Y.output,Me=Y.avail_out,me=Y.next_in,Se=Y.input,ie=Y.avail_in,Q=L.hold,ge=L.bits,L.mode===12&&(L.back=-1);break}for(L.back=0;Ge=(re=L.lencode[Q&(1<>>16&255,Te=65535&re,!((pt=re>>>24)<=ge);){if(ie===0)break e;ie--,Q+=Se[me++]<>je)])>>>16&255,Te=65535&re,!(je+(pt=re>>>24)<=ge);){if(ie===0)break e;ie--,Q+=Se[me++]<>>=je,ge-=je,L.back+=je}if(Q>>>=pt,ge-=pt,L.back+=pt,L.length=Te,Ge===0){L.mode=26;break}if(32&Ge){L.back=-1,L.mode=12;break}if(64&Ge){Y.msg="invalid literal/length code",L.mode=30;break}L.extra=15&Ge,L.mode=22;case 22:if(L.extra){for(se=L.extra;ge>>=L.extra,ge-=L.extra,L.back+=L.extra}L.was=L.length,L.mode=23;case 23:for(;Ge=(re=L.distcode[Q&(1<>>16&255,Te=65535&re,!((pt=re>>>24)<=ge);){if(ie===0)break e;ie--,Q+=Se[me++]<>je)])>>>16&255,Te=65535&re,!(je+(pt=re>>>24)<=ge);){if(ie===0)break e;ie--,Q+=Se[me++]<>>=je,ge-=je,L.back+=je}if(Q>>>=pt,ge-=pt,L.back+=pt,64&Ge){Y.msg="invalid distance code",L.mode=30;break}L.offset=Te,L.extra=15&Ge,L.mode=24;case 24:if(L.extra){for(se=L.extra;ge>>=L.extra,ge-=L.extra,L.back+=L.extra}if(L.offset>L.dmax){Y.msg="invalid distance too far back",L.mode=30;break}L.mode=25;case 25:if(Me===0)break e;if(Be=Le-Me,L.offset>Be){if((Be=L.offset-Be)>L.whave&&L.sane){Y.msg="invalid distance too far back",L.mode=30;break}We=Be>L.wnext?(Be-=L.wnext,L.wsize-Be):L.wnext-Be,Be>L.length&&(Be=L.length),st=L.window}else st=Xe,We=X-L.offset,Be=L.length;for(Mej?(ae=We[st+C[_e]],ge[Ke+C[_e]]):(ae=96,0),b=1<>X)+(I-=b)]=N<<24|ae<<16|ce|0,I!==0;);for(b=1<>=1;if(b!==0?(Q&=b-1,Q+=b):Q=0,_e++,--Le[Y]==0){if(Y===Se)break;Y=y[E+C[_e]]}if(Xe>>7)]}function Ke(re,ye){re.pending_buf[re.pending++]=255&ye,re.pending_buf[re.pending++]=ye>>>8&255}function Le(re,ye,R){re.bi_valid>w-R?(re.bi_buf|=ye<>w-re.bi_valid,re.bi_valid+=R-w):(re.bi_buf|=ye<>>=1,R<<=1,0<--ye;);return R>>>1}function st(re,ye,R){var ee,D,ue=new Array(C+1),le=0;for(ee=1;ee<=C;ee++)ue[ee]=le=le+R[ee-1]<<1;for(D=0;D<=ye;D++){var ke=re[2*D+1];ke!==0&&(re[2*D]=We(ue[ke]++,ke))}}function pt(re){var ye;for(ye=0;ye>1;1<=R;R--)je(re,ue,R);for(D=Ne;R=re.heap[1],re.heap[1]=re.heap[re.heap_len--],je(re,ue,1),ee=re.heap[1],re.heap[--re.heap_max]=R,re.heap[--re.heap_max]=ee,ue[2*D]=ue[2*R]+ue[2*ee],re.depth[D]=(re.depth[R]>=re.depth[ee]?re.depth[R]:re.depth[ee])+1,ue[2*R+1]=ue[2*ee+1]=D,re.heap[1]=D++,je(re,ue,1),2<=re.heap_len;);re.heap[--re.heap_max]=re.heap[1],function(Je,Ve){var Z,ve,Re,qe,Qe,tt,ft=Ve.dyn_tree,ht=Ve.max_code,Tt=Ve.stat_desc.static_tree,bt=Ve.stat_desc.has_stree,Et=Ve.stat_desc.extra_bits,Lt=Ve.stat_desc.extra_base,at=Ve.stat_desc.max_length,Ot=0;for(qe=0;qe<=C;qe++)Je.bl_count[qe]=0;for(ft[2*Je.heap[Je.heap_max]+1]=0,Z=Je.heap_max+1;Z>=7;D>>=1)if(1&dt&&ke.dyn_ltree[2*Ne]!==0)return p;if(ke.dyn_ltree[18]!==0||ke.dyn_ltree[20]!==0||ke.dyn_ltree[26]!==0)return _;for(Ne=32;Ne>>3,(ue=re.static_len+3+7>>>3)<=D&&(D=ue)):D=ue=R+5,R+4<=D&&ye!==-1?se(re,ye,R,ee):re.strategy===4||ue===D?(Le(re,2+(ee?1:0),3),Ye(re,xe,Y)):(Le(re,4+(ee?1:0),3),function(ke,Ne,dt,Je){var Ve;for(Le(ke,Ne-257,5),Le(ke,dt-1,5),Le(ke,Je-4,4),Ve=0;Ve>>8&255,re.pending_buf[re.d_buf+2*re.last_lit+1]=255&ye,re.pending_buf[re.l_buf+re.last_lit]=255&R,re.last_lit++,ye===0?re.dyn_ltree[2*R]++:(re.matches++,ye--,re.dyn_ltree[2*(L[R]+y+1)]++,re.dyn_dtree[2*ge(ye)]++),re.last_lit===re.lit_bufsize-1},a._tr_align=function(re){Le(re,2,3),Be(re,I,xe),function(ye){ye.bi_valid===16?(Ke(ye,ye.bi_buf),ye.bi_buf=0,ye.bi_valid=0):8<=ye.bi_valid&&(ye.pending_buf[ye.pending++]=255&ye.bi_buf,ye.bi_buf>>=8,ye.bi_valid-=8)}(re)}},{"../utils/common":41}],53:[function(r,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(r,o,a){(function(l){(function(p,_){if(!p.setImmediate){var h,g,M,y,E=1,T={},O=!1,S=p.document,C=Object.getPrototypeOf&&Object.getPrototypeOf(p);C=C&&C.setTimeout?C:p,h={}.toString.call(p.process)==="[object process]"?function(U){process.nextTick(function(){b(U)})}:function(){if(p.postMessage&&!p.importScripts){var U=!0,z=p.onmessage;return p.onmessage=function(){U=!1},p.postMessage("","*"),p.onmessage=z,U}}()?(y="setImmediate$"+Math.random()+"$",p.addEventListener?p.addEventListener("message",I,!1):p.attachEvent("onmessage",I),function(U){p.postMessage(y+U,"*")}):p.MessageChannel?((M=new MessageChannel).port1.onmessage=function(U){b(U.data)},function(U){M.port2.postMessage(U)}):S&&"onreadystatechange"in S.createElement("script")?(g=S.documentElement,function(U){var z=S.createElement("script");z.onreadystatechange=function(){b(U),z.onreadystatechange=null,g.removeChild(z),z=null},g.appendChild(z)}):function(U){setTimeout(b,0,U)},C.setImmediate=function(U){typeof U!="function"&&(U=new Function(""+U));for(var z=new Array(arguments.length-1),B=0;B"u"?l===void 0?this:l:self)}).call(this,typeof Co<"u"?Co:typeof self<"u"?self:typeof window<"u"?window:{})},{}]},{},[10])(10)})})(tx);var fE=tx.exports;const hE=k_(fE);var rx={exports:{}};(function(e,t){(function(r,o){o()})(Co,function(){function r(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,y){var E=new XMLHttpRequest;E.open("GET",g),E.responseType="blob",E.onload=function(){h(E.response,M,y)},E.onerror=function(){console.error("could not download file")},E.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 p=typeof window=="object"&&window.window===window?window:typeof self=="object"&&self.self===self?self:typeof Co=="object"&&Co.global===Co?Co:void 0,_=p.navigator&&/Macintosh/.test(navigator.userAgent)&&/AppleWebKit/.test(navigator.userAgent)&&!/Safari/.test(navigator.userAgent),h=p.saveAs||(typeof window!="object"||window!==p?function(){}:"download"in HTMLAnchorElement.prototype&&!_?function(g,M,y){var E=p.URL||p.webkitURL,T=document.createElement("a");M=M||g.name||"download",T.download=M,T.rel="noopener",typeof g=="string"?(T.href=g,T.origin===location.origin?l(T):a(T.href)?o(g,M,y):l(T,T.target="_blank")):(T.href=E.createObjectURL(g),setTimeout(function(){E.revokeObjectURL(T.href)},4e4),setTimeout(function(){l(T)},0))}:"msSaveOrOpenBlob"in navigator?function(g,M,y){if(M=M||g.name||"download",typeof g!="string")navigator.msSaveOrOpenBlob(r(g,y),M);else if(a(g))o(g,M,y);else{var E=document.createElement("a");E.href=g,E.target="_blank",setTimeout(function(){l(E)})}}:function(g,M,y,E){if(E=E||open("","_blank"),E&&(E.document.title=E.document.body.innerText="downloading..."),typeof g=="string")return o(g,M,y);var T=g.type==="application/octet-stream",O=/constructor/i.test(p.HTMLElement)||p.safari,S=/CriOS\/[\d]+/.test(navigator.userAgent);if((S||T&&O||_)&&typeof FileReader<"u"){var C=new FileReader;C.onloadend=function(){var I=C.result;I=S?I:I.replace(/^data:[^;]*;/,"data:attachment/file;"),E?E.location.href=I:location=I,E=null},C.readAsDataURL(g)}else{var w=p.URL||p.webkitURL,b=w.createObjectURL(g);E?E.location=b:location.href=b,E=null,setTimeout(function(){w.revokeObjectURL(b)},4e4)}});p.saveAs=h.saveAs=h,e.exports=h})})(rx);var mE=rx.exports;function gE(){const[e,t]=fr.useState([]),[r,o]=fr.useState([]),[a,l]=fr.useState(!1),[p,_]=fr.useState(!1),[h,g]=fr.useState(!0),[M,y]=fr.useState(null),E=fr.useRef(null),T=fr.useRef(null);fr.useEffect(()=>{(async()=>{try{if(!navigator.gpu)throw new Error("WebGPU is not supported in this browser.");const ce="Xenova/modnet";pE.backends.onnx.wasm.proxy=!1,E.current??(E.current=await cE.from_pretrained(ce,{device:"webgpu"})),T.current??(T.current=await dE.from_pretrained(ce))}catch(ce){y(ce)}g(!1)})()},[]);const O=fr.useCallback(ce=>{t(xe=>[...xe,...ce.map(Y=>URL.createObjectURL(Y))])},[]),{getRootProps:S,getInputProps:C,isDragActive:w,isDragAccept:b,isDragReject:I}=Y2({onDrop:O,accept:{"image/*":[".jpeg",".jpg",".png"]}}),U=ce=>{t(xe=>xe.filter((Y,_e)=>_e!==ce)),o(xe=>xe.filter((Y,_e)=>_e!==ce))},z=async()=>{l(!0),o([]);const ce=E.current,xe=T.current;for(let Y=0;Y[...Me,me.toDataURL("image/png")])}l(!1),_(!0)},B=async()=>{const ce=new hE,xe=e.map((_e,L)=>new Promise(Se=>{const Xe=document.createElement("canvas"),me=Xe.getContext("2d"),X=new Image;X.src=r[L]||_e,X.onload=()=>{Xe.width=X.width,Xe.height=X.height,me.drawImage(X,0,0),Xe.toBlob(ie=>{ie&&ce.file(`image-${L+1}.png`,ie),Se(null)},"image/png")}}));await Promise.all(xe);const Y=await ce.generateAsync({type:"blob"});mE.saveAs(Y,"images.zip")},j=()=>{t([]),o([]),_(!1)},N=async ce=>{try{const Y=await(await fetch(ce)).blob(),_e=new ClipboardItem({[Y.type]:Y});await navigator.clipboard.write([_e]),console.log("Image copied to clipboard")}catch(xe){console.error("Failed to copy image: ",xe)}},ae=ce=>{const xe=document.createElement("a");xe.href=ce,xe.download="image.png",document.body.appendChild(xe),xe.click(),document.body.removeChild(xe)};return M?Cr.jsx("div",{className:"min-h-screen bg-black text-white flex items-center justify-center",children:Cr.jsxs("div",{className:"text-center",children:[Cr.jsx("h2",{className:"text-4xl mb-2",children:"ERROR"}),Cr.jsx("p",{className:"text-xl max-w-[500px]",children:M.message})]})}):h?Cr.jsx("div",{className:"min-h-screen bg-black text-white flex items-center justify-center",children:Cr.jsxs("div",{className:"text-center",children:[Cr.jsx("div",{className:"inline-block animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-white mb-4"}),Cr.jsx("p",{className:"text-lg",children:"Loading background removal model..."})]})}):Cr.jsx("div",{className:"min-h-screen bg-black text-white p-8",children:Cr.jsxs("div",{className:"max-w-4xl mx-auto",children:[Cr.jsx("h1",{className:"text-4xl font-bold mb-2 text-center",children:"Remove Background WebGPU"}),Cr.jsxs("h2",{className:"text-lg font-semibold mb-2 text-center",children:["In-browser background removal, powered by"," ",Cr.jsx("a",{className:"underline",target:"_blank",href:"https://github.com/xenova/transformers.js",children:"🤗 Transformers.js"})]}),Cr.jsxs("div",{className:"flex justify-center mb-8 gap-8",children:[Cr.jsx("a",{className:"underline",target:"_blank",href:"https://github.com/huggingface/transformers.js-examples/blob/main/LICENSE",children:"License (Apache 2.0)"}),Cr.jsx("a",{className:"underline",target:"_blank",href:"https://huggingface.co/Xenova/modnet",children:"Model (MODNet)"}),Cr.jsx("a",{className:"underline",target:"_blank",href:"https://github.com/huggingface/transformers.js-examples/pull/4",children:"Code (GitHub)"})]}),Cr.jsxs("div",{...S(),className:`p-8 mb-8 border-2 border-dashed rounded-lg text-center cursor-pointer transition-colors duration-300 ease-in-out + ${b?"border-green-500 bg-green-900/20":""} + ${I?"border-red-500 bg-red-900/20":""} + ${w?"border-blue-500 bg-blue-900/20":"border-gray-700 hover:border-blue-500 hover:bg-blue-900/10"} + `,children:[Cr.jsx("input",{...C(),className:"hidden"}),Cr.jsx("p",{className:"text-lg mb-2",children:w?"Drop the images here...":"Drag and drop some images here"}),Cr.jsx("p",{className:"text-sm text-gray-400",children:"or click to select files"})]}),Cr.jsxs("div",{className:"flex flex-col items-center gap-4 mb-8",children:[Cr.jsx("button",{onClick:z,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"}),Cr.jsxs("div",{className:"flex gap-4",children:[Cr.jsx("button",{onClick:B,disabled:!p,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"}),Cr.jsx("button",{onClick:j,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"})]})]}),Cr.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6",children:e.map((ce,xe)=>Cr.jsxs("div",{className:"relative group",children:[Cr.jsx("img",{src:r[xe]||ce,alt:`Image ${xe+1}`,className:"rounded-lg object-cover w-full h-48"}),r[xe]&&Cr.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:[Cr.jsx("button",{onClick:()=>N(r[xe]||ce),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 ${xe+1} to clipboard`,children:"Copy"}),Cr.jsx("button",{onClick:()=>ae(r[xe]||ce),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 ${xe+1}`,children:"Download"})]}),Cr.jsx("button",{onClick:()=>U(xe),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 ${xe+1}`,children:"✕"})]},xe))})]})})}L2(document.getElementById("root")).render(Cr.jsx(fr.StrictMode,{children:Cr.jsx(gE,{})}));