diff --git "a/assets/index-DMZXZig0.js" "b/assets/index-DMZXZig0.js" new file mode 100644--- /dev/null +++ "b/assets/index-DMZXZig0.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 f of l.addedNodes)f.tagName==="LINK"&&f.rel==="modulepreload"&&o(f)}).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:{}},Mr={};/** + * @license React + * react.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var Yf=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,f=null;if(t!=null)for(o in t.ref!==void 0&&(f=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 p=Array(_),g=0;g<_;g++)p[g]=arguments[g+2];a.children=p}if(e&&e.defaultProps)for(o in _=e.defaultProps,_)a[o]===void 0&&(a[o]=_[o]);return{$$typeof:Yf,type:e,key:l,ref:f,props:a,_owner:C_.current}}function XM(e,t){return{$$typeof:Yf,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===Yf}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 ph(e,t,r,o,a){var l=typeof e;(l==="undefined"||l==="boolean")&&(e=null);var f=!1;if(e===null)f=!0;else switch(l){case"string":case"number":f=!0;break;case"object":switch(e.$$typeof){case Yf:case RM:f=!0}}if(f)return f=e,a=a(f),e=o===""?"."+tg(f,0):o,nv(a)?(r="",e!=null&&(r=e.replace(iv,"$&/")+"/"),ph(a,t,r,"",function(g){return g})):a!=null&&(P_(a)&&(a=XM(a,r+(!a.key||f&&f.key===a.key?"":(""+a.key).replace(iv,"$&/")+"/")+e)),t.push(a)),1;if(f=0,o=o===""?".":o+":",nv(e))for(var _=0;_>>1,me=X[Q];if(0>>1;Qa(Be,Se))Wea(st,Be)?(X[Q]=st,X[We]=Se,Q=We):(X[Q]=Be,X[Le]=Se,Q=Le);else if(Wea(st,Se))X[Q]=st,X[We]=Se,Q=We;else break e}}return ae}function a(X,ae){var Se=X.sortIndex-ae.sortIndex;return Se!==0?Se:X.id-ae.id}if(typeof performance=="object"&&typeof performance.now=="function"){var l=performance;e.unstable_now=function(){return l.now()}}else{var f=Date,_=f.now();e.unstable_now=function(){return f.now()-_}}var p=[],g=[],M=1,w=null,C=3,T=!1,z=!1,S=!1,E=typeof setTimeout=="function"?setTimeout:null,y=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 ae=r(g);ae!==null;){if(ae.callback===null)o(g);else if(ae.startTime<=X)o(g),ae.sortIndex=ae.expirationTime,t(p,ae);else break;ae=r(g)}}function V(X){if(S=!1,I(X),!z)if(r(p)!==null)z=!0,Xe(O);else{var ae=r(g);ae!==null&&ge(V,ae.startTime-X)}}function O(X,ae){z=!1,S&&(S=!1,y(D),D=-1),T=!0;var Se=C;try{for(I(ae),w=r(p);w!==null&&(!(w.expirationTime>ae)||X&&!Ce());){var Q=w.callback;if(typeof Q=="function"){w.callback=null,C=w.priorityLevel;var me=Q(w.expirationTime<=ae);ae=e.unstable_now(),typeof me=="function"?w.callback=me:w===r(p)&&o(p),I(ae)}else o(p);w=r(p)}if(w!==null)var Ke=!0;else{var Le=r(g);Le!==null&&ge(V,Le.startTime-ae),Ke=!1}return Ke}finally{w=null,C=Se,T=!1}}var N=!1,j=null,D=-1,ee=5,de=-1;function Ce(){return!(e.unstable_now()-deX||125Q?(X.sortIndex=Se,t(g,X),r(p)===null&&X===r(g)&&(S?(y(D),D=-1):S=!0,ge(V,Se-Q))):(X.sortIndex=me,t(p,X),z||T||(z=!0,Xe(O))),X},e.unstable_shouldYield=Ce,e.unstable_wrapCallback=function(X){var ae=C;return function(){var Se=C;C=ae;try{return X.apply(this,arguments)}finally{C=Se}}}})(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=pr,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,f){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=f}var Bn={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){Bn[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];Bn[t]=new ni(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){Bn[e]=new ni(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){Bn[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){Bn[e]=new ni(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){Bn[e]=new ni(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){Bn[e]=new ni(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){Bn[e]=new ni(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){Bn[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_);Bn[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_);Bn[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_);Bn[t]=new ni(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){Bn[e]=new ni(e,1,!1,e.toLowerCase(),null,!1,!1)});Bn.xlinkHref=new ni("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){Bn[e]=new ni(e,1,!1,e.toLowerCase(),null,!0,!0)});function I_(e,t,r,o){var a=Bn.hasOwnProperty(t)?Bn[t]:null;(a!==null?a.type!==0:o||!(2_||a[f]!==l[_]){var p=` +`+a[f].replace(" at new "," at ");return e.displayName&&p.includes("")&&(p=p.replace("",e.displayName)),p}while(1<=f&&0<=_);break}}}finally{ng=!1,Error.prepareStackTrace=r}return(e=e?e.displayName||e.name:"")?yf(e):""}function fT(e){switch(e.tag){case 5:return yf(e.type);case 16:return yf("Lazy");case 13:return yf("Suspense");case 19:return yf("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 Ol:return"Fragment";case zl: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 z_:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case O_: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 pT(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(f){o=""+f,l.call(this,f)}}),Object.defineProperty(e,t,{enumerable:r.enumerable}),{getValue:function(){return o},setValue:function(f){o=""+f},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function Qp(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 zg(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")?Og(e,t.type,r):t.hasOwnProperty("defaultValue")&&Og(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 Og(e,t,r){(t!=="number"||Sh(e.ownerDocument)!==e)&&(r==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+r&&(e.defaultValue=""+r))}var vf=Array.isArray;function Hl(e,t,r,o){if(e=e.options,t){t={};for(var a=0;a"+t.valueOf().toString()+"",t=Yp.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function zf(e,t){if(t){var r=e.firstChild;if(r&&r===e.lastChild&&r.nodeType===3){r.nodeValue=t;return}}e.textContent=t}var Tf={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(Tf).forEach(function(e){mT.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),Tf[t]=Tf[e]})});function X1(e,t,r){return t==null||typeof t=="boolean"||t===""?"":r||typeof t!="number"||t===0||Tf.hasOwnProperty(e)&&Tf[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 fv(e){if(e=ep(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,fv(e),t)for(e=0;e>>=0,e===0?32:31-(ET(e)/CT|0)|0}var Zp=64,Jp=4194304;function bf(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,f=r&268435455;if(f!==0){var _=f&~a;_!==0?o=bf(_):(l&=f,l!==0&&(o=bf(l)))}else f=r&~a,f!==0?o=bf(f):l!==0&&(o=bf(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 Zf(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=Sf),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_=ps=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 f=Ev(r,o);a&&f&&(e.rangeCount!==1||e.anchorNode!==a.node||e.anchorOffset!==a.offset||e.focusNode!==f.node||e.focusOffset!==f.offset)&&(t=t.createRange(),t.setStart(a.node,a.offset),e.removeAllRanges(),l>o?(e.addRange(t),e.extend(f.node,f.offset)):(t.setEnd(f.node,f.offset),e.addRange(t)))}}for(t=[],e=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,Cf=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}),Cf&&Nf(Cf,o)||(Cf=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 Oh(){tn(ui),tn(qn)}function Ov(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,pT(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 zb(e){Eo===null?Eo=[e]:Eo.push(e)}function $k(e){om=!0,zb(e)}function Es(){if(!wg&&Eo!==null){wg=!0;var e=0,t=jr;try{var r=Eo;for(jr=1;e>=f,a-=f,Po=1<<32-Qi(t)+a|r<D?(ee=j,j=null):ee=j.sibling;var de=C(y,j,I[D],V);if(de===null){j===null&&(j=ee);break}e&&j&&de.alternate===null&&t(y,j),b=l(de,b,D),N===null?O=de:N.sibling=de,N=de,j=ee}if(D===I.length)return r(y,j),nn&&ea(y,D),O;if(j===null){for(;DD?(ee=j,j=null):ee=j.sibling;var Ce=C(y,j,de.value,V);if(Ce===null){j===null&&(j=ee);break}e&&j&&Ce.alternate===null&&t(y,j),b=l(Ce,b,D),N===null?O=Ce:N.sibling=Ce,N=Ce,j=ee}if(de.done)return r(y,j),nn&&ea(y,D),O;if(j===null){for(;!de.done;D++,de=I.next())de=w(y,de.value,V),de!==null&&(b=l(de,b,D),N===null?O=de:N.sibling=de,N=de);return nn&&ea(y,D),O}for(j=o(y,j);!de.done;D++,de=I.next())de=T(j,y,D,de.value,V),de!==null&&(e&&de.alternate!==null&&j.delete(de.key===null?D:de.key),b=l(de,b,D),N===null?O=de:N.sibling=de,N=de);return e&&j.forEach(function(te){return t(y,te)}),nn&&ea(y,D),O}function E(y,b,I,V){if(typeof I=="object"&&I!==null&&I.type===Ol&&I.key===null&&(I=I.props.children),typeof I=="object"&&I!==null){switch(I.$$typeof){case Xp:e:{for(var O=I.key,N=b;N!==null;){if(N.key===O){if(O=I.type,O===Ol){if(N.tag===7){r(y,N.sibling),b=a(N,I.props.children),b.return=y,y=b;break e}}else if(N.elementType===O||typeof O=="object"&&O!==null&&O.$$typeof===us&&Bv(O)===N.type){r(y,N.sibling),b=a(N,I.props),b.ref=gf(y,N,I),b.return=y,y=b;break e}r(y,N);break}else t(y,N);N=N.sibling}I.type===Ol?(b=aa(I.props.children,y.mode,V,I.key),b.return=y,y=b):(V=Th(I.type,I.key,I.props,null,y.mode,V),V.ref=gf(y,b,I),V.return=y,y=V)}return f(y);case zl:e:{for(N=I.key;b!==null;){if(b.key===N)if(b.tag===4&&b.stateNode.containerInfo===I.containerInfo&&b.stateNode.implementation===I.implementation){r(y,b.sibling),b=a(b,I.children||[]),b.return=y,y=b;break e}else{r(y,b);break}else t(y,b);b=b.sibling}b=Sg(I,y.mode,V),b.return=y,y=b}return f(y);case us:return N=I._init,E(y,b,N(I._payload),V)}if(vf(I))return z(y,b,I,V);if(df(I))return S(y,b,I,V);sh(y,I)}return typeof I=="string"&&I!==""||typeof I=="number"?(I=""+I,b!==null&&b.tag===6?(r(y,b.sibling),b=a(b,I),b.return=y,y=b):(r(y,b),b=kg(I,y.mode,V),b.return=y,y=b),f(y)):r(y,b)}return E}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,zo(e,o)}function zo(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,zo(e,r)}return a=o.interleaved,a===null?(t.next=t,Z_(o)):(t.next=a.next,a.next=t),o.interleaved=t,zo(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 f={eventTime:r.eventTime,lane:r.lane,tag:r.tag,payload:r.payload,callback:r.callback,next:null};l===null?a=l=f:l=l.next=f,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,f=a.lastBaseUpdate,_=a.shared.pending;if(_!==null){a.shared.pending=null;var p=_,g=p.next;p.next=null,f===null?l=g:f.next=g,f=p;var M=e.alternate;M!==null&&(M=M.updateQueue,_=M.lastBaseUpdate,_!==f&&(_===null?M.firstBaseUpdate=g:_.next=g,M.lastBaseUpdate=p))}if(l!==null){var w=a.baseState;f=0,M=g=p=null,_=l;do{var C=_.lane,T=_.eventTime;if((o&C)===C){M!==null&&(M=M.next={eventTime:T,lane:0,tag:_.tag,payload:_.payload,callback:_.callback,next:null});e:{var z=e,S=_;switch(C=t,T=r,S.tag){case 1:if(z=S.payload,typeof z=="function"){w=z.call(T,w,C);break e}w=z;break e;case 3:z.flags=z.flags&-65537|128;case 0:if(z=S.payload,C=typeof z=="function"?z.call(T,w,C):z,C==null)break e;w=ln({},w,C);break e;case 2:cs=!0}}_.callback!==null&&_.lane!==0&&(e.flags|=64,C=a.effects,C===null?a.effects=[_]:C.push(_))}else T={eventTime:T,lane:C,tag:_.tag,payload:_.payload,callback:_.callback,next:null},M===null?(g=M=T,p=w):M=M.next=T,f|=C;if(_=_.next,_===null){if(_=a.shared.pending,_===null)break;C=_,_=C.next,C.next=null,a.lastBaseUpdate=C,a.shared.pending=null}}while(!0);if(M===null&&(p=w),a.baseState=p,a.firstBaseUpdate=g,a.lastBaseUpdate=M,t=a.shared.interleaved,t!==null){a=t;do f|=a.lane,a=a.next;while(a!==t)}else l===null&&(a.shared.lanes=0);da|=f,e.lanes=f,e.memoizedState=w}}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{jr=r,vg.transition=o}}function i2(){return Ri().memoizedState}function zk(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 Ok(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 f=t.lastRenderedState,_=l(f,r);if(a.hasEagerState=!0,a.eagerState=_,Zi(_,f)){var p=t.interleaved;p===null?(a.next=a,Z_(t)):(a.next=p.next,p.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){Pf=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=zk.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(),In===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,Kf(9,Hb.bind(null,o,l,r,t),void 0,null),r},useId:function(){var e=lo(),t=In.identifierPrefix;if(nn){var r=$o,o=Po;r=(o&~(1<<32-Qi(o)-1)).toString(32)+r,t=":"+t+"R"+r,r=Hf++,0<\/script>",e=e.removeChild(e.firstChild)):typeof o.is=="string"?e=f.createElement(r,{is:o.is}):(e=f.createElement(r),r==="select"&&(f=e,o.multiple?f.multiple=!0:o.size&&(f.size=o.size))):e=f.createElementNS(e,r),e[uo]=t,e[Vf]=o,_2(e,t,!1,!1),t.stateNode=e;e:{switch(f=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,_f(l,!1),t.lanes=4194304)}else{if(!o)if(e=Uh(f),e!==null){if(t.flags|=128,o=!0,r=e.updateQueue,r!==null&&(t.updateQueue=r,t.flags|=4),_f(l,!0),l.tail===null&&l.tailMode==="hidden"&&!f.alternate&&!nn)return Gn(t),null}else 2*mn()-l.renderingStartTime>iu&&r!==1073741824&&(t.flags|=128,o=!0,_f(l,!1),t.lanes=4194304);l.isBackwards?(f.sibling=t.child,t.child=f):(r=l.last,r!==null?r.sibling=f:t.child=f,l.last=f)}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 p0(),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)&&Oh(),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 p0(),null;case 24:return null;default:return null}}var lh=!1,Hn=!1,Gk=typeof WeakSet=="function"?WeakSet:Set,Ut=null;function Wl(e,t){var r=e.ref;if(r!==null)if(typeof r=="function")try{r(null)}catch(o){pn(e,t,o)}else r.current=null}function f_(e,t,r){try{r()}catch(o){pn(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 f=0,_=-1,p=-1,g=0,M=0,w=e,C=null;t:for(;;){for(var T;w!==r||a!==0&&w.nodeType!==3||(_=f+a),w!==l||o!==0&&w.nodeType!==3||(p=f+o),w.nodeType===3&&(f+=w.nodeValue.length),(T=w.firstChild)!==null;)C=w,w=T;for(;;){if(w===e)break t;if(C===r&&++g===a&&(_=f),C===l&&++M===o&&(p=f),(T=w.nextSibling)!==null)break;w=C,C=w.parentNode}w=T}r=_===-1||p===-1?null:{start:_,end:p}}else r=null}r=r||{start:0,end:0}}else r=null;for(Qg={focusedElem:e,selectionRange:r},Ah=!1,Ut=t;Ut!==null;)if(t=Ut,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,Ut=e;else for(;Ut!==null;){t=Ut;try{var z=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(z!==null){var S=z.memoizedProps,E=z.memoizedState,y=t.stateNode,b=y.getSnapshotBeforeUpdate(t.elementType===t.type?S:qi(t.type,S),E);y.__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(V){pn(t,t.return,V)}if(e=t.sibling,e!==null){e.return=t.return,Ut=e;break}Ut=t.return}return z=e1,e1=!1,z}function $f(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&&f_(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 p_(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[Vf],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=zh));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 Ln=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=Ln,a=Ki;Ln=null,ls(e,t,r),Ln=o,Ki=a,Ln!==null&&(Ki?(e=Ln,r=r.stateNode,e.nodeType===8?e.parentNode.removeChild(r):e.removeChild(r)):Ln.removeChild(r.stateNode));break;case 18:Ln!==null&&(Ki?(e=Ln,r=r.stateNode,e.nodeType===8?_g(e.parentNode,r):e.nodeType===1&&_g(e,r),Rf(e)):_g(Ln,r.stateNode));break;case 4:o=Ln,a=Ki,Ln=r.stateNode.containerInfo,Ki=!0,ls(e,t,r),Ln=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,f=l.destroy;l=l.tag,f!==void 0&&(l&2||l&4)&&f_(r,t,f),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(_){pn(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=f),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,Ut=e.current;Ut!==null;){var l=Ut,f=l.child;if(Ut.flags&16){var _=l.deletions;if(_!==null){for(var p=0;p<_.length;p++){var g=_[p];for(Ut=g;Ut!==null;){var M=Ut;switch(M.tag){case 0:case 11:case 15:$f(8,M,l)}var w=M.child;if(w!==null)w.return=M,Ut=w;else for(;Ut!==null;){M=Ut;var C=M.sibling,T=M.return;if(v2(M),M===g){Ut=null;break}if(C!==null){C.return=T,Ut=C;break}Ut=T}}}var z=l.alternate;if(z!==null){var S=z.child;if(S!==null){z.child=null;do{var E=S.sibling;S.sibling=null,S=E}while(S!==null)}}Ut=l}}if(l.subtreeFlags&2064&&f!==null)f.return=l,Ut=f;else e:for(;Ut!==null;){if(l=Ut,l.flags&2048)switch(l.tag){case 0:case 11:case 15:$f(9,l,l.return)}var y=l.sibling;if(y!==null){y.return=l.return,Ut=y;break e}Ut=l.return}}var b=e.current;for(Ut=b;Ut!==null;){f=Ut;var I=f.child;if(f.subtreeFlags&2064&&I!==null)I.return=f,Ut=I;else e:for(f=b;Ut!==null;){if(_=Ut,_.flags&2048)try{switch(_.tag){case 0:case 11:case 15:lm(9,_)}}catch(O){pn(_,_.return,O)}if(_===f){Ut=null;break e}var V=_.sibling;if(V!==null){V.return=_.return,Ut=V;break e}Ut=_.return}}if(zr=a,Es(),co&&typeof co.onPostCommitFiberRoot=="function")try{co.onPostCommitFiberRoot(em,e)}catch{}o=!0}return o}finally{jr=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&&(Zf(e,1,t),di(e,t))}function pn(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&&(Zf(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,In===e&&(Rn&r)===r&&(En===4||En===3&&(Rn&130023424)===Rn&&500>mn()-d0?sa(e,0):c0|=r),di(e,t)}function $2(e,t){t===0&&(e.mode&1?(t=Jp,Jp<<=1,!(Jp&130023424)&&(Jp=4194304)):t=1);var r=ti();e=zo(e,t),e!==null&&(Zf(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&&Ob(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 f=t.memoizedState;if(o=f.element,l.isDehydrated)if(l={element:o,isDehydrated:!1,cache:f.cache,pendingSuspenseBoundaries:f.pendingSuspenseBoundaries,transitions:f.transitions},t.updateQueue.baseState=l,t.memoizedState=l,t.flags&256){a=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=Oo(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,f=a.children,Yg(o,a)?f=null:l!==null&&Yg(o,l)&&(t.flags|=32),p2(e,t),ei(e,t,f,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,f=a.value,Qr(Bh,o._currentValue),o._currentValue=f,l!==null)if(Zi(l.value,f)){if(l.children===a.children&&!ui.current){t=Oo(e,t,r);break e}}else for(l=t.child,l!==null&&(l.return=t);l!==null;){var _=l.dependencies;if(_!==null){f=l.child;for(var p=_.firstContext;p!==null;){if(p.context===o){if(l.tag===1){p=Ao(-1,r&-r),p.tag=2;var g=l.updateQueue;if(g!==null){g=g.shared;var M=g.pending;M===null?p.next=p:(p.next=M.next,M.next=p),g.pending=p}}l.lanes|=r,p=l.alternate,p!==null&&(p.lanes|=r),n_(l.return,r,t),_.lanes|=r;break}p=p.next}}else if(l.tag===10)f=l.type===t.type?null:l.child;else if(l.tag===18){if(f=l.return,f===null)throw Error(xt(341));f.lanes|=r,_=f.alternate,_!==null&&(_.lanes|=r),n_(f,r,t),f=l.sibling}else f=l.child;if(f!==null)f.return=l;else for(f=l;f!==null;){if(f===t){f=null;break}if(l=f.sibling,l!==null){l.return=f.return,f=l;break}f=f.return}l=f}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 f2(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 Oi(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===z_)return 11;if(e===O_)return 14}return 2}function xs(e,t){var r=e.alternate;return r===null?(r=Oi(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 f=2;if(o=e,typeof e=="function")m0(e)&&(f=1);else if(typeof e=="string")f=5;else e:switch(e){case Ol:return aa(r.children,a,l,t);case F_:f=8,a|=8;break;case Pg:return e=Oi(12,r,t,a|2),e.elementType=Pg,e.lanes=l,e;case $g:return e=Oi(13,r,t,a),e.elementType=$g,e.lanes=l,e;case Ag:return e=Oi(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:f=10;break e;case j1:f=9;break e;case z_:f=11;break e;case O_:f=14;break e;case us:f=16,o=null;break e}throw Error(xt(130,e==null?e:typeof e,""))}return t=Oi(f,r,t,a),t.elementType=e,t.type=o,t.lanes=l,t}function aa(e,t,r,o){return e=Oi(7,e,o,t),e.lanes=r,e}function cm(e,t,r,o){return e=Oi(22,e,o,t),e.elementType=U1,e.lanes=r,e.stateNode={isHidden:!1},e}function kg(e,t,r){return e=Oi(6,e,null,t),e.lanes=r,e}function Sg(e,t,r){return t=Oi(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,f,_,p){return e=new iS(e,t,r,_,p),t===1?(t=1,l===!0&&(t|=8)):t=0,l=Oi(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",fS=dS,pS=fS;function B2(){}function N2(){}N2.resetWarningCache=B2;var hS=function(){function e(o,a,l,f,_,p){if(p!==pS){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 Hr=k_(mS);function lu(e,t,r,o){function a(l){return l instanceof r?l:new r(function(f){f(l)})}return new(r||(r=Promise))(function(l,f){function _(M){try{g(o.next(M))}catch(w){f(w)}}function p(M){try{g(o.throw(M))}catch(w){f(w)}}function g(M){M.done?l(M.value):a(M.value).then(_,p)}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,f=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return f.next=_(0),f.throw=_(1),f.return=_(2),typeof Symbol=="function"&&(f[Symbol.iterator]=function(){return this}),f;function _(g){return function(M){return p([g,M])}}function p(g){if(o)throw new TypeError("Generator is already executing.");for(;f&&(f=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(_){f={error:_}}finally{try{a&&!a.done&&(r=o.return)&&r.call(o)}finally{if(f)throw f.error}}return l}function f1(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 rp(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 rp(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,p1(j2(o))];case 2:return[2,p1(v_(e.files).map(function(l){return rp(l)}))]}})})}function p1(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,f=e.maxFiles,_=e.validator;return!l&&t.length>1||l&&f>=1&&t.length>f?!1:t.every(function(p){var g=G2(p,r),M=Qf(g,1),w=M[0],C=H2(p,o,a),T=Qf(C,1),z=T[0],S=_?_(p):null;return w&&z&&!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),f=1;fe.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=pr.forwardRef(function(e,t){var r=e.children,o=Zh(e,QS),a=Y2(o),l=a.open,f=Zh(a,YS);return pr.useImperativeHandle(t,function(){return{open:l}},[l]),JM.createElement(pr.Fragment,null,r(on(on({},f),{},{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:Hr.func,accept:Hr.objectOf(Hr.arrayOf(Hr.string)),multiple:Hr.bool,preventDropOnDocument:Hr.bool,noClick:Hr.bool,noKeyboard:Hr.bool,noDrag:Hr.bool,noDragEventsBubbling:Hr.bool,minSize:Hr.number,maxSize:Hr.number,maxFiles:Hr.number,disabled:Hr.bool,getFilesFromEvent:Hr.func,onFileDialogCancel:Hr.func,onFileDialogOpen:Hr.func,useFsAccessApi:Hr.bool,autoFocus:Hr.bool,onDragEnter:Hr.func,onDragLeave:Hr.func,onDragOver:Hr.func,onDrop:Hr.func,onDropAccepted:Hr.func,onDropRejected:Hr.func,onError:Hr.func,validator:Hr.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,f=t.minSize,_=t.multiple,p=t.maxFiles,g=t.onDragEnter,M=t.onDragLeave,w=t.onDragOver,C=t.onDrop,T=t.onDropAccepted,z=t.onDropRejected,S=t.onFileDialogCancel,E=t.onFileDialogOpen,y=t.useFsAccessApi,b=t.autoFocus,I=t.preventDropOnDocument,V=t.noClick,O=t.noKeyboard,N=t.noDrag,j=t.noDragEventsBubbling,D=t.onError,ee=t.validator,de=pr.useMemo(function(){return qS(r)},[r]),Ce=pr.useMemo(function(){return HS(r)},[r]),te=pr.useMemo(function(){return typeof E=="function"?E:x1},[E]),_e=pr.useMemo(function(){return typeof S=="function"?S:x1},[S]),R=pr.useRef(null),xe=pr.useRef(null),Xe=pr.useReducer(lE,T_),ge=Eg(Xe,2),X=ge[0],ae=ge[1],Se=X.isFocused,Q=X.isFileDialogActive,me=pr.useRef(typeof window<"u"&&window.isSecureContext&&y&&GS()),Ke=function(){!me.current&&Q&&setTimeout(function(){if(xe.current){var Te=xe.current.files;Te.length||(ae({type:"closeDialog"}),_e())}},300)};pr.useEffect(function(){return window.addEventListener("focus",Ke,!1),function(){window.removeEventListener("focus",Ke,!1)}},[xe,Q,_e,me]);var Le=pr.useRef([]),Be=function(Te){R.current&&R.current.contains(Te.target)||(Te.preventDefault(),Le.current=[])};pr.useEffect(function(){return I&&(document.addEventListener("dragover",v1,!1),document.addEventListener("drop",Be,!1)),function(){I&&(document.removeEventListener("dragover",v1),document.removeEventListener("drop",Be))}},[R,I]),pr.useEffect(function(){return!o&&b&&R.current&&R.current.focus(),function(){}},[R,b,o]);var We=pr.useCallback(function(le){D?D(le):console.error(le)},[D]),st=pr.useCallback(function(le){le.preventDefault(),le.persist(),B(le),Le.current=[].concat(eE(Le.current),[le.target]),dh(le)&&Promise.resolve(a(le)).then(function(Te){if(!(Yh(le)&&!j)){var Ne=Te.length,dt=Ne>0&&jS({files:Te,accept:de,minSize:f,maxSize:l,multiple:_,maxFiles:p,validator:ee}),Je=Ne>0&&!dt;ae({isDragAccept:dt,isDragReject:Je,isDragActive:!0,type:"setDraggedFiles"}),g&&g(le)}}).catch(function(Te){return We(Te)})},[a,g,We,j,de,f,l,_,p,ee]),ft=pr.useCallback(function(le){le.preventDefault(),le.persist(),B(le);var Te=dh(le);if(Te&&le.dataTransfer)try{le.dataTransfer.dropEffect="copy"}catch{}return Te&&w&&w(le),!1},[w,j]),Ge=pr.useCallback(function(le){le.preventDefault(),le.persist(),B(le);var Te=Le.current.filter(function(dt){return R.current&&R.current.contains(dt)}),Ne=Te.indexOf(le.target);Ne!==-1&&Te.splice(Ne,1),Le.current=Te,!(Te.length>0)&&(ae({type:"setDraggedFiles",isDragActive:!1,isDragAccept:!1,isDragReject:!1}),dh(le)&&M&&M(le))},[R,M,j]),Me=pr.useCallback(function(le,Te){var Ne=[],dt=[];le.forEach(function(Je){var Ve=G2(Je,de),Y=Eg(Ve,2),ve=Y[0],Re=Y[1],qe=H2(Je,f,l),Qe=Eg(qe,2),tt=Qe[0],pt=Qe[1],ht=ee?ee(Je):null;if(ve&&tt&&!ht)Ne.push(Je);else{var Tt=[Re,pt];ht&&(Tt=Tt.concat(ht)),dt.push({file:Je,errors:Tt.filter(function(vt){return vt})})}}),(!_&&Ne.length>1||_&&p>=1&&Ne.length>p)&&(Ne.forEach(function(Je){dt.push({file:Je,errors:[NS]})}),Ne.splice(0)),ae({acceptedFiles:Ne,fileRejections:dt,type:"setFiles"}),C&&C(Ne,dt,Te),dt.length>0&&z&&z(dt,Te),Ne.length>0&&T&&T(Ne,Te)},[ae,_,de,f,l,p,C,T,z,ee]),je=pr.useCallback(function(le){le.preventDefault(),le.persist(),B(le),Le.current=[],dh(le)&&Promise.resolve(a(le)).then(function(Te){Yh(le)&&!j||Me(Te,le)}).catch(function(Te){return We(Te)}),ae({type:"reset"})},[a,Me,We,j]),Ye=pr.useCallback(function(){if(me.current){ae({type:"openDialog"}),te();var le={multiple:_,types:Ce};window.showOpenFilePicker(le).then(function(Te){return a(Te)}).then(function(Te){Me(Te,null),ae({type:"closeDialog"})}).catch(function(Te){KS(Te)?(_e(Te),ae({type:"closeDialog"})):XS(Te)?(me.current=!1,xe.current?(xe.current.value=null,xe.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(Te)});return}xe.current&&(ae({type:"openDialog"}),te(),xe.current.value=null,xe.current.click())},[ae,te,_e,y,Me,We,Ce,_]),et=pr.useCallback(function(le){!R.current||!R.current.isEqualNode(le.target)||(le.key===" "||le.key==="Enter"||le.keyCode===32||le.keyCode===13)&&(le.preventDefault(),Ye())},[R,Ye]),A=pr.useCallback(function(){ae({type:"focus"})},[]),$e=pr.useCallback(function(){ae({type:"blur"})},[]),Pe=pr.useCallback(function(){V||(WS()?setTimeout(Ye,0):Ye())},[V,Ye]),se=function(Te){return o?null:Te},ne=function(Te){return O?null:se(Te)},ye=function(Te){return N?null:se(Te)},B=function(Te){j&&Te.stopPropagation()},J=pr.useMemo(function(){return function(){var le=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},Te=le.refKey,Ne=Te===void 0?"ref":Te,dt=le.role,Je=le.onKeyDown,Ve=le.onFocus,Y=le.onBlur,ve=le.onClick,Re=le.onDragEnter,qe=le.onDragOver,Qe=le.onDragLeave,tt=le.onDrop,pt=Zh(le,ZS);return on(on(M_({onKeyDown:ne(ao(Je,et)),onFocus:ne(ao(Ve,A)),onBlur:ne(ao(Y,$e)),onClick:se(ao(ve,Pe)),onDragEnter:ye(ao(Re,st)),onDragOver:ye(ao(qe,ft)),onDragLeave:ye(ao(Qe,Ge)),onDrop:ye(ao(tt,je)),role:typeof dt=="string"&&dt!==""?dt:"presentation"},Ne,R),!o&&!O?{tabIndex:0}:{}),pt)}},[R,et,A,$e,Pe,st,ft,Ge,je,O,N,o]),L=pr.useCallback(function(le){le.stopPropagation()},[]),ue=pr.useMemo(function(){return function(){var le=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},Te=le.refKey,Ne=Te===void 0?"ref":Te,dt=le.onChange,Je=le.onClick,Ve=Zh(le,JS),Y=M_({accept:de,multiple:_,type:"file",style:{display:"none"},onChange:se(ao(dt,je)),onClick:se(ao(Je,L)),tabIndex:-1},Ne,xe);return on(on({},Y),Ve)}},[xe,r,_,je,o]);return on(on({},X),{},{isFocused:Se&&!o,getRootProps:J,getInputProps:ue,rootRef:R,inputRef:xe,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:()=>Se,tokenize:()=>w});var o=Object.freeze({Text:"Text",NumericLiteral:"NumericLiteral",BooleanLiteral:"BooleanLiteral",StringLiteral:"StringLiteral",Identifier:"Identifier",Equals:"Equals",OpenParen:"OpenParen",CloseParen:"CloseParen",OpenStatement:"OpenStatement",CloseStatement:"CloseStatement",OpenExpression:"OpenExpression",CloseExpression:"CloseExpression",OpenSquareBracket:"OpenSquareBracket",CloseSquareBracket:"CloseSquareBracket",OpenCurlyBracket:"OpenCurlyBracket",CloseCurlyBracket:"CloseCurlyBracket",Comma:"Comma",Dot:"Dot",Colon:"Colon",Pipe:"Pipe",CallOperator:"CallOperator",AdditiveBinaryOperator:"AdditiveBinaryOperator",MultiplicativeBinaryOperator:"MultiplicativeBinaryOperator",ComparisonBinaryOperator:"ComparisonBinaryOperator",UnaryOperator:"UnaryOperator",Set:"Set",If:"If",For:"For",In:"In",Is:"Is",NotIn:"NotIn",Else:"Else",EndIf:"EndIf",ElseIf:"ElseIf",EndFor:"EndFor",And:"And",Or:"Or",Not:"UnaryOperator",Macro:"Macro",EndMacro:"EndMacro"}),a=Object.freeze({set:o.Set,for:o.For,in:o.In,is:o.Is,if:o.If,else:o.Else,endif:o.EndIf,elif:o.ElseIf,endfor:o.EndFor,and:o.And,or:o.Or,not:o.Not,"not in":o.NotIn,macro:o.Macro,endmacro:o.EndMacro,true:o.BooleanLiteral,false:o.BooleanLiteral,True:o.BooleanLiteral,False:o.BooleanLiteral}),l=class{constructor(B,J){this.value=B,this.type=J}};function f(B){return/\w/.test(B)}function _(B){return/[0-9]/.test(B)}var p=[["{%",o.OpenStatement],["%}",o.CloseStatement],["{{",o.OpenExpression],["}}",o.CloseExpression],["(",o.OpenParen],[")",o.CloseParen],["{",o.OpenCurlyBracket],["}",o.CloseCurlyBracket],["[",o.OpenSquareBracket],["]",o.CloseSquareBracket],[",",o.Comma],[".",o.Dot],[":",o.Colon],["|",o.Pipe],["<=",o.ComparisonBinaryOperator],[">=",o.ComparisonBinaryOperator],["==",o.ComparisonBinaryOperator],["!=",o.ComparisonBinaryOperator],["<",o.ComparisonBinaryOperator],[">",o.ComparisonBinaryOperator],["+",o.AdditiveBinaryOperator],["-",o.AdditiveBinaryOperator],["*",o.MultiplicativeBinaryOperator],["/",o.MultiplicativeBinaryOperator],["%",o.MultiplicativeBinaryOperator],["=",o.Equals]],g=new Map([["n",` +`],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function M(B,J={}){return B.endsWith(` +`)&&(B=B.slice(0,-1)),B=B.replace(/{#.*?#}/gs,"{##}"),J.lstrip_blocks&&(B=B.replace(/^[ \t]*({[#%])/gm,"$1")),J.trim_blocks&&(B=B.replace(/([#%]})\n/g,"$1")),B.replace(/{##}/g,"").replace(/-%}\s*/g,"%}").replace(/\s*{%-/g,"{%").replace(/-}}\s*/g,"}}").replace(/\s*{{-/g,"{{")}function w(B,J={}){var Ne,dt,Je;const L=[],ue=M(B,J);let le=0;const Te=Ve=>{let Y="";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}`);Y+=Re;continue}if(Y+=ue[le++],le>=ue.length)throw new SyntaxError("Unexpected end of input")}return Y};e:for(;le0){L.push(new l(ve,o.Text));continue}}Te(ve=>/\s/.test(ve));const Y=ue[le];if(Y==="-"||Y==="+"){const ve=(dt=L.at(-1))==null?void 0:dt.type;if(ve===o.Text||ve===void 0)throw new SyntaxError(`Unexpected character: ${Y}`);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=Te(_);L.push(new l(`${Y}${Re}`,Re.length>0?o.NumericLiteral:o.UnaryOperator));continue}}}for(const[ve,Re]of p)if(ue.slice(le,le+ve.length)===ve){L.push(new l(ve,Re)),le+=ve.length;continue e}if(Y==="'"||Y==='"'){++le;const ve=Te(Re=>Re!==Y);L.push(new l(ve,o.StringLiteral)),++le;continue}if(_(Y)){const ve=Te(_);L.push(new l(ve,o.NumericLiteral));continue}if(f(Y)){const ve=Te(f),Re=Object.hasOwn(a,ve)?a[ve]:o.Identifier;Re===o.In&&((Je=L.at(-1))==null?void 0:Je.type)===o.Not?(L.pop(),L.push(new l("not in",o.NotIn))):L.push(new l(ve,Re));continue}throw new SyntaxError(`Unexpected character: ${Y}`)}return L}var C=class{constructor(){He(this,"type","Statement")}},T=class extends C{constructor(J){super();He(this,"type","Program");this.body=J}},z=class extends C{constructor(J,L,ue){super();He(this,"type","If");this.test=J,this.body=L,this.alternate=ue}},S=class extends C{constructor(J,L,ue,le){super();He(this,"type","For");this.loopvar=J,this.iterable=L,this.body=ue,this.defaultBlock=le}},E=class extends C{constructor(J,L){super();He(this,"type","Set");this.assignee=J,this.value=L}},y=class extends C{constructor(J,L,ue){super();He(this,"type","Macro");this.name=J,this.args=L,this.body=ue}},b=class extends C{constructor(){super(...arguments);He(this,"type","Expression")}},I=class extends b{constructor(J,L,ue){super();He(this,"type","MemberExpression");this.object=J,this.property=L,this.computed=ue}},V=class extends b{constructor(J,L){super();He(this,"type","CallExpression");this.callee=J,this.args=L}},O=class extends b{constructor(J){super();He(this,"type","Identifier");this.value=J}},N=class extends b{constructor(J){super();He(this,"type","Literal");this.value=J}},j=class extends N{constructor(){super(...arguments);He(this,"type","NumericLiteral")}},D=class extends N{constructor(){super(...arguments);He(this,"type","StringLiteral")}},ee=class extends N{constructor(){super(...arguments);He(this,"type","BooleanLiteral")}},de=class extends N{constructor(){super(...arguments);He(this,"type","ArrayLiteral")}},Ce=class extends N{constructor(){super(...arguments);He(this,"type","TupleLiteral")}},te=class extends N{constructor(){super(...arguments);He(this,"type","ObjectLiteral")}},_e=class extends b{constructor(J,L,ue){super();He(this,"type","BinaryExpression");this.operator=J,this.left=L,this.right=ue}},R=class extends b{constructor(J,L){super();He(this,"type","FilterExpression");this.operand=J,this.filter=L}},xe=class extends b{constructor(J,L){super();He(this,"type","SelectExpression");this.iterable=J,this.test=L}},Xe=class extends b{constructor(J,L,ue){super();He(this,"type","TestExpression");this.operand=J,this.negate=L,this.test=ue}},ge=class extends b{constructor(J,L){super();He(this,"type","UnaryExpression");this.operator=J,this.argument=L}},X=class extends b{constructor(J=void 0,L=void 0,ue=void 0){super();He(this,"type","SliceExpression");this.start=J,this.stop=L,this.step=ue}},ae=class extends b{constructor(J,L){super();He(this,"type","KeywordArgumentExpression");this.key=J,this.value=L}};function Se(B){const J=new T([]);let L=0;function ue(mt,Pt){const Nt=B[L++];if(!Nt||Nt.type!==mt)throw new Error(`Parser Error: ${Pt}. ${Nt.type} !== ${mt}.`);return Nt}function le(){switch(B[L].type){case o.Text:return dt();case o.OpenStatement:return Je();case o.OpenExpression:return Ve();default:throw new SyntaxError(`Unexpected token type: ${B[L].type}`)}}function Te(...mt){return L+mt.length<=B.length&&mt.some((Pt,Nt)=>Pt!==B[L+Nt].type)}function Ne(...mt){return L+mt.length<=B.length&&mt.every((Pt,Nt)=>Pt===B[L+Nt].type)}function dt(){return new D(ue(o.Text,"Expected text token").value)}function Je(){ue(o.OpenStatement,"Expected opening statement token");let mt;switch(B[L].type){case o.Set:++L,mt=Y(),ue(o.CloseStatement,"Expected closing statement token");break;case o.If:++L,mt=ve(),ue(o.OpenStatement,"Expected {% token"),ue(o.EndIf,"Expected endif token"),ue(o.CloseStatement,"Expected %} token");break;case o.Macro:++L,mt=Re(),ue(o.OpenStatement,"Expected {% token"),ue(o.EndMacro,"Expected endmacro token"),ue(o.CloseStatement,"Expected %} token");break;case o.For:++L,mt=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: ${B[L].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 Y(){const mt=tt();if(Ne(o.Equals)){++L;const Pt=Y();return new E(mt,Pt)}return mt}function ve(){var un,Bi,Mi,Wr,wn,Kr,fi,Or;const mt=tt();ue(o.CloseStatement,"Expected closing statement token");const Pt=[],Nt=[];for(;!(((un=B[L])==null?void 0:un.type)===o.OpenStatement&&(((Bi=B[L+1])==null?void 0:Bi.type)===o.ElseIf||((Mi=B[L+1])==null?void 0:Mi.type)===o.Else||((Wr=B[L+1])==null?void 0:Wr.type)===o.EndIf));)Pt.push(le());if(((wn=B[L])==null?void 0:wn.type)===o.OpenStatement&&((Kr=B[L+1])==null?void 0:Kr.type)!==o.EndIf)if(++L,Ne(o.ElseIf))ue(o.ElseIf,"Expected elseif token"),Nt.push(ve());else for(ue(o.Else,"Expected else token"),ue(o.CloseStatement,"Expected closing statement token");!(((fi=B[L])==null?void 0:fi.type)===o.OpenStatement&&((Or=B[L+1])==null?void 0:Or.type)===o.EndIf);)Nt.push(le());return new z(mt,Pt,Nt)}function Re(){const mt=Pr();if(mt.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");const Pt=Vt();ue(o.CloseStatement,"Expected closing statement token");const Nt=[];for(;Te(o.OpenStatement,o.EndMacro);)Nt.push(le());return new y(mt,Pt,Nt)}function qe(mt=!1){const Pt=mt?Pr:tt,Nt=[Pt()],un=Ne(o.Comma);for(;un&&(++L,Nt.push(Pt()),!!Ne(o.Comma)););return un?new Ce(Nt):Nt[0]}function Qe(){const mt=qe(!0);if(!(mt instanceof O||mt instanceof Ce))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${mt.type} instead`);ue(o.In,"Expected `in` keyword following loop variable");const Pt=tt();ue(o.CloseStatement,"Expected closing statement token");const Nt=[];for(;Te(o.OpenStatement,o.EndFor)&&Te(o.OpenStatement,o.Else);)Nt.push(le());const un=[];if(Ne(o.OpenStatement,o.Else))for(++L,++L,ue(o.CloseStatement,"Expected closing statement token");Te(o.OpenStatement,o.EndFor);)un.push(le());return new S(mt,Pt,Nt,un)}function tt(){return pt()}function pt(){const mt=ht();if(Ne(o.If)){++L;const Pt=ht();if(Ne(o.Else)){++L;const Nt=ht();return new z(Pt,[mt],[Nt])}else return new xe(mt,Pt)}return mt}function ht(){let mt=Tt();for(;Ne(o.Or);){const Pt=B[L];++L;const Nt=Tt();mt=new _e(Pt,mt,Nt)}return mt}function Tt(){let mt=vt();for(;Ne(o.And);){const Pt=B[L];++L;const Nt=vt();mt=new _e(Pt,mt,Nt)}return mt}function vt(){let mt;for(;Ne(o.Not);){const Pt=B[L];++L;const Nt=vt();mt=new ge(Pt,Nt)}return mt??Et()}function Et(){let mt=Lt();for(;Ne(o.ComparisonBinaryOperator)||Ne(o.In)||Ne(o.NotIn);){const Pt=B[L];++L;const Nt=Lt();mt=new _e(Pt,mt,Nt)}return mt}function Lt(){let mt=Ht();for(;Ne(o.AdditiveBinaryOperator);){const Pt=B[L];++L;const Nt=Ht();mt=new _e(Pt,mt,Nt)}return mt}function at(){const mt=rr();return Ne(o.OpenParen)?zt(mt):mt}function zt(mt){let Pt=new V(mt,Vt());return Ne(o.OpenParen)&&(Pt=zt(Pt)),Pt}function Vt(){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 Pt=tt();if(Ne(o.Equals)){if(++L,!(Pt instanceof O))throw new SyntaxError("Expected identifier for keyword argument");const Nt=tt();Pt=new ae(Pt,Nt)}mt.push(Pt),Ne(o.Comma)&&++L}return mt}function Yt(){const mt=[];let Pt=!1;for(;!Ne(o.CloseSquareBracket);)Ne(o.Colon)?(mt.push(void 0),++L,Pt=!0):(mt.push(tt()),Ne(o.Colon)&&(++L,Pt=!0));if(mt.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(Pt){if(mt.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new X(...mt)}return mt[0]}function rr(){let mt=Pr();for(;Ne(o.Dot)||Ne(o.OpenSquareBracket);){const Pt=B[L];++L;let Nt;const un=Pt.type!==o.Dot;if(un)Nt=Yt(),ue(o.CloseSquareBracket,"Expected closing square bracket");else if(Nt=Pr(),Nt.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");mt=new I(mt,Nt,un)}return mt}function Ht(){let mt=Cr();for(;Ne(o.MultiplicativeBinaryOperator);){const Pt=B[L];++L;const Nt=Cr();mt=new _e(Pt,mt,Nt)}return mt}function Cr(){let mt=Yr();for(;Ne(o.Is);){++L;const Pt=Ne(o.Not);Pt&&++L;let Nt=Pr();if(Nt instanceof ee&&(Nt=new O(Nt.value.toString())),!(Nt instanceof O))throw new SyntaxError("Expected identifier for the test");mt=new Xe(mt,Pt,Nt)}return mt}function Yr(){let mt=at();for(;Ne(o.Pipe);){++L;let Pt=Pr();if(!(Pt instanceof O))throw new SyntaxError("Expected identifier for the filter");Ne(o.OpenParen)&&(Pt=zt(Pt)),mt=new R(mt,Pt)}return mt}function Pr(){const mt=B[L];switch(mt.type){case o.NumericLiteral:return++L,new j(Number(mt.value));case o.StringLiteral:return++L,new D(mt.value);case o.BooleanLiteral:return++L,new ee(mt.value.toLowerCase()==="true");case o.Identifier:return++L,new O(mt.value);case o.OpenParen:{++L;const Pt=qe();if(B[L].type!==o.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${B[L].type} instead`);return++L,Pt}case o.OpenSquareBracket:{++L;const Pt=[];for(;!Ne(o.CloseSquareBracket);)Pt.push(tt()),Ne(o.Comma)&&++L;return++L,new de(Pt)}case o.OpenCurlyBracket:{++L;const Pt=new Map;for(;!Ne(o.CloseCurlyBracket);){const Nt=tt();ue(o.Colon,"Expected colon between key and value in object literal");const un=tt();Pt.set(Nt,un),Ne(o.Comma)&&++L}return++L,new te(Pt)}default:throw new SyntaxError(`Unexpected token: ${mt.type}`)}}for(;L=0?(J=(J??(J=0))<0?Math.max(B.length+J,0):Math.min(J,B.length),L=(L??(L=B.length))<0?Math.max(B.length+L,0):Math.min(L,B.length)):(J=(J??(J=B.length-1))<0?Math.max(B.length+J,-1):Math.min(J,B.length-1),L=(L??(L=-1))<-1?Math.max(B.length+L,-1):Math.min(L,B.length-1));const Te=[];for(let Ne=J;le*NeJ.toUpperCase())}var Le=class{constructor(B=void 0){He(this,"type","RuntimeValue");He(this,"value");He(this,"builtins",new Map);this.value=B}__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")}},ft=class extends Le{constructor(){super(...arguments);He(this,"type","ObjectValue");He(this,"builtins",new Map([["get",new Ye(([J,L])=>{if(!(J instanceof We))throw new Error(`Object key must be a string: got ${J.type}`);return this.value.get(J.value)??L??new et})],["items",new Ye(()=>new Me(Array.from(this.value.entries()).map(([J,L])=>new Me([new We(J),L]))))]]))}__bool__(){return new st(this.value.size>0)}},Ge=class extends ft{constructor(){super(...arguments);He(this,"type","KeywordArgumentsValue")}},Me=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 Me{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(B){He(this,"variables",new Map([["namespace",new Ye(B=>{if(B.length===0)return new ft(new Map);if(B.length!==1||!(B[0]instanceof ft))throw new Error("`namespace` expects either zero arguments or a single object argument");return B[0]})]]));He(this,"tests",new Map([["boolean",B=>B.type==="BooleanValue"],["callable",B=>B instanceof Ye],["odd",B=>{if(B.type!=="NumericValue")throw new Error(`Cannot apply test "odd" to type: ${B.type}`);return B.value%2!==0}],["even",B=>{if(B.type!=="NumericValue")throw new Error(`Cannot apply test "even" to type: ${B.type}`);return B.value%2===0}],["false",B=>B.type==="BooleanValue"&&!B.value],["true",B=>B.type==="BooleanValue"&&B.value],["string",B=>B.type==="StringValue"],["number",B=>B.type==="NumericValue"],["integer",B=>B.type==="NumericValue"&&Number.isInteger(B.value)],["iterable",B=>B instanceof Me||B instanceof We],["lower",B=>{const J=B.value;return B.type==="StringValue"&&J===J.toLowerCase()}],["upper",B=>{const J=B.value;return B.type==="StringValue"&&J===J.toUpperCase()}],["none",B=>B.type==="NullValue"],["defined",B=>B.type!=="UndefinedValue"],["undefined",B=>B.type==="UndefinedValue"],["equalto",(B,J)=>B.value===J.value],["eq",(B,J)=>B.value===J.value]]));this.parent=B}set(B,J){return this.declareVariable(B,se(J))}declareVariable(B,J){if(this.variables.has(B))throw new SyntaxError(`Variable already declared: ${B}`);return this.variables.set(B,J),J}setVariable(B,J){return this.variables.set(B,J),J}resolve(B){if(this.variables.has(B))return this;if(this.parent)return this.parent.resolve(B);throw new Error(`Unknown variable: ${B}`)}lookupVariable(B){try{return this.resolve(B).variables.get(B)??new A}catch{return new A}}},Pe=class{constructor(B){He(this,"global");this.global=B??new $e}run(B){return this.evaluate(B,this.global)}evaluateBinaryExpression(B,J){const L=this.evaluate(B.left,J);switch(B.operator.value){case"and":return L.__bool__().value?this.evaluate(B.right,J):L;case"or":return L.__bool__().value?L:this.evaluate(B.right,J)}const ue=this.evaluate(B.right,J);switch(B.operator.value){case"==":return new st(L.value==ue.value);case"!=":return new st(L.value!=ue.value)}if(L instanceof A||ue instanceof A)throw new Error("Cannot perform operation on undefined values");if(L instanceof et||ue instanceof et)throw new Error("Cannot perform operation on null values");if(L instanceof Be&&ue instanceof Be)switch(B.operator.value){case"+":return new Be(L.value+ue.value);case"-":return new Be(L.value-ue.value);case"*":return new Be(L.value*ue.value);case"/":return new Be(L.value/ue.value);case"%":return new Be(L.value%ue.value);case"<":return new st(L.value":return new st(L.value>ue.value);case">=":return new st(L.value>=ue.value);case"<=":return new st(L.value<=ue.value)}else if(L instanceof Me&&ue instanceof Me)switch(B.operator.value){case"+":return new Me(L.value.concat(ue.value))}else if(ue instanceof Me){const le=ue.value.find(Te=>Te.value===L.value)!==void 0;switch(B.operator.value){case"in":return new st(le);case"not in":return new st(!le)}}if(L instanceof We||ue instanceof We)switch(B.operator.value){case"+":return new We(L.value.toString()+ue.value.toString())}if(L instanceof We&&ue instanceof We)switch(B.operator.value){case"in":return new st(ue.value.includes(L.value));case"not in":return new st(!ue.value.includes(L.value))}if(L instanceof We&&ue instanceof ft)switch(B.operator.value){case"in":return new st(ue.value.has(L.value));case"not in":return new st(!ue.value.has(L.value))}throw new SyntaxError(`Unknown operator "${B.operator.value}" between ${L.type} and ${ue.type}`)}evaluateArguments(B,J){const L=[],ue=new Map;for(const le of B)if(le.type==="KeywordArgumentExpression"){const Te=le;ue.set(Te.key.value,this.evaluate(Te.value,J))}else{if(ue.size>0)throw new Error("Positional arguments must come before keyword arguments");L.push(this.evaluate(le,J))}return[L,ue]}evaluateFilterExpression(B,J){const L=this.evaluate(B.operand,J);if(B.filter.type==="Identifier"){const ue=B.filter;if(ue.value==="tojson")return new We(ne(L));if(L instanceof Me)switch(ue.value){case"list":return L;case"first":return L.value[0];case"last":return L.value[L.value.length-1];case"length":return new Be(L.value.length);case"reverse":return new Me(L.value.reverse());case"sort":return new Me(L.value.sort((le,Te)=>{if(le.type!==Te.type)throw new Error(`Cannot compare different types: ${le.type} and ${Te.type}`);switch(le.type){case"NumericValue":return le.value-Te.value;case"StringValue":return le.value.localeCompare(Te.value);default:throw new Error(`Cannot compare type: ${le.type}`)}}));default:throw new Error(`Unknown ArrayValue filter: ${ue.value}`)}else if(L instanceof We)switch(ue.value){case"length":return new Be(L.value.length);case"upper":return new We(L.value.toUpperCase());case"lower":return new We(L.value.toLowerCase());case"title":return new We(Ke(L.value));case"capitalize":return new We(L.value.charAt(0).toUpperCase()+L.value.slice(1));case"trim":return new We(L.value.trim());case"indent":return new We(L.value.split(` +`).map((le,Te)=>Te===0||le.length===0?le:" "+le).join(` +`));case"string":return L;default:throw new Error(`Unknown StringValue filter: ${ue.value}`)}else if(L instanceof Be)switch(ue.value){case"abs":return new Be(Math.abs(L.value));default:throw new Error(`Unknown NumericValue filter: ${ue.value}`)}else if(L instanceof ft)switch(ue.value){case"items":return new Me(Array.from(L.value.entries()).map(([le,Te])=>new Me([new We(le),Te])));case"length":return new Be(L.value.size);default:throw new Error(`Unknown ObjectValue filter: ${ue.value}`)}throw new Error(`Cannot apply filter "${ue.value}" to type: ${L.type}`)}else if(B.filter.type==="CallExpression"){const ue=B.filter;if(ue.callee.type!=="Identifier")throw new Error(`Unknown filter: ${ue.callee.type}`);const le=ue.callee.value;if(le==="tojson"){const[,Te]=this.evaluateArguments(ue.args,J),Ne=Te.get("indent")??new et;if(!(Ne instanceof Be||Ne instanceof et))throw new Error("If set, indent must be a number");return new We(ne(L,Ne.value))}if(L instanceof Me){switch(le){case"selectattr":{if(L.value.some(Y=>!(Y instanceof ft)))throw new Error("`selectattr` can only be applied to array of objects");if(ue.args.some(Y=>Y.type!=="StringLiteral"))throw new Error("arguments of `selectattr` must be strings");const[Te,Ne,dt]=ue.args.map(Y=>this.evaluate(Y,J));let Je;if(Ne){const Y=J.tests.get(Ne.value);if(!Y)throw new Error(`Unknown test: ${Ne.value}`);Je=Y}else Je=(...Y)=>Y[0].__bool__().value;const Ve=L.value.filter(Y=>{const ve=Y.value.get(Te.value);return ve?Je(ve,dt):!1});return new Me(Ve)}case"map":{const[,Te]=this.evaluateArguments(ue.args,J);if(Te.has("attribute")){const Ne=Te.get("attribute");if(!(Ne instanceof We))throw new Error("attribute must be a string");const dt=Te.get("default"),Je=L.value.map(Ve=>{if(!(Ve instanceof ft))throw new Error("items in map must be an object");return Ve.value.get(Ne.value)??dt??new A});return new Me(Je)}else throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${le}`)}else if(L instanceof We){switch(le){case"indent":{const[Te,Ne]=this.evaluateArguments(ue.args,J),dt=Te.at(0)??Ne.get("width")??new Be(4);if(!(dt instanceof Be))throw new Error("width must be a number");const Je=Te.at(1)??Ne.get("first")??new st(!1),Ve=Te.at(2)??Ne.get("blank")??new st(!1),Y=L.value.split(` +`),ve=" ".repeat(dt.value),Re=Y.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: ${L.type}`)}throw new Error(`Unknown filter: ${B.filter.type}`)}evaluateTestExpression(B,J){const L=this.evaluate(B.operand,J),ue=J.tests.get(B.test.value);if(!ue)throw new Error(`Unknown test: ${B.test.value}`);const le=ue(L);return new st(B.negate?!le:le)}evaluateUnaryExpression(B,J){const L=this.evaluate(B.argument,J);switch(B.operator.value){case"not":return new st(!L.value);default:throw new SyntaxError(`Unknown operator: ${B.operator.value}`)}}evalProgram(B,J){return this.evaluateBlock(B.body,J)}evaluateBlock(B,J){let L="";for(const ue of B){const le=this.evaluate(ue,J);le.type!=="NullValue"&&le.type!=="UndefinedValue"&&(L+=le.value)}return new We(L)}evaluateIdentifier(B,J){return J.lookupVariable(B.value)}evaluateCallExpression(B,J){const[L,ue]=this.evaluateArguments(B.args,J);ue.size>0&&L.push(new Ge(ue));const le=this.evaluate(B.callee,J);if(le.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${le.type}`);return le.value(L,J)}evaluateSliceExpression(B,J,L){if(!(B instanceof Me||B instanceof We))throw new Error("Slice object must be an array or string");const ue=this.evaluate(J.start,L),le=this.evaluate(J.stop,L),Te=this.evaluate(J.step,L);if(!(ue instanceof Be||ue instanceof A))throw new Error("Slice start must be numeric or undefined");if(!(le instanceof Be||le instanceof A))throw new Error("Slice stop must be numeric or undefined");if(!(Te instanceof Be||Te instanceof A))throw new Error("Slice step must be numeric or undefined");return B instanceof Me?new Me(me(B.value,ue.value,le.value,Te.value)):new We(me(Array.from(B.value),ue.value,le.value,Te.value).join(""))}evaluateMemberExpression(B,J){const L=this.evaluate(B.object,J);let ue;if(B.computed){if(B.property.type==="SliceExpression")return this.evaluateSliceExpression(L,B.property,J);ue=this.evaluate(B.property,J)}else ue=new We(B.property.value);let le;if(L instanceof ft){if(!(ue instanceof We))throw new Error(`Cannot access property with non-string: got ${ue.type}`);le=L.value.get(ue.value)??L.builtins.get(ue.value)}else if(L instanceof Me||L instanceof We)if(ue instanceof Be)le=L.value.at(ue.value),L instanceof We&&(le=new We(L.value.at(ue.value)));else if(ue instanceof We)le=L.builtins.get(ue.value);else throw new Error(`Cannot access property with non-string/non-number: got ${ue.type}`);else{if(!(ue instanceof We))throw new Error(`Cannot access property with non-string: got ${ue.type}`);le=L.builtins.get(ue.value)}return le instanceof Le?le:new A}evaluateSet(B,J){const L=this.evaluate(B.value,J);if(B.assignee.type==="Identifier"){const ue=B.assignee.value;J.setVariable(ue,L)}else if(B.assignee.type==="MemberExpression"){const ue=B.assignee,le=this.evaluate(ue.object,J);if(!(le instanceof ft))throw new Error("Cannot assign to member of non-object");if(ue.property.type!=="Identifier")throw new Error("Cannot assign to member with non-identifier property");le.value.set(ue.property.value,L)}else throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(B.assignee)}`);return new et}evaluateIf(B,J){const L=this.evaluate(B.test,J);return this.evaluateBlock(L.__bool__().value?B.body:B.alternate,J)}evaluateFor(B,J){const L=new $e(J);let ue,le;if(B.iterable.type==="SelectExpression"){const Ve=B.iterable;le=this.evaluate(Ve.iterable,L),ue=Ve.test}else le=this.evaluate(B.iterable,L);if(!(le instanceof Me))throw new Error(`Expected iterable type in for loop: got ${le.type}`);const Te=[],Ne=[];for(let Ve=0;Veqe.setVariable(B.loopvar.value,ve);else if(B.loopvar.type==="TupleLiteral"){const qe=B.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 pt=0;pt0?Te[Ve-1]:new A],["nextitem",Ve{var Ne;const le=new $e(ue);L=L.slice();let Te;((Ne=L.at(-1))==null?void 0:Ne.type)==="KeywordArgumentsValue"&&(Te=L.pop());for(let dt=0;dtthis.evaluate(L,J)));case"TupleLiteral":return new je(B.value.map(L=>this.evaluate(L,J)));case"ObjectLiteral":{const L=new Map;for(const[ue,le]of B.value){const Te=this.evaluate(ue,J);if(!(Te instanceof We))throw new Error(`Object keys must be strings: got ${Te.type}`);L.set(Te.value,this.evaluate(le,J))}return new ft(L)}case"Identifier":return this.evaluateIdentifier(B,J);case"CallExpression":return this.evaluateCallExpression(B,J);case"MemberExpression":return this.evaluateMemberExpression(B,J);case"UnaryExpression":return this.evaluateUnaryExpression(B,J);case"BinaryExpression":return this.evaluateBinaryExpression(B,J);case"FilterExpression":return this.evaluateFilterExpression(B,J);case"TestExpression":return this.evaluateTestExpression(B,J);default:throw new SyntaxError(`Unknown node type: ${B.type}`)}}};function se(B){switch(typeof B){case"number":return new Be(B);case"string":return new We(B);case"boolean":return new st(B);case"undefined":return new A;case"object":return B===null?new et:Array.isArray(B)?new Me(B.map(se)):new ft(new Map(Object.entries(B).map(([J,L])=>[J,se(L)])));case"function":return new Ye((J,L)=>{const ue=B(...J.map(le=>le.value))??null;return se(ue)});default:throw new Error(`Cannot convert to runtime value: ${B}`)}}function ne(B,J,L){const ue=L??0;switch(B.type){case"NullValue":case"UndefinedValue":return"null";case"NumericValue":case"StringValue":case"BooleanValue":return JSON.stringify(B.value);case"ArrayValue":case"ObjectValue":{const le=J?" ".repeat(J):"",Te=` +`+le.repeat(ue),Ne=Te+le;if(B.type==="ArrayValue"){const dt=B.value.map(Je=>ne(Je,J,ue+1));return J?`[${Ne}${dt.join(`,${Ne}`)}${Te}]`:`[${dt.join(", ")}]`}else{const dt=Array.from(B.value.entries()).map(([Je,Ve])=>{const Y=`"${Je}": ${ne(Ve,J,ue+1)}`;return J?`${Ne}${Y}`:Y});return J?`{${dt.join(",")}${Te}}`:`{${dt.join(", ")}}`}}default:throw new Error(`Cannot convert to JSON: ${B.type}`)}}var ye=class{constructor(B){He(this,"parsed");const J=w(B,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=Se(J)}render(B){const J=new $e;J.set("false",!1),J.set("true",!0),J.set("raise_exception",le=>{throw new Error(le)}),J.set("range",Q);for(const[le,Te]of Object.entries(B))J.set(le,Te);return new Pe(J).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=(p,g,M)=>{if(g&&typeof g.init=="function"&&typeof g.createInferenceSessionHandler=="function"){const w=o.get(p);if(w===void 0)o.set(p,{backend:g,priority:M});else{if(w.priority>M)return;if(w.priority===M&&w.backend!==g)throw new Error(`cannot register backend "${p}" using priority ${M}`)}if(M>=0){const C=a.indexOf(p);C!==-1&&a.splice(C,1);for(let T=0;T{const g=o.get(p);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(p)),await g.initPromise,g.initialized=!0,g.backend}catch(w){return M||(g.error=`${w}`,g.aborted=!0),g.error}finally{delete g.initPromise}}},_=async p=>{const g=p.executionProviders||[],M=g.map(E=>typeof E=="string"?E:E.name),w=M.length===0?a:M;let C;const T=[],z=new Set;for(const E of w){const y=await f(E);typeof y=="string"?T.push({name:E,err:y}):(C||(C=y),C===y&&z.add(E))}if(!C)throw new Error(`no available backend found. ERR: ${T.map(E=>`[${E.name}] ${E.err}`).join(", ")}`);for(const{name:E,err:y}of T)M.includes(E)&&console.warn(`removing requested execution provider "${E}" from session options because it is not available: ${y}`);const S=g.filter(E=>z.has(typeof E=="string"?E:E.name));return[C,new Proxy(p,{get:(E,y)=>y==="executionProviders"?S:Reflect.get(E,y)})]}},"./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(f){if(f!==void 0){if(typeof f!="string"||["verbose","info","warning","error","fatal"].indexOf(f)===-1)throw new Error(`Unsupported logging level: ${f}`);a=f}},get logLevel(){return a}};Object.defineProperty(l,"logLevel",{enumerable:!0})},"./node_modules/onnxruntime-common/dist/esm/env.js":(e,t,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:()=>f.Tensor,TrainingSession:()=>p.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"),f=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 p=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:()=>f});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 f{constructor(p){this.handler=p}async run(p,g,M){(0,l.TRACE_FUNC_BEGIN)();const w={};let C={};if(typeof p!="object"||p===null||p instanceof a.Tensor||Array.isArray(p))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 E of g){if(typeof E!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(E)===-1)throw new RangeError(`'fetches' contains invalid output name: ${E}.`);w[E]=null}if(typeof M=="object"&&M!==null)C=M;else if(typeof M<"u")throw new TypeError("'options' must be an object.")}else{let E=!1;const y=Object.getOwnPropertyNames(g);for(const b of this.outputNames)if(y.indexOf(b)!==-1){const I=g[b];(I===null||I instanceof a.Tensor)&&(E=!0,T=!1,w[b]=I)}if(E){if(typeof M=="object"&&M!==null)C=M;else if(typeof M<"u")throw new TypeError("'options' must be an object.")}else C=g}}else if(typeof g<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const E of this.inputNames)if(typeof p[E]>"u")throw new Error(`input '${E}' is missing in 'feeds'.`);if(T)for(const E of this.outputNames)w[E]=null;const z=await this.handler.run(p,w,C),S={};for(const E in z)if(Object.hasOwnProperty.call(z,E)){const y=z[E];y instanceof a.Tensor?S[E]=y:S[E]=new a.Tensor(y.type,y.data,y.dims)}return(0,l.TRACE_FUNC_END)(),S}async release(){return this.handler.dispose()}static async create(p,g,M,w){(0,l.TRACE_FUNC_BEGIN)();let C,T={};if(typeof p=="string"){if(C=p,typeof g=="object"&&g!==null)T=g;else if(typeof g<"u")throw new TypeError("'options' must be an object.")}else if(p instanceof Uint8Array){if(C=p,typeof g=="object"&&g!==null)T=g;else if(typeof g<"u")throw new TypeError("'options' must be an object.")}else if(p instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&p instanceof SharedArrayBuffer){const y=p;let b=0,I=p.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>=y.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${y.byteLength}).`);if(I=p.byteLength-b,typeof M=="number"){if(I=M,!Number.isSafeInteger(I))throw new RangeError("'byteLength' must be an integer.");if(I<=0||b+I>y.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${y.byteLength-b}].`);if(typeof w=="object"&&w!==null)T=w;else if(typeof w<"u")throw new TypeError("'options' must be an object.")}else if(typeof M<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof g<"u")throw new TypeError("'options' must be an object.");C=new Uint8Array(y,b,I)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");const[z,S]=await(0,o.resolveBackendAndExecutionProviders)(T),E=await z.createInferenceSessionHandler(C,S);return(0,l.TRACE_FUNC_END)(),new f(E)}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,f)=>{const _=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);_.width=l.dims[3],_.height=l.dims[2];const p=_.getContext("2d");if(p!=null){let g,M;(f==null?void 0:f.tensorLayout)!==void 0&&f.tensorLayout==="NHWC"?(g=l.dims[2],M=l.dims[3]):(g=l.dims[3],M=l.dims[2]);const w=(f==null?void 0:f.format)!==void 0?f.format:"RGB",C=f==null?void 0:f.norm;let T,z;C===void 0||C.mean===void 0?T=[255,255,255,255]:typeof C.mean=="number"?T=[C.mean,C.mean,C.mean,C.mean]:(T=[C.mean[0],C.mean[1],C.mean[2],0],C.mean[3]!==void 0&&(T[3]=C.mean[3])),C===void 0||C.bias===void 0?z=[0,0,0,0]:typeof C.bias=="number"?z=[C.bias,C.bias,C.bias,C.bias]:(z=[C.bias[0],C.bias[1],C.bias[2],0],C.bias[3]!==void 0&&(z[3]=C.bias[3]));const S=M*g;let E=0,y=S,b=S*2,I=-1;w==="RGBA"?(E=0,y=S,b=S*2,I=S*3):w==="RGB"?(E=0,y=S,b=S*2):w==="RBG"&&(E=0,b=S,y=S*2);for(let V=0;V{const _=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");let p;if(_!=null){let g,M,w;(f==null?void 0:f.tensorLayout)!==void 0&&f.tensorLayout==="NHWC"?(g=l.dims[2],M=l.dims[1],w=l.dims[3]):(g=l.dims[3],M=l.dims[2],w=l.dims[1]);const C=f!==void 0&&f.format!==void 0?f.format:"RGB",T=f==null?void 0:f.norm;let z,S;T===void 0||T.mean===void 0?z=[255,255,255,255]:typeof T.mean=="number"?z=[T.mean,T.mean,T.mean,T.mean]:(z=[T.mean[0],T.mean[1],T.mean[2],255],T.mean[3]!==void 0&&(z[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 E=M*g;if(f!==void 0&&(f.format!==void 0&&w===4&&f.format!=="RGBA"||w===3&&f.format!=="RGB"&&f.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");const y=4;let b=0,I=1,V=2,O=3,N=0,j=E,D=E*2,ee=-1;C==="RGBA"?(N=0,j=E,D=E*2,ee=E*3):C==="RGB"?(N=0,j=E,D=E*2):C==="RBG"&&(N=0,D=E,j=E*2),p=_.createImageData(g,M);for(let de=0;de{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:()=>p,tensorFromTexture:()=>f});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:w,width:C}=M,T=M.norm??{mean:255,bias:0};let z,S;typeof T.mean=="number"?z=[T.mean,T.mean,T.mean,T.mean]:z=[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 E=M.format!==void 0?M.format:"RGBA",y=M.tensorFormat!==void 0&&M.tensorFormat!==void 0?M.tensorFormat:"RGB",b=w*C,I=y==="RGBA"?new Float32Array(b*4):new Float32Array(b*3);let V=4,O=0,N=1,j=2,D=3,ee=0,de=b,Ce=b*2,te=-1;E==="RGB"&&(V=3,O=0,N=1,j=2,D=-1),y==="RGBA"?te=b*3:y==="RBG"?(ee=0,Ce=b,de=b*2):y==="BGR"&&(Ce=0,de=b,ee=b*2);for(let R=0;R{const w=typeof HTMLImageElement<"u"&&g instanceof HTMLImageElement,C=typeof ImageData<"u"&&g instanceof ImageData,T=typeof ImageBitmap<"u"&&g instanceof ImageBitmap,z=typeof g=="string";let S,E=M??{};const y=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},b=I=>I instanceof HTMLCanvasElement||I instanceof OffscreenCanvas?I.getContext("2d"):null;if(w){const I=y();I.width=g.width,I.height=g.height;const V=b(I);if(V!=null){let O=g.height,N=g.width;if(M!==void 0&&M.resizedHeight!==void 0&&M.resizedWidth!==void 0&&(O=M.resizedHeight,N=M.resizedWidth),M!==void 0){if(E=M,M.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");E.tensorFormat="RGBA",E.height=O,E.width=N}else E.tensorFormat="RGBA",E.height=O,E.width=N;V.drawImage(g,0,0),S=V.getImageData(0,0,N,O).data}else throw new Error("Can not access image data")}else if(C){let I,V;if(M!==void 0&&M.resizedWidth!==void 0&&M.resizedHeight!==void 0?(I=M.resizedHeight,V=M.resizedWidth):(I=g.height,V=g.width),M!==void 0&&(E=M),E.format="RGBA",E.height=I,E.width=V,M!==void 0){const O=y();O.width=V,O.height=I;const N=b(O);if(N!=null)N.putImageData(g,0,0),S=N.getImageData(0,0,V,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=y();I.width=g.width,I.height=g.height;const V=b(I);if(V!=null){const O=g.height,N=g.width;return V.drawImage(g,0,0,N,O),S=V.getImageData(0,0,N,O).data,E.height=O,E.width=N,a(S,E)}else throw new Error("Can not access image data")}else{if(z)return new Promise((I,V)=>{const O=y(),N=b(O);if(!g||!N)return V();const j=new Image;j.crossOrigin="Anonymous",j.src=g,j.onload=()=>{O.width=j.width,O.height=j.height,N.drawImage(j,0,0,O.width,O.height);const D=N.getImageData(0,0,O.width,O.height);E.height=O.height,E.width=O.width,I(a(D.data,E))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(S!==void 0)return a(S,E);throw new Error("Input data provided is not supported - aborted tensor creation")},f=(g,M)=>{const{width:w,height:C,download:T,dispose:z}=M,S=[1,C,w,4];return new o.Tensor({location:"texture",type:"float32",texture:g,dims:S,download:T,dispose:z})},_=(g,M)=>{const{dataType:w,dims:C,download:T,dispose:z}=M;return new o.Tensor({location:"gpu-buffer",type:w??"float32",gpuBuffer:g,dims:C,download:T,dispose:z})},p=(g,M,w)=>new o.Tensor({location:"cpu-pinned",type:g,data:M,dims:w??[M.length]})},"./node_modules/onnxruntime-common/dist/esm/tensor-factory.js":(e,t,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:()=>f});const o=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array]]),a=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);let l=!1;const f=()=>{if(!l){l=!0;const _=typeof BigInt64Array<"u"&&BigInt64Array.from,p=typeof BigUint64Array<"u"&&BigUint64Array.from,g=typeof Float16Array<"u"&&Float16Array.from;_&&(o.set("int64",BigInt64Array),a.set(BigInt64Array,"int64")),p&&(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"),f=r("./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js");class _{constructor(g,M,w){(0,l.checkTypedArray)();let C,T;if(typeof g=="object"&&"location"in g)switch(this.dataLocation=g.location,C=g.type,T=g.dims,g.location){case"cpu-pinned":{const S=l.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(C);if(!S)throw new TypeError(`unsupported type "${C}" to create tensor from pinned buffer`);if(!(g.data instanceof S))throw new TypeError(`buffer should be of type ${S.name}`);this.cpuData=g.data;break}case"texture":{if(C!=="float32")throw new TypeError(`unsupported type "${C}" to create tensor from texture`);this.gpuTextureData=g.texture,this.downloader=g.download,this.disposer=g.dispose;break}case"gpu-buffer":{if(C!=="float32"&&C!=="float16"&&C!=="int32"&&C!=="int64"&&C!=="uint32"&&C!=="uint8"&&C!=="bool")throw new TypeError(`unsupported type "${C}" to create tensor from gpu buffer`);this.gpuBufferData=g.gpuBuffer,this.downloader=g.download,this.disposer=g.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let S,E;if(typeof g=="string")if(C=g,E=w,g==="string"){if(!Array.isArray(M))throw new TypeError("A string tensor's data must be a string array.");S=M}else{const y=l.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(g);if(y===void 0)throw new TypeError(`Unsupported tensor type: ${g}.`);if(Array.isArray(M)){if(g==="float16"&&y===Uint16Array)throw new TypeError("Creating a float16 tensor from number array is not supported. Please use Uint16Array as data.");g==="uint64"||g==="int64"?S=y.from(M,BigInt):S=y.from(M)}else if(M instanceof y)S=M;else throw new TypeError(`A ${C} tensor's data must be type of ${y}`)}else if(E=M,Array.isArray(g)){if(g.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");const y=typeof g[0];if(y==="string")C="string",S=g;else if(y==="boolean")C="bool",S=Uint8Array.from(g);else throw new TypeError(`Invalid element type of data array: ${y}.`)}else{const y=l.NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.get(g.constructor);if(y===void 0)throw new TypeError(`Unsupported type for tensor data: ${g.constructor}.`);C=y,S=g}if(E===void 0)E=[S.length];else if(!Array.isArray(E))throw new TypeError("A tensor's dims must be a number array");T=E,this.cpuData=S,this.dataLocation="cpu"}const z=(0,f.calculateSize)(T);if(this.cpuData&&z!==this.cpuData.length)throw new Error(`Tensor's size(${z}) does not match data length(${this.cpuData.length}).`);this.type=C,this.dims=T,this.size=z}static async fromImage(g,M){return(0,a.tensorFromImage)(g,M)}static fromTexture(g,M){return(0,a.tensorFromTexture)(g,M)}static fromGpuBuffer(g,M){return(0,a.tensorFromGpuBuffer)(g,M)}static fromPinnedBuffer(g,M,w){return(0,a.tensorFromPinnedBuffer)(g,M,w)}toDataURL(g){return(0,o.tensorToDataURL)(this,g)}toImageData(g){return(0,o.tensorToImageData)(this,g)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}async getData(g){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;const M=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=M,g&&this.disposer&&(this.disposer(),this.disposer=void 0),M}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(g){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return(0,f.tensorReshape)(this,g)}}},"./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js":(e,t,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=f=>{let _=1;for(let p=0;p{switch(f.location){case"cpu":return new o.Tensor(f.type,f.data,_);case"cpu-pinned":return new o.Tensor({location:"cpu-pinned",data:f.data,type:f.type,dims:_});case"texture":return new o.Tensor({location:"texture",texture:f.texture,type:f.type,dims:_});case"gpu-buffer":return new o.Tensor({location:"gpu-buffer",gpuBuffer:f.gpuBuffer,type:f.type,dims:_});default:throw new Error(`tensorReshape: tensor location ${f.location} is not supported`)}}},"./node_modules/onnxruntime-common/dist/esm/tensor.js":(e,t,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:()=>f,TRACE_FUNC_END:()=>_});var o=r("./node_modules/onnxruntime-common/dist/esm/env-impl.js");const a=(p,g)=>{(typeof o.env.trace>"u"?!o.env.wasm.trace:!o.env.trace)||console.timeStamp(`${p}::ORT::${g}`)},l=(p,g)=>{var C;const M=((C=new Error().stack)==null?void 0:C.split(/\r\n|\r|\n/g))||[];let w=!1;for(let T=0;T{(typeof o.env.trace>"u"?!o.env.wasm.trace:!o.env.trace)||l("BEGIN",p)},_=p=>{(typeof o.env.trace>"u"?!o.env.wasm.trace:!o.env.trace)||l("END",p)}},"./node_modules/onnxruntime-common/dist/esm/training-session-impl.js":(e,t,r)=>{r.r(t),r.d(t,{TrainingSession:()=>f});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 f{constructor(p,g,M){this.handler=p,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(p,g){const M=p.evalModel||"",w=p.optimizerModel||"",C=g||{},[T,z]=await(0,o.resolveBackendAndExecutionProviders)(C);if(T.createTrainingSessionHandler){const S=await T.createTrainingSessionHandler(p.checkpointState,p.trainModel,M,w,z);return new f(S,!!p.optimizerModel,!!p.evalModel)}else throw new Error(l)}typeNarrowingForRunStep(p,g,M,w,C){const T={};let z={};if(typeof M!="object"||M===null||M instanceof a.Tensor||Array.isArray(M))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let S=!0;if(typeof w=="object"){if(w===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(w instanceof a.Tensor)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(w)){if(w.length===0)throw new TypeError("'fetches' cannot be an empty array.");S=!1;for(const E of w){if(typeof E!="string")throw new TypeError("'fetches' must be a string array or an object.");if(g.indexOf(E)===-1)throw new RangeError(`'fetches' contains invalid output name: ${E}.`);T[E]=null}if(typeof C=="object"&&C!==null)z=C;else if(typeof C<"u")throw new TypeError("'options' must be an object.")}else{let E=!1;const y=Object.getOwnPropertyNames(w);for(const b of g)if(y.indexOf(b)!==-1){const I=w[b];(I===null||I instanceof a.Tensor)&&(E=!0,S=!1,T[b]=I)}if(E){if(typeof C=="object"&&C!==null)z=C;else if(typeof C<"u")throw new TypeError("'options' must be an object.")}else z=w}}else if(typeof w<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const E of p)if(typeof M[E]>"u")throw new Error(`input '${E}' is missing in 'feeds'.`);if(S)for(const E of g)T[E]=null;return[T,z]}convertHandlerReturnTypeToMapOfTensors(p){const g={};for(const M in p)if(Object.hasOwnProperty.call(p,M)){const w=p[M];w instanceof a.Tensor?g[M]=w:g[M]=new a.Tensor(w.type,w.data,w.dims)}return g}async lazyResetGrad(){await this.handler.lazyResetGrad()}async runTrainStep(p,g,M){const[w,C]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,p,g,M),T=await this.handler.runTrainStep(p,w,C);return this.convertHandlerReturnTypeToMapOfTensors(T)}async runOptimizerStep(p){if(this.hasOptimizerModel)await this.handler.runOptimizerStep(p||{});else throw new Error("This TrainingSession has no OptimizerModel loaded.")}async runEvalStep(p,g,M){if(this.hasEvalModel){const[w,C]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,p,g,M),T=await this.handler.runEvalStep(p,w,C);return this.convertHandlerReturnTypeToMapOfTensors(T)}else throw new Error("This TrainingSession has no EvalModel loaded.")}async getParametersSize(p=!0){return this.handler.getParametersSize(p)}async loadParametersBuffer(p,g=!0){const M=await this.getParametersSize(g);if(p.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(p,g)}async getContiguousParameters(p=!0){return this.handler.getContiguousParameters(p)}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:()=>ne,TRACE:()=>je,TRACE_FUNC_BEGIN:()=>et,TRACE_FUNC_END:()=>A,Tensor:()=>Ge,TrainingSession:()=>dt,default:()=>wx,env:()=>D,registerBackend:()=>z});/*! + * ONNX Runtime Web v1.19.0-dev.20240804-ee2fe87e2d + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */var o=Object.defineProperty,a=Object.getOwnPropertyDescriptor,l=Object.getOwnPropertyNames,f=Object.prototype.hasOwnProperty,_=(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')}),p=(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))!f.call(n,c)&&c!==s&&o(n,c,{get:()=>i[c],enumerable:!(u=a(i,c))||u.enumerable});return n},w=n=>M(o({},"__esModule",{value:!0}),n),C,T,z,S,E,y=p(()=>{C=new Map,T=[],z=(n,i,s)=>{if(i&&typeof i.init=="function"&&typeof i.createInferenceSessionHandler=="function"){let u=C.get(n);if(u===void 0)C.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 h=0;h{let i=C.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}}},E=async n=>{let i=n.executionProviders||[],s=i.map(k=>typeof k=="string"?k:k.name),u=s.length===0?T:s,c,h=[],d=new Set;for(let k of u){let $=await S(k);typeof $=="string"?h.push({name:k,err:$}):(c||(c=$),c===$&&d.add(k))}if(!c)throw new Error(`no available backend found. ERR: ${h.map(k=>`[${k.name}] ${k.err}`).join(", ")}`);for(let{name:k,err:$}of h)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=p(()=>{y()}),I,V=p(()=>{I="1.19.0-dev.20240730-530a2d7b41"}),O,N,j=p(()=>{V(),O="warning",N={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}`);O=n}},get logLevel(){return O}},Object.defineProperty(N,"logLevel",{enumerable:!0})}),D,ee=p(()=>{j(),D=N}),de,Ce,te=p(()=>{de=(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,h;(i==null?void 0:i.tensorLayout)!==void 0&&i.tensorLayout==="NHWC"?(c=n.dims[2],h=n.dims[3]):(c=n.dims[3],h=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=h*c,q=0,v=H,oe=H*2,re=-1;d==="RGBA"?(q=0,v=H,oe=H*2,re=H*3):d==="RGB"?(q=0,v=H,oe=H*2):d==="RBG"&&(q=0,oe=H,v=H*2);for(let ce=0;ce{let s=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),u;if(s!=null){let c,h,d;(i==null?void 0:i.tensorLayout)!==void 0&&i.tensorLayout==="NHWC"?(c=n.dims[2],h=n.dims[1],d=n.dims[3]):(c=n.dims[3],h=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=h*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,re=1,ce=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,h);for(let Ie=0;Ie{ft(),_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},h,d;typeof c.mean=="number"?h=[c.mean,c.mean,c.mean,c.mean]:h=[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,re=2,ce=3,we=0,be=$,he=$*2,De=-1;x==="RGB"&&(q=3,v=0,oe=1,re=2,ce=-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,re+=q,oe+=q,ce+=q)H[we++]=(n[v]+d[0])/h[0],H[be++]=(n[oe]+d[1])/h[1],H[he++]=(n[re]+d[2])/h[2],De!==-1&&ce!==-1&&(H[De++]=(n[ce]+d[3])/h[3]);return k==="RGBA"?new st("float32",H,[1,4,s,u]):new st("float32",H,[1,3,s,u])},R=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,h=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(h)return new Promise((H,q)=>{let v=k(),oe=$(v);if(!n||!oe)return q();let re=new Image;re.crossOrigin="Anonymous",re.src=n,re.onload=()=>{v.width=re.width,v.height=re.height,oe.drawImage(re,0,0,v.width,v.height);let ce=oe.getImageData(0,0,v.width,v.height);x.height=v.height,x.width=v.width,H(_e(ce.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")},xe=(n,i)=>{let{width:s,height:u,download:c,dispose:h}=i,d=[1,u,s,4];return new st({location:"texture",type:"float32",texture:n,dims:d,download:c,dispose:h})},Xe=(n,i)=>{let{dataType:s,dims:u,download:c,dispose:h}=i;return new st({location:"gpu-buffer",type:s??"float32",gpuBuffer:n,dims:u,download:c,dispose:h})},ge=(n,i,s)=>new st({location:"cpu-pinned",type:n,data:i,dims:s??[i.length]})}),ae,Se,Q,me,Ke=p(()=>{ae=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array]]),Se=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),Q=!1,me=()=>{if(!Q){Q=!0;let n=typeof BigInt64Array<"u"&&BigInt64Array.from,i=typeof BigUint64Array<"u"&&BigUint64Array.from,s=typeof Float16Array<"u"&&Float16Array.from;n&&(ae.set("int64",BigInt64Array),Se.set(BigInt64Array,"int64")),i&&(ae.set("uint64",BigUint64Array),Se.set(BigUint64Array,"uint64")),s?(ae.set("float16",Float16Array),Se.set(Float16Array,"float16")):ae.set("float16",Uint16Array)}}}),Le,Be,We=p(()=>{ft(),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,ft=p(()=>{te(),X(),Ke(),We(),st=class{constructor(n,i,s){me();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=ae.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=ae.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=Se.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 h=Le(c);if(this.cpuData&&h!==this.cpuData.length)throw new Error(`Tensor's size(${h}) does not match data length(${this.cpuData.length}).`);this.type=u,this.dims=c,this.size=h}static async fromImage(n,i){return R(n,i)}static fromTexture(n,i){return xe(n,i)}static fromGpuBuffer(n,i){return Xe(n,i)}static fromPinnedBuffer(n,i,s){return ge(n,i,s)}toDataURL(n){return de(this,n)}toImageData(n){return Ce(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,Me=p(()=>{ft(),Ge=st}),je,Ye,et,A,$e=p(()=>{j(),je=(n,i)=>{(typeof N.trace>"u"?!N.wasm.trace:!N.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 h=0;h{(typeof N.trace>"u"?!N.wasm.trace:!N.trace)||Ye("BEGIN",n)},A=n=>{(typeof N.trace>"u"?!N.wasm.trace:!N.trace)||Ye("END",n)}}),Pe,se=p(()=>{y(),Me(),$e(),Pe=class Z2{constructor(i){this.handler=i}async run(i,s,u){et();let c={},h={};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)h=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)h=u;else if(typeof u<"u")throw new TypeError("'options' must be an object.")}else h=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,h),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 h,d={};if(typeof i=="string"){if(h=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(h=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.");h=new Uint8Array(H,q,v)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[x,k]=await E(d),$=await x.createInferenceSessionHandler(h,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}}}),ne,ye=p(()=>{se(),ne=Pe}),B=p(()=>{}),J=p(()=>{}),L=p(()=>{}),ue=p(()=>{}),le,Te,Ne=p(()=>{y(),Me(),le="Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.",Te=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||"",h=s||{},[d,x]=await E(h);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,h){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 h=="object"&&h!==null)x=h;else if(typeof h<"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 h=="object"&&h!==null)x=h;else if(typeof h<"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,h]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,i,s,u),d=await this.handler.runTrainStep(i,c,h);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,h]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,i,s,u),d=await this.handler.runEvalStep(i,c,h);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=p(()=>{Ne(),dt=Te}),Ve={};g(Ve,{InferenceSession:()=>ne,TRACE:()=>je,TRACE_FUNC_BEGIN:()=>et,TRACE_FUNC_END:()=>A,Tensor:()=>Ge,TrainingSession:()=>dt,env:()=>D,registerBackend:()=>z});var Y=p(()=>{b(),ee(),ye(),Me(),B(),J(),$e(),L(),ue(),Je()}),ve=p(()=>{}),Re={};g(Re,{default:()=>tt});var qe,Qe,tt,pt=p(()=>{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:h}=u;Mm(h,c).then(()=>{postMessage({type:s})},d=>{postMessage({type:s,err:d})});break}case"copy-from":{let{buffer:c}=u,h=Ip(c);postMessage({type:s,out:h});break}case"create":{let{model:c,options:h}=u;Tm(c,h).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:h,inputs:d,outputIndices:x,options:k}=u;Em(c,h,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,vt,Et,Lt=p(()=>{var n;vt=(Tt=import.meta.url,async function(i={}){function s(){return fr.buffer!=er.buffer&&On(),er}function u(){return fr.buffer!=er.buffer&&On(),_r}function c(){return fr.buffer!=er.buffer&&On(),ot}function h(){return fr.buffer!=er.buffer&&On(),Wt}function d(){return fr.buffer!=er.buffer&&On(),ir}function x(){return fr.buffer!=er.buffer&&On(),Vr}function k(){return fr.buffer!=er.buffer&&On(),fn}function $(){return fr.buffer!=er.buffer&&On(),si}var H,q,v=Object.assign({},i),oe=new Promise((m,F)=>{H=m,q=F}),re=typeof window=="object",ce=typeof importScripts=="function",we=ce&&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,Z,pe)=>(...Oe)=>{let lt=io,wt=Z==null?void 0:Z();Oe=K(...Oe);let Ct=Z==null?void 0:Z();return wt!==Ct&&(K=Ct,pe(wt),Z=pe=null),io!=lt?new Promise((Ft,Qt)=>{qm={resolve:Ft,reject:Qt}}):Oe},F=K=>async(...Z)=>{var pe;try{if(v.Eb)throw Error("Session already started");let Oe=v.Eb={bc:Z[0],errors:[]},lt=await K(...Z);if(v.Eb!==Oe)throw Error("Session mismatch");(pe=v.Mb)==null||pe.flush();let wt=Oe.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=(Z,pe,Oe,lt)=>K.registerBuffer(Z,pe,Oe,lt),v.jsepGetBuffer=Z=>K.getBuffer(Z),v.jsepCreateDownloader=(Z,pe,Oe)=>K.createDownloader(Z,pe,Oe),v.jsepOnReleaseSession=Z=>{K.onReleaseSession(Z)},v.jsepOnRunStart=Z=>K.onRunStart(Z)}};var De,Ae,Ie=Object.assign({},v),gt="./this.program",ut=(m,F)=>{throw F},yt="";(re||ce)&&(ce?yt=self.location.href:typeof document<"u"&&document.currentScript&&(yt=document.currentScript.src),Tt&&(yt=Tt),yt=yt.startsWith("blob:")?"":yt.substr(0,yt.replace(/[?#].*/,"").lastIndexOf("/")+1),ce&&(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 Z=new XMLHttpRequest;Z.open("GET",m,!0),Z.responseType="arraybuffer",Z.onload=()=>{Z.status==200||Z.status==0&&Z.response?F(Z.response):K()},Z.onerror=K,Z.send(null)});var Dt,Bt=console.log.bind(console),mr=console.error.bind(console),vr=Bt,or=mr;if(Object.assign(v,Ie),Ie=null,we){let m=function(F){try{var K=F.data,Z=K.cmd;if(Z==="load"){let pe=[];self.onmessage=Oe=>pe.push(Oe),self.startWorker=()=>{postMessage({cmd:"loaded"});for(let Oe of pe)m(Oe);self.onmessage=m};for(let Oe of K.handlers)v[Oe]&&!v[Oe].proxy||(v[Oe]=(...lt)=>{postMessage({Lb:"callHandler",kc:Oe,args:lt})},Oe=="print"&&(vr=v[Oe]),Oe=="printErr"&&(or=v[Oe]));fr=K.wasmMemory,On(),Ir(K.wasmModule)}else if(Z==="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(pe){if(pe!="unwind")throw pe}}else Z==="cancel"?Il()&&Hp(-1):K.target!=="setimmediate"&&(Z==="checkMailbox"?Zr&&Lp():Z&&(or(`worker: received unknown command ${Z}`),or(K)))}catch(pe){throw Gy(),pe}};var Ir,Zr=!1;or=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(Z=>{Ir=pe=>{pe=new WebAssembly.Instance(pe,Uw()),K(pe),Z()}}),self.onunhandledrejection=F=>{throw F.reason||F},self.onmessage=m}v.wasmBinary&&(Dt=v.wasmBinary);var fr,Gr,jt,er,_r,ot,Wt,ir,Vr,fn,kn,rs,si,gi=!1;function On(){var m=fr.buffer;v.HEAP8=er=new Int8Array(m),v.HEAP16=ot=new Int16Array(m),v.HEAPU8=_r=new Uint8Array(m),v.HEAPU16=Wt=new Uint16Array(m),v.HEAP32=ir=new Int32Array(m),v.HEAPU32=Vr=new Uint32Array(m),v.HEAPF32=fn=new Float32Array(m),v.HEAPF64=si=new Float64Array(m),v.HEAP64=kn=new BigInt64Array(m),v.HEAPU64=rs=new BigUint64Array(m)}if(!we){if(!((fr=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0})).buffer instanceof be))throw or("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");On()}var uf=[],Dn=[],Jn=[],$i=0,ns=null;function Op(){if(--$i==0&&ns){var m=ns;ns=null,m()}}function Pl(m){throw or(m="Aborted("+m+")"),gi=!0,jt=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(Z){if(!Dt&&(re||ce)){if(typeof fetch=="function"&&!Bw(Z))return fetch(Z,{credentials:"same-origin"}).then(pe=>{if(!pe.ok)throw`failed to load wasm binary file at '${Z}'`;return pe.arrayBuffer()}).catch(()=>Nw(Z));if(De)return new Promise((pe,Oe)=>{De(Z,lt=>pe(new Uint8Array(lt)),Oe)})}return Promise.resolve().then(()=>Nw(Z))}(m).then(Z=>WebAssembly.instantiate(Z,F)).then(K,Z=>{or(`failed to asynchronously prepare wasm: ${Z}`),Pl(Z)})}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:fy,W:py,va:kx,D:Sx,P:Ex,O:Px,C:Ax,s:Ix,p:Fx,E:zx,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:fM,j:pM,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:zy,_:Lm,A:Oy,I:Dy,ha:Ly,H:Ry,a:fr,wa:Dm,ua:jy,q:zM}}}var Fm={848436:(m,F,K,Z)=>{if(v===void 0||!v.Fb)return 1;if((m=$n(m>>>0)).startsWith("./")&&(m=m.substring(2)),!(m=v.Fb.get(m)))return 2;if(Z>>>=0,(F>>>=0)+(K>>>=0)>m.byteLength)return 3;try{return u().set(m.subarray(F,F+K),Z>>>0),0}catch{return 4}},848937:()=>{v.Ub()},848968:()=>{v.Vb()},848997:()=>{v.Zb()},849022:m=>v.Tb(m),849055:m=>v.Xb(m),849087:(m,F,K)=>{v.Nb(m,F,K,!0)},849126:(m,F,K)=>{v.Nb(m,F,K)},849159:()=>typeof wasmOffsetConverter<"u",849216:m=>{v.jb("Abs",m,void 0)},849267:m=>{v.jb("Neg",m,void 0)},849318:m=>{v.jb("Floor",m,void 0)},849371:m=>{v.jb("Ceil",m,void 0)},849423:m=>{v.jb("Reciprocal",m,void 0)},849481:m=>{v.jb("Sqrt",m,void 0)},849533:m=>{v.jb("Exp",m,void 0)},849584:m=>{v.jb("Erf",m,void 0)},849635:m=>{v.jb("Sigmoid",m,void 0)},849690:(m,F,K)=>{v.jb("HardSigmoid",m,{alpha:F,beta:K})},849769:m=>{v.jb("Log",m,void 0)},849820:m=>{v.jb("Sin",m,void 0)},849871:m=>{v.jb("Cos",m,void 0)},849922:m=>{v.jb("Tan",m,void 0)},849973:m=>{v.jb("Asin",m,void 0)},850025:m=>{v.jb("Acos",m,void 0)},850077:m=>{v.jb("Atan",m,void 0)},850129:m=>{v.jb("Sinh",m,void 0)},850181:m=>{v.jb("Cosh",m,void 0)},850233:m=>{v.jb("Asinh",m,void 0)},850286:m=>{v.jb("Acosh",m,void 0)},850339:m=>{v.jb("Atanh",m,void 0)},850392:m=>{v.jb("Tanh",m,void 0)},850444:m=>{v.jb("Not",m,void 0)},850495:(m,F,K)=>{v.jb("Clip",m,{min:F,max:K})},850564:m=>{v.jb("Clip",m,void 0)},850616:(m,F)=>{v.jb("Elu",m,{alpha:F})},850674:m=>{v.jb("Relu",m,void 0)},850726:(m,F)=>{v.jb("LeakyRelu",m,{alpha:F})},850790:(m,F)=>{v.jb("ThresholdedRelu",m,{alpha:F})},850860:(m,F)=>{v.jb("Cast",m,{to:F})},850918:m=>{v.jb("Add",m,void 0)},850969:m=>{v.jb("Sub",m,void 0)},851020:m=>{v.jb("Mul",m,void 0)},851071:m=>{v.jb("Div",m,void 0)},851122:m=>{v.jb("Pow",m,void 0)},851173:m=>{v.jb("Equal",m,void 0)},851226:m=>{v.jb("Greater",m,void 0)},851281:m=>{v.jb("GreaterOrEqual",m,void 0)},851343:m=>{v.jb("Less",m,void 0)},851395:m=>{v.jb("LessOrEqual",m,void 0)},851454:(m,F,K,Z,pe)=>{v.jb("ReduceMean",m,{keepDims:!!F,noopWithEmptyAxes:!!K,axes:Z?Array.from(d().subarray(Z>>>0,pe>>>0)):[]})},851613:(m,F,K,Z,pe)=>{v.jb("ReduceMax",m,{keepDims:!!F,noopWithEmptyAxes:!!K,axes:Z?Array.from(d().subarray(Z>>>0,pe>>>0)):[]})},851771:(m,F,K,Z,pe)=>{v.jb("ReduceMin",m,{keepDims:!!F,noopWithEmptyAxes:!!K,axes:Z?Array.from(d().subarray(Z>>>0,pe>>>0)):[]})},851929:(m,F,K,Z,pe)=>{v.jb("ReduceProd",m,{keepDims:!!F,noopWithEmptyAxes:!!K,axes:Z?Array.from(d().subarray(Z>>>0,pe>>>0)):[]})},852088:(m,F,K,Z,pe)=>{v.jb("ReduceSum",m,{keepDims:!!F,noopWithEmptyAxes:!!K,axes:Z?Array.from(d().subarray(Z>>>0,pe>>>0)):[]})},852246:(m,F,K,Z,pe)=>{v.jb("ReduceL1",m,{keepDims:!!F,noopWithEmptyAxes:!!K,axes:Z?Array.from(d().subarray(Z>>>0,pe>>>0)):[]})},852403:(m,F,K,Z,pe)=>{v.jb("ReduceL2",m,{keepDims:!!F,noopWithEmptyAxes:!!K,axes:Z?Array.from(d().subarray(Z>>>0,pe>>>0)):[]})},852560:(m,F,K,Z,pe)=>{v.jb("ReduceLogSum",m,{keepDims:!!F,noopWithEmptyAxes:!!K,axes:Z?Array.from(d().subarray(Z>>>0,pe>>>0)):[]})},852721:(m,F,K,Z,pe)=>{v.jb("ReduceSumSquare",m,{keepDims:!!F,noopWithEmptyAxes:!!K,axes:Z?Array.from(d().subarray(Z>>>0,pe>>>0)):[]})},852885:(m,F,K,Z,pe)=>{v.jb("ReduceLogSumExp",m,{keepDims:!!F,noopWithEmptyAxes:!!K,axes:Z?Array.from(d().subarray(Z>>>0,pe>>>0)):[]})},853049:m=>{v.jb("Where",m,void 0)},853102:(m,F,K)=>{v.jb("Transpose",m,{perm:F?Array.from(d().subarray(F>>>0,K>>>0)):[]})},853210:(m,F,K,Z)=>{v.jb("DepthToSpace",m,{blocksize:F,mode:$n(K),format:Z?"NHWC":"NCHW"})},853343:(m,F,K,Z)=>{v.jb("DepthToSpace",m,{blocksize:F,mode:$n(K),format:Z?"NHWC":"NCHW"})},853476:(m,F,K,Z,pe,Oe,lt,wt,Ct,Ft,Qt,Fr,Rr,it,lr)=>{v.jb("ConvTranspose",m,{format:Ct?"NHWC":"NCHW",autoPad:F,dilations:[K],group:Z,kernelShape:[pe],pads:[Oe,lt],strides:[wt],wIsConst:()=>!!s()[Ft>>>0],outputPadding:Qt?Array.from(d().subarray(Qt>>>0,Fr>>>0)):[],outputShape:Rr?Array.from(d().subarray(Rr>>>0,it>>>0)):[],activation:$n(lr)})},853877:(m,F,K,Z,pe,Oe,lt,wt,Ct,Ft,Qt,Fr,Rr,it)=>{v.jb("ConvTranspose",m,{format:wt?"NHWC":"NCHW",autoPad:F,dilations:Array.from(d().subarray(K>>>0,2+(K>>>0)>>>0)),group:Z,kernelShape:Array.from(d().subarray(pe>>>0,2+(pe>>>0)>>>0)),pads:Array.from(d().subarray(Oe>>>0,4+(Oe>>>0)>>>0)),strides:Array.from(d().subarray(lt>>>0,2+(lt>>>0)>>>0)),wIsConst:()=>!!s()[Ct>>>0],outputPadding:Ft?Array.from(d().subarray(Ft>>>0,Qt>>>0)):[],outputShape:Fr?Array.from(d().subarray(Fr>>>0,Rr>>>0)):[],activation:$n(it)})},854442:(m,F,K,Z,pe,Oe,lt,wt,Ct,Ft,Qt,Fr,Rr,it,lr)=>{v.jb("ConvTranspose",m,{format:Ct?"NHWC":"NCHW",autoPad:F,dilations:[K],group:Z,kernelShape:[pe],pads:[Oe,lt],strides:[wt],wIsConst:()=>!!s()[Ft>>>0],outputPadding:Qt?Array.from(d().subarray(Qt>>>0,Fr>>>0)):[],outputShape:Rr?Array.from(d().subarray(Rr>>>0,it>>>0)):[],activation:$n(lr)})},854843:(m,F,K,Z,pe,Oe,lt,wt,Ct,Ft,Qt,Fr,Rr,it)=>{v.jb("ConvTranspose",m,{format:wt?"NHWC":"NCHW",autoPad:F,dilations:Array.from(d().subarray(K>>>0,2+(K>>>0)>>>0)),group:Z,kernelShape:Array.from(d().subarray(pe>>>0,2+(pe>>>0)>>>0)),pads:Array.from(d().subarray(Oe>>>0,4+(Oe>>>0)>>>0)),strides:Array.from(d().subarray(lt>>>0,2+(lt>>>0)>>>0)),wIsConst:()=>!!s()[Ct>>>0],outputPadding:Ft?Array.from(d().subarray(Ft>>>0,Qt>>>0)):[],outputShape:Fr?Array.from(d().subarray(Fr>>>0,Rr>>>0)):[],activation:$n(it)})},855408:(m,F)=>{v.jb("GlobalAveragePool",m,{format:F?"NHWC":"NCHW"})},855499:(m,F,K,Z,pe,Oe,lt,wt,Ct,Ft,Qt,Fr,Rr,it,lr,Br)=>{v.jb("AveragePool",m,{format:Br?"NHWC":"NCHW",auto_pad:F,ceil_mode:K,count_include_pad:Z,storage_order:pe,dilations:[Oe,lt],kernel_shape:[wt,Ct],pads:[Ft,Qt,Fr,Rr],strides:[it,lr]})},855783:(m,F)=>{v.jb("GlobalAveragePool",m,{format:F?"NHWC":"NCHW"})},855874:(m,F,K,Z,pe,Oe,lt,wt,Ct,Ft,Qt,Fr,Rr,it,lr,Br)=>{v.jb("AveragePool",m,{format:Br?"NHWC":"NCHW",auto_pad:F,ceil_mode:K,count_include_pad:Z,storage_order:pe,dilations:[Oe,lt],kernel_shape:[wt,Ct],pads:[Ft,Qt,Fr,Rr],strides:[it,lr]})},856158:(m,F)=>{v.jb("GlobalMaxPool",m,{format:F?"NHWC":"NCHW"})},856245:(m,F,K,Z,pe,Oe,lt,wt,Ct,Ft,Qt,Fr,Rr,it,lr,Br)=>{v.jb("MaxPool",m,{format:Br?"NHWC":"NCHW",auto_pad:F,ceil_mode:K,count_include_pad:Z,storage_order:pe,dilations:[Oe,lt],kernel_shape:[wt,Ct],pads:[Ft,Qt,Fr,Rr],strides:[it,lr]})},856525:(m,F)=>{v.jb("GlobalMaxPool",m,{format:F?"NHWC":"NCHW"})},856612:(m,F,K,Z,pe,Oe,lt,wt,Ct,Ft,Qt,Fr,Rr,it,lr,Br)=>{v.jb("MaxPool",m,{format:Br?"NHWC":"NCHW",auto_pad:F,ceil_mode:K,count_include_pad:Z,storage_order:pe,dilations:[Oe,lt],kernel_shape:[wt,Ct],pads:[Ft,Qt,Fr,Rr],strides:[it,lr]})},856892:(m,F,K,Z,pe)=>{v.jb("Gemm",m,{alpha:F,beta:K,transA:Z,transB:pe})},856996:m=>{v.jb("MatMul",m,void 0)},857050:(m,F,K,Z)=>{v.jb("ArgMax",m,{keepDims:!!F,selectLastIndex:!!K,axis:Z})},857158:(m,F,K,Z)=>{v.jb("ArgMin",m,{keepDims:!!F,selectLastIndex:!!K,axis:Z})},857266:(m,F)=>{v.jb("Softmax",m,{axis:F})},857329:(m,F)=>{v.jb("Concat",m,{axis:F})},857389:(m,F,K,Z,pe)=>{v.jb("Split",m,{axis:F,numOutputs:K,splitSizes:Z?Array.from(d().subarray(Z>>>0,pe>>>0)):[]})},857529:m=>{v.jb("Expand",m,void 0)},857583:(m,F)=>{v.jb("Gather",m,{axis:Number(F)})},857654:(m,F)=>{v.jb("GatherElements",m,{axis:Number(F)})},857733:(m,F,K,Z,pe,Oe,lt,wt,Ct,Ft,Qt)=>{v.jb("Resize",m,{antialias:F,axes:K?Array.from(d().subarray(K>>>0,Z>>>0)):[],coordinateTransformMode:$n(pe),cubicCoeffA:Oe,excludeOutside:lt,extrapolationValue:wt,keepAspectRatioPolicy:$n(Ct),mode:$n(Ft),nearestMode:$n(Qt)})},858079:(m,F,K,Z,pe,Oe,lt)=>{v.jb("Slice",m,{starts:F?Array.from(d().subarray(F>>>0,K>>>0)):[],ends:Z?Array.from(d().subarray(Z>>>0,pe>>>0)):[],axes:Oe?Array.from(d().subarray(Oe>>>0,lt>>>0)):[]})},858295:m=>{v.jb("Tile",m,void 0)},858347:(m,F,K)=>{v.jb("InstanceNormalization",m,{epsilon:F,format:K?"NHWC":"NCHW"})},858461:(m,F,K)=>{v.jb("InstanceNormalization",m,{epsilon:F,format:K?"NHWC":"NCHW"})},858575:m=>{v.jb("Range",m,void 0)},858628:(m,F)=>{v.jb("Einsum",m,{equation:$n(F)})},858709:(m,F,K,Z,pe)=>{v.jb("Pad",m,{mode:F,value:K,pads:Z?Array.from(d().subarray(Z>>>0,pe>>>0)):[]})},858836:(m,F,K,Z,pe,Oe)=>{v.jb("BatchNormalization",m,{epsilon:F,momentum:K,spatial:!!pe,trainingMode:!!Z,format:Oe?"NHWC":"NCHW"})},859005:(m,F,K,Z,pe,Oe)=>{v.jb("BatchNormalization",m,{epsilon:F,momentum:K,spatial:!!pe,trainingMode:!!Z,format:Oe?"NHWC":"NCHW"})},859174:(m,F,K)=>{v.jb("CumSum",m,{exclusive:Number(F),reverse:Number(K)})},859271:(m,F,K,Z,pe,Oe,lt,wt,Ct)=>{v.jb("Attention",m,{numHeads:F,isUnidirectional:K,maskFilterValue:Z,scale:pe,doRotary:Oe,qkvHiddenSizes:lt?Array.from(d().subarray(Number(wt)>>>0,Number(wt)+lt>>>0)):[],pastPresentShareBuffer:!!Ct})},859543:m=>{v.jb("BiasAdd",m,void 0)},859598:m=>{v.jb("BiasSplitGelu",m,void 0)},859659:m=>{v.jb("FastGelu",m,void 0)},859715:(m,F,K,Z,pe,Oe,lt,wt,Ct,Ft,Qt,Fr,Rr,it,lr,Br)=>{v.jb("Conv",m,{format:Fr?"NHWC":"NCHW",auto_pad:F,dilations:K?Array.from(d().subarray(K>>>0,Z>>>0)):[],group:pe,kernel_shape:Oe?Array.from(d().subarray(Oe>>>0,lt>>>0)):[],pads:wt?Array.from(d().subarray(wt>>>0,Ct>>>0)):[],strides:Ft?Array.from(d().subarray(Ft>>>0,Qt>>>0)):[],w_is_const:()=>!!s()[Rr>>>0],activation:$n(it),activation_params:lr?Array.from(k().subarray(lr>>>0,Br>>>0)):[]})},860211:m=>{v.jb("Gelu",m,void 0)},860263:(m,F,K,Z)=>{v.jb("GroupQueryAttention",m,{numHeads:F,kvNumHeads:K,scale:Z})},860376:(m,F,K,Z)=>{v.jb("LayerNormalization",m,{axis:F,epsilon:K,simplified:!!Z})},860487:(m,F,K,Z)=>{v.jb("LayerNormalization",m,{axis:F,epsilon:K,simplified:!!Z})},860598:(m,F,K,Z,pe,Oe)=>{v.jb("MatMulNBits",m,{k:F,n:K,accuracyLevel:Z,bits:pe,blockSize:Oe})},860725:(m,F,K,Z,pe,Oe)=>{v.jb("MultiHeadAttention",m,{numHeads:F,isUnidirectional:K,maskFilterValue:Z,scale:pe,doRotary:Oe})},860884:(m,F)=>{v.jb("QuickGelu",m,{alpha:F})},860948:(m,F,K,Z,pe)=>{v.jb("RotaryEmbedding",m,{interleaved:!!F,numHeads:K,rotaryEmbeddingDim:Z,scale:pe})},861087:(m,F,K)=>{v.jb("SkipLayerNormalization",m,{epsilon:F,simplified:!!K})},861189:m=>{v.Yb(m)},861223:(m,F)=>v.$b(m,F,v.Eb.bc,v.Eb.errors),861335:(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 zm(m){this.name="ExitStatus",this.message=`Program terminated with exit(${m})`,this.status=m}var Om=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 Z=2*K.length,pe=eg(),Oe=Jm(8*Z),lt=Oe>>>3,wt=0;wt>>0]=Ct)}return m=Hy(m,0,Z,Oe,F),qp(pe),m};function Dm(m){if(we)return rn(0,1,m);if(jt=m,!(0{if(jt=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=pe=>{var Oe=(pe=pe.data).cmd;if(pe.targetThread&&pe.targetThread!=Il()){var lt=ro[pe.targetThread];lt?lt.postMessage(pe,pe.transferList):or(`Internal error! Worker sent a message "${Oe}" to target pthread ${pe.targetThread}, but that thread no longer exists!`)}else Oe==="checkMailbox"?Lp():Oe==="spawnThread"?Vw(pe):Oe==="cleanupThread"?Hw(ro[pe.thread]):Oe==="killThread"?(pe=pe.thread,Oe=ro[pe],delete ro[pe],Om(Oe),Zm(pe),Zs.splice(Zs.indexOf(Oe),1),Oe.Ab=0):Oe==="cancelThread"?ro[pe.thread].postMessage({cmd:"cancel"}):Oe==="loaded"?(m.loaded=!0,F(m)):Oe==="alert"?alert(`Thread ${pe.threadId}: ${pe.text}`):pe.target==="setimmediate"?m.postMessage(pe):Oe==="callHandler"?v[pe.handler](...pe.args):Oe&&or(`worker sent an unknown command ${Oe}`)},m.onerror=pe=>{throw or(`worker sent an error! ${pe.filename}:${pe.lineno}: ${pe.message}`),pe};var K,Z=[];for(K of[])v.hasOwnProperty(K)&&Z.push(K);m.postMessage({cmd:"load",handlers:Z,wasmMemory:fr,wasmModule:Gr})});function Xw(){var m=new Worker(new URL(import.meta.url),{type:"module",workerData:"em-pthread",name:"em-pthread"});is.push(m)}var Dp=m=>{for(;0{var m=Il(),F=x()[m+52>>>2>>>0];m=x()[m+56>>>2>>>0],Ky(F,F-m),qp(F)},xx=(m,F)=>{Ys=0,m=Xy(m,F),0>>=0);throw F>>>=0,K>>>=0,x()[Z.Ib+16>>>2>>>0]=0,x()[Z.Ib+4>>>2>>>0]=F,x()[Z.Ib+8>>>2>>>0]=K,m}function Qw(m,F,K,Z){return we?rn(2,1,m,F,K,Z):Yw(m,F,K,Z)}function Yw(m,F,K,Z){if(m>>>=0,F>>>=0,K>>>=0,Z>>>=0,be===void 0)return or("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var pe=[];return we&&pe.length===0?Qw(m,F,K,Z):(m={cc:K,Ab:m,Pb:Z,ic:pe},we?(m.Lb="spawnThread",postMessage(m,pe),0):Vw(m))}var Zw=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,Jw=(m,F,K)=>{var Z=(F>>>=0)+K;for(K=F;m[K]&&!(K>=Z);)++K;if(16(pe=(240&pe)==224?(15&pe)<<12|Oe<<6|lt:(7&pe)<<18|Oe<<12|lt<<6|63&m[F++])?Z+=String.fromCharCode(pe):(pe-=65536,Z+=String.fromCharCode(55296|pe>>10,56320|1023&pe))}}else Z+=String.fromCharCode(pe)}return Z},$n=(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=Z?F++:2047>=Z?F+=2:55296<=Z&&57343>=Z?(F+=4,++K):F+=3}return F},ry=(m,F,K,Z)=>{if(!(0>>=0;Z=K+Z-1;for(var Oe=0;Oe=lt&&(lt=65536+((1023<)<<10)|1023&m.charCodeAt(++Oe)),127>=lt){if(K>=Z)break;F[K++>>>0]=lt}else{if(2047>=lt){if(K+1>=Z)break;F[K++>>>0]=192|lt>>6}else{if(65535>=lt){if(K+2>=Z)break;F[K++>>>0]=224|lt>>12}else{if(K+3>=Z)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-pe},$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,Z){if(we)return rn(10,1,m,F,K,Z)}function uy(m,F,K,Z){if(we)return rn(11,1,m,F,K,Z)}function cy(m,F,K,Z){if(we)return rn(12,1,m,F,K,Z)}function dy(m){if(we)return rn(13,1,m)}function fy(m,F){if(we)return rn(14,1,m,F)}function py(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(Z,pe,Oe={}){var lt=pe.name;if(!Z)throw new os(`type "${lt}" must have a positive integer typeid pointer`);if(Nm.hasOwnProperty(Z)){if(Oe.Rb)return;throw new os(`Cannot register type '${lt}' twice`)}Nm[Z]=pe,Bm.hasOwnProperty(Z)&&(pe=Bm[Z],delete Bm[Z],pe.forEach(wt=>wt()))}(m,F,K)}var my=(m,F,K)=>{switch(F){case 1:return K?Z=>s()[Z>>>0]:Z=>u()[Z>>>0];case 2:return K?Z=>c()[Z>>>1>>>0]:Z=>h()[Z>>>1>>>0];case 4:return K?Z=>d()[Z>>>2>>>0]:Z=>x()[Z>>>2>>>0];case 8:return K?Z=>kn[Z>>>3]:Z=>rs[Z>>>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:Z=>Z,toWireType:function(Z,pe){if(typeof pe!="bigint"&&typeof pe!="number")throw pe=pe===null?"null":(Z=typeof pe)=="object"||Z==="array"||Z==="function"?pe.toString():""+pe,new TypeError(`Cannot convert "${pe}" to ${this.name}`);return typeof pe=="number"&&(pe=BigInt(pe)),pe},argPackAdvance:ss,readValueFromPointer:my(F,K,F.indexOf("u")==-1),Db:null})}var ss=8;function Ex(m,F,K,Z){Mo(m>>>=0,{name:F=no(F>>>0),fromWireType:function(pe){return!!pe},toWireType:function(pe,Oe){return Oe?K:Z},argPackAdvance:ss,readValueFromPointer:function(pe){return this.fromWireType(u()[pe>>>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:Z=>Z,toWireType:(Z,pe)=>pe,argPackAdvance:ss,readValueFromPointer:$x(F,K),Db:null})}function Ix(m,F,K,Z,pe){if(m>>>=0,K>>>=0,F=no(F>>>0),pe===-1&&(pe=4294967295),pe=wt=>wt,Z===0){var Oe=32-8*K;pe=wt=>wt<>>Oe}var lt=F.includes("unsigned")?function(wt,Ct){return Ct>>>0}:function(wt,Ct){return Ct};Mo(m,{name:F,fromWireType:pe,toWireType:lt,argPackAdvance:ss,readValueFromPointer:my(F,K,Z!==0),Db:null})}function Fx(m,F,K){function Z(Oe){var lt=x()[Oe>>>2>>>0];return Oe=x()[Oe+4>>>2>>>0],new pe(s().buffer,Oe,lt)}var pe=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][F];Mo(m>>>=0,{name:K=no(K>>>0),fromWireType:Z,argPackAdvance:ss,readValueFromPointer:Z},{Rb:!0})}function zx(m,F){m>>>=0;var K=(F=no(F>>>0))==="std::string";Mo(m,{name:F,fromWireType:function(Z){var pe=x()[Z>>>2>>>0],Oe=Z+4;if(K)for(var lt=Oe,wt=0;wt<=pe;++wt){var Ct=Oe+wt;if(wt==pe||u()[Ct>>>0]==0){if(lt=$n(lt,Ct-lt),Ft===void 0)var Ft=lt;else Ft+="\0",Ft+=lt;lt=Ct+1}}else{for(Ft=Array(pe),wt=0;wt>>0]);Ft=Ft.join("")}return oo(Z),Ft},toWireType:function(Z,pe){pe instanceof ArrayBuffer&&(pe=new Uint8Array(pe));var Oe=typeof pe=="string";if(!(Oe||pe instanceof Uint8Array||pe instanceof Uint8ClampedArray||pe instanceof Int8Array))throw new os("Cannot pass non-string to std::string");var lt=K&&Oe?Rm(pe):pe.length,wt=Gp(4+lt+1),Ct=wt+4;if(x()[wt>>>2>>>0]=lt,K&&Oe)$l(pe,Ct,lt+1);else if(Oe)for(Oe=0;Oe>>0]=Ft}else for(Oe=0;Oe>>0]=pe[Oe];return Z!==null&&Z.push(oo,wt),wt},argPackAdvance:ss,readValueFromPointer:Vm,Db(Z){oo(Z)}})}var gy=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,Ox=(m,F)=>{for(var K=m>>1,Z=K+F/2;!(K>=Z)&&h()[K>>>0];)++K;if(32<(K<<=1)-m&&gy)return gy.decode(u().slice(m,K));for(K="",Z=0;!(Z>=F/2);++Z){var pe=c()[m+2*Z>>>1>>>0];if(pe==0)break;K+=String.fromCharCode(pe)}return K},Dx=(m,F,K)=>{if(K??(K=2147483647),2>K)return 0;var Z=F;K=(K-=2)<2*m.length?K/2:m.length;for(var pe=0;pe>>1>>>0]=Oe,F+=2}return c()[F>>>1>>>0]=0,F-Z},Lx=m=>2*m.length,Rx=(m,F)=>{for(var K=0,Z="";!(K>=F/4);){var pe=d()[m+4*K>>>2>>>0];if(pe==0)break;++K,65536<=pe?(pe-=65536,Z+=String.fromCharCode(55296|pe>>10,56320|1023&pe)):Z+=String.fromCharCode(pe)}return Z},Bx=(m,F,K)=>{if(F>>>=0,K??(K=2147483647),4>K)return 0;var Z=F;K=Z+K-4;for(var pe=0;pe=Oe&&(Oe=65536+((1023&Oe)<<10)|1023&m.charCodeAt(++pe)),d()[F>>>2>>>0]=Oe,(F+=4)+4>K)break}return d()[F>>>2>>>0]=0,F-Z},Nx=m=>{for(var F=0,K=0;K=Z&&++K,F+=4}return F};function jx(m,F,K){if(m>>>=0,F>>>=0,K=no(K>>>=0),F===2)var Z=Ox,pe=Dx,Oe=Lx,lt=wt=>h()[wt>>>1>>>0];else F===4&&(Z=Rx,pe=Bx,Oe=Nx,lt=wt=>x()[wt>>>2>>>0]);Mo(m,{name:K,fromWireType:wt=>{for(var Ct,Ft=x()[wt>>>2>>>0],Qt=wt+4,Fr=0;Fr<=Ft;++Fr){var Rr=wt+4+Fr*F;Fr!=Ft&<(Rr)!=0||(Qt=Z(Qt,Rr-Qt),Ct===void 0?Ct=Qt:(Ct+="\0",Ct+=Qt),Qt=Rr+F)}return oo(wt),Ct},toWireType:(wt,Ct)=>{if(typeof Ct!="string")throw new os(`Cannot pass non-string to C++ string type ${K}`);var Ft=Oe(Ct),Qt=Gp(4+Ft+F);return x()[Qt>>>2>>>0]=Ft/F,pe(Ct,Qt+4,Ft+F),wt!==null&&wt.push(oo,Qt),Qt},argPackAdvance:ss,readValueFromPointer:Vm,Db(wt){oo(wt)}})}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,!ce,1,!re,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(Lp),m+=128,Atomics.store(d(),m>>>2,1))}var Lp=()=>{var m=Il();m&&(Wm(m),_y(qy))};function Gx(m,F){(m>>>=0)==F>>>0?setTimeout(Lp):we?postMessage({targetThread:m,cmd:"checkMailbox"}):(m=ro[m])&&m.postMessage({cmd:"checkMailbox"})}var Gm=[];function Hx(m,F,K,Z,pe){for(F>>>=0,Z/=2,Gm.length=Z,K=pe>>>0>>>3,pe=0;pe>>0];return(F?Fm[F]:OM[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 Z=[];return m=m.toWireType(Z,K),Z.length&&(x()[F>>>2>>>0]=Ii(Z)),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 Rp=m=>{try{m()}catch(F){Pl(F)}},as=0,io=null,yy=0,Bp=[],vy={},by={},Qx=0,qm=null,Yx=[];function xy(m){return function(F){if(!gi){if(as===0){var K=!1,Z=!1;F((pe=0)=>{if(!gi&&(yy=pe,K=!0,Z)){as=2,Rp(()=>Zy(io)),typeof Browser<"u"&&Browser.Jb.Qb&&Browser.Jb.resume(),pe=!1;try{var Oe=function(){var Ct=d()[io+8>>>2>>>0];return Ct=Kt[by[Ct]],--Ys,Ct()}()}catch(Ct){Oe=Ct,pe=!0}var lt=!1;if(!io){var wt=qm;wt&&(qm=null,(pe?wt.reject:wt.resolve)(Oe),lt=!0)}if(pe&&!lt)throw Oe}}),Z=!0,K||(as=1,io=function(){var pe=Gp(65548),Oe=pe+12;x()[pe>>>2>>>0]=Oe,x()[pe+4>>>2>>>0]=Oe+65536,Oe=Bp[0];var lt=vy[Oe];return lt===void 0&&(lt=Qx++,vy[Oe]=lt,by[lt]=Oe),Oe=lt,d()[pe+8>>>2>>>0]=Oe,pe}(),typeof Browser<"u"&&Browser.Jb.Qb&&Browser.Jb.pause(),Rp(()=>Qy(io)))}else as===2?(as=0,Rp(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 Np=[];function Jx(m,F,K,Z){return K>>>=0,Z>>>=0,(m=Np[m>>>0])(null,F=Ai(F>>>0),K,Z)}var eM={},jp=m=>{var F=eM[m];return F===void 0?no(m):F};function tM(m,F,K,Z,pe){return K>>>=0,Z>>>=0,pe>>>=0,(m=Np[m>>>0])(F=Ai(F>>>0),F[K=jp(K)],Z,pe)}var My=()=>typeof globalThis=="object"?globalThis:Function("return this")();function rM(m){return(m>>>=0)==0?Ii(My()):(m=jp(m),Ii(My()[m]))}var nM=m=>{var F=Np.length;return Np.push(m),F},iM=(m,F)=>{for(var K=Array(m),Z=0;Z>>2>>>0],"parameter "+Z);return K},Ty=(m,F)=>Object.defineProperty(F,"name",{value:m});function oM(m,F,K){var Z=(F=iM(m,F>>>0)).shift();m--;var pe=`return function (obj, func, destructorsRef, args) { +`,Oe=0,lt=[];K===0&<.push("obj");for(var wt=["retType"],Ct=[Z],Ft=0;FtQt.name).join(", ")}) => ${Z.name}>`,nM(Ty(K,m))}function sM(m){return m=jp(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 fM(){return Ii({})}function pM(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 Z=new Date(m.getFullYear(),0,1).getTimezoneOffset();m=0|(K!=Z&&m.getTimezoneOffset()==Math.min(Z,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],Z=F.getTimezoneOffset(),pe=new Date(F.getFullYear(),6,1).getTimezoneOffset(),Oe=new Date(F.getFullYear(),0,1).getTimezoneOffset(),lt=Math.min(Oe,pe);return 0>K?d()[m+32>>>2>>>0]=+(pe!=Oe&<==Z):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,Z,pe,Oe,lt){return we?rn(16,1,m,F,K,Z,pe,Oe,lt):-52}function Cy(m,F,K,Z,pe,Oe){if(we)return rn(17,1,m,F,K,Z,pe,Oe)}function yM(m,F,K,Z){m>>>=0,F>>>=0,K>>>=0,Z>>>=0;var pe=new Date().getFullYear(),Oe=new Date(pe,0,1),lt=new Date(pe,6,1);pe=Oe.getTimezoneOffset();var wt=lt.getTimezoneOffset(),Ct=Math.max(pe,wt);x()[m>>>2>>>0]=60*Ct,d()[F>>>2>>>0]=+(pe!=wt),Oe=(m=Ft=>Ft.toLocaleTimeString(void 0,{hour12:!1,timeZoneName:"short"}).split(" ")[1])(Oe),lt=m(lt),wt{Km.length=0;for(var K;K=u()[m++>>>0];){var Z=K!=105;F+=(Z&=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+=Z?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 or($n(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 Z=F*(1+.2/K);Z=Math.min(Z,m+100663296);var pe=Math;Z=Math.max(m,Z);e:{pe=(pe.min.call(pe,4294901760,Z+(65536-Z%65536)%65536)-fr.buffer.byteLength+65535)/65536;try{fr.grow(pe),On();var Oe=1;break e}catch{}Oe=void 0}if(Oe)return!0}return!1}var Up=()=>(Pl("Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER"),0),cf={},Ay=m=>{m.forEach(F=>{Up()})};function $M(){var m=Error().stack.toString().split(` +`);return m[0]=="Error"&&m.shift(),Ay(m),cf.Ob=Up(),cf.ac=m,cf.Ob}function AM(m,F,K){if(m>>>=0,F>>>=0,cf.Ob==m)var Z=cf.ac;else(Z=Error().stack.toString().split(` +`))[0]=="Error"&&Z.shift(),Ay(Z);for(var pe=3;Z[pe]&&Up()!=m;)++pe;for(m=0;m>>2>>>0]=Up();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((Z,pe)=>{var Oe=F+K;for(pe=x()[m+4*pe>>>2>>>0]=Oe,Oe=0;Oe>>0]=Z.charCodeAt(Oe);s()[pe>>>0]=0,K+=Z.length+1}),0}function zy(m,F){if(we)return rn(19,1,m,F);m>>>=0,F>>>=0;var K=Iy();x()[m>>>2>>>0]=K.length;var Z=0;return K.forEach(pe=>Z+=pe.length+1),x()[F>>>2>>>0]=Z,0}function Oy(m){return we?rn(20,1,m):52}function Dy(m,F,K,Z){return we?rn(21,1,m,F,K,Z):52}function Ly(m,F,K,Z){return we?rn(22,1,m,F,K,Z):70}var IM=[null,[],[]];function Ry(m,F,K,Z){if(we)return rn(23,1,m,F,K,Z);F>>>=0,K>>>=0,Z>>>=0;for(var pe=0,Oe=0;Oe>>2>>>0],wt=x()[F+4>>>2>>>0];F+=8;for(var Ct=0;Ct>>0],Qt=IM[m];Ft===0||Ft===10?((m===1?vr:or)(Jw(Qt,0)),Qt.length=0):Qt.push(Ft)}pe+=wt}return x()[Z>>>2>>>0]=pe,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,Z){function pe(it,lr,Br){for(it=typeof it=="number"?it.toString():it||"";it.lengthtv?-1:0Js-it.getDate())){it.setDate(it.getDate()+lr);break}lr-=Js-it.getDate()+1,it.setDate(1),11>Br?it.setMonth(Br+1):(it.setMonth(0),it.setFullYear(it.getFullYear()+1))}return Br=new Date(it.getFullYear()+1,0,4),lr=wt(new Date(it.getFullYear(),0,4)),Br=wt(Br),0>=lt(lr,it)?0>=lt(Br,it)?it.getFullYear()+1:it.getFullYear():it.getFullYear()-1}m>>>=0,F>>>=0,K>>>=0,Z>>>=0;var Ft=x()[Z+40>>>2>>>0];for(var Qt in Z={fc:d()[Z>>>2>>>0],ec:d()[Z+4>>>2>>>0],Gb:d()[Z+8>>>2>>>0],Kb:d()[Z+12>>>2>>>0],Hb:d()[Z+16>>>2>>>0],Cb:d()[Z+20>>>2>>>0],ub:d()[Z+24>>>2>>>0],Bb:d()[Z+28>>>2>>>0],nc:d()[Z+32>>>2>>>0],dc:d()[Z+36>>>2>>>0],hc:Ft?$n(Ft):""},K=$n(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 Fr="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),Rr="January February March April May June July August September October November December".split(" ");for(Qt in Ft={"%a":it=>Fr[it.ub].substring(0,3),"%A":it=>Fr[it.ub],"%b":it=>Rr[it.Hb].substring(0,3),"%B":it=>Rr[it.Hb],"%C":it=>Oe((it.Cb+1900)/100|0,2),"%d":it=>Oe(it.Kb,2),"%e":it=>pe(it.Kb,2," "),"%g":it=>Ct(it).toString().substring(2),"%G":Ct,"%H":it=>Oe(it.Gb,2),"%I":it=>((it=it.Gb)==0?it=12:12{for(var lr=0,Br=0;Br<=it.Hb-1;lr+=(Al(it.Cb+1900)?By:Ny)[Br++]);return Oe(it.Kb+lr,3)},"%m":it=>Oe(it.Hb+1,2),"%M":it=>Oe(it.ec,2),"%n":()=>` +`,"%p":it=>0<=it.Gb&&12>it.Gb?"AM":"PM","%S":it=>Oe(it.fc,2),"%t":()=>" ","%u":it=>it.ub||7,"%U":it=>Oe(Math.floor((it.Bb+7-it.ub)/7),2),"%V":it=>{var lr=Math.floor((it.Bb+7-(it.ub+6)%7)/7);if(2>=(it.ub+371-it.Bb-2)%7&&lr++,lr)lr==53&&((Br=(it.ub+371-it.Bb)%7)==4||Br==3&&Al(it.Cb)||(lr=1));else{lr=52;var Br=(it.ub+7-it.Bb-1)%7;(Br==4||Br==5&&Al(it.Cb%400-1))&&lr++}return Oe(lr,2)},"%w":it=>it.ub,"%W":it=>Oe(Math.floor((it.Bb+7-(it.ub+6)%7)/7),2),"%y":it=>(it.Cb+1900).toString().substring(2),"%Y":it=>it.Cb+1900,"%z":it=>{var lr=0<=(it=it.dc);return it=Math.abs(it)/60,(lr?"+":"-")+("0000"+(it/60*100+it%60)).slice(-4)},"%Z":it=>it.hc,"%%":()=>"%"},K=K.replace(/%%/g,"\0\0"),Ft)K.includes(Qt)&&(K=K.replace(new RegExp(Qt,"g"),Ft[Qt](Z)));return Qt=function(it){var lr=Array(Rm(it)+1);return ry(it,lr,0,lr.length),lr}(K=K.replace(/\0\0/g,"%")),Qt.length>F?0:(FM(Qt,m),Qt.length-1)}function zM(m,F,K,Z){return jy(m>>>0,F>>>0,K>>>0,Z>>>0)}we||function(){for(var m=v.numThreads-1;m--;)Xw();uf.unshift(()=>{$i++,function(F){we?F():Promise.all(is.map(Kw)).then(F)}(()=>Op())})}();for(var Uy=Array(256),Vp=0;256>Vp;++Vp)Uy[Vp]=String.fromCharCode(Vp);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 OM=[Dm,Ww,Qw,ey,ty,ny,iy,oy,sy,ay,ly,uy,cy,dy,fy,py,Ey,Cy,Fy,zy,Oy,Dy,Ly,Ry],Kt=function(){function m(K,Z){return Kt=K.exports,Kt=function(){var pe=Kt,Oe={};for(let[lt,wt]of Object.entries(pe))Oe[lt]=typeof wt=="function"?(...Ct)=>{Bp.push(lt);try{return wt(...Ct)}finally{gi||(Bp.pop(),io&&as===1&&Bp.length===0&&(as=0,Ys+=1,Rp(Yy),typeof Fibers<"u"&&Fibers.oc()))}}:wt;return Oe}(),Kt=function(){var pe=Kt,Oe=wt=>Ct=>wt(Ct)>>>0,lt=wt=>()=>wt()>>>0;return(pe=Object.assign({},pe)).Ca=Oe(pe.Ca),pe.fb=lt(pe.fb),pe.gb=Oe(pe.gb),pe.emscripten_main_runtime_thread_id=lt(pe.emscripten_main_runtime_thread_id),pe.sb=Oe(pe.sb),pe.tb=lt(pe.tb),pe}(),Gw.push(Kt.ib),Dn.unshift(Kt.Ba),Gr=Z,Op(),Kt}var F=Uw();if($i++,v.instantiateWasm)try{return v.instantiateWasm(F,m)}catch(K){or(`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",yt):yt+"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,Z){var pe=Im;return Dt||typeof WebAssembly.instantiateStreaming!="function"||Rw(pe)||Bw(pe)||typeof fetch!="function"?jw(pe,K,Z):fetch(pe,{credentials:"same-origin"}).then(Oe=>WebAssembly.instantiateStreaming(Oe,K).then(Z,function(lt){return or(`wasm streaming compile failed: ${lt}`),or("falling back to ArrayBuffer instantiation"),jw(pe,K,Z)}))}(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,Z,pe,Oe,lt,wt,Ct,Ft)=>(v._OrtCreateSessionOptions=Kt.Ga)(m,F,K,Z,pe,Oe,lt,wt,Ct,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,Z,pe,Oe)=>(v._OrtCreateTensor=Kt.Ra)(m,F,K,Z,pe,Oe),v._OrtGetTensorData=(m,F,K,Z,pe)=>(v._OrtGetTensorData=Kt.Sa)(m,F,K,Z,pe),v._OrtReleaseTensor=m=>(v._OrtReleaseTensor=Kt.Ta)(m),v._OrtCreateRunOptions=(m,F,K,Z)=>(v._OrtCreateRunOptions=Kt.Ua)(m,F,K,Z),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,Z)=>(v._OrtBindOutput=Kt.Za)(m,F,K,Z),v._OrtClearBoundOutputs=m=>(v._OrtClearBoundOutputs=Kt._a)(m),v._OrtReleaseBinding=m=>(v._OrtReleaseBinding=Kt.$a)(m),v._OrtRunWithBinding=(m,F,K,Z,pe)=>(v._OrtRunWithBinding=Kt.ab)(m,F,K,Z,pe),v._OrtRun=(m,F,K,Z,pe,Oe,lt,wt)=>(v._OrtRun=Kt.bb)(m,F,K,Z,pe,Oe,lt,wt),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 Wp,Il=()=>(Il=Kt.fb)(),Gp=v._malloc=m=>(Gp=v._malloc=Kt.gb)(m),oo=v._free=m=>(oo=v._free=Kt.hb)(m),Ym=(m,F,K,Z,pe,Oe)=>(Ym=Kt.kb)(m,F,K,Z,pe,Oe),Gy=()=>(Gy=Kt.lb)(),Hy=(m,F,K,Z,pe)=>(Hy=Kt.mb)(m,F,K,Z,pe),Zm=m=>(Zm=Kt.nb)(m),Hp=m=>(Hp=Kt.ob)(m),qy=()=>(qy=Kt.pb)(),Ky=(m,F)=>(Ky=Kt.qb)(m,F),qp=m=>(qp=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||Dp(Dn),startWorker(v)):(Dp(uf),0<$i||Wp||(Wp=!0,v.calledRun=!0,gi||(we||Dp(Dn),H(v),we||Dp(Jn)))))}return v.___start_em_js=861437,v.___stop_em_js=861659,v.stackSave=()=>eg(),v.stackRestore=m=>qp(m),v.stackAlloc=m=>Jm(m),v.UTF8ToString=$n,v.stringToUTF8=$l,v.lengthBytesUTF8=Rm,ns=function m(){Wp||ev(),Wp||(ns=m)},ev(),oe}),Et=vt,((n=globalThis.self)==null?void 0:n.name)==="em-pthread"&&vt()}),at,zt,Vt,Xt,Yt,rr,Ht,Cr,Yr=p(()=>{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),zt=typeof location>"u"?void 0:location.origin,Vt=(s,u)=>{try{let c=u??at;return(c?new URL(s,c):new URL(s)).origin===zt}catch{return!1}},Xt=async s=>{let u=await(await fetch(s,{credentials:"same-origin"})).blob();return URL.createObjectURL(u)},Yt=(pt(),w(Re)).default,rr=async()=>{if(!at)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(Vt(at))return[void 0,Yt()];let s=await Xt(at);return[s,Yt(s)]},Ht=(Lt(),w(ht)).default,Cr=async(s,u,c)=>[void 0,Ht]}),Pr,mt,Pt,Nt,un,Bi,Mi,Wr,wn=p(()=>{Yr(),mt=!1,Pt=!1,Nt=!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(Pt)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Nt)throw new Error("previous call to 'initializeWebAssembly()' failed.");Pt=!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,h=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 Cr(x,h,s>1),oe=!1,re=[];if(i>0&&re.push(new Promise(ce=>{setTimeout(()=>{oe=!0,ce()},i)})),re.push(new Promise((ce,we)=>{let be={numThreads:s};H?be.wasmBinary=H:($||h)&&(be.locateFile=(he,De)=>$??(h??De)+he),v(be).then(he=>{Pt=!1,mt=!0,Pr=he,ce(),q&&URL.revokeObjectURL(q)},he=>{Pt=!1,Nt=!0,we(he)})})),await Promise.race(re),oe)throw new Error(`WebAssembly backend initializing failed due to timeout: ${i}ms`)},Wr=()=>{if(mt&&Pr)return Pr;throw new Error("WebAssembly is not initialized yet.")}}),Kr,fi,Or,Ni=p(()=>{wn(),Kr=(n,i)=>{let s=Wr(),u=s.lengthBytesUTF8(n)+1,c=s._malloc(u);return s.stringToUTF8(n,c,u),i.push(c),c},fi=(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,h])=>{let d=i?i+c:c;if(typeof h=="object")fi(h,d+".",s,u);else if(typeof h=="string"||typeof h=="number")u(d,h.toString());else if(typeof h=="boolean")u(d,h?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof h}`)})},Or=n=>{let i=Wr(),s=i.stackSave();try{let u=i.stackAlloc(8);i._OrtGetLastError(u,u+4);let c=i.HEAP32[u/4],h=i.HEAPU32[u/4+1],d=h?i.UTF8ToString(h):"";throw new Error(`${n} ERROR_CODE: ${c}, ERROR_MESSAGE: ${d}`)}finally{i.stackRestore(s)}}}),Ti,Cs=p(()=>{wn(),Ni(),Ti=n=>{let i=Wr(),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 h=0;return(n==null?void 0:n.tag)!==void 0&&(h=Kr(n.tag,u)),s=i._OrtCreateRunOptions(c.logSeverityLevel,c.logVerbosityLevel,!!c.terminate,h),s===0&&Or("Can't create run options."),(n==null?void 0:n.extra)!==void 0&&fi(n.extra,"",new WeakSet,(d,x)=>{let k=Kr(d,u),$=Kr(x,u);i._OrtAddRunConfigEntry(s,k,$)!==0&&Or(`Can't set a run config entry: ${d} - ${x}.`)}),[s,u]}catch(h){throw s!==0&&i._OrtReleaseRunOptions(s),u.forEach(d=>i._free(d)),h}}}),Lo,Ro,Bo,No,ji,Ps=p(()=>{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);Wr()._OrtAddSessionConfigEntry(n,x,k)!==0&&Or(`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);Wr()._OrtAddSessionConfigEntry(n,x,k)!==0&&Or(`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 h=Kr(c,s);Wr()._OrtAppendExecutionProvider(n,h)!==0&&Or(`Can't append execution provider: ${c}.`)}},ji=n=>{let i=Wr(),s=0,u=[],c=n||{};Bo(c);try{let h=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(h,!!c.enableCpuMemArena,!!c.enableMemPattern,d,!!c.enableProfiling,0,x,k,$,H),s===0&&Or("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&&Or(`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&&Or(`Can't set a free dimension override: ${q} - ${v}.`)}return c.extra!==void 0&&fi(c.extra,"",new WeakSet,(q,v)=>{let oe=Kr(q,u),re=Kr(v,u);i._OrtAddSessionConfigEntry(s,oe,re)!==0&&Or(`Can't set a session config entry: ${q} - ${v}.`)}),[s,u]}catch(h){throw s!==0&&i._OrtReleaseSessionOptions(s),u.forEach(d=>i._free(d)),h}}}),po,pi,ki,Si,Ji,ho,mo,Zt=p(()=>{po=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}`)}},pi=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=p(()=>{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(),h;try{h=new ArrayBuffer(u)}catch(x){if(x instanceof RangeError){let k=Math.ceil(u/65536);h=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(h,d,$).set(k),d+=$}return new Uint8Array(h,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,Ur,Nn=p(()=>{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)},Ur=(...n)=>{Wo&&Go(...n)}}),Ue,W=p(()=>{Zt(),Ue=(n,i)=>new(Si(i))(n)}),fe=p(()=>{}),Ee,Fe,ze,rt,Mt,St,kt,It,tr,$r=p(()=>{Nn(),fe(),Ee=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=[],ze=n=>Math.ceil(n/16)*16,rt=n=>{for(let i=0;iMt++,kt=async(n,i,s,u)=>{let c=ze(s),h=n.device.createBuffer({size:c,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let d=n.getCommandEncoder();n.endComputePass(),d.copyBufferToBuffer(i,0,h,0,c),n.flush(),await h.mapAsync(GPUMapMode.READ);let x=h.getMappedRange();if(u){let k=u();return k.set(new Uint8Array(x,0,s)),k}else return new Uint8Array(x.slice(0,s))}finally{h.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 Ee)Fe.push(i),this.freeBuffers.set(i,[]),this.freeUniformBuffers.set(i,[])}upload(n,i){let s=i.buffer,u=i.byteOffset,c=i.byteLength,h=ze(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:h,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,h),Ur("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=ze(s.originalSize),h=this.backend.getCommandEncoder();this.backend.endComputePass(),h.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 Ur("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),Ur("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),Ur("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,h=(i&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(c||h){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}),Ur("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 Ur("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=Ee.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)}),sr,qt,gr=p(()=>{sr=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 sr(n)}),Cn,gn,ct,Kn,br,cn,Fn,Jt=p(()=>{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 h=Math.max(n.length,i.length),d=new Array(h);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[h-2],d[h-1]]=x}for(let x=s?3:1;x<=h;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[h-x]=Math.max(k,$);else{if(H>1)return;d[h-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),h=u-1;for(;h>=0;){if(i[h]%s===0){c[h]=i[h]/s;break}if(s%i[h]!==0)throw new Error("cannot convert shape");c[h]=1,s/=i[h],h--}for(h--;h>=0;h--)c[h]=i[h];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 h=s;h=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,h)=>c+s[h]+s[h+u])}static areEqual(i,s){return i.length!==s.length?!1:i.every((u,c)=>u===s[c])}},Kn=class Mf{static adjustPoolAttributes(i,s,u,c,h,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,h,d,x){if(x){if(h.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(),jn=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}`)}},Tr=(n,i=1)=>{let s=yn(n,i);return typeof s=="string"?s:s[0]},kr=(n,i=1)=>{let s=yn(n,i);return typeof s=="string"?s:s[1]},$t=(...n)=>{let i=[];return n.forEach(s=>{s.length!==0&&i.push({type:12,data:s},{type:12,data:ct.computeStrides(s)})}),i},wr=n=>n%4===0?4:n%2===0?2:1,Dr=(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})`,Un=(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,Ot=(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 h=typeof s=="number",d=h?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`,re={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},ce=h?"uniforms.":"",we=`${ce}${n}_shape`,be=`${ce}${n}_strides`,he="";for(let ot=0;ot ${v.indices} { + var indices: ${v.indices}; + var current = offset; + ${he} + return indices; + }`,Ae=ot=>(re.offsetToIndices=!0,d<2?ot:`o2i_${n}(${ot})`),Ie=[];if(d>=2)for(let ot=d-1;ot>=0;ot--)Ie.push(`${Ot(be,ot,d)} * (indices[${ot}])`);let gt=d<2?"":` + fn i2o_${n}(indices: ${v.indices}) -> u32 { + return ${Ie.join("+")}; + }`,ut=ot=>(re.indicesToOffset=!0,d<2?ot:`i2o_${n}(${ot})`),yt=(...ot)=>d===0?"0u":`${v.indices}(${ot.map(oe).join(",")})`,Dt=(ot,Wt)=>d<2?`${ot}`:`${Ot(ot,Wt,d)}`,Bt=(ot,Wt,ir)=>d<2?`${ot}=${ir};`:`${Ot(ot,Wt,d)}=${ir};`,mr={},vr=(ot,Wt)=>{re.broadcastedIndicesToOffset=!0;let ir=`${Wt.name}broadcastedIndicesTo${n}Offset`;if(ir in mr)return`${ir}(${ot})`;let Vr=[];for(let fn=d-1;fn>=0;fn--){let kn=Wt.indicesGet("outputIndices",fn+Wt.rank-d);Vr.push(`${Dt(be,fn)} * (${kn} % ${Dt(we,fn)})`)}return mr[ir]=`fn ${ir}(outputIndices: ${Wt.type.indices}) -> u32 { + return ${Vr.length>0?Vr.join("+"):"0u"}; + }`,`${ir}(${ot})`},or=(ot,Wt)=>(()=>{if(v.storage===v.value)return`${n}[${ot}]=${Wt};`;if(v.storage==="vec2"&&v.value==="i32")return`${n}[${ot}]=vec2(u32(${Wt}), select(0u, 0xFFFFFFFFu, ${Wt} < 0));`;if(v.storage==="vec2"&&v.value==="u32")return`${n}[${ot}]=vec2(u32(${Wt}), 0u);`;if(v.storage==="u32"&&v.value==="vec4")return`${n}[${ot}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${Wt}));`;throw new Error(`not supported combination of storage type ${v.storage} and value type ${v.value} yet`)})(),Ir=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 ${Ir(`i2o_${n}(indices)`)}; + }`,fr=d<2?"":(()=>{let ot=x.map(ir=>`d${ir}: u32`).join(", "),Wt=x.map(ir=>`d${ir}`).join(", ");return` + fn get_${n}(${ot}) -> ${H} { + return get_${n}ByIndices(${yt(Wt)}); + }`})(),Gr=(...ot)=>{if(ot.length!==d)throw new Error(`indices length must be ${d}`);let Wt=ot.map(oe).join(",");return d===0?Ir("0u"):d===1?Ir(Wt[0]):(re.get=!0,re.getByIndices=!0,re.indicesToOffset=!0,`get_${n}(${Wt})`)},jt=ot=>d<2?Ir(ot):(re.getByIndices=!0,re.indicesToOffset=!0,`get_${n}ByIndices(${ot})`),er=d<2?"":` + fn set_${n}ByIndices(indices: ${v.indices}, value: ${H}) { + ${or(`i2o_${n}(indices)`,"value")} + }`,_r=d<2?"":(()=>{let ot=x.map(ir=>`d${ir}: u32`).join(", "),Wt=x.map(ir=>`d${ir}`).join(", ");return` + fn set_${n}(${ot}, value: ${H}) { + set_${n}ByIndices(${yt(Wt)}, value); + }`})();return{impl:()=>{let ot=[],Wt=!1;return re.offsetToIndices&&(ot.push(De),Wt=!0),re.indicesToOffset&&(ot.push(gt),Wt=!0),re.broadcastedIndicesToOffset&&(Object.values(mr).forEach(ir=>ot.push(ir)),Wt=!0),re.set&&(ot.push(_r),Wt=!0),re.setByIndices&&(ot.push(er),Wt=!0),re.get&&(ot.push(fr),Wt=!0),re.getByIndices&&(ot.push(Zr),Wt=!0),!h&&Wt&&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:vr,indices:yt,indicesGet:Dt,indicesSet:Bt,set:(...ot)=>{if(ot.length!==d+1)throw new Error(`indices length must be ${d}`);let Wt=ot[d];if(typeof Wt!="string")throw new Error("value must be string");let ir=ot.slice(0,d).map(oe).join(",");return d===0?or("0u",Wt):d===1?or(ir[0],Wt):(re.set=!0,re.setByIndices=!0,re.indicesToOffset=!0,`set_${n}(${ir}, ${Wt})`)},setByOffset:or,setByIndices:(ot,Wt)=>d<2?or(ot,Wt):(re.setByIndices=!0,re.indicesToOffset=!0,`set_${n}ByIndices(${ot}, ${Wt});`),get:Gr,getByOffset:Ir,getByIndices:jt,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=jn){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,h=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(${h}) { + ${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(h)}return u}}),du,_a,Ho,fu,hi,pu,wa,yo=p(()=>{Zt(),Jt(),gr(),ur(),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)),fu=(n,i,s,u)=>{let c=[];c.push(`fn perm(i: ${u.type.indices}) -> ${s.type.indices} { + var a: ${s.type.indices};`);for(let h=0;h{let s=n.dataType,u=n.dims.length,c=_a(u,i),h=Ho(n.dims,c),d=Gt("output",s,h.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)} + + ${fu(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(h);return{outputs:[{dims:h,dataType:$[0].dataType}],dispatchGroup:{x:Math.ceil(H/64)},programUniforms:[{type:12,data:H},...$t($[0].dims,h)]}},getShaderSource:k}},pu=(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,np=p(()=>{Zt(),Jt(),ur(),$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 h=0;hn[h]);return[s,c]},yu=(n,i)=>{let s=n.length+i.length,u=[],c=0;for(let h=0;h{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,h,d)=>{let x=s[0].dims,k=ct.size(h),$=ct.size(d),H=_t("_A",s[0].dataType,x),q=Gt("output",c,h),v=32,oe=` + var aBestValues : array; + `;return{name:n,shaderCache:i,getShaderSource:re=>` + ${re.registerUniform("reduceSize","u32").declareVariables(H,q)} + ${oe} + fn DIV_CEIL(a : u32, b : u32) -> u32 { + return ((a - 1u) / b + 1u); + } + ${re.mainStart(v)} + + let outputIndex = global_idx / ${v}; + let offset = outputIndex * uniforms.reduceSize; + + var bestValue = f32(${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:h,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),h=c.axes;h.length===0&&!c.noopWithEmptyAxes&&(h=n.inputs[0].dims.map((oe,re)=>re));let d=ct.normalizeAxes(h,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,zu,Sa,Ou,Du,Yn,Lu,Ru,Ea,Bu,Nu,Ca,ju,Uu,Pa,Vu,$a=p(()=>{Zt(),Jt(),gr(),ur(),np(),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,h,d=!1,x=!1)=>{let k=[],$=s[0].dims,H=$.length,q=ct.normalizeAxes(c,H),v=!x&&q.length===0;$.forEach((ce,we)=>{v||q.indexOf(we)>=0?d&&k.push(1):k.push(ce)});let oe=k.length,re=ct.size(k);return{name:n,shaderCache:i,getShaderSource:ce=>{let we=[],be=_t("_A",s[0].dataType,H),he=Gt("output",h,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` + + ${ce.registerUniform("output_size","u32").declareVariables(be,he)} + + ${ce.mainStart()} + ${ce.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + var input_indices: ${be.type.indices}; + let output_indices = ${he.offsetToIndices("global_idx")}; + + ${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:h}],dispatchGroup:{x:Math.ceil(re/64)},programUniforms:[{type:12,data:re},...$t($,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,h=c.length===1?s:Is(c,s);n.compute(As(i,{hint:h.cacheKey,inputDependencies:["rank"]},[c[0]],h.noopWithEmptyAxes&&h.axes.length===0?Pu:u,h.axes,c[0].dataType,h.keepDims,h.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 h=[];for(let d=0;d=0||c.length===0)&&h.push(s.indicesSet("input_indices",d,0));return[`${h.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 h=1;for(let d=0;d=0||c.length===0)&&(h*=n.inputs[0].dims[d]);return["var sum = f32(0);","",`sum += f32(${s.getByIndices("input_indices")});`,`let value = ${u.type.value}(sum / ${h});`]})},zu=(n,i)=>{Qn(n.inputs),ii(n,"ReduceMin",i,(s,u,c)=>{let h=[];for(let d=0;d=0||c.length===0)&&h.push(`input_indices[${d}] = 0;`);return[`${h.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")};`,""])},Ou=(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 h=0;h1024},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)?zu(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)?Ou(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,zs,ip=p(()=>{Zt(),gr(),$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,h)=>{let d=[];for(let x=0;x=0||h.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,h)=>{let d=[];for(let x=0;x=0||h.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]})},zs=n=>qt(n)}),Hu,Aa,qu,Ku,vo,Xu,Qu,Os=p(()=>{Zt(),fe(),ur(),Hu=(n,i)=>{let s=n[0],u=n[1],c=n[2],h=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 re=$;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 ce=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||(ce=d.dims[3])}let we=re+ce,be=-1,he=0;if(h)throw new Error("Mask not supported");if(d)throw new Error("past is not supported");return{batchSize:k,sequenceLength:$,pastSequenceLength:ce,kvSequenceLength:re,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=wr(u),h=64,d=u/c;d{let oe=Gt("x",i.dataType,i.dims,c),re=[{name:"d_inv",type:kr(i.dataType)},{name:"d_comp",type:"u32"},{name:"elements_per_thread",type:"u32"}];return` + var thread_max: array; + var thread_sum: array; + ${v.registerUniforms(re).declareVariables(oe)} + ${v.mainStart([h,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 < ${h}; 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 < ${h}; 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:`${h};${$};${c}`},getShaderSource:q,getRunData:()=>({outputs:[],dispatchGroup:{x:s},programUniforms:k})}},qu=(n,i,s,u,c,h,d,x)=>{let k=x+h.kvSequenceLength,$=[h.batchSize,h.numHeads,h.sequenceLength,k],H=h.kvNumHeads===void 0&&n.outputCount>1,q=H?[h.batchSize,h.numHeads,k,h.headSize]:void 0,v=d.scale===0?1/Math.sqrt(h.headSize):d.scale,oe=wr(h.headSize),re=h.headSize/oe,ce=12,we={x:Math.ceil(k/ce),y:Math.ceil(h.sequenceLength/ce),z:h.batchSize*h.numHeads},be=[{type:12,data:h.sequenceLength},{type:12,data:re},{type:12,data:k},{type:12,data:h.numHeads},{type:1,data:v},{type:12,data:x},{type:12,data:h.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),yt=[gt,ut];if(u){let or=_t("past_key",u.dataType,u.dims,oe);yt.push(or)}c&&yt.push(_t("relative_position_bias",c.dataType,c.dims));let Dt=Gt("output",i.dataType,$),Bt=[Dt];H&&Bt.push(Gt("present_key",i.dataType,q,oe));let mr=kr(1,oe),vr=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"alpha",type:"f32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"}];return` + const TILE_SIZE = ${ce}u; + + var tileQ: array<${gt.type.storage}, ${ce*ce}>; + var tileK: array<${gt.type.storage}, ${ce*ce}>; + ${Ie.registerUniforms(vr).declareVariables(...yt,...Bt)} + ${Ie.mainStart([ce,ce,1])} + // x holds the N and y holds the M + let headIdx = workgroup_id.z; + let m = workgroup_id.y * TILE_SIZE; + let n = workgroup_id.x * TILE_SIZE; + let qOffset = uniforms.M * uniforms.K * headIdx + m * uniforms.K; + ${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 = ${mr}(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 += ${mr}(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,h)=>{let d=h+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},re=[{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:h},{type:12,data:c.kvSequenceLength}],ce=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:ce},getRunData:()=>({outputs:we,dispatchGroup:oe,programUniforms:re}),getShaderSource:be}},vo=(n,i,s,u,c,h,d,x,k,$,H)=>{let q=n.outputCount,v=$.kvNumHeads!==void 0||q>1?$.pastSequenceLength:0,oe=v+$.kvSequenceLength,re=$.kvNumHeads===void 0&&q>1&&d?[i,s,d]:[i,s];k&&re.push(k);let ce=n.compute(qu(n,i,s,q>1?d:void 0,k,$,H,v),{inputs:re,outputs:$.kvNumHeads===void 0&&q>1?[-1,1]:[-1]})[0];n.compute(Aa(n,ce,$.batchSize*$.numHeads*$.sequenceLength,oe),{inputs:[ce],outputs:[]});let we=$.kvNumHeads===void 0&&q>1&&x?[ce,u,x]:[ce,u];n.compute(Ku(n,ce,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,h=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:h},{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),re=Gt("output_v",k[0].dataType,s),ce=_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=ce.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(ce,we,be,v,oe,re)} + ${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,h]=Xu(n,s);return vo(n,u,c,h,n.inputs[4],void 0,void 0,void 0,n.inputs[5],s,i)}}),Yu,Zu,Ju,ec,tc=p(()=>{Y(),Zt(),Jt(),gr(),ur(),Yu=(n,i)=>{if(!n||n.length!==5)throw new Error("BatchNormalization requires 5 inputs");let s=(u,c,h)=>{let d=c.length;if(d!==u.length)throw new Error(`${h}: num dimensions != ${d}`);c.forEach((x,k)=>{if(x!==u[k])throw new Error(`${h}: 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,h=n[0].dims,d=u?wr(h[h.length-1]):1,x=c==="NHWC"&&h.length>1?d:1,k=ct.size(h)/d,$=u,H=$?h.length:h,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),re=_t("inputMean",n[3].dataType,n[3].dims,x),ce=_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 = ${h.length===1?"0u":c==="NHWC"?`outputIndices[${h.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[${h.length-1}];`;for(let Ae=1;Ae` + const epsilon = ${s}; + ${De.registerUniform("outputSize","u32").declareVariables(q,v,oe,re,ce,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 = ${re.getByOffset("cOffset")}; + let inputVar = ${ce.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},...$t(h)]:[{type:12,data:k}]})}},Ju=n=>qt(n),ec=(n,i)=>{let{inputs:s,outputCount:u}=n,c=Ju({...i,outputCount:u});if(D.webgpu.validateInputContent&&Yu(s,c),i.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");n.compute(Zu(s,c))}}),rc,nc,Ia,op=p(()=>{Jt(),ur(),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,h=_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(h,d,x,k)} + + ${$.mainStart()} + ${$.guardAgainstOutOfBoundsWorkgroupSizes(u)} + let value = ${h.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,yr,oc,sc,Fa,ac,lc,za,uc,cc,Ds,dc,fc,pc,Oa,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=p(()=>{Zt(),Jt(),gr(),ur(),ic=(n,i,s,u,c,h)=>{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,$)} + + ${h??""} + + ${n.mainStart()} + ${n.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + + let a = ${k.getByOffset("global_idx")}; + ${$.setByOffset("global_idx",x)} + }`},yr=(n,i,s,u,c,h=n.dataType)=>({name:i,shaderCache:{hint:c,inputDependencies:["type"]},getShaderSource:d=>ic(d,ct.size(n.dims),n.dataType,h,s,u),getRunData:d=>({outputs:[{dims:n.dims,dataType:h}],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(yr(n.inputs[0],"Abs","abs"))},sc=n=>{n.compute(yr(n.inputs[0],"Acos","acos"))},Fa=n=>{n.compute(yr(n.inputs[0],"Acosh","acosh"))},ac=n=>{n.compute(yr(n.inputs[0],"Asin","asin"))},lc=n=>{n.compute(yr(n.inputs[0],"Asinh","asinh"))},za=n=>{n.compute(yr(n.inputs[0],"Atan","atan"))},uc=n=>{n.compute(yr(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(yr(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]:Fn;return qt({min:i,max:s})},fc=(n,i)=>{let s=n.inputs.length===1?i:dc(n.inputs),u=kr(n.inputs[0].dataType);n.compute(yr(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]})},pc=n=>{n.compute(yr(n.inputs[0],"Ceil","ceil"))},Oa=n=>{n.compute(yr(n.inputs[0],"Cos","cos"))},hc=n=>{n.compute(yr(n.inputs[0],"Cosh","cosh"))},bo=n=>qt(n),mc=(n,i)=>{let s=kr(n.inputs[0].dataType);n.compute(yr(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=kr(n.inputs[0].dataType);n.compute(yr(n.inputs[0],"Erf",s=>`erf_vf32(${s})`,Ls(i)))},Da=n=>{n.compute(yr(n.inputs[0],"Exp","exp"))},_c=n=>{n.compute(yr(n.inputs[0],"Floor","floor"))},wc=n=>{let i=kr(n.inputs[0].dataType);n.compute(yr(n.inputs[0],"Gelu",s=>`0.5 * ${s} * (1.0 + erf_vf32(${s} * 0.7071067811865475))`,Ls(i)))},yc=(n,i)=>{let s=kr(n.inputs[0].dataType);n.compute(yr(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(yr(n.inputs[0],"Not",i=>`!${i}`))},vc=n=>{n.compute(yr(n.inputs[0],"Neg",i=>`-${i}`))},bc=n=>{n.compute(yr(n.inputs[0],"Reciprocal",i=>`1.0/${i}`))},Ra=n=>{let i=kr(n.inputs[0].dataType);n.compute(yr(n.inputs[0],"Relu",s=>`select(vec4<${i}>(0.0), ${s}, ${s} > vec4<${i}>(0.0))`))},xc=n=>{n.compute(yr(n.inputs[0],"Sigmoid",i=>`(1.0 / (1.0 + exp(-${i})))`))},Mc=n=>qt(n),Ba=(n,i)=>{let s=kr(n.inputs[0].dataType);n.compute(yr(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(yr(n.inputs[0],"Sin","sin"))},kc=n=>{n.compute(yr(n.inputs[0],"Sinh","sinh"))},Na=n=>{n.compute(yr(n.inputs[0],"Sqrt","sqrt"))},Sc=n=>{n.compute(yr(n.inputs[0],"Tan","tan"))},ja=n=>`sign(${n}) * (1 - exp(-2 * abs(${n}))) / (1 + exp(-2 * abs(${n})))`,Ua=n=>{n.compute(yr(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=kr(n.inputs[0].dataType);n.compute(yr(n.inputs[0],"FastGelu",Wa,Va(i),void 0,n.inputs[0].dataType))},Cc=(n,i)=>{let s=kr(n.inputs[0].dataType);return n.compute(yr(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(yr(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=kr(n.inputs[0].dataType);n.compute(yr(n.inputs[0],"QuickGelu",$c,Pc(s,i.alpha),i.cacheKey,n.inputs[0].dataType))}}),qa,Ic,Fc,zc=p(()=>{Jt(),ur(),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),h=ct.size(i)/4,d=Tr(n[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:i,dataType:n[0].dataType}],dispatchGroup:{x:Math.ceil(h/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(h)} + 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))}}),Oc,Dc,Zn,Lc,Rc,Ka,Bc,Nc,jc,Uc,Vc,Wc,Xa,sp=p(()=>{Zt(),Jt(),ur(),Oc=(n,i,s,u,c,h,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 re=Gt("outputData",H,u.length,4),ce=_t("aData",k,i.length,4),we=_t("bData",$,s.length,4),be;if(c)if(h){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=re.setByOffset("global_idx",oe(he?`${ce.type.value}(${ce.getByOffset("0")}.x)`:ce.getByOffset("global_idx"),De?`${we.type.value}(${we.getByOffset("0")}.x)`:we.getByOffset("global_idx"))):be=` + let outputIndices = ${re.offsetToIndices("global_idx * 4u")}; + let offsetA = ${ce.broadcastedIndicesToOffset("outputIndices",re)}; + let offsetB = ${we.broadcastedIndicesToOffset("outputIndices",re)}; + ${re.setByOffset("global_idx",oe(d||Ae?ce.getByOffset("offsetA / 4u"):`${ce.type.value}(${ce.getByOffset("offsetA / 4u")}[offsetA % 4u])`,d||Ie?we.getByOffset("offsetB / 4u"):`${we.type.value}(${we.getByOffset("offsetB / 4u")}[offsetB % 4u])`))} + `}else be=re.setByOffset("global_idx",oe(ce.getByOffset("global_idx"),we.getByOffset("global_idx")));else{if(!h)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} = ${re.offsetToIndices(`global_idx * 4u + ${Ae}u`)}; + let offsetA${Ae} = ${ce.broadcastedIndicesToOffset(`outputIndices${Ae}`,re)}; + let offsetB${Ae} = ${we.broadcastedIndicesToOffset(`outputIndices${Ae}`,re)}; + 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(ce,we,re)} + + ${q??""} + + ${n.mainStart()} + ${n.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${be} + }`},Dc=(n,i,s,u,c,h,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 re=ct.size(s.dims)===1,ce=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(re),v.push(ce),v.push(we),v.push(be);let he=1;for(let De=1;Deoe.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:oe=>Oc(oe,s.dims,u.dims,k,H,x,q,c,s.dataType,u.dataType,d,h),getRunData:()=>({outputs:[{dims:k,dataType:d}],dispatchGroup:{x:Math.ceil($/64/4)},programUniforms:[{type:12,data:Math.ceil(ct.size(k)/4)},...$t(s.dims,u.dims,k)]})}},Zn=(n,i,s,u,c,h)=>{n.compute(Dc(i,c??"",n.inputs[0],n.inputs[1],s,u,h))},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,ap=p(()=>{Zt(),Jt(),gr(),ur(),Gc=(n,i)=>{if(!n||n.length<1)throw new Error("too few inputs");let s=0,u=n[s],c=u.dataType,h=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!==h)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),h=new Array(n.length),d=new Array(n.length),x=0,k=[],$=[],H=[{type:12,data:c}];for(let ce=0;ce`uniforms.sizeInConcatAxis${ce}`).join(","),re=ce=>` + + ${(()=>{ce.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:re}},Ui=(n,i)=>{let s=n.inputs,u=s[0].dims,c=ct.normalizeAxis(i.axis,u.length);Gc(s,c);let h=u.slice();h[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,h,s[0].dataType),{inputs:d})},Kc=n=>qt({axis:n.axis})}),Vi,Wi,Ei,Ya,Gi=p(()=>{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,Fn];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=p(()=>{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=p(()=>{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=p(()=>{Zt(),Jt(),ur(),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,h=32,d=!1,x=32)=>{let k=i[1]*n[1],$=i[0]*n[0],H=c?k:h,q=c?h:k,v=H/i[0],oe=h/i[1];if(!((c&&v===4&&n[1]===4||!c&&(v===3||v===4))&&H%i[0]===0&&h%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 ${h} 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]}>, ${h}>; + +const rowPerThread = ${n[1]}; +const colPerThread = ${n[0]}; +const innerElementSize = ${v}; +const tileInner = ${h}; + +@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/h)}`:"(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,h=32,d=!1,x=32,k=!1)=>{let $=n[1]*i[1],H=n[0]*i[0],q=c?$:h,v=c?h:$;if(!(v%i[1]===0&&q%i[0]===0&&h%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 ${h} must be divisible by workgroupSize[1]${i[1]}`);let oe=v/i[1],re=q/i[0],ce=h/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 < ${h}; 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) * ${re}; +let tileRowB = i32(localId.y) * ${ce}; +// Loop over shared dimension. +for (var t = 0; t < num_tiles; t = t + 1) { + // Load one tile of A into local memory. + for (var innerRow = 0; innerRow < ${oe}; innerRow = innerRow + 1) { + for (var innerCol = 0; innerCol < ${re}; 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 < ${ce}; innerRow = innerRow + 1) { + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + let inputRow = tileRowB + innerRow; + let inputCol = tileCol + innerCol; + mm_Bsub[inputRow][inputCol] = mm_readB(batch, + kStart + inputRow, + globalCol + innerCol${u?", batchIndices":""}); + } + } + kStart = kStart + tileInner; + workgroupBarrier(); + + // Compute acc values for a single thread. + var BCached : array<${s}, colPerThread>; + for (var k = 0; k < tileInner; k = k + 1) { + for (var inner = 0; inner < colPerThread; inner = inner + 1) { + BCached[inner] = mm_Bsub[k][tileCol + inner]; + } + + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + ${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, ${h}>; + const rowPerThread = ${n[1]}; + const colPerThread = ${n[0]}; + const tileInner = ${h}; + +@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/h)}`:"(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,h=!1)=>{let[d,x,k]=c,[$,H,q,v]=u,oe=wo(d,k),re=wo(x,k),ce=Tr(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 re.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,ce)} { + var value = ${vn(n,ce)}(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,ce)} { + var value = ${vn(n,ce)}(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,ce)}) { + 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 + ${h?"bias[colIn]":`${vn(n,ce)}(bias[row])`};`:""} + ${s} + ${v.setByIndices("vec3(coords)","value")} + } + } + `},tl=(n,i,s,u,c=!1)=>{let h=n[0].dims,d=n[1].dims,x=h.slice(0,-2),k=d.slice(0,-2),$=u?u.slice(0,-2):s.slice(0,-2),H=ct.size($),q=h[h.length-2],v=h[h.length-1],oe=d[d.length-1],re=v%4===0&&oe%4===0,ce=q<=8?[4,1,1]:[4,4,1],we=[8,8,1],be=[Math.ceil(oe/we[0]/ce[0]),Math.ceil(q/we[1]/ce[1]),Math.ceil(H/we[2]/ce[2])],he=re?4:1,De=[...x,q,v/he],Ae=De.length,Ie=[...k,v,oe/he],gt=Ie.length,ut=[H,q,oe/he],yt=[{type:6,data:q},{type:6,data:oe},{type:6,data:v}];Wi(i,yt),yt.push(...$t($,De,Ie));let Dt=["rank","rank"],Bt=n.length>2;Bt&&(yt.push(...$t(n[2].dims)),Dt.push("rank")),yt.push(...$t(ut));let mr=vr=>{let or=$.length,Ir=ma("batchDims",n[0].dataType,or,1),Zr=Tr(n[0].dataType),fr=_t("a",n[0].dataType,Ae,he),Gr=_t("b",n[1].dataType,gt,he),jt=Gt("result",n[0].dataType,ut.length,he),er=[fr,Gr];if(Bt){let Vr=c?he:1;er.push(_t("bias",n[2].dataType,n[2].dims.length,Vr))}let _r=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];Ei(i,_r);let ot=Tr(jt.type.tensor),Wt=Vi(i,jt.type.value,ot),ir=Ns(he,Bt,Wt,[Ir,fr,Gr,jt],[x,k,$],c);return` + ${vr.registerUniforms(_r).registerInternalVariables(Ir).declareVariables(...er,jt)} + ${ir} + ${re?Rs(ce,we,Zr,Ir):Bs(ce,we,Zr,Ir)} + `};return{name:"MatMul",shaderCache:{hint:`${ce};${i.activation};${re};${c}`,inputDependencies:Dt},getRunData:()=>({outputs:[{dims:s,dataType:n[0].dataType}],dispatchGroup:{x:be[0],y:be[1],z:be[2]},programUniforms:yt}),getShaderSource:mr}}}),Zc,lp,up=p(()=>{Zt(),Nn(),ur(),Gi(),xo(),Xc(),js(),Zc=(n,i,s,u,c=!1,h,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); + `,re=n?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",ce=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 < ${re} && xCol >= 0 && xCol < ${ce}) { + ${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,$),yt=Vi(h,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)} + ${yt} + setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); + } + }`},lp=(n,i,s,u,c,h,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],re=k&&($%4===0||$%3===0)&&oe%4===0,ce=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(ce/be[0]/he[0]),Math.ceil(we/be[1]/he[1]),Math.ceil(H/be[2]/he[2])];Ur("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${De}`);let Ae=re?k&&$%4!==0?3:4:1,Ie=be[1]*he[1],gt=be[0]*he[0],ut=Math.max(be[0]*Ae,be[1]),yt=u%Ie===0,Dt=c%gt===0,Bt=h%ut===0,mr=re?[Ae,4,4]:[1,1,1],vr=[{type:6,data:u},{type:6,data:c},{type:6,data:h},{type:6,data:[i.pads[0],i.pads[1]]},{type:6,data:i.strides},{type:6,data:i.dilations}];Wi(i,vr),vr.push(...$t(n[0].dims,n[1].dims));let or=["rank","rank"];d&&(vr.push(...$t(n[2].dims)),or.push("rank")),vr.push(...$t(s));let Ir=Zr=>{let fr=[{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,fr);let Gr=re?4:1,jt=Tr(n[0].dataType),er=` + fn setOutputAtIndex(flatIndex : i32, value : ${re?`vec4<${jt}>`:jt}) { + result[flatIndex] = ${re?`vec4<${jt}>`:jt}(value); + } + fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${re?`vec4<${jt}>`:jt}) { + let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3)); + setOutputAtIndex(flatIndex ${re?"/ 4":""}, value); + }`,_r=_t("x",n[0].dataType,n[0].dims.length,Ae===3?1:Ae),ot=_t("w",n[1].dataType,n[1].dims.length,Gr),Wt=[_r,ot],ir=Gt("result",n[0].dataType,s.length,Gr);if(d){let Vr=_t("bias",n[2].dataType,n[2].dims.length,Gr);Wt.push(Vr),er+=` + fn getBiasByOutputCoords(coords : vec4) -> ${re?`vec4<${jt}>`:jt} { + return bias[coords.${k?"w":"y"}${re?"/ 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(fr).declareVariables(...Wt,ir)} + ${er} + ${Zc(k,yt,Dt,Bt,d,i,mr[0],mr[1],mr[2],jt)} + ${re?Rs(he,be,jt,void 0,!k,ut):Bs(he,be,jt,void 0,!k,ut,!1,void 0,x)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${i.cacheKey};${Ae};${re};${yt};${Dt};${Bt};${Ie};${gt};${ut}`,inputDependencies:or},getRunData:()=>({outputs:[{dims:s,dataType:n[0].dataType}],dispatchGroup:{x:De[0],y:De[1],z:De[2]},programUniforms:vr}),getShaderSource:Ir}}}),Jc,rl,Ci,ed,nl,td,rd,nd,il=p(()=>{Zt(),Nn(),Jt(),ur(),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 h=[0,0,0,s];for(let d=0;d<3;d++)n[d]+2*c>=i[d]&&(h[d]=Math.trunc((n[d]-i[d]+2*c)/u[d]+1));return h},td=(n,i,s,u,c,h,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 re=nl([i,s,u,1],[x,k,$],1,[c,h,d],n);q=re[0],v=re[1],oe=re[2]}else if(Array.isArray(n)){if(!n.every((ce,we,be)=>ce===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 re=nl([i,s,u,1],[x,k,$],1,[c,h,d],n[0]);q=re[0],v=re[1],oe=re[2]}else if(n==="SAME_UPPER"){q=Math.ceil(i/c),v=Math.ceil(s/h),oe=Math.ceil(u/d);let re=(q-1)*c+x-i,ce=(v-1)*h+k-s,we=(oe-1)*d+$-u,be=Math.floor(re/2),he=re-be,De=Math.floor(ce/2),Ae=ce-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,h=!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,re,ce]=i,[we,be,he]=rl(s),[De,Ae,Ie]=rl(u),gt=Ci(oe,De),ut=Ci(re,Ae),yt=Ci(ce,Ie),{padInfo:Dt,outDepth:Bt,outHeight:mr,outWidth:vr}=td(c,k,$,H,we,be,he,gt,ut,yt),or=h?v*q:v,Ir=[0,0,0,0,0];return d==="channelsFirst"?Ir=[x,or,Bt,mr,vr]:d==="channelsLast"&&(Ir=[x,Bt,mr,vr,or]),{batchSize:x,dataFormat:d,inDepth:k,inHeight:$,inWidth:H,inChannels:q,outDepth:Bt,outHeight:mr,outWidth:vr,outChannels:or,padInfo:Dt,strideDepth:we,strideHeight:be,strideWidth:he,filterDepth:oe,filterHeight:re,filterWidth:ce,effectiveFilterDepth:gt,effectiveFilterHeight:ut,effectiveFilterWidth:yt,dilationDepth:De,dilationHeight:Ae,dilationWidth:Ie,inShape:n,outShape:Ir,filterShape:i}},nd=(n,i,s,u,c,h)=>{let d=h==="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];Ur("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(...$t(n[0].dims,n[1].dims));let oe=["rank","rank"],re=n.length===3;re&&(v.push(...$t(n[2].dims)),oe.push("rank")),v.push(...$t(s));let ce=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=Tr(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),yt="";if(re){let mr=_t("bias",n[2].dataType,n[2].dims.length,he);gt.push(mr),yt+=` + fn getBiasByOutputCoords(coords : array) -> ${De} { + return bias[${d?Ot("coords",4,5):Ot("coords",1,5)}]; + }`}let Dt=vn(H,De),Bt=Vi(i,Dt,De);return` + ${yt} + 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 = ${Ot("coords",0,Ae.rank)}; + let d2 = ${d?Ot("coords",Ae.rank-1,Ae.rank):Ot("coords",1,Ae.rank)}; + let xFRCCorner = vec3(${d?Ot("coords",1,Ae.rank):Ot("coords",2,Ae.rank)}, + ${d?Ot("coords",2,Ae.rank):Ot("coords",3,Ae.rank)}, + ${d?Ot("coords",3,Ae.rank):Ot("coords",4,Ae.rank)}) * uniforms.strides - uniforms.pads; + let xFCorner = xFRCCorner.x; + let xRCorner = xFRCCorner.y; + let xCCorner = xFRCCorner.z; + let xShapeY = ${d?Ot("uniforms.x_shape",1,Ae.rank):Ot("uniforms.x_shape",2,Ae.rank)}; + let xShapeZ = ${d?Ot("uniforms.x_shape",2,Ae.rank):Ot("uniforms.x_shape",3,Ae.rank)}; + let xShapeW = ${d?Ot("uniforms.x_shape",3,Ae.rank):Ot("uniforms.x_shape",4,Ae.rank)}; + let xShapeU = ${d?Ot("uniforms.x_shape",4,Ae.rank):Ot("uniforms.x_shape",1,Ae.rank)}; + let inputDepthNearestVec4 = (xShapeU / 4) * 4; + let inputDepthVec4Remainder = xShapeU % 4; + + var value = 0.0; + for (var wF = 0u; wF < uniforms.filter_dims[0]; wF++) { + let xF = xFCorner + wF * uniforms.dilations[0]; + if (xF < 0 || xF >= xShapeY) { + continue; + } + + for (var wR = 0u; wR < uniforms.filter_dims[1]; wR++) { + let xR = xRCorner + wR * uniforms.dilations[1]; + if (xR < 0 || xR >= xShapeZ) { + continue; + } + + for (var wC = 0u; wC < uniforms.filter_dims[2]; wC++) { + let xC = xCCorner + wC * uniforms.dilations[2]; + if (xC < 0 || xC >= xShapeW) { + continue; + } + + for (var d1 = 0u; d1 < inputDepthNearestVec4; d1 += 4) { + ${d?`let xValues = vec4( + getX(batch, xF, xR, xC, d1), + getX(batch, xF, xR, xC, d1 + 1), + getX(batch, xF, xR, xC, d1 + 2), + getX(batch, xF, xR, xC, d1 + 3)); + `:`let xValues = vec4( + getX(batch, d1, xF, xR, xC), + getX(batch, d1 + 1, xF, xR, xC), + getX(batch, d1 + 2, xF, xR, xC), + getX(batch, d1 + 3, xF, xR, xC)); + `} + let wValues = vec4( + getW(d2, d1, wF, wR, wC), + getW(d2, d1 + 1, wF, wR, wC), + getW(d2, d1 + 2, wF, wR, wC), + getW(d2, d1 + 3, wF, wR, wC)); + value += dot(xValues, wValues); + } + if (inputDepthVec4Remainder == 1) { + ${d?`value += getX(batch, xF, xR, xC, inputDepthNearestVec4) + * getW(d2, inputDepthNearestVec4, wF, wR, wC);`:`value += getX(batch, inputDepthNearestVec4, xF, xR, xC) + * getW(d2, inputDepthNearestVec4, wF, wR, wC);`} + } else if (inputDepthVec4Remainder == 2) { + ${d?`let xValues = vec2( + getX(batch, xF, xR, xC, inputDepthNearestVec4), + getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1)); + `:`let xValues = vec2( + getX(batch, inputDepthNearestVec4, xF, xR, xC), + getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC)); + `} + let wValues = vec2( + getW(d2, inputDepthNearestVec4, wF, wR, wC), + getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC)); + value += dot(xValues, wValues); + } else if (inputDepthVec4Remainder == 3) { + ${d?`let xValues = vec3( + getX(batch, xF, xR, xC, inputDepthNearestVec4), + getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1), + getX(batch, xF, xR, xC, inputDepthNearestVec4 + 2)); + `:`let xValues = vec3( + getX(batch, inputDepthNearestVec4, xF, xR, xC), + getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC), + getX(batch, inputDepthNearestVec4 + 2, xF, xR, xC)); + `} + let wValues = vec3( + getW(d2, inputDepthNearestVec4, wF, wR, wC), + getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC), + getW(d2, inputDepthNearestVec4 + 2, wF, wR, wC)); + value += dot(xValues, wValues); + } + } + } + } + ${re?"value = value + getBiasByOutputCoords(coords)":""}; + ${Bt} + result[global_idx] = f32(value); + }`};return{name:"Conv3DNaive",shaderCache:{hint:`${i.cacheKey};${d};${H};${re}`,inputDependencies:oe},getRunData:()=>({outputs:[{dims:s,dataType:n[0].dataType}],dispatchGroup:{x:$[0],y:$[1],z:$[2]},programUniforms:v}),getShaderSource:ce}}}),id,od,cp=p(()=>{Zt(),Jt(),ur(),cd(),Gi(),id=(n,i,s)=>{let u=n.length>2,c=u?"value += b[output_channel];":"",h=n[0].dims,d=n[1].dims,x=d[0]/i.group,k=i.format==="NHWC",$=Us(h,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(...$t(h,d));let v=["rank","rank"];u&&(q.push(...$t(n[2].dims)),v.push("rank")),q.push(...$t($));let oe=re=>{let ce=Gt("output",n[0].dataType,$.length),we=Tr(ce.type.tensor),be=Vi(i,ce.type.value,we),he=_t("x",n[0].dataType,h.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),` + ${re.registerUniforms(Ie).declareVariables(...Ae,ce)} + + ${re.mainStart()} + ${re.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let outputIndices = ${ce.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: ${ce.type.value} = ${ce.type.value}(0); + for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[1]; wInChannel++) { + let input_channel = group_id * uniforms.w_shape[1] + wInChannel; + for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[2]; wHeight++) { + let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0]; + + if (xHeight < 0u || xHeight >= uniforms.x_shape[${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} + ${ce.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=wr(s[3]),h=wr(s[2]),d=ct.size(s)/c/h,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(...$t(x,k,$));let q=(h-1)*i.strides[1]+k[1],v=oe=>{let re=Gt("output",n[0].dataType,$.length,c),ce=Tr(re.type.tensor),we=Vi(i,re.type.value,ce),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,re)} + ${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] / ${h}u; + let col = (index1 % width1) * ${h}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<${re.type.value}, ${h}>; + 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 < ${h}u; i++) { + values[i] = fma(x_vals[i * u32(uniforms.strides[1]) + w_width], w_val, values[i]); + } + } + } + } + + for (var i = 0u; i < ${h}u; i++) { + var value = values[i]; + ${Ae} + ${we} + ${re.set("batch","row","col + i","output_channel","value")}; + } + }`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${i.cacheKey};${c};${h};${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=p(()=>{Zt(),Jt(),js(),ur(),Gi(),ol=(n,i,s,u,c=!1)=>{let h=n[0].dims,d=n[1].dims,x=h[h.length-2],k=d[d.length-1],$=h[h.length-1],H=wr(k),q=wr($),v=wr(x),oe=ct.size(s)/H/v,re=n.length>2,ce=u?u.slice(0,-2):s.slice(0,-2),we=[ct.size(ce),x,k],be=[{type:12,data:oe},{type:12,data:x},{type:12,data:k},{type:12,data:$}];Wi(i,be),be.push(...$t(ce,h,d)),re&&be.push(...$t(n[2].dims)),be.push(...$t(we));let he=De=>{let Ae=ma("batch_dims",n[0].dataType,ce.length),Ie=_t("a",n[0].dataType,h.length,q),gt=_t("b",n[1].dataType,d.length,H),ut=Gt("output",n[0].dataType,we.length,H),yt=Tr(ut.type.tensor),Dt=Vi(i,ut.type.value,yt),Bt=[Ie,gt],mr="";if(re){let er=c?H:1;Bt.push(_t("bias",n[2].dataType,n[2].dims.length,er)),mr=`${c?`value += bias[col / ${er}];`:`value += ${ut.type.value}(bias[row + i]);`}`}let vr=h.slice(0,-2),or=d.slice(0,-2),Ir=wo(vr,ce),Zr=wo(or,ce),fr=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];Ei(i,fr);let Gr=(er,_r)=>{let ot=er.rank,Wt=er.name;if(ot===2)return`var ${Wt}_indices = ${er.type.indices}(0u, 0u);`;let ir=Ae.rank,Vr=`var ${Wt}_indices: ${er.type.indices};`;for(let fn=ot-2-1,kn=ir-1;fn>=0;fn--,kn--)Vr+=` +${Wt}_indices[${fn}] = ${ir>1?`batch_indices[${kn}]`:"batch_indices"};`;return _r.forEach(fn=>{Vr+=` +${Wt}_indices[${fn}] = 0;`}),Vr+=`${Wt}_indices[${ot-2}] = 0u; + ${Wt}_indices[${ot-1}] = 0u;`,Vr},jt=()=>{let er=`var a_data: ${Ie.type.value};`;for(let _r=0;_r; + for (var k: u32 = 0u; k < uniforms.K; k = k + ${q}) { + ${jt()} + } + for (var i = 0u; i < ${v}u; i++) { + var value = values[i]; + ${mr} + ${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:re?["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=p(()=>{Jt(),up(),il(),js(),cp(),Gi(),sl(),yo(),Us=(n,i,s,u,c,h)=>{let d=n[0],x=n.slice(h?1:2,h?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(h?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 h=2;h{let i=Ya(n),s=n.format,u=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][n.auto_pad],c=n.dilations,h=n.group,d=n.kernel_shape,x=n.pads,k=n.strides,$=n.w_is_const();return{autoPad:u,format:s,dilations:c,group:h,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 yt=[i[0],ut];i.length===3&&yt.push(i[2]),n.compute(od(yt,u,gt),{inputs:yt})}else n.compute(id(i,u));return}let h=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],re=q[c?3:1],ce=c&&$===d&&H===x&&s.pads[0]===0&&s.pads[1]===0;if(ce||$===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,yt,Dt,Bt=[];if(c){let or=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=or),ce){let Ir=d*x*k;ut=i[0].reshape([1,gt,Ir]),yt=or.reshape([1,Ir,re]),Dt=[1,gt,re]}else ut=i[0].reshape([gt,d*x,k]),yt=or.reshape([1,k,re]),Dt=[gt,v*oe,re];Bt.push(ut),Bt.push(yt)}else ut=i[0].reshape([gt,k,d*x]),yt=i[1].reshape([1,re,k]),Dt=[gt,re,v*oe],Bt.push(yt),Bt.push(ut);h&&Bt.push(i[2]);let mr=Dt[2],vr=Bt[0].dims[Bt[0].dims.length-1];mr<8&&vr<8?n.compute(ol(Bt,u,q,Dt,c),{inputs:Bt}):n.compute(tl(Bt,u,q,Dt,c),{inputs:Bt});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];h&&he.push(i[2]);let De=c?v*oe:re,Ae=c?re:v*oe,Ie=$*H*k;n.compute(lp(he,u,q,De,Ae,Ie,h,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]],h=[1].concat(i.strides),d=[1].concat(i.dilations),x=[1].concat(i.kernelShape),k=Ws({...i,pads:c,strides:h,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),h=s.autoPad==="NOTSET"?s.pads:s.autoPad,d=rd(i[0].dims,i[1].dims,s.strides,s.dilations,h,!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,fd,dp=p(()=>{Zt(),Nn(),ur(),Gi(),xo(),Xc(),js(),dd=(n,i=!1,s,u,c=4)=>{let h=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);`,re=` + 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); + ${h(c)} + } + return ${u}(0.0); + `,ce=Vi(s,u);return` + fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${u} { + ${n?oe:re} + } + + fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${u} { + ${n?re: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)} + ${ce} + result[getIndexFromCoords4D(coords, vec4(uniforms.result_shape))/${c}] = value; + } + }`},fd=(n,i,s,u,c,h,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],re=k&&$%4===0&&$%3&&oe%4===0,ce=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(ce/be[0]/he[0]),Math.ceil(we/be[1]/he[1]),Math.ceil(H/be[2]/he[2])];Ur("verbose",()=>`[conv_backprop_mm_webgpu] dispatch = ${De}`);let Ae=re?4:1,Ie=Math.max(be[0]*Ae,be[1]),gt=re?4:1,ut=[i.kernelShape[k?1:2],i.kernelShape[k?2:3]],yt=[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=[yt[0]-1-Math.floor((i.pads[0]+i.pads[2])/2),yt[1]-1-Math.floor((i.pads[1]+i.pads[3])/2)],Bt=[{type:6,data:u},{type:6,data:c},{type:6,data:h},{type:6,data:i.strides},{type:6,data:i.dilations},{type:6,data:ut},{type:6,data:Dt}];Wi(i,Bt),Bt.push(...$t(n[0].dims,n[1].dims));let mr=["rank","rank"];d&&(Bt.push(...$t(n[2].dims)),mr.push("rank")),Bt.push(...$t(s));let vr=or=>{let Ir=_t("x",n[0].dataType,n[0].dims.length,gt),Zr=_t("w",n[1].dataType,n[1].dims.length,1),fr=Gt("result",n[0].dataType,s.length,gt),Gr=[Ir,Zr],jt="";if(d){let ot=_t("bias",n[2].dataType,n[2].dims.length,gt);Gr.push(ot),jt+=` + fn getBiasByOutputCoords(coords : vec4) -> ${ot.type.value} { + return bias[coords.${k?"w":"y"}${re?"/ 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 _r=Tr(n[0].dataType,1);if(_r!=="f16"&&_r!=="f32")throw new Error(`elemType ${_r} is not supported.`);return` + ${Ja("uniforms.result_strides")} + ${or.registerUniforms(er).declareVariables(...Gr,fr)}; + ${jt} + ${dd(k,d,i,Ir.type.value,Ae)} + ${re?Rs(he,be,_r,void 0,!k,Ie):Bs(he,be,_r,void 0,!k,Ie,!1,void 0,x)}`};return{name:"Conv2DTransposeMatMul",shaderCache:{hint:`${i.cacheKey};${he};${be};${re}`,inputDependencies:mr},getRunData:()=>({outputs:[{dims:s,dataType:n[0].dataType}],dispatchGroup:{x:De[0],y:De[1],z:De[2]},programUniforms:Bt}),getShaderSource:vr}}}),cl,Xo,mm=p(()=>{Zt(),Nn(),Jt(),ur(),cl=(n,i,s,u,c,h=!1,d,x,k=!1)=>{let $=k?1:2,H=k?2:3,q=k?3:1,v=h?2:1,oe=` + fn setOutputAtIndex(flatIndex : u32, value : ${h?`vec4<${d}>`:d}) { + result[flatIndex] = ${h?`vec4<${d}>`:d}(value); + }`;u&&(oe+=` + fn getBiasByOutputCoords(coords : vec4) -> ${h?`vec4<${d}>`:d} { + return bias[coords.${k?"w":"y"}${h?"/ 4":""}]; + }`);let re=h?4:1,ce=_t("W",i[1].dataType,i[1].dims.length,re),we=_t("Dy",i[0].dataType,i[0].dims.length,re),be=[we,ce];u&&be.push(_t("bias",i[2].dataType,[s[q]].length,re));let he=Gt("result",i[0].dataType,s.length,re),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 = ${ce.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; + let wValue1 = ${ce.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; + let wValue2 = ${ce.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; + let wValue3 = ${ce.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; + + var xValue = ${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 = ${ce.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; + let wValue1 = ${ce.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; + let wValue2 = ${ce.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; + let wValue3 = ${ce.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; + + var xValue = ${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 = ${ce.get("u32(wRPerm)","u32(wCPerm)","d1","d2")}; + let wValue1 = ${ce.get("u32(wRPerm)","u32(wCPerm)","d1 + 1","d2")}; + let wValue2 = ${ce.get("u32(wRPerm)","u32(wCPerm)","d1 + 2","d2")}; + let wValue3 = ${ce.get("u32(wRPerm)","u32(wCPerm)","d1 + 3","d2")}; + + var xValue = ${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 = ${ce.get("inputChannel","wOutChannel","u32(wRPerm)","u32(wCPerm)")}; + dotProd = dotProd + xValue * wValue; + inputChannel = inputChannel + 1; + } + } + } + let value = dotProd + ${u?"bias[d1]":`${d}(0.0)`}; + ${he.setByOffset("global_idx","value")}; + `;return` + ${n.registerUniforms(x).declareVariables(...be,he)} + ${oe} + + ${n.mainStart()} + ${n.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}; + ${h?De:Ae}}`},Xo=(n,i,s)=>{let u=n.length>2,c=i.outputShape,h=ct.size(c),d=[Math.ceil(h/64),1,1];Ur("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],re=!1,ce=i.group,we=n[1].dims,be=we[0]/ce,he=we[1],De=[{type:12,data:h},{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},...$t(n[0].dims,n[1].dims)];u&&(De.push(...$t(n[2].dims)),k.push("rank")),De.push(...$t(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"}],yt=Tr(n[0].dataType);return`${cl(gt,n,c,u,Ae,re,yt,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}}}),pd,hd,dl,fl,md,pl,gd,_d,hl,fp,gm=p(()=>{dp(),mm(),Gi(),yo(),pd=(n,i,s,u,c,h)=>(n-1)*i+s+(u-1)*c+1-h,hd=(n,i,s,u,c)=>{let h=Math.floor(n/2);i==="SAME_UPPER"?(s[u]=h,s[c]=n-h):i==="SAME_LOWER"&&(s[u]=n-h,s[c]=h)},dl=(n,i,s,u,c,h,d,x,k,$)=>{let H=n.length-2,q=$.length===0;if(k.length===0)for(let re=0;re{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,h);let H=Object.assign({},n);return Object.assign(H,{kernelShape:s,pads:c,outputPadding:d,outputShape:h,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,h=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:h,kernelShape:d,outputPadding:H,outputShape:q,pads:x,strides:k,wIsConst:$,...i,cacheKey:`${n.format};${i.activation};`}},pl=(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 h=n[0].dims.length-2;if(i.dilations.reduce((d,x)=>d+x,0)>0&&i.dilations.length!==h)throw new Error(`dilations should be ${h}D`);if(i.strides.reduce((d,x)=>d+x,0)>0&&i.strides.length!==h)throw new Error(`strides should be ${h}D`);if(i.pads.reduce((d,x)=>d+x,0)>0&&i.pads.length!==h*2)throw new Error(`pads should be ${h*2}D`);if(i.outputPadding.length!==h&&i.outputPadding.length!==0)throw new Error(`output_padding should be ${h}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=fl(s,i),c=s.format==="NHWC",h=u.outputShape,d=h[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=h[c?1:2],$=h[c?2:3],H=i[1].dims[2],q=i[1].dims[3],v=c?k*$:d,oe=c?d:k*$,re=H*q*x,ce=!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(fd(be,u,h,v,oe,re,he,ce),{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 h=i.dilations;(h.length===0||h[0]===0)&&(h=[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),h=[1].concat(h),c=[1].concat(c);let k=fl({...i,pads:x,strides:d,dilations:h,kernelShape:c},u);n.compute(Xo(u,k,$=>s?[$[0],$[2],$[3]]:[$[0],$[1],$[3]]))},fp=(n,i)=>{pl(n.inputs,i),n.inputs[0].dims.length===3?hl(n,i):_d(n,n.inputs,i)}}),ml,gl,wd,pp=p(()=>{Zt(),Jt(),gr(),ur(),ml=(n,i,s,u)=>{let c=ct.size(i),h=i.length,d=_t("input",n,h),x=Gt("output",n,h),k=s.dataType===6?s.getInt32Array()[0]:Number(s.getBigInt64Array()[0]),$=ct.normalizeAxis(k,h),H=q=>{let v=` i32(${d.indicesGet("inputIndices","uniforms.axis")}) `,oe=Ot("uniforms.input_shape","uniforms.axis",h),re=u.reverse?v+(u.exclusive?" + 1":""):"0",ce=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 = ${re}; + let last : i32 = ${ce}; + for (var i : i32 = first; i < last; i++) { + ${d.indicesSet("inputIndices","uniforms.axis","u32(i)")}; + sum = sum + ${d.getByIndices("inputIndices")}; + } + ${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:$},...$t(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,hp=p(()=>{Zt(),Jt(),gr(),ur(),_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 h=0;h{let s,u,c,h,d,x,k=i.format==="NHWC",$=i.blocksize,H=i.mode==="DCR";k?([s,u,c,h]=n.dims,d=H?[s,u,c,$,$,h/$**2]:[s,u,c,h/$**2,$,$],x=H?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([s,u,c,h]=[n.dims[0],n.dims[2],n.dims[3],n.dims[1]],d=H?[s,$,$,h/$**2,u,c]:[s,h/$**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,re=_t("a",oe,v),ce=Gt("output",oe,v),we=be=>` + ${be.registerUniform("output_size","u32").declareVariables(re,ce)} + + ${yd(x,v,re,ce)} + + ${be.mainStart()} + ${be.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${ce.offsetToIndices("global_idx")}; + let aIndices = perm(indices); + + ${ce.setByOffset("global_idx",re.getByIndices("aIndices"))} + }`;return{name:"DepthToSpace",shaderCache:{hint:`${n.dims};${i.blocksize};${i.mode}`,inputDependencies:["rank"]},getRunData:be=>{let he=k?[s,u*$,c*$,h/$**2]:[s,h/$**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},...$t(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,Lr,mp,gp,_p,Gs,xd,Md,Td,wp=p(()=>{Zt(),Jt(),gr(),ur(),Qo="[a-zA-Z]|\\.\\.\\.",Yo="("+Qo+")+",yl="^"+Yo+"$",Lr="("+Yo+",)*"+Yo,mp="^"+Lr+"$",gp=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)}},_p=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(mp)))throw new Error("Invalid LHS term");if(s.split(",").forEach((h,d)=>{let x=n[d].dims.slice();if(!h.match(RegExp(yl)))throw new Error("Invalid LHS term");let k=this.processTerm(h,!0,x,d);this.lhs.push(k)}),u==="")u+=[...this.symbolToInfo.entries()].filter(([h,d])=>d.count===1||h==="...").map(([h])=>h).join("");else if(!u.match(RegExp(Yo)))throw new Error("Invalid RHS");(c=u.match(RegExp(Qo,"g")))==null||c.forEach(h=>{if(h==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let d=this.symbolToInfo.get(h);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,h=!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 gp(u);return k==null||k.forEach((H,q)=>{if(H==="..."){if(h)throw new Error("Only one ellipsis is allowed per input term");h=!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,$)),h=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;",re=[],ce=[],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((yt,Dt)=>{if(Ae.inputIndices.includes(Dt)){let Bt=yt.symbolToIndices.get(Ie);if(Bt===void 0)throw new Error("Invalid symbol error");Bt.forEach(mr=>{H.push(`${c[Dt].indicesSet(`input${Dt}Indices`,mr,d.indicesGet("outputIndices",ut))}`)})}})}else s.lhs.forEach((ut,yt)=>{if(Ae.inputIndices.includes(yt)){let Dt=ut.symbolToIndices.get(Ie);if(Dt===void 0)throw new Error("Invalid symbol error");Dt.forEach(Bt=>{re.push(`${c[yt].indicesSet(`input${yt}Indices`,Bt,`${Ie}`)}`)}),be.push(`prod *= ${c[yt].getByIndices(`input${yt}Indices`)};`)}}),ce.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,...ce,...re,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:h});let H=n.map((q,v)=>[...$t(q)]).reduce((q,v)=>q.concat(v),$);return H.push(...$t(u)),{outputs:[{dims:u,dataType:i}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:H}},getShaderSource:k}},Md=(n,i)=>{let s=new _p(n.inputs,i.equation),u=s.outputDims,c=n.inputs.map((h,d)=>h.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=p(()=>{Zt(),Jt(),ur(),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,h=c===9?4:1,d=Math.ceil(ct.size(u)/h),x=$=>{let H=_t("input",c,i.length,h),q=Gt("output",c,u.length,h),v;if(c===9){let oe=(re,ce,we="")=>` + let outputIndices${ce} = ${q.offsetToIndices(`outputOffset + ${ce}u`)}; + let offset${ce} = ${H.broadcastedIndicesToOffset(`outputIndices${ce}`,q)}; + let index${ce} = offset${ce} / 4u; + let component${ce} = offset${ce} % 4u; + ${re}[${ce}] = ${we}(${H.getByOffset(`index${ce}`)}[component${ce}]); + `;v=` + let outputOffset = global_idx * ${h}; + 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},...$t(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]})}}),yp,Ed,vp=p(()=>{Zt(),Jt(),ur(),Ha(),yp=n=>{let i=n[0].dataType,s=ct.size(n[0].dims),u=ct.size(n[1].dims),c=u%4===0,h=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(kr(i))} + + ${d.mainStart(jn)} + ${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:h,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/jn/4)}})}},Ed=n=>{n.inputs.length<2||ct.size(n.inputs[1].dims)===0?Ec(n):n.compute(yp(n.inputs))}}),Cd,Pd,$d,Ad,bp=p(()=>{Zt(),Jt(),gr(),ur(),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,h=ct.normalizeAxis(i.axis,c),d=s.slice(0);d.splice(h,1,...u);let x=s[h],k=n[0].dataType===9?4:1,$=Math.ceil(ct.size(d)/k),H=[{type:12,data:$},{type:6,data:x},{type:12,data:h},...$t(n[0].dims,n[1].dims,d)],q=v=>{let oe=_t("data",n[0].dataType,n[0].dims.length,k),re=_t("inputIndices",n[1].dataType,n[1].dims.length),ce=Gt("output",n[0].dataType,d.length,k),we=he=>{let De=u.length,Ae=`var indicesIndices${he} = ${re.type.indices}(0);`;for(let Ie=0;Ie1?`indicesIndices${he}[${Ie}]`:`indicesIndices${he}`} = ${d.length>1?`outputIndices${he}[uniforms.axis + ${Ie}]`:`outputIndices${he}`};`;Ae+=` + var idx${he} = ${re.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} = ${ce.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")} + ${ce.setByOffset("global_idx","value")} + `}else be=` + let outputIndices = ${ce.offsetToIndices("global_idx")}; + ${we("")}; + let value = ${oe.getByIndices("dataIndices")}; + ${ce.setByOffset("global_idx","value")}; + `;return` + ${v.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(oe,re,ce)} + ${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,zd,Od,xp=p(()=>{Zt(),Jt(),gr(),ur(),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,h=n[1].dims,d=n[1].dataType,x=ct.normalizeAxis(i.axis,c),k=s[x],$=h.slice(0),H=ct.size($),q=_t("input",u,c),v=_t("indicesInput",d,h.length),oe=Gt("output",u,$.length),re=[{type:12,data:H},{type:6,data:k},{type:12,data:x}];return re.push(...$t(s,h,$)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:$,dataType:n[0].dataType}],dispatchGroup:{x:Math.ceil(H/64)},programUniforms:re}),getShaderSource:ce=>` + ${ce.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(q,v,oe)} + ${ce.mainStart()} + ${ce.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")}; + }`}},zd=n=>qt({axis:n.axis}),Od=(n,i)=>{let s=n.inputs;Id(s),n.compute(Fd(n.inputs,i))}}),Dd,Ld,Rd,Mp,Bd=p(()=>{Zt(),Jt(),ur(),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,h,d]=br.getShapeOfGemmResult(s,i.transA,u,i.transB,n.length===3?n[2].dims:void 0),x=[c,h];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:h},{type:12,data:d},{type:1,data:i.alpha},{type:1,data:i.beta}],H=["type","type"];n.length===3&&($.push(...$t(n[2].dims)),H.push("rank")),$.push(...$t(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 re=i.alpha===1?"":"value *= uniforms.alpha;",ce=_t("a",n[0].dataType,n[0].dims),we=_t("b",n[1].dataType,n[1].dims),be=ce.type.value,he=null,De=[ce,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} + } + + ${re} + ${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}`}},Mp=(n,i)=>{Dd(n.inputs),n.compute(Ld(n.inputs,i))}}),Pn,Nd,jd,xl,Ud,Zo,Vd,Wd=p(()=>{Zt(),Jt(),gr(),fe(),Os(),ur(),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),h=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],re=v,ce=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');ce=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,re=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,re=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,re=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(h){if(h.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 yt=d.dims;throw yt.length===1?yt[0]===q?De=1:yt[0]===3*q+2&&(De=3):yt.length===2&&yt[0]===q&&yt[1]===re&&(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(re!==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(re!==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=ce+re,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:ce,kvSequenceLength:re,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,h,d)=>{let x=[u,c,h],k=ct.size(x),$=[{type:12,data:k},{type:12,data:d},{type:12,data:h}],H=q=>{let v=Gt("qkv_with_bias",i.dataType,x),oe=_t("qkv",i.dataType,x),re=_t("bias",s.dataType,x),ce=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return` + ${q.registerUniforms(ce).declareVariables(oe,re,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,h,d,x)=>{let k=h;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,h,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 h.dims.length===3&&(k=h.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),h=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&&h&&c.dims.length===4&&h.dims.length===4,v=Zo(n,s.batchSize,s.numHeads,s.sequenceLength,s.headSize,u,d,0);if(q)return vo(n,v,c,h,x,void 0,$,H,k,s,i);if(!c||!h)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),re=Zo(n,s.batchSize,s.numHeads,s.kvSequenceLength,s.vHeadSize,h,d,2*s.hiddenSize);vo(n,v,oe,re,x,void 0,$,H,k,s,i)}}),Ml,Gd,Hd,Tl,qd,Kd=p(()=>{Zt(),Jt(),ur(),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),h=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(h/64)},programUniforms:[{type:12,data:h},...$t(n[0].dims,c)]}),getShaderSource:$}},qd=n=>{Gd(n.inputs),n.compute(Tl(n.inputs),{inputs:[0]})}}),Xd,kl,Qd,Yd,Sl,Zd,Tp=p(()=>{Zt(),Jt(),gr(),Os(),ur(),Wd(),Kd(),yo(),Xd=(n,i)=>{let s=n[0],u=n[1],c=n[2],h=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,re=Math.floor(H/i.numHeads),ce=h&&h.dims.length!==0,we=d&&d.dims.length!==0,be=!0;if(ce&&we){if(h.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=h.dims[1],oe=h.dims[1]}else if(ce||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]!==re)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(c)throw new Error('Expect "value" be none when "key" has packed kv format.');he=5,q=u.dims[1]}else{if(u.dims[1]!==i.numHeads||u.dims[3]!==re)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');he=0,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:re,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],h=4,d=ct.size(c)/h,x=u.totalSequenceLength,k=Gt("present_kv",s,c.length,h),$=_t("new_kv",n.dataType,n.dims.length,h),H=i?_t("past_kv",i.dataType,i.dims.length,h):void 0,q=Math.ceil(u.headSize/h),v={x,y:n.dims[0],z:1},oe=i?["rank","rank"]:["rank"],re=[{type:12,data:d},{type:12,data:u.pastSequenceLength},{type:12,data:u.kvSequenceLength},{type:12,data:u.totalSequenceLength}],ce=[$];H?(re.push(...$t(n.dims),...$t(i.dims),...$t(c)),ce.push(H)):re.push(...$t(n.dims),...$t(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(...ce,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:re}),getShaderSource:Ae}},Qd=n=>qt({...n}),Yd=qt({perm:[0,2,1,3]}),Sl=(n,i,s,u,c)=>{let h=i,d=u.kvNumHeads,x=u.nReps;return i.dims.length===3&&u.kvSequenceLength!==0&&(h=i.reshape([u.batchSize,u.kvSequenceLength,d,u.headSize])),s?h=n.compute(kl(h,s,h.dataType,u),{inputs:[h,s],outputs:[u.isPastkvBSNH?c:-1]})[0]:h=n.compute(kl(h,void 0,h.dataType,u),{inputs:[h],outputs:[u.isPastkvBSNH?c:-1]})[0],x!==1&&(h=n.compute(Tl([h],[1,1,1,x]),{inputs:[h],outputs:[-1]})[0],h=h.reshape([u.batchSize,u.totalSequenceLength,d*x,u.headSize])),n.compute(hi(h,Yd.perm),{inputs:[h],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,h=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],h,s,2);vo(n,u,d,x,void 0,void 0,void 0,void 0,void 0,s,i)}}),Jd,ef,tf,rf,wm=p(()=>{Zt(),Jt(),ur(),Jd=(n,i)=>{let s=n[0].dims,u=s,c=2,h=ct.sizeToDimension(s,c),d=ct.sizeFromDimension(s,c),x=wr(d),k=d/x,$=[s[0],s[1],k],H=["rank","type","type"],q=[{type:12,data:d},{type:12,data:k}];q.push(...$t($,$));let v=oe=>{let re=_t("x",n[0].dataType,$.length,x),ce=_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=[re,ce,we,be],De=re.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}(${re.get("batch","channel","h")}); + } + workgroupShared[localIndex] = initial; + workgroupBarrier(); + + // Calculate the mean of current channel data. + for (var currSize = workgroupSize >> 1; currSize > 0; currSize = currSize >> 1) { + if (localIndex < currSize) { + workgroupShared[localIndex] = workgroupShared[localIndex] + workgroupShared[localIndex + currSize]; + } + workgroupBarrier(); + } + if (localIndex == 0) { + meanShared = ${Un("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}(${re.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 = ${Un("workgroupShared[0]",x)}; + } + workgroupBarrier(); + + let invStdDev = inverseSqrt(squaredNormShared / f32(uniforms.normSize) + f32(${i.epsilon})); + let channelScale = invStdDev * f32(${ce.getByOffset("channel")}); + let channelShift = f32(${we.getByOffset("channel")}) - meanShared * channelScale; + for (var h = localIndex; h < uniforms.normPackedSize; h += workgroupSize) { + let value = ${re.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:h},programUniforms:q}),getShaderSource:v}},ef=(n,i,s,u,c,h,d,x)=>{let k=wr(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,re=Math.ceil(h/$),ce=["type"],we=[{type:12,data:re},{type:12,data:h},{type:12,data:Math.floor(d/k)},{type:12,data:Math.floor(h*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 = ${Dr("f32",k)}; + var squaredSum = ${Dr("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:ce},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:h},{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),yt=_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<${yt.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 = ${Dr("f32",k)}; + var squaredSum = ${Dr("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]},tf=(n,i,s)=>{let u=i[0].dims,c=u,h=u[0],d=u[u.length-1],x=ct.sizeFromDimension(u,1)/d,k=wr(d),$=ct.size(c)/k,H=[{type:12,data:x},{type:12,data:Math.floor(d/k)}],q=["type","type"],v=ef(n,i[0],i[1],i[2],h,x,d,s.epsilon),oe=re=>{let ce=Tr(i[0].dataType),we=k===1?"vec2f":`mat2x${k}f`,be=k===1?ce:`vec${k}<${ce}>`,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; + + ${re.mainStart()} + let currentImageNumber = global_idx / (uniforms.C * uniforms.H); + let currentChannelNumber = global_idx % uniforms.C; + + let scaleOffset = currentImageNumber * uniforms.C + currentChannelNumber; + let scale = scaleInput[scaleOffset]; + output[global_idx] = fma(input[global_idx], ${be}(scale[0]), ${be}(scale[1])); + }`};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]})},rf=(n,i)=>{i.format==="NHWC"?tf(n,n.inputs,i):n.compute(Jd(n.inputs,i))}}),cr,nf,hn,bn=p(()=>{Zt(),Jt(),ur(),cr=n=>{if(!n||n.length<2)throw new Error("layerNorm requires at least 2 inputs.")},nf=(n,i,s)=>{let u=i.simplified,c=n[0].dims,h=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(h.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=Tr(n[0].dataType),ut=[_t("x",n[0].dataType,n[0].dims,re),_t("scale",h.dataType,h.dims,re)];d&&ut.push(_t("bias",d.dataType,d.dims,re)),ut.push(Gt("output",n[0].dataType,x,re)),be&&ut.push(Gt("mean_data_output",1,oe)),he&&ut.push(Gt("inv_std_output",1,oe));let yt=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return` + ${Ie.registerUniforms(yt).declareVariables(...ut)} + ${Ie.mainStart()} + ${Ie.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")} + let offset = global_idx * uniforms.norm_size_vectorized; + var mean_vector = ${Dr("f32",re)}; + var mean_square_vector = ${Dr("f32",re)}; + + for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) { + let value = ${Xr(gt,re,"x[h + offset]")}; + mean_vector += value; + mean_square_vector += value * value; + } + let mean = ${Un("mean_vector",re)} / uniforms.norm_size; + let inv_std_dev = inverseSqrt(${Un("mean_square_vector",re)} / uniforms.norm_size ${u?"":"- mean * mean"} + uniforms.epsilon); + + for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) { + let f32input = ${Xr(gt,re,"x[j + offset]")}; + let f32scale = ${Xr(gt,re,"scale[j]")}; + output[j + offset] = ${ut[0].type.value}((f32input ${u?"":"- mean"}) * inv_std_dev * f32scale + ${d?`+ ${Xr(gt,re,"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:`${re};${s};${u}`,inputDependencies:ce},getRunData:()=>({outputs:Ae,dispatchGroup:{x:Math.ceil($/64)},programUniforms:we}),getShaderSource:De}},hn=(n,i)=>{cr(n.inputs),n.compute(nf(n.inputs,i,n.outputCount))}}),xn,to,kp,of,Sp=p(()=>{Zt(),Jt(),gr(),ur(),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),h=i.blockSize/8*i.bits,d=n[1];if(!ct.areEqual(d.dims,[i.n,c,h]))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,h=c.length,d=Math.floor((i.k+i.blockSize-1)/i.blockSize),x=c[h-2],k=i.k,$=i.n,H=c.slice(0,h-2),q=ct.size(H),v=i.blockSize/8*i.bits/4,oe=n[0].dataType,re=wr(x),ce=wr(i.k),we=wr(v),be=ki(oe),he=x*d*be,De=Math.floor(u/he),Ae=d<=s[0]&&De>0,Ie=!Ae||De>=4?wr($):De>=2&&wr($)>=2?2:1,gt=H.concat([x,$]),ut=ct.size(gt)/Ie/re,yt=Ae?[]:[{type:12,data:ut},{type:12,data:i.blockSize}],Dt=[q,x,k/ce],Bt=ct.convertShape(n[1].dims).slice();Bt.splice(-1,1,v/we),yt.push(...$t(Dt)),yt.push(...$t(Bt)),yt.push(...$t(n[2].dims)),n.length===4&&yt.push(...$t(ct.convertShape(n[3].dims)));let mr=[q,x,$/Ie];yt.push(...$t(mr));let vr=or=>{let Ir=Dt.length,Zr=_t("a",n[0].dataType,Ir,ce),fr=_t("b",12,Bt.length,we),Gr=_t("scales",n[2].dataType,n[2].dims.length),jt=[Zr,fr,Gr],er=n.length===4?_t("zero_points",12,n[3].dims.length):void 0;er&&jt.push(er);let _r=mr.length,ot=Gt("output",n[0].dataType,_r,Ie),Wt=[{name:"output_size",type:"u32"},{name:"block_size",type:"u32"}],ir=Tr(n[0].dataType),Vr=(()=>{switch(ce){case 1:return`array<${ir}, 8>`;case 2:return`mat4x2<${ir}>`;case 4:return`mat2x4<${ir}>`;default:throw new Error(`${ce}-component is not supported.`)}})(),fn=` + for (var word: u32 = 0; word < ${v}; word += ${we}) { + ${fr.indicesSet("b_indices","2","word")}; + let b_data = ${fr.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 = ${Vr}(${Array.from({length:4},(rs,si)=>`${ir}(b_value_lower[${si}]), ${ir}(b_value_upper[${si}])`).join(", ")}); + let b_dequantized_values = ${ce===1?`${Vr}(${Array.from({length:8},(rs,si)=>`(b_quantized_values[${si}] - zero_point) * scale`).join(", ")});`:`(b_quantized_values - ${Vr}(${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:re}u; m++) { + ${Zr.indicesSet("a_indices",Ir-2,Ae?"m":`row * ${re} + m`)}; + ${Zr.indicesSet("a_indices",Ir-1,"word_offset")}; + var input_offset = ${Zr.indicesToOffset("a_indices")}; + var a_data: ${Vr}; + for (var j: u32 = 0; j < ${8/ce}; 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/ce},(rs,si)=>`${ce===1?`a_data[${si}] * b_dequantized_values[${si}]`:`dot(a_data[${si}], b_dequantized_values[${si}])`}`).join(" + ")}; + } + word_offset += ${8/ce}; + } + }`,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}>; + ${or.declareVariables(...jt,ot)} + ${or.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: ${fr.type.indices}; + ${fr.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 = ${Gr.getByOffset("scales_index")}; + // The default zero point is 8 for unsigned 4-bit quantization. + let zero_point = ${ir}(${er?"(zero_point_word) & 0xFu":8}); + ${fr.indicesSet("b_indices","1","block")}; + var word_offset: u32 = block * ${i.blockSize/ce}; + var workgroup_shared_offset: u32 = block * ${x}; + ${fn} + } + 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",_r-1,"col")}; + ${ot.indicesSet("output_indices",_r-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}; + } + } + }`:` + ${or.registerUniforms(Wt).declareVariables(...jt,ot)} + ${or.mainStart()} + ${or.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + var output_values: array<${ot.type.value}, ${re}>; + var output_indices = ${ot.offsetToIndices("global_idx")}; + var col = ${ot.indicesGet("output_indices",_r-1)}; + var row = ${ot.indicesGet("output_indices",_r-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: ${fr.type.indices}; + for (var c: u32 = 0; c < ${Ie}; c++) { + ${fr.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 = ${Gr.getByOffset("scale_index")}; + // The default zero point is 8 for unsigned 4-bit quantization. + let zero_point = ${ir}(${er?"extractBits(zero_point_word, zero_point_offset, 4)":8}); + ${fr.indicesSet("b_indices","1","block")}; + var word_offset: u32 = block_offset; + ${fn} + scale_index++; + ${kn} + block_offset += uniforms.block_size / ${ce}; + } + // Drop the trailing 4 bits if the zero_poit_offset is not a byte boundary to align with the next byte. + ${er?`if (zero_point_offset % 8 > 0) { + ${kn} + }`:""} + } + for (var k: u32 = 0u; k < ${re}u; k++) { + ${ot.indicesSet("output_indices",_r-2,`${re} * 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:yt}),getShaderSource:vr}},kp=(n,i)=>{xn(n.inputs,i);let s=n.getMaxComputeWorkgroupSizes(),u=n.getMaxComputeWorkgroupStoragesize();n.compute(to(n.inputs,i,s,u))},of=n=>qt(n)}),U,G,ie,ke,nt,Ze,bt,At,Rt,dr=p(()=>{Zt(),Jt(),ur(),U=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)}) - ${Ot("uniforms.pads",c,s)}; + if (k < 0) { + break; + } + if (k >= i32(${Ot("uniforms.x_shape",c,i)})) { + break; + } + offset += k * i32(${Ot("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]; + } + `},ie=(n,i,s)=>{let u="";for(let c=i-1;c>=0;--c)u+=` + k = i32(${n.indicesGet("indices",c)}) - ${Ot("uniforms.pads",c,s)}; + if (k < 0) { + k = -k; + } + { + let _2n_1 = 2 * (i32(${Ot("uniforms.x_shape",c,i)}) - 1); + k = k % _2n_1; + if(k >= i32(${Ot("uniforms.x_shape",c,i)})) { + k = _2n_1 - k; + } + } + offset += k * i32(${Ot("uniforms.x_strides",c,i)}); + `;return` + var offset = 0; + var k = 0; + ${u} + value = x[offset]; + `},ke=(n,i,s)=>{let u="";for(let c=i-1;c>=0;--c)u+=` + k = i32(${n.indicesGet("indices",c)}) - ${Ot("uniforms.pads",c,s)}; + if (k < 0) { + k = 0; + } + if (k >= i32(${Ot("uniforms.x_shape",c,i)})) { + k = i32(${Ot("uniforms.x_shape",c,i)}) - 1; + } + offset += k * i32(${Ot("uniforms.x_strides",c,i)}); + `;return` + var offset = 0; + var k = 0; + ${u} + value = x[offset]; + `},nt=(n,i,s)=>{let u="";for(let c=i-1;c>=0;--c)u+=` + k = i32(${n.indicesGet("indices",c)}) - ${Ot("uniforms.pads",c,s)}; + if (k < 0) { + k += i32(${Ot("uniforms.x_shape",c,i)}]); + } + if (k >= i32(${Ot("uniforms.x_shape",c,i)})) { + k -= i32(${Ot("uniforms.x_shape",c,i)}); + } + offset += k * i32(${Ot("uniforms.x_strides",c,i)}); + `;return` + var offset = 0; + var k = 0; + ${u} + value = x[offset]; + `},Ze=(n,i,s)=>{switch(s.mode){case 0:return G(n,i,s.pads.length);case 1:return ie(n,i,s.pads.length);case 2:return ke(n,i,s.pads.length);case 3:return nt(n,i,s.pads.length);default:throw new Error("Invalid mode")}},bt=(n,i)=>{let s=ct.padShape(n[0].dims.slice(),i.pads),u=n[0].dims,c=ct.size(s),h=[{type:12,data:c},{type:6,data:i.pads}];i.mode===0&&h.push({type:n[0].dataType,data:i.value}),h.push(...$t(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=Ze($,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:h}),getShaderSource:x}},At=(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,h=new Int32Array(2*c).fill(0);if(n.length>=4){let x=n[3].getBigInt64Array();for(let k=0;kh[Number(k)]=Number(x));let d=[];return h.forEach(x=>d.push(x)),{mode:i.mode,value:u,pads:d}}else return i},Rt=(n,i)=>{U(n.inputs);let s=At(n.inputs,i);n.compute(bt(n.inputs,s),{inputs:[0]})}}),hr,Ar,nr,ar,xr,Er,Sr,Nr,Vn,zn,Pi,Mn,dn,Tn,qs,Ks,El,ym,mi,Jo=p(()=>{Y(),Zt(),Jt(),ur(),hr=n=>{if(D.webgpu.validateInputContent&&(!n||n.length!==1))throw new Error("Pool ops requires 1 input.")},Ar=(n,i,s)=>{let u=i.format==="NHWC",c=n.dims.slice();u&&c.splice(1,0,c.pop());let h=Object.hasOwnProperty.call(i,"dilations"),d=i.kernelShape.slice(),x=i.strides.slice(),k=h?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);h?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]},nr=(n,i)=>{let s=i.format==="NHWC",u=ct.size(n),c=ct.size(i.kernelShape),h=[{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);h.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],re=i.strides[i.strides.length-2],ce=i.pads[i.pads.length/2-2],we=i.pads[i.pads.length-2];v=!!(ce+we),h.push({type:12,data:oe},{type:12,data:re},{type:12,data:ce},{type:12,data:we}),d.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[h,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);h.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[h,d,!!k,!1,!1]}},ar=(n,i,s,u,c,h,d,x,k,$,H,q)=>{let v=c.format==="NHWC",oe=i.type.value,re=Gt("output",i.type.tensor,u);if(c.kernelShape.length<=2){let ce="",we="",be="",he=s-(v?2:1);if(H?ce=` + for (var i: u32 = 0u; i < uniforms.kw; i++) { + xIndices[${he}] = indices[${he}] * uniforms.sw - uniforms.pwStart + i; + if (xIndices[${he}] < 0 || xIndices[${he}] + >= uniforms.x_shape[${he}]) { + pad++; + continue; + } + let x_val = x[${i.indicesToOffset("xIndices")}]; + ${h} + }`:ce=` + for (var i: u32 = 0u; i < uniforms.kw; i++) { + xIndices[${he}] = indices[${he}] * uniforms.sw - uniforms.pwStart + i; + let x_val = x[${i.indicesToOffset("xIndices")}]; + ${h} + }`,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,re)} + + ${n.mainStart()} + ${n.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + + let indices = ${re.offsetToIndices("global_idx")}; + var xIndices = ${re.offsetToIndices("global_idx")}; + + var value = ${oe}(${x}); + var pad = 0; + ${we} + ${ce} + ${be} + ${d} + + output[global_idx] = value; + }`}else{if(v)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let ce=c.kernelShape.length,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")}]; + ${h} + }`:be=` + } + let x_val = x[${i.indicesToOffset("xIndices")}]; + ${h} + `,` + ${n.registerUniforms(k).declareVariables(i,re)} + + ${n.mainStart()} + ${n.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + let indices = ${re.offsetToIndices("global_idx")}; + var xIndices = ${re.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 < ${ce-1}u; j++) { + offsets[j] = offset / ${Ot("uniforms.kernelStrides","j",ce)}; + offset -= offsets[j] * ${Ot("uniforms.kernelStrides","j",ce)}; + } + offsets[${ce-1}] = offset; + + isPad = false; + for (var j = ${s-ce}u; j < ${s}u; j++) { + xIndices[j] = indices[j] * ${Ot("uniforms.strides",`j - ${s-ce}u`,ce)} + + offsets[j - ${s-ce}u] - ${Ot("uniforms.pads","j - 2u",we)}; + ${be} + } + ${d} + + output[global_idx] = value; + }`}},xr=n=>`${n.format};${n.ceilMode};${n.autoPad};${n.kernelShape.length}`,Er=n=>`${xr(n)};${n.countIncludePad}`,Sr=n=>`${xr(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}),Vn=(n,i,s,u)=>{let[c,h]=Ar(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,re]=nr(h,c);H.push(...$t(i.dims,h));let ce=["rank"];return{name:n,shaderCache:{hint:`${u.cacheKey};${v};${oe};${re}`,inputDependencies:ce},getRunData:()=>({outputs:[{dims:h,dataType:i.dataType}],dispatchGroup:{x:Math.ceil(ct.size(h)/64)},programUniforms:H}),getShaderSource:we=>ar(we,d,i.dims.length,h.length,c,k,$,0,q,v,oe,re)}},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:Er(u)}},Pi=(n,i)=>{hr(n.inputs),n.compute(Vn("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)=>{hr(n.inputs),n.compute(Vn("GlobalAveragePool",n.inputs[0],!0,i))},qs=(n,i,s,u)=>{let[c,h]=Ar(i,u,s),d=` + value = max(x_val, value); + `,x="",k=_t("x",i.dataType,i.dims.length),$=["rank"],[H,q,v,oe,re]=nr(h,c);return H.push(...$t(i.dims,h)),{name:n,shaderCache:{hint:`${u.cacheKey};${v};${oe};${re}`,inputDependencies:$},getRunData:()=>({outputs:[{dims:h,dataType:i.dataType}],dispatchGroup:{x:Math.ceil(ct.size(h)/64)},programUniforms:H}),getShaderSource:ce=>ar(ce,k,i.dims.length,h.length,c,d,x,i.dataType===10?-65504:-1e5,q,v,oe,re)}},Ks=(n,i)=>{hr(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:Sr(c)}},ym=n=>{let i=n.format;return{format:i,...Mn,cacheKey:i}},mi=(n,i)=>{hr(n.inputs),n.compute(qs("GlobalMaxPool",n.inputs[0],!0,i))}}),Ep,Cp,Pp,$p=p(()=>{Y(),Zt(),ur(),Ep=(n,i,s)=>{let u=n===i,c=ni&&s>0;if(u||c||h)throw new Error("Range these inputs' contents are invalid.")},Cp=(n,i,s,u)=>{let c=Math.abs(Math.ceil((i-n)/s)),h=[c],d=c,x=[{type:12,data:d},{type:u,data:n},{type:u,data:s},...$t(h)],k=$=>{let H=Gt("output",u,h.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:h,dataType:u}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:x})}},Pp=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]),D.webgpu.validateInputContent&&Ep(i,s,u),n.compute(Cp(i,s,u,n.inputs[0].dataType),{inputs:[]})}}),b0,x0,M0,T0,k0,S0,E0,C0,P0,$0,A0,vm,I0,F0,z0,O0,D0,L0,R0,nx=p(()=>{Zt(),Jt(),gr(),ur(),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,h)=>u[c]=n[h]),u},M0=(n,i,s,u,c,h)=>{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=>h.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((h,d)=>{u[h]=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(h=>c.push(h)),Math.max(...u)>n.length)throw new Error("axes is out of bound");u.forEach((h,d)=>c[h]=s[d])}else s.forEach(h=>c.push(h));else{if(i.length===0)throw new Error("Resize requires either scales or sizes.");c=n.map((h,d)=>Math.round(h*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(h=>i[h]),Number.MAX_VALUE):Math.min(...i,Number.MAX_VALUE);case"not_smaller":return s.axes.length>0?Math.max(...s.axes.map(h=>i[h]),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(h=>i[h]=u),s.axes.forEach(h=>c[h]=Math.round(n[h]*i[h]))):(i.fill(u,0,i.length),c.forEach((h,d)=>c[d]=Math.round(h*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 = ${Ot("uniforms.scales","i",u)}; + var roi_low = ${Ot("uniforms.roi","i",c)}; + var roi_hi = ${Ot("uniforms.roi",`i + ${i.length}`,c)}; + if (scale == 1.0) { + original_indices[i] = ${n.type.value}(output_index); + } else { + var input_shape_i = ${Ot("uniforms.input_shape","i",i.length)}; + var output_shape_i = ${Ot("uniforms.output_shape","i",s.length)}; + original_indices[i] = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, + input_shape_i, roi_low, roi_hi); + } + } + return original_indices; + }`,$0=(n,i,s,u,c,h,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 = ${Ot("uniforms.scales","i",c)}; + if (scale == 1.0) { + input_index = output_index; + } else { + var roi_low = ${Ot("uniforms.roi","i",h)}; + var roi_hi = ${Ot("uniforms.roi",`i + ${s.length}`,h)}; + var input_shape_i = ${Ot("uniforms.input_shape","i",s.length)}; + var output_shape_i = ${Ot("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 >= ${Ot("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[h,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,h,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[${h}])`:"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,h,d,x,k,$)=>{let H=s.length===2,[q,v]=H?[0,1]:[2,3],oe=n.type.value,re=ce=>{let we=ce===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",ce)}; + var originalIdx: ${oe} = getOriginalCoordinateFromResizedCoordinate(output_index, ${c[ce]}, + ${u[ce]}, ${s[ce]}, ${h[ce]}, ${h[ce]} + ${s.length}); + var fractOriginalIdx: ${oe} = originalIdx - floor(originalIdx); + var coefs = getCubicInterpolationCoefs(fractOriginalIdx); + + if (${x} && (originalIdx < 0 || originalIdx > (${s[ce]} - 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[ce]}) { + ${$?`coefs[i + 1] = 0.0; + continue;`:x?`return ${k};`:`${we} = max(0, min(${we}, ${s[ce]} - 1));`}; + } + var input_indices_copy: ${n.type.indices} = input_indices; + ${n.indicesSet("input_indices_copy",ce,`u32(${we})`)}; + data[i + 1] = ${ce===q?n.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"}; + } + return cubicInterpolation1D(data, coefs); + }`};return` + ${re(q)}; + ${re(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); + } + `},z0=(n,i,s,u,c)=>{let[h,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,$,h,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[${h}])`:"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); + }`},O0=(n,i,s,u,c,h)=>{let d=n.dims,x=S0(h,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]),re=i.coordinateTransformMode==="tf_crop_and_resize",ce=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,re)}; + `;case"linear":return` + ${P0(H,d,k,$.length,x.length)}; + ${(()=>{if(d.length===2||d.length===4)return`${I0(q,H,d,re,ce)}`;if(d.length===3||d.length===5)return`${z0(q,H,d,re,ce)}`;throw Error("Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.")})()}; + `;case"cubic":return` + ${(()=>{if(d.length===2||d.length===4)return`${F0(q,H,d,k,$,x,i.cubicCoeffA,re,i.extrapolationValue,i.excludeOutside)}`;throw Error("Cubic mode only supports input dims 2 and 4 are supported in linear mode.")})()}; + `;default:throw Error("Invalid resize mode")}})()}; + `} + ${he.registerUniform("output_size","u32").registerUniform("scales","f32",$.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},...$t(d,k)]})}},D0=n=>{let i=n.customDataBuffer;return new Uint32Array(i,i.byteOffset,1)[0]},L0=(n,i)=>{let s=[],u=[],c=[],h=D0(n);if(i.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");M0(n.inputs,i,h,s,u,c),n.compute(O0(n.inputs[0],i,h,s,u,c),{inputs:[0]})},R0=n=>{let i=n.antialias,s=n.axes,u=n.coordinateTransformMode,c=n.cubicCoeffA,h=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:h,extrapolationValue:d,keepAspectRatioPolicy:x,mode:k,nearestMode:$})}}),B0,N0,j0,ix=p(()=>{Zt(),Jt(),gr(),ur(),B0=(n,i)=>{let[s,u,c,h]=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(h.dims.length!==2)throw new Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${h.dims.length}`);if(!ct.areEqual(c.dims,h.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:h}=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),re=[{type:1,data:h},{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]}):[],...$t(n[0].dims,n[1].dims,n[2].dims,n[3].dims,n[0].dims)],ce=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(jn)} + 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:ce,getRunData:()=>({outputs:[{dims:n[0].dims,dataType:n[0].dataType}],dispatchGroup:{x:Math.ceil(ct.size(v)/jn)},programUniforms:re})}},j0=(n,i)=>{B0(n.inputs,i),n.compute(N0(n.inputs,i))}}),U0,V0,W0,ox=p(()=>{Zt(),Jt(),ur(),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],h=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]!==h)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,h=n[0].dims,d=ct.size(h),x=h,k=d,$=h.slice(-1)[0],H=u?h.slice(0,-1).concat(1):[],q=!c&&n.length>3,v=n.length>4,oe=u&&s>1,re=u&&s>2,ce=s>3,we=64,be=wr($),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)),re&&ut.push(Gt("inv_std_output",1,H)),ce&&ut.push(Gt("input_skip_bias_sum",n[0].dataType,x,be));let yt=Tr(n[0].dataType),Dt=Tr(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]":yt+"(0.0)"}; + let input_value = x[offset + i]; + let value = input_value + skip_value + bias_value; + ${ce?"input_skip_bias_sum[offset + i] = value;":""} + output[offset + i] = value; + let f32_value = ${Xr(yt,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 = ${Un("sum",be)} / f32(uniforms.hidden_size); + let inv_std_dev = inverseSqrt(${Un("square_sum",be)} / f32(uniforms.hidden_size) ${c?"":"- mean * mean"} + uniforms.epsilon); + ${oe?"mean_output[global_idx] = mean;":""} + ${re?"inv_std_output[global_idx] = inv_std_dev;":""} + + for (var i: u32 = 0; i < stride; i++) { + output[offset + i] = (output[offset + i] ${c?"":`- ${yt}(mean)`}) * + ${yt}(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:h,dataType:n[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${be};${oe};${re};${ce}`,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,sf,H0,bm,q0,K0,X0,Q0,sx=p(()=>{Zt(),Jt(),gr(),ur(),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`)})},sf=(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=sf(n,1),u=sf(n,2),c=sf(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 h=n;return n<0&&(h+=s[u[i]]),c[i]<0?Math.max(0,Math.min(h,s[u[i]]-1)):Math.max(0,Math.min(h,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 = ${Ot("uniforms.input_shape","i",s.length)}; + let steps_i = ${Ot("uniforms.steps","i",s.length)}; + let signs_i = ${Ot("uniforms.signs","i",s.length)}; + let starts_i = ${Ot("uniforms.starts","i",s.length)}; + var output_index = ${i.indicesGet("output_indices","i")}; + var input_index = output_index * steps_i + starts_i + carry; + carry = input_index / input_shape_i; + input_index = input_index % input_shape_i; + if (signs_i < 0) { + input_index = input_shape_i - input_index - 1u + starts_i; + } + ${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()],h=sf(n,4);h.forEach(be=>be!==0||(()=>{throw new Error("step cannot be 0")})),h.length===0&&(h=Array(c.length).fill(1));let d=i.starts.map((be,he)=>bm(be,he,s,c,h)),x=i.ends.map((be,he)=>bm(be,he,s,c,h));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));h.forEach((be,he,De)=>{if(be<0){let Ae=(x[he]-d[he])/be,Ie=d[he],gt=Ie+Ae*h[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])/h[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($),re=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:d.length},{name:"signs",type:"i32",length:k.length},{name:"steps",type:"u32",length:h.length}],ce=[{type:12,data:oe},{type:12,data:d},{type:6,data:k},{type:12,data:h},...$t(n[0].dims,$)],we=be=>` + ${be.registerUniforms(re).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}_${h.length}`,inputDependencies:["rank"]},getShaderSource:we,getRunData:()=>({outputs:[H],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:ce})}},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=p(()=>{Zt(),Jt(),gr(),ur(),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,h=i.axis;if(h<0&&(h=s.length+h),hbe===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,re=Tr(n.dataType)==="f32"?`var threadMax = ${oe}(-3.402823e+38f);`:`var threadMax = ${oe}(-65504.0h);`,ce=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 + ${re} + for (var col = lindex; col < cols; col += wg) { + let value = getValue(row, col, row_stride); + threadMax = max(threadMax, value); + } + if (lindex < cols) { + threadShared[lindex] = threadMax; + } + workgroupBarrier(); + + var reduceSize = min(cols, wg); + for (var currSize = reduceSize >> 1; currSize > 0; currSize = reduceSize >> 1) { + reduceSize = currSize + (reduceSize & 1); + if (lindex < currSize) { + threadShared[lindex] = max(threadShared[lindex], threadShared[lindex + reduceSize]); + } + workgroupBarrier(); + } + if (lindex == 0) { + rowMaxShared = ${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}(${Un("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:ce}},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=p(()=>{Zt(),Jt(),gr(),ur(),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 < ${Ot("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,h=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 re=0;re` + ${re.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",k.length).declareVariables(x,...d)} + ${nw(k.length)} + ${iw(d)} + + ${re.mainStart()} + ${re.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")} + + var indices = ${x.offsetToIndices("global_idx")}; + var index = ${x.indicesGet("indices",h)}; + let output_number = calculateOutputIndex(index); + if (output_number != 0) { + index -= ${Ot("uniforms.size_in_split_axis","output_number - 1u",k.length)}; + ${x.indicesSet("indices",h,"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=p(()=>{Zt(),Jt(),ur(),lw=(n,i,s,u,c)=>{let h=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)$=h.setByOffset("global_idx",H(d.getByOffset("global_idx"),x.getByOffset("global_idx"),k.getByOffset("global_idx")));else{let q=(v,oe,re="")=>{let ce=`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} = ${h.offsetToIndices(`global_idx * 4u + ${oe}u`)}; + let offset_a${oe} = ${d.broadcastedIndicesToOffset(`output_indices${oe}`,h)}; + let offset_b${oe} = ${x.broadcastedIndicesToOffset(`output_indices${oe}`,h)}; + let offset_c${oe} = ${k.broadcastedIndicesToOffset(`output_indices${oe}`,h)}; + 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}] = ${re}(${H(ce,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,h)} + ${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,h=!(ct.areEqual(i,s)&&ct.areEqual(s,u)),d=i,x=ct.size(i);if(h){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,h,c),getRunData:()=>({outputs:[{dims:d,dataType:c}],dispatchGroup:{x:Math.ceil(x/64/4)},programUniforms:[{type:12,data:k},...$t(u,i,s,d)]})}},cw=n=>{n.compute(uw(n.inputs))}}),dw,cx=p(()=>{ip(),Os(),tc(),op(),zc(),sp(),ap(),cd(),gm(),pp(),hp(),wp(),_m(),vp(),bp(),xp(),Bd(),Tp(),wm(),bn(),sl(),Sp(),Wd(),dr(),Jo(),$p(),$a(),nx(),ix(),ox(),sx(),ax(),lx(),Kd(),yo(),Ha(),ux(),dw=new Map([["Abs",[oc]],["Acos",[sc]],["Acosh",[Fa]],["Add",[Lc]],["ArgMax",[Gu,zs]],["ArgMin",[Wu,zs]],["Asin",[ac]],["Asinh",[lc]],["Atan",[za]],["Atanh",[uc]],["Attention",[Qu]],["AveragePool",[Pi,zn]],["BatchNormalization",[ec]],["BiasAdd",[Ia]],["BiasSplitGelu",[Fc]],["Cast",[Ds,cc]],["Ceil",[pc]],["Clip",[fc]],["Concat",[Ui,Kc]],["Conv",[Ko,ll]],["ConvTranspose",[fp,md]],["Cos",[Oa]],["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",[Od,zd]],["Gelu",[wc]],["Gemm",[Mp,Rd]],["GlobalAveragePool",[Tn,dn]],["GlobalMaxPool",[mi,ym]],["Greater",[Uc]],["GreaterOrEqual",[Wc]],["GroupQueryAttention",[Zd,Qd]],["HardSigmoid",[Ba,Mc]],["InstanceNormalization",[rf]],["LayerNormalization",[hn]],["LeakyRelu",[yc,bo]],["Less",[Vc]],["LessOrEqual",[Xa]],["Log",[Ga]],["MatMul",[ad]],["MatMulNBits",[kp,of]],["MaxPool",[Ks,El]],["Mul",[Bc]],["MultiHeadAttention",[Vd,jd]],["Neg",[vc]],["Not",[La]],["Pad",[Rt]],["Pow",[Nc]],["QuickGelu",[Ac,bo]],["Range",[Pp]],["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",[pu,wa]],["Where",[cw]]])}),fw,dx=p(()=>{Y(),Nn(),ur(),fw=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 h=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=h.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),h=n.getShaderSource(c),d=`${u.join(` +`)} +${c.additionalImplementations} +${h}`,x=s.createShaderModule({code:d,label:n.name});Ur("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 h=i*s*u,d=Math.ceil(Math.sqrt(h));if(d>c){if(d=Math.ceil(Math.cbrt(h)),d>c)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[d,d,d]}else return[d,d,1]}}}),pw,hw,mw,gw,fx=p(()=>{Y(),Zt(),Nn(),W(),$r(),cx(),dx(),pw=(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,h;let u=n.name;return(c=n.shaderCache)!=null&&c.hint&&(u+="["+n.shaderCache.hint+"]"),u+=":"+s+`:${pw(i,((h=n.shaderCache)==null?void 0:h.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 fw(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 ce=Number(oe-this.queryTimeBase),we=Number(re-this.queryTimeBase);if(!Number.isSafeInteger(ce)||!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:pi(be.dataType)})),outputsMetadata:v.map(be=>({dims:be.dims,dataType:pi(be.dataType)})),kernelId:d,kernelType:k,kernelName:$,programName:H,startTime:ce,endTime:we});else{let be="";q.forEach((De,Ae)=>{be+=`input[${Ae}]: [${De.dims}] | ${pi(De.dataType)}, `});let he="";v.forEach((De,Ae)=>{he+=`output[${Ae}]: [${De.dims}] | ${pi(De.dataType)}, `}),console.log(`[profiling] kernel "${d}|${k}|${$}|${H}" ${be}${he}execution time: ${we-ce} ns`)}je("GPU",`${H}::${oe}::${re}`)}n.unmap(),this.pendingQueries.delete(n)}),A()}run(n,i,s,u,c,h){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=h)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 yt=typeof ut.data=="number"?[ut.data]:ut.data;if(yt.length===0)return;let Dt=ut.type===10?2:4,Bt,mr;ut.type===10?(mr=yt.length>4?16:yt.length>2?8:yt.length*Dt,Bt=yt.length>4?16:Dt*yt.length):(mr=yt.length<=2?yt.length*Dt:16,Bt=16),he=Math.ceil(he/mr)*mr,De.push(he);let vr=ut.type===10?8:4;he+=yt.length>4?Math.ceil(yt.length/vr)*Bt:yt.length*Dt});let Ae=16;he=Math.ceil(he/Ae)*Ae;let Ie=new ArrayBuffer(he);$.forEach((ut,yt)=>{let Dt=De[yt],Bt=typeof ut.data=="number"?[ut.data]:ut.data;if(ut.type===6)new Int32Array(Ie,Dt,Bt.length).set(Bt);else if(ut.type===12)new Uint32Array(Ie,Dt,Bt.length).set(Bt);else if(ut.type===10)new Uint16Array(Ie,Dt,Bt.length).set(Bt);else if(ut.type===1)new Float32Array(Ie,Dt,Bt.length).set(Bt);else throw new Error(`Unsupported uniform type: ${pi(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 re=this.programManager.normalizeDispatchGroupSize(k),ce=re[1]===1&&re[2]===1,we=hw(n,i,ce),be=this.programManager.getArtifact(we);if(be||(be=this.programManager.build(n,re),this.programManager.setArtifact(we,be),Ur("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(Ur("info",()=>`[ProgramManager] run "${n.name}" (key=${we}) with ${re[0]}x${re[1]}x${re[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let he={kernelId:this.currentKernelId,programName:be.programInfo.name,inputTensorViews:i,outputTensorViews:q};this.pendingKernels.push(he),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(he)}return this.programManager.run(be,d,v,re,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 h={kernelType:n,kernelName:u,kernelEntry:c[0],attributes:[c[1],s]};this.kernels.set(i,h)}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,h=u.kernelName,d=u.kernelEntry,x=u.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${c}] ${h}" is not allowed to be called recursively`);this.currentKernelId=n,x[0]&&(x[1]=x[0](x[1]),x[0]=void 0),Ur("info",()=>`[WebGPU] Start to run kernel "[${c}] ${h}"...`);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}] ${h}" failed. ${$}`)),1}finally{k&&s.push(this.device.popErrorScope().then($=>$?`GPU validation error for kernel "[${c}] ${h}": ${$.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 h=c.get(i),d=this.gpuDataManager.registerExternalBuffer(s,u,h==null?void 0:h[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(){Ur("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(){Ur("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){Ur("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 Ap,ww,yw,px=p(()=>{Zt(),fx(),Nn(),Jt(),Ap=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 h=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 Ap(this.module,k,this.output(x,$),$),h=(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 Ap(this.module,x,q,k)};return this.backend.run(n,s,u,c,h,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 h=0;h{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 h=new gw;await h.initialize(s,u),c("webgpu",[h,d=>h.alloc(d),d=>h.free(d),(d,x,k,$=!1)=>{if($)Ur("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${d}, dst=${x}, size=${k}`),h.memcpy(d,x);else{Ur("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${d}, gpuDataId=${x}, size=${k}`);let H=i.HEAPU8.subarray(d>>>0,(d>>>0)+k);h.upload(x,H)}},async(d,x,k)=>{Ur("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${d}, dataOffset=${x}, size=${k}`),await h.download(d,()=>i.HEAPU8.subarray(x>>>0,(x>>>0)+k))},(d,x,k)=>h.createKernel(d,x,k,i.UTF8ToString(i._JsepGetNodeName(x))),d=>h.releaseKernel(d),(d,x,k,$)=>{Ur("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${k}, kernel=${d}, contextDataOffset=${x}`);let H=new ww(i,h,x);return h.computeKernel(d,H,$)},()=>h.captureBegin(),()=>h.captureEnd(),()=>h.replay()])}else c("webnn")}}),vw,xm,Mm,es,bw,Ip,Tm,km,Sm,Em,Cm,Pm,xw=p(()=>{Cs(),Ps(),Zt(),wn(),Ni(),jo(),vw=(n,i)=>{Wr()._OrtInit(n,i)!==0&&Or("Can't initialize onnxruntime.")},xm=async n=>{vw(n.wasm.numThreads,Ji(n.logLevel))},Mm=async(n,i)=>{{let s=(px(),w(_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 h=n.webgpu.forceFallbackAdapter;if(h!==void 0&&typeof h!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${h}"`);if(u=await navigator.gpu.requestAdapter({powerPreference:c,forceFallbackAdapter:h}),!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",Wr(),n,u)}if(i==="webnn"){if(typeof navigator>"u"||!navigator.ml)throw new Error("WebNN is not supported in current environment");await s("webnn",Wr(),n)}}},es=new Map,bw=n=>{let i=Wr(),s=i.stackSave();try{let u=i.stackAlloc(8);return i._OrtGetInputOutputCount(n,u,u+4)!==0&&Or("Can't get session input/output count."),[i.HEAP32[u/4],i.HEAP32[u/4+1]]}finally{i.stackRestore(s)}},Ip=n=>{let i=Wr(),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=Wr();Array.isArray(n)?[s,u]=n:n.buffer===c.HEAPU8.buffer?[s,u]=[n.byteOffset,n.byteLength]:[s,u]=Ip(n);let h=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,yt=Ie==null?void 0:Ie.deviceType,Dt=Ie==null?void 0:Ie.numThreads,Bt=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:yt,numThreads:Dt,powerPreference:Bt})}else c.currentContext=await navigator.ml.createContext();break}h=await c._OrtCreateSession(s,u,d),h===0&&Or("Can't create a session."),c.currentContext&&(c.currentContext=void 0);let[oe,re]=bw(h),ce=!!(i!=null&&i.enableGraphCapture),we=[],be=[],he=[];for(let Ae=0;AeAe==="gpu-buffer")&&(x=c._OrtCreateBinding(h),x===0&&Or("Can't create IO binding."),De={handle:x,outputPreferredLocations:he,outputPreferredLocationsEncoded:he.map(Ae=>mo(Ae))}),es.set(h,[h,$,H,De,ce,!1]),[h,we,be]}catch(oe){throw $.forEach(re=>c._OrtFree(re)),H.forEach(re=>c._OrtFree(re)),x!==0&&c._OrtReleaseBinding(x),h!==0&&c._OrtReleaseSession(h),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=Wr(),s=es.get(n);if(!s)throw new Error(`cannot release session. invalid session id: ${n}`);let[u,c,h,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($)),h.forEach($=>i._OrtFree($)),i._OrtReleaseSession(u),es.delete(n)},Sm=(n,i,s,u,c,h=!1)=>{if(!n){i.push(0);return}let d=Wr(),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(h&&$!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${c} when enableGraphCapture is true.`);if($==="gpu-buffer"){let re=n[2].gpuBuffer,ce=ki(po(x));q=k.reduce((be,he)=>be*he,1)*ce;let we=d.jsepRegisterBuffer;if(!we)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');H=we(u,c,re,q)}else{let re=n[2];if(Array.isArray(re)){q=4*re.length,H=d._malloc(q),s.push(H);let ce=H/4;for(let we=0;wed.HEAP32[re++]=we);let ce=d._OrtCreateTensor(po(x),H,q,oe,k.length,mo($));ce===0&&Or(`Can't create tensor for input/output. session=${u}, index=${c}.`),i.push(ce)}finally{d.stackRestore(v)}},Em=async(n,i,s,u,c,h)=>{var Bt,mr;let d=Wr(),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],re=i.length,ce=u.length,we=0,be=[],he=[],De=[],Ae=[],Ie=d.stackSave(),gt=d.stackAlloc(re*4),ut=d.stackAlloc(re*4),yt=d.stackAlloc(ce*4),Dt=d.stackAlloc(ce*4);try{[we,be]=Ti(h);for(let jt=0;jtDn*Jn,1);ir=pi(kn);let uf=q==null?void 0:q.outputPreferredLocations[u[jt]];if(ir==="string"){if(uf==="gpu-buffer")throw new Error("String tensor is not supported on GPU.");let Dn=[],Jn=Vr/4;for(let $i=0;$i0){let Dn=d.jsepGetBuffer;if(!Dn)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let Jn=Dn(Vr),$i=ki(kn);if($i===void 0||!ho(ir))throw new Error(`Unsupported data type: ${ir}`);Wt=!0,Gr.push([ir,gi,{gpuBuffer:Jn,download:d.jsepCreateDownloader(Jn,On*$i,ir),dispose:()=>{d._OrtReleaseTensor(er)}},"gpu-buffer"])}else{let Dn=Si(ir),Jn=new Dn(On);new Uint8Array(Jn.buffer,Jn.byteOffset,Jn.byteLength).set(d.HEAPU8.subarray(Vr,Vr+Jn.byteLength)),Gr.push([ir,gi,Jn,"cpu"])}}finally{d.stackRestore(_r),ir==="string"&&Vr&&d._free(Vr),Wt||d._OrtReleaseTensor(er)}}return q&&!v&&(d._OrtClearBoundOutputs(q.handle),es.set(n,[k,$,H,q,v,!1])),Gr}finally{d.stackRestore(Ie),he.forEach(vr=>d._OrtReleaseTensor(vr)),De.forEach(vr=>d._OrtReleaseTensor(vr)),Ae.forEach(vr=>d._free(vr)),we!==0&&d._OrtReleaseRunOptions(we),be.forEach(vr=>d._free(vr))}},Cm=n=>{let i=Wr(),s=es.get(n);if(!s)throw new Error("invalid session id");let u=s[0],c=i._OrtEndProfiling(u);c===0&&Or("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,af,lf,Fp,$m,zp,Xs,Qs,Mw,Tw,kw,Sw,Ew,Cw,Pw,$w,Aw=p(()=>{Y(),xw(),wn(),Yr(),ts=()=>!!D.wasm.proxy&&typeof document<"u",Cl=!1,af=!1,lf=!1,zp=new Map,Xs=(n,i)=>{let s=zp.get(n);s?s.push(i):zp.set(n,[i])},Qs=()=>{if(Cl||!af||lf||!oi)throw new Error("worker not ready")},Mw=n=>{switch(n.data.type){case"init-wasm":Cl=!1,n.data.err?(lf=!0,$m[1](n.data.err)):(af=!0,$m[0]()),Fp&&(URL.revokeObjectURL(Fp),Fp=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let i=zp.get(n.data.type);n.data.err?i.shift()[1](n.data.err):i.shift()[0](n.data.out);break}}},Tw=async()=>{if(!af){if(Cl)throw new Error("multiple calls to 'initWasm()' detected.");if(lf)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=h=>i(h),oi.onmessage=Mw,$m=[n,i];let c={type:"init-wasm",in:D};oi.postMessage(c),Fp=s}catch(c){i(c)}},i)});try{await Mi(D.wasm),await xm(D),af=!0}catch(n){throw lf=!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:D}};oi.postMessage(u)});await Mm(D,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])})):Ip(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}}},h=[];n instanceof Uint8Array&&h.push(n.buffer),oi.postMessage(c,h)})}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,h)=>{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:h}};oi.postMessage($,Pm(k))})}else return Em(n,i,s,u,c,h)},$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=p(()=>{Y(),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],re=this.inputNames.indexOf(v);if(re===-1)throw new Error(`invalid input '${v}'`);u.push(oe),c.push(re)});let h=[],d=[];Object.entries(i).forEach(q=>{let v=q[0],oe=q[1],re=this.outputNames.indexOf(v);if(re===-1)throw new Error(`invalid output '${v}'`);h.push(oe),d.push(re)});let x=u.map((q,v)=>Am(q,()=>`input "${this.inputNames[c[v]]}"`)),k=h.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]]]=h[q]??Iw($[q]);return A(),H}startProfiling(){}endProfiling(){$w(this.sessionId)}}}),zw,Ow,mx=p(()=>{Y(),Aw(),hx(),Yr(),zw=()=>{if((typeof D.wasm.initTimeout!="number"||D.wasm.initTimeout<0)&&(D.wasm.initTimeout=0),D.wasm.simd===!1&&console.warn('Deprecated property "env.wasm.simd" is set to false. non-SIMD build is no longer provided, and this setting will be ignored.'),typeof D.wasm.proxy!="boolean"&&(D.wasm.proxy=!1),typeof D.wasm.trace!="boolean"&&(D.wasm.trace=!1),typeof D.wasm.numThreads!="number"||!Number.isInteger(D.wasm.numThreads)||D.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)D.wasm.numThreads=1;else{let n=typeof navigator>"u"?_("node:os").cpus().length:navigator.hardwareConcurrency;D.wasm.numThreads=Math.min(4,Math.ceil((n||1)/2))}},Ow=class{async init(n){zw(),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=p(()=>{mx(),Lw=new Ow});Y(),Y(),Y();var _x="1.19.0-dev.20240804-ee2fe87e2d",wx=Ve;{let n=(gx(),w(Dw)).wasmBackend;z("webgpu",n,5),z("webnn",n,5),z("cpu",n,10),z("wasm",n,10)}Object.defineProperty(D.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:()=>z,deviceToExecutionProviders:()=>C,isONNXProxy:()=>y,isONNXTensor:()=>S});var a=r("./src/env.js"),l=r("?2ce3"),f=r("./node_modules/onnxruntime-web/dist/ort.webgpu.bundle.min.mjs"),_=r("./node_modules/onnxruntime-common/dist/esm/index.js");const p=[];let g,M;if(a.apis.IS_NODE_ENV){switch(M=l??(o||(o=r.t(l,2))),process.platform){case"win32":p.push("dml");break;case"linux":process.arch==="x64"&&p.push("cuda");break}p.push("cpu"),g=["cpu"]}else M=f,a.apis.IS_WEBGPU_AVAILABLE&&p.push("webgpu"),p.push("wasm"),g=["wasm"];const w=M.InferenceSession;function C(b){let I=g;if(b){if(!p.includes(b))throw new Error(`Unsupported device: "${b}". Should be one of: ${p.join(", ")}.`);I=[b]}return I}let T=null;async function z(b,I){T&&await T;const V=w.create(b,I);return T??(T=V),await V}function S(b){return b instanceof M.Tensor}const E=M==null?void 0:M.env;E!=null&&E.wasm&&(E.wasm.wasmPaths=`https://cdn.jsdelivr.net/npm/@huggingface/transformers@${a.env.version}/dist/`,E.wasm.proxy=!a.apis.IS_WEBWORKER_ENV,(typeof crossOriginIsolated>"u"||!crossOriginIsolated)&&(E.wasm.numThreads=1),typeof navigator<"u"&&/iP(hone|od|ad).+16_4.+AppleWebKit/.test(navigator.userAgent)&&(E.wasm.simd=!1)),E!=null&&E.webgpu&&(E.webgpu.powerPreference="high-performance");function y(){var b;return(b=E==null?void 0:E.wasm)==null?void 0:b.proxy}a.env.backends.onnx=E},"./src/configs.js":(e,t,r)=>{r.r(t),r.d(t,{AutoConfig:()=>g,PretrainedConfig:()=>p,getKeyValueShapes:()=>_});var o=r("./src/utils/core.js"),a=r("./src/utils/hub.js");async function l(M,w){return await(0,a.getModelJSON)(M,"config.json",!0,w)}function f(M){const w={};let C={};switch(M.model_type){case"llava":case"paligemma":case"florence2":C=f(M.text_config);break;case"moondream1":C=f(M.phi_config);break;case"musicgen":C=f(M.decoder);break;case"gpt2":case"gptj":case"codegen":case"gpt_bigcode":w.num_heads="n_head",w.num_layers="n_layer",w.hidden_size="n_embd";break;case"gpt_neox":case"stablelm":case"opt":case"phi":case"phi3":case"falcon":w.num_heads="num_attention_heads",w.num_layers="num_hidden_layers",w.hidden_size="hidden_size";break;case"llama":case"cohere":case"mistral":case"starcoder2":case"qwen2":w.num_heads="num_key_value_heads",w.num_layers="num_hidden_layers",w.hidden_size="hidden_size",w.num_attention_heads="num_attention_heads";break;case"gemma":case"gemma2":w.num_heads="num_key_value_heads",w.num_layers="num_hidden_layers",w.dim_kv="head_dim";break;case"openelm":w.num_heads="num_kv_heads",w.num_layers="num_transformer_layers",w.dim_kv="head_dim";break;case"gpt_neo":case"donut-swin":w.num_heads="num_heads",w.num_layers="num_layers",w.hidden_size="hidden_size";break;case"bloom":w.num_heads="n_head",w.num_layers="n_layer",w.hidden_size="hidden_size";break;case"mpt":w.num_heads="n_heads",w.num_layers="n_layers",w.hidden_size="d_model";break;case"t5":case"mt5":case"longt5":w.num_decoder_layers="num_decoder_layers",w.num_decoder_heads="num_heads",w.decoder_dim_kv="d_kv",w.num_encoder_layers="num_layers",w.num_encoder_heads="num_heads",w.encoder_dim_kv="d_kv";break;case"bart":case"mbart":case"marian":case"whisper":case"m2m_100":case"blenderbot":case"blenderbot-small":case"florence2_language":w.num_decoder_layers="decoder_layers",w.num_decoder_heads="decoder_attention_heads",w.decoder_hidden_size="d_model",w.num_encoder_layers="encoder_layers",w.num_encoder_heads="encoder_attention_heads",w.encoder_hidden_size="d_model";break;case"speecht5":w.num_decoder_layers="decoder_layers",w.num_decoder_heads="decoder_attention_heads",w.decoder_hidden_size="hidden_size",w.num_encoder_layers="encoder_layers",w.num_encoder_heads="encoder_attention_heads",w.encoder_hidden_size="hidden_size";break;case"trocr":w.num_encoder_layers=w.num_decoder_layers="decoder_layers",w.num_encoder_heads=w.num_decoder_heads="decoder_attention_heads",w.encoder_hidden_size=w.decoder_hidden_size="d_model";break;case"musicgen_decoder":w.num_encoder_layers=w.num_decoder_layers="num_hidden_layers",w.num_encoder_heads=w.num_decoder_heads="num_attention_heads",w.encoder_hidden_size=w.decoder_hidden_size="hidden_size";break;case"vision-encoder-decoder":const z=f(M.decoder),S="num_decoder_layers"in z,E=(0,o.pick)(M,["model_type","is_encoder_decoder"]);return S?(E.num_decoder_layers=z.num_decoder_layers,E.num_decoder_heads=z.num_decoder_heads,E.decoder_hidden_size=z.decoder_hidden_size,E.num_encoder_layers=z.num_encoder_layers,E.num_encoder_heads=z.num_encoder_heads,E.encoder_hidden_size=z.encoder_hidden_size):(E.num_layers=z.num_layers,E.num_heads=z.num_heads,E.hidden_size=z.hidden_size),E}const T={...C,...(0,o.pick)(M,["model_type","multi_query","is_encoder_decoder"])};for(const z in w)T[z]=M[w[z]];return T}function _(M,{prefix:w="past_key_values"}={}){const C={},T=M.normalized_config,z=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,E=T.decoder_dim_kv??T.decoder_hidden_size/T.num_decoder_heads,y=[z,T.num_encoder_heads,0,S],b=[z,T.num_decoder_heads,0,E];for(let I=0;I{var j;r.r(t),r.d(t,{apis:()=>S,env:()=>O});var o=r("?569f"),a=r("?3f59"),l=r("?154a");const f="3.0.0-alpha.6",_=typeof self<"u",p=_&&self.constructor.name==="DedicatedWorkerGlobalScope",g=_&&"caches"in self,M=typeof navigator<"u"&&"gpu"in navigator,w=typeof process<"u",C=w&&((j=process==null?void 0:process.release)==null?void 0:j.name)==="node",T=!N(o),z=!N(a),S=Object.freeze({IS_BROWSER_ENV:_,IS_WEBWORKER_ENV:p,IS_WEB_CACHE_AVAILABLE:g,IS_WEBGPU_AVAILABLE:M,IS_PROCESS_AVAILABLE:w,IS_NODE_ENV:C,IS_FS_AVAILABLE:T,IS_PATH_AVAILABLE:z}),E=T&&z,y=E?a.dirname(a.dirname(l.fileURLToPath(import.meta.url))):"./",b=E?a.join(y,"/.cache/"):null,I="/models/",V=E?a.join(y,I):I,O={version:f,backends:{onnx:{},tfjs:{}},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!_,localModelPath:V,useFS:T,useBrowserCache:g,useFSCache:T,cacheDir:b,useCustomCache:!1,customCache:null};function N(D){return Object.keys(D).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(f){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)(f,Object.getOwnPropertyNames(this)))}}},"./src/generation/logits_process.js":(e,t,r)=>{r.r(t),r.d(t,{ClassifierFreeGuidanceLogitsProcessor:()=>y,ForcedBOSTokenLogitsProcessor:()=>p,ForcedEOSTokenLogitsProcessor:()=>g,LogitsProcessor:()=>l,LogitsProcessorList:()=>_,LogitsWarper:()=>f,MinLengthLogitsProcessor:()=>z,MinNewTokensLengthLogitsProcessor:()=>S,NoBadWordsLogitsProcessor:()=>E,NoRepeatNGramLogitsProcessor:()=>C,RepetitionPenaltyLogitsProcessor:()=>T,SuppressTokensAtBeginLogitsProcessor:()=>M,TemperatureLogitsWarper:()=>b,TopKLogitsWarper:()=>V,TopPLogitsWarper:()=>I,WhisperTimeStampLogitsProcessor:()=>w});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(N,j){throw Error("`_call` should be implemented in a subclass")}}class f extends o.Callable{_call(N,j){throw Error("`_call` should be implemented in a subclass")}}class _ extends o.Callable{constructor(){super(),this.processors=[]}push(N){this.processors.push(N)}extend(N){this.processors.push(...N)}_call(N,j){let D=j;for(const ee of this.processors)D=ee(N,D);return D}[Symbol.iterator](){return this.processors.values()}}class p extends l{constructor(N){super(),this.bos_token_id=N}_call(N,j){for(let D=0;D=1&&Ce[Ce.length-1]>=this.timestamp_begin,_e=Ce.length<2||Ce[Ce.length-2]>=this.timestamp_begin;if(te&&(_e?de.subarray(this.timestamp_begin).fill(-1/0):de.subarray(0,this.eos_token_id).fill(-1/0)),N[D].length===this.begin_index&&this.max_initial_timestamp_index!==null){const ge=this.timestamp_begin+this.max_initial_timestamp_index;de.subarray(ge+1).fill(-1/0)}const R=(0,a.log_softmax)(de),xe=Math.log(R.subarray(this.timestamp_begin).map(Math.exp).reduce((ge,X)=>ge+X)),Xe=(0,a.max)(R.subarray(0,this.timestamp_begin))[0];xe>Xe&&de.subarray(0,this.timestamp_begin).fill(-1/0)}return j}}class C extends l{constructor(N){super(),this.no_repeat_ngram_size=N}getNgrams(N){const j=N.length,D=[];for(let de=0;de1 to use the classifier free guidance processor, got guidance scale ${N}.`);this.guidance_scale=N}_call(N,j){if(j.dims[0]!==2*N.length)throw new Error(`Logits should have twice the batch size of the input ids, the first half of batches corresponding to the conditional inputs, and the second half of batches corresponding to the unconditional inputs. Got batch size ${j.dims[0]} for the logits and ${N.length} for the input ids.`);const D=N.length,ee=j.slice([0,D],null),de=j.slice([D,j.dims[0]],null);for(let Ce=0;Ce1)throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${N}`);if(!Number.isInteger(D)||D<1)throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${D}`);this.top_p=N,this.filter_value=j,this.min_tokens_to_keep=D}}class V extends f{constructor(N,{filter_value:j=-1/0,min_tokens_to_keep:D=1}={}){if(super(),!Number.isInteger(N)||N<0)throw new Error(`\`top_k\` must be a positive integer, but is ${N}`);this.top_k=Math.max(N,D),this.filter_value=j}}},"./src/generation/logits_sampler.js":(e,t,r)=>{r.r(t),r.d(t,{LogitsSampler:()=>f});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 f extends o.Callable{constructor(w){super(),this.generation_config=w}async _call(w){return this.sample(w)}async sample(w){throw Error("sample should be implemented in subclasses.")}getLogits(w,C){let T=w.dims.at(-1),z=w.data;if(C===-1)z=z.slice(-T);else{let S=C*T;z=z.slice(S,S+T)}return z}randomSelect(w){let C=0;for(let z=0;z1)return new g(w);if(w.num_return_sequences>1)throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${w.num_return_sequences}.`);return new _(w)}}class _ extends f{async sample(w){const C=(0,l.max)(w.data)[1];return[[BigInt(C),0]]}}class p extends f{async sample(w){let C=w.dims.at(-1);this.generation_config.top_k>0&&(C=Math.min(this.generation_config.top_k,C));const[T,z]=await(0,a.topk)(w,C),S=(0,l.softmax)(T.data);return Array.from({length:this.generation_config.num_beams},()=>{const E=this.randomSelect(S);return[z.data[E],Math.log(S[E])]})}}class g extends f{async sample(w){let C=w.dims.at(-1);this.generation_config.top_k>0&&(C=Math.min(this.generation_config.top_k,C));const[T,z]=await(0,a.topk)(w,C),S=(0,l.softmax)(T.data);return Array.from({length:this.generation_config.num_beams},(E,y)=>[z.data[y],Math.log(S[y])])}}},"./src/generation/stopping_criteria.js":(e,t,r)=>{r.r(t),r.d(t,{EosTokenCriteria:()=>_,InterruptableStoppingCriteria:()=>p,MaxLengthCriteria:()=>f,StoppingCriteria:()=>a,StoppingCriteriaList:()=>l});var o=r("./src/utils/generic.js");class a extends o.Callable{_call(M,w){throw Error("StoppingCriteria needs to be subclassed")}}class l extends o.Callable{constructor(){super(),this.criteria=[]}push(M){this.criteria.push(M)}extend(M){M instanceof l?M=M.criteria:M instanceof a&&(M=[M]),this.criteria.push(...M)}_call(M,w){const C=new Array(M.length).fill(!1);for(const T of this.criteria){const z=T(M,w);for(let S=0;Sw.length>=this.max_length)}}class _ extends a{constructor(M){super(),Array.isArray(M)||(M=[M]),this.eos_token_id=M}_call(M,w){return M.map(C=>{const T=C.at(-1);return this.eos_token_id.some(z=>T==z)})}}class p extends a{constructor(){super(),this.interrupted=!1}interrupt(){this.interrupted=!0}reset(){this.interrupted=!1}_call(M,w){return new Array(M.length).fill(this.interrupted)}}},"./src/generation/streamers.js":(e,t,r)=>{r.r(t),r.d(t,{BaseStreamer:()=>f,TextStreamer:()=>p,WhisperTextStreamer:()=>g});var o=r("./src/utils/core.js"),a=r("./src/tokenizers.js"),l=r("./src/env.js");class f{put(w){throw Error("Not implemented")}end(){throw Error("Not implemented")}}const _=l.apis.IS_PROCESS_AVAILABLE?M=>process.stdout.write(M):M=>console.log(M);class p extends f{constructor(w,{skip_prompt:C=!1,callback_function:T=null,token_callback_function:z=null,decode_kwargs:S={},...E}={}){super(),this.tokenizer=w,this.skip_prompt=C,this.callback_function=T??_,this.token_callback_function=z,this.decode_kwargs={...S,...E},this.token_cache=[],this.print_len=0,this.next_tokens_are_prompt=!0}put(w){var S;if(w.length>1)throw Error("TextStreamer only supports batch size of 1");const C=w[0];if((S=this.token_callback_function)==null||S.call(this,C),this.skip_prompt&&this.next_tokens_are_prompt){this.next_tokens_are_prompt=!1;return}this.token_cache=(0,o.mergeArrays)(this.token_cache,C);const T=this.tokenizer.decode(this.token_cache,this.decode_kwargs);let z;T.endsWith(` +`)?(z=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))?(z=T.slice(this.print_len),this.print_len+=z.length):(z=T.slice(this.print_len,T.lastIndexOf(" ")+1),this.print_len+=z.length),this.on_finalized_text(z,!1)}end(){let w;this.token_cache.length>0?(w=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len),this.token_cache=[],this.print_len=0):w="",this.next_tokens_are_prompt=!0,this.on_finalized_text(w,!0)}on_finalized_text(w,C){var T,z;w.length>0&&((T=this.callback_function)==null||T.call(this,w)),C&&this.callback_function===_&&l.apis.IS_PROCESS_AVAILABLE&&((z=this.callback_function)==null||z.call(this,` +`))}}class g extends p{constructor(w,{skip_prompt:C=!1,callback_function:T=null,token_callback_function:z=null,on_chunk_start:S=null,on_chunk_end:E=null,on_finalize:y=null,time_precision:b=.02,skip_special_tokens:I=!0,decode_kwargs:V={}}={}){super(w,{skip_prompt:C,callback_function:T,token_callback_function:z,decode_kwargs:{skip_special_tokens:I,...V}}),this.timestamp_begin=w.timestamp_begin,this.on_chunk_start=S,this.on_chunk_end=E,this.on_finalize=y,this.time_precision=b,this.waiting_for_timestamp=!1}put(w){var T,z;if(w.length>1)throw Error("WhisperTextStreamer only supports batch size of 1");const C=w[0];if(C.length===1){const S=Number(C[0])-this.timestamp_begin;if(S>=0){const E=S*this.time_precision;this.waiting_for_timestamp?(T=this.on_chunk_end)==null||T.call(this,E):(z=this.on_chunk_start)==null||z.call(this,E),this.waiting_for_timestamp=!this.waiting_for_timestamp,w=[[]]}}return super.put(w)}end(){var w;super.end(),(w=this.on_finalize)==null||w.call(this)}}},"./src/models.js":(e,t,r)=>{r.r(t),r.d(t,{ASTForAudioClassification:()=>$s,ASTModel:()=>Ot,ASTPreTrainedModel:()=>Un,AlbertForMaskedLM:()=>Zt,AlbertForQuestionAnswering:()=>mo,AlbertForSequenceClassification:()=>ho,AlbertModel:()=>Ji,AlbertPreTrainedModel:()=>Si,AutoModel:()=>Bd,AutoModelForAudioClassification:()=>Yd,AutoModelForAudioFrameClassification:()=>Zd,AutoModelForCTC:()=>Qd,AutoModelForCausalLM:()=>Vd,AutoModelForDepthEstimation:()=>tf,AutoModelForDocumentQuestionAnswering:()=>Tp,AutoModelForImageClassification:()=>Hd,AutoModelForImageFeatureExtraction:()=>rf,AutoModelForImageMatting:()=>Jd,AutoModelForImageSegmentation:()=>Tl,AutoModelForImageToImage:()=>ef,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:()=>fe,BartModel:()=>Ue,BartPretrainedModel:()=>Nn,BaseModelOutput:()=>Ke,BeitForImageClassification:()=>cc,BeitModel:()=>uc,BeitPreTrainedModel:()=>za,BertForMaskedLM:()=>We,BertForQuestionAnswering:()=>Ge,BertForSequenceClassification:()=>st,BertForTokenClassification:()=>ft,BertModel:()=>Be,BertPreTrainedModel:()=>Le,BlenderbotForConditionalGeneration:()=>It,BlenderbotModel:()=>kt,BlenderbotPreTrainedModel:()=>St,BlenderbotSmallForConditionalGeneration:()=>sr,BlenderbotSmallModel:()=>$r,BlenderbotSmallPreTrainedModel:()=>tr,BloomForCausalLM:()=>Gu,BloomModel:()=>Wu,BloomPreTrainedModel:()=>Fs,CLIPModel:()=>fu,CLIPPreTrainedModel:()=>Ho,CLIPSegForImageSegmentation:()=>yu,CLIPSegModel:()=>wu,CLIPSegPreTrainedModel:()=>ya,CLIPTextModelWithProjection:()=>hi,CLIPVisionModelWithProjection:()=>pu,CamembertForMaskedLM:()=>Re,CamembertForQuestionAnswering:()=>tt,CamembertForSequenceClassification:()=>qe,CamembertForTokenClassification:()=>Qe,CamembertModel:()=>ve,CamembertPreTrainedModel:()=>Y,CausalLMOutput:()=>to,CausalLMOutputWithPast:()=>kp,ChineseCLIPModel:()=>_u,ChineseCLIPPreTrainedModel:()=>gu,ClapAudioModelWithProjection:()=>fd,ClapModel:()=>cd,ClapPreTrainedModel:()=>Ko,ClapTextModelWithProjection:()=>dd,CodeGenForCausalLM:()=>As,CodeGenModel:()=>Pu,CodeGenPreTrainedModel:()=>Qn,CohereForCausalLM:()=>Iu,CohereModel:()=>Au,CoherePreTrainedModel:()=>Ta,ConvBertForMaskedLM:()=>B,ConvBertForQuestionAnswering:()=>ue,ConvBertForSequenceClassification:()=>J,ConvBertForTokenClassification:()=>L,ConvBertModel:()=>ye,ConvBertPreTrainedModel:()=>ne,ConvNextForImageClassification:()=>Fc,ConvNextModel:()=>Ic,ConvNextPreTrainedModel:()=>qa,ConvNextV2ForImageClassification:()=>Dc,ConvNextV2Model:()=>Oc,ConvNextV2PreTrainedModel:()=>zc,DPTForDepthEstimation:()=>Wa,DPTModel:()=>Va,DPTPreTrainedModel:()=>Ua,DebertaForMaskedLM:()=>Tt,DebertaForQuestionAnswering:()=>Lt,DebertaForSequenceClassification:()=>vt,DebertaForTokenClassification:()=>Et,DebertaModel:()=>ht,DebertaPreTrainedModel:()=>pt,DebertaV2ForMaskedLM:()=>Vt,DebertaV2ForQuestionAnswering:()=>rr,DebertaV2ForSequenceClassification:()=>Xt,DebertaV2ForTokenClassification:()=>Yt,DebertaV2Model:()=>zt,DebertaV2PreTrainedModel:()=>at,DeiTForImageClassification:()=>bc,DeiTModel:()=>vc,DeiTPreTrainedModel:()=>La,DepthAnythingForDepthEstimation:()=>Cc,DepthAnythingPreTrainedModel:()=>Ec,DetrForObjectDetection:()=>fc,DetrForSegmentation:()=>pc,DetrModel:()=>dc,DetrObjectDetectionOutput:()=>Oa,DetrPreTrainedModel:()=>Ds,DetrSegmentationOutput:()=>hc,Dinov2ForImageClassification:()=>Rc,Dinov2Model:()=>Lc,Dinov2PreTrainedModel:()=>Zn,DistilBertForMaskedLM:()=>Pt,DistilBertForQuestionAnswering:()=>mt,DistilBertForSequenceClassification:()=>Yr,DistilBertForTokenClassification:()=>Pr,DistilBertModel:()=>Cr,DistilBertPreTrainedModel:()=>Ht,DonutSwinModel:()=>Ha,DonutSwinPreTrainedModel:()=>Ac,EfficientNetForImageClassification:()=>_d,EfficientNetModel:()=>gd,EfficientNetPreTrainedModel:()=>pl,ElectraForMaskedLM:()=>Ne,ElectraForQuestionAnswering:()=>Ve,ElectraForSequenceClassification:()=>dt,ElectraForTokenClassification:()=>Je,ElectraModel:()=>Te,ElectraPreTrainedModel:()=>le,EsmForMaskedLM:()=>Bi,EsmForSequenceClassification:()=>Mi,EsmForTokenClassification:()=>Wr,EsmModel:()=>un,EsmPreTrainedModel:()=>Nt,FalconForCausalLM:()=>ud,FalconModel:()=>ld,FalconPreTrainedModel:()=>ul,FastViTForImageClassification:()=>Zu,FastViTModel:()=>Yu,FastViTPreTrainedModel:()=>Os,Florence2ForConditionalGeneration:()=>_a,Florence2PreTrainedModel:()=>du,GLPNForDepthEstimation:()=>$c,GLPNModel:()=>Pc,GLPNPreTrainedModel:()=>Ga,GPT2LMHeadModel:()=>bu,GPT2Model:()=>vu,GPT2PreTrainedModel:()=>va,GPTBigCodeForCausalLM:()=>np,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:()=>Ou,Gemma2PreTrainedModel:()=>Sa,GemmaForCausalLM:()=>zu,GemmaModel:()=>Fu,GemmaPreTrainedModel:()=>ka,HubertForCTC:()=>Jc,HubertForSequenceClassification:()=>rl,HubertModel:()=>up,HubertPreTrainedModel:()=>lp,ImageMattingOutput:()=>of,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:()=>ze,MBartForSequenceClassification:()=>rt,MBartModel:()=>Fe,MBartPreTrainedModel:()=>Ee,MPNetForMaskedLM:()=>Lo,MPNetForQuestionAnswering:()=>No,MPNetForSequenceClassification:()=>Ro,MPNetForTokenClassification:()=>Bo,MPNetModel:()=>Cs,MPNetPreTrainedModel:()=>Ti,MT5ForConditionalGeneration:()=>Ur,MT5Model:()=>Go,MT5PreTrainedModel:()=>_o,MarianMTModel:()=>Gc,MarianModel:()=>sp,MarianPreTrainedModel:()=>Xa,MaskedLMOutput:()=>bn,MistralForCausalLM:()=>Vs,MistralModel:()=>Us,MistralPreTrainedModel:()=>sl,MobileBertForMaskedLM:()=>fi,MobileBertForQuestionAnswering:()=>Ni,MobileBertForSequenceClassification:()=>Or,MobileBertModel:()=>Kr,MobileBertPreTrainedModel:()=>wn,MobileNetV1ForImageClassification:()=>pp,MobileNetV1Model:()=>wd,MobileNetV1PreTrainedModel:()=>gl,MobileNetV2ForImageClassification:()=>vd,MobileNetV2Model:()=>yd,MobileNetV2PreTrainedModel:()=>_l,MobileNetV3ForImageClassification:()=>hp,MobileNetV3Model:()=>bd,MobileNetV3PreTrainedModel:()=>wl,MobileNetV4ForImageClassification:()=>yl,MobileNetV4Model:()=>Yo,MobileNetV4PreTrainedModel:()=>Qo,MobileViTForImageClassification:()=>nc,MobileViTModel:()=>rc,MobileViTPreTrainedModel:()=>tc,MobileViTV2ForImageClassification:()=>ic,MobileViTV2Model:()=>op,MobileViTV2PreTrainedModel:()=>Ia,ModelOutput:()=>me,Moondream1ForConditionalGeneration:()=>ur,MptForCausalLM:()=>Hu,MptModel:()=>ip,MptPreTrainedModel:()=>zs,MusicgenForCausalLM:()=>gm,MusicgenForConditionalGeneration:()=>ml,MusicgenModel:()=>fp,MusicgenPreTrainedModel:()=>hl,NomicBertModel:()=>je,NomicBertPreTrainedModel:()=>Me,OPTForCausalLM:()=>Ku,OPTModel:()=>qu,OPTPreTrainedModel:()=>Aa,OpenELMForCausalLM:()=>Ru,OpenELMModel:()=>Lu,OpenELMPreTrainedModel:()=>Yn,OwlViTForObjectDetection:()=>sc,OwlViTModel:()=>oc,OwlViTPreTrainedModel:()=>yr,Owlv2ForObjectDetection:()=>lc,Owlv2Model:()=>ac,Owlv2PreTrainedModel:()=>Fa,Phi3ForCausalLM:()=>$a,Phi3Model:()=>Vu,Phi3PreTrainedModel:()=>Pa,PhiForCausalLM:()=>Uu,PhiModel:()=>ju,PhiPreTrainedModel:()=>Ca,PreTrainedModel:()=>Q,PretrainedMixin:()=>Lr,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:()=>gr,RobertaPreTrainedModel:()=>qt,SamImageSegmentationOutput:()=>Wc,SamModel:()=>Vc,SamPreTrainedModel:()=>Uc,SegformerForImageClassification:()=>pd,SegformerForSemanticSegmentation:()=>hd,SegformerModel:()=>mm,SegformerPreTrainedModel:()=>Xo,Seq2SeqLMOutput:()=>wm,SequenceClassifierOutput:()=>cr,SiglipModel:()=>yo,SiglipPreTrainedModel:()=>wa,SiglipTextModel:()=>hu,SiglipVisionModel:()=>mu,SpeechT5ForSpeechToText:()=>od,SpeechT5ForTextToSpeech:()=>cp,SpeechT5HifiGan:()=>ol,SpeechT5Model:()=>id,SpeechT5PreTrainedModel:()=>il,SqueezeBertForMaskedLM:()=>po,SqueezeBertForQuestionAnswering:()=>ki,SqueezeBertForSequenceClassification:()=>pi,SqueezeBertModel:()=>Ps,SqueezeBertPreTrainedModel:()=>ji,StableLmForCausalLM:()=>md,StableLmModel:()=>fl,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:()=>Sp,VitsPreTrainedModel:()=>dp,Wav2Vec2BertForCTC:()=>js,Wav2Vec2BertForSequenceClassification:()=>Zc,Wav2Vec2BertModel:()=>tl,Wav2Vec2BertPreTrainedModel:()=>Ns,Wav2Vec2ForAudioFrameClassification:()=>Wi,Wav2Vec2ForCTC:()=>ap,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:()=>jn,XLMModel:()=>cn,XLMPreTrainedModel:()=>br,XLMRobertaForMaskedLM:()=>$t,XLMRobertaForQuestionAnswering:()=>Xr,XLMRobertaForSequenceClassification:()=>wr,XLMRobertaForTokenClassification:()=>Dr,XLMRobertaModel:()=>kr,XLMRobertaPreTrainedModel:()=>Tr,XLMWithLMHeadModel:()=>Fn,XVectorOutput:()=>nf,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"),f=r("./src/utils/generic.js"),_=r("./src/utils/core.js"),p=r("./src/utils/hub.js"),g=r("./src/generation/logits_process.js"),M=r("./src/generation/configuration_utils.js"),w=r("./src/utils/tensor.js"),C=r("./src/utils/maths.js"),T=r("./src/generation/stopping_criteria.js"),z=r("./src/generation/logits_sampler.js"),S=r("./src/env.js"),E=r("./src/models/whisper/generation_whisper.js"),y=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,V=new Map,O=new Map;async function N(U,G,ie){let ke=ie.device;ke&&typeof ke!="string"&&(ke.hasOwnProperty(G)?ke=ke[G]:(console.warn(`device not specified for "${G}". Using the default device.`),ke=null));const nt=(0,a.deviceToExecutionProviders)(ke);let Ze=ie.dtype;if(typeof Ze!="string"&&(Ze&&Ze.hasOwnProperty(G)?Ze=Ze[G]:(Ze=l.DEFAULT_DEVICE_DTYPE_MAPPING[nt[0]],console.warn(`dtype not specified for "${G}". Using the default dtype for this device (${Ze}).`))),l.DEFAULT_DTYPE_SUFFIX_MAPPING.hasOwnProperty(Ze)){if(Ze===l.DATA_TYPES.fp16&&ke==="webgpu"&&!await(0,l.isWebGpuFp16Supported)())throw new Error(`The device (${ke}) does not support fp16.`)}else throw new Error(`Invalid dtype: ${Ze}. Should be one of: ${Object.keys(l.DATA_TYPES).join(", ")}`);const bt=l.DEFAULT_DTYPE_SUFFIX_MAPPING[Ze],At=`${ie.subfolder??""}/${G}${bt}.onnx`,Rt={...ie.session_options};Rt.executionProviders??(Rt.executionProviders=nt);const dr=(0,p.getModelFile)(U,At,!0,ie);let hr=[];if(ie.use_external_data_format&&(ie.use_external_data_format===!0||typeof ie.use_external_data_format=="object"&&ie.use_external_data_format.hasOwnProperty(G)&&ie.use_external_data_format[G]===!0)){if(S.apis.IS_NODE_ENV)throw new Error("External data format is not yet supported in Node.js");const nr=`${G}${bt}.onnx_data`,ar=`${ie.subfolder??""}/${nr}`;hr.push(new Promise(async(xr,Er)=>{const Sr=await(0,p.getModelFile)(U,ar,!0,ie);xr({path:nr,data:Sr})}))}else Rt.externalData!==void 0&&(hr=Rt.externalData.map(async nr=>{if(typeof nr.data=="string"){const ar=await(0,p.getModelFile)(U,nr.data,!0,ie);return{...nr,data:ar}}return nr}));if(hr.length>0&&(Rt.externalData=await Promise.all(hr)),ke==="webgpu"){const nr=(0,o.getKeyValueShapes)(ie.config,{prefix:"present"});if(Object.keys(nr).length>0&&!(0,a.isONNXProxy)()){const ar={};for(const xr in nr)ar[xr]="gpu-buffer";Rt.preferredOutputLocation=ar}}return{buffer:await dr,session_options:Rt}}async function j(U,G,ie){return Object.fromEntries(await Promise.all(Object.keys(G).map(async ke=>{const{buffer:nt,session_options:Ze}=await N(U,G[ke],ie),bt=await(0,a.createInferenceSession)(nt,Ze);return[ke,bt]})))}function D(U,G){const ie=Object.create(null),ke=[];for(const bt of U.inputNames){const At=G[bt];if(!(At instanceof w.Tensor)){ke.push(bt);continue}ie[bt]=(0,a.isONNXProxy)()?At.clone():At}if(ke.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${ke.join(", ")}.`);const nt=Object.keys(G).length,Ze=U.inputNames.length;if(nt>Ze){let bt=Object.keys(G).filter(At=>!U.inputNames.includes(At));console.warn(`WARNING: Too many inputs were provided (${nt} > ${Ze}). The following inputs will be ignored: "${bt.join(", ")}".`)}return ie}async function ee(U,G){const ie=D(U,G);try{const ke=Object.fromEntries(Object.entries(ie).map(([Ze,bt])=>[Ze,bt.ort_tensor]));let nt=await U.run(ke);return nt=de(nt),nt}catch(ke){throw console.error(`An error occurred during model execution: "${ke}".`),console.error("Inputs given to model:",ie),ke}}function de(U){for(let G in U)(0,a.isONNXTensor)(U[G])?U[G]=new w.Tensor(U[G]):typeof U[G]=="object"&&de(U[G]);return U}function Ce(U){if(U instanceof w.Tensor)return U;if(U.length===0)throw Error("items must be non-empty");if(Array.isArray(U[0])){if(U.some(G=>G.length!==U[0].length))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=True' and/or 'truncation=True' to have batched tensors with the same length.");return new w.Tensor("int64",BigInt64Array.from(U.flat().map(G=>BigInt(G))),[U.length,U[0].length])}else return new w.Tensor("int64",BigInt64Array.from(U.map(G=>BigInt(G))),[1,U.length])}function te(U){return new w.Tensor("bool",[U],[1])}async function _e(U,G){let{encoder_outputs:ie,input_ids:ke,decoder_input_ids:nt,...Ze}=G;if(!ie){const At=(0,_.pick)(G,U.sessions.model.inputNames);ie=(await R(U,At)).last_hidden_state}return Ze.input_ids=nt,Ze.encoder_hidden_states=ie,U.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(Ze.encoder_attention_mask=G.attention_mask),await xe(U,Ze,!0)}async function R(U,G){const ie=U.sessions.model,ke=(0,_.pick)(G,ie.inputNames);if(ie.inputNames.includes("inputs_embeds")&&!ke.inputs_embeds){if(!G.input_ids)throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");ke.inputs_embeds=await U.encode_text({input_ids:G.input_ids})}return ie.inputNames.includes("token_type_ids")&&!ke.token_type_ids&&(ke.token_type_ids=new w.Tensor("int64",new BigInt64Array(ke.input_ids.data.length),ke.input_ids.dims)),await ee(ie,ke)}async function xe(U,G,ie=!1){const ke=U.sessions[ie?"decoder_model_merged":"model"],{past_key_values:nt,...Ze}=G;ke.inputNames.includes("use_cache_branch")&&(Ze.use_cache_branch=te(!!nt)),ke.inputNames.includes("position_ids")&&Ze.attention_mask&&!Ze.position_ids&&(Ze.position_ids=ge(Ze,nt)),U.addPastKeyValues(Ze,nt);const bt=(0,_.pick)(Ze,ke.inputNames);return await ee(ke,bt)}async function Xe(U,{input_ids:G=null,attention_mask:ie=null,pixel_values:ke=null,position_ids:nt=null,inputs_embeds:Ze=null,past_key_values:bt=null,generation_config:At=null,logits_processor:Rt=null,...dr}){if(!Ze){if(Ze=await U.encode_text({input_ids:G}),ke&&G.dims[1]!==1){const Ar=await U.encode_image({pixel_values:ke});({inputs_embeds:Ze,attention_mask:ie}=U._merge_input_ids_with_image_features({image_features:Ar,inputs_embeds:Ze,input_ids:G,attention_mask:ie}))}else if(bt&&ke&&G.dims[1]===1){const Ar=G.dims[1],nr=Object.values(bt)[0].dims.at(-2);ie=(0,w.cat)([(0,w.ones)([G.dims[0],nr]),ie.slice(null,[ie.dims[1]-Ar,ie.dims[1]])],1)}}return await xe(U,{inputs_embeds:Ze,past_key_values:bt,attention_mask:ie,position_ids:nt,generation_config:At,logits_processor:Rt},!0)}function ge(U,G=null){const{input_ids:ie,inputs_embeds:ke,attention_mask:nt}=U,[Ze,bt]=nt.dims,At=new BigInt64Array(nt.data.length);for(let dr=0;drZe.dims[1])){if(ntAt==U.config.image_token_index)){const At=U.config.num_image_tokens;if(!At)throw new Error("`num_image_tokens` is missing in the model configuration.");const Rt=Ze.dims[1]-(nt-At);ie.input_ids=Ze.slice(null,[-Rt,null]),ie.attention_mask=(0,w.ones)([1,nt+Rt])}}}return ie}function ae(U,G,ie,ke){return ie.past_key_values&&(G=G.map(nt=>[nt.at(-1)])),{...ie,decoder_input_ids:Ce(G)}}function Se(U,...G){return U.config.is_encoder_decoder?ae(U,...G):X(U,...G)}class Q extends f.Callable{constructor(ie,ke){super();He(this,"main_input_name","input_ids");He(this,"forward_params",["input_ids","attention_mask"]);this.config=ie,this.sessions=ke;const nt=O.get(this.constructor),Ze=I.get(nt);switch(this.can_generate=!1,this._forward=null,this._prepare_inputs_for_generation=null,Ze){case b.DecoderOnly:this.can_generate=!0,this._forward=xe,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=ae;break;case b.EncoderDecoder:this._forward=_e;break;case b.ImageTextToText:this.can_generate=!0,this._forward=Xe,this._prepare_inputs_for_generation=Se;break;default:this._forward=R;break}this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){var ke;const ie=[];for(const nt of Object.values(this.sessions))(ke=nt==null?void 0:nt.handler)!=null&&ke.dispose&&ie.push(nt.handler.dispose());return await Promise.all(ie)}static async from_pretrained(ie,{progress_callback:ke=null,config:nt=null,cache_dir:Ze=null,local_files_only:bt=!1,revision:At="main",model_file_name:Rt=null,subfolder:dr="onnx",device:hr=null,dtype:Ar=null,use_external_data_format:nr=null,session_options:ar={}}={}){let xr={progress_callback:ke,config:nt,cache_dir:Ze,local_files_only:bt,revision:At,model_file_name:Rt,subfolder:dr,device:hr,dtype:Ar,use_external_data_format:nr,session_options:ar};const Er=O.get(this),Sr=I.get(Er);nt=xr.config=await o.AutoConfig.from_pretrained(ie,xr);let Nr;if(Sr===b.DecoderOnly)Nr=await Promise.all([j(ie,{model:xr.model_file_name??"model"},xr),(0,p.getModelJSON)(ie,"generation_config.json",!1,xr)]);else if(Sr===b.Seq2Seq||Sr===b.Vision2Seq)Nr=await Promise.all([j(ie,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},xr),(0,p.getModelJSON)(ie,"generation_config.json",!1,xr)]);else if(Sr===b.MaskGeneration)Nr=await Promise.all([j(ie,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},xr)]);else if(Sr===b.EncoderDecoder)Nr=await Promise.all([j(ie,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},xr)]);else if(Sr===b.ImageTextToText){const Vn={embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};nt.is_encoder_decoder&&(Vn.model="encoder_model"),Nr=await Promise.all([j(ie,Vn,xr),(0,p.getModelJSON)(ie,"generation_config.json",!1,xr)])}else Sr===b.Musicgen?Nr=await Promise.all([j(ie,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},xr),(0,p.getModelJSON)(ie,"generation_config.json",!1,xr)]):(Sr!==b.EncoderOnly&&console.warn(`Model type for '${Er??(nt==null?void 0:nt.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(ie,{model:xr.model_file_name??"model"},xr)]));return new this(nt,...Nr)}async _call(ie){return await this.forward(ie)}async forward(ie){return await this._forward(this,ie)}_get_logits_warper(ie){const ke=new g.LogitsProcessorList;return ie.temperature!==null&&ie.temperature!==1&&ke.push(new g.TemperatureLogitsWarper(ie.temperature)),ie.top_k!==null&&ie.top_k!==0&&ke.push(new g.TopKLogitsWarper(ie.top_k)),ie.top_p!==null&&ie.top_p<1&&ke.push(new g.TopPLogitsWarper(ie.top_p)),ke}_get_logits_processor(ie,ke,nt=null){const Ze=new g.LogitsProcessorList;if(ie.repetition_penalty!==null&&ie.repetition_penalty!==1&&Ze.push(new g.RepetitionPenaltyLogitsProcessor(ie.repetition_penalty)),ie.no_repeat_ngram_size!==null&&ie.no_repeat_ngram_size>0&&Ze.push(new g.NoRepeatNGramLogitsProcessor(ie.no_repeat_ngram_size)),ie.bad_words_ids!==null&&Ze.push(new g.NoBadWordsLogitsProcessor(ie.bad_words_ids,ie.eos_token_id)),ie.min_length!==null&&ie.eos_token_id!==null&&ie.min_length>0&&Ze.push(new g.MinLengthLogitsProcessor(ie.min_length,ie.eos_token_id)),ie.min_new_tokens!==null&&ie.eos_token_id!==null&&ie.min_new_tokens>0&&Ze.push(new g.MinNewTokensLengthLogitsProcessor(ke,ie.min_new_tokens,ie.eos_token_id)),ie.forced_bos_token_id!==null&&Ze.push(new g.ForcedBOSTokenLogitsProcessor(ie.forced_bos_token_id)),ie.forced_eos_token_id!==null&&Ze.push(new g.ForcedEOSTokenLogitsProcessor(ie.max_length,ie.forced_eos_token_id)),ie.begin_suppress_tokens!==null){const bt=ke>1||ie.forced_bos_token_id===null?ke:ke+1;Ze.push(new g.SuppressTokensAtBeginLogitsProcessor(ie.begin_suppress_tokens,bt))}return ie.guidance_scale!==null&&ie.guidance_scale>1&&Ze.push(new g.ClassifierFreeGuidanceLogitsProcessor(ie.guidance_scale)),nt!==null&&Ze.extend(nt),Ze}_prepare_generation_config(ie,ke,nt=M.GenerationConfig){const Ze={...this.config};for(const At of["decoder","generator","text_config"])At in Ze&&Object.assign(Ze,Ze[At]);const bt=new nt(Ze);return"generation_config"in this&&Object.assign(bt,this.generation_config),ie&&Object.assign(bt,ie),ke&&Object.assign(bt,(0,_.pick)(ke,Object.getOwnPropertyNames(bt))),bt}_get_stopping_criteria(ie,ke=null){const nt=new T.StoppingCriteriaList;return ie.max_length!==null&&nt.push(new T.MaxLengthCriteria(ie.max_length,this.config.max_position_embeddings??null)),ie.eos_token_id!==null&&nt.push(new T.EosTokenCriteria(ie.eos_token_id)),ke&&nt.extend(ke),nt}_validate_model_class(){if(!this.can_generate){const ie=[Hs,bl,vl,Gs],ke=O.get(this.constructor),nt=new Set,Ze=this.config.model_type;for(const At of ie){const Rt=At.get(Ze);Rt&&nt.add(Rt[0])}let bt=`The current model class (${ke}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw nt.size>0&&(bt+=` Please use the following class instead: ${[...nt].join(", ")}`),Error(bt)}}prepare_inputs_for_generation(...ie){return this._prepare_inputs_for_generation(this,...ie)}_update_model_kwargs_for_generation({generated_input_ids:ie,outputs:ke,model_inputs:nt,is_encoder_decoder:Ze}){return nt.past_key_values=this.getPastKeyValues(ke,nt.past_key_values),nt.input_ids=new w.Tensor("int64",ie.flat(),[ie.length,1]),Ze||(nt.attention_mask=(0,w.cat)([nt.attention_mask,(0,w.ones)([nt.attention_mask.dims[0],1])],1)),nt.position_ids=null,nt}_prepare_model_inputs({inputs:ie,bos_token_id:ke,model_kwargs:nt}){const Ze=(0,_.pick)(nt,this.forward_params),bt=this.main_input_name;if(bt in Ze){if(ie)throw new Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else Ze[bt]=ie;return{inputs_tensor:Ze[bt],model_inputs:Ze,model_input_name:bt}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:ie,model_inputs:ke,model_input_name:nt,generation_config:Ze}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!ke.inputs_embeds&&"_prepare_inputs_embeds"in this){const{input_ids:At,pixel_values:Rt,attention_mask:dr,...hr}=ke,Ar=await this._prepare_inputs_embeds(ke);ke={...hr,...(0,_.pick)(Ar,["inputs_embeds","attention_mask"])}}let{last_hidden_state:bt}=await R(this,ke);if(Ze.guidance_scale!==null&&Ze.guidance_scale>1)bt=(0,w.cat)([bt,(0,w.full_like)(bt,0)],0),"attention_mask"in ke&&(ke.attention_mask=(0,w.cat)([ke.attention_mask,(0,w.zeros_like)(ke.attention_mask)],0));else if(ke.decoder_input_ids){const At=Ce(ke.decoder_input_ids).dims[0];if(At!==bt.dims[0]){if(bt.dims[0]!==1)throw new Error(`The encoder outputs have a different batch size (${bt.dims[0]}) than the decoder inputs (${At}).`);bt=(0,w.cat)(Array.from({length:At},()=>bt),0)}}return ke.encoder_outputs=bt,ke}_prepare_decoder_input_ids_for_generation({batch_size:ie,model_input_name:ke,model_kwargs:nt,decoder_start_token_id:Ze,bos_token_id:bt,generation_config:At}){let{decoder_input_ids:Rt,...dr}=nt;if(Rt)Array.isArray(Rt[0])||(Rt=Array.from({length:ie},()=>Rt));else if(Ze??(Ze=bt),this.config.model_type==="musicgen")Rt=Array.from({length:ie*this.config.decoder.num_codebooks},()=>[Ze]);else if(Array.isArray(Ze)){if(Ze.length!==ie)throw new Error(`\`decoder_start_token_id\` expcted to have length ${ie} but got ${Ze.length}`);Rt=Ze}else Rt=Array.from({length:ie},()=>[Ze]);return Rt=Ce(Rt),nt.decoder_attention_mask=(0,w.ones_like)(Rt),{input_ids:Rt,model_inputs:dr}}async generate({inputs:ie=null,generation_config:ke=null,logits_processor:nt=null,stopping_criteria:Ze=null,streamer:bt=null,...At}){this._validate_model_class(),ke=this._prepare_generation_config(ke,At);let{inputs_tensor:Rt,model_inputs:dr,model_input_name:hr}=this._prepare_model_inputs({inputs:ie,model_kwargs:At});const Ar=this.config.is_encoder_decoder;Ar&&("encoder_outputs"in dr||(dr=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:Rt,model_inputs:dr,model_input_name:hr,generation_config:ke})));let nr;Ar?{input_ids:nr,model_inputs:dr}=this._prepare_decoder_input_ids_for_generation({batch_size:dr[hr].dims.at(0),model_input_name:hr,model_kwargs:dr,decoder_start_token_id:ke.decoder_start_token_id,bos_token_id:ke.bos_token_id,generation_config:ke}):nr=dr[hr];let ar=nr.dims.at(-1);ke.max_new_tokens!==null&&(ke.max_length=ar+ke.max_new_tokens);const xr=this._get_logits_processor(ke,ar,nt),Er=this._get_stopping_criteria(ke,Ze),Sr=dr[hr].dims.at(0),Nr=z.LogitsSampler.getSampler(ke),Vn=new Array(Sr).fill(0),zn=nr.tolist();bt&&bt.put(zn);let Pi=null,Mn={};for(;;){dr=this.prepare_inputs_for_generation(zn,dr,ke);const Tn=await this.forward(dr);if(ke.output_attentions&&ke.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=xr(zn,qs),El=[];for(let mi=0;mimi)){ke.return_dict_in_generate&&(Pi=this.getPastKeyValues(Tn,dr.past_key_values,!1));break}dr=this._update_model_kwargs_for_generation({generated_input_ids:El,outputs:Tn,model_inputs:dr,is_encoder_decoder:Ar})}bt&&bt.end();const dn=new w.Tensor("int64",zn.flat(),[zn.length,zn[0].length]);return ke.return_dict_in_generate?{sequences:dn,past_key_values:Pi,...Mn}:dn}getPastKeyValues(ie,ke,nt=!0){const Ze=Object.create(null);for(const bt in ie)if(bt.startsWith("present")){const At=bt.replace("present","past_key_values");if(ke&&bt.includes("encoder"))Ze[At]=ke[At];else{if(nt&&ke){const Rt=ke[At];Rt.location==="gpu-buffer"&&Rt.dispose()}Ze[At]=ie[bt]}}return Ze}getAttentions(ie){const ke={};for(const nt of["cross_attentions","encoder_attentions","decoder_attentions"])for(const Ze in ie)Ze.startsWith(nt)&&(nt in ke||(ke[nt]=[]),ke[nt].push(ie[Ze]));return ke}addPastKeyValues(ie,ke){if(ke)Object.assign(ie,ke);else{const nt=this.custom_config.kv_cache_dtype??"float32",Ze=nt==="float16"?new Uint16Array:[],bt=(0,o.getKeyValueShapes)(this.config);for(const At in bt)ie[At]=new w.Tensor(nt,Ze,bt[At])}}async encode_image({pixel_values:ie}){const ke=(await ee(this.sessions.vision_encoder,{pixel_values:ie})).image_features;return this.config.num_image_tokens||(console.warn(`The number of image tokens was not set in the model configuration. Setting it to the number of features detected by the vision encoder (${ke.dims[1]}).`),this.config.num_image_tokens=ke.dims[1]),ke}async encode_text({input_ids:ie}){return(await ee(this.sessions.embed_tokens,{input_ids:ie})).inputs_embeds}}class me{}class Ke extends me{constructor({last_hidden_state:G,hidden_states:ie=null,attentions:ke=null}){super(),this.last_hidden_state=G,this.hidden_states=ie,this.attentions=ke}}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 cr(await super._call(G))}}class ft 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 Me extends Q{}class je extends Me{}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 cr(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 ne extends Q{}class ye extends ne{}class B extends ne{async _call(G){return new bn(await super._call(G))}}class J extends ne{async _call(G){return new cr(await super._call(G))}}class L extends ne{async _call(G){return new hn(await super._call(G))}}class ue extends ne{async _call(G){return new xn(await super._call(G))}}class le extends Q{}class Te 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 cr(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 Y extends Q{}class ve extends Y{}class Re extends Y{async _call(G){return new bn(await super._call(G))}}class qe extends Y{async _call(G){return new cr(await super._call(G))}}class Qe extends Y{async _call(G){return new hn(await super._call(G))}}class tt extends Y{async _call(G){return new xn(await super._call(G))}}class pt extends Q{}class ht extends pt{}class Tt extends pt{async _call(G){return new bn(await super._call(G))}}class vt extends pt{async _call(G){return new cr(await super._call(G))}}class Et extends pt{async _call(G){return new hn(await super._call(G))}}class Lt extends pt{async _call(G){return new xn(await super._call(G))}}class at extends Q{}class zt extends at{}class Vt extends at{async _call(G){return new bn(await super._call(G))}}class Xt extends at{async _call(G){return new cr(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 Cr extends Ht{}class Yr extends Ht{async _call(G){return new cr(await super._call(G))}}class Pr 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 Pt extends Ht{async _call(G){return new bn(await super._call(G))}}class Nt extends Q{}class un extends Nt{}class Bi extends Nt{async _call(G){return new bn(await super._call(G))}}class Mi extends Nt{async _call(G){return new cr(await super._call(G))}}class Wr extends Nt{async _call(G){return new hn(await super._call(G))}}class wn extends Q{}class Kr extends wn{}class fi extends wn{async _call(G){return new bn(await super._call(G))}}class Or extends wn{async _call(G){return new cr(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 cr(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 po extends ji{async _call(G){return new bn(await super._call(G))}}class pi extends ji{async _call(G){return new cr(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 cr(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(ie,ke,nt){super(ie,ke);He(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"]);this.generation_config=nt}}class jo extends eo{}class Uo extends eo{}class go extends Q{constructor(G,ie,ke){super(G,ie),this.generation_config=ke}}class Vo extends go{}class Wo extends go{}class _o extends Q{constructor(G,ie,ke){super(G,ie),this.generation_config=ke}}class Go extends _o{}class Ur extends _o{}class Nn extends Q{constructor(G,ie,ke){super(G,ie),this.generation_config=ke}}class Ue extends Nn{}class W extends Nn{}class fe extends Nn{async _call(G){return new cr(await super._call(G))}}class Ee extends Q{constructor(G,ie,ke){super(G,ie),this.generation_config=ke}}class Fe extends Ee{}class ze extends Ee{}class rt extends Ee{async _call(G){return new cr(await super._call(G))}}class Mt extends Ee{}class St extends Q{constructor(G,ie,ke){super(G,ie),this.generation_config=ke}}class kt extends St{}class It extends St{}class tr extends Q{constructor(G,ie,ke){super(G,ie),this.generation_config=ke}}class $r extends tr{}class sr extends tr{}class qt extends Q{}class gr 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 cr(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 br extends Q{}class cn extends br{}class Fn extends br{async _call(G){return new bn(await super._call(G))}}class Jt extends br{async _call(G){return new cr(await super._call(G))}}class jn extends br{async _call(G){return new hn(await super._call(G))}}class yn extends br{async _call(G){return new xn(await super._call(G))}}class Tr extends Q{}class kr extends Tr{}class $t extends Tr{async _call(G){return new bn(await super._call(G))}}class wr extends Tr{async _call(G){return new cr(await super._call(G))}}class Dr extends Tr{async _call(G){return new hn(await super._call(G))}}class Xr extends Tr{async _call(G){return new xn(await super._call(G))}}class Un extends Q{}class Ot extends Un{}class $s extends Un{}class _t extends Q{constructor(ie,ke,nt){super(ie,ke);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=nt}}class Gt extends _t{}class ma extends _t{_prepare_generation_config(G,ie){return super._prepare_generation_config(G,ie,E.WhisperGenerationConfig)}_retrieve_init_tokens(G){const ie=[G.decoder_start_token_id];let ke=G.language;const nt=G.task;if(G.is_multilingual){ke||(console.warn("No language specified - defaulting to English (en)."),ke="en");const bt=`<|${(0,y.whisper_language_to_code)(ke)}|>`;ie.push(G.lang_to_id[bt]),ie.push(G.task_to_id[nt??"transcribe"])}else if(ke||nt)throw new Error("Cannot specify `task` or `language` for an English-only model. If the model is intended to be multilingual, pass `is_multilingual=true` to generate, or update the generation config.");return!G.return_timestamps&&G.no_timestamps_token_id&&ie.at(-1)!==G.no_timestamps_token_id?ie.push(G.no_timestamps_token_id):G.return_timestamps&&ie.at(-1)===G.no_timestamps_token_id&&(console.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),ie.pop()),ie.filter(Ze=>Ze!=null)}async generate({inputs:G=null,generation_config:ie=null,logits_processor:ke=null,stopping_criteria:nt=null,...Ze}){ie=this._prepare_generation_config(ie,Ze);const bt=Ze.decoder_input_ids??this._retrieve_init_tokens(ie);if(ie.return_timestamps&&(ke??(ke=new g.LogitsProcessorList),ke.push(new g.WhisperTimeStampLogitsProcessor(ie,bt))),ie.begin_suppress_tokens&&(ke??(ke=new g.LogitsProcessorList),ke.push(new g.SuppressTokensAtBeginLogitsProcessor(ie.begin_suppress_tokens,bt.length))),ie.return_token_timestamps){if(!ie.alignment_heads)throw new Error("Model generation config has no `alignment_heads`, token-level timestamps not available. See https://gist.github.com/hollance/42e32852f24243b748ae6bc1f985b13a on how to add this property to the generation config.");ie.task==="translate"&&console.warn("Token-level timestamps may not be reliable for task 'translate'."),ie.output_attentions=!0,ie.return_dict_in_generate=!0}const At=await super.generate({inputs:G,generation_config:ie,logits_processor:ke,decoder_input_ids:bt,...Ze});return ie.return_token_timestamps&&(At.token_timestamps=this._extract_token_timestamps(At,ie.alignment_heads,ie.num_frames)),At}_extract_token_timestamps(G,ie,ke=null,nt=.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`.");ke==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 Ze=this.config.median_filter_width;Ze===void 0&&(console.warn("Model config has no `median_filter_width`, using default value of 7."),Ze=7);const bt=G.cross_attentions,At=Array.from({length:this.config.decoder_layers},(Er,Sr)=>(0,w.cat)(bt.map(Nr=>Nr[Sr]),2)),Rt=(0,w.stack)(ie.map(([Er,Sr])=>{if(Er>=At.length)throw new Error(`Layer index ${Er} is out of bounds for cross attentions (length ${At.length}).`);return ke?At[Er].slice(null,Sr,null,[0,ke]):At[Er].slice(null,Sr)})).transpose(1,0,2,3),[dr,hr]=(0,w.std_mean)(Rt,-2,0,!0),Ar=Rt.clone();for(let Er=0;ErNr[Tn+1]-Nr[Tn]),Pi=(0,_.mergeArrays)([1],zn).map(dn=>!!dn),Mn=[];for(let dn=0;dnnr.findIndex(ar=>ar==Ze)),Rt=At.every(nr=>nr===-1),dr=At.every(nr=>nr!==-1);if(!Rt&&!dr)throw new Error("Every input should contain either 0 or 1 image token.");if(Rt)return{inputs_embeds:G,attention_mask:nt};const hr=[],Ar=[];for(let nr=0;nrZe*bt,1);G.input_labels=new w.Tensor("int64",new BigInt64Array(nt).fill(1n),ke)}const ie={image_embeddings:G.image_embeddings,image_positional_embeddings:G.image_positional_embeddings};return G.input_points&&(ie.input_points=G.input_points),G.input_labels&&(ie.input_labels=G.input_labels),G.input_boxes&&(ie.input_boxes=G.input_boxes),await ee(this.sessions.prompt_encoder_mask_decoder,ie)}async _call(G){return new Wc(await super._call(G))}}class Wc extends me{constructor({iou_scores:G,pred_masks:ie}){super(),this.iou_scores=G,this.pred_masks=ie}}class Xa extends Q{constructor(G,ie,ke){super(G,ie),this.generation_config=ke}}class sp extends Xa{}class Gc extends Xa{}class Qa extends Q{constructor(G,ie,ke){super(G,ie),this.generation_config=ke}}class Hc extends Qa{}class qc extends Qa{}class Ui extends Q{}class Kc extends Ui{}class ap extends Ui{async _call(G){return new to(await super._call(G))}}class Vi extends Ui{async _call(G){return new cr(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 cr(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 cr(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 cr(await super._call(G))}}class lp extends Q{}class up 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 cr(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 cr(await super._call(G))}}class rd extends Ci{async _call(G){return new nf(await super._call(G))}}class nd extends Ci{async _call(G){return new hn(await super._call(G))}}class il extends Q{constructor(G,ie,ke){super(G,ie),this.generation_config=ke}}class id extends il{}class od extends il{}class cp extends il{async generate_speech(G,ie,{threshold:ke=.5,minlenratio:nt=0,maxlenratio:Ze=20,vocoder:bt=null}={}){const At={input_ids:G},{encoder_outputs:Rt,encoder_attention_mask:dr}=await R(this,At),hr=Rt.dims[1]/this.config.reduction_factor,Ar=Math.floor(hr*Ze),nr=Math.floor(hr*nt),ar=this.config.num_mel_bins;let xr=[],Er=null,Sr=null,Nr=0;for(;;){++Nr;const Pi=te(!!Sr);let Mn;Sr?Mn=Sr.output_sequence_out:Mn=new w.Tensor("float32",new Float32Array(ar),[1,1,ar]);let dn={use_cache_branch:Pi,output_sequence:Mn,encoder_attention_mask:dr,speaker_embeddings:ie,encoder_hidden_states:Rt};this.addPastKeyValues(dn,Er),Sr=await ee(this.sessions.decoder_model_merged,dn),Er=this.getPastKeyValues(Sr,Er);const{prob:Tn,spectrum:qs}=Sr;if(xr.push(qs),Nr>=nr&&(Array.from(Tn.data).filter(Ks=>Ks>=ke).length>0||Nr>=Ar))break}const Vn=(0,w.cat)(xr),{waveform:zn}=await ee(bt.sessions.model,{spectrogram:Vn});return{spectrogram:Vn,waveform:zn}}}class ol extends Q{constructor(){super(...arguments);He(this,"main_input_name","spectrogram")}}class sd extends Q{constructor(G,ie,ke){super(G,ie),this.generation_config=ke}}class ad extends sd{}class sl extends Q{constructor(G,ie,ke){super(G,ie),this.generation_config=ke}}class Us extends sl{}class Vs extends sl{}class al extends Q{constructor(G,ie,ke){super(G,ie),this.generation_config=ke}}class Ws extends al{}class ll extends al{}class ul extends Q{constructor(G,ie,ke){super(G,ie),this.generation_config=ke}}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,ie={}){return ie.model_file_name??(ie.model_file_name="text_model"),super.from_pretrained(G,ie)}}class fd extends Ko{static async from_pretrained(G,ie={}){return ie.model_file_name??(ie.model_file_name="audio_model"),super.from_pretrained(G,ie)}}class dp extends Q{}class cl extends dp{async _call(G){return new Sp(await super._call(G))}}class Xo extends Q{}class mm extends Xo{}class pd extends Xo{}class hd extends Xo{}class dl extends Q{constructor(G,ie,ke){super(G,ie),this.generation_config=ke}}class fl extends dl{}class md extends dl{}class pl extends Q{}class gd extends pl{}class _d extends pl{async _call(G){return new cr(await super._call(G))}}class hl extends Q{}class fp extends hl{}class gm extends hl{}class ml extends Q{constructor(ie,ke,nt){super(ie,ke);He(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"]);this.generation_config=nt}_apply_and_filter_by_delay_pattern_mask(ie){const[ke,nt]=ie.dims,Ze=this.config.decoder.num_codebooks,bt=nt-Ze;let At=0;for(let hr=0;hr0&&ar<=bt&&(ie.data[At++]=ie.data[hr])}const Rt=Math.floor(ke/Ze),dr=At/(Rt*Ze);return new w.Tensor(ie.type,ie.data.slice(0,At),[Rt,Ze,dr])}prepare_inputs_for_generation(ie,ke,nt){let Ze=structuredClone(ie);for(let At=0;At=Rt&&(Ze[At][Rt]=BigInt(this.config.decoder.pad_token_id));return nt.guidance_scale!==null&&nt.guidance_scale>1&&(Ze=Ze.concat(Ze)),super.prepare_inputs_for_generation(Ze,ke,nt)}async generate(ie){const ke=await super.generate(ie),nt=this._apply_and_filter_by_delay_pattern_mask(ke).unsqueeze_(0),{audio_values:Ze}=await ee(this.sessions.encodec_decode,{audio_codes:nt});return Ze}}class gl extends Q{}class wd extends gl{}class pp extends gl{async _call(G){return new cr(await super._call(G))}}class _l extends Q{}class yd extends _l{}class vd extends _l{async _call(G){return new cr(await super._call(G))}}class wl extends Q{}class bd extends wl{}class hp extends wl{async _call(G){return new cr(await super._call(G))}}class Qo extends Q{}class Yo extends Qo{}class yl extends Qo{async _call(G){return new cr(await super._call(G))}}class Lr{static async from_pretrained(G,{progress_callback:ie=null,config:ke=null,cache_dir:nt=null,local_files_only:Ze=!1,revision:bt="main",model_file_name:At=null,subfolder:Rt="onnx",device:dr=null,dtype:hr=null,use_external_data_format:Ar=null,session_options:nr={}}={}){let ar={progress_callback:ie,config:ke,cache_dir:nt,local_files_only:Ze,revision:bt,model_file_name:At,subfolder:Rt,device:dr,dtype:hr,use_external_data_format:Ar,session_options:nr};if(ar.config=await o.AutoConfig.from_pretrained(G,ar),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);for(let xr of this.MODEL_CLASS_MAPPINGS){const Er=xr.get(ar.config.model_type);if(Er)return await Er[1].from_pretrained(G,ar)}if(this.BASE_IF_FAIL)return console.warn(`Unknown model class "${ar.config.model_type}", attempting to construct from base class.`),await Q.from_pretrained(G,ar);throw Error(`Unsupported model type: ${ar.config.model_type}`)}}He(Lr,"MODEL_CLASS_MAPPINGS",null),He(Lr,"BASE_IF_FAIL",!1);const mp=new Map([["bert",["BertModel",Be]],["nomic_bert",["NomicBertModel",je]],["roformer",["RoFormerModel",et]],["electra",["ElectraModel",Te]],["esm",["EsmModel",un]],["convbert",["ConvBertModel",ye]],["camembert",["CamembertModel",ve]],["deberta",["DebertaModel",ht]],["deberta-v2",["DebertaV2Model",zt]],["mpnet",["MPNetModel",Cs]],["albert",["AlbertModel",Ji]],["distilbert",["DistilBertModel",Cr]],["roberta",["RobertaModel",gr]],["xlm",["XLMModel",cn]],["xlm-roberta",["XLMRobertaModel",kr]],["clap",["ClapModel",cd]],["clip",["CLIPModel",fu]],["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",up]],["wavlm",["WavLMModel",ed]],["audio-spectrogram-transformer",["ASTModel",Ot]],["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",op]],["owlvit",["OwlViTModel",oc]],["owlv2",["Owlv2Model",ac]],["beit",["BeitModel",uc]],["deit",["DeiTModel",vc]],["convnext",["ConvNextModel",Ic]],["convnextv2",["ConvNextV2Model",Oc]],["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]]]),gp=new Map([["t5",["T5Model",jo]],["longt5",["LongT5Model",Vo]],["mt5",["MT5Model",Go]],["bart",["BartModel",Ue]],["mbart",["MBartModel",Fe]],["marian",["MarianModel",sp]],["whisper",["WhisperModel",Gt]],["m2m_100",["M2M100Model",Hc]],["blenderbot",["BlenderbotModel",kt]],["blenderbot-small",["BlenderbotSmallModel",$r]]]),_p=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",Ou]],["openelm",["OpenELMModel",Lu]],["qwen2",["Qwen2Model",Bu]],["phi",["PhiModel",ju]],["phi3",["Phi3Model",Vu]],["mpt",["MptModel",ip]],["opt",["OPTModel",qu]],["mistral",["MistralModel",Us]],["starcoder2",["Starcoder2Model",Ws]],["falcon",["FalconModel",ld]],["stablelm",["StableLmModel",fl]]]),Gs=new Map([["speecht5",["SpeechT5ForSpeechToText",od]],["whisper",["WhisperForConditionalGeneration",ma]]]),xd=new Map([["speecht5",["SpeechT5ForTextToSpeech",cp]]]),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",J]],["camembert",["CamembertForSequenceClassification",qe]],["deberta",["DebertaForSequenceClassification",vt]],["deberta-v2",["DebertaV2ForSequenceClassification",Xt]],["mpnet",["MPNetForSequenceClassification",Ro]],["albert",["AlbertForSequenceClassification",ho]],["distilbert",["DistilBertForSequenceClassification",Yr]],["roberta",["RobertaForSequenceClassification",gn]],["xlm",["XLMForSequenceClassification",Jt]],["xlm-roberta",["XLMRobertaForSequenceClassification",wr]],["bart",["BartForSequenceClassification",fe]],["mbart",["MBartForSequenceClassification",rt]],["mobilebert",["MobileBertForSequenceClassification",Or]],["squeezebert",["SqueezeBertForSequenceClassification",pi]]]),wp=new Map([["bert",["BertForTokenClassification",ft]],["roformer",["RoFormerForTokenClassification",Pe]],["electra",["ElectraForTokenClassification",Je]],["esm",["EsmForTokenClassification",Wr]],["convbert",["ConvBertForTokenClassification",L]],["camembert",["CamembertForTokenClassification",Qe]],["deberta",["DebertaForTokenClassification",Et]],["deberta-v2",["DebertaV2ForTokenClassification",Yt]],["mpnet",["MPNetForTokenClassification",Bo]],["distilbert",["DistilBertForTokenClassification",Pr]],["roberta",["RobertaForTokenClassification",ct]],["xlm",["XLMForTokenClassification",jn]],["xlm-roberta",["XLMRobertaForTokenClassification",Dr]]]),vl=new Map([["t5",["T5ForConditionalGeneration",Uo]],["longt5",["LongT5ForConditionalGeneration",Wo]],["mt5",["MT5ForConditionalGeneration",Ur]],["bart",["BartForConditionalGeneration",W]],["mbart",["MBartForConditionalGeneration",ze]],["marian",["MarianMTModel",Gc]],["m2m_100",["M2M100ForConditionalGeneration",qc]],["blenderbot",["BlenderbotForConditionalGeneration",It]],["blenderbot-small",["BlenderbotSmallForConditionalGeneration",sr]]]),Hs=new Map([["bloom",["BloomForCausalLM",Gu]],["gpt2",["GPT2LMHeadModel",bu]],["gptj",["GPTJForCausalLM",Eu]],["gpt_bigcode",["GPTBigCodeForCausalLM",np]],["gpt_neo",["GPTNeoForCausalLM",Mu]],["gpt_neox",["GPTNeoXForCausalLM",ku]],["codegen",["CodeGenForCausalLM",As]],["llama",["LlamaForCausalLM",$u]],["cohere",["CohereForCausalLM",Iu]],["gemma",["GemmaForCausalLM",zu]],["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",B]],["camembert",["CamembertForMaskedLM",Re]],["deberta",["DebertaForMaskedLM",Tt]],["deberta-v2",["DebertaV2ForMaskedLM",Vt]],["mpnet",["MPNetForMaskedLM",Lo]],["albert",["AlbertForMaskedLM",Zt]],["distilbert",["DistilBertForMaskedLM",Pt]],["roberta",["RobertaForMaskedLM",Cn]],["xlm",["XLMWithLMHeadModel",Fn]],["xlm-roberta",["XLMRobertaForMaskedLM",$t]],["mobilebert",["MobileBertForMaskedLM",fi]],["squeezebert",["SqueezeBertForMaskedLM",po]]]),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",ur]],["florence2",["Florence2ForConditionalGeneration",_a]]]),yp=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",pd]],["efficientnet",["EfficientNetForImageClassification",_d]],["mobilenet_v1",["MobileNetV1ForImageClassification",pp]],["mobilenet_v2",["MobileNetV2ForImageClassification",vd]],["mobilenet_v3",["MobileNetV3ForImageClassification",hp]],["mobilenet_v4",["MobileNetV4ForImageClassification",yl]]]),vp=new Map([["detr",["DetrForObjectDetection",fc]],["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",pc]],["clipseg",["CLIPSegForImageSegmentation",yu]]]),$d=new Map([["segformer",["SegformerForSemanticSegmentation",hd]]]),Ad=new Map([["sam",["SamModel",Vc]]]),bp=new Map([["wav2vec2",["Wav2Vec2ForCTC",ap]],["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]]]),zd=new Map([["unispeech-sat",["UniSpeechSatForAudioFrameClassification",Bs]],["wavlm",["WavLMForAudioFrameClassification",nd]],["wav2vec2",["Wav2Vec2ForAudioFrameClassification",Wi]],["pyannote",["PyAnnoteForAudioFrameClassification",Gi]]]),Od=new Map([["vitmatte",["VitMatteForImageMatting",ec]]]),xp=new Map([["swin2sr",["Swin2SRForImageSuperResolution",ja]]]),Dd=new Map([["dpt",["DPTForDepthEstimation",Wa]],["depth_anything",["DepthAnythingForDepthEstimation",Cc]],["glpn",["GLPNForDepthEstimation",$c]]]),Ld=new Map([["clip",["CLIPVisionModelWithProjection",pu]],["siglip",["SiglipVisionModel",mu]]]),Rd=[[mp,b.EncoderOnly],[gp,b.EncoderDecoder],[_p,b.DecoderOnly],[Td,b.EncoderOnly],[wp,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],[Od,b.EncoderOnly],[xp,b.EncoderOnly],[Dd,b.EncoderOnly],[vp,b.EncoderOnly],[Cd,b.EncoderOnly],[Ad,b.MaskGeneration],[bp,b.EncoderOnly],[Id,b.EncoderOnly],[xd,b.Seq2Seq],[Md,b.EncoderOnly],[Fd,b.EncoderOnly],[zd,b.EncoderOnly],[Ld,b.EncoderOnly]];for(const[U,G]of Rd)for(const[ie,ke]of U.values())I.set(ie,G),O.set(ke,ie),V.set(ie,ke);const Mp=[["MusicgenForConditionalGeneration",ml,b.Musicgen],["CLIPTextModelWithProjection",hi,b.EncoderOnly],["SiglipTextModel",hu,b.EncoderOnly],["ClapTextModelWithProjection",dd,b.EncoderOnly],["ClapAudioModelWithProjection",fd,b.EncoderOnly]];for(const[U,G,ie]of Mp)I.set(U,ie),O.set(G,U),V.set(U,G);class Bd extends Lr{}He(Bd,"MODEL_CLASS_MAPPINGS",Rd.map(G=>G[0])),He(Bd,"BASE_IF_FAIL",!0);class Pn extends Lr{}He(Pn,"MODEL_CLASS_MAPPINGS",[Td]);class Nd extends Lr{}He(Nd,"MODEL_CLASS_MAPPINGS",[wp]);class jd extends Lr{}He(jd,"MODEL_CLASS_MAPPINGS",[vl]);class xl extends Lr{}He(xl,"MODEL_CLASS_MAPPINGS",[Gs]);class Ud extends Lr{}He(Ud,"MODEL_CLASS_MAPPINGS",[xd]);class Zo extends Lr{}He(Zo,"MODEL_CLASS_MAPPINGS",[Md]);class Vd extends Lr{}He(Vd,"MODEL_CLASS_MAPPINGS",[Hs]);class Wd extends Lr{}He(Wd,"MODEL_CLASS_MAPPINGS",[kd]);class Ml extends Lr{}He(Ml,"MODEL_CLASS_MAPPINGS",[Sd]);class Gd extends Lr{}He(Gd,"MODEL_CLASS_MAPPINGS",[bl]);class Hd extends Lr{}He(Hd,"MODEL_CLASS_MAPPINGS",[Ed]);class Tl extends Lr{}He(Tl,"MODEL_CLASS_MAPPINGS",[Pd]);class qd extends Lr{}He(qd,"MODEL_CLASS_MAPPINGS",[$d]);class Kd extends Lr{}He(Kd,"MODEL_CLASS_MAPPINGS",[vp]);class Xd extends Lr{}He(Xd,"MODEL_CLASS_MAPPINGS",[Cd]);class kl extends Lr{}He(kl,"MODEL_CLASS_MAPPINGS",[Ad]);class Qd extends Lr{}He(Qd,"MODEL_CLASS_MAPPINGS",[bp]);class Yd extends Lr{}He(Yd,"MODEL_CLASS_MAPPINGS",[Id]);class Sl extends Lr{}He(Sl,"MODEL_CLASS_MAPPINGS",[Fd]);class Zd extends Lr{}He(Zd,"MODEL_CLASS_MAPPINGS",[zd]);class Tp extends Lr{}He(Tp,"MODEL_CLASS_MAPPINGS",[yp]);class Jd extends Lr{}He(Jd,"MODEL_CLASS_MAPPINGS",[Od]);class ef extends Lr{}He(ef,"MODEL_CLASS_MAPPINGS",[xp]);class tf extends Lr{}He(tf,"MODEL_CLASS_MAPPINGS",[Dd]);class rf extends Lr{}He(rf,"MODEL_CLASS_MAPPINGS",[Ld]);class wm extends me{constructor({logits:G,past_key_values:ie,encoder_outputs:ke,decoder_attentions:nt=null,cross_attentions:Ze=null}){super(),this.logits=G,this.past_key_values=ie,this.encoder_outputs=ke,this.decoder_attentions=nt,this.cross_attentions=Ze}}class cr extends me{constructor({logits:G}){super(),this.logits=G}}class nf extends me{constructor({logits:G,embeddings:ie}){super(),this.logits=G,this.embeddings=ie}}class hn extends me{constructor({logits:G}){super(),this.logits=G}}class bn extends me{constructor({logits:G}){super(),this.logits=G}}class xn extends me{constructor({start_logits:G,end_logits:ie}){super(),this.start_logits=G,this.end_logits=ie}}class to extends me{constructor({logits:G}){super(),this.logits=G}}class kp extends me{constructor({logits:G,past_key_values:ie}){super(),this.logits=G,this.past_key_values=ie}}class of extends me{constructor({alphas:G}){super(),this.alphas=G}}class Sp extends me{constructor({waveform:G,spectrogram:ie}){super(),this.waveform=G,this.spectrogram=ie}}},"./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:()=>f});const o=[["en","english"],["zh","chinese"],["de","german"],["es","spanish"],["ru","russian"],["ko","korean"],["fr","french"],["ja","japanese"],["pt","portuguese"],["tr","turkish"],["pl","polish"],["ca","catalan"],["nl","dutch"],["ar","arabic"],["sv","swedish"],["it","italian"],["id","indonesian"],["hi","hindi"],["fi","finnish"],["vi","vietnamese"],["he","hebrew"],["uk","ukrainian"],["el","greek"],["ms","malay"],["cs","czech"],["ro","romanian"],["da","danish"],["hu","hungarian"],["ta","tamil"],["no","norwegian"],["th","thai"],["ur","urdu"],["hr","croatian"],["bg","bulgarian"],["lt","lithuanian"],["la","latin"],["mi","maori"],["ml","malayalam"],["cy","welsh"],["sk","slovak"],["te","telugu"],["fa","persian"],["lv","latvian"],["bn","bengali"],["sr","serbian"],["az","azerbaijani"],["sl","slovenian"],["kn","kannada"],["et","estonian"],["mk","macedonian"],["br","breton"],["eu","basque"],["is","icelandic"],["hy","armenian"],["ne","nepali"],["mn","mongolian"],["bs","bosnian"],["kk","kazakh"],["sq","albanian"],["sw","swahili"],["gl","galician"],["mr","marathi"],["pa","punjabi"],["si","sinhala"],["km","khmer"],["sn","shona"],["yo","yoruba"],["so","somali"],["af","afrikaans"],["oc","occitan"],["ka","georgian"],["be","belarusian"],["tg","tajik"],["sd","sindhi"],["gu","gujarati"],["am","amharic"],["yi","yiddish"],["lo","lao"],["uz","uzbek"],["fo","faroese"],["ht","haitian creole"],["ps","pashto"],["tk","turkmen"],["nn","nynorsk"],["mt","maltese"],["sa","sanskrit"],["lb","luxembourgish"],["my","myanmar"],["bo","tibetan"],["tl","tagalog"],["mg","malagasy"],["as","assamese"],["tt","tatar"],["haw","hawaiian"],["ln","lingala"],["ha","hausa"],["ba","bashkir"],["jw","javanese"],["su","sundanese"]],a=new Map(o),l=new Map([...o.map(([_,p])=>[p,_]),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);function f(_){_=_.toLowerCase();let p=l.get(_);if(p===void 0)if(a.has(_))p=_;else{const M=_.length===2?a.keys():a.values();throw new Error(`Language "${_}" is not supported. Must be one of: ${JSON.stringify(M)}`)}return p}},"./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:()=>f});var o=r("./src/backends/onnx.js"),a=r("./src/utils/tensor.js");const l=async(_,p,g)=>{const M=await(0,o.createInferenceSession)(new Uint8Array(_),p);return async w=>{const C=Object.fromEntries(Object.entries(w).map(([z,S])=>[z,S.ort_tensor])),T=await M.run(C);return Array.isArray(g)?g.map(z=>new a.Tensor(T[z])):new a.Tensor(T[g])}};class f{static get bilinear_interpolate_4d(){return this._bilinear_interpolate_4d||(this._bilinear_interpolate_4d=l([8,9,18,0,58,128,1,10,40,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,17,10,4,109,111,100,101,34,6,108,105,110,101,97,114,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bilinear_interpolate_4d}static get bicubic_interpolate_4d(){return this._bicubic_interpolate_4d||(this._bicubic_interpolate_4d=l([8,9,18,0,58,127,10,39,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,16,10,4,109,111,100,101,34,5,99,117,98,105,99,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bicubic_interpolate_4d}static get matmul(){return this._matmul||(this._matmul=l([8,9,18,0,58,55,10,17,10,1,97,10,1,98,18,1,99,34,6,77,97,116,77,117,108,18,1,114,90,9,10,1,97,18,4,10,2,8,1,90,9,10,1,98,18,4,10,2,8,1,98,9,10,1,99,18,4,10,2,8,1,66,2,16,20],this.session_options,"c")),this._matmul}static get stft(){return this._stft||(this._stft=l([8,7,18,0,58,148,1,10,38,10,1,115,10,1,106,10,1,119,10,1,108,18,1,111,34,4,83,84,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,115,90,26,10,1,115,18,21,10,19,8,1,18,15,10,3,18,1,98,10,3,18,1,115,10,3,18,1,99,90,11,10,1,106,18,6,10,4,8,7,18,0,90,16,10,1,119,18,11,10,9,8,1,18,5,10,3,18,1,119,90,11,10,1,108,18,6,10,4,8,7,18,0,98,31,10,1,111,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,102,10,3,18,1,100,10,3,18,1,99,66,2,16,17],this.session_options,"o")),this._stft}static get rfft(){return this._rfft||(this._rfft=l([8,9,18,0,58,97,10,33,10,1,120,10,0,10,1,97,18,1,121,34,3,68,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,100,90,21,10,1,120,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,90,11,10,1,97,18,6,10,4,8,7,18,0,98,21,10,1,121,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,66,2,16,20],this.session_options,"y")),this._rfft}static get top_k(){return this._top_k||(this._top_k=l([8,10,18,0,58,73,10,18,10,1,120,10,1,107,18,1,118,18,1,105,34,4,84,111,112,75,18,1,116,90,9,10,1,120,18,4,10,2,8,1,90,15,10,1,107,18,10,10,8,8,7,18,4,10,2,8,1,98,9,10,1,118,18,4,10,2,8,1,98,9,10,1,105,18,4,10,2,8,7,66,2,16,21],this.session_options,["v","i"])),this._top_k}}He(f,"session_options",{})},"./src/pipelines.js":(e,t,r)=>{r.r(t),r.d(t,{AudioClassificationPipeline:()=>te,AutomaticSpeechRecognitionPipeline:()=>R,DepthEstimationPipeline:()=>Le,DocumentQuestionAnsweringPipeline:()=>Q,FeatureExtractionPipeline:()=>de,FillMaskPipeline:()=>I,ImageClassificationPipeline:()=>Xe,ImageFeatureExtractionPipeline:()=>Ce,ImageSegmentationPipeline:()=>ge,ImageToImagePipeline:()=>Ke,ImageToTextPipeline:()=>xe,ObjectDetectionPipeline:()=>ae,Pipeline:()=>S,QuestionAnsweringPipeline:()=>b,SummarizationPipeline:()=>O,Text2TextGenerationPipeline:()=>V,TextClassificationPipeline:()=>E,TextGenerationPipeline:()=>D,TextToAudioPipeline:()=>me,TokenClassificationPipeline:()=>y,TranslationPipeline:()=>N,ZeroShotAudioClassificationPipeline:()=>_e,ZeroShotClassificationPipeline:()=>ee,ZeroShotImageClassificationPipeline:()=>X,ZeroShotObjectDetectionPipeline:()=>Se,pipeline:()=>st});var o=r("./src/tokenizers.js"),a=r("./src/models.js"),l=r("./src/processors.js"),f=r("./src/utils/generic.js"),_=r("./src/utils/core.js"),p=r("./src/utils/maths.js"),g=r("./src/utils/audio.js"),M=r("./src/utils/tensor.js"),w=r("./src/utils/image.js");async function C(Ge){return Array.isArray(Ge)||(Ge=[Ge]),await Promise.all(Ge.map(Me=>w.RawImage.read(Me)))}async function T(Ge,Me){return Array.isArray(Ge)||(Ge=[Ge]),await Promise.all(Ge.map(je=>typeof je=="string"||je instanceof URL?(0,g.read_audio)(je,Me):je instanceof Float64Array?new Float32Array(je):je))}function z(Ge,Me){Me&&(Ge=Ge.map($e=>$e|0));const[je,Ye,et,A]=Ge;return{xmin:je,ymin:Ye,xmax:et,ymax:A}}class S extends f.Callable{constructor({task:Me,model:je,tokenizer:Ye=null,processor:et=null}){super(),this.task=Me,this.model=je,this.tokenizer=Ye,this.processor=et}async dispose(){await this.model.dispose()}}class E extends S{constructor(Me){super(Me)}async _call(Me,{top_k:je=1}={}){const Ye=this.tokenizer(Me,{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,p.softmax)(se.data),se.dims),$e=this.model.config.id2label,Pe=[];for(const se of et.logits){const ne=A(se),ye=await(0,M.topk)(ne,je),B=ye[0].tolist(),L=ye[1].tolist().map((ue,le)=>({label:$e?$e[ue]:`LABEL_${ue}`,score:B[le]}));je===1?Pe.push(...L):Pe.push(L)}return Array.isArray(Me)||je===1?Pe:Pe[0]}}class y extends S{constructor(Me){super(Me)}async _call(Me,{ignore_labels:je=["O"]}={}){const Ye=Array.isArray(Me),et=this.tokenizer(Ye?Me:[Me],{padding:!0,truncation:!0}),$e=(await this.model(et)).logits,Pe=this.model.config.id2label,se=[];for(let ne=0;ne<$e.dims[0];++ne){const ye=et.input_ids[ne],B=$e[ne],J=[];for(let L=0;LJe==this.tokenizer.sep_token_id);se[B].map((Je,Ve)=>Je==1&&(Ve===0||Ve>L&&ne.findIndex(Y=>Y==J[Ve])===-1));const ue=A[B].tolist(),le=$e[B].tolist();for(let Je=1;JeVe==J[Je])!==-1)&&(ue[Je]=-1/0,le[Je]=-1/0);const Te=(0,p.softmax)(ue).map((Je,Ve)=>[Je,Ve]),Ne=(0,p.softmax)(le).map((Je,Ve)=>[Je,Ve]);Te[0][0]=0,Ne[0][0]=0;const dt=(0,_.product)(Te,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(ne===-1)throw Error(`Mask token (${this.tokenizer.mask_token}) not found in text.`);const ye=et[Pe][ne],B=await(0,M.topk)(new M.Tensor("float32",(0,p.softmax)(ye.data),ye.dims),je),J=B[0].tolist(),L=B[1].tolist();A.push(L.map((ue,le)=>{const Te=se.slice();return Te[ne]=ue,{score:J[le],token:Number(ue),token_str:this.tokenizer.model.vocab[ue],sequence:this.tokenizer.decode(Te,{skip_special_tokens:!0})}}))}return Array.isArray(Me)?A:A[0]}}class V 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(ne=>this.model.config.prefix+ne));const et=this.model.config.task_specific_params;et&&et[this.task]&&et[this.task].prefix&&(je=je.map(ne=>et[this.task].prefix+ne));const A=this.tokenizer,$e={padding:!0,truncation:!0};let Pe;this instanceof N&&"_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(ne=>({[this._key]:ne}))}}class O extends V{constructor(je){super(je);He(this,"_key","summary_text")}}class N extends V{constructor(je){super(je);He(this,"_key","translation_text")}}function j(Ge){return Array.isArray(Ge)&&Ge.every(Me=>"role"in Me&&"content"in Me)}class D extends S{constructor(Me){super(Me)}async _call(Me,je={}){let Ye=!1,et=!1,A;if(typeof Me=="string")A=Me=[Me];else if(Array.isArray(Me)&&Me.every(L=>typeof L=="string"))Ye=!0,A=Me;else{if(j(Me))Me=[Me];else if(Array.isArray(Me)&&Me.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=Me.map(L=>this.tokenizer.apply_chat_template(L,{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}),ne=await this.model.generate({...se,...je}),ye=this.tokenizer.batch_decode(ne,{skip_special_tokens:!0});let B;!Pe&&se.input_ids.dims.at(-1)>0&&(B=this.tokenizer.batch_decode(se.input_ids,{skip_special_tokens:!0}).map(L=>L.length));const J=Array.from({length:Me.length},L=>[]);for(let L=0;L[je.toLowerCase(),Ye])),this.entailment_id=this.label2id.entailment,this.entailment_id===void 0&&(console.warn("Could not find 'entailment' in label2id mapping. Using 2 as entailment_id."),this.entailment_id=2),this.contradiction_id=this.label2id.contradiction??this.label2id.not_entailment,this.contradiction_id===void 0&&(console.warn("Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id."),this.contradiction_id=0)}async _call(Me,je,{hypothesis_template:Ye="This example is {}.",multi_label:et=!1}={}){const A=Array.isArray(Me);A||(Me=[Me]),Array.isArray(je)||(je=[je]);const $e=je.map(ne=>Ye.replace("{}",ne)),Pe=et||je.length===1,se=[];for(const ne of Me){const ye=[];for(const L of $e){const ue=this.tokenizer(ne,{text_pair:L,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 J=(Pe?ye.map(L=>(0,p.softmax)(L)[1]):(0,p.softmax)(ye)).map((L,ue)=>[L,ue]).sort((L,ue)=>ue[0]-L[0]);se.push({sequence:ne,labels:J.map(L=>je[L[1]]),scores:J.map(L=>L[0])})}return A?se:se[0]}}class de extends S{constructor(Me){super(Me)}async _call(Me,{pooling:je="none",normalize:Ye=!1,quantize:et=!1,precision:A="binary"}={}){const $e=this.tokenizer(Me,{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 Ce extends S{constructor(Me){super(Me)}async _call(Me,{pool:je=null}={}){const Ye=await C(Me),{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 te extends S{constructor(Me){super(Me)}async _call(Me,{top_k:je=5}={}){const Ye=this.processor.feature_extractor.config.sampling_rate,et=await T(Me,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],B=await(0,M.topk)(new M.Tensor("float32",(0,p.softmax)(ye.data),ye.dims),je),J=B[0].tolist(),ue=B[1].tolist().map((le,Te)=>({label:A?A[le]:`LABEL_${le}`,score:J[Te]}));$e.push(ue)}return Array.isArray(Me)?$e:$e[0]}}class _e extends S{constructor(Me){super(Me)}async _call(Me,je,{hypothesis_template:Ye="This is a sound of {}."}={}){const et=!Array.isArray(Me);et&&(Me=[Me]);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(Me,Pe),ne=[];for(const ye of se){const B=await this.processor(ye),J=await this.model({...$e,...B}),L=(0,p.softmax)(J.logits_per_audio.data);ne.push([...L].map((ue,le)=>({score:ue,label:je[le]})))}return et?ne[0]:ne}}class R extends S{constructor(Me){super(Me)}async _call(Me,je={}){switch(this.model.config.model_type){case"whisper":return this._call_whisper(Me,je);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":return this._call_wav2vec2(Me,je);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(Me,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(Me);Ye&&(Me=[Me]);const et=this.processor.feature_extractor.config.sampling_rate,A=await T(Me,et),$e=[];for(const Pe of A){const se=await this.processor(Pe),ye=(await this.model(se)).logits[0],B=[];for(const L of ye)B.push((0,p.max)(L.data)[1]);const J=this.tokenizer.decode(B);$e.push({text:J})}return Ye?$e[0]:$e}async _call_whisper(Me,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(Me);se&&(Me=[Me]);const ne=this.processor.feature_extractor.config.chunk_length/this.model.config.max_source_positions,ye=this.processor.feature_extractor.config.hop_length,B=this.processor.feature_extractor.config.sampling_rate,J=await T(Me,B),L=[];for(const ue of J){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=B*et,Je=B*$e,Ve=dt-2*Je;let Y=0;for(;;){const ve=Y+dt,Re=ue.subarray(Y,ve),qe=await this.processor(Re),Qe=Y===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;Y+=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,p.round)(Ve,2))):dt.tokens=Je[0].tolist(),dt.stride=dt.stride.map(Ve=>Ve/B)}const[Te,Ne]=this.tokenizer._decode_asr(le,{time_precision:ne,return_timestamps:Ye,force_full_sequences:A});L.push({text:Te,...Ne})}return se?L[0]:L}}class xe extends S{constructor(Me){super(Me)}async _call(Me,je={}){const Ye=Array.isArray(Me),et=await C(Me),{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}),ne=this.tokenizer.batch_decode(se,{skip_special_tokens:!0}).map(ye=>({generated_text:ye.trim()}));$e.push(ne)}return Ye?$e:$e[0]}}class Xe extends S{constructor(Me){super(Me)}async _call(Me,{top_k:je=5}={}){const Ye=await C(Me),{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 ne=await(0,M.topk)(new M.Tensor("float32",(0,p.softmax)(se.data),se.dims),je),ye=ne[0].tolist(),J=ne[1].tolist().map((L,ue)=>({label:$e?$e[L]:`LABEL_${L}`,score:ye[ue]}));Pe.push(J)}return Array.isArray(Me)?Pe:Pe[0]}}class ge extends S{constructor(Me){super(Me),this.subtasks_mapping={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"}}async _call(Me,{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(Me)&&Me.length!==1)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");const ne=await C(Me),ye=ne.map(Ne=>[Ne.height,Ne.width]),{pixel_values:B,pixel_mask:J}=await this.processor(ne),L=await this.model({pixel_values:B,pixel_mask:J});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,Te=[];if(Pe==="panoptic"||Pe==="instance"){const Ne=ue(L,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("{}",J)),Pe=this.tokenizer($e,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:se}=await this.processor(A),ne=await this.model({...Pe,pixel_values:se}),ye=this.model.config.model_type==="siglip"?J=>J.sigmoid().data:J=>(0,p.softmax)(J.data),B=[];for(const J of ne.logits_per_image){const ue=[...ye(J)].map((le,Te)=>({score:le,label:je[Te]}));ue.sort((le,Te)=>Te.score-le.score),B.push(ue)}return et?B:B[0]}}class ae extends S{constructor(Me){super(Me)}async _call(Me,{threshold:je=.9,percentage:Ye=!1}={}){const et=Array.isArray(Me);if(et&&Me.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");const A=await C(Me),$e=Ye?null:A.map(L=>[L.height,L.width]),{pixel_values:Pe,pixel_mask:se}=await this.processor(A),ne=await this.model({pixel_values:Pe,pixel_mask:se}),ye=this.processor.feature_extractor.post_process_object_detection(ne,je,$e),B=this.model.config.id2label,J=ye.map(L=>L.boxes.map((ue,le)=>({score:L.scores[le],label:B[L.classes[le]],box:z(ue,!Ye)})));return et?J:J[0]}}class Se extends S{constructor(Me){super(Me)}async _call(Me,je,{threshold:Ye=.1,top_k:et=null,percentage:A=!1}={}){const $e=Array.isArray(Me),Pe=await C(Me),se=this.tokenizer(je,{padding:!0,truncation:!0}),ne=await this.processor(Pe),ye=[];for(let B=0;B({score:Te.scores[Je],label:je[Te.classes[Je]],box:z(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(Me){super(Me)}async _call(Me,je,Ye={}){throw new Error("This pipeline is not yet supported in Transformers.js v3.")}}class me 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(Me){super(Me)}async _call(Me){const je=await C(Me),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(w.RawImage.fromTensor(Pe))}return A.length>1?A:A[0]}}class Le extends S{constructor(Me){super(Me)}async _call(Me){const je=await C(Me),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:E,model:a.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{tokenizer:o.AutoTokenizer,pipeline:y,model:a.AutoModelForTokenClassification,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{tokenizer:o.AutoTokenizer,pipeline: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:O,model:a.AutoModelForSeq2SeqLM,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{tokenizer:o.AutoTokenizer,pipeline:N,model:a.AutoModelForSeq2SeqLM,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{tokenizer:o.AutoTokenizer,pipeline:V,model:a.AutoModelForSeq2SeqLM,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{tokenizer:o.AutoTokenizer,pipeline:D,model:a.AutoModelForCausalLM,default:{model:"Xenova/gpt2"},type:"text"},"zero-shot-classification":{tokenizer:o.AutoTokenizer,pipeline:ee,model:a.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:te,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:R,model:[a.AutoModelForSpeechSeq2Seq,a.AutoModelForCTC],processor:l.AutoProcessor,default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{tokenizer:o.AutoTokenizer,pipeline:me,model:[a.AutoModelForTextToWaveform,a.AutoModelForTextToSpectrogram],processor:[l.AutoProcessor,null],default:{model:"Xenova/speecht5_tts"},type:"text"},"image-to-text":{tokenizer:o.AutoTokenizer,pipeline:xe,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:ge,model:[a.AutoModelForImageSegmentation,a.AutoModelForSemanticSegmentation],processor:l.AutoProcessor,default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"zero-shot-image-classification":{tokenizer:o.AutoTokenizer,pipeline:X,model:a.AutoModel,processor:l.AutoProcessor,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:ae,model:a.AutoModelForObjectDetection,processor:l.AutoProcessor,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{tokenizer:o.AutoTokenizer,pipeline:Se,model:a.AutoModelForZeroShotObjectDetection,processor:l.AutoProcessor,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{tokenizer:o.AutoTokenizer,pipeline: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:de,model:a.AutoModel,default:{model:"Xenova/all-MiniLM-L6-v2"},type:"text"},"image-feature-extraction":{processor:l.AutoProcessor,pipeline:Ce,model:[a.AutoModelForImageFeatureExtraction,a.AutoModel],default:{model:"Xenova/vit-base-patch16-224-in21k"},type:"image"}}),We=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});async function st(Ge,Me=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:ne=null,session_options:ye={}}={}){Ge=We[Ge]??Ge;const B=Be[Ge.split("_",1)[0]];if(!B)throw Error(`Unsupported pipeline: ${Ge}. Must be one of [${Object.keys(Be)}]`);Me||(Me=B.default.model,console.log(`No model specified. Using default model: "${Me}".`));const J={progress_callback:je,config:Ye,cache_dir:et,local_files_only:A,revision:$e,device:Pe,dtype:se,model_file_name:ne,session_options:ye},L=new Map([["tokenizer",B.tokenizer],["model",B.model],["processor",B.processor]]),ue=await ft(L,Me,J);ue.task=Ge,(0,_.dispatchCallback)(je,{status:"ready",task:Ge,model:Me});const le=B.pipeline;return new le(ue)}async function ft(Ge,Me,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,ne)=>{var B,J;let ye;for(let L of $e){if(L===null){se(null);return}try{se(await L.from_pretrained(Me,je));return}catch(ue){if((B=ue.message)!=null&&B.includes("Unsupported model type"))ye=ue;else if((J=ue.message)!=null&&J.includes("Could not locate file"))ye=ue;else{ne(ue);return}}}ne(ye)}):Pe=$e.from_pretrained(Me,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:()=>O,CLIPImageProcessor:()=>N,ChineseCLIPFeatureExtractor:()=>j,ClapFeatureExtractor:()=>Pe,ConvNextFeatureExtractor:()=>ee,ConvNextImageProcessor:()=>de,DPTFeatureExtractor:()=>y,DPTImageProcessor:()=>b,DeiTFeatureExtractor:()=>Ke,DetrFeatureExtractor:()=>st,DonutFeatureExtractor:()=>Be,EfficientNetImageProcessor:()=>_e,FeatureExtractor:()=>z,Florence2Processor:()=>dt,GLPNFeatureExtractor:()=>V,ImageFeatureExtractor:()=>S,MobileNetV1FeatureExtractor:()=>R,MobileNetV2FeatureExtractor:()=>xe,MobileNetV3FeatureExtractor:()=>Xe,MobileNetV4FeatureExtractor:()=>ge,MobileViTFeatureExtractor:()=>X,MobileViTImageProcessor:()=>ae,NougatImageProcessor:()=>We,OwlViTFeatureExtractor:()=>Se,OwlViTProcessor:()=>Ne,Owlv2ImageProcessor:()=>Q,Processor:()=>B,PyAnnoteFeatureExtractor:()=>se,PyAnnoteProcessor:()=>le,RTDetrImageProcessor:()=>me,SamImageProcessor:()=>Ge,SamProcessor:()=>J,SeamlessM4TFeatureExtractor:()=>A,SegformerFeatureExtractor:()=>E,SiglipImageProcessor:()=>D,SpeechT5FeatureExtractor:()=>ye,SpeechT5Processor:()=>Te,Swin2SRImageProcessor:()=>Me,ViTFeatureExtractor:()=>Ce,ViTImageProcessor:()=>te,VitMatteImageProcessor:()=>je,Wav2Vec2FeatureExtractor:()=>et,Wav2Vec2ProcessorWithLM:()=>ue,WeSpeakerFeatureExtractor:()=>ne,WhisperFeatureExtractor:()=>Ye,WhisperProcessor:()=>L,YolosFeatureExtractor:()=>ft});var o=r("./src/utils/generic.js"),a=r("./src/utils/core.js"),l=r("./src/utils/hub.js"),f=r("./src/utils/maths.js"),_=r("./src/utils/tensor.js");r("./src/utils/image.js");var p=r("./src/utils/audio.js");function g([Ve,Y,ve,Re]){return[Ve-ve/2,Y-Re/2,Ve+ve/2,Y+Re/2]}function M(Ve,Y=.5,ve=null,Re=!1){const qe=Ve.logits,Qe=Ve.pred_boxes,[tt,pt,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 vt=0;vtY&&Yt.push(Ht)}else{let Ht=(0,f.max)(Xt.data)[1];if(Ht===ht-1||(rr=(0,f.softmax)(Xt.data),rr[Ht]Yr*Et[(Pr+1)%2])),Lt.boxes.push(Cr),Lt.classes.push(Ht),Lt.scores.push(rr[Ht])}}Tt.push(Lt)}return Tt}function w(Ve,Y){var ve;if(!(Ve instanceof Float32Array||Ve instanceof Float64Array))throw new Error(`${Y} expects input to be a Float32Array or a Float64Array, but got ${((ve=Ve==null?void 0:Ve.constructor)==null?void 0:ve.name)??typeof Ve} instead. If using the feature extractor directly, remember to use \`read_audio(url, sampling_rate)\` to obtain the raw audio data of the file/url.`)}function C(Ve,Y,ve=0,Re=null){const qe=Ve/Y;let Qe=(0,f.bankers_round)(qe)*Y;return Re!==null&&Qe>Re&&(Qe=Math.floor(qe)*Y),QeQe?Tt=Math.floor(Qe*ht/qe):Qe>qe&&(ht=Math.floor(qe*Tt/Qe)),await Y.resize(Tt,ht,{resample:Re}))}async crop_margin(Y,ve=200){const Re=Y.clone().grayscale(),qe=(0,f.min)(Re.data)[0],tt=(0,f.max)(Re.data)[0]-qe;if(tt===0)return Y;const pt=ve/255;let ht=Re.width,Tt=Re.height,vt=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 E extends S{post_process_semantic_segmentation(Y,ve=null){const Re=Y.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 zt=new Array(ht.dims[0]),Vt=Et.data;for(let Yt=0;YtYt!==void 0);Qe.push({segmentation:Et,labels:Xt})}return Qe}}class y extends S{}class b extends y{}class I extends S{}class V extends S{}class O extends S{}class N extends O{}class j extends S{}class D extends S{}class ee extends S{constructor(Y){super(Y),this.crop_pct=this.config.crop_pct??224/256}async resize(Y){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(Y,{shortest_edge:qe});Y=await Y.resize(Qe,tt,{resample:this.resample}),Y=await Y.center_crop(ve,ve)}else Y=await Y.resize(ve,ve,{resample:this.resample});return Y}}class de extends ee{}class Ce extends S{}class te extends S{}class _e extends S{constructor(Y){super(Y),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map(ve=>ve*ve))}}class R extends S{}class xe extends S{}class Xe extends S{}class ge extends S{}class X extends S{}class ae extends X{}class Se extends S{post_process_object_detection(...Y){return M(...Y)}}class Q extends Se{}class me extends S{post_process_object_detection(...Y){return M(...Y)}}class Ke extends S{}class Le extends S{}class Be extends S{pad_image(Y,ve,Re,qe={}){const[Qe,tt,pt]=ve;let ht=this.image_mean;Array.isArray(this.image_mean)||(ht=new Array(pt).fill(ht));let Tt=this.image_std;Array.isArray(Tt)||(Tt=new Array(pt).fill(ht));const vt=ht.map((Et,Lt)=>-Et/Tt[Lt]);return super.pad_image(Y,ve,Re,{center:!0,constant_values:vt,...qe})}}class We extends Be{}class st extends S{async _call(Y){const ve=await super._call(Y),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(...Y){return M(...Y)}remove_low_and_no_objects(Y,ve,Re,qe){let Qe=[],tt=[],pt=[];for(let ht=0;htRe&&(Qe.push(vt),tt.push(at),pt.push(Et))}return[Qe,tt,pt]}check_segment_validity(Y,ve,Re,qe=.5,Qe=.8){let tt=[],pt=0,ht=0;const Tt=ve[Re].data;for(let Et=0;Et=qe&&++ht;let vt=pt>0&&ht>0;return vt&&(vt=pt/ht>Qe),[vt,tt]}compute_segments(Y,ve,Re,qe,Qe,tt=null,pt=null){let[ht,Tt]=pt??Y[0].dims,vt=new _.Tensor("int32",new Int32Array(ht*Tt),[ht,Tt]),Et=[];if(pt!==null)for(let Xt=0;Xtat[Ht]&&(Lt[Ht]=Xt,at[Ht]=rr[Ht])}let zt=0;const Vt=vt.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",Y.flat(1/0).map(BigInt),Re)}async _call(Y,{input_points:ve=null,input_labels:Re=null,input_boxes:qe=null}={}){const Qe=await super._call(Y);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(Y,ve,Re,{mask_threshold:qe=0,binarize:Qe=!0,pad_size:tt=null}={}){const pt=[];tt=tt??this.pad_size;const ht=[tt.height,tt.width];for(let Tt=0;Ttqe&&(zt[Vt]=1);Lt=new _.Tensor("bool",zt,Lt.dims)}pt.push(Lt)}return pt}generate_crop_boxes(Y,ve,{crop_n_layers:Re=0,overlap_ratio:qe=512/1500,points_per_crop:Qe=32,crop_n_points_downscale_factor:tt=1}={}){}}class Me extends S{pad_image(Y,ve,Re,qe={}){const[Qe,tt,pt]=ve;return super.pad_image(Y,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(Y,ve){Array.isArray(Y)||(Y=[Y]),Array.isArray(ve)||(ve=[ve]);const Re=await Promise.all(Y.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,pt)=>(0,_.cat)([tt.pixel_values,qe[pt].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 z{constructor(Y){var ve;super(Y),(ve=this.config).mel_filters??(ve.mel_filters=(0,p.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,p.window_function)(this.config.n_fft,"hann")}async _extract_fbank_features(Y){const ve=await(0,p.spectrogram)(Y,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,f.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=Y.slice(0,this.config.n_samples)):(ve=new Float32Array(this.config.n_samples),ve.set(Y)),{input_features:(await this._extract_fbank_features(ve)).unsqueeze_(0)}}}class et extends z{_zero_mean_unit_var_norm(Y){const Re=Y.reduce((Qe,tt)=>Qe+tt,0)/Y.length,qe=Y.reduce((Qe,tt)=>Qe+(tt-Re)**2,0)/Y.length;return Y.map(Qe=>(Qe-Re)/Math.sqrt(qe+1e-7))}async _call(Y){w(Y,"Wav2Vec2FeatureExtractor"),Y instanceof Float64Array&&(Y=new Float32Array(Y));let ve=Y;this.config.do_normalize&&(ve=this._zero_mean_unit_var_norm(ve));const Re=[1,ve.length];return{input_values:new _.Tensor("float32",ve,Re),attention_mask:new _.Tensor("int64",new BigInt64Array(ve.length).fill(1n),Re)}}}class A extends z{constructor(Y){super(Y);const ve=this.config.sampling_rate,Re=(0,p.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,p.spectrogram)(Y,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(Y,{padding:ve=!0,pad_to_multiple_of:Re=2,do_normalize_per_mel_bins:qe=!0,return_attention_mask:Qe=!0}={}){w(Y,"SeamlessM4TFeatureExtractor");let tt=await this._extract_fbank_features(Y,this.config.max_length);if(qe){const[zt,Vt]=tt.dims,Xt=tt.data;for(let Yt=0;Yt0){const rr=new Float32Array(Vt*(zt+Yt));rr.set(Xt),rr.fill(this.config.padding_value,Xt.length);const Ht=zt+Yt;tt=new _.Tensor(tt.type,rr,[Ht,Vt]),Qe&&(pt=new _.Tensor("int64",new BigInt64Array(Ht),[1,Ht]),pt.data.fill(1n,0,zt))}}const[ht,Tt]=tt.dims,vt=this.config.stride;if(ht%vt!==0)throw new Error(`The number of frames (${ht}) must be a multiple of the stride (${vt}).`);const Lt=tt.view(1,Math.floor(ht/vt),Tt*vt),at={input_features:Lt};if(Qe){const zt=Lt.dims[1],Vt=new BigInt64Array(zt);if(pt){const Xt=pt.data;for(let Yt=1,rr=0;Yt0)if(Re==="rand_trunc"){const pt=Math.floor(Math.random()*(tt+1));Y=Y.subarray(pt,pt+ve),Qe=await this._extract_fbank_features(Y,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${Re}" not implemented`);else{if(tt<0){let pt=new Float64Array(ve);if(pt.set(Y),qe==="repeat")for(let ht=Y.length;ht({id:ht,start:Tt*Re,end:vt*Re,confidence:Et/(vt-Tt)})))}return qe}}class ne extends z{constructor(Y){super(Y);const ve=this.config.sampling_rate,Re=(0,p.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,p.spectrogram)(Y,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(Y){w(Y,"WeSpeakerFeatureExtractor");const ve=(await this._extract_fbank_features(Y)).unsqueeze_(0);if(this.config.fbank_centering_span===null){const Re=ve.mean(1).data,qe=ve.data,[Qe,tt,pt]=ve.dims;for(let ht=0;ht/gm,bboxes:/([^<]+)?/gm},this.size_per_bin=1e3}construct_prompts(Y){typeof Y=="string"&&(Y=[Y]);const ve=[];for(const Re of Y)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!==Y.length&&ve.push(Re)}return ve}post_process_generation(Y,ve,Re){const qe=this.tasks_answer_post_processing_type.get(ve)??"pure_text";Y=Y.replaceAll("","").replaceAll("","");let Qe;switch(qe){case"pure_text":Qe=Y;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":const tt=qe==="ocr"?"quad_boxes":"bboxes",pt=Y.matchAll(this.regexes[tt]),ht=[],Tt=[];for(const[vt,Et,...Lt]of pt)ht.push(Et?Et.trim():ht.at(-1)??""),Tt.push(Lt.map((at,zt)=>(Number(at)+.5)/this.size_per_bin*Re[zt%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(Y,{progress_callback:ve=null,config:Re=null,cache_dir:qe=null,local_files_only:Qe=!1,revision:tt="main"}={}){let pt=Re??await(0,l.getModelJSON)(Y,"preprocessor_config.json",!0,{progress_callback:ve,config:Re,cache_dir:qe,local_files_only:Qe,revision:tt}),ht=pt.feature_extractor_type??pt.image_processor_type,Tt=this.FEATURE_EXTRACTOR_CLASS_MAPPING[ht];if(!Tt)if(pt.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 vt=this.PROCESSOR_CLASS_MAPPING[pt.processor_class]??B,Et=new Tt(pt);return new vt(Et)}}He(Je,"FEATURE_EXTRACTOR_CLASS_MAPPING",{ImageFeatureExtractor:S,WhisperFeatureExtractor:Ye,ViTFeatureExtractor:Ce,MobileViTFeatureExtractor:X,MobileViTImageProcessor:ae,MobileNetV1FeatureExtractor:R,MobileNetV2FeatureExtractor:xe,MobileNetV3FeatureExtractor:Xe,MobileNetV4FeatureExtractor:ge,OwlViTFeatureExtractor:Se,Owlv2ImageProcessor:Q,CLIPFeatureExtractor:O,CLIPImageProcessor:N,Florence2Processor:dt,ChineseCLIPFeatureExtractor:j,SiglipImageProcessor:D,ConvNextFeatureExtractor:ee,ConvNextImageProcessor:de,SegformerFeatureExtractor:E,BitImageProcessor:I,DPTImageProcessor:b,DPTFeatureExtractor:y,GLPNFeatureExtractor:V,BeitFeatureExtractor:Le,DeiTFeatureExtractor:Ke,DetrFeatureExtractor:st,RTDetrImageProcessor:me,YolosFeatureExtractor:ft,DonutFeatureExtractor:Be,NougatImageProcessor:We,EfficientNetImageProcessor:_e,ViTImageProcessor:te,VitMatteImageProcessor:je,SamImageProcessor:Ge,Swin2SRImageProcessor:Me,Wav2Vec2FeatureExtractor:et,SeamlessM4TFeatureExtractor:A,SpeechT5FeatureExtractor:ye,ASTFeatureExtractor:$e,ClapFeatureExtractor:Pe,PyAnnoteFeatureExtractor:se,WeSpeakerFeatureExtractor:ne}),He(Je,"PROCESSOR_CLASS_MAPPING",{WhisperProcessor:L,Wav2Vec2ProcessorWithLM:ue,PyAnnoteProcessor:le,SamProcessor:J,SpeechT5Processor:Te,OwlViTProcessor:Ne,Florence2Processor:dt})},"./src/tokenizers.js":(e,t,r)=>{r.r(t),r.d(t,{AlbertTokenizer:()=>Vt,AutoTokenizer:()=>Nn,BartTokenizer:()=>Wr,BertTokenizer:()=>zt,BlenderbotSmallTokenizer:()=>Vo,BlenderbotTokenizer:()=>go,BloomTokenizer:()=>Or,CLIPTokenizer:()=>Zt,CamembertTokenizer:()=>Pt,CodeGenTokenizer:()=>mo,CodeLlamaTokenizer:()=>Cs,CohereTokenizer:()=>Ur,ConvBertTokenizer:()=>Yr,DebertaTokenizer:()=>rr,DebertaV2Tokenizer:()=>Ht,DistilBertTokenizer:()=>mt,ElectraTokenizer:()=>un,EsmTokenizer:()=>ji,FalconTokenizer:()=>Bo,GPT2Tokenizer:()=>Mi,GPTNeoXTokenizer:()=>No,GemmaTokenizer:()=>po,Grok1Tokenizer:()=>pi,HerbertTokenizer:()=>Cr,LlamaTokenizer:()=>Ti,M2M100Tokenizer:()=>Ji,MBart50Tokenizer:()=>Kr,MBartTokenizer:()=>wn,MPNetTokenizer:()=>Ro,MarianTokenizer:()=>jo,MobileBertTokenizer:()=>Xt,NllbTokenizer:()=>Si,NougatTokenizer:()=>_o,PreTrainedTokenizer:()=>at,Qwen2Tokenizer:()=>Ps,RoFormerTokenizer:()=>Pr,RobertaTokenizer:()=>fi,SiglipTokenizer:()=>eo,SpeechT5Tokenizer:()=>Wo,SqueezeBertTokenizer:()=>Yt,T5Tokenizer:()=>Bi,TokenizerModel:()=>Ce,VitsTokenizer:()=>Go,Wav2Vec2CTCTokenizer:()=>Uo,WhisperTokenizer:()=>ho,XLMRobertaTokenizer:()=>Lo,XLMTokenizer:()=>Nt,is_chinese_char:()=>V});var o=r("./src/utils/generic.js"),a=r("./src/utils/core.js"),l=r("./src/utils/hub.js"),f=r("./src/utils/maths.js"),_=r("./src/utils/tensor.js"),p=r("./src/utils/data-structures.js"),g=r("./node_modules/@huggingface/jinja/dist/index.js"),M=r("./src/models/whisper/common_whisper.js"),w=r("./src/utils/constants.js");async function C(Ue,W){const fe=await Promise.all([(0,l.getModelJSON)(Ue,"tokenizer.json",!0,W),(0,l.getModelJSON)(Ue,"tokenizer_config.json",!0,W)]);return W.legacy!==null&&(fe[1].legacy=W.legacy),fe}function T(Ue,W){const fe=[];let Ee=0;for(const Fe of Ue.matchAll(W)){const ze=Fe[0];Ee0&&fe.push(ze),Ee=Fe.index+ze.length}return Ee=19968&&Ue<=40959||Ue>=13312&&Ue<=19903||Ue>=131072&&Ue<=173791||Ue>=173824&&Ue<=177983||Ue>=177984&&Ue<=178207||Ue>=178208&&Ue<=183983||Ue>=63744&&Ue<=64255||Ue>=194560&&Ue<=195103}function O(Ue,W,fe){const Ee=[];let Fe=0;for(;Fethis.tokens_to_ids.get(fe)??this.unk_token_id)}convert_ids_to_tokens(W){return W.map(fe=>this.vocab[fe]??this.unk_token)}}class te extends Ce{constructor(W){super(W),this.tokens_to_ids=S(W.vocab),this.unk_token_id=this.tokens_to_ids.get(W.unk_token),this.unk_token=W.unk_token,this.max_input_chars_per_word=W.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(const[fe,Ee]of this.tokens_to_ids)this.vocab[Ee]=fe}encode(W){const fe=[];for(const Ee of W){const Fe=[...Ee];if(Fe.length>this.max_input_chars_per_word){fe.push(this.unk_token);continue}let ze=!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){ze=!0;break}Mt.push(kt),rt=St}ze?fe.push(this.unk_token):fe.push(...Mt)}return fe}}class _e extends Ce{constructor(W,fe){super(W);const Ee=W.vocab.length;this.vocab=new Array(Ee),this.scores=new Array(Ee);for(let Fe=0;Fe[Fe,ze])),this.bosToken=" ",this.bosTokenId=this.tokens_to_ids.get(this.bosToken),this.eosToken=fe.eos_token,this.eosTokenId=this.tokens_to_ids.get(this.eosToken),this.unkToken=this.vocab[this.unk_token_id],this.minScore=(0,f.min)(this.scores)[0],this.unkScore=this.minScore-10,this.scores[this.unk_token_id]=this.unkScore,this.trie=new p.CharTrie,this.trie.extend(this.vocab),this.fuse_unk=!0}populateNodes(W){const fe=W.sentence,Ee=fe.length;let Fe=0;for(;Fe{const Ue=[...Array.from({length:94},(Fe,ze)=>ze+33),...Array.from({length:12},(Fe,ze)=>ze+161),...Array.from({length:82},(Fe,ze)=>ze+174)],W=Ue.slice();let fe=0;for(let Fe=0;Fe<256;++Fe)Ue.includes(Fe)||(Ue.push(Fe),W.push(256+fe),fe+=1);const Ee=W.map(Fe=>String.fromCharCode(Fe));return Object.fromEntries(Ue.map((Fe,ze)=>[Fe,Ee[ze]]))})(),xe=(0,a.reverseDictionary)(R);class Xe extends Ce{constructor(W){super(W),this.BPE_SPLIT_TOKEN=" ",this.tokens_to_ids=S(W.vocab),this.unk_token_id=this.tokens_to_ids.get(W.unk_token),this.unk_token=W.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(const[fe,Ee]of this.tokens_to_ids)this.vocab[Ee]=fe;this.bpe_ranks=new Map(W.merges.map((fe,Ee)=>[fe,Ee])),this.merges=W.merges.map(fe=>fe.split(this.BPE_SPLIT_TOKEN)),this.end_of_word_suffix=W.end_of_word_suffix,this.continuing_subword_suffix=W.continuing_subword_suffix??null,this.byte_fallback=this.config.byte_fallback??!1,this.byte_fallback&&(this.text_encoder=new TextEncoder),this.ignore_merges=this.config.ignore_merges??!1,this.cache=new Map}bpe(W){if(W.length===0)return[];const fe=this.cache.get(W);if(fe!==void 0)return fe;const Ee=Array.from(W);this.end_of_word_suffix&&(Ee[Ee.length-1]+=this.end_of_word_suffix);let Fe=[];if(Ee.length>1){const ze=new p.PriorityQueue((St,kt)=>St.score`<0x${rt.toString(16).toUpperCase().padStart(2,"0")}>`)):fe.push(this.unk_token)}return fe}}class ge extends Ce{constructor(W,fe){super(W),this.tokens_to_ids=S(fe.target_lang?W.vocab[fe.target_lang]:W.vocab),this.bos_token=fe.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=fe.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=fe.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=fe.unk_token,this.unk_token_id=this.tokens_to_ids.get(this.unk_token),this.vocab=new Array(this.tokens_to_ids.size);for(const[Ee,Fe]of this.tokens_to_ids)this.vocab[Fe]=Ee}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 ft(W);case"Precompiled":return new Qe(W);case"Sequence":return new st(W);case"Replace":return new ae(W);case"NFC":return new Se(W);case"NFKC":return new Q(W);case"NFKD":return new me(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 ae extends X{normalize(W){const fe=z(this.config.pattern);return fe===null?W:W.replaceAll(fe,this.config.content)}}class Se extends X{normalize(W){return W=W.normalize("NFC"),W}}class Q extends X{normalize(W){return W=W.normalize("NFKC"),W}}class me 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(fe=>X.fromConfig(fe))}normalize(W){return this.normalizers.reduce((fe,Ee)=>Ee.normalize(fe),W)}}class ft extends X{_tokenize_chinese_chars(W){const fe=[];for(let Ee=0;Eethis.pre_tokenize_text(Ee,fe)):this.pre_tokenize_text(W,fe)).flat()}_call(W,fe){return this.pre_tokenize(W,fe)}}class Me extends Ge{constructor(W){super(),this.pattern=new RegExp(`[^\\s${j}]+|[${j}]`,"gu")}pre_tokenize_text(W,fe){return W.trim().match(this.pattern)||[]}}class je extends Ge{constructor(W){super(),this.config=W,this.add_prefix_space=this.config.add_prefix_space,this.trim_offsets=this.config.trim_offsets,this.use_regex=this.config.use_regex??!0,this.pattern=new RegExp("'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)|\\s+","gu"),this.byte_encoder=R,this.text_encoder=new TextEncoder}pre_tokenize_text(W,fe){return this.add_prefix_space&&!W.startsWith(" ")&&(W=" "+W),(this.use_regex?W.match(this.pattern)||[]:[W]).map(Fe=>Array.from(this.text_encoder.encode(Fe),ze=>this.byte_encoder[ze]).join(""))}}class Ye extends Ge{constructor(W){super(),this.config=W,this.pattern=z(this.config.pattern,this.config.invert)}pre_tokenize_text(W,fe){return this.pattern===null?[]:this.config.invert?W.match(this.pattern)||[]: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,fe){return W.match(this.pattern)||[]}}class A extends Ge{constructor(W){super(),this.config=W;const fe=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(fe,"gu")}pre_tokenize_text(W,fe){return W.match(this.pattern)||[]}}class $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 ne(W);case"ByteLevel":return new ye(W);case"RobertaProcessing":return new se(W);case"BertProcessing":return new Pe(W);case"Sequence":return new B(W);default:throw new Error(`Unknown PostProcessor type: ${W.type}`)}}post_process(W,...fe){throw Error("post_process should be implemented in subclass.")}_call(W,...fe){return this.post_process(W,...fe)}}class Pe extends $e{constructor(W){super(W),this.cls=W.cls[0],this.sep=W.sep[0]}post_process(W,fe=null,{add_special_tokens:Ee=!0}={}){Ee&&(W=(0,a.mergeArrays)([this.cls],W,[this.sep]));let Fe=new Array(W.length).fill(0);if(fe!==null){const ze=Ee&&this instanceof se?[this.sep]:[],rt=Ee?[this.sep]:[];W=(0,a.mergeArrays)(W,ze,fe,rt),Fe=(0,a.mergeArrays)(Fe,new Array(fe.length+ze.length+rt.length).fill(1))}return{tokens:W,token_type_ids:Fe}}}class se extends Pe{}class ne extends $e{constructor(W){super(W),this.single=W.single,this.pair=W.pair}post_process(W,fe=null,{add_special_tokens:Ee=!0}={}){const Fe=fe===null?this.single:this.pair;let ze=[],rt=[];for(const Mt of Fe)"SpecialToken"in Mt?Ee&&(ze.push(Mt.SpecialToken.id),rt.push(Mt.SpecialToken.type_id)):"Sequence"in Mt&&(Mt.Sequence.id==="A"?(ze=(0,a.mergeArrays)(ze,W),rt=(0,a.mergeArrays)(rt,new Array(W.length).fill(Mt.Sequence.type_id))):Mt.Sequence.id==="B"&&(ze=(0,a.mergeArrays)(ze,fe),rt=(0,a.mergeArrays)(rt,new Array(fe.length).fill(Mt.Sequence.type_id))));return{tokens:ze,token_type_ids:rt}}}class ye extends $e{post_process(W,fe=null){return fe&&(W=(0,a.mergeArrays)(W,fe)),{tokens:W}}}class B extends $e{constructor(W){super(W),this.processors=W.processors.map(fe=>$e.fromConfig(fe))}post_process(W,fe=null,Ee={}){let Fe;for(const ze of this.processors)if(ze instanceof ye)W=ze.post_process(W).tokens,fe&&(fe=ze.post_process(fe).tokens);else{const rt=ze.post_process(W,fe,Ee);W=rt.tokens,Fe=rt.token_type_ids}return{tokens:W,token_type_ids:Fe}}}class J extends o.Callable{constructor(W){super(),this.config=W,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets=W.trim_offsets}static fromConfig(W){if(W===null)return null;switch(W.type){case"WordPiece":return new Ne(W);case"Metaspace":return new qe(W);case"ByteLevel":return new dt(W);case"Replace":return new L(W);case"ByteFallback":return new ue(W);case"Fuse":return new le(W);case"Strip":return new Te(W);case"Sequence":return new Ve(W);case"CTC":return new Je(W);case"BPEDecoder":return new Y(W);default:throw new Error(`Unknown Decoder type: ${W.type}`)}}_call(W){return this.decode(W)}decode(W){return this.decode_chain(W).join("")}decode_chain(W){throw Error("`decode_chain` should be implemented in subclass.")}}class L extends J{decode_chain(W){const fe=z(this.config.pattern);return fe===null?W:W.map(Ee=>Ee.replaceAll(fe,this.config.content))}}class ue extends J{constructor(W){super(W),this.text_decoder=new TextDecoder}decode_chain(W){const fe=[];let Ee=[];for(const Fe of W){let ze=null;if(Fe.length===6&&Fe.startsWith("<0x")&&Fe.endsWith(">")){const rt=parseInt(Fe.slice(3,5),16);isNaN(rt)||(ze=rt)}if(ze!==null)Ee.push(ze);else{if(Ee.length>0){const rt=this.text_decoder.decode(Uint8Array.from(Ee));fe.push(rt),Ee=[]}fe.push(Fe)}}if(Ee.length>0){const Fe=this.text_decoder.decode(Uint8Array.from(Ee));fe.push(Fe),Ee=[]}return fe}}class le extends J{decode_chain(W){return[W.join("")]}}class Te extends J{constructor(W){super(W),this.content=this.config.content,this.start=this.config.start,this.stop=this.config.stop}decode_chain(W){return W.map(fe=>{let Ee=0;for(let ze=0;ze(Ee!==0&&(fe.startsWith(this.config.prefix)?fe=fe.replace(this.config.prefix,""):fe=" "+fe),this.cleanup&&(fe=y(fe)),fe))}}class dt extends J{constructor(W){super(W),this.byte_decoder=xe,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(W){const fe=W.join(""),Ee=new Uint8Array([...fe].map(ze=>this.byte_decoder[ze]));return this.text_decoder.decode(Ee)}decode_chain(W){const fe=[];let Ee=[];for(const Fe of W)this.added_tokens.find(ze=>ze.content===Fe)!==void 0?(Ee.length>0&&(fe.push(this.convert_tokens_to_string(Ee)),Ee=[]),fe.push(Fe)):Ee.push(Fe);return Ee.length>0&&fe.push(this.convert_tokens_to_string(Ee)),fe}}class Je extends J{constructor(W){super(W),this.pad_token=this.config.pad_token,this.word_delimiter_token=this.config.word_delimiter_token,this.cleanup=this.config.cleanup}convert_tokens_to_string(W){if(W.length===0)return"";const fe=[W[0]];for(let ze=1;zeze!==this.pad_token).join("");return this.cleanup&&(Fe=y(Fe).replaceAll(this.word_delimiter_token," ").trim()),Fe}decode_chain(W){return[this.convert_tokens_to_string(W)]}}class Ve extends J{constructor(W){super(W),this.decoders=W.decoders.map(fe=>J.fromConfig(fe))}decode_chain(W){return this.decoders.reduce((fe,Ee)=>Ee.decode_chain(fe),W)}}class Y extends J{constructor(W){super(W),this.suffix=this.config.suffix}decode_chain(W){return W.map((fe,Ee)=>fe.replaceAll(this.suffix,Ee===W.length-1?"":" "))}}class ve extends J{decode_chain(W){let fe="";for(let Ee=1;EeEe.normalize("NFKC")).join("~"):W=W.normalize("NFKC"),W}}class tt extends Ge{constructor(W){super(),this.tokenizers=W.pretokenizers.map(fe=>Ge.fromConfig(fe))}pre_tokenize_text(W,fe){return this.tokenizers.reduce((Ee,Fe)=>Fe.pre_tokenize(Ee,fe),[W])}}class pt extends Ge{constructor(W){super()}pre_tokenize_text(W,fe){return W.match(/\w+|[^\w\s]+/g)||[]}}class ht extends Ge{constructor(W){super()}pre_tokenize_text(W,fe){return N(W)}}class Tt extends Ge{constructor(W){super(),this.config=W,this.pattern=z(this.config.pattern),this.content=this.config.content}pre_tokenize_text(W,fe){return this.pattern===null?[W]:[W.replaceAll(this.pattern,this.config.content)]}}const vt=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function Et(Ue,W,fe,Ee){for(const Fe of Object.keys(Ue)){const ze=W-Ue[Fe].length,rt=fe(Fe),Mt=new Array(ze).fill(rt);Ue[Fe]=Ee==="right"?(0,a.mergeArrays)(Ue[Fe],Mt):(0,a.mergeArrays)(Mt,Ue[Fe])}}function Lt(Ue,W){for(const fe of Object.keys(Ue))Ue[fe].length=W}class at extends o.Callable{constructor(fe,Ee){super();He(this,"return_token_type_ids",!1);He(this,"padding_side","right");this._tokenizer_config=Ee,this.normalizer=X.fromConfig(fe.normalizer),this.pre_tokenizer=Ge.fromConfig(fe.pre_tokenizer),this.model=Ce.fromConfig(fe.model,Ee),this.post_processor=$e.fromConfig(fe.post_processor),this.decoder=J.fromConfig(fe.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];for(const Fe of fe.added_tokens){const ze=new de(Fe);this.added_tokens.push(ze),this.model.tokens_to_ids.set(ze.content,ze.id),this.model.vocab[ze.id]=ze.content,ze.special&&(this.special_tokens.push(ze.content),this.all_special_ids.push(ze.id))}if(this.additional_special_tokens=Ee.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,ze)=>ze.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=Ee.model_max_length,this.remove_space=Ee.remove_space,this.clean_up_tokenization_spaces=Ee.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=Ee.do_lowercase_and_remove_accent??!1,Ee.padding_side&&(this.padding_side=Ee.padding_side),this.legacy=!1,this.chat_template=Ee.chat_template??null,Array.isArray(this.chat_template)){const Fe=Object.create(null);for(const{name:ze,template:rt}of this.chat_template){if(typeof ze!="string"||typeof rt!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');Fe[ze]=rt}this.chat_template=Fe}this._compiled_template_cache=new Map}getToken(...fe){for(const Ee of fe){const Fe=this._tokenizer_config[Ee];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(fe,{progress_callback:Ee=null,config:Fe=null,cache_dir:ze=null,local_files_only:rt=!1,revision:Mt="main",legacy:St=null}={}){const kt=await C(fe,{progress_callback:Ee,config:Fe,cache_dir:ze,local_files_only:rt,revision:Mt,legacy:St});return new this(...kt)}_call(fe,{text_pair:Ee=null,add_special_tokens:Fe=!0,padding:ze=!1,truncation:rt=null,max_length:Mt=null,return_tensor:St=!0,return_token_type_ids:kt=null}={}){const It=Array.isArray(fe);let tr;if(It){if(fe.length===0)throw Error("text array must be non-empty");if(Ee!==null){if(Array.isArray(Ee)){if(fe.length!==Ee.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");tr=fe.map((sr,qt)=>this._encode_plus(sr,{text_pair:Ee[qt],add_special_tokens:Fe,return_token_type_ids:kt}))}else tr=fe.map(sr=>this._encode_plus(sr,{add_special_tokens:Fe,return_token_type_ids:kt}))}else{if(fe==null)throw Error("text may not be null or undefined");if(Array.isArray(Ee))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(fe,{text_pair:Ee,add_special_tokens:Fe,return_token_type_ids:kt})]}if(Mt===null?ze==="max_length"?Mt=this.model_max_length:Mt=(0,f.max)(tr.map(sr=>sr.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),ze||rt)for(let sr=0;srMt?rt&&Lt(tr[sr],Mt):ze&&Et(tr[sr],Mt,qt=>qt==="input_ids"?this.pad_token_id:0,this.padding_side));const $r={};if(St){if(!(ze&&rt)&&tr.some(qt=>{var gr;for(const Cn of Object.keys(qt))if(qt[Cn].length!==((gr=tr[0][Cn])==null?void 0:gr.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 sr=[tr.length,tr[0].input_ids.length];for(const qt of Object.keys(tr[0]))$r[qt]=new _.Tensor("int64",BigInt64Array.from(tr.flatMap(gr=>gr[qt]).map(BigInt)),sr)}else{for(const sr of Object.keys(tr[0]))$r[sr]=tr.map(qt=>qt[sr]);if(!It)for(const sr of Object.keys($r))$r[sr]=$r[sr][0]}return $r}_encode_text(fe){return fe===null?null:(this.added_tokens_regex?fe.split(this.added_tokens_regex).filter(ze=>ze):[fe]).map((ze,rt)=>{if(this.added_tokens.find(St=>St.content===ze)!==void 0)return ze;{if(this.remove_space===!0&&(ze=ze.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(ze=I(ze)),this.normalizer!==null&&(ze=this.normalizer(ze)),ze.length===0)return[];const St=this.pre_tokenizer!==null?this.pre_tokenizer(ze,{section_index:rt}):[ze];return this.model(St)}}).flat()}_encode_plus(fe,{text_pair:Ee=null,add_special_tokens:Fe=!0,return_token_type_ids:ze=null}={}){const{tokens:rt,token_type_ids:Mt}=this._tokenize_helper(fe,{pair:Ee,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(ze??this.return_token_type_ids)&&Mt&&(kt.token_type_ids=Mt),kt}_tokenize_helper(fe,{pair:Ee=null,add_special_tokens:Fe=!1}={}){const ze=this._encode_text(fe),rt=this._encode_text(Ee);return this.post_processor?this.post_processor(ze,rt,{add_special_tokens:Fe}):{tokens:(0,a.mergeArrays)(ze??[],rt??[])}}tokenize(fe,{pair:Ee=null,add_special_tokens:Fe=!1}={}){return this._tokenize_helper(fe,{pair:Ee,add_special_tokens:Fe}).tokens}encode(fe,{text_pair:Ee=null,add_special_tokens:Fe=!0,return_token_type_ids:ze=null}={}){return this._encode_plus(fe,{text_pair:Ee,add_special_tokens:Fe,return_token_type_ids:ze}).input_ids}batch_decode(fe,Ee={}){return fe instanceof _.Tensor&&(fe=fe.tolist()),fe.map(Fe=>this.decode(Fe,Ee))}decode(fe,Ee={}){if(fe instanceof _.Tensor&&(fe=E(fe)),!Array.isArray(fe)||fe.length===0||!(0,a.isIntegralNumber)(fe[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(fe,Ee)}decode_single(fe,{skip_special_tokens:Ee=!1,clean_up_tokenization_spaces:Fe=null}){let ze=this.model.convert_ids_to_tokens(fe);Ee&&(ze=ze.filter(Mt=>!this.special_tokens.includes(Mt)));let rt=this.decoder?this.decoder(ze):ze.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(rt=rt.replaceAll(this.decoder.end_of_word_suffix," "),Ee&&(rt=rt.trim())),(Fe??this.clean_up_tokenization_spaces)&&(rt=y(rt)),rt}apply_chat_template(fe,{tools:Ee=null,documents:Fe=null,chat_template:ze=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:$r=!1,tokenizer_kwargs:sr={},...qt}={}){if(this.chat_template&&typeof this.chat_template=="object"||this.chat_template===null){const ct=this.chat_template;if(ze!==null&&Object.hasOwn(ct,ze))ze=ct[ze];else if(ze===null&&"default"in ct)ze=ct.default;else if(ze===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)ze=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 ze!="string")throw Error(`chat_template must be a string, but got ${typeof ze}`);let gr=this._compiled_template_cache.get(ze);gr===void 0&&(gr=new g.Template(ze),this._compiled_template_cache.set(ze,gr));const Cn=Object.create(null);for(const ct of vt){const Kn=this.getToken(ct);Kn&&(Cn[ct]=Kn)}const gn=gr.render({messages:fe,add_generation_prompt:rt,tools:Ee,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,...sr});return $r?ct:ct.input_ids}return gn}}class zt extends at{constructor(){super(...arguments);He(this,"return_token_type_ids",!0)}}class Vt 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 Cr 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 Pr extends at{constructor(){super(...arguments);He(this,"return_token_type_ids",!0)}}class mt extends at{}class Pt extends at{}class Nt extends at{constructor(fe,Ee){super(fe,Ee);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 Wr extends at{}class wn extends at{constructor(W,fe){super(W,fe),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.special_tokens.filter(Ee=>this.languageRegex.test(Ee)),this.lang_to_token=Ee=>Ee}_build_translation_inputs(W,fe,Ee){return ki(this,W,fe,Ee)}}class Kr extends wn{}class fi extends at{}class Or extends at{constructor(W,fe){var ze,rt;const Ee=".,!?…。,、।۔،",Fe=(rt=(ze=W.pre_tokenizer)==null?void 0:ze.pretokenizers[0])==null?void 0:rt.pattern;Fe&&Fe.Regex===` ?[^(\\s|[${Ee}])]+`&&(Fe.Regex=` ?[^\\s${Ee}]+`),super(W,fe)}}const Ni="▁";class Ti extends at{constructor(fe,Ee){super(fe,Ee);He(this,"padding_side","left");this.legacy=Ee.legacy??!0,this.legacy||(this.normalizer=null,this.pre_tokenizer=new Re({replacement:Ni,add_prefix_space:!0,prepend_scheme:"first"}))}_encode_text(fe){if(fe===null)return null;if(this.legacy||fe.length===0)return super._encode_text(fe);let Ee=super._encode_text(Ni+fe.replaceAll(Ni," "));return Ee.length>1&&Ee[0]===Ni&&this.special_tokens.includes(Ee[1])&&(Ee=Ee.slice(1)),Ee}}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 po extends at{}class pi extends at{}function ki(Ue,W,fe,Ee){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=Ee.src_lang,ze=Ee.tgt_lang;if(!Ue.language_codes.includes(ze))throw new Error(`Target language code "${ze}" 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 Ee.forced_bos_token_id=Ue.model.convert_tokens_to_ids([Ue.lang_to_token(ze)])[0],Ue._call(W,fe)}class Si extends at{constructor(W,fe){super(W,fe),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.special_tokens.filter(Ee=>this.languageRegex.test(Ee)),this.lang_to_token=Ee=>Ee}_build_translation_inputs(W,fe,Ee){return ki(this,W,fe,Ee)}}class Ji extends at{constructor(W,fe){super(W,fe),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.special_tokens.filter(Ee=>this.languageRegex.test(Ee)).map(Ee=>Ee.slice(2,-2)),this.lang_to_token=Ee=>`__${Ee}__`}_build_translation_inputs(W,fe,Ee){return ki(this,W,fe,Ee)}}class ho extends at{get timestamp_begin(){return this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0]+1}_decode_asr(W,{return_timestamps:fe=!1,return_language:Ee=!1,time_precision:Fe=null,force_full_sequences:ze=!0}={}){if(Fe===null)throw Error("Must specify time_precision");let rt=null;const Mt=fe==="word";function St(){return{language:rt,timestamp:[null,null],text:""}}const kt=[];let It=St(),tr=0;const $r=this.timestamp_begin;let sr=[],qt=[],gr=!1,Cn=null;const gn=new Set(this.all_special_ids);for(const br of W){const cn=br.tokens,Fn=Mt?br.token_timestamps:null;let Jt=null,jn=$r;if("stride"in br){const[kr,$t,wr]=br.stride;if(tr-=$t,Cn=kr-wr,$t&&(jn=$t/Fe+$r),wr)for(let Dr=cn.length-1;Dr>=0;--Dr){const Xr=Number(cn[Dr]);if(Xr>=$r){if(Jt!==null&&(Xr-$r)*Fe=$r){const wr=($t-$r)*Fe+tr,Dr=(0,f.round)(wr,2);if(Jt!==null&&$t>=Jt)gr=!0;else if(gr||sr.length>0&&$t0?(sr.push(yn),Mt&&qt.push(Tr)):sr.every(kr=>kr.length===0)&&(It=St(),sr=[],yn=[],qt=[],Tr=[])}if(sr.length>0){if(ze&&fe)throw new Error("Whisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. Also make sure WhisperTimeStampLogitsProcessor was used during generation.");const[br,cn]=this.findLongestCommonSequence(sr,qt),Fn=this.decode(br);It.text=Fn,Mt&&(It.words=this.collateWordTimestamps(br,cn,rt)),kt.push(It)}let ct=Object.create(null);const Kn=kt.map(br=>br.text).join("");if(fe||Ee){for(let br=0;br0;let Mt=rt?[]:null,St=rt?fe[0]:null;for(let kt=1;ktDr===Tr[Xr]&&St[cn+Xr]<=fe[kt][jn+Xr]).length:kr=Jt.filter((Dr,Xr)=>Dr===Tr[Xr]).length;const $t=br/1e4,wr=kr/br+$t;kr>1&&wr>tr&&(tr=wr,$r=[cn,Fn,jn,yn])}const[qt,gr,Cn,gn]=$r,ct=Math.floor((gr+qt)/2),Kn=Math.floor((gn+Cn)/2);ze.push(...Ee.slice(0,ct)),Ee=It.slice(Kn),Fe=Ee.length,rt&&(Mt.push(...St.slice(0,ct)),St=fe[kt].slice(Kn))}return ze.push(...Ee),rt?(Mt.push(...St),[ze,Mt]):[ze,[]]}collateWordTimestamps(W,fe,Ee){const[Fe,ze,rt]=this.combineTokensIntoWords(W,Ee),Mt=[];for(let St=0;St=Fe){const Mt=((rt-Fe)*Ee).toFixed(2);ze.push(`<|${Mt}|>`),ze.push([])}else ze[ze.length-1].push(rt);return ze=ze.map(rt=>typeof rt=="string"?rt:super.decode(rt,fe)),ze.join("")}splitTokensOnUnicode(W){const fe=this.decode(W,{decode_with_timestamps:!0}),Ee="�",Fe=[],ze=[],rt=[];let Mt=[],St=[],kt=0;for(let It=0;It=this.model.tokens_to_ids.get("<|endoftext|>"),qt=It.startsWith(" "),gr=It.trim(),Cn=St.test(gr);if(sr||qt||Cn||ze.length===0)ze.push(It),rt.push(tr),Mt.push($r);else{const gn=ze.length-1;ze[gn]+=It,rt[gn].push(...tr),Mt[gn].push(...$r)}}return[ze,rt,Mt]}mergePunctuations(W,fe,Ee,Fe,ze){const rt=structuredClone(W),Mt=structuredClone(fe),St=structuredClone(Ee);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:fe=null,no_timestamps:Ee=!0}={}){const Fe=[];if(W){const ze=(0,M.whisper_language_to_code)(W),rt=this.model.tokens_to_ids.get(`<|${ze}|>`);if(rt===void 0)throw new Error(`Unable to find language "${ze}" in model vocabulary. Please report this issue at ${w.GITHUB_ISSUE_URL}.`);Fe.push(rt)}else Fe.push(null);if(fe){if(fe=fe.toLowerCase(),fe!=="transcribe"&&fe!=="translate")throw new Error(`Task "${fe}" is not supported. Must be one of: ["transcribe", "translate"]`);const ze=this.model.tokens_to_ids.get(`<|${fe}|>`);if(ze===void 0)throw new Error(`Unable to find task "${fe}" in model vocabulary. Please report this issue at ${w.GITHUB_ISSUE_URL}.`);Fe.push(ze)}else Fe.push(null);if(Ee){const ze=this.model.tokens_to_ids.get("<|notimestamps|>");if(ze===void 0)throw new Error(`Unable to find "<|notimestamps|>" in model vocabulary. Please report this issue at ${w.GITHUB_ISSUE_URL}.`);Fe.push(ze)}return Fe.map((ze,rt)=>[rt+1,ze]).filter(ze=>ze[1]!==null)}}class mo extends at{}class Zt extends at{}class eo extends at{}class jo extends at{constructor(W,fe){super(W,fe),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=this.model.vocab.filter(Ee=>this.languageRegex.test(Ee)),console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(W){if(W===null)return null;const[fe,...Ee]=W.trim().split(this.languageRegex);if(Ee.length===0)return super._encode_text(fe);if(Ee.length===2){const[Fe,ze]=Ee;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(ze))}}}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,fe){super(W,fe),this.decoder=new ve({})}}class Ur extends at{}class Nn{static async from_pretrained(W,{progress_callback:fe=null,config:Ee=null,cache_dir:Fe=null,local_files_only:ze=!1,revision:rt="main",legacy:Mt=null}={}){var $r;const[St,kt]=await C(W,{progress_callback:fe,config:Ee,cache_dir:Fe,local_files_only:ze,revision:rt,legacy:Mt}),It=(($r=kt.tokenizer_class)==null?void 0:$r.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(Nn,"TOKENIZER_CLASS_MAPPING",{T5Tokenizer:Bi,DistilBertTokenizer:mt,CamembertTokenizer:Pt,DebertaTokenizer:rr,DebertaV2Tokenizer:Ht,BertTokenizer:zt,HerbertTokenizer:Cr,ConvBertTokenizer:Yr,RoFormerTokenizer:Pr,XLMTokenizer:Nt,ElectraTokenizer:un,MobileBertTokenizer:Xt,SqueezeBertTokenizer:Yt,AlbertTokenizer:Vt,GPT2Tokenizer:Mi,BartTokenizer:Wr,MBartTokenizer:wn,MBart50Tokenizer:Kr,RobertaTokenizer:fi,WhisperTokenizer:ho,CodeGenTokenizer:mo,CLIPTokenizer:Zt,SiglipTokenizer:eo,MarianTokenizer:jo,BloomTokenizer:Or,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:po,Grok1Tokenizer:pi,CohereTokenizer:Ur,PreTrainedTokenizer:at})},"./src/utils/audio.js":(e,t,r)=>{r.r(t),r.d(t,{hamming:()=>M,hanning:()=>g,mel_filter_bank:()=>y,read_audio:()=>_,spectrogram:()=>N,window_function:()=>j});var o=r("./src/utils/hub.js"),a=r("./src/utils/maths.js"),l=r("./src/utils/core.js"),f=r("./src/utils/tensor.js");async function _(D,ee){if(typeof AudioContext>"u")throw Error("Unable to load audio from path/URL since `AudioContext` is not available in your environment. Instead, audio data should be passed directly to the pipeline/processor. For more information and some example code, see https://huggingface.co/docs/transformers.js/guides/node-audio-processing.");const de=await(await(0,o.getFile)(D)).arrayBuffer(),Ce=new AudioContext({sampleRate:ee});typeof ee>"u"&&console.warn(`No sampling rate provided, using default of ${Ce.sampleRate}Hz.`);const te=await Ce.decodeAudioData(de);let _e;if(te.numberOfChannels===2){const R=Math.sqrt(2),xe=te.getChannelData(0),Xe=te.getChannelData(1);_e=new Float32Array(xe.length);for(let ge=0;ge2595*Math.log10(1+D/700),kaldi:D=>1127*Math.log(1+D/700),slaney:(D,ee=1e3,de=15,Ce=27/Math.log(6.4))=>D>=ee?de+Math.log(D/ee)*Ce:3*D/200};function C(D,ee="htk"){const de=w[ee];if(!de)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof D=="number"?de(D):D.map(Ce=>de(Ce))}const T={htk:D=>700*(10**(D/2595)-1),kaldi:D=>700*(Math.exp(D/1127)-1),slaney:(D,ee=1e3,de=15,Ce=Math.log(6.4)/27)=>D>=de?ee*Math.exp(Ce*(D-de)):200*D/3};function z(D,ee="htk"){const de=T[ee];if(!de)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof D=="number"?de(D):D.map(Ce=>de(Ce))}function S(D,ee){const de=Float64Array.from({length:ee.length-1},(R,xe)=>ee[xe+1]-ee[xe]),Ce=Array.from({length:D.length},()=>new Array(ee.length));for(let R=0;Rnew Array(D.length));for(let R=0;RD+Ce*_e)}function y(D,ee,de,Ce,te,_e=null,R="htk",xe=!1){if(_e!==null&&_e!=="slaney")throw new Error('norm must be one of null or "slaney"');const Xe=C(de,R),ge=C(Ce,R),X=E(Xe,ge,ee+2);let ae=z(X,R),Se;if(xe){const me=te/(D*2);Se=C(Float64Array.from({length:D},(Ke,Le)=>Le*me),R),ae=X}else Se=E(0,Math.floor(te/2),D);const Q=S(Se,ae);if(_e!==null&&_e==="slaney")for(let me=0;mete)throw Error(`frame_length (${de}) may not be larger than fft_length (${te})`);if(Ge!==de)throw new Error(`Length of the window (${Ge}) must equal frame_length (${de})`);if(Ce<=0)throw new Error("hop_length must be greater than zero");if(_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(R){if(xe!=="reflect")throw new Error(`pad_mode="${xe}" not implemented yet.`);const J=Math.floor((te-1)/2)+1;D=b(D,J,J)}let Me=Math.floor(1+Math.floor((D.length-de)/Ce));Be!==null&&MeMe?st&&(et=We):et=Ye=We);const A=new a.FFT(te),$e=new Float64Array(te),Pe=new Float64Array(A.outputBufferSize),se=new Float32Array(je*et);for(let J=0;J=1;--le)$e[le]-=ge*$e[le-1];$e[0]*=1-ge}for(let le=0;leMath.pow(xe,.85));break;default:throw new Error(`Unknown window type ${ee}.`)}if(de&&(R=R.subarray(0,D)),Ce===null)return R;if(D>Ce)throw new Error(`Length of the window (${D}) may not be larger than frame_length (${Ce})`);return R}},"./src/utils/constants.js":(e,t,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:()=>p,calculateReflectOffset:()=>C,dispatchCallback:()=>o,escapeRegExp:()=>l,isIntegralNumber:()=>_,isTypedArray:()=>f,mergeArrays:()=>M,pick:()=>T,pop:()=>g,product:()=>w,reverseDictionary:()=>a});function o(z,S){z&&z(S)}function a(z){return Object.fromEntries(Object.entries(z).map(([S,E])=>[E,S]))}function l(z){return z.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function f(z){var S,E,y;return((y=(E=(S=z==null?void 0:z.prototype)==null?void 0:S.__proto__)==null?void 0:E.constructor)==null?void 0:y.name)==="TypedArray"}function _(z){return Number.isInteger(z)||typeof z=="bigint"}function p(z){const S=[];let E=z;for(;Array.isArray(E);)S.push(E.length),E=E[0];return S}function g(z,S,E=void 0){const y=z[S];if(y!==void 0)return delete z[S],y;if(E===void 0)throw Error(`Key ${S} does not exist in object.`);return E}function M(...z){return Array.prototype.concat.apply([],z)}function w(...z){return z.reduce((S,E)=>S.flatMap(y=>E.map(b=>[y,b])))}function C(z,S){return Math.abs((z+S)%(2*S)-S)}function T(z,S){return Object.assign({},...S.map(E=>{if(z[E]!==void 0)return{[E]:z[E]}}))}},"./src/utils/data-structures.js":(e,t,r)=>{r.r(t),r.d(t,{CharTrie:()=>a,PriorityQueue:()=>o,TokenLattice:()=>f});class o{constructor(g=(w,C)=>w>C,M=1/0){this._heap=[],this._comparator=g,this._maxSize=M}get size(){return this._heap.length}isEmpty(){return this.size===0}peek(){return this._heap[0]}push(...g){return this.extend(g)}extend(g){for(const M of g)if(this.size0&&this._swap(0,M),this._heap.pop(),this._siftDown(),g}replace(g){const M=this.peek();return this._heap[0]=g,this._siftDown(),M}_parent(g){return(g+1>>>1)-1}_left(g){return(g<<1)+1}_right(g){return g+1<<1}_greater(g,M){return this._comparator(this._heap[g],this._heap[M])}_swap(g,M){const w=this._heap[g];this._heap[g]=this._heap[M],this._heap[M]=w}_siftUp(){this._siftUpFrom(this.size-1)}_siftUpFrom(g){for(;g>0&&this._greater(g,this._parent(g));)this._swap(g,this._parent(g)),g=this._parent(g)}_siftDown(){let g=0;for(;this._left(g)[]),this.endNodes=Array.from({length:this.len+1},()=>[]);const C=new _(this.bosTokenId,0,0,0,0),T=new _(this.eosTokenId,1,this.len,0,0);this.nodes.push(C.clone()),this.nodes.push(T.clone()),this.beginNodes[this.len].push(T),this.endNodes[0].push(C)}insert(g,M,w,C){const T=this.nodes.length,z=new _(C,T,g,M,w);this.beginNodes[g].push(z),this.endNodes[g+M].push(z),this.nodes.push(z)}viterbi(){const g=this.len;let M=0;for(;M<=g;){if(this.beginNodes[M].length==0)return[];for(let S of this.beginNodes[M]){S.prev=null;let E=0,y=null;for(let b of this.endNodes[M]){const I=b.backtraceScore+S.score;(y===null||I>E)&&(y=b.clone(),E=I)}if(y!==null)S.prev=y,S.backtraceScore=E;else return[]}++M}const w=[],T=this.beginNodes[g][0].prev;if(T===null)return[];let z=T.clone();for(;z.prev!==null;)w.push(z.clone()),z=z.clone().prev.clone();return w.reverse(),w}piece(g){return this.sentence.slice(g.pos,g.pos+g.length)}tokens(){return this.viterbi().map(M=>this.piece(M))}tokenIds(){return this.viterbi().map(M=>M.tokenId)}}class _{constructor(g,M,w,C,T){this.tokenId=g,this.nodeId=M,this.pos=w,this.length=C,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({cpu:"cpu",gpu:"gpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml"})},"./src/utils/dtypes.js":(e,t,r)=>{r.r(t),r.d(t,{DATA_TYPES:()=>f,DEFAULT_DEVICE_DTYPE_MAPPING:()=>_,DEFAULT_DTYPE_SUFFIX_MAPPING:()=>p,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}}(),f=Object.freeze({fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16"}),_=Object.freeze({[a.DEVICE_TYPES.cpu]:f.q8,[a.DEVICE_TYPES.gpu]:f.fp32,[a.DEVICE_TYPES.wasm]:f.q8,[a.DEVICE_TYPES.webgpu]:f.fp32,[a.DEVICE_TYPES.cuda]:f.fp32,[a.DEVICE_TYPES.dml]:f.fp32}),p=Object.freeze({[f.fp32]:"",[f.fp16]:"_fp16",[f.int8]:"_int8",[f.uint8]:"_uint8",[f.q8]:"_quantized",[f.q4]:"_q4",[f.q4f16]:"_q4f16",[f.bnb4]:"_bnb4"})},"./src/utils/generic.js":(e,t,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:()=>E});var o=r("?7a2c"),a=r("?a42a"),l=r("./src/env.js"),f=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 p{constructor(V){if(this.filePath=V,this.headers=new Headers,this.exists=o.existsSync(V),this.exists){this.status=200,this.statusText="OK";let O=o.statSync(V);this.headers.set("content-length",O.size.toString()),this.updateContentType();let N=this;this.body=new ReadableStream({start(j){N.arrayBuffer().then(D=>{j.enqueue(new Uint8Array(D)),j.close()})}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){const V=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",_[V]??"application/octet-stream")}clone(){let V=new p(this.filePath);return V.exists=this.exists,V.status=this.status,V.statusText=this.statusText,V.headers=new Headers(this.headers),V}async arrayBuffer(){return(await o.promises.readFile(this.filePath)).buffer}async blob(){const V=await o.promises.readFile(this.filePath);return new Blob([V],{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,V=null,O=null){let N;try{N=new URL(I)}catch{return!1}return!(V&&!V.includes(N.protocol)||O&&!O.includes(N.hostname))}async function M(I){var V;if(l.env.useFS&&!g(I,["http:","https:","blob:"]))return new p(I);if(typeof process<"u"&&((V=process==null?void 0:process.release)==null?void 0:V.name)==="node"){const O=!!(ko!=null&&ko.TESTING_REMOTELY),N=l.env.version,j=new Headers;if(j.set("User-Agent",`transformers.js/${N}; is_ci/${O};`),g(I,["http:","https:"],["huggingface.co","hf.co"])){const ee=(ko==null?void 0:ko.HF_TOKEN)??(ko==null?void 0:ko.HF_ACCESS_TOKEN);ee&&j.set("Authorization",`Bearer ${ee}`)}return fetch(I,{headers:j})}else return fetch(I)}const w={400:"Bad request error occurred while trying to load file",401:"Unauthorized access to file",403:"Forbidden access to file",404:"Could not locate file",408:"Request timeout error occurred while trying to load file",500:"Internal server error error occurred while trying to load file",502:"Bad gateway error occurred while trying to load file",503:"Service unavailable error occurred while trying to load file",504:"Gateway timeout error occurred while trying to load file"};function C(I,V,O){if(!O)return null;const N=w[I]??`Error (${I}) occurred while trying to load file`;throw Error(`${N}: "${V}".`)}class T{constructor(V){this.path=V}async match(V){let O=a.join(this.path,V),N=new p(O);if(N.exists)return N}async put(V,O){const N=Buffer.from(await O.arrayBuffer());let j=a.join(this.path,V);try{await o.promises.mkdir(a.dirname(j),{recursive:!0}),await o.promises.writeFile(j,N)}catch(D){console.warn("An error occurred while writing the file to cache:",D)}}}async function z(I,...V){for(let O of V)try{let N=await I.match(O);if(N)return N}catch{continue}}async function S(I,V,O=!0,N={}){if(!l.env.allowLocalModels){if(N.local_files_only)throw Error("Invalid configuration detected: local models are disabled (`env.allowLocalModels=false`) but you have requested to only use local models (`local_files_only=true`).");if(!l.env.allowRemoteModels)throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.")}(0,f.dispatchCallback)(N.progress_callback,{status:"initiate",name:I,file:V});let j;if(!j&&l.env.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{j=await caches.open("transformers-cache")}catch(Se){console.warn("An error occurred while opening the browser cache:",Se)}}if(!j&&l.env.useFSCache&&(j=new T(N.cache_dir??l.env.cacheDir)),!j&&l.env.useCustomCache){if(!l.env.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!l.env.customCache.match||!l.env.customCache.put)throw new Error("`env.customCache` must be an object which implements the `match` and `put` functions of the Web Cache API. For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache");j=l.env.customCache}const D=N.revision??"main";let ee=b(I,V),de=b(l.env.localModelPath,ee),Ce=b(l.env.remoteHost,l.env.remotePathTemplate.replaceAll("{model}",I).replaceAll("{revision}",encodeURIComponent(D)),V),te=D==="main"?ee:b(I,D,V),_e,R=j instanceof T?te:Ce,xe=!1,Xe;j&&(Xe=await z(j,de,R));const ge=Xe!==void 0;if(Xe===void 0){if(l.env.allowLocalModels)if(g(ee,["http:","https:"])){if(N.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${ee}.`);if(!l.env.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${ee}.`)}else try{Xe=await M(de),_e=de}catch(Q){console.warn(`Unable to load from local path "${de}": "${Q}"`)}if(Xe===void 0||Xe.status===404){if(N.local_files_only||!l.env.allowRemoteModels){if(O)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${de}".`);return null}if(Xe=await M(Ce),Xe.status!==200)return C(Xe.status,Ce,O);_e=R}xe=j&&typeof Response<"u"&&Xe instanceof Response&&Xe.status===200}(0,f.dispatchCallback)(N.progress_callback,{status:"download",name:I,file:V});const X={status:"progress",name:I,file:V};let ae;return N.progress_callback?ge&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent)?(ae=new Uint8Array(await Xe.arrayBuffer()),(0,f.dispatchCallback)(N.progress_callback,{...X,progress:100,loaded:ae.length,total:ae.length})):ae=await y(Xe,Se=>{(0,f.dispatchCallback)(N.progress_callback,{...X,...Se})}):ae=new Uint8Array(await Xe.arrayBuffer()),xe&&_e&&await j.match(_e)===void 0&&await j.put(_e,new Response(ae,{headers:Xe.headers})).catch(Se=>{console.warn(`Unable to add response to browser cache: ${Se}.`)}),(0,f.dispatchCallback)(N.progress_callback,{status:"done",name:I,file:V}),ae}async function E(I,V,O=!0,N={}){let j=await S(I,V,O,N);if(j===null)return{};let ee=new TextDecoder("utf-8").decode(j);return JSON.parse(ee)}async function y(I,V){const O=I.headers.get("Content-Length");O===null&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let N=parseInt(O??"0"),j=new Uint8Array(N),D=0;const ee=I.body.getReader();async function de(){const{done:Ce,value:te}=await ee.read();if(Ce)return;let _e=D+te.length;if(_e>N){N=_e;let xe=new Uint8Array(N);xe.set(j),j=xe}j.set(te,D),D=_e;const R=D/N*100;return V({progress:R,loaded:D,total:N}),de()}return await de(),j}function b(...I){return I=I.map((V,O)=>(O&&(V=V.replace(new RegExp("^/"),"")),O!==I.length-1&&(V=V.replace(new RegExp("/$"),"")),V)),I.join("/")}},"./src/utils/image.js":(e,t,r)=>{r.r(t),r.d(t,{RawImage:()=>z});var o=r("./src/utils/hub.js"),a=r("./src/env.js"),l=r("./src/utils/tensor.js"),f=r("?2b25");const _=typeof self<"u",p=_&&self.constructor.name==="DedicatedWorkerGlobalScope";let g,M,w;if(_)g=(S,E)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(S,E)},w=self.createImageBitmap,M=self.ImageData;else if(f)w=async S=>{const y=(await S.metadata()).channels,{data:b,info:I}=await S.rotate().raw().toBuffer({resolveWithObject:!0}),V=new z(new Uint8ClampedArray(b),I.width,I.height,I.channels);return y!==void 0&&y!==I.channels&&V.convert(y),V};else throw new Error("Unable to load image processing library.");const C={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 z{constructor(E,y,b,I){this.data=E,this.width=y,this.height=b,this.channels=I}get size(){return[this.width,this.height]}static async read(E){if(E instanceof z)return E;if(typeof E=="string"||E instanceof URL)return await this.fromURL(E);throw new Error(`Unsupported input type: ${typeof E}`)}static fromCanvas(E){if(!_)throw new Error("fromCanvas() is only supported in browser environments.");const b=E.getContext("2d").getImageData(0,0,E.width,E.height).data;return new z(b,E.width,E.height,4)}static async fromURL(E){const y=await(0,o.getFile)(E);if(y.status!==200)throw new Error(`Unable to read image from "${E}" (${y.status} ${y.statusText})`);const b=await y.blob();return this.fromBlob(b)}static async fromBlob(E){if(_){const y=await w(E),b=g(y.width,y.height).getContext("2d");return b.drawImage(y,0,0),new this(b.getImageData(0,0,y.width,y.height).data,y.width,y.height,4)}else{const y=f(await E.arrayBuffer());return await w(y)}}static fromTensor(E,y="CHW"){if(E.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${E.dims.length} dimensions.`);if(y==="CHW")E=E.transpose(1,2,0);else if(y!=="HWC")throw new Error(`Unsupported channel format: ${y}`);if(!(E.data instanceof Uint8ClampedArray||E.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${E.type}`);switch(E.dims[2]){case 1:case 2:case 3:case 4:return new z(E.data,E.dims[1],E.dims[0],E.dims[2]);default:throw new Error(`Unsupported number of channels: ${E.dims[2]}`)}}grayscale(){if(this.channels===1)return this;const E=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let y=0,b=0;y=0?j=b:ee=-b,I>=0?D=I:de=-I,N.drawImage(O,j,D,E,y,ee,de,E,y),new z(N.getImageData(0,0,E,y).data,E,y,4).convert(V)}else{let V=this.toSharp();if(b>=0&&I>=0)V=V.extract({left:Math.floor(b),top:Math.floor(I),width:E,height:y});else if(b<=0&&I<=0){const O=Math.floor(-I),N=Math.floor(-b);V=V.extend({top:O,left:N,right:E-this.width-N,bottom:y-this.height-O})}else{let O=[0,0],N=0;I<0?(O[0]=Math.floor(-I),O[1]=y-this.height-O[0]):N=Math.floor(I);let j=[0,0],D=0;b<0?(j[0]=Math.floor(-b),j[1]=E-this.width-j[0]):D=Math.floor(b),V=V.extend({top:O[0],bottom:O[1],left:j[0],right:j[1]}).extract({left:D,top:N,width:E,height:y})}return await w(V)}}async toBlob(E="image/png",y=1){if(!_)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:E,quality:y})}toTensor(E="CHW"){let y=new l.Tensor("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(E!=="HWC")if(E==="CHW")y=y.permute(2,0,1);else throw new Error(`Unsupported channel format: ${E}`);return y}toCanvas(){if(!_)throw new Error("toCanvas() is only supported in browser environments.");const E=this.clone().rgba(),y=g(E.width,E.height),b=new M(E.data,E.width,E.height);return y.getContext("2d").putImageData(b,0,0),y}_update(E,y,b,I=null){return this.data=E,this.width=y,this.height=b,I!==null&&(this.channels=I),this}clone(){return new z(this.data.slice(),this.width,this.height,this.channels)}convert(E){if(this.channels===E)return this;switch(E){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(E){if(_){if(p)throw new Error("Unable to save an image from a Web Worker.");const y=E.split(".").pop().toLowerCase(),b=T.get(y)??"image/png",I=await this.toBlob(b),V=URL.createObjectURL(I),O=document.createElement("a");O.href=V,O.download=E,O.click(),O.remove()}else{if(a.env.useFS)return await this.toSharp().toFile(E);throw new Error("Unable to save the image because filesystem is disabled in this environment.")}}toSharp(){if(_)throw new Error("toSharp() is only supported in server-side environments.");return f(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}}},"./src/utils/maths.js":(e,t,r)=>{r.r(t),r.d(t,{FFT:()=>S,bankers_round:()=>b,cos_sim:()=>p,dot:()=>_,dynamic_time_warping:()=>I,interpolate_data:()=>o,log_softmax:()=>f,magnitude:()=>g,max:()=>w,medianFilter:()=>E,min:()=>M,permute_data:()=>a,round:()=>y,softmax:()=>l});function o(V,[O,N,j],[D,ee],de="bilinear",Ce=!1){const te=ee/j,_e=D/N,R=new V.constructor(D*ee*O),xe=N*j,Xe=D*ee;for(let ge=0;ge=0;--Ce)D[Ce]=te,j[Ce]=O[N[Ce]],te*=j[Ce];const ee=N.map((Ce,te)=>D[N.indexOf(te)]),de=new V.constructor(V.length);for(let Ce=0;Ce=0;--_e)te+=R%O[_e]*ee[_e],R=Math.floor(R/O[_e]);de[te]=V[Ce]}return[de,j]}function l(V){const O=w(V)[0],N=V.map(ee=>Math.exp(ee-O)),j=N.reduce((ee,de)=>ee+de,0);return N.map(ee=>ee/j)}function f(V){return l(V).map(j=>Math.log(j))}function _(V,O){let N=0;for(let j=0;jO+N*N,0))}function M(V){if(V.length===0)throw Error("Array must not be empty");let O=V[0],N=0;for(let j=1;jO&&(O=V[j],N=j);return[Number(O),N]}function C(V){return V>0&&(V&V-1)===0}class T{constructor(O){if(this.size=O|0,this.size<=1||!C(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=O<<1,this.table=new Float64Array(this.size*2);for(let j=0;jj;j<<=1)++N;this._width=N%2===0?N-1:N,this._bitrev=new Int32Array(1<>>D&3)<>>1);for(let D=0;D>>1]=O[D];return j}toComplexArray(O,N){const j=N||this.createComplexArray();for(let D=0;D>>1],j[D+1]=0;return j}transform(O,N){if(O===N)throw new Error("Input and output buffers must be different");this._transform4(O,N,1)}realTransform(O,N){if(O===N)throw new Error("Input and output buffers must be different");this._realTransform4(O,N,1)}inverseTransform(O,N){if(O===N)throw new Error("Input and output buffers must be different");this._transform4(O,N,-1);for(let j=0;j>=2;de>=2;de>>=2){Ce=D/de<<1;const Xe=Ce>>>2;for(te=0;te>>1,de>>>1)}else for(te=0,_e=0;te>>1,de>>>1,j)}const xe=this.table;for(de>>=2;de>=2;de>>=2){Ce=D/de<<1;const ge=Ce>>>1,X=ge>>>1,ae=X>>>1;for(te=0;te>>1;for(let ge=2;ge>1;++R){const xe=(R+1-O)**2/2,Xe=Math.sqrt(te**2+_e**2)**xe,ge=xe*Math.atan2(_e,te),X=2*R;ee[X]=Xe*Math.cos(ge),ee[X+1]=Xe*Math.sin(ge),de[X]=ee[X],de[X+1]=-ee[X+1]}this._slicedChirpBuffer=ee.subarray(N,j),this._f=new T(D>>1),this._f.transform(this._chirpBuffer,de)}_transform(O,N,j){const D=this._buffer1,ee=this._buffer2,de=this._outBuffer1,Ce=this._outBuffer2,te=this._chirpBuffer,_e=this._slicedChirpBuffer,R=this._a;if(j)for(let xe=0;xe<_e.length;xe+=2){const Xe=xe+1,ge=xe>>1,X=N[ge];D[xe]=X*_e[xe],D[Xe]=X*_e[Xe]}else for(let xe=0;xe<_e.length;xe+=2){const Xe=xe+1;D[xe]=N[xe]*_e[xe]-N[Xe]*_e[Xe],D[Xe]=N[xe]*_e[Xe]+N[Xe]*_e[xe]}this._f.transform(de,D);for(let xe=0;xe=V.length&&(te=2*(V.length-1)-te),j[de++]=V[te]}j.sort(),N[ee]=j[D]}return N}function y(V,O){const N=Math.pow(10,O);return Math.round(V*N)/N}function b(V){const O=Math.round(V);return Math.abs(V)%1===.5?O%2===0?O:O-1:O}function I(V){const O=V.length,N=V[0].length,j=[O+1,N+1],D=Array.from({length:j[0]},()=>Array(j[1]).fill(1/0));D[0][0]=0;const ee=Array.from({length:j[0]},()=>Array(j[1]).fill(-1));for(let R=1;R0||Ce>0;)switch(te.push(de-1),_e.push(Ce-1),ee[de][Ce]){case 0:--de,--Ce;break;case 1:--de;break;case 2:--Ce;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${de}, ${Ce}]. Please file a bug report.`)}return te.reverse(),_e.reverse(),[te,_e]}},"./src/utils/tensor.js":(e,t,r)=>{r.r(t),r.d(t,{Tensor:()=>_,cat:()=>V,full:()=>de,full_like:()=>Ce,interpolate:()=>M,interpolate_4d:()=>w,layer_norm:()=>E,matmul:()=>C,mean:()=>j,mean_pooling:()=>S,ones:()=>te,ones_like:()=>_e,permute:()=>g,quantize_embeddings:()=>Xe,rfft:()=>T,stack:()=>O,std_mean:()=>N,topk:()=>z,zeros:()=>R,zeros_like:()=>xe});var o=r("./src/utils/maths.js"),a=r("./src/backends/onnx.js"),l=r("./src/ops/registry.js");const f=Object.freeze({float32:Float32Array,float16:Uint16Array,float64:Float64Array,string:Array,int8:Int8Array,uint8:Uint8Array,int16:Int16Array,uint16:Uint16Array,int32:Int32Array,uint32:Uint32Array,int64:BigInt64Array,uint64:BigUint64Array,bool:Uint8Array});class _{constructor(...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:(ae,Se)=>{if(typeof Se=="string"){let Q=Number(Se);if(Number.isInteger(Q))return ae._getitem(Q)}return ae[Se]},set:(ae,Se,Q)=>ae[Se]=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,...ae]=this.dims;if(ae.length>0){const Se=ae.reduce((Q,me)=>Q*me);for(let Q=0;Q0){const Q=Se.reduce((me,Ke)=>me*Ke);return this._subarray(X,Q,Se)}else return new _(this.type,[this.data[X]],Se)}indexOf(X){const ae=this.data;for(let Se=0;SeGe)throw new Error(`Invalid slice: ${st}`);const Me=[Math.max(ft,0),Math.min(Ge,this.dims[We])];Se.push(Me),ae.push(Me[1]-Me[0])}else throw new Error(`Invalid slice: ${st}`)}const Q=Se.map(([We,st])=>st-We),me=Q.reduce((We,st)=>We*st),Ke=this.data,Le=new Ke.constructor(me),Be=this.stride();for(let We=0;We=0;--ft){const Me=Q[ft];st+=(Ge%Me+Se[ft][0])*Be[ft],Ge=Math.floor(Ge/Me)}Le[We]=Ke[st]}return new _(this.type,Le,ae)}permute(...X){return g(this,X)}transpose(...X){return this.permute(...X)}sum(X=null,ae=!1){return this.norm(1,X,ae)}norm(X="fro",ae=null,Se=!1){if(X==="fro")X=2;else if(typeof X=="string")throw Error(`Unsupported norm: ${X}`);const Q=this.data;if(ae===null){let Le=Q.reduce((Be,We)=>Be+We**X,0)**(1/X);return new _(this.type,[Le],[])}ae=I(ae,this.dims.length);const me=this.dims.slice();me[ae]=1;const Ke=new Q.constructor(Q.length/this.dims[ae]);for(let Le=0;Le=0;--We){const Ge=this.dims[We];if(We!==ae){const Me=st%Ge;Be+=Me*ft,ft*=me[We]}st=Math.floor(st/Ge)}Ke[Be]+=Q[Le]**X}if(X!==1)for(let Le=0;Le=0;--Be){const ft=this.dims[Be];if(Be!==ae){const Ge=We%ft;Le+=Ge*st,st*=this.dims[Be]}We=Math.floor(We/ft)}Q[Ke]/=me[Le]}return this}normalize(X=2,ae=1){return this.clone().normalize_(X,ae)}stride(){return D(this.dims)}squeeze(X=null){return new _(this.type,this.data,y(this.dims,X))}squeeze_(X=null){return this.dims=y(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,ae=-1){ae=(ae+this.dims.length)%this.dims.length;let Se=this.dims.slice(0,X),Q=this.dims.slice(X,ae+1),me=this.dims.slice(ae+1);return this.dims=[...Se,Q.reduce((Ke,Le)=>Ke*Le,1),...me],this}flatten(X=0,ae=-1){return this.clone().flatten_(X,ae)}view(...X){let ae=-1;for(let Q=0;QLe!==ae?me*Ke:me,1);X[ae]=Se.length/Q}return new _(this.type,Se,X)}neg_(){const X=this.data;for(let ae=0;aeme*Ke);if(ae!==Se)throw Error(`cannot reshape array of size ${ae} into shape (${X})`);let Q=ge;for(let me=X.length-1;me>=0;me--)Q=Q.reduce((Ke,Le)=>{let Be=Ke[Ke.length-1];return Be.lengthae!==1):typeof X=="number"?ge[X]===1&&ge.splice(X,1):Array.isArray(X)&&(ge=ge.filter((ae,Se)=>ae!==1||!X.includes(Se))),ge}function b(ge,X){return X=I(X,ge.length+1),ge=ge.slice(),ge.splice(X,0,1),ge}function I(ge,X,ae=null,Se=!0){if(Se&&(ge<-X||ge>=X))throw new Error(`IndexError: index ${ge} is out of bounds for dimension${ae===null?"":" "+ae} with size ${X}`);return ge<0&&(ge=(ge%X+X)%X),ge}function V(ge,X=0){X=I(X,ge[0].dims.length);const ae=ge[0].dims.slice();ae[X]=ge.reduce((Ke,Le)=>Ke+Le.dims[X],0);const Se=ae.reduce((Ke,Le)=>Ke*Le,1),Q=new ge[0].data.constructor(Se),me=ge[0].type;if(X===0){let Ke=0;for(const Le of ge){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=Me%Ye;Ge===X&&(et+=Ke),ft+=et*je,je*=ae[Ge],Me=Math.floor(Me/Ye)}Q[ft]=Be[st]}Ke+=We[X]}}return new _(me,Q,ae)}function O(ge,X=0){return V(ge.map(ae=>ae.unsqueeze(X)),X)}function N(ge,X=null,ae=1,Se=!1){const Q=ge.data,me=ge.dims;if(X===null){const Ge=Q.reduce((et,A)=>et+A,0)/Q.length,Me=Math.sqrt(Q.reduce((et,A)=>et+(A-Ge)**2,0)/(Q.length-ae)),je=new _(ge.type,[Ge],[]);return[new _(ge.type,[Me],[]),je]}X=I(X,me.length);const Ke=j(ge,X,Se),Le=Ke.data,Be=me.slice();Be[X]=1;const We=new Q.constructor(Q.length/me[X]);for(let ft=0;ft=0;--Me){const et=me[Me];if(Me!==X){const A=je%et;Ge+=A*Ye,Ye*=Be[Me]}je=Math.floor(je/et)}We[Ge]+=(Q[ft]-Le[Ge])**2}for(let ft=0;ftBe+We,0);return new _(ge.type,[Le/Se.length],[])}const Q=ge.dims;X=I(X,Q.length);const me=Q.slice();me[X]=1;const Ke=new Se.constructor(Se.length/Q[X]);for(let Le=0;Le=0;--We){const Ge=Q[We];if(We!==X){const Me=st%Ge;Be+=Me*ft,ft*=me[We]}st=Math.floor(st/Ge)}Ke[Be]+=Se[Le]}if(Q[X]!==1)for(let Le=0;Le=0;--ae)X[ae]=Se,Se*=ge[ae];return X}function ee(ge,X,ae,Se){const Q=ge.reduce((me,Ke)=>me*Ke,1);return new _(ae,new Se(Q).fill(X),ge)}function de(ge,X){let ae,Se;if(typeof X=="number")ae="float32",Se=Float32Array;else if(typeof X=="bigint")ae="int64",Se=BigInt64Array;else throw new Error(`Unsupported data type: ${typeof X}`);return ee(ge,X,ae,Se)}function Ce(ge,X){return de(ge.dims,X)}function te(ge){return ee(ge,1n,"int64",BigInt64Array)}function _e(ge){return te(ge.dims)}function R(ge){return ee(ge,0n,"int64",BigInt64Array)}function xe(ge){return R(ge.dims)}function Xe(ge,X){if(ge.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(ge.dims.at(-1)%8!==0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(X))throw new Error("The precision must be either 'binary' or 'ubinary'");const ae=X==="binary",Se=ae?"int8":"uint8",Q=ae?Int8Array:Uint8Array,me=ge.data,Ke=new Q(me.length/8);for(let Le=0;Le0?1:0,We=Math.floor(Le/8),st=Le%8;Ke[We]|=Be<<7-st,ae&&st===0&&(Ke[We]-=128)}return new _(Se,Ke,[ge.dims[0],ge.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 f=o&2&&r;typeof f=="object"&&!~t.indexOf(f);f=e(f))Object.getOwnPropertyNames(f).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:()=>w.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:()=>w.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:()=>w.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:()=>w.StoppingCriteria,StoppingCriteriaList:()=>w.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:()=>p.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:()=>p.cat,cos_sim:()=>g.cos_sim,dot:()=>g.dot,dynamic_time_warping:()=>g.dynamic_time_warping,env:()=>e.env,full:()=>p.full,full_like:()=>p.full_like,getKeyValueShapes:()=>l.getKeyValueShapes,hamming:()=>f.hamming,hanning:()=>f.hanning,interpolate:()=>p.interpolate,interpolate_4d:()=>p.interpolate_4d,interpolate_data:()=>g.interpolate_data,is_chinese_char:()=>o.is_chinese_char,layer_norm:()=>p.layer_norm,log_softmax:()=>g.log_softmax,magnitude:()=>g.magnitude,matmul:()=>p.matmul,max:()=>g.max,mean:()=>p.mean,mean_pooling:()=>p.mean_pooling,medianFilter:()=>g.medianFilter,mel_filter_bank:()=>f.mel_filter_bank,min:()=>g.min,ones:()=>p.ones,ones_like:()=>p.ones_like,permute:()=>p.permute,permute_data:()=>g.permute_data,pipeline:()=>t.pipeline,quantize_embeddings:()=>p.quantize_embeddings,read_audio:()=>f.read_audio,rfft:()=>p.rfft,round:()=>g.round,softmax:()=>g.softmax,spectrogram:()=>f.spectrogram,stack:()=>p.stack,std_mean:()=>p.std_mean,topk:()=>p.topk,window_function:()=>f.window_function,zeros:()=>p.zeros,zeros_like:()=>p.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"),f=en("./src/utils/audio.js"),_=en("./src/utils/image.js"),p=en("./src/utils/tensor.js"),g=en("./src/utils/maths.js"),M=en("./src/generation/streamers.js"),w=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;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 fh(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 f(g,M){if(!a[g]){if(!o[g]){var w=typeof fh=="function"&&fh;if(!M&&w)return w(g,!0);if(_)return _(g,!0);var C=new Error("Cannot find module '"+g+"'");throw C.code="MODULE_NOT_FOUND",C}var T=a[g]={exports:{}};o[g][0].call(T.exports,function(z){var S=o[g][1][z];return f(S||z)},T,T.exports,r,o,a,l)}return a[g].exports}for(var _=typeof fh=="function"&&fh,p=0;p>2,T=(3&g)<<4|M>>4,z=1>6:64,S=2>4,M=(15&C)<<4|(T=_.indexOf(p.charAt(S++)))>>2,w=(3&T)<<6|(z=_.indexOf(p.charAt(S++))),b[E++]=g,T!==64&&(b[E++]=M),z!==64&&(b[E++]=w);return b}},{"./support":30,"./utils":32}],2:[function(r,o,a){var l=r("./external"),f=r("./stream/DataWorker"),_=r("./stream/Crc32Probe"),p=r("./stream/DataLengthProbe");function g(M,w,C,T,z){this.compressedSize=M,this.uncompressedSize=w,this.crc32=C,this.compression=T,this.compressedContent=z}g.prototype={getContentWorker:function(){var M=new f(l.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new p("data_length")),w=this;return M.on("end",function(){if(this.streamInfo.data_length!==w.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),M},getCompressedWorker:function(){return new f(l.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},g.createWorkerFrom=function(M,w,C){return M.pipe(new _).pipe(new p("uncompressedSize")).pipe(w.compressWorker(C)).pipe(new p("compressedSize")).withStreamInfo("compression",w)},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"),f=function(){for(var _,p=[],g=0;g<256;g++){_=g;for(var M=0;M<8;M++)_=1&_?3988292384^_>>>1:_>>>1;p[g]=_}return p}();o.exports=function(_,p){return _!==void 0&&_.length?l.getTypeOf(_)!=="string"?function(g,M,w,C){var T=f,z=C+w;g^=-1;for(var S=C;S>>8^T[255&(g^M[S])];return-1^g}(0|p,_,_.length,0):function(g,M,w,C){var T=f,z=C+w;g^=-1;for(var S=C;S>>8^T[255&(g^M.charCodeAt(S))];return-1^g}(0|p,_,_.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",f=r("pako"),_=r("./utils"),p=r("./stream/GenericWorker"),g=l?"uint8array":"array";function M(w,C){p.call(this,"FlateWorker/"+w),this._pako=null,this._pakoAction=w,this._pakoOptions=C,this.meta={}}a.magic="\b\0",_.inherits(M,p),M.prototype.processChunk=function(w){this.meta=w.meta,this._pako===null&&this._createPako(),this._pako.push(_.transformTo(g,w.data),!1)},M.prototype.flush=function(){p.prototype.flush.call(this),this._pako===null&&this._createPako(),this._pako.push([],!0)},M.prototype.cleanUp=function(){p.prototype.cleanUp.call(this),this._pako=null},M.prototype._createPako=function(){this._pako=new f[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var w=this;this._pako.onData=function(C){w.push({data:C,meta:w.meta})}},a.compressWorker=function(w){return new M("Deflate",w)},a.uncompressWorker=function(){return new M("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(r,o,a){function l(T,z){var S,E="";for(S=0;S>>=8;return E}function f(T,z,S,E,y,b){var I,V,O=T.file,N=T.compression,j=b!==g.utf8encode,D=_.transformTo("string",b(O.name)),ee=_.transformTo("string",g.utf8encode(O.name)),de=O.comment,Ce=_.transformTo("string",b(de)),te=_.transformTo("string",g.utf8encode(de)),_e=ee.length!==O.name.length,R=te.length!==de.length,xe="",Xe="",ge="",X=O.dir,ae=O.date,Se={crc32:0,compressedSize:0,uncompressedSize:0};z&&!S||(Se.crc32=T.crc32,Se.compressedSize=T.compressedSize,Se.uncompressedSize=T.uncompressedSize);var Q=0;z&&(Q|=8),j||!_e&&!R||(Q|=2048);var me=0,Ke=0;X&&(me|=16),y==="UNIX"?(Ke=798,me|=function(Be,We){var st=Be;return Be||(st=We?16893:33204),(65535&st)<<16}(O.unixPermissions,X)):(Ke=20,me|=function(Be){return 63&(Be||0)}(O.dosPermissions)),I=ae.getUTCHours(),I<<=6,I|=ae.getUTCMinutes(),I<<=5,I|=ae.getUTCSeconds()/2,V=ae.getUTCFullYear()-1980,V<<=4,V|=ae.getUTCMonth()+1,V<<=5,V|=ae.getUTCDate(),_e&&(Xe=l(1,1)+l(M(D),4)+ee,xe+="up"+l(Xe.length,2)+Xe),R&&(ge=l(1,1)+l(M(Ce),4)+te,xe+="uc"+l(ge.length,2)+ge);var Le="";return Le+=` +\0`,Le+=l(Q,2),Le+=N.magic,Le+=l(I,2),Le+=l(V,2),Le+=l(Se.crc32,4),Le+=l(Se.compressedSize,4),Le+=l(Se.uncompressedSize,4),Le+=l(D.length,2),Le+=l(xe.length,2),{fileRecord:w.LOCAL_FILE_HEADER+Le+D+xe,dirRecord:w.CENTRAL_FILE_HEADER+l(Ke,2)+Le+l(Ce.length,2)+"\0\0\0\0"+l(me,4)+l(E,4)+D+xe+Ce}}var _=r("../utils"),p=r("../stream/GenericWorker"),g=r("../utf8"),M=r("../crc32"),w=r("../signature");function C(T,z,S,E){p.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=z,this.zipPlatform=S,this.encodeFileName=E,this.streamFiles=T,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}_.inherits(C,p),C.prototype.push=function(T){var z=T.meta.percent||0,S=this.entriesCount,E=this._sources.length;this.accumulate?this.contentBuffer.push(T):(this.bytesWritten+=T.data.length,p.prototype.push.call(this,{data:T.data,meta:{currentFile:this.currentFile,percent:S?(z+100*(S-E-1))/S:100}}))},C.prototype.openedSource=function(T){this.currentSourceOffset=this.bytesWritten,this.currentFile=T.file.name;var z=this.streamFiles&&!T.file.dir;if(z){var S=f(T,z,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:S.fileRecord,meta:{percent:0}})}else this.accumulate=!0},C.prototype.closedSource=function(T){this.accumulate=!1;var z=this.streamFiles&&!T.file.dir,S=f(T,z,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(S.dirRecord),z)this.push({data:function(E){return w.DATA_DESCRIPTOR+l(E.crc32,4)+l(E.compressedSize,4)+l(E.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},C.prototype.flush=function(){for(var T=this.bytesWritten,z=0;z=this.index;p--)g=(g<<8)+this.byteAt(p);return this.index+=_,g},readString:function(_){return l.transformTo("string",this.readData(_))},readData:function(){},lastIndexOfSignature:function(){},readAndCheckSignature:function(){},readDate:function(){var _=this.readInt(4);return new Date(Date.UTC(1980+(_>>25&127),(_>>21&15)-1,_>>16&31,_>>11&31,_>>5&63,(31&_)<<1))}},o.exports=f},{"../utils":32}],19:[function(r,o,a){var l=r("./Uint8ArrayReader");function f(_){l.call(this,_)}r("../utils").inherits(f,l),f.prototype.readData=function(_){this.checkOffset(_);var p=this.data.slice(this.zero+this.index,this.zero+this.index+_);return this.index+=_,p},o.exports=f},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(r,o,a){var l=r("./DataReader");function f(_){l.call(this,_)}r("../utils").inherits(f,l),f.prototype.byteAt=function(_){return this.data.charCodeAt(this.zero+_)},f.prototype.lastIndexOfSignature=function(_){return this.data.lastIndexOf(_)-this.zero},f.prototype.readAndCheckSignature=function(_){return _===this.readData(4)},f.prototype.readData=function(_){this.checkOffset(_);var p=this.data.slice(this.zero+this.index,this.zero+this.index+_);return this.index+=_,p},o.exports=f},{"../utils":32,"./DataReader":18}],21:[function(r,o,a){var l=r("./ArrayReader");function f(_){l.call(this,_)}r("../utils").inherits(f,l),f.prototype.readData=function(_){if(this.checkOffset(_),_===0)return new Uint8Array(0);var p=this.data.subarray(this.zero+this.index,this.zero+this.index+_);return this.index+=_,p},o.exports=f},{"../utils":32,"./ArrayReader":17}],22:[function(r,o,a){var l=r("../utils"),f=r("../support"),_=r("./ArrayReader"),p=r("./StringReader"),g=r("./NodeBufferReader"),M=r("./Uint8ArrayReader");o.exports=function(w){var C=l.getTypeOf(w);return l.checkSupport(C),C!=="string"||f.uint8array?C==="nodebuffer"?new g(w):f.uint8array?new M(l.transformTo("uint8array",w)):new _(l.transformTo("array",w)):new p(w)}},{"../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"),f=r("../utils");function _(p){l.call(this,"ConvertWorker to "+p),this.destType=p}f.inherits(_,l),_.prototype.processChunk=function(p){this.push({data:f.transformTo(this.destType,p.data),meta:p.meta})},o.exports=_},{"../utils":32,"./GenericWorker":28}],25:[function(r,o,a){var l=r("./GenericWorker"),f=r("../crc32");function _(){l.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}r("../utils").inherits(_,l),_.prototype.processChunk=function(p){this.streamInfo.crc32=f(p.data,this.streamInfo.crc32||0),this.push(p)},o.exports=_},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(r,o,a){var l=r("../utils"),f=r("./GenericWorker");function _(p){f.call(this,"DataLengthProbe for "+p),this.propName=p,this.withStreamInfo(p,0)}l.inherits(_,f),_.prototype.processChunk=function(p){if(p){var g=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=g+p.data.length}f.prototype.processChunk.call(this,p)},o.exports=_},{"../utils":32,"./GenericWorker":28}],27:[function(r,o,a){var l=r("../utils"),f=r("./GenericWorker");function _(p){f.call(this,"DataWorker");var g=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,p.then(function(M){g.dataIsReady=!0,g.data=M,g.max=M&&M.length||0,g.type=l.getTypeOf(M),g.isPaused||g._tickAndRepeat()},function(M){g.error(M)})}l.inherits(_,f),_.prototype.cleanUp=function(){f.prototype.cleanUp.call(this),this.data=null},_.prototype.resume=function(){return!!f.prototype.resume.call(this)&&(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,l.delay(this._tickAndRepeat,[],this)),!0)},_.prototype._tickAndRepeat=function(){this._tickScheduled=!1,this.isPaused||this.isFinished||(this._tick(),this.isFinished||(l.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0))},_.prototype._tick=function(){if(this.isPaused||this.isFinished)return!1;var p=null,g=Math.min(this.max,this.index+16384);if(this.index>=this.max)return this.end();switch(this.type){case"string":p=this.data.substring(this.index,g);break;case"uint8array":p=this.data.subarray(this.index,g);break;case"array":case"nodebuffer":p=this.data.slice(this.index,g)}return this.index=g,this.push({data:p,meta:{percent:this.max?this.index/this.max*100:0}})},o.exports=_},{"../utils":32,"./GenericWorker":28}],28:[function(r,o,a){function l(f){this.name=f||"default",this.streamInfo={},this.generatedError=null,this.extraStreamInfo={},this.isPaused=!0,this.isFinished=!1,this.isLocked=!1,this._listeners={data:[],end:[],error:[]},this.previous=null}l.prototype={push:function(f){this.emit("data",f)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0}catch(f){this.emit("error",f)}return!0},error:function(f){return!this.isFinished&&(this.isPaused?this.generatedError=f:(this.isFinished=!0,this.emit("error",f),this.previous&&this.previous.error(f),this.cleanUp()),!0)},on:function(f,_){return this._listeners[f].push(_),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(f,_){if(this._listeners[f])for(var p=0;p "+f:f}},o.exports=l},{}],29:[function(r,o,a){var l=r("../utils"),f=r("./ConvertWorker"),_=r("./GenericWorker"),p=r("../base64"),g=r("../support"),M=r("../external"),w=null;if(g.nodestream)try{w=r("../nodejs/NodejsStreamOutputAdapter")}catch{}function C(z,S){return new M.Promise(function(E,y){var b=[],I=z._internalType,V=z._outputType,O=z._mimeType;z.on("data",function(N,j){b.push(N),S&&S(j)}).on("error",function(N){b=[],y(N)}).on("end",function(){try{var N=function(j,D,ee){switch(j){case"blob":return l.newBlob(l.transformTo("arraybuffer",D),ee);case"base64":return p.encode(D);default:return l.transformTo(j,D)}}(V,function(j,D){var ee,de=0,Ce=null,te=0;for(ee=0;ee"u")a.blob=!1;else{var l=new ArrayBuffer(0);try{a.blob=new Blob([l],{type:"application/zip"}).size===0}catch{try{var f=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);f.append(l),a.blob=f.getBlob("application/zip").size===0}catch{a.blob=!1}}}try{a.nodestream=!!r("readable-stream").Readable}catch{a.nodestream=!1}},{"readable-stream":16}],31:[function(r,o,a){for(var l=r("./utils"),f=r("./support"),_=r("./nodejsUtils"),p=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 w(){p.call(this,"utf-8 decode"),this.leftOver=null}function C(){p.call(this,"utf-8 encode")}a.utf8encode=function(T){return f.nodebuffer?_.newBufferFrom(T,"utf-8"):function(z){var S,E,y,b,I,V=z.length,O=0;for(b=0;b>>6:(E<65536?S[I++]=224|E>>>12:(S[I++]=240|E>>>18,S[I++]=128|E>>>12&63),S[I++]=128|E>>>6&63),S[I++]=128|63&E);return S}(T)},a.utf8decode=function(T){return f.nodebuffer?l.transformTo("nodebuffer",T).toString("utf-8"):function(z){var S,E,y,b,I=z.length,V=new Array(2*I);for(S=E=0;S>10&1023,V[E++]=56320|1023&y)}return V.length!==E&&(V.subarray?V=V.subarray(0,E):V.length=E),l.applyFromCharCode(V)}(T=l.transformTo(f.uint8array?"uint8array":"array",T))},l.inherits(w,p),w.prototype.processChunk=function(T){var z=l.transformTo(f.uint8array?"uint8array":"array",T.data);if(this.leftOver&&this.leftOver.length){if(f.uint8array){var S=z;(z=new Uint8Array(S.length+this.leftOver.length)).set(this.leftOver,0),z.set(S,this.leftOver.length)}else z=this.leftOver.concat(z);this.leftOver=null}var E=function(b,I){var V;for((I=I||b.length)>b.length&&(I=b.length),V=I-1;0<=V&&(192&b[V])==128;)V--;return V<0||V===0?I:V+g[b[V]]>I?V:I}(z),y=z;E!==z.length&&(f.uint8array?(y=z.subarray(0,E),this.leftOver=z.subarray(E,z.length)):(y=z.slice(0,E),this.leftOver=z.slice(E,z.length))),this.push({data:a.utf8decode(y),meta:T.meta})},w.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:a.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},a.Utf8DecodeWorker=w,l.inherits(C,p),C.prototype.processChunk=function(T){this.push({data:a.utf8encode(T.data),meta:T.meta})},a.Utf8EncodeWorker=C},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(r,o,a){var l=r("./support"),f=r("./base64"),_=r("./nodejsUtils"),p=r("./external");function g(S){return S}function M(S,E){for(var y=0;y>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===f.MAX_VALUE_32BITS&&(this.uncompressedSize=T.readInt(8)),this.compressedSize===f.MAX_VALUE_32BITS&&(this.compressedSize=T.readInt(8)),this.localHeaderOffset===f.MAX_VALUE_32BITS&&(this.localHeaderOffset=T.readInt(8)),this.diskNumberStart===f.MAX_VALUE_32BITS&&(this.diskNumberStart=T.readInt(4))}},readExtraFields:function(T){var z,S,E,y=T.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});T.index+4>>6:(T<65536?C[E++]=224|T>>>12:(C[E++]=240|T>>>18,C[E++]=128|T>>>12&63),C[E++]=128|T>>>6&63),C[E++]=128|63&T);return C},a.buf2binstring=function(w){return M(w,w.length)},a.binstring2buf=function(w){for(var C=new l.Buf8(w.length),T=0,z=C.length;T>10&1023,b[z++]=56320|1023&S)}return M(b,z)},a.utf8border=function(w,C){var T;for((C=C||w.length)>w.length&&(C=w.length),T=C-1;0<=T&&(192&w[T])==128;)T--;return T<0||T===0?C:T+p[w[T]]>C?T:C}},{"./common":41}],43:[function(r,o,a){o.exports=function(l,f,_,p){for(var g=65535&l|0,M=l>>>16&65535|0,w=0;_!==0;){for(_-=w=2e3<_?2e3:_;M=M+(g=g+f[p++]|0)|0,--w;);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 f,_=[],p=0;p<256;p++){f=p;for(var g=0;g<8;g++)f=1&f?3988292384^f>>>1:f>>>1;_[p]=f}return _}();o.exports=function(f,_,p,g){var M=l,w=g+p;f^=-1;for(var C=g;C>>8^M[255&(f^_[C])];return-1^f}},{}],46:[function(r,o,a){var l,f=r("../utils/common"),_=r("./trees"),p=r("./adler32"),g=r("./crc32"),M=r("./messages"),w=0,C=4,T=0,z=-2,S=-1,E=4,y=2,b=8,I=9,V=286,O=30,N=19,j=2*V+1,D=15,ee=3,de=258,Ce=de+ee+1,te=42,_e=113,R=1,xe=2,Xe=3,ge=4;function X(A,$e){return A.msg=M[$e],$e}function ae(A){return(A<<1)-(4A.avail_out&&(Pe=A.avail_out),Pe!==0&&(f.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 me(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,ne=A.max_chain_length,ye=A.strstart,B=A.prev_length,J=A.nice_match,L=A.strstart>A.w_size-Ce?A.strstart-(A.w_size-Ce):0,ue=A.window,le=A.w_mask,Te=A.prev,Ne=A.strstart+de,dt=ue[ye+B-1],Je=ue[ye+B];A.prev_length>=A.good_match&&(ne>>=2),J>A.lookahead&&(J=A.lookahead);do if(ue[(Pe=$e)+B]===Je&&ue[Pe+B-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]&&yeL&&--ne!=0);return B<=A.lookahead?B:A.lookahead}function We(A){var $e,Pe,se,ne,ye,B,J,L,ue,le,Te=A.w_size;do{if(ne=A.window_size-A.lookahead-A.strstart,A.strstart>=Te+(Te-Ce)){for(f.arraySet(A.window,A.window,Te,Te,0),A.match_start-=Te,A.strstart-=Te,A.block_start-=Te,$e=Pe=A.hash_size;se=A.head[--$e],A.head[$e]=Te<=se?se-Te:0,--Pe;);for($e=Pe=Te;se=A.prev[--$e],A.prev[$e]=Te<=se?se-Te:0,--Pe;);ne+=Te}if(A.strm.avail_in===0)break;if(B=A.strm,J=A.window,L=A.strstart+A.lookahead,ue=ne,le=void 0,le=B.avail_in,ue=ee)for(ye=A.strstart-A.insert,A.ins_h=A.window[ye],A.ins_h=(A.ins_h<=ee&&(A.ins_h=(A.ins_h<=ee)if(se=_._tr_tally(A,A.strstart-A.match_start,A.match_length-ee),A.lookahead-=A.match_length,A.match_length<=A.max_lazy_match&&A.lookahead>=ee){for(A.match_length--;A.strstart++,A.ins_h=(A.ins_h<=ee&&(A.ins_h=(A.ins_h<=ee&&A.match_length<=A.prev_length){for(ne=A.strstart+A.lookahead-ee,se=_._tr_tally(A,A.strstart-1-A.prev_match,A.prev_length-ee),A.lookahead-=A.prev_length-1,A.prev_length-=2;++A.strstart<=ne&&(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===w)return R;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,me(A,!1),A.strm.avail_out===0)||A.strstart-A.block_start>=A.w_size-Ce&&(me(A,!1),A.strm.avail_out===0))return R}return A.insert=0,$e===C?(me(A,!0),A.strm.avail_out===0?Xe:ge):(A.strstart>A.block_start&&(me(A,!1),A.strm.avail_out),R)}),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,ft),new Ge(8,16,32,32,ft),new Ge(8,16,128,128,ft),new Ge(8,32,128,256,ft),new Ge(32,128,258,1024,ft),new Ge(32,258,258,4096,ft)],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?z:(A.state.gzhead=$e,T):z},a.deflate=function(A,$e){var Pe,se,ne,ye;if(!A||!A.state||5<$e||$e<0)return A?X(A,z):z;if(se=A.state,!A.output||!A.input&&A.avail_in!==0||se.status===666&&$e!==C)return X(A,A.avail_out===0?-5:z);if(se.strm=A,Pe=se.last_flush,se.last_flush=$e,se.status===te)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 B=b+(se.w_bits-8<<4)<<8;B|=(2<=se.strategy||se.level<2?0:se.level<6?1:se.level===6?2:3)<<6,se.strstart!==0&&(B|=32),B+=31-B%31,se.status=_e,Le(se,B),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(ne=se.pending;se.gzindex<(65535&se.gzhead.extra.length)&&(se.pending!==se.pending_buf_size||(se.gzhead.hcrc&&se.pending>ne&&(A.adler=g(A.adler,se.pending_buf,se.pending-ne,ne)),Q(A),ne=se.pending,se.pending!==se.pending_buf_size));)Ke(se,255&se.gzhead.extra[se.gzindex]),se.gzindex++;se.gzhead.hcrc&&se.pending>ne&&(A.adler=g(A.adler,se.pending_buf,se.pending-ne,ne)),se.gzindex===se.gzhead.extra.length&&(se.gzindex=0,se.status=73)}else se.status=73;if(se.status===73)if(se.gzhead.name){ne=se.pending;do{if(se.pending===se.pending_buf_size&&(se.gzhead.hcrc&&se.pending>ne&&(A.adler=g(A.adler,se.pending_buf,se.pending-ne,ne)),Q(A),ne=se.pending,se.pending===se.pending_buf_size)){ye=1;break}ye=se.gzindexne&&(A.adler=g(A.adler,se.pending_buf,se.pending-ne,ne)),ye===0&&(se.gzindex=0,se.status=91)}else se.status=91;if(se.status===91)if(se.gzhead.comment){ne=se.pending;do{if(se.pending===se.pending_buf_size&&(se.gzhead.hcrc&&se.pending>ne&&(A.adler=g(A.adler,se.pending_buf,se.pending-ne,ne)),Q(A),ne=se.pending,se.pending===se.pending_buf_size)){ye=1;break}ye=se.gzindexne&&(A.adler=g(A.adler,se.pending_buf,se.pending-ne,ne)),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&&ae($e)<=ae(Pe)&&$e!==C)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!==w&&se.status!==666){var J=se.strategy===2?function(L,ue){for(var le;;){if(L.lookahead===0&&(We(L),L.lookahead===0)){if(ue===w)return R;break}if(L.match_length=0,le=_._tr_tally(L,0,L.window[L.strstart]),L.lookahead--,L.strstart++,le&&(me(L,!1),L.strm.avail_out===0))return R}return L.insert=0,ue===C?(me(L,!0),L.strm.avail_out===0?Xe:ge):L.last_lit&&(me(L,!1),L.strm.avail_out===0)?R:xe}(se,$e):se.strategy===3?function(L,ue){for(var le,Te,Ne,dt,Je=L.window;;){if(L.lookahead<=de){if(We(L),L.lookahead<=de&&ue===w)return R;if(L.lookahead===0)break}if(L.match_length=0,L.lookahead>=ee&&0L.lookahead&&(L.match_length=L.lookahead)}if(L.match_length>=ee?(le=_._tr_tally(L,1,L.match_length-ee),L.lookahead-=L.match_length,L.strstart+=L.match_length,L.match_length=0):(le=_._tr_tally(L,0,L.window[L.strstart]),L.lookahead--,L.strstart++),le&&(me(L,!1),L.strm.avail_out===0))return R}return L.insert=0,ue===C?(me(L,!0),L.strm.avail_out===0?Xe:ge):L.last_lit&&(me(L,!1),L.strm.avail_out===0)?R:xe}(se,$e):l[se.level].func(se,$e);if(J!==Xe&&J!==ge||(se.status=666),J===R||J===Xe)return A.avail_out===0&&(se.last_flush=-1),T;if(J===xe&&($e===1?_._tr_align(se):$e!==5&&(_._tr_stored_block(se,0,0,!1),$e===3&&(Se(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!==C?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&&(Se(Pe.head),Pe.strstart=0,Pe.block_start=0,Pe.insert=0),ue=new f.Buf8(Pe.w_size),f.arraySet(ue,$e,le-Pe.w_size,Pe.w_size,0),$e=ue,le=Pe.w_size),B=A.avail_in,J=A.next_in,L=A.input,A.avail_in=le,A.next_in=0,A.input=$e,We(Pe);Pe.lookahead>=ee;){for(se=Pe.strstart,ne=Pe.lookahead-(ee-1);Pe.ins_h=(Pe.ins_h<>>=ee=D>>>24,I-=ee,(ee=D>>>16&255)===0)xe[M++]=65535&D;else{if(!(16&ee)){if(!(64&ee)){D=V[(65535&D)+(b&(1<>>=ee,I-=ee),I<15&&(b+=R[p++]<>>=ee=D>>>24,I-=ee,!(16&(ee=D>>>16&255))){if(!(64&ee)){D=O[(65535&D)+(b&(1<>>=ee,I-=ee,(ee=M-w)>3,b&=(1<<(I-=de<<3))-1,l.next_in=p,l.next_out=M,l.avail_in=p>>24&255)+(te>>>8&65280)+((65280&te)<<8)+((255&te)<<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(te){var _e;return te&&te.state?(_e=te.state,te.total_in=te.total_out=_e.total=0,te.msg="",_e.wrap&&(te.adler=1&_e.wrap),_e.mode=z,_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(E),_e.sane=1,_e.back=-1,C):T}function V(te){var _e;return te&&te.state?((_e=te.state).wsize=0,_e.whave=0,_e.wnext=0,I(te)):T}function O(te,_e){var R,xe;return te&&te.state?(xe=te.state,_e<0?(R=0,_e=-_e):(R=1+(_e>>4),_e<48&&(_e&=15)),_e&&(_e<8||15<_e)?T:(xe.window!==null&&xe.wbits!==_e&&(xe.window=null),xe.wrap=R,xe.wbits=_e,V(te))):T}function N(te,_e){var R,xe;return te?(xe=new b,(te.state=xe).window=null,(R=O(te,_e))!==C&&(te.state=null),R):T}var j,D,ee=!0;function de(te){if(ee){var _e;for(j=new l.Buf32(512),D=new l.Buf32(32),_e=0;_e<144;)te.lens[_e++]=8;for(;_e<256;)te.lens[_e++]=9;for(;_e<280;)te.lens[_e++]=7;for(;_e<288;)te.lens[_e++]=8;for(g(M,te.lens,0,288,j,0,te.work,{bits:9}),_e=0;_e<32;)te.lens[_e++]=5;g(w,te.lens,0,32,D,0,te.work,{bits:5}),ee=!1}te.lencode=j,te.lenbits=9,te.distcode=D,te.distbits=5}function Ce(te,_e,R,xe){var Xe,ge=te.state;return ge.window===null&&(ge.wsize=1<=ge.wsize?(l.arraySet(ge.window,_e,R-ge.wsize,ge.wsize,0),ge.wnext=0,ge.whave=ge.wsize):(xe<(Xe=ge.wsize-ge.wnext)&&(Xe=xe),l.arraySet(ge.window,_e,R-xe,Xe,ge.wnext),(xe-=Xe)?(l.arraySet(ge.window,_e,R-xe,xe,0),ge.wnext=xe,ge.whave=ge.wsize):(ge.wnext+=Xe,ge.wnext===ge.wsize&&(ge.wnext=0),ge.whave>>8&255,R.check=_(R.check,ye,2,0),me=Q=0,R.mode=2;break}if(R.flags=0,R.head&&(R.head.done=!1),!(1&R.wrap)||(((255&Q)<<8)+(Q>>8))%31){te.msg="incorrect header check",R.mode=30;break}if((15&Q)!=8){te.msg="unknown compression method",R.mode=30;break}if(me-=4,A=8+(15&(Q>>>=4)),R.wbits===0)R.wbits=A;else if(A>R.wbits){te.msg="invalid window size",R.mode=30;break}R.dmax=1<>8&1),512&R.flags&&(ye[0]=255&Q,ye[1]=Q>>>8&255,R.check=_(R.check,ye,2,0)),me=Q=0,R.mode=3;case 3:for(;me<32;){if(ae===0)break e;ae--,Q+=xe[ge++]<>>8&255,ye[2]=Q>>>16&255,ye[3]=Q>>>24&255,R.check=_(R.check,ye,4,0)),me=Q=0,R.mode=4;case 4:for(;me<16;){if(ae===0)break e;ae--,Q+=xe[ge++]<>8),512&R.flags&&(ye[0]=255&Q,ye[1]=Q>>>8&255,R.check=_(R.check,ye,2,0)),me=Q=0,R.mode=5;case 5:if(1024&R.flags){for(;me<16;){if(ae===0)break e;ae--,Q+=xe[ge++]<>>8&255,R.check=_(R.check,ye,2,0)),me=Q=0}else R.head&&(R.head.extra=null);R.mode=6;case 6:if(1024&R.flags&&(ae<(Be=R.length)&&(Be=ae),Be&&(R.head&&(A=R.head.extra_len-R.length,R.head.extra||(R.head.extra=new Array(R.head.extra_len)),l.arraySet(R.head.extra,xe,ge,Be,A)),512&R.flags&&(R.check=_(R.check,xe,Be,ge)),ae-=Be,ge+=Be,R.length-=Be),R.length))break e;R.length=0,R.mode=7;case 7:if(2048&R.flags){if(ae===0)break e;for(Be=0;A=xe[ge+Be++],R.head&&A&&R.length<65536&&(R.head.name+=String.fromCharCode(A)),A&&Be>9&1,R.head.done=!0),te.adler=R.check=0,R.mode=12;break;case 10:for(;me<32;){if(ae===0)break e;ae--,Q+=xe[ge++]<>>=7&me,me-=7&me,R.mode=27;break}for(;me<3;){if(ae===0)break e;ae--,Q+=xe[ge++]<>>=1)){case 0:R.mode=14;break;case 1:if(de(R),R.mode=20,_e!==6)break;Q>>>=2,me-=2;break e;case 2:R.mode=17;break;case 3:te.msg="invalid block type",R.mode=30}Q>>>=2,me-=2;break;case 14:for(Q>>>=7&me,me-=7&me;me<32;){if(ae===0)break e;ae--,Q+=xe[ge++]<>>16^65535)){te.msg="invalid stored block lengths",R.mode=30;break}if(R.length=65535&Q,me=Q=0,R.mode=15,_e===6)break e;case 15:R.mode=16;case 16:if(Be=R.length){if(ae>>=5,me-=5,R.ndist=1+(31&Q),Q>>>=5,me-=5,R.ncode=4+(15&Q),Q>>>=4,me-=4,286>>=3,me-=3}for(;R.have<19;)R.lens[B[R.have++]]=0;if(R.lencode=R.lendyn,R.lenbits=7,Pe={bits:R.lenbits},$e=g(0,R.lens,0,19,R.lencode,0,R.work,Pe),R.lenbits=Pe.bits,$e){te.msg="invalid code lengths set",R.mode=30;break}R.have=0,R.mode=19;case 19:for(;R.have>>16&255,Me=65535&ne,!((ft=ne>>>24)<=me);){if(ae===0)break e;ae--,Q+=xe[ge++]<>>=ft,me-=ft,R.lens[R.have++]=Me;else{if(Me===16){for(se=ft+2;me>>=ft,me-=ft,R.have===0){te.msg="invalid bit length repeat",R.mode=30;break}A=R.lens[R.have-1],Be=3+(3&Q),Q>>>=2,me-=2}else if(Me===17){for(se=ft+3;me>>=ft)),Q>>>=3,me-=3}else{for(se=ft+7;me>>=ft)),Q>>>=7,me-=7}if(R.have+Be>R.nlen+R.ndist){te.msg="invalid bit length repeat",R.mode=30;break}for(;Be--;)R.lens[R.have++]=A}}if(R.mode===30)break;if(R.lens[256]===0){te.msg="invalid code -- missing end-of-block",R.mode=30;break}if(R.lenbits=9,Pe={bits:R.lenbits},$e=g(M,R.lens,0,R.nlen,R.lencode,0,R.work,Pe),R.lenbits=Pe.bits,$e){te.msg="invalid literal/lengths set",R.mode=30;break}if(R.distbits=6,R.distcode=R.distdyn,Pe={bits:R.distbits},$e=g(w,R.lens,R.nlen,R.ndist,R.distcode,0,R.work,Pe),R.distbits=Pe.bits,$e){te.msg="invalid distances set",R.mode=30;break}if(R.mode=20,_e===6)break e;case 20:R.mode=21;case 21:if(6<=ae&&258<=Se){te.next_out=X,te.avail_out=Se,te.next_in=ge,te.avail_in=ae,R.hold=Q,R.bits=me,p(te,Le),X=te.next_out,Xe=te.output,Se=te.avail_out,ge=te.next_in,xe=te.input,ae=te.avail_in,Q=R.hold,me=R.bits,R.mode===12&&(R.back=-1);break}for(R.back=0;Ge=(ne=R.lencode[Q&(1<>>16&255,Me=65535&ne,!((ft=ne>>>24)<=me);){if(ae===0)break e;ae--,Q+=xe[ge++]<>je)])>>>16&255,Me=65535&ne,!(je+(ft=ne>>>24)<=me);){if(ae===0)break e;ae--,Q+=xe[ge++]<>>=je,me-=je,R.back+=je}if(Q>>>=ft,me-=ft,R.back+=ft,R.length=Me,Ge===0){R.mode=26;break}if(32&Ge){R.back=-1,R.mode=12;break}if(64&Ge){te.msg="invalid literal/length code",R.mode=30;break}R.extra=15&Ge,R.mode=22;case 22:if(R.extra){for(se=R.extra;me>>=R.extra,me-=R.extra,R.back+=R.extra}R.was=R.length,R.mode=23;case 23:for(;Ge=(ne=R.distcode[Q&(1<>>16&255,Me=65535&ne,!((ft=ne>>>24)<=me);){if(ae===0)break e;ae--,Q+=xe[ge++]<>je)])>>>16&255,Me=65535&ne,!(je+(ft=ne>>>24)<=me);){if(ae===0)break e;ae--,Q+=xe[ge++]<>>=je,me-=je,R.back+=je}if(Q>>>=ft,me-=ft,R.back+=ft,64&Ge){te.msg="invalid distance code",R.mode=30;break}R.offset=Me,R.extra=15&Ge,R.mode=24;case 24:if(R.extra){for(se=R.extra;me>>=R.extra,me-=R.extra,R.back+=R.extra}if(R.offset>R.dmax){te.msg="invalid distance too far back",R.mode=30;break}R.mode=25;case 25:if(Se===0)break e;if(Be=Le-Se,R.offset>Be){if((Be=R.offset-Be)>R.whave&&R.sane){te.msg="invalid distance too far back",R.mode=30;break}We=Be>R.wnext?(Be-=R.wnext,R.wsize-Be):R.wnext-Be,Be>R.length&&(Be=R.length),st=R.window}else st=Xe,We=X-R.offset,Be=R.length;for(Sej?(ee=We[st+E[_e]],me[Ke+E[_e]]):(ee=96,0),b=1<>X)+(I-=b)]=D<<24|ee<<16|de|0,I!==0;);for(b=1<>=1;if(b!==0?(Q&=b-1,Q+=b):Q=0,_e++,--Le[te]==0){if(te===xe)break;te=w[C+E[_e]]}if(Xe>>7)]}function Ke(ne,ye){ne.pending_buf[ne.pending++]=255&ye,ne.pending_buf[ne.pending++]=ye>>>8&255}function Le(ne,ye,B){ne.bi_valid>y-B?(ne.bi_buf|=ye<>y-ne.bi_valid,ne.bi_valid+=B-y):(ne.bi_buf|=ye<>>=1,B<<=1,0<--ye;);return B>>>1}function st(ne,ye,B){var J,L,ue=new Array(E+1),le=0;for(J=1;J<=E;J++)ue[J]=le=le+B[J-1]<<1;for(L=0;L<=ye;L++){var Te=ne[2*L+1];Te!==0&&(ne[2*L]=We(ue[Te]++,Te))}}function ft(ne){var ye;for(ye=0;ye>1;1<=B;B--)je(ne,ue,B);for(L=Ne;B=ne.heap[1],ne.heap[1]=ne.heap[ne.heap_len--],je(ne,ue,1),J=ne.heap[1],ne.heap[--ne.heap_max]=B,ne.heap[--ne.heap_max]=J,ue[2*L]=ue[2*B]+ue[2*J],ne.depth[L]=(ne.depth[B]>=ne.depth[J]?ne.depth[B]:ne.depth[J])+1,ue[2*B+1]=ue[2*J+1]=L,ne.heap[1]=L++,je(ne,ue,1),2<=ne.heap_len;);ne.heap[--ne.heap_max]=ne.heap[1],function(Je,Ve){var Y,ve,Re,qe,Qe,tt,pt=Ve.dyn_tree,ht=Ve.max_code,Tt=Ve.stat_desc.static_tree,vt=Ve.stat_desc.has_stree,Et=Ve.stat_desc.extra_bits,Lt=Ve.stat_desc.extra_base,at=Ve.stat_desc.max_length,zt=0;for(qe=0;qe<=E;qe++)Je.bl_count[qe]=0;for(pt[2*Je.heap[Je.heap_max]+1]=0,Y=Je.heap_max+1;Y>=7;L>>=1)if(1&dt&&Te.dyn_ltree[2*Ne]!==0)return f;if(Te.dyn_ltree[18]!==0||Te.dyn_ltree[20]!==0||Te.dyn_ltree[26]!==0)return _;for(Ne=32;Ne>>3,(ue=ne.static_len+3+7>>>3)<=L&&(L=ue)):L=ue=B+5,B+4<=L&&ye!==-1?se(ne,ye,B,J):ne.strategy===4||ue===L?(Le(ne,2+(J?1:0),3),Ye(ne,Ce,te)):(Le(ne,4+(J?1:0),3),function(Te,Ne,dt,Je){var Ve;for(Le(Te,Ne-257,5),Le(Te,dt-1,5),Le(Te,Je-4,4),Ve=0;Ve>>8&255,ne.pending_buf[ne.d_buf+2*ne.last_lit+1]=255&ye,ne.pending_buf[ne.l_buf+ne.last_lit]=255&B,ne.last_lit++,ye===0?ne.dyn_ltree[2*B]++:(ne.matches++,ye--,ne.dyn_ltree[2*(R[B]+w+1)]++,ne.dyn_dtree[2*me(ye)]++),ne.last_lit===ne.lit_bufsize-1},a._tr_align=function(ne){Le(ne,2,3),Be(ne,I,Ce),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)}(ne)}},{"../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(f,_){if(!f.setImmediate){var p,g,M,w,C=1,T={},z=!1,S=f.document,E=Object.getPrototypeOf&&Object.getPrototypeOf(f);E=E&&E.setTimeout?E:f,p={}.toString.call(f.process)==="[object process]"?function(V){process.nextTick(function(){b(V)})}:function(){if(f.postMessage&&!f.importScripts){var V=!0,O=f.onmessage;return f.onmessage=function(){V=!1},f.postMessage("","*"),f.onmessage=O,V}}()?(w="setImmediate$"+Math.random()+"$",f.addEventListener?f.addEventListener("message",I,!1):f.attachEvent("onmessage",I),function(V){f.postMessage(w+V,"*")}):f.MessageChannel?((M=new MessageChannel).port1.onmessage=function(V){b(V.data)},function(V){M.port2.postMessage(V)}):S&&"onreadystatechange"in S.createElement("script")?(g=S.documentElement,function(V){var O=S.createElement("script");O.onreadystatechange=function(){b(V),O.onreadystatechange=null,g.removeChild(O),O=null},g.appendChild(O)}):function(V){setTimeout(b,0,V)},E.setImmediate=function(V){typeof V!="function"&&(V=new Function(""+V));for(var O=new Array(arguments.length-1),N=0;N"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 pE=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,w){var C=new XMLHttpRequest;C.open("GET",g),C.responseType="blob",C.onload=function(){p(C.response,M,w)},C.onerror=function(){console.error("could not download file")},C.send()}function a(g){var M=new XMLHttpRequest;M.open("HEAD",g,!1);try{M.send()}catch{}return 200<=M.status&&299>=M.status}function l(g){try{g.dispatchEvent(new MouseEvent("click"))}catch{var M=document.createEvent("MouseEvents");M.initMouseEvent("click",!0,!0,window,0,0,0,80,20,!1,!1,!1,!1,0,null),g.dispatchEvent(M)}}var f=typeof window=="object"&&window.window===window?window:typeof self=="object"&&self.self===self?self:typeof Co=="object"&&Co.global===Co?Co:void 0,_=f.navigator&&/Macintosh/.test(navigator.userAgent)&&/AppleWebKit/.test(navigator.userAgent)&&!/Safari/.test(navigator.userAgent),p=f.saveAs||(typeof window!="object"||window!==f?function(){}:"download"in HTMLAnchorElement.prototype&&!_?function(g,M,w){var C=f.URL||f.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,w):l(T,T.target="_blank")):(T.href=C.createObjectURL(g),setTimeout(function(){C.revokeObjectURL(T.href)},4e4),setTimeout(function(){l(T)},0))}:"msSaveOrOpenBlob"in navigator?function(g,M,w){if(M=M||g.name||"download",typeof g!="string")navigator.msSaveOrOpenBlob(r(g,w),M);else if(a(g))o(g,M,w);else{var C=document.createElement("a");C.href=g,C.target="_blank",setTimeout(function(){l(C)})}}:function(g,M,w,C){if(C=C||open("","_blank"),C&&(C.document.title=C.document.body.innerText="downloading..."),typeof g=="string")return o(g,M,w);var T=g.type==="application/octet-stream",z=/constructor/i.test(f.HTMLElement)||f.safari,S=/CriOS\/[\d]+/.test(navigator.userAgent);if((S||T&&z||_)&&typeof FileReader<"u"){var E=new FileReader;E.onloadend=function(){var I=E.result;I=S?I:I.replace(/^data:[^;]*;/,"data:attachment/file;"),C?C.location.href=I:location=I,C=null},E.readAsDataURL(g)}else{var y=f.URL||f.webkitURL,b=y.createObjectURL(g);C?C.location=b:location.href=b,C=null,setTimeout(function(){y.revokeObjectURL(b)},4e4)}});f.saveAs=p.saveAs=p,e.exports=p})})(rx);var hE=rx.exports;function mE(){const[e,t]=pr.useState([]),[r,o]=pr.useState([]),[a,l]=pr.useState(!1),[f,_]=pr.useState(!1),[p,g]=pr.useState(!0),M=pr.useRef(null),w=pr.useRef(null);pr.useEffect(()=>{(async()=>{const D="Xenova/modnet";M.current??(M.current=await cE.from_pretrained(D,{device:"webgpu"})),w.current??(w.current=await dE.from_pretrained(D)),g(!1)})()},[]);const C=pr.useCallback(D=>{t(ee=>[...ee,...D.map(de=>URL.createObjectURL(de))])},[]),{getRootProps:T,getInputProps:z,isDragActive:S,isDragAccept:E,isDragReject:y}=Y2({onDrop:C,accept:{"image/*":[".jpeg",".jpg",".png"]}}),b=D=>{t(ee=>ee.filter((de,Ce)=>Ce!==D)),o(ee=>ee.filter((de,Ce)=>Ce!==D))},I=async()=>{l(!0),o([]);const D=M.current,ee=w.current;for(let de=0;de[...X,xe.toDataURL("image/png")])}l(!1),_(!0)},V=async()=>{const D=new pE;for(let de=0;de{_e.onload=()=>{Ce.width=_e.width,Ce.height=_e.height,te.drawImage(_e,0,0),Ce.toBlob(xe=>{xe&&D.file(`image${de+1}.png`,xe),R(null)},"image/png")}})}const ee=await D.generateAsync({type:"blob"});hE.saveAs(ee,"images.zip")},O=()=>{t([]),o([]),_(!1)},N=D=>{navigator.clipboard.writeText(D).then(()=>{console.log("Image URL copied to clipboard")})},j=D=>{const ee=document.createElement("a");ee.href=D,ee.download="image.png",document.body.appendChild(ee),ee.click(),document.body.removeChild(ee)};return p?qr.jsx("div",{className:"min-h-screen bg-black text-white flex items-center justify-center",children:qr.jsxs("div",{className:"text-center",children:[qr.jsx("div",{className:"inline-block animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-white mb-4"}),qr.jsx("p",{className:"text-lg",children:"Loading background removal model..."})]})}):qr.jsx("div",{className:"min-h-screen bg-black text-white p-8",children:qr.jsxs("div",{className:"max-w-4xl mx-auto",children:[qr.jsx("h1",{className:"text-4xl font-bold mb-2 text-center",children:"Remove Background WebGPU"}),qr.jsxs("h2",{className:"text-lg font-semibold mb-8 text-center",children:["In-browser background removal, powered by"," ",qr.jsx("a",{className:"underline",target:"_blank",href:"https://github.com/xenova/transformers.js",children:"🤗 Transformers.js"})]}),qr.jsxs("div",{...T(),className:`p-8 mb-8 border-2 border-dashed rounded-lg text-center cursor-pointer transition-colors duration-300 ease-in-out + ${E?"border-green-500 bg-green-900/20":""} + ${y?"border-red-500 bg-red-900/20":""} + ${S?"border-blue-500 bg-blue-900/20":"border-gray-700 hover:border-blue-500 hover:bg-blue-900/10"} + `,children:[qr.jsx("input",{...z(),className:"hidden"}),qr.jsx("p",{className:"text-lg mb-2",children:S?"Drop the images here...":"Drag and drop some images here"}),qr.jsx("p",{className:"text-sm text-gray-400",children:"or click to select files"})]}),qr.jsxs("div",{className:"flex flex-col items-center gap-4 mb-8",children:[qr.jsx("button",{onClick:I,disabled:a||e.length===0,className:"px-6 py-3 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 focus:ring-offset-black disabled:bg-gray-700 disabled:cursor-not-allowed transition-colors duration-200 text-lg font-semibold",children:a?"Processing...":"Process"}),qr.jsxs("div",{className:"flex gap-4",children:[qr.jsx("button",{onClick:V,disabled:!f,className:"px-3 py-1 bg-green-600 text-white rounded-md hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-green-500 focus:ring-offset-2 focus:ring-offset-black disabled:bg-gray-700 disabled:cursor-not-allowed transition-colors duration-200 text-sm",children:"Download as ZIP"}),qr.jsx("button",{onClick:O,className:"px-3 py-1 bg-red-600 text-white rounded-md hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-offset-2 focus:ring-offset-black transition-colors duration-200 text-sm",children:"Clear All"})]})]}),qr.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6",children:e.map((D,ee)=>qr.jsxs("div",{className:"relative group",children:[qr.jsx("img",{src:r[ee]||D,alt:`Image ${ee+1}`,className:"rounded-lg object-cover w-full h-48"}),qr.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:[qr.jsx("button",{onClick:()=>N(r[ee]||D),className:"mx-2 px-3 py-1 bg-white text-gray-900 rounded-md hover:bg-gray-200 transition-colors duration-200 text-sm","aria-label":`Copy image ${ee+1} URL to clipboard`,children:"Copy URL"}),qr.jsx("button",{onClick:()=>j(r[ee]||D),className:"mx-2 px-3 py-1 bg-white text-gray-900 rounded-md hover:bg-gray-200 transition-colors duration-200 text-sm","aria-label":`Download image ${ee+1}`,children:"Download"})]}),qr.jsx("button",{onClick:()=>b(ee),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 ${ee+1}`,children:"✕"})]},ee))})]})})}L2(document.getElementById("root")).render(qr.jsx(pr.StrictMode,{children:qr.jsx(mE,{})}));